@suifei/dsh-ai-team 0.3.53 → 0.3.56

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/lib/host/views.js CHANGED
@@ -6,21 +6,15 @@
6
6
  */
7
7
 
8
8
  import { isInformationalThreadMention } from '../domain/inbox.js';
9
-
10
- const ACTIVE_MEMBER_STATUSES = new Set(['provisioning', 'running', 'idle']);
9
+ import { isReviewCandidate } from '../domain/policy.js';
10
+ import { isTaskBlocked } from '../ledger/fold.js';
11
11
 
12
12
  function nameOf(state, memberId) {
13
13
  if (memberId === null || memberId === undefined) return null;
14
14
  return state.members?.[memberId]?.name ?? memberId;
15
15
  }
16
16
 
17
- function isBlocked(state, task) {
18
- if (!Array.isArray(task.blockedBy) || task.blockedBy.length === 0) return false;
19
- return task.blockedBy.some((id) => {
20
- const dependency = state.tasks?.[id];
21
- return dependency === undefined || dependency.status !== 'done' || dependency.tombstone === true;
22
- });
23
- }
17
+ const isBlocked = (state, task) => isTaskBlocked(state, task);
24
18
 
25
19
  function threadReplies(state, taskId) {
26
20
  return state.threads?.[taskId]?.headSeq ?? 0;
@@ -34,7 +28,9 @@ export function taskCard(state, task) {
34
28
  title: task.title ?? '',
35
29
  status: task.status,
36
30
  owner: nameOf(state, task.ownerId ?? task.accountableOwnerId),
31
+ ownerId: task.ownerId ?? task.accountableOwnerId ?? null,
37
32
  assignee: nameOf(state, task.assigneeId),
33
+ assigneeId: task.assigneeId ?? null,
38
34
  replies: threadReplies(state, task.id),
39
35
  following: (state.followers?.[task.id] ?? []).length > 0,
40
36
  blockedBy: Array.isArray(task.blockedBy) ? [...task.blockedBy] : [],
@@ -50,13 +46,7 @@ export function taskCard(state, task) {
50
46
 
51
47
  /** Agent members that may still be asked to review (not retired/failed). */
52
48
  function eligibleAgents(state, task) {
53
- const claimed = new Set(Array.isArray(task.claimHistory) ? task.claimHistory : []);
54
- return Object.values(state.members ?? {}).filter((member) => {
55
- if (member.kind === 'human') return false;
56
- if (!ACTIVE_MEMBER_STATUSES.has(member.status)) return false;
57
- if (member.id === task.assigneeId) return false;
58
- return !claimed.has(member.id);
59
- });
49
+ return Object.values(state.members ?? {}).filter((member) => isReviewCandidate(member, task));
60
50
  }
61
51
 
62
52
  function doneAt(task) {
package/lib/host/waker.js CHANGED
@@ -74,6 +74,9 @@ function promptFor(reason, state, taskId) {
74
74
  if (reason === 'pmo_stall') {
75
75
  return `PMO 巡检:${title} 已长时间没有新进展。读 Thread 当前状态,继续推进或明确报告卡点;不要静默等待,也不要重复已完成的证据。`;
76
76
  }
77
+ if (reason === 'pmo_meeting') {
78
+ return 'PMO 会议进行中,你是正式参会成员。读取已完成 Task、Thread 与项目目标,从你的专业视角(UX/业务/执行/验收/编程)在 Thread 发表意见并 @owner;指出被忽略的用户体验、运营需求或风险,不重复他人结论,不自行开卡,不等待 Human。';
79
+ }
77
80
  if (reason === 'pmo_continue') {
78
81
  return 'PMO 自动推进:当前没有 active Task。先开一次复盘/头脑风暴/深度研究会议(读取已完成 Task、Thread 与核心 skill;在 Thread/@ 相关成员形成意见),据此自己产出验收标准与下一批 Task;resultDefinition 必须可验证,qaRequired 必须有 qaChecklist。不要等待 Human、不要只汇报、不要重复已完成卡。Human 只观测,所有需要决策的问题交 PMO 自动决策。';
79
82
  }
@@ -221,7 +224,17 @@ export function planWakes(state, result, actor = {}) {
221
224
  if (event?.type === 'pmo/continue') {
222
225
  const project = Object.values(state.projects ?? {})[0];
223
226
  const bucket = event.payload?.bucket ?? Math.floor(Date.now() / 600_000);
224
- add(project?.ownerMemberId, null, 'pmo_continue', `pmo:${project?.id ?? 'project'}:${bucket}`);
227
+ const ownerId = project?.ownerMemberId;
228
+ // PMO meetings include every agent member; the owner leads, everyone
229
+ // else contributes from their own professional seat.
230
+ for (const member of Object.values(state.members ?? {})) {
231
+ if (member.kind !== 'agent' || member.status === 'retired') continue;
232
+ if (member.id === ownerId) {
233
+ add(member.id, null, 'pmo_continue', `pmo:${project?.id ?? 'project'}:${bucket}`);
234
+ } else {
235
+ add(member.id, null, 'pmo_meeting', `pmo_meeting:${project?.id ?? 'project'}:${member.id}:${bucket}`);
236
+ }
237
+ }
225
238
  }
226
239
  if (event?.type === 'inbox/item-created') {
227
240
  add(event.payload?.item?.memberId, event.payload?.item?.ref?.taskId ?? null, 'inbox', `inbox:${event.payload?.item?.id ?? event.seq}`);
@@ -31,9 +31,18 @@
31
31
  */
32
32
 
33
33
  import { GENESIS_HASH, isPlainObject } from './events.js';
34
+ import { isReviewCandidate } from '../domain/policy.js';
34
35
 
35
36
  /** 投影状态版本;改动折叠语义时必须递增(03 §6.4)。 */
36
- export const FOLD_STATE_VERSION = 1;
37
+ export const FOLD_STATE_VERSION = 2;
38
+
39
+ /**
40
+ * 投影封顶:大规模/长迭代账本下,stream 与每个 Thread 的 entries 不随事件数
41
+ * 无界增长(它们只是展示投影,完整历史在账本事件里,可按需重放)。
42
+ * headSeq/seq 单调计数不受影响,回复基线与去重仍然成立。
43
+ */
44
+ export const STREAM_TAIL_LIMIT = 500;
45
+ export const THREAD_ENTRIES_LIMIT = 500;
37
46
 
38
47
  export const TASK_STATUS = Object.freeze({
39
48
  PENDING: 'pending',
@@ -84,6 +93,7 @@ function emptyState() {
84
93
  threads: {},
85
94
  inbox: {},
86
95
  stream: [],
96
+ streamTotal: 0,
87
97
  followers: {},
88
98
  humanMemberId: null,
89
99
  };
@@ -527,7 +537,13 @@ function applyThreadPosted(state, event, payload) {
527
537
  eventId: event.id,
528
538
  };
529
539
 
530
- const entries = [...previous.entries, entry].sort((left, right) => left.seq - right.seq);
540
+ // Thread 条目 seq 单调递增(dedupe 已挡同 seq),直接追加;仅手工乱序回放
541
+ // 才回退到插入排序。entries 按 THREAD_ENTRIES_LIMIT 封顶,headSeq 仍单调。
542
+ const lastEntry = previous.entries[previous.entries.length - 1];
543
+ let entries = lastEntry !== undefined && lastEntry.seq > entrySeq
544
+ ? [...previous.entries, entry].sort((left, right) => left.seq - right.seq)
545
+ : [...previous.entries, entry];
546
+ if (entries.length > THREAD_ENTRIES_LIMIT) entries = entries.slice(entries.length - THREAD_ENTRIES_LIMIT);
531
547
  const headEntry = entries[entries.length - 1];
532
548
  const headSeq = Math.max(previous.headSeq, entrySeq, headEntry.seq);
533
549
  const thread = {
@@ -604,8 +620,16 @@ function applyStreamPosted(state, event, payload) {
604
620
  parentEventId: stringOrNull(payload.parentEventId),
605
621
  at: event.at,
606
622
  };
607
- const stream = [...state.stream, entry].sort((left, right) => left.seq - right.seq);
608
- return advance(state, event, { stream });
623
+ // 事件按 seq 递增到达(applyEvent 已挡住 seq <= lastSeq),直接追加即可;
624
+ // 只有手工构造的乱序回放才需要插入排序,用末尾比较识别。投影按
625
+ // STREAM_TAIL_LIMIT 封顶:完整历史在账本里,可重放。
626
+ const last = state.stream[state.stream.length - 1];
627
+ let stream = last !== undefined && last.seq > event.seq
628
+ ? [...state.stream, entry].sort((left, right) => left.seq - right.seq)
629
+ : [...state.stream, entry];
630
+ const streamTotal = (state.streamTotal ?? 0) + 1;
631
+ if (stream.length > STREAM_TAIL_LIMIT) stream = stream.slice(stream.length - STREAM_TAIL_LIMIT);
632
+ return advance(state, event, { stream, streamTotal });
609
633
  }
610
634
 
611
635
  function applyFollow(state, event, payload, following) {
@@ -698,6 +722,8 @@ export function applyEvent(state, event) {
698
722
  const sessionId = textOr(payload.sessionId, null);
699
723
  const member = memberId === null ? undefined : state.members[memberId];
700
724
  if (member === undefined || sessionId === null) return advance(state, event);
725
+ // 投影防御:retired 成员不得被绑定事件复活,必须走 member.rejoin。
726
+ if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
701
727
  return advance(state, event, {
702
728
  members: {
703
729
  ...state.members,
@@ -802,6 +828,8 @@ export function applyEvent(state, event) {
802
828
  const memberId = textOr(payload.memberId, null);
803
829
  const member = memberId === null ? undefined : state.members[memberId];
804
830
  if (member === undefined) return advance(state, event);
831
+ // 投影防御:retired 成员的旧会话回报 completed 不算恢复。
832
+ if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
805
833
  return advance(state, event, {
806
834
  members: {
807
835
  ...state.members,
@@ -820,6 +848,8 @@ export function applyEvent(state, event) {
820
848
  const memberId = textOr(payload.memberId, null);
821
849
  const member = memberId === null ? undefined : state.members[memberId];
822
850
  if (member === undefined) return advance(state, event);
851
+ // 投影防御:重试退役成员必须走 member.rejoin(顺带清 talentPool)。
852
+ if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
823
853
  return advance(state, event, {
824
854
  members: {
825
855
  ...state.members,
@@ -998,17 +1028,15 @@ export function isTaskBlocked(state, taskOrId) {
998
1028
 
999
1029
  /**
1000
1030
  * 验收资格纯函数(02 INV-04 / Q-05):
1001
- * - Agent 必须未退役、不是当前 assignee、且从未 claim 过(历史谓词)。
1002
1031
  * - Human 是唯一例外,可验收自己执行的 Task;二次确认由命令层负责。
1032
+ * - Agent 的资格判定统一走 policy.isReviewCandidate(与 views/Waker 同一实现)。
1003
1033
  */
1004
1034
  export function isEligibleReviewer(state, taskId, memberId) {
1005
1035
  const task = state.tasks[taskId];
1006
1036
  const member = state.members[memberId];
1007
1037
  if (!task || task.tombstone || !member) return false;
1008
1038
  if (member.kind === 'human') return true;
1009
- if (member.status === MEMBER_STATUS.RETIRED) return false;
1010
- if (task.assigneeId === memberId) return false;
1011
- return !hasClaimed(task, memberId);
1039
+ return isReviewCandidate(member, task);
1012
1040
  }
1013
1041
 
1014
1042
  /** 状态里的 Task 是否处于已知状态值(供测试/诊断使用)。 */
@@ -29,7 +29,8 @@ import {
29
29
  verifyChain,
30
30
  verifyEvent,
31
31
  } from './events.js';
32
- import { applyEvent, fold, initialState } from './fold.js';
32
+ import { applyEvent, FOLD_STATE_VERSION, fold, initialState } from './fold.js';
33
+ import { loadCheckpoint, saveCheckpoint } from './checkpoint.js';
33
34
 
34
35
  export { LedgerError };
35
36
 
@@ -403,7 +404,10 @@ export class LedgerWriter {
403
404
  if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
404
405
 
405
406
  const plans = [];
406
- const seenIds = new Set(this._ids);
407
+ // 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
408
+ // append 全量拷贝已存事件集合带来的平方级开销。
409
+ const seenIds = new Set();
410
+ const hasId = (id) => seenIds.has(id) || this._ids.has(id);
407
411
  let seq = this._head.seq;
408
412
  let prevHash = this._head.hash;
409
413
 
@@ -431,7 +435,7 @@ export class LedgerWriter {
431
435
 
432
436
  const at = draft.at ?? this._clock();
433
437
  const id = draft.id ?? newEventId(at);
434
- if (seenIds.has(id)) {
438
+ if (hasId(id)) {
435
439
  throw new LedgerError('E_DUPLICATE_ID', 'event id already exists in this ledger', { id });
436
440
  }
437
441
  seenIds.add(id);
@@ -488,7 +492,13 @@ export class LedgerWriter {
488
492
  (segCount > 0 &&
489
493
  (segCount >= this.segmentEvents || segSize + plan.line.length > this.segmentBytes));
490
494
  if (needRoll) {
491
- if (segFd !== null) this._fs.closeSync(segFd);
495
+ if (segFd !== null) {
496
+ // 落盘后再关闭旧段:closeSync 不保证刷盘,若旧段尾部整行
497
+ // 只留在 OS 缓冲而崩溃丢失,新段首行的 prevHash/seq 将与
498
+ // 截断后的旧段尾对不上,哈希链断裂且无法修复。
499
+ if (this.fsync) this._fs.fsyncSync(segFd);
500
+ this._fs.closeSync(segFd);
501
+ }
492
502
  // 段号 = 上一个已存在段的编号 + 1;全新账本的第一段仍是 000001。
493
503
  const lastIndex =
494
504
  created.length > 0
@@ -884,15 +894,86 @@ export class LedgerWriter {
884
894
  export function openLedger(options = {}) {
885
895
  const writer = new LedgerWriter(options);
886
896
  const opened = writer.open();
887
- const events = writer.readAll({ repairTail: false });
888
- const state = fold(events);
897
+ // checkpoint 命中且账本与检查点齐平时,跳过全量 readAll(boot 的大头):
898
+ // state 直接取自检查点,events 惰性化(首次访问才读盘,append 只增新事件)。
899
+ // 尾部存在时才需要一次 readAll 来续放投影。
900
+ const checkpointOptions = options.checkpoint ?? null;
901
+ const checkpointDir = checkpointOptions?.dir ?? writer.dir;
902
+ const stateVersion = checkpointOptions?.stateVersion ?? FOLD_STATE_VERSION;
903
+ let state;
904
+ let recovery = null;
905
+ let events = null;
906
+ const ensureEvents = () => {
907
+ if (events === null) events = writer.readAll({ repairTail: false });
908
+ return events;
909
+ };
910
+ if (checkpointOptions) {
911
+ const loaded = loadCheckpoint(checkpointDir, {
912
+ stateVersion,
913
+ hashAt: (seq) => writer.hashAt(seq),
914
+ });
915
+ if (loaded.checkpoint && loaded.checkpoint.lastSeq === writer.head.seq) {
916
+ // 齐平:零尾放,账本事件列表不进内存。
917
+ state = loaded.checkpoint.state;
918
+ recovery = {
919
+ source: loaded.source,
920
+ fromSeq: loaded.checkpoint.lastSeq + 1,
921
+ tailReplayed: 0,
922
+ errors: loaded.errors,
923
+ };
924
+ } else {
925
+ const fromSeq = loaded.checkpoint ? loaded.checkpoint.lastSeq + 1 : 1;
926
+ state = loaded.checkpoint ? loaded.checkpoint.state : initialState();
927
+ const all = ensureEvents();
928
+ for (const event of all) {
929
+ if (event.seq >= fromSeq) Object.assign(state, applyEvent(state, event));
930
+ }
931
+ recovery = {
932
+ source: loaded.source ?? 'replay',
933
+ fromSeq,
934
+ tailReplayed: Math.max(0, writer.head.seq - fromSeq + 1),
935
+ errors: loaded.errors,
936
+ };
937
+ }
938
+ } else {
939
+ events = writer.readAll({ repairTail: false });
940
+ state = fold(events);
941
+ }
889
942
 
890
943
  let onEvent = typeof options.onEvent === 'function' ? options.onEvent : null;
944
+ // 检查点节奏:boot 后落一次地板,之后每 saveEvery 次追加落一次,close
945
+ // 前必落——崩溃窗口最多丢 saveEvery 个事件的投影进度(账本本体无损)。
946
+ const saveEvery = Number.isSafeInteger(checkpointOptions?.saveEvery)
947
+ ? Math.max(50, checkpointOptions.saveEvery)
948
+ : 500;
949
+ let eventsSinceCheckpoint = 0;
950
+ const saveCheckpointNow = () => {
951
+ if (!checkpointOptions) return null;
952
+ try {
953
+ return saveCheckpoint(
954
+ checkpointDir,
955
+ { stateVersion, lastSeq: writer.head.seq, lastHash: writer.head.hash, state },
956
+ { hashAt: (seq) => writer.hashAt(seq) },
957
+ );
958
+ } catch (error) {
959
+ // 检查点保存失败绝不影响追加,但必须可见:静默失败会让检查点
960
+ // 名存实亡(boot 退化为全量重放而无人知晓)。
961
+ console.warn(`[ai-team] ledger ${writer.projectId} checkpoint save failed:`, error?.message ?? error);
962
+ return { error: error.message ?? String(error) };
963
+ }
964
+ };
965
+ if (checkpointOptions) {
966
+ const saved = saveCheckpointNow();
967
+ recovery.saved = saved && !saved.error ? saved.path : (saved?.error ?? null);
968
+ }
891
969
  const ledger = {
892
970
  projectId: writer.projectId,
893
971
  writer,
894
972
  state,
895
- events,
973
+ /** 账本事件全列表(checkpoint 模式下惰性读盘,append 持续追加)。 */
974
+ get events() {
975
+ return ensureEvents();
976
+ },
896
977
  opened,
897
978
  get onEvent() {
898
979
  return onEvent;
@@ -910,20 +991,28 @@ export function openLedger(options = {}) {
910
991
  const event = await writer.append(draft);
911
992
  // 只有 append 成功(含 fsync)后才推进内存状态。
912
993
  Object.assign(state, applyEvent(state, event));
913
- events.push(event);
994
+ ensureEvents().push(event);
914
995
  try {
915
996
  onEvent?.(event);
916
997
  } catch {
917
998
  /* a projection listener must never break the append */
918
999
  }
1000
+ if (checkpointOptions) {
1001
+ eventsSinceCheckpoint += 1;
1002
+ if (eventsSinceCheckpoint >= saveEvery) {
1003
+ eventsSinceCheckpoint = 0;
1004
+ saveCheckpointNow();
1005
+ }
1006
+ }
919
1007
  return event;
920
1008
  },
921
1009
  async appendMany(drafts) {
922
1010
  const appended = await writer.appendMany(drafts);
923
1011
  let next = state;
1012
+ const list = ensureEvents();
924
1013
  for (const event of appended) {
925
1014
  next = applyEvent(next, event);
926
- events.push(event);
1015
+ list.push(event);
927
1016
  }
928
1017
  Object.assign(state, next);
929
1018
  for (const event of appended) {
@@ -933,8 +1022,19 @@ export function openLedger(options = {}) {
933
1022
  /* a projection listener must never break the append */
934
1023
  }
935
1024
  }
1025
+ if (checkpointOptions) {
1026
+ eventsSinceCheckpoint += appended.length;
1027
+ if (eventsSinceCheckpoint >= saveEvery) {
1028
+ eventsSinceCheckpoint = 0;
1029
+ saveCheckpointNow();
1030
+ }
1031
+ }
936
1032
  return appended;
937
1033
  },
1034
+ /** boot 时检查点恢复方式:'primary'/'backup'/'replay' 与尾放区间。 */
1035
+ get recovery() {
1036
+ return recovery;
1037
+ },
938
1038
  readAll(readOptions = {}) {
939
1039
  return writer.readAll(readOptions);
940
1040
  },
@@ -975,6 +1075,7 @@ export function openLedger(options = {}) {
975
1075
  return writer.repair();
976
1076
  },
977
1077
  close() {
1078
+ if (checkpointOptions) saveCheckpointNow();
978
1079
  writer.close();
979
1080
  },
980
1081
  };
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * LLM failure classification and the deterministic retry/fallback decision.
3
3
  *
4
- * The Host never sleeps or polls for a retry: a transient failure is attempted
5
- * on the next event/startup (or immediately when the caller already has a new
6
- * model configured). Auth/billing/policy failures are fail-closed and require
7
- * a Human or the Project owner to change the environment.
4
+ * The listener on `agent/request-error` owns the retry for transient
5
+ * server/network failures and re-dispatches the same request immediately
6
+ * (DSH's agent loop supports that via `{ kind: 'retry' }`). There are no
7
+ * timers: a fallback patch only rewrites the member's persisted config, so it
8
+ * takes effect on the next wake — the current turn ends (`fail`). Rate limits
9
+ * also end the turn: hammering the same route at once burns the retry budget
10
+ * without a backoff clock. Auth/billing/policy failures are fail-closed and
11
+ * require a Human or the Project owner to change the environment.
8
12
  */
9
13
 
10
14
  export const FAILURE_CATEGORY = Object.freeze({
@@ -80,8 +84,10 @@ function fallbackAt(config, index) {
80
84
  }
81
85
 
82
86
  /**
83
- * Decide what the Waker does next. No timers: `retry` means "re-wake on the
84
- * next event/startup"; `fallback` also carries the exact member config patch.
87
+ * Decide what the request-error listener does next. `retry` re-dispatches the
88
+ * same request immediately; `fallback` writes the config patch and ends the
89
+ * turn (it can only take effect on the next wake, because a step's route is
90
+ * captured before dispatch); `fail` ends the turn unchanged.
85
91
  */
86
92
  export function retryDecision(failure, config = {}, attempt = 1) {
87
93
  const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
@@ -105,7 +111,13 @@ export function retryDecision(failure, config = {}, attempt = 1) {
105
111
  reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
106
112
  };
107
113
  }
108
- return { action: 'retry', attempt, reason: 'same model, next event/startup' };
114
+ // No fallback route configured: a rate limit would hit again at once
115
+ // without a backoff clock — end the turn and let the next event/startup
116
+ // try fresh instead of burning the budget on a throttled route.
117
+ if (failure.category === FAILURE_CATEGORY.RATE_LIMIT) {
118
+ return { action: 'fail', attempt, reason: 'rate limited; left to the next wake' };
119
+ }
120
+ return { action: 'retry', attempt, reason: 'same route, immediate retry' };
109
121
  }
110
122
 
111
123
  export function describeFailure(failure) {
@@ -98,6 +98,9 @@ export class MemberRuntime {
98
98
  this.preset = options.preset ?? null;
99
99
  this.agentPresets = options.agentPresets ?? null;
100
100
  this.direct = options.direct === true;
101
+ // Cold resumes produce AgentHandles the caller does not store; the owner
102
+ // tracks them here so teardown can dispose every member activation.
103
+ this.trackHandle = typeof options.trackHandle === 'function' ? options.trackHandle : null;
101
104
  this.clock = options.clock ?? (() => Date.now());
102
105
  }
103
106
 
@@ -241,6 +244,7 @@ export class MemberRuntime {
241
244
  setup: async (agentCtx) => { await this.agentPresets.mount(agentCtx, preset); },
242
245
  } : {}),
243
246
  });
247
+ this.trackHandle?.(handle);
244
248
  agent = handle.agent;
245
249
  } catch (error) {
246
250
  fail('E_SESSION_MISSING', `member ${member.id} cannot be resumed: ${error?.message ?? error}`);
@@ -259,7 +263,8 @@ export class MemberRuntime {
259
263
  // for a spawned subagent. Then the normal permission check applies.
260
264
  if ((session === undefined || session === null) && this.agents?.resume !== undefined) {
261
265
  try {
262
- await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
266
+ const handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
267
+ this.trackHandle?.(handle);
263
268
  session = this.sessions?.get?.(member.sessionId);
264
269
  } catch { /* fall through to sendMessage cold path */ }
265
270
  }
@@ -3,6 +3,12 @@
3
3
  * marketplace's user-skill scanner. It exposes `<dshHome>/skills` and project
4
4
  * `.dsh/skills` / `.agents/skills` to the normal `skills` service, so members can
5
5
  * load installed skills through their own `skill` tool.
6
+ *
7
+ * Discovery parity with @deepseek-ai/dsh-skill-filesystem (README L36-56):
8
+ * directory bundles `<name>/SKILL.md` and flat `<name>.md` files, required
9
+ * kebab-case `name` + `description`, loose-boolean `disable-model-invocation`
10
+ * / `user-invocable` keys, and the official rank order (project-dsh 100,
11
+ * project-agents 200, user-dsh 400, bundled 600; lower rank wins a name).
6
12
  */
7
13
 
8
14
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
@@ -11,6 +17,14 @@ import { isSkillExcluded } from './skill-policy.js';
11
17
 
12
18
  const MAX_BODY_BYTES = 512 * 1024;
13
19
 
20
+ /** Official per-source ranks; a lower rank beats a higher one on name clash. */
21
+ const SOURCE_RANK = Object.freeze({
22
+ 'project-dsh': 100,
23
+ 'project-agents': 200,
24
+ 'user-dsh': 400,
25
+ bundled: 600,
26
+ });
27
+
14
28
  function parseFrontmatter(text) {
15
29
  if (!text.startsWith('---')) return {};
16
30
  const end = text.indexOf('\n---', 3);
@@ -39,6 +53,68 @@ function unquote(value) {
39
53
  : text;
40
54
  }
41
55
 
56
+ /**
57
+ * Official loose boolean syntax (skill-filesystem README L38): YAML booleans
58
+ * plus case-insensitive true/false, yes/no, on/off, 1/0. `null` marks a
59
+ * rejected spelling, which drops the whole skill instead of silently allowing
60
+ * an interface.
61
+ */
62
+ function parseLooseBoolean(value) {
63
+ if (typeof value === 'boolean') return value;
64
+ const text = String(value ?? '').trim().toLowerCase();
65
+ if (['true', 'yes', 'on', '1'].includes(text)) return true;
66
+ if (['false', 'no', 'off', '0'].includes(text)) return false;
67
+ return null;
68
+ }
69
+
70
+ /** Resolve one invocation flag; returns null when the skill must be dropped. */
71
+ function invocationFlag(fields, key, inverted) {
72
+ const raw = fields[key];
73
+ if (raw === undefined) return true;
74
+ const parsed = parseLooseBoolean(raw);
75
+ if (parsed === null) return null;
76
+ return inverted ? !parsed : parsed;
77
+ }
78
+
79
+ function scanCandidate(file, fallbackName, source) {
80
+ if (!existsSync(file)) return null;
81
+ let text;
82
+ try {
83
+ if (statSync(file).size > MAX_BODY_BYTES) return null;
84
+ text = readFileSync(file, 'utf8');
85
+ } catch {
86
+ return null;
87
+ }
88
+ const fields = parseFrontmatter(text);
89
+ const name = unquote(fields.name) || fallbackName;
90
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) return null;
91
+ if (isSkillExcluded(name)) return null;
92
+ const description = unquote(fields.description);
93
+ // Official semantics: `description` is required; a skill without one is
94
+ // dropped with a warning rather than synthesized into the catalog.
95
+ if (description === '') {
96
+ console.warn(`[ai-team] skill "${name}" dropped: frontmatter description is required`);
97
+ return null;
98
+ }
99
+ const modelInvocable = invocationFlag(fields, 'disable-model-invocation', true);
100
+ const userInvocable = invocationFlag(fields, 'user-invocable', false);
101
+ if (modelInvocable === null || userInvocable === null) {
102
+ console.warn(`[ai-team] skill "${name}" dropped: "${modelInvocable === null ? 'disable-model-invocation' : 'user-invocable'}" is not a recognized boolean`);
103
+ return null;
104
+ }
105
+ return {
106
+ name,
107
+ description,
108
+ whenToUse: unquote(fields.whenToUse) || unquote(fields['when-to-use']) || undefined,
109
+ invocation: { modelInvocable, userInvocable },
110
+ source,
111
+ provider: 'ai-team-files',
112
+ path: file,
113
+ locator: file,
114
+ rank: SOURCE_RANK[source] ?? 500,
115
+ };
116
+ }
117
+
42
118
  function scanRoot(root, source) {
43
119
  const candidates = [];
44
120
  if (!existsSync(root)) return candidates;
@@ -49,43 +125,30 @@ function scanRoot(root, source) {
49
125
  return candidates;
50
126
  }
51
127
  for (const entry of entries) {
52
- if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
53
- const file = join(root, entry.name, 'SKILL.md');
54
- if (!existsSync(file)) continue;
55
- let text;
56
- try {
57
- if (statSync(file).size > MAX_BODY_BYTES) continue;
58
- text = readFileSync(file, 'utf8');
59
- } catch {
128
+ if (entry.name.startsWith('.')) continue;
129
+ if (entry.isDirectory()) {
130
+ const found = scanCandidate(join(root, entry.name, 'SKILL.md'), entry.name, source);
131
+ if (found !== null) candidates.push(found);
60
132
  continue;
61
133
  }
62
- const fields = parseFrontmatter(text);
63
- const name = unquote(fields.name) || entry.name;
64
- if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) continue;
65
- if (isSkillExcluded(name)) continue;
66
- candidates.push({
67
- name,
68
- description: unquote(fields.description) || `Skill ${name}`,
69
- whenToUse: unquote(fields.whenToUse) || unquote(fields['when-to-use']) || undefined,
70
- invocation: { modelInvocable: true, userInvocable: true },
71
- source,
72
- provider: 'ai-team-files',
73
- path: file,
74
- locator: file,
75
- rank: 0,
76
- });
134
+ if (entry.isFile() && entry.name.endsWith('.md')) {
135
+ const found = scanCandidate(join(root, entry.name), entry.name.replace(/\.md$/, ''), source);
136
+ if (found !== null) candidates.push(found);
137
+ }
77
138
  }
78
139
  return candidates;
79
140
  }
80
141
 
81
142
  export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}) {
143
+ // Bundled last: the official rank order puts disk roots above the packaged
144
+ // copy, so a user's own edit of a same-named skill wins (README L48-56).
82
145
  const roots = [];
83
- if (bundledDir) roots.push([join(bundledDir, 'skills'), 'bundled']);
84
- if (dshHome) roots.push([join(dshHome, 'skills'), 'user-dsh']);
85
146
  if (projectCwd) {
86
147
  roots.push([join(projectCwd, '.dsh', 'skills'), 'project-dsh']);
87
148
  roots.push([join(projectCwd, '.agents', 'skills'), 'project-agents']);
88
149
  }
150
+ if (dshHome) roots.push([join(dshHome, 'skills'), 'user-dsh']);
151
+ if (bundledDir) roots.push([join(bundledDir, 'skills'), 'bundled']);
89
152
  return {
90
153
  name: 'ai-team-files',
91
154
  async list(options = {}) {
@@ -95,16 +158,17 @@ export function createFileSkillProvider({ dshHome, projectCwd, bundledDir } = {}
95
158
  [join(options.cwd, '.agents', 'skills'), 'project-agents'],
96
159
  ]
97
160
  : [];
98
- const seen = new Set();
99
161
  const all = [];
100
162
  for (const [root, source] of [...roots, ...extra]) {
101
- for (const candidate of scanRoot(root, source)) {
102
- if (seen.has(candidate.name)) continue;
103
- seen.add(candidate.name);
104
- all.push(candidate);
105
- }
163
+ all.push(...scanRoot(root, source));
106
164
  }
107
- return all.sort((left, right) => left.name.localeCompare(right.name));
165
+ // Same-name clash: the lowest rank wins, mirroring the registry's
166
+ // rank → provider-order → local-order adjudication.
167
+ const byName = new Map();
168
+ for (const candidate of all.sort((left, right) => left.rank - right.rank)) {
169
+ if (!byName.has(candidate.name)) byName.set(candidate.name, candidate);
170
+ }
171
+ return [...byName.values()].sort((left, right) => left.name.localeCompare(right.name));
108
172
  },
109
173
  async get(candidate) {
110
174
  const file = candidate?.locator;
@@ -120,4 +184,3 @@ export function installFileSkillProvider(skills, options) {
120
184
  const provider = createFileSkillProvider(options);
121
185
  return skills.registerProvider(() => provider);
122
186
  }
123
-