@yankeguo/dsh-devlead 0.2.3 → 0.2.5

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 +33 -6
  2. package/lib/index.js +1651 -101
  3. package/package.json +11 -11
package/lib/index.js CHANGED
@@ -11,8 +11,14 @@ import { Service } from "@deepseek-ai/cordis";
11
11
  import z2 from "@deepseek-ai/schemastery";
12
12
  import { ReasoningEffortId } from "@deepseek-ai/dsh-llm";
13
13
  import { appendPluginRecord as appendPluginRecord2 } from "@deepseek-ai/dsh-session";
14
- import "@deepseek-ai/dsh-session";
15
- import { DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2 } from "@yankeguo/dsh-devlead-protocol";
14
+ import { SessionId as toSessionId3 } from "@deepseek-ai/dsh-session";
15
+ import {
16
+ DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2,
17
+ DEVLEAD_REPORT_MAX_PER_TURN,
18
+ DEVLEAD_REPORT_MESSAGE_MAX as DEVLEAD_REPORT_MESSAGE_MAX4,
19
+ DEVLEAD_REPORT_SUMMARY_MAX as DEVLEAD_REPORT_SUMMARY_MAX4,
20
+ isDevLeadReportKind as isDevLeadReportKind2
21
+ } from "@yankeguo/dsh-devlead-protocol";
16
22
 
17
23
  // packages/devlead/src/domain.ts
18
24
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
@@ -23,11 +29,16 @@ import {
23
29
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
24
30
  DEVLEAD_MODE_RECORD_TYPE,
25
31
  DEVLEAD_RECORD_VERSION,
32
+ DEVLEAD_REPORT_MESSAGE_MAX,
33
+ DEVLEAD_REPORT_RECORD_TYPE,
34
+ DEVLEAD_REPORT_SUMMARY_MAX,
26
35
  DEVLEAD_RESET_RECORD_TYPE,
27
36
  DEVLEAD_WATCH_RECORD_TYPE,
28
37
  DEVLEAD_DEFAULT_MAX_WATCHED,
29
38
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
39
+ devLeadReportId,
30
40
  excerptLine,
41
+ isDevLeadReportKind,
31
42
  isDevLeadTransition,
32
43
  notificationId
33
44
  } from "@yankeguo/dsh-devlead-protocol";
@@ -98,6 +109,28 @@ function devLeadNotification(sessionId, sessionTitle, transition, turn, at, erro
98
109
  ...summary === void 0 ? {} : { summary }
99
110
  };
100
111
  }
112
+ function devLeadReport(input) {
113
+ const message = input.message.trim();
114
+ const title = input.senderSessionTitle === void 0 ? void 0 : excerptLine(input.senderSessionTitle, DEVLEAD_ERROR_EXCERPT_MAX);
115
+ const summary = input.summary === void 0 ? void 0 : excerptLine(input.summary, DEVLEAD_REPORT_SUMMARY_MAX);
116
+ const workspaceTitle = input.senderWorkspaceTitle === void 0 ? void 0 : excerptLine(input.senderWorkspaceTitle, DEVLEAD_ERROR_EXCERPT_MAX);
117
+ return {
118
+ id: devLeadReportId(input.senderSessionId, input.turn, input.kind, message),
119
+ kind: input.kind,
120
+ message,
121
+ ...summary === void 0 ? {} : { summary },
122
+ senderSessionId: input.senderSessionId,
123
+ ...title === void 0 ? {} : { senderSessionTitle: title },
124
+ ...input.senderWorkspaceId === void 0 ? {} : { senderWorkspaceId: input.senderWorkspaceId },
125
+ ...workspaceTitle === void 0 ? {} : { senderWorkspaceTitle: workspaceTitle },
126
+ leadSessionId: input.leadSessionId,
127
+ turn: Number.isSafeInteger(input.turn) && input.turn >= 0 ? input.turn : 0,
128
+ at: representableInstant(input.at, Date.now())
129
+ };
130
+ }
131
+ function reportRecord(report) {
132
+ return { kind: "devlead/report", version: DEVLEAD_RECORD_VERSION, report };
133
+ }
101
134
  function representableInstant(at, fallback) {
102
135
  return Number.isSafeInteger(at) && at >= 0 && at <= DEVLEAD_MAX_INSTANT ? at : fallback;
103
136
  }
@@ -145,6 +178,15 @@ function decodeExcerpt(value, label) {
145
178
  }
146
179
  return value;
147
180
  }
181
+ function decodeExcerptWithMax(value, label, max) {
182
+ if (typeof value !== "string" || value.length === 0) {
183
+ throw new Error(`${label} must be a non-empty string when present`);
184
+ }
185
+ if (value.length > max * 2 || Array.from(value).length > max) {
186
+ throw new Error(`${label} must be at most ${max} code points`);
187
+ }
188
+ return value;
189
+ }
148
190
  function decodeModeRecord(value) {
149
191
  const record2 = expectRecord(value, DEVLEAD_MODE_RECORD_TYPE);
150
192
  const label = "mode record";
@@ -176,6 +218,71 @@ function decodeWatchRecord(value) {
176
218
  at: decodeInstant(record2.at, `${label} at`)
177
219
  };
178
220
  }
221
+ function decodeReport(value) {
222
+ const record2 = expectRecord(value, DEVLEAD_REPORT_RECORD_TYPE);
223
+ const label = "report";
224
+ expectFields(record2, label, [
225
+ "id",
226
+ "kind",
227
+ "message",
228
+ "senderSessionId",
229
+ "leadSessionId",
230
+ "turn",
231
+ "at"
232
+ ], [
233
+ "summary",
234
+ "senderSessionTitle",
235
+ "senderWorkspaceId",
236
+ "senderWorkspaceTitle"
237
+ ]);
238
+ if (typeof record2.id !== "string" || record2.id.length === 0) {
239
+ throw new Error(`${label} id must be a non-empty string`);
240
+ }
241
+ if (!isDevLeadReportKind(record2.kind)) {
242
+ throw new Error(`${label} kind ${JSON.stringify(record2.kind)} is not recognized`);
243
+ }
244
+ if (typeof record2.message !== "string" || record2.message.trim().length === 0) {
245
+ throw new Error(`${label} message must be a non-empty string`);
246
+ }
247
+ if (Array.from(record2.message).length > DEVLEAD_REPORT_MESSAGE_MAX) {
248
+ throw new Error(`${label} message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX} code points`);
249
+ }
250
+ if (typeof record2.senderSessionId !== "string" || record2.senderSessionId.length === 0) {
251
+ throw new Error(`${label} senderSessionId must be a non-empty string`);
252
+ }
253
+ if (typeof record2.leadSessionId !== "string" || record2.leadSessionId.length === 0) {
254
+ throw new Error(`${label} leadSessionId must be a non-empty string`);
255
+ }
256
+ const turn = typeof record2.turn === "number" && Number.isSafeInteger(record2.turn) && record2.turn >= 0 ? record2.turn : (() => {
257
+ throw new Error(`${label} turn must be a non-negative safe integer`);
258
+ })();
259
+ const summary = record2.summary === void 0 ? void 0 : decodeExcerptWithMax(record2.summary, `${label} summary`, DEVLEAD_REPORT_SUMMARY_MAX);
260
+ const senderSessionTitle = record2.senderSessionTitle === void 0 ? void 0 : decodeExcerpt(record2.senderSessionTitle, `${label} senderSessionTitle`);
261
+ const senderWorkspaceId = record2.senderWorkspaceId === void 0 ? void 0 : decodeExcerpt(record2.senderWorkspaceId, `${label} senderWorkspaceId`);
262
+ const senderWorkspaceTitle = record2.senderWorkspaceTitle === void 0 ? void 0 : decodeExcerpt(record2.senderWorkspaceTitle, `${label} senderWorkspaceTitle`);
263
+ const id = devLeadReportId(record2.senderSessionId, turn, record2.kind, record2.message);
264
+ if (record2.id !== id) throw new Error(`${label} id must be ${id}`);
265
+ return {
266
+ id,
267
+ kind: record2.kind,
268
+ message: record2.message,
269
+ ...summary === void 0 ? {} : { summary },
270
+ senderSessionId: record2.senderSessionId,
271
+ ...senderSessionTitle === void 0 ? {} : { senderSessionTitle },
272
+ ...senderWorkspaceId === void 0 ? {} : { senderWorkspaceId },
273
+ ...senderWorkspaceTitle === void 0 ? {} : { senderWorkspaceTitle },
274
+ leadSessionId: record2.leadSessionId,
275
+ turn,
276
+ at: decodeInstant(record2.at, `${label} at`)
277
+ };
278
+ }
279
+ function decodeReportRecord(value) {
280
+ const record2 = expectRecord(value, DEVLEAD_REPORT_RECORD_TYPE);
281
+ const label = "report record";
282
+ expectFields(record2, label, ["kind", "version", "report"]);
283
+ expectEnvelope(record2, DEVLEAD_REPORT_RECORD_TYPE, "devlead/report");
284
+ return decodeReport(record2.report);
285
+ }
179
286
  function decodeNotification(value) {
180
287
  const record2 = expectRecord(value, DEVLEAD_NOTIFICATION_RECORD_TYPE);
181
288
  const label = "notification";
@@ -368,9 +475,6 @@ function agentTeamsCapabilityOf(ctx) {
368
475
  return candidate;
369
476
  }
370
477
 
371
- // packages/devlead/src/fold.ts
372
- import { pluginRecordOf } from "@deepseek-ai/dsh-session";
373
-
374
478
  // node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
375
479
  var external_exports = {};
376
480
  __export(external_exports, {
@@ -14885,22 +14989,262 @@ function date4(params) {
14885
14989
  // node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
14886
14990
  config(en_default());
14887
14991
 
14992
+ // packages/devlead/src/outbox.ts
14993
+ import {
14994
+ DEVLEAD_MAX_INSTANT as DEVLEAD_MAX_INSTANT2,
14995
+ DEVLEAD_REPORT_KINDS,
14996
+ DEVLEAD_REPORT_MESSAGE_MAX as DEVLEAD_REPORT_MESSAGE_MAX2,
14997
+ DEVLEAD_REPORT_SUMMARY_MAX as DEVLEAD_REPORT_SUMMARY_MAX2,
14998
+ devLeadReportId as devLeadReportId2
14999
+ } from "@yankeguo/dsh-devlead-protocol";
15000
+ var OUTBOX_DOMAIN = "devlead_report_outbox";
15001
+ var OUTBOX_TABLE = "pending";
15002
+ var IGNORED_TABLE = "ignored";
15003
+ var DEVLEAD_REPORT_OUTBOX_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
15004
+ var reportSchema = external_exports.object({
15005
+ id: external_exports.string().min(1),
15006
+ kind: external_exports.enum([...DEVLEAD_REPORT_KINDS]),
15007
+ message: external_exports.string().min(1).refine(
15008
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_MESSAGE_MAX2,
15009
+ { message: `report message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX2} code points` }
15010
+ ),
15011
+ summary: external_exports.string().min(1).refine(
15012
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_SUMMARY_MAX2,
15013
+ { message: `report summary must be at most ${DEVLEAD_REPORT_SUMMARY_MAX2} code points` }
15014
+ ).optional(),
15015
+ senderSessionId: external_exports.string().min(1),
15016
+ senderSessionTitle: external_exports.string().min(1).optional(),
15017
+ senderWorkspaceId: external_exports.string().min(1).optional(),
15018
+ senderWorkspaceTitle: external_exports.string().min(1).optional(),
15019
+ leadSessionId: external_exports.string().min(1),
15020
+ turn: external_exports.number().int().nonnegative(),
15021
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2)
15022
+ }).strict().refine(
15023
+ (report) => report.id === devLeadReportId2(report.senderSessionId, report.turn, report.kind, report.message),
15024
+ { message: "report id must match senderSessionId, turn, kind, and message" }
15025
+ );
15026
+ var outboxSchema = external_exports.object({
15027
+ report: reportSchema,
15028
+ enqueuedAt: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2)
15029
+ }).strict();
15030
+ var ignoredSchema = external_exports.object({
15031
+ sessionId: external_exports.string().min(1),
15032
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2)
15033
+ }).strict();
15034
+ var OUTBOX_SPEC = {
15035
+ name: OUTBOX_DOMAIN,
15036
+ version: 1,
15037
+ layout: "per-record",
15038
+ invalidRecords: "backup-and-skip",
15039
+ tables: {
15040
+ pending: { valueSchema: outboxSchema },
15041
+ ignored: { valueSchema: ignoredSchema }
15042
+ }
15043
+ };
15044
+ function devLeadOutboxKey(report) {
15045
+ return Buffer.from(`${report.leadSessionId}\0${report.id}`, "utf8").toString("base64url");
15046
+ }
15047
+ function sessionKey(sessionId) {
15048
+ return Buffer.from(sessionId, "utf8").toString("base64url");
15049
+ }
15050
+ var DevLeadReportOutbox = class _DevLeadReportOutbox {
15051
+ constructor(ctx, domain2) {
15052
+ this.ctx = ctx;
15053
+ this.domain = domain2;
15054
+ }
15055
+ ctx;
15056
+ domain;
15057
+ /** Whether the domain was opened and remains available. */
15058
+ get available() {
15059
+ return !this.closed;
15060
+ }
15061
+ closed = false;
15062
+ /** Last outbox write/open failure, for diagnostics and receipts. */
15063
+ lastError;
15064
+ /**
15065
+ * Open the outbox domain when the Host composes storage-domain.
15066
+ * @param ctx - Host context carrying the optional service.
15067
+ * @returns the outbox, or undefined when storage is unavailable.
15068
+ */
15069
+ static async open(ctx) {
15070
+ const getter = ctx;
15071
+ const facility = getter.get("storageDomain");
15072
+ if (facility === void 0) return void 0;
15073
+ try {
15074
+ const domain2 = await facility.open(OUTBOX_SPEC);
15075
+ return new _DevLeadReportOutbox(ctx, domain2);
15076
+ } catch (error51) {
15077
+ ctx.logger.warn(`devlead: durable report outbox unavailable: ${error51 instanceof Error ? error51.message : String(error51)}`);
15078
+ return void 0;
15079
+ }
15080
+ }
15081
+ /**
15082
+ * Persist one report before the child receives a success receipt.
15083
+ * @param report - report to enqueue.
15084
+ * @returns whether the row is durable.
15085
+ */
15086
+ async put(report) {
15087
+ if (this.closed) return false;
15088
+ const key = devLeadOutboxKey(report);
15089
+ try {
15090
+ const table = this.domain.table(OUTBOX_TABLE);
15091
+ const existing = table.get(key);
15092
+ await table.put(key, {
15093
+ report,
15094
+ enqueuedAt: existing?.enqueuedAt ?? Date.now()
15095
+ });
15096
+ this.lastError = void 0;
15097
+ return true;
15098
+ } catch (error51) {
15099
+ this.lastError = error51 instanceof Error ? error51.message : String(error51);
15100
+ this.ctx.logger.warn(`devlead: could not durably enqueue report "${report.id}": ${this.lastError}`);
15101
+ return false;
15102
+ }
15103
+ }
15104
+ /**
15105
+ * Remove one delivered outbox row.
15106
+ * @param reportId - report identity.
15107
+ * @returns whether the row is gone (or was already absent).
15108
+ */
15109
+ async delete(report) {
15110
+ if (this.closed) return false;
15111
+ try {
15112
+ await this.domain.table(OUTBOX_TABLE).delete(devLeadOutboxKey(report));
15113
+ return true;
15114
+ } catch (error51) {
15115
+ this.ctx.logger.warn(`devlead: could not remove delivered report "${report.id}" from the outbox: ${error51 instanceof Error ? error51.message : String(error51)}`);
15116
+ return false;
15117
+ }
15118
+ }
15119
+ /**
15120
+ * Snapshot all undelivered rows.
15121
+ * @returns rows in storage iteration order.
15122
+ */
15123
+ entries() {
15124
+ if (this.closed) return [];
15125
+ try {
15126
+ return [...this.domain.table(OUTBOX_TABLE).entries()].map(([, value]) => value);
15127
+ } catch (error51) {
15128
+ this.ctx.logger.warn(`devlead: could not read the durable report outbox: ${error51 instanceof Error ? error51.message : String(error51)}`);
15129
+ return [];
15130
+ }
15131
+ }
15132
+ /**
15133
+ * Delete undelivered rows older than the retention horizon.
15134
+ * @param now - current epoch milliseconds.
15135
+ * @param retentionMs - maximum age, defaulting to the outbox retention.
15136
+ * @returns number of removed rows.
15137
+ */
15138
+ async prune(now = Date.now(), retentionMs = DEVLEAD_REPORT_OUTBOX_RETENTION_MS) {
15139
+ const cutoff = now - retentionMs;
15140
+ const stale = this.entries().filter((entry) => entry.enqueuedAt < cutoff);
15141
+ if (stale.length === 0) return 0;
15142
+ try {
15143
+ const removed = await this.domain.table(OUTBOX_TABLE).deleteMany(stale.map((entry) => devLeadOutboxKey(entry.report)));
15144
+ if (removed > 0) {
15145
+ this.ctx.logger.warn(
15146
+ `devlead: discarded ${String(removed)} undelivered report(s) older than the ${String(retentionMs)} ms outbox retention`
15147
+ );
15148
+ }
15149
+ return removed;
15150
+ } catch (error51) {
15151
+ this.ctx.logger.warn(`devlead: could not prune the durable report outbox: ${error51 instanceof Error ? error51.message : String(error51)}`);
15152
+ return 0;
15153
+ }
15154
+ }
15155
+ /**
15156
+ * Drop every report queued for one lead, used by `/devlead reset`.
15157
+ * @param leadSessionId - lead identity.
15158
+ * @returns number of removed rows.
15159
+ */
15160
+ async dropForLead(leadSessionId) {
15161
+ const keys = this.entries().filter((entry) => entry.report.leadSessionId === leadSessionId).map((entry) => devLeadOutboxKey(entry.report));
15162
+ if (keys.length === 0) return 0;
15163
+ try {
15164
+ return await this.domain.table(OUTBOX_TABLE).deleteMany(keys);
15165
+ } catch (error51) {
15166
+ this.ctx.logger.warn(`devlead: could not drop outbox reports for lead "${leadSessionId}": ${error51 instanceof Error ? error51.message : String(error51)}`);
15167
+ return 0;
15168
+ }
15169
+ }
15170
+ /**
15171
+ * Persist one archived-holder tombstone.
15172
+ * @param sessionId - ignored Session identity.
15173
+ * @returns whether the tombstone is durable.
15174
+ */
15175
+ async rememberIgnored(sessionId) {
15176
+ if (this.closed) return false;
15177
+ try {
15178
+ await this.domain.table(IGNORED_TABLE).put(sessionKey(sessionId), {
15179
+ sessionId,
15180
+ at: Date.now()
15181
+ });
15182
+ return true;
15183
+ } catch (error51) {
15184
+ this.ctx.logger.warn(`devlead: could not persist archived-holder tombstone "${sessionId}": ${error51 instanceof Error ? error51.message : String(error51)}`);
15185
+ return false;
15186
+ }
15187
+ }
15188
+ /**
15189
+ * Remove one archived-holder tombstone after a successful release.
15190
+ * @param sessionId - Session identity.
15191
+ */
15192
+ async forgetIgnored(sessionId) {
15193
+ if (this.closed) return;
15194
+ try {
15195
+ await this.domain.table(IGNORED_TABLE).delete(sessionKey(sessionId));
15196
+ } catch (error51) {
15197
+ this.ctx.logger.warn(`devlead: could not clear archived-holder tombstone "${sessionId}": ${error51 instanceof Error ? error51.message : String(error51)}`);
15198
+ }
15199
+ }
15200
+ /**
15201
+ * Read every archived-holder tombstone.
15202
+ * @returns Session identities.
15203
+ */
15204
+ ignoredIds() {
15205
+ if (this.closed) return [];
15206
+ try {
15207
+ return [...this.domain.table(IGNORED_TABLE).entries()].map(([, value]) => value.sessionId);
15208
+ } catch (error51) {
15209
+ this.ctx.logger.warn(`devlead: could not read archived-holder tombstones: ${error51 instanceof Error ? error51.message : String(error51)}`);
15210
+ return [];
15211
+ }
15212
+ }
15213
+ /** Close the domain handle. */
15214
+ async close() {
15215
+ if (this.closed) return;
15216
+ this.closed = true;
15217
+ try {
15218
+ await this.domain.close();
15219
+ } catch (error51) {
15220
+ this.ctx.logger.warn(`devlead: could not close the durable report outbox: ${error51 instanceof Error ? error51.message : String(error51)}`);
15221
+ }
15222
+ }
15223
+ };
15224
+
14888
15225
  // packages/devlead/src/fold.ts
15226
+ import { pluginRecordOf } from "@deepseek-ai/dsh-session";
14889
15227
  import {
14890
15228
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2,
14891
15229
  DEVLEAD_ERROR_EXCERPT_MAX as DEVLEAD_ERROR_EXCERPT_MAX2,
14892
- DEVLEAD_MAX_INSTANT as DEVLEAD_MAX_INSTANT2,
15230
+ DEVLEAD_MAX_INSTANT as DEVLEAD_MAX_INSTANT3,
14893
15231
  DEVLEAD_MODE_PROJECTION_KEY,
14894
15232
  DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE2,
14895
15233
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE2,
14896
15234
  DEVLEAD_PROJECTION_KEY,
15235
+ DEVLEAD_REPORT_KINDS as DEVLEAD_REPORT_KINDS2,
15236
+ DEVLEAD_REPORT_MESSAGE_MAX as DEVLEAD_REPORT_MESSAGE_MAX3,
15237
+ DEVLEAD_REPORT_RECORD_TYPE as DEVLEAD_REPORT_RECORD_TYPE2,
15238
+ DEVLEAD_REPORT_RETENTION,
15239
+ DEVLEAD_REPORT_SUMMARY_MAX as DEVLEAD_REPORT_SUMMARY_MAX3,
14897
15240
  DEVLEAD_RESET_RECORD_TYPE as DEVLEAD_RESET_RECORD_TYPE2,
14898
15241
  DEVLEAD_TRANSITIONS,
14899
15242
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE2,
15243
+ devLeadReportId as devLeadReportId3,
14900
15244
  notificationId as notificationId2
14901
15245
  } from "@yankeguo/dsh-devlead-protocol";
14902
15246
  function emptyDevLeadProjectionState() {
14903
- return { enabled: false, sessions: [], notifications: [], failure: null };
15247
+ return { enabled: false, sessions: [], notifications: [], reports: [], failure: null };
14904
15248
  }
14905
15249
  var excerptSchema = external_exports.string().min(1).refine(
14906
15250
  (value) => value.length <= DEVLEAD_ERROR_EXCERPT_MAX2 * 2 && Array.from(value).length <= DEVLEAD_ERROR_EXCERPT_MAX2,
@@ -14914,7 +15258,7 @@ var notificationSchema = external_exports.object({
14914
15258
  // by the core can never become a record that this fold rejects.
14915
15259
  transition: external_exports.enum([...DEVLEAD_TRANSITIONS]),
14916
15260
  turn: external_exports.number().int().positive(),
14917
- at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2),
15261
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT3),
14918
15262
  error: excerptSchema.optional(),
14919
15263
  summary: excerptSchema.optional()
14920
15264
  }).strict().refine(
@@ -14925,11 +15269,39 @@ var notificationSchema = external_exports.object({
14925
15269
  ),
14926
15270
  { message: "notification id must match sessionId, turn, and transition" }
14927
15271
  );
15272
+ var reportMessageSchema = external_exports.string().min(1).refine(
15273
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_MESSAGE_MAX3,
15274
+ { message: `report message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX3} code points` }
15275
+ );
15276
+ var reportSchema2 = external_exports.object({
15277
+ id: external_exports.string().min(1),
15278
+ kind: external_exports.enum([...DEVLEAD_REPORT_KINDS2]),
15279
+ message: reportMessageSchema,
15280
+ summary: external_exports.string().min(1).refine(
15281
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_SUMMARY_MAX3,
15282
+ { message: `report summary must be at most ${DEVLEAD_REPORT_SUMMARY_MAX3} code points` }
15283
+ ).optional(),
15284
+ senderSessionId: external_exports.string().min(1),
15285
+ senderSessionTitle: excerptSchema.optional(),
15286
+ senderWorkspaceId: external_exports.string().min(1).optional(),
15287
+ senderWorkspaceTitle: excerptSchema.optional(),
15288
+ leadSessionId: external_exports.string().min(1),
15289
+ turn: external_exports.number().int().nonnegative(),
15290
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT3)
15291
+ }).strict().refine(
15292
+ (report) => report.id === devLeadReportId3(report.senderSessionId, report.turn, report.kind, report.message),
15293
+ { message: "report id must match senderSessionId, turn, kind, and message" }
15294
+ );
14928
15295
  function retainNotification(notifications, notification) {
14929
15296
  if (notifications.some((existing) => existing.id === notification.id)) return notifications;
14930
15297
  const next = [...notifications, notification];
14931
15298
  return next.length <= DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2 ? next : next.slice(next.length - DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2);
14932
15299
  }
15300
+ function retainReport(reports, report) {
15301
+ if (reports.some((existing) => existing.id === report.id)) return reports;
15302
+ const next = [...reports, report];
15303
+ return next.length <= DEVLEAD_REPORT_RETENTION ? next : next.slice(next.length - DEVLEAD_REPORT_RETENTION);
15304
+ }
14933
15305
  function sameSessionIds(left, right) {
14934
15306
  return left.length === right.length && left.every((id, index) => id === right[index]);
14935
15307
  }
@@ -14943,6 +15315,10 @@ var devLeadProjectionStateSchema = external_exports.object({
14943
15315
  (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14944
15316
  { message: "notification ids must be unique" }
14945
15317
  ),
15318
+ reports: external_exports.array(reportSchema2).max(DEVLEAD_REPORT_RETENTION).refine(
15319
+ (reports) => new Set(reports.map((report) => report.id)).size === reports.length,
15320
+ { message: "report ids must be unique" }
15321
+ ),
14946
15322
  failure: external_exports.string().min(1).nullable()
14947
15323
  }).strict();
14948
15324
  var devLeadProjectionSchema = external_exports.object({
@@ -14951,6 +15327,10 @@ var devLeadProjectionSchema = external_exports.object({
14951
15327
  notifications: external_exports.array(notificationSchema).max(DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2).refine(
14952
15328
  (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14953
15329
  { message: "notification ids must be unique" }
15330
+ ),
15331
+ reports: external_exports.array(reportSchema2).max(DEVLEAD_REPORT_RETENTION).refine(
15332
+ (reports) => new Set(reports.map((report) => report.id)).size === reports.length,
15333
+ { message: "report ids must be unique" }
14954
15334
  )
14955
15335
  }).strict();
14956
15336
  var wireViews = /* @__PURE__ */ new WeakMap();
@@ -14960,7 +15340,8 @@ function devLeadProjectionView(state) {
14960
15340
  const view = {
14961
15341
  enabled: state.enabled,
14962
15342
  sessions: state.sessions,
14963
- notifications: state.notifications
15343
+ notifications: state.notifications,
15344
+ reports: state.reports
14964
15345
  };
14965
15346
  wireViews.set(state, view);
14966
15347
  return view;
@@ -14993,6 +15374,11 @@ function applyDevLeadProjection(state, event) {
14993
15374
  const notifications = retainNotification(state.notifications, notification);
14994
15375
  return notifications === state.notifications ? state : { ...state, notifications };
14995
15376
  }
15377
+ case DEVLEAD_REPORT_RECORD_TYPE2: {
15378
+ const report = decodeReportRecord(record2.data);
15379
+ const reports = retainReport(state.reports, report);
15380
+ return reports === state.reports ? state : { ...state, reports };
15381
+ }
14996
15382
  default:
14997
15383
  return state;
14998
15384
  }
@@ -15023,9 +15409,9 @@ var devLeadProjectionDefinition = {
15023
15409
  // conversation reads it: keep it out of every Session summary/list row.
15024
15410
  summary: false
15025
15411
  },
15026
- // 1: the initial durable representation of the mode, watch set, and keyed
15027
- // notification records.
15028
- stateVersion: 1
15412
+ // 2: adds the retained `reports` array to the state; version 1 cache rows
15413
+ // are discarded and refolded from the durable log.
15414
+ stateVersion: 2
15029
15415
  };
15030
15416
  function emptyDevLeadModeProjectionState() {
15031
15417
  return { enabled: false, failure: null };
@@ -15071,6 +15457,9 @@ function applyDevLeadModeProjection(state, event) {
15071
15457
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2:
15072
15458
  decodeNotificationRecord(record2.data);
15073
15459
  return state;
15460
+ case DEVLEAD_REPORT_RECORD_TYPE2:
15461
+ decodeReportRecord(record2.data);
15462
+ return state;
15074
15463
  default:
15075
15464
  return state;
15076
15465
  }
@@ -15097,6 +15486,45 @@ var devLeadModeProjectionDefinition = {
15097
15486
  stateVersion: 1
15098
15487
  };
15099
15488
 
15489
+ // packages/devlead/src/active.ts
15490
+ import { pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
15491
+ import {
15492
+ DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
15493
+ DEVLEAD_RESET_RECORD_TYPE as DEVLEAD_RESET_RECORD_TYPE3
15494
+ } from "@yankeguo/dsh-devlead-protocol";
15495
+ function lastEnabledAt(events) {
15496
+ let at;
15497
+ for (const event of events) {
15498
+ const record2 = pluginRecordOf2(event);
15499
+ if (record2 === void 0) continue;
15500
+ if (record2.type === DEVLEAD_MODE_RECORD_TYPE3) {
15501
+ const data = record2.data;
15502
+ if (data.enabled === true && typeof data.at === "number" && Number.isFinite(data.at)) at = data.at;
15503
+ continue;
15504
+ }
15505
+ if (record2.type === DEVLEAD_RESET_RECORD_TYPE3) at = void 0;
15506
+ }
15507
+ return at;
15508
+ }
15509
+ function rankActiveSessions(occupants, preferredSessionId) {
15510
+ return [...occupants].sort((left, right) => {
15511
+ if (left.sessionId === preferredSessionId) return -1;
15512
+ if (right.sessionId === preferredSessionId) return 1;
15513
+ if (left.archived !== right.archived) return left.archived ? 1 : -1;
15514
+ if (left.live !== right.live) return left.live ? -1 : 1;
15515
+ if (left.running !== right.running) return left.running ? -1 : 1;
15516
+ return right.enabledAt - left.enabledAt || right.createdAt - left.createdAt || left.sessionId.localeCompare(right.sessionId);
15517
+ });
15518
+ }
15519
+ function activeSessionLabel(occupant) {
15520
+ const title = occupant.title?.trim() ?? "";
15521
+ return title.length === 0 ? occupant.sessionId : `${title} (${occupant.sessionId})`;
15522
+ }
15523
+ function alreadyActiveMessage(occupant) {
15524
+ const label = activeSessionLabel(occupant);
15525
+ return `Another Session is already in DevLead mode: ${label}. Run /devlead off there first, then enable this Session.`;
15526
+ }
15527
+
15100
15528
  // packages/devlead/src/isolation.ts
15101
15529
  function worktreeCheckoutOf(value) {
15102
15530
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -15118,19 +15546,23 @@ function worktreeCapabilityOf(ctx) {
15118
15546
  }
15119
15547
 
15120
15548
  // packages/devlead/src/notification.ts
15121
- import { appendPluginRecord, pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
15549
+ import { appendPluginRecord, pluginRecordOf as pluginRecordOf3 } from "@deepseek-ai/dsh-session";
15122
15550
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
15123
15551
  import {
15124
15552
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3,
15125
15553
  DEVLEAD_MESSAGE_KIND as DEVLEAD_MESSAGE_KIND2,
15126
- DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
15554
+ DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE4,
15127
15555
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE3,
15556
+ DEVLEAD_REPORT_RECORD_TYPE as DEVLEAD_REPORT_RECORD_TYPE3,
15557
+ DEVLEAD_REPORT_RETENTION as DEVLEAD_REPORT_RETENTION2,
15128
15558
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE3,
15129
15559
  isDevLeadTransition as isDevLeadTransition2,
15130
- notificationLine
15560
+ notificationLine,
15561
+ reportLine
15131
15562
  } from "@yankeguo/dsh-devlead-protocol";
15132
15563
  var MAX_DIGEST_LINES = 12;
15133
15564
  var DELIVERY_RETRY_MS = 1e3;
15565
+ var MAX_COLD_RESUME_ATTEMPTS = 5;
15134
15566
  var DEVLEAD_MAX_WARNED_FAILURES = 256;
15135
15567
  function renderDevLeadNotice(notifications, total = notifications.length) {
15136
15568
  const shown = notifications.slice(-MAX_DIGEST_LINES);
@@ -15144,6 +15576,18 @@ function renderDevLeadNotice(notifications, total = notifications.length) {
15144
15576
  "Call devlead_notifications for the retained digest, or devlead_get_session for one session in detail. Decide what the Dev Lead should do next: continue an existing conversation, dispatch new work, or report to the human."
15145
15577
  ].join("\n");
15146
15578
  }
15579
+ function renderDevLeadReportNotice(reports) {
15580
+ const shown = reports.slice(-MAX_DIGEST_LINES);
15581
+ const omitted = reports.length - shown.length;
15582
+ const lines = shown.map((report) => `- ${reportLine(report)}`);
15583
+ if (omitted > 0) lines.unshift(`- (${omitted} earlier report(s) omitted; call devlead_notifications for the digest)`);
15584
+ return [
15585
+ "[DEV LEAD REPORT]",
15586
+ "A watched Session sent a mid-turn report. This is a one-way update, not a question; there is no reply channel in it.",
15587
+ ...lines,
15588
+ "Call devlead_notifications for the retained digest, or devlead_get_session for detail. If the report needs a decision or steering, use devlead_prompt_session to continue that Session; otherwise keep working."
15589
+ ].join("\n");
15590
+ }
15147
15591
  var DevLeadNotificationHub = class {
15148
15592
  /**
15149
15593
  * @param ctx - host context providing the Agent registry and Session store.
@@ -15189,7 +15633,7 @@ var DevLeadNotificationHub = class {
15189
15633
  if (status !== "idle") return;
15190
15634
  const runtime = this.leads.get(String(agent.id));
15191
15635
  if (runtime === void 0) return;
15192
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
15636
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15193
15637
  void this.flush(runtime);
15194
15638
  });
15195
15639
  this.ctx.on("session/event", (session, event) => {
@@ -15231,6 +15675,121 @@ var DevLeadNotificationHub = class {
15231
15675
  if (runtime === void 0) return;
15232
15676
  await this.flush(runtime);
15233
15677
  }
15678
+ /**
15679
+ * List the active DevLead Sessions currently watching one Session.
15680
+ * A runtime exists only for an enabled lead, and `setWatched` keeps its
15681
+ * reverse index exact, so no durable read is needed on this hot path.
15682
+ * @param sessionId - candidate watched Session identity.
15683
+ * @returns watching lead identities, in insertion order.
15684
+ */
15685
+ supervisorsOf(sessionId) {
15686
+ if (this.stopping) return [];
15687
+ const watchers = this.watchers.get(sessionId);
15688
+ if (watchers === void 0) return [];
15689
+ return [...watchers].filter((leadId) => this.leads.has(leadId));
15690
+ }
15691
+ /**
15692
+ * Persist and queue one report from a watched Session.
15693
+ *
15694
+ * The report receipt is appended to the lead's own Session log, exactly like
15695
+ * a turn notification, so the fold and the retained digest survive a restart.
15696
+ * When the lead is cold the receipt waits in `unsavedReports` and the normal
15697
+ * flush path resumes the lead (when `wakeColdSession` is enabled) before
15698
+ * writing it. The call returns after the queue decision, never after the
15699
+ * lead's wake-up turn, so the reporter is not blocked.
15700
+ * @param report - report addressed to one active lead.
15701
+ * @returns whether the report belongs to an indexed watch relationship.
15702
+ */
15703
+ report(report) {
15704
+ if (this.stopping) return false;
15705
+ const runtime = this.leads.get(report.leadSessionId);
15706
+ if (runtime === void 0 || !runtime.watched.has(report.senderSessionId)) return false;
15707
+ if (runtime.pendingReports.some((existing) => existing.id === report.id) || runtime.unsavedReports.some((existing) => existing.id === report.id)) return true;
15708
+ const session = this.ctx.sessions.get(toSessionId(report.leadSessionId));
15709
+ if (session !== void 0) {
15710
+ const state = this.stateOf(session);
15711
+ if (state === void 0 || !state.enabled) return false;
15712
+ if (state.reports.some((existing) => existing.id === report.id)) return true;
15713
+ if (this.appendReportRecord(session, report)) {
15714
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15715
+ } else {
15716
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15717
+ }
15718
+ } else {
15719
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15720
+ }
15721
+ this.scheduleFlush(runtime);
15722
+ return true;
15723
+ }
15724
+ /**
15725
+ * Persist one report receipt into the lead's attached Session log and wait
15726
+ * for the durability checkpoint before claiming delivery.
15727
+ *
15728
+ * A cold lead cannot accept the receipt yet, so the report is queued for the
15729
+ * normal cold-wake path and this method returns false; the caller keeps its
15730
+ * durable outbox row and replays it later. An archived lead, a disabled lead,
15731
+ * or a removed watch relationship returns false without queueing.
15732
+ * @param report - report addressed to one watched lead.
15733
+ * @returns whether the lead Session log now carries a flushed receipt.
15734
+ */
15735
+ async persistReport(report) {
15736
+ if (this.stopping) return false;
15737
+ const runtime = this.leads.get(report.leadSessionId);
15738
+ if (runtime === void 0 || !runtime.watched.has(report.senderSessionId)) return false;
15739
+ if (this.ctx.get("workspaceRegistry")?.archivedSessionIds.some((id) => String(id) === report.leadSessionId) ?? false) {
15740
+ return false;
15741
+ }
15742
+ const session = this.ctx.sessions.get(toSessionId(report.leadSessionId));
15743
+ if (session === void 0) {
15744
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15745
+ this.scheduleFlush(runtime);
15746
+ return false;
15747
+ }
15748
+ const state = this.stateOf(session);
15749
+ if (state === void 0 || !state.enabled) return false;
15750
+ if (!state.reports.some((existing) => existing.id === report.id)) {
15751
+ try {
15752
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
15753
+ } catch (error51) {
15754
+ this.ctx.logger.warn(
15755
+ `devlead: could not record a report for lead "${runtime.sessionId}": ${thrownMessage(error51)}`
15756
+ );
15757
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15758
+ this.scheduleFlush(runtime);
15759
+ return false;
15760
+ }
15761
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15762
+ }
15763
+ try {
15764
+ await this.ctx.sessions.flush(session);
15765
+ } catch (error51) {
15766
+ this.ctx.logger.warn(
15767
+ `devlead: report receipt for lead "${runtime.sessionId}" could not be flushed to persistence: ${thrownMessage(error51)}`
15768
+ );
15769
+ this.scheduleFlush(runtime);
15770
+ return false;
15771
+ }
15772
+ this.scheduleFlush(runtime);
15773
+ return true;
15774
+ }
15775
+ /**
15776
+ * Append one report receipt and fire-and-forget its durability checkpoint.
15777
+ * @param session - attached lead Session log receiving the record.
15778
+ * @param report - report to persist.
15779
+ * @returns whether the append succeeded.
15780
+ */
15781
+ appendReportRecord(session, report) {
15782
+ try {
15783
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
15784
+ } catch (error51) {
15785
+ this.ctx.logger.warn(
15786
+ `devlead: could not record a report for lead "${report.leadSessionId}": ${thrownMessage(error51)}`
15787
+ );
15788
+ return false;
15789
+ }
15790
+ void this.checkpoint(session, report.leadSessionId);
15791
+ return true;
15792
+ }
15234
15793
  /** Index every live lead Session at plugin load. */
15235
15794
  bootstrap() {
15236
15795
  for (const agent of this.ctx.agents.list()) this.syncLead(agent);
@@ -15283,8 +15842,12 @@ var DevLeadNotificationHub = class {
15283
15842
  return;
15284
15843
  }
15285
15844
  const runtime = this.ensureLead(sessionId);
15845
+ runtime.resumeAttempts = 0;
15286
15846
  this.setWatched(runtime, state.sessions);
15287
- if (runtime.pending.length > 0 || runtime.unsaved.length > 0) this.scheduleFlush(runtime);
15847
+ if (runtime.pending.length > 0 || runtime.pendingReports.length > 0 || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) {
15848
+ this.clearTimer(runtime);
15849
+ this.scheduleFlush(runtime);
15850
+ }
15288
15851
  }
15289
15852
  /**
15290
15853
  * Create the runtime row for one lead Session.
@@ -15298,10 +15861,13 @@ var DevLeadNotificationHub = class {
15298
15861
  sessionId,
15299
15862
  watched: /* @__PURE__ */ new Set(),
15300
15863
  pending: [],
15864
+ pendingReports: [],
15301
15865
  unsaved: [],
15866
+ unsavedReports: [],
15302
15867
  timer: void 0,
15303
15868
  scheduled: false,
15304
- flushing: false
15869
+ flushing: false,
15870
+ resumeAttempts: 0
15305
15871
  };
15306
15872
  this.leads.set(sessionId, runtime);
15307
15873
  return runtime;
@@ -15347,7 +15913,11 @@ var DevLeadNotificationHub = class {
15347
15913
  runtime.watched = next;
15348
15914
  runtime.pending = runtime.pending.filter((notification) => next.has(notification.sessionId));
15349
15915
  runtime.unsaved = runtime.unsaved.filter((notification) => next.has(notification.sessionId));
15350
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) this.clearTimer(runtime);
15916
+ runtime.pendingReports = runtime.pendingReports.filter((report) => next.has(report.senderSessionId));
15917
+ runtime.unsavedReports = runtime.unsavedReports.filter((report) => next.has(report.senderSessionId));
15918
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) {
15919
+ this.clearTimer(runtime);
15920
+ }
15351
15921
  }
15352
15922
  /**
15353
15923
  * Drop one lead runtime and its reverse-index entries.
@@ -15371,7 +15941,9 @@ var DevLeadNotificationHub = class {
15371
15941
  }
15372
15942
  }
15373
15943
  runtime.pending = [];
15944
+ runtime.pendingReports = [];
15374
15945
  runtime.unsaved = [];
15946
+ runtime.unsavedReports = [];
15375
15947
  this.leads.delete(leadId);
15376
15948
  }
15377
15949
  this.resuming.delete(leadId);
@@ -15394,8 +15966,8 @@ var DevLeadNotificationHub = class {
15394
15966
  onSessionEvent(session, event) {
15395
15967
  if (this.stopping) return;
15396
15968
  const sessionId = String(session.id);
15397
- const record2 = pluginRecordOf2(event);
15398
- if (record2 !== void 0 && (record2.type === DEVLEAD_MODE_RECORD_TYPE3 || record2.type === DEVLEAD_WATCH_RECORD_TYPE3 || record2.type === DEVLEAD_RESET_RECORD_TYPE)) {
15969
+ const record2 = pluginRecordOf3(event);
15970
+ if (record2 !== void 0 && (record2.type === DEVLEAD_MODE_RECORD_TYPE4 || record2.type === DEVLEAD_WATCH_RECORD_TYPE3 || record2.type === DEVLEAD_RESET_RECORD_TYPE)) {
15399
15971
  const agent = this.ctx.agents.get(session.id);
15400
15972
  if (agent !== void 0) this.syncLead(agent);
15401
15973
  }
@@ -15461,10 +16033,10 @@ var DevLeadNotificationHub = class {
15461
16033
  const runtime = this.leads.get(leadId);
15462
16034
  if (runtime === void 0) return;
15463
16035
  const session = this.ctx.sessions.get(toSessionId(leadId));
15464
- if (session !== void 0) this.appendNotificationRecord(session, notification, leadId);
16036
+ const persisted = session !== void 0 && this.appendNotificationRecord(session, notification, leadId);
15465
16037
  if (runtime.pending.some((existing) => existing.id === notification.id)) return;
15466
16038
  if (runtime.unsaved.some((existing) => existing.id === notification.id)) return;
15467
- if (session === void 0) {
16039
+ if (!persisted) {
15468
16040
  runtime.unsaved = [...runtime.unsaved, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15469
16041
  this.scheduleFlush(runtime);
15470
16042
  return;
@@ -15480,15 +16052,17 @@ var DevLeadNotificationHub = class {
15480
16052
  * @param session - lead Session receiving the record.
15481
16053
  * @param notification - notification to persist.
15482
16054
  * @param leadId - lead Session identity used in warnings.
16055
+ * @returns whether the durable append succeeded.
15483
16056
  */
15484
16057
  appendNotificationRecord(session, notification, leadId) {
15485
16058
  try {
15486
16059
  appendPluginRecord(session, DEVLEAD_NOTIFICATION_RECORD_TYPE3, notificationRecord(notification));
15487
16060
  } catch (error51) {
15488
16061
  this.ctx.logger.warn(`devlead: could not record a notification for lead "${leadId}": ${thrownMessage(error51)}`);
15489
- return;
16062
+ return false;
15490
16063
  }
15491
16064
  void this.checkpoint(session, leadId);
16065
+ return true;
15492
16066
  }
15493
16067
  /**
15494
16068
  * Fire-and-forget one Session durability checkpoint.
@@ -15512,8 +16086,9 @@ var DevLeadNotificationHub = class {
15512
16086
  * @param runtime - lead runtime row.
15513
16087
  */
15514
16088
  persistUnsaved(session, runtime) {
15515
- if (runtime.unsaved.length === 0) return;
16089
+ if (runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15516
16090
  const remaining = [];
16091
+ const remainingReports = [];
15517
16092
  let appended = false;
15518
16093
  for (const notification of runtime.unsaved) {
15519
16094
  try {
@@ -15528,9 +16103,23 @@ var DevLeadNotificationHub = class {
15528
16103
  appended = true;
15529
16104
  runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15530
16105
  }
16106
+ for (const report of runtime.unsavedReports) {
16107
+ try {
16108
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
16109
+ } catch (error51) {
16110
+ this.ctx.logger.warn(
16111
+ `devlead: could not record a report for lead "${runtime.sessionId}": ${thrownMessage(error51)}`
16112
+ );
16113
+ remainingReports.push(report);
16114
+ continue;
16115
+ }
16116
+ appended = true;
16117
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
16118
+ }
15531
16119
  runtime.unsaved = remaining;
16120
+ runtime.unsavedReports = remainingReports;
15532
16121
  if (appended) void this.checkpoint(session, runtime.sessionId);
15533
- if (remaining.length > 0) this.scheduleRetry(runtime);
16122
+ if (remaining.length > 0 || remainingReports.length > 0) this.scheduleRetry(runtime);
15534
16123
  }
15535
16124
  /**
15536
16125
  * Arm the coalescing window for one lead.
@@ -15574,7 +16163,7 @@ var DevLeadNotificationHub = class {
15574
16163
  if (this.stopping) return;
15575
16164
  if (this.leads.get(runtime.sessionId) !== runtime) return;
15576
16165
  if (runtime.flushing) return;
15577
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
16166
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15578
16167
  const leadSessionId = toSessionId(runtime.sessionId);
15579
16168
  const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(leadSessionId) ?? false;
15580
16169
  if (archived) {
@@ -15582,7 +16171,7 @@ var DevLeadNotificationHub = class {
15582
16171
  if (session !== void 0) {
15583
16172
  this.persistUnsaved(session, runtime);
15584
16173
  runtime.pending = [];
15585
- runtime.unsaved = [];
16174
+ runtime.pendingReports = [];
15586
16175
  }
15587
16176
  this.clearTimer(runtime);
15588
16177
  return;
@@ -15593,18 +16182,24 @@ var DevLeadNotificationHub = class {
15593
16182
  return;
15594
16183
  }
15595
16184
  this.persistUnsaved(agent.session, runtime);
15596
- if (runtime.pending.length === 0) return;
16185
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0) return;
15597
16186
  if (this.hasQueuedNotice(agent)) {
15598
16187
  this.scheduleRetry(runtime);
15599
16188
  return;
15600
16189
  }
15601
16190
  const batch = runtime.pending;
16191
+ const reportBatch = runtime.pendingReports;
15602
16192
  runtime.pending = [];
16193
+ runtime.pendingReports = [];
15603
16194
  this.clearTimer(runtime);
15604
16195
  runtime.flushing = true;
15605
16196
  let failed = false;
15606
16197
  try {
15607
- agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
16198
+ const text = [
16199
+ batch.length === 0 ? "" : renderDevLeadNotice(batch),
16200
+ reportBatch.length === 0 ? "" : renderDevLeadReportNotice(reportBatch)
16201
+ ].filter((part) => part.length > 0).join("\n\n");
16202
+ agent.followup(createDevLeadNoticeMessage(text));
15608
16203
  try {
15609
16204
  await this.ctx.sessions.flush(agent.session);
15610
16205
  } catch (error51) {
@@ -15613,12 +16208,13 @@ var DevLeadNotificationHub = class {
15613
16208
  } catch (error51) {
15614
16209
  this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15615
16210
  runtime.pending = [...batch, ...runtime.pending].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
16211
+ runtime.pendingReports = [...reportBatch, ...runtime.pendingReports].slice(-DEVLEAD_REPORT_RETENTION2);
15616
16212
  failed = true;
15617
16213
  } finally {
15618
16214
  runtime.flushing = false;
15619
16215
  }
15620
- if ((runtime.pending.length > 0 || runtime.unsaved.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
15621
- if (failed || runtime.unsaved.length > 0) {
16216
+ if ((runtime.pending.length > 0 || runtime.pendingReports.length > 0 || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
16217
+ if (failed || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) {
15622
16218
  this.scheduleRetry(runtime);
15623
16219
  } else {
15624
16220
  this.scheduleFlush(runtime);
@@ -15637,6 +16233,26 @@ var DevLeadNotificationHub = class {
15637
16233
  void this.flush(runtime);
15638
16234
  }, DELIVERY_RETRY_MS);
15639
16235
  }
16236
+ /**
16237
+ * Schedule a bounded retry after a failed cold-lead resume.
16238
+ *
16239
+ * A cold lead's unsaved notifications are memory-only, so a transient
16240
+ * resolve failure (a held writer, a warming controller) must not strand the
16241
+ * batch until the next watched `turn/end`. The attempt counter is reset when
16242
+ * the Agent becomes live; after the cap, one warning reports the give-up and
16243
+ * the next live index or watched event retries naturally.
16244
+ * @param runtime - lead runtime row.
16245
+ */
16246
+ retryColdResume(runtime) {
16247
+ runtime.resumeAttempts += 1;
16248
+ if (runtime.resumeAttempts >= MAX_COLD_RESUME_ATTEMPTS) {
16249
+ this.ctx.logger.warn(
16250
+ `devlead: giving up resuming cold lead "${runtime.sessionId}" after ${runtime.resumeAttempts} attempts; open the Session or wait for its next watched event`
16251
+ );
16252
+ return;
16253
+ }
16254
+ this.scheduleRetry(runtime);
16255
+ }
15640
16256
  /**
15641
16257
  * Whether one lead Agent already holds an undelivered digest notice.
15642
16258
  * @param agent - live lead Agent.
@@ -15665,12 +16281,14 @@ var DevLeadNotificationHub = class {
15665
16281
  if (this.stopping) return;
15666
16282
  if ("error" in resolved) {
15667
16283
  this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${resolved.error.message}`);
16284
+ this.retryColdResume(runtime);
15668
16285
  return;
15669
16286
  }
15670
16287
  this.syncLead(resolved.agent);
15671
16288
  } catch (error51) {
15672
16289
  if (!this.stopping) {
15673
16290
  this.ctx.logger.warn(`devlead: could not resume lead "${leadId}": ${thrownMessage(error51)}`);
16291
+ this.retryColdResume(runtime);
15674
16292
  }
15675
16293
  } finally {
15676
16294
  this.resuming.delete(leadId);
@@ -15679,14 +16297,17 @@ var DevLeadNotificationHub = class {
15679
16297
  };
15680
16298
 
15681
16299
  // packages/devlead/src/persistence.ts
15682
- async function persistedSessionsOf(ctx) {
16300
+ async function persistedSessionsOf(ctx, signal) {
15683
16301
  const candidate = ctx.get("sessionPersistence");
15684
16302
  if (typeof candidate !== "object" || candidate === null) return { verifiable: false };
15685
16303
  const list = candidate.list;
15686
16304
  if (typeof list !== "function") return { verifiable: false };
15687
16305
  let listed;
15688
16306
  try {
15689
- listed = await Promise.resolve(list.call(candidate));
16307
+ listed = await Promise.resolve(list.call(
16308
+ candidate,
16309
+ signal === void 0 ? void 0 : { signal }
16310
+ ));
15690
16311
  } catch {
15691
16312
  return { verifiable: true };
15692
16313
  }
@@ -15704,6 +16325,42 @@ async function persistedSessionsOf(ctx) {
15704
16325
  return { verifiable: true, ids };
15705
16326
  }
15706
16327
 
16328
+ // packages/devlead/src/presets.ts
16329
+ function recordOf2(value) {
16330
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
16331
+ }
16332
+ function stringField2(value) {
16333
+ return typeof value === "string" ? value : "";
16334
+ }
16335
+ function agentPresetRosterCapabilityOf(ctx) {
16336
+ const candidate = ctx.get("agentPresets");
16337
+ if (typeof candidate !== "object" || candidate === null) return void 0;
16338
+ const defaultId = candidate.defaultId;
16339
+ const list = candidate.list;
16340
+ if (typeof defaultId !== "string" || typeof list !== "function") return void 0;
16341
+ return candidate;
16342
+ }
16343
+ function devLeadAgentPresetsOf(rows, defaultId) {
16344
+ const presets = [];
16345
+ for (const row of rows) {
16346
+ const record2 = recordOf2(row);
16347
+ if (record2 === void 0) continue;
16348
+ const id = stringField2(record2.id).trim();
16349
+ if (id.length === 0) continue;
16350
+ const name = stringField2(record2.name).trim();
16351
+ const description = stringField2(record2.description).trim();
16352
+ const broken = stringField2(record2.broken).trim();
16353
+ presets.push({
16354
+ id,
16355
+ default: id === defaultId,
16356
+ ...name.length === 0 ? {} : { name },
16357
+ ...description.length === 0 ? {} : { description },
16358
+ ...broken.length === 0 ? {} : { broken }
16359
+ });
16360
+ }
16361
+ return presets;
16362
+ }
16363
+
15707
16364
  // packages/devlead/src/projection-cache.ts
15708
16365
  function projectionCacheOf(ctx) {
15709
16366
  const candidate = ctx.get("sessionProjectionCache");
@@ -15711,9 +16368,12 @@ function projectionCacheOf(ctx) {
15711
16368
  const cachedSnapshot = candidate.cachedSnapshot;
15712
16369
  if (typeof cachedSnapshot !== "function") return void 0;
15713
16370
  const service = candidate;
15714
- return { cachedSnapshot: (header) => service.cachedSnapshot(header) };
16371
+ return {
16372
+ cachedSnapshot: (header) => service.cachedSnapshot(header),
16373
+ ...typeof service.write === "function" ? { write: (session) => service.write(session) } : {}
16374
+ };
15715
16375
  }
15716
- function devLeadPrefilterOf(cache, header) {
16376
+ function devLeadActivePrefilterOf(cache, header) {
15717
16377
  let snapshot;
15718
16378
  try {
15719
16379
  snapshot = cache.cachedSnapshot(header);
@@ -15725,12 +16385,9 @@ function devLeadPrefilterOf(cache, header) {
15725
16385
  if (typeof values !== "object" || values === null) return "unknown";
15726
16386
  const devLead = values.devLead;
15727
16387
  if (typeof devLead !== "object" || devLead === null) return "unknown";
15728
- const record2 = devLead;
15729
- if (record2.enabled !== true) {
15730
- return record2.enabled === false ? "not-lead" : "unknown";
15731
- }
15732
- if (!Array.isArray(record2.sessions)) return "unknown";
15733
- return record2.sessions.length > 0 ? "lead" : "not-lead";
16388
+ const enabled = devLead.enabled;
16389
+ if (enabled === true) return "active";
16390
+ return enabled === false ? "inactive" : "unknown";
15734
16391
  }
15735
16392
 
15736
16393
  // packages/devlead/src/views.ts
@@ -15785,6 +16442,12 @@ async function collectSessionIds(deps, workspace, exhaustive = false) {
15785
16442
  }
15786
16443
  } catch (error51) {
15787
16444
  rethrowIfAborted(error51, signal);
16445
+ if (exhaustive) {
16446
+ throw new DevLeadError(
16447
+ `could not list persisted Sessions to resolve a full identity: ${thrownMessage(error51)}`,
16448
+ "DEVLEAD_SESSION_UNAVAILABLE"
16449
+ );
16450
+ }
15788
16451
  }
15789
16452
  }
15790
16453
  }
@@ -15824,12 +16487,43 @@ async function knownSessions(deps, ids) {
15824
16487
  }
15825
16488
  return result;
15826
16489
  }
15827
- async function readSessionFacts(deps, ids) {
15828
- const known = await knownSessions(deps, ids);
15829
- const workspaces = /* @__PURE__ */ new Map();
15830
- const archived = /* @__PURE__ */ new Set();
15831
- const registry2 = deps.ctx.get("workspaceRegistry");
15832
- if (registry2 !== void 0) {
16490
+ async function sessionRankFacts(deps, ids) {
16491
+ const { ctx, signal } = deps;
16492
+ const result = /* @__PURE__ */ new Map();
16493
+ const missingHeader = [];
16494
+ for (const id of ids) {
16495
+ const session = ctx.sessions.get(toSessionId2(id));
16496
+ const agent = ctx.agents.get(toSessionId2(id));
16497
+ const live = session !== void 0 || agent !== void 0;
16498
+ const sessionObject = session ?? agent?.session;
16499
+ const title = sessionObject === void 0 ? void 0 : ctx.get("sessionTitle")?.get(sessionObject)?.title;
16500
+ result.set(id, { title, header: sessionObject?.header, live });
16501
+ if (sessionObject === void 0) missingHeader.push(id);
16502
+ }
16503
+ if (missingHeader.length > 0) {
16504
+ const query = ctx.get("sessionQuery");
16505
+ if (query !== void 0) {
16506
+ try {
16507
+ const records = await query.listSessions(signal);
16508
+ const wanted = new Set(missingHeader);
16509
+ for (const record2 of records) {
16510
+ const id = String(record2.header.id);
16511
+ const entry = wanted.has(id) ? result.get(id) : void 0;
16512
+ if (entry !== void 0) result.set(id, { ...entry, header: record2.header });
16513
+ }
16514
+ } catch (error51) {
16515
+ rethrowIfAborted(error51, signal);
16516
+ }
16517
+ }
16518
+ }
16519
+ return result;
16520
+ }
16521
+ async function readSessionFacts(deps, ids) {
16522
+ const known = await knownSessions(deps, ids);
16523
+ const workspaces = /* @__PURE__ */ new Map();
16524
+ const archived = /* @__PURE__ */ new Set();
16525
+ const registry2 = deps.ctx.get("workspaceRegistry");
16526
+ if (registry2 !== void 0) {
15833
16527
  const requested = new Set(ids);
15834
16528
  for (const sessionId of registry2.archivedSessionIds) {
15835
16529
  const id = String(sessionId);
@@ -15845,12 +16539,12 @@ async function readSessionFacts(deps, ids) {
15845
16539
  }
15846
16540
  return { known, workspaces, archived };
15847
16541
  }
15848
- function rankSessionIds(deps, ids, facts, limit) {
16542
+ function rankSessionIds(deps, ids, known, limit) {
15849
16543
  const ranked = ids.map((id) => ({
15850
16544
  id,
15851
16545
  watched: deps.isWatched(id),
15852
16546
  running: deps.ctx.agents.get(toSessionId2(id))?.status === "running",
15853
- createdAt: facts.known.get(id)?.header?.createdAt ?? 0
16547
+ createdAt: known.get(id)?.header?.createdAt ?? 0
15854
16548
  }));
15855
16549
  ranked.sort((left, right) => {
15856
16550
  if (left.watched !== right.watched) return left.watched ? -1 : 1;
@@ -15911,7 +16605,8 @@ async function buildSessionView(deps, sessionId, withLog, facts) {
15911
16605
  const workspace = facts.workspaces.get(sessionId);
15912
16606
  const boundary = agent === void 0 ? void 0 : ctx.agents.turnBoundaryOf(agent.session);
15913
16607
  const log = withLog ? await sessionLogFacts(deps, sessionId) : {};
15914
- const lastTurn = log.lastTurn ?? boundary?.lastTurn;
16608
+ const boundaryTurn = boundary !== void 0 && boundary.lastTurn > 0 ? boundary.lastTurn : void 0;
16609
+ const lastTurn = log.lastTurn ?? boundaryTurn;
15915
16610
  return {
15916
16611
  sessionId,
15917
16612
  ...known?.title === void 0 ? {} : { title: known.title },
@@ -16024,6 +16719,7 @@ async function resolveSessionReference(deps, reference) {
16024
16719
  // packages/devlead/src/index.ts
16025
16720
  var MAX_TIMER_DELAY_MS = 2147483647;
16026
16721
  var MAX_COLD_LEAD_LOG_READS = 64;
16722
+ var MAX_ACTIVE_SCAN_UNKNOWN_READS = 64;
16027
16723
  var REHYDRATION_READINESS_TIMEOUT_MS = 2e3;
16028
16724
  var REHYDRATION_READINESS_POLL_MS = 100;
16029
16725
  var Config = z2.object({
@@ -16137,6 +16833,45 @@ var DevLeadService = class extends Service {
16137
16833
  rehydrated = false;
16138
16834
  /** In-flight rehydration attempt, so concurrent readiness triggers share it. */
16139
16835
  rehydrating;
16836
+ /** Whether the plugin fiber was disposed; late rehydration steps must stop. */
16837
+ disposed = false;
16838
+ /** Resolver of the active readiness sleep, so disposal can wake it. */
16839
+ readinessWake;
16840
+ /** Timer of the active readiness sleep, so disposal can clear it. */
16841
+ readinessTimer;
16842
+ /** Serializes global-mode admission so two concurrent enables cannot both pass. */
16843
+ admissionTail = Promise.resolve();
16844
+ /**
16845
+ * Last known global DevLead occupant, used only as a recovery preference.
16846
+ * Every admission still re-derives occupancy from durable/live projections;
16847
+ * this hint merely keeps an incumbent from being displaced by a Session
16848
+ * resumed later.
16849
+ */
16850
+ activeSessionId;
16851
+ /** Cold enabled Sessions discovered by the boot rehydration scan. */
16852
+ recoveredActive = [];
16853
+ /** Whether the service finished its first activation-phase reconciliation. */
16854
+ initialized = false;
16855
+ /**
16856
+ * Per-reporter report budget and idempotency window for the current turn.
16857
+ * Process-local by design; a restart resets the window, while the lead's
16858
+ * durable report digest remains the audit authority.
16859
+ */
16860
+ reportState = /* @__PURE__ */ new Map();
16861
+ /** Durable report outbox; undefined when the Host composes no storage-domain. */
16862
+ outbox;
16863
+ /** In-flight outbox opening. */
16864
+ outboxOpening;
16865
+ /** Optional-service fiber that retries opening the outbox once storage mounts. */
16866
+ outboxInjection;
16867
+ /** Guard against overlapping outbox replay passes. */
16868
+ outboxReplaying = false;
16869
+ /**
16870
+ * Archived holders whose mode-off could not be written. The durable
16871
+ * tombstones live in the outbox domain; this set is the in-process mirror
16872
+ * and also covers a Host without storage.
16873
+ */
16874
+ ignoredArchived = /* @__PURE__ */ new Set();
16140
16875
  /**
16141
16876
  * Disposers of the armed readiness retry: the optional-service injection fiber
16142
16877
  * and, while the query engine itself is missing, the lifecycle listeners.
@@ -16160,9 +16895,50 @@ var DevLeadService = class extends Service {
16160
16895
  );
16161
16896
  this.hub.start();
16162
16897
  this.ctx.effect(function* () {
16163
- yield () => this.disposeRehydrationRetry();
16898
+ yield () => {
16899
+ this.disposed = true;
16900
+ this.wakeReadiness();
16901
+ this.disposeRehydrationRetry();
16902
+ this.outboxInjection?.dispose();
16903
+ this.outboxInjection = void 0;
16904
+ void this.outbox?.close();
16905
+ };
16164
16906
  }.bind(this), "devlead: cold rehydration");
16907
+ this.ctx.effect(function* () {
16908
+ const dispose = this.ctx.on("agent/created", ({ agent }) => {
16909
+ if (this.disposed) return void 0;
16910
+ const state = this.projectionHandle.stateOf(agent.session);
16911
+ if (state.failure !== null || !state.enabled) return void 0;
16912
+ if (this.activeSessionId === void 0) {
16913
+ void this.reconcileActiveSessions(String(agent.id));
16914
+ void this.replayOutbox();
16915
+ return void 0;
16916
+ }
16917
+ if (this.activeSessionId === String(agent.id)) {
16918
+ void this.replayOutbox();
16919
+ return void 0;
16920
+ }
16921
+ void this.reconcileActiveSessions(this.activeSessionId);
16922
+ void this.replayOutbox();
16923
+ return void 0;
16924
+ });
16925
+ yield dispose;
16926
+ }.bind(this), "devlead: single active");
16927
+ await this.openOutbox();
16928
+ if (this.outbox === void 0) {
16929
+ this.outboxInjection = this.ctx.inject(["storageDomain"], () => {
16930
+ void this.openOutbox().then(() => this.replayOutbox());
16931
+ return void 0;
16932
+ });
16933
+ }
16165
16934
  await this.rehydrateFromPersistence();
16935
+ await this.reconcileActiveSessions(void 0, {
16936
+ includePersisted: false,
16937
+ knownActive: this.recoveredActive
16938
+ });
16939
+ this.recoveredActive = [];
16940
+ await this.replayOutbox();
16941
+ this.initialized = true;
16166
16942
  }
16167
16943
  /**
16168
16944
  * Rebuild the notification hub's watch index from durable state.
@@ -16204,7 +16980,7 @@ var DevLeadService = class extends Service {
16204
16980
  * steady Host pays one macrotask plus one comparison.
16205
16981
  */
16206
16982
  async runRehydration() {
16207
- if (this.rehydrated) return;
16983
+ if (this.rehydrated || this.disposed) return;
16208
16984
  const queryReady = this.ctx.get("sessionQuery") !== void 0;
16209
16985
  try {
16210
16986
  this.hub.rehydrate(this.liveAttachLeads());
@@ -16229,12 +17005,15 @@ var DevLeadService = class extends Service {
16229
17005
  return;
16230
17006
  }
16231
17007
  await this.awaitCorpusReady();
16232
- if (this.rehydrated) return;
17008
+ if (this.rehydrated || this.disposed) return;
16233
17009
  try {
16234
- this.hub.rehydrate(await this.persistedLeadRecords(true));
17010
+ const scan = await this.persistedLeadRecords(true);
17011
+ this.recoveredActive = [...scan.active];
17012
+ this.hub.rehydrate(scan.leads.filter((record2) => this.ctx.agents.get(toSessionId3(record2.sessionId)) === void 0));
16235
17013
  } catch (error51) {
16236
17014
  this.ctx.logger.warn(`devlead: cold lead rehydration failed: ${thrownMessage(error51)}`);
16237
17015
  }
17016
+ if (this.disposed) return;
16238
17017
  this.finalizeRehydration();
16239
17018
  }
16240
17019
  /**
@@ -16249,29 +17028,34 @@ var DevLeadService = class extends Service {
16249
17028
  */
16250
17029
  async awaitCorpusReady() {
16251
17030
  const deadline = Date.now() + REHYDRATION_READINESS_TIMEOUT_MS;
16252
- let probe = await persistedSessionsOf(this.ctx);
16253
- while (probe.verifiable && probe.ids === void 0 && Date.now() < deadline) {
16254
- await new Promise((resolve) => {
16255
- setTimeout(resolve, REHYDRATION_READINESS_POLL_MS);
16256
- });
16257
- probe = await persistedSessionsOf(this.ctx);
17031
+ let probe = await this.probeCorpus(deadline);
17032
+ while (!this.disposed && probe?.verifiable === true && probe.ids === void 0 && Date.now() < deadline) {
17033
+ await this.readinessSleep(REHYDRATION_READINESS_POLL_MS);
17034
+ probe = await this.probeCorpus(deadline);
17035
+ }
17036
+ if (this.disposed) return;
17037
+ const ids = probe?.ids;
17038
+ if (ids === void 0) {
17039
+ if (probe?.verifiable === true) {
17040
+ this.ctx.logger.warn(
17041
+ `devlead: the Session persistence listing did not settle within ${REHYDRATION_READINESS_TIMEOUT_MS}ms; cold lead rehydration proceeds best-effort`
17042
+ );
17043
+ }
17044
+ return;
16258
17045
  }
16259
- const ids = probe.ids;
16260
- if (ids === void 0) return;
16261
17046
  if (ids.size === 0) return;
16262
17047
  let consistent = false;
16263
- while (Date.now() < deadline) {
16264
- const listed = await this.listedPersistedSessionIds();
17048
+ while (!this.disposed && Date.now() < deadline) {
17049
+ const listed = await this.listedPersistedSessionIds(deadline);
16265
17050
  if (this.containsAllSessionIds(listed, ids)) {
16266
17051
  consistent = true;
16267
17052
  break;
16268
17053
  }
16269
- await new Promise((resolve) => {
16270
- setTimeout(resolve, REHYDRATION_READINESS_POLL_MS);
16271
- });
17054
+ await this.readinessSleep(REHYDRATION_READINESS_POLL_MS);
16272
17055
  }
17056
+ if (this.disposed) return;
16273
17057
  if (!consistent) {
16274
- consistent = this.containsAllSessionIds(await this.listedPersistedSessionIds(), ids);
17058
+ consistent = this.containsAllSessionIds(await this.listedPersistedSessionIds(deadline), ids);
16275
17059
  }
16276
17060
  if (!consistent) {
16277
17061
  this.ctx.logger.warn(
@@ -16279,6 +17063,51 @@ var DevLeadService = class extends Service {
16279
17063
  );
16280
17064
  }
16281
17065
  }
17066
+ /**
17067
+ * Read the persistence ground truth under the readiness deadline. The real
17068
+ * backend honors the signal; the race is a belt-and-braces bound for a
17069
+ * backend that ignores it, so plugin load can never hang on the probe.
17070
+ * @param deadline - absolute readiness deadline.
17071
+ * @returns the probe result, or undefined when the deadline is already spent
17072
+ * or the listing did not settle in time.
17073
+ */
17074
+ async probeCorpus(deadline) {
17075
+ if (this.disposed) return void 0;
17076
+ const remaining = deadline - Date.now();
17077
+ if (remaining <= 0) return void 0;
17078
+ const controller = new AbortController();
17079
+ const timer = setTimeout(() => controller.abort(), remaining);
17080
+ try {
17081
+ const aborted2 = new Promise((resolve) => {
17082
+ controller.signal.addEventListener("abort", () => resolve(void 0), { once: true });
17083
+ });
17084
+ return await Promise.race([persistedSessionsOf(this.ctx, controller.signal), aborted2]);
17085
+ } finally {
17086
+ clearTimeout(timer);
17087
+ }
17088
+ }
17089
+ /** Resolve a short readiness sleep early when the plugin is disposed. */
17090
+ async readinessSleep(milliseconds) {
17091
+ if (this.disposed) return;
17092
+ await new Promise((resolve) => {
17093
+ this.readinessWake = resolve;
17094
+ this.readinessTimer = setTimeout(() => {
17095
+ this.readinessTimer = void 0;
17096
+ this.readinessWake = void 0;
17097
+ resolve();
17098
+ }, milliseconds);
17099
+ });
17100
+ }
17101
+ /** Wake the active readiness sleep (if any) after disposal. */
17102
+ wakeReadiness() {
17103
+ if (this.readinessTimer !== void 0) {
17104
+ clearTimeout(this.readinessTimer);
17105
+ this.readinessTimer = void 0;
17106
+ }
17107
+ const wake = this.readinessWake;
17108
+ this.readinessWake = void 0;
17109
+ wake?.();
17110
+ }
16282
17111
  /**
16283
17112
  * Whether one corpus listing contains every expected Session id.
16284
17113
  * @param listed - ids visible in the query corpus.
@@ -16297,19 +17126,30 @@ var DevLeadService = class extends Service {
16297
17126
  * Before its optional persistence binding is installed the query engine merges
16298
17127
  * only live Sessions, so this is the number the readiness barrier compares
16299
17128
  * against the persistence service's complete stored listing.
17129
+ * @param deadline - absolute readiness deadline for the listing read.
16300
17130
  * @returns the visible persisted Session ids.
16301
17131
  */
16302
- async listedPersistedSessionIds() {
17132
+ async listedPersistedSessionIds(deadline) {
16303
17133
  const query = this.ctx.get("sessionQuery");
16304
17134
  if (query === void 0) return /* @__PURE__ */ new Set();
17135
+ const remaining = deadline - Date.now();
17136
+ if (remaining <= 0) return /* @__PURE__ */ new Set();
17137
+ const controller = new AbortController();
17138
+ const timer = setTimeout(() => controller.abort(), remaining);
16305
17139
  try {
16306
- const records = await query.listSessions();
17140
+ const aborted2 = new Promise((resolve) => {
17141
+ controller.signal.addEventListener("abort", () => resolve(void 0), { once: true });
17142
+ });
17143
+ const records = await Promise.race([query.listSessions(controller.signal), aborted2]);
17144
+ if (records === void 0) return /* @__PURE__ */ new Set();
16307
17145
  return new Set(
16308
17146
  records.filter((record2) => record2.persisted).map((record2) => String(record2.header.id))
16309
17147
  );
16310
17148
  } catch (error51) {
16311
17149
  this.ctx.logger.debug(`devlead: corpus readiness listing failed: ${thrownMessage(error51)}`);
16312
17150
  return /* @__PURE__ */ new Set();
17151
+ } finally {
17152
+ clearTimeout(timer);
16313
17153
  }
16314
17154
  }
16315
17155
  /**
@@ -16320,6 +17160,12 @@ var DevLeadService = class extends Service {
16320
17160
  finalizeRehydration() {
16321
17161
  this.rehydrated = true;
16322
17162
  this.disposeRehydrationRetry();
17163
+ if (this.initialized && !this.disposed) {
17164
+ void this.reconcileActiveSessions(this.activeSessionId, {
17165
+ includePersisted: false,
17166
+ knownActive: this.recoveredActive
17167
+ });
17168
+ }
16323
17169
  }
16324
17170
  /** Dispose every armed readiness-retry hook. */
16325
17171
  disposeRehydrationRetry() {
@@ -16364,6 +17210,14 @@ var DevLeadService = class extends Service {
16364
17210
  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"
16365
17211
  );
16366
17212
  }
17213
+ /** Whether the durable report outbox is open and usable. */
17214
+ get reportOutboxAvailable() {
17215
+ return this.outbox?.available === true;
17216
+ }
17217
+ /** Last durable-outbox failure, exposed for the E2E probe and diagnostics. */
17218
+ get reportOutboxLastError() {
17219
+ return this.outbox?.lastError;
17220
+ }
16367
17221
  /** Deployment configuration after validation; read-only. */
16368
17222
  get settings() {
16369
17223
  return this.resolved;
@@ -16407,7 +17261,7 @@ var DevLeadService = class extends Service {
16407
17261
  }
16408
17262
  /**
16409
17263
  * Save one Session's DevLead selection. Human-entry points own this call: the
16410
- * `/devlead` command and the browser switch, never a model tool.
17264
+ * `/devlead` command and the composer-toolbar toggle, never a model tool.
16411
17265
  * @param agent - exact live Session Agent receiving the selection.
16412
17266
  * @param enabled - selected mode.
16413
17267
  * @param signal - cancellation checked before the write.
@@ -16416,23 +17270,43 @@ var DevLeadService = class extends Service {
16416
17270
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
16417
17271
  */
16418
17272
  async setEnabled(agent, enabled, signal) {
16419
- this.assertLive(agent);
16420
- signal?.throwIfAborted();
16421
- const current = this.projectionHandle.stateOf(agent.session);
16422
- if (current.failure !== null) {
17273
+ await this.withAdmission(async () => {
17274
+ this.assertLive(agent);
17275
+ signal?.throwIfAborted();
17276
+ const current = this.projectionHandle.stateOf(agent.session);
17277
+ if (current.failure !== null) {
17278
+ if (enabled) {
17279
+ throw new DevLeadError(
17280
+ `DevLead state for Session "${agent.id}" is damaged (${current.failure}); run /devlead reset first to discard the damaged watch set and notification digest`,
17281
+ "DEVLEAD_PROJECTION_INVALID"
17282
+ );
17283
+ }
17284
+ this.appendResetRecord(agent.session);
17285
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
17286
+ await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
17287
+ if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17288
+ return;
17289
+ }
17290
+ if (current.enabled === enabled) {
17291
+ if (enabled) this.activeSessionId = String(agent.id);
17292
+ return;
17293
+ }
16423
17294
  if (enabled) {
16424
- throw new DevLeadError(
16425
- `DevLead state for Session "${agent.id}" is damaged (${current.failure}); run /devlead reset first to discard the damaged watch set and notification digest`,
16426
- "DEVLEAD_PROJECTION_INVALID"
16427
- );
17295
+ const blocker = await this.blockingOccupant(agent, signal);
17296
+ if (blocker !== void 0) {
17297
+ throw new DevLeadError(
17298
+ alreadyActiveMessage(blocker),
17299
+ "DEVLEAD_ALREADY_ACTIVE"
17300
+ );
17301
+ }
16428
17302
  }
16429
- this.appendResetRecord(agent.session);
16430
- await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
16431
- return;
16432
- }
16433
- if (current.enabled === enabled) return;
16434
- appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
16435
- await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
17303
+ appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
17304
+ await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
17305
+ await this.checkpointProjectionCache(agent.session, `DevLead mode for Session "${agent.id}"`);
17306
+ if (enabled) this.activeSessionId = String(agent.id);
17307
+ else if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17308
+ if (enabled) void this.replayOutbox();
17309
+ });
16436
17310
  }
16437
17311
  /**
16438
17312
  * Discard one Session's durable DevLead state so a damaged fold can recover.
@@ -16448,10 +17322,16 @@ var DevLeadService = class extends Service {
16448
17322
  * @throws {@link DevLeadError} when the Agent is not live.
16449
17323
  */
16450
17324
  async reset(agent, signal) {
16451
- this.assertLive(agent);
16452
- signal?.throwIfAborted();
16453
- this.appendResetRecord(agent.session);
16454
- await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
17325
+ await this.withAdmission(async () => {
17326
+ this.assertLive(agent);
17327
+ signal?.throwIfAborted();
17328
+ this.appendResetRecord(agent.session);
17329
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
17330
+ await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
17331
+ await this.outbox?.dropForLead(String(agent.id));
17332
+ this.ignoredArchived.delete(String(agent.id));
17333
+ if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17334
+ });
16455
17335
  }
16456
17336
  /**
16457
17337
  * Append one reset marker to a Session log.
@@ -16469,6 +17349,7 @@ var DevLeadService = class extends Service {
16469
17349
  * @returns detached Workspace views in registry order.
16470
17350
  */
16471
17351
  async listWorkspaces(signal) {
17352
+ signal?.throwIfAborted();
16472
17353
  const registry2 = this.ctx.get("workspaceRegistry");
16473
17354
  if (registry2 === void 0) return [];
16474
17355
  const views = [];
@@ -16606,9 +17487,10 @@ var DevLeadService = class extends Service {
16606
17487
  const listingCap = options.watchedOnly === true ? Math.max(this.resolved.maxListedSessions, deps.watchedSessions.length) : this.resolved.maxListedSessions;
16607
17488
  const requestedLimit = listLimit(options.limit, listingCap);
16608
17489
  const limit = options.watchedOnly === true ? Math.max(requestedLimit, deps.watchedSessions.length) : requestedLimit;
16609
- const facts = await readSessionFacts(deps, ids);
17490
+ const ranking = await sessionRankFacts(deps, ids);
16610
17491
  signal?.throwIfAborted();
16611
- const retained = rankSessionIds(deps, ids, facts, limit);
17492
+ const retained = rankSessionIds(deps, ids, ranking, limit);
17493
+ const facts = await readSessionFacts(deps, retained);
16612
17494
  return await devLeadSessionViews(deps, retained, false, facts);
16613
17495
  }
16614
17496
  /**
@@ -16648,6 +17530,52 @@ var DevLeadService = class extends Service {
16648
17530
  signal?.throwIfAborted();
16649
17531
  return devLeadModelCatalogOf(catalog);
16650
17532
  }
17533
+ /**
17534
+ * Read the Host's Agent preset roster for creation-time preset selection.
17535
+ *
17536
+ * The roster is optional: a Host that composes no Agent preset service
17537
+ * returns `available: false` with a reason instead of an empty list that
17538
+ * could be mistaken for "no presets defined". When the service is present,
17539
+ * rows are normalized onto the stable protocol view; a row without a usable
17540
+ * id is dropped, and the Host's effective default gets the `default` marker.
17541
+ * This is a read-only capability: no Session, profile default, or preset is
17542
+ * changed.
17543
+ * @param agent - exact live lead Agent.
17544
+ * @param signal - cancellation checked before and after the roster read.
17545
+ * @returns the roster view, or an explicit unavailable result.
17546
+ * @throws {@link DevLeadError} `DEVLEAD_SESSION_UNAVAILABLE` when a composed
17547
+ * roster fails a read.
17548
+ */
17549
+ async listAgentPresets(agent, signal) {
17550
+ this.assertReady(agent);
17551
+ signal?.throwIfAborted();
17552
+ const roster = agentPresetRosterCapabilityOf(this.ctx);
17553
+ if (roster === void 0) {
17554
+ return {
17555
+ available: false,
17556
+ presets: [],
17557
+ reason: "this Host composes no Agent preset roster; omit preset to use the Host default"
17558
+ };
17559
+ }
17560
+ let rows;
17561
+ try {
17562
+ rows = await roster.list();
17563
+ if (!Array.isArray(rows)) {
17564
+ throw new Error("the roster service returned no array");
17565
+ }
17566
+ } catch (error51) {
17567
+ signal?.throwIfAborted();
17568
+ throw new DevLeadError(
17569
+ `could not read the Agent preset roster: ${thrownMessage(error51)}`,
17570
+ "DEVLEAD_SESSION_UNAVAILABLE"
17571
+ );
17572
+ }
17573
+ signal?.throwIfAborted();
17574
+ return {
17575
+ available: true,
17576
+ presets: devLeadAgentPresetsOf(rows, roster.defaultId)
17577
+ };
17578
+ }
16651
17579
  /**
16652
17580
  * Read one Session in detail, including folded turn and assistant facts.
16653
17581
  * @param agent - exact live lead Agent.
@@ -16949,6 +17877,272 @@ var DevLeadService = class extends Service {
16949
17877
  const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
16950
17878
  return state.notifications.slice(-effective);
16951
17879
  }
17880
+ /** Open the optional durable outbox once and load its archived-holder tombstones. */
17881
+ async openOutbox() {
17882
+ if (this.outbox !== void 0 || this.outboxOpening !== void 0) return;
17883
+ const run = (async () => {
17884
+ const outbox = await DevLeadReportOutbox.open(this.ctx);
17885
+ if (outbox === void 0) {
17886
+ this.ctx.logger.debug(
17887
+ "devlead: no storage-domain service is composed; reports use the explicit non-durable fallback"
17888
+ );
17889
+ return;
17890
+ }
17891
+ this.outbox = outbox;
17892
+ for (const sessionId of outbox.ignoredIds()) this.ignoredArchived.add(sessionId);
17893
+ await outbox.prune();
17894
+ })();
17895
+ this.outboxOpening = run;
17896
+ try {
17897
+ await run;
17898
+ } finally {
17899
+ this.outboxOpening = void 0;
17900
+ }
17901
+ }
17902
+ /**
17903
+ * Replay durable outbox rows whose lead is now attachable, then clear each
17904
+ * row only after its Session-log receipt was flushed.
17905
+ */
17906
+ async replayOutbox() {
17907
+ if (this.disposed || this.outbox === void 0 || this.outboxReplaying) return;
17908
+ this.outboxReplaying = true;
17909
+ try {
17910
+ await this.outbox.prune();
17911
+ const archived = new Set(
17912
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
17913
+ );
17914
+ let waiting = 0;
17915
+ for (const entry of this.outbox.entries()) {
17916
+ if (this.disposed) return;
17917
+ const report = entry.report;
17918
+ if (archived.has(report.leadSessionId)) {
17919
+ waiting += 1;
17920
+ continue;
17921
+ }
17922
+ let delivered = false;
17923
+ try {
17924
+ delivered = await this.hub?.persistReport(report) ?? false;
17925
+ } catch (error51) {
17926
+ this.ctx.logger.warn(
17927
+ `devlead: could not replay report "${report.id}": ${thrownMessage(error51)}`
17928
+ );
17929
+ }
17930
+ if (delivered) await this.outbox.delete(report);
17931
+ else waiting += 1;
17932
+ }
17933
+ if (waiting > 0) {
17934
+ this.ctx.logger.warn(
17935
+ `devlead: ${String(waiting)} durable report(s) wait for their lead Session or watch relationship to return`
17936
+ );
17937
+ }
17938
+ } finally {
17939
+ this.outboxReplaying = false;
17940
+ }
17941
+ }
17942
+ /**
17943
+ * Persist a report in the durable outbox (when available) and try to write
17944
+ * its lead receipt. The outbox row is only removed after the lead flush
17945
+ * succeeded; otherwise the report remains replayable.
17946
+ * @param report - validated report.
17947
+ * @returns the child-facing receipt with durability status.
17948
+ */
17949
+ async deliverReport(report) {
17950
+ const outboxed = this.outbox === void 0 ? false : await this.outbox.put(report);
17951
+ if (outboxed && this.outbox !== void 0) {
17952
+ let delivered = false;
17953
+ try {
17954
+ delivered = await this.hub?.persistReport(report) ?? false;
17955
+ } catch (error51) {
17956
+ this.ctx.logger.warn(
17957
+ `devlead: report "${report.id}" is durable but its first delivery attempt failed: ${thrownMessage(error51)}`
17958
+ );
17959
+ }
17960
+ if (delivered) await this.outbox.delete(report);
17961
+ return {
17962
+ report,
17963
+ durable: true,
17964
+ queued: !delivered
17965
+ };
17966
+ }
17967
+ const accepted = this.hub?.report(report) ?? false;
17968
+ if (!accepted) {
17969
+ throw new DevLeadError(
17970
+ "the active DevLead Session stopped watching this Session before the report could be queued",
17971
+ "DEVLEAD_NOT_SUPERVISED"
17972
+ );
17973
+ }
17974
+ return {
17975
+ report,
17976
+ durable: false,
17977
+ queued: true,
17978
+ warning: "durable report storage is unavailable on this Host; the receipt is queued in memory and may be lost if the Host exits before the lead consumes it" + (this.outbox?.lastError === void 0 ? "" : ` (${this.outbox.lastError})`)
17979
+ };
17980
+ }
17981
+ /**
17982
+ * Resolve the unique active DevLead Session supervising one reporter.
17983
+ *
17984
+ * The hub's reverse index already reflects durable watch/mode state (live and
17985
+ * cold rehydrated leads). Archived leads are excluded, and when historical
17986
+ * state leaves more than one watcher the current global incumbent wins; with
17987
+ * no unique answer the reporter is treated as unsupervised instead of
17988
+ * broadcasting to an arbitrary lead.
17989
+ * @param agent - candidate watched Session Agent.
17990
+ * @returns the supervising lead Session id, or undefined.
17991
+ */
17992
+ supervisorOf(agent) {
17993
+ if (this.hub === void 0) return void 0;
17994
+ if (this.ctx.agents.get(agent.id) !== agent) return void 0;
17995
+ if (this.isEnabled(agent)) return void 0;
17996
+ const archived = new Set(
17997
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
17998
+ );
17999
+ const candidates = this.hub.supervisorsOf(String(agent.id)).filter((id) => !archived.has(id));
18000
+ if (candidates.length === 0) return void 0;
18001
+ if (candidates.length === 1) return candidates[0];
18002
+ return this.activeSessionId !== void 0 && candidates.includes(this.activeSessionId) ? this.activeSessionId : void 0;
18003
+ }
18004
+ /**
18005
+ * List archived Sessions that still carry a durable enabled mode.
18006
+ *
18007
+ * They are ignored by admission (an archived Session is not an active lead),
18008
+ * but the human needs a visible, actionable recovery path: unarchive and open
18009
+ * the Session to run `/devlead off`, or delete it. The list is also the
18010
+ * diagnostic surface for a tombstone that could not be cleared.
18011
+ * @param signal - cancellation threaded through the scan.
18012
+ * @returns archived holders with human labels.
18013
+ */
18014
+ async archivedOccupants(signal) {
18015
+ const active = await this.scanActiveSessions(signal);
18016
+ signal?.throwIfAborted();
18017
+ return active.filter((occupant) => occupant.archived).map((occupant) => ({
18018
+ sessionId: occupant.sessionId,
18019
+ ...occupant.title === void 0 ? {} : { title: occupant.title }
18020
+ }));
18021
+ }
18022
+ /**
18023
+ * Whether one Session may send mid-turn reports to an active DevLead.
18024
+ * @param agent - candidate reporter Agent.
18025
+ * @returns whether the reporter has exactly one usable supervisor.
18026
+ */
18027
+ isSupervised(agent) {
18028
+ return this.supervisorOf(agent) !== void 0;
18029
+ }
18030
+ /**
18031
+ * Send one mid-turn report from a watched Session to its active DevLead.
18032
+ *
18033
+ * The durable receipt is appended to the lead's own Session log (or queued
18034
+ * for a cold lead by the hub), then the lead is woken through the same
18035
+ * coalesced notice path as turn notifications. This method returns after the
18036
+ * receipt/queue decision and never waits for the lead's next turn, so the
18037
+ * reporter is not blocked. Same-message reports in one turn are idempotent;
18038
+ * more than {@link DEVLEAD_REPORT_MAX_PER_TURN} distinct reports in one turn
18039
+ * are refused.
18040
+ * @param agent - exact live reporter Agent.
18041
+ * @param request - report text, kind, and optional summary.
18042
+ * @param signal - cancellation checked before durable work.
18043
+ * @returns the report receipt, including whether it is durable and still queued.
18044
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_SUPERVISED` when no unique active
18045
+ * lead watches the reporter, `DEVLEAD_INVALID_INPUT` for unusable fields,
18046
+ * and `DEVLEAD_REPORT_RATE_LIMITED` when the per-turn budget is exhausted.
18047
+ */
18048
+ async reportProgress(agent, request, signal) {
18049
+ this.assertLive(agent);
18050
+ signal?.throwIfAborted();
18051
+ if (this.isEnabled(agent)) {
18052
+ throw new DevLeadError(
18053
+ "this Session is the active DevLead; a DevLead Session cannot report to itself",
18054
+ "DEVLEAD_NOT_SUPERVISED"
18055
+ );
18056
+ }
18057
+ const leadSessionId = this.supervisorOf(agent);
18058
+ if (leadSessionId === void 0) {
18059
+ throw new DevLeadError(
18060
+ "this Session is not watched by the unique active DevLead Session, so it cannot send a report",
18061
+ "DEVLEAD_NOT_SUPERVISED"
18062
+ );
18063
+ }
18064
+ const message = request.message.trim();
18065
+ if (message.length === 0) {
18066
+ throw new DevLeadError("report message must not be empty", "DEVLEAD_INVALID_INPUT");
18067
+ }
18068
+ if (message.length > DEVLEAD_REPORT_MESSAGE_MAX4 * 2 || Array.from(message).length > DEVLEAD_REPORT_MESSAGE_MAX4) {
18069
+ throw new DevLeadError(
18070
+ `report message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX4} code points`,
18071
+ "DEVLEAD_INVALID_INPUT"
18072
+ );
18073
+ }
18074
+ const kind = request.kind ?? "progress";
18075
+ if (!isDevLeadReportKind2(kind)) {
18076
+ throw new DevLeadError(
18077
+ `report kind ${JSON.stringify(kind)} is not recognized; use progress, blocked, decision, or fyi`,
18078
+ "DEVLEAD_INVALID_INPUT"
18079
+ );
18080
+ }
18081
+ const summary = request.summary?.trim();
18082
+ if (summary !== void 0 && (summary.length === 0 || summary.length > DEVLEAD_REPORT_SUMMARY_MAX4 * 2 || Array.from(summary).length > DEVLEAD_REPORT_SUMMARY_MAX4)) {
18083
+ throw new DevLeadError(
18084
+ `report summary must be 1-${DEVLEAD_REPORT_SUMMARY_MAX4} code points when present`,
18085
+ "DEVLEAD_INVALID_INPUT"
18086
+ );
18087
+ }
18088
+ const reporterId = String(agent.id);
18089
+ const turn = this.ctx.agents.turnBoundaryOf(agent.session).lastTurn;
18090
+ const previous = this.reportState.get(reporterId);
18091
+ const state = previous !== void 0 && previous.turn === turn && previous.leadSessionId === leadSessionId ? previous : { turn, leadSessionId, messages: /* @__PURE__ */ new Map() };
18092
+ if (previous === void 0 || previous.turn !== turn || previous.leadSessionId !== leadSessionId) {
18093
+ this.reportState.set(reporterId, state);
18094
+ }
18095
+ const duplicate = state.messages.get(message);
18096
+ if (duplicate !== void 0) return duplicate;
18097
+ if (state.messages.size >= DEVLEAD_REPORT_MAX_PER_TURN) {
18098
+ throw new DevLeadError(
18099
+ `this Session already sent ${DEVLEAD_REPORT_MAX_PER_TURN} reports in turn ${turn}; wait for the next turn or let the DevLead continue`,
18100
+ "DEVLEAD_REPORT_RATE_LIMITED"
18101
+ );
18102
+ }
18103
+ const title = this.ctx.get("sessionTitle")?.get(agent.session)?.title;
18104
+ let senderWorkspaceId;
18105
+ let senderWorkspaceTitle;
18106
+ for (const workspace of this.ctx.get("workspaceRegistry")?.list() ?? []) {
18107
+ if (!workspace.sessionIds.some((id) => String(id) === reporterId)) continue;
18108
+ senderWorkspaceId = workspace.id;
18109
+ senderWorkspaceTitle = workspace.title;
18110
+ break;
18111
+ }
18112
+ const report = devLeadReport({
18113
+ senderSessionId: reporterId,
18114
+ ...title === void 0 ? {} : { senderSessionTitle: title },
18115
+ ...senderWorkspaceId === void 0 ? {} : { senderWorkspaceId },
18116
+ ...senderWorkspaceTitle === void 0 ? {} : { senderWorkspaceTitle },
18117
+ leadSessionId,
18118
+ turn,
18119
+ kind,
18120
+ message,
18121
+ ...summary === void 0 ? {} : { summary },
18122
+ at: Date.now()
18123
+ });
18124
+ signal?.throwIfAborted();
18125
+ const receipt = await this.deliverReport(report);
18126
+ state.messages.set(message, receipt);
18127
+ if (this.reportState.size > 512) {
18128
+ const oldest = this.reportState.keys().next().value;
18129
+ if (oldest !== void 0) this.reportState.delete(oldest);
18130
+ }
18131
+ return receipt;
18132
+ }
18133
+ /**
18134
+ * Read the retained mid-turn report digest of one live lead.
18135
+ * @param agent - exact live lead Agent.
18136
+ * @param options - optional newest-row limit, defaulting to 20.
18137
+ * @returns detached reports, oldest first.
18138
+ */
18139
+ reports(agent, options = {}) {
18140
+ this.assertReady(agent);
18141
+ const state = this.strictStateOf(agent.session);
18142
+ const limit = options.limit ?? 20;
18143
+ const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
18144
+ return state.reports.slice(-effective);
18145
+ }
16952
18146
  // ---------------------------------------------------------------------------
16953
18147
  // Internals
16954
18148
  // ---------------------------------------------------------------------------
@@ -17020,6 +18214,336 @@ var DevLeadService = class extends Service {
17020
18214
  this.ctx.logger.warn(`devlead: ${what} could not be flushed to persistence: ${thrownMessage(error51)}`);
17021
18215
  }
17022
18216
  }
18217
+ /**
18218
+ * Eagerly checkpoint the optional Session projection cache after a durable
18219
+ * DevLead mode/watch/reset write.
18220
+ *
18221
+ * Cold rehydration trusts a cached "disabled/empty watch" row as a negative
18222
+ * pre-filter, and the cache's normal write-behind can lag the log by its
18223
+ * throttled interval. Without this eager write a crash in that window leaves
18224
+ * a stale negative row that hides a real cold lead until a human opens it.
18225
+ * The write is best-effort: a cache that is absent or fails only leaves the
18226
+ * throttled checkpoint in place, and the scan's exact fold still recovers the
18227
+ * lead whenever the row is positive or unclassified.
18228
+ * @param session - Session whose durable DevLead state just changed.
18229
+ * @param what - operation label for the failure warning.
18230
+ */
18231
+ async checkpointProjectionCache(session, what) {
18232
+ const cache = projectionCacheOf(this.ctx);
18233
+ if (cache?.write === void 0) return;
18234
+ try {
18235
+ await cache.write(session);
18236
+ } catch (error51) {
18237
+ this.ctx.logger.warn(`devlead: ${what} could not be checkpointed into the Session projection cache: ${thrownMessage(error51)}`);
18238
+ }
18239
+ }
18240
+ /**
18241
+ * Serialize one global-mode critical section. Every admission waits for the
18242
+ * previous one, so two concurrent enables cannot both scan an empty Host and
18243
+ * then both append. The tail promise is released in `finally`, including on
18244
+ * a rejected admission.
18245
+ * @param body - critical section to run exclusively.
18246
+ * @returns the body result.
18247
+ */
18248
+ async withAdmission(body) {
18249
+ const previous = this.admissionTail;
18250
+ let release;
18251
+ this.admissionTail = new Promise((resolve) => {
18252
+ release = resolve;
18253
+ });
18254
+ await previous;
18255
+ try {
18256
+ return await body();
18257
+ } finally {
18258
+ release();
18259
+ }
18260
+ }
18261
+ /**
18262
+ * Find an enabled Session other than `agent`, releasing archived holders
18263
+ * first. This is the admission check under the global mutex.
18264
+ * @param agent - Session requesting the mode.
18265
+ * @param signal - caller cancellation checked around the scan and releases.
18266
+ * @returns the blocking occupant, or undefined when the mode is free.
18267
+ */
18268
+ async blockingOccupant(agent, signal) {
18269
+ const active = await this.scanActiveSessions(signal);
18270
+ const blockers = [];
18271
+ for (const occupant of active) {
18272
+ if (occupant.sessionId === String(agent.id)) continue;
18273
+ if (occupant.archived) {
18274
+ signal?.throwIfAborted();
18275
+ if (await this.releaseActiveOccupant(occupant, "archived")) {
18276
+ await this.rememberReleased(occupant.sessionId);
18277
+ } else {
18278
+ await this.rememberIgnored(occupant.sessionId);
18279
+ this.ctx.logger.warn(
18280
+ `devlead: archived Session "${occupant.sessionId}" is ignored for admission; unarchive and open it to run /devlead off, or delete it`
18281
+ );
18282
+ }
18283
+ continue;
18284
+ }
18285
+ if (this.ignoredArchived.has(occupant.sessionId)) {
18286
+ if (await this.releaseActiveOccupant(occupant, "duplicate")) {
18287
+ await this.rememberReleased(occupant.sessionId);
18288
+ }
18289
+ continue;
18290
+ }
18291
+ blockers.push(occupant);
18292
+ }
18293
+ signal?.throwIfAborted();
18294
+ return blockers.length === 0 ? void 0 : rankActiveSessions(blockers, this.activeSessionId)[0];
18295
+ }
18296
+ /**
18297
+ * Scan every live and persisted Session for an enabled DevLead mode.
18298
+ *
18299
+ * Live Sessions are authoritative directly from the projection handle. Cold
18300
+ * Sessions use the projection cache as a zero-I/O pre-filter: `active` rows
18301
+ * are folded exactly, `inactive` rows are skipped, and rows the cache cannot
18302
+ * classify (including a Host with no cache) are folded up to a bounded read
18303
+ * budget. The budget only limits an arbitrarily large unknown history and is
18304
+ * reported; positively active rows are never skipped.
18305
+ * @param signal - caller cancellation threaded through query reads.
18306
+ * @returns every enabled Session, deduplicated by id.
18307
+ */
18308
+ async scanActiveSessions(signal, includePersisted = true) {
18309
+ const active = /* @__PURE__ */ new Map();
18310
+ const seen = /* @__PURE__ */ new Set();
18311
+ const archived = new Set(
18312
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
18313
+ );
18314
+ const addLive = (session) => {
18315
+ const sessionId = String(session.id);
18316
+ if (seen.has(sessionId)) return;
18317
+ seen.add(sessionId);
18318
+ const state = this.projectionHandle.stateOf(session);
18319
+ if (state.failure !== null || !state.enabled) return;
18320
+ const title = this.ctx.get("sessionTitle")?.get(session)?.title;
18321
+ const agent = this.ctx.agents.get(session.id);
18322
+ active.set(sessionId, {
18323
+ sessionId,
18324
+ ...title === void 0 || title.trim().length === 0 ? {} : { title },
18325
+ live: true,
18326
+ archived: archived.has(sessionId),
18327
+ running: agent?.status === "running",
18328
+ createdAt: session.header.createdAt,
18329
+ enabledAt: 0
18330
+ });
18331
+ };
18332
+ for (const agent of this.ctx.agents.list()) addLive(agent.session);
18333
+ for (const session of this.ctx.sessions.list()) addLive(session);
18334
+ signal?.throwIfAborted();
18335
+ if (!includePersisted) return [...active.values()];
18336
+ const query = this.ctx.get("sessionQuery");
18337
+ if (query === void 0) return [...active.values()];
18338
+ let records;
18339
+ try {
18340
+ records = await query.listSessions(signal);
18341
+ } catch (error51) {
18342
+ if (signal?.aborted === true) throw error51;
18343
+ this.ctx.logger.warn(`devlead: could not list persisted Sessions for global DevLead admission: ${thrownMessage(error51)}`);
18344
+ return [...active.values()];
18345
+ }
18346
+ const cache = projectionCacheOf(this.ctx);
18347
+ let unknownReads = 0;
18348
+ let capped = false;
18349
+ let warnedRead = false;
18350
+ for (const record2 of records) {
18351
+ signal?.throwIfAborted();
18352
+ const sessionId = String(record2.header.id);
18353
+ if (seen.has(sessionId)) continue;
18354
+ const prefilter = cache === void 0 ? "unknown" : devLeadActivePrefilterOf(cache, record2.header);
18355
+ if (prefilter === "inactive") {
18356
+ seen.add(sessionId);
18357
+ continue;
18358
+ }
18359
+ if (prefilter === "unknown") {
18360
+ if (unknownReads >= MAX_ACTIVE_SCAN_UNKNOWN_READS) {
18361
+ capped = true;
18362
+ continue;
18363
+ }
18364
+ unknownReads += 1;
18365
+ }
18366
+ seen.add(sessionId);
18367
+ let events;
18368
+ try {
18369
+ events = (await query.readSession(record2.header.id)).events;
18370
+ } catch (error51) {
18371
+ if (signal?.aborted === true) throw error51;
18372
+ if (!warnedRead) {
18373
+ warnedRead = true;
18374
+ this.ctx.logger.warn(`devlead: could not read a persisted Session log for global DevLead admission: ${thrownMessage(error51)}`);
18375
+ }
18376
+ continue;
18377
+ }
18378
+ let state = emptyDevLeadProjectionState();
18379
+ for (const event of events) {
18380
+ state = applyDevLeadProjection(state, event);
18381
+ if (state.failure !== null) break;
18382
+ }
18383
+ if (state.failure !== null || !state.enabled) continue;
18384
+ active.set(sessionId, {
18385
+ sessionId,
18386
+ live: false,
18387
+ archived: archived.has(sessionId),
18388
+ running: false,
18389
+ createdAt: record2.header.createdAt,
18390
+ enabledAt: lastEnabledAt(events) ?? 0
18391
+ });
18392
+ }
18393
+ if (capped) {
18394
+ this.ctx.logger.warn(
18395
+ `devlead: global DevLead admission scanned only ${MAX_ACTIVE_SCAN_UNKNOWN_READS} unclassified persisted Session logs; compose projection cache rows to make the single-active check exhaustive`
18396
+ );
18397
+ }
18398
+ return [...active.values()];
18399
+ }
18400
+ /**
18401
+ * Durably disable one active occupant so the global slot becomes free.
18402
+ *
18403
+ * A live Session (or Agent-owned Session) is appended directly. A cold
18404
+ * Session is resumed through the optional Session controller first; without
18405
+ * that capability the release fails softly and the caller reports the
18406
+ * occupant, rather than clearing a durable mode the Host cannot rewrite.
18407
+ * @param occupant - active Session to disable.
18408
+ * @param reason - `archived` or `duplicate`, recorded in the warning.
18409
+ * @returns whether the durable mode is now off (or already was).
18410
+ */
18411
+ async releaseActiveOccupant(occupant, reason) {
18412
+ let session = this.ctx.sessions.get(toSessionId3(occupant.sessionId));
18413
+ if (session === void 0) {
18414
+ const controller = this.ctx.get("sessionController");
18415
+ if (controller === void 0) {
18416
+ this.ctx.logger.warn(
18417
+ `devlead: Session "${occupant.sessionId}" still holds DevLead mode but is cold and no Session controller can resume it to release the slot`
18418
+ );
18419
+ return false;
18420
+ }
18421
+ try {
18422
+ const resolved = await controller.resolveAgent(toSessionId3(occupant.sessionId));
18423
+ if ("error" in resolved) {
18424
+ this.ctx.logger.warn(
18425
+ `devlead: could not resume DevLead occupant "${occupant.sessionId}" to release the slot: ${resolved.error.message}`
18426
+ );
18427
+ return false;
18428
+ }
18429
+ session = resolved.agent.session;
18430
+ } catch (error51) {
18431
+ this.ctx.logger.warn(
18432
+ `devlead: could not resume DevLead occupant "${occupant.sessionId}" to release the slot: ${thrownMessage(error51)}`
18433
+ );
18434
+ return false;
18435
+ }
18436
+ }
18437
+ try {
18438
+ const state = this.projectionHandle.stateOf(session);
18439
+ if (state.failure !== null) {
18440
+ this.ctx.logger.warn(
18441
+ `devlead: cannot release DevLead occupant "${occupant.sessionId}": its projection is damaged (${state.failure})`
18442
+ );
18443
+ return false;
18444
+ }
18445
+ if (state.enabled) {
18446
+ appendPluginRecord2(session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(false, Date.now()));
18447
+ await this.flushDurably(session, `DevLead release for Session "${occupant.sessionId}"`);
18448
+ await this.checkpointProjectionCache(session, `DevLead release for Session "${occupant.sessionId}"`);
18449
+ }
18450
+ } catch (error51) {
18451
+ this.ctx.logger.warn(
18452
+ `devlead: could not release DevLead occupant "${occupant.sessionId}": ${thrownMessage(error51)}`
18453
+ );
18454
+ return false;
18455
+ }
18456
+ if (this.activeSessionId === occupant.sessionId) this.activeSessionId = void 0;
18457
+ this.ctx.logger.warn(
18458
+ `devlead: disabled DevLead mode for Session "${occupant.sessionId}" (${reason}); only one Session may hold DevLead mode at a time`
18459
+ );
18460
+ await this.rememberReleased(occupant.sessionId);
18461
+ return true;
18462
+ }
18463
+ /** Remember one ignored archived holder in memory and, when available, durably. */
18464
+ async rememberIgnored(sessionId) {
18465
+ this.ignoredArchived.add(sessionId);
18466
+ await this.outbox?.rememberIgnored(sessionId);
18467
+ }
18468
+ /** Forget one ignored-holder tombstone after a successful release. */
18469
+ async rememberReleased(sessionId) {
18470
+ if (!this.ignoredArchived.delete(sessionId)) return;
18471
+ await this.outbox?.forgetIgnored(sessionId);
18472
+ }
18473
+ /**
18474
+ * Reconcile a Host that already has (or has recovered) multiple enabled
18475
+ * Sessions.
18476
+ *
18477
+ * Archived holders are released first. The remaining occupants are ranked
18478
+ * deterministically; the preferred/live/newest one stays enabled and every
18479
+ * other is durably disabled with a warning. If a cold holder cannot be
18480
+ * resumed, it is left enabled and keeps blocking new admissions, which is
18481
+ * safer than silently creating a second active Session.
18482
+ * @param preferredSessionId - incumbent to keep when it is still active.
18483
+ */
18484
+ async reconcileActiveSessions(preferredSessionId, options = {}) {
18485
+ if (this.disposed) return;
18486
+ try {
18487
+ await this.withAdmission(async () => {
18488
+ if (this.disposed) return;
18489
+ const scanned = await this.scanActiveSessions(void 0, options.includePersisted !== false);
18490
+ const merged = /* @__PURE__ */ new Map();
18491
+ for (const occupant of options.knownActive ?? []) merged.set(occupant.sessionId, occupant);
18492
+ for (const occupant of scanned) merged.set(occupant.sessionId, occupant);
18493
+ const liveIds = /* @__PURE__ */ new Set();
18494
+ for (const agent of this.ctx.agents.list()) liveIds.add(String(agent.id));
18495
+ for (const session of this.ctx.sessions.list()) liveIds.add(String(session.id));
18496
+ for (const sessionId of liveIds) {
18497
+ if (!scanned.some((occupant) => occupant.sessionId === sessionId)) merged.delete(sessionId);
18498
+ }
18499
+ const active = [...merged.values()];
18500
+ if (active.length === 0) {
18501
+ this.activeSessionId = void 0;
18502
+ return;
18503
+ }
18504
+ const remaining = [];
18505
+ for (const occupant of active) {
18506
+ if (occupant.archived) {
18507
+ if (!await this.releaseActiveOccupant(occupant, "archived")) {
18508
+ await this.rememberIgnored(occupant.sessionId);
18509
+ this.ctx.logger.warn(
18510
+ `devlead: archived Session "${occupant.sessionId}" still has DevLead mode enabled but is ignored for admission; unarchive and open it to run /devlead off, or delete it`
18511
+ );
18512
+ }
18513
+ continue;
18514
+ }
18515
+ if (this.ignoredArchived.has(occupant.sessionId)) {
18516
+ if (await this.releaseActiveOccupant(occupant, "duplicate")) {
18517
+ await this.rememberReleased(occupant.sessionId);
18518
+ }
18519
+ continue;
18520
+ }
18521
+ remaining.push(occupant);
18522
+ }
18523
+ if (remaining.length === 0) {
18524
+ this.activeSessionId = void 0;
18525
+ return;
18526
+ }
18527
+ const ranked = rankActiveSessions(remaining, preferredSessionId ?? this.activeSessionId);
18528
+ const keeper = ranked[0];
18529
+ if (keeper === void 0) return;
18530
+ this.activeSessionId = keeper.sessionId;
18531
+ let failed = 0;
18532
+ for (const extra of ranked.slice(1)) {
18533
+ if (!await this.releaseActiveOccupant(extra, "duplicate")) failed += 1;
18534
+ }
18535
+ if (ranked.length > 1) {
18536
+ this.ctx.logger.warn(
18537
+ `devlead: found ${ranked.length} enabled Sessions after recovery; keeping "${keeper.sessionId}"` + (failed > 0 ? ` and could not disable ${failed}` : "")
18538
+ );
18539
+ }
18540
+ });
18541
+ } catch (error51) {
18542
+ if (!this.disposed) {
18543
+ this.ctx.logger.warn(`devlead: global DevLead admission reconciliation failed: ${thrownMessage(error51)}`);
18544
+ }
18545
+ }
18546
+ }
17023
18547
  /** Reject any use of a tool surface while DevLead mode is off. */
17024
18548
  assertReady(agent) {
17025
18549
  this.assertLive(agent);
@@ -17074,10 +18598,18 @@ var DevLeadService = class extends Service {
17074
18598
  */
17075
18599
  async persistedLeadRecords(scanPersisted) {
17076
18600
  const leads = /* @__PURE__ */ new Map();
18601
+ const active = [];
18602
+ const archived = new Set(
18603
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
18604
+ );
17077
18605
  const remember = (sessionId, sessions) => {
17078
18606
  if (sessionId.length === 0 || sessions.length === 0) return;
17079
18607
  leads.set(sessionId, [...sessions]);
17080
18608
  };
18609
+ const result = () => ({
18610
+ leads: [...leads].map(([sessionId, watched]) => ({ sessionId, watched })),
18611
+ active
18612
+ });
17081
18613
  for (const lead of this.liveAttachLeads()) remember(lead.sessionId, lead.watched);
17082
18614
  if (!scanPersisted) {
17083
18615
  if (this.ctx.get("sessionQuery") === void 0) {
@@ -17087,23 +18619,23 @@ var DevLeadService = class extends Service {
17087
18619
  "devlead: the Session persistence binding is not composed yet; cold lead rehydration scans live Sessions only"
17088
18620
  );
17089
18621
  }
17090
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18622
+ return result();
17091
18623
  }
17092
18624
  const query = this.ctx.get("sessionQuery");
17093
- if (query === void 0) return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18625
+ if (query === void 0) return result();
17094
18626
  const cache = projectionCacheOf(this.ctx);
17095
18627
  if (cache === void 0) {
17096
18628
  this.ctx.logger.warn(
17097
18629
  "devlead: this Host composes no Session projection cache, so cold lead rehydration reads no persisted logs; only live lead Sessions are rehydrated"
17098
18630
  );
17099
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18631
+ return result();
17100
18632
  }
17101
18633
  let records;
17102
18634
  try {
17103
18635
  records = await query.listSessions();
17104
18636
  } catch (error51) {
17105
18637
  this.ctx.logger.warn(`devlead: could not list persisted Sessions for cold lead rehydration: ${thrownMessage(error51)}`);
17106
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18638
+ return result();
17107
18639
  }
17108
18640
  let unknownReads = 0;
17109
18641
  let capped = false;
@@ -17113,8 +18645,8 @@ var DevLeadService = class extends Service {
17113
18645
  const sessionId = String(record2.header.id);
17114
18646
  if (leads.has(sessionId) || record2.live) continue;
17115
18647
  if (record2.header.origin === "subagent") continue;
17116
- const prefilter = devLeadPrefilterOf(cache, record2.header);
17117
- if (prefilter === "not-lead") continue;
18648
+ const prefilter = devLeadActivePrefilterOf(cache, record2.header);
18649
+ if (prefilter === "inactive") continue;
17118
18650
  if (prefilter === "unknown") {
17119
18651
  if (unknownReads >= MAX_COLD_LEAD_LOG_READS) {
17120
18652
  capped = true;
@@ -17144,14 +18676,23 @@ var DevLeadService = class extends Service {
17144
18676
  }
17145
18677
  continue;
17146
18678
  }
17147
- if (state.enabled) remember(sessionId, state.sessions);
18679
+ if (!state.enabled) continue;
18680
+ active.push({
18681
+ sessionId,
18682
+ live: false,
18683
+ archived: archived.has(sessionId),
18684
+ running: false,
18685
+ createdAt: record2.header.createdAt,
18686
+ enabledAt: lastEnabledAt(events) ?? 0
18687
+ });
18688
+ remember(sessionId, state.sessions);
17148
18689
  }
17149
18690
  if (capped) {
17150
18691
  this.ctx.logger.warn(
17151
18692
  `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`
17152
18693
  );
17153
18694
  }
17154
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18695
+ return result();
17155
18696
  }
17156
18697
  /**
17157
18698
  * Validate one requested model selection against the Host's LLM registry.
@@ -17509,6 +19050,8 @@ var DevLeadService = class extends Service {
17509
19050
  const next = watching ? [...state.sessions, id] : state.sessions.filter((existing) => existing !== id);
17510
19051
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
17511
19052
  await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
19053
+ await this.checkpointProjectionCache(agent.session, `watch set for lead "${agent.id}"`);
19054
+ if (watching) void this.replayOutbox();
17512
19055
  return { sessionId: id, watched: watching, sessions: next };
17513
19056
  }
17514
19057
  };
@@ -17523,6 +19066,9 @@ export {
17523
19066
  DEVLEAD_MODE_RECORD_TYPE,
17524
19067
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
17525
19068
  DEVLEAD_RECORD_VERSION,
19069
+ DEVLEAD_REPORT_MESSAGE_MAX,
19070
+ DEVLEAD_REPORT_RECORD_TYPE,
19071
+ DEVLEAD_REPORT_SUMMARY_MAX,
17526
19072
  DEVLEAD_RESET_RECORD_TYPE,
17527
19073
  DEVLEAD_WATCH_RECORD_TYPE,
17528
19074
  DevLeadError,
@@ -17535,6 +19081,8 @@ export {
17535
19081
  decodeModeRecord,
17536
19082
  decodeNotification,
17537
19083
  decodeNotificationRecord,
19084
+ decodeReport,
19085
+ decodeReportRecord,
17538
19086
  decodeResetRecord,
17539
19087
  decodeWatchRecord,
17540
19088
  index_default as default,
@@ -17547,6 +19095,7 @@ export {
17547
19095
  devLeadProjectionSchema,
17548
19096
  devLeadProjectionStateSchema,
17549
19097
  devLeadProjectionView,
19098
+ devLeadReport,
17550
19099
  emptyDevLeadModeProjectionState,
17551
19100
  emptyDevLeadProjectionState,
17552
19101
  failureExcerpt,
@@ -17555,6 +19104,7 @@ export {
17555
19104
  notificationId,
17556
19105
  notificationRecord,
17557
19106
  renderDevLeadNotice,
19107
+ reportRecord,
17558
19108
  representableInstant,
17559
19109
  resetRecord,
17560
19110
  watchRecord