@markus-global/cli 0.11.1 → 0.11.2

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 +1447 -695
  5. package/dist/web-ui/assets/{CommentInput-PDh2FT6S.js → CommentInput-Cgu8208h.js} +1 -1
  6. package/dist/web-ui/assets/{ContentRenderer-HvsvN5z8.js → ContentRenderer-rzRUDj8T.js} +2 -2
  7. package/dist/web-ui/assets/{DeliverableShareModal-7skvb6AH.js → DeliverableShareModal-BvfmqTNG.js} +1 -1
  8. package/dist/web-ui/assets/{Deliverables-vaxjOmgk.js → Deliverables-DKTLnaF8.js} +1 -1
  9. package/dist/web-ui/assets/{Notifications-BSYS-Xqp.js → Notifications-CWaO9onn.js} +1 -1
  10. package/dist/web-ui/assets/{Search-DMTKdv_5.js → Search-D_C5Eyed.js} +1 -1
  11. package/dist/web-ui/assets/Settings-B5Ib6SFf.js +8 -0
  12. package/dist/web-ui/assets/{Store-C2Gp54yd.js → Store-D__pfqoc.js} +1 -1
  13. package/dist/web-ui/assets/Team-FFbGLcXj.js +84 -0
  14. package/dist/web-ui/assets/{Work-D2V9dc4t.js → Work-BJ7kXixx.js} +1 -1
  15. package/dist/web-ui/assets/{arc-DXI9jypb.js → arc-BN0GMYN6.js} +1 -1
  16. package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-D0dgsLxO.js → architectureDiagram-3BPJPVTR-BP5Nnl2Y.js} +1 -1
  17. package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-D3jOMfnK.js → blockDiagram-GPEHLZMM-nKHUCU_z.js} +1 -1
  18. package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-Q2Ldw3Sv.js → c4Diagram-AAUBKEIU-DoS0wcHh.js} +1 -1
  19. package/dist/web-ui/assets/channel-C_kHFvaW.js +1 -0
  20. package/dist/web-ui/assets/{chunk-2J33WTMH-DB_uyGmL.js → chunk-2J33WTMH-CP54_XNl.js} +1 -1
  21. package/dist/web-ui/assets/{chunk-4BX2VUAB-Y9c_3cDt.js → chunk-4BX2VUAB-DMvJaJb7.js} +1 -1
  22. package/dist/web-ui/assets/{chunk-55IACEB6-xRXDDqG3.js → chunk-55IACEB6-DQnZgoOO.js} +1 -1
  23. package/dist/web-ui/assets/{chunk-727SXJPM-CwY1lVes.js → chunk-727SXJPM-B5_3LI53.js} +1 -1
  24. package/dist/web-ui/assets/{chunk-AQP2D5EJ-fIC-6Whq.js → chunk-AQP2D5EJ-B5Mh5bI_.js} +1 -1
  25. package/dist/web-ui/assets/{chunk-FMBD7UC4-IlZKWtdL.js → chunk-FMBD7UC4-mjYTpuBm.js} +1 -1
  26. package/dist/web-ui/assets/{chunk-ND2GUHAM-a3CXI6Kb.js → chunk-ND2GUHAM-BxTrseJg.js} +1 -1
  27. package/dist/web-ui/assets/{chunk-QZHKN3VN-Cnn8UAUY.js → chunk-QZHKN3VN-C1do5brE.js} +1 -1
  28. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-UF2PuXCi.js +1 -0
  29. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-UF2PuXCi.js +1 -0
  30. package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-BJPva2zo.js → cose-bilkent-S5V4N54A-DMn7aSDK.js} +1 -1
  31. package/dist/web-ui/assets/{dagre-BM42HDAG-CEFKUAeR.js → dagre-BM42HDAG-CE-tTagY.js} +1 -1
  32. package/dist/web-ui/assets/{diagram-2AECGRRQ-CJ_RLW56.js → diagram-2AECGRRQ-BwyvxbJa.js} +1 -1
  33. package/dist/web-ui/assets/{diagram-5GNKFQAL-7_jNRwT_.js → diagram-5GNKFQAL-Nopndxl0.js} +1 -1
  34. package/dist/web-ui/assets/{diagram-KO2AKTUF-CfwfuTpe.js → diagram-KO2AKTUF-CGTjHHnD.js} +1 -1
  35. package/dist/web-ui/assets/{diagram-LMA3HP47-CgA0Xoif.js → diagram-LMA3HP47-DhC3AqLA.js} +1 -1
  36. package/dist/web-ui/assets/{diagram-OG6HWLK6-C4hKO_tx.js → diagram-OG6HWLK6-BIuzyWJO.js} +1 -1
  37. package/dist/web-ui/assets/{docx-preview-C6dfKcRb.js → docx-preview-ClO_djcO.js} +1 -1
  38. package/dist/web-ui/assets/{erDiagram-TEJ5UH35-YKBDWeXd.js → erDiagram-TEJ5UH35-Nmfi9Wv0.js} +1 -1
  39. package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-jQOEkqH3.js → flowDiagram-I6XJVG4X-BVAM5QzO.js} +1 -1
  40. package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-CKAc4LGG.js → ganttDiagram-6RSMTGT7-BGdTbY0A.js} +1 -1
  41. package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-DIytf2iV.js → gitGraphDiagram-PVQCEYII-BMfug5mp.js} +1 -1
  42. package/dist/web-ui/assets/{index-DQZuBgCk.js → index-1X1Ykov8.js} +73 -73
  43. package/dist/web-ui/assets/index-3PQIqBtv.css +1 -0
  44. package/dist/web-ui/assets/{infoDiagram-5YYISTIA-BLLcTqQ8.js → infoDiagram-5YYISTIA-DAqSLNMU.js} +1 -1
  45. package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-ZS_AZA3m.js → ishikawaDiagram-YF4QCWOH-Bro4RrlG.js} +1 -1
  46. package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-Ctoivwi3.js → journeyDiagram-JHISSGLW-CdRHOaID.js} +1 -1
  47. package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-CfcPO__T.js → kanban-definition-UN3LZRKU-9iLNl-rB.js} +1 -1
  48. package/dist/web-ui/assets/{mermaid.core-DzupXsSn.js → mermaid.core-BRHCbDDt.js} +5 -5
  49. package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BkhUn8LW.js → mindmap-definition-RKZ34NQL-BLm-XQ6W.js} +1 -1
  50. package/dist/web-ui/assets/{pieDiagram-4H26LBE5-nF1mw9W9.js → pieDiagram-4H26LBE5-ith90T5A.js} +1 -1
  51. package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-BB6ocoXG.js → quadrantDiagram-W4KKPZXB-Cb08oHG7.js} +1 -1
  52. package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-CVQoAqkp.js → requirementDiagram-4Y6WPE33-DzMKi4w8.js} +1 -1
  53. package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-BrhNGTIx.js → sankeyDiagram-5OEKKPKP-C0Wv4A7m.js} +1 -1
  54. package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-DmOCmx0n.js → sequenceDiagram-3UESZ5HK-C_HL9WB0.js} +1 -1
  55. package/dist/web-ui/assets/{stateDiagram-AJRCARHV-ChJl2DyB.js → stateDiagram-AJRCARHV-BFfTVEYQ.js} +1 -1
  56. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-DuO1A2q2.js +1 -0
  57. package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-DhxcmpUp.js → timeline-definition-PNZ67QCA-cyPnAADn.js} +1 -1
  58. package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-D6GtjxcJ.js → vennDiagram-CIIHVFJN-Cb82-9OZ.js} +1 -1
  59. package/dist/web-ui/assets/{wardley-L42UT6IY-CUDg0-0c.js → wardley-L42UT6IY-BTW1NXXR.js} +1 -1
  60. package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-CV97tBgz.js → wardleyDiagram-YWT4CUSO-C_F_dT6n.js} +1 -1
  61. package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-DCVmw2nR.js → xychartDiagram-2RQKCTM6-clcfplhG.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-ooEzVvXw.js +0 -8
  65. package/dist/web-ui/assets/Team-BVuNOPeb.js +0 -84
  66. package/dist/web-ui/assets/channel-C8ilVfxi.js +0 -1
  67. package/dist/web-ui/assets/classDiagram-4FO5ZUOK-BmfrDuwr.js +0 -1
  68. package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-BmfrDuwr.js +0 -1
  69. package/dist/web-ui/assets/index-DxPx73Ja.css +0 -1
  70. package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-B-Lfl2Dh.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, END_TURN_REPLY_SENTINEL, 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,12 +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
5462
  END_TURN_REPLY_SENTINEL = "[end_turn]";
5466
- COMPLETION_MARKER_INSTRUCTION = `
5467
-
5468
- [IMPORTANT: When you have finished processing this request, you MUST end your final response with the exact token: ${COMPLETION_MARKER}]`;
5469
- COMPLETION_MARKER_LEAK_RE = /<{1,2}\s*HANDLE_COMPLETE\s*>{1,2}/gi;
5463
+ LEGACY_COMPLETION_TOKEN_RE = /<{1,2}\s*HANDLE_COMPLETE\s*>{1,2}/gi;
5470
5464
  TASK_MAX_NO_SUBMIT_RETRIES = 8;
5471
5465
  TASK_RETRY_DELAYS_MS = [3e4, 6e4, 12e4, 24e4, 48e4, 6e5];
5472
5466
  PREEMPT_REQUEUE_DELAY_MS = 3e3;
@@ -5474,8 +5468,15 @@ var init_limits = __esm({
5474
5468
  SYSTEM_SOPS_CHARS = 3e3;
5475
5469
  SYSTEM_LONGTERM_MEMORY_CHARS = 5e3;
5476
5470
  MEMORY_MD_SECTION_MAX_CHARS = 3e3;
5477
- 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;
5478
5477
  MEMORY_OBSERVATIONS_MAX_CHARS = 3e4;
5478
+ MEMORY_OBSERVATIONS_HARD_MAX_CHARS = 2e5;
5479
+ MEMORY_FRAGMENTS_MAX_CHARS = 6e4;
5479
5480
  KNOWLEDGE_SECTION_KEY_MAX_CHARS = 64;
5480
5481
  KNOWLEDGE_STUB_MAX_CHARS = 400;
5481
5482
  MEMORY_ENTRY_MAX_CHARS = 4e3;
@@ -5753,8 +5754,6 @@ __export(dist_exports, {
5753
5754
  CLI_EXIT_CODES: () => CLI_EXIT_CODES,
5754
5755
  COLD_CONVERSE_FIXED_MAX: () => COLD_CONVERSE_FIXED_MAX,
5755
5756
  COLD_REFLEX_FIXED_MAX: () => COLD_REFLEX_FIXED_MAX,
5756
- COMPLETION_MARKER: () => COMPLETION_MARKER,
5757
- COMPLETION_MARKER_INSTRUCTION: () => COMPLETION_MARKER_INSTRUCTION,
5758
5757
  CONTEXT_ABSURD_MESSAGE_CHARS: () => CONTEXT_ABSURD_MESSAGE_CHARS,
5759
5758
  CONTEXT_ABS_HISTORY_TARGET_TOKENS: () => CONTEXT_ABS_HISTORY_TARGET_TOKENS,
5760
5759
  CONTEXT_ABS_HISTORY_TOKENS: () => CONTEXT_ABS_HISTORY_TOKENS,
@@ -5763,7 +5762,6 @@ __export(dist_exports, {
5763
5762
  CONTEXT_SLOT_MAX_CHARS: () => CONTEXT_SLOT_MAX_CHARS,
5764
5763
  CONTEXT_VOLATILE_REARM_CALLS: () => CONTEXT_VOLATILE_REARM_CALLS,
5765
5764
  CONTEXT_WARN_RATIO: () => CONTEXT_WARN_RATIO,
5766
- CognitiveDepth: () => CognitiveDepth,
5767
5765
  DEEP_SLEEP_IDLE_HEARTBEATS: () => DEEP_SLEEP_IDLE_HEARTBEATS,
5768
5766
  DEFAULT_HEARTBEAT_INTERVAL_MS: () => DEFAULT_HEARTBEAT_INTERVAL_MS,
5769
5767
  DEFERRED_CATALOG_MAX_CHARS: () => DEFERRED_CATALOG_MAX_CHARS,
@@ -5797,9 +5795,16 @@ __export(dist_exports, {
5797
5795
  MAX_TOKENS_AFFORD_SAFETY: () => MAX_TOKENS_AFFORD_SAFETY,
5798
5796
  MAX_TOKENS_CLAMP_FLOOR: () => MAX_TOKENS_CLAMP_FLOOR,
5799
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,
5800
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,
5801
5806
  MEMORY_MD_SECTION_MAX_CHARS: () => MEMORY_MD_SECTION_MAX_CHARS,
5802
- MEMORY_MD_TOTAL_MAX_CHARS: () => MEMORY_MD_TOTAL_MAX_CHARS,
5807
+ MEMORY_OBSERVATIONS_HARD_MAX_CHARS: () => MEMORY_OBSERVATIONS_HARD_MAX_CHARS,
5803
5808
  MEMORY_OBSERVATIONS_MAX_CHARS: () => MEMORY_OBSERVATIONS_MAX_CHARS,
5804
5809
  MIN_HEARTBEAT_INTERVAL_MS: () => MIN_HEARTBEAT_INTERVAL_MS,
5805
5810
  MODEL_CAPABILITY_TYPES: () => MODEL_CAPABILITY_TYPES,
@@ -5951,7 +5956,6 @@ __export(dist_exports, {
5951
5956
  getProviderBootstrapModel: () => getProviderBootstrapModel,
5952
5957
  getRunStatePath: () => getRunStatePath,
5953
5958
  getTextContent: () => getTextContent,
5954
- hasCompletionMarker: () => hasCompletionMarker,
5955
5959
  inspectSubscriptionKey: () => inspectSubscriptionKey,
5956
5960
  installCrashGuard: () => installCrashGuard,
5957
5961
  isCliErrorResponse: () => isCliErrorResponse,
@@ -5985,6 +5989,8 @@ __export(dist_exports, {
5985
5989
  readManifest: () => readManifest,
5986
5990
  readRunState: () => readRunState,
5987
5991
  renderStepPrompt: () => renderStepPrompt,
5992
+ replaceAllLiteral: () => replaceAllLiteral,
5993
+ replaceLiteral: () => replaceLiteral,
5988
5994
  requirementId: () => requirementId,
5989
5995
  resolveBinary: () => resolveBinary,
5990
5996
  resolveEntityKey: () => resolveEntityKey,
@@ -5997,8 +6003,8 @@ __export(dist_exports, {
5997
6003
  saveConfig: () => saveConfig,
5998
6004
  scoreKeywordHaystack: () => scoreKeywordHaystack,
5999
6005
  scoreKeywordQuery: () => scoreKeywordQuery,
6000
- stripCompletionMarkerLeak: () => stripCompletionMarkerLeak,
6001
6006
  stripInternalBlocks: () => stripInternalBlocks,
6007
+ stripLegacyCompletionToken: () => stripLegacyCompletionToken,
6002
6008
  summarizeEnv: () => summarizeEnv,
6003
6009
  taskId: () => taskId,
6004
6010
  toPackageSlug: () => toPackageSlug,
@@ -6029,7 +6035,6 @@ var init_dist = __esm({
6029
6035
  init_file_storage();
6030
6036
  init_mailbox();
6031
6037
  init_workflow_template();
6032
- init_cognitive();
6033
6038
  init_model_catalog();
6034
6039
  init_license();
6035
6040
  init_coding_tool();
@@ -6040,6 +6045,7 @@ var init_dist = __esm({
6040
6045
  init_crash();
6041
6046
  init_id();
6042
6047
  init_text();
6048
+ init_literal_replace();
6043
6049
  init_platform();
6044
6050
  init_keyword_search();
6045
6051
  init_models();
@@ -6361,6 +6367,17 @@ var init_lock_resources = __esm({
6361
6367
  }
6362
6368
  });
6363
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
+
6364
6381
  // ../core/dist/tracing.js
6365
6382
  function setTracingProvider(provider) {
6366
6383
  activeProvider = provider;
@@ -7890,6 +7907,91 @@ var init_taxonomy = __esm({
7890
7907
  }
7891
7908
  });
7892
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
+
7893
7995
  // ../core/dist/atomic-write.js
7894
7996
  import { renameSync, writeFileSync as writeFileSync5 } from "node:fs";
7895
7997
  function writeFileAtomic(filePath, content) {
@@ -7930,11 +8032,70 @@ var init_context_slot = __esm({
7930
8032
  }
7931
8033
  });
7932
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
+
7933
8085
  // ../core/dist/memory/store.js
7934
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";
7935
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
+ }
7936
8094
  function sanitizeSectionBody(content) {
7937
- 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, "");
7938
8099
  }
7939
8100
  function normalizeSectionKey(raw) {
7940
8101
  const flat = String(raw ?? "").replace(/[\r\n]+/g, " ").trim();
@@ -7967,14 +8128,6 @@ function sanitizeEntry(raw) {
7967
8128
  metadata: typeof r.metadata === "object" && r.metadata !== null ? r.metadata : void 0
7968
8129
  };
7969
8130
  }
7970
- function safeJson(value) {
7971
- try {
7972
- const s2 = JSON.stringify(value);
7973
- return typeof s2 === "string" ? s2 : "";
7974
- } catch {
7975
- return "";
7976
- }
7977
- }
7978
8131
  function parseDataMeta(raw) {
7979
8132
  if (!raw)
7980
8133
  return void 0;
@@ -8114,6 +8267,24 @@ function formatTags(metadata) {
8114
8267
  const tags = metadata?.tags;
8115
8268
  return Array.isArray(tags) ? tags.map(String).join(" ") : "";
8116
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
+ }
8117
8288
  function parseCuratedSections(markdown) {
8118
8289
  if (!markdown.trim())
8119
8290
  return [];
@@ -8138,16 +8309,30 @@ function parseCuratedSections(markdown) {
8138
8309
  function slugSectionId(name) {
8139
8310
  return name.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/gi, "_").replace(/^_|_$/g, "").slice(0, 80) || "section";
8140
8311
  }
8141
- 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;
8142
8313
  var init_store = __esm({
8143
8314
  "../core/dist/memory/store.js"() {
8144
8315
  "use strict";
8145
8316
  init_dist();
8146
8317
  init_taxonomy();
8318
+ init_residue_repair();
8147
8319
  init_atomic_write();
8148
8320
  init_context_slot();
8321
+ init_records();
8149
8322
  log8 = createLogger("memory-store");
8150
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
+ ]);
8151
8336
  NOTEBOOK_HEADING_RE = /^## (.+)$/;
8152
8337
  NOTEBOOK_UPDATED_RE = /^<!-- updated: (.+) -->$/;
8153
8338
  NOTEBOOK_MANAGED_RE = /^<!-- managed: (\w+) -->$/;
@@ -8164,6 +8349,21 @@ var init_store = __esm({
8164
8349
  saveDebounce = /* @__PURE__ */ new Map();
8165
8350
  longTermFile;
8166
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;
8167
8367
  constructor(dataDir) {
8168
8368
  this.dataDir = dataDir;
8169
8369
  this.sessionsDir = join7(dataDir, "sessions");
@@ -8173,38 +8373,116 @@ var init_store = __esm({
8173
8373
  mkdirSync6(this.logsDir, { recursive: true });
8174
8374
  ensureKnowledgeFile(dataDir);
8175
8375
  this.longTermFile = knowledgePath(dataDir);
8176
- 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");
8177
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
+ }
8178
8392
  this.loadSessionsFromDisk();
8179
8393
  }
8180
8394
  getStoreFileName() {
8181
8395
  return basename2(this.longTermFile);
8182
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
+ }
8183
8406
  /** 归档文件名:超预算段落正文的**无损**去处(可被 memory_search 检索,不注入)。 */
8184
8407
  getArchiveFileName() {
8185
8408
  return basename2(this.longTermArchiveFile);
8186
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
+ }
8187
8458
  /**
8188
8459
  * 记忆预算健康度(审计 P-12):驱动提示词内的健康信号,让 Agent 知道何时该整理。
8189
8460
  */
8190
8461
  getMemoryHealth() {
8191
- let totalChars = 0;
8462
+ let content = "";
8192
8463
  try {
8193
8464
  if (existsSync8(this.longTermFile))
8194
- totalChars = readFileSync6(this.longTermFile, "utf-8").length;
8465
+ content = readFileSync6(this.longTermFile, "utf-8");
8195
8466
  } catch {
8196
8467
  }
8197
8468
  let archiveChars = 0;
8198
- try {
8199
- if (existsSync8(this.longTermArchiveFile))
8200
- archiveChars = readFileSync6(this.longTermArchiveFile, "utf-8").length;
8201
- } 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
+ }
8202
8475
  }
8203
- const cap = MEMORY_MD_TOTAL_MAX_CHARS;
8476
+ const { curated } = splitKnowledgeSections(content);
8477
+ const curatedChars = curated.length;
8478
+ const observationChars = this.observationPayloadChars();
8204
8479
  return {
8205
- totalChars,
8206
- cap,
8207
- 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,
8208
8486
  observations: this.entries.length,
8209
8487
  curatedSections: parseCuratedSections(this.getLongTermMemory()).length,
8210
8488
  archiveChars,
@@ -8242,28 +8520,104 @@ var init_store = __esm({
8242
8520
  }
8243
8521
  }
8244
8522
  /**
8245
- * Losslessly move a curated section body into `knowledge-archive.md`
8523
+ * Losslessly move a curated section body into `knowledge-archive.json`
8246
8524
  * (审计 P-04/P-05:绝不静默丢弃 / 截断)。
8247
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.
8248
8530
  */
8249
8531
  archiveSection(name, body) {
8250
8532
  const trimmed = body.trim();
8251
8533
  if (!trimmed)
8252
8534
  return 0;
8253
8535
  try {
8254
- 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";
8255
- const existing = existsSync8(this.longTermArchiveFile) ? readFileSync6(this.longTermArchiveFile, "utf-8") : head;
8256
- if (!existing.includes(trimmed)) {
8257
- appendFileSync2(this.longTermArchiveFile, `## ${name}
8258
- ${trimmed}
8259
-
8260
- `);
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));
8261
8550
  }
8262
8551
  } catch (err) {
8263
- log8.warn("Failed to archive section body", { name, error: String(err) });
8552
+ log8.warn("Failed to archive section record", { name, error: String(err) });
8264
8553
  }
8265
8554
  return trimmed.length;
8266
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
+ }
8267
8621
  /**
8268
8622
  * NOTE (2026-09-16): `getStateMemory()` / `pruneStateMemory()` were removed together
8269
8623
  * with the state.md store. Situational state is Working-layer data and lives in
@@ -8273,16 +8627,38 @@ ${trimmed}
8273
8627
  */
8274
8628
  // --- Short-term: session messages ---
8275
8629
  addEntry(entry) {
8276
- 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);
8277
8647
  this.saveToDisk();
8278
8648
  log8.debug("Memory entry added", { type: entry.type, id: entry.id });
8649
+ return { ok: true };
8279
8650
  }
8280
8651
  getEntries(type, limit) {
8281
- 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];
8282
8654
  if (limit)
8283
8655
  result = result.slice(-limit);
8284
8656
  return result;
8285
8657
  }
8658
+ /** All session-compaction fragments currently held (most recent last). */
8659
+ getFragments() {
8660
+ return [...this.fragments];
8661
+ }
8286
8662
  getEntriesByTag(tag, limit) {
8287
8663
  const tagged = this.entries.filter((e) => Array.isArray(e.metadata?.tags) && e.metadata.tags.includes(tag));
8288
8664
  return limit ? tagged.slice(-limit) : tagged;
@@ -8320,24 +8696,33 @@ ${section3.body}`;
8320
8696
  });
8321
8697
  }
8322
8698
  try {
8323
- if (existsSync8(this.longTermArchiveFile)) {
8324
- const archivedText = readFileSync6(this.longTermArchiveFile, "utf-8");
8325
- for (const section3 of parseCuratedSections(archivedText)) {
8326
- const body = `## ${section3.name}
8327
- ${section3.body}`;
8328
- const score = scoreKeywordHaystack(body, tokens, fullLower);
8329
- if (score <= 0)
8330
- continue;
8331
- scored.push({
8332
- entry: {
8333
- id: `archived_${slugSectionId(section3.name)}`,
8334
- timestamp: "",
8335
- type: "fact",
8336
- content: body.length > 2500 ? `${body.slice(0, 2500)}\u2026` : body,
8337
- metadata: { source: "archive", section: section3.name, store: this.getArchiveFileName() }
8338
- },
8339
- score: score + 0.1
8340
- });
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 });
8341
8726
  }
8342
8727
  }
8343
8728
  } catch {
@@ -8538,8 +8923,9 @@ ${content}`);
8538
8923
  *
8539
8924
  * Returns a structured result so callers (the memory tools) can surface a refusal
8540
8925
  * to the model instead of the write silently no-op'ing (B1). `{ ok: true }` on success;
8541
- * `{ ok: false, reason }` when the write is refused (over the total cap even after
8542
- * 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.
8543
8929
  */
8544
8930
  addLongTermMemory(rawKey, content) {
8545
8931
  const sectionKey = normalizeSectionKey(rawKey);
@@ -8566,7 +8952,7 @@ ${content}`);
8566
8952
  let updated;
8567
8953
  if (existing.includes(sectionHeader)) {
8568
8954
  const regex = new RegExp(`(## ${key2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})\\n[\\s\\S]*?(?=\\n## |$)`);
8569
- updated = existing.replace(regex, `${sectionHeader}
8955
+ updated = existing.replace(regex, () => `${sectionHeader}
8570
8956
  ${truncatedContent}
8571
8957
  `);
8572
8958
  } else {
@@ -8583,17 +8969,24 @@ ${truncatedContent}
8583
8969
  `;
8584
8970
  }
8585
8971
  }
8586
- writeFileAtomic(this.longTermFile, updated);
8587
- if (updated.length > MEMORY_MD_TOTAL_MAX_CHARS) {
8588
- const rebalanced = this.compressLongTermMemory();
8589
- 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", {
8590
8982
  key: key2,
8591
- totalChars: updated.length,
8592
- charsAfter: rebalanced.charsAfter,
8593
- archived: rebalanced.truncatedChunks
8983
+ curatedChars,
8984
+ softCap: MEMORY_MD_CURATED_MAX_CHARS,
8985
+ hardCap: MEMORY_MD_CURATED_HARD_MAX_CHARS,
8986
+ store: this.getStoreFileName()
8594
8987
  });
8595
8988
  }
8596
- 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() });
8597
8990
  return { ok: true };
8598
8991
  } catch (err) {
8599
8992
  log8.warn("Failed to write long-term memory", { key: key2, error: String(err) });
@@ -8664,7 +9057,7 @@ ${truncatedContent}
8664
9057
  const obsIdx = content.indexOf("## _observations");
8665
9058
  const obsPart = obsIdx >= 0 ? content.slice(obsIdx).trimStart() : "";
8666
9059
  const updated = (curatedAfter.trimEnd() + (obsPart ? "\n\n" + obsPart : "")).trimEnd() + "\n";
8667
- writeFileAtomic(this.longTermFile, updated);
9060
+ this.writeKnowledgeMd(updated);
8668
9061
  log8.info("Curated section removed", {
8669
9062
  name,
8670
9063
  removedChars: curatedBefore.length - curatedAfter.length,
@@ -8874,7 +9267,7 @@ ${truncatedContent}
8874
9267
  /** Search archived conversation_fragment entries for this session. */
8875
9268
  retrieveFragments(query2, maxResults = 5) {
8876
9269
  const q = query2.trim().toLowerCase();
8877
- const hits = this.entries.filter((e) => e.type === "conversation_fragment");
9270
+ const hits = [...this.fragments, ...this.archivedFragmentEntries()].filter((e) => e.type === "conversation_fragment");
8878
9271
  const scored = hits.map((e) => {
8879
9272
  const hay = e.content.toLowerCase();
8880
9273
  let score = 0;
@@ -8892,7 +9285,7 @@ ${truncatedContent}
8892
9285
  }
8893
9286
  /** Re-inject one archived fragment back into the live session as a user message. */
8894
9287
  includeFragment(sessionId, fragmentId) {
8895
- 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");
8896
9289
  if (!entry) {
8897
9290
  return { ok: false, message: `No archived fragment with id ${fragmentId}.` };
8898
9291
  }
@@ -8914,17 +9307,17 @@ ${entry.content}
8914
9307
  }
8915
9308
  /** Purge archived fragments for a session (used by session_purge). */
8916
9309
  purgeSessionFragments(sessionId) {
8917
- const before2 = this.entries.length;
8918
- this.entries = this.entries.filter((e) => !(e.type === "conversation_fragment" && e.metadata?.sessionId === sessionId));
8919
- 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;
8920
9313
  if (removed > 0)
8921
- this.saveToDisk();
9314
+ this.saveFragmentsToDisk();
8922
9315
  return removed;
8923
9316
  }
8924
9317
  /** Lightweight session stats for session_status. */
8925
9318
  sessionStats(sessionId) {
8926
9319
  const session = this.sessions.get(sessionId);
8927
- 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;
8928
9321
  return {
8929
9322
  messageCount: session?.messages.length ?? 0,
8930
9323
  slotKeys: Object.keys(session?.slots ?? {}),
@@ -9008,7 +9401,32 @@ ${entry.content}
9008
9401
  log8.warn("Failed to migrate memories.json, starting fresh");
9009
9402
  }
9010
9403
  }
9011
- 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");
9012
9430
  const before2 = this.entries.length;
9013
9431
  this.entries = this.entries.filter((e) => e.content.trim().length > 0);
9014
9432
  if (this.entries.length < before2) {
@@ -9016,6 +9434,8 @@ ${entry.content}
9016
9434
  removed: before2 - this.entries.length,
9017
9435
  store: this.getStoreFileName()
9018
9436
  });
9437
+ }
9438
+ if (hadLegacyRegion) {
9019
9439
  this.saveToDisk();
9020
9440
  }
9021
9441
  const migrationChanged = this.runLegacyMigrations();
@@ -9039,36 +9459,316 @@ ${entry.content}
9039
9459
  if (this.entries.length > 0) {
9040
9460
  log8.info(`Loaded ${this.entries.length} observation entries from ${this.getStoreFileName()}`);
9041
9461
  }
9042
- this.convergeLongTermToCap();
9462
+ this.enforceMemoryBudgets();
9043
9463
  }
9044
9464
  /**
9045
- * 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`):
9470
+ *
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.
9046
9479
  *
9047
- * Idempotent and cheap when already within budget (one `statSync`). Delegates to
9048
- * `compressLongTermMemory` so the per-section cap, the stub marker and the
9049
- * `## _observations` carve-out all follow one implementation.
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).
9050
9484
  */
9051
- convergeLongTermToCap() {
9052
- if (!existsSync8(this.longTermFile)) {
9053
- 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++;
9054
9599
  }
9055
- let chars = 0;
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) {
9056
9612
  try {
9057
- chars = readFileSync6(this.longTermFile, "utf-8").length;
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");
9058
9627
  } catch {
9059
- return { converged: false, charsBefore: 0, charsAfter: 0 };
9628
+ return [];
9060
9629
  }
9061
- if (chars <= MEMORY_MD_TOTAL_MAX_CHARS) {
9062
- return { converged: false, charsBefore: chars, charsAfter: chars };
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]);
9662
+ }
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 = "";
9668
+ try {
9669
+ if (existsSync8(this.longTermFile))
9670
+ curatedRaw = readFileSync6(this.longTermFile, "utf-8");
9671
+ } catch {
9672
+ }
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) });
9063
9771
  }
9064
- const result = this.compressLongTermMemory();
9065
- log8.warn("knowledge.md over budget at load \u2014 converged", {
9066
- charsBefore: result.charsBefore,
9067
- charsAfter: result.charsAfter,
9068
- cap: MEMORY_MD_TOTAL_MAX_CHARS,
9069
- store: this.getStoreFileName()
9070
- });
9071
- return { converged: true, charsBefore: result.charsBefore, charsAfter: result.charsAfter };
9072
9772
  }
9073
9773
  /**
9074
9774
  * Detect a knowledge.md that needs a boot-time rebuild: either unexpectedly
@@ -9089,6 +9789,20 @@ ${entry.content}
9089
9789
  }
9090
9790
  }
9091
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
+ }
9092
9806
  parseObservationsFromMemoryMd() {
9093
9807
  if (!existsSync8(this.longTermFile))
9094
9808
  return [];
@@ -9097,66 +9811,73 @@ ${entry.content}
9097
9811
  const obsMatch = content.match(/(?:^|\n)## _observations\n([\s\S]*)$/);
9098
9812
  if (!obsMatch)
9099
9813
  return [];
9100
- const obsContent = obsMatch[1];
9101
- const entries2 = [];
9102
- const subsections = obsContent.split(/\n### /).filter((s2) => s2.trim());
9103
- for (const section3 of subsections) {
9104
- const lines = section3.split("\n");
9105
- const headerLine = lines[0] ?? "";
9106
- if (headerLine.startsWith("<!--"))
9107
- continue;
9108
- const idMatch = headerLine.match(/^(\S+)/);
9109
- if (!idMatch)
9110
- continue;
9111
- const id = idMatch[1];
9112
- let type = "note";
9113
- let tags = [];
9114
- let restoredMeta;
9115
- const contentLines = [];
9116
- for (let i = 1; i < lines.length; i++) {
9117
- const metaMatch = lines[i].match(/^<!-- type: (\w+)(?:, tags: (.*?))?(?:, data-meta: (.+))? -->$/);
9118
- if (metaMatch) {
9119
- const typeVal = metaMatch[1];
9120
- if (typeVal && VALID_TYPES.has(typeVal))
9121
- type = typeVal;
9122
- let parsedMeta;
9123
- if (metaMatch[3])
9124
- parsedMeta = parseDataMeta(metaMatch[3]);
9125
- const legacyTags = metaMatch[2] ? metaMatch[2].split(",").map((t2) => t2.trim()).filter(Boolean) : [];
9126
- const metaTags = parsedMeta && Array.isArray(parsedMeta.tags) ? parsedMeta.tags : legacyTags;
9127
- if (parsedMeta) {
9128
- const rest = { ...parsedMeta };
9129
- delete rest.tags;
9130
- restoredMeta = { ...restoredMeta ?? {}, ...rest };
9131
- }
9132
- if (Array.isArray(metaTags)) {
9133
- tags = metaTags.map(String);
9134
- restoredMeta = { ...restoredMeta ?? {}, tags };
9135
- } else if (parsedMeta) {
9136
- restoredMeta = { ...restoredMeta ?? {} };
9137
- }
9138
- if (tags.some((t2) => /data-meta|\\"|\\:/i.test(t2)))
9139
- tags = [];
9140
- continue;
9141
- }
9142
- contentLines.push(lines[i]);
9143
- }
9144
- const idTs = id.match(/^obs_(\d+)/);
9145
- const timestamp = idTs ? new Date(parseInt(idTs[1])).toISOString() : (/* @__PURE__ */ new Date()).toISOString();
9146
- entries2.push({
9147
- id,
9148
- timestamp,
9149
- type,
9150
- content: contentLines.join("\n").trim(),
9151
- metadata: restoredMeta !== void 0 ? restoredMeta : tags.length > 0 ? { tags } : void 0
9152
- });
9153
- }
9154
- return entries2;
9814
+ return this.parseEntryBlocks(obsMatch[1]);
9155
9815
  } catch (err) {
9156
9816
  log8.warn("Failed to parse observations from knowledge.md", { error: String(err) });
9157
9817
  return [];
9158
9818
  }
9159
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
+ }
9160
9881
  loadSessionsFromDisk() {
9161
9882
  try {
9162
9883
  const files = readdirSync(this.sessionsDir).filter((f) => f.endsWith(".json"));
@@ -9219,57 +9940,47 @@ ${entry.content}
9219
9940
  }
9220
9941
  saveToDisk() {
9221
9942
  try {
9222
- const obsLines = [
9223
- "## _observations",
9224
- "<!-- This section is the observation buffer. Searched on-demand, NOT always injected into prompt. -->",
9225
- "<!-- Dream cycle consolidates recurring patterns into curated sections above. -->",
9226
- ""
9227
- ];
9228
- const isFrag = (e) => e.type === "conversation_fragment";
9229
- const obsCount = () => this.entries.filter((e) => !isFrag(e)).length;
9230
- let obsChars = this.entries.filter((e) => !isFrag(e)).reduce((n2, e) => n2 + e.content.length + 96, 0);
9231
- while (obsChars > MEMORY_OBSERVATIONS_MAX_CHARS && obsCount() > 1) {
9232
- const idx = this.entries.findIndex((e) => !isFrag(e));
9233
- if (idx < 0)
9234
- break;
9235
- const oldest = this.entries.splice(idx, 1)[0];
9236
- this.archiveSection(`observation ${oldest.id}`, oldest.content);
9237
- obsChars -= oldest.content.length + 96;
9238
- }
9239
- const keptObs = this.entries.filter((e) => !isFrag(e)).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9240
- const keptFrags = this.entries.filter(isFrag).slice(-_MemoryStore.MAX_MEMORY_ENTRIES);
9241
- const keepIds = new Set([...keptObs, ...keptFrags].map((e) => e.id));
9242
- const entries2 = this.entries.filter((e) => keepIds.has(e.id) && e.content.trim().length > 0);
9943
+ const entries2 = this.observationWriteSet();
9243
9944
  this.entries = entries2;
9244
- for (const entry of entries2) {
9245
- obsLines.push(`### ${entry.id}`);
9246
- const tags = Array.isArray(entry.metadata?.tags) ? entry.metadata.tags : [];
9247
- const meta = entry.metadata && typeof entry.metadata === "object" ? { ...entry.metadata, tags } : tags.length > 0 ? { tags } : void 0;
9248
- const metaJson = meta ? safeJson(meta) : "";
9249
- obsLines.push(`<!-- type: ${entry.type}${metaJson ? `, data-meta: ${metaJson}` : ""} -->`);
9250
- obsLines.push(entry.content);
9251
- obsLines.push("");
9252
- }
9253
- const obsSection = obsLines.join("\n");
9254
- let existing = "";
9255
- if (existsSync8(this.longTermFile)) {
9256
- existing = readFileSync6(this.longTermFile, "utf-8");
9257
- }
9258
- let obsStart = existing.indexOf("\n## _observations");
9259
- if (obsStart < 0 && existing.startsWith("## _observations"))
9260
- obsStart = 0;
9261
- let updated;
9262
- if (obsStart > 0) {
9263
- updated = existing.slice(0, obsStart) + "\n" + obsSection;
9264
- } else if (obsStart === 0) {
9265
- updated = obsSection;
9266
- } else {
9267
- updated = (existing ? existing.trimEnd() + "\n\n" : "") + obsSection;
9268
- }
9269
- writeFileAtomic(this.longTermFile, updated);
9945
+ writeFileAtomic(this.observationFile, serializeRecords(entries2));
9946
+ this.writeCuratedKnowledgeMd();
9270
9947
  } catch (err) {
9271
- 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 {
9272
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
+ ` : "");
9273
9984
  }
9274
9985
  saveSessionToDisk(session) {
9275
9986
  try {
@@ -9289,88 +10000,8 @@ ${entry.content}
9289
10000
  this.saveSessionToDisk(session);
9290
10001
  }, 1e3));
9291
10002
  }
9292
- /** Compress knowledge.md — truncate oversized sections to prevent context bloat */
9293
- compressLongTermMemory() {
9294
- if (!existsSync8(this.longTermFile)) {
9295
- return { charsBefore: 0, charsAfter: 0, sectionsBefore: 0, sectionsAfter: 0, truncatedChunks: 0 };
9296
- }
9297
- const content = readFileSync6(this.longTermFile, "utf-8");
9298
- const charsBefore = content.length;
9299
- const lines = content.split("\n");
9300
- let i = 0;
9301
- const preambleLines = [];
9302
- while (i < lines.length && !lines[i].startsWith("## ")) {
9303
- preambleLines.push(lines[i]);
9304
- i++;
9305
- }
9306
- const sections = [];
9307
- let currentHeader = "";
9308
- let currentBody = [];
9309
- let currentIsObs = false;
9310
- while (i < lines.length) {
9311
- const line = lines[i];
9312
- if (line.startsWith("## ")) {
9313
- if (currentHeader) {
9314
- sections.push({ headerLine: currentHeader, body: currentBody, observationBuffer: currentIsObs });
9315
- }
9316
- currentHeader = line;
9317
- currentBody = [];
9318
- currentIsObs = /^##\s+_observations\s*$/.test(line);
9319
- } else {
9320
- currentBody.push(line);
9321
- }
9322
- i++;
9323
- }
9324
- if (currentHeader) {
9325
- sections.push({ headerLine: currentHeader, body: currentBody, observationBuffer: currentIsObs });
9326
- }
9327
- const sectionsBefore = sections.length;
9328
- let archived = 0;
9329
- const render2 = () => {
9330
- const out = [...preambleLines];
9331
- for (const s2 of sections)
9332
- out.push(s2.headerLine, s2.body.join("\n"));
9333
- return out.join("\n");
9334
- };
9335
- const size = () => render2().length;
9336
- const isPointer = (s2) => /^_\[archived/.test(s2.body.join("\n").trim());
9337
- const archiveBodyOf = (section3) => {
9338
- const bodyStr = section3.body.join("\n").trim();
9339
- if (!bodyStr)
9340
- return;
9341
- const name = section3.headerLine.replace(/^##\s+/, "").trim();
9342
- this.archiveSection(name, bodyStr);
9343
- section3.body = [`_[archived \u2192 ${this.getArchiveFileName()}\uFF1B\u6B63\u6587\u5DF2\u65E0\u635F\u5F52\u6863\uFF0C\u53EF\u7528 memory_search \u68C0\u7D22]_`];
9344
- archived++;
9345
- };
9346
- for (const section3 of sections) {
9347
- if (section3.observationBuffer)
9348
- continue;
9349
- if (section3.body.join("\n").length > MEMORY_MD_SECTION_MAX_CHARS)
9350
- archiveBodyOf(section3);
9351
- }
9352
- if (size() > MEMORY_MD_TOTAL_MAX_CHARS) {
9353
- const shrinkable = sections.filter((s2) => !s2.observationBuffer && !isPointer(s2)).sort((a, b) => b.body.join("\n").length - a.body.join("\n").length);
9354
- for (const section3 of shrinkable) {
9355
- if (size() <= MEMORY_MD_TOTAL_MAX_CHARS)
9356
- break;
9357
- if (section3.body.join("\n").trim().length <= 120)
9358
- continue;
9359
- archiveBodyOf(section3);
9360
- }
9361
- }
9362
- const compressed = render2();
9363
- if (compressed !== content)
9364
- writeFileAtomic(this.longTermFile, compressed);
9365
- return {
9366
- charsBefore,
9367
- charsAfter: compressed.length,
9368
- sectionsBefore,
9369
- sectionsAfter: sections.length,
9370
- truncatedChunks: archived
9371
- };
9372
- }
9373
10003
  };
10004
+ FRAGMENT_REGION_HEADER = "## _session_fragments";
9374
10005
  }
9375
10006
  });
9376
10007
 
@@ -9401,7 +10032,8 @@ function freshCounters() {
9401
10032
  cacheWriteTokens: 0,
9402
10033
  turnsCompleted: 0,
9403
10034
  nonChatTurns: 0,
9404
- markerMissTurns: 0,
10035
+ emptyTurns: 0,
10036
+ endTurnTurns: 0,
9405
10037
  promptTokensReported: 0
9406
10038
  };
9407
10039
  }
@@ -9517,9 +10149,10 @@ var init_agent_metrics = __esm({
9517
10149
  this.scheduleSave();
9518
10150
  }
9519
10151
  /**
9520
- * C2: a mailbox turn completed. Non-chat turns are expected to end with a completion
9521
- * marker; missing markers on those turns feed the marker-failure rate. Chat turns are
9522
- * 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.
9523
10156
  */
9524
10157
  recordTurn(opts) {
9525
10158
  const c = this.counters;
@@ -9528,8 +10161,10 @@ var init_agent_metrics = __esm({
9528
10161
  c.estimatedCost += opts.costUsd;
9529
10162
  if (!opts.isChat) {
9530
10163
  c.nonChatTurns++;
9531
- if (!opts.hadCompletionMarker)
9532
- c.markerMissTurns++;
10164
+ if (opts.emptyReply)
10165
+ c.emptyTurns++;
10166
+ if (opts.endedTurnViaTool)
10167
+ c.endTurnTurns++;
9533
10168
  }
9534
10169
  this.scheduleSave();
9535
10170
  }
@@ -9561,13 +10196,15 @@ var init_agent_metrics = __esm({
9561
10196
  };
9562
10197
  }
9563
10198
  computeHarnessMetrics(c) {
9564
- 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;
9565
10201
  const cacheHitRate = c.promptTokens > 0 ? Math.min(1, c.cacheReadTokens / c.promptTokens) : 0;
9566
10202
  const window3 = this.computeWindowStats();
9567
10203
  const perTurnCostUsd = c.turnsCompleted > 0 ? c.estimatedCost / c.turnsCompleted : 0;
9568
10204
  return {
9569
10205
  compressionCount: c.compressionCount,
9570
- markerFailureRate,
10206
+ emptyTurnRate,
10207
+ turnEndedViaToolRate,
9571
10208
  cacheHitRate,
9572
10209
  cacheHitRateWindow: window3.cacheHitRateWindow,
9573
10210
  cacheHitRateSamples: window3.cacheHitRateSamples,
@@ -10600,9 +11237,12 @@ _[norms truncated \u2014 read \`${opts.teamDataDir ?? "team"}/NORMS.md\` for ful
10600
11237
  try {
10601
11238
  const h = opts.memory.getMemoryHealth();
10602
11239
  const staleDays = h.lastConsolidatedAt ? Math.max(0, Math.floor((Date.now() - Date.parse(h.lastConsolidatedAt)) / 864e5)) : null;
10603
- if (h.percent >= 70 || staleDays !== null && staleDays >= 14) {
11240
+ if (h.percent >= MEMORY_HEALTH_WARN_PERCENT || staleDays !== null && staleDays >= 14) {
10604
11241
  const staleness = staleDays !== null && staleDays >= 14 ? ` \xB7 \u4E0A\u6B21\u6574\u7406 ${staleDays} \u5929\u524D` : "";
10605
- 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`);
10606
11246
  }
10607
11247
  } catch {
10608
11248
  }
@@ -10735,21 +11375,11 @@ _[dynamic context truncated]_`);
10735
11375
  }
10736
11376
  }
10737
11377
  const alreadyShownIds = /* @__PURE__ */ new Set();
10738
- const cpp = opts.cognitiveContext;
10739
- if (cpp && !cpp.isEmpty) {
10740
- if (cpp.cognitiveContext) {
10741
- dynamic.push("\n## Cognitive Context");
10742
- dynamic.push(cpp.cognitiveContext);
10743
- }
10744
- if (cpp.retrievedContext) {
10745
- dynamic.push("\n## Retrieved Context");
10746
- dynamic.push(cpp.retrievedContext);
10747
- }
10748
- if (cpp.reflection) {
10749
- dynamic.push("\n## Reflection");
10750
- dynamic.push(cpp.reflection);
10751
- }
10752
- } else if (!isDream) {
11378
+ if (opts.cognitiveContext) {
11379
+ dynamic.push("\n## Cognitive Context");
11380
+ dynamic.push(opts.cognitiveContext);
11381
+ }
11382
+ if (!isDream) {
10753
11383
  const relevantMemories = await this.retrieveRelevantMemories(opts.memory, opts.currentQuery, opts.agentId, alreadyShownIds);
10754
11384
  if (relevantMemories.length > 0) {
10755
11385
  volatile.push("\n## Relevant Memories");
@@ -14811,6 +15441,10 @@ function createShellTool(security, workspacePath, agentMeta, policy, onCommandAp
14811
15441
  session_id: {
14812
15442
  type: "string",
14813
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)."
14814
15448
  }
14815
15449
  },
14816
15450
  required: ["command"]
@@ -15057,6 +15691,14 @@ var init_shell = __esm({
15057
15691
  }
15058
15692
  });
15059
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
+
15060
15702
  // ../core/dist/tools/file.js
15061
15703
  import { readFileSync as readFileSync11, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, existsSync as existsSync15, statSync as statSync2 } from "node:fs";
15062
15704
  import { basename as basename4, dirname as dirname4, resolve as resolve7 } from "node:path";
@@ -15251,7 +15893,7 @@ function createFileEditTool(security, workspacePath, policy) {
15251
15893
  error: `old_string found ${count} times \u2014 must be unique. Add more surrounding context to make it unique.`
15252
15894
  });
15253
15895
  }
15254
- const updated = content.replace(oldStr, newStr);
15896
+ const updated = replaceLiteral(content, oldStr, newStr);
15255
15897
  writeFileSync10(path, updated);
15256
15898
  return JSON.stringify({ status: "success", path, replacements: 1 });
15257
15899
  } catch (error) {
@@ -15267,6 +15909,7 @@ var init_file = __esm({
15267
15909
  init_dist();
15268
15910
  init_security();
15269
15911
  init_write_guard();
15912
+ init_literal_replace2();
15270
15913
  MANIFEST_FILENAMES2 = /* @__PURE__ */ new Set(["agent.json", "team.json", "skill.json"]);
15271
15914
  FileReadTool = createFileReadTool();
15272
15915
  FileWriteTool = createFileWriteTool();
@@ -48526,7 +49169,7 @@ function createPatchTool(security, workspacePath, policy) {
48526
49169
  error: `Hunk ${i + 1} old_string found ${count} times in ${patch.file} \u2014 must be unique`
48527
49170
  });
48528
49171
  }
48529
- content = content.replace(hunk.old_string, hunk.new_string);
49172
+ content = replaceLiteral(content, hunk.old_string, hunk.new_string);
48530
49173
  }
48531
49174
  }
48532
49175
  if (patch.action === "create" && !patch.content && patch.content !== "") {
@@ -48548,7 +49191,7 @@ function createPatchTool(security, workspacePath, policy) {
48548
49191
  case "edit": {
48549
49192
  let content = readFileSync12(filePath, "utf-8");
48550
49193
  for (const hunk of patch.hunks) {
48551
- content = content.replace(hunk.old_string, hunk.new_string);
49194
+ content = replaceLiteral(content, hunk.old_string, hunk.new_string);
48552
49195
  }
48553
49196
  writeFileSync11(filePath, content);
48554
49197
  results.push({
@@ -48594,6 +49237,7 @@ var init_patch = __esm({
48594
49237
  "use strict";
48595
49238
  init_security();
48596
49239
  init_file();
49240
+ init_literal_replace2();
48597
49241
  }
48598
49242
  });
48599
49243
 
@@ -49046,10 +49690,12 @@ function persistSubagentLog(dataDir, subagentId, entries2) {
49046
49690
  }
49047
49691
  async function runSubagentLoop(ctx, task, opts) {
49048
49692
  const hardCap = ctx.maxToolIterations ?? DEFAULT_MAX_SUBAGENT_ITERATIONS;
49049
- 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;
49050
49696
  const onProgress = opts?.onProgress;
49051
- const sharedBudget = opts?.sharedBudget;
49052
- let budgetExhausted = false;
49697
+ let status = "completed";
49698
+ let aggregateCeilingReached = false;
49053
49699
  const subagentId = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
49054
49700
  const logEntries = [];
49055
49701
  const parentTools = ctx.getTools();
@@ -49074,7 +49720,8 @@ async function runSubagentLoop(ctx, task, opts) {
49074
49720
  subagentId,
49075
49721
  taskLength: task.length,
49076
49722
  toolCount: toolMap.size,
49077
- maxIterations: maxIter
49723
+ maxIterations,
49724
+ iterationBudget
49078
49725
  });
49079
49726
  onProgress?.({
49080
49727
  type: "started",
@@ -49088,23 +49735,41 @@ async function runSubagentLoop(ctx, task, opts) {
49088
49735
  }, provider), `subagent-${subagentId}-init`);
49089
49736
  let iterations = 0;
49090
49737
  while (response.finishReason === "tool_use" && response.toolCalls?.length || response.finishReason === "max_tokens") {
49091
- if (++iterations > maxIter) {
49092
- log14.warn("Subagent hit max iterations", { parentAgent: ctx.agentId, subagentId, iterations });
49093
- onProgress?.({ type: "error", content: `Subagent hit max iterations (${maxIter})` });
49094
- break;
49095
- }
49096
- if (sharedBudget) {
49097
- if (sharedBudget.remaining <= 0) {
49098
- budgetExhausted = true;
49099
- log14.warn("Subagent stopped: shared aggregate budget exhausted", { parentAgent: ctx.agentId, subagentId, iterations });
49100
- 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" });
49101
49748
  break;
49102
49749
  }
49103
- 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;
49104
49768
  }
49769
+ iterations++;
49105
49770
  onProgress?.({
49106
49771
  type: "iteration",
49107
- content: `Iteration ${iterations}/${maxIter}`,
49772
+ content: `Iteration ${iterations}/${maxIterations}`,
49108
49773
  metadata: { iteration: iterations, finishReason: response.finishReason }
49109
49774
  });
49110
49775
  if (response.finishReason === "max_tokens" && !response.toolCalls?.length) {
@@ -49181,11 +49846,15 @@ async function runSubagentLoop(ctx, task, opts) {
49181
49846
  }, provider), `subagent-${subagentId}-iter${iterations}`);
49182
49847
  }
49183
49848
  const rawResult = response.content;
49184
- let cleanResult = stripThinkTags(rawResult);
49185
- if (budgetExhausted) {
49186
- 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()}
49187
49854
 
49188
- [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.]";
49189
49858
  }
49190
49859
  logEntries.push({
49191
49860
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -49196,19 +49865,26 @@ async function runSubagentLoop(ctx, task, opts) {
49196
49865
  if (ctx.dataDir) {
49197
49866
  logPath = persistSubagentLog(ctx.dataDir, subagentId, logEntries);
49198
49867
  }
49199
- log14.info("Subagent completed", {
49868
+ log14.info("Subagent finished", {
49200
49869
  parentAgent: ctx.agentId,
49201
49870
  subagentId,
49871
+ status,
49202
49872
  iterations,
49873
+ aggregateCeilingReached,
49203
49874
  resultLength: cleanResult.length,
49204
49875
  logPath
49205
49876
  });
49206
49877
  onProgress?.({
49207
- type: "completed",
49208
- content: `Subagent completed in ${iterations} iterations`,
49209
- 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 }
49210
49881
  });
49211
- return cleanResult;
49882
+ return {
49883
+ status,
49884
+ output: cleanResult,
49885
+ iterations,
49886
+ aggregateCeilingReached
49887
+ };
49212
49888
  }
49213
49889
  function createSubagentTool(ctx) {
49214
49890
  return {
@@ -49233,6 +49909,10 @@ function createSubagentTool(ctx) {
49233
49909
  max_iterations: {
49234
49910
  type: "number",
49235
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)."
49236
49916
  }
49237
49917
  },
49238
49918
  required: ["task"]
@@ -49243,13 +49923,19 @@ function createSubagentTool(ctx) {
49243
49923
  return JSON.stringify({ status: "error", error: "task is required" });
49244
49924
  }
49245
49925
  try {
49246
- const result = await runSubagentLoop(ctx, task, {
49926
+ const loop = await runSubagentLoop(ctx, task, {
49247
49927
  systemPrompt: args["system_prompt"],
49248
49928
  allowedTools: args["allowed_tools"],
49249
49929
  maxIterations: args["max_iterations"],
49930
+ iterationBudget: args["iteration_budget"],
49250
49931
  onProgress: ctx.getProgressCallback?.()
49251
49932
  });
49252
- 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
+ });
49253
49939
  } catch (err) {
49254
49940
  log14.error("Subagent execution failed", { error: String(err) });
49255
49941
  return JSON.stringify({ status: "error", error: `Subagent failed: ${String(err)}` });
@@ -49285,6 +49971,10 @@ function createParallelSubagentTool(ctx) {
49285
49971
  max_iterations: {
49286
49972
  type: "number",
49287
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."
49288
49978
  }
49289
49979
  },
49290
49980
  required: ["id", "task"]
@@ -49322,46 +50012,71 @@ function createParallelSubagentTool(ctx) {
49322
50012
  metadata: { taskIds: tasks.map((t2) => t2.id) }
49323
50013
  });
49324
50014
  const startTime = Date.now();
49325
- const sharedBudget = { remaining: SUBAGENT_MAX_AGGREGATE_ITERATIONS };
50015
+ const aggregateBudget = { remaining: SUBAGENT_MAX_AGGREGATE_ITERATIONS };
49326
50016
  const results = await Promise.allSettled(tasks.map(async (t2) => {
49327
50017
  const perTaskProgress = onProgress ? (event) => onProgress({
49328
50018
  ...event,
49329
50019
  content: `[${t2.id}] ${event.content}`,
49330
50020
  metadata: { ...event.metadata, parallelTaskId: t2.id }
49331
50021
  }) : void 0;
49332
- const result = await runSubagentLoop(ctx, t2.task, {
50022
+ const loop = await runSubagentLoop(ctx, t2.task, {
49333
50023
  systemPrompt: sharedSystemPrompt,
49334
50024
  allowedTools: t2.allowed_tools,
49335
50025
  maxIterations: t2.max_iterations,
50026
+ iterationBudget: t2.iteration_budget,
49336
50027
  onProgress: perTaskProgress,
49337
- sharedBudget
50028
+ aggregateBudget
49338
50029
  });
49339
- return { id: t2.id, result };
50030
+ return { id: t2.id, loop };
49340
50031
  }));
49341
- const budgetExceeded = sharedBudget.remaining <= 0;
50032
+ const budgetExceeded = aggregateBudget.remaining <= 0;
49342
50033
  const output = results.map((r, i) => {
49343
50034
  if (r.status === "fulfilled") {
49344
- 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
+ };
49345
50044
  }
49346
- 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
+ };
49347
50052
  });
49348
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;
49349
50055
  const failed = output.filter((o) => o.status === "error").length;
49350
50056
  const durationMs = Date.now() - startTime;
49351
50057
  log14.info("Parallel subagents finished", {
49352
50058
  parentAgent: ctx.agentId,
49353
50059
  completed,
50060
+ stoppedEarly,
49354
50061
  failed,
50062
+ budgetExceeded,
49355
50063
  totalDurationMs: durationMs
49356
50064
  });
49357
50065
  onProgress?.({
49358
- type: "completed",
49359
- content: `${completed}/${tasks.length} subagents completed (${durationMs}ms)`,
49360
- 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 }
49361
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");
49362
50077
  return JSON.stringify({
49363
50078
  status: "completed",
49364
- 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("; "),
49365
50080
  durationMs,
49366
50081
  budgetExceeded,
49367
50082
  aggregateIterationBudget: SUBAGENT_MAX_AGGREGATE_ITERATIONS,
@@ -50751,9 +51466,6 @@ function detectAbnormalCompletion(reply, item) {
50751
51466
  if (reply === void 0 || reply === "") {
50752
51467
  return "empty reply from LLM-invoking item";
50753
51468
  }
50754
- if (!hasCompletionMarker(reply)) {
50755
- return "completion marker missing from reply";
50756
- }
50757
51469
  return void 0;
50758
51470
  }
50759
51471
  var log17, AttentionController;
@@ -51535,15 +52247,7 @@ var init_attention = __esm({
51535
52247
  const retries = item.retryCount ?? 0;
51536
52248
  const isUserInteraction = _AttentionController.USER_INTERACTION_TYPES.has(item.sourceType);
51537
52249
  if (abnormalReason && retries < MAILBOX_ITEM_MAX_RETRIES) {
51538
- if (abnormalReason === "completion marker missing from reply") {
51539
- log17.warn("Completion marker still missing after in-session continuation \u2014 marking dropped without retry", {
51540
- agentId: this.agentId,
51541
- itemId: item.id,
51542
- type: item.sourceType
51543
- });
51544
- this.emitIncomplete(item, abnormalReason);
51545
- this.mailbox.drop(item.id);
51546
- } else if (isUserInteraction) {
52250
+ if (isUserInteraction) {
51547
52251
  log17.warn("Abnormal completion for user interaction \u2014 marking dropped without retry", {
51548
52252
  agentId: this.agentId,
51549
52253
  itemId: item.id,
@@ -51773,8 +52477,8 @@ var init_attention = __esm({
51773
52477
  }
51774
52478
  /**
51775
52479
  * A3: emit a structured `agent:incomplete` event when a mailbox item completes
51776
- * without finishing cleanly (marker missing after continuation, or abnormal reply
51777
- * 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.
51778
52482
  */
51779
52483
  /**
51780
52484
  * 等待某 worker 的在途处理 promise 结束(有界等待)。
@@ -52424,18 +53128,20 @@ var init_resource_locks = __esm({
52424
53128
  const req = requests[index];
52425
53129
  const key2 = lockKey(req);
52426
53130
  const outer = heldLocksStore.getStore();
52427
- if (outer?.held.some((h) => lockKey(h) === key2)) {
53131
+ if (outer?.held.some((h) => !h.released && lockKey(h.req) === key2)) {
52428
53132
  return this.acquireChain(requests, index + 1, fn);
52429
53133
  }
52430
- const conflicting = outer?.held.find((h) => locksConflict(h, req));
53134
+ const conflicting = outer?.held.find((h) => !h.released && locksConflict(h.req, req));
52431
53135
  if (conflicting)
52432
- throw new LockNestingConflictError(conflicting, req);
53136
+ throw new LockNestingConflictError(conflicting.req, req);
52433
53137
  await this.acquireOne(req);
52434
- const nextHeld = { held: [...outer?.held ?? [], req] };
53138
+ const holder = { req, released: false };
53139
+ const nextHeld = { held: [...outer?.held ?? [], holder] };
52435
53140
  try {
52436
53141
  return await heldLocksStore.run(nextHeld, () => this.acquireChain(requests, index + 1, fn));
52437
53142
  } finally {
52438
53143
  this.releaseOne(req);
53144
+ holder.released = true;
52439
53145
  }
52440
53146
  }
52441
53147
  acquireOne(req) {
@@ -53874,27 +54580,17 @@ function sanitizeLLMReply(reply) {
53874
54580
  return cleaned || reply;
53875
54581
  }
53876
54582
  function stripCompletionMarker(reply) {
53877
- return stripCompletionMarkerLeak(reply).trim();
54583
+ return stripLegacyCompletionToken(reply).trim();
53878
54584
  }
53879
54585
  function createMarkerStrippingDelta(rawEmit) {
53880
- const markerLen = COMPLETION_MARKER.length;
53881
- let tail = "";
53882
- const emit = (chunk) => {
53883
- tail += chunk;
53884
- if (tail.length <= markerLen)
53885
- return;
53886
- const safe = tail.slice(0, tail.length - markerLen);
53887
- tail = tail.slice(safe.length);
53888
- if (safe)
53889
- rawEmit(safe);
53890
- };
53891
- const flush = () => {
53892
- const cleaned = stripCompletionMarkerLeak(tail);
53893
- tail = "";
53894
- if (cleaned)
53895
- rawEmit(cleaned);
54586
+ return {
54587
+ emit: (chunk) => {
54588
+ if (chunk)
54589
+ rawEmit(chunk);
54590
+ },
54591
+ flush: () => {
54592
+ }
53896
54593
  };
53897
- return { emit, flush };
53898
54594
  }
53899
54595
  function addArgCasingAliases(args) {
53900
54596
  if (!args || typeof args !== "object" || Array.isArray(args)) {
@@ -53941,6 +54637,7 @@ var init_agent2 = __esm({
53941
54637
  "use strict";
53942
54638
  init_dist();
53943
54639
  init_lock_resources();
54640
+ init_dream_trigger();
53944
54641
  init_tracing();
53945
54642
  init_events();
53946
54643
  init_token_counter();
@@ -54170,8 +54867,6 @@ var init_agent2 = __esm({
54170
54867
  notebookSaveTimer;
54171
54868
  /** Earliest time the debounced notebook write may be deferred to (maxWait). */
54172
54869
  notebookSaveDeadline;
54173
- /** 审计 §8.1:CPP 的 LLM 管道已移除;仅保留配置(决定是否注入确定性情境块)。 */
54174
- cognitiveConfig;
54175
54870
  /** Ring buffer of recent activity summaries for triage context. */
54176
54871
  recentActivityRing = [];
54177
54872
  static ACTIVITY_RING_SIZE = 8;
@@ -54366,9 +55061,6 @@ var init_agent2 = __esm({
54366
55061
  this.guardrails = new GuardrailPipeline();
54367
55062
  this.toolHooks = new ToolHookRegistry();
54368
55063
  this.metricsCollector = new AgentMetricsCollector(this.id, options.dataDir);
54369
- if (options.cognitive?.enabled) {
54370
- this.cognitiveConfig = options.cognitive;
54371
- }
54372
55064
  this.heartbeat = new HeartbeatScheduler(this.id, this.eventBus, {
54373
55065
  intervalMs: this.config.heartbeatIntervalMs,
54374
55066
  enabled: true
@@ -54951,7 +55643,8 @@ ${notification.stdoutTail}`);
54951
55643
  try {
54952
55644
  this.metricsCollector.recordTurn({
54953
55645
  isChat: item.sourceType === "human_chat",
54954
- hadCompletionMarker: typeof result === "string" && result.includes(COMPLETION_MARKER)
55646
+ endedTurnViaTool,
55647
+ emptyReply: result === void 0 || result === ""
54955
55648
  });
54956
55649
  } catch (err) {
54957
55650
  log20.debug("recordTurn failed", { agentId: this.id, itemId: item.id, error: String(err) });
@@ -55083,21 +55776,35 @@ ${notification.stdoutTail}`);
55083
55776
  sessionToolNames
55084
55777
  };
55085
55778
  }
55086
- async ensureCompletionMarker(reply, sessionId, onEvent) {
55779
+ /**
55780
+ * If a turn finished without a typed completion signal, continue in-session with
55781
+ * tools enabled so the model can finish announced-but-unfinished work rather than
55782
+ * leaving the user with a plan and no result.
55783
+ *
55784
+ * The guard is TYPED: a turn that ended via the `end_turn` tool is complete by
55785
+ * definition (as are cancellation / preemption / merge), so no continuation runs.
55786
+ * The nudge asks for the `end_turn` **tool call** — the same signal the mailbox
55787
+ * layer reads — instead of a magic string (docs/PLATFORM-HARDENING-2026-10.md §6).
55788
+ *
55789
+ * Still a single bounded continuation attempt: if it yields nothing further the
55790
+ * reply is returned as-is and the attention controller completes the item, because
55791
+ * a non-empty reply is never "abnormal".
55792
+ */
55793
+ async ensureTurnCompleted(reply, sessionId, onEvent) {
55087
55794
  if (!reply || reply === "[cancelled]" || reply === "[preempted]" || reply === "[merged]")
55088
55795
  return reply;
55089
- if (hasCompletionMarker(reply))
55796
+ if (this.endTurnRequested)
55090
55797
  return reply;
55091
55798
  if (!sessionId || !this.memory.getSession(sessionId))
55092
55799
  return reply;
55093
- log20.info("Completion marker missing \u2014 continuing in-session to obtain marker", {
55800
+ log20.info("Turn finished without an end_turn signal \u2014 continuing in-session to close it out", {
55094
55801
  agentId: this.id,
55095
55802
  sessionId,
55096
55803
  replyLength: reply.length
55097
55804
  });
55098
55805
  this.memory.appendMessage(sessionId, {
55099
55806
  role: "user",
55100
- 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}`
55807
+ 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.`
55101
55808
  });
55102
55809
  try {
55103
55810
  const selectCtx = this.buildSessionAwareToolSelectContext(sessionId, reply, {
@@ -55110,7 +55817,7 @@ ${notification.stdoutTail}`);
55110
55817
  };
55111
55818
  let llmTools = this.buildToolDefinitions(markerToolSelectOpts);
55112
55819
  const multimodalToolNames = ["generate_image", "text_to_speech", "speech_to_text", "generate_video"];
55113
- log20.info("ensureCompletionMarker tool selection", {
55820
+ log20.info("ensureTurnCompleted tool selection", {
55114
55821
  agentId: this.id,
55115
55822
  sessionId,
55116
55823
  toolCount: llmTools.length,
@@ -55144,7 +55851,7 @@ ${notification.stdoutTail}`);
55144
55851
  const maxIter = Math.min(this._maxToolIterations, 24);
55145
55852
  while (shouldContinueToolLoop(response, { endTurnRequested: this.endTurnRequested })) {
55146
55853
  if (++toolIter > maxIter) {
55147
- log20.warn("ensureCompletionMarker tool loop hit max iterations", {
55854
+ log20.warn("ensureTurnCompleted tool loop hit max iterations", {
55148
55855
  agentId: this.id,
55149
55856
  sessionId,
55150
55857
  iterations: toolIter,
@@ -55160,7 +55867,7 @@ ${notification.stdoutTail}`);
55160
55867
  });
55161
55868
  this.memory.appendMessage(sessionId, {
55162
55869
  role: "user",
55163
- content: `[Continue from where you left off. When done, end with exactly: ${COMPLETION_MARKER}]`
55870
+ content: "[Continue from where you left off. When you are truly done, call the end_turn tool.]"
55164
55871
  });
55165
55872
  } else {
55166
55873
  this.memory.appendMessage(sessionId, {
@@ -55266,8 +55973,7 @@ ${item.payload.content}` + batchSuffix;
55266
55973
  };
55267
55974
  const ts = Date.now();
55268
55975
  const registry = MAILBOX_TYPE_REGISTRY[item.sourceType];
55269
- const needsMarker = !!registry?.invokesLLM;
55270
- const markerSuffix = needsMarker ? COMPLETION_MARKER_INSTRUCTION : "";
55976
+ const needsTurnCompletion = !!registry?.invokesLLM;
55271
55977
  const buildHandleOpts = (defaults = {}) => {
55272
55978
  const opts = { ...defaults };
55273
55979
  const ex = extra;
@@ -55316,7 +56022,7 @@ ${item.payload.content}` + batchSuffix;
55316
56022
  });
55317
56023
  } else {
55318
56024
  let reply2 = await this.handleMessageStream(
55319
- item.payload.content + markerSuffix,
56025
+ item.payload.content,
55320
56026
  extra.onEvent,
55321
56027
  item.metadata?.senderId,
55322
56028
  senderInfo,
@@ -55328,8 +56034,8 @@ ${item.payload.content}` + batchSuffix;
55328
56034
  // bound memory session instead of trusting the worker pointer.
55329
56035
  extra.sessionId
55330
56036
  );
55331
- if (needsMarker && item.sourceType !== "human_chat") {
55332
- reply2 = await this.ensureCompletionMarker(reply2, this.currentSessionId, extra.onEvent);
56037
+ if (needsTurnCompletion && item.sourceType !== "human_chat") {
56038
+ reply2 = await this.ensureTurnCompleted(reply2, this.currentSessionId, extra.onEvent);
55333
56039
  }
55334
56040
  resolveResponse(reply2);
55335
56041
  return reply2;
@@ -55358,9 +56064,9 @@ ${item.payload.content}` + batchSuffix;
55358
56064
  const opts = buildHandleOpts(defaults);
55359
56065
  if (item.sourceType === "a2a_message" && extra.scenario === void 0)
55360
56066
  opts.scenario = "a2a";
55361
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, opts);
55362
- if (needsMarker && item.sourceType !== "human_chat") {
55363
- reply = await this.ensureCompletionMarker(reply, opts.sessionId ?? this.currentSessionId);
56067
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, opts);
56068
+ if (needsTurnCompletion && item.sourceType !== "human_chat") {
56069
+ reply = await this.ensureTurnCompleted(reply, opts.sessionId ?? this.currentSessionId);
55364
56070
  }
55365
56071
  resolveResponse(reply);
55366
56072
  return reply;
@@ -55446,16 +56152,16 @@ ${item.payload.content}` + batchSuffix;
55446
56152
  }
55447
56153
  case "mention": {
55448
56154
  const mentionSessionId = `sys_${this.id}_${ts}`;
55449
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: mentionSessionId, scenario: "a2a" }));
55450
- if (needsMarker)
55451
- reply = await this.ensureCompletionMarker(reply, mentionSessionId);
56155
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: mentionSessionId, scenario: "a2a" }));
56156
+ if (needsTurnCompletion)
56157
+ reply = await this.ensureTurnCompleted(reply, mentionSessionId);
55452
56158
  resolveResponse(reply);
55453
56159
  return reply;
55454
56160
  }
55455
56161
  case "requirement_update": {
55456
56162
  if (extra.actionRequired) {
55457
56163
  const reqId = item.payload.requirementId ?? "unknown";
55458
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56164
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55459
56165
  sessionId: `requirement_${reqId}_${ts}`,
55460
56166
  scenario: "requirement_action",
55461
56167
  allowedTools: new Set(REQUIREMENT_ACTION_ALLOWED_TOOLS)
@@ -55472,7 +56178,7 @@ ${item.payload.content}` + batchSuffix;
55472
56178
  }
55473
56179
  case "requirement_comment": {
55474
56180
  const reqId = item.payload.requirementId ?? "unknown";
55475
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56181
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55476
56182
  sessionId: `comment_${reqId}_${ts}`,
55477
56183
  scenario: "comment_response",
55478
56184
  allowedTools: new Set(COMMENT_RESPONSE_ALLOWED_TOOLS)
@@ -55483,7 +56189,7 @@ ${item.payload.content}` + batchSuffix;
55483
56189
  case "workflow_update": {
55484
56190
  if (extra.actionRequired) {
55485
56191
  const wfEvent = extra.event ?? "update";
55486
- const reply = await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56192
+ const reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55487
56193
  sessionId: `workflow_${wfEvent}_${ts}`,
55488
56194
  scenario: "workflow_action",
55489
56195
  allowedTools: new Set(WORKFLOW_ACTION_ALLOWED_TOOLS)
@@ -55506,7 +56212,7 @@ ${item.payload.content}` + batchSuffix;
55506
56212
  this.injectUserMessage(sessionId, item.payload.content);
55507
56213
  } else {
55508
56214
  const commentTaskId = taskId2 ?? "unknown";
55509
- await this.handleMessage(item.payload.content + COMPLETION_MARKER_INSTRUCTION, item.metadata?.senderId, senderInfo, buildHandleOpts({
56215
+ await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({
55510
56216
  sessionId: `comment_${commentTaskId}_${ts}`,
55511
56217
  scenario: "comment_response",
55512
56218
  allowedTools: new Set(COMMENT_RESPONSE_ALLOWED_TOOLS)
@@ -55517,9 +56223,9 @@ ${item.payload.content}` + batchSuffix;
55517
56223
  }
55518
56224
  case "review_request": {
55519
56225
  const reviewSessionId = `review_${this.id}_${ts}`;
55520
- 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" }));
55521
- if (needsMarker)
55522
- reply = await this.ensureCompletionMarker(reply, reviewSessionId);
56226
+ 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" }));
56227
+ if (needsTurnCompletion)
56228
+ reply = await this.ensureTurnCompleted(reply, reviewSessionId);
55523
56229
  resolveResponse(reply);
55524
56230
  return reply;
55525
56231
  }
@@ -55528,7 +56234,7 @@ ${item.payload.content}` + batchSuffix;
55528
56234
  agentId: this.id,
55529
56235
  triggeredAt: item.queuedAt
55530
56236
  });
55531
- const hbReply = hbResult === "[preempted]" || hbResult === "[cancelled]" ? hbResult : COMPLETION_MARKER;
56237
+ const hbReply = hbResult === "[preempted]" || hbResult === "[cancelled]" ? hbResult : END_TURN_REPLY_SENTINEL;
55532
56238
  resolveResponse(hbReply);
55533
56239
  return hbReply;
55534
56240
  }
@@ -55536,17 +56242,17 @@ ${item.payload.content}` + batchSuffix;
55536
56242
  case "daily_report": {
55537
56243
  const sysSessionId = `sys_${this.id}_${ts}`;
55538
56244
  const sysScenario = (extra.callbackType !== void 0 ? asAgentScenario(extra.scenario) : void 0) ?? "heartbeat";
55539
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, buildHandleOpts({ sessionId: sysSessionId, scenario: sysScenario }));
55540
- if (needsMarker)
55541
- reply = await this.ensureCompletionMarker(reply, sysSessionId);
56245
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, buildHandleOpts({ sessionId: sysSessionId, scenario: sysScenario }));
56246
+ if (needsTurnCompletion)
56247
+ reply = await this.ensureTurnCompleted(reply, sysSessionId);
55542
56248
  resolveResponse(reply);
55543
56249
  return reply;
55544
56250
  }
55545
56251
  case "memory_consolidation": {
55546
56252
  const memSessionId = `sys_${this.id}_${ts}`;
55547
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, buildHandleOpts({ sessionId: memSessionId, scenario: "memory_consolidation" }));
55548
- if (needsMarker)
55549
- reply = await this.ensureCompletionMarker(reply, memSessionId);
56253
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, buildHandleOpts({ sessionId: memSessionId, scenario: "memory_consolidation" }));
56254
+ if (needsTurnCompletion)
56255
+ reply = await this.ensureTurnCompleted(reply, memSessionId);
55550
56256
  resolveResponse(reply);
55551
56257
  return reply;
55552
56258
  }
@@ -55555,16 +56261,16 @@ ${item.payload.content}` + batchSuffix;
55555
56261
  const onLog = extra.onLog ?? (() => {
55556
56262
  });
55557
56263
  if (sessionId) {
55558
- let reply2 = await this.respondInSession(sessionId, item.payload.content + markerSuffix, onLog);
55559
- if (needsMarker)
55560
- reply2 = await this.ensureCompletionMarker(reply2, sessionId);
56264
+ let reply2 = await this.respondInSession(sessionId, item.payload.content, onLog);
56265
+ if (needsTurnCompletion)
56266
+ reply2 = await this.ensureTurnCompleted(reply2, sessionId);
55561
56267
  resolveResponse(reply2);
55562
56268
  return reply2;
55563
56269
  }
55564
56270
  const srFallbackSessionId = `sys_${this.id}_${ts}`;
55565
- let reply = await this.handleMessage(item.payload.content + markerSuffix, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: srFallbackSessionId }));
55566
- if (needsMarker)
55567
- reply = await this.ensureCompletionMarker(reply, srFallbackSessionId);
56271
+ let reply = await this.handleMessage(item.payload.content, item.metadata?.senderId, senderInfo, buildHandleOpts({ sessionId: srFallbackSessionId }));
56272
+ if (needsTurnCompletion)
56273
+ reply = await this.ensureTurnCompleted(reply, srFallbackSessionId);
55568
56274
  resolveResponse(reply);
55569
56275
  return reply;
55570
56276
  }
@@ -55574,9 +56280,9 @@ ${item.payload.content}` + batchSuffix;
55574
56280
  const cbOpts = buildHandleOpts({ scenario: cbScenario });
55575
56281
  if (originSessionId)
55576
56282
  cbOpts.sessionId = originSessionId;
55577
- let reply = await this.handleMessage(item.payload.content + markerSuffix, void 0, void 0, cbOpts);
55578
- if (needsMarker)
55579
- reply = await this.ensureCompletionMarker(reply, cbOpts.sessionId ?? this.currentSessionId);
56283
+ let reply = await this.handleMessage(item.payload.content, void 0, void 0, cbOpts);
56284
+ if (needsTurnCompletion)
56285
+ reply = await this.ensureTurnCompleted(reply, cbOpts.sessionId ?? this.currentSessionId);
55580
56286
  resolveResponse(reply);
55581
56287
  return reply;
55582
56288
  }
@@ -56090,16 +56796,65 @@ ${item.payload.content}` + batchSuffix;
56090
56796
  * 测试与诊断断言。
56091
56797
  */
56092
56798
  cancelActiveStream(target) {
56093
- const workerId = this.resolveCancelTargetWorker(target);
56094
- if (workerId !== void 0 && this.workerWorkspaces.has(workerId)) {
56095
- this.cancelActiveStreamCore(workerId);
56096
- this.lastCancelledWorkerId = workerId;
56097
- return workerId;
56799
+ const resolved = this.resolveCancelTarget(target);
56800
+ if (resolved.kind === "worker") {
56801
+ this.cancelActiveStreamCore(resolved.workerId);
56802
+ this.lastCancelledWorkerId = resolved.workerId;
56803
+ return resolved.workerId;
56804
+ }
56805
+ if (resolved.kind === "none") {
56806
+ log20.warn("cancelActiveStream: scoped target matched no active stream \u2014 ignoring", {
56807
+ agentId: this.id,
56808
+ itemId: target?.itemId,
56809
+ sessionId: target?.sessionId,
56810
+ workerId: target?.workerId,
56811
+ workerCount: this.attentionController.getWorkerCount()
56812
+ });
56813
+ this.lastCancelledWorkerId = void 0;
56814
+ return void 0;
56098
56815
  }
56099
56816
  this.cancelActiveStreamCore();
56100
56817
  this.lastCancelledWorkerId = void 0;
56101
56818
  return void 0;
56102
56819
  }
56820
+ /**
56821
+ * 三态解析,语义严格区分:
56822
+ *
56823
+ * - `worker` 命中持有该目标的 worker → 只取消它的流;
56824
+ * - `root` **无 target** 的 legacy 调用 → 保持旧行为(ALS / 根上下文);
56825
+ * - `none` **显式给了 target 却解析不到任何在途流** → 调用方必须 no-op。
56826
+ *
56827
+ * 区分 `none` 与 `root` 正是这个 bug 的根因:旧实现把两者并成同一条兼容
56828
+ * 路径,于是「按 sessionId 取消」在目标不存在时静默升级成「取消当前在跑的
56829
+ * 那条流」—— 限定范围的请求降级为不限定范围的破坏性动作。
56830
+ */
56831
+ resolveCancelTarget(target) {
56832
+ if (!target)
56833
+ return { kind: "root" };
56834
+ if (target.workerId !== void 0) {
56835
+ return this.workerWorkspaces.has(target.workerId) ? { kind: "worker", workerId: target.workerId } : { kind: "none" };
56836
+ }
56837
+ if (this.attentionController.getWorkerCount() > 1) {
56838
+ const workerId = this.resolveCancelTargetWorker(target);
56839
+ return workerId !== void 0 ? { kind: "worker", workerId } : { kind: "none" };
56840
+ }
56841
+ const focus = this.attentionController.getCurrentFocus();
56842
+ if (!focus)
56843
+ return { kind: "none" };
56844
+ if (target.itemId !== void 0 && focus.id === target.itemId)
56845
+ return { kind: "root" };
56846
+ if (target.sessionId !== void 0 && this.focusMatchesSession(focus, target.sessionId))
56847
+ return { kind: "root" };
56848
+ return { kind: "none" };
56849
+ }
56850
+ /**
56851
+ * focus 上表达「属于哪个 DB 会话」的全部既有约定。
56852
+ * 与 `AttentionController.findWorkerBySessionId` 必须同一套匹配规则,
56853
+ * 否则串行/并发模式会对同一个 target 给出互相矛盾的答案。
56854
+ */
56855
+ focusMatchesSession(focus, sessionId) {
56856
+ return focus.metadata?.sessionId === sessionId || focus.metadata?.dbSessionId === sessionId || focus.payload?.extra?.sessionId === sessionId;
56857
+ }
56103
56858
  /** 最近一次定向取消实际命中的 workerId(未定向命中时为 undefined)。 */
56104
56859
  lastCancelledWorkerId;
56105
56860
  /** 诊断/测试:最近一次 cancelActiveStream 命中的 workerId。 */
@@ -56276,6 +57031,23 @@ ${conversationText}`
56276
57031
  }
56277
57032
  return `Task ${taskId2}`;
56278
57033
  }
57034
+ /** Banner that starts every offload payload. Used to emit it AND to detect an
57035
+ * already-offloaded result, so a capped output is never offloaded twice. */
57036
+ static OFFLOAD_BANNER_PREFIX = "[FULL output (";
57037
+ /**
57038
+ * Read the optional per-call output cap (`max_output_chars`).
57039
+ *
57040
+ * This is a cross-tool convention: any tool may advertise it, and the agent
57041
+ * honours it at the tool boundary (see `executeToolInternal`). It exists because
57042
+ * the alternative was worse — the agent had no way to *ask* for less output, so a
57043
+ * chatty command (a 46 k-char grep) was offloaded with a 2 k preview and cost a
57044
+ * second `file_read` round-trip to get at the part it actually wanted.
57045
+ */
57046
+ static readMaxOutputChars(args) {
57047
+ const raw = args?.["max_output_chars"];
57048
+ const n2 = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw) : NaN;
57049
+ return Number.isFinite(n2) && n2 > 0 ? Math.floor(n2) : void 0;
57050
+ }
56279
57051
  static BROWSER_INTERACTIVE_TOOLS = /* @__PURE__ */ new Set([
56280
57052
  "take_snapshot",
56281
57053
  "take_screenshot",
@@ -56287,15 +57059,18 @@ ${conversationText}`
56287
57059
  "performance_stop_trace",
56288
57060
  "performance_analyze_insight"
56289
57061
  ]);
56290
- offloadLargeResult(toolName, result) {
56291
- const OFFLOAD_THRESHOLD = TOOL_RESULT_OFFLOAD_CHARS;
57062
+ offloadLargeResult(toolName, result, maxOutputChars) {
57063
+ if (result.startsWith(_Agent.OFFLOAD_BANNER_PREFIX))
57064
+ return result;
57065
+ const requestedCap = maxOutputChars && maxOutputChars > 0 ? Math.floor(maxOutputChars) : void 0;
57066
+ const OFFLOAD_THRESHOLD = requestedCap ? Math.min(TOOL_RESULT_OFFLOAD_CHARS, requestedCap) : TOOL_RESULT_OFFLOAD_CHARS;
56292
57067
  if (result.length <= OFFLOAD_THRESHOLD)
56293
57068
  return result;
56294
57069
  if (toolName === "file_read")
56295
57070
  return result;
56296
57071
  const baseName = toolName.includes("__") ? toolName.split("__").pop() : toolName;
56297
57072
  const isBrowserTool = _Agent.BROWSER_INTERACTIVE_TOOLS.has(baseName);
56298
- const previewSize = isBrowserTool ? 3e4 : 2e3;
57073
+ const previewSize = requestedCap ?? (isBrowserTool ? 3e4 : 2e3);
56299
57074
  try {
56300
57075
  const offloadDir = join12(this.dataDir, "tool-outputs");
56301
57076
  mkdirSync12(offloadDir, { recursive: true });
@@ -56305,8 +57080,8 @@ ${conversationText}`
56305
57080
  const preview = safeSlice(result, 0, previewSize);
56306
57081
  const lineCount = result.split("\n").length;
56307
57082
  return [
56308
- `[FULL output (${result.length} chars, ${lineCount} lines) saved to: ${filepath}]`,
56309
- `[NOTE: The content below is only the first ${previewSize} chars. The complete, untruncated result is in the file above.]`,
57083
+ `${_Agent.OFFLOAD_BANNER_PREFIX}${result.length} chars, ${lineCount} lines) saved to: ${filepath}]`,
57084
+ `[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.]`,
56310
57085
  `[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)]`,
56311
57086
  ``,
56312
57087
  preview,
@@ -56739,16 +57514,14 @@ _[truncated \u2014 full text in NOTEBOOK.md]
56739
57514
  return parts.length > 0 ? parts.join("\n\n") : void 0;
56740
57515
  }
56741
57516
  /**
56742
- * 审计 §8.1:确定性情境准备(原 CPP 的 LLM 多阶段管道已移除)。
57517
+ * 审计 §8.1:确定性情境块(原 CPP 的 LLM 多阶段管道已移除)。
56743
57518
  *
56744
57519
  * 旧 CPP 在主调用前跑 0–3 次 LLM(appraise / reflect),带来额外时延与成本,
56745
57520
  * 且与上下文引擎自身「有界的相关记忆检索」重复。现改为**纯确定性**装配一小段
56746
- * 情境块(近期活动 + 工作记忆键);更深的跨域召回由 Agent 按场景提示主动调
56747
- * `memory_search` / `kb_search` 承担。返回 undefined 表示无情境可注入。
57521
+ * 情境块(近期活动 + 工作记忆键),始终注入;更深的跨域召回由 Agent 按场景提示
57522
+ * 主动调 `memory_search` / `kb_search` 承担。返回 undefined 表示无可注入内容。
56748
57523
  */
56749
- async prepareCognitiveContext(_scenario, _message, _sender) {
56750
- if (!this.cognitiveConfig?.enabled)
56751
- return void 0;
57524
+ buildCognitiveContext() {
56752
57525
  const parts = [];
56753
57526
  const activity = this.recentActivityRing.slice(-3);
56754
57527
  if (activity.length > 0) {
@@ -56758,13 +57531,7 @@ _[truncated \u2014 full text in NOTEBOOK.md]
56758
57531
  const keys2 = [...this.workingMemory.keys()].slice(0, 8).join(", ");
56759
57532
  parts.push(`Working memory: ${this.workingMemory.size} entries (${keys2})`);
56760
57533
  }
56761
- if (parts.length === 0)
56762
- return void 0;
56763
- return {
56764
- depth: CognitiveDepth.D1_Reactive,
56765
- cognitiveContext: parts.join("\n"),
56766
- isEmpty: false
56767
- };
57534
+ return parts.length > 0 ? parts.join("\n") : void 0;
56768
57535
  }
56769
57536
  getMailboxContext() {
56770
57537
  const mind = this.attentionController.getMindState();
@@ -57337,7 +58104,7 @@ ${report}`);
57337
58104
  const userContent = await this.buildUserContent(userMessage, options?.images, options?.fileNames, options?.imagePaths);
57338
58105
  this.memory.appendMessage(sessionId, { role: "user", content: userContent });
57339
58106
  await this.activateTokenCounterForModel();
57340
- const cognitiveContext = await this.prepareCognitiveContext(scenario, effectiveMessage, senderId);
58107
+ const cognitiveContext = this.buildCognitiveContext();
57341
58108
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
57342
58109
  agentId: this.id,
57343
58110
  agentName: this.config.name,
@@ -57952,7 +58719,7 @@ ${chatYield.item.payload.content}`;
57952
58719
  const userContent = await this.buildUserContent(userMessage, images, fileNames, imagePaths);
57953
58720
  this.memory.appendMessage(this.currentSessionId, { role: "user", content: userContent });
57954
58721
  await this.activateTokenCounterForModel();
57955
- const cognitiveContext = await this.prepareCognitiveContext("chat", effectiveMessage, senderId);
58722
+ const cognitiveContext = this.buildCognitiveContext();
57956
58723
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
57957
58724
  agentId: this.id,
57958
58725
  agentName: this.config.name,
@@ -58371,7 +59138,7 @@ ${streamYield.item.payload.content}`;
58371
59138
  if (streamChatActivityId)
58372
59139
  this.endActivity(streamChatActivityId, { success: false });
58373
59140
  this.transitionStatus({ to: "idle" });
58374
- return truncated + COMPLETION_MARKER;
59141
+ return truncated;
58375
59142
  }
58376
59143
  if (streamChatActivityId)
58377
59144
  this.endActivity(streamChatActivityId, { success: !cancelToken?.userStopped });
@@ -58571,7 +59338,7 @@ ${streamYield.item.payload.content}`;
58571
59338
  this.memory.appendMessage(sessionId, { role: "user", content: taskPrompt });
58572
59339
  }
58573
59340
  await this.activateTokenCounterForModel();
58574
- const cognitiveContext = await this.prepareCognitiveContext("task_execution", taskPrompt);
59341
+ const cognitiveContext = this.buildCognitiveContext();
58575
59342
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
58576
59343
  agentId: this.id,
58577
59344
  agentName: this.config.name,
@@ -59042,7 +59809,7 @@ ${yieldResult.item.payload.content}`
59042
59809
  const emitDelta = markerDeltaRIS.emit;
59043
59810
  this.memory.getOrCreateSession(this.id, sessionId);
59044
59811
  this.memory.appendMessage(sessionId, { role: "user", content: userMessage });
59045
- const cognitiveContext = await this.prepareCognitiveContext("chat", userMessage);
59812
+ const cognitiveContext = this.buildCognitiveContext();
59046
59813
  const systemPromptBuild = await this.contextEngine.buildSystemPrompt({
59047
59814
  agentId: this.id,
59048
59815
  agentName: this.config.name,
@@ -60480,7 +61247,20 @@ ${d.text}
60480
61247
  }
60481
61248
  return await this.executeToolInternal(toolCall, onOutput, sessionId);
60482
61249
  }
61250
+ /**
61251
+ * Tool-boundary entry point. Every tool invocation funnels through here (write-locked
61252
+ * or not), which makes it the single place that can honour a per-call output cap
61253
+ * (`max_output_chars`) exactly once, whichever loop drove the call.
61254
+ *
61255
+ * The cap is enforced LOSSLESSLY: hitting it delegates to `offloadLargeResult`, which
61256
+ * writes the complete output to a file and returns a capped preview plus that path.
61257
+ */
60483
61258
  async executeToolInternal(toolCall, onOutput, sessionId) {
61259
+ const raw = await this.runTool(toolCall, onOutput, sessionId);
61260
+ const cap = _Agent.readMaxOutputChars(toolCall.arguments);
61261
+ return cap ? this.offloadLargeResult(toolCall.name, raw, cap) : raw;
61262
+ }
61263
+ async runTool(toolCall, onOutput, sessionId) {
60484
61264
  if (toolCall.name === "end_turn") {
60485
61265
  this.endTurnRequested = true;
60486
61266
  this.endTurnCount++;
@@ -61348,14 +62128,14 @@ ${todayLog.slice(0, HEARTBEAT_DAILY_LOG_CHARS)}
61348
62128
  try {
61349
62129
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
61350
62130
  const entries2 = this.memory.getObservations();
62131
+ const health = this.memory.getMemoryHealth();
61351
62132
  const dreamKey = entries2.length > 500 ? `${today}_${Math.floor(Date.now() / (6 * 36e5))}` : today;
61352
- if (entries2.length >= 50 && this.lastDreamDate !== dreamKey) {
62133
+ if (shouldRunDreamCycle({ observationPercent: health.observationPercent, entryCount: entries2.length }) && this.lastDreamDate !== dreamKey) {
61353
62134
  this.lastDreamDate = dreamKey;
61354
62135
  await _Agent.acquireDreamSlot();
61355
62136
  try {
61356
62137
  await this.resourceLocks.withLock(memoryResourceLock("knowledge"), async () => {
61357
62138
  await this.dreamConsolidateMemory(entries2);
61358
- this.pruneMemoryMd();
61359
62139
  this.memory.markConsolidated?.();
61360
62140
  });
61361
62141
  } finally {
@@ -61543,117 +62323,6 @@ ${promo.content}` : promo.content;
61543
62323
  log20.warn("Dream cycle failed", { agentId: this.id, error: String(error) });
61544
62324
  }
61545
62325
  }
61546
- /**
61547
- * Enforce knowledge.md hygiene: remove daily-report sections (they belong in
61548
- * daily-logs/), strip leaked LLM <think> blocks, and enforce section/total
61549
- * size limits via heuristic compression. Preserves ## _observations.
61550
- */
61551
- pruneMemoryMd() {
61552
- const content = this.memory.getLongTermMemory();
61553
- if (!content)
61554
- return;
61555
- const lines = content.split("\n");
61556
- const afterSectionPrune = [];
61557
- let inDailyReport = false;
61558
- for (const line of lines) {
61559
- if (line.startsWith("## daily-report-")) {
61560
- inDailyReport = true;
61561
- continue;
61562
- }
61563
- if (inDailyReport && line.startsWith("## ")) {
61564
- inDailyReport = false;
61565
- }
61566
- if (!inDailyReport)
61567
- afterSectionPrune.push(line);
61568
- }
61569
- const sections = [];
61570
- let currentHeading = "";
61571
- let currentBody = [];
61572
- let sectionStart = 0;
61573
- for (let i = 0; i <= afterSectionPrune.length; i++) {
61574
- const line = i < afterSectionPrune.length ? afterSectionPrune[i] : void 0;
61575
- const isHeading = line !== void 0 && /^#{1,3}\s/.test(line);
61576
- if (isHeading || line === void 0) {
61577
- if (currentHeading || currentBody.length > 0) {
61578
- sections.push({
61579
- heading: currentHeading,
61580
- body: currentBody.join("\n").trim(),
61581
- startIdx: sectionStart
61582
- });
61583
- }
61584
- currentHeading = line ?? "";
61585
- currentBody = [];
61586
- sectionStart = i;
61587
- } else {
61588
- currentBody.push(line);
61589
- }
61590
- }
61591
- const headingLastIdx = /* @__PURE__ */ new Map();
61592
- const normalizeHeading = (h) => h.replace(/^#+\s*/, "").trim().toLowerCase();
61593
- for (let i = 0; i < sections.length; i++) {
61594
- const key2 = normalizeHeading(sections[i].heading);
61595
- if (key2)
61596
- headingLastIdx.set(key2, i);
61597
- }
61598
- const deduped = [];
61599
- for (let i = 0; i < sections.length; i++) {
61600
- const s2 = sections[i];
61601
- const key2 = normalizeHeading(s2.heading);
61602
- if (key2 && headingLastIdx.get(key2) !== i && headingLastIdx.has(key2)) {
61603
- continue;
61604
- }
61605
- deduped.push(s2);
61606
- }
61607
- afterSectionPrune.length = 0;
61608
- for (const s2 of deduped) {
61609
- if (s2.heading)
61610
- afterSectionPrune.push(s2.heading);
61611
- if (s2.body)
61612
- afterSectionPrune.push(s2.body);
61613
- afterSectionPrune.push("");
61614
- }
61615
- const outputLines = [];
61616
- let inThinkBlock = false;
61617
- for (const line of afterSectionPrune) {
61618
- if (line.trim() === "<think>") {
61619
- inThinkBlock = true;
61620
- continue;
61621
- }
61622
- if (inThinkBlock && line.trim() === "</think>") {
61623
- inThinkBlock = false;
61624
- continue;
61625
- }
61626
- if (!inThinkBlock)
61627
- outputLines.push(line);
61628
- }
61629
- const pruned = outputLines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
61630
- if (pruned !== content.trim()) {
61631
- const knowledgeMdPath = join12(this.dataDir, "knowledge.md");
61632
- let obsTail = "";
61633
- try {
61634
- if (existsSync19(knowledgeMdPath)) {
61635
- const existing = readFileSync13(knowledgeMdPath, "utf-8");
61636
- const obsStart = existing.indexOf("\n## _observations");
61637
- if (obsStart >= 0)
61638
- obsTail = existing.slice(obsStart);
61639
- else if (existing.startsWith("## _observations"))
61640
- obsTail = "\n" + existing;
61641
- }
61642
- } catch {
61643
- }
61644
- writeFileSync13(knowledgeMdPath, pruned + (obsTail ? "\n" + obsTail.replace(/^\n+/, "") : "") + "\n");
61645
- log20.info("Pruned knowledge.md: removed daily-report sections and LLM artifacts", { agentId: this.id });
61646
- }
61647
- const compressed = this.memory.compressLongTermMemory();
61648
- if (compressed.truncatedChunks > 0) {
61649
- log20.info("Compressed knowledge.md during Dream Cycle", {
61650
- agentId: this.id,
61651
- charsBefore: compressed.charsBefore,
61652
- charsAfter: compressed.charsAfter,
61653
- sectionsTrimmed: compressed.truncatedChunks
61654
- });
61655
- }
61656
- }
61657
62326
  };
61658
62327
  }
61659
62328
  });
@@ -132025,7 +132694,7 @@ var require_buffers = __commonJS({
132025
132694
  // ../../node_modules/.pnpm/binary@0.3.0/node_modules/binary/lib/vars.js
132026
132695
  var require_vars = __commonJS({
132027
132696
  "../../node_modules/.pnpm/binary@0.3.0/node_modules/binary/lib/vars.js"(exports2, module2) {
132028
- module2.exports = function(store) {
132697
+ module2.exports = function(store2) {
132029
132698
  function getset(name, value) {
132030
132699
  var node = vars.store;
132031
132700
  var keys2 = name.split(".");
@@ -132047,7 +132716,7 @@ var require_vars = __commonJS({
132047
132716
  set: function(name, value) {
132048
132717
  return getset(name, value);
132049
132718
  },
132050
- store: store || {}
132719
+ store: store2 || {}
132051
132720
  };
132052
132721
  return vars;
132053
132722
  };
@@ -192480,12 +193149,12 @@ var require_fontkit_umd = __commonJS({
192480
193149
  (_codePoints = codePoints).unshift.apply(_codePoints, this.glyphs[componentGlyph].codePoints);
192481
193150
  var action = actions.getItem(actionIndex++);
192482
193151
  last = !!(action & LAST_MASK);
192483
- var store = !!(action & STORE_MASK);
193152
+ var store2 = !!(action & STORE_MASK);
192484
193153
  var offset2 = (action & OFFSET_MASK) << 2 >> 2;
192485
193154
  offset2 += this.glyphs[componentGlyph].id;
192486
193155
  var component = components.getItem(offset2);
192487
193156
  ligatureIndex += component;
192488
- if (last || store) {
193157
+ if (last || store2) {
192489
193158
  var ligatureEntry = ligatureList.getItem(ligatureIndex);
192490
193159
  this.glyphs[componentGlyph] = this.font.getGlyph(ligatureEntry, codePoints);
192491
193160
  ligatureGlyphs.push(componentGlyph);
@@ -203019,15 +203688,24 @@ function createMemoryTools(ctx) {
203019
203688
  content,
203020
203689
  metadata: tagArray?.length ? { tags: tagArray } : void 0
203021
203690
  };
203022
- ctx.memory.addEntry(entry);
203691
+ const wrote = ctx.memory.addEntry(entry);
203692
+ if (wrote && wrote.ok === false) {
203693
+ return JSON.stringify({
203694
+ status: "error",
203695
+ ok: false,
203696
+ id: entry.id,
203697
+ error: wrote.reason ?? "memory write refused",
203698
+ store: storeName(ctx.memory)
203699
+ });
203700
+ }
203023
203701
  if (ctx.semanticSearch?.isEnabled()) {
203024
203702
  ctx.semanticSearch.indexMemory(entry, ctx.agentId).catch((err) => {
203025
203703
  log27.warn("Failed to index memory for semantic search", { error: String(err) });
203026
203704
  });
203027
203705
  }
203028
- const store = storeName(ctx.memory);
203029
- log27.info("Agent saved memory", { agentId: ctx.agentId, type, contentLen: content.length, store });
203030
- return JSON.stringify({ status: "saved", id: entry.id, type, store });
203706
+ const store2 = storeName(ctx.memory);
203707
+ log27.info("Agent saved memory", { agentId: ctx.agentId, type, contentLen: content.length, store: store2 });
203708
+ return JSON.stringify({ status: "saved", id: entry.id, type, store: store2 });
203031
203709
  }
203032
203710
  },
203033
203711
  {
@@ -203055,7 +203733,7 @@ function createMemoryTools(ctx) {
203055
203733
  const query2 = args["query"] ?? "";
203056
203734
  const type = args["type"];
203057
203735
  const limit = args["limit"] ?? 10;
203058
- const store = storeName(ctx.memory);
203736
+ const store2 = storeName(ctx.memory);
203059
203737
  if (!query2.trim()) {
203060
203738
  const entries2 = ctx.memory.getEntries(type ?? void 0, limit);
203061
203739
  return JSON.stringify({
@@ -203067,7 +203745,7 @@ function createMemoryTools(ctx) {
203067
203745
  tags: e.metadata?.tags
203068
203746
  })),
203069
203747
  count: entries2.length,
203070
- store
203748
+ store: store2
203071
203749
  });
203072
203750
  }
203073
203751
  let keywordResults = ctx.memory.search(query2);
@@ -203104,7 +203782,7 @@ function createMemoryTools(ctx) {
203104
203782
  })),
203105
203783
  count: merged.length,
203106
203784
  searchMethod: extras.length > 0 ? "semantic+keyword" : "semantic",
203107
- store
203785
+ store: store2
203108
203786
  });
203109
203787
  }
203110
203788
  log27.info("Semantic search returned 0 results, using keyword search", {
@@ -203128,13 +203806,13 @@ function createMemoryTools(ctx) {
203128
203806
  })),
203129
203807
  count: results.length,
203130
203808
  searchMethod: "keyword",
203131
- store
203809
+ store: store2
203132
203810
  });
203133
203811
  }
203134
203812
  },
203135
203813
  {
203136
203814
  name: "memory_update",
203137
- 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.',
203815
+ 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.',
203138
203816
  inputSchema: {
203139
203817
  type: "object",
203140
203818
  properties: {
@@ -203164,10 +203842,27 @@ function createMemoryTools(ctx) {
203164
203842
  const content = args["content"] ?? "";
203165
203843
  const mode = normalizeWriteMode(args["mode"]);
203166
203844
  const ids = args["ids"];
203167
- const store = storeName(ctx.memory);
203845
+ const store2 = storeName(ctx.memory);
203846
+ if (section3 === "_preamble") {
203847
+ if (mode === "forget" || mode === "delete") {
203848
+ const r = ctx.memory.removeLongTermPreamble?.();
203849
+ if (!r)
203850
+ return JSON.stringify({ status: "error", error: "this store does not support preamble removal", store: store2 });
203851
+ if (!r.ok)
203852
+ return JSON.stringify({ status: "error", error: "preamble removal refused", store: store2 });
203853
+ log27.info("Agent cleared the curated preamble", { agentId: ctx.agentId, removedChars: r.removedChars });
203854
+ return JSON.stringify({ status: "forgotten", section: "_preamble", removedChars: r.removedChars, store: store2 });
203855
+ }
203856
+ const w = ctx.memory.setLongTermPreamble?.(content);
203857
+ if (!w)
203858
+ return JSON.stringify({ status: "error", error: "this store does not support a preamble", store: store2 });
203859
+ if (!w.ok)
203860
+ return JSON.stringify({ status: "error", error: w.reason ?? "preamble write refused", section: section3, store: store2 });
203861
+ return JSON.stringify({ status: "updated", section: "_preamble", mode, store: store2 });
203862
+ }
203168
203863
  if (mode === "delete") {
203169
203864
  if (!ids?.length) {
203170
- return JSON.stringify({ status: "error", error: "Provide ids to delete.", store });
203865
+ return JSON.stringify({ status: "error", error: "Provide ids to delete.", store: store2 });
203171
203866
  }
203172
203867
  const capped = ids.slice(0, 20);
203173
203868
  const removed = ctx.memory.removeEntries(capped);
@@ -203179,15 +203874,15 @@ function createMemoryTools(ctx) {
203179
203874
  }
203180
203875
  }
203181
203876
  log27.info("Agent deleted memories", { agentId: ctx.agentId, removed });
203182
- return JSON.stringify({ status: "deleted", removed, store });
203877
+ return JSON.stringify({ status: "deleted", removed, store: store2 });
203183
203878
  }
203184
203879
  if (mode === "forget") {
203185
203880
  if (!section3?.trim()) {
203186
- return JSON.stringify({ status: "error", error: "Provide the section name to forget.", store });
203881
+ return JSON.stringify({ status: "error", error: "Provide the section name to forget.", store: store2 });
203187
203882
  }
203188
203883
  const result = ctx.memory.removeLongTermSection(section3);
203189
203884
  if (!result.ok) {
203190
- return JSON.stringify({ status: "error", error: result.reason ?? "Failed to forget section.", store });
203885
+ return JSON.stringify({ status: "error", error: result.reason ?? "Failed to forget section.", store: store2 });
203191
203886
  }
203192
203887
  log27.info("Agent forgot a curated section", {
203193
203888
  agentId: ctx.agentId,
@@ -203198,12 +203893,12 @@ function createMemoryTools(ctx) {
203198
203893
  status: "forgotten",
203199
203894
  section: section3,
203200
203895
  removedChars: result.removedChars,
203201
- reason: `Section "${section3}" removed from ${store}.`,
203202
- store
203896
+ reason: `Section "${section3}" removed from ${store2}.`,
203897
+ store: store2
203203
203898
  });
203204
203899
  }
203205
203900
  if (!section3?.trim()) {
203206
- return JSON.stringify({ status: "error", error: "section is required", store });
203901
+ return JSON.stringify({ status: "error", error: "section is required", store: store2 });
203207
203902
  }
203208
203903
  let writeResult;
203209
203904
  if (mode === "patch") {
@@ -203216,10 +203911,10 @@ ${content}` : content;
203216
203911
  }
203217
203912
  if (!writeResult.ok) {
203218
203913
  log27.warn("Agent long-term memory write refused", { agentId: ctx.agentId, section: section3, mode, reason: writeResult.reason });
203219
- return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store });
203914
+ return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store: store2 });
203220
203915
  }
203221
- log27.info("Agent updated long-term memory", { agentId: ctx.agentId, section: section3, mode, contentLen: content.length, store });
203222
- return JSON.stringify({ status: "updated", section: section3, mode, store });
203916
+ log27.info("Agent updated long-term memory", { agentId: ctx.agentId, section: section3, mode, contentLen: content.length, store: store2 });
203917
+ return JSON.stringify({ status: "updated", section: section3, mode, store: store2 });
203223
203918
  }
203224
203919
  },
203225
203920
  // Backward compatibility aliases
@@ -203262,16 +203957,16 @@ ${content}` : content;
203262
203957
  async execute(args) {
203263
203958
  const ids = args["ids"];
203264
203959
  const tag = args["tag"];
203265
- const store = storeName(ctx.memory);
203960
+ const store2 = storeName(ctx.memory);
203266
203961
  if (!ids?.length && !tag)
203267
- return JSON.stringify({ status: "error", error: "Provide ids or tag.", store });
203962
+ return JSON.stringify({ status: "error", error: "Provide ids or tag.", store: store2 });
203268
203963
  let removed = 0;
203269
203964
  if (ids?.length) {
203270
203965
  removed = ctx.memory.removeEntries(ids.slice(0, 20));
203271
203966
  } else if (tag) {
203272
203967
  removed = ctx.memory.removeEntriesByTag(tag);
203273
203968
  }
203274
- return JSON.stringify({ status: "deleted", removed, store });
203969
+ return JSON.stringify({ status: "deleted", removed, store: store2 });
203275
203970
  }
203276
203971
  },
203277
203972
  {
@@ -203290,7 +203985,7 @@ ${content}` : content;
203290
203985
  const section3 = args["section"];
203291
203986
  const content = args["content"];
203292
203987
  const mode = normalizeWriteMode(args["mode"]);
203293
- const store = storeName(ctx.memory);
203988
+ const store2 = storeName(ctx.memory);
203294
203989
  let writeResult;
203295
203990
  if (mode === "patch") {
203296
203991
  const existing = ctx.memory.getLongTermSection(section3);
@@ -203300,17 +203995,17 @@ ${content}` : content);
203300
203995
  writeResult = ctx.memory.addLongTermMemory(section3, content);
203301
203996
  }
203302
203997
  if (!writeResult.ok) {
203303
- return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store });
203998
+ return JSON.stringify({ status: "error", ok: false, error: writeResult.reason ?? "knowledge.md write refused", section: section3, mode, store: store2 });
203304
203999
  }
203305
- return JSON.stringify({ status: "updated", section: section3, mode, store });
204000
+ return JSON.stringify({ status: "updated", section: section3, mode, store: store2 });
203306
204001
  }
203307
204002
  },
203308
204003
  {
203309
204004
  name: "memory_stats",
203310
- 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.",
204005
+ 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.",
203311
204006
  inputSchema: { type: "object", properties: {} },
203312
204007
  async execute() {
203313
- const store = storeName(ctx.memory);
204008
+ const store2 = storeName(ctx.memory);
203314
204009
  const health = ctx.memory.getMemoryHealth();
203315
204010
  const curated = ctx.memory.getLongTermMemory();
203316
204011
  const obs = ctx.memory.getObservations();
@@ -203318,17 +204013,25 @@ ${content}` : content);
203318
204013
  const obsChars = obs.reduce((s2, e) => s2 + (e.content?.length ?? 0), 0);
203319
204014
  return JSON.stringify({
203320
204015
  status: "ok",
203321
- store,
204016
+ store: store2,
204017
+ // The injected budget — the one that actually costs prompt space.
203322
204018
  budget: {
203323
- totalChars: health.totalChars,
203324
- limit: health.cap,
204019
+ curatedChars: health.curatedChars,
204020
+ limit: health.curatedCap,
203325
204021
  usedPercent: health.percent
203326
204022
  },
204023
+ // A separate, non-injected budget (searched on demand).
204024
+ observationBuffer: {
204025
+ chars: health.observationChars,
204026
+ limit: health.observationCap,
204027
+ usedPercent: health.observationPercent
204028
+ },
203327
204029
  observations: { count: obs.length, chars: obsChars },
203328
204030
  curatedSections: { count: sectionNames.length, names: sectionNames.slice(0, 20) },
203329
204031
  archivedChars: health.archiveChars,
203330
204032
  lastConsolidatedAt: health.lastConsolidatedAt,
203331
- 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
204033
+ 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,
204034
+ 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
203332
204035
  });
203333
204036
  }
203334
204037
  },
@@ -203359,16 +204062,16 @@ ${content}` : content);
203359
204062
  required: ["target_section"]
203360
204063
  },
203361
204064
  async execute(args) {
203362
- const store = storeName(ctx.memory);
204065
+ const store2 = storeName(ctx.memory);
203363
204066
  const target = String(args["target_section"] ?? "").trim();
203364
204067
  if (!target) {
203365
- return JSON.stringify({ status: "error", error: "target_section is required.", store });
204068
+ return JSON.stringify({ status: "error", error: "target_section is required.", store: store2 });
203366
204069
  }
203367
204070
  if (/^_observations$/i.test(target)) {
203368
204071
  return JSON.stringify({
203369
204072
  status: "error",
203370
204073
  error: 'The `_observations` buffer is not a curated section \u2014 merge INTO a named section (e.g. "procedures").',
203371
- store
204074
+ store: store2
203372
204075
  });
203373
204076
  }
203374
204077
  const query2 = String(args["query"] ?? "").trim().toLowerCase();
@@ -203390,7 +204093,7 @@ ${content}` : content);
203390
204093
  archived: 0,
203391
204094
  section: target,
203392
204095
  message: "No matching observations found.",
203393
- store
204096
+ store: store2
203394
204097
  });
203395
204098
  }
203396
204099
  const selected = matches2.slice(-limit);
@@ -203410,7 +204113,7 @@ ${newLines.join("\n")}` : newLines.join("\n");
203410
204113
  error: writeResult.reason ?? "knowledge.md write refused",
203411
204114
  moved: 0,
203412
204115
  section: target,
203413
- store
204116
+ store: store2
203414
204117
  });
203415
204118
  }
203416
204119
  const archived = ctx.memory.removeEntries(selected.map((e) => e.id));
@@ -203434,7 +204137,7 @@ ${newLines.join("\n")}` : newLines.join("\n");
203434
204137
  archived,
203435
204138
  section: target,
203436
204139
  message: `Merged ${selected.length} observation(s) into "${target}" and archived them.`,
203437
- store
204140
+ store: store2
203438
204141
  });
203439
204142
  }
203440
204143
  }
@@ -207525,6 +208228,41 @@ var init_semantic_search = __esm({
207525
208228
  }
207526
208229
  });
207527
208230
 
208231
+ // ../core/dist/skill-warnings.js
208232
+ function resolveMissingSkills(config, registry) {
208233
+ const assigned = config?.skills ?? [];
208234
+ if (assigned.length === 0)
208235
+ return [];
208236
+ if (!registry)
208237
+ return [...assigned];
208238
+ return assigned.filter((name) => !registry.get(name));
208239
+ }
208240
+ function buildSkillWarnings(config, registry) {
208241
+ const missing = resolveMissingSkills(config, registry);
208242
+ const available = registry ? registry.list().map((s2) => s2.name).slice(0, SKILL_WARNINGS_AVAILABLE_LIMIT) : [];
208243
+ return { missing, available };
208244
+ }
208245
+ function setAgentSkillWarnings(agent, warnings) {
208246
+ store.set(agent, {
208247
+ missing: [...warnings.missing],
208248
+ available: [...warnings.available]
208249
+ });
208250
+ }
208251
+ function getAgentSkillWarnings(agent) {
208252
+ const stored = store.get(agent);
208253
+ if (!stored)
208254
+ return void 0;
208255
+ return { missing: [...stored.missing], available: [...stored.available] };
208256
+ }
208257
+ var SKILL_WARNINGS_AVAILABLE_LIMIT, store;
208258
+ var init_skill_warnings = __esm({
208259
+ "../core/dist/skill-warnings.js"() {
208260
+ "use strict";
208261
+ SKILL_WARNINGS_AVAILABLE_LIMIT = 50;
208262
+ store = /* @__PURE__ */ new WeakMap();
208263
+ }
208264
+ });
208265
+
207528
208266
  // ../core/dist/tools/chrome-dialog-clicker.js
207529
208267
  import { execFile as execFile3, spawn as spawn5 } from "node:child_process";
207530
208268
  import { platform as platform6, homedir as homedir8 } from "node:os";
@@ -210411,6 +211149,7 @@ var init_agent_manager = __esm({
210411
211149
  init_recall();
210412
211150
  init_session();
210413
211151
  init_semantic_search();
211152
+ init_skill_warnings();
210414
211153
  init_chrome_dialog_clicker();
210415
211154
  init_markus_browser_bridge();
210416
211155
  init_markus_browser_mcp();
@@ -210500,7 +211239,6 @@ var init_agent_manager = __esm({
210500
211239
  recallCallbacks;
210501
211240
  delegationManager;
210502
211241
  _maxToolIterations = Infinity;
210503
- _cognitiveConfig;
210504
211242
  _concurrentConfig;
210505
211243
  _codingToolsEnabled = false;
210506
211244
  _codingToolsConfigs;
@@ -210693,12 +211431,6 @@ Priority: ${delegation.priority}`, envelope.from, { name: envelope.from, role: "
210693
211431
  set maxToolIterations(value) {
210694
211432
  this._maxToolIterations = value <= 0 ? Infinity : value;
210695
211433
  }
210696
- get cognitiveConfig() {
210697
- return this._cognitiveConfig;
210698
- }
210699
- set cognitiveConfig(value) {
210700
- this._cognitiveConfig = value;
210701
- }
210702
211434
  get concurrentConfig() {
210703
211435
  return this._concurrentConfig;
210704
211436
  }
@@ -211303,7 +212035,6 @@ You are ${request.name}.`,
211303
212035
  pathPolicy,
211304
212036
  skillRegistry: this.skillRegistry,
211305
212037
  maxToolIterations: this._maxToolIterations,
211306
- cognitive: this._cognitiveConfig,
211307
212038
  handbookPath: this.resolveHandbookPath(roleName)
211308
212039
  };
211309
212040
  const agent = new Agent(agentOpts);
@@ -211342,14 +212073,15 @@ You are ${request.name}.`,
211342
212073
  if (this.skillRegistry) {
211343
212074
  agent.setAvailableSkillCatalog(this.skillRegistry.getSkillCatalog());
211344
212075
  }
212076
+ const skillWarnings = buildSkillWarnings(config, this.skillRegistry);
212077
+ setAgentSkillWarnings(agent, skillWarnings);
212078
+ if (skillWarnings.missing.length > 0) {
212079
+ log53.debug(`Agent ${config.name} (${id}) references skills not found in registry`, {
212080
+ missing: skillWarnings.missing,
212081
+ available: skillWarnings.available
212082
+ });
212083
+ }
211345
212084
  if (this.skillRegistry && config.skills.length > 0) {
211346
- const missingSkills = config.skills.filter((s2) => !this.skillRegistry.get(s2));
211347
- if (missingSkills.length > 0) {
211348
- log53.warn(`Agent ${config.name} (${id}) references skills not found in registry`, {
211349
- missing: missingSkills,
211350
- available: this.skillRegistry.list().map((s2) => s2.name)
211351
- });
211352
- }
211353
212085
  for (const skillName of config.skills) {
211354
212086
  const skill = this.skillRegistry.get(skillName);
211355
212087
  if (skill?.manifest.mcpServers) {
@@ -212117,20 +212849,20 @@ You are ${row.name}.`,
212117
212849
  restoredState: { tokensUsedToday: row.tokensUsedToday ?? 0 },
212118
212850
  skillRegistry: this.skillRegistry,
212119
212851
  maxToolIterations: this._maxToolIterations,
212120
- cognitive: this._cognitiveConfig,
212121
212852
  handbookPath: this.resolveHandbookPath(row.roleId ?? row.roleName)
212122
212853
  });
212123
212854
  if (this.skillRegistry) {
212124
212855
  agent.setAvailableSkillCatalog(this.skillRegistry.getSkillCatalog());
212125
212856
  }
212857
+ const skillWarnings = buildSkillWarnings(config, this.skillRegistry);
212858
+ setAgentSkillWarnings(agent, skillWarnings);
212859
+ if (skillWarnings.missing.length > 0) {
212860
+ log53.debug(`Restored agent ${config.name} (${id}) references skills not found in registry`, {
212861
+ missing: skillWarnings.missing,
212862
+ available: skillWarnings.available
212863
+ });
212864
+ }
212126
212865
  if (this.skillRegistry && config.skills.length > 0) {
212127
- const missingSkills = config.skills.filter((s2) => !this.skillRegistry.get(s2));
212128
- if (missingSkills.length > 0) {
212129
- log53.warn(`Restored agent ${config.name} (${id}) references skills not found in registry`, {
212130
- missing: missingSkills,
212131
- available: this.skillRegistry.list().map((s2) => s2.name)
212132
- });
212133
- }
212134
212866
  const mcpConnections = [];
212135
212867
  for (const skillName of config.skills) {
212136
212868
  const skill = this.skillRegistry.get(skillName);
@@ -222362,8 +223094,8 @@ var init_external_gateway = __esm({
222362
223094
  setTasksFetcher(fetcher) {
222363
223095
  this.tasksFetcher = fetcher;
222364
223096
  }
222365
- setStore(store) {
222366
- this.store = store;
223097
+ setStore(store2) {
223098
+ this.store = store2;
222367
223099
  }
222368
223100
  /** Load persisted registrations from the store into memory. Call once at startup. */
222369
223101
  async loadFromStore(agentExists) {
@@ -226806,6 +227538,7 @@ __export(dist_exports3, {
226806
227538
  ReviewService: () => ReviewService,
226807
227539
  RoleLoader: () => RoleLoader,
226808
227540
  SCENARIO_ALLOWED_TOOLS: () => SCENARIO_ALLOWED_TOOLS,
227541
+ SKILL_WARNINGS_AVAILABLE_LIMIT: () => SKILL_WARNINGS_AVAILABLE_LIMIT,
226809
227542
  SUPPORTED_EXTERNAL_FORMATS: () => SUPPORTED_EXTERNAL_FORMATS,
226810
227543
  SecurityGuard: () => SecurityGuard,
226811
227544
  SemanticMemorySearch: () => SemanticMemorySearch,
@@ -226831,6 +227564,7 @@ __export(dist_exports3, {
226831
227564
  buildDistillationPrompt: () => buildDistillationPrompt,
226832
227565
  buildModelsAuthHeaders: () => buildModelsAuthHeaders,
226833
227566
  buildModelsEndpoint: () => buildModelsEndpoint,
227567
+ buildSkillWarnings: () => buildSkillWarnings,
226834
227568
  buildTaskContextPackage: () => buildTaskContextPackage,
226835
227569
  checkAutoClickStatus: () => checkAutoClickStatus,
226836
227570
  clearEnvironmentCache: () => clearEnvironmentCache,
@@ -226894,6 +227628,7 @@ __export(dist_exports3, {
226894
227628
  generateHandbook: () => generateHandbook,
226895
227629
  generateIdempotencyKey: () => generateIdempotencyKey,
226896
227630
  getAdapter: () => getAdapter,
227631
+ getAgentSkillWarnings: () => getAgentSkillWarnings,
226897
227632
  getAllAdapters: () => getAllAdapters,
226898
227633
  getAvailableProfiles: () => getAvailableProfiles,
226899
227634
  getBridgeToolDescriptors: () => getBridgeToolDescriptors,
@@ -226937,11 +227672,13 @@ __export(dist_exports3, {
226937
227672
  resetMarkitdownCache: () => resetMarkitdownCache,
226938
227673
  resolveMarkusRoute: () => resolveMarkusRoute,
226939
227674
  resolveMarkusSearchProvider: () => resolveMarkusSearchProvider,
227675
+ resolveMissingSkills: () => resolveMissingSkills,
226940
227676
  runSubagentLoop: () => runSubagentLoop,
226941
227677
  saveNotebook: () => saveNotebook,
226942
227678
  scenarioToPack: () => scenarioToPack,
226943
227679
  sensitiveDataGuardrail: () => sensitiveDataGuardrail,
226944
227680
  serializeNotebook: () => serializeNotebook,
227681
+ setAgentSkillWarnings: () => setAgentSkillWarnings,
226945
227682
  setTracingProvider: () => setTracingProvider,
226946
227683
  shouldDistillTask: () => shouldDistillTask,
226947
227684
  shouldEnterDeepSleep: () => shouldEnterDeepSleep,
@@ -226959,6 +227696,7 @@ var init_dist7 = __esm({
226959
227696
  init_tracing();
226960
227697
  init_agent_manager();
226961
227698
  init_role_loader();
227699
+ init_skill_warnings();
226962
227700
  init_heartbeat();
226963
227701
  init_context_engine();
226964
227702
  init_token_counter();
@@ -227792,6 +228530,23 @@ var init_org_service = __esm({
227792
228530
  const results = await Promise.all(restorePromises);
227793
228531
  const restoredCount = results.filter(Boolean).length;
227794
228532
  log73.info(`Restored ${restoredCount} agents from DB`);
228533
+ try {
228534
+ const affected = [];
228535
+ for (const row of toRestore) {
228536
+ try {
228537
+ const inst = this.agentManager.getAgent(row.id);
228538
+ const w = getAgentSkillWarnings(inst);
228539
+ if (w && w.missing.length > 0)
228540
+ affected.push({ name: row.name, missing: w.missing });
228541
+ } catch {
228542
+ }
228543
+ }
228544
+ if (affected.length > 0) {
228545
+ 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 });
228546
+ }
228547
+ } catch (summaryErr) {
228548
+ log73.warn("Failed to summarize missing-skill warnings after restore", { error: String(summaryErr) });
228549
+ }
227795
228550
  } catch (error) {
227796
228551
  log73.warn("Failed to restore agents from DB", { error: String(error) });
227797
228552
  }
@@ -351378,7 +352133,7 @@ var init_sse_handler = __esm({
351378
352133
  const segText = this.msgSegments.filter((s2) => s2.type === "text").map((s2) => s2.content).join("");
351379
352134
  persistReply = segText || "";
351380
352135
  }
351381
- persistReply = stripCompletionMarkerLeak(persistReply).trim() || persistReply;
352136
+ persistReply = stripLegacyCompletionToken(persistReply).trim() || persistReply;
351382
352137
  const isEmptyTerminal = !persistReply && this.msgSegments.every((s2) => s2.type !== "tool" && !(s2.type === "text" && (s2.content || s2.thinking)));
351383
352138
  const treatAsStopped = wasCancelled || isCancelledReply && isEmptyTerminal;
351384
352139
  const donePayload = {
@@ -359040,6 +359795,18 @@ ${cleanText}`,
359040
359795
  }, taskLookup, void 0, DEFAULT_CONSERVATOR_CONFIG);
359041
359796
  return { ...a, runtime: { ...runtime, stall: verdict.stall, dirty: verdict.dirty } };
359042
359797
  });
359798
+ const skillAgentManager = this.orgService.getAgentManager();
359799
+ agents = agents.map((a) => {
359800
+ try {
359801
+ const inst = skillAgentManager.getAgent(a.id);
359802
+ const w = getAgentSkillWarnings(inst);
359803
+ if (w && w.missing.length > 0) {
359804
+ return { ...a, skillWarnings: { missing: w.missing } };
359805
+ }
359806
+ } catch {
359807
+ }
359808
+ return a;
359809
+ });
359043
359810
  this.json(res, 200, { agents });
359044
359811
  return;
359045
359812
  }
@@ -360247,8 +361014,11 @@ ${userText}` : userText;
360247
361014
  const h = mem.getMemoryHealth?.();
360248
361015
  return h ? {
360249
361016
  usedPercent: h.percent,
360250
- budgetChars: h.totalChars,
360251
- budgetLimit: h.cap,
361017
+ budgetChars: h.curatedChars,
361018
+ budgetLimit: h.curatedCap,
361019
+ observationPercent: h.observationPercent,
361020
+ observationChars: h.observationChars,
361021
+ observationLimit: h.observationCap,
360252
361022
  observationCount: h.observations,
360253
361023
  curatedCount: h.curatedSections,
360254
361024
  archivedChars: h.archiveChars,
@@ -360843,6 +361613,10 @@ EXPLANATION_END`;
360843
361613
  activeTaskCount: state.activeTaskCount,
360844
361614
  activeTaskIds: state.activeTaskIds,
360845
361615
  skills: agent.getActiveSkillNames(),
361616
+ // H9: assigned skills that are not installed in the registry. Stamped on the agent
361617
+ // instance at create/restore; full shape here (missing + available catalog, capped).
361618
+ // Always present so the UI has a stable field to render the ⚠️ degradation banner.
361619
+ skillWarnings: getAgentSkillWarnings(agent) ?? { missing: [], available: [] },
360846
361620
  availableSkills: this.skillRegistry?.list().map((s2) => ({
360847
361621
  name: s2.name,
360848
361622
  description: s2.description,
@@ -362775,7 +363549,6 @@ EXPLANATION_END`;
362775
363549
  const am = this.orgService.getAgentManager();
362776
363550
  this.json(res, 200, {
362777
363551
  maxToolIterations: am.maxToolIterations,
362778
- cognitive: am.cognitiveConfig ?? { enabled: false },
362779
363552
  concurrent: am.concurrentConfig ?? { enabled: true, maxWorkers: 3 }
362780
363553
  });
362781
363554
  return;
@@ -362791,16 +363564,6 @@ EXPLANATION_END`;
362791
363564
  am.maxToolIterations = body["maxToolIterations"];
362792
363565
  changed = true;
362793
363566
  }
362794
- if (body["cognitive"] && typeof body["cognitive"] === "object") {
362795
- const cc = body["cognitive"];
362796
- am.cognitiveConfig = {
362797
- enabled: cc["enabled"] === true,
362798
- maxDepth: typeof cc["maxDepth"] === "number" ? cc["maxDepth"] : void 0,
362799
- appraisalModel: typeof cc["appraisalModel"] === "string" ? cc["appraisalModel"] : void 0,
362800
- timeoutMs: typeof cc["timeoutMs"] === "number" ? cc["timeoutMs"] : void 0
362801
- };
362802
- changed = true;
362803
- }
362804
363567
  if (body["concurrent"] && typeof body["concurrent"] === "object") {
362805
363568
  const cc = body["concurrent"];
362806
363569
  const policy = cc["conflictPolicy"];
@@ -362816,7 +363579,6 @@ EXPLANATION_END`;
362816
363579
  saveConfig({
362817
363580
  agent: {
362818
363581
  maxToolIterations: am.maxToolIterations,
362819
- cognitive: am.cognitiveConfig,
362820
363582
  concurrent: am.concurrentConfig
362821
363583
  }
362822
363584
  }, this.markusConfigPath);
@@ -362839,7 +363601,6 @@ EXPLANATION_END`;
362839
363601
  }
362840
363602
  this.json(res, 200, {
362841
363603
  maxToolIterations: am.maxToolIterations,
362842
- cognitive: am.cognitiveConfig ?? { enabled: false },
362843
363604
  concurrent: am.concurrentConfig ?? { enabled: true, maxWorkers: 3 }
362844
363605
  });
362845
363606
  return;
@@ -386620,15 +387381,6 @@ async function createServices(config) {
386620
387381
  if (config.agent?.maxToolIterations) {
386621
387382
  agentManager.maxToolIterations = config.agent.maxToolIterations;
386622
387383
  }
386623
- if (config.agent?.cognitive) {
386624
- const cc = config.agent.cognitive;
386625
- agentManager.cognitiveConfig = {
386626
- enabled: cc.enabled ?? false,
386627
- maxDepth: cc.maxDepth,
386628
- appraisalModel: cc.appraisalModel,
386629
- timeoutMs: cc.timeoutMs
386630
- };
386631
- }
386632
387384
  if (config.codingTools) {
386633
387385
  agentManager.setCodingToolsConfig(config.codingTools);
386634
387386
  }