@suifei/dsh-ai-team 0.4.92 → 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,20 @@
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% 失败。
3
18
  ## 0.4.92 - 2026-11-14
4
19
 
5
20
  **会议并发回帖不再被拒:迟到的回帖照收,并把错过的发言带回去;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'),
@@ -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.92",
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",