taskboard-workbench 0.3.4 → 0.3.5

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.
@@ -12,6 +12,7 @@ import { EXIT, TbError, invalidField } from "../core/errors.mjs";
12
12
  import { resolveContext } from "../core/binding.mjs";
13
13
  import { scanProjectMaterials, buildMaterialIndex, collectExternalFiles } from "../core/intake.mjs";
14
14
  import { scanAgentTeams, OFFICIAL_TEAM } from "../core/agent-teams.mjs";
15
+ import { BRIDGE_MODE, BRIDGE_POLICY, BRIDGE_POLICY_TITLE, buildCardTaskMap, mapCardToTeamTasks, readPluginTeams, slimPluginTeam } from "../core/team-bridge.mjs";
15
16
  import { buildTeamDirective } from "../host/team-engine.mjs";
16
17
  import { runExecutionLoop, activeEngine } from "../core/loop.mjs";
17
18
  import { assertTeamTemplate, assertQualityGates, planTeamMembers } from "../core/team.mjs";
@@ -44,6 +45,8 @@ import { deriveEmptyState } from "../core/empty-state.mjs";
44
45
  import { buildAdvance, renderAdvanceBlock, applyDecision } from "../core/advance.mjs";
45
46
  import { renderMemoryBlock } from "../core/memory.mjs";
46
47
  import { taskSessionTitle, projectMainSessionTitle } from "../core/session-naming.mjs";
48
+ // 卡 `-264`(R188):派发目标解析 —— 「优先复用已绑定空闲会话,无则新建 + 首次授权」,纯逻辑 + 注入探活。
49
+ import { pickDispatchTarget, buildReuseDirective, buildAuthorizationDirective } from "../core/dispatch-target.mjs";
47
50
  import { collectKickoffFacts, hasEngineerExecutor, hasReviewerRole } from "./kickoff.mjs";
48
51
  import { runVerifyCommand, probeVerifyApplicability } from "./verify.mjs";
49
52
  import { DIAGNOSTIC_KINDS, evaluateTaskDiagnostics, projectDiagnostics, summarizeDiagnostics, resolveSessionRef, humanReviewProbe, humanReviewAnsweredBy } from "../core/diagnostics.mjs";
@@ -52,7 +55,7 @@ import { resolveCliExecutor, executeTaskWithCli, buildTaskPrompt, cliArgsFor, cl
52
55
  // 卡 `-238`(R174):执行者注册表 —— 按卡选「团队 / dsh / claude / codex / hermes」的唯一真源。
53
56
  // 本文件只用它**解析与校验**,参数与「指令怎么给」都由注册表给,路由不另写第二份。
54
57
  import { EXECUTOR_SPECS, EXECUTOR_KINDS, buildExecutorArgs, detectBinary, findExecutorSpec, isExecutorForbidden, listExecutors } from "../core/executors.mjs";
55
- import { DEFAULT_FAILURE_LIMIT } from "../core/store.mjs";
58
+ import { DEFAULT_FAILURE_LIMIT, displayRunSummary } from "../core/store.mjs";
56
59
  // 卡 `-177`(2026-10-29 · 口径 X):acceptance 缺省口径与 MCP **共用同一份**,不在本文件另写判断。
57
60
  import { markAcceptance, acceptanceFlag } from "../core/acceptance.mjs";
58
61
  // P5 档 C(卡 `-210`):开局注入的唯一实现(内容仍由 `buildFlowBlock()` 生成,本文件不复制正文)。
@@ -60,6 +63,41 @@ import { FLOW_INJECT_MANUAL, FLOW_INJECT_ROLES, injectFlow, normalizeFlowInjectP
60
63
 
61
64
  export const API_SCHEMA_VERSION = 2;
62
65
 
66
+ /**
67
+ * 修复动作后**重算诊断**(卡 `-248` · 需求 `R178` ⑤ ·「修复后自动 resolve」)。
68
+ *
69
+ * 诊断是「只增不减」的:规则只在**被评估**时才会重算,而评估只发生在读路径上
70
+ * (`GET /execution` / `GET /diagnostics`)。于是修复动作(重派 / 回收认领 / 请求评审 /
71
+ * 重置失败计数 / 改绑负责人)已经把成因消掉了,却没人重算 ⇒ 那条诊断一直挂着(`count` 还在涨),
72
+ * 人看到的是「我明明修好了,它还在喊」。
73
+ *
74
+ * 这里在**动作落库后立刻重算一次** ⇒ 成因已消的诊断当场消解(FR-79 的「问题消失即自动消解」)。
75
+ * 只重算**这一张卡**,不扫项目;写入走的是 `evaluateTaskDiagnostics`(诊断的唯一写入口)。
76
+ */
77
+ function refreshDiagnosticsAfterFix(store, ref) {
78
+ try { return evaluateTaskDiagnostics(store, ref); } catch { return null; }
79
+ }
80
+
81
+ /**
82
+ * 卡 `-268`(需求 `R184`)· **尝试记录的展示口径**:`summary` 字段不再露记账文案。
83
+ *
84
+ * 写路径(`-259`)只管得住**新行**;库里躺着 **22 行**老口径的「按成功完成记账(失败计数清零)」
85
+ * 与 **7 行**空摘要(真机读数 2026-11-13)⇒ 只修写路径,老卡打开仍是记账文案 —— 正是验收
86
+ * 第 2 条要禁的那句。
87
+ *
88
+ * 这里在**读路径**统一兜一次(`displayRunSummary` 是唯一判据,与 `normalizeRunSummary` 同源):
89
+ * · `summary` = **给人看的**(空 / 纯记账文案 ⇒ 「执行方未回写摘要」;执行方真写了 ⇒ 原样)
90
+ * · `summaryRaw` = **库里原文**(一字不改 —— 改历史 = 篡改过程证据)
91
+ * 在途尝试(`status="running"`)的 `summary` 恒为 null ⇒ **不套回落文案**:把「还在跑」说成
92
+ * 「没回写」是另一种撒谎。
93
+ */
94
+ function withDisplaySummary(run) {
95
+ if (!run) return null;
96
+ const raw = run.summary ?? null;
97
+ const summary = run.status === "running" ? raw : displayRunSummary(raw);
98
+ return { ...run, summary, summaryRaw: raw };
99
+ }
100
+
63
101
  export function httpStatusFor(error) {
64
102
  if (error.code === "STORE_UNAVAILABLE") return 503;
65
103
  if (error.code === "NOT_FOUND" || error.code.endsWith("_NOT_FOUND")) return 404;
@@ -314,12 +352,18 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
314
352
  }
315
353
  let sessionBound = null;
316
354
  let association = null;
355
+ // 卡 `-263`(需求 `R187`):绑定的**来源**与派生依据要说得出 —— 否则「执行会话」在配置页只显示一个
356
+ // 英文 role,用户无法判断它是「批准过的」还是「按任务归属派生的」,更无法知道它什么时候会消失。
357
+ let roleDerived = false;
358
+ let executorTasks = [];
317
359
  if (ctx.project && session) {
318
360
  // 首个进入该项目的会话成为"主会话"(首次绑定不改写)
319
361
  if (!ctx.project.initialSessionId) ctx = { ...ctx, project: store.bindInitialSession(ctx.project.id, session) };
320
362
  const binding = store.sessionBinding(ctx.project.id, session);
321
363
  sessionBound = binding.bound;
322
364
  association = binding.role;
365
+ roleDerived = binding.derived === true;
366
+ executorTasks = Array.isArray(binding.tasks) ? binding.tasks : [];
323
367
  }
324
368
  const mainSessionId = ctx.project ? (store.requireProject(ctx.project.id).initialSessionId ?? null) : null;
325
369
  // FR-84 补口(2026-10-23)· **实例工作区预检**:一个 DSH 实例只有一个工作区(宿主不给切换服务,
@@ -327,7 +371,7 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
327
371
  // 这里把「本会话落哪个工作区」如实交出来(只读探测),前端据此提前告知,不再让用户走
328
372
  // 「重建 → 还是说工作区不对」的弯路。
329
373
  const sessionOrigin = session ? await sessionOriginOf(session, ctx.project ?? null) : null;
330
- return { status: 200, payload: { cwd: cwd ?? null, session: session ?? null, project: ctx.project, requirementDoc: ctx.requirementDoc, sessionBound, mainSessionId, association, sessionOrigin } };
374
+ return { status: 200, payload: { cwd: cwd ?? null, session: session ?? null, project: ctx.project, requirementDoc: ctx.requirementDoc, sessionBound, mainSessionId, association, roleDerived, executorTasks, sessionOrigin } };
331
375
  }
332
376
  if (pathname === "/api/projects") {
333
377
  if (method === "GET") {
@@ -626,6 +670,38 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
626
670
  const thirdParty = await scanAgentTeams(project.workspacePath, { mainSessionId: project.initialSessionId ?? null });
627
671
  return { status: 200, payload: { mainSessionId: project.initialSessionId ?? null, teams: [OFFICIAL_TEAM, ...thirdParty], count: 1 + thirdParty.length } };
628
672
  }
673
+ // 团队任务 ↔ 看板卡映射(卡 `-247` · 需求 `R178` ④):**只读同步器**。
674
+ // 插件侧 `.agent-teams/<team>/team.json` 的任务只有自己的 t-id、没有卡号字段 ⇒ 映射由
675
+ // 「项目自有卡号在团队任务文本里全词命中」推导,附命中字段与片段。
676
+ // **不写 team_tasks、不改 .agent-teams/**(写进去会踩 `team_tasks_active_lock` 把看板卡锁死)。
677
+ const projectTeamBridgeRoute = /^\/api\/projects\/([^/]+)\/team-bridge$/.exec(pathname);
678
+ if (projectTeamBridgeRoute) {
679
+ if (method !== "GET") throw new TbError("USAGE_ERROR", "team-bridge 仅支持 GET(只读同步器)");
680
+ const project = store.requireProject(decodeURIComponent(projectTeamBridgeRoute[1]));
681
+ const teams = await readPluginTeams(project.workspacePath ?? null);
682
+ const cards = store.listTasks({ projectId: project.id }).map((task) => ({
683
+ id: task.id,
684
+ identifier: task.identifier,
685
+ title: task.title,
686
+ status: task.status,
687
+ }));
688
+ const { rows, unmapped, stats } = buildCardTaskMap({ cards, teams });
689
+ return {
690
+ status: 200,
691
+ payload: {
692
+ mode: BRIDGE_MODE,
693
+ policy: BRIDGE_POLICY,
694
+ policyTitle: BRIDGE_POLICY_TITLE,
695
+ projectId: project.id,
696
+ workspacePath: project.workspacePath ?? null,
697
+ mainSessionId: project.initialSessionId ?? null,
698
+ teams: teams.map(slimPluginTeam),
699
+ mappings: rows,
700
+ unmapped,
701
+ stats,
702
+ },
703
+ };
704
+ }
629
705
  const projectSessionsRoute = /^\/api\/projects\/([^/]+)\/sessions$/.exec(pathname);
630
706
  if (projectSessionsRoute) {
631
707
  const project = store.requireProject(decodeURIComponent(projectSessionsRoute[1]));
@@ -636,7 +712,40 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
636
712
  for (const row of rows) sessions.push({ ...row, liveness: await sessionStateOf(row.sessionId) });
637
713
  const mainSessionId = project.initialSessionId ?? null;
638
714
  const main = mainSessionId ? { sessionId: mainSessionId, role: "main", liveness: await sessionStateOf(mainSessionId) } : null;
639
- return { status: 200, payload: { sessions, main, staleMain: Boolean(main && main.liveness.exists === false) } };
715
+ // 卡 `-263`(需求 `R187`)· **执行会话**:按 `tasks.session_id` 聚合的「正在干本项目卡」的会话。
716
+ // 这是**只读派生**行(与上面 `sessions` 的批准记录不同源),所以:
717
+ // · 已经在主会话/批准列表里的,不再重复列(同一会话一行,避免「一处两条」);
718
+ // · 不给「解除」入口 —— 它的生命周期由任务状态决定(done/canceled 自动收回);
719
+ // · 明写 `derived:true`,前端据此标注来源,不要让人误以为是「批准过」。
720
+ const covered = new Set([mainSessionId, ...rows.map((r) => r.sessionId)].filter(Boolean));
721
+ const executors = [];
722
+ for (const ex of store.listExecutorSessions(project.id)) {
723
+ if (covered.has(ex.sessionId)) continue;
724
+ executors.push({ ...ex, derived: true, liveness: await sessionStateOf(ex.sessionId) });
725
+ }
726
+ return { status: 200, payload: { sessions, main, executors, staleMain: Boolean(main && main.liveness.exists === false) } };
727
+ }
728
+ // 卡 `-264`(需求 `R188`)· **派发目标预览**(只读,不建会话、不投递)。
729
+ // 用途:抽屉「下一步」区在点「启动执行」之前就告诉人「这条会交给谁」——
730
+ // reuse ⇒ 复用它(已绑定本项目的空闲会话)
731
+ // create-and-authorize ⇒ 没有可用绑定会话,点了会新建一条并**首次授权**
732
+ // 判据与 `/execute` 共用 `pickDispatchTarget`(**不写第二份**,避免「预览说 A、执行做 B」)。
733
+ const projectDispatchTargetRoute = /^\/api\/projects\/([^/]+)\/dispatch-target$/.exec(pathname);
734
+ if (projectDispatchTargetRoute) {
735
+ if (method !== "GET") throw new TbError("USAGE_ERROR", "dispatch-target 仅支持 GET");
736
+ const project = store.requireProject(decodeURIComponent(projectDispatchTargetRoute[1]));
737
+ const port = store.hostSessionPort;
738
+ if (!port?.available) {
739
+ return {
740
+ status: 200,
741
+ payload: {
742
+ projectId: project.id, decision: "degraded", target: null, candidates: [],
743
+ reason: "host-session-unavailable", hostAvailable: false,
744
+ },
745
+ };
746
+ }
747
+ const picked = await pickDispatchTarget(store, project.id, { sessionStateOf, sessionOriginOf });
748
+ return { status: 200, payload: { projectId: project.id, ...picked, hostAvailable: true } };
640
749
  }
641
750
  // FR-84 补口(2026-10-22)· **本工作区已有会话**候选列表。
642
751
  // 用途:宿主**建会话**能力不可用时(实例未加载宿主 shim → `create()` 抛
@@ -927,8 +1036,23 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
927
1036
  };
928
1037
  });
929
1038
  } catch { diagnostics = []; }
1039
+ // 卡 `-258`(需求 `R184`)· 抽屉「执行记录」聚合段的**唯一数据源**。
1040
+ // 真机(2026-11-12 · 卡 `-248`):结构化四节证据 `task_evidence` 早已写进库(verdict/deviation/
1041
+ // boundary/artifacts 齐全),但它在服务端**只被 `evaluateTaskDiagnostics` 读去判「有没有产物」**,
1042
+ // 从来没有回传给前端 —— 于是人打开一张「待验收」的卡,看不到任何执行记录,只能去翻评论。
1043
+ // 这里把「最近一次结构化证据 + 最近一次尝试」只读回传;**零写副作用**(本端点的不变量)。
1044
+ // 读不到就如实给 null / 0,不臆造(前端据此渲染显式空态)。
1045
+ let executionRun = currentRun;
1046
+ let runsCount = 0;
1047
+ try {
1048
+ const allRuns = typeof store.listTaskRuns === "function" ? store.listTaskRuns(task.identifier) : [];
1049
+ runsCount = Array.isArray(allRuns) ? allRuns.length : 0;
1050
+ if (!executionRun && runsCount > 0) executionRun = allRuns[runsCount - 1];
1051
+ } catch { /* 读失败按「无尝试」处理,不伪造 */ }
1052
+ // 卡 `-268`(需求 `R184`):摘要按**展示口径**回传(不再露记账文案),原文另存 `summaryRaw`。
1053
+ const executionRecord = { evidence, run: withDisplaySummary(executionRun), runsCount };
930
1054
  const stage = ticketStage(task, { evidence, decision: null, comments, sessionState, currentRun, diagnostics });
931
- return { status: 200, payload: { task, comments, reviewEvidence: buildReviewEvidence({ comments }), ticketStage: stage } };
1055
+ return { status: 200, payload: { task, comments, reviewEvidence: buildReviewEvidence({ comments }), ticketStage: stage, executionRecord } };
932
1056
  }
933
1057
  if (method === "PATCH") {
934
1058
  const task = store.updateTask(ref, {
@@ -952,6 +1076,7 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
952
1076
  // 漏带/带字符串一律按"没批准"处理(store 侧严格 `=== true`)⇒ 拖拽/脚本的静默收口必然被拒。
953
1077
  skipReview: body.skipReview,
954
1078
  });
1079
+ refreshDiagnosticsAfterFix(store, task.identifier); // 卡 `-248`:改绑负责人 / 改状态后重算
955
1080
  return { status: 200, payload: { task } };
956
1081
  }
957
1082
  if (method === "DELETE") {
@@ -1294,10 +1419,43 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1294
1419
  // 于是被归因门 / 授权门 / 人工校验门拒绝的点击**照样留下副作用**(多一个空会话 + 视图被切走)。
1295
1420
  // 门序列的唯一来源仍是 store.assertExecutable(startTaskExecution 会再复检一次)。
1296
1421
  store.assertExecutable(ref);
1297
- // 宿主路径:可用则建会话(+尝试预置)并打开;不可用则降级(保留 directive 兜底)。
1422
+ // 卡 `-264`(需求 `R188`):**先解析派发目标**,再决定「复用已绑定空闲会话」还是「新建 + 首次授权」。
1423
+ // 旧行为是「没给 sessionId 就一律新建」—— 每张卡一条孤立会话,项目里空闲的主会话/已批准会话完全没被利用。
1424
+ let dispatch = null; // { decision, target, reason, candidates }
1425
+ let authorization = null; // 新建路径的授权留痕(回包给人看,也方便审计对齐)
1426
+ // 卡 `-272`(需求 `R188` 验收③):**新建路径的任务书是否真的送达**(preset 可能被宿主静默吞掉)。
1427
+ // null(不适用:复用路径 / 降级)· { delivered, via, reason } —— 界面的「已下发」必须以它为准。
1428
+ let bookDelivery = null;
1429
+ if (!sessionId && port?.available) {
1430
+ try {
1431
+ dispatch = await pickDispatchTarget(store, execTask.projectId, { sessionStateOf, sessionOriginOf });
1432
+ } catch (error) {
1433
+ // 解析失败不阻断:如实记一句,走「新建 + 授权」这条保底路(至少不会派给一个不知道状态的会话)。
1434
+ dispatch = { decision: "create-and-authorize", target: null, candidates: [], reason: `resolve-error:${error?.code ?? error?.message ?? error}` };
1435
+ }
1436
+ }
1437
+ // ① 复用路径:只在**判得出空闲**时才走(判不准/跨工作区/在跑 都不选)。
1438
+ if (!sessionId && dispatch?.target?.sessionId) {
1439
+ const target = dispatch.target;
1440
+ let sent = null;
1441
+ let sendReason = null;
1442
+ try { sent = await port.sendPrompt(target.sessionId, buildReuseDirective({ task: execTask, project: store.getProject(execTask.projectId), target })); }
1443
+ catch (error) { sendReason = error?.code ?? String(error?.message ?? error); }
1444
+ if (Boolean(sent?.sent ?? sent?.delivered ?? false)) {
1445
+ sessionId = target.sessionId;
1446
+ reason = null;
1447
+ // 与新建路径同一 UX:把执行会话切到前台(用户刚点了「启动执行」,本来就该看到它在跑)。
1448
+ try { await port.openSession(sessionId); } catch { /* 打开失败不影响派发 */ }
1449
+ } else {
1450
+ // 投递失败 ⇒ **回落新建**(不谎报「已派给空闲会话」),原因如实带回去。
1451
+ reason = `reuse-send-failed:${sendReason ?? sent?.reason ?? "not-delivered"}`;
1452
+ }
1453
+ }
1454
+ // ② 新建路径(没有可用候选 / 复用投递失败):建会话 → **当场授权**(首次授权)→ 任务书带授权段。
1298
1455
  if (!sessionId && port?.available) {
1299
1456
  try {
1300
- const preset = `任务 ${execTask.identifier}:${execTask.title}\n操作指引:认领 → 执行 → 提交"待验收";不得置"完成"(人工确认)。`;
1457
+ const project = store.getProject(execTask.projectId);
1458
+ const preset = buildAuthorizationDirective({ task: execTask, project });
1301
1459
  // 2026-10-23 用户命名约束(口径 1):任务会话统一「【任务】+ 任务标题 + 时间」。
1302
1460
  // 同时补 `cwd`(本仓旧缺漏):不传 cwd 时宿主把会话落在**进程目录**(真机取证到 `cwd="/"`),
1303
1461
  // 正是「接续会话跨工作区错乱」的一个来源。
@@ -1305,6 +1463,8 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1305
1463
  sessionName = taskSessionTitle(execTask.title);
1306
1464
  const created = await port.createSession({
1307
1465
  preset,
1466
+ // 保持与 FR-95-15 守卫同一形状(`cwd: store.getProject(...)?.workspacePath ?? undefined`):
1467
+ // 这是「建会话必须带上项目工作区」的**行内可核对**证据,不要为了少一次读库把它改成变量。
1308
1468
  cwd: store.getProject(execTask.projectId)?.workspacePath ?? undefined,
1309
1469
  title: sessionName,
1310
1470
  // P5 档 C(卡 `-210`):执行会话 ⇒ 只吃「摘要版」(`main-only` 下**不注入**)。
@@ -1316,6 +1476,53 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1316
1476
  presetApplied = Boolean(created.presetApplied);
1317
1477
  titleApplied = created.titleApplied ?? null;
1318
1478
  titleReason = created.titleReason ?? null;
1479
+ // 卡 `-272`(需求 `R188` 验收③)· **任务书必须真的送到**,不能「建了会话就算下发完成」。
1480
+ //
1481
+ // 实测缺口(旧口径必现):宿主 `createSession({preset})` 在 scope 解析不到时(`index.js`
1482
+ // `loadScopeFactory()` 失败 ⇒ preset binding 被拒)**会静静吞掉 preset**,只回
1483
+ // `presetApplied:false` —— 会话建出来了、授权行也写了、回包还是 `create-and-authorize`,
1484
+ // 而**授权指令与任务书一个字都没投进那条会话**,前端照样报「无需再申请关联」。
1485
+ // 这正是 `R188` ③「投递给该会话的任务书里含【授权】/ 不得再申请 / 回写四节」没有兑现。
1486
+ //
1487
+ // 处置:preset 未送达 ⇒ **用 sendPrompt 补投一次同一份任务书**(不是重复投递:preset
1488
+ // 那条路本来就失败了);补投仍失败 ⇒ **如实记账**(审计 + 卡上评论 = 人看得见的地方),
1489
+ // 回包 `launch.authorization.delivered=false` + 原因,界面据此不得谎称「已下发」。
1490
+ let bookDelivered = Boolean(created.presetApplied);
1491
+ let bookVia = bookDelivered ? "preset" : null;
1492
+ let bookReason = bookDelivered ? null : "preset-not-applied";
1493
+ if (!bookDelivered && typeof port.sendPrompt === "function") {
1494
+ let resent = null;
1495
+ try { resent = await port.sendPrompt(sessionId, preset); }
1496
+ catch (error) { bookReason = error?.code ?? String(error?.message ?? error); }
1497
+ if (Boolean(resent?.sent ?? resent?.delivered ?? false)) {
1498
+ bookDelivered = true;
1499
+ bookVia = "send-prompt-fallback";
1500
+ bookReason = null;
1501
+ } else if (resent) {
1502
+ bookReason = resent?.reason ?? bookReason ?? "not-delivered";
1503
+ }
1504
+ }
1505
+ bookDelivery = { delivered: bookDelivered, via: bookVia, reason: bookReason };
1506
+ if (!bookDelivered) {
1507
+ // 两条路(preset / 直投)都失败 ⇒ 人必须能看见「这张卡派下去了,但会话没收到任务书」。
1508
+ try { store.recordAudit({ actor: "board", action: "authorize-exec-deliver", target: execTask.identifier, allowed: false, reason: String(bookReason ?? "not-delivered"), detail: JSON.stringify({ sessionId, projectId: execTask.projectId, via: bookVia }) }); } catch { /* ignore */ }
1509
+ try { store.addComment(execTask.id, { body: `⚠ 执行会话已建并授权,但**任务书未送达**(${bookReason ?? "原因未知"})—— 这条会话不知道自己要做什么。\n- 会话:${sessionId}\n- 已尝试:createSession 的 preset(未生效)+ sendPrompt 补投(未送达)\n- 处置:点「打开执行会话」把本卡任务书手工贴过去,或解决宿主 preset 投递能力(dsh-scope 未解析)后重派` }); } catch { /* ignore */ }
1510
+ }
1511
+ // **新建即授权**:人点「启动执行」就是授权本身(需求 `R188` 的「或」分支)。
1512
+ // 不写这一行,就会退回 `-263` 之前的孤立会话:`project_sessions` 无行,只能靠派生兜底。
1513
+ const auth = store.approveSessionAssociation(execTask.projectId, sessionId);
1514
+ authorization = {
1515
+ mode: "execute-click", projectId: execTask.projectId, sessionId, status: auth.status,
1516
+ // 卡 `-272`:授权「已生效」与「任务书已送达」是两件事 —— 前者写库必然成功,后者靠宿主。
1517
+ // 回包把两者分开给,界面才不会拿「授权成功」冒充「任务书已送达」。
1518
+ delivered: bookDelivery?.delivered ?? null,
1519
+ deliveryVia: bookDelivery?.via ?? null,
1520
+ deliveryReason: bookDelivery?.reason ?? null,
1521
+ };
1522
+ try {
1523
+ store.recordAudit({ actor: "board", action: "authorize-exec-session", target: execTask.identifier, allowed: true, reason: "execute-click", detail: JSON.stringify({ sessionId, projectId: execTask.projectId, pickReason: dispatch?.reason ?? null }) });
1524
+ } catch { /* ignore */ }
1525
+ try { store.recordTaskEvent(execTask.id, { type: "session_authorized", actor: "board", detail: `新建执行会话 ${sessionId} 并首次授权绑定项目 ${execTask.projectId}(execute-click)` }); } catch { /* ignore */ }
1319
1526
  await port.openSession(sessionId);
1320
1527
  } else {
1321
1528
  reason = "session-create-failed";
@@ -1328,10 +1535,23 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1328
1535
  }
1329
1536
  const result = store.startTaskExecution(ref, { sessionId });
1330
1537
  result.launch.presetApplied = presetApplied;
1538
+ // 卡 `-272`(需求 `R188` 验收③):`presetApplied` 是**宿主自述**(preset 有没有生效),
1539
+ // `bookDelivery` 是**任务书到底有没有送达**(preset 被吞 ⇒ 走 `sendPrompt` 补投,补投也失败 ⇒ false)。
1540
+ // 两者分开给:界面判定「已下发」只能看后者,不能拿前者冒充。
1541
+ result.launch.bookDelivery = bookDelivery;
1331
1542
  result.launch.titleApplied = titleApplied;
1332
1543
  if (titleApplied === false) result.launch.titleReason = titleReason;
1333
1544
  result.launch.sessionName = sessionName;
1545
+ // 卡 `-264`:派发决策要可判读 —— 「复用了谁 / 为什么没复用 / 是不是刚授权的」都能从回包读出来。
1546
+ result.launch.mode = sessionId ? (dispatch?.target?.sessionId === sessionId ? "reuse-bound" : (authorization ? "create-and-authorize" : "session")) : "degraded";
1547
+ // 需求 `R188` 验收①点名的字段:`reusedFrom` 说明「这次复用的是哪一类绑定会话」
1548
+ // (`main` 主会话 / `approved` 已批准关联 / `executor` 派生执行会话)。
1549
+ // 非复用路径一律给 `null`(**键恒在**):调用方不必区分「没这个字段」与「不是复用」。
1550
+ result.launch.reusedFrom = result.launch.mode === "reuse-bound" ? (dispatch?.target?.kind ?? null) : null;
1551
+ result.launch.dispatch = dispatch ? { decision: dispatch.decision, reason: dispatch.reason, target: dispatch.target, candidates: dispatch.candidates } : null;
1552
+ if (authorization) result.launch.authorization = authorization;
1334
1553
  if (!sessionId) result.launch.reason = reason ?? "host-session-unavailable";
1554
+ else if (reason) result.launch.fallbackReason = reason;
1335
1555
  emit("task.updated", { taskId: result.task.id, identifier: result.task.identifier, status: result.task.status });
1336
1556
  return { status: 200, payload: result };
1337
1557
  }
@@ -1362,7 +1582,14 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1362
1582
  ? { sessionId: mainId, liveness: await sessionStateOf(mainId), origin: await sessionOriginOf(mainId, proj) }
1363
1583
  : null;
1364
1584
  }
1365
- return { status: 200, payload: { ...store.getTaskExecution(ref), claim: store.taskClaimState(ref), watchdog: assessTaskRef(store, ref), diagnostics: diag.diagnostics, diagnosticSummary: diag.summary, runs: store.listTaskRuns(ref), sessionRef } };
1585
+ // 卡 `-264`(需求 `R188`)· **派发目标预览**:抽屉点「启动执行」前先告诉人「会交给谁」。
1586
+ // 只在「还能派」的状态下算(in_review/done/canceled 不派发),且每候选要探活 ⇒ 不做无用功。
1587
+ let dispatchTarget = null;
1588
+ if (["todo", "blocked", "in_progress"].includes(diag.task.status) && store.hostSessionPort?.available) {
1589
+ try { dispatchTarget = await pickDispatchTarget(store, diag.task.projectId, { sessionStateOf, sessionOriginOf }); }
1590
+ catch (error) { dispatchTarget = { decision: "create-and-authorize", target: null, candidates: [], reason: `resolve-error:${error?.code ?? error?.message ?? error}` }; }
1591
+ }
1592
+ return { status: 200, payload: { ...store.getTaskExecution(ref), claim: store.taskClaimState(ref), watchdog: assessTaskRef(store, ref), diagnostics: diag.diagnostics, diagnosticSummary: diag.summary, runs: store.listTaskRuns(ref).map(withDisplaySummary), sessionRef, dispatchTarget } };
1366
1593
  }
1367
1594
  // FR-82:尝试记录(每次认领执行一条:状态/结果/摘要/错误/起止/心跳/运行时上限)
1368
1595
  const taskRunsRoute = /^\/api\/tasks\/([^/]+)\/runs$/.exec(pathname);
@@ -1370,7 +1597,7 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1370
1597
  if (method !== "GET") throw new TbError("USAGE_ERROR", "runs 仅支持 GET");
1371
1598
  const task = store.requireTaskRef(decodeURIComponent(taskRunsRoute[1]));
1372
1599
  const runs = store.listTaskRuns(task);
1373
- return { status: 200, payload: { identifier: task.identifier, count: runs.length, currentRun: store.getCurrentRun(task), runs } };
1600
+ return { status: 200, payload: { identifier: task.identifier, count: runs.length, currentRun: withDisplaySummary(store.getCurrentRun(task)), runs: runs.map(withDisplaySummary) } };
1374
1601
  }
1375
1602
  // FR-82:任务事件流(追加式;`since` = 已见游标,返回增量)
1376
1603
  const taskEventsRoute = /^\/api\/tasks\/([^/]+)\/events$/.exec(pathname);
@@ -1433,6 +1660,7 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1433
1660
  if (taskResetFailuresRoute) {
1434
1661
  if (method !== "POST") throw new TbError("USAGE_ERROR", "reset-failures 仅支持 POST");
1435
1662
  const task = store.resetTaskFailures(decodeURIComponent(taskResetFailuresRoute[1]));
1663
+ refreshDiagnosticsAfterFix(store, task.identifier); // 卡 `-248`:重置失败计数后重算(`repeated_failure` 消解)
1436
1664
  emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
1437
1665
  return { status: 200, payload: { task, guard: store.dispatchGuard(task) } };
1438
1666
  }
@@ -1451,6 +1679,7 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1451
1679
  const ref = decodeURIComponent(taskReclaimRoute[1]);
1452
1680
  const r = store.reclaimStaleClaim(ref);
1453
1681
  if (r.reclaimed) {
1682
+ refreshDiagnosticsAfterFix(store, ref); // 卡 `-248`:回收认领后重算(`unclaimed` 消解)
1454
1683
  const t = store.getTaskById(store.requireTaskRef(ref).id);
1455
1684
  emit("task.updated", { taskId: t.id, identifier: t.identifier, status: t.status });
1456
1685
  }
@@ -1786,11 +2015,31 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1786
2015
  const directive = buildTeamDirective({ teamId: run.id, targetTask: task.identifier, targetRequirement: task.requirementId, members: members.map((m) => m.role), tasks: [{ task: task.identifier, subject: task.title }], qualityGates }, engine);
1787
2016
  return { run, members, tasks, directive };
1788
2017
  }).filter((e) => e.members.length > 0 || e.tasks.length > 0); // 跳过空 run,避免详情显示"空团队"掩盖真实反馈
2018
+ // 卡 `-247`(需求 `R178` ④):**团队侧反查** —— 这张卡在承载环境 agent-team 插件那边是哪个 t-id。
2019
+ // 只读同步:读工作区 `.agent-teams/<team>/team.json`,不写 team_tasks、不改插件产物。
2020
+ // 命中不到 ⇒ 如实给「看板只展示、不参与团队状态」的明文声明(不臆断"没有团队在跑")。
2021
+ let bridge = null;
2022
+ try {
2023
+ const project = store.requireProject(task.projectId);
2024
+ const pluginTeams = await readPluginTeams(project.workspacePath ?? null);
2025
+ const bridgeRows = mapCardToTeamTasks(task.identifier, pluginTeams);
2026
+ bridge = {
2027
+ mode: BRIDGE_MODE,
2028
+ policy: BRIDGE_POLICY,
2029
+ policyTitle: BRIDGE_POLICY_TITLE,
2030
+ workspacePath: project.workspacePath ?? null,
2031
+ pluginTeamCount: pluginTeams.length,
2032
+ mapped: bridgeRows.length > 0,
2033
+ rows: bridgeRows,
2034
+ };
2035
+ } catch {
2036
+ bridge = { mode: BRIDGE_MODE, policy: BRIDGE_POLICY, policyTitle: BRIDGE_POLICY_TITLE, workspacePath: null, pluginTeamCount: 0, mapped: false, rows: [] };
2037
+ }
1789
2038
  return {
1790
2039
  status: 200,
1791
2040
  payload: {
1792
2041
  task: { id: task.id, identifier: task.identifier, title: task.title, status: task.status, sessionId: task.sessionId ?? null },
1793
- engine, teams, count: teams.length, lock: store.getTaskLock(ref),
2042
+ engine, teams, count: teams.length, lock: store.getTaskLock(ref), bridge,
1794
2043
  },
1795
2044
  };
1796
2045
  }
@@ -1800,9 +2049,10 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1800
2049
  const ref = decodeURIComponent(taskExecActionRoute[1]);
1801
2050
  const action = taskExecActionRoute[2];
1802
2051
  const task = action === "fail" ? store.recordTaskExecutionFailure(ref, { evidence: body.evidence, kind: body.kind })
1803
- : action === "review" ? store.submitTaskForReview(ref, { comment: body.comment })
2052
+ : action === "review" ? store.submitTaskForReview(ref, { comment: body.comment, summary: body.summary })
1804
2053
  : action === "retry" ? store.retryTaskExecution(ref)
1805
2054
  : store.releaseTaskAssignment(ref);
2055
+ refreshDiagnosticsAfterFix(store, task.identifier); // 卡 `-248`:修复动作后重算 ⇒ 该消的诊断当场消解
1806
2056
  emit("task.updated", { taskId: task.id, identifier: task.identifier, status: task.status });
1807
2057
  return { status: 200, payload: { task } };
1808
2058
  }
@@ -1825,11 +2075,12 @@ export function createApiRouter({ store, aiElaborator, events, executorProbe = d
1825
2075
  }
1826
2076
  if (method !== "POST") throw new TbError("USAGE_ERROR", "review 仅支持 GET / POST");
1827
2077
  const action = String(body.action ?? "request");
1828
- const result = action === "request" ? store.requestReview(ref, { reviewer: body.reviewer ?? null, dependsOn: body.dependsOn ?? null, comment: body.comment ?? "", actor: body.actor ?? "human" })
2078
+ const result = action === "request" ? store.requestReview(ref, { reviewer: body.reviewer ?? null, dependsOn: body.dependsOn ?? null, comment: body.comment ?? "", summary: body.summary ?? null, actor: body.actor ?? "human" })
1829
2079
  : action === "changes" ? store.requestChanges(ref, { comment: body.comment ?? "", actor: body.actor ?? "reviewer" })
1830
2080
  : action === "approve" ? store.approveReview(ref, { comment: body.comment ?? "", actor: body.actor ?? "reviewer" })
1831
2081
  : null;
1832
2082
  if (!result) throw invalidField("action", "action 只支持 request / changes / approve");
2083
+ refreshDiagnosticsAfterFix(store, result.task.identifier); // 卡 `-248`:指派评审者后重算(`review_deadlock` 消解)
1833
2084
  emit("task.updated", { taskId: result.task.id, identifier: result.task.identifier, status: result.task.status });
1834
2085
  return { status: 200, payload: result };
1835
2086
  }