@yankeguo/dsh-devlead 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/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,263 @@ 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,
15242
+ DEVLEAD_WATCH_PROJECTION_KEY,
14899
15243
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE2,
15244
+ devLeadReportId as devLeadReportId3,
14900
15245
  notificationId as notificationId2
14901
15246
  } from "@yankeguo/dsh-devlead-protocol";
14902
15247
  function emptyDevLeadProjectionState() {
14903
- return { enabled: false, sessions: [], notifications: [], failure: null };
15248
+ return { enabled: false, sessions: [], notifications: [], reports: [], failure: null };
14904
15249
  }
14905
15250
  var excerptSchema = external_exports.string().min(1).refine(
14906
15251
  (value) => value.length <= DEVLEAD_ERROR_EXCERPT_MAX2 * 2 && Array.from(value).length <= DEVLEAD_ERROR_EXCERPT_MAX2,
@@ -14914,7 +15259,7 @@ var notificationSchema = external_exports.object({
14914
15259
  // by the core can never become a record that this fold rejects.
14915
15260
  transition: external_exports.enum([...DEVLEAD_TRANSITIONS]),
14916
15261
  turn: external_exports.number().int().positive(),
14917
- at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT2),
15262
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT3),
14918
15263
  error: excerptSchema.optional(),
14919
15264
  summary: excerptSchema.optional()
14920
15265
  }).strict().refine(
@@ -14925,11 +15270,39 @@ var notificationSchema = external_exports.object({
14925
15270
  ),
14926
15271
  { message: "notification id must match sessionId, turn, and transition" }
14927
15272
  );
15273
+ var reportMessageSchema = external_exports.string().min(1).refine(
15274
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_MESSAGE_MAX3,
15275
+ { message: `report message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX3} code points` }
15276
+ );
15277
+ var reportSchema2 = external_exports.object({
15278
+ id: external_exports.string().min(1),
15279
+ kind: external_exports.enum([...DEVLEAD_REPORT_KINDS2]),
15280
+ message: reportMessageSchema,
15281
+ summary: external_exports.string().min(1).refine(
15282
+ (value) => Array.from(value).length <= DEVLEAD_REPORT_SUMMARY_MAX3,
15283
+ { message: `report summary must be at most ${DEVLEAD_REPORT_SUMMARY_MAX3} code points` }
15284
+ ).optional(),
15285
+ senderSessionId: external_exports.string().min(1),
15286
+ senderSessionTitle: excerptSchema.optional(),
15287
+ senderWorkspaceId: external_exports.string().min(1).optional(),
15288
+ senderWorkspaceTitle: excerptSchema.optional(),
15289
+ leadSessionId: external_exports.string().min(1),
15290
+ turn: external_exports.number().int().nonnegative(),
15291
+ at: external_exports.number().int().nonnegative().max(DEVLEAD_MAX_INSTANT3)
15292
+ }).strict().refine(
15293
+ (report) => report.id === devLeadReportId3(report.senderSessionId, report.turn, report.kind, report.message),
15294
+ { message: "report id must match senderSessionId, turn, kind, and message" }
15295
+ );
14928
15296
  function retainNotification(notifications, notification) {
14929
15297
  if (notifications.some((existing) => existing.id === notification.id)) return notifications;
14930
15298
  const next = [...notifications, notification];
14931
15299
  return next.length <= DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2 ? next : next.slice(next.length - DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2);
14932
15300
  }
15301
+ function retainReport(reports, report) {
15302
+ if (reports.some((existing) => existing.id === report.id)) return reports;
15303
+ const next = [...reports, report];
15304
+ return next.length <= DEVLEAD_REPORT_RETENTION ? next : next.slice(next.length - DEVLEAD_REPORT_RETENTION);
15305
+ }
14933
15306
  function sameSessionIds(left, right) {
14934
15307
  return left.length === right.length && left.every((id, index) => id === right[index]);
14935
15308
  }
@@ -14943,6 +15316,10 @@ var devLeadProjectionStateSchema = external_exports.object({
14943
15316
  (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14944
15317
  { message: "notification ids must be unique" }
14945
15318
  ),
15319
+ reports: external_exports.array(reportSchema2).max(DEVLEAD_REPORT_RETENTION).refine(
15320
+ (reports) => new Set(reports.map((report) => report.id)).size === reports.length,
15321
+ { message: "report ids must be unique" }
15322
+ ),
14946
15323
  failure: external_exports.string().min(1).nullable()
14947
15324
  }).strict();
14948
15325
  var devLeadProjectionSchema = external_exports.object({
@@ -14951,6 +15328,10 @@ var devLeadProjectionSchema = external_exports.object({
14951
15328
  notifications: external_exports.array(notificationSchema).max(DEVLEAD_DEFAULT_NOTIFICATION_RETENTION2).refine(
14952
15329
  (notifications) => new Set(notifications.map((notification) => notification.id)).size === notifications.length,
14953
15330
  { message: "notification ids must be unique" }
15331
+ ),
15332
+ reports: external_exports.array(reportSchema2).max(DEVLEAD_REPORT_RETENTION).refine(
15333
+ (reports) => new Set(reports.map((report) => report.id)).size === reports.length,
15334
+ { message: "report ids must be unique" }
14954
15335
  )
14955
15336
  }).strict();
14956
15337
  var wireViews = /* @__PURE__ */ new WeakMap();
@@ -14960,7 +15341,8 @@ function devLeadProjectionView(state) {
14960
15341
  const view = {
14961
15342
  enabled: state.enabled,
14962
15343
  sessions: state.sessions,
14963
- notifications: state.notifications
15344
+ notifications: state.notifications,
15345
+ reports: state.reports
14964
15346
  };
14965
15347
  wireViews.set(state, view);
14966
15348
  return view;
@@ -14993,6 +15375,11 @@ function applyDevLeadProjection(state, event) {
14993
15375
  const notifications = retainNotification(state.notifications, notification);
14994
15376
  return notifications === state.notifications ? state : { ...state, notifications };
14995
15377
  }
15378
+ case DEVLEAD_REPORT_RECORD_TYPE2: {
15379
+ const report = decodeReportRecord(record2.data);
15380
+ const reports = retainReport(state.reports, report);
15381
+ return reports === state.reports ? state : { ...state, reports };
15382
+ }
14996
15383
  default:
14997
15384
  return state;
14998
15385
  }
@@ -15023,8 +15410,82 @@ var devLeadProjectionDefinition = {
15023
15410
  // conversation reads it: keep it out of every Session summary/list row.
15024
15411
  summary: false
15025
15412
  },
15026
- // 1: the initial durable representation of the mode, watch set, and keyed
15027
- // notification records.
15413
+ // 2: adds the retained `reports` array to the state; version 1 cache rows
15414
+ // are discarded and refolded from the durable log.
15415
+ stateVersion: 2
15416
+ };
15417
+ function emptyDevLeadWatchProjectionState() {
15418
+ return { sessions: [], failure: null };
15419
+ }
15420
+ var devLeadWatchProjectionStateSchema = external_exports.object({
15421
+ sessions: external_exports.array(external_exports.string().min(1)).refine(
15422
+ (sessions) => new Set(sessions).size === sessions.length,
15423
+ { message: "watch sessions must be unique" }
15424
+ ),
15425
+ failure: external_exports.string().min(1).nullable()
15426
+ }).strict();
15427
+ var devLeadWatchProjectionSchema = external_exports.object({
15428
+ sessions: external_exports.array(external_exports.string().min(1)).refine(
15429
+ (sessions) => new Set(sessions).size === sessions.length,
15430
+ { message: "watch sessions must be unique" }
15431
+ )
15432
+ }).strict();
15433
+ function devLeadWatchProjectionView(state) {
15434
+ return { sessions: state.sessions };
15435
+ }
15436
+ function applyDevLeadWatchProjection(state, event) {
15437
+ const record2 = pluginRecordOf(event);
15438
+ if (record2 === void 0) return state;
15439
+ if (record2.type === DEVLEAD_RESET_RECORD_TYPE2) {
15440
+ try {
15441
+ decodeResetRecord(record2.data);
15442
+ return emptyDevLeadWatchProjectionState();
15443
+ } catch (error51) {
15444
+ if (state.failure !== null) return state;
15445
+ const message = error51 instanceof Error ? error51.message : String(error51);
15446
+ return {
15447
+ ...state,
15448
+ failure: `devlead watch replay failed at session event ${event.seq} (${record2.type}): ${message}`
15449
+ };
15450
+ }
15451
+ }
15452
+ if (state.failure !== null) return state;
15453
+ try {
15454
+ switch (record2.type) {
15455
+ case DEVLEAD_WATCH_RECORD_TYPE2: {
15456
+ const watch = decodeWatchRecord(record2.data);
15457
+ return sameSessionIds(state.sessions, watch.sessions) ? state : { sessions: watch.sessions, failure: null };
15458
+ }
15459
+ case DEVLEAD_MODE_RECORD_TYPE2:
15460
+ decodeModeRecord(record2.data);
15461
+ return state;
15462
+ case DEVLEAD_NOTIFICATION_RECORD_TYPE2:
15463
+ decodeNotificationRecord(record2.data);
15464
+ return state;
15465
+ case DEVLEAD_REPORT_RECORD_TYPE2:
15466
+ decodeReportRecord(record2.data);
15467
+ return state;
15468
+ default:
15469
+ return state;
15470
+ }
15471
+ } catch (error51) {
15472
+ const message = error51 instanceof Error ? error51.message : String(error51);
15473
+ return {
15474
+ ...state,
15475
+ failure: `devlead watch replay failed at session event ${event.seq} (${record2.type}): ${message}`
15476
+ };
15477
+ }
15478
+ }
15479
+ var devLeadWatchProjectionDefinition = {
15480
+ key: DEVLEAD_WATCH_PROJECTION_KEY,
15481
+ stateSchema: devLeadWatchProjectionStateSchema,
15482
+ init: emptyDevLeadWatchProjectionState,
15483
+ apply: applyDevLeadWatchProjection,
15484
+ wire: {
15485
+ viewSchema: devLeadWatchProjectionSchema,
15486
+ view: devLeadWatchProjectionView
15487
+ },
15488
+ // 1: the initial summary representation of the watch set.
15028
15489
  stateVersion: 1
15029
15490
  };
15030
15491
  function emptyDevLeadModeProjectionState() {
@@ -15071,6 +15532,9 @@ function applyDevLeadModeProjection(state, event) {
15071
15532
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2:
15072
15533
  decodeNotificationRecord(record2.data);
15073
15534
  return state;
15535
+ case DEVLEAD_REPORT_RECORD_TYPE2:
15536
+ decodeReportRecord(record2.data);
15537
+ return state;
15074
15538
  default:
15075
15539
  return state;
15076
15540
  }
@@ -15097,6 +15561,45 @@ var devLeadModeProjectionDefinition = {
15097
15561
  stateVersion: 1
15098
15562
  };
15099
15563
 
15564
+ // packages/devlead/src/active.ts
15565
+ import { pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
15566
+ import {
15567
+ DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
15568
+ DEVLEAD_RESET_RECORD_TYPE as DEVLEAD_RESET_RECORD_TYPE3
15569
+ } from "@yankeguo/dsh-devlead-protocol";
15570
+ function lastEnabledAt(events) {
15571
+ let at;
15572
+ for (const event of events) {
15573
+ const record2 = pluginRecordOf2(event);
15574
+ if (record2 === void 0) continue;
15575
+ if (record2.type === DEVLEAD_MODE_RECORD_TYPE3) {
15576
+ const data = record2.data;
15577
+ if (data.enabled === true && typeof data.at === "number" && Number.isFinite(data.at)) at = data.at;
15578
+ continue;
15579
+ }
15580
+ if (record2.type === DEVLEAD_RESET_RECORD_TYPE3) at = void 0;
15581
+ }
15582
+ return at;
15583
+ }
15584
+ function rankActiveSessions(occupants, preferredSessionId) {
15585
+ return [...occupants].sort((left, right) => {
15586
+ if (left.sessionId === preferredSessionId) return -1;
15587
+ if (right.sessionId === preferredSessionId) return 1;
15588
+ if (left.archived !== right.archived) return left.archived ? 1 : -1;
15589
+ if (left.live !== right.live) return left.live ? -1 : 1;
15590
+ if (left.running !== right.running) return left.running ? -1 : 1;
15591
+ return right.enabledAt - left.enabledAt || right.createdAt - left.createdAt || left.sessionId.localeCompare(right.sessionId);
15592
+ });
15593
+ }
15594
+ function activeSessionLabel(occupant) {
15595
+ const title = occupant.title?.trim() ?? "";
15596
+ return title.length === 0 ? occupant.sessionId : `${title} (${occupant.sessionId})`;
15597
+ }
15598
+ function alreadyActiveMessage(occupant) {
15599
+ const label = activeSessionLabel(occupant);
15600
+ return `Another Session is already in DevLead mode: ${label}. Run /devlead off there first, then enable this Session.`;
15601
+ }
15602
+
15100
15603
  // packages/devlead/src/isolation.ts
15101
15604
  function worktreeCheckoutOf(value) {
15102
15605
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -15118,16 +15621,19 @@ function worktreeCapabilityOf(ctx) {
15118
15621
  }
15119
15622
 
15120
15623
  // packages/devlead/src/notification.ts
15121
- import { appendPluginRecord, pluginRecordOf as pluginRecordOf2 } from "@deepseek-ai/dsh-session";
15624
+ import { appendPluginRecord, pluginRecordOf as pluginRecordOf3 } from "@deepseek-ai/dsh-session";
15122
15625
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
15123
15626
  import {
15124
15627
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION as DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3,
15125
15628
  DEVLEAD_MESSAGE_KIND as DEVLEAD_MESSAGE_KIND2,
15126
- DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE3,
15629
+ DEVLEAD_MODE_RECORD_TYPE as DEVLEAD_MODE_RECORD_TYPE4,
15127
15630
  DEVLEAD_NOTIFICATION_RECORD_TYPE as DEVLEAD_NOTIFICATION_RECORD_TYPE3,
15631
+ DEVLEAD_REPORT_RECORD_TYPE as DEVLEAD_REPORT_RECORD_TYPE3,
15632
+ DEVLEAD_REPORT_RETENTION as DEVLEAD_REPORT_RETENTION2,
15128
15633
  DEVLEAD_WATCH_RECORD_TYPE as DEVLEAD_WATCH_RECORD_TYPE3,
15129
15634
  isDevLeadTransition as isDevLeadTransition2,
15130
- notificationLine
15635
+ notificationLine,
15636
+ reportLine
15131
15637
  } from "@yankeguo/dsh-devlead-protocol";
15132
15638
  var MAX_DIGEST_LINES = 12;
15133
15639
  var DELIVERY_RETRY_MS = 1e3;
@@ -15145,6 +15651,18 @@ function renderDevLeadNotice(notifications, total = notifications.length) {
15145
15651
  "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
15652
  ].join("\n");
15147
15653
  }
15654
+ function renderDevLeadReportNotice(reports) {
15655
+ const shown = reports.slice(-MAX_DIGEST_LINES);
15656
+ const omitted = reports.length - shown.length;
15657
+ const lines = shown.map((report) => `- ${reportLine(report)}`);
15658
+ if (omitted > 0) lines.unshift(`- (${omitted} earlier report(s) omitted; call devlead_notifications for the digest)`);
15659
+ return [
15660
+ "[DEV LEAD REPORT]",
15661
+ "A watched Session sent a mid-turn report. This is a one-way update, not a question; there is no reply channel in it.",
15662
+ ...lines,
15663
+ "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."
15664
+ ].join("\n");
15665
+ }
15148
15666
  var DevLeadNotificationHub = class {
15149
15667
  /**
15150
15668
  * @param ctx - host context providing the Agent registry and Session store.
@@ -15190,7 +15708,7 @@ var DevLeadNotificationHub = class {
15190
15708
  if (status !== "idle") return;
15191
15709
  const runtime = this.leads.get(String(agent.id));
15192
15710
  if (runtime === void 0) return;
15193
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
15711
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15194
15712
  void this.flush(runtime);
15195
15713
  });
15196
15714
  this.ctx.on("session/event", (session, event) => {
@@ -15232,6 +15750,121 @@ var DevLeadNotificationHub = class {
15232
15750
  if (runtime === void 0) return;
15233
15751
  await this.flush(runtime);
15234
15752
  }
15753
+ /**
15754
+ * List the active DevLead Sessions currently watching one Session.
15755
+ * A runtime exists only for an enabled lead, and `setWatched` keeps its
15756
+ * reverse index exact, so no durable read is needed on this hot path.
15757
+ * @param sessionId - candidate watched Session identity.
15758
+ * @returns watching lead identities, in insertion order.
15759
+ */
15760
+ supervisorsOf(sessionId) {
15761
+ if (this.stopping) return [];
15762
+ const watchers = this.watchers.get(sessionId);
15763
+ if (watchers === void 0) return [];
15764
+ return [...watchers].filter((leadId) => this.leads.has(leadId));
15765
+ }
15766
+ /**
15767
+ * Persist and queue one report from a watched Session.
15768
+ *
15769
+ * The report receipt is appended to the lead's own Session log, exactly like
15770
+ * a turn notification, so the fold and the retained digest survive a restart.
15771
+ * When the lead is cold the receipt waits in `unsavedReports` and the normal
15772
+ * flush path resumes the lead (when `wakeColdSession` is enabled) before
15773
+ * writing it. The call returns after the queue decision, never after the
15774
+ * lead's wake-up turn, so the reporter is not blocked.
15775
+ * @param report - report addressed to one active lead.
15776
+ * @returns whether the report belongs to an indexed watch relationship.
15777
+ */
15778
+ report(report) {
15779
+ if (this.stopping) return false;
15780
+ const runtime = this.leads.get(report.leadSessionId);
15781
+ if (runtime === void 0 || !runtime.watched.has(report.senderSessionId)) return false;
15782
+ if (runtime.pendingReports.some((existing) => existing.id === report.id) || runtime.unsavedReports.some((existing) => existing.id === report.id)) return true;
15783
+ const session = this.ctx.sessions.get(toSessionId(report.leadSessionId));
15784
+ if (session !== void 0) {
15785
+ const state = this.stateOf(session);
15786
+ if (state === void 0 || !state.enabled) return false;
15787
+ if (state.reports.some((existing) => existing.id === report.id)) return true;
15788
+ if (this.appendReportRecord(session, report)) {
15789
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15790
+ } else {
15791
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15792
+ }
15793
+ } else {
15794
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15795
+ }
15796
+ this.scheduleFlush(runtime);
15797
+ return true;
15798
+ }
15799
+ /**
15800
+ * Persist one report receipt into the lead's attached Session log and wait
15801
+ * for the durability checkpoint before claiming delivery.
15802
+ *
15803
+ * A cold lead cannot accept the receipt yet, so the report is queued for the
15804
+ * normal cold-wake path and this method returns false; the caller keeps its
15805
+ * durable outbox row and replays it later. An archived lead, a disabled lead,
15806
+ * or a removed watch relationship returns false without queueing.
15807
+ * @param report - report addressed to one watched lead.
15808
+ * @returns whether the lead Session log now carries a flushed receipt.
15809
+ */
15810
+ async persistReport(report) {
15811
+ if (this.stopping) return false;
15812
+ const runtime = this.leads.get(report.leadSessionId);
15813
+ if (runtime === void 0 || !runtime.watched.has(report.senderSessionId)) return false;
15814
+ if (this.ctx.get("workspaceRegistry")?.archivedSessionIds.some((id) => String(id) === report.leadSessionId) ?? false) {
15815
+ return false;
15816
+ }
15817
+ const session = this.ctx.sessions.get(toSessionId(report.leadSessionId));
15818
+ if (session === void 0) {
15819
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15820
+ this.scheduleFlush(runtime);
15821
+ return false;
15822
+ }
15823
+ const state = this.stateOf(session);
15824
+ if (state === void 0 || !state.enabled) return false;
15825
+ if (!state.reports.some((existing) => existing.id === report.id)) {
15826
+ try {
15827
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
15828
+ } catch (error51) {
15829
+ this.ctx.logger.warn(
15830
+ `devlead: could not record a report for lead "${runtime.sessionId}": ${thrownMessage(error51)}`
15831
+ );
15832
+ runtime.unsavedReports = [...runtime.unsavedReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15833
+ this.scheduleFlush(runtime);
15834
+ return false;
15835
+ }
15836
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
15837
+ }
15838
+ try {
15839
+ await this.ctx.sessions.flush(session);
15840
+ } catch (error51) {
15841
+ this.ctx.logger.warn(
15842
+ `devlead: report receipt for lead "${runtime.sessionId}" could not be flushed to persistence: ${thrownMessage(error51)}`
15843
+ );
15844
+ this.scheduleFlush(runtime);
15845
+ return false;
15846
+ }
15847
+ this.scheduleFlush(runtime);
15848
+ return true;
15849
+ }
15850
+ /**
15851
+ * Append one report receipt and fire-and-forget its durability checkpoint.
15852
+ * @param session - attached lead Session log receiving the record.
15853
+ * @param report - report to persist.
15854
+ * @returns whether the append succeeded.
15855
+ */
15856
+ appendReportRecord(session, report) {
15857
+ try {
15858
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
15859
+ } catch (error51) {
15860
+ this.ctx.logger.warn(
15861
+ `devlead: could not record a report for lead "${report.leadSessionId}": ${thrownMessage(error51)}`
15862
+ );
15863
+ return false;
15864
+ }
15865
+ void this.checkpoint(session, report.leadSessionId);
15866
+ return true;
15867
+ }
15235
15868
  /** Index every live lead Session at plugin load. */
15236
15869
  bootstrap() {
15237
15870
  for (const agent of this.ctx.agents.list()) this.syncLead(agent);
@@ -15286,7 +15919,7 @@ var DevLeadNotificationHub = class {
15286
15919
  const runtime = this.ensureLead(sessionId);
15287
15920
  runtime.resumeAttempts = 0;
15288
15921
  this.setWatched(runtime, state.sessions);
15289
- if (runtime.pending.length > 0 || runtime.unsaved.length > 0) {
15922
+ if (runtime.pending.length > 0 || runtime.pendingReports.length > 0 || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) {
15290
15923
  this.clearTimer(runtime);
15291
15924
  this.scheduleFlush(runtime);
15292
15925
  }
@@ -15303,7 +15936,9 @@ var DevLeadNotificationHub = class {
15303
15936
  sessionId,
15304
15937
  watched: /* @__PURE__ */ new Set(),
15305
15938
  pending: [],
15939
+ pendingReports: [],
15306
15940
  unsaved: [],
15941
+ unsavedReports: [],
15307
15942
  timer: void 0,
15308
15943
  scheduled: false,
15309
15944
  flushing: false,
@@ -15353,7 +15988,11 @@ var DevLeadNotificationHub = class {
15353
15988
  runtime.watched = next;
15354
15989
  runtime.pending = runtime.pending.filter((notification) => next.has(notification.sessionId));
15355
15990
  runtime.unsaved = runtime.unsaved.filter((notification) => next.has(notification.sessionId));
15356
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) this.clearTimer(runtime);
15991
+ runtime.pendingReports = runtime.pendingReports.filter((report) => next.has(report.senderSessionId));
15992
+ runtime.unsavedReports = runtime.unsavedReports.filter((report) => next.has(report.senderSessionId));
15993
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) {
15994
+ this.clearTimer(runtime);
15995
+ }
15357
15996
  }
15358
15997
  /**
15359
15998
  * Drop one lead runtime and its reverse-index entries.
@@ -15377,7 +16016,9 @@ var DevLeadNotificationHub = class {
15377
16016
  }
15378
16017
  }
15379
16018
  runtime.pending = [];
16019
+ runtime.pendingReports = [];
15380
16020
  runtime.unsaved = [];
16021
+ runtime.unsavedReports = [];
15381
16022
  this.leads.delete(leadId);
15382
16023
  }
15383
16024
  this.resuming.delete(leadId);
@@ -15400,8 +16041,8 @@ var DevLeadNotificationHub = class {
15400
16041
  onSessionEvent(session, event) {
15401
16042
  if (this.stopping) return;
15402
16043
  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)) {
16044
+ const record2 = pluginRecordOf3(event);
16045
+ if (record2 !== void 0 && (record2.type === DEVLEAD_MODE_RECORD_TYPE4 || record2.type === DEVLEAD_WATCH_RECORD_TYPE3 || record2.type === DEVLEAD_RESET_RECORD_TYPE)) {
15405
16046
  const agent = this.ctx.agents.get(session.id);
15406
16047
  if (agent !== void 0) this.syncLead(agent);
15407
16048
  }
@@ -15520,8 +16161,9 @@ var DevLeadNotificationHub = class {
15520
16161
  * @param runtime - lead runtime row.
15521
16162
  */
15522
16163
  persistUnsaved(session, runtime) {
15523
- if (runtime.unsaved.length === 0) return;
16164
+ if (runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15524
16165
  const remaining = [];
16166
+ const remainingReports = [];
15525
16167
  let appended = false;
15526
16168
  for (const notification of runtime.unsaved) {
15527
16169
  try {
@@ -15536,10 +16178,24 @@ var DevLeadNotificationHub = class {
15536
16178
  appended = true;
15537
16179
  runtime.pending = [...runtime.pending, notification].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
15538
16180
  }
15539
- runtime.unsaved = remaining;
15540
- if (appended) void this.checkpoint(session, runtime.sessionId);
15541
- if (remaining.length > 0) this.scheduleRetry(runtime);
15542
- }
16181
+ for (const report of runtime.unsavedReports) {
16182
+ try {
16183
+ appendPluginRecord(session, DEVLEAD_REPORT_RECORD_TYPE3, reportRecord(report));
16184
+ } catch (error51) {
16185
+ this.ctx.logger.warn(
16186
+ `devlead: could not record a report for lead "${runtime.sessionId}": ${thrownMessage(error51)}`
16187
+ );
16188
+ remainingReports.push(report);
16189
+ continue;
16190
+ }
16191
+ appended = true;
16192
+ runtime.pendingReports = [...runtime.pendingReports, report].slice(-DEVLEAD_REPORT_RETENTION2);
16193
+ }
16194
+ runtime.unsaved = remaining;
16195
+ runtime.unsavedReports = remainingReports;
16196
+ if (appended) void this.checkpoint(session, runtime.sessionId);
16197
+ if (remaining.length > 0 || remainingReports.length > 0) this.scheduleRetry(runtime);
16198
+ }
15543
16199
  /**
15544
16200
  * Arm the coalescing window for one lead.
15545
16201
  * @param runtime - lead runtime row.
@@ -15582,7 +16238,7 @@ var DevLeadNotificationHub = class {
15582
16238
  if (this.stopping) return;
15583
16239
  if (this.leads.get(runtime.sessionId) !== runtime) return;
15584
16240
  if (runtime.flushing) return;
15585
- if (runtime.pending.length === 0 && runtime.unsaved.length === 0) return;
16241
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0 && runtime.unsaved.length === 0 && runtime.unsavedReports.length === 0) return;
15586
16242
  const leadSessionId = toSessionId(runtime.sessionId);
15587
16243
  const archived = this.ctx.get("workspaceRegistry")?.archivedSessionIds.includes(leadSessionId) ?? false;
15588
16244
  if (archived) {
@@ -15590,6 +16246,7 @@ var DevLeadNotificationHub = class {
15590
16246
  if (session !== void 0) {
15591
16247
  this.persistUnsaved(session, runtime);
15592
16248
  runtime.pending = [];
16249
+ runtime.pendingReports = [];
15593
16250
  }
15594
16251
  this.clearTimer(runtime);
15595
16252
  return;
@@ -15600,18 +16257,24 @@ var DevLeadNotificationHub = class {
15600
16257
  return;
15601
16258
  }
15602
16259
  this.persistUnsaved(agent.session, runtime);
15603
- if (runtime.pending.length === 0) return;
16260
+ if (runtime.pending.length === 0 && runtime.pendingReports.length === 0) return;
15604
16261
  if (this.hasQueuedNotice(agent)) {
15605
16262
  this.scheduleRetry(runtime);
15606
16263
  return;
15607
16264
  }
15608
16265
  const batch = runtime.pending;
16266
+ const reportBatch = runtime.pendingReports;
15609
16267
  runtime.pending = [];
16268
+ runtime.pendingReports = [];
15610
16269
  this.clearTimer(runtime);
15611
16270
  runtime.flushing = true;
15612
16271
  let failed = false;
15613
16272
  try {
15614
- agent.followup(createDevLeadNoticeMessage(renderDevLeadNotice(batch)));
16273
+ const text = [
16274
+ batch.length === 0 ? "" : renderDevLeadNotice(batch),
16275
+ reportBatch.length === 0 ? "" : renderDevLeadReportNotice(reportBatch)
16276
+ ].filter((part) => part.length > 0).join("\n\n");
16277
+ agent.followup(createDevLeadNoticeMessage(text));
15615
16278
  try {
15616
16279
  await this.ctx.sessions.flush(agent.session);
15617
16280
  } catch (error51) {
@@ -15620,12 +16283,13 @@ var DevLeadNotificationHub = class {
15620
16283
  } catch (error51) {
15621
16284
  this.ctx.logger.warn(`devlead: could not wake lead "${runtime.sessionId}": ${thrownMessage(error51)}`);
15622
16285
  runtime.pending = [...batch, ...runtime.pending].slice(-DEVLEAD_DEFAULT_NOTIFICATION_RETENTION3);
16286
+ runtime.pendingReports = [...reportBatch, ...runtime.pendingReports].slice(-DEVLEAD_REPORT_RETENTION2);
15623
16287
  failed = true;
15624
16288
  } finally {
15625
16289
  runtime.flushing = false;
15626
16290
  }
15627
- if ((runtime.pending.length > 0 || runtime.unsaved.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
15628
- if (failed || runtime.unsaved.length > 0) {
16291
+ if ((runtime.pending.length > 0 || runtime.pendingReports.length > 0 || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) && this.leads.get(runtime.sessionId) === runtime) {
16292
+ if (failed || runtime.unsaved.length > 0 || runtime.unsavedReports.length > 0) {
15629
16293
  this.scheduleRetry(runtime);
15630
16294
  } else {
15631
16295
  this.scheduleFlush(runtime);
@@ -15784,7 +16448,7 @@ function projectionCacheOf(ctx) {
15784
16448
  ...typeof service.write === "function" ? { write: (session) => service.write(session) } : {}
15785
16449
  };
15786
16450
  }
15787
- function devLeadPrefilterOf(cache, header) {
16451
+ function devLeadActivePrefilterOf(cache, header) {
15788
16452
  let snapshot;
15789
16453
  try {
15790
16454
  snapshot = cache.cachedSnapshot(header);
@@ -15796,12 +16460,9 @@ function devLeadPrefilterOf(cache, header) {
15796
16460
  if (typeof values !== "object" || values === null) return "unknown";
15797
16461
  const devLead = values.devLead;
15798
16462
  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";
16463
+ const enabled = devLead.enabled;
16464
+ if (enabled === true) return "active";
16465
+ return enabled === false ? "inactive" : "unknown";
15805
16466
  }
15806
16467
 
15807
16468
  // packages/devlead/src/views.ts
@@ -16133,6 +16794,7 @@ async function resolveSessionReference(deps, reference) {
16133
16794
  // packages/devlead/src/index.ts
16134
16795
  var MAX_TIMER_DELAY_MS = 2147483647;
16135
16796
  var MAX_COLD_LEAD_LOG_READS = 64;
16797
+ var MAX_ACTIVE_SCAN_UNKNOWN_READS = 64;
16136
16798
  var REHYDRATION_READINESS_TIMEOUT_MS = 2e3;
16137
16799
  var REHYDRATION_READINESS_POLL_MS = 100;
16138
16800
  var Config = z2.object({
@@ -16252,6 +16914,39 @@ var DevLeadService = class extends Service {
16252
16914
  readinessWake;
16253
16915
  /** Timer of the active readiness sleep, so disposal can clear it. */
16254
16916
  readinessTimer;
16917
+ /** Serializes global-mode admission so two concurrent enables cannot both pass. */
16918
+ admissionTail = Promise.resolve();
16919
+ /**
16920
+ * Last known global DevLead occupant, used only as a recovery preference.
16921
+ * Every admission still re-derives occupancy from durable/live projections;
16922
+ * this hint merely keeps an incumbent from being displaced by a Session
16923
+ * resumed later.
16924
+ */
16925
+ activeSessionId;
16926
+ /** Cold enabled Sessions discovered by the boot rehydration scan. */
16927
+ recoveredActive = [];
16928
+ /** Whether the service finished its first activation-phase reconciliation. */
16929
+ initialized = false;
16930
+ /**
16931
+ * Per-reporter report budget and idempotency window for the current turn.
16932
+ * Process-local by design; a restart resets the window, while the lead's
16933
+ * durable report digest remains the audit authority.
16934
+ */
16935
+ reportState = /* @__PURE__ */ new Map();
16936
+ /** Durable report outbox; undefined when the Host composes no storage-domain. */
16937
+ outbox;
16938
+ /** In-flight outbox opening. */
16939
+ outboxOpening;
16940
+ /** Optional-service fiber that retries opening the outbox once storage mounts. */
16941
+ outboxInjection;
16942
+ /** Guard against overlapping outbox replay passes. */
16943
+ outboxReplaying = false;
16944
+ /**
16945
+ * Archived holders whose mode-off could not be written. The durable
16946
+ * tombstones live in the outbox domain; this set is the in-process mirror
16947
+ * and also covers a Host without storage.
16948
+ */
16949
+ ignoredArchived = /* @__PURE__ */ new Set();
16255
16950
  /**
16256
16951
  * Disposers of the armed readiness retry: the optional-service injection fiber
16257
16952
  * and, while the query engine itself is missing, the lifecycle listeners.
@@ -16268,6 +16963,7 @@ var DevLeadService = class extends Service {
16268
16963
  async [Service.init]() {
16269
16964
  this.projectionHandle = await this.ctx.sessionProjections.register(devLeadProjectionDefinition);
16270
16965
  await this.ctx.sessionProjections.register(devLeadModeProjectionDefinition);
16966
+ await this.ctx.sessionProjections.register(devLeadWatchProjectionDefinition);
16271
16967
  this.hub = new DevLeadNotificationHub(
16272
16968
  this.ctx,
16273
16969
  (session) => this.projectionHandle.stateOf(session),
@@ -16279,9 +16975,46 @@ var DevLeadService = class extends Service {
16279
16975
  this.disposed = true;
16280
16976
  this.wakeReadiness();
16281
16977
  this.disposeRehydrationRetry();
16978
+ this.outboxInjection?.dispose();
16979
+ this.outboxInjection = void 0;
16980
+ void this.outbox?.close();
16282
16981
  };
16283
16982
  }.bind(this), "devlead: cold rehydration");
16983
+ this.ctx.effect(function* () {
16984
+ const dispose = this.ctx.on("agent/created", ({ agent }) => {
16985
+ if (this.disposed) return void 0;
16986
+ const state = this.projectionHandle.stateOf(agent.session);
16987
+ if (state.failure !== null || !state.enabled) return void 0;
16988
+ if (this.activeSessionId === void 0) {
16989
+ void this.reconcileActiveSessions(String(agent.id));
16990
+ void this.replayOutbox();
16991
+ return void 0;
16992
+ }
16993
+ if (this.activeSessionId === String(agent.id)) {
16994
+ void this.replayOutbox();
16995
+ return void 0;
16996
+ }
16997
+ void this.reconcileActiveSessions(this.activeSessionId);
16998
+ void this.replayOutbox();
16999
+ return void 0;
17000
+ });
17001
+ yield dispose;
17002
+ }.bind(this), "devlead: single active");
17003
+ await this.openOutbox();
17004
+ if (this.outbox === void 0) {
17005
+ this.outboxInjection = this.ctx.inject(["storageDomain"], () => {
17006
+ void this.openOutbox().then(() => this.replayOutbox());
17007
+ return void 0;
17008
+ });
17009
+ }
16284
17010
  await this.rehydrateFromPersistence();
17011
+ await this.reconcileActiveSessions(void 0, {
17012
+ includePersisted: false,
17013
+ knownActive: this.recoveredActive
17014
+ });
17015
+ this.recoveredActive = [];
17016
+ await this.replayOutbox();
17017
+ this.initialized = true;
16285
17018
  }
16286
17019
  /**
16287
17020
  * Rebuild the notification hub's watch index from durable state.
@@ -16350,8 +17083,9 @@ var DevLeadService = class extends Service {
16350
17083
  await this.awaitCorpusReady();
16351
17084
  if (this.rehydrated || this.disposed) return;
16352
17085
  try {
16353
- const records = await this.persistedLeadRecords(true);
16354
- this.hub.rehydrate(records.filter((record2) => this.ctx.agents.get(toSessionId3(record2.sessionId)) === void 0));
17086
+ const scan = await this.persistedLeadRecords(true);
17087
+ this.recoveredActive = [...scan.active];
17088
+ this.hub.rehydrate(scan.leads.filter((record2) => this.ctx.agents.get(toSessionId3(record2.sessionId)) === void 0));
16355
17089
  } catch (error51) {
16356
17090
  this.ctx.logger.warn(`devlead: cold lead rehydration failed: ${thrownMessage(error51)}`);
16357
17091
  }
@@ -16502,6 +17236,12 @@ var DevLeadService = class extends Service {
16502
17236
  finalizeRehydration() {
16503
17237
  this.rehydrated = true;
16504
17238
  this.disposeRehydrationRetry();
17239
+ if (this.initialized && !this.disposed) {
17240
+ void this.reconcileActiveSessions(this.activeSessionId, {
17241
+ includePersisted: false,
17242
+ knownActive: this.recoveredActive
17243
+ });
17244
+ }
16505
17245
  }
16506
17246
  /** Dispose every armed readiness-retry hook. */
16507
17247
  disposeRehydrationRetry() {
@@ -16546,6 +17286,14 @@ var DevLeadService = class extends Service {
16546
17286
  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
17287
  );
16548
17288
  }
17289
+ /** Whether the durable report outbox is open and usable. */
17290
+ get reportOutboxAvailable() {
17291
+ return this.outbox?.available === true;
17292
+ }
17293
+ /** Last durable-outbox failure, exposed for the E2E probe and diagnostics. */
17294
+ get reportOutboxLastError() {
17295
+ return this.outbox?.lastError;
17296
+ }
16549
17297
  /** Deployment configuration after validation; read-only. */
16550
17298
  get settings() {
16551
17299
  return this.resolved;
@@ -16598,25 +17346,43 @@ var DevLeadService = class extends Service {
16598
17346
  * @throws {@link DevLeadError} when the Agent is not live or the replay failed.
16599
17347
  */
16600
17348
  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) {
17349
+ await this.withAdmission(async () => {
17350
+ this.assertLive(agent);
17351
+ signal?.throwIfAborted();
17352
+ const current = this.projectionHandle.stateOf(agent.session);
17353
+ if (current.failure !== null) {
17354
+ if (enabled) {
17355
+ throw new DevLeadError(
17356
+ `DevLead state for Session "${agent.id}" is damaged (${current.failure}); run /devlead reset first to discard the damaged watch set and notification digest`,
17357
+ "DEVLEAD_PROJECTION_INVALID"
17358
+ );
17359
+ }
17360
+ this.appendResetRecord(agent.session);
17361
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
17362
+ await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
17363
+ if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17364
+ return;
17365
+ }
17366
+ if (current.enabled === enabled) {
17367
+ if (enabled) this.activeSessionId = String(agent.id);
17368
+ return;
17369
+ }
16605
17370
  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
- );
17371
+ const blocker = await this.blockingOccupant(agent, signal);
17372
+ if (blocker !== void 0) {
17373
+ throw new DevLeadError(
17374
+ alreadyActiveMessage(blocker),
17375
+ "DEVLEAD_ALREADY_ACTIVE"
17376
+ );
17377
+ }
16610
17378
  }
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}"`);
17379
+ appendPluginRecord2(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
17380
+ await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
17381
+ await this.checkpointProjectionCache(agent.session, `DevLead mode for Session "${agent.id}"`);
17382
+ if (enabled) this.activeSessionId = String(agent.id);
17383
+ else if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17384
+ if (enabled) void this.replayOutbox();
17385
+ });
16620
17386
  }
16621
17387
  /**
16622
17388
  * Discard one Session's durable DevLead state so a damaged fold can recover.
@@ -16632,11 +17398,16 @@ var DevLeadService = class extends Service {
16632
17398
  * @throws {@link DevLeadError} when the Agent is not live.
16633
17399
  */
16634
17400
  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}"`);
17401
+ await this.withAdmission(async () => {
17402
+ this.assertLive(agent);
17403
+ signal?.throwIfAborted();
17404
+ this.appendResetRecord(agent.session);
17405
+ await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
17406
+ await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
17407
+ await this.outbox?.dropForLead(String(agent.id));
17408
+ this.ignoredArchived.delete(String(agent.id));
17409
+ if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
17410
+ });
16640
17411
  }
16641
17412
  /**
16642
17413
  * Append one reset marker to a Session log.
@@ -17182,6 +17953,272 @@ var DevLeadService = class extends Service {
17182
17953
  const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
17183
17954
  return state.notifications.slice(-effective);
17184
17955
  }
17956
+ /** Open the optional durable outbox once and load its archived-holder tombstones. */
17957
+ async openOutbox() {
17958
+ if (this.outbox !== void 0 || this.outboxOpening !== void 0) return;
17959
+ const run = (async () => {
17960
+ const outbox = await DevLeadReportOutbox.open(this.ctx);
17961
+ if (outbox === void 0) {
17962
+ this.ctx.logger.debug(
17963
+ "devlead: no storage-domain service is composed; reports use the explicit non-durable fallback"
17964
+ );
17965
+ return;
17966
+ }
17967
+ this.outbox = outbox;
17968
+ for (const sessionId of outbox.ignoredIds()) this.ignoredArchived.add(sessionId);
17969
+ await outbox.prune();
17970
+ })();
17971
+ this.outboxOpening = run;
17972
+ try {
17973
+ await run;
17974
+ } finally {
17975
+ this.outboxOpening = void 0;
17976
+ }
17977
+ }
17978
+ /**
17979
+ * Replay durable outbox rows whose lead is now attachable, then clear each
17980
+ * row only after its Session-log receipt was flushed.
17981
+ */
17982
+ async replayOutbox() {
17983
+ if (this.disposed || this.outbox === void 0 || this.outboxReplaying) return;
17984
+ this.outboxReplaying = true;
17985
+ try {
17986
+ await this.outbox.prune();
17987
+ const archived = new Set(
17988
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
17989
+ );
17990
+ let waiting = 0;
17991
+ for (const entry of this.outbox.entries()) {
17992
+ if (this.disposed) return;
17993
+ const report = entry.report;
17994
+ if (archived.has(report.leadSessionId)) {
17995
+ waiting += 1;
17996
+ continue;
17997
+ }
17998
+ let delivered = false;
17999
+ try {
18000
+ delivered = await this.hub?.persistReport(report) ?? false;
18001
+ } catch (error51) {
18002
+ this.ctx.logger.warn(
18003
+ `devlead: could not replay report "${report.id}": ${thrownMessage(error51)}`
18004
+ );
18005
+ }
18006
+ if (delivered) await this.outbox.delete(report);
18007
+ else waiting += 1;
18008
+ }
18009
+ if (waiting > 0) {
18010
+ this.ctx.logger.warn(
18011
+ `devlead: ${String(waiting)} durable report(s) wait for their lead Session or watch relationship to return`
18012
+ );
18013
+ }
18014
+ } finally {
18015
+ this.outboxReplaying = false;
18016
+ }
18017
+ }
18018
+ /**
18019
+ * Persist a report in the durable outbox (when available) and try to write
18020
+ * its lead receipt. The outbox row is only removed after the lead flush
18021
+ * succeeded; otherwise the report remains replayable.
18022
+ * @param report - validated report.
18023
+ * @returns the child-facing receipt with durability status.
18024
+ */
18025
+ async deliverReport(report) {
18026
+ const outboxed = this.outbox === void 0 ? false : await this.outbox.put(report);
18027
+ if (outboxed && this.outbox !== void 0) {
18028
+ let delivered = false;
18029
+ try {
18030
+ delivered = await this.hub?.persistReport(report) ?? false;
18031
+ } catch (error51) {
18032
+ this.ctx.logger.warn(
18033
+ `devlead: report "${report.id}" is durable but its first delivery attempt failed: ${thrownMessage(error51)}`
18034
+ );
18035
+ }
18036
+ if (delivered) await this.outbox.delete(report);
18037
+ return {
18038
+ report,
18039
+ durable: true,
18040
+ queued: !delivered
18041
+ };
18042
+ }
18043
+ const accepted = this.hub?.report(report) ?? false;
18044
+ if (!accepted) {
18045
+ throw new DevLeadError(
18046
+ "the active DevLead Session stopped watching this Session before the report could be queued",
18047
+ "DEVLEAD_NOT_SUPERVISED"
18048
+ );
18049
+ }
18050
+ return {
18051
+ report,
18052
+ durable: false,
18053
+ queued: true,
18054
+ 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})`)
18055
+ };
18056
+ }
18057
+ /**
18058
+ * Resolve the unique active DevLead Session that watches one reporter.
18059
+ *
18060
+ * The hub's reverse index already reflects durable watch/mode state (live and
18061
+ * cold rehydrated leads). Archived leads are excluded, and when historical
18062
+ * state leaves more than one watcher the current global incumbent wins; with
18063
+ * no unique answer the reporter is treated as unwatched instead of
18064
+ * broadcasting to an arbitrary lead.
18065
+ * @param agent - candidate watched Session Agent.
18066
+ * @returns the watching lead Session id, or undefined.
18067
+ */
18068
+ supervisorOf(agent) {
18069
+ if (this.hub === void 0) return void 0;
18070
+ if (this.ctx.agents.get(agent.id) !== agent) return void 0;
18071
+ if (this.isEnabled(agent)) return void 0;
18072
+ const archived = new Set(
18073
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
18074
+ );
18075
+ const candidates = this.hub.supervisorsOf(String(agent.id)).filter((id) => !archived.has(id));
18076
+ if (candidates.length === 0) return void 0;
18077
+ if (candidates.length === 1) return candidates[0];
18078
+ return this.activeSessionId !== void 0 && candidates.includes(this.activeSessionId) ? this.activeSessionId : void 0;
18079
+ }
18080
+ /**
18081
+ * List archived Sessions that still carry a durable enabled mode.
18082
+ *
18083
+ * They are ignored by admission (an archived Session is not an active lead),
18084
+ * but the human needs a visible, actionable recovery path: unarchive and open
18085
+ * the Session to run `/devlead off`, or delete it. The list is also the
18086
+ * diagnostic surface for a tombstone that could not be cleared.
18087
+ * @param signal - cancellation threaded through the scan.
18088
+ * @returns archived holders with human labels.
18089
+ */
18090
+ async archivedOccupants(signal) {
18091
+ const active = await this.scanActiveSessions(signal);
18092
+ signal?.throwIfAborted();
18093
+ return active.filter((occupant) => occupant.archived).map((occupant) => ({
18094
+ sessionId: occupant.sessionId,
18095
+ ...occupant.title === void 0 ? {} : { title: occupant.title }
18096
+ }));
18097
+ }
18098
+ /**
18099
+ * Whether one Session may send mid-turn reports to an active DevLead.
18100
+ * @param agent - candidate reporter Agent.
18101
+ * @returns whether the reporter has exactly one active lead watching it.
18102
+ */
18103
+ isSupervised(agent) {
18104
+ return this.supervisorOf(agent) !== void 0;
18105
+ }
18106
+ /**
18107
+ * Send one mid-turn report from a watched Session to its active DevLead.
18108
+ *
18109
+ * The durable receipt is appended to the lead's own Session log (or queued
18110
+ * for a cold lead by the hub), then the lead is woken through the same
18111
+ * coalesced notice path as turn notifications. This method returns after the
18112
+ * receipt/queue decision and never waits for the lead's next turn, so the
18113
+ * reporter is not blocked. Same-message reports in one turn are idempotent;
18114
+ * more than {@link DEVLEAD_REPORT_MAX_PER_TURN} distinct reports in one turn
18115
+ * are refused.
18116
+ * @param agent - exact live reporter Agent.
18117
+ * @param request - report text, kind, and optional summary.
18118
+ * @param signal - cancellation checked before durable work.
18119
+ * @returns the report receipt, including whether it is durable and still queued.
18120
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_SUPERVISED` when no unique active
18121
+ * lead watches the reporter, `DEVLEAD_INVALID_INPUT` for unusable fields,
18122
+ * and `DEVLEAD_REPORT_RATE_LIMITED` when the per-turn budget is exhausted.
18123
+ */
18124
+ async reportProgress(agent, request, signal) {
18125
+ this.assertLive(agent);
18126
+ signal?.throwIfAborted();
18127
+ if (this.isEnabled(agent)) {
18128
+ throw new DevLeadError(
18129
+ "this Session is the active DevLead; a DevLead Session cannot report to itself",
18130
+ "DEVLEAD_NOT_SUPERVISED"
18131
+ );
18132
+ }
18133
+ const leadSessionId = this.supervisorOf(agent);
18134
+ if (leadSessionId === void 0) {
18135
+ throw new DevLeadError(
18136
+ "this Session is not watched by the unique active DevLead Session, so it cannot send a report",
18137
+ "DEVLEAD_NOT_SUPERVISED"
18138
+ );
18139
+ }
18140
+ const message = request.message.trim();
18141
+ if (message.length === 0) {
18142
+ throw new DevLeadError("report message must not be empty", "DEVLEAD_INVALID_INPUT");
18143
+ }
18144
+ if (message.length > DEVLEAD_REPORT_MESSAGE_MAX4 * 2 || Array.from(message).length > DEVLEAD_REPORT_MESSAGE_MAX4) {
18145
+ throw new DevLeadError(
18146
+ `report message must be at most ${DEVLEAD_REPORT_MESSAGE_MAX4} code points`,
18147
+ "DEVLEAD_INVALID_INPUT"
18148
+ );
18149
+ }
18150
+ const kind = request.kind ?? "progress";
18151
+ if (!isDevLeadReportKind2(kind)) {
18152
+ throw new DevLeadError(
18153
+ `report kind ${JSON.stringify(kind)} is not recognized; use progress, blocked, decision, or fyi`,
18154
+ "DEVLEAD_INVALID_INPUT"
18155
+ );
18156
+ }
18157
+ const summary = request.summary?.trim();
18158
+ if (summary !== void 0 && (summary.length === 0 || summary.length > DEVLEAD_REPORT_SUMMARY_MAX4 * 2 || Array.from(summary).length > DEVLEAD_REPORT_SUMMARY_MAX4)) {
18159
+ throw new DevLeadError(
18160
+ `report summary must be 1-${DEVLEAD_REPORT_SUMMARY_MAX4} code points when present`,
18161
+ "DEVLEAD_INVALID_INPUT"
18162
+ );
18163
+ }
18164
+ const reporterId = String(agent.id);
18165
+ const turn = this.ctx.agents.turnBoundaryOf(agent.session).lastTurn;
18166
+ const previous = this.reportState.get(reporterId);
18167
+ const state = previous !== void 0 && previous.turn === turn && previous.leadSessionId === leadSessionId ? previous : { turn, leadSessionId, messages: /* @__PURE__ */ new Map() };
18168
+ if (previous === void 0 || previous.turn !== turn || previous.leadSessionId !== leadSessionId) {
18169
+ this.reportState.set(reporterId, state);
18170
+ }
18171
+ const duplicate = state.messages.get(message);
18172
+ if (duplicate !== void 0) return duplicate;
18173
+ if (state.messages.size >= DEVLEAD_REPORT_MAX_PER_TURN) {
18174
+ throw new DevLeadError(
18175
+ `this Session already sent ${DEVLEAD_REPORT_MAX_PER_TURN} reports in turn ${turn}; wait for the next turn or let the DevLead continue`,
18176
+ "DEVLEAD_REPORT_RATE_LIMITED"
18177
+ );
18178
+ }
18179
+ const title = this.ctx.get("sessionTitle")?.get(agent.session)?.title;
18180
+ let senderWorkspaceId;
18181
+ let senderWorkspaceTitle;
18182
+ for (const workspace of this.ctx.get("workspaceRegistry")?.list() ?? []) {
18183
+ if (!workspace.sessionIds.some((id) => String(id) === reporterId)) continue;
18184
+ senderWorkspaceId = workspace.id;
18185
+ senderWorkspaceTitle = workspace.title;
18186
+ break;
18187
+ }
18188
+ const report = devLeadReport({
18189
+ senderSessionId: reporterId,
18190
+ ...title === void 0 ? {} : { senderSessionTitle: title },
18191
+ ...senderWorkspaceId === void 0 ? {} : { senderWorkspaceId },
18192
+ ...senderWorkspaceTitle === void 0 ? {} : { senderWorkspaceTitle },
18193
+ leadSessionId,
18194
+ turn,
18195
+ kind,
18196
+ message,
18197
+ ...summary === void 0 ? {} : { summary },
18198
+ at: Date.now()
18199
+ });
18200
+ signal?.throwIfAborted();
18201
+ const receipt = await this.deliverReport(report);
18202
+ state.messages.set(message, receipt);
18203
+ if (this.reportState.size > 512) {
18204
+ const oldest = this.reportState.keys().next().value;
18205
+ if (oldest !== void 0) this.reportState.delete(oldest);
18206
+ }
18207
+ return receipt;
18208
+ }
18209
+ /**
18210
+ * Read the retained mid-turn report digest of one live lead.
18211
+ * @param agent - exact live lead Agent.
18212
+ * @param options - optional newest-row limit, defaulting to 20.
18213
+ * @returns detached reports, oldest first.
18214
+ */
18215
+ reports(agent, options = {}) {
18216
+ this.assertReady(agent);
18217
+ const state = this.strictStateOf(agent.session);
18218
+ const limit = options.limit ?? 20;
18219
+ const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
18220
+ return state.reports.slice(-effective);
18221
+ }
17185
18222
  // ---------------------------------------------------------------------------
17186
18223
  // Internals
17187
18224
  // ---------------------------------------------------------------------------
@@ -17276,6 +18313,313 @@ var DevLeadService = class extends Service {
17276
18313
  this.ctx.logger.warn(`devlead: ${what} could not be checkpointed into the Session projection cache: ${thrownMessage(error51)}`);
17277
18314
  }
17278
18315
  }
18316
+ /**
18317
+ * Serialize one global-mode critical section. Every admission waits for the
18318
+ * previous one, so two concurrent enables cannot both scan an empty Host and
18319
+ * then both append. The tail promise is released in `finally`, including on
18320
+ * a rejected admission.
18321
+ * @param body - critical section to run exclusively.
18322
+ * @returns the body result.
18323
+ */
18324
+ async withAdmission(body) {
18325
+ const previous = this.admissionTail;
18326
+ let release;
18327
+ this.admissionTail = new Promise((resolve) => {
18328
+ release = resolve;
18329
+ });
18330
+ await previous;
18331
+ try {
18332
+ return await body();
18333
+ } finally {
18334
+ release();
18335
+ }
18336
+ }
18337
+ /**
18338
+ * Find an enabled Session other than `agent`, releasing archived holders
18339
+ * first. This is the admission check under the global mutex.
18340
+ * @param agent - Session requesting the mode.
18341
+ * @param signal - caller cancellation checked around the scan and releases.
18342
+ * @returns the blocking occupant, or undefined when the mode is free.
18343
+ */
18344
+ async blockingOccupant(agent, signal) {
18345
+ const active = await this.scanActiveSessions(signal);
18346
+ const blockers = [];
18347
+ for (const occupant of active) {
18348
+ if (occupant.sessionId === String(agent.id)) continue;
18349
+ if (occupant.archived) {
18350
+ signal?.throwIfAborted();
18351
+ if (await this.releaseActiveOccupant(occupant, "archived")) {
18352
+ await this.rememberReleased(occupant.sessionId);
18353
+ } else {
18354
+ await this.rememberIgnored(occupant.sessionId);
18355
+ this.ctx.logger.warn(
18356
+ `devlead: archived Session "${occupant.sessionId}" is ignored for admission; unarchive and open it to run /devlead off, or delete it`
18357
+ );
18358
+ }
18359
+ continue;
18360
+ }
18361
+ if (this.ignoredArchived.has(occupant.sessionId)) {
18362
+ if (await this.releaseActiveOccupant(occupant, "duplicate")) {
18363
+ await this.rememberReleased(occupant.sessionId);
18364
+ }
18365
+ continue;
18366
+ }
18367
+ blockers.push(occupant);
18368
+ }
18369
+ signal?.throwIfAborted();
18370
+ return blockers.length === 0 ? void 0 : rankActiveSessions(blockers, this.activeSessionId)[0];
18371
+ }
18372
+ /**
18373
+ * Scan every live and persisted Session for an enabled DevLead mode.
18374
+ *
18375
+ * Live Sessions are authoritative directly from the projection handle. Cold
18376
+ * Sessions use the projection cache as a zero-I/O pre-filter: `active` rows
18377
+ * are folded exactly, `inactive` rows are skipped, and rows the cache cannot
18378
+ * classify (including a Host with no cache) are folded up to a bounded read
18379
+ * budget. The budget only limits an arbitrarily large unknown history and is
18380
+ * reported; positively active rows are never skipped.
18381
+ * @param signal - caller cancellation threaded through query reads.
18382
+ * @returns every enabled Session, deduplicated by id.
18383
+ */
18384
+ async scanActiveSessions(signal, includePersisted = true) {
18385
+ const active = /* @__PURE__ */ new Map();
18386
+ const seen = /* @__PURE__ */ new Set();
18387
+ const archived = new Set(
18388
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
18389
+ );
18390
+ const addLive = (session) => {
18391
+ const sessionId = String(session.id);
18392
+ if (seen.has(sessionId)) return;
18393
+ seen.add(sessionId);
18394
+ const state = this.projectionHandle.stateOf(session);
18395
+ if (state.failure !== null || !state.enabled) return;
18396
+ const title = this.ctx.get("sessionTitle")?.get(session)?.title;
18397
+ const agent = this.ctx.agents.get(session.id);
18398
+ active.set(sessionId, {
18399
+ sessionId,
18400
+ ...title === void 0 || title.trim().length === 0 ? {} : { title },
18401
+ live: true,
18402
+ archived: archived.has(sessionId),
18403
+ running: agent?.status === "running",
18404
+ createdAt: session.header.createdAt,
18405
+ enabledAt: 0
18406
+ });
18407
+ };
18408
+ for (const agent of this.ctx.agents.list()) addLive(agent.session);
18409
+ for (const session of this.ctx.sessions.list()) addLive(session);
18410
+ signal?.throwIfAborted();
18411
+ if (!includePersisted) return [...active.values()];
18412
+ const query = this.ctx.get("sessionQuery");
18413
+ if (query === void 0) return [...active.values()];
18414
+ let records;
18415
+ try {
18416
+ records = await query.listSessions(signal);
18417
+ } catch (error51) {
18418
+ if (signal?.aborted === true) throw error51;
18419
+ this.ctx.logger.warn(`devlead: could not list persisted Sessions for global DevLead admission: ${thrownMessage(error51)}`);
18420
+ return [...active.values()];
18421
+ }
18422
+ const cache = projectionCacheOf(this.ctx);
18423
+ let unknownReads = 0;
18424
+ let capped = false;
18425
+ let warnedRead = false;
18426
+ for (const record2 of records) {
18427
+ signal?.throwIfAborted();
18428
+ const sessionId = String(record2.header.id);
18429
+ if (seen.has(sessionId)) continue;
18430
+ const prefilter = cache === void 0 ? "unknown" : devLeadActivePrefilterOf(cache, record2.header);
18431
+ if (prefilter === "inactive") {
18432
+ seen.add(sessionId);
18433
+ continue;
18434
+ }
18435
+ if (prefilter === "unknown") {
18436
+ if (unknownReads >= MAX_ACTIVE_SCAN_UNKNOWN_READS) {
18437
+ capped = true;
18438
+ continue;
18439
+ }
18440
+ unknownReads += 1;
18441
+ }
18442
+ seen.add(sessionId);
18443
+ let events;
18444
+ try {
18445
+ events = (await query.readSession(record2.header.id)).events;
18446
+ } catch (error51) {
18447
+ if (signal?.aborted === true) throw error51;
18448
+ if (!warnedRead) {
18449
+ warnedRead = true;
18450
+ this.ctx.logger.warn(`devlead: could not read a persisted Session log for global DevLead admission: ${thrownMessage(error51)}`);
18451
+ }
18452
+ continue;
18453
+ }
18454
+ let state = emptyDevLeadProjectionState();
18455
+ for (const event of events) {
18456
+ state = applyDevLeadProjection(state, event);
18457
+ if (state.failure !== null) break;
18458
+ }
18459
+ if (state.failure !== null || !state.enabled) continue;
18460
+ active.set(sessionId, {
18461
+ sessionId,
18462
+ live: false,
18463
+ archived: archived.has(sessionId),
18464
+ running: false,
18465
+ createdAt: record2.header.createdAt,
18466
+ enabledAt: lastEnabledAt(events) ?? 0
18467
+ });
18468
+ }
18469
+ if (capped) {
18470
+ this.ctx.logger.warn(
18471
+ `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`
18472
+ );
18473
+ }
18474
+ return [...active.values()];
18475
+ }
18476
+ /**
18477
+ * Durably disable one active occupant so the global slot becomes free.
18478
+ *
18479
+ * A live Session (or Agent-owned Session) is appended directly. A cold
18480
+ * Session is resumed through the optional Session controller first; without
18481
+ * that capability the release fails softly and the caller reports the
18482
+ * occupant, rather than clearing a durable mode the Host cannot rewrite.
18483
+ * @param occupant - active Session to disable.
18484
+ * @param reason - `archived` or `duplicate`, recorded in the warning.
18485
+ * @returns whether the durable mode is now off (or already was).
18486
+ */
18487
+ async releaseActiveOccupant(occupant, reason) {
18488
+ let session = this.ctx.sessions.get(toSessionId3(occupant.sessionId));
18489
+ if (session === void 0) {
18490
+ const controller = this.ctx.get("sessionController");
18491
+ if (controller === void 0) {
18492
+ this.ctx.logger.warn(
18493
+ `devlead: Session "${occupant.sessionId}" still holds DevLead mode but is cold and no Session controller can resume it to release the slot`
18494
+ );
18495
+ return false;
18496
+ }
18497
+ try {
18498
+ const resolved = await controller.resolveAgent(toSessionId3(occupant.sessionId));
18499
+ if ("error" in resolved) {
18500
+ this.ctx.logger.warn(
18501
+ `devlead: could not resume DevLead occupant "${occupant.sessionId}" to release the slot: ${resolved.error.message}`
18502
+ );
18503
+ return false;
18504
+ }
18505
+ session = resolved.agent.session;
18506
+ } catch (error51) {
18507
+ this.ctx.logger.warn(
18508
+ `devlead: could not resume DevLead occupant "${occupant.sessionId}" to release the slot: ${thrownMessage(error51)}`
18509
+ );
18510
+ return false;
18511
+ }
18512
+ }
18513
+ try {
18514
+ const state = this.projectionHandle.stateOf(session);
18515
+ if (state.failure !== null) {
18516
+ this.ctx.logger.warn(
18517
+ `devlead: cannot release DevLead occupant "${occupant.sessionId}": its projection is damaged (${state.failure})`
18518
+ );
18519
+ return false;
18520
+ }
18521
+ if (state.enabled) {
18522
+ appendPluginRecord2(session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(false, Date.now()));
18523
+ await this.flushDurably(session, `DevLead release for Session "${occupant.sessionId}"`);
18524
+ await this.checkpointProjectionCache(session, `DevLead release for Session "${occupant.sessionId}"`);
18525
+ }
18526
+ } catch (error51) {
18527
+ this.ctx.logger.warn(
18528
+ `devlead: could not release DevLead occupant "${occupant.sessionId}": ${thrownMessage(error51)}`
18529
+ );
18530
+ return false;
18531
+ }
18532
+ if (this.activeSessionId === occupant.sessionId) this.activeSessionId = void 0;
18533
+ this.ctx.logger.warn(
18534
+ `devlead: disabled DevLead mode for Session "${occupant.sessionId}" (${reason}); only one Session may hold DevLead mode at a time`
18535
+ );
18536
+ await this.rememberReleased(occupant.sessionId);
18537
+ return true;
18538
+ }
18539
+ /** Remember one ignored archived holder in memory and, when available, durably. */
18540
+ async rememberIgnored(sessionId) {
18541
+ this.ignoredArchived.add(sessionId);
18542
+ await this.outbox?.rememberIgnored(sessionId);
18543
+ }
18544
+ /** Forget one ignored-holder tombstone after a successful release. */
18545
+ async rememberReleased(sessionId) {
18546
+ if (!this.ignoredArchived.delete(sessionId)) return;
18547
+ await this.outbox?.forgetIgnored(sessionId);
18548
+ }
18549
+ /**
18550
+ * Reconcile a Host that already has (or has recovered) multiple enabled
18551
+ * Sessions.
18552
+ *
18553
+ * Archived holders are released first. The remaining occupants are ranked
18554
+ * deterministically; the preferred/live/newest one stays enabled and every
18555
+ * other is durably disabled with a warning. If a cold holder cannot be
18556
+ * resumed, it is left enabled and keeps blocking new admissions, which is
18557
+ * safer than silently creating a second active Session.
18558
+ * @param preferredSessionId - incumbent to keep when it is still active.
18559
+ */
18560
+ async reconcileActiveSessions(preferredSessionId, options = {}) {
18561
+ if (this.disposed) return;
18562
+ try {
18563
+ await this.withAdmission(async () => {
18564
+ if (this.disposed) return;
18565
+ const scanned = await this.scanActiveSessions(void 0, options.includePersisted !== false);
18566
+ const merged = /* @__PURE__ */ new Map();
18567
+ for (const occupant of options.knownActive ?? []) merged.set(occupant.sessionId, occupant);
18568
+ for (const occupant of scanned) merged.set(occupant.sessionId, occupant);
18569
+ const liveIds = /* @__PURE__ */ new Set();
18570
+ for (const agent of this.ctx.agents.list()) liveIds.add(String(agent.id));
18571
+ for (const session of this.ctx.sessions.list()) liveIds.add(String(session.id));
18572
+ for (const sessionId of liveIds) {
18573
+ if (!scanned.some((occupant) => occupant.sessionId === sessionId)) merged.delete(sessionId);
18574
+ }
18575
+ const active = [...merged.values()];
18576
+ if (active.length === 0) {
18577
+ this.activeSessionId = void 0;
18578
+ return;
18579
+ }
18580
+ const remaining = [];
18581
+ for (const occupant of active) {
18582
+ if (occupant.archived) {
18583
+ if (!await this.releaseActiveOccupant(occupant, "archived")) {
18584
+ await this.rememberIgnored(occupant.sessionId);
18585
+ this.ctx.logger.warn(
18586
+ `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`
18587
+ );
18588
+ }
18589
+ continue;
18590
+ }
18591
+ if (this.ignoredArchived.has(occupant.sessionId)) {
18592
+ if (await this.releaseActiveOccupant(occupant, "duplicate")) {
18593
+ await this.rememberReleased(occupant.sessionId);
18594
+ }
18595
+ continue;
18596
+ }
18597
+ remaining.push(occupant);
18598
+ }
18599
+ if (remaining.length === 0) {
18600
+ this.activeSessionId = void 0;
18601
+ return;
18602
+ }
18603
+ const ranked = rankActiveSessions(remaining, preferredSessionId ?? this.activeSessionId);
18604
+ const keeper = ranked[0];
18605
+ if (keeper === void 0) return;
18606
+ this.activeSessionId = keeper.sessionId;
18607
+ let failed = 0;
18608
+ for (const extra of ranked.slice(1)) {
18609
+ if (!await this.releaseActiveOccupant(extra, "duplicate")) failed += 1;
18610
+ }
18611
+ if (ranked.length > 1) {
18612
+ this.ctx.logger.warn(
18613
+ `devlead: found ${ranked.length} enabled Sessions after recovery; keeping "${keeper.sessionId}"` + (failed > 0 ? ` and could not disable ${failed}` : "")
18614
+ );
18615
+ }
18616
+ });
18617
+ } catch (error51) {
18618
+ if (!this.disposed) {
18619
+ this.ctx.logger.warn(`devlead: global DevLead admission reconciliation failed: ${thrownMessage(error51)}`);
18620
+ }
18621
+ }
18622
+ }
17279
18623
  /** Reject any use of a tool surface while DevLead mode is off. */
17280
18624
  assertReady(agent) {
17281
18625
  this.assertLive(agent);
@@ -17330,10 +18674,18 @@ var DevLeadService = class extends Service {
17330
18674
  */
17331
18675
  async persistedLeadRecords(scanPersisted) {
17332
18676
  const leads = /* @__PURE__ */ new Map();
18677
+ const active = [];
18678
+ const archived = new Set(
18679
+ (this.ctx.get("workspaceRegistry")?.archivedSessionIds ?? []).map((id) => String(id))
18680
+ );
17333
18681
  const remember = (sessionId, sessions) => {
17334
18682
  if (sessionId.length === 0 || sessions.length === 0) return;
17335
18683
  leads.set(sessionId, [...sessions]);
17336
18684
  };
18685
+ const result = () => ({
18686
+ leads: [...leads].map(([sessionId, watched]) => ({ sessionId, watched })),
18687
+ active
18688
+ });
17337
18689
  for (const lead of this.liveAttachLeads()) remember(lead.sessionId, lead.watched);
17338
18690
  if (!scanPersisted) {
17339
18691
  if (this.ctx.get("sessionQuery") === void 0) {
@@ -17343,23 +18695,23 @@ var DevLeadService = class extends Service {
17343
18695
  "devlead: the Session persistence binding is not composed yet; cold lead rehydration scans live Sessions only"
17344
18696
  );
17345
18697
  }
17346
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18698
+ return result();
17347
18699
  }
17348
18700
  const query = this.ctx.get("sessionQuery");
17349
- if (query === void 0) return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18701
+ if (query === void 0) return result();
17350
18702
  const cache = projectionCacheOf(this.ctx);
17351
18703
  if (cache === void 0) {
17352
18704
  this.ctx.logger.warn(
17353
18705
  "devlead: this Host composes no Session projection cache, so cold lead rehydration reads no persisted logs; only live lead Sessions are rehydrated"
17354
18706
  );
17355
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18707
+ return result();
17356
18708
  }
17357
18709
  let records;
17358
18710
  try {
17359
18711
  records = await query.listSessions();
17360
18712
  } catch (error51) {
17361
18713
  this.ctx.logger.warn(`devlead: could not list persisted Sessions for cold lead rehydration: ${thrownMessage(error51)}`);
17362
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18714
+ return result();
17363
18715
  }
17364
18716
  let unknownReads = 0;
17365
18717
  let capped = false;
@@ -17369,8 +18721,8 @@ var DevLeadService = class extends Service {
17369
18721
  const sessionId = String(record2.header.id);
17370
18722
  if (leads.has(sessionId) || record2.live) continue;
17371
18723
  if (record2.header.origin === "subagent") continue;
17372
- const prefilter = devLeadPrefilterOf(cache, record2.header);
17373
- if (prefilter === "not-lead") continue;
18724
+ const prefilter = devLeadActivePrefilterOf(cache, record2.header);
18725
+ if (prefilter === "inactive") continue;
17374
18726
  if (prefilter === "unknown") {
17375
18727
  if (unknownReads >= MAX_COLD_LEAD_LOG_READS) {
17376
18728
  capped = true;
@@ -17400,14 +18752,23 @@ var DevLeadService = class extends Service {
17400
18752
  }
17401
18753
  continue;
17402
18754
  }
17403
- if (state.enabled) remember(sessionId, state.sessions);
18755
+ if (!state.enabled) continue;
18756
+ active.push({
18757
+ sessionId,
18758
+ live: false,
18759
+ archived: archived.has(sessionId),
18760
+ running: false,
18761
+ createdAt: record2.header.createdAt,
18762
+ enabledAt: lastEnabledAt(events) ?? 0
18763
+ });
18764
+ remember(sessionId, state.sessions);
17404
18765
  }
17405
18766
  if (capped) {
17406
18767
  this.ctx.logger.warn(
17407
18768
  `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
18769
  );
17409
18770
  }
17410
- return [...leads].map(([sessionId, watched]) => ({ sessionId, watched }));
18771
+ return result();
17411
18772
  }
17412
18773
  /**
17413
18774
  * Validate one requested model selection against the Host's LLM registry.
@@ -17766,6 +19127,7 @@ var DevLeadService = class extends Service {
17766
19127
  appendPluginRecord2(agent.session, DEVLEAD_WATCH_RECORD_TYPE, watchRecord(next, Date.now()));
17767
19128
  await this.flushDurably(agent.session, `watch set for lead "${agent.id}"`);
17768
19129
  await this.checkpointProjectionCache(agent.session, `watch set for lead "${agent.id}"`);
19130
+ if (watching) void this.replayOutbox();
17769
19131
  return { sessionId: id, watched: watching, sessions: next };
17770
19132
  }
17771
19133
  };
@@ -17780,18 +19142,24 @@ export {
17780
19142
  DEVLEAD_MODE_RECORD_TYPE,
17781
19143
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
17782
19144
  DEVLEAD_RECORD_VERSION,
19145
+ DEVLEAD_REPORT_MESSAGE_MAX,
19146
+ DEVLEAD_REPORT_RECORD_TYPE,
19147
+ DEVLEAD_REPORT_SUMMARY_MAX,
17783
19148
  DEVLEAD_RESET_RECORD_TYPE,
17784
19149
  DEVLEAD_WATCH_RECORD_TYPE,
17785
19150
  DevLeadError,
17786
19151
  DevLeadService,
17787
19152
  applyDevLeadModeProjection,
17788
19153
  applyDevLeadProjection,
19154
+ applyDevLeadWatchProjection,
17789
19155
  assistantExcerpt,
17790
19156
  createDevLeadNoticeMessage,
17791
19157
  createDevLeadPromptMessage,
17792
19158
  decodeModeRecord,
17793
19159
  decodeNotification,
17794
19160
  decodeNotificationRecord,
19161
+ decodeReport,
19162
+ decodeReportRecord,
17795
19163
  decodeResetRecord,
17796
19164
  decodeWatchRecord,
17797
19165
  index_default as default,
@@ -17804,14 +19172,21 @@ export {
17804
19172
  devLeadProjectionSchema,
17805
19173
  devLeadProjectionStateSchema,
17806
19174
  devLeadProjectionView,
19175
+ devLeadReport,
19176
+ devLeadWatchProjectionDefinition,
19177
+ devLeadWatchProjectionSchema,
19178
+ devLeadWatchProjectionStateSchema,
19179
+ devLeadWatchProjectionView,
17807
19180
  emptyDevLeadModeProjectionState,
17808
19181
  emptyDevLeadProjectionState,
19182
+ emptyDevLeadWatchProjectionState,
17809
19183
  failureExcerpt,
17810
19184
  isDevLeadError,
17811
19185
  modeRecord,
17812
19186
  notificationId,
17813
19187
  notificationRecord,
17814
19188
  renderDevLeadNotice,
19189
+ reportRecord,
17815
19190
  representableInstant,
17816
19191
  resetRecord,
17817
19192
  watchRecord