@suifei/dsh-ai-team 0.3.98 → 0.4.1

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
@@ -28,8 +28,10 @@ import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
28
28
  import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
29
29
  import { formatRubric, scoreSkillRubric } from './lib/skillopt/rubric.js';
30
30
  import { makeJudge, makeReadPair } from './lib/skillopt/gate-wiring.js';
31
- import { runOptimizeLoop } from './lib/skillopt/optimizer.js';
32
- import { makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
31
+ import { runOptimizeLoop, weakestDimension } from './lib/skillopt/optimizer.js';
32
+ import { hasPairedKeepRecord, makeGenerator, makeResultAppender, makeVcs } from './lib/skillopt/optimize-wiring.js';
33
+ import { listJobs, readJob, writeJob } from './lib/skillopt/jobs.js';
34
+ import { reconcileJobs } from './lib/skillopt/job-runner.js';
33
35
  import { createMemberPermissionGuard } from './lib/host/permission-guard.js';
34
36
  import { installFaultAdapter } from './lib/host/fault-adapter.js';
35
37
  import { buildModelCatalog } from './lib/host/model-catalog.js';
@@ -46,7 +48,7 @@ export const name = 'ai-team';
46
48
  /** The workbench only makes sense where the Web carrier exists. */
47
49
  export const inject = ['webServer', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell'];
48
50
 
49
- const VERSION = '0.3.98';
51
+ const VERSION = '0.4.1';
50
52
  const HUMAN_ID = 'mem_human';
51
53
 
52
54
  const SKILLOPT_BACKENDS = ['mock', 'claude', 'codex', 'copilot', 'cursor', 'pi', 'opencode', 'handoff', 'azure_openai'];
@@ -73,6 +75,28 @@ export const Config = z.object({
73
75
  skilloptJudgeVotes: z.number().step(1).min(3).max(9).default(3),
74
76
  });
75
77
 
78
+ /**
79
+ * 惰性 shell 服务代理:插件注入时机可能早于 shell 服务就绪,注册与 tick 都
80
+ * 必须在调用时现取,避免「boot 时未就绪 → 整条技能链静默跳过」。
81
+ */
82
+ function lazyShellService(ctx) {
83
+ const get = () => {
84
+ const service = ctx.get('shell');
85
+ if (service === undefined || service === null) throw new Error('shell service is not available');
86
+ return service;
87
+ };
88
+ return {
89
+ resolve: (spec) => {
90
+ const service = get();
91
+ return typeof service.resolve === 'function' ? service.resolve(spec) : spec;
92
+ },
93
+ execute: async (spec) => {
94
+ const service = get();
95
+ return typeof service.execute === 'function' ? service.execute(spec) : service.run(spec);
96
+ },
97
+ };
98
+ }
99
+
76
100
  function send(res, body, status = 200) {
77
101
  if (res.writableEnded) return;
78
102
  res.statusCode = status;
@@ -462,7 +486,7 @@ export function apply(ctx, config = {}) {
462
486
  agentPresets: ctx.get('agentPresets'),
463
487
  direct: false,
464
488
  parent: parentInfo.agent,
465
- provider: providers[0],
489
+ provider: (ctx.get('subagents')?.list?.() ?? [])[0],
466
490
  preset: 'standard',
467
491
  cwd,
468
492
  trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
@@ -541,6 +565,35 @@ export function apply(ctx, config = {}) {
541
565
  if (projectRuntime === null || projectRuntime === undefined) return;
542
566
  const state = projectRuntime.service.state;
543
567
  const project = state.projects?.[projectRuntime.id];
568
+ // job 收割先于 pmoAuto 门:Human 启动的优化 job 与 PMO 派发无关,
569
+ // PMO 自动关闭时也必须收敛(否则 job 永远停在 generating)。
570
+ // 两阶段异步优化 job 收割:与任务派发无关,放在停止门之前——
571
+ // Human 启动的 job 必须在任意运行态下收敛(生成/评审/落盘)。
572
+ try {
573
+ const parentInfo = await ensureParent();
574
+ await reconcileJobs({
575
+ ctx,
576
+ projectDir: project.workspacePath || projectRuntime.dir,
577
+ deps: {
578
+ now: () => Date.now(),
579
+ provider: (ctx.get('subagents')?.list?.() ?? [])[0],
580
+ parent: parentInfo?.agent,
581
+ votes: config.skilloptJudgeVotes ?? 3,
582
+ startChild: async (label, spec) => {
583
+ const child = await subagents.startActivation({ ...spec, label });
584
+ return { childId: child.childId, outputStart: child.outputStart ?? null };
585
+ },
586
+ readText: (file) => readFileSync(file, 'utf8'),
587
+ writeText: (file, next) => writeFileSync(file, next, 'utf8'),
588
+ score: (value) => scoreSkillRubric(value, { measured: false }),
589
+ appendResult: makeResultAppender({ projectDir: project.workspacePath || projectRuntime.dir }),
590
+ vcs: await makeVcs({ shell: lazyShellService(ctx), projectDir: project.workspacePath || projectRuntime.dir }),
591
+ diag: (row) => diag.append(row),
592
+ },
593
+ });
594
+ } catch (error) {
595
+ diag.append({ ev: 'skillopt.job.tick.fail', message: error?.message ?? String(error) });
596
+ }
544
597
  if (project === undefined || project.pmoAuto === false || project.status === 'archived') return;
545
598
  // P6 停止门:stopped 项目停止一切派发(补派/心跳/升级/continue 全停),
546
599
  // 正在执行的回合自然完成;唤醒事件 hook 同样检查(见 wakeFromResult)。
@@ -755,18 +808,7 @@ export function apply(ctx, config = {}) {
755
808
  try {
756
809
  // shell 惰性代理:注入时机早于 shell 服务就绪时,注册仍必须完成——
757
810
  // 每次调用现取,避免「boot 时 shell 未就绪 → 整条技能链静默跳过」。
758
- const shellProxy = {
759
- resolve: (spec) => {
760
- const service = ctx.get('shell');
761
- if (service === undefined || service === null) throw new Error('shell service is not available');
762
- return typeof service.resolve === 'function' ? service.resolve(spec) : spec;
763
- },
764
- execute: async (spec) => {
765
- const service = ctx.get('shell');
766
- if (service === undefined || service === null) throw new Error('shell service is not available');
767
- return typeof service.execute === 'function' ? service.execute(spec) : service.run(spec);
768
- },
769
- };
811
+ const shellProxy = lazyShellService(ctx);
770
812
  if (!tools?.register) {
771
813
  diag.append({ ev: 'skillopt.skip.fail', hasToolsRegister: false, hasShell: Boolean(ctx.get('shell')) });
772
814
  console.warn('[ai-team] SkillOpt tools not registered: no tool registry');
@@ -787,7 +829,9 @@ export function apply(ctx, config = {}) {
787
829
  });
788
830
  const adoptGate = createAdoptGate({
789
831
  readPair,
790
- judge,
832
+ // 两阶段异步模式:工具 execute 内无法等待子代理,判据改为
833
+ // results.tsv 中该 skill 已存在 paired keep 记录(同步可查)。
834
+ hasKeepRecord: async ({ projectDir, skillPath }) => hasPairedKeepRecord(projectDir, skillPath),
791
835
  diag: (line, extra) => diag.append({
792
836
  ev: extra?.ev ?? 'skillopt.adoptgate',
793
837
  message: line,
@@ -862,64 +906,79 @@ export function apply(ctx, config = {}) {
862
906
  });
863
907
  // Darwin Phase 2:自动 hill-climbing(诊断→生成→写入→judge→keep/revert)。
864
908
  // 同一轮只改一个维度,版本化走干净 git 仓库,否则 .bak 备份。
909
+ // 两阶段异步:工具只启动生成子代理并写 job,收割由 PMO tick 完成
910
+ // (工具 execute 内无法同步等待一次性子代理——实测 result 永不 settle)。
865
911
  const optimizeTool = tools.register({
866
912
  name: 'skillopt_optimize',
867
- description: 'Run the Darwin hill-climbing loop on one SKILL.md: weakest-dimension diagnosis, generated candidate, paired independent judge, keep/revert, results.tsv.',
913
+ 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.',
868
914
  parameters: {
869
915
  project: { type: 'string', description: 'Project directory' },
870
916
  skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
871
- rounds: { type: 'number', description: 'Max rounds (default 3)' },
872
917
  },
873
918
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
874
919
  async execute(args) {
875
920
  const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
876
921
  const skillPath = typeof args?.skillPath === 'string' && args.skillPath !== '' ? args.skillPath : join(project, 'SKILL.md');
877
922
  if (!existsSync(skillPath)) return `[skillopt optimize] SKILL.md not found: ${skillPath}`;
878
- const rounds = Number.isSafeInteger(args?.rounds) ? Math.max(1, Math.min(5, args.rounds)) : 3;
879
- const vcs = await makeVcs({ shell: shellProxy, projectDir: project });
880
- const result = await runOptimizeLoop({
923
+ const text0 = readFileSync(skillPath, 'utf8');
924
+ const rubric = scoreSkillRubric(text0, { measured: false });
925
+ const dimension = weakestDimension(rubric);
926
+ if (dimension === null) return '[skillopt optimize] rubric produced no scorable dimension';
927
+ const parentInfo = await ensureParent();
928
+ const generator = makeGenerator({
929
+ subagents: ctx.get('subagents'),
930
+ ensureParent: () => ensureParent(),
931
+ providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
932
+ cwd: project,
933
+ diag,
934
+ });
935
+ const jobId = 'job_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
936
+ const child = await generator.start({
881
937
  skillPath,
882
- rounds,
883
- readText: async (path) => readFileSync(path, 'utf8'),
884
- writeText: async (path, text) => writeFileSync(path, text, 'utf8'),
885
- score: (text) => scoreSkillRubric(text, { measured: false }),
886
- generate: makeGenerator({
887
- subagents: ctx.get('subagents'),
888
- ensureParent: () => ensureParent(),
889
- providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
890
- cwd: project,
891
- diag,
892
- }),
893
- judge: async ({ before, after }) => {
894
- const judge = makeJudge({
895
- subagents: ctx.get('subagents'),
896
- ensureParent: () => ensureParent(),
897
- providerName: () => (ctx.get('subagents')?.list?.() ?? [])[0],
898
- votes: config.skilloptJudgeVotes ?? 3,
899
- diag,
900
- });
901
- return judge({ before, after, projectDir: project });
902
- },
903
- vcs,
904
- appendResult: makeResultAppender({ projectDir: project }),
938
+ before: text0,
939
+ dimension,
940
+ round: 1,
941
+ });
942
+ writeJob(project, {
943
+ id: jobId,
944
+ state: 'generating',
945
+ project,
946
+ skillPath,
947
+ skillName: skillPath.split(/[\\/]/).slice(-2, -1)[0] ?? skillPath,
948
+ dimension: `dim${dimension.id}` + ' ' + dimension.name,
949
+ generatorChildId: child.childId,
950
+ outputStart: child.outputStart ?? null,
951
+ parentId: parentInfo?.agent?.id ?? null,
952
+ createdAt: Date.now(),
905
953
  });
906
- diag.append({ ev: 'skillopt.optimize', project, skillPath, status: result.status, rounds: result.rounds.length, finalScore: result.finalScore, vcs: vcs.kind });
907
- const lines = [
908
- `[skillopt optimize] status=${result.status} rounds=${result.rounds.length} finalScore=${result.finalScore ?? '-'} vcs=${vcs.kind}`,
909
- ...(result.rounds ?? []).map((round) => ` r${round.round} ${round.dimension}: ${round.verdict} (${round.better}-${round.worse}) ${round.oldScore}→${round.newScore ?? '-'}${round.kept ? ' kept' : ' reverted'}`),
910
- result.error ? ` error: ${result.error}` : '',
911
- ].filter(Boolean);
912
- return lines.join('\n');
954
+ diag.append({ ev: 'skillopt.job.started', jobId, project, skillPath, dimension: `dim${dimension.id}`, generatorChildId: child.childId });
955
+ return [
956
+ `[skillopt optimize] started job=${jobId} target=dim${dimension.id} ${dimension.name} baseline=${rubric.total}` ,
957
+ ' two-phase async: the PMO tick harvests generator -> judges -> keep/revert and appends results.tsv',
958
+ ' poll with skillopt_jobs',
959
+ ].join('\n');
960
+ },
961
+ });
962
+ const jobsTool = tools.register({
963
+ name: 'skillopt_jobs',
964
+ description: 'List optimize jobs (state, target dimension, verdict) for a project.',
965
+ parameters: { project: { type: 'string', description: 'Project directory' } },
966
+ output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
967
+ async execute(args) {
968
+ const project = typeof args?.project === 'string' && args.project !== '' ? args.project : process.cwd();
969
+ const jobs = listJobs(project);
970
+ if (jobs.length === 0) return '[skillopt jobs] none';
971
+ 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');
913
972
  },
914
973
  });
915
- // 汇总释放:引擎工具 + 三个附加工具(顺序无关,各自 try)。
916
974
  const disposeExtra = () => {
917
975
  try { disposeSkillOpt?.(); } catch { /* already disposed */ }
918
976
  try { rubricTool?.(); } catch { /* noop */ }
919
977
  try { judgeTool?.(); } catch { /* noop */ }
920
978
  try { optimizeTool?.(); } catch { /* noop */ }
979
+ try { jobsTool?.(); } catch { /* noop */ }
921
980
  };
922
- disposeSkillOpt = disposeExtra;
981
+ disposeSkillOpt = disposeExtra;
923
982
  diag.append({ ev: 'skillopt.registered', backend: config.skilloptBackend ?? 'mock', timeoutMs: config.skilloptTimeoutMs ?? 120_000, adoptGate: true, judgeVotes: config.skilloptJudgeVotes ?? 3, optimize: true });
924
983
  }
925
984
  } catch (error) {
@@ -1052,7 +1111,7 @@ export function apply(ctx, config = {}) {
1052
1111
  agentPresets: ctx.get('agentPresets'),
1053
1112
  direct: false,
1054
1113
  parent: parentInfo.agent,
1055
- provider: providers[0],
1114
+ provider: (ctx.get('subagents')?.list?.() ?? [])[0],
1056
1115
  preset: 'standard',
1057
1116
  cwd: effectiveDir,
1058
1117
  trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
@@ -12,12 +12,15 @@
12
12
  /**
13
13
  * @param {object} deps
14
14
  * @param {(projectDir: string) => Promise<{before: string|null, after: string|null, skillPath: string|null}>} deps.readPair
15
- * @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} deps.judge
15
+ * @param {(input: object) => Promise<{verdict:string, better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>} [deps.judge]
16
+ * 同步不可行时(工具 execute 内无法等待子代理)改用 deps.hasKeepRecord。
17
+ * @param {(input:{projectDir:string, skillPath:string|null}) => Promise<boolean>|boolean} [deps.hasKeepRecord]
18
+ * 两阶段异步模式的同步判据:results.tsv 中存在该 skill 的 paired keep 记录。
16
19
  * @param {(line: string, extra?: object) => void} [deps.diag]
17
20
  * @returns {(args: object, exec?: object) => Promise<string|null>} 返回拒绝原因;null = 放行
18
21
  */
19
22
  export function createAdoptGate(deps) {
20
- const { readPair, judge, diag } = deps;
23
+ const { readPair, judge, hasKeepRecord, diag } = deps;
21
24
  return async (args) => {
22
25
  const projectDir = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project : null;
23
26
  if (projectDir === null) return 'adopt gate: project directory is required';
@@ -34,6 +37,21 @@ export function createAdoptGate(deps) {
34
37
  diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
35
38
  return message;
36
39
  }
40
+ // 两阶段异步模式:判据来自已落盘的 paired keep 记录(同步可查)。
41
+ if (typeof hasKeepRecord === 'function') {
42
+ let verified = false;
43
+ try {
44
+ verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null });
45
+ } catch (error) {
46
+ const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
47
+ diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
48
+ return message;
49
+ }
50
+ diag?.('skillopt.adoptgate.decision', { ev: 'skillopt.adoptgate', project: projectDir, source: 'paired-keep-record', verified });
51
+ if (verified) return null;
52
+ return 'adopt gate: no paired keep record for this skill — run the optimize loop to a keep first (unverified adopt is refused)';
53
+ }
54
+ if (typeof judge !== 'function') return 'adopt gate: no verification source configured (unverified adopt is refused)';
37
55
  let result;
38
56
  try {
39
57
  result = await judge({ before: pair.before, after: pair.after, projectDir, skillPath: pair.skillPath ?? null });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 优化 job 的宿主侧收割:每个 PMO tick 调用一次,把状态机的一步动作落到
3
+ * 真实文件/子代理/结果记录上。
4
+ *
5
+ * 与 jobs.js(纯逻辑)分离;本模块只做注入式 I/O,因此测试可用内存实现。
6
+ */
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { extractAssistantText } from './subagent-text.js';
9
+ import { isChildSettled, planJobStep, readJob, writeJob, listJobs } from './jobs.js';
10
+ import { decideByMajority, normalizeVoteCount, parseJudgeOutput, buildPairPrompt, voteFromParsed } from './judge.js';
11
+ import { validateCandidate } from './optimizer.js';
12
+
13
+ /** 观测一个在飞子代理:状态 + 会话事件(同步,供状态机使用)。 */
14
+ export function observeChild(ctx, childId, outputStart) {
15
+ const agent = ctx.get('agents')?.get?.(childId);
16
+ if (agent === undefined || agent === null) return { status: null, events: [] };
17
+ let events = [];
18
+ try {
19
+ events = agent.session?.snapshotEvents?.(outputStart) ?? [];
20
+ } catch { /* session may be gone */ }
21
+ return { status: agent.status ?? null, events, text: extractAssistantText(events) };
22
+ }
23
+
24
+ /**
25
+ * 推进一个 job 一步。
26
+ *
27
+ * @param {object} input
28
+ * @param {object} input.ctx DSH context
29
+ * @param {string} input.projectDir
30
+ * @param {object} input.job job 记录
31
+ * @param {object} input.deps
32
+ * @param {(name:string, spec:object)=>Promise<object>} input.deps.startChild 启动子代理(返回 {childId})
33
+ * @param {(path:string, text:string)=>void} input.deps.writeText
34
+ * @param {(path:string)=>string} input.deps.readText
35
+ * @param {object} input.deps.vcs makeVcs 结果
36
+ * @param {(line:string)=>Promise<void>} input.deps.appendResult
37
+ * @param {(text:string)=>object} input.deps.score
38
+ * @param {() => number} input.deps.now
39
+ * @param {string} input.deps.provider
40
+ * @param {object} input.deps.parent
41
+ * @param {number} [input.deps.votes]
42
+ * @param {(row:object)=>void} [input.deps.diag]
43
+ * @returns {Promise<{job:object, changed:boolean}>}
44
+ */
45
+ export async function stepJob(input) {
46
+ const { ctx, projectDir, deps } = input;
47
+ let job = input.job;
48
+ const children = {};
49
+ for (const childId of [job.generatorChildId, ...(job.judgeChildIds ?? [])].filter(Boolean)) {
50
+ children[childId] = observeChild(ctx, childId, job.outputStart);
51
+ }
52
+ const plan = planJobStep(job, { children, now: deps.now() });
53
+ if (plan.next === job.state && plan.actions.every((action) => action.type === 'await')) {
54
+ return { job, changed: false };
55
+ }
56
+ for (const action of plan.actions) {
57
+ if (action.type === 'fail') {
58
+ await rollback({ deps, job, projectDir });
59
+ job = { ...job, state: 'failed', error: action.payload?.reason ?? 'failed', updatedAt: deps.now() };
60
+ deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: job.error });
61
+ } else if (action.type === 'apply-candidate') {
62
+ // 备份基线 → 写入候选 → 校验(超限时回滚)。
63
+ const before = deps.readText(job.skillPath);
64
+ const validation = validateCandidate({ before, after: action.payload?.text ?? '' });
65
+ if (!validation.ok) {
66
+ await rollback({ deps, job, projectDir });
67
+ job = { ...job, state: 'failed', error: validation.reason, updatedAt: deps.now() };
68
+ deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: validation.reason });
69
+ break;
70
+ }
71
+ job = { ...job, before, candidate: action.payload.text, backup: await deps.vcs.backup(job.skillPath, before) };
72
+ deps.writeText(job.skillPath, action.payload.text);
73
+ } else if (action.type === 'start-judges') {
74
+ const votes = normalizeVoteCount(deps.votes ?? 3);
75
+ const judgeChildIds = [];
76
+ const judgeOrders = [];
77
+ for (let index = 0; index < votes; index++) {
78
+ const order = Math.random() < 0.5 ? 'ab' : 'ba';
79
+ const { prompt } = buildPairPrompt({ before: job.before, after: job.candidate, order });
80
+ const child = await deps.startChild(`skillopt-judge-${job.id}-${index + 1}`, {
81
+ provider: deps.provider,
82
+ request: {
83
+ cwd: projectDir,
84
+ prompt: [{ type: 'text', text: prompt }],
85
+ parent: deps.parent,
86
+ },
87
+ delivery: 'parent',
88
+ signal: new AbortController().signal,
89
+ });
90
+ judgeChildIds.push(child.childId);
91
+ judgeOrders.push({ childId: child.childId, order });
92
+ }
93
+ job = { ...job, state: 'judging', judgeChildIds, judgeOrders, updatedAt: deps.now() };
94
+ } else if (action.type === 'finish') {
95
+ const votes = [];
96
+ for (const row of action.payload?.votes ?? []) {
97
+ const mapping = (job.judgeOrders ?? []).find((entry) => entry.childId === row.childId);
98
+ const parsed = parseJudgeOutput(row.text);
99
+ const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping?.order === 'ba' });
100
+ votes.push({ childId: row.childId, vote, margin: parsed?.margin ?? null, reason: parsed?.reason ?? '' });
101
+ }
102
+ const decision = decideByMajority(votes.map((entry) => entry.vote));
103
+ const kept = decision.verdict === 'keep';
104
+ if (!kept) await rollback({ deps, job, projectDir });
105
+ job = { ...job, state: 'done', decision: { ...decision, votes, kept }, updatedAt: deps.now() };
106
+ const afterText = kept ? job.candidate : job.before;
107
+ const beforeScore = deps.score(job.before)?.total ?? null;
108
+ const afterScore = deps.score(afterText)?.total ?? null;
109
+ await deps.appendResult([
110
+ new Date(deps.now()).toISOString().slice(0, 19),
111
+ deps.vcs.kind === 'git' ? (job.commit ?? '-') : '-',
112
+ job.skillName,
113
+ String(beforeScore ?? '-'),
114
+ String(afterScore ?? '-'),
115
+ kept ? 'keep' : 'revert',
116
+ job.dimension ?? '-',
117
+ `${decision.better}-${decision.worse} ${decision.verdict}`,
118
+ 'paired',
119
+ ].join('\t'));
120
+ deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
121
+ }
122
+ }
123
+ if (plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
124
+ writeJob(projectDir, job);
125
+ return { job, changed: true };
126
+ }
127
+
128
+ async function rollback({ deps, job, projectDir }) {
129
+ if (job?.candidate === undefined || job?.before === undefined) return;
130
+ try {
131
+ if (deps.vcs.kind === 'file' && typeof job.backup === 'string') {
132
+ await deps.vcs.restore(job.skillPath, job.backup);
133
+ } else {
134
+ deps.writeText(job.skillPath, job.before);
135
+ }
136
+ } catch { /* best effort */ }
137
+ }
138
+
139
+ /** 收割全部 pending job(tick 入口)。 */
140
+ export async function reconcileJobs(input) {
141
+ const jobs = listJobs(input.projectDir).filter((job) => job.state === 'generating' || job.state === 'judging');
142
+ const results = [];
143
+ for (const job of jobs) {
144
+ results.push(await stepJob({ ...input, job }));
145
+ }
146
+ return results;
147
+ }
148
+
149
+ export { isChildSettled, readJob, writeJob };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 两阶段异步优化 job(tick 驱动状态机)。
3
+ *
4
+ * 为什么必须两阶段:插件工具**无法在 execute 内同步等待一次性子代理**——
5
+ * `activation.result` 由宿主在子代理回合完成时 resolve,而工具执行本身就在
6
+ * 一个回合内(实测等待 121s 超时、输出为空)。因此:
7
+ *
8
+ * 阶段 1(工具调用):启动生成子代理,写 job 文件,立即返回 started;
9
+ * 阶段 2(PMO tick):每轮检查在飞子代理是否完成 → 取输出 → 校验候选 →
10
+ * 写文件 → 启动 judge 组 → judge 完成 → 多数决 → keep/revert → results.tsv。
11
+ *
12
+ * job 状态:`generating` → `judging` → `done` | `failed`。
13
+ * 全部为纯逻辑 + 注入式 I/O,便于在测试里用内存文件系统驱动任意 tick 序列。
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+
18
+ export const JOB_STATES = Object.freeze(['generating', 'judging', 'done', 'failed']);
19
+ const JOB_TTL_MS = 30 * 60 * 1000;
20
+
21
+ /** job 目录(项目内,随 .skillopt-sleep 一起被忽略/清理)。 */
22
+ export function jobsDir(projectDir) {
23
+ return join(projectDir, '.skillopt-sleep', 'jobs');
24
+ }
25
+
26
+ /** 读取一个 job 文件(损坏视为不存在)。 */
27
+ export function readJob(projectDir, jobId) {
28
+ try {
29
+ return JSON.parse(readFileSync(join(jobsDir(projectDir), `${jobId}.json`), 'utf8'));
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /** 列出全部 job(按创建时间升序)。 */
36
+ export function listJobs(projectDir) {
37
+ const dir = jobsDir(projectDir);
38
+ if (!existsSync(dir)) return [];
39
+ const jobs = [];
40
+ for (const name of readdirSync(dir)) {
41
+ if (!name.endsWith('.json')) continue;
42
+ try {
43
+ jobs.push(JSON.parse(readFileSync(join(dir, name), 'utf8')));
44
+ } catch { /* skip corrupt */ }
45
+ }
46
+ return jobs.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
47
+ }
48
+
49
+ /** 写入 job(原子性靠单写者约定;插件 tick 单线程)。 */
50
+ export function writeJob(projectDir, job) {
51
+ const dir = jobsDir(projectDir);
52
+ mkdirSync(dir, { recursive: true });
53
+ writeFileSync(join(dir, `${job.id}.json`), JSON.stringify(job, null, 2), 'utf8');
54
+ return job;
55
+ }
56
+
57
+ /** 删除 job 文件(done/failed 的收尾清理)。 */
58
+ export function removeJob(projectDir, jobId) {
59
+ try { unlinkSync(join(jobsDir(projectDir), `${jobId}.json`)); } catch { /* already gone */ }
60
+ }
61
+
62
+ /**
63
+ * 判定在飞子代理是否已完成。
64
+ * @param {{status?: string, events?: Array}} observation 宿主观测(agent.status + 会话事件)
65
+ * @returns {boolean}
66
+ */
67
+ export function isChildSettled(observation) {
68
+ const events = Array.isArray(observation?.events) ? observation.events : [];
69
+ if (events.some((event) => event?.type === 'subagent/end' || event?.type === 'session/end')) return true;
70
+ // 一次性子代理完成后 agent 回到 idle;无 agent(已释放)同样视为结束。
71
+ return observation?.status === 'idle' || observation?.status === null || observation?.status === undefined && events.length > 0;
72
+ }
73
+
74
+ /** job 是否超时(TTL)。 */
75
+ export function isJobExpired(job, nowMs, ttlMs = JOB_TTL_MS) {
76
+ return typeof job?.createdAt === 'number' && nowMs - job.createdAt > ttlMs;
77
+ }
78
+
79
+ /**
80
+ * 状态机的一步决策(纯函数):
81
+ * @param {object} job 当前 job
82
+ * @param {{children: Record<string, {status?:string, events?:Array}>, now: number}} observation
83
+ * @returns {{next: string, actions: Array<{type:string, payload?:object}>, reason?: string}}
84
+ * actions.type: 'finish-keep'|'finish-revert'|'fail'|'start-judges'|'apply-candidate'|'await'
85
+ */
86
+ export function planJobStep(job, observation) {
87
+ const state = job?.state;
88
+ if (state === 'done' || state === 'failed') return { next: state, actions: [], reason: 'terminal' };
89
+ if (isJobExpired(job, observation.now)) {
90
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'job timeout' } }], reason: 'timeout' };
91
+ }
92
+ if (state === 'generating') {
93
+ const child = observation.children?.[job.generatorChildId];
94
+ if (!isChildSettled(child)) return { next: state, actions: [{ type: 'await' }], reason: 'generator running' };
95
+ const text = typeof child?.text === 'string' ? child.text : '';
96
+ if (text.trim() === '') {
97
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'generator returned an empty candidate' } }], reason: 'empty candidate' };
98
+ }
99
+ return { next: 'judging', actions: [{ type: 'apply-candidate', payload: { text } }, { type: 'start-judges' }], reason: 'generator settled' };
100
+ }
101
+ if (state === 'judging') {
102
+ const votes = [];
103
+ let allSettled = true;
104
+ for (const childId of job.judgeChildIds ?? []) {
105
+ const child = observation.children?.[childId];
106
+ if (!isChildSettled(child)) { allSettled = false; continue; }
107
+ votes.push({ childId, text: typeof child?.text === 'string' ? child.text : '' });
108
+ }
109
+ if (!allSettled) return { next: state, actions: [{ type: 'await' }], reason: 'judges running' };
110
+ return { next: 'done', actions: [{ type: 'finish', payload: { votes } }], reason: 'judges settled' };
111
+ }
112
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: `unknown state ${String(state)}` } }], reason: 'unknown state' };
113
+ }
@@ -59,9 +59,13 @@ export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
59
59
  };
60
60
  }
61
61
 
62
- /** 独立生成器:一次性子代理按 rubric 短板改进,只输出完整新文件。 */
63
- export function makeGenerator({ subagents, ensureParent, providerName, cwd, diag }) {
64
- return async ({ skillPath, before, dimension, round }) => {
62
+
63
+ export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
64
+ /**
65
+ * 启动生成子代理(两阶段:只启动,不等待)。返回 { childId, outputStart };
66
+ * 输出由 PMO tick 从会话事件里收割(工具 execute 内无法同步等待)。
67
+ */
68
+ const start = async ({ before, dimension, round }) => {
65
69
  const parentInfo = await ensureParent();
66
70
  const provider = providerName();
67
71
  const prompt = [
@@ -81,18 +85,26 @@ export function makeGenerator({ subagents, ensureParent, providerName, cwd, diag
81
85
  delivery: 'parent',
82
86
  signal: new AbortController().signal,
83
87
  });
84
- // 探针(ev 以 .fail 结尾以便在 errors 级 diag 中可见)。
85
- diag?.append?.({ ev: 'skillopt.generate.probe.fail', kind: activation?.kind ?? null, hasHandle: Boolean(activation?.handle), hasAgent: Boolean(activation?.handle?.agent), hasSnapshot: typeof activation?.handle?.agent?.session?.snapshotEvents === 'function', outputStart: typeof activation?.outputStart, keys: Object.keys(activation ?? {}).join(',') });
86
- try {
87
- const raw = await awaitActivationText(activation);
88
- diag?.append?.({ ev: 'skillopt.generate.text.fail', chars: raw.length, preview: raw.slice(0, 160) });
89
- // 去掉可能包裹的 ```markdown 围栏。
90
- const fenced = raw.match(/```(?:markdown|md)?\s*\n([\s\S]*?)\n```/);
91
- return fenced !== null ? fenced[1] : raw.trim();
92
- } finally {
93
- try { await activation?.dispose?.(); } catch { /* already gone */ }
94
- }
88
+ return { childId: activation.childId, outputStart: activation.outputStart ?? null };
95
89
  };
90
+ return { start };
91
+ }
92
+
93
+ /**
94
+ * 同步判据:results.tsv 中该 skill 的**最后一条**记录是否为 paired keep。
95
+ * adopt 门在工具 execute 内无法等待子代理,因此以已落盘的 judge 结论为准。
96
+ */
97
+ export function hasPairedKeepRecord(projectDir, skillPath) {
98
+ const name = typeof skillPath === 'string' && skillPath !== ''
99
+ ? skillPath.split(/[\\/]/).slice(-2, -1)[0]
100
+ : null;
101
+ const file = join(projectDir, '.skillopt-sleep', 'results.tsv');
102
+ if (!existsSync(file)) return false;
103
+ const lines = readFileSync(file, 'utf8').trim().split(/\r?\n/).slice(1);
104
+ const rows = lines.map((line) => line.split('\t')).filter((cells) => name === null || cells[2] === name);
105
+ const last = rows.at(-1);
106
+ if (last === undefined) return false;
107
+ return last[5] === 'keep' && last[8] === 'paired';
96
108
  }
97
109
 
98
110
  /** results.tsv 追加(表头自动补)。 */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.3.98",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",