@suifei/dsh-ai-team 0.4.160 → 0.4.162

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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.162 - 2026-12-04
4
+
5
+ - DSH 会话可预览多张任务卡的执行人、交付标准和独立验收项。确认后整批写入账本并沿用项目派发规则。也可为待领取的原任务分派执行人,确认时会重新对照原卡版本。感谢 @buger-gif 提出会话内建卡与分派的场景(#121)。
6
+
7
+ ## 0.4.161 - 2026-12-04
8
+
9
+ - DSH 会话内的增员、改岗位和离队交接可写进同一份编制草稿。确认时核对整组成员和任务,再写入一条账本记录。感谢 @buger-gif 提供会话调整编制与原任务交接的场景(#121)。
10
+ - 只读编制巡检同时记录项目级提交、通过、退回和人工自验次数,可与待验收积压和槽位余量对照。感谢 @buger-gif 提供验收队列巡检案例(#116)。
11
+
3
12
  ## 0.4.160 - 2026-12-04
4
13
 
5
14
  - DSH 会话建队可按目标里明确出现的分工补齐预设,并把补位依据放入同一份建队草稿。确认时重新核对名单。初始化中断后可按确认时的名单补齐。感谢 @buger-gif 提供按目标增补岗位的场景(#121)。
package/README.md CHANGED
@@ -37,6 +37,9 @@
37
37
 
38
38
  ## 最近更新
39
39
 
40
+ - **会话里建卡和分派**(0.4.162)。可核对整批任务的执行人、交付标准和独立验收项,再一次确认到文渊阁。待领取的原卡也能在会话里分派。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
41
+ - **会话一次确认多项编制调整**(0.4.161)。增员、改岗位和原任务交接可进入同一份草稿,核对整组后一次写入。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
42
+ - **巡检验收流量**(0.4.161)。巡检在同一条记录里报告本窗口提交、通过与退回的次数,另列人工自验,方便和待验收积压、槽位余量对照。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
40
43
  - **会话建队按目标补位**(0.4.160)。当目标明确需要的岗位能补齐预设空缺时,同一草稿会列出新增岗位和匹配依据。确认时重新核对整份编制。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
41
44
  - **会话建队人数核对**(0.4.159)。目标可用「配 6 个人」指定人数,草稿列出目标人数和预设编制,人数不一致时先提示调整预设。感谢 [@buger-gif](https://github.com/buger-gif),[#121](https://github.com/suifei/dsh-ai-team/issues/121)。
42
45
  - **实时代理树槽位**(0.4.158)。支持 `capacityOf` 的宿主会在编制巡检中报告已占用和剩余槽位,建议新增成员时可看出同时启动是否需要排队。感谢 [@buger-gif](https://github.com/buger-gif),[#116](https://github.com/suifei/dsh-ai-team/issues/116)。
@@ -155,12 +158,13 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
155
158
 
156
159
  `/ai-team 编制` 显示当前工作区的项目与成员编号。同一工作区有多个项目时,先选项目,使用 `/ai-team 编制 项目ID` 查看成员。用 `/ai-team 人才 [关键词]` 查看人才编号。
157
160
 
158
- 也可以用 `/ai-team 调整` 说清一件事。同一工作区有多个项目时,在句子前加项目编号。同名成员或人才会列出编号供选择。
161
+ 可以用 `/ai-team 调整` 在一句话里说明同一个项目的几项调整。同一工作区有多个项目时,在句子前加项目编号。同名成员或人才会列出编号供选择。
159
162
 
160
163
  ```text
161
164
  /ai-team 调整 给团队加一位文案
162
165
  /ai-team 调整 把校书的岗位改为文档协调
163
166
  /ai-team 调整 让墨痕把任务交给校书后离队
167
+ /ai-team 调整 给团队加一位文案,并把校书的岗位改为文档协调,再让墨痕把任务交给校书后离队
164
168
  ```
165
169
 
166
170
  ```text
@@ -169,7 +173,19 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
169
173
  /ai-team 离队 项目ID 成员ID [接手人ID]
170
174
  ```
171
175
 
172
- 变更命令先显示草稿,用同一会话里的确认命令写入。有未收口任务时须指定项目内的接手人,插件交接原卡后再将成员移入人才池。草稿生成后若成员、人才或任务有变化,重新预览再确认。
176
+ 变更命令先显示草稿,用同一会话里的确认命令写入。有未收口任务时须指定项目内会留队的接手人。多项调整共用一条账本记录,确认时重新核对成员、人才与原任务。有冲突或草稿过期时,先重新预览再确认。
177
+
178
+ ### 从 DSH 会话建卡和分派
179
+
180
+ 用 `/ai-team 任务` 提交首批任务草稿。每行一张卡,用竖线依次分隔标题、执行人和交付标准。第四列可填写独立验收项,多项用分号隔开。执行人用在队成员的名字或编号。
181
+
182
+ ```text
183
+ /ai-team 任务
184
+ 整理接口示例 | 墨痕 | 提供两组请求和响应 | 字段有出处;示例可复核
185
+ 统一术语 | 校书 | 列出术语和原文出处
186
+ ```
187
+
188
+ 同一工作区有多个项目时,在 `任务` 或 `分派` 后写明项目编号。用 `/ai-team 分派 #2 校书` 为看板上待领取的原卡更换执行人。两种命令都在当前会话里显示草稿,确认后由项目现有规则派发。首发试跑项目继续在「首发试跑」推进。
173
189
 
174
190
  ### 按蓝图试跑
175
191
 
@@ -183,7 +199,7 @@ const svg = HashAvatar.svg('墨渊', { gender: 'male', age: 'middle', race: 'asi
183
199
 
184
200
  ### 只读编制巡检试跑
185
201
 
186
- 在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。
202
+ 在当前 DSH profile 的 `ai-team` 配置中设 `staffingReviewMinutes: 180` 和 `diagLevel: full` 后,启用 PMO 自动的运行中普通项目会随现有巡检周期采样,每个时间窗口记录一次。`staffingReviewMinutes: 0`(默认)关闭采样。诊断日志中的 `pmo.staffing.review` 包含岗位已分配队列、可认领与待验收队列、最长及平均等待,以及采样窗口内每位成员的提交、验收和退回。返工率按退回的本窗口提交除以本窗口提交数计算,零样本为空。项目级 `acceptanceActivity` 按 `since`、`now` 内的账本记录计数,包含已离队成员和人工处理的结果。通过次数包含人工自验,日志另外列出自验次数。
187
203
 
188
204
  巡检还会记录没有合格验收人的任务 ID 和在队成员运行回合数。宿主提供 `capacityOf` 时,`host-live` 表示当前代理树的实时槽位快照,`occupiedSlots` 和 `remainingSlots` 分别记录占用和余量。`host` 表示这棵树的容量回执,`default` 表示默认估计。这两种来源的占用和余量字段为空。宿主释放槽位后,插件优先补投本树排队最久的成员。加人建议会提示采样时的槽位不足,长期无人可验收的任务也会进入现有补位建议。
189
205
 
@@ -434,7 +450,7 @@ round-19 DeepSeek + Zhipu 双 provider
434
450
  | 贡献者 | 贡献 | 带来的进展 |
435
451
  |---|---|---|
436
452
  | [@idontlikefruit](https://github.com/idontlikefruit) | 受阻状态的三组复现输入 [#115](https://github.com/suifei/dsh-ai-team/issues/115) | 统一看板徽标、读屏和分组统计的受阻判定,保留历史依赖 |
437
- | [@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 会话按目标建议预设、核对人数和补位依据,确认建队及原任务交接 |
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 会话按目标建议预设、核对人数和补位依据,一次确认多项编制调整、原任务交接或首批任务分派 |
438
454
  | [@Estelle00](https://github.com/Estelle00) | DSH 0.2.3 启动 503 的复现和桌面验证 [#122](https://github.com/suifei/dsh-ai-team/issues/122) | 接入新版会话鉴权接口,恢复工作台初始化,并在 Alpha 宿主验证看板登录 |
439
455
  | [@phm101299-ui](https://github.com/phm101299-ui) | PMO 冷恢复的复现、根因和桌面验证 [#112](https://github.com/suifei/dsh-ai-team/issues/112) | 让原 PMO 在宿主重启后带着模型路由继续工作,保留成员关系和任务 |
440
456
  | [@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
@@ -23,6 +23,7 @@ import { resolveDefaultWorkspace } from './lib/host/default-workspace.js';
23
23
  import { hostPlatform, requireWorkspaceDirectory, workspaceExample } from './lib/host/workspace-path.js';
24
24
  import { sessionTeamCommand } from './lib/host/session-team-command.js';
25
25
  import { createSessionRoster } from './lib/host/session-roster.js';
26
+ import { createSessionTasks } from './lib/host/session-tasks.js';
26
27
  import { migrateLegacyNamespace, resolveProfile } from './lib/ledger/namespace.js';
27
28
  import { ids } from './lib/domain/ids.js';
28
29
  import { ERRORS, fail } from './lib/domain/errors.js';
@@ -2590,6 +2591,16 @@ export function apply(ctx, config = {}) {
2590
2591
  diag.append({ ev: 'member.activation.disposed', memberId, sessionId, reason });
2591
2592
  }
2592
2593
 
2594
+ const sessionProjectAccess = {
2595
+ async runtimes() {
2596
+ await ready;
2597
+ if (disposed || booted === null) fail(ERRORS.INVALID_STATE, '文渊阁账本尚未就绪。');
2598
+ return booted.runtimes.values();
2599
+ },
2600
+ isAvailable: (runtime) => !disposed && projectRuntime(runtime.id) === runtime
2601
+ && !peopleProjectIsArchived(booted.registry.list().find(({ id }) => id === runtime.id), runtime),
2602
+ actor: { kind: 'human', memberId: HUMAN_ID },
2603
+ };
2593
2604
  const nativeTeamCommand = sessionTeamCommand({
2594
2605
  prepare(input) {
2595
2606
  const project = projectInput(input);
@@ -2620,17 +2631,11 @@ export function apply(ctx, config = {}) {
2620
2631
  },
2621
2632
  create: async (id, input) => (await activateProject(id, { ...input, pmoAuto: false })).service.state.projects[id],
2622
2633
  prepareRoster: createSessionRoster({
2623
- async runtimes() {
2624
- await ready;
2625
- if (disposed || booted === null) fail(ERRORS.INVALID_STATE, '文渊阁账本尚未就绪。');
2626
- return booted.runtimes.values();
2627
- },
2628
- isAvailable: (runtime) => !disposed && projectRuntime(runtime.id) === runtime
2629
- && !peopleProjectIsArchived(booted.registry.list().find(({ id }) => id === runtime.id), runtime),
2634
+ ...sessionProjectAccess,
2630
2635
  catalog: () => talentCatalog(diag),
2631
- actor: { kind: 'human', memberId: HUMAN_ID },
2632
2636
  disposeMemberActivation,
2633
2637
  }),
2638
+ prepareTasks: createSessionTasks(sessionProjectAccess),
2634
2639
  diag,
2635
2640
  });
2636
2641
  const registerSessionCommand = (scoped) => {
package/lib/host/pmo.js CHANGED
@@ -259,6 +259,15 @@ function tasksWithoutReviewer(state, tasks) {
259
259
  return tasks.filter((task) => !members.some((member) => isReviewCandidate(member, task, state)));
260
260
  }
261
261
 
262
+ const ACCEPTANCE_ACTIVITY = new Map([
263
+ ['task/submitted', 'submitted'],
264
+ ['task/accepted', 'accepted'],
265
+ ['review/accepted', 'accepted'],
266
+ ['review/human_self_accept', 'accepted'],
267
+ ['task/changes-requested', 'returned'],
268
+ ['review/changes-requested', 'returned'],
269
+ ]);
270
+
262
271
  /** A read-only rollup of the existing queues and observed submissions in this window. */
263
272
  export function staffingReview(state, events, { now, intervalMs, capacity, capacitySource = null, occupiedSlots = null, remainingSlots = null, inTurn, advice = [], suppressed = [] }) {
264
273
  const since = now - intervalMs;
@@ -266,17 +275,22 @@ export function staffingReview(state, events, { now, intervalMs, capacity, capac
266
275
  .filter((member) => member.kind === 'agent' && member.status !== 'retired')
267
276
  .map(({ id, role, status }) => [id, { id, role: role || '未设置岗位', status, submitted: 0, accepted: 0, returned: 0 }]));
268
277
  const submissions = new Map();
278
+ const acceptanceActivity = { submitted: 0, accepted: 0, returned: 0, humanSelfAccepted: 0 };
269
279
  for (const event of events) {
270
280
  if (!Number.isFinite(event.at) || event.at < since || event.at > now) continue;
271
- const taskId = event.payload?.taskId;
272
- if (typeof taskId !== 'string') continue;
273
- if (event.type === 'task/submitted') {
281
+ const activity = ACCEPTANCE_ACTIVITY.get(event.type);
282
+ const taskId = event.payload?.taskId ?? event.payload?.id;
283
+ if (activity === undefined || typeof taskId !== 'string' || taskId === '') continue;
284
+ acceptanceActivity[activity] += 1;
285
+ if (activity === 'submitted') {
274
286
  const member = event.actor?.kind === 'agent' ? people.get(event.actor.memberId) : undefined;
275
287
  submissions.set(taskId, member);
276
288
  if (member) member.submitted += 1;
277
- } else if (event.type === 'task/accepted' || event.type === 'task/changes-requested') {
289
+ } else {
290
+ const selfAccepted = activity === 'accepted' && (event.type === 'review/human_self_accept' || event.payload?.selfExecuted === true);
278
291
  const member = submissions.get(taskId);
279
- if (member) member[event.type === 'task/accepted' ? 'accepted' : 'returned'] += 1;
292
+ if (selfAccepted) acceptanceActivity.humanSelfAccepted += 1;
293
+ else if (member) member[activity] += 1;
280
294
  submissions.delete(taskId);
281
295
  }
282
296
  }
@@ -302,6 +316,7 @@ export function staffingReview(state, events, { now, intervalMs, capacity, capac
302
316
  since, now, capacity, capacitySource, capacityScope: 'agent-tree', occupiedSlots, remainingSlots, activeMemberTurns,
303
317
  claimable: waitingSummary(claimableTasks(state, open), now),
304
318
  pendingAcceptance: waitingSummary(waitingReview, now),
319
+ acceptanceActivity,
305
320
  pendingAcceptanceWithoutReviewer: { ...waitingSummary(missingReviewers, now), taskIds: missingReviewers.map(({ id }) => id) },
306
321
  roles: [...groups.values()].map(({ assigned, ...group }) => ({ ...group, assignedQueue: waitingSummary(assigned, now) })),
307
322
  advice,
@@ -23,7 +23,7 @@ import { appendReply, createThread } from '../domain/thread.js';
23
23
  import { boardView, projectOverview, quadrantsView, taskCard } from './views.js';
24
24
  import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-config.js';
25
25
  import { parseAvatar } from '../domain/avatar.js';
26
- import { MEMBER_STATUS, isBoardIdle } from '../ledger/fold.js';
26
+ import { MEMBER_STATUS, ROSTER_BATCH_EVENT, TASK_BATCH_EVENT, applyEvent, isBoardIdle, isDraftChange } from '../ledger/fold.js';
27
27
 
28
28
  const MEMBER_STATUS_VALUES = new Set(Object.values(MEMBER_STATUS));
29
29
  import { checkPersonality, isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
@@ -35,6 +35,8 @@ import {
35
35
  } from '../domain/team-blueprint.js';
36
36
 
37
37
  const PMO_ACTOR = Object.freeze({ kind: 'system', memberId: 'mem_pmo' });
38
+ const ROSTER_COMMANDS = new Set(['member.add', 'member.profile.update', 'member.leave']);
39
+ const TASK_DRAFT_COMMANDS = new Set(['task.create', 'task.assign']);
38
40
  const BLUEPRINT_START_STAGES = ['sample', 'improve', 'rerun'];
39
41
  const BLUEPRINT_AGENT_COMMANDS = new Set([
40
42
  'stream.post', 'thread.post', 'task.claim', 'task.submit', 'task.accept', 'task.request_changes', 'decision.request',
@@ -544,6 +546,76 @@ export class TeamService {
544
546
  }
545
547
  }
546
548
 
549
+ /** 会话确认的编制变更。多项变更共享一条持久事件,单项沿用原命令。 */
550
+ dispatchRoster(draft) {
551
+ return this.#dispatchSessionDraft(draft, ROSTER_BATCH_EVENT, ROSTER_COMMANDS, '编制');
552
+ }
553
+
554
+ dispatchTaskDraft(draft, { preview = false } = {}) {
555
+ return this.#dispatchSessionDraft(draft, TASK_BATCH_EVENT, TASK_DRAFT_COMMANDS, '任务', preview);
556
+ }
557
+
558
+ async #dispatchSessionDraft({ actor, projectId, correlationId, verifyDraft, commands }, batchType, allowed, label, preview = false) {
559
+ if (actor?.kind !== 'human' || actor.memberId !== this.humanId() || typeof verifyDraft !== 'function') {
560
+ fail(ERRORS.UNAUTHORIZED, `${label}草稿需要由本项目的用户确认`);
561
+ }
562
+ if (projectId !== this.ledger.projectId) fail(ERRORS.NOT_FOUND, `${label}草稿对应的项目已变化`);
563
+ if (!Array.isArray(commands) || commands.length === 0 || commands.some((command) => !allowed.has(command?.type))) {
564
+ fail(ERRORS.INVALID_ARGUMENT, `${label}草稿包含不支持的命令`);
565
+ }
566
+ const scope = { actor, projectId, correlationId, verifyDraft };
567
+ if (preview) return (await this.#stageSessionDraft(commands, scope, batchType)).results;
568
+ if (commands.length === 1) {
569
+ const [{ type, payload }] = commands;
570
+ return [await this.dispatch({ ...scope, type, payload })];
571
+ }
572
+
573
+ return this.runExclusive(async () => {
574
+ verifyDraft();
575
+ const { at, changes, expectedHeadSeq, results } = await this.#stageSessionDraft(commands, scope, batchType);
576
+ verifyDraft();
577
+ try {
578
+ await this.ledger.append({ type: batchType, projectId, actor, correlationId, at, payload: { changes } }, { expectedHeadSeq });
579
+ } catch (error) {
580
+ if (error?.code === 'E_LEDGER_HEAD_CHANGED') fail(ERRORS.REVISION, '项目在确认期间已有新变化,请重新生成草稿。');
581
+ if (error?.code === 'E_EVENT_TOO_LARGE') fail(ERRORS.INVALID_ARGUMENT, `这份${label}草稿涉及的记录过多,请分成较小的草稿。`);
582
+ throw error;
583
+ }
584
+ const ev = batchType === ROSTER_BATCH_EVENT ? 'session.roster.batch.committed' : 'session.task.batch.committed';
585
+ this.diag?.append({ ev, projectId, draftId: correlationId, commands: commands.length, changes: changes.length });
586
+ return results;
587
+ });
588
+ }
589
+
590
+ async #stageSessionDraft(commands, { actor, projectId, correlationId }, batchType) {
591
+ let stagedState = this.state;
592
+ const expectedHeadSeq = stagedState.lastSeq;
593
+ const at = this.now();
594
+ const changes = [];
595
+ const staging = new TeamService({
596
+ now: () => at,
597
+ memberConfigPolicy: this.memberConfigPolicy,
598
+ ledger: {
599
+ projectId,
600
+ get state() { return stagedState; },
601
+ async append(draft) {
602
+ const change = { type: draft.type, payload: draft.payload };
603
+ if (!isDraftChange(batchType, change)) fail(ERRORS.INVALID_STATE, '草稿产生了不支持的账本变更');
604
+ const event = { ...draft, projectId, seq: stagedState.lastSeq + 1 };
605
+ stagedState = applyEvent(stagedState, event);
606
+ changes.push(change);
607
+ return event;
608
+ },
609
+ },
610
+ });
611
+ const results = [];
612
+ for (const { type, payload } of commands) {
613
+ // 草稿复核在外层完成。离队命令继续采用经复核的交接规则。
614
+ results.push(await staging.dispatch({ type, payload, actor, projectId, correlationId, verifyDraft() {} }));
615
+ }
616
+ return { at, changes, expectedHeadSeq, results };
617
+ }
618
+
547
619
  checkBlueprintCommand(command, payload) {
548
620
  const project = this.state.projects?.[command.projectId];
549
621
  if (!project?.blueprint) return;
@@ -0,0 +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,12 +1,11 @@
1
- import { realpathSync } from 'node:fs';
2
- import { isAbsolute } from 'node:path';
3
1
  import { listTalents } from '../domain/catalog.js';
4
2
  import { DomainError, ERRORS, fail } from '../domain/errors.js';
5
3
  import { unfinishedTasksFor } from '../domain/member-profile.js';
4
+ import { activeSessionMembers, memberLabel, resolveName, selectSessionProject, workspaceProject } from './session-project.js';
6
5
 
7
6
  const USAGE = {
8
7
  编制: '/ai-team 编制 [项目ID]',
9
- 调整: '/ai-team 调整 [项目ID] 一句话',
8
+ 调整: '/ai-team 调整 [项目ID] 逐项说明编制调整',
10
9
  人才: '/ai-team 人才 [关键词]',
11
10
  增员: '/ai-team 增员 项目ID 人才ID',
12
11
  改岗位: '/ai-team 改岗位 项目ID 成员ID 新岗位',
@@ -16,38 +15,16 @@ const USAGE = {
16
15
  export const rosterHelp = Object.values(USAGE).join('\n');
17
16
  export const isRosterAction = (action) => Object.hasOwn(USAGE, action);
18
17
 
19
- function workspaceProject(runtime, workspacePath) {
20
- const project = runtime.service.state.projects?.[runtime.id];
21
- if (!project || project.status === 'archived' || typeof project.workspacePath !== 'string' || !isAbsolute(project.workspacePath)) return null;
22
- try {
23
- return realpathSync(project.workspacePath) === workspacePath ? project : null;
24
- } catch {
25
- return null;
26
- }
27
- }
28
-
29
- const memberLabel = (member) => `${member.name}(${member.id})`;
18
+ const ROSTER_SENTENCE_HELP = '请明确每项调整。示例:给团队加一位文案,并把校书的岗位改为文档协调。';
30
19
 
31
- function resolveName(entries, value, label, aliases = (entry) => [entry.name]) {
32
- const name = value.trim();
33
- const direct = entries.find(({ id }) => id === name);
34
- if (direct) return direct.id;
35
- const matches = entries.filter((entry) => aliases(entry).includes(name));
36
- if (matches.length === 1) return matches[0].id;
37
- if (matches.length === 0) fail(ERRORS.NOT_FOUND, `找不到${label}「${name}」,请核对名字或编号。`);
38
- fail(ERRORS.CONFLICT, `${label}「${name}」有多个候选,请使用编号。\n${matches.map(memberLabel).join('\n')}`);
39
- }
40
-
41
- function readRosterSentence(sentence, runtime, catalog) {
42
- const statement = sentence.trim().replace(/[。!!.]$/u, '');
43
- const hint = '一句话只能准备一项调整。示例:给团队加一位文案;把校书的岗位改为文档协调;让墨痕把任务交给校书后离队。';
44
- if (/[。;;\r\n]|(?:并|同时|然后)\s*(?:给|把|让|再|加|离队|改)/u.test(statement)) fail(ERRORS.INVALID_ARGUMENT, hint);
20
+ function readRosterAction(statement, runtime, catalog) {
21
+ if (/[。;;\r\n]|(?:并|同时|然后)\s*(?:给|把|让|再|加|离队|改)/u.test(statement)) fail(ERRORS.INVALID_ARGUMENT, ROSTER_SENTENCE_HELP);
45
22
  const hire = /^给团队加(?:一位|一名)\s*(.+)$/u.exec(statement);
46
23
  if (hire) {
47
24
  const target = resolveName(listTalents(catalog()), hire[1], '人才', ({ name, role }) => [name, role]);
48
25
  return { action: '增员', target, value: '' };
49
26
  }
50
- const members = Object.values(runtime.service.state.members ?? {}).filter(({ kind, status }) => kind === 'agent' && status !== 'retired');
27
+ const members = activeSessionMembers(runtime.service.state);
51
28
  const findMember = (name) => resolveName(members, name, '成员');
52
29
  const edit = /^把(.+?)的岗位改为\s*(.+)$/u.exec(statement);
53
30
  if (edit) return { action: '改岗位', target: findMember(edit[1]), value: edit[2].trim() };
@@ -55,7 +32,13 @@ function readRosterSentence(sentence, runtime, catalog) {
55
32
  if (handoff) return { action: '离队', target: findMember(handoff[1]), value: findMember(handoff[2]) };
56
33
  const leave = /^让(.+?)离队$/u.exec(statement);
57
34
  if (leave) return { action: '离队', target: findMember(leave[1]), value: '' };
58
- fail(ERRORS.INVALID_ARGUMENT, hint);
35
+ fail(ERRORS.INVALID_ARGUMENT, ROSTER_SENTENCE_HELP);
36
+ }
37
+
38
+ function readRosterSentence(sentence, runtime, catalog) {
39
+ const statement = sentence.trim().replace(/[。!!.]$/u, '');
40
+ const separator = /(?:[,,;;。\r\n]+\s*|[,,;;。]?\s*(?:并且|同时|然后|另外|并|再|和)(?:\s*再)?\s*)(?=给团队加|把|让)/u;
41
+ return statement.split(separator).map((part) => readRosterAction(part.trim(), runtime, catalog));
59
42
  }
60
43
 
61
44
  function describeRoster(runtime, project) {
@@ -110,6 +93,29 @@ function planChange(runtime, action, target, value, catalog) {
110
93
  };
111
94
  }
112
95
 
96
+ function checkRosterActions(actions) {
97
+ const targets = new Set();
98
+ const leaving = new Set(actions.filter(({ action }) => action === '离队').map(({ target }) => target));
99
+ for (const { action, target, value } of actions) {
100
+ if (action === '增员') continue;
101
+ if (targets.has(target)) fail(ERRORS.CONFLICT, `同一草稿中有多项调整涉及成员 ${target},请明确保留哪一项。`);
102
+ targets.add(target);
103
+ if (action === '离队' && leaving.has(value)) fail(ERRORS.CONFLICT, '同一草稿中接手人也要离队,请指定会留队的成员。');
104
+ }
105
+ }
106
+
107
+ function planChanges(runtime, actions, catalog) {
108
+ const plans = actions.map(({ action, target, value }) => planChange(runtime, action, target, value, catalog));
109
+ const transferred = new Set();
110
+ for (const { taskRevisions = [] } of plans) {
111
+ for (const [id] of taskRevisions) {
112
+ if (transferred.has(id)) fail(ERRORS.CONFLICT, '同一张原任务涉及多个离队成员,请先明确交接顺序。');
113
+ transferred.add(id);
114
+ }
115
+ }
116
+ return plans;
117
+ }
118
+
113
119
  export function createSessionRoster({ runtimes, isAvailable, catalog, actor, disposeMemberActivation }) {
114
120
  return async function prepareRoster({ action: requested, argument, workspacePath }) {
115
121
  if (requested === '人才') {
@@ -126,54 +132,55 @@ export function createSessionRoster({ runtimes, isAvailable, catalog, actor, dis
126
132
  if (wrongTarget || (requested === '增员' && rest !== '') || (requested === '改岗位' && rest === '')
127
133
  || (requested === '离队' && /\s/.test(rest))) fail(ERRORS.INVALID_ARGUMENT, `用 ${USAGE[requested]}。`);
128
134
  }
129
- const options = [];
130
- for (const runtime of await runtimes()) {
131
- const project = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
132
- if (project !== null) options.push({ runtime, project });
133
- }
134
- if (requestedProject === undefined && options.length > 1) {
135
- const usage = requestedSentence ? '/ai-team 调整 项目ID 一句话' : '/ai-team 编制 项目ID';
136
- return { text: [`同一工作区有多个项目,请使用 ${usage}。`, ...options.map(({ project }) => `- ${project.id} · ${project.name}`)].join('\n') };
137
- }
138
- const selection = requestedProject === undefined ? options[0] : options.find(({ project }) => project.id === requestedProject);
139
- if (!selection) fail(ERRORS.NOT_FOUND, '当前会话的工作区找不到该项目。使用 /ai-team 编制 查看同一工作区的项目。');
135
+ const usage = requestedSentence ? '/ai-team 调整 项目ID 一句话' : '/ai-team 编制 项目ID';
136
+ const selection = await selectSessionProject({ runtimes, isAvailable, workspacePath, projectId: requestedProject, usage });
137
+ if (selection.text) return selection;
140
138
  const { runtime, project } = selection;
141
139
  if (requested === '编制') return { text: describeRoster(runtime, project) };
142
- const { action, target, value } = requestedSentence
140
+ const actions = requestedSentence
143
141
  ? readRosterSentence(requestedProject ? input.slice(first.length) : input, runtime, catalog)
144
- : { action: requested, target: supplied, value: rest };
142
+ : [{ action: requested, target: supplied, value: rest }];
145
143
  const projectId = project.id;
146
-
147
- const change = planChange(runtime, action, target, value, catalog);
148
- const command = { type: change.type, payload: change.payload, actor, projectId };
149
- runtime.service.checkBlueprintCommand(command, change.payload);
150
- const approved = JSON.stringify(change);
144
+ checkRosterActions(actions);
145
+ const changes = planChanges(runtime, actions, catalog);
146
+ const commands = changes.map(({ type, payload }) => ({ type, payload }));
147
+ for (const { type, payload } of commands) runtime.service.checkBlueprintCommand({ type, actor, projectId }, payload);
148
+ const approved = JSON.stringify(changes);
149
+ const verifyDraft = () => {
150
+ const currentProject = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
151
+ if (!currentProject || currentProject.name !== project.name) {
152
+ fail(ERRORS.REVISION, '项目或工作目录已变化,请重新生成草稿。');
153
+ }
154
+ let current;
155
+ try {
156
+ current = planChanges(runtime, actions, catalog);
157
+ } catch (error) {
158
+ if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请核对编制后重新生成草稿。`);
159
+ throw error;
160
+ }
161
+ if (JSON.stringify(current) !== approved) fail(ERRORS.REVISION, '成员、人才或任务已变化,请重新生成草稿。');
162
+ };
163
+ const grouped = changes.length > 1;
151
164
  return {
152
- projectId, action,
153
- lines: [`编制草稿 ${project.name}(${projectId})`, ...change.lines],
165
+ projectId, action: grouped ? '调整' : actions[0].action, details: { changes: changes.length },
166
+ lines: [`编制草稿 ${project.name}(${projectId})`, ...changes.flatMap(({ lines }) => lines)],
154
167
  async apply(draftId) {
155
- const result = await runtime.service.dispatch({
156
- ...command, correlationId: draftId,
157
- verifyDraft() {
158
- const currentProject = isAvailable(runtime) ? workspaceProject(runtime, workspacePath) : null;
159
- if (!currentProject || currentProject.name !== project.name) {
160
- fail(ERRORS.REVISION, '项目或工作目录已变化,请重新生成草稿。');
161
- }
162
- let current;
163
- try {
164
- current = planChange(runtime, action, target, value, catalog);
165
- } catch (error) {
166
- if (error instanceof DomainError) fail(ERRORS.REVISION, `${error.message} 请核对编制后重新生成草稿。`);
167
- throw error;
168
- }
169
- if (JSON.stringify(current) !== approved) fail(ERRORS.REVISION, '成员、人才或任务已变化,请重新生成草稿。');
170
- },
168
+ const committed = await runtime.service.dispatchRoster({
169
+ commands, actor, projectId, correlationId: draftId, verifyDraft,
171
170
  });
172
- if (action === '离队') {
173
- await disposeMemberActivation(runtime, target, command.type);
174
- return `已将${memberLabel(result.member)}移入人才池,交接了 ${result.transferredTasks?.length ?? 0} 张原任务。`;
171
+ const lines = [];
172
+ for (const [index, result] of committed.entries()) {
173
+ const { action, target } = actions[index];
174
+ if (action === '离队') {
175
+ await disposeMemberActivation(runtime, target, commands[index].type);
176
+ lines.push(`已将${memberLabel(result.member)}移入人才池,交接了 ${result.transferredTasks?.length ?? 0} 张原任务。`);
177
+ } else if (action === '增员') {
178
+ lines.push(`已添加${memberLabel(result.member)}。`);
179
+ } else {
180
+ lines.push(`已将${memberLabel(result.member)}的岗位更新为「${result.member.role}」。`);
181
+ }
175
182
  }
176
- return action === '增员' ? `已添加${memberLabel(result.member)}。` : `已将${memberLabel(result.member)}的岗位更新为「${result.member.role}」。`;
183
+ return grouped ? [`已确认 ${changes.length} 项编制调整。`, ...lines].join('\n') : lines[0];
177
184
  },
178
185
  };
179
186
  };
@@ -0,0 +1,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
+ 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
+ }