@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.
package/index.js CHANGED
@@ -11,6 +11,8 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
+ import { readFileSync, writeFileSync } from 'node:fs';
15
+ import z from '@deepseek-ai/schemastery';
14
16
  import { ProjectRuntime } from './lib/host/project-runtime.js';
15
17
  import { ProjectRegistry } from './lib/host/project-registry.js';
16
18
  import { ids } from './lib/domain/ids.js';
@@ -28,16 +30,43 @@ import { installFaultAdapter } from './lib/host/fault-adapter.js';
28
30
  import { buildModelCatalog } from './lib/host/model-catalog.js';
29
31
  import { createTeamTool } from './lib/host/member-tools.js';
30
32
  import { describeWake, planWakes } from './lib/host/waker.js';
33
+ import { aggregatePeople } from './lib/host/people-view.js';
34
+ import { riskView } from './lib/host/risk-view.js';
35
+ import { weeklyView } from './lib/host/weekly-view.js';
36
+ import { isInformationalThreadMention } from './lib/domain/inbox.js';
37
+ import { createDiagLogger, defaultDiagDir } from './lib/diaglog.js';
31
38
 
32
39
  export const name = 'ai-team';
33
40
 
34
41
  /** The workbench only makes sense where the Web carrier exists. */
35
42
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
36
43
 
37
- const VERSION = '0.3.54';
44
+ const VERSION = '0.3.60';
38
45
  const PROJECT_ID = 'prj_main';
39
46
  const HUMAN_ID = 'mem_human';
40
47
 
48
+ const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
49
+
50
+ /**
51
+ * Tunable values live in the plugin Config so users edit their patch layer
52
+ * (the user's patch survives upgrades). Integer fields use `.step(1)`: the
53
+ * bundled schemastery zod face has no `.int()`.
54
+ */
55
+ export const Config = z.object({
56
+ // diaglog level: 'off' silent, 'errors' crash/fail rows only, 'full' all rows
57
+ diagLevel: z.union(['off', 'errors', 'full']).default('errors'),
58
+ // directory of the diagnostic JSONL log (one file per day)
59
+ diagLogDir: z.string().default(defaultDiagDir()),
60
+ // rotation cap for one diagnostic log file
61
+ diagLogMaxBytes: z.number().step(1).min(65536).max(16777216).default(1048576),
62
+ // default SkillOpt backend for skillopt_* tools; 'mock' is the safe shipped
63
+ // default (no model calls, no live-file writes) — a real backend must be
64
+ // configured here or passed per call.
65
+ skilloptBackend: z.union(SKILLOPT_BACKENDS).default('mock'),
66
+ // per-call timeout for skillopt_* engine runs
67
+ skilloptTimeoutMs: z.number().step(1).min(10_000).max(600_000).default(120_000),
68
+ });
69
+
41
70
  function send(res, body, status = 200) {
42
71
  if (res.writableEnded) return;
43
72
  res.statusCode = status;
@@ -71,18 +100,12 @@ function profileName() {
71
100
  return process.env.DSH_PROFILE || 'default';
72
101
  }
73
102
 
74
- function errorResponse(res, error) {
75
- const code = typeof error?.code === 'string' ? error.code : 'INTERNAL';
76
- const status = typeof error?.status === 'number' ? error.status : (code === 'E_STORAGE' ? 503 : 409);
77
- send(res, { error: { code, message: error?.message ?? 'command failed', details: error?.details ?? null } }, status);
78
- }
79
-
80
103
  /**
81
104
  * Open the default Project ledger and seed the Human + Project skeleton once.
82
105
  * A torn tail is repaired by the writer; the repair is recorded as a system
83
106
  * event so the append-only history explains the gap.
84
107
  */
85
- async function boot() {
108
+ async function boot(diag) {
86
109
  const dataDir = join(dshHome(), 'ai-team', profileName());
87
110
  const registry = ProjectRegistry.load(dataDir);
88
111
  const runtimes = new Map();
@@ -93,11 +116,19 @@ async function boot() {
93
116
  projectName: project.name,
94
117
  projectGoal: project.goal,
95
118
  workspacePath: project.workspacePath ?? '',
119
+ diag,
96
120
  });
97
121
  runtimes.set(project.id, runtime);
98
122
  }
99
123
  const activeProjectId = registry.activeProjectId;
100
124
  const runtime = runtimes.get(activeProjectId) ?? runtimes.values().next().value;
125
+ diag?.append({
126
+ ev: 'boot.done',
127
+ dataDir,
128
+ projects: [...runtimes.keys()],
129
+ activeProjectId,
130
+ events: [...runtimes.values()].reduce((sum, item) => sum + item.ledger.headSeq, 0),
131
+ });
101
132
  return {
102
133
  ...runtime,
103
134
  runtime,
@@ -110,7 +141,26 @@ async function boot() {
110
141
  };
111
142
  }
112
143
 
113
- export function apply(ctx) {
144
+ export function apply(ctx, config = {}) {
145
+ // Diagnostic log first: every later row (boot, wake, PMO, dispatch) lands
146
+ // here with the configured level ('off'/'errors'/'full', errors shipped).
147
+ // The `??` chain keeps direct apply() calls (tests) on shipped defaults.
148
+ const diag = createDiagLogger({
149
+ dir: config.diagLogDir ?? defaultDiagDir(),
150
+ maxBytes: config.diagLogMaxBytes ?? 1048576,
151
+ level: config.diagLevel ?? 'errors',
152
+ });
153
+ // HTTP 层失败/拒绝的统一落点(route.reject 在 errors 白名单内)。
154
+ const errorResponse = (res, error) => {
155
+ diag.append({
156
+ ev: 'route.reject',
157
+ code: typeof error?.code === 'string' ? error.code : 'INTERNAL',
158
+ message: error?.message ?? String(error ?? 'command failed'),
159
+ });
160
+ const code = typeof error?.code === 'string' ? error.code : 'INTERNAL';
161
+ const status = typeof error?.status === 'number' ? error.status : (code === 'E_STORAGE' ? 503 : 409);
162
+ send(res, { error: { code, message: error?.message ?? 'command failed', details: error?.details ?? null } }, status);
163
+ };
114
164
  ctx.effect(() => {
115
165
  const webServer = ctx.get('webServer');
116
166
  if (webServer === undefined) return () => {};
@@ -137,6 +187,7 @@ export function apply(ctx) {
137
187
  const created = await registry.create?.(path, projectRuntime.service.state.projects[projectRuntime.id]?.name ?? '文渊阁');
138
188
  return created ?? null;
139
189
  } catch (error) {
190
+ diag.append({ ev: 'workspace.fail', projectId: projectRuntime.id, path, message: error?.message ?? String(error) });
140
191
  console.warn('[ai-team] workspace unavailable:', error?.message ?? error);
141
192
  return null;
142
193
  }
@@ -152,7 +203,9 @@ export function apply(ctx) {
152
203
  try {
153
204
  if (typeof titleService.get === 'function' && titleService.get(session)?.title === title) return;
154
205
  titleService.rename(session, title);
206
+ diag.append({ ev: 'session.title', sessionId: member.sessionId, title, projectId: projectRuntime.id });
155
207
  } catch (error) {
208
+ diag.append({ ev: 'session.title.fail', sessionId: member.sessionId, message: error?.message ?? String(error) });
156
209
  console.warn('[ai-team] session title failed:', error?.message ?? error);
157
210
  }
158
211
  };
@@ -163,6 +216,7 @@ export function apply(ctx) {
163
216
  try {
164
217
  await workspace.attachSession(sessionId);
165
218
  } catch (error) {
219
+ diag.append({ ev: 'workspace.attach.fail', sessionId, message: error?.message ?? String(error) });
166
220
  console.warn('[ai-team] member session workspace attach failed:', error?.message ?? error);
167
221
  }
168
222
  };
@@ -180,7 +234,9 @@ export function apply(ctx) {
180
234
  if (session === undefined || session === null || typeof session.append !== 'function') return;
181
235
  session.append('model/selection', { provider: selection.provider, model: selection.model });
182
236
  modelSelectionLogged.set(sessionId, route);
237
+ diag.append({ ev: 'model.selection', sessionId, route, label: label ?? null });
183
238
  } catch (error) {
239
+ diag.append({ ev: 'model.selection.fail', sessionId, label: label ?? null, message: error?.message ?? String(error) });
184
240
  console.warn('[ai-team] model selection persist failed:', label ?? sessionId, error?.message ?? error);
185
241
  }
186
242
  };
@@ -189,7 +245,7 @@ export function apply(ctx) {
189
245
  sandboxPolicy: ctx.get('sandboxPolicy'),
190
246
  });
191
247
  const ready = access.ok
192
- ? Promise.resolve().then(boot)
248
+ ? Promise.resolve().then(() => boot(diag))
193
249
  .then(async (value) => {
194
250
  booted = value;
195
251
  for (const runtime of value.runtimes.values()) {
@@ -200,12 +256,21 @@ export function apply(ctx) {
200
256
  persistModelSelection(member.sessionId, member.config, member.name);
201
257
  }
202
258
  }
203
- void pmoTick(runtime).catch((error) => console.warn('[ai-team] PMO tick failed:', error?.message ?? error));
259
+ // Attach the broadcast/wake hook before the first tick: events
260
+ // produced by the tick must reach SSE clients immediately.
261
+ attachRuntime(runtime);
262
+ void pmoTick(runtime).catch((error) => {
263
+ diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
264
+ console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
265
+ });
204
266
  }
205
267
  if (pmoTimer === null) {
206
268
  pmoTimer = setInterval(() => {
207
269
  for (const runtime of booted?.runtimes?.values() ?? []) {
208
- void pmoTick(runtime).catch((error) => console.warn('[ai-team] PMO tick failed:', error?.message ?? error));
270
+ void pmoTick(runtime).catch((error) => {
271
+ diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
272
+ console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
273
+ });
209
274
  }
210
275
  }, 60_000);
211
276
  pmoTimer.unref?.();
@@ -214,20 +279,26 @@ export function apply(ctx) {
214
279
  })
215
280
  .catch((error) => {
216
281
  bootError = error;
282
+ diag.append({ ev: 'boot.fail', message: error?.message ?? String(error) });
217
283
  console.error('[ai-team] ledger boot failed:', error?.message ?? error);
218
284
  return null;
219
285
  })
220
286
  : Promise.resolve(null);
221
287
  if (!access.ok) {
222
288
  bootError = Object.assign(new Error(access.reason), { code: access.code, status: 503 });
289
+ diag.append({ ev: 'boot.refused', code: access.code, reason: access.reason });
223
290
  console.error('[ai-team] refused to start:', access.code, access.reason);
224
291
  }
225
292
 
226
293
  const sseClients = new Set();
227
294
  const activations = new Map();
228
295
  // DSH exposes a model-request failure waterfall. We classify the failure,
229
- // record it, and only own recovery for retryable categories. No timers:
230
- // a retry is the DSH loop's own decision; our fallback config applies next wake.
296
+ // record it, and own the immediate retry only for transient server/network
297
+ // failures ({ kind: 'retry' } re-dispatches the same request). A fallback
298
+ // patch rewrites the persisted config, which a live step cannot pick up —
299
+ // so the turn ends there and the next wake runs on the new route. Rate
300
+ // limits end the turn too: no backoff clock means an immediate retry just
301
+ // burns the budget against a throttled route.
231
302
  const offRequestError = typeof ctx.on === 'function'
232
303
  ? ctx.on('agent/request-error', async (payload, next) => {
233
304
  if (booted === null) return next();
@@ -242,18 +313,21 @@ export function apply(ctx) {
242
313
  ...failure,
243
314
  provider: payload.provider ?? null,
244
315
  model: member.config?.model ?? null,
245
- });
246
- } catch {
316
+ }, failureRuntime.id);
317
+ } catch (error) {
318
+ console.warn('[ai-team] member failure record failed:', member.id, error?.message ?? error);
247
319
  return next();
248
320
  }
249
321
  if (!failure.retryable) return next();
250
322
  const decision = retryDecision(failure, member.config ?? {}, recorded.member.attempts ?? 1);
251
323
  if (decision.action === 'fallback' && decision.patch !== undefined) {
252
324
  try {
253
- await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback');
254
- } catch { /* policy/rollback failure must not turn into a retry storm */ }
325
+ await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback', failureRuntime.id);
326
+ } catch (error) {
327
+ console.warn('[ai-team] member fallback failed:', member.id, error?.message ?? error);
328
+ }
255
329
  }
256
- if (decision.action === 'fail') return next();
330
+ if (decision.action !== 'retry') return next();
257
331
  return { kind: 'retry' };
258
332
  })
259
333
  : () => {};
@@ -271,14 +345,17 @@ export function apply(ctx) {
271
345
  try {
272
346
  await sessions?.flush?.(session);
273
347
  } catch (error) {
348
+ diag.append({ ev: 'session.flush.fail', sessionId: session?.id ?? null, message: error?.message ?? String(error) });
274
349
  console.warn('[ai-team] member session flush failed:', error?.message ?? error);
275
350
  }
276
351
  if (event?.data?.reason?.kind !== 'completed') return;
277
352
  if (member.lastFailure === undefined || member.lastFailure === null) return;
278
353
  try {
279
- await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null);
354
+ await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null, eventRuntime.id);
280
355
  broadcast(undefined, eventRuntime);
281
- } catch { /* recovery is best-effort; the ledger still has the failure */ }
356
+ } catch (error) {
357
+ console.warn('[ai-team] member recovery record failed:', member.id, error?.message ?? error);
358
+ }
282
359
  })
283
360
  : () => {};
284
361
  let llmFaultMode = null;
@@ -287,22 +364,33 @@ export function apply(ctx) {
287
364
  : () => {};
288
365
  let host = null;
289
366
  let hostPromise = null;
290
- const wakeKeys = new Set();
367
+ const wakeKeys = new Map();
291
368
  const activationTasks = new Map();
292
369
  const pmoLastKick = new Map();
293
370
  const pmoLastStall = new Map();
294
371
  const pmoLastHeartbeat = new Map();
295
372
  const pmoLastEscalate = new Map();
296
373
  const pmoLastReview = new Map();
374
+ // Members resumed from cold sessions produce AgentHandles nobody stored;
375
+ // track them by session id so teardown — and session reseat — can
376
+ // dispose exactly the handle they own.
377
+ const resumedHandles = new Map();
297
378
  let pmoTimer = null;
298
- const projectCwd = (projectRuntime, member) => member?.workspace
379
+ // 项目工作目录(显式,无兜底):null 表示尚未设置。历史版本在此处用
380
+ // runtime.dir(账本目录)兜底,曾把成员会话 cwd 钉进插件数据目录。
381
+ const projectWorkspace = (projectRuntime, member) => member?.workspace
299
382
  || projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath
300
- || projectRuntime?.dir
301
- || undefined;
383
+ || null;
302
384
  const wakeFromResult = async (projectRuntime, result, actor = {}) => {
303
385
  if (projectRuntime === null || projectRuntime === undefined) return;
304
386
  const plans = planWakes(projectRuntime.service.state, result, actor);
305
387
  if (plans.length === 0) return;
388
+ // Window eviction: a key older than this horizon can no longer dedupe
389
+ // a relevant event, so drop it instead of growing the Map forever.
390
+ const head = projectRuntime?.ledger?.head?.seq ?? 0;
391
+ for (const [key, seq] of wakeKeys) {
392
+ if (Number.isSafeInteger(seq) && head - seq > 500) wakeKeys.delete(key);
393
+ }
306
394
  const subagents = ctx.get('subagents');
307
395
  const sessions = ctx.get('sessions');
308
396
  const permissionPresets = ctx.get('permissionPresets');
@@ -321,8 +409,15 @@ export function apply(ctx) {
321
409
  if (member === undefined) continue;
322
410
  // Reserve before the async delivery: the HTTP result and the ledger
323
411
  // event both schedule the same plan, and only one may deliver it.
324
- wakeKeys.add(plan.key);
325
- const cwd = projectCwd(projectRuntime, member);
412
+ wakeKeys.set(plan.key, result?.event?.seq ?? head);
413
+ // 无工作目录的项目不 wake(与 activate 的 fail-closed 同一不变量):
414
+ // 冷恢复/直连唤醒都会在会话原 cwd 里干活,不该落到插件数据目录。
415
+ const projectWorkspacePath = projectWorkspace(projectRuntime, member);
416
+ if (projectWorkspacePath === null || projectWorkspacePath.trim?.() === '') {
417
+ diag?.append({ ev: 'wake.skip', projectId: projectRuntime.id, memberId: plan.memberId, reason: 'E_WORKSPACE_REQUIRED' });
418
+ continue;
419
+ }
420
+ const cwd = projectWorkspacePath;
326
421
  try {
327
422
  // Idle default members have no Agent session yet. A wake must
328
423
  // activate them first; otherwise the first Human message is
@@ -356,6 +451,7 @@ export function apply(ctx) {
356
451
  provider: providers[0],
357
452
  preset: 'standard',
358
453
  cwd,
454
+ trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
359
455
  });
360
456
  const delivered = await runtime.wake(member, { prompt: await wakePrompt(plan, member) });
361
457
  messageId = delivered.messageId ?? null;
@@ -365,14 +461,32 @@ export function apply(ctx) {
365
461
  }
366
462
  await projectRuntime.service.recordWake(plan.memberId, {
367
463
  ok: true, taskId: plan.taskId, reason: plan.reason, messageId,
464
+ }, projectRuntime.id);
465
+ diag.append({
466
+ ev: 'wake.delivered',
467
+ projectId: projectRuntime.id,
468
+ memberId: plan.memberId,
469
+ taskId: plan.taskId ?? null,
470
+ reason: plan.reason,
471
+ activated: member.sessionId === undefined || messageId === null ? 'activation' : 'wake',
472
+ messageId,
368
473
  });
369
474
  } catch (error) {
370
475
  wakeKeys.delete(plan.key);
476
+ diag.append({
477
+ ev: 'wake.fail',
478
+ projectId: projectRuntime.id,
479
+ memberId: plan.memberId,
480
+ taskId: plan.taskId ?? null,
481
+ reason: plan.reason,
482
+ code: error?.code ?? null,
483
+ message: error?.message ?? String(error),
484
+ });
371
485
  console.warn('[ai-team] wake failed:', plan.memberId, error?.code ?? error?.message ?? error);
372
486
  try {
373
487
  await projectRuntime.service.recordWake(plan.memberId, {
374
488
  ok: false, taskId: plan.taskId, reason: plan.reason, error: error?.code ?? error?.message ?? String(error),
375
- });
489
+ }, projectRuntime.id);
376
490
  } catch { /* ledger may be closed */ }
377
491
  }
378
492
  }
@@ -387,7 +501,7 @@ export function apply(ctx) {
387
501
  await titleMemberSession(projectRuntime, member);
388
502
  }
389
503
  }
390
- const results = await projectRuntime.service.autoAnswerDecisions();
504
+ const results = await projectRuntime.service.autoAnswerDecisions(projectRuntime.id);
391
505
  for (const result of results) {
392
506
  const taskId = result?.item?.ref?.taskId;
393
507
  if (typeof taskId === 'string' && result.entry !== null && result.entry !== undefined) {
@@ -449,7 +563,17 @@ export function apply(ctx) {
449
563
  event: { type: 'pmo/stall', payload: { taskId: task.id, bucket: Math.floor(now / 1_800_000) } },
450
564
  }, {});
451
565
  }
452
- if (active.length > 0) return;
566
+ if (active.length > 0) {
567
+ // Prune per-task clock entries whose task left the active set, so
568
+ // the five Map keys track live work instead of growing forever.
569
+ const live = new Set(active.map((task) => task.id));
570
+ for (const map of [pmoLastReview, pmoLastHeartbeat, pmoLastEscalate, pmoLastStall]) {
571
+ for (const taskId of map.keys()) {
572
+ if (!live.has(taskId)) map.delete(taskId);
573
+ }
574
+ }
575
+ return;
576
+ }
453
577
  const last = pmoLastKick.get(projectRuntime.id) ?? 0;
454
578
  if (now - last < 10 * 60_000) return;
455
579
  pmoLastKick.set(projectRuntime.id, now);
@@ -494,8 +618,12 @@ export function apply(ctx) {
494
618
  const stream = llm.stream({
495
619
  provider: selection.provider,
496
620
  model: selection.model,
497
- system: '你是团队的人格蒸馏器。只输出要求的 JSON,不调用工具。',
498
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
621
+ // GenerateOptions has no top-level `system` field; the distiller
622
+ // constraint travels as a system-role message.
623
+ messages: [
624
+ { role: 'system', content: [{ type: 'text', text: '你是团队的人格蒸馏器。只输出要求的 JSON,不调用工具。' }] },
625
+ { role: 'user', content: [{ type: 'text', text: prompt }] },
626
+ ],
499
627
  maxTokens: 400,
500
628
  });
501
629
  for await (const chunk of stream) {
@@ -535,6 +663,7 @@ export function apply(ctx) {
535
663
  bundledDir: fileURLToPath(new URL('./', import.meta.url)),
536
664
  }) ?? (() => {});
537
665
  } catch (error) {
666
+ diag.append({ ev: 'skill.provider.fail', message: error?.message ?? String(error) });
538
667
  console.warn('[ai-team] file skill provider failed:', error?.message ?? error);
539
668
  }
540
669
  const tools = ctx.get('tools');
@@ -542,17 +671,21 @@ export function apply(ctx) {
542
671
  try {
543
672
  const shell = ctx.get('shell');
544
673
  if (tools?.register && shell) {
674
+ // Backend/timeout come from the plugin Config (patch layer), so an
675
+ // operator can move the skillopt_* tools off the safe mock default.
545
676
  disposeSkillOpt = applySkillOpt({
546
677
  tools,
547
678
  shell,
548
679
  logger: console,
549
680
  }, {
550
- backend: 'mock',
681
+ backend: config.skilloptBackend ?? 'mock',
551
682
  project: process.cwd(),
552
- timeoutMs: 120_000,
683
+ timeoutMs: config.skilloptTimeoutMs ?? 120_000,
553
684
  }) ?? (() => {});
685
+ diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000 });
554
686
  }
555
687
  } catch (error) {
688
+ diag.append({ ev: 'skillopt.fail', message: error?.message ?? String(error) });
556
689
  console.warn('[ai-team] bundled SkillOpt tools failed:', error?.message ?? error);
557
690
  }
558
691
  let disposeTool = () => {};
@@ -572,6 +705,7 @@ export function apply(ctx) {
572
705
  })
573
706
  : () => {};
574
707
  } catch (error) {
708
+ diag.append({ ev: 'team.tool.fail', message: error?.message ?? String(error) });
575
709
  console.warn('[ai-team] team tool registration failed:', error?.message ?? error);
576
710
  }
577
711
 
@@ -591,7 +725,7 @@ export function apply(ctx) {
591
725
  }).then(async (value) => {
592
726
  if (value.created === true && existingHost === undefined) {
593
727
  for (const runtime of booted?.runtimes?.values() ?? []) {
594
- await runtime.service.bindHostSession(value.sessionId);
728
+ await runtime.service.bindHostSession(value.sessionId, runtime.id);
595
729
  }
596
730
  }
597
731
  host = value;
@@ -608,15 +742,51 @@ export function apply(ctx) {
608
742
  if (member === undefined) return { error: { code: 'E_NOT_FOUND', message: 'member not found' }, status: 404 };
609
743
  if (member.status === 'retired') return { error: { code: 'E_INVALID_STATE', message: 'member is retired' }, status: 409 };
610
744
  if (member.status === 'running' && body.payload?.force !== true) return { error: { code: 'E_INVALID_STATE', message: 'member is already running' }, status: 409 };
745
+ // 无目录项目 fail-closed:成员绝不落到宿主默认目录或插件数据目录
746
+ // (projectCwd 的 dir 兜底)里执行。显式判工作目录,不吃兜底。
747
+ // 先于 reseat 释放旧句柄——否则无目录的 force 会先杀句柄再 409。
748
+ const workspacePath = projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath;
749
+ const effectiveDir = member?.workspace || (typeof workspacePath === 'string' ? workspacePath.trim() : '');
750
+ if (effectiveDir === '') {
751
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_WORKSPACE_REQUIRED' });
752
+ return {
753
+ error: {
754
+ code: 'E_WORKSPACE_REQUIRED',
755
+ message: 'this Project has no workspace yet; set a workspace directory before activating members',
756
+ },
757
+ status: 409,
758
+ };
759
+ }
760
+ // 会话重建(reseat):成员已有会话且本次为 force 时,先释放旧会话的
761
+ // 运行时句柄(activation / resume handle),旧 DSH 会话本体由宿主持
762
+ // 久管理,插件不再持有或唤醒它;新会话落在当前项目工作目录。这是
763
+ // 修复历史"账本目录兜底 cwd"游离会话的唯一路径(会话 cwd 创建时
764
+ // 钉死,resume 不覆盖,DSH 不提供原地改 cwd 的 API)。
765
+ if (typeof member.sessionId === 'string' && member.sessionId !== '' && body.payload?.force === true) {
766
+ const staleId = member.sessionId;
767
+ const staleActivation = activations.get(staleId);
768
+ if (staleActivation !== undefined) {
769
+ activations.delete(staleId);
770
+ try { await staleActivation.dispose?.(); } catch { /* already gone */ }
771
+ }
772
+ const staleHandle = resumedHandles.get(staleId);
773
+ if (staleHandle !== undefined) {
774
+ resumedHandles.delete(staleId);
775
+ try { await staleHandle.dispose?.(); } catch { /* already gone */ }
776
+ }
777
+ diag?.append({ ev: 'member.reseat', memberId: member.id, oldSessionId: staleId, projectId: projectRuntime.id });
778
+ }
611
779
  const subagents = ctx.get('subagents');
612
780
  const sessions = ctx.get('sessions');
613
781
  const permissionPresets = ctx.get('permissionPresets');
614
782
  const sandboxPolicy = ctx.get('sandboxPolicy');
615
783
  if (subagents === undefined || sessions === undefined || permissionPresets === undefined || sandboxPolicy === undefined) {
784
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE' });
616
785
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'member runtime services are unavailable' }, status: 503 };
617
786
  }
618
787
  const providers = typeof subagents.list === 'function' ? subagents.list() : [];
619
788
  if (providers.length === 0) {
789
+ diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_RUNTIME_UNAVAILABLE', detail: 'no provider' });
620
790
  return { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'no subagent provider is registered' }, status: 503 };
621
791
  }
622
792
  try {
@@ -646,12 +816,13 @@ export function apply(ctx) {
646
816
  parent: parentInfo.agent,
647
817
  provider: providers[0],
648
818
  preset: 'standard',
649
- cwd: projectCwd(projectRuntime, member),
819
+ cwd: effectiveDir,
820
+ trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
650
821
  });
651
822
  const result = await runtime.activate(activationMember, {
652
823
  prompt: `${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
653
824
  ? body.payload.prompt
654
- : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: projectCwd(projectRuntime, activationMember) })}${await loadSkillContext(activationMember, projectRuntime.dir)}`,
825
+ : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, projectRuntime.dir)}`,
655
826
  });
656
827
  let bound;
657
828
  try {
@@ -696,6 +867,7 @@ export function apply(ctx) {
696
867
  broadcast(event, runtime);
697
868
  const actorId = event?.actor?.kind === 'agent' ? event.actor.memberId : undefined;
698
869
  void wakeFromResult(runtime, { event }, actorId === undefined ? {} : { agentId: actorId }).catch((error) => {
870
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: event?.type ?? null, message: error?.message ?? String(error) });
699
871
  console.warn('[ai-team] event wake planner failed:', error?.message ?? error);
700
872
  });
701
873
  };
@@ -724,12 +896,13 @@ export function apply(ctx) {
724
896
  // once per Project, without timers or periodic polling.
725
897
  for (const runtime of value.runtimes.values()) {
726
898
  void wakeFromResult(runtime, { event: { type: 'team/startup' } }, {}).catch((error) => {
899
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: 'team/startup', message: error?.message ?? String(error) });
727
900
  console.warn('[ai-team] startup wake planner failed:', error?.message ?? error);
728
901
  });
729
902
  }
730
903
  }
731
904
  }).catch(() => {});
732
- const broadcast = (event, runtime = currentRuntime()) => {
905
+ const broadcastNow = (event, runtime = currentRuntime()) => {
733
906
  if (runtime === null || runtime === undefined) return;
734
907
  const payload = {
735
908
  ...snapshot(runtime),
@@ -751,6 +924,25 @@ export function apply(ctx) {
751
924
  }
752
925
  }
753
926
  };
927
+ // 合帧:一条 wake 链会连发 2-4 条账本事件,每条都全量重算 board+quadrants
928
+ // 并整帧广播是平方级放大。按 Project 250ms 窗口合并为一次快照帧;
929
+ // 帧内 event 取窗口最后一条(客户端 toast 仍有通知,rev 守卫保证幂等)。
930
+ const pendingFrames = new Map();
931
+ const broadcast = (event, runtime = currentRuntime()) => {
932
+ if (runtime === null || runtime === undefined) return;
933
+ const queued = pendingFrames.get(runtime.id);
934
+ if (queued !== undefined) {
935
+ queued.lastEvent = event ?? queued.lastEvent;
936
+ return;
937
+ }
938
+ const entry = { runtime, lastEvent: event ?? null };
939
+ pendingFrames.set(runtime.id, entry);
940
+ entry.timer = setTimeout(() => {
941
+ pendingFrames.delete(runtime.id);
942
+ broadcastNow(entry.lastEvent ?? undefined, entry.runtime);
943
+ }, 250);
944
+ entry.timer.unref?.();
945
+ };
754
946
 
755
947
  async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '') {
756
948
  await ready;
@@ -763,6 +955,7 @@ export function apply(ctx) {
763
955
  projectName,
764
956
  projectGoal,
765
957
  workspacePath,
958
+ diag,
766
959
  });
767
960
  booted.runtimes.set(nextProjectId, next);
768
961
  attachRuntime(next);
@@ -793,6 +986,11 @@ export function apply(ctx) {
793
986
  }
794
987
 
795
988
  if (req.method === 'GET' && url.pathname === '/ai-team/api/skills-debug') {
989
+ // Developer diagnostic; gated like the test.* hooks so production
990
+ // does not expose the installed skill inventory.
991
+ if (process.env.DSH_AI_TEAM_TEST !== '1') {
992
+ return send(res, { error: { code: 'E_FORBIDDEN', message: 'debug endpoint is disabled' } }, 403);
993
+ }
796
994
  const variants = {};
797
995
  for (const [label, options] of [
798
996
  ['none', {}],
@@ -814,18 +1012,112 @@ export function apply(ctx) {
814
1012
  const catalog = await buildModelCatalog(ctx.get('llm'), ctx.get('agentDefaultModel'));
815
1013
  return send(res, catalog);
816
1014
  }
817
- if (req.method === 'GET' && url.pathname === '/ai-team/api/health') {
818
- const head = booted.ledger.head;
1015
+ // R-17 person 别名:视图层绑定(name → personId),文件存策略数据
1016
+ // 目录;聚合时别名生效,未绑定回落同名聚合(可回退路径)。
1017
+ const aliasesPath = join(booted.dataDir, 'people-aliases.json');
1018
+ const readAliases = () => {
1019
+ try {
1020
+ const parsed = JSON.parse(readFileSync(aliasesPath, 'utf8'));
1021
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
1022
+ } catch {
1023
+ return null;
1024
+ }
1025
+ };
1026
+ // 人员池:按"人"聚合各项目账本的成员身份/状态/失败/任务数
1027
+ //(11-管理视角与信息架构 §2;只读,复用既有投影,不建新数据)。
1028
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/people') {
1029
+ const registryEntries = booted.registry.list();
1030
+ const people = aggregatePeople(registryEntries, [...booted.runtimes.values()], { aliases: readAliases() });
1031
+ return send(res, { ok: true, people });
1032
+ }
1033
+ // R-17 绑定:把一个名字并到某个 personId(Human 在人员池显式确认)。
1034
+ if (req.method === 'POST' && url.pathname === '/ai-team/api/people-aliases') {
1035
+ const body = await readJson(req);
1036
+ const memberName = typeof body?.name === 'string' ? body.name.trim() : '';
1037
+ const personId = typeof body?.personId === 'string' ? body.personId.trim() : '';
1038
+ if (memberName === '' || personId === '') {
1039
+ return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'name and personId are required' } }, 400);
1040
+ }
1041
+ const aliases = readAliases() ?? {};
1042
+ aliases[memberName] = personId;
1043
+ writeFileSync(aliasesPath, JSON.stringify(aliases, null, 2) + '\n', 'utf8');
1044
+ diag?.append({ ev: 'people.alias', name: memberName, personId });
1045
+ return send(res, { ok: true, aliases });
1046
+ }
1047
+ // 待验收跨项目队列(R-09):各项目 q1 中需要 Human 验收的任务
1048
+ //(review/irreversible 类目,复用 quadrantsView 既有投影)。
1049
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/pending-acceptance') {
1050
+ const registryEntries = booted.registry.list();
1051
+ const rows = [];
1052
+ for (const runtime of booted.runtimes.values()) {
1053
+ const projectName = registryEntries.find((project) => project.id === runtime.id)?.name ?? runtime.id;
1054
+ const q1 = runtime.service.quadrants(runtime.id).q1;
1055
+ for (const item of q1.items ?? []) {
1056
+ if (item.kind !== 'task' || (item.category !== 'review' && item.category !== 'irreversible')) continue;
1057
+ rows.push({ ...item, projectId: runtime.id, projectName });
1058
+ }
1059
+ }
1060
+ return send(res, { ok: true, rows });
1061
+ }
1062
+ // 风险清单(R-07):当前项目账本的三类风险只读投影(受阻/失败/待决超时)。
1063
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/risks') {
1064
+ const requested = url.searchParams.get('project');
1065
+ const runtime = (requested === null ? null : projectRuntime(requested)) ?? currentRuntime();
1066
+ if (runtime === null || runtime === undefined) {
1067
+ return send(res, { ok: true, risks: { rev: 0, generatedAt: Date.now(), blocked: [], failures: [], staleDecisions: [], counts: { blocked: 0, failures: 0, staleDecisions: 0 } } });
1068
+ }
1069
+ const staleHours = Number.parseFloat(url.searchParams.get('staleHours') ?? '');
1070
+ const risks = riskView(runtime.service.state, {
1071
+ now: Date.now(),
1072
+ staleHours: Number.isFinite(staleHours) && staleHours > 0 ? staleHours : 24,
1073
+ });
1074
+ return send(res, { ok: true, projectId: runtime.id, risks });
1075
+ }
1076
+ // 项目周报(R-11):同一投影的正向/负向双解读数据面。
1077
+ const weekly = url.pathname.match(/^\/ai-team\/api\/projects\/([^/]+)\/weekly$/);
1078
+ if (req.method === 'GET' && weekly !== null) {
1079
+ const runtime = projectRuntime(decodeURIComponent(weekly[1]));
1080
+ if (runtime === null) return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
1081
+ const weeks = Number.parseInt(url.searchParams.get('weeks') ?? '', 10);
1082
+ return send(res, {
1083
+ ok: true,
1084
+ projectId: runtime.id,
1085
+ weekly: weeklyView(runtime.service.state, {
1086
+ now: Date.now(),
1087
+ weeks: Number.isSafeInteger(weeks) && weeks > 0 ? Math.min(weeks, 12) : 1,
1088
+ }),
1089
+ });
1090
+ }
1091
+ // 任务事件历史(R-18):Human 侧可追溯入口的只读数据面。
1092
+ const taskEvents = url.pathname.match(/^\/ai-team\/api\/projects\/([^/]+)\/tasks\/([^/]+)\/events$/);
1093
+ if (req.method === 'GET' && taskEvents !== null) {
1094
+ const runtime = projectRuntime(decodeURIComponent(taskEvents[1]));
1095
+ const taskId = decodeURIComponent(taskEvents[2]);
1096
+ if (runtime === null || runtime === undefined) return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
1097
+ const events = runtime.ledger.events.filter((event) => {
1098
+ const pid = event.payload?.taskId ?? event.payload?.id ?? null;
1099
+ return typeof pid === 'string' && pid === taskId;
1100
+ });
1101
+ return send(res, {
1102
+ ok: true,
1103
+ taskId,
1104
+ events: events.map((event) => ({
1105
+ seq: event.seq, type: event.type, at: event.at,
1106
+ actor: event.actor ?? null,
1107
+ })),
1108
+ });
1109
+ }
1110
+ if (req.method === 'GET' && url.pathname === '/ai-team/api/health') { const head = booted.ledger.head;
819
1111
  return send(res, {
820
1112
  ok: true,
821
1113
  plugin: name,
822
1114
  version: VERSION,
823
1115
  projectId: booted.activeProjectId,
824
1116
  activeProjectId: booted.activeProjectId,
825
- ledger: { events: booted.ledger.events.length, head },
1117
+ ledger: { events: booted.ledger.headSeq, head },
826
1118
  projects: [...booted.runtimes.values()].map((runtime) => ({
827
1119
  id: runtime.id,
828
- events: runtime.ledger.events.length,
1120
+ events: runtime.ledger.headSeq,
829
1121
  head: runtime.ledger.head.seq,
830
1122
  active: runtime.id === booted.activeProjectId,
831
1123
  })),
@@ -887,11 +1179,22 @@ export function apply(ctx) {
887
1179
  const requestedRuntime = requested === null ? null : projectRuntime(requested);
888
1180
  const bootstrapRuntime = requestedRuntime ?? currentRuntime();
889
1181
  const bootstrap = bootstrapRuntime.service.bootstrap(bootstrapRuntime.id);
1182
+ // 跨项目收件箱聚合:其它项目只读 state.inbox 过滤(此前对每个
1183
+ // 项目整调 bootstrap——board+quadrants+threads 全算,O(项目数×
1184
+ // 全视图)/请求)。
890
1185
  const inbox = [];
891
1186
  for (const runtime of booted.runtimes.values()) {
892
1187
  const projectName = booted.registry.list().find((project) => project.id === runtime.id)?.name ?? runtime.id;
893
- const view = runtime.id === bootstrapRuntime.id ? bootstrap : runtime.service.bootstrap(runtime.id);
894
- for (const item of view.inbox ?? []) {
1188
+ if (runtime.id === bootstrapRuntime.id) {
1189
+ for (const item of bootstrap.inbox ?? []) {
1190
+ inbox.push({ ...item, projectId: runtime.id, projectName });
1191
+ }
1192
+ continue;
1193
+ }
1194
+ const humanId = runtime.service.humanId();
1195
+ for (const item of Object.values(runtime.service.state.inbox ?? {})) {
1196
+ if (humanId === null || item.memberId !== humanId) continue;
1197
+ if (isInformationalThreadMention(item)) continue;
895
1198
  inbox.push({ ...item, projectId: runtime.id, projectName });
896
1199
  }
897
1200
  }
@@ -1049,7 +1352,8 @@ export function apply(ctx) {
1049
1352
  const goal = typeof body.payload?.goal === 'string' ? body.payload.goal.trim() : '';
1050
1353
  const workspacePath = typeof body.payload?.workspacePath === 'string' ? body.payload.workspacePath.trim() : '';
1051
1354
  if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
1052
- if (workspacePath === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project workspacePath is required' } }, 400);
1355
+ // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
1356
+ // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
1053
1357
  const id = ids.project();
1054
1358
  booted.registry.add({ id, name, goal, workspacePath });
1055
1359
  const next = await activateProject(id, name, goal, workspacePath);
@@ -1080,6 +1384,7 @@ export function apply(ctx) {
1080
1384
  });
1081
1385
  send(res, { ok: true, ...result });
1082
1386
  void wakeFromResult(runtime, result, { agentId: HUMAN_ID }).catch((error) => {
1387
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: result?.event?.type ?? null, message: error?.message ?? String(error) });
1083
1388
  console.warn('[ai-team] wake planner failed:', error?.message ?? error);
1084
1389
  });
1085
1390
  return;
@@ -1104,6 +1409,10 @@ export function apply(ctx) {
1104
1409
  try { client.res.end(); } catch { /* socket already gone */ }
1105
1410
  }
1106
1411
  sseClients.clear();
1412
+ for (const entry of pendingFrames.values()) {
1413
+ try { clearTimeout(entry.timer); } catch { /* already fired */ }
1414
+ }
1415
+ pendingFrames.clear();
1107
1416
  if (pmoTimer !== null) { clearInterval(pmoTimer); pmoTimer = null; }
1108
1417
  for (const activation of activations.values()) {
1109
1418
  cleanup.push(Promise.resolve().then(async () => {
@@ -1111,6 +1420,12 @@ export function apply(ctx) {
1111
1420
  }));
1112
1421
  }
1113
1422
  activations.clear();
1423
+ for (const handle of resumedHandles.values()) {
1424
+ cleanup.push(Promise.resolve().then(async () => {
1425
+ try { await handle?.dispose?.(); } catch { /* already gone */ }
1426
+ }));
1427
+ }
1428
+ resumedHandles.clear();
1114
1429
  if (host !== null) cleanup.push(Promise.resolve().then(async () => {
1115
1430
  try { await host.dispose?.(); } catch { /* already gone */ }
1116
1431
  }));