@yankeguo/dsh-devlead 0.1.1 → 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 +1050 -150
  3. package/package.json +4 -3
package/lib/index.js CHANGED
@@ -17,10 +17,12 @@ import { DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2 } from "@ya
17
17
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
18
18
  import {
19
19
  DEVLEAD_ERROR_EXCERPT_MAX,
20
+ DEVLEAD_MAX_INSTANT,
20
21
  DEVLEAD_MESSAGE_KIND,
21
22
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
22
23
  DEVLEAD_MODE_RECORD_TYPE,
23
24
  DEVLEAD_RECORD_VERSION,
25
+ DEVLEAD_RESET_RECORD_TYPE,
24
26
  DEVLEAD_WATCH_RECORD_TYPE,
25
27
  DEVLEAD_DEFAULT_MAX_WATCHED,
26
28
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
@@ -79,11 +81,15 @@ function watchRecord(sessions, at) {
79
81
  function notificationRecord(notification) {
80
82
  return { kind: "devlead/notification", version: DEVLEAD_RECORD_VERSION, notification };
81
83
  }
84
+ function resetRecord(at) {
85
+ return { kind: "devlead/reset", version: DEVLEAD_RECORD_VERSION, at };
86
+ }
82
87
  function devLeadNotification(sessionId, sessionTitle, transition, turn, at, error51, summary) {
88
+ const title = sessionTitle === void 0 ? void 0 : excerptLine(sessionTitle, DEVLEAD_ERROR_EXCERPT_MAX);
83
89
  return {
84
90
  id: notificationId(sessionId, turn, transition),
85
91
  sessionId,
86
- ...sessionTitle === void 0 ? {} : { sessionTitle },
92
+ ...title === void 0 ? {} : { sessionTitle: title },
87
93
  transition,
88
94
  turn,
89
95
  at,
@@ -91,9 +97,8 @@ function devLeadNotification(sessionId, sessionTitle, transition, turn, at, erro
91
97
  ...summary === void 0 ? {} : { summary }
92
98
  };
93
99
  }
94
- var MAX_INSTANT = 864e13;
95
100
  function representableInstant(at, fallback) {
96
- return Number.isSafeInteger(at) && at >= 0 && at <= MAX_INSTANT ? at : fallback;
101
+ return Number.isSafeInteger(at) && at >= 0 && at <= DEVLEAD_MAX_INSTANT ? at : fallback;
97
102
  }
98
103
  function expectRecord(value, type) {
99
104
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -119,7 +124,7 @@ function expectEnvelope(value, type, kind) {
119
124
  }
120
125
  }
121
126
  function decodeInstant(value, label) {
122
- if (!Number.isSafeInteger(value) || value < 0 || value > MAX_INSTANT) {
127
+ if (!Number.isSafeInteger(value) || value < 0 || value > DEVLEAD_MAX_INSTANT) {
123
128
  throw new Error(`${label} must be a non-negative integer instant in epoch milliseconds`);
124
129
  }
125
130
  return value;
@@ -130,6 +135,15 @@ function decodeTurn(value, label) {
130
135
  }
131
136
  return value;
132
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
+ }
133
147
  function decodeModeRecord(value) {
134
148
  const record2 = expectRecord(value, DEVLEAD_MODE_RECORD_TYPE);
135
149
  const label = "mode record";
@@ -175,30 +189,24 @@ function decodeNotification(value) {
175
189
  if (typeof record2.sessionId !== "string" || record2.sessionId.length === 0) {
176
190
  throw new Error(`${label} sessionId must be a non-empty string`);
177
191
  }
178
- if (record2.sessionTitle !== void 0 && (typeof record2.sessionTitle !== "string" || record2.sessionTitle.length === 0)) {
179
- throw new Error(`${label} sessionTitle must be a non-empty string when present`);
180
- }
192
+ const sessionTitle = record2.sessionTitle === void 0 ? void 0 : decodeExcerpt(record2.sessionTitle, `${label} sessionTitle`);
181
193
  if (!isDevLeadTransition(record2.transition)) {
182
194
  throw new Error(`${label} transition ${JSON.stringify(record2.transition)} is not recognized`);
183
195
  }
184
196
  const turn = decodeTurn(record2.turn, `${label} turn`);
185
- if (record2.error !== void 0 && (typeof record2.error !== "string" || record2.error.length === 0)) {
186
- throw new Error(`${label} error must be a non-empty string when present`);
187
- }
188
- if (record2.summary !== void 0 && (typeof record2.summary !== "string" || record2.summary.length === 0)) {
189
- throw new Error(`${label} summary must be a non-empty string when present`);
190
- }
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`);
191
199
  const id = notificationId(record2.sessionId, turn, record2.transition);
192
200
  if (record2.id !== id) throw new Error(`${label} id must be ${id}`);
193
201
  return {
194
202
  id,
195
203
  sessionId: record2.sessionId,
196
- ...record2.sessionTitle === void 0 ? {} : { sessionTitle: record2.sessionTitle },
204
+ ...sessionTitle === void 0 ? {} : { sessionTitle },
197
205
  transition: record2.transition,
198
206
  turn,
199
207
  at: decodeInstant(record2.at, `${label} at`),
200
- ...record2.error === void 0 ? {} : { error: record2.error },
201
- ...record2.summary === void 0 ? {} : { summary: record2.summary }
208
+ ...error51 === void 0 ? {} : { error: error51 },
209
+ ...summary === void 0 ? {} : { summary }
202
210
  };
203
211
  }
204
212
  function decodeNotificationRecord(value) {
@@ -208,6 +216,17 @@ function decodeNotificationRecord(value) {
208
216
  expectEnvelope(record2, DEVLEAD_NOTIFICATION_RECORD_TYPE, "devlead/notification");
209
217
  return decodeNotification(record2.notification);
210
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
+ }
211
230
  function failureExcerpt(error51) {
212
231
  return excerptLine(thrownMessage(error51), DEVLEAD_ERROR_EXCERPT_MAX);
213
232
  }
@@ -14736,32 +14755,43 @@ config(en_default());
14736
14755
  // packages/devlead/src/fold.ts
14737
14756
  import {
14738
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,
14739
14761
  DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE2,
14740
14762
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE2,
14741
14763
  DEVLEAD_PROJECTION_KEY,
14742
- 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
14743
14768
  } from "@yankeguo/dsh-devlead-protocol";
14744
14769
  function emptyDevLeadProjectionState() {
14745
14770
  return { enabled: false, sessions: [], notifications: [], failure: null };
14746
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
+ );
14747
14776
  var notificationSchema = external_exports.object({
14748
14777
  id: external_exports.string().min(1),
14749
14778
  sessionId: external_exports.string().min(1),
14750
- sessionTitle: external_exports.string().min(1).optional(),
14751
- transition: external_exports.enum([
14752
- "completed",
14753
- "aborted",
14754
- "blocked",
14755
- "error",
14756
- "max-tokens",
14757
- "interrupted",
14758
- "forked"
14759
- ]),
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]),
14760
14783
  turn: external_exports.number().int().positive(),
14761
- at: external_exports.number().int().nonnegative(),
14762
- error: external_exports.string().min(1).optional(),
14763
- summary: external_exports.string().min(1).optional()
14764
- }).strict();
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
+ );
14765
14795
  function retainNotification(notifications, notification) {
14766
14796
  if (notifications.some((existing) => existing.id === notification.id)) return notifications;
14767
14797
  const next = [...notifications, notification];
@@ -14772,14 +14802,23 @@ function sameSessionIds(left, right) {
14772
14802
  }
14773
14803
  var devLeadProjectionStateSchema = external_exports.object({
14774
14804
  enabled: external_exports.boolean(),
14775
- sessions: external_exports.array(external_exports.string().min(1)),
14776
- 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
+ ),
14777
14813
  failure: external_exports.string().min(1).nullable()
14778
14814
  }).strict();
14779
14815
  var devLeadProjectionSchema = external_exports.object({
14780
14816
  enabled: external_exports.boolean(),
14781
14817
  sessions: external_exports.array(external_exports.string().min(1)),
14782
- 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
+ )
14783
14822
  }).strict();
14784
14823
  var wireViews = /* @__PURE__ */ new WeakMap();
14785
14824
  function devLeadProjectionView(state) {
@@ -14794,9 +14833,18 @@ function devLeadProjectionView(state) {
14794
14833
  return view;
14795
14834
  }
14796
14835
  function applyDevLeadProjection(state, event) {
14797
- if (state.failure !== null) return state;
14798
14836
  const record2 = pluginRecordOf(event);
14799
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;
14800
14848
  try {
14801
14849
  switch (record2.type) {
14802
14850
  case DEVLEAD_MODE_RECORD_TYPE2: {
@@ -14816,15 +14864,18 @@ function applyDevLeadProjection(state, event) {
14816
14864
  return state;
14817
14865
  }
14818
14866
  } catch (error51) {
14819
- const message = error51 instanceof Error ? error51.message : String(error51);
14820
- const failure = {
14821
- ...state,
14822
- failure: `devlead replay failed at session event ${event.seq} (${record2.type}): ${message}`
14823
- };
14824
- wireViews.set(failure, devLeadProjectionView(state));
14825
- return failure;
14867
+ return freezeProjection(state, event, record2.type, error51);
14826
14868
  }
14827
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
+ }
14828
14879
  var devLeadProjectionDefinition = {
14829
14880
  key: DEVLEAD_PROJECTION_KEY,
14830
14881
  stateSchema: devLeadProjectionStateSchema,
@@ -14843,6 +14894,95 @@ var devLeadProjectionDefinition = {
14843
14894
  // notification records.
14844
14895
  stateVersion: 1
14845
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
+ }
14846
14986
 
14847
14987
  // packages/devlead/src/notification.ts
14848
14988
  import { appendPluginRecord, pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
@@ -14858,6 +14998,7 @@ import {
14858
14998
  } from "@yankeguo/dsh-devlead-protocol";
14859
14999
  var MAX_DIGEST_LINES = 12;
14860
15000
  var DELIVERY_RETRY_MS = 1e3;
15001
+ var DEVLEAD_MAX_WARNED_FAILURES = 256;
14861
15002
  function renderDevLeadNotice(notifications, total = notifications.length) {
14862
15003
  const shown = notifications.slice(-MAX_DIGEST_LINES);
14863
15004
  const omitted = total - shown.length;
@@ -14884,7 +15025,7 @@ var DevLeadNotificationHub = class {
14884
15025
  ctx;
14885
15026
  readState;
14886
15027
  config;
14887
- /** Live lead Sessions by identity. */
15028
+ /** Indexed lead Sessions by identity. */
14888
15029
  leads = /* @__PURE__ */ new Map();
14889
15030
  /** Watched Session identity → lead Session identities watching it. */
14890
15031
  watchers = /* @__PURE__ */ new Map();
@@ -14892,8 +15033,10 @@ var DevLeadNotificationHub = class {
14892
15033
  resuming = /* @__PURE__ */ new Set();
14893
15034
  /** Latest assistant excerpt observed per watched Session, bounded and pruned with the index. */
14894
15035
  lastAssistant = /* @__PURE__ */ new Map();
14895
- /** Sessions whose replay failure has already been reported, so a corrupt log warns once. */
15036
+ /** Sessions whose replay failure has already been reported, so a corrupt log warns once per Host process. */
14896
15037
  warnedFailures = /* @__PURE__ */ new Set();
15038
+ /** Leads whose persisted watch set named themselves; warn once per live indexing. */
15039
+ warnedSelfWatch = /* @__PURE__ */ new Set();
14897
15040
  started = false;
14898
15041
  stopping = false;
14899
15042
  /**
@@ -14909,13 +15052,11 @@ var DevLeadNotificationHub = class {
14909
15052
  this.syncLead(agent);
14910
15053
  return void 0;
14911
15054
  });
14912
- this.ctx.on("agent/disposed", ({ agent }) => {
14913
- this.removeLead(String(agent.id));
14914
- });
14915
15055
  this.ctx.on("agent/status", ({ agent, status }) => {
14916
15056
  if (status !== "idle") return;
14917
15057
  const runtime = this.leads.get(String(agent.id));
14918
- 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;
14919
15060
  void this.flush(runtime);
14920
15061
  });
14921
15062
  this.ctx.on("session/event", (session, event) => {
@@ -14928,6 +15069,25 @@ var DevLeadNotificationHub = class {
14928
15069
  };
14929
15070
  }.bind(this), "devlead: notification hub");
14930
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
+ }
14931
15091
  /**
14932
15092
  * Deliver any queued digest for one lead right now.
14933
15093
  * @param leadSessionId - lead Session identity.
@@ -14944,8 +15104,10 @@ var DevLeadNotificationHub = class {
14944
15104
  }
14945
15105
  /**
14946
15106
  * Read one Session's fold state, treating a replay failure as unavailable.
14947
- * A corrupt log is reported once per Session to keep a poisoned Session from
14948
- * flooding the log on every event.
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`).
14949
15111
  * @param session - live Session.
14950
15112
  * @returns the fold state, or undefined when the projection is invalid.
14951
15113
  */
@@ -14955,6 +15117,7 @@ var DevLeadNotificationHub = class {
14955
15117
  if (state.failure !== null) {
14956
15118
  if (!this.warnedFailures.has(sessionId)) {
14957
15119
  this.warnedFailures.add(sessionId);
15120
+ this.trimWarnedFailures();
14958
15121
  this.ctx.logger.warn(`devlead: ${state.failure}`);
14959
15122
  }
14960
15123
  return void 0;
@@ -14962,9 +15125,20 @@ var DevLeadNotificationHub = class {
14962
15125
  this.warnedFailures.delete(sessionId);
14963
15126
  return state;
14964
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
+ }
14965
15136
  /**
14966
15137
  * Reconcile one live lead Agent with its durable state: register, update the
14967
- * 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.
14968
15142
  * @param agent - live Agent that may lead.
14969
15143
  */
14970
15144
  syncLead(agent) {
@@ -14977,7 +15151,7 @@ var DevLeadNotificationHub = class {
14977
15151
  }
14978
15152
  const runtime = this.ensureLead(sessionId);
14979
15153
  this.setWatched(runtime, state.sessions);
14980
- if (runtime.pending.length > 0) this.scheduleFlush(runtime);
15154
+ if (runtime.pending.length > 0 || runtime.unsaved.length > 0) this.scheduleFlush(runtime);
14981
15155
  }
14982
15156
  /**
14983
15157
  * Create the runtime row for one lead Session.
@@ -14991,6 +15165,7 @@ var DevLeadNotificationHub = class {
14991
15165
  sessionId,
14992
15166
  watched: /* @__PURE__ */ new Set(),
14993
15167
  pending: [],
15168
+ unsaved: [],
14994
15169
  timer: void 0,
14995
15170
  scheduled: false,
14996
15171
  flushing: false
@@ -15000,11 +15175,23 @@ var DevLeadNotificationHub = class {
15000
15175
  }
15001
15176
  /**
15002
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.
15003
15184
  * @param runtime - lead runtime row.
15004
15185
  * @param sessions - complete durable watch set.
15005
15186
  */
15006
15187
  setWatched(runtime, sessions) {
15007
- 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);
15008
15195
  for (const watched of runtime.watched) {
15009
15196
  if (next.has(watched)) continue;
15010
15197
  const set2 = this.watchers.get(watched);
@@ -15026,10 +15213,15 @@ var DevLeadNotificationHub = class {
15026
15213
  }
15027
15214
  runtime.watched = next;
15028
15215
  runtime.pending = runtime.pending.filter((notification) => next.has(notification.sessionId));
15029
- 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);
15030
15218
  }
15031
15219
  /**
15032
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).
15033
15225
  * @param leadId - lead Session identity.
15034
15226
  */
15035
15227
  removeLead(leadId) {
@@ -15046,12 +15238,13 @@ var DevLeadNotificationHub = class {
15046
15238
  }
15047
15239
  }
15048
15240
  runtime.pending = [];
15241
+ runtime.unsaved = [];
15049
15242
  this.leads.delete(leadId);
15050
15243
  }
15051
15244
  this.resuming.delete(leadId);
15052
- this.warnedFailures.delete(leadId);
15245
+ this.warnedSelfWatch.delete(leadId);
15053
15246
  }
15054
- /** Clear one pending coalescing timer or queued zero-delay flush. */
15247
+ /** Clear one pending coalescing/retry timer or queued zero-delay flush. */
15055
15248
  clearTimer(runtime) {
15056
15249
  if (runtime.timer !== void 0) {
15057
15250
  clearTimeout(runtime.timer);
@@ -15069,7 +15262,7 @@ var DevLeadNotificationHub = class {
15069
15262
  if (this.stopping) return;
15070
15263
  const sessionId = String(session.id);
15071
15264
  const record2 = pluginRecordOf2(event);
15072
- 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)) {
15073
15266
  const agent = this.ctx.agents.get(session.id);
15074
15267
  if (agent !== void 0) this.syncLead(agent);
15075
15268
  }
@@ -15119,24 +15312,92 @@ var DevLeadNotificationHub = class {
15119
15312
  );
15120
15313
  }
15121
15314
  /**
15122
- * Persist one notification into a lead Session and queue its wake-up. A
15123
- * notification whose identity is already queued is not queued twice, so a
15124
- * replayed `turn/end` cannot double a digest line.
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.
15125
15323
  * @param leadId - lead Session identity.
15126
15324
  * @param notification - observed notification.
15127
15325
  */
15128
15326
  record(leadId, notification) {
15327
+ if (notification.sessionId === leadId) return;
15129
15328
  const runtime = this.leads.get(leadId);
15329
+ if (runtime === void 0) return;
15130
15330
  const session = this.ctx.sessions.get(toSessionId(leadId));
15131
- 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) {
15132
15352
  try {
15133
15353
  appendPluginRecord(session, DEVLEAD_NOTIFICATION_RECORD_TYPE3, notificationRecord(notification));
15134
15354
  } catch (error51) {
15135
15355
  this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${thrownMessage(error51)}`);
15356
+ return;
15136
15357
  }
15137
- if (runtime.pending.some((existing) => existing.id === notification.id)) return;
15138
- runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15139
- this.scheduleFlush(runtime);
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
+ );
15372
+ }
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);
15140
15401
  }
15141
15402
  /**
15142
15403
  * Arm the coalescing window for one lead.
@@ -15158,23 +15419,50 @@ var DevLeadNotificationHub = class {
15158
15419
  }, this.config.batchMs);
15159
15420
  }
15160
15421
  /**
15161
- * 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.
15162
15437
  * @param runtime - lead runtime row.
15163
15438
  * @returns fulfillment after the delivery attempt settles.
15164
15439
  */
15165
15440
  async flush(runtime) {
15166
15441
  if (this.stopping) return;
15167
15442
  if (this.leads.get(runtime.sessionId) !== runtime) return;
15168
- if (runtime.flushing || runtime.pending.length === 0) return;
15169
- const agent = this.ctx.agents.get(toSessionId(runtime.sessionId));
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);
15170
15458
  if (agent === void 0) {
15171
15459
  if (this.config.wakeColdSession) await this.resumeCold(runtime);
15172
15460
  return;
15173
15461
  }
15174
- const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(toSessionId(runtime.sessionId)) ?? false;
15175
- if (archived) {
15176
- runtime.pending = [];
15177
- this.clearTimer(runtime);
15462
+ this.persistUnsaved(agent.session, runtime);
15463
+ if (runtime.pending.length === 0) return;
15464
+ if (this.hasQueuedNotice(agent)) {
15465
+ this.scheduleRetry(runtime);
15178
15466
  return;
15179
15467
  }
15180
15468
  const batch = runtime.pending;
@@ -15183,13 +15471,11 @@ var DevLeadNotificationHub = class {
15183
15471
  runtime.flushing = true;
15184
15472
  let failed = false;
15185
15473
  try {
15186
- if (!this.hasQueuedNotice(agent)) {
15187
- agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
15188
- try {
15189
- await this.ctx.sessions.flush(agent.session);
15190
- } catch (error51) {
15191
- this.ctx.logger.warn(`devlead: notification digest could not be flushed for lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15192
- }
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)}`);
15193
15479
  }
15194
15480
  } catch (error51) {
15195
15481
  this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
@@ -15198,8 +15484,8 @@ var DevLeadNotificationHub = class {
15198
15484
  } finally {
15199
15485
  runtime.flushing = false;
15200
15486
  }
15201
- if (runtime.pending.length > 0 && this.leads.get(runtime.sessionId) === runtime) {
15202
- if (failed) {
15487
+ if ((runtime.pending.length > 0 || runtime.unsaved.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
15488
+ if (failed || runtime.unsaved.length > 0) {
15203
15489
  this.scheduleRetry(runtime);
15204
15490
  } else {
15205
15491
  this.scheduleFlush(runtime);
@@ -15207,7 +15493,8 @@ var DevLeadNotificationHub = class {
15207
15493
  }
15208
15494
  }
15209
15495
  /**
15210
- * Arm one bounded retry after a failed wake-up delivery.
15496
+ * Arm one bounded retry: a failed wake-up delivery, or a recheck of a batch
15497
+ * kept pending behind an undelivered inbox notice.
15211
15498
  * @param runtime - lead runtime row.
15212
15499
  */
15213
15500
  scheduleRetry(runtime) {
@@ -15258,6 +15545,61 @@ var DevLeadNotificationHub = class {
15258
15545
  }
15259
15546
  };
15260
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
+
15261
15603
  // packages/devlead/src/views.ts
15262
15604
  import { SessionId as toSessionId2 } from "@deepseek-ai/dsh-session";
15263
15605
  import { isDevLeadTransition as isDevLeadTransition3 } from "@yankeguo/dsh-devlead-protocol";
@@ -15417,7 +15759,7 @@ async function sessionLogFacts(deps, sessionId) {
15417
15759
  if (event.type === "turn/end") {
15418
15760
  const kind = event.data.reason.kind;
15419
15761
  lastTransition = isDevLeadTransition3(kind) ? kind : "interrupted";
15420
- lastError = kind === "error" ? event.data.reason.error.message : void 0;
15762
+ lastError = kind === "error" ? failureExcerpt(event.data.reason.error) : void 0;
15421
15763
  }
15422
15764
  }
15423
15765
  const lastAssistant = lastAssistantExcerpt(events);
@@ -15532,17 +15874,21 @@ async function resolveSessionReference(deps, reference) {
15532
15874
  }
15533
15875
 
15534
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;
15535
15881
  var Config = z2.object({
15536
- notificationBatchMs: z2.number().step(1).min(0).default(400),
15882
+ notificationBatchMs: z2.number().step(1).min(0).max(MAX_TIMER_DELAY_MS).default(400),
15537
15883
  maxWatchedSessions: z2.number().step(1).min(1).default(DEVLEAD_DEFAULT_MAX_WATCHED2),
15538
15884
  maxListedSessions: z2.number().step(1).min(1).default(200),
15539
- wakeColdSession: z2.boolean().default(false),
15885
+ wakeColdSession: z2.boolean().default(true),
15540
15886
  defaultAgentPreset: z2.string().default("")
15541
15887
  });
15542
15888
  function resolveConfig(config2) {
15543
15889
  const notificationBatchMs = config2.notificationBatchMs ?? 400;
15544
- if (!Number.isSafeInteger(notificationBatchMs) || notificationBatchMs < 0) {
15545
- 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}`);
15546
15892
  }
15547
15893
  const maxWatchedSessions = config2.maxWatchedSessions ?? DEVLEAD_DEFAULT_MAX_WATCHED2;
15548
15894
  if (!Number.isSafeInteger(maxWatchedSessions) || maxWatchedSessions < 1) {
@@ -15552,7 +15898,7 @@ function resolveConfig(config2) {
15552
15898
  if (!Number.isSafeInteger(maxListedSessions) || maxListedSessions < 1) {
15553
15899
  throw new TypeError("maxListedSessions must be a positive safe integer");
15554
15900
  }
15555
- const wakeColdSession = config2.wakeColdSession ?? false;
15901
+ const wakeColdSession = config2.wakeColdSession ?? true;
15556
15902
  if (typeof wakeColdSession !== "boolean") throw new TypeError("wakeColdSession must be a boolean");
15557
15903
  const defaultAgentPreset = config2.defaultAgentPreset ?? "";
15558
15904
  if (typeof defaultAgentPreset !== "string") throw new TypeError("defaultAgentPreset must be a string");
@@ -15605,6 +15951,28 @@ var DevLeadService = class extends Service {
15605
15951
  projectionHandle;
15606
15952
  /** Watched-session notification hub, started with the service. */
15607
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;
15608
15976
  /**
15609
15977
  * @param ctx - owning cordis context.
15610
15978
  * @param config - deployment configuration for notification and listing limits.
@@ -15615,17 +15983,236 @@ var DevLeadService = class extends Service {
15615
15983
  }
15616
15984
  async [Service.init]() {
15617
15985
  this.projectionHandle = await this.ctx.sessionProjections.register(devLeadProjectionDefinition);
15986
+ await this.ctx.sessionProjections.register(devLeadModeProjectionDefinition);
15618
15987
  this.hub = new DevLeadNotificationHub(
15619
15988
  this.ctx,
15620
15989
  (session) => this.projectionHandle.stateOf(session),
15621
15990
  { batchMs: this.resolved.notificationBatchMs, wakeColdSession: this.resolved.wakeColdSession }
15622
15991
  );
15623
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
+ );
15624
16197
  }
15625
16198
  /** Deployment configuration after validation; read-only. */
15626
16199
  get settings() {
15627
16200
  return this.resolved;
15628
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
+ }
15629
16216
  // ---------------------------------------------------------------------------
15630
16217
  // Mode
15631
16218
  // ---------------------------------------------------------------------------
@@ -15662,11 +16249,48 @@ var DevLeadService = class extends Service {
15662
16249
  async setEnabled(agent, enabled, signal) {
15663
16250
  this.assertLive(agent);
15664
16251
  signal?.throwIfAborted();
15665
- 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
+ }
15666
16264
  if (current.enabled === enabled) return;
15667
16265
  appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
15668
16266
  await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
15669
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()));
16293
+ }
15670
16294
  // ---------------------------------------------------------------------------
15671
16295
  // Workspaces
15672
16296
  // ---------------------------------------------------------------------------
@@ -15686,30 +16310,36 @@ var DevLeadService = class extends Service {
15686
16310
  return views;
15687
16311
  }
15688
16312
  /**
15689
- * Register an existing directory as a Workspace, creating a missing
15690
- * directory first when allowed.
16313
+ * Register an existing directory as a Workspace for one live lead.
15691
16314
  *
15692
16315
  * The Workspace registry itself canonicalizes the path (`fs.realpath`, so
15693
16316
  * trailing slashes and symlinks normalize), rejects relative spellings, and
15694
16317
  * requires an existing directory; this method only adds the optional
15695
16318
  * missing-directory creation and the stable DevLead error vocabulary.
15696
16319
  * An already-registered canonical path reuses its Workspace and keeps the
15697
- * registered title: `options.title` applies only when a new record is created.
15698
- * @param path - fully qualified directory path.
15699
- * @param options - optional title (new registrations only), missing-directory
15700
- * policy (default creates), and cancellation checked before the registry write.
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.
15701
16330
  * @returns the registered or existing Workspace view.
15702
- * @throws {@link DevLeadError} `DEVLEAD_DIRECTORY_MISSING` when the directory
15703
- * is missing and creation is disabled, `DEVLEAD_INVALID_INPUT` for every
15704
- * other unusable path or registration failure.
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.
15705
16335
  */
15706
- async useWorkspace(path, options = {}) {
15707
- const trimmed = path.trim();
15708
- if (trimmed.length === 0) throw new DevLeadError("a directory path is required", "DEVLEAD_INVALID_INPUT");
15709
- const signal = options.signal;
16336
+ async useWorkspace(agent, request, signal) {
16337
+ this.assertReady(agent);
15710
16338
  signal?.throwIfAborted();
15711
- const create = options.create ?? true;
15712
- const title = options.title?.trim();
16339
+ const trimmed = request.path.trim();
16340
+ if (trimmed.length === 0) throw new DevLeadError("a directory path is required", "DEVLEAD_INVALID_INPUT");
16341
+ const create = request.create ?? false;
16342
+ const title = request.title?.trim();
15713
16343
  const resolvedTitle = title === void 0 || title.length === 0 ? void 0 : title;
15714
16344
  const registry2 = this.requireWorkspaceRegistry();
15715
16345
  let workspace;
@@ -15720,7 +16350,7 @@ var DevLeadService = class extends Service {
15720
16350
  if (failure.code !== "DEVLEAD_DIRECTORY_MISSING") throw failure;
15721
16351
  if (!create) {
15722
16352
  throw new DevLeadError(
15723
- `directory "${trimmed}" does not exist; create it first or retry with create enabled`,
16353
+ `directory "${trimmed}" does not exist; retry with create: true to create it, or create the directory first`,
15724
16354
  "DEVLEAD_DIRECTORY_MISSING"
15725
16355
  );
15726
16356
  }
@@ -15750,10 +16380,11 @@ var DevLeadService = class extends Service {
15750
16380
  * always survives truncation; only retained rows pay for full view assembly.
15751
16381
  * @param agent - exact live lead Agent.
15752
16382
  * @param options - optional Workspace filter, watch-only filter, row limit
15753
- * (capped by `maxListedSessions`), and cancellation checked between reads
15754
- * and rows. A watched-only listing is never truncated below the watch set:
15755
- * that set is already bounded by `maxWatchedSessions`, and the `/devlead`
15756
- * status view would otherwise report truncated watch rows as missing.
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.
15757
16388
  * @returns detached Session views, watched and running rows first.
15758
16389
  * @throws {@link DevLeadError} when the Agent is not live, the Workspace does
15759
16390
  * not resolve, the projection replay failed, or `limit` is not a positive
@@ -15774,7 +16405,8 @@ var DevLeadService = class extends Service {
15774
16405
  signal?.throwIfAborted();
15775
16406
  if (options.watchedOnly === true) ids = ids.filter((id) => deps.isWatched(id));
15776
16407
  const listingCap = options.watchedOnly === true ? Math.max(this.resolved.maxListedSessions, deps.watchedSessions.length) : this.resolved.maxListedSessions;
15777
- const limit = listLimit(options.limit, listingCap);
16408
+ const requestedLimit = listLimit(options.limit, listingCap);
16409
+ const limit = options.watchedOnly === true ? Math.max(requestedLimit, deps.watchedSessions.length) : requestedLimit;
15778
16410
  const facts = await readSessionFacts(deps, ids);
15779
16411
  signal?.throwIfAborted();
15780
16412
  const retained = rankSessionIds(deps, ids, facts, limit);
@@ -15799,13 +16431,26 @@ var DevLeadService = class extends Service {
15799
16431
  /**
15800
16432
  * Create one ordinary Session in a Workspace and optionally prompt it.
15801
16433
  *
15802
- * Cancellation is cooperative: the signal is checked before each awaited
15803
- * stage, so a cancelled call stops before it watches or prompts the new
15804
- * Session. Session creation itself is not abortable once started.
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.
15805
16447
  * @param agent - exact live lead Agent.
15806
- * @param request - Workspace, optional title, initial prompt, watch policy, and preset.
15807
- * @param signal - cancellation checked between stages.
15808
- * @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.
15809
16454
  * @throws {@link DevLeadError} when the mode is off, the Host cannot create
15810
16455
  * Sessions, or the destination is not usable.
15811
16456
  */
@@ -15820,36 +16465,54 @@ var DevLeadService = class extends Service {
15820
16465
  );
15821
16466
  }
15822
16467
  const watch = request.watch ?? true;
15823
- if (watch) this.assertWatchCapacity(agent);
15824
- const workspace = await this.createTargetWorkspace(agent, request.workspace);
15825
- signal?.throwIfAborted();
15826
- const preset = request.preset?.trim() ?? this.resolved.defaultAgentPreset;
15827
- let created;
16468
+ const releaseWatch = watch ? this.reserveWatchSlot(agent) : void 0;
15828
16469
  try {
15829
- created = await controller.create({
15830
- workspaceId: workspace.id,
15831
- ...preset === void 0 || preset.length === 0 ? {} : { agentPreset: preset }
15832
- });
15833
- } catch (error51) {
15834
- throw this.sessionUnavailable(`could not create a Session in "${workspace.title}": ${thrownMessage(error51)}`, error51);
15835
- }
15836
- signal?.throwIfAborted();
15837
- const sessionId = String(created.sessionId);
15838
- if (request.title !== void 0 && request.title.trim().length > 0) {
15839
- this.tryRename(created.sessionId, request.title.trim());
15840
- }
15841
- if (watch) await this.setWatching(agent, created.sessionId, true, signal);
15842
- const prompt = request.prompt?.trim() ?? "";
15843
- const prompted = prompt.length > 0;
15844
- if (prompted) {
15845
- await this.admitPrompt(agent, created.sessionId, prompt, false, signal);
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?.();
15846
16515
  }
15847
- const deps = this.viewDeps(agent, signal);
15848
- return {
15849
- session: await devLeadSessionView(deps, sessionId, true),
15850
- workspace: await devLeadWorkspaceView(workspace),
15851
- prompted
15852
- };
15853
16516
  }
15854
16517
  /**
15855
16518
  * Admit one prompt into an existing Session, resuming a cold Session and
@@ -15885,8 +16548,24 @@ var DevLeadService = class extends Service {
15885
16548
  );
15886
16549
  }
15887
16550
  const watch = options.watch ?? true;
15888
- if (watch) await this.setWatching(agent, resolved.sessionId, true, signal);
15889
- const resumed = await this.admitPrompt(agent, resolved.sessionId, text, true, signal);
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
+ }
15890
16569
  return {
15891
16570
  sessionId: String(resolved.sessionId),
15892
16571
  watched: this.strictStateOf(agent.session).sessions.includes(String(resolved.sessionId)),
@@ -15941,18 +16620,47 @@ var DevLeadService = class extends Service {
15941
16620
  }
15942
16621
  }
15943
16622
  /**
15944
- * Check that one more watched Session fits under the configured cap, before a
15945
- * write path creates side effects it cannot roll back.
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.
15946
16626
  * @param agent - exact live lead Agent.
15947
16627
  */
15948
16628
  assertWatchCapacity(agent) {
15949
16629
  const state = this.strictStateOf(agent.session);
15950
- if (state.sessions.length < this.resolved.maxWatchedSessions) return;
16630
+ const reserved = this.watchReservations.get(String(agent.id)) ?? 0;
16631
+ if (state.sessions.length + reserved < this.resolved.maxWatchedSessions) return;
15951
16632
  throw new DevLeadError(
15952
16633
  `watch limit reached (${this.resolved.maxWatchedSessions}); unwatch a Session before adding another`,
15953
16634
  "DEVLEAD_WATCH_LIMIT"
15954
16635
  );
15955
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
+ }
15956
16664
  /**
15957
16665
  * Flush one Session's durability checkpoint. `SessionStore.flush` returns
15958
16666
  * false when no durability participant is composed (a headless/SDK host that
@@ -15986,6 +16694,123 @@ var DevLeadService = class extends Service {
15986
16694
  if (state.failure !== null) throw new DevLeadError(state.failure, "DEVLEAD_PROJECTION_INVALID");
15987
16695
  return state;
15988
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
+ }
15989
16814
  /** Require the Workspace registry capability. */
15990
16815
  requireWorkspaceRegistry() {
15991
16816
  const registry2 = this.ctx.get("workspaceRegistry");
@@ -16047,6 +16872,69 @@ var DevLeadService = class extends Service {
16047
16872
  );
16048
16873
  }
16049
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
+ }
16937
+ }
16050
16938
  /** Rename a freshly created Session, logging a failure instead of aborting creation. */
16051
16939
  tryRename(sessionId, title) {
16052
16940
  const titles = this.ctx.get("sessionTitle");
@@ -16135,9 +17023,11 @@ var DevLeadService = class extends Service {
16135
17023
  * @param sessionId - target Session identity.
16136
17024
  * @param watching - whether to include the Session.
16137
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.
16138
17028
  * @returns the resulting watch mutation.
16139
17029
  */
16140
- async setWatching(agent, sessionId, watching, signal) {
17030
+ async setWatching(agent, sessionId, watching, signal, reservedSlot = false) {
16141
17031
  signal?.throwIfAborted();
16142
17032
  const id = String(sessionId);
16143
17033
  if (id === String(agent.id)) {
@@ -16148,7 +17038,7 @@ var DevLeadService = class extends Service {
16148
17038
  if (present === watching) {
16149
17039
  return { sessionId: id, watched: present, sessions: state.sessions };
16150
17040
  }
16151
- if (watching) this.assertWatchCapacity(agent);
17041
+ if (watching && !reservedSlot) this.assertWatchCapacity(agent);
16152
17042
  const next = watching ? [...state.sessions, id] : state.sessions.filter((existing) => existing !== id);
16153
17043
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
16154
17044
  await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
@@ -16161,13 +17051,16 @@ export {
16161
17051
  DEVLEAD_DEFAULT_MAX_WATCHED,
16162
17052
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
16163
17053
  DEVLEAD_ERROR_EXCERPT_MAX,
17054
+ DEVLEAD_MAX_INSTANT,
16164
17055
  DEVLEAD_MESSAGE_KIND,
16165
17056
  DEVLEAD_MODE_RECORD_TYPE,
16166
17057
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
16167
17058
  DEVLEAD_RECORD_VERSION,
17059
+ DEVLEAD_RESET_RECORD_TYPE,
16168
17060
  DEVLEAD_WATCH_RECORD_TYPE,
16169
17061
  DevLeadError,
16170
17062
  DevLeadService,
17063
+ applyDevLeadModeProjection,
16171
17064
  applyDevLeadProjection,
16172
17065
  assistantExcerpt,
16173
17066
  createDevLeadNoticeMessage,
@@ -16175,13 +17068,19 @@ export {
16175
17068
  decodeModeRecord,
16176
17069
  decodeNotification,
16177
17070
  decodeNotificationRecord,
17071
+ decodeResetRecord,
16178
17072
  decodeWatchRecord,
16179
17073
  index_default as default,
17074
+ devLeadModeProjectionDefinition,
17075
+ devLeadModeProjectionSchema,
17076
+ devLeadModeProjectionStateSchema,
17077
+ devLeadModeProjectionView,
16180
17078
  devLeadNotification,
16181
17079
  devLeadProjectionDefinition,
16182
17080
  devLeadProjectionSchema,
16183
17081
  devLeadProjectionStateSchema,
16184
17082
  devLeadProjectionView,
17083
+ emptyDevLeadModeProjectionState,
16185
17084
  emptyDevLeadProjectionState,
16186
17085
  failureExcerpt,
16187
17086
  isDevLeadError,
@@ -16190,5 +17089,6 @@ export {
16190
17089
  notificationRecord,
16191
17090
  renderDevLeadNotice,
16192
17091
  representableInstant,
17092
+ resetRecord,
16193
17093
  watchRecord
16194
17094
  };