dsh-progress-union 0.7.0-rc.2 → 0.7.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
@@ -601,8 +601,110 @@ function resultDigest(text, failed) {
601
601
  return ((failed ? '失败:' : '结果:') + (s.length > 54 ? s.slice(0, 54) + '…' : s)).slice(0, 60)
602
602
  }
603
603
 
604
+ // ============================================================================
605
+ // v0.7.0 R3:板格式校验(纯函数)+ LLM 任务操作的三个 system 常量
606
+ // validateBoard 只吃数据、不碰状态:ops 路由拿到模型返回后先校验再落盘,
607
+ // errors=必须拦(非法数据),warnings=只提示(可疑但可写)。
608
+ // ============================================================================
609
+
610
+ const OPS_MAX_ITEMS = 60
611
+ const OPS_MAX_TITLE = 180
612
+ const OPS_MAX_CHANGES = 8
613
+ const OPS_KINDS = new Set(['refine', 'mutate', 'ask', 'validate'])
614
+ // R4:只认这三类结构性变更(增/删/排序)——它们会让「板上第几项在做什么」整体位移。
615
+ const MAJOR_CHANGE_TAG = 'progress-major-change'
616
+ const STRUCTURAL_KINDS = new Set(['add', 'remove', 'order'])
617
+
618
+ /**
619
+ * 校验一份板项集合:接受 `[{...}]` 或 `{items:[...]}`。
620
+ * 硬错(errors):非数组 / 项数超上限 / 项不是对象 / title 缺失或过长 /
621
+ * status 不在枚举 / percent 越界 / status=done 但 percent≠100。
622
+ * 软提示(warnings):空板 / title 重复 / order 重复 / 多个 doing。
623
+ * 绝不抛错:返回 `{ok,count,errors,warnings}`,调用方自己决定拦不拦。
624
+ */
625
+ function validateBoard(input) {
626
+ const errors = []
627
+ const warnings = []
628
+ const items = Array.isArray(input)
629
+ ? input
630
+ : (isObject(input) && Array.isArray(input.items) ? input.items : null)
631
+ if (!items) {
632
+ return { ok: false, count: 0, errors: ['items 必须是数组'], warnings }
633
+ }
634
+ if (items.length === 0) warnings.push('空板:没有任何任务项')
635
+ if (items.length > OPS_MAX_ITEMS) {
636
+ errors.push(`项数 ${items.length} 超过上限 ${OPS_MAX_ITEMS}`)
637
+ }
638
+ const titles = new Set()
639
+ const orders = new Map()
640
+ let doing = 0
641
+ items.forEach((item, index) => {
642
+ const at = `第 ${index + 1} 项`
643
+ if (!isObject(item)) {
644
+ errors.push(`${at}不是对象`)
645
+ return
646
+ }
647
+ const title = String(item.title == null ? '' : item.title).trim()
648
+ if (!title) errors.push(`${at}缺少 title`)
649
+ else if (title.length > OPS_MAX_TITLE) errors.push(`${at} title 过长(${title.length} 字 >${OPS_MAX_TITLE})`)
650
+ else if (titles.has(title)) warnings.push(`${at} title 与前面重复:${title}`)
651
+ else titles.add(title)
652
+ let status = 'todo'
653
+ if (item.status !== undefined && item.status !== null && String(item.status).trim() !== '') {
654
+ status = normalizeStatus(item.status)
655
+ if (status === undefined) errors.push(`${at} status 非法:${item.status}(合法值 todo|doing|done|blocked)`)
656
+ }
657
+ if (status === 'doing') doing += 1
658
+ if (item.percent !== undefined && item.percent !== null) {
659
+ const pct = Number(item.percent)
660
+ if (!Number.isFinite(pct) || pct < 0 || pct > 100) {
661
+ errors.push(`${at} percent 越界:${item.percent}(应为 0-100)`)
662
+ } else if (status === 'done' && Math.round(pct) !== 100) {
663
+ errors.push(`${at} status=done 但 percent=${Math.round(pct)}(done 必须 100)`)
664
+ }
665
+ }
666
+ if (item.order !== undefined && item.order !== null) {
667
+ const order = Number(item.order)
668
+ if (!Number.isFinite(order)) errors.push(`${at} order 不是数字:${item.order}`)
669
+ else {
670
+ const o = Math.trunc(order)
671
+ if (orders.has(o)) warnings.push(`order 重复:${o}(第 ${orders.get(o) + 1} 项与第 ${index + 1} 项)`)
672
+ else orders.set(o, index)
673
+ }
674
+ }
675
+ })
676
+ if (doing > 1) warnings.push(`同时 doing ${doing} 项(约定只有一项在做)`)
677
+ return { ok: errors.length === 0, count: items.length, errors, warnings }
678
+ }
679
+
680
+ // ops 三路 system:严格 JSON、统一形状 `{changes,answer}`、最多 8 条改动。
681
+ // 只有 refine/mutate 会动板;ask 只回文本,模型若硬塞 changes 也会被路由丢掉。
682
+ const OPS_REFINE_SYSTEM = 'You refine a user-facing task board so the work is easier to track. '
683
+ + 'Given the board checklist and an optional focus item, split coarse items into smaller verifiable ones, '
684
+ + 'give each a concrete title and (when known) current/next text. '
685
+ + 'Rules: at most ' + OPS_MAX_CHANGES + ' changes; only ONE item may be doing; keep existing ids when editing; '
686
+ + 'never invent completed work; never touch items outside the given board. '
687
+ + 'Output strictly ONE JSON object: '
688
+ + '{"changes":[{"kind":"add|edit|remove","id"?:string,"title"?:string,"status"?:"todo|doing|done|blocked","percent"?:0-100,"current"?:string,"next"?:string,"order"?:number}],"answer":"<one line, same language as the board>"}. '
689
+ + 'Respond with the JSON object only — no prose, no code fences.'
690
+
691
+ const OPS_MUTATE_SYSTEM = 'You apply one user instruction to a user-facing task board: add, edit, reorder or remove items. '
692
+ + 'Rules: change only what the instruction asks for; at most ' + OPS_MAX_CHANGES + ' changes; use the ids given in the board for edit/remove; '
693
+ + 'use "order" (0-based) to reorder; never invent completed work; if the instruction is not actionable on a task board, '
694
+ + 'return zero changes and say why in the answer. '
695
+ + 'Output strictly ONE JSON object: '
696
+ + '{"changes":[{"kind":"add|edit|remove","id"?:string,"title"?:string,"status"?:"todo|doing|done|blocked","percent"?:0-100,"current"?:string,"next"?:string,"order"?:number}],"answer":"<one line, same language as the board>"}. '
697
+ + 'Respond with the JSON object only — no prose, no code fences.'
698
+
699
+ const OPS_ASK_SYSTEM = 'You answer ONE short question about a task board, using ONLY the checklist given to you. '
700
+ + 'You must not change the board: always return an empty changes array. '
701
+ + 'If the board does not contain the answer, say so plainly instead of guessing. '
702
+ + 'Answer in the same language as the board, in at most 600 characters. '
703
+ + 'Output strictly ONE JSON object: {"changes":[],"answer":"<text>"}. '
704
+ + 'Respond with the JSON object only — no prose, no code fences.'
705
+
604
706
  // 纯解析函数导出(仅供 test/plan.test.mjs 单测;不在 dsh 契约面上,勿在插件间消费)。
605
- export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir, classifyDownload, parseProgress, unwrapAct, isDownloadItem, describeToolStep, glossCommand, resultDigest }
707
+ export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir, classifyDownload, parseProgress, unwrapAct, isDownloadItem, describeToolStep, glossCommand, resultDigest, validateBoard }
606
708
 
607
709
  const PROGRESS_POLICY = `## 进度板
608
710
  progress_update 维护用户可见的实时进度板。每项含 title/status/percent/current/next/approach/note。
@@ -2107,6 +2209,7 @@ export async function apply(ctx, config) {
2107
2209
  for (const change of changes) applyOneChange(working, change, origin, at, records, warnings)
2108
2210
 
2109
2211
  let revisionChanged = false
2212
+ let notified = false
2110
2213
  if (records.length > 0) {
2111
2214
  working.revision += 1
2112
2215
  working.updatedAt = at
@@ -2149,6 +2252,11 @@ export async function apply(ctx, config) {
2149
2252
  if (revisionChanged) {
2150
2253
  try { maybeEchoBack(sessionId) } catch (_err) {}
2151
2254
  }
2255
+ // v0.7.0 R4:用户或侧边栏 LLM 操作把板改出了结构性变化 → 落输入队列提醒。
2256
+ // 主模型自己写板(origin='agent')不提醒——它知道刚写了什么;观察者自动同步也不提醒。
2257
+ if ((origin === 'user' || origin === 'ops') && records.length > 0) {
2258
+ try { notified = maybeNotifyMajorChange(sessionId, records, working.revision) } catch (_err) {}
2259
+ }
2152
2260
  }
2153
2261
  // 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
2154
2262
  // 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
@@ -2163,7 +2271,7 @@ export async function apply(ctx, config) {
2163
2271
  fields: record.fields.map((field) => field.field),
2164
2272
  }
2165
2273
  })
2166
- return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean), warnings }
2274
+ return { snapshot: publicSnapshot(working), changed: changed.filter(Boolean), warnings, notified }
2167
2275
  }
2168
2276
 
2169
2277
  // ==========================================================================
@@ -2674,6 +2782,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2674
2782
  const at = now()
2675
2783
  o = { outputs: [], tools: [], lastBoardAt: at, lastModelAt: at, stepsSinceBoard: 0, stepsSinceModel: 0, lastAutoSyncAt: 0,
2676
2784
  assistantCalls: 0, lastAssistantAt: 0, assistantNote: '', assistantError: '',
2785
+ // v0.7.0 R4:重大变更提醒的去重位。turnSeq 每个用户回合 +1,noticeTurn 记
2786
+ // 「哪个回合已经提醒过」——同回合再改板只提一次(合并),同 rev 不重投。
2787
+ turnSeq: 0, noticeTurn: -1, noticeRev: 0, lastNoticeAt: 0, noticeTier: '',
2677
2788
  // v0.7.0 R1/R2:下载事实态。都是单值(非环):长会话下 observers 不随事件数增长。
2678
2789
  lastDownload: null, lastResult: null, downloadGuess: null }
2679
2790
  observers.set(sid, o)
@@ -2682,11 +2793,13 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2682
2793
  }
2683
2794
 
2684
2795
  // board 写后重置计数器:origin='observer'/'assistant' 只刷新"板新鲜度",不抵消"模型未同步"。
2796
+ // v0.7.0 R3:origin='ops' 同理——侧边栏的 LLM 操作不是主模型写的,不能让它
2797
+ // 看起来像「模型刚刚同过步」(否则催办会被静拂,stepsSinceModel 也不会归零)。
2685
2798
  function noteBoardWrite(sid, origin, at) {
2686
2799
  const o = obsOf(sid)
2687
2800
  o.lastBoardAt = at
2688
2801
  o.stepsSinceBoard = 0
2689
- if (origin !== 'observer' && origin !== 'assistant') {
2802
+ if (origin !== 'observer' && origin !== 'assistant' && origin !== 'ops') {
2690
2803
  o.lastModelAt = at
2691
2804
  o.stepsSinceModel = 0
2692
2805
  }
@@ -3051,6 +3164,295 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3051
3164
  return lines
3052
3165
  }
3053
3166
 
3167
+ // ==========================================================================
3168
+ // B2b. v0.7.0 R4:重大(结构性)变更 → 输入队列
3169
+ // running → agent.steer(本回合 next-step,黄档可见可编辑);
3170
+ // idle → agent.followup(下一回合排队)。消息 source.kind='user',
3171
+ // 这样 dsh-input-traffic 的 isHumanSteer(kind===undefined||kind==='user')
3172
+ // 会把当成人话留在黄档;正文裹 <progress-major-change rev="N"> 供幂等与溯源。
3173
+ // 本插件不拦截、不强制:发完就返回,失败只记日志。
3174
+ // ==========================================================================
3175
+
3176
+ function structuralOf(records) {
3177
+ return (records || []).filter((r) => r && (r.kind === 'add' || r.kind === 'remove'
3178
+ || (r.kind === 'edit' && (r.fields || []).some((f) => f && f.field === 'order'))))
3179
+ }
3180
+
3181
+ function renderMajorChange(rev, structural, state) {
3182
+ const lines = structural.map((r) => {
3183
+ if (r.kind === 'remove') return `- 删除:${r.title || r.itemId}`
3184
+ if (r.kind === 'add') return `+ 新增:${r.title || r.itemId}`
3185
+ const f = (r.fields || []).find((x) => x && x.field === 'order')
3186
+ return `↕ 排序:${r.title || r.itemId}${f ? `(${f.from} → ${f.to})` : ''}`
3187
+ })
3188
+ const open = `<${MAJOR_CHANGE_TAG} rev="${rev}">`
3189
+ const close = `</${MAJOR_CHANGE_TAG}>`
3190
+ return [
3191
+ open,
3192
+ '进度板发生了结构性变更(用户在面板直接改板,或通到侧边栏的 LLM 操作):',
3193
+ ...lines,
3194
+ '',
3195
+ '当前清单(以此为准):',
3196
+ ...renderChecklist(state, cfg.observer.maxItems),
3197
+ '',
3198
+ '不要按旧顺序推进;动手前先用 progress_update 对账(无变化传 changes=[],并带 ackUserRevision)。',
3199
+ close,
3200
+ ].join('\n')
3201
+ }
3202
+
3203
+ /**
3204
+ * @returns true 表示确实往队列里丢了一条(失败/去重返回 false,绝不抛)。
3205
+ */
3206
+ function maybeNotifyMajorChange(sid, records, rev) {
3207
+ if (!cfg.notifyMajorChanges) return false
3208
+ if (!isEnabled(sid)) return false
3209
+ const structural = structuralOf(records)
3210
+ if (structural.length === 0) return false
3211
+ const revN = Math.trunc(Number(rev) || 0)
3212
+ if (revN <= 0) return false
3213
+ const o = obsOf(sid)
3214
+ // 幂等两层:同 rev 不重投(HTTP 重试/重放);同回合只提一次(多改几次合成一条)。
3215
+ if (o.noticeRev === revN) return false
3216
+ if (o.noticeTurn === o.turnSeq) return false
3217
+ const agent = liveAgentOf(sid)
3218
+ if (!agent) return false
3219
+ const message = {
3220
+ id: `pmc-${revN.toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
3221
+ role: 'user',
3222
+ content: [{ type: 'text', text: renderMajorChange(revN, structural, ensureState(sid)) }],
3223
+ source: { kind: 'user', producer: 'dsh-progress-union', rev: revN },
3224
+ }
3225
+ const running = agent.status === 'running' && typeof agent.steer === 'function'
3226
+ if (!running && typeof agent.followup !== 'function') return false
3227
+ try {
3228
+ if (running) agent.steer(message)
3229
+ else agent.followup(message)
3230
+ } catch (err) {
3231
+ try {
3232
+ ctx.logger?.warn?.(`progress-union: major-change notice failed: ${err instanceof Error ? err.message : String(err)}`)
3233
+ } catch (_logErr) {}
3234
+ return false
3235
+ }
3236
+ o.noticeRev = revN
3237
+ o.noticeTurn = o.turnSeq
3238
+ o.lastNoticeAt = now()
3239
+ o.noticeTier = running ? 'next-step' : 'next-turn'
3240
+ return true
3241
+ }
3242
+
3243
+ // ==========================================================================
3244
+ // B2c. v0.7.0 R3:侧边栏 LLM 任务操作(拆分 / 问询 / 增删改排序 / 校验)
3245
+ // 只复用既有辅助通道 callAssistant;不新开顶级标签、零新增依赖。
3246
+ // ==========================================================================
3247
+
3248
+ // provider/model 候选:照 prime-memory 口径——先问 llm.listProviders(),
3249
+ // 再读 agentDefaultModel.currentSelection() 拿宿主当前选择。服务缺失就空数组,
3250
+ // 面板据此隐藏下拉(而不是报错)。
3251
+ async function opsProviders() {
3252
+ const providers = []
3253
+ const src = ctx.llm && typeof ctx.llm.listProviders === 'function' ? ctx.llm : llm
3254
+ try {
3255
+ const list = src && typeof src.listProviders === 'function' ? await src.listProviders() : []
3256
+ for (const p of list || []) {
3257
+ if (!p || typeof p !== 'object') continue
3258
+ const id = String(p.id ?? p.name ?? '').trim()
3259
+ if (!id) continue
3260
+ const models = (Array.isArray(p.models) ? p.models : [])
3261
+ .map((m) => (typeof m === 'string' ? { id: m, label: m }
3262
+ : (m && m.id ? { id: String(m.id), label: String(m.label ?? m.name ?? m.id) } : null)))
3263
+ .filter(Boolean)
3264
+ providers.push({ id, label: String(p.label ?? p.displayName ?? id), models })
3265
+ }
3266
+ } catch (_err) {}
3267
+ let selection = null
3268
+ try {
3269
+ selection = ctx.get('agentDefaultModel')?.currentSelection?.() ?? null
3270
+ } catch (_err) {}
3271
+ const a = liveAssistant()
3272
+ const sel = isObject(selection) ? { provider: String(selection.provider ?? ''), model: String(selection.model ?? '') } : { provider: '', model: '' }
3273
+ return {
3274
+ ok: true,
3275
+ providers,
3276
+ default: sel.provider && sel.model ? sel : { provider: String(a.provider || ''), model: String(a.model || '') },
3277
+ configured: { mode: String(a.mode || ''), provider: String(a.provider || ''), model: String(a.model || '') },
3278
+ }
3279
+ }
3280
+
3281
+ // 面板显式给了 provider/model → 走宿主 registered(下拉选的就是宿主已注册渠道);
3282
+ // 没选就回退设置页的 mode。两边都凑不齐可用组合则返回 null(路由当 400,不进 LLM)。
3283
+ function opsAssistantArgs(body) {
3284
+ const base = liveAssistant()
3285
+ const reqProvider = String(body && body.provider ? body.provider : '').trim()
3286
+ const reqModel = String(body && body.model ? body.model : '').trim()
3287
+ const provider = reqProvider || String(base.provider || '').trim()
3288
+ const model = reqModel || String(base.model || '').trim()
3289
+ const explicit = reqProvider !== '' || reqModel !== ''
3290
+ const mode = explicit && provider && model ? 'registered' : String(base.mode || '')
3291
+ if (mode === 'registered') {
3292
+ if (!llm || typeof llm.stream !== 'function' || !provider || !model) return null
3293
+ return { ...base, mode: 'registered', provider, model, maxSlotChanges: OPS_MAX_CHANGES }
3294
+ }
3295
+ if (mode === 'direct') {
3296
+ if (!String(base.baseUrl || '').trim() || !model) return null
3297
+ return { ...base, mode: 'direct', model }
3298
+ }
3299
+ return null
3300
+ }
3301
+
3302
+ // 喂给模型的板必须带 id,否则它无法指认“edit/remove 哪一项”。
3303
+ function renderOpsBoard(state, maxItems) {
3304
+ const items = state.items.slice().sort((a, b) => a.order - b.order)
3305
+ const lines = items.slice(0, maxItems).map((item) => {
3306
+ const bits = [`${item.id} | ${item.status} ${item.percent}% | ${item.title}`]
3307
+ if (item.current) bits.push(`当前:${item.current}`)
3308
+ if (item.next) bits.push(`下一步:${item.next}`)
3309
+ if (item.note) bits.push(`备注:${item.note.slice(0, 160)}`)
3310
+ return bits.join(' · ')
3311
+ })
3312
+ if (items.length > maxItems) lines.push(`…另有 ${items.length - maxItems} 项未列出`)
3313
+ return lines
3314
+ }
3315
+
3316
+ // 模型返的 changes → applyChanges 能吃的形状(≤ 8 条、只认板上已有 id、
3317
+ // 数值全部钉到合法区间)。非法条目直接丢,不为了让某条过就臆造 id。
3318
+ function opsChanges(state, proposal) {
3319
+ const raw = Array.isArray(proposal.changes)
3320
+ ? proposal.changes
3321
+ : (isObject(proposal.board) && Array.isArray(proposal.board.changes) ? proposal.board.changes : [])
3322
+ const byId = new Map(state.items.map((item) => [item.id, item]))
3323
+ const out = []
3324
+ for (const c of raw.slice(0, OPS_MAX_CHANGES)) {
3325
+ if (!isObject(c)) continue
3326
+ const kind = String(c.kind || (c.id ? 'edit' : 'add')).toLowerCase()
3327
+ if (kind === 'add') {
3328
+ const title = text(c.title, MAX_TITLE)
3329
+ if (!title) continue
3330
+ const patch = { title }
3331
+ const st = normalizeStatus(c.status)
3332
+ if (st) patch.status = st
3333
+ if (Number.isFinite(Number(c.percent))) patch.percent = Math.max(0, Math.min(100, Math.round(Number(c.percent))))
3334
+ for (const field of ['current', 'next']) {
3335
+ if (typeof c[field] === 'string' && c[field].trim()) patch[field] = text(c[field], MAX_TEXT)
3336
+ }
3337
+ if (typeof c.note === 'string' && c.note.trim()) patch.note = text(c.note, MAX_NOTE)
3338
+ if (Number.isFinite(Number(c.order))) patch.order = Math.max(0, Math.trunc(Number(c.order)))
3339
+ out.push(patch)
3340
+ } else if (kind === 'remove') {
3341
+ const target = byId.get(String(c.id || ''))
3342
+ || (typeof c.title === 'string' ? state.items.find((item) => item.title === String(c.title).trim()) : undefined)
3343
+ if (target) out.push({ id: target.id, remove: true })
3344
+ } else {
3345
+ const target = byId.get(String(c.id || ''))
3346
+ if (!target) continue
3347
+ const patch = { id: target.id }
3348
+ const st = normalizeStatus(c.status)
3349
+ if (st) patch.status = st
3350
+ if (Number.isFinite(Number(c.percent))) patch.percent = Math.max(0, Math.min(100, Math.round(Number(c.percent))))
3351
+ if (typeof c.title === 'string' && c.title.trim()) patch.title = text(c.title, MAX_TITLE)
3352
+ for (const field of ['current', 'next']) {
3353
+ if (typeof c[field] === 'string' && c[field].trim()) patch[field] = text(c[field], MAX_TEXT)
3354
+ }
3355
+ if (typeof c.note === 'string' && c.note.trim()) patch.note = text(c.note, MAX_NOTE)
3356
+ if (Number.isFinite(Number(c.order))) patch.order = Math.max(0, Math.trunc(Number(c.order)))
3357
+ if (Object.keys(patch).length > 1) out.push(patch)
3358
+ }
3359
+ }
3360
+ return out
3361
+ }
3362
+
3363
+ function badRequest(message) {
3364
+ const error = new Error(message)
3365
+ error.statusCode = 400
3366
+ throw error
3367
+ }
3368
+
3369
+ async function runOps(body) {
3370
+ const sessionId = String(body && body.sessionId ? body.sessionId : '')
3371
+ if (!sessionId || sessionId.length > 240) badRequest('缺少有效的 sessionId')
3372
+ const op = String(body && body.op ? body.op : '').toLowerCase()
3373
+ if (!OPS_KINDS.has(op)) badRequest(`未知操作:${op || '(空)'}(可用 refine|mutate|ask|validate)`)
3374
+ const state = ensureState(sessionId)
3375
+ const question = text(body && body.question, 1200) || ''
3376
+ const targetId = String(body && body.targetId ? body.targetId : '')
3377
+
3378
+ // 校验是纯本地活:不进 LLM、不花 token,面板随时能拿到大磎。
3379
+ if (op === 'validate') {
3380
+ const v = validateBoard(state.items)
3381
+ return {
3382
+ ok: true,
3383
+ op,
3384
+ applied: false,
3385
+ changes: [],
3386
+ warnings: v.errors.concat(v.warnings),
3387
+ answer: v.ok
3388
+ ? `格式校验通过(${v.count} 项${v.warnings.length ? `,${v.warnings.length} 条提醒` : ''})`
3389
+ : `格式校验发现 ${v.errors.length} 处硬错`,
3390
+ validation: v,
3391
+ }
3392
+ }
3393
+ if (op === 'mutate' && !question) badRequest('增删改操作需要一句指令')
3394
+ if (op === 'ask' && !question) badRequest('问询需要一个问题')
3395
+
3396
+ const a = opsAssistantArgs(body)
3397
+ if (!a) badRequest('辅助模型未配置:请在设置页选 provider/model,或在面板下拉里直接指定')
3398
+
3399
+ const cap = Math.max(Number(cfg.observer.maxItems) || 12, 24)
3400
+ const lines = [
3401
+ `操作:${op}`,
3402
+ `板 rev=${state.revision} · 共 ${state.items.length} 项`,
3403
+ '',
3404
+ '<progress-board ids="true">',
3405
+ ...renderOpsBoard(state, cap),
3406
+ '</progress-board>',
3407
+ '',
3408
+ ]
3409
+ if (op === 'refine') {
3410
+ const target = targetId ? state.items.find((item) => item.id === targetId) : null
3411
+ lines.push(target
3412
+ ? `聚焦项:${target.id} — ${target.title}(只拆分这一项,其余不动)`
3413
+ : '聚焦项:未指定,整板粗粒度项都可以细化。')
3414
+ if (question) lines.push(`用户补充:${question}`)
3415
+ } else {
3416
+ lines.push(`指令:${question}`)
3417
+ }
3418
+ const system = op === 'refine' ? OPS_REFINE_SYSTEM : (op === 'mutate' ? OPS_MUTATE_SYSTEM : OPS_ASK_SYSTEM)
3419
+ let raw
3420
+ try {
3421
+ raw = await callAssistant({ system, user: lines.join('\n'), a })
3422
+ } catch (err) {
3423
+ const error = new Error(`辅助模型调用失败:${err instanceof Error ? err.message : String(err)}`)
3424
+ error.statusCode = 502
3425
+ throw error
3426
+ }
3427
+ const proposal = parseProposal(raw)
3428
+ if (!proposal) {
3429
+ const error = new Error('辅助模型没有返回可解析的 JSON')
3430
+ error.statusCode = 502
3431
+ throw error
3432
+ }
3433
+ const answer = text(String(proposal.answer || proposal.note || ''), 1200)
3434
+ if (op === 'ask') {
3435
+ // 问询只回文本:即使模型硬塞了 changes 也不落盘。
3436
+ return { ok: true, op, applied: false, changes: [], warnings: [], answer: answer || '(模型未给出回答)' }
3437
+ }
3438
+ const mapped = opsChanges(state, proposal)
3439
+ if (mapped.length === 0) {
3440
+ return { ok: true, op, applied: false, changes: [], warnings: answer ? [] : ['模型未提出可用改动'], answer: answer || '无需改动' }
3441
+ }
3442
+ const result = await applyChanges({ sessionId, changes: mapped, origin: 'ops' })
3443
+ const post = validateBoard(result.snapshot.items)
3444
+ return {
3445
+ ok: true,
3446
+ op,
3447
+ applied: true,
3448
+ changes: result.changed,
3449
+ warnings: (result.warnings || []).concat(post.errors),
3450
+ answer: answer || `已应用 ${result.changed.length} 条改动`,
3451
+ notified: result.notified === true,
3452
+ snapshot: result.snapshot,
3453
+ }
3454
+ }
3455
+
3054
3456
  // ==========================================================================
3055
3457
  // B3. plan 文档(codeplan 的 spec/tasks/checklist)→ 助手的任务细化原料
3056
3458
  // 实测要点(findings.md §4):cwd 在 session **顶层**;宿主 todo 只认
@@ -3841,6 +4243,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3841
4243
  // 辅助 LLM 的每回合配额:开新回合重置(轮次草案不跨回合复用)
3842
4244
  obsOf(sid).assistantCalls = 0
3843
4245
  obsOf(sid).roundDraft = ''
4246
+ // R4:新回合 = 新的提醒窗口(上一回合提醒过不挡住本回合的结构性变更)
4247
+ obsOf(sid).turnSeq += 1
3844
4248
  if (!task.active) {
3845
4249
  task.active = true
3846
4250
  task.startedAt = now()
@@ -4705,6 +5109,50 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
4705
5109
  }),
4706
5110
  )
4707
5111
 
5112
+ // v0.7.0 R3:侧边栏 LLM 任务操作(只挂 union 主前缀,不进 /progress-board 别名)
5113
+ routeDisposers.push(
5114
+ webServer.register({
5115
+ kind: 'exact',
5116
+ path: `${ROUTE_BASE}/ops/providers`,
5117
+ handler: async (req, res) => {
5118
+ if (req.method !== 'GET') {
5119
+ res.writeHead(405, { allow: 'GET' })
5120
+ res.end()
5121
+ return
5122
+ }
5123
+ try {
5124
+ sendJson(res, 200, await opsProviders())
5125
+ } catch (error) {
5126
+ sendJson(res, 200, { ok: false, providers: [], default: { provider: '', model: '' }, error: error instanceof Error ? error.message : String(error) })
5127
+ }
5128
+ },
5129
+ }),
5130
+ )
5131
+ routeDisposers.push(
5132
+ webServer.register({
5133
+ kind: 'exact',
5134
+ path: `${ROUTE_BASE}/ops`,
5135
+ handler: async (req, res) => {
5136
+ if (req.method !== 'POST') {
5137
+ res.writeHead(405, { allow: 'POST' })
5138
+ res.end()
5139
+ return
5140
+ }
5141
+ if (!String(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) {
5142
+ sendJson(res, 415, { ok: false, error: 'content-type 必须是 application/json' })
5143
+ return
5144
+ }
5145
+ try {
5146
+ const body = await readJson(req)
5147
+ sendJson(res, 200, await runOps(body))
5148
+ } catch (error) {
5149
+ const status = error && error.statusCode ? error.statusCode : 400
5150
+ sendJson(res, status, { ok: false, error: error instanceof Error ? error.message : String(error) })
5151
+ }
5152
+ },
5153
+ }),
5154
+ )
5155
+
4708
5156
  // 板路由:union 主前缀 + /progress-board 旧前缀别名(同 handler,保留一版)
4709
5157
  for (const base of [ROUTE_BASE, LEGACY_BASE]) {
4710
5158
  routeDisposers.push(
@@ -4749,7 +5197,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
4749
5197
  expectedRevision: body.expectedRevision,
4750
5198
  ackUserRevision: undefined,
4751
5199
  })
4752
- sendJson(res, 200, { ok: true, ...result.snapshot, changed: result.changed })
5200
+ sendJson(res, 200, { ok: true, ...result.snapshot, changed: result.changed, notified: result.notified === true })
4753
5201
  } catch (error) {
4754
5202
  const status = error && error.statusCode ? error.statusCode : 400
4755
5203
  sendJson(res, status, {
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.7.0-rc.2",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎;向压缩插件暴露只读三层进度锚点(service + HTTP 双平面);0.6.0 起每回合落一版会话归档(handoff + 重启注入一次)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
8
8
  "registry": "https://registry.npmjs.org",
9
9
  "access": "public",
10
- "tag": "rc"
10
+ "tag": "latest"
11
11
  },
12
12
  "dependencies": {
13
13
  "@deepseek-ai/schemastery": "~3.18.4"
@@ -272,3 +272,101 @@ test('rc.2:子条文案 zh/en 成对(本仓 client 只有内联 zh/en 两份
272
272
  assert.equal(hits.length, 2, `${k} 必须在 zh/en 各出现一次(实得 ${hits.length})`)
273
273
  }
274
274
  })
275
+
276
+ // ── rc.3:侧边栏「LLM 操作」小块(R3)────────────────────────────────────
277
+
278
+ /** 把 opsOutcome 从 client.js 里抠出来真跑:它是纯函数(不依赖 React hooks)。 */
279
+ function loadOpsOutcome() {
280
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
281
+ const start = src.indexOf('function opsOutcome(t, json) {')
282
+ assert.ok(start > 0, 'opsOutcome 必须存在')
283
+ const end = src.indexOf('\n }\n', start)
284
+ assert.ok(end > start, 'opsOutcome 函数体必须能定界')
285
+ return new Function('t', `${src.slice(start, end + 6)}\nreturn opsOutcome`)(
286
+ (key) => key,
287
+ )
288
+ }
289
+
290
+ test('rc.3:opsOutcome 把 validate 回执压成文本,ok/warning/error 三档颜色分开', () => {
291
+ const outcome = loadOpsOutcome()
292
+ const t = (key) => key
293
+ const clean = outcome(t, { op: 'validate', validation: { ok: true, count: 3, errors: [], warnings: [] } })
294
+ assert.equal(clean.kind, 'ok')
295
+ assert.equal(clean.text, 'opsValidOk · 3 opsItemsUnit')
296
+ const warned = outcome(t, { op: 'validate', validation: { ok: true, count: 2, errors: [], warnings: ['空板:没有任何任务项'] } })
297
+ assert.equal(warned.kind, 'warn', '可疑但可写 → warn 档,不能当成错误')
298
+ assert.match(warned.text, /空板/)
299
+ const bad = outcome(t, { op: 'validate', validation: { ok: false, count: 4, errors: ['项数 4 超过上限'], warnings: [] } })
300
+ assert.equal(bad.kind, 'bad')
301
+ assert.match(bad.text, /opsValidBad/)
302
+ assert.match(bad.text, /项数 4 超过上限/)
303
+ })
304
+
305
+ test('rc.3:opsOutcome 对 refine/mutate/ask 只回文本,没落地也不冒充成功', () => {
306
+ const outcome = loadOpsOutcome()
307
+ const t = (key) => key
308
+ const refined = outcome(t, { op: 'refine', answer: '已拆成两步', changes: [{ id: 'a' }], warnings: [] })
309
+ assert.equal(refined.kind, 'ok')
310
+ assert.equal(refined.text, '已拆成两步')
311
+ const empty = outcome(t, { op: 'mutate', answer: '', changes: [], warnings: [] })
312
+ assert.equal(empty.text, 'opsNoChanges', '模型没给出可落地改动必须直说')
313
+ const warned = outcome(t, { op: 'ask', answer: '只有 1 项在做', changes: [], warnings: ['同时 doing 2 项'] })
314
+ assert.equal(warned.kind, 'warn')
315
+ assert.equal(warned.text, '只有 1 项在做\n同时 doing 2 项')
316
+ })
317
+
318
+ test('rc.3:LLM 操作块只读 providers + POST /ops,不开新标签也不动路由面', () => {
319
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
320
+ assert.match(src, /fetch\(`\$\{API\}\/ops\/providers`/, 'provider 下拉必须拉宿主面,不在客户端写死')
321
+ assert.match(src, /fetch\(`\$\{API\}\/ops`, \{\n\s+method: 'POST'/, '四个动作统一走 POST /ops')
322
+ assert.match(src, /const OPS_ACTIONS = \[\s*\['refine', 'opsRefine'\],\s*\['mutate', 'opsMutate'\],\s*\['ask', 'opsAsk'\],\s*\['validate', 'opsValidate'\],/, '恰好四个动作,不多不少')
323
+ // 不新开顶级标签:只允许在 ProgressSidePanel 里渲染一次,且不能新增任何 tab/slot 注册
324
+ const panelStart = src.indexOf('function ProgressSidePanel(props) {')
325
+ const panelEnd = src.indexOf("inject: ['slots', 'locale'", panelStart)
326
+ assert.ok(panelStart > 0 && panelEnd > panelStart, 'ProgressSidePanel 边界必须可定界')
327
+ assert.equal((src.match(/h\(LlmOpsBlock, \{/g) || []).length, 1, '操作块只挂一处(侧栏面板内)')
328
+ const usage = src.indexOf('h(LlmOpsBlock, {')
329
+ assert.ok(usage > panelStart && usage < panelEnd, '操作块必须渲染在 ProgressSidePanel 内部')
330
+ assert.ok(src.indexOf('function LlmOpsBlock({') < panelStart, '组件定义在面板之前')
331
+ assert.equal(src.slice(panelStart, panelEnd).includes('sidebarRightTabs'), false, '不得为 LLM 操作新开右侧顶级页签')
332
+ // 落盘回执就地刷板,不额外 GET 一次
333
+ assert.match(src, /if \(body\.applied === true && body\.snapshot\) onApplied\(body\.snapshot\)/)
334
+ assert.match(src, /const applyRemoteSnapshot = useCallback\(/)
335
+ })
336
+
337
+ test('rc.3:操作块样式只用宿主令牌,窄屏降级', () => {
338
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
339
+ const cssStart = src.indexOf('.pb-ops {')
340
+ const cssEnd = src.indexOf('.pb-side-footer {')
341
+ assert.ok(cssStart > 0 && cssEnd > cssStart, '操作块样式必须排在侧栏页脚之前')
342
+ const css = src.slice(cssStart, cssEnd)
343
+ assert.doesNotMatch(css, /#[0-9a-fA-F]{3,6}/, '不得硬编十六进制色')
344
+ assert.doesNotMatch(css, /rgba?\(/, '不得硬编 rgb 色(皮肤切换会失配)')
345
+ assert.match(css, /\.pb-ops-out \{[^}]*var\(--dsw-alias-brand-primary\)/, '结果条左边线用主色令牌')
346
+ assert.match(css, /\.pb-ops-out\.bad \{[^}]*var\(--dsw-alias-state-error-primary\)/, '错误档用 error 令牌')
347
+ assert.match(css, /\.pb-ops-out\.warn \{[^}]*var\(--dsw-alias-state-warn-primary\)/, '可疑档用 warn 令牌')
348
+ assert.match(css, /@media \(max-width: 760px\) \{ \.pb-ops-hint \{ display: none; \} \}/, '窄屏收掉提示文案')
349
+ assert.match(css, /@media \(max-width: 520px\) \{ \.pb-ops-row \{ flex-direction: column; \} \}/, '极窄屏下拉竖排')
350
+ })
351
+
352
+ test('rc.3:操作块文案 zh/en 成对(本仓 client 只有内联 zh/en 两份字典)', () => {
353
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
354
+ const keys = ['opsTitle', 'opsHint', 'opsProvider', 'opsModel', 'opsProviderNone', 'opsQuestion', 'opsRefine', 'opsMutate', 'opsAsk', 'opsValidate', 'opsBusy', 'opsNoChanges', 'opsValidOk', 'opsValidBad', 'opsItemsUnit']
355
+ for (const k of keys) {
356
+ const hits = src.match(new RegExp(`\\n\\s+${k}: '[^']+',`, 'g')) || []
357
+ assert.equal(hits.length, 2, `${k} 必须在 zh/en 各出现一次(实得 ${hits.length})`)
358
+ }
359
+ })
360
+
361
+ test('0.7.0:新增任务 wake 与 R4 落队列互斥,同一次改板队列里只留一条', () => {
362
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
363
+ // 真机偏差:面板加两项后 input-traffic 出现两条同文排队条目——客户端 wake 与
364
+ // 服务端 R4 提醒各发一条。门控必须读服务端 notified 回执。
365
+ assert.match(src, /if \(addedTitles\.length > 0 && body\.notified !== true\) \{/, 'wake 前必须让位给服务端已落队列的提醒')
366
+ const wakeStart = src.indexOf('props.wakeAgent?.(')
367
+ const gateStart = src.lastIndexOf('if (addedTitles.length > 0', wakeStart)
368
+ assert.ok(gateStart > 0 && wakeStart - gateStart < 400, 'wake 调用必须在 notified 门控块内')
369
+ // 门控只在 mutate 的成功分支里,失败分支(throw)不得触发 wake
370
+ const throwAt = src.lastIndexOf('throw new Error(body?.error', wakeStart)
371
+ assert.ok(throwAt < gateStart, '错误分支必须在门控之前退出,不共享 wake 通道')
372
+ })