taskboard-workbench 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,12 @@
1
1
  /**
2
2
  * api.mjs —— 纯路由逻辑(不依赖 node:http)。独立服务与 DSH 宿主插件共用。
3
3
  */
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+
4
7
  import { PRIORITIES, STATUSES } from "../core/domain.mjs";
8
+ import { materializeProjectNorms, normsView } from "../core/norms.mjs";
9
+ import { docsView, materializeProjectDocs, readDocFile } from "../core/docs-assets.mjs";
5
10
  import { clampElaborateLimit } from "../core/requirements.mjs";
6
11
  import { EXIT, TbError, invalidField } from "../core/errors.mjs";
7
12
  import { resolveContext } from "../core/binding.mjs";
@@ -21,12 +26,17 @@ import { deriveNextStep } from "../core/next-step.mjs";
21
26
  * 真实情况:独立进程实例(`node src/server/server.mjs`,没有 DSH 宿主)的 `host.capabilities` 恒为 `null`,
22
27
  * 这类动作在该进程上**做不到**,正确出路是"换到 DSH 内的任务工作台"或"把 prompt 粘到会话里手工投递"。
23
28
  */
29
+ /** 随包机器规范目录(`package.json#files` 含 `spec/norms`);项目副本在 `<工作区>/.taskboard/norms/`。 */
30
+ const PACKAGED_NORMS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../spec/norms");
31
+ /** 随包**人读**文档目录(`package.json#files` 含 `spec/docs`);项目副本默认在 `<工作区>/.taskboard/docs/`。 */
32
+ const PACKAGED_DOCS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../spec/docs");
33
+
24
34
  const HOST_UNAVAILABLE_NEXT = "该实例没有宿主会话通道(独立进程,/api/health 的 host.capabilities 为 null):改到 DSH 内的任务工作台操作,或把返回的 prompt 直接粘到会话里手工投递";
25
35
 
26
36
  import { buildDebugDispatchPrompt } from "../core/debug-dispatch.mjs";
27
37
  import { buildSplitAskPrompt } from "../core/split-ask.mjs";
28
38
  import { buildReviewEvidence, formatVerifyComment, normalizeVerifyCommand, summarizeVerifyOutput, VERIFY_DEFAULT_COMMAND } from "../core/verify.mjs";
29
- import { evaluateKickoff } from "../core/kickoff.mjs";
39
+ import { buildGapPrompt, buildKickoffTodos, collectGaps, evaluateKickoff } from "../core/kickoff.mjs";
30
40
  import { deriveEmptyState } from "../core/empty-state.mjs";
31
41
  // 2026-10-28 拍板 E1–E3 / D-M1–D-M5:项目推进清单(纯投影 + 幂等回写)与项目记忆(L2 条目 + L3 召回)。
32
42
  import { buildAdvance, renderAdvanceBlock, applyDecision } from "../core/advance.mjs";
@@ -40,6 +50,8 @@ import { resolveCliExecutor, executeTaskWithCli, buildTaskPrompt, cliArgsFor, cl
40
50
  import { DEFAULT_FAILURE_LIMIT } from "../core/store.mjs";
41
51
  // 卡 `-177`(2026-10-29 · 口径 X):acceptance 缺省口径与 MCP **共用同一份**,不在本文件另写判断。
42
52
  import { markAcceptance, acceptanceFlag } from "../core/acceptance.mjs";
53
+ // P5 档 C(卡 `-210`):开局注入的唯一实现(内容仍由 `buildFlowBlock()` 生成,本文件不复制正文)。
54
+ import { FLOW_INJECT_MANUAL, FLOW_INJECT_ROLES, injectFlow, normalizeFlowInjectPolicy } from "../core/flow-inject.mjs";
43
55
 
44
56
  export const API_SCHEMA_VERSION = 2;
45
57
 
@@ -330,6 +342,59 @@ export function createApiRouter({ store, aiElaborator, events } = {}) {
330
342
  });
331
343
  return { status: 200, payload: { project: project.id, workspacePath: project.workspacePath ?? null, readable: facts.readable, ...report } };
332
344
  }
345
+ // 卡 `-229`(需求 R170):配置页「引入主对话」—— 把**当前实时缺口**投给项目主会话。
346
+ // 与上方 GET /kickoff 严格分离:GET 只读(注释见上,绝不写任何数据);本路由只做「现算缺口 + 投递 + 审计」,
347
+ // 同样**不改任何完成度数据**。缺口由 collectGaps(evaluateKickoff(...)) 投影 ⇒ 完成度真源仍只有 evaluateKickoff。
348
+ const projectKickoffAnnounceRoute = /^\/api\/projects\/([^/]+)\/kickoff\/announce$/.exec(pathname);
349
+ if (projectKickoffAnnounceRoute) {
350
+ if (method !== "POST") throw new TbError("USAGE_ERROR", "kickoff/announce 仅支持 POST");
351
+ const project = store.requireProject(decodeURIComponent(projectKickoffAnnounceRoute[1]));
352
+ // 每次现算(与 GET /kickoff 同一份自检数据源),保证「投出去的条目数 = 配置页未完成项数」。
353
+ const settings = store.getProjectSettings(project.id);
354
+ const facts = collectKickoffFacts(project.workspacePath ?? null);
355
+ const report = evaluateKickoff({
356
+ files: facts.files,
357
+ settings,
358
+ custom: { reviewerRole: hasReviewerRole(settings?.teamTemplate), engineerExecutor: hasEngineerExecutor(settings?.teamTemplate) },
359
+ });
360
+ const gaps = collectGaps(report);
361
+ // 卡 `-230`:同一次聚合出**结构化 todolist**(一步一条、依赖顺序、每条带可执行判据)。
362
+ const todos = buildKickoffTodos({ project, gaps });
363
+ // 卡 `t20`(需求 `R170`):缺口注入必须带「关联需求」—— 否则执行侧建的卡会被归因门拒(EXECUTION_NOT_ATTRIBUTED)。
364
+ // 候选只取**本项目未关闭**的条目:已关闭的条目建出来的卡同样过不了归因门(等价于未归属)。
365
+ const requirements = store
366
+ .listRequirementItems({ projectId: project.id })
367
+ .filter((it) => it.status !== "closed")
368
+ .map((it) => ({ identifier: it.identifier, title: it.title }));
369
+ // 显式指定的那条要**先校验再拼正文**:不存在的引用不得静默降级成「未指定」(那会建出一堆无归属的卡)。
370
+ let requirement = null;
371
+ const requirementRef = body.requirement == null ? "" : String(body.requirement).trim();
372
+ if (requirementRef !== "") {
373
+ // 卡 `-234`:本路由一定知道项目 ⇒ 简写 `R170` 按本项目解析。
374
+ const item = store.requireRequirementItemRef(requirementRef, { projectId: project.id }); // 不存在 ⇒ REQUIREMENT_NOT_FOUND
375
+ if (item.projectId !== project.id) {
376
+ throw new TbError("REQUIREMENT_NOT_FOUND", `需求条目不属于本项目:${requirementRef}`, { ref: requirementRef, projectId: project.id });
377
+ }
378
+ requirement = { identifier: item.identifier, title: item.title };
379
+ }
380
+ const prompt = buildGapPrompt({ project, gaps, todos, requirement, requirements });
381
+ const summary = { step: gaps.step, done: gaps.done, total: gaps.total, count: gaps.items.length, todos: todos.length };
382
+ const sid = body.sessionId ? String(body.sessionId) : (project.initialSessionId ?? null);
383
+ if (!sid) throw new TbError("NO_MAIN_SESSION", "该项目还没有主会话:先在开局流程绑主会话,或用 body.sessionId 指定", { projectId: project.id, gaps: summary, todos, prompt, requirement, requirements });
384
+ const hostPort = store.hostSessionPort;
385
+ if (!hostPort || typeof hostPort.sendPrompt !== "function") {
386
+ // 与本文件 split-ask 同口径:投不进去也要给人能做的事 —— 正文原样回带(前端据此降级,不得谎称已投递)。
387
+ // 新增 host-unavailable 投递点须同步校准 `tests/host-gate.test.mjs` 的计数(守卫按该字面量出现次数钉住)。
388
+ return { status: 200, payload: { project: project.id, sessionId: sid, delivered: false, reason: "host-unavailable", hostCapabilities: null, nextAction: HOST_UNAVAILABLE_NEXT, gaps: summary, todos, prompt, requirement, requirements, block: prompt } };
389
+ }
390
+ let sent = null;
391
+ try { sent = await hostPort.sendPrompt(sid, prompt); } catch (e) { sent = { sent: false, reason: e?.message ?? "error" }; }
392
+ const delivered = Boolean(sent?.sent ?? sent?.delivered);
393
+ try {
394
+ store.recordAudit({ actor: body.actor ?? "board", action: "kickoff-announce", target: project.id, allowed: delivered, reason: delivered ? "delivered" : (sent?.reason ?? "delivery-failed"), detail: `session=${sid} gaps=${gaps.items.length} checks=${gaps.done}/${gaps.total} steps=${gaps.step}` });
395
+ } catch { /* 审计失败不阻断投递结论(投递已生效时谎报失败会诱发重复注入) */ }
396
+ return { status: 200, payload: { project: project.id, sessionId: sid, delivered, reason: delivered ? null : (sent?.reason ?? "delivery-failed"), gaps: summary, todos, prompt, requirement, requirements, block: prompt } };
397
+ }
333
398
  // 项目设置(FR-56):项目环境约束 + agent 执行团队模板
334
399
  const projectSettingsRoute = /^\/api\/projects\/([^/]+)\/settings$/.exec(pathname);
335
400
  if (projectSettingsRoute) {
@@ -346,11 +411,146 @@ export function createApiRouter({ store, aiElaborator, events } = {}) {
346
411
  if (roles.length) assertTeamTemplate({ roles, qualityGates: tpl?.qualityGates });
347
412
  else assertQualityGates({ qualityGates: tpl?.qualityGates });
348
413
  }
349
- const saved = store.saveProjectSettings(project.id, { envConfig: body.envConfig, teamTemplate: body.teamTemplate, loop: body.loop });
414
+ // P5 档 C(卡 `-210`):`flowInjectPolicy` 是**切换注入行为**的配置 ⇒ 写前校验(非法值不落库)。
415
+ // 未传 = 保持不变(老前端 / 只改 envConfig 的调用方零影响)。
416
+ let flowInjectPolicy;
417
+ if (body.flowInjectPolicy !== undefined) flowInjectPolicy = normalizeFlowInjectPolicy(body.flowInjectPolicy, { strict: true });
418
+ const saved = store.saveProjectSettings(project.id, { envConfig: body.envConfig, teamTemplate: body.teamTemplate, loop: body.loop, flowInjectPolicy });
350
419
  return { status: 200, payload: saved };
351
420
  }
352
421
  throw new TbError("USAGE_ERROR", "settings 仅支持 GET 或 PUT");
353
422
  }
423
+ // 开局注入(P5 档 C · 卡 `-210`):档 C 的**人工出口**(`tb-flow inject --session`)+ 审计查询。
424
+ // 内容与自动注入**共用** `src/core/flow-inject.mjs`(同一个 `buildFlowBlock()`)—— 本文件不复制正文。
425
+ const projectFlowRoute = /^\/api\/projects\/([^/]+)\/flow\/(inject|injections)$/.exec(pathname);
426
+ if (projectFlowRoute) {
427
+ const project = store.requireProject(decodeURIComponent(projectFlowRoute[1]));
428
+ const action = projectFlowRoute[2];
429
+ const configuredPolicy = store.getProjectSettings(project.id).flowInjectPolicy ?? "off";
430
+ if (action === "injections") {
431
+ if (method !== "GET") throw new TbError("USAGE_ERROR", "flow/injections 仅支持 GET");
432
+ const rows = store.listFlowInjections({ projectId: project.id, sessionId: searchParams.get("sessionId") ?? undefined });
433
+ return { status: 200, payload: { projectId: project.id, policy: configuredPolicy, injections: rows } };
434
+ }
435
+ if (method !== "POST") throw new TbError("USAGE_ERROR", "flow/inject 仅支持 POST");
436
+ const sessionId = String(body.sessionId ?? "").trim();
437
+ if (!sessionId) throw new TbError("USAGE_ERROR", "缺 sessionId:要投进哪个会话(tb-flow inject --session <id>)");
438
+ // 角色:显式优先;不传就按「是不是项目主会话」推(推错只会少注,不会把完整版塞进执行会话)。
439
+ const role = body.role === undefined || body.role === null || String(body.role).trim() === ""
440
+ ? (sessionId === project.initialSessionId ? "main" : "exec")
441
+ : String(body.role).trim();
442
+ if (!FLOW_INJECT_ROLES.includes(role)) {
443
+ throw new TbError("USAGE_ERROR", `role 只能是 ${FLOW_INJECT_ROLES.join(" / ")}`, { role });
444
+ }
445
+ const port = store.hostSessionPort;
446
+ // 人工一次性投递:审计记 `manual`(显式绕过 `off`,但**子 agent 仍不注入** —— 硬规则不因人工放开)。
447
+ const result = await injectFlow({
448
+ store,
449
+ deliver: (sid, text) => (port && typeof port.sendPrompt === "function"
450
+ ? port.sendPrompt(sid, text)
451
+ : Promise.resolve({ sent: false, reason: "host-unavailable" })),
452
+ projectId: project.id,
453
+ sessionId,
454
+ role,
455
+ policy: FLOW_INJECT_MANUAL,
456
+ source: body.source ?? "api",
457
+ });
458
+ if (!result.injected) {
459
+ return { status: 200, payload: {
460
+ delivered: false, sessionId, role, policy: result.policy, reason: result.reason,
461
+ nextAction: result.reason === "host-unavailable" ? HOST_UNAVAILABLE_NEXT : null,
462
+ // 投不进去也要给出人能做的事:正文原样回带,手工粘贴即可(与本文件 split-ask 同口径)。
463
+ prompt: result.text ?? null, digest: result.digest ?? null, chars: result.chars ?? 0,
464
+ } };
465
+ }
466
+ try {
467
+ store.recordAudit({
468
+ actor: "board", action: "flow-inject", target: project.id, allowed: true, reason: role,
469
+ detail: JSON.stringify({ sessionId, policy: result.policy, version: result.version, digest: result.digest, chars: result.chars, source: result.source }),
470
+ });
471
+ } catch { /* 审计失败不影响投递结论(投递已生效,谎报失败会诱发重复注入) */ }
472
+ return { status: 200, payload: {
473
+ delivered: true, sessionId, role, policy: result.policy, version: result.version,
474
+ contractVersion: result.contractVersion, digest: result.digest, chars: result.chars,
475
+ injection: {
476
+ id: result.injectionId, projectId: project.id, sessionId, policy: result.policy,
477
+ contractVersion: result.contractVersion, digest: result.digest, injectedAt: result.injectedAt,
478
+ },
479
+ auditRecorded: result.auditRecorded, source: result.source,
480
+ } };
481
+ }
482
+ // 项目级机器规范(卡 `-216` / 需求 `R160`):看板到底读的是哪份、要不要生成 / 恢复副本。
483
+ const projectNormsRoute = /^\/api\/projects\/([^/]+)\/norms$/.exec(pathname);
484
+ if (projectNormsRoute) {
485
+ const project = store.requireProject(decodeURIComponent(projectNormsRoute[1]));
486
+ const workspacePath = project.workspacePath ?? null;
487
+ if (method === "GET") {
488
+ return { status: 200, payload: normsView({ packagedDir: PACKAGED_NORMS_DIR, workspacePath }) };
489
+ }
490
+ if (method === "POST") {
491
+ const action = String(body.action ?? "materialize");
492
+ if (action !== "materialize" && action !== "reset") throw new TbError("USAGE_ERROR", "action 只支持 materialize / reset");
493
+ const out = materializeProjectNorms({ packagedDir: PACKAGED_NORMS_DIR, workspacePath, overwrite: action === "reset" });
494
+ try {
495
+ store.recordAudit({
496
+ actor: body.actor ?? "human", action: `norms-${action}`, target: project.id, allowed: true,
497
+ reason: out.dir, detail: JSON.stringify({ written: out.written, kept: out.kept }),
498
+ });
499
+ } catch { /* 审计失败不影响复制结果 */ }
500
+ return { status: 200, payload: { ...out, view: normsView({ packagedDir: PACKAGED_NORMS_DIR, workspacePath }) } };
501
+ }
502
+ throw new TbError("USAGE_ERROR", "norms 仅支持 GET 或 POST(POST body.action = materialize | reset)");
503
+ }
504
+ // 项目级**人读**文档位置(卡 `-220` / 需求 `R161`):包内默认 / 项目存放 / 生效来源 —— 可查、可看、可改。
505
+ // 与 `norms` 分开:这里改文档**不影响契约**(契约只吃 `spec/norms/`),所以别做成同一张卡。
506
+ const projectDocsRoute = /^\/api\/projects\/([^/]+)\/docs$/.exec(pathname);
507
+ if (projectDocsRoute) {
508
+ const project = store.requireProject(decodeURIComponent(projectDocsRoute[1]));
509
+ const workspacePath = project.workspacePath ?? null;
510
+ const overrideDir = store.getProjectSettings(project.id)?.envConfig?.docsDir ?? null;
511
+ const view = () => docsView({ packagedDir: PACKAGED_DOCS_DIR, workspacePath, overrideDir });
512
+ if (method === "GET") {
513
+ const file = searchParams.get("file");
514
+ // ?file= 只读「看一眼」:路径按**生效目录**解析(有副本读副本,没有读包内)。
515
+ if (file) {
516
+ const cur = view();
517
+ return { status: 200, payload: { ...readDocFile(cur.effective.dir, file), source: cur.effective.source, dir: cur.effective.dir } };
518
+ }
519
+ return { status: 200, payload: view() };
520
+ }
521
+ if (method === "POST") {
522
+ const action = String(body.action ?? "materialize");
523
+ if (action !== "materialize" && action !== "reset") throw new TbError("USAGE_ERROR", "action 只支持 materialize / reset");
524
+ const out = materializeProjectDocs({ packagedDir: PACKAGED_DOCS_DIR, workspacePath, overrideDir, overwrite: action === "reset" });
525
+ try {
526
+ store.recordAudit({
527
+ actor: body.actor ?? "human", action: `docs-${action}`, target: project.id, allowed: true,
528
+ reason: out.dir, detail: JSON.stringify({ written: out.written, kept: out.kept }),
529
+ });
530
+ } catch { /* 审计失败不影响复制结果 */ }
531
+ return { status: 200, payload: { ...out, view: view() } };
532
+ }
533
+ if (method === "PUT") {
534
+ // 改存放位置:空 / null ⇒ 恢复默认(删 docsDir 键,不留空串歧义)。
535
+ const next = body.dir;
536
+ if (next !== undefined && next !== null && typeof next !== "string") throw new TbError("USAGE_ERROR", "dir 必须是字符串或 null");
537
+ const current = store.getProjectSettings(project.id).envConfig ?? {};
538
+ const envConfig = { ...current };
539
+ if (next === undefined || next === null || String(next).trim() === "") delete envConfig.docsDir;
540
+ else envConfig.docsDir = String(next).trim();
541
+ // 写前先解析一遍:相对路径无工作区时会抛 WORKSPACE_MISSING —— 在写库**之前**拦,避免存进一个用不了的配置。
542
+ const after = docsView({ packagedDir: PACKAGED_DOCS_DIR, workspacePath, overrideDir: envConfig.docsDir ?? null });
543
+ store.saveProjectSettings(project.id, { envConfig });
544
+ try {
545
+ store.recordAudit({
546
+ actor: body.actor ?? "human", action: "docs-set-dir", target: project.id, allowed: true,
547
+ reason: after.project.dir, detail: JSON.stringify({ override: envConfig.docsDir ?? null, isDefault: !envConfig.docsDir }),
548
+ });
549
+ } catch { /* 审计失败不影响保存 */ }
550
+ return { status: 200, payload: docsView({ packagedDir: PACKAGED_DOCS_DIR, workspacePath, overrideDir: envConfig.docsDir ?? null }) };
551
+ }
552
+ throw new TbError("USAGE_ERROR", "docs 仅支持 GET / POST(materialize|reset) / PUT(dir)");
553
+ }
354
554
  // 会话 ↔ 项目关联(FR-63):列出 / 申请 / 批准
355
555
  const projectAgentTeamsRoute = /^\/api\/projects\/([^/]+)\/agent-teams$/.exec(pathname);
356
556
  if (projectAgentTeamsRoute) {
@@ -466,6 +666,9 @@ export function createApiRouter({ store, aiElaborator, events } = {}) {
466
666
  const created = await port.createSession({
467
667
  cwd: project.workspacePath ?? undefined,
468
668
  title: mainSessionName,
669
+ // P5 档 C(卡 `-210`):声明角色 —— 只有 `main` 才吃「完整版装载块」。
670
+ role: "main",
671
+ projectId: project.id,
469
672
  });
470
673
  const sessionId = created?.sessionId ?? null;
471
674
  if (!sessionId) throw new TbError("SESSION_CREATE_FAILED", "宿主未能创建会话", { reason: created?.reason ?? null });
@@ -1006,6 +1209,9 @@ export function createApiRouter({ store, aiElaborator, events } = {}) {
1006
1209
  preset,
1007
1210
  cwd: store.getProject(execTask.projectId)?.workspacePath ?? undefined,
1008
1211
  title: sessionName,
1212
+ // P5 档 C(卡 `-210`):执行会话 ⇒ 只吃「摘要版」(`main-only` 下**不注入**)。
1213
+ role: "exec",
1214
+ projectId: execTask.projectId,
1009
1215
  });
1010
1216
  if (created?.sessionId) {
1011
1217
  sessionId = created.sessionId;