@suifei/dsh-ai-team 0.4.36 → 0.4.38

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.38 - 2026-11-12
4
+
5
+ **中危批次 8:技能根、决策串行化、失败升级去重**
6
+
7
+ - **成员技能不再静默缺席**:`loadSkillContext` 只在一个根下找 `skills/`,而调用方传的是**项目账本目录**,它下面永远没有 `skills/`。现在支持多根:工作区 `.dsh/skills`、用户 `~/.dsh/skills`、插件数据目录依次查找。
8
+ - **决策命令串行化**:`decision.request` / `decision.answer` 与 task 命令一样纳入 `runExclusive`——`answerDecision` 之前仍在锁外「读 headSeq → 分配 seq → append」,并发时同 seq 会被 fold 去重静默丢弃,双方都返回成功。
9
+ - **失败升级不再被自己的决策吞掉**:升级项的去重键用的是 `ref.memberId`,而 `requestDecision` 里同名字段的语义是「申请人」——成员只要有一条自己提的未决决策,ta 的致命失败就再也不会生成升级项。现在升级项带 `ref.kind = 'member_failure'` + `ref.failedMemberId`,按自己的字段去重(旧数据也做了兼容判定)。
10
+ - 测试:`node --test` **235/235**(新增 2 例)。
11
+
12
+ ## 0.4.37 - 2026-11-12
13
+
14
+ **中危批次 7:评审卡收口、job 终态、幽灵成员、重试预算**
15
+
16
+ - **评审卡三条终态都收口**:成功路径原本会关掉评审卡,超时与 conflict 两条失败路径不会——卡永久 pending 进入 PMO 的 active 集合,被 heartbeat/stall/escalate 反复唤醒评审官。现在收口逻辑抽成一个 `closeReviewCard`,三条路径共用。
17
+ - **done 不可被回退**:并发收票/收割时,后到的一次判断可能把已 done 的 job 覆写成 failed(之后 TTL 与统计都按错误状态走)。`writeJob` 现在拒绝用非 done 状态覆盖 done。
18
+ - **幽灵成员与幽灵依赖**:`task.create` 之前不校验 `ownerId` / `assigneeId` / `blockedBy`,不存在的 id 会直接写进投影且没有修复命令——卡永久挂在不存在的人名下,或被一个不存在的依赖永久 blocked。现在统一走 `requireMemberRef`(与 `taskCommand` 共用同一实现)。
19
+ - **重试预算按请求算**:`retryDecision` 的 `attempt` 原来传的是 `member.attempts`(成员**生命周期**失败计数),换路索引被跳过、预算被历史失败提前耗尽。改为按会话 + 10 分钟窗口的连续失败计数。
20
+ - 测试:`node --test` **233/233**(新增 3 例)。
21
+
3
22
  ## 0.4.36 - 2026-11-12
4
23
 
5
24
  **中危批次 6:PMO tick 崩溃、重复决策、接管不污染验收资格、退役终态**
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';
@@ -1513,7 +1521,7 @@ export function apply(ctx, config = {}) {
1513
1521
  const result = await runtime.activate(activationMember, {
1514
1522
  prompt: `${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
1515
1523
  ? body.payload.prompt
1516
- : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, projectRuntime.dir)}`,
1524
+ : '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${await formatSkillCatalog(skillsService, { cwd: effectiveDir })}${await loadSkillContext(activationMember, [join(effectiveDir, '.dsh'), dshHome(), projectRuntime.dir])}`,
1517
1525
  });
1518
1526
  let bound;
1519
1527
  try {
@@ -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
@@ -425,8 +437,8 @@ export class TeamService {
425
437
  case 'task.follow': return await this.follow(command, payload);
426
438
  case 'thread.post': return await this.postThread(command, payload);
427
439
  case 'inbox.ack': return await this.ack(command, payload);
428
- case 'decision.request': return await this.requestDecision(command, payload);
429
- case 'decision.answer': return await this.answerDecision(command, payload);
440
+ case 'decision.request': return await this.runExclusive(() => this.requestDecision(command, payload));
441
+ case 'decision.answer': return await this.runExclusive(() => this.answerDecision(command, payload));
430
442
  default: fail(ERRORS.INVALID_ARGUMENT, `unknown command: ${String(command.type)}`);
431
443
  }
432
444
  } catch (error) {
@@ -971,10 +983,15 @@ export class TeamService {
971
983
  let inboxItem = null;
972
984
  if (fatal) {
973
985
  const humanId = this.humanId();
986
+ // 去重必须用自己的判别字段:`ref.memberId` 在 requestDecision 里表示
987
+ // 「申请人」,与这里「失败的成员」同名不同义——成员只要有一条自己提的
988
+ // 未决决策,ta 的致命失败就再也不会生成升级项。
974
989
  const duplicate = humanId === null ? undefined : Object.values(this.state.inbox ?? {}).find((item) =>
975
990
  item.memberId === humanId
976
991
  && item.requiresDecision === true
977
- && item.ref?.memberId === memberId
992
+ && (item.ref?.kind === 'member_failure'
993
+ ? item.ref?.failedMemberId === memberId
994
+ : item.ref?.kind === undefined && item.ref?.memberId === memberId && item.ref?.category !== undefined)
978
995
  && !['resolved', 'dismissed', 'superseded'].includes(item.state));
979
996
  if (humanId !== null && duplicate === undefined) {
980
997
  const activeTask = Object.values(this.state.tasks ?? {}).find((task) =>
@@ -985,7 +1002,7 @@ export class TeamService {
985
1002
  inboxItem = createInboxItem({
986
1003
  memberId: humanId,
987
1004
  type: 'decision_required',
988
- ref: { memberId, category: recorded.category, taskId },
1005
+ ref: { kind: 'member_failure', failedMemberId: memberId, memberId, category: recorded.category, taskId },
989
1006
  requiresDecision: true,
990
1007
  }, { at: this.now() });
991
1008
  await this.ledger.append({
@@ -1068,6 +1085,17 @@ export class TeamService {
1068
1085
  if (qaRequired && qaChecklist.length === 0) {
1069
1086
  fail(ERRORS.INVALID_ARGUMENT, 'qaRequired needs at least one qaChecklist item');
1070
1087
  }
1088
+ // 幽灵成员 id / 不存在的依赖会被直接写进投影,且没有修复命令:卡的 owner 永远
1089
+ // 不对,或被一个不存在的依赖永久 blocked。
1090
+ requireMemberRef(state, ownerId, 'ownerId');
1091
+ requireMemberRef(state, payload.assigneeId, 'assigneeId', { agentOnly: true });
1092
+ if (Array.isArray(payload.blockedBy)) {
1093
+ for (const dependency of payload.blockedBy) {
1094
+ if (typeof dependency !== 'string' || state.tasks?.[dependency] === undefined) {
1095
+ fail(ERRORS.INVALID_ARGUMENT, `blockedBy ${String(dependency)} is not a Task of this project`);
1096
+ }
1097
+ }
1098
+ }
1071
1099
  const title = typeof payload.title === 'string' ? payload.title.trim() : '';
1072
1100
  const resultDefinition = typeof payload.resultDefinition === 'string' ? payload.resultDefinition.trim() : '';
1073
1101
  const duplicate = Object.values(state.tasks ?? {}).find((candidate) =>
@@ -1107,13 +1135,7 @@ export class TeamService {
1107
1135
  const expectedRevision = command.payload?.expectedRevision;
1108
1136
  // 目标成员必须真实存在且可用:幽灵 id 写进投影后,真实成员 claim 会一直
1109
1137
  // 撞 E_ALREADY_CLAIMED,只能由 owner/Human 重新指派才能解锁。
1110
- const requireAgentMember = (memberId, field) => {
1111
- if (typeof memberId !== 'string' || memberId === '') return;
1112
- const candidate = this.state.members?.[memberId];
1113
- if (candidate === undefined) fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not a Team member`);
1114
- if (candidate.kind !== 'agent') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} is not an agent member`);
1115
- if (candidate.status === 'retired') fail(ERRORS.INVALID_ARGUMENT, `${field} ${memberId} has left the team`);
1116
- };
1138
+ const requireAgentMember = (memberId, field) => requireMemberRef(this.state, memberId, field, { agentOnly: true });
1117
1139
  let outcome;
1118
1140
  switch (action) {
1119
1141
  case 'claim': outcome = claimTask(task, command.actor, state.tasks ?? {}, { expectedRevision, at: this.now() }); break;
@@ -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))
@@ -9,19 +9,28 @@ const MAX_SKILL_CHARS = 1800;
9
9
  export async function loadSkillContext(member, dataDir) {
10
10
  const skills = Array.isArray(member?.skills) ? member.skills : [];
11
11
  const chunks = [CORE_SKILL_TEXT.replace(/^---[\s\S]*?\n---\s*/, '').trim()];
12
- for (const raw of (typeof dataDir === 'string' ? skills.slice(0, 4) : [])) {
12
+ // 可以传一个根,也可以传多个根(工作区 `.dsh/skills`、用户 `~/.dsh/skills`、插件数据目录)。
13
+ // 只认一个根时,成员声明的技能会静默缺席——调用方传的是项目账本目录,它下面
14
+ // 永远没有 `skills/`。
15
+ const roots = (Array.isArray(dataDir) ? dataDir : [dataDir])
16
+ .filter((root) => typeof root === 'string' && root !== '');
17
+ for (const raw of skills.slice(0, 4)) {
13
18
  const name = basename(String(raw)).replace(/[^a-zA-Z0-9._-]/g, '');
14
19
  if (name === '' || name === '.' || name === '..' || name.startsWith('.')) continue;
15
20
  if (isSkillExcluded(name)) continue;
16
- const candidates = [join(dataDir, 'skills', name, 'SKILL.md'), join(dataDir, 'skills', `${name}.md`)];
17
- for (const candidate of candidates) {
18
- try {
19
- const text = await readFile(candidate, 'utf8');
20
- chunks.push(`### ${name}\n${text.slice(0, MAX_SKILL_CHARS)}`);
21
- break;
22
- } catch (error) {
23
- if (error?.code !== 'ENOENT') break;
21
+ for (const root of roots) {
22
+ let loaded = false;
23
+ for (const candidate of [join(root, 'skills', name, 'SKILL.md'), join(root, 'skills', `${name}.md`)]) {
24
+ try {
25
+ const text = await readFile(candidate, 'utf8');
26
+ chunks.push(`### ${name}\n${text.slice(0, MAX_SKILL_CHARS)}`);
27
+ loaded = true;
28
+ break;
29
+ } catch (error) {
30
+ if (error?.code !== 'ENOENT') break;
31
+ }
24
32
  }
33
+ if (loaded) break;
25
34
  }
26
35
  }
27
36
  return chunks.length === 0 ? '' : `\n\n[技能资料]\n${chunks.join('\n\n')}`;
@@ -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.36",
3
+ "version": "0.4.38",
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",