taskboard-workbench 0.3.1 → 0.3.2

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.
@@ -0,0 +1,190 @@
1
+ /**
2
+ * flow-inject.mjs —— 开局注入的**唯一实现**(P5 档 C · 卡 `-210` · 需求 `R128`)
3
+ *
4
+ * 方案依据:`skills/taskboard-flow/references/injection.md`(三档装载 + 分层注入策略)。
5
+ * 接线前的事实:`flow_inject_policy` 是**全仓无 reader 的静默缺口**(卡 `-186` 用守卫钉住),
6
+ * 本文件就是那个 reader —— 从此改它**真的会改变行为**。
7
+ *
8
+ * 三档里的位置:
9
+ * · 档 A(人贴 `tb-flow start`)/ 档 B(项目 `AGENTS.md` 约定)= 已可用,与本文件无关;
10
+ * · **档 C(宿主自动注入)= 本文件 + `index.js` 的 `createSession()` 出口**;
11
+ * · 人工一次性投递(`tb-flow inject --session`)也走本文件 ⇒ **只有一条注入实现**。
12
+ *
13
+ * 四条硬约束(对应验收 ①③④⑤):
14
+ * ① **内容只有一个生成器**:完整版 = `buildFlowBlock().text`(与 `tb-flow start` / MCP `prompts/get`
15
+ * **逐字节相同**);摘要版 = `buildFlowSummary(block)`(由同一个 block 剪裁,不另写规则);
16
+ * ② **失败不阻断调用方**:本模块**从不抛错**,一律返回 `{ injected, delivered, reason, ... }`,
17
+ * 宿主/HTTP/CLI 自行决定怎么报(会话创建流程不得被注入异常打断);
18
+ * ③ **每次投递留审计**:成功即写 `flow_injections`(六字段:session_id / project_id / policy /
19
+ * contract_version / digest / injected_at);`digest = sha256(实际投出的正文)`,可事后核「投的是哪一版」;
20
+ * ④ **默认零行为变化**:`flow_inject_policy` 缺省 `off` ⇒ 不构建、不投递、不写行。
21
+ *
22
+ * 依赖方向:本模块在 `src/core/`,但只 import `flow-block.mjs` 这个**纯文本生成器**(不 import 任何 MCP
23
+ * 协议 / stdio 代码);这样宿主、HTTP、CLI 三处能共用同一段判定,不会出现「六个入口两种语义」。
24
+ */
25
+ import { sha256 } from "./contract.mjs";
26
+ import { TbError } from "./errors.mjs";
27
+ import { buildFlowBlock, buildFlowSummary } from "../mcp/flow-block.mjs";
28
+ import { resolveProject } from "../mcp/tools.mjs";
29
+
30
+ /** 自动注入策略(`project_settings.flow_inject_policy` 的合法取值)。默认 `off`。 */
31
+ export const DEFAULT_FLOW_INJECT_POLICY = "off";
32
+ export const FLOW_INJECT_POLICIES = Object.freeze(["off", "main-only", "main+exec", "all"]);
33
+ /** 人工一次性投递的审计标签(`tb-flow inject --session`):它显式绕过 `off`,所以必须能被区分出来。 */
34
+ export const FLOW_INJECT_MANUAL = "manual";
35
+ /** 会话角色:主会话(完整版)/ 执行会话(摘要版)/ 关联会话(摘要版)/ 子 agent(**永不注入**)。 */
36
+ export const FLOW_INJECT_ROLES = Object.freeze(["main", "exec", "related", "subagent"]);
37
+ /** 摘要版 token 上限(验收 ④)。用 `estimateFlowTokens()` 度量,口径见该函数。 */
38
+ export const FLOW_INJECT_SUMMARY_MAX_TOKENS = 300;
39
+ /** 审计表 `policy` 列的合法取值(四个策略 + 人工)。 */
40
+ export const FLOW_INJECT_AUDIT_VALUES = Object.freeze([...FLOW_INJECT_POLICIES, FLOW_INJECT_MANUAL]);
41
+
42
+ /**
43
+ * 归一化策略值。空值 ⇒ 默认 `off`;非法值 ⇒ `null`(`strict` 时抛 `INVALID_FLOW_INJECT_POLICY`)。
44
+ * 只做形状归一(大小写 / 下划线与连字符),**不猜语义**。
45
+ */
46
+ export function normalizeFlowInjectPolicy(value, { strict = false } = {}) {
47
+ const raw = String(value ?? "").trim().toLowerCase().replace(/_/g, "-");
48
+ if (raw === "") return DEFAULT_FLOW_INJECT_POLICY;
49
+ const canon = raw === "main-exec" ? "main+exec" : raw;
50
+ if (FLOW_INJECT_AUDIT_VALUES.includes(canon)) return canon;
51
+ if (strict) {
52
+ throw new TbError(
53
+ "INVALID_FLOW_INJECT_POLICY",
54
+ `flow_inject_policy 只能是 ${FLOW_INJECT_POLICIES.join(" / ")}(收到 ${JSON.stringify(value)})`,
55
+ { value: value ?? null, allowed: FLOW_INJECT_POLICIES },
56
+ );
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /**
62
+ * 纯判定:这条会话该不该注入、注入哪一版。**不读库、不投递、不写审计** —— 所以能单测、能被任何入口复用。
63
+ *
64
+ * 角色 × 策略矩阵(`✓` = 注入):
65
+ *
66
+ * | 角色 \ 策略 | off | main-only | main+exec | all | manual |
67
+ * |---|---|---|---|---|---|
68
+ * | main | — | ✓ 完整版 | ✓ 完整版 | ✓ 完整版 | ✓ 完整版 |
69
+ * | exec | — | — | ✓ 摘要版 | ✓ 摘要版 | ✓ 摘要版 |
70
+ * | related | — | — | — | ✓ 摘要版 | ✓ 摘要版 |
71
+ * | subagent| — | — | — | —(**硬规则:子 agent 永不注入**) | — |
72
+ *
73
+ * `manual` 只给 `tb-flow inject --session` 用:人显式要求时不受 `off` 约束,但**子 agent 仍不注入**
74
+ * (子 agent 由父会话派活,塞流程只会稀释它自己的任务上下文 —— 这条不因"人工"而放开)。
75
+ *
76
+ * @returns {{inject:boolean, version:"full"|"summary"|null, reason:string}}
77
+ */
78
+ export function decideFlowInjection({ policy = DEFAULT_FLOW_INJECT_POLICY, role = null } = {}) {
79
+ const p = normalizeFlowInjectPolicy(policy);
80
+ if (!p) return { inject: false, version: null, reason: "policy-invalid" };
81
+ const r = String(role ?? "").trim() || null;
82
+ if (!r) return { inject: false, version: null, reason: "role-unknown" };
83
+ if (!FLOW_INJECT_ROLES.includes(r)) return { inject: false, version: null, reason: "role-invalid" };
84
+ if (r === "subagent") return { inject: false, version: null, reason: "subagent-never" };
85
+ if (p === "off") return { inject: false, version: null, reason: "policy-off" };
86
+ if (p === "main-only" && r !== "main") return { inject: false, version: null, reason: "policy-main-only" };
87
+ if (p === "main+exec" && r === "related") return { inject: false, version: null, reason: "policy-main+exec" };
88
+ return { inject: true, version: r === "main" ? "full" : "summary", reason: "ok" };
89
+ }
90
+
91
+ /**
92
+ * 估算 tokens(**保守上界**:CJK 一字算 1、其余 4 字符算 1 —— 宁可高估)。
93
+ * 用于验收 ④「摘要版 ≤ 300 tokens」,不追求与某个具体 tokenizer 对齐。
94
+ */
95
+ export function estimateFlowTokens(text) {
96
+ const s = String(text ?? "");
97
+ const cjk = (s.match(/[\u2e80-\u9fff\uff00-\uffef\u3000-\u303f]/g) ?? []).length;
98
+ const rest = Math.max(0, s.length - cjk);
99
+ return Math.ceil(cjk + rest / 4);
100
+ }
101
+
102
+ /**
103
+ * 注入一次(唯一入口)。**不抛错**:任何异常都收成 `{ injected:false, reason }`。
104
+ *
105
+ * @param {object} opts
106
+ * @param {object} opts.store 已打开的 store(缺 ⇒ `no-store`)
107
+ * @param {Function} opts.deliver `(sessionId, text) => Promise<{sent|delivered, reason?}>`
108
+ * @param {string} [opts.projectId] 项目 id(优先;宿主建会话时调用方已知)
109
+ * @param {object} [opts.project] 项目对象(给了就不再查库)
110
+ * @param {string} opts.sessionId 目标会话
111
+ * @param {string} [opts.role] `main` / `exec` / `related` / `subagent`
112
+ * @param {string} [opts.cwd] 未给 projectId 时按工作区匹配项目
113
+ * @param {string} [opts.policy] 显式策略(缺省读项目设置;`manual` = 人工一次性投递)
114
+ * @param {string} [opts.source] 审计来源标记(`createSession` / `tb-flow-cli` / `api`),只回带不落库
115
+ * @returns {Promise<{injected:boolean, delivered:boolean, reason:string, sessionId:string|null,
116
+ * projectId:string|null, policy:string|null, role:string|null, version:string|null,
117
+ * contractVersion:string|null, digest:string|null, chars:number, injectedAt:string|null,
118
+ * injectionId:number|null, auditRecorded:boolean, text:string|null, source:string}>}
119
+ */
120
+ export async function injectFlow({
121
+ store = null,
122
+ deliver = null,
123
+ projectId = null,
124
+ project = null,
125
+ sessionId = null,
126
+ role = null,
127
+ cwd = null,
128
+ policy = null,
129
+ source = "manual",
130
+ } = {}) {
131
+ const out = {
132
+ injected: false, delivered: false, reason: "inject-error",
133
+ sessionId: sessionId ?? null, projectId: projectId ?? null, policy: null, role: role ?? null,
134
+ version: null, contractVersion: null, digest: null, chars: 0,
135
+ injectedAt: null, injectionId: null, auditRecorded: false, text: null, source,
136
+ };
137
+ try {
138
+ if (!store) return { ...out, reason: "no-store" };
139
+ if (!sessionId) return { ...out, reason: "no-session" };
140
+
141
+ let proj = project && typeof project === "object" ? project : null;
142
+ if (!proj) {
143
+ proj = projectId
144
+ ? store.requireProject(String(projectId))
145
+ : resolveProject(store, { cwd: cwd ?? process.cwd() }).project;
146
+ }
147
+ out.projectId = proj.id;
148
+
149
+ const configured = policy === null || policy === undefined
150
+ ? (normalizeFlowInjectPolicy(store.getProjectSettings(proj.id)?.flowInjectPolicy) ?? DEFAULT_FLOW_INJECT_POLICY)
151
+ : (normalizeFlowInjectPolicy(policy) ?? String(policy));
152
+ const decision = decideFlowInjection({ policy: configured, role });
153
+ // 审计里记**实际生效的**那个值;非法值原样记下来(便于追「谁写坏了配置」)。
154
+ out.policy = normalizeFlowInjectPolicy(configured) ?? String(configured);
155
+ if (!decision.inject) return { ...out, reason: decision.reason };
156
+
157
+ const block = buildFlowBlock({ store, project: proj, matchedBy: "explicit" });
158
+ const text = decision.version === "full" ? block.text : buildFlowSummary(block);
159
+ out.version = decision.version;
160
+ out.contractVersion = block.contract?.version ?? null;
161
+ out.digest = sha256(text);
162
+ out.chars = text.length;
163
+ out.text = text;
164
+
165
+ if (typeof deliver !== "function") return { ...out, reason: "no-delivery-channel" };
166
+ const sent = await deliver(sessionId, text);
167
+ out.delivered = Boolean(sent?.sent ?? sent?.delivered ?? false);
168
+ if (!out.delivered) return { ...out, reason: sent?.reason ?? "delivery-failed" };
169
+ out.injected = true;
170
+ out.reason = "ok";
171
+
172
+ // 审计写失败**不回退投递结论**:内容确实进了会话,谎报"没注入"会让调用方重复注入。
173
+ try {
174
+ const row = store.recordFlowInjection({
175
+ projectId: proj.id, sessionId, policy: out.policy,
176
+ contractVersion: out.contractVersion, digest: out.digest,
177
+ });
178
+ out.injectionId = row.id;
179
+ out.injectedAt = row.injectedAt;
180
+ out.auditRecorded = true;
181
+ } catch (error) {
182
+ out.auditRecorded = false;
183
+ out.reason = "injected-audit-failed";
184
+ out.auditError = error?.code ?? String(error?.message ?? error ?? "audit-failed");
185
+ }
186
+ return out;
187
+ } catch (error) {
188
+ return { ...out, reason: error?.code ?? String(error?.message ?? error ?? "inject-error") };
189
+ }
190
+ }
@@ -13,6 +13,8 @@
13
13
  * 红线(与 FR-85 同口径):**自检只给结论,不改任何数据**;缺什么由人(或用既有入口)去补。
14
14
  */
15
15
 
16
+ import { TbError } from "./errors.mjs";
17
+
16
18
  /** 出处(写进报告,便于追溯;引用不复制原文)。 */
17
19
  export const KICKOFF_SOURCE = Object.freeze({
18
20
  title: "Vibe Coding 团队协作技巧(鱼皮 / ai-guide)",
@@ -145,3 +147,290 @@ export function evaluateKickoff({ files = {}, settings = {}, custom = {} } = {})
145
147
  : `开局对齐未完成(${doneCount}/${steps.length}):未对齐项 ${missing.map((s) => s.title).join("、")};建议先补齐再派发执行。`,
146
148
  };
147
149
  }
150
+
151
+ /** 回查:report 的步骤只有 id/title/status/done/total/checks,判据来源(paths/setting/custom)
152
+ * 必须回 `KICKOFF_ALIGNMENT_STEPS` 这**唯一一份**定义里取 —— 不复制第二份步骤定义。 */
153
+ const stepDefOf = (stepId) => KICKOFF_ALIGNMENT_STEPS.find((s) => s.id === stepId) ?? null;
154
+ const checkDefOf = (stepDef, checkId) => (stepDef?.checks ?? []).find((c) => c.id === checkId) ?? null;
155
+ /** 步骤在规范序里的下标(未知 stepId 排最后)。 */
156
+ const canonicalStepIndex = (stepId) => {
157
+ const i = KICKOFF_ALIGNMENT_STEPS.findIndex((s) => s.id === stepId);
158
+ return i < 0 ? KICKOFF_ALIGNMENT_STEPS.length : i;
159
+ };
160
+ /**
161
+ * 判据的「可核验信号」——**结构化**描述(不解析自然语言):
162
+ * { kind:"paths", any:[文件候选] } / { kind:"setting", keys:[点路径] } / { kind:"custom", id }
163
+ * todolist 生成器据此拼**可执行命令**(见 buildKickoffTodos)。
164
+ */
165
+ function signalOf(def) {
166
+ if (Array.isArray(def?.paths) && def.paths.length) return { kind: "paths", any: def.paths.map(String) };
167
+ if (def?.setting) return { kind: "setting", keys: (Array.isArray(def.setting) ? def.setting : [def.setting]).map(String) };
168
+ if (def?.custom) return { kind: "custom", id: String(def.custom) };
169
+ return { kind: "unknown" };
170
+ }
171
+ /** 信号 → 人能读的「动作 / 判据」文案(必须点名具体文件或设置项,禁止泛化措辞)。 */
172
+ function describeSignal(signal, fallbackId) {
173
+ if (signal.kind === "paths") return { action: `新增/补齐文件(任一即可):${signal.any.join(" / ")}`, criterion: `工作区存在文件(任一):${signal.any.join(" / ")}` };
174
+ if (signal.kind === "setting") return { action: `在项目设置里填写 ${signal.keys.join(" 或 ")} 的值`, criterion: `项目设置 ${signal.keys.join(" 或 ")} 非空` };
175
+ if (signal.kind === "custom") return { action: `按团队模板补齐自检项 ${signal.id}`, criterion: `团队模板自检项 ${signal.id} 为真` };
176
+ return { action: `补齐自检项 ${fallbackId}`, criterion: `自检项 ${fallbackId} 为真` };
177
+ }
178
+
179
+ /**
180
+ * 卡 `-229`(需求 `R170`):把自检结论**投影**成「缺口清单」。
181
+ *
182
+ * 入参就是 `evaluateKickoff()` 的返回值 —— **本函数不重新判定任何判据、不新增完成度真源**,
183
+ * 只是把已经算好的 `steps[].done/total` 与 `checks[].ok` 换个形状摆出来。
184
+ * 形状:`{ step, done, total, items:[{label, action, criterion, step}] }`
185
+ * · `step` = 步骤总数(= report.steps.length,本项目 6)
186
+ * · `done`/`total` = **判据**级计数(逐步骤累加 report.steps[].done/total,不重算)
187
+ * · `items` = 未通过的判据(`items.length === 0` ⟺ `done === total` ⟺ `report.ready === true`)
188
+ * · `items[].step` 是**步骤归属**(渲染表格用),同样直接取自 report,不是第二份完成度。
189
+ */
190
+ export function collectGaps(report) {
191
+ // F3(评审):非法入参**显式抛错**。曾经静默返回全零 ⇒ 前端读成「零缺口=已对齐」并置灰(假绿)。
192
+ if (!report || typeof report !== "object" || Array.isArray(report) || !Array.isArray(report.steps)) {
193
+ throw new TbError(
194
+ "INVALID_FIELD",
195
+ "collectGaps(report) 只接受 evaluateKickoff() 的返回值(对象且含 steps 数组);传 projectId 字符串之类是误用 —— 缺口必须来自自检结果,不能凭空算",
196
+ { got: Array.isArray(report) ? "array" : typeof report },
197
+ );
198
+ }
199
+ const steps = report.steps;
200
+ const items = [];
201
+ for (const step of steps) {
202
+ if (step?.status === "done") continue; // 已完成步骤:整步跳过(只统计未完成)
203
+ const stepDef = stepDefOf(step?.id);
204
+ const title = String(step?.title ?? stepDef?.title ?? "");
205
+ for (const check of step?.checks ?? []) {
206
+ if (check?.ok === true) continue; // 已通过判据:跳过(只统计未完成)
207
+ const def = checkDefOf(stepDef, check?.id); // F1:回查唯一一份步骤定义拿来源
208
+ const signal = signalOf(def);
209
+ const { action, criterion } = describeSignal(signal, String(check?.id ?? "?"));
210
+ items.push({
211
+ label: String(check?.label ?? def?.label ?? ""),
212
+ action,
213
+ criterion,
214
+ step: title,
215
+ stepId: String(step?.id ?? ""),
216
+ checkId: String(check?.id ?? ""),
217
+ signal,
218
+ });
219
+ }
220
+ }
221
+ const done = steps.reduce((n, s) => n + (Number(s?.done) || 0), 0);
222
+ const total = steps.reduce((n, s) => n + (Number(s?.total) || 0), 0);
223
+ return { step: steps.length, done, total, items };
224
+ }
225
+
226
+ /** 卡 `-230`(需求 R170):每条 todo 的「完成后提示」——正文与结构体共用这一份文案。 */
227
+ export const KICKOFF_TODO_HINT = "完成后回配置页「项目开局对齐」重跑配置页自检(点「重新自检」;✅ 与计数随真实判据变化)";
228
+
229
+ /** 六步顺序的**唯一**短文案(注入正文与守卫都用它,别另抄一份)。 */
230
+ export const KICKOFF_ORDER_TEXT = "规范 → 文档 → Git → 审查 → 协作 → 分工";
231
+
232
+ /** 设置类判据的兜底基址:与 `scripts/tb-flow.mjs` 的 `--host` 约定同源,可用 TB_BASE 覆盖。 */
233
+ const SETTINGS_BASE = "http://127.0.0.1:3080/integrations/taskboard-workbench";
234
+
235
+ /** 单引号安全包裹(命令里会拼整段 node 脚本;脚本内只用双引号,不出现单引号)。 */
236
+ const shellQuote = (value) => `'${String(value).replace(/'/g, `'\\''`)}'`;
237
+
238
+ /**
239
+ * `node -e` 脚本壳(Node 18+ 自带 fetch):基址读 `TB_BASE`,缺省 `SETTINGS_BASE`。
240
+ * 非 2xx / 解析失败 / 任何异常一律 `process.exit(1)` —— 拿不到数据=判不通过,绝不假绿。
241
+ */
242
+ const settingsFetchScript = (pid, body) =>
243
+ `const base=process.env.TB_BASE||"${SETTINGS_BASE}";fetch(base+"/api/projects/${pid}/settings").then((r)=>{if(!r.ok)process.exit(1);return r.json();}).then((j)=>{${body}}).catch(()=>process.exit(1));`;
244
+
245
+ /** `setting` 判据的判定体:与 `isFilled()` 同口径(undefined/null/""/[]/{} 都算没填)。 */
246
+ const settingCheckBody = (keys) =>
247
+ `const pick=(o,p)=>String(p).split(".").reduce((a,k)=>(a==null?a:a[k]),o);const filled=(v)=>v!==undefined&&v!==null&&(typeof v==="string"?v.trim()!=="":Array.isArray(v)?v.length>0:typeof v==="object"?Object.keys(v).length>0:true);process.exit(${JSON.stringify(keys)}.some((k)=>filled(pick(j,k)))?0:1);`;
248
+
249
+ /** `reviewerRole` 判定体:只在 `teamTemplate.roles` 段内看角色名是否含 `review`(不扫全 JSON)。 */
250
+ const REVIEWER_CHECK_BODY =
251
+ `const r=j&&j.teamTemplate&&j.teamTemplate.roles;const names=Array.isArray(r)?r.map((x)=>String((x&&x.role)!==undefined?x.role:x).toLowerCase()):(r&&typeof r==="object"?Object.keys(r).map((k)=>k.toLowerCase()):[]);process.exit(names.some((n)=>n.includes("review"))?0:1);`;
252
+
253
+ /** `engineerExecutor` 判定体:与 `hasEngineerExecutor()` 同口径(roles[engineer].executor / roles.engineer / teamTemplate.engineer.verifyCommand)。 */
254
+ const ENGINEER_CHECK_BODY =
255
+ `const t=j&&j.teamTemplate;const r=t&&t.roles;let ok=false;if(Array.isArray(r))ok=r.some((x)=>String((x&&x.role)!==undefined?x.role:"").toLowerCase()==="engineer"&&String((x&&x.executor)||"").trim()!=="");else if(r&&typeof r==="object"&&r.engineer)ok=true;if(!ok)ok=String((t&&t.engineer&&t.engineer.verifyCommand)||"").trim()!=="";process.exit(ok?0:1);`;
256
+
257
+ /** 候选路径 → 紧凑形态:无目录且有扩展名的,按「最后一个点之前」归并成 glob
258
+ * (`.eslintrc.json` / `.eslintrc.cjs` ⇒ `.eslintrc*`);带目录或无扩展名的原样保留。
259
+ * 只为把命令压短,**不新增判据真源**;语义仍是「任一存在即通过」。 */
260
+ const compactPathGlobs = (any) => {
261
+ const groups = new Map();
262
+ const order = [];
263
+ for (const raw of any) {
264
+ const base = String(raw);
265
+ const dot = base.lastIndexOf(".");
266
+ const stem = base.includes("/") || dot <= 0 ? base : base.slice(0, dot);
267
+ if (!groups.has(stem)) { groups.set(stem, []); order.push(stem); }
268
+ groups.get(stem).push(base);
269
+ }
270
+ return order.map((stem) => (groups.get(stem).length > 1 ? `${stem}*` : groups.get(stem)[0]));
271
+ };
272
+
273
+ /**
274
+ * 判据信号 → **可执行命令**(POSIX sh;在项目工作区根目录执行):
275
+ * · paths ⇒ `e=$(ls -d …|head -1); [ -n "$e" ]`(文件存在性,任一即可;紧凑形态)
276
+ * · setting ⇒ `node -e '…fetch …/api/projects/<id>/settings…'`,按 `isFilled()` 口径判**值非空**
277
+ * · custom ⇒ 同上,但按角色名/执行器判(`reviewerRole` 只看 `teamTemplate.roles`)
278
+ * 旧写法用 `grep '"gitFlow"'` 只匹配**键名**、`grep -i 'reviewer'` 是全 JSON 子串匹配,
279
+ * 与「值非空 / 为该角色」不等价 ⇒ 键在值空、或无关文本里提到 reviewer 都会假绿。
280
+ *
281
+ * paths 分支的紧凑形态(卡 `t22`):原 `[ -e "A" ] || [ -e "B" ] …` 全展开会随候选数线性变长
282
+ * (code-style 一步 15 个候选),叠加多判据后超过 `VERIFY_MAX_COMMAND`。改为归并 glob + 一次 `ls -d`,
283
+ * 判据语义不变(任一存在 ⇒ `$e` 非空 ⇒ 0);glob 部分**不能加引号**(加引号就不展开)。
284
+ */
285
+ export function gapVerifyCommand(signal, projectId) {
286
+ const kind = signal?.kind ?? "unknown";
287
+ if (kind === "paths") {
288
+ const any = Array.isArray(signal.any) ? signal.any : [];
289
+ if (any.length === 0) return "false";
290
+ const items = compactPathGlobs(any).map((p) => (p.endsWith("*") ? p : shellQuote(p)));
291
+ return `e=$(ls -d ${items.join(" ")} 2>/dev/null|head -1); [ -n "$e" ]`;
292
+ }
293
+ const pid = encodeURIComponent(String(projectId ?? "?"));
294
+ if (kind === "setting") {
295
+ const keys = (Array.isArray(signal.keys) ? signal.keys : []).map(String);
296
+ return `node -e ${shellQuote(settingsFetchScript(pid, settingCheckBody(keys)))}`;
297
+ }
298
+ if (kind === "custom") {
299
+ const id = String(signal.id ?? "");
300
+ if (id === "reviewerRole") return `node -e ${shellQuote(settingsFetchScript(pid, REVIEWER_CHECK_BODY))}`;
301
+ if (id === "engineerExecutor") return `node -e ${shellQuote(settingsFetchScript(pid, ENGINEER_CHECK_BODY))}`;
302
+ // 未知 custom 项:保守不通过(宁可让人手工核,也不假绿)。
303
+ return `echo ${shellQuote(`no machine check for custom:${id}`)} >&2; false`;
304
+ }
305
+ return `echo "no machine check for ${kind}" >&2; false`;
306
+ }
307
+
308
+ /** 卡 `-230`:缺口清单 → **分步 todolist**(一步一条,顺序固定 = 依赖顺序)。
309
+ * **不解析自然语言**:全部字段由 `collectGaps().items[]` 的 `signal`/`action`/`criterion` 机械拼装。
310
+ * 每条的 `hint` 固定为 `KICKOFF_TODO_HINT`(完成后回配置页重跑自检)。
311
+ */
312
+ export function buildKickoffTodos({ project, gaps } = {}) {
313
+ if (!gaps || typeof gaps !== "object" || !Array.isArray(gaps.items)) {
314
+ throw new TbError("INVALID_FIELD", "buildKickoffTodos({project, gaps}) 需要 collectGaps() 的输出(含 items 数组)", { got: typeof gaps });
315
+ }
316
+ const pid = project?.id ?? null;
317
+ const order = [];
318
+ const buckets = new Map();
319
+ for (const item of gaps.items) {
320
+ const key = String(item?.stepId ?? item?.step ?? "");
321
+ if (!buckets.has(key)) {
322
+ buckets.set(key, { stepId: key, step: String(item?.step ?? ""), items: [] });
323
+ order.push(key);
324
+ }
325
+ buckets.get(key).items.push(item);
326
+ }
327
+ // 顺序**按规范序**(不是入参出现顺序):逆序喂进来也要输出 规范 → 文档 → Git → 审查 → 协作 → 分工。
328
+ // 未知 stepId 排最后,相互间保持原顺序(稳定排序;Array#sort 自 ES2019 起保证稳定)。
329
+ order.sort((a, b) => canonicalStepIndex(a) - canonicalStepIndex(b));
330
+ return order.map((key, i) => {
331
+ const bucket = buckets.get(key);
332
+ const items = bucket.items;
333
+ return {
334
+ index: i + 1,
335
+ stepId: bucket.stepId,
336
+ step: bucket.step,
337
+ action: items.map((it) => String(it?.action ?? "")).filter(Boolean).join(";"),
338
+ criterion: items.map((it) => String(it?.criterion ?? "")).filter(Boolean).join(";"),
339
+ verifyCommand: items.map((it) => `( ${gapVerifyCommand(it?.signal, pid)} )`).join(" && "),
340
+ hint: KICKOFF_TODO_HINT,
341
+ labels: items.map((it) => String(it?.label ?? "")).filter(Boolean),
342
+ };
343
+ });
344
+ }
345
+
346
+ /**
347
+ * 卡 `t20`(需求 `R170`):缺口注入的「建卡要求(关联需求)」段 —— **纯字符串拼接,不解析自然语言**。
348
+ *
349
+ * 为什么必须有这一段:执行侧收到缺口后是照正文建卡的,而 `store.createTask` 认完整 identifier
350
+ * (形如 `taskboard-workbench-R170`)与简写 `R170`(卡 `-234` 起按本项目解析),且没归属的卡执行时
351
+ * 会被归因门拒(`EXECUTION_NOT_ATTRIBUTED`)。正文里一个字不提「关联需求」⇒ 建出来的卡必然无归属 ⇒ 建了也跑不动。
352
+ *
353
+ * 三态(三选一,互斥):
354
+ * · 给了 `requirement`(本次指定)⇒ 只写这一条,**不再**列候选(候选是噪音,还会引诱执行侧另选);
355
+ * · 没给但有候选 ⇒ 列出来让人/执行侧选一条(完整标识 + 标题,两者都要,否则对不上号);
356
+ * · 没给且无候选 ⇒ 明说「本项目暂无未关闭需求」,并给显式逃生口 `unattributedReason`。
357
+ */
358
+ function buildRequirementSection(requirement, requirements) {
359
+ const lines = [
360
+ "## 建卡要求(关联需求)",
361
+ "",
362
+ "- 每张卡必须带 `requirement` 字段;写**完整标识**最稳(形如 `taskboard-workbench-R170`),简写 `R170` 也认(按本项目解析)。",
363
+ "- 未归属的卡执行时会被归因门拒绝(`EXECUTION_NOT_ATTRIBUTED`)—— 建出来也跑不动。",
364
+ ];
365
+ const picked = requirement && typeof requirement === "object" ? String(requirement.identifier ?? "").trim() : "";
366
+ if (picked !== "") {
367
+ const title = String(requirement.title ?? "").trim();
368
+ lines.push(`- 本次指定关联需求:\`${picked}\`${title ? `(${title})` : ""}。`);
369
+ } else {
370
+ const candidates = (Array.isArray(requirements) ? requirements : [])
371
+ .map((it) => ({ identifier: String(it?.identifier ?? "").trim(), title: String(it?.title ?? "").trim() }))
372
+ .filter((it) => it.identifier !== "");
373
+ if (candidates.length > 0) {
374
+ lines.push("- 本次未指定:从下列候选里选一条填进 `requirement`(完整标识 + 标题):");
375
+ for (const it of candidates) lines.push(` - \`${it.identifier}\`${it.title ? ` ${it.title}` : ""}`);
376
+ } else {
377
+ lines.push("- 本项目暂无未关闭需求,需先建需求条目或用 `unattributedReason` 显式声明(写明不归属的原因)。");
378
+ }
379
+ }
380
+ lines.push("");
381
+ return lines;
382
+ }
383
+
384
+ /**
385
+ * 卡 `-229`:把缺口清单拼成**可直接投进主会话**的一段正文(纯函数,便于单测/复用)。
386
+ * 表格四列与需求一致:步骤 / 缺什么 / 建议动作 / 判据;并按 report 的步骤顺序(即依赖顺序)排列。
387
+ */
388
+ export function buildGapPrompt({ project, gaps, todos, requirement = null, requirements = [] } = {}) {
389
+ const p = project ?? {};
390
+ const g = gaps ?? { step: 0, done: 0, total: 0, items: [] };
391
+ const items = Array.isArray(g.items) ? g.items : [];
392
+ const todoList = Array.isArray(todos) ? todos : buildKickoffTodos({ project, gaps: g });
393
+ const requirementSection = buildRequirementSection(requirement, requirements);
394
+ const name = String(p.name ?? "").trim() || "(未命名项目)";
395
+ const id = String(p.id ?? "").trim() || "?";
396
+ const cell = (value) => String(value ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
397
+ const lines = [
398
+ `[任务工作台 · 开局对齐缺口] 项目:${name}(${id})`,
399
+ "",
400
+ `当前缺口 ${items.length} 项(共 ${Number(g.step) || 0} 步;判据自检 ${Number(g.done) || 0}/${Number(g.total) || 0} 已通过)。`,
401
+ `请把下列缺口建成待办清单(todolist),**按依赖顺序推进**(${KICKOFF_ORDER_TEXT})。`,
402
+ "",
403
+ "| # | 步骤 | 缺什么 | 建议动作 | 判据 |",
404
+ "|---|---|---|---|---|",
405
+ ];
406
+ if (items.length === 0) {
407
+ lines.push("| — | — | (无缺口:开局已对齐) | — | — |");
408
+ } else {
409
+ items.forEach((item, i) => {
410
+ lines.push(`| ${i + 1} | ${cell(item?.step)} | ${cell(item?.label)} | ${cell(item?.action)} | ${cell(item?.criterion)} |`);
411
+ });
412
+ }
413
+ lines.push("", `## 待办清单(todolist · 按依赖顺序推进 · 共 ${todoList.length} 条)`, "");
414
+ if (todoList.length === 0) {
415
+ lines.push("- (无缺口:开局对齐已完成,不需要待办)");
416
+ } else {
417
+ for (const todo of todoList) {
418
+ lines.push(`${todo.index}. [ ] ${todo.step}`);
419
+ lines.push(` - 动作:${todo.action}`);
420
+ lines.push(` - 判据:${todo.criterion}`);
421
+ lines.push(` - 命令:${todo.verifyCommand}`);
422
+ lines.push(` - 完成:${todo.hint}`);
423
+ }
424
+ }
425
+ lines.push(
426
+ "",
427
+ // 卡 `t20`:紧跟在待办清单之后 —— 执行侧读到这里正是「准备建卡」的那一刻,要求要摆在手边。
428
+ ...requirementSection,
429
+ "> 本清单与「开工语」(新会话首条 `KICKOFF_PROMPT` ①–⑧ 的第 ① 项)是**同一套六步**,不另立流程。",
430
+ "",
431
+ "## 推进纪律",
432
+ "- 每完成一项,回配置页「项目开局对齐」点「重新自检」:✅ 与计数随真实判据变化(判据只此一份,不另立真源)。",
433
+ "- 缺什么以自检读数为准:本清单由 evaluateKickoff() 的当前结果投影,不缓存、不臆断。",
434
+ );
435
+ return lines.join("\n");
436
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * 项目级机器规范(卡 `-216` / 需求 `R160`,2026-11-04 人拍)。
3
+ *
4
+ * 为什么需要:`spec/norms/*.md` 是随包分发的**默认**规范,但它躺在 `node_modules` 里 ——
5
+ * 用户要按自己团队的口径改,只能改安装目录(升级即丢),或者改 `docs/`(不入 git、不进包)。
6
+ * 所以给每个项目一份**可改副本**:`<项目工作区>/.taskboard/norms/`。
7
+ *
8
+ * 三条设计口径(对应决策点):
9
+ * · **D-A 位置**:`.taskboard/norms/` —— 不与用户自己的 `spec/` 撞名,且一眼看出是工具产物;
10
+ * · **D-B 时机**:只在**显式动作**(配置页按钮 / API)时复制,**建项目不静默写用户目录**;
11
+ * · **D-C 改动**:改正文必须 bump `version`,否则 `build-norms --check` / digest 校验红。
12
+ *
13
+ * 读优先级:项目副本存在 → 用它;**缺哪一份就用包内那份**(逐份回落,不是整目录回落,
14
+ * 也不是报错 —— 升级新增规范时,旧副本必然缺新那份,报错等于把用户挡在门外)。
15
+ */
16
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
17
+ import path from "node:path";
18
+
19
+ import { loadNorms, parseNormDoc } from "./contract.mjs";
20
+ import { TbError } from "./errors.mjs";
21
+
22
+ /** 项目副本相对工作区的位置。 */
23
+ export const PROJECT_NORMS_SUBDIR = path.join(".taskboard", "norms");
24
+
25
+ /** @param {string|null|undefined} workspacePath */
26
+ export function projectNormsDir(workspacePath) {
27
+ const ws = typeof workspacePath === "string" ? workspacePath.trim() : "";
28
+ if (!ws) return null;
29
+ return path.join(ws, PROJECT_NORMS_SUBDIR);
30
+ }
31
+
32
+ function hasMarkdown(dir) {
33
+ try {
34
+ return readdirSync(dir).some((f) => f.endsWith(".md"));
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 解析「本项目实际生效的规范」。
42
+ *
43
+ * @param {{packagedDir:string, workspacePath?:string|null}} input
44
+ * @returns {{source:"packaged"|"project", dir:string, projectDir:string|null, hasProjectCopy:boolean,
45
+ * norms:Array, fallbackIds:string[], ignoredFiles:string[]}}
46
+ */
47
+ /**
48
+ * 读项目副本(**逐文件容错**):README / 用户自己的笔记这类没有 frontmatter 的文件直接跳过;
49
+ * 有 frontmatter 但格式坏的,记进 `ignored` 而不抛 —— 否则一份坏文件会把整个看板挡在门外。
50
+ */
51
+ export function readProjectNorms(dir) {
52
+ const files = readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
53
+ const norms = []; const ignored = [];
54
+ for (const f of files) {
55
+ const abs = path.join(dir, f);
56
+ const text = readFileSync(abs, "utf8");
57
+ if (!text.replace(/^\uFEFF/, "").startsWith("---\n")) { ignored.push({ file: f, reason: "no-frontmatter" }); continue; }
58
+ try {
59
+ const parsed = parseNormDoc(text, abs, { allowUnknown: true });
60
+ norms.push({
61
+ id: parsed.meta.norm_id, version: parsed.meta.version, updated: parsed.meta.updated,
62
+ appliesTo: parsed.meta.applies_to, digest: parsed.digest, file: abs,
63
+ relPath: path.join(PROJECT_NORMS_SUBDIR, f), body: parsed.body,
64
+ });
65
+ } catch (error) {
66
+ ignored.push({ file: f, reason: error?.code ?? "invalid", message: error?.message ?? String(error) });
67
+ }
68
+ }
69
+ return { norms, ignored };
70
+ }
71
+
72
+ export function resolveNorms({ packagedDir, workspacePath = null }) {
73
+ const packaged = loadNorms(packagedDir);
74
+ const dir = projectNormsDir(workspacePath);
75
+ if (!dir || !hasMarkdown(dir)) {
76
+ return { source: "packaged", dir: packagedDir, projectDir: dir, hasProjectCopy: false, norms: packaged, fallbackIds: [], ignoredFiles: [] };
77
+ }
78
+ const local = readProjectNorms(dir);
79
+ const byId = new Map(local.norms.map((n) => [n.id, n]));
80
+ const packagedIds = new Set(packaged.map((n) => n.id));
81
+ const fallbackIds = [];
82
+ const norms = packaged.map((p) => {
83
+ const mine = byId.get(p.id);
84
+ if (!mine) { fallbackIds.push(p.id); return p; }
85
+ return mine;
86
+ });
87
+ const unknown = local.norms.filter((n) => !packagedIds.has(n.id)).map((n) => ({ file: path.basename(n.file), reason: "unknown-id" }));
88
+ return { source: "project", dir, projectDir: dir, hasProjectCopy: true, norms, fallbackIds, ignoredFiles: [...local.ignored, ...unknown] };
89
+ }
90
+
91
+ /** 配置页/接口用的只读视图(带「与内置是否不同」)。 */
92
+ export function normsView({ packagedDir, workspacePath = null }) {
93
+ const resolved = resolveNorms({ packagedDir, workspacePath });
94
+ const packaged = loadNorms(packagedDir);
95
+ const packagedById = new Map(packaged.map((n) => [n.id, n]));
96
+ return {
97
+ source: resolved.source,
98
+ dir: resolved.dir,
99
+ projectDir: resolved.projectDir,
100
+ packagedDir: packagedDir,
101
+ hasProjectCopy: resolved.hasProjectCopy,
102
+ fallbackIds: resolved.fallbackIds,
103
+ ignoredFiles: resolved.ignoredFiles,
104
+ norms: resolved.norms.map((n) => {
105
+ const base = packagedById.get(n.id);
106
+ return {
107
+ id: n.id,
108
+ version: n.version,
109
+ updated: n.updated,
110
+ digest: n.digest,
111
+ origin: resolved.hasProjectCopy && resolved.fallbackIds.includes(n.id) ? "packaged" : resolved.source,
112
+ modified: Boolean(base) && base.digest !== n.digest,
113
+ file: path.basename(n.file),
114
+ };
115
+ }),
116
+ };
117
+ }
118
+
119
+ const README = `# 本项目的机器规范(可改)
120
+
121
+ 这个目录是**本项目的规范副本**,来源是任务工作台随包分发的默认规范(共 N 份)。
122
+ 看板读写时**优先读这里**;这里缺哪一份,就回落用安装包里那份(不会报错)。
123
+
124
+ ## 怎么改
125
+
126
+ 1. 直接编辑 \`.md\` 正文(frontmatter 的 \`norm_id\` 不要动);
127
+ 2. **改正文必须同时把 \`version\` 加 1**,否则会被判「规范被偷偷改了」;
128
+ 3. 改完自检:\`node <安装包>/tools/build-norms.mjs --dir .taskboard/norms --check\`
129
+ 4. 改完要重算契约基线(否则写操作会按「旧契约」被拦):配置页 →「规范来源」→ 重算 / 或 \`POST /api/projects/<id>/contract/recheck\`。
130
+
131
+ ## 要不要入库
132
+
133
+ 这个目录在**你的项目工作区**里,要不要 \`git add\` 由你定 —— 想让团队共享就入库,只想本机生效就加进 \`.gitignore\`。
134
+
135
+ ## 恢复默认
136
+
137
+ 配置页 →「规范来源」→「恢复默认」(会用安装包里的版本覆盖本目录)。
138
+ `;
139
+
140
+ /**
141
+ * 把包内默认规范复制成项目副本。
142
+ * @param {{packagedDir:string, workspacePath?:string|null, overwrite?:boolean}} input
143
+ */
144
+ export function materializeProjectNorms({ packagedDir, workspacePath = null, overwrite = false }) {
145
+ const dir = projectNormsDir(workspacePath);
146
+ if (!dir) throw new TbError("WORKSPACE_MISSING", "项目未配置工作区目录(workspacePath)⇒ 无法生成规范副本;请先在「配置 → 当前绑定」填工作区");
147
+ mkdirSync(dir, { recursive: true });
148
+ const packaged = loadNorms(packagedDir);
149
+ const written = []; const kept = [];
150
+ for (const n of packaged) {
151
+ const target = path.join(dir, path.basename(n.file));
152
+ if (existsSync(target) && !overwrite) { kept.push(n.id); continue; }
153
+ copyFileSync(n.file, target);
154
+ written.push(n.id);
155
+ }
156
+ const manifestSrc = path.join(packagedDir, "manifest.json");
157
+ const manifestDst = path.join(dir, "manifest.json");
158
+ if (existsSync(manifestSrc) && (overwrite || !existsSync(manifestDst))) copyFileSync(manifestSrc, manifestDst);
159
+ const readme = path.join(dir, "README.md");
160
+ if (overwrite || !existsSync(readme)) writeFileSync(readme, README.replace("N 份", `${packaged.length} 份`), "utf8");
161
+ return { dir, written, kept, count: packaged.length };
162
+ }
163
+
164
+ /** 只读:副本里是否有内容(给「恢复默认」按钮判断要不要二次确认)。 */
165
+ export function projectNormsPresent(workspacePath) {
166
+ const dir = projectNormsDir(workspacePath);
167
+ return Boolean(dir && hasMarkdown(dir));
168
+ }
169
+
170
+ /** 读一份规范正文(给配置页「预览」用;不做任何写)。 */
171
+ export function readNormFile(dir, file) {
172
+ const base = path.basename(String(file ?? ""));
173
+ if (!base.endsWith(".md")) throw new TbError("USAGE_ERROR", "只允许读 .md");
174
+ const target = path.join(dir, base);
175
+ if (!existsSync(target)) throw new TbError("NORM_NOT_FOUND", `规范文件不存在:${base}`);
176
+ return readFileSync(target, "utf8");
177
+ }