taskboard-workbench 0.2.0 → 0.3.1

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 (36) hide show
  1. package/CHANGELOG.md +321 -0
  2. package/README.md +95 -0
  3. package/package.json +20 -6
  4. package/scripts/tb-flow.mjs +86 -0
  5. package/skills/taskboard-flow/SKILL.md +89 -0
  6. package/skills/taskboard-flow/references/errors.md +61 -0
  7. package/skills/taskboard-flow/references/injection.md +76 -0
  8. package/skills/taskboard-flow/references/steps/S0.md +31 -0
  9. package/skills/taskboard-flow/references/steps/S1.md +28 -0
  10. package/skills/taskboard-flow/references/steps/S2.md +31 -0
  11. package/skills/taskboard-flow/references/steps/S3.md +22 -0
  12. package/skills/taskboard-flow/references/steps/S4.md +25 -0
  13. package/skills/taskboard-flow/references/steps/S5.md +36 -0
  14. package/skills/taskboard-flow/references/steps/S6.md +30 -0
  15. package/skills/taskboard-flow/references/steps/S7.md +23 -0
  16. package/spec/norms/acceptance.md +36 -0
  17. package/spec/norms/card-update.md +39 -0
  18. package/spec/norms/doc-editing.md +30 -0
  19. package/spec/norms/flow.md +45 -0
  20. package/spec/norms/manifest.json +41 -0
  21. package/spec/norms/project-defaults.md +33 -0
  22. package/src/core/acceptance.mjs +62 -0
  23. package/src/core/contract.mjs +287 -0
  24. package/src/core/errors.mjs +3 -0
  25. package/src/core/evidence.mjs +86 -0
  26. package/src/core/intake.mjs +87 -24
  27. package/src/core/requirements.mjs +31 -1
  28. package/src/core/store.mjs +376 -6
  29. package/src/core/ticket-stage.mjs +162 -0
  30. package/src/mcp/flow-block.mjs +173 -0
  31. package/src/mcp/server.mjs +175 -0
  32. package/src/mcp/tools.mjs +769 -0
  33. package/src/server/api.mjs +128 -30
  34. package/src/server/server.mjs +3 -0
  35. package/web/app.js +162 -34
  36. package/web/tokens.css +12 -0
@@ -0,0 +1,162 @@
1
+ /**
2
+ * 阶段推导**单一口径**(FR-108 / 卡 `-196` · 0-A1)。
3
+ *
4
+ * 这一层只做「判」,不碰库、不发请求(0-A1 的边界):输入的 `evidence` / `decision` / `comments`
5
+ * 由调用方给,输出一个 `stage` 加上四套旧口径的**同批读数**。
6
+ *
7
+ * 为什么不是"再写第五套判断":四套旧口径(`next-step` / `verify` / `watchdog` / `diagnostics`)
8
+ * 各自回答一个侧面的问题,谁都不是"这张卡到哪一步"的唯一答案。本函数**直接复用**它们的纯函数
9
+ * (`deriveNextStep` / `assessTask` / `latestAutoReview`),只做**归一**,不复制任何判定规则 ——
10
+ * 规则一复制就必然漂移(这正是 FR-108 要消灭的东西)。
11
+ *
12
+ * 交付物漏斗(stage 的核心,按优先级):
13
+ * `done` / `canceled` → `human_review_pending` → `blocked_by_human_review`
14
+ * → `awaiting_review_request` → `stale` → `rework` → `awaiting_human_done` → `review_pending`
15
+ * → `ready` → `refs_unresolved` → `format_ok` → `blocked` → `in_progress` → `todo` → `backlog` → `not_ready`
16
+ *
17
+ * 三条**刻意**的优先级(都有测试钉住,改动即红):
18
+ * 1. `awaiting_review_request` 在 `stale` **之前**:卡还没发起评审,先说"去发起",别拿证据态盖住流程态。
19
+ * 2. `stale` 在 `awaiting_human_done` / `review_pending` **之前**:证据或版本变了就**不许**再邀请人点「完成」
20
+ * (GWT-3 的产品含义就是这一条 —— 否则人点下去确认的是他没看过的那一版)。
21
+ * 3. `review_pending` 在 `format_ok` **之前**:卡已在评审队列里,"等你评审"比"格式合格"更该先说。
22
+ */
23
+ import { deriveNextStep } from "./next-step.mjs";
24
+ import { assessTask } from "./watchdog.mjs";
25
+ import { latestAutoReview } from "./verify.mjs";
26
+ import { evidenceFormatOk } from "./evidence.mjs";
27
+
28
+ /** 全部可能的阶段(同时也是**优先级**顺序的声明式副本,测试用它做白名单校验)。 */
29
+ export const TICKET_STAGES = Object.freeze([
30
+ "done", "canceled",
31
+ "human_review_pending", "blocked_by_human_review",
32
+ "awaiting_review_request", "stale",
33
+ "rework", "awaiting_human_done", "review_pending",
34
+ "ready", "refs_unresolved", "format_ok",
35
+ "blocked", "in_progress", "todo", "backlog", "not_ready",
36
+ ]);
37
+
38
+ /** 交付物漏斗状态(`stage` 的候选来源)。 */
39
+ export const DELIVERY_STATES = Object.freeze(["none", "incomplete", "refs_unresolved", "format_ok", "ready", "stale"]);
40
+
41
+ const text = (v) => (typeof v === "string" ? v.trim() : "");
42
+ const norm = (v) => (v === null || v === undefined || v === "" ? null : String(v));
43
+
44
+ function labelList(task) {
45
+ return Array.isArray(task?.labels) ? task.labels.map((l) => text(l)) : [];
46
+ }
47
+
48
+ /**
49
+ * 交付物漏斗(纯):`none` → `incomplete` / `refs_unresolved` → `format_ok` → `ready`,判过又变 → `stale`。
50
+ *
51
+ * 只认 `layer="llm"` 的判定:规则层通过(`format_ok`)不是"内容已判",不能冒充 `ready`(GWT-2)。
52
+ */
53
+ export function deriveDelivery({ task = {}, evidence = null, decision = null } = {}) {
54
+ const llm = decision && String(decision.layer ?? "") === "llm" ? decision : null;
55
+ if (llm) {
56
+ const decisionVerdict = String(llm.decision ?? "");
57
+ if (decisionVerdict !== "ready") {
58
+ // 判过但没判成 ready(如 needs_changes):不是 ready,也不是 stale —— 交回人看判定理由。
59
+ return { state: "incomplete", reason: `判定层结论 ${decisionVerdict || "(空)"}`, decision: llm };
60
+ }
61
+ const evidenceIdMismatch = !evidence || (llm.evidenceId ?? null) !== evidence.id;
62
+ const versionMismatch = Number(llm.taskVersion) !== Number(task?.version);
63
+ if (evidenceIdMismatch || versionMismatch) {
64
+ return {
65
+ state: "stale",
66
+ reason: evidenceIdMismatch
67
+ ? `判定绑定的证据 ${llm.evidenceId ?? "(空)"} 不是当前最新证据 ${evidence?.id ?? "(无)"}`
68
+ : `判定绑定版本 v${llm.taskVersion} ≠ 当前 v${task?.version}`,
69
+ decision: llm,
70
+ evidenceId: evidence?.id ?? null,
71
+ };
72
+ }
73
+ return { state: "ready", reason: "判定与证据/版本一致", decision: llm, evidenceId: evidence.id };
74
+ }
75
+ if (!evidence) return { state: "none", reason: "尚无结构化证据" };
76
+ if (evidence.refsState === "unresolved") {
77
+ return { state: "refs_unresolved", reason: "artifact_refs 有解不开的 commit/file", evidenceId: evidence.id };
78
+ }
79
+ if (!evidenceFormatOk(evidence)) {
80
+ return { state: "incomplete", reason: "证据四字段不全", evidenceId: evidence.id };
81
+ }
82
+ return { state: "format_ok", reason: "四字段齐、无内容判定", evidenceId: evidence.id };
83
+ }
84
+
85
+ /**
86
+ * 归一为单一 `stage`(纯)。优先级见文件头三条。
87
+ * 返回 `{ stage, reason, delivery, next, watch, verify, diagnostics }` ——
88
+ * 后四者是**同批读数**(不参与 stage 计算,但同一函数给出,避免调用方各取一套再自己拼)。
89
+ * `next` = `deriveNextStep()` 的**完整**回包,`watch` = `assessTask()` 的**完整**回包(卡 `-199`:
90
+ * 抽屉直接消费这两个对象,不再各自去请求 `/next-step` 与 `/execution`)。
91
+ */
92
+ export function ticketStage(task = {}, ctx = {}) {
93
+ const t = task ?? {};
94
+ const status = String(t.status ?? "");
95
+ const review = norm(t.reviewState);
96
+ const labels = labelList(t);
97
+ const delivery = deriveDelivery({ task: t, evidence: ctx.evidence ?? null, decision: ctx.decision ?? null });
98
+
99
+ const watch = assessTask({
100
+ task: t,
101
+ comments: ctx.comments ?? [],
102
+ sessionState: ctx.sessionState ?? null,
103
+ currentRun: ctx.currentRun ?? null,
104
+ now: ctx.now,
105
+ thresholdMs: ctx.thresholdMs,
106
+ });
107
+ // 「停滞」只有一个来源:看护读数。**不接受调用方另给一个布尔** —— 那等于在同一条链上留第二个口径
108
+ // (真机教训:`next-step` 与 `watchdog` 对同一张卡给出相反结论时,人不知道该信哪个)。
109
+ const stalled = watch.state === "stalled";
110
+ const next = deriveNextStep(t, { humanReviewBlocker: ctx.humanReviewBlocker ?? null, stalled });
111
+ const autoReview = latestAutoReview(ctx.comments ?? []);
112
+
113
+ // 卡 `-199`(FR-108 收口):`next` / `watch` **原样整份透传**,不再削成 `{code,title}` / `{state,minutes}`。
114
+ // 削字段不是"瘦身",是**静默删功能**:`next` 少了 `hint/steps/focus/actions/blocker`,「下一步」区块
115
+ // 就只剩一句标题(步骤、按钮、默认折叠、前置卡跳转全没了);`watch` 少了 `followups/reason`,
116
+ // 「派生为子任务 / 忽略」与「执行会话未在线」文案就一起消失。调用方只消费这一份,所以必须给全。
117
+ const base = {
118
+ delivery,
119
+ next,
120
+ watch,
121
+ verify: autoReview ? { verdict: autoReview.verdict ?? null, at: autoReview.at ?? null } : null,
122
+ diagnostics: Array.isArray(ctx.diagnostics) ? ctx.diagnostics.slice() : [],
123
+ };
124
+
125
+ // 1) 终态
126
+ if (status === "done") return { stage: "done", reason: "已完成", ...base };
127
+ if (status === "canceled") return { stage: "canceled", reason: "已取消", ...base };
128
+
129
+ // 2) 人工校验门(人在环升级门:执行侧不得认领/不得 done)
130
+ const humanReview = labels.includes("human_review");
131
+ if (humanReview && String(t.humanReviewState ?? "pending") !== "concluded") {
132
+ return { stage: "human_review_pending", reason: "人工校验卡待结论", ...base };
133
+ }
134
+ if (ctx.humanReviewBlocker) {
135
+ return { stage: "blocked_by_human_review", reason: `被人工校验门挡住:${ctx.humanReviewBlocker.identifier ?? "?"}`, ...base };
136
+ }
137
+
138
+ // 3) 待验收但从未发起评审(GWT-4:先于其他分支)
139
+ if (status === "in_review" && !t.reviewRequestedAt) {
140
+ return { stage: "awaiting_review_request", reason: "在待验收但未发起评审", ...base };
141
+ }
142
+
143
+ // 4) 证据/版本已变(GWT-3:不得显示为 ready,也不得邀请人点完成)
144
+ if (delivery.state === "stale") return { stage: "stale", reason: delivery.reason, ...base };
145
+
146
+ // 5) 评审流程态
147
+ if (status === "in_review" && review === "changes_requested") return { stage: "rework", reason: "评审要求返工", ...base };
148
+ if (status === "in_review" && review === "approved") return { stage: "awaiting_human_done", reason: "评审已通过,等人工确认完成", ...base };
149
+ if (status === "in_review") return { stage: "review_pending", reason: "等待评审", ...base };
150
+
151
+ // 6) 交付物漏斗(非评审队列时,"交付物到哪一步"就是这张卡的阶段)
152
+ if (delivery.state === "ready") return { stage: "ready", reason: delivery.reason, ...base };
153
+ if (delivery.state === "refs_unresolved") return { stage: "refs_unresolved", reason: delivery.reason, ...base };
154
+ if (delivery.state === "format_ok") return { stage: "format_ok", reason: delivery.reason, ...base };
155
+
156
+ // 7) 普通流程态
157
+ if (status === "blocked") return { stage: "blocked", reason: "受阻", ...base };
158
+ if (status === "in_progress") return { stage: "in_progress", reason: "进行中", ...base };
159
+ if (status === "todo") return { stage: "todo", reason: "待办", ...base };
160
+ if (status === "backlog") return { stage: "backlog", reason: "待办池", ...base };
161
+ return { stage: "not_ready", reason: delivery.reason, ...base };
162
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * flow-block.mjs —— 「装载块」的唯一生成器(P4 · 2026-10-29)
3
+ *
4
+ * 三档开局(档 A 人贴 / 档 B 外部 agent 约定 / 将来的档 C 宿主注入)**必须产出同一份文本**,
5
+ * 否则会出现三份不同的说明书 —— 这正是本仓过去栽过的坑(同名两条 SOP,谁都不知道信哪个)。
6
+ *
7
+ * 所以这里只有一处实现:
8
+ * · `node scripts/tb-flow.mjs start` → `buildFlowBlock()`
9
+ * · MCP prompt `taskboard.flow` → `buildFlowBlock()`
10
+ * · 将来的宿主注入(档 C) → 也调 `buildFlowBlock()`
11
+ *
12
+ * **不复制 SKILL.md 的正文**:八步表格与五条硬规则都从 `skills/taskboard-flow/SKILL.md`
13
+ * 的标记区间里**原样抽取**(`<!-- flow-block:steps -->` / `<!-- flow-block:rules -->`)。
14
+ * 这样 skill 改了,装载块跟着改;本文件永远不会"自己长出一份规则"。
15
+ */
16
+ import { existsSync, readFileSync } from "node:fs";
17
+ import path from "node:path";
18
+
19
+ import { PKG_ROOT, deriveFlowNext, projectGaps, resolveProject } from "./tools.mjs";
20
+
21
+ export const SKILL_DIR = path.join(PKG_ROOT, "skills", "taskboard-flow");
22
+ export const SKILL_PATH = path.join(SKILL_DIR, "SKILL.md");
23
+
24
+ const STEPS_OPEN = "<!-- flow-block:steps -->";
25
+ const STEPS_CLOSE = "<!-- /flow-block:steps -->";
26
+ const RULES_OPEN = "<!-- flow-block:rules -->";
27
+ const RULES_CLOSE = "<!-- /flow-block:rules -->";
28
+
29
+ function sliceBetween(text, open, close) {
30
+ const i = text.indexOf(open);
31
+ const j = text.indexOf(close);
32
+ if (i < 0 || j < 0 || j <= i) return "";
33
+ return text.slice(i + open.length, j).trim();
34
+ }
35
+
36
+ /** 读 SKILL.md 的 frontmatter(只支持本项目用到的 `key: value` 平铺形状)。 */
37
+ function parseFrontmatter(text) {
38
+ const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
39
+ if (!m) return {};
40
+ const out = {};
41
+ for (const line of m[1].split(/\r?\n/)) {
42
+ const kv = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line.trim());
43
+ if (!kv) continue;
44
+ let value = kv[2].trim();
45
+ if (value.startsWith("[") && value.endsWith("]")) {
46
+ value = value.slice(1, -1).split(",").map((x) => x.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
47
+ } else {
48
+ value = value.replace(/^["']|["']$/g, "");
49
+ if (/^\d+$/.test(value)) value = Number(value);
50
+ }
51
+ out[kv[1]] = value;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** 只读:把 skill 的三段(meta / 八步 / 五条硬规则)取出来。 */
57
+ export function readSkill() {
58
+ if (!existsSync(SKILL_PATH)) {
59
+ throw new Error(`skill 缺失:${SKILL_PATH}(打包时请确认 package.json#files 含 "skills")`);
60
+ }
61
+ const text = readFileSync(SKILL_PATH, "utf8");
62
+ const meta = parseFrontmatter(text);
63
+ const steps = sliceBetween(text, STEPS_OPEN, STEPS_CLOSE);
64
+ const rules = sliceBetween(text, RULES_OPEN, RULES_CLOSE);
65
+ if (!steps) throw new Error(`SKILL.md 缺少八步标记区间(${STEPS_OPEN} … ${STEPS_CLOSE})`);
66
+ if (!rules) throw new Error(`SKILL.md 缺少硬规则标记区间(${RULES_OPEN} … ${RULES_CLOSE})`);
67
+ return { meta, steps, rules, path: SKILL_PATH, relPath: "skills/taskboard-flow/SKILL.md" };
68
+ }
69
+
70
+ const shortDigest = (d) => (typeof d === "string" && d.length >= 8 ? `${d.slice(0, 8)}…` : "(未取到)");
71
+
72
+ /**
73
+ * 生成装载块(纯读:不写库、不建目录)。
74
+ *
75
+ * @returns {{text:string, project:object, contract:object, gaps:object, nextStep:object, skill:object}}
76
+ */
77
+ export function buildFlowBlock({ store, project, cwd, matchedBy } = {}) {
78
+ const skill = readSkill();
79
+ const resolved = project && typeof project === "object"
80
+ ? { project, matchedBy: matchedBy ?? "explicit" }
81
+ : resolveProject(store, { project, cwd });
82
+ const { tasks, items, gaps } = projectGaps(store, resolved.project);
83
+ const nextStep = deriveFlowNext({ tasks, items, gaps });
84
+ const snap = store.contractSnapshot(resolved.project.id);
85
+ const snapVersion = snap.snapshot.contractVersion;
86
+ const normOf = (id) => (snap.snapshot.norms ?? []).find((n) => n.id === id);
87
+ const changed = Array.isArray(snap.changed?.changedFiles) ? snap.changed.changedFiles : [];
88
+
89
+ const lines = [
90
+ "# 任务看板主流程 · 装载块",
91
+ "",
92
+ `> 由 taskboard-workbench 生成(skill \`taskboard-flow@v${skill.meta.version ?? "?"}\` · 契约 \`${snapVersion}\`)。`,
93
+ "> 把这一整块当本轮上下文即可开工;**下面第 4 节的八步是全文,不要只看摘要**。",
94
+ "",
95
+ "## 1. 项目",
96
+ "",
97
+ `- id:\`${resolved.project.id}\``,
98
+ `- 名称:${resolved.project.name}`,
99
+ `- 工作区:${resolved.project.workspacePath ? `\`${resolved.project.workspacePath}\`` : "(未设置)"}`,
100
+ `- 主会话:${resolved.project.initialSessionId ? `\`${resolved.project.initialSessionId}\`` : "**未绑定**(投递会落空)"}`,
101
+ `- 匹配方式:${resolved.matchedBy}`,
102
+ "",
103
+ "## 2. 契约",
104
+ "",
105
+ `- contract_version:\`${snapVersion}\``,
106
+ `- 规范:${(snap.snapshot.norms ?? []).map((n) => `${n.id}@v${n.version}(${shortDigest(n.digest)})`).join(" · ")}`,
107
+ `- 与基线比对:${snap.stale ? `**已漂移**(${changed.join(" / ") || "未报出文件"})—— 先读变更部分再动手` : "一致"}`,
108
+ `- 门档:${Object.entries(snap.snapshot.gates ?? {}).map(([k, v]) => `${k}=${v}`).join(" · ")}`,
109
+ "",
110
+ "## 3. 现在缺什么(gaps)",
111
+ "",
112
+ `- 未归因卡:**${gaps.unattributedTasks}**${gaps.unattributedTasks ? `(先补归因再派发,否则 \`EXECUTION_NOT_ATTRIBUTED\`)` : "(干净)"}`,
113
+ `- 未绑定主会话:${gaps.unboundSession ? "**是** ⇒ 回看板「重建/绑定主会话」" : "否"}`,
114
+ `- 待确认候选:**${gaps.pendingCandidates}**${gaps.pendingCandidates > 20 ? "(超阈值 20 ⇒ 先确认/丢弃,别急着条目化)" : ""}`,
115
+ `- 无任务的条目:${gaps.requirementsWithoutTasks} · 评审中卡:${gaps.tasksInReview} · 受阻卡:${gaps.tasksBlocked}`,
116
+ `- 看板:任务 ${tasks.length} · 需求条目 ${items.length}`,
117
+ "",
118
+ "## 4. 本轮该先做",
119
+ "",
120
+ `**${nextStep.step} · ${nextStep.title}** —— ${nextStep.why}`,
121
+ nextStep.humanAction === "authorize" ? "\n> ⚠ 这一步要**人**做(`backlog → todo` 是人工授权),执行侧不得代点。" : "",
122
+ nextStep.humanAction === "accept" ? "\n> ⚠ 这一步要**人**做(`done` 只能人点;评审门 + 人工收口)。" : "",
123
+ "",
124
+ "## 5. 八步(完整定义,取自 `skills/taskboard-flow/SKILL.md`)",
125
+ "",
126
+ skill.steps,
127
+ "",
128
+ "## 6. 五条硬规则(都由门守,不靠自觉)",
129
+ "",
130
+ skill.rules,
131
+ "",
132
+ "## 7. 取规范正文(别凭记忆)",
133
+ "",
134
+ "- 主流程:`norm_get { norm: \"flow\" }`",
135
+ "- 卡片更新(回填要它的 digest):`norm_get { norm: \"card-update\" }`",
136
+ "- 项目自有补充:`norm_get { norm: \"project\", project: \"" + resolved.project.id + "\" }`(读 `<workspace>/AGENTS.md`)",
137
+ "",
138
+ "## 8. 开工前的自检(一条命令)",
139
+ "",
140
+ "```bash",
141
+ `node scripts/tb-flow.mjs start --project ${resolved.project.id} # 与本块同源`,
142
+ "```",
143
+ ];
144
+
145
+ return {
146
+ text: lines.filter((l) => l !== undefined).join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n",
147
+ project: { id: resolved.project.id, name: resolved.project.name, workspacePath: resolved.project.workspacePath ?? null, matchedBy: resolved.matchedBy },
148
+ contract: { version: snapVersion, stale: Boolean(snap.stale), changed, gates: snap.snapshot.gates ?? {} },
149
+ gaps,
150
+ nextStep,
151
+ skill: { name: skill.meta.name ?? "taskboard-flow", version: skill.meta.version ?? null, requiresContract: skill.meta.requires_contract ?? null, path: skill.relPath },
152
+ };
153
+ }
154
+
155
+ /** 档 B:给项目 `AGENTS.md` 用的片段(只指路,不复制正文)。 */
156
+ export function buildAgentsSnippet({ project, pkgPath } = {}) {
157
+ const pkg = pkgPath ?? PKG_ROOT;
158
+ const proj = project ? ` --project ${project}` : " --project <项目id>";
159
+ return [
160
+ "## 开工(任务看板主流程)",
161
+ "",
162
+ "本项目用 taskboard-workbench 管任务。**动代码之前**先跑:",
163
+ "",
164
+ "```bash",
165
+ `node ${pkg}/scripts/tb-flow.mjs start${proj}`,
166
+ "```",
167
+ "",
168
+ "把输出的「装载块」当本轮上下文:`nextStep` 就是本轮该先做的事,`gaps` 告诉你哪里还欠账。",
169
+ `流程细节见 \`${pkg}/skills/taskboard-flow/SKILL.md\`。`,
170
+ "",
171
+ "> 这段只指路,不替代本文件其余约定。",
172
+ ].join("\n");
173
+ }
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * server.mjs —— Taskboard Workbench MCP server(stdio · 零依赖 · 只读五 + 写四)。
4
+ *
5
+ * 方案依据:§6.1 —— **stdio 而不是 HTTP**:① 不占端口、不碰 `:3080`;② 不需要重载宿主、
6
+ * 不写 `~/.dsh/**`;③ 每个 agent 会话一个进程,天然隔离。数据连**同一个** `taskboard.sqlite`。
7
+ *
8
+ * 用法:
9
+ * node src/mcp/server.mjs --data-dir <dir> # 由 MCP 客户端作为子进程拉起
10
+ * node src/mcp/server.mjs --print-tools # 打印工具清单(调试 / 守卫测试用)
11
+ * node src/mcp/server.mjs --read-only # **只读模式**(P3 的回滚开关):写四件不出现在 tools/list,调用即 READ_ONLY_MODE
12
+ *
13
+ * 传输:newline-delimited JSON-RPC 2.0(MCP stdio transport)。
14
+ * stdout **只允许**出现协议消息;日志一律走 stderr(否则客户端解析失败)。
15
+ */
16
+ import { createInterface } from "node:readline";
17
+ import { readFileSync } from "node:fs";
18
+ import path from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ import { openStore } from "../core/store.mjs";
22
+ import { TbError } from "../core/errors.mjs";
23
+ import { TOOLS, TOOL_NAMES, PKG_ROOT } from "./tools.mjs";
24
+ import { buildFlowBlock, readSkill } from "./flow-block.mjs";
25
+
26
+ const argv = process.argv.slice(2);
27
+ const argOf = (name) => {
28
+ const i = argv.indexOf(name);
29
+ return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
30
+ };
31
+ const has = (name) => argv.includes(name);
32
+
33
+ // P3 的回滚开关(方案 §十 回滚列 / 风险表 R2):只读模式下按 annotations.readOnlyHint 过滤工具面。
34
+ // 这是**承诺过的逃生口** —— 写工具出问题时应能一条参数降级,而不是回退提交。
35
+ const READ_ONLY = has("--read-only");
36
+ const ACTIVE_TOOLS = READ_ONLY ? TOOLS.filter((t) => t.annotations?.readOnlyHint === true) : TOOLS;
37
+ const ACTIVE_NAMES = ACTIVE_TOOLS.map((t) => t.name);
38
+
39
+ if (has("--help") || has("-h")) {
40
+ process.stderr.write(`taskboard-workbench MCP server(9 个工具:只读五 / 写四 · prompt 1)
41
+ 用法: node src/mcp/server.mjs [--data-dir <dir>] [--print-tools] [--read-only]
42
+ 只读: --read-only 关闭写四件(card_create / card_progress / requirement_upsert / requirement_change)——P3 的回滚开关
43
+ 工具: ${TOOL_NAMES.join(", ")}
44
+ 提示: prompt taskboard.flow(= node scripts/tb-flow.mjs start 的输出)
45
+ 数据: --data-dir > $TB_DATA_DIR > 默认(同 Web/CLI)
46
+ `);
47
+ process.exit(0);
48
+ }
49
+
50
+ const pkg = JSON.parse(readFileSync(path.join(PKG_ROOT, "package.json"), "utf8"));
51
+
52
+ if (has("--print-tools")) {
53
+ process.stdout.write(`${JSON.stringify({ name: pkg.name, version: pkg.version, readOnly: READ_ONLY, tools: ACTIVE_NAMES }, null, 2)}\n`);
54
+ process.exit(0);
55
+ }
56
+
57
+ const dataDir = argOf("--data-dir") ?? process.env.TB_DATA_DIR ?? undefined;
58
+ const store = openStore({ dataDir, env: process.env });
59
+ const ctx = { store };
60
+ let skillMeta = null;
61
+ try { skillMeta = readSkill().meta; } catch { /* skill 缺失时不影响工具面;prompts/* 会报出具体原因 */ }
62
+ process.stderr.write(`[tb-mcp] ready dataDir=${store.dataDir} readOnly=${READ_ONLY} tools=${ACTIVE_NAMES.join(",")} prompt=taskboard.flow skill=${skillMeta ? `v${skillMeta.version}` : "missing"}\n`);
63
+
64
+ const SERVER_INFO = { name: "taskboard-workbench", version: pkg.version };
65
+ const DEFAULT_PROTOCOL = "2025-06-18";
66
+
67
+ const send = (payload) => {
68
+ if (payload === null || payload === undefined) return;
69
+ process.stdout.write(`${JSON.stringify(payload)}\n`);
70
+ };
71
+ const result = (id, value) => ({ jsonrpc: "2.0", id, result: value });
72
+ const rpcError = (id, code, message, data) => ({ jsonrpc: "2.0", id, error: { code, message, ...(data === undefined ? {} : { data }) } });
73
+
74
+ /** 工具错误 → `isError:true` 的 content(协议层没坏,是这次调用不成立)。 */
75
+ const toolError = (error) => {
76
+ const body = error instanceof TbError
77
+ ? { error: { code: error.code, message: error.message, details: error.details ?? null } }
78
+ : { error: { code: "INTERNAL_ERROR", message: error?.message ?? String(error) } };
79
+ return { content: [{ type: "text", text: JSON.stringify(body, null, 2) }], isError: true };
80
+ };
81
+
82
+ function listTools() {
83
+ return ACTIVE_TOOLS.map((t) => ({
84
+ name: t.name,
85
+ description: t.description,
86
+ inputSchema: t.inputSchema,
87
+ annotations: t.annotations,
88
+ }));
89
+ }
90
+
91
+ async function handle(message) {
92
+ if (!message || typeof message !== "object" || Array.isArray(message)) return rpcError(null, -32600, "Invalid Request");
93
+ const { id, method, params } = message;
94
+ const isNotification = id === undefined || id === null;
95
+
96
+ if (method === "initialize") {
97
+ const requested = typeof params?.protocolVersion === "string" ? params.protocolVersion : DEFAULT_PROTOCOL;
98
+ return result(id, { protocolVersion: requested, capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } }, serverInfo: SERVER_INFO });
99
+ }
100
+ if (typeof method === "string" && method.startsWith("notifications/")) return null;
101
+ if (method === "ping") return result(id, {});
102
+ if (method === "tools/list") return result(id, { tools: listTools() });
103
+ if (method === "tools/call") {
104
+ const name = params?.name;
105
+ const tool = ACTIVE_TOOLS.find((t) => t.name === name);
106
+ if (!tool) {
107
+ // 只读模式下「写工具存在但被关掉」与「工具根本不存在」必须分开报:
108
+ // 前者是**预期降级**(回滚开关生效),后者是客户端拼错了名字。
109
+ if (READ_ONLY && TOOLS.some((t) => t.name === name)) {
110
+ return result(id, toolError(new TbError(
111
+ "READ_ONLY_MODE",
112
+ `--read-only 已启用:写工具 ${name} 不可用(P3 回滚开关)。只读工具:${ACTIVE_NAMES.join(", ")}`,
113
+ { tool: name, readOnly: true, available: ACTIVE_NAMES },
114
+ )));
115
+ }
116
+ return rpcError(id, -32602, `Unknown tool: ${name ?? "(missing)"}`, { tools: ACTIVE_NAMES });
117
+ }
118
+ try {
119
+ const value = await tool.handler(ctx, params?.arguments ?? {});
120
+ return result(id, { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], isError: false });
121
+ } catch (error) {
122
+ return result(id, toolError(error));
123
+ }
124
+ }
125
+ // ---- prompts:档 A「一键拉取装载块」 ----
126
+ // 与 `node scripts/tb-flow.mjs start` 共用 buildFlowBlock() ⇒ 两处输出**必须逐字节相同**(守卫测试钉住)。
127
+ if (method === "prompts/list") {
128
+ return result(id, {
129
+ prompts: [{
130
+ name: "taskboard.flow",
131
+ title: "任务看板主流程装载块",
132
+ description: "八步主流程 + 当前项目快照 + 本轮该先做的事(只读;与 `tb-flow start` 同源)",
133
+ arguments: [
134
+ { name: "project", description: "项目 id(省略则按 cwd 匹配)", required: false },
135
+ { name: "cwd", description: "工作目录(默认进程 cwd)", required: false },
136
+ ],
137
+ }],
138
+ });
139
+ }
140
+ if (method === "prompts/get") {
141
+ const name = params?.name;
142
+ if (name !== "taskboard.flow") return rpcError(id, -32602, `Unknown prompt: ${name ?? "(missing)"}`, { prompts: ["taskboard.flow"] });
143
+ const args = params?.arguments ?? {};
144
+ try {
145
+ const block = buildFlowBlock({ store: ctx.store, project: args.project, cwd: args.cwd });
146
+ return result(id, {
147
+ description: `任务看板主流程装载块(${block.project.id} · 契约 ${block.contract.version})`,
148
+ messages: [{ role: "user", content: { type: "text", text: block.text } }],
149
+ });
150
+ } catch (error) {
151
+ return rpcError(id, -32603, error instanceof TbError ? `${error.code}: ${error.message}` : (error?.message ?? String(error)), error instanceof TbError ? { code: error.code, details: error.details ?? null } : undefined);
152
+ }
153
+ }
154
+ if (isNotification) return null;
155
+ return rpcError(id, -32601, `Method not found: ${method ?? "(missing)"}`);
156
+ }
157
+
158
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
159
+ rl.on("line", (line) => {
160
+ const text = line.trim();
161
+ if (text === "") return;
162
+ let message;
163
+ try { message = JSON.parse(text); }
164
+ catch (error) {
165
+ send(rpcError(null, -32700, `Parse error: ${error.message}`));
166
+ return;
167
+ }
168
+ Promise.resolve(handle(message)).then(send).catch((error) => {
169
+ send(rpcError(message?.id ?? null, -32603, error?.message ?? "Internal error"));
170
+ });
171
+ });
172
+ rl.on("close", () => {
173
+ try { store.close(); } catch { /* ignore */ }
174
+ process.exit(0);
175
+ });