@suifei/dsh-ai-team 0.4.23 → 0.4.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -18,6 +18,7 @@ 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.23';
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),
@@ -406,6 +450,25 @@ export function apply(ctx, config = {}) {
406
450
  : () => {};
407
451
  const offSessionEvent = typeof ctx.on === 'function'
408
452
  ? ctx.on('session/event', async (session, event) => {
453
+ // 成员输出探针:直接观察成员回合产出了什么(判定「成员是否真的在
454
+ // 工作 / 是否调用工具」的唯一插件侧可见通道)。
455
+ try {
456
+ if (booted !== null && event?.type === 'assistant/message' && runtimeForAgent(session?.id) !== null) {
457
+ const content = event?.data?.message?.content ?? [];
458
+ const text = (Array.isArray(content) ? content : [])
459
+ .map((block) => (typeof block === 'string' ? block : block?.text ?? ``))
460
+ .filter(Boolean)
461
+ .join('\n');
462
+ diag.append({
463
+ ev: 'member.output.probe',
464
+ sessionId: session?.id ?? null,
465
+ chars: text.length,
466
+ preview: text.slice(0, 240),
467
+ });
468
+ }
469
+ } catch (probeError) {
470
+ diag.append({ ev: 'member.output.probe.fail', error: probeError?.message ?? String(probeError) });
471
+ }
409
472
  if (booted === null || event?.type !== 'turn/end') return;
410
473
  const eventRuntime = runtimeForAgent(session?.id);
411
474
  const member = eventRuntime === null ? undefined : Object.values(eventRuntime.service.state.members ?? {})
@@ -421,12 +484,28 @@ export function apply(ctx, config = {}) {
421
484
  diag.append({ ev: 'session.flush.fail', sessionId: session?.id ?? null, message: error?.message ?? String(error) });
422
485
  console.warn('[ai-team] member session flush failed:', error?.message ?? error);
423
486
  }
424
- 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
+ }
425
503
  if (member.lastFailure === undefined || member.lastFailure === null) return;
426
504
  try {
427
505
  await eventRuntime.service.recordMemberRecovery(member.id, member.attempts ?? 0, member.config ?? null, eventRuntime.id);
428
506
  broadcast(undefined, eventRuntime);
429
507
  } catch (error) {
508
+ diag.append({ ev: 'member.recovery.fail', memberId: member.id, message: error?.message ?? String(error) });
430
509
  console.warn('[ai-team] member recovery record failed:', member.id, error?.message ?? error);
431
510
  }
432
511
  })
@@ -438,6 +517,9 @@ export function apply(ctx, config = {}) {
438
517
  let host = null;
439
518
  let hostPromise = null;
440
519
  const wakeKeys = new Map();
520
+ // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
521
+ // 造成 autoAnswerDecisions/reconcileJobs 并发执行同一条账本。按 Project 去重。
522
+ const pmoBusy = new Set();
441
523
  const activationTasks = new Map();
442
524
  const pmoLastKick = new Map();
443
525
  const pmoLastStall = new Map();
@@ -462,7 +544,7 @@ export function apply(ctx, config = {}) {
462
544
  // 驱动,不断 Human 通道。
463
545
  const gateProject = projectRuntime.service.state.projects?.[projectRuntime.id];
464
546
  if (gateProject !== undefined && gateProject.runState === 'stopped' && actor?.kind !== 'human') return;
465
- const plans = planWakes(projectRuntime.service.state, result, actor);
547
+ const plans = planWakes(projectRuntime.service.state, result, actor, { projectId: projectRuntime.id });
466
548
  if (plans.length === 0) return;
467
549
  // Window eviction: a key older than this horizon can no longer dedupe
468
550
  // a relevant event, so drop it instead of growing the Map forever.
@@ -486,16 +568,18 @@ export function apply(ctx, config = {}) {
486
568
  if (wakeKeys.has(plan.key)) continue;
487
569
  let member = projectRuntime.service.state.members?.[plan.memberId];
488
570
  if (member === undefined) continue;
489
- // Reserve before the async delivery: the HTTP result and the ledger
490
- // event both schedule the same plan, and only one may deliver it.
491
- wakeKeys.set(plan.key, result?.event?.seq ?? head);
492
571
  // 无工作目录的项目不 wake(与 activate 的 fail-closed 同一不变量):
493
572
  // 冷恢复/直连唤醒都会在会话原 cwd 里干活,不该落到插件数据目录。
573
+ // 必须在占用去重键**之前**判定:这些键多数不带时间桶,跳过时若已占用,
574
+ // 同一事件(startup/thread/reflection)之后再也不会被重新规划。
494
575
  const projectWorkspacePath = projectWorkspace(projectRuntime, member);
495
576
  if (projectWorkspacePath === null || projectWorkspacePath.trim?.() === '') {
496
577
  diag?.append({ ev: 'wake.skip', projectId: projectRuntime.id, memberId: plan.memberId, reason: 'E_WORKSPACE_REQUIRED' });
497
578
  continue;
498
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);
499
583
  const cwd = projectWorkspacePath;
500
584
  try {
501
585
  // Idle default members have no Agent session yet. A wake must
@@ -578,7 +662,14 @@ export function apply(ctx, config = {}) {
578
662
  sessionIdType: typeof targetMember?.sessionId,
579
663
  failureText: failureText.slice(0, 160),
580
664
  });
581
- 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
582
673
  && typeof targetMember?.sessionId === 'string' && targetMember.sessionId !== '';
583
674
  diag.append({
584
675
  ev: 'wake.catch.probe.fail',
@@ -624,6 +715,9 @@ export function apply(ctx, config = {}) {
624
715
  };
625
716
  const pmoTick = async (projectRuntime) => {
626
717
  if (projectRuntime === null || projectRuntime === undefined) return;
718
+ // 归档修复重试点:boot 时 workspaceRegistry 往往还没 active,等 tick
719
+ // (60s 后)再试一次;修好即置位,之后每个 tick 直接返回。
720
+ await repairArchivedHosts();
627
721
  const state = projectRuntime.service.state;
628
722
  const project = state.projects?.[projectRuntime.id];
629
723
  // job 收割先于 pmoAuto 门:Human 启动的优化 job 与 PMO 派发无关,
@@ -644,7 +738,9 @@ export function apply(ctx, config = {}) {
644
738
  ensureParent: () => ensureParent(),
645
739
  votes: config.skilloptJudgeVotes ?? 3,
646
740
  startChild: async (label, spec) => {
647
- const child = await subagents.startActivation({ ...spec, label });
741
+ // 必须走 serviceOf:这里不在 activateMember/wakeFromResult 的
742
+ // 词法作用域内,裸写 subagents 会在判官轮抛 ReferenceError。
743
+ const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
648
744
  return { childId: child.childId, outputStart: child.outputStart ?? null };
649
745
  },
650
746
  readText: (file) => readFileSync(file, 'utf8'),
@@ -895,17 +991,26 @@ export function apply(ctx, config = {}) {
895
991
  readPair,
896
992
  // 两阶段异步模式:工具 execute 内无法等待子代理,判据改为
897
993
  // results.tsv 中该 skill 已存在 paired keep 记录(同步可查)。
898
- hasKeepRecord: async ({ projectDir, skillPath }) => hasPairedKeepRecord(projectDir, skillPath),
994
+ hasKeepRecord: async ({ projectDir, skillPath, candidate }) => hasPairedKeepRecord(projectDir, skillPath, candidate),
899
995
  diag: (line, extra) => diag.append({
900
996
  ev: extra?.ev ?? 'skillopt.adoptgate',
901
997
  message: line,
902
998
  ...(extra?.project === undefined ? {} : { project: extra.project }),
903
999
  }),
904
1000
  });
1001
+ // 授权门:这批工具是全局注册的,但 adopt/schedule 会改 live 文件与系统
1002
+ // cron。只允许 Team 成员与 Human 面对的根会话;一次性子代理一律拒绝。
1003
+ const skilloptCallerAllowed = (exec) => {
1004
+ const agentId = exec?.agent?.id;
1005
+ if (typeof agentId !== 'string' || agentId === '') return false;
1006
+ if (runtimeForAgent(agentId) !== null) return true;
1007
+ return exec?.agent?.session?.header?.origin !== 'subagent';
1008
+ };
1009
+ const guardedTools = wrapToolsWithSkilloptAccess(tools, skilloptCallerAllowed);
905
1010
  // Backend/timeout come from the plugin Config (patch layer), so an
906
1011
  // operator can move the skillopt_* tools off the safe mock default.
907
1012
  disposeSkillOpt = applySkillOpt({
908
- tools: wrapToolsWithAdoptGate(tools, adoptGate),
1013
+ tools: wrapToolsWithAdoptGate(guardedTools, adoptGate),
909
1014
  shell: shellProxy,
910
1015
  logger: console,
911
1016
  }, {
@@ -914,7 +1019,7 @@ export function apply(ctx, config = {}) {
914
1019
  timeoutMs: config.skilloptTimeoutMs ?? 120_000,
915
1020
  }) ?? (() => {});
916
1021
  // 9 维 rubric(triage)与独立 judge(keep/revert)作为新工具暴露。
917
- const rubricTool = tools.register({
1022
+ const rubricTool = guardedTools.register({
918
1023
  name: 'skillopt_rubric',
919
1024
  description: 'Score a SKILL.md against the 9-dimension Darwin rubric (triage only — absolute scores must not be used for keep/revert).',
920
1025
  parameters: {
@@ -939,7 +1044,7 @@ export function apply(ctx, config = {}) {
939
1044
  return formatRubric(result);
940
1045
  },
941
1046
  });
942
- const judgeTool = tools.register({
1047
+ const judgeTool = guardedTools.register({
943
1048
  name: 'skillopt_judge',
944
1049
  description: 'Paired independent-judge verdict (N odd votes, majority) for before/after SKILL.md — the authoritative keep/revert signal.',
945
1050
  parameters: {
@@ -972,7 +1077,7 @@ export function apply(ctx, config = {}) {
972
1077
  // 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
973
1078
  // 两阶段异步:工具只启动生成子代理并写 job,收割由 PMO tick 完成
974
1079
  // (工具 execute 内无法同步等待一次性子代理——实测 result 永不 settle)。
975
- const optimizeTool = tools.register({
1080
+ const optimizeTool = guardedTools.register({
976
1081
  name: 'skillopt_optimize',
977
1082
  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.',
978
1083
  parameters: {
@@ -1058,7 +1163,7 @@ export function apply(ctx, config = {}) {
1058
1163
  ].join('\n');
1059
1164
  },
1060
1165
  });
1061
- const jobsTool = tools.register({
1166
+ const jobsTool = guardedTools.register({
1062
1167
  name: 'skillopt_jobs',
1063
1168
  description: 'List optimize jobs (state, target dimension, verdict) for a project.',
1064
1169
  parameters: { project: { type: 'string', description: 'Project directory' } },
@@ -1108,15 +1213,42 @@ export function apply(ctx, config = {}) {
1108
1213
  const collected = collectReview({ service: runtime.service, job });
1109
1214
  const expected = collected.expected ?? job.reviewOrders?.length ?? 3;
1110
1215
  if (collected.votes.length < expected) {
1216
+ // 评审通道被 reconcileJobs 明确排除,没有 TTL 兜底:评审官不回帖
1217
+ // 时 job 会永久停在 judging、评审卡永久 active。这里补超时终态。
1218
+ if (isJobExpired(job, Date.now(), REVIEW_JOB_TTL_MS)) {
1219
+ writeJob(job.project, {
1220
+ ...job,
1221
+ state: 'failed',
1222
+ error: `review timed out after ${Math.round(REVIEW_JOB_TTL_MS / 60000)}min (${collected.votes.length}/${expected} votes)`,
1223
+ updatedAt: Date.now(),
1224
+ });
1225
+ diag.append({ ev: 'skillopt.job.timeout', jobId: job.id, got: collected.votes.length, expected });
1226
+ continue;
1227
+ }
1111
1228
  diag.append({ ev: 'skillopt.review.waiting', jobId: job.id, got: collected.votes.length, expected });
1112
1229
  continue;
1113
1230
  }
1114
1231
  const kept = collected.decision.verdict === 'keep';
1232
+ const jobDir = job.project;
1233
+ // 落盘前先确认 live 仍是评审时的基线:评审期间的人工修改不能被
1234
+ // 一次 revert 用陈旧快照覆盖(反之亦然)。
1235
+ let liveText = null;
1236
+ try { liveText = existsSync(job.skillPath) ? readFileSync(job.skillPath, 'utf8') : null; } catch { liveText = null; }
1237
+ if (liveText !== null && typeof job.before === 'string' && sha12(liveText) !== sha12(job.before)) {
1238
+ writeJob(jobDir, { ...job, state: 'failed', error: 'live SKILL.md changed during review (conflict)', updatedAt: Date.now() });
1239
+ diag.append({ ev: 'skillopt.job.conflict', jobId: job.id, skillPath: job.skillPath });
1240
+ continue;
1241
+ }
1242
+ let backupPath = null;
1243
+ try {
1244
+ backupPath = backupLive({ projectDir: jobDir, skillPath: job.skillPath, text: liveText ?? job.before ?? '' });
1245
+ } catch (error) {
1246
+ diag.append({ ev: 'skillopt.job.backup.fail', jobId: job.id, message: error?.message ?? String(error) });
1247
+ }
1115
1248
  // keep → 落盘候选;revert → 恢复基线(评审卡收票后才动文件)。
1116
- writeFileSync(job.skillPath, kept ? job.candidate : job.before, 'utf8');
1249
+ applyLiveAtomically(job.skillPath, kept ? job.candidate : job.before);
1117
1250
  const beforeScore = scoreSkillRubric(job.before, { measured: false })?.total ?? null;
1118
1251
  const afterScore = scoreSkillRubric(kept ? job.candidate : job.before, { measured: false })?.total ?? null;
1119
- const jobDir = job.project;
1120
1252
  const appender = makeResultAppender({ projectDir: jobDir });
1121
1253
  await appender([
1122
1254
  new Date().toISOString().slice(0, 19),
@@ -1128,22 +1260,45 @@ export function apply(ctx, config = {}) {
1128
1260
  job.dimension ?? '-',
1129
1261
  `${collected.decision.better}-${collected.decision.worse} ${collected.decision.verdict}` ,
1130
1262
  'paired',
1263
+ sha12(job.candidate),
1131
1264
  ].join('\t'));
1132
- writeJob(jobDir, { ...job, state: 'done', decision: collected.decision, updatedAt: Date.now() });
1265
+ writeJob(jobDir, { ...job, state: 'done', decision: collected.decision, backup: backupPath ?? job.backup ?? null, updatedAt: Date.now() });
1266
+ // 评审卡必须收口:否则它保持 pending 进入 PMO 的 active 集合,
1267
+ // 会被 heartbeat/stall/escalate 反复唤醒评审官(每 job 永久留一张卡)。
1268
+ try {
1269
+ const card = runtime.service.state.tasks?.[job.reviewTaskId];
1270
+ if (card !== undefined && card.status !== 'done' && card.status !== 'cancelled' && card.tombstone !== true) {
1271
+ await runtime.service.dispatch({
1272
+ type: 'task.cancel',
1273
+ payload: {
1274
+ taskId: job.reviewTaskId,
1275
+ expectedRevision: card.revision,
1276
+ reason: `blind review collected: ${collected.decision.verdict}`,
1277
+ },
1278
+ actor,
1279
+ projectId: runtime.id,
1280
+ });
1281
+ }
1282
+ } catch (error) {
1283
+ diag.append({ ev: 'skillopt.review.card.close.fail', jobId: job.id, taskId: job.reviewTaskId, message: error?.message ?? String(error) });
1284
+ }
1133
1285
  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' });
1134
1286
  }
1135
1287
  if (jobs.length === 0) return '[skillopt jobs] none';
1136
1288
  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');
1137
1289
  },
1138
1290
  });
1291
+ // 先保存 applySkillOpt 的真实 disposer:直接把 disposeSkillOpt 指向
1292
+ // disposeExtra 会形成自引用递归(teardown 时栈溢出且原始 disposer 永不可达)。
1293
+ const innerSkillOptDispose = disposeSkillOpt;
1139
1294
  const disposeExtra = () => {
1140
- try { disposeSkillOpt?.(); } catch { /* already disposed */ }
1295
+ try { innerSkillOptDispose?.(); } catch { /* already disposed */ }
1141
1296
  try { rubricTool?.(); } catch { /* noop */ }
1142
1297
  try { judgeTool?.(); } catch { /* noop */ }
1143
1298
  try { optimizeTool?.(); } catch { /* noop */ }
1144
1299
  try { jobsTool?.(); } catch { /* noop */ }
1145
1300
  };
1146
- disposeSkillOpt = disposeExtra;
1301
+ disposeSkillOpt = disposeExtra;
1147
1302
  diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
1148
1303
  }
1149
1304
  } catch (error) {
@@ -1163,7 +1318,13 @@ export function apply(ctx, config = {}) {
1163
1318
  return runtime.service.dispatch(command);
1164
1319
  },
1165
1320
  }), {
1166
- when: (activation) => runtimeForAgent(activation?.agent?.id) !== null,
1321
+ // 可见性判定不能按「请求者是已知成员」来算:
1322
+ // * 成员的首个 model step 发生在 bindMemberSession 写入 sessionId 之前
1323
+ // (activate() 返回后才写),此时 runtimeForAgent(请求者) 为 null,
1324
+ // 实测首个 header 43 个工具、第二个起 44 个,差集恰好是 team;
1325
+ // * owner/宿主永远不是成员,按此判定它也拿不到 team。
1326
+ // 因此只要本进程内 AI Team runtime 已 boot,团队板工具即对 agent 可见。
1327
+ when: () => booted !== null,
1167
1328
  })
1168
1329
  : () => {};
1169
1330
  } catch (error) {
@@ -1171,8 +1332,48 @@ export function apply(ctx, config = {}) {
1171
1332
  console.warn('[ai-team] team tool registration failed:', error?.message ?? error);
1172
1333
  }
1173
1334
 
1335
+ // 历史归档修复:成员是 host 的子会话,`archived-session-gate` 会沿 subagent
1336
+ // 血缘上溯,父会话被归档即拒绝整条血缘 —— 回合以 {kind:'blocked'} 结束且不发
1337
+ // 模型请求(实测 453 blocked / 0 completed)。旧版本把 host 归档用于隐藏会话。
1338
+ let hostRepaired = false;
1339
+ let hostRepairWarned = false;
1340
+ const repairArchivedHosts = async () => {
1341
+ if (hostRepaired) return;
1342
+ try {
1343
+ const registry = serviceOf(ctx, 'workspaceRegistry');
1344
+ const repaired = await repairHostSessions({
1345
+ runtimes: booted?.runtimes?.values() ?? [],
1346
+ sessions: serviceOf(ctx, 'sessions'),
1347
+ workspaceRegistry: registry,
1348
+ diag,
1349
+ });
1350
+ // null = workspaceRegistry 尚未 active(它要等 sessionPersistence 与
1351
+ // 历史 bootstrap)。保持未修复状态,交给下一次 tick/ensureParent 重试;
1352
+ // 否则一次早跑就永久放弃,正是上一版静默失效的原因。
1353
+ if (repaired === null) {
1354
+ if (!hostRepairWarned) {
1355
+ hostRepairWarned = true;
1356
+ let keys = [];
1357
+ try { keys = registry === null || registry === undefined ? [] : Object.keys(registry).slice(0, 8); } catch { keys = ['<unreadable>']; }
1358
+ diag.append({
1359
+ ev: 'host.repair.deferred.fail',
1360
+ reason: 'workspaceRegistry not ready',
1361
+ registryType: typeof registry,
1362
+ hasUnarchive: typeof registry?.unarchiveSession,
1363
+ keys,
1364
+ });
1365
+ }
1366
+ return;
1367
+ }
1368
+ hostRepaired = true;
1369
+ } catch (error) {
1370
+ hostRepaired = true;
1371
+ diag.append({ ev: 'host.unarchive.sweep.fail', error: error?.message ?? String(error) });
1372
+ }
1373
+ };
1174
1374
  const ensureParent = async () => {
1175
1375
  if (host !== null) return host;
1376
+ await repairArchivedHosts();
1176
1377
  if (hostPromise === null) {
1177
1378
  const existingHost = [...(booted?.runtimes?.values() ?? [])]
1178
1379
  .map((runtime) => runtime.service.state.hostSessionId)
@@ -1916,6 +2117,30 @@ export function apply(ctx, config = {}) {
1916
2117
  projectId: runtime.id,
1917
2118
  correlationId: typeof body.correlationId === 'string' ? body.correlationId : undefined,
1918
2119
  });
2120
+ // 归档必须同时落到全局 registry:否则 bootstrap 仍报 archived:false,
2121
+ // 项目留在树上,且「最后一个 active 项目」保护对后续归档永远失效。
2122
+ if (body.type === 'project.archive' && body.payload?.archived !== false) {
2123
+ try {
2124
+ booted.registry.setArchived(runtime.id, true);
2125
+ } catch (error) {
2126
+ diag.append({ ev: 'project.archive.registry.fail', projectId: runtime.id, message: error?.message ?? String(error) });
2127
+ }
2128
+ }
2129
+ // 退役/离队后必须释放常驻子代理:否则 activation 句柄只在 force
2130
+ // 重建或插件卸载时才回收,退役成员的会话会一直挂在进程里。
2131
+ if (body.type === 'member.retire' || body.type === 'member.leave') {
2132
+ const retiredId = body.payload?.memberId;
2133
+ const retired = runtime.service.state.members?.[retiredId];
2134
+ const retiredSession = retired?.sessionId;
2135
+ if (typeof retiredSession === 'string') {
2136
+ const activation = activations.get(retiredSession);
2137
+ if (activation !== undefined) {
2138
+ activations.delete(retiredSession);
2139
+ try { await activation.dispose?.(); } catch { /* already gone */ }
2140
+ diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2141
+ }
2142
+ }
2143
+ }
1919
2144
  send(res, { ok: true, ...result });
1920
2145
  void wakeFromResult(runtime, result, { agentId: HUMAN_ID }).catch((error) => {
1921
2146
  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) {
@@ -1,11 +1,13 @@
1
1
  /**
2
- * The member-facing Team tool. It is registered globally but only becomes
3
- * visible to a session that is a live Team member (`when` checks the ledger).
2
+ * The member-facing Team tool. It is registered globally and becomes visible
3
+ * once the AI Team runtime booted (see index.js `when`); the tool itself still
4
+ * refuses any session that is not a live Team member (`E_NOT_MEMBER`).
4
5
  *
5
6
  * Mutations require `expectedRevision` (Task CAS) and `baseSeq` (Thread stale
6
7
  * reply protection); errors are returned as data so the member can re-read.
7
8
  */
8
9
  import { taskCard } from './views.js';
10
+ import { isQaMember } from '../domain/member-profile.js';
9
11
 
10
12
  const ACTIONS = ['tasks', 'members', 'inbox', 'recall', 'create', 'askHuman', 'member', 'evolve', 'distill', 'note', 'skill', 'claim', 'submit', 'thread', 'reply', 'accept', 'requestChanges'];
11
13
 
@@ -138,7 +140,7 @@ export function createTeamTool(options) {
138
140
  name: candidate.name,
139
141
  role: candidate.role,
140
142
  status: candidate.status,
141
- qa: /验收|qa|quality|test|verification/i.test(candidate.role ?? ''),
143
+ qa: isQaMember(candidate),
142
144
  }));
143
145
  return { ok: true, projectId: pid, members };
144
146
  }
@@ -242,7 +244,7 @@ export function createTeamTool(options) {
242
244
  ...(args.qaRequired === true ? { qaRequired: true } : {}),
243
245
  ...(Array.isArray(args.qaChecklist) ? { qaChecklist: args.qaChecklist } : {}),
244
246
  });
245
- return { ok: true, task: taskCard(options.getState(), result.task) };
247
+ return { ok: true, task: taskCard(options.getState(exec), result.task) };
246
248
  }
247
249
  if (args.action === 'askHuman') {
248
250
  if (!Array.isArray(args.questions) || args.questions.length === 0) {
@@ -280,7 +282,7 @@ export function createTeamTool(options) {
280
282
  }
281
283
  const type = args.action === 'requestChanges' ? 'task.request_changes' : `task.${args.action}`;
282
284
  const result = await command(type, payload);
283
- return { ok: true, task: taskCard(options.getState(), result.task), event: result.event?.type ?? null };
285
+ return { ok: true, task: taskCard(options.getState(exec), result.task), event: result.event?.type ?? null };
284
286
  }
285
287
  if (args.action === 'thread') {
286
288
  if (typeof args.taskId !== 'string') return failure({ code: 'E_INVALID_ARGUMENT', message: 'taskId is required' });
@@ -61,6 +61,19 @@ export class ProjectRegistry {
61
61
  this.save();
62
62
  }
63
63
 
64
+ /** Mirror a Project's archive flag into the global index (ledger stays the source of truth). */
65
+ setArchived(id, archived) {
66
+ const project = this.projects.find((entry) => entry.id === id);
67
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
68
+ project.archived = archived === true;
69
+ if (archived === true && this.activeProjectId === id) {
70
+ const fallback = this.projects.find((entry) => entry.id !== id && entry.archived !== true);
71
+ if (fallback !== undefined) this.activeProjectId = fallback.id;
72
+ }
73
+ this.save();
74
+ return project;
75
+ }
76
+
64
77
  save() {
65
78
  const file = join(this.rootDir, 'projects.json');
66
79
  const temp = `${file}.tmp`;