taskboard-workbench 0.0.0-stage → 0.3.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 (75) hide show
  1. package/CHANGELOG.md +403 -0
  2. package/LICENSE +21 -0
  3. package/README.md +210 -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 +96 -4
  9. package/scripts/tb-flow.mjs +86 -0
  10. package/skills/taskboard-flow/SKILL.md +89 -0
  11. package/skills/taskboard-flow/references/errors.md +61 -0
  12. package/skills/taskboard-flow/references/injection.md +70 -0
  13. package/skills/taskboard-flow/references/steps/S0.md +31 -0
  14. package/skills/taskboard-flow/references/steps/S1.md +28 -0
  15. package/skills/taskboard-flow/references/steps/S2.md +31 -0
  16. package/skills/taskboard-flow/references/steps/S3.md +22 -0
  17. package/skills/taskboard-flow/references/steps/S4.md +25 -0
  18. package/skills/taskboard-flow/references/steps/S5.md +36 -0
  19. package/skills/taskboard-flow/references/steps/S6.md +30 -0
  20. package/skills/taskboard-flow/references/steps/S7.md +23 -0
  21. package/spec/norms/acceptance.md +36 -0
  22. package/spec/norms/card-update.md +39 -0
  23. package/spec/norms/doc-editing.md +30 -0
  24. package/spec/norms/flow.md +45 -0
  25. package/spec/norms/manifest.json +41 -0
  26. package/spec/norms/project-defaults.md +33 -0
  27. package/spec//345/233/242/351/230/237agent.md +171 -0
  28. package/src/core/acceptance.mjs +62 -0
  29. package/src/core/advance.mjs +192 -0
  30. package/src/core/agent-teams.mjs +48 -0
  31. package/src/core/binding.mjs +44 -0
  32. package/src/core/config.mjs +22 -0
  33. package/src/core/contract.mjs +287 -0
  34. package/src/core/debug-dispatch.mjs +94 -0
  35. package/src/core/delivery.mjs +93 -0
  36. package/src/core/deps.mjs +53 -0
  37. package/src/core/diagnostics.mjs +648 -0
  38. package/src/core/domain.mjs +235 -0
  39. package/src/core/empty-state.mjs +240 -0
  40. package/src/core/errors.mjs +142 -0
  41. package/src/core/evidence.mjs +86 -0
  42. package/src/core/executor.mjs +645 -0
  43. package/src/core/human-review.mjs +773 -0
  44. package/src/core/intake.mjs +179 -0
  45. package/src/core/kickoff.mjs +147 -0
  46. package/src/core/loop.mjs +498 -0
  47. package/src/core/memory.mjs +193 -0
  48. package/src/core/next-step.mjs +377 -0
  49. package/src/core/notify.mjs +183 -0
  50. package/src/core/owner.mjs +41 -0
  51. package/src/core/requirements.mjs +292 -0
  52. package/src/core/review.mjs +82 -0
  53. package/src/core/session-naming.mjs +64 -0
  54. package/src/core/split-ask.mjs +107 -0
  55. package/src/core/store.mjs +3442 -0
  56. package/src/core/team.mjs +170 -0
  57. package/src/core/ticket-stage.mjs +150 -0
  58. package/src/core/verify.mjs +170 -0
  59. package/src/core/watchdog.mjs +144 -0
  60. package/src/host/ai-elaborator.mjs +26 -0
  61. package/src/host/team-engine.mjs +125 -0
  62. package/src/host/tool-surface.mjs +205 -0
  63. package/src/mcp/flow-block.mjs +173 -0
  64. package/src/mcp/server.mjs +156 -0
  65. package/src/mcp/tools.mjs +764 -0
  66. package/src/server/api.mjs +2050 -0
  67. package/src/server/events.mjs +32 -0
  68. package/src/server/kickoff.mjs +46 -0
  69. package/src/server/server.mjs +214 -0
  70. package/src/server/verify.mjs +112 -0
  71. package/tools/env-check.mjs +35 -0
  72. package/tools/seed.mjs +67 -0
  73. package/web/app.js +5337 -0
  74. package/web/index.html +15 -0
  75. package/web/tokens.css +1151 -0
@@ -0,0 +1,44 @@
1
+ /**
2
+ * binding.mjs —— 工作区 ↔ 项目 ↔ 需求文档 的绑定核心(FR-02/34)。
3
+ * 会话/工作区(cwd)→ 最长前缀匹配项目(workspacePath);无匹配回落默认项目;项目必有需求文档。
4
+ */
5
+ const norm = (p) => String(p ?? "").replace(/\/+$/, "");
6
+
7
+ /**
8
+ * 按 cwd 解析所属项目:workspacePath 最长前缀命中优先;否则回落第一个项目(默认项目)。
9
+ * 与 `matchProjectForCwd` 同一口径 —— 两者的唯一差别只是**要不要如实报告"是否命中"**。
10
+ */
11
+ export function resolveProjectForCwd(store, cwd) {
12
+ return matchProjectForCwd(store, cwd).project;
13
+ }
14
+
15
+ /**
16
+ * 与 `resolveProjectForCwd` 同口径,但**额外如实报告是否由 cwd 命中**。
17
+ * 用途:FR-29 要求"cwd 无法匹配项目而回落默认项目时**必须提示用户**" —— 只拿到 project
18
+ * 是分不出"真命中"和"回落"的(回落也是返回一个项目)。
19
+ */
20
+ export function matchProjectForCwd(store, cwd) {
21
+ const projects = store.listProjects();
22
+ if (projects.length === 0) return { project: null, matched: false };
23
+ const target = norm(cwd);
24
+ if (target) {
25
+ let best = null;
26
+ for (const p of projects) {
27
+ const wp = norm(p.workspacePath);
28
+ if (!wp) continue;
29
+ if (target === wp || target.startsWith(`${wp}/`)) {
30
+ if (!best || wp.length > norm(best.workspacePath).length) best = p;
31
+ }
32
+ }
33
+ if (best) return { project: best, matched: true };
34
+ }
35
+ return { project: projects.find((p) => p.id === "default") ?? projects[0], matched: false };
36
+ }
37
+
38
+ /** 解析"当前工作区上下文":{ project, requirementDoc }(需求文档不存在则自动建立)。 */
39
+ export function resolveContext(store, cwd) {
40
+ const project = resolveProjectForCwd(store, cwd);
41
+ if (!project) return { project: null, requirementDoc: null };
42
+ const requirementDoc = store.ensureRequirementDoc(project.id);
43
+ return { project, requirementDoc };
44
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 运行期配置:数据目录解析(FR-31/FR-33)。
3
+ * 优先级:显式参数 --data-dir > 环境变量 TB_DATA_DIR > 默认临时目录。
4
+ * 默认放临时目录,保证"运行不写仓库"(本机仓库目录只读)。
5
+ */
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+
9
+ export const DEFAULT_DATA_DIR = path.join(os.tmpdir(), "tb-workbench-mvp-a");
10
+ export const DB_FILENAME = "taskboard.sqlite";
11
+
12
+ export function resolveDataDir({ dataDir, env = process.env } = {}) {
13
+ const fromArg = typeof dataDir === "string" ? dataDir.trim() : "";
14
+ if (fromArg) return path.resolve(fromArg);
15
+ const fromEnv = typeof env.TB_DATA_DIR === "string" ? env.TB_DATA_DIR.trim() : "";
16
+ if (fromEnv) return path.resolve(fromEnv);
17
+ return DEFAULT_DATA_DIR;
18
+ }
19
+
20
+ export function resolveDbPath(dataDir) {
21
+ return path.join(dataDir, DB_FILENAME);
22
+ }
@@ -0,0 +1,287 @@
1
+ /**
2
+ * contract.mjs —— 契约快照(P1 · 2026-10-29)
3
+ *
4
+ * 方案依据:`docs/设计/技能化与MCP契约-架构变更方案-2026-10-28.md`
5
+ * §6.4 契约版本与规范摘要校验 · §7.1 frontmatter 契约 · §8 数据模型 · §17.3.1 D4 最终裁定。
6
+ *
7
+ * 一句话:**把「规范读了就算」变成「用旧规范干活会显性失败」**。
8
+ *
9
+ * contract_version = f(需求文档 digest, 机器规范 digest×版本, 门配置)
10
+ *
11
+ * 三条设计约束(都是被踩出来的):
12
+ * ① **本模块不写库、不改状态** —— 纯计算 + 纯读文件,谁都能安全调(HTTP / MCP / CLI 同一份实现,
13
+ * 防「六个入口两种语义」);
14
+ * ② **机器规范唯一真源是 `spec/norms/*.md`**(随包分发);`docs/规范/*.md` 是给人读的开发文档,
15
+ * 永不入 git,**不作为任何运行时真源**(D4 用户二次拍板,不可改变);
16
+ * ③ **正文变了但 version 没 bump ⇒ 守卫报红**(`tests/norms-parity.test.mjs`)——
17
+ * 否则「悄悄改规范」就是下一个不可追的漂移源。
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
21
+ import path from "node:path";
22
+
23
+ import { TbError } from "./errors.mjs";
24
+
25
+ /** 随包分发的五份机器规范(缺一份即 `NORM_NOT_FOUND`)。 */
26
+ export const NORM_IDS = Object.freeze(["flow", "card-update", "doc-editing", "acceptance", "project-defaults"]);
27
+
28
+ /** 参与 contract_version 的门配置项(顺序固定 ⇒ 可复现)。 */
29
+ export const GATE_NAMES = Object.freeze(["attribution", "authorization", "review", "humanReview"]);
30
+
31
+ export const CONTRACT_VERSION_PREFIX = "v1-";
32
+
33
+ export function sha256(text) {
34
+ return createHash("sha256").update(String(text ?? ""), "utf8").digest("hex");
35
+ }
36
+
37
+ /**
38
+ * 解析带 frontmatter 的规范正文。
39
+ *
40
+ * 只认最小 YAML 子集(`key: value` / `key: [a, b]` / 数字 / 引号串)——本仓规范就是这么写的,
41
+ * 引完整 YAML 解析器会把「机器规范的形状」变成第三方依赖的版本风险。
42
+ *
43
+ * @returns {{meta:{norm_id:string,version:number,updated:string,applies_to:string[]}, body:string, digest:string}}
44
+ */
45
+ export function parseNormDoc(text, file = "<norm>") {
46
+ const raw = String(text ?? "").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
47
+ if (!raw.startsWith("---\n")) throw new TbError("NORM_INVALID", `规范缺 frontmatter:${file}`, { file });
48
+ const end = raw.indexOf("\n---\n", 4);
49
+ if (end < 0) throw new TbError("NORM_INVALID", `规范 frontmatter 未闭合:${file}`, { file });
50
+ const head = raw.slice(4, end);
51
+ const body = raw.slice(end + 5);
52
+ const meta = {};
53
+ for (const line of head.split("\n")) {
54
+ if (line.trim() === "" || line.trim().startsWith("#")) continue;
55
+ const idx = line.indexOf(":");
56
+ if (idx <= 0) throw new TbError("NORM_INVALID", `规范 frontmatter 行无法解析:${file} · ${line}`, { file });
57
+ const key = line.slice(0, idx).trim();
58
+ meta[key] = parseScalar(line.slice(idx + 1).trim());
59
+ }
60
+ const normId = String(meta.norm_id ?? "");
61
+ if (!NORM_IDS.includes(normId)) {
62
+ throw new TbError("NORM_INVALID", `规范 norm_id 非法:${file} · ${JSON.stringify(meta.norm_id)}`, { file, allowed: NORM_IDS });
63
+ }
64
+ if (!Number.isInteger(meta.version) || meta.version < 1) {
65
+ throw new TbError("NORM_INVALID", `规范 version 必须是 ≥1 的整数:${file}`, { file });
66
+ }
67
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(meta.updated ?? ""))) {
68
+ throw new TbError("NORM_INVALID", `规范 updated 必须是 YYYY-MM-DD:${file}`, { file });
69
+ }
70
+ const appliesTo = Array.isArray(meta.applies_to) ? meta.applies_to : [String(meta.applies_to ?? "")].filter(Boolean);
71
+ if (appliesTo.length === 0) throw new TbError("NORM_INVALID", `规范 applies_to 不能为空:${file}`, { file });
72
+ return { meta: { norm_id: normId, version: meta.version, updated: String(meta.updated), applies_to: appliesTo }, body, digest: sha256(body) };
73
+ }
74
+
75
+ function parseScalar(value) {
76
+ const v = String(value ?? "").trim();
77
+ if (v.startsWith("[") && v.endsWith("]")) {
78
+ return v.slice(1, -1).split(",").map((s) => s.trim()).filter(Boolean).map(stripQuotes);
79
+ }
80
+ if (/^-?\d+$/.test(v)) return Number(v);
81
+ if (v === "true") return true;
82
+ if (v === "false") return false;
83
+ return stripQuotes(v);
84
+ }
85
+
86
+ function stripQuotes(s) {
87
+ const v = String(s).trim();
88
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) return v.slice(1, -1);
89
+ return v;
90
+ }
91
+
92
+ /**
93
+ * 读一个规范目录(`spec/norms/*.md`)。
94
+ *
95
+ * @param {string} dir
96
+ * @param {{requireAll?: boolean}} [opts] `requireAll`(默认 true)=五份必须齐;单测造夹具时可关。
97
+ */
98
+ export function loadNorms(dir, { requireAll = true } = {}) {
99
+ if (!dir || !existsSync(dir)) throw new TbError("NORM_NOT_FOUND", `机器规范目录不存在:${dir}`, { dir });
100
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
101
+ const norms = [];
102
+ const seen = new Map();
103
+ for (const file of files) {
104
+ const abs = path.join(dir, file);
105
+ const parsed = parseNormDoc(readFileSync(abs, "utf8"), abs);
106
+ const prev = seen.get(parsed.meta.norm_id);
107
+ if (prev) throw new TbError("NORM_INVALID", `norm_id 重复:${parsed.meta.norm_id}(${prev} / ${abs})`, { normId: parsed.meta.norm_id });
108
+ seen.set(parsed.meta.norm_id, abs);
109
+ norms.push({ id: parsed.meta.norm_id, version: parsed.meta.version, updated: parsed.meta.updated, appliesTo: parsed.meta.applies_to, digest: parsed.digest, file: abs, relPath: `spec/norms/${file}`, body: parsed.body });
110
+ }
111
+ if (requireAll) {
112
+ const missing = NORM_IDS.filter((id) => !seen.has(id));
113
+ if (missing.length) throw new TbError("NORM_NOT_FOUND", `机器规范缺文件:${missing.join(" / ")}`, { dir, missing });
114
+ }
115
+ return norms;
116
+ }
117
+
118
+ /** 门配置归一化(缺项取默认值;未知键忽略,避免把 UI 状态算进版本)。 */
119
+ export function normalizeGates(gates = {}) {
120
+ const out = {};
121
+ for (const name of GATE_NAMES) out[name] = String(gates?.[name] ?? "n/a");
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * 计算契约快照(纯函数,可无限重算)。
127
+ *
128
+ * @param {{requirementsText?: string, norms: Array<{id,version,digest,relPath?}>, gates?: object, docVersion?: number|null}} input
129
+ * @returns {{contractVersion:string, docDigest:string, docVersion:number|null, norms:Array, gates:object, material:string}}
130
+ */
131
+ export function computeContract({ requirementsText = "", norms = [], gates = {}, docVersion = null } = {}) {
132
+ const docDigest = sha256(requirementsText);
133
+ const normRows = [...norms]
134
+ .map((n) => ({ id: n.id, version: n.version, digest: n.digest, file: n.relPath ?? n.file ?? null }))
135
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
136
+ const gateRows = normalizeGates(gates);
137
+ const material = JSON.stringify({ doc: docDigest, norms: normRows.map((n) => [n.id, n.version, n.digest]), gates: GATE_NAMES.map((g) => [g, gateRows[g]]) });
138
+ return {
139
+ contractVersion: `${CONTRACT_VERSION_PREFIX}${sha256(material).slice(0, 12)}`,
140
+ docDigest,
141
+ docVersion,
142
+ norms: normRows,
143
+ gates: gateRows,
144
+ material,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * 两次快照之间「到底哪份文件变了」——`CONTRACT_STALE` 必须能报出来(D5 硬要求 ②)。
150
+ *
151
+ * @returns {{versionChanged:boolean, docChanged:boolean, normChanges:Array<{norm,from,to,file}>, gateChanges:Array<{gate,from,to}>, changedFiles:string[]}}
152
+ */
153
+ export function diffContract(prev, next) {
154
+ const before = new Map((prev?.norms ?? []).map((n) => [n.id, n]));
155
+ const normChanges = [];
156
+ for (const n of next?.norms ?? []) {
157
+ const old = before.get(n.id);
158
+ if (!old) {
159
+ normChanges.push({ norm: n.id, from: null, to: n.version, file: n.file });
160
+ continue;
161
+ }
162
+ if (old.version !== n.version || old.digest !== n.digest) {
163
+ normChanges.push({ norm: n.id, from: old.version, to: n.version, file: n.file ?? old.file ?? null });
164
+ }
165
+ }
166
+ const gateChanges = [];
167
+ for (const g of GATE_NAMES) {
168
+ const from = prev?.gates?.[g] ?? null;
169
+ const to = next?.gates?.[g] ?? null;
170
+ if (from !== to) gateChanges.push({ gate: g, from, to });
171
+ }
172
+ const docChanged = Boolean(prev) && prev?.docDigest !== next?.docDigest;
173
+ const changedFiles = [
174
+ ...(docChanged ? ["requirement-doc"] : []),
175
+ ...normChanges.map((c) => c.file).filter(Boolean),
176
+ ];
177
+ return {
178
+ versionChanged: Boolean(prev) && prev?.contractVersion !== next?.contractVersion,
179
+ docChanged,
180
+ normChanges,
181
+ gateChanges,
182
+ changedFiles,
183
+ };
184
+ }
185
+
186
+ /**
187
+ * P1.5 · D2 `warn` 档的**纯判据**:把「调用方用的契约」与「当前契约」比一比。
188
+ *
189
+ * **不抛错、不写库** —— 阻断与否由调用方决定(warn 档:只记审计、照常写入)。
190
+ * 老客户端 / Web 不带 `contract` 字段 ⇒ `skipped`,零打扰(向后兼容)。
191
+ *
192
+ * @param {object} current `computeContract()` 的结果
193
+ * @param {{version?:string, contractVersion?:string, normDigest?:string, normDigests?:Record<string,string>}} submitted
194
+ * @returns {{verdict:"skipped"|"unknown"|"ok"|"warn", problems:Array<object>}}
195
+ */
196
+ export function evaluateSubmittedContract(current, submitted) {
197
+ if (!submitted || typeof submitted !== "object") return { verdict: "skipped", problems: [] };
198
+ if (!current || typeof current.contractVersion !== "string") return { verdict: "unknown", problems: [] };
199
+ const problems = [];
200
+ const version = submitted.version ?? submitted.contractVersion ?? null;
201
+ if (version != null && String(version) !== "" && String(version) !== current.contractVersion) {
202
+ problems.push({ kind: "version", yours: String(version), current: current.contractVersion });
203
+ }
204
+ const norms = Array.isArray(current.norms) ? current.norms : [];
205
+ const single = submitted.normDigest ?? null;
206
+ if (single != null && String(single) !== "" && !norms.some((n) => n.digest === String(single))) {
207
+ problems.push({ kind: "norm_digest", norm: null, yours: String(single), current: null });
208
+ }
209
+ const map = submitted.normDigests && typeof submitted.normDigests === "object" ? submitted.normDigests : null;
210
+ if (map) {
211
+ for (const [id, digest] of Object.entries(map)) {
212
+ const hit = norms.find((n) => n.id === id);
213
+ if (!hit) problems.push({ kind: "norm_unknown", norm: id, yours: String(digest), current: null });
214
+ else if (hit.digest !== String(digest)) problems.push({ kind: "norm_digest", norm: id, yours: String(digest), current: hit.digest });
215
+ }
216
+ }
217
+ if (problems.length > 0) return { verdict: "warn", problems };
218
+ const touched = version != null || single != null || map != null;
219
+ return { verdict: touched ? "ok" : "skipped", problems };
220
+ }
221
+
222
+ /** `409 CONTRACT_STALE` 的返回体(形状固定:agent 拿到就能自纠偏重试)。 */
223
+ export function staleError({ yours, current, changed }) {
224
+ const files = changed?.changedFiles ?? [];
225
+ return new TbError(
226
+ "CONTRACT_STALE",
227
+ `契约已更新:你用 ${yours ?? "(未提供)"},当前 ${current.contractVersion}${files.length ? `;变化来自 ${files.join(" / ")}` : ""}`,
228
+ {
229
+ your_version: yours ?? null,
230
+ current_version: current.contractVersion,
231
+ changed: changed ?? null,
232
+ digest: current.docDigest,
233
+ snapshot: current,
234
+ remedy: "用返回体里的 snapshot.contractVersion 重试(无需人确认)",
235
+ },
236
+ );
237
+ }
238
+
239
+ /**
240
+ * 比对「当前规范文件」与「已提交的 manifest」。
241
+ *
242
+ * 这是「**正文变了但 version 没 bump**」的唯一拦截点(§7.1):
243
+ * `digest 变了 && version 没变` ⇒ `NORM_VERSION_NOT_BUMPED`(守卫红),
244
+ * 否则「悄悄改规范」会让所有 agent 的 `norm_digest` 校验形同虚设。
245
+ *
246
+ * @param {Array} norms `loadNorms()` 的结果
247
+ * @param {{norms?: Array}} manifest `spec/norms/manifest.json` 的内容
248
+ */
249
+ export function diffNormsManifest(norms, manifest) {
250
+ const listed = new Map(((manifest?.norms) ?? []).map((n) => [n.norm_id ?? n.id, n]));
251
+ const issues = [];
252
+ const current = new Map();
253
+ for (const n of norms) {
254
+ current.set(n.id, n);
255
+ const old = listed.get(n.id);
256
+ if (!old) {
257
+ issues.push({ code: "NORM_UNLISTED", norm: n.id, file: n.relPath, message: `manifest 里没有 ${n.id}(新规范?跑 build-norms 生成)` });
258
+ continue;
259
+ }
260
+ if (Number(n.version) < Number(old.version)) {
261
+ issues.push({ code: "NORM_DOWNGRADE", norm: n.id, file: n.relPath, from: old.version, to: n.version, message: `${n.id} 版本回退:${old.version} → ${n.version}` });
262
+ continue;
263
+ }
264
+ if (Number(n.version) === Number(old.version) && n.digest !== old.digest) {
265
+ issues.push({ code: "NORM_VERSION_NOT_BUMPED", norm: n.id, file: n.relPath, version: n.version, message: `${n.id} 正文变了但 version 仍是 ${n.version} —— 必须 bump 版本` });
266
+ }
267
+ }
268
+ for (const [id, old] of listed) {
269
+ if (!current.has(id)) issues.push({ code: "NORM_MISSING", norm: id, file: old.file ?? null, message: `manifest 登记了 ${id},但目录里没有这份文件` });
270
+ }
271
+ const needsWrite = norms.some((n) => {
272
+ const old = listed.get(n.id);
273
+ return !old || Number(old.version) !== Number(n.version) || old.digest !== n.digest;
274
+ });
275
+ return { ok: issues.length === 0, issues, needsWrite };
276
+ }
277
+
278
+ /** 生成 manifest(稳定顺序,不含时间戳 ⇒ 可幂等 `--check`)。 */
279
+ export function buildNormsManifest(norms) {
280
+ return {
281
+ schemaVersion: 1,
282
+ note: "由 node tools/build-norms.mjs 生成;正文变了必须 bump version(否则 tests/norms-parity.test.mjs 报红)",
283
+ norms: [...norms]
284
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
285
+ .map((n) => ({ norm_id: n.id, version: n.version, updated: n.updated, digest: n.digest, file: n.relPath })),
286
+ };
287
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 「交项目主会话执行调试」的指令构造(纯函数)——FR-97。
3
+ *
4
+ * 为什么单独成一个模块:投递给宿主会话的文本是**契约的一部分**(收方 agent 完全靠它知道
5
+ * 边界红线与回报格式),必须能被单测逐段断言,也必须与 HTTP 路由、store 写入解耦。
6
+ * 本模块**不碰 DOM / 不发请求 / 不读库**。
7
+ *
8
+ * 边界红线必须原样出现在指令里:收方 agent 运行在另一个会话,不会读本仓 `AGENTS.md`,
9
+ * 看不到看板卡上的验收标准 —— 这是唯一能把纪律带过去的通道。
10
+ */
11
+
12
+ /** 收方 agent 必须遵守的边界(真机教训沉淀,不得随意删改)。 */
13
+ export const DEBUG_DISPATCH_BOUNDARIES = Object.freeze([
14
+ "不 commit、不 push(commit 归队长/人)",
15
+ "不改范围外文件;共享文件串行修改",
16
+ "不改历史决策文档(docs/历史归档/、已定稿的需求与计划条款)",
17
+ "不删用户数据(看板项目 / 任务 / 需求条目):删除类操作必须先获得用户明确指示",
18
+ "不把任务置「完成(done)」:完成只能由人确认,执行侧最多置「待验收」",
19
+ "动 ~/.dsh/profiles/**、LaunchAgent plist、dsh plugin add/remove、宿主进程重启 —— 必须先汇报并取得用户明确审批",
20
+ "不隐藏失败:失败原样上报,禁止「重试到成功再报」",
21
+ ]);
22
+
23
+ /** 收方 agent 的回报格式(四节,与 docs/规范/01-协作规范.md §二 对齐)。 */
24
+ export const DEBUG_DISPATCH_REPORT_FORMAT = Object.freeze([
25
+ "判定:完成 / 部分 / 停下(哪一步)",
26
+ "偏离说明:与本指令不符之处如实写(不写偏离=隐藏信息)",
27
+ "边界自查:逐条对齐上面的边界红线",
28
+ "产物路径:落盘文件 / 验证读数的位置",
29
+ ]);
30
+
31
+ function line(value, fallback = "(未填写)") {
32
+ const text = String(value ?? "").trim();
33
+ return text || fallback;
34
+ }
35
+
36
+ /**
37
+ * 拼「调试修复指令」。
38
+ *
39
+ * @param {object} input
40
+ * @param {object} input.task 任务行(identifier / title / status / description / labels)
41
+ * @param {object} [input.project] 项目行(id / name / workspacePath)
42
+ * @param {string} [input.note] 人工补充说明(可空)
43
+ * @param {string} [input.nextStep] 本卡「下一步」引导标题/提示,供收方知道卡面已判定为什么状态
44
+ * @returns {string} 可直接投递给宿主会话的完整指令文本(纯字符串,无副作用)
45
+ */
46
+ export function buildDebugDispatchPrompt({ task, project, note, nextStep } = {}) {
47
+ const t = task ?? {};
48
+ const p = project ?? {};
49
+ const identifier = line(t.identifier, "(无编号)");
50
+ const title = line(t.title, "(无标题)");
51
+ const status = line(t.status, "(未知)");
52
+ const labels = Array.isArray(t.labels) ? t.labels.filter((l) => String(l ?? "").trim()) : [];
53
+
54
+ const parts = [];
55
+ parts.push(`# 任务:修复看板卡 ${identifier} 无法规范流转的问题(调试修复)`);
56
+ parts.push("");
57
+ parts.push(`## 卡号与标题`);
58
+ parts.push(`- 卡号:${identifier}`);
59
+ parts.push(`- 标题:${title}`);
60
+ parts.push(`- 当前状态:${status}${labels.length ? `(标签:${labels.join(" / ")})` : ""}`);
61
+ parts.push(`- 所属项目:${line(p.name ?? p.id)}`);
62
+ parts.push(`- 工作区:${line(p.workspacePath)}`);
63
+ parts.push("");
64
+
65
+ parts.push(`## 现状与现象(卡面原文,请先读懂再动手)`);
66
+ parts.push(line(t.description, "(卡面无描述)"));
67
+ parts.push("");
68
+
69
+ if (nextStep) {
70
+ parts.push(`## 看板已给出的「下一步」判定`);
71
+ parts.push(line(nextStep));
72
+ parts.push("");
73
+ }
74
+
75
+ if (note && String(note).trim()) {
76
+ parts.push(`## 派发人补充说明`);
77
+ parts.push(String(note).trim());
78
+ parts.push("");
79
+ }
80
+
81
+ parts.push(`## 边界红线(必须遵守;违反其一即视为交付失败)`);
82
+ for (const b of DEBUG_DISPATCH_BOUNDARIES) parts.push(`- ${b}`);
83
+ parts.push("");
84
+
85
+ parts.push(`## 回报格式(四节,缺节视为未完成)`);
86
+ for (const r of DEBUG_DISPATCH_REPORT_FORMAT) parts.push(`- ${r}`);
87
+ parts.push("");
88
+
89
+ parts.push(`## 完成后`);
90
+ parts.push(`- 把结论回写到看板卡 ${identifier}(评论 + 状态),**不要置「完成」**。`);
91
+ parts.push(`- 验证读数要可复跑(如 \`npm test\` 的通过/失败计数),不要只写「已验证」。`);
92
+
93
+ return parts.join("\n");
94
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * delivery.mjs —— 「投递到会话」与「会话里真的交了作业」的**分档判定**(FR-79 / FR-82 补口)。
3
+ *
4
+ * 背景(真机 2026-10-22 · 续二十二):看板把派发指令投进项目主会话后,会话里的 agent 确实在干活
5
+ * (会话记录里能看到改 `web/app.js`、调 `taskboard_*` 工具),但**既没有提交「待验收」,也没有留评论**
6
+ * ⇒ 30 分钟后被看护按「认领心跳陈旧」回收,任务静默退回「todo」。看板上只留下一句「认领已回收」,
7
+ * **看不出**「这次是投递给会话的、会话没交作业、工作区可能已经有改动」——工作成果与看板状态脱钩。
8
+ *
9
+ * 本模块**只做判定**(纯函数、零副作用、零 I/O),措辞与落盘由调用方决定:
10
+ * · `store` 在收口(回收 / 超时)时用它决定是否补一条「未收尾」留痕(评论 + 事件);
11
+ * · `diagnostics` 用它产出 `delivery_untaken` 诊断 —— 走 FR-79 的统一出口:**可见 + 给恢复动作**。
12
+ *
13
+ * 判据(四条,缺一不算):
14
+ * ① 任务仍停在**可执行侧**(`todo` / `in_progress`)—— 已提交待验收 / 已完成 / 已取消的任务都有结论;
15
+ * ② 最近一次尝试是**会话投递**(`run.sessionId` 非空)—— CLI 执行器投递以退出码收口,成败都是结论;
16
+ * ③ 该次尝试的收口结局是「**被回收 / 超时**」(有结论的结局是 `success` / `failed` / `cancelled` …);
17
+ * ④ 该次尝试**开始之后没有任何评论**(提交待验收、进展汇报、人工反馈都会留评论)。
18
+ *
19
+ * 判定为“未收尾”不等于“失败了” —— 它表达的是:**投出去的东西没有回报**,需要人看一眼工作区。
20
+ */
21
+
22
+ /** 「会话投递没回报」的收口结局。`interrupted`(进程重启)不在此列:那是另一类事故,已有自己的留痕。 */
23
+ export const UNTAKEN_RUN_OUTCOMES = Object.freeze(["reclaimed", "timeout"]);
24
+
25
+ /** 只有还站在可执行侧的任务才算“未收尾”(有结论的任务不会命中)。 */
26
+ export const UNTAKEN_STATUSES = Object.freeze(["todo", "in_progress"]);
27
+
28
+ /** 收口留痕用的固定前缀 —— 也用于把「系统留痕」与「人的结论」区分开。 */
29
+ export const UNTAKEN_COMMENT_MARKER = "【投递未收尾】";
30
+
31
+ /**
32
+ * **系统留痕**(不是结论)。判定「该次尝试有没有交作业」时必须把它们排除,否则:
33
+ * · 投递那一刻写的「派发指令已投递到项目主会话…」会把自己这次尝试判成“已回报”;
34
+ * · 收口时写的「【投递未收尾】…」会让 FR-79 诊断再也命中不了(自己消掉自己的证据)。
35
+ * 三处留痕的措辞都从这里取,避免又出现两份常量。
36
+ */
37
+ export const SYSTEM_TRACE_MARKERS = Object.freeze([
38
+ UNTAKEN_COMMENT_MARKER,
39
+ "派发指令已投递到项目主会话",
40
+ "已交给 CLI 执行器",
41
+ // 看护回收时写的那句「认领已回收(…)→ 退回「todo」」同样是**系统留痕**:它描述的是"锁被收回",
42
+ // 不是"会话交过作业"。不排除它,回收动作会**自己消掉自己**要暴露的证据(第一次接线上就被这条挡住过)。
43
+ "认领已回收",
44
+ ]);
45
+
46
+ /** 这条评论算不算「结论/进展」(系统留痕不算)。 */
47
+ export function isConclusionComment(body) {
48
+ const text = String(body ?? "");
49
+ return !SYSTEM_TRACE_MARKERS.some((marker) => text.includes(marker));
50
+ }
51
+
52
+ /** 取最近一次尝试(按 attempt 取最大;attempt 相同则靠后写入者胜)。 */
53
+ export function findLatestRun(runs = []) {
54
+ let best = null;
55
+ for (const run of Array.isArray(runs) ? runs : []) {
56
+ if (!run) continue;
57
+ if (!best) { best = run; continue; }
58
+ const a = Number(run.attempt ?? 0);
59
+ const b = Number(best.attempt ?? 0);
60
+ if (a > b) best = run;
61
+ else if (a === b) best = run; // 同 attempt:以列表更靠后的为准(与 listTaskRuns 的 order by attempt,rowid 对齐)
62
+ }
63
+ return best;
64
+ }
65
+
66
+ /** 结局 → 人话(用于评论/诊断文案)。 */
67
+ export function untakenReasonLabel(outcome) {
68
+ if (outcome === "reclaimed") return "认领被回收(心跳陈旧 / 认领过期)";
69
+ if (outcome === "timeout") return "超过运行时上限被收口";
70
+ return `收口结局 ${outcome ?? "未知"}`;
71
+ }
72
+
73
+ /**
74
+ * 判定最近一次尝试是否属「投递到会话后没有收尾」。
75
+ * @returns {{run: object, reason: string}|null} 命中时给出该次尝试与结局说明;否则 `null`。
76
+ */
77
+ export function detectUntakenDelivery({ task = null, runs = [], comments = [] } = {}) {
78
+ if (!task) return null;
79
+ if (!UNTAKEN_STATUSES.includes(task.status)) return null;
80
+ const run = findLatestRun(runs);
81
+ if (!run) return null;
82
+ if (!run.sessionId) return null;
83
+ if (!UNTAKEN_RUN_OUTCOMES.includes(run.outcome)) return null;
84
+ const startedAt = Date.parse(run.startedAt ?? "");
85
+ if (!Number.isFinite(startedAt)) return null;
86
+ const reported = (Array.isArray(comments) ? comments : []).some((c) => {
87
+ if (!isConclusionComment(c?.body)) return false;
88
+ const at = Date.parse(c?.createdAt ?? "");
89
+ return Number.isFinite(at) && at >= startedAt;
90
+ });
91
+ if (reported) return null;
92
+ return { run, reason: untakenReasonLabel(run.outcome) };
93
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * deps.mjs —— 任务依赖(blocks)纯函数层(FR-39)。
3
+ * 有向依赖 A blocks B;同项目、无自环、无环。环检测的权威实现基于存储层递归 CTE,
4
+ * 本模块提供可单测的纯函数版本(供 domain 层复用)。
5
+ */
6
+ import { TbError, invalidField } from "./errors.mjs";
7
+
8
+ /** 断言:不能自环。 */
9
+ export function assertNotSelfDependency(blockerId, blockedId) {
10
+ if (blockerId === blockedId) {
11
+ throw new TbError("DEPENDENCY_SELF", "任务不能依赖自己", { taskId: blockerId });
12
+ }
13
+ }
14
+
15
+ /** 断言:依赖两端必须同项目。 */
16
+ export function assertSameProjectDependency(blocker, blocked) {
17
+ if (blocker.projectId !== blocked.projectId) {
18
+ throw new TbError(
19
+ "DEPENDENCY_CROSS_PROJECT",
20
+ `依赖不能跨项目(前置 ${blocker.projectId},后继 ${blocked.projectId})`,
21
+ { blockerProjectId: blocker.projectId, blockedProjectId: blocked.projectId },
22
+ );
23
+ }
24
+ }
25
+
26
+ /**
27
+ * 环检测(纯函数版):新增 blocker→blocked 是否成环。
28
+ * 成环 ⇔ 沿现有 blocker→blocked 边,从 `blockedId` 能回到 `blockerId`。
29
+ * @param {string} blockerId
30
+ * @param {string} blockedId
31
+ * @param {(id: string) => string[]} dependentsOf 返回某任务的直接后继(blocked)列表
32
+ */
33
+ export function assertNoDependencyCycle(blockerId, blockedId, dependentsOf) {
34
+ const seen = new Set();
35
+ const stack = [blockedId];
36
+ while (stack.length) {
37
+ const cur = stack.pop();
38
+ if (cur === blockerId) {
39
+ throw new TbError("DEPENDENCY_CYCLE", "依赖会形成环,已拒绝", { blockerId, blockedId });
40
+ }
41
+ if (seen.has(cur)) continue;
42
+ seen.add(cur);
43
+ for (const nxt of dependentsOf(cur) ?? []) stack.push(nxt);
44
+ }
45
+ }
46
+
47
+ /** 断言:blocker 不是 blocked 的必填字段缺失。 */
48
+ export function requireTaskRef(task, ref) {
49
+ if (!task) throw new TbError("TASK_NOT_FOUND", `任务不存在:${ref}`, { ref });
50
+ return task;
51
+ }
52
+
53
+ export { invalidField };