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.
@@ -0,0 +1,274 @@
1
+ /**
2
+ * team-bridge.mjs —— 团队任务 ↔ 看板卡映射(**只读同步器** · 卡 `-247` / 需求 `R178` ④)。
3
+ *
4
+ * ## 背景:两套系统零桥接
5
+ *
6
+ * | 侧 | 真源 | 与看板卡的关联 |
7
+ * | --- | --- | --- |
8
+ * | 工作台本地 | `team_runs` / `team_members` / `team_tasks`(`POST /api/teams/:id/tasks` 写入) | `team_tasks.task_id → tasks.id`,**真外键** |
9
+ * | 承载环境 agent-team 插件 | 工作区 `.agent-teams/<team>/team.json`(插件写) | **无字段**:插件任务只有自己的 `t1/t2/…` |
10
+ *
11
+ * 真机读数(2026-11-12 · `R178` ④):`team_tasks` 18 行全是 10 月旧队,`scada-vibe` 项目 **0 行**;
12
+ * 插件侧 `scada-vibe-squad` 8 条团队任务在跑,但看板侧查不到任何 t-id —— 两套系统平行。
13
+ *
14
+ * ## 口径(方案二 + 方案三兜底)
15
+ *
16
+ * 插件侧任务与看板卡的关联**只存在于文本里**(任务描述 / 产出 / 验收结果里出现卡号),
17
+ * 插件**没有**卡号字段 ⇒ 本模块用「**项目自有卡号全词命中**」推导,并**保留证据**(命中字段 + 片段)。
18
+ *
19
+ * - 命中 ⇒ 该卡可反查团队侧 `t-id`;
20
+ * - 未命中 ⇒ **明文声明**「看板只展示、不参与团队状态」(不是"查不到就是没有",是明说边界)。
21
+ *
22
+ * ## 只读纪律(硬约束)
23
+ *
24
+ * - **不写 `team_tasks`**:那张表上有 `team_tasks_active_lock`(同一卡只允许一个活跃团队任务),
25
+ * 把插件团队写进去会让看板侧的合法派发被 `TASK_LOCKED` 挡死 ⇒ 写库方案天然带这个雷。
26
+ * - **不改 `.agent-teams/**`**:那是宿主插件的产物(卡面「不改宿主插件」)。
27
+ * - **不改 schema、不动历史数据**。
28
+ * - 推导结果**不入库**,每次请求现读现算 ⇒ 没有第二份真源,也就没有漂移。
29
+ *
30
+ * 本模块**刻意不复用** `src/core/agent-teams.mjs` 的扫描器:那个只返回团队摘要(成员数 / 任务数),
31
+ * 本模块要任务全文;改它会给既有 `GET /api/projects/:id/agent-teams` 带来回归风险。
32
+ */
33
+
34
+ import { readdir, readFile } from "node:fs/promises";
35
+ import { join } from "node:path";
36
+
37
+ /** 映射口径标识(回包里如实带出,别让人以为这是真外键)。 */
38
+ export const BRIDGE_MODE = "read-only-sync";
39
+
40
+ /** 明文声明(卡面「或明文声明『看板只展示不参与状态』」的落点;未命中映射时逐字展示)。 */
41
+ export const BRIDGE_POLICY_TITLE = "看板只展示、不参与团队状态";
42
+
43
+ export const BRIDGE_POLICY = [
44
+ "两套系统并列:工作台本地(team_runs/team_members/team_tasks)与承载环境 agent-team 插件(工作区 .agent-teams/<team>/team.json)**各自记账、互不驱动**。",
45
+ `本映射是**只读推导**(${BRIDGE_MODE}):插件侧任务没有卡号字段,映射由「项目自有卡号在团队任务文本里全词命中」得出,并附命中字段与片段。`,
46
+ `未命中映射的卡:${BRIDGE_POLICY_TITLE} —— 看板侧状态与团队侧状态互不影响;看板的「完成」仍只能由人确认。`,
47
+ "回滚:本映射不写任何表、不改任何文件 ⇒ 回滚=撤掉本路由与前端展示,历史数据零影响。",
48
+ ].join("\n");
49
+
50
+ const MAX_DEPTH = 6;
51
+ const SNIPPET_PAD = 40;
52
+
53
+ /* ───────────────────────── 只读扫描:插件侧团队 ───────────────────────── */
54
+
55
+ /**
56
+ * 读工作区 `.agent-teams/*\/team.json`(**只读**)。
57
+ *
58
+ * @param {string|null} workspacePath
59
+ * @returns {Promise<Array<{id:string,name:string,phase:string|null,captainSessionId:string|null,memberCount:number,taskCount:number,tasks:Array<object>}>>}
60
+ */
61
+ export async function readPluginTeams(workspacePath) {
62
+ if (!workspacePath) return [];
63
+ const root = join(workspacePath, ".agent-teams");
64
+ let entries = [];
65
+ try {
66
+ entries = await readdir(root, { withFileTypes: true });
67
+ } catch {
68
+ return []; // 工作区没有 .agent-teams/ 或读不到 ⇒ 空(不是错误)
69
+ }
70
+ const teams = [];
71
+ for (const entry of entries) {
72
+ if (!entry.isDirectory() || entry.name === "archive") continue;
73
+ let raw = null;
74
+ try {
75
+ raw = await readFile(join(root, entry.name, "team.json"), "utf8");
76
+ } catch {
77
+ continue;
78
+ }
79
+ let parsed = null;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ } catch {
83
+ continue; // 非法 JSON ⇒ 跳过(不猜)
84
+ }
85
+ const tasks = Array.isArray(parsed?.tasks) ? parsed.tasks : [];
86
+ teams.push({
87
+ id: parsed?.id ?? entry.name,
88
+ name: parsed?.name ?? entry.name,
89
+ phase: parsed?.phase ?? null,
90
+ captainSessionId: parsed?.captainSessionId ?? null,
91
+ memberCount: Array.isArray(parsed?.members) ? parsed.members.length : 0,
92
+ taskCount: tasks.length,
93
+ tasks: tasks.map((task) => ({
94
+ id: task?.id ?? null,
95
+ subject: task?.subject ?? null,
96
+ status: task?.status ?? null,
97
+ assignee: task?.assignee ?? null,
98
+ kind: task?.kind ?? null,
99
+ dependencies: Array.isArray(task?.dependencies) ? task.dependencies : [],
100
+ fields: collectFields(task),
101
+ })),
102
+ });
103
+ }
104
+ return teams;
105
+ }
106
+
107
+ /** 对外回包用的精简形状(**去掉 `fields` 全文**,避免把插件产出整段搬进接口)。 */
108
+ export function slimPluginTeam(team) {
109
+ return {
110
+ id: team.id,
111
+ name: team.name,
112
+ phase: team.phase,
113
+ captainSessionId: team.captainSessionId,
114
+ memberCount: team.memberCount,
115
+ taskCount: team.taskCount,
116
+ };
117
+ }
118
+
119
+ /* ───────────────────────── 映射推导 ───────────────────────── */
120
+
121
+ /**
122
+ * 单卡反查:这张卡在插件侧命中哪几个 `t-id`。
123
+ *
124
+ * @param {string} identifier 看板卡号(如 `scada-vibe-3`)
125
+ * @param {Array} teams `readPluginTeams` 的结果
126
+ */
127
+ export function mapCardToTeamTasks(identifier, teams) {
128
+ const target = String(identifier ?? "").trim();
129
+ if (!target) return [];
130
+ const matcher = buildMatcher([target]);
131
+ if (!matcher) return [];
132
+ const rows = [];
133
+ for (const team of teams ?? []) {
134
+ for (const task of team.tasks ?? []) {
135
+ const hits = findHits(task.fields, matcher);
136
+ if (!hits.length) continue;
137
+ rows.push({
138
+ teamId: team.id,
139
+ teamName: team.name,
140
+ teamPhase: team.phase ?? null,
141
+ teamTaskId: task.id,
142
+ teamTaskSubject: task.subject ?? null,
143
+ teamTaskStatus: task.status ?? null,
144
+ teamTaskKind: task.kind ?? null,
145
+ assignee: task.assignee ?? null,
146
+ dependencies: task.dependencies ?? [],
147
+ evidence: hits.map(({ field, snippet }) => ({ field, snippet })),
148
+ });
149
+ }
150
+ }
151
+ return rows;
152
+ }
153
+
154
+ /**
155
+ * 项目级映射表:项目全部卡 × 插件侧团队任务。
156
+ *
157
+ * @param {{cards: Array<{id:string,identifier:string,title?:string,status?:string}>, teams: Array}} input
158
+ */
159
+ export function buildCardTaskMap({ cards, teams } = {}) {
160
+ const cardList = (cards ?? []).map((card) => ({
161
+ id: card?.id ?? null,
162
+ identifier: card?.identifier ?? null,
163
+ title: card?.title ?? null,
164
+ status: card?.status ?? null,
165
+ }));
166
+ const matcher = buildMatcher(cardList.map((card) => card.identifier));
167
+ const rows = [];
168
+ const mappedCardIds = new Set();
169
+ if (matcher) {
170
+ for (const team of teams ?? []) {
171
+ for (const task of team.tasks ?? []) {
172
+ const hits = findHits(task.fields, matcher);
173
+ if (!hits.length) continue;
174
+ const byIdentifier = new Map();
175
+ for (const hit of hits) {
176
+ if (!byIdentifier.has(hit.identifier)) byIdentifier.set(hit.identifier, []);
177
+ byIdentifier.get(hit.identifier).push(hit);
178
+ }
179
+ for (const [identifier, evidence] of byIdentifier) {
180
+ const card = cardList.find((c) => c.identifier === identifier);
181
+ if (!card) continue;
182
+ mappedCardIds.add(card.id);
183
+ rows.push({
184
+ cardId: card.id,
185
+ cardIdentifier: card.identifier,
186
+ cardTitle: card.title,
187
+ cardStatus: card.status,
188
+ teamId: team.id,
189
+ teamName: team.name,
190
+ teamPhase: team.phase ?? null,
191
+ teamTaskId: task.id,
192
+ teamTaskSubject: task.subject ?? null,
193
+ teamTaskStatus: task.status ?? null,
194
+ assignee: task.assignee ?? null,
195
+ evidence: evidence.map(({ field, snippet }) => ({ field, snippet })),
196
+ });
197
+ }
198
+ }
199
+ }
200
+ }
201
+ const unmapped = cardList
202
+ .filter((card) => !mappedCardIds.has(card.id))
203
+ .map((card) => ({ id: card.id, identifier: card.identifier, title: card.title, status: card.status }));
204
+ const stats = {
205
+ cards: cardList.length,
206
+ mappedCards: mappedCardIds.size,
207
+ unmappedCards: unmapped.length,
208
+ pluginTeams: (teams ?? []).length,
209
+ pluginTasks: (teams ?? []).reduce((n, team) => n + (team?.tasks?.length ?? 0), 0),
210
+ mappedRows: rows.length,
211
+ };
212
+ return { rows, unmapped, stats };
213
+ }
214
+
215
+ /* ───────────────────────── 内部工具 ───────────────────────── */
216
+
217
+ /** 递归收集对象里的所有字符串叶子(带字段路径)—— 命中证据要指得出"在哪个字段"。 */
218
+ function collectFields(value, path = "", out = [], depth = 0) {
219
+ if (depth > MAX_DEPTH) return out;
220
+ if (typeof value === "string") {
221
+ if (value.length) out.push({ path: path || "(root)", text: value });
222
+ return out;
223
+ }
224
+ if (Array.isArray(value)) {
225
+ value.forEach((item, index) => collectFields(item, `${path}[${index}]`, out, depth + 1));
226
+ return out;
227
+ }
228
+ if (value && typeof value === "object") {
229
+ for (const [key, item] of Object.entries(value)) collectFields(item, path ? `${path}.${key}` : key, out, depth + 1);
230
+ }
231
+ return out;
232
+ }
233
+
234
+ function escapeRegExp(text) {
235
+ return String(text).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
236
+ }
237
+
238
+ /**
239
+ * 卡号全词匹配器。
240
+ *
241
+ * - 长的排前面(`scada-vibe-10` 必须排在 `scada-vibe-1` 前面,否则前者会被后者的否定前瞻挡成"不命中");
242
+ * - 两侧用**字符类否定**而不是 `\b`:卡号里含 `-`,`\b` 会把 `scada-vibe-1` 的结尾边界算在 `-` 上 ⇒ 误判。
243
+ */
244
+ function buildMatcher(identifiers) {
245
+ const list = [...new Set((identifiers ?? []).map((x) => String(x ?? "").trim()).filter(Boolean))].sort(
246
+ (a, b) => b.length - a.length || a.localeCompare(b),
247
+ );
248
+ if (!list.length) return null;
249
+ const pattern = `(?<![A-Za-z0-9_-])(${list.map(escapeRegExp).join("|")})(?![A-Za-z0-9_-])`;
250
+ return { pattern, regex: new RegExp(pattern, "g"), list };
251
+ }
252
+
253
+ /** 在字段集合里找命中(返回命中字段 + 片段)。 */
254
+ function findHits(fields, matcher) {
255
+ if (!matcher) return [];
256
+ const hits = [];
257
+ for (const { path, text } of fields ?? []) {
258
+ matcher.regex.lastIndex = 0;
259
+ let match = matcher.regex.exec(text);
260
+ while (match !== null) {
261
+ hits.push({ identifier: match[1], field: path, snippet: snippetAround(text, match.index, match[0].length) });
262
+ if (match.index === matcher.regex.lastIndex) matcher.regex.lastIndex += 1; // 防零宽死循环
263
+ match = matcher.regex.exec(text);
264
+ }
265
+ }
266
+ return hits;
267
+ }
268
+
269
+ function snippetAround(text, index, length) {
270
+ const start = Math.max(0, index - SNIPPET_PAD);
271
+ const end = Math.min(text.length, index + length + SNIPPET_PAD);
272
+ const body = text.slice(start, end).replace(/\s+/g, " ").trim();
273
+ return `${start > 0 ? "…" : ""}${body}${end < text.length ? "…" : ""}`;
274
+ }
package/src/core/team.mjs CHANGED
@@ -47,6 +47,39 @@ export const STATUS_MAPPING = Object.freeze({
47
47
  /** 执行侧允许写入的项目状态(**不含 done**)。 */
48
48
  export const TEAM_WRITABLE_STATUSES = Object.freeze(["in_progress", "in_review", "blocked", "canceled"]);
49
49
 
50
+ /**
51
+ * 执行侧可写状态 ↔ **看板列名** 对照(卡 `-261`)。
52
+ *
53
+ * 用途**只有两处**:① 报错文案把误传的看板列名**直接点名**到枚举(少一次「读报错 → 猜语言 → 重试」的往返);
54
+ * ② 守卫测试断言「四种中文各能落到对应英文状态」。
55
+ *
56
+ * **不做入参归一**:中文一律**拒绝**(需求 `R186` ③:仍拒绝、不做静默映射)——
57
+ * 一旦这里开始接受中文,契约里就同时留着两套词汇,`-262` 立的「单一真源英文枚举」口径当场作废。
58
+ */
59
+ export const TEAM_STATUS_COLUMN_LABELS = Object.freeze({
60
+ in_progress: "进行中",
61
+ in_review: "待验收",
62
+ blocked: "受阻",
63
+ canceled: "取消",
64
+ });
65
+
66
+ /**
67
+ * 列名别名:看板 UI 的列名与工具文案差一个字(UI 写「已取消」、工具写「取消」),
68
+ * 只认一种写法会让「已取消」变成死胡同 —— 这里按**枚举**归一,别名只是入口。
69
+ */
70
+ const TEAM_STATUS_COLUMN_ALIASES = Object.freeze({ 已取消: "canceled" });
71
+
72
+ /**
73
+ * 反查:看板列名 → 状态枚举。**只用于报错文案**(不改写入参、不做映射)。
74
+ * 认不得(不是已知列名 / 大小写或空格对不上)⇒ 返回 `null` ⇒ 报错只列全部合法值,**不给猜测**。
75
+ */
76
+ export function teamStatusEnumForColumn(label) {
77
+ if (typeof label !== "string") return null;
78
+ if (Object.hasOwn(TEAM_STATUS_COLUMN_ALIASES, label)) return TEAM_STATUS_COLUMN_ALIASES[label];
79
+ const hit = Object.entries(TEAM_STATUS_COLUMN_LABELS).find(([, name]) => name === label);
80
+ return hit ? hit[0] : null;
81
+ }
82
+
50
83
  /**
51
84
  * FR-50:团队模板的**角色集合**——权威来源是 `spec/团队agent.md` §一 的角色表(id 列)。
52
85
  * 只认这 6 个派发角色;用于创建团队时校验模板里出现的角色名。
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import { matchProjectForCwd, resolveContext, resolveProjectForCwd } from "../core/binding.mjs";
15
15
  import { TbError } from "../core/errors.mjs";
16
+ import { TEAM_WRITABLE_STATUSES } from "../core/team.mjs";
16
17
 
17
18
  const text = (v) => [{ type: "text", text: typeof v === "string" ? v : JSON.stringify(v, null, 2) }];
18
19
  // 宿主 tools 服务对 JSON-schema 有**子集校验**(dsh-tools/json-schema):`type` 只能是
@@ -162,8 +163,20 @@ export function registerTaskboardTools({ tools, store, events = null, defineTool
162
163
 
163
164
  reg({
164
165
  name: "taskboard_update_status",
165
- description: "更新任务状态(执行侧可用:进行中/待验收/受阻/取消);**不得写 done**(人工确认)。置「受阻」时可带 kind(dependency/needs_input/capability/transient)以便分类与循环升级;置「待验收」= **请求评审**(FR-83,欢迎带 comment 说明与触发的疑问)。",
166
- parameters: { ref: { type: "string", required: true }, status: { type: "string", required: true }, kind: { type: "string" }, reason: { type: "string" }, comment: { type: "string" } },
166
+ description: "更新任务状态(执行侧可写:in_progress / in_review / blocked / canceled)。**status 必须传英文枚举**——中文只是看板列名对照:in_progress(进行中)/ in_review(待验收)/ blocked(受阻)/ canceled(取消),传中文会被拒。**不得写 done**(人工确认,schema 直接拒)。置 blocked 时可带 kind(dependency/needs_input/capability/transient)以便分类与循环升级;置 in_review = **请求评审**(FR-83,欢迎带 comment 说明与触发的疑问)。",
167
+ parameters: {
168
+ ref: { type: "string", required: true, description: "任务编号(如 taskboard-workbench-1)或任务 id。" },
169
+ // 卡 `-262`(需求 `R186`):`status` 原先只有 `type: "string"`、描述里写中文 ⇒ 模型照描述填「待验收」,
170
+ // 实现只认英文枚举,必抛 `INVALID_FIELD: 执行侧不允许写入 待验收`。
171
+ // 现在把合法值写进 schema:宿主 JSON-schema 子集已核实支持 `type:"string"` 上的 `enum`
172
+ // (dsh-tools `compileValueSchema` 的 string 分支允许 authorKeys + type/enum/const)。
173
+ // 卡 `-261`:参数描述里把「看板列名 = 枚举」对照**直接摆出来** —— 模型填这一格时看到的是对照本身,
174
+ // 而不是「不要传中文」这种只说禁令的话(对照同样只用于**报错文案**,不做入参归一)。
175
+ status: { type: "string", required: true, enum: [...TEAM_WRITABLE_STATUSES], description: "英文枚举(必填):in_progress / in_review / blocked / canceled。对照:进行中=in_progress / 待验收=in_review / 受阻=blocked / 取消=canceled。中文只是看板列名,不要传中文。" },
176
+ kind: { type: "string", description: "仅在 status=blocked 时生效:dependency / needs_input / capability / transient(缺省 transient)。" },
177
+ reason: { type: "string", description: "受阻原因 / 撤单说明(可选)。" },
178
+ comment: { type: "string", description: "仅在 status=in_review 时作为评审请求说明(可选)。" },
179
+ },
167
180
  async execute(args, exec) {
168
181
  const actor = actorOf(exec) ?? "agent";
169
182
  // FR-80:置「受阻」走统一分类入口(带类型 + 复发升级);