dsh-progress-union 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -20,6 +20,7 @@ import fs from 'node:fs'
20
20
  import os from 'node:os'
21
21
  import path from 'node:path'
22
22
  import z from '@deepseek-ai/schemastery'
23
+ import { ANCHOR_VERSION, ANCHOR_ROUTES, BOARD_STATUSES } from './anchor.js'
23
24
 
24
25
  // 设置页可见性:0.1.7+ 宿主把 composition entry 当设置节,直接按导出的 Config
25
26
  // **逐叶子**的 .volatile() 标记生成「设置 → 插件」里的表单,并把 volatile 字段以
@@ -50,14 +51,27 @@ export const Config = z.object({
50
51
  maxReconcileIntervalMs: z.number().step(1000).min(0).default(60000).volatile(),
51
52
  mirrorThrottleMs: z.number().step(1).min(0).default(200).volatile(),
52
53
  }).default({}),
54
+ // v0.5.0:plan 文档(.agents/plans/<slug>/{spec,tasks,checklist}.md)喂给任务管理 LLM。
55
+ // off = 完全不读盘
56
+ // read = 读 + 解析 + 喂助手 + 板从 tasks.md 细化(默认;只读,不动用户文件)
57
+ // sync = read + 板项完成时回勾 tasks.md 的 `- [ ]` → `- [x]`(会写用户文件)
58
+ planSync: z.union(['off', 'read', 'sync']).default('read').volatile(),
59
+ plan: z.object({
60
+ maxFiles: z.number().step(1).min(1).default(3).volatile(),
61
+ maxBytes: z.number().step(1024).min(4096).default(48 * 1024).volatile(),
62
+ maxTasks: z.number().step(1).min(1).default(40).volatile(),
63
+ rescanMs: z.number().step(1000).min(1000).default(5000).volatile(),
64
+ echoBack: z.boolean().default(true).volatile(),
65
+ }).default({}),
53
66
  })
54
67
 
55
68
  // —— 路由与存储标识 ——
56
69
  const ROUTE_BASE = '/progress-union'
57
70
  const LEGACY_BASE = '/progress-board' // 别名保留一版,与 board 原面板/脚本兼容
58
- const WIDGET_STATUS_ROUTE = '/dsh-progress/status'
71
+ const WIDGET_STATUS_ROUTE = ANCHOR_ROUTES.status
72
+ const ANCHOR_ROUTE = ANCHOR_ROUTES.anchor
73
+ const SNAPSHOT_ROUTE = ANCHOR_ROUTES.snapshot
59
74
  const UNIT_NAME = 'progress_union'
60
- const ANCHOR_VERSION = 1
61
75
 
62
76
  // —— board 侧限额(fork 原值,不放宽)——
63
77
  const MAX_BODY_BYTES = 256 * 1024
@@ -71,7 +85,31 @@ const MAX_NOTE = 1600
71
85
  const MAX_GROUP = 80
72
86
  const STALE_MS = 10 * 60 * 1000
73
87
  const KICKOFF_COOLDOWN_MS = 60 * 1000
74
- const STATUSES = new Set(['todo', 'doing', 'done', 'blocked'])
88
+ const STATUSES = new Set(BOARD_STATUSES)
89
+
90
+ // —— v0.5.0:plan 文档(codeplan 的 spec/tasks/checklist)——
91
+ const PLAN_DIR = '.agents/plans'
92
+ const PLAN_FILES = ['tasks.md', 'checklist.md', 'spec.md']
93
+ // 候选目录判定只用勾选类文件:只有 spec.md 的计划还没拆任务,既无可喂也没法回勾。
94
+ const PLAN_CHECK_FILES = ['tasks.md', 'checklist.md']
95
+ // 状态别名归一:PTC 通道(run_code 内 tools.progress_update)**不经过工具 schema**,
96
+ // 模型会按官方 todo 词表传 pending/in_progress/completed——旧版直接抛「未知状态」,
97
+ // 整批 changes 全灭(session-1969 实测)。这里只做词表归一,不猜语义。
98
+ const STATUS_ALIASES = new Map([
99
+ ['todo', 'todo'], ['pending', 'todo'], ['open', 'todo'], ['not-started', 'todo'],
100
+ ['doing', 'doing'], ['in_progress', 'doing'], ['in-progress', 'doing'], ['inprogress', 'doing'],
101
+ ['running', 'doing'], ['active', 'doing'], ['started', 'doing'], ['wip', 'doing'],
102
+ ['done', 'done'], ['completed', 'done'], ['complete', 'done'], ['finished', 'done'],
103
+ ['blocked', 'blocked'], ['blocker', 'blocked'], ['failed', 'blocked'], ['error', 'blocked'],
104
+ ['stuck', 'blocked'], ['waiting', 'blocked'],
105
+ ])
106
+ function normalizeStatus(raw) {
107
+ if (typeof raw !== 'string') return undefined
108
+ const key = raw.trim().toLowerCase()
109
+ if (!key) return undefined
110
+ if (STATUSES.has(key)) return key
111
+ return STATUS_ALIASES.get(key)
112
+ }
75
113
 
76
114
  // —— /progress-goal 迷你目标域常量(自建,不复用官方 goals 域)——
77
115
  const GOAL_PHASES = new Set(['idle', 'active', 'paused', 'blocked', 'complete'])
@@ -95,6 +133,9 @@ const BAD_READ_GRACE_MS = 2000
95
133
  export const name = 'dsh-progress-union'
96
134
  export const inject = ['tools', 'systemPrompt', 'webServer', 'agents', 'commands', 'llm', 'settings']
97
135
 
136
+ // 纯解析函数导出(仅供 test/plan.test.mjs 单测;不在 dsh 契约面上,勿在插件间消费)。
137
+ export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir }
138
+
98
139
  const PROGRESS_POLICY = `## 进度板
99
140
  progress_update 维护用户可见的实时进度板。每项含 title/status/percent/current/next/approach/note。
100
141
  - 每个用户回合开始时先检查进度板:如果板是空的,你的第一个工具调用必须是 progress_update,先建立扁平任务,再执行任何其他工具。不要等做完才补计划。
@@ -175,6 +216,7 @@ function emptyState(sessionId) {
175
216
  items: [],
176
217
  userChanges: [],
177
218
  todoMirror: null, // v0.3.0:自家镜像写入的 hash/at/count,回环识别用
219
+ planSlug: '', // v0.5.0:显式绑定的 plan 目录名(空=按 mtime 自动选)
178
220
  goal: emptyGoal(),
179
221
  }
180
222
  }
@@ -219,8 +261,185 @@ function summarize(items) {
219
261
  }
220
262
  }
221
263
 
264
+ // ============================================================================
265
+ // v0.5.0:plan 文档解析(codeplan 的 tasks.md / checklist.md / spec.md)
266
+ // 纯函数、不读盘——读盘由 apply 闭包内的 scanPlan 负责,便于单测。
267
+ // 勾选态词表只有两种:[ ] 未完成、[x]/[X] 完成;其余标记(如 [~])按未完成算,
268
+ // 但记 mark 原文交给上层,避免把模型自造标记当事实。
269
+ // ============================================================================
270
+
271
+ /**
272
+ * 解析 tasks.md / checklist.md 的勾选结构。
273
+ * 产出 { phases: [{ title, tasks: [{ id, text, checked, mark, evidence, line }] }], counts }
274
+ * 兼容:`## Phase 1: xxx` / `### 分组` / 无标题的裸列表(落到 phase='')。
275
+ */
276
+ function parseChecklistMarkdown(markdown) {
277
+ const lines = String(markdown || '').split(/\r?\n/)
278
+ const phases = []
279
+ let current = { title: '', tasks: [] }
280
+ phases.push(current)
281
+ // `- [ ] t01 描述` 或 `* [x] 描述`;允许 0–3 层缩进
282
+ const TASK_RE = /^(\s{0,6})[-*+]\s+\[([^\]]{0,3})\]\s*(.*)$/
283
+ const HEAD_RE = /^(\s{0,3})(#{2,4})\s+(.+?)\s*$/
284
+ for (let index = 0; index < lines.length; index += 1) {
285
+ const line = lines[index]
286
+ const head = line.match(HEAD_RE)
287
+ if (head) {
288
+ const title = head[3].trim()
289
+ if (title) {
290
+ current = { title, tasks: [] }
291
+ phases.push(current)
292
+ }
293
+ continue
294
+ }
295
+ const m = line.match(TASK_RE)
296
+ if (!m) continue
297
+ const mark = String(m[2] || '').trim()
298
+ let body = String(m[3] || '').trim()
299
+ if (!body) continue
300
+ // 任务 id 前缀:t01 / T12 / A3 之类,取出来做稳定键(回勾与去重用)
301
+ let id = ''
302
+ const idMatch = body.match(/^([A-Za-z]{1,3}\d{1,3})\s+/)
303
+ if (idMatch) {
304
+ id = idMatch[1]
305
+ body = body.slice(idMatch[0].length).trim()
306
+ }
307
+ // 行尾证据:`✅(验证:…;2026-11-26)` / `✅ 证据…`
308
+ let evidence = ''
309
+ const evMatch = body.match(/\s*(?:✅|✓)\s*(?:(|\()?\s*(?:验证:)?\s*([^))]*?)(?:)|\))?\s*$/)
310
+ if (evMatch && evMatch[0].trim()) {
311
+ // 只在勾选态成立时把尾巴当证据,避免把正文里的 ✅ 剥掉
312
+ if (mark.toLowerCase() === 'x') {
313
+ evidence = evMatch[1].trim().slice(0, 240)
314
+ body = body.slice(0, evMatch.index).trim()
315
+ }
316
+ }
317
+ current.tasks.push({
318
+ id,
319
+ text: body.slice(0, 400),
320
+ checked: mark.toLowerCase() === 'x',
321
+ mark,
322
+ evidence,
323
+ line: index + 1,
324
+ })
325
+ }
326
+ const out = phases.filter((p) => p.title || p.tasks.length > 0)
327
+ let total = 0
328
+ let done = 0
329
+ for (const p of out) {
330
+ for (const t of p.tasks) {
331
+ total += 1
332
+ if (t.checked) done += 1
333
+ }
334
+ }
335
+ return { phases: out, counts: { total, done, pending: total - done } }
336
+ }
337
+
338
+ /** spec.md 只取标题骨架(H1/H2 + 每节首行),避免整篇塞进助手输入。 */
339
+ function parseSpecOutline(markdown) {
340
+ const lines = String(markdown || '').split(/\r?\n/)
341
+ const sections = []
342
+ let current = null
343
+ for (const line of lines) {
344
+ const head = line.match(/^(#{1,3})\s+(.+?)\s*$/)
345
+ if (head) {
346
+ current = { level: head[1].length, title: head[2].trim(), first: '' }
347
+ sections.push(current)
348
+ continue
349
+ }
350
+ if (current && !current.first) {
351
+ const t = line.trim()
352
+ if (t && !t.startsWith('|') && !t.startsWith('>') && !t.startsWith('```')) current.first = t.slice(0, 200)
353
+ }
354
+ }
355
+ return sections.slice(0, 16)
356
+ }
357
+
358
+ /** 一份 plan 文档的稳定指纹:mtime + size(不含路径——Windows 盘符冒号会污染切分)。 */
359
+ function planFileStamp(file) {
360
+ try {
361
+ const st = fs.statSync(file)
362
+ return { stamp: `${Math.round(st.mtimeMs)}:${st.size}`, mtime: Math.round(st.mtimeMs) }
363
+ } catch (_err) {
364
+ return null
365
+ }
366
+ }
367
+
368
+ // —— cwd 三路兜底(实测:cwd 在 session 事件**顶层**,不是 header 里)——
369
+ // 原 markLineage / task.project 只读 session.header.cwd,实测恒空,等于一直没生效。
370
+ function sessionCwd(session) {
371
+ try {
372
+ if (!session) return ''
373
+ const hd = session.header && typeof session.header === 'object' ? session.header : null
374
+ const candidates = [hd && hd.cwd, session.cwd, hd && hd.workspace, session.workspace]
375
+ for (const value of candidates) {
376
+ if (typeof value === 'string' && value.trim()) return value.trim()
377
+ }
378
+ } catch (_err) {}
379
+ return ''
380
+ }
381
+
382
+ /** `<cwd>/.agents/plans` 下的候选计划目录(必须有勾选类文件才算)。 */
383
+ function planDirCandidates(cwd) {
384
+ if (!cwd) return []
385
+ const root = path.join(cwd, PLAN_DIR)
386
+ let names = []
387
+ try {
388
+ names = fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name)
389
+ } catch (_err) {
390
+ return []
391
+ }
392
+ const out = []
393
+ for (const name of names) {
394
+ const dir = path.join(root, name)
395
+ // 只有 spec.md 的计划(还没拆任务)不能当候选:没有勾选表可喂,也没法回勾。
396
+ // 锚点判断用 tasks.md → checklist.md 的顺序(codeplan 里 tasks 是任务分解,优先)。
397
+ let info = null
398
+ for (const f of PLAN_CHECK_FILES) {
399
+ info = planFileStamp(path.join(dir, f))
400
+ if (info) break
401
+ }
402
+ if (!info) continue
403
+ out.push({ slug: name, dir, stamp: info.stamp, mtime: info.mtime })
404
+ }
405
+ return out.sort((a, b) => b.mtime - a.mtime)
406
+ }
407
+
408
+ /** 选计划目录:显式 slug 优先(必须存在),否则 mtime 最新。 */
409
+ function pickPlanDir(cwd, preferredSlug) {
410
+ const list = planDirCandidates(cwd)
411
+ if (!list.length) return null
412
+ const want = String(preferredSlug || '').trim()
413
+ if (want) {
414
+ const hit = list.find((x) => x.slug === want)
415
+ if (hit) return hit
416
+ return null // 显式绑了但目录没了:宁可不喂,也不悄悄换成别的计划
417
+ }
418
+ return list[0]
419
+ }
420
+
421
+ function readCapped(file, maxBytes) {
422
+ try {
423
+ const st = fs.statSync(file)
424
+ if (!st.isFile() || st.size <= 0) return ''
425
+ const cap = Math.max(4096, Number(maxBytes) || 48 * 1024)
426
+ if (st.size <= cap) return readJsonText(file)
427
+ // 超大文件只读前 cap 字节(勾选表头通常在前部;截断由上层标注)
428
+ const fd = fs.openSync(file, 'r')
429
+ try {
430
+ const buf = Buffer.alloc(cap)
431
+ const read = fs.readSync(fd, buf, 0, cap, 0)
432
+ return buf.subarray(0, read).toString('utf8')
433
+ } finally {
434
+ fs.closeSync(fd)
435
+ }
436
+ } catch (_err) {
437
+ return ''
438
+ }
439
+ }
440
+
222
441
  // —— v0.3.0:板 → 官方 todo 的纯映射(content 唯一非空、in_progress ≤1)——
223
- function boardToTodos(state, maxItems) {
442
+ function boardToTodos(state, maxItems, opts) {
224
443
  const limit = Math.max(1, Number(maxItems) || 12)
225
444
  const items = (Array.isArray(state && state.items) ? state.items : [])
226
445
  .slice()
@@ -229,6 +448,8 @@ function boardToTodos(state, maxItems) {
229
448
  const todos = []
230
449
  const seen = new Set()
231
450
  let doingSeen = false
451
+ // v0.5.0:rich 模式把 group / percent 一并带出(任务表转出的步骤细节不再被削平)。
452
+ const rich = Boolean(opts && opts.rich)
232
453
  for (const item of items) {
233
454
  const content = String(item && item.title || '').trim()
234
455
  if (!content || seen.has(content)) continue
@@ -238,7 +459,13 @@ function boardToTodos(state, maxItems) {
238
459
  else if (item.status === 'doing') {
239
460
  if (!doingSeen) { status = 'in_progress'; doingSeen = true }
240
461
  }
241
- todos.push({ content, status })
462
+ const todo = { content, status }
463
+ if (rich) {
464
+ if (item.group) todo.group = String(item.group)
465
+ if (typeof item.percent === 'number') todo.percent = item.percent
466
+ if (item.status === 'blocked') todo.blocked = true
467
+ }
468
+ todos.push(todo)
242
469
  }
243
470
  return todos
244
471
  }
@@ -350,6 +577,10 @@ function parseProgressFile(file, key) {
350
577
  try {
351
578
  const parsed = JSON.parse(readJsonText(file))
352
579
  if (parsed && typeof parsed === 'object' && typeof parsed.task === 'string' && Array.isArray(parsed.stages)) {
580
+ // v0.5.0:可选 steps(步骤名数组,与 stages 同义但更贴近任务表)与 group 透传,
581
+ // 供迷你条按步骤渲染;老上报没有这两个字段时保持原形状,零迁移成本。
582
+ if (!Array.isArray(parsed.steps) && Array.isArray(parsed.stages)) parsed.steps = parsed.stages
583
+ if (typeof parsed.group !== 'string') parsed.group = ''
353
584
  lastGoodByKey.set(key, parsed)
354
585
  lastGoodAt = Date.now()
355
586
  return parsed
@@ -366,8 +597,11 @@ function parseProgressFile(file, key) {
366
597
  }
367
598
 
368
599
  // 鲸程兼容层:读 $DSH_HOME/dsh-progress/<sid>.json 上报(板关闭时的增强层)。
369
- function readFileTasks() {
600
+ // activeSids:调用方传入的活跃会话集合(本函数在模块级,不能直接引用 apply 闭包里的
601
+ // states/taskMap——那次越界引用会让 /dsh-progress/status 整条路由抛错)。
602
+ function readFileTasks(activeSids) {
370
603
  const out = []
604
+ const active = activeSids instanceof Set ? activeSids : new Set()
371
605
  let names = []
372
606
  try {
373
607
  names = fs.readdirSync(PROGRESS_DIR).filter((n) => n.endsWith('.json'))
@@ -380,14 +614,20 @@ function readFileTasks() {
380
614
  if (parsed) out.push({ ...parsed, reportId: parsed.session ? String(parsed.session) : name.replace(/\.json$/, ''), source: 'dir' })
381
615
  }
382
616
  // 24 小时未更新的分文件顺手清理(活跃会话个位数,逐次 stat 可忽略)
617
+ // v0.5.0 修正:**不得删掉还在跑的会话的上报文件**。旧逻辑只看 mtime,把「常驻
618
+ // 会话超过 24h 没更新进度文件」与「过期垃圾」混为一谈——那次清理会直接顶掉
619
+ // 用户正看着的任务条。现在只有「文件里声明的 session 不在活跃集合里」才允许删。
383
620
  for (const name of names) {
384
621
  const full = path.join(PROGRESS_DIR, name)
385
622
  try {
386
623
  const st = fs.statSync(full)
387
- if (Date.now() - st.mtimeMs > PROGRESS_DIR_KEEP_MS) {
388
- fs.unlinkSync(full)
389
- lastGoodByKey.delete(full)
390
- }
624
+ if (Date.now() - st.mtimeMs <= PROGRESS_DIR_KEEP_MS) continue
625
+ const parsed = parseProgressFile(full, full)
626
+ const declared = parsed && parsed.session ? String(parsed.session) : ''
627
+ const stem = name.replace(/\.json$/, '')
628
+ if ((declared && active.has(declared)) || active.has(stem)) continue
629
+ fs.unlinkSync(full)
630
+ lastGoodByKey.delete(full)
391
631
  } catch (_err) {}
392
632
  }
393
633
  const legacy = parseProgressFile(PROGRESS_FILE, PROGRESS_FILE)
@@ -576,6 +816,18 @@ const DEFAULT_CONFIG = {
576
816
  // v0.3.0:板 → 官方 todo 镜像与冲突裁决。默认 reconcile;不想要行为变更可在设置页关。
577
817
  todoSync: 'reconcile', // off | mirror | reconcile
578
818
  todo: { maxReconcileIntervalMs: 60_000, mirrorThrottleMs: 200 },
819
+ // v0.5.0:plan 文档(codeplan 的 spec/tasks/checklist)喂给任务管理 LLM。
820
+ // off = 完全不读盘
821
+ // read = 读 + 解析 + 喂助手 + 观察块摘要(默认;只读,不动用户文件)
822
+ // sync = read + 板项完成时回勾 tasks.md(会写用户文件,需用户显式开启)
823
+ planSync: 'read', // off | read | sync
824
+ plan: {
825
+ maxFiles: 3,
826
+ maxBytes: 48 * 1024,
827
+ maxTasks: 40,
828
+ rescanMs: 5000,
829
+ echoBack: true,
830
+ },
579
831
  // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案):
580
832
  // mode: 'registered' 走宿主 llm.stream(选已注册 llm-pi-ai provider/model);
581
833
  // 'direct' 走自建 OpenAI 兼容端点(baseUrl/apiKey/model);'' 关。
@@ -666,6 +918,26 @@ export async function apply(ctx, config) {
666
918
  return out
667
919
  }
668
920
  Object.defineProperty(cfg, 'todo', { get: todoNow, configurable: true, enumerable: true })
921
+
922
+ // v0.5.0:planSync / plan.* 同样逐叶子解包(设置页改完立即生效)。
923
+ const planSyncRaw = config && typeof config === 'object' ? config.planSync : undefined
924
+ Object.defineProperty(cfg, 'planSync', {
925
+ get: () => readVolatile(planSyncRaw, DEFAULT_CONFIG.planSync),
926
+ configurable: true, enumerable: true,
927
+ })
928
+ const planRaw = config && typeof config === 'object' ? config.plan : undefined
929
+ function planNow() {
930
+ const base = DEFAULT_CONFIG.plan
931
+ const raw = unwrapLive(planRaw)
932
+ if (!isObject(raw)) return { ...base }
933
+ const out = { ...base }
934
+ for (const key of Object.keys(base)) {
935
+ const v = unwrapLive(raw[key])
936
+ if (v !== undefined) out[key] = v
937
+ }
938
+ return out
939
+ }
940
+ Object.defineProperty(cfg, 'plan', { get: planNow, configurable: true, enumerable: true })
669
941
  const now = () => Date.now()
670
942
 
671
943
  // —— 状态容器 ——
@@ -1034,7 +1306,7 @@ export async function apply(ctx, config) {
1034
1306
  return undefined
1035
1307
  }
1036
1308
 
1037
- function applyOneChange(state, change, origin, at, records) {
1309
+ function applyOneChange(state, change, origin, at, records, warnings) {
1038
1310
  if (!isObject(change)) throw new Error('changes 的每一项必须是对象')
1039
1311
  const remove = change.remove === true
1040
1312
  const existing = findItem(state, change)
@@ -1055,7 +1327,13 @@ export async function apply(ctx, config) {
1055
1327
  if (state.items.length >= MAX_ITEMS) throw new Error(`任务数量已达到上限 ${MAX_ITEMS}`)
1056
1328
  const title = text(change.title, MAX_TITLE)
1057
1329
  if (!title) throw new Error('任务标题不能为空')
1058
- const status = STATUSES.has(change.status) ? change.status : 'todo'
1330
+ // 新增分支同样吃别名(PTC 词表 pending/in_progress/completed);无法识别时
1331
+ // 落默认 todo 并回 warning——与编辑分支的宽容策略保持一致。
1332
+ const statusRaw = normalizeStatus(change.status)
1333
+ if (typeof change.status === 'string' && statusRaw === undefined) {
1334
+ warnings.push(`status "${change.status}" 无法识别(已按 todo 处理,合法值 todo|doing|done|blocked)`)
1335
+ }
1336
+ const status = statusRaw ?? 'todo'
1059
1337
  const percent = status === 'done' ? 100 : Math.max(0, Math.min(100, Math.round(finiteNumber(change.percent) ?? 0)))
1060
1338
  const item = {
1061
1339
  id: newItemId(),
@@ -1098,12 +1376,21 @@ export async function apply(ctx, config) {
1098
1376
  }
1099
1377
 
1100
1378
  if (typeof change.status === 'string') {
1101
- if (!STATUSES.has(change.status)) throw new Error(`未知状态:${change.status}`)
1102
- record('status', existing.status, change.status)
1103
- existing.status = change.status
1104
- if (change.status === 'done') {
1105
- record('percent', existing.percent, 100)
1106
- existing.percent = 100
1379
+ // PTC 通道(run_code 内 tools.progress_update)绕过工具 JSON Schema,模型会按
1380
+ // 官方 todo 词表传 pending/in_progress/completed。词表归一;归一失败只跳过该
1381
+ // 字段并记 warning——不为了一个词表错就让整批 changes 全灭(会话 1969 实测)。
1382
+ // 注意:这里**只对 status 宽容**。remove 找不到目标、新增缺 title、percent 非
1383
+ // 数字仍抛错——那些是真 bug,静默会掩盖。
1384
+ const normalized = normalizeStatus(change.status)
1385
+ if (normalized === undefined) {
1386
+ warnings.push(`status "${change.status}" 无法识别(已忽略,合法值 todo|doing|done|blocked)`)
1387
+ } else {
1388
+ record('status', existing.status, normalized)
1389
+ existing.status = normalized
1390
+ if (normalized === 'done') {
1391
+ record('percent', existing.percent, 100)
1392
+ existing.percent = 100
1393
+ }
1107
1394
  }
1108
1395
  }
1109
1396
 
@@ -1170,8 +1457,9 @@ export async function apply(ctx, config) {
1170
1457
  // 变成重复或半应用任务(board 原教训,原样保留)。
1171
1458
  const working = clone(state)
1172
1459
  const records = []
1460
+ const warnings = []
1173
1461
  const at = now()
1174
- for (const change of changes) applyOneChange(working, change, origin, at, records)
1462
+ for (const change of changes) applyOneChange(working, change, origin, at, records, warnings)
1175
1463
 
1176
1464
  let revisionChanged = false
1177
1465
  if (records.length > 0) {
@@ -1206,8 +1494,14 @@ export async function apply(ctx, config) {
1206
1494
  if (revisionChanged || (origin === 'agent' && ackUserRevision !== undefined)) {
1207
1495
  states.set(sessionId, working)
1208
1496
  await persist(sessionId)
1497
+ // 锚点订阅:持久化后按 revision 去重推送(同一 revision 不重复)。
1498
+ if (revisionChanged) notifyAnchor(sessionId, working.revision)
1209
1499
  // 唯一写板入口:持久化之后调度 todo 镜像(200ms 去抖,off 时直接返回)。
1210
1500
  if (revisionChanged) scheduleTodoMirror(sessionId)
1501
+ // v0.5.0:sync 模式下把已完成的项回勾到 tasks.md(默认 read 时内部直接返回 0)。
1502
+ if (revisionChanged) {
1503
+ try { maybeEchoBack(sessionId) } catch (_err) {}
1504
+ }
1211
1505
  }
1212
1506
  // 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
1213
1507
  // 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
@@ -1222,7 +1516,7 @@ export async function apply(ctx, config) {
1222
1516
  fields: record.fields.map((field) => field.field),
1223
1517
  }
1224
1518
  })
1225
- return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean) }
1519
+ return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean), warnings }
1226
1520
  }
1227
1521
 
1228
1522
  // ==========================================================================
@@ -1616,8 +1910,17 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1616
1910
  if (typeof d.name !== 'string' || !d.name) return
1617
1911
  const o = obsOf(sid)
1618
1912
  const at = now()
1619
- o.tools.push({ at, name: d.name, brief: briefArgs(d.arguments) })
1620
- if (o.tools.length > 8) o.tools.splice(0, o.tools.length - 8)
1913
+ const brief = briefArgs(d.arguments)
1914
+ // PTC 一步可能派发几十条同名工具(实测某会话单会话 86 次 shell),全量 push 会把
1915
+ // 真实动作挤出 o.tools 窗口。同 name+brief 与末条相同时只推进时间戳。
1916
+ const last = o.tools[o.tools.length - 1]
1917
+ if (last && last.name === d.name && last.brief === brief) {
1918
+ last.at = at
1919
+ last.count = (last.count || 1) + 1
1920
+ } else {
1921
+ o.tools.push({ at, name: d.name, brief, count: 1 })
1922
+ if (o.tools.length > 8) o.tools.splice(0, o.tools.length - 8)
1923
+ }
1621
1924
  // 文件改动(事实级):任何带路径类参数的工具调用都记一笔,同路径去重留最新
1622
1925
  const file = filePathOf(d.arguments)
1623
1926
  if (file) {
@@ -1781,6 +2084,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1781
2084
  o.lastAssistantAt = at
1782
2085
  const lastOutput = o.outputs[o.outputs.length - 1]
1783
2086
  const files = Array.isArray(o.files) ? o.files.slice(-4).map((f) => f.path) : []
2087
+ const planText = planBrief(sid)
1784
2088
  const lines = [
1785
2089
  `目标:${state.goal && state.goal.phase === 'active' ? JSON.stringify(state.goal.objective) : '(无)'}`,
1786
2090
  ...renderChecklist(state, cfg.observer.maxItems),
@@ -1788,6 +2092,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1788
2092
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1789
2093
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1790
2094
  ]
2095
+ // plan 文档是**助手细化板的主原料**:用户明确要求让任务管理 LLM 读 spec/tasks/checklist。
2096
+ if (planText) lines.push(planText)
1791
2097
  try {
1792
2098
  const raw = await callAssistant({ system: ASSISTANT_SYSTEM, user: lines.join('\n'), a })
1793
2099
  const proposal = parseProposal(raw)
@@ -1824,6 +2130,156 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1824
2130
  return lines
1825
2131
  }
1826
2132
 
2133
+ // ==========================================================================
2134
+ // B3. plan 文档(codeplan 的 spec/tasks/checklist)→ 助手的任务细化原料
2135
+ // 实测要点(findings.md §4):cwd 在 session **顶层**;宿主 todo 只认
2136
+ // content+status 两个字段;设置页不会自动渲染新叶子。
2137
+ // ==========================================================================
2138
+
2139
+ const planCache = new Map() // sessionId → { stamp, slug, at, data }
2140
+ // session/event 里拿到的 cwd 缓存:事件流的 session 对象一定带顶层 cwd,比
2141
+ // agent.session 可靠(后者在测试基座/旧宿主上可能没有 cwd,甚至拿不到 agent)。
2142
+ const cwdBySession = new Map()
2143
+
2144
+ /** 扫描并缓存当前会话的 plan 文档。cwd 拿不到时返回 null(不猜 process.cwd())。 */
2145
+ function scanPlan(sid) {
2146
+ if (String(cfg.planSync || 'off') === 'off') return null
2147
+ let cwd = cwdBySession.get(sid) || ''
2148
+ if (!cwd) {
2149
+ const agent = agentOfSession.get(sid)
2150
+ cwd = sessionCwd(agent && agent.session)
2151
+ if (cwd) cwdBySession.set(sid, cwd)
2152
+ }
2153
+ if (!cwd) return null
2154
+ const state = states.get(sid)
2155
+ const preferred = state ? String(state.planSlug || '') : ''
2156
+ const hit = pickPlanDir(cwd, preferred)
2157
+ if (!hit) {
2158
+ planCache.delete(sid)
2159
+ return null
2160
+ }
2161
+ const at = now()
2162
+ const cached = planCache.get(sid)
2163
+ const rescanMs = Math.max(1000, Number(cfg.plan.rescanMs) || 5000)
2164
+ if (cached && cached.stamp === hit.stamp && cached.slug === hit.slug && at - cached.at < rescanMs) return cached.data
2165
+
2166
+ const maxBytes = Math.max(4096, Number(cfg.plan.maxBytes) || 48 * 1024)
2167
+ const checkFile = PLAN_CHECK_FILES.find((f) => planFileStamp(path.join(hit.dir, f)))
2168
+ const markdown = checkFile ? readCapped(path.join(hit.dir, checkFile), maxBytes) : ''
2169
+ const parsed = parseChecklistMarkdown(markdown)
2170
+ const specRaw = readCapped(path.join(hit.dir, 'spec.md'), maxBytes)
2171
+ const data = {
2172
+ slug: hit.slug,
2173
+ dir: hit.dir,
2174
+ file: checkFile || '',
2175
+ truncated: Boolean(checkFile) && markdown.length >= maxBytes,
2176
+ phases: parsed.phases.filter((p) => p.title || p.tasks.length),
2177
+ counts: parsed.counts,
2178
+ spec: parseSpecOutline(specRaw),
2179
+ }
2180
+ planCache.set(sid, { stamp: hit.stamp, slug: hit.slug, at, data })
2181
+ return data
2182
+ }
2183
+
2184
+ /** 助手输入里的 <plan> 段:勾选计数 + 各 Phase 进度 + 未完项 + spec 大纲。 */
2185
+ function planBrief(sid) {
2186
+ const p = scanPlan(sid)
2187
+ if (!p || p.counts.total === 0) return ''
2188
+ const lines = [`<plan slug="${p.slug}" file="${p.file}">`]
2189
+ lines.push(`勾选:${p.counts.done}/${p.counts.total}(${p.counts.pending} 未完成)${p.truncated ? '(文件已截断,仅前 48KB)' : ''}`)
2190
+ for (const phase of p.phases.slice(0, 8)) {
2191
+ if (!phase.title) continue
2192
+ const total = phase.tasks.length
2193
+ if (!total) continue
2194
+ const done = phase.tasks.filter((t) => t.checked).length
2195
+ lines.push(`${phase.title} ${done}/${total}`)
2196
+ }
2197
+ const pending = []
2198
+ for (const phase of p.phases) {
2199
+ for (const t of phase.tasks) {
2200
+ if (t.checked) continue
2201
+ pending.push(`${t.id ? t.id + ' ' : ''}${t.text.slice(0, 80)}`)
2202
+ if (pending.length >= 8) break
2203
+ }
2204
+ if (pending.length >= 8) break
2205
+ }
2206
+ if (pending.length) lines.push(`未完:${pending.join(' · ')}`)
2207
+ if (p.spec.length) lines.push(`spec 大纲:${p.spec.slice(0, 8).map((s) => s.title).join(' / ')}`)
2208
+ lines.push('</plan>')
2209
+ return lines.join('\n')
2210
+ }
2211
+
2212
+ /** 观察块的一行摘要(给主模型看,不占助手配额)。 */
2213
+ function planLine(sid) {
2214
+ const p = scanPlan(sid)
2215
+ if (!p || p.counts.total === 0) return ''
2216
+ const doing = p.phases.find((ph) => ph.tasks.some((t) => !t.checked))
2217
+ const phase = doing && doing.title ? `,当前 ${doing.title}` : ''
2218
+ return `[plan] ${p.slug}:勾选 ${p.counts.done}/${p.counts.total}${phase}${p.truncated ? '(已截断)' : ''}`
2219
+ }
2220
+
2221
+ // ==========================================================================
2222
+ // B4. 回勾(planSync='sync' 才启用):板项 done → tasks.md 的 `- [ ]` → `- [x]`
2223
+ // 写用户文件是高风险动作,护栏三层:
2224
+ // ① 默认 planSync='read',sync 必须用户显式开;
2225
+ // ② 只改「当前仍未被勾选」且正文匹配的行;用户改过就不动;
2226
+ // ③ 只改勾选态 + 追加 ✅ 证据,绝不改任务本体(codeplan 铁律)。
2227
+ // ==========================================================================
2228
+
2229
+ const echoedKeys = new Map() // `${sid}:${slug}:${line}:${title}` → at,防重复回勾
2230
+
2231
+ /** 把板里已 done 且能命中 plan 未勾项的任务,回勾到文件。返回改动条数。 */
2232
+ function maybeEchoBack(sid) {
2233
+ if (String(cfg.planSync || '') !== 'sync') return 0
2234
+ const p = scanPlan(sid)
2235
+ if (!p || !p.file || p.counts.pending === 0) return 0
2236
+ const state = states.get(sid)
2237
+ if (!state) return 0
2238
+ const doneItems = state.items.filter((item) => item.status === 'done')
2239
+ if (!doneItems.length) return 0
2240
+ let text = ''
2241
+ try {
2242
+ text = fs.readFileSync(path.join(p.dir, p.file), 'utf8')
2243
+ } catch (_err) {
2244
+ return 0
2245
+ }
2246
+ const eol = text.includes('\r\n') ? '\r\n' : '\n'
2247
+ const lines = text.split(/\r?\n/)
2248
+ const today = new Date().toISOString().slice(0, 10)
2249
+ const TASK_RE = /^(\s{0,6}[-*+]\s+)\[([ xX])\]\s*(.*)$/
2250
+ let changed = 0
2251
+ for (const item of doneItems) {
2252
+ const title = String(item.title || '').trim()
2253
+ if (!title) continue
2254
+ // 命中规则:行仍未被勾选,且正文包含板项标题。不命中就跳过(不猜 id 前缀)。
2255
+ let target = -1
2256
+ for (let i = 0; i < lines.length; i += 1) {
2257
+ const m = lines[i].match(TASK_RE)
2258
+ if (!m || String(m[2]).toLowerCase() === 'x') continue
2259
+ if (String(m[3] || '').includes(title)) { target = i; break }
2260
+ }
2261
+ if (target < 0) continue
2262
+ const key = `${sid}:${p.slug}:${target}:${title.slice(0, 40)}`
2263
+ const last = echoedKeys.get(key)
2264
+ if (last && now() - last < 10 * 60 * 1000) continue
2265
+ const m = lines[target].match(TASK_RE)
2266
+ if (!m) continue
2267
+ const evidence = String(item.current || item.next || '板已完成').replace(/\s+/g, ' ').slice(0, 120)
2268
+ lines[target] = `${m[1]}[x] ${String(m[3]).replace(/\s*✅.*$/, '').trim()} ✅(验证:${evidence};${today})`
2269
+ echoedKeys.set(key, now())
2270
+ changed += 1
2271
+ }
2272
+ if (changed > 0) {
2273
+ try {
2274
+ fs.writeFileSync(path.join(p.dir, p.file), lines.join(eol), 'utf8')
2275
+ planCache.delete(sid) // 文件已变,下次重扫
2276
+ } catch (_err) {
2277
+ return 0
2278
+ }
2279
+ }
2280
+ return changed
2281
+ }
2282
+
1827
2283
  /**
1828
2284
  * 观察块:每请求重建(systemPrompt.context),不进历史累积。
1829
2285
  * = 清单(checklist)+ 官方 todo 进度 + 最近输出 + 最近动作 +(滞后时)催办。
@@ -1855,7 +2311,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1855
2311
  const lastOutput = o.outputs[o.outputs.length - 1]
1856
2312
  if (lastOutput) lines.push(`最近输出:「${lastOutput.text}」`)
1857
2313
  const tools = o.tools.slice(-cfg.observer.maxTools)
1858
- if (tools.length) lines.push(`最近动作:${tools.map((x) => x.name).join(' → ')}`)
2314
+ if (tools.length) lines.push(`最近动作:${tools.map((x) => (x.count > 1 ? `${x.name}×${x.count}` : x.name)).join(' → ')}`)
2315
+ if (o.lastToolError) lines.push(`最近失败:${o.lastToolError.name}${o.lastToolError.message ? ' · ' + o.lastToolError.message : ''}`)
1859
2316
  const synced = o.stepsSinceModel > 0 ? `${o.stepsSinceModel} 步前` : '本回合'
1860
2317
  const late = modelIsLate(sid, at)
1861
2318
  if (late) {
@@ -1865,6 +2322,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1865
2322
  if (o.assistantNote) lines.push(`助手审查:${o.assistantNote}`)
1866
2323
  if (o.roundDraft) lines.push(`助手轮次草案(仅供参考):${o.roundDraft}`)
1867
2324
  if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
2325
+ const planRow = planLine(sid)
2326
+ if (planRow) lines.push(planRow)
1868
2327
  return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
1869
2328
  }
1870
2329
 
@@ -1942,12 +2401,16 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1942
2401
  }
1943
2402
 
1944
2403
  // 子智能体识别:delegationDepth>0 即子会话;parentSession 存在才采用,拿不到不硬猜。
2404
+ // 注意:这些字段在现行宿主上位于 session **顶层**(实测见 findings.md §4 t01),
2405
+ // header 只是兼容兜底——旧代码只读 header,导致 isSub/parentId 一直没生效。
1945
2406
  function markLineage(task, session) {
1946
2407
  try {
1947
- const hd = session && session.header
1948
- if (!hd || !task) return
1949
- if (typeof hd.delegationDepth === 'number' && hd.delegationDepth > 0) task.isSub = true
1950
- if (task.isSub && hd.parentSession) task.parentId = String(hd.parentSession)
2408
+ if (!session || !task) return
2409
+ const hd = session.header && typeof session.header === 'object' ? session.header : {}
2410
+ const depth = typeof session.delegationDepth === 'number' ? session.delegationDepth : hd.delegationDepth
2411
+ if (typeof depth === 'number' && depth > 0) task.isSub = true
2412
+ const parent = session.parentSession || hd.parentSession
2413
+ if (task.isSub && parent) task.parentId = String(parent)
1951
2414
  } catch (_err) {}
1952
2415
  }
1953
2416
 
@@ -2165,7 +2628,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2165
2628
  }
2166
2629
  // 鲸程兼容层:board 关闭的会话若有文件上报任务,合并/独立成条(blocked 也要显示)。
2167
2630
  const reportsByKey = new Map()
2168
- for (const rep of readFileTasks()) {
2631
+ for (const rep of readFileTasks(new Set([...states.keys(), ...taskMap.keys()]))) {
2169
2632
  const key = String(rep.reportId || 'legacy')
2170
2633
  const prev = reportsByKey.get(key)
2171
2634
  if (!prev || (Number(rep.updatedAt) || 0) >= (Number(prev.updatedAt) || 0)) reportsByKey.set(key, rep)
@@ -2281,11 +2744,35 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2281
2744
  if (!event) return
2282
2745
  const sid = session && session.id ? String(session.id) : 'default'
2283
2746
  const type = event.type
2747
+ // plan 扫描的 cwd 来源:会话事件流里的 session 对象(顶层带 cwd)。只记一次。
2748
+ if (!cwdBySession.has(sid)) {
2749
+ const c = sessionCwd(session)
2750
+ if (c) cwdBySession.set(sid, c)
2751
+ }
2284
2752
  // 观察者原料:最近输出(assistant/message)与最近动作(tool/call)都是会话事实
2285
2753
  if (type === 'tool/call') {
2286
2754
  recordTool(sid, event.data)
2287
2755
  return
2288
2756
  }
2757
+ // PTC(run_code 内 tools.*)的内层调用落在 ptc-dispatch:外层 tool/call 只有
2758
+ // run_code。不接这里,观察者的「最近动作」在 PTC 会话里恒为 run_code,
2759
+ // 助手拿不到原料——这是「todolist 步骤弱化」的机械原因(实测 153 条)。
2760
+ if (type === 'tool/ptc-dispatch') {
2761
+ const dd = event.data || {}
2762
+ // 只记完成的 dispatch(有 isError 字段才代表终态);dispatch-start 是起始事件,
2763
+ // 同一条会在终态再记一次,重复记会把窗口挤满。
2764
+ if (Object.prototype.hasOwnProperty.call(dd, 'isError')) {
2765
+ recordTool(sid, dd)
2766
+ if (dd.isError) {
2767
+ const o = obsOf(sid)
2768
+ o.lastToolError = { name: String(dd.name || ''), at: now() }
2769
+ o.lastToolError.message = String(
2770
+ (Array.isArray(dd.content) ? (dd.content.find((b) => b && b.type === 'text') || {}).text : '') || '',
2771
+ ).slice(0, 160)
2772
+ }
2773
+ }
2774
+ return
2775
+ }
2289
2776
  if (type === 'assistant/message') {
2290
2777
  recordOutput(sid, event.data)
2291
2778
  return
@@ -2379,7 +2866,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2379
2866
  if (task.isSub && pendingText) task.subTitled = true
2380
2867
  task.project = ''
2381
2868
  try {
2382
- const cwd = session && session.header && session.header.cwd ? String(session.header.cwd) : ''
2869
+ // 实测:cwd 在 session 事件**顶层**(见 findings.md §4 t01);旧代码只读
2870
+ // session.header.cwd,在现行宿主上恒空 → 项目名一直是空串。
2871
+ const cwd = sessionCwd(session)
2383
2872
  if (cwd) task.project = path.basename(cwd)
2384
2873
  } catch (_err) {}
2385
2874
  } else {
@@ -2529,6 +3018,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2529
3018
  }
2530
3019
 
2531
3020
  // —— service 平面(同进程零 I/O;宿主无 provide 面时静默只留 HTTP)——
3021
+ const anchorListeners = new Map() // sessionId -> Set<listener>
3022
+ const lastAnchorRevision = new Map() // sessionId -> 已推送的 revision
2532
3023
  const anchorApi = {
2533
3024
  version: ANCHOR_VERSION,
2534
3025
  get(sessionId, atMs) {
@@ -2538,6 +3029,30 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2538
3029
  const ids = new Set([...states.keys(), ...taskMap.keys()])
2539
3030
  return [...ids].map((sid) => buildAnchor(sid, finiteNumber(atMs) ?? now()))
2540
3031
  },
3032
+ subscribe(listener, sessionId) {
3033
+ if (typeof listener !== 'function') return () => {}
3034
+ if (sessionId === undefined) {
3035
+ const offs = [...states.keys(), ...taskMap.keys()].map((sid) => anchorApi.subscribe(listener, sid))
3036
+ return () => offs.forEach((off) => off())
3037
+ }
3038
+ const sid = String(sessionId)
3039
+ let set = anchorListeners.get(sid)
3040
+ if (!set) { set = new Set(); anchorListeners.set(sid, set) }
3041
+ set.add(listener)
3042
+ return () => {
3043
+ set.delete(listener)
3044
+ if (set.size === 0) anchorListeners.delete(sid)
3045
+ }
3046
+ },
3047
+ }
3048
+ function notifyAnchor(sessionId, revision) {
3049
+ const set = anchorListeners.get(sessionId)
3050
+ if (!set || set.size === 0) return
3051
+ if (lastAnchorRevision.get(sessionId) === revision) return
3052
+ lastAnchorRevision.set(sessionId, revision)
3053
+ for (const listener of [...set]) {
3054
+ try { listener({ sessionId, revision }) } catch (_err) {}
3055
+ }
2541
3056
  }
2542
3057
  if (typeof ctx.provide === 'function') {
2543
3058
  try {
@@ -2848,6 +3363,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2848
3363
  revision: { type: 'number' },
2849
3364
  summary: { type: 'object', additionalProperties: true },
2850
3365
  changed: { type: 'array', items: { type: 'object', additionalProperties: true } },
3366
+ warnings: { type: 'array', items: { type: 'string' } },
2851
3367
  },
2852
3368
  },
2853
3369
  render(_args, value) {
@@ -2875,6 +3391,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2875
3391
  agentSeenRevision: result.snapshot.agentSeenRevision,
2876
3392
  summary: result.snapshot.summary,
2877
3393
  changed: result.changed,
3394
+ // PTC 通道绕过 schema,坏词表/坏字段在这里回声,模型下一轮能自己修。
3395
+ warnings: result.warnings,
2878
3396
  inFlight: anchor.board.inFlight.slice(0, 6),
2879
3397
  time: {
2880
3398
  steps: anchor.time.steps,
@@ -2894,11 +3412,38 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2894
3412
  () =>
2895
3413
  commands.register({
2896
3414
  name: 'progress',
2897
- description: '启用/关闭进度板工具(默认不加载,避免 token 开销)',
2898
- input: { hint: '[on|off]' },
3415
+ description: '启用/关闭进度板工具;`plan <slug>` 绑定 plan 文档,`plan off` 解绑',
3416
+ input: { hint: '[on|off|plan <slug>|plan off]' },
2899
3417
  handler: ({ agent, rawInput }) => {
2900
3418
  const sessionId = sessionOfAgent(agent)
2901
- const mode = String(rawInput || '').trim().toLowerCase()
3419
+ const raw = String(rawInput || '').trim()
3420
+ const mode = raw.toLowerCase()
3421
+ // /progress plan <slug> | /progress plan off —— plan 文档显式绑定
3422
+ if (mode === 'plan' || mode.startsWith('plan ')) {
3423
+ const state = ensureState(sessionId)
3424
+ const arg = raw.slice(4).trim()
3425
+ if (!arg || arg.toLowerCase() === 'off') {
3426
+ state.planSlug = ''
3427
+ void persist(sessionId)
3428
+ planCache.delete(sessionId)
3429
+ return { kind: 'success', text: 'plan 文档已解绑;恢复按 mtime 自动选最新计划目录。' }
3430
+ }
3431
+ const cwd = sessionCwd(agent && agent.session)
3432
+ if (!cwd) {
3433
+ return { kind: 'error', text: '拿不到本会话 cwd,无法校验 plan 目录(宿主版本可能未暴露 session.cwd)。' }
3434
+ }
3435
+ const list = planDirCandidates(cwd).map((x) => x.slug)
3436
+ if (!list.includes(arg)) {
3437
+ return {
3438
+ kind: 'error',
3439
+ text: `找不到计划 "${arg}"(需含 tasks.md 或 checklist.md)。可用:${list.slice(0, 5).join('、') || '(无)'}`,
3440
+ }
3441
+ }
3442
+ state.planSlug = arg
3443
+ void persist(sessionId)
3444
+ planCache.delete(sessionId)
3445
+ return { kind: 'success', text: `plan 文档已绑定到 "${arg}";观察块与助手输入将读取它的 tasks/checklist/spec。` }
3446
+ }
2902
3447
  if (mode === 'off') {
2903
3448
  setEnabled(sessionId, false)
2904
3449
  return { kind: 'success', text: '进度板已关闭;Agent 不再加载进度工具,文件上报协议恢复,手动编辑仍会保存。' }
@@ -2906,7 +3451,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2906
3451
  setEnabled(sessionId, true)
2907
3452
  return {
2908
3453
  kind: 'success',
2909
- text: '进度板已启用;之后在主界面发消息时 Agent 会自动更新,收起侧栏也不会关闭。输入 /progress off 可关闭。',
3454
+ text: '进度板已启用;之后在主界面发消息时 Agent 会自动更新,收起侧栏也不会关闭。输入 /progress off 可关闭;/progress plan <slug> 可绑定计划目录。',
2910
3455
  }
2911
3456
  },
2912
3457
  }),