taskboard-workbench 0.3.0 → 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.
@@ -290,3 +290,41 @@ export function summarizeRequirementCompletion(tasks = []) {
290
290
  }
291
291
  return { total, closed, active, counts, verdict, ready, text, tasks: list };
292
292
  }
293
+
294
+ /**
295
+ * 条目详情的**完整性形态**(`R159` D-1=`c` / D-3=派生,2026-11-04 人拍)。
296
+ *
297
+ * 为什么是派生而不是落库:判据客观(长度 + 末字符 + 归类前缀),随数据自动更新,
298
+ * 不需要迁移与历史回填;真要「人工豁免某一条」时再升级成字段。
299
+ *
300
+ * 三态(顺序有意义 —— 镜像优先,因为镜像是**设计上限**而不是事故):
301
+ * · `mirror` —— 文档镜像/归类归档条目(`【归类 YYYY-MM-DD · …】非需求条目`),正文本来就是片段;
302
+ * · `truncated` —— 正文被 2000 字符截断的残片(早期导入 `slice(0,2000)` 的历史损伤);
303
+ * · `full` —— 其余(含空描述:那是另一种缺口,由 `acceptanceSet` 负责,不是残片)。
304
+ *
305
+ * ⚠️ 只判「形状」,不读盘 ⇒ 判不出「源文已演进 / 源档缺失」(那两条要 cwd + 文件比对,
306
+ * 只在一次性分析工具里做,见 docs/进度/2026-11-04-R159判据说明与R160范围扩写.md §A4)。
307
+ */
308
+ export const DETAIL_STATES = Object.freeze(["full", "truncated", "mirror"]);
309
+
310
+ /** 2000 字符截断的**下界**(实测 1999/2000 都有,留 10 字符容差)。 */
311
+ export const TRUNCATED_MIN_LEN = 1990;
312
+
313
+ /** 句读/收尾字符:末字符属于它就不算被截断(`|` `>` 是 markdown 表格行尾)。 */
314
+ const SENTENCE_END_CHARS = new Set([..."。!?…;))】」』”\"'.:;!?]`|>"]);
315
+
316
+ const MIRROR_PREFIX = /^【归类\s*\d{4}-\d{2}-\d{2}\s*·/;
317
+
318
+ /**
319
+ * @param {string|null|undefined} description
320
+ * @returns {"full"|"truncated"|"mirror"}
321
+ */
322
+ export function deriveDetailState(description) {
323
+ const text = typeof description === "string" ? description : "";
324
+ const head = text.trimStart();
325
+ if (MIRROR_PREFIX.test(head)) return "mirror";
326
+ const trimmed = text.trimEnd();
327
+ if (trimmed === "") return "full";
328
+ if (trimmed.length >= TRUNCATED_MIN_LEN && !SENTENCE_END_CHARS.has(trimmed.at(-1))) return "truncated";
329
+ return "full";
330
+ }
@@ -20,6 +20,7 @@ import {
20
20
  import { normalizeOwner, splitOwnerLabels } from "./owner.mjs";
21
21
  import { TbError, invalidField } from "./errors.mjs";
22
22
  import { computeContract, diffContract, evaluateSubmittedContract, loadNorms } from "./contract.mjs";
23
+ import { resolveNorms } from "./norms.mjs";
23
24
  import { UNTAKEN_COMMENT_MARKER, detectUntakenDelivery } from "./delivery.mjs";
24
25
  import { VERIFY_MAX_COMMAND, parseVerifyComment } from "./verify.mjs";
25
26
  import {
@@ -27,6 +28,7 @@ import {
27
28
  elaborateDocument, formatRequirementIdentifier, normalizeTitle, parseRequirementIdentifier,
28
29
  titleKey, assertRequirementStatus, normalizeCandidates, summarizeRequirementCompletion,
29
30
  clampElaborateLimit, ELABORATE_PREVIEW_SIZE, DEFAULT_ELABORATE_LIMIT, MAX_ELABORATE_LIMIT,
31
+ deriveDetailState,
30
32
  } from "./requirements.mjs";
31
33
  import { TEAM_WRITABLE_STATUSES } from "./team.mjs";
32
34
  import { evidenceProblems, normalizeArtifactRefs, verifyArtifactRefs } from "./evidence.mjs";
@@ -36,7 +38,7 @@ import { HUMAN_REVIEW_LABEL, assertConclusion, categoryLabel, conclusionOutcome,
36
38
  // 项目记忆(2026-10-28 拍板 D-M1):L2 记忆条目,与内核表同库;**不是第二真源**(必带 provenance)。
37
39
  import { createMemoryApi } from "./memory.mjs";
38
40
 
39
- export const SCHEMA_VERSION = 13; // 13:交付物证据 task_evidence + 授权快照 task_mandates(0-B · 卡 -197);12:契约快照
41
+ export const SCHEMA_VERSION = 14; // 14:项目设置 flow_inject_policy(P5 档 C · 卡 -210);13:交付物证据 task_evidence + 授权快照 task_mandates(0-B · 卡 -197);12:契约快照
40
42
  // 条目化数量口径(卡 `-169` P4②):定义在 requirements.mjs(纯模块),此处转发以便调用方就近取用。
41
43
  export { clampElaborateLimit, DEFAULT_ELABORATE_LIMIT, MAX_ELABORATE_LIMIT, ELABORATE_PREVIEW_SIZE };
42
44
 
@@ -62,12 +64,16 @@ export function normalizeAcceptance(value) {
62
64
  /**
63
65
  * 任务级「复核动作」(命令)归一:空串/未传 → `null` =**回落**(任务级 → 项目 `envConfig.verifyCommand`
64
66
  * → 内置默认),只有显式写了命令才覆盖。长度上限与 FR-90 的 `normalizeVerifyCommand` **同口径**
65
- * (常量从 `verify.mjs` 取,避免两份)。
67
+ * (常量从 `verify.mjs` 取,避免两份);超限**抛错不截断**(截断会把命令切成语法错误 ⇒ 自动复核 exit 2)。
66
68
  */
67
69
  export function normalizeTaskVerifyCommand(value) {
68
70
  if (value === undefined || value === null) return null;
69
71
  const s = String(value).trim();
70
- return s === "" ? null : s.slice(0, VERIFY_MAX_COMMAND);
72
+ if (s === "") return null;
73
+ if (s.length > VERIFY_MAX_COMMAND) {
74
+ throw new TbError("USAGE_ERROR", `复核命令过长(${s.length} 字符 > 上限 ${VERIFY_MAX_COMMAND}):请压短后再提交(旧行为是静默截断,截断后命令会变成语法错误)`, { length: s.length, max: VERIFY_MAX_COMMAND });
75
+ }
76
+ return s;
71
77
  }
72
78
 
73
79
  // ---- 尝试记录与事件流(FR-82) ------------------------------------------------
@@ -240,6 +246,9 @@ create table if not exists project_settings (
240
246
  env_config text not null default '{}',
241
247
  team_template text not null default '{}',
242
248
  loop_config text not null default '{}',
249
+ -- P5 档 C(卡 -210 · 需求 R128):开局注入策略 off(默认)/ main-only / main+exec / all。
250
+ -- 读点在 index.js 的 createSession() 出口与 src/core/flow-inject.mjs;默认 off ⇒ 零行为变化。
251
+ flow_inject_policy text not null default 'off',
243
252
  updated_at text not null
244
253
  );
245
254
  create table if not exists project_sessions (
@@ -575,6 +584,8 @@ const rowToRequirementItem = (row) => (row ? {
575
584
  id: row.id, identifier: row.identifier, projectId: row.project_id, docId: row.doc_id,
576
585
  title: row.title, description: row.description, acceptance: row.acceptance,
577
586
  priority: row.priority, status: row.status, source: row.source, normTitle: row.norm_title,
587
+ // `R159`(D-1=`c` / D-3=派生):完整性形态是**算出来的**,不是存的 —— 列表/详情/完成度三处同源。
588
+ detailState: deriveDetailState(row.description),
578
589
  feasibility: row.feasibility ?? null, feasibilityReason: row.feasibility_reason ?? null,
579
590
  feasibilityBy: row.feasibility_by ?? null, feasibilityOverride: row.feasibility_override ?? null,
580
591
  createdAt: row.created_at, updatedAt: row.updated_at,
@@ -599,6 +610,85 @@ function insertRequirementItem(db, { id, projectId, docId, title, description, a
599
610
  return identifier;
600
611
  }
601
612
 
613
+ // ---------------- 卡 `-234`(需求 `R171`):需求条目「简写」与「报错要能照抄」 ----------------
614
+ /**
615
+ * 简写形态:`R170`(只有序号,不带项目前缀)。
616
+ *
617
+ * 为什么简写**必须带 projectId 才解析**:identifier 是 `<项目id>-R<序号>`,同一个序号在**多个项目**里都可能
618
+ * 存在;没有项目范围就只能猜,而猜必然选错(卡里明令禁止把简写做成跨项目模糊匹配)。
619
+ * 没有项目范围时不是「猜一个」,而是报错并把各项目的候选列出来(列候选 ≠ 解析)。
620
+ */
621
+ const REQUIREMENT_SHORT_REF = /^R([1-9]\d*)$/;
622
+ /** 报错体里给几条例目示例:够照抄,又不把错误体撑大。 */
623
+ const REQUIREMENT_REF_EXAMPLES = 5;
624
+
625
+ /** 取若干条「可照抄」的 identifier(给了项目就只取该项目的 —— 跨项目示例会把人带偏)。 */
626
+ function requirementRefExamples(db, projectId) {
627
+ const rows = projectId
628
+ ? db.prepare("select identifier from requirement_items where project_id = ? order by created_at, rowid limit ?").all(projectId, REQUIREMENT_REF_EXAMPLES)
629
+ : db.prepare("select identifier from requirement_items order by created_at, rowid limit ?").all(REQUIREMENT_REF_EXAMPLES);
630
+ return rows.map((row) => row.identifier);
631
+ }
632
+
633
+ /**
634
+ * `REQUIREMENT_NOT_FOUND` 的**唯一**构造点(错误码一字不改:下游按 `code` 分支)。
635
+ *
636
+ * 两条硬口径(卡 `-234`):
637
+ * ① **不得谎报**:`R170` 这条不存在 ≠ 需求不存在;「写法没被认出来」更不等于「数据没有」。
638
+ * ② **报错就是文档**:`details` 里必须带可直接照抄的完整标识(`hint` + `examples`),
639
+ * 调用方不必再去翻文档就知道该写什么。
640
+ */
641
+ function buildRequirementNotFoundError(db, ref, options = {}) {
642
+ const raw = typeof ref === "string" ? ref.trim() : String(ref ?? "");
643
+ const projectId = typeof options?.projectId === "string" ? options.projectId.trim() : "";
644
+ const examples = requirementRefExamples(db, projectId);
645
+ const exampleText = examples.length ? examples.join(" / ") : "(库里暂无条目)";
646
+ // 没给项目时示例只能跨项目取 —— 必须标明「不限项目」,否则等于暗示这条在本项目里可用。
647
+ const exampleLabel = projectId === "" ? "库里现有条目(不限项目)" : "本项目可用条目";
648
+ const short = REQUIREMENT_SHORT_REF.exec(raw);
649
+ if (short) {
650
+ const sequence = Number(short[1]);
651
+ const resolvedIdentifier = projectId === "" ? null : formatRequirementIdentifier(projectId, sequence);
652
+ if (resolvedIdentifier) {
653
+ // 已按项目解析成完整标识,仍然查不到 ⇒ 是「条目不存在」,不是「写法不对」。
654
+ return new TbError("REQUIREMENT_NOT_FOUND", `需求条目不存在:${raw}(简写已按项目 ${projectId} 解析为 ${resolvedIdentifier},该项目内没有这条)`, {
655
+ ref: raw,
656
+ refKind: "short",
657
+ projectId,
658
+ resolvedIdentifier,
659
+ hint: `\`${raw}\` 这种简写只在「给定项目」内解析:本次按 \`${projectId}\` 解析成 \`${resolvedIdentifier}\`,照样查不到 ⇒ 是**条目不存在**,不是写法没被认出来。可照抄的${exampleLabel}:${exampleText}。`,
660
+ examples,
661
+ });
662
+ }
663
+ // 没有项目范围:**不猜**。把各项目里同序号的全标识列成候选,让人自己挑一条。
664
+ const candidates = db
665
+ .prepare("select identifier from requirement_items where identifier like ? order by created_at, rowid limit ?")
666
+ .all(`%-R${sequence}`, REQUIREMENT_REF_EXAMPLES)
667
+ .map((row) => row.identifier);
668
+ const suggest = candidates[0] ?? examples[0] ?? `<项目id>-R${sequence}`;
669
+ return new TbError("REQUIREMENT_NOT_FOUND", `需求条目引用无法解析:${raw} —— 简写缺少项目范围(同一序号在多个项目里都可能存在,未做跨项目猜测);请写完整标识,如 ${suggest}`, {
670
+ ref: raw,
671
+ refKind: "short",
672
+ projectId: null,
673
+ resolvedIdentifier: null,
674
+ candidates,
675
+ hint: `简写 \`${raw}\` 必须带项目才能解析。两条路:① 写完整标识(形如 \`<项目id>-R${sequence}\`)${candidates.length ? `,库里现有:${candidates.join(" / ")}` : ""};② 走带项目的入口(如 \`POST /api/tasks\` 给 projectId,简写即按该项目解析)。`,
676
+ examples,
677
+ });
678
+ }
679
+ // 非简写:id / 完整标识 / 其它形态 —— 统一补上「能照抄的写法」,message 保持原文(真·不存在)。
680
+ const kind = parseRequirementIdentifier(raw) ? "identifier" : "other";
681
+ return new TbError("REQUIREMENT_NOT_FOUND", `需求条目不存在:${raw}`, {
682
+ ref: raw,
683
+ refKind: kind,
684
+ ...(projectId === "" ? {} : { projectId }),
685
+ hint: kind === "identifier"
686
+ ? `\`${raw}\` 是完整标识形态(\`<项目id>-R<序号>\`),本次就是按完整标识查的 ⇒ 该条目确实不存在。可照抄的${exampleLabel}:${exampleText}。`
687
+ : `\`${raw}\` 既不是条目 id、也不是 \`<项目id>-R<序号>\` 形态;可用写法:完整标识(如 \`${examples[0] ?? "<项目id>-R<序号>"}\`)或简写 \`R<序号>\`(需带项目)。`,
688
+ examples,
689
+ });
690
+ }
691
+
602
692
  function isConstraintError(error, needle) {
603
693
  const message = String(error?.message ?? "");
604
694
  return message.includes("UNIQUE constraint failed") && message.includes(needle);
@@ -676,7 +766,7 @@ export function migrateRequirementSeq(db) {
676
766
  const projectColumns = db.prepare("pragma table_info(projects)").all().map((row) => row.name);
677
767
  const taskColumns = db.prepare("pragma table_info(tasks)").all().map((row) => row.name);
678
768
  const candidateColumns = db.prepare("pragma table_info(requirement_candidates)").all().map((row) => row.name);
679
- const result = { addedReqSeqColumn: false, addedTaskRequirementColumn: false, addedCandidateSourceColumn: false, addedTaskSessionColumn: false, addedProjectSessionColumn: false, addedClaimColumn: false, addedFailureColumn: false, addedBlockColumn: false, addedRunColumn: false, addedReviewColumn: false, addedCommentEditColumn: false, addedBoardPositionColumn: false };
769
+ const result = { addedReqSeqColumn: false, addedTaskRequirementColumn: false, addedCandidateSourceColumn: false, addedTaskSessionColumn: false, addedProjectSessionColumn: false, addedClaimColumn: false, addedFailureColumn: false, addedBlockColumn: false, addedRunColumn: false, addedReviewColumn: false, addedCommentEditColumn: false, addedBoardPositionColumn: false, addedFlowInjectPolicyColumn: false };
680
770
  if (!projectColumns.includes("next_req_seq")) {
681
771
  db.exec("alter table projects add column next_req_seq integer not null default 1");
682
772
  result.addedReqSeqColumn = true;
@@ -690,6 +780,11 @@ export function migrateRequirementSeq(db) {
690
780
  db.exec("alter table project_settings add column loop_config text not null default '{}'");
691
781
  result.addedLoopColumn = true;
692
782
  }
783
+ // P5 档 C(卡 `-210`):老库补 `flow_inject_policy`。默认 `off` ⇒ **迁移本身不改变任何行为**。
784
+ if (psColumns.length && !psColumns.includes("flow_inject_policy")) {
785
+ db.exec("alter table project_settings add column flow_inject_policy text not null default 'off'");
786
+ result.addedFlowInjectPolicyColumn = true;
787
+ }
693
788
  const depColumns = db.prepare("pragma table_info(task_dependencies)").all().map((row) => row.name);
694
789
  if (depColumns.length && !depColumns.includes("reason")) {
695
790
  db.exec("alter table task_dependencies add column reason text");
@@ -878,10 +973,25 @@ export function openStore(options = {}) {
878
973
  // 797 条既有用例与真机交互一起打红;按 §17.5「先 warn 后 reject」两步走,P3 随 MCP 一起翻默认。
879
974
  const strictAttribution =
880
975
  String((options.env ?? process.env)?.TB_STRICT_ATTRIBUTION ?? "") === "1";
881
- // P1 契约快照:机器规范默认随包读 `spec/norms/*.md`;测试可传 `normsDir` 或直接传 `norms`。
882
- const normsDir = options.normsDir ?? path.join(PKG_ROOT, "spec", "norms");
976
+ // D2 契约门(2026-11-04 人拍 **R-A**):默认 `reject` —— **只拒「带了但过期」**。
977
+ // `skipped`(调用方根本没带 contract,如 Web / CLI)**照旧放行** ⇒ 主力入口零影响。
978
+ // 回滚开关:`TB_CONTRACT_MODE=warn`(一行降级,等价 2026-10-29 起的旧行为)。
979
+ const contractMode =
980
+ String((options.env ?? process.env)?.TB_CONTRACT_MODE ?? "reject").trim().toLowerCase() === "warn" ? "warn" : "reject";
981
+ // P1 契约快照:机器规范默认随包读 `spec/norms/*.md`;测试可传 `normsDir` / 直接传 `norms` / 传解析器。
982
+ // 卡 `-216`(R160):项目若有 `<工作区>/.taskboard/norms/`,**优先用副本**,缺项逐份回落包内。
983
+ const packagedNormsDir = options.normsDir ?? path.join(PKG_ROOT, "spec", "norms");
883
984
  const injectedNorms = Array.isArray(options.norms) ? options.norms : null;
884
- const loadNormsForContract = () => injectedNorms ?? loadNorms(normsDir);
985
+ const resolveNormsForProject = (projectId) => {
986
+ if (injectedNorms) return { source: "injected", dir: packagedNormsDir, norms: injectedNorms, fallbackIds: [] };
987
+ if (typeof options.normsResolver === "function") {
988
+ const out = options.normsResolver(projectId);
989
+ return Array.isArray(out) ? { source: "injected", dir: packagedNormsDir, norms: out, fallbackIds: [] } : out;
990
+ }
991
+ if (options.normsDir) return { source: "packaged", dir: packagedNormsDir, norms: loadNorms(packagedNormsDir), fallbackIds: [] };
992
+ const project = store.getProject(projectId);
993
+ return resolveNorms({ packagedDir: packagedNormsDir, workspacePath: project?.workspacePath ?? null });
994
+ };
885
995
 
886
996
  let db;
887
997
  let migration;
@@ -921,25 +1031,48 @@ export function openStore(options = {}) {
921
1031
  return contractCheckCache.byProject.get(projectId);
922
1032
  }
923
1033
  /**
924
- * 只有**调用方显式带 `contract`** 才校验(老客户端不带 ⇒ skipped,零打扰)。
925
- * 判 `warn` **不阻断写入**,只落一条 `contract-warn` 审计;
926
- * 之后可用 `GET /api/governance/audit?action=contract-warn` 查「谁在用旧规范干活」。
1034
+ * 契约门(**门在写入之前**,这是切 reject 的硬前提)。
1035
+ *
1036
+ * 只有**调用方显式带 `contract`** 才校验(老客户端 / Web / CLI 不带 ⇒ `skipped`,零打扰)。
1037
+ * 带了但与当前不符 ⇒ `warn` verdict:
1038
+ * · `contractMode === "warn"`(回滚档)⇒ 只落 `contract-warn` 审计,照常写入;
1039
+ * · `contractMode === "reject"`(**默认**,2026-11-04 人拍 R-A)⇒ 落 `contract-reject` 审计并抛
1040
+ * `CONTRACT_STALE`。**必须在任何写库动作之前调用**,否则会「先写成功再回 409」。
1041
+ *
1042
+ * 为什么默认就拒:MCP 写工具**总是**带契约,所以被拒的正是「拿旧模板干活的 agent」;
1043
+ * 而 `contract-warn` 生产审计自 2026-10-29 起一直是 **0 行** ⇒ 无存量会被打断。
927
1044
  */
928
- function noteContractUse(projectId, submitted, target) {
1045
+ function assertContractUsable(projectId, submitted, target) {
929
1046
  const current = currentContractCached(projectId);
930
1047
  const verdict = evaluateSubmittedContract(current, submitted);
931
1048
  if (verdict.verdict !== "warn") return verdict;
1049
+ const detail = JSON.stringify({ problems: verdict.problems, current_version: current?.contractVersion ?? null, mode: contractMode });
932
1050
  try {
933
1051
  store.recordAudit({
934
1052
  actor: String(submitted?.actor ?? "unknown"),
935
1053
  action: "contract-warn",
936
1054
  target: String(target ?? projectId),
937
- allowed: true,
1055
+ allowed: contractMode !== "reject",
938
1056
  reason: "stale",
939
- detail: JSON.stringify({ problems: verdict.problems, current_version: current?.contractVersion ?? null }),
1057
+ detail,
940
1058
  });
941
1059
  } catch { /* 审计写失败也不能影响业务写入 */ }
942
- return verdict;
1060
+ if (contractMode !== "reject") return verdict;
1061
+ try {
1062
+ store.recordAudit({
1063
+ actor: String(submitted?.actor ?? "unknown"),
1064
+ action: "contract-reject",
1065
+ target: String(target ?? projectId),
1066
+ allowed: false,
1067
+ reason: "stale",
1068
+ detail,
1069
+ });
1070
+ } catch { /* 同上 */ }
1071
+ throw new TbError(
1072
+ "CONTRACT_STALE",
1073
+ `你带的契约已过期(${verdict.problems.map((p) => (p.norm ? `${p.kind}:${p.norm}` : p.kind)).join(", ")});先取最新契约再重试;确需按旧契约写入请设 TB_CONTRACT_MODE=warn`,
1074
+ { problems: verdict.problems, currentVersion: current?.contractVersion ?? null },
1075
+ );
943
1076
  }
944
1077
 
945
1078
  /**
@@ -1019,7 +1152,8 @@ export function openStore(options = {}) {
1019
1152
  contractSnapshot(projectId) {
1020
1153
  const project = store.requireProject(projectId);
1021
1154
  const doc = store.getRequirementDoc(projectId);
1022
- const norms = loadNormsForContract();
1155
+ const resolved = resolveNormsForProject(projectId);
1156
+ const norms = resolved.norms;
1023
1157
  const gates = {
1024
1158
  attribution: strictAttribution ? "reject" : "warn",
1025
1159
  authorization: "hard",
@@ -1033,7 +1167,9 @@ export function openStore(options = {}) {
1033
1167
  : null;
1034
1168
  return {
1035
1169
  project: { id: project.id, name: project.name },
1036
- normsDir,
1170
+ normsDir: resolved.dir ?? packagedNormsDir,
1171
+ normsSource: resolved.source ?? "packaged",
1172
+ normsFallbackIds: resolved.fallbackIds ?? [],
1037
1173
  snapshot,
1038
1174
  baseline: stored,
1039
1175
  changed,
@@ -1268,6 +1404,10 @@ export function openStore(options = {}) {
1268
1404
  throw new TbError("REQUIREMENT_REQUIRED", "建卡必须归属需求条目:请给 requirement <条目>;确实不需要归属时用 unattributedReason <理由> 显式声明(会落审计)", { projectId });
1269
1405
  }
1270
1406
 
1407
+ // 契约门(D2/R-A):**必须在 begin 之前** —— 否则旧契约会「先建出卡再回 409」。
1408
+ // 代价:审计 target 只能指到 `project:new-task`(卡号此时还不存在)。
1409
+ assertContractUsable(projectId, input.contract, `${projectId}:new-task`);
1410
+
1271
1411
  let requirementId = null; // 事务内解析、事务外留痕(故声明在 try 之外)
1272
1412
 
1273
1413
  db.exec("begin immediate");
@@ -1282,7 +1422,8 @@ export function openStore(options = {}) {
1282
1422
  // 归因校验必须在**同一事务内**:条目不存在 / 跨项目 ⇒ 整笔回滚(连 next_seq 一起回滚,
1283
1423
  // 不留编号空洞、不留孤儿卡)。
1284
1424
  if (requirementRef !== "") {
1285
- const item = store.requireRequirementItemRef(requirementRef);
1425
+ // 卡 `-234`:建卡**一定**有 projectId ⇒ 简写 `R170` 在这里按本项目解析(不用跨项目猜)。
1426
+ const item = store.requireRequirementItemRef(requirementRef, { projectId });
1286
1427
  if (item.projectId !== projectId) {
1287
1428
  throw new TbError("DEPENDENCY_CROSS_PROJECT", `条目与任务必须同项目(条目 ${item.projectId},任务 ${projectId})`, { requirementProjectId: item.projectId, taskProjectId: projectId });
1288
1429
  }
@@ -1313,8 +1454,6 @@ export function openStore(options = {}) {
1313
1454
  store.recordTaskEvent(id, { type: "attribution_missing", to: status, actor: "human", detail: "建卡未归属需求条目(未声明理由)—— 启动执行/派发团队会被归因门拒绝" });
1314
1455
  }
1315
1456
  const created = store.getTaskById(id);
1316
- // P1.5 · warn 档:审计要指到**这张卡**(不是 `task:new`)。切 reject 时必须把这行挪到 `begin` 之前。
1317
- noteContractUse(projectId, input.contract, created.identifier);
1318
1457
  return created;
1319
1458
  },
1320
1459
 
@@ -1414,7 +1553,7 @@ export function openStore(options = {}) {
1414
1553
 
1415
1554
  updateTask(ref, changes = {}) {
1416
1555
  const current = store.requireTaskRef(ref);
1417
- noteContractUse(current.projectId, changes.contract, current.identifier);
1556
+ assertContractUsable(current.projectId, changes.contract, current.identifier);
1418
1557
  const { expectedVersion } = changes;
1419
1558
  if (expectedVersion === undefined || expectedVersion === null) {
1420
1559
  throw new TbError("MISSING_VERSION", "更新必须提供 expectedVersion(我读到的版本)", { taskId: current.id, currentVersion: current.version });
@@ -1575,7 +1714,7 @@ export function openStore(options = {}) {
1575
1714
 
1576
1715
  addComment(ref, input = {}) {
1577
1716
  const task = store.requireTaskRef(ref);
1578
- noteContractUse(task.projectId, input.contract, task.identifier);
1717
+ assertContractUsable(task.projectId, input.contract, task.identifier);
1579
1718
  const body = normalizeDescription(input.body);
1580
1719
  const id = input.id ?? randomUUID();
1581
1720
  const timestamp = nowIso();
@@ -1700,14 +1839,33 @@ export function openStore(options = {}) {
1700
1839
  },
1701
1840
 
1702
1841
  // ---------------------------------------------------------------- 需求条目(FR-35)
1703
- getRequirementItemRef(ref) {
1842
+ /**
1843
+ * 需求条目引用解析:条目 id / 完整 identifier(`<项目id>-R<序号>`)/ **简写 `R170`**。
1844
+ *
1845
+ * 卡 `-234`(需求 `R171`):此前只认前两种,于是「照着需求编号写」的人写 `R170` 直接吃
1846
+ * `需求条目不存在:R170` —— 把「写法没被认出来」说成「数据没有」,引导人去查数据。
1847
+ *
1848
+ * 简写**只在给定 `projectId` 的范围内**解析(`R170` → `<projectId>-R170`,DB 唯一约束保证不打嗝);
1849
+ * 没给 `projectId` 时**不猜**(跨项目同序号必然选错),交给 `requireRequirementItemRef` 报错并列候选。
1850
+ *
1851
+ * @param {string} ref
1852
+ * @param {{ projectId?: string }} [options]
1853
+ */
1854
+ getRequirementItemRef(ref, options = {}) {
1704
1855
  if (typeof ref !== "string" || ref.trim() === "") return null;
1705
1856
  const value = ref.trim();
1706
- return store.getRequirementItemById(value) ?? store.getRequirementItemByIdentifier(value);
1707
- },
1708
- requireRequirementItemRef(ref) {
1709
- const item = store.getRequirementItemRef(ref);
1710
- if (!item) throw new TbError("REQUIREMENT_NOT_FOUND", `需求条目不存在:${ref}`, { ref });
1857
+ const direct = store.getRequirementItemById(value) ?? store.getRequirementItemByIdentifier(value);
1858
+ if (direct) return direct;
1859
+ const short = REQUIREMENT_SHORT_REF.exec(value);
1860
+ if (!short) return null;
1861
+ const projectId = typeof options?.projectId === "string" ? options.projectId.trim() : "";
1862
+ if (projectId === "") return null;
1863
+ return store.getRequirementItemByIdentifier(formatRequirementIdentifier(projectId, Number(short[1])));
1864
+ },
1865
+ /** 同上,查不到就抛 `REQUIREMENT_NOT_FOUND`(错误码不变;`details` 带可直接照抄的完整标识)。 */
1866
+ requireRequirementItemRef(ref, options = {}) {
1867
+ const item = store.getRequirementItemRef(ref, options);
1868
+ if (!item) throw buildRequirementNotFoundError(db, ref, options);
1711
1869
  return item;
1712
1870
  },
1713
1871
  getRequirementItemById(id) {
@@ -1744,6 +1902,8 @@ export function openStore(options = {}) {
1744
1902
  }
1745
1903
  const id = input.id ?? randomUUID();
1746
1904
  const ts = nowIso();
1905
+ // 契约门(D2/R-A):同上,必须在 begin 之前。
1906
+ assertContractUsable(projectId, input.contract, `${projectId}:new-requirement`);
1747
1907
  db.exec("begin immediate");
1748
1908
  try {
1749
1909
  insertRequirementItem(db, { id, projectId, docId, title, description, acceptance, priority, status, source, ts });
@@ -1754,13 +1914,12 @@ export function openStore(options = {}) {
1754
1914
  throw error;
1755
1915
  }
1756
1916
  const createdItem = store.getRequirementItemById(id);
1757
- noteContractUse(projectId, input.contract, createdItem.identifier);
1758
1917
  return createdItem;
1759
1918
  },
1760
1919
  /** 更新需求条目(状态/标题/说明/验收/优先级)——资料引入后的"确认/修订"。 */
1761
1920
  updateRequirementItem(ref, changes = {}) {
1762
1921
  const item = store.requireRequirementItemRef(ref);
1763
- noteContractUse(item.projectId, changes.contract, item.identifier);
1922
+ assertContractUsable(item.projectId, changes.contract, item.identifier);
1764
1923
  const sets = []; const params = [];
1765
1924
  if (changes.title !== undefined) {
1766
1925
  const nextTitle = assertTitle(changes.title);
@@ -3074,21 +3233,23 @@ export function openStore(options = {}) {
3074
3233
  store.requireProject(projectId);
3075
3234
  const row = db.prepare("select * from project_settings where project_id = ?").get(projectId);
3076
3235
  const parse = (s) => { try { return JSON.parse(s); } catch { return {}; } };
3236
+ // `flowInjectPolicy`:P5 档 C(卡 `-210`)的开局注入策略;无设置行 / 老库(列已迁移,默认 `off`)一律 `off`。
3077
3237
  return row
3078
- ? { projectId, envConfig: parse(row.env_config), teamTemplate: parse(row.team_template), loop: parse(row.loop_config), updatedAt: row.updated_at }
3079
- : { projectId, envConfig: {}, teamTemplate: {}, loop: {}, updatedAt: null };
3238
+ ? { projectId, envConfig: parse(row.env_config), teamTemplate: parse(row.team_template), loop: parse(row.loop_config), flowInjectPolicy: row.flow_inject_policy ?? "off", updatedAt: row.updated_at }
3239
+ : { projectId, envConfig: {}, teamTemplate: {}, loop: {}, flowInjectPolicy: "off", updatedAt: null };
3080
3240
  },
3081
- saveProjectSettings(projectId, { envConfig, teamTemplate, loop } = {}) {
3241
+ saveProjectSettings(projectId, { envConfig, teamTemplate, loop, flowInjectPolicy } = {}) {
3082
3242
  store.requireProject(projectId);
3083
3243
  const current = store.getProjectSettings(projectId);
3084
3244
  const nextEnv = envConfig === undefined ? current.envConfig : envConfig;
3085
3245
  const nextTpl = teamTemplate === undefined ? current.teamTemplate : teamTemplate;
3086
3246
  const nextLoop = loop === undefined ? current.loop : loop;
3247
+ const nextPolicy = flowInjectPolicy === undefined ? (current.flowInjectPolicy ?? "off") : flowInjectPolicy;
3087
3248
  const ts = nowIso();
3088
3249
  db.prepare(
3089
- `insert into project_settings (project_id, env_config, team_template, loop_config, updated_at) values (?,?,?,?,?)
3090
- on conflict(project_id) do update set env_config = excluded.env_config, team_template = excluded.team_template, loop_config = excluded.loop_config, updated_at = excluded.updated_at`,
3091
- ).run(projectId, JSON.stringify(nextEnv ?? {}), JSON.stringify(nextTpl ?? {}), JSON.stringify(nextLoop ?? {}), ts);
3250
+ `insert into project_settings (project_id, env_config, team_template, loop_config, flow_inject_policy, updated_at) values (?,?,?,?,?,?)
3251
+ on conflict(project_id) do update set env_config = excluded.env_config, team_template = excluded.team_template, loop_config = excluded.loop_config, flow_inject_policy = excluded.flow_inject_policy, updated_at = excluded.updated_at`,
3252
+ ).run(projectId, JSON.stringify(nextEnv ?? {}), JSON.stringify(nextTpl ?? {}), JSON.stringify(nextLoop ?? {}), String(nextPolicy ?? "off"), ts);
3092
3253
  return store.getProjectSettings(projectId);
3093
3254
  },
3094
3255
  /** 列出团队执行记录(可按目标任务过滤),并带出目标任务编号/标题,供工作台"归属团队"视图使用。 */
@@ -86,6 +86,8 @@ export function deriveDelivery({ task = {}, evidence = null, decision = null } =
86
86
  * 归一为单一 `stage`(纯)。优先级见文件头三条。
87
87
  * 返回 `{ stage, reason, delivery, next, watch, verify, diagnostics }` ——
88
88
  * 后四者是**同批读数**(不参与 stage 计算,但同一函数给出,避免调用方各取一套再自己拼)。
89
+ * `next` = `deriveNextStep()` 的**完整**回包,`watch` = `assessTask()` 的**完整**回包(卡 `-199`:
90
+ * 抽屉直接消费这两个对象,不再各自去请求 `/next-step` 与 `/execution`)。
89
91
  */
90
92
  export function ticketStage(task = {}, ctx = {}) {
91
93
  const t = task ?? {};
@@ -108,7 +110,17 @@ export function ticketStage(task = {}, ctx = {}) {
108
110
  const next = deriveNextStep(t, { humanReviewBlocker: ctx.humanReviewBlocker ?? null, stalled });
109
111
  const autoReview = latestAutoReview(ctx.comments ?? []);
110
112
 
111
- const base = { delivery, next: { code: next.code, title: next.title }, watch: { state: watch.state, minutes: watch.minutes }, verify: autoReview ? { verdict: autoReview.verdict ?? null, at: autoReview.at ?? null } : null, diagnostics: Array.isArray(ctx.diagnostics) ? ctx.diagnostics.slice() : [] };
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
+ };
112
124
 
113
125
  // 1) 终态
114
126
  if (status === "done") return { stage: "done", reason: "已完成", ...base };
@@ -13,21 +13,29 @@
13
13
  * 跑命令的 I/O 在 `../server/verify.mjs`(有超时与输出截断),本模块保持纯函数以便单测。
14
14
  */
15
15
 
16
+ import { TbError } from "./errors.mjs";
16
17
  import { latestProgressComment } from "./watchdog.mjs";
17
18
 
18
19
  /** 证据评论前缀与默认命令(项目未配置时的兜底)。 */
19
20
  export const VERIFY_COMMENT_PREFIX = "【自动复核】";
20
21
  export const VERIFY_DEFAULT_COMMAND = "npm test";
21
- /** 命令长度与输出尾段上限:评论是给人看的证据,不是日志搬运。 */
22
- export const VERIFY_MAX_COMMAND = 300;
22
+ /** 命令长度上限:**2000**(原 300 是"手敲命令"的尺寸;开局缺口命令是**机器生成**的,
23
+ * 一步要覆盖 2–4 条判据,实测最长 1133 字符 —— 300 会让生成侧根本无法产出可存的命令)。
24
+ * 超限一律报错,**不静默截断**:截断会把命令切成语法错误(`-232` 自动复核 exit 2 的根因)。 */
25
+ export const VERIFY_MAX_COMMAND = 2000;
26
+ /** 输出尾段上限:评论是给人看的证据,不是日志搬运。 */
23
27
  export const VERIFY_MAX_TAIL = 4000;
24
28
  /** FR-94:随证据一起落盘的「本卡验收标准」上限(给人看,长文截断即可)。 */
25
29
  export const VERIFY_MAX_ACCEPTANCE = 2000;
26
30
 
27
- /** 命令归一:空/非字符串 → 默认命令;超长截断(防把整段脚本塞进评论)。 */
31
+ /** 命令归一:空/非字符串 → 默认命令;超长**报错**(不再静默截断 —— 截断后命令会变成语法错误)。 */
28
32
  export function normalizeVerifyCommand(raw) {
29
33
  const s = String(raw ?? "").trim();
30
- return s === "" ? VERIFY_DEFAULT_COMMAND : s.slice(0, VERIFY_MAX_COMMAND);
34
+ if (s === "") return VERIFY_DEFAULT_COMMAND;
35
+ if (s.length > VERIFY_MAX_COMMAND) {
36
+ throw new TbError("USAGE_ERROR", `复核命令过长(${s.length} 字符 > 上限 ${VERIFY_MAX_COMMAND}):请压短后再提交(不再静默截断 —— 截断会把命令切成语法错误)`, { length: s.length, max: VERIFY_MAX_COMMAND });
37
+ }
38
+ return s;
31
39
  }
32
40
 
33
41
  /**
@@ -152,6 +152,36 @@ export function buildFlowBlock({ store, project, cwd, matchedBy } = {}) {
152
152
  };
153
153
  }
154
154
 
155
+ /**
156
+ * P5 档 C(卡 `-210`)· **摘要版**装载块 —— 给执行 / 关联会话用(≤ 300 tokens)。
157
+ *
158
+ * 三条约束(为什么是「从 block 剪裁」而不是「另写一份」):
159
+ * ① **唯一真源仍是一个**:本函数只吃 `buildFlowBlock()` 的返回值(`nextStep` / `contract`),
160
+ * 不读库、不读 SKILL.md、不写字面量步骤 —— 八步改了这里不可能说旧话;
161
+ * ② **只留护栏**:执行会话不需要八步全文(完整版 ≈2–3k tokens),只需要「别把 done 写了」
162
+ * 「backlog→todo 是人工授权」「回填要带什么」这三类会当场报错的东西;
163
+ * ③ **确定性**:同样的 block ⇒ 逐字节同样的摘要(可比较、可审计)。
164
+ *
165
+ * @param {ReturnType<typeof buildFlowBlock>} block
166
+ * @returns {string} 摘要文本(以 `\n` 结尾,与完整版同一收尾约定)
167
+ */
168
+ export function buildFlowSummary(block) {
169
+ if (!block || typeof block !== "object" || !block.nextStep) {
170
+ throw new Error("buildFlowSummary 需要 buildFlowBlock() 的返回值(含 nextStep),不接受裸数据");
171
+ }
172
+ const step = block.nextStep;
173
+ const version = block.contract?.version ?? "(未取到)";
174
+ return [
175
+ "任务看板主流程(摘要)",
176
+ `当前步:${step.step} · ${step.title}`,
177
+ "两道门:done 只能人点(GOVERNANCE_AGENT_DONE)· backlog→todo 是人工授权(EXECUTION_NOT_AUTHORIZED)",
178
+ "回填要带:evidence[](file/command/url/reading)+ norm_digest(norm_get \"card-update\")",
179
+ `契约:${version}(用旧版本会落 contract-warn)`,
180
+ "常见错误码:EXECUTION_NOT_ATTRIBUTED(先补归因)· CONTRACT_STALE / NORM_STALE(重取规范)· REVIEW_NOT_APPROVED(等人复核)",
181
+ "全文:`node scripts/tb-flow.mjs start`(与宿主注入同源)",
182
+ ].join("\n").trimEnd() + "\n";
183
+ }
184
+
155
185
  /** 档 B:给项目 `AGENTS.md` 用的片段(只指路,不复制正文)。 */
156
186
  export function buildAgentsSnippet({ project, pkgPath } = {}) {
157
187
  const pkg = pkgPath ?? PKG_ROOT;
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * server.mjs —— Taskboard Workbench MCP server(stdio · 零依赖 · 只读四工具)。
3
+ * server.mjs —— Taskboard Workbench MCP server(stdio · 零依赖 · 只读五 + 写四)。
4
4
  *
5
5
  * 方案依据:§6.1 —— **stdio 而不是 HTTP**:① 不占端口、不碰 `:3080`;② 不需要重载宿主、
6
6
  * 不写 `~/.dsh/**`;③ 每个 agent 会话一个进程,天然隔离。数据连**同一个** `taskboard.sqlite`。
@@ -8,6 +8,7 @@
8
8
  * 用法:
9
9
  * node src/mcp/server.mjs --data-dir <dir> # 由 MCP 客户端作为子进程拉起
10
10
  * node src/mcp/server.mjs --print-tools # 打印工具清单(调试 / 守卫测试用)
11
+ * node src/mcp/server.mjs --read-only # **只读模式**(P3 的回滚开关):写四件不出现在 tools/list,调用即 READ_ONLY_MODE
11
12
  *
12
13
  * 传输:newline-delimited JSON-RPC 2.0(MCP stdio transport)。
13
14
  * stdout **只允许**出现协议消息;日志一律走 stderr(否则客户端解析失败)。
@@ -29,9 +30,16 @@ const argOf = (name) => {
29
30
  };
30
31
  const has = (name) => argv.includes(name);
31
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
+
32
39
  if (has("--help") || has("-h")) {
33
40
  process.stderr.write(`taskboard-workbench MCP server(9 个工具:只读五 / 写四 · prompt 1)
34
- 用法: node src/mcp/server.mjs [--data-dir <dir>] [--print-tools]
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 的回滚开关
35
43
  工具: ${TOOL_NAMES.join(", ")}
36
44
  提示: prompt taskboard.flow(= node scripts/tb-flow.mjs start 的输出)
37
45
  数据: --data-dir > $TB_DATA_DIR > 默认(同 Web/CLI)
@@ -42,7 +50,7 @@ if (has("--help") || has("-h")) {
42
50
  const pkg = JSON.parse(readFileSync(path.join(PKG_ROOT, "package.json"), "utf8"));
43
51
 
44
52
  if (has("--print-tools")) {
45
- process.stdout.write(`${JSON.stringify({ name: pkg.name, version: pkg.version, tools: TOOLS.map((t) => t.name) }, null, 2)}\n`);
53
+ process.stdout.write(`${JSON.stringify({ name: pkg.name, version: pkg.version, readOnly: READ_ONLY, tools: ACTIVE_NAMES }, null, 2)}\n`);
46
54
  process.exit(0);
47
55
  }
48
56
 
@@ -51,7 +59,7 @@ const store = openStore({ dataDir, env: process.env });
51
59
  const ctx = { store };
52
60
  let skillMeta = null;
53
61
  try { skillMeta = readSkill().meta; } catch { /* skill 缺失时不影响工具面;prompts/* 会报出具体原因 */ }
54
- process.stderr.write(`[tb-mcp] ready dataDir=${store.dataDir} tools=${TOOL_NAMES.join(",")} prompt=taskboard.flow skill=${skillMeta ? `v${skillMeta.version}` : "missing"}\n`);
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`);
55
63
 
56
64
  const SERVER_INFO = { name: "taskboard-workbench", version: pkg.version };
57
65
  const DEFAULT_PROTOCOL = "2025-06-18";
@@ -72,7 +80,7 @@ const toolError = (error) => {
72
80
  };
73
81
 
74
82
  function listTools() {
75
- return TOOLS.map((t) => ({
83
+ return ACTIVE_TOOLS.map((t) => ({
76
84
  name: t.name,
77
85
  description: t.description,
78
86
  inputSchema: t.inputSchema,
@@ -94,8 +102,19 @@ async function handle(message) {
94
102
  if (method === "tools/list") return result(id, { tools: listTools() });
95
103
  if (method === "tools/call") {
96
104
  const name = params?.name;
97
- const tool = TOOLS.find((t) => t.name === name);
98
- if (!tool) return rpcError(id, -32602, `Unknown tool: ${name ?? "(missing)"}`, { tools: TOOL_NAMES });
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
+ }
99
118
  try {
100
119
  const value = await tool.handler(ctx, params?.arguments ?? {});
101
120
  return result(id, { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], isError: false });