@suifei/dsh-ai-team 0.4.145 → 0.4.146

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 (39) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -21
  3. package/README.md +19 -1
  4. package/client.js +118 -17
  5. package/cordis.patch.yml +31 -31
  6. package/icon.svg +12 -12
  7. package/index.js +7 -1
  8. package/lib/domain/ids.js +26 -26
  9. package/lib/domain/inbox.js +93 -93
  10. package/lib/domain/member-config.js +168 -168
  11. package/lib/host/decision-report.js +72 -72
  12. package/lib/host/default-workspace.js +69 -69
  13. package/lib/host/fault-adapter.js +50 -50
  14. package/lib/host/people-view.js +9 -2
  15. package/lib/host/permission-guard.js +61 -61
  16. package/lib/host/project-registry.js +104 -104
  17. package/lib/host/risk-view.js +99 -99
  18. package/lib/host/weekly-view.js +86 -86
  19. package/lib/host/workspace-path.js +94 -94
  20. package/lib/ledger/checkpoint.js +415 -415
  21. package/lib/ledger/events.js +398 -398
  22. package/lib/ledger/namespace.js +124 -124
  23. package/lib/ledger/tools.js +118 -118
  24. package/lib/ledger/writer.js +1266 -1266
  25. package/lib/runtime/error-chain.js +31 -31
  26. package/lib/runtime/shell-guard.js +102 -102
  27. package/lib/runtime/skill-catalog.js +41 -41
  28. package/lib/runtime/skill-policy.js +12 -12
  29. package/lib/skillopt/adopt-gate.js +108 -108
  30. package/lib/skillopt/gate-wiring.js +146 -146
  31. package/lib/skillopt/jobs.js +135 -135
  32. package/lib/skillopt/proposal-store.js +33 -33
  33. package/lib/skillopt/review-runner.js +107 -107
  34. package/lib/skillopt/rubric.js +189 -189
  35. package/lib/skillopt/subagent-text.js +101 -101
  36. package/lib/skillopt/tool-access.js +56 -56
  37. package/locale/en.json +6 -6
  38. package/locale/zh.json +6 -6
  39. package/package.json +1 -1
@@ -1,146 +1,146 @@
1
- /**
2
- * SkillOpt adopt gate 的宿主接线:把「读候选/基线」和「独立 judge」落到
3
- * DSH 服务上。与 adopt-gate.js(纯协议)分离,便于单测协议、集成测接线。
4
- *
5
- * baseline 取 live SKILL.md 当前内容:adopt 之前 live 文件就是改前版本
6
- * (staging 只写候选项),因此不需要 git 历史即可对比。
7
- */
8
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
9
- import { isAbsolute, join } from 'node:path';
10
- import { judgePair } from './judge-runner.js';
11
-
12
- /** 引号一个 argv 元素(Windows cmd 与 POSIX sh 通用单引号形式)。 */
13
- export function quoteArgv(argv) {
14
- const quote = (value) => {
15
- const text = String(value);
16
- if (text === '' || /[\s"'`$\\!&|<>()*?^%;]/.test(text)) return '"' + text.replace(/"/g, '\\"') + '"';
17
- return text;
18
- };
19
- return argv.map(quote).join(' ');
20
- }
21
-
22
- /**
23
- * 模型可控的 project 会被拼进 shell 命令,因此必须在进 shell 前校验。
24
- * `quoteArgv` 只是引号包裹:`$(...)`、反引号在双引号内仍会被 shell 展开,
25
- * 而 pwsh 下 `\"` 也不是转义——只靠引号挡不住注入。这里要求它是一个
26
- * 真实存在的绝对目录,且不含任何 shell 元字符。
27
- */
28
- export function assertSafeProjectDir(dir) {
29
- if (typeof dir !== 'string' || dir.trim() === '') throw new Error('project directory is required');
30
- const text = dir.trim();
31
- if (!isAbsolute(text)) throw new Error('project directory must be an absolute path');
32
- if (/[\u0000-\u001f`$;|&<>(){}[\]*?"'!^%\r\n]/.test(text)) {
33
- throw new Error('project directory must not contain shell metacharacters');
34
- }
35
- if (!existsSync(text) || statSync(text).isDirectory() !== true) {
36
- throw new Error('project directory does not exist');
37
- }
38
- return text;
39
- }
40
-
41
- /** 跑引擎 CLI(status 等只读命令);返回 {exitCode, stdout, stderr}。 */
42
- export async function runEngineCli(shell, args, options = {}) {
43
- const request = {
44
- command: quoteArgv(args),
45
- timeoutMs: options.timeoutMs ?? 60_000,
46
- signal: options.signal,
47
- };
48
- const spec = typeof shell?.resolve === 'function' ? shell.resolve(request) : request;
49
- const exec = typeof shell?.execute === 'function'
50
- ? await shell.execute(spec)
51
- : await shell.run(spec);
52
- const result = typeof exec?.result === 'function' ? await exec.result() : exec;
53
- const text = (value) => (typeof value === 'string' ? value : value?.text ?? '');
54
- return {
55
- exitCode: result?.exitCode ?? null,
56
- stdout: text(result?.stdout),
57
- stderr: text(result?.stderr),
58
- timedOut: result?.timedOut === true,
59
- };
60
- }
61
-
62
- /**
63
- * 构造 readPair:从引擎 status 找 latest staging,从 staging 目录读候选与基线。
64
- * @param {{shell:object, engineScript:string, python?:string, diag?:object}} deps
65
- * @returns {(projectDir: string) => Promise<{before:string, after:string, skillPath:string|null}>}
66
- */
67
- export function makeReadPair(deps) {
68
- const { shell, engineScript, python = 'python', diag } = deps;
69
- return async (projectDir) => {
70
- const safeDir = assertSafeProjectDir(projectDir);
71
- const status = await runEngineCli(shell, [python, engineScript, 'status', '--json', '--project', safeDir]);
72
- if (status.timedOut) throw new Error('engine status timed out');
73
- const raw = status.stdout.slice(status.stdout.indexOf('{'));
74
- let payload;
75
- try {
76
- payload = JSON.parse(raw);
77
- } catch {
78
- throw new Error(`cannot parse engine status: ${(status.stderr || status.stdout).slice(0, 200)}`);
79
- }
80
- const stagingDir = payload?.latest_staging;
81
- if (typeof stagingDir !== 'string' || stagingDir === '' || !existsSync(stagingDir)) {
82
- throw new Error('no staged proposal (run skillopt_run first; latest_staging is empty)');
83
- }
84
- const names = readdirSync(stagingDir);
85
- const markdown = names.filter((name) => name.toLowerCase().endsWith('.md'));
86
- const manifests = names.filter((name) => name.toLowerCase().endsWith('.json'));
87
- if (markdown.length === 0 || manifests.length === 0) {
88
- throw new Error(`staging ${stagingDir} has no proposal/manifest pair (found: ${names.join(', ') || 'nothing'})`);
89
- }
90
- // manifest: 取含 live_skill_path 的第一行(字段名以引擎为准)。
91
- let livePath = null;
92
- for (const manifestName of manifests) {
93
- try {
94
- const manifest = JSON.parse(readFileSync(join(stagingDir, manifestName), 'utf8'));
95
- const rows = Array.isArray(manifest) ? manifest : manifest?.skills ?? manifest?.proposals ?? [manifest];
96
- const row = (Array.isArray(rows) ? rows : []).find((entry) => typeof entry?.live_skill_path === 'string');
97
- if (row !== undefined) { livePath = row.live_skill_path; break; }
98
- } catch { /* try next */ }
99
- }
100
- const after = readFileSync(join(stagingDir, markdown[0]), 'utf8');
101
- if (livePath === null || !existsSync(livePath)) {
102
- // 无基线时退回「候选内部基线」不可行——拒绝由 gate 处理。
103
- throw new Error('staging manifest has no reachable live_skill_path; baseline unavailable');
104
- }
105
- const before = readFileSync(livePath, 'utf8');
106
- diag?.append?.({ ev: 'skillopt.readpair', project: projectDir, stagingDir, livePath, bytesBefore: before.length, bytesAfter: after.length });
107
- return { before, after, skillPath: livePath };
108
- };
109
- }
110
-
111
- /**
112
- * 构造 judge 函数(供 adopt gate 用):惰性取 parent/provider,起独立子代理盲评。
113
- * @param {object} deps
114
- * @param {object} deps.subagents ctx.get('subagents')
115
- * @param {() => Promise<{agent: object}>} deps.ensureParent
116
- * @param {() => string} deps.providerName
117
- * @param {number} [deps.votes]
118
- * @param {object} [deps.diag]
119
- */
120
- export function makeJudge(deps) {
121
- const { subagents, ensureParent, providerName, votes, diag } = deps;
122
- return async ({ before, after, projectDir }) => {
123
- const parentInfo = await ensureParent();
124
- const provider = providerName();
125
- const result = await judgePair({
126
- before,
127
- after,
128
- subagents,
129
- parent: parentInfo?.agent,
130
- provider,
131
- cwd: projectDir,
132
- votes,
133
- });
134
- diag?.append?.({
135
- ev: 'skillopt.judge',
136
- project: projectDir,
137
- verdict: result.verdict,
138
- better: result.better,
139
- worse: result.worse,
140
- ties: result.ties,
141
- valid: result.valid,
142
- errors: result.errors,
143
- });
144
- return result;
145
- };
146
- }
1
+ /**
2
+ * SkillOpt adopt gate 的宿主接线:把「读候选/基线」和「独立 judge」落到
3
+ * DSH 服务上。与 adopt-gate.js(纯协议)分离,便于单测协议、集成测接线。
4
+ *
5
+ * baseline 取 live SKILL.md 当前内容:adopt 之前 live 文件就是改前版本
6
+ * (staging 只写候选项),因此不需要 git 历史即可对比。
7
+ */
8
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
9
+ import { isAbsolute, join } from 'node:path';
10
+ import { judgePair } from './judge-runner.js';
11
+
12
+ /** 引号一个 argv 元素(Windows cmd 与 POSIX sh 通用单引号形式)。 */
13
+ export function quoteArgv(argv) {
14
+ const quote = (value) => {
15
+ const text = String(value);
16
+ if (text === '' || /[\s"'`$\\!&|<>()*?^%;]/.test(text)) return '"' + text.replace(/"/g, '\\"') + '"';
17
+ return text;
18
+ };
19
+ return argv.map(quote).join(' ');
20
+ }
21
+
22
+ /**
23
+ * 模型可控的 project 会被拼进 shell 命令,因此必须在进 shell 前校验。
24
+ * `quoteArgv` 只是引号包裹:`$(...)`、反引号在双引号内仍会被 shell 展开,
25
+ * 而 pwsh 下 `\"` 也不是转义——只靠引号挡不住注入。这里要求它是一个
26
+ * 真实存在的绝对目录,且不含任何 shell 元字符。
27
+ */
28
+ export function assertSafeProjectDir(dir) {
29
+ if (typeof dir !== 'string' || dir.trim() === '') throw new Error('project directory is required');
30
+ const text = dir.trim();
31
+ if (!isAbsolute(text)) throw new Error('project directory must be an absolute path');
32
+ if (/[\u0000-\u001f`$;|&<>(){}[\]*?"'!^%\r\n]/.test(text)) {
33
+ throw new Error('project directory must not contain shell metacharacters');
34
+ }
35
+ if (!existsSync(text) || statSync(text).isDirectory() !== true) {
36
+ throw new Error('project directory does not exist');
37
+ }
38
+ return text;
39
+ }
40
+
41
+ /** 跑引擎 CLI(status 等只读命令);返回 {exitCode, stdout, stderr}。 */
42
+ export async function runEngineCli(shell, args, options = {}) {
43
+ const request = {
44
+ command: quoteArgv(args),
45
+ timeoutMs: options.timeoutMs ?? 60_000,
46
+ signal: options.signal,
47
+ };
48
+ const spec = typeof shell?.resolve === 'function' ? shell.resolve(request) : request;
49
+ const exec = typeof shell?.execute === 'function'
50
+ ? await shell.execute(spec)
51
+ : await shell.run(spec);
52
+ const result = typeof exec?.result === 'function' ? await exec.result() : exec;
53
+ const text = (value) => (typeof value === 'string' ? value : value?.text ?? '');
54
+ return {
55
+ exitCode: result?.exitCode ?? null,
56
+ stdout: text(result?.stdout),
57
+ stderr: text(result?.stderr),
58
+ timedOut: result?.timedOut === true,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * 构造 readPair:从引擎 status 找 latest staging,从 staging 目录读候选与基线。
64
+ * @param {{shell:object, engineScript:string, python?:string, diag?:object}} deps
65
+ * @returns {(projectDir: string) => Promise<{before:string, after:string, skillPath:string|null}>}
66
+ */
67
+ export function makeReadPair(deps) {
68
+ const { shell, engineScript, python = 'python', diag } = deps;
69
+ return async (projectDir) => {
70
+ const safeDir = assertSafeProjectDir(projectDir);
71
+ const status = await runEngineCli(shell, [python, engineScript, 'status', '--json', '--project', safeDir]);
72
+ if (status.timedOut) throw new Error('engine status timed out');
73
+ const raw = status.stdout.slice(status.stdout.indexOf('{'));
74
+ let payload;
75
+ try {
76
+ payload = JSON.parse(raw);
77
+ } catch {
78
+ throw new Error(`cannot parse engine status: ${(status.stderr || status.stdout).slice(0, 200)}`);
79
+ }
80
+ const stagingDir = payload?.latest_staging;
81
+ if (typeof stagingDir !== 'string' || stagingDir === '' || !existsSync(stagingDir)) {
82
+ throw new Error('no staged proposal (run skillopt_run first; latest_staging is empty)');
83
+ }
84
+ const names = readdirSync(stagingDir);
85
+ const markdown = names.filter((name) => name.toLowerCase().endsWith('.md'));
86
+ const manifests = names.filter((name) => name.toLowerCase().endsWith('.json'));
87
+ if (markdown.length === 0 || manifests.length === 0) {
88
+ throw new Error(`staging ${stagingDir} has no proposal/manifest pair (found: ${names.join(', ') || 'nothing'})`);
89
+ }
90
+ // manifest: 取含 live_skill_path 的第一行(字段名以引擎为准)。
91
+ let livePath = null;
92
+ for (const manifestName of manifests) {
93
+ try {
94
+ const manifest = JSON.parse(readFileSync(join(stagingDir, manifestName), 'utf8'));
95
+ const rows = Array.isArray(manifest) ? manifest : manifest?.skills ?? manifest?.proposals ?? [manifest];
96
+ const row = (Array.isArray(rows) ? rows : []).find((entry) => typeof entry?.live_skill_path === 'string');
97
+ if (row !== undefined) { livePath = row.live_skill_path; break; }
98
+ } catch { /* try next */ }
99
+ }
100
+ const after = readFileSync(join(stagingDir, markdown[0]), 'utf8');
101
+ if (livePath === null || !existsSync(livePath)) {
102
+ // 无基线时退回「候选内部基线」不可行——拒绝由 gate 处理。
103
+ throw new Error('staging manifest has no reachable live_skill_path; baseline unavailable');
104
+ }
105
+ const before = readFileSync(livePath, 'utf8');
106
+ diag?.append?.({ ev: 'skillopt.readpair', project: projectDir, stagingDir, livePath, bytesBefore: before.length, bytesAfter: after.length });
107
+ return { before, after, skillPath: livePath };
108
+ };
109
+ }
110
+
111
+ /**
112
+ * 构造 judge 函数(供 adopt gate 用):惰性取 parent/provider,起独立子代理盲评。
113
+ * @param {object} deps
114
+ * @param {object} deps.subagents ctx.get('subagents')
115
+ * @param {() => Promise<{agent: object}>} deps.ensureParent
116
+ * @param {() => string} deps.providerName
117
+ * @param {number} [deps.votes]
118
+ * @param {object} [deps.diag]
119
+ */
120
+ export function makeJudge(deps) {
121
+ const { subagents, ensureParent, providerName, votes, diag } = deps;
122
+ return async ({ before, after, projectDir }) => {
123
+ const parentInfo = await ensureParent();
124
+ const provider = providerName();
125
+ const result = await judgePair({
126
+ before,
127
+ after,
128
+ subagents,
129
+ parent: parentInfo?.agent,
130
+ provider,
131
+ cwd: projectDir,
132
+ votes,
133
+ });
134
+ diag?.append?.({
135
+ ev: 'skillopt.judge',
136
+ project: projectDir,
137
+ verdict: result.verdict,
138
+ better: result.better,
139
+ worse: result.worse,
140
+ ties: result.ties,
141
+ valid: result.valid,
142
+ errors: result.errors,
143
+ });
144
+ return result;
145
+ };
146
+ }
@@ -1,136 +1,136 @@
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 { reportFail } from '../diaglog.js';
16
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
17
- import { join } from 'node:path';
18
-
19
- export const JOB_STATES = Object.freeze(['generating', 'judging', 'done', 'failed']);
20
- const JOB_TTL_MS = 30 * 60 * 1000;
21
-
22
- /** job 目录(项目内,随 .skillopt-sleep 一起被忽略/清理)。 */
23
- export function jobsDir(projectDir) {
24
- return join(projectDir, '.skillopt-sleep', 'jobs');
25
- }
26
-
27
- /** 读取一个 job 文件(损坏视为不存在)。 */
28
- export function readJob(projectDir, jobId) {
29
- try {
30
- return JSON.parse(readFileSync(join(jobsDir(projectDir), `${jobId}.json`), 'utf8'));
31
- } catch {
32
- return null;
33
- }
34
- }
35
-
36
- /** 列出全部 job(按创建时间升序)。 */
37
- export function listJobs(projectDir) {
38
- const dir = jobsDir(projectDir);
39
- if (!existsSync(dir)) return [];
40
- const jobs = [];
41
- for (const name of readdirSync(dir)) {
42
- if (!name.endsWith('.json')) continue;
43
- try {
44
- jobs.push(JSON.parse(readFileSync(join(dir, name), 'utf8')));
45
- } catch (error) {
46
- // 静默跳过会让「job 幽灵消失」无从排查:坏文件保留在盘上并留一行警告。
47
- reportFail('job.file.unreadable.fail', { file: name }, `[skillopt] skipping unreadable job file ${name}: ${error?.message ?? error}`);
48
- }
49
- }
50
- return jobs.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
51
- }
52
-
53
- /** 写入 job:先写临时文件再改名,避免进程中断留下半截 JSON。 */
54
- export function writeJob(projectDir, job) {
55
- const dir = jobsDir(projectDir);
56
- mkdirSync(dir, { recursive: true });
57
- const target = join(dir, `${job.id}.json`);
58
- // done 是终态,不可被回退:并发收票/收割时,后到的一次判断可能把已完成的 job
59
- // 覆写成 failed,之后 TTL 与统计都会按错误状态走。
60
- const existing = readJob(projectDir, job.id);
61
- if (existing !== null && existing.state === 'done' && job.state !== 'done') {
62
- reportFail('job.overwrite.refused.fail', { jobId: job.id, next: job.state }, `[skillopt] refusing to overwrite a done job ${job.id} with ${String(job.state)}`);
63
- return existing;
64
- }
65
- const temp = `${target}.tmp`;
66
- writeFileSync(temp, JSON.stringify(job, null, 2), 'utf8');
67
- renameSync(temp, target);
68
- return job;
69
- }
70
-
71
- /** 删除 job 文件(done/failed 的收尾清理)。 */
72
- export function removeJob(projectDir, jobId) {
73
- try { unlinkSync(join(jobsDir(projectDir), `${jobId}.json`)); } catch { /* already gone */ }
74
- }
75
-
76
- /**
77
- * 判定在飞子代理是否已完成。
78
- *
79
- * 关键:**查不到状态不等于已完成**。刚启动的子代理可能在宿主 registry 里
80
- * 暂不可见(agents.get 返回 undefined),此时必须继续等(有 TTL 兜底),
81
- * 否则会在子代理尚未产出时报「空候选」。只有明确 idle / 结束事件 /
82
- * 有事件且无状态时才算结束。
83
- *
84
- * @param {{status?: string|null, events?: Array}} observation
85
- * @returns {boolean}
86
- */
87
- export function isChildSettled(observation) {
88
- const events = Array.isArray(observation?.events) ? observation.events : [];
89
- if (events.some((event) => event?.type === 'subagent/end' || event?.type === 'session/end')) return true;
90
- const status = observation?.status;
91
- if (status === 'idle') return true;
92
- if (status === 'running') return false;
93
- // 状态未知:有事件说明会话存在且可能已产出(无结束事件时由 TTL 兜底)。
94
- return events.length > 0;
95
- }
96
-
97
- /** job 是否超时(TTL)。 */
98
- export function isJobExpired(job, nowMs, ttlMs = JOB_TTL_MS) {
99
- return typeof job?.createdAt === 'number' && nowMs - job.createdAt > ttlMs;
100
- }
101
-
102
- /**
103
- * 状态机的一步决策(纯函数):
104
- * @param {object} job 当前 job
105
- * @param {{children: Record<string, {status?:string, events?:Array}>, now: number}} observation
106
- * @returns {{next: string, actions: Array<{type:string, payload?:object}>, reason?: string}}
107
- * actions.type: 'finish-keep'|'finish-revert'|'fail'|'start-judges'|'apply-candidate'|'await'
108
- */
109
- export function planJobStep(job, observation) {
110
- const state = job?.state;
111
- if (state === 'done' || state === 'failed') return { next: state, actions: [], reason: 'terminal' };
112
- if (isJobExpired(job, observation.now)) {
113
- return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'job timeout' } }], reason: 'timeout' };
114
- }
115
- if (state === 'generating') {
116
- const child = observation.children?.[job.generatorChildId];
117
- if (!isChildSettled(child)) return { next: state, actions: [{ type: 'await' }], reason: 'generator running' };
118
- const text = typeof child?.text === 'string' ? child.text : '';
119
- if (text.trim() === '') {
120
- return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'generator returned an empty candidate' } }], reason: 'empty candidate' };
121
- }
122
- return { next: 'judging', actions: [{ type: 'apply-candidate', payload: { text } }, { type: 'start-judges' }], reason: 'generator settled' };
123
- }
124
- if (state === 'judging') {
125
- const votes = [];
126
- let allSettled = true;
127
- for (const childId of job.judgeChildIds ?? []) {
128
- const child = observation.children?.[childId];
129
- if (!isChildSettled(child)) { allSettled = false; continue; }
130
- votes.push({ childId, text: typeof child?.text === 'string' ? child.text : '' });
131
- }
132
- if (!allSettled) return { next: state, actions: [{ type: 'await' }], reason: 'judges running' };
133
- return { next: 'done', actions: [{ type: 'finish', payload: { votes } }], reason: 'judges settled' };
134
- }
135
- return { next: 'failed', actions: [{ type: 'fail', payload: { reason: `unknown state ${String(state)}` } }], reason: 'unknown state' };
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 { reportFail } from '../diaglog.js';
16
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+
19
+ export const JOB_STATES = Object.freeze(['generating', 'judging', 'done', 'failed']);
20
+ const JOB_TTL_MS = 30 * 60 * 1000;
21
+
22
+ /** job 目录(项目内,随 .skillopt-sleep 一起被忽略/清理)。 */
23
+ export function jobsDir(projectDir) {
24
+ return join(projectDir, '.skillopt-sleep', 'jobs');
25
+ }
26
+
27
+ /** 读取一个 job 文件(损坏视为不存在)。 */
28
+ export function readJob(projectDir, jobId) {
29
+ try {
30
+ return JSON.parse(readFileSync(join(jobsDir(projectDir), `${jobId}.json`), 'utf8'));
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ /** 列出全部 job(按创建时间升序)。 */
37
+ export function listJobs(projectDir) {
38
+ const dir = jobsDir(projectDir);
39
+ if (!existsSync(dir)) return [];
40
+ const jobs = [];
41
+ for (const name of readdirSync(dir)) {
42
+ if (!name.endsWith('.json')) continue;
43
+ try {
44
+ jobs.push(JSON.parse(readFileSync(join(dir, name), 'utf8')));
45
+ } catch (error) {
46
+ // 静默跳过会让「job 幽灵消失」无从排查:坏文件保留在盘上并留一行警告。
47
+ reportFail('job.file.unreadable.fail', { file: name }, `[skillopt] skipping unreadable job file ${name}: ${error?.message ?? error}`);
48
+ }
49
+ }
50
+ return jobs.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
51
+ }
52
+
53
+ /** 写入 job:先写临时文件再改名,避免进程中断留下半截 JSON。 */
54
+ export function writeJob(projectDir, job) {
55
+ const dir = jobsDir(projectDir);
56
+ mkdirSync(dir, { recursive: true });
57
+ const target = join(dir, `${job.id}.json`);
58
+ // done 是终态,不可被回退:并发收票/收割时,后到的一次判断可能把已完成的 job
59
+ // 覆写成 failed,之后 TTL 与统计都会按错误状态走。
60
+ const existing = readJob(projectDir, job.id);
61
+ if (existing !== null && existing.state === 'done' && job.state !== 'done') {
62
+ reportFail('job.overwrite.refused.fail', { jobId: job.id, next: job.state }, `[skillopt] refusing to overwrite a done job ${job.id} with ${String(job.state)}`);
63
+ return existing;
64
+ }
65
+ const temp = `${target}.tmp`;
66
+ writeFileSync(temp, JSON.stringify(job, null, 2), 'utf8');
67
+ renameSync(temp, target);
68
+ return job;
69
+ }
70
+
71
+ /** 删除 job 文件(done/failed 的收尾清理)。 */
72
+ export function removeJob(projectDir, jobId) {
73
+ try { unlinkSync(join(jobsDir(projectDir), `${jobId}.json`)); } catch { /* already gone */ }
74
+ }
75
+
76
+ /**
77
+ * 判定在飞子代理是否已完成。
78
+ *
79
+ * 关键:**查不到状态不等于已完成**。刚启动的子代理可能在宿主 registry 里
80
+ * 暂不可见(agents.get 返回 undefined),此时必须继续等(有 TTL 兜底),
81
+ * 否则会在子代理尚未产出时报「空候选」。只有明确 idle / 结束事件 /
82
+ * 有事件且无状态时才算结束。
83
+ *
84
+ * @param {{status?: string|null, events?: Array}} observation
85
+ * @returns {boolean}
86
+ */
87
+ export function isChildSettled(observation) {
88
+ const events = Array.isArray(observation?.events) ? observation.events : [];
89
+ if (events.some((event) => event?.type === 'subagent/end' || event?.type === 'session/end')) return true;
90
+ const status = observation?.status;
91
+ if (status === 'idle') return true;
92
+ if (status === 'running') return false;
93
+ // 状态未知:有事件说明会话存在且可能已产出(无结束事件时由 TTL 兜底)。
94
+ return events.length > 0;
95
+ }
96
+
97
+ /** job 是否超时(TTL)。 */
98
+ export function isJobExpired(job, nowMs, ttlMs = JOB_TTL_MS) {
99
+ return typeof job?.createdAt === 'number' && nowMs - job.createdAt > ttlMs;
100
+ }
101
+
102
+ /**
103
+ * 状态机的一步决策(纯函数):
104
+ * @param {object} job 当前 job
105
+ * @param {{children: Record<string, {status?:string, events?:Array}>, now: number}} observation
106
+ * @returns {{next: string, actions: Array<{type:string, payload?:object}>, reason?: string}}
107
+ * actions.type: 'finish-keep'|'finish-revert'|'fail'|'start-judges'|'apply-candidate'|'await'
108
+ */
109
+ export function planJobStep(job, observation) {
110
+ const state = job?.state;
111
+ if (state === 'done' || state === 'failed') return { next: state, actions: [], reason: 'terminal' };
112
+ if (isJobExpired(job, observation.now)) {
113
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'job timeout' } }], reason: 'timeout' };
114
+ }
115
+ if (state === 'generating') {
116
+ const child = observation.children?.[job.generatorChildId];
117
+ if (!isChildSettled(child)) return { next: state, actions: [{ type: 'await' }], reason: 'generator running' };
118
+ const text = typeof child?.text === 'string' ? child.text : '';
119
+ if (text.trim() === '') {
120
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: 'generator returned an empty candidate' } }], reason: 'empty candidate' };
121
+ }
122
+ return { next: 'judging', actions: [{ type: 'apply-candidate', payload: { text } }, { type: 'start-judges' }], reason: 'generator settled' };
123
+ }
124
+ if (state === 'judging') {
125
+ const votes = [];
126
+ let allSettled = true;
127
+ for (const childId of job.judgeChildIds ?? []) {
128
+ const child = observation.children?.[childId];
129
+ if (!isChildSettled(child)) { allSettled = false; continue; }
130
+ votes.push({ childId, text: typeof child?.text === 'string' ? child.text : '' });
131
+ }
132
+ if (!allSettled) return { next: state, actions: [{ type: 'await' }], reason: 'judges running' };
133
+ return { next: 'done', actions: [{ type: 'finish', payload: { votes } }], reason: 'judges settled' };
134
+ }
135
+ return { next: 'failed', actions: [{ type: 'fail', payload: { reason: `unknown state ${String(state)}` } }], reason: 'unknown state' };
136
136
  }
@@ -1,33 +1,33 @@
1
- /**
2
- * 提案落盘的共用原语:内容指纹、live 文件备份、原子替换。
3
- *
4
- * 三者必须一起用:先按 sha 判断 live 是否仍是评审时的基线(并发冲突),再备份,
5
- * 最后用 tmp + rename 原子替换。缺任一步都会出现「评审期间的人工修改被静默覆盖」
6
- * 或「写到一半崩溃留下半截 SKILL.md」。
7
- */
8
- import { createHash } from 'node:crypto';
9
- import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
10
- import { join } from 'node:path';
11
-
12
- /** 12 位内容指纹:足够区分提案版本,又能塞进 results.tsv 的一列。 */
13
- export function sha12(text) {
14
- return createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex').slice(0, 12);
15
- }
16
-
17
- /** 备份 live 文本到 `.skillopt-sleep/backups/`,返回备份路径。 */
18
- export function backupLive({ projectDir, skillPath, text, now = Date.now() }) {
19
- const dir = join(projectDir, '.skillopt-sleep', 'backups');
20
- mkdirSync(dir, { recursive: true });
21
- const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');
22
- const name = String(skillPath).split(/[\\/]/).pop() ?? 'SKILL.md';
23
- const target = join(dir, `${name}.${stamp}.bak`);
24
- writeFileSync(target, String(text ?? ''), 'utf8');
25
- return target;
26
- }
27
-
28
- /** 同目录 tmp + rename,避免半截写入。 */
29
- export function applyLiveAtomically(path, text) {
30
- const tmp = `${path}.tmp-${process.pid.toString(36)}-${Date.now().toString(36)}`;
31
- writeFileSync(tmp, String(text ?? ''), 'utf8');
32
- renameSync(tmp, path);
33
- }
1
+ /**
2
+ * 提案落盘的共用原语:内容指纹、live 文件备份、原子替换。
3
+ *
4
+ * 三者必须一起用:先按 sha 判断 live 是否仍是评审时的基线(并发冲突),再备份,
5
+ * 最后用 tmp + rename 原子替换。缺任一步都会出现「评审期间的人工修改被静默覆盖」
6
+ * 或「写到一半崩溃留下半截 SKILL.md」。
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
10
+ import { join } from 'node:path';
11
+
12
+ /** 12 位内容指纹:足够区分提案版本,又能塞进 results.tsv 的一列。 */
13
+ export function sha12(text) {
14
+ return createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex').slice(0, 12);
15
+ }
16
+
17
+ /** 备份 live 文本到 `.skillopt-sleep/backups/`,返回备份路径。 */
18
+ export function backupLive({ projectDir, skillPath, text, now = Date.now() }) {
19
+ const dir = join(projectDir, '.skillopt-sleep', 'backups');
20
+ mkdirSync(dir, { recursive: true });
21
+ const stamp = new Date(now).toISOString().replace(/[:.]/g, '-');
22
+ const name = String(skillPath).split(/[\\/]/).pop() ?? 'SKILL.md';
23
+ const target = join(dir, `${name}.${stamp}.bak`);
24
+ writeFileSync(target, String(text ?? ''), 'utf8');
25
+ return target;
26
+ }
27
+
28
+ /** 同目录 tmp + rename,避免半截写入。 */
29
+ export function applyLiveAtomically(path, text) {
30
+ const tmp = `${path}.tmp-${process.pid.toString(36)}-${Date.now().toString(36)}`;
31
+ writeFileSync(tmp, String(text ?? ''), 'utf8');
32
+ renameSync(tmp, path);
33
+ }