@suifei/dsh-ai-team 0.3.68 → 0.3.70

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.70 — 2026-11-11
4
+
5
+ - **项目全局掌控:启动 / 停止 / 交接**(用户需求):新命令 `project.runState`(Human-only,账本留痕)——**停止**:PMO tick 与事件唤醒双门停止一切派发(正在执行的子任务自然完成,私信仍可);**启动**:空项目显式启动解除 P1a 等待门(Human 点启动即指令)或停止的项目继续开工(下一 tick ≤60s 生效)。新命令 `project.handoff`:按时序生成**交接文档**(Human 指令时序 + 任务全量状态/证据/QA + Thread 摘要 + 接手提示)写入工作目录 `docs/HANDOFF-<时间戳>.md`,账本留痕路径。项目头新增「项目运行 · 开/停止中」与「生成交接文档」按钮(chatGate/archive 旁)。bootstrap 下发 runState。
6
+
7
+ ## 0.3.69 — 2026-11-11
8
+
9
+ 用户实证问题批(docs/phase1-2026-11-10/15-问题清单):
10
+
11
+ - **空项目不再被 PMO 自动开工**:`pmo/continue` 加门——从未有过任务的项目等待 Human 首条指令(新装用户配置目录后不再被自动建卡);
12
+ - **批量取消**:「团队动态」分区新增「取消全部待处理(n)」按钮(逐卡 task.cancel + 成功/失败汇总),免去逐卡点开;
13
+ - **会话标题加项目前缀**:`【项目名】成员名(角色)`——多项目同名成员在 DSH 侧栏可区分;
14
+ - **项目归档(软删)**:新命令 `project.archive`(Human-only,账本留痕)+ 项目头「归档项目」按钮:bootstrap 过滤 archived 项目,成员 DSH 会话不受影响;最后一个 active 项目不可归档;
15
+ - 问题清单与 P2(人员池批量模型配置)/P5(direct-subagent 取证)计划见 docs/phase1-2026-11-10/15。
16
+
3
17
  ## 0.3.68 — 2026-11-11
4
18
 
5
19
  - **【致命】取消任务对话框卡死修复(用户实证三连)**:①根因是 `WorkbenchDialog` 挂载处**漏传 `onDismiss` prop**——settle/cancel 调用 `onDismiss()` 抛 TypeError,`setDialog(null)` 永不执行,对话框永久驻留无法关闭;②「确定没反应」实为 resolve 已执行(任务在后台真实取消)但关框崩溃吞掉了全部反馈;③「理由可留空」的提示与确定按钮禁用矛盾,且 host 域层 `cancelTask/reopenTask` 的 `requireText(reason)` 也强制必填——三层各自为政。现修复:挂载处显式传 `onDismiss: () => setDialog(null)`;settle 先关框后 resolve(后续异步不再阻断);对话框新增 `optional` 语义(理由类输入允许留空);domain 层 cancel/reopen 理由改 `optionalText`(留空记空串,超长边界保留)。新增 cancel/reason 链路测试 2 项(138 总)。
package/client.js CHANGED
@@ -221,7 +221,23 @@ window.__ModuleLoader__.load({
221
221
  chatGateClosedPlaceholder: '对话通道已关闭',
222
222
  chatGateOpened: 'Human 对话通道已开启:私信将直达成员下一轮。',
223
223
  chatGateClosedShort: 'Human 对话通道已关闭。',
224
- routingHint: '成员的原生会话由团队路由驱动,宿主不接受直接输入;请用下方私信与成员对话(下一轮生效)。',
224
+ routingHint: '成员的原生会话由团队路由驱动,宿主不接受直接输入;请用下方私信与成员对话(下一轮生效)。',
225
+ runOn: '项目运行 · 开',
226
+ runOff: '项目运行 · 停止中',
227
+ runStateHint: '停止:当前子任务完成后停止派发(不再派发新任务/心跳/升级);启动:空项目开始或停止的项目继续开工',
228
+ runStarted: '项目已启动:PMO 将在下一个巡检周期开工。',
229
+ runStopped: '项目已停止:正在执行的子任务自然完成后不再派发。',
230
+ handoffBtn: '生成交接文档',
231
+ handoffHint: '按时序生成项目交接文档(Human 指令 + 任务全量),写入工作目录 docs/ 下',
232
+ handoffDone: '交接文档已生成:{path}',
233
+ cancelAllPending: '取消全部待处理({n})',
234
+ cancelAllHint: '批量取消当前全部待处理任务(逐卡取消并汇总结果)',
235
+ cancelAllDone: '批量取消完成:成功 {done} 个,失败 {failed} 个。',
236
+ working: '处理中…',
237
+ archiveProject: '归档项目',
238
+ archiveHint: '归档当前项目(从工作台移除;账本保留,DSH 会话不受影响)',
239
+ archiveConfirmTitle: '归档项目',
240
+ archiveConfirmBody: '将「{name}」从工作台归档移除?账本保留、成员 DSH 会话不受影响。',
225
241
  pmoEnabled: 'PMO 自动已开启。',
226
242
  pmoDisabled: 'PMO 自动已关闭,决策回到收件箱。',
227
243
  notifyTaskCreated: '新 Task 已创建',
@@ -618,7 +634,23 @@ window.__ModuleLoader__.load({
618
634
  chatGateClosedPlaceholder: 'Chat channel closed',
619
635
  chatGateOpened: 'Human chat channel opened: DMs reach members next round.',
620
636
  chatGateClosedShort: 'Human chat channel closed.',
621
- routingHint: 'Member native sessions are driven by team routing; the host rejects direct input. Use the DM below to talk to a member (effective next round).',
637
+ routingHint: 'Member native sessions are driven by team routing; the host rejects direct input. Use the DM below to talk to a member (effective next round).',
638
+ runOn: 'Project run · on',
639
+ runOff: 'Project run · stopping',
640
+ runStateHint: 'Stop: finish the in-flight subtask then halt dispatch (no new tasks/heartbeats/escalations); Start: kick an empty project or resume a stopped one',
641
+ runStarted: 'Project started: PMO begins at the next tick.',
642
+ runStopped: 'Project stopped: in-flight subtasks finish, then dispatch halts.',
643
+ handoffBtn: 'Generate handoff doc',
644
+ handoffHint: 'Generate a chronological handoff document (Human instructions + all task info) into the workspace docs/ folder',
645
+ handoffDone: 'Handoff document written: {path}',
646
+ cancelAllPending: 'Cancel all pending ({n})',
647
+ cancelAllHint: 'Batch-cancel every pending task (one by one, with a summary)',
648
+ cancelAllDone: 'Batch cancel done: {done} ok, {failed} failed.',
649
+ working: 'Working…',
650
+ archiveProject: 'Archive project',
651
+ archiveHint: 'Archive this project (removed from the workbench; ledger kept, DSH sessions unaffected)',
652
+ archiveConfirmTitle: 'Archive project',
653
+ archiveConfirmBody: 'Archive "{name}" and remove it from the workbench? The ledger is kept and member DSH sessions are unaffected.',
622
654
  pmoEnabled: 'PMO auto enabled.',
623
655
  pmoDisabled: 'PMO auto disabled; decisions go back to the inbox.',
624
656
  notifyTaskCreated: 'New Task created',
@@ -1806,8 +1838,9 @@ window.__ModuleLoader__.load({
1806
1838
  }, '⋯'));
1807
1839
  }
1808
1840
 
1809
- function TeamPulse({ t, agents, tasks, onOpen }) {
1841
+ function TeamPulse({ t, agents, tasks, onOpen, onCancelAllPending, cancelBusy }) {
1810
1842
  const active = tasks.filter((task) => ['pending', 'in_progress', 'pending_acceptance'].includes(task.status)).slice(-5);
1843
+ const pendingTasks = tasks.filter((task) => task.status === 'pending');
1811
1844
  const running = agents.filter((agent) => agent.status === 'running');
1812
1845
  const starting = active.length === 0 && tasks.length === 0 && running.length > 0;
1813
1846
  if (active.length === 0 && !starting) return null;
@@ -1821,7 +1854,11 @@ window.__ModuleLoader__.load({
1821
1854
  return h('section', { className: 'at-teampulse', 'aria-label': t('teamPulseTitle') },
1822
1855
  h('div', { className: 'at-teampulsehead' },
1823
1856
  h('span', { className: 'at-teampulsetitle' }, t('teamPulseTitle')),
1824
- h('span', { className: 'at-teampulsecount' }, summary || t('teamPulseWorking'))),
1857
+ h('span', { className: 'at-teampulsecount' }, summary || t('teamPulseWorking')),
1858
+ // P1b:批量取消——Human 无需逐卡点开(用户实证的取消体验痛点)。
1859
+ pendingTasks.length > 0 && onCancelAllPending
1860
+ ? h('button', { className: 'at-btn at-btn-small', type: 'button', onClick: () => onCancelAllPending(pendingTasks), disabled: cancelBusy === true, title: t('cancelAllHint') }, cancelBusy ? t('working') : tf(t, 'cancelAllPending', { n: pendingTasks.length }))
1861
+ : null),
1825
1862
  active.length
1826
1863
  ? h('div', { className: 'at-teampulselist' }, active.map((task) => h('button', {
1827
1864
  key: task.id,
@@ -2843,9 +2880,60 @@ window.__ModuleLoader__.load({
2843
2880
  const selectedTask = tasks.find((task) => task.id === selected) ?? tasks[0] ?? null;
2844
2881
  const thread = threadFor(data, selectedTask?.id);
2845
2882
  const quadrants = deriveQuadrants(data);
2883
+ // P1b:批量取消全部待处理(逐卡 task.cancel,Human-only;汇总结果)。
2884
+ const [cancelAllBusy, setCancelAllBusy] = React.useState(false);
2885
+ async function cancelAllPending(pendingTasks) {
2886
+ if (!Array.isArray(pendingTasks) || pendingTasks.length === 0) return;
2887
+ setCancelAllBusy(true);
2888
+ let done = 0; let failed = 0;
2889
+ try {
2890
+ for (const task of pendingTasks) {
2891
+ try {
2892
+ await runCommand('task.cancel', { taskId: task.id, expectedRevision: task.revision, reason: t('cancelAllHint') });
2893
+ done += 1;
2894
+ } catch { failed += 1; }
2895
+ }
2896
+ sayRight(tf(t, 'cancelAllDone', { done, failed }));
2897
+ await reloadData();
2898
+ } finally {
2899
+ setCancelAllBusy(false);
2900
+ }
2901
+ }
2902
+ async function archiveCurrentProject() {
2903
+ if (!project) return;
2904
+ const answer = await askConfirm(t('archiveConfirmTitle'), tf(t, 'archiveConfirmBody', { name: project.name }));
2905
+ if (answer !== true) return;
2906
+ try {
2907
+ await runCommand('project.archive', { archived: true });
2908
+ say(t('archiveDone'));
2909
+ await reloadData();
2910
+ } catch (error) {
2911
+ sayRight(tf(t, 'sendFailed', { message: error?.message ?? String(error) }));
2912
+ }
2913
+ }
2846
2914
  const inboxItems = (data.inbox ?? []).filter((item) => !isInformationalInboxItem(item));
2847
2915
  // R-13bis:Human↔成员对话门(项目级开关,账本留痕)。
2848
2916
  const chatGateClosed = (project?.chatGate ?? 'open') === 'closed';
2917
+ // P6:项目运行态(启动/停止)+ 交接文档落盘。
2918
+ const runStopped = (project?.runState ?? 'running') === 'stopped';
2919
+ async function toggleRunState() {
2920
+ try {
2921
+ await runCommand('project.runState', { runState: runStopped ? 'running' : 'stopped' });
2922
+ say(runStopped ? t('runStarted') : t('runStopped'));
2923
+ await reloadData();
2924
+ } catch (error) {
2925
+ sayRight(tf(t, 'sendFailed', { message: error?.message ?? String(error) }));
2926
+ }
2927
+ }
2928
+ async function makeHandoff() {
2929
+ if (!project) return;
2930
+ try {
2931
+ const result = await runCommand('project.handoff', {});
2932
+ sayRight(tf(t, 'handoffDone', { path: result.filePath ?? '' }));
2933
+ } catch (error) {
2934
+ sayRight(tf(t, 'sendFailed', { message: error?.message ?? String(error) }));
2935
+ }
2936
+ }
2849
2937
  async function toggleChatGate() {
2850
2938
  try {
2851
2939
  await runCommand('project.chatGate', { gate: chatGateClosed ? 'open' : 'closed' });
@@ -3863,7 +3951,7 @@ window.__ModuleLoader__.load({
3863
3951
  ? h(Situation, { t, quadrants, tasks, onItem: openQuadrantItem, onViewAll: viewQuadrant })
3864
3952
  : h('div', { className: 'at-stream', role: 'tabpanel', id: 'at-panel-main', 'aria-labelledby': 'at-tab-main' },
3865
3953
  h('div', { className: 'at-streaminner', role: 'log', 'aria-live': 'polite', 'aria-label': t('streamAria') },
3866
- h(TeamPulse, { t, agents: data.agents, tasks, onOpen: openTask }),
3954
+ h(TeamPulse, { t, agents: data.agents, tasks, onOpen: openTask, onCancelAllPending: cancelAllPending, cancelBusy: cancelAllBusy }),
3867
3955
  data.stream.length
3868
3956
  ? data.stream.map((item) => h(StreamMessage, {
3869
3957
  key: item.id,
@@ -3919,7 +4007,26 @@ window.__ModuleLoader__.load({
3919
4007
  title: t('chatGateHint'),
3920
4008
  'aria-pressed': !chatGateClosed,
3921
4009
  onClick: () => { void toggleChatGate(); },
3922
- }, !chatGateClosed ? t('chatGateOn') : t('chatGateOff'))) : null,
4010
+ }, !chatGateClosed ? t('chatGateOn') : t('chatGateOff'),
4011
+ h('button', {
4012
+ className: cx('at-pmobtn', !runStopped && 'at-pmo-on'),
4013
+ type: 'button',
4014
+ title: t('runStateHint'),
4015
+ 'aria-pressed': !runStopped,
4016
+ onClick: () => { void toggleRunState(); },
4017
+ }, !runStopped ? t('runOn') : t('runOff')),
4018
+ h('button', {
4019
+ className: 'at-workspacebtn',
4020
+ type: 'button',
4021
+ title: t('handoffHint'),
4022
+ onClick: () => { void makeHandoff(); },
4023
+ }, t('handoffBtn')),
4024
+ h('button', {
4025
+ className: 'at-workspacebtn',
4026
+ type: 'button',
4027
+ title: t('archiveHint'),
4028
+ onClick: () => { void archiveCurrentProject(); },
4029
+ }, t('archiveProject')))) : null,
3923
4030
  inInbox || inPeople ? null : h('div', { className: 'at-tabs', role: 'tablist', 'aria-label': t('tabsAria'), onKeyDown: tabKeyDown },
3924
4031
  h('button', {
3925
4032
  className: cx('at-tab', tab === 'main' && 'at-on'),
package/index.js CHANGED
@@ -41,7 +41,7 @@ export const name = 'ai-team';
41
41
  /** The workbench only makes sense where the Web carrier exists. */
42
42
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
43
43
 
44
- const VERSION = '0.3.68';
44
+ const VERSION = '0.3.70';
45
45
  const PROJECT_ID = 'prj_main';
46
46
  const HUMAN_ID = 'mem_human';
47
47
 
@@ -192,14 +192,16 @@ export function apply(ctx, config = {}) {
192
192
  return null;
193
193
  }
194
194
  };
195
- const memberSessionTitle = (member) => `${member?.name ?? 'Agent'}(${member?.role ?? 'Agent'})`.trim().slice(0, 120);
195
+ // 会话标题带项目前缀:多项目同名成员在 DSH 侧栏无法区分(用户实证)。
196
+ const memberSessionTitle = (member, projectName) => `${projectName ? '【' + projectName + '】' : ''}${member?.name ?? 'Agent'}(${member?.role ?? 'Agent'})`.trim().slice(0, 120);
197
+ const projectNameOf = (projectRuntime) => projectRuntime?.service?.state?.projects?.[projectRuntime?.id]?.name ?? '';
196
198
  const titleMemberSession = async (projectRuntime, member) => {
197
199
  if (member === undefined) return;
198
200
  const sessions = ctx.get('sessions');
199
201
  const titleService = ctx.get('sessionTitle');
200
202
  const session = sessions?.get?.(member.sessionId);
201
203
  if (session === undefined || session === null || typeof titleService?.rename !== 'function') return;
202
- const title = memberSessionTitle(member);
204
+ const title = memberSessionTitle(member, projectNameOf(projectRuntime));
203
205
  try {
204
206
  if (typeof titleService.get === 'function' && titleService.get(session)?.title === title) return;
205
207
  titleService.rename(session, title);
@@ -384,6 +386,9 @@ export function apply(ctx, config = {}) {
384
386
  || null;
385
387
  const wakeFromResult = async (projectRuntime, result, actor = {}) => {
386
388
  if (projectRuntime === null || projectRuntime === undefined) return;
389
+ // P6 停止门(事件 hook 侧):stopped 项目不再派发任何唤醒。
390
+ const gateProject = projectRuntime.service.state.projects?.[projectRuntime.id];
391
+ if (gateProject !== undefined && gateProject.runState === 'stopped') return;
387
392
  const plans = planWakes(projectRuntime.service.state, result, actor);
388
393
  if (plans.length === 0) return;
389
394
  // Window eviction: a key older than this horizon can no longer dedupe
@@ -497,6 +502,9 @@ export function apply(ctx, config = {}) {
497
502
  const state = projectRuntime.service.state;
498
503
  const project = state.projects?.[projectRuntime.id];
499
504
  if (project === undefined || project.pmoAuto === false || project.status === 'archived') return;
505
+ // P6 停止门:stopped 项目停止一切派发(补派/心跳/升级/continue 全停),
506
+ // 正在执行的回合自然完成;唤醒事件 hook 同样检查(见 wakeFromResult)。
507
+ if (project.runState === 'stopped') return;
500
508
  for (const member of Object.values(state.members ?? {})) {
501
509
  if (member.kind === 'agent' && typeof member.sessionId === 'string') {
502
510
  await titleMemberSession(projectRuntime, member);
@@ -606,6 +614,10 @@ export function apply(ctx, config = {}) {
606
614
  }
607
615
  return;
608
616
  }
617
+ // P1a 门更新:空项目且未被 Human 显式启动 → 等待首条指令;显式启动
618
+ // (project.runState=running)即视为指令,解除等待。
619
+ const hasAnyTaskHistory = Object.keys(state.tasks ?? {}).length > 0;
620
+ if (!hasAnyTaskHistory && project.explicitStart !== true) return;
609
621
  const last = pmoLastKick.get(projectRuntime.id) ?? 0;
610
622
  if (now - last < 10 * 60_000) return;
611
623
  pmoLastKick.set(projectRuntime.id, now);
@@ -1,4 +1,5 @@
1
- import { existsSync, readFileSync, statSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import pathDefault from 'node:path';
2
3
  import { ERRORS, fail } from '../domain/errors.js';
3
4
  import { findReportPath, parseDecisionQuestions } from './decision-report.js';
4
5
  import { ids } from '../domain/ids.js';
@@ -38,6 +39,63 @@ function mentionsHuman(body) {
38
39
  * `ledger.append` must update `ledger.state` before resolving (or provide a
39
40
  * synchronous state read after an awaited append).
40
41
  */
42
+ /**
43
+ * P6 交接文档:按时序拼接 Human 指令与全部任务关键信息,写入项目工作
44
+ * 目录(交付给别的工具继续开发);账本留痕记录路径。
45
+ */
46
+ // P6 交接文档生成:Human 指令时序 + 任务全量关键信息,Markdown 落盘。
47
+ function handoffMarkdown(state, project, nowMs) {
48
+ const line = (text) => String(text ?? '').replace(/\r?\n/g, '\n ');
49
+ const out = [];
50
+ out.push(`# 项目交接文档 — ${project.name}`);
51
+ out.push('');
52
+ out.push(`- 生成时间:${new Date(nowMs).toISOString()}`);
53
+ out.push(`- 项目 id:${project.id}`);
54
+ out.push(`- 目标:${project.goal ?? '(未填写)'}`);
55
+ out.push(`- 工作目录:${project.workspacePath}`);
56
+ out.push(`- 运行态:${project.runState === 'stopped' ? '已停止(交接前)' : '运行中'}`);
57
+ out.push('');
58
+ out.push('## 一、Human 指令时序(按账本顺序)');
59
+ out.push('');
60
+ const humanMessages = (state.stream ?? []).filter((entry) => entry.kind === 'human_message');
61
+ if (humanMessages.length === 0) out.push('(无 Human 指令记录)');
62
+ for (const entry of humanMessages) {
63
+ out.push(`- ${new Date(entry.at ?? 0).toISOString()} — ${line(entry.body)}`);
64
+ }
65
+ out.push('');
66
+ out.push('## 二、任务清单(含状态与验收要点)');
67
+ out.push('');
68
+ const tasks = Object.values(state.tasks ?? {}).filter((task) => task.tombstone !== true)
69
+ .sort((left, right) => (left.createdAt ?? 0) - (right.createdAt ?? 0));
70
+ if (tasks.length === 0) out.push('(无任务)');
71
+ for (const task of tasks) {
72
+ out.push(`### #${task.number ?? task.id} ${task.title} — ${task.status}`);
73
+ out.push(`- 结果定义:${line(task.resultDefinition)}`);
74
+ if (task.summary) out.push(`- 提交摘要:${line(task.summary)}`);
75
+ for (const ev of task.evidence ?? []) out.push(`- 证据(${ev.kind}):${line(ev.value)}`);
76
+ if (task.qaChecks?.length) out.push(`- QA 检查:${task.qaChecks.map((c) => `${c.passed ? '✔' : '✘'} ${line(c.text ?? '')}`).join(';')}`);
77
+ if (task.reason) out.push(`- 最近理由:${line(task.reason)}`);
78
+ out.push(`- 责任位:owner=${task.ownerId ?? '—'};assignee=${task.assigneeId ?? '—'};更新于 ${new Date(task.updatedAt ?? 0).toISOString()}`);
79
+ out.push('');
80
+ }
81
+ out.push('## 三、Thread 关键讨论(按任务)');
82
+ out.push('');
83
+ for (const [taskId, thread] of Object.entries(state.threads ?? {})) {
84
+ const entries = thread.entries ?? [];
85
+ if (entries.length === 0) continue;
86
+ out.push(`### Task ${taskId}`);
87
+ for (const entry of entries.slice(-20)) {
88
+ out.push(`- ${new Date(entry.at ?? 0).toISOString()} ${entry.author ?? entry.authorId ?? '—'}:${line(entry.body)}`);
89
+ }
90
+ out.push('');
91
+ }
92
+ out.push('## 四、接手提示');
93
+ out.push('');
94
+ out.push('- 以上内容来自插件账本投影(append-only,时序可信);接手工具可直接在工作目录继续开发。');
95
+ out.push('- 成员的 DSH 会话仍在,如需复用团队请保持项目 runState;如改用其他工具,可停止本项目。');
96
+ return out.join('\n') + '\n';
97
+ }
98
+
41
99
  export class TeamService {
42
100
  /**
43
101
  * @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number, diag?: { append: (row: any) => any } }} options
@@ -81,10 +139,13 @@ export class TeamService {
81
139
  /** One page of workbench state; the UI reads this instead of the ledger. */
82
140
  bootstrap(projectId, threadTaskId) {
83
141
  const state = this.state;
84
- const projects = Object.values(state.projects ?? {}).map((p) => ({
85
- id: p.id, name: p.name, goal: p.goal ?? '', owner: p.ownerName ?? p.ownerMemberId ?? p.ownerId, workspacePath: p.workspacePath ?? '', pmoAuto: p.pmoAuto !== false, active: p.status !== 'archived',
86
- chatGate: p.chatGate === 'closed' ? 'closed' : 'open',
87
- }));
142
+ const projects = Object.values(state.projects ?? {})
143
+ .filter((p) => p.status !== 'archived')
144
+ .map((p) => ({
145
+ id: p.id, name: p.name, goal: p.goal ?? '', owner: p.ownerName ?? p.ownerMemberId ?? p.ownerId, workspacePath: p.workspacePath ?? '', pmoAuto: p.pmoAuto !== false, active: p.status !== 'archived',
146
+ chatGate: p.chatGate === 'closed' ? 'closed' : 'open',
147
+ runState: p.runState === 'stopped' ? 'stopped' : 'running',
148
+ }));
88
149
  const members = Object.values(state.members ?? {}).map((m) => ({
89
150
  id: m.id,
90
151
  name: m.name,
@@ -276,6 +337,9 @@ export class TeamService {
276
337
  case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
277
338
  case 'project.pmo.update': return await this.setProjectPmo(command, payload);
278
339
  case 'project.chatGate': return await this.setProjectChatGate(command, payload);
340
+ case 'project.archive': return await this.setProjectArchive(command, payload);
341
+ case 'project.runState': return await this.setProjectRunState(command, payload);
342
+ case 'project.handoff': return await this.handoffProject(command, payload);
279
343
  case 'stream.post': return await this.postStream(command, payload);
280
344
  case 'member.add': return await this.addMember(command, payload);
281
345
  case 'member.bind': return await this.bindMemberSession(command, payload);
@@ -397,6 +461,58 @@ export class TeamService {
397
461
  return { project: { ...project, chatGate: gate } };
398
462
  }
399
463
 
464
+ // P4:项目归档(软删)——账本 append-only 纪律下不可物理删除;archived
465
+ // 项目从工作台消失(bootstrap 过滤),成员的 DSH 会话不受影响。
466
+ // P6:项目运行态(启动/停止/交接)—— Human 的全局掌控面。
467
+ // 'stopped':PMO tick 停止派发(补派/心跳/升级/continue 全停),正在执行
468
+ // 的回合自然完成;'running'(默认):正常驱动。start 时 explicitStart=true
469
+ // 解除空项目的 P1a 等待门(Human 显式启动即指令)。
470
+ async setProjectRunState(command, payload) {
471
+ const projectId = command.projectId;
472
+ const project = this.state.projects?.[projectId];
473
+ if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
474
+ const runState = payload.runState;
475
+ if (runState !== 'running' && runState !== 'stopped') fail(ERRORS.INVALID_ARGUMENT, 'runState must be running or stopped');
476
+ if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the project run state');
477
+ await this.append(command, 'project/run-state', { projectId, runState, reason: payload.reason ?? '' });
478
+ return { project: { ...project, runState, explicitStart: runState === 'running' ? true : project.explicitStart === true } };
479
+ }
480
+
481
+
482
+ async handoffProject(command, payload) {
483
+ const projectId = command.projectId;
484
+ const project = this.state.projects?.[projectId];
485
+ if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
486
+ if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may request a handoff');
487
+ if (typeof project.workspacePath !== 'string' || project.workspacePath.trim() === '') {
488
+ fail(ERRORS.INVALID_STATE, '项目未配置工作目录,无法落盘交接文档');
489
+ }
490
+ const nowMs = this.now();
491
+ const markdown = handoffMarkdown(this.state, project, nowMs);
492
+ const docsDir = pathDefault.join(project.workspacePath, 'docs');
493
+ mkdirSync(docsDir, { recursive: true });
494
+ const stamp = new Date(nowMs).toISOString().replace(/[:T]/g, '-').slice(0, 19);
495
+ const filePath = pathDefault.join(docsDir, `HANDOFF-${stamp}.md`);
496
+ writeFileSync(filePath, markdown, 'utf8');
497
+ await this.append(command, 'project/handoff', { projectId, filePath, reason: payload.reason ?? '' });
498
+ return { project, filePath };
499
+ }
500
+
501
+ async setProjectArchive(command, payload) {
502
+ const projectId = command.projectId;
503
+ const project = this.state.projects?.[projectId];
504
+ if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
505
+ const archived = payload.archived !== false;
506
+ if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may archive a project');
507
+ if (archived === false && project.status === 'archived') fail(ERRORS.INVALID_STATE, 'archived projects cannot be un-archived in this version');
508
+ const active = Object.values(this.state.projects ?? {}).filter((p) => p.status !== 'archived');
509
+ if (archived && active.length <= 1 && active[0]?.id === projectId) {
510
+ fail(ERRORS.INVALID_STATE, 'cannot archive the last active project');
511
+ }
512
+ await this.append(command, 'project/archived', { projectId, archived, reason: payload.reason ?? '' });
513
+ return { project: { ...project, status: archived ? 'archived' : 'active' } };
514
+ }
515
+
400
516
  async setProjectPmo(command, payload) { const projectId = command.projectId;
401
517
  const project = this.state.projects?.[projectId];
402
518
  if (project === undefined) fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
@@ -686,6 +686,47 @@ export function applyEvent(state, event) {
686
686
  });
687
687
  }
688
688
 
689
+ case 'project/archived': {
690
+ const projectId = textOr(payload.projectId, event.projectId);
691
+ const project = state.projects?.[projectId];
692
+ if (project === undefined || payload.archived !== true) return advance(state, event);
693
+ return advance(state, event, {
694
+ projects: {
695
+ ...state.projects,
696
+ [projectId]: { ...project, status: 'archived', archivedAt: event.at },
697
+ },
698
+ });
699
+ }
700
+
701
+ case 'project/run-state': {
702
+ const projectId = textOr(payload.projectId, event.projectId);
703
+ const project = state.projects?.[projectId];
704
+ if (project === undefined || (payload.runState !== 'running' && payload.runState !== 'stopped')) return advance(state, event);
705
+ return advance(state, event, {
706
+ projects: {
707
+ ...state.projects,
708
+ [projectId]: {
709
+ ...project,
710
+ runState: payload.runState,
711
+ // Human 显式启动 = 指令:解除空项目的 P1a 等待门。
712
+ explicitStart: project.explicitStart === true || payload.runState === 'running',
713
+ },
714
+ },
715
+ });
716
+ }
717
+
718
+ case 'project/handoff': {
719
+ const projectId = textOr(payload.projectId, event.projectId);
720
+ const project = state.projects?.[projectId];
721
+ if (project === undefined) return advance(state, event);
722
+ return advance(state, event, {
723
+ projects: {
724
+ ...state.projects,
725
+ [projectId]: { ...project, lastHandoffAt: event.at, lastHandoffPath: textOr(payload.filePath, null) },
726
+ },
727
+ });
728
+ }
729
+
689
730
  case 'project/workspace-changed': {
690
731
  const projectId = textOr(payload.projectId, event.projectId);
691
732
  const workspacePath = textOr(payload.workspacePath, null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.3.68",
3
+ "version": "0.3.70",
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",