@suifei/dsh-ai-team 0.4.35 → 0.4.37

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,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.37 - 2026-11-12
4
+
5
+ **中危批次 7:评审卡收口、job 终态、幽灵成员、重试预算**
6
+
7
+ - **评审卡三条终态都收口**:成功路径原本会关掉评审卡,超时与 conflict 两条失败路径不会——卡永久 pending 进入 PMO 的 active 集合,被 heartbeat/stall/escalate 反复唤醒评审官。现在收口逻辑抽成一个 `closeReviewCard`,三条路径共用。
8
+ - **done 不可被回退**:并发收票/收割时,后到的一次判断可能把已 done 的 job 覆写成 failed(之后 TTL 与统计都按错误状态走)。`writeJob` 现在拒绝用非 done 状态覆盖 done。
9
+ - **幽灵成员与幽灵依赖**:`task.create` 之前不校验 `ownerId` / `assigneeId` / `blockedBy`,不存在的 id 会直接写进投影且没有修复命令——卡永久挂在不存在的人名下,或被一个不存在的依赖永久 blocked。现在统一走 `requireMemberRef`(与 `taskCommand` 共用同一实现)。
10
+ - **重试预算按请求算**:`retryDecision` 的 `attempt` 原来传的是 `member.attempts`(成员**生命周期**失败计数),换路索引被跳过、预算被历史失败提前耗尽。改为按会话 + 10 分钟窗口的连续失败计数。
11
+ - 测试:`node --test` **233/233**(新增 3 例)。
12
+
13
+ ## 0.4.36 - 2026-11-12
14
+
15
+ **中危批次 6:PMO tick 崩溃、重复决策、接管不污染验收资格、退役终态**
16
+
17
+ - **PMO tick 不再每轮抛 TypeError**:`autoAnswerDecisions` 在 Human 缺失时返回数字 `0`,调用方按数组迭代直接 TypeError,整个 tick 被打断且每轮重复。改为返回 `[]`。
18
+ - **重复决策被拒**:`answerDecision` 没有终态前置,对已 `resolved`/`dismissed`/`superseded` 的决策项再次提交会被接受,重复写 Thread 回复、ack 回来的还是旧答案。
19
+ - **接管不再污染验收资格**(INV-07):`task/taken-over` 把继任者写进 `claimHistory`,而 `isReviewCandidate` 会排除 `claimHistory` 里的人——继任者因此永久没有资格验收自己名下的卡。接管事实改由既有的 `takeoverHistory` 记录。
20
+ - **退役是终态**:`member.fail` 与迟到的 `recordMemberFailure` 都不再接受退役成员(此前 retired 会被改写成 failed,随后 `member.bind` 能把成员复活)。
21
+ - **删除死代码**:`installFileSkillProvider` 按「`registerProvider` 可能返回 invalidate」处理,而 SDK 契约只返回 disposer——该分支永远不可达,已按契约收敛。
22
+ - 测试:`node --test` **231/231**(新增 3 例;另按 INV-07 更新 1 处既有断言)。
23
+
3
24
  ## 0.4.35 - 2026-11-12
4
25
 
5
26
  **中危批次 5:命名空间、poison 恢复、多数决、并发认领**
package/index.js CHANGED
@@ -20,7 +20,7 @@ import { ids } from './lib/domain/ids.js';
20
20
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
21
21
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
22
22
  import { repairArchivedHosts as repairHostSessions } from './lib/runtime/host-repair.js';
23
- import { classifyLlmFailure, retryDecision } from './lib/runtime/failure-policy.js';
23
+ import { classifyLlmFailure, nextRequestAttempt, retryDecision } from './lib/runtime/failure-policy.js';
24
24
  import { memberIdentity } from './lib/domain/member-profile.js';
25
25
  import { loadSkillContext } from './lib/runtime/skill-loader.js';
26
26
  import { formatSkillCatalog } from './lib/runtime/skill-catalog.js';
@@ -410,7 +410,10 @@ export function apply(ctx, config = {}) {
410
410
  // fallback(换路),此前一律 next() 让它们的 fallback 永远不可达。
411
411
  const fallbackCapable = failure.action === 'fallback' || failure.action === 'compact_or_fallback';
412
412
  if (!failure.retryable && !fallbackCapable) return next();
413
- const decision = retryDecision(failure, member.config ?? {}, recorded.member.attempts ?? 1);
413
+ // 用「本次请求」的连续失败数,而不是成员生命周期的 attempts:后者会让换路索引
414
+ // 被跳过、重试预算被历史失败提前耗尽。
415
+ const attempt = nextRequestAttempt(requestAttempts, member.sessionId);
416
+ const decision = retryDecision(failure, member.config ?? {}, attempt);
414
417
  if (decision.action === 'fallback' && decision.patch !== undefined) {
415
418
  try {
416
419
  await failureRuntime.service.applySystemFallback(member.id, decision.patch, 'llm-fallback', failureRuntime.id);
@@ -524,6 +527,8 @@ export function apply(ctx, config = {}) {
524
527
  // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
525
528
  // 造成 autoAnswerDecisions/reconcileJobs 并发执行同一条账本。按 Project 去重。
526
529
  const pmoBusy = new Set();
530
+ // 本次请求的连续失败计数(按成员会话、10 分钟窗口)。
531
+ const requestAttempts = new Map();
527
532
  const activationTasks = new Map();
528
533
  const pmoLastKick = new Map();
529
534
  const pmoLastStall = new Map();
@@ -1224,6 +1229,22 @@ export function apply(ctx, config = {}) {
1224
1229
  const jobs = roots.flatMap((jobRoot) => listJobs(jobRoot));
1225
1230
  // judging 状态的 job:从评审卡收票(账本通道),不走子代理 reconcile。
1226
1231
  const actor = { kind: 'human', memberId: HUMAN_ID };
1232
+ // 评审卡收口:成功、超时、冲突三条终态都要关。否则卡保持 pending 进入
1233
+ // PMO 的 active 集合,被 heartbeat/stall/escalate 反复唤醒评审官。
1234
+ const closeReviewCard = async (runtime, taskId, reason) => {
1235
+ try {
1236
+ const card = runtime.service.state.tasks?.[taskId];
1237
+ if (card === undefined || card.status === 'done' || card.status === 'cancelled' || card.tombstone === true) return;
1238
+ await runtime.service.dispatch({
1239
+ type: 'task.cancel',
1240
+ payload: { taskId, expectedRevision: card.revision, reason },
1241
+ actor,
1242
+ projectId: runtime.id,
1243
+ });
1244
+ } catch (error) {
1245
+ diag.append({ ev: 'skillopt.review.card.close.fail', taskId, message: error?.message ?? String(error) });
1246
+ }
1247
+ };
1227
1248
  for (const job of jobs) {
1228
1249
  if (job.state !== 'judging' || typeof job.reviewTaskId !== 'string') continue;
1229
1250
  const runtime = [...(booted?.runtimes?.values?.() ?? [])].find((entry) => entry.dir === job.project);
@@ -1243,6 +1264,8 @@ export function apply(ctx, config = {}) {
1243
1264
  error: `review timed out after ${Math.round(REVIEW_JOB_TTL_MS / 60000)}min (${collected.votes.length}/${expected} votes)`,
1244
1265
  updatedAt: Date.now(),
1245
1266
  });
1267
+ // 超时也要收口:否则这张卡永久 pending,PMO 会一直唤醒评审官。
1268
+ await closeReviewCard(runtime, job.reviewTaskId, 'blind review timed out');
1246
1269
  diag.append({ ev: 'skillopt.job.timeout', jobId: job.id, got: collected.votes.length, expected });
1247
1270
  continue;
1248
1271
  }
@@ -1257,6 +1280,7 @@ export function apply(ctx, config = {}) {
1257
1280
  try { liveText = existsSync(job.skillPath) ? readFileSync(job.skillPath, 'utf8') : null; } catch { liveText = null; }
1258
1281
  if (liveText !== null && typeof job.before === 'string' && sha12(liveText) !== sha12(job.before)) {
1259
1282
  writeJob(jobDir, { ...job, state: 'failed', error: 'live SKILL.md changed during review (conflict)', updatedAt: Date.now() });
1283
+ await closeReviewCard(runtime, job.reviewTaskId, 'blind review aborted: live file changed');
1260
1284
  diag.append({ ev: 'skillopt.job.conflict', jobId: job.id, skillPath: job.skillPath });
1261
1285
  continue;
1262
1286
  }
@@ -1286,23 +1310,7 @@ export function apply(ctx, config = {}) {
1286
1310
  writeJob(jobDir, { ...job, state: 'done', decision: collected.decision, backup: backupPath ?? job.backup ?? null, updatedAt: Date.now() });
1287
1311
  // 评审卡必须收口:否则它保持 pending 进入 PMO 的 active 集合,
1288
1312
  // 会被 heartbeat/stall/escalate 反复唤醒评审官(每 job 永久留一张卡)。
1289
- try {
1290
- const card = runtime.service.state.tasks?.[job.reviewTaskId];
1291
- if (card !== undefined && card.status !== 'done' && card.status !== 'cancelled' && card.tombstone !== true) {
1292
- await runtime.service.dispatch({
1293
- type: 'task.cancel',
1294
- payload: {
1295
- taskId: job.reviewTaskId,
1296
- expectedRevision: card.revision,
1297
- reason: `blind review collected: ${collected.decision.verdict}`,
1298
- },
1299
- actor,
1300
- projectId: runtime.id,
1301
- });
1302
- }
1303
- } catch (error) {
1304
- diag.append({ ev: 'skillopt.review.card.close.fail', jobId: job.id, taskId: job.reviewTaskId, message: error?.message ?? String(error) });
1305
- }
1313
+ await closeReviewCard(runtime, job.reviewTaskId, `blind review collected: ${collected.decision.verdict}`);
1306
1314
  diag.append({ ev: 'skillopt.job.done', jobId: job.id, verdict: collected.decision.verdict, better: collected.decision.better, worse: collected.decision.worse, kept, source: 'reviewer-card' });
1307
1315
  }
1308
1316
  if (jobs.length === 0) return '[skillopt jobs] none';
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
2
  import pathDefault from 'node:path';
3
3
  import { ERRORS, fail } from '../domain/errors.js';
4
4
  import { findReportPath, parseDecisionQuestions } from './decision-report.js';
@@ -99,6 +99,18 @@ function handoffMarkdown(state, project, nowMs) {
99
99
  return out.join('\n') + '\n';
100
100
  }
101
101
 
102
+ /**
103
+ * 成员引用的统一校验:幽灵 id 写进投影后没有修复命令,卡片会永久挂在不存在的人名下。
104
+ * `agentOnly` 用于只能由 Agent 担任的字段(assignee)。
105
+ */
106
+ export function requireMemberRef(state, memberId, field, { agentOnly = false } = {}) {
107
+ if (typeof memberId !== 'string' || memberId === '') return;
108
+ const candidate = state?.members?.[memberId];
109
+ if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
110
+ if (agentOnly && candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
111
+ if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
112
+ }
113
+
102
114
  export class TeamService {
103
115
  /**
104
116
  * @param {{ ledger: { state: any, append: (input: any) => Promise<any> }, now?: () => number, diag?: { append: (row: any) => any } }} options
@@ -710,6 +722,8 @@ export class TeamService {
710
722
  if (command.actor.kind !== 'human') fail(ERRORS.UNAUTHORIZED, 'only Human may mark a member failed');
711
723
  const member = this.state.members?.[payload.memberId];
712
724
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(payload.memberId)} not found`);
725
+ // 退役是终态:把 retired 改成 failed 会让 member.bind 之后把 ta 复活。
726
+ if (member.status === 'retired') fail(ERRORS.INVALID_STATE, `member ${member.id} is retired`);
713
727
  await this.append(command, 'member/failed', { memberId: member.id, reason: payload.reason ?? '' });
714
728
  return { member: { ...member, status: 'failed', failure: payload.reason ?? '' } };
715
729
  }
@@ -939,6 +953,9 @@ export class TeamService {
939
953
  async recordMemberFailure(memberId, failure, projectId = Object.keys(this.state.projects ?? {})[0]) {
940
954
  const member = this.state.members?.[memberId];
941
955
  if (member === undefined) fail(ERRORS.NOT_FOUND, `member ${String(memberId)} not found`);
956
+ // 退役成员不该被迟到的 LLM 失败改成 failed(fold 对这条事件没有 retired 守卫,
957
+ // 之后 member.bind 就能把 ta 复活)。直接忽略,不写事件。
958
+ if (member.status === 'retired') return null;
942
959
  const attempt = Number.isSafeInteger(failure.attempt) ? failure.attempt : (member.lastFailure?.attempt ?? 0) + 1;
943
960
  const fatal = failure.category === 'auth' || failure.category === 'billing' || failure.category === 'policy' || failure.category === 'unknown';
944
961
  // Tool-argument and provider dumps can run to kilobytes; the ledger and
@@ -1063,6 +1080,17 @@ export class TeamService {
1063
1080
  if (qaRequired && qaChecklist.length === 0) {
1064
1081
  fail(ERRORS.INVALID_ARGUMENT, 'qaRequired needs at least one qaChecklist item');
1065
1082
  }
1083
+ // 幽灵成员 id / 不存在的依赖会被直接写进投影,且没有修复命令:卡的 owner 永远
1084
+ // 不对,或被一个不存在的依赖永久 blocked。
1085
+ requireMemberRef(state, ownerId, 'ownerId');
1086
+ requireMemberRef(state, payload.assigneeId, 'assigneeId', { agentOnly: true });
1087
+ if (Array.isArray(payload.blockedBy)) {
1088
+ for (const dependency of payload.blockedBy) {
1089
+ if (typeof dependency !== 'string' || state.tasks?.[dependency] === undefined) {
1090
+ fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} is not a Task of this project`);
1091
+ }
1092
+ }
1093
+ }
1066
1094
  const title = typeof payload.title === 'string' ? payload.title.trim() : '';
1067
1095
  const resultDefinition = typeof payload.resultDefinition === 'string' ? payload.resultDefinition.trim() : '';
1068
1096
  const duplicate = Object.values(state.tasks ?? {}).find((candidate) =>
@@ -1102,13 +1130,7 @@ export class TeamService {
1102
1130
  const expectedRevision = command.payload?.expectedRevision;
1103
1131
  // 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
1104
1132
  // 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
1105
- const requireAgentMember = (memberId, field) => {
1106
- if (typeof memberId !== 'string' || memberId === '') return;
1107
- const candidate = this.state.members?.[memberId];
1108
- if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
1109
- if (candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
1110
- if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
1111
- };
1133
+ const requireAgentMember = (memberId, field) => requireMemberRef(this.state, memberId, field, { agentOnly: true });
1112
1134
  let outcome;
1113
1135
  switch (action) {
1114
1136
  case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
@@ -1270,7 +1292,9 @@ export class TeamService {
1270
1292
  /** PMO: answer all pending structured questions with the max-value policy. */
1271
1293
  async autoAnswerDecisions(projectId = Object.keys(this.state.projects ?? {})[0]) {
1272
1294
  const humanId = this.humanId();
1273
- if (humanId === null) return 0;
1295
+ // 合同是「返回回答列表」:这里曾返回数字 0,调用方按数组迭代时抛 TypeError,
1296
+ // 整个 PMO tick 被打断且每个 tick 都重复失败。
1297
+ if (humanId === null || humanId === undefined) return [];
1274
1298
  const items = Object.values(this.state.inbox ?? {}).filter((item) =>
1275
1299
  item.memberId === humanId
1276
1300
  && item.type === 'decision_required'
@@ -1393,6 +1417,11 @@ export class TeamService {
1393
1417
  }
1394
1418
  const humanId = command.actor.memberId;
1395
1419
  if (item.memberId !== humanId) fail(ERRORS.UNAUTHORIZED, 'decision belongs to another member');
1420
+ // 终态前置:已 resolved/dismissed/superseded 的决策项再次提交过去会被接受,
1421
+ // 于是同一决策重复写 Thread 回复,ack 回来的 item 还是旧答案。
1422
+ if (['resolved', 'dismissed', 'superseded'].includes(item.state)) {
1423
+ fail(ERRORS.INVALID_STATE, `decision ${String(item.id)} is already ${String(item.state)}`);
1424
+ }
1396
1425
  const answers = (Array.isArray(payload.answers) ? payload.answers : [])
1397
1426
  .map((answer, index) => ({
1398
1427
  id: typeof answer?.id === 'string' && answer.id !== '' ? answer.id : `q${index + 1}`,
@@ -452,14 +452,15 @@ function applyTaskEvent(state, event, payload) {
452
452
  case 'task/taken-over': {
453
453
  const to = textOr(payload.toMemberId, null);
454
454
  if (to === null) return advance(state, event);
455
- const history = Array.isArray(task.claimHistory) ? task.claimHistory : [];
455
+ // INV-07:只有 claim 能进 claimHistory。接管曾把继任者写进去,而
456
+ // isReviewCandidate 会排除所有在 claimHistory 里的人——继任者因此永久
457
+ // 没有资格验收自己名下的这张卡。接管事实由 takeoverHistory 记录。
456
458
  const takeoverHistory = Array.isArray(task.takeoverHistory) ? task.takeoverHistory : [];
457
459
  return patch({
458
460
  ...task,
459
461
  accountableOwnerId: to,
460
462
  ownerId: to,
461
463
  assigneeId: to,
462
- claimHistory: history.includes(to) ? history : [...history, to],
463
464
  takeoverHistory: [...takeoverHistory, {
464
465
  from: textOr(payload.fromMemberId, task.assigneeId ?? task.ownerId ?? null),
465
466
  to,
@@ -91,6 +91,23 @@ function fallbackAt(config, index) {
91
91
  * turn (it can only take effect on the next wake, because a step's route is
92
92
  * captured before dispatch); `fail` ends the turn unchanged.
93
93
  */
94
+ /**
95
+ * 本次请求的连续失败次数。
96
+ *
97
+ * 此前调用方把 `member.attempts`(成员**生命周期**里的失败计数)当成本次尝试数传进来,
98
+ * 于是换路索引被跳过、重试预算被历史失败提前耗尽。这里按会话维护一个窗口内的计数:
99
+ * 窗口过期即视为新请求(成员被唤醒重试时应当拿到完整预算)。
100
+ */
101
+ export function nextRequestAttempt(store, sessionId, now = Date.now(), windowMs = 10 * 60_000) {
102
+ const key = typeof sessionId === 'string' && sessionId !== '' ? sessionId : '(unknown)';
103
+ const prior = store?.get?.(key);
104
+ const attempt = prior !== undefined && typeof prior.at === 'number' && now - prior.at < windowMs
105
+ ? prior.count + 1
106
+ : 1;
107
+ store?.set?.(key, { count: attempt, at: now });
108
+ return attempt;
109
+ }
110
+
94
111
  export function retryDecision(failure, config = {}, attempt = 1) {
95
112
  const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
96
113
  ? Math.max(1, Math.min(config.retry.maxAttempts, 5))
@@ -194,17 +194,12 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
194
194
  export function installFileSkillProvider(skills, options) {
195
195
  if (!skills || typeof skills.registerProvider !== 'function') return () => {};
196
196
  const provider = createFileSkillProvider(options);
197
+ // SDK 契约(dsh-skill.md):`registerProvider` 同步注册、**返回 disposer**,
198
+ // 没有 invalidate 这一档。旧实现按「可能返回 { dispose, invalidate }」处理,
199
+ // invalidate 分支永远不可达,属于死代码——这里只保留真实的两种返回形态。
197
200
  const control = skills.registerProvider(() => provider);
198
- // registerProvider 可能返回 disposer,也可能返回 { dispose, invalidate } 的
199
- // control:直接把它当函数调用会在 teardown 里抛错(provider 泄漏),且从不
200
- // invalidate 会让技能目录一直停在注册时的快照。
201
- if (typeof control === 'function') {
202
- return () => {
203
- try { control(); } catch { /* already disposed */ }
204
- };
205
- }
201
+ const dispose = typeof control === 'function' ? control : control?.dispose;
206
202
  return () => {
207
- try { control?.invalidate?.(); } catch { /* cache may be gone */ }
208
- try { control?.dispose?.(); } catch { /* already disposed */ }
203
+ try { dispose?.(); } catch { /* already disposed */ }
209
204
  };
210
205
  }
@@ -54,6 +54,13 @@ export function writeJob(projectDir, job) {
54
54
  const dir = jobsDir(projectDir);
55
55
  mkdirSync(dir, { recursive: true });
56
56
  const target = join(dir, `${job.id}.json`);
57
+ // done 是终态,不可被回退:并发收票/收割时,后到的一次判断可能把已完成的 job
58
+ // 覆写成 failed,之后 TTL 与统计都会按错误状态走。
59
+ const existing = readJob(projectDir, job.id);
60
+ if (existing !== null && existing.state === 'done' && job.state !== 'done') {
61
+ console.warn(`[skillopt] refusing to overwrite a done job ${job.id} with ${String(job.state)}`);
62
+ return existing;
63
+ }
57
64
  const temp = `${target}.tmp`;
58
65
  writeFileSync(temp, JSON.stringify(job, null, 2), 'utf8');
59
66
  renameSync(temp, target);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.35",
3
+ "version": "0.4.37",
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",