taskboard-workbench 0.0.0-stage → 0.2.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +21 -0
  3. package/README.md +121 -2
  4. package/cli/tb.mjs +314 -0
  5. package/cordis.patch.yml +5 -0
  6. package/index.js +633 -0
  7. package/lib/client.js +522 -0
  8. package/package.json +83 -4
  9. package/spec//345/233/242/351/230/237agent.md +171 -0
  10. package/src/core/advance.mjs +192 -0
  11. package/src/core/agent-teams.mjs +48 -0
  12. package/src/core/binding.mjs +44 -0
  13. package/src/core/config.mjs +22 -0
  14. package/src/core/debug-dispatch.mjs +94 -0
  15. package/src/core/delivery.mjs +93 -0
  16. package/src/core/deps.mjs +53 -0
  17. package/src/core/diagnostics.mjs +648 -0
  18. package/src/core/domain.mjs +235 -0
  19. package/src/core/empty-state.mjs +240 -0
  20. package/src/core/errors.mjs +139 -0
  21. package/src/core/executor.mjs +645 -0
  22. package/src/core/human-review.mjs +773 -0
  23. package/src/core/intake.mjs +116 -0
  24. package/src/core/kickoff.mjs +147 -0
  25. package/src/core/loop.mjs +498 -0
  26. package/src/core/memory.mjs +193 -0
  27. package/src/core/next-step.mjs +377 -0
  28. package/src/core/notify.mjs +183 -0
  29. package/src/core/owner.mjs +41 -0
  30. package/src/core/requirements.mjs +262 -0
  31. package/src/core/review.mjs +82 -0
  32. package/src/core/session-naming.mjs +64 -0
  33. package/src/core/split-ask.mjs +107 -0
  34. package/src/core/store.mjs +3103 -0
  35. package/src/core/team.mjs +170 -0
  36. package/src/core/verify.mjs +170 -0
  37. package/src/core/watchdog.mjs +144 -0
  38. package/src/host/ai-elaborator.mjs +26 -0
  39. package/src/host/team-engine.mjs +125 -0
  40. package/src/host/tool-surface.mjs +205 -0
  41. package/src/server/api.mjs +1974 -0
  42. package/src/server/events.mjs +32 -0
  43. package/src/server/kickoff.mjs +46 -0
  44. package/src/server/server.mjs +211 -0
  45. package/src/server/verify.mjs +112 -0
  46. package/tools/env-check.mjs +35 -0
  47. package/tools/seed.mjs +67 -0
  48. package/web/app.js +5237 -0
  49. package/web/index.html +15 -0
  50. package/web/tokens.css +1139 -0
@@ -0,0 +1,193 @@
1
+ /**
2
+ * memory.mjs —— 项目记忆条目(2026-10-28 拍板 D-M1/D-M2/D-M5)。
3
+ *
4
+ * 定位:**L2 记忆层不是第二真源**。每条记忆=一句结论 + 指回事实流的 `provenance`
5
+ * (`event:<cursor>` / `doc:<path>#<anchor>` / `session:<id>` / `run:<taskRunId>`)——
6
+ * 把整张 `memory_entries` 删掉,系统功能一件不少,只是"变笨"。
7
+ *
8
+ * 三条来自本仓实证的红线:
9
+ * ① 假记忆比空记忆更坏(69 张卡里 56 张挂兜底条目 `R124`)⇒ 写入默认 `proposed`,人 accept 才召回;
10
+ * ② 不删只取代(`superseded`)⇒ 仍可回查"以前是这么定的,后来改了";
11
+ * ③ 先脱敏再入记忆(全局 AGENTS §3)⇒ `sk-*` / `*_token` / 私钥一律拒收。
12
+ */
13
+ import { TbError } from "./errors.mjs";
14
+
15
+ export const MEMORY_SCOPES = Object.freeze(["project", "agent", "org"]);
16
+ export const MEMORY_KINDS = Object.freeze(["convention", "decision", "pitfall", "fact", "procedure"]);
17
+ export const MEMORY_VISIBILITIES = Object.freeze(["private", "shared", "org"]);
18
+
19
+ /** 召回默认预算(D-M5:6 条 / 3000 字;`fact` 只在显式请求时给)。 */
20
+ export const MEMORY_RECALL_DEFAULT = Object.freeze({
21
+ limit: 6, charBudget: 3000, quotas: Object.freeze({ convention: 3, decision: 2, pitfall: 1 }),
22
+ });
23
+
24
+ export const MEMORY_TITLE_MAX = 80;
25
+ export const MEMORY_BODY_MAX = 4000;
26
+
27
+ /** 记忆会跨项目流动,泄露面比文档更大 ⇒ 入库即拦。 */
28
+ const SECRET_RE = /(sk-[A-Za-z0-9_-]{12,})|(\b[A-Za-z0-9_]*_token\s*[:=]\s*\S+)|(-----BEGIN [A-Z ]*PRIVATE KEY-----)|(\bBearer\s+[A-Za-z0-9._-]{20,})/;
29
+
30
+ const pick = (list, value, field) => {
31
+ const v = String(value ?? "").trim();
32
+ if (!list.includes(v)) throw new TbError("USAGE_ERROR", `${field} 必须是 ${list.join(" / ")} 之一,收到 ${JSON.stringify(value)}`, { field });
33
+ return v;
34
+ };
35
+
36
+ const rowToEntry = (row, nowMs) => {
37
+ if (!row) return null;
38
+ const ttl = row.ttl_days ?? null;
39
+ // ttl_days=0 表示「立刻过期」(>= 而非 >,否则同一毫秒内判不出来)
40
+ const stale = ttl != null && (nowMs - Date.parse(row.updated_at)) >= ttl * 86400000;
41
+ return {
42
+ id: row.id,
43
+ scope: row.scope,
44
+ projectId: row.project_id ?? null,
45
+ agentId: row.agent_id ?? null,
46
+ kind: row.kind,
47
+ title: row.title,
48
+ body: row.body,
49
+ tags: (() => { try { return JSON.parse(row.tags ?? "[]"); } catch { return []; } })(),
50
+ provenance: row.provenance,
51
+ confidence: row.confidence,
52
+ visibility: row.visibility,
53
+ verifiedAt: row.verified_at ?? null,
54
+ ttlDays: ttl,
55
+ stale,
56
+ supersedes: row.supersedes ?? null,
57
+ createdBy: row.created_by,
58
+ createdAt: row.created_at,
59
+ updatedAt: row.updated_at,
60
+ };
61
+ };
62
+
63
+ export function createMemoryApi({ db, nowIso, randomUUID }) {
64
+ const memory = {
65
+ /** 写入/更新一条记忆。**默认 propose**(D-M2:agent 可提议,人 accept 才召回)。 */
66
+ upsertMemoryEntry(input = {}) {
67
+ const scope = pick(MEMORY_SCOPES, input.scope ?? "project", "scope");
68
+ const kind = pick(MEMORY_KINDS, input.kind, "kind");
69
+ const visibility = pick(MEMORY_VISIBILITIES, input.visibility ?? (scope === "project" ? "shared" : "org"), "visibility");
70
+ const title = String(input.title ?? "").trim();
71
+ if (!title) throw new TbError("USAGE_ERROR", "记忆必须有 title", { field: "title" });
72
+ if (title.length > MEMORY_TITLE_MAX) throw new TbError("USAGE_ERROR", `title 超长(>${MEMORY_TITLE_MAX} 字),说明该拆条`, { field: "title" });
73
+ const body = String(input.body ?? "").trim();
74
+ if (!body) throw new TbError("USAGE_ERROR", "记忆必须有 body", { field: "body" });
75
+ if (body.length > MEMORY_BODY_MAX) throw new TbError("USAGE_ERROR", `body 超长(>${MEMORY_BODY_MAX} 字),说明该拆条`, { field: "body" });
76
+ // R-M3:无出处一律 reject —— 记忆必须能回指事实流
77
+ const provenance = String(input.provenance ?? "").trim();
78
+ if (!provenance) throw new TbError("USAGE_ERROR", "记忆必须带 provenance(event:<cursor> / doc:<path>#<anchor> / session:<id> / run:<id>),无出处的记忆一律拒收", { field: "provenance" });
79
+ // R-M5:先脱敏再入记忆
80
+ const hit = SECRET_RE.exec(`${title}\n${body}\n${provenance}`);
81
+ if (hit) throw new TbError("MEMORY_SECRET_REJECTED", "疑似敏感信息(密钥 / token / 私钥),先脱敏再入记忆", { field: "body", pattern: hit[1] ? "sk-*" : (hit[2] ? "*_token" : "private-key") });
82
+ const verifiedAt = input.verifiedAt ? String(input.verifiedAt) : null;
83
+ if (kind === "fact" && !verifiedAt) throw new TbError("USAGE_ERROR", "kind=fact 必须带 verifiedAt(事实一定会过期,过期即降权)", { field: "verifiedAt" });
84
+ if (scope === "project" && !input.projectId) throw new TbError("USAGE_ERROR", "scope=project 必须带 projectId", { field: "projectId" });
85
+ if (scope === "agent" && !input.agentId) throw new TbError("USAGE_ERROR", "scope=agent 必须带 agentId", { field: "agentId" });
86
+
87
+ const ts = nowIso();
88
+ const existing = db.prepare("select * from memory_entries where scope = ? and kind = ? and title = ? and provenance = ?")
89
+ .get(scope, kind, title, provenance);
90
+ if (existing) {
91
+ db.prepare("update memory_entries set body = ?, tags = ?, visibility = ?, verified_at = ?, ttl_days = ?, updated_at = ? where id = ?")
92
+ .run(body, JSON.stringify(input.tags ?? []), visibility, verifiedAt, input.ttlDays ?? null, ts, existing.id);
93
+ return { entry: memory.getMemoryEntry(existing.id), created: false };
94
+ }
95
+ const id = `mem-${randomUUID().replace(/-/g, "").slice(0, 12)}`;
96
+ db.prepare(
97
+ `insert into memory_entries (id, scope, project_id, agent_id, kind, title, body, tags, provenance, confidence,
98
+ visibility, verified_at, ttl_days, supersedes, created_by, created_at, updated_at)
99
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, 'proposed', ?, ?, ?, null, ?, ?, ?)`,
100
+ ).run(id, scope, input.projectId ?? null, input.agentId ?? null, kind, title, body,
101
+ JSON.stringify(input.tags ?? []), provenance, visibility, verifiedAt, input.ttlDays ?? null,
102
+ String(input.createdBy ?? "agent:unknown"), ts, ts);
103
+ return { entry: memory.getMemoryEntry(id), created: true };
104
+ },
105
+
106
+ getMemoryEntry(id) {
107
+ return rowToEntry(db.prepare("select * from memory_entries where id = ?").get(String(id)), Date.now());
108
+ },
109
+
110
+ listMemoryEntries({ projectId = null, scope = null, kind = null, includeProposed = false, includeSuperseded = false } = {}) {
111
+ const where = [];
112
+ const params = [];
113
+ if (projectId) { where.push("(project_id = ? or scope = 'org')"); params.push(projectId); }
114
+ if (scope) { where.push("scope = ?"); params.push(pick(MEMORY_SCOPES, scope, "scope")); }
115
+ if (kind) { where.push("kind = ?"); params.push(pick(MEMORY_KINDS, kind, "kind")); }
116
+ if (!includeProposed) where.push("confidence = 'accepted'");
117
+ if (!includeSuperseded) where.push("supersedes is null");
118
+ const sql = `select * from memory_entries ${where.length ? `where ${where.join(" and ")}` : ""} order by updated_at desc, id asc`;
119
+ const nowMs = Date.now();
120
+ return db.prepare(sql).all(...params).map((r) => rowToEntry(r, nowMs));
121
+ },
122
+
123
+ /** 人/评审确认 —— 只有 accepted 才会被召回。 */
124
+ acceptMemoryEntry(id, { actor = "human" } = {}) {
125
+ const entry = memory.getMemoryEntry(id);
126
+ if (!entry) throw new TbError("MEMORY_NOT_FOUND", `记忆不存在:${id}`, { id });
127
+ const ts = nowIso();
128
+ db.prepare("update memory_entries set confidence = 'accepted', updated_at = ? where id = ?").run(ts, entry.id);
129
+ return { entry: memory.getMemoryEntry(entry.id), acceptedBy: String(actor) };
130
+ },
131
+
132
+ /** 不删只取代(R-M2)。 */
133
+ supersedeMemoryEntry(id, { byId = null, actor = "human" } = {}) {
134
+ const entry = memory.getMemoryEntry(id);
135
+ if (!entry) throw new TbError("MEMORY_NOT_FOUND", `记忆不存在:${id}`, { id });
136
+ const ts = nowIso();
137
+ db.prepare("update memory_entries set supersedes = ?, updated_at = ? where id = ?").run(byId, ts, entry.id);
138
+ return { entry: memory.getMemoryEntry(entry.id), supersededBy: byId ?? null, actor: String(actor) };
139
+ },
140
+
141
+ /**
142
+ * 召回(L3):只取 `accepted` 且未过期的条目,按 kind 配额 + 字数预算。
143
+ * `fact` 默认**不召回**(过期事实比没有记忆更坏,R-M4),除非显式 `includeKinds`。
144
+ */
145
+ recallMemory({ projectId = null, limit = MEMORY_RECALL_DEFAULT.limit, charBudget = MEMORY_RECALL_DEFAULT.charBudget, quotas = MEMORY_RECALL_DEFAULT.quotas, includeFacts = false } = {}) {
146
+ const pool = memory.listMemoryEntries({ projectId, includeProposed: false })
147
+ .filter((e) => !e.stale)
148
+ .filter((e) => includeFacts || e.kind !== "fact");
149
+ const used = Object.fromEntries(MEMORY_KINDS.map((k) => [k, 0]));
150
+ const entries = [];
151
+ let chars = 0;
152
+ for (const entry of pool) {
153
+ if (entries.length >= limit) break;
154
+ const quota = quotas?.[entry.kind];
155
+ if (quota != null && used[entry.kind] >= quota) continue;
156
+ const cost = entry.title.length + entry.body.length;
157
+ if (chars + cost > charBudget) continue;
158
+ entries.push(entry);
159
+ used[entry.kind] += 1;
160
+ chars += cost;
161
+ }
162
+ return { entries, count: entries.length, chars };
163
+ },
164
+
165
+ /** 召回审计:能回答"这次为什么这么答"(上游原文的请求日志范式)。 */
166
+ recordMemoryRecalls({ sessionId = null, entries = [], reason = null } = {}) {
167
+ const ts = nowIso();
168
+ const stmt = db.prepare("insert into memory_recalls (session_id, entry_id, reason, injected_chars, created_at) values (?, ?, ?, ?, ?)");
169
+ let n = 0;
170
+ for (const entry of entries) { stmt.run(sessionId, entry.id, reason, entry.title.length + entry.body.length, ts); n += 1; }
171
+ return n;
172
+ },
173
+
174
+ listMemoryRecalls({ limit = 50 } = {}) {
175
+ return db.prepare("select * from memory_recalls order by id desc limit ?").all(Math.max(1, Number(limit) || 50));
176
+ },
177
+ };
178
+ return memory;
179
+ }
180
+
181
+ /** L3 装载块:与「推进清单」并列,不新造格式。 */
182
+ export function renderMemoryBlock(recall, { projectName = null } = {}) {
183
+ const head = `【项目记忆${projectName ? ` · ${projectName}` : ""}】`;
184
+ if (!recall || recall.count === 0) return `${head}\n(暂无已确认记忆)`;
185
+ const kindLabel = { convention: "约定", decision: "裁定", pitfall: "踩坑", fact: "事实", procedure: "SOP" };
186
+ const lines = recall.entries.map((e) => `- [${kindLabel[e.kind] ?? e.kind}] ${e.title}(${e.id},出自 ${e.provenance})`);
187
+ return [
188
+ head,
189
+ `(共 ${recall.count} 条 · 已确认)`,
190
+ ...lines,
191
+ "规则:以上为已确认结论;与本轮事实冲突时**以事实为准**,并在回复中指出该条需要复核。",
192
+ ].join("\n");
193
+ }
@@ -0,0 +1,377 @@
1
+ /**
2
+ * 「下一步」引导(纯函数)——抽屉里那张卡**现在该做什么**的唯一口径。
3
+ *
4
+ * 为什么单独成一个模块:真机反馈(2026-10-22)「任务详情界面没有下一步该做啥的提示,
5
+ * 也没有操作按钮」——按钮此前按**功能分类**散落在「评审 / 操作 / 人工校验」各区,
6
+ * 没有任何一处回答"我现在该干嘛";尤其"被人工校验门挡住"的卡只有一行文字说明,
7
+ * 连跳过去下结论的入口都没有。引导口径是**状态推导**,与渲染无关,因此放核心层做纯函数、
8
+ * 由单测覆盖每个分支,前端只负责把 action id 映射成按钮与埋点。
9
+ *
10
+ * 设计约束:
11
+ * - **只读推导**,不改任何状态;不产生副作用。
12
+ * - action 用稳定 id 表达意图,文案与处理留在前端(本模块不碰 DOM / 不发请求)。
13
+ * - 优先级即数组顺序:人工校验门 > 评审 > 其它状态。人环门是**上游阻塞**,
14
+ * 它挡住时"去下结论"永远比"这张卡自己该怎么走"更该先说。
15
+ */
16
+
17
+ /** 全部可能的引导码(测试与前端兜底用)。 */
18
+ export const NEXT_STEP_CODES = Object.freeze([
19
+ "human-review-pending",
20
+ "blocked-by-human-review",
21
+ "awaiting-human-done",
22
+ "review-pending",
23
+ "rework",
24
+ "blocked",
25
+ "blocked-no-attribution",
26
+ "needs-host-action",
27
+ "backlog",
28
+ "backlog-no-attribution",
29
+ "todo-no-attribution",
30
+ "todo",
31
+ "in-progress",
32
+ "in-progress-stalled",
33
+ "done",
34
+ "canceled",
35
+ "unknown",
36
+ ]);
37
+
38
+ const ACTION_KINDS = Object.freeze(["primary", "default", "danger"]);
39
+
40
+ function action(id, label, kind = "default") {
41
+ if (!ACTION_KINDS.includes(kind)) throw new Error(`未知按钮语义:${kind}`);
42
+ return { id, label, kind };
43
+ }
44
+
45
+ function isHumanReview(task) {
46
+ const labels = Array.isArray(task?.labels) ? task.labels : [];
47
+ return labels.some((l) => String(l ?? "").trim() === "human_review");
48
+ }
49
+
50
+ function blockedBy(task) {
51
+ const blocker = task?.humanReviewBlocker ?? null;
52
+ if (!blocker || !blocker.identifier) return null;
53
+ return { identifier: String(blocker.identifier), title: blocker.title ?? null, category: blocker.category ?? null };
54
+ }
55
+
56
+ /**
57
+ * 「下一步是宿主 / 终端类动作」的特征词(FR-97)。
58
+ *
59
+ * 口径要窄:命中即断言"看板执行循环做不了",误判会把普通卡错误地推给主会话。
60
+ * 只收**明确的宿主/环境动作**说法,不收"重启服务"之外含义模糊的词。
61
+ */
62
+ const HOST_ACTION_RE = /(\.dsh\/profiles|~\/\.dsh|LaunchAgent|plist|dsh plugin (add|remove)|pnpm install|重启\s*(dsh|宿主|服务)|重载插件|安装插件|杀进程|\bkill\b)/i;
63
+
64
+ /** 卡是否需要宿主/终端环境才能推进(已归因才有意义:未归因交出去也走不通)。 */
65
+ function needsHostAction(task, ctx = {}) {
66
+ if (!task?.requirementId) return false; // 未归因:先归因,别推给主会话
67
+ if (ctx.hostAction === true) return true; // 调用方可显式给判据(如人工标注)
68
+ if (ctx.hostAction === false) return false;
69
+ const haystack = [task.title, task.description, task.nextStepHint].filter(Boolean).join("\n");
70
+ return HOST_ACTION_RE.test(haystack);
71
+ }
72
+
73
+ /**
74
+ * 推导「下一步」。
75
+ *
76
+ * @param {object} task 任务行(含 status / labels / reviewState / requirementId / humanReview* 字段)
77
+ * @param {object} [ctx]
78
+ * @param {{identifier:string,title?:string,category?:string}|null} [ctx.humanReviewBlocker]
79
+ * 当本卡的**前置**里有一张「待结论」的人工校验卡时传它(前端从依赖表映射得到)
80
+ * @returns {{code:string,title:string,hint:string,actions:Array<{id:string,label:string,kind:string}>,
81
+ * blocker:{identifier:string,title:string|null,category:string|null}|null}}
82
+ */
83
+ function derive(task, ctx = {}) {
84
+ const t = task ?? {};
85
+ const status = String(t.status ?? "");
86
+ const review = t.reviewState === null || t.reviewState === undefined || t.reviewState === "" ? null : String(t.reviewState);
87
+ const closed = status === "done" || status === "canceled";
88
+ const blocker = closed ? null : blockedBy(ctx);
89
+
90
+ // 1) 本卡自己就是人工校验卡且尚未结论 —— 唯一出口是下结论(执行侧不得认领、不得 done)。
91
+ if (isHumanReview(t) && String(t.humanReviewState ?? "pending") !== "concluded") {
92
+ return {
93
+ code: "human-review-pending",
94
+ title: "这一步归你:给人工校验结论",
95
+ hint: "本卡是人工校验卡(人在环升级门)——结论给出前它挡住的下游一律不推进;执行侧不得认领、不得置「完成」。",
96
+ actions: [action("conclude-human-review", "去下结论(本页「人工校验」区块)", "primary")],
97
+ blocker: null,
98
+ };
99
+ }
100
+
101
+ // 2) 本卡被一张「待结论」的人工校验卡挡住 —— 先说清"被谁挡、去哪解",并给直达入口。
102
+ if (blocker) {
103
+ return {
104
+ code: "blocked-by-human-review",
105
+ title: `被人工校验门挡住:${blocker.identifier}`,
106
+ hint: `前置 ${blocker.identifier} 是人工校验卡(待结论)${blocker.category ? `·类别 ${blocker.category}` : ""}:结论给出前本卡不推进、不自动重派。先去那张卡下结论。`,
107
+ actions: [
108
+ action("open-blocker", `打开 ${blocker.identifier} 下结论`, "primary"),
109
+ action("goto-deps", "查看阻塞因素"),
110
+ ],
111
+ blocker,
112
+ };
113
+ }
114
+
115
+ // 3) 待验收:按评审态分流。
116
+ if (status === "in_review") {
117
+ if (review === "approved") {
118
+ return {
119
+ code: "awaiting-human-done",
120
+ title: "只差你点「完成」",
121
+ hint: "实现与评审都过了。红线:完成只能由人确认,执行侧与评审都不会代点。",
122
+ actions: [action("complete", "完成(仅人工可确认)", "primary")],
123
+ blocker: null,
124
+ };
125
+ }
126
+ if (review === "changes_requested") {
127
+ return {
128
+ code: "rework",
129
+ title: "返工中:按评审说明改完再提交评审",
130
+ hint: `返工第 ${t.reviewRound ?? 0} 轮${t.reviewSourceStatus ? `·完成后先回「${t.reviewSourceStatus}」再提交` : ""};返工只回来源列,下游继续受阻直到解锁。`,
131
+ actions: [action("goto-review", "去「评审」区块填说明", "primary")],
132
+ blocker: null,
133
+ };
134
+ }
135
+ return {
136
+ code: "review-pending",
137
+ title: "等你评审",
138
+ hint: t.reviewer ? `评审者:${t.reviewer}` : "未指派评审者:超时会产出「评审死锁」诊断。",
139
+ actions: [
140
+ action("review-approve", "评审通过", "primary"),
141
+ action("goto-review", "请求返工(需填说明)"),
142
+ ],
143
+ blocker: null,
144
+ };
145
+ }
146
+
147
+ // 4) 受阻。
148
+ if (status === "blocked") {
149
+ // FR-97:受阻且已归因的卡此前只有「重试 / 看诊断」两个出口 —— 但**大量受阻卡的真实卡点
150
+ // 是「卡住了、需要人或环境介入」**(要动 ~/.dsh、要重启宿主),反复「重试」既不解决也不该由
151
+ // 团队自己扛。给两个可点出口:交项目主会话执行(调试修复)/ 转为执行调试。
152
+ // 归因门在先:未归因的卡交出去也走不通,先说清该去归因。
153
+ if (!t.requirementId) {
154
+ return {
155
+ code: "blocked-no-attribution",
156
+ title: "先归因,再决定怎么救",
157
+ hint: "本卡受阻且**未归属需求条目** —— 交主会话执行 / 转为执行调试都需要先归因,否则下游一律推不动。",
158
+ actions: [
159
+ action("goto-attribution", "去归因(关联需求条目)", "primary"),
160
+ action("goto-diagnostics", "查看诊断"),
161
+ ],
162
+ blocker: null,
163
+ };
164
+ }
165
+ return {
166
+ code: "blocked",
167
+ title: "受阻:先看原因,再决定重试还是交人",
168
+ hint: `${t.blockKind ? `类型 ${t.blockKind}·` : ""}同因复发 ${t.blockRecurrences ?? 0} 次${t.triageAt ? "·已转人工兜底" : ""}。`,
169
+ actions: [
170
+ action("retry", "重试(退回待办)", "primary"),
171
+ action("dispatch-main-session", "交项目主会话执行(调试修复)"),
172
+ action("to-debug", "转为执行调试"),
173
+ action("goto-diagnostics", "查看诊断"),
174
+ ],
175
+ blocker: null,
176
+ };
177
+ }
178
+
179
+ // 4·5) FR-97:**下一步本身是宿主/终端类动作**的卡(要动 ~/.dsh、装/卸插件、重启宿主等)。
180
+ // 这类动作看板自己的执行循环做不了 —— 既不是"重试"能解决的,也不是团队内部能闭环的;
181
+ // 必须交给人 / 项目主会话。
182
+ // 位置很关键:放在「受阻」之后(受阻卡已在上面按 blocked 口径给全了动作)、
183
+ // 「待办池/可开工/进行中」之前 —— 这样**任何还没收口的卡**,只要下一步要动宿主环境,
184
+ // 都会被识别出来,而不是只有 blocked 一类卡才有这个出口。
185
+ if (!closed && needsHostAction(t, ctx)) {
186
+ return {
187
+ code: "needs-host-action",
188
+ title: "这一步要动宿主环境:交主会话或转调试",
189
+ hint: "本卡的下一步涉及宿主 / 终端环境(装插件、重启服务、改 ~/.dsh 等)——看板执行循环做不了。可交项目主会话执行(调试修复),或标记为「执行调试」后由人接手。",
190
+ actions: [
191
+ action("dispatch-main-session", "交项目主会话执行(调试修复)", "primary"),
192
+ action("to-debug", "转为执行调试"),
193
+ ],
194
+ blocker: null,
195
+ };
196
+ }
197
+
198
+ // 5) 待办池:未授权开工,团队不会认领。
199
+ if (status === "backlog") {
200
+ // 门序列与服务端 `store.assertExecutable` 一致:**归因门先于授权门** ⇒ 未归因的待办池卡
201
+ // 先归因。否则「先授权 → 再点启动执行」仍会被归因门拒(同一句报错换个入口再来一次,
202
+ // 真机 2026-10-22 用户第十次投递的正是这句)。
203
+ if (!t.requirementId) {
204
+ return {
205
+ code: "backlog-no-attribution",
206
+ title: "先归因,再授权开工",
207
+ hint: "本卡在「待办池」且未归属需求条目 —— 归因门在授权门之前:「启动执行 / 派发团队」都会被拒(EXECUTION_NOT_ATTRIBUTED)。",
208
+ actions: [action("goto-attribution", "去归因(关联需求条目)", "primary")],
209
+ blocker: null,
210
+ };
211
+ }
212
+ return {
213
+ code: "backlog",
214
+ title: "未授权开工",
215
+ hint: "在「待办池」= 未授权开工,团队不得认领。",
216
+ actions: [action("authorize", "授权开工", "primary")],
217
+ blocker: null,
218
+ };
219
+ }
220
+
221
+ // 6) 可开工:先过分归因门,再派发。
222
+ if (status === "todo") {
223
+ if (!t.requirementId) {
224
+ return {
225
+ code: "todo-no-attribution",
226
+ title: "先归因,否则会被归因门拦下",
227
+ hint: "本卡未归属需求条目 —— 「启动执行 / 派发团队」都会被归因门拒绝(EXECUTION_NOT_ATTRIBUTED)。",
228
+ actions: [action("goto-attribution", "去归因(关联需求条目)", "primary")],
229
+ blocker: null,
230
+ };
231
+ }
232
+ return {
233
+ code: "todo",
234
+ title: "可开工:派人或启动执行",
235
+ hint: "归因已就绪;可「启动执行」(会话 + 开局提示词),或交给团队执行器。",
236
+ actions: [action("start-execution", "启动执行", "primary")],
237
+ blocker: null,
238
+ };
239
+ }
240
+
241
+ // 7) 进行中:看护读数(FR-75/76)。
242
+ if (status === "in_progress") {
243
+ // 看护读数:只有 `stalled` 才算停滞;`idle`(空闲但未超阈值)/`running`/`awaiting-decision`
244
+ // 都是正常读数,不得被引导文案说成停滞。
245
+ const stalled = ctx.stalled === true || task?.watchdog?.state === "stalled";
246
+ return {
247
+ code: stalled ? "in-progress-stalled" : "in-progress",
248
+ title: stalled ? "疑似停滞:看进展,或退回待办重派" : "执行中:盯着回写",
249
+ hint: stalled ? "已超阈值无进展回报——可打开执行会话看现场,或退回待办重新派发。" : "执行侧回写后状态会回流;异常可退回待办。",
250
+ actions: [
251
+ action("open-session", "打开执行会话", "primary"),
252
+ action("retry", "退回待办(重新派发)"),
253
+ ],
254
+ blocker: null,
255
+ };
256
+ }
257
+
258
+ if (status === "done") {
259
+ return { code: "done", title: "已收口", hint: "本卡已完成,无待办动作。", actions: [], blocker: null };
260
+ }
261
+ if (status === "canceled") {
262
+ return { code: "canceled", title: "已取消", hint: "本卡已取消,不参与派发与看护。", actions: [], blocker: null };
263
+ }
264
+ return { code: "unknown", title: "状态未知", hint: `未识别的状态:${status || "(空)"}。`, actions: [], blocker: null };
265
+ }
266
+
267
+ /**
268
+ * 引导码 → **呈现口径**:`focus` 该展开哪个区块、`steps` 按什么顺序做。
269
+ *
270
+ * 真机反馈(2026-10-22)「既然任务收口了,为何该页面还有这么多人工检验、评审、执行会话按钮动作…
271
+ * 任务异常时又可评审又可检验、无从下手」——所以引导不能只有一句话和几个按钮,还得回答
272
+ * 「现在只该动哪一处」以及「按 1-2-3 怎么走」。这张表是**纯数据**,前端拿它决定默认折叠与步骤展示:
273
+ * - `focus` 为字符串数组 = 只默认展开标题命中这些关键字的区块;`[]` = 只留只读区;
274
+ * - `focus` 为 `null` = **不干预**(状态未识别时不要把界面按猜测重排)。
275
+ */
276
+ const GUIDANCE = Object.freeze({
277
+ "human-review-pending": {
278
+ focus: ["人工校验"],
279
+ steps: [
280
+ "先读本卡的证据与判定类别(真 bug / 需求异化 / 技术方案变化 / 与上游需求不符)",
281
+ "在「人工校验」区块填结论说明",
282
+ "三选一给结论:继续(continue)/ 改需求(change-requirement)/ 关单(close)",
283
+ ],
284
+ },
285
+ "blocked-by-human-review": {
286
+ focus: ["人工校验"],
287
+ steps: [
288
+ "打开前置的人工校验卡,把结论定下来(三选一)",
289
+ "结论给出后,本卡的前置门即消耗,回到本卡继续推进",
290
+ "结论若是「与上游需求不符」,先改需求或关单,再决定本卡去向",
291
+ ],
292
+ },
293
+ "awaiting-human-done": {
294
+ focus: [],
295
+ steps: ["核对证据链(评审已通过、改动与验证都在卡上)", "点「完成」收口 —— 完成只有人能点,且不会自动回退"],
296
+ },
297
+ "review-pending": {
298
+ focus: ["评审"],
299
+ steps: [
300
+ "读证据评论与改动摘要",
301
+ "需要时先指派评审者(留空=未指派,超时会产出「评审死锁」诊断)",
302
+ "填说明后「评审通过」,或「请求返工」(返工必填说明)",
303
+ ],
304
+ },
305
+ rework: {
306
+ focus: ["评审"],
307
+ steps: ["在「评审」区块读返工说明", "按说明改完,先回来源列再重新提交评审", "等新结论 —— 可点「评审通过」,或再次返工"],
308
+ },
309
+ blocked: {
310
+ focus: ["诊断与恢复动作"],
311
+ steps: [
312
+ "先看「诊断与恢复动作」里的失败点 / 退出码 / 命令",
313
+ "属环境或瞬时问题 → 「重试(退回待办)」让它重新派发",
314
+ "反复重试无效、且卡点需要人或环境介入 → 「交项目主会话执行(调试修复)」",
315
+ "想由人接手 → 「转为执行调试」(加标记、回待办,便于集中处理)",
316
+ ],
317
+ },
318
+ "blocked-no-attribution": {
319
+ focus: ["归因", "诊断与恢复动作"],
320
+ steps: [
321
+ "在「归因」区块选一个需求条目 —— 未归因时交主会话也走不通",
322
+ "点「关联需求条目」后回到本卡",
323
+ "再选「交项目主会话执行」或「转为执行调试」",
324
+ ],
325
+ },
326
+ "needs-host-action": {
327
+ focus: ["执行会话", "操作"],
328
+ steps: [
329
+ "确认这一步确实要动宿主环境(改 ~/.dsh、装/卸插件、重启服务等)",
330
+ "「交项目主会话执行(调试修复)」:指令含边界红线,投递到项目主会话",
331
+ "或「转为执行调试」标记后由人接手 —— 注意此类动作常需先报批",
332
+ ],
333
+ },
334
+ backlog: { focus: [], steps: ["确认这张卡确实要开工 → 「授权开工」(转「可开工」)", "未授权前团队不会认领它"] },
335
+ "backlog-no-attribution": {
336
+ focus: ["归因"],
337
+ steps: ["在「归因」区块选一个需求条目(归因门在授权门之前)", "点「关联需求条目」——不归因时「启动执行 / 派发团队」都会被拒绝", "回本卡「授权开工」→ 再「启动执行」"],
338
+ },
339
+ "todo-no-attribution": {
340
+ focus: ["归因"],
341
+ steps: ["在「归因」区块选一个需求条目", "点「关联需求条目」——不归因时「启动执行 / 派发团队」都会被归因门拒绝", "回到本卡再「启动执行」"],
342
+ },
343
+ todo: {
344
+ focus: ["执行会话", "归属团队"],
345
+ steps: ["确认归因已就绪", "「启动执行」:建/切执行会话 + 投开局提示词", "或交给团队执行器按并行策略派发"],
346
+ },
347
+ "in-progress": {
348
+ focus: ["执行会话", "执行看护"],
349
+ steps: ["盯执行侧回写(状态会回流到看板)", "需要现场 → 「打开执行会话」", "异常 → 「退回待办(重新派发)」"],
350
+ },
351
+ "in-progress-stalled": {
352
+ focus: ["执行会话", "执行看护"],
353
+ steps: ["「打开执行会话」看现场(历史在会话里)", "确认确实没进展 → 「退回待办」释放锁、重新派发", "反复停滞 → 申报人工校验,交人兜底"],
354
+ },
355
+ done: { focus: ["操作"], steps: [] },
356
+ canceled: { focus: ["操作"], steps: [] },
357
+ unknown: { focus: null, steps: [] },
358
+ });
359
+
360
+ /**
361
+ * 推导「下一步」引导(对外的唯一入口)。
362
+ *
363
+ * @param {object} task 任务行(含 status / labels / reviewState / requirementId / humanReview* 字段)
364
+ * @param {object} [ctx]
365
+ * @param {{identifier:string,title?:string,category?:string}|null} [ctx.humanReviewBlocker]
366
+ * 当本卡的**前置**里有一张「待结论」的人工校验卡时传它(前端从依赖表映射得到)
367
+ * @param {boolean} [ctx.stalled] 看护读数(FR-75):仅 `true` 视为停滞
368
+ * @returns {{code:string,title:string,hint:string,steps:string[],
369
+ * focus:string[]|null,actions:Array<{id:string,label:string,kind:string}>,
370
+ * blocker:{identifier:string,title:string|null,category:string|null}|null}}
371
+ * `focus` 供前端做默认折叠(见 GUIDANCE),`steps` 是给人看的 1-2-3 操作顺序。
372
+ */
373
+ export function deriveNextStep(task, ctx = {}) {
374
+ const result = derive(task, ctx);
375
+ const guide = GUIDANCE[result.code] ?? GUIDANCE.unknown;
376
+ return { ...result, focus: guide.focus, steps: [...guide.steps] };
377
+ }