@suifei/dsh-ai-team 0.4.24 → 0.4.28

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/client.js +30 -10
  3. package/index.js +300 -42
  4. package/lib/domain/task.js +6 -0
  5. package/lib/host/decision-report.js +16 -2
  6. package/lib/host/member-tools.js +7 -5
  7. package/lib/host/project-registry.js +19 -2
  8. package/lib/host/service.js +172 -35
  9. package/lib/host/views.js +23 -1
  10. package/lib/host/waker.js +7 -3
  11. package/lib/host/weekly-view.js +3 -0
  12. package/lib/ledger/checkpoint.js +11 -0
  13. package/lib/ledger/writer.js +164 -23
  14. package/lib/runtime/failure-policy.js +15 -4
  15. package/lib/runtime/host-agent.js +38 -10
  16. package/lib/runtime/host-repair.js +70 -0
  17. package/lib/runtime/member-runtime.js +19 -12
  18. package/lib/runtime/skill-catalog.js +4 -1
  19. package/lib/runtime/skill-provider.js +29 -5
  20. package/lib/skillopt/adopt-gate.js +1 -1
  21. package/lib/skillopt/gate-wiring.js +24 -4
  22. package/lib/skillopt/job-runner.js +5 -0
  23. package/lib/skillopt/jobs.js +4 -1
  24. package/lib/skillopt/judge.js +46 -12
  25. package/lib/skillopt/optimize-wiring.js +12 -6
  26. package/lib/skillopt/proposal-store.js +33 -0
  27. package/lib/skillopt/review-runner.js +17 -3
  28. package/lib/skillopt/reviewer.js +4 -4
  29. package/lib/skillopt/rubric.js +20 -6
  30. package/lib/skillopt/tool-access.js +56 -0
  31. package/package.json +3 -3
  32. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__init__.cpython-311.pyc +0 -0
  33. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__main__.cpython-311.pyc +0 -0
  34. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/backend.cpython-311.pyc +0 -0
  35. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/budget.cpython-311.pyc +0 -0
  36. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/config.cpython-311.pyc +0 -0
  37. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/consolidate.cpython-311.pyc +0 -0
  38. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/cycle.cpython-311.pyc +0 -0
  39. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/dream.cpython-311.pyc +0 -0
  40. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/evidence.cpython-311.pyc +0 -0
  41. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/gate.cpython-311.pyc +0 -0
  42. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/handoff_backend.cpython-311.pyc +0 -0
  43. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest.cpython-311.pyc +0 -0
  44. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_codex.cpython-311.pyc +0 -0
  45. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot.cpython-311.pyc +0 -0
  46. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot_cli.cpython-311.pyc +0 -0
  47. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_cursor.cpython-311.pyc +0 -0
  48. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_opencode.cpython-311.pyc +0 -0
  49. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_pi.cpython-311.pyc +0 -0
  50. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_sources.cpython-311.pyc +0 -0
  51. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/judges.cpython-311.pyc +0 -0
  52. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/memory.cpython-311.pyc +0 -0
  53. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/mine.cpython-311.pyc +0 -0
  54. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/multi_skill.cpython-311.pyc +0 -0
  55. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/replay.cpython-311.pyc +0 -0
  56. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/skill_resolver.cpython-311.pyc +0 -0
  57. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/staging.cpython-311.pyc +0 -0
  58. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/state.cpython-311.pyc +0 -0
  59. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/tasks_file.cpython-311.pyc +0 -0
  60. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/types.cpython-311.pyc +0 -0
@@ -1,11 +1,13 @@
1
1
  /**
2
- * The member-facing Team tool. It is registered globally but only becomes
3
- * visible to a session that is a live Team member (`when` checks the ledger).
2
+ * The member-facing Team tool. It is registered globally and becomes visible
3
+ * once the AI Team runtime booted (see index.js `when`); the tool itself still
4
+ * refuses any session that is not a live Team member (`E_NOT_MEMBER`).
4
5
  *
5
6
  * Mutations require `expectedRevision` (Task CAS) and `baseSeq` (Thread stale
6
7
  * reply protection); errors are returned as data so the member can re-read.
7
8
  */
8
9
  import { taskCard } from './views.js';
10
+ import { isQaMember } from '../domain/member-profile.js';
9
11
 
10
12
  const ACTIONS = ['tasks', 'members', 'inbox', 'recall', 'create', 'askHuman', 'member', 'evolve', 'distill', 'note', 'skill', 'claim', 'submit', 'thread', 'reply', 'accept', 'requestChanges'];
11
13
 
@@ -138,7 +140,7 @@ export function createTeamTool(options) {
138
140
  name: candidate.name,
139
141
  role: candidate.role,
140
142
  status: candidate.status,
141
- qa: /验收|qa|quality|test|verification/i.test(candidate.role ?? ''),
143
+ qa: isQaMember(candidate),
142
144
  }));
143
145
  return { ok: true, projectId: pid, members };
144
146
  }
@@ -242,7 +244,7 @@ export function createTeamTool(options) {
242
244
  ...(args.qaRequired === true ? { qaRequired: true } : {}),
243
245
  ...(Array.isArray(args.qaChecklist) ? { qaChecklist: args.qaChecklist } : {}),
244
246
  });
245
- return { ok: true, task: taskCard(options.getState(), result.task) };
247
+ return { ok: true, task: taskCard(options.getState(exec), result.task) };
246
248
  }
247
249
  if (args.action === 'askHuman') {
248
250
  if (!Array.isArray(args.questions) || args.questions.length === 0) {
@@ -280,7 +282,7 @@ export function createTeamTool(options) {
280
282
  }
281
283
  const type = args.action === 'requestChanges' ? 'task.request_changes' : `task.${args.action}`;
282
284
  const result = await command(type, payload);
283
- return { ok: true, task: taskCard(options.getState(), result.task), event: result.event?.type ?? null };
285
+ return { ok: true, task: taskCard(options.getState(exec), result.task), event: result.event?.type ?? null };
284
286
  }
285
287
  if (args.action === 'thread') {
286
288
  if (typeof args.taskId !== 'string') return failure({ code: 'E_INVALID_ARGUMENT', message: 'taskId is required' });
@@ -1,4 +1,4 @@
1
- /** Lightweight Project index. The ledger remains the source of truth for Project state. */
1
+ /** Lightweight Project index. The ledger remains the source of truth for Project state. */
2
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { DEFAULT_PROJECT_ID } from './project-runtime.js';
@@ -56,11 +56,28 @@ export class ProjectRegistry {
56
56
  }
57
57
 
58
58
  setActive(id) {
59
- if (!this.projects.some((project) => project.id === id)) throw new Error(`unknown project: ${id}`);
59
+ const project = this.projects.find((entry) => entry.id === id);
60
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
61
+ // 归档项目不能成为 active:registry 的 active 会被 bootstrap 当作「默认项目」,
62
+ // 指向一个已归档/无账本的项目会让工作台直接不可达。
63
+ if (project.archived === true) throw new Error(`project ${id} is archived`);
60
64
  this.activeProjectId = id;
61
65
  this.save();
62
66
  }
63
67
 
68
+ /** Mirror a Project's archive flag into the global index (ledger stays the source of truth). */
69
+ setArchived(id, archived) {
70
+ const project = this.projects.find((entry) => entry.id === id);
71
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
72
+ project.archived = archived === true;
73
+ if (archived === true && this.activeProjectId === id) {
74
+ const fallback = this.projects.find((entry) => entry.id !== id && entry.archived !== true);
75
+ if (fallback !== undefined) this.activeProjectId = fallback.id;
76
+ }
77
+ this.save();
78
+ return project;
79
+ }
80
+
64
81
  save() {
65
82
  const file = join(this.rootDir, 'projects.json');
66
83
  const temp = `${file}.tmp`;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
2
  import pathDefault from 'node:path';
3
3
  import { ERRORS, fail } from '../domain/errors.js';
4
4
  import { findReportPath, parseDecisionQuestions } from './decision-report.js';
@@ -21,6 +21,9 @@ import {
21
21
  import { appendReply, createThread } from '../domain/thread.js';
22
22
  import { boardView, quadrantsView, taskCard } from './views.js';
23
23
  import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-config.js';
24
+ import { MEMBER_STATUS } from '../ledger/fold.js';
25
+
26
+ const MEMBER_STATUS_VALUES = new Set(Object.values(MEMBER_STATUS));
24
27
  import { isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
25
28
 
26
29
  function mentionsHuman(body) {
@@ -112,6 +115,18 @@ export class TeamService {
112
115
  return this.ledger.state;
113
116
  }
114
117
 
118
+ /**
119
+ * Serialize a mutation that must observe a fresh projection across an await.
120
+ * `ledger.append` is async, so two concurrent dispatches can both read the
121
+ * same pre-append projection. A rejected run never poisons the chain.
122
+ */
123
+ runExclusive(work) {
124
+ const run = this.exclusive ?? Promise.resolve();
125
+ const result = run.then(work, work);
126
+ this.exclusive = result.then(() => undefined, () => undefined);
127
+ return result;
128
+ }
129
+
115
130
  /** The Human member id, derived once per call from the folded state. */
116
131
  humanId() {
117
132
  return this.state.humanMemberId
@@ -139,7 +154,11 @@ export class TeamService {
139
154
  /** One page of workbench state; the UI reads this instead of the ledger. */
140
155
  bootstrap(projectId, threadTaskId) {
141
156
  const state = this.state;
142
- const projects = Object.values(state.projects ?? {})
157
+ // 归档项目仍要被「看见」:列表里过滤掉它们,但存在性判定必须用未过滤的
158
+ // 记录——否则归归档项目会被报成 E_NOT_FOUND,与 board()/quadrants() 的口径
159
+ // 打架,且客户端把归档项目渲染成可点的只读行,选中即失败。
160
+ const allProjectRecords = Object.values(state.projects ?? {});
161
+ const projects = allProjectRecords
143
162
  .filter((p) => p.status !== 'archived')
144
163
  .map((p) => ({
145
164
  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',
@@ -175,11 +194,32 @@ export class TeamService {
175
194
  .filter((task) => task.tombstone !== true && task.status !== 'deleted')
176
195
  .map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
177
196
  const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
197
+ // 与 board/quadrants 同口径:显式给了**不存在**的 projectId 必须报错,不能返回
198
+ // 一个 project:null 的空壳让调用方分不清「项目不存在」和「空项目」。
199
+ // 存在性按未过滤记录判定:归档项目是「已归档」,不是「不存在」。
200
+ if (projectId !== undefined && state.projects?.[projectId] === undefined) {
201
+ fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
202
+ }
203
+ // 归档项目:仍返回它的只读视图(列表里不出现,但请求它时可用)。
204
+ const archivedProject = projectId !== undefined && project === undefined
205
+ ? {
206
+ id: projectId,
207
+ name: state.projects[projectId].name ?? projectId,
208
+ goal: state.projects[projectId].goal ?? '',
209
+ owner: state.projects[projectId].ownerName ?? state.projects[projectId].ownerMemberId ?? null,
210
+ workspacePath: state.projects[projectId].workspacePath ?? '',
211
+ pmoAuto: state.projects[projectId].pmoAuto !== false,
212
+ active: false,
213
+ archived: true,
214
+ runState: state.projects[projectId].runState === 'stopped' ? 'stopped' : 'running',
215
+ }
216
+ : null;
217
+ const selectedProject = project ?? archivedProject ?? undefined;
178
218
  // 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
179
219
  // stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
180
- const stream = project === undefined
220
+ const stream = selectedProject === undefined
181
221
  ? []
182
- : (state.stream ?? []).filter((entry) => entry.projectId === project.id).slice(-200);
222
+ : (state.stream ?? []).filter((entry) => entry.projectId === selectedProject.id).slice(-200);
183
223
  const selected = threadTaskId ?? tasks.find((task) => task.status === 'in_progress')?.id ?? tasks[0]?.id;
184
224
  const threadOf = (taskId) => {
185
225
  const full = taskId === undefined || taskId === null ? undefined : state.threads?.[taskId];
@@ -193,7 +233,7 @@ export class TeamService {
193
233
  (item.memberId === this.humanId())
194
234
  && !isInformationalThreadMention(item));
195
235
  return {
196
- project: project ?? null,
236
+ project: selectedProject ?? null,
197
237
  projects,
198
238
  agents,
199
239
  members,
@@ -202,8 +242,8 @@ export class TeamService {
202
242
  thread,
203
243
  threads,
204
244
  inbox,
205
- board: project === undefined ? null : this.board(project.id),
206
- quadrants: project === undefined ? null : this.quadrants(project.id),
245
+ board: selectedProject === undefined ? null : this.board(selectedProject.id),
246
+ quadrants: selectedProject === undefined ? null : this.quadrants(selectedProject.id),
207
247
  };
208
248
  }
209
249
 
@@ -216,11 +256,22 @@ export class TeamService {
216
256
  const humanId = this.humanId();
217
257
  if (humanId === null) return 0;
218
258
  const projectId = Object.keys(this.state.projects ?? {})[0];
259
+ // 路径包含性:Thread 正文由 agent 写,正文里的绝对路径不能变成
260
+ // 「读主机任意文件」的通道——只接受项目工作目录内的 .md。
261
+ const allowedRoot = typeof workspacePath === 'string' && workspacePath !== ''
262
+ ? pathDefault.resolve(workspacePath)
263
+ : null;
264
+ const insideWorkspace = (candidate) => {
265
+ if (allowedRoot === null) return false;
266
+ const resolved = pathDefault.resolve(candidate);
267
+ const relative = pathDefault.relative(allowedRoot, resolved);
268
+ return relative !== '' && !relative.startsWith('..') && !pathDefault.isAbsolute(relative);
269
+ };
219
270
  let reportPath = null;
220
271
  for (const task of Object.values(this.state.tasks ?? {})) {
221
272
  for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
222
273
  const found = findReportPath(entry.body);
223
- if (found !== null && existsSync(found)) { reportPath = found; break; }
274
+ if (found !== null && insideWorkspace(found) && existsSync(found)) { reportPath = found; break; }
224
275
  }
225
276
  if (reportPath !== null) break;
226
277
  }
@@ -408,13 +459,29 @@ export class TeamService {
408
459
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a Project');
409
460
  if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required');
410
461
  const id = this.ledger.projectId ?? payload.id ?? ids.project();
462
+ // 重复 id 会覆盖既有项目的 name/goal/owner/status(fold 按 id 合并),
463
+ // 静默丢掉原项目。create 必须是「新建」。
464
+ if (this.state.projects?.[id] !== undefined) {
465
+ fail(ERRORS.CONFLICT, `project ${id} already exists`);
466
+ }
467
+ // 工作目录可空(稍后设置),但给了就必须存在——与 project.workspace.update
468
+ // 的校验一致,否则成员激活会在一个不存在的 cwd 上失败。
469
+ const rawWorkspace = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '';
470
+ if (rawWorkspace !== '') {
471
+ let stat = null;
472
+ try { stat = statSync(rawWorkspace); } catch { stat = null; }
473
+ if (stat === null) fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${rawWorkspace};请先创建该目录,或选择已存在的目录`);
474
+ if (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
475
+ fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${rawWorkspace}`);
476
+ }
477
+ }
411
478
  const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
412
479
  const project = {
413
480
  id,
414
481
  name: payload.name.trim(),
415
482
  goal: payload.goal ?? '',
416
483
  ownerMemberId,
417
- workspacePath: payload.workspacePath ?? '',
484
+ workspacePath: rawWorkspace,
418
485
  status: 'active',
419
486
  createdAt: this.now(),
420
487
  };
@@ -538,8 +605,10 @@ export class TeamService {
538
605
  if (author === undefined) fail(ERRORS.UNAUTHORIZED, 'actor must be a Team member');
539
606
  // seq 由账本事件定(fold 用 event.seq;payload 里的幻影计数会被忽略,
540
607
  // 并发下还会重复——曾造成 API 返回值与投影不一致)。
608
+ // kind 必须反映真实作者:`human_message` 是 Waker 判定「Human 下了指令」的
609
+ // 唯一依据(会触发建卡唤醒),agent 发言若也标成它,等于让 agent 冒充 Human。
541
610
  const entry = {
542
- kind: 'human_message',
611
+ kind: command.actor.kind === 'human' ? 'human_message' : 'milestone',
543
612
  authorId: author.id,
544
613
  body,
545
614
  at: this.now(),
@@ -557,13 +626,28 @@ export class TeamService {
557
626
  async addMember(command, payload) {
558
627
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a member');
559
628
  if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'member name is required');
629
+ // id 由调用方给出时必须是非空字符串且未被占用:否则会覆盖既有成员
630
+ // (fold 按 id 合并,sessionId/config 一起丢失),或写入非字符串 id 被
631
+ // fold 丢弃却仍返回成功。
632
+ if (payload.id !== undefined) {
633
+ if (typeof payload.id !== 'string' || payload.id.trim() === '') {
634
+ fail(ERRORS.INVALID_ARGUMENT, 'member id must be a non-empty string');
635
+ }
636
+ if (this.state.members?.[payload.id] !== undefined) {
637
+ fail(ERRORS.CONFLICT, `member ${payload.id} already exists`);
638
+ }
639
+ }
640
+ const status = payload.status === undefined ? MEMBER_STATUS.IDLE : payload.status;
641
+ if (!MEMBER_STATUS_VALUES.has(status)) {
642
+ fail(ERRORS.INVALID_ARGUMENT, `member status must be one of ${[...MEMBER_STATUS_VALUES].join(', ')}`);
643
+ }
560
644
  const member = {
561
645
  id: payload.id ?? ids.member(),
562
646
  name: payload.name.trim(),
563
647
  kind: payload.kind === 'human' ? 'human' : 'agent',
564
648
  role: payload.role ?? '',
565
649
  personality: typeof payload.personality === 'string' ? payload.personality : '',
566
- status: typeof payload.status === 'string' ? payload.status : 'idle',
650
+ status,
567
651
  createdAt: this.now(),
568
652
  };
569
653
  await this.append(command, 'project/member-added', {
@@ -808,7 +892,9 @@ export class TeamService {
808
892
  }
809
893
  const current = normalizeMemberConfig(member.config ?? {});
810
894
  const result = applyMemberConfigPatch(current, payload.patch ?? {}, {
811
- policy: { ...this.memberConfigPolicy, ...(payload.policy ?? {}) },
895
+ // policy 只能来自服务端注入:允许命令 payload 覆盖等于让调用方自己定义
896
+ // 授权边界(实测可把 allowedModels 扩到未授权模型)。
897
+ policy: { ...this.memberConfigPolicy },
812
898
  configVersion: member.configVersion ?? 0,
813
899
  });
814
900
  if (!result.changed) return { member, config: current, changed: false };
@@ -1009,11 +1095,23 @@ export class TeamService {
1009
1095
  const task = state.tasks?.[taskId];
1010
1096
  if (task === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1011
1097
  const expectedRevision = command.payload?.expectedRevision;
1098
+ // 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
1099
+ // 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
1100
+ const requireAgentMember = (memberId, field) => {
1101
+ if (typeof memberId !== 'string' || memberId === '') return;
1102
+ const candidate = this.state.members?.[memberId];
1103
+ if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
1104
+ if (candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
1105
+ if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
1106
+ };
1012
1107
  let outcome;
1013
1108
  switch (action) {
1014
1109
  case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
1015
1110
  case 'release': outcome = releaseTask(task, command.actor, { expectedRevision, reason: command.payload?.reason, at: this.now() }); break;
1016
- case 'assign': outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() }); break;
1111
+ case 'assign':
1112
+ requireAgentMember(command.payload?.assigneeId, 'assigneeId');
1113
+ outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() });
1114
+ break;
1017
1115
  case 'submit': outcome = submitTask(task, command.actor, { summary: command.payload?.summary, evidence: command.payload?.evidence }, { expectedRevision, at: this.now() }); break;
1018
1116
  case 'accept': {
1019
1117
  // Agent actors are pre-resolved by dispatch; resolve defensively here
@@ -1030,8 +1128,21 @@ export class TeamService {
1030
1128
  const checklist = Array.isArray(task.qaChecklist) ? task.qaChecklist : [];
1031
1129
  const checks = Array.isArray(command.payload?.checks) ? command.payload.checks : [];
1032
1130
  if (reviewer !== null && checklist.length > 0) {
1033
- if (checks.length !== checklist.length || checks.some((check) => check?.passed !== true)) {
1034
- fail(ERRORS.INVALID_STATE, 'every QA checklist item must pass before acceptance');
1131
+ // QA 门禁必须逐项对应 task.qaChecklist:只比较条数 + passed 会让
1132
+ // 任意 item 文本(含伪造/无关条目)通过门禁,与 tool schema 契约
1133
+ // "Exact qaChecklist item" 不一致。
1134
+ const pending = checklist.map((item) => String(item));
1135
+ for (const check of checks) {
1136
+ if (check?.passed !== true) fail(ERRORS.INVALID_STATE, 'every QA checklist item must pass before acceptance');
1137
+ const text = typeof check?.item === 'string' ? check.item : '';
1138
+ const at = pending.indexOf(text);
1139
+ if (at === -1) {
1140
+ fail(ERRORS.INVALID_ARGUMENT, `unknown QA checklist item: ${text === '' ? '(empty)' : text}`);
1141
+ }
1142
+ pending.splice(at, 1);
1143
+ }
1144
+ if (pending.length > 0) {
1145
+ fail(ERRORS.INVALID_STATE, `QA checklist item not verified: ${pending[0]}`);
1035
1146
  }
1036
1147
  }
1037
1148
  outcome = acceptTask(task, command.actor, {
@@ -1044,13 +1155,19 @@ export class TeamService {
1044
1155
  case 'request_changes': outcome = requestChangesTask(task, command.actor, { note: command.payload?.note }, { expectedRevision, at: this.now() }); break;
1045
1156
  case 'cancel': outcome = cancelTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, at: this.now() }); break;
1046
1157
  case 'reopen': outcome = reopenTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, members: state.members, at: this.now() }); break;
1047
- case 'reassign': outcome = reassignTask(task, command.actor, command.payload?.ownerId, { expectedRevision, reason: command.payload?.reason, at: this.now() }); break;
1158
+ case 'reassign':
1159
+ requireAgentMember(command.payload?.ownerId, 'ownerId');
1160
+ outcome = reassignTask(task, command.actor, command.payload?.ownerId, { expectedRevision, reason: command.payload?.reason, at: this.now() });
1161
+ break;
1048
1162
  case 'delete': outcome = deleteTask(task, command.actor, { expectedRevision, at: this.now() }); break;
1049
1163
  default: fail(ERRORS.INVALID_ARGUMENT, `unknown task action: ${action}`);
1050
1164
  }
1051
1165
  await this.ledger.append({ ...outcome.event, actor: command.actor, correlationId: command.correlationId, projectId: command.projectId, at: this.now() });
1052
- if (action === 'accept') await this.notifyTaskFollowers(outcome.task, command);
1053
- return { task: outcome.task, event: outcome.event };
1166
+ // fold 会丢弃陈旧 revision 的事件(revision <= 当前),务必返回已提交的投影,
1167
+ // 否则并发 claim/accept 的失败方会收到“成功”并发出错误的 follower 通知。
1168
+ const committed = this.state.tasks?.[outcome.task.id] ?? outcome.task;
1169
+ if (action === 'accept') await this.notifyTaskFollowers(committed, command);
1170
+ return { task: committed, event: outcome.event };
1054
1171
  }
1055
1172
 
1056
1173
  async convert(command, payload) {
@@ -1116,22 +1233,27 @@ export class TeamService {
1116
1233
  }
1117
1234
 
1118
1235
  async postThread(command, payload) {
1119
- const state = this.state;
1120
1236
  const taskId = payload.taskId;
1121
- if (state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1122
- const thread = state.threads?.[taskId] ?? createThread(taskId);
1123
- const actorKind = command.actor.kind;
1124
- const authorId = command.actor.memberId ?? this.humanId();
1125
- const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
1126
- await this.ledger.append({
1127
- type: 'thread/posted',
1128
- payload: { taskId, ...outcome.entry },
1129
- actor: command.actor,
1130
- correlationId: command.correlationId,
1131
- projectId: command.projectId,
1132
- at: this.now(),
1237
+ if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1238
+ // headSeq 的读取与 ledger.append 之间有一次 await:两个并发 reply 会读到同一个
1239
+ // headSeq、各自生成 seq=headSeq+1,fold 按 seq 去重后第二条被永久丢弃,而两次
1240
+ // 调用都返回成功。用 runExclusive 让「读头 + 分配 seq + 提交」串行。
1241
+ return this.runExclusive(async () => {
1242
+ if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1243
+ const thread = this.state.threads?.[taskId] ?? createThread(taskId);
1244
+ const actorKind = command.actor.kind;
1245
+ const authorId = command.actor.memberId ?? this.humanId();
1246
+ const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
1247
+ await this.ledger.append({
1248
+ type: 'thread/posted',
1249
+ payload: { taskId, ...outcome.entry },
1250
+ actor: command.actor,
1251
+ correlationId: command.correlationId,
1252
+ projectId: command.projectId,
1253
+ at: this.now(),
1254
+ });
1255
+ return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry };
1133
1256
  });
1134
- return { thread: outcome.thread, entry: outcome.entry };
1135
1257
  }
1136
1258
 
1137
1259
  /** PMO: answer all pending structured questions with the max-value policy. */
@@ -1190,7 +1312,7 @@ export class TeamService {
1190
1312
  });
1191
1313
  await this.ledger.append({
1192
1314
  type: 'inbox/acked',
1193
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1315
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1194
1316
  actor: { kind: 'system', memberId: 'mem_pmo' },
1195
1317
  projectId,
1196
1318
  at: this.now(),
@@ -1268,6 +1390,15 @@ export class TeamService {
1268
1390
  .filter((answer) => answer.value !== '');
1269
1391
  if (answers.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'at least one answer is required');
1270
1392
  const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
1393
+ // 决策必须覆盖全部问题:只答一半就把 item 置为 resolved,会让未答的问题
1394
+ // 从待决策表单里消失(UI 有 complete 校验,命令层也必须一致)。
1395
+ if (questions.length > 0) {
1396
+ const known = new Set(questions.map((question) => question.id));
1397
+ const unknown = answers.filter((answer) => !known.has(answer.id)).map((answer) => answer.id);
1398
+ if (unknown.length > 0) fail(ERRORS.INVALID_ARGUMENT, `unknown question id(s): ${unknown.join(', ')}`);
1399
+ const missing = questions.filter((question) => !answers.some((answer) => answer.id === question.id)).map((question) => question.id);
1400
+ if (missing.length > 0) fail(ERRORS.INVALID_ARGUMENT, `every question must be answered; missing: ${missing.join(', ')}`);
1401
+ }
1271
1402
  const lines = answers.map((answer) => {
1272
1403
  const question = questions.find((candidate) => candidate.id === answer.id);
1273
1404
  return `- ${question?.text ?? answer.id}: ${answer.value}`;
@@ -1295,7 +1426,7 @@ export class TeamService {
1295
1426
  const next = ackInboxItem(item, { disposition: 'done', decision: { answers, note: payload.note ?? '', body } }, { at: this.now() });
1296
1427
  await this.ledger.append({
1297
1428
  type: 'inbox/acked',
1298
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1429
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1299
1430
  actor: command.actor,
1300
1431
  projectId: command.projectId,
1301
1432
  at: this.now(),
@@ -1307,10 +1438,16 @@ export class TeamService {
1307
1438
  const state = this.state;
1308
1439
  const item = state.inbox?.[payload.itemId];
1309
1440
  if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
1441
+ // 归属校验:成员只能处理自己的收件项。缺了这条,任意 agent 可用一个
1442
+ // itemId 把别人的(含 Human 的)决策项标成 resolved。
1443
+ const actorMemberId = command.actor.memberId ?? this.humanId();
1444
+ if (command.actor.kind !== 'human' && item.memberId !== actorMemberId) {
1445
+ fail(ERRORS.UNAUTHORIZED, 'inbox item belongs to another member');
1446
+ }
1310
1447
  const next = ackInboxItem(item, { disposition: payload.disposition, decision: payload.decision }, { at: this.now() });
1311
1448
  await this.ledger.append({
1312
1449
  type: 'inbox/acked',
1313
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1450
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1314
1451
  actor: command.actor,
1315
1452
  correlationId: command.correlationId,
1316
1453
  projectId: command.projectId,
package/lib/host/views.js CHANGED
@@ -40,6 +40,25 @@ export function taskCard(state, task) {
40
40
  irreversible: task.irreversible === true,
41
41
  qaRequired: task.qaRequired === true,
42
42
  qaChecklist: task.qaChecklist ?? [],
43
+ // 验收面板要显示「提交了什么」:domain 把 summary/evidence 写在 task 根上,
44
+ // 这里统一成面板消费的 submission 形状,并归一化证据条目({kind,value}
45
+ // → {label,ref}),否则面板永远显示「无证据」占位。两者都为空时给 null,
46
+ // 让面板区分「没提交」与「提交了空内容」。
47
+ submission: (() => {
48
+ const summary = typeof task.summary === 'string' ? task.summary : '';
49
+ const evidence = (Array.isArray(task.evidence) ? task.evidence : []).map((entry) => {
50
+ if (typeof entry === 'string') return { label: entry, ref: '' };
51
+ const label = entry?.label ?? entry?.value ?? entry?.text ?? entry?.kind ?? '';
52
+ return { label: String(label), ref: typeof entry?.ref === 'string' ? entry.ref : '' };
53
+ });
54
+ if (summary === '' && evidence.length === 0) return null;
55
+ return { summary, evidence };
56
+ })(),
57
+ // 完成面板读 completedAt / acceptedBy:domain 只存 acceptedAt 与 reviewerId,
58
+ // 这里投影成面板字段,否则 done 卡永远显示「无信息」。
59
+ completedAt: task.status === 'done' ? doneAt(task) : (task.acceptedAt ?? null),
60
+ acceptedBy: task.reviewerId === undefined || task.reviewerId === null ? null : nameOf(state, task.reviewerId),
61
+ evidenceCount: Array.isArray(task.evidence) ? task.evidence.length : 0,
43
62
  updatedAt: task.updatedAt ?? null,
44
63
  };
45
64
  }
@@ -195,12 +214,15 @@ export function quadrantsView(state, options = {}) {
195
214
  q3.sort(byWaiting);
196
215
  q4.sort((left, right) => (right.doneAt ?? 0) - (left.doneAt ?? 0));
197
216
  const q4Total = q4.length;
217
+ // q4Limit 是面板的展示上限(调用方按窗口传入);count/total 仍报全部完成数,
218
+ // 只有 items 受限制——之前把 limit 只回显、items 固定 slice(0,5),参数形同虚设。
219
+ const q4Items = q4.slice(0, Math.max(0, q4Limit));
198
220
  return {
199
221
  rev: state.lastSeq ?? 0,
200
222
  generatedAt: now,
201
223
  q1: { count: q1.length, items: q1.slice(0, 5) },
202
224
  q2: { count: q2.length, items: q2.slice(0, 5) },
203
225
  q3: { count: q3.length, items: q3.slice(0, 5) },
204
- q4: { count: q4Total, items: q4.slice(0, 5), total: q4Total, limit: q4Limit },
226
+ q4: { count: q4Total, items: q4Items, total: q4Total, limit: q4Limit },
205
227
  };
206
228
  }
package/lib/host/waker.js CHANGED
@@ -95,7 +95,7 @@ function promptFor(reason, state, taskId) {
95
95
  * @param {{ agentId?: string }} actor
96
96
  * @returns {Array<{memberId:string, taskId:string|null, reason:string, prompt:string, key:string}>}
97
97
  */
98
- export function planWakes(state, result, actor = {}) {
98
+ export function planWakes(state, result, actor = {}, options = {}) {
99
99
  const event = result?.event ?? null;
100
100
  const task = result?.task ?? null;
101
101
  const targets = new Map();
@@ -108,12 +108,15 @@ export function planWakes(state, result, actor = {}) {
108
108
  // wake so the same member can claim it.
109
109
  if (actor.agentId !== undefined && memberId === actor.agentId && (reason === 'thread_reply' || reason === 'review_requested')) return;
110
110
  if (targets.has(memberId + ':' + reason)) return;
111
+ // 去重键必须带上接收者与 Project:`wakeKeys` 是 Host 级全局表,同一 event
112
+ // seq 在多个 Project 里会重复,两个接收者共用键会让第二个计划被静默丢弃。
113
+ const scopedKey = `${key}:${memberId}:${options.projectId ?? ''}`;
111
114
  targets.set(memberId + ':' + reason, {
112
115
  memberId,
113
116
  taskId: taskId ?? null,
114
117
  reason,
115
118
  prompt: (promptOverride ?? promptFor(reason, state, taskId)) + (taskId ? ` Task id: ${taskId}.` : ''),
116
- key,
119
+ key: scopedKey,
117
120
  });
118
121
  };
119
122
 
@@ -136,7 +139,8 @@ export function planWakes(state, result, actor = {}) {
136
139
  );
137
140
  }
138
141
  if (event?.type === 'task/created' || (event === null && task !== null && task.status === 'pending')) {
139
- const created = task ?? event?.payload?.task;
142
+ // 账本事件路径没有嵌套 task:payload 只有 taskId,必须回投影里取。
143
+ const created = task ?? (event?.payload?.taskId === undefined ? null : state.tasks?.[event.payload.taskId]) ?? null;
140
144
  if (created !== null && created !== undefined) {
141
145
  add(created.ownerId, created.id, 'task_created', `task_created:${created.id}`);
142
146
  add(created.assigneeId, created.id, 'task_assigned', `task_assigned:${created.id}`);
@@ -55,6 +55,9 @@ export function weeklyView(state, { now = Date.now(), weeks = 1 } = {}) {
55
55
  for (const item of Object.values(state.inbox ?? {})) {
56
56
  if (item.type !== 'decision_required' || item.requiresDecision !== true) continue;
57
57
  if (item.state !== 'done' && item.state !== 'resolved') continue;
58
+ // PMO 自动答复(decision.auto === true)不是 Human 介入:周报的
59
+ // 「零 Human」口径若把自动决策算进去,就永远看不到真实的人工干预。
60
+ if (item.decision?.auto === true) continue;
58
61
  if ((item.ackedAt ?? 0) >= windowStart) decisionsAnswered += 1;
59
62
  }
60
63
  const humanTasks = humanId === null ? 0
@@ -129,6 +129,17 @@ export function validateCheckpoint(checkpoint, options = {}) {
129
129
  if (!isPlainObject(checkpoint.state)) {
130
130
  return invalid('E_CHECKPOINT_INVALID', 'checkpoint.state must be a plain object');
131
131
  }
132
+ // state 自述水位必须与外层水位一致:hashMatches 只证明 lastHash 等于账本第
133
+ // lastSeq 条事件的 hash,并不覆盖 state 内容。state 被截断/错位而外层水位仍
134
+ // 有效时,openLedger 的齐平分支持零尾放采信错误投影。(只校验 seq:内容哈希
135
+ // 由外层 lastHash 链保证,避免遮蔽 E_CHECKPOINT_HASH 的诊断。)
136
+ const stateSeq = checkpoint.state.lastSeq;
137
+ if (Number.isSafeInteger(stateSeq) && stateSeq !== checkpoint.lastSeq) {
138
+ return invalid('E_CHECKPOINT_STATE_MISMATCH', 'checkpoint.state.lastSeq does not match the checkpoint watermark', {
139
+ expected: checkpoint.lastSeq,
140
+ actual: stateSeq,
141
+ });
142
+ }
132
143
  return { ok: true };
133
144
  }
134
145