@yankeguo/dsh-devlead 0.4.0 → 0.4.2-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +32 -7
  2. package/lib/index.js +1468 -47
  3. package/package.json +3 -2
package/lib/index.js CHANGED
@@ -6,7 +6,8 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // packages/devlead/src/index.ts
9
- import { mkdir } from "node:fs/promises";
9
+ import { mkdir as mkdir2, stat as stat3 } from "node:fs/promises";
10
+ import { isAbsolute as isAbsolute3 } from "node:path";
10
11
  import { Service } from "@deepseek-ai/cordis";
11
12
  import z2 from "@deepseek-ai/schemastery";
12
13
  import { MessageId, ReasoningEffortId } from "@deepseek-ai/dsh-llm";
@@ -122,6 +123,302 @@ function readRecord(event) {
122
123
  }
123
124
  }
124
125
 
126
+ // packages/devlead/src/session-log-recovery.ts
127
+ import { open, stat } from "node:fs/promises";
128
+ import { isAbsolute } from "node:path";
129
+ import { promisify } from "node:util";
130
+ import { constants, zstdDecompress } from "node:zlib";
131
+ import { SessionLogOffset } from "@deepseek-ai/dsh-session";
132
+ var decompress = promisify(zstdDecompress);
133
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
134
+ var ZSTD_MAGIC = 4247762216;
135
+ var DEVLEAD_RECORD_PREFIX = "plugin:devlead/";
136
+ var HEADER_REQUIRED = ["type", "version", "id", "createdAt", "isSeeded", "delegationDepth"];
137
+ var HEADER_OPTIONAL = ["cwd", "parentSession", "origin", "agentPreset"];
138
+ var EVENT_REQUIRED = ["type", "seq", "time", "data"];
139
+ var EVENT_OPTIONAL = ["ignorable", "sourceEventSeqs", "surfaceOp"];
140
+ function isUnknownNonIgnorableEventError(error51) {
141
+ for (let current = error51, depth = 0; depth < 8 && current !== void 0 && current !== null; depth += 1) {
142
+ if (typeof current === "object") {
143
+ const candidate = current;
144
+ if (candidate.name === "SessionFormatUnsupportedError" && typeof candidate.message === "string" && candidate.message.includes("unknown to this harness and not marked ignorable")) return true;
145
+ current = candidate.cause;
146
+ continue;
147
+ }
148
+ break;
149
+ }
150
+ return false;
151
+ }
152
+ async function recoverUnknownEventSessionLog(ctx, header, signal) {
153
+ const persistence = ctx.get("sessionPersistence");
154
+ const stat4 = persistence?.stat;
155
+ if (typeof stat4 !== "function") {
156
+ throw new Error(`Session "${String(header.id)}" needs read-only log recovery, but the persistence backend exposes no stat()`);
157
+ }
158
+ signal?.throwIfAborted();
159
+ const snapshot = await stat4.call(
160
+ persistence,
161
+ header.id,
162
+ signal === void 0 ? void 0 : { signal }
163
+ );
164
+ signal?.throwIfAborted();
165
+ const location = snapshot?.location;
166
+ const path = location?.path;
167
+ const kind = location?.kind;
168
+ if (kind !== "jsonl" || typeof path !== "string" || !isAbsolute(path)) {
169
+ throw new Error(`Session "${String(header.id)}" has no backend-verified absolute JSONL artifact path for read-only recovery`);
170
+ }
171
+ return await readCurrentJsonlForDevLead(path, header, signal);
172
+ }
173
+ async function readCurrentJsonlForDevLead(path, expectedHeader, signal) {
174
+ if (!isAbsolute(path) || !/session\.v4\.jsonl(?:\.zstd)?$/.test(path)) {
175
+ throw new Error(`read-only DevLead recovery supports only current session.v4.jsonl[.zstd] artifacts: ${path}`);
176
+ }
177
+ signal?.throwIfAborted();
178
+ const beforePath = await stat(path, { bigint: true });
179
+ const handle = await open(path, "r");
180
+ let bytes;
181
+ try {
182
+ const beforeHandle = await handle.stat({ bigint: true });
183
+ assertSamePhysicalFile(beforePath, beforeHandle, path);
184
+ bytes = await handle.readFile(signal === void 0 ? void 0 : { signal });
185
+ const afterHandle = await handle.stat({ bigint: true });
186
+ const afterPath = await stat(path, { bigint: true });
187
+ assertSamePhysicalFile(beforeHandle, afterHandle, path);
188
+ assertSamePhysicalFile(afterHandle, afterPath, path);
189
+ } finally {
190
+ await handle.close();
191
+ }
192
+ signal?.throwIfAborted();
193
+ let plaintext;
194
+ try {
195
+ plaintext = path.endsWith(".zstd") ? await decodeZstdFrames(bytes, signal) : bytes;
196
+ } catch (error51) {
197
+ signal?.throwIfAborted();
198
+ throw new Error(`could not decode Session log ${path}: ${error51 instanceof Error ? error51.message : String(error51)}`, { cause: error51 });
199
+ }
200
+ signal?.throwIfAborted();
201
+ const events = parseCurrentJsonl(plaintext, expectedHeader, path);
202
+ return { path, inheritedEventCount: inheritedCut(events, expectedHeader, path), events };
203
+ }
204
+ function assertSamePhysicalFile(left, right, path) {
205
+ if (left.dev !== right.dev || left.ino !== right.ino || left.size !== right.size || left.mtimeNs !== right.mtimeNs || left.ctimeNs !== right.ctimeNs) {
206
+ throw new Error(`Session log changed during read-only recovery; retry the bounded scan: ${path}`);
207
+ }
208
+ }
209
+ async function decodeZstdFrames(bytes, signal) {
210
+ const { frames, tornStart } = scanFrames(bytes);
211
+ if (frames.length === 0) throw new Error("empty or header-less Zstandard session log");
212
+ const chunks = [];
213
+ for (const frame of frames) {
214
+ signal?.throwIfAborted();
215
+ chunks.push(await decompress(bytes.subarray(frame.start, frame.end)));
216
+ }
217
+ const header = chunks[0];
218
+ if (header.length === 0 || header.indexOf(10) !== header.length - 1) {
219
+ throw new Error("corrupt Zstandard session log: first frame is not exactly one header line");
220
+ }
221
+ const complete = Buffer.concat(chunks);
222
+ if (complete.length === 0 || complete.at(-1) !== 10) {
223
+ throw new Error("corrupt Zstandard session log: complete frame contains a torn JSONL record");
224
+ }
225
+ if (tornStart === void 0) return complete;
226
+ signal?.throwIfAborted();
227
+ try {
228
+ const recovered = await decompress(bytes.subarray(tornStart), {
229
+ finishFlush: constants.ZSTD_e_flush
230
+ });
231
+ return Buffer.concat([complete, recovered]);
232
+ } catch (error51) {
233
+ signal?.throwIfAborted();
234
+ if (error51 instanceof Error && error51.name === "AbortError") throw error51;
235
+ return complete;
236
+ }
237
+ }
238
+ function scanFrames(bytes) {
239
+ const frames = [];
240
+ let offset = 0;
241
+ while (offset < bytes.length) {
242
+ const start = offset;
243
+ if (bytes.length - offset < 4) return { frames, tornStart: start };
244
+ if (bytes.readUInt32LE(offset) !== ZSTD_MAGIC) {
245
+ throw new Error(`corrupt Zstandard session log: invalid frame magic at byte ${offset}`);
246
+ }
247
+ offset += 4;
248
+ if (offset === bytes.length) return { frames, tornStart: start };
249
+ const descriptor = bytes.readUInt8(offset);
250
+ offset += 1;
251
+ if ((descriptor & 24) !== 0) {
252
+ throw new Error(`corrupt Zstandard session log: reserved frame-header bit at byte ${offset - 1}`);
253
+ }
254
+ const contentSizeFlag = descriptor >>> 6;
255
+ const singleSegment = (descriptor & 32) !== 0;
256
+ const checksum = (descriptor & 4) !== 0;
257
+ const dictionaryFlag = descriptor & 3;
258
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
259
+ const contentSizeBytes = contentSizeFlag === 0 ? singleSegment ? 1 : 0 : 1 << contentSizeFlag;
260
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
261
+ if (bytes.length - offset < remainingHeaderBytes) return { frames, tornStart: start };
262
+ offset += remainingHeaderBytes;
263
+ for (; ; ) {
264
+ if (bytes.length - offset < 3) return { frames, tornStart: start };
265
+ const blockHeader = bytes.readUIntLE(offset, 3);
266
+ offset += 3;
267
+ const lastBlock = (blockHeader & 1) !== 0;
268
+ const blockType = blockHeader >>> 1 & 3;
269
+ const blockSize = blockHeader >>> 3;
270
+ if (blockType === 3) {
271
+ throw new Error(`corrupt Zstandard session log: reserved block type at byte ${offset - 3}`);
272
+ }
273
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
274
+ if (bytes.length - offset < payloadBytes) return { frames, tornStart: start };
275
+ offset += payloadBytes;
276
+ if (lastBlock) break;
277
+ }
278
+ if (checksum) {
279
+ if (bytes.length - offset < 4) return { frames, tornStart: start };
280
+ offset += 4;
281
+ }
282
+ frames.push({ start, end: offset });
283
+ }
284
+ return { frames };
285
+ }
286
+ function parseCurrentJsonl(bytes, expectedHeader, path) {
287
+ const headerEnd = bytes.indexOf(10);
288
+ if (headerEnd < 0) throw new Error(`empty or header-less Session log: ${path}`);
289
+ const header = parseRecord(bytes.subarray(0, headerEnd), "header", path);
290
+ assertExactKeys(header, HEADER_REQUIRED, HEADER_OPTIONAL, "physical Session header", path);
291
+ if (header["type"] !== "session" || header["version"] !== 4 || typeof header["id"] !== "string" || typeof header["isSeeded"] !== "boolean" || header["origin"] !== void 0 && header["origin"] !== "subagent") {
292
+ throw new Error(`invalid physical v4 Session header in ${path}`);
293
+ }
294
+ assertCount(header["createdAt"], "header createdAt", path);
295
+ assertCount(header["delegationDepth"], "header delegationDepth", path);
296
+ for (const key of ["parentSession", "agentPreset"]) {
297
+ if (header[key] !== void 0 && typeof header[key] !== "string") {
298
+ throw new Error(`invalid physical Session header ${key} in ${path}`);
299
+ }
300
+ }
301
+ if (header["cwd"] !== void 0 && (typeof header["cwd"] !== "string" || !isAbsolute(header["cwd"]))) {
302
+ throw new Error(`invalid physical Session header cwd in ${path}`);
303
+ }
304
+ if (header["id"] !== String(expectedHeader.id) || header["createdAt"] !== expectedHeader.createdAt || header["isSeeded"] !== (expectedHeader.isSeeded === true) || header["cwd"] !== expectedHeader.cwd || header["parentSession"] !== expectedHeader.parentSession || header["origin"] !== expectedHeader.origin || header["agentPreset"] !== expectedHeader.agentPreset || header["delegationDepth"] !== (expectedHeader.delegationDepth ?? 0)) {
305
+ throw new Error(`Session log header does not match the validated corpus listing: ${path}`);
306
+ }
307
+ const events = [];
308
+ let lineStart = headerEnd + 1;
309
+ while (lineStart < bytes.length) {
310
+ const newline = bytes.indexOf(10, lineStart);
311
+ if (newline < 0) break;
312
+ const line = bytes.subarray(lineStart, newline);
313
+ lineStart = newline + 1;
314
+ const event = parseRecord(line, `event ${String(events.length)}`, path);
315
+ assertExactKeys(event, EVENT_REQUIRED, EVENT_OPTIONAL, `Session event ${String(events.length)}`, path);
316
+ if (typeof event["type"] !== "string" || event["type"].length === 0) {
317
+ throw new Error(`invalid Session event type at seq ${String(events.length)} in ${path}`);
318
+ }
319
+ assertCount(event["seq"], `Session event ${String(events.length)} seq`, path);
320
+ if (event["seq"] !== events.length) {
321
+ throw new Error(`non-contiguous Session event ${String(events.length)} in ${path}`);
322
+ }
323
+ if (!Number.isSafeInteger(event["time"]) || Object.is(event["time"], -0)) {
324
+ throw new Error(`invalid Session event time at seq ${String(events.length)} in ${path}`);
325
+ }
326
+ if (event["ignorable"] !== void 0 && event["ignorable"] !== true) {
327
+ throw new Error(`Session event ignorable must be true when present at seq ${String(events.length)} in ${path}`);
328
+ }
329
+ if (event["type"] === "session/end-seed") assertEndSeedData(event["data"], events.length, path);
330
+ if (event["type"].startsWith(DEVLEAD_RECORD_PREFIX) && event["ignorable"] !== true) {
331
+ throw new Error(`DevLead record at seq ${String(events.length)} is not marked ignorable in ${path}`);
332
+ }
333
+ const decoded = event["sourceEventSeqs"] === void 0 ? event : {
334
+ ...event,
335
+ sourceEventSeqs: decodeSourceEventSeqs(event["sourceEventSeqs"], events.length, path)
336
+ };
337
+ events.push(decoded);
338
+ }
339
+ return events;
340
+ }
341
+ function assertEndSeedData(data, seq, path) {
342
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
343
+ throw new Error(`session/end-seed data must be an object at seq ${String(seq)} in ${path}`);
344
+ }
345
+ const record2 = data;
346
+ if (Object.keys(record2).some((key) => key !== "inherited") || record2["inherited"] !== void 0 && record2["inherited"] !== true) {
347
+ throw new Error(`invalid session/end-seed data at seq ${String(seq)} in ${path}`);
348
+ }
349
+ }
350
+ function assertExactKeys(record2, required2, optional2, label, path) {
351
+ const allowed = /* @__PURE__ */ new Set([...required2, ...optional2]);
352
+ const missing = required2.find((key) => !Object.hasOwn(record2, key));
353
+ if (missing !== void 0) throw new Error(`${label} lacks required field ${missing} in ${path}`);
354
+ const unexpected = Object.keys(record2).find((key) => !allowed.has(key));
355
+ if (unexpected !== void 0) throw new Error(`${label} has unexpected field ${unexpected} in ${path}`);
356
+ }
357
+ function assertCount(value, label, path) {
358
+ if (!Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {
359
+ throw new Error(`${label} must be a non-negative safe integer in ${path}`);
360
+ }
361
+ }
362
+ function decodeSourceEventSeqs(value, maxEntries, path) {
363
+ if (!Array.isArray(value)) throw new Error(`sourceEventSeqs must be an array in ${path}`);
364
+ const output = [];
365
+ let hasRange = false;
366
+ for (const entry of value) {
367
+ if (!Array.isArray(entry)) {
368
+ assertCount(entry, "sourceEventSeqs member", path);
369
+ output.push(entry);
370
+ continue;
371
+ }
372
+ if (entry.length !== 2) throw new Error(`sourceEventSeqs range must be a [start, end] pair in ${path}`);
373
+ assertCount(entry[0], "sourceEventSeqs range start", path);
374
+ assertCount(entry[1], "sourceEventSeqs range end", path);
375
+ const start = entry[0];
376
+ const end = entry[1];
377
+ if (start > end || end >= maxEntries || end - start + 1 > maxEntries - output.length) {
378
+ throw new Error(`sourceEventSeqs range exceeds its event seq in ${path}`);
379
+ }
380
+ for (let current = start; current <= end; current += 1) output.push(current);
381
+ hasRange = true;
382
+ }
383
+ const seen = /* @__PURE__ */ new Set();
384
+ for (const source of output) {
385
+ if (source >= maxEntries || seen.has(source)) {
386
+ throw new Error(`sourceEventSeqs must contain unique earlier seqs in ${path}`);
387
+ }
388
+ seen.add(source);
389
+ }
390
+ if (hasRange && output.some((source, index) => index > 0 && source <= output[index - 1])) {
391
+ throw new Error(`sourceEventSeqs ranges must be strictly increasing in ${path}`);
392
+ }
393
+ return output;
394
+ }
395
+ function parseRecord(line, label, path) {
396
+ let value;
397
+ try {
398
+ value = JSON.parse(utf8.decode(line));
399
+ } catch (error51) {
400
+ throw new Error(`invalid committed ${label} JSON in ${path}`, { cause: error51 });
401
+ }
402
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
403
+ throw new Error(`invalid committed ${label}: expected a JSON object in ${path}`);
404
+ }
405
+ return value;
406
+ }
407
+ function inheritedCut(events, header, path) {
408
+ let inherited;
409
+ for (const event of events) {
410
+ if (event.type !== "session/end-seed") continue;
411
+ const data = event.data;
412
+ if (data?.inherited === true) inherited = event.seq;
413
+ }
414
+ if (header.isSeeded === true) {
415
+ if (inherited === void 0) throw new Error(`seeded Session has no inherited-cut marker: ${path}`);
416
+ return SessionLogOffset(inherited);
417
+ }
418
+ if (inherited !== void 0) throw new Error(`unseeded Session has an inherited-cut marker: ${path}`);
419
+ return SessionLogOffset(0);
420
+ }
421
+
125
422
  // packages/devlead/src/index.ts
126
423
  import {
127
424
  DEVLEAD_DEFAULT_MAX_WATCHED as DEVLEAD_DEFAULT_MAX_WATCHED2,
@@ -16595,8 +16892,8 @@ function applyDevLeadProjection(state, event) {
16595
16892
  return mode.enabled === state.enabled ? state : { ...state, enabled: mode.enabled };
16596
16893
  }
16597
16894
  case DEVLEAD_WATCH_RECORD_TYPE2: {
16598
- const watch = decodeWatchRecord(record2.data);
16599
- return sameSessionIds(state.sessions, watch.sessions) ? state : { ...state, sessions: watch.sessions };
16895
+ const watch2 = decodeWatchRecord(record2.data);
16896
+ return sameSessionIds(state.sessions, watch2.sessions) ? state : { ...state, sessions: watch2.sessions };
16600
16897
  }
16601
16898
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2: {
16602
16899
  const notification = decodeNotificationRecord(record2.data);
@@ -16703,8 +17000,8 @@ function applyDevLeadWatchProjection(state, event) {
16703
17000
  try {
16704
17001
  switch (record2.type) {
16705
17002
  case DEVLEAD_WATCH_RECORD_TYPE2: {
16706
- const watch = decodeWatchRecord(record2.data);
16707
- return sameSessionIds(state.sessions, watch.sessions) ? state : { sessions: watch.sessions, failure: null, inheritedEventCount: state.inheritedEventCount };
17003
+ const watch2 = decodeWatchRecord(record2.data);
17004
+ return sameSessionIds(state.sessions, watch2.sessions) ? state : { sessions: watch2.sessions, failure: null, inheritedEventCount: state.inheritedEventCount };
16708
17005
  }
16709
17006
  case DEVLEAD_MODE_RECORD_TYPE2:
16710
17007
  decodeModeRecord(record2.data);
@@ -17684,6 +17981,749 @@ function worktreeCapabilityOf(ctx) {
17684
17981
  return candidate;
17685
17982
  }
17686
17983
 
17984
+ // packages/devlead/src/board.ts
17985
+ import { watch } from "node:fs";
17986
+ import { mkdir, readFile, stat as stat2 } from "node:fs/promises";
17987
+ import { basename, dirname, isAbsolute as isAbsolute2, join, normalize } from "node:path";
17988
+ import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
17989
+ import {
17990
+ createDevLeadBoardSchema,
17991
+ devLeadBoardIssueViews,
17992
+ DEVLEAD_BOARD_DIR_SEGMENTS,
17993
+ DEVLEAD_BOARD_FILE_NAME,
17994
+ DEVLEAD_BOARD_ID_MAX,
17995
+ DEVLEAD_BOARD_MAX_BLOCKERS,
17996
+ DEVLEAD_BOARD_MAX_BYTES,
17997
+ DEVLEAD_BOARD_MAX_PROJECTS,
17998
+ DEVLEAD_BOARD_MAX_TASKS,
17999
+ DEVLEAD_BOARD_PATH_MAX,
18000
+ DEVLEAD_BOARD_READ_MAX_BYTES,
18001
+ DEVLEAD_BOARD_SCHEMA_VERSION,
18002
+ DEVLEAD_BOARD_TEXT_MAX,
18003
+ DEVLEAD_BOARD_TITLE_MAX
18004
+ } from "@yankeguo/dsh-devlead-protocol";
18005
+ var DEVLEAD_BOARD_SUMMARY_MAX_BYTES = 1536;
18006
+ var DEVLEAD_BOARD_READ_MAX_TASKS = 50;
18007
+ var DEVLEAD_BOARD_READ_ATTEMPTS = 4;
18008
+ var DevLeadBoardError = class extends Error {
18009
+ /**
18010
+ * @param message - human-readable failure.
18011
+ * @param code - stable tool-facing code.
18012
+ * @param issues - path-qualified validation details.
18013
+ */
18014
+ constructor(message, code, issues = []) {
18015
+ super(message);
18016
+ this.code = code;
18017
+ this.issues = issues;
18018
+ this.name = "DevLeadBoardError";
18019
+ }
18020
+ code;
18021
+ issues;
18022
+ };
18023
+ function isDevLeadBoardError(error51) {
18024
+ if (error51 instanceof DevLeadBoardError) return true;
18025
+ if (!(error51 instanceof Error)) return false;
18026
+ const code = error51.code;
18027
+ return typeof code === "string" && code.startsWith("BOARD_");
18028
+ }
18029
+ var devLeadBoardSchema = createDevLeadBoardSchema(isAbsolute2);
18030
+ function sameFingerprint(left, right) {
18031
+ return left !== void 0 && left.mtimeMs === right.mtimeMs && left.size === right.size && left.ino === right.ino;
18032
+ }
18033
+ function validationError(error51) {
18034
+ const issues = devLeadBoardIssueViews(error51.issues);
18035
+ const limited = error51.issues.some((issue2) => issue2.code === "too_big");
18036
+ const code = limited ? "BOARD_LIMIT_EXCEEDED" : "BOARD_INVALID";
18037
+ const first = issues[0];
18038
+ return new DevLeadBoardError(
18039
+ `board validation failed${first === void 0 ? "" : ` at ${first.pointer || "/"}: ${first.message}`}`,
18040
+ code,
18041
+ issues
18042
+ );
18043
+ }
18044
+ function parseBoard(value) {
18045
+ const parsed = devLeadBoardSchema.safeParse(value);
18046
+ if (!parsed.success) throw validationError(parsed.error);
18047
+ return parsed.data;
18048
+ }
18049
+ function errorMessage2(error51) {
18050
+ return error51 instanceof Error ? error51.message : String(error51);
18051
+ }
18052
+ var FILESYSTEM_ERROR_CODES = /* @__PURE__ */ new Set([
18053
+ "EACCES",
18054
+ "EAGAIN",
18055
+ "EBUSY",
18056
+ "EDQUOT",
18057
+ "EEXIST",
18058
+ "EFBIG",
18059
+ "EIO",
18060
+ "EISDIR",
18061
+ "ELOOP",
18062
+ "EMFILE",
18063
+ "ENAMETOOLONG",
18064
+ "ENFILE",
18065
+ "ENOMEM",
18066
+ "ENOENT",
18067
+ "ENOSPC",
18068
+ "ENOTDIR",
18069
+ "ENOTEMPTY",
18070
+ "EPERM",
18071
+ "EROFS",
18072
+ "ETXTBSY"
18073
+ ]);
18074
+ function errorCode(error51) {
18075
+ if (typeof error51 !== "object" || error51 === null) return void 0;
18076
+ const code = error51.code;
18077
+ return typeof code === "string" ? code : void 0;
18078
+ }
18079
+ function isWriterLockTimeout(error51) {
18080
+ const message = errorMessage2(error51);
18081
+ const code = errorCode(error51);
18082
+ return code === "FILE_LOCK_TIMEOUT" || code === "ATOMIC_WRITE_LOCK_TIMEOUT" || /timed out waiting for the writer lock|writer lock timed out/iu.test(message);
18083
+ }
18084
+ function isWriteIoError(error51) {
18085
+ const code = errorCode(error51);
18086
+ return code !== void 0 && FILESYSTEM_ERROR_CODES.has(code) || error51 instanceof Error && error51.name === "FileLockError" || isWriterLockTimeout(error51);
18087
+ }
18088
+ function writeIoError(filePath, error51) {
18089
+ const retry = isWriterLockTimeout(error51);
18090
+ return new DevLeadBoardError(
18091
+ `could not write board ${filePath}: ${errorMessage2(error51)}${retry ? "; retry after the current writer finishes" : ""}`,
18092
+ "BOARD_IO_ERROR"
18093
+ );
18094
+ }
18095
+ function normalizeUpdatedBy(updatedBy) {
18096
+ const title = updatedBy.title.trim().slice(0, DEVLEAD_BOARD_TITLE_MAX);
18097
+ return { sessionId: updatedBy.sessionId, title: title.length === 0 ? "DevLead" : title };
18098
+ }
18099
+ function resolveDevLeadBoardPath(input = {}) {
18100
+ const override = input.override?.trim() ?? "";
18101
+ if (override.length > 0) {
18102
+ if (!isAbsolute2(override)) return { kind: "disabled", reason: "invalid-override" };
18103
+ return { kind: "resolved", path: normalize(override), source: "override" };
18104
+ }
18105
+ const cwd = input.cwd?.trim() ?? "";
18106
+ if (cwd.length === 0) return { kind: "disabled", reason: "no-workspace" };
18107
+ if (!isAbsolute2(cwd)) return { kind: "disabled", reason: "relative-workspace" };
18108
+ return {
18109
+ kind: "resolved",
18110
+ path: join(normalize(cwd), ...DEVLEAD_BOARD_DIR_SEGMENTS, DEVLEAD_BOARD_FILE_NAME),
18111
+ source: "workspace"
18112
+ };
18113
+ }
18114
+ function boundReadResult(result) {
18115
+ const serializedBytes = (projects2, truncated2) => Buffer.byteLength(JSON.stringify({
18116
+ revision: result.revision,
18117
+ updatedAt: result.updatedAt,
18118
+ projects: projects2,
18119
+ ...truncated2 ? { truncated: true } : {}
18120
+ }), "utf8");
18121
+ if (serializedBytes(result.projects, result.truncated === true) <= DEVLEAD_BOARD_READ_MAX_BYTES) return result;
18122
+ const projects = result.projects.map((project) => structuredClone(project));
18123
+ let truncated = true;
18124
+ for (; ; ) {
18125
+ if (serializedBytes(projects, truncated) <= DEVLEAD_BOARD_READ_MAX_BYTES) break;
18126
+ let trimmed = false;
18127
+ for (let index = projects.length - 1; index >= 0 && !trimmed; index -= 1) {
18128
+ const tasks = projects[index]?.tasks;
18129
+ if (tasks !== void 0 && tasks.length > 0) {
18130
+ projects[index] = { ...projects[index], tasks: tasks.slice(0, -1) };
18131
+ trimmed = true;
18132
+ }
18133
+ }
18134
+ if (trimmed) continue;
18135
+ for (let index = projects.length - 1; index >= 0 && !trimmed; index -= 1) {
18136
+ const project = projects[index];
18137
+ if (project.blockers.length > 0) {
18138
+ projects[index] = { ...project, blockers: project.blockers.slice(0, -1) };
18139
+ trimmed = true;
18140
+ }
18141
+ }
18142
+ if (trimmed) continue;
18143
+ if (projects.length > 1) {
18144
+ projects.pop();
18145
+ continue;
18146
+ }
18147
+ break;
18148
+ }
18149
+ return {
18150
+ revision: result.revision,
18151
+ updatedAt: result.updatedAt,
18152
+ projects,
18153
+ ...truncated ? { truncated: true } : {}
18154
+ };
18155
+ }
18156
+ var DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID = "devlead-validation";
18157
+ function singleLine(value) {
18158
+ return value.replaceAll(/[\p{Cc}\p{Cf}]+/gu, " ").replaceAll(/\s+/gu, " ").trim();
18159
+ }
18160
+ function resolveProject(board, reference) {
18161
+ const trimmed = reference.trim();
18162
+ if (trimmed.length === 0) {
18163
+ throw new DevLeadBoardError("project must not be empty", "BOARD_INVALID", [
18164
+ { pointer: "/project", message: "project must not be empty" }
18165
+ ]);
18166
+ }
18167
+ const byId = board.projects.find((project) => project.id === trimmed);
18168
+ if (byId !== void 0) return byId;
18169
+ const byPath = board.projects.find((project) => project.workspace.path === trimmed);
18170
+ if (byPath !== void 0) return byPath;
18171
+ const titled = board.projects.filter((project) => project.workspace.title === trimmed);
18172
+ if (titled.length === 1 && titled[0] !== void 0) return titled[0];
18173
+ if (titled.length > 1) {
18174
+ throw new DevLeadBoardError(
18175
+ `project title "${trimmed}" is ambiguous; use its id or workspace path`,
18176
+ "BOARD_PROJECT_AMBIGUOUS"
18177
+ );
18178
+ }
18179
+ throw new DevLeadBoardError(`no board project matches "${trimmed}"`, "BOARD_PROJECT_NOT_FOUND");
18180
+ }
18181
+ function emptyBoard(updatedBy, updatedAt) {
18182
+ return {
18183
+ schemaVersion: DEVLEAD_BOARD_SCHEMA_VERSION,
18184
+ revision: 0,
18185
+ updatedAt,
18186
+ updatedBy: structuredClone(updatedBy),
18187
+ projects: []
18188
+ };
18189
+ }
18190
+ function validateUpdateInput(patch) {
18191
+ const normalized = { ...patch, updatedBy: normalizeUpdatedBy(patch.updatedBy) };
18192
+ const timestamp = (/* @__PURE__ */ new Date(0)).toISOString();
18193
+ const candidate = emptyBoard(normalized.updatedBy, timestamp);
18194
+ if (patch.create !== true) {
18195
+ const reference = patch.project.trim();
18196
+ if (reference.length === 0) resolveProject(candidate, reference);
18197
+ const validationTasks = /* @__PURE__ */ new Map();
18198
+ for (const upsert2 of patch.tasks?.upsert ?? []) {
18199
+ if (!validationTasks.has(upsert2.id)) {
18200
+ validationTasks.set(upsert2.id, {
18201
+ id: upsert2.id,
18202
+ title: upsert2.title ?? "DevLead validation",
18203
+ status: "todo",
18204
+ updatedAt: timestamp
18205
+ });
18206
+ }
18207
+ }
18208
+ candidate.projects.push({
18209
+ id: DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID,
18210
+ workspace: { path: "/devlead-validation", title: "DevLead validation" },
18211
+ status: "active",
18212
+ priority: "medium",
18213
+ goal: "",
18214
+ focus: "",
18215
+ next: "",
18216
+ blockers: [],
18217
+ tasks: [...validationTasks.values()],
18218
+ updatedAt: timestamp
18219
+ });
18220
+ }
18221
+ applyProjectPatch(
18222
+ candidate,
18223
+ patch.create === true ? normalized : { ...normalized, project: DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID },
18224
+ timestamp
18225
+ );
18226
+ parseBoard(candidate);
18227
+ return normalized;
18228
+ }
18229
+ function validateMissingFileUpdate(patch, expectedRevision) {
18230
+ const timestamp = (/* @__PURE__ */ new Date(0)).toISOString();
18231
+ const current = emptyBoard(patch.updatedBy, timestamp);
18232
+ if (expectedRevision !== void 0 && expectedRevision !== 0) {
18233
+ throw new DevLeadBoardError(
18234
+ `board revision conflict: expected r${expectedRevision}, current r0`,
18235
+ "BOARD_REVISION_CONFLICT",
18236
+ [{ pointer: "/revision", message: `expected ${expectedRevision}, current 0` }]
18237
+ );
18238
+ }
18239
+ const next = structuredClone(current);
18240
+ applyProjectPatch(next, patch, timestamp);
18241
+ next.revision = 1;
18242
+ next.updatedAt = timestamp;
18243
+ next.updatedBy = structuredClone(patch.updatedBy);
18244
+ parseBoard(next);
18245
+ }
18246
+ function projectView(project, includeTasks) {
18247
+ const view = structuredClone(project);
18248
+ if (includeTasks) view.tasks = (view.tasks ?? []).slice(0, DEVLEAD_BOARD_READ_MAX_TASKS);
18249
+ else delete view.tasks;
18250
+ return view;
18251
+ }
18252
+ function appendUtf8(target, addition, maximum) {
18253
+ const bytes = Buffer.byteLength(addition, "utf8");
18254
+ if (target.bytes + bytes > maximum) return false;
18255
+ target.text += addition;
18256
+ target.bytes += bytes;
18257
+ return true;
18258
+ }
18259
+ function renderDevLeadBoardSummary(board) {
18260
+ if (board === void 0 || board.projects.length === 0) return "";
18261
+ const counts = { active: 0, blocked: 0, paused: 0, done: 0 };
18262
+ for (const project of board.projects) counts[project.status] += 1;
18263
+ const lines = [
18264
+ `DevLead board r${board.revision} ${board.updatedAt}; projects ${board.projects.length}: active ${counts.active}, blocked ${counts.blocked}, paused ${counts.paused}, done ${counts.done}`
18265
+ ];
18266
+ for (const project of board.projects) {
18267
+ const focus = Array.from(singleLine(project.focus)).slice(0, 120).join("");
18268
+ lines.push(
18269
+ `- ${singleLine(project.id)}/${singleLine(project.workspace.title)} [${project.status}/${project.priority}]${focus.length === 0 ? "" : ` focus: ${focus}`}${project.blockers.length === 0 ? "" : ` !blockers:${project.blockers.length}`}`
18270
+ );
18271
+ }
18272
+ const output = { text: "", bytes: 0 };
18273
+ for (let index = 0; index < lines.length; index += 1) {
18274
+ const line = lines[index] ?? "";
18275
+ if (!appendUtf8(output, `${index === 0 ? "" : "\n"}${line}`, DEVLEAD_BOARD_SUMMARY_MAX_BYTES)) {
18276
+ appendUtf8(output, "\n\u2026", DEVLEAD_BOARD_SUMMARY_MAX_BYTES);
18277
+ break;
18278
+ }
18279
+ }
18280
+ return output.text;
18281
+ }
18282
+ var DevLeadBoardStore = class {
18283
+ /**
18284
+ * @param boardPath - absolute deployment-configured path; blank/undefined disables the board.
18285
+ * @param logger - Host logger for best-effort watcher failures.
18286
+ * @param now - injectable clock used by tests.
18287
+ */
18288
+ constructor(boardPath, logger2 = { warn: () => void 0 }, now = Date.now) {
18289
+ this.logger = logger2;
18290
+ this.now = now;
18291
+ const trimmed = boardPath?.trim() ?? "";
18292
+ if (trimmed.length > 0 && !isAbsolute2(trimmed)) {
18293
+ throw new DevLeadBoardError("boardPath must be an absolute path", "BOARD_INVALID", [
18294
+ { pointer: "/boardPath", message: "boardPath must be an absolute path" }
18295
+ ]);
18296
+ }
18297
+ this.filePath = trimmed.length === 0 ? void 0 : trimmed;
18298
+ }
18299
+ logger;
18300
+ now;
18301
+ filePath;
18302
+ cache;
18303
+ fingerprint;
18304
+ lastError;
18305
+ dirty = true;
18306
+ loading;
18307
+ writeTail = Promise.resolve();
18308
+ watcher;
18309
+ closed = false;
18310
+ /** Absolute configured file path, or undefined when disabled. */
18311
+ get path() {
18312
+ return this.filePath;
18313
+ }
18314
+ /** Whether board reads/writes are configured. */
18315
+ get enabled() {
18316
+ return this.filePath !== void 0;
18317
+ }
18318
+ /**
18319
+ * Prepare the watchable parent, then load without rejecting for a malformed
18320
+ * file.
18321
+ *
18322
+ * The service only calls this for an explicit deployment override or for a
18323
+ * derived path whose workspace root already exists as a directory; a missing
18324
+ * workspace root disables the board instead of being recreated here.
18325
+ */
18326
+ async start() {
18327
+ if (this.filePath === void 0) return;
18328
+ try {
18329
+ await mkdir(dirname(this.filePath), { recursive: true, mode: 448 });
18330
+ } catch (error51) {
18331
+ if (isDevLeadBoardError(error51)) throw error51;
18332
+ if (isWriteIoError(error51)) throw writeIoError(this.filePath, error51);
18333
+ throw error51;
18334
+ }
18335
+ await this.refresh(true);
18336
+ this.startWatcher();
18337
+ }
18338
+ /** Stop watching and settle already-queued work. */
18339
+ async close() {
18340
+ this.closed = true;
18341
+ this.watcher?.close();
18342
+ this.watcher = void 0;
18343
+ await this.loading;
18344
+ await this.writeTail;
18345
+ }
18346
+ requirePath() {
18347
+ if (this.filePath === void 0) {
18348
+ throw new DevLeadBoardError("DevLead board is disabled; configure devlead boardPath", "BOARD_DISABLED");
18349
+ }
18350
+ return this.filePath;
18351
+ }
18352
+ startWatcher() {
18353
+ const filePath = this.filePath;
18354
+ if (filePath === void 0 || this.watcher !== void 0 || this.closed) return;
18355
+ try {
18356
+ this.watcher = watch(dirname(filePath), { persistent: false }, (_event, filename) => {
18357
+ if (filename !== null && filename.toString() !== basename(filePath)) return;
18358
+ this.dirty = true;
18359
+ void this.refresh();
18360
+ });
18361
+ this.watcher.on("error", (error51) => {
18362
+ this.logger.warn(`devlead: board watcher failed for ${filePath}: ${errorMessage2(error51)}`);
18363
+ this.watcher?.close();
18364
+ this.watcher = void 0;
18365
+ });
18366
+ } catch (error51) {
18367
+ if (error51.code !== "ENOENT") {
18368
+ this.logger.warn(`devlead: could not watch board ${filePath}: ${errorMessage2(error51)}`);
18369
+ }
18370
+ }
18371
+ }
18372
+ async refresh(force = false) {
18373
+ if (this.filePath === void 0) return;
18374
+ if (this.dirty) force = true;
18375
+ for (; ; ) {
18376
+ const pending = this.loading;
18377
+ if (pending !== void 0) {
18378
+ await pending;
18379
+ if (!force) return;
18380
+ continue;
18381
+ }
18382
+ const operation = this.load(force);
18383
+ this.loading = operation;
18384
+ try {
18385
+ await operation;
18386
+ return;
18387
+ } finally {
18388
+ if (this.loading === operation) this.loading = void 0;
18389
+ }
18390
+ }
18391
+ }
18392
+ async load(force) {
18393
+ const filePath = this.requirePath();
18394
+ this.dirty = false;
18395
+ try {
18396
+ for (let attempt = 0; attempt < DEVLEAD_BOARD_READ_ATTEMPTS; attempt += 1) {
18397
+ const before = await stat2(filePath);
18398
+ if (!force && this.cache !== void 0 && this.lastError === void 0 && sameFingerprint(this.fingerprint, before)) {
18399
+ this.startWatcher();
18400
+ return;
18401
+ }
18402
+ if (before.size > DEVLEAD_BOARD_MAX_BYTES) {
18403
+ this.lastError = new DevLeadBoardError(
18404
+ `board file exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes`,
18405
+ "BOARD_LIMIT_EXCEEDED",
18406
+ [{ pointer: "", message: `file size ${before.size} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18407
+ );
18408
+ return;
18409
+ }
18410
+ const content = await readFile(filePath, "utf8");
18411
+ const after = await stat2(filePath);
18412
+ if (!sameFingerprint(before, after) || Buffer.byteLength(content, "utf8") !== after.size) continue;
18413
+ let value;
18414
+ try {
18415
+ value = JSON.parse(content);
18416
+ } catch (error51) {
18417
+ this.lastError = new DevLeadBoardError(
18418
+ `board file is not valid JSON: ${errorMessage2(error51)}`,
18419
+ "BOARD_INVALID",
18420
+ [{ pointer: "", message: errorMessage2(error51) }]
18421
+ );
18422
+ return;
18423
+ }
18424
+ let board;
18425
+ try {
18426
+ board = parseBoard(value);
18427
+ } catch (error51) {
18428
+ this.lastError = error51 instanceof DevLeadBoardError ? error51 : new DevLeadBoardError(errorMessage2(error51), "BOARD_INVALID");
18429
+ return;
18430
+ }
18431
+ this.cache = board;
18432
+ this.fingerprint = { mtimeMs: after.mtimeMs, size: after.size, ino: after.ino };
18433
+ this.lastError = void 0;
18434
+ this.startWatcher();
18435
+ return;
18436
+ }
18437
+ this.lastError = new DevLeadBoardError(
18438
+ `board file changed repeatedly while reading ${filePath}; retry`,
18439
+ "BOARD_IO_ERROR"
18440
+ );
18441
+ } catch (error51) {
18442
+ if (error51.code === "ENOENT") {
18443
+ this.cache = void 0;
18444
+ this.fingerprint = void 0;
18445
+ this.lastError = new DevLeadBoardError(`board file does not exist: ${filePath}`, "BOARD_NOT_FOUND");
18446
+ return;
18447
+ }
18448
+ if (error51 instanceof DevLeadBoardError) {
18449
+ this.lastError = error51;
18450
+ return;
18451
+ }
18452
+ this.lastError = new DevLeadBoardError(
18453
+ `could not read board ${filePath}: ${errorMessage2(error51)}`,
18454
+ "BOARD_IO_ERROR"
18455
+ );
18456
+ }
18457
+ }
18458
+ async current() {
18459
+ this.requirePath();
18460
+ await this.refresh();
18461
+ if (this.lastError !== void 0) throw this.lastError;
18462
+ if (this.cache === void 0) {
18463
+ throw new DevLeadBoardError("board has no valid snapshot", "BOARD_NOT_FOUND");
18464
+ }
18465
+ return this.cache;
18466
+ }
18467
+ /** Read a detached, optionally filtered board projection. */
18468
+ async read(filter = {}) {
18469
+ const board = await this.current();
18470
+ const includeTasks = filter.includeTasks ?? filter.project !== void 0;
18471
+ if (filter.limit !== void 0 && (!Number.isSafeInteger(filter.limit) || filter.limit < 1)) {
18472
+ throw new DevLeadBoardError("limit must be a positive safe integer", "BOARD_INVALID", [
18473
+ { pointer: "/limit", message: "limit must be a positive safe integer" }
18474
+ ]);
18475
+ }
18476
+ let projects;
18477
+ let truncated = false;
18478
+ if (filter.project !== void 0) {
18479
+ projects = [resolveProject(board, filter.project)];
18480
+ } else {
18481
+ const limit = Math.min(filter.limit ?? DEVLEAD_BOARD_MAX_PROJECTS, DEVLEAD_BOARD_MAX_PROJECTS);
18482
+ projects = board.projects.slice(0, limit);
18483
+ truncated = board.projects.length > projects.length;
18484
+ }
18485
+ return boundReadResult({
18486
+ revision: board.revision,
18487
+ updatedAt: board.updatedAt,
18488
+ projects: projects.map((project) => {
18489
+ if (includeTasks && project.tasks.length > DEVLEAD_BOARD_READ_MAX_TASKS) truncated = true;
18490
+ return projectView(project, includeTasks);
18491
+ }),
18492
+ ...truncated ? { truncated: true } : {}
18493
+ });
18494
+ }
18495
+ /**
18496
+ * Apply one project mutation. Host calls share one promise chain; every call
18497
+ * then performs its own locked disk read-modify-write cycle.
18498
+ */
18499
+ async update(patch, expectedRevision, signal) {
18500
+ this.requirePath();
18501
+ if (expectedRevision !== void 0 && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
18502
+ throw new DevLeadBoardError("expectedRevision must be a non-negative safe integer", "BOARD_INVALID", [
18503
+ { pointer: "/expectedRevision", message: "expectedRevision must be a non-negative safe integer" }
18504
+ ]);
18505
+ }
18506
+ signal?.throwIfAborted();
18507
+ const operation = this.writeTail.then(() => this.updateLocked(patch, expectedRevision, signal));
18508
+ this.writeTail = operation.catch(() => void 0);
18509
+ return operation;
18510
+ }
18511
+ async updateLocked(input, expectedRevision, signal) {
18512
+ const filePath = this.requirePath();
18513
+ try {
18514
+ const patch = validateUpdateInput(input);
18515
+ try {
18516
+ await stat2(dirname(filePath));
18517
+ } catch (error51) {
18518
+ if (errorCode(error51) !== "ENOENT") throw error51;
18519
+ validateMissingFileUpdate(patch, expectedRevision);
18520
+ }
18521
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
18522
+ this.startWatcher();
18523
+ return await withFileLock(filePath, async () => {
18524
+ signal?.throwIfAborted();
18525
+ await this.refresh(true);
18526
+ if (this.lastError !== void 0 && this.lastError.code !== "BOARD_NOT_FOUND") throw this.lastError;
18527
+ const timestamp = new Date(this.now()).toISOString();
18528
+ const current = this.cache ?? emptyBoard(patch.updatedBy, timestamp);
18529
+ if (expectedRevision !== void 0 && current.revision !== expectedRevision) {
18530
+ throw new DevLeadBoardError(
18531
+ `board revision conflict: expected r${expectedRevision}, current r${current.revision}`,
18532
+ "BOARD_REVISION_CONFLICT",
18533
+ [{ pointer: "/revision", message: `expected ${expectedRevision}, current ${current.revision}` }]
18534
+ );
18535
+ }
18536
+ const next = structuredClone(current);
18537
+ const changed = applyProjectPatch(next, patch, timestamp);
18538
+ const project = resolveProject(next, patch.project);
18539
+ if (changed.length === 0) {
18540
+ return {
18541
+ revision: current.revision,
18542
+ updatedAt: current.updatedAt,
18543
+ project: projectView(project, false),
18544
+ changed
18545
+ };
18546
+ }
18547
+ next.revision = current.revision + 1;
18548
+ next.updatedAt = timestamp;
18549
+ next.updatedBy = structuredClone(patch.updatedBy);
18550
+ const validated = parseBoard(next);
18551
+ const content = `${JSON.stringify(validated, null, 2)}
18552
+ `;
18553
+ const bytes = Buffer.byteLength(content, "utf8");
18554
+ if (bytes > DEVLEAD_BOARD_MAX_BYTES) {
18555
+ throw new DevLeadBoardError(
18556
+ `board update would exceed ${DEVLEAD_BOARD_MAX_BYTES} bytes (${bytes})`,
18557
+ "BOARD_LIMIT_EXCEEDED",
18558
+ [{ pointer: "", message: `serialized size ${bytes} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18559
+ );
18560
+ }
18561
+ await writeFileAtomic(filePath, content, { mode: 384, dirMode: 448 });
18562
+ const written = await stat2(filePath);
18563
+ this.cache = validated;
18564
+ this.lastError = void 0;
18565
+ this.dirty = false;
18566
+ this.fingerprint = { mtimeMs: written.mtimeMs, size: written.size, ino: written.ino };
18567
+ this.startWatcher();
18568
+ return {
18569
+ revision: validated.revision,
18570
+ updatedAt: validated.updatedAt,
18571
+ project: projectView(resolveProject(validated, project.id), false),
18572
+ changed
18573
+ };
18574
+ }, signal === void 0 ? {} : { signal });
18575
+ } catch (error51) {
18576
+ if (isDevLeadBoardError(error51)) throw error51;
18577
+ if (isWriteIoError(error51)) throw writeIoError(filePath, error51);
18578
+ throw error51;
18579
+ }
18580
+ }
18581
+ /** Synchronous cache-only text for `systemPrompt.context()`. */
18582
+ summary() {
18583
+ if (this.filePath === void 0) return "";
18584
+ return renderDevLeadBoardSummary(this.cache);
18585
+ }
18586
+ };
18587
+ function applyProjectPatch(board, patch, timestamp) {
18588
+ const changed = [];
18589
+ let project;
18590
+ try {
18591
+ project = resolveProject(board, patch.project);
18592
+ } catch (error51) {
18593
+ if (!(error51 instanceof DevLeadBoardError) || error51.code !== "BOARD_PROJECT_NOT_FOUND" || patch.create !== true) throw error51;
18594
+ const workspacePatch = patch.set?.workspace;
18595
+ const workspacePath = workspacePatch?.path;
18596
+ if (workspacePath === void 0 || workspacePath.trim().length === 0) {
18597
+ throw new DevLeadBoardError("creating a project requires set.workspace.path", "BOARD_INVALID", [
18598
+ { pointer: "/set/workspace/path", message: "required when create is true" }
18599
+ ]);
18600
+ }
18601
+ const id = patch.project.trim();
18602
+ project = {
18603
+ id,
18604
+ workspace: {
18605
+ path: workspacePath,
18606
+ title: workspacePatch?.title ?? (basename(workspacePath) || id)
18607
+ },
18608
+ status: "active",
18609
+ priority: "medium",
18610
+ goal: "",
18611
+ focus: "",
18612
+ next: "",
18613
+ blockers: [],
18614
+ tasks: [],
18615
+ updatedAt: timestamp
18616
+ };
18617
+ board.projects.push(project);
18618
+ changed.push("project.create");
18619
+ }
18620
+ let projectChanged = changed.length > 0;
18621
+ const set2 = patch.set;
18622
+ if (set2 !== void 0) {
18623
+ for (const field of ["status", "priority", "goal", "focus", "next"]) {
18624
+ const value = set2[field];
18625
+ if (value !== void 0 && project[field] !== value) {
18626
+ Object.assign(project, { [field]: value });
18627
+ changed.push(`set.${field}`);
18628
+ projectChanged = true;
18629
+ }
18630
+ }
18631
+ if (set2.workspace !== void 0) {
18632
+ for (const field of ["path", "title"]) {
18633
+ const value = set2.workspace[field];
18634
+ if (value !== void 0 && project.workspace[field] !== value) {
18635
+ project.workspace[field] = value;
18636
+ changed.push(`set.workspace.${field}`);
18637
+ projectChanged = true;
18638
+ }
18639
+ }
18640
+ }
18641
+ }
18642
+ const blockers = patch.blockers;
18643
+ if (blockers?.clear === true && project.blockers.length > 0) {
18644
+ project.blockers = [];
18645
+ changed.push("blockers.clear");
18646
+ projectChanged = true;
18647
+ }
18648
+ if (blockers?.remove !== void 0) {
18649
+ const remove = new Set(blockers.remove);
18650
+ const retained = project.blockers.filter((blocker) => !remove.has(blocker.id));
18651
+ if (retained.length !== project.blockers.length) {
18652
+ project.blockers = retained;
18653
+ changed.push("blockers.remove");
18654
+ projectChanged = true;
18655
+ }
18656
+ }
18657
+ for (const addition of blockers?.add ?? []) {
18658
+ const existing = project.blockers.find((blocker2) => blocker2.id === addition.id);
18659
+ const sessionId = addition.sessionId ?? existing?.sessionId;
18660
+ const blocker = {
18661
+ id: addition.id,
18662
+ text: addition.text,
18663
+ since: existing?.since ?? timestamp,
18664
+ ...sessionId === void 0 ? {} : { sessionId }
18665
+ };
18666
+ if (existing === void 0) {
18667
+ project.blockers.push(blocker);
18668
+ changed.push(`blockers.add:${addition.id}`);
18669
+ projectChanged = true;
18670
+ } else if (existing.text !== blocker.text || existing.sessionId !== blocker.sessionId) {
18671
+ Object.assign(existing, blocker);
18672
+ changed.push(`blockers.add:${addition.id}`);
18673
+ projectChanged = true;
18674
+ }
18675
+ }
18676
+ if (patch.tasks?.remove !== void 0) {
18677
+ const remove = new Set(patch.tasks.remove);
18678
+ const retained = project.tasks.filter((task) => !remove.has(task.id));
18679
+ if (retained.length !== project.tasks.length) {
18680
+ project.tasks = retained;
18681
+ changed.push("tasks.remove");
18682
+ projectChanged = true;
18683
+ }
18684
+ }
18685
+ for (const upsert2 of patch.tasks?.upsert ?? []) {
18686
+ const existing = project.tasks.find((task) => task.id === upsert2.id);
18687
+ if (existing === void 0) {
18688
+ if (upsert2.title === void 0 || upsert2.title.trim().length === 0) {
18689
+ throw new DevLeadBoardError(`new task "${upsert2.id}" requires a non-empty title`, "BOARD_INVALID", [
18690
+ { pointer: "/tasks/upsert", message: `new task "${upsert2.id}" requires title` }
18691
+ ]);
18692
+ }
18693
+ project.tasks.push({
18694
+ id: upsert2.id,
18695
+ title: upsert2.title,
18696
+ status: upsert2.status ?? "todo",
18697
+ ...upsert2.ownerSessionId === void 0 ? {} : { ownerSessionId: upsert2.ownerSessionId },
18698
+ updatedAt: timestamp
18699
+ });
18700
+ changed.push(`tasks.upsert:${upsert2.id}`);
18701
+ projectChanged = true;
18702
+ continue;
18703
+ }
18704
+ let taskChanged = false;
18705
+ if (upsert2.title !== void 0 && existing.title !== upsert2.title) {
18706
+ existing.title = upsert2.title;
18707
+ taskChanged = true;
18708
+ }
18709
+ if (upsert2.status !== void 0 && existing.status !== upsert2.status) {
18710
+ existing.status = upsert2.status;
18711
+ taskChanged = true;
18712
+ }
18713
+ if (upsert2.ownerSessionId !== void 0 && existing.ownerSessionId !== upsert2.ownerSessionId) {
18714
+ existing.ownerSessionId = upsert2.ownerSessionId;
18715
+ taskChanged = true;
18716
+ }
18717
+ if (taskChanged) {
18718
+ existing.updatedAt = timestamp;
18719
+ changed.push(`tasks.upsert:${upsert2.id}`);
18720
+ projectChanged = true;
18721
+ }
18722
+ }
18723
+ if (projectChanged) project.updatedAt = timestamp;
18724
+ return changed;
18725
+ }
18726
+
17687
18727
  // packages/devlead/src/notification.ts
17688
18728
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
17689
18729
  import {
@@ -19870,9 +20910,9 @@ var REHYDRATION_FINALIZE_TIMEOUT_MS = 5e3;
19870
20910
  var MAX_FINALIZE_LISTING_REFRESHES = 2;
19871
20911
  var DEFAULT_SUPERVISION_DEGRADED_REASON = "the cold-lead supervisor index is incomplete";
19872
20912
  var REHYDRATION_PROBE_MESSAGES = {
19873
- "corrupt-terminal": "devlead: cold lead rehydration is degraded by a corrupt persisted DevLead replay; ordinary retries are paused and a slow 30s recovery probe retries every 30s. Open (resume) the affected DevLead Session and run /devlead reset there, or repair/delete the corrupt Session log; the probe recovers once the cause is removed (a Host restart also rebuilds the index)",
19874
- "live-failure": "devlead: a live attached DevLead projection is corrupt, so the supervisor set cannot be proven; prompting stays disabled until it is repaired. Open the affected Session, run /devlead reset there, or repair/delete the corrupt Session log; the slow 30s recovery probe retries every 30s and recovers once the cause is removed",
19875
- "retry-cap": `devlead: cold lead rehydration failed ${String(MAX_REHYDRATION_RETRY_ATTEMPTS)} bounded retry attempts; prompting stays disabled until a complete scan succeeds. Open (resume) the affected DevLead Session and run /devlead reset there, repair or delete the unreadable/corrupt Session storage, or restart the Host; the slow 30s recovery probe retries every 30s and recovers once the cause is removed`
20913
+ "corrupt-terminal": "devlead: cold lead rehydration is degraded by a corrupt persisted DevLead replay; ordinary retries are paused and a slow 30s recovery probe retries every 30s. Resolve any raw format/read blocker in the detailed error, then open (resume) the affected DevLead Session and run /devlead reset there; the probe recovers once the cause is removed (a Host restart also rebuilds the index)",
20914
+ "live-failure": "devlead: a live attached DevLead projection is corrupt, so the supervisor set cannot be proven; prompting stays disabled until it is repaired. Open the affected Session and run /devlead reset there; the slow 30s recovery probe retries every 30s and recovers once the cause is removed",
20915
+ "retry-cap": `devlead: cold lead rehydration failed ${String(MAX_REHYDRATION_RETRY_ATTEMPTS)} bounded retry attempts; prompting stays disabled until a complete scan succeeds. Follow the detailed Session/path/cause error: transient causes need no log edits. Open (resume) the named DevLead Session for corrupt DevLead records and run /devlead reset there; raw storage failures require storage/plugin repair or a readable backup; the slow 30s recovery probe retries every 30s and a Host restart also rebuilds the index`
19876
20916
  };
19877
20917
  var REHYDRATION_DEGRADED_CAUSES = {
19878
20918
  list: "the persisted Session corpus could not be listed",
@@ -19905,7 +20945,8 @@ var Config = z2.object({
19905
20945
  maxListedSessions: z2.number().step(1).min(1).default(200),
19906
20946
  wakeColdSession: z2.boolean().default(true),
19907
20947
  defaultAgentPreset: z2.string().default(""),
19908
- questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS)
20948
+ questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS),
20949
+ boardPath: z2.string().default("")
19909
20950
  });
19910
20951
  function resolveConfig(config2) {
19911
20952
  const notificationBatchMs = config2.notificationBatchMs ?? 400;
@@ -19932,6 +20973,12 @@ function resolveConfig(config2) {
19932
20973
  if (!Number.isSafeInteger(questionTtlMs) || questionTtlMs < 0) {
19933
20974
  throw new TypeError("questionTtlMs must be a non-negative safe integer");
19934
20975
  }
20976
+ const boardPath = config2.boardPath ?? "";
20977
+ if (typeof boardPath !== "string") throw new TypeError("boardPath must be a string");
20978
+ const trimmedBoardPath = boardPath.trim();
20979
+ if (trimmedBoardPath.length > 0 && !isAbsolute3(trimmedBoardPath)) {
20980
+ throw new TypeError("boardPath must be an absolute path");
20981
+ }
19935
20982
  return {
19936
20983
  notificationBatchMs,
19937
20984
  actionRequiredBatchMs,
@@ -19939,7 +20986,8 @@ function resolveConfig(config2) {
19939
20986
  maxListedSessions,
19940
20987
  wakeColdSession,
19941
20988
  defaultAgentPreset: defaultAgentPreset.trim().length === 0 ? void 0 : defaultAgentPreset.trim(),
19942
- questionTtlMs
20989
+ questionTtlMs,
20990
+ ...trimmedBoardPath.length === 0 ? {} : { boardPath: trimmedBoardPath }
19943
20991
  };
19944
20992
  }
19945
20993
  function remoteCodeOf(error51) {
@@ -20070,12 +21118,38 @@ function validatedQuestions(value, kind) {
20070
21118
  };
20071
21119
  });
20072
21120
  }
21121
+ function devLeadBoardStartErrorOf(error51) {
21122
+ if (isDevLeadBoardError(error51)) return { code: error51.code, message: error51.message };
21123
+ return { code: "BOARD_IO_ERROR", message: thrownMessage(error51) };
21124
+ }
20073
21125
  var DevLeadService = class extends Service {
20074
21126
  static inject = ["agents", "sessions", "sessionProjections"];
20075
21127
  /** Loader schema, applied by the Loader before construction. */
20076
21128
  static Config = Config;
20077
21129
  /** Validated deployment configuration. */
20078
21130
  resolved;
21131
+ /**
21132
+ * Current project board store. It belongs to the one active lead Session (or
21133
+ * its configured override); with no active lead this is a disabled store
21134
+ * whose reads/writes report BOARD_DISABLED and whose summary is empty.
21135
+ */
21136
+ boardStore;
21137
+ /** Active lead Session whose workspace owns {@link boardStore}, when enabled. */
21138
+ boardLeadSessionIdValue;
21139
+ /** Whether the current board path comes from the deployment Config override. */
21140
+ boardPathOverrideValue = false;
21141
+ /** Latest board start failure; the rest of the service keeps serving without a board. */
21142
+ boardStartErrorValue;
21143
+ /** Why the board is disabled right now, or undefined while a store is active. */
21144
+ boardDisabledReasonValue;
21145
+ /** Serializes store swaps so two lead changes can never interleave one store. */
21146
+ boardSyncTail = Promise.resolve();
21147
+ /**
21148
+ * Original workspace root of each known lead Session, including cold ones
21149
+ * recovered from the persisted corpus (their header is not live in the
21150
+ * Session store, so the board path needs this cache).
21151
+ */
21152
+ leadWorkspaceRoots = /* @__PURE__ */ new Map();
20079
21153
  /** Awaited registration of the `devLead` projection unit. */
20080
21154
  projectionHandle;
20081
21155
  /** Host-driven projections replacing deprecated synchronous event readers. */
@@ -20107,6 +21181,8 @@ var DevLeadService = class extends Service {
20107
21181
  liveAttachFailure = false;
20108
21182
  /** Human-readable cause of the current degraded supervision state. */
20109
21183
  supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
21184
+ /** Latest concrete Session/path/cause; retained when a later retry-cap warning is emitted. */
21185
+ supervisionDegradedDetail;
20110
21186
  /** Invalidates every in-flight scan application; bumped by reset and service recomposition. */
20111
21187
  rehydrationEpoch = 0;
20112
21188
  /** Whether the current attempt reached the corpus scan (early live-only returns do not). */
@@ -20379,6 +21455,7 @@ var DevLeadService = class extends Service {
20379
21455
  constructor(ctx, config2 = {}) {
20380
21456
  super(ctx, "devLead");
20381
21457
  this.resolved = resolveConfig(config2);
21458
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
20382
21459
  }
20383
21460
  async [Service.init]() {
20384
21461
  initializeRecordApi(this.ctx.logger);
@@ -20427,7 +21504,12 @@ var DevLeadService = class extends Service {
20427
21504
  opening?.catch(() => void 0),
20428
21505
  idempotencyOpening?.catch(() => void 0)
20429
21506
  ]);
20430
- await Promise.all([this.outbox?.close(), this.idempotencyStore?.close()]);
21507
+ await this.boardSyncTail.catch(() => void 0);
21508
+ await Promise.all([
21509
+ this.boardStore.close(),
21510
+ this.outbox?.close(),
21511
+ this.idempotencyStore?.close()
21512
+ ]);
20431
21513
  })();
20432
21514
  };
20433
21515
  }.bind(this), "devlead: cold rehydration");
@@ -20511,6 +21593,7 @@ var DevLeadService = class extends Service {
20511
21593
  knownActive: this.recoveredActive
20512
21594
  });
20513
21595
  this.recoveredActive = [];
21596
+ await this.syncBoardToActiveLead();
20514
21597
  await this.replayOutbox();
20515
21598
  this.initialized = true;
20516
21599
  }
@@ -21111,6 +22194,7 @@ var DevLeadService = class extends Service {
21111
22194
  this.rehydrated = true;
21112
22195
  this.corpusWasProven = true;
21113
22196
  this.supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
22197
+ this.supervisionDegradedDetail = void 0;
21114
22198
  this.trustedBindings = this.currentCorpusBindings();
21115
22199
  this.observedBindings = this.trustedBindings;
21116
22200
  this.coldScan = void 0;
@@ -21326,6 +22410,7 @@ var DevLeadService = class extends Service {
21326
22410
  if (this.disposed) return;
21327
22411
  this.invalidateCorpusProof();
21328
22412
  this.supervisionDegradedReason = reason;
22413
+ this.supervisionDegradedDetail = void 0;
21329
22414
  this.requestFreshRehydration();
21330
22415
  this.armRehydrationRetry(this.ctx.get("sessionQuery") !== void 0);
21331
22416
  void this.rehydrateFromPersistence();
@@ -21406,8 +22491,8 @@ var DevLeadService = class extends Service {
21406
22491
  * states and exhausted retry budgets are recoverable without a Host restart:
21407
22492
  * the probe re-lists and rescans once every {@link DEGRADED_REHYDRATION_PROBE_MS}.
21408
22493
  * The probe itself does not repair anything: it retries every 30s and recovers
21409
- * once a human opens the affected Session and resets it, repairs/deletes the
21410
- * corrupt log, or restarts the Host. An explicit reset recovers immediately.
22494
+ * after the transient cause clears, a read-only recovery succeeds, a human
22495
+ * resets corrupt DevLead state, or the Host restarts. An explicit reset recovers immediately.
21411
22496
  * @param reason - stable warning key and degraded-state cause.
21412
22497
  */
21413
22498
  scheduleRehydrationProbe(reason) {
@@ -21470,8 +22555,10 @@ var DevLeadService = class extends Service {
21470
22555
  this.rehydrationLifecycle = { queryReady, disposers };
21471
22556
  }
21472
22557
  /** Emit each rehydration warning reason once per service epoch and track its cause. */
21473
- warnRehydration(reason, message) {
22558
+ warnRehydration(reason, message, detail) {
21474
22559
  this.supervisionDegradedReason = REHYDRATION_DEGRADED_CAUSES[reason] ?? message;
22560
+ if (detail !== void 0) this.supervisionDegradedDetail = detail;
22561
+ else if (reason !== "retry-cap" && reason !== "corrupt-terminal") this.supervisionDegradedDetail = void 0;
21475
22562
  if (this.rehydrationWarnings.has(reason)) return;
21476
22563
  this.rehydrationWarnings.add(reason);
21477
22564
  this.ctx.logger.warn(message);
@@ -21507,6 +22594,251 @@ var DevLeadService = class extends Service {
21507
22594
  return recordApiStatus();
21508
22595
  }
21509
22596
  // ---------------------------------------------------------------------------
22597
+ // Project board
22598
+ // ---------------------------------------------------------------------------
22599
+ /** Current project board store; disabled when no lead/workspace owns one. */
22600
+ get board() {
22601
+ return this.boardStore;
22602
+ }
22603
+ /** Active lead Session id whose workspace owns the current board, when enabled. */
22604
+ get boardLeadSessionId() {
22605
+ return this.boardLeadSessionIdValue;
22606
+ }
22607
+ /** Whether the current board path comes from the deployment Config override. */
22608
+ get boardPathOverride() {
22609
+ return this.boardPathOverrideValue;
22610
+ }
22611
+ /**
22612
+ * Latest project-board start failure, if any.
22613
+ *
22614
+ * A degraded board keeps DevLead itself loaded: tools then report the real
22615
+ * filesystem failure as a structured board error instead of the plugin
22616
+ * refusing to activate.
22617
+ */
22618
+ get boardStartError() {
22619
+ return this.boardStartErrorValue;
22620
+ }
22621
+ /**
22622
+ * Why the project board is currently disabled, when it is.
22623
+ *
22624
+ * `missing-workspace` reports a lead whose recorded original workspace root is
22625
+ * gone (or is no longer a directory): the board stays disabled with one
22626
+ * warning and the Host never recreates the workspace. An explicit deployment
22627
+ * `boardPath` override bypasses this check and keeps the existing pre-create
22628
+ * semantics. Undefined while a board store is active.
22629
+ */
22630
+ get boardDisabledReason() {
22631
+ return this.boardDisabledReasonValue;
22632
+ }
22633
+ /**
22634
+ * Resolve the calling lead's board file and hand it a tool read. Only the
22635
+ * unique active lead may reach the store; with no active lead/workspace the
22636
+ * call reports BOARD_DISABLED.
22637
+ * @param agent - calling live Agent.
22638
+ * @param filter - bounded project/task filtering.
22639
+ * @returns the bounded read result.
22640
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_ENABLED` for a non-mode Agent.
22641
+ * @throws {@link DevLeadBoardError} `BOARD_DISABLED` when the caller is not
22642
+ * the active lead or its workspace records no board location.
22643
+ */
22644
+ async readBoard(agent, filter = {}) {
22645
+ if (!this.isEnabled(agent)) {
22646
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
22647
+ }
22648
+ this.requireActiveBoardLead(agent);
22649
+ return this.boardStore.read(filter);
22650
+ }
22651
+ /**
22652
+ * Dynamic board summary for one prompt-assembly Agent.
22653
+ *
22654
+ * Returns the cache-only text only when the caller is both an enabled lead
22655
+ * and the owner of the current store; a duplicate or non-owner enabled Agent
22656
+ * gets an empty summary instead of another workspace's board.
22657
+ * @param agent - Agent whose turn is being assembled.
22658
+ * @returns the bounded board summary, or an empty string.
22659
+ */
22660
+ boardSummaryFor(agent) {
22661
+ if (!this.isEnabled(agent)) return "";
22662
+ if (this.boardLeadSessionIdValue !== String(agent.id)) return "";
22663
+ return this.boardStore.summary();
22664
+ }
22665
+ /** Reject a board operation whose caller does not own the current store. */
22666
+ requireActiveBoardLead(agent) {
22667
+ if (this.boardLeadSessionIdValue === String(agent.id) && this.boardStore.path !== void 0) return;
22668
+ throw new DevLeadBoardError(
22669
+ "the DevLead project board is not active for the calling lead: no active lead workspace currently owns a board file",
22670
+ "BOARD_DISABLED"
22671
+ );
22672
+ }
22673
+ /** Serialize one active-lead → board synchronization. */
22674
+ syncBoardToActiveLead() {
22675
+ const run = this.boardSyncTail.then(() => this.applyActiveLeadBoard());
22676
+ this.boardSyncTail = run.catch(() => void 0);
22677
+ return run;
22678
+ }
22679
+ /** Apply the current lead identity to the board store (serialized). */
22680
+ async applyActiveLeadBoard() {
22681
+ if (this.disposed) return;
22682
+ const sessionId = this.activeSessionId;
22683
+ if (sessionId === void 0) {
22684
+ await this.swapBoardStore(void 0, void 0);
22685
+ return;
22686
+ }
22687
+ await this.swapBoardStore(sessionId, this.leadWorkspaceRootOf(sessionId));
22688
+ }
22689
+ /** Original workspace root for one lead: live header first, cached cold header second. */
22690
+ leadWorkspaceRootOf(sessionId) {
22691
+ const live = this.ctx.sessions.get(toSessionId3(sessionId));
22692
+ const fromLive = live?.header.cwd;
22693
+ if (fromLive !== void 0 && fromLive.trim().length > 0) {
22694
+ this.leadWorkspaceRoots.set(sessionId, fromLive);
22695
+ return fromLive;
22696
+ }
22697
+ return this.leadWorkspaceRoots.get(sessionId);
22698
+ }
22699
+ /** Cache one lead's original workspace root (cold leads are not in the live store). */
22700
+ rememberLeadWorkspaceRoot(sessionId, cwd) {
22701
+ if (cwd === void 0 || cwd.trim().length === 0) this.leadWorkspaceRoots.delete(sessionId);
22702
+ else this.leadWorkspaceRoots.set(sessionId, cwd);
22703
+ }
22704
+ /**
22705
+ * Point the service at the board file of one lead, releasing any previous
22706
+ * store/watcher.
22707
+ *
22708
+ * The path is the Config override when configured, otherwise the lead's
22709
+ * original workspace root plus `.dsh/devlead/board.json`. A derived path is
22710
+ * used only while that workspace root still exists as a directory: a cold
22711
+ * lead whose recorded root was deleted or moved must never make the Host
22712
+ * recreate the workspace (with just `.dsh/devlead`) to host the board file.
22713
+ * The same resolved file keeps its store (so a lead switch inside one
22714
+ * workspace does not churn the watcher); a changed path starts the new store
22715
+ * before the old one is closed, so an in-flight read never sees a
22716
+ * half-swapped service. A start failure is recorded and logged but never
22717
+ * rejects: the store is kept so its later operations report the real
22718
+ * filesystem failure, and the next same-path sync or path switch retries it.
22719
+ * @param sessionId - active lead identity, or undefined when disabled.
22720
+ * @param workspaceRoot - that lead's original workspace root, when known.
22721
+ */
22722
+ async swapBoardStore(sessionId, workspaceRoot) {
22723
+ const resolution = sessionId === void 0 ? { kind: "disabled", reason: "no-workspace" } : resolveDevLeadBoardPath({
22724
+ ...this.resolved.boardPath === void 0 ? {} : { override: this.resolved.boardPath },
22725
+ ...workspaceRoot === void 0 ? {} : { cwd: workspaceRoot }
22726
+ });
22727
+ if (resolution.kind === "disabled") {
22728
+ if (resolution.reason === "relative-workspace") {
22729
+ this.ctx.logger.warn(
22730
+ `devlead: Session "${sessionId ?? ""}" records a relative workspace root (${workspaceRoot ?? ""}); the project board stays disabled until it has an absolute workspace root`
22731
+ );
22732
+ }
22733
+ await this.disableBoardStore(resolution.reason);
22734
+ return;
22735
+ }
22736
+ const nextPath = resolution.path;
22737
+ const nextOverride = resolution.source === "override";
22738
+ if (resolution.source === "workspace" && !await this.workspaceRootExists(workspaceRoot)) {
22739
+ this.ctx.logger.warn(
22740
+ `devlead: Session "${sessionId ?? ""}" records a workspace root (${workspaceRoot ?? ""}) that is missing or not a directory; the project board stays disabled instead of recreating the workspace. Configure an absolute devlead boardPath if this Session should keep a project board.`
22741
+ );
22742
+ await this.disableBoardStore("missing-workspace");
22743
+ return;
22744
+ }
22745
+ const previous = this.boardStore;
22746
+ if (previous.path === nextPath) {
22747
+ this.boardLeadSessionIdValue = sessionId;
22748
+ this.boardPathOverrideValue = nextOverride;
22749
+ this.boardDisabledReasonValue = void 0;
22750
+ if (this.boardStartErrorValue !== void 0) {
22751
+ await this.retryBoardStart(previous, nextPath);
22752
+ }
22753
+ return;
22754
+ }
22755
+ const next = new DevLeadBoardStore(nextPath, this.ctx.logger);
22756
+ let startError;
22757
+ try {
22758
+ await next.start();
22759
+ } catch (error51) {
22760
+ startError = devLeadBoardStartErrorOf(error51);
22761
+ this.logBoardStartFailure(nextPath, startError);
22762
+ }
22763
+ this.boardStore = next;
22764
+ this.boardLeadSessionIdValue = sessionId;
22765
+ this.boardPathOverrideValue = nextOverride;
22766
+ this.boardDisabledReasonValue = void 0;
22767
+ this.boardStartErrorValue = startError;
22768
+ await this.closeBoardStore(previous);
22769
+ }
22770
+ /**
22771
+ * Whether one derived board's workspace root still exists as a directory.
22772
+ *
22773
+ * Any stat failure (missing, not a directory, unreadable) is treated as
22774
+ * unusable: the board is disabled instead of attempting a write under a root
22775
+ * the Host cannot verify.
22776
+ * @param workspaceRoot - the lead's recorded original workspace root.
22777
+ * @returns whether `start()` may safely prepare the board parent under it.
22778
+ */
22779
+ async workspaceRootExists(workspaceRoot) {
22780
+ if (workspaceRoot === void 0 || workspaceRoot.trim().length === 0) return false;
22781
+ try {
22782
+ return (await stat3(workspaceRoot)).isDirectory();
22783
+ } catch {
22784
+ return false;
22785
+ }
22786
+ }
22787
+ /** Retry `start()` on the current same-path store, keeping the degraded record on failure. */
22788
+ async retryBoardStart(store, path) {
22789
+ let startError;
22790
+ try {
22791
+ await store.start();
22792
+ } catch (error51) {
22793
+ startError = devLeadBoardStartErrorOf(error51);
22794
+ this.logBoardStartFailure(path, startError);
22795
+ }
22796
+ this.boardStartErrorValue = startError;
22797
+ }
22798
+ /** Log one board degradation without failing the surrounding service. */
22799
+ logBoardStartFailure(path, failure) {
22800
+ this.ctx.logger.warn(
22801
+ `devlead: project board at ${path} is degraded and DevLead stays loaded: ${failure.code}: ${failure.message}`
22802
+ );
22803
+ }
22804
+ /** Release any current board store and expose why the board is disabled. */
22805
+ async disableBoardStore(reason) {
22806
+ const previous = this.boardStore;
22807
+ this.boardLeadSessionIdValue = void 0;
22808
+ this.boardPathOverrideValue = false;
22809
+ this.boardStartErrorValue = void 0;
22810
+ this.boardDisabledReasonValue = reason;
22811
+ if (previous.path !== void 0) {
22812
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
22813
+ await this.closeBoardStore(previous);
22814
+ }
22815
+ }
22816
+ /** Close one replaced store without letting cleanup failure break the swap. */
22817
+ async closeBoardStore(store) {
22818
+ if (store.path === void 0) return;
22819
+ try {
22820
+ await store.close();
22821
+ } catch (error51) {
22822
+ this.ctx.logger.warn(`devlead: could not close the previous project board store: ${thrownMessage(error51)}`);
22823
+ }
22824
+ }
22825
+ /**
22826
+ * Stamp the calling lead's identity onto one board mutation. The board file
22827
+ * path is derived from the active lead's workspace (or the Config override);
22828
+ * model callers supply only a logical patch.
22829
+ */
22830
+ async updateBoard(agent, patch, expectedRevision, signal) {
22831
+ if (!this.isEnabled(agent)) {
22832
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
22833
+ }
22834
+ this.requireActiveBoardLead(agent);
22835
+ const title = this.ctx.get("sessionTitle")?.get(agent.session)?.title ?? "DevLead";
22836
+ return this.boardStore.update({
22837
+ ...patch,
22838
+ updatedBy: { sessionId: String(agent.id), title }
22839
+ }, expectedRevision, signal);
22840
+ }
22841
+ // ---------------------------------------------------------------------------
21510
22842
  // Mode
21511
22843
  // ---------------------------------------------------------------------------
21512
22844
  /**
@@ -21577,11 +22909,18 @@ var DevLeadService = class extends Service {
21577
22909
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21578
22910
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21579
22911
  await this.discardLeadReportState(String(agent.id));
21580
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22912
+ if (this.activeSessionId === String(agent.id)) {
22913
+ this.activeSessionId = void 0;
22914
+ await this.syncBoardToActiveLead();
22915
+ }
21581
22916
  return;
21582
22917
  }
21583
22918
  if (current.enabled === enabled) {
21584
- if (enabled) this.activeSessionId = String(agent.id);
22919
+ if (enabled) {
22920
+ this.activeSessionId = String(agent.id);
22921
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
22922
+ await this.syncBoardToActiveLead();
22923
+ }
21585
22924
  return;
21586
22925
  }
21587
22926
  if (enabled) {
@@ -21596,8 +22935,13 @@ var DevLeadService = class extends Service {
21596
22935
  appendRecordOrThrow(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
21597
22936
  await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
21598
22937
  await this.checkpointProjectionCache(agent.session, `DevLead mode for Session "${agent.id}"`);
21599
- if (enabled) this.activeSessionId = String(agent.id);
21600
- else if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22938
+ if (enabled) {
22939
+ this.activeSessionId = String(agent.id);
22940
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
22941
+ } else if (this.activeSessionId === String(agent.id)) {
22942
+ this.activeSessionId = void 0;
22943
+ }
22944
+ await this.syncBoardToActiveLead();
21601
22945
  if (enabled) void this.replayOutbox();
21602
22946
  });
21603
22947
  }
@@ -21622,7 +22966,10 @@ var DevLeadService = class extends Service {
21622
22966
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21623
22967
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21624
22968
  await this.discardLeadReportState(String(agent.id));
21625
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22969
+ if (this.activeSessionId === String(agent.id)) {
22970
+ this.activeSessionId = void 0;
22971
+ await this.syncBoardToActiveLead();
22972
+ }
21626
22973
  });
21627
22974
  }
21628
22975
  /**
@@ -21651,6 +22998,7 @@ var DevLeadService = class extends Service {
21651
22998
  this.rehydrationProgress = false;
21652
22999
  this.liveAttachFailure = false;
21653
23000
  this.supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
23001
+ this.supervisionDegradedDetail = void 0;
21654
23002
  if (this.rehydrationRetryTimer !== void 0) {
21655
23003
  clearTimeout(this.rehydrationRetryTimer);
21656
23004
  this.rehydrationRetryTimer = void 0;
@@ -21742,7 +23090,7 @@ var DevLeadService = class extends Service {
21742
23090
  }
21743
23091
  signal?.throwIfAborted();
21744
23092
  try {
21745
- await mkdir(trimmed, { recursive: true });
23093
+ await mkdir2(trimmed, { recursive: true });
21746
23094
  } catch (mkdirError) {
21747
23095
  throw workspacePathFailure(mkdirError, trimmed);
21748
23096
  }
@@ -22065,8 +23413,8 @@ var DevLeadService = class extends Service {
22065
23413
  );
22066
23414
  }
22067
23415
  if (requestedModel !== void 0) await this.assertModelSelectable(requestedModel, signal);
22068
- const watch = request.watch ?? true;
22069
- const releaseWatch = watch ? this.reserveWatchSlot(agent) : void 0;
23416
+ const watch2 = request.watch ?? true;
23417
+ const releaseWatch = watch2 ? this.reserveWatchSlot(agent) : void 0;
22070
23418
  try {
22071
23419
  const workspace = await this.createTargetWorkspace(agent, request.workspace);
22072
23420
  signal?.throwIfAborted();
@@ -22093,7 +23441,7 @@ var DevLeadService = class extends Service {
22093
23441
  if (request.title !== void 0 && request.title.trim().length > 0) {
22094
23442
  this.tryRename(created.sessionId, request.title.trim());
22095
23443
  }
22096
- if (watch) {
23444
+ if (watch2) {
22097
23445
  await this.setWatching(agent, created.sessionId, true, signal, true);
22098
23446
  releaseWatch?.();
22099
23447
  }
@@ -22328,8 +23676,8 @@ var DevLeadService = class extends Service {
22328
23676
  );
22329
23677
  }
22330
23678
  this.assertSupervisionProofHeld(proof, targetId);
22331
- const watch = options.watch ?? true;
22332
- const added = watch && !watchedNow();
23679
+ const watch2 = options.watch ?? true;
23680
+ const added = watch2 && !watchedNow();
22333
23681
  if (added) await this.setWatching(agent, resolved.sessionId, true, signal);
22334
23682
  let admission;
22335
23683
  try {
@@ -22743,7 +24091,7 @@ var DevLeadService = class extends Service {
22743
24091
  /** Fail-closed error for an unproven or no-longer-proven supervisor index. */
22744
24092
  supervisionUnavailable(targetId) {
22745
24093
  return new DevLeadError(
22746
- `cannot prove the complete DevLead supervisor set for Session "${targetId}" yet; no prompt was delivered \u2014 ${this.supervisionDegradedReason}. Recovery: open (resume) the affected DevLead Session and run /devlead reset there, or repair/delete the corrupt or unreadable Session log; the slow recovery probe retries every ${String(DEGRADED_REHYDRATION_PROBE_MS / 1e3)}s and recovers once the cause is removed, and a Host restart also rebuilds the index`,
24094
+ `cannot prove the complete DevLead supervisor set for Session "${targetId}" yet; no prompt was delivered \u2014 ${this.supervisionDegradedDetail ?? this.supervisionDegradedReason}. Recovery: transient I/O, timeout, listing, and torn-tail failures are retried automatically. For corrupt DevLead records, first resolve any raw format/read blocker in the detail (upgrade/repair the owning plugin or restore a readable backup), then open (resume) that named DevLead Session and run /devlead reset there. Do not delete logs merely to bypass this check. The slow recovery probe retries every ${String(DEGRADED_REHYDRATION_PROBE_MS / 1e3)}s, and a Host restart also rebuilds the index`,
22747
24095
  "DEVLEAD_SESSION_UNAVAILABLE"
22748
24096
  );
22749
24097
  }
@@ -23160,16 +24508,16 @@ var DevLeadService = class extends Service {
23160
24508
  * reported.
23161
24509
  *
23162
24510
  * `strict` makes the scan safe for admission: a corpus listing failure, or a
23163
- * log read failure for a row the cache positively classified as active, is a
23164
- * hard `DEVLEAD_SESSION_UNAVAILABLE` instead of a best-effort skip, because
23165
- * admitting on an unverifiable corpus could create a second active lead.
24511
+ * log read/recovery/fold failure for any candidate actually read, is a hard
24512
+ * `DEVLEAD_SESSION_UNAVAILABLE` instead of a best-effort skip, because
24513
+ * admitting on an unverifiable candidate could create a second active lead.
23166
24514
  * Reconciliation and status remain best-effort.
23167
24515
  * @param signal - caller cancellation threaded through query reads.
23168
24516
  * @param includePersisted - whether the persisted corpus is scanned.
23169
24517
  * @param strict - whether unknown occupancy is a hard error (admission only).
23170
24518
  * @returns every enabled Session, deduplicated by id.
23171
24519
  * @throws {@link DevLeadError} `DEVLEAD_SESSION_UNAVAILABLE` when `strict` is
23172
- * set and a cache-positive candidate or the corpus listing cannot be read.
24520
+ * set and a candidate read/recovery/fold or the corpus listing cannot be proven.
23173
24521
  */
23174
24522
  async scanActiveSessions(signal, includePersisted = true, strict = false) {
23175
24523
  const active = /* @__PURE__ */ new Map();
@@ -23193,6 +24541,7 @@ var DevLeadService = class extends Service {
23193
24541
  archived: archived.has(sessionId),
23194
24542
  running: agent?.status === "running",
23195
24543
  createdAt: session.header.createdAt,
24544
+ ...session.header.cwd === void 0 ? {} : { cwd: session.header.cwd },
23196
24545
  enabledAt: 0
23197
24546
  });
23198
24547
  };
@@ -23240,14 +24589,14 @@ var DevLeadService = class extends Service {
23240
24589
  let events;
23241
24590
  let inheritedEventCount = 0;
23242
24591
  try {
23243
- const snapshot = await query.readSession(record2.header.id);
24592
+ const snapshot = await this.readColdSessionForSupervision(query, record2.header, signal);
23244
24593
  events = snapshot.events;
23245
24594
  inheritedEventCount = snapshot.inheritedEventCount;
23246
24595
  } catch (error51) {
23247
24596
  if (signal?.aborted === true) throw error51;
23248
- if (strict && prefilter === "active") {
24597
+ if (strict) {
23249
24598
  throw new DevLeadError(
23250
- `could not verify global DevLead occupancy: persisted Session "${sessionId}" is cached as an active DevLead but its log could not be read: ${thrownMessage(error51)}`,
24599
+ `could not verify global DevLead occupancy: persisted Session "${sessionId}" could not be read (${prefilter} cache classification): ${thrownMessage(error51)}`,
23251
24600
  "DEVLEAD_SESSION_UNAVAILABLE"
23252
24601
  );
23253
24602
  }
@@ -23262,13 +24611,23 @@ var DevLeadService = class extends Service {
23262
24611
  state = applyDevLeadProjection(state, event);
23263
24612
  if (state.failure !== null) break;
23264
24613
  }
23265
- if (state.failure !== null || !state.enabled) continue;
24614
+ if (state.failure !== null) {
24615
+ if (strict) {
24616
+ throw new DevLeadError(
24617
+ `could not verify global DevLead occupancy: persisted Session "${sessionId}" has a corrupt DevLead replay (${prefilter} cache classification): ${state.failure}`,
24618
+ "DEVLEAD_SESSION_UNAVAILABLE"
24619
+ );
24620
+ }
24621
+ continue;
24622
+ }
24623
+ if (!state.enabled) continue;
23266
24624
  active.set(sessionId, {
23267
24625
  sessionId,
23268
24626
  live: false,
23269
24627
  archived: archived.has(sessionId),
23270
24628
  running: false,
23271
24629
  createdAt: record2.header.createdAt,
24630
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
23272
24631
  enabledAt: lastEnabledAt(events) ?? 0
23273
24632
  });
23274
24633
  }
@@ -23335,7 +24694,10 @@ var DevLeadService = class extends Service {
23335
24694
  );
23336
24695
  return false;
23337
24696
  }
23338
- if (this.activeSessionId === occupant.sessionId) this.activeSessionId = void 0;
24697
+ if (this.activeSessionId === occupant.sessionId) {
24698
+ this.activeSessionId = void 0;
24699
+ await this.syncBoardToActiveLead();
24700
+ }
23339
24701
  this.ctx.logger.warn(
23340
24702
  `devlead: disabled DevLead mode for Session "${occupant.sessionId}" (${reason}); only one Session may hold DevLead mode at a time`
23341
24703
  );
@@ -23380,6 +24742,7 @@ var DevLeadService = class extends Service {
23380
24742
  if (!scanned.some((occupant) => occupant.sessionId === sessionId)) merged.delete(sessionId);
23381
24743
  }
23382
24744
  const active = [...merged.values()];
24745
+ for (const occupant of active) this.rememberLeadWorkspaceRoot(occupant.sessionId, occupant.cwd);
23383
24746
  if (active.length === 0) {
23384
24747
  this.activeSessionId = void 0;
23385
24748
  return;
@@ -23428,6 +24791,7 @@ var DevLeadService = class extends Service {
23428
24791
  this.ctx.logger.warn(`devlead: global DevLead admission reconciliation failed: ${thrownMessage(error51)}`);
23429
24792
  }
23430
24793
  }
24794
+ await this.syncBoardToActiveLead();
23431
24795
  }
23432
24796
  /** Reject any use of a tool surface while DevLead mode is off. */
23433
24797
  assertReady(agent) {
@@ -23506,6 +24870,29 @@ var DevLeadService = class extends Service {
23506
24870
  this.replayingOpenQuestions = false;
23507
24871
  }
23508
24872
  }
24873
+ /**
24874
+ * Read one cold candidate through the Host's replay-validated query path.
24875
+ * Only a precise unknown-non-ignorable-event refusal uses the read-only
24876
+ * current-JSONL recovery: all records are still read and the caller applies
24877
+ * the same strict DevLead fold, so unrelated legacy vocabulary cannot hide a
24878
+ * foreign supervisor or excuse corrupt DevLead state.
24879
+ */
24880
+ async readColdSessionForSupervision(query, header, signal) {
24881
+ try {
24882
+ const snapshot = await query.readSession(header.id);
24883
+ signal?.throwIfAborted();
24884
+ return snapshot;
24885
+ } catch (error51) {
24886
+ signal?.throwIfAborted();
24887
+ if (!isUnknownNonIgnorableEventError(error51)) throw error51;
24888
+ const recovered = await recoverUnknownEventSessionLog(this.ctx, header, signal);
24889
+ signal?.throwIfAborted();
24890
+ this.ctx.logger.debug(
24891
+ `devlead: recovered a complete current JSONL log for DevLead-only replay after an unrelated unknown event; session=${String(header.id)} path=${recovered.path} events=${String(recovered.events.length)}`
24892
+ );
24893
+ return recovered;
24894
+ }
24895
+ }
23509
24896
  /**
23510
24897
  * Scan durable state for lead Sessions the hub must index after a restart.
23511
24898
  *
@@ -23524,9 +24911,9 @@ var DevLeadService = class extends Service {
23524
24911
  * Cheap sources first: a live Session without an Agent has its projection
23525
24912
  * folded directly (attach-only leads), then the persisted corpus is filtered
23526
24913
  * through the projection cache — a row that positively reports an enabled mode
23527
- * with a non-empty watch set is a candidate, a disabled/empty row is skipped
23528
- * without reading its log, and only unclassified rows pay for a complete
23529
- * full-log exact fold (bounded, because a Host history is unbounded).
24914
+ * with a non-empty watch set is a candidate; every other non-live, non-subagent
24915
+ * row still pays for a complete full-log exact fold (bounded, because a Host
24916
+ * history is unbounded and a stale-negative cache row is not authorization).
23530
24917
  * A corrupt replay skips that candidate with one warning; it must never stop
23531
24918
  * the scan, and it must never make the plugin fail to load.
23532
24919
  * @param listing - barrier-validated listing; re-verified when omitted.
@@ -23665,14 +25052,16 @@ var DevLeadService = class extends Service {
23665
25052
  const prefilter = cache === void 0 ? "unknown" : devLeadActivePrefilterOf(cache, record2.header);
23666
25053
  let events;
23667
25054
  let inheritedEventCount = 0;
25055
+ let sourcePath;
23668
25056
  try {
23669
- const snapshot = await this.awaitScan(query.readSession(record2.header.id), signal);
25057
+ const snapshot = await this.awaitScan(this.readColdSessionForSupervision(query, record2.header, signal), signal);
23670
25058
  if (snapshot === SCAN_ABORTED) {
23671
25059
  state.complete = false;
23672
25060
  return result([...state.leads.values()], state.active, false);
23673
25061
  }
23674
25062
  events = snapshot.events;
23675
25063
  inheritedEventCount = snapshot.inheritedEventCount;
25064
+ sourcePath = snapshot.path;
23676
25065
  } catch (error51) {
23677
25066
  if (signal?.aborted) {
23678
25067
  state.complete = false;
@@ -23684,7 +25073,8 @@ var DevLeadService = class extends Service {
23684
25073
  readFailed = true;
23685
25074
  this.warnRehydration(
23686
25075
  "read",
23687
- `devlead: a persisted Session stayed unreadable (not found) after re-listing; keeping the cursor for a bounded retry: ${thrownMessage(error51)}`
25076
+ `devlead: Session "${sessionId}" stayed unreadable (not found) after re-listing; keeping the cursor for a bounded retry: ${thrownMessage(error51)}`,
25077
+ `Session "${sessionId}" stayed unreadable (not found) after re-listing: ${thrownMessage(error51)}`
23688
25078
  );
23689
25079
  break;
23690
25080
  }
@@ -23699,7 +25089,8 @@ var DevLeadService = class extends Service {
23699
25089
  this.rehydrationValidationUnverifiable = true;
23700
25090
  this.warnRehydration(
23701
25091
  "read",
23702
- `devlead: could not re-verify the Session corpus after a not-found read; keeping the trusted cursor for a bounded retry: ${thrownMessage(error51)}`
25092
+ `devlead: could not re-verify the Session corpus after Session "${sessionId}" returned not-found; keeping the trusted cursor for a bounded retry: ${thrownMessage(error51)}`,
25093
+ `Session "${sessionId}" returned not-found and its corpus re-list failed: ${thrownMessage(error51)}`
23703
25094
  );
23704
25095
  return result([...state.leads.values()], state.active, false);
23705
25096
  }
@@ -23731,7 +25122,11 @@ var DevLeadService = class extends Service {
23731
25122
  }
23732
25123
  state.complete = false;
23733
25124
  readFailed = true;
23734
- this.warnRehydration("read", `devlead: could not read a cold lead candidate Session log: ${thrownMessage(error51)}`);
25125
+ this.warnRehydration(
25126
+ "read",
25127
+ `devlead: could not read a cold lead candidate Session log "${sessionId}": ${thrownMessage(error51)}`,
25128
+ `Session "${sessionId}" could not be read: ${thrownMessage(error51)}`
25129
+ );
23735
25130
  break;
23736
25131
  }
23737
25132
  if (prefilter !== "active") reads += 1;
@@ -23743,7 +25138,12 @@ var DevLeadService = class extends Service {
23743
25138
  if (folded.failure !== null) {
23744
25139
  state.complete = false;
23745
25140
  state.corrupt = true;
23746
- this.warnRehydration("corrupt", `devlead: skipping a cold lead candidate with a corrupt DevLead replay: ${folded.failure}`);
25141
+ const location = sourcePath === void 0 ? "" : ` at ${sourcePath}`;
25142
+ this.warnRehydration(
25143
+ "corrupt",
25144
+ `devlead: skipping cold lead candidate Session "${sessionId}"${location} with a corrupt DevLead replay: ${folded.failure}`,
25145
+ `Session "${sessionId}"${location} has a corrupt DevLead replay: ${folded.failure}`
25146
+ );
23747
25147
  state.index += 1;
23748
25148
  continue;
23749
25149
  }
@@ -23757,6 +25157,7 @@ var DevLeadService = class extends Service {
23757
25157
  archived: archived.has(sessionId),
23758
25158
  running: false,
23759
25159
  createdAt: record2.header.createdAt,
25160
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
23760
25161
  enabledAt: lastEnabledAt(events) ?? 0
23761
25162
  });
23762
25163
  }
@@ -24420,8 +25821,8 @@ ${text}` : text,
24420
25821
  return record2;
24421
25822
  }
24422
25823
  /** Lazy TTL: only a still-open question expires; answered is never rewritten. */
24423
- questionExpired(report, answers, now = Date.now(), open = questionStatusOf(answers, report.id) === "open") {
24424
- return this.resolved.questionTtlMs > 0 && report.kind === "question" && open && now - report.at >= this.resolved.questionTtlMs;
25824
+ questionExpired(report, answers, now = Date.now(), open2 = questionStatusOf(answers, report.id) === "open") {
25825
+ return this.resolved.questionTtlMs > 0 && report.kind === "question" && open2 && now - report.at >= this.resolved.questionTtlMs;
24425
25826
  }
24426
25827
  /**
24427
25828
  * Read the derived question/answer state of one question report from the
@@ -24446,9 +25847,9 @@ ${text}` : text,
24446
25847
  };
24447
25848
  }
24448
25849
  const answeredAt = fact.answeredAt ?? (fact.status === "admitted" || fact.status === "claimed" || fact.status === "presented" ? fact.at : void 0);
24449
- const open = fact.status === "discarded" || fact.status === "failed";
25850
+ const open2 = fact.status === "discarded" || fact.status === "failed";
24450
25851
  return {
24451
- questionStatus: open && this.questionExpired(report, state.answers, Date.now(), true) ? "expired" : open ? "open" : "answered",
25852
+ questionStatus: open2 && this.questionExpired(report, state.answers, Date.now(), true) ? "expired" : open2 ? "open" : "answered",
24452
25853
  answerStatus: fact.status,
24453
25854
  answerMessageId: fact.messageId,
24454
25855
  ...answeredAt === void 0 ? {} : { answeredAt },
@@ -25790,6 +27191,20 @@ ${text}` : text,
25790
27191
  var index_default = DevLeadService;
25791
27192
  export {
25792
27193
  Config,
27194
+ DEVLEAD_BOARD_DIR_SEGMENTS,
27195
+ DEVLEAD_BOARD_FILE_NAME,
27196
+ DEVLEAD_BOARD_ID_MAX,
27197
+ DEVLEAD_BOARD_MAX_BLOCKERS,
27198
+ DEVLEAD_BOARD_MAX_BYTES,
27199
+ DEVLEAD_BOARD_MAX_PROJECTS,
27200
+ DEVLEAD_BOARD_MAX_TASKS,
27201
+ DEVLEAD_BOARD_PATH_MAX,
27202
+ DEVLEAD_BOARD_READ_MAX_BYTES,
27203
+ DEVLEAD_BOARD_READ_MAX_TASKS,
27204
+ DEVLEAD_BOARD_SCHEMA_VERSION,
27205
+ DEVLEAD_BOARD_SUMMARY_MAX_BYTES,
27206
+ DEVLEAD_BOARD_TEXT_MAX,
27207
+ DEVLEAD_BOARD_TITLE_MAX,
25793
27208
  DEVLEAD_DEFAULT_MAX_WATCHED,
25794
27209
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
25795
27210
  DEVLEAD_ERROR_EXCERPT_MAX,
@@ -25809,6 +27224,8 @@ export {
25809
27224
  DEVLEAD_REPORT_SUMMARY_MAX,
25810
27225
  DEVLEAD_RESET_RECORD_TYPE,
25811
27226
  DEVLEAD_WATCH_RECORD_TYPE,
27227
+ DevLeadBoardError,
27228
+ DevLeadBoardStore,
25812
27229
  DevLeadError,
25813
27230
  DevLeadMetrics,
25814
27231
  DevLeadService,
@@ -25832,6 +27249,7 @@ export {
25832
27249
  decodeResetRecord,
25833
27250
  decodeWatchRecord,
25834
27251
  index_default as default,
27252
+ devLeadBoardSchema,
25835
27253
  devLeadModeProjectionDefinition,
25836
27254
  devLeadModeProjectionSchema,
25837
27255
  devLeadModeProjectionStateSchema,
@@ -25850,6 +27268,7 @@ export {
25850
27268
  emptyDevLeadProjectionState,
25851
27269
  emptyDevLeadWatchProjectionState,
25852
27270
  failureExcerpt,
27271
+ isDevLeadBoardError,
25853
27272
  isDevLeadError,
25854
27273
  isHumanDirectedTurn,
25855
27274
  legacyDevLeadRecordReason,
@@ -25857,11 +27276,13 @@ export {
25857
27276
  notificationId,
25858
27277
  notificationRecord,
25859
27278
  recordApiStatus,
27279
+ renderDevLeadBoardSummary,
25860
27280
  renderDevLeadNotice,
25861
27281
  repairRecord,
25862
27282
  reportAnswerRecord,
25863
27283
  reportRecord,
25864
27284
  representableInstant,
25865
27285
  resetRecord,
27286
+ resolveDevLeadBoardPath,
25866
27287
  watchRecord
25867
27288
  };