taskboard-workbench 0.3.2 → 0.3.4

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.
@@ -4,7 +4,7 @@
4
4
  * owner 为 tasks 正式列(t24)——老库的 `owner:<role>` 标签在打开时一次性迁移(幂等)。
5
5
  * 注意:tasks_owner_idx 只在迁移函数里创建(老库建表语句是 no-op,提前建索引会因缺列失败)。
6
6
  */
7
- import { randomUUID } from "node:crypto";
7
+ import { createHash, randomUUID } from "node:crypto";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { mkdirSync } from "node:fs";
10
10
  import path from "node:path";
@@ -31,14 +31,15 @@ import {
31
31
  deriveDetailState,
32
32
  } from "./requirements.mjs";
33
33
  import { TEAM_WRITABLE_STATUSES } from "./team.mjs";
34
- import { evidenceProblems, normalizeArtifactRefs, verifyArtifactRefs } from "./evidence.mjs";
34
+ import { evidenceProblems, makeResolver, normalizeArtifactRefs, verifyArtifactRefs } from "./evidence.mjs";
35
35
  import { REVIEW_SOURCE_STATUSES, REVIEW_IDLE_MS, detectReviewDeadlock, reviewReturnStatus } from "./review.mjs";
36
36
  import { NOTIFY_DELIVERY_MODES, buildNotifyMessage, normalizeDeliveryMode, selectNotifyEvents } from "./notify.mjs";
37
37
  import { HUMAN_REVIEW_LABEL, assertConclusion, categoryLabel, conclusionOutcome, isHumanReviewTask, validateHumanReviewDraft } from "./human-review.mjs";
38
38
  // 项目记忆(2026-10-28 拍板 D-M1):L2 记忆条目,与内核表同库;**不是第二真源**(必带 provenance)。
39
39
  import { createMemoryApi } from "./memory.mjs";
40
+ import { createLeaseApi } from "./instance-lease.mjs";
40
41
 
41
- export const SCHEMA_VERSION = 14; // 14:项目设置 flow_inject_policy(P5 档 C · 卡 -210);13:交付物证据 task_evidence + 授权快照 task_mandates(0-B · 卡 -197);12:契约快照
42
+ export const SCHEMA_VERSION = 15; // 15:agents / agent_sessions + task_evidence.evidence_hash + WAL(0-B-b · 卡 -239);14:项目设置 flow_inject_policy(P5 档 C · 卡 -210);13:交付物证据 task_evidence + 授权快照 task_mandates(0-B · 卡 -197);12:契约快照
42
43
  // 条目化数量口径(卡 `-169` P4②):定义在 requirements.mjs(纯模块),此处转发以便调用方就近取用。
43
44
  export { clampElaborateLimit, DEFAULT_ELABORATE_LIMIT, MAX_ELABORATE_LIMIT, ELABORATE_PREVIEW_SIZE };
44
45
 
@@ -288,6 +289,8 @@ create table if not exists task_evidence (
288
289
  verdict text not null, deviation text not null default '', boundary text not null default '',
289
290
  artifacts text not null default '[]', artifact_refs text not null default '[]',
290
291
  refs_state text not null default 'unchecked',
292
+ -- 0-B-b(FR-106 第 5 条):同一份证据重复提交按指纹幂等(返回首次结果、不增行)
293
+ evidence_hash text,
291
294
  actor text not null, task_version integer not null, created_at text not null
292
295
  );
293
296
  create index if not exists task_evidence_task_idx on task_evidence(task_id, created_at);
@@ -298,6 +301,24 @@ create table if not exists task_mandates (
298
301
  requirement_ref text, contract_version text, norms_digest text,
299
302
  scope text not null default '', claim_owner text, claim_source text, created_at text not null
300
303
  );
304
+ -- agent 身份(FR-108 / 0-B-b):**进程级本地身份**,不是鉴权体系。
305
+ -- token_hash 只建表留接口 —— stdio MCP 没有鉴权通道,令牌要等 S3 才有载体;
306
+ -- 所以**任何地方都不得以「有这张表」为由宣称鉴权已生效**。
307
+ create table if not exists agents (
308
+ id text primary key,
309
+ kind text not null default 'agent' check (kind in ('human','agent')),
310
+ display_name text not null default '',
311
+ token_hash text,
312
+ permission_profile text,
313
+ created_at text not null
314
+ );
315
+ -- 身份 ≠ 会话:会话绑定只是 agent 的**可选**属性(未绑定会话的本地 agent 同样有身份)。
316
+ create table if not exists agent_sessions (
317
+ agent_id text not null references agents(id) on delete cascade,
318
+ session_id text,
319
+ bound_at text not null,
320
+ primary key (agent_id, session_id)
321
+ );
301
322
  create index if not exists task_mandates_task_idx on task_mandates(task_id, created_at);
302
323
 
303
324
  create index if not exists task_runs_task_idx on task_runs(task_id, started_at);
@@ -700,12 +721,37 @@ function rowToTaskEvidence(row) {
700
721
  id: row.id, taskId: row.task_id,
701
722
  verdict: row.verdict, deviation: row.deviation, boundary: row.boundary,
702
723
  artifacts: safeJsonArray(row.artifacts), artifactRefs: safeJsonArray(row.artifact_refs),
703
- refsState: row.refs_state, actor: row.actor, taskVersion: row.task_version, createdAt: row.created_at,
724
+ refsState: row.refs_state, evidenceHash: row.evidence_hash ?? null,
725
+ actor: row.actor, taskVersion: row.task_version, createdAt: row.created_at,
726
+ };
727
+ }
728
+ function rowToAgent(row) {
729
+ return {
730
+ id: row.id, kind: row.kind, displayName: row.display_name,
731
+ // 注意:**不回传 token_hash 原文之外的任何东西** —— 这里只如实标注"有没有登记过",
732
+ // 不把哈希值抛给调用方(哈希本身也不该在 UI/日志里流转)。
733
+ hasTokenHash: Boolean(row.token_hash),
734
+ permissionProfile: row.permission_profile ?? null, createdAt: row.created_at,
704
735
  };
705
736
  }
706
737
  function safeJsonArray(raw) {
707
738
  try { const v = JSON.parse(raw ?? "[]"); return Array.isArray(v) ? v : []; } catch { return []; }
708
739
  }
740
+ /**
741
+ * 证据指纹(FR-106 第 5 条 / 0-B-b):同一次回填重复调用不该长第二行。
742
+ *
743
+ * 为什么用 sha256 而不是拿内容建唯一索引:内容列是 JSON 文本,顺序一变就不等;
744
+ * 指纹先归一(固定字段序 + 归一后的 refs),同一份证据无论怎么传都得到同一个值。
745
+ * 与 `src/mcp/tools.mjs` 的 `evidenceHash` **不是一回事**:那个给评论去重、只覆盖 `evidence[]`。
746
+ */
747
+ function evidenceFingerprint({ verdict, deviation, boundary, artifacts, refs }) {
748
+ const material = JSON.stringify({
749
+ verdict, deviation, boundary,
750
+ artifacts: [...artifacts],
751
+ refs: (refs ?? []).map((r) => [r.kind, r.ref, r.note ?? ""]),
752
+ });
753
+ return createHash("sha256").update(material).digest("hex").slice(0, 32);
754
+ }
709
755
 
710
756
  export function migrateOwnerField(db) {
711
757
  const columns = db.prepare("pragma table_info(tasks)").all().map((row) => row.name);
@@ -761,6 +807,24 @@ export function migrateTeamMembers(db) {
761
807
  return { addedTeamMemberExecutorColumn: false };
762
808
  }
763
809
 
810
+ /**
811
+ * 迁移(幂等,0-B-b):老库的 `task_evidence` 补 `evidence_hash` 列 + 指纹索引。
812
+ *
813
+ * 为什么必须用迁移而不是只改建表语句:`create table if not exists` 对已存在的表是 no-op,
814
+ * 老库(schema 14)不会自动长出新列 —— 那样「幂等提交」在存量库上会直接报 no column。
815
+ */
816
+ export function migrateTaskEvidenceHash(db) {
817
+ const columns = db.prepare("pragma table_info(task_evidence)").all().map((row) => row.name);
818
+ if (columns.length === 0) return { addedEvidenceHashColumn: false };
819
+ if (!columns.includes("evidence_hash")) {
820
+ db.exec("alter table task_evidence add column evidence_hash text");
821
+ db.exec("create index if not exists task_evidence_hash_idx on task_evidence(task_id, evidence_hash)");
822
+ return { addedEvidenceHashColumn: true };
823
+ }
824
+ db.exec("create index if not exists task_evidence_hash_idx on task_evidence(task_id, evidence_hash)");
825
+ return { addedEvidenceHashColumn: false };
826
+ }
827
+
764
828
  /** 迁移(幂等):老库的 projects 表补 `next_req_seq` 列(需求条目编号序列)。 */
765
829
  export function migrateRequirementSeq(db) {
766
830
  const projectColumns = db.prepare("pragma table_info(projects)").all().map((row) => row.name);
@@ -1000,8 +1064,14 @@ export function openStore(options = {}) {
1000
1064
  db = new DatabaseSync(dbPath);
1001
1065
  db.exec("pragma foreign_keys = on");
1002
1066
  db.exec("pragma busy_timeout = 5000");
1067
+ // 0-B-b · F6:`WAL` —— 读写不互相阻塞(Web 读看板时 MCP/CLI 仍可写)。
1068
+ // **连带义务**:备份不能只拷 `.sqlite`(已提交但未 checkpoint 的页在 `-wal` 里),
1069
+ // 必须走 `.backup` / `VACUUM INTO`;`tools/baseline-metrics.mjs` 已用 `backup()`,
1070
+ // `tools/audit-intake.mjs` 与 `tools/seed-docs.mjs` 本轮一并改掉 `copyFileSync`。
1071
+ // `:memory:` 不支持 WAL(也无意义),显式跳过。
1072
+ if (dbPath !== ":memory:") db.exec("pragma journal_mode = wal");
1003
1073
  db.exec(SCHEMA_SQL);
1004
- migration = { ...migrateOwnerField(db), ...migrateRequirementSeq(db), ...migrateTeamMembers(db) };
1074
+ migration = { ...migrateOwnerField(db), ...migrateRequirementSeq(db), ...migrateTeamMembers(db), ...migrateTaskEvidenceHash(db) };
1005
1075
  } catch (error) {
1006
1076
  const wrapped = new TbError(
1007
1077
  "STORE_UNAVAILABLE",
@@ -2610,6 +2680,29 @@ export function openStore(options = {}) {
2610
2680
  return store.requestReview(ref, { comment, actor: "team" }).task;
2611
2681
  },
2612
2682
  // ---------------- 评审流程(FR-83) ----------------
2683
+ /**
2684
+ * 缺省评审者(卡 `-244` / 需求 `R178`):项目团队模板里含 `review` 的角色名。
2685
+ *
2686
+ * 为什么要有:`requestReview` 不传 reviewer 时原来一律留空,而 `detectReviewDeadlock`
2687
+ * 对「reviewer 为空且超过阈值」**必然**产出 `unassigned` 死锁(`review.mjs:73-79`)——
2688
+ * 即「待验收」只要没人手填评审者就注定变高危诊断。真机里 8 张卡 reviewer 全空、
2689
+ * vibe-5/6 挂 37 分钟,就是这条的产物。
2690
+ * 找不到 review 角色(或项目没配团队模板)⇒ 仍返回 null,**旧行为一字不变**。
2691
+ */
2692
+ pickDefaultReviewer(projectId) {
2693
+ try {
2694
+ const roles = store.getProjectSettings(projectId)?.teamTemplate?.roles;
2695
+ const norm = (name) => String(name ?? "").trim().toLowerCase();
2696
+ if (Array.isArray(roles)) {
2697
+ const hit = roles.map((r) => norm(r?.role ?? r)).find((n) => n.includes("review"));
2698
+ if (hit) return hit;
2699
+ } else if (roles && typeof roles === "object") {
2700
+ const hit = Object.keys(roles).map(norm).find((n) => n.includes("review"));
2701
+ if (hit) return hit;
2702
+ }
2703
+ } catch { /* 项目设置读不到 ⇒ 不指派,保持旧行为 */ }
2704
+ return null;
2705
+ },
2613
2706
  /**
2614
2707
  * 请求评审(FR-83 的一等流程):进「待验收」+ **指派评审者** + 记下**来源列**(返工退回哪一列)。
2615
2708
  * 释放实现认领(FR-77);执行成功照 FR-78 记账;事件流写 `review_requested`。
@@ -2617,6 +2710,9 @@ export function openStore(options = {}) {
2617
2710
  requestReview(ref, { reviewer = null, dependsOn = null, comment = "", actor = "team", now = null } = {}) {
2618
2711
  const task = store.requireTaskRef(ref);
2619
2712
  const at = new Date(now ?? Date.now()).toISOString();
2713
+ // 卡 `-244`(R178):显式传了的优先;没传就按项目团队模板补一个评审角色,
2714
+ // 否则「待验收」必然在阈值后变成 `unassigned` 评审死锁。
2715
+ const assigned = reviewer ?? store.pickDefaultReviewer(task.projectId);
2620
2716
  // 来源列:第一次提交时记下当前列;返工后重提则**沿用**上次来源列(保证返工总回同一实现列)
2621
2717
  const source = task.status === "in_review"
2622
2718
  ? (task.reviewSourceStatus ?? "in_progress")
@@ -2627,13 +2723,17 @@ export function openStore(options = {}) {
2627
2723
  review_depends_on = case when ? is null then review_depends_on else ? end,
2628
2724
  claim_lock = null, claim_expires = null, claim_owner = null, last_heartbeat_at = null,
2629
2725
  version = version + 1, updated_at = ? where id = ?`,
2630
- ).run(reviewer, at, source, dependsOn, dependsOn, at, task.id);
2726
+ ).run(assigned, at, source, dependsOn, dependsOn, at, task.id);
2631
2727
  if (comment) store.addComment(task.id, { body: comment });
2632
2728
  store.markTaskSucceeded(task.identifier); // FR-78:产出已提交待验收 = 本次执行成功
2633
- store.recordTaskEvent(task.id, { type: "status_changed", from: task.status, to: "in_review", actor });
2634
- store.recordTaskEvent(task.id, { type: "review_requested", to: "in_review", actor, detail: `${reviewer ? `指派评审者 ${reviewer}` : "未指派评审者"}·来源列 ${source}${comment ? `|${comment}` : ""}` });
2729
+ // 卡 `-245`(R178):已经在「待验收」再点一次,是同态迁移 —— 不写空转事件
2730
+ // (真机 8 卡攒了 16 条 `in_review→in_review`,纯日志噪音)。`review_requested` 照写,动作本身要留痕。
2731
+ if (task.status !== "in_review") {
2732
+ store.recordTaskEvent(task.id, { type: "status_changed", from: task.status, to: "in_review", actor });
2733
+ }
2734
+ store.recordTaskEvent(task.id, { type: "review_requested", to: "in_review", actor, detail: `${assigned ? `指派评审者 ${assigned}` : "未指派评审者"}·来源列 ${source}${comment ? `|${comment}` : ""}` });
2635
2735
  const next = store.getTaskById(task.id);
2636
- if (!reviewer) {
2736
+ if (!assigned) {
2637
2737
  try { store.addComment(task.id, { body: `待评审(未指派评审者):${REVIEW_IDLE_MS / 60000} 分钟无人处理将产出「评审死锁」诊断。` }); } catch { /* ignore */ }
2638
2738
  }
2639
2739
  return { task: next, review: { state: next.reviewState, reviewer: next.reviewer, sourceStatus: source, round: next.reviewRound }, deadlock: detectReviewDeadlock(store, next) };
@@ -2828,6 +2928,15 @@ export function openStore(options = {}) {
2828
2928
  * 不留半条记录。`refs_state` 由调用方给定的 `resolve` 决定(不给则 `unchecked`):解不开的
2829
2929
  * `artifact_refs` 永远不许被当作"已校验通过"。
2830
2930
  */
2931
+ /**
2932
+ * 写一条交付物证据(FR-106 的唯一落库点:MCP `card_evidence_submit` 与 HTTP `POST /api/tasks/:ref/evidence` 都走这里)。
2933
+ *
2934
+ * 三条口径(0-B-b 卡 `-239`):
2935
+ * ① **四字段硬门**在事务前 —— 缺一即 `EVIDENCE_INCOMPLETE`,零落库(既有行为,不改);
2936
+ * ② **核验 root 绑 `project.workspacePath`** —— 不传 `resolve` 时用项目工作区,**不用 `process.cwd()`**
2937
+ * (MCP 子进程的 cwd 是客户端目录,拿它核验等于核到别的仓库);
2938
+ * ③ **同指纹幂等** —— 同一张卡上 `evidenceHash` 相同 ⇒ 返回首次那条,不增行。
2939
+ */
2831
2940
  addTaskEvidence(ref, input = {}) {
2832
2941
  const task = store.requireTaskRef(ref);
2833
2942
  const problems = evidenceProblems(input);
@@ -2836,15 +2945,28 @@ export function openStore(options = {}) {
2836
2945
  }
2837
2946
  const artifacts = (Array.isArray(input.artifacts) ? input.artifacts : []).map((a) => String(a).trim()).filter(Boolean);
2838
2947
  const refs = normalizeArtifactRefs(input.artifactRefs);
2839
- const verified = verifyArtifactRefs(refs, input.resolve);
2948
+ // 核验器:调用方给就用调用方的(测试注入),否则**必须**按项目工作区建。
2949
+ let resolver = input.resolve;
2950
+ if (typeof resolver !== "function") {
2951
+ const project = store.getProject(task.projectId);
2952
+ resolver = makeResolver({ root: project?.workspacePath ?? null });
2953
+ }
2954
+ const verified = verifyArtifactRefs(refs, resolver);
2955
+ const verdict = String(input.verdict).trim();
2956
+ const deviation = String(input.deviation ?? "").trim();
2957
+ const boundary = String(input.boundary ?? "").trim();
2958
+ const evidenceHash = evidenceFingerprint({ verdict, deviation, boundary, artifacts, refs });
2959
+ const existing = db.prepare("select * from task_evidence where task_id = ? and evidence_hash = ? order by created_at, rowid limit 1").get(task.id, evidenceHash);
2960
+ if (existing) return { ...rowToTaskEvidence(existing), deduped: true };
2840
2961
  const id = randomUUID();
2841
2962
  const at = nowIso();
2842
2963
  db.prepare(
2843
- `insert into task_evidence (id, task_id, verdict, deviation, boundary, artifacts, artifact_refs, refs_state, actor, task_version, created_at)
2844
- values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2845
- ).run(id, task.id, String(input.verdict).trim(), String(input.deviation ?? "").trim(), String(input.boundary ?? "").trim(),
2846
- JSON.stringify(artifacts), JSON.stringify(refs), verified.state, String(input.actor ?? "agent"), Number(task.version), at);
2847
- return store.getTaskEvidenceById(id);
2964
+ `insert into task_evidence (id, task_id, verdict, deviation, boundary, artifacts, artifact_refs, refs_state, evidence_hash, actor, task_version, created_at)
2965
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2966
+ ).run(id, task.id, verdict, deviation, boundary,
2967
+ JSON.stringify(artifacts), JSON.stringify(refs), verified.state, evidenceHash,
2968
+ String(input.actor ?? "agent"), Number(task.version), at);
2969
+ return { ...store.getTaskEvidenceById(id), deduped: false };
2848
2970
  },
2849
2971
  getTaskEvidenceById(id) {
2850
2972
  const row = db.prepare("select * from task_evidence where id = ?").get(id);
@@ -2854,6 +2976,42 @@ export function openStore(options = {}) {
2854
2976
  const task = store.requireTaskRef(ref);
2855
2977
  return db.prepare("select * from task_evidence where task_id = ? order by created_at, rowid").all(task.id).map(rowToTaskEvidence);
2856
2978
  },
2979
+ /**
2980
+ * 登记 agent 身份(FR-108 / 0-B-b)—— **进程级本地身份**,不是鉴权。
2981
+ *
2982
+ * 幂等:同一个 `id` 再登记**复用已有行**(不新建、不换 id),只补空字段。
2983
+ * `tokenHash` 只落接口位:stdio MCP 没有鉴权通道,**本轮不宣称鉴权生效**。
2984
+ */
2985
+ registerAgent(input = {}) {
2986
+ const declared = typeof input.id === "string" ? input.id.trim() : "";
2987
+ const id = declared !== "" ? declared : `anon-${randomUUID()}`;
2988
+ const existing = db.prepare("select * from agents where id = ?").get(id);
2989
+ const at = nowIso();
2990
+ if (existing) {
2991
+ // 只补空字段,不覆盖已登记的值(否则重启时传不同 display_name 会把历史身份改掉)。
2992
+ db.prepare("update agents set display_name = case when display_name = '' then ? else display_name end, permission_profile = coalesce(permission_profile, ?) where id = ?")
2993
+ .run(String(input.displayName ?? "").trim(), input.permissionProfile ?? null, id);
2994
+ return { ...rowToAgent(db.prepare("select * from agents where id = ?").get(id)), created: false };
2995
+ }
2996
+ db.prepare("insert into agents (id, kind, display_name, token_hash, permission_profile, created_at) values (?, ?, ?, ?, ?, ?)")
2997
+ .run(id, input.kind === "human" ? "human" : "agent", String(input.displayName ?? "").trim(),
2998
+ input.tokenHash ?? null, input.permissionProfile ?? null, at);
2999
+ return { ...rowToAgent(db.prepare("select * from agents where id = ?").get(id)), created: true };
3000
+ },
3001
+ getAgent(id) {
3002
+ const row = db.prepare("select * from agents where id = ?").get(String(id));
3003
+ return row ? rowToAgent(row) : null;
3004
+ },
3005
+ listAgents() {
3006
+ return db.prepare("select * from agents order by created_at, rowid").all().map(rowToAgent);
3007
+ },
3008
+ bindAgentSession(agentId, sessionId) {
3009
+ if (!store.getAgent(agentId)) throw new TbError("AGENT_NOT_FOUND", `未登记的 agent:${agentId}`, { agentId });
3010
+ if (sessionId === null || sessionId === undefined || String(sessionId).trim() === "") return null;
3011
+ db.prepare("insert or ignore into agent_sessions (agent_id, session_id, bound_at) values (?, ?, ?)")
3012
+ .run(String(agentId), String(sessionId), nowIso());
3013
+ return { agentId: String(agentId), sessionId: String(sessionId) };
3014
+ },
2857
3015
  /** 有效证据 = 最新一条(历史留档但不再生效)。 */
2858
3016
  latestTaskEvidence(ref) {
2859
3017
  const all = store.listTaskEvidence(ref);
@@ -3590,6 +3748,13 @@ export function openStore(options = {}) {
3590
3748
  legacyOwnerLabels: count("select count(*) as n from tasks where labels like '%owner:%'"),
3591
3749
  dbPath,
3592
3750
  dataDir,
3751
+ // 卡 `-237`:`role` = writer | follower;follower 表示「另一个实例正持有写者租约」。
3752
+ // 这里刻意用 **现读**(fresh):health 是给「我现在能不能写」这个判断看的,
3753
+ // 吃 15s 的本地缓存会让提示滞后于事实。
3754
+ role: typeof store.instanceRoleFresh === "function" ? store.instanceRoleFresh() : "writer",
3755
+ leaseOwner: typeof store.instanceLeaseOwnerFresh === "function" ? store.instanceLeaseOwnerFresh() : null,
3756
+ // 卡 `-236`:默认目录搬家后的**只读**迁移提示(空新库 + 有数据的旧库)。由宿主侧探测后挂上,探测不到就是 null。
3757
+ dataDirHint: store.dataDirHint ?? null,
3593
3758
  schemaVersion: SCHEMA_VERSION,
3594
3759
  migration,
3595
3760
  };
@@ -3598,6 +3763,8 @@ export function openStore(options = {}) {
3598
3763
 
3599
3764
  // 项目记忆:同库、同事务语义,但**不感知** MCP/CLI/Web(只是用例层的又一扇门)。
3600
3765
  Object.assign(store, createMemoryApi({ db, nowIso, randomUUID }));
3766
+ // 卡 `-237`(R173):多实例单写者租约(不 acquire 的调用方恒 writer ⇒ 零行为变化)。
3767
+ Object.assign(store, createLeaseApi({ db, nowIso, randomUUID }));
3601
3768
 
3602
3769
  return store;
3603
3770
  }
@@ -38,6 +38,33 @@ export function normalizeVerifyCommand(raw) {
38
38
  return s;
39
39
  }
40
40
 
41
+ /**
42
+ * 「这条命令根本跑不起来」的前置识别(卡 `-249` / 需求 `R179`)。
43
+ *
44
+ * 真机 2026-11-12(`scada-vibe-1`):复核动作被写成
45
+ * `git -C 00-project-real/scada status --porcelain && git apply --check <diff文件>` ——
46
+ * `<diff文件>` 是**给人看的占位符**,但 `spawn(cmd, { shell: true })` 会交给 `/bin/sh` 解析:
47
+ * `<` 被当成重定向、`>` 没有目标 ⇒ **语法错误** ⇒ 退出码 2 ⇒ 结论写成「失败(退出码 2)」。
48
+ * 读起来像「产品挂了 / 测试没过」,实际是「这条命令不是命令,是模板」。
49
+ *
50
+ * 处置与 FR-94 的第三态同构:**不跑**,判「不适用」,并把该替换的位置原样点名。
51
+ * 只认两种明显的模板痕迹(`<…>` 与 `{{…}}`):`diff <(a) <(b)` 这类进程替换、`2>&1` 这类
52
+ * 重定向都不会命中,避免把合法命令误判成模板。
53
+ */
54
+ export function detectUnrunnableVerify(raw) {
55
+ const s = String(raw ?? "").trim();
56
+ if (s === "") return null;
57
+ const angle = /<([^<>\n]{1,40})>/.exec(s);
58
+ if (angle) {
59
+ return { kind: "placeholder", token: angle[0], reason: `复核命令含未替换的占位符 ${angle[0]}(shell 会把 \`<\` 当重定向解析 ⇒ 语法错误,永远跑不起来)` };
60
+ }
61
+ const brace = /\{\{([^}\n]{1,40})\}\}/.exec(s);
62
+ if (brace) {
63
+ return { kind: "placeholder", token: brace[0], reason: `复核命令含未替换的占位符 ${brace[0]}(模板变量没展开)` };
64
+ }
65
+ return null;
66
+ }
67
+
41
68
  /**
42
69
  * 人能读的结论(评审人第一眼看的就这一行)。
43
70
  *
@@ -8,7 +8,8 @@
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
+ * node src/mcp/server.mjs --read-only # **只读模式**(P3 的回滚开关):写件不出现在 tools/list,调用即 READ_ONLY_MODE
12
+ * node src/mcp/server.mjs --agent-id <id> # 0-B-b:登记进程级本地身份(缺省生成匿名 id 落盘)
12
13
  *
13
14
  * 传输:newline-delimited JSON-RPC 2.0(MCP stdio transport)。
14
15
  * stdout **只允许**出现协议消息;日志一律走 stderr(否则客户端解析失败)。
@@ -37,9 +38,9 @@ const ACTIVE_TOOLS = READ_ONLY ? TOOLS.filter((t) => t.annotations?.readOnlyHint
37
38
  const ACTIVE_NAMES = ACTIVE_TOOLS.map((t) => t.name);
38
39
 
39
40
  if (has("--help") || has("-h")) {
40
- process.stderr.write(`taskboard-workbench MCP server(9 个工具:只读五 / 写四 · prompt 1)
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 的回滚开关
41
+ process.stderr.write(`taskboard-workbench MCP server(${TOOL_NAMES.length} 个工具:只读五 / 写五 · prompt 1)
42
+ 用法: node src/mcp/server.mjs [--data-dir <dir>] [--agent-id <id>] [--print-tools] [--read-only]
43
+ 只读: --read-only 关闭写件(card_create / card_progress / card_evidence_submit / requirement_upsert / requirement_change)——P3 的回滚开关
43
44
  工具: ${TOOL_NAMES.join(", ")}
44
45
  提示: prompt taskboard.flow(= node scripts/tb-flow.mjs start 的输出)
45
46
  数据: --data-dir > $TB_DATA_DIR > 默认(同 Web/CLI)
@@ -56,10 +57,22 @@ if (has("--print-tools")) {
56
57
 
57
58
  const dataDir = argOf("--data-dir") ?? process.env.TB_DATA_DIR ?? undefined;
58
59
  const store = openStore({ dataDir, env: process.env });
59
- const ctx = { store };
60
+ // 0-B-b(FR-108):**进程级本地身份**。`--agent-id` 显式给就复用那一行;不给就生成匿名 id 并落盘
61
+ // (不是"每次调用一个新 id" —— 同一进程内只有一个 id,重启才可能换)。
62
+ // 注意边界:`token_hash` 只是建表留接口,stdio MCP **没有鉴权通道**,这里**不宣称鉴权生效**。
63
+ // ⚠ `--read-only` 是**零写入**的回滚开关:只读模式下**不登记**(登记本身是一条 insert),
64
+ // 用一个不落库的进程内身份代替 —— 否则"只读"会变成"只读 + 悄悄写一行 agents"。
65
+ const agent = READ_ONLY
66
+ ? { id: argOf("--agent-id") ?? "readonly", created: false, persisted: false }
67
+ : { ...store.registerAgent({
68
+ id: argOf("--agent-id") ?? undefined,
69
+ displayName: argOf("--agent-name") ?? "",
70
+ kind: "agent",
71
+ }), persisted: true };
72
+ const ctx = { store, agentId: agent.id };
60
73
  let skillMeta = null;
61
74
  try { skillMeta = readSkill().meta; } catch { /* skill 缺失时不影响工具面;prompts/* 会报出具体原因 */ }
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`);
75
+ process.stderr.write(`[tb-mcp] ready dataDir=${store.dataDir} readOnly=${READ_ONLY} agent=${agent.id}${agent.created ? "(new)" : ""} tools=${ACTIVE_NAMES.join(",")} prompt=taskboard.flow skill=${skillMeta ? `v${skillMeta.version}` : "missing"}\n`);
63
76
 
64
77
  const SERVER_INFO = { name: "taskboard-workbench", version: pkg.version };
65
78
  const DEFAULT_PROTOCOL = "2025-06-18";
package/src/mcp/tools.mjs CHANGED
@@ -25,6 +25,8 @@ import { evaluateSubmittedContract, loadNorms, NORM_IDS, sha256 } from "../core/
25
25
  import { TbError } from "../core/errors.mjs";
26
26
  import { matchProjectForCwd } from "../core/binding.mjs";
27
27
  import { markAcceptance, acceptanceFlag } from "../core/acceptance.mjs";
28
+ import { EVIDENCE_KINDS, EVIDENCE_REF_KINDS, artifactRefKindProblems } from "../core/evidence.mjs";
29
+ import { ticketStage } from "../core/ticket-stage.mjs";
28
30
 
29
31
  /** 包根目录(仓库里 = 仓库根;npm 包里 = package 根)。`spec/norms` 在两处都随包存在。 */
30
32
  export const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
@@ -211,7 +213,10 @@ export function workbenchAudit({ store }, args = {}) {
211
213
 
212
214
  /* --------------------------------------------------- P3:写工具 + 条目列表 ---- */
213
215
 
214
- const EVIDENCE_KINDS = Object.freeze(["file", "command", "url", "reading"]);
216
+ // `EVIDENCE_KINDS` 现在只有一处定义(`src/core/evidence.mjs`)—— 三个入口共用,避免各写一份漂移。
217
+ // `card_progress` 只收**过程性证据**(command/url/reading/file);`commit` 属交付证据(`card_evidence_submit`),
218
+ // 从同一个枚举里派生而不是另写一份,这样新增 kind 时只改一处。
219
+ const PROCESS_EVIDENCE_KINDS = Object.freeze(EVIDENCE_KINDS.filter((k) => k !== "commit"));
215
220
  /** 条目「版本」:`requirement_items` 没有 version 列 ⇒ 用**内容摘要**当乐观锁(纯读、可重算、与行数无关)。 */
216
221
  const REQ_VERSION_FIELDS = Object.freeze(["title", "description", "acceptance", "priority", "status"]);
217
222
 
@@ -250,7 +255,7 @@ function normalizeEvidence(list) {
250
255
  throw fail(
251
256
  "EVIDENCE_REQUIRED",
252
257
  "回填进度必须带 evidence[](非空数组),每项 {kind, ref, note?};只写「已完成」三个字不算证据",
253
- { allowedKinds: EVIDENCE_KINDS },
258
+ { allowedKinds: PROCESS_EVIDENCE_KINDS },
254
259
  );
255
260
  }
256
261
  return list.map((raw, i) => {
@@ -258,8 +263,8 @@ function normalizeEvidence(list) {
258
263
  throw fail("EVIDENCE_INVALID", `evidence[${i}] 必须是对象 {kind, ref, note?}`, { index: i });
259
264
  }
260
265
  const kind = String(raw.kind ?? "").trim();
261
- if (!EVIDENCE_KINDS.includes(kind)) {
262
- throw fail("EVIDENCE_INVALID", `evidence[${i}].kind 必须是 ${EVIDENCE_KINDS.join(" / ")} 之一`, { index: i, received: kind, allowedKinds: EVIDENCE_KINDS });
266
+ if (!PROCESS_EVIDENCE_KINDS.includes(kind)) {
267
+ throw fail("EVIDENCE_INVALID", `evidence[${i}].kind 必须是 ${PROCESS_EVIDENCE_KINDS.join(" / ")} 之一`, { index: i, received: kind, allowedKinds: EVIDENCE_KINDS });
263
268
  }
264
269
  const ref = String(raw.ref ?? "").trim();
265
270
  if (ref === "") {
@@ -586,6 +591,59 @@ export function cardProgress({ store }, args = {}) {
586
591
  };
587
592
  }
588
593
 
594
+ /* ---------------- card_evidence_submit(写 · 交付证据 · FR-106 / 0-B-b) ---------------- */
595
+
596
+ /**
597
+ * 交付证据写入口(MCP 侧)。与 HTTP `POST /api/tasks/:ref/evidence` **同源**。
598
+ *
599
+ * 刻意**不接受**「只给 `evidence[]`」的调用形态:`store.addTaskEvidence` 的四字段硬门会整笔拒,
600
+ * 工具一上线就是死的。要写过程性证据(command / url / reading)请走 `card_progress`;
601
+ * 这里只写**交付证据**(verdict / deviation / boundary / artifacts)。
602
+ */
603
+ export function cardEvidenceSubmit({ store, agentId }, args = {}) {
604
+ const ref = [args.card, args.ref, args.task]
605
+ .find((x) => typeof x === "string" && x.trim() !== "")?.trim() ?? "";
606
+ if (ref === "") throw fail("USAGE_ERROR", "card_evidence_submit 需要 card(任务编号或 id)", {});
607
+ const task = store.requireTaskRef(ref);
608
+
609
+ const submittedRefs = args.artifact_refs ?? args.artifactRefs;
610
+ const badKinds = artifactRefKindProblems(submittedRefs);
611
+ if (badKinds.length) {
612
+ throw fail("INVALID_ARTIFACT_REF", `artifact_refs 只接受 ${EVIDENCE_REF_KINDS.join(" / ")}(非法项:第 ${badKinds.map((b) => b.index + 1).join("、")} 项)`, { problems: badKinds });
613
+ }
614
+
615
+ const evidence = store.addTaskEvidence(task.identifier, {
616
+ verdict: args.verdict,
617
+ deviation: args.deviation,
618
+ boundary: args.boundary,
619
+ artifacts: args.artifacts,
620
+ artifactRefs: submittedRefs,
621
+ // 身份不是自报:默认取**进程身份**(`--agent-id`),显式 `actor_id` 只在测试里用。
622
+ actor: args.actor_id ?? agentId ?? "agent",
623
+ });
624
+
625
+ const after = store.requireTaskRef(task.identifier);
626
+ return {
627
+ card: {
628
+ identifier: after.identifier,
629
+ status: after.status,
630
+ version: after.version,
631
+ requirementId: after.requirementId ?? null,
632
+ },
633
+ evidence: {
634
+ id: evidence.id,
635
+ deduped: Boolean(evidence.deduped),
636
+ refsState: evidence.refsState,
637
+ evidenceHash: evidence.evidenceHash ?? null,
638
+ actor: evidence.actor,
639
+ artifacts: evidence.artifacts,
640
+ artifactRefs: evidence.artifactRefs,
641
+ },
642
+ ticketStage: ticketStage(after, { evidence, comments: store.listComments(after.id) }),
643
+ contract: contractReadout(store, task.projectId, args.contract),
644
+ };
645
+ }
646
+
589
647
  /* ------------------------------------------------------------------ 注册表 ---- */
590
648
 
591
649
  const ok = (schema) => schema;
@@ -733,6 +791,39 @@ export const TOOLS = Object.freeze([
733
791
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
734
792
  handler: cardCreate,
735
793
  },
794
+ {
795
+ name: "card_evidence_submit",
796
+ description: "提交交付证据(写)。四字段**必填**:verdict / deviation / boundary / artifacts(缺一 ⇒ EVIDENCE_INCOMPLETE,零落库)。artifact_refs 只接受 commit / file(其余 ⇒ INVALID_ARTIFACT_REF)。同指纹重复提交幂等(返回首次结果、不增行)。与 HTTP POST /api/tasks/:ref/evidence 同源。",
797
+ inputSchema: ok({
798
+ type: "object",
799
+ required: ["card", "verdict", "deviation", "boundary", "artifacts"],
800
+ properties: {
801
+ card: { type: "string", description: "任务编号或 id" },
802
+ verdict: { type: "string", description: "判定(做了什么、结论是什么)" },
803
+ deviation: { type: "string", description: "偏离说明(没按原计划做的部分都写这里;不写=隐藏信息)" },
804
+ boundary: { type: "string", description: "边界自查(未取得/无法判定的读数必须明说)" },
805
+ artifacts: { type: "array", items: { type: "string" }, description: "产物路径 / 命令 / 指纹(非空)" },
806
+ artifact_refs: {
807
+ type: "array",
808
+ items: {
809
+ type: "object",
810
+ properties: {
811
+ kind: { type: "string", enum: [...EVIDENCE_REF_KINDS] },
812
+ ref: { type: "string" },
813
+ note: { type: "string" },
814
+ },
815
+ required: ["kind", "ref"],
816
+ additionalProperties: false,
817
+ },
818
+ description: "需要核验的产物引用(仅 commit / file)",
819
+ },
820
+ contract: { type: "object", description: "调用方用的契约(warn 档:只留痕不阻断)" },
821
+ },
822
+ additionalProperties: false,
823
+ }),
824
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
825
+ handler: cardEvidenceSubmit,
826
+ },
736
827
  {
737
828
  name: "card_progress",
738
829
  description: "回填进度(写)。**证据必填**(evidence[] 非空,每项 {kind:file|command|url|reading, ref, note?})+ **norm_digest 必填**(card-update 规范的 sha256)。状态走执行侧门:done 只能人点。",
@@ -747,7 +838,7 @@ export const TOOLS = Object.freeze([
747
838
  items: {
748
839
  type: "object",
749
840
  properties: {
750
- kind: { type: "string", enum: ["file", "command", "url", "reading"] },
841
+ kind: { type: "string", enum: [...PROCESS_EVIDENCE_KINDS] },
751
842
  ref: { type: "string" },
752
843
  note: { type: "string" },
753
844
  },