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.
@@ -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");
@@ -883,10 +978,20 @@ export function openStore(options = {}) {
883
978
  // 回滚开关:`TB_CONTRACT_MODE=warn`(一行降级,等价 2026-10-29 起的旧行为)。
884
979
  const contractMode =
885
980
  String((options.env ?? process.env)?.TB_CONTRACT_MODE ?? "reject").trim().toLowerCase() === "warn" ? "warn" : "reject";
886
- // P1 契约快照:机器规范默认随包读 `spec/norms/*.md`;测试可传 `normsDir` 或直接传 `norms`。
887
- const normsDir = options.normsDir ?? path.join(PKG_ROOT, "spec", "norms");
981
+ // P1 契约快照:机器规范默认随包读 `spec/norms/*.md`;测试可传 `normsDir` / 直接传 `norms` / 传解析器。
982
+ // 卡 `-216`(R160):项目若有 `<工作区>/.taskboard/norms/`,**优先用副本**,缺项逐份回落包内。
983
+ const packagedNormsDir = options.normsDir ?? path.join(PKG_ROOT, "spec", "norms");
888
984
  const injectedNorms = Array.isArray(options.norms) ? options.norms : null;
889
- 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
+ };
890
995
 
891
996
  let db;
892
997
  let migration;
@@ -1047,7 +1152,8 @@ export function openStore(options = {}) {
1047
1152
  contractSnapshot(projectId) {
1048
1153
  const project = store.requireProject(projectId);
1049
1154
  const doc = store.getRequirementDoc(projectId);
1050
- const norms = loadNormsForContract();
1155
+ const resolved = resolveNormsForProject(projectId);
1156
+ const norms = resolved.norms;
1051
1157
  const gates = {
1052
1158
  attribution: strictAttribution ? "reject" : "warn",
1053
1159
  authorization: "hard",
@@ -1061,7 +1167,9 @@ export function openStore(options = {}) {
1061
1167
  : null;
1062
1168
  return {
1063
1169
  project: { id: project.id, name: project.name },
1064
- normsDir,
1170
+ normsDir: resolved.dir ?? packagedNormsDir,
1171
+ normsSource: resolved.source ?? "packaged",
1172
+ normsFallbackIds: resolved.fallbackIds ?? [],
1065
1173
  snapshot,
1066
1174
  baseline: stored,
1067
1175
  changed,
@@ -1314,7 +1422,8 @@ export function openStore(options = {}) {
1314
1422
  // 归因校验必须在**同一事务内**:条目不存在 / 跨项目 ⇒ 整笔回滚(连 next_seq 一起回滚,
1315
1423
  // 不留编号空洞、不留孤儿卡)。
1316
1424
  if (requirementRef !== "") {
1317
- const item = store.requireRequirementItemRef(requirementRef);
1425
+ // 卡 `-234`:建卡**一定**有 projectId ⇒ 简写 `R170` 在这里按本项目解析(不用跨项目猜)。
1426
+ const item = store.requireRequirementItemRef(requirementRef, { projectId });
1318
1427
  if (item.projectId !== projectId) {
1319
1428
  throw new TbError("DEPENDENCY_CROSS_PROJECT", `条目与任务必须同项目(条目 ${item.projectId},任务 ${projectId})`, { requirementProjectId: item.projectId, taskProjectId: projectId });
1320
1429
  }
@@ -1730,14 +1839,33 @@ export function openStore(options = {}) {
1730
1839
  },
1731
1840
 
1732
1841
  // ---------------------------------------------------------------- 需求条目(FR-35)
1733
- 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 = {}) {
1734
1855
  if (typeof ref !== "string" || ref.trim() === "") return null;
1735
1856
  const value = ref.trim();
1736
- return store.getRequirementItemById(value) ?? store.getRequirementItemByIdentifier(value);
1737
- },
1738
- requireRequirementItemRef(ref) {
1739
- const item = store.getRequirementItemRef(ref);
1740
- 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);
1741
1869
  return item;
1742
1870
  },
1743
1871
  getRequirementItemById(id) {
@@ -3105,21 +3233,23 @@ export function openStore(options = {}) {
3105
3233
  store.requireProject(projectId);
3106
3234
  const row = db.prepare("select * from project_settings where project_id = ?").get(projectId);
3107
3235
  const parse = (s) => { try { return JSON.parse(s); } catch { return {}; } };
3236
+ // `flowInjectPolicy`:P5 档 C(卡 `-210`)的开局注入策略;无设置行 / 老库(列已迁移,默认 `off`)一律 `off`。
3108
3237
  return row
3109
- ? { projectId, envConfig: parse(row.env_config), teamTemplate: parse(row.team_template), loop: parse(row.loop_config), updatedAt: row.updated_at }
3110
- : { 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 };
3111
3240
  },
3112
- saveProjectSettings(projectId, { envConfig, teamTemplate, loop } = {}) {
3241
+ saveProjectSettings(projectId, { envConfig, teamTemplate, loop, flowInjectPolicy } = {}) {
3113
3242
  store.requireProject(projectId);
3114
3243
  const current = store.getProjectSettings(projectId);
3115
3244
  const nextEnv = envConfig === undefined ? current.envConfig : envConfig;
3116
3245
  const nextTpl = teamTemplate === undefined ? current.teamTemplate : teamTemplate;
3117
3246
  const nextLoop = loop === undefined ? current.loop : loop;
3247
+ const nextPolicy = flowInjectPolicy === undefined ? (current.flowInjectPolicy ?? "off") : flowInjectPolicy;
3118
3248
  const ts = nowIso();
3119
3249
  db.prepare(
3120
- `insert into project_settings (project_id, env_config, team_template, loop_config, updated_at) values (?,?,?,?,?)
3121
- 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`,
3122
- ).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);
3123
3253
  return store.getProjectSettings(projectId);
3124
3254
  },
3125
3255
  /** 列出团队执行记录(可按目标任务过滤),并带出目标任务编号/标题,供工作台"归属团队"视图使用。 */
@@ -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;
package/src/mcp/tools.mjs CHANGED
@@ -314,7 +314,8 @@ export function requirementUpsert({ store }, args = {}) {
314
314
  const ref = refCandidate ? refCandidate.trim() : "";
315
315
 
316
316
  if (ref !== "") {
317
- const current = store.requireRequirementItemRef(ref);
317
+ // 卡 `-234`:MCP 这里已解析出项目 ⇒ 简写 `R170` 按本项目解析(不再因为「没写全」被判不存在)。
318
+ const current = store.requireRequirementItemRef(ref, { projectId: project.id });
318
319
  if (current.projectId !== project.id) {
319
320
  throw fail("DEPENDENCY_CROSS_PROJECT", `条目属于别的项目:${ref}(${current.projectId})`, { requirement: ref, requirementProject: current.projectId, project: project.id });
320
321
  }
@@ -361,7 +362,7 @@ export function requirementChange({ store }, args = {}) {
361
362
  const { project } = resolveProject(store, args);
362
363
  const ref = [args.requirement, args.id].find((x) => typeof x === "string" && x.trim() !== "");
363
364
  if (!ref) throw fail("USAGE_ERROR", "requirement_change 需要 requirement(条目编号或 id)", {});
364
- const item = store.requireRequirementItemRef(ref.trim());
365
+ const item = store.requireRequirementItemRef(ref.trim(), { projectId: project.id }); // 卡 `-234`:简写按本项目解析
365
366
  if (item.projectId !== project.id) {
366
367
  throw fail("DEPENDENCY_CROSS_PROJECT", `条目属于别的项目:${ref}(${item.projectId})`, { requirement: ref, requirementProject: item.projectId, project: project.id });
367
368
  }