taskboard-workbench 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/README.md +89 -0
  3. package/package.json +18 -5
  4. package/scripts/tb-flow.mjs +86 -0
  5. package/skills/taskboard-flow/SKILL.md +89 -0
  6. package/skills/taskboard-flow/references/errors.md +61 -0
  7. package/skills/taskboard-flow/references/injection.md +70 -0
  8. package/skills/taskboard-flow/references/steps/S0.md +31 -0
  9. package/skills/taskboard-flow/references/steps/S1.md +28 -0
  10. package/skills/taskboard-flow/references/steps/S2.md +31 -0
  11. package/skills/taskboard-flow/references/steps/S3.md +22 -0
  12. package/skills/taskboard-flow/references/steps/S4.md +25 -0
  13. package/skills/taskboard-flow/references/steps/S5.md +36 -0
  14. package/skills/taskboard-flow/references/steps/S6.md +30 -0
  15. package/skills/taskboard-flow/references/steps/S7.md +23 -0
  16. package/spec/norms/acceptance.md +36 -0
  17. package/spec/norms/card-update.md +39 -0
  18. package/spec/norms/doc-editing.md +30 -0
  19. package/spec/norms/flow.md +45 -0
  20. package/spec/norms/manifest.json +41 -0
  21. package/spec/norms/project-defaults.md +33 -0
  22. package/src/core/acceptance.mjs +62 -0
  23. package/src/core/contract.mjs +287 -0
  24. package/src/core/errors.mjs +3 -0
  25. package/src/core/evidence.mjs +86 -0
  26. package/src/core/intake.mjs +87 -24
  27. package/src/core/requirements.mjs +31 -1
  28. package/src/core/store.mjs +345 -6
  29. package/src/core/ticket-stage.mjs +150 -0
  30. package/src/mcp/flow-block.mjs +173 -0
  31. package/src/mcp/server.mjs +156 -0
  32. package/src/mcp/tools.mjs +764 -0
  33. package/src/server/api.mjs +106 -30
  34. package/src/server/server.mjs +3 -0
  35. package/web/app.js +117 -17
  36. package/web/tokens.css +12 -0
@@ -20,7 +20,9 @@ export const REQUIREMENT_STATUSES = Object.freeze(["draft", "open", "done", "clo
20
20
  /** 需求终态:已完成 / 已关闭(都不再产生新任务;`done` 需关联任务先收口)。 */
21
21
  export const REQUIREMENT_DONE_STATUSES = Object.freeze(["done", "closed"]);
22
22
  /** 需求条目来源:手工 / 规则解析(fallback)/ AI 拆解(首选)/ 资料引入。 */
23
- export const REQUIREMENT_SOURCES = Object.freeze(["manual", "elaborated-rule", "elaborated-ai", "intake"]);
23
+ // 卡 `-176`(2026-10-29):补 `mcp`。此前 MCP `requirement_upsert` 建条目一律落默认 `manual`
24
+ // ⇒ 「这条是人手建的还是 MCP 建的」在库里不可辨(审计也就无从按入口统计)。
25
+ export const REQUIREMENT_SOURCES = Object.freeze(["manual", "elaborated-rule", "elaborated-ai", "intake", "mcp"]);
24
26
  /** 可行性结论取值(追加字段)。 */
25
27
  export const FEASIBILITY_VERDICTS = Object.freeze(["feasible", "infeasible"]);
26
28
 
@@ -77,6 +79,34 @@ export function titleKey(value) {
77
79
  }
78
80
 
79
81
  /** 抽取需求文档正文里的候选条目(规则解析,非 AI)。 */
82
+ // ---- 条目化的数量口径(卡 `-169` P4② · 2026-10-29 口径变更) -----------------
83
+ /**
84
+ * 真机实证(2026-10-28):一份「资料索引」类需求文档走**规则**条目化,产出 **4213 条**,
85
+ * 其中 0 条是真需求 —— 全是**文件清单行**(`- docs/a.md` 这种)。
86
+ * 旧口径 `limit` 默认 **100** 且 **body 传了也不生效** ⇒ 一按按钮就落 100 条 `pending` 候选,
87
+ * 这就是「100 条 pending」的直接来路。
88
+ *
89
+ * 新口径(本卡批准的 P4②):
90
+ * 1. `limit` **默认 20**(100 → 20),**硬顶 200**,且**从 body 透传**;
91
+ * 2. `auto` 模式**只用 AI**,AI 不可用 ⇒ **拒绝**(`AI_UNAVAILABLE`,零落库)——
92
+ * 要规则降级必须**显式** `fallback:"rule"`(把「其实没 AI」从「看起来成功」改成「明确失败」);
93
+ * 3. 规则模式支持 `dryRun` 预览(零落库)。
94
+ */
95
+ export const DEFAULT_ELABORATE_LIMIT = 20;
96
+ export const MAX_ELABORATE_LIMIT = 200;
97
+ export const ELABORATE_PREVIEW_SIZE = 10;
98
+
99
+ /**
100
+ * `limit` 归一:空 ⇒ 默认 20;非正整数 ⇒ **报错**(不静默回落 —— 否则「我传了 5 却写了 20」极难查);
101
+ * 超硬顶 ⇒ 夹到 200(上限语义,夹取比报错更符合预期)。
102
+ */
103
+ export function clampElaborateLimit(value) {
104
+ if (value === undefined || value === null || value === "") return DEFAULT_ELABORATE_LIMIT;
105
+ const n = Number(value);
106
+ if (!Number.isInteger(n) || n <= 0) throw invalidField("limit", `limit 必须是正整数,收到:${String(value)}`);
107
+ return Math.min(n, MAX_ELABORATE_LIMIT);
108
+ }
109
+
80
110
  export function elaborateDocument(body) {
81
111
  if (typeof body !== "string") throw invalidField("body", "需求文档正文必须是字符串");
82
112
  const candidates = [];
@@ -5,6 +5,7 @@
5
5
  * 注意:tasks_owner_idx 只在迁移函数里创建(老库建表语句是 no-op,提前建索引会因缺列失败)。
6
6
  */
7
7
  import { randomUUID } from "node:crypto";
8
+ import { fileURLToPath } from "node:url";
8
9
  import { mkdirSync } from "node:fs";
9
10
  import path from "node:path";
10
11
  import { DatabaseSync } from "node:sqlite";
@@ -18,21 +19,27 @@ import {
18
19
  } from "./domain.mjs";
19
20
  import { normalizeOwner, splitOwnerLabels } from "./owner.mjs";
20
21
  import { TbError, invalidField } from "./errors.mjs";
22
+ import { computeContract, diffContract, evaluateSubmittedContract, loadNorms } from "./contract.mjs";
21
23
  import { UNTAKEN_COMMENT_MARKER, detectUntakenDelivery } from "./delivery.mjs";
22
24
  import { VERIFY_MAX_COMMAND, parseVerifyComment } from "./verify.mjs";
23
25
  import {
24
26
  assertFeasibilityVerdict, assertRequirementSource, assertSplitTasks,
25
27
  elaborateDocument, formatRequirementIdentifier, normalizeTitle, parseRequirementIdentifier,
26
28
  titleKey, assertRequirementStatus, normalizeCandidates, summarizeRequirementCompletion,
29
+ clampElaborateLimit, ELABORATE_PREVIEW_SIZE, DEFAULT_ELABORATE_LIMIT, MAX_ELABORATE_LIMIT,
27
30
  } from "./requirements.mjs";
28
31
  import { TEAM_WRITABLE_STATUSES } from "./team.mjs";
32
+ import { evidenceProblems, normalizeArtifactRefs, verifyArtifactRefs } from "./evidence.mjs";
29
33
  import { REVIEW_SOURCE_STATUSES, REVIEW_IDLE_MS, detectReviewDeadlock, reviewReturnStatus } from "./review.mjs";
30
34
  import { NOTIFY_DELIVERY_MODES, buildNotifyMessage, normalizeDeliveryMode, selectNotifyEvents } from "./notify.mjs";
31
35
  import { HUMAN_REVIEW_LABEL, assertConclusion, categoryLabel, conclusionOutcome, isHumanReviewTask, validateHumanReviewDraft } from "./human-review.mjs";
32
36
  // 项目记忆(2026-10-28 拍板 D-M1):L2 记忆条目,与内核表同库;**不是第二真源**(必带 provenance)。
33
37
  import { createMemoryApi } from "./memory.mjs";
34
38
 
35
- export const SCHEMA_VERSION = 11; // 11:项目记忆(memory_entries / memory_links / memory_recalls)
39
+ export const SCHEMA_VERSION = 13; // 13:交付物证据 task_evidence + 授权快照 task_mandates(0-B · 卡 -197);12:契约快照
40
+ // 条目化数量口径(卡 `-169` P4②):定义在 requirements.mjs(纯模块),此处转发以便调用方就近取用。
41
+ export { clampElaborateLimit, DEFAULT_ELABORATE_LIMIT, MAX_ELABORATE_LIMIT, ELABORATE_PREVIEW_SIZE };
42
+
36
43
 
37
44
  // ---- 任务级验收标准与复核动作(FR-94) ---------------------------------------
38
45
  /**
@@ -264,6 +271,26 @@ create table if not exists task_runs (
264
271
  created_at text not null, updated_at text not null
265
272
  );
266
273
  create unique index if not exists task_runs_task_attempt_idx on task_runs(task_id, attempt);
274
+ -- 交付物证据(FR-106 / 0-B):**结构化**落库,同一任务「最新一条」为有效证据;历史不回填。
275
+ -- 为什么不是一段自由文本评论:评论表没有 author 字段(805 条作者不可机读),且"四节齐不齐"
276
+ -- 无法被机器判定 —— 于是评审、Router、度量都只能靠人读。
277
+ create table if not exists task_evidence (
278
+ id text primary key, task_id text not null references tasks(id) on delete cascade,
279
+ verdict text not null, deviation text not null default '', boundary text not null default '',
280
+ artifacts text not null default '[]', artifact_refs text not null default '[]',
281
+ refs_state text not null default 'unchecked',
282
+ actor text not null, task_version integer not null, created_at text not null
283
+ );
284
+ create index if not exists task_evidence_task_idx on task_evidence(task_id, created_at);
285
+ -- 授权快照(FR-107 / 0-B):**append-only**,只有 insert;范围变大 = 新行(不 update 旧行)。
286
+ -- 起因:2026-10-28 一次补 69 张无归因卡,其中 56 张**真实来源已不可考** —— 因为"当初凭什么做"没有载体。
287
+ create table if not exists task_mandates (
288
+ id text primary key, task_id text not null references tasks(id) on delete cascade,
289
+ requirement_ref text, contract_version text, norms_digest text,
290
+ scope text not null default '', claim_owner text, claim_source text, created_at text not null
291
+ );
292
+ create index if not exists task_mandates_task_idx on task_mandates(task_id, created_at);
293
+
267
294
  create index if not exists task_runs_task_idx on task_runs(task_id, started_at);
268
295
  -- 任务事件流(FR-82):**追加式**,任务内 seq 单调 + 全库 cursor 单调(FR-81 的推送游标)。
269
296
  create table if not exists task_events (
@@ -315,10 +342,37 @@ create table if not exists memory_recalls (
315
342
  id integer primary key autoincrement,
316
343
  session_id text, entry_id text not null, reason text, injected_chars integer, created_at text not null
317
344
  );
345
+ -- 契约快照(P1 · 方案 §8 数据模型):每个项目一行「上次算出来的契约」。
346
+ -- 作用:① 让 CONTRACT_STALE 能报出「哪份文件变了」;② 让漂移盘点有基线。
347
+ -- 注意:**只是缓存,不是真源** —— 真源永远是 requirement_docs + spec/norms/*.md,删表只丢基线。
348
+ create table if not exists project_contract (
349
+ project_id text primary key references projects(id) on delete cascade,
350
+ contract_version text not null,
351
+ doc_digest text not null,
352
+ doc_version integer,
353
+ norms_json text not null default '[]',
354
+ gates_json text not null default '{}',
355
+ computed_at text not null,
356
+ updated_at text not null
357
+ );
358
+ -- 装载块注入审计(P1 建表 · D3 档 C 推迟,这里只留审计位,默认策略 off 不写)
359
+ create table if not exists flow_injections (
360
+ id integer primary key autoincrement,
361
+ project_id text,
362
+ session_id text,
363
+ policy text not null,
364
+ contract_version text not null,
365
+ digest text,
366
+ injected_at text not null
367
+ );
368
+ create index if not exists flow_injections_project_idx on flow_injections(project_id, injected_at);
318
369
  `;
319
370
 
320
371
  const nowIso = () => new Date().toISOString();
321
372
 
373
+ /** 包根(`src/core/` 往上两级)——机器规范默认从 `<包根>/spec/norms` 读,随包分发。 */
374
+ const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
375
+
322
376
  /**
323
377
  * FR-80:阻断路由(纯函数)。对齐 hermes `_route_block`(kanban_db.py:2955)。
324
378
  * - `dependency`:**不进人工受阻队列**,回到"可开工(todo)"等父任务(事件 `dependency_wait`)
@@ -551,6 +605,18 @@ function isConstraintError(error, needle) {
551
605
  }
552
606
 
553
607
  /** 一次性迁移(幂等):1) 老库补 owner 列;2) `owner:<role>` 标签搬进 owner 并从 labels 移除。 */
608
+ function rowToTaskEvidence(row) {
609
+ return {
610
+ id: row.id, taskId: row.task_id,
611
+ verdict: row.verdict, deviation: row.deviation, boundary: row.boundary,
612
+ artifacts: safeJsonArray(row.artifacts), artifactRefs: safeJsonArray(row.artifact_refs),
613
+ refsState: row.refs_state, actor: row.actor, taskVersion: row.task_version, createdAt: row.created_at,
614
+ };
615
+ }
616
+ function safeJsonArray(raw) {
617
+ try { const v = JSON.parse(raw ?? "[]"); return Array.isArray(v) ? v : []; } catch { return []; }
618
+ }
619
+
554
620
  export function migrateOwnerField(db) {
555
621
  const columns = db.prepare("pragma table_info(tasks)").all().map((row) => row.name);
556
622
  let addedColumn = false;
@@ -812,6 +878,10 @@ export function openStore(options = {}) {
812
878
  // 797 条既有用例与真机交互一起打红;按 §17.5「先 warn 后 reject」两步走,P3 随 MCP 一起翻默认。
813
879
  const strictAttribution =
814
880
  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");
883
+ const injectedNorms = Array.isArray(options.norms) ? options.norms : null;
884
+ const loadNormsForContract = () => injectedNorms ?? loadNorms(normsDir);
815
885
 
816
886
  let db;
817
887
  let migration;
@@ -836,6 +906,63 @@ export function openStore(options = {}) {
836
906
  throw wrapped;
837
907
  }
838
908
 
909
+ // ---- P1.5 · D2 `warn` 档:写路径上的契约校验(内核层,不阻断)---------------------
910
+ // 为什么放内核:MCP / HTTP / CLI / Web / dsh-tool 五个入口都落到这里;放在门面层就会
911
+ // 「六个入口两种语义」(方案 §17.3 D2 拍板 B)。warn 档只记审计,观察一周后再切 reject。
912
+ const CONTRACT_CHECK_TTL_MS = 20000; // 每次写都读五份规范 + 需求文档太重,短 TTL 缓存足够
913
+ const contractCheckCache = { at: 0, byProject: new Map() };
914
+ function currentContractCached(projectId) {
915
+ const now = Date.now();
916
+ if (now - contractCheckCache.at > CONTRACT_CHECK_TTL_MS) { contractCheckCache.at = now; contractCheckCache.byProject.clear(); }
917
+ if (!contractCheckCache.byProject.has(projectId)) {
918
+ try { contractCheckCache.byProject.set(projectId, store.contractSnapshot(projectId).snapshot); }
919
+ catch { contractCheckCache.byProject.set(projectId, null); }
920
+ }
921
+ return contractCheckCache.byProject.get(projectId);
922
+ }
923
+ /**
924
+ * 只有**调用方显式带 `contract`** 才校验(老客户端不带 ⇒ skipped,零打扰)。
925
+ * 判 `warn` **不阻断写入**,只落一条 `contract-warn` 审计;
926
+ * 之后可用 `GET /api/governance/audit?action=contract-warn` 查「谁在用旧规范干活」。
927
+ */
928
+ function noteContractUse(projectId, submitted, target) {
929
+ const current = currentContractCached(projectId);
930
+ const verdict = evaluateSubmittedContract(current, submitted);
931
+ if (verdict.verdict !== "warn") return verdict;
932
+ try {
933
+ store.recordAudit({
934
+ actor: String(submitted?.actor ?? "unknown"),
935
+ action: "contract-warn",
936
+ target: String(target ?? projectId),
937
+ allowed: true,
938
+ reason: "stale",
939
+ detail: JSON.stringify({ problems: verdict.problems, current_version: current?.contractVersion ?? null }),
940
+ });
941
+ } catch { /* 审计写失败也不能影响业务写入 */ }
942
+ return verdict;
943
+ }
944
+
945
+ /**
946
+ * FR-107 内部助手:**冻结一条授权快照**(append-only;失败不阻断主流程)。
947
+ *
948
+ * 三条路径都要冻结,因为本项目口径里「认领」有三种入口,缺一条就等于 100% 结构化率是假的:
949
+ * · `claimTask`(执行器拿锁)—— scope=claim
950
+ * · `updateTask → in_progress`(看板拖拽 / HTTP PATCH)—— scope=board
951
+ * · `teamSetTaskStatus → in_progress`(执行侧 / 团队通道 / MCP)—— scope=team
952
+ * 范围变大 = 新行(不 update 旧行),所以重复进入 in_progress 会产生多行,这是刻意的。
953
+ */
954
+ const freezeMandate = (taskId, { scope = "claim", claimOwner = null, claimSource = null } = {}) => {
955
+ try {
956
+ const t = store.getTaskById(taskId);
957
+ if (!t) return null;
958
+ let requirementRef = null;
959
+ try {
960
+ requirementRef = t.requirementId ? (store.getRequirementItemById(t.requirementId)?.identifier ?? null) : null;
961
+ } catch { requirementRef = null; }
962
+ return store.recordTaskMandate(t.identifier, { requirementRef, scope, claimOwner, claimSource });
963
+ } catch { return null; }
964
+ }
965
+
839
966
  const store = {
840
967
  schemaVersion: SCHEMA_VERSION,
841
968
  dataDir,
@@ -882,6 +1009,95 @@ export function openStore(options = {}) {
882
1009
  return project;
883
1010
  },
884
1011
 
1012
+ /**
1013
+ * P1 · 契约快照(**纯读**,不写库)。
1014
+ *
1015
+ * `contractVersion = f(需求文档 digest, 机器规范 digest×版本, 门配置)`;
1016
+ * 同时把「与上次落库的基线相比哪份文件变了」一起返回 —— 这正是 `CONTRACT_STALE`
1017
+ * 必须能报出 `changed[]` 的来源(D5 硬要求:只报「过期」不报「哪份变了」=让人猜)。
1018
+ */
1019
+ contractSnapshot(projectId) {
1020
+ const project = store.requireProject(projectId);
1021
+ const doc = store.getRequirementDoc(projectId);
1022
+ const norms = loadNormsForContract();
1023
+ const gates = {
1024
+ attribution: strictAttribution ? "reject" : "warn",
1025
+ authorization: "hard",
1026
+ review: "hard",
1027
+ humanReview: "hard",
1028
+ };
1029
+ const snapshot = computeContract({ requirementsText: doc?.body ?? "", norms, gates, docVersion: doc?.version ?? null });
1030
+ const stored = store.getProjectContract(projectId);
1031
+ const changed = stored
1032
+ ? diffContract({ contractVersion: stored.contractVersion, docDigest: stored.docDigest, norms: stored.norms, gates: stored.gates }, snapshot)
1033
+ : null;
1034
+ return {
1035
+ project: { id: project.id, name: project.name },
1036
+ normsDir,
1037
+ snapshot,
1038
+ baseline: stored,
1039
+ changed,
1040
+ stale: Boolean(changed?.versionChanged),
1041
+ };
1042
+ },
1043
+
1044
+ /** P1 · 重算并落基线(`project_contract` 唯一写入点)。只存缓存,不影响业务状态。 */
1045
+ refreshProjectContract(projectId, { reason = null } = {}) {
1046
+ const result = store.contractSnapshot(projectId);
1047
+ const ts = nowIso();
1048
+ const { snapshot } = result;
1049
+ db.prepare(
1050
+ `insert into project_contract (project_id, contract_version, doc_digest, doc_version, norms_json, gates_json, computed_at, updated_at)
1051
+ values (?, ?, ?, ?, ?, ?, ?, ?)
1052
+ on conflict(project_id) do update set
1053
+ contract_version = excluded.contract_version, doc_digest = excluded.doc_digest,
1054
+ doc_version = excluded.doc_version, norms_json = excluded.norms_json,
1055
+ gates_json = excluded.gates_json, computed_at = excluded.computed_at, updated_at = excluded.updated_at`,
1056
+ ).run(projectId, snapshot.contractVersion, snapshot.docDigest, snapshot.docVersion ?? null,
1057
+ JSON.stringify(snapshot.norms), JSON.stringify(snapshot.gates), ts, ts);
1058
+ return { ...result, baseline: store.getProjectContract(projectId), reason };
1059
+ },
1060
+
1061
+ getProjectContract(projectId) {
1062
+ const row = db.prepare("select * from project_contract where project_id = ?").get(projectId);
1063
+ if (!row) return null;
1064
+ const parse = (text, fallback) => {
1065
+ try { return JSON.parse(text ?? ""); } catch { return fallback; }
1066
+ };
1067
+ return {
1068
+ projectId: row.project_id,
1069
+ contractVersion: row.contract_version,
1070
+ docDigest: row.doc_digest,
1071
+ docVersion: row.doc_version ?? null,
1072
+ norms: parse(row.norms_json, []),
1073
+ gates: parse(row.gates_json, {}),
1074
+ computedAt: row.computed_at,
1075
+ updatedAt: row.updated_at,
1076
+ };
1077
+ },
1078
+
1079
+ /** P1 · 装载块注入审计(D3 档 C 推迟:默认策略 off,这张表只是「将来要能追」的位子)。 */
1080
+ recordFlowInjection({ projectId = null, sessionId = null, policy = "off", contractVersion, digest = null } = {}) {
1081
+ if (!contractVersion) throw invalidField("contractVersion", "recordFlowInjection 必须带 contractVersion");
1082
+ const ts = nowIso();
1083
+ const info = db.prepare(
1084
+ "insert into flow_injections (project_id, session_id, policy, contract_version, digest, injected_at) values (?, ?, ?, ?, ?, ?)",
1085
+ ).run(projectId, sessionId, String(policy), String(contractVersion), digest, ts);
1086
+ return { id: Number(info.lastInsertRowid), projectId, sessionId, policy: String(policy), contractVersion, digest, injectedAt: ts };
1087
+ },
1088
+
1089
+ listFlowInjections(filter = {}) {
1090
+ const clauses = [];
1091
+ const args = [];
1092
+ if (filter.projectId) { clauses.push("project_id = ?"); args.push(filter.projectId); }
1093
+ if (filter.sessionId) { clauses.push("session_id = ?"); args.push(filter.sessionId); }
1094
+ const where = clauses.length ? ` where ${clauses.join(" and ")}` : "";
1095
+ return db.prepare(`select * from flow_injections${where} order by id`).all(...args).map((row) => ({
1096
+ id: row.id, projectId: row.project_id, sessionId: row.session_id, policy: row.policy,
1097
+ contractVersion: row.contract_version, digest: row.digest, injectedAt: row.injected_at,
1098
+ }));
1099
+ },
1100
+
885
1101
  /**
886
1102
  * FR-03:删除项目 —— **非空守卫**(验收要点:删除非空项目被拒绝且有明确提示)。
887
1103
  *
@@ -1096,7 +1312,10 @@ export function openStore(options = {}) {
1096
1312
  } else {
1097
1313
  store.recordTaskEvent(id, { type: "attribution_missing", to: status, actor: "human", detail: "建卡未归属需求条目(未声明理由)—— 启动执行/派发团队会被归因门拒绝" });
1098
1314
  }
1099
- return store.getTaskById(id);
1315
+ const created = store.getTaskById(id);
1316
+ // P1.5 · warn 档:审计要指到**这张卡**(不是 `task:new`)。切 reject 时必须把这行挪到 `begin` 之前。
1317
+ noteContractUse(projectId, input.contract, created.identifier);
1318
+ return created;
1100
1319
  },
1101
1320
 
1102
1321
  getTaskRef(ref) {
@@ -1195,6 +1414,7 @@ export function openStore(options = {}) {
1195
1414
 
1196
1415
  updateTask(ref, changes = {}) {
1197
1416
  const current = store.requireTaskRef(ref);
1417
+ noteContractUse(current.projectId, changes.contract, current.identifier);
1198
1418
  const { expectedVersion } = changes;
1199
1419
  if (expectedVersion === undefined || expectedVersion === null) {
1200
1420
  throw new TbError("MISSING_VERSION", "更新必须提供 expectedVersion(我读到的版本)", { taskId: current.id, currentVersion: current.version });
@@ -1321,6 +1541,10 @@ export function openStore(options = {}) {
1321
1541
  // FR-82:状态变化 → 事件流追加(不再让各处各自造"状态历史")。
1322
1542
  // 注意:**纯列内排序不写任何事件** —— 版式调整不是任务生命周期事件,塞进去只会污染事件流与通知口径。
1323
1543
  store.recordTaskEvent(current.id, { type: "status_changed", from: current.status, to: nextStatus, actor: changes.actor ?? "human" });
1544
+ // FR-111(`-195`):进待验收就补评审发起时间(幂等;已有值不覆盖)
1545
+ if (nextStatus === "in_review" && !current.reviewRequestedAt) store.markReviewRequested(current.id, timestamp);
1546
+ // FR-107(`-197`):看板 PATCH 进入「进行中」= 本项目口径下的一次认领 ⇒ 冻结授权快照
1547
+ if (nextStatus === "in_progress") freezeMandate(current.id, { scope: "board", claimOwner: nextOwner ?? actor, claimSource: current.status });
1324
1548
  }
1325
1549
  // FR-83 补口(卡 `-162`):逃生口放行后必须**可回看** —— 这是"人显式决定跳过评审"的取证点,
1326
1550
  // 否则事后只看到一张 done 卡,分不清"评审通过后收口"与"跳过评审收口"。
@@ -1351,6 +1575,7 @@ export function openStore(options = {}) {
1351
1575
 
1352
1576
  addComment(ref, input = {}) {
1353
1577
  const task = store.requireTaskRef(ref);
1578
+ noteContractUse(task.projectId, input.contract, task.identifier);
1354
1579
  const body = normalizeDescription(input.body);
1355
1580
  const id = input.id ?? randomUUID();
1356
1581
  const timestamp = nowIso();
@@ -1528,13 +1753,24 @@ export function openStore(options = {}) {
1528
1753
  if (isConstraintError(error, "requirement_items.identifier")) throw new TbError("REQ_IDENTIFIER_CONFLICT", "需求条目编号冲突,请重试", { projectId });
1529
1754
  throw error;
1530
1755
  }
1531
- return store.getRequirementItemById(id);
1756
+ const createdItem = store.getRequirementItemById(id);
1757
+ noteContractUse(projectId, input.contract, createdItem.identifier);
1758
+ return createdItem;
1532
1759
  },
1533
1760
  /** 更新需求条目(状态/标题/说明/验收/优先级)——资料引入后的"确认/修订"。 */
1534
1761
  updateRequirementItem(ref, changes = {}) {
1535
1762
  const item = store.requireRequirementItemRef(ref);
1763
+ noteContractUse(item.projectId, changes.contract, item.identifier);
1536
1764
  const sets = []; const params = [];
1537
- if (changes.title !== undefined) { sets.push("title = ?"); params.push(assertTitle(changes.title)); }
1765
+ if (changes.title !== undefined) {
1766
+ const nextTitle = assertTitle(changes.title);
1767
+ sets.push("title = ?"); params.push(nextTitle);
1768
+ // 卡 `-178`(2026-10-29):改标题**必须同步去重键** `norm_title`。
1769
+ // 此前只写 `title` ⇒ 条目改名后 `norm_title` 仍指向旧标题,而 `confirmRequirementCandidates`
1770
+ // 是按 `norm_title` 去重的 ⇒ 同一条目会被当成「新条目」再插一次(陈旧键 = 静默重复)。
1771
+ // 存量实测 `normTitleMismatch = 0`(`tools/audit-intake.mjs`),所以这是**防新增**而非修存量。
1772
+ sets.push("norm_title = ?"); params.push(titleKey(nextTitle));
1773
+ }
1538
1774
  if (changes.description !== undefined) { sets.push("description = ?"); params.push(normalizeDescription(changes.description)); }
1539
1775
  if (changes.acceptance !== undefined) { sets.push("acceptance = ?"); params.push(String(changes.acceptance)); }
1540
1776
  if (changes.priority !== undefined) { sets.push("priority = ?"); params.push(assertPriority(changes.priority)); }
@@ -1582,11 +1818,25 @@ export function openStore(options = {}) {
1582
1818
  if (!doc) throw new TbError("REQUIREMENT_DOC_NOT_FOUND", `需求文档不存在:${options.docId ?? ref ?? options.projectId}`, { ref: options.docId ?? ref ?? options.projectId });
1583
1819
  // 规则解析 = fallback 路径(AI 版见切片2,或由宿主注入 aiElaborator)
1584
1820
  // B-2:规则条目化可能一次产出成百上千条(尤其对"资料索引"这类文档)→ 加数量上限,防"候选洪水"
1585
- const limit = Number.isFinite(options.limit) ? options.limit : 100;
1821
+ // 卡 `-169` P4②(2026-10-29):默认 100 → **20**,硬顶 200,见文件头 DEFAULT_ELABORATE_LIMIT 注释。
1822
+ const limit = clampElaborateLimit(options.limit);
1586
1823
  const all = elaborateDocument(doc.body);
1587
1824
  const capped = all.slice(0, limit);
1825
+ const truncated = all.length > capped.length;
1826
+ // dryRun:**零落库**,只回预览(规则模式此前"一点就写",人没有反悔的机会)
1827
+ if (options.dryRun === true) {
1828
+ const preview = capped.slice(0, ELABORATE_PREVIEW_SIZE).map((c) => ({
1829
+ title: c.title, description: c.description, acceptance: c.acceptance, priority: c.priority,
1830
+ }));
1831
+ return {
1832
+ docId: doc.id, dryRun: true, source: "elaborated-rule", mode: "rule",
1833
+ limit, totalFound: all.length, truncated,
1834
+ preview, previewCount: preview.length,
1835
+ candidates: [], duplicatesSkipped: 0,
1836
+ };
1837
+ }
1588
1838
  const res = store.addRequirementCandidates(doc.id, capped, { source: "elaborated-rule" });
1589
- return { ...res, truncated: all.length > capped.length, totalFound: all.length };
1839
+ return { ...res, limit, truncated, totalFound: all.length };
1590
1840
  },
1591
1841
  /** 写入一组候选条目(AI 或规则产出共用);去重、未确认不落 requirement_items。 */
1592
1842
  addRequirementCandidates(ref, candidates, { source = "elaborated-rule" } = {}) {
@@ -1930,6 +2180,8 @@ export function openStore(options = {}) {
1930
2180
  if (res.changes !== 1) return { claimed: false, reason: "cas-lost", task: store.getTaskById(task.id) };
1931
2181
  // FR-82:**认领即开一条尝试记录**(授权→尝试→结论 可回看)
1932
2182
  const run = store.startTaskRun(task.identifier, { sessionId, claimLock: lock, actor: sessionId ?? "team", now: ts });
2183
+ // FR-107(`-197`):认领即冻结**授权事实**(append-only)。失败不阻断认领(快照是留痕,不是门)。
2184
+ freezeMandate(task.id, { scope: "claim", claimOwner: sessionId ?? null, claimSource: sourceStatus ?? cur?.status ?? null });
1933
2185
  store.recordTaskEvent(task.id, { type: "claimed", to: "claimed", actor: sessionId ?? "team", detail: `认领(来源 ${sourceStatus ?? cur?.status ?? "-"})`, now: ts });
1934
2186
  return { claimed: true, claim: { lock, expiresAt: expires, owner: sessionId ?? null, source: sourceStatus ?? cur?.status ?? null }, run: run.started ? run.run : null, task: store.getTaskById(task.id) };
1935
2187
  },
@@ -2392,6 +2644,81 @@ export function openStore(options = {}) {
2392
2644
  * 追加一条任务事件(**追加式**,供看护 / 通知 / 详情共同消费——不各自造数)。
2393
2645
  * 事件写失败不阻断主流程(返回 null),保证生命周期方法不被可观测性拖垮。
2394
2646
  */
2647
+ /**
2648
+ * FR-111(卡 `-195`):**进了「待验收」就视为已发起评审** —— 补 `review_requested_at`。
2649
+ *
2650
+ * 为什么要兜底:`requestReview` 会写这个字段,但「看板点下一列」/ 团队回流 / 执行侧置待验收
2651
+ * 这三条路径都只改 `status`,于是出现「卡在待验收列、却没有任何人被请求评审」——
2652
+ * `-193` 快照实测 16 张里 10 张如此(中位滞留 148.4h)。
2653
+ *
2654
+ * 三条纪律:
2655
+ * 1. **幂等**:已有值不覆盖(首次提交时间才是度量口径,M1 全靠它)。
2656
+ * 2. **不涨 version**:这是同一次逻辑写入的记账字段;涨了会破坏调用方 `expectedVersion` 语义。
2657
+ * 3. **不改 `review_state`**:置 `pending` 是「显式请求评审」的动作语义(会释放认领、记来源列),
2658
+ * 混用会把「人点下一列」变成「重设评审轮次」。
2659
+ */
2660
+ markReviewRequested(taskId, at = nowIso()) {
2661
+ if (!taskId) return null;
2662
+ try {
2663
+ db.prepare("update tasks set review_requested_at = ? where id = ? and (review_requested_at is null or review_requested_at = '')").run(at, taskId);
2664
+ return at;
2665
+ } catch { return null; }
2666
+ },
2667
+ /**
2668
+ * 交付物证据(FR-106 / 卡 `-197`):**门在落库前** —— 四字段缺一个就整笔拒绝(`EVIDENCE_INCOMPLETE`),
2669
+ * 不留半条记录。`refs_state` 由调用方给定的 `resolve` 决定(不给则 `unchecked`):解不开的
2670
+ * `artifact_refs` 永远不许被当作"已校验通过"。
2671
+ */
2672
+ addTaskEvidence(ref, input = {}) {
2673
+ const task = store.requireTaskRef(ref);
2674
+ const problems = evidenceProblems(input);
2675
+ if (problems.length) {
2676
+ throw new TbError("EVIDENCE_INCOMPLETE", `交付物证据四字段不全:${problems.map((p) => p.field).join(", ")}`, { identifier: task.identifier, problems });
2677
+ }
2678
+ const artifacts = (Array.isArray(input.artifacts) ? input.artifacts : []).map((a) => String(a).trim()).filter(Boolean);
2679
+ const refs = normalizeArtifactRefs(input.artifactRefs);
2680
+ const verified = verifyArtifactRefs(refs, input.resolve);
2681
+ const id = randomUUID();
2682
+ const at = nowIso();
2683
+ db.prepare(
2684
+ `insert into task_evidence (id, task_id, verdict, deviation, boundary, artifacts, artifact_refs, refs_state, actor, task_version, created_at)
2685
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2686
+ ).run(id, task.id, String(input.verdict).trim(), String(input.deviation ?? "").trim(), String(input.boundary ?? "").trim(),
2687
+ JSON.stringify(artifacts), JSON.stringify(refs), verified.state, String(input.actor ?? "agent"), Number(task.version), at);
2688
+ return store.getTaskEvidenceById(id);
2689
+ },
2690
+ getTaskEvidenceById(id) {
2691
+ const row = db.prepare("select * from task_evidence where id = ?").get(id);
2692
+ return row ? rowToTaskEvidence(row) : null;
2693
+ },
2694
+ listTaskEvidence(ref) {
2695
+ const task = store.requireTaskRef(ref);
2696
+ return db.prepare("select * from task_evidence where task_id = ? order by created_at, rowid").all(task.id).map(rowToTaskEvidence);
2697
+ },
2698
+ /** 有效证据 = 最新一条(历史留档但不再生效)。 */
2699
+ latestTaskEvidence(ref) {
2700
+ const all = store.listTaskEvidence(ref);
2701
+ return all.length ? all[all.length - 1] : null;
2702
+ },
2703
+ /**
2704
+ * 授权快照(FR-107):**append-only**。没有 update / delete 方法,也别加 ——
2705
+ * 加了就等于"授权事实可以被改写",那这张表就白建了。
2706
+ */
2707
+ recordTaskMandate(ref, input = {}) {
2708
+ const task = store.requireTaskRef(ref);
2709
+ const id = randomUUID();
2710
+ const at = nowIso();
2711
+ db.prepare(
2712
+ `insert into task_mandates (id, task_id, requirement_ref, contract_version, norms_digest, scope, claim_owner, claim_source, created_at)
2713
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2714
+ ).run(id, task.id, input.requirementRef ?? null, input.contractVersion ?? null, input.normsDigest ?? null,
2715
+ String(input.scope ?? ""), input.claimOwner ?? null, input.claimSource ?? null, at);
2716
+ return db.prepare("select * from task_mandates where id = ?").get(id);
2717
+ },
2718
+ listTaskMandates(ref) {
2719
+ const task = store.requireTaskRef(ref);
2720
+ return db.prepare("select * from task_mandates where task_id = ? order by created_at, rowid").all(task.id);
2721
+ },
2395
2722
  recordTaskEvent(ref, { type, from = null, to = null, actor = "system", detail = null, now = null } = {}) {
2396
2723
  try {
2397
2724
  if (!type) return null;
@@ -3020,6 +3347,15 @@ export function openStore(options = {}) {
3020
3347
  const clearClaim = status === "in_progress" ? "" : ", claim_lock = null, claim_expires = null, claim_owner = null, last_heartbeat_at = null";
3021
3348
  db.prepare(`update tasks set status = ?${clearClaim}, version = version + 1, updated_at = ? where id = ?`).run(status, nowIso(), t.id);
3022
3349
  store.recordAudit({ actor, action: "set-status", target: t.identifier, allowed: true, reason: "team-writable", detail: status });
3350
+ // FR-112(卡 `-194`):**状态变化必须进事件流**。此前全仓只有 3 处 emit(updateTask / requestReview /
3351
+ // 评审收口),本入口与 applyTeamTaskOutcome 直接写列 ⇒ 实测 175 次完成类变更里 46 次(26%)无事件,
3352
+ // 而诊断 / 看护 / 通知 / M1 度量**全部**建在事件流上 —— 漏 26% 等于度量基础不可信。
3353
+ // 只在实际变化时发(同状态重复写不产生假事件)。
3354
+ if (t.status !== status) store.recordTaskEvent(t.id, { type: "status_changed", from: t.status, to: status, actor });
3355
+ // FR-111(`-195`):执行侧 / 团队通道置待验收同样补评审发起时间
3356
+ if (status === "in_review" && t.status !== status && !t.reviewRequestedAt) store.markReviewRequested(t.id);
3357
+ // FR-107(`-197`):执行侧 / 团队通道进入「进行中」同样是一次认领 ⇒ 冻结授权快照
3358
+ if (status === "in_progress" && t.status !== status) freezeMandate(t.id, { scope: "team", claimOwner: t.claimOwner ?? actor, claimSource: t.status });
3023
3359
  return store.getTaskById(t.id);
3024
3360
  },
3025
3361
  /** 红线③:审查未过 / 上游失败 → 下游保持 blocked(不解锁)。 */
@@ -3047,6 +3383,8 @@ export function openStore(options = {}) {
3047
3383
  const ev = evidence ? `(证据:${evidence})` : "";
3048
3384
  if (outcome === "completed") {
3049
3385
  db.prepare("update tasks set status = 'in_review', version = version + 1, updated_at = ? where id = ?").run(nowIso(), t.id);
3386
+ if (t.status !== "in_review") store.recordTaskEvent(t.id, { type: "status_changed", from: t.status, to: "in_review", actor: "team" }); // FR-112
3387
+ if (!t.reviewRequestedAt) store.markReviewRequested(t.id); // FR-111(`-195`):团队回流进待验收也补
3050
3388
  db.prepare("update team_tasks set status = 'completed', updated_at = ? where id = ?").run(nowIso(), teamTaskId);
3051
3389
  if (row.kind === "review" && reviewPassed !== true) store.blockDownstream(t.id, "review-not-passed");
3052
3390
  store.addComment(t.id, { body: `团队回报:完成 → 提交待验收${ev}` }); // 自动登记反馈
@@ -3054,6 +3392,7 @@ export function openStore(options = {}) {
3054
3392
  } else if (outcome === "failed") {
3055
3393
  // FR-80:团队回报失败也走统一受阻入口(transient)
3056
3394
  db.prepare("update tasks set status = 'blocked', version = version + 1, updated_at = ? where id = ?").run(nowIso(), t.id);
3395
+ if (t.status !== "blocked") store.recordTaskEvent(t.id, { type: "status_changed", from: t.status, to: "blocked", actor: "team" }); // FR-112
3057
3396
  db.prepare("update team_tasks set status = 'failed', updated_at = ? where id = ?").run(nowIso(), teamTaskId);
3058
3397
  store.blockDownstream(t.id, "upstream-failed");
3059
3398
  store.addComment(t.id, { body: `团队回报:失败 → 受阻${ev}` }); // 自动登记失败反馈