@suifei/dsh-ai-team 0.4.109 → 0.4.111

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/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.111 - 2026-11-16
4
+
5
+ **SkillOpt 一次性子代理不再逐个唤醒 PMO**
6
+
7
+ - 作答、判官、生成子代理用 `delivery: 'parent'` 启动;官方语义是 parent 投递「通知父会话的模型」,caller
8
+ 投递「只把结果交回调用方」。il2c 实机:PMO 宿主会话 16:30 起收到 104 条「子智能体已完成任务」,开了 51 个
9
+ 回合(单回合用量 404K tok),主对话被逐条点评夜间环的内容淹没,会话头显示「112 个子智能体」;
10
+ - 4 处 SkillOpt 一次性子代理改为 `delivery: 'caller'`(结果仍经 `activation.result` / 会话事件取回);
11
+ 成员激活保留 `parent`——成员结果本就要交给 PMO;
12
+ - 宿主文档:本地子代理总会进入父会话目录,`dispose` 后仍在目录里,子智能体计数不会因此下降;
13
+ - 测试:`test/stop-guard.test.js` 新增投递契约 1 例(换回旧实现即失败),`darwin-alignment` 判官断言改为 caller;
14
+
15
+ ## 0.4.110 - 2026-11-16
16
+
17
+ **SkillOpt 一次性子代理只凭题面作答,不在真实工作区动手**
18
+
19
+ - il2c night 8 实机:handoff 作答子代理继承 PMO 宿主的 `danger-full-access`,工作目录就是 il2c 工作区;
20
+ 回放题里它真的去读仓库与账本「取证」后作答。这次挖出的任务恰好都是只读对账,若挖出「修复 csvstat 门禁」
21
+ 这类任务,回放就会真改代码、写账本;
22
+ - 宿主没有可编程的只读预设(默认只有 `workspace-write`+ask 与 `danger-full-access`),在工具层拦:新增
23
+ `registerOneShotToolGuard`(`tools.guard`),`skillopt-*` 一次性子代理(作答、判官、生成)的任何工具调用一律
24
+ 拒绝,理由回给模型「只凭题面文字回答」;拦截行 `skillopt.oneshot.tool.blocked` 在发布默认 `errors` 级别可见;
25
+ - 作答子代理的工作目录改为工作区之外的空目录(系统临时目录下 `dsh-ai-team-skillopt-answer`),项目 AGENTS.md
26
+ 与仓库不进作答上下文;
27
+ - 测试:`test/stop-guard.test.js` 新增 1 例;
28
+
3
29
  ## 0.4.109 - 2026-11-16
4
30
 
5
31
  **dsh 来源不再采 SkillOpt 自己的子代理会话**
package/index.js CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { planDispatch, planTaskNudges } from './lib/host/pmo.js';
12
12
  import { pmoHasNews } from './lib/ledger/fold.js';
13
- import { homedir } from 'node:os';
13
+ import { homedir, tmpdir } from 'node:os';
14
14
  import { randomUUID } from 'node:crypto';
15
15
  import { join, sep } from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
@@ -58,7 +58,7 @@ import { describeTaskContext, describeWake, planWakes } from './lib/host/waker.j
58
58
  import { describeCauseChain } from './lib/runtime/error-chain.js';
59
59
  import { classifyWakeFailure, isMalformedTurnError } from './lib/runtime/wake-failure.js';
60
60
  import { registerShellGuard } from './lib/runtime/shell-guard.js';
61
- import { registerStopGuard } from './lib/runtime/stop-guard.js';
61
+ import { registerOneShotToolGuard, registerStopGuard } from './lib/runtime/stop-guard.js';
62
62
  import { registerTeamDiscipline } from './lib/runtime/deferral-guard.js';
63
63
  import { createActivationBudget } from './lib/runtime/activation-budget.js';
64
64
  import { blocksActivation, probeProviderRegistration } from './lib/runtime/subagent-probe.js';
@@ -691,7 +691,7 @@ export function apply(ctx, config = {}) {
691
691
  // il2c 2997 次唤醒里 pmo_dispatch 为 0)。进程内状态,重启即清空——重启时本就没有回合在跑。
692
692
  const turnsInFlight = new Set();
693
693
  // 团队推进纪律:系统提示词段 + 回合收尾时纠偏「把行动挂在钟点上」(il2c:「今夜 03:17 自然相裁决点」)。
694
- let teamDiscipline = { observe: () => {}, exempt: () => {}, dispose: () => {} };
694
+ let teamDiscipline = { observe: () => {}, exempt: () => {}, isOneShot: () => false, dispose: () => {} };
695
695
  try {
696
696
  teamDiscipline = registerTeamDiscipline({
697
697
  systemPrompt: serviceOf(ctx, 'systemPrompt'),
@@ -1160,11 +1160,15 @@ export function apply(ctx, config = {}) {
1160
1160
  diag: (row) => diag.append(row),
1161
1161
  startChild: async (label, request) => {
1162
1162
  const parentInfo = await ensureParent(projectRuntime);
1163
+ // 作答在工作区之外的空目录里进行:项目 AGENTS.md / 仓库不进作答上下文,
1164
+ // 工具调用另由 registerOneShotToolGuard 一律拒绝。
1165
+ const answerCwd = join(tmpdir(), 'dsh-ai-team-skillopt-answer');
1166
+ mkdirSync(answerCwd, { recursive: true });
1163
1167
  const activation = await serviceOf(ctx, 'subagents').startActivation(activationSpec({
1164
1168
  provider: resolveSubagentProviderName(serviceOf(ctx, 'subagents'), config?.subagentProviderName),
1165
1169
  label,
1166
- request: { cwd: request.cwd, prompt: [{ type: 'text', text: request.prompt }], parent: parentInfo?.agent },
1167
- delivery: 'parent',
1170
+ request: { cwd: answerCwd, prompt: [{ type: 'text', text: request.prompt }], parent: parentInfo?.agent },
1171
+ delivery: 'caller',
1168
1172
  signal: new AbortController().signal,
1169
1173
  }));
1170
1174
  const childId = activation.childId;
@@ -1862,8 +1866,10 @@ export function apply(ctx, config = {}) {
1862
1866
  // 停止即停:停止期间 PMO 与成员不得用宿主内置工具(send_message 等)互相唤醒或派生
1863
1867
  // 子智能体——实机停止后 PMO 收到「成员被停」通知,又用 send_message 把成员续跑了 25 分钟。
1864
1868
  let disposeStopGuard = () => {};
1869
+ let disposeOneShotToolGuard = () => {};
1865
1870
  try {
1866
1871
  disposeStopGuard = registerStopGuard({ tools: tools ?? serviceOf(ctx, 'tools'), projectOf: teamProjectOf, diag });
1872
+ disposeOneShotToolGuard = registerOneShotToolGuard({ tools: tools ?? serviceOf(ctx, 'tools'), isOneShot: (sessionId) => teamDiscipline.isOneShot?.(sessionId) === true, diag });
1867
1873
  } catch (error) {
1868
1874
  diag.append({ ev: 'stop.guard.fail', message: error?.message ?? String(error) });
1869
1875
  }
@@ -2953,6 +2959,7 @@ export function apply(ctx, config = {}) {
2953
2959
  try { removeDiagSink(); } catch { /* sink already replaced */ }
2954
2960
  try { disposeShellGuard(); } catch { /* already disposed */ }
2955
2961
  try { disposeStopGuard(); } catch { /* already disposed */ }
2962
+ try { disposeOneShotToolGuard(); } catch { /* already disposed */ }
2956
2963
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
2957
2964
  // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
2958
2965
  // 否则下一组合抢在关锁之前打开同一账本。
package/lib/diaglog.js CHANGED
@@ -39,6 +39,8 @@ export function isErrorEvent(ev) {
39
39
  || ev === 'team.interrupt'
40
40
  // 停止期间团队会话想唤醒/派生智能体被拦下:停止是否真的停住的直接证据。
41
41
  || ev === 'team.stopped.blocked'
42
+ // SkillOpt 一次性子代理想调工具被拦下:作答有没有在真实工作区里动手的直接证据。
43
+ || ev === 'skillopt.oneshot.tool.blocked'
42
44
  // 换新团队会话(Human):新旧 PMO 与每个成员的新旧会话。
43
45
  || ev === 'team.renewed'
44
46
  // 重建后旧会话有没有从工作区摘掉:决定工作区列表是否随自愈累积死会话。
@@ -79,7 +79,7 @@ export const TEAM_DISCIPLINE_TEXT = [
79
79
  * diag?: { append?: (row: object) => void },
80
80
  * newId: () => string,
81
81
  * }} options
82
- * @returns {{ observe: (session: any, event: any) => void, stopping: (payload: any) => Promise<void>, exempt: (sessionId: string) => void, dispose: () => void }}
82
+ * @returns {{ observe: (session: any, event: any) => void, stopping: (payload: any) => Promise<void>, exempt: (sessionId: string) => void, isOneShot: (sessionId: string) => boolean, dispose: () => void }}
83
83
  */
84
84
  export function registerTeamDiscipline({ systemPrompt, on, teamProjectOf, diag, newId }) {
85
85
  const disposers = [];
@@ -161,6 +161,7 @@ export function registerTeamDiscipline({ systemPrompt, on, teamProjectOf, diag,
161
161
  exempt: (sessionId) => {
162
162
  if (typeof sessionId === 'string' && sessionId !== '') oneShot.add(sessionId);
163
163
  },
164
+ isOneShot: (sessionId) => typeof sessionId === 'string' && oneShot.has(sessionId),
164
165
  dispose: () => {
165
166
  for (const dispose of disposers.splice(0)) {
166
167
  try { dispose?.(); } catch { /* already disposed */ }
@@ -31,6 +31,45 @@ export function stoppedTeamDenial(execution, projectOf) {
31
31
  };
32
32
  }
33
33
 
34
+ /**
35
+ * SkillOpt 一次性子代理(handoff 作答、判官、生成)只凭题面文字作答,不得调用任何工具。
36
+ *
37
+ * il2c night 8 实机:作答子代理继承 PMO 宿主的 danger-full-access,工作目录就是 il2c
38
+ * 工作区,回放题里它真的去读仓库与账本「取证」——题目若是「修复 csvstat 门禁」它就会真改
39
+ * 代码、写账本。宿主没有可编程的只读预设(默认只有 workspace-write+ask 与
40
+ * danger-full-access),所以在工具层拒绝。
41
+ *
42
+ * @param {object} execution 宿主 ToolExecution(name / agent.id)
43
+ * @param {(sessionId: string) => boolean} isOneShot
44
+ * @returns {string | null} 需要拒绝时返回理由
45
+ */
46
+ export function oneShotToolDenial(execution, isOneShot) {
47
+ const sessionId = execution?.agent?.id;
48
+ if (typeof sessionId !== 'string' || sessionId === '' || isOneShot(sessionId) !== true) return null;
49
+ return `已阻止:这是 SkillOpt 的一次性作答,只凭题面文字回答,不得调用任何工具(${String(execution?.name ?? '')})。不要读写文件、不要执行命令,直接输出题目要求的答案。`;
50
+ }
51
+
52
+ /**
53
+ * @param {object} options
54
+ * @param {object} options.tools `ctx.tools`
55
+ * @param {(sessionId: string) => boolean} options.isOneShot
56
+ * @param {{ append?: (row: object) => void }} [options.diag]
57
+ * @returns {() => void} disposer
58
+ */
59
+ export function registerOneShotToolGuard({ tools, isOneShot, diag }) {
60
+ if (tools === undefined || tools === null || typeof tools.guard !== 'function') return () => {};
61
+ return tools.guard((execution) => {
62
+ try {
63
+ const reason = oneShotToolDenial(execution, isOneShot);
64
+ if (reason === null) return undefined;
65
+ diag?.append?.({ ev: 'skillopt.oneshot.tool.blocked', sessionId: execution?.agent?.id ?? null, tool: String(execution?.name ?? '') });
66
+ return reason;
67
+ } catch {
68
+ return undefined;
69
+ }
70
+ });
71
+ }
72
+
34
73
  /**
35
74
  * @param {object} options
36
75
  * @param {object} options.tools `ctx.tools`
@@ -1,208 +1,208 @@
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
- import { sha12 } from './proposal-store.js';
13
-
14
- /** 观测一个在飞子代理:状态 + 会话事件(同步,供状态机使用)。 */
15
- export function observeChild(ctx, childId, outputStart) {
16
- // 三条路径兜底:agents(活 agent)→ subagents activation → sessions。
17
- const agent = ctx.get('agents')?.get?.(childId);
18
- if (agent !== undefined && agent !== null) {
19
- let events = [];
20
- try {
21
- events = agent.session?.snapshotEvents?.(outputStart) ?? [];
22
- } catch { /* session may be gone */ }
23
- return { status: agent.status ?? null, events, text: extractAssistantText(events) };
24
- }
25
- // 刚启动的子代理可能不在 agents registry:用 sessions 服务读会话事件。
26
- const session = ctx.get('sessions')?.get?.(childId);
27
- if (session !== undefined && session !== null) {
28
- let events = [];
29
- try {
30
- events = session.snapshotEvents?.(outputStart) ?? [];
31
- } catch { /* session may be gone */ }
32
- return { status: null, events, text: extractAssistantText(events) };
33
- }
34
- // 完全查不到:不得视为已完成(由 TTL 兜底),调用方会继续等待。
35
- return { status: 'running', events: [] };
36
- }
37
-
38
- /**
39
- * 推进一个 job 一步。
40
- *
41
- * @param {object} input
42
- * @param {object} input.ctx DSH context
43
- * @param {string} input.projectDir
44
- * @param {object} input.job job 记录
45
- * @param {object} input.deps
46
- * @param {(name:string, spec:object)=>Promise<object>} input.deps.startChild 启动子代理(返回 {childId})
47
- * @param {(path:string, text:string)=>void} input.deps.writeText
48
- * @param {(path:string)=>string} input.deps.readText
49
- * @param {object} input.deps.vcs makeVcs 结果
50
- * @param {(line:string)=>Promise<void>} input.deps.appendResult
51
- * @param {(text:string)=>object} input.deps.score
52
- * @param {() => number} input.deps.now
53
- * @param {string} input.deps.provider
54
- * @param {object} input.deps.parent
55
- * @param {number} [input.deps.votes]
56
- * @param {(row:object)=>void} [input.deps.diag]
57
- * @returns {Promise<{job:object, changed:boolean}>}
58
- */
59
- export async function stepJob(input) {
60
- const { ctx, projectDir, deps } = input;
61
- let job = input.job;
62
- const children = {};
63
- for (const childId of [job.generatorChildId, ...(job.judgeChildIds ?? [])].filter(Boolean)) {
64
- children[childId] = observeChild(ctx, childId, job.outputStart);
65
- }
66
- const plan = planJobStep(job, { children, now: deps.now() });
67
- if (plan.next === job.state && plan.actions.every((action) => action.type === 'await')) {
68
- return { job, changed: false };
69
- }
70
- for (const action of plan.actions) {
71
- if (action.type === 'fail') {
72
- await rollback({ deps, job, projectDir });
73
- job = { ...job, state: 'failed', error: action.payload?.reason ?? 'failed', updatedAt: deps.now() };
74
- await recordFail({ deps, job });
75
- deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: job.error });
76
- break;
77
- } else if (action.type === 'apply-candidate') {
78
- // 备份基线 → 写入候选 → 校验(超限时回滚)。
79
- const before = deps.readText(job.skillPath);
80
- const validation = validateCandidate({ before, after: action.payload?.text ?? '' });
81
- if (!validation.ok) {
82
- await rollback({ deps, job, projectDir });
83
- job = { ...job, state: 'failed', error: validation.reason, updatedAt: deps.now() };
84
- await recordFail({ deps, job });
85
- deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: validation.reason });
86
- break;
87
- }
88
- // 不是每个 vcs 适配器都有 backup(git 适配器就没有):无脑调用会 TypeError,
89
- // job 卡到 TTL 才失败。
90
- const backup = typeof deps.vcs?.backup === 'function' ? await deps.vcs.backup(job.skillPath, before) : null;
91
- job = { ...job, before, candidate: action.payload.text, backup };
92
- // 先落盘再改 live:中途崩溃时 job 里已有 before/backup,可据此回滚;
93
- // 反过来(先改 live)会让磁盘上的技能停在未审候选且无任何记录。
94
- writeJob(projectDir, job);
95
- deps.writeText(job.skillPath, action.payload.text);
96
- } else if (action.type === 'start-judges') {
97
- const votes = normalizeVoteCount(deps.votes ?? 3);
98
- const parentInfo = typeof deps.ensureParent === 'function' ? await deps.ensureParent() : null;
99
- const parent = parentInfo?.agent ?? deps.parent;
100
- const judgeChildIds = [];
101
- const judgeOrders = [];
102
- for (let index = 0; index < votes; index++) {
103
- const order = Math.random() < 0.5 ? 'ab' : 'ba';
104
- const { prompt } = buildPairPrompt({ before: job.before, after: job.candidate, order });
105
- const child = await deps.startChild(`skillopt-judge-${job.id}-${index + 1}`, {
106
- provider: deps.provider,
107
- request: {
108
- cwd: projectDir,
109
- prompt: [{ type: 'text', text: prompt }],
110
- parent,
111
- },
112
- delivery: 'parent',
113
- signal: new AbortController().signal,
114
- });
115
- judgeChildIds.push(child.childId);
116
- judgeOrders.push({ childId: child.childId, order });
117
- }
118
- job = { ...job, state: 'judging', judgeChildIds, judgeOrders, updatedAt: deps.now() };
119
- } else if (action.type === 'finish') {
120
- const votes = [];
121
- for (const row of action.payload?.votes ?? []) {
122
- const mapping = (job.judgeOrders ?? []).find((entry) => entry.childId === row.childId);
123
- const parsed = parseJudgeOutput(row.text);
124
- const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping?.order === 'ba' });
125
- votes.push({ childId: row.childId, vote, margin: parsed?.margin ?? null, reason: parsed?.reason ?? '' });
126
- }
127
- const decision = decideByMajority(votes.map((entry) => entry.vote));
128
- const kept = decision.verdict === 'keep';
129
- if (!kept) await rollback({ deps, job, projectDir });
130
- job = { ...job, state: 'done', decision: { ...decision, votes, kept }, updatedAt: deps.now() };
131
- const afterText = kept ? job.candidate : job.before;
132
- const beforeScore = deps.score(job.before)?.total ?? null;
133
- const afterScore = deps.score(afterText)?.total ?? null;
134
- await deps.appendResult([
135
- new Date(deps.now()).toISOString().slice(0, 19),
136
- deps.vcs.kind === 'git' ? (job.commit ?? '-') : '-',
137
- job.skillName,
138
- String(beforeScore ?? '-'),
139
- String(afterScore ?? '-'),
140
- kept ? 'keep' : 'revert',
141
- job.dimension ?? '-',
142
- `${decision.better}-${decision.worse} ${decision.verdict}`,
143
- 'paired',
144
- sha12(job.candidate),
145
- ].join('\t'));
146
- deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
147
- }
148
- }
149
- // 失败/完成是终态:plan 是在 switch 之前算的,若拿它回写就会把刚判死的 job
150
- // 复活成 judging,下一轮再拿一个未应用的候选写假记录。
151
- const terminal = job.state === 'failed' || job.state === 'done';
152
- if (!terminal && plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
153
- writeJob(projectDir, job);
154
- return { job, changed: true };
155
- }
156
-
157
- /** failed 终态也必须成行(results.tsv ≡ jobs 盘件机判行;257-#60②)。 */
158
- async function recordFail({ deps, job }) {
159
- await deps.appendResult([
160
- new Date(deps.now()).toISOString().slice(0, 19),
161
- '-',
162
- job.skillName ?? '-',
163
- '-',
164
- '-',
165
- 'failed',
166
- job.dimension ?? '-',
167
- String(job.error ?? 'failed').replace(/[\t\r\n]+/g, ' '),
168
- 'paired',
169
- typeof job.candidate === 'string' ? sha12(job.candidate) : '-',
170
- ].join('\t'));
171
- }
172
-
173
- async function rollback({ deps, job, projectDir }) {
174
- if (job?.candidate === undefined || job?.before === undefined) return;
175
- // 回滚前必须确认 live 仍是**我们写下的那个候选**:评审期间可能有人手改,
176
- // 无条件把陈旧的 before 写回去会覆盖掉那次人工修改(且原子性无从谈起)。
177
- let current = null;
178
- try {
179
- current = deps.readText ? deps.readText(job.skillPath) : null;
180
- } catch {
181
- current = null;
182
- }
183
- if (typeof current === 'string' && sha12(current) !== sha12(job.candidate)) {
184
- deps.diag?.({ ev: 'skillopt.rollback.skipped', jobId: job.id, reason: 'live file changed since the candidate was applied' });
185
- return;
186
- }
187
- try {
188
- if (deps.vcs.kind === 'file' && typeof job.backup === 'string') {
189
- await deps.vcs.restore(job.skillPath, job.backup);
190
- } else {
191
- deps.writeText(job.skillPath, job.before);
192
- }
193
- } catch { /* best effort */ }
194
- }
195
-
196
- /** 收割全部 pending job(tick 入口)。 */
197
- export async function reconcileJobs(input) {
198
- // 评审通道的 job(带 reviewTaskId)由 skillopt_jobs 收集,不走子代理 reconcile:
199
- // 否则 reconcile 会在评审官回帖前把它判成 inconclusive done。
200
- const jobs = listJobs(input.projectDir).filter((job) => (job.state === 'generating' || job.state === 'judging') && typeof job.reviewTaskId !== 'string');
201
- const results = [];
202
- for (const job of jobs) {
203
- results.push(await stepJob({ ...input, job }));
204
- }
205
- return results;
206
- }
207
-
208
- export { isChildSettled, readJob, writeJob };
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
+ import { sha12 } from './proposal-store.js';
13
+
14
+ /** 观测一个在飞子代理:状态 + 会话事件(同步,供状态机使用)。 */
15
+ export function observeChild(ctx, childId, outputStart) {
16
+ // 三条路径兜底:agents(活 agent)→ subagents activation → sessions。
17
+ const agent = ctx.get('agents')?.get?.(childId);
18
+ if (agent !== undefined && agent !== null) {
19
+ let events = [];
20
+ try {
21
+ events = agent.session?.snapshotEvents?.(outputStart) ?? [];
22
+ } catch { /* session may be gone */ }
23
+ return { status: agent.status ?? null, events, text: extractAssistantText(events) };
24
+ }
25
+ // 刚启动的子代理可能不在 agents registry:用 sessions 服务读会话事件。
26
+ const session = ctx.get('sessions')?.get?.(childId);
27
+ if (session !== undefined && session !== null) {
28
+ let events = [];
29
+ try {
30
+ events = session.snapshotEvents?.(outputStart) ?? [];
31
+ } catch { /* session may be gone */ }
32
+ return { status: null, events, text: extractAssistantText(events) };
33
+ }
34
+ // 完全查不到:不得视为已完成(由 TTL 兜底),调用方会继续等待。
35
+ return { status: 'running', events: [] };
36
+ }
37
+
38
+ /**
39
+ * 推进一个 job 一步。
40
+ *
41
+ * @param {object} input
42
+ * @param {object} input.ctx DSH context
43
+ * @param {string} input.projectDir
44
+ * @param {object} input.job job 记录
45
+ * @param {object} input.deps
46
+ * @param {(name:string, spec:object)=>Promise<object>} input.deps.startChild 启动子代理(返回 {childId})
47
+ * @param {(path:string, text:string)=>void} input.deps.writeText
48
+ * @param {(path:string)=>string} input.deps.readText
49
+ * @param {object} input.deps.vcs makeVcs 结果
50
+ * @param {(line:string)=>Promise<void>} input.deps.appendResult
51
+ * @param {(text:string)=>object} input.deps.score
52
+ * @param {() => number} input.deps.now
53
+ * @param {string} input.deps.provider
54
+ * @param {object} input.deps.parent
55
+ * @param {number} [input.deps.votes]
56
+ * @param {(row:object)=>void} [input.deps.diag]
57
+ * @returns {Promise<{job:object, changed:boolean}>}
58
+ */
59
+ export async function stepJob(input) {
60
+ const { ctx, projectDir, deps } = input;
61
+ let job = input.job;
62
+ const children = {};
63
+ for (const childId of [job.generatorChildId, ...(job.judgeChildIds ?? [])].filter(Boolean)) {
64
+ children[childId] = observeChild(ctx, childId, job.outputStart);
65
+ }
66
+ const plan = planJobStep(job, { children, now: deps.now() });
67
+ if (plan.next === job.state && plan.actions.every((action) => action.type === 'await')) {
68
+ return { job, changed: false };
69
+ }
70
+ for (const action of plan.actions) {
71
+ if (action.type === 'fail') {
72
+ await rollback({ deps, job, projectDir });
73
+ job = { ...job, state: 'failed', error: action.payload?.reason ?? 'failed', updatedAt: deps.now() };
74
+ await recordFail({ deps, job });
75
+ deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: job.error });
76
+ break;
77
+ } else if (action.type === 'apply-candidate') {
78
+ // 备份基线 → 写入候选 → 校验(超限时回滚)。
79
+ const before = deps.readText(job.skillPath);
80
+ const validation = validateCandidate({ before, after: action.payload?.text ?? '' });
81
+ if (!validation.ok) {
82
+ await rollback({ deps, job, projectDir });
83
+ job = { ...job, state: 'failed', error: validation.reason, updatedAt: deps.now() };
84
+ await recordFail({ deps, job });
85
+ deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: validation.reason });
86
+ break;
87
+ }
88
+ // 不是每个 vcs 适配器都有 backup(git 适配器就没有):无脑调用会 TypeError,
89
+ // job 卡到 TTL 才失败。
90
+ const backup = typeof deps.vcs?.backup === 'function' ? await deps.vcs.backup(job.skillPath, before) : null;
91
+ job = { ...job, before, candidate: action.payload.text, backup };
92
+ // 先落盘再改 live:中途崩溃时 job 里已有 before/backup,可据此回滚;
93
+ // 反过来(先改 live)会让磁盘上的技能停在未审候选且无任何记录。
94
+ writeJob(projectDir, job);
95
+ deps.writeText(job.skillPath, action.payload.text);
96
+ } else if (action.type === 'start-judges') {
97
+ const votes = normalizeVoteCount(deps.votes ?? 3);
98
+ const parentInfo = typeof deps.ensureParent === 'function' ? await deps.ensureParent() : null;
99
+ const parent = parentInfo?.agent ?? deps.parent;
100
+ const judgeChildIds = [];
101
+ const judgeOrders = [];
102
+ for (let index = 0; index < votes; index++) {
103
+ const order = Math.random() < 0.5 ? 'ab' : 'ba';
104
+ const { prompt } = buildPairPrompt({ before: job.before, after: job.candidate, order });
105
+ const child = await deps.startChild(`skillopt-judge-${job.id}-${index + 1}`, {
106
+ provider: deps.provider,
107
+ request: {
108
+ cwd: projectDir,
109
+ prompt: [{ type: 'text', text: prompt }],
110
+ parent,
111
+ },
112
+ delivery: 'caller',
113
+ signal: new AbortController().signal,
114
+ });
115
+ judgeChildIds.push(child.childId);
116
+ judgeOrders.push({ childId: child.childId, order });
117
+ }
118
+ job = { ...job, state: 'judging', judgeChildIds, judgeOrders, updatedAt: deps.now() };
119
+ } else if (action.type === 'finish') {
120
+ const votes = [];
121
+ for (const row of action.payload?.votes ?? []) {
122
+ const mapping = (job.judgeOrders ?? []).find((entry) => entry.childId === row.childId);
123
+ const parsed = parseJudgeOutput(row.text);
124
+ const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping?.order === 'ba' });
125
+ votes.push({ childId: row.childId, vote, margin: parsed?.margin ?? null, reason: parsed?.reason ?? '' });
126
+ }
127
+ const decision = decideByMajority(votes.map((entry) => entry.vote));
128
+ const kept = decision.verdict === 'keep';
129
+ if (!kept) await rollback({ deps, job, projectDir });
130
+ job = { ...job, state: 'done', decision: { ...decision, votes, kept }, updatedAt: deps.now() };
131
+ const afterText = kept ? job.candidate : job.before;
132
+ const beforeScore = deps.score(job.before)?.total ?? null;
133
+ const afterScore = deps.score(afterText)?.total ?? null;
134
+ await deps.appendResult([
135
+ new Date(deps.now()).toISOString().slice(0, 19),
136
+ deps.vcs.kind === 'git' ? (job.commit ?? '-') : '-',
137
+ job.skillName,
138
+ String(beforeScore ?? '-'),
139
+ String(afterScore ?? '-'),
140
+ kept ? 'keep' : 'revert',
141
+ job.dimension ?? '-',
142
+ `${decision.better}-${decision.worse} ${decision.verdict}`,
143
+ 'paired',
144
+ sha12(job.candidate),
145
+ ].join('\t'));
146
+ deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
147
+ }
148
+ }
149
+ // 失败/完成是终态:plan 是在 switch 之前算的,若拿它回写就会把刚判死的 job
150
+ // 复活成 judging,下一轮再拿一个未应用的候选写假记录。
151
+ const terminal = job.state === 'failed' || job.state === 'done';
152
+ if (!terminal && plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
153
+ writeJob(projectDir, job);
154
+ return { job, changed: true };
155
+ }
156
+
157
+ /** failed 终态也必须成行(results.tsv ≡ jobs 盘件机判行;257-#60②)。 */
158
+ async function recordFail({ deps, job }) {
159
+ await deps.appendResult([
160
+ new Date(deps.now()).toISOString().slice(0, 19),
161
+ '-',
162
+ job.skillName ?? '-',
163
+ '-',
164
+ '-',
165
+ 'failed',
166
+ job.dimension ?? '-',
167
+ String(job.error ?? 'failed').replace(/[\t\r\n]+/g, ' '),
168
+ 'paired',
169
+ typeof job.candidate === 'string' ? sha12(job.candidate) : '-',
170
+ ].join('\t'));
171
+ }
172
+
173
+ async function rollback({ deps, job, projectDir }) {
174
+ if (job?.candidate === undefined || job?.before === undefined) return;
175
+ // 回滚前必须确认 live 仍是**我们写下的那个候选**:评审期间可能有人手改,
176
+ // 无条件把陈旧的 before 写回去会覆盖掉那次人工修改(且原子性无从谈起)。
177
+ let current = null;
178
+ try {
179
+ current = deps.readText ? deps.readText(job.skillPath) : null;
180
+ } catch {
181
+ current = null;
182
+ }
183
+ if (typeof current === 'string' && sha12(current) !== sha12(job.candidate)) {
184
+ deps.diag?.({ ev: 'skillopt.rollback.skipped', jobId: job.id, reason: 'live file changed since the candidate was applied' });
185
+ return;
186
+ }
187
+ try {
188
+ if (deps.vcs.kind === 'file' && typeof job.backup === 'string') {
189
+ await deps.vcs.restore(job.skillPath, job.backup);
190
+ } else {
191
+ deps.writeText(job.skillPath, job.before);
192
+ }
193
+ } catch { /* best effort */ }
194
+ }
195
+
196
+ /** 收割全部 pending job(tick 入口)。 */
197
+ export async function reconcileJobs(input) {
198
+ // 评审通道的 job(带 reviewTaskId)由 skillopt_jobs 收集,不走子代理 reconcile:
199
+ // 否则 reconcile 会在评审官回帖前把它判成 inconclusive done。
200
+ const jobs = listJobs(input.projectDir).filter((job) => (job.state === 'generating' || job.state === 'judging') && typeof job.reviewTaskId !== 'string');
201
+ const results = [];
202
+ for (const job of jobs) {
203
+ results.push(await stepJob({ ...input, job }));
204
+ }
205
+ return results;
206
+ }
207
+
208
+ export { isChildSettled, readJob, writeJob };
@@ -49,7 +49,7 @@ export async function judgePair(input) {
49
49
  provider,
50
50
  label: `skillopt-judge-${index + 1}`,
51
51
  request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
52
- delivery: 'parent',
52
+ delivery: 'caller',
53
53
  signal: new AbortController().signal,
54
54
  }));
55
55
  const text = await awaitActivationText(activation, { timeoutMs: JUDGE_TIMEOUT_MS });
@@ -84,7 +84,7 @@ export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
84
84
  provider,
85
85
  label: `skillopt-optimize-${round}`,
86
86
  request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
87
- delivery: 'parent',
87
+ delivery: 'caller',
88
88
  signal: new AbortController().signal,
89
89
  }));
90
90
  return { childId: activation.childId, outputStart: activation.outputStart ?? null };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.109",
3
+ "version": "0.4.111",
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",
@@ -75,6 +75,8 @@ With `backend=handoff` the engine stops with exit 3 whenever model calls need
75
75
  answers (`<project>/.skillopt-sleep-handoff/pending.json`). The AI team answers
76
76
  them automatically: on each PMO tick, one fresh one-shot reviewer subagent per
77
77
  call writes `answers/<id>.md`, then the scheduled `run.ps1` is rerun to resume.
78
+ The answering subagent runs outside the workspace and every tool call it makes
79
+ is refused, so a replayed task is answered in text, never carried out for real.
78
80
  Do not answer these prompts from a member session — its history contaminates the
79
81
  held-out gate. Exit 3 in the task result means "waiting for answers", not failure.
80
82