@suifei/dsh-ai-team 0.4.23 → 0.4.27

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.
@@ -41,6 +41,13 @@ export const DEFAULT_SEGMENT_BYTES = 32 * 1024 * 1024;
41
41
  export const SEGMENT_PATTERN = /^ledger-(\d{6})\.jsonl$/;
42
42
  export const LOCK_FILE = 'lock';
43
43
 
44
+ /**
45
+ * Grace period for an unreadable lock record. The lock file is created empty and
46
+ * filled immediately after, so a 0-byte file is normal for a live writer; only
47
+ * an unreadable record older than this counts as a crashed writer.
48
+ */
49
+ export const LOCK_WRITE_GRACE_MS = 10_000;
50
+
44
51
  const DRAFT_FIELDS = new Set([
45
52
  'type',
46
53
  'payload',
@@ -148,6 +155,8 @@ export class LedgerWriter {
148
155
  this._repairs = [];
149
156
  this._openResult = null;
150
157
  this._queue = Promise.resolve();
158
+ // 回滚失败后置为非空:本句柄不可继续写,必须 close + open 重新扫描。
159
+ this._poisoned = null;
151
160
  }
152
161
 
153
162
  get head() {
@@ -187,6 +196,7 @@ export class LedgerWriter {
187
196
  }
188
197
 
189
198
  const repairs = [];
199
+ this._poisoned = null;
190
200
  try {
191
201
  if (this.useLock) this._acquireLock(repairs);
192
202
  const scan = this._scan({ repairTail: this.repairTailOnOpen });
@@ -261,6 +271,14 @@ export class LedgerWriter {
261
271
  return Promise.reject(new LedgerError('E_EVENT_INVALID', 'appendMany expects an array'));
262
272
  }
263
273
  if (drafts.length === 0) return Promise.resolve([]);
274
+ // 回滚失败过:本句柄的历史不再可信(可能已有半截写入留在段内),
275
+ // 继续接单会把后续事件追加到未知状态之后。要求 close + open 重新扫描。
276
+ if (this._poisoned !== null && this._poisoned !== undefined) {
277
+ return Promise.reject(new LedgerError('E_LEDGER_POISONED',
278
+ `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
279
+ rollbackError: this._poisoned,
280
+ }));
281
+ }
264
282
  return this._enqueue(() => this._appendBatch(drafts));
265
283
  }
266
284
 
@@ -499,13 +517,13 @@ export class LedgerWriter {
499
517
  if (this.fsync) this._fs.fsyncSync(segFd);
500
518
  this._fs.closeSync(segFd);
501
519
  }
502
- // 段号 = 上一个已存在段的编号 + 1;全新账本的第一段仍是 000001。
503
- const lastIndex =
504
- created.length > 0
505
- ? created[created.length - 1].index
506
- : origin.fd !== null
507
- ? origin.index
508
- : origin.index - 1;
520
+ // 段号 = 磁盘上已存在段的最大编号 + 1(全新账本的第一段是 000001)。
521
+ // 不能从 origin.index 推导:回滚失败会留下 fd=null 的当前段,
522
+ // 而 origin.index 是「下一个待用编号」,据此新建会复用已存在的段号。
523
+ const lastIndex = Math.max(
524
+ created.length > 0 ? created[created.length - 1].index : 0,
525
+ this._lastSegmentIndexOnDisk(),
526
+ );
509
527
  segIndex = lastIndex + 1;
510
528
  segName = formatSegmentName(segIndex);
511
529
  segPath = path.join(this.dir, segName);
@@ -523,6 +541,7 @@ export class LedgerWriter {
523
541
  if (this.fsync) this._fs.fsyncSync(segFd);
524
542
  } catch (writeError) {
525
543
  const rollbackError = this._rollback(origin, created, segFd);
544
+ if (rollbackError) this._poisoned = rollbackError;
526
545
  if (writeError instanceof LedgerError) {
527
546
  if (rollbackError) writeError.details = { ...writeError.details, rollbackError };
528
547
  throw writeError;
@@ -611,6 +630,8 @@ export class LedgerWriter {
611
630
 
612
631
  _syncCurrentFromScan(scan) {
613
632
  if (scan.segments.length === 0) {
633
+ // 空账本:**不要**预创建段文件——空段会被扫描当成可修复的尾段删掉,
634
+ // 段号就跳到 2 了。fd 留空,首次 append 会按需创建 000001。
614
635
  this._current = {
615
636
  index: 1,
616
637
  name: formatSegmentName(1),
@@ -629,6 +650,30 @@ export class LedgerWriter {
629
650
  size: this._fs.statSync(last.path).size,
630
651
  count: scan.counts.get(last.index) ?? 0,
631
652
  };
653
+ this._reopenCurrent();
654
+ }
655
+
656
+ /** Re-open the current segment for append when the rollback left no usable fd. */
657
+ _reopenCurrent() {
658
+ if (this._current === null || this._current.fd !== null) return;
659
+ try {
660
+ this._current = {
661
+ ...this._current,
662
+ fd: this._fs.openSync(this._current.path, 'a'),
663
+ };
664
+ } catch {
665
+ // 段文件可能已被回滚删除;保持 fd=null,append 会按磁盘最大段号新建。
666
+ this._current = { ...this._current, fd: null };
667
+ }
668
+ }
669
+
670
+ /** Highest segment index that actually exists on disk (0 when the dir is empty). */
671
+ _lastSegmentIndexOnDisk() {
672
+ let max = 0;
673
+ for (const segment of this._listSegments()) {
674
+ if (segment.index > max) max = segment.index;
675
+ }
676
+ return max;
632
677
  }
633
678
 
634
679
  _listSegments() {
@@ -678,6 +723,7 @@ export class LedgerWriter {
678
723
  const segments = this._listSegments();
679
724
  const events = [];
680
725
  const counts = new Map();
726
+ const seenIds = new Set();
681
727
  let prevHash = GENESIS_HASH;
682
728
  let expectedSeq = 1;
683
729
  let repair = null;
@@ -745,6 +791,18 @@ export class LedgerWriter {
745
791
  ...result,
746
792
  });
747
793
  }
794
+ // 事件 id 是外部引用的唯一键:append 路径保证不重复,但双写者/外部
795
+ // 合并/手工修复都可能造出重复 id。载入时静默折叠会让引用产生歧义,
796
+ // 因此在这里按损坏账本处理(open 与 verify 都会报出来)。
797
+ if (seenIds.has(event.id)) {
798
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains a duplicate event id', {
799
+ reason: 'duplicate-id',
800
+ file: segment.name,
801
+ line: lineIndex + 1,
802
+ id: event.id,
803
+ });
804
+ }
805
+ seenIds.add(event.id);
748
806
  events.push(event);
749
807
  prevHash = event.hash;
750
808
  expectedSeq += 1;
@@ -782,6 +840,7 @@ export class LedgerWriter {
782
840
 
783
841
  _acquireLock(repairs) {
784
842
  const lockPath = path.join(this.dir, LOCK_FILE);
843
+ const takeoverPath = `${lockPath}.takeover`;
785
844
 
786
845
  for (let attempt = 0; attempt < 2; attempt += 1) {
787
846
  try {
@@ -807,8 +866,9 @@ export class LedgerWriter {
807
866
  }
808
867
 
809
868
  const existing = this._readLock(lockPath);
810
- const stale = this._isStaleLock(existing.data);
811
- if (!stale) {
869
+ // 锁在 fopen 与读取之间消失:没有锁可接管,直接重试创建。
870
+ if (existing.error === 'missing') continue;
871
+ if (!this._isStaleLock(existing.data, lockPath)) {
812
872
  throw new LedgerError('E_LOCKED', 'project ledger is locked by another writer', {
813
873
  pid: existing.data?.pid ?? null,
814
874
  host: existing.data?.host ?? null,
@@ -820,20 +880,48 @@ export class LedgerWriter {
820
880
  pid: existing.data?.pid ?? null,
821
881
  });
822
882
  }
883
+ // 单赢家接管:只有成功创建 takeover 标记的进程可以删除陈旧锁。
884
+ // 否则两个进程会各自"读到陈旧 → unlink → 新建",把对方的活锁删掉。
885
+ let marker;
886
+ try {
887
+ marker = this._fs.openSync(takeoverPath, 'wx');
888
+ } catch (markerError) {
889
+ throw new LedgerError('E_LOCKED', markerError.code === 'EEXIST'
890
+ ? 'another writer is taking over the ledger lock'
891
+ : `cannot create ledger takeover marker: ${markerError.message}`, {
892
+ pid: existing.data?.pid ?? null,
893
+ sysCode: markerError.code ?? null,
894
+ });
895
+ }
823
896
  try {
824
- this._fs.unlinkSync(lockPath);
825
- } catch (unlinkError) {
826
- throw new LedgerError('E_LOCKED', `cannot remove stale ledger lock: ${unlinkError.message}`);
897
+ this._fs.closeSync(marker);
898
+ // 标记生效后重新读取:原主可能已经写完(或已被别人接管成新锁)。
899
+ const fresh = this._readLock(lockPath);
900
+ if (fresh.error !== 'missing' && !this._isStaleLock(fresh.data, lockPath)) {
901
+ throw new LedgerError('E_LOCKED', 'ledger lock was refreshed by its owner during takeover', {
902
+ pid: fresh.data?.pid ?? null,
903
+ });
904
+ }
905
+ try {
906
+ this._fs.unlinkSync(lockPath);
907
+ } catch (unlinkError) {
908
+ if (unlinkError.code !== 'ENOENT') {
909
+ throw new LedgerError('E_LOCKED', `cannot remove stale ledger lock: ${unlinkError.message}`);
910
+ }
911
+ }
912
+ repairs.push({
913
+ kind: 'stale-lock',
914
+ pid: existing.data?.pid ?? null,
915
+ host: existing.data?.host ?? null,
916
+ startedAt: existing.data?.startedAt ?? null,
917
+ reason: existing.error ?? 'owner-not-running',
918
+ });
919
+ } finally {
920
+ try { this._fs.unlinkSync(takeoverPath); } catch { /* marker already gone */ }
827
921
  }
828
- repairs.push({
829
- kind: 'stale-lock',
830
- pid: existing.data?.pid ?? null,
831
- host: existing.data?.host ?? null,
832
- startedAt: existing.data?.startedAt ?? null,
833
- reason: existing.error ?? 'owner-not-running',
834
- });
835
922
  }
836
923
  }
924
+ throw new LedgerError('E_LOCKED', 'project ledger lock could not be acquired', {});
837
925
  }
838
926
 
839
927
  _readLock(lockPath) {
@@ -850,8 +938,21 @@ export class LedgerWriter {
850
938
  }
851
939
  }
852
940
 
853
- _isStaleLock(data) {
854
- if (!data || !Number.isSafeInteger(data.pid) || data.pid <= 0) return true;
941
+ /** Age of the on-disk lock record in ms; Infinity when it cannot be stat'd. */
942
+ _lockRecordAge(lockPath) {
943
+ try {
944
+ return this._clock() - this._fs.statSync(lockPath).mtimeMs;
945
+ } catch {
946
+ return Number.POSITIVE_INFINITY;
947
+ }
948
+ }
949
+
950
+ _isStaleLock(data, lockPath) {
951
+ if (!data || !Number.isSafeInteger(data.pid) || data.pid <= 0) {
952
+ // 锁创建与写入 payload 之间文件是 0 字节:无条件判陈旧会让并发进程
953
+ // 接管一个仍然活着的锁。给写入一个宽限期,超时后才认为是崩溃残留。
954
+ return this._lockRecordAge(lockPath) > LOCK_WRITE_GRACE_MS;
955
+ }
855
956
  // 不同主机共享目录:无法用本机 PID 判断,保守视为仍持有。
856
957
  if (typeof data.host === 'string' && data.host.length > 0 && data.host !== os.hostname()) {
857
958
  return false;
@@ -993,10 +1094,13 @@ export function openLedger(options = {}) {
993
1094
  return writer.head.seq;
994
1095
  },
995
1096
  async append(draft) {
1097
+ // 先齐平 events:checkpoint 齐平启动时 events 还是 null,若等 append 之后再
1098
+ // readAll,刚写入的事件会被读出来、再被 push 一次(重复)。
1099
+ const list = ensureEvents();
996
1100
  const event = await writer.append(draft);
997
1101
  // 只有 append 成功(含 fsync)后才推进内存状态。
998
1102
  Object.assign(state, applyEvent(state, event));
999
- ensureEvents().push(event);
1103
+ list.push(event);
1000
1104
  try {
1001
1105
  onEvent?.(event);
1002
1106
  } catch {
@@ -1012,9 +1116,9 @@ export function openLedger(options = {}) {
1012
1116
  return event;
1013
1117
  },
1014
1118
  async appendMany(drafts) {
1119
+ const list = ensureEvents();
1015
1120
  const appended = await writer.appendMany(drafts);
1016
1121
  let next = state;
1017
- const list = ensureEvents();
1018
1122
  for (const event of appended) {
1019
1123
  next = applyEvent(next, event);
1020
1124
  list.push(event);
@@ -50,6 +50,11 @@ export function classifyLlmFailure(error) {
50
50
  if (status === 401 || status === 403 || code.includes('INVALID_API_KEY') || code.includes('UNAUTHORIZED')) {
51
51
  return { ...base, category: FAILURE_CATEGORY.AUTH, retryable: false, humanRequired: true, action: 'stop' };
52
52
  }
53
+ // 429 必须先判:限流响应常带 "quota"/"insufficient" 字样,若先走 billing
54
+ // 分支就会被当成致命计费错误,永远不重试也不换路。
55
+ if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
56
+ return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
57
+ }
53
58
  if (
54
59
  status === 402 ||
55
60
  /insufficient|balance|quota|billing|payment|credit/.test(code) ||
@@ -57,9 +62,6 @@ export function classifyLlmFailure(error) {
57
62
  ) {
58
63
  return { ...base, category: FAILURE_CATEGORY.BILLING, retryable: false, humanRequired: true, action: 'stop' };
59
64
  }
60
- if (status === 429 || code.includes('RATE_LIMIT') || /rate limit/.test(text)) {
61
- return { ...base, category: FAILURE_CATEGORY.RATE_LIMIT, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
62
- }
63
65
  if (status !== null && status >= 500) {
64
66
  return { ...base, category: FAILURE_CATEGORY.SERVER, retryable: true, humanRequired: false, action: 'retry_or_fallback' };
65
67
  }
@@ -93,7 +95,13 @@ export function retryDecision(failure, config = {}, attempt = 1) {
93
95
  const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
94
96
  ? Math.max(1, Math.min(config.retry.maxAttempts, 5))
95
97
  : 3;
96
- if (!failure?.retryable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable` };
98
+ // 换路(fallback)能否执行取决于“路由可变”,与“同路由立刻重试”不同:
99
+ // model_unavailable / context_overflow 明确声明了 fallback 语义且 retryable=false,
100
+ // 若这里按 retryable 一刀切返回 fail,它们的 fallback 声明就永远不可达。
101
+ const fallbackCapable = failure?.retryable === true
102
+ || failure?.action === 'fallback'
103
+ || failure?.action === 'compact_or_fallback';
104
+ if (!fallbackCapable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} has no recoverable action` };
97
105
  const nextFallbackIndex = attempt - 1;
98
106
  const fallback = fallbackAt(config, nextFallbackIndex);
99
107
  if (fallback !== null) {
@@ -112,6 +120,9 @@ export function retryDecision(failure, config = {}, attempt = 1) {
112
120
  reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
113
121
  };
114
122
  }
123
+ if (failure?.retryable !== true) {
124
+ return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable and has no fallback route` };
125
+ }
115
126
  if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
116
127
  // No fallback route configured: a rate limit would hit again at once
117
128
  // without a backoff clock — end the turn and let the next event/startup
@@ -3,11 +3,20 @@
3
3
  *
4
4
  * Preference order:
5
5
  * 1. an existing live root Agent (the Human's current session);
6
- * 2. a lazily created, archived Team Host Agent (the Human owner has no
6
+ * 2. a lazily created Team Host Agent (the Human owner has no
7
7
  * session, e.g. the workbench was opened without a chat).
8
8
  *
9
9
  * The Host Agent is a runtime root, not a product member: it owns no Task,
10
- * has no product decision power, and is archived from the session list.
10
+ * has no product decision power.
11
+ *
12
+ * IMPORTANT — the Host Agent must never be archived. Members are subagent
13
+ * descendants of it, and `archived-session-gate` (dsh-api-session-controller)
14
+ * rejects every `agent/pre-step` whose Session, or any Session above it in the
15
+ * subagent lineage, is archived. The loop then ends the turn as
16
+ * `{kind:'blocked'}` **without issuing a model request**, so archiving the host
17
+ * silently disables the whole team (observed: 453 blocked turns, 0 completed).
18
+ * Earlier revisions archived it to hide it from the session list; that is
19
+ * repaired here by unarchiving on resolve.
11
20
  */
12
21
  import { randomUUID } from 'node:crypto';
13
22
 
@@ -35,6 +44,21 @@ export async function ensureHostAgent(options) {
35
44
  if (agents === undefined || typeof agents.create !== 'function') {
36
45
  throw new HostAgentError('E_RUNTIME_UNAVAILABLE', 'agents service is unavailable');
37
46
  }
47
+ // Repair a Host Agent archived by an earlier revision: the archive gate
48
+ // covers the host's whole subagent lineage, so every member turn would end
49
+ // blocked before any model request. `unarchiveSession` resolves without
50
+ // writing when the id is not archived, so no read-back is needed — and
51
+ // gating on the undocumented `archivedSessionIds` accessor is what silently
52
+ // skipped this repair before.
53
+ const unarchiveHost = async (sessionId) => {
54
+ const registry = options.workspaceRegistry;
55
+ if (typeof registry?.unarchiveSession !== 'function') return;
56
+ try {
57
+ await registry.unarchiveSession(sessionId);
58
+ } catch (error) {
59
+ console.warn('[ai-team] could not unarchive Team Host session:', error?.message ?? error);
60
+ }
61
+ };
38
62
  // Persist the resolved route into the session log. Live AgentOptions die
39
63
  // with the process; without a recorded selection a restored session renders
40
64
  // prompts with an unresolvable {{model}} variable.
@@ -51,13 +75,14 @@ export async function ensureHostAgent(options) {
51
75
  if (typeof options.resumeSessionId === 'string' && options.resumeSessionId !== '') {
52
76
  const live = typeof agents.get === 'function' ? agents.get(options.resumeSessionId) : undefined;
53
77
  if (live !== undefined) {
78
+ await unarchiveHost(options.resumeSessionId);
54
79
  const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
55
80
  persistSelection(options.resumeSessionId, selection);
56
81
  return { agent: live, created: false, resumed: true, sessionId: options.resumeSessionId, dispose: async () => {} };
57
82
  }
58
83
  try {
59
84
  const handle = await agents.resume({ resumeSessionId: options.resumeSessionId });
60
- try { await options.workspaceRegistry?.archiveSession?.(options.resumeSessionId); } catch { /* cosmetic */ }
85
+ await unarchiveHost(options.resumeSessionId);
61
86
  const selection = typeof options.agentDefaultModel?.currentSelection === 'function' ? options.agentDefaultModel.currentSelection() : null;
62
87
  persistSelection(options.resumeSessionId, selection);
63
88
  return {
@@ -77,7 +102,15 @@ export async function ensureHostAgent(options) {
77
102
  }
78
103
  const roots = typeof agents.roots === 'function' ? agents.roots() : [];
79
104
  if (roots.length > 0) {
80
- return { agent: roots[0], created: false, sessionId: roots[0].id, dispose: async () => {} };
105
+ // roots() 只保证注册顺序,不保证某个元素是「Human 的根会话」;优先挑一个
106
+ // 真正没有父会话、且不是 subagent 出来的根,避免把成员自己的父链当成
107
+ // Human 通道(那会让成员成为彼此的 parent)。
108
+ const rootAgent = roots.find((candidate) => {
109
+ const header = candidate?.session?.header;
110
+ if (header === undefined) return true;
111
+ return header.origin !== 'subagent' && header.parentSession === undefined;
112
+ }) ?? roots[0];
113
+ return { agent: rootAgent, created: false, sessionId: rootAgent.id, dispose: async () => {} };
81
114
  }
82
115
 
83
116
  const selection = typeof options.agentDefaultModel?.currentSelection === 'function'
@@ -103,12 +136,7 @@ export async function ensureHostAgent(options) {
103
136
  }
104
137
  persistSelection(sessionId, selection);
105
138
  const host = handle.agent;
106
- try {
107
- await options.workspaceRegistry?.archiveSession?.(sessionId);
108
- } catch (error) {
109
- // Hiding the host session is cosmetic; activation still works.
110
- console.warn('[ai-team] could not archive Team Host session:', error?.message ?? error);
111
- }
139
+ await unarchiveHost(sessionId);
112
140
  return {
113
141
  agent: host,
114
142
  created: true,
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Repair Team Host sessions archived by earlier revisions.
3
+ *
4
+ * Members are subagent descendants of the Host Agent, and
5
+ * `archived-session-gate` (dsh-api-session-controller) rejects every
6
+ * `agent/pre-step` whose Session — or any Session above it in the subagent
7
+ * lineage — is archived. The loop then ends the turn as `{kind:'blocked'}`
8
+ * **without issuing a model request**, so an archived Host silently disables
9
+ * the whole team (measured: 453 blocked turns, 0 completed, no `request/header`).
10
+ *
11
+ * Earlier revisions archived the Host on purpose to hide it from the session
12
+ * list. This sweep lifts that damage by calling `unarchiveSession` for the
13
+ * persisted host of each runtime and the `parentSession` of every member session.
14
+ *
15
+ * Two constraints learned the hard way:
16
+ * 1. Use only the **documented** API. `archivedSessionIds` is not part of the
17
+ * workspaceRegistry contract; gating on it silently skipped the whole
18
+ * repair. `unarchiveSession` on a non-archived id resolves without writing,
19
+ * so calling it unconditionally is safe and needs no read-back.
20
+ * 2. Diagnostics ending without `.fail` are dropped at the default `errors`
21
+ * diag level. Failure rows therefore carry `.fail`; success is proven by
22
+ * the durable archive list, not by a log line.
23
+ */
24
+
25
+ /**
26
+ * @param {{
27
+ * runtimes: Iterable<any>,
28
+ * sessions?: { get?: (id: string) => any },
29
+ * workspaceRegistry?: { unarchiveSession?: (id: string) => Promise<void> },
30
+ * diag?: { append?: (row: any) => any } | null,
31
+ * knownHostSessionIds?: Iterable<string>
32
+ * }} options
33
+ * @returns {Promise<string[]|null>} session ids the sweep asked to unarchive;
34
+ * `null` means the registry was not ready yet and the caller should retry.
35
+ */
36
+ export async function repairArchivedHosts(options = {}) {
37
+ const registry = options.workspaceRegistry;
38
+ // `workspaceRegistry` 要等 sessionPersistence 与历史 bootstrap 完成才 active,
39
+ // 插件激活瞬间常常还取不到。此时返回 null(而不是空数组)让调用方保持
40
+ // 「未修复」状态,等下一个 tick 重试——而不是一次失败就永久放弃。
41
+ if (registry === undefined || registry === null || typeof registry.unarchiveSession !== 'function') return null;
42
+
43
+ const victims = new Set();
44
+ for (const known of options.knownHostSessionIds ?? []) {
45
+ if (typeof known === 'string' && known !== '') victims.add(known);
46
+ }
47
+ for (const runtime of options.runtimes ?? []) {
48
+ const hostId = runtime?.service?.state?.hostSessionId;
49
+ if (typeof hostId === 'string' && hostId !== '') victims.add(hostId);
50
+ for (const member of Object.values(runtime?.service?.state?.members ?? {})) {
51
+ const sessionId = member?.sessionId;
52
+ if (typeof sessionId !== 'string' || sessionId === '') continue;
53
+ try {
54
+ const header = options.sessions?.get?.(sessionId)?.header;
55
+ if (typeof header?.parentSession === 'string') victims.add(header.parentSession);
56
+ } catch { /* member session is not live; skip */ }
57
+ }
58
+ }
59
+
60
+ const repaired = [];
61
+ for (const sessionId of victims) {
62
+ try {
63
+ await registry.unarchiveSession(sessionId);
64
+ repaired.push(sessionId);
65
+ } catch (error) {
66
+ options.diag?.append?.({ ev: 'host.unarchive.fail', sessionId, message: error?.message ?? String(error) });
67
+ }
68
+ }
69
+ return repaired;
70
+ }
@@ -256,19 +256,26 @@ export class MemberRuntime {
256
256
  return { messageId: message.id, sessionId: member.sessionId, direct: true };
257
257
  }
258
258
  let session = this.sessions?.get?.(member.sessionId);
259
- // An idle child may be cold. Resume it explicitly under the live parent
260
- // before delivery: sendMessage's cold path does not always start a turn
261
- // for a spawned subagent. Then the normal permission check applies.
262
- if ((session === undefined || session === null) && this.agents?.resume !== undefined) {
263
- try {
264
- const handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
265
- this.trackHandle?.(member.sessionId, handle);
266
- session = this.sessions?.get?.(member.sessionId);
267
- } catch { /* fall through to sendMessage cold path */ }
268
- }
269
- // If resume still could not produce a live Session, sendMessage is the
270
- // only available path; its permission preset is already in the session log.
259
+ // 冷会话:只走**一条**恢复路径。先 agents.resume 再 sendMessage 会让
260
+ // subagent manager 再做一次冷恢复并以 NOT_RESUMABLE 失败(它的 continuable
261
+ // 句柄已被前一次 resume 消耗),进而触发上层强制重建、丢成员历史。
271
262
  if (session === undefined || session === null) {
263
+ if (this.agents?.resume !== undefined) {
264
+ let handle = null;
265
+ try {
266
+ handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
267
+ } catch { handle = null; }
268
+ if (handle?.agent !== undefined && handle?.agent !== null && typeof handle.agent.followup === 'function') {
269
+ this.trackHandle?.(member.sessionId, handle);
270
+ await this.ensurePermission(member.sessionId);
271
+ const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
272
+ handle.agent.followup(message);
273
+ const live = this.sessions?.get?.(member.sessionId);
274
+ if (live !== undefined && live !== null && typeof this.sessions.flush === 'function') await this.sessions.flush(live);
275
+ return { messageId: message.id, sessionId: member.sessionId, cold: true, resumed: true };
276
+ }
277
+ }
278
+ // resume 不可用:只剩 subagent manager 的冷投递(其权限预设已在会话日志里)。
272
279
  const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
273
280
  signal: options.signal ?? new AbortController().signal,
274
281
  });
@@ -18,7 +18,10 @@ export async function formatSkillCatalog(skills, options = {}) {
18
18
  ...(options.cwd ? { cwd: options.cwd } : {}),
19
19
  }).catch(() => []);
20
20
  if (!Array.isArray(summaries) || summaries.length === 0) return '';
21
- const available = summaries.filter((skill) => !isSkillExcluded(skill?.name));
21
+ // 只注入「模型可以自己调用」的技能:`disable-model-invocation: true` 的技能
22
+ // 是给 Human 显式用的,列进成员 prompt 会把成员引向一个它无权调用的入口。
23
+ const available = summaries.filter((skill) =>
24
+ !isSkillExcluded(skill?.name) && skill?.modelInvocable !== false && skill?.disableModelInvocation !== true);
22
25
  if (available.length === 0) return '';
23
26
  const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 12;
24
27
  const rows = available.slice(0, limit).map((skill) => {
@@ -87,7 +87,10 @@ function scanCandidate(file, fallbackName, source) {
87
87
  }
88
88
  const fields = parseFrontmatter(text);
89
89
  const name = unquote(fields.name) || fallbackName;
90
- if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) return null;
90
+ // Must match the host registry's SKILL_NAME exactly (`^[a-z0-9]+(?:-[a-z0-9]+)*$`):
91
+ // a name we accept but the registry rejects makes `skills.snapshot` throw
92
+ // "skill provider returned invalid skill name", which aborts every agent step.
93
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return null;
91
94
  if (isSkillExcluded(name)) return null;
92
95
  const description = unquote(fields.description);
93
96
  // Official semantics: `description` is required; a skill without one is
@@ -173,8 +176,14 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
173
176
  async get(candidate) {
174
177
  const file = candidate?.locator;
175
178
  if (typeof file !== 'string' || !existsSync(file)) return undefined;
176
- if (statSync(file).size > MAX_BODY_BYTES) return undefined;
177
- return { ...candidate, content: readFileSync(file, 'utf8') };
179
+ // 读取失败不能把 rejection 冒到 skill 工具:宿主在 agent/pre-step 里
180
+ // await skills.snapshot,一次 EACCES/EBUSY 会打断该 agent 的整个回合。
181
+ try {
182
+ if (statSync(file).size > MAX_BODY_BYTES) return undefined;
183
+ return { ...candidate, content: readFileSync(file, 'utf8') };
184
+ } catch {
185
+ return undefined;
186
+ }
178
187
  },
179
188
  };
180
189
  }
@@ -182,5 +191,17 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
182
191
  export function installFileSkillProvider(skills, options) {
183
192
  if (!skills || typeof skills.registerProvider !== 'function') return () => {};
184
193
  const provider = createFileSkillProvider(options);
185
- return skills.registerProvider(() => provider);
194
+ const control = skills.registerProvider(() => provider);
195
+ // registerProvider 可能返回 disposer,也可能返回 { dispose, invalidate } 的
196
+ // control:直接把它当函数调用会在 teardown 里抛错(provider 泄漏),且从不
197
+ // invalidate 会让技能目录一直停在注册时的快照。
198
+ if (typeof control === 'function') {
199
+ return () => {
200
+ try { control(); } catch { /* already disposed */ }
201
+ };
202
+ }
203
+ return () => {
204
+ try { control?.invalidate?.(); } catch { /* cache may be gone */ }
205
+ try { control?.dispose?.(); } catch { /* already disposed */ }
206
+ };
186
207
  }
@@ -41,7 +41,7 @@ export function createAdoptGate(deps) {
41
41
  if (typeof hasKeepRecord === 'function') {
42
42
  let verified = false;
43
43
  try {
44
- verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null });
44
+ verified = await hasKeepRecord({ projectDir, skillPath: pair.skillPath ?? null, candidate: pair.after });
45
45
  } catch (error) {
46
46
  const message = `adopt gate: cannot read judge records (${error?.message ?? error})`;
47
47
  diag?.(message, { ev: 'skillopt.adoptgate.fail', project: projectDir });
@@ -9,6 +9,7 @@ import { extractAssistantText } from './subagent-text.js';
9
9
  import { isChildSettled, planJobStep, readJob, writeJob, listJobs } from './jobs.js';
10
10
  import { decideByMajority, normalizeVoteCount, parseJudgeOutput, buildPairPrompt, voteFromParsed } from './judge.js';
11
11
  import { validateCandidate } from './optimizer.js';
12
+ import { sha12 } from './proposal-store.js';
12
13
 
13
14
  /** 观测一个在飞子代理:状态 + 会话事件(同步,供状态机使用)。 */
14
15
  export function observeChild(ctx, childId, outputStart) {
@@ -82,6 +83,9 @@ export async function stepJob(input) {
82
83
  break;
83
84
  }
84
85
  job = { ...job, before, candidate: action.payload.text, backup: await deps.vcs.backup(job.skillPath, before) };
86
+ // 先落盘再改 live:中途崩溃时 job 里已有 before/backup,可据此回滚;
87
+ // 反过来(先改 live)会让磁盘上的技能停在未审候选且无任何记录。
88
+ writeJob(projectDir, job);
85
89
  deps.writeText(job.skillPath, action.payload.text);
86
90
  } else if (action.type === 'start-judges') {
87
91
  const votes = normalizeVoteCount(deps.votes ?? 3);
@@ -131,6 +135,7 @@ export async function stepJob(input) {
131
135
  job.dimension ?? '-',
132
136
  `${decision.better}-${decision.worse} ${decision.verdict}`,
133
137
  'paired',
138
+ sha12(job.candidate),
134
139
  ].join('\t'));
135
140
  deps.diag?.({ ev: 'skillopt.job.done', jobId: job.id, verdict: decision.verdict, better: decision.better, worse: decision.worse, kept });
136
141
  }
@@ -41,7 +41,10 @@ export function listJobs(projectDir) {
41
41
  if (!name.endsWith('.json')) continue;
42
42
  try {
43
43
  jobs.push(JSON.parse(readFileSync(join(dir, name), 'utf8')));
44
- } catch { /* skip corrupt */ }
44
+ } catch (error) {
45
+ // 静默跳过会让「job 幽灵消失」无从排查:坏文件保留在盘上并留一行警告。
46
+ console.warn(`[skillopt] skipping unreadable job file ${name}: ${error?.message ?? error}`);
47
+ }
45
48
  }
46
49
  return jobs.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0));
47
50
  }