@suifei/dsh-ai-team 0.4.162 → 0.4.164

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.164 - 2026-12-04
4
+
5
+ - 运行中的常规项目可以在关闭 PMO 自动时开启只读编制巡检。诊断日志同时记录 PMO 状态、验收流量、积压、槽位和建议。关闭 PMO 后建议仅用于诊断采样。感谢 @buger-gif 提供编制巡检和真实验收队列场景(#116)。
6
+
7
+ ## 0.4.163 - 2026-12-04
8
+
9
+ - `/ai-team 开工` 根据目标建议团队和一张可独立验收的首发样稿。项目、编制和首发任务在同一次确认中落地,任务走文渊阁现有派发与验收流程。项目登记失败后重试可沿用已落盘的原卡。感谢 @buger-gif 提供从一句目标到建队派活的场景(#121)。
10
+
3
11
  ## 0.4.162 - 2026-12-04
4
12
 
5
13
  - DSH 会话可预览多张任务卡的执行人、交付标准和独立验收项。确认后整批写入账本并沿用项目派发规则。也可为待领取的原任务分派执行人,确认时会重新对照原卡版本。感谢 @buger-gif 提出会话内建卡与分派的场景(#121)。
package/README.md CHANGED
@@ -37,6 +37,8 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **手动调度项目也能巡检编制**(0.4.164)。打开巡检设置后,即使关闭 PMO 自动,也可按窗口观察待验收任务、验收流量和代理树槽位。采样建议留在诊断日志。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
41
+ - **一句目标开工**(0.4.163)。在 DSH 会话输入 `/ai-team 开工 目标`,可一起核对预设、编制、首发样稿、执行人和验收条件。确认后创建项目并派发首发任务。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
40
42
  - **会话里建卡和分派**(0.4.162)。可核对整批任务的执行人、交付标准和独立验收项,再一次确认到文渊阁。待领取的原卡也能在会话里分派。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
41
43
  - **会话一次确认多项编制调整**(0.4.161)。增员、改岗位和原任务交接可进入同一份草稿,核对整组后一次写入。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
42
44
  - **巡检验收流量**(0.4.161)。巡检在同一条记录里报告本窗口提交、通过与退回的次数,另列人工自验,方便和待验收积压、槽位余量对照。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
@@ -154,6 +156,8 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
154
156
 
155
157
  新项目会出现在文渊阁,PMO 自动初始关闭。团队准备好后,可以在项目页开启 PMO 自动。
156
158
 
159
+ 需要一次确认就派发首份样稿时,用 `/ai-team 开工 整理接口文档`。草稿会同时显示推荐团队、执行人、样稿范围和独立验收条件。可在目标末尾写明人数,或用 `/ai-team 开工 --team docs 整理接口文档` 指定预设。确认后可以从看板查看首发任务与派发进展。后续任务也可继续在同一会话起草。
160
+
157
161
  ### 从 DSH 会话调整编制
158
162
 
159
163
  `/ai-team 编制` 显示当前工作区的项目与成员编号。同一工作区有多个项目时,先选项目,使用 `/ai-team 编制 项目ID` 查看成员。用 `/ai-team 人才 [关键词]` 查看人才编号。
@@ -199,7 +203,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
199
203
 
200
204
  ### 只读编制巡检试跑
201
205
 
202
- 在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。项目级 `acceptanceActivity` 按 `since`、`now` 内的账本记录计数,包含已离队成员和人工处理的结果。通过次数包含人工自验,日志另外列出自验次数。
206
+ 在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,运行中的普通项目会随现有巡检周期采样,每个时间窗口记录一次。关闭 PMO 自动时,采样建议只写入诊断日志。暂停项目会暂停巡检,`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 记录采样时的 `pmoAuto`、岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。项目级 `acceptanceActivity` 按 `since`、`now` 内的账本记录计数,包含已离队成员和人工处理的结果。通过次数包含人工自验,日志另外列出自验次数。
203
207
 
204
208
  巡检还会记录没有合格验收人的任务 ID 和在队成员运行回合数。宿主提供 `capacityOf` 时,`host-live` 表示当前代理树的实时槽位快照,`occupiedSlots` 和 `remainingSlots` 分别记录占用和余量。`host` 表示这棵树的容量回执,`default` 表示默认估计。这两种来源的占用和余量字段为空。宿主释放槽位后,插件优先补投本树排队最久的成员。加人建议会提示采样时的槽位不足,长期无人可验收的任务也会进入现有补位建议。
205
209
 
@@ -450,7 +454,7 @@ round-19 DeepSeek + Zhipu 双 provider
450
454
  | 贡献者 | 贡献 | 带来的进展 |
451
455
  |---|---|---|
452
456
  | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
453
- | [@buger-gif](https://github.com/buger-gif) | 编制巡检、离队交接案例 [#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117),派发空转记录 [#120](https://github.com/suifei/dsh-ai-team/issues/120),会话建队、指定人数、按目标补位、调整编制与任务分派场景 [#121](https://github.com/suifei/dsh-ai-team/issues/121) | 统一认领与离队顺序,减少派发空转,可按窗口对照验收流量和代理树槽位。在 DSH 会话按目标建议预设、核对人数和补位依据,一次确认多项编制调整、原任务交接或首批任务分派 |
457
+ | [@buger-gif](https://github.com/buger-gif) | 编制巡检、离队交接案例 [#116](https://github.com/suifei/dsh-ai-team/issues/116)、[#117](https://github.com/suifei/dsh-ai-team/issues/117),派发空转记录 [#120](https://github.com/suifei/dsh-ai-team/issues/120),会话按目标建队开工、指定人数、按目标补位、调整编制与任务分派场景 [#121](https://github.com/suifei/dsh-ai-team/issues/121) | 统一认领与离队顺序,减少派发空转。手动调度的项目也可以按巡检窗口对照验收流量和代理树槽位。在 DSH 会话按目标核对团队和首发样稿后一次确认开工,也可调整编制、交接原任务或分派已有卡片 |
454
458
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化,并在 Alpha 宿主验证看板登录 |
455
459
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
456
460
  | [@godfay-g](https://github.com/godfay-g) | 技能目录和 ZIP 的导入建议 [#109](https://github.com/suifei/dsh-ai-team/issues/109) | 成员与自定义人才可在文渊阁选择已安装的技能或导入完整技能包。0.4.151 统一新建人才的导入入口,并由文渊阁直接安装整包 |
package/index.js CHANGED
@@ -1395,6 +1395,39 @@ export function apply(ctx, config = {}) {
1395
1395
  diag.append({ ev: 'blueprint.advance.fail', projectId: runtime.id, message: error?.message ?? String(error) });
1396
1396
  }
1397
1397
  };
1398
+ const inspectStaffing = (projectRuntime) => {
1399
+ const staffingState = projectRuntime.service.state;
1400
+ const project = staffingState.projects?.[projectRuntime.id];
1401
+ if (disposed || !project || project.status === 'archived' || project.runState === 'stopped') return [];
1402
+ const pmoAuto = project.pmoAuto !== false;
1403
+ const now = Date.now();
1404
+ const reviewInterval = (config.staffingReviewMinutes ?? 0) * 60_000;
1405
+ const reviewWindow = diag.level === 'full' && reviewInterval > 0 ? Math.floor(now / reviewInterval) : null;
1406
+ const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1407
+ if (!pmoAuto && (!reviewDue || project.blueprint)) return [];
1408
+ const suppressed = [];
1409
+ const inTurn = (id) => turnsInFlight.has(id);
1410
+ const hostCapacity = treeCapacity.read(hosts.get(projectRuntime.id)?.agent, serviceOf(ctx, 'subagents'));
1411
+ const capacity = hostCapacity.capacity ?? HOST_SUBAGENT_LIMIT;
1412
+ const adviceList = planStaffingAdvice(staffingState, {
1413
+ now, inTurn, capacity, remainingSlots: hostCapacity.remainingSlots,
1414
+ humanId: projectRuntime.service.humanId(), wait: (config.staffingAdviceMinutes ?? 30) * 60_000,
1415
+ onSuppressed: reviewDue ? (entry) => suppressed.push(entry) : undefined,
1416
+ });
1417
+ if (reviewDue) {
1418
+ pmoStaffingReviewWindows.set(projectRuntime.id, reviewWindow);
1419
+ try {
1420
+ const review = staffingReview(staffingState, projectRuntime.ledger.events, {
1421
+ ...hostCapacity, now, intervalMs: reviewInterval, capacity,
1422
+ inTurn, advice: adviceList, suppressed,
1423
+ });
1424
+ diag.append({ ev: 'pmo.staffing.review', projectId: projectRuntime.id, window: reviewWindow, pmoAuto, ...review });
1425
+ } catch (error) {
1426
+ diag.append({ ev: 'pmo.staffing.review.fail', projectId: projectRuntime.id, message: error?.message ?? String(error) });
1427
+ }
1428
+ }
1429
+ return pmoAuto ? adviceList : [];
1430
+ };
1398
1431
  const pmoTick = async (projectRuntime) => {
1399
1432
  if (projectRuntime === null || projectRuntime === undefined) return;
1400
1433
  // 归档修复重试点:boot 时 workspaceRegistry 往往还没 active,等 tick
@@ -1441,10 +1474,13 @@ export function apply(ctx, config = {}) {
1441
1474
  // 门禁必须在 await 之后重新取:reconcileJobs 可能耗时数秒,期间 Human
1442
1475
  // 可能已经停用 PMO / 归档 / 停止项目,用 await 之前的快照会继续写账本。
1443
1476
  const project = projectRuntime.service.state.projects?.[projectRuntime.id];
1444
- if (project === undefined || project.pmoAuto === false || project.status === 'archived') return;
1445
1477
  // P6 停止门:stopped 项目停止一切派发(补派/心跳/升级/continue 全停),
1446
1478
  // 正在执行的回合自然完成;唤醒事件 hook 同样检查(见 wakeFromResult)。
1447
- if (project.runState === 'stopped') return;
1479
+ if (!project || project.status === 'archived' || project.runState === 'stopped') return;
1480
+ if (project.pmoAuto === false) {
1481
+ inspectStaffing(projectRuntime);
1482
+ return;
1483
+ }
1448
1484
  for (const member of Object.values(state.members ?? {})) {
1449
1485
  if (member.kind === 'agent' && typeof member.sessionId === 'string') {
1450
1486
  await titleMemberSession(projectRuntime, member);
@@ -1505,34 +1541,9 @@ export function apply(ctx, config = {}) {
1505
1541
  }, {});
1506
1542
  }
1507
1543
  // 加人建议:推进过慢(待办没人接 / 待验收排长队)时给 Human 收件箱一条建议,由 Human 决定(planStaffingAdvice)。
1508
- const staffingState = projectRuntime.service.state;
1509
- const reviewInterval = (config.staffingReviewMinutes ?? 0) * 60_000;
1510
- const reviewWindow = diag.level === 'full' && reviewInterval > 0 ? Math.floor(now / reviewInterval) : null;
1511
- const reviewDue = reviewWindow !== null && pmoStaffingReviewWindows.get(projectRuntime.id) !== reviewWindow;
1512
- const suppressed = [];
1513
- const inTurn = (id) => turnsInFlight.has(id);
1514
- const hostCapacity = treeCapacity.read(hosts.get(projectRuntime.id)?.agent, serviceOf(ctx, 'subagents'));
1515
- const capacity = hostCapacity.capacity ?? HOST_SUBAGENT_LIMIT;
1516
- const adviceList = planStaffingAdvice(staffingState, {
1517
- now, inTurn, capacity, remainingSlots: hostCapacity.remainingSlots,
1518
- humanId: projectRuntime.service.humanId(), wait: (config.staffingAdviceMinutes ?? 30) * 60_000,
1519
- onSuppressed: reviewDue ? (entry) => suppressed.push(entry) : undefined,
1520
- });
1521
- if (reviewDue) {
1522
- pmoStaffingReviewWindows.set(projectRuntime.id, reviewWindow);
1523
- try {
1524
- const review = staffingReview(staffingState, projectRuntime.ledger.events, {
1525
- ...hostCapacity, now, intervalMs: reviewInterval, capacity,
1526
- inTurn, advice: adviceList, suppressed,
1527
- });
1528
- diag.append({ ev: 'pmo.staffing.review', projectId: projectRuntime.id, window: reviewWindow, ...review });
1529
- } catch (error) {
1530
- diag.append({ ev: 'pmo.staffing.review.fail', projectId: projectRuntime.id, message: error?.message ?? String(error) });
1531
- }
1532
- }
1533
- for (const advice of adviceList) {
1544
+ for (const advice of inspectStaffing(projectRuntime)) {
1534
1545
  const item = await projectRuntime.service.recordStaffingAdvice(projectRuntime.id, advice);
1535
- diag.append({ ev: 'pmo.advice', projectId: projectRuntime.id, role: advice.role, count: advice.count, title: advice.title, itemId: item?.id ?? null });
1546
+ if (item) diag.append({ ev: 'pmo.advice', projectId: projectRuntime.id, role: advice.role, count: advice.count, title: advice.title, itemId: item.id });
1536
1547
  }
1537
1548
  if (active.length > 0) {
1538
1549
  // Prune per-task clock entries whose task left the active set, so
@@ -2541,7 +2552,7 @@ export function apply(ctx, config = {}) {
2541
2552
  function activateProject(projectId, input) {
2542
2553
  return trackProjectOperation(activateProjectRuntime(projectId, input));
2543
2554
  }
2544
- async function activateProjectRuntime(nextProjectId, { name, goal, workspacePath = '', teamPreset = null, blueprint = null, pmoAuto = true }) {
2555
+ async function activateProjectRuntime(nextProjectId, { name, goal, workspacePath = '', teamPreset = null, blueprint = null, pmoAuto = true, firstTask }) {
2545
2556
  await ready;
2546
2557
  if (disposed || booted === null) throw new Error('team ledger is unavailable');
2547
2558
  let next = projectRuntime(nextProjectId);
@@ -2560,8 +2571,9 @@ export function apply(ctx, config = {}) {
2560
2571
  blueprint,
2561
2572
  pmoAuto,
2562
2573
  });
2563
- // 账本和两个岗位先落地,重启时才不会把半写的蓝图项目播种成预设团队。
2574
+ // 登记后工作台和启动恢复才可见。先落地确认过的成员和首发任务。
2564
2575
  try {
2576
+ if (firstTask) await next.seedFirstTask(firstTask);
2565
2577
  booted.registry.add({ id: nextProjectId, name, goal, workspacePath });
2566
2578
  } catch (error) {
2567
2579
  await next.close();
@@ -2579,7 +2591,11 @@ export function apply(ctx, config = {}) {
2579
2591
  ledger: next.ledger,
2580
2592
  service: next.service,
2581
2593
  };
2582
- if (!disposed) broadcast(undefined, next);
2594
+ if (!disposed) {
2595
+ const event = firstTask ? next.firstTaskEvent() : undefined;
2596
+ if (event) next.ledger.onEvent?.(event);
2597
+ else broadcast(undefined, next);
2598
+ }
2583
2599
  return next;
2584
2600
  }
2585
2601
  async function disposeMemberActivation(runtime, memberId, reason) {
@@ -2611,7 +2627,7 @@ export function apply(ctx, config = {}) {
2611
2627
  const candidates = matchTeamPresets(catalog, project.goal);
2612
2628
  diag.append({ ev: 'session.team.recommendation', candidates: candidates.map(({ id, terms }) => ({ id, terms })) });
2613
2629
  if (candidates.length !== 1) {
2614
- const hint = '请用 /ai-team 建队 --team 预设ID 目标 指定团队。';
2630
+ const hint = `请用 /ai-team ${input.action} --team 预设ID 目标 指定团队。`;
2615
2631
  const summary = candidates.map(({ name, id, terms }) => `- ${name}(${id}) · ${terms.join('、')}`).join('\n');
2616
2632
  fail(ERRORS.INVALID_ARGUMENT, summary ? `目标对应多个团队。${hint}\n${summary}` : `目标中缺少明确的团队线索。${hint}`);
2617
2633
  }
@@ -2629,7 +2645,11 @@ export function apply(ctx, config = {}) {
2629
2645
  }
2630
2646
  return { ...project, teamPreset: preset, matchedTerms, suggestions, supplements: added };
2631
2647
  },
2632
- create: async (id, input) => (await activateProject(id, { ...input, pmoAuto: false })).service.state.projects[id],
2648
+ async create(id, input) {
2649
+ const runtime = await activateProject(id, { ...input, pmoAuto: false });
2650
+ const taskId = input.firstTask ? runtime.firstTaskEvent()?.payload.taskId : undefined;
2651
+ return { project: runtime.service.state.projects[id], task: taskId ? runtime.service.state.tasks[taskId] : undefined };
2652
+ },
2633
2653
  prepareRoster: createSessionRoster({
2634
2654
  ...sessionProjectAccess,
2635
2655
  catalog: () => talentCatalog(diag),
@@ -1,104 +1,109 @@
1
- /** Lightweight Project index. The ledger remains the source of truth for Project state. */
2
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { DEFAULT_PROJECT_ID } from './project-runtime.js';
5
- import { reportFail } from '../diaglog.js';
6
-
7
- export class ProjectRegistry {
8
- constructor({ rootDir, projects, activeProjectId }) {
9
- this.rootDir = rootDir;
10
- this.projects = Array.isArray(projects) ? projects : [];
11
- this.activeProjectId = activeProjectId ?? DEFAULT_PROJECT_ID;
12
- }
13
-
14
- static load(rootDir, options = {}) {
15
- // 初装时会给一个默认项目;它必须有工作目录,否则成员会话的 cwd 只能落到
16
- // 插件数据目录(workspace attach 会被拒,成员也在错误目录里干活)。
17
- const defaultWorkspacePath = typeof options.defaultWorkspacePath === 'string' ? options.defaultWorkspacePath : '';
18
- mkdirSync(rootDir, { recursive: true });
19
- const file = join(rootDir, 'projects.json');
20
- let parsed;
21
- try {
22
- parsed = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
23
- } catch (error) {
24
- // A corrupt index must not silently vanish the user's project list:
25
- // keep the broken file for forensics, then fall back to the default.
26
- const kept = `${file}.corrupt-${Date.now()}`;
27
- try { renameSync(file, kept); } catch { /* rename is best-effort */ }
28
- reportFail('registry.corrupt.fail', { kept }, `[ai-team] projects.json was unreadable (${error?.message ?? error}); kept as ${kept}`);
29
- parsed = null;
30
- }
31
- // 默认项目只在**一个项目都没有**时播种(初装的第一入口)。此前只要列表里
32
- // 缺少 `prj_main` 就补一条:用户把它删掉后会被静默复活,等于删不掉。
33
- const projects = Array.isArray(parsed?.projects) && parsed.projects.length > 0
34
- ? parsed.projects.filter((project) => typeof project?.id === 'string' && project.id !== '')
35
- : [];
36
- if (projects.length === 0) projects.push({ id: DEFAULT_PROJECT_ID, name: '我的项目', createdAt: 0 });
37
- const active = projects.some((project) => project.id === parsed?.activeProjectId)
38
- ? parsed.activeProjectId
39
- : projects[0].id;
40
- const registry = new ProjectRegistry({ rootDir, projects, activeProjectId: active });
41
- if (!existsSync(file)) registry.save();
42
- return registry;
43
- }
44
-
45
- get activeProject() {
46
- return this.projects.find((project) => project.id === this.activeProjectId) ?? this.projects[0];
47
- }
48
-
49
- list() {
50
- return this.projects.map((project) => ({ ...project, active: project.id === this.activeProjectId }));
51
- }
52
-
53
- /** 更新某个项目的工作目录(与账本的 project/workspace-changed 保持同步)。 */
54
- setWorkspace(id, workspacePath) {
55
- const project = this.projects.find((entry) => entry.id === id);
56
- if (project === undefined) return false;
57
- const next = typeof workspacePath === 'string' ? workspacePath : '';
58
- if ((project.workspacePath ?? '') === next) return false;
59
- project.workspacePath = next;
60
- this.save();
61
- return true;
62
- }
63
- add({ id, name, createdAt, goal, workspacePath }) {
64
- if (typeof id !== 'string' || id === '') throw new Error('project id is required');
65
- if (!this.projects.some((project) => project.id === id)) {
66
- this.projects.push({ id, name: name ?? id, goal: goal ?? '', workspacePath: workspacePath ?? '', createdAt: createdAt ?? Date.now() });
67
- this.save();
68
- }
69
- return this.projects.find((project) => project.id === id);
70
- }
71
-
72
- setActive(id) {
73
- const project = this.projects.find((entry) => entry.id === id);
74
- if (project === undefined) throw new Error(`unknown project: ${id}`);
75
- // 归档项目不能成为 active:registry 的 active 会被 bootstrap 当作「默认项目」,
76
- // 指向一个已归档/无账本的项目会让工作台直接不可达。
77
- if (project.archived === true) throw new Error(`project ${id} is archived`);
78
- this.activeProjectId = id;
79
- this.save();
80
- }
81
-
82
- /** Mirror a Project's archive flag into the global index (ledger stays the source of truth). */
83
- setArchived(id, archived) {
84
- const project = this.projects.find((entry) => entry.id === id);
85
- if (project === undefined) throw new Error(`unknown project: ${id}`);
86
- project.archived = archived === true;
87
- if (archived === true && this.activeProjectId === id) {
88
- const fallback = this.projects.find((entry) => entry.id !== id && entry.archived !== true);
89
- if (fallback !== undefined) this.activeProjectId = fallback.id;
90
- }
91
- this.save();
92
- return project;
93
- }
94
-
95
- save() {
96
- const file = join(this.rootDir, 'projects.json');
97
- const temp = `${file}.tmp`;
98
- writeFileSync(temp, JSON.stringify({
99
- activeProjectId: this.activeProjectId,
100
- projects: this.projects,
101
- }, null, 2), 'utf8');
102
- renameSync(temp, file);
103
- }
104
- }
1
+ /** Lightweight Project index. The ledger remains the source of truth for Project state. */
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { DEFAULT_PROJECT_ID } from './project-runtime.js';
5
+ import { reportFail } from '../diaglog.js';
6
+
7
+ export class ProjectRegistry {
8
+ constructor({ rootDir, projects, activeProjectId }) {
9
+ this.rootDir = rootDir;
10
+ this.projects = Array.isArray(projects) ? projects : [];
11
+ this.activeProjectId = activeProjectId ?? DEFAULT_PROJECT_ID;
12
+ }
13
+
14
+ static load(rootDir, options = {}) {
15
+ // 初装时会给一个默认项目;它必须有工作目录,否则成员会话的 cwd 只能落到
16
+ // 插件数据目录(workspace attach 会被拒,成员也在错误目录里干活)。
17
+ const defaultWorkspacePath = typeof options.defaultWorkspacePath === 'string' ? options.defaultWorkspacePath : '';
18
+ mkdirSync(rootDir, { recursive: true });
19
+ const file = join(rootDir, 'projects.json');
20
+ let parsed;
21
+ try {
22
+ parsed = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null;
23
+ } catch (error) {
24
+ // A corrupt index must not silently vanish the user's project list:
25
+ // keep the broken file for forensics, then fall back to the default.
26
+ const kept = `${file}.corrupt-${Date.now()}`;
27
+ try { renameSync(file, kept); } catch { /* rename is best-effort */ }
28
+ reportFail('registry.corrupt.fail', { kept }, `[ai-team] projects.json was unreadable (${error?.message ?? error}); kept as ${kept}`);
29
+ parsed = null;
30
+ }
31
+ // 默认项目只在**一个项目都没有**时播种(初装的第一入口)。此前只要列表里
32
+ // 缺少 `prj_main` 就补一条:用户把它删掉后会被静默复活,等于删不掉。
33
+ const projects = Array.isArray(parsed?.projects) && parsed.projects.length > 0
34
+ ? parsed.projects.filter((project) => typeof project?.id === 'string' && project.id !== '')
35
+ : [];
36
+ if (projects.length === 0) projects.push({ id: DEFAULT_PROJECT_ID, name: '我的项目', createdAt: 0 });
37
+ const active = projects.some((project) => project.id === parsed?.activeProjectId)
38
+ ? parsed.activeProjectId
39
+ : projects[0].id;
40
+ const registry = new ProjectRegistry({ rootDir, projects, activeProjectId: active });
41
+ if (!existsSync(file)) registry.save();
42
+ return registry;
43
+ }
44
+
45
+ get activeProject() {
46
+ return this.projects.find((project) => project.id === this.activeProjectId) ?? this.projects[0];
47
+ }
48
+
49
+ list() {
50
+ return this.projects.map((project) => ({ ...project, active: project.id === this.activeProjectId }));
51
+ }
52
+
53
+ /** 更新某个项目的工作目录(与账本的 project/workspace-changed 保持同步)。 */
54
+ setWorkspace(id, workspacePath) {
55
+ const project = this.projects.find((entry) => entry.id === id);
56
+ if (project === undefined) return false;
57
+ const next = typeof workspacePath === 'string' ? workspacePath : '';
58
+ if ((project.workspacePath ?? '') === next) return false;
59
+ project.workspacePath = next;
60
+ this.save();
61
+ return true;
62
+ }
63
+ add({ id, name, createdAt, goal, workspacePath }) {
64
+ if (typeof id !== 'string' || id === '') throw new Error('project id is required');
65
+ if (!this.projects.some((project) => project.id === id)) {
66
+ this.projects.push({ id, name: name ?? id, goal: goal ?? '', workspacePath: workspacePath ?? '', createdAt: createdAt ?? Date.now() });
67
+ try {
68
+ this.save();
69
+ } catch (error) {
70
+ this.projects.pop();
71
+ throw error;
72
+ }
73
+ }
74
+ return this.projects.find((project) => project.id === id);
75
+ }
76
+
77
+ setActive(id) {
78
+ const project = this.projects.find((entry) => entry.id === id);
79
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
80
+ // 归档项目不能成为 active:registry 的 active 会被 bootstrap 当作「默认项目」,
81
+ // 指向一个已归档/无账本的项目会让工作台直接不可达。
82
+ if (project.archived === true) throw new Error(`project ${id} is archived`);
83
+ this.activeProjectId = id;
84
+ this.save();
85
+ }
86
+
87
+ /** Mirror a Project's archive flag into the global index (ledger stays the source of truth). */
88
+ setArchived(id, archived) {
89
+ const project = this.projects.find((entry) => entry.id === id);
90
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
91
+ project.archived = archived === true;
92
+ if (archived === true && this.activeProjectId === id) {
93
+ const fallback = this.projects.find((entry) => entry.id !== id && entry.archived !== true);
94
+ if (fallback !== undefined) this.activeProjectId = fallback.id;
95
+ }
96
+ this.save();
97
+ return project;
98
+ }
99
+
100
+ save() {
101
+ const file = join(this.rootDir, 'projects.json');
102
+ const temp = `${file}.tmp`;
103
+ writeFileSync(temp, JSON.stringify({
104
+ activeProjectId: this.activeProjectId,
105
+ projects: this.projects,
106
+ }, null, 2), 'utf8');
107
+ renameSync(temp, file);
108
+ }
109
+ }
@@ -101,6 +101,21 @@ export class ProjectRuntime {
101
101
  return runtime;
102
102
  }
103
103
 
104
+ firstTaskEvent() {
105
+ return this.ledger.events.find(({ type, correlationId }) => type === 'task/created' && correlationId === this.id);
106
+ }
107
+
108
+ async seedFirstTask(payload) {
109
+ // 项目登记失败时,沿用这次确认已经落盘的任务。
110
+ const existing = this.firstTaskEvent();
111
+ if (existing) return existing;
112
+ await this.service.dispatch({
113
+ type: 'task.create', actor: { kind: 'human', memberId: HUMAN_ID },
114
+ projectId: this.id, correlationId: this.id, payload,
115
+ });
116
+ return this.firstTaskEvent();
117
+ }
118
+
104
119
  close() {
105
120
  try {
106
121
  this.ledger?.close?.();
@@ -1805,6 +1805,8 @@ export class TeamService {
1805
1805
  */
1806
1806
  async recordStaffingAdvice(projectId, advice) {
1807
1807
  return this.runExclusive(async () => {
1808
+ const project = this.state.projects?.[projectId];
1809
+ if (!project || project.pmoAuto === false || project.status === 'archived' || project.runState === 'stopped') return null;
1808
1810
  const humanId = this.humanId();
1809
1811
  if (humanId === null) return null;
1810
1812
  const item = createInboxItem({
@@ -1,43 +1,43 @@
1
- import { realpathSync } from 'node:fs';
2
- import { isAbsolute } from 'node:path';
3
- import { ERRORS, fail } from '../domain/errors.js';
4
-
5
- export function workspaceProject(runtime, workspacePath) {
6
- const project = runtime.service.state.projects?.[runtime.id];
7
- if (!project || project.status === 'archived' || typeof project.workspacePath !== 'string' || !isAbsolute(project.workspacePath)) return null;
8
- try {
9
- return realpathSync(project.workspacePath) === workspacePath ? project : null;
10
- } catch {
11
- return null;
12
- }
13
- }
14
-
15
- export async function selectSessionProject({ runtimes, isAvailable, workspacePath, projectId, usage }) {
16
- const options = [];
17
- for (const runtime of await runtimes()) {
18
- const project = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
19
- if (project !== null) options.push({ runtime, project });
20
- }
21
- if (projectId === undefined && options.length > 1) {
22
- return { text: [`同一工作区有多个项目,请使用 ${usage}。`, ...options.map(({ project }) => `- ${project.id} · ${project.name}`)].join('\n') };
23
- }
24
- const selection = projectId === undefined ? options[0] : options.find(({ project }) => project.id === projectId);
25
- if (!selection) fail(ERRORS.NOT_FOUND, '当前会话的工作区找不到该项目。使用 /ai-team 编制 查看同一工作区的项目。');
26
- return selection;
27
- }
28
-
29
- export const memberLabel = (member) => `${member.name}(${member.id})`;
30
-
31
- export function activeSessionMembers(state) {
32
- return Object.values(state.members ?? {}).filter(({ kind, status }) => kind === 'agent' && status !== 'retired');
33
- }
34
-
35
- export function resolveName(entries, value, label, aliases = (entry) => [entry.name]) {
36
- const name = value.trim();
37
- const direct = entries.find(({ id }) => id === name);
38
- if (direct) return direct.id;
39
- const matches = entries.filter((entry) => aliases(entry).includes(name));
40
- if (matches.length === 1) return matches[0].id;
41
- if (matches.length === 0) fail(ERRORS.NOT_FOUND, `找不到${label}「${name}」,请核对名字或编号。`);
42
- fail(ERRORS.CONFLICT, `${label}「${name}」有多个候选,请使用编号。\n${matches.map(memberLabel).join('\n')}`);
43
- }
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute } from 'node:path';
3
+ import { ERRORS, fail } from '../domain/errors.js';
4
+
5
+ export function workspaceProject(runtime, workspacePath) {
6
+ const project = runtime.service.state.projects?.[runtime.id];
7
+ if (!project || project.status === 'archived' || typeof project.workspacePath !== 'string' || !isAbsolute(project.workspacePath)) return null;
8
+ try {
9
+ return realpathSync(project.workspacePath) === workspacePath ? project : null;
10
+ } catch {
11
+ return null;
12
+ }
13
+ }
14
+
15
+ export async function selectSessionProject({ runtimes, isAvailable, workspacePath, projectId, usage }) {
16
+ const options = [];
17
+ for (const runtime of await runtimes()) {
18
+ const project = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
19
+ if (project !== null) options.push({ runtime, project });
20
+ }
21
+ if (projectId === undefined && options.length > 1) {
22
+ return { text: [`同一工作区有多个项目,请使用 ${usage}。`, ...options.map(({ project }) => `- ${project.id} · ${project.name}`)].join('\n') };
23
+ }
24
+ const selection = projectId === undefined ? options[0] : options.find(({ project }) => project.id === projectId);
25
+ if (!selection) fail(ERRORS.NOT_FOUND, '当前会话的工作区找不到该项目。使用 /ai-team 编制 查看同一工作区的项目。');
26
+ return selection;
27
+ }
28
+
29
+ export const memberLabel = (member) => `${member.name}(${member.id})`;
30
+
31
+ export function activeSessionMembers(state) {
32
+ return Object.values(state.members ?? {}).filter(({ kind, status }) => kind === 'agent' && status !== 'retired');
33
+ }
34
+
35
+ export function resolveName(entries, value, label, aliases = (entry) => [entry.name]) {
36
+ const name = value.trim();
37
+ const direct = entries.find(({ id }) => id === name);
38
+ if (direct) return direct.id;
39
+ const matches = entries.filter((entry) => aliases(entry).includes(name));
40
+ if (matches.length === 1) return matches[0].id;
41
+ if (matches.length === 0) fail(ERRORS.NOT_FOUND, `找不到${label}「${name}」,请核对名字或编号。`);
42
+ fail(ERRORS.CONFLICT, `${label}「${name}」有多个候选,请使用编号。\n${matches.map(memberLabel).join('\n')}`);
43
+ }
@@ -1,112 +1,143 @@
1
- import { DomainError, ERRORS, fail } from '../domain/errors.js';
2
- import { activeSessionMembers, memberLabel, resolveName, selectSessionProject, workspaceProject } from './session-project.js';
3
-
4
- const USAGE = {
5
- 任务: '/ai-team 任务 [项目ID] 标题 | 执行人 | 交付标准 [| 独立验收项](一行一张)',
6
- 分派: '/ai-team 分派 [项目ID] #任务编号 执行人',
7
- };
8
-
9
- export const taskHelp = Object.values(USAGE).join('\n');
10
- export const isTaskAction = (action) => Object.hasOwn(USAGE, action);
11
-
12
- function planTasks(input, assigneeFor) {
13
- return input.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean).map((line, index) => {
14
- const fields = line.split(/[||]/u).map((field) => field.trim());
15
- const [title, executor, resultDefinition, checks] = fields;
16
- if (fields.length > 4 || !title || !executor || !resultDefinition || checks === '') {
17
- fail(ERRORS.INVALID_ARGUMENT, `第 ${index + 1} 行须提供标题、执行人和交付标准。用 ${USAGE.任务}。`);
18
- }
19
- const qaChecklist = checks?.split(/[;;]/u).map((check) => check.trim()).filter(Boolean) ?? [];
20
- const assignee = assigneeFor(executor);
21
- return {
22
- command: { type: 'task.create', payload: { title, resultDefinition, assigneeId: assignee.id, qaRequired: checks !== undefined, qaChecklist } },
23
- assignee: memberLabel(assignee),
24
- };
25
- });
26
- }
27
-
28
- function planAssignment(input, state, assigneeFor) {
29
- const match = /^(#\d+|tsk_\S+)\s+(.+)$/u.exec(input);
30
- if (!match) fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE.分派}。`);
31
- const [, reference, executor] = match;
32
- const task = reference.startsWith('#')
33
- ? Object.values(state.tasks).find(({ number }) => number === Number(reference.slice(1)))
34
- : state.tasks[reference];
35
- if (!task || task.tombstone) fail(ERRORS.NOT_FOUND, `同一项目中找不到任务 ${reference}。`);
36
- const assignee = assigneeFor(executor);
37
- const previous = state.members?.[task.assigneeId];
38
- return [{
39
- command: { type: 'task.assign', payload: { taskId: task.id, expectedRevision: task.revision, assigneeId: assignee.id } },
40
- assignee: memberLabel(assignee),
41
- previous: previous ? memberLabel(previous) : task.assigneeId ?? '未分派',
42
- title: task.title,
43
- }];
44
- }
45
-
46
- export function createSessionTasks({ runtimes, isAvailable, actor }) {
47
- return async function prepareTasks({ action, argument, workspacePath }) {
48
- const input = argument.trim();
49
- const explicit = /^(prj_\S+)(?:\s+|$)/u.exec(input);
50
- const body = input.slice(explicit?.[0].length ?? 0);
51
- if (body === '') fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE[action]}。`);
52
- const usage = USAGE[action].replace('[项目ID]', '项目ID');
53
- const selection = await selectSessionProject({ runtimes, isAvailable, workspacePath, projectId: explicit?.[1], usage });
54
- if (selection.text) return selection;
55
- const { runtime, project } = selection;
56
- const projectId = project.id;
57
- const creating = action === '任务';
58
- const readPlan = () => {
59
- const current = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
60
- if (!current) fail(ERRORS.NOT_FOUND, '项目或工作目录已变化。');
61
- const state = runtime.service.state;
62
- const members = activeSessionMembers(state);
63
- const assigneeFor = (value) => state.members[resolveName(members, value, '执行人')];
64
- const entries = creating ? planTasks(body, assigneeFor) : planAssignment(body, state, assigneeFor);
65
- const ownerId = creating ? current.ownerMemberId ?? current.ownerId : null;
66
- const owner = state.members?.[ownerId];
67
- return { entries, projectName: current.name, owner: owner ? memberLabel(owner) : ownerId };
68
- };
69
- const plan = readPlan();
70
- const signature = JSON.stringify(plan);
71
- const verifyDraft = () => {
72
- let current;
73
- try {
74
- current = readPlan();
75
- } catch (error) {
76
- if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请重新生成任务草稿。`);
77
- throw error;
78
- }
79
- if (JSON.stringify(current) !== signature) fail(ERRORS.REVISION, '项目、执行人或任务已变化,请重新生成任务草稿。');
80
- };
81
- const draft = { actor, projectId, verifyDraft, commands: plan.entries.map(({ command }) => command) };
82
- const preview = await runtime.service.dispatchTaskDraft(draft, { preview: true });
83
- const lines = preview.flatMap(({ task }, index) => {
84
- const { assignee, command, previous } = plan.entries[index];
85
- if (!creating) return [`任务 #${task.number} ${task.title}`, `当前执行人 ${previous}`, `新执行人 ${assignee}`];
86
- if (task.qaChecklist.length !== command.payload.qaChecklist.length) {
87
- fail(ERRORS.INVALID_ARGUMENT, `每张任务最多填写 ${task.qaChecklist.length} 项独立验收。`);
88
- }
89
- return [
90
- `- ${task.title} → ${assignee}`,
91
- ` 交付标准 ${task.resultDefinition}`,
92
- ...(task.qaRequired ? [` 独立验收 ${task.qaChecklist.join(';')}`] : []),
93
- ];
94
- });
95
- return {
96
- projectId, action, cancelMessage: '已取消任务草稿。', details: { tasks: preview.length },
97
- lines: [
98
- `${creating ? '建卡草稿' : '分派草稿'} ${plan.projectName}(${projectId})`,
99
- ...(creating && plan.owner ? [`任务负责人 ${plan.owner}`] : []),
100
- ...lines,
101
- '确认后写入看板,按项目现有规则派发。',
102
- ],
103
- async apply(correlationId) {
104
- const results = await runtime.service.dispatchTaskDraft({ ...draft, correlationId });
105
- return [
106
- creating ? `已建卡并分派 ${results.length} 张任务。` : '已分派原任务。',
107
- ...results.map(({ task }, index) => `- #${task.number} ${task.title} → ${plan.entries[index].assignee}`),
108
- ].join('\n');
109
- },
110
- };
111
- };
112
- }
1
+ import { DomainError, ERRORS, fail } from '../domain/errors.js';
2
+ import { activeSessionMembers, memberLabel, resolveName, selectSessionProject, workspaceProject } from './session-project.js';
3
+
4
+ const USAGE = {
5
+ 任务: '/ai-team 任务 [项目ID] 标题 | 执行人 | 交付标准 [| 独立验收项](一行一张)',
6
+ 分派: '/ai-team 分派 [项目ID] #任务编号 执行人',
7
+ };
8
+
9
+ export const taskHelp = Object.values(USAGE).join('\n');
10
+ export const isTaskAction = (action) => Object.hasOwn(USAGE, action);
11
+
12
+ const FIRST_SAMPLES = {
13
+ docs: { talent: 'tech-writer', output: '一小节文档样稿,包含用途、一个例子和需补充的事实' },
14
+ content: { talent: 'copywriter', output: '一份可审阅的短文样稿,标明读者、要点和事实出处' },
15
+ education: { talent: 'curriculum-designer', output: '一个最小课例,包含学习目标、一题练习、答案和判断依据' },
16
+ video: { talent: 'scriptwriter', output: '一个可审阅的短场景脚本,标明起止内容和素材缺口' },
17
+ game: { talent: 'game-designer', output: '一段最小玩法说明,包含初始状态、一次操作和预期结果' },
18
+ };
19
+
20
+ /** 首发先跑一张可验收的样稿,沿用现有岗位与看板验收。 */
21
+ export function planFirstTask(preset, goal) {
22
+ if (goal === '') fail(ERRORS.INVALID_ARGUMENT, '请填写要交付的目标,例如「整理接口文档」。');
23
+ const sample = preset.source === 'user' ? undefined : FIRST_SAMPLES[preset.id];
24
+ const executors = preset.team.members.filter(({ id, duty }) => duty === 'executor' && id !== preset.team.lead);
25
+ const executor = executors.find(({ talent }) => talent.id === sample?.talent) ?? executors[0];
26
+ if (!executor) fail(ERRORS.INVALID_ARGUMENT, '这个团队没有独立执行人,请选择包含执行岗位的团队。');
27
+ const scope = Array.from(goal.replace(/\s+/gu, ' '));
28
+ const label = scope.slice(0, 80).join('');
29
+ const output = sample?.output ?? '一份最小可审阅的交付样稿,包含一个实例和可以逐项复核的结果';
30
+ return {
31
+ title: `首发样稿 · ${label}${scope.length > 80 ? '…' : ''}`,
32
+ assigneeId: executor.id,
33
+ resultDefinition: `从项目目标中选一个最小样本,基于现有材料提交${output}。交付时注明采用的范围、原始材料出处和待确认项,供复核。`,
34
+ qaRequired: true,
35
+ qaChecklist: ['样稿覆盖所选样本,交付项可逐项核对', '出处可追溯,缺少材料或待确认项已标明'],
36
+ };
37
+ }
38
+
39
+ export function taskDraftLines(task, assignee) {
40
+ return [
41
+ `- ${task.title} → ${assignee}`,
42
+ ` 交付标准 ${task.resultDefinition}`,
43
+ ...(task.qaRequired ? [` 独立验收 ${task.qaChecklist.join(';')}`] : []),
44
+ ];
45
+ }
46
+
47
+ function planTasks(input, assigneeFor) {
48
+ return input.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean).map((line, index) => {
49
+ const fields = line.split(/[||]/u).map((field) => field.trim());
50
+ const [title, executor, resultDefinition, checks] = fields;
51
+ if (fields.length > 4 || !title || !executor || !resultDefinition || checks === '') {
52
+ fail(ERRORS.INVALID_ARGUMENT, `第 ${index + 1} 行须提供标题、执行人和交付标准。用 ${USAGE.任务}。`);
53
+ }
54
+ const qaChecklist = checks?.split(/[;;]/u).map((check) => check.trim()).filter(Boolean) ?? [];
55
+ const assignee = assigneeFor(executor);
56
+ return {
57
+ command: { type: 'task.create', payload: { title, resultDefinition, assigneeId: assignee.id, qaRequired: checks !== undefined, qaChecklist } },
58
+ assignee: memberLabel(assignee),
59
+ };
60
+ });
61
+ }
62
+
63
+ function planAssignment(input, state, assigneeFor) {
64
+ const match = /^(#\d+|tsk_\S+)\s+(.+)$/u.exec(input);
65
+ if (!match) fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE.分派}。`);
66
+ const [, reference, executor] = match;
67
+ const task = reference.startsWith('#')
68
+ ? Object.values(state.tasks).find(({ number }) => number === Number(reference.slice(1)))
69
+ : state.tasks[reference];
70
+ if (!task || task.tombstone) fail(ERRORS.NOT_FOUND, `同一项目中找不到任务 ${reference}。`);
71
+ const assignee = assigneeFor(executor);
72
+ const previous = state.members?.[task.assigneeId];
73
+ return [{
74
+ command: { type: 'task.assign', payload: { taskId: task.id, expectedRevision: task.revision, assigneeId: assignee.id } },
75
+ assignee: memberLabel(assignee),
76
+ previous: previous ? memberLabel(previous) : task.assigneeId ?? '未分派',
77
+ title: task.title,
78
+ }];
79
+ }
80
+
81
+ export function createSessionTasks({ runtimes, isAvailable, actor }) {
82
+ return async function prepareTasks({ action, argument, workspacePath }) {
83
+ const input = argument.trim();
84
+ const explicit = /^(prj_\S+)(?:\s+|$)/u.exec(input);
85
+ const body = input.slice(explicit?.[0].length ?? 0);
86
+ if (body === '') fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE[action]}。`);
87
+ const usage = USAGE[action].replace('[项目ID]', '项目ID');
88
+ const selection = await selectSessionProject({ runtimes, isAvailable, workspacePath, projectId: explicit?.[1], usage });
89
+ if (selection.text) return selection;
90
+ const { runtime, project } = selection;
91
+ const projectId = project.id;
92
+ const creating = action === '任务';
93
+ const readPlan = () => {
94
+ const current = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
95
+ if (!current) fail(ERRORS.NOT_FOUND, '项目或工作目录已变化。');
96
+ const state = runtime.service.state;
97
+ const members = activeSessionMembers(state);
98
+ const assigneeFor = (value) => state.members[resolveName(members, value, '执行人')];
99
+ const entries = creating ? planTasks(body, assigneeFor) : planAssignment(body, state, assigneeFor);
100
+ const ownerId = creating ? current.ownerMemberId ?? current.ownerId : null;
101
+ const owner = state.members?.[ownerId];
102
+ return { entries, projectName: current.name, owner: owner ? memberLabel(owner) : ownerId };
103
+ };
104
+ const plan = readPlan();
105
+ const signature = JSON.stringify(plan);
106
+ const verifyDraft = () => {
107
+ let current;
108
+ try {
109
+ current = readPlan();
110
+ } catch (error) {
111
+ if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请重新生成任务草稿。`);
112
+ throw error;
113
+ }
114
+ if (JSON.stringify(current) !== signature) fail(ERRORS.REVISION, '项目、执行人或任务已变化,请重新生成任务草稿。');
115
+ };
116
+ const draft = { actor, projectId, verifyDraft, commands: plan.entries.map(({ command }) => command) };
117
+ const preview = await runtime.service.dispatchTaskDraft(draft, { preview: true });
118
+ const lines = preview.flatMap(({ task }, index) => {
119
+ const { assignee, command, previous } = plan.entries[index];
120
+ if (!creating) return [`任务 #${task.number} ${task.title}`, `当前执行人 ${previous}`, `新执行人 ${assignee}`];
121
+ if (task.qaChecklist.length !== command.payload.qaChecklist.length) {
122
+ fail(ERRORS.INVALID_ARGUMENT, `每张任务最多填写 ${task.qaChecklist.length} 项独立验收。`);
123
+ }
124
+ return taskDraftLines(task, assignee);
125
+ });
126
+ return {
127
+ projectId, action, cancelMessage: '已取消任务草稿。', details: { tasks: preview.length },
128
+ lines: [
129
+ `${creating ? '建卡草稿' : '分派草稿'} ${plan.projectName}(${projectId})`,
130
+ ...(creating && plan.owner ? [`任务负责人 ${plan.owner}`] : []),
131
+ ...lines,
132
+ '确认后写入看板,按项目现有规则派发。',
133
+ ],
134
+ async apply(correlationId) {
135
+ const results = await runtime.service.dispatchTaskDraft({ ...draft, correlationId });
136
+ return [
137
+ creating ? `已建卡并分派 ${results.length} 张任务。` : '已分派原任务。',
138
+ ...results.map(({ task }, index) => `- #${task.number} ${task.title} → ${plan.entries[index].assignee}`),
139
+ ].join('\n');
140
+ },
141
+ };
142
+ };
143
+ }
@@ -2,11 +2,12 @@ import { realpathSync } from 'node:fs';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { DomainError, ERRORS, fail } from '../domain/errors.js';
4
4
  import { ids, newId } from '../domain/ids.js';
5
+ import { memberLabel } from './session-project.js';
5
6
  import { isRosterAction, rosterHelp } from './session-roster.js';
6
- import { isTaskAction, taskHelp } from './session-tasks.js';
7
+ import { isTaskAction, planFirstTask, taskDraftLines, taskHelp } from './session-tasks.js';
7
8
  import { requireWorkspaceDirectory } from './workspace-path.js';
8
9
 
9
- const HELP = `用 /ai-team 建队 目标 生成草稿。可在目标前加 --team 预设ID 或 --recommend,或在目标末尾加「,配 6 个人」核对编制。按草稿中的命令确认或取消。\n${rosterHelp}\n${taskHelp}`;
10
+ const HELP = `用 /ai-team 建队 目标 生成团队草稿,或用 /ai-team 开工 目标 同时预览团队和一张首发样稿任务。可用 --team 预设ID 指定团队,或在目标末尾加「,配 6 个人」核对编制。建队可用 --recommend 按目标建议预设。按草稿中的命令确认或取消。\n${rosterHelp}\n${taskHelp}`;
10
11
 
11
12
  function sessionWorkspace(session) {
12
13
  const path = session?.header?.cwd;
@@ -16,13 +17,15 @@ function sessionWorkspace(session) {
16
17
  return realpathSync(requireWorkspaceDirectory(path));
17
18
  }
18
19
 
19
- const draftSignature = ({ teamPreset, supplements }) => JSON.stringify([
20
- teamPreset.id, teamPreset.source, teamPreset.dir, teamPreset.team, supplements,
20
+ const draftSignature = ({ teamPreset, supplements, firstTask }) => JSON.stringify([
21
+ teamPreset.id, teamPreset.source, teamPreset.dir, teamPreset.team, supplements, firstTask,
21
22
  ]);
22
23
 
23
- function requestedRosterSize(goal) {
24
- const count = /(?:^|[,;。\r\n])\s*配\s*([+-]?\d+(?:\.\d+)?|[零〇一二两三四五六七八九十]+)\s*(?:[个名位]\s*)?(?:人|成员)\s*[。.!]?$/u.exec(goal.normalize('NFKC'))?.[1];
25
- if (count === undefined) return null;
24
+ function parseRosterSize(goal) {
25
+ const normalized = goal.normalize('NFKC');
26
+ const suffix = /(?:^|[,;。\r\n])\s*配\s*([+-]?\d+(?:\.\d+)?|[零〇一二两三四五六七八九十]+)\s*(?:[个名位]\s*)?(?:人|成员)\s*[。.!]?$/u.exec(normalized);
27
+ if (!suffix) return { requestedMembers: null, taskGoal: goal };
28
+ const count = suffix[1];
26
29
  const digits = '零一二三四五六七八九';
27
30
  const chinese = /^(?:([一二三四五六七八九]?)十)?([零一二三四五六七八九]?)$/u.exec(count.replaceAll('两', '二').replaceAll('〇', '零'));
28
31
  let size = Number(count);
@@ -32,7 +35,7 @@ function requestedRosterSize(goal) {
32
35
  size = 10 * tensDigit + digits.indexOf(ones || '零');
33
36
  }
34
37
  if (!Number.isSafeInteger(size) || size < 1) fail(ERRORS.INVALID_ARGUMENT, '请填写正整数人数,例如「,配 6 个人」。');
35
- return size;
38
+ return { requestedMembers: size, taskGoal: normalized.slice(0, suffix.index).trim() };
36
39
  }
37
40
 
38
41
  /** 只有当前用户会话能确认它的草稿。 */
@@ -48,8 +51,8 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
48
51
  };
49
52
  return {
50
53
  name: 'ai-team',
51
- description: '在会话里建队、调整文渊阁编制及分派任务',
52
- input: { hint: '建队 / 编制 / 调整 / 人才 / 任务 / 分派 / 确认 / 取消' },
54
+ description: '在会话里建队开工、调整文渊阁编制及分派任务',
55
+ input: { hint: '建队 / 开工 / 编制 / 调整 / 人才 / 任务 / 分派 / 确认 / 取消' },
53
56
  async handler({ agent, rawInput, signal }) {
54
57
  const session = agent?.session;
55
58
  const [, action, argument = ''] = /^(\S+)(?:\s+([\s\S]*))?$/.exec(rawInput.trim()) ?? [];
@@ -57,7 +60,8 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
57
60
  try {
58
61
  if (action === undefined || action === '帮助') return { kind: 'success', text: HELP };
59
62
  const prepareAction = isRosterAction(action) ? prepareRoster : isTaskAction(action) ? prepareTasks : null;
60
- if (action !== '建队' && action !== '确认' && action !== '取消' && !prepareAction) return { kind: 'error', text: HELP };
63
+ const kickoff = action === '开工';
64
+ if (!kickoff && action !== '建队' && action !== '确认' && action !== '取消' && !prepareAction) return { kind: 'error', text: HELP };
61
65
  const workspacePath = sessionWorkspace(session);
62
66
  const existing = drafts.get(session);
63
67
  if (prepareAction) {
@@ -65,13 +69,14 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
65
69
  if (signal?.aborted) return { kind: 'error', text: '这次命令已取消。' };
66
70
  return draft.apply ? preview(session, workspacePath, draft) : { kind: 'success', text: draft.text };
67
71
  }
68
- if (action === '建队') {
72
+ if (action === '建队' || kickoff) {
69
73
  const selected = /^--team\s+(\S+)\s+([\s\S]+)$/.exec(argument);
70
- const recommend = /^--recommend(?:\s|$)/.test(argument);
71
- const goal = (recommend ? argument.slice('--recommend'.length) : selected?.[2] ?? argument).trim();
74
+ const recommendFlag = /^--recommend(?:\s|$)/.test(argument);
75
+ const goal = (recommendFlag ? argument.slice('--recommend'.length) : selected?.[2] ?? argument).trim();
72
76
  if (goal === '' || (!selected && argument.startsWith('--team'))) return { kind: 'error', text: HELP };
73
- const requestedMembers = requestedRosterSize(goal);
74
- const input = { name: goal.split(/\r?\n/, 1)[0], goal, workspacePath, team: selected?.[1] ?? '', recommend, requestedMembers };
77
+ const { requestedMembers, taskGoal } = parseRosterSize(goal);
78
+ const recommend = recommendFlag || (kickoff && !selected);
79
+ const input = { name: goal.split(/\r?\n/, 1)[0], goal, workspacePath, team: selected?.[1] ?? '', recommend, requestedMembers, action };
75
80
  const prepareDraft = () => {
76
81
  const project = prepare(input);
77
82
  const count = project.teamPreset.team.members.length;
@@ -81,18 +86,20 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
81
86
  const hint = suggestions.length > 0 ? `\n匹配到这些补位候选,可在目标中明确所需分工。\n${suggestions.join('\n')}` : '';
82
87
  fail(ERRORS.INVALID_ARGUMENT, `目标要求 ${requestedMembers} 人,${team.name}(${id})有 ${count} 人。请用 --team 选择匹配人数的预设,或在文渊阁调整预设后重新建队。${hint}`);
83
88
  }
84
- return project;
89
+ return kickoff ? { ...project, firstTask: planFirstTask(project.teamPreset, taskGoal) } : project;
85
90
  };
86
91
  const proposed = prepareDraft();
87
92
  const members = proposed.teamPreset.team.members;
88
93
  const id = ids.project();
89
94
  const signature = draftSignature(proposed);
90
95
  const supplementEvidence = new Map(proposed.supplements.map(({ member, terms }) => [member.id, terms]));
96
+ const firstTask = proposed.firstTask;
97
+ const taskLines = firstTask ? taskDraftLines(firstTask, memberLabel(members.find(({ id }) => id === firstTask.assigneeId))) : [];
91
98
  return preview(session, workspacePath, {
92
- id, action,
93
- details: { preset: proposed.teamPreset.id, members: members.length, requestedMembers },
99
+ id, action, cancelMessage: kickoff ? '已取消开工草稿。' : '已取消建队草稿。',
100
+ details: { preset: proposed.teamPreset.id, members: members.length, requestedMembers, ...(firstTask ? { firstAssigneeId: firstTask.assigneeId } : {}) },
94
101
  lines: [
95
- `建队草稿 ${input.name}`,
102
+ `${kickoff ? '开工' : '建队'}草稿 ${input.name}`,
96
103
  `目标 ${goal}`,
97
104
  `工作目录 ${workspacePath}`,
98
105
  `预设 ${proposed.teamPreset.team.name}(${proposed.teamPreset.id})`,
@@ -102,7 +109,8 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
102
109
  const terms = supplementEvidence.get(member.id);
103
110
  return `- ${member.name} · ${member.role}${terms ? `(补位依据 ${terms.join('、')})` : ''}`;
104
111
  }),
105
- '确认后创建项目,PMO 自动为关闭状态。',
112
+ ...taskLines,
113
+ firstTask ? '确认后创建项目并派发首发样稿。PMO 自动初始关闭。' : '确认后创建项目,PMO 自动为关闭状态。',
106
114
  ],
107
115
  async apply() {
108
116
  let approved;
@@ -115,7 +123,8 @@ export function sessionTeamCommand({ prepare, create, prepareRoster, prepareTask
115
123
  if (draftSignature(approved) !== signature) {
116
124
  fail(ERRORS.REVISION, '团队预设或匹配证据已更新,请重新生成草稿后再确认。');
117
125
  }
118
- const project = await create(id, approved);
126
+ const { project, task } = await create(id, approved);
127
+ if (task) return `已创建「${project.name}」(${project.id}),首发任务 #${task.number} ${task.title} 已写入并进入派发。可在文渊阁跟踪进展。`;
119
128
  return `已创建「${project.name}」(${project.id})。可在文渊阁查看团队,准备好后开启 PMO 自动。`;
120
129
  },
121
130
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.162",
3
+ "version": "0.4.164",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",