@suifei/dsh-ai-team 0.4.92 → 0.4.94

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,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.94 - 2026-11-15
4
+
5
+ **成员会话重建后,旧会话从工作区摘下**
6
+
7
+ 成员会话不可恢复(`NOT_RESUMABLE` 等)时插件会自愈重建一个新会话,但被替换的旧会话仍挂在项目工作区下。
8
+ 宿主没有删除会话的 API,于是每次重建都在工作区列表里多留一个永不再用的会话——实机 il2c 在 11-12/13 两天
9
+ 自愈重建 322 次,il2c 工作区下累积 323 个死成员会话(`workspace.json` 里 354 个会话只有 25 个在用或属于 Human)。
10
+
11
+ - `index.js` `activateMember`:force 重建成功、新会话挂上工作区后,对旧会话调用工作区的 `detachSession`;
12
+ 诊断行 `workspace.detach`(`errors` 级可见)/ `workspace.detach.fail`;
13
+ - `member.autoreseat` 诊断行补记触发的 `failureCode` 与唤醒 `reason`,之后能区分重建成因;
14
+ - 测试:`node --test` **332 通过 / 1 跳过**;`host.test` 新增「旧会话摘下、新会话挂上」断言(去掉修复即失败);
15
+ - E2E(隔离 DSH_HOME,rc.1 与 rc.3):`member.reseat` 后 `workspace.json` 中旧会话不在、新会话在,诊断有 `workspace.detach` 行。
16
+
17
+ ## 0.4.93 - 2026-11-14
18
+
19
+ **rc.2+ 宿主上成员能激活了:`startActivation` 同时给出扁平与嵌套两种 spec**
20
+
21
+ DSH rc.2 起 `SubagentActivationSpec extends SubagentStartRequest`——`parent` / `cwd` / `prompt` /
22
+ `agentPreset` / `agentOptions` 平铺在 spec 顶层;rc.1(桌面版)仍读嵌套的 `spec.request.*`。插件只给嵌套
23
+ 形状,rc.2 / rc.3 上 `spec.parent` 为 undefined,每次激活都以「subagent creation requires the exact live
24
+ parent agent」失败(成员、技能评审、技能优化子代理全部不可用)。
25
+
26
+ - `lib/runtime/activation-spec.js` `activationSpec`:请求字段既平铺在顶层、也保留在 `request` 下;各宿主
27
+ 只读自己的字段、忽略另一份(rc.1 / rc.3 源码核对)。成员激活、技能评审(两处)、技能优化共 5 处调用统一走它;
28
+ - 测试:`node --test` **332 通过 / 1 跳过**;`member-activation` 新增双形状读取 1 条;
29
+ - E2E(全新隔离 DSH_HOME,成员全部 qwen,「用 js 写 2 种排序算法」):rc.3 / rc.2 / rc.1 三个宿主均在 2 分钟内
30
+ 完成「PMO 建卡 → 成员激活认领 → 提交 → 验收 → wave_done 汇报」,之后静默(rc.3 观察 12 分钟账本不再增长);
31
+ rc.3 / rc.2 失败仅启动期 2 条注册表未就绪,rc.1 另有 1 条重复认领的业务拒绝。修复前 rc.2+ 激活 100% 失败。
3
32
  ## 0.4.92 - 2026-11-14
4
33
 
5
34
  **会议并发回帖不再被拒:迟到的回帖照收,并把错过的发言带回去;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';
@@ -413,6 +414,20 @@ export function apply(ctx, config = {}) {
413
414
  console.warn('[ai-team] member session workspace attach failed:', error?.message ?? error, '— reseat the member (team member.reseat) to recreate its session in the project workspace');
414
415
  }
415
416
  };
417
+ // 重建(reseat)替换掉的旧成员会话从工作区摘下。宿主没有删会话的 API,
418
+ // 不摘的话每次重建都在工作区列表里多挂一个永不再用的会话(实机 il2c:
419
+ // 11-12/13 两天 322 次自愈重建 → 323 个死会话挂在 il2c 工作区下)。
420
+ const detachMemberWorkspace = async (projectRuntime, sessionId) => {
421
+ if (typeof sessionId !== 'string' || sessionId === '') return;
422
+ const workspace = await workspaceForProject(projectRuntime);
423
+ if (workspace === null || workspace === undefined || typeof workspace.detachSession !== 'function') return;
424
+ try {
425
+ await workspace.detachSession(sessionId);
426
+ diag.append({ ev: 'workspace.detach', sessionId, projectId: projectRuntime?.id ?? null });
427
+ } catch (error) {
428
+ diag.append({ ev: 'workspace.detach.fail', sessionId, projectId: projectRuntime?.id ?? null, message: error?.message ?? String(error) });
429
+ }
430
+ };
416
431
  // A restored member session has no live AgentOptions; without a recorded
417
432
  // model/selection event its prompt renders with an unresolvable {{model}}.
418
433
  const modelSelectionLogged = new Map();
@@ -1072,6 +1087,9 @@ export function apply(ctx, config = {}) {
1072
1087
  memberId: plan.memberId,
1073
1088
  oldSessionId: targetMember.sessionId,
1074
1089
  newSessionId: reseated?.sessionId ?? null,
1090
+ // 记下触发码:11-12/13 的 322 次重建事后无从区分成因。
1091
+ failureCode,
1092
+ reason: plan.reason,
1075
1093
  ok: reseated?.error === undefined,
1076
1094
  error: reseated?.error ?? null,
1077
1095
  });
@@ -1119,7 +1137,7 @@ export function apply(ctx, config = {}) {
1119
1137
  startChild: async (label, spec) => {
1120
1138
  // 必须走 serviceOf:这里不在 activateMember/wakeFromResult 的
1121
1139
  // 词法作用域内,裸写 subagents 会在判官轮抛 ReferenceError。
1122
- const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
1140
+ const child = await serviceOf(ctx, 'subagents').startActivation(activationSpec({ ...spec, label }));
1123
1141
  return { childId: child.childId, outputStart: child.outputStart ?? null };
1124
1142
  },
1125
1143
  readText: (file) => readFileSync(file, 'utf8'),
@@ -1567,7 +1585,7 @@ export function apply(ctx, config = {}) {
1567
1585
  ensureParent: () => ensureParent(),
1568
1586
  votes: config.skilloptJudgeVotes ?? 3,
1569
1587
  startChild: async (label, spec) => {
1570
- const child = await serviceOf(ctx, 'subagents').startActivation({ ...spec, label });
1588
+ const child = await serviceOf(ctx, 'subagents').startActivation(activationSpec({ ...spec, label }));
1571
1589
  return { childId: child.childId, outputStart: child.outputStart ?? null };
1572
1590
  },
1573
1591
  readText: (file) => readFileSync(file, 'utf8'),
@@ -1919,8 +1937,10 @@ export function apply(ctx, config = {}) {
1919
1937
  // 久管理,插件不再持有或唤醒它;新会话落在当前项目工作目录。这是
1920
1938
  // 修复历史"账本目录兜底 cwd"游离会话的唯一路径(会话 cwd 创建时
1921
1939
  // 钉死,resume 不覆盖,DSH 不提供原地改 cwd 的 API)。
1922
- if (typeof member.sessionId === 'string' && member.sessionId !== '' && body.payload?.force === true) {
1923
- const staleId = member.sessionId;
1940
+ const staleId = typeof member.sessionId === 'string' && member.sessionId !== '' && body.payload?.force === true
1941
+ ? member.sessionId
1942
+ : null;
1943
+ if (staleId !== null) {
1924
1944
  const staleActivation = activations.get(staleId);
1925
1945
  if (staleActivation !== undefined) {
1926
1946
  activations.delete(staleId);
@@ -2001,6 +2021,7 @@ export function apply(ctx, config = {}) {
2001
2021
  }
2002
2022
  activations.set(result.childId, result.activation);
2003
2023
  await attachMemberWorkspace(projectRuntime, result.childId);
2024
+ if (staleId !== null && staleId !== result.childId) await detachMemberWorkspace(projectRuntime, staleId);
2004
2025
  persistModelSelection(result.childId, activationMember.config, member.name);
2005
2026
  return {
2006
2027
  ok: true,
package/lib/diaglog.js CHANGED
@@ -36,7 +36,9 @@ export function isErrorEvent(ev) {
36
36
  // 必须在发布默认级别可见,否则只能看到一连串 wake.fail 而不知道有没有救回来。
37
37
  || ev === 'member.autoreseat'
38
38
  // Human 停止时中断了哪些成员:决定「停了之后还在跑」是不是插件的锅。
39
- || ev === 'team.interrupt');
39
+ || ev === 'team.interrupt'
40
+ // 重建后旧会话有没有从工作区摘掉:决定工作区列表是否随自愈累积死会话。
41
+ || ev === 'workspace.detach');
40
42
  }
41
43
 
42
44
  /**
@@ -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.94",
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",