dsh-progress-union 0.4.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
@@ -51,6 +51,18 @@ export const Config = z.object({
51
51
  maxReconcileIntervalMs: z.number().step(1000).min(0).default(60000).volatile(),
52
52
  mirrorThrottleMs: z.number().step(1).min(0).default(200).volatile(),
53
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({}),
54
66
  })
55
67
 
56
68
  // —— 路由与存储标识 ——
@@ -75,6 +87,30 @@ const STALE_MS = 10 * 60 * 1000
75
87
  const KICKOFF_COOLDOWN_MS = 60 * 1000
76
88
  const STATUSES = new Set(BOARD_STATUSES)
77
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
+ }
113
+
78
114
  // —— /progress-goal 迷你目标域常量(自建,不复用官方 goals 域)——
79
115
  const GOAL_PHASES = new Set(['idle', 'active', 'paused', 'blocked', 'complete'])
80
116
  const GOAL_SOURCE_KIND = 'plugin:progress-goal-goal' // producer-owned source kind(身份栅栏用)
@@ -97,6 +133,9 @@ const BAD_READ_GRACE_MS = 2000
97
133
  export const name = 'dsh-progress-union'
98
134
  export const inject = ['tools', 'systemPrompt', 'webServer', 'agents', 'commands', 'llm', 'settings']
99
135
 
136
+ // 纯解析函数导出(仅供 test/plan.test.mjs 单测;不在 dsh 契约面上,勿在插件间消费)。
137
+ export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir }
138
+
100
139
  const PROGRESS_POLICY = `## 进度板
101
140
  progress_update 维护用户可见的实时进度板。每项含 title/status/percent/current/next/approach/note。
102
141
  - 每个用户回合开始时先检查进度板:如果板是空的,你的第一个工具调用必须是 progress_update,先建立扁平任务,再执行任何其他工具。不要等做完才补计划。
@@ -177,6 +216,7 @@ function emptyState(sessionId) {
177
216
  items: [],
178
217
  userChanges: [],
179
218
  todoMirror: null, // v0.3.0:自家镜像写入的 hash/at/count,回环识别用
219
+ planSlug: '', // v0.5.0:显式绑定的 plan 目录名(空=按 mtime 自动选)
180
220
  goal: emptyGoal(),
181
221
  }
182
222
  }
@@ -221,8 +261,185 @@ function summarize(items) {
221
261
  }
222
262
  }
223
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
+
224
441
  // —— v0.3.0:板 → 官方 todo 的纯映射(content 唯一非空、in_progress ≤1)——
225
- function boardToTodos(state, maxItems) {
442
+ function boardToTodos(state, maxItems, opts) {
226
443
  const limit = Math.max(1, Number(maxItems) || 12)
227
444
  const items = (Array.isArray(state && state.items) ? state.items : [])
228
445
  .slice()
@@ -231,6 +448,8 @@ function boardToTodos(state, maxItems) {
231
448
  const todos = []
232
449
  const seen = new Set()
233
450
  let doingSeen = false
451
+ // v0.5.0:rich 模式把 group / percent 一并带出(任务表转出的步骤细节不再被削平)。
452
+ const rich = Boolean(opts && opts.rich)
234
453
  for (const item of items) {
235
454
  const content = String(item && item.title || '').trim()
236
455
  if (!content || seen.has(content)) continue
@@ -240,7 +459,13 @@ function boardToTodos(state, maxItems) {
240
459
  else if (item.status === 'doing') {
241
460
  if (!doingSeen) { status = 'in_progress'; doingSeen = true }
242
461
  }
243
- 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)
244
469
  }
245
470
  return todos
246
471
  }
@@ -352,6 +577,10 @@ function parseProgressFile(file, key) {
352
577
  try {
353
578
  const parsed = JSON.parse(readJsonText(file))
354
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 = ''
355
584
  lastGoodByKey.set(key, parsed)
356
585
  lastGoodAt = Date.now()
357
586
  return parsed
@@ -368,8 +597,11 @@ function parseProgressFile(file, key) {
368
597
  }
369
598
 
370
599
  // 鲸程兼容层:读 $DSH_HOME/dsh-progress/<sid>.json 上报(板关闭时的增强层)。
371
- function readFileTasks() {
600
+ // activeSids:调用方传入的活跃会话集合(本函数在模块级,不能直接引用 apply 闭包里的
601
+ // states/taskMap——那次越界引用会让 /dsh-progress/status 整条路由抛错)。
602
+ function readFileTasks(activeSids) {
372
603
  const out = []
604
+ const active = activeSids instanceof Set ? activeSids : new Set()
373
605
  let names = []
374
606
  try {
375
607
  names = fs.readdirSync(PROGRESS_DIR).filter((n) => n.endsWith('.json'))
@@ -382,14 +614,20 @@ function readFileTasks() {
382
614
  if (parsed) out.push({ ...parsed, reportId: parsed.session ? String(parsed.session) : name.replace(/\.json$/, ''), source: 'dir' })
383
615
  }
384
616
  // 24 小时未更新的分文件顺手清理(活跃会话个位数,逐次 stat 可忽略)
617
+ // v0.5.0 修正:**不得删掉还在跑的会话的上报文件**。旧逻辑只看 mtime,把「常驻
618
+ // 会话超过 24h 没更新进度文件」与「过期垃圾」混为一谈——那次清理会直接顶掉
619
+ // 用户正看着的任务条。现在只有「文件里声明的 session 不在活跃集合里」才允许删。
385
620
  for (const name of names) {
386
621
  const full = path.join(PROGRESS_DIR, name)
387
622
  try {
388
623
  const st = fs.statSync(full)
389
- if (Date.now() - st.mtimeMs > PROGRESS_DIR_KEEP_MS) {
390
- fs.unlinkSync(full)
391
- lastGoodByKey.delete(full)
392
- }
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)
393
631
  } catch (_err) {}
394
632
  }
395
633
  const legacy = parseProgressFile(PROGRESS_FILE, PROGRESS_FILE)
@@ -578,6 +816,18 @@ const DEFAULT_CONFIG = {
578
816
  // v0.3.0:板 → 官方 todo 镜像与冲突裁决。默认 reconcile;不想要行为变更可在设置页关。
579
817
  todoSync: 'reconcile', // off | mirror | reconcile
580
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
+ },
581
831
  // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案):
582
832
  // mode: 'registered' 走宿主 llm.stream(选已注册 llm-pi-ai provider/model);
583
833
  // 'direct' 走自建 OpenAI 兼容端点(baseUrl/apiKey/model);'' 关。
@@ -668,6 +918,26 @@ export async function apply(ctx, config) {
668
918
  return out
669
919
  }
670
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 })
671
941
  const now = () => Date.now()
672
942
 
673
943
  // —— 状态容器 ——
@@ -1036,7 +1306,7 @@ export async function apply(ctx, config) {
1036
1306
  return undefined
1037
1307
  }
1038
1308
 
1039
- function applyOneChange(state, change, origin, at, records) {
1309
+ function applyOneChange(state, change, origin, at, records, warnings) {
1040
1310
  if (!isObject(change)) throw new Error('changes 的每一项必须是对象')
1041
1311
  const remove = change.remove === true
1042
1312
  const existing = findItem(state, change)
@@ -1057,7 +1327,13 @@ export async function apply(ctx, config) {
1057
1327
  if (state.items.length >= MAX_ITEMS) throw new Error(`任务数量已达到上限 ${MAX_ITEMS}`)
1058
1328
  const title = text(change.title, MAX_TITLE)
1059
1329
  if (!title) throw new Error('任务标题不能为空')
1060
- 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'
1061
1337
  const percent = status === 'done' ? 100 : Math.max(0, Math.min(100, Math.round(finiteNumber(change.percent) ?? 0)))
1062
1338
  const item = {
1063
1339
  id: newItemId(),
@@ -1100,12 +1376,21 @@ export async function apply(ctx, config) {
1100
1376
  }
1101
1377
 
1102
1378
  if (typeof change.status === 'string') {
1103
- if (!STATUSES.has(change.status)) throw new Error(`未知状态:${change.status}`)
1104
- record('status', existing.status, change.status)
1105
- existing.status = change.status
1106
- if (change.status === 'done') {
1107
- record('percent', existing.percent, 100)
1108
- 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
+ }
1109
1394
  }
1110
1395
  }
1111
1396
 
@@ -1172,8 +1457,9 @@ export async function apply(ctx, config) {
1172
1457
  // 变成重复或半应用任务(board 原教训,原样保留)。
1173
1458
  const working = clone(state)
1174
1459
  const records = []
1460
+ const warnings = []
1175
1461
  const at = now()
1176
- for (const change of changes) applyOneChange(working, change, origin, at, records)
1462
+ for (const change of changes) applyOneChange(working, change, origin, at, records, warnings)
1177
1463
 
1178
1464
  let revisionChanged = false
1179
1465
  if (records.length > 0) {
@@ -1212,6 +1498,10 @@ export async function apply(ctx, config) {
1212
1498
  if (revisionChanged) notifyAnchor(sessionId, working.revision)
1213
1499
  // 唯一写板入口:持久化之后调度 todo 镜像(200ms 去抖,off 时直接返回)。
1214
1500
  if (revisionChanged) scheduleTodoMirror(sessionId)
1501
+ // v0.5.0:sync 模式下把已完成的项回勾到 tasks.md(默认 read 时内部直接返回 0)。
1502
+ if (revisionChanged) {
1503
+ try { maybeEchoBack(sessionId) } catch (_err) {}
1504
+ }
1215
1505
  }
1216
1506
  // 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
1217
1507
  // 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
@@ -1226,7 +1516,7 @@ export async function apply(ctx, config) {
1226
1516
  fields: record.fields.map((field) => field.field),
1227
1517
  }
1228
1518
  })
1229
- return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean) }
1519
+ return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean), warnings }
1230
1520
  }
1231
1521
 
1232
1522
  // ==========================================================================
@@ -1620,8 +1910,17 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1620
1910
  if (typeof d.name !== 'string' || !d.name) return
1621
1911
  const o = obsOf(sid)
1622
1912
  const at = now()
1623
- o.tools.push({ at, name: d.name, brief: briefArgs(d.arguments) })
1624
- 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
+ }
1625
1924
  // 文件改动(事实级):任何带路径类参数的工具调用都记一笔,同路径去重留最新
1626
1925
  const file = filePathOf(d.arguments)
1627
1926
  if (file) {
@@ -1785,6 +2084,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1785
2084
  o.lastAssistantAt = at
1786
2085
  const lastOutput = o.outputs[o.outputs.length - 1]
1787
2086
  const files = Array.isArray(o.files) ? o.files.slice(-4).map((f) => f.path) : []
2087
+ const planText = planBrief(sid)
1788
2088
  const lines = [
1789
2089
  `目标:${state.goal && state.goal.phase === 'active' ? JSON.stringify(state.goal.objective) : '(无)'}`,
1790
2090
  ...renderChecklist(state, cfg.observer.maxItems),
@@ -1792,6 +2092,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1792
2092
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1793
2093
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1794
2094
  ]
2095
+ // plan 文档是**助手细化板的主原料**:用户明确要求让任务管理 LLM 读 spec/tasks/checklist。
2096
+ if (planText) lines.push(planText)
1795
2097
  try {
1796
2098
  const raw = await callAssistant({ system: ASSISTANT_SYSTEM, user: lines.join('\n'), a })
1797
2099
  const proposal = parseProposal(raw)
@@ -1828,6 +2130,156 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1828
2130
  return lines
1829
2131
  }
1830
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
+
1831
2283
  /**
1832
2284
  * 观察块:每请求重建(systemPrompt.context),不进历史累积。
1833
2285
  * = 清单(checklist)+ 官方 todo 进度 + 最近输出 + 最近动作 +(滞后时)催办。
@@ -1859,7 +2311,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1859
2311
  const lastOutput = o.outputs[o.outputs.length - 1]
1860
2312
  if (lastOutput) lines.push(`最近输出:「${lastOutput.text}」`)
1861
2313
  const tools = o.tools.slice(-cfg.observer.maxTools)
1862
- 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 : ''}`)
1863
2316
  const synced = o.stepsSinceModel > 0 ? `${o.stepsSinceModel} 步前` : '本回合'
1864
2317
  const late = modelIsLate(sid, at)
1865
2318
  if (late) {
@@ -1869,6 +2322,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1869
2322
  if (o.assistantNote) lines.push(`助手审查:${o.assistantNote}`)
1870
2323
  if (o.roundDraft) lines.push(`助手轮次草案(仅供参考):${o.roundDraft}`)
1871
2324
  if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
2325
+ const planRow = planLine(sid)
2326
+ if (planRow) lines.push(planRow)
1872
2327
  return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
1873
2328
  }
1874
2329
 
@@ -1946,12 +2401,16 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1946
2401
  }
1947
2402
 
1948
2403
  // 子智能体识别:delegationDepth>0 即子会话;parentSession 存在才采用,拿不到不硬猜。
2404
+ // 注意:这些字段在现行宿主上位于 session **顶层**(实测见 findings.md §4 t01),
2405
+ // header 只是兼容兜底——旧代码只读 header,导致 isSub/parentId 一直没生效。
1949
2406
  function markLineage(task, session) {
1950
2407
  try {
1951
- const hd = session && session.header
1952
- if (!hd || !task) return
1953
- if (typeof hd.delegationDepth === 'number' && hd.delegationDepth > 0) task.isSub = true
1954
- 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)
1955
2414
  } catch (_err) {}
1956
2415
  }
1957
2416
 
@@ -2169,7 +2628,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2169
2628
  }
2170
2629
  // 鲸程兼容层:board 关闭的会话若有文件上报任务,合并/独立成条(blocked 也要显示)。
2171
2630
  const reportsByKey = new Map()
2172
- for (const rep of readFileTasks()) {
2631
+ for (const rep of readFileTasks(new Set([...states.keys(), ...taskMap.keys()]))) {
2173
2632
  const key = String(rep.reportId || 'legacy')
2174
2633
  const prev = reportsByKey.get(key)
2175
2634
  if (!prev || (Number(rep.updatedAt) || 0) >= (Number(prev.updatedAt) || 0)) reportsByKey.set(key, rep)
@@ -2285,11 +2744,35 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2285
2744
  if (!event) return
2286
2745
  const sid = session && session.id ? String(session.id) : 'default'
2287
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
+ }
2288
2752
  // 观察者原料:最近输出(assistant/message)与最近动作(tool/call)都是会话事实
2289
2753
  if (type === 'tool/call') {
2290
2754
  recordTool(sid, event.data)
2291
2755
  return
2292
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
+ }
2293
2776
  if (type === 'assistant/message') {
2294
2777
  recordOutput(sid, event.data)
2295
2778
  return
@@ -2383,7 +2866,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2383
2866
  if (task.isSub && pendingText) task.subTitled = true
2384
2867
  task.project = ''
2385
2868
  try {
2386
- 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)
2387
2872
  if (cwd) task.project = path.basename(cwd)
2388
2873
  } catch (_err) {}
2389
2874
  } else {
@@ -2878,6 +3363,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2878
3363
  revision: { type: 'number' },
2879
3364
  summary: { type: 'object', additionalProperties: true },
2880
3365
  changed: { type: 'array', items: { type: 'object', additionalProperties: true } },
3366
+ warnings: { type: 'array', items: { type: 'string' } },
2881
3367
  },
2882
3368
  },
2883
3369
  render(_args, value) {
@@ -2905,6 +3391,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2905
3391
  agentSeenRevision: result.snapshot.agentSeenRevision,
2906
3392
  summary: result.snapshot.summary,
2907
3393
  changed: result.changed,
3394
+ // PTC 通道绕过 schema,坏词表/坏字段在这里回声,模型下一轮能自己修。
3395
+ warnings: result.warnings,
2908
3396
  inFlight: anchor.board.inFlight.slice(0, 6),
2909
3397
  time: {
2910
3398
  steps: anchor.time.steps,
@@ -2924,11 +3412,38 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2924
3412
  () =>
2925
3413
  commands.register({
2926
3414
  name: 'progress',
2927
- description: '启用/关闭进度板工具(默认不加载,避免 token 开销)',
2928
- input: { hint: '[on|off]' },
3415
+ description: '启用/关闭进度板工具;`plan <slug>` 绑定 plan 文档,`plan off` 解绑',
3416
+ input: { hint: '[on|off|plan <slug>|plan off]' },
2929
3417
  handler: ({ agent, rawInput }) => {
2930
3418
  const sessionId = sessionOfAgent(agent)
2931
- 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
+ }
2932
3447
  if (mode === 'off') {
2933
3448
  setEnabled(sessionId, false)
2934
3449
  return { kind: 'success', text: '进度板已关闭;Agent 不再加载进度工具,文件上报协议恢复,手动编辑仍会保存。' }
@@ -2936,7 +3451,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2936
3451
  setEnabled(sessionId, true)
2937
3452
  return {
2938
3453
  kind: 'success',
2939
- text: '进度板已启用;之后在主界面发消息时 Agent 会自动更新,收起侧栏也不会关闭。输入 /progress off 可关闭。',
3454
+ text: '进度板已启用;之后在主界面发消息时 Agent 会自动更新,收起侧栏也不会关闭。输入 /progress off 可关闭;/progress plan <slug> 可绑定计划目录。',
2940
3455
  }
2941
3456
  },
2942
3457
  }),