@suifei/dsh-ai-team 0.4.39 → 0.4.41

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,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.41 - 2026-11-12
4
+
5
+ **批 10:收割幂等、句柄回收、别名原子写、自动作答边界**
6
+
7
+ - **收割可恢复**:`applyLiveAtomically` 与「写 results/终态」之间崩溃,上一版会让下一轮把 live ≠ before 判成 conflict——一次成功的 `keep` 被判失败。现在先判定「live 已等于候选」(`alreadyApplied`)走幂等收尾,并在改 live 前把 `decision/backup/applyingSince` 落进 job 记录。
8
+ - **退役/离队回收冷恢复句柄**:`resumedHandles` 与 `activations` 分开登记,之前只回收后者,冷恢复出来的成员会话会一直挂在进程里。
9
+ - **人员别名原子写**:写临时文件再 rename;且**读取失败不再当空表**覆盖——文件损坏时返回 409 让用户先修正,而不是把已有别名清空。
10
+ - **自动作答只回答有问题的决策**:成员致命失败生成的升级项没有 `questions`,自动作答会用一句通用话术把它 `resolved`,Human 再也看不到真正的失败。
11
+ - 测试:`node --test` **243/243**(新增 1 例)。
12
+
13
+ ## 0.4.40 - 2026-11-12
14
+
15
+ **批 9:依赖可达性、账本修复入口、job 状态机、投票解析统一**
16
+
17
+ - **依赖不能指向已删的卡**:删除是 tombstone,而依赖判定只认 `status === 'done'`——指向一张已删除/已取消的卡会让新卡**永久** blocked 且无修复命令。`task.create` 现在拒绝这类 `blockedBy`。
18
+ - **`project.repair` 命令**:`ledger.repair()` 此前没有任何生产调用点,poison 之后只能重启。新增 Human 专用命令,返回 `repair`/`repairs`/`events`/`stateLastSeq` 并记 `ledger.repaired` 诊断。
19
+ - **job 状态机三处**:① `deps.vcs.backup` 不是每个适配器都有(git 就没有),无脑调用会 TypeError 让 job 卡到 TTL;② `plan.next` 是在 switch 之前算的,回写会把刚判死的 job 复活成 `judging`,下一轮再拿一个未应用的候选写假记录;③ `rollback` 无条件把陈旧的 `before` 写回 live,会覆盖评审期间的人工修改——现在先校验 live 仍是候选文本。
20
+ - **投票解析统一**:评审通道原本用自己的「第一个 `{` 到第一个 `}`」正则,会把模板回显计成票、也会在正文含 `}` 时整票丢弃。现在复用 judge 的平衡扫描解析器,并让它保留 `orderId`。
21
+ - 测试:`node --test` **242/242**(新增 4 例)。
22
+
3
23
  ## 0.4.39 - 2026-11-12
4
24
 
5
25
  **第三轮(对抗性复审)回归修复**
package/index.js CHANGED
@@ -11,7 +11,7 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
14
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
15
15
  import z from '@deepseek-ai/schemastery';
16
16
  import { ProjectRuntime } from './lib/host/project-runtime.js';
17
17
  import { ProjectRegistry } from './lib/host/project-registry.js';
@@ -1292,20 +1292,30 @@ export function apply(ctx, config = {}) {
1292
1292
  // 一次 revert 用陈旧快照覆盖(反之亦然)。
1293
1293
  let liveText = null;
1294
1294
  try { liveText = existsSync(job.skillPath) ? readFileSync(job.skillPath, 'utf8') : null; } catch { liveText = null; }
1295
- if (liveText !== null && typeof job.before === 'string' && sha12(liveText) !== sha12(job.before)) {
1295
+ // live 与候选一致 = 上一次已经落过盘、只差收尾(进程在「改 live」与
1296
+ // 「写 results/终态」之间崩溃)。这不是 conflict:按 conflict 处理会把
1297
+ // 一次成功的 keep 在下一轮判成失败。
1298
+ const liveSha = liveText === null ? null : sha12(liveText);
1299
+ const candidateSha = typeof job.candidate === 'string' ? sha12(job.candidate) : null;
1300
+ const alreadyApplied = liveSha !== null && candidateSha !== null && liveSha === candidateSha;
1301
+ if (!alreadyApplied && liveText !== null && typeof job.before === 'string' && liveSha !== sha12(job.before)) {
1296
1302
  writeJob(jobDir, { ...job, state: 'failed', error: 'live SKILL.md changed during review (conflict)', updatedAt: Date.now() });
1297
1303
  await closeReviewCard(runtime, job.reviewTaskId, 'blind review aborted: live file changed');
1298
1304
  diag.append({ ev: 'skillopt.job.conflict', jobId: job.id, skillPath: job.skillPath });
1299
1305
  continue;
1300
1306
  }
1307
+ if (alreadyApplied) diag.append({ ev: 'skillopt.job.resume', jobId: job.id, reason: 'candidate already applied' });
1301
1308
  let backupPath = null;
1302
1309
  try {
1303
1310
  backupPath = backupLive({ projectDir: jobDir, skillPath: job.skillPath, text: liveText ?? job.before ?? '' });
1304
1311
  } catch (error) {
1305
1312
  diag.append({ ev: 'skillopt.job.backup.fail', jobId: job.id, message: error?.message ?? String(error) });
1306
1313
  }
1314
+ // 先把决定落成 job 记录:进程若在「改 live」之后崩溃,下一次仍能看出
1315
+ // 这次要收尾成什么(配合上面的 alreadyApplied 幂等判定)。
1316
+ writeJob(jobDir, { ...job, decision: collected.decision, backup: backupPath ?? job.backup ?? null, applyingSince: Date.now() });
1307
1317
  // keep → 落盘候选;revert → 恢复基线(评审卡收票后才动文件)。
1308
- applyLiveAtomically(job.skillPath, kept ? job.candidate : job.before);
1318
+ if (!alreadyApplied) applyLiveAtomically(job.skillPath, kept ? job.candidate : job.before);
1309
1319
  const beforeScore = scoreSkillRubric(job.before, { measured: false })?.total ?? null;
1310
1320
  const afterScore = scoreSkillRubric(kept ? job.candidate : job.before, { measured: false })?.total ?? null;
1311
1321
  const appender = makeResultAppender({ projectDir: jobDir });
@@ -1751,13 +1761,21 @@ export function apply(ctx, config = {}) {
1751
1761
  if (memberName === '' || personId === '') {
1752
1762
  return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'name and personId are required' } }, 400);
1753
1763
  }
1754
- const aliases = readAliases() ?? {};
1764
+ // 读失败/文件损坏不能当成空表:那会把用户已有的别名整文件覆盖掉。
1765
+ const existing = readAliases();
1766
+ if (existing === null && existsSync(aliasesPath)) {
1767
+ return send(res, { error: { code: 'E_UNREADABLE', message: 'people-aliases.json 无法解析;请先修正或删除该文件再绑定' } }, 409);
1768
+ }
1769
+ const aliases = existing ?? {};
1755
1770
  // 归一到视图层的桶键:接受 `person:<id>`、`name:<名字>` 或裸名字。
1756
1771
  // 归一后才能与 aggregatePeople 的桶键对齐(裸名字曾让两行永不合并,
1757
1772
  // 而界面还提示「已绑定」)。
1758
1773
  const normalized = personId.startsWith('person:') || personId.startsWith('name:') ? personId : `name:${personId}`;
1759
1774
  aliases[memberName] = normalized;
1760
- writeFileSync(aliasesPath, JSON.stringify(aliases, null, 2) + '\n', 'utf8');
1775
+ // 原子写:先写临时文件再改名,半个文件会让下一次读取直接判损坏。
1776
+ const tempPath = `${aliasesPath}.tmp`;
1777
+ writeFileSync(tempPath, JSON.stringify(aliases, null, 2) + '\n', 'utf8');
1778
+ renameSync(tempPath, aliasesPath);
1761
1779
  diag?.append({ ev: 'people.alias', name: memberName, personId });
1762
1780
  return send(res, { ok: true, aliases });
1763
1781
  }
@@ -2231,6 +2249,14 @@ export function apply(ctx, config = {}) {
2231
2249
  try { await activation.dispose?.(); } catch { /* already gone */ }
2232
2250
  diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2233
2251
  }
2252
+ // 冷恢复得到的 handle 也要回收:它同样常驻进程,且不会因为
2253
+ // activation 被 dispose 而消失(两套句柄分开登记)。
2254
+ const resumed = resumedHandles.get(retiredSession);
2255
+ if (resumed !== undefined) {
2256
+ resumedHandles.delete(retiredSession);
2257
+ try { await resumed.dispose?.(); } catch { /* already gone */ }
2258
+ diag.append({ ev: 'member.resumed-handle.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2259
+ }
2234
2260
  }
2235
2261
  }
2236
2262
  send(res, { ok: true, ...result });
@@ -413,6 +413,7 @@ export class TeamService {
413
413
  case 'project.create': return await this.createProject(command, payload);
414
414
  case 'project.owner.update': return await this.changeProjectOwner(command, payload);
415
415
  case 'project.workspace.update': return await this.changeProjectWorkspace(command, payload);
416
+ case 'project.repair': return await this.runExclusive(() => this.repairLedger(command));
416
417
  case 'project.pmo.update': return await this.setProjectPmo(command, payload);
417
418
  case 'project.archive': return await this.setProjectArchive(command, payload);
418
419
  case 'project.runState': return await this.setProjectRunState(command, payload);
@@ -524,6 +525,27 @@ export class TeamService {
524
525
  return { project };
525
526
  }
526
527
 
528
+ /**
529
+ * 账本自检/修复入口(仅 Human)。`ledger.repair()` 此前没有任何生产调用点:
530
+ * 回滚失败被置为 poisoned 之后,除了重启宿主没有任何恢复路径。
531
+ */
532
+ async repairLedger(command) {
533
+ if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may repair the ledger');
534
+ const result = this.ledger.repair();
535
+ this.diag?.append({
536
+ ev: 'ledger.repaired',
537
+ projectId: command.projectId ?? null,
538
+ repair: result?.repair ?? null,
539
+ events: result?.events ?? null,
540
+ stateLastSeq: result?.stateLastSeq ?? null,
541
+ });
542
+ return {
543
+ repaired: result?.repair ?? null,
544
+ repairs: Array.isArray(result?.repairs) ? result.repairs : [],
545
+ events: result?.events ?? null,
546
+ stateLastSeq: result?.stateLastSeq ?? null,
547
+ };
548
+ }
527
549
  async changeProjectWorkspace(command, payload) {
528
550
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may change the Project workspace');
529
551
  const projectId = command.projectId;
@@ -1107,6 +1129,12 @@ export class TeamService {
1107
1129
  if (typeof dependency !== 'string' || Object.hasOwn(state.tasks ?? {}, dependency) !== true) {
1108
1130
  fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} is not a Task of this project`);
1109
1131
  }
1132
+ // 删除是 tombstone 而不是物理移除,而依赖判定只认 status === 'done':
1133
+ // 指向一张已删除的卡会让新卡**永久** blocked,且没有修复命令。
1134
+ const dependencyTask = state.tasks[dependency];
1135
+ if (dependencyTask?.tombstone === true || dependencyTask?.status === 'deleted' || dependencyTask?.status === 'cancelled') {
1136
+ fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} can never complete (it is ${dependencyTask?.tombstone === true ? 'deleted' : String(dependencyTask?.status)})`);
1137
+ }
1110
1138
  }
1111
1139
  }
1112
1140
  const title = typeof payload.title === 'string' ? payload.title.trim() : '';
@@ -1313,10 +1341,14 @@ export class TeamService {
1313
1341
  // 合同是「返回回答列表」:这里曾返回数字 0,调用方按数组迭代时抛 TypeError,
1314
1342
  // 整个 PMO tick 被打断且每个 tick 都重复失败。
1315
1343
  if (humanId === null || humanId === undefined) return [];
1344
+ // 只自动回答**有结构化问题**的决策项。成员致命失败生成的升级项没有 questions,
1345
+ // 自动作答会用一句通用话术把它 resolved,Human 再也看不到真正的失败。
1316
1346
  const items = Object.values(this.state.inbox ?? {}).filter((item) =>
1317
1347
  item.memberId === humanId
1318
1348
  && item.type === 'decision_required'
1319
- && item.state === 'unread');
1349
+ && item.state === 'unread'
1350
+ && Array.isArray(item.ref?.questions)
1351
+ && item.ref.questions.length > 0);
1320
1352
  const results = [];
1321
1353
  for (const item of items) {
1322
1354
  const questions = Array.isArray(item.ref?.questions) ? item.ref.questions : [];
@@ -1,4 +1,4 @@
1
- /**
1
+ /**
2
2
  * 优化 job 的宿主侧收割:每个 PMO tick 调用一次,把状态机的一步动作落到
3
3
  * 真实文件/子代理/结果记录上。
4
4
  *
@@ -82,7 +82,10 @@ export async function stepJob(input) {
82
82
  deps.diag?.({ ev: 'skillopt.job.fail', jobId: job.id, reason: validation.reason });
83
83
  break;
84
84
  }
85
- job = { ...job, before, candidate: action.payload.text, backup: await deps.vcs.backup(job.skillPath, before) };
85
+ // 不是每个 vcs 适配器都有 backup(git 适配器就没有):无脑调用会 TypeError,
86
+ // job 卡到 TTL 才失败。
87
+ const backup = typeof deps.vcs?.backup === 'function' ? await deps.vcs.backup(job.skillPath, before) : null;
88
+ job = { ...job, before, candidate: action.payload.text, backup };
86
89
  // 先落盘再改 live:中途崩溃时 job 里已有 before/backup,可据此回滚;
87
90
  // 反过来(先改 live)会让磁盘上的技能停在未审候选且无任何记录。
88
91
  writeJob(projectDir, job);
@@ -140,13 +143,28 @@ export async function stepJob(input) {
140
143
  deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
141
144
  }
142
145
  }
143
- if (plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
146
+ // 失败/完成是终态:plan 是在 switch 之前算的,若拿它回写就会把刚判死的 job
147
+ // 复活成 judging,下一轮再拿一个未应用的候选写假记录。
148
+ const terminal = job.state === 'failed' || job.state === 'done';
149
+ if (!terminal && plan.next !== job.state && plan.next !== 'failed') job = { ...job, state: plan.next, updatedAt: deps.now() };
144
150
  writeJob(projectDir, job);
145
151
  return { job, changed: true };
146
152
  }
147
153
 
148
154
  async function rollback({ deps, job, projectDir }) {
149
155
  if (job?.candidate === undefined || job?.before === undefined) return;
156
+ // 回滚前必须确认 live 仍是**我们写下的那个候选**:评审期间可能有人手改,
157
+ // 无条件把陈旧的 before 写回去会覆盖掉那次人工修改(且原子性无从谈起)。
158
+ let current = null;
159
+ try {
160
+ current = deps.readText ? deps.readText(job.skillPath) : null;
161
+ } catch {
162
+ current = null;
163
+ }
164
+ if (typeof current === 'string' && sha12(current) !== sha12(job.candidate)) {
165
+ deps.diag?.({ ev: 'skillopt.rollback.skipped', jobId: job.id, reason: 'live file changed since the candidate was applied' });
166
+ return;
167
+ }
150
168
  try {
151
169
  if (deps.vcs.kind === 'file' && typeof job.backup === 'string') {
152
170
  await deps.vcs.restore(job.skillPath, job.backup);
@@ -88,6 +88,9 @@ export function parseJudgeOutput(output) {
88
88
  better: row.better,
89
89
  margin: row.margin === 'clear' ? 'clear' : 'slight',
90
90
  reason: typeof row.reason === 'string' ? row.reason.slice(0, 300) : '',
91
+ // 评审通道的回帖带 orderId(这一票对应哪一个 A/B 顺序);judge 通道没有
92
+ // 这个字段,忽略即可。保留它才能让两条通道共用同一个解析器。
93
+ ...(typeof row.orderId === 'string' && row.orderId !== '' ? { orderId: row.orderId } : {}),
91
94
  };
92
95
  }
93
96
  return found;
@@ -7,6 +7,7 @@
7
7
  * 的条目即可拿到 verdict,**不依赖一次性子代理的输出**。
8
8
  */
9
9
  import { REVIEWER_NAME, REVIEWER_ROLE, buildReviewRequest, decideReviewVotes, reviewVoteCount } from './reviewer.js';
10
+ import { parseJudgeOutput } from './judge.js';
10
11
 
11
12
  const REVIEW_TASK_PREFIX = 'skillopt-review';
12
13
 
@@ -79,14 +80,9 @@ export function collectReview({ service, job }) {
79
80
  for (const entry of entries) {
80
81
  if (votes.length >= orders.length) break;
81
82
  if (entry?.authorId !== reviewerId) continue;
82
- const parsed = (() => {
83
- try {
84
- const match = String(entry.body ?? '').match(/\{[\s\S]*?"better"[\s\S]*?\}/);
85
- return match === null ? null : JSON.parse(match[0]);
86
- } catch {
87
- return null;
88
- }
89
- })();
83
+ // 复用 judge 的容错解析:自己的「第一个 { 到第一个 }」正则会把模板回显
84
+ // 计成票,也会在正文含 } 时整票丢弃。
85
+ const parsed = parseJudgeOutput(entry.body);
90
86
  if (parsed === null || (parsed.better !== 'A' && parsed.better !== 'B' && parsed.better !== 'tie')) continue;
91
87
  let order = typeof parsed.orderId === 'string' ? byOrderId.get(parsed.orderId) : undefined;
92
88
  // 旧 job 的 orders 没有 orderId:保留按序对齐的兼容路径,但仍受票数上限约束。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.39",
3
+ "version": "0.4.41",
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",