@suifei/dsh-ai-team 0.4.110 → 0.4.112

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,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.112 - 2026-11-16
4
+
5
+ **任务记录同样打开即在最新回帖(#33 后续)**
6
+
7
+ - 实机:0.4.108 起主对话已贴底,右侧任务记录(Thread 面板)打开仍停在顶部的完成信息,最新回帖要手动拖到底;
8
+ - 跟随接线抽成 `useFollowLatest`(主对话与任务记录共用一份,内部仍是 `createStreamFollower`),任务记录按
9
+ 任务切换重置贴底,新回帖或状态变化时按是否停在底部决定跟随,上翻时底部浮出「↓ N 条新消息」;
10
+ 内容变高改为观察滚动容器的每个直接子块(任务记录不是单一内层容器);
11
+ - 测试:`test/client-stream-follow.test.js` 新增接线契约 1 例,`test/client.render.test.js` 增加「打开任务后 Thread
12
+ 面板渲染且带跟随接线」(换回旧 client.js 两处即失败);
13
+
14
+ ## 0.4.111 - 2026-11-16
15
+
16
+ **SkillOpt 一次性子代理不再逐个唤醒 PMO**
17
+
18
+ - 作答、判官、生成子代理用 `delivery: 'parent'` 启动;官方语义是 parent 投递「通知父会话的模型」,caller
19
+ 投递「只把结果交回调用方」。il2c 实机:PMO 宿主会话 16:30 起收到 104 条「子智能体已完成任务」,开了 51 个
20
+ 回合(单回合用量 404K tok),主对话被逐条点评夜间环的内容淹没,会话头显示「112 个子智能体」;
21
+ - 4 处 SkillOpt 一次性子代理改为 `delivery: 'caller'`(结果仍经 `activation.result` / 会话事件取回);
22
+ 成员激活保留 `parent`——成员结果本就要交给 PMO;
23
+ - 宿主文档:本地子代理总会进入父会话目录,`dispose` 后仍在目录里,子智能体计数不会因此下降;
24
+ - 测试:`test/stop-guard.test.js` 新增投递契约 1 例(换回旧实现即失败),`darwin-alignment` 判官断言改为 caller;
25
+
3
26
  ## 0.4.110 - 2026-11-16
4
27
 
5
28
  **SkillOpt 一次性子代理只凭题面作答,不在真实工作区动手**
package/client.js CHANGED
@@ -2250,6 +2250,13 @@ window.__ModuleLoader__.load({
2250
2250
  const headSeq = thread?.headSeq ?? thread?.entries?.length ?? 0;
2251
2251
  const stale = replyBase !== null && replyBase !== undefined && headSeq > replyBase;
2252
2252
  const entries = Array.isArray(thread?.entries) ? thread.entries : [];
2253
+ // #33 任务记录同样打开即在最新回帖:换任务重置,新回帖到达时按是否停在底部决定跟随。
2254
+ const threadFollow = useFollowLatest({
2255
+ key: task.id,
2256
+ shown: !converting,
2257
+ count: entries.length,
2258
+ tail: entries.length > 0 ? String(entries[entries.length - 1]?.seq ?? '') + '|' + task.status : task.status,
2259
+ });
2253
2260
  return h('aside', { className: 'at-right', role: 'complementary', 'aria-label': t('threadAria'), tabIndex: -1, ref: panelRef },
2254
2261
  h('div', { className: 'at-rhead' },
2255
2262
  h('div', { className: 'at-rh' },
@@ -2264,7 +2271,7 @@ window.__ModuleLoader__.load({
2264
2271
  h('button', { className: 'at-noteclose', type: 'button', 'aria-label': t('dismiss'), title: t('dismiss'), onClick: onDismissNote }, h(Ico, { name: 'close', size: 12 }))) : null,
2265
2272
  converting
2266
2273
  ? h(ConvertForm, { t, project, task, thread, title: convert.title, dod: convert.dod, onTitle: convert.onTitle, onDod: convert.onDod, onCancel: convert.onCancel, onSubmit: convert.onSubmit })
2267
- : h('div', { className: 'at-rbody' },
2274
+ : h('div', { className: 'at-rbody', ref: threadFollow.ref, onScroll: threadFollow.onScroll },
2268
2275
  stale ? h(ConflictBanner, { t, thread, baseSeq: replyBase, headSeq, onContinue }) : null,
2269
2276
  task.status === 'done' ? h(DoneSummary, { t, task }) : h(TaskDetail, { t, task }),
2270
2277
  entries.length
@@ -2311,6 +2318,7 @@ window.__ModuleLoader__.load({
2311
2318
  h('span', { className: 'at-peopleprojectname' }, '#' + event.seq),
2312
2319
  h('span', { className: 'at-peoplestate' }, event.type),
2313
2320
  h('span', { className: 'at-peopletasks' }, fmtTime(event.at) + actorSuffix(event.actor)))))) : null,
2321
+ !converting ? h(JumpToLatest, { t, unseen: threadFollow.unseen, onJump: threadFollow.jump }) : null,
2314
2322
  !converting ? h('div', { className: 'at-rfoot' },
2315
2323
  h('div', { className: 'at-box at-rbox' },
2316
2324
  h('textarea', {
@@ -2666,6 +2674,60 @@ window.__ModuleLoader__.load({
2666
2674
  }
2667
2675
  // </stream-follow>
2668
2676
 
2677
+ /**
2678
+ * 滚动容器「跟随最新」的 React 接线(主对话、任务记录共用这一份)。
2679
+ * key 变化即重置并贴底(切项目/标签/任务);
2680
+ * shown 容器在场时才量尺寸;
2681
+ * count/tail 条目数与最后一条的标识,变化即按 follower 判定贴底或累计未读。
2682
+ * 只用 useLayoutEffect:尺寸读写要在绘制前完成,避免先闪到顶部再跳到底。
2683
+ */
2684
+ function useFollowLatest({ key, shown, count, tail }) {
2685
+ const ref = React.useRef(null);
2686
+ const followerRef = React.useRef(null);
2687
+ if (followerRef.current === null) followerRef.current = createStreamFollower();
2688
+ const [unseen, setUnseen] = React.useState(0);
2689
+ React.useLayoutEffect(() => {
2690
+ followerRef.current.reset();
2691
+ setUnseen(0);
2692
+ }, [key]);
2693
+ React.useLayoutEffect(() => {
2694
+ const el = ref.current;
2695
+ if (!shown || el === null || el === undefined) return;
2696
+ const step = followerRef.current.onContent(el, count);
2697
+ if (step.scrollTo !== null) el.scrollTop = step.scrollTo;
2698
+ setUnseen(step.unseen);
2699
+ }, [key, shown, count, tail]);
2700
+ React.useLayoutEffect(() => {
2701
+ const el = ref.current;
2702
+ if (!shown || el === null || el === undefined || typeof ResizeObserver !== 'function') return undefined;
2703
+ // 观察每个直接子块:容器自身高度固定,内容变高(卡片展开、字体晚到)只体现在子块上。
2704
+ const observer = new ResizeObserver(() => {
2705
+ const to = followerRef.current.onResize(el);
2706
+ if (to !== null) el.scrollTop = to;
2707
+ });
2708
+ for (const child of Array.from(el.children ?? [])) observer.observe(child);
2709
+ return () => observer.disconnect();
2710
+ }, [key, shown, count]);
2711
+ return {
2712
+ ref,
2713
+ unseen,
2714
+ onScroll: (event) => setUnseen(followerRef.current.onScroll(event.currentTarget)),
2715
+ jump: () => {
2716
+ const el = ref.current;
2717
+ if (el !== null && el !== undefined) el.scrollTop = followerRef.current.jump(el);
2718
+ setUnseen(0);
2719
+ },
2720
+ };
2721
+ }
2722
+
2723
+ /** 「↓ N 条新消息」:零高度锚点 + 绝对定位按钮,不进文档流,不改变任何滚动位置。 */
2724
+ function JumpToLatest({ t, unseen, onJump }) {
2725
+ if (!(unseen > 0)) return null;
2726
+ return h('div', { className: 'at-streamjumpanchor' },
2727
+ h('button', { className: 'at-streamjump', type: 'button', onClick: onJump },
2728
+ h(Ico, { name: 'down', size: 12 }), tf(t, 'streamUnseen', { count: unseen })));
2729
+ }
2730
+
2669
2731
  function Workbench({ t, ctx }) {
2670
2732
  const [phase, setPhase] = React.useState('loading');
2671
2733
  const [data, setData] = React.useState(null);
@@ -2820,42 +2882,18 @@ window.__ModuleLoader__.load({
2820
2882
  const replyRef = React.useRef(null);
2821
2883
  const triggerRef = React.useRef(null);
2822
2884
  const mobileRef = React.useRef(null);
2823
- // #33 主对话跟随最新(算法见 createStreamFollower)。
2824
- const streamRef = React.useRef(null);
2825
- const followerRef = React.useRef(null);
2826
- if (followerRef.current === null) followerRef.current = createStreamFollower();
2827
- const [streamUnseen, setStreamUnseen] = React.useState(0);
2885
+ // #33 主对话跟随最新(useFollowLatest / createStreamFollower)。
2828
2886
  const streamItems = Array.isArray(data?.stream) ? data.stream : [];
2829
- const streamTail = streamItems.length > 0 ? streamItems[streamItems.length - 1]?.id ?? '' : '';
2830
- const streamShown = scope === 'project' && tab === 'main';
2831
- React.useLayoutEffect(() => {
2832
- followerRef.current.reset();
2833
- setStreamUnseen(0);
2834
- }, [projectId, scope, tab]);
2835
- React.useLayoutEffect(() => {
2836
- const el = streamRef.current;
2837
- if (!streamShown || el === null || el === undefined) return;
2838
- const step = followerRef.current.onContent(el, streamItems.length);
2839
- if (step.scrollTo !== null) el.scrollTop = step.scrollTo;
2840
- setStreamUnseen(step.unseen);
2841
- }, [projectId, streamShown, streamItems.length, streamTail]);
2842
- React.useLayoutEffect(() => {
2843
- const el = streamRef.current;
2844
- const inner = el?.firstElementChild;
2845
- if (!streamShown || inner === null || inner === undefined || typeof ResizeObserver !== 'function') return undefined;
2846
- const observer = new ResizeObserver(() => {
2847
- const to = followerRef.current.onResize(el);
2848
- if (to !== null) el.scrollTop = to;
2849
- });
2850
- observer.observe(inner);
2851
- return () => observer.disconnect();
2852
- }, [projectId, streamShown, data !== null]);
2853
- const onStreamScroll = (event) => setStreamUnseen(followerRef.current.onScroll(event.currentTarget));
2854
- const jumpToLatest = () => {
2855
- const el = streamRef.current;
2856
- if (el !== null && el !== undefined) el.scrollTop = followerRef.current.jump(el);
2857
- setStreamUnseen(0);
2858
- };
2887
+ const mainFollow = useFollowLatest({
2888
+ key: projectId + '|' + scope + '|' + tab,
2889
+ shown: scope === 'project' && tab === 'main' && data !== null,
2890
+ count: streamItems.length,
2891
+ tail: streamItems.length > 0 ? streamItems[streamItems.length - 1]?.id ?? '' : '',
2892
+ });
2893
+ const streamRef = mainFollow.ref;
2894
+ const streamUnseen = mainFollow.unseen;
2895
+ const onStreamScroll = mainFollow.onScroll;
2896
+ const jumpToLatest = mainFollow.jump;
2859
2897
  // R-08 快捷键:composer 聚焦句柄 + `?` 帮助浮层开关。
2860
2898
  const composerInputRef = React.useRef(null);
2861
2899
  const [shortcutsOpen, setShortcutsOpen] = React.useState(false);
@@ -4314,12 +4352,7 @@ window.__ModuleLoader__.load({
4314
4352
  onSetWorkspace: openWorkspaceEditor,
4315
4353
  onExample: () => setDraft(t('emptyStreamExample')),
4316
4354
  }))),
4317
- // 零高度锚点 + 绝对定位按钮:不进文档流,不改变任何滚动位置。
4318
- streamUnseen > 0
4319
- ? h('div', { className: 'at-streamjumpanchor' },
4320
- h('button', { className: 'at-streamjump', type: 'button', onClick: jumpToLatest },
4321
- h(Ico, { name: 'down', size: 12 }), tf(t, 'streamUnseen', { count: streamUnseen })))
4322
- : null);
4355
+ h(JumpToLatest, { t, unseen: streamUnseen, onJump: jumpToLatest }));
4323
4356
 
4324
4357
  return h('div', { className: 'at-root', role: 'region', 'aria-label': t('panel') },
4325
4358
  h('div', { className: 'at-top' },
package/index.js CHANGED
@@ -1168,7 +1168,7 @@ export function apply(ctx, config = {}) {
1168
1168
  provider: resolveSubagentProviderName(serviceOf(ctx, 'subagents'), config?.subagentProviderName),
1169
1169
  label,
1170
1170
  request: { cwd: answerCwd, prompt: [{ type: 'text', text: request.prompt }], parent: parentInfo?.agent },
1171
- delivery: 'parent',
1171
+ delivery: 'caller',
1172
1172
  signal: new AbortController().signal,
1173
1173
  }));
1174
1174
  const childId = activation.childId;
@@ -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.110",
3
+ "version": "0.4.112",
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",