@yankeguo/dsh-devlead 0.1.0 → 0.2.0

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.
Files changed (3) hide show
  1. package/README.md +50 -0
  2. package/lib/index.js +1498 -315
  3. package/package.json +4 -3
package/lib/index.js CHANGED
@@ -6,8 +6,7 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // packages/devlead/src/index.ts
9
- import { mkdir, stat } from "node:fs/promises";
10
- import { isAbsolute } from "node:path";
9
+ import { mkdir } from "node:fs/promises";
11
10
  import { Service } from "@deepseek-ai/cordis";
12
11
  import z2 from "@deepseek-ai/schemastery";
13
12
  import { appendPluginRecord as appendPluginRecord2 } from "@deepseek-ai/dsh-session";
@@ -18,10 +17,12 @@ import { DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2 } from "@ya
18
17
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
19
18
  import {
20
19
  DEVLEAD_ERROR_EXCERPT_MAX,
20
+ DEVLEAD_MAX_INSTANT,
21
21
  DEVLEAD_MESSAGE_KIND,
22
22
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
23
23
  DEVLEAD_MODE_RECORD_TYPE,
24
24
  DEVLEAD_RECORD_VERSION,
25
+ DEVLEAD_RESET_RECORD_TYPE,
25
26
  DEVLEAD_WATCH_RECORD_TYPE,
26
27
  DEVLEAD_DEFAULT_MAX_WATCHED,
27
28
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
@@ -29,6 +30,36 @@ import {
29
30
  isDevLeadTransition,
30
31
  notificationId
31
32
  } from "@yankeguo/dsh-devlead-protocol";
33
+
34
+ // packages/devlead/src/error.ts
35
+ var DevLeadError = class extends Error {
36
+ /**
37
+ * @param message - human-readable failure text.
38
+ * @param code - stable code from {@link DevLeadErrorCode}.
39
+ */
40
+ constructor(message, code) {
41
+ super(message);
42
+ this.code = code;
43
+ this.name = "DevLeadError";
44
+ }
45
+ code;
46
+ };
47
+ function isDevLeadError(error51) {
48
+ if (error51 instanceof DevLeadError) return true;
49
+ if (!(error51 instanceof Error)) return false;
50
+ const candidate = error51;
51
+ return typeof candidate.code === "string" && candidate.code.startsWith("DEVLEAD_");
52
+ }
53
+ function thrownMessage(error51) {
54
+ if (error51 instanceof Error) return error51.message;
55
+ if (typeof error51 === "object" && error51 !== null && "message" in error51) {
56
+ const message = error51.message;
57
+ if (typeof message === "string") return message;
58
+ }
59
+ return String(error51);
60
+ }
61
+
62
+ // packages/devlead/src/domain.ts
32
63
  function createDevLeadPromptMessage(text, lead) {
33
64
  return createUserMessage({
34
65
  content: [{ type: "text", text }],
@@ -50,11 +81,15 @@ function watchRecord(sessions, at) {
50
81
  function notificationRecord(notification) {
51
82
  return { kind: "devlead/notification", version: DEVLEAD_RECORD_VERSION, notification };
52
83
  }
84
+ function resetRecord(at) {
85
+ return { kind: "devlead/reset", version: DEVLEAD_RECORD_VERSION, at };
86
+ }
53
87
  function devLeadNotification(sessionId, sessionTitle, transition, turn, at, error51, summary) {
88
+ const title = sessionTitle === void 0 ? void 0 : excerptLine(sessionTitle, DEVLEAD_ERROR_EXCERPT_MAX);
54
89
  return {
55
90
  id: notificationId(sessionId, turn, transition),
56
91
  sessionId,
57
- ...sessionTitle === void 0 ? {} : { sessionTitle },
92
+ ...title === void 0 ? {} : { sessionTitle: title },
58
93
  transition,
59
94
  turn,
60
95
  at,
@@ -62,12 +97,24 @@ function devLeadNotification(sessionId, sessionTitle, transition, turn, at, erro
62
97
  ...summary === void 0 ? {} : { summary }
63
98
  };
64
99
  }
100
+ function representableInstant(at, fallback) {
101
+ return Number.isSafeInteger(at) && at >= 0 && at <= DEVLEAD_MAX_INSTANT ? at : fallback;
102
+ }
65
103
  function expectRecord(value, type) {
66
104
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
67
105
  throw new Error(`record "${type}" payload is not a plain object`);
68
106
  }
69
107
  return value;
70
108
  }
109
+ function expectFields(value, label, required2, optional2 = []) {
110
+ const allowed = /* @__PURE__ */ new Set([...required2, ...optional2]);
111
+ for (const key of Object.keys(value)) {
112
+ if (!allowed.has(key)) throw new Error(`${label} carries unexpected field ${JSON.stringify(key)}`);
113
+ }
114
+ for (const key of required2) {
115
+ if (!(key in value)) throw new Error(`${label} is missing field ${JSON.stringify(key)}`);
116
+ }
117
+ }
71
118
  function expectEnvelope(value, type, kind) {
72
119
  if (value.kind !== kind) {
73
120
  throw new Error(`record "${type}" carries unexpected kind ${JSON.stringify(value.kind)}`);
@@ -76,99 +123,116 @@ function expectEnvelope(value, type, kind) {
76
123
  throw new Error(`record "${type}" carries unsupported version ${JSON.stringify(value.version)}`);
77
124
  }
78
125
  }
126
+ function decodeInstant(value, label) {
127
+ if (!Number.isSafeInteger(value) || value < 0 || value > DEVLEAD_MAX_INSTANT) {
128
+ throw new Error(`${label} must be a non-negative integer instant in epoch milliseconds`);
129
+ }
130
+ return value;
131
+ }
132
+ function decodeTurn(value, label) {
133
+ if (!Number.isSafeInteger(value) || value < 1) {
134
+ throw new Error(`${label} must be a positive safe integer`);
135
+ }
136
+ return value;
137
+ }
138
+ function decodeExcerpt(value, label) {
139
+ if (typeof value !== "string" || value.length === 0) {
140
+ throw new Error(`${label} must be a non-empty string when present`);
141
+ }
142
+ if (value.length > DEVLEAD_ERROR_EXCERPT_MAX * 2 || Array.from(value).length > DEVLEAD_ERROR_EXCERPT_MAX) {
143
+ throw new Error(`${label} must be at most ${DEVLEAD_ERROR_EXCERPT_MAX} code points`);
144
+ }
145
+ return value;
146
+ }
79
147
  function decodeModeRecord(value) {
80
148
  const record2 = expectRecord(value, DEVLEAD_MODE_RECORD_TYPE);
149
+ const label = "mode record";
150
+ expectFields(record2, label, ["kind", "version", "enabled", "at"]);
81
151
  expectEnvelope(record2, DEVLEAD_MODE_RECORD_TYPE, "devlead/mode");
82
- if (typeof record2.enabled !== "boolean") throw new Error("mode record enabled must be a boolean");
83
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
84
- throw new Error("mode record at must be a non-negative safe integer");
85
- }
86
- return { kind: "devlead/mode", version: DEVLEAD_RECORD_VERSION, enabled: record2.enabled, at: record2.at };
152
+ if (typeof record2.enabled !== "boolean") throw new Error(`${label} enabled must be a boolean`);
153
+ return {
154
+ kind: "devlead/mode",
155
+ version: DEVLEAD_RECORD_VERSION,
156
+ enabled: record2.enabled,
157
+ at: decodeInstant(record2.at, `${label} at`)
158
+ };
87
159
  }
88
160
  function decodeWatchRecord(value) {
89
161
  const record2 = expectRecord(value, DEVLEAD_WATCH_RECORD_TYPE);
162
+ const label = "watch record";
163
+ expectFields(record2, label, ["kind", "version", "sessions", "at"]);
90
164
  expectEnvelope(record2, DEVLEAD_WATCH_RECORD_TYPE, "devlead/watch");
91
165
  if (!Array.isArray(record2.sessions) || !record2.sessions.every((session) => typeof session === "string" && session.length > 0)) {
92
- throw new Error("watch record sessions must be a non-empty string array");
166
+ throw new Error(`${label} sessions must be a non-empty string array`);
93
167
  }
94
168
  if (new Set(record2.sessions).size !== record2.sessions.length) {
95
- throw new Error("watch record sessions must be unique");
96
- }
97
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
98
- throw new Error("watch record at must be a non-negative safe integer");
169
+ throw new Error(`${label} sessions must be unique`);
99
170
  }
100
171
  return {
101
172
  kind: "devlead/watch",
102
173
  version: DEVLEAD_RECORD_VERSION,
103
174
  sessions: [...record2.sessions],
104
- at: record2.at
175
+ at: decodeInstant(record2.at, `${label} at`)
105
176
  };
106
177
  }
107
178
  function decodeNotification(value) {
108
179
  const record2 = expectRecord(value, DEVLEAD_NOTIFICATION_RECORD_TYPE);
109
- if (typeof record2.id !== "string" || record2.id.length === 0) throw new Error("notification id must be a non-empty string");
110
- if (typeof record2.sessionId !== "string" || record2.sessionId.length === 0) {
111
- throw new Error("notification sessionId must be a non-empty string");
180
+ const label = "notification";
181
+ expectFields(record2, label, ["id", "sessionId", "transition", "turn", "at"], [
182
+ "sessionTitle",
183
+ "error",
184
+ "summary"
185
+ ]);
186
+ if (typeof record2.id !== "string" || record2.id.length === 0) {
187
+ throw new Error(`${label} id must be a non-empty string`);
112
188
  }
113
- if (record2.sessionTitle !== void 0 && (typeof record2.sessionTitle !== "string" || record2.sessionTitle.length === 0)) {
114
- throw new Error("notification sessionTitle must be a non-empty string when present");
189
+ if (typeof record2.sessionId !== "string" || record2.sessionId.length === 0) {
190
+ throw new Error(`${label} sessionId must be a non-empty string`);
115
191
  }
192
+ const sessionTitle = record2.sessionTitle === void 0 ? void 0 : decodeExcerpt(record2.sessionTitle, `${label} sessionTitle`);
116
193
  if (!isDevLeadTransition(record2.transition)) {
117
- throw new Error(`notification transition ${JSON.stringify(record2.transition)} is not recognized`);
194
+ throw new Error(`${label} transition ${JSON.stringify(record2.transition)} is not recognized`);
118
195
  }
119
- if (!Number.isSafeInteger(record2.turn) || record2.turn < 1) {
120
- throw new Error("notification turn must be a positive safe integer");
121
- }
122
- if (!Number.isSafeInteger(record2.at) || record2.at < 0) {
123
- throw new Error("notification at must be a non-negative safe integer");
124
- }
125
- if (record2.error !== void 0 && (typeof record2.error !== "string" || record2.error.length === 0)) {
126
- throw new Error("notification error must be a non-empty string when present");
127
- }
128
- if (record2.summary !== void 0 && (typeof record2.summary !== "string" || record2.summary.length === 0)) {
129
- throw new Error("notification summary must be a non-empty string when present");
130
- }
131
- const id = notificationId(record2.sessionId, record2.turn, record2.transition);
132
- if (record2.id !== id) throw new Error(`notification id must be ${id}`);
196
+ const turn = decodeTurn(record2.turn, `${label} turn`);
197
+ const error51 = record2.error === void 0 ? void 0 : decodeExcerpt(record2.error, `${label} error`);
198
+ const summary = record2.summary === void 0 ? void 0 : decodeExcerpt(record2.summary, `${label} summary`);
199
+ const id = notificationId(record2.sessionId, turn, record2.transition);
200
+ if (record2.id !== id) throw new Error(`${label} id must be ${id}`);
133
201
  return {
134
202
  id,
135
203
  sessionId: record2.sessionId,
136
- ...record2.sessionTitle === void 0 ? {} : { sessionTitle: record2.sessionTitle },
204
+ ...sessionTitle === void 0 ? {} : { sessionTitle },
137
205
  transition: record2.transition,
138
- turn: record2.turn,
139
- at: record2.at,
140
- ...record2.error === void 0 ? {} : { error: record2.error },
141
- ...record2.summary === void 0 ? {} : { summary: record2.summary }
206
+ turn,
207
+ at: decodeInstant(record2.at, `${label} at`),
208
+ ...error51 === void 0 ? {} : { error: error51 },
209
+ ...summary === void 0 ? {} : { summary }
142
210
  };
143
211
  }
144
212
  function decodeNotificationRecord(value) {
145
213
  const record2 = expectRecord(value, DEVLEAD_NOTIFICATION_RECORD_TYPE);
214
+ const label = "notification record";
215
+ expectFields(record2, label, ["kind", "version", "notification"]);
146
216
  expectEnvelope(record2, DEVLEAD_NOTIFICATION_RECORD_TYPE, "devlead/notification");
147
217
  return decodeNotification(record2.notification);
148
218
  }
219
+ function decodeResetRecord(value) {
220
+ const record2 = expectRecord(value, DEVLEAD_RESET_RECORD_TYPE);
221
+ const label = "reset record";
222
+ expectFields(record2, label, ["kind", "version", "at"]);
223
+ expectEnvelope(record2, DEVLEAD_RESET_RECORD_TYPE, "devlead/reset");
224
+ return {
225
+ kind: "devlead/reset",
226
+ version: DEVLEAD_RECORD_VERSION,
227
+ at: decodeInstant(record2.at, `${label} at`)
228
+ };
229
+ }
149
230
  function failureExcerpt(error51) {
150
- const message = error51 instanceof Error ? error51.message : typeof error51 === "object" && error51 !== null && "message" in error51 && typeof error51.message === "string" ? error51.message : String(error51);
151
- return excerptLine(message, DEVLEAD_ERROR_EXCERPT_MAX);
231
+ return excerptLine(thrownMessage(error51), DEVLEAD_ERROR_EXCERPT_MAX);
152
232
  }
153
-
154
- // packages/devlead/src/error.ts
155
- var DevLeadError = class extends Error {
156
- /**
157
- * @param message - human-readable failure text.
158
- * @param code - stable code from {@link DevLeadErrorCode}.
159
- */
160
- constructor(message, code) {
161
- super(message);
162
- this.code = code;
163
- this.name = "DevLeadError";
164
- }
165
- code;
166
- };
167
- function isDevLeadError(error51) {
168
- if (error51 instanceof DevLeadError) return true;
169
- if (!(error51 instanceof Error)) return false;
170
- const candidate = error51;
171
- return typeof candidate.code === "string" && candidate.code.startsWith("DEVLEAD_");
233
+ function assistantExcerpt(blocks) {
234
+ const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
235
+ return excerptLine(text, DEVLEAD_ERROR_EXCERPT_MAX);
172
236
  }
173
237
 
174
238
  // packages/devlead/src/fold.ts
@@ -14691,55 +14755,96 @@ config(en_default());
14691
14755
  // packages/devlead/src/fold.ts
14692
14756
  import {
14693
14757
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2,
14758
+ DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX2,
14759
+ DEVLEAD_MAX_INSTANT as DEVLEAD_MAX_INSTANT2,
14760
+ DEVLEAD_MODE_PROJECTION_KEY,
14694
14761
  DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE2,
14695
14762
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE2,
14696
14763
  DEVLEAD_PROJECTION_KEY,
14697
- DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE2
14764
+ DEVLEAD_RESET_RECORD_TYPE as DEVLEAD_RESET_RECORD_TYPE2,
14765
+ DEVLEAD_TRANSITIONS,
14766
+ DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE2,
14767
+ notificationId as notificationId2
14698
14768
  } from "@yankeguo/dsh-devlead-protocol";
14699
14769
  function emptyDevLeadProjectionState() {
14700
14770
  return { enabled: false, sessions: [], notifications: [], failure: null };
14701
14771
  }
14772
+ var excerptSchema = external_exports.string().min(1).refine(
14773
+ (value) => value.length <= DEVLEAD_ERROR_EXCERPT_MAX2 * 2 && Array.from(value).length <= DEVLEAD_ERROR_EXCERPT_MAX2,
14774
+ { message: `excerpt must be at most ${DEVLEAD_ERROR_EXCERPT_MAX2} code points` }
14775
+ );
14702
14776
  var notificationSchema = external_exports.object({
14703
14777
  id: external_exports.string().min(1),
14704
14778
  sessionId: external_exports.string().min(1),
14705
- sessionTitle: external_exports.string().min(1).optional(),
14706
- transition: external_exports.enum([
14707
- "completed",
14708
- "aborted",
14709
- "blocked",
14710
- "error",
14711
- "max-tokens",
14712
- "interrupted",
14713
- "forked"
14714
- ]),
14779
+ sessionTitle: excerptSchema.optional(),
14780
+ // Derived from the shared vocabulary: a protocol transition added and written
14781
+ // by the core can never become a record that this fold rejects.
14782
+ transition: external_exports.enum([...DEVLEAD_TRANSITIONS]),
14715
14783
  turn: external_exports.number().int().positive(),
14716
- at: external_exports.number().int().nonnegative(),
14717
- error: external_exports.string().min(1).optional(),
14718
- summary: external_exports.string().min(1).optional()
14719
- });
14784
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2),
14785
+ error: excerptSchema.optional(),
14786
+ summary: excerptSchema.optional()
14787
+ }).strict().refine(
14788
+ (notification) => notification.id === notificationId2(
14789
+ notification.sessionId,
14790
+ notification.turn,
14791
+ notification.transition
14792
+ ),
14793
+ { message: "notification id must match sessionId, turn, and transition" }
14794
+ );
14720
14795
  function retainNotification(notifications, notification) {
14721
14796
  if (notifications.some((existing) => existing.id === notification.id)) return notifications;
14722
14797
  const next = [...notifications, notification];
14723
14798
  return next.length <= DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2 ? next : next.slice(next.length - DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2);
14724
14799
  }
14800
+ function sameSessionIds(left, right) {
14801
+ return left.length === right.length && left.every((id, index) => id === right[index]);
14802
+ }
14725
14803
  var devLeadProjectionStateSchema = external_exports.object({
14726
14804
  enabled: external_exports.boolean(),
14727
- sessions: external_exports.array(external_exports.string().min(1)),
14728
- notifications: external_exports.array(notificationSchema),
14805
+ sessions: external_exports.array(external_exports.string().min(1)).refine(
14806
+ (sessions) => new Set(sessions).size === sessions.length,
14807
+ { message: "sessions must be unique" }
14808
+ ),
14809
+ notifications: external_exports.array(notificationSchema).max(DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2).refine(
14810
+ (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14811
+ { message: "notification ids must be unique" }
14812
+ ),
14729
14813
  failure: external_exports.string().min(1).nullable()
14730
14814
  }).strict();
14731
14815
  var devLeadProjectionSchema = external_exports.object({
14732
14816
  enabled: external_exports.boolean(),
14733
14817
  sessions: external_exports.array(external_exports.string().min(1)),
14734
- notifications: external_exports.array(notificationSchema)
14818
+ notifications: external_exports.array(notificationSchema).max(DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2).refine(
14819
+ (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14820
+ { message: "notification ids must be unique" }
14821
+ )
14735
14822
  }).strict();
14823
+ var wireViews = /* @__PURE__ */ new WeakMap();
14736
14824
  function devLeadProjectionView(state) {
14737
- return { enabled: state.enabled, sessions: state.sessions, notifications: state.notifications };
14825
+ const cached2 = wireViews.get(state);
14826
+ if (cached2 !== void 0) return cached2;
14827
+ const view = {
14828
+ enabled: state.enabled,
14829
+ sessions: state.sessions,
14830
+ notifications: state.notifications
14831
+ };
14832
+ wireViews.set(state, view);
14833
+ return view;
14738
14834
  }
14739
14835
  function applyDevLeadProjection(state, event) {
14740
- if (state.failure !== null) return state;
14741
14836
  const record2 = pluginRecordOf(event);
14742
14837
  if (record2 === void 0) return state;
14838
+ if (record2.type === DEVLEAD_RESET_RECORD_TYPE2) {
14839
+ try {
14840
+ decodeResetRecord(record2.data);
14841
+ return emptyDevLeadProjectionState();
14842
+ } catch (error51) {
14843
+ if (state.failure !== null) return state;
14844
+ return freezeProjection(state, event, record2.type, error51);
14845
+ }
14846
+ }
14847
+ if (state.failure !== null) return state;
14743
14848
  try {
14744
14849
  switch (record2.type) {
14745
14850
  case DEVLEAD_MODE_RECORD_TYPE2: {
@@ -14748,7 +14853,7 @@ function applyDevLeadProjection(state, event) {
14748
14853
  }
14749
14854
  case DEVLEAD_WATCH_RECORD_TYPE2: {
14750
14855
  const watch = decodeWatchRecord(record2.data);
14751
- return { ...state, sessions: watch.sessions };
14856
+ return sameSessionIds(state.sessions, watch.sessions) ? state : { ...state, sessions: watch.sessions };
14752
14857
  }
14753
14858
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2: {
14754
14859
  const notification = decodeNotificationRecord(record2.data);
@@ -14759,41 +14864,141 @@ function applyDevLeadProjection(state, event) {
14759
14864
  return state;
14760
14865
  }
14761
14866
  } catch (error51) {
14762
- const message = error51 instanceof Error ? error51.message : String(error51);
14763
- return {
14764
- ...state,
14765
- failure: `devlead replay failed at session event ${event.seq} (${record2.type}): ${message}`
14766
- };
14867
+ return freezeProjection(state, event, record2.type, error51);
14767
14868
  }
14768
14869
  }
14870
+ function freezeProjection(state, event, type, error51) {
14871
+ const message = error51 instanceof Error ? error51.message : String(error51);
14872
+ const failure = {
14873
+ ...state,
14874
+ failure: `devlead replay failed at session event ${event.seq} (${type}): ${message}`
14875
+ };
14876
+ wireViews.set(failure, devLeadProjectionView(state));
14877
+ return failure;
14878
+ }
14769
14879
  var devLeadProjectionDefinition = {
14770
14880
  key: DEVLEAD_PROJECTION_KEY,
14771
14881
  stateSchema: devLeadProjectionStateSchema,
14882
+ // The unit owns no Session-metadata-derived state, so it ignores the header
14883
+ // and inherited-prefix arguments the registry passes.
14772
14884
  init: emptyDevLeadProjectionState,
14773
14885
  apply: applyDevLeadProjection,
14774
14886
  wire: {
14775
14887
  viewSchema: devLeadProjectionSchema,
14776
- view: devLeadProjectionView
14888
+ view: devLeadProjectionView,
14889
+ // The retained digest makes this value large, and only the open
14890
+ // conversation reads it: keep it out of every Session summary/list row.
14891
+ summary: false
14777
14892
  },
14778
14893
  // 1: the initial durable representation of the mode, watch set, and keyed
14779
14894
  // notification records.
14780
14895
  stateVersion: 1
14781
14896
  };
14897
+ function emptyDevLeadModeProjectionState() {
14898
+ return { enabled: false, failure: null };
14899
+ }
14900
+ var devLeadModeProjectionStateSchema = external_exports.object({
14901
+ enabled: external_exports.boolean(),
14902
+ failure: external_exports.string().min(1).nullable()
14903
+ }).strict();
14904
+ var devLeadModeProjectionSchema = external_exports.object({
14905
+ enabled: external_exports.boolean()
14906
+ }).strict();
14907
+ var MODE_ENABLED_VIEW = { enabled: true };
14908
+ var MODE_DISABLED_VIEW = { enabled: false };
14909
+ function devLeadModeProjectionView(state) {
14910
+ return state.enabled ? MODE_ENABLED_VIEW : MODE_DISABLED_VIEW;
14911
+ }
14912
+ function applyDevLeadModeProjection(state, event) {
14913
+ const record2 = pluginRecordOf(event);
14914
+ if (record2 === void 0) return state;
14915
+ if (record2.type === DEVLEAD_RESET_RECORD_TYPE2) {
14916
+ try {
14917
+ decodeResetRecord(record2.data);
14918
+ return emptyDevLeadModeProjectionState();
14919
+ } catch (error51) {
14920
+ if (state.failure !== null) return state;
14921
+ const message = error51 instanceof Error ? error51.message : String(error51);
14922
+ return {
14923
+ ...state,
14924
+ failure: `devlead mode replay failed at session event ${event.seq} (${record2.type}): ${message}`
14925
+ };
14926
+ }
14927
+ }
14928
+ if (state.failure !== null) return state;
14929
+ try {
14930
+ switch (record2.type) {
14931
+ case DEVLEAD_MODE_RECORD_TYPE2: {
14932
+ const mode = decodeModeRecord(record2.data);
14933
+ return mode.enabled === state.enabled ? state : { enabled: mode.enabled, failure: null };
14934
+ }
14935
+ case DEVLEAD_WATCH_RECORD_TYPE2:
14936
+ decodeWatchRecord(record2.data);
14937
+ return state;
14938
+ case DEVLEAD_NOTIFICATION_RECORD_TYPE2:
14939
+ decodeNotificationRecord(record2.data);
14940
+ return state;
14941
+ default:
14942
+ return state;
14943
+ }
14944
+ } catch (error51) {
14945
+ const message = error51 instanceof Error ? error51.message : String(error51);
14946
+ return {
14947
+ ...state,
14948
+ failure: `devlead mode replay failed at session event ${event.seq} (${record2.type}): ${message}`
14949
+ };
14950
+ }
14951
+ }
14952
+ var devLeadModeProjectionDefinition = {
14953
+ key: DEVLEAD_MODE_PROJECTION_KEY,
14954
+ stateSchema: devLeadModeProjectionStateSchema,
14955
+ // The unit owns no Session-metadata-derived state, so it ignores the header
14956
+ // and inherited-prefix arguments the registry passes.
14957
+ init: emptyDevLeadModeProjectionState,
14958
+ apply: applyDevLeadModeProjection,
14959
+ wire: {
14960
+ viewSchema: devLeadModeProjectionSchema,
14961
+ view: devLeadModeProjectionView
14962
+ },
14963
+ // 1: the initial durable representation of the compact mode selection.
14964
+ stateVersion: 1
14965
+ };
14966
+
14967
+ // packages/devlead/src/isolation.ts
14968
+ function worktreeCheckoutOf(value) {
14969
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
14970
+ const record2 = value;
14971
+ const path = record2.path;
14972
+ const branch = record2.branch;
14973
+ const baseCommit = record2.baseCommit;
14974
+ if (typeof path !== "string" || path.length === 0) return void 0;
14975
+ if (typeof branch !== "string" || branch.length === 0) return void 0;
14976
+ if (typeof baseCommit !== "string" || baseCommit.length === 0) return void 0;
14977
+ return { path, branch, baseCommit };
14978
+ }
14979
+ function worktreeCapabilityOf(ctx) {
14980
+ const candidate = ctx.get("worktrees");
14981
+ if (typeof candidate !== "object" || candidate === null) return void 0;
14982
+ const create = candidate.create;
14983
+ if (typeof create !== "function") return void 0;
14984
+ return candidate;
14985
+ }
14782
14986
 
14783
14987
  // packages/devlead/src/notification.ts
14784
14988
  import { appendPluginRecord, pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
14785
14989
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
14786
14990
  import {
14787
14991
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3,
14788
- DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX2,
14789
14992
  DEVLEAD_MESSAGE_KIND as DEVLEAD_MESSAGE_KIND2,
14790
14993
  DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
14791
14994
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE3,
14792
14995
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE3,
14793
- excerptLine as excerptLine2,
14996
+ isDevLeadTransition as isDevLeadTransition2,
14794
14997
  notificationLine
14795
14998
  } from "@yankeguo/dsh-devlead-protocol";
14796
14999
  var MAX_DIGEST_LINES = 12;
15000
+ var DELIVERY_RETRY_MS = 1e3;
15001
+ var DEVLEAD_MAX_WARNED_FAILURES = 256;
14797
15002
  function renderDevLeadNotice(notifications, total = notifications.length) {
14798
15003
  const shown = notifications.slice(-MAX_DIGEST_LINES);
14799
15004
  const omitted = total - shown.length;
@@ -14820,7 +15025,7 @@ var DevLeadNotificationHub = class {
14820
15025
  ctx;
14821
15026
  readState;
14822
15027
  config;
14823
- /** Live lead Sessions by identity. */
15028
+ /** Indexed lead Sessions by identity. */
14824
15029
  leads = /* @__PURE__ */ new Map();
14825
15030
  /** Watched Session identity → lead Session identities watching it. */
14826
15031
  watchers = /* @__PURE__ */ new Map();
@@ -14828,22 +15033,30 @@ var DevLeadNotificationHub = class {
14828
15033
  resuming = /* @__PURE__ */ new Set();
14829
15034
  /** Latest assistant excerpt observed per watched Session, bounded and pruned with the index. */
14830
15035
  lastAssistant = /* @__PURE__ */ new Map();
15036
+ /** Sessions whose replay failure has already been reported, so a corrupt log warns once per Host process. */
15037
+ warnedFailures = /* @__PURE__ */ new Set();
15038
+ /** Leads whose persisted watch set named themselves; warn once per live indexing. */
15039
+ warnedSelfWatch = /* @__PURE__ */ new Set();
15040
+ started = false;
14831
15041
  stopping = false;
14832
- /** Install the lifecycle listeners and index every currently live lead. */
15042
+ /**
15043
+ * Install the lifecycle listeners and index every currently live lead.
15044
+ * Calling this twice is a no-op: the hub owns exactly one listener set.
15045
+ */
14833
15046
  start() {
15047
+ if (this.started) return;
15048
+ this.started = true;
14834
15049
  this.bootstrap();
14835
15050
  this.ctx.effect(function* () {
14836
15051
  this.ctx.on("agent/created", ({ agent }) => {
14837
15052
  this.syncLead(agent);
14838
15053
  return void 0;
14839
15054
  });
14840
- this.ctx.on("agent/disposed", ({ agent }) => {
14841
- this.removeLead(String(agent.id));
14842
- });
14843
15055
  this.ctx.on("agent/status", ({ agent, status }) => {
14844
15056
  if (status !== "idle") return;
14845
15057
  const runtime = this.leads.get(String(agent.id));
14846
- if (runtime === void 0 || runtime.pending.length === 0) return;
15058
+ if (runtime === void 0) return;
15059
+ if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
14847
15060
  void this.flush(runtime);
14848
15061
  });
14849
15062
  this.ctx.on("session/event", (session, event) => {
@@ -14856,6 +15069,25 @@ var DevLeadNotificationHub = class {
14856
15069
  };
14857
15070
  }.bind(this), "devlead: notification hub");
14858
15071
  }
15072
+ /**
15073
+ * Rebuild the watch index from durable state without requiring a live Agent
15074
+ * or Session (cold rehydration after a Host restart).
15075
+ *
15076
+ * Idempotent and safe before {@link start}: it only creates runtime rows and
15077
+ * replaces their watched sets, so calling it again with the same records is a
15078
+ * no-op.
15079
+ * @param leads - persisted lead records reported by the Host's durable scan.
15080
+ */
15081
+ rehydrate(leads) {
15082
+ if (this.stopping) return;
15083
+ for (const lead of leads) {
15084
+ if (typeof lead.sessionId !== "string" || lead.sessionId.length === 0) continue;
15085
+ if (!Array.isArray(lead.watched)) continue;
15086
+ const watched = lead.watched.filter((id) => typeof id === "string" && id.length > 0);
15087
+ const runtime = this.ensureLead(lead.sessionId);
15088
+ this.setWatched(runtime, watched);
15089
+ }
15090
+ }
14859
15091
  /**
14860
15092
  * Deliver any queued digest for one lead right now.
14861
15093
  * @param leadSessionId - lead Session identity.
@@ -14872,20 +15104,41 @@ var DevLeadNotificationHub = class {
14872
15104
  }
14873
15105
  /**
14874
15106
  * Read one Session's fold state, treating a replay failure as unavailable.
15107
+ *
15108
+ * A corrupt log is reported once per Session per Host process: the id stays in
15109
+ * the bounded warned set across disposal/reopen, and is only forgotten when a
15110
+ * later read returns a valid state (for example after a `/devlead reset`).
14875
15111
  * @param session - live Session.
14876
15112
  * @returns the fold state, or undefined when the projection is invalid.
14877
15113
  */
14878
15114
  stateOf(session) {
14879
15115
  const state = this.readState(session);
15116
+ const sessionId = String(session.id);
14880
15117
  if (state.failure !== null) {
14881
- this.ctx.logger.warn(`devlead: ${state.failure}`);
15118
+ if (!this.warnedFailures.has(sessionId)) {
15119
+ this.warnedFailures.add(sessionId);
15120
+ this.trimWarnedFailures();
15121
+ this.ctx.logger.warn(`devlead: ${state.failure}`);
15122
+ }
14882
15123
  return void 0;
14883
15124
  }
15125
+ this.warnedFailures.delete(sessionId);
14884
15126
  return state;
14885
15127
  }
15128
+ /** Keep {@link warnedFailures} bounded, evicting the oldest ids first. */
15129
+ trimWarnedFailures() {
15130
+ while (this.warnedFailures.size > DEVLEAD_MAX_WARNED_FAILURES) {
15131
+ const oldest = this.warnedFailures.values().next().value;
15132
+ if (oldest === void 0) return;
15133
+ this.warnedFailures.delete(oldest);
15134
+ }
15135
+ }
14886
15136
  /**
14887
15137
  * Reconcile one live lead Agent with its durable state: register, update the
14888
- * watch index, or drop the runtime when the mode is off.
15138
+ * watch index, or drop the runtime when the mode is off. A lead that becomes
15139
+ * live with queued work (notifications observed while it was cold) arms its
15140
+ * flush, so opening or resuming the Session writes the records and delivers
15141
+ * the digest.
14889
15142
  * @param agent - live Agent that may lead.
14890
15143
  */
14891
15144
  syncLead(agent) {
@@ -14898,7 +15151,7 @@ var DevLeadNotificationHub = class {
14898
15151
  }
14899
15152
  const runtime = this.ensureLead(sessionId);
14900
15153
  this.setWatched(runtime, state.sessions);
14901
- if (runtime.pending.length > 0) this.scheduleFlush(runtime);
15154
+ if (runtime.pending.length > 0 || runtime.unsaved.length > 0) this.scheduleFlush(runtime);
14902
15155
  }
14903
15156
  /**
14904
15157
  * Create the runtime row for one lead Session.
@@ -14912,7 +15165,9 @@ var DevLeadNotificationHub = class {
14912
15165
  sessionId,
14913
15166
  watched: /* @__PURE__ */ new Set(),
14914
15167
  pending: [],
15168
+ unsaved: [],
14915
15169
  timer: void 0,
15170
+ scheduled: false,
14916
15171
  flushing: false
14917
15172
  };
14918
15173
  this.leads.set(sessionId, runtime);
@@ -14920,11 +15175,23 @@ var DevLeadNotificationHub = class {
14920
15175
  }
14921
15176
  /**
14922
15177
  * Replace one lead's watch set and update the reverse index.
15178
+ *
15179
+ * The most recently observed durable set is authoritative: a notification of
15180
+ * a Session that is no longer watched is dropped from both queues. A watch set
15181
+ * that names its own lead (only possible through a hand-edited or migrated
15182
+ * log) is filtered here, with one warning per live indexing, because accepting
15183
+ * it would make each turn/end append to the event currently being published.
14923
15184
  * @param runtime - lead runtime row.
14924
15185
  * @param sessions - complete durable watch set.
14925
15186
  */
14926
15187
  setWatched(runtime, sessions) {
14927
- const next = new Set(sessions);
15188
+ const selfWatched = sessions.includes(runtime.sessionId);
15189
+ if (selfWatched && !this.warnedSelfWatch.has(runtime.sessionId)) {
15190
+ this.warnedSelfWatch.add(runtime.sessionId);
15191
+ this.ctx.logger.warn(`devlead: lead "${runtime.sessionId}" lists itself in its persisted watch set; ignoring it`);
15192
+ }
15193
+ if (!selfWatched) this.warnedSelfWatch.delete(runtime.sessionId);
15194
+ const next = new Set(selfWatched ? sessions.filter((id) => id !== runtime.sessionId) : sessions);
14928
15195
  for (const watched of runtime.watched) {
14929
15196
  if (next.has(watched)) continue;
14930
15197
  const set2 = this.watchers.get(watched);
@@ -14946,10 +15213,15 @@ var DevLeadNotificationHub = class {
14946
15213
  }
14947
15214
  runtime.watched = next;
14948
15215
  runtime.pending = runtime.pending.filter((notification) => next.has(notification.sessionId));
14949
- if (runtime.pending.length === 0) this.clearTimer(runtime);
15216
+ runtime.unsaved = runtime.unsaved.filter((notification) => next.has(notification.sessionId));
15217
+ if (runtime.pending.length === 0 && runtime.unsaved.length === 0) this.clearTimer(runtime);
14950
15218
  }
14951
15219
  /**
14952
15220
  * Drop one lead runtime and its reverse-index entries.
15221
+ *
15222
+ * The remembered corrupt-replay warnings deliberately survive this call: the
15223
+ * same damaged Session must not warn again just because its Agent was
15224
+ * disposed and reopened (only a valid state clears the marker).
14953
15225
  * @param leadId - lead Session identity.
14954
15226
  */
14955
15227
  removeLead(leadId) {
@@ -14965,15 +15237,20 @@ var DevLeadNotificationHub = class {
14965
15237
  this.lastAssistant.delete(watched);
14966
15238
  }
14967
15239
  }
15240
+ runtime.pending = [];
15241
+ runtime.unsaved = [];
14968
15242
  this.leads.delete(leadId);
14969
15243
  }
14970
15244
  this.resuming.delete(leadId);
15245
+ this.warnedSelfWatch.delete(leadId);
14971
15246
  }
14972
- /** Clear one pending coalescing timer. */
15247
+ /** Clear one pending coalescing/retry timer or queued zero-delay flush. */
14973
15248
  clearTimer(runtime) {
14974
- if (runtime.timer === void 0) return;
14975
- clearTimeout(runtime.timer);
14976
- runtime.timer = void 0;
15249
+ if (runtime.timer !== void 0) {
15250
+ clearTimeout(runtime.timer);
15251
+ runtime.timer = void 0;
15252
+ }
15253
+ runtime.scheduled = false;
14977
15254
  }
14978
15255
  /**
14979
15256
  * Observe one committed Session event for lead-state changes and watched
@@ -14985,7 +15262,7 @@ var DevLeadNotificationHub = class {
14985
15262
  if (this.stopping) return;
14986
15263
  const sessionId = String(session.id);
14987
15264
  const record2 = pluginRecordOf2(event);
14988
- if (record2 !== void 0 && (record2.type === DEVLEAD_MODE_RECORD_TYPE3 || record2.type === DEVLEAD_WATCH_RECORD_TYPE3)) {
15265
+ if (record2 !== void 0 && (record2.type === DEVLEAD_MODE_RECORD_TYPE3 || record2.type === DEVLEAD_WATCH_RECORD_TYPE3 || record2.type === DEVLEAD_RESET_RECORD_TYPE)) {
14989
15266
  const agent = this.ctx.agents.get(session.id);
14990
15267
  if (agent !== void 0) this.syncLead(agent);
14991
15268
  }
@@ -15006,8 +15283,7 @@ var DevLeadNotificationHub = class {
15006
15283
  * @param blocks - assistant message content blocks.
15007
15284
  */
15008
15285
  rememberAssistant(sessionId, blocks) {
15009
- const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
15010
- const excerpt = excerptLine2(text, DEVLEAD_ERROR_EXCERPT_MAX2);
15286
+ const excerpt = assistantExcerpt(blocks);
15011
15287
  if (excerpt !== void 0) this.lastAssistant.set(sessionId, excerpt);
15012
15288
  }
15013
15289
  /**
@@ -15018,8 +15294,10 @@ var DevLeadNotificationHub = class {
15018
15294
  */
15019
15295
  notificationOf(session, event) {
15020
15296
  if (event.type !== "turn/end") return void 0;
15297
+ const turn = event.data.turn;
15298
+ if (!Number.isSafeInteger(turn) || turn < 1) return void 0;
15021
15299
  const reason = event.data.reason.kind;
15022
- const transition = reason === "completed" || reason === "aborted" || reason === "blocked" || reason === "error" || reason === "max-tokens" || reason === "interrupted" || reason === "forked" ? reason : "interrupted";
15300
+ const transition = isDevLeadTransition2(reason) ? reason : "interrupted";
15023
15301
  const title = this.ctx.get("sessionTitle")?.get(session)?.title;
15024
15302
  const error51 = reason === "error" ? failureExcerpt(event.data.reason.error) : void 0;
15025
15303
  const summary = this.lastAssistant.get(String(session.id));
@@ -15027,37 +15305,110 @@ var DevLeadNotificationHub = class {
15027
15305
  String(session.id),
15028
15306
  title,
15029
15307
  transition,
15030
- event.data.turn,
15031
- event.time,
15308
+ turn,
15309
+ representableInstant(event.time, Date.now()),
15032
15310
  error51,
15033
15311
  summary
15034
15312
  );
15035
15313
  }
15036
15314
  /**
15037
15315
  * Persist one notification into a lead Session and queue its wake-up.
15316
+ *
15317
+ * The durable row is written first whenever the lead Session's log is
15318
+ * attached (the digest stays the audit authority; the fold dedupes a replayed
15319
+ * identity). A cold lead Session (persisted but not attached) cannot append,
15320
+ * so the notification waits in `unsaved` until it becomes live. An identity
15321
+ * already queued in either queue is not queued twice, so a replayed
15322
+ * `turn/end` cannot double a digest line.
15038
15323
  * @param leadId - lead Session identity.
15039
15324
  * @param notification - observed notification.
15040
15325
  */
15041
15326
  record(leadId, notification) {
15327
+ if (notification.sessionId === leadId) return;
15042
15328
  const runtime = this.leads.get(leadId);
15329
+ if (runtime === void 0) return;
15043
15330
  const session = this.ctx.sessions.get(toSessionId(leadId));
15044
- if (runtime === void 0 || session === void 0) return;
15331
+ if (session !== void 0) this.appendNotificationRecord(session, notification, leadId);
15332
+ if (runtime.pending.some((existing) => existing.id === notification.id)) return;
15333
+ if (runtime.unsaved.some((existing) => existing.id === notification.id)) return;
15334
+ if (session === void 0) {
15335
+ runtime.unsaved = [...runtime.unsaved, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15336
+ this.scheduleFlush(runtime);
15337
+ return;
15338
+ }
15339
+ runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15340
+ this.scheduleFlush(runtime);
15341
+ }
15342
+ /**
15343
+ * Append one durable notification record and fire-and-forget its durability
15344
+ * checkpoint, shortening the crash window between the append and the digest
15345
+ * delivery. A failed append is a warning: the wake-up still happens (the
15346
+ * record may be lost, but the lead is not left unnotified).
15347
+ * @param session - lead Session receiving the record.
15348
+ * @param notification - notification to persist.
15349
+ * @param leadId - lead Session identity used in warnings.
15350
+ */
15351
+ appendNotificationRecord(session, notification, leadId) {
15045
15352
  try {
15046
15353
  appendPluginRecord(session, DEVLEAD_NOTIFICATION_RECORD_TYPE3, notificationRecord(notification));
15047
15354
  } catch (error51) {
15048
- this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${String(error51)}`);
15355
+ this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${thrownMessage(error51)}`);
15356
+ return;
15357
+ }
15358
+ void this.checkpoint(session, leadId);
15359
+ }
15360
+ /**
15361
+ * Fire-and-forget one Session durability checkpoint.
15362
+ * @param session - Session whose buffered events should be persisted.
15363
+ * @param leadId - lead Session identity used in warnings.
15364
+ */
15365
+ async checkpoint(session, leadId) {
15366
+ try {
15367
+ await this.ctx.sessions.flush(session);
15368
+ } catch (error51) {
15369
+ this.ctx.logger.warn(
15370
+ `devlead: recorded notification for lead "${leadId}" could not be flushed to persistence: ${thrownMessage(error51)}`
15371
+ );
15049
15372
  }
15050
- runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15051
- this.scheduleFlush(runtime);
15373
+ }
15374
+ /**
15375
+ * Append the notifications that could not be persisted while the lead Session
15376
+ * was cold, moving each durable success into `pending`. A failed append keeps
15377
+ * the notification in `unsaved` and arms the bounded retry.
15378
+ * @param session - attached lead Session log receiving the records.
15379
+ * @param runtime - lead runtime row.
15380
+ */
15381
+ persistUnsaved(session, runtime) {
15382
+ if (runtime.unsaved.length === 0) return;
15383
+ const remaining = [];
15384
+ let appended = false;
15385
+ for (const notification of runtime.unsaved) {
15386
+ try {
15387
+ appendPluginRecord(session, DEVLEAD_NOTIFICATION_RECORD_TYPE3, notificationRecord(notification));
15388
+ } catch (error51) {
15389
+ this.ctx.logger.warn(
15390
+ `devlead: could not record a notification for lead "${runtime.sessionId}": ${thrownMessage(error51)}`
15391
+ );
15392
+ remaining.push(notification);
15393
+ continue;
15394
+ }
15395
+ appended = true;
15396
+ runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15397
+ }
15398
+ runtime.unsaved = remaining;
15399
+ if (appended) void this.checkpoint(session, runtime.sessionId);
15400
+ if (remaining.length > 0) this.scheduleRetry(runtime);
15052
15401
  }
15053
15402
  /**
15054
15403
  * Arm the coalescing window for one lead.
15055
15404
  * @param runtime - lead runtime row.
15056
15405
  */
15057
15406
  scheduleFlush(runtime) {
15058
- if (this.stopping || runtime.timer !== void 0 || runtime.flushing) return;
15407
+ if (this.stopping || runtime.timer !== void 0 || runtime.scheduled || runtime.flushing) return;
15059
15408
  if (this.config.batchMs <= 0) {
15409
+ runtime.scheduled = true;
15060
15410
  queueMicrotask(() => {
15411
+ runtime.scheduled = false;
15061
15412
  void this.flush(runtime);
15062
15413
  });
15063
15414
  return;
@@ -15068,41 +15419,90 @@ var DevLeadNotificationHub = class {
15068
15419
  }, this.config.batchMs);
15069
15420
  }
15070
15421
  /**
15071
- * Deliver one coalesced digest to a lead whose Agent is live.
15422
+ * Deliver one coalesced digest to a live lead, or resume an indexed-but-cold
15423
+ * lead when `wakeColdSession` is enabled.
15424
+ *
15425
+ * An archived lead is checked first and pauses delivery unconditionally: it is
15426
+ * never resumed, even when `wakeColdSession` is enabled. An archived lead whose
15427
+ * Session log is attached persists its cold observations (an archived Session
15428
+ * can still append) and then drops the in-memory queues; one that is fully
15429
+ * cold keeps them until it is unarchived and opened.
15430
+ *
15431
+ * A live lead first persists any notification observed while it was cold. The
15432
+ * digest is only taken when the lead's inbox holds no undelivered DevLead
15433
+ * notice: otherwise the batch stays pending and a bounded recheck timer is
15434
+ * armed, so a second batch can never be silently dropped while the first wake
15435
+ * is still queued (D5). The durable digest stays visible once the Session is
15436
+ * restored.
15072
15437
  * @param runtime - lead runtime row.
15073
15438
  * @returns fulfillment after the delivery attempt settles.
15074
15439
  */
15075
15440
  async flush(runtime) {
15076
- if (this.stopping || runtime.flushing || runtime.pending.length === 0) return;
15077
- const agent = this.ctx.agents.get(toSessionId(runtime.sessionId));
15441
+ if (this.stopping) return;
15442
+ if (this.leads.get(runtime.sessionId) !== runtime) return;
15443
+ if (runtime.flushing) return;
15444
+ if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
15445
+ const leadSessionId = toSessionId(runtime.sessionId);
15446
+ const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(leadSessionId) ?? false;
15447
+ if (archived) {
15448
+ const session = this.ctx.sessions.get(leadSessionId) ?? this.ctx.agents.get(leadSessionId)?.session;
15449
+ if (session !== void 0) {
15450
+ this.persistUnsaved(session, runtime);
15451
+ runtime.pending = [];
15452
+ runtime.unsaved = [];
15453
+ }
15454
+ this.clearTimer(runtime);
15455
+ return;
15456
+ }
15457
+ const agent = this.ctx.agents.get(leadSessionId);
15078
15458
  if (agent === void 0) {
15079
15459
  if (this.config.wakeColdSession) await this.resumeCold(runtime);
15080
15460
  return;
15081
15461
  }
15082
- const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(toSessionId(runtime.sessionId)) ?? false;
15083
- if (archived) {
15084
- runtime.pending = [];
15462
+ this.persistUnsaved(agent.session, runtime);
15463
+ if (runtime.pending.length === 0) return;
15464
+ if (this.hasQueuedNotice(agent)) {
15465
+ this.scheduleRetry(runtime);
15085
15466
  return;
15086
15467
  }
15087
15468
  const batch = runtime.pending;
15088
15469
  runtime.pending = [];
15470
+ this.clearTimer(runtime);
15089
15471
  runtime.flushing = true;
15472
+ let failed = false;
15090
15473
  try {
15091
- if (!this.hasQueuedNotice(agent)) {
15092
- agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
15093
- try {
15094
- await this.ctx.sessions.flush(agent.session);
15095
- } catch (error51) {
15096
- this.ctx.logger.warn(`devlead: notification digest was not flushed for lead "${runtime.sessionId}": ${String(error51)}`);
15097
- }
15474
+ agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
15475
+ try {
15476
+ await this.ctx.sessions.flush(agent.session);
15477
+ } catch (error51) {
15478
+ this.ctx.logger.warn(`devlead: notification digest could not be flushed for lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15098
15479
  }
15099
15480
  } catch (error51) {
15100
- this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${String(error51)}`);
15481
+ this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15101
15482
  runtime.pending = [...batch, ...runtime.pending].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15483
+ failed = true;
15102
15484
  } finally {
15103
15485
  runtime.flushing = false;
15104
15486
  }
15105
- if (runtime.pending.length > 0) this.scheduleFlush(runtime);
15487
+ if ((runtime.pending.length > 0 || runtime.unsaved.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
15488
+ if (failed || runtime.unsaved.length > 0) {
15489
+ this.scheduleRetry(runtime);
15490
+ } else {
15491
+ this.scheduleFlush(runtime);
15492
+ }
15493
+ }
15494
+ }
15495
+ /**
15496
+ * Arm one bounded retry: a failed wake-up delivery, or a recheck of a batch
15497
+ * kept pending behind an undelivered inbox notice.
15498
+ * @param runtime - lead runtime row.
15499
+ */
15500
+ scheduleRetry(runtime) {
15501
+ if (this.stopping || runtime.timer !== void 0 || runtime.scheduled || runtime.flushing) return;
15502
+ runtime.timer = setTimeout(() => {
15503
+ runtime.timer = void 0;
15504
+ void this.flush(runtime);
15505
+ }, DELIVERY_RETRY_MS);
15106
15506
  }
15107
15507
  /**
15108
15508
  * Whether one lead Agent already holds an undelivered digest notice.
@@ -15121,6 +15521,7 @@ var DevLeadNotificationHub = class {
15121
15521
  * @returns fulfillment after the resume attempt settles.
15122
15522
  */
15123
15523
  async resumeCold(runtime) {
15524
+ if (this.stopping) return;
15124
15525
  const leadId = runtime.sessionId;
15125
15526
  if (this.resuming.has(leadId)) return;
15126
15527
  const controller = this.ctx.get("sessionController");
@@ -15128,26 +15529,80 @@ var DevLeadNotificationHub = class {
15128
15529
  this.resuming.add(leadId);
15129
15530
  try {
15130
15531
  const resolved = await controller.resolveAgent(toSessionId(leadId));
15532
+ if (this.stopping) return;
15131
15533
  if ("error" in resolved) {
15132
15534
  this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${resolved.error.message}`);
15133
15535
  return;
15134
15536
  }
15135
15537
  this.syncLead(resolved.agent);
15136
15538
  } catch (error51) {
15137
- this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${String(error51)}`);
15539
+ if (!this.stopping) {
15540
+ this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${thrownMessage(error51)}`);
15541
+ }
15138
15542
  } finally {
15139
15543
  this.resuming.delete(leadId);
15140
15544
  }
15141
15545
  }
15142
15546
  };
15143
15547
 
15548
+ // packages/devlead/src/persistence.ts
15549
+ async function persistedSessionsOf(ctx) {
15550
+ const candidate = ctx.get("sessionPersistence");
15551
+ if (typeof candidate !== "object" || candidate === null) return { verifiable: false };
15552
+ const list = candidate.list;
15553
+ if (typeof list !== "function") return { verifiable: false };
15554
+ let listed;
15555
+ try {
15556
+ listed = await Promise.resolve(list.call(candidate));
15557
+ } catch {
15558
+ return { verifiable: true };
15559
+ }
15560
+ if (!Array.isArray(listed)) return { verifiable: true };
15561
+ const ids = /* @__PURE__ */ new Set();
15562
+ for (const snapshot of listed) {
15563
+ if (typeof snapshot !== "object" || snapshot === null) continue;
15564
+ const header = snapshot.header;
15565
+ if (typeof header !== "object" || header === null) continue;
15566
+ const id = header.id;
15567
+ if (id === void 0 || id === null) continue;
15568
+ const text = typeof id === "string" ? id : String(id);
15569
+ if (text.length > 0) ids.add(text);
15570
+ }
15571
+ return { verifiable: true, ids };
15572
+ }
15573
+
15574
+ // packages/devlead/src/projection-cache.ts
15575
+ function projectionCacheOf(ctx) {
15576
+ const candidate = ctx.get("sessionProjectionCache");
15577
+ if (typeof candidate !== "object" || candidate === null) return void 0;
15578
+ const cachedSnapshot = candidate.cachedSnapshot;
15579
+ if (typeof cachedSnapshot !== "function") return void 0;
15580
+ const service = candidate;
15581
+ return { cachedSnapshot: (header) => service.cachedSnapshot(header) };
15582
+ }
15583
+ function devLeadPrefilterOf(cache, header) {
15584
+ let snapshot;
15585
+ try {
15586
+ snapshot = cache.cachedSnapshot(header);
15587
+ } catch {
15588
+ return "unknown";
15589
+ }
15590
+ if (typeof snapshot !== "object" || snapshot === null) return "unknown";
15591
+ const values = snapshot.values;
15592
+ if (typeof values !== "object" || values === null) return "unknown";
15593
+ const devLead = values.devLead;
15594
+ if (typeof devLead !== "object" || devLead === null) return "unknown";
15595
+ const record2 = devLead;
15596
+ if (record2.enabled !== true) {
15597
+ return record2.enabled === false ? "not-lead" : "unknown";
15598
+ }
15599
+ if (!Array.isArray(record2.sessions)) return "unknown";
15600
+ return record2.sessions.length > 0 ? "lead" : "not-lead";
15601
+ }
15602
+
15144
15603
  // packages/devlead/src/views.ts
15145
15604
  import { SessionId as toSessionId2 } from "@deepseek-ai/dsh-session";
15146
- import {
15147
- DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX3,
15148
- excerptLine as excerptLine3,
15149
- isDevLeadTransition as isDevLeadTransition2
15150
- } from "@yankeguo/dsh-devlead-protocol";
15605
+ import { isDevLeadTransition as isDevLeadTransition3 } from "@yankeguo/dsh-devlead-protocol";
15151
15606
  async function devLeadWorkspaceView(workspace) {
15152
15607
  const status = await workspace.status();
15153
15608
  return {
@@ -15160,8 +15615,11 @@ async function devLeadWorkspaceView(workspace) {
15160
15615
  updatedAt: workspace.updatedAt
15161
15616
  };
15162
15617
  }
15163
- async function collectSessionIds(deps, workspace) {
15164
- const { ctx } = deps;
15618
+ function rethrowIfAborted(error51, signal) {
15619
+ if (signal?.aborted === true) throw error51;
15620
+ }
15621
+ async function collectSessionIds(deps, workspace, exhaustive = false) {
15622
+ const { ctx, signal } = deps;
15165
15623
  const ids = /* @__PURE__ */ new Set();
15166
15624
  const admissible = (id) => {
15167
15625
  const session = ctx.sessions.get(toSessionId2(id)) ?? ctx.agents.get(toSessionId2(id))?.session;
@@ -15186,20 +15644,22 @@ async function collectSessionIds(deps, workspace) {
15186
15644
  const query = ctx.get("sessionQuery");
15187
15645
  if (query !== void 0) {
15188
15646
  try {
15189
- const records = await query.listSessions();
15647
+ const records = await query.listSessions(signal);
15190
15648
  for (const record2 of records) {
15191
- if (ids.size >= deps.maxListedSessions) break;
15649
+ if (!exhaustive && ids.size >= deps.maxListedSessions) break;
15192
15650
  if (record2.header.origin === "subagent") continue;
15193
15651
  ids.add(record2.header.id);
15194
15652
  }
15195
- } catch {
15653
+ } catch (error51) {
15654
+ rethrowIfAborted(error51, signal);
15196
15655
  }
15197
15656
  }
15198
15657
  }
15658
+ signal?.throwIfAborted();
15199
15659
  return [...ids].filter(admissible);
15200
15660
  }
15201
15661
  async function knownSessions(deps, ids) {
15202
- const { ctx } = deps;
15662
+ const { ctx, signal } = deps;
15203
15663
  const result = /* @__PURE__ */ new Map();
15204
15664
  const pendingTitles = [];
15205
15665
  for (const id of ids) {
@@ -15207,7 +15667,7 @@ async function knownSessions(deps, ids) {
15207
15667
  const agent = ctx.agents.get(toSessionId2(id));
15208
15668
  const live = session !== void 0 || agent !== void 0;
15209
15669
  const sessionObject = session ?? agent?.session;
15210
- let title = sessionObject === void 0 ? void 0 : ctx.get("sessionTitle")?.get(sessionObject)?.title;
15670
+ const title = sessionObject === void 0 ? void 0 : ctx.get("sessionTitle")?.get(sessionObject)?.title;
15211
15671
  if (title === void 0) pendingTitles.push(id);
15212
15672
  result.set(id, { title, header: sessionObject?.header, live });
15213
15673
  }
@@ -15215,7 +15675,7 @@ async function knownSessions(deps, ids) {
15215
15675
  const query = ctx.get("sessionQuery");
15216
15676
  if (query !== void 0) {
15217
15677
  try {
15218
- const observations = await query.readTitleSnapshots(pendingTitles.map((id) => toSessionId2(id)));
15678
+ const observations = await query.readTitleSnapshots(pendingTitles.map((id) => toSessionId2(id)), signal);
15219
15679
  for (const observation of observations) {
15220
15680
  if (observation.status !== "fulfilled") continue;
15221
15681
  const { session, title: snapshot } = observation.value;
@@ -15224,19 +15684,53 @@ async function knownSessions(deps, ids) {
15224
15684
  if (entry === void 0) continue;
15225
15685
  result.set(id, { ...entry, title: snapshot?.title ?? entry.title, header: session });
15226
15686
  }
15227
- } catch {
15687
+ } catch (error51) {
15688
+ rethrowIfAborted(error51, signal);
15228
15689
  }
15229
15690
  }
15230
15691
  }
15231
15692
  return result;
15232
15693
  }
15694
+ async function readSessionFacts(deps, ids) {
15695
+ const known = await knownSessions(deps, ids);
15696
+ const workspaces = /* @__PURE__ */ new Map();
15697
+ const archived = /* @__PURE__ */ new Set();
15698
+ const registry2 = deps.ctx.get("workspaceRegistry");
15699
+ if (registry2 !== void 0) {
15700
+ const requested = new Set(ids);
15701
+ for (const sessionId of registry2.archivedSessionIds) {
15702
+ const id = String(sessionId);
15703
+ if (requested.has(id)) archived.add(id);
15704
+ }
15705
+ for (const workspace of registry2.list()) {
15706
+ for (const sessionId of workspace.sessionIds) {
15707
+ const id = String(sessionId);
15708
+ if (!requested.has(id) || workspaces.has(id)) continue;
15709
+ workspaces.set(id, workspace);
15710
+ }
15711
+ }
15712
+ }
15713
+ return { known, workspaces, archived };
15714
+ }
15715
+ function rankSessionIds(deps, ids, facts, limit) {
15716
+ const ranked = ids.map((id) => ({
15717
+ id,
15718
+ watched: deps.isWatched(id),
15719
+ running: deps.ctx.agents.get(toSessionId2(id))?.status === "running",
15720
+ createdAt: facts.known.get(id)?.header?.createdAt ?? 0
15721
+ }));
15722
+ ranked.sort((left, right) => {
15723
+ if (left.watched !== right.watched) return left.watched ? -1 : 1;
15724
+ if (left.running !== right.running) return left.running ? -1 : 1;
15725
+ return right.createdAt - left.createdAt || left.id.localeCompare(right.id);
15726
+ });
15727
+ return ranked.slice(0, Math.max(1, limit)).map((entry) => entry.id);
15728
+ }
15233
15729
  function lastAssistantExcerpt(events) {
15234
15730
  for (let index = events.length - 1; index >= 0; index -= 1) {
15235
15731
  const event = events[index];
15236
15732
  if (event === void 0 || event.type !== "assistant/message") continue;
15237
- const blocks = event.data.message.content;
15238
- const text = blocks.filter((block) => typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
15239
- const excerpt = excerptLine3(text, DEVLEAD_ERROR_EXCERPT_MAX3);
15733
+ const excerpt = assistantExcerpt(event.data.message.content);
15240
15734
  if (excerpt !== void 0) return excerpt;
15241
15735
  }
15242
15736
  return void 0;
@@ -15244,13 +15738,16 @@ function lastAssistantExcerpt(events) {
15244
15738
  async function sessionLogFacts(deps, sessionId) {
15245
15739
  const query = deps.ctx.get("sessionQuery");
15246
15740
  if (query === void 0) return {};
15741
+ deps.signal?.throwIfAborted();
15247
15742
  let events;
15248
15743
  try {
15249
15744
  const snapshot = await query.readSession(toSessionId2(sessionId));
15250
15745
  events = snapshot.events;
15251
- } catch {
15746
+ } catch (error51) {
15747
+ rethrowIfAborted(error51, deps.signal);
15252
15748
  return {};
15253
15749
  }
15750
+ deps.signal?.throwIfAborted();
15254
15751
  const last = events.at(-1);
15255
15752
  let lastTurn;
15256
15753
  let lastTransition;
@@ -15261,10 +15758,8 @@ async function sessionLogFacts(deps, sessionId) {
15261
15758
  }
15262
15759
  if (event.type === "turn/end") {
15263
15760
  const kind = event.data.reason.kind;
15264
- if (isDevLeadTransition2(kind)) {
15265
- lastTransition = kind;
15266
- lastError = kind === "error" ? event.data.reason.error.message : void 0;
15267
- }
15761
+ lastTransition = isDevLeadTransition3(kind) ? kind : "interrupted";
15762
+ lastError = kind === "error" ? failureExcerpt(event.data.reason.error) : void 0;
15268
15763
  }
15269
15764
  }
15270
15765
  const lastAssistant = lastAssistantExcerpt(events);
@@ -15276,52 +15771,43 @@ async function sessionLogFacts(deps, sessionId) {
15276
15771
  ...lastAssistant === void 0 ? {} : { lastAssistant }
15277
15772
  };
15278
15773
  }
15279
- async function buildSessionView(deps, sessionId, withLog, known) {
15774
+ async function buildSessionView(deps, sessionId, withLog, facts) {
15280
15775
  const { ctx } = deps;
15281
- const facts = known ?? (await knownSessions(deps, [sessionId])).get(sessionId);
15282
- const session = ctx.sessions.get(toSessionId2(sessionId));
15776
+ const known = facts.known.get(sessionId);
15283
15777
  const agent = ctx.agents.get(toSessionId2(sessionId));
15284
- const archived = ctx.get("workspaceRegistry")?.archivedSessionIds.includes(toSessionId2(sessionId)) ?? false;
15285
- const workspace = workspaceOf(deps, sessionId);
15286
- const live = facts?.live ?? false;
15778
+ const workspace = facts.workspaces.get(sessionId);
15287
15779
  const boundary = agent === void 0 ? void 0 : ctx.agents.turnBoundaryOf(agent.session);
15288
15780
  const log = withLog ? await sessionLogFacts(deps, sessionId) : {};
15781
+ const lastTurn = log.lastTurn ?? boundary?.lastTurn;
15289
15782
  return {
15290
15783
  sessionId,
15291
- ...facts?.title === void 0 ? {} : { title: facts.title },
15784
+ ...known?.title === void 0 ? {} : { title: known.title },
15292
15785
  ...workspace === void 0 ? {} : { workspaceId: workspace.id, workspaceTitle: workspace.title },
15293
- ...facts?.header?.cwd === void 0 ? {} : { cwd: facts.header.cwd },
15294
- live,
15786
+ ...known?.header?.cwd === void 0 ? {} : { cwd: known.header.cwd },
15787
+ live: known?.live ?? false,
15295
15788
  running: agent?.status === "running",
15296
15789
  watched: deps.isWatched(sessionId),
15297
- archived,
15298
- ...boundary === void 0 ? {} : { lastTurn: boundary.lastTurn },
15790
+ archived: facts.archived.has(sessionId),
15791
+ ...lastTurn === void 0 ? {} : { lastTurn },
15299
15792
  ...agent === void 0 ? {} : { pendingInputs: agent.inbox.nextTurn.length + agent.inbox.nextStep.length },
15300
15793
  ...log,
15301
- ...log.lastTurn === void 0 && boundary !== void 0 ? { lastTurn: boundary.lastTurn } : {},
15302
- ...facts?.header?.createdAt === void 0 ? {} : { createdAt: facts.header.createdAt }
15794
+ ...known?.header?.createdAt === void 0 ? {} : { createdAt: known.header.createdAt }
15303
15795
  };
15304
15796
  }
15305
- function workspaceOf(deps, sessionId) {
15306
- const registry2 = deps.ctx.get("workspaceRegistry");
15307
- if (registry2 === void 0) return void 0;
15308
- for (const workspace of registry2.list()) {
15309
- if (workspace.sessionIds.includes(toSessionId2(sessionId))) return workspace;
15310
- }
15311
- return void 0;
15312
- }
15313
15797
  async function devLeadSessionView(deps, sessionId, withLog) {
15314
- return await buildSessionView(deps, sessionId, withLog);
15798
+ const facts = await readSessionFacts(deps, [sessionId]);
15799
+ return await buildSessionView(deps, sessionId, withLog, facts);
15315
15800
  }
15316
- async function devLeadSessionViews(deps, ids, withLog) {
15317
- const facts = await knownSessions(deps, ids);
15801
+ async function devLeadSessionViews(deps, ids, withLog, facts) {
15802
+ const batch = facts ?? await readSessionFacts(deps, ids);
15318
15803
  const views = [];
15319
15804
  for (const id of ids) {
15320
- views.push(await buildSessionView(deps, id, withLog, facts.get(id)));
15805
+ deps.signal?.throwIfAborted();
15806
+ views.push(await buildSessionView(deps, id, withLog, batch));
15321
15807
  }
15322
15808
  return views;
15323
15809
  }
15324
- async function resolveWorkspaceReference(ctx, reference) {
15810
+ async function resolveWorkspaceReference(ctx, reference, signal) {
15325
15811
  const registry2 = ctx.get("workspaceRegistry");
15326
15812
  if (registry2 === void 0) {
15327
15813
  throw new DevLeadError("this Host composes no Workspace registry", "DEVLEAD_WORKSPACE_NOT_FOUND");
@@ -15330,50 +15816,79 @@ async function resolveWorkspaceReference(ctx, reference) {
15330
15816
  const byId = registry2.list().find((workspace) => workspace.id === trimmed);
15331
15817
  if (byId !== void 0) return byId;
15332
15818
  try {
15819
+ signal?.throwIfAborted();
15333
15820
  const byPath = await registry2.resolveByPath(trimmed);
15334
15821
  if (byPath !== void 0) return byPath;
15335
- } catch {
15822
+ } catch (error51) {
15823
+ rethrowIfAborted(error51, signal);
15336
15824
  }
15825
+ signal?.throwIfAborted();
15337
15826
  throw new DevLeadError(
15338
15827
  `no Workspace matches "${reference}"; register the repository directory first with devlead_use_workspace`,
15339
15828
  "DEVLEAD_WORKSPACE_NOT_FOUND"
15340
15829
  );
15341
15830
  }
15831
+ async function resolveExactSession(deps, reference) {
15832
+ const { ctx } = deps;
15833
+ const sessionId = toSessionId2(reference);
15834
+ const live = ctx.agents.get(sessionId) !== void 0;
15835
+ if (deps.watchedSessions.includes(reference)) return { sessionId, live };
15836
+ const session = ctx.sessions.get(sessionId) ?? ctx.agents.get(sessionId)?.session;
15837
+ if (session !== void 0) {
15838
+ if (session.header.origin === "subagent") return void 0;
15839
+ return { sessionId, live };
15840
+ }
15841
+ const query = ctx.get("sessionQuery");
15842
+ if (query === void 0) return void 0;
15843
+ try {
15844
+ const observation = await query.readTitleSnapshot(sessionId, deps.signal);
15845
+ if (observation.session.origin === "subagent") return void 0;
15846
+ return { sessionId, live: false };
15847
+ } catch (error51) {
15848
+ rethrowIfAborted(error51, deps.signal);
15849
+ return void 0;
15850
+ }
15851
+ }
15342
15852
  async function resolveSessionReference(deps, reference) {
15343
15853
  const trimmed = reference.trim();
15344
15854
  if (trimmed.length === 0) throw new DevLeadError("a Session id is required", "DEVLEAD_INVALID_INPUT");
15345
- const candidates = await collectSessionIds(deps, void 0);
15346
- const exact = candidates.find((id) => id === trimmed);
15347
- let resolvedId = exact;
15855
+ const exact = await resolveExactSession(deps, trimmed);
15856
+ if (exact !== void 0) return exact;
15857
+ const candidates = await collectSessionIds(deps, void 0, true);
15858
+ const matched = candidates.filter((id) => id.startsWith(trimmed));
15859
+ const resolvedId = matched.find((id) => id === trimmed) ?? (matched.length === 1 ? matched[0] : void 0);
15860
+ if (resolvedId === void 0 && matched.length === 0) {
15861
+ throw new DevLeadError(
15862
+ `no Session matches "${reference}"; list the addressable Sessions with devlead_list_sessions`,
15863
+ "DEVLEAD_SESSION_NOT_FOUND"
15864
+ );
15865
+ }
15348
15866
  if (resolvedId === void 0) {
15349
- const matched = candidates.filter((id) => id.startsWith(trimmed));
15350
- if (matched.length === 0) {
15351
- throw new DevLeadError(`no Session matches "${reference}"`, "DEVLEAD_SESSION_NOT_FOUND");
15352
- }
15353
- if (matched.length > 1) {
15354
- throw new DevLeadError(
15355
- `Session prefix "${reference}" is ambiguous: ${matched.slice(0, 8).join(", ")}`,
15356
- "DEVLEAD_INVALID_INPUT"
15357
- );
15358
- }
15359
- resolvedId = matched[0];
15867
+ throw new DevLeadError(
15868
+ `Session prefix "${reference}" is ambiguous: ${matched.slice(0, 8).join(", ")}`,
15869
+ "DEVLEAD_INVALID_INPUT"
15870
+ );
15360
15871
  }
15361
15872
  const sessionId = toSessionId2(resolvedId);
15362
15873
  return { sessionId, live: deps.ctx.agents.get(sessionId) !== void 0 };
15363
15874
  }
15364
15875
 
15365
15876
  // packages/devlead/src/index.ts
15877
+ var MAX_TIMER_DELAY_MS = 2147483647;
15878
+ var MAX_COLD_LEAD_LOG_READS = 64;
15879
+ var REHYDRATION_READINESS_TIMEOUT_MS = 2e3;
15880
+ var REHYDRATION_READINESS_POLL_MS = 100;
15366
15881
  var Config = z2.object({
15367
- notificationBatchMs: z2.number().step(1).min(0).default(400),
15882
+ notificationBatchMs: z2.number().step(1).min(0).max(MAX_TIMER_DELAY_MS).default(400),
15368
15883
  maxWatchedSessions: z2.number().step(1).min(1).default(DEVLEAD_DEFAULT_MAX_WATCHED2),
15369
15884
  maxListedSessions: z2.number().step(1).min(1).default(200),
15370
- wakeColdSession: z2.boolean().default(false),
15885
+ wakeColdSession: z2.boolean().default(true),
15371
15886
  defaultAgentPreset: z2.string().default("")
15372
15887
  });
15373
15888
  function resolveConfig(config2) {
15374
15889
  const notificationBatchMs = config2.notificationBatchMs ?? 400;
15375
- if (!Number.isSafeInteger(notificationBatchMs) || notificationBatchMs < 0) {
15376
- throw new TypeError("notificationBatchMs must be a non-negative safe integer");
15890
+ if (!Number.isSafeInteger(notificationBatchMs) || notificationBatchMs < 0 || notificationBatchMs > MAX_TIMER_DELAY_MS) {
15891
+ throw new TypeError(`notificationBatchMs must be an integer between 0 and ${MAX_TIMER_DELAY_MS}`);
15377
15892
  }
15378
15893
  const maxWatchedSessions = config2.maxWatchedSessions ?? DEVLEAD_DEFAULT_MAX_WATCHED2;
15379
15894
  if (!Number.isSafeInteger(maxWatchedSessions) || maxWatchedSessions < 1) {
@@ -15383,7 +15898,7 @@ function resolveConfig(config2) {
15383
15898
  if (!Number.isSafeInteger(maxListedSessions) || maxListedSessions < 1) {
15384
15899
  throw new TypeError("maxListedSessions must be a positive safe integer");
15385
15900
  }
15386
- const wakeColdSession = config2.wakeColdSession ?? false;
15901
+ const wakeColdSession = config2.wakeColdSession ?? true;
15387
15902
  if (typeof wakeColdSession !== "boolean") throw new TypeError("wakeColdSession must be a boolean");
15388
15903
  const defaultAgentPreset = config2.defaultAgentPreset ?? "";
15389
15904
  if (typeof defaultAgentPreset !== "string") throw new TypeError("defaultAgentPreset must be a string");
@@ -15400,8 +15915,31 @@ function remoteCodeOf(error51) {
15400
15915
  const code = error51.code;
15401
15916
  return typeof code === "string" ? code : void 0;
15402
15917
  }
15403
- function renderThrown(error51) {
15404
- return error51 instanceof Error ? error51.message : String(error51);
15918
+ function listLimit(limit, maximum) {
15919
+ if (limit === void 0) return maximum;
15920
+ if (!Number.isSafeInteger(limit) || limit < 1) {
15921
+ throw new DevLeadError("limit must be a positive safe integer", "DEVLEAD_INVALID_INPUT");
15922
+ }
15923
+ return Math.min(limit, maximum);
15924
+ }
15925
+ function workspacePathFailure(error51, path) {
15926
+ const errno = error51?.code;
15927
+ if (errno === "ENOENT") {
15928
+ return new DevLeadError(
15929
+ `directory "${path}" does not exist; create it first or let this call create it`,
15930
+ "DEVLEAD_DIRECTORY_MISSING"
15931
+ );
15932
+ }
15933
+ if (error51 instanceof TypeError && /fully qualified/u.test(thrownMessage(error51))) {
15934
+ return new DevLeadError(
15935
+ `"${path}" is not a fully qualified path; pass an absolute directory path`,
15936
+ "DEVLEAD_INVALID_INPUT"
15937
+ );
15938
+ }
15939
+ return new DevLeadError(
15940
+ `could not register "${path}" as a Workspace: ${thrownMessage(error51)}`,
15941
+ "DEVLEAD_INVALID_INPUT"
15942
+ );
15405
15943
  }
15406
15944
  var DevLeadService = class extends Service {
15407
15945
  static inject = ["agents", "sessions", "sessionProjections"];
@@ -15413,6 +15951,28 @@ var DevLeadService = class extends Service {
15413
15951
  projectionHandle;
15414
15952
  /** Watched-session notification hub, started with the service. */
15415
15953
  hub;
15954
+ /**
15955
+ * Watch slots reserved by in-flight `createSession` calls, per lead Session
15956
+ * id. The pre-create capacity check alone is not atomic: two concurrent calls
15957
+ * can both pass it, then the second watch write fails after its Session was
15958
+ * already created. The reservation is counted by every capacity check and
15959
+ * released in a `finally`.
15960
+ */
15961
+ watchReservations = /* @__PURE__ */ new Map();
15962
+ /**
15963
+ * Whether the authoritative readiness scan of the durable lead records has
15964
+ * completed. A Host that never composes the optional Session persistence
15965
+ * service can never list a persisted corpus, so it never becomes `rehydrated`
15966
+ * and simply keeps serving live Sessions.
15967
+ */
15968
+ rehydrated = false;
15969
+ /** In-flight rehydration attempt, so concurrent readiness triggers share it. */
15970
+ rehydrating;
15971
+ /**
15972
+ * Disposers of the armed readiness retry: the optional-service injection fiber
15973
+ * and, while the query engine itself is missing, the lifecycle listeners.
15974
+ */
15975
+ rehydrationRetry;
15416
15976
  /**
15417
15977
  * @param ctx - owning cordis context.
15418
15978
  * @param config - deployment configuration for notification and listing limits.
@@ -15423,17 +15983,236 @@ var DevLeadService = class extends Service {
15423
15983
  }
15424
15984
  async [Service.init]() {
15425
15985
  this.projectionHandle = await this.ctx.sessionProjections.register(devLeadProjectionDefinition);
15986
+ await this.ctx.sessionProjections.register(devLeadModeProjectionDefinition);
15426
15987
  this.hub = new DevLeadNotificationHub(
15427
15988
  this.ctx,
15428
15989
  (session) => this.projectionHandle.stateOf(session),
15429
15990
  { batchMs: this.resolved.notificationBatchMs, wakeColdSession: this.resolved.wakeColdSession }
15430
15991
  );
15431
15992
  this.hub.start();
15993
+ this.ctx.effect(function* () {
15994
+ yield () => this.disposeRehydrationRetry();
15995
+ }.bind(this), "devlead: cold rehydration");
15996
+ await this.rehydrateFromPersistence();
15997
+ }
15998
+ /**
15999
+ * Rebuild the notification hub's watch index from durable state.
16000
+ *
16001
+ * The authoritative persisted-corpus scan never runs inline with the service
16002
+ * that requested it: the real Session query engine binds the optional
16003
+ * `sessionPersistence` service through its own scheduled `ctx.inject`
16004
+ * callback, so `ctx.get('sessionPersistence')` can already be defined while
16005
+ * `query.listSessions()` still silently returns live-only rows. Every
16006
+ * readiness scan therefore waits one task boundary and a bounded
16007
+ * corpus-readiness barrier (see {@link awaitCorpusReady}) before `rehydrated`
16008
+ * becomes final, so `[Service.init]` cannot resolve before the hub's watch
16009
+ * index was rebuilt.
16010
+ */
16011
+ async rehydrateFromPersistence() {
16012
+ if (this.rehydrated) return;
16013
+ const pending = this.rehydrating;
16014
+ if (pending !== void 0) {
16015
+ await pending;
16016
+ return;
16017
+ }
16018
+ const run = this.runRehydration();
16019
+ this.rehydrating = run;
16020
+ try {
16021
+ await run;
16022
+ } finally {
16023
+ this.rehydrating = void 0;
16024
+ }
16025
+ }
16026
+ /**
16027
+ * Run one rehydration attempt: the live-attach fallback immediately, a
16028
+ * boot-time corpus-readiness barrier, then one authoritative persisted scan.
16029
+ *
16030
+ * The barrier is the fix for the ready-vs-rehydration race: until the query
16031
+ * engine's own optional `sessionPersistence` binding is installed its listing
16032
+ * is live-only, so the scan must wait until every stored Session the
16033
+ * persistence service reports is visible in the query corpus. The wait is
16034
+ * bounded and only happens when the corpus is observably inconsistent; a
16035
+ * steady Host pays one macrotask plus one comparison.
16036
+ */
16037
+ async runRehydration() {
16038
+ if (this.rehydrated) return;
16039
+ const queryReady = this.ctx.get("sessionQuery") !== void 0;
16040
+ try {
16041
+ this.hub.rehydrate(this.liveAttachLeads());
16042
+ } catch (error51) {
16043
+ this.ctx.logger.warn(`devlead: cold lead rehydration failed: ${thrownMessage(error51)}`);
16044
+ }
16045
+ if (!queryReady) {
16046
+ this.armRehydrationRetry(false);
16047
+ return;
16048
+ }
16049
+ this.armRehydrationRetry(true);
16050
+ await new Promise((resolve) => {
16051
+ setTimeout(resolve, 0);
16052
+ });
16053
+ if (this.rehydrated) return;
16054
+ if (this.ctx.get("sessionQuery") === void 0) {
16055
+ this.armRehydrationRetry(false);
16056
+ return;
16057
+ }
16058
+ if (this.ctx.get("sessionPersistence") === void 0) {
16059
+ this.armRehydrationRetry(true);
16060
+ return;
16061
+ }
16062
+ await this.awaitCorpusReady();
16063
+ if (this.rehydrated) return;
16064
+ try {
16065
+ this.hub.rehydrate(await this.persistedLeadRecords(true));
16066
+ } catch (error51) {
16067
+ this.ctx.logger.warn(`devlead: cold lead rehydration failed: ${thrownMessage(error51)}`);
16068
+ }
16069
+ this.finalizeRehydration();
16070
+ }
16071
+ /**
16072
+ * Boot-time readiness barrier: wait (bounded) until the Session query corpus
16073
+ * lists every Session the optional persistence service reports as stored.
16074
+ *
16075
+ * The persistence listing is the ground truth: a fresh Host reports no stored
16076
+ * Sessions and proceeds immediately, a steady Host reports the same Sessions
16077
+ * the corpus lists, and only a corpus whose optional binding is still warming
16078
+ * up is observably inconsistent. The barrier is best-effort — after the bound
16079
+ * it warns once and lets the scan proceed.
16080
+ */
16081
+ async awaitCorpusReady() {
16082
+ const deadline = Date.now() + REHYDRATION_READINESS_TIMEOUT_MS;
16083
+ let probe = await persistedSessionsOf(this.ctx);
16084
+ while (probe.verifiable && probe.ids === void 0 && Date.now() < deadline) {
16085
+ await new Promise((resolve) => {
16086
+ setTimeout(resolve, REHYDRATION_READINESS_POLL_MS);
16087
+ });
16088
+ probe = await persistedSessionsOf(this.ctx);
16089
+ }
16090
+ const ids = probe.ids;
16091
+ if (ids === void 0) return;
16092
+ if (ids.size === 0) return;
16093
+ let consistent = false;
16094
+ while (Date.now() < deadline) {
16095
+ const listed = await this.listedPersistedSessionIds();
16096
+ if (this.containsAllSessionIds(listed, ids)) {
16097
+ consistent = true;
16098
+ break;
16099
+ }
16100
+ await new Promise((resolve) => {
16101
+ setTimeout(resolve, REHYDRATION_READINESS_POLL_MS);
16102
+ });
16103
+ }
16104
+ if (!consistent) {
16105
+ consistent = this.containsAllSessionIds(await this.listedPersistedSessionIds(), ids);
16106
+ }
16107
+ if (!consistent) {
16108
+ this.ctx.logger.warn(
16109
+ "devlead: the persisted Session corpus is still warming up; cold lead rehydration proceeds best-effort"
16110
+ );
16111
+ }
16112
+ }
16113
+ /**
16114
+ * Whether one corpus listing contains every expected Session id.
16115
+ * @param listed - ids visible in the query corpus.
16116
+ * @param expected - ids the persistence service reports as stored.
16117
+ * @returns whether every expected id is listed.
16118
+ */
16119
+ containsAllSessionIds(listed, expected) {
16120
+ for (const id of expected) {
16121
+ if (!listed.has(id)) return false;
16122
+ }
16123
+ return true;
16124
+ }
16125
+ /**
16126
+ * Read the ids of the persisted Sessions visible in the Session query corpus.
16127
+ *
16128
+ * Before its optional persistence binding is installed the query engine merges
16129
+ * only live Sessions, so this is the number the readiness barrier compares
16130
+ * against the persistence service's complete stored listing.
16131
+ * @returns the visible persisted Session ids.
16132
+ */
16133
+ async listedPersistedSessionIds() {
16134
+ const query = this.ctx.get("sessionQuery");
16135
+ if (query === void 0) return /* @__PURE__ */ new Set();
16136
+ try {
16137
+ const records = await query.listSessions();
16138
+ return new Set(
16139
+ records.filter((record2) => record2.persisted).map((record2) => String(record2.header.id))
16140
+ );
16141
+ } catch (error51) {
16142
+ this.ctx.logger.debug(`devlead: corpus readiness listing failed: ${thrownMessage(error51)}`);
16143
+ return /* @__PURE__ */ new Set();
16144
+ }
16145
+ }
16146
+ /**
16147
+ * Mark rehydration final and disarm the optional-service retry. The
16148
+ * authoritative scan runs after the readiness barrier, so it needs no
16149
+ * confirmation re-scan.
16150
+ */
16151
+ finalizeRehydration() {
16152
+ this.rehydrated = true;
16153
+ this.disposeRehydrationRetry();
16154
+ }
16155
+ /** Dispose every armed readiness-retry hook. */
16156
+ disposeRehydrationRetry() {
16157
+ const disposers = this.rehydrationRetry;
16158
+ if (disposers === void 0) return;
16159
+ this.rehydrationRetry = void 0;
16160
+ for (const dispose of disposers.splice(0)) dispose();
16161
+ }
16162
+ /**
16163
+ * Arm the readiness retry for a Host that composed the DevLead service before
16164
+ * its Session query engine or persistence binding.
16165
+ *
16166
+ * The persistence service is awaited through a one-shot optional-service fiber
16167
+ * (`ctx.inject`): it fires as soon as the real profile installs the service,
16168
+ * which happens during Host boot, well before the Web server accepts the first
16169
+ * prompt. Lifecycle listeners are only armed while the query engine itself is
16170
+ * missing — a Host without persistence can never list a persisted corpus, so
16171
+ * scanning on every event would be pointless work.
16172
+ * @param queryReady - whether `sessionQuery` was composed when the scan ran.
16173
+ */
16174
+ armRehydrationRetry(queryReady) {
16175
+ if (this.rehydrated || this.rehydrationRetry !== void 0) return;
16176
+ const disposers = [];
16177
+ const retry = () => {
16178
+ if (this.rehydrated) {
16179
+ this.disposeRehydrationRetry();
16180
+ return void 0;
16181
+ }
16182
+ if (this.ctx.get("sessionQuery") === void 0) return void 0;
16183
+ if (this.ctx.get("sessionPersistence") === void 0) return void 0;
16184
+ void this.rehydrateFromPersistence();
16185
+ return void 0;
16186
+ };
16187
+ const injection = this.ctx.inject(["sessionPersistence"], retry);
16188
+ disposers.push(() => injection.dispose());
16189
+ if (!queryReady) {
16190
+ disposers.push(this.ctx.on("agent/created", retry));
16191
+ disposers.push(this.ctx.on("session/event", retry));
16192
+ }
16193
+ this.rehydrationRetry = disposers;
16194
+ this.ctx.logger.debug(
16195
+ queryReady ? "devlead: the Session persistence binding is not ready yet; cold lead rehydration is retried when it is composed" : "devlead: the Session query engine is not composed yet; cold lead rehydration is retried on Session lifecycle events"
16196
+ );
15432
16197
  }
15433
16198
  /** Deployment configuration after validation; read-only. */
15434
16199
  get settings() {
15435
16200
  return this.resolved;
15436
16201
  }
16202
+ /**
16203
+ * Whether this Host currently composes a usable experimental Git worktree
16204
+ * service, so a `worktree` isolation request can be attempted.
16205
+ *
16206
+ * The check is structural and evaluated at call time, so a Host that loads or
16207
+ * unloads the capability while DevLead is running reports its current state.
16208
+ * DevLead itself never depends on the experimental package: without it, the
16209
+ * getter is simply `false` and `createSession` reports an `unavailable`
16210
+ * isolation outcome.
16211
+ * @returns whether Git worktree isolation is available.
16212
+ */
16213
+ get worktreeIsolationAvailable() {
16214
+ return worktreeCapabilityOf(this.ctx) !== void 0;
16215
+ }
15437
16216
  // ---------------------------------------------------------------------------
15438
16217
  // Mode
15439
16218
  // ---------------------------------------------------------------------------
@@ -15463,19 +16242,54 @@ var DevLeadService = class extends Service {
15463
16242
  * @param agent - exact live Session Agent receiving the selection.
15464
16243
  * @param enabled - selected mode.
15465
16244
  * @param signal - cancellation checked before the write.
15466
- * @returns fulfillment after the selection is durable.
16245
+ * @returns fulfillment after the committed selection's durability checkpoint
16246
+ * was attempted (a host without a persistence participant keeps it in memory).
15467
16247
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
15468
16248
  */
15469
16249
  async setEnabled(agent, enabled, signal) {
15470
16250
  this.assertLive(agent);
15471
16251
  signal?.throwIfAborted();
15472
- const current = this.strictStateOf(agent.session);
16252
+ const current = this.projectionHandle.stateOf(agent.session);
16253
+ if (current.failure !== null) {
16254
+ if (enabled) {
16255
+ throw new DevLeadError(
16256
+ `DevLead state for Session "${agent.id}" is damaged (${current.failure}); run /devlead reset first to discard the damaged watch set and notification digest`,
16257
+ "DEVLEAD_PROJECTION_INVALID"
16258
+ );
16259
+ }
16260
+ this.appendResetRecord(agent.session);
16261
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
16262
+ return;
16263
+ }
15473
16264
  if (current.enabled === enabled) return;
15474
16265
  appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
15475
- const flushed = await this.ctx.sessions.flush(agent.session);
15476
- if (!flushed) {
15477
- this.ctx.logger.warn(`devlead: DevLead mode for Session "${agent.id}" was not flushed to persistence`);
15478
- }
16266
+ await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
16267
+ }
16268
+ /**
16269
+ * Discard one Session's durable DevLead state so a damaged fold can recover.
16270
+ *
16271
+ * Appending the reset marker restarts both projections from their empty state
16272
+ * (mode off, empty watch set, no retained digest). The human-entry points own
16273
+ * this call: `/devlead reset` and `/devlead off` on a frozen Session. It does
16274
+ * not require the mode to be on, and it is safe to call repeatedly.
16275
+ * @param agent - exact live Session Agent owning the state.
16276
+ * @param signal - cancellation checked before the write.
16277
+ * @returns fulfillment after the reset record's durability checkpoint was
16278
+ * attempted.
16279
+ * @throws {@link DevLeadError} when the Agent is not live.
16280
+ */
16281
+ async reset(agent, signal) {
16282
+ this.assertLive(agent);
16283
+ signal?.throwIfAborted();
16284
+ this.appendResetRecord(agent.session);
16285
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
16286
+ }
16287
+ /**
16288
+ * Append one reset marker to a Session log.
16289
+ * @param session - Session whose DevLead state is discarded.
16290
+ */
16291
+ appendResetRecord(session) {
16292
+ appendPluginRecord2(session, DEVLEAD_RESET_RECORD_TYPE, resetRecord(Date.now()));
15479
16293
  }
15480
16294
  // ---------------------------------------------------------------------------
15481
16295
  // Workspaces
@@ -15496,44 +16310,62 @@ var DevLeadService = class extends Service {
15496
16310
  return views;
15497
16311
  }
15498
16312
  /**
15499
- * Register an existing directory as a Workspace, creating a missing
15500
- * directory first when allowed.
15501
- * @param path - fully qualified directory path.
15502
- * @param options - optional title and missing-directory policy (default creates).
16313
+ * Register an existing directory as a Workspace for one live lead.
16314
+ *
16315
+ * The Workspace registry itself canonicalizes the path (`fs.realpath`, so
16316
+ * trailing slashes and symlinks normalize), rejects relative spellings, and
16317
+ * requires an existing directory; this method only adds the optional
16318
+ * missing-directory creation and the stable DevLead error vocabulary.
16319
+ * An already-registered canonical path reuses its Workspace and keeps the
16320
+ * registered title: `request.title` applies only when a new record is created.
16321
+ *
16322
+ * Directory creation is opt-in: `request.create` defaults to `false`, so a
16323
+ * missing directory reports `DEVLEAD_DIRECTORY_MISSING` and the caller must
16324
+ * explicitly retry with `create: true`. Creating a Host directory is a
16325
+ * high-impact side effect, so the model must have asked for it.
16326
+ * @param agent - exact live lead Agent making the registration.
16327
+ * @param request - directory path, optional title (new registrations only),
16328
+ * and the missing-directory policy (default: never create).
16329
+ * @param signal - cancellation checked before and between the registry writes.
15503
16330
  * @returns the registered or existing Workspace view.
15504
- * @throws {@link DevLeadError} when the path is not usable.
16331
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_ENABLED`/`DEVLEAD_AGENT_NOT_LIVE`
16332
+ * for a disallowed caller, `DEVLEAD_DIRECTORY_MISSING` when the directory is
16333
+ * missing and creation is disabled, `DEVLEAD_INVALID_INPUT` for every other
16334
+ * unusable path or registration failure.
15505
16335
  */
15506
- async useWorkspace(path, options = {}) {
15507
- const trimmed = path.trim();
16336
+ async useWorkspace(agent, request, signal) {
16337
+ this.assertReady(agent);
16338
+ signal?.throwIfAborted();
16339
+ const trimmed = request.path.trim();
15508
16340
  if (trimmed.length === 0) throw new DevLeadError("a directory path is required", "DEVLEAD_INVALID_INPUT");
15509
- if (!isAbsolute(trimmed)) {
15510
- throw new DevLeadError(`"${trimmed}" is not a fully qualified path`, "DEVLEAD_INVALID_INPUT");
15511
- }
15512
- options.signal?.throwIfAborted();
15513
- const create = options.create ?? true;
15514
- const exists = await stat(trimmed).then(() => true, () => false);
15515
- if (!exists) {
16341
+ const create = request.create ?? false;
16342
+ const title = request.title?.trim();
16343
+ const resolvedTitle = title === void 0 || title.length === 0 ? void 0 : title;
16344
+ const registry2 = this.requireWorkspaceRegistry();
16345
+ let workspace;
16346
+ try {
16347
+ workspace = await registry2.create(trimmed, resolvedTitle);
16348
+ } catch (error51) {
16349
+ const failure = workspacePathFailure(error51, trimmed);
16350
+ if (failure.code !== "DEVLEAD_DIRECTORY_MISSING") throw failure;
15516
16351
  if (!create) {
15517
- throw new DevLeadError(`directory "${trimmed}" does not exist`, "DEVLEAD_DIRECTORY_MISSING");
15518
- }
15519
- try {
15520
- await mkdir(trimmed, { recursive: true });
15521
- } catch (error51) {
15522
16352
  throw new DevLeadError(
15523
- `could not create directory "${trimmed}": ${renderThrown(error51)}`,
16353
+ `directory "${trimmed}" does not exist; retry with create: true to create it, or create the directory first`,
15524
16354
  "DEVLEAD_DIRECTORY_MISSING"
15525
16355
  );
15526
16356
  }
15527
- }
15528
- const registry2 = this.requireWorkspaceRegistry();
15529
- let workspace;
15530
- try {
15531
- workspace = await registry2.create(trimmed, options.title);
15532
- } catch (error51) {
15533
- throw new DevLeadError(
15534
- `could not register "${trimmed}" as a Workspace: ${renderThrown(error51)}`,
15535
- "DEVLEAD_DIRECTORY_MISSING"
15536
- );
16357
+ signal?.throwIfAborted();
16358
+ try {
16359
+ await mkdir(trimmed, { recursive: true });
16360
+ } catch (mkdirError) {
16361
+ throw workspacePathFailure(mkdirError, trimmed);
16362
+ }
16363
+ signal?.throwIfAborted();
16364
+ try {
16365
+ workspace = await registry2.create(trimmed, resolvedTitle);
16366
+ } catch (retryError) {
16367
+ throw workspacePathFailure(retryError, trimmed);
16368
+ }
15537
16369
  }
15538
16370
  return await devLeadWorkspaceView(workspace);
15539
16371
  }
@@ -15542,55 +16374,89 @@ var DevLeadService = class extends Service {
15542
16374
  // ---------------------------------------------------------------------------
15543
16375
  /**
15544
16376
  * List Sessions this lead can address.
15545
- * @param options - optional Workspace filter, watch-only filter, and row limit.
15546
- * @param signal - cancellation checked between rows.
16377
+ *
16378
+ * Rows are ranked by cheap live facts (watched, running, then most recently
16379
+ * created) before the limit is applied, so a watched or running Session
16380
+ * always survives truncation; only retained rows pay for full view assembly.
16381
+ * @param agent - exact live lead Agent.
16382
+ * @param options - optional Workspace filter, watch-only filter, row limit
16383
+ * (capped by `maxListedSessions`, except that a watched-only listing is
16384
+ * never truncated below the watch set), and cancellation checked between
16385
+ * reads and rows. The watched set is already bounded by
16386
+ * `maxWatchedSessions`; the `/devlead` status view would otherwise report
16387
+ * truncated watch rows as missing.
15547
16388
  * @returns detached Session views, watched and running rows first.
16389
+ * @throws {@link DevLeadError} when the Agent is not live, the Workspace does
16390
+ * not resolve, the projection replay failed, or `limit` is not a positive
16391
+ * safe integer.
15548
16392
  */
15549
- async listSessions(agent, options = {}, signal) {
16393
+ async listSessions(agent, options = {}) {
15550
16394
  this.assertLive(agent);
15551
- const deps = this.viewDeps(agent);
16395
+ const signal = options.signal;
16396
+ const deps = this.viewDeps(agent, signal);
15552
16397
  signal?.throwIfAborted();
15553
16398
  let ids;
15554
16399
  if (options.workspace !== void 0 && options.workspace.trim().length > 0) {
15555
- const workspace = await resolveWorkspaceReference(this.ctx, options.workspace);
16400
+ const workspace = await resolveWorkspaceReference(this.ctx, options.workspace, signal);
15556
16401
  ids = await collectSessionIds(deps, workspace);
15557
16402
  } else {
15558
16403
  ids = await collectSessionIds(deps, void 0);
15559
16404
  }
16405
+ signal?.throwIfAborted();
15560
16406
  if (options.watchedOnly === true) ids = ids.filter((id) => deps.isWatched(id));
15561
- const limit = options.limit ?? this.resolved.maxListedSessions;
15562
- const views = await devLeadSessionViews(deps, ids, false);
15563
- views.sort((left, right) => {
15564
- if (left.watched !== right.watched) return left.watched ? -1 : 1;
15565
- if (left.running !== right.running) return left.running ? -1 : 1;
15566
- return (right.updatedAt ?? right.createdAt ?? 0) - (left.updatedAt ?? left.createdAt ?? 0) || left.sessionId.localeCompare(right.sessionId);
15567
- });
15568
- return views.slice(0, Math.max(1, limit));
16407
+ const listingCap = options.watchedOnly === true ? Math.max(this.resolved.maxListedSessions, deps.watchedSessions.length) : this.resolved.maxListedSessions;
16408
+ const requestedLimit = listLimit(options.limit, listingCap);
16409
+ const limit = options.watchedOnly === true ? Math.max(requestedLimit, deps.watchedSessions.length) : requestedLimit;
16410
+ const facts = await readSessionFacts(deps, ids);
16411
+ signal?.throwIfAborted();
16412
+ const retained = rankSessionIds(deps, ids, facts, limit);
16413
+ return await devLeadSessionViews(deps, retained, false, facts);
15569
16414
  }
15570
16415
  /**
15571
16416
  * Read one Session in detail, including folded turn and assistant facts.
15572
- * @param sessionId - Session id or unique prefix.
15573
- * @param signal - cancellation checked before the log read.
16417
+ * @param agent - exact live lead Agent.
16418
+ * @param sessionId - Session id or unique prefix; exact ids stay addressable
16419
+ * beyond the bounded listing window.
16420
+ * @param signal - cancellation checked before and between the query reads.
15574
16421
  * @returns the detached Session view.
15575
16422
  * @throws {@link DevLeadError} when the reference is missing or ambiguous.
15576
16423
  */
15577
16424
  async getSession(agent, sessionId, signal) {
15578
16425
  this.assertLive(agent);
15579
- const deps = this.viewDeps(agent);
16426
+ const deps = this.viewDeps(agent, signal);
15580
16427
  const resolved = await resolveSessionReference(deps, sessionId);
15581
16428
  signal?.throwIfAborted();
15582
16429
  return await devLeadSessionView(deps, String(resolved.sessionId), true);
15583
16430
  }
15584
16431
  /**
15585
16432
  * Create one ordinary Session in a Workspace and optionally prompt it.
16433
+ *
16434
+ * A requested `worktree` checkout isolation is applied best effort between
16435
+ * the watch update and the initial prompt: when the Host composes no
16436
+ * compatible Git worktree service, the new Session is not live, or creation
16437
+ * fails, the result reports an `unavailable`/`failed` isolation outcome and
16438
+ * the call still succeeds, with the Session working in the Workspace
16439
+ * checkout.
16440
+ *
16441
+ * Cancellation is cooperative: the signal is checked before each stage. A
16442
+ * cancellation that arrives after the Session was created cannot undo the
16443
+ * creation (or a title/watch mutation already applied); it only stops the
16444
+ * next side effect, so a cancelled create may leave a watched Session behind
16445
+ * without running isolation or admitting the prompt. Session creation itself
16446
+ * is not abortable once started.
15586
16447
  * @param agent - exact live lead Agent.
15587
- * @param request - Workspace, optional title, initial prompt, watch policy, and preset.
15588
- * @returns the created Session and the Workspace it joined.
16448
+ * @param request - Workspace, optional title, initial prompt, watch policy,
16449
+ * preset, and checkout isolation mode.
16450
+ * @param signal - cancellation checked between stages and threaded into the
16451
+ * worktree creation.
16452
+ * @returns the created Session, the Workspace it joined, and the
16453
+ * checkout-isolation outcome.
15589
16454
  * @throws {@link DevLeadError} when the mode is off, the Host cannot create
15590
16455
  * Sessions, or the destination is not usable.
15591
16456
  */
15592
- async createSession(agent, request) {
16457
+ async createSession(agent, request, signal) {
15593
16458
  this.assertReady(agent);
16459
+ signal?.throwIfAborted();
15594
16460
  const controller = this.ctx.get("sessionController");
15595
16461
  if (controller === void 0) {
15596
16462
  throw new DevLeadError(
@@ -15598,34 +16464,55 @@ var DevLeadService = class extends Service {
15598
16464
  "DEVLEAD_SESSION_UNAVAILABLE"
15599
16465
  );
15600
16466
  }
15601
- const workspace = await this.createTargetWorkspace(agent, request.workspace);
15602
- const preset = request.preset?.trim() ?? this.resolved.defaultAgentPreset;
15603
- let created;
15604
- try {
15605
- created = await controller.create({
15606
- workspaceId: workspace.id,
15607
- ...preset === void 0 || preset.length === 0 ? {} : { agentPreset: preset }
15608
- });
15609
- } catch (error51) {
15610
- throw this.sessionUnavailable(`could not create a Session in "${workspace.title}": ${renderThrown(error51)}`, error51);
15611
- }
15612
- const sessionId = String(created.sessionId);
15613
- if (request.title !== void 0 && request.title.trim().length > 0) {
15614
- this.tryRename(created.sessionId, request.title.trim());
15615
- }
15616
16467
  const watch = request.watch ?? true;
15617
- if (watch) await this.setWatching(agent, created.sessionId, true);
15618
- const prompt = request.prompt?.trim() ?? "";
15619
- const prompted = prompt.length > 0;
15620
- if (prompted) {
15621
- await this.admitPrompt(agent, created.sessionId, prompt, false);
16468
+ const releaseWatch = watch ? this.reserveWatchSlot(agent) : void 0;
16469
+ try {
16470
+ const workspace = await this.createTargetWorkspace(agent, request.workspace);
16471
+ signal?.throwIfAborted();
16472
+ if (await workspace.status() !== "ok") {
16473
+ throw new DevLeadError(
16474
+ `Workspace "${workspace.title}" (${workspace.path}) is no longer an available directory; restore it or register a different Workspace`,
16475
+ "DEVLEAD_DIRECTORY_MISSING"
16476
+ );
16477
+ }
16478
+ signal?.throwIfAborted();
16479
+ const preset = request.preset?.trim() ?? this.resolved.defaultAgentPreset;
16480
+ let created;
16481
+ try {
16482
+ created = await controller.create({
16483
+ workspaceId: workspace.id,
16484
+ ...preset === void 0 || preset.length === 0 ? {} : { agentPreset: preset }
16485
+ });
16486
+ } catch (error51) {
16487
+ throw this.sessionUnavailable(`could not create a Session in "${workspace.title}": ${thrownMessage(error51)}`, error51);
16488
+ }
16489
+ signal?.throwIfAborted();
16490
+ const sessionId = String(created.sessionId);
16491
+ if (request.title !== void 0 && request.title.trim().length > 0) {
16492
+ this.tryRename(created.sessionId, request.title.trim());
16493
+ }
16494
+ if (watch) {
16495
+ await this.setWatching(agent, created.sessionId, true, signal, true);
16496
+ releaseWatch?.();
16497
+ }
16498
+ signal?.throwIfAborted();
16499
+ const isolation = await this.isolateSession(created.sessionId, request.isolation ?? "none", signal);
16500
+ signal?.throwIfAborted();
16501
+ const prompt = request.prompt?.trim() ?? "";
16502
+ const prompted = prompt.length > 0;
16503
+ if (prompted) {
16504
+ await this.admitPrompt(agent, created.sessionId, prompt, false, signal);
16505
+ }
16506
+ const deps = this.viewDeps(agent, signal);
16507
+ return {
16508
+ session: await devLeadSessionView(deps, sessionId, true),
16509
+ workspace: await devLeadWorkspaceView(workspace),
16510
+ prompted,
16511
+ isolation
16512
+ };
16513
+ } finally {
16514
+ releaseWatch?.();
15622
16515
  }
15623
- const deps = this.viewDeps(agent);
15624
- return {
15625
- session: await devLeadSessionView(deps, sessionId, true),
15626
- workspace: await devLeadWorkspaceView(workspace),
15627
- prompted
15628
- };
15629
16516
  }
15630
16517
  /**
15631
16518
  * Admit one prompt into an existing Session, resuming a cold Session and
@@ -15633,16 +16520,20 @@ var DevLeadService = class extends Service {
15633
16520
  * @param agent - exact live lead Agent.
15634
16521
  * @param sessionId - Session id or unique prefix.
15635
16522
  * @param prompt - non-empty prompt text.
15636
- * @param options - optional watch policy (default watches).
16523
+ * @param options - optional watch policy (default watches) and cancellation
16524
+ * checked between stages.
15637
16525
  * @returns the admitted prompt receipt.
15638
16526
  * @throws {@link DevLeadError} when the Session is missing, archived, or cannot be resumed.
15639
16527
  */
15640
16528
  async promptSession(agent, sessionId, prompt, options = {}) {
15641
16529
  this.assertReady(agent);
16530
+ const signal = options.signal;
16531
+ signal?.throwIfAborted();
15642
16532
  const text = prompt.trim();
15643
16533
  if (text.length === 0) throw new DevLeadError("a non-empty prompt is required", "DEVLEAD_INVALID_INPUT");
15644
- const deps = this.viewDeps(agent);
16534
+ const deps = this.viewDeps(agent, signal);
15645
16535
  const resolved = await resolveSessionReference(deps, sessionId);
16536
+ signal?.throwIfAborted();
15646
16537
  if (String(resolved.sessionId) === String(agent.id)) {
15647
16538
  throw new DevLeadError(
15648
16539
  "a DevLead Session cannot prompt itself; end this turn and continue from a new human turn",
@@ -15650,9 +16541,31 @@ var DevLeadService = class extends Service {
15650
16541
  );
15651
16542
  }
15652
16543
  this.assertNotArchived(resolved.sessionId);
16544
+ if (!resolved.live && this.ctx.get("sessionController") === void 0) {
16545
+ throw new DevLeadError(
16546
+ `Session "${resolved.sessionId}" is not live and this Host composes no Session activator, so it cannot be prompted`,
16547
+ "DEVLEAD_SESSION_UNAVAILABLE"
16548
+ );
16549
+ }
15653
16550
  const watch = options.watch ?? true;
15654
- if (watch) await this.setWatching(agent, resolved.sessionId, true);
15655
- const resumed = await this.admitPrompt(agent, resolved.sessionId, text, true);
16551
+ const alreadyWatched = this.strictStateOf(agent.session).sessions.includes(String(resolved.sessionId));
16552
+ const added = watch && !alreadyWatched;
16553
+ if (added) await this.setWatching(agent, resolved.sessionId, true, signal);
16554
+ let resumed;
16555
+ try {
16556
+ resumed = await this.admitPrompt(agent, resolved.sessionId, text, true, signal);
16557
+ } catch (error51) {
16558
+ if (added) {
16559
+ try {
16560
+ await this.setWatching(agent, resolved.sessionId, false);
16561
+ } catch (compensateError) {
16562
+ this.ctx.logger.warn(
16563
+ `devlead: could not roll back the automatic watch for Session "${String(resolved.sessionId)}": ` + thrownMessage(compensateError)
16564
+ );
16565
+ }
16566
+ }
16567
+ throw error51;
16568
+ }
15656
16569
  return {
15657
16570
  sessionId: String(resolved.sessionId),
15658
16571
  watched: this.strictStateOf(agent.session).sessions.includes(String(resolved.sessionId)),
@@ -15664,23 +16577,27 @@ var DevLeadService = class extends Service {
15664
16577
  * @param agent - exact live lead Agent.
15665
16578
  * @param sessionId - Session id or unique prefix.
15666
16579
  * @param watching - whether the Session should be watched.
16580
+ * @param signal - cancellation checked before resolving and before the write.
15667
16581
  * @returns the resulting watch mutation.
15668
16582
  * @throws {@link DevLeadError} when the Session is missing, self-addressed, or over the limit.
15669
16583
  */
15670
- async watchSession(agent, sessionId, watching) {
16584
+ async watchSession(agent, sessionId, watching, signal) {
15671
16585
  this.assertReady(agent);
15672
- const deps = this.viewDeps(agent);
16586
+ signal?.throwIfAborted();
16587
+ const deps = this.viewDeps(agent, signal);
15673
16588
  const resolved = await resolveSessionReference(deps, sessionId);
16589
+ signal?.throwIfAborted();
15674
16590
  if (String(resolved.sessionId) === String(agent.id)) {
15675
16591
  throw new DevLeadError("a DevLead Session cannot watch itself", "DEVLEAD_SELF_WATCH");
15676
16592
  }
15677
- return await this.setWatching(agent, resolved.sessionId, watching);
16593
+ return await this.setWatching(agent, resolved.sessionId, watching, signal);
15678
16594
  }
15679
16595
  /**
15680
16596
  * Read the retained notification digest of one live lead Session.
15681
16597
  * @param agent - exact live lead Agent.
15682
- * @param options - maximum rows (newest last).
15683
- * @returns retained notifications, oldest first.
16598
+ * @param options - newest-row limit; omitted or not a positive safe integer
16599
+ * keeps the default of 20 rows.
16600
+ * @returns the newest retained notifications, oldest first.
15684
16601
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
15685
16602
  */
15686
16603
  notifications(agent, options = {}) {
@@ -15696,7 +16613,69 @@ var DevLeadService = class extends Service {
15696
16613
  /** Reject an Agent that is not this registry's exact live instance. */
15697
16614
  assertLive(agent) {
15698
16615
  if (this.ctx.agents.get(agent.id) !== agent) {
15699
- throw new DevLeadError(`agent "${agent.id}" is not live in this registry`, "DEVLEAD_AGENT_NOT_LIVE");
16616
+ throw new DevLeadError(
16617
+ `agent "${agent.id}" is not live in this registry; reopen its Session and retry`,
16618
+ "DEVLEAD_AGENT_NOT_LIVE"
16619
+ );
16620
+ }
16621
+ }
16622
+ /**
16623
+ * Check that one more watched Session fits under the configured cap, including
16624
+ * watch slots reserved by in-flight creates, before a write path creates side
16625
+ * effects it cannot roll back.
16626
+ * @param agent - exact live lead Agent.
16627
+ */
16628
+ assertWatchCapacity(agent) {
16629
+ const state = this.strictStateOf(agent.session);
16630
+ const reserved = this.watchReservations.get(String(agent.id)) ?? 0;
16631
+ if (state.sessions.length + reserved < this.resolved.maxWatchedSessions) return;
16632
+ throw new DevLeadError(
16633
+ `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
16634
+ "DEVLEAD_WATCH_LIMIT"
16635
+ );
16636
+ }
16637
+ /**
16638
+ * Claim one watch slot synchronously for an in-flight create call.
16639
+ * @param agent - exact live lead Agent.
16640
+ * @returns an idempotent release function for the caller's `finally`.
16641
+ * @throws {@link DevLeadError} `DEVLEAD_WATCH_LIMIT` when the current watch
16642
+ * set plus every other reservation is already at the cap.
16643
+ */
16644
+ reserveWatchSlot(agent) {
16645
+ const leadId = String(agent.id);
16646
+ const state = this.strictStateOf(agent.session);
16647
+ const reserved = this.watchReservations.get(leadId) ?? 0;
16648
+ if (state.sessions.length + reserved >= this.resolved.maxWatchedSessions) {
16649
+ throw new DevLeadError(
16650
+ `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
16651
+ "DEVLEAD_WATCH_LIMIT"
16652
+ );
16653
+ }
16654
+ this.watchReservations.set(leadId, reserved + 1);
16655
+ let released = false;
16656
+ return () => {
16657
+ if (released) return;
16658
+ released = true;
16659
+ const current = this.watchReservations.get(leadId) ?? 0;
16660
+ if (current <= 1) this.watchReservations.delete(leadId);
16661
+ else this.watchReservations.set(leadId, current - 1);
16662
+ };
16663
+ }
16664
+ /**
16665
+ * Flush one Session's durability checkpoint. `SessionStore.flush` returns
16666
+ * false when no durability participant is composed (a headless/SDK host that
16667
+ * keeps logs in memory) — that is not a failure, so it stays silent; only a
16668
+ * composed participant's own rejection is reported, and it is downgraded to a
16669
+ * warning because the append already committed to the live log and a later
16670
+ * checkpoint can still reach storage.
16671
+ * @param session - Session whose buffered events should be persisted.
16672
+ * @param what - operation name used in the warning text.
16673
+ */
16674
+ async flushDurably(session, what) {
16675
+ try {
16676
+ await this.ctx.sessions.flush(session);
16677
+ } catch (error51) {
16678
+ this.ctx.logger.warn(`devlead: ${what} could not be flushed to persistence: ${thrownMessage(error51)}`);
15700
16679
  }
15701
16680
  }
15702
16681
  /** Reject any use of a tool surface while DevLead mode is off. */
@@ -15715,6 +16694,123 @@ var DevLeadService = class extends Service {
15715
16694
  if (state.failure !== null) throw new DevLeadError(state.failure, "DEVLEAD_PROJECTION_INVALID");
15716
16695
  return state;
15717
16696
  }
16697
+ /**
16698
+ * Collect the attach-only leads of the current Session store: a live Session
16699
+ * whose log is attached but which has no Agent. Its projection can be folded
16700
+ * without any corpus I/O, so this fallback is available immediately even
16701
+ * before the persistence binding is ready.
16702
+ * @returns one persisted lead record per attach-only lead Session.
16703
+ */
16704
+ liveAttachLeads() {
16705
+ const leads = [];
16706
+ for (const session of this.ctx.sessions.list()) {
16707
+ if (this.ctx.agents.get(session.id) !== void 0) continue;
16708
+ if (session.header.origin === "subagent") continue;
16709
+ const state = this.projectionHandle.stateOf(session);
16710
+ if (state.failure !== null) continue;
16711
+ const sessionId = String(session.id);
16712
+ if (state.enabled && state.sessions.length > 0) leads.push({ sessionId, watched: [...state.sessions] });
16713
+ }
16714
+ return leads;
16715
+ }
16716
+ /**
16717
+ * Scan durable state for lead Sessions the hub must index after a restart.
16718
+ *
16719
+ * Only called with `scanPersisted: true` once both the Session query engine
16720
+ * and the optional Session persistence service are composed; otherwise only
16721
+ * the live-attach fallback runs.
16722
+ *
16723
+ * Cheap sources first: a live Session without an Agent has its projection
16724
+ * folded directly (attach-only leads), then the persisted corpus is filtered
16725
+ * through the projection cache — a row that positively reports an enabled mode
16726
+ * with a non-empty watch set is a candidate, a disabled/empty row is skipped
16727
+ * without reading its log, and only unclassified rows pay for a complete
16728
+ * full-log exact fold (bounded, because a Host history is unbounded).
16729
+ * A corrupt replay skips that candidate with one warning; it must never stop
16730
+ * the scan, and it must never make the plugin fail to load.
16731
+ * @returns one persisted lead record per recovered lead Session.
16732
+ */
16733
+ async persistedLeadRecords(scanPersisted) {
16734
+ const leads = /* @__PURE__ */ new Map();
16735
+ const remember = (sessionId, sessions) => {
16736
+ if (sessionId.length === 0 || sessions.length === 0) return;
16737
+ leads.set(sessionId, [...sessions]);
16738
+ };
16739
+ for (const lead of this.liveAttachLeads()) remember(lead.sessionId, lead.watched);
16740
+ if (!scanPersisted) {
16741
+ if (this.ctx.get("sessionQuery") === void 0) {
16742
+ this.ctx.logger.debug("devlead: no Session query engine is composed; cold lead rehydration scans live Sessions only");
16743
+ } else {
16744
+ this.ctx.logger.debug(
16745
+ "devlead: the Session persistence binding is not composed yet; cold lead rehydration scans live Sessions only"
16746
+ );
16747
+ }
16748
+ return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
16749
+ }
16750
+ const query = this.ctx.get("sessionQuery");
16751
+ if (query === void 0) return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
16752
+ const cache = projectionCacheOf(this.ctx);
16753
+ if (cache === void 0) {
16754
+ this.ctx.logger.warn(
16755
+ "devlead: this Host composes no Session projection cache, so cold lead rehydration reads no persisted logs; only live lead Sessions are rehydrated"
16756
+ );
16757
+ return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
16758
+ }
16759
+ let records;
16760
+ try {
16761
+ records = await query.listSessions();
16762
+ } catch (error51) {
16763
+ this.ctx.logger.warn(`devlead: could not list persisted Sessions for cold lead rehydration: ${thrownMessage(error51)}`);
16764
+ return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
16765
+ }
16766
+ let unknownReads = 0;
16767
+ let capped = false;
16768
+ let warnedCorrupt = false;
16769
+ let warnedRead = false;
16770
+ for (const record2 of records) {
16771
+ const sessionId = String(record2.header.id);
16772
+ if (leads.has(sessionId) || record2.live) continue;
16773
+ if (record2.header.origin === "subagent") continue;
16774
+ const prefilter = devLeadPrefilterOf(cache, record2.header);
16775
+ if (prefilter === "not-lead") continue;
16776
+ if (prefilter === "unknown") {
16777
+ if (unknownReads >= MAX_COLD_LEAD_LOG_READS) {
16778
+ capped = true;
16779
+ continue;
16780
+ }
16781
+ unknownReads += 1;
16782
+ }
16783
+ let events;
16784
+ try {
16785
+ events = (await query.readSession(record2.header.id)).events;
16786
+ } catch (error51) {
16787
+ if (!warnedRead) {
16788
+ warnedRead = true;
16789
+ this.ctx.logger.warn(`devlead: could not read a cold lead candidate Session log: ${thrownMessage(error51)}`);
16790
+ }
16791
+ continue;
16792
+ }
16793
+ let state = emptyDevLeadProjectionState();
16794
+ for (const event of events) {
16795
+ state = applyDevLeadProjection(state, event);
16796
+ if (state.failure !== null) break;
16797
+ }
16798
+ if (state.failure !== null) {
16799
+ if (!warnedCorrupt) {
16800
+ warnedCorrupt = true;
16801
+ this.ctx.logger.warn(`devlead: skipping a cold lead candidate with a corrupt DevLead replay: ${state.failure}`);
16802
+ }
16803
+ continue;
16804
+ }
16805
+ if (state.enabled) remember(sessionId, state.sessions);
16806
+ }
16807
+ if (capped) {
16808
+ this.ctx.logger.warn(
16809
+ `devlead: cold lead rehydration stopped reading unclassified Session logs after ${MAX_COLD_LEAD_LOG_READS}; compose projection cache rows to restore leads beyond that bound`
16810
+ );
16811
+ }
16812
+ return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
16813
+ }
15718
16814
  /** Require the Workspace registry capability. */
15719
16815
  requireWorkspaceRegistry() {
15720
16816
  const registry2 = this.ctx.get("workspaceRegistry");
@@ -15726,14 +16822,21 @@ var DevLeadService = class extends Service {
15726
16822
  }
15727
16823
  return registry2;
15728
16824
  }
15729
- /** Build the read-side dependency bundle for one live lead Agent. */
15730
- viewDeps(agent) {
16825
+ /**
16826
+ * Build the read-side dependency bundle for one live lead Agent.
16827
+ * @param agent - exact live lead Agent.
16828
+ * @param signal - optional cancellation threaded into every read.
16829
+ * @returns the view dependencies.
16830
+ */
16831
+ viewDeps(agent, signal) {
15731
16832
  const state = this.strictStateOf(agent.session);
16833
+ const watched = new Set(state.sessions);
15732
16834
  return {
15733
16835
  ctx: this.ctx,
15734
16836
  maxListedSessions: this.resolved.maxListedSessions,
15735
16837
  watchedSessions: state.sessions,
15736
- isWatched: (sessionId) => state.sessions.includes(sessionId)
16838
+ isWatched: (sessionId) => watched.has(sessionId),
16839
+ ...signal === void 0 ? {} : { signal }
15737
16840
  };
15738
16841
  }
15739
16842
  /**
@@ -15759,7 +16862,78 @@ var DevLeadService = class extends Service {
15759
16862
  if (byPath !== void 0) return byPath;
15760
16863
  const recorded = registry2.list().find((workspace) => workspace.path === cwd);
15761
16864
  if (recorded !== void 0) return recorded;
15762
- return await registry2.create(cwd);
16865
+ try {
16866
+ return await registry2.create(cwd);
16867
+ } catch (error51) {
16868
+ const failure = workspacePathFailure(error51, cwd);
16869
+ throw new DevLeadError(
16870
+ `the lead Session's working directory "${cwd}" is not usable: ${thrownMessage(error51)}; name a Workspace or path explicitly`,
16871
+ failure.code
16872
+ );
16873
+ }
16874
+ }
16875
+ /**
16876
+ * Attempt the checkout isolation requested for a freshly created Session.
16877
+ *
16878
+ * Isolation is best effort and never fails the creation call: a missing or
16879
+ * malformed capability, a Session that is not live, and a rejected creation
16880
+ * are all reported in the result, leaving the Session usable in its Workspace
16881
+ * checkout. Cancellation is the only throwing path, and it wins over a
16882
+ * reported failure so an aborted call is not misreported as a worktree
16883
+ * failure.
16884
+ * @param sessionId - freshly created Session identity.
16885
+ * @param mode - requested isolation mode; `none` never touches the capability.
16886
+ * @param signal - cancellation checked before the attempt and threaded into
16887
+ * the worktree creation.
16888
+ * @returns the isolation outcome.
16889
+ */
16890
+ async isolateSession(sessionId, mode, signal) {
16891
+ if (mode !== "worktree") return { requested: "none", status: "none" };
16892
+ signal?.throwIfAborted();
16893
+ const capability = worktreeCapabilityOf(this.ctx);
16894
+ if (capability === void 0) {
16895
+ return {
16896
+ requested: "worktree",
16897
+ status: "unavailable",
16898
+ reason: "this Host composes no Git worktree service, so the Session stays in its Workspace checkout"
16899
+ };
16900
+ }
16901
+ const child = this.ctx.agents.get(sessionId);
16902
+ if (child === void 0) {
16903
+ return {
16904
+ requested: "worktree",
16905
+ status: "unavailable",
16906
+ reason: `Session "${String(sessionId)}" is not live, so no worktree can be created for it`
16907
+ };
16908
+ }
16909
+ try {
16910
+ const created = await capability.create(child, {}, signal);
16911
+ signal?.throwIfAborted();
16912
+ const checkout = worktreeCheckoutOf(created);
16913
+ if (checkout === void 0) {
16914
+ this.ctx.logger.warn(
16915
+ `devlead: the Git worktree service returned an unusable checkout for Session "${String(sessionId)}"`
16916
+ );
16917
+ return {
16918
+ requested: "worktree",
16919
+ status: "failed",
16920
+ reason: "the Git worktree service returned an unusable checkout"
16921
+ };
16922
+ }
16923
+ return {
16924
+ requested: "worktree",
16925
+ status: "worktree",
16926
+ path: checkout.path,
16927
+ branch: checkout.branch,
16928
+ baseCommit: checkout.baseCommit
16929
+ };
16930
+ } catch (error51) {
16931
+ signal?.throwIfAborted();
16932
+ this.ctx.logger.warn(
16933
+ `devlead: could not create a Git worktree for Session "${String(sessionId)}": ${thrownMessage(error51)}`
16934
+ );
16935
+ return { requested: "worktree", status: "failed", reason: thrownMessage(error51) };
16936
+ }
15763
16937
  }
15764
16938
  /** Rename a freshly created Session, logging a failure instead of aborting creation. */
15765
16939
  tryRename(sessionId, title) {
@@ -15769,7 +16943,7 @@ var DevLeadService = class extends Service {
15769
16943
  try {
15770
16944
  titles.rename(session, title);
15771
16945
  } catch (error51) {
15772
- this.ctx.logger.warn(`devlead: Session "${sessionId}" was not renamed: ${renderThrown(error51)}`);
16946
+ this.ctx.logger.warn(`devlead: Session "${sessionId}" was not renamed: ${thrownMessage(error51)}`);
15773
16947
  }
15774
16948
  }
15775
16949
  /** Reject a Session the Workspace registry lists as archived. */
@@ -15794,9 +16968,11 @@ var DevLeadService = class extends Service {
15794
16968
  * @param sessionId - target Session identity.
15795
16969
  * @param text - non-empty prompt text.
15796
16970
  * @param allowResume - whether a cold Session may be resumed.
16971
+ * @param signal - cancellation checked before the resume and the admission.
15797
16972
  * @returns whether the Host resumed a cold Session.
15798
16973
  */
15799
- async admitPrompt(leadAgent, sessionId, text, allowResume) {
16974
+ async admitPrompt(leadAgent, sessionId, text, allowResume, signal) {
16975
+ signal?.throwIfAborted();
15800
16976
  let target = this.ctx.agents.get(sessionId);
15801
16977
  let resumed = false;
15802
16978
  if (target === void 0) {
@@ -15823,23 +16999,22 @@ var DevLeadService = class extends Service {
15823
16999
  } catch (error51) {
15824
17000
  if (error51 instanceof DevLeadError) throw error51;
15825
17001
  throw new DevLeadError(
15826
- `could not resume Session "${sessionId}": ${renderThrown(error51)}`,
17002
+ `could not resume Session "${sessionId}": ${thrownMessage(error51)}`,
15827
17003
  "DEVLEAD_SESSION_UNAVAILABLE"
15828
17004
  );
15829
17005
  }
17006
+ signal?.throwIfAborted();
15830
17007
  }
17008
+ signal?.throwIfAborted();
15831
17009
  try {
15832
17010
  target.followup(createDevLeadPromptMessage(text, leadAgent));
15833
17011
  } catch (error51) {
15834
17012
  throw new DevLeadError(
15835
- `could not admit a prompt into Session "${sessionId}": ${renderThrown(error51)}`,
17013
+ `could not admit a prompt into Session "${sessionId}": ${thrownMessage(error51)}`,
15836
17014
  "DEVLEAD_SESSION_UNAVAILABLE"
15837
17015
  );
15838
17016
  }
15839
- const flushed = await this.ctx.sessions.flush(target.session);
15840
- if (!flushed) {
15841
- this.ctx.logger.warn(`devlead: prompt into Session "${sessionId}" was not flushed to persistence`);
15842
- }
17017
+ await this.flushDurably(target.session, `prompt into Session "${sessionId}"`);
15843
17018
  return resumed;
15844
17019
  }
15845
17020
  /**
@@ -15847,9 +17022,13 @@ var DevLeadService = class extends Service {
15847
17022
  * @param agent - exact live lead Agent.
15848
17023
  * @param sessionId - target Session identity.
15849
17024
  * @param watching - whether to include the Session.
17025
+ * @param signal - cancellation checked before the write.
17026
+ * @param reservedSlot - the caller already holds a watch reservation for this
17027
+ * lead (the create path), so the capacity check must not count it again.
15850
17028
  * @returns the resulting watch mutation.
15851
17029
  */
15852
- async setWatching(agent, sessionId, watching) {
17030
+ async setWatching(agent, sessionId, watching, signal, reservedSlot = false) {
17031
+ signal?.throwIfAborted();
15853
17032
  const id = String(sessionId);
15854
17033
  if (id === String(agent.id)) {
15855
17034
  throw new DevLeadError("a DevLead Session cannot watch itself", "DEVLEAD_SELF_WATCH");
@@ -15859,18 +17038,10 @@ var DevLeadService = class extends Service {
15859
17038
  if (present === watching) {
15860
17039
  return { sessionId: id, watched: present, sessions: state.sessions };
15861
17040
  }
15862
- if (watching && state.sessions.length >= this.resolved.maxWatchedSessions) {
15863
- throw new DevLeadError(
15864
- `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
15865
- "DEVLEAD_WATCH_LIMIT"
15866
- );
15867
- }
17041
+ if (watching && !reservedSlot) this.assertWatchCapacity(agent);
15868
17042
  const next = watching ? [...state.sessions, id] : state.sessions.filter((existing) => existing !== id);
15869
17043
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
15870
- const flushed = await this.ctx.sessions.flush(agent.session);
15871
- if (!flushed) {
15872
- this.ctx.logger.warn(`devlead: watch set for lead "${agent.id}" was not flushed to persistence`);
15873
- }
17044
+ await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
15874
17045
  return { sessionId: id, watched: watching, sessions: next };
15875
17046
  }
15876
17047
  };
@@ -15880,26 +17051,36 @@ export {
15880
17051
  DEVLEAD_DEFAULT_MAX_WATCHED,
15881
17052
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
15882
17053
  DEVLEAD_ERROR_EXCERPT_MAX,
17054
+ DEVLEAD_MAX_INSTANT,
15883
17055
  DEVLEAD_MESSAGE_KIND,
15884
17056
  DEVLEAD_MODE_RECORD_TYPE,
15885
17057
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
15886
17058
  DEVLEAD_RECORD_VERSION,
17059
+ DEVLEAD_RESET_RECORD_TYPE,
15887
17060
  DEVLEAD_WATCH_RECORD_TYPE,
15888
17061
  DevLeadError,
15889
17062
  DevLeadService,
17063
+ applyDevLeadModeProjection,
15890
17064
  applyDevLeadProjection,
17065
+ assistantExcerpt,
15891
17066
  createDevLeadNoticeMessage,
15892
17067
  createDevLeadPromptMessage,
15893
17068
  decodeModeRecord,
15894
17069
  decodeNotification,
15895
17070
  decodeNotificationRecord,
17071
+ decodeResetRecord,
15896
17072
  decodeWatchRecord,
15897
17073
  index_default as default,
17074
+ devLeadModeProjectionDefinition,
17075
+ devLeadModeProjectionSchema,
17076
+ devLeadModeProjectionStateSchema,
17077
+ devLeadModeProjectionView,
15898
17078
  devLeadNotification,
15899
17079
  devLeadProjectionDefinition,
15900
17080
  devLeadProjectionSchema,
15901
17081
  devLeadProjectionStateSchema,
15902
17082
  devLeadProjectionView,
17083
+ emptyDevLeadModeProjectionState,
15903
17084
  emptyDevLeadProjectionState,
15904
17085
  failureExcerpt,
15905
17086
  isDevLeadError,
@@ -15907,5 +17088,7 @@ export {
15907
17088
  notificationId,
15908
17089
  notificationRecord,
15909
17090
  renderDevLeadNotice,
17091
+ representableInstant,
17092
+ resetRecord,
15910
17093
  watchRecord
15911
17094
  };