@yankeguo/dsh-devlead 0.2.4 → 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 +29 -4
  2. package/lib/index.js +1358 -65
  3. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -12,7 +12,13 @@ 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
14
  import { SessionId as toSessionId3 } from "@deepseek-ai/dsh-session";
15
- import { DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2 } from "@yankeguo/dsh-devlead-protocol";
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,16 +15546,19 @@ 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;
@@ -15145,6 +15576,18 @@ function renderDevLeadNotice(notifications, total = notifications.length) {
15145
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."
15146
15577
  ].join("\n");
15147
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
+ }
15148
15591
  var DevLeadNotificationHub = class {
15149
15592
  /**
15150
15593
  * @param ctx - host context providing the Agent registry and Session store.
@@ -15190,7 +15633,7 @@ var DevLeadNotificationHub = class {
15190
15633
  if (status !== "idle") return;
15191
15634
  const runtime = this.leads.get(String(agent.id));
15192
15635
  if (runtime === void 0) return;
15193
- 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;
15194
15637
  void this.flush(runtime);
15195
15638
  });
15196
15639
  this.ctx.on("session/event", (session, event) => {
@@ -15232,6 +15675,121 @@ var DevLeadNotificationHub = class {
15232
15675
  if (runtime === void 0) return;
15233
15676
  await this.flush(runtime);
15234
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
+ }
15235
15793
  /** Index every live lead Session at plugin load. */
15236
15794
  bootstrap() {
15237
15795
  for (const agent of this.ctx.agents.list()) this.syncLead(agent);
@@ -15286,7 +15844,7 @@ var DevLeadNotificationHub = class {
15286
15844
  const runtime = this.ensureLead(sessionId);
15287
15845
  runtime.resumeAttempts = 0;
15288
15846
  this.setWatched(runtime, state.sessions);
15289
- if (runtime.pending.length > 0 || runtime.unsaved.length > 0) {
15847
+ if (runtime.pending.length > 0 || runtime.pendingReports.length > 0 || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) {
15290
15848
  this.clearTimer(runtime);
15291
15849
  this.scheduleFlush(runtime);
15292
15850
  }
@@ -15303,7 +15861,9 @@ var DevLeadNotificationHub = class {
15303
15861
  sessionId,
15304
15862
  watched: /* @__PURE__ */ new Set(),
15305
15863
  pending: [],
15864
+ pendingReports: [],
15306
15865
  unsaved: [],
15866
+ unsavedReports: [],
15307
15867
  timer: void 0,
15308
15868
  scheduled: false,
15309
15869
  flushing: false,
@@ -15353,7 +15913,11 @@ var DevLeadNotificationHub = class {
15353
15913
  runtime.watched = next;
15354
15914
  runtime.pending = runtime.pending.filter((notification) => next.has(notification.sessionId));
15355
15915
  runtime.unsaved = runtime.unsaved.filter((notification) => next.has(notification.sessionId));
15356
- 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
+ }
15357
15921
  }
15358
15922
  /**
15359
15923
  * Drop one lead runtime and its reverse-index entries.
@@ -15377,7 +15941,9 @@ var DevLeadNotificationHub = class {
15377
15941
  }
15378
15942
  }
15379
15943
  runtime.pending = [];
15944
+ runtime.pendingReports = [];
15380
15945
  runtime.unsaved = [];
15946
+ runtime.unsavedReports = [];
15381
15947
  this.leads.delete(leadId);
15382
15948
  }
15383
15949
  this.resuming.delete(leadId);
@@ -15400,8 +15966,8 @@ var DevLeadNotificationHub = class {
15400
15966
  onSessionEvent(session, event) {
15401
15967
  if (this.stopping) return;
15402
15968
  const sessionId = String(session.id);
15403
- const record2 = pluginRecordOf2(event);
15404
- 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)) {
15405
15971
  const agent = this.ctx.agents.get(session.id);
15406
15972
  if (agent !== void 0) this.syncLead(agent);
15407
15973
  }
@@ -15520,8 +16086,9 @@ var DevLeadNotificationHub = class {
15520
16086
  * @param runtime - lead runtime row.
15521
16087
  */
15522
16088
  persistUnsaved(session, runtime) {
15523
- if (runtime.unsaved.length === 0) return;
16089
+ if (runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15524
16090
  const remaining = [];
16091
+ const remainingReports = [];
15525
16092
  let appended = false;
15526
16093
  for (const notification of runtime.unsaved) {
15527
16094
  try {
@@ -15536,9 +16103,23 @@ var DevLeadNotificationHub = class {
15536
16103
  appended = true;
15537
16104
  runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15538
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
+ }
15539
16119
  runtime.unsaved = remaining;
16120
+ runtime.unsavedReports = remainingReports;
15540
16121
  if (appended) void this.checkpoint(session, runtime.sessionId);
15541
- if (remaining.length > 0) this.scheduleRetry(runtime);
16122
+ if (remaining.length > 0 || remainingReports.length > 0) this.scheduleRetry(runtime);
15542
16123
  }
15543
16124
  /**
15544
16125
  * Arm the coalescing window for one lead.
@@ -15582,7 +16163,7 @@ var DevLeadNotificationHub = class {
15582
16163
  if (this.stopping) return;
15583
16164
  if (this.leads.get(runtime.sessionId) !== runtime) return;
15584
16165
  if (runtime.flushing) return;
15585
- 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;
15586
16167
  const leadSessionId = toSessionId(runtime.sessionId);
15587
16168
  const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(leadSessionId) ?? false;
15588
16169
  if (archived) {
@@ -15590,6 +16171,7 @@ var DevLeadNotificationHub = class {
15590
16171
  if (session !== void 0) {
15591
16172
  this.persistUnsaved(session, runtime);
15592
16173
  runtime.pending = [];
16174
+ runtime.pendingReports = [];
15593
16175
  }
15594
16176
  this.clearTimer(runtime);
15595
16177
  return;
@@ -15600,18 +16182,24 @@ var DevLeadNotificationHub = class {
15600
16182
  return;
15601
16183
  }
15602
16184
  this.persistUnsaved(agent.session, runtime);
15603
- if (runtime.pending.length === 0) return;
16185
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0) return;
15604
16186
  if (this.hasQueuedNotice(agent)) {
15605
16187
  this.scheduleRetry(runtime);
15606
16188
  return;
15607
16189
  }
15608
16190
  const batch = runtime.pending;
16191
+ const reportBatch = runtime.pendingReports;
15609
16192
  runtime.pending = [];
16193
+ runtime.pendingReports = [];
15610
16194
  this.clearTimer(runtime);
15611
16195
  runtime.flushing = true;
15612
16196
  let failed = false;
15613
16197
  try {
15614
- 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));
15615
16203
  try {
15616
16204
  await this.ctx.sessions.flush(agent.session);
15617
16205
  } catch (error51) {
@@ -15620,12 +16208,13 @@ var DevLeadNotificationHub = class {
15620
16208
  } catch (error51) {
15621
16209
  this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15622
16210
  runtime.pending = [...batch, ...runtime.pending].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
16211
+ runtime.pendingReports = [...reportBatch, ...runtime.pendingReports].slice(-DEVLEAD_REPORT_RETENTION2);
15623
16212
  failed = true;
15624
16213
  } finally {
15625
16214
  runtime.flushing = false;
15626
16215
  }
15627
- if ((runtime.pending.length > 0 || runtime.unsaved.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
15628
- 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) {
15629
16218
  this.scheduleRetry(runtime);
15630
16219
  } else {
15631
16220
  this.scheduleFlush(runtime);
@@ -15784,7 +16373,7 @@ function projectionCacheOf(ctx) {
15784
16373
  ...typeof service.write === "function" ? { write: (session) => service.write(session) } : {}
15785
16374
  };
15786
16375
  }
15787
- function devLeadPrefilterOf(cache, header) {
16376
+ function devLeadActivePrefilterOf(cache, header) {
15788
16377
  let snapshot;
15789
16378
  try {
15790
16379
  snapshot = cache.cachedSnapshot(header);
@@ -15796,12 +16385,9 @@ function devLeadPrefilterOf(cache, header) {
15796
16385
  if (typeof values !== "object" || values === null) return "unknown";
15797
16386
  const devLead = values.devLead;
15798
16387
  if (typeof devLead !== "object" || devLead === null) return "unknown";
15799
- const record2 = devLead;
15800
- if (record2.enabled !== true) {
15801
- return record2.enabled === false ? "not-lead" : "unknown";
15802
- }
15803
- if (!Array.isArray(record2.sessions)) return "unknown";
15804
- 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";
15805
16391
  }
15806
16392
 
15807
16393
  // packages/devlead/src/views.ts
@@ -16133,6 +16719,7 @@ async function resolveSessionReference(deps, reference) {
16133
16719
  // packages/devlead/src/index.ts
16134
16720
  var MAX_TIMER_DELAY_MS = 2147483647;
16135
16721
  var MAX_COLD_LEAD_LOG_READS = 64;
16722
+ var MAX_ACTIVE_SCAN_UNKNOWN_READS = 64;
16136
16723
  var REHYDRATION_READINESS_TIMEOUT_MS = 2e3;
16137
16724
  var REHYDRATION_READINESS_POLL_MS = 100;
16138
16725
  var Config = z2.object({
@@ -16252,6 +16839,39 @@ var DevLeadService = class extends Service {
16252
16839
  readinessWake;
16253
16840
  /** Timer of the active readiness sleep, so disposal can clear it. */
16254
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();
16255
16875
  /**
16256
16876
  * Disposers of the armed readiness retry: the optional-service injection fiber
16257
16877
  * and, while the query engine itself is missing, the lifecycle listeners.
@@ -16279,9 +16899,46 @@ var DevLeadService = class extends Service {
16279
16899
  this.disposed = true;
16280
16900
  this.wakeReadiness();
16281
16901
  this.disposeRehydrationRetry();
16902
+ this.outboxInjection?.dispose();
16903
+ this.outboxInjection = void 0;
16904
+ void this.outbox?.close();
16282
16905
  };
16283
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
+ }
16284
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;
16285
16942
  }
16286
16943
  /**
16287
16944
  * Rebuild the notification hub's watch index from durable state.
@@ -16350,8 +17007,9 @@ var DevLeadService = class extends Service {
16350
17007
  await this.awaitCorpusReady();
16351
17008
  if (this.rehydrated || this.disposed) return;
16352
17009
  try {
16353
- const records = await this.persistedLeadRecords(true);
16354
- this.hub.rehydrate(records.filter((record2) => this.ctx.agents.get(toSessionId3(record2.sessionId)) === void 0));
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));
16355
17013
  } catch (error51) {
16356
17014
  this.ctx.logger.warn(`devlead: cold lead rehydration failed: ${thrownMessage(error51)}`);
16357
17015
  }
@@ -16502,6 +17160,12 @@ var DevLeadService = class extends Service {
16502
17160
  finalizeRehydration() {
16503
17161
  this.rehydrated = true;
16504
17162
  this.disposeRehydrationRetry();
17163
+ if (this.initialized && !this.disposed) {
17164
+ void this.reconcileActiveSessions(this.activeSessionId, {
17165
+ includePersisted: false,
17166
+ knownActive: this.recoveredActive
17167
+ });
17168
+ }
16505
17169
  }
16506
17170
  /** Dispose every armed readiness-retry hook. */
16507
17171
  disposeRehydrationRetry() {
@@ -16546,6 +17210,14 @@ var DevLeadService = class extends Service {
16546
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"
16547
17211
  );
16548
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
+ }
16549
17221
  /** Deployment configuration after validation; read-only. */
16550
17222
  get settings() {
16551
17223
  return this.resolved;
@@ -16598,25 +17270,43 @@ var DevLeadService = class extends Service {
16598
17270
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
16599
17271
  */
16600
17272
  async setEnabled(agent, enabled, signal) {
16601
- this.assertLive(agent);
16602
- signal?.throwIfAborted();
16603
- const current = this.projectionHandle.stateOf(agent.session);
16604
- 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
+ }
16605
17294
  if (enabled) {
16606
- throw new DevLeadError(
16607
- `DevLead state for Session "${agent.id}" is damaged (${current.failure}); run /devlead reset first to discard the damaged watch set and notification digest`,
16608
- "DEVLEAD_PROJECTION_INVALID"
16609
- );
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
+ }
16610
17302
  }
16611
- this.appendResetRecord(agent.session);
16612
- await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
16613
- await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
16614
- return;
16615
- }
16616
- if (current.enabled === enabled) return;
16617
- appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
16618
- await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
16619
- await this.checkpointProjectionCache(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
+ });
16620
17310
  }
16621
17311
  /**
16622
17312
  * Discard one Session's durable DevLead state so a damaged fold can recover.
@@ -16632,11 +17322,16 @@ var DevLeadService = class extends Service {
16632
17322
  * @throws {@link DevLeadError} when the Agent is not live.
16633
17323
  */
16634
17324
  async reset(agent, signal) {
16635
- this.assertLive(agent);
16636
- signal?.throwIfAborted();
16637
- this.appendResetRecord(agent.session);
16638
- await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
16639
- await this.checkpointProjectionCache(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
+ });
16640
17335
  }
16641
17336
  /**
16642
17337
  * Append one reset marker to a Session log.
@@ -17182,6 +17877,272 @@ var DevLeadService = class extends Service {
17182
17877
  const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
17183
17878
  return state.notifications.slice(-effective);
17184
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
+ }
17185
18146
  // ---------------------------------------------------------------------------
17186
18147
  // Internals
17187
18148
  // ---------------------------------------------------------------------------
@@ -17276,6 +18237,313 @@ var DevLeadService = class extends Service {
17276
18237
  this.ctx.logger.warn(`devlead: ${what} could not be checkpointed into the Session projection cache: ${thrownMessage(error51)}`);
17277
18238
  }
17278
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
+ }
17279
18547
  /** Reject any use of a tool surface while DevLead mode is off. */
17280
18548
  assertReady(agent) {
17281
18549
  this.assertLive(agent);
@@ -17330,10 +18598,18 @@ var DevLeadService = class extends Service {
17330
18598
  */
17331
18599
  async persistedLeadRecords(scanPersisted) {
17332
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
+ );
17333
18605
  const remember = (sessionId, sessions) => {
17334
18606
  if (sessionId.length === 0 || sessions.length === 0) return;
17335
18607
  leads.set(sessionId, [...sessions]);
17336
18608
  };
18609
+ const result = () => ({
18610
+ leads: [...leads].map(([sessionId, watched]) => ({ sessionId, watched })),
18611
+ active
18612
+ });
17337
18613
  for (const lead of this.liveAttachLeads()) remember(lead.sessionId, lead.watched);
17338
18614
  if (!scanPersisted) {
17339
18615
  if (this.ctx.get("sessionQuery") === void 0) {
@@ -17343,23 +18619,23 @@ var DevLeadService = class extends Service {
17343
18619
  "devlead: the Session persistence binding is not composed yet; cold lead rehydration scans live Sessions only"
17344
18620
  );
17345
18621
  }
17346
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18622
+ return result();
17347
18623
  }
17348
18624
  const query = this.ctx.get("sessionQuery");
17349
- if (query === void 0) return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18625
+ if (query === void 0) return result();
17350
18626
  const cache = projectionCacheOf(this.ctx);
17351
18627
  if (cache === void 0) {
17352
18628
  this.ctx.logger.warn(
17353
18629
  "devlead: this Host composes no Session projection cache, so cold lead rehydration reads no persisted logs; only live lead Sessions are rehydrated"
17354
18630
  );
17355
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18631
+ return result();
17356
18632
  }
17357
18633
  let records;
17358
18634
  try {
17359
18635
  records = await query.listSessions();
17360
18636
  } catch (error51) {
17361
18637
  this.ctx.logger.warn(`devlead: could not list persisted Sessions for cold lead rehydration: ${thrownMessage(error51)}`);
17362
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18638
+ return result();
17363
18639
  }
17364
18640
  let unknownReads = 0;
17365
18641
  let capped = false;
@@ -17369,8 +18645,8 @@ var DevLeadService = class extends Service {
17369
18645
  const sessionId = String(record2.header.id);
17370
18646
  if (leads.has(sessionId) || record2.live) continue;
17371
18647
  if (record2.header.origin === "subagent") continue;
17372
- const prefilter = devLeadPrefilterOf(cache, record2.header);
17373
- if (prefilter === "not-lead") continue;
18648
+ const prefilter = devLeadActivePrefilterOf(cache, record2.header);
18649
+ if (prefilter === "inactive") continue;
17374
18650
  if (prefilter === "unknown") {
17375
18651
  if (unknownReads >= MAX_COLD_LEAD_LOG_READS) {
17376
18652
  capped = true;
@@ -17400,14 +18676,23 @@ var DevLeadService = class extends Service {
17400
18676
  }
17401
18677
  continue;
17402
18678
  }
17403
- 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);
17404
18689
  }
17405
18690
  if (capped) {
17406
18691
  this.ctx.logger.warn(
17407
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`
17408
18693
  );
17409
18694
  }
17410
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18695
+ return result();
17411
18696
  }
17412
18697
  /**
17413
18698
  * Validate one requested model selection against the Host's LLM registry.
@@ -17766,6 +19051,7 @@ var DevLeadService = class extends Service {
17766
19051
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
17767
19052
  await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
17768
19053
  await this.checkpointProjectionCache(agent.session, `watch set for lead "${agent.id}"`);
19054
+ if (watching) void this.replayOutbox();
17769
19055
  return { sessionId: id, watched: watching, sessions: next };
17770
19056
  }
17771
19057
  };
@@ -17780,6 +19066,9 @@ export {
17780
19066
  DEVLEAD_MODE_RECORD_TYPE,
17781
19067
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
17782
19068
  DEVLEAD_RECORD_VERSION,
19069
+ DEVLEAD_REPORT_MESSAGE_MAX,
19070
+ DEVLEAD_REPORT_RECORD_TYPE,
19071
+ DEVLEAD_REPORT_SUMMARY_MAX,
17783
19072
  DEVLEAD_RESET_RECORD_TYPE,
17784
19073
  DEVLEAD_WATCH_RECORD_TYPE,
17785
19074
  DevLeadError,
@@ -17792,6 +19081,8 @@ export {
17792
19081
  decodeModeRecord,
17793
19082
  decodeNotification,
17794
19083
  decodeNotificationRecord,
19084
+ decodeReport,
19085
+ decodeReportRecord,
17795
19086
  decodeResetRecord,
17796
19087
  decodeWatchRecord,
17797
19088
  index_default as default,
@@ -17804,6 +19095,7 @@ export {
17804
19095
  devLeadProjectionSchema,
17805
19096
  devLeadProjectionStateSchema,
17806
19097
  devLeadProjectionView,
19098
+ devLeadReport,
17807
19099
  emptyDevLeadModeProjectionState,
17808
19100
  emptyDevLeadProjectionState,
17809
19101
  failureExcerpt,
@@ -17812,6 +19104,7 @@ export {
17812
19104
  notificationId,
17813
19105
  notificationRecord,
17814
19106
  renderDevLeadNotice,
19107
+ reportRecord,
17815
19108
  representableInstant,
17816
19109
  resetRecord,
17817
19110
  watchRecord