@yankeguo/dsh-devlead 0.4.1 → 0.4.2-rc.3

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 +27 -4
  2. package/lib/index.js +1096 -23
  3. package/package.json +3 -2
package/lib/index.js CHANGED
@@ -6,7 +6,8 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // packages/devlead/src/index.ts
9
- import { mkdir } from "node:fs/promises";
9
+ import { mkdir as mkdir2, stat as stat3 } from "node:fs/promises";
10
+ import { isAbsolute as isAbsolute3 } from "node:path";
10
11
  import { Service } from "@deepseek-ai/cordis";
11
12
  import z2 from "@deepseek-ai/schemastery";
12
13
  import { MessageId, ReasoningEffortId } from "@deepseek-ai/dsh-llm";
@@ -150,12 +151,12 @@ function isUnknownNonIgnorableEventError(error51) {
150
151
  }
151
152
  async function recoverUnknownEventSessionLog(ctx, header, signal) {
152
153
  const persistence = ctx.get("sessionPersistence");
153
- const stat2 = persistence?.stat;
154
- if (typeof stat2 !== "function") {
154
+ const stat4 = persistence?.stat;
155
+ if (typeof stat4 !== "function") {
155
156
  throw new Error(`Session "${String(header.id)}" needs read-only log recovery, but the persistence backend exposes no stat()`);
156
157
  }
157
158
  signal?.throwIfAborted();
158
- const snapshot = await stat2.call(
159
+ const snapshot = await stat4.call(
159
160
  persistence,
160
161
  header.id,
161
162
  signal === void 0 ? void 0 : { signal }
@@ -16891,8 +16892,8 @@ function applyDevLeadProjection(state, event) {
16891
16892
  return mode.enabled === state.enabled ? state : { ...state, enabled: mode.enabled };
16892
16893
  }
16893
16894
  case DEVLEAD_WATCH_RECORD_TYPE2: {
16894
- const watch = decodeWatchRecord(record2.data);
16895
- 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 };
16896
16897
  }
16897
16898
  case DEVLEAD_NOTIFICATION_RECORD_TYPE2: {
16898
16899
  const notification = decodeNotificationRecord(record2.data);
@@ -16999,8 +17000,8 @@ function applyDevLeadWatchProjection(state, event) {
16999
17000
  try {
17000
17001
  switch (record2.type) {
17001
17002
  case DEVLEAD_WATCH_RECORD_TYPE2: {
17002
- const watch = decodeWatchRecord(record2.data);
17003
- 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 };
17004
17005
  }
17005
17006
  case DEVLEAD_MODE_RECORD_TYPE2:
17006
17007
  decodeModeRecord(record2.data);
@@ -17980,6 +17981,749 @@ function worktreeCapabilityOf(ctx) {
17980
17981
  return candidate;
17981
17982
  }
17982
17983
 
17984
+ // packages/devlead/src/board.ts
17985
+ import { watch } from "node:fs";
17986
+ import { mkdir, readFile, stat as stat2 } from "node:fs/promises";
17987
+ import { basename, dirname, isAbsolute as isAbsolute2, join, normalize } from "node:path";
17988
+ import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
17989
+ import {
17990
+ createDevLeadBoardSchema,
17991
+ devLeadBoardIssueViews,
17992
+ DEVLEAD_BOARD_DIR_SEGMENTS,
17993
+ DEVLEAD_BOARD_FILE_NAME,
17994
+ DEVLEAD_BOARD_ID_MAX,
17995
+ DEVLEAD_BOARD_MAX_BLOCKERS,
17996
+ DEVLEAD_BOARD_MAX_BYTES,
17997
+ DEVLEAD_BOARD_MAX_PROJECTS,
17998
+ DEVLEAD_BOARD_MAX_TASKS,
17999
+ DEVLEAD_BOARD_PATH_MAX,
18000
+ DEVLEAD_BOARD_READ_MAX_BYTES,
18001
+ DEVLEAD_BOARD_SCHEMA_VERSION,
18002
+ DEVLEAD_BOARD_TEXT_MAX,
18003
+ DEVLEAD_BOARD_TITLE_MAX
18004
+ } from "@yankeguo/dsh-devlead-protocol";
18005
+ var DEVLEAD_BOARD_SUMMARY_MAX_BYTES = 1536;
18006
+ var DEVLEAD_BOARD_READ_MAX_TASKS = 50;
18007
+ var DEVLEAD_BOARD_READ_ATTEMPTS = 4;
18008
+ var DevLeadBoardError = class extends Error {
18009
+ /**
18010
+ * @param message - human-readable failure.
18011
+ * @param code - stable tool-facing code.
18012
+ * @param issues - path-qualified validation details.
18013
+ */
18014
+ constructor(message, code, issues = []) {
18015
+ super(message);
18016
+ this.code = code;
18017
+ this.issues = issues;
18018
+ this.name = "DevLeadBoardError";
18019
+ }
18020
+ code;
18021
+ issues;
18022
+ };
18023
+ function isDevLeadBoardError(error51) {
18024
+ if (error51 instanceof DevLeadBoardError) return true;
18025
+ if (!(error51 instanceof Error)) return false;
18026
+ const code = error51.code;
18027
+ return typeof code === "string" && code.startsWith("BOARD_");
18028
+ }
18029
+ var devLeadBoardSchema = createDevLeadBoardSchema(isAbsolute2);
18030
+ function sameFingerprint(left, right) {
18031
+ return left !== void 0 && left.mtimeMs === right.mtimeMs && left.size === right.size && left.ino === right.ino;
18032
+ }
18033
+ function validationError(error51) {
18034
+ const issues = devLeadBoardIssueViews(error51.issues);
18035
+ const limited = error51.issues.some((issue2) => issue2.code === "too_big");
18036
+ const code = limited ? "BOARD_LIMIT_EXCEEDED" : "BOARD_INVALID";
18037
+ const first = issues[0];
18038
+ return new DevLeadBoardError(
18039
+ `board validation failed${first === void 0 ? "" : ` at ${first.pointer || "/"}: ${first.message}`}`,
18040
+ code,
18041
+ issues
18042
+ );
18043
+ }
18044
+ function parseBoard(value) {
18045
+ const parsed = devLeadBoardSchema.safeParse(value);
18046
+ if (!parsed.success) throw validationError(parsed.error);
18047
+ return parsed.data;
18048
+ }
18049
+ function errorMessage2(error51) {
18050
+ return error51 instanceof Error ? error51.message : String(error51);
18051
+ }
18052
+ var FILESYSTEM_ERROR_CODES = /* @__PURE__ */ new Set([
18053
+ "EACCES",
18054
+ "EAGAIN",
18055
+ "EBUSY",
18056
+ "EDQUOT",
18057
+ "EEXIST",
18058
+ "EFBIG",
18059
+ "EIO",
18060
+ "EISDIR",
18061
+ "ELOOP",
18062
+ "EMFILE",
18063
+ "ENAMETOOLONG",
18064
+ "ENFILE",
18065
+ "ENOMEM",
18066
+ "ENOENT",
18067
+ "ENOSPC",
18068
+ "ENOTDIR",
18069
+ "ENOTEMPTY",
18070
+ "EPERM",
18071
+ "EROFS",
18072
+ "ETXTBSY"
18073
+ ]);
18074
+ function errorCode(error51) {
18075
+ if (typeof error51 !== "object" || error51 === null) return void 0;
18076
+ const code = error51.code;
18077
+ return typeof code === "string" ? code : void 0;
18078
+ }
18079
+ function isWriterLockTimeout(error51) {
18080
+ const message = errorMessage2(error51);
18081
+ const code = errorCode(error51);
18082
+ return code === "FILE_LOCK_TIMEOUT" || code === "ATOMIC_WRITE_LOCK_TIMEOUT" || /timed out waiting for the writer lock|writer lock timed out/iu.test(message);
18083
+ }
18084
+ function isWriteIoError(error51) {
18085
+ const code = errorCode(error51);
18086
+ return code !== void 0 && FILESYSTEM_ERROR_CODES.has(code) || error51 instanceof Error && error51.name === "FileLockError" || isWriterLockTimeout(error51);
18087
+ }
18088
+ function writeIoError(filePath, error51) {
18089
+ const retry = isWriterLockTimeout(error51);
18090
+ return new DevLeadBoardError(
18091
+ `could not write board ${filePath}: ${errorMessage2(error51)}${retry ? "; retry after the current writer finishes" : ""}`,
18092
+ "BOARD_IO_ERROR"
18093
+ );
18094
+ }
18095
+ function normalizeUpdatedBy(updatedBy) {
18096
+ const title = updatedBy.title.trim().slice(0, DEVLEAD_BOARD_TITLE_MAX);
18097
+ return { sessionId: updatedBy.sessionId, title: title.length === 0 ? "DevLead" : title };
18098
+ }
18099
+ function resolveDevLeadBoardPath(input = {}) {
18100
+ const override = input.override?.trim() ?? "";
18101
+ if (override.length > 0) {
18102
+ if (!isAbsolute2(override)) return { kind: "disabled", reason: "invalid-override" };
18103
+ return { kind: "resolved", path: normalize(override), source: "override" };
18104
+ }
18105
+ const cwd = input.cwd?.trim() ?? "";
18106
+ if (cwd.length === 0) return { kind: "disabled", reason: "no-workspace" };
18107
+ if (!isAbsolute2(cwd)) return { kind: "disabled", reason: "relative-workspace" };
18108
+ return {
18109
+ kind: "resolved",
18110
+ path: join(normalize(cwd), ...DEVLEAD_BOARD_DIR_SEGMENTS, DEVLEAD_BOARD_FILE_NAME),
18111
+ source: "workspace"
18112
+ };
18113
+ }
18114
+ function boundReadResult(result) {
18115
+ const serializedBytes = (projects2, truncated2) => Buffer.byteLength(JSON.stringify({
18116
+ revision: result.revision,
18117
+ updatedAt: result.updatedAt,
18118
+ projects: projects2,
18119
+ ...truncated2 ? { truncated: true } : {}
18120
+ }), "utf8");
18121
+ if (serializedBytes(result.projects, result.truncated === true) <= DEVLEAD_BOARD_READ_MAX_BYTES) return result;
18122
+ const projects = result.projects.map((project) => structuredClone(project));
18123
+ let truncated = true;
18124
+ for (; ; ) {
18125
+ if (serializedBytes(projects, truncated) <= DEVLEAD_BOARD_READ_MAX_BYTES) break;
18126
+ let trimmed = false;
18127
+ for (let index = projects.length - 1; index >= 0 && !trimmed; index -= 1) {
18128
+ const tasks = projects[index]?.tasks;
18129
+ if (tasks !== void 0 && tasks.length > 0) {
18130
+ projects[index] = { ...projects[index], tasks: tasks.slice(0, -1) };
18131
+ trimmed = true;
18132
+ }
18133
+ }
18134
+ if (trimmed) continue;
18135
+ for (let index = projects.length - 1; index >= 0 && !trimmed; index -= 1) {
18136
+ const project = projects[index];
18137
+ if (project.blockers.length > 0) {
18138
+ projects[index] = { ...project, blockers: project.blockers.slice(0, -1) };
18139
+ trimmed = true;
18140
+ }
18141
+ }
18142
+ if (trimmed) continue;
18143
+ if (projects.length > 1) {
18144
+ projects.pop();
18145
+ continue;
18146
+ }
18147
+ break;
18148
+ }
18149
+ return {
18150
+ revision: result.revision,
18151
+ updatedAt: result.updatedAt,
18152
+ projects,
18153
+ ...truncated ? { truncated: true } : {}
18154
+ };
18155
+ }
18156
+ var DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID = "devlead-validation";
18157
+ function singleLine(value) {
18158
+ return value.replaceAll(/[\p{Cc}\p{Cf}]+/gu, " ").replaceAll(/\s+/gu, " ").trim();
18159
+ }
18160
+ function resolveProject(board, reference) {
18161
+ const trimmed = reference.trim();
18162
+ if (trimmed.length === 0) {
18163
+ throw new DevLeadBoardError("project must not be empty", "BOARD_INVALID", [
18164
+ { pointer: "/project", message: "project must not be empty" }
18165
+ ]);
18166
+ }
18167
+ const byId = board.projects.find((project) => project.id === trimmed);
18168
+ if (byId !== void 0) return byId;
18169
+ const byPath = board.projects.find((project) => project.workspace.path === trimmed);
18170
+ if (byPath !== void 0) return byPath;
18171
+ const titled = board.projects.filter((project) => project.workspace.title === trimmed);
18172
+ if (titled.length === 1 && titled[0] !== void 0) return titled[0];
18173
+ if (titled.length > 1) {
18174
+ throw new DevLeadBoardError(
18175
+ `project title "${trimmed}" is ambiguous; use its id or workspace path`,
18176
+ "BOARD_PROJECT_AMBIGUOUS"
18177
+ );
18178
+ }
18179
+ throw new DevLeadBoardError(`no board project matches "${trimmed}"`, "BOARD_PROJECT_NOT_FOUND");
18180
+ }
18181
+ function emptyBoard(updatedBy, updatedAt) {
18182
+ return {
18183
+ schemaVersion: DEVLEAD_BOARD_SCHEMA_VERSION,
18184
+ revision: 0,
18185
+ updatedAt,
18186
+ updatedBy: structuredClone(updatedBy),
18187
+ projects: []
18188
+ };
18189
+ }
18190
+ function validateUpdateInput(patch) {
18191
+ const normalized = { ...patch, updatedBy: normalizeUpdatedBy(patch.updatedBy) };
18192
+ const timestamp = (/* @__PURE__ */ new Date(0)).toISOString();
18193
+ const candidate = emptyBoard(normalized.updatedBy, timestamp);
18194
+ if (patch.create !== true) {
18195
+ const reference = patch.project.trim();
18196
+ if (reference.length === 0) resolveProject(candidate, reference);
18197
+ const validationTasks = /* @__PURE__ */ new Map();
18198
+ for (const upsert2 of patch.tasks?.upsert ?? []) {
18199
+ if (!validationTasks.has(upsert2.id)) {
18200
+ validationTasks.set(upsert2.id, {
18201
+ id: upsert2.id,
18202
+ title: upsert2.title ?? "DevLead validation",
18203
+ status: "todo",
18204
+ updatedAt: timestamp
18205
+ });
18206
+ }
18207
+ }
18208
+ candidate.projects.push({
18209
+ id: DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID,
18210
+ workspace: { path: "/devlead-validation", title: "DevLead validation" },
18211
+ status: "active",
18212
+ priority: "medium",
18213
+ goal: "",
18214
+ focus: "",
18215
+ next: "",
18216
+ blockers: [],
18217
+ tasks: [...validationTasks.values()],
18218
+ updatedAt: timestamp
18219
+ });
18220
+ }
18221
+ applyProjectPatch(
18222
+ candidate,
18223
+ patch.create === true ? normalized : { ...normalized, project: DEVLEAD_BOARD_PREFLIGHT_PROJECT_ID },
18224
+ timestamp
18225
+ );
18226
+ parseBoard(candidate);
18227
+ return normalized;
18228
+ }
18229
+ function validateMissingFileUpdate(patch, expectedRevision) {
18230
+ const timestamp = (/* @__PURE__ */ new Date(0)).toISOString();
18231
+ const current = emptyBoard(patch.updatedBy, timestamp);
18232
+ if (expectedRevision !== void 0 && expectedRevision !== 0) {
18233
+ throw new DevLeadBoardError(
18234
+ `board revision conflict: expected r${expectedRevision}, current r0`,
18235
+ "BOARD_REVISION_CONFLICT",
18236
+ [{ pointer: "/revision", message: `expected ${expectedRevision}, current 0` }]
18237
+ );
18238
+ }
18239
+ const next = structuredClone(current);
18240
+ applyProjectPatch(next, patch, timestamp);
18241
+ next.revision = 1;
18242
+ next.updatedAt = timestamp;
18243
+ next.updatedBy = structuredClone(patch.updatedBy);
18244
+ parseBoard(next);
18245
+ }
18246
+ function projectView(project, includeTasks) {
18247
+ const view = structuredClone(project);
18248
+ if (includeTasks) view.tasks = (view.tasks ?? []).slice(0, DEVLEAD_BOARD_READ_MAX_TASKS);
18249
+ else delete view.tasks;
18250
+ return view;
18251
+ }
18252
+ function appendUtf8(target, addition, maximum) {
18253
+ const bytes = Buffer.byteLength(addition, "utf8");
18254
+ if (target.bytes + bytes > maximum) return false;
18255
+ target.text += addition;
18256
+ target.bytes += bytes;
18257
+ return true;
18258
+ }
18259
+ function renderDevLeadBoardSummary(board) {
18260
+ if (board === void 0 || board.projects.length === 0) return "";
18261
+ const counts = { active: 0, blocked: 0, paused: 0, done: 0 };
18262
+ for (const project of board.projects) counts[project.status] += 1;
18263
+ const lines = [
18264
+ `DevLead board r${board.revision} ${board.updatedAt}; projects ${board.projects.length}: active ${counts.active}, blocked ${counts.blocked}, paused ${counts.paused}, done ${counts.done}`
18265
+ ];
18266
+ for (const project of board.projects) {
18267
+ const focus = Array.from(singleLine(project.focus)).slice(0, 120).join("");
18268
+ lines.push(
18269
+ `- ${singleLine(project.id)}/${singleLine(project.workspace.title)} [${project.status}/${project.priority}]${focus.length === 0 ? "" : ` focus: ${focus}`}${project.blockers.length === 0 ? "" : ` !blockers:${project.blockers.length}`}`
18270
+ );
18271
+ }
18272
+ const output = { text: "", bytes: 0 };
18273
+ for (let index = 0; index < lines.length; index += 1) {
18274
+ const line = lines[index] ?? "";
18275
+ if (!appendUtf8(output, `${index === 0 ? "" : "\n"}${line}`, DEVLEAD_BOARD_SUMMARY_MAX_BYTES)) {
18276
+ appendUtf8(output, "\n\u2026", DEVLEAD_BOARD_SUMMARY_MAX_BYTES);
18277
+ break;
18278
+ }
18279
+ }
18280
+ return output.text;
18281
+ }
18282
+ var DevLeadBoardStore = class {
18283
+ /**
18284
+ * @param boardPath - absolute deployment-configured path; blank/undefined disables the board.
18285
+ * @param logger - Host logger for best-effort watcher failures.
18286
+ * @param now - injectable clock used by tests.
18287
+ */
18288
+ constructor(boardPath, logger2 = { warn: () => void 0 }, now = Date.now) {
18289
+ this.logger = logger2;
18290
+ this.now = now;
18291
+ const trimmed = boardPath?.trim() ?? "";
18292
+ if (trimmed.length > 0 && !isAbsolute2(trimmed)) {
18293
+ throw new DevLeadBoardError("boardPath must be an absolute path", "BOARD_INVALID", [
18294
+ { pointer: "/boardPath", message: "boardPath must be an absolute path" }
18295
+ ]);
18296
+ }
18297
+ this.filePath = trimmed.length === 0 ? void 0 : trimmed;
18298
+ }
18299
+ logger;
18300
+ now;
18301
+ filePath;
18302
+ cache;
18303
+ fingerprint;
18304
+ lastError;
18305
+ dirty = true;
18306
+ loading;
18307
+ writeTail = Promise.resolve();
18308
+ watcher;
18309
+ closed = false;
18310
+ /** Absolute configured file path, or undefined when disabled. */
18311
+ get path() {
18312
+ return this.filePath;
18313
+ }
18314
+ /** Whether board reads/writes are configured. */
18315
+ get enabled() {
18316
+ return this.filePath !== void 0;
18317
+ }
18318
+ /**
18319
+ * Prepare the watchable parent, then load without rejecting for a malformed
18320
+ * file.
18321
+ *
18322
+ * The service only calls this for an explicit deployment override or for a
18323
+ * derived path whose workspace root already exists as a directory; a missing
18324
+ * workspace root disables the board instead of being recreated here.
18325
+ */
18326
+ async start() {
18327
+ if (this.filePath === void 0) return;
18328
+ try {
18329
+ await mkdir(dirname(this.filePath), { recursive: true, mode: 448 });
18330
+ } catch (error51) {
18331
+ if (isDevLeadBoardError(error51)) throw error51;
18332
+ if (isWriteIoError(error51)) throw writeIoError(this.filePath, error51);
18333
+ throw error51;
18334
+ }
18335
+ await this.refresh(true);
18336
+ this.startWatcher();
18337
+ }
18338
+ /** Stop watching and settle already-queued work. */
18339
+ async close() {
18340
+ this.closed = true;
18341
+ this.watcher?.close();
18342
+ this.watcher = void 0;
18343
+ await this.loading;
18344
+ await this.writeTail;
18345
+ }
18346
+ requirePath() {
18347
+ if (this.filePath === void 0) {
18348
+ throw new DevLeadBoardError("DevLead board is disabled; configure devlead boardPath", "BOARD_DISABLED");
18349
+ }
18350
+ return this.filePath;
18351
+ }
18352
+ startWatcher() {
18353
+ const filePath = this.filePath;
18354
+ if (filePath === void 0 || this.watcher !== void 0 || this.closed) return;
18355
+ try {
18356
+ this.watcher = watch(dirname(filePath), { persistent: false }, (_event, filename) => {
18357
+ if (filename !== null && filename.toString() !== basename(filePath)) return;
18358
+ this.dirty = true;
18359
+ void this.refresh();
18360
+ });
18361
+ this.watcher.on("error", (error51) => {
18362
+ this.logger.warn(`devlead: board watcher failed for ${filePath}: ${errorMessage2(error51)}`);
18363
+ this.watcher?.close();
18364
+ this.watcher = void 0;
18365
+ });
18366
+ } catch (error51) {
18367
+ if (error51.code !== "ENOENT") {
18368
+ this.logger.warn(`devlead: could not watch board ${filePath}: ${errorMessage2(error51)}`);
18369
+ }
18370
+ }
18371
+ }
18372
+ async refresh(force = false) {
18373
+ if (this.filePath === void 0) return;
18374
+ if (this.dirty) force = true;
18375
+ for (; ; ) {
18376
+ const pending = this.loading;
18377
+ if (pending !== void 0) {
18378
+ await pending;
18379
+ if (!force) return;
18380
+ continue;
18381
+ }
18382
+ const operation = this.load(force);
18383
+ this.loading = operation;
18384
+ try {
18385
+ await operation;
18386
+ return;
18387
+ } finally {
18388
+ if (this.loading === operation) this.loading = void 0;
18389
+ }
18390
+ }
18391
+ }
18392
+ async load(force) {
18393
+ const filePath = this.requirePath();
18394
+ this.dirty = false;
18395
+ try {
18396
+ for (let attempt = 0; attempt < DEVLEAD_BOARD_READ_ATTEMPTS; attempt += 1) {
18397
+ const before = await stat2(filePath);
18398
+ if (!force && this.cache !== void 0 && this.lastError === void 0 && sameFingerprint(this.fingerprint, before)) {
18399
+ this.startWatcher();
18400
+ return;
18401
+ }
18402
+ if (before.size > DEVLEAD_BOARD_MAX_BYTES) {
18403
+ this.lastError = new DevLeadBoardError(
18404
+ `board file exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes`,
18405
+ "BOARD_LIMIT_EXCEEDED",
18406
+ [{ pointer: "", message: `file size ${before.size} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18407
+ );
18408
+ return;
18409
+ }
18410
+ const content = await readFile(filePath, "utf8");
18411
+ const after = await stat2(filePath);
18412
+ if (!sameFingerprint(before, after) || Buffer.byteLength(content, "utf8") !== after.size) continue;
18413
+ let value;
18414
+ try {
18415
+ value = JSON.parse(content);
18416
+ } catch (error51) {
18417
+ this.lastError = new DevLeadBoardError(
18418
+ `board file is not valid JSON: ${errorMessage2(error51)}`,
18419
+ "BOARD_INVALID",
18420
+ [{ pointer: "", message: errorMessage2(error51) }]
18421
+ );
18422
+ return;
18423
+ }
18424
+ let board;
18425
+ try {
18426
+ board = parseBoard(value);
18427
+ } catch (error51) {
18428
+ this.lastError = error51 instanceof DevLeadBoardError ? error51 : new DevLeadBoardError(errorMessage2(error51), "BOARD_INVALID");
18429
+ return;
18430
+ }
18431
+ this.cache = board;
18432
+ this.fingerprint = { mtimeMs: after.mtimeMs, size: after.size, ino: after.ino };
18433
+ this.lastError = void 0;
18434
+ this.startWatcher();
18435
+ return;
18436
+ }
18437
+ this.lastError = new DevLeadBoardError(
18438
+ `board file changed repeatedly while reading ${filePath}; retry`,
18439
+ "BOARD_IO_ERROR"
18440
+ );
18441
+ } catch (error51) {
18442
+ if (error51.code === "ENOENT") {
18443
+ this.cache = void 0;
18444
+ this.fingerprint = void 0;
18445
+ this.lastError = new DevLeadBoardError(`board file does not exist: ${filePath}`, "BOARD_NOT_FOUND");
18446
+ return;
18447
+ }
18448
+ if (error51 instanceof DevLeadBoardError) {
18449
+ this.lastError = error51;
18450
+ return;
18451
+ }
18452
+ this.lastError = new DevLeadBoardError(
18453
+ `could not read board ${filePath}: ${errorMessage2(error51)}`,
18454
+ "BOARD_IO_ERROR"
18455
+ );
18456
+ }
18457
+ }
18458
+ async current() {
18459
+ this.requirePath();
18460
+ await this.refresh();
18461
+ if (this.lastError !== void 0) throw this.lastError;
18462
+ if (this.cache === void 0) {
18463
+ throw new DevLeadBoardError("board has no valid snapshot", "BOARD_NOT_FOUND");
18464
+ }
18465
+ return this.cache;
18466
+ }
18467
+ /** Read a detached, optionally filtered board projection. */
18468
+ async read(filter = {}) {
18469
+ const board = await this.current();
18470
+ const includeTasks = filter.includeTasks ?? filter.project !== void 0;
18471
+ if (filter.limit !== void 0 && (!Number.isSafeInteger(filter.limit) || filter.limit < 1)) {
18472
+ throw new DevLeadBoardError("limit must be a positive safe integer", "BOARD_INVALID", [
18473
+ { pointer: "/limit", message: "limit must be a positive safe integer" }
18474
+ ]);
18475
+ }
18476
+ let projects;
18477
+ let truncated = false;
18478
+ if (filter.project !== void 0) {
18479
+ projects = [resolveProject(board, filter.project)];
18480
+ } else {
18481
+ const limit = Math.min(filter.limit ?? DEVLEAD_BOARD_MAX_PROJECTS, DEVLEAD_BOARD_MAX_PROJECTS);
18482
+ projects = board.projects.slice(0, limit);
18483
+ truncated = board.projects.length > projects.length;
18484
+ }
18485
+ return boundReadResult({
18486
+ revision: board.revision,
18487
+ updatedAt: board.updatedAt,
18488
+ projects: projects.map((project) => {
18489
+ if (includeTasks && project.tasks.length > DEVLEAD_BOARD_READ_MAX_TASKS) truncated = true;
18490
+ return projectView(project, includeTasks);
18491
+ }),
18492
+ ...truncated ? { truncated: true } : {}
18493
+ });
18494
+ }
18495
+ /**
18496
+ * Apply one project mutation. Host calls share one promise chain; every call
18497
+ * then performs its own locked disk read-modify-write cycle.
18498
+ */
18499
+ async update(patch, expectedRevision, signal) {
18500
+ this.requirePath();
18501
+ if (expectedRevision !== void 0 && (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0)) {
18502
+ throw new DevLeadBoardError("expectedRevision must be a non-negative safe integer", "BOARD_INVALID", [
18503
+ { pointer: "/expectedRevision", message: "expectedRevision must be a non-negative safe integer" }
18504
+ ]);
18505
+ }
18506
+ signal?.throwIfAborted();
18507
+ const operation = this.writeTail.then(() => this.updateLocked(patch, expectedRevision, signal));
18508
+ this.writeTail = operation.catch(() => void 0);
18509
+ return operation;
18510
+ }
18511
+ async updateLocked(input, expectedRevision, signal) {
18512
+ const filePath = this.requirePath();
18513
+ try {
18514
+ const patch = validateUpdateInput(input);
18515
+ try {
18516
+ await stat2(dirname(filePath));
18517
+ } catch (error51) {
18518
+ if (errorCode(error51) !== "ENOENT") throw error51;
18519
+ validateMissingFileUpdate(patch, expectedRevision);
18520
+ }
18521
+ await mkdir(dirname(filePath), { recursive: true, mode: 448 });
18522
+ this.startWatcher();
18523
+ return await withFileLock(filePath, async () => {
18524
+ signal?.throwIfAborted();
18525
+ await this.refresh(true);
18526
+ if (this.lastError !== void 0 && this.lastError.code !== "BOARD_NOT_FOUND") throw this.lastError;
18527
+ const timestamp = new Date(this.now()).toISOString();
18528
+ const current = this.cache ?? emptyBoard(patch.updatedBy, timestamp);
18529
+ if (expectedRevision !== void 0 && current.revision !== expectedRevision) {
18530
+ throw new DevLeadBoardError(
18531
+ `board revision conflict: expected r${expectedRevision}, current r${current.revision}`,
18532
+ "BOARD_REVISION_CONFLICT",
18533
+ [{ pointer: "/revision", message: `expected ${expectedRevision}, current ${current.revision}` }]
18534
+ );
18535
+ }
18536
+ const next = structuredClone(current);
18537
+ const changed = applyProjectPatch(next, patch, timestamp);
18538
+ const project = resolveProject(next, patch.project);
18539
+ if (changed.length === 0) {
18540
+ return {
18541
+ revision: current.revision,
18542
+ updatedAt: current.updatedAt,
18543
+ project: projectView(project, false),
18544
+ changed
18545
+ };
18546
+ }
18547
+ next.revision = current.revision + 1;
18548
+ next.updatedAt = timestamp;
18549
+ next.updatedBy = structuredClone(patch.updatedBy);
18550
+ const validated = parseBoard(next);
18551
+ const content = `${JSON.stringify(validated, null, 2)}
18552
+ `;
18553
+ const bytes = Buffer.byteLength(content, "utf8");
18554
+ if (bytes > DEVLEAD_BOARD_MAX_BYTES) {
18555
+ throw new DevLeadBoardError(
18556
+ `board update would exceed ${DEVLEAD_BOARD_MAX_BYTES} bytes (${bytes})`,
18557
+ "BOARD_LIMIT_EXCEEDED",
18558
+ [{ pointer: "", message: `serialized size ${bytes} exceeds ${DEVLEAD_BOARD_MAX_BYTES} bytes` }]
18559
+ );
18560
+ }
18561
+ await writeFileAtomic(filePath, content, { mode: 384, dirMode: 448 });
18562
+ const written = await stat2(filePath);
18563
+ this.cache = validated;
18564
+ this.lastError = void 0;
18565
+ this.dirty = false;
18566
+ this.fingerprint = { mtimeMs: written.mtimeMs, size: written.size, ino: written.ino };
18567
+ this.startWatcher();
18568
+ return {
18569
+ revision: validated.revision,
18570
+ updatedAt: validated.updatedAt,
18571
+ project: projectView(resolveProject(validated, project.id), false),
18572
+ changed
18573
+ };
18574
+ }, signal === void 0 ? {} : { signal });
18575
+ } catch (error51) {
18576
+ if (isDevLeadBoardError(error51)) throw error51;
18577
+ if (isWriteIoError(error51)) throw writeIoError(filePath, error51);
18578
+ throw error51;
18579
+ }
18580
+ }
18581
+ /** Synchronous cache-only text for `systemPrompt.context()`. */
18582
+ summary() {
18583
+ if (this.filePath === void 0) return "";
18584
+ return renderDevLeadBoardSummary(this.cache);
18585
+ }
18586
+ };
18587
+ function applyProjectPatch(board, patch, timestamp) {
18588
+ const changed = [];
18589
+ let project;
18590
+ try {
18591
+ project = resolveProject(board, patch.project);
18592
+ } catch (error51) {
18593
+ if (!(error51 instanceof DevLeadBoardError) || error51.code !== "BOARD_PROJECT_NOT_FOUND" || patch.create !== true) throw error51;
18594
+ const workspacePatch = patch.set?.workspace;
18595
+ const workspacePath = workspacePatch?.path;
18596
+ if (workspacePath === void 0 || workspacePath.trim().length === 0) {
18597
+ throw new DevLeadBoardError("creating a project requires set.workspace.path", "BOARD_INVALID", [
18598
+ { pointer: "/set/workspace/path", message: "required when create is true" }
18599
+ ]);
18600
+ }
18601
+ const id = patch.project.trim();
18602
+ project = {
18603
+ id,
18604
+ workspace: {
18605
+ path: workspacePath,
18606
+ title: workspacePatch?.title ?? (basename(workspacePath) || id)
18607
+ },
18608
+ status: "active",
18609
+ priority: "medium",
18610
+ goal: "",
18611
+ focus: "",
18612
+ next: "",
18613
+ blockers: [],
18614
+ tasks: [],
18615
+ updatedAt: timestamp
18616
+ };
18617
+ board.projects.push(project);
18618
+ changed.push("project.create");
18619
+ }
18620
+ let projectChanged = changed.length > 0;
18621
+ const set2 = patch.set;
18622
+ if (set2 !== void 0) {
18623
+ for (const field of ["status", "priority", "goal", "focus", "next"]) {
18624
+ const value = set2[field];
18625
+ if (value !== void 0 && project[field] !== value) {
18626
+ Object.assign(project, { [field]: value });
18627
+ changed.push(`set.${field}`);
18628
+ projectChanged = true;
18629
+ }
18630
+ }
18631
+ if (set2.workspace !== void 0) {
18632
+ for (const field of ["path", "title"]) {
18633
+ const value = set2.workspace[field];
18634
+ if (value !== void 0 && project.workspace[field] !== value) {
18635
+ project.workspace[field] = value;
18636
+ changed.push(`set.workspace.${field}`);
18637
+ projectChanged = true;
18638
+ }
18639
+ }
18640
+ }
18641
+ }
18642
+ const blockers = patch.blockers;
18643
+ if (blockers?.clear === true && project.blockers.length > 0) {
18644
+ project.blockers = [];
18645
+ changed.push("blockers.clear");
18646
+ projectChanged = true;
18647
+ }
18648
+ if (blockers?.remove !== void 0) {
18649
+ const remove = new Set(blockers.remove);
18650
+ const retained = project.blockers.filter((blocker) => !remove.has(blocker.id));
18651
+ if (retained.length !== project.blockers.length) {
18652
+ project.blockers = retained;
18653
+ changed.push("blockers.remove");
18654
+ projectChanged = true;
18655
+ }
18656
+ }
18657
+ for (const addition of blockers?.add ?? []) {
18658
+ const existing = project.blockers.find((blocker2) => blocker2.id === addition.id);
18659
+ const sessionId = addition.sessionId ?? existing?.sessionId;
18660
+ const blocker = {
18661
+ id: addition.id,
18662
+ text: addition.text,
18663
+ since: existing?.since ?? timestamp,
18664
+ ...sessionId === void 0 ? {} : { sessionId }
18665
+ };
18666
+ if (existing === void 0) {
18667
+ project.blockers.push(blocker);
18668
+ changed.push(`blockers.add:${addition.id}`);
18669
+ projectChanged = true;
18670
+ } else if (existing.text !== blocker.text || existing.sessionId !== blocker.sessionId) {
18671
+ Object.assign(existing, blocker);
18672
+ changed.push(`blockers.add:${addition.id}`);
18673
+ projectChanged = true;
18674
+ }
18675
+ }
18676
+ if (patch.tasks?.remove !== void 0) {
18677
+ const remove = new Set(patch.tasks.remove);
18678
+ const retained = project.tasks.filter((task) => !remove.has(task.id));
18679
+ if (retained.length !== project.tasks.length) {
18680
+ project.tasks = retained;
18681
+ changed.push("tasks.remove");
18682
+ projectChanged = true;
18683
+ }
18684
+ }
18685
+ for (const upsert2 of patch.tasks?.upsert ?? []) {
18686
+ const existing = project.tasks.find((task) => task.id === upsert2.id);
18687
+ if (existing === void 0) {
18688
+ if (upsert2.title === void 0 || upsert2.title.trim().length === 0) {
18689
+ throw new DevLeadBoardError(`new task "${upsert2.id}" requires a non-empty title`, "BOARD_INVALID", [
18690
+ { pointer: "/tasks/upsert", message: `new task "${upsert2.id}" requires title` }
18691
+ ]);
18692
+ }
18693
+ project.tasks.push({
18694
+ id: upsert2.id,
18695
+ title: upsert2.title,
18696
+ status: upsert2.status ?? "todo",
18697
+ ...upsert2.ownerSessionId === void 0 ? {} : { ownerSessionId: upsert2.ownerSessionId },
18698
+ updatedAt: timestamp
18699
+ });
18700
+ changed.push(`tasks.upsert:${upsert2.id}`);
18701
+ projectChanged = true;
18702
+ continue;
18703
+ }
18704
+ let taskChanged = false;
18705
+ if (upsert2.title !== void 0 && existing.title !== upsert2.title) {
18706
+ existing.title = upsert2.title;
18707
+ taskChanged = true;
18708
+ }
18709
+ if (upsert2.status !== void 0 && existing.status !== upsert2.status) {
18710
+ existing.status = upsert2.status;
18711
+ taskChanged = true;
18712
+ }
18713
+ if (upsert2.ownerSessionId !== void 0 && existing.ownerSessionId !== upsert2.ownerSessionId) {
18714
+ existing.ownerSessionId = upsert2.ownerSessionId;
18715
+ taskChanged = true;
18716
+ }
18717
+ if (taskChanged) {
18718
+ existing.updatedAt = timestamp;
18719
+ changed.push(`tasks.upsert:${upsert2.id}`);
18720
+ projectChanged = true;
18721
+ }
18722
+ }
18723
+ if (projectChanged) project.updatedAt = timestamp;
18724
+ return changed;
18725
+ }
18726
+
17983
18727
  // packages/devlead/src/notification.ts
17984
18728
  import { SessionId as toSessionId } from "@deepseek-ai/dsh-session";
17985
18729
  import {
@@ -20201,7 +20945,8 @@ var Config = z2.object({
20201
20945
  maxListedSessions: z2.number().step(1).min(1).default(200),
20202
20946
  wakeColdSession: z2.boolean().default(true),
20203
20947
  defaultAgentPreset: z2.string().default(""),
20204
- questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS)
20948
+ questionTtlMs: z2.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_QUESTION_TTL_MS),
20949
+ boardPath: z2.string().default("")
20205
20950
  });
20206
20951
  function resolveConfig(config2) {
20207
20952
  const notificationBatchMs = config2.notificationBatchMs ?? 400;
@@ -20228,6 +20973,12 @@ function resolveConfig(config2) {
20228
20973
  if (!Number.isSafeInteger(questionTtlMs) || questionTtlMs < 0) {
20229
20974
  throw new TypeError("questionTtlMs must be a non-negative safe integer");
20230
20975
  }
20976
+ const boardPath = config2.boardPath ?? "";
20977
+ if (typeof boardPath !== "string") throw new TypeError("boardPath must be a string");
20978
+ const trimmedBoardPath = boardPath.trim();
20979
+ if (trimmedBoardPath.length > 0 && !isAbsolute3(trimmedBoardPath)) {
20980
+ throw new TypeError("boardPath must be an absolute path");
20981
+ }
20231
20982
  return {
20232
20983
  notificationBatchMs,
20233
20984
  actionRequiredBatchMs,
@@ -20235,7 +20986,8 @@ function resolveConfig(config2) {
20235
20986
  maxListedSessions,
20236
20987
  wakeColdSession,
20237
20988
  defaultAgentPreset: defaultAgentPreset.trim().length === 0 ? void 0 : defaultAgentPreset.trim(),
20238
- questionTtlMs
20989
+ questionTtlMs,
20990
+ ...trimmedBoardPath.length === 0 ? {} : { boardPath: trimmedBoardPath }
20239
20991
  };
20240
20992
  }
20241
20993
  function remoteCodeOf(error51) {
@@ -20366,12 +21118,38 @@ function validatedQuestions(value, kind) {
20366
21118
  };
20367
21119
  });
20368
21120
  }
21121
+ function devLeadBoardStartErrorOf(error51) {
21122
+ if (isDevLeadBoardError(error51)) return { code: error51.code, message: error51.message };
21123
+ return { code: "BOARD_IO_ERROR", message: thrownMessage(error51) };
21124
+ }
20369
21125
  var DevLeadService = class extends Service {
20370
21126
  static inject = ["agents", "sessions", "sessionProjections"];
20371
21127
  /** Loader schema, applied by the Loader before construction. */
20372
21128
  static Config = Config;
20373
21129
  /** Validated deployment configuration. */
20374
21130
  resolved;
21131
+ /**
21132
+ * Current project board store. It belongs to the one active lead Session (or
21133
+ * its configured override); with no active lead this is a disabled store
21134
+ * whose reads/writes report BOARD_DISABLED and whose summary is empty.
21135
+ */
21136
+ boardStore;
21137
+ /** Active lead Session whose workspace owns {@link boardStore}, when enabled. */
21138
+ boardLeadSessionIdValue;
21139
+ /** Whether the current board path comes from the deployment Config override. */
21140
+ boardPathOverrideValue = false;
21141
+ /** Latest board start failure; the rest of the service keeps serving without a board. */
21142
+ boardStartErrorValue;
21143
+ /** Why the board is disabled right now, or undefined while a store is active. */
21144
+ boardDisabledReasonValue;
21145
+ /** Serializes store swaps so two lead changes can never interleave one store. */
21146
+ boardSyncTail = Promise.resolve();
21147
+ /**
21148
+ * Original workspace root of each known lead Session, including cold ones
21149
+ * recovered from the persisted corpus (their header is not live in the
21150
+ * Session store, so the board path needs this cache).
21151
+ */
21152
+ leadWorkspaceRoots = /* @__PURE__ */ new Map();
20375
21153
  /** Awaited registration of the `devLead` projection unit. */
20376
21154
  projectionHandle;
20377
21155
  /** Host-driven projections replacing deprecated synchronous event readers. */
@@ -20677,6 +21455,7 @@ var DevLeadService = class extends Service {
20677
21455
  constructor(ctx, config2 = {}) {
20678
21456
  super(ctx, "devLead");
20679
21457
  this.resolved = resolveConfig(config2);
21458
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
20680
21459
  }
20681
21460
  async [Service.init]() {
20682
21461
  initializeRecordApi(this.ctx.logger);
@@ -20725,7 +21504,12 @@ var DevLeadService = class extends Service {
20725
21504
  opening?.catch(() => void 0),
20726
21505
  idempotencyOpening?.catch(() => void 0)
20727
21506
  ]);
20728
- await Promise.all([this.outbox?.close(), this.idempotencyStore?.close()]);
21507
+ await this.boardSyncTail.catch(() => void 0);
21508
+ await Promise.all([
21509
+ this.boardStore.close(),
21510
+ this.outbox?.close(),
21511
+ this.idempotencyStore?.close()
21512
+ ]);
20729
21513
  })();
20730
21514
  };
20731
21515
  }.bind(this), "devlead: cold rehydration");
@@ -20809,6 +21593,7 @@ var DevLeadService = class extends Service {
20809
21593
  knownActive: this.recoveredActive
20810
21594
  });
20811
21595
  this.recoveredActive = [];
21596
+ await this.syncBoardToActiveLead();
20812
21597
  await this.replayOutbox();
20813
21598
  this.initialized = true;
20814
21599
  }
@@ -21809,6 +22594,251 @@ var DevLeadService = class extends Service {
21809
22594
  return recordApiStatus();
21810
22595
  }
21811
22596
  // ---------------------------------------------------------------------------
22597
+ // Project board
22598
+ // ---------------------------------------------------------------------------
22599
+ /** Current project board store; disabled when no lead/workspace owns one. */
22600
+ get board() {
22601
+ return this.boardStore;
22602
+ }
22603
+ /** Active lead Session id whose workspace owns the current board, when enabled. */
22604
+ get boardLeadSessionId() {
22605
+ return this.boardLeadSessionIdValue;
22606
+ }
22607
+ /** Whether the current board path comes from the deployment Config override. */
22608
+ get boardPathOverride() {
22609
+ return this.boardPathOverrideValue;
22610
+ }
22611
+ /**
22612
+ * Latest project-board start failure, if any.
22613
+ *
22614
+ * A degraded board keeps DevLead itself loaded: tools then report the real
22615
+ * filesystem failure as a structured board error instead of the plugin
22616
+ * refusing to activate.
22617
+ */
22618
+ get boardStartError() {
22619
+ return this.boardStartErrorValue;
22620
+ }
22621
+ /**
22622
+ * Why the project board is currently disabled, when it is.
22623
+ *
22624
+ * `missing-workspace` reports a lead whose recorded original workspace root is
22625
+ * gone (or is no longer a directory): the board stays disabled with one
22626
+ * warning and the Host never recreates the workspace. An explicit deployment
22627
+ * `boardPath` override bypasses this check and keeps the existing pre-create
22628
+ * semantics. Undefined while a board store is active.
22629
+ */
22630
+ get boardDisabledReason() {
22631
+ return this.boardDisabledReasonValue;
22632
+ }
22633
+ /**
22634
+ * Resolve the calling lead's board file and hand it a tool read. Only the
22635
+ * unique active lead may reach the store; with no active lead/workspace the
22636
+ * call reports BOARD_DISABLED.
22637
+ * @param agent - calling live Agent.
22638
+ * @param filter - bounded project/task filtering.
22639
+ * @returns the bounded read result.
22640
+ * @throws {@link DevLeadError} `DEVLEAD_NOT_ENABLED` for a non-mode Agent.
22641
+ * @throws {@link DevLeadBoardError} `BOARD_DISABLED` when the caller is not
22642
+ * the active lead or its workspace records no board location.
22643
+ */
22644
+ async readBoard(agent, filter = {}) {
22645
+ if (!this.isEnabled(agent)) {
22646
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
22647
+ }
22648
+ this.requireActiveBoardLead(agent);
22649
+ return this.boardStore.read(filter);
22650
+ }
22651
+ /**
22652
+ * Dynamic board summary for one prompt-assembly Agent.
22653
+ *
22654
+ * Returns the cache-only text only when the caller is both an enabled lead
22655
+ * and the owner of the current store; a duplicate or non-owner enabled Agent
22656
+ * gets an empty summary instead of another workspace's board.
22657
+ * @param agent - Agent whose turn is being assembled.
22658
+ * @returns the bounded board summary, or an empty string.
22659
+ */
22660
+ boardSummaryFor(agent) {
22661
+ if (!this.isEnabled(agent)) return "";
22662
+ if (this.boardLeadSessionIdValue !== String(agent.id)) return "";
22663
+ return this.boardStore.summary();
22664
+ }
22665
+ /** Reject a board operation whose caller does not own the current store. */
22666
+ requireActiveBoardLead(agent) {
22667
+ if (this.boardLeadSessionIdValue === String(agent.id) && this.boardStore.path !== void 0) return;
22668
+ throw new DevLeadBoardError(
22669
+ "the DevLead project board is not active for the calling lead: no active lead workspace currently owns a board file",
22670
+ "BOARD_DISABLED"
22671
+ );
22672
+ }
22673
+ /** Serialize one active-lead → board synchronization. */
22674
+ syncBoardToActiveLead() {
22675
+ const run = this.boardSyncTail.then(() => this.applyActiveLeadBoard());
22676
+ this.boardSyncTail = run.catch(() => void 0);
22677
+ return run;
22678
+ }
22679
+ /** Apply the current lead identity to the board store (serialized). */
22680
+ async applyActiveLeadBoard() {
22681
+ if (this.disposed) return;
22682
+ const sessionId = this.activeSessionId;
22683
+ if (sessionId === void 0) {
22684
+ await this.swapBoardStore(void 0, void 0);
22685
+ return;
22686
+ }
22687
+ await this.swapBoardStore(sessionId, this.leadWorkspaceRootOf(sessionId));
22688
+ }
22689
+ /** Original workspace root for one lead: live header first, cached cold header second. */
22690
+ leadWorkspaceRootOf(sessionId) {
22691
+ const live = this.ctx.sessions.get(toSessionId3(sessionId));
22692
+ const fromLive = live?.header.cwd;
22693
+ if (fromLive !== void 0 && fromLive.trim().length > 0) {
22694
+ this.leadWorkspaceRoots.set(sessionId, fromLive);
22695
+ return fromLive;
22696
+ }
22697
+ return this.leadWorkspaceRoots.get(sessionId);
22698
+ }
22699
+ /** Cache one lead's original workspace root (cold leads are not in the live store). */
22700
+ rememberLeadWorkspaceRoot(sessionId, cwd) {
22701
+ if (cwd === void 0 || cwd.trim().length === 0) this.leadWorkspaceRoots.delete(sessionId);
22702
+ else this.leadWorkspaceRoots.set(sessionId, cwd);
22703
+ }
22704
+ /**
22705
+ * Point the service at the board file of one lead, releasing any previous
22706
+ * store/watcher.
22707
+ *
22708
+ * The path is the Config override when configured, otherwise the lead's
22709
+ * original workspace root plus `.dsh/devlead/board.json`. A derived path is
22710
+ * used only while that workspace root still exists as a directory: a cold
22711
+ * lead whose recorded root was deleted or moved must never make the Host
22712
+ * recreate the workspace (with just `.dsh/devlead`) to host the board file.
22713
+ * The same resolved file keeps its store (so a lead switch inside one
22714
+ * workspace does not churn the watcher); a changed path starts the new store
22715
+ * before the old one is closed, so an in-flight read never sees a
22716
+ * half-swapped service. A start failure is recorded and logged but never
22717
+ * rejects: the store is kept so its later operations report the real
22718
+ * filesystem failure, and the next same-path sync or path switch retries it.
22719
+ * @param sessionId - active lead identity, or undefined when disabled.
22720
+ * @param workspaceRoot - that lead's original workspace root, when known.
22721
+ */
22722
+ async swapBoardStore(sessionId, workspaceRoot) {
22723
+ const resolution = sessionId === void 0 ? { kind: "disabled", reason: "no-workspace" } : resolveDevLeadBoardPath({
22724
+ ...this.resolved.boardPath === void 0 ? {} : { override: this.resolved.boardPath },
22725
+ ...workspaceRoot === void 0 ? {} : { cwd: workspaceRoot }
22726
+ });
22727
+ if (resolution.kind === "disabled") {
22728
+ if (resolution.reason === "relative-workspace") {
22729
+ this.ctx.logger.warn(
22730
+ `devlead: Session "${sessionId ?? ""}" records a relative workspace root (${workspaceRoot ?? ""}); the project board stays disabled until it has an absolute workspace root`
22731
+ );
22732
+ }
22733
+ await this.disableBoardStore(resolution.reason);
22734
+ return;
22735
+ }
22736
+ const nextPath = resolution.path;
22737
+ const nextOverride = resolution.source === "override";
22738
+ if (resolution.source === "workspace" && !await this.workspaceRootExists(workspaceRoot)) {
22739
+ this.ctx.logger.warn(
22740
+ `devlead: Session "${sessionId ?? ""}" records a workspace root (${workspaceRoot ?? ""}) that is missing or not a directory; the project board stays disabled instead of recreating the workspace. Configure an absolute devlead boardPath if this Session should keep a project board.`
22741
+ );
22742
+ await this.disableBoardStore("missing-workspace");
22743
+ return;
22744
+ }
22745
+ const previous = this.boardStore;
22746
+ if (previous.path === nextPath) {
22747
+ this.boardLeadSessionIdValue = sessionId;
22748
+ this.boardPathOverrideValue = nextOverride;
22749
+ this.boardDisabledReasonValue = void 0;
22750
+ if (this.boardStartErrorValue !== void 0) {
22751
+ await this.retryBoardStart(previous, nextPath);
22752
+ }
22753
+ return;
22754
+ }
22755
+ const next = new DevLeadBoardStore(nextPath, this.ctx.logger);
22756
+ let startError;
22757
+ try {
22758
+ await next.start();
22759
+ } catch (error51) {
22760
+ startError = devLeadBoardStartErrorOf(error51);
22761
+ this.logBoardStartFailure(nextPath, startError);
22762
+ }
22763
+ this.boardStore = next;
22764
+ this.boardLeadSessionIdValue = sessionId;
22765
+ this.boardPathOverrideValue = nextOverride;
22766
+ this.boardDisabledReasonValue = void 0;
22767
+ this.boardStartErrorValue = startError;
22768
+ await this.closeBoardStore(previous);
22769
+ }
22770
+ /**
22771
+ * Whether one derived board's workspace root still exists as a directory.
22772
+ *
22773
+ * Any stat failure (missing, not a directory, unreadable) is treated as
22774
+ * unusable: the board is disabled instead of attempting a write under a root
22775
+ * the Host cannot verify.
22776
+ * @param workspaceRoot - the lead's recorded original workspace root.
22777
+ * @returns whether `start()` may safely prepare the board parent under it.
22778
+ */
22779
+ async workspaceRootExists(workspaceRoot) {
22780
+ if (workspaceRoot === void 0 || workspaceRoot.trim().length === 0) return false;
22781
+ try {
22782
+ return (await stat3(workspaceRoot)).isDirectory();
22783
+ } catch {
22784
+ return false;
22785
+ }
22786
+ }
22787
+ /** Retry `start()` on the current same-path store, keeping the degraded record on failure. */
22788
+ async retryBoardStart(store, path) {
22789
+ let startError;
22790
+ try {
22791
+ await store.start();
22792
+ } catch (error51) {
22793
+ startError = devLeadBoardStartErrorOf(error51);
22794
+ this.logBoardStartFailure(path, startError);
22795
+ }
22796
+ this.boardStartErrorValue = startError;
22797
+ }
22798
+ /** Log one board degradation without failing the surrounding service. */
22799
+ logBoardStartFailure(path, failure) {
22800
+ this.ctx.logger.warn(
22801
+ `devlead: project board at ${path} is degraded and DevLead stays loaded: ${failure.code}: ${failure.message}`
22802
+ );
22803
+ }
22804
+ /** Release any current board store and expose why the board is disabled. */
22805
+ async disableBoardStore(reason) {
22806
+ const previous = this.boardStore;
22807
+ this.boardLeadSessionIdValue = void 0;
22808
+ this.boardPathOverrideValue = false;
22809
+ this.boardStartErrorValue = void 0;
22810
+ this.boardDisabledReasonValue = reason;
22811
+ if (previous.path !== void 0) {
22812
+ this.boardStore = new DevLeadBoardStore(void 0, this.ctx.logger);
22813
+ await this.closeBoardStore(previous);
22814
+ }
22815
+ }
22816
+ /** Close one replaced store without letting cleanup failure break the swap. */
22817
+ async closeBoardStore(store) {
22818
+ if (store.path === void 0) return;
22819
+ try {
22820
+ await store.close();
22821
+ } catch (error51) {
22822
+ this.ctx.logger.warn(`devlead: could not close the previous project board store: ${thrownMessage(error51)}`);
22823
+ }
22824
+ }
22825
+ /**
22826
+ * Stamp the calling lead's identity onto one board mutation. The board file
22827
+ * path is derived from the active lead's workspace (or the Config override);
22828
+ * model callers supply only a logical patch.
22829
+ */
22830
+ async updateBoard(agent, patch, expectedRevision, signal) {
22831
+ if (!this.isEnabled(agent)) {
22832
+ throw new DevLeadError("DevLead mode is not enabled for the calling Agent", "DEVLEAD_NOT_ENABLED");
22833
+ }
22834
+ this.requireActiveBoardLead(agent);
22835
+ const title = this.ctx.get("sessionTitle")?.get(agent.session)?.title ?? "DevLead";
22836
+ return this.boardStore.update({
22837
+ ...patch,
22838
+ updatedBy: { sessionId: String(agent.id), title }
22839
+ }, expectedRevision, signal);
22840
+ }
22841
+ // ---------------------------------------------------------------------------
21812
22842
  // Mode
21813
22843
  // ---------------------------------------------------------------------------
21814
22844
  /**
@@ -21879,11 +22909,18 @@ var DevLeadService = class extends Service {
21879
22909
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21880
22910
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21881
22911
  await this.discardLeadReportState(String(agent.id));
21882
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22912
+ if (this.activeSessionId === String(agent.id)) {
22913
+ this.activeSessionId = void 0;
22914
+ await this.syncBoardToActiveLead();
22915
+ }
21883
22916
  return;
21884
22917
  }
21885
22918
  if (current.enabled === enabled) {
21886
- if (enabled) this.activeSessionId = String(agent.id);
22919
+ if (enabled) {
22920
+ this.activeSessionId = String(agent.id);
22921
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
22922
+ await this.syncBoardToActiveLead();
22923
+ }
21887
22924
  return;
21888
22925
  }
21889
22926
  if (enabled) {
@@ -21898,8 +22935,13 @@ var DevLeadService = class extends Service {
21898
22935
  appendRecordOrThrow(agent.session, DEVLEAD_MODE_RECORD_TYPE, modeRecord(enabled, Date.now()));
21899
22936
  await this.flushDurably(agent.session, `DevLead mode for Session "${agent.id}"`);
21900
22937
  await this.checkpointProjectionCache(agent.session, `DevLead mode for Session "${agent.id}"`);
21901
- if (enabled) this.activeSessionId = String(agent.id);
21902
- else if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22938
+ if (enabled) {
22939
+ this.activeSessionId = String(agent.id);
22940
+ this.rememberLeadWorkspaceRoot(String(agent.id), agent.session.header.cwd);
22941
+ } else if (this.activeSessionId === String(agent.id)) {
22942
+ this.activeSessionId = void 0;
22943
+ }
22944
+ await this.syncBoardToActiveLead();
21903
22945
  if (enabled) void this.replayOutbox();
21904
22946
  });
21905
22947
  }
@@ -21924,7 +22966,10 @@ var DevLeadService = class extends Service {
21924
22966
  await this.flushDurably(agent.session, `DevLead reset for Session "${agent.id}"`);
21925
22967
  await this.checkpointProjectionCache(agent.session, `DevLead reset for Session "${agent.id}"`);
21926
22968
  await this.discardLeadReportState(String(agent.id));
21927
- if (this.activeSessionId === String(agent.id)) this.activeSessionId = void 0;
22969
+ if (this.activeSessionId === String(agent.id)) {
22970
+ this.activeSessionId = void 0;
22971
+ await this.syncBoardToActiveLead();
22972
+ }
21928
22973
  });
21929
22974
  }
21930
22975
  /**
@@ -22045,7 +23090,7 @@ var DevLeadService = class extends Service {
22045
23090
  }
22046
23091
  signal?.throwIfAborted();
22047
23092
  try {
22048
- await mkdir(trimmed, { recursive: true });
23093
+ await mkdir2(trimmed, { recursive: true });
22049
23094
  } catch (mkdirError) {
22050
23095
  throw workspacePathFailure(mkdirError, trimmed);
22051
23096
  }
@@ -22368,8 +23413,8 @@ var DevLeadService = class extends Service {
22368
23413
  );
22369
23414
  }
22370
23415
  if (requestedModel !== void 0) await this.assertModelSelectable(requestedModel, signal);
22371
- const watch = request.watch ?? true;
22372
- const releaseWatch = watch ? this.reserveWatchSlot(agent) : void 0;
23416
+ const watch2 = request.watch ?? true;
23417
+ const releaseWatch = watch2 ? this.reserveWatchSlot(agent) : void 0;
22373
23418
  try {
22374
23419
  const workspace = await this.createTargetWorkspace(agent, request.workspace);
22375
23420
  signal?.throwIfAborted();
@@ -22396,7 +23441,7 @@ var DevLeadService = class extends Service {
22396
23441
  if (request.title !== void 0 && request.title.trim().length > 0) {
22397
23442
  this.tryRename(created.sessionId, request.title.trim());
22398
23443
  }
22399
- if (watch) {
23444
+ if (watch2) {
22400
23445
  await this.setWatching(agent, created.sessionId, true, signal, true);
22401
23446
  releaseWatch?.();
22402
23447
  }
@@ -22631,8 +23676,8 @@ var DevLeadService = class extends Service {
22631
23676
  );
22632
23677
  }
22633
23678
  this.assertSupervisionProofHeld(proof, targetId);
22634
- const watch = options.watch ?? true;
22635
- const added = watch && !watchedNow();
23679
+ const watch2 = options.watch ?? true;
23680
+ const added = watch2 && !watchedNow();
22636
23681
  if (added) await this.setWatching(agent, resolved.sessionId, true, signal);
22637
23682
  let admission;
22638
23683
  try {
@@ -23496,6 +24541,7 @@ var DevLeadService = class extends Service {
23496
24541
  archived: archived.has(sessionId),
23497
24542
  running: agent?.status === "running",
23498
24543
  createdAt: session.header.createdAt,
24544
+ ...session.header.cwd === void 0 ? {} : { cwd: session.header.cwd },
23499
24545
  enabledAt: 0
23500
24546
  });
23501
24547
  };
@@ -23581,6 +24627,7 @@ var DevLeadService = class extends Service {
23581
24627
  archived: archived.has(sessionId),
23582
24628
  running: false,
23583
24629
  createdAt: record2.header.createdAt,
24630
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
23584
24631
  enabledAt: lastEnabledAt(events) ?? 0
23585
24632
  });
23586
24633
  }
@@ -23647,7 +24694,10 @@ var DevLeadService = class extends Service {
23647
24694
  );
23648
24695
  return false;
23649
24696
  }
23650
- if (this.activeSessionId === occupant.sessionId) this.activeSessionId = void 0;
24697
+ if (this.activeSessionId === occupant.sessionId) {
24698
+ this.activeSessionId = void 0;
24699
+ await this.syncBoardToActiveLead();
24700
+ }
23651
24701
  this.ctx.logger.warn(
23652
24702
  `devlead: disabled DevLead mode for Session "${occupant.sessionId}" (${reason}); only one Session may hold DevLead mode at a time`
23653
24703
  );
@@ -23692,6 +24742,7 @@ var DevLeadService = class extends Service {
23692
24742
  if (!scanned.some((occupant) => occupant.sessionId === sessionId)) merged.delete(sessionId);
23693
24743
  }
23694
24744
  const active = [...merged.values()];
24745
+ for (const occupant of active) this.rememberLeadWorkspaceRoot(occupant.sessionId, occupant.cwd);
23695
24746
  if (active.length === 0) {
23696
24747
  this.activeSessionId = void 0;
23697
24748
  return;
@@ -23740,6 +24791,7 @@ var DevLeadService = class extends Service {
23740
24791
  this.ctx.logger.warn(`devlead: global DevLead admission reconciliation failed: ${thrownMessage(error51)}`);
23741
24792
  }
23742
24793
  }
24794
+ await this.syncBoardToActiveLead();
23743
24795
  }
23744
24796
  /** Reject any use of a tool surface while DevLead mode is off. */
23745
24797
  assertReady(agent) {
@@ -24105,6 +25157,7 @@ var DevLeadService = class extends Service {
24105
25157
  archived: archived.has(sessionId),
24106
25158
  running: false,
24107
25159
  createdAt: record2.header.createdAt,
25160
+ ...record2.header.cwd === void 0 ? {} : { cwd: record2.header.cwd },
24108
25161
  enabledAt: lastEnabledAt(events) ?? 0
24109
25162
  });
24110
25163
  }
@@ -26138,6 +27191,20 @@ ${text}` : text,
26138
27191
  var index_default = DevLeadService;
26139
27192
  export {
26140
27193
  Config,
27194
+ DEVLEAD_BOARD_DIR_SEGMENTS,
27195
+ DEVLEAD_BOARD_FILE_NAME,
27196
+ DEVLEAD_BOARD_ID_MAX,
27197
+ DEVLEAD_BOARD_MAX_BLOCKERS,
27198
+ DEVLEAD_BOARD_MAX_BYTES,
27199
+ DEVLEAD_BOARD_MAX_PROJECTS,
27200
+ DEVLEAD_BOARD_MAX_TASKS,
27201
+ DEVLEAD_BOARD_PATH_MAX,
27202
+ DEVLEAD_BOARD_READ_MAX_BYTES,
27203
+ DEVLEAD_BOARD_READ_MAX_TASKS,
27204
+ DEVLEAD_BOARD_SCHEMA_VERSION,
27205
+ DEVLEAD_BOARD_SUMMARY_MAX_BYTES,
27206
+ DEVLEAD_BOARD_TEXT_MAX,
27207
+ DEVLEAD_BOARD_TITLE_MAX,
26141
27208
  DEVLEAD_DEFAULT_MAX_WATCHED,
26142
27209
  DEVLEAD_DEFAULT_NOTIFICATION_RETENTION,
26143
27210
  DEVLEAD_ERROR_EXCERPT_MAX,
@@ -26157,6 +27224,8 @@ export {
26157
27224
  DEVLEAD_REPORT_SUMMARY_MAX,
26158
27225
  DEVLEAD_RESET_RECORD_TYPE,
26159
27226
  DEVLEAD_WATCH_RECORD_TYPE,
27227
+ DevLeadBoardError,
27228
+ DevLeadBoardStore,
26160
27229
  DevLeadError,
26161
27230
  DevLeadMetrics,
26162
27231
  DevLeadService,
@@ -26180,6 +27249,7 @@ export {
26180
27249
  decodeResetRecord,
26181
27250
  decodeWatchRecord,
26182
27251
  index_default as default,
27252
+ devLeadBoardSchema,
26183
27253
  devLeadModeProjectionDefinition,
26184
27254
  devLeadModeProjectionSchema,
26185
27255
  devLeadModeProjectionStateSchema,
@@ -26198,6 +27268,7 @@ export {
26198
27268
  emptyDevLeadProjectionState,
26199
27269
  emptyDevLeadWatchProjectionState,
26200
27270
  failureExcerpt,
27271
+ isDevLeadBoardError,
26201
27272
  isDevLeadError,
26202
27273
  isHumanDirectedTurn,
26203
27274
  legacyDevLeadRecordReason,
@@ -26205,11 +27276,13 @@ export {
26205
27276
  notificationId,
26206
27277
  notificationRecord,
26207
27278
  recordApiStatus,
27279
+ renderDevLeadBoardSummary,
26208
27280
  renderDevLeadNotice,
26209
27281
  repairRecord,
26210
27282
  reportAnswerRecord,
26211
27283
  reportRecord,
26212
27284
  representableInstant,
26213
27285
  resetRecord,
27286
+ resolveDevLeadBoardPath,
26214
27287
  watchRecord
26215
27288
  };