@suifei/dsh-ai-team 0.4.24 → 0.4.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/client.js +30 -10
  3. package/index.js +300 -42
  4. package/lib/domain/task.js +6 -0
  5. package/lib/host/decision-report.js +16 -2
  6. package/lib/host/member-tools.js +7 -5
  7. package/lib/host/project-registry.js +19 -2
  8. package/lib/host/service.js +172 -35
  9. package/lib/host/views.js +23 -1
  10. package/lib/host/waker.js +7 -3
  11. package/lib/host/weekly-view.js +3 -0
  12. package/lib/ledger/checkpoint.js +11 -0
  13. package/lib/ledger/writer.js +164 -23
  14. package/lib/runtime/failure-policy.js +15 -4
  15. package/lib/runtime/host-agent.js +38 -10
  16. package/lib/runtime/host-repair.js +70 -0
  17. package/lib/runtime/member-runtime.js +19 -12
  18. package/lib/runtime/skill-catalog.js +4 -1
  19. package/lib/runtime/skill-provider.js +29 -5
  20. package/lib/skillopt/adopt-gate.js +1 -1
  21. package/lib/skillopt/gate-wiring.js +24 -4
  22. package/lib/skillopt/job-runner.js +5 -0
  23. package/lib/skillopt/jobs.js +4 -1
  24. package/lib/skillopt/judge.js +46 -12
  25. package/lib/skillopt/optimize-wiring.js +12 -6
  26. package/lib/skillopt/proposal-store.js +33 -0
  27. package/lib/skillopt/review-runner.js +17 -3
  28. package/lib/skillopt/reviewer.js +4 -4
  29. package/lib/skillopt/rubric.js +20 -6
  30. package/lib/skillopt/tool-access.js +56 -0
  31. package/package.json +3 -3
  32. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__init__.cpython-311.pyc +0 -0
  33. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__main__.cpython-311.pyc +0 -0
  34. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/backend.cpython-311.pyc +0 -0
  35. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/budget.cpython-311.pyc +0 -0
  36. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/config.cpython-311.pyc +0 -0
  37. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/consolidate.cpython-311.pyc +0 -0
  38. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/cycle.cpython-311.pyc +0 -0
  39. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/dream.cpython-311.pyc +0 -0
  40. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/evidence.cpython-311.pyc +0 -0
  41. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/gate.cpython-311.pyc +0 -0
  42. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/handoff_backend.cpython-311.pyc +0 -0
  43. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest.cpython-311.pyc +0 -0
  44. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_codex.cpython-311.pyc +0 -0
  45. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot.cpython-311.pyc +0 -0
  46. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot_cli.cpython-311.pyc +0 -0
  47. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_cursor.cpython-311.pyc +0 -0
  48. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_opencode.cpython-311.pyc +0 -0
  49. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_pi.cpython-311.pyc +0 -0
  50. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_sources.cpython-311.pyc +0 -0
  51. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/judges.cpython-311.pyc +0 -0
  52. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/memory.cpython-311.pyc +0 -0
  53. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/mine.cpython-311.pyc +0 -0
  54. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/multi_skill.cpython-311.pyc +0 -0
  55. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/replay.cpython-311.pyc +0 -0
  56. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/skill_resolver.cpython-311.pyc +0 -0
  57. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/staging.cpython-311.pyc +0 -0
  58. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/state.cpython-311.pyc +0 -0
  59. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/tasks_file.cpython-311.pyc +0 -0
  60. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/types.cpython-311.pyc +0 -0
package/index.js CHANGED
@@ -11,13 +11,14 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
14
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
15
15
  import z from '@deepseek-ai/schemastery';
16
16
  import { ProjectRuntime } from './lib/host/project-runtime.js';
17
17
  import { ProjectRegistry } from './lib/host/project-registry.js';
18
18
  import { ids } from './lib/domain/ids.js';
19
19
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
20
20
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
21
+ import { repairArchivedHosts as repairHostSessions } from './lib/runtime/host-repair.js';
21
22
  import { classifyLlmFailure, retryDecision } from './lib/runtime/failure-policy.js';
22
23
  import { memberIdentity } from './lib/domain/member-profile.js';
23
24
  import { loadSkillContext } from './lib/runtime/skill-loader.js';
@@ -26,11 +27,16 @@ import { isSkillExcluded } from './lib/runtime/skill-policy.js';
26
27
  import { installFileSkillProvider } from './lib/runtime/skill-provider.js';
27
28
  import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
28
29
  import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
30
+ import { wrapToolsWithSkilloptAccess } from './lib/skillopt/tool-access.js';
31
+ import { applyLiveAtomically, backupLive, sha12 } from './lib/skillopt/proposal-store.js';
29
32
  import { formatRubric, scoreSkillRubric } from './lib/skillopt/rubric.js';
30
33
  import { makeJudge, makeReadPair } from './lib/skillopt/gate-wiring.js';
31
34
  import { runOptimizeLoop, validateCandidate, weakestDimension } from './lib/skillopt/optimizer.js';
32
35
  import { hasPairedKeepRecord, makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
33
- import { listJobs, readJob, writeJob } from './lib/skillopt/jobs.js';
36
+ import { isJobExpired, listJobs, readJob, writeJob } from './lib/skillopt/jobs.js';
37
+
38
+ /** 评审通道 job 的兜底 TTL:与子代理通道(jobs.js JOB_TTL_MS)保持一致。 */
39
+ const REVIEW_JOB_TTL_MS = 30 * 60 * 1000;
34
40
  import { reconcileJobs } from './lib/skillopt/job-runner.js';
35
41
  import { collectReview, startReview } from './lib/skillopt/review-runner.js';
36
42
  import { REVIEWER_NAME } from './lib/skillopt/reviewer.js';
@@ -52,7 +58,15 @@ export const name = 'ai-team';
52
58
  // 实际使用的服务(含可选服务:缺失时 serviceOf 回退 ctx.get 并返回 undefined)。
53
59
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell', 'agents', 'subagents', 'sessions'];
54
60
 
55
- const VERSION = '0.4.24';
61
+ // 版本号只有一处真源:package.json。硬编码字面量曾让 /health 在升版后仍报旧版本,
62
+ // 误导「运行实例是否加载了新代码」的判断。
63
+ const VERSION = (() => {
64
+ try {
65
+ return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '0.0.0';
66
+ } catch {
67
+ return '0.0.0';
68
+ }
69
+ })();
56
70
  const HUMAN_ID = 'mem_human';
57
71
 
58
72
  const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
@@ -309,18 +323,36 @@ export function apply(ctx, config = {}) {
309
323
  // Attach the broadcast/wake hook before the first tick: events
310
324
  // produced by the tick must reach SSE clients immediately.
311
325
  attachRuntime(runtime);
312
- void pmoTick(runtime).catch((error) => {
313
- diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
314
- console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
315
- });
326
+ if (!pmoBusy.has(runtime.id)) {
327
+ pmoBusy.add(runtime.id);
328
+ void pmoTick(runtime).catch((error) => {
329
+ diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
330
+ console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
331
+ }).finally(() => pmoBusy.delete(runtime.id));
332
+ }
316
333
  }
334
+ // 归档修复不能等 tick:workspaceRegistry 要等 sessionPersistence 与
335
+ // 历史 bootstrap 完成才 active,boot 时通常还取不到。这里先试一次,
336
+ // 再用一个短重试窗口(2s × 30)兜住就绪时间,不必等 60s 的 tick。
337
+ void (async () => {
338
+ for (let attempt = 0; attempt < 30; attempt += 1) {
339
+ await repairArchivedHosts();
340
+ if (hostRepaired) return;
341
+ await new Promise((resolve) => { const timer = setTimeout(resolve, 2000); timer.unref?.(); });
342
+ }
343
+ })();
317
344
  if (pmoTimer === null) {
318
345
  pmoTimer = setInterval(() => {
319
346
  for (const runtime of booted?.runtimes?.values() ?? []) {
347
+ if (pmoBusy.has(runtime.id)) {
348
+ diag.append({ ev: 'pmo.tick.skip', projectId: runtime.id, reason: 'in-flight' });
349
+ continue;
350
+ }
351
+ pmoBusy.add(runtime.id);
320
352
  void pmoTick(runtime).catch((error) => {
321
353
  diag.append({ ev: 'pmo.tick.fail', projectId: runtime.id, message: error?.message ?? String(error) });
322
354
  console.warn('[ai-team] PMO tick failed:', error?.message ?? error);
323
- });
355
+ }).finally(() => pmoBusy.delete(runtime.id));
324
356
  }
325
357
  }, 60_000);
326
358
  pmoTimer.unref?.();
@@ -365,15 +397,21 @@ export function apply(ctx, config = {}) {
365
397
  model: member.config?.model ?? null,
366
398
  }, failureRuntime.id);
367
399
  } catch (error) {
400
+ // diag 是唯一持久化通道:只打 console 等于线上不可诊断。
401
+ diag.append({ ev: 'member.failure.record.fail', memberId: member.id, message: error?.message ?? String(error) });
368
402
  console.warn('[ai-team] member failure record failed:', member.id, error?.message ?? error);
369
403
  return next();
370
404
  }
371
- if (!failure.retryable) return next();
405
+ // 不可重试 ≠ 不可恢复:model_unavailable / context_overflow 声明的是
406
+ // fallback(换路),此前一律 next() 让它们的 fallback 永远不可达。
407
+ const fallbackCapable = failure.action === 'fallback' || failure.action === 'compact_or_fallback';
408
+ if (!failure.retryable && !fallbackCapable) return next();
372
409
  const decision = retryDecision(failure, member.config ?? {}, recorded.member.attempts ?? 1);
373
410
  if (decision.action === 'fallback' && decision.patch !== undefined) {
374
411
  try {
375
412
  await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback', failureRuntime.id);
376
413
  } catch (error) {
414
+ diag.append({ ev: 'member.fallback.fail', memberId: member.id, message: error?.message ?? String(error) });
377
415
  console.warn('[ai-team] member fallback failed:', member.id, error?.message ?? error);
378
416
  }
379
417
  }
@@ -381,20 +419,26 @@ export function apply(ctx, config = {}) {
381
419
  return { kind: 'retry' };
382
420
  })
383
421
  : () => {};
384
- // 诊断:记录成员 agent 可见的工具名与 preset。DSH 以「scope carrier +
385
- // agent」两个参数 emit(文档:both with the agent's scope carrier),
386
- // 因此回调需兼容两种形状,取真正带 ctx 的那个。
422
+ // 诊断:记录成员 agent 可见的工具名与 preset。规范签名(cordis_inspect_query
423
+ // Event/agent/created 实测):单参 payload = { agent, source, signal },
424
+ // 不是 (scopeCarrier, agent)。此前按双参取会把 payload 当 agent,agentId 恒 null。
387
425
  const offAgentCreated = typeof ctx.on === 'function'
388
- ? ctx.on('agent/created', (first, second) => {
426
+ ? ctx.on('agent/created', (payload) => {
389
427
  try {
390
- const agent = second?.ctx !== undefined ? second : (first?.ctx !== undefined ? first : (second ?? first));
391
- if (agent?.ctx?.tools === undefined) return;
392
- const runtime = runtimeForAgent(agent?.id);
428
+ const agent = payload?.agent;
429
+ const agentId = agent?.id ?? null;
430
+ if (agentId === null) return;
431
+ const runtime = runtimeForAgent(agentId);
393
432
  if (runtime === null) return; // 只关注成员会话
394
- const names = (agent.ctx.tools.definitions?.() ?? []).map((definition) => definition.name);
433
+ const presets = serviceOf(ctx, 'agentPresets');
434
+ const tools = agent?.ctx?.tools ?? presets?.serviceFor?.(agent, 'tools');
435
+ const names = (tools?.definitions?.() ?? []).map((definition) => definition.name);
436
+ let preset = null;
437
+ try { preset = presets?.composedPreset?.(agent.ctx) ?? null; } catch { /* preset is optional */ }
395
438
  diag.append({
396
- ev: 'agent.created.probe.fail',
397
- agentId: agent?.id ?? null,
439
+ ev: 'agent.created.probe',
440
+ agentId,
441
+ preset,
398
442
  toolCount: names.length,
399
443
  hasTeam: names.includes('team'),
400
444
  names: names.slice(0, 40),
@@ -416,7 +460,7 @@ export function apply(ctx, config = {}) {
416
460
  .filter(Boolean)
417
461
  .join('\n');
418
462
  diag.append({
419
- ev: 'member.output.probe.fail',
463
+ ev: 'member.output.probe',
420
464
  sessionId: session?.id ?? null,
421
465
  chars: text.length,
422
466
  preview: text.slice(0, 240),
@@ -440,12 +484,28 @@ export function apply(ctx, config = {}) {
440
484
  diag.append({ ev: 'session.flush.fail', sessionId: session?.id ?? null, message: error?.message ?? String(error) });
441
485
  console.warn('[ai-team] member session flush failed:', error?.message ?? error);
442
486
  }
443
- if (event?.data?.reason?.kind !== 'completed') return;
487
+ // 回合结局必须全部可见:`blocked` 表示回合在发出模型请求前就被拒绝
488
+ // (典型原因:会话或血缘祖先被归档),`error` 表示模型/工具链失败。
489
+ // 旧实现只认 completed,这两种结局被静默丢弃,恢复链路永不触发。
490
+ const endKind = event?.data?.reason?.kind ?? 'unknown';
491
+ if (endKind !== 'completed') {
492
+ diag.append({
493
+ ev: 'member.turn.blocked',
494
+ memberId: member.id,
495
+ sessionId: session?.id ?? null,
496
+ kind: endKind,
497
+ reason: event?.data?.reason?.error?.message ?? null,
498
+ });
499
+ // blocked 最常见的原因是归档 gate:立刻复核一次血缘归档状态。
500
+ if (endKind === 'blocked') void repairArchivedHosts();
501
+ return;
502
+ }
444
503
  if (member.lastFailure === undefined || member.lastFailure === null) return;
445
504
  try {
446
505
  await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null, eventRuntime.id);
447
506
  broadcast(undefined, eventRuntime);
448
507
  } catch (error) {
508
+ diag.append({ ev: 'member.recovery.fail', memberId: member.id, message: error?.message ?? String(error) });
449
509
  console.warn('[ai-team] member recovery record failed:', member.id, error?.message ?? error);
450
510
  }
451
511
  })
@@ -457,6 +517,9 @@ export function apply(ctx, config = {}) {
457
517
  let host = null;
458
518
  let hostPromise = null;
459
519
  const wakeKeys = new Map();
520
+ // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
521
+ // 造成 autoAnswerDecisions/reconcileJobs 并发执行同一条账本。按 Project 去重。
522
+ const pmoBusy = new Set();
460
523
  const activationTasks = new Map();
461
524
  const pmoLastKick = new Map();
462
525
  const pmoLastStall = new Map();
@@ -481,7 +544,7 @@ export function apply(ctx, config = {}) {
481
544
  // 驱动,不断 Human 通道。
482
545
  const gateProject = projectRuntime.service.state.projects?.[projectRuntime.id];
483
546
  if (gateProject !== undefined && gateProject.runState === 'stopped' && actor?.kind !== 'human') return;
484
- const plans = planWakes(projectRuntime.service.state, result, actor);
547
+ const plans = planWakes(projectRuntime.service.state, result, actor, { projectId: projectRuntime.id });
485
548
  if (plans.length === 0) return;
486
549
  // Window eviction: a key older than this horizon can no longer dedupe
487
550
  // a relevant event, so drop it instead of growing the Map forever.
@@ -505,16 +568,18 @@ export function apply(ctx, config = {}) {
505
568
  if (wakeKeys.has(plan.key)) continue;
506
569
  let member = projectRuntime.service.state.members?.[plan.memberId];
507
570
  if (member === undefined) continue;
508
- // Reserve before the async delivery: the HTTP result and the ledger
509
- // event both schedule the same plan, and only one may deliver it.
510
- wakeKeys.set(plan.key, result?.event?.seq ?? head);
511
571
  // 无工作目录的项目不 wake(与 activate 的 fail-closed 同一不变量):
512
572
  // 冷恢复/直连唤醒都会在会话原 cwd 里干活,不该落到插件数据目录。
573
+ // 必须在占用去重键**之前**判定:这些键多数不带时间桶,跳过时若已占用,
574
+ // 同一事件(startup/thread/reflection)之后再也不会被重新规划。
513
575
  const projectWorkspacePath = projectWorkspace(projectRuntime, member);
514
576
  if (projectWorkspacePath === null || projectWorkspacePath.trim?.() === '') {
515
577
  diag?.append({ ev: 'wake.skip', projectId: projectRuntime.id, memberId: plan.memberId, reason: 'E_WORKSPACE_REQUIRED' });
516
578
  continue;
517
579
  }
580
+ // Reserve before the async delivery: the HTTP result and the ledger
581
+ // event both schedule the same plan, and only one may deliver it.
582
+ wakeKeys.set(plan.key, result?.event?.seq ?? head);
518
583
  const cwd = projectWorkspacePath;
519
584
  try {
520
585
  // Idle default members have no Agent session yet. A wake must
@@ -597,7 +662,14 @@ export function apply(ctx, config = {}) {
597
662
  sessionIdType: typeof targetMember?.sessionId,
598
663
  failureText: failureText.slice(0, 160),
599
664
  });
600
- const legacySession = /subagent|not-found|not found|E_SESSION_MISSING|NOT_RESUMABLE|unavailable/i.test(failureText)
665
+ // 只按结构化错误码判定:对整段 message 做宽词匹配会把「sessions
666
+ // service is unavailable」「task not found」这类瞬时/无关错误也算命中,
667
+ // 进而 force reseat 丢掉成员会话上下文。
668
+ const failureCode = String(error?.code ?? '').toUpperCase();
669
+ const deadSessionPool = failureCode === 'E_SESSION_MISSING'
670
+ || failureCode === 'NOT_RESUMABLE'
671
+ || failureCode === 'ENOTFOUND';
672
+ const legacySession = deadSessionPool
601
673
  && typeof targetMember?.sessionId === 'string' && targetMember.sessionId !== '';
602
674
  diag.append({
603
675
  ev: 'wake.catch.probe.fail',
@@ -643,6 +715,9 @@ export function apply(ctx, config = {}) {
643
715
  };
644
716
  const pmoTick = async (projectRuntime) => {
645
717
  if (projectRuntime === null || projectRuntime === undefined) return;
718
+ // 归档修复重试点:boot 时 workspaceRegistry 往往还没 active,等 tick
719
+ // (60s 后)再试一次;修好即置位,之后每个 tick 直接返回。
720
+ await repairArchivedHosts();
646
721
  const state = projectRuntime.service.state;
647
722
  const project = state.projects?.[projectRuntime.id];
648
723
  // job 收割先于 pmoAuto 门:Human 启动的优化 job 与 PMO 派发无关,
@@ -663,7 +738,9 @@ export function apply(ctx, config = {}) {
663
738
  ensureParent: () => ensureParent(),
664
739
  votes: config.skilloptJudgeVotes ?? 3,
665
740
  startChild: async (label, spec) => {
666
- const child = await subagents.startActivation({ ...spec, label });
741
+ // 必须走 serviceOf:这里不在 activateMember/wakeFromResult 的
742
+ // 词法作用域内,裸写 subagents 会在判官轮抛 ReferenceError。
743
+ const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
667
744
  return { childId: child.childId, outputStart: child.outputStart ?? null };
668
745
  },
669
746
  readText: (file) => readFileSync(file, 'utf8'),
@@ -914,17 +991,40 @@ export function apply(ctx, config = {}) {
914
991
  readPair,
915
992
  // 两阶段异步模式:工具 execute 内无法等待子代理,判据改为
916
993
  // results.tsv 中该 skill 已存在 paired keep 记录(同步可查)。
917
- hasKeepRecord: async ({ projectDir, skillPath }) => hasPairedKeepRecord(projectDir, skillPath),
994
+ // results.tsv 的写入根是插件数据目录(job.project = runtime.dir),而
995
+ // adopt 门拿到的是模型传入的 args.project(通常是工作区)。只查后者的
996
+ // 话,keep 记录永远找不到、adopt 恒被拒——这里把两个根都查。
997
+ hasKeepRecord: async ({ projectDir, skillPath, candidate }) => {
998
+ const roots = new Set();
999
+ if (typeof projectDir === 'string' && projectDir !== '') roots.add(projectDir);
1000
+ for (const runtime of booted?.runtimes?.values() ?? []) {
1001
+ if (typeof runtime?.dir === 'string' && runtime.dir !== '') roots.add(runtime.dir);
1002
+ }
1003
+ for (const root of roots) {
1004
+ if (hasPairedKeepRecord(root, skillPath, candidate)) return true;
1005
+ }
1006
+ diag.append({ ev: 'skillopt.adoptgate.norecord.fail', projectDir: projectDir ?? null, skillPath: skillPath ?? null, roots: roots.size });
1007
+ return false;
1008
+ },
918
1009
  diag: (line, extra) => diag.append({
919
1010
  ev: extra?.ev ?? 'skillopt.adoptgate',
920
1011
  message: line,
921
1012
  ...(extra?.project === undefined ? {} : { project: extra.project }),
922
1013
  }),
923
1014
  });
1015
+ // 授权门:这批工具是全局注册的,但 adopt/schedule 会改 live 文件与系统
1016
+ // cron。只允许 Team 成员与 Human 面对的根会话;一次性子代理一律拒绝。
1017
+ const skilloptCallerAllowed = (exec) => {
1018
+ const agentId = exec?.agent?.id;
1019
+ if (typeof agentId !== 'string' || agentId === '') return false;
1020
+ if (runtimeForAgent(agentId) !== null) return true;
1021
+ return exec?.agent?.session?.header?.origin !== 'subagent';
1022
+ };
1023
+ const guardedTools = wrapToolsWithSkilloptAccess(tools, skilloptCallerAllowed);
924
1024
  // Backend/timeout come from the plugin Config (patch layer), so an
925
1025
  // operator can move the skillopt_* tools off the safe mock default.
926
1026
  disposeSkillOpt = applySkillOpt({
927
- tools: wrapToolsWithAdoptGate(tools, adoptGate),
1027
+ tools: wrapToolsWithAdoptGate(guardedTools, adoptGate),
928
1028
  shell: shellProxy,
929
1029
  logger: console,
930
1030
  }, {
@@ -933,7 +1033,7 @@ export function apply(ctx, config = {}) {
933
1033
  timeoutMs: config.skilloptTimeoutMs ?? 120_000,
934
1034
  }) ?? (() => {});
935
1035
  // 9 维 rubric(triage)与独立 judge(keep/revert)作为新工具暴露。
936
- const rubricTool = tools.register({
1036
+ const rubricTool = guardedTools.register({
937
1037
  name: 'skillopt_rubric',
938
1038
  description: 'Score a SKILL.md against the 9-dimension Darwin rubric (triage only — absolute scores must not be used for keep/revert).',
939
1039
  parameters: {
@@ -958,7 +1058,7 @@ export function apply(ctx, config = {}) {
958
1058
  return formatRubric(result);
959
1059
  },
960
1060
  });
961
- const judgeTool = tools.register({
1061
+ const judgeTool = guardedTools.register({
962
1062
  name: 'skillopt_judge',
963
1063
  description: 'Paired independent-judge verdict (N odd votes, majority) for before/after SKILL.md — the authoritative keep/revert signal.',
964
1064
  parameters: {
@@ -991,7 +1091,7 @@ export function apply(ctx, config = {}) {
991
1091
  // 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
992
1092
  // 两阶段异步:工具只启动生成子代理并写 job,收割由 PMO tick 完成
993
1093
  // (工具 execute 内无法同步等待一次性子代理——实测 result 永不 settle)。
994
- const optimizeTool = tools.register({
1094
+ const optimizeTool = guardedTools.register({
995
1095
  name: 'skillopt_optimize',
996
1096
  description: 'Start a Darwin hill-climbing job for one SKILL.md (diagnose, generate candidate, paired judge, keep/revert). The PMO tick harvests it; poll skillopt_jobs for the outcome.',
997
1097
  parameters: {
@@ -1077,7 +1177,7 @@ export function apply(ctx, config = {}) {
1077
1177
  ].join('\n');
1078
1178
  },
1079
1179
  });
1080
- const jobsTool = tools.register({
1180
+ const jobsTool = guardedTools.register({
1081
1181
  name: 'skillopt_jobs',
1082
1182
  description: 'List optimize jobs (state, target dimension, verdict) for a project.',
1083
1183
  parameters: { project: { type: 'string', description: 'Project directory' } },
@@ -1127,15 +1227,42 @@ export function apply(ctx, config = {}) {
1127
1227
  const collected = collectReview({ service: runtime.service, job });
1128
1228
  const expected = collected.expected ?? job.reviewOrders?.length ?? 3;
1129
1229
  if (collected.votes.length < expected) {
1230
+ // 评审通道被 reconcileJobs 明确排除,没有 TTL 兜底:评审官不回帖
1231
+ // 时 job 会永久停在 judging、评审卡永久 active。这里补超时终态。
1232
+ if (isJobExpired(job, Date.now(), REVIEW_JOB_TTL_MS)) {
1233
+ writeJob(job.project, {
1234
+ ...job,
1235
+ state: 'failed',
1236
+ error: `review timed out after ${Math.round(REVIEW_JOB_TTL_MS / 60000)}min (${collected.votes.length}/${expected} votes)`,
1237
+ updatedAt: Date.now(),
1238
+ });
1239
+ diag.append({ ev: 'skillopt.job.timeout', jobId: job.id, got: collected.votes.length, expected });
1240
+ continue;
1241
+ }
1130
1242
  diag.append({ ev: 'skillopt.review.waiting', jobId: job.id, got: collected.votes.length, expected });
1131
1243
  continue;
1132
1244
  }
1133
1245
  const kept = collected.decision.verdict === 'keep';
1246
+ const jobDir = job.project;
1247
+ // 落盘前先确认 live 仍是评审时的基线:评审期间的人工修改不能被
1248
+ // 一次 revert 用陈旧快照覆盖(反之亦然)。
1249
+ let liveText = null;
1250
+ try { liveText = existsSync(job.skillPath) ? readFileSync(job.skillPath, 'utf8') : null; } catch { liveText = null; }
1251
+ if (liveText !== null && typeof job.before === 'string' && sha12(liveText) !== sha12(job.before)) {
1252
+ writeJob(jobDir, { ...job, state: 'failed', error: 'live SKILL.md changed during review (conflict)', updatedAt: Date.now() });
1253
+ diag.append({ ev: 'skillopt.job.conflict', jobId: job.id, skillPath: job.skillPath });
1254
+ continue;
1255
+ }
1256
+ let backupPath = null;
1257
+ try {
1258
+ backupPath = backupLive({ projectDir: jobDir, skillPath: job.skillPath, text: liveText ?? job.before ?? '' });
1259
+ } catch (error) {
1260
+ diag.append({ ev: 'skillopt.job.backup.fail', jobId: job.id, message: error?.message ?? String(error) });
1261
+ }
1134
1262
  // keep → 落盘候选;revert → 恢复基线(评审卡收票后才动文件)。
1135
- writeFileSync(job.skillPath, kept ? job.candidate : job.before, 'utf8');
1263
+ applyLiveAtomically(job.skillPath, kept ? job.candidate : job.before);
1136
1264
  const beforeScore = scoreSkillRubric(job.before, { measured: false })?.total ?? null;
1137
1265
  const afterScore = scoreSkillRubric(kept ? job.candidate : job.before, { measured: false })?.total ?? null;
1138
- const jobDir = job.project;
1139
1266
  const appender = makeResultAppender({ projectDir: jobDir });
1140
1267
  await appender([
1141
1268
  new Date().toISOString().slice(0, 19),
@@ -1147,22 +1274,45 @@ export function apply(ctx, config = {}) {
1147
1274
  job.dimension ?? '-',
1148
1275
  `${collected.decision.better}-${collected.decision.worse} ${collected.decision.verdict}` ,
1149
1276
  'paired',
1277
+ sha12(job.candidate),
1150
1278
  ].join('\t'));
1151
- writeJob(jobDir, { ...job, state: 'done', decision: collected.decision, updatedAt: Date.now() });
1279
+ writeJob(jobDir, { ...job, state: 'done', decision: collected.decision, backup: backupPath ?? job.backup ?? null, updatedAt: Date.now() });
1280
+ // 评审卡必须收口:否则它保持 pending 进入 PMO 的 active 集合,
1281
+ // 会被 heartbeat/stall/escalate 反复唤醒评审官(每 job 永久留一张卡)。
1282
+ try {
1283
+ const card = runtime.service.state.tasks?.[job.reviewTaskId];
1284
+ if (card !== undefined && card.status !== 'done' && card.status !== 'cancelled' && card.tombstone !== true) {
1285
+ await runtime.service.dispatch({
1286
+ type: 'task.cancel',
1287
+ payload: {
1288
+ taskId: job.reviewTaskId,
1289
+ expectedRevision: card.revision,
1290
+ reason: `blind review collected: ${collected.decision.verdict}`,
1291
+ },
1292
+ actor,
1293
+ projectId: runtime.id,
1294
+ });
1295
+ }
1296
+ } catch (error) {
1297
+ diag.append({ ev: 'skillopt.review.card.close.fail', jobId: job.id, taskId: job.reviewTaskId, message: error?.message ?? String(error) });
1298
+ }
1152
1299
  diag.append({ ev: 'skillopt.job.done', jobId: job.id, verdict: collected.decision.verdict, better: collected.decision.better, worse: collected.decision.worse, kept, source: 'reviewer-card' });
1153
1300
  }
1154
1301
  if (jobs.length === 0) return '[skillopt jobs] none';
1155
1302
  return ['[skillopt jobs]', ...jobs.map((job) => ` ${job.id} ${job.state} ${job.dimension ?? '-'}${job.decision ? ` verdict=${job.decision.verdict} (${job.decision.better}-${job.decision.worse})` : ''}${job.error ? ` error=${job.error}` : ''}`)].join('\n');
1156
1303
  },
1157
1304
  });
1305
+ // 先保存 applySkillOpt 的真实 disposer:直接把 disposeSkillOpt 指向
1306
+ // disposeExtra 会形成自引用递归(teardown 时栈溢出且原始 disposer 永不可达)。
1307
+ const innerSkillOptDispose = disposeSkillOpt;
1158
1308
  const disposeExtra = () => {
1159
- try { disposeSkillOpt?.(); } catch { /* already disposed */ }
1309
+ try { innerSkillOptDispose?.(); } catch { /* already disposed */ }
1160
1310
  try { rubricTool?.(); } catch { /* noop */ }
1161
1311
  try { judgeTool?.(); } catch { /* noop */ }
1162
1312
  try { optimizeTool?.(); } catch { /* noop */ }
1163
1313
  try { jobsTool?.(); } catch { /* noop */ }
1164
1314
  };
1165
- disposeSkillOpt = disposeExtra;
1315
+ disposeSkillOpt = disposeExtra;
1166
1316
  diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
1167
1317
  }
1168
1318
  } catch (error) {
@@ -1182,7 +1332,13 @@ export function apply(ctx, config = {}) {
1182
1332
  return runtime.service.dispatch(command);
1183
1333
  },
1184
1334
  }), {
1185
- when: (activation) => runtimeForAgent(activation?.agent?.id) !== null,
1335
+ // 可见性判定不能按「请求者是已知成员」来算:
1336
+ // * 成员的首个 model step 发生在 bindMemberSession 写入 sessionId 之前
1337
+ // (activate() 返回后才写),此时 runtimeForAgent(请求者) 为 null,
1338
+ // 实测首个 header 43 个工具、第二个起 44 个,差集恰好是 team;
1339
+ // * owner/宿主永远不是成员,按此判定它也拿不到 team。
1340
+ // 因此只要本进程内 AI Team runtime 已 boot,团队板工具即对 agent 可见。
1341
+ when: () => booted !== null,
1186
1342
  })
1187
1343
  : () => {};
1188
1344
  } catch (error) {
@@ -1190,8 +1346,48 @@ export function apply(ctx, config = {}) {
1190
1346
  console.warn('[ai-team] team tool registration failed:', error?.message ?? error);
1191
1347
  }
1192
1348
 
1349
+ // 历史归档修复:成员是 host 的子会话,`archived-session-gate` 会沿 subagent
1350
+ // 血缘上溯,父会话被归档即拒绝整条血缘 —— 回合以 {kind:'blocked'} 结束且不发
1351
+ // 模型请求(实测 453 blocked / 0 completed)。旧版本把 host 归档用于隐藏会话。
1352
+ let hostRepaired = false;
1353
+ let hostRepairWarned = false;
1354
+ const repairArchivedHosts = async () => {
1355
+ if (hostRepaired) return;
1356
+ try {
1357
+ const registry = serviceOf(ctx, 'workspaceRegistry');
1358
+ const repaired = await repairHostSessions({
1359
+ runtimes: booted?.runtimes?.values() ?? [],
1360
+ sessions: serviceOf(ctx, 'sessions'),
1361
+ workspaceRegistry: registry,
1362
+ diag,
1363
+ });
1364
+ // null = workspaceRegistry 尚未 active(它要等 sessionPersistence 与
1365
+ // 历史 bootstrap)。保持未修复状态,交给下一次 tick/ensureParent 重试;
1366
+ // 否则一次早跑就永久放弃,正是上一版静默失效的原因。
1367
+ if (repaired === null) {
1368
+ if (!hostRepairWarned) {
1369
+ hostRepairWarned = true;
1370
+ let keys = [];
1371
+ try { keys = registry === null || registry === undefined ? [] : Object.keys(registry).slice(0, 8); } catch { keys = ['<unreadable>']; }
1372
+ diag.append({
1373
+ ev: 'host.repair.deferred.fail',
1374
+ reason: 'workspaceRegistry not ready',
1375
+ registryType: typeof registry,
1376
+ hasUnarchive: typeof registry?.unarchiveSession,
1377
+ keys,
1378
+ });
1379
+ }
1380
+ return;
1381
+ }
1382
+ hostRepaired = true;
1383
+ } catch (error) {
1384
+ hostRepaired = true;
1385
+ diag.append({ ev: 'host.unarchive.sweep.fail', error: error?.message ?? String(error) });
1386
+ }
1387
+ };
1193
1388
  const ensureParent = async () => {
1194
1389
  if (host !== null) return host;
1390
+ await repairArchivedHosts();
1195
1391
  if (hostPromise === null) {
1196
1392
  const existingHost = [...(booted?.runtimes?.values() ?? [])]
1197
1393
  .map((runtime) => runtime.service.state.hostSessionId)
@@ -1665,8 +1861,16 @@ export function apply(ctx, config = {}) {
1665
1861
  if (req.method === 'GET' && url.pathname === '/ai-team/api/bootstrap') {
1666
1862
  const requested = url.searchParams.get('project');
1667
1863
  const requestedRuntime = requested === null ? null : projectRuntime(requested);
1668
- const bootstrapRuntime = requestedRuntime ?? currentRuntime();
1669
- const bootstrap = bootstrapRuntime.service.bootstrap(bootstrapRuntime.id);
1864
+ // 账本里真实存在的项目(registry 的 active 可能与正在服务的账本脱钩)。
1865
+ const servedProjects = (runtime) => Object.keys(runtime?.service?.state?.projects ?? {});
1866
+ let bootstrapRuntime = requestedRuntime ?? currentRuntime();
1867
+ if (requested === null && servedProjects(bootstrapRuntime).length === 0 && servedProjects(booted?.runtime).length > 0) {
1868
+ bootstrapRuntime = booted.runtime;
1869
+ }
1870
+ // 隐式请求用该 runtime 账本里的第一个项目;显式传了不存在的 id 仍由
1871
+ // service 的严格校验报错(保留审计修复,不再静默返回空壳)。
1872
+ const servedProjectId = servedProjects(bootstrapRuntime)[0] ?? bootstrapRuntime.id;
1873
+ const bootstrap = bootstrapRuntime.service.bootstrap(requested === null ? servedProjectId : bootstrapRuntime.id);
1670
1874
  // 跨项目收件箱聚合:其它项目只读 state.inbox 过滤(此前对每个
1671
1875
  // 项目整调 bootstrap——board+quadrants+threads 全算,O(项目数×
1672
1876
  // 全视图)/请求)。
@@ -1853,7 +2057,20 @@ export function apply(ctx, config = {}) {
1853
2057
  if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
1854
2058
  // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
1855
2059
  // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
2060
+ // 但给了就必须真实存在:非法路径若先写进 registry,boot 会在
2061
+ // 该项上抛出,导致整个插件起不来(所有路由 503),只能手工改
2062
+ // projects.json 才能恢复。
2063
+ if (workspacePath !== '') {
2064
+ let stat = null;
2065
+ try { stat = statSync(workspacePath); } catch { stat = null; }
2066
+ if (stat === null || (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true)) {
2067
+ return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `工作目录不存在或不是目录:${workspacePath}` } }, 400);
2068
+ }
2069
+ }
1856
2070
  const id = ids.project();
2071
+ // 先校验工作目录(上面已做),再写 registry、最后开 runtime:
2072
+ // activateProject 内部会调用 registry.setActive(id),因此该行必须已
2073
+ // 存在。校验前置后,不会再把一个打不开的项目写进 projects.json。
1857
2074
  booted.registry.add({ id, name, goal, workspacePath });
1858
2075
  const next = await activateProject(id, name, goal, workspacePath);
1859
2076
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
@@ -1864,7 +2081,9 @@ export function apply(ctx, config = {}) {
1864
2081
  return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
1865
2082
  }
1866
2083
  const record = booted.registry.list().find((project) => project.id === target);
1867
- const next = await activateProject(target, record?.name, record?.goal);
2084
+ // 透传 workspacePath:否则账本里的 project/created 会把工作目录写成空,
2085
+ // 之后该项目的成员激活永远 E_WORKSPACE_REQUIRED。
2086
+ const next = await activateProject(target, record?.name, record?.goal, record?.workspacePath);
1868
2087
  return send(res, { ok: true, project: next.service.state.projects[target] ?? record });
1869
2088
  }
1870
2089
  if (body.type === 'member.activate') {
@@ -1935,6 +2154,45 @@ export function apply(ctx, config = {}) {
1935
2154
  projectId: runtime.id,
1936
2155
  correlationId: typeof body.correlationId === 'string' ? body.correlationId : undefined,
1937
2156
  });
2157
+ // 归档必须同时落到全局 registry:否则 bootstrap 仍报 archived:false,
2158
+ // 项目留在树上,且「最后一个 active 项目」保护对后续归档永远失效。
2159
+ if (body.type === 'project.archive' && body.payload?.archived !== false) {
2160
+ try {
2161
+ booted.registry.setArchived(runtime.id, true);
2162
+ } catch (error) {
2163
+ diag.append({ ev: 'project.archive.registry.fail', projectId: runtime.id, message: error?.message ?? String(error) });
2164
+ }
2165
+ // 归档的正是当前 active:必须同步把 booted 指向 registry 选出的
2166
+ // fallback,否则无参 bootstrap 仍落在已归档 runtime 上 → 工作台
2167
+ // 直接 UNREACHABLE,刷新后也没有项目树可切走,只能重启宿主。
2168
+ if (booted.activeProjectId === runtime.id) {
2169
+ const fallbackId = booted.registry.activeProjectId;
2170
+ const fallback = booted.registry.list().find((project) => project.id === fallbackId);
2171
+ if (fallback !== undefined && fallback.id !== runtime.id) {
2172
+ try {
2173
+ await activateProject(fallback.id, fallback.name, fallback.goal, fallback.workspacePath);
2174
+ diag.append({ ev: 'project.archive.reactivated', from: runtime.id, to: fallback.id });
2175
+ } catch (error) {
2176
+ diag.append({ ev: 'project.archive.reactivate.fail', from: runtime.id, to: fallback.id, message: error?.message ?? String(error) });
2177
+ }
2178
+ }
2179
+ }
2180
+ }
2181
+ // 退役/离队后必须释放常驻子代理:否则 activation 句柄只在 force
2182
+ // 重建或插件卸载时才回收,退役成员的会话会一直挂在进程里。
2183
+ if (body.type === 'member.retire' || body.type === 'member.leave') {
2184
+ const retiredId = body.payload?.memberId;
2185
+ const retired = runtime.service.state.members?.[retiredId];
2186
+ const retiredSession = retired?.sessionId;
2187
+ if (typeof retiredSession === 'string') {
2188
+ const activation = activations.get(retiredSession);
2189
+ if (activation !== undefined) {
2190
+ activations.delete(retiredSession);
2191
+ try { await activation.dispose?.(); } catch { /* already gone */ }
2192
+ diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2193
+ }
2194
+ }
2195
+ }
1938
2196
  send(res, { ok: true, ...result });
1939
2197
  void wakeFromResult(runtime, result, { agentId: HUMAN_ID }).catch((error) => {
1940
2198
  diag.append({ ev: 'wake.plan.fail', projectId: runtime.id, eventType: result?.event?.type ?? null, message: error?.message ?? String(error) });
@@ -302,6 +302,12 @@ export function reassignTask(task, actor, newOwnerId, options = {}) {
302
302
  assertOwnerOrHuman(task, actor);
303
303
  if (typeof newOwnerId !== 'string' || newOwnerId === '') fail(ERRORS.INVALID_ARGUMENT, 'newOwnerId is required');
304
304
  if (newOwnerId === task.ownerId) fail(ERRORS.INVALID_ARGUMENT, 'new owner equals current owner');
305
+ // fold's applyTaskReassigned drops the event for any other status; failing here
306
+ // keeps the domain contract identical to the projection instead of reporting a
307
+ // change that never lands (and bumping revision past the committed one).
308
+ if (task.status !== 'pending' && task.status !== 'in_progress' && task.status !== 'pending_acceptance') {
309
+ fail(ERRORS.INVALID_STATE, `owner cannot be reassigned while the task is ${task.status}`);
310
+ }
305
311
  const updated = next(task, { ownerId: newOwnerId, updatedAt: options.at ?? Date.now() });
306
312
  return {
307
313
  task: updated,
@@ -17,8 +17,22 @@ function stripMarkdown(value) {
17
17
 
18
18
  export function findReportPath(text) {
19
19
  if (typeof text !== 'string') return null;
20
- const matches = text.match(/[A-Za-z]:\\[^\s"'<>|]+?\.md\b/g);
21
- return matches === null || matches.length === 0 ? null : matches[matches.length - 1];
20
+ // 三种写法都要认:反斜杠绝对路径、正斜杠绝对路径、以及带空格(含引号/代码
21
+ // 围栏)的路径。只匹配 `[A-Za-z]:\\...` 会让「E:/works/a b/report.md」这类
22
+ // 完全合法、且是本机常见输出的路径永远进不了 Inbox。
23
+ const patterns = [
24
+ /"[A-Za-z]:[\\/][^"<>|\r\n]+?\.md"/g,
25
+ /'[A-Za-z]:[\\/][^'<>|\r\n]+?\.md'/g,
26
+ /`[A-Za-z]:[\\/][^`<>|\r\n]+?\.md`/g,
27
+ /[A-Za-z]:[\\/][^\s"'<>|`]+?\.md\b/g,
28
+ ];
29
+ const found = [];
30
+ for (const pattern of patterns) {
31
+ for (const match of text.matchAll(pattern)) {
32
+ found.push(match[0].replace(/^["'`]|["'`]$/g, ''));
33
+ }
34
+ }
35
+ return found.length === 0 ? null : found[found.length - 1];
22
36
  }
23
37
 
24
38
  export function parseDecisionQuestions(markdown) {