mocode-ai 1.9.3 → 1.9.5

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.
@@ -13,7 +13,7 @@ import { formatArtifactTokenSources } from '../context/artifacts.js';
13
13
  import { getAgentMode } from '../agent/mode.js';
14
14
  import { getCurrentSessionId } from '../session/state.js';
15
15
  import { getSandboxRoot } from '../sandbox/root.js';
16
- import { planStepLabel } from '../session/notes.js';
16
+ import { planStepLabel, planStepParts } from '../session/notes.js';
17
17
  /** /context 的用量条(详情版,进内容区):只算对话内容(不含 system prompt),方便用户感知自己发了多少、agent 回复了多少。 */
18
18
  export function renderContextBar(history) {
19
19
  // 过滤掉 system 消息,只算对话内容
@@ -56,7 +56,7 @@ export function renderContextBar(history) {
56
56
  * 空对话(只有 system 提示、还没发任何消息)恒显 0% 0/window:固定 system prompt + 工具
57
57
  * schema 是每次请求的基础设施开销,不算用户占用的上下文,避免刚进 REPL 就显示十几 k。
58
58
  * 有对话后必须**用全 prompt 估算**(消息 + 工具 schema + 尾部 ephemeral 注入),与压缩触发器
59
- * evaluateBudget 的 system+history+toolOld+toolRecent 总账对齐——任何一段漏算都会让
59
+ * evaluateBudget 的 total / rawTotal 总账对齐——任何一段漏算都会让
60
60
  * bar 与触发器口径不一致、看着没到 80% 实际已经在压。
61
61
  * 触发器用 `Math.max(rawTotal, total) >= 0.8 * window`,bar 也照搬:校正后和校正前
62
62
  * 哪个大取哪个,确保不会因 correction<1 而低估。ephemeral 文本由 agent/core 每步写入
@@ -132,20 +132,40 @@ export function readPlanStatusFromNotes() {
132
132
  return null;
133
133
  const endOffset = lines.slice(start + 1).findIndex((line) => /^##\s/.test(line));
134
134
  const end = endOffset < 0 ? lines.length : start + 1 + endOffset;
135
- const section = lines.slice(start, end).join('\n').trimEnd();
135
+ const sectionLines = lines.slice(start + 1, end);
136
+ const section = [lines[start], ...sectionLines].join('\n').trimEnd();
136
137
  const title = lines[start].match(/^## Plan:\s*(.+)$/)?.[1].trim();
137
138
  if (!title)
138
139
  return null;
139
- const total = (section.match(/^\s*-\s*\[[ xX]\]\s*\d+\./gm) || []).length;
140
- const currentMatch = section.match(/^\s*-\s*\[ \]\s*(\d+)\.\s*(.+)$/m);
141
- const current = currentMatch ? planStepLabel(currentMatch[2]) : undefined;
140
+ const stepRe = /^\s*-\s*\[([ xX])\]\s*(\d+)\.\s*(.*)$/;
141
+ let total = 0;
142
+ let currentMatch = null;
143
+ const steps = [];
144
+ for (const line of sectionLines) {
145
+ const m = line.match(stepRe);
146
+ if (!m)
147
+ continue;
148
+ total++;
149
+ const done = m[1].toLowerCase() === 'x';
150
+ const isCurrent = !done && currentMatch === null;
151
+ if (isCurrent)
152
+ currentMatch = m;
153
+ steps.push({
154
+ no: Number(m[2]),
155
+ label: planStepLabel(m[3] ?? ''),
156
+ detail: planStepParts(m[3] ?? '').detail || undefined,
157
+ done,
158
+ current: isCurrent,
159
+ });
160
+ }
161
+ const current = currentMatch ? planStepLabel(currentMatch[3] ?? '') : undefined;
142
162
  // 括号进度 = 「当前执行到的步骤序号/总数」(执行第 1 步显示 1/3),与 `▸ 当前步` 后缀自洽;
143
163
  // 旧语义 done/total 会永远慢一拍(执行第 2 步显示 1/3)。全勾选时显示 total/total(通常已自动结算为 Done,chip 消失)。
144
- const activeNo = currentMatch ? Number(currentMatch[1]) : total;
164
+ const activeNo = currentMatch ? Number(currentMatch[2]) : total;
145
165
  const summary = `plan: ${title} (${activeNo}/${total})`;
146
166
  // mtime 让“相同内容被重写为一项新计划”也能重新出现,而不被旧轮次误抑制。
147
167
  const fingerprint = `${sessionId}\0${fs.statSync(p).mtimeMs}\0${section}`;
148
- return { fingerprint, summary: current ? `${summary} ▸ ${current}` : summary };
168
+ return { fingerprint, title, steps, summary: current ? `${summary} ▸ ${current}` : summary };
149
169
  }
150
170
  catch {
151
171
  return null;
@@ -155,22 +175,25 @@ export function readPlanStatusFromNotes() {
155
175
  export function settlePlanStatus() {
156
176
  settledPlanFingerprint = readPlanStatusFromNotes()?.fingerprint;
157
177
  }
158
- /** 从 notes.md 读取活跃 plan 摘要;已结算且未变化的旧 plan 不再显示。 */
178
+ /** 从 notes.md 读取活跃 plan;已结算且未变化的旧 plan 返回 null(状态栏不显示)。 */
159
179
  export function readPlanFromNotes() {
160
180
  const plan = readPlanStatusFromNotes();
161
181
  if (!plan || plan.fingerprint === settledPlanFingerprint)
162
- return '';
163
- return plan.summary;
182
+ return null;
183
+ return { summary: plan.summary, key: plan.title, steps: plan.steps };
164
184
  }
165
185
  /** 状态行基线:模型 / context / cwd / 模式标识 / 活跃 plan chip / 本轮 token。repl 在轮次边界、切模式、plan 变更时调。 */
166
186
  export function refreshStatusBase(history, lastTurnUsage) {
187
+ const plan = readPlanFromNotes();
167
188
  layout.setStatusBase({
168
189
  model: config.model,
169
190
  contextBar: renderContextBarInline(history),
170
191
  cwd: process.cwd(),
171
192
  modeTag: getAgentMode() === 'plan' ? 'Plan' : 'Auto',
172
193
  effort: getActiveEffort() === 'auto' ? undefined : getActiveEffort(),
173
- planSummary: readPlanFromNotes(),
194
+ planSummary: plan?.summary ?? '',
195
+ planKey: plan?.key,
196
+ planSteps: plan?.steps,
174
197
  lastTurnUsage,
175
198
  });
176
199
  }
@@ -52,6 +52,8 @@ const MEMORY_STATE_FILES = [
52
52
  'memory-audit.jsonl', // R8 审计日志
53
53
  'memory-health.json', // 健康快照
54
54
  'memory-recall-stats.json', // 召回统计(R0.2)
55
+ 'memory-adoption.jsonl', // R19 送达/采纳事件账本
56
+ 'memory-adoption-summary.json', // R19 过期事件聚合
55
57
  ];
56
58
  /**
57
59
  * 写入类工具试图改 `.mocode` 下的记忆状态文件时返回拒绝文案;否则 null。
@@ -1,6 +1,7 @@
1
1
  import { chat, chatTools, correctTokenEstimate, estimateMessagesTokens, estimatePromptTokens, estimateToolSchemaTokens, estimateTokens, } from '../llm/index.js';
2
2
  import { config, isMemoryEnabled } from '../config/index.js';
3
3
  import { appendPendingCandidates, extractMemoryCandidates, isCompactHandoffEnabled, memoryCandidatesInstruction, } from '../memory/pending.js';
4
+ import { adoptionEvaluationInstruction, applyAdoptionEvaluations, extractAdoptionEvaluations, } from '../memory/adoption.js';
4
5
  import { COMPACT_USER_VERBATIM_MAX_TOKENS, COMPACT_USER_VERBATIM_WINDOW_RATIO, MAX_HISTORY_RESULT, MAX_MEMORY_RESULT, MAX_OLD_TOOL_STUB, MAX_SKILL_RESULT, SUMMARY_KEYFACTS_MAX_CHARS, SUMMARY_KEYFACTS_MIN_CHARS, SUMMARY_KEYFACTS_WINDOW_RATIO, SUMMARY_MSG_MAX_CHARS, SUMMARY_OUTPUT_MAX_CHARS, SUMMARY_TRANSCRIPT_WINDOW_RATIO, USER_DIRECTIVE_MAX_CHARS, USER_DIRECTIVE_MAX_CONSTRAINTS, } from '../tools/constants.js';
5
6
  import { ui } from '../ui/theme.js';
6
7
  import { Spinner } from '../ui/spinner.js';
@@ -494,9 +495,11 @@ function capSummaryOutput(summary) {
494
495
  * 子 agent 的压缩不入队:候选是项目级知识,子 agent 的中间推理不该污染主库
495
496
  * (与 archive/snapshot 的 main-agent-only 同一条边界)。
496
497
  */
497
- function finalizeSummaryOutput(raw, capture) {
498
- const { summary, candidates } = extractMemoryCandidates(raw);
499
- if (capture && candidates.length > 0) {
498
+ function finalizeSummaryOutput(raw, captureCandidates, captureAdoptions = false) {
499
+ // R19 段与 R13 候选段都不属于交接摘要,先剥采纳段再剥候选段,避免相邻标题互相吞掉。
500
+ const { text, evaluations } = extractAdoptionEvaluations(raw);
501
+ const { summary, candidates } = extractMemoryCandidates(text);
502
+ if (captureCandidates && candidates.length > 0) {
500
503
  try {
501
504
  appendPendingCandidates(candidates);
502
505
  }
@@ -504,6 +507,8 @@ function finalizeSummaryOutput(raw, capture) {
504
507
  /* best-effort:入队失败只丢这一批候选,绝不阻塞压缩 */
505
508
  }
506
509
  }
510
+ if (captureAdoptions && evaluations.length > 0)
511
+ applyAdoptionEvaluations(evaluations);
507
512
  return capSummaryOutput(summary);
508
513
  }
509
514
  /** 按封顶配额拼转录。scale ∈ (0,1] 等比缩小各角色配额(总预算不足时用)。 */
@@ -532,7 +537,7 @@ function buildTranscript(stripped, scale) {
532
537
  })
533
538
  .join('\n');
534
539
  }
535
- async function defaultSummarize(older, focus, signal, runtime = defaultCompactionRuntime, capture = false) {
540
+ async function defaultSummarize(older, focus, signal, runtime = defaultCompactionRuntime, capture = false, captureAdoptions = false) {
536
541
  // 已中断就别白拼转录了(几千 token 的字符串拼接 + 一去不回的 LLM 请求)。
537
542
  if (signal?.aborted) {
538
543
  throw new DOMException('This operation was aborted', 'AbortError');
@@ -574,7 +579,8 @@ async function defaultSummarize(older, focus, signal, runtime = defaultCompactio
574
579
  'Never invent facts, paths, or results that are not in the transcript; if unsure whether something happened, omit it.' +
575
580
  // R13:候选段是"附加要求",只在捕获开启时追加。它的内容不计入 400 词上限,
576
581
  // 且必须写在正文结构之后——解析端按 `## Memory Candidates` 标题切走。
577
- (capture ? memoryCandidatesInstruction() : ''),
582
+ (capture ? memoryCandidatesInstruction() : '') +
583
+ (captureAdoptions ? adoptionEvaluationInstruction('compact') : ''),
578
584
  };
579
585
  const userMsg = {
580
586
  role: 'user',
@@ -592,7 +598,7 @@ async function defaultSummarize(older, focus, signal, runtime = defaultCompactio
592
598
  // 推理模型可能只返 reasoning_content(content 为 null),或幻觉出 tool_calls → 视为失败
593
599
  if (r.toolCalls.length > 0 || !r.content)
594
600
  return null;
595
- return finalizeSummaryOutput(r.content, capture);
601
+ return finalizeSummaryOutput(r.content, capture, captureAdoptions);
596
602
  }
597
603
  finally {
598
604
  spinner.stop();
@@ -616,7 +622,7 @@ function buildForkMessages(history, kept) {
616
622
  return out;
617
623
  }
618
624
  /** fork 尾部 user 消息:摘要任务指令(原 legacy sysMsg 的规则,措辞改为"上方对话")。 */
619
- function compactForkInstruction(focus, capture = false) {
625
+ function compactForkInstruction(focus, capture = false, captureAdoptions = false) {
620
626
  const focusLine = focus ? `Focus: prioritize facts / decisions / file changes related to 「${focus}」.\n\n` : '';
621
627
  return (focusLine +
622
628
  '[COMPACT TASK] You are an aggressive session compressor writing a handoff note for an agent that is about to lose the context above. ' +
@@ -634,7 +640,8 @@ function compactForkInstruction(focus, capture = false) {
634
640
  'Rules: total ≤ 400 words. State conclusions and locations (path:line where useful), never paste content. ' +
635
641
  'Write each Key Fact as one self-contained line (no pronouns, no "as above", no cross-references). ' +
636
642
  'Do not emit tool calls and do not invent facts; if unsure whether something happened, omit it.' +
637
- (capture ? memoryCandidatesInstruction() : ''));
643
+ (capture ? memoryCandidatesInstruction() : '') +
644
+ (captureAdoptions ? adoptionEvaluationInstruction('compact') : ''));
638
645
  }
639
646
  /** buffer 校验:fork 全量(含指令 + 摘要输出上限)必须装得进窗口,否则回落 legacy。 */
640
647
  function forkFits(prefix, instruction, activeTools, window) {
@@ -644,7 +651,7 @@ function forkFits(prefix, instruction, activeTools, window) {
644
651
  return forkInput + outputBudget <= window;
645
652
  }
646
653
  /** 执行 fork 请求:复用父前缀 + activeTools,记录 compact phase 用量。 */
647
- async function forkSummarize(prefix, instruction, signal, runtime, activeTools, state, capture = false) {
654
+ async function forkSummarize(prefix, instruction, signal, runtime, activeTools, state, capture = false, captureAdoptions = false) {
648
655
  if (signal?.aborted)
649
656
  throw new DOMException('This operation is aborted', 'AbortError');
650
657
  const messages = [...prefix, { role: 'user', content: instruction }];
@@ -675,7 +682,7 @@ async function forkSummarize(prefix, instruction, signal, runtime, activeTools,
675
682
  // 同 legacy:幻觉 tool_calls 或空 content → 失败(调用方回落 microcompact)。
676
683
  if (r.toolCalls.length > 0 || !r.content)
677
684
  return null;
678
- return finalizeSummaryOutput(r.content, capture);
685
+ return finalizeSummaryOutput(r.content, capture, captureAdoptions);
679
686
  }
680
687
  finally {
681
688
  spinner.stop();
@@ -885,17 +892,20 @@ export async function compactHistory(history, opts) {
885
892
  // archive/snapshot(子 agent 的中间推理不属于项目级知识);
886
893
  // - 独立开关让它能单独关(压缩是高频路径,出问题要能立刻止血而不连带关记忆)。
887
894
  const captureCandidates = state === contextState && isMemoryEnabled() && isCompactHandoffEnabled();
895
+ // R19 与 R13 是独立供给:即使关闭压缩候选交接,只要主 agent 的既有压缩调用发生,
896
+ // 仍可评估已经送达的记忆;子 agent 不可写入主会话观测账本。
897
+ const captureAdoptions = state === contextState && isMemoryEnabled();
888
898
  const summarizeFn = opts.summarize ??
889
899
  (async (older, focus, signal) => {
890
900
  const rt = opts.runtime ?? defaultCompactionRuntime;
891
901
  // P0:fork 关闭或 buffer 装不下 → 回落 legacy 独立 compressor 路径。
892
902
  if (!config.compactFork)
893
- return defaultSummarize(older, focus, signal, rt, captureCandidates);
903
+ return defaultSummarize(older, focus, signal, rt, captureCandidates, captureAdoptions);
894
904
  const prefix = buildForkMessages(history, kept);
895
- const instruction = compactForkInstruction(focus, captureCandidates);
905
+ const instruction = compactForkInstruction(focus, captureCandidates, captureAdoptions);
896
906
  if (!forkFits(prefix, instruction, activeTools, opts.window))
897
- return defaultSummarize(older, focus, signal, rt, captureCandidates);
898
- return forkSummarize(prefix, instruction, signal, rt, activeTools, state, captureCandidates);
907
+ return defaultSummarize(older, focus, signal, rt, captureCandidates, captureAdoptions);
908
+ return forkSummarize(prefix, instruction, signal, rt, activeTools, state, captureCandidates, captureAdoptions);
899
909
  });
900
910
  let summary = null;
901
911
  try {
@@ -6,8 +6,8 @@
6
6
  */
7
7
  export { compactHistory, maybeCompact, capToolResultForHistory, truncateMid, contextState, createContextState, } from './compact.js';
8
8
  // ── Context Budget Scheduler 接缝 ────────────────────────────────────────
9
- // agent/core.ts 在 age-aware sweep 后调用 runScheduler(history, step):评估五区预算,
10
- // 只执行可落地的 warn / compact_history;开关关闭时退化为 maybeCompact。
9
+ // agent/core.ts 在 age-aware sweep 后调用 runScheduler(history, step):评估请求占用,
10
+ // 唯一动作是 compact_history;开关关闭时退化为 maybeCompact。
11
11
  // repl /compact 命令调 manualCompact(history, focus?):与自动路径共享决策,focus 透传摘要 prompt。
12
12
  export { runScheduler, manualCompact, createBudgetScheduler } from './scheduler.js';
13
13
  export { newSessionId, saveSession, loadSession, listSessions, sessionDir } from './persist.js';
@@ -73,14 +73,24 @@ export function renderPlanSection(plan) {
73
73
  * 与 renderPlanSection 配对(一个写一个读),格式定义与解析同处,避免散落两处走样。
74
74
  */
75
75
  export function planStepLabel(raw) {
76
+ const { label, detail } = planStepParts(raw);
77
+ return label || detail || raw.trim();
78
+ }
79
+ /**
80
+ * 步骤行正文的完整拆解:短标签 + 详情 + 进行中文案。planStepLabel 的无损版——
81
+ * 底栏 plan chip 点击步骤展开详情时需要 detail(不再只取短标签丢掉描述)。
82
+ * detail 取 `**title** — ` 之后的正文;无 title 的老 plan detail 为空串(整行已当 label)。
83
+ */
84
+ export function planStepParts(raw) {
76
85
  const body = raw.trim();
77
86
  const afIdx = body.lastIndexOf('◀');
78
87
  const activeForm = afIdx >= 0 ? body.slice(afIdx + 1).trim() : '';
79
88
  const main = (afIdx >= 0 ? body.slice(0, afIdx) : body).trim();
80
89
  const m = main.match(/^\*\*(.+?)\*\*(?:\s*—\s*)?([\s\S]*)$/);
81
90
  const title = m?.[1]?.trim() ?? '';
82
- const content = (m ? (m[2] ?? '') : main).trim();
83
- return title || activeForm || content || main;
91
+ const detail = (m ? (m[2] ?? '') : '').trim();
92
+ const content = m ? detail : main;
93
+ return { label: title || activeForm || content, detail, activeForm };
84
94
  }
85
95
  /** 读取当前活跃 `## Plan:` 段的标题;无活跃 plan 返 null。 */
86
96
  export function readActivePlanTitle(sessionId = getCurrentSessionId()) {
@@ -1,6 +1,6 @@
1
1
  // Context Budget Scheduler: normal operation is metadata-only. History content is
2
2
  // rewritten only after real occupancy reaches the shared pressure threshold.
3
- import { evaluateBudget, scheduleActions, formatReport, DEFAULT_BUDGET_POLICY, } from '../context/budget.js';
3
+ import { evaluateBudget, scheduleActions, DEFAULT_BUDGET_POLICY, } from '../context/budget.js';
4
4
  import { chatTools } from '../llm/index.js';
5
5
  import { defaultCompactionRuntime, maybeCompact, contextState, } from './compact.js';
6
6
  import { pruneStaleArtifacts, refreshArtifactFreshness } from '../context/artifacts.js';
@@ -8,6 +8,8 @@ import { pruneSuperseded } from '../context/relevance.js';
8
8
  import { clearRetrievableResults } from '../context/clearing.js';
9
9
  import { createAgeAwareEncodingState } from '../context/age-aware.js';
10
10
  import { applyImageBudget } from '../context/vision-window.js';
11
+ import { ui } from '../ui/theme.js';
12
+ import * as layout from '../ui/layout.js';
11
13
  function emptyPressure(report) {
12
14
  return {
13
15
  triggered: false,
@@ -23,6 +25,14 @@ function emptyPressure(report) {
23
25
  /** One scheduler instance is owned by one agent run. */
24
26
  export function createBudgetScheduler(state = contextState, runtime = defaultCompactionRuntime) {
25
27
  const evaluate = (history, step, activeTools, ephemeralTokens) => evaluateBudget(history, runtime.config.contextWindowTokens, step, state.correction, activeTools, ephemeralTokens);
28
+ // 断路器:压缩跑完仍站在压力线之上,说明「压不下去」是结构性的(system prompt + 工具 schema
29
+ // 等固定开销本身超线,或存在超大单条)。调度器每个 run 新建一次(等价于一个用户轮),所以
30
+ // 这两个标志天然是 turn 作用域的——与 model-turn.ts 的 overflowCompaction 断路器同口径,
31
+ // 但那边按 turnId 计数是因为它挂在跨轮复用的 runtimeContextState 上,这里不需要。
32
+ // 不设此闸的后果:小窗口模型下每步都会付一次完整摘要(输入上限 0.55×window),并连带让
33
+ // readDedup 全量失效、history 前缀缓存归零,三步损耗叠加。
34
+ let compactStuck = false;
35
+ let compactStuckWarned = false;
26
36
  const scheduler = {
27
37
  lastRunLog: null,
28
38
  async runStep(history, step, activeTools = chatTools, ephemeralTokens = 0, signal) {
@@ -91,19 +101,35 @@ export function createBudgetScheduler(state = contextState, runtime = defaultCom
91
101
  pressure.staleArtifacts > 0 ||
92
102
  pressure.encodedLogsAndSearches > 0 ||
93
103
  pressure.cleared > 0;
104
+ let skippedByBreaker = false;
94
105
  for (const _action of actions) {
106
+ if (compactStuck) {
107
+ skippedByBreaker = true;
108
+ break;
109
+ }
95
110
  const result = await maybeCompact(history, report, undefined, state, activeTools, signal, runtime);
96
111
  compactHistoryCalled = true;
97
112
  historyRebuilt ||= result?.historyRebuilt === true;
98
113
  contentMutated ||= result?.compacted === true;
114
+ // 压完仍在线上 → 本 run 不再重试。注意不能只判 summarized:noop-shrunk-too-large /
115
+ // noop-protected 同样是「束手无策」,重复调用只是白跑。
116
+ if (result && result.estimateAfter >= pressureLine)
117
+ compactStuck = true;
118
+ }
119
+ // 首次压完超阈时 compact.ts 已经打过一行提示;这里只在**真的又触发、却被断路器挡下**
120
+ // 时补一句,说明"别指望再压一次",避免两次提示措辞打架。
121
+ if (skippedByBreaker && !compactStuckWarned) {
122
+ compactStuckWarned = true;
123
+ layout.contentWrite(` ${ui.yellow}●${ui.reset} ${ui.yellow}本回合已停止重复压缩(压不下去是结构性的:固定开销或超大单条超线);建议 /clear 或改用更大窗口的模型。${ui.reset}\n`);
99
124
  }
100
125
  const log = {
101
126
  step,
102
127
  report,
103
- actions,
128
+ actions: compactStuck ? [] : actions,
104
129
  pressure,
105
130
  compactHistoryCalled,
106
131
  historyMutation: historyRebuilt ? 'rebuild' : contentMutated ? 'content' : 'none',
132
+ breakerOpen: compactStuck,
107
133
  ts: Date.now(),
108
134
  };
109
135
  scheduler.lastRunLog = log;
@@ -200,4 +226,4 @@ export async function manualCompact(history, focus, opts) {
200
226
  state.schedulerLog = log;
201
227
  return log;
202
228
  }
203
- export { evaluateBudget, scheduleActions, formatReport };
229
+ export { evaluateBudget, scheduleActions };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * /usage 按天用量的终端柱状图(替代长表格:300 天的表有 300+ 行,不可用)。
3
+ *
4
+ * 设计:
5
+ * - 固定 CHART_ROWS 行高,区间再长也不增高;天数 > MAX_BARS 时按等宽时间桶聚合
6
+ * (300 天 → 每柱 7 天,约 43 根柱)。
7
+ * - 柱高按 log1p 缩放:日用量从几十 k 到几百 M 跨 4 个数量级,线性柱会让小日全贴底。
8
+ * - x 轴标签等距抽样(MM-DD),柱子密集时不互相叠字。
9
+ *
10
+ * 纯函数:输入每日聚合 + 终端列宽,输出多行 ANSI 字符串(非 markdown,直接 contentWrite)。
11
+ */
12
+ import { ui } from '../ui/theme.js';
13
+ import { fmtCompactTokens } from '../ui/render.js';
14
+ export const CHART_ROWS = 6;
15
+ /** 柱数上限:超过则按时间桶聚合。 */
16
+ export const MAX_BARS = 48;
17
+ /** 左侧对数标尺占用列宽。 */
18
+ const SCALE_W = 7;
19
+ /** 每日数据 → 柱数据;超过 maxBars 则等宽分桶(桶内求和,标签取桶末日)。 */
20
+ export function bucketizeDays(data, maxBars = MAX_BARS) {
21
+ const n = data.length;
22
+ if (n === 0)
23
+ return [];
24
+ const toBar = (d) => ({
25
+ label: d.day.slice(5),
26
+ total: d.input + d.output,
27
+ input: d.input,
28
+ output: d.output,
29
+ calls: d.calls,
30
+ spanDays: 1,
31
+ });
32
+ if (n <= maxBars)
33
+ return data.map(toBar);
34
+ const size = Math.ceil(n / maxBars);
35
+ const bars = [];
36
+ for (let i = 0; i < n; i += size) {
37
+ const chunk = data.slice(i, i + size);
38
+ const agg = chunk.reduce((acc, d) => {
39
+ acc.input += d.input;
40
+ acc.output += d.output;
41
+ acc.calls += d.calls;
42
+ return acc;
43
+ }, { input: 0, output: 0, calls: 0 });
44
+ bars.push({
45
+ label: chunk[chunk.length - 1].day.slice(5),
46
+ total: agg.input + agg.output,
47
+ input: agg.input,
48
+ output: agg.output,
49
+ calls: agg.calls,
50
+ spanDays: chunk.length,
51
+ });
52
+ }
53
+ return bars;
54
+ }
55
+ /** 柱高 → 颜色梯度(顶层黄、高量绿、中量青、低量 dim)。 */
56
+ function bandColor(height) {
57
+ if (height >= CHART_ROWS)
58
+ return ui.yellow;
59
+ if (height >= CHART_ROWS - 2)
60
+ return ui.green;
61
+ if (height >= 2)
62
+ return ui.cyan;
63
+ return ui.dim;
64
+ }
65
+ /**
66
+ * 渲染柱状图为物理行数组(调用方自行 join '\n')。
67
+ * @param cols 终端列宽;图表总宽钳到 [28, 84]。
68
+ */
69
+ export function renderUsageBars(bars, cols) {
70
+ if (bars.length === 0 || bars.every((b) => b.total <= 0))
71
+ return [];
72
+ const totalW = Math.max(28, Math.min(cols - 2, 84));
73
+ const plotW = totalW - SCALE_W;
74
+ const slot = Math.max(1, Math.floor(plotW / bars.length));
75
+ const barW = Math.min(3, Math.max(1, slot - 1));
76
+ const maxV = Math.max(...bars.map((b) => b.total));
77
+ const logMax = Math.log1p(maxV);
78
+ const heightOf = (v) => (v <= 0 ? 0 : Math.max(1, Math.round((Math.log1p(v) / logMax) * CHART_ROWS)));
79
+ const scaleCol = (text) => ui.dim + String(text).padStart(SCALE_W - 1) + ' ' + ui.reset;
80
+ const lines = [];
81
+ for (let r = CHART_ROWS; r >= 1; r--) {
82
+ // 仅顶行/底行给对数标尺(最大/最小),中间行留空,省地方也不制造精度错觉。
83
+ let row;
84
+ if (r === CHART_ROWS)
85
+ row = scaleCol(fmtCompactTokens(maxV));
86
+ else if (r === 1)
87
+ row = scaleCol('0');
88
+ else
89
+ row = ' '.repeat(SCALE_W);
90
+ for (const b of bars) {
91
+ const h = heightOf(b.total);
92
+ if (r <= h) {
93
+ const color = bandColor(h);
94
+ row += color + '█'.repeat(barW) + ui.reset + ' '.repeat(Math.max(0, slot - barW));
95
+ }
96
+ else {
97
+ row += ' '.repeat(slot);
98
+ }
99
+ }
100
+ lines.push(row.replace(/\s+$/, ''));
101
+ }
102
+ // x 轴标签:按可用宽度等距抽样,每标签至少 6 列间隔(MM-DD 长 5)。
103
+ const labelEvery = Math.max(1, Math.ceil(6 / slot));
104
+ let axis = ' '.repeat(SCALE_W);
105
+ bars.forEach((b, i) => {
106
+ if (i % labelEvery === 0) {
107
+ // 覆盖该 slot 起点放标签;抽样间隔保证不会与下一个标签相撞。
108
+ axis += ui.dim + b.label + ui.reset + ' '.repeat(Math.max(0, slot * labelEvery - 5));
109
+ }
110
+ });
111
+ lines.push(axis.replace(/\s+$/, ''));
112
+ return lines;
113
+ }
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
3
3
  import { contentHash } from '../../changeset/index.js';
4
4
  import { entriesAnchoredTo } from '../../memory/store.js';
5
5
  import { evaluateAnchorsAgainst, toAnchorPath } from '../../memory/anchor.js';
6
+ import { recordMemoryDelivery } from '../../memory/adoption.js';
6
7
  import { IMAGE_READ_MARKER, MAX_FILE_LINES, MAX_HISTORY_RESULT } from '../constants.js';
7
8
  import { MAX_INLINE_BYTES_DEFAULT, isProbablyBinary, loadImageAttachmentWithDownscale, sniffImageMime, } from '../../attachments/image.js';
8
9
  import { config, isMemoryEnabled } from '../../config/index.js';
@@ -201,6 +202,8 @@ function memoryHintFor(path, data) {
201
202
  .slice(0, MEMORY_HINT_LIMIT);
202
203
  if (fresh.length === 0)
203
204
  return '';
205
+ for (const entry of fresh)
206
+ recordMemoryDelivery(entry.id, 'anchor_read');
204
207
  const lines = fresh.map((e) => `- [${e.id}] ${e.name} — ${e.summary}`);
205
208
  return `\n\n## Memory anchored to this file\n${lines.join('\n')}`;
206
209
  }
@@ -25,12 +25,12 @@ import { t } from '../../i18n/index.js';
25
25
  import { state } from './state.js';
26
26
  import { esc, cup, getGeo, setRegion, runningCaretPos, contentMode } from './screen.js';
27
27
  import { normalizeSelection, normalizeInputSelection, extractSelectionText, extractInputSelectionText, isInputRow, pasteIntoInput, inputScreenToInputPos, } from './selection.js';
28
- import { composePlanLines, drawStatusBar, startTurnTimer, stopTurnTimer } from './statusbar.js';
28
+ import { composePlanLines, drawStatusBar, startTurnTimer, stopTurnTimer, isPlanRow, togglePlanExpanded, togglePlanDetail, setPlanRelayoutHandler, } from './statusbar.js';
29
29
  import { paintInput, repaint } from './input-paint.js';
30
30
  import { WHEEL_LINES, screenRowToAbsLine, repaintViewport, scrollBy, scrollWheel, resetScroll, lockScrollToBottom, } from './scroll.js';
31
31
  import { contentWrite, contentInsertAfter, contentDeleteFrom, contentReplaceLine, reflowContentForResize, flushMdSegment, } from './content-write.js';
32
32
  export { isTuiActive, getGeo, getEffectiveContentBottom, setRegion, contentMode, isStreamingPaused } from './screen.js';
33
- export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, setPendingAttachChips, } from './statusbar.js';
33
+ export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, setPendingAttachChips, togglePlanExpanded, togglePlanDetail, } from './statusbar.js';
34
34
  export { paintInput, paintRunningInput, repaint } from './input-paint.js';
35
35
  export { isScrolled, repaintViewport, repaintContentLine, scrollBy, scrollWheel, resetScroll, setMenuReserve, lockScrollToBottom, unlockScroll, isScrollLocked, } from './scroll.js';
36
36
  export { contentWrite, writeBanner, rewriteBanner, bannerHeight, contentWriteMd, contentWriteMdOnce, clearContent, rewindContent, writeWelcomeBlock, dismissWelcomeBlock, contentInsertAfter, contentDeleteFrom, totalRows, isLastContentRowBlank, normalizeMutationBoundary, normalizeInputBoundary, contentReplaceLine, notifyContentReset, } from './content-write.js';
@@ -238,6 +238,14 @@ function handleMouseEvent(e) {
238
238
  scrollWheel(e.dir);
239
239
  return;
240
240
  }
241
+ // plan chip 行点击(在滚动区外的固定脚栏):按下记录命中行,release 时按行路由——
242
+ // 标题行=折叠/展开整个计划,步骤行=展开/收起该步详情(见 release 分支)。
243
+ // 不走内容选区——plan 行不属于内容缓冲,screenRowToAbsLine 会把它错误钳到 contentBottom。
244
+ // 面板/picker 期间(mouseEnabled=false)不响应,与其它非滚轮鼠标交互一致,防重排覆盖弹窗。
245
+ if (state.mouseEnabled && e.button === 0 && e.type === 'press' && isPlanRow(e.row)) {
246
+ state.planPressRow = e.row;
247
+ return;
248
+ }
241
249
  // 输入行左键点击:INPUT 态(含 intervention 面板,其 cursorChangeHandler 已注册)允许定位光标,
242
250
  // 提升用户体验(点哪插哪)。RUNNING 态直接 no-op——光标定位是 INPUT 态交互,运行态
243
251
  // typeahead 由键盘体系管理(←/→/Home/End,running-input.ts),不应触发模式切换(见
@@ -309,6 +317,9 @@ function handleMouseEvent(e) {
309
317
  return;
310
318
  }
311
319
  if (e.type === 'drag') {
320
+ // 从 plan 行拖出:视为取消点击(与 batch 摘要行"纯点击才折叠"一致),不展开。
321
+ if (state.planPressRow !== null && !isPlanRow(e.row))
322
+ state.planPressRow = null;
312
323
  if (state.inputSelection) {
313
324
  // 输入框拖动选区:更新 end,触边不动 scroll(输入框行数有限,无外滚概念);重画底栏。
314
325
  const pos = inputScreenToInputPos(e.row, e.col);
@@ -340,6 +351,20 @@ function handleMouseEvent(e) {
340
351
  }
341
352
  // release(左键)
342
353
  state.selecting = false;
354
+ // plan chip 纯点击(press 命中且未拖出):按 planRowStep 映射路由——
355
+ // 标题行(offset 0)= 折叠/展开整个计划;步骤行 = 展开/收起该步详情;指示行(null)= no-op。
356
+ if (state.planPressRow !== null) {
357
+ const pressRow = state.planPressRow;
358
+ state.planPressRow = null;
359
+ if (isPlanRow(e.row)) {
360
+ const stepNo = state.planRowStep[e.row - (g.contentBottom + 1)] ?? null;
361
+ if (stepNo !== null)
362
+ togglePlanDetail(stepNo);
363
+ else if (pressRow === g.contentBottom + 1)
364
+ togglePlanExpanded(); // 仅标题行折叠整个计划
365
+ return;
366
+ }
367
+ }
343
368
  // 输入框 release 优先:未拖动 → 清选区(光标已定好);拖动过 → 留高亮等右键复制
344
369
  if (state.inputSelection) {
345
370
  if (!state.inputSelection.dragged) {
@@ -505,6 +530,12 @@ export function enterAltScreen() {
505
530
  // 不动终端窗口背景:底色保持用户终端原色,主题只作用于我们画出的 SGR 颜色。
506
531
  stdout.write(esc.mouseOn); // 完整鼠标追踪(按下/拖动/释放/滚轮)→ mouse.swallow 重组 → handleMouseEvent
507
532
  mouse.setHandler(handleMouseEvent);
533
+ // plan 展开态导致脚栏高度变化时,drawStatusBar 心跳路径经此回调全幅重排(重画内容区 + 输入区),
534
+ // 避免在 statusbar 层静态 import input-paint 形成循环依赖。
535
+ setPlanRelayoutHandler(() => {
536
+ repaintViewport();
537
+ repaint();
538
+ });
508
539
  // 进入 alt screen 前 base 可能已设了 planSummary;按当前 planSummary 重算 planRows,
509
540
  // 让首次 setRegion 撑出正确脚栏高(否则 plan 撑 2 行时会被 spinner 行覆盖)。
510
541
  if (state.base)
@@ -593,6 +624,7 @@ export function exitAltScreen() {
593
624
  state.frameCol = 0;
594
625
  mouse.setHandler(null);
595
626
  mouse.resetMouse();
627
+ setPlanRelayoutHandler(null);
596
628
  state.selection = null;
597
629
  state.selecting = false;
598
630
  // raw 还原独立 try:非 TTY / 不支持时 setRawMode 抛错,不应阻断 stdout 恢复(alt 退屏必须执行)。
@@ -135,6 +135,14 @@ export function paintInput(view) {
135
135
  startVis: 0,
136
136
  }
137
137
  : windowInputVis(view.lines, view.cursorLine, view.cursorCol, preGeo.cols, promptW, preGeo.rows);
138
+ // 先按本帧输入行数 + 屏幕高度给 plan 区域算精确行数预算(展开态可能占多行),
139
+ // composePlanLines 据此钳制 planRows,随后 needFooterH 才能与实际渲染行数一致。
140
+ // 约束:footerH = 5 + inputRows + (planRows-1) ≤ rows-1(至少留 1 行内容区)。
141
+ state.inputRows = vis.inputRows;
142
+ // 约束:needFooterH = 5+inputRows+(planRows-1) ≤ rows-1(至少留 1 行内容区)
143
+ // → planRows ≤ rows-5-inputRows。展开 20 步的大计划在矮终端里由此钳制。
144
+ const planMaxRows = Math.max(1, preGeo.rows - 5 - vis.inputRows);
145
+ const planLines = composePlanLines(state.base, preGeo.cols, planMaxRows);
138
146
  const needFooterH = 5 + vis.inputRows + (state.planRows - 1); // 1 虚拟空 + 1 spinner 行 + 1 上线 + 输入行 + 1 下线 + 1 model 行 + plan 多出的行数
139
147
  let g = preGeo;
140
148
  if (needFooterH !== state.footerH) {
@@ -157,24 +165,18 @@ export function paintInput(view) {
157
165
  buf += cup(effBottom, 1) + esc.clearLine + line;
158
166
  }
159
167
  // 2c. 虚拟空行(内容区与状态栏之间的视觉间隔,属底栏非内容):
160
- // - 有活跃 plan:渲染 plan chip(整帧重画时也要更新,避免 listener 漏触发后残留)
168
+ // - 有活跃 plan:渲染 plan chip——折叠 1 行摘要,点击展开后逐行列全部步骤(行数按 2. 的预算钳制)
161
169
  // - 否则有待发图片附件:渲染附件 chip(不进内容缓冲,提交后由 echoInput 正式回显)
162
170
  // - 都没有:清空保留作分隔
163
- // - plan 过长:占 2 行(planRows=2),spinner/上线/输入行随之整体下移 1 行
164
- // paintInput 与 drawStatusBar 共享同一 planRows 模块态,setRegion 已据此把脚栏撑高。
171
+ // setRegion 已按 planRows 撑高脚栏,spinner/上线/输入行随之下移。
165
172
  {
166
- const planBuf = composePlanLines(state.base, preGeo.cols);
167
- for (let i = 0; i < planBuf.length; i++) {
168
- buf += cup(g.contentBottom + 1 + i, 1) + esc.clearLine + planBuf[i];
169
- }
170
- // 计划行从 2 行降到 1 行(plan 当前很短):清掉残留的第 2 行,不留尾巴。
171
- if (planBuf.length < state.planRows && state.planRows === 2) {
172
- buf += cup(g.contentBottom + 2, 1) + esc.clearLine;
173
- state.planRows = 1;
173
+ // 复用步骤 2. 已按精确预算算好的 plan 行(planRows 已写入 state),此处不再重算。
174
+ for (let i = 0; i < planLines.length; i++) {
175
+ buf += cup(g.contentBottom + 1 + i, 1) + esc.clearLine + planLines[i];
174
176
  }
175
177
  // 无 plan 时:画待发附件脚栏(chip + 降采样 badge + 非视觉预警,不进内容缓冲);
176
178
  // slash 菜单向上展开时最后一行也落在这一行,会互相覆盖——菜单打开期间隐藏(关菜单恢复)。
177
- if (planBuf.length === 0) {
179
+ if (planLines.length === 0) {
178
180
  const attLine = view.menu && view.menu.lines.length > 0 ? '' : composePendingAttachLine(g.cols);
179
181
  buf += cup(g.contentBottom + 1, 1) + esc.clearLine + attLine;
180
182
  }
@@ -79,10 +79,23 @@ export const state = {
79
79
  spinnerFrame: undefined,
80
80
  turnStart: null, // RUNNING 态起点(Date.now());INPUT 态为 null。composeStatus 据此拼走时。
81
81
  turnTimer: null, // 走时刷新计时器(独立于 spinner):流式期间 spinner 停转,由它续刷状态行。
82
- /** 当前 plan chip 占用脚栏行数(1 或 2)。composePlanLines 每次重算后写入。
83
- * 驱动 paintInput setRegion(fh) 动态撑高脚栏;drawStatusBar 据此画 1/2 行 plan,
84
- * 与 spinner/上线/输入/下线/model 行的 +1/+2/+3/+4/+5 偏移天然一致(contentBottom 自动重算)。 */
82
+ /** 当前 plan chip 占用脚栏行数:折叠=1(摘要行;超长仍单行截断),展开=1+步骤行数(按脚栏剩余高度钳制)。
83
+ * composePlanLines 每次重算后写入。驱动 paintInput setRegion(fh) 动态撑高脚栏;drawStatusBar
84
+ * 据此画 plan 各行,与 spinner/上线/输入/下线/model 行的 +1/+2/+3/+4/+5 偏移天然一致(contentBottom 自动重算)。 */
85
85
  planRows: 1,
86
+ /** plan chip 展开态(点击摘要行切换)。planKey 变化(新计划/结算消失)时自动回 false。 */
87
+ planExpanded: false,
88
+ /** 当前已渲染 plan 的身份(标题);与 base.planKey 不同说明 plan 换了,收起展开态。 */
89
+ planStateKey: undefined,
90
+ /** 当前输入框可视行数(paintInput 每帧写入):drawStatusBar 路径钳制展开 plan 高度时需要它算脚栏预算。 */
91
+ inputRows: 1,
92
+ /** 左键按下的屏幕行(release 未拖出 plan 区才触发,与内容区选区/折叠交互同构);null=未按在 plan 行上。 */
93
+ planPressRow: null,
94
+ /** 点击展开详情的步骤号集合(仅展开态有意义);planKey 变化时清空。 */
95
+ planOpenSteps: new Set(),
96
+ /** 展开态行→步骤号映射(plan 区内第 i 行对应哪一步;0=标题行→null)。composePlanLines 每次重建,
97
+ * 鼠标 release 时据此把点击行路由到「折叠整个计划 / 切换某步详情」。 */
98
+ planRowStep: [],
86
99
  runningFrame: -1, // 运行态状态行 chip 心跳帧(转圈帧 明灭);INPUT 态 -1 退回静态 ●
87
100
  /** 上一次 paintLiveAtCursor 实际画帧的屏坐标(0=未画)。clearLiveAtCursor 清"这行"而非当前续写位——
88
101
  * 防 spinner 运行期间续写位漂移时清错行、旧帧行残留(见 557e678 移除 isStreamingPaused 后的间歇性 frame 泄漏)。 */