@suifei/dsh-ai-team 0.4.23 → 0.4.27

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.
@@ -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
@@ -175,6 +190,11 @@ export class TeamService {
175
190
  .filter((task) => task.tombstone !== true && task.status !== 'deleted')
176
191
  .map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
177
192
  const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
193
+ // 与 board/quadrants 同口径:显式给了不存在的 projectId 必须报错,不能返回
194
+ // 一个 project:null 的空壳让调用方分不清「项目不存在」和「空项目」。
195
+ if (projectId !== undefined && project === undefined) {
196
+ fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
197
+ }
178
198
  // 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
179
199
  // stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
180
200
  const stream = project === undefined
@@ -216,11 +236,22 @@ export class TeamService {
216
236
  const humanId = this.humanId();
217
237
  if (humanId === null) return 0;
218
238
  const projectId = Object.keys(this.state.projects ?? {})[0];
239
+ // 路径包含性:Thread 正文由 agent 写,正文里的绝对路径不能变成
240
+ // 「读主机任意文件」的通道——只接受项目工作目录内的 .md。
241
+ const allowedRoot = typeof workspacePath === 'string' && workspacePath !== ''
242
+ ? pathDefault.resolve(workspacePath)
243
+ : null;
244
+ const insideWorkspace = (candidate) => {
245
+ if (allowedRoot === null) return false;
246
+ const resolved = pathDefault.resolve(candidate);
247
+ const relative = pathDefault.relative(allowedRoot, resolved);
248
+ return relative !== '' && !relative.startsWith('..') && !pathDefault.isAbsolute(relative);
249
+ };
219
250
  let reportPath = null;
220
251
  for (const task of Object.values(this.state.tasks ?? {})) {
221
252
  for (const entry of this.state.threads?.[task.id]?.entries ?? []) {
222
253
  const found = findReportPath(entry.body);
223
- if (found !== null && existsSync(found)) { reportPath = found; break; }
254
+ if (found !== null && insideWorkspace(found) && existsSync(found)) { reportPath = found; break; }
224
255
  }
225
256
  if (reportPath !== null) break;
226
257
  }
@@ -408,13 +439,29 @@ export class TeamService {
408
439
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a Project');
409
440
  if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required');
410
441
  const id = this.ledger.projectId ?? payload.id ?? ids.project();
442
+ // 重复 id 会覆盖既有项目的 name/goal/owner/status(fold 按 id 合并),
443
+ // 静默丢掉原项目。create 必须是「新建」。
444
+ if (this.state.projects?.[id] !== undefined) {
445
+ fail(ERRORS.CONFLICT, `project ${id} already exists`);
446
+ }
447
+ // 工作目录可空(稍后设置),但给了就必须存在——与 project.workspace.update
448
+ // 的校验一致,否则成员激活会在一个不存在的 cwd 上失败。
449
+ const rawWorkspace = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '';
450
+ if (rawWorkspace !== '') {
451
+ let stat = null;
452
+ try { stat = statSync(rawWorkspace); } catch { stat = null; }
453
+ if (stat === null) fail(ERRORS.INVALID_ARGUMENT, `工作目录不存在:${rawWorkspace};请先创建该目录,或选择已存在的目录`);
454
+ if (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true) {
455
+ fail(ERRORS.INVALID_ARGUMENT, `工作目录不是目录:${rawWorkspace}`);
456
+ }
457
+ }
411
458
  const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
412
459
  const project = {
413
460
  id,
414
461
  name: payload.name.trim(),
415
462
  goal: payload.goal ?? '',
416
463
  ownerMemberId,
417
- workspacePath: payload.workspacePath ?? '',
464
+ workspacePath: rawWorkspace,
418
465
  status: 'active',
419
466
  createdAt: this.now(),
420
467
  };
@@ -538,8 +585,10 @@ export class TeamService {
538
585
  if (author === undefined) fail(ERRORS.UNAUTHORIZED, 'actor must be a Team member');
539
586
  // seq 由账本事件定(fold 用 event.seq;payload 里的幻影计数会被忽略,
540
587
  // 并发下还会重复——曾造成 API 返回值与投影不一致)。
588
+ // kind 必须反映真实作者:`human_message` 是 Waker 判定「Human 下了指令」的
589
+ // 唯一依据(会触发建卡唤醒),agent 发言若也标成它,等于让 agent 冒充 Human。
541
590
  const entry = {
542
- kind: 'human_message',
591
+ kind: command.actor.kind === 'human' ? 'human_message' : 'milestone',
543
592
  authorId: author.id,
544
593
  body,
545
594
  at: this.now(),
@@ -557,13 +606,28 @@ export class TeamService {
557
606
  async addMember(command, payload) {
558
607
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a member');
559
608
  if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'member name is required');
609
+ // id 由调用方给出时必须是非空字符串且未被占用:否则会覆盖既有成员
610
+ // (fold 按 id 合并,sessionId/config 一起丢失),或写入非字符串 id 被
611
+ // fold 丢弃却仍返回成功。
612
+ if (payload.id !== undefined) {
613
+ if (typeof payload.id !== 'string' || payload.id.trim() === '') {
614
+ fail(ERRORS.INVALID_ARGUMENT, 'member id must be a non-empty string');
615
+ }
616
+ if (this.state.members?.[payload.id] !== undefined) {
617
+ fail(ERRORS.CONFLICT, `member ${payload.id} already exists`);
618
+ }
619
+ }
620
+ const status = payload.status === undefined ? MEMBER_STATUS.IDLE : payload.status;
621
+ if (!MEMBER_STATUS_VALUES.has(status)) {
622
+ fail(ERRORS.INVALID_ARGUMENT, `member status must be one of ${[...MEMBER_STATUS_VALUES].join(', ')}`);
623
+ }
560
624
  const member = {
561
625
  id: payload.id ?? ids.member(),
562
626
  name: payload.name.trim(),
563
627
  kind: payload.kind === 'human' ? 'human' : 'agent',
564
628
  role: payload.role ?? '',
565
629
  personality: typeof payload.personality === 'string' ? payload.personality : '',
566
- status: typeof payload.status === 'string' ? payload.status : 'idle',
630
+ status,
567
631
  createdAt: this.now(),
568
632
  };
569
633
  await this.append(command, 'project/member-added', {
@@ -808,7 +872,9 @@ export class TeamService {
808
872
  }
809
873
  const current = normalizeMemberConfig(member.config ?? {});
810
874
  const result = applyMemberConfigPatch(current, payload.patch ?? {}, {
811
- policy: { ...this.memberConfigPolicy, ...(payload.policy ?? {}) },
875
+ // policy 只能来自服务端注入:允许命令 payload 覆盖等于让调用方自己定义
876
+ // 授权边界(实测可把 allowedModels 扩到未授权模型)。
877
+ policy: { ...this.memberConfigPolicy },
812
878
  configVersion: member.configVersion ?? 0,
813
879
  });
814
880
  if (!result.changed) return { member, config: current, changed: false };
@@ -1009,11 +1075,23 @@ export class TeamService {
1009
1075
  const task = state.tasks?.[taskId];
1010
1076
  if (task === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1011
1077
  const expectedRevision = command.payload?.expectedRevision;
1078
+ // 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
1079
+ // 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
1080
+ const requireAgentMember = (memberId, field) => {
1081
+ if (typeof memberId !== 'string' || memberId === '') return;
1082
+ const candidate = this.state.members?.[memberId];
1083
+ if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
1084
+ if (candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
1085
+ if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
1086
+ };
1012
1087
  let outcome;
1013
1088
  switch (action) {
1014
1089
  case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
1015
1090
  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;
1091
+ case 'assign':
1092
+ requireAgentMember(command.payload?.assigneeId, 'assigneeId');
1093
+ outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() });
1094
+ break;
1017
1095
  case 'submit': outcome = submitTask(task, command.actor, { summary: command.payload?.summary, evidence: command.payload?.evidence }, { expectedRevision, at: this.now() }); break;
1018
1096
  case 'accept': {
1019
1097
  // Agent actors are pre-resolved by dispatch; resolve defensively here
@@ -1030,8 +1108,21 @@ export class TeamService {
1030
1108
  const checklist = Array.isArray(task.qaChecklist) ? task.qaChecklist : [];
1031
1109
  const checks = Array.isArray(command.payload?.checks) ? command.payload.checks : [];
1032
1110
  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');
1111
+ // QA 门禁必须逐项对应 task.qaChecklist:只比较条数 + passed 会让
1112
+ // 任意 item 文本(含伪造/无关条目)通过门禁,与 tool schema 契约
1113
+ // "Exact qaChecklist item" 不一致。
1114
+ const pending = checklist.map((item) => String(item));
1115
+ for (const check of checks) {
1116
+ if (check?.passed !== true) fail(ERRORS.INVALID_STATE, 'every QA checklist item must pass before acceptance');
1117
+ const text = typeof check?.item === 'string' ? check.item : '';
1118
+ const at = pending.indexOf(text);
1119
+ if (at === -1) {
1120
+ fail(ERRORS.INVALID_ARGUMENT, `unknown QA checklist item: ${text === '' ? '(empty)' : text}`);
1121
+ }
1122
+ pending.splice(at, 1);
1123
+ }
1124
+ if (pending.length > 0) {
1125
+ fail(ERRORS.INVALID_STATE, `QA checklist item not verified: ${pending[0]}`);
1035
1126
  }
1036
1127
  }
1037
1128
  outcome = acceptTask(task, command.actor, {
@@ -1044,13 +1135,19 @@ export class TeamService {
1044
1135
  case 'request_changes': outcome = requestChangesTask(task, command.actor, { note: command.payload?.note }, { expectedRevision, at: this.now() }); break;
1045
1136
  case 'cancel': outcome = cancelTask(task, command.actor, { reason: command.payload?.reason, expectedRevision, at: this.now() }); break;
1046
1137
  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;
1138
+ case 'reassign':
1139
+ requireAgentMember(command.payload?.ownerId, 'ownerId');
1140
+ outcome = reassignTask(task, command.actor, command.payload?.ownerId, { expectedRevision, reason: command.payload?.reason, at: this.now() });
1141
+ break;
1048
1142
  case 'delete': outcome = deleteTask(task, command.actor, { expectedRevision, at: this.now() }); break;
1049
1143
  default: fail(ERRORS.INVALID_ARGUMENT, `unknown task action: ${action}`);
1050
1144
  }
1051
1145
  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 };
1146
+ // fold 会丢弃陈旧 revision 的事件(revision <= 当前),务必返回已提交的投影,
1147
+ // 否则并发 claim/accept 的失败方会收到“成功”并发出错误的 follower 通知。
1148
+ const committed = this.state.tasks?.[outcome.task.id] ?? outcome.task;
1149
+ if (action === 'accept') await this.notifyTaskFollowers(committed, command);
1150
+ return { task: committed, event: outcome.event };
1054
1151
  }
1055
1152
 
1056
1153
  async convert(command, payload) {
@@ -1116,22 +1213,27 @@ export class TeamService {
1116
1213
  }
1117
1214
 
1118
1215
  async postThread(command, payload) {
1119
- const state = this.state;
1120
1216
  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(),
1217
+ if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1218
+ // headSeq 的读取与 ledger.append 之间有一次 await:两个并发 reply 会读到同一个
1219
+ // headSeq、各自生成 seq=headSeq+1,fold 按 seq 去重后第二条被永久丢弃,而两次
1220
+ // 调用都返回成功。用 runExclusive 让「读头 + 分配 seq + 提交」串行。
1221
+ return this.runExclusive(async () => {
1222
+ if (this.state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
1223
+ const thread = this.state.threads?.[taskId] ?? createThread(taskId);
1224
+ const actorKind = command.actor.kind;
1225
+ const authorId = command.actor.memberId ?? this.humanId();
1226
+ const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
1227
+ await this.ledger.append({
1228
+ type: 'thread/posted',
1229
+ payload: { taskId, ...outcome.entry },
1230
+ actor: command.actor,
1231
+ correlationId: command.correlationId,
1232
+ projectId: command.projectId,
1233
+ at: this.now(),
1234
+ });
1235
+ return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry };
1133
1236
  });
1134
- return { thread: outcome.thread, entry: outcome.entry };
1135
1237
  }
1136
1238
 
1137
1239
  /** PMO: answer all pending structured questions with the max-value policy. */
@@ -1190,7 +1292,7 @@ export class TeamService {
1190
1292
  });
1191
1293
  await this.ledger.append({
1192
1294
  type: 'inbox/acked',
1193
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1295
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1194
1296
  actor: { kind: 'system', memberId: 'mem_pmo' },
1195
1297
  projectId,
1196
1298
  at: this.now(),
@@ -1268,6 +1370,15 @@ export class TeamService {
1268
1370
  .filter((answer) => answer.value !== '');
1269
1371
  if (answers.length === 0) fail(ERRORS.INVALID_ARGUMENT, 'at least one answer is required');
1270
1372
  const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
1373
+ // 决策必须覆盖全部问题:只答一半就把 item 置为 resolved,会让未答的问题
1374
+ // 从待决策表单里消失(UI 有 complete 校验,命令层也必须一致)。
1375
+ if (questions.length > 0) {
1376
+ const known = new Set(questions.map((question) => question.id));
1377
+ const unknown = answers.filter((answer) => !known.has(answer.id)).map((answer) => answer.id);
1378
+ if (unknown.length > 0) fail(ERRORS.INVALID_ARGUMENT, `unknown question id(s): ${unknown.join(', ')}`);
1379
+ const missing = questions.filter((question) => !answers.some((answer) => answer.id === question.id)).map((question) => question.id);
1380
+ if (missing.length > 0) fail(ERRORS.INVALID_ARGUMENT, `every question must be answered; missing: ${missing.join(', ')}`);
1381
+ }
1271
1382
  const lines = answers.map((answer) => {
1272
1383
  const question = questions.find((candidate) => candidate.id === answer.id);
1273
1384
  return `- ${question?.text ?? answer.id}: ${answer.value}`;
@@ -1295,7 +1406,7 @@ export class TeamService {
1295
1406
  const next = ackInboxItem(item, { disposition: 'done', decision: { answers, note: payload.note ?? '', body } }, { at: this.now() });
1296
1407
  await this.ledger.append({
1297
1408
  type: 'inbox/acked',
1298
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1409
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1299
1410
  actor: command.actor,
1300
1411
  projectId: command.projectId,
1301
1412
  at: this.now(),
@@ -1307,10 +1418,16 @@ export class TeamService {
1307
1418
  const state = this.state;
1308
1419
  const item = state.inbox?.[payload.itemId];
1309
1420
  if (item === undefined) fail(ERRORS.NOT_FOUND, `inbox item ${String(payload.itemId)} not found`);
1421
+ // 归属校验:成员只能处理自己的收件项。缺了这条,任意 agent 可用一个
1422
+ // itemId 把别人的(含 Human 的)决策项标成 resolved。
1423
+ const actorMemberId = command.actor.memberId ?? this.humanId();
1424
+ if (command.actor.kind !== 'human' && item.memberId !== actorMemberId) {
1425
+ fail(ERRORS.UNAUTHORIZED, 'inbox item belongs to another member');
1426
+ }
1310
1427
  const next = ackInboxItem(item, { disposition: payload.disposition, decision: payload.decision }, { at: this.now() });
1311
1428
  await this.ledger.append({
1312
1429
  type: 'inbox/acked',
1313
- payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
1430
+ payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, decision: next.decision ?? null, at: next.ackedAt },
1314
1431
  actor: command.actor,
1315
1432
  correlationId: command.correlationId,
1316
1433
  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