@suifei/dsh-ai-team 0.4.91 → 0.4.93

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,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.93 - 2026-11-14
4
+
5
+ **rc.2+ 宿主上成员能激活了:`startActivation` 同时给出扁平与嵌套两种 spec**
6
+
7
+ DSH rc.2 起 `SubagentActivationSpec extends SubagentStartRequest`——`parent` / `cwd` / `prompt` /
8
+ `agentPreset` / `agentOptions` 平铺在 spec 顶层;rc.1(桌面版)仍读嵌套的 `spec.request.*`。插件只给嵌套
9
+ 形状,rc.2 / rc.3 上 `spec.parent` 为 undefined,每次激活都以「subagent creation requires the exact live
10
+ parent agent」失败(成员、技能评审、技能优化子代理全部不可用)。
11
+
12
+ - `lib/runtime/activation-spec.js` `activationSpec`:请求字段既平铺在顶层、也保留在 `request` 下;各宿主
13
+ 只读自己的字段、忽略另一份(rc.1 / rc.3 源码核对)。成员激活、技能评审(两处)、技能优化共 5 处调用统一走它;
14
+ - 测试:`node --test` **332 通过 / 1 跳过**;`member-activation` 新增双形状读取 1 条;
15
+ - E2E(全新隔离 DSH_HOME,成员全部 qwen,「用 js 写 2 种排序算法」):rc.3 / rc.2 / rc.1 三个宿主均在 2 分钟内
16
+ 完成「PMO 建卡 → 成员激活认领 → 提交 → 验收 → wave_done 汇报」,之后静默(rc.3 观察 12 分钟账本不再增长);
17
+ rc.3 / rc.2 失败仅启动期 2 条注册表未就绪,rc.1 另有 1 条重复认领的业务拒绝。修复前 rc.2+ 激活 100% 失败。
18
+ ## 0.4.92 - 2026-11-14
19
+
20
+ **会议并发回帖不再被拒:迟到的回帖照收,并把错过的发言带回去;PMO 叫不醒就不开会**
21
+
22
+ 会议/复盘时多名成员读同一个 Thread head 后同时回帖,旧规则(`baseSeq` 必须等于 head,否则
23
+ `E_STALE_REPLY`)只放行第一条,其余重读、重写、再次落败——成员原话「三次回帖均因会议并发被拒」,
24
+ r09 一轮 46 次,失败计数全部来自这里。回帖本身没有错,只是晚了。
25
+
26
+ - `lib/domain/thread.js` `appendReply`:不再拒绝落后的 `baseSeq`,条目照记自己的 `baseSeq`,并返回
27
+ `missed`(读取之后新增的条目);超前的 `baseSeq` 仍是 `E_INVALID_ARGUMENT`。`E_STALE_REPLY` 错误码移除;
28
+ - `lib/host/member-tools.js` `reply`:有错过的他人发言时返回 `missed`(正文截 2000 字)与提示「只有它们
29
+ 改变了你的结论才再补一条」;自己的旧帖不算错过;
30
+ - PMO 叫不醒就不开会(`lib/host/waker.js` `pmo/continue`):r13 中 PMO 因 AUTH 失败,定时推进仍把其余 5 名
31
+ 成员拉进会议,无人主持、无人收口。现在 owner 不可唤醒(failed / retired / 缺失)时整场会议不规划;
32
+ - 测试:`node --test` **331 通过 / 1 跳过**;`waker` 新增无主持会议 1 条,`domain` 改写 1 条,新增 `thread-meeting`(三人并发全部落帖、
33
+ 迟到者拿到错过的两条)。
34
+ - E2E(隔离 DSH_HOME,项目「排序-B」派一种排序,12 分钟):线程 7 条回帖中 2 条迟到(seq 4 基于 2、seq 5
35
+ 基于 3)全部落帖,`E_STALE_REPLY` 0、`dispatch.fail` 0(旧规则下这 2 条会被拒并重写)。
36
+
3
37
  ## 0.4.91 - 2026-11-14
4
38
 
5
39
  **停止即中断成员回合;重启不再惊动已静默的团队;已绑定的 PMO 会话启动即归入工作区**
package/index.js CHANGED
@@ -23,6 +23,7 @@ import { migrateLegacyNamespace, resolveProfile } from './lib/ledger/namespace.j
23
23
  import { ids } from './lib/domain/ids.js';
24
24
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
25
25
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
26
+ import { activationSpec } from './lib/runtime/activation-spec.js';
26
27
  import { repairArchivedHosts as repairHostSessions } from './lib/runtime/host-repair.js';
27
28
  import { classifyLlmFailure, nextRequestAttempt, retryDecision } from './lib/runtime/failure-policy.js';
28
29
  import { memberIdentity } from './lib/domain/member-profile.js';
@@ -1119,7 +1120,7 @@ export function apply(ctx, config = {}) {
1119
1120
  startChild: async (label, spec) => {
1120
1121
  // 必须走 serviceOf:这里不在 activateMember/wakeFromResult 的
1121
1122
  // 词法作用域内,裸写 subagents 会在判官轮抛 ReferenceError。
1122
- const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
1123
+ const child = await serviceOf(ctx, 'subagents').startActivation(activationSpec({ ...spec, label }));
1123
1124
  return { childId: child.childId, outputStart: child.outputStart ?? null };
1124
1125
  },
1125
1126
  readText: (file) => readFileSync(file, 'utf8'),
@@ -1567,7 +1568,7 @@ export function apply(ctx, config = {}) {
1567
1568
  ensureParent: () => ensureParent(),
1568
1569
  votes: config.skilloptJudgeVotes ?? 3,
1569
1570
  startChild: async (label, spec) => {
1570
- const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
1571
+ const child = await serviceOf(ctx, 'subagents').startActivation(activationSpec({ ...spec, label }));
1571
1572
  return { childId: child.childId, outputStart: child.outputStart ?? null };
1572
1573
  },
1573
1574
  readText: (file) => readFileSync(file, 'utf8'),
@@ -24,7 +24,6 @@ export const ERRORS = {
24
24
  BLOCKED: 'E_TASK_BLOCKED',
25
25
  NOT_READY: 'E_TASK_NOT_READY',
26
26
  NOT_ELIGIBLE: 'E_REVIEWER_NOT_ELIGIBLE',
27
- STALE_REPLY: 'E_STALE_REPLY',
28
27
  LIMIT: 'E_LIMIT',
29
28
  IRREVERSIBLE_CONFIRM: 'E_IRREVERSIBLE_CONFIRM_REQUIRED',
30
29
  INVALID_ARGUMENT: 'E_INVALID_ARGUMENT',
@@ -1,54 +1,46 @@
1
- import { ERRORS, fail } from './errors.js';
2
-
3
- /** A thread is one append-only conversation attached to a Task. */
4
- export function createThread(taskId) {
5
- return { taskId, headSeq: 0, entries: [] };
6
- }
7
-
8
- /**
9
- * Append a reply. Agents must reply against the current head; a stale baseSeq
10
- * is rejected with the entries that changed since the reader last looked.
11
- * Human replies bypass the check (the Human sees the live thread).
12
- */
13
- export function appendReply(thread, input, options = {}) {
14
- const body = typeof input.body === 'string' ? input.body.trim() : '';
15
- if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'reply body is required');
16
- if (body.length > 16_384) fail(ERRORS.INVALID_ARGUMENT, 'reply body is too long');
17
- if (typeof input.authorId !== 'string' || input.authorId === '') fail(ERRORS.INVALID_ARGUMENT, 'authorId is required');
18
- const baseSeq = input.baseSeq ?? 0;
19
- if (!Number.isSafeInteger(baseSeq) || baseSeq < 0) fail(ERRORS.INVALID_ARGUMENT, 'baseSeq must be a non-negative integer');
20
- if (baseSeq > thread.headSeq) fail(ERRORS.INVALID_ARGUMENT, 'baseSeq is ahead of the thread head');
21
- if (input.actorKind !== 'human' && baseSeq !== thread.headSeq) {
22
- const changed = thread.entries.filter((entry) => entry.seq > baseSeq);
23
- fail(ERRORS.STALE_REPLY, 'thread changed since you read it; re-read before replying', {
24
- details: {
25
- taskId: thread.taskId,
26
- baseSeq,
27
- headSeq: thread.headSeq,
28
- changes: changed.map((entry) => ({
29
- seq: entry.seq,
30
- authorId: entry.authorId,
31
- at: entry.at,
32
- excerpt: entry.body.slice(0, 200),
33
- })),
34
- },
35
- });
36
- }
37
- const entry = {
38
- seq: thread.headSeq + 1,
39
- authorId: input.authorId,
40
- baseSeq,
41
- body,
42
- at: options.at ?? Date.now(),
43
- refs: [...(input.refs ?? [])],
44
- };
45
- return {
46
- thread: { ...thread, headSeq: entry.seq, entries: [...thread.entries, entry] },
47
- entry,
48
- };
49
- }
50
-
51
- /** Entries after `baseSeq`, used by the stale-reply error and the UI diff. */
52
- export function entriesSince(thread, baseSeq) {
53
- return thread.entries.filter((entry) => entry.seq > baseSeq);
54
- }
1
+ import { ERRORS, fail } from './errors.js';
2
+
3
+ /** A thread is one append-only conversation attached to a Task. */
4
+ export function createThread(taskId) {
5
+ return { taskId, headSeq: 0, entries: [] };
6
+ }
7
+
8
+ /**
9
+ * Append a reply. `baseSeq` is the head the author read; it is recorded on the
10
+ * entry, and every entry that landed after it comes back as `missed`, so the
11
+ * author learns what it did not see and can follow up if that changes its view.
12
+ *
13
+ * A stale `baseSeq` used to be rejected (E_STALE_REPLY). In a meeting five
14
+ * members read the same head and answer at once: only the first got through,
15
+ * the rest re-read, re-wrote and lost again ("三次回帖均因会议并发被拒";
16
+ * r09: 46 rejections in one round). The reply itself was never wrong — only
17
+ * late — so it is accepted and the gap is reported instead.
18
+ */
19
+ export function appendReply(thread, input, options = {}) {
20
+ const body = typeof input.body === 'string' ? input.body.trim() : '';
21
+ if (body === '') fail(ERRORS.INVALID_ARGUMENT, 'reply body is required');
22
+ if (body.length > 16_384) fail(ERRORS.INVALID_ARGUMENT, 'reply body is too long');
23
+ if (typeof input.authorId !== 'string' || input.authorId === '') fail(ERRORS.INVALID_ARGUMENT, 'authorId is required');
24
+ const baseSeq = input.baseSeq ?? 0;
25
+ if (!Number.isSafeInteger(baseSeq) || baseSeq < 0) fail(ERRORS.INVALID_ARGUMENT, 'baseSeq must be a non-negative integer');
26
+ if (baseSeq > thread.headSeq) fail(ERRORS.INVALID_ARGUMENT, 'baseSeq is ahead of the thread head');
27
+ const missed = entriesSince(thread, baseSeq);
28
+ const entry = {
29
+ seq: thread.headSeq + 1,
30
+ authorId: input.authorId,
31
+ baseSeq,
32
+ body,
33
+ at: options.at ?? Date.now(),
34
+ refs: [...(input.refs ?? [])],
35
+ };
36
+ return {
37
+ thread: { ...thread, headSeq: entry.seq, entries: [...thread.entries, entry] },
38
+ entry,
39
+ missed,
40
+ };
41
+ }
42
+
43
+ /** Entries after `baseSeq`, reported as `missed` on a late reply and used by the UI diff. */
44
+ export function entriesSince(thread, baseSeq) {
45
+ return thread.entries.filter((entry) => entry.seq > baseSeq);
46
+ }
@@ -3,8 +3,9 @@
3
3
  * once the AI Team runtime booted (see index.js `when`); the tool itself still
4
4
  * refuses any session that is not a live Team member (`E_NOT_MEMBER`).
5
5
  *
6
- * Mutations require `expectedRevision` (Task CAS) and `baseSeq` (Thread stale
7
- * reply protection); errors are returned as data so the member can re-read.
6
+ * Task mutations require `expectedRevision` (CAS). A reply carries `baseSeq`
7
+ * (the head it was written against); a late reply is accepted and the entries it
8
+ * missed come back in the result. Errors are returned as data so the member can re-read.
8
9
  */
9
10
  import { taskCard } from './views.js';
10
11
  import { isQaMember } from '../domain/member-profile.js';
@@ -62,7 +63,7 @@ export function createTeamTool(options) {
62
63
  action: { type: 'string', enum: ACTIONS, description: 'Operation to perform.' },
63
64
  taskId: { type: 'string', description: 'Task id from tasks.' },
64
65
  expectedRevision: { type: 'integer', description: 'Task revision from tasks/claim; required for claim/submit/accept/requestChanges.' },
65
- baseSeq: { type: 'integer', description: 'Thread headSeq read before replying; required for reply.' },
66
+ baseSeq: { type: 'integer', description: 'Thread headSeq read before replying; required for reply. A late reply is still posted and returns the entries you missed.' },
66
67
  afterSeq: { type: 'integer', description: 'Return Thread entries after this seq.' },
67
68
  summary: { type: 'string', description: 'What was done, for submit.' },
68
69
  evidence: { type: 'array', items: { type: 'string' }, description: 'Evidence strings/paths, at least one for submit.' },
@@ -297,7 +298,18 @@ export function createTeamTool(options) {
297
298
  if (!Number.isSafeInteger(args.baseSeq)) return failure({ code: 'E_INVALID_ARGUMENT', message: 'baseSeq is required; read thread first' });
298
299
  if (typeof args.body !== 'string' || args.body.trim() === '') return failure({ code: 'E_INVALID_ARGUMENT', message: 'body is required' });
299
300
  const result = await command('thread.post', { taskId: args.taskId, baseSeq: args.baseSeq, body: args.body });
300
- return { ok: true, taskId: args.taskId, headSeq: result.thread.headSeq, entry: result.entry };
301
+ const missed = (result.missed ?? []).filter((entry) => entry.authorId !== member.id);
302
+ if (missed.length === 0) return { ok: true, taskId: args.taskId, headSeq: result.thread.headSeq, entry: result.entry };
303
+ // 迟到的回帖照收(会议里并发是常态),把读取之后新增的发言带回去:
304
+ // 只有它们改变了你的结论才再补一条,不要为了「对齐」重复发言。
305
+ return {
306
+ ok: true,
307
+ taskId: args.taskId,
308
+ headSeq: result.thread.headSeq,
309
+ entry: result.entry,
310
+ missed: missed.map((entry) => ({ seq: entry.seq, authorId: entry.authorId, body: entry.body.slice(0, 2000) })),
311
+ note: `posted; ${missed.length} repl${missed.length === 1 ? 'y' : 'ies'} landed after you read the thread (shown in missed). Reply again only if they change your answer.`,
312
+ };
301
313
  }
302
314
  if (args.action === 'say') {
303
315
  // 核心模型:只有项目 PMO 面向 Human 说话(主对话);成员在各自 Task Thread 里协作。
@@ -1380,7 +1380,7 @@ export class TeamService {
1380
1380
  projectId: command.projectId,
1381
1381
  at: this.now(),
1382
1382
  });
1383
- return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry };
1383
+ return { thread: this.state.threads?.[taskId] ?? outcome.thread, entry: outcome.entry, missed: outcome.missed };
1384
1384
  });
1385
1385
  }
1386
1386
 
package/lib/host/waker.js CHANGED
@@ -286,8 +286,11 @@ export function planWakes(state, result, actor = {}, options = {}) {
286
286
  const bucket = event.payload?.bucket ?? Math.floor(Date.now() / 600_000);
287
287
  const ownerId = project?.ownerMemberId;
288
288
  // PMO meetings include every agent member; the owner leads, everyone
289
- // else contributes from their own professional seat.
290
- for (const member of Object.values(state.members ?? {})) {
289
+ // else contributes from their own professional seat. No wakeable owner,
290
+ // no meeting: r13 convened five members around a failed PMO (AUTH) —
291
+ // a headless meeting that nobody chairs or closes.
292
+ const members = agentMember(state, ownerId) === null ? [] : Object.values(state.members ?? {});
293
+ for (const member of members) {
291
294
  if (member.kind !== 'agent' || member.status === 'retired') continue;
292
295
  if (member.id === ownerId) {
293
296
  add(member.id, null, 'pmo_continue', `pmo:${project?.id ?? 'project'}:${bucket}`);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Build a `subagents.startActivation` spec every supported host accepts.
3
+ *
4
+ * The spec shape changed between DSH releases:
5
+ * - rc.1 (desktop) reads the task from a nested `spec.request`
6
+ * (`spec.request.parent`, `.cwd`, `.prompt`, `.agentOptions`, ...);
7
+ * - rc.2 / rc.3 flattened it: `SubagentActivationSpec extends
8
+ * SubagentStartRequest`, so they read `spec.parent`, `spec.cwd`, ...
9
+ * and a nested-only spec fails with "subagent creation requires the exact
10
+ * live parent agent" (every activation failed on rc.2+).
11
+ *
12
+ * Each host reads only its own fields and ignores the other's, so the spec
13
+ * carries both: the request fields at the top level and the same object under
14
+ * `request`. Top-level `provider` / `label` / `signal` / `delivery` win over
15
+ * anything the request carries.
16
+ *
17
+ * @param {{ provider: string, label: string, signal: AbortSignal, delivery: 'parent'|'caller', request: object }} input
18
+ */
19
+ export function activationSpec({ provider, label, signal, delivery, request }) {
20
+ return { ...request, provider, label, signal, delivery, request };
21
+ }
@@ -15,6 +15,7 @@
15
15
  import { buildAgentOptions } from '../domain/member-config.js';
16
16
 
17
17
  import { resolveTeamPreset } from '../host/permission-guard.js';
18
+ import { activationSpec } from './activation-spec.js';
18
19
 
19
20
  const TEAM_PRESET = 'danger-full-access';
20
21
 
@@ -116,7 +117,7 @@ export class MemberRuntime {
116
117
  const agentOptions = buildAgentOptions(member.config ?? {});
117
118
  let activation;
118
119
  try {
119
- activation = await this.subagents.startActivation({
120
+ activation = await this.subagents.startActivation(activationSpec({
120
121
  provider: options.provider ?? this.provider,
121
122
  label: member.name,
122
123
  request: {
@@ -128,7 +129,7 @@ export class MemberRuntime {
128
129
  },
129
130
  signal,
130
131
  delivery: 'parent',
131
- });
132
+ }));
132
133
  } catch (error) {
133
134
  fail('E_ACTIVATION', `member activation failed: ${error?.message ?? error}`, { memberId: member.id });
134
135
  }
@@ -1,68 +1,69 @@
1
- /**
2
- * 独立 judge 执行器:用 DSH 的 subagent 起**一次性评审子代理**(与 darwin
3
- * 的「spawn 独立子 agent」同义),子代理上下文干净、不参与优化,天然杜绝
4
- * 「自己改自己评」的乐观偏差。
5
- *
6
- * 每个 judge 只做一次 A/B 盲评(顺序随机化),输出一行 JSON;本模块负责
7
- * 汇总成 paired 多数决 verdict。
8
- */
9
- import { buildPairPrompt, decideByMajority, normalizeVoteCount, parseJudgeOutput, voteFromParsed } from './judge.js';
10
- import { awaitActivationText } from './subagent-text.js';
11
-
12
- const JUDGE_TIMEOUT_MS = 120_000;
13
-
14
- /**
15
- * 起 N 个独立 judge 子代理做 paired 比较。
16
- *
17
- * @param {object} input
18
- * @param {string} input.before 改前全文
19
- * @param {string} input.after 改后全文
20
- * @param {object} input.subagents ctx.get('subagents')
21
- * @param {object} input.parent 父 Agent(插件 parentInfo.agent)
22
- * @param {string} input.provider subagent provider 名
23
- * @param {string} input.cwd judge 子代理工作目录
24
- * @param {number} [input.votes] 奇数票数(默认 3,平局可升 5)
25
- * @param {() => number} [input.random] 注入随机源(测试用;默认 Math.random)
26
- * @returns {Promise<{verdict:'keep'|'revert'|'inconclusive', better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>}
27
- */
28
- export async function judgePair(input) {
29
- const {
30
- before, after, subagents, parent, provider, cwd,
31
- votes: requestedVotes, random = Math.random,
32
- } = input;
33
- if (typeof before !== 'string' || typeof after !== 'string') {
34
- throw new TypeError('judgePair needs before/after text');
35
- }
36
- if (typeof subagents?.startActivation !== 'function' || parent === undefined) {
37
- throw new Error('judge unavailable: subagent service or parent agent missing');
38
- }
39
- const votes = normalizeVoteCount(requestedVotes);
40
- const rows = [];
41
- const errors = [];
42
- for (let index = 0; index < votes; index++) {
43
- const order = random() < 0.5 ? 'ab' : 'ba';
44
- const { prompt, mapping } = buildPairPrompt({ before, after, order });
45
- let activation = null;
46
- try {
47
- activation = await subagents.startActivation({
48
- provider,
49
- label: `skillopt-judge-${index + 1}`,
50
- request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
51
- delivery: 'parent',
52
- signal: new AbortController().signal,
53
- });
54
- const text = await awaitActivationText(activation, { timeoutMs: JUDGE_TIMEOUT_MS });
55
- const parsed = parseJudgeOutput(text);
56
- const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping.aIsAfter });
57
- if (vote === null) errors.push(`judge ${index + 1}: unparseable output`);
58
- rows.push({ index: index + 1, order, vote, reason: parsed?.reason ?? '', margin: parsed?.margin ?? null });
59
- } catch (error) {
60
- errors.push(`judge ${index + 1}: ${error?.message ?? String(error)}`);
61
- rows.push({ index: index + 1, order, vote: null, reason: '', margin: null });
62
- } finally {
63
- try { await activation?.dispose?.(); } catch { /* already gone */ }
64
- }
65
- }
66
- const decision = decideByMajority(rows.map((row) => row.vote));
67
- return { ...decision, votes: rows, errors };
68
- }
1
+ /**
2
+ * 独立 judge 执行器:用 DSH 的 subagent 起**一次性评审子代理**(与 darwin
3
+ * 的「spawn 独立子 agent」同义),子代理上下文干净、不参与优化,天然杜绝
4
+ * 「自己改自己评」的乐观偏差。
5
+ *
6
+ * 每个 judge 只做一次 A/B 盲评(顺序随机化),输出一行 JSON;本模块负责
7
+ * 汇总成 paired 多数决 verdict。
8
+ */
9
+ import { buildPairPrompt, decideByMajority, normalizeVoteCount, parseJudgeOutput, voteFromParsed } from './judge.js';
10
+ import { awaitActivationText } from './subagent-text.js';
11
+ import { activationSpec } from '../runtime/activation-spec.js';
12
+
13
+ const JUDGE_TIMEOUT_MS = 120_000;
14
+
15
+ /**
16
+ * 起 N 个独立 judge 子代理做 paired 比较。
17
+ *
18
+ * @param {object} input
19
+ * @param {string} input.before 改前全文
20
+ * @param {string} input.after 改后全文
21
+ * @param {object} input.subagents ctx.get('subagents')
22
+ * @param {object} input.parent 父 Agent(插件 parentInfo.agent)
23
+ * @param {string} input.provider subagent provider 名
24
+ * @param {string} input.cwd judge 子代理工作目录
25
+ * @param {number} [input.votes] 奇数票数(默认 3,平局可升 5)
26
+ * @param {() => number} [input.random] 注入随机源(测试用;默认 Math.random)
27
+ * @returns {Promise<{verdict:'keep'|'revert'|'inconclusive', better:number, worse:number, ties:number, valid:number, votes:Array, errors:string[]}>}
28
+ */
29
+ export async function judgePair(input) {
30
+ const {
31
+ before, after, subagents, parent, provider, cwd,
32
+ votes: requestedVotes, random = Math.random,
33
+ } = input;
34
+ if (typeof before !== 'string' || typeof after !== 'string') {
35
+ throw new TypeError('judgePair needs before/after text');
36
+ }
37
+ if (typeof subagents?.startActivation !== 'function' || parent === undefined) {
38
+ throw new Error('judge unavailable: subagent service or parent agent missing');
39
+ }
40
+ const votes = normalizeVoteCount(requestedVotes);
41
+ const rows = [];
42
+ const errors = [];
43
+ for (let index = 0; index < votes; index++) {
44
+ const order = random() < 0.5 ? 'ab' : 'ba';
45
+ const { prompt, mapping } = buildPairPrompt({ before, after, order });
46
+ let activation = null;
47
+ try {
48
+ activation = await subagents.startActivation(activationSpec({
49
+ provider,
50
+ label: `skillopt-judge-${index + 1}`,
51
+ request: { cwd, prompt: [{ type: 'text', text: prompt }], parent },
52
+ delivery: 'parent',
53
+ signal: new AbortController().signal,
54
+ }));
55
+ const text = await awaitActivationText(activation, { timeoutMs: JUDGE_TIMEOUT_MS });
56
+ const parsed = parseJudgeOutput(text);
57
+ const vote = voteFromParsed(parsed === null ? null : { ...parsed, aIsAfter: mapping.aIsAfter });
58
+ if (vote === null) errors.push(`judge ${index + 1}: unparseable output`);
59
+ rows.push({ index: index + 1, order, vote, reason: parsed?.reason ?? '', margin: parsed?.margin ?? null });
60
+ } catch (error) {
61
+ errors.push(`judge ${index + 1}: ${error?.message ?? String(error)}`);
62
+ rows.push({ index: index + 1, order, vote: null, reason: '', margin: null });
63
+ } finally {
64
+ try { await activation?.dispose?.(); } catch { /* already gone */ }
65
+ }
66
+ }
67
+ const decision = decideByMajority(rows.map((row) => row.vote));
68
+ return { ...decision, votes: rows, errors };
69
+ }
@@ -1,128 +1,129 @@
1
- /**
2
- * 自动优化循环的宿主适配:VCS(git / 文件备份)、候选生成器(独立子代理)、
3
- * results.tsv 追加。与 optimizer.js 的纯编排分离,便于测试替换。
4
- */
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
6
- import { dirname, join } from 'node:path';
7
- import { runEngineCli, quoteArgv } from './gate-wiring.js';
8
- import { awaitActivationText } from './subagent-text.js';
9
- import { sha12 } from './proposal-store.js';
10
-
11
- /** 项目是否为干净 git 仓库(决定 git 棘轮还是文件备份)。 */
12
- async function isCleanGitRepo(shell, cwd) {
13
- const inside = await runEngineCli(shell, ['git', '-C', cwd, 'rev-parse', '--is-inside-work-tree']).catch(() => null);
14
- if (inside?.exitCode !== 0 || !/true/.test(inside?.stdout ?? '')) return false;
15
- const status = await runEngineCli(shell, ['git', '-C', cwd, 'status', '--porcelain']).catch(() => null);
16
- return status?.exitCode === 0 && (status.stdout ?? '').trim() === '';
17
- }
18
-
19
- /**
20
- * @param {{shell:object, projectDir:string, now?:()=>number}} deps
21
- * @returns {Promise<object>} vcs 适配器
22
- */
23
- export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
24
- const git = await isCleanGitRepo(shell, projectDir);
25
- if (git) {
26
- const commit = async (message) => {
27
- const add = await runEngineCli(shell, ['git', '-C', projectDir, 'add', '-A']);
28
- if (add.exitCode !== 0) throw new Error(`git add failed: ${add.stderr}`);
29
- const done = await runEngineCli(shell, ['git', '-C', projectDir, 'commit', '-m', message, '--no-verify']);
30
- if (done.exitCode !== 0) throw new Error(`git commit failed: ${done.stderr}`);
31
- const head = await runEngineCli(shell, ['git', '-C', projectDir, 'rev-parse', '--short', 'HEAD']);
32
- return (head.stdout ?? '').trim() || null;
33
- };
34
- return {
35
- kind: 'git',
36
- commit,
37
- // keep 时无需额外动作:commit 已留下保留版本。
38
- commitKept: async () => {},
39
- revert: async () => {
40
- const done = await runEngineCli(shell, ['git', '-C', projectDir, 'revert', 'HEAD', '--no-edit']);
41
- if (done.exitCode !== 0) throw new Error(`git revert failed: ${done.stderr}`);
42
- },
43
- writeBaseline: async (path, text) => { writeFileSync(path, text, 'utf8'); },
44
- };
45
- }
46
- const backupDir = join(projectDir, '.skillopt-sleep', 'backups');
47
- mkdirSync(backupDir, { recursive: true });
48
- return {
49
- kind: 'file',
50
- backup: async (path, text) => {
51
- const stamp = new Date(now()).toISOString().replace(/[:.]/g, '-');
52
- const target = join(backupDir, `${path.split(/[\\/]/).pop()}.${stamp}.bak`);
53
- writeFileSync(target, text, 'utf8');
54
- return target;
55
- },
56
- restore: async (path, backupPath) => {
57
- if (!existsSync(backupPath)) throw new Error(`backup missing: ${backupPath}`);
58
- copyFileSync(backupPath, path);
59
- },
60
- };
61
- }
62
-
63
-
64
- export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
65
- /**
66
- * 启动生成子代理(两阶段:只启动,不等待)。返回 { childId, outputStart };
67
- * 输出由 PMO tick 从会话事件里收割(工具 execute 内无法同步等待)。
68
- */
69
- const start = async ({ before, dimension, round }) => {
70
- const parentInfo = await ensureParent();
71
- const provider = providerName();
72
- const prompt = [
73
- '你是技能改进器。只输出改进后的完整 SKILL.md 内容(不要解释、不要代码围栏)。',
74
- `目标维度:dim${dimension.id} ${dimension.name}(当前 ${dimension.score}/10,权重 ${dimension.weight})。`,
75
- '硬约束:不得改变技能的核心用途;只解决该维度;不得删掉已有的失败分支/检查点/反例清单;',
76
- '不得加长到原文 150% 以上;不得引入软化措辞(建议/可以考虑/根据情况/灵活把握/视情况而定)。',
77
- `这是第 ${round} 轮。`,
78
- '',
79
- '## 原文',
80
- before,
81
- ].join('\n');
82
- const activation = await subagents.startActivation({
83
- provider,
84
- label: `skillopt-optimize-${round}`,
85
- request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
86
- delivery: 'parent',
87
- signal: new AbortController().signal,
88
- });
89
- return { childId: activation.childId, outputStart: activation.outputStart ?? null };
90
- };
91
- return { start };
92
- }
93
-
94
- /**
95
- * 同步判据:results.tsv 中该 skill 的**最后一条**记录是否为 paired keep,
96
- * 且该记录的内容指纹必须等于当前 staging 候选。
97
- *
98
- * 只查「最后一条是 keep」会让任意一次旧 keep 解锁任意新提案(adopt 门形同虚设),
99
- * 因此第 10 列记录候选的 sha12,比对不上就按「未验证」拒绝。
100
- */
101
- export function hasPairedKeepRecord(projectDir, skillPath, candidateText) {
102
- const name = typeof skillPath === 'string' && skillPath !== ''
103
- ? skillPath.split(/[\\/]/).slice(-2, -1)[0]
104
- : null;
105
- const file = join(projectDir, '.skillopt-sleep', 'results.tsv');
106
- if (!existsSync(file)) return false;
107
- const lines = readFileSync(file, 'utf8').trim().split(/\r?\n/).slice(1);
108
- const rows = lines.map((line) => line.split('\t')).filter((cells) => name === null || cells[2] === name);
109
- const last = rows.at(-1);
110
- if (last === undefined) return false;
111
- if (last[5] !== 'keep' || last[8] !== 'paired') return false;
112
- if (typeof candidateText !== 'string') return false;
113
- return last[9] === sha12(candidateText);
114
- }
115
-
116
- /** results.tsv 追加(表头自动补)。 */
117
- export function makeResultAppender({ projectDir }) {
118
- const dir = join(projectDir, '.skillopt-sleep');
119
- const path = join(dir, 'results.tsv');
120
- return async (line) => {
121
- mkdirSync(dir, { recursive: true });
122
- const header = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode', 'proposal_sha'].join('\t');
123
- const prefix = existsSync(path) && readFileSync(path, 'utf8').includes('proposal_sha') ? '' : header + '\n';
124
- writeFileSync(path, prefix + line + '\n', { encoding: 'utf8', flag: 'a' });
125
- };
126
- }
127
-
128
- export { quoteArgv };
1
+ /**
2
+ * 自动优化循环的宿主适配:VCS(git / 文件备份)、候选生成器(独立子代理)、
3
+ * results.tsv 追加。与 optimizer.js 的纯编排分离,便于测试替换。
4
+ */
5
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { runEngineCli, quoteArgv } from './gate-wiring.js';
8
+ import { awaitActivationText } from './subagent-text.js';
9
+ import { sha12 } from './proposal-store.js';
10
+ import { activationSpec } from '../runtime/activation-spec.js';
11
+
12
+ /** 项目是否为干净 git 仓库(决定 git 棘轮还是文件备份)。 */
13
+ async function isCleanGitRepo(shell, cwd) {
14
+ const inside = await runEngineCli(shell, ['git', '-C', cwd, 'rev-parse', '--is-inside-work-tree']).catch(() => null);
15
+ if (inside?.exitCode !== 0 || !/true/.test(inside?.stdout ?? '')) return false;
16
+ const status = await runEngineCli(shell, ['git', '-C', cwd, 'status', '--porcelain']).catch(() => null);
17
+ return status?.exitCode === 0 && (status.stdout ?? '').trim() === '';
18
+ }
19
+
20
+ /**
21
+ * @param {{shell:object, projectDir:string, now?:()=>number}} deps
22
+ * @returns {Promise<object>} vcs 适配器
23
+ */
24
+ export async function makeVcs({ shell, projectDir, now = () => Date.now() }) {
25
+ const git = await isCleanGitRepo(shell, projectDir);
26
+ if (git) {
27
+ const commit = async (message) => {
28
+ const add = await runEngineCli(shell, ['git', '-C', projectDir, 'add', '-A']);
29
+ if (add.exitCode !== 0) throw new Error(`git add failed: ${add.stderr}`);
30
+ const done = await runEngineCli(shell, ['git', '-C', projectDir, 'commit', '-m', message, '--no-verify']);
31
+ if (done.exitCode !== 0) throw new Error(`git commit failed: ${done.stderr}`);
32
+ const head = await runEngineCli(shell, ['git', '-C', projectDir, 'rev-parse', '--short', 'HEAD']);
33
+ return (head.stdout ?? '').trim() || null;
34
+ };
35
+ return {
36
+ kind: 'git',
37
+ commit,
38
+ // keep 时无需额外动作:commit 已留下保留版本。
39
+ commitKept: async () => {},
40
+ revert: async () => {
41
+ const done = await runEngineCli(shell, ['git', '-C', projectDir, 'revert', 'HEAD', '--no-edit']);
42
+ if (done.exitCode !== 0) throw new Error(`git revert failed: ${done.stderr}`);
43
+ },
44
+ writeBaseline: async (path, text) => { writeFileSync(path, text, 'utf8'); },
45
+ };
46
+ }
47
+ const backupDir = join(projectDir, '.skillopt-sleep', 'backups');
48
+ mkdirSync(backupDir, { recursive: true });
49
+ return {
50
+ kind: 'file',
51
+ backup: async (path, text) => {
52
+ const stamp = new Date(now()).toISOString().replace(/[:.]/g, '-');
53
+ const target = join(backupDir, `${path.split(/[\\/]/).pop()}.${stamp}.bak`);
54
+ writeFileSync(target, text, 'utf8');
55
+ return target;
56
+ },
57
+ restore: async (path, backupPath) => {
58
+ if (!existsSync(backupPath)) throw new Error(`backup missing: ${backupPath}`);
59
+ copyFileSync(backupPath, path);
60
+ },
61
+ };
62
+ }
63
+
64
+
65
+ export function makeGenerator({ subagents, ensureParent, providerName, cwd }) {
66
+ /**
67
+ * 启动生成子代理(两阶段:只启动,不等待)。返回 { childId, outputStart };
68
+ * 输出由 PMO tick 从会话事件里收割(工具 execute 内无法同步等待)。
69
+ */
70
+ const start = async ({ before, dimension, round }) => {
71
+ const parentInfo = await ensureParent();
72
+ const provider = providerName();
73
+ const prompt = [
74
+ '你是技能改进器。只输出改进后的完整 SKILL.md 内容(不要解释、不要代码围栏)。',
75
+ `目标维度:dim${dimension.id} ${dimension.name}(当前 ${dimension.score}/10,权重 ${dimension.weight})。`,
76
+ '硬约束:不得改变技能的核心用途;只解决该维度;不得删掉已有的失败分支/检查点/反例清单;',
77
+ '不得加长到原文 150% 以上;不得引入软化措辞(建议/可以考虑/根据情况/灵活把握/视情况而定)。',
78
+ `这是第 ${round} 轮。`,
79
+ '',
80
+ '## 原文',
81
+ before,
82
+ ].join('\n');
83
+ const activation = await subagents.startActivation(activationSpec({
84
+ provider,
85
+ label: `skillopt-optimize-${round}`,
86
+ request: { cwd, prompt: [{ type: 'text', text: prompt }], parent: parentInfo?.agent },
87
+ delivery: 'parent',
88
+ signal: new AbortController().signal,
89
+ }));
90
+ return { childId: activation.childId, outputStart: activation.outputStart ?? null };
91
+ };
92
+ return { start };
93
+ }
94
+
95
+ /**
96
+ * 同步判据:results.tsv 中该 skill 的**最后一条**记录是否为 paired keep,
97
+ * 且该记录的内容指纹必须等于当前 staging 候选。
98
+ *
99
+ * 只查「最后一条是 keep」会让任意一次旧 keep 解锁任意新提案(adopt 门形同虚设),
100
+ * 因此第 10 列记录候选的 sha12,比对不上就按「未验证」拒绝。
101
+ */
102
+ export function hasPairedKeepRecord(projectDir, skillPath, candidateText) {
103
+ const name = typeof skillPath === 'string' && skillPath !== ''
104
+ ? skillPath.split(/[\\/]/).slice(-2, -1)[0]
105
+ : null;
106
+ const file = join(projectDir, '.skillopt-sleep', 'results.tsv');
107
+ if (!existsSync(file)) return false;
108
+ const lines = readFileSync(file, 'utf8').trim().split(/\r?\n/).slice(1);
109
+ const rows = lines.map((line) => line.split('\t')).filter((cells) => name === null || cells[2] === name);
110
+ const last = rows.at(-1);
111
+ if (last === undefined) return false;
112
+ if (last[5] !== 'keep' || last[8] !== 'paired') return false;
113
+ if (typeof candidateText !== 'string') return false;
114
+ return last[9] === sha12(candidateText);
115
+ }
116
+
117
+ /** results.tsv 追加(表头自动补)。 */
118
+ export function makeResultAppender({ projectDir }) {
119
+ const dir = join(projectDir, '.skillopt-sleep');
120
+ const path = join(dir, 'results.tsv');
121
+ return async (line) => {
122
+ mkdirSync(dir, { recursive: true });
123
+ const header = ['timestamp', 'commit', 'skill', 'old_score', 'new_score', 'status', 'dimension', 'note', 'eval_mode', 'proposal_sha'].join('\t');
124
+ const prefix = existsSync(path) && readFileSync(path, 'utf8').includes('proposal_sha') ? '' : header + '\n';
125
+ writeFileSync(path, prefix + line + '\n', { encoding: 'utf8', flag: 'a' });
126
+ };
127
+ }
128
+
129
+ export { quoteArgv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.91",
3
+ "version": "0.4.93",
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",