@suifei/dsh-ai-team 0.3.54 → 0.3.60

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.
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from 'node:fs';
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
2
  import { ERRORS, fail } from '../domain/errors.js';
3
3
  import { findReportPath, parseDecisionQuestions } from './decision-report.js';
4
4
  import { ids } from '../domain/ids.js';
@@ -18,7 +18,7 @@ import {
18
18
  submitTask,
19
19
  } from '../domain/task.js';
20
20
  import { appendReply, createThread } from '../domain/thread.js';
21
- import { boardView, quadrantsView } from './views.js';
21
+ import { boardView, quadrantsView, taskCard } from './views.js';
22
22
  import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-config.js';
23
23
  import { isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
24
24
 
@@ -40,18 +40,27 @@ function mentionsHuman(body) {
40
40
  */
41
41
  export class TeamService {
42
42
  /**
43
- * @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number }} options
43
+ * @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number, diag?: { append: (row: any) => any } }} options
44
44
  */
45
45
  constructor(options) {
46
46
  this.ledger = options.ledger;
47
47
  this.now = options.now ?? (() => Date.now());
48
48
  this.memberConfigPolicy = options.memberConfigPolicy ?? {};
49
+ /** Diagnostic sink ({ append(row) }); optional so tests run without it. */
50
+ this.diag = options.diag ?? null;
49
51
  }
50
52
 
51
53
  get state() {
52
54
  return this.ledger.state;
53
55
  }
54
56
 
57
+ /** The Human member id, derived once per call from the folded state. */
58
+ humanId() {
59
+ return this.state.humanMemberId
60
+ ?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
61
+ ?? null;
62
+ }
63
+
55
64
  /** Four-column board derived from the same ledger state. */
56
65
  board(projectId, options = {}) {
57
66
  if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
@@ -65,9 +74,7 @@ export class TeamService {
65
74
  if (projectId !== undefined && this.state.projects?.[projectId] === undefined) {
66
75
  fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
67
76
  }
68
- const human = options.humanMemberId ?? this.state.humanMemberId
69
- ?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
70
- ?? 'mem_human';
77
+ const human = options.humanMemberId ?? this.humanId() ?? 'mem_human';
71
78
  return quadrantsView(this.state, { ...options, humanMemberId: human });
72
79
  }
73
80
 
@@ -101,37 +108,28 @@ export class TeamService {
101
108
  lastRecoveredAt: m.lastRecoveredAt ?? null,
102
109
  }));
103
110
  const agents = members.filter((m) => m.kind !== 'human');
111
+ // One Task card shape for board, quadrants and bootstrap; bootstrap only
112
+ // adds the submission bookkeeping the panel needs.
104
113
  const tasks = Object.values(state.tasks ?? {})
105
114
  .filter((task) => task.tombstone !== true && task.status !== 'deleted')
106
- .map((task) => ({
107
- id: task.id,
108
- number: task.number,
109
- title: task.title,
110
- status: task.status,
111
- owner: state.members?.[task.ownerId]?.name ?? task.ownerId,
112
- ownerId: task.ownerId,
113
- assignee: task.assigneeId === null || task.assigneeId === undefined ? null : (state.members?.[task.assigneeId]?.name ?? task.assigneeId),
114
- assigneeId: task.assigneeId ?? null,
115
- replies: state.threads?.[task.id]?.headSeq ?? 0,
116
- following: (state.followers?.[task.id] ?? []).length > 0,
117
- blockedBy: task.blockedBy ?? [],
118
- revision: task.revision,
119
- resultDefinition: task.resultDefinition,
120
- qaRequired: task.qaRequired === true,
121
- qaChecklist: task.qaChecklist ?? [],
122
- qaChecks: task.qaChecks ?? [],
123
- updatedAt: task.updatedAt ?? task.createdAt ?? null,
124
- }));
115
+ .map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
125
116
  const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
126
- const stream = project === undefined ? [] : (state.stream ?? []).filter((entry) => entry.projectId === project.id);
117
+ // 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
118
+ // stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
119
+ const stream = project === undefined
120
+ ? []
121
+ : (state.stream ?? []).filter((entry) => entry.projectId === project.id).slice(-200);
127
122
  const selected = threadTaskId ?? tasks.find((task) => task.status === 'in_progress')?.id ?? tasks[0]?.id;
128
- const thread = selected === undefined ? null : (state.threads?.[selected] ?? { taskId: selected, headSeq: 0, entries: [] });
129
- const threads = Object.fromEntries(tasks.map((task) => [
130
- task.id,
131
- state.threads?.[task.id] ?? { taskId: task.id, headSeq: 0, entries: [] },
132
- ]));
123
+ const threadOf = (taskId) => {
124
+ const full = taskId === undefined || taskId === null ? undefined : state.threads?.[taskId];
125
+ if (full === undefined) return { taskId, headSeq: 0, entries: [], entryTotal: 0 };
126
+ const entries = Array.isArray(full.entries) ? full.entries : [];
127
+ return { ...full, entries: entries.slice(-50), entryTotal: full.headSeq ?? entries.length };
128
+ };
129
+ const thread = selected === undefined ? null : threadOf(selected);
130
+ const threads = Object.fromEntries(tasks.map((task) => [task.id, threadOf(task.id)]));
133
131
  const inbox = Object.values(state.inbox ?? {}).filter((item) =>
134
- (item.memberId === state.humanMemberId || item.memberId === 'h1')
132
+ (item.memberId === this.humanId())
135
133
  && !isInformationalThreadMention(item));
136
134
  return {
137
135
  project: project ?? null,
@@ -154,9 +152,7 @@ export class TeamService {
154
152
  * per-entry dedupe makes it idempotent.
155
153
  */
156
154
  async backfillHumanMentions(workspacePath = '') {
157
- const humanId = this.state.humanMemberId
158
- ?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
159
- ?? null;
155
+ const humanId = this.humanId();
160
156
  if (humanId === null) return 0;
161
157
  const projectId = Object.keys(this.state.projects ?? {})[0];
162
158
  let reportPath = null;
@@ -168,6 +164,13 @@ export class TeamService {
168
164
  if (reportPath !== null) break;
169
165
  }
170
166
  let reportQuestions = [];
167
+ if (reportPath !== null) {
168
+ try {
169
+ // An agent-authored path drives a server-side read here; cap the
170
+ // read so a giant or adversarial report cannot flood memory.
171
+ if (statSync(reportPath).size > 256 * 1024) reportPath = null;
172
+ } catch { reportPath = null; }
173
+ }
171
174
  if (reportPath !== null) {
172
175
  try {
173
176
  reportQuestions = parseDecisionQuestions(readFileSync(reportPath, 'utf8'));
@@ -227,48 +230,102 @@ export class TeamService {
227
230
  async dispatch(command) {
228
231
  const payload = command.payload ?? {};
229
232
  const actor = command.actor;
230
- if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
231
- fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
232
- }
233
- switch (command.type) {
234
- case 'project.create': return await this.createProject(command, payload);
235
- case 'project.owner.update': return await this.changeProjectOwner(command, payload);
236
- case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
237
- case 'project.pmo.update': return await this.setProjectPmo(command, payload);
238
- case 'stream.post': return await this.postStream(command, payload);
239
- case 'member.add': return await this.addMember(command, payload);
240
- case 'member.bind': return await this.bindMemberSession(command, payload);
241
- case 'member.fail': return await this.failMember(command, payload);
242
- case 'member.retire': return await this.retireMember(command, payload);
243
- case 'member.profile.update': return await this.updateMemberProfile(command, payload);
244
- case 'member.evolve': return await this.evolveMember(command, payload);
245
- case 'member.distill': return await this.distillMember(command, payload);
246
- case 'member.leave': return await this.leaveMember(command, payload);
247
- case 'member.rejoin': return await this.rejoinMember(command, payload);
248
- case 'member.takeover': return await this.takeoverMember(command, payload);
249
- case 'member.message': return await this.messageMember(command, payload);
250
- case 'member.note': return await this.addMemberNote(command, payload);
251
- case 'member.skill': return await this.addMemberSkill(command, payload);
252
- case 'member.config.update': return await this.updateMemberConfig(command, payload);
253
- case 'member.retry': return await this.retryMember(command, payload);
254
- case 'task.create': return await this.createTask(command, payload);
255
- case 'task.claim': return await this.taskCommand(command, 'claim');
256
- case 'task.release': return await this.taskCommand(command, 'release');
257
- case 'task.assign': return await this.taskCommand(command, 'assign');
258
- case 'task.submit': return await this.taskCommand(command, 'submit');
259
- case 'task.accept': return await this.taskCommand(command, 'accept');
260
- case 'task.request_changes': return await this.taskCommand(command, 'request_changes');
261
- case 'task.cancel': return await this.taskCommand(command, 'cancel');
262
- case 'task.reopen': return await this.taskCommand(command, 'reopen');
263
- case 'task.reassign': return await this.taskCommand(command, 'reassign');
264
- case 'task.delete': return await this.taskCommand(command, 'delete');
265
- case 'task.convert': return await this.convert(command, payload);
266
- case 'task.follow': return await this.follow(command, payload);
267
- case 'thread.post': return await this.postThread(command, payload);
268
- case 'inbox.ack': return await this.ack(command, payload);
269
- case 'decision.request': return await this.requestDecision(command, payload);
270
- case 'decision.answer': return await this.answerDecision(command, payload);
271
- default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
233
+ // Diagnostic trail: one entry row per command, one failure row on throw,
234
+ // one done row with the duration in every case. 前置校验失败也必须留痕
235
+ // (errors 档只留 .fail 行,校验抛出必须发生在 try 内才能落行)。
236
+ const startedAt = Date.now();
237
+ const failRow = (code, message) => {
238
+ this.diag?.append({
239
+ ev: 'dispatch.fail',
240
+ type: command.type,
241
+ code,
242
+ projectId: command.projectId ?? null,
243
+ message,
244
+ elapsedMs: Date.now() - startedAt,
245
+ });
246
+ };
247
+ this.diag?.append({
248
+ ev: 'dispatch.start',
249
+ type: command.type,
250
+ actor: actor?.kind ?? null,
251
+ memberId: actor?.memberId ?? null,
252
+ projectId: command.projectId ?? null,
253
+ });
254
+ try {
255
+ if (actor === undefined || (actor.kind !== 'human' && actor.kind !== 'agent')) {
256
+ failRow(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
257
+ fail(ERRORS.UNAUTHORIZED, 'an exact Team member is required');
258
+ }
259
+ // An agent actor must resolve to a live, non-retired member: otherwise a
260
+ // forged or stale memberId would bypass owner/QA checks downstream.
261
+ if (actor.kind === 'agent') {
262
+ const actingMember = this.state.members?.[actor.memberId];
263
+ if (actingMember === undefined || actingMember.kind !== 'agent') {
264
+ failRow(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
265
+ fail(ERRORS.UNAUTHORIZED, `agent actor ${String(actor.memberId ?? '?')} is not a Team member`);
266
+ }
267
+ if (actingMember.status === 'retired') {
268
+ failRow(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
269
+ fail(ERRORS.INVALID_STATE, `agent ${actingMember.name ?? actingMember.id} is retired`);
270
+ }
271
+ }
272
+ switch (command.type) {
273
+ case 'project.create': return await this.createProject(command, payload);
274
+ case 'project.owner.update': return await this.changeProjectOwner(command, payload);
275
+ case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
276
+ case 'project.pmo.update': return await this.setProjectPmo(command, payload);
277
+ case 'stream.post': return await this.postStream(command, payload);
278
+ case 'member.add': return await this.addMember(command, payload);
279
+ case 'member.bind': return await this.bindMemberSession(command, payload);
280
+ case 'member.fail': return await this.failMember(command, payload);
281
+ case 'member.retire': return await this.retireMember(command, payload);
282
+ case 'member.profile.update': return await this.updateMemberProfile(command, payload);
283
+ case 'member.evolve': return await this.evolveMember(command, payload);
284
+ case 'member.distill': return await this.distillMember(command, payload);
285
+ case 'member.leave': return await this.leaveMember(command, payload);
286
+ case 'member.rejoin': return await this.rejoinMember(command, payload);
287
+ case 'member.takeover': return await this.takeoverMember(command, payload);
288
+ case 'member.message': return await this.messageMember(command, payload);
289
+ case 'member.note': return await this.addMemberNote(command, payload);
290
+ case 'member.skill': return await this.addMemberSkill(command, payload);
291
+ case 'member.config.update': return await this.updateMemberConfig(command, payload);
292
+ case 'member.retry': return await this.retryMember(command, payload);
293
+ case 'task.create': return await this.createTask(command, payload);
294
+ case 'task.claim': return await this.taskCommand(command, 'claim');
295
+ case 'task.release': return await this.taskCommand(command, 'release');
296
+ case 'task.assign': return await this.taskCommand(command, 'assign');
297
+ case 'task.submit': return await this.taskCommand(command, 'submit');
298
+ case 'task.accept': return await this.taskCommand(command, 'accept');
299
+ case 'task.request_changes': return await this.taskCommand(command, 'request_changes');
300
+ case 'task.cancel': return await this.taskCommand(command, 'cancel');
301
+ case 'task.reopen': return await this.taskCommand(command, 'reopen');
302
+ case 'task.reassign': return await this.taskCommand(command, 'reassign');
303
+ case 'task.delete': return await this.taskCommand(command, 'delete');
304
+ case 'task.convert': return await this.convert(command, payload);
305
+ case 'task.follow': return await this.follow(command, payload);
306
+ case 'thread.post': return await this.postThread(command, payload);
307
+ case 'inbox.ack': return await this.ack(command, payload);
308
+ case 'decision.request': return await this.requestDecision(command, payload);
309
+ case 'decision.answer': return await this.answerDecision(command, payload);
310
+ default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
311
+ }
312
+ } catch (error) {
313
+ this.diag?.append({
314
+ ev: 'dispatch.fail',
315
+ type: command.type,
316
+ code: error?.code ?? 'INTERNAL',
317
+ projectId: command.projectId ?? null,
318
+ message: error?.message ?? String(error),
319
+ elapsedMs: Date.now() - startedAt,
320
+ });
321
+ throw error;
322
+ } finally {
323
+ this.diag?.append({
324
+ ev: 'dispatch.done',
325
+ type: command.type,
326
+ projectId: command.projectId ?? null,
327
+ elapsedMs: Date.now() - startedAt,
328
+ });
272
329
  }
273
330
  }
274
331
 
@@ -287,7 +344,7 @@ export class TeamService {
287
344
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may create a Project');
288
345
  if (typeof payload.name !== 'string' || payload.name.trim() === '') fail(ERRORS.INVALID_ARGUMENT, 'project name is required');
289
346
  const id = this.ledger.projectId ?? payload.id ?? ids.project();
290
- const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? 'h1';
347
+ const ownerMemberId = payload.ownerId ?? command.actor.memberId ?? this.humanId();
291
348
  const project = {
292
349
  id,
293
350
  name: payload.name.trim(),
@@ -354,8 +411,9 @@ export class TeamService {
354
411
  if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'stream message body is required');
355
412
  const author = this.state.members?.[command.actor.memberId];
356
413
  if (author === undefined) fail(ERRORS.UNAUTHORIZED, 'actor must be a Team member');
414
+ // seq 由账本事件定(fold 用 event.seq;payload 里的幻影计数会被忽略,
415
+ // 并发下还会重复——曾造成 API 返回值与投影不一致)。
357
416
  const entry = {
358
- seq: (this.state.stream?.at(-1)?.seq ?? 0) + 1,
359
417
  kind: 'human_message',
360
418
  authorId: author.id,
361
419
  body,
@@ -368,7 +426,7 @@ export class TeamService {
368
426
  projectId: command.projectId,
369
427
  at: this.now(),
370
428
  });
371
- return { entry, event };
429
+ return { entry: { ...entry, seq: event.seq }, event };
372
430
  }
373
431
 
374
432
  async addMember(command, payload) {
@@ -395,25 +453,25 @@ export class TeamService {
395
453
  return { member };
396
454
  }
397
455
 
398
- async recordWake(memberId, info) {
456
+ async recordWake(memberId, info, projectId = Object.keys(this.state.projects ?? {})[0]) {
399
457
  const event = {
400
458
  type: info.ok === true ? 'wake/delivered' : 'wake/failed',
401
459
  payload: { memberId, taskId: info.taskId ?? null, reason: info.reason ?? null, messageId: info.messageId ?? null, error: info.error ?? null },
402
460
  actor: { kind: 'system' },
403
- projectId: Object.keys(this.state.projects ?? {})[0],
461
+ projectId,
404
462
  at: this.now(),
405
463
  };
406
464
  await this.ledger.append(event);
407
465
  return event;
408
466
  }
409
467
 
410
- async bindHostSession(sessionId) {
468
+ async bindHostSession(sessionId, projectId = Object.keys(this.state.projects ?? {})[0]) {
411
469
  if (typeof sessionId !== 'string' || sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'host sessionId is required');
412
470
  await this.ledger.append({
413
471
  type: 'team/host-bound',
414
472
  payload: { sessionId },
415
473
  actor: { kind: 'system' },
416
- projectId: Object.keys(this.state.projects ?? {})[0],
474
+ projectId,
417
475
  at: this.now(),
418
476
  });
419
477
  return { sessionId };
@@ -423,6 +481,8 @@ export class TeamService {
423
481
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may bind a member session');
424
482
  const member = this.state.members?.[payload.memberId];
425
483
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
484
+ // 退役成员不得经 bind 复活;重新入队必须走 member.rejoin(清 talentPool)。
485
+ if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired`);
426
486
  if (typeof payload.sessionId !== 'string' || payload.sessionId === '') fail(ERRORS.INVALID_ARGUMENT, 'sessionId is required');
427
487
  await this.append(command, 'member/session-bound', {
428
488
  memberId: member.id,
@@ -646,6 +706,8 @@ export class TeamService {
646
706
  async retryMember(command, payload) {
647
707
  const member = this.state.members?.[payload.memberId];
648
708
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
709
+ // 退役成员的重启必须走 member.rejoin(清 talentPool/leftTeamAt)。
710
+ if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.name ?? member.id} is retired; use member.rejoin`);
649
711
  const project = this.state.projects?.[command.projectId];
650
712
  const isHuman = command.actor.kind === 'human';
651
713
  const isLead = project?.ownerMemberId === command.actor.memberId || project?.ownerId === command.actor.memberId;
@@ -658,7 +720,7 @@ export class TeamService {
658
720
  }
659
721
 
660
722
  /** Host/Waker calls these; actor is system, never a Human decision. */
661
- async recordMemberFailure(memberId, failure) {
723
+ async recordMemberFailure(memberId, failure, projectId = Object.keys(this.state.projects ?? {})[0]) {
662
724
  const member = this.state.members?.[memberId];
663
725
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
664
726
  const attempt = Number.isSafeInteger(failure.attempt) ? failure.attempt : (member.lastFailure?.attempt ?? 0) + 1;
@@ -668,14 +730,21 @@ export class TeamService {
668
730
  type: 'member/llm-failed',
669
731
  payload: { ...recorded, memberId, fatal },
670
732
  actor: { kind: 'system' },
671
- projectId: Object.keys(this.state.projects ?? {})[0],
733
+ projectId,
672
734
  at: this.now(),
673
735
  });
736
+ this.diag?.append({
737
+ ev: fatal ? 'member.fail' : 'member.llm-failed',
738
+ memberId,
739
+ category: recorded.category,
740
+ attempt,
741
+ provider: recorded.provider ?? null,
742
+ model: recorded.model ?? null,
743
+ projectId,
744
+ });
674
745
  let inboxItem = null;
675
746
  if (fatal) {
676
- const humanId = this.state.humanMemberId
677
- ?? Object.values(this.state.members ?? {}).find((candidate) => candidate.kind === 'human')?.id
678
- ?? null;
747
+ const humanId = this.humanId();
679
748
  const duplicate = humanId === null ? undefined : Object.values(this.state.inbox ?? {}).find((item) =>
680
749
  item.memberId === humanId
681
750
  && item.requiresDecision === true
@@ -697,7 +766,7 @@ export class TeamService {
697
766
  type: 'inbox/item-created',
698
767
  payload: { itemId: inboxItem.id, ...inboxItem },
699
768
  actor: { kind: 'system' },
700
- projectId: Object.keys(this.state.projects ?? {})[0],
769
+ projectId,
701
770
  at: this.now(),
702
771
  });
703
772
  }
@@ -709,7 +778,7 @@ export class TeamService {
709
778
  }
710
779
 
711
780
  /** Fallback changes are system-authored config events, rollback-able by Human. */
712
- async applySystemFallback(memberId, patch, reason = 'llm-fallback') {
781
+ async applySystemFallback(memberId, patch, reason = 'llm-fallback', projectId = Object.keys(this.state.projects ?? {})[0]) {
713
782
  const member = this.state.members?.[memberId];
714
783
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
715
784
  const current = normalizeMemberConfig(member.config ?? {});
@@ -718,6 +787,13 @@ export class TeamService {
718
787
  configVersion: member.configVersion ?? 0,
719
788
  });
720
789
  if (!result.changed) return { member, config: current, changed: false };
790
+ this.diag?.append({
791
+ ev: 'member.fallback',
792
+ memberId,
793
+ reason,
794
+ patch,
795
+ projectId,
796
+ });
721
797
  const nextConfig = {
722
798
  ...result.config,
723
799
  updatedBy: 'system',
@@ -734,22 +810,23 @@ export class TeamService {
734
810
  reason,
735
811
  },
736
812
  actor: { kind: 'system' },
737
- projectId: Object.keys(this.state.projects ?? {})[0],
813
+ projectId,
738
814
  at: this.now(),
739
815
  });
740
816
  return { member: { ...member, config: nextConfig, configVersion: nextConfig.configVersion }, config: nextConfig, changed: true };
741
817
  }
742
818
 
743
- async recordMemberRecovery(memberId, attempt, effectiveConfig) {
819
+ async recordMemberRecovery(memberId, attempt, effectiveConfig, projectId = Object.keys(this.state.projects ?? {})[0]) {
744
820
  const member = this.state.members?.[memberId];
745
821
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
746
822
  await this.ledger.append({
747
823
  type: 'member/recovered',
748
824
  payload: { memberId, attempt, effectiveConfig: effectiveConfig ?? member.config ?? null },
749
825
  actor: { kind: 'system' },
750
- projectId: Object.keys(this.state.projects ?? {})[0],
826
+ projectId,
751
827
  at: this.now(),
752
828
  });
829
+ this.diag?.append({ ev: 'member.recovered', memberId, attempt, projectId });
753
830
  return { member: { ...member, status: 'running', lastRecoveredAt: this.now() } };
754
831
  }
755
832
 
@@ -809,7 +886,14 @@ export class TeamService {
809
886
  case 'assign': outcome = assignTask(task, command.actor, command.payload?.assigneeId, { expectedRevision, at: this.now() }); break;
810
887
  case 'submit': outcome = submitTask(task, command.actor, { summary: command.payload?.summary, evidence: command.payload?.evidence }, { expectedRevision, at: this.now() }); break;
811
888
  case 'accept': {
812
- const reviewer = command.actor.kind === 'agent' ? state.members?.[command.actor.memberId] : null;
889
+ // Agent actors are pre-resolved by dispatch; resolve defensively here
890
+ // so an unknown memberId fails closed instead of skipping the QA gate.
891
+ const reviewer = command.actor.kind === 'agent'
892
+ ? this.state.members?.[command.actor.memberId] ?? undefined
893
+ : null;
894
+ if (command.actor.kind === 'agent' && reviewer === undefined) {
895
+ fail(ERRORS.UNAUTHORIZED, `agent actor ${String(command.actor.memberId ?? '?')} is not a Team member`);
896
+ }
813
897
  if (task.qaRequired === true && reviewer !== null && !isQaMember(reviewer)) {
814
898
  fail(ERRORS.INVALID_STATE, 'this task requires a QA reviewer');
815
899
  }
@@ -892,7 +976,7 @@ export class TeamService {
892
976
  const following = payload.following === true;
893
977
  await this.ledger.append({
894
978
  type: following ? 'task/followed' : 'task/unfollowed',
895
- payload: { taskId: payload.taskId, memberId: command.actor.memberId ?? 'h1' },
979
+ payload: { taskId: payload.taskId, memberId: command.actor.memberId ?? this.humanId() },
896
980
  actor: command.actor,
897
981
  correlationId: command.correlationId,
898
982
  projectId: command.projectId,
@@ -907,7 +991,7 @@ export class TeamService {
907
991
  if (state.tasks?.[taskId] === undefined) fail(ERRORS.NOT_FOUND, `task ${String(taskId)} not found`);
908
992
  const thread = state.threads?.[taskId] ?? createThread(taskId);
909
993
  const actorKind = command.actor.kind;
910
- const authorId = command.actor.memberId ?? 'h1';
994
+ const authorId = command.actor.memberId ?? this.humanId();
911
995
  const outcome = appendReply(thread, { authorId, actorKind, baseSeq: payload.baseSeq, body: payload.body, refs: payload.refs }, { at: this.now() });
912
996
  await this.ledger.append({
913
997
  type: 'thread/posted',
@@ -921,10 +1005,8 @@ export class TeamService {
921
1005
  }
922
1006
 
923
1007
  /** PMO: answer all pending structured questions with the max-value policy. */
924
- async autoAnswerDecisions() {
925
- const humanId = this.state.humanMemberId
926
- ?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
927
- ?? null;
1008
+ async autoAnswerDecisions(projectId = Object.keys(this.state.projects ?? {})[0]) {
1009
+ const humanId = this.humanId();
928
1010
  if (humanId === null) return 0;
929
1011
  const items = Object.values(this.state.inbox ?? {}).filter((item) =>
930
1012
  item.memberId === humanId
@@ -934,12 +1016,12 @@ export class TeamService {
934
1016
  for (const item of items) {
935
1017
  const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
936
1018
  const answers = chooseDecisionAnswers(questions);
937
- results.push(await this.autoAnswerDecision(item, answers));
1019
+ results.push(await this.autoAnswerDecision(item, answers, projectId));
938
1020
  }
939
1021
  return results;
940
1022
  }
941
1023
 
942
- async autoAnswerDecision(item, answers) {
1024
+ async autoAnswerDecision(item, answers, projectId = Object.keys(this.state.projects ?? {})[0]) {
943
1025
  const taskId = typeof item.ref?.taskId === 'string' ? item.ref.taskId : null;
944
1026
  const task = taskId === null ? undefined : this.state.tasks?.[taskId];
945
1027
  const questionById = new Map((item.ref?.questions ?? []).map((question) => [question.id, question.text]));
@@ -960,7 +1042,7 @@ export class TeamService {
960
1042
  type: 'thread/posted',
961
1043
  payload: { taskId: task.id, ...outcome.entry },
962
1044
  actor: { kind: 'system', memberId: 'mem_pmo' },
963
- projectId: Object.keys(this.state.projects ?? {})[0],
1045
+ projectId,
964
1046
  at: this.now(),
965
1047
  });
966
1048
  entry = outcome.entry;
@@ -969,11 +1051,18 @@ export class TeamService {
969
1051
  disposition: 'done',
970
1052
  decision: { answers, auto: true, by: 'mem_pmo', body },
971
1053
  }, { at: this.now() });
1054
+ this.diag?.append({
1055
+ ev: 'pmo.auto-answer',
1056
+ itemId: item.id,
1057
+ taskId,
1058
+ answers: answers.length,
1059
+ projectId,
1060
+ });
972
1061
  await this.ledger.append({
973
1062
  type: 'inbox/acked',
974
1063
  payload: { itemId: next.id, memberId: next.memberId, state: next.state, disposition: next.disposition, at: next.ackedAt },
975
1064
  actor: { kind: 'system', memberId: 'mem_pmo' },
976
- projectId: Object.keys(this.state.projects ?? {})[0],
1065
+ projectId,
977
1066
  at: this.now(),
978
1067
  });
979
1068
  return { item: next, entry };
@@ -981,9 +1070,7 @@ export class TeamService {
981
1070
 
982
1071
  /** Surface an explicit Human decision request with all questions inline. */
983
1072
  async requestDecision(command, payload) {
984
- const humanId = this.state.humanMemberId
985
- ?? Object.values(this.state.members ?? {}).find((member) => member.kind === 'human')?.id
986
- ?? null;
1073
+ const humanId = this.humanId();
987
1074
  if (humanId === null) fail(ERRORS.NOT_FOUND, 'Human member not found');
988
1075
  const raw = Array.isArray(payload.questions) ? payload.questions : [];
989
1076
  if (raw.length === 0 || raw.length > 20) fail(ERRORS.INVALID_ARGUMENT, 'questions must contain 1..20 items');
package/lib/host/views.js CHANGED
@@ -6,21 +6,15 @@
6
6
  */
7
7
 
8
8
  import { isInformationalThreadMention } from '../domain/inbox.js';
9
-
10
- const ACTIVE_MEMBER_STATUSES = new Set(['provisioning', 'running', 'idle']);
9
+ import { isReviewCandidate } from '../domain/policy.js';
10
+ import { isTaskBlocked } from '../ledger/fold.js';
11
11
 
12
12
  function nameOf(state, memberId) {
13
13
  if (memberId === null || memberId === undefined) return null;
14
14
  return state.members?.[memberId]?.name ?? memberId;
15
15
  }
16
16
 
17
- function isBlocked(state, task) {
18
- if (!Array.isArray(task.blockedBy) || task.blockedBy.length === 0) return false;
19
- return task.blockedBy.some((id) => {
20
- const dependency = state.tasks?.[id];
21
- return dependency === undefined || dependency.status !== 'done' || dependency.tombstone === true;
22
- });
23
- }
17
+ const isBlocked = (state, task) => isTaskBlocked(state, task);
24
18
 
25
19
  function threadReplies(state, taskId) {
26
20
  return state.threads?.[taskId]?.headSeq ?? 0;
@@ -34,7 +28,9 @@ export function taskCard(state, task) {
34
28
  title: task.title ?? '',
35
29
  status: task.status,
36
30
  owner: nameOf(state, task.ownerId ?? task.accountableOwnerId),
31
+ ownerId: task.ownerId ?? task.accountableOwnerId ?? null,
37
32
  assignee: nameOf(state, task.assigneeId),
33
+ assigneeId: task.assigneeId ?? null,
38
34
  replies: threadReplies(state, task.id),
39
35
  following: (state.followers?.[task.id] ?? []).length > 0,
40
36
  blockedBy: Array.isArray(task.blockedBy) ? [...task.blockedBy] : [],
@@ -50,13 +46,7 @@ export function taskCard(state, task) {
50
46
 
51
47
  /** Agent members that may still be asked to review (not retired/failed). */
52
48
  function eligibleAgents(state, task) {
53
- const claimed = new Set(Array.isArray(task.claimHistory) ? task.claimHistory : []);
54
- return Object.values(state.members ?? {}).filter((member) => {
55
- if (member.kind === 'human') return false;
56
- if (!ACTIVE_MEMBER_STATUSES.has(member.status)) return false;
57
- if (member.id === task.assigneeId) return false;
58
- return !claimed.has(member.id);
59
- });
49
+ return Object.values(state.members ?? {}).filter((member) => isReviewCandidate(member, task));
60
50
  }
61
51
 
62
52
  function doneAt(task) {
package/lib/host/waker.js CHANGED
@@ -16,7 +16,10 @@ function agentMember(state, memberId) {
16
16
  if (typeof memberId !== 'string') return null;
17
17
  const member = state.members?.[memberId];
18
18
  if (member === undefined || member.kind !== 'agent') return null;
19
- if (member.status === 'retired') return null;
19
+ // failed 成员不自动唤醒(其 LLM 正在失败,自动唤醒只会烧预算):
20
+ // 恢复走 member.retry(Human/Project owner 显式动作)或 Human 在成员
21
+ // 资料里的「重试」;review 路径另经 eligibleReviewers 的同一排除。
22
+ if (member.status === 'retired' || member.status === 'failed') return null;
20
23
  return member;
21
24
  }
22
25
 
@@ -202,6 +205,13 @@ export function planWakes(state, result, actor = {}) {
202
205
  if (task !== undefined) {
203
206
  const bucket = event.payload?.bucket ?? Math.floor(Date.now() / 3_600_000);
204
207
  add(task.ownerId, task.id, 'pmo_escalate', `pmo_escalate:${task.id}:${bucket}`);
208
+ // Handoffs and meeting decisions live in Thread text; the wake
209
+ // matrix cannot see them. Escalation therefore also reaches the
210
+ // Project owner, who may take the card or re-point it.
211
+ const projectOwner = Object.values(state.projects ?? {})[0]?.ownerMemberId;
212
+ if (projectOwner !== undefined && projectOwner !== task.ownerId) {
213
+ add(projectOwner, task.id, 'pmo_escalate', `pmo_escalate_owner:${task.id}:${bucket}`);
214
+ }
205
215
  }
206
216
  }
207
217
  if (event?.type === 'pmo/heartbeat') {