@suifei/dsh-ai-team 0.3.53 → 0.3.56

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,7 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
+ import z from '@deepseek-ai/schemastery';
14
15
  import { ProjectRuntime } from './lib/host/project-runtime.js';
15
16
  import { ProjectRegistry } from './lib/host/project-registry.js';
16
17
  import { ids } from './lib/domain/ids.js';
@@ -28,16 +29,39 @@ import { installFaultAdapter } from './lib/host/fault-adapter.js';
28
29
  import { buildModelCatalog } from './lib/host/model-catalog.js';
29
30
  import { createTeamTool } from './lib/host/member-tools.js';
30
31
  import { describeWake, planWakes } from './lib/host/waker.js';
32
+ import { createDiagLogger, defaultDiagDir } from './lib/diaglog.js';
31
33
 
32
34
  export const name = 'ai-team';
33
35
 
34
36
  /** The workbench only makes sense where the Web carrier exists. */
35
37
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy'];
36
38
 
37
- const VERSION = '0.3.53';
39
+ const VERSION = '0.3.56';
38
40
  const PROJECT_ID = 'prj_main';
39
41
  const HUMAN_ID = 'mem_human';
40
42
 
43
+ const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
44
+
45
+ /**
46
+ * Tunable values live in the plugin Config so users edit their patch layer
47
+ * (the user's patch survives upgrades). Integer fields use `.step(1)`: the
48
+ * bundled schemastery zod face has no `.int()`.
49
+ */
50
+ export const Config = z.object({
51
+ // diaglog level: 'off' silent, 'errors' crash/fail rows only, 'full' all rows
52
+ diagLevel: z.union(['off', 'errors', 'full']).default('errors'),
53
+ // directory of the diagnostic JSONL log (one file per day)
54
+ diagLogDir: z.string().default(defaultDiagDir()),
55
+ // rotation cap for one diagnostic log file
56
+ diagLogMaxBytes: z.number().step(1).min(65536).max(16777216).default(1048576),
57
+ // default SkillOpt backend for skillopt_* tools; 'mock' is the safe shipped
58
+ // default (no model calls, no live-file writes) — a real backend must be
59
+ // configured here or passed per call.
60
+ skilloptBackend: z.union(SKILLOPT_BACKENDS).default('mock'),
61
+ // per-call timeout for skillopt_* engine runs
62
+ skilloptTimeoutMs: z.number().step(1).min(10_000).max(600_000).default(120_000),
63
+ });
64
+
41
65
  function send(res, body, status = 200) {
42
66
  if (res.writableEnded) return;
43
67
  res.statusCode = status;
@@ -82,7 +106,7 @@ function errorResponse(res, error) {
82
106
  * A torn tail is repaired by the writer; the repair is recorded as a system
83
107
  * event so the append-only history explains the gap.
84
108
  */
85
- async function boot() {
109
+ async function boot(diag) {
86
110
  const dataDir = join(dshHome(), 'ai-team', profileName());
87
111
  const registry = ProjectRegistry.load(dataDir);
88
112
  const runtimes = new Map();
@@ -93,11 +117,19 @@ async function boot() {
93
117
  projectName: project.name,
94
118
  projectGoal: project.goal,
95
119
  workspacePath: project.workspacePath ?? '',
120
+ diag,
96
121
  });
97
122
  runtimes.set(project.id, runtime);
98
123
  }
99
124
  const activeProjectId = registry.activeProjectId;
100
125
  const runtime = runtimes.get(activeProjectId) ?? runtimes.values().next().value;
126
+ diag?.append({
127
+ ev: 'boot.done',
128
+ dataDir,
129
+ projects: [...runtimes.keys()],
130
+ activeProjectId,
131
+ events: [...runtimes.values()].reduce((sum, item) => sum + item.ledger.headSeq, 0),
132
+ });
101
133
  return {
102
134
  ...runtime,
103
135
  runtime,
@@ -110,7 +142,15 @@ async function boot() {
110
142
  };
111
143
  }
112
144
 
113
- export function apply(ctx) {
145
+ export function apply(ctx, config = {}) {
146
+ // Diagnostic log first: every later row (boot, wake, PMO, dispatch) lands
147
+ // here with the configured level ('off'/'errors'/'full', errors shipped).
148
+ // The `??` chain keeps direct apply() calls (tests) on shipped defaults.
149
+ const diag = createDiagLogger({
150
+ dir: config.diagLogDir ?? defaultDiagDir(),
151
+ maxBytes: config.diagLogMaxBytes ?? 1048576,
152
+ level: config.diagLevel ?? 'errors',
153
+ });
114
154
  ctx.effect(() => {
115
155
  const webServer = ctx.get('webServer');
116
156
  if (webServer === undefined) return () => {};
@@ -137,6 +177,7 @@ export function apply(ctx) {
137
177
  const created = await registry.create?.(path, projectRuntime.service.state.projects[projectRuntime.id]?.name ?? '文渊阁');
138
178
  return created ?? null;
139
179
  } catch (error) {
180
+ diag.append({ ev: 'workspace.fail', projectId: projectRuntime.id, path, message: error?.message ?? String(error) });
140
181
  console.warn('[ai-team] workspace unavailable:', error?.message ?? error);
141
182
  return null;
142
183
  }
@@ -152,7 +193,9 @@ export function apply(ctx) {
152
193
  try {
153
194
  if (typeof titleService.get === 'function' && titleService.get(session)?.title === title) return;
154
195
  titleService.rename(session, title);
196
+ diag.append({ ev: 'session.title', sessionId: member.sessionId, title, projectId: projectRuntime.id });
155
197
  } catch (error) {
198
+ diag.append({ ev: 'session.title.fail', sessionId: member.sessionId, message: error?.message ?? String(error) });
156
199
  console.warn('[ai-team] session title failed:', error?.message ?? error);
157
200
  }
158
201
  };
@@ -163,6 +206,7 @@ export function apply(ctx) {
163
206
  try {
164
207
  await workspace.attachSession(sessionId);
165
208
  } catch (error) {
209
+ diag.append({ ev: 'workspace.attach.fail', sessionId, message: error?.message ?? String(error) });
166
210
  console.warn('[ai-team] member session workspace attach failed:', error?.message ?? error);
167
211
  }
168
212
  };
@@ -180,7 +224,9 @@ export function apply(ctx) {
180
224
  if (session === undefined || session === null || typeof session.append !== 'function') return;
181
225
  session.append('model/selection', { provider: selection.provider, model: selection.model });
182
226
  modelSelectionLogged.set(sessionId, route);
227
+ diag.append({ ev: 'model.selection', sessionId, route, label: label ?? null });
183
228
  } catch (error) {
229
+ diag.append({ ev: 'model.selection.fail', sessionId, label: label ?? null, message: error?.message ?? String(error) });
184
230
  console.warn('[ai-team] model selection persist failed:', label ?? sessionId, error?.message ?? error);
185
231
  }
186
232
  };
@@ -189,7 +235,7 @@ export function apply(ctx) {
189
235
  sandboxPolicy: ctx.get('sandboxPolicy'),
190
236
  });
191
237
  const ready = access.ok
192
- ? Promise.resolve().then(boot)
238
+ ? Promise.resolve().then(() => boot(diag))
193
239
  .then(async (value) => {
194
240
  booted = value;
195
241
  for (const runtime of value.runtimes.values()) {
@@ -200,12 +246,21 @@ export function apply(ctx) {
200
246
  persistModelSelection(member.sessionId, member.config, member.name);
201
247
  }
202
248
  }
203
- void pmoTick(runtime).catch((error) => console.warn('[ai-team] PMO tick failed:', error?.message ?? error));
249
+ // Attach the broadcast/wake hook before the first tick: events
250
+ // produced by the tick must reach SSE clients immediately.
251
+ attachRuntime(runtime);
252
+ void pmoTick(runtime).catch((error) => {
253
+ diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
254
+ console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
255
+ });
204
256
  }
205
257
  if (pmoTimer === null) {
206
258
  pmoTimer = setInterval(() => {
207
259
  for (const runtime of booted?.runtimes?.values() ?? []) {
208
- void pmoTick(runtime).catch((error) => console.warn('[ai-team] PMO tick failed:', error?.message ?? error));
260
+ void pmoTick(runtime).catch((error) => {
261
+ diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
262
+ console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
263
+ });
209
264
  }
210
265
  }, 60_000);
211
266
  pmoTimer.unref?.();
@@ -214,20 +269,26 @@ export function apply(ctx) {
214
269
  })
215
270
  .catch((error) => {
216
271
  bootError = error;
272
+ diag.append({ ev: 'boot.fail', message: error?.message ?? String(error) });
217
273
  console.error('[ai-team] ledger boot failed:', error?.message ?? error);
218
274
  return null;
219
275
  })
220
276
  : Promise.resolve(null);
221
277
  if (!access.ok) {
222
278
  bootError = Object.assign(new Error(access.reason), { code: access.code, status: 503 });
279
+ diag.append({ ev: 'boot.refused', code: access.code, reason: access.reason });
223
280
  console.error('[ai-team] refused to start:', access.code, access.reason);
224
281
  }
225
282
 
226
283
  const sseClients = new Set();
227
284
  const activations = new Map();
228
285
  // 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.
286
+ // record it, and own the immediate retry only for transient server/network
287
+ // failures ({ kind: 'retry' } re-dispatches the same request). A fallback
288
+ // patch rewrites the persisted config, which a live step cannot pick up —
289
+ // so the turn ends there and the next wake runs on the new route. Rate
290
+ // limits end the turn too: no backoff clock means an immediate retry just
291
+ // burns the budget against a throttled route.
231
292
  const offRequestError = typeof ctx.on === 'function'
232
293
  ? ctx.on('agent/request-error', async (payload, next) => {
233
294
  if (booted === null) return next();
@@ -242,18 +303,21 @@ export function apply(ctx) {
242
303
  ...failure,
243
304
  provider: payload.provider ?? null,
244
305
  model: member.config?.model ?? null,
245
- });
246
- } catch {
306
+ }, failureRuntime.id);
307
+ } catch (error) {
308
+ console.warn('[ai-team] member failure record failed:', member.id, error?.message ?? error);
247
309
  return next();
248
310
  }
249
311
  if (!failure.retryable) return next();
250
312
  const decision = retryDecision(failure, member.config ?? {}, recorded.member.attempts ?? 1);
251
313
  if (decision.action === 'fallback' && decision.patch !== undefined) {
252
314
  try {
253
- await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback');
254
- } catch { /* policy/rollback failure must not turn into a retry storm */ }
315
+ await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback', failureRuntime.id);
316
+ } catch (error) {
317
+ console.warn('[ai-team] member fallback failed:', member.id, error?.message ?? error);
318
+ }
255
319
  }
256
- if (decision.action === 'fail') return next();
320
+ if (decision.action !== 'retry') return next();
257
321
  return { kind: 'retry' };
258
322
  })
259
323
  : () => {};
@@ -271,14 +335,17 @@ export function apply(ctx) {
271
335
  try {
272
336
  await sessions?.flush?.(session);
273
337
  } catch (error) {
338
+ diag.append({ ev: 'session.flush.fail', sessionId: session?.id ?? null, message: error?.message ?? String(error) });
274
339
  console.warn('[ai-team] member session flush failed:', error?.message ?? error);
275
340
  }
276
341
  if (event?.data?.reason?.kind !== 'completed') return;
277
342
  if (member.lastFailure === undefined || member.lastFailure === null) return;
278
343
  try {
279
- await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null);
344
+ await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null, eventRuntime.id);
280
345
  broadcast(undefined, eventRuntime);
281
- } catch { /* recovery is best-effort; the ledger still has the failure */ }
346
+ } catch (error) {
347
+ console.warn('[ai-team] member recovery record failed:', member.id, error?.message ?? error);
348
+ }
282
349
  })
283
350
  : () => {};
284
351
  let llmFaultMode = null;
@@ -287,13 +354,16 @@ export function apply(ctx) {
287
354
  : () => {};
288
355
  let host = null;
289
356
  let hostPromise = null;
290
- const wakeKeys = new Set();
357
+ const wakeKeys = new Map();
291
358
  const activationTasks = new Map();
292
359
  const pmoLastKick = new Map();
293
360
  const pmoLastStall = new Map();
294
361
  const pmoLastHeartbeat = new Map();
295
362
  const pmoLastEscalate = new Map();
296
363
  const pmoLastReview = new Map();
364
+ // Members resumed from cold sessions produce AgentHandles nobody stored;
365
+ // track them so teardown can dispose every owned activation.
366
+ const resumedHandles = new Set();
297
367
  let pmoTimer = null;
298
368
  const projectCwd = (projectRuntime, member) => member?.workspace
299
369
  || projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath
@@ -303,6 +373,12 @@ export function apply(ctx) {
303
373
  if (projectRuntime === null || projectRuntime === undefined) return;
304
374
  const plans = planWakes(projectRuntime.service.state, result, actor);
305
375
  if (plans.length === 0) return;
376
+ // Window eviction: a key older than this horizon can no longer dedupe
377
+ // a relevant event, so drop it instead of growing the Map forever.
378
+ const head = projectRuntime?.ledger?.head?.seq ?? 0;
379
+ for (const [key, seq] of wakeKeys) {
380
+ if (Number.isSafeInteger(seq) && head - seq > 500) wakeKeys.delete(key);
381
+ }
306
382
  const subagents = ctx.get('subagents');
307
383
  const sessions = ctx.get('sessions');
308
384
  const permissionPresets = ctx.get('permissionPresets');
@@ -321,7 +397,7 @@ export function apply(ctx) {
321
397
  if (member === undefined) continue;
322
398
  // Reserve before the async delivery: the HTTP result and the ledger
323
399
  // event both schedule the same plan, and only one may deliver it.
324
- wakeKeys.add(plan.key);
400
+ wakeKeys.set(plan.key, result?.event?.seq ?? head);
325
401
  const cwd = projectCwd(projectRuntime, member);
326
402
  try {
327
403
  // Idle default members have no Agent session yet. A wake must
@@ -356,6 +432,7 @@ export function apply(ctx) {
356
432
  provider: providers[0],
357
433
  preset: 'standard',
358
434
  cwd,
435
+ trackHandle: (handle) => resumedHandles.add(handle),
359
436
  });
360
437
  const delivered = await runtime.wake(member, { prompt: await wakePrompt(plan, member) });
361
438
  messageId = delivered.messageId ?? null;
@@ -365,14 +442,32 @@ export function apply(ctx) {
365
442
  }
366
443
  await projectRuntime.service.recordWake(plan.memberId, {
367
444
  ok: true, taskId: plan.taskId, reason: plan.reason, messageId,
445
+ }, projectRuntime.id);
446
+ diag.append({
447
+ ev: 'wake.delivered',
448
+ projectId: projectRuntime.id,
449
+ memberId: plan.memberId,
450
+ taskId: plan.taskId ?? null,
451
+ reason: plan.reason,
452
+ activated: member.sessionId === undefined || messageId === null ? 'activation' : 'wake',
453
+ messageId,
368
454
  });
369
455
  } catch (error) {
370
456
  wakeKeys.delete(plan.key);
457
+ diag.append({
458
+ ev: 'wake.fail',
459
+ projectId: projectRuntime.id,
460
+ memberId: plan.memberId,
461
+ taskId: plan.taskId ?? null,
462
+ reason: plan.reason,
463
+ code: error?.code ?? null,
464
+ message: error?.message ?? String(error),
465
+ });
371
466
  console.warn('[ai-team] wake failed:', plan.memberId, error?.code ?? error?.message ?? error);
372
467
  try {
373
468
  await projectRuntime.service.recordWake(plan.memberId, {
374
469
  ok: false, taskId: plan.taskId, reason: plan.reason, error: error?.code ?? error?.message ?? String(error),
375
- });
470
+ }, projectRuntime.id);
376
471
  } catch { /* ledger may be closed */ }
377
472
  }
378
473
  }
@@ -387,7 +482,7 @@ export function apply(ctx) {
387
482
  await titleMemberSession(projectRuntime, member);
388
483
  }
389
484
  }
390
- const results = await projectRuntime.service.autoAnswerDecisions();
485
+ const results = await projectRuntime.service.autoAnswerDecisions(projectRuntime.id);
391
486
  for (const result of results) {
392
487
  const taskId = result?.item?.ref?.taskId;
393
488
  if (typeof taskId === 'string' && result.entry !== null && result.entry !== undefined) {
@@ -449,7 +544,17 @@ export function apply(ctx) {
449
544
  event: { type: 'pmo/stall', payload: { taskId: task.id, bucket: Math.floor(now / 1_800_000) } },
450
545
  }, {});
451
546
  }
452
- if (active.length > 0) return;
547
+ if (active.length > 0) {
548
+ // Prune per-task clock entries whose task left the active set, so
549
+ // the five Map keys track live work instead of growing forever.
550
+ const live = new Set(active.map((task) => task.id));
551
+ for (const map of [pmoLastReview, pmoLastHeartbeat, pmoLastEscalate, pmoLastStall]) {
552
+ for (const taskId of map.keys()) {
553
+ if (!live.has(taskId)) map.delete(taskId);
554
+ }
555
+ }
556
+ return;
557
+ }
453
558
  const last = pmoLastKick.get(projectRuntime.id) ?? 0;
454
559
  if (now - last < 10 * 60_000) return;
455
560
  pmoLastKick.set(projectRuntime.id, now);
@@ -494,8 +599,12 @@ export function apply(ctx) {
494
599
  const stream = llm.stream({
495
600
  provider: selection.provider,
496
601
  model: selection.model,
497
- system: '你是团队的人格蒸馏器。只输出要求的 JSON,不调用工具。',
498
- messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
602
+ // GenerateOptions has no top-level `system` field; the distiller
603
+ // constraint travels as a system-role message.
604
+ messages: [
605
+ { role: 'system', content: [{ type: 'text', text: '你是团队的人格蒸馏器。只输出要求的 JSON,不调用工具。' }] },
606
+ { role: 'user', content: [{ type: 'text', text: prompt }] },
607
+ ],
499
608
  maxTokens: 400,
500
609
  });
501
610
  for await (const chunk of stream) {
@@ -535,6 +644,7 @@ export function apply(ctx) {
535
644
  bundledDir: fileURLToPath(new URL('./', import.meta.url)),
536
645
  }) ?? (() => {});
537
646
  } catch (error) {
647
+ diag.append({ ev: 'skill.provider.fail', message: error?.message ?? String(error) });
538
648
  console.warn('[ai-team] file skill provider failed:', error?.message ?? error);
539
649
  }
540
650
  const tools = ctx.get('tools');
@@ -542,17 +652,21 @@ export function apply(ctx) {
542
652
  try {
543
653
  const shell = ctx.get('shell');
544
654
  if (tools?.register && shell) {
655
+ // Backend/timeout come from the plugin Config (patch layer), so an
656
+ // operator can move the skillopt_* tools off the safe mock default.
545
657
  disposeSkillOpt = applySkillOpt({
546
658
  tools,
547
659
  shell,
548
660
  logger: console,
549
661
  }, {
550
- backend: 'mock',
662
+ backend: config.skilloptBackend ?? 'mock',
551
663
  project: process.cwd(),
552
- timeoutMs: 120_000,
664
+ timeoutMs: config.skilloptTimeoutMs ?? 120_000,
553
665
  }) ?? (() => {});
666
+ diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000 });
554
667
  }
555
668
  } catch (error) {
669
+ diag.append({ ev: 'skillopt.fail', message: error?.message ?? String(error) });
556
670
  console.warn('[ai-team] bundled SkillOpt tools failed:', error?.message ?? error);
557
671
  }
558
672
  let disposeTool = () => {};
@@ -572,6 +686,7 @@ export function apply(ctx) {
572
686
  })
573
687
  : () => {};
574
688
  } catch (error) {
689
+ diag.append({ ev: 'team.tool.fail', message: error?.message ?? String(error) });
575
690
  console.warn('[ai-team] team tool registration failed:', error?.message ?? error);
576
691
  }
577
692
 
@@ -591,7 +706,7 @@ export function apply(ctx) {
591
706
  }).then(async (value) => {
592
707
  if (value.created === true && existingHost === undefined) {
593
708
  for (const runtime of booted?.runtimes?.values() ?? []) {
594
- await runtime.service.bindHostSession(value.sessionId);
709
+ await runtime.service.bindHostSession(value.sessionId, runtime.id);
595
710
  }
596
711
  }
597
712
  host = value;
@@ -647,6 +762,7 @@ export function apply(ctx) {
647
762
  provider: providers[0],
648
763
  preset: 'standard',
649
764
  cwd: projectCwd(projectRuntime, member),
765
+ trackHandle: (handle) => resumedHandles.add(handle),
650
766
  });
651
767
  const result = await runtime.activate(activationMember, {
652
768
  prompt: `${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
@@ -696,6 +812,7 @@ export function apply(ctx) {
696
812
  broadcast(event, runtime);
697
813
  const actorId = event?.actor?.kind === 'agent' ? event.actor.memberId : undefined;
698
814
  void wakeFromResult(runtime, { event }, actorId === undefined ? {} : { agentId: actorId }).catch((error) => {
815
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: event?.type ?? null, message: error?.message ?? String(error) });
699
816
  console.warn('[ai-team] event wake planner failed:', error?.message ?? error);
700
817
  });
701
818
  };
@@ -724,12 +841,13 @@ export function apply(ctx) {
724
841
  // once per Project, without timers or periodic polling.
725
842
  for (const runtime of value.runtimes.values()) {
726
843
  void wakeFromResult(runtime, { event: { type: 'team/startup' } }, {}).catch((error) => {
844
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: 'team/startup', message: error?.message ?? String(error) });
727
845
  console.warn('[ai-team] startup wake planner failed:', error?.message ?? error);
728
846
  });
729
847
  }
730
848
  }
731
849
  }).catch(() => {});
732
- const broadcast = (event, runtime = currentRuntime()) => {
850
+ const broadcastNow = (event, runtime = currentRuntime()) => {
733
851
  if (runtime === null || runtime === undefined) return;
734
852
  const payload = {
735
853
  ...snapshot(runtime),
@@ -751,6 +869,25 @@ export function apply(ctx) {
751
869
  }
752
870
  }
753
871
  };
872
+ // 合帧:一条 wake 链会连发 2-4 条账本事件,每条都全量重算 board+quadrants
873
+ // 并整帧广播是平方级放大。按 Project 250ms 窗口合并为一次快照帧;
874
+ // 帧内 event 取窗口最后一条(客户端 toast 仍有通知,rev 守卫保证幂等)。
875
+ const pendingFrames = new Map();
876
+ const broadcast = (event, runtime = currentRuntime()) => {
877
+ if (runtime === null || runtime === undefined) return;
878
+ const queued = pendingFrames.get(runtime.id);
879
+ if (queued !== undefined) {
880
+ queued.lastEvent = event ?? queued.lastEvent;
881
+ return;
882
+ }
883
+ const entry = { runtime, lastEvent: event ?? null };
884
+ pendingFrames.set(runtime.id, entry);
885
+ entry.timer = setTimeout(() => {
886
+ pendingFrames.delete(runtime.id);
887
+ broadcastNow(entry.lastEvent ?? undefined, entry.runtime);
888
+ }, 250);
889
+ entry.timer.unref?.();
890
+ };
754
891
 
755
892
  async function activateProject(nextProjectId, projectName, projectGoal, workspacePath = '') {
756
893
  await ready;
@@ -793,6 +930,11 @@ export function apply(ctx) {
793
930
  }
794
931
 
795
932
  if (req.method === 'GET' && url.pathname === '/ai-team/api/skills-debug') {
933
+ // Developer diagnostic; gated like the test.* hooks so production
934
+ // does not expose the installed skill inventory.
935
+ if (process.env.DSH_AI_TEAM_TEST !== '1') {
936
+ return send(res, { error: { code: 'E_FORBIDDEN', message: 'debug endpoint is disabled' } }, 403);
937
+ }
796
938
  const variants = {};
797
939
  for (const [label, options] of [
798
940
  ['none', {}],
@@ -822,10 +964,10 @@ export function apply(ctx) {
822
964
  version: VERSION,
823
965
  projectId: booted.activeProjectId,
824
966
  activeProjectId: booted.activeProjectId,
825
- ledger: { events: booted.ledger.events.length, head },
967
+ ledger: { events: booted.ledger.headSeq, head },
826
968
  projects: [...booted.runtimes.values()].map((runtime) => ({
827
969
  id: runtime.id,
828
- events: runtime.ledger.events.length,
970
+ events: runtime.ledger.headSeq,
829
971
  head: runtime.ledger.head.seq,
830
972
  active: runtime.id === booted.activeProjectId,
831
973
  })),
@@ -1080,6 +1222,7 @@ export function apply(ctx) {
1080
1222
  });
1081
1223
  send(res, { ok: true, ...result });
1082
1224
  void wakeFromResult(runtime, result, { agentId: HUMAN_ID }).catch((error) => {
1225
+ diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: result?.event?.type ?? null, message: error?.message ?? String(error) });
1083
1226
  console.warn('[ai-team] wake planner failed:', error?.message ?? error);
1084
1227
  });
1085
1228
  return;
@@ -1104,6 +1247,10 @@ export function apply(ctx) {
1104
1247
  try { client.res.end(); } catch { /* socket already gone */ }
1105
1248
  }
1106
1249
  sseClients.clear();
1250
+ for (const entry of pendingFrames.values()) {
1251
+ try { clearTimeout(entry.timer); } catch { /* already fired */ }
1252
+ }
1253
+ pendingFrames.clear();
1107
1254
  if (pmoTimer !== null) { clearInterval(pmoTimer); pmoTimer = null; }
1108
1255
  for (const activation of activations.values()) {
1109
1256
  cleanup.push(Promise.resolve().then(async () => {
@@ -1111,6 +1258,12 @@ export function apply(ctx) {
1111
1258
  }));
1112
1259
  }
1113
1260
  activations.clear();
1261
+ for (const handle of resumedHandles) {
1262
+ cleanup.push(Promise.resolve().then(async () => {
1263
+ try { await handle?.dispose?.(); } catch { /* already gone */ }
1264
+ }));
1265
+ }
1266
+ resumedHandles.clear();
1114
1267
  if (host !== null) cleanup.push(Promise.resolve().then(async () => {
1115
1268
  try { await host.dispose?.(); } catch { /* already gone */ }
1116
1269
  }));
package/lib/diaglog.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Plugin-owned diagnostic log: one JSONL file per day, appended serially,
3
+ * rotated at a byte cap, and readable back through tail(). Both the Host
4
+ * (boot, dispatch, wake, PMO, member failure/recovery) and the Client half
5
+ * (via route rows) write into it, so "the panel shows no data" is answerable
6
+ * from evidence. Levels: 'off' silent, 'errors' crash/fail rows only
7
+ * (shipped default), 'full' everything (development).
8
+ */
9
+ import { appendFile, mkdir, readFile, rename, stat } from 'node:fs/promises';
10
+ import { homedir } from 'node:os';
11
+ import { join } from 'node:path';
12
+
13
+ /** The date-stamped file name carries the project id and the day (naming rule). */
14
+ export function diagFileName(date = new Date()) {
15
+ return `aiteam-diag-${date.toISOString().slice(0, 10)}.jsonl`;
16
+ }
17
+
18
+ export function defaultDiagDir() {
19
+ return join(homedir(), '.dsh', 'ai-team');
20
+ }
21
+
22
+ /** Rows worth keeping when the logger runs in `errors` mode. */
23
+ export function isErrorEvent(ev) {
24
+ return typeof ev === 'string'
25
+ && (ev.endsWith('.fail') || ev === 'boot.refused' || ev === 'route.reject' || ev === 'ledger.repair');
26
+ }
27
+
28
+ /**
29
+ * @param options - { dir, maxBytes, now, enabled, level } seams for tests.
30
+ * `level`: 'off' drops every row (published default footprint), 'errors' keeps
31
+ * only crash/fail rows, 'full' writes everything (development).
32
+ */
33
+ export function createDiagLogger(options = {}) {
34
+ const dir = options.dir ?? defaultDiagDir();
35
+ const maxBytes = options.maxBytes ?? 1048576;
36
+ const enabled = options.enabled !== false;
37
+ const level = ['off', 'errors', 'full'].includes(options.level) ? options.level : 'errors';
38
+ const now = options.now ?? (() => new Date());
39
+ let queue = Promise.resolve();
40
+ let dirReady = null;
41
+ /** @type {number} */
42
+ let appended = 0;
43
+
44
+ const ensureDir = () => {
45
+ if (dirReady === null) dirReady = mkdir(dir, { recursive: true });
46
+ return dirReady;
47
+ };
48
+
49
+ const path = () => join(dir, diagFileName(now()));
50
+
51
+ function append(row) {
52
+ if (!enabled || level === 'off' || (level === 'errors' && !isErrorEvent(row.ev))) return queue;
53
+ const line = `${JSON.stringify({ t: now().toISOString(), ...row })}\n`;
54
+ queue = queue.then(async () => {
55
+ await ensureDir();
56
+ appended++;
57
+ if (appended % 20 === 1) {
58
+ // Cheap periodic rotation: stat at most every 20 appends.
59
+ try {
60
+ const info = await stat(path());
61
+ if (info.size > maxBytes) await rename(path(), `${path()}.1`);
62
+ } catch { /* first write: nothing to rotate */ }
63
+ }
64
+ await appendFile(path(), line, 'utf8');
65
+ }).catch(() => void 0);
66
+ return queue;
67
+ }
68
+
69
+ /**
70
+ * Read back the newest rows of today's file.
71
+ * @param count - rows to return, newest last.
72
+ */
73
+ async function tail(count = 50) {
74
+ let text = '';
75
+ try {
76
+ text = await readFile(path(), 'utf8');
77
+ } catch {
78
+ return { file: path(), rows: [] };
79
+ }
80
+ const rows = text
81
+ .split('\n')
82
+ .filter((line) => line !== '')
83
+ .map((line) => {
84
+ try {
85
+ return JSON.parse(line);
86
+ } catch {
87
+ return { t: '?', ev: 'unparsed', line };
88
+ }
89
+ });
90
+ return { file: path(), rows: rows.slice(-Math.max(1, Math.min(500, count))) };
91
+ }
92
+
93
+ return {
94
+ append,
95
+ tail,
96
+ path,
97
+ dir,
98
+ get level() {
99
+ return level;
100
+ },
101
+ get queueSize() {
102
+ return appended;
103
+ },
104
+ };
105
+ }
@@ -39,15 +39,8 @@ export function unfinishedTasksFor(state, memberId) {
39
39
  /**
40
40
  * Pick an Agent eligible to review this task: not the assignee, never claimed,
41
41
  * active, QA first, then any reviewer-role member, then any other Agent.
42
+ *
43
+ * The rule itself lives in `policy.js` (single implementation for ledger,
44
+ * views and Waker); this re-export keeps the historical import path stable.
42
45
  */
43
- export function eligibleReviewers(state, task) {
44
- if (task === undefined || task === null) return [];
45
- const candidates = Object.values(state.members ?? {}).filter((member) =>
46
- member.kind === 'agent'
47
- && member.status !== 'retired'
48
- && member.id !== task.assigneeId
49
- && !(task.claimHistory ?? []).includes(member.id)
50
- && (task.qaRequired !== true || isQaMember(member)));
51
- const rank = (member) => (isQaMember(member) ? 0 : isReviewerMember(member) ? 1 : 2);
52
- return candidates.sort((a, b) => rank(a) - rank(b) || String(a.createdAt).localeCompare(String(b.createdAt)));
53
- }
46
+ export { eligibleReviewers } from './policy.js';
@@ -1,7 +1,38 @@
1
1
  import { ERRORS, fail } from './errors.js';
2
+ import { isQaMember, isReviewerMember } from './member-profile.js';
2
3
 
3
4
  /** @typedef {{ kind: 'human'|'agent'|'system', memberId?: string }} Actor */
4
5
 
6
+ /** Member statuses allowed to hold work or review; failed members are out. */
7
+ export const ACTIVE_MEMBER_STATUSES = Object.freeze(['provisioning', 'running', 'idle']);
8
+
9
+ /**
10
+ * The single authority for "which Agent may review this Task" (INV-04/Q-05):
11
+ * active, not the current assignee, never a past claimant. QA-required Tasks
12
+ * narrow candidates to QA members. The command layer additionally resolves the
13
+ * acting member; Human review is the fallback (policy reasons live in
14
+ * reviewEligibility below).
15
+ */
16
+ export function isReviewCandidate(member, task) {
17
+ if (member?.kind !== 'agent') return false;
18
+ if (!ACTIVE_MEMBER_STATUSES.includes(member.status)) return false;
19
+ if (member.id === task.assigneeId) return false;
20
+ if (Array.isArray(task.claimHistory) && task.claimHistory.includes(member.id)) return false;
21
+ if (task.qaRequired === true && !isQaMember(member)) return false;
22
+ return true;
23
+ }
24
+
25
+ /**
26
+ * Ranked review candidates for the Waker: QA first, then reviewer roles,
27
+ * then any other eligible Agent. Older members win ties.
28
+ */
29
+ export function eligibleReviewers(state, task) {
30
+ if (task === undefined || task === null) return [];
31
+ const candidates = Object.values(state.members ?? {}).filter((member) => isReviewCandidate(member, task));
32
+ const rank = (member) => (isQaMember(member) ? 0 : isReviewerMember(member) ? 1 : 2);
33
+ return candidates.sort((a, b) => rank(a) - rank(b) || String(a.createdAt).localeCompare(String(b.createdAt)));
34
+ }
35
+
5
36
  export function isHuman(actor) {
6
37
  return actor?.kind === 'human';
7
38
  }