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

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 +64 -7
  2. package/lib/index.js +2186 -59
  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 mkdir3, stat as stat4 } from "node:fs/promises";
10
+ import { isAbsolute as isAbsolute4 } 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 stat5 = persistence?.stat;
155
+ if (typeof stat5 !== "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 stat5.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,1387 @@ 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 serializedBytes2 = (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 (serializedBytes2(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 (serializedBytes2(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 resolveDevLeadBoardProject(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) resolveDevLeadBoardProject(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, notes) {
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
+ const projectNotes = project.status === "active" ? notes?.projects.find((candidate) => candidate.id === project.id)?.notes : void 0;
18269
+ const latest = projectNotes?.reduce(
18270
+ (current, note) => current === void 0 || note.updatedAt > current.updatedAt ? note : current,
18271
+ void 0
18272
+ );
18273
+ const latestTitle = latest === void 0 ? "" : Array.from(singleLine(latest.title)).slice(0, 80).join("");
18274
+ lines.push(
18275
+ `- ${singleLine(project.id)}/${singleLine(project.workspace.title)} [${project.status}/${project.priority}]${focus.length === 0 ? "" : ` focus: ${focus}`}${project.blockers.length === 0 ? "" : ` !blockers:${project.blockers.length}`}${projectNotes === void 0 || projectNotes.length === 0 ? "" : ` notes:${projectNotes.length}`}${latestTitle.length === 0 ? "" : ` latest:"${latestTitle}"`}`
18276
+ );
18277
+ }
18278
+ const output = { text: "", bytes: 0 };
18279
+ for (let index = 0; index < lines.length; index += 1) {
18280
+ const line = lines[index] ?? "";
18281
+ if (!appendUtf8(output, `${index === 0 ? "" : "\n"}${line}`, DEVLEAD_BOARD_SUMMARY_MAX_BYTES)) {
18282
+ appendUtf8(output, "\n\u2026", DEVLEAD_BOARD_SUMMARY_MAX_BYTES);
18283
+ break;
18284
+ }
18285
+ }
18286
+ return output.text;
18287
+ }
18288
+ var DevLeadBoardStore = class {
18289
+ /**
18290
+ * @param boardPath - absolute deployment-configured path; blank/undefined disables the board.
18291
+ * @param logger - Host logger for best-effort watcher failures.
18292
+ * @param now - injectable clock used by tests.
18293
+ */
18294
+ constructor(boardPath, logger2 = { warn: () => void 0 }, now = Date.now) {
18295
+ this.logger = logger2;
18296
+ this.now = now;
18297
+ const trimmed = boardPath?.trim() ?? "";
18298
+ if (trimmed.length > 0 && !isAbsolute2(trimmed)) {
18299
+ throw new DevLeadBoardError("boardPath must be an absolute path", "BOARD_INVALID", [
18300
+ { pointer: "/boardPath", message: "boardPath must be an absolute path" }
18301
+ ]);
18302
+ }
18303
+ this.filePath = trimmed.length === 0 ? void 0 : trimmed;
18304
+ }
18305
+ logger;
18306
+ now;
18307
+ filePath;
18308
+ cache;
18309
+ fingerprint;
18310
+ lastError;
18311
+ dirty = true;
18312
+ loading;
18313
+ writeTail = Promise.resolve();
18314
+ watcher;
18315
+ closed = false;
18316
+ /** Absolute configured file path, or undefined when disabled. */
18317
+ get path() {
18318
+ return this.filePath;
18319
+ }
18320
+ /** Whether board reads/writes are configured. */
18321
+ get enabled() {
18322
+ return this.filePath !== void 0;
18323
+ }
18324
+ /**
18325
+ * Prepare the watchable parent, then load without rejecting for a malformed
18326
+ * file.
18327
+ *
18328
+ * The service only calls this for an explicit deployment override or for a
18329
+ * derived path whose workspace root already exists as a directory; a missing
18330
+ * workspace root disables the board instead of being recreated here.
18331
+ */
18332
+ async start() {
18333
+ if (this.filePath === void 0) return;
18334
+ try {
18335
+ await mkdir(dirname(this.filePath), { recursive: true, mode: 448 });
18336
+ } catch (error51) {
18337
+ if (isDevLeadBoardError(error51)) throw error51;
18338
+ if (isWriteIoError(error51)) throw writeIoError(this.filePath, error51);
18339
+ throw error51;
18340
+ }
18341
+ await this.refresh(true);
18342
+ this.startWatcher();
18343
+ }
18344
+ /** Stop watching and settle already-queued work. */
18345
+ async close() {
18346
+ this.closed = true;
18347
+ this.watcher?.close();
18348
+ this.watcher = void 0;
18349
+ await this.loading;
18350
+ await this.writeTail;
18351
+ }
18352
+ requirePath() {
18353
+ if (this.filePath === void 0) {
18354
+ throw new DevLeadBoardError("DevLead board is disabled; configure devlead boardPath", "BOARD_DISABLED");
18355
+ }
18356
+ return this.filePath;
18357
+ }
18358
+ startWatcher() {
18359
+ const filePath = this.filePath;
18360
+ if (filePath === void 0 || this.watcher !== void 0 || this.closed) return;
18361
+ try {
18362
+ this.watcher = watch(dirname(filePath), { persistent: false }, (_event, filename) => {
18363
+ if (filename !== null && filename.toString() !== basename(filePath)) return;
18364
+ this.dirty = true;
18365
+ void this.refresh();
18366
+ });
18367
+ this.watcher.on("error", (error51) => {
18368
+ this.logger.warn(`devlead: board watcher failed for ${filePath}: ${errorMessage2(error51)}`);
18369
+ this.watcher?.close();
18370
+ this.watcher = void 0;
18371
+ });
18372
+ } catch (error51) {
18373
+ if (error51.code !== "ENOENT") {
18374
+ this.logger.warn(`devlead: could not watch board ${filePath}: ${errorMessage2(error51)}`);
18375
+ }
18376
+ }
18377
+ }
18378
+ async refresh(force = false) {
18379
+ if (this.filePath === void 0) return;
18380
+ if (this.dirty) force = true;
18381
+ for (; ; ) {
18382
+ const pending = this.loading;
18383
+ if (pending !== void 0) {
18384
+ await pending;
18385
+ if (!force) return;
18386
+ continue;
18387
+ }
18388
+ const operation = this.load(force);
18389
+ this.loading = operation;
18390
+ try {
18391
+ await operation;
18392
+ return;
18393
+ } finally {
18394
+ if (this.loading === operation) this.loading = void 0;
18395
+ }
18396
+ }
18397
+ }
18398
+ async load(force) {
18399
+ const filePath = this.requirePath();
18400
+ this.dirty = false;
18401
+ try {
18402
+ for (let attempt = 0; attempt < DEVLEAD_BOARD_READ_ATTEMPTS; attempt += 1) {
18403
+ const before = await stat2(filePath);
18404
+ if (!force && this.cache !== void 0 && this.lastError === void 0 && sameFingerprint(this.fingerprint, before)) {
18405
+ this.startWatcher();
18406
+ return;
18407
+ }
18408
+ if (before.size > DEVLEAD_BOARD_MAX_BYTES) {
18409
+ this.lastError = new DevLeadBoardError(
18410
+ `board file exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes`,
18411
+ "BOARD_LIMIT_EXCEEDED",
18412
+ [{ pointer: "", message: `file size ${before.size} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18413
+ );
18414
+ return;
18415
+ }
18416
+ const content = await readFile(filePath, "utf8");
18417
+ const after = await stat2(filePath);
18418
+ if (!sameFingerprint(before, after) || Buffer.byteLength(content, "utf8") !== after.size) continue;
18419
+ let value;
18420
+ try {
18421
+ value = JSON.parse(content);
18422
+ } catch (error51) {
18423
+ this.lastError = new DevLeadBoardError(
18424
+ `board file is not valid JSON: ${errorMessage2(error51)}`,
18425
+ "BOARD_INVALID",
18426
+ [{ pointer: "", message: errorMessage2(error51) }]
18427
+ );
18428
+ return;
18429
+ }
18430
+ let board;
18431
+ try {
18432
+ board = parseBoard(value);
18433
+ } catch (error51) {
18434
+ this.lastError = error51 instanceof DevLeadBoardError ? error51 : new DevLeadBoardError(errorMessage2(error51), "BOARD_INVALID");
18435
+ return;
18436
+ }
18437
+ this.cache = board;
18438
+ this.fingerprint = { mtimeMs: after.mtimeMs, size: after.size, ino: after.ino };
18439
+ this.lastError = void 0;
18440
+ this.startWatcher();
18441
+ return;
18442
+ }
18443
+ this.lastError = new DevLeadBoardError(
18444
+ `board file changed repeatedly while reading ${filePath}; retry`,
18445
+ "BOARD_IO_ERROR"
18446
+ );
18447
+ } catch (error51) {
18448
+ if (error51.code === "ENOENT") {
18449
+ this.cache = void 0;
18450
+ this.fingerprint = void 0;
18451
+ this.lastError = new DevLeadBoardError(`board file does not exist: ${filePath}`, "BOARD_NOT_FOUND");
18452
+ return;
18453
+ }
18454
+ if (error51 instanceof DevLeadBoardError) {
18455
+ this.lastError = error51;
18456
+ return;
18457
+ }
18458
+ this.lastError = new DevLeadBoardError(
18459
+ `could not read board ${filePath}: ${errorMessage2(error51)}`,
18460
+ "BOARD_IO_ERROR"
18461
+ );
18462
+ }
18463
+ }
18464
+ async current() {
18465
+ this.requirePath();
18466
+ await this.refresh();
18467
+ if (this.lastError !== void 0) throw this.lastError;
18468
+ if (this.cache === void 0) {
18469
+ throw new DevLeadBoardError("board has no valid snapshot", "BOARD_NOT_FOUND");
18470
+ }
18471
+ return this.cache;
18472
+ }
18473
+ /** Read a detached, optionally filtered board projection. */
18474
+ async read(filter = {}) {
18475
+ const board = await this.current();
18476
+ const includeTasks = filter.includeTasks ?? filter.project !== void 0;
18477
+ if (filter.limit !== void 0 && (!Number.isSafeInteger(filter.limit) || filter.limit < 1)) {
18478
+ throw new DevLeadBoardError("limit must be a positive safe integer", "BOARD_INVALID", [
18479
+ { pointer: "/limit", message: "limit must be a positive safe integer" }
18480
+ ]);
18481
+ }
18482
+ let projects;
18483
+ let truncated = false;
18484
+ if (filter.project !== void 0) {
18485
+ projects = [resolveDevLeadBoardProject(board, filter.project)];
18486
+ } else {
18487
+ const limit2 = Math.min(filter.limit ?? DEVLEAD_BOARD_MAX_PROJECTS, DEVLEAD_BOARD_MAX_PROJECTS);
18488
+ projects = board.projects.slice(0, limit2);
18489
+ truncated = board.projects.length > projects.length;
18490
+ }
18491
+ return boundReadResult({
18492
+ revision: board.revision,
18493
+ updatedAt: board.updatedAt,
18494
+ projects: projects.map((project) => {
18495
+ if (includeTasks && project.tasks.length > DEVLEAD_BOARD_READ_MAX_TASKS) truncated = true;
18496
+ return projectView(project, includeTasks);
18497
+ }),
18498
+ ...truncated ? { truncated: true } : {}
18499
+ });
18500
+ }
18501
+ /** Resolve one id/title/path against the latest valid board snapshot. */
18502
+ async resolveProject(reference) {
18503
+ return structuredClone(resolveDevLeadBoardProject(await this.current(), reference));
18504
+ }
18505
+ /**
18506
+ * Apply one project mutation. Host calls share one promise chain; every call
18507
+ * then performs its own locked disk read-modify-write cycle.
18508
+ */
18509
+ async update(patch, expectedRevision, signal) {
18510
+ this.requirePath();
18511
+ if (expectedRevision !== void 0 && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
18512
+ throw new DevLeadBoardError("expectedRevision must be a non-negative safe integer", "BOARD_INVALID", [
18513
+ { pointer: "/expectedRevision", message: "expectedRevision must be a non-negative safe integer" }
18514
+ ]);
18515
+ }
18516
+ signal?.throwIfAborted();
18517
+ const operation = this.writeTail.then(() => this.updateLocked(patch, expectedRevision, signal));
18518
+ this.writeTail = operation.catch(() => void 0);
18519
+ return operation;
18520
+ }
18521
+ async updateLocked(input, expectedRevision, signal) {
18522
+ const filePath = this.requirePath();
18523
+ try {
18524
+ const patch = validateUpdateInput(input);
18525
+ try {
18526
+ await stat2(dirname(filePath));
18527
+ } catch (error51) {
18528
+ if (errorCode(error51) !== "ENOENT") throw error51;
18529
+ validateMissingFileUpdate(patch, expectedRevision);
18530
+ }
18531
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
18532
+ this.startWatcher();
18533
+ return await withFileLock(filePath, async () => {
18534
+ signal?.throwIfAborted();
18535
+ await this.refresh(true);
18536
+ if (this.lastError !== void 0 && this.lastError.code !== "BOARD_NOT_FOUND") throw this.lastError;
18537
+ const timestamp = new Date(this.now()).toISOString();
18538
+ const current = this.cache ?? emptyBoard(patch.updatedBy, timestamp);
18539
+ if (expectedRevision !== void 0 && current.revision !== expectedRevision) {
18540
+ throw new DevLeadBoardError(
18541
+ `board revision conflict: expected r${expectedRevision}, current r${current.revision}`,
18542
+ "BOARD_REVISION_CONFLICT",
18543
+ [{ pointer: "/revision", message: `expected ${expectedRevision}, current ${current.revision}` }]
18544
+ );
18545
+ }
18546
+ const next = structuredClone(current);
18547
+ const changed = applyProjectPatch(next, patch, timestamp);
18548
+ const project = resolveDevLeadBoardProject(next, patch.project);
18549
+ if (changed.length === 0) {
18550
+ return {
18551
+ revision: current.revision,
18552
+ updatedAt: current.updatedAt,
18553
+ project: projectView(project, false),
18554
+ changed
18555
+ };
18556
+ }
18557
+ next.revision = current.revision + 1;
18558
+ next.updatedAt = timestamp;
18559
+ next.updatedBy = structuredClone(patch.updatedBy);
18560
+ const validated = parseBoard(next);
18561
+ const content = `${JSON.stringify(validated, null, 2)}
18562
+ `;
18563
+ const bytes = Buffer.byteLength(content, "utf8");
18564
+ if (bytes > DEVLEAD_BOARD_MAX_BYTES) {
18565
+ throw new DevLeadBoardError(
18566
+ `board update would exceed ${DEVLEAD_BOARD_MAX_BYTES} bytes (${bytes})`,
18567
+ "BOARD_LIMIT_EXCEEDED",
18568
+ [{ pointer: "", message: `serialized size ${bytes} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18569
+ );
18570
+ }
18571
+ await writeFileAtomic(filePath, content, { mode: 384, dirMode: 448 });
18572
+ const written = await stat2(filePath);
18573
+ this.cache = validated;
18574
+ this.lastError = void 0;
18575
+ this.dirty = false;
18576
+ this.fingerprint = { mtimeMs: written.mtimeMs, size: written.size, ino: written.ino };
18577
+ this.startWatcher();
18578
+ return {
18579
+ revision: validated.revision,
18580
+ updatedAt: validated.updatedAt,
18581
+ project: projectView(resolveDevLeadBoardProject(validated, project.id), false),
18582
+ changed
18583
+ };
18584
+ }, signal === void 0 ? {} : { signal });
18585
+ } catch (error51) {
18586
+ if (isDevLeadBoardError(error51)) throw error51;
18587
+ if (isWriteIoError(error51)) throw writeIoError(filePath, error51);
18588
+ throw error51;
18589
+ }
18590
+ }
18591
+ /** Synchronous cache-only text for `systemPrompt.context()`. */
18592
+ summary(notes) {
18593
+ if (this.filePath === void 0) return "";
18594
+ return renderDevLeadBoardSummary(this.cache, notes);
18595
+ }
18596
+ };
18597
+ function applyProjectPatch(board, patch, timestamp) {
18598
+ const changed = [];
18599
+ let project;
18600
+ try {
18601
+ project = resolveDevLeadBoardProject(board, patch.project);
18602
+ } catch (error51) {
18603
+ if (!(error51 instanceof DevLeadBoardError) || error51.code !== "BOARD_PROJECT_NOT_FOUND" || patch.create !== true) throw error51;
18604
+ const workspacePatch = patch.set?.workspace;
18605
+ const workspacePath = workspacePatch?.path;
18606
+ if (workspacePath === void 0 || workspacePath.trim().length === 0) {
18607
+ throw new DevLeadBoardError("creating a project requires set.workspace.path", "BOARD_INVALID", [
18608
+ { pointer: "/set/workspace/path", message: "required when create is true" }
18609
+ ]);
18610
+ }
18611
+ const id = patch.project.trim();
18612
+ project = {
18613
+ id,
18614
+ workspace: {
18615
+ path: workspacePath,
18616
+ title: workspacePatch?.title ?? (basename(workspacePath) || id)
18617
+ },
18618
+ status: "active",
18619
+ priority: "medium",
18620
+ goal: "",
18621
+ focus: "",
18622
+ next: "",
18623
+ blockers: [],
18624
+ tasks: [],
18625
+ updatedAt: timestamp
18626
+ };
18627
+ board.projects.push(project);
18628
+ changed.push("project.create");
18629
+ }
18630
+ let projectChanged = changed.length > 0;
18631
+ const set2 = patch.set;
18632
+ if (set2 !== void 0) {
18633
+ for (const field of ["status", "priority", "goal", "focus", "next"]) {
18634
+ const value = set2[field];
18635
+ if (value !== void 0 && project[field] !== value) {
18636
+ Object.assign(project, { [field]: value });
18637
+ changed.push(`set.${field}`);
18638
+ projectChanged = true;
18639
+ }
18640
+ }
18641
+ if (set2.workspace !== void 0) {
18642
+ for (const field of ["path", "title"]) {
18643
+ const value = set2.workspace[field];
18644
+ if (value !== void 0 && project.workspace[field] !== value) {
18645
+ project.workspace[field] = value;
18646
+ changed.push(`set.workspace.${field}`);
18647
+ projectChanged = true;
18648
+ }
18649
+ }
18650
+ }
18651
+ }
18652
+ const blockers = patch.blockers;
18653
+ if (blockers?.clear === true && project.blockers.length > 0) {
18654
+ project.blockers = [];
18655
+ changed.push("blockers.clear");
18656
+ projectChanged = true;
18657
+ }
18658
+ if (blockers?.remove !== void 0) {
18659
+ const remove = new Set(blockers.remove);
18660
+ const retained = project.blockers.filter((blocker) => !remove.has(blocker.id));
18661
+ if (retained.length !== project.blockers.length) {
18662
+ project.blockers = retained;
18663
+ changed.push("blockers.remove");
18664
+ projectChanged = true;
18665
+ }
18666
+ }
18667
+ for (const addition of blockers?.add ?? []) {
18668
+ const existing = project.blockers.find((blocker2) => blocker2.id === addition.id);
18669
+ const sessionId = addition.sessionId ?? existing?.sessionId;
18670
+ const blocker = {
18671
+ id: addition.id,
18672
+ text: addition.text,
18673
+ since: existing?.since ?? timestamp,
18674
+ ...sessionId === void 0 ? {} : { sessionId }
18675
+ };
18676
+ if (existing === void 0) {
18677
+ project.blockers.push(blocker);
18678
+ changed.push(`blockers.add:${addition.id}`);
18679
+ projectChanged = true;
18680
+ } else if (existing.text !== blocker.text || existing.sessionId !== blocker.sessionId) {
18681
+ Object.assign(existing, blocker);
18682
+ changed.push(`blockers.add:${addition.id}`);
18683
+ projectChanged = true;
18684
+ }
18685
+ }
18686
+ if (patch.tasks?.remove !== void 0) {
18687
+ const remove = new Set(patch.tasks.remove);
18688
+ const retained = project.tasks.filter((task) => !remove.has(task.id));
18689
+ if (retained.length !== project.tasks.length) {
18690
+ project.tasks = retained;
18691
+ changed.push("tasks.remove");
18692
+ projectChanged = true;
18693
+ }
18694
+ }
18695
+ for (const upsert2 of patch.tasks?.upsert ?? []) {
18696
+ const existing = project.tasks.find((task) => task.id === upsert2.id);
18697
+ if (existing === void 0) {
18698
+ if (upsert2.title === void 0 || upsert2.title.trim().length === 0) {
18699
+ throw new DevLeadBoardError(`new task "${upsert2.id}" requires a non-empty title`, "BOARD_INVALID", [
18700
+ { pointer: "/tasks/upsert", message: `new task "${upsert2.id}" requires title` }
18701
+ ]);
18702
+ }
18703
+ project.tasks.push({
18704
+ id: upsert2.id,
18705
+ title: upsert2.title,
18706
+ status: upsert2.status ?? "todo",
18707
+ ...upsert2.ownerSessionId === void 0 ? {} : { ownerSessionId: upsert2.ownerSessionId },
18708
+ updatedAt: timestamp
18709
+ });
18710
+ changed.push(`tasks.upsert:${upsert2.id}`);
18711
+ projectChanged = true;
18712
+ continue;
18713
+ }
18714
+ let taskChanged = false;
18715
+ if (upsert2.title !== void 0 && existing.title !== upsert2.title) {
18716
+ existing.title = upsert2.title;
18717
+ taskChanged = true;
18718
+ }
18719
+ if (upsert2.status !== void 0 && existing.status !== upsert2.status) {
18720
+ existing.status = upsert2.status;
18721
+ taskChanged = true;
18722
+ }
18723
+ if (upsert2.ownerSessionId !== void 0 && existing.ownerSessionId !== upsert2.ownerSessionId) {
18724
+ existing.ownerSessionId = upsert2.ownerSessionId;
18725
+ taskChanged = true;
18726
+ }
18727
+ if (taskChanged) {
18728
+ existing.updatedAt = timestamp;
18729
+ changed.push(`tasks.upsert:${upsert2.id}`);
18730
+ projectChanged = true;
18731
+ }
18732
+ }
18733
+ if (projectChanged) project.updatedAt = timestamp;
18734
+ return changed;
18735
+ }
18736
+
18737
+ // packages/devlead/src/notes.ts
18738
+ import { createHash as createHash2, randomUUID as cryptoRandomUUID } from "node:crypto";
18739
+ import { mkdir as mkdir2, readFile as readFile2, rm, stat as stat3 } from "node:fs/promises";
18740
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join2 } from "node:path";
18741
+ import { withFileLock as withFileLock2, writeFileAtomic as writeFileAtomic2 } from "@deepseek-ai/dsh-atomic-write";
18742
+ import {
18743
+ createDevLeadNotesIndexSchema,
18744
+ devLeadBoardIssueViews as devLeadBoardIssueViews2,
18745
+ DEVLEAD_NOTES_DIR_NAME,
18746
+ DEVLEAD_NOTES_DIRECTORY_MAX,
18747
+ DEVLEAD_NOTES_ID_MAX,
18748
+ DEVLEAD_NOTES_INDEX_FILE_NAME,
18749
+ DEVLEAD_NOTES_INDEX_MAX_BYTES,
18750
+ DEVLEAD_NOTES_MAX_PER_PROJECT,
18751
+ DEVLEAD_NOTES_MAX_PROJECTS,
18752
+ DEVLEAD_NOTES_NOTE_MAX_BYTES,
18753
+ DEVLEAD_NOTES_PATH_MAX,
18754
+ DEVLEAD_NOTES_READ_MAX_BYTES,
18755
+ DEVLEAD_NOTES_SCHEMA_VERSION,
18756
+ DEVLEAD_NOTES_SUMMARY_MAX,
18757
+ DEVLEAD_NOTES_TIMESTAMP_MAX,
18758
+ DEVLEAD_NOTES_TITLE_MAX
18759
+ } from "@yankeguo/dsh-devlead-protocol";
18760
+ var notesIndexSchema = createDevLeadNotesIndexSchema();
18761
+ var EMPTY_TIMESTAMP = (/* @__PURE__ */ new Date(0)).toISOString();
18762
+ var READ_ATTEMPTS = 4;
18763
+ function emptyIndex() {
18764
+ return {
18765
+ schemaVersion: DEVLEAD_NOTES_SCHEMA_VERSION,
18766
+ revision: 0,
18767
+ updatedAt: EMPTY_TIMESTAMP,
18768
+ projects: []
18769
+ };
18770
+ }
18771
+ function sameFingerprint2(left, right) {
18772
+ return left !== void 0 && left.mtimeMs === right.mtimeMs && left.size === right.size && left.ino === right.ino;
18773
+ }
18774
+ function errorMessage3(error51) {
18775
+ return error51 instanceof Error ? error51.message : String(error51);
18776
+ }
18777
+ function errorCode2(error51) {
18778
+ if (typeof error51 !== "object" || error51 === null) return void 0;
18779
+ const code = error51.code;
18780
+ return typeof code === "string" ? code : void 0;
18781
+ }
18782
+ var FILESYSTEM_ERROR_CODES2 = /* @__PURE__ */ new Set([
18783
+ "EACCES",
18784
+ "EAGAIN",
18785
+ "EBUSY",
18786
+ "EDQUOT",
18787
+ "EEXIST",
18788
+ "EFBIG",
18789
+ "EIO",
18790
+ "EISDIR",
18791
+ "ELOOP",
18792
+ "EMFILE",
18793
+ "ENAMETOOLONG",
18794
+ "ENFILE",
18795
+ "ENOMEM",
18796
+ "ENOENT",
18797
+ "ENOSPC",
18798
+ "ENOTDIR",
18799
+ "ENOTEMPTY",
18800
+ "EPERM",
18801
+ "EROFS",
18802
+ "ETXTBSY"
18803
+ ]);
18804
+ function isWriterLockTimeout2(error51) {
18805
+ const message = errorMessage3(error51);
18806
+ const code = errorCode2(error51);
18807
+ return code === "FILE_LOCK_TIMEOUT" || code === "ATOMIC_WRITE_LOCK_TIMEOUT" || /timed out waiting for the writer lock|writer lock timed out/iu.test(message);
18808
+ }
18809
+ function isWriteIoError2(error51) {
18810
+ const code = errorCode2(error51);
18811
+ return code !== void 0 && FILESYSTEM_ERROR_CODES2.has(code) || error51 instanceof Error && error51.name === "FileLockError" || isWriterLockTimeout2(error51);
18812
+ }
18813
+ function ioError(action, path, error51) {
18814
+ const retry = isWriterLockTimeout2(error51);
18815
+ return new DevLeadBoardError(
18816
+ `could not ${action} ${path}: ${errorMessage3(error51)}${retry ? "; retry after the current writer finishes" : ""}`,
18817
+ "BOARD_IO_ERROR"
18818
+ );
18819
+ }
18820
+ function invalid(message, pointer) {
18821
+ return new DevLeadBoardError(message, "BOARD_INVALID", [{ pointer, message }]);
18822
+ }
18823
+ function limit(message, pointer) {
18824
+ return new DevLeadBoardError(message, "BOARD_LIMIT_EXCEEDED", [{ pointer, message }]);
18825
+ }
18826
+ function validationError2(error51) {
18827
+ const issues = devLeadBoardIssueViews2(error51.issues);
18828
+ const limited = error51.issues.some((issue2) => issue2.code === "too_big");
18829
+ const first = issues[0];
18830
+ return new DevLeadBoardError(
18831
+ `notes index validation failed${first === void 0 ? "" : ` at ${first.pointer || "/"}: ${first.message}`}`,
18832
+ limited ? "BOARD_LIMIT_EXCEEDED" : "BOARD_INVALID",
18833
+ issues
18834
+ );
18835
+ }
18836
+ function parseIndex(value) {
18837
+ const parsed = notesIndexSchema.safeParse(value);
18838
+ if (!parsed.success) throw validationError2(parsed.error);
18839
+ return parsed.data;
18840
+ }
18841
+ function validateNonNegativeInteger(value, field) {
18842
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) {
18843
+ throw invalid(`${field} must be a non-negative safe integer`, `/${field}`);
18844
+ }
18845
+ }
18846
+ function validateContentSize(content, pointer = "/content") {
18847
+ const bytes = Buffer.byteLength(content, "utf8");
18848
+ if (bytes > DEVLEAD_NOTES_NOTE_MAX_BYTES) {
18849
+ throw limit(`note content exceeds ${DEVLEAD_NOTES_NOTE_MAX_BYTES} UTF-8 bytes (${bytes})`, pointer);
18850
+ }
18851
+ }
18852
+ function decodeUtf8(bytes, label) {
18853
+ try {
18854
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
18855
+ } catch (error51) {
18856
+ throw invalid(`${label} is not valid UTF-8: ${errorMessage3(error51)}`, "");
18857
+ }
18858
+ }
18859
+ function serializedBytes(value) {
18860
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
18861
+ }
18862
+ function boundNoteRead(result) {
18863
+ if (result.note === void 0 || serializedBytes(result) <= DEVLEAD_NOTES_READ_MAX_BYTES) return result;
18864
+ const characters = Array.from(result.note.content);
18865
+ let low = 0;
18866
+ let high = characters.length;
18867
+ let content = "";
18868
+ while (low <= high) {
18869
+ const middle = Math.floor((low + high) / 2);
18870
+ const candidate = characters.slice(0, middle).join("");
18871
+ const bounded = {
18872
+ ...result,
18873
+ note: { ...result.note, content: candidate },
18874
+ truncated: true
18875
+ };
18876
+ if (serializedBytes(bounded) <= DEVLEAD_NOTES_READ_MAX_BYTES) {
18877
+ content = candidate;
18878
+ low = middle + 1;
18879
+ } else {
18880
+ high = middle - 1;
18881
+ }
18882
+ }
18883
+ return { ...result, note: { ...result.note, content }, truncated: true };
18884
+ }
18885
+ function validateWriteShape(patch) {
18886
+ validateNonNegativeInteger(patch.expectedRevision, "expectedRevision");
18887
+ if (!["create", "update-metadata", "delete"].includes(patch.operation)) {
18888
+ throw invalid("operation must be create, update-metadata, or delete", "/operation");
18889
+ }
18890
+ if (patch.operation !== "create" && patch.note === void 0) {
18891
+ throw invalid(`note is required for ${patch.operation}`, "/note");
18892
+ }
18893
+ if (patch.operation === "create") {
18894
+ if (patch.title === void 0 || patch.title.trim().length === 0) {
18895
+ throw invalid("create requires a non-empty title", "/title");
18896
+ }
18897
+ } else if (patch.content !== void 0) {
18898
+ throw invalid(`${patch.operation} does not accept content; edit the returned Markdown path with native file tools`, "/content");
18899
+ }
18900
+ if (patch.operation === "delete" && (patch.title !== void 0 || patch.summary !== void 0)) {
18901
+ throw invalid("delete does not accept title or summary", "/operation");
18902
+ }
18903
+ if (patch.content !== void 0) validateContentSize(patch.content);
18904
+ const id = patch.note ?? "00000000-0000-4000-8000-000000000000";
18905
+ const directory = "project-0123456789ab";
18906
+ parseIndex({
18907
+ ...emptyIndex(),
18908
+ projects: [{
18909
+ id: "validation",
18910
+ directory,
18911
+ notes: [{
18912
+ id,
18913
+ title: patch.title?.trim() ?? "DevLead validation",
18914
+ summary: patch.summary ?? "",
18915
+ updatedAt: EMPTY_TIMESTAMP,
18916
+ bytes: 0,
18917
+ path: `${directory}/${id}.md`
18918
+ }]
18919
+ }]
18920
+ });
18921
+ }
18922
+ function projectDirectory(projectId, index) {
18923
+ const existing = index.projects.find((project) => project.id === projectId);
18924
+ if (existing !== void 0) return existing.directory;
18925
+ const hash2 = createHash2("sha256").update(projectId, "utf8").digest("hex");
18926
+ const normalized = projectId.normalize("NFKD").toLowerCase();
18927
+ let base = normalized.replaceAll(/[^a-z0-9._-]+/gu, "-").replaceAll(/^[._-]+|[._-]+$/gu, "");
18928
+ base = base.slice(0, 48).replaceAll(/[._-]+$/gu, "");
18929
+ if (base.length === 0) base = "project";
18930
+ const short = `${base}-${hash2.slice(0, 12)}`;
18931
+ const collision = index.projects.some((project) => project.directory === short && project.id !== projectId);
18932
+ return collision ? `${base}-${hash2}` : short;
18933
+ }
18934
+ function noteFilePath(root, project, note) {
18935
+ return join2(root, project.directory, `${note.id}.md`);
18936
+ }
18937
+ var DevLeadBoardNotesStore = class {
18938
+ constructor(boardPath, board, logger2 = { warn: () => void 0 }, now = Date.now, randomUUID = cryptoRandomUUID) {
18939
+ this.board = board;
18940
+ this.logger = logger2;
18941
+ this.now = now;
18942
+ this.randomUUID = randomUUID;
18943
+ const trimmed = boardPath?.trim() ?? "";
18944
+ if (trimmed.length > 0 && !isAbsolute3(trimmed)) {
18945
+ throw invalid("boardPath must be an absolute path", "/boardPath");
18946
+ }
18947
+ this.rootPath = trimmed.length === 0 ? void 0 : join2(dirname2(trimmed), DEVLEAD_NOTES_DIR_NAME);
18948
+ this.filePath = this.rootPath === void 0 ? void 0 : join2(this.rootPath, DEVLEAD_NOTES_INDEX_FILE_NAME);
18949
+ }
18950
+ board;
18951
+ logger;
18952
+ now;
18953
+ randomUUID;
18954
+ rootPath;
18955
+ filePath;
18956
+ cache;
18957
+ lastError;
18958
+ writeTail = Promise.resolve();
18959
+ /** Absolute notes root, or undefined while the owning board is disabled. */
18960
+ get path() {
18961
+ return this.rootPath;
18962
+ }
18963
+ /** Absolute notes-index path, exposed for diagnostics/tests, never accepted as input. */
18964
+ get indexPath() {
18965
+ return this.filePath;
18966
+ }
18967
+ get enabled() {
18968
+ return this.rootPath !== void 0;
18969
+ }
18970
+ /** Prepare the root and populate the cache; a malformed index degrades reads, not service activation. */
18971
+ async start() {
18972
+ if (this.rootPath === void 0) return;
18973
+ const root = this.rootPath;
18974
+ try {
18975
+ await mkdir2(root, { recursive: true, mode: 448 });
18976
+ } catch (error51) {
18977
+ throw ioError("prepare notes root", root, error51);
18978
+ }
18979
+ await this.refresh();
18980
+ }
18981
+ /** Settle queued writes. No watcher or timer remains owned by this store. */
18982
+ async close() {
18983
+ await this.writeTail;
18984
+ }
18985
+ /** Last valid cached index for the synchronous board-summary renderer. */
18986
+ summaryIndex() {
18987
+ return this.cache;
18988
+ }
18989
+ requireRoot() {
18990
+ if (this.rootPath === void 0) {
18991
+ throw new DevLeadBoardError("DevLead board notes are disabled; activate a lead board first", "BOARD_DISABLED");
18992
+ }
18993
+ return this.rootPath;
18994
+ }
18995
+ requireIndexPath() {
18996
+ this.requireRoot();
18997
+ if (this.filePath === void 0) throw new DevLeadBoardError("DevLead board notes are disabled", "BOARD_DISABLED");
18998
+ return this.filePath;
18999
+ }
19000
+ async refresh() {
19001
+ const filePath = this.requireIndexPath();
19002
+ try {
19003
+ for (let attempt = 0; attempt < READ_ATTEMPTS; attempt += 1) {
19004
+ const before = await stat3(filePath);
19005
+ if (before.size > DEVLEAD_NOTES_INDEX_MAX_BYTES) {
19006
+ this.lastError = limit(
19007
+ `notes index exceeds ${DEVLEAD_NOTES_INDEX_MAX_BYTES} bytes (${before.size})`,
19008
+ ""
19009
+ );
19010
+ return;
19011
+ }
19012
+ const bytes = await readFile2(filePath);
19013
+ const after = await stat3(filePath);
19014
+ if (!sameFingerprint2({ mtimeMs: before.mtimeMs, size: before.size, ino: before.ino }, {
19015
+ mtimeMs: after.mtimeMs,
19016
+ size: after.size,
19017
+ ino: after.ino
19018
+ }) || bytes.length !== after.size) continue;
19019
+ let value;
19020
+ try {
19021
+ value = JSON.parse(decodeUtf8(bytes, "notes index"));
19022
+ } catch (error51) {
19023
+ this.lastError = isDevLeadBoardError(error51) ? error51 : new DevLeadBoardError(
19024
+ `notes index is not valid JSON: ${errorMessage3(error51)}`,
19025
+ "BOARD_INVALID",
19026
+ [{ pointer: "", message: errorMessage3(error51) }]
19027
+ );
19028
+ return;
19029
+ }
19030
+ try {
19031
+ this.cache = parseIndex(value);
19032
+ } catch (error51) {
19033
+ this.lastError = isDevLeadBoardError(error51) ? error51 : new DevLeadBoardError(errorMessage3(error51), "BOARD_INVALID");
19034
+ return;
19035
+ }
19036
+ this.lastError = void 0;
19037
+ return;
19038
+ }
19039
+ this.lastError = ioError("read stable notes index", filePath, new Error("file changed repeatedly; retry"));
19040
+ } catch (error51) {
19041
+ if (errorCode2(error51) === "ENOENT") {
19042
+ this.cache = emptyIndex();
19043
+ this.lastError = void 0;
19044
+ return;
19045
+ }
19046
+ if (isDevLeadBoardError(error51)) {
19047
+ this.lastError = error51;
19048
+ return;
19049
+ }
19050
+ this.lastError = ioError("read notes index", filePath, error51);
19051
+ }
19052
+ }
19053
+ async current() {
19054
+ await this.refresh();
19055
+ if (this.lastError !== void 0) throw this.lastError;
19056
+ return this.cache ?? emptyIndex();
19057
+ }
19058
+ /** Read one project's metadata list, or one note body bounded for the model result. */
19059
+ async read(filter) {
19060
+ this.requireRoot();
19061
+ const operation = this.writeTail.then(() => this.readReconciled(filter));
19062
+ this.writeTail = operation.catch(() => void 0);
19063
+ return operation;
19064
+ }
19065
+ /**
19066
+ * Native Markdown edits bypass this store, so every model read/list lazily
19067
+ * reconciles the selected file snapshots. One locked transaction validates
19068
+ * all selected bodies before committing any metadata repair; an invalid or
19069
+ * missing body therefore leaves the previous index untouched.
19070
+ */
19071
+ async readReconciled(filter) {
19072
+ const root = this.requireRoot();
19073
+ const filePath = this.requireIndexPath();
19074
+ try {
19075
+ const boardProject = await this.board.resolveProject(filter.project);
19076
+ return await withFileLock2(filePath, async () => {
19077
+ const current = await this.current();
19078
+ const currentProject = current.projects.find((candidate) => candidate.id === boardProject.id);
19079
+ let selected = currentProject?.notes ?? [];
19080
+ if (filter.note !== void 0) {
19081
+ const metadata2 = currentProject?.notes.find((note) => note.id === filter.note);
19082
+ if (currentProject === void 0 || metadata2 === void 0) {
19083
+ throw new DevLeadBoardError(`note "${filter.note}" was not found`, "BOARD_NOTE_NOT_FOUND");
19084
+ }
19085
+ selected = [metadata2];
19086
+ }
19087
+ const bodies = /* @__PURE__ */ new Map();
19088
+ if (currentProject !== void 0) {
19089
+ for (const metadata2 of selected) bodies.set(metadata2.id, await this.readBody(currentProject, metadata2));
19090
+ }
19091
+ let index = current;
19092
+ if (currentProject !== void 0 && selected.some((metadata2) => {
19093
+ const body = bodies.get(metadata2.id);
19094
+ return metadata2.bytes !== body.buffer.length || metadata2.updatedAt !== body.updatedAt;
19095
+ })) {
19096
+ const next = structuredClone(current);
19097
+ const project2 = next.projects.find((candidate) => candidate.id === boardProject.id);
19098
+ for (const metadata2 of project2.notes) {
19099
+ const body = bodies.get(metadata2.id);
19100
+ if (body === void 0) continue;
19101
+ metadata2.bytes = body.buffer.length;
19102
+ metadata2.updatedAt = body.updatedAt;
19103
+ }
19104
+ next.revision = current.revision + 1;
19105
+ next.updatedAt = new Date(this.now()).toISOString();
19106
+ index = this.validateNext(next);
19107
+ await this.commitIndex(filePath, index);
19108
+ }
19109
+ const project = index.projects.find((candidate) => candidate.id === boardProject.id);
19110
+ const view = { id: boardProject.id, directory: projectDirectory(boardProject.id, index) };
19111
+ if (filter.note === void 0) {
19112
+ return {
19113
+ revision: index.revision,
19114
+ updatedAt: index.updatedAt,
19115
+ project: view,
19116
+ notes: (project?.notes ?? []).map((metadata2) => this.publicMetadata(root, project, metadata2))
19117
+ };
19118
+ }
19119
+ const metadata = project.notes.find((note) => note.id === filter.note);
19120
+ return boundNoteRead({
19121
+ revision: index.revision,
19122
+ updatedAt: index.updatedAt,
19123
+ project: view,
19124
+ note: {
19125
+ ...this.publicMetadata(root, project, metadata),
19126
+ content: bodies.get(metadata.id).content
19127
+ }
19128
+ });
19129
+ });
19130
+ } catch (error51) {
19131
+ if (isDevLeadBoardError(error51)) throw error51;
19132
+ if (isWriteIoError2(error51)) throw ioError("read notes", filePath, error51);
19133
+ throw error51;
19134
+ }
19135
+ }
19136
+ publicMetadata(root, project, metadata) {
19137
+ return { ...structuredClone(metadata), absolutePath: noteFilePath(root, project, metadata) };
19138
+ }
19139
+ /** Serialize Host calls, then use the index file's cross-process writer lock for each mutation. */
19140
+ async write(patch, signal) {
19141
+ this.requireRoot();
19142
+ validateWriteShape(patch);
19143
+ signal?.throwIfAborted();
19144
+ const operation = this.writeTail.then(() => this.writeLocked(patch, signal));
19145
+ this.writeTail = operation.catch(() => void 0);
19146
+ return operation;
19147
+ }
19148
+ async writeLocked(patch, signal) {
19149
+ const root = this.requireRoot();
19150
+ const filePath = this.requireIndexPath();
19151
+ try {
19152
+ const boardProject = await this.board.resolveProject(patch.project);
19153
+ await mkdir2(root, { recursive: true, mode: 448 });
19154
+ return await withFileLock2(filePath, async () => {
19155
+ signal?.throwIfAborted();
19156
+ const current = await this.current();
19157
+ if (patch.expectedRevision !== void 0 && current.revision !== patch.expectedRevision) {
19158
+ throw new DevLeadBoardError(
19159
+ `notes index revision conflict: expected r${patch.expectedRevision}, current r${current.revision}`,
19160
+ "BOARD_REVISION_CONFLICT",
19161
+ [{ pointer: "/revision", message: `expected ${patch.expectedRevision}, current ${current.revision}` }]
19162
+ );
19163
+ }
19164
+ const timestamp = new Date(this.now()).toISOString();
19165
+ const next = structuredClone(current);
19166
+ let project = next.projects.find((candidate) => candidate.id === boardProject.id);
19167
+ if (patch.operation === "create") {
19168
+ if (project === void 0) {
19169
+ project = { id: boardProject.id, directory: projectDirectory(boardProject.id, next), notes: [] };
19170
+ next.projects.push(project);
19171
+ }
19172
+ return await this.createNote(root, filePath, current, next, project, patch, timestamp);
19173
+ }
19174
+ if (project === void 0) throw new DevLeadBoardError(`note "${patch.note ?? ""}" was not found`, "BOARD_NOTE_NOT_FOUND");
19175
+ const metadata = project.notes.find((note) => note.id === patch.note);
19176
+ if (metadata === void 0) {
19177
+ throw new DevLeadBoardError(`note "${patch.note ?? ""}" was not found`, "BOARD_NOTE_NOT_FOUND");
19178
+ }
19179
+ if (patch.operation === "delete") {
19180
+ return await this.deleteNote(root, filePath, current, next, project, metadata, timestamp);
19181
+ }
19182
+ return await this.changeMetadata(root, filePath, current, next, project, metadata, patch);
19183
+ }, signal === void 0 ? {} : { signal });
19184
+ } catch (error51) {
19185
+ if (isDevLeadBoardError(error51)) throw error51;
19186
+ if (isWriteIoError2(error51)) throw ioError("write notes", filePath, error51);
19187
+ throw error51;
19188
+ }
19189
+ }
19190
+ async createNote(root, filePath, current, next, project, patch, timestamp) {
19191
+ let id = patch.note;
19192
+ if (id === void 0) {
19193
+ for (let attempt = 0; attempt < 4; attempt += 1) {
19194
+ const candidate = this.randomUUID();
19195
+ if (!project.notes.some((note) => note.id === candidate)) {
19196
+ id = candidate;
19197
+ break;
19198
+ }
19199
+ }
19200
+ if (id === void 0) throw invalid("could not allocate a unique note id", "/note");
19201
+ parseIndex({
19202
+ ...emptyIndex(),
19203
+ projects: [{ id: "validation", directory: project.directory, notes: [{
19204
+ id,
19205
+ title: "validation",
19206
+ summary: "",
19207
+ updatedAt: EMPTY_TIMESTAMP,
19208
+ bytes: 0,
19209
+ path: `${project.directory}/${id}.md`
19210
+ }] }]
19211
+ });
19212
+ }
19213
+ if (project.notes.some((note) => note.id === id)) {
19214
+ throw invalid(`note "${id}" already exists in project "${project.id}"`, "/note");
19215
+ }
19216
+ if (project.notes.length >= DEVLEAD_NOTES_MAX_PER_PROJECT) {
19217
+ throw limit(`project "${project.id}" already has ${DEVLEAD_NOTES_MAX_PER_PROJECT} notes`, "/notes");
19218
+ }
19219
+ const content = patch.content ?? "";
19220
+ const metadata = {
19221
+ id,
19222
+ title: patch.title.trim(),
19223
+ summary: patch.summary ?? "",
19224
+ updatedAt: timestamp,
19225
+ bytes: Buffer.byteLength(content, "utf8"),
19226
+ path: `${project.directory}/${id}.md`
19227
+ };
19228
+ project.notes.push(metadata);
19229
+ next.revision = current.revision + 1;
19230
+ next.updatedAt = timestamp;
19231
+ const validated = this.validateNext(next);
19232
+ const validatedProject = validated.projects.find((candidate) => candidate.id === project.id);
19233
+ const validatedNote = validatedProject.notes.find((note) => note.id === id);
19234
+ await this.writeBodyAndCommit(root, filePath, validatedProject, validatedNote, content, void 0, validated);
19235
+ return {
19236
+ revision: validated.revision,
19237
+ updatedAt: validated.updatedAt,
19238
+ project: { id: project.id, directory: project.directory },
19239
+ note: this.publicMetadata(root, validatedProject, validatedNote),
19240
+ operation: "create",
19241
+ changed: true
19242
+ };
19243
+ }
19244
+ async changeMetadata(root, filePath, current, next, project, metadata, patch) {
19245
+ const title = patch.title === void 0 ? metadata.title : patch.title.trim();
19246
+ if (title.length === 0) throw invalid("title must not be empty", "/title");
19247
+ const summary = patch.summary ?? metadata.summary;
19248
+ const changed = title !== metadata.title || summary !== metadata.summary;
19249
+ if (!changed) {
19250
+ return {
19251
+ revision: current.revision,
19252
+ updatedAt: current.updatedAt,
19253
+ project: { id: project.id, directory: project.directory },
19254
+ note: this.publicMetadata(root, project, metadata),
19255
+ operation: patch.operation,
19256
+ changed: false
19257
+ };
19258
+ }
19259
+ Object.assign(metadata, { title, summary });
19260
+ next.revision = current.revision + 1;
19261
+ next.updatedAt = new Date(this.now()).toISOString();
19262
+ const validated = this.validateNext(next);
19263
+ const validatedProject = validated.projects.find((candidate) => candidate.id === project.id);
19264
+ const validatedNote = validatedProject.notes.find((note) => note.id === metadata.id);
19265
+ await this.commitIndex(filePath, validated);
19266
+ return {
19267
+ revision: validated.revision,
19268
+ updatedAt: validated.updatedAt,
19269
+ project: { id: project.id, directory: project.directory },
19270
+ note: this.publicMetadata(root, validatedProject, validatedNote),
19271
+ operation: patch.operation,
19272
+ changed: true
19273
+ };
19274
+ }
19275
+ async deleteNote(root, filePath, current, next, project, metadata, timestamp) {
19276
+ project.notes = project.notes.filter((note) => note.id !== metadata.id);
19277
+ if (project.notes.length === 0) next.projects = next.projects.filter((candidate) => candidate.id !== project.id);
19278
+ next.revision = current.revision + 1;
19279
+ next.updatedAt = timestamp;
19280
+ const validated = this.validateNext(next);
19281
+ await this.commitIndex(filePath, validated);
19282
+ try {
19283
+ await rm(noteFilePath(root, project, metadata), { force: true });
19284
+ } catch (error51) {
19285
+ this.logger.warn(`devlead: deleted note ${metadata.id} from the index but could not remove its orphan body: ${errorMessage3(error51)}`);
19286
+ }
19287
+ return {
19288
+ revision: validated.revision,
19289
+ updatedAt: validated.updatedAt,
19290
+ project: { id: project.id, directory: project.directory },
19291
+ note: this.publicMetadata(root, project, metadata),
19292
+ operation: "delete",
19293
+ changed: true,
19294
+ deleted: true
19295
+ };
19296
+ }
19297
+ validateNext(next) {
19298
+ const validated = parseIndex(next);
19299
+ const content = `${JSON.stringify(validated, null, 2)}
19300
+ `;
19301
+ const bytes = Buffer.byteLength(content, "utf8");
19302
+ if (bytes > DEVLEAD_NOTES_INDEX_MAX_BYTES) {
19303
+ throw limit(`notes index update would exceed ${DEVLEAD_NOTES_INDEX_MAX_BYTES} bytes (${bytes})`, "");
19304
+ }
19305
+ return validated;
19306
+ }
19307
+ async writeBodyAndCommit(root, filePath, project, metadata, content, previous, validated) {
19308
+ const bodyPath = noteFilePath(root, project, metadata);
19309
+ await mkdir2(dirname2(bodyPath), { recursive: true, mode: 448 });
19310
+ await writeFileAtomic2(bodyPath, content, { mode: 384, dirMode: 448 });
19311
+ try {
19312
+ await this.commitIndex(filePath, validated);
19313
+ } catch (error51) {
19314
+ try {
19315
+ if (previous === void 0) await rm(bodyPath, { force: true });
19316
+ else await writeFileAtomic2(bodyPath, previous, { mode: 384, dirMode: 448 });
19317
+ } catch (rollbackError) {
19318
+ this.logger.warn(
19319
+ `devlead: notes index commit failed and body rollback also failed for ${metadata.id}: ${errorMessage3(rollbackError)}`
19320
+ );
19321
+ }
19322
+ throw error51;
19323
+ }
19324
+ }
19325
+ async commitIndex(filePath, validated) {
19326
+ await writeFileAtomic2(filePath, `${JSON.stringify(validated, null, 2)}
19327
+ `, { mode: 384, dirMode: 448 });
19328
+ this.cache = validated;
19329
+ this.lastError = void 0;
19330
+ }
19331
+ /** Read a stable native-edited body; reconciliation, never body rewriting, handles stale metadata. */
19332
+ async readBody(project, metadata) {
19333
+ const root = this.requireRoot();
19334
+ const path = noteFilePath(root, project, metadata);
19335
+ try {
19336
+ for (let attempt = 0; attempt < READ_ATTEMPTS; attempt += 1) {
19337
+ const before = await stat3(path);
19338
+ if (before.size > DEVLEAD_NOTES_NOTE_MAX_BYTES) {
19339
+ throw limit(`note "${metadata.id}" exceeds ${DEVLEAD_NOTES_NOTE_MAX_BYTES} bytes (${before.size})`, "/note");
19340
+ }
19341
+ const buffer = await readFile2(path);
19342
+ const after = await stat3(path);
19343
+ if (before.mtimeMs !== after.mtimeMs || before.size !== after.size || before.ino !== after.ino || buffer.length !== after.size) continue;
19344
+ return {
19345
+ buffer,
19346
+ content: decodeUtf8(buffer, `note "${metadata.id}"`),
19347
+ updatedAt: after.mtime.toISOString()
19348
+ };
19349
+ }
19350
+ throw ioError("read stable note", path, new Error("file changed repeatedly; retry"));
19351
+ } catch (error51) {
19352
+ if (isDevLeadBoardError(error51)) throw error51;
19353
+ if (errorCode2(error51) === "ENOENT") {
19354
+ throw new DevLeadBoardError(
19355
+ `note "${metadata.id}" is indexed but its Markdown body is missing`,
19356
+ "BOARD_NOTE_NOT_FOUND"
19357
+ );
19358
+ }
19359
+ if (isWriteIoError2(error51)) throw ioError("read note", path, error51);
19360
+ throw error51;
19361
+ }
19362
+ }
19363
+ };
19364
+
17687
19365
  // packages/devlead/src/notification.ts
17688
19366
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
17689
19367
  import {
@@ -19649,7 +21327,7 @@ async function readSessionFacts(deps, ids) {
19649
21327
  }
19650
21328
  return { known, workspaces, archived };
19651
21329
  }
19652
- function rankSessionIds(deps, ids, known, limit) {
21330
+ function rankSessionIds(deps, ids, known, limit2) {
19653
21331
  const ranked = ids.map((id) => ({
19654
21332
  id,
19655
21333
  watched: deps.isWatched(id),
@@ -19661,7 +21339,7 @@ function rankSessionIds(deps, ids, known, limit) {
19661
21339
  if (left.running !== right.running) return left.running ? -1 : 1;
19662
21340
  return right.createdAt - left.createdAt || left.id.localeCompare(right.id);
19663
21341
  });
19664
- return ranked.slice(0, Math.max(1, limit)).map((entry) => entry.id);
21342
+ return ranked.slice(0, Math.max(1, limit2)).map((entry) => entry.id);
19665
21343
  }
19666
21344
  function lastAssistantExcerpt(events) {
19667
21345
  for (let index = events.length - 1; index >= 0; index -= 1) {
@@ -19870,9 +21548,9 @@ var REHYDRATION_FINALIZE_TIMEOUT_MS = 5e3;
19870
21548
  var MAX_FINALIZE_LISTING_REFRESHES = 2;
19871
21549
  var DEFAULT_SUPERVISION_DEGRADED_REASON = "the cold-lead supervisor index is incomplete";
19872
21550
  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`
21551
+ "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)",
21552
+ "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",
21553
+ "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
21554
  };
19877
21555
  var REHYDRATION_DEGRADED_CAUSES = {
19878
21556
  list: "the persisted Session corpus could not be listed",
@@ -19905,7 +21583,8 @@ var Config = z2.object({
19905
21583
  maxListedSessions: z2.number().step(1).min(1).default(200),
19906
21584
  wakeColdSession: z2.boolean().default(true),
19907
21585
  defaultAgentPreset: z2.string().default(""),
19908
- questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS)
21586
+ questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS),
21587
+ boardPath: z2.string().default("")
19909
21588
  });
19910
21589
  function resolveConfig(config2) {
19911
21590
  const notificationBatchMs = config2.notificationBatchMs ?? 400;
@@ -19932,6 +21611,12 @@ function resolveConfig(config2) {
19932
21611
  if (!Number.isSafeInteger(questionTtlMs) || questionTtlMs < 0) {
19933
21612
  throw new TypeError("questionTtlMs must be a non-negative safe integer");
19934
21613
  }
21614
+ const boardPath = config2.boardPath ?? "";
21615
+ if (typeof boardPath !== "string") throw new TypeError("boardPath must be a string");
21616
+ const trimmedBoardPath = boardPath.trim();
21617
+ if (trimmedBoardPath.length > 0 && !isAbsolute4(trimmedBoardPath)) {
21618
+ throw new TypeError("boardPath must be an absolute path");
21619
+ }
19935
21620
  return {
19936
21621
  notificationBatchMs,
19937
21622
  actionRequiredBatchMs,
@@ -19939,7 +21624,8 @@ function resolveConfig(config2) {
19939
21624
  maxListedSessions,
19940
21625
  wakeColdSession,
19941
21626
  defaultAgentPreset: defaultAgentPreset.trim().length === 0 ? void 0 : defaultAgentPreset.trim(),
19942
- questionTtlMs
21627
+ questionTtlMs,
21628
+ ...trimmedBoardPath.length === 0 ? {} : { boardPath: trimmedBoardPath }
19943
21629
  };
19944
21630
  }
19945
21631
  function remoteCodeOf(error51) {
@@ -19953,12 +21639,12 @@ function isSessionNotFoundError(error51) {
19953
21639
  const message = error51 instanceof Error ? error51.message : String(error51);
19954
21640
  return /not found|does not exist|unknown session|SESSION_NOT_FOUND/iu.test(message);
19955
21641
  }
19956
- function listLimit(limit, maximum) {
19957
- if (limit === void 0) return maximum;
19958
- if (!Number.isSafeInteger(limit) || limit < 1) {
21642
+ function listLimit(limit2, maximum) {
21643
+ if (limit2 === void 0) return maximum;
21644
+ if (!Number.isSafeInteger(limit2) || limit2 < 1) {
19959
21645
  throw new DevLeadError("limit must be a positive safe integer", "DEVLEAD_INVALID_INPUT");
19960
21646
  }
19961
- return Math.min(limit, maximum);
21647
+ return Math.min(limit2, maximum);
19962
21648
  }
19963
21649
  function workspacePathFailure(error51, path) {
19964
21650
  const errno = error51?.code;
@@ -20070,12 +21756,40 @@ function validatedQuestions(value, kind) {
20070
21756
  };
20071
21757
  });
20072
21758
  }
21759
+ function devLeadBoardStartErrorOf(error51) {
21760
+ if (isDevLeadBoardError(error51)) return { code: error51.code, message: error51.message };
21761
+ return { code: "BOARD_IO_ERROR", message: thrownMessage(error51) };
21762
+ }
20073
21763
  var DevLeadService = class extends Service {
20074
21764
  static inject = ["agents", "sessions", "sessionProjections"];
20075
21765
  /** Loader schema, applied by the Loader before construction. */
20076
21766
  static Config = Config;
20077
21767
  /** Validated deployment configuration. */
20078
21768
  resolved;
21769
+ /**
21770
+ * Current project board store. It belongs to the one active lead Session (or
21771
+ * its configured override); with no active lead this is a disabled store
21772
+ * whose reads/writes report BOARD_DISABLED and whose summary is empty.
21773
+ */
21774
+ boardStore;
21775
+ /** Markdown notes store paired with {@link boardStore}'s exact path and lifecycle. */
21776
+ notesStore;
21777
+ /** Active lead Session whose workspace owns {@link boardStore}, when enabled. */
21778
+ boardLeadSessionIdValue;
21779
+ /** Whether the current board path comes from the deployment Config override. */
21780
+ boardPathOverrideValue = false;
21781
+ /** Latest board start failure; the rest of the service keeps serving without a board. */
21782
+ boardStartErrorValue;
21783
+ /** Why the board is disabled right now, or undefined while a store is active. */
21784
+ boardDisabledReasonValue;
21785
+ /** Serializes store swaps so two lead changes can never interleave one store. */
21786
+ boardSyncTail = Promise.resolve();
21787
+ /**
21788
+ * Original workspace root of each known lead Session, including cold ones
21789
+ * recovered from the persisted corpus (their header is not live in the
21790
+ * Session store, so the board path needs this cache).
21791
+ */
21792
+ leadWorkspaceRoots = /* @__PURE__ */ new Map();
20079
21793
  /** Awaited registration of the `devLead` projection unit. */
20080
21794
  projectionHandle;
20081
21795
  /** Host-driven projections replacing deprecated synchronous event readers. */
@@ -20107,6 +21821,8 @@ var DevLeadService = class extends Service {
20107
21821
  liveAttachFailure = false;
20108
21822
  /** Human-readable cause of the current degraded supervision state. */
20109
21823
  supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
21824
+ /** Latest concrete Session/path/cause; retained when a later retry-cap warning is emitted. */
21825
+ supervisionDegradedDetail;
20110
21826
  /** Invalidates every in-flight scan application; bumped by reset and service recomposition. */
20111
21827
  rehydrationEpoch = 0;
20112
21828
  /** Whether the current attempt reached the corpus scan (early live-only returns do not). */
@@ -20379,6 +22095,8 @@ var DevLeadService = class extends Service {
20379
22095
  constructor(ctx, config2 = {}) {
20380
22096
  super(ctx, "devLead");
20381
22097
  this.resolved = resolveConfig(config2);
22098
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
22099
+ this.notesStore = new DevLeadBoardNotesStore(void 0, this.boardStore, this.ctx.logger);
20382
22100
  }
20383
22101
  async [Service.init]() {
20384
22102
  initializeRecordApi(this.ctx.logger);
@@ -20427,7 +22145,13 @@ var DevLeadService = class extends Service {
20427
22145
  opening?.catch(() => void 0),
20428
22146
  idempotencyOpening?.catch(() => void 0)
20429
22147
  ]);
20430
- await Promise.all([this.outbox?.close(), this.idempotencyStore?.close()]);
22148
+ await this.boardSyncTail.catch(() => void 0);
22149
+ await Promise.all([
22150
+ this.boardStore.close(),
22151
+ this.notesStore.close(),
22152
+ this.outbox?.close(),
22153
+ this.idempotencyStore?.close()
22154
+ ]);
20431
22155
  })();
20432
22156
  };
20433
22157
  }.bind(this), "devlead: cold rehydration");
@@ -20511,6 +22235,7 @@ var DevLeadService = class extends Service {
20511
22235
  knownActive: this.recoveredActive
20512
22236
  });
20513
22237
  this.recoveredActive = [];
22238
+ await this.syncBoardToActiveLead();
20514
22239
  await this.replayOutbox();
20515
22240
  this.initialized = true;
20516
22241
  }
@@ -21111,6 +22836,7 @@ var DevLeadService = class extends Service {
21111
22836
  this.rehydrated = true;
21112
22837
  this.corpusWasProven = true;
21113
22838
  this.supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
22839
+ this.supervisionDegradedDetail = void 0;
21114
22840
  this.trustedBindings = this.currentCorpusBindings();
21115
22841
  this.observedBindings = this.trustedBindings;
21116
22842
  this.coldScan = void 0;
@@ -21326,6 +23052,7 @@ var DevLeadService = class extends Service {
21326
23052
  if (this.disposed) return;
21327
23053
  this.invalidateCorpusProof();
21328
23054
  this.supervisionDegradedReason = reason;
23055
+ this.supervisionDegradedDetail = void 0;
21329
23056
  this.requestFreshRehydration();
21330
23057
  this.armRehydrationRetry(this.ctx.get("sessionQuery") !== void 0);
21331
23058
  void this.rehydrateFromPersistence();
@@ -21406,8 +23133,8 @@ var DevLeadService = class extends Service {
21406
23133
  * states and exhausted retry budgets are recoverable without a Host restart:
21407
23134
  * the probe re-lists and rescans once every {@link DEGRADED_REHYDRATION_PROBE_MS}.
21408
23135
  * 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.
23136
+ * after the transient cause clears, a read-only recovery succeeds, a human
23137
+ * resets corrupt DevLead state, or the Host restarts. An explicit reset recovers immediately.
21411
23138
  * @param reason - stable warning key and degraded-state cause.
21412
23139
  */
21413
23140
  scheduleRehydrationProbe(reason) {
@@ -21470,8 +23197,10 @@ var DevLeadService = class extends Service {
21470
23197
  this.rehydrationLifecycle = { queryReady, disposers };
21471
23198
  }
21472
23199
  /** Emit each rehydration warning reason once per service epoch and track its cause. */
21473
- warnRehydration(reason, message) {
23200
+ warnRehydration(reason, message, detail) {
21474
23201
  this.supervisionDegradedReason = REHYDRATION_DEGRADED_CAUSES[reason] ?? message;
23202
+ if (detail !== void 0) this.supervisionDegradedDetail = detail;
23203
+ else if (reason !== "retry-cap" && reason !== "corrupt-terminal") this.supervisionDegradedDetail = void 0;
21475
23204
  if (this.rehydrationWarnings.has(reason)) return;
21476
23205
  this.rehydrationWarnings.add(reason);
21477
23206
  this.ctx.logger.warn(message);
@@ -21507,6 +23236,299 @@ var DevLeadService = class extends Service {
21507
23236
  return recordApiStatus();
21508
23237
  }
21509
23238
  // ---------------------------------------------------------------------------
23239
+ // Project board
23240
+ // ---------------------------------------------------------------------------
23241
+ /** Current project board store; disabled when no lead/workspace owns one. */
23242
+ get board() {
23243
+ return this.boardStore;
23244
+ }
23245
+ /** Current notes store, rooted at `dirname(board.path)/notes` when enabled. */
23246
+ get notes() {
23247
+ return this.notesStore;
23248
+ }
23249
+ /** Active lead Session id whose workspace owns the current board, when enabled. */
23250
+ get boardLeadSessionId() {
23251
+ return this.boardLeadSessionIdValue;
23252
+ }
23253
+ /** Whether the current board path comes from the deployment Config override. */
23254
+ get boardPathOverride() {
23255
+ return this.boardPathOverrideValue;
23256
+ }
23257
+ /**
23258
+ * Latest project-board start failure, if any.
23259
+ *
23260
+ * A degraded board keeps DevLead itself loaded: tools then report the real
23261
+ * filesystem failure as a structured board error instead of the plugin
23262
+ * refusing to activate.
23263
+ */
23264
+ get boardStartError() {
23265
+ return this.boardStartErrorValue;
23266
+ }
23267
+ /**
23268
+ * Why the project board is currently disabled, when it is.
23269
+ *
23270
+ * `missing-workspace` reports a lead whose recorded original workspace root is
23271
+ * gone (or is no longer a directory): the board stays disabled with one
23272
+ * warning and the Host never recreates the workspace. An explicit deployment
23273
+ * `boardPath` override bypasses this check and keeps the existing pre-create
23274
+ * semantics. Undefined while a board store is active.
23275
+ */
23276
+ get boardDisabledReason() {
23277
+ return this.boardDisabledReasonValue;
23278
+ }
23279
+ /**
23280
+ * Resolve the calling lead's board file and hand it a tool read. Only the
23281
+ * unique active lead may reach the store; with no active lead/workspace the
23282
+ * call reports BOARD_DISABLED.
23283
+ * @param agent - calling live Agent.
23284
+ * @param filter - bounded project/task filtering.
23285
+ * @returns the bounded read result.
23286
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_ENABLED` for a non-mode Agent.
23287
+ * @throws {@link DevLeadBoardError} `BOARD_DISABLED` when the caller is not
23288
+ * the active lead or its workspace records no board location.
23289
+ */
23290
+ async readBoard(agent, filter = {}) {
23291
+ if (!this.isEnabled(agent)) {
23292
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
23293
+ }
23294
+ this.requireActiveBoardLead(agent);
23295
+ return this.boardStore.read(filter);
23296
+ }
23297
+ /**
23298
+ * Dynamic board summary for one prompt-assembly Agent.
23299
+ *
23300
+ * Returns the cache-only text only when the caller is both an enabled lead
23301
+ * and the owner of the current store; a duplicate or non-owner enabled Agent
23302
+ * gets an empty summary instead of another workspace's board.
23303
+ * @param agent - Agent whose turn is being assembled.
23304
+ * @returns the bounded board summary, or an empty string.
23305
+ */
23306
+ boardSummaryFor(agent) {
23307
+ if (!this.isEnabled(agent)) return "";
23308
+ if (this.boardLeadSessionIdValue !== String(agent.id)) return "";
23309
+ return this.boardStore.summary(this.notesStore.summaryIndex());
23310
+ }
23311
+ /** Read one active-lead project's note metadata or one complete Markdown note. */
23312
+ async readBoardNote(agent, filter) {
23313
+ if (!this.isEnabled(agent)) {
23314
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
23315
+ }
23316
+ this.requireActiveBoardLead(agent);
23317
+ return this.notesStore.read(filter);
23318
+ }
23319
+ /** Apply one logical note mutation for the active lead; no caller path is accepted. */
23320
+ async writeBoardNote(agent, patch, signal) {
23321
+ if (!this.isEnabled(agent)) {
23322
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
23323
+ }
23324
+ this.requireActiveBoardLead(agent);
23325
+ return this.notesStore.write(patch, signal);
23326
+ }
23327
+ /** Reject a board operation whose caller does not own the current store. */
23328
+ requireActiveBoardLead(agent) {
23329
+ if (this.boardLeadSessionIdValue === String(agent.id) && this.boardStore.path !== void 0) return;
23330
+ throw new DevLeadBoardError(
23331
+ "the DevLead project board is not active for the calling lead: no active lead workspace currently owns a board file",
23332
+ "BOARD_DISABLED"
23333
+ );
23334
+ }
23335
+ /** Serialize one active-lead → board synchronization. */
23336
+ syncBoardToActiveLead() {
23337
+ const run = this.boardSyncTail.then(() => this.applyActiveLeadBoard());
23338
+ this.boardSyncTail = run.catch(() => void 0);
23339
+ return run;
23340
+ }
23341
+ /** Apply the current lead identity to the board store (serialized). */
23342
+ async applyActiveLeadBoard() {
23343
+ if (this.disposed) return;
23344
+ const sessionId = this.activeSessionId;
23345
+ if (sessionId === void 0) {
23346
+ await this.swapBoardStore(void 0, void 0);
23347
+ return;
23348
+ }
23349
+ await this.swapBoardStore(sessionId, this.leadWorkspaceRootOf(sessionId));
23350
+ }
23351
+ /** Original workspace root for one lead: live header first, cached cold header second. */
23352
+ leadWorkspaceRootOf(sessionId) {
23353
+ const live = this.ctx.sessions.get(toSessionId3(sessionId));
23354
+ const fromLive = live?.header.cwd;
23355
+ if (fromLive !== void 0 && fromLive.trim().length > 0) {
23356
+ this.leadWorkspaceRoots.set(sessionId, fromLive);
23357
+ return fromLive;
23358
+ }
23359
+ return this.leadWorkspaceRoots.get(sessionId);
23360
+ }
23361
+ /** Cache one lead's original workspace root (cold leads are not in the live store). */
23362
+ rememberLeadWorkspaceRoot(sessionId, cwd) {
23363
+ if (cwd === void 0 || cwd.trim().length === 0) this.leadWorkspaceRoots.delete(sessionId);
23364
+ else this.leadWorkspaceRoots.set(sessionId, cwd);
23365
+ }
23366
+ /**
23367
+ * Point the service at the board file of one lead, releasing any previous
23368
+ * store/watcher.
23369
+ *
23370
+ * The path is the Config override when configured, otherwise the lead's
23371
+ * original workspace root plus `.dsh/devlead/board.json`. A derived path is
23372
+ * used only while that workspace root still exists as a directory: a cold
23373
+ * lead whose recorded root was deleted or moved must never make the Host
23374
+ * recreate the workspace (with just `.dsh/devlead`) to host the board file.
23375
+ * The same resolved file keeps its store (so a lead switch inside one
23376
+ * workspace does not churn the watcher); a changed path starts the new store
23377
+ * before the old one is closed, so an in-flight read never sees a
23378
+ * half-swapped service. A start failure is recorded and logged but never
23379
+ * rejects: the store is kept so its later operations report the real
23380
+ * filesystem failure, and the next same-path sync or path switch retries it.
23381
+ * @param sessionId - active lead identity, or undefined when disabled.
23382
+ * @param workspaceRoot - that lead's original workspace root, when known.
23383
+ */
23384
+ async swapBoardStore(sessionId, workspaceRoot) {
23385
+ const resolution = sessionId === void 0 ? { kind: "disabled", reason: "no-workspace" } : resolveDevLeadBoardPath({
23386
+ ...this.resolved.boardPath === void 0 ? {} : { override: this.resolved.boardPath },
23387
+ ...workspaceRoot === void 0 ? {} : { cwd: workspaceRoot }
23388
+ });
23389
+ if (resolution.kind === "disabled") {
23390
+ if (resolution.reason === "relative-workspace") {
23391
+ this.ctx.logger.warn(
23392
+ `devlead: Session "${sessionId ?? ""}" records a relative workspace root (${workspaceRoot ?? ""}); the project board stays disabled until it has an absolute workspace root`
23393
+ );
23394
+ }
23395
+ await this.disableBoardStore(resolution.reason);
23396
+ return;
23397
+ }
23398
+ const nextPath = resolution.path;
23399
+ const nextOverride = resolution.source === "override";
23400
+ if (resolution.source === "workspace" && !await this.workspaceRootExists(workspaceRoot)) {
23401
+ this.ctx.logger.warn(
23402
+ `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.`
23403
+ );
23404
+ await this.disableBoardStore("missing-workspace");
23405
+ return;
23406
+ }
23407
+ const previous = this.boardStore;
23408
+ const previousNotes = this.notesStore;
23409
+ if (previous.path === nextPath) {
23410
+ this.boardLeadSessionIdValue = sessionId;
23411
+ this.boardPathOverrideValue = nextOverride;
23412
+ this.boardDisabledReasonValue = void 0;
23413
+ if (this.boardStartErrorValue !== void 0) {
23414
+ await this.retryBoardStart(previous, nextPath);
23415
+ }
23416
+ return;
23417
+ }
23418
+ const next = new DevLeadBoardStore(nextPath, this.ctx.logger);
23419
+ const nextNotes = new DevLeadBoardNotesStore(nextPath, next, this.ctx.logger);
23420
+ let startError;
23421
+ try {
23422
+ await next.start();
23423
+ } catch (error51) {
23424
+ startError = devLeadBoardStartErrorOf(error51);
23425
+ this.logBoardStartFailure(nextPath, startError);
23426
+ }
23427
+ try {
23428
+ await nextNotes.start();
23429
+ } catch (error51) {
23430
+ const notesError = devLeadBoardStartErrorOf(error51);
23431
+ startError ??= notesError;
23432
+ this.logBoardStartFailure(nextNotes.indexPath ?? nextPath, notesError);
23433
+ }
23434
+ this.boardStore = next;
23435
+ this.notesStore = nextNotes;
23436
+ this.boardLeadSessionIdValue = sessionId;
23437
+ this.boardPathOverrideValue = nextOverride;
23438
+ this.boardDisabledReasonValue = void 0;
23439
+ this.boardStartErrorValue = startError;
23440
+ await Promise.all([this.closeBoardStore(previous), this.closeNotesStore(previousNotes)]);
23441
+ }
23442
+ /**
23443
+ * Whether one derived board's workspace root still exists as a directory.
23444
+ *
23445
+ * Any stat failure (missing, not a directory, unreadable) is treated as
23446
+ * unusable: the board is disabled instead of attempting a write under a root
23447
+ * the Host cannot verify.
23448
+ * @param workspaceRoot - the lead's recorded original workspace root.
23449
+ * @returns whether `start()` may safely prepare the board parent under it.
23450
+ */
23451
+ async workspaceRootExists(workspaceRoot) {
23452
+ if (workspaceRoot === void 0 || workspaceRoot.trim().length === 0) return false;
23453
+ try {
23454
+ return (await stat4(workspaceRoot)).isDirectory();
23455
+ } catch {
23456
+ return false;
23457
+ }
23458
+ }
23459
+ /** Retry `start()` on the current same-path store, keeping the degraded record on failure. */
23460
+ async retryBoardStart(store, path) {
23461
+ let startError;
23462
+ try {
23463
+ await store.start();
23464
+ } catch (error51) {
23465
+ startError = devLeadBoardStartErrorOf(error51);
23466
+ this.logBoardStartFailure(path, startError);
23467
+ }
23468
+ try {
23469
+ await this.notesStore.start();
23470
+ } catch (error51) {
23471
+ const notesError = devLeadBoardStartErrorOf(error51);
23472
+ startError ??= notesError;
23473
+ this.logBoardStartFailure(this.notesStore.indexPath ?? path, notesError);
23474
+ }
23475
+ this.boardStartErrorValue = startError;
23476
+ }
23477
+ /** Log one board degradation without failing the surrounding service. */
23478
+ logBoardStartFailure(path, failure) {
23479
+ this.ctx.logger.warn(
23480
+ `devlead: project board at ${path} is degraded and DevLead stays loaded: ${failure.code}: ${failure.message}`
23481
+ );
23482
+ }
23483
+ /** Release any current board store and expose why the board is disabled. */
23484
+ async disableBoardStore(reason) {
23485
+ const previous = this.boardStore;
23486
+ const previousNotes = this.notesStore;
23487
+ this.boardLeadSessionIdValue = void 0;
23488
+ this.boardPathOverrideValue = false;
23489
+ this.boardStartErrorValue = void 0;
23490
+ this.boardDisabledReasonValue = reason;
23491
+ if (previous.path !== void 0) {
23492
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
23493
+ this.notesStore = new DevLeadBoardNotesStore(void 0, this.boardStore, this.ctx.logger);
23494
+ await Promise.all([this.closeBoardStore(previous), this.closeNotesStore(previousNotes)]);
23495
+ }
23496
+ }
23497
+ /** Close one replaced store without letting cleanup failure break the swap. */
23498
+ async closeBoardStore(store) {
23499
+ if (store.path === void 0) return;
23500
+ try {
23501
+ await store.close();
23502
+ } catch (error51) {
23503
+ this.ctx.logger.warn(`devlead: could not close the previous project board store: ${thrownMessage(error51)}`);
23504
+ }
23505
+ }
23506
+ /** Close one replaced notes store without failing the surrounding board swap. */
23507
+ async closeNotesStore(store) {
23508
+ if (store.path === void 0) return;
23509
+ try {
23510
+ await store.close();
23511
+ } catch (error51) {
23512
+ this.ctx.logger.warn(`devlead: could not close the previous board notes store: ${thrownMessage(error51)}`);
23513
+ }
23514
+ }
23515
+ /**
23516
+ * Stamp the calling lead's identity onto one board mutation. The board file
23517
+ * path is derived from the active lead's workspace (or the Config override);
23518
+ * model callers supply only a logical patch.
23519
+ */
23520
+ async updateBoard(agent, patch, expectedRevision, signal) {
23521
+ if (!this.isEnabled(agent)) {
23522
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
23523
+ }
23524
+ this.requireActiveBoardLead(agent);
23525
+ const title = this.ctx.get("sessionTitle")?.get(agent.session)?.title ?? "DevLead";
23526
+ return this.boardStore.update({
23527
+ ...patch,
23528
+ updatedBy: { sessionId: String(agent.id), title }
23529
+ }, expectedRevision, signal);
23530
+ }
23531
+ // ---------------------------------------------------------------------------
21510
23532
  // Mode
21511
23533
  // ---------------------------------------------------------------------------
21512
23534
  /**
@@ -21577,11 +23599,18 @@ var DevLeadService = class extends Service {
21577
23599
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21578
23600
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21579
23601
  await this.discardLeadReportState(String(agent.id));
21580
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
23602
+ if (this.activeSessionId === String(agent.id)) {
23603
+ this.activeSessionId = void 0;
23604
+ await this.syncBoardToActiveLead();
23605
+ }
21581
23606
  return;
21582
23607
  }
21583
23608
  if (current.enabled === enabled) {
21584
- if (enabled) this.activeSessionId = String(agent.id);
23609
+ if (enabled) {
23610
+ this.activeSessionId = String(agent.id);
23611
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
23612
+ await this.syncBoardToActiveLead();
23613
+ }
21585
23614
  return;
21586
23615
  }
21587
23616
  if (enabled) {
@@ -21596,8 +23625,13 @@ var DevLeadService = class extends Service {
21596
23625
  appendRecordOrThrow(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
21597
23626
  await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
21598
23627
  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;
23628
+ if (enabled) {
23629
+ this.activeSessionId = String(agent.id);
23630
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
23631
+ } else if (this.activeSessionId === String(agent.id)) {
23632
+ this.activeSessionId = void 0;
23633
+ }
23634
+ await this.syncBoardToActiveLead();
21601
23635
  if (enabled) void this.replayOutbox();
21602
23636
  });
21603
23637
  }
@@ -21622,7 +23656,10 @@ var DevLeadService = class extends Service {
21622
23656
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21623
23657
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21624
23658
  await this.discardLeadReportState(String(agent.id));
21625
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
23659
+ if (this.activeSessionId === String(agent.id)) {
23660
+ this.activeSessionId = void 0;
23661
+ await this.syncBoardToActiveLead();
23662
+ }
21626
23663
  });
21627
23664
  }
21628
23665
  /**
@@ -21651,6 +23688,7 @@ var DevLeadService = class extends Service {
21651
23688
  this.rehydrationProgress = false;
21652
23689
  this.liveAttachFailure = false;
21653
23690
  this.supervisionDegradedReason = DEFAULT_SUPERVISION_DEGRADED_REASON;
23691
+ this.supervisionDegradedDetail = void 0;
21654
23692
  if (this.rehydrationRetryTimer !== void 0) {
21655
23693
  clearTimeout(this.rehydrationRetryTimer);
21656
23694
  this.rehydrationRetryTimer = void 0;
@@ -21742,7 +23780,7 @@ var DevLeadService = class extends Service {
21742
23780
  }
21743
23781
  signal?.throwIfAborted();
21744
23782
  try {
21745
- await mkdir(trimmed, { recursive: true });
23783
+ await mkdir3(trimmed, { recursive: true });
21746
23784
  } catch (mkdirError) {
21747
23785
  throw workspacePathFailure(mkdirError, trimmed);
21748
23786
  }
@@ -21822,10 +23860,10 @@ var DevLeadService = class extends Service {
21822
23860
  if (options.watchedOnly === true) ids = ids.filter((id) => deps.isWatched(id));
21823
23861
  const listingCap = options.watchedOnly === true ? Math.max(this.resolved.maxListedSessions, deps.watchedSessions.length) : this.resolved.maxListedSessions;
21824
23862
  const requestedLimit = listLimit(options.limit, listingCap);
21825
- const limit = options.watchedOnly === true ? Math.max(requestedLimit, deps.watchedSessions.length) : requestedLimit;
23863
+ const limit2 = options.watchedOnly === true ? Math.max(requestedLimit, deps.watchedSessions.length) : requestedLimit;
21826
23864
  const ranking = await sessionRankFacts(deps, ids);
21827
23865
  signal?.throwIfAborted();
21828
- const retained = rankSessionIds(deps, ids, ranking, limit);
23866
+ const retained = rankSessionIds(deps, ids, ranking, limit2);
21829
23867
  const facts = await readSessionFacts(deps, retained);
21830
23868
  return await devLeadSessionViews(deps, retained, false, facts);
21831
23869
  }
@@ -22065,8 +24103,8 @@ var DevLeadService = class extends Service {
22065
24103
  );
22066
24104
  }
22067
24105
  if (requestedModel !== void 0) await this.assertModelSelectable(requestedModel, signal);
22068
- const watch = request.watch ?? true;
22069
- const releaseWatch = watch ? this.reserveWatchSlot(agent) : void 0;
24106
+ const watch2 = request.watch ?? true;
24107
+ const releaseWatch = watch2 ? this.reserveWatchSlot(agent) : void 0;
22070
24108
  try {
22071
24109
  const workspace = await this.createTargetWorkspace(agent, request.workspace);
22072
24110
  signal?.throwIfAborted();
@@ -22093,7 +24131,7 @@ var DevLeadService = class extends Service {
22093
24131
  if (request.title !== void 0 && request.title.trim().length > 0) {
22094
24132
  this.tryRename(created.sessionId, request.title.trim());
22095
24133
  }
22096
- if (watch) {
24134
+ if (watch2) {
22097
24135
  await this.setWatching(agent, created.sessionId, true, signal, true);
22098
24136
  releaseWatch?.();
22099
24137
  }
@@ -22328,8 +24366,8 @@ var DevLeadService = class extends Service {
22328
24366
  );
22329
24367
  }
22330
24368
  this.assertSupervisionProofHeld(proof, targetId);
22331
- const watch = options.watch ?? true;
22332
- const added = watch && !watchedNow();
24369
+ const watch2 = options.watch ?? true;
24370
+ const added = watch2 && !watchedNow();
22333
24371
  if (added) await this.setWatching(agent, resolved.sessionId, true, signal);
22334
24372
  let admission;
22335
24373
  try {
@@ -22516,8 +24554,8 @@ var DevLeadService = class extends Service {
22516
24554
  notifications(agent, options = {}) {
22517
24555
  this.assertLive(agent);
22518
24556
  const state = this.strictStateOf(agent.session);
22519
- const limit = options.limit ?? 20;
22520
- const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
24557
+ const limit2 = options.limit ?? 20;
24558
+ const effective = Number.isSafeInteger(limit2) && limit2 > 0 ? limit2 : 20;
22521
24559
  return state.notifications.slice(-effective);
22522
24560
  }
22523
24561
  /** Open the durable non-answer idempotency table once, with safe fallback. */
@@ -22743,7 +24781,7 @@ var DevLeadService = class extends Service {
22743
24781
  /** Fail-closed error for an unproven or no-longer-proven supervisor index. */
22744
24782
  supervisionUnavailable(targetId) {
22745
24783
  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`,
24784
+ `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
24785
  "DEVLEAD_SESSION_UNAVAILABLE"
22748
24786
  );
22749
24787
  }
@@ -22967,8 +25005,8 @@ var DevLeadService = class extends Service {
22967
25005
  reports(agent, options = {}) {
22968
25006
  this.assertLive(agent);
22969
25007
  const state = this.strictStateOf(agent.session);
22970
- const limit = options.limit ?? 20;
22971
- const effective = Number.isSafeInteger(limit) && limit > 0 ? limit : 20;
25008
+ const limit2 = options.limit ?? 20;
25009
+ const effective = Number.isSafeInteger(limit2) && limit2 > 0 ? limit2 : 20;
22972
25010
  return state.reports.slice(-effective);
22973
25011
  }
22974
25012
  /**
@@ -23160,16 +25198,16 @@ var DevLeadService = class extends Service {
23160
25198
  * reported.
23161
25199
  *
23162
25200
  * `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.
25201
+ * log read/recovery/fold failure for any candidate actually read, is a hard
25202
+ * `DEVLEAD_SESSION_UNAVAILABLE` instead of a best-effort skip, because
25203
+ * admitting on an unverifiable candidate could create a second active lead.
23166
25204
  * Reconciliation and status remain best-effort.
23167
25205
  * @param signal - caller cancellation threaded through query reads.
23168
25206
  * @param includePersisted - whether the persisted corpus is scanned.
23169
25207
  * @param strict - whether unknown occupancy is a hard error (admission only).
23170
25208
  * @returns every enabled Session, deduplicated by id.
23171
25209
  * @throws {@link DevLeadError} `DEVLEAD_SESSION_UNAVAILABLE` when `strict` is
23172
- * set and a cache-positive candidate or the corpus listing cannot be read.
25210
+ * set and a candidate read/recovery/fold or the corpus listing cannot be proven.
23173
25211
  */
23174
25212
  async scanActiveSessions(signal, includePersisted = true, strict = false) {
23175
25213
  const active = /* @__PURE__ */ new Map();
@@ -23193,6 +25231,7 @@ var DevLeadService = class extends Service {
23193
25231
  archived: archived.has(sessionId),
23194
25232
  running: agent?.status === "running",
23195
25233
  createdAt: session.header.createdAt,
25234
+ ...session.header.cwd === void 0 ? {} : { cwd: session.header.cwd },
23196
25235
  enabledAt: 0
23197
25236
  });
23198
25237
  };
@@ -23240,14 +25279,14 @@ var DevLeadService = class extends Service {
23240
25279
  let events;
23241
25280
  let inheritedEventCount = 0;
23242
25281
  try {
23243
- const snapshot = await query.readSession(record2.header.id);
25282
+ const snapshot = await this.readColdSessionForSupervision(query, record2.header, signal);
23244
25283
  events = snapshot.events;
23245
25284
  inheritedEventCount = snapshot.inheritedEventCount;
23246
25285
  } catch (error51) {
23247
25286
  if (signal?.aborted === true) throw error51;
23248
- if (strict && prefilter === "active") {
25287
+ if (strict) {
23249
25288
  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)}`,
25289
+ `could not verify global DevLead occupancy: persisted Session "${sessionId}" could not be read (${prefilter} cache classification): ${thrownMessage(error51)}`,
23251
25290
  "DEVLEAD_SESSION_UNAVAILABLE"
23252
25291
  );
23253
25292
  }
@@ -23262,13 +25301,23 @@ var DevLeadService = class extends Service {
23262
25301
  state = applyDevLeadProjection(state, event);
23263
25302
  if (state.failure !== null) break;
23264
25303
  }
23265
- if (state.failure !== null || !state.enabled) continue;
25304
+ if (state.failure !== null) {
25305
+ if (strict) {
25306
+ throw new DevLeadError(
25307
+ `could not verify global DevLead occupancy: persisted Session "${sessionId}" has a corrupt DevLead replay (${prefilter} cache classification): ${state.failure}`,
25308
+ "DEVLEAD_SESSION_UNAVAILABLE"
25309
+ );
25310
+ }
25311
+ continue;
25312
+ }
25313
+ if (!state.enabled) continue;
23266
25314
  active.set(sessionId, {
23267
25315
  sessionId,
23268
25316
  live: false,
23269
25317
  archived: archived.has(sessionId),
23270
25318
  running: false,
23271
25319
  createdAt: record2.header.createdAt,
25320
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
23272
25321
  enabledAt: lastEnabledAt(events) ?? 0
23273
25322
  });
23274
25323
  }
@@ -23335,7 +25384,10 @@ var DevLeadService = class extends Service {
23335
25384
  );
23336
25385
  return false;
23337
25386
  }
23338
- if (this.activeSessionId === occupant.sessionId) this.activeSessionId = void 0;
25387
+ if (this.activeSessionId === occupant.sessionId) {
25388
+ this.activeSessionId = void 0;
25389
+ await this.syncBoardToActiveLead();
25390
+ }
23339
25391
  this.ctx.logger.warn(
23340
25392
  `devlead: disabled DevLead mode for Session "${occupant.sessionId}" (${reason}); only one Session may hold DevLead mode at a time`
23341
25393
  );
@@ -23380,6 +25432,7 @@ var DevLeadService = class extends Service {
23380
25432
  if (!scanned.some((occupant) => occupant.sessionId === sessionId)) merged.delete(sessionId);
23381
25433
  }
23382
25434
  const active = [...merged.values()];
25435
+ for (const occupant of active) this.rememberLeadWorkspaceRoot(occupant.sessionId, occupant.cwd);
23383
25436
  if (active.length === 0) {
23384
25437
  this.activeSessionId = void 0;
23385
25438
  return;
@@ -23428,6 +25481,7 @@ var DevLeadService = class extends Service {
23428
25481
  this.ctx.logger.warn(`devlead: global DevLead admission reconciliation failed: ${thrownMessage(error51)}`);
23429
25482
  }
23430
25483
  }
25484
+ await this.syncBoardToActiveLead();
23431
25485
  }
23432
25486
  /** Reject any use of a tool surface while DevLead mode is off. */
23433
25487
  assertReady(agent) {
@@ -23506,6 +25560,29 @@ var DevLeadService = class extends Service {
23506
25560
  this.replayingOpenQuestions = false;
23507
25561
  }
23508
25562
  }
25563
+ /**
25564
+ * Read one cold candidate through the Host's replay-validated query path.
25565
+ * Only a precise unknown-non-ignorable-event refusal uses the read-only
25566
+ * current-JSONL recovery: all records are still read and the caller applies
25567
+ * the same strict DevLead fold, so unrelated legacy vocabulary cannot hide a
25568
+ * foreign supervisor or excuse corrupt DevLead state.
25569
+ */
25570
+ async readColdSessionForSupervision(query, header, signal) {
25571
+ try {
25572
+ const snapshot = await query.readSession(header.id);
25573
+ signal?.throwIfAborted();
25574
+ return snapshot;
25575
+ } catch (error51) {
25576
+ signal?.throwIfAborted();
25577
+ if (!isUnknownNonIgnorableEventError(error51)) throw error51;
25578
+ const recovered = await recoverUnknownEventSessionLog(this.ctx, header, signal);
25579
+ signal?.throwIfAborted();
25580
+ this.ctx.logger.debug(
25581
+ `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)}`
25582
+ );
25583
+ return recovered;
25584
+ }
25585
+ }
23509
25586
  /**
23510
25587
  * Scan durable state for lead Sessions the hub must index after a restart.
23511
25588
  *
@@ -23524,9 +25601,9 @@ var DevLeadService = class extends Service {
23524
25601
  * Cheap sources first: a live Session without an Agent has its projection
23525
25602
  * folded directly (attach-only leads), then the persisted corpus is filtered
23526
25603
  * 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).
25604
+ * with a non-empty watch set is a candidate; every other non-live, non-subagent
25605
+ * row still pays for a complete full-log exact fold (bounded, because a Host
25606
+ * history is unbounded and a stale-negative cache row is not authorization).
23530
25607
  * A corrupt replay skips that candidate with one warning; it must never stop
23531
25608
  * the scan, and it must never make the plugin fail to load.
23532
25609
  * @param listing - barrier-validated listing; re-verified when omitted.
@@ -23665,14 +25742,16 @@ var DevLeadService = class extends Service {
23665
25742
  const prefilter = cache === void 0 ? "unknown" : devLeadActivePrefilterOf(cache, record2.header);
23666
25743
  let events;
23667
25744
  let inheritedEventCount = 0;
25745
+ let sourcePath;
23668
25746
  try {
23669
- const snapshot = await this.awaitScan(query.readSession(record2.header.id), signal);
25747
+ const snapshot = await this.awaitScan(this.readColdSessionForSupervision(query, record2.header, signal), signal);
23670
25748
  if (snapshot === SCAN_ABORTED) {
23671
25749
  state.complete = false;
23672
25750
  return result([...state.leads.values()], state.active, false);
23673
25751
  }
23674
25752
  events = snapshot.events;
23675
25753
  inheritedEventCount = snapshot.inheritedEventCount;
25754
+ sourcePath = snapshot.path;
23676
25755
  } catch (error51) {
23677
25756
  if (signal?.aborted) {
23678
25757
  state.complete = false;
@@ -23684,7 +25763,8 @@ var DevLeadService = class extends Service {
23684
25763
  readFailed = true;
23685
25764
  this.warnRehydration(
23686
25765
  "read",
23687
- `devlead: a persisted Session stayed unreadable (not found) after re-listing; keeping the cursor for a bounded retry: ${thrownMessage(error51)}`
25766
+ `devlead: Session "${sessionId}" stayed unreadable (not found) after re-listing; keeping the cursor for a bounded retry: ${thrownMessage(error51)}`,
25767
+ `Session "${sessionId}" stayed unreadable (not found) after re-listing: ${thrownMessage(error51)}`
23688
25768
  );
23689
25769
  break;
23690
25770
  }
@@ -23699,7 +25779,8 @@ var DevLeadService = class extends Service {
23699
25779
  this.rehydrationValidationUnverifiable = true;
23700
25780
  this.warnRehydration(
23701
25781
  "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)}`
25782
+ `devlead: could not re-verify the Session corpus after Session "${sessionId}" returned not-found; keeping the trusted cursor for a bounded retry: ${thrownMessage(error51)}`,
25783
+ `Session "${sessionId}" returned not-found and its corpus re-list failed: ${thrownMessage(error51)}`
23703
25784
  );
23704
25785
  return result([...state.leads.values()], state.active, false);
23705
25786
  }
@@ -23731,7 +25812,11 @@ var DevLeadService = class extends Service {
23731
25812
  }
23732
25813
  state.complete = false;
23733
25814
  readFailed = true;
23734
- this.warnRehydration("read", `devlead: could not read a cold lead candidate Session log: ${thrownMessage(error51)}`);
25815
+ this.warnRehydration(
25816
+ "read",
25817
+ `devlead: could not read a cold lead candidate Session log "${sessionId}": ${thrownMessage(error51)}`,
25818
+ `Session "${sessionId}" could not be read: ${thrownMessage(error51)}`
25819
+ );
23735
25820
  break;
23736
25821
  }
23737
25822
  if (prefilter !== "active") reads += 1;
@@ -23743,7 +25828,12 @@ var DevLeadService = class extends Service {
23743
25828
  if (folded.failure !== null) {
23744
25829
  state.complete = false;
23745
25830
  state.corrupt = true;
23746
- this.warnRehydration("corrupt", `devlead: skipping a cold lead candidate with a corrupt DevLead replay: ${folded.failure}`);
25831
+ const location = sourcePath === void 0 ? "" : ` at ${sourcePath}`;
25832
+ this.warnRehydration(
25833
+ "corrupt",
25834
+ `devlead: skipping cold lead candidate Session "${sessionId}"${location} with a corrupt DevLead replay: ${folded.failure}`,
25835
+ `Session "${sessionId}"${location} has a corrupt DevLead replay: ${folded.failure}`
25836
+ );
23747
25837
  state.index += 1;
23748
25838
  continue;
23749
25839
  }
@@ -23757,6 +25847,7 @@ var DevLeadService = class extends Service {
23757
25847
  archived: archived.has(sessionId),
23758
25848
  running: false,
23759
25849
  createdAt: record2.header.createdAt,
25850
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
23760
25851
  enabledAt: lastEnabledAt(events) ?? 0
23761
25852
  });
23762
25853
  }
@@ -24420,8 +26511,8 @@ ${text}` : text,
24420
26511
  return record2;
24421
26512
  }
24422
26513
  /** 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;
26514
+ questionExpired(report, answers, now = Date.now(), open2 = questionStatusOf(answers, report.id) === "open") {
26515
+ return this.resolved.questionTtlMs > 0 && report.kind === "question" && open2 && now - report.at >= this.resolved.questionTtlMs;
24425
26516
  }
24426
26517
  /**
24427
26518
  * Read the derived question/answer state of one question report from the
@@ -24446,9 +26537,9 @@ ${text}` : text,
24446
26537
  };
24447
26538
  }
24448
26539
  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";
26540
+ const open2 = fact.status === "discarded" || fact.status === "failed";
24450
26541
  return {
24451
- questionStatus: open && this.questionExpired(report, state.answers, Date.now(), true) ? "expired" : open ? "open" : "answered",
26542
+ questionStatus: open2 && this.questionExpired(report, state.answers, Date.now(), true) ? "expired" : open2 ? "open" : "answered",
24452
26543
  answerStatus: fact.status,
24453
26544
  answerMessageId: fact.messageId,
24454
26545
  ...answeredAt === void 0 ? {} : { answeredAt },
@@ -25790,6 +27881,20 @@ ${text}` : text,
25790
27881
  var index_default = DevLeadService;
25791
27882
  export {
25792
27883
  Config,
27884
+ DEVLEAD_BOARD_DIR_SEGMENTS,
27885
+ DEVLEAD_BOARD_FILE_NAME,
27886
+ DEVLEAD_BOARD_ID_MAX,
27887
+ DEVLEAD_BOARD_MAX_BLOCKERS,
27888
+ DEVLEAD_BOARD_MAX_BYTES,
27889
+ DEVLEAD_BOARD_MAX_PROJECTS,
27890
+ DEVLEAD_BOARD_MAX_TASKS,
27891
+ DEVLEAD_BOARD_PATH_MAX,
27892
+ DEVLEAD_BOARD_READ_MAX_BYTES,
27893
+ DEVLEAD_BOARD_READ_MAX_TASKS,
27894
+ DEVLEAD_BOARD_SCHEMA_VERSION,
27895
+ DEVLEAD_BOARD_SUMMARY_MAX_BYTES,
27896
+ DEVLEAD_BOARD_TEXT_MAX,
27897
+ DEVLEAD_BOARD_TITLE_MAX,
25793
27898
  DEVLEAD_DEFAULT_MAX_WATCHED,
25794
27899
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
25795
27900
  DEVLEAD_ERROR_EXCERPT_MAX,
@@ -25797,6 +27902,20 @@ export {
25797
27902
  DEVLEAD_MAX_INSTANT,
25798
27903
  DEVLEAD_MESSAGE_KIND,
25799
27904
  DEVLEAD_MODE_RECORD_TYPE,
27905
+ DEVLEAD_NOTES_DIRECTORY_MAX,
27906
+ DEVLEAD_NOTES_DIR_NAME,
27907
+ DEVLEAD_NOTES_ID_MAX,
27908
+ DEVLEAD_NOTES_INDEX_FILE_NAME,
27909
+ DEVLEAD_NOTES_INDEX_MAX_BYTES,
27910
+ DEVLEAD_NOTES_MAX_PER_PROJECT,
27911
+ DEVLEAD_NOTES_MAX_PROJECTS,
27912
+ DEVLEAD_NOTES_NOTE_MAX_BYTES,
27913
+ DEVLEAD_NOTES_PATH_MAX,
27914
+ DEVLEAD_NOTES_READ_MAX_BYTES,
27915
+ DEVLEAD_NOTES_SCHEMA_VERSION,
27916
+ DEVLEAD_NOTES_SUMMARY_MAX,
27917
+ DEVLEAD_NOTES_TIMESTAMP_MAX,
27918
+ DEVLEAD_NOTES_TITLE_MAX,
25800
27919
  DEVLEAD_NOTIFICATION_RECORD_TYPE,
25801
27920
  DEVLEAD_QUESTIONS_MAX,
25802
27921
  DEVLEAD_QUESTION_FIELD_MAX,
@@ -25809,6 +27928,9 @@ export {
25809
27928
  DEVLEAD_REPORT_SUMMARY_MAX,
25810
27929
  DEVLEAD_RESET_RECORD_TYPE,
25811
27930
  DEVLEAD_WATCH_RECORD_TYPE,
27931
+ DevLeadBoardError,
27932
+ DevLeadBoardNotesStore,
27933
+ DevLeadBoardStore,
25812
27934
  DevLeadError,
25813
27935
  DevLeadMetrics,
25814
27936
  DevLeadService,
@@ -25832,6 +27954,7 @@ export {
25832
27954
  decodeResetRecord,
25833
27955
  decodeWatchRecord,
25834
27956
  index_default as default,
27957
+ devLeadBoardSchema,
25835
27958
  devLeadModeProjectionDefinition,
25836
27959
  devLeadModeProjectionSchema,
25837
27960
  devLeadModeProjectionStateSchema,
@@ -25850,6 +27973,7 @@ export {
25850
27973
  emptyDevLeadProjectionState,
25851
27974
  emptyDevLeadWatchProjectionState,
25852
27975
  failureExcerpt,
27976
+ isDevLeadBoardError,
25853
27977
  isDevLeadError,
25854
27978
  isHumanDirectedTurn,
25855
27979
  legacyDevLeadRecordReason,
@@ -25857,11 +27981,14 @@ export {
25857
27981
  notificationId,
25858
27982
  notificationRecord,
25859
27983
  recordApiStatus,
27984
+ renderDevLeadBoardSummary,
25860
27985
  renderDevLeadNotice,
25861
27986
  repairRecord,
25862
27987
  reportAnswerRecord,
25863
27988
  reportRecord,
25864
27989
  representableInstant,
25865
27990
  resetRecord,
27991
+ resolveDevLeadBoardPath,
27992
+ resolveDevLeadBoardProject,
25866
27993
  watchRecord
25867
27994
  };