@adhdev/daemon-core 0.9.82-rc.464 → 0.9.82-rc.466

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -409,10 +409,10 @@ function readInjected(value) {
409
409
  }
410
410
  function getDaemonBuildInfo() {
411
411
  if (cached) return cached;
412
- const commit = readInjected(true ? "260f54788520ce6f51b44fa097d6d3ee337fe79d" : void 0) ?? "unknown";
413
- const commitShort = readInjected(true ? "260f5478" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
- const version = readInjected(true ? "0.9.82-rc.464" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
- const builtAt = readInjected(true ? "2026-07-05T05:20:43.844Z" : void 0);
412
+ const commit = readInjected(true ? "e0f04b7d54855e0f0d5ed4200078d95596ab9f6f" : void 0) ?? "unknown";
413
+ const commitShort = readInjected(true ? "e0f04b7d" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
414
+ const version = readInjected(true ? "0.9.82-rc.466" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
415
+ const builtAt = readInjected(true ? "2026-07-05T08:18:54.364Z" : void 0);
416
416
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
417
417
  return cached;
418
418
  }
@@ -486,8 +486,8 @@ function validateChangeImpactConfig(raw, source = "inline") {
486
486
  }
487
487
  return { valid: errors.length === 0, errors, config: errors.length === 0 ? config : void 0 };
488
488
  }
489
- function parseConfigText(path44, text) {
490
- if (/\.json$/i.test(path44)) return JSON.parse(text);
489
+ function parseConfigText(path45, text) {
490
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
491
491
  return yaml.load(text);
492
492
  }
493
493
  function loadChangeImpactConfig(repoRoot) {
@@ -1104,14 +1104,14 @@ async function deriveSubmoduleGitlinkStatuses(repo, options) {
1104
1104
  const lastCheckedAt = Date.now();
1105
1105
  const headOidByPath = /* @__PURE__ */ new Map();
1106
1106
  const entries = await Promise.all(
1107
- paths.filter((path44) => !ignoreSet.has(path44)).map(async (path44) => {
1108
- const repoPath = repo.repoRoot + "/" + path44;
1109
- const expected = await readGitlinkExpectedSha(repo, path44, options);
1107
+ paths.filter((path45) => !ignoreSet.has(path45)).map(async (path45) => {
1108
+ const repoPath = repo.repoRoot + "/" + path45;
1109
+ const expected = await readGitlinkExpectedSha(repo, path45, options);
1110
1110
  const actual = await readSubmoduleHeadSha(repo, repoPath, options);
1111
- if (actual) headOidByPath.set(path44, actual);
1111
+ if (actual) headOidByPath.set(path45, actual);
1112
1112
  const outOfSync = actual === null ? true : expected !== null && expected !== actual;
1113
1113
  return {
1114
- path: path44,
1114
+ path: path45,
1115
1115
  // Prefer the recorded gitlink SHA (matches the legacy column); fall back
1116
1116
  // to the checked-out SHA so the field is never empty when both are known.
1117
1117
  commit: expected ?? actual ?? "",
@@ -2559,12 +2559,12 @@ function readGitSubmodules(value, parentRepoRoot) {
2559
2559
  if (!Array.isArray(value)) return void 0;
2560
2560
  const submodules = value.map((entry) => {
2561
2561
  const submodule = readRecord(entry);
2562
- const path44 = readString2(submodule.path);
2562
+ const path45 = readString2(submodule.path);
2563
2563
  const commit = readString2(submodule.commit);
2564
- const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path44);
2565
- if (!path44 || !commit) return null;
2564
+ const repoPath = readString2(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path45);
2565
+ if (!path45 || !commit) return null;
2566
2566
  const result = {
2567
- path: path44,
2567
+ path: path45,
2568
2568
  commit,
2569
2569
  dirty: readBoolean(submodule.dirty) ?? false,
2570
2570
  outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
@@ -2895,10 +2895,10 @@ function getMeshConfigPath() {
2895
2895
  return (0, import_path3.join)(getConfigDir(), "meshes.json");
2896
2896
  }
2897
2897
  function loadMeshConfig() {
2898
- const path44 = getMeshConfigPath();
2899
- if (!(0, import_fs3.existsSync)(path44)) return { meshes: [] };
2898
+ const path45 = getMeshConfigPath();
2899
+ if (!(0, import_fs3.existsSync)(path45)) return { meshes: [] };
2900
2900
  try {
2901
- const raw = JSON.parse((0, import_fs3.readFileSync)(path44, "utf-8"));
2901
+ const raw = JSON.parse((0, import_fs3.readFileSync)(path45, "utf-8"));
2902
2902
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
2903
2903
  const config = raw;
2904
2904
  const migrated = migrateLoadedMeshConfig(config);
@@ -2947,16 +2947,16 @@ function normalizeCapabilityTags(value) {
2947
2947
  return tags.length ? tags : void 0;
2948
2948
  }
2949
2949
  function saveMeshConfig(config) {
2950
- const path44 = getMeshConfigPath();
2951
- (0, import_fs3.writeFileSync)(path44, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2950
+ const path45 = getMeshConfigPath();
2951
+ (0, import_fs3.writeFileSync)(path45, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
2952
2952
  }
2953
2953
  function normalizeRepoIdentity(remoteUrl) {
2954
2954
  let identity = remoteUrl.trim();
2955
2955
  if (identity.startsWith("http://") || identity.startsWith("https://")) {
2956
2956
  try {
2957
2957
  const url = new URL(identity);
2958
- const path44 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2959
- return `${url.hostname}/${path44}`;
2958
+ const path45 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
2959
+ return `${url.hostname}/${path45}`;
2960
2960
  } catch {
2961
2961
  }
2962
2962
  }
@@ -4203,59 +4203,59 @@ function isMeshEventScope(value) {
4203
4203
  function isNonEmptyString(value) {
4204
4204
  return typeof value === "string" && value.length > 0;
4205
4205
  }
4206
- function assertCoordinatorIdentity(raw, path44) {
4206
+ function assertCoordinatorIdentity(raw, path45) {
4207
4207
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4208
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path44, "must be an object");
4208
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path45, "must be an object");
4209
4209
  }
4210
4210
  const obj = raw;
4211
4211
  if (!isNonEmptyString(obj.daemonId)) {
4212
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.daemonId`, "must be a non-empty string");
4212
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.daemonId`, "must be a non-empty string");
4213
4213
  }
4214
4214
  if (!isNonEmptyString(obj.coordinatorRunId)) {
4215
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.coordinatorRunId`, "must be a non-empty string");
4215
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.coordinatorRunId`, "must be a non-empty string");
4216
4216
  }
4217
4217
  const sessionId = obj.sessionId;
4218
4218
  if (sessionId !== void 0 && !isNonEmptyString(sessionId)) {
4219
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.sessionId`, "must be a non-empty string when provided");
4219
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.sessionId`, "must be a non-empty string when provided");
4220
4220
  }
4221
4221
  return sessionId !== void 0 ? { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId, sessionId } : { daemonId: obj.daemonId, coordinatorRunId: obj.coordinatorRunId };
4222
4222
  }
4223
- function assertPendingMeshCoordinatorEventV2(raw, path44 = "$") {
4223
+ function assertPendingMeshCoordinatorEventV2(raw, path45 = "$") {
4224
4224
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4225
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path44, "must be an object");
4225
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, path45, "must be an object");
4226
4226
  }
4227
4227
  const obj = raw;
4228
4228
  if (!isSupportedMeshProtocolVersion(obj.protocolVersion)) {
4229
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
4229
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.protocolVersion`, `must be one of ${SUPPORTED_MESH_PROTOCOL_VERSIONS.join(", ")}`);
4230
4230
  }
4231
4231
  if (!isNonEmptyString(obj.eventId)) {
4232
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.eventId`, "must be a non-empty string");
4232
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.eventId`, "must be a non-empty string");
4233
4233
  }
4234
4234
  if (!isMeshEventScope(obj.scope)) {
4235
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
4235
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.scope`, `must be one of ${MESH_EVENT_SCOPES.join(", ")}`);
4236
4236
  }
4237
4237
  if (!isNonEmptyString(obj.event)) {
4238
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.event`, "must be a non-empty string");
4238
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.event`, "must be a non-empty string");
4239
4239
  }
4240
4240
  if (!isNonEmptyString(obj.meshId)) {
4241
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.meshId`, "must be a non-empty string");
4241
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.meshId`, "must be a non-empty string");
4242
4242
  }
4243
- const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path44}.dispatchedBy`);
4243
+ const dispatchedBy = assertCoordinatorIdentity(obj.dispatchedBy, `${path45}.dispatchedBy`);
4244
4244
  if (obj.scope === "unicast") {
4245
4245
  if (!obj.intendedFor) {
4246
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.intendedFor`, "unicast scope requires intendedFor");
4246
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.intendedFor`, "unicast scope requires intendedFor");
4247
4247
  }
4248
4248
  } else if (obj.intendedFor !== void 0) {
4249
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.intendedFor`, "only unicast scope may set intendedFor");
4249
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.intendedFor`, "only unicast scope may set intendedFor");
4250
4250
  }
4251
- const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path44}.intendedFor`) : void 0;
4251
+ const intendedFor = obj.intendedFor ? assertCoordinatorIdentity(obj.intendedFor, `${path45}.intendedFor`) : void 0;
4252
4252
  const metadata = obj.metadataEvent && typeof obj.metadataEvent === "object" && !Array.isArray(obj.metadataEvent) ? obj.metadataEvent : null;
4253
4253
  if (!metadata) {
4254
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.metadataEvent`, "must be an object");
4254
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.metadataEvent`, "must be an object");
4255
4255
  }
4256
4256
  const queuedAt = typeof obj.queuedAt === "number" && Number.isFinite(obj.queuedAt) ? obj.queuedAt : null;
4257
4257
  if (queuedAt === null) {
4258
- throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path44}.queuedAt`, "must be a finite number");
4258
+ throw new MeshContractViolationError(MESH_PROTOCOL_VERSION_V2, `${path45}.queuedAt`, "must be a finite number");
4259
4259
  }
4260
4260
  return {
4261
4261
  event: obj.event,
@@ -4418,10 +4418,10 @@ function rotateArchiveFile(meshId, archivePath) {
4418
4418
  }
4419
4419
  }
4420
4420
  function readArchivedCounts(meshId) {
4421
- const path44 = getArchivedCountsPath(meshId);
4422
- if (!(0, import_fs4.existsSync)(path44)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4421
+ const path45 = getArchivedCountsPath(meshId);
4422
+ if (!(0, import_fs4.existsSync)(path45)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4423
4423
  try {
4424
- return JSON.parse((0, import_fs4.readFileSync)(path44, "utf-8"));
4424
+ return JSON.parse((0, import_fs4.readFileSync)(path45, "utf-8"));
4425
4425
  } catch {
4426
4426
  return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: "" };
4427
4427
  }
@@ -5151,7 +5151,8 @@ var init_mesh_ledger = __esm({
5151
5151
  "task_completed",
5152
5152
  "task_failed",
5153
5153
  "task_stalled",
5154
- "recovery_attempted"
5154
+ "recovery_attempted",
5155
+ "session_auto_launch"
5155
5156
  ]);
5156
5157
  DEFAULT_LEDGER_SLICE_LIMIT = 100;
5157
5158
  MAX_LEDGER_SLICE_LIMIT = 500;
@@ -5643,11 +5644,11 @@ function readNodeReporter(node, key2) {
5643
5644
  function buildMeshNodeCapabilityTags(node, providerType) {
5644
5645
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
5645
5646
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
5646
- const os31 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5647
+ const os32 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
5647
5648
  const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
5648
5649
  return normalizeMeshCapabilityTags([
5649
5650
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
5650
- `os=${os31}`,
5651
+ `os=${os32}`,
5651
5652
  `arch=${arch2}`,
5652
5653
  ...provider ? [`provider=${provider}`] : [],
5653
5654
  // Worktree nodes automatically expose a "worktree=<branch>" tag so that
@@ -6601,10 +6602,10 @@ var init_mesh_runtime_store = __esm({
6601
6602
  this.migratedMeshIds.add(meshId);
6602
6603
  const count = this.db.prepare("SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?").get(meshId);
6603
6604
  if (count.count > 0) return;
6604
- const path44 = legacyQueuePath(meshId);
6605
- if (!(0, import_fs5.existsSync)(path44)) return;
6605
+ const path45 = legacyQueuePath(meshId);
6606
+ if (!(0, import_fs5.existsSync)(path45)) return;
6606
6607
  try {
6607
- const entries = JSON.parse((0, import_fs5.readFileSync)(path44, "utf-8"));
6608
+ const entries = JSON.parse((0, import_fs5.readFileSync)(path45, "utf-8"));
6608
6609
  if (!Array.isArray(entries)) return;
6609
6610
  const insert = this.db.prepare(`
6610
6611
  INSERT OR REPLACE INTO mesh_queue (
@@ -7344,6 +7345,10 @@ var init_mesh_runtime_store = __esm({
7344
7345
  }
7345
7346
  // ── G2: Event Ledger ────────────────────────────────────────────────────
7346
7347
  appendLedgerEntry(entry) {
7348
+ if (!entry.kind || !String(entry.kind).trim()) {
7349
+ LOG.warn("MeshRuntimeStore", `Refusing to append ledger entry with empty kind for mesh ${entry.meshId} (id ${entry.id})`);
7350
+ return;
7351
+ }
7347
7352
  this.db.prepare(
7348
7353
  `INSERT OR IGNORE INTO mesh_event_ledger
7349
7354
  (id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
@@ -7478,6 +7483,7 @@ var init_mesh_runtime_store = __esm({
7478
7483
  );
7479
7484
  this.db.transaction(() => {
7480
7485
  for (const e of entries) {
7486
+ if (!e.kind || !String(e.kind).trim()) continue;
7481
7487
  const result = stmt.run(
7482
7488
  e.id,
7483
7489
  e.meshId,
@@ -7772,6 +7778,41 @@ var init_mesh_runtime_store = __esm({
7772
7778
  `DELETE FROM mesh_pending_events WHERE id IN (${idList.map(() => "?").join(",")})`
7773
7779
  ).run(...idList).changes;
7774
7780
  }
7781
+ /**
7782
+ * Retention prune for mesh_pending_events. This table has no lifecycle GC of its
7783
+ * own: a drained row is soft-marked (drained=1) and RETAINED — deliberately, so
7784
+ * drainedEventIdsForMesh() has a durable v2-eventId dedup baseline — and an
7785
+ * undrained row queued for a coordinator that never returned (a dead/evicted
7786
+ * coordinator identity) stays drained=0 forever. Both accumulate without bound
7787
+ * (observed: tens of thousands of rows, mostly stale). This is the missing
7788
+ * retention step. Two independent windows:
7789
+ *
7790
+ * - drained rows older than `drainedOlderThanMs`: the coordinator consumed them
7791
+ * long ago; the only thing they still back is the eventId re-delivery guard,
7792
+ * which is only meaningful for the recent past (a re-delivery of a week-old
7793
+ * event cannot occur — its producer session is long gone). Safe to delete.
7794
+ * - UNDRAINED rows older than `undrainedOlderThanMs` (a much wider window):
7795
+ * these are orphaned events for a coordinator identity that never drained
7796
+ * them. Kept wide so a genuinely-offline-but-returning coordinator still
7797
+ * receives its backlog; only genuinely unrecoverable orphans are swept.
7798
+ *
7799
+ * Both windows key off `queued_at` (always present) — `drained_at` can be NULL on
7800
+ * legacy rows. Returns the number of rows deleted. Best-effort / idempotent:
7801
+ * running it repeatedly with nothing to prune is a cheap no-op.
7802
+ */
7803
+ prunePendingEvents(opts) {
7804
+ const now = Date.now();
7805
+ const drainedCutoff = now - Math.max(0, opts.drainedOlderThanMs);
7806
+ const undrainedCutoff = now - Math.max(0, opts.undrainedOlderThanMs);
7807
+ let removed = 0;
7808
+ removed += this.db.prepare(
7809
+ "DELETE FROM mesh_pending_events WHERE drained = 1 AND queued_at < ?"
7810
+ ).run(drainedCutoff).changes;
7811
+ removed += this.db.prepare(
7812
+ "DELETE FROM mesh_pending_events WHERE drained = 0 AND queued_at < ?"
7813
+ ).run(undrainedCutoff).changes;
7814
+ return removed;
7815
+ }
7775
7816
  };
7776
7817
  }
7777
7818
  });
@@ -8513,8 +8554,8 @@ function resolveMeshCoordinatorSetup(options) {
8513
8554
  }
8514
8555
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
8515
8556
  if (mcpConfig.mode === "auto_import") {
8516
- const path44 = mcpConfig.path?.trim();
8517
- if (!path44) {
8557
+ const path45 = mcpConfig.path?.trim();
8558
+ if (!path45) {
8518
8559
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
8519
8560
  }
8520
8561
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -8534,7 +8575,7 @@ function resolveMeshCoordinatorSetup(options) {
8534
8575
  return {
8535
8576
  kind: "auto_import",
8536
8577
  serverName,
8537
- configPath: resolveMcpConfigPath(path44, workspace),
8578
+ configPath: resolveMcpConfigPath(path45, workspace),
8538
8579
  configFormat: mcpConfig.format,
8539
8580
  mcpServer
8540
8581
  };
@@ -8735,8 +8776,8 @@ function stripCoordinatorWrapperFile(filePath) {
8735
8776
  const remaining = (existing.slice(0, openIdx) + existing.slice(closeIdx + CLOSE.length)).replace(/^\s*\n+/, "").replace(/\n+\s*$/, "");
8736
8777
  if (!remaining.trim()) {
8737
8778
  try {
8738
- const fs40 = require("fs");
8739
- fs40.unlinkSync(filePath);
8779
+ const fs41 = require("fs");
8780
+ fs41.unlinkSync(filePath);
8740
8781
  } catch {
8741
8782
  }
8742
8783
  } else {
@@ -8838,10 +8879,10 @@ function getRegistryPath() {
8838
8879
  return (0, import_path6.join)(getDaemonDataDir(), "mesh-coordinators.json");
8839
8880
  }
8840
8881
  function loadMeshCoordinatorRegistry() {
8841
- const path44 = getRegistryPath();
8842
- if (!(0, import_fs6.existsSync)(path44)) return;
8882
+ const path45 = getRegistryPath();
8883
+ if (!(0, import_fs6.existsSync)(path45)) return;
8843
8884
  try {
8844
- const raw = JSON.parse((0, import_fs6.readFileSync)(path44, "utf-8"));
8885
+ const raw = JSON.parse((0, import_fs6.readFileSync)(path45, "utf-8"));
8845
8886
  if (!Array.isArray(raw)) return;
8846
8887
  _registry.clear();
8847
8888
  for (const entry of raw) {
@@ -9012,8 +9053,8 @@ function validateMeshRefineConfig(config, source = "inline") {
9012
9053
  if (rejectedCommands.length) errors.push("one or more validation commands are invalid");
9013
9054
  return { valid: errors.length === 0, errors, bootstrapCommands, commands, rejectedCommands, bootstrapMode, deprecationWarnings };
9014
9055
  }
9015
- function parseConfigText2(path44, text) {
9016
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9056
+ function parseConfigText2(path45, text) {
9057
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9017
9058
  return yaml2.load(text);
9018
9059
  }
9019
9060
  function loadMeshRefineConfig(mesh, workspace) {
@@ -9420,8 +9461,8 @@ function isCleanIgnoringSubmoduleGitlinks(porcelain, submodulePaths) {
9420
9461
  const lines = porcelain.split(/\r?\n/).filter((line) => line.length > 0);
9421
9462
  for (const line of lines) {
9422
9463
  const status = line.slice(0, 2);
9423
- const path44 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
9424
- const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path44);
9464
+ const path45 = line.slice(3).trim().replace(/\\/g, "/").replace(/\/+$/, "");
9465
+ const isGitlinkPointerMove = (status === " M" || status === "M ") && submodulePaths.has(path45);
9425
9466
  if (!isGitlinkPointerMove) return false;
9426
9467
  }
9427
9468
  return true;
@@ -9456,8 +9497,8 @@ function shouldDeferDispatchForBootstrap(node, nowMs = Date.now()) {
9456
9497
  if (node?.worktreeBootstrap?.status !== "running") return false;
9457
9498
  return !isWorktreeBootstrapStaleRunning(node, nowMs);
9458
9499
  }
9459
- function parseConfigText3(path44, text) {
9460
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9500
+ function parseConfigText3(path45, text) {
9501
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9461
9502
  return yaml3.load(text);
9462
9503
  }
9463
9504
  function truncateOutput(value) {
@@ -9735,8 +9776,8 @@ __export(mesh_json_config_exports, {
9735
9776
  function isRecord3(value) {
9736
9777
  return !!value && typeof value === "object" && !Array.isArray(value);
9737
9778
  }
9738
- function parseConfigText4(path44, text) {
9739
- if (/\.json$/i.test(path44)) return JSON.parse(text);
9779
+ function parseConfigText4(path45, text) {
9780
+ if (/\.json$/i.test(path45)) return JSON.parse(text);
9740
9781
  return yaml4.load(text);
9741
9782
  }
9742
9783
  function normalizeOperatingNote(value) {
@@ -11692,10 +11733,10 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11692
11733
  const primaryDaemonId = daemonIds[0];
11693
11734
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
11694
11735
  const events = [];
11695
- for (const path44 of paths) {
11696
- if (!(0, import_fs11.existsSync)(path44)) continue;
11736
+ for (const path45 of paths) {
11737
+ if (!(0, import_fs11.existsSync)(path45)) continue;
11697
11738
  try {
11698
- const raw = (0, import_fs11.readFileSync)(path44, "utf-8");
11739
+ const raw = (0, import_fs11.readFileSync)(path45, "utf-8");
11699
11740
  const parsed = raw.split("\n").filter(Boolean).flatMap((line) => {
11700
11741
  try {
11701
11742
  return [JSON.parse(line)];
@@ -11703,7 +11744,7 @@ function readPendingMeshCoordinatorEventsFromDisk(meshId, coordinatorDaemonId) {
11703
11744
  return [];
11704
11745
  }
11705
11746
  });
11706
- const filtered = primaryDaemonId && path44 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11747
+ const filtered = primaryDaemonId && path45 === getPendingEventsPath(meshId) ? parsed.filter((e) => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId)) : parsed;
11707
11748
  events.push(...filtered);
11708
11749
  } catch {
11709
11750
  }
@@ -11768,11 +11809,26 @@ function reconcilePendingMeshCoordinatorEvents(meshId, events) {
11768
11809
  const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
11769
11810
  return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
11770
11811
  }
11771
- function trimPendingEventsIfNeeded(path44) {
11812
+ function prunePendingMeshCoordinatorEventsRetention() {
11772
11813
  try {
11773
- if (!(0, import_fs11.existsSync)(path44)) return;
11774
- if ((0, import_fs11.statSync)(path44).size <= MAX_PENDING_EVENTS_BYTES) return;
11775
- const lines = (0, import_fs11.readFileSync)(path44, "utf-8").split("\n").filter(Boolean);
11814
+ const removed = MeshRuntimeStore.getInstance().prunePendingEvents({
11815
+ drainedOlderThanMs: PENDING_EVENTS_DRAINED_RETENTION_MS,
11816
+ undrainedOlderThanMs: PENDING_EVENTS_UNDRAINED_RETENTION_MS
11817
+ });
11818
+ if (removed > 0) {
11819
+ LOG.info("MeshEvents", `Pruned ${removed} stale pending-event row(s) (drained >7d / undrained >30d)`);
11820
+ }
11821
+ return removed;
11822
+ } catch (e) {
11823
+ LOG.warn("MeshEvents", `Pending-event retention prune failed: ${e?.message || e}`);
11824
+ return 0;
11825
+ }
11826
+ }
11827
+ function trimPendingEventsIfNeeded(path45) {
11828
+ try {
11829
+ if (!(0, import_fs11.existsSync)(path45)) return;
11830
+ if ((0, import_fs11.statSync)(path45).size <= MAX_PENDING_EVENTS_BYTES) return;
11831
+ const lines = (0, import_fs11.readFileSync)(path45, "utf-8").split("\n").filter(Boolean);
11776
11832
  if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
11777
11833
  const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
11778
11834
  for (const line of dropped) {
@@ -11805,7 +11861,7 @@ function trimPendingEventsIfNeeded(path44) {
11805
11861
  LOG.warn("MeshEvents", `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
11806
11862
  }
11807
11863
  }
11808
- (0, import_fs11.writeFileSync)(path44, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11864
+ (0, import_fs11.writeFileSync)(path45, lines.slice(-MAX_PENDING_EVENTS_KEEP).join("\n") + "\n", "utf-8");
11809
11865
  } catch {
11810
11866
  }
11811
11867
  }
@@ -11813,18 +11869,24 @@ function stampPendingEventV2(event, hint) {
11813
11869
  if (event.protocolVersion === MESH_PROTOCOL_VERSION_V2 && readNonEmptyString2(event.eventId)) {
11814
11870
  return event;
11815
11871
  }
11816
- const dispatchedBy = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
11872
+ const coordinatorIdentity = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
11817
11873
  daemonId: event.targetCoordinatorDaemonId,
11818
11874
  coordinatorRunId: hint?.coordinatorRunId,
11819
11875
  sessionId: event.targetCoordinatorSessionId
11820
11876
  });
11821
- const intendedFor = hint?.intendedFor ?? dispatchedBy;
11877
+ const selfFallback = !coordinatorIdentity;
11878
+ const dispatchedBy = coordinatorIdentity ?? coordinatorIdentityFromEmitFields({
11879
+ daemonId: readNonEmptyString2(loadConfig().machineId)
11880
+ });
11881
+ const intendedFor = hint?.intendedFor ?? (selfFallback ? void 0 : coordinatorIdentity);
11822
11882
  const stamp = buildPendingEventEmitStamp({
11823
11883
  eventName: event.event,
11824
11884
  eventId: (0, import_crypto8.randomUUID)(),
11825
11885
  dispatchedBy,
11826
11886
  intendedFor,
11827
- scope: hint?.scope
11887
+ // Force broadcast for the self-fallback so a unicast-defaulting terminal
11888
+ // event isn't addressed to this daemon alone; an explicit hint still wins.
11889
+ scope: hint?.scope ?? (selfFallback ? "broadcast" : void 0)
11828
11890
  });
11829
11891
  if (!stamp) return event;
11830
11892
  return {
@@ -11868,6 +11930,9 @@ function readV2EnvelopeFromWire(payload) {
11868
11930
  }
11869
11931
  function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11870
11932
  const event = stampPendingEventV2(rawEvent, hint);
11933
+ return persistPendingMeshCoordinatorEvent(event);
11934
+ }
11935
+ function persistPendingMeshCoordinatorEvent(event) {
11871
11936
  try {
11872
11937
  if (hasPendingRefineTerminalEventDuplicate(event)) {
11873
11938
  LOG.info("MeshEvents", `Suppressed duplicate pending ${event.event} for refine job ${readRefineJobId2(event)}`);
@@ -11902,9 +11967,9 @@ function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11902
11967
  } catch {
11903
11968
  }
11904
11969
  try {
11905
- const path44 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11906
- trimPendingEventsIfNeeded(path44);
11907
- (0, import_fs11.appendFileSync)(path44, JSON.stringify(event) + "\n", "utf-8");
11970
+ const path45 = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
11971
+ trimPendingEventsIfNeeded(path45);
11972
+ (0, import_fs11.appendFileSync)(path45, JSON.stringify(event) + "\n", "utf-8");
11908
11973
  } catch (e) {
11909
11974
  if (!sqliteOk) throw e;
11910
11975
  LOG.warn("MeshEvents", `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
@@ -11915,10 +11980,10 @@ function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11915
11980
  return false;
11916
11981
  }
11917
11982
  }
11918
- function atomicDrainFile(path44) {
11919
- const tmpPath = `${path44}.draining`;
11983
+ function atomicDrainFile(path45) {
11984
+ const tmpPath = `${path45}.draining`;
11920
11985
  try {
11921
- (0, import_fs11.renameSync)(path44, tmpPath);
11986
+ (0, import_fs11.renameSync)(path45, tmpPath);
11922
11987
  } catch {
11923
11988
  return null;
11924
11989
  }
@@ -11937,10 +12002,10 @@ function atomicDrainFile(path44) {
11937
12002
  return null;
11938
12003
  }
11939
12004
  }
11940
- function selectiveDrainFile(path44, predicate) {
11941
- const tmpPath = `${path44}.draining`;
12005
+ function selectiveDrainFile(path45, predicate) {
12006
+ const tmpPath = `${path45}.draining`;
11942
12007
  try {
11943
- (0, import_fs11.renameSync)(path44, tmpPath);
12008
+ (0, import_fs11.renameSync)(path45, tmpPath);
11944
12009
  } catch {
11945
12010
  return [];
11946
12011
  }
@@ -11972,12 +12037,12 @@ function selectiveDrainFile(path44, predicate) {
11972
12037
  }
11973
12038
  try {
11974
12039
  if (keptLines.length > 0) {
11975
- (0, import_fs11.writeFileSync)(path44, keptLines.join("\n") + "\n", "utf-8");
12040
+ (0, import_fs11.writeFileSync)(path45, keptLines.join("\n") + "\n", "utf-8");
11976
12041
  }
11977
12042
  (0, import_fs11.unlinkSync)(tmpPath);
11978
12043
  } catch {
11979
12044
  try {
11980
- if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path44)) (0, import_fs11.renameSync)(tmpPath, path44);
12045
+ if ((0, import_fs11.existsSync)(tmpPath) && !(0, import_fs11.existsSync)(path45)) (0, import_fs11.renameSync)(tmpPath, path45);
11981
12046
  } catch {
11982
12047
  }
11983
12048
  return [];
@@ -12018,16 +12083,16 @@ function drainPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId, opts) {
12018
12083
  LOG.warn("MeshEvents", `SQLite pending-event drain failed for mesh ${meshId}; JSONL fallback only: ${e?.message || e}`);
12019
12084
  }
12020
12085
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12021
- for (const path44 of paths) {
12022
- const isSharedFile = !!primaryDaemonId && path44 === getPendingEventsPath(meshId);
12086
+ for (const path45 of paths) {
12087
+ const isSharedFile = !!primaryDaemonId && path45 === getPendingEventsPath(meshId);
12023
12088
  const targets = (e) => !isSharedFile || !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId);
12024
12089
  if (onlyEvents) {
12025
- for (const event of selectiveDrainFile(path44, (e) => targets(e) && matchesFilter(e.event))) {
12090
+ for (const event of selectiveDrainFile(path45, (e) => targets(e) && matchesFilter(e.event))) {
12026
12091
  pushUnique(event);
12027
12092
  }
12028
12093
  continue;
12029
12094
  }
12030
- const content = atomicDrainFile(path44);
12095
+ const content = atomicDrainFile(path45);
12031
12096
  if (!content) continue;
12032
12097
  const parsed = content.split("\n").filter(Boolean).flatMap((line) => {
12033
12098
  try {
@@ -12068,9 +12133,9 @@ function retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId)
12068
12133
  const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
12069
12134
  const primaryDaemonId = daemonIds[0];
12070
12135
  const paths = primaryDaemonId ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12071
- for (const path44 of paths) {
12136
+ for (const path45 of paths) {
12072
12137
  try {
12073
- removed += selectiveDrainFile(path44, matchesTask).length;
12138
+ removed += selectiveDrainFile(path45, matchesTask).length;
12074
12139
  } catch {
12075
12140
  }
12076
12141
  }
@@ -12122,14 +12187,14 @@ function clearPendingMeshCoordinatorEvents(meshId, coordinatorDaemonId) {
12122
12187
  } catch {
12123
12188
  }
12124
12189
  const paths = coordinatorDaemonId ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)] : [getPendingEventsPath(meshId)];
12125
- for (const path44 of paths) {
12126
- if ((0, import_fs11.existsSync)(path44)) try {
12127
- (0, import_fs11.unlinkSync)(path44);
12190
+ for (const path45 of paths) {
12191
+ if ((0, import_fs11.existsSync)(path45)) try {
12192
+ (0, import_fs11.unlinkSync)(path45);
12128
12193
  } catch {
12129
12194
  }
12130
12195
  }
12131
12196
  }
12132
- var import_fs11, import_path10, import_crypto8, REFINE_TERMINAL_EVENTS, meshV2DrainCounters, warnedV2Violations, TERMINAL_COMPLETION_EVENTS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP;
12197
+ var import_fs11, import_path10, import_crypto8, REFINE_TERMINAL_EVENTS, meshV2DrainCounters, warnedV2Violations, TERMINAL_COMPLETION_EVENTS, MAX_PENDING_EVENTS_BYTES, MAX_PENDING_EVENTS_KEEP, PENDING_EVENTS_DRAINED_RETENTION_MS, PENDING_EVENTS_UNDRAINED_RETENTION_MS;
12133
12198
  var init_mesh_events_pending = __esm({
12134
12199
  "src/mesh/mesh-events-pending.ts"() {
12135
12200
  "use strict";
@@ -12137,6 +12202,7 @@ var init_mesh_events_pending = __esm({
12137
12202
  import_path10 = require("path");
12138
12203
  import_crypto8 = require("crypto");
12139
12204
  init_logger();
12205
+ init_config();
12140
12206
  init_mesh_ledger();
12141
12207
  init_mesh_runtime_store();
12142
12208
  init_mesh_events_utils();
@@ -12172,6 +12238,8 @@ var init_mesh_events_pending = __esm({
12172
12238
  TERMINAL_COMPLETION_EVENTS = /* @__PURE__ */ new Set(["agent:generating_completed", "agent:stopped"]);
12173
12239
  MAX_PENDING_EVENTS_BYTES = 100 * 1024;
12174
12240
  MAX_PENDING_EVENTS_KEEP = 50;
12241
+ PENDING_EVENTS_DRAINED_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
12242
+ PENDING_EVENTS_UNDRAINED_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
12175
12243
  }
12176
12244
  });
12177
12245
 
@@ -12804,9 +12872,9 @@ function findBinary(name) {
12804
12872
  for (const ext of exes) {
12805
12873
  const fullPath = path11.join(p, trimmed + ext);
12806
12874
  try {
12807
- const fs40 = require("fs");
12808
- if (fs40.existsSync(fullPath)) {
12809
- const stat2 = fs40.statSync(fullPath);
12875
+ const fs41 = require("fs");
12876
+ if (fs41.existsSync(fullPath)) {
12877
+ const stat2 = fs41.statSync(fullPath);
12810
12878
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
12811
12879
  return fullPath;
12812
12880
  }
@@ -12820,12 +12888,12 @@ function findBinary(name) {
12820
12888
  function isScriptBinary(binaryPath) {
12821
12889
  if (!path11.isAbsolute(binaryPath)) return false;
12822
12890
  try {
12823
- const fs40 = require("fs");
12824
- const resolved = fs40.realpathSync(binaryPath);
12891
+ const fs41 = require("fs");
12892
+ const resolved = fs41.realpathSync(binaryPath);
12825
12893
  const head = Buffer.alloc(8);
12826
- const fd = fs40.openSync(resolved, "r");
12827
- fs40.readSync(fd, head, 0, 8, 0);
12828
- fs40.closeSync(fd);
12894
+ const fd = fs41.openSync(resolved, "r");
12895
+ fs41.readSync(fd, head, 0, 8, 0);
12896
+ fs41.closeSync(fd);
12829
12897
  let i = 0;
12830
12898
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
12831
12899
  return head[i] === 35 && head[i + 1] === 33;
@@ -12836,12 +12904,12 @@ function isScriptBinary(binaryPath) {
12836
12904
  function looksLikeMachOOrElf(filePath) {
12837
12905
  if (!path11.isAbsolute(filePath)) return false;
12838
12906
  try {
12839
- const fs40 = require("fs");
12840
- const resolved = fs40.realpathSync(filePath);
12907
+ const fs41 = require("fs");
12908
+ const resolved = fs41.realpathSync(filePath);
12841
12909
  const buf = Buffer.alloc(8);
12842
- const fd = fs40.openSync(resolved, "r");
12843
- fs40.readSync(fd, buf, 0, 8, 0);
12844
- fs40.closeSync(fd);
12910
+ const fd = fs41.openSync(resolved, "r");
12911
+ fs41.readSync(fd, buf, 0, 8, 0);
12912
+ fs41.closeSync(fd);
12845
12913
  let i = 0;
12846
12914
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
12847
12915
  const b = buf.subarray(i);
@@ -17229,6 +17297,11 @@ function sweepExpiredRemoteIdleSessions() {
17229
17297
  MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
17230
17298
  } catch {
17231
17299
  }
17300
+ const now = Date.now();
17301
+ if (now - lastPendingEventsPruneAt >= PENDING_EVENTS_PRUNE_INTERVAL_MS) {
17302
+ lastPendingEventsPruneAt = now;
17303
+ prunePendingMeshCoordinatorEventsRetention();
17304
+ }
17232
17305
  }
17233
17306
  function isIntentionalCleanupStopMetadata(event) {
17234
17307
  return event.intentional === true || event.intentionalStop === true || event.operatorCleanup === true || event.reason === "operator_cleanup" || event.stopReason === "operator_cleanup" || event.cleanupReason === "operator_cleanup" || event.source === "mesh_cleanup_sessions" || event.source === "mesh_remove_node";
@@ -18287,7 +18360,7 @@ function setupMeshEventForwarding(components) {
18287
18360
  flushPendingForMeshIdleCoordinators(components, routing.meshId);
18288
18361
  });
18289
18362
  }
18290
- var REMOTE_IDLE_SESSION_TTL_MS, meshByWorkspaceCache, MESH_WORKSPACE_CACHE_TTL_MS, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, RECONCILED_COMPLETION_SOURCES, coordinatorForwardLanes;
18363
+ var REMOTE_IDLE_SESSION_TTL_MS, meshByWorkspaceCache, MESH_WORKSPACE_CACHE_TTL_MS, lastPendingEventsPruneAt, PENDING_EVENTS_PRUNE_INTERVAL_MS, INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS, RECENT_COMPLETION_FINGERPRINT_TTL_MS, RECONCILED_COMPLETION_SOURCES, coordinatorForwardLanes;
18291
18364
  var init_mesh_event_forwarding = __esm({
18292
18365
  "src/mesh/mesh-event-forwarding.ts"() {
18293
18366
  "use strict";
@@ -18314,6 +18387,8 @@ var init_mesh_event_forwarding = __esm({
18314
18387
  REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1e3;
18315
18388
  meshByWorkspaceCache = /* @__PURE__ */ new Map();
18316
18389
  MESH_WORKSPACE_CACHE_TTL_MS = 5e3;
18390
+ lastPendingEventsPruneAt = 0;
18391
+ PENDING_EVENTS_PRUNE_INTERVAL_MS = 60 * 60 * 1e3;
18317
18392
  INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1e3;
18318
18393
  RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1e3;
18319
18394
  RECONCILED_COMPLETION_SOURCES = /* @__PURE__ */ new Set([
@@ -18336,40 +18411,48 @@ var init_mesh_events_coordinator = __esm({
18336
18411
  }
18337
18412
  });
18338
18413
 
18339
- // src/mesh/mesh-reconcile-loop.ts
18340
- function resolveAutoPruneMinAgeMs() {
18341
- const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
18342
- if (raw) {
18343
- const parsed = Number.parseInt(raw, 10);
18344
- if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
18345
- }
18346
- return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
18414
+ // src/mesh/mesh-reconcile-identity.ts
18415
+ function resolveCoordinatorDaemonIds(components) {
18416
+ const statusInstanceId = readNonEmptyString2(components.statusInstanceId);
18417
+ const machineId = readNonEmptyString2(loadConfig().machineId);
18418
+ return expandDaemonIdForms([statusInstanceId, machineId]);
18347
18419
  }
18348
- function resolvePendingHeldDrainEscalateMs() {
18349
- return resolveTunedReconcileMs("MESH_PENDING_HELD_DRAIN_ESCALATE_MS", DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, 4e3, 5 * 6e4);
18420
+ function daemonHostsMesh(mesh, daemonIds) {
18421
+ const host = mesh.meshHost;
18422
+ if (!host) return true;
18423
+ if (host.role && host.role !== "host") return false;
18424
+ const hostDaemonId = readNonEmptyString2(host.hostDaemonId);
18425
+ if (!hostDaemonId) return true;
18426
+ return daemonIdListIncludes(daemonIds, hostDaemonId);
18350
18427
  }
18351
- function resolveReconcileIntervalMs() {
18352
- const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
18353
- if (raw) {
18354
- const parsed = Number.parseInt(raw, 10);
18355
- if (Number.isFinite(parsed) && parsed >= 1e3 && parsed <= 6e4) return parsed;
18356
- }
18357
- return DEFAULT_RECONCILE_INTERVAL_MS;
18428
+ function daemonIdListIncludes(ids, id) {
18429
+ if (!id) return false;
18430
+ return ids.some((candidate) => candidate === id || daemonIdsEquivalent(candidate, id));
18358
18431
  }
18359
- function resolveTunedReconcileMs(envName, def, min, max) {
18360
- const raw = readNonEmptyString2(process.env[envName]);
18361
- if (raw) {
18362
- const parsed = Number.parseInt(raw, 10);
18363
- if (Number.isFinite(parsed) && parsed >= min && parsed <= max) return parsed;
18432
+ function resolveCoordinatorSelfIds(mesh, drainDaemonIds) {
18433
+ const ids = new Set(drainDaemonIds);
18434
+ for (const node of mesh.nodes) {
18435
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
18436
+ const nodeMachineId = readNonEmptyString2(node.machineId);
18437
+ const isSelf = nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId) || nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId);
18438
+ if (!isSelf) continue;
18439
+ if (nodeDaemonId) ids.add(nodeDaemonId);
18440
+ if (nodeMachineId) ids.add(nodeMachineId);
18364
18441
  }
18365
- return def;
18366
- }
18367
- function resolveAckedDeathDeadlineMs() {
18368
- return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_DEATH_DEADLINE_MS", 8 * 6e4, 0, 60 * 6e4);
18369
- }
18370
- function resolveAckedTranscriptFastTrackGraceMs() {
18371
- return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS", 4e4, 0, 5 * 6e4);
18442
+ const hostDaemonId = readNonEmptyString2(mesh.meshHost?.hostDaemonId);
18443
+ if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
18444
+ return [...ids];
18372
18445
  }
18446
+ var init_mesh_reconcile_identity = __esm({
18447
+ "src/mesh/mesh-reconcile-identity.ts"() {
18448
+ "use strict";
18449
+ init_config();
18450
+ init_dist();
18451
+ init_mesh_events_utils();
18452
+ }
18453
+ });
18454
+
18455
+ // src/mesh/mesh-reconcile-v2-backstop.ts
18373
18456
  function getMeshV2BackstopCounters() {
18374
18457
  return { ...meshV2BackstopCounters };
18375
18458
  }
@@ -18385,6 +18468,37 @@ function recordBackstopFire(kind, detail) {
18385
18468
  LOG.warn("MeshReconcileV2", `v2 ENFORCE last-resort backstop fired (${kind}): ${detail}. Under a healthy v2 completion contract this should be 0 \u2014 a worker's real terminal emit was lost/late.`);
18386
18469
  }
18387
18470
  }
18471
+ var meshV2BackstopCounters;
18472
+ var init_mesh_reconcile_v2_backstop = __esm({
18473
+ "src/mesh/mesh-reconcile-v2-backstop.ts"() {
18474
+ "use strict";
18475
+ init_logger();
18476
+ meshV2BackstopCounters = {
18477
+ /** PHASE-4 transcript synthesis actually reconciled a missing completion. */
18478
+ phase4SynthesisFired: 0,
18479
+ /** Acked-hold transcript fast-track promoted a synth ahead of the death deadline. */
18480
+ ackedHoldFastTrackFired: 0,
18481
+ /** Acked-hold death-deadline backstop released a held synth (the 8-min net). */
18482
+ ackedHoldDeathDeadlineFired: 0
18483
+ };
18484
+ }
18485
+ });
18486
+
18487
+ // src/mesh/mesh-reconcile-acked-hold.ts
18488
+ function resolveTunedReconcileMs(envName, def, min, max) {
18489
+ const raw = readNonEmptyString2(process.env[envName]);
18490
+ if (raw) {
18491
+ const parsed = Number.parseInt(raw, 10);
18492
+ if (Number.isFinite(parsed) && parsed >= min && parsed <= max) return parsed;
18493
+ }
18494
+ return def;
18495
+ }
18496
+ function resolveAckedDeathDeadlineMs() {
18497
+ return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_DEATH_DEADLINE_MS", 8 * 6e4, 0, 60 * 6e4);
18498
+ }
18499
+ function resolveAckedTranscriptFastTrackGraceMs() {
18500
+ return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS", 4e4, 0, 5 * 6e4);
18501
+ }
18388
18502
  function inFlightSynthKey(meshId, taskId) {
18389
18503
  return `${meshId}::${taskId}`;
18390
18504
  }
@@ -18467,36 +18581,54 @@ function rehydrateAckedHoldsForMesh(meshId) {
18467
18581
  LOG.info("MeshReconcile", `Rehydrated ${rows.length} persisted acked-hold row(s) for mesh ${meshId} after (re)start`);
18468
18582
  }
18469
18583
  }
18470
- function resolveCoordinatorDaemonIds(components) {
18471
- const statusInstanceId = readNonEmptyString2(components.statusInstanceId);
18472
- const machineId = readNonEmptyString2(loadConfig().machineId);
18473
- return expandDaemonIdForms([statusInstanceId, machineId]);
18584
+ function collectHeldSynthKeysForMesh(meshId) {
18585
+ const heldKeys = /* @__PURE__ */ new Set();
18586
+ for (const key2 of inFlightAckedHoldState.keys()) {
18587
+ if (key2.startsWith(`${meshId}::`)) heldKeys.add(key2);
18588
+ }
18589
+ const store = holdStore();
18590
+ if (store) {
18591
+ try {
18592
+ for (const row of store.listInflightHoldsByMesh(meshId)) {
18593
+ heldKeys.add(inFlightSynthKey(meshId, row.taskId));
18594
+ }
18595
+ } catch {
18596
+ }
18597
+ }
18598
+ return heldKeys;
18474
18599
  }
18475
- function daemonHostsMesh(mesh, daemonIds) {
18476
- const host = mesh.meshHost;
18477
- if (!host) return true;
18478
- if (host.role && host.role !== "host") return false;
18479
- const hostDaemonId = readNonEmptyString2(host.hostDaemonId);
18480
- if (!hostDaemonId) return true;
18481
- return daemonIdListIncludes(daemonIds, hostDaemonId);
18600
+ var ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, rehydratedHoldMeshes;
18601
+ var init_mesh_reconcile_acked_hold = __esm({
18602
+ "src/mesh/mesh-reconcile-acked-hold.ts"() {
18603
+ "use strict";
18604
+ init_logger();
18605
+ init_mesh_runtime_store();
18606
+ init_mesh_events_utils();
18607
+ ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
18608
+ inFlightAckedHoldState = /* @__PURE__ */ new Map();
18609
+ rehydratedHoldMeshes = /* @__PURE__ */ new Set();
18610
+ }
18611
+ });
18612
+
18613
+ // src/mesh/mesh-reconcile-loop.ts
18614
+ function resolveAutoPruneMinAgeMs() {
18615
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
18616
+ if (raw) {
18617
+ const parsed = Number.parseInt(raw, 10);
18618
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
18619
+ }
18620
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
18482
18621
  }
18483
- function daemonIdListIncludes(ids, id) {
18484
- if (!id) return false;
18485
- return ids.some((candidate) => candidate === id || daemonIdsEquivalent(candidate, id));
18622
+ function resolvePendingHeldDrainEscalateMs() {
18623
+ return resolveTunedReconcileMs("MESH_PENDING_HELD_DRAIN_ESCALATE_MS", DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, 4e3, 5 * 6e4);
18486
18624
  }
18487
- function resolveCoordinatorSelfIds(mesh, drainDaemonIds) {
18488
- const ids = new Set(drainDaemonIds);
18489
- for (const node of mesh.nodes) {
18490
- const nodeDaemonId = readNonEmptyString2(node.daemonId);
18491
- const nodeMachineId = readNonEmptyString2(node.machineId);
18492
- const isSelf = nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId) || nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId);
18493
- if (!isSelf) continue;
18494
- if (nodeDaemonId) ids.add(nodeDaemonId);
18495
- if (nodeMachineId) ids.add(nodeMachineId);
18625
+ function resolveReconcileIntervalMs() {
18626
+ const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
18627
+ if (raw) {
18628
+ const parsed = Number.parseInt(raw, 10);
18629
+ if (Number.isFinite(parsed) && parsed >= 1e3 && parsed <= 6e4) return parsed;
18496
18630
  }
18497
- const hostDaemonId = readNonEmptyString2(mesh.meshHost?.hostDaemonId);
18498
- if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
18499
- return [...ids];
18631
+ return DEFAULT_RECONCILE_INTERVAL_MS;
18500
18632
  }
18501
18633
  function findLiveCoordinators(components) {
18502
18634
  const out = [];
@@ -19262,19 +19394,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
19262
19394
  const activeTaskKeys = new Set(
19263
19395
  dispatches.map((d) => readNonEmptyString2(d.taskId)).filter(Boolean).map((taskId) => inFlightSynthKey(mesh.id, taskId))
19264
19396
  );
19265
- const heldKeys = /* @__PURE__ */ new Set();
19266
- for (const key2 of inFlightAckedHoldState.keys()) {
19267
- if (key2.startsWith(`${mesh.id}::`)) heldKeys.add(key2);
19268
- }
19269
- const store = holdStore();
19270
- if (store) {
19271
- try {
19272
- for (const row of store.listInflightHoldsByMesh(mesh.id)) {
19273
- heldKeys.add(inFlightSynthKey(mesh.id, row.taskId));
19274
- }
19275
- } catch {
19276
- }
19277
- }
19397
+ const heldKeys = collectHeldSynthKeysForMesh(mesh.id);
19278
19398
  for (const key2 of heldKeys) {
19279
19399
  if (!activeTaskKeys.has(key2)) deleteHoldState(key2, mesh.id);
19280
19400
  }
@@ -19550,7 +19670,7 @@ function setupMeshReconcileLoop(components) {
19550
19670
  }
19551
19671
  };
19552
19672
  }
19553
- var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, rehydratedHoldMeshes, meshV2BackstopCounters, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
19673
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
19554
19674
  var init_mesh_reconcile_loop = __esm({
19555
19675
  "src/mesh/mesh-reconcile-loop.ts"() {
19556
19676
  "use strict";
@@ -19572,20 +19692,14 @@ var init_mesh_reconcile_loop = __esm({
19572
19692
  init_mesh_active_work();
19573
19693
  init_mesh_events_stale();
19574
19694
  init_chat_message_normalization();
19695
+ init_mesh_reconcile_identity();
19696
+ init_mesh_reconcile_v2_backstop();
19697
+ init_mesh_reconcile_acked_hold();
19698
+ init_mesh_reconcile_v2_backstop();
19699
+ init_mesh_reconcile_acked_hold();
19575
19700
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
19576
19701
  DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
19577
19702
  DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12e3;
19578
- ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
19579
- inFlightAckedHoldState = /* @__PURE__ */ new Map();
19580
- rehydratedHoldMeshes = /* @__PURE__ */ new Set();
19581
- meshV2BackstopCounters = {
19582
- /** PHASE-4 transcript synthesis actually reconciled a missing completion. */
19583
- phase4SynthesisFired: 0,
19584
- /** Acked-hold transcript fast-track promoted a synth ahead of the death deadline. */
19585
- ackedHoldFastTrackFired: 0,
19586
- /** Acked-hold death-deadline backstop released a held synth (the 8-min net). */
19587
- ackedHoldDeathDeadlineFired: 0
19588
- };
19589
19703
  coordinatorModalParkState = /* @__PURE__ */ new Map();
19590
19704
  heldEventLedgerRecorded = /* @__PURE__ */ new Set();
19591
19705
  ASSIGNED_STRANDED_DEADLINE_MS = 5 * 6e4;
@@ -20280,7 +20394,7 @@ function getCliValidator() {
20280
20394
  return _cliValidator;
20281
20395
  }
20282
20396
  function formatIssue(err) {
20283
- const path44 = err.instancePath || "";
20397
+ const path45 = err.instancePath || "";
20284
20398
  const params = err.params;
20285
20399
  let message = err.message || "validation failed";
20286
20400
  let allowed;
@@ -20298,7 +20412,7 @@ function formatIssue(err) {
20298
20412
  } else if (err.keyword === "type") {
20299
20413
  message = `must be ${params.type}`;
20300
20414
  }
20301
- return { path: path44, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
20415
+ return { path: path45, keyword: err.keyword, message, ...allowed !== void 0 ? { allowed } : {} };
20302
20416
  }
20303
20417
  function validateCliProviderManifest(manifest) {
20304
20418
  const validator = getCliValidator();
@@ -20594,49 +20708,49 @@ function validateFsmSpec(raw) {
20594
20708
  }
20595
20709
  return errs;
20596
20710
  }
20597
- function validateCondition(c, sectionIds, path44) {
20711
+ function validateCondition(c, sectionIds, path45) {
20598
20712
  const errs = [];
20599
20713
  const w = c;
20600
20714
  if ("all" in w) {
20601
- w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.all[${i}]`)));
20715
+ w.all.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path45}.all[${i}]`)));
20602
20716
  return errs;
20603
20717
  }
20604
20718
  if ("any" in w) {
20605
- w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path44}.any[${i}]`)));
20719
+ w.any.forEach((x, i) => errs.push(...validateCondition(x, sectionIds, `${path45}.any[${i}]`)));
20606
20720
  return errs;
20607
20721
  }
20608
20722
  if ("not" in w) {
20609
- errs.push(...validateCondition(w.not, sectionIds, `${path44}.not`));
20723
+ errs.push(...validateCondition(w.not, sectionIds, `${path45}.not`));
20610
20724
  return errs;
20611
20725
  }
20612
20726
  if ("matches" in w) {
20613
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
20727
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path45}.section "${w.section}" unknown`);
20614
20728
  try {
20615
20729
  new RegExp(w.matches, w.flags ?? "i");
20616
20730
  } catch (e) {
20617
- errs.push(`${path44}.matches invalid regex: ${e.message}`);
20731
+ errs.push(`${path45}.matches invalid regex: ${e.message}`);
20618
20732
  }
20619
20733
  return errs;
20620
20734
  }
20621
20735
  if ("cursor_above" in w && "changed" in w) return errs;
20622
20736
  if ("elapsed_ms" in w) {
20623
- if (typeof w.elapsed_ms !== "number") errs.push(`${path44}.elapsed_ms must be a number`);
20737
+ if (typeof w.elapsed_ms !== "number") errs.push(`${path45}.elapsed_ms must be a number`);
20624
20738
  return errs;
20625
20739
  }
20626
20740
  if ("stable_ms" in w) {
20627
- if (typeof w.stable_ms !== "number") errs.push(`${path44}.stable_ms must be a number`);
20628
- if (w.section && !sectionIds.has(w.section)) errs.push(`${path44}.section "${w.section}" unknown`);
20741
+ if (typeof w.stable_ms !== "number") errs.push(`${path45}.stable_ms must be a number`);
20742
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path45}.section "${w.section}" unknown`);
20629
20743
  if (w.ignore_lines !== void 0) {
20630
- if (typeof w.ignore_lines !== "string") errs.push(`${path44}.ignore_lines must be a string`);
20744
+ if (typeof w.ignore_lines !== "string") errs.push(`${path45}.ignore_lines must be a string`);
20631
20745
  else try {
20632
20746
  new RegExp(w.ignore_lines, "m");
20633
20747
  } catch (e) {
20634
- errs.push(`${path44}.ignore_lines invalid regex: ${e.message}`);
20748
+ errs.push(`${path45}.ignore_lines invalid regex: ${e.message}`);
20635
20749
  }
20636
20750
  }
20637
20751
  return errs;
20638
20752
  }
20639
- errs.push(`${path44} is not a recognized condition`);
20753
+ errs.push(`${path45} is not a recognized condition`);
20640
20754
  return errs;
20641
20755
  }
20642
20756
  var fs10;
@@ -21135,8 +21249,8 @@ var init_pty_transport = __esm({
21135
21249
  let cwd = options.cwd;
21136
21250
  if (cwd) {
21137
21251
  try {
21138
- const fs40 = require("fs");
21139
- const stat2 = fs40.statSync(cwd);
21252
+ const fs41 = require("fs");
21253
+ const stat2 = fs41.statSync(cwd);
21140
21254
  if (!stat2.isDirectory()) cwd = os14.homedir();
21141
21255
  } catch {
21142
21256
  cwd = os14.homedir();
@@ -25069,7 +25183,7 @@ function _getRegisteredRoots() {
25069
25183
  }
25070
25184
  function canonicalize(p) {
25071
25185
  try {
25072
- const resolved = path34.resolve(p);
25186
+ const resolved = path35.resolve(p);
25073
25187
  try {
25074
25188
  return nodeFs.realpathSync.native ? nodeFs.realpathSync.native(resolved) : nodeFs.realpathSync(resolved);
25075
25189
  } catch {
@@ -25089,7 +25203,7 @@ function isCallerInsideGatedRoot(callerFilename) {
25089
25203
  }
25090
25204
  for (const root of _gatedRoots) {
25091
25205
  if (normalized === root.rootPath) return root;
25092
- if (normalized.startsWith(root.rootPath + path34.sep)) return root;
25206
+ if (normalized.startsWith(root.rootPath + path35.sep)) return root;
25093
25207
  }
25094
25208
  return null;
25095
25209
  }
@@ -25108,16 +25222,16 @@ function ensureInstalled() {
25108
25222
  };
25109
25223
  }
25110
25224
  function gatedRequire(request, parent, isMain, gated, originalLoad) {
25111
- if (request.startsWith("./") || request.startsWith("../") || path34.isAbsolute(request)) {
25225
+ if (request.startsWith("./") || request.startsWith("../") || path35.isAbsolute(request)) {
25112
25226
  let resolved;
25113
25227
  try {
25114
- const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path34.join(gated.rootPath, "__entry__.js"));
25228
+ const callerRequire = parent?.filename ? (0, import_node_module2.createRequire)(parent.filename) : (0, import_node_module2.createRequire)(path35.join(gated.rootPath, "__entry__.js"));
25115
25229
  resolved = callerRequire.resolve(request);
25116
25230
  } catch {
25117
25231
  return originalLoad.call(this, request, parent, isMain);
25118
25232
  }
25119
25233
  const resolvedCanon = canonicalize(resolved) || resolved;
25120
- if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path34.sep))) {
25234
+ if (!(resolvedCanon === gated.rootPath || resolvedCanon.startsWith(gated.rootPath + path35.sep))) {
25121
25235
  denyRequire(request, parent, `relative path escapes provider root (resolved to ${resolvedCanon})`);
25122
25236
  }
25123
25237
  return originalLoad.call(this, request, parent, isMain);
@@ -25141,11 +25255,11 @@ function denyRequire(request, parent, reason) {
25141
25255
  err.callerFilename = caller;
25142
25256
  throw err;
25143
25257
  }
25144
- var path34, import_node_module2, nodeFs, nodeChildProcess, SAFE_STDLIB, SHIMMED_STDLIB, ALL_GATED_STDLIB, FS_READ_ONLY_MEMBERS, FS_PROMISES_READ_ONLY_MEMBERS, FS_SHIM, CHILD_PROCESS_SHIM, DANGEROUS_PROCESS_METHODS, _processGloballyHardened, _originalProcessMethods, PROCESS_SHIM, _gatedRoots, _installed, PROVIDER_REQUIRE_POLICY;
25258
+ var path35, import_node_module2, nodeFs, nodeChildProcess, SAFE_STDLIB, SHIMMED_STDLIB, ALL_GATED_STDLIB, FS_READ_ONLY_MEMBERS, FS_PROMISES_READ_ONLY_MEMBERS, FS_SHIM, CHILD_PROCESS_SHIM, DANGEROUS_PROCESS_METHODS, _processGloballyHardened, _originalProcessMethods, PROCESS_SHIM, _gatedRoots, _installed, PROVIDER_REQUIRE_POLICY;
25145
25259
  var init_require_whitelist = __esm({
25146
25260
  "src/providers/sdk/v1/sandbox/require-whitelist.ts"() {
25147
25261
  "use strict";
25148
- path34 = __toESM(require("path"));
25262
+ path35 = __toESM(require("path"));
25149
25263
  import_node_module2 = require("module");
25150
25264
  nodeFs = __toESM(require("fs"));
25151
25265
  nodeChildProcess = __toESM(require("child_process"));
@@ -27249,17 +27363,17 @@ function checkPathExists(paths) {
27249
27363
  return null;
27250
27364
  }
27251
27365
  async function detectIDEs(providerLoader) {
27252
- const os31 = (0, import_os2.platform)();
27366
+ const os32 = (0, import_os2.platform)();
27253
27367
  const results = [];
27254
27368
  for (const def of getMergedDefinitions()) {
27255
27369
  const cliPath = findCliCommand(providerLoader?.getIdeCliCommand(def.id, def.cli) || def.cli);
27256
- const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os31] || []) || []);
27370
+ const appPath = checkPathExists(providerLoader?.getIdePathCandidates(def.id, def.paths[os32] || []) || []);
27257
27371
  let resolvedCli = cliPath;
27258
- if (!resolvedCli && appPath && os31 === "darwin") {
27372
+ if (!resolvedCli && appPath && os32 === "darwin") {
27259
27373
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
27260
27374
  if ((0, import_fs15.existsSync)(bundledCli)) resolvedCli = bundledCli;
27261
27375
  }
27262
- if (!resolvedCli && appPath && os31 === "win32") {
27376
+ if (!resolvedCli && appPath && os32 === "win32") {
27263
27377
  const { dirname: dirname17 } = await import("path");
27264
27378
  const appDir = dirname17(appPath);
27265
27379
  const candidates = [
@@ -27276,7 +27390,7 @@ async function detectIDEs(providerLoader) {
27276
27390
  }
27277
27391
  }
27278
27392
  }
27279
- const installed = os31 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
27393
+ const installed = os32 === "darwin" ? !!(resolvedCli || appPath) : !!resolvedCli;
27280
27394
  const version = null;
27281
27395
  results.push({
27282
27396
  id: def.id,
@@ -36699,9 +36813,9 @@ var DaemonCommandHandler = class {
36699
36813
  * point at a sibling git checkout.
36700
36814
  */
36701
36815
  getUpstreamInstallRoot() {
36702
- const os31 = require("os");
36703
- const path44 = require("path");
36704
- return path44.join(os31.homedir(), ".adhdev", "providers", ".upstream");
36816
+ const os32 = require("os");
36817
+ const path45 = require("path");
36818
+ return path45.join(os32.homedir(), ".adhdev", "providers", ".upstream");
36705
36819
  }
36706
36820
  /**
36707
36821
  * Download a single provider manifest from the registry and write it to
@@ -36725,8 +36839,8 @@ var DaemonCommandHandler = class {
36725
36839
  return { success: false, error: "invalid type" };
36726
36840
  }
36727
36841
  const https = require("https");
36728
- const fs40 = require("fs");
36729
- const path44 = require("path");
36842
+ const fs41 = require("fs");
36843
+ const path45 = require("path");
36730
36844
  const REGISTRY = resolveRegistryBaseUrl(loadConfig().registryUrl);
36731
36845
  function fetchText(url, timeoutMs) {
36732
36846
  return new Promise((resolve25, reject) => {
@@ -36763,12 +36877,12 @@ var DaemonCommandHandler = class {
36763
36877
  return { success: false, error: `checksum mismatch: expected ${meta.checksum}, got ${actualChecksum}` };
36764
36878
  }
36765
36879
  const installRoot = this.getUpstreamInstallRoot();
36766
- const installRootResolved = path44.resolve(installRoot);
36767
- const targetDir = path44.resolve(path44.join(installRoot, category, type));
36768
- if (!targetDir.startsWith(installRootResolved + path44.sep)) {
36880
+ const installRootResolved = path45.resolve(installRoot);
36881
+ const targetDir = path45.resolve(path45.join(installRoot, category, type));
36882
+ if (!targetDir.startsWith(installRootResolved + path45.sep)) {
36769
36883
  return { success: false, error: "install path escaped upstream root" };
36770
36884
  }
36771
- fs40.mkdirSync(targetDir, { recursive: true });
36885
+ fs41.mkdirSync(targetDir, { recursive: true });
36772
36886
  let manifestProbe = {};
36773
36887
  try {
36774
36888
  manifestProbe = JSON.parse(manifestBody);
@@ -36792,8 +36906,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36792
36906
  }
36793
36907
  }
36794
36908
  const targetFile = isV1 ? "provider.v1.json" : "provider.json";
36795
- const targetPath = path44.join(targetDir, targetFile);
36796
- fs40.writeFileSync(targetPath, manifestBody, "utf-8");
36909
+ const targetPath = path45.join(targetDir, targetFile);
36910
+ fs41.writeFileSync(targetPath, manifestBody, "utf-8");
36797
36911
  const manifestJson = JSON.parse(manifestBody);
36798
36912
  const scriptFetch = await this.fetchProviderSources(
36799
36913
  manifestJson,
@@ -36863,8 +36977,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36863
36977
  const repo = source.repo;
36864
36978
  const ref = source.ref;
36865
36979
  const https = require("https");
36866
- const fs40 = require("fs");
36867
- const path44 = require("path");
36980
+ const fs41 = require("fs");
36981
+ const path45 = require("path");
36868
36982
  function fetchJson(url, timeoutMs) {
36869
36983
  return new Promise((resolve25, reject) => {
36870
36984
  const req = https.get(url, {
@@ -36920,9 +37034,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36920
37034
  }
36921
37035
  let fetchedCount = 0;
36922
37036
  const sharedDirRel = `${category}/_shared`;
36923
- const sharedTargetDir = path44.resolve(path44.join(targetDir, "../_shared"));
36924
- const installRootResolved = path44.resolve(path44.join(targetDir, "../.."));
36925
- if (sharedTargetDir.startsWith(installRootResolved + path44.sep)) {
37037
+ const sharedTargetDir = path45.resolve(path45.join(targetDir, "../_shared"));
37038
+ const installRootResolved = path45.resolve(path45.join(targetDir, "../.."));
37039
+ if (sharedTargetDir.startsWith(installRootResolved + path45.sep)) {
36926
37040
  const sharedStack = [sharedDirRel];
36927
37041
  while (sharedStack.length) {
36928
37042
  const relDir = sharedStack.pop();
@@ -36945,10 +37059,10 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36945
37059
  try {
36946
37060
  const body = await fetchBinary(entry.download_url, 3e4);
36947
37061
  const relInside = entry.path.startsWith(sharedDirRel + "/") ? entry.path.slice(sharedDirRel.length + 1) : entry.path;
36948
- const outPath = path44.resolve(path44.join(sharedTargetDir, relInside));
36949
- if (!outPath.startsWith(path44.resolve(sharedTargetDir) + path44.sep)) continue;
36950
- fs40.mkdirSync(path44.dirname(outPath), { recursive: true });
36951
- fs40.writeFileSync(outPath, body);
37062
+ const outPath = path45.resolve(path45.join(sharedTargetDir, relInside));
37063
+ if (!outPath.startsWith(path45.resolve(sharedTargetDir) + path45.sep)) continue;
37064
+ fs41.mkdirSync(path45.dirname(outPath), { recursive: true });
37065
+ fs41.writeFileSync(outPath, body);
36952
37066
  fetchedCount++;
36953
37067
  } catch (e) {
36954
37068
  errors.push(`fetch shared ${entry.path}: ${e?.message ?? e}`);
@@ -36981,13 +37095,13 @@ ${formatManifestValidationIssues2(validation.issues)}`,
36981
37095
  try {
36982
37096
  const body = await fetchBinary(entry.download_url, 3e4);
36983
37097
  const relInsideProvider = entry.path.startsWith(subdir + "/") ? entry.path.slice(subdir.length + 1) : entry.path;
36984
- const outPath = path44.resolve(path44.join(targetDir, relInsideProvider));
36985
- if (!outPath.startsWith(path44.resolve(targetDir) + path44.sep)) {
37098
+ const outPath = path45.resolve(path45.join(targetDir, relInsideProvider));
37099
+ if (!outPath.startsWith(path45.resolve(targetDir) + path45.sep)) {
36986
37100
  errors.push(`refusing to write outside targetDir: ${entry.path}`);
36987
37101
  continue;
36988
37102
  }
36989
- fs40.mkdirSync(path44.dirname(outPath), { recursive: true });
36990
- fs40.writeFileSync(outPath, body);
37103
+ fs41.mkdirSync(path45.dirname(outPath), { recursive: true });
37104
+ fs41.writeFileSync(outPath, body);
36991
37105
  fetchedCount++;
36992
37106
  } catch (e) {
36993
37107
  errors.push(`fetch ${entry.path}: ${e?.message ?? e}`);
@@ -37015,19 +37129,19 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37015
37129
  if (!["cli", "ide", "extension", "acp"].includes(category)) {
37016
37130
  return { success: false, error: `unknown category: ${category}` };
37017
37131
  }
37018
- const fs40 = require("fs");
37019
- const path44 = require("path");
37132
+ const fs41 = require("fs");
37133
+ const path45 = require("path");
37020
37134
  try {
37021
37135
  const installRoot = this.getUpstreamInstallRoot();
37022
- const installRootResolved = path44.resolve(installRoot);
37023
- const targetDir = path44.resolve(path44.join(installRoot, category, type));
37024
- if (!targetDir.startsWith(installRootResolved + path44.sep)) {
37136
+ const installRootResolved = path45.resolve(installRoot);
37137
+ const targetDir = path45.resolve(path45.join(installRoot, category, type));
37138
+ if (!targetDir.startsWith(installRootResolved + path45.sep)) {
37025
37139
  return { success: false, error: "refusing to delete outside upstream root" };
37026
37140
  }
37027
- if (!fs40.existsSync(targetDir)) {
37141
+ if (!fs41.existsSync(targetDir)) {
37028
37142
  return { success: false, error: "not installed" };
37029
37143
  }
37030
- fs40.rmSync(targetDir, { recursive: true, force: true });
37144
+ fs41.rmSync(targetDir, { recursive: true, force: true });
37031
37145
  if (this._ctx.providerLoader) {
37032
37146
  this._ctx.providerLoader.reload();
37033
37147
  this._ctx.providerLoader.registerToDetector();
@@ -37043,28 +37157,28 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37043
37157
  * the UI and by the update checker.
37044
37158
  */
37045
37159
  handleListInstalledProviders(_args) {
37046
- const fs40 = require("fs");
37047
- const path44 = require("path");
37160
+ const fs41 = require("fs");
37161
+ const path45 = require("path");
37048
37162
  const installRoot = this.getUpstreamInstallRoot();
37049
- if (!fs40.existsSync(installRoot)) return { success: true, providers: [] };
37163
+ if (!fs41.existsSync(installRoot)) return { success: true, providers: [] };
37050
37164
  const CATEGORIES = ["cli", "ide", "extension", "acp"];
37051
37165
  const items = [];
37052
37166
  for (const category of CATEGORIES) {
37053
- const categoryDir = path44.join(installRoot, category);
37054
- if (!fs40.existsSync(categoryDir)) continue;
37167
+ const categoryDir = path45.join(installRoot, category);
37168
+ if (!fs41.existsSync(categoryDir)) continue;
37055
37169
  let entries;
37056
37170
  try {
37057
- entries = fs40.readdirSync(categoryDir);
37171
+ entries = fs41.readdirSync(categoryDir);
37058
37172
  } catch {
37059
37173
  continue;
37060
37174
  }
37061
37175
  for (const type of entries) {
37062
- const v1Path = path44.join(categoryDir, type, "provider.v1.json");
37063
- const v0Path = path44.join(categoryDir, type, "provider.json");
37064
- const manifestPath = fs40.existsSync(v1Path) ? v1Path : fs40.existsSync(v0Path) ? v0Path : null;
37176
+ const v1Path = path45.join(categoryDir, type, "provider.v1.json");
37177
+ const v0Path = path45.join(categoryDir, type, "provider.json");
37178
+ const manifestPath = fs41.existsSync(v1Path) ? v1Path : fs41.existsSync(v0Path) ? v0Path : null;
37065
37179
  if (!manifestPath) continue;
37066
37180
  try {
37067
- const m = JSON.parse(fs40.readFileSync(manifestPath, "utf-8"));
37181
+ const m = JSON.parse(fs41.readFileSync(manifestPath, "utf-8"));
37068
37182
  items.push({
37069
37183
  type,
37070
37184
  category,
@@ -37175,8 +37289,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37175
37289
  if (!/^@[a-z0-9_-]+$/i.test(requestedName)) {
37176
37290
  return { success: false, error: "name must match @[a-z0-9_-]+" };
37177
37291
  }
37178
- const fs40 = require("fs");
37179
- const path44 = require("path");
37292
+ const fs41 = require("fs");
37293
+ const path45 = require("path");
37180
37294
  const { spawnSync: spawnSync2 } = require("child_process");
37181
37295
  const file = ext.loadExternalSources();
37182
37296
  if (file.sources.some((s2) => s2.name === requestedName)) {
@@ -37185,9 +37299,9 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37185
37299
  if (file.sources.some((s2) => s2.url === url && s2.ref === ref)) {
37186
37300
  return { success: false, error: `source url+ref already registered (use a different name to track another ref)` };
37187
37301
  }
37188
- const sourceDir = path44.join(ext.externalRoot(), requestedName);
37189
- if (!fs40.existsSync(ext.externalRoot())) fs40.mkdirSync(ext.externalRoot(), { recursive: true });
37190
- if (fs40.existsSync(sourceDir)) {
37302
+ const sourceDir = path45.join(ext.externalRoot(), requestedName);
37303
+ if (!fs41.existsSync(ext.externalRoot())) fs41.mkdirSync(ext.externalRoot(), { recursive: true });
37304
+ if (fs41.existsSync(sourceDir)) {
37191
37305
  return { success: false, error: `directory already exists: ${sourceDir} (rename or remove first)` };
37192
37306
  }
37193
37307
  const clone = spawnSync2("git", ["clone", "--depth=1", "--branch", ref, "--", url, sourceDir], {
@@ -37197,7 +37311,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37197
37311
  });
37198
37312
  if (clone.status !== 0) {
37199
37313
  try {
37200
- fs40.rmSync(sourceDir, { recursive: true, force: true });
37314
+ fs41.rmSync(sourceDir, { recursive: true, force: true });
37201
37315
  } catch {
37202
37316
  }
37203
37317
  return { success: false, error: `git clone failed: ${(clone.stderr || clone.stdout || "").trim() || "unknown error"}` };
@@ -37241,15 +37355,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
37241
37355
  const name = typeof args?.name === "string" ? args.name.trim() : "";
37242
37356
  if (!name) return { success: false, error: "name is required" };
37243
37357
  const ext = (init_external_sources(), __toCommonJS(external_sources_exports));
37244
- const fs40 = require("fs");
37245
- const path44 = require("path");
37358
+ const fs41 = require("fs");
37359
+ const path45 = require("path");
37246
37360
  const file = ext.loadExternalSources();
37247
37361
  const match = file.sources.find((s2) => s2.name === name);
37248
37362
  if (!match) return { success: false, error: `source "${name}" not registered` };
37249
- const sourceDir = path44.join(ext.externalRoot(), name);
37250
- if (fs40.existsSync(sourceDir)) {
37363
+ const sourceDir = path45.join(ext.externalRoot(), name);
37364
+ if (fs41.existsSync(sourceDir)) {
37251
37365
  try {
37252
- fs40.rmSync(sourceDir, { recursive: true, force: true });
37366
+ fs41.rmSync(sourceDir, { recursive: true, force: true });
37253
37367
  } catch (e) {
37254
37368
  return { success: false, error: `failed to delete ${sourceDir}: ${e?.message || e}` };
37255
37369
  }
@@ -38034,24 +38148,24 @@ var statusMetaHandlers = {
38034
38148
  // src/commands/low-family/coordinator-prompt.ts
38035
38149
  var coordinatorPromptHandlers = {
38036
38150
  list_coordinator_prompts: async (_ctx, _args) => {
38037
- const fs40 = await import("fs");
38038
- const path44 = await import("path");
38039
- const os31 = await import("os");
38040
- const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
38151
+ const fs41 = await import("fs");
38152
+ const path45 = await import("path");
38153
+ const os32 = await import("os");
38154
+ const dir = path45.join(os32.homedir(), ".adhdev", "coordinator-prompts");
38041
38155
  const entries = {};
38042
38156
  try {
38043
- if (fs40.existsSync(dir)) {
38044
- for (const name of fs40.readdirSync(dir)) {
38157
+ if (fs41.existsSync(dir)) {
38158
+ for (const name of fs41.readdirSync(dir)) {
38045
38159
  const matchOverride = name.match(/^([a-zA-Z0-9_.-]+)\.md$/);
38046
38160
  const matchAppend = name.match(/^([a-zA-Z0-9_.-]+)\.append\.md$/);
38047
38161
  const m = matchAppend || matchOverride;
38048
38162
  if (!m) continue;
38049
38163
  const isAppend = !!matchAppend;
38050
38164
  const key2 = m[1];
38051
- const full = path44.join(dir, name);
38165
+ const full = path45.join(dir, name);
38052
38166
  let content = "";
38053
38167
  try {
38054
- content = fs40.readFileSync(full, "utf8");
38168
+ content = fs41.readFileSync(full, "utf8");
38055
38169
  } catch {
38056
38170
  }
38057
38171
  if (!entries[key2]) entries[key2] = { override: "", append: "" };
@@ -38065,24 +38179,24 @@ var coordinatorPromptHandlers = {
38065
38179
  return { success: true, dir, entries };
38066
38180
  },
38067
38181
  write_coordinator_prompt: async (_ctx, args) => {
38068
- const fs40 = await import("fs");
38069
- const path44 = await import("path");
38070
- const os31 = await import("os");
38182
+ const fs41 = await import("fs");
38183
+ const path45 = await import("path");
38184
+ const os32 = await import("os");
38071
38185
  const key2 = typeof args?.key === "string" ? args.key.trim() : "";
38072
38186
  const kind = args?.kind === "append" ? "append" : "override";
38073
38187
  const content = typeof args?.content === "string" ? args.content : "";
38074
38188
  if (!key2 || !/^[a-zA-Z0-9_.-]+$/.test(key2)) {
38075
38189
  return { success: false, error: "key must match [a-zA-Z0-9_.-]+" };
38076
38190
  }
38077
- const dir = path44.join(os31.homedir(), ".adhdev", "coordinator-prompts");
38191
+ const dir = path45.join(os32.homedir(), ".adhdev", "coordinator-prompts");
38078
38192
  const filename = kind === "append" ? `${key2}.append.md` : `${key2}.md`;
38079
- const full = path44.join(dir, filename);
38193
+ const full = path45.join(dir, filename);
38080
38194
  try {
38081
- fs40.mkdirSync(dir, { recursive: true });
38195
+ fs41.mkdirSync(dir, { recursive: true });
38082
38196
  if (content.trim()) {
38083
- fs40.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
38084
- } else if (fs40.existsSync(full)) {
38085
- fs40.unlinkSync(full);
38197
+ fs41.writeFileSync(full, content, { encoding: "utf8", mode: 384 });
38198
+ } else if (fs41.existsSync(full)) {
38199
+ fs41.unlinkSync(full);
38086
38200
  }
38087
38201
  return { success: true, path: full, kind, key: key2 };
38088
38202
  } catch (error) {
@@ -39165,9 +39279,9 @@ var lowFamilyRegistry = new Map(
39165
39279
  init_dist();
39166
39280
 
39167
39281
  // src/commands/cli-manager.ts
39168
- var os21 = __toESM(require("os"));
39169
- var path28 = __toESM(require("path"));
39170
- var crypto5 = __toESM(require("crypto"));
39282
+ var os22 = __toESM(require("os"));
39283
+ var path29 = __toESM(require("path"));
39284
+ var crypto6 = __toESM(require("crypto"));
39171
39285
  var import_fs16 = require("fs");
39172
39286
  var import_child_process8 = require("child_process");
39173
39287
  var import_chalk = __toESM(require("chalk"));
@@ -39182,11 +39296,9 @@ init_coordinator_registry();
39182
39296
  init_summary_metadata();
39183
39297
 
39184
39298
  // src/providers/cli-provider-instance.ts
39185
- var os20 = __toESM(require("os"));
39186
- var path26 = __toESM(require("path"));
39187
- var crypto4 = __toESM(require("crypto"));
39188
- var fs19 = __toESM(require("fs"));
39189
- var import_node_module = require("module");
39299
+ var os21 = __toESM(require("os"));
39300
+ var crypto5 = __toESM(require("crypto"));
39301
+ var fs20 = __toESM(require("fs"));
39190
39302
  init_contracts2();
39191
39303
  init_provider_input_support();
39192
39304
  init_hash();
@@ -42392,28 +42504,11 @@ function workingDirBasename(p) {
42392
42504
  return (p || "").split(/[\\/]/).filter(Boolean).pop() || "session";
42393
42505
  }
42394
42506
 
42395
- // src/providers/cli-provider-instance.ts
42396
- var STATUS_HYDRATION_TAIL_LIMIT = 200;
42397
- function isIdleStatus(value) {
42398
- const status = typeof value === "string" ? value.trim().toLowerCase() : "";
42399
- return !status || status === "idle" || status === "ready";
42400
- }
42401
- function getMessageTime(message) {
42402
- if (!message || typeof message !== "object") return 0;
42403
- const record = message;
42404
- const value = Number(record.receivedAt ?? record.timestamp ?? 0);
42405
- return Number.isFinite(value) ? value : 0;
42406
- }
42407
- var COMPLETED_FINALIZATION_RETRY_MS = 1e3;
42408
- var COMPLETED_FINALIZATION_MAX_WAIT_MS = 3e4;
42409
- var NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4e3;
42410
- var USER_INPUT_ACK_DEDUP_WINDOW_MS = 6e4;
42411
- var STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12e3;
42412
- var TERMINAL_MESH_EVENTS = /* @__PURE__ */ new Set([
42413
- "agent:generating_completed",
42414
- "agent:stopped",
42415
- "agent:ready"
42416
- ]);
42507
+ // src/providers/cli-provider-input-prompt.ts
42508
+ var os20 = __toESM(require("os"));
42509
+ var path26 = __toESM(require("path"));
42510
+ var crypto4 = __toESM(require("crypto"));
42511
+ var fs19 = __toESM(require("fs"));
42417
42512
  var IMAGE_MIME_EXTENSIONS = {
42418
42513
  "image/png": ".png",
42419
42514
  "image/jpeg": ".jpg",
@@ -42477,19 +42572,6 @@ function cleanupStaleMaterializedImages(dir) {
42477
42572
  } catch {
42478
42573
  }
42479
42574
  }
42480
- function hasNonEmptyCliModalButtons(activeModal) {
42481
- const buttons = activeModal?.buttons;
42482
- return Array.isArray(buttons) && buttons.some((button) => String(button || "").trim().length > 0);
42483
- }
42484
- function isCliGeneratingLikeStatus(status) {
42485
- return status === "generating" || status === "streaming" || status === "no_progress" || status === "long_generating" || status === "starting";
42486
- }
42487
- function computeTurnAnchoredDurationMs(engineTurnStartedAt, generatingStartedAt, now) {
42488
- const engineStart = typeof engineTurnStartedAt === "number" && Number.isFinite(engineTurnStartedAt) ? engineTurnStartedAt : 0;
42489
- if (engineStart > 0) return { durationMs: now - engineStart, anchor: "turn-start" };
42490
- if (generatingStartedAt > 0) return { durationMs: now - generatingStartedAt, anchor: "generatingStartedAt" };
42491
- return { durationMs: 0, anchor: "none" };
42492
- }
42493
42575
  function buildCliStructuredInputPrompt(input, options = {}) {
42494
42576
  const promptParts = [];
42495
42577
  const imageRefs = [];
@@ -42527,6 +42609,9 @@ function buildCliStructuredInputPrompt(input, options = {}) {
42527
42609
  ].filter((value, index, values) => value.trim().length > 0 && values.indexOf(value) === index);
42528
42610
  return ordered.join("\n");
42529
42611
  }
42612
+
42613
+ // src/providers/cli-provider-history-dedup.ts
42614
+ init_contracts2();
42530
42615
  function normalizePersistableCliHistoryContent(content) {
42531
42616
  return flattenContent(content).replace(/\s+/g, " ").trim();
42532
42617
  }
@@ -42558,10 +42643,37 @@ function buildIncrementalHistoryAppendMessages(previousMessages, currentMessages
42558
42643
  if (sharedPrefixLength === previousMessages.length) return currentMessages.slice(sharedPrefixLength);
42559
42644
  return currentMessages;
42560
42645
  }
42646
+
42647
+ // src/providers/cli-provider-status-helpers.ts
42648
+ var path27 = __toESM(require("path"));
42649
+ var import_node_module = require("module");
42650
+ function isIdleStatus(value) {
42651
+ const status = typeof value === "string" ? value.trim().toLowerCase() : "";
42652
+ return !status || status === "idle" || status === "ready";
42653
+ }
42654
+ function getMessageTime(message) {
42655
+ if (!message || typeof message !== "object") return 0;
42656
+ const record = message;
42657
+ const value = Number(record.receivedAt ?? record.timestamp ?? 0);
42658
+ return Number.isFinite(value) ? value : 0;
42659
+ }
42660
+ function hasNonEmptyCliModalButtons(activeModal) {
42661
+ const buttons = activeModal?.buttons;
42662
+ return Array.isArray(buttons) && buttons.some((button) => String(button || "").trim().length > 0);
42663
+ }
42664
+ function isCliGeneratingLikeStatus(status) {
42665
+ return status === "generating" || status === "streaming" || status === "no_progress" || status === "long_generating" || status === "starting";
42666
+ }
42667
+ function computeTurnAnchoredDurationMs(engineTurnStartedAt, generatingStartedAt, now) {
42668
+ const engineStart = typeof engineTurnStartedAt === "number" && Number.isFinite(engineTurnStartedAt) ? engineTurnStartedAt : 0;
42669
+ if (engineStart > 0) return { durationMs: now - engineStart, anchor: "turn-start" };
42670
+ if (generatingStartedAt > 0) return { durationMs: now - generatingStartedAt, anchor: "generatingStartedAt" };
42671
+ return { durationMs: 0, anchor: "none" };
42672
+ }
42561
42673
  var CachedDatabaseSync = null;
42562
42674
  function getDatabaseSync() {
42563
42675
  if (CachedDatabaseSync) return CachedDatabaseSync;
42564
- const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path26.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
42676
+ const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path27.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
42565
42677
  const sqliteModule = requireFn(`node:${"sqlite"}`);
42566
42678
  CachedDatabaseSync = sqliteModule.DatabaseSync;
42567
42679
  if (!CachedDatabaseSync) {
@@ -42603,13 +42715,26 @@ async function waitForCliAdapterReady(adapter, options) {
42603
42715
  }
42604
42716
  throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
42605
42717
  }
42718
+
42719
+ // src/providers/cli-provider-instance.ts
42720
+ var STATUS_HYDRATION_TAIL_LIMIT = 200;
42721
+ var COMPLETED_FINALIZATION_RETRY_MS = 1e3;
42722
+ var COMPLETED_FINALIZATION_MAX_WAIT_MS = 3e4;
42723
+ var NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4e3;
42724
+ var USER_INPUT_ACK_DEDUP_WINDOW_MS = 6e4;
42725
+ var STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12e3;
42726
+ var TERMINAL_MESH_EVENTS = /* @__PURE__ */ new Set([
42727
+ "agent:generating_completed",
42728
+ "agent:stopped",
42729
+ "agent:ready"
42730
+ ]);
42606
42731
  var CliProviderInstance = class _CliProviderInstance {
42607
42732
  constructor(provider, workingDir, cliArgs = [], instanceId, transportFactory, options) {
42608
42733
  this.provider = provider;
42609
42734
  this.workingDir = workingDir;
42610
42735
  this.cliArgs = cliArgs;
42611
42736
  this.type = provider.type;
42612
- this.instanceId = instanceId || crypto4.randomUUID();
42737
+ this.instanceId = instanceId || crypto5.randomUUID();
42613
42738
  this.presentationMode = "chat";
42614
42739
  this.providerSessionId = options?.providerSessionId;
42615
42740
  this.launchMode = options?.launchMode || "new";
@@ -42649,6 +42774,33 @@ var CliProviderInstance = class _CliProviderInstance {
42649
42774
  * from scratch rather than firing on a stale timestamp.
42650
42775
  */
42651
42776
  static AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
42777
+ /**
42778
+ * AUTOAPPROVE-FLAP-RECUR (Fix B): extended busy-side continuity window for a
42779
+ * DELEGATED-WORKER auto-approve episode that is genuinely still cycling.
42780
+ *
42781
+ * The default AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) absorbs a *momentary*
42782
+ * `generating` blip. But a delegated worker running a Bash approval observed
42783
+ * the FSM cycle the FULL state waiting_approval → busy → waiting_approval on a
42784
+ * 2–5s period (the button set scrolls in/out AND the modal question repaints,
42785
+ * so the adapter genuinely reports status=generating for whole seconds between
42786
+ * approval frames). Each busy phase outran the 1500ms hysteresis, so the
42787
+ * settle clock was WIPED (the genuine-resolution branch), the 600ms settle
42788
+ * window never accumulated across the flap, resolveModal never fired
42789
+ * (resolveModal count 0), and the mask-stall clock instead tripped at 4500ms →
42790
+ * coordinator nudge → the flap the coordinator observed.
42791
+ *
42792
+ * A genuine resolution and a flap both start with a busy phase; they diverge
42793
+ * only in whether waiting_approval RETURNS. So we cannot simply lengthen the
42794
+ * blanket hysteresis (that would make every real resolution hold the gate
42795
+ * open for seconds). Instead this longer window applies ONLY while an active
42796
+ * mask episode is alive (autoApproveMaskSince > 0) AND the session is a
42797
+ * delegated worker — i.e. exactly the never-resolving-flap case. A foreground
42798
+ * / attended session keeps the tight 1500ms window unchanged. The mask-stall
42799
+ * bound below still caps the episode, so a worker whose approval truly never
42800
+ * returns is surfaced to the coordinator within AUTO_APPROVE_MASK_STALL_MS
42801
+ * rather than held forever.
42802
+ */
42803
+ static AUTO_APPROVE_FLAP_CONTINUITY_MS = 4e3;
42652
42804
  /**
42653
42805
  * STATUS-MISMATCH: upper bound on how long the auto-approve→`generating` SURFACE
42654
42806
  * mask may hide a worker's `waiting_approval` (status + activeModal) before we give
@@ -42723,9 +42875,22 @@ var CliProviderInstance = class _CliProviderInstance {
42723
42875
  pendingAutoApprovalSince = 0;
42724
42876
  autoApproveSettleTimer = null;
42725
42877
  // Wall-clock when auto-approve first observed status!=waiting_approval while
42726
- // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
42878
+ // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS (or,
42879
+ // for a delegated-worker flap episode, AUTO_APPROVE_FLAP_CONTINUITY_MS) so a
42727
42880
  // brief generating flip does not immediately wipe the settle clock.
42728
42881
  autoApproveInactiveSince = 0;
42882
+ // AUTOAPPROVE-FLAP-RECUR (Fix A): wall-clock when the CURRENT waiting_approval
42883
+ // episode last presented a concrete, captured modal (buttons.length > 0). The
42884
+ // Claude TUI momentarily reports status=waiting_approval with activeModal=null
42885
+ // / an empty button block while the button block scrolls out of the captured
42886
+ // frame; the raw guard below (buttons.length===0) used to bail on that frame,
42887
+ // never advancing the settle gate and leaving no re-check armed — so a modal
42888
+ // that flapped modal=none ↔ N-buttons around the settle boundary never
42889
+ // accumulated its 600ms. This tracks the last GOOD-modal frame so a short
42890
+ // scroll-out blip is absorbed (settle keeps running against the last captured
42891
+ // signature) while a genuinely closed modal — buttons empty continuously past
42892
+ // the continuity window — is still recognised and resets the gate.
42893
+ autoApproveLastModalSeenAt = 0;
42729
42894
  // STATUS-MISMATCH: wall-clock when the CURRENT auto-approve episode (waiting_approval
42730
42895
  // + shouldAutoApprove) first began wanting to mask. Unlike pendingAutoApprovalSince it
42731
42896
  // is NOT reset when the modal signature changes (a still-streaming/flapping prompt) and
@@ -42835,10 +43000,10 @@ var CliProviderInstance = class _CliProviderInstance {
42835
43000
  * Replaces the previously duplicated probeOpenCode/Codex/Goose functions.
42836
43001
  */
42837
43002
  probeSessionIdFromConfig(probe) {
42838
- const resolvedDbPath = probe.dbPath.replace(/^~/, os20.homedir());
43003
+ const resolvedDbPath = probe.dbPath.replace(/^~/, os21.homedir());
42839
43004
  const now = Date.now();
42840
43005
  if (this.cachedSqliteDbMissingUntil > now) return null;
42841
- if (!fs19.existsSync(resolvedDbPath)) {
43006
+ if (!fs20.existsSync(resolvedDbPath)) {
42842
43007
  this.cachedSqliteDbMissingUntil = now + 1e4;
42843
43008
  return null;
42844
43009
  }
@@ -43434,7 +43599,7 @@ var CliProviderInstance = class _CliProviderInstance {
43434
43599
  if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
43435
43600
  if (this.lastExternalCompletionProbe?.sourcePath) {
43436
43601
  try {
43437
- fs19.statSync(this.lastExternalCompletionProbe.sourcePath);
43602
+ fs20.statSync(this.lastExternalCompletionProbe.sourcePath);
43438
43603
  } catch {
43439
43604
  }
43440
43605
  }
@@ -43688,6 +43853,20 @@ var CliProviderInstance = class _CliProviderInstance {
43688
43853
  isMeshWorkerSession() {
43689
43854
  return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.meshNodeId || this.settings.launchedByCoordinator);
43690
43855
  }
43856
+ /**
43857
+ * AUTOAPPROVE-FLAP-RECUR (Fix A+B): how long a busy blip / modal scroll-out may
43858
+ * persist before the in-progress settle gate is torn down. For a delegated
43859
+ * worker whose auto-approve episode is genuinely still cycling (mask clock
43860
+ * alive), the FSM's full waiting_approval → busy → waiting_approval flap runs
43861
+ * on a multi-second period, so the settle continuity window is extended to
43862
+ * AUTO_APPROVE_FLAP_CONTINUITY_MS to bridge it (still bounded, and still capped
43863
+ * by AUTO_APPROVE_MASK_STALL_MS). Every other case — foreground/attended
43864
+ * session, or no active mask episode — keeps the tight default hysteresis so a
43865
+ * genuine resolution frees the gate promptly.
43866
+ */
43867
+ autoApproveContinuityWindowMs() {
43868
+ return this.autoApproveMaskSince > 0 && this.isMeshWorkerSession() ? _CliProviderInstance.AUTO_APPROVE_FLAP_CONTINUITY_MS : _CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS;
43869
+ }
43691
43870
  // FALSE-IDLE (self-coordinator settle): an autonomously-progressing mesh session
43692
43871
  // is either a delegated worker (isMeshWorkerSession) OR the coordinator's OWN
43693
43872
  // claude-cli session (meshCoordinatorFor). Both run auto-approved tool turns whose
@@ -43923,6 +44102,7 @@ var CliProviderInstance = class _CliProviderInstance {
43923
44102
  this.autoApproveInactiveSince = 0;
43924
44103
  this.autoApproveMaskSince = 0;
43925
44104
  this.stalledApprovalNudgeEpisode = 0;
44105
+ this.autoApproveLastModalSeenAt = 0;
43926
44106
  if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
43927
44107
  this.autoApproveSettleTimer = setTimeout(() => {
43928
44108
  this.autoApproveSettleTimer = null;
@@ -43936,12 +44116,13 @@ var CliProviderInstance = class _CliProviderInstance {
43936
44116
  if (this.pendingAutoApprovalSince) {
43937
44117
  if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
43938
44118
  const goneForMs = now - this.autoApproveInactiveSince;
43939
- if (goneForMs < _CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
44119
+ const continuityMs = this.autoApproveContinuityWindowMs();
44120
+ if (goneForMs < continuityMs) {
43940
44121
  if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
43941
44122
  this.autoApproveSettleTimer = setTimeout(() => {
43942
44123
  this.autoApproveSettleTimer = null;
43943
44124
  this.recheckAutoApproveSettled();
43944
- }, _CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
44125
+ }, continuityMs - goneForMs + 20);
43945
44126
  return autoApproveActive;
43946
44127
  }
43947
44128
  }
@@ -43950,6 +44131,7 @@ var CliProviderInstance = class _CliProviderInstance {
43950
44131
  this.autoApproveInactiveSince = 0;
43951
44132
  this.autoApproveMaskSince = 0;
43952
44133
  this.stalledApprovalNudgeEpisode = 0;
44134
+ this.autoApproveLastModalSeenAt = 0;
43953
44135
  if (this.autoApproveSettleTimer) {
43954
44136
  clearTimeout(this.autoApproveSettleTimer);
43955
44137
  this.autoApproveSettleTimer = null;
@@ -43962,8 +44144,22 @@ var CliProviderInstance = class _CliProviderInstance {
43962
44144
  const modal = adapterStatus.activeModal;
43963
44145
  const buttons = Array.isArray(modal?.buttons) ? modal.buttons.map((b) => String(b || "").trim()).filter(Boolean) : [];
43964
44146
  if (!modal || buttons.length === 0) {
44147
+ const blipForMs = this.autoApproveLastModalSeenAt ? now - this.autoApproveLastModalSeenAt : Infinity;
44148
+ if (this.pendingAutoApprovalSince && blipForMs < this.autoApproveContinuityWindowMs()) {
44149
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
44150
+ this.autoApproveSettleTimer = setTimeout(() => {
44151
+ this.autoApproveSettleTimer = null;
44152
+ this.recheckAutoApproveSettled();
44153
+ }, this.autoApproveContinuityWindowMs() - blipForMs + 20);
44154
+ return autoApproveActive;
44155
+ }
44156
+ if (blipForMs >= this.autoApproveContinuityWindowMs()) {
44157
+ this.pendingAutoApprovalSignature = "";
44158
+ this.pendingAutoApprovalSince = 0;
44159
+ }
43965
44160
  return autoApproveActive;
43966
44161
  }
44162
+ this.autoApproveLastModalSeenAt = now;
43967
44163
  const modalKind = typeof modal?.kind === "string" ? modal.kind : "approval";
43968
44164
  if (modalKind !== "approval") {
43969
44165
  return autoApproveActive;
@@ -44007,6 +44203,7 @@ var CliProviderInstance = class _CliProviderInstance {
44007
44203
  this.autoApproveInactiveSince = 0;
44008
44204
  this.autoApproveMaskSince = 0;
44009
44205
  this.stalledApprovalNudgeEpisode = 0;
44206
+ this.autoApproveLastModalSeenAt = 0;
44010
44207
  if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
44011
44208
  this.autoApproveBusyTimer = setTimeout(() => {
44012
44209
  this.autoApproveBusy = false;
@@ -44652,6 +44849,8 @@ ${effect.notification.body || ""}`.trim();
44652
44849
  if (!this.isMeshWorkerSession()) return;
44653
44850
  if (adapterStatus?.status !== "waiting_approval") return;
44654
44851
  if (!this.autoApproveMaskStalled(now)) return;
44852
+ const modalButtons = Array.isArray(adapterStatus.activeModal?.buttons) ? adapterStatus.activeModal.buttons.map((b) => String(b || "").trim()).filter(Boolean) : [];
44853
+ if (this.pendingAutoApprovalSince && modalButtons.length > 0) return;
44655
44854
  if (this.stalledApprovalNudgeEpisode === this.autoApproveMaskSince) return;
44656
44855
  this.stalledApprovalNudgeEpisode = this.autoApproveMaskSince;
44657
44856
  const modal = adapterStatus.activeModal;
@@ -44967,7 +45166,7 @@ ${effect.notification.body || ""}`.trim();
44967
45166
  };
44968
45167
  addDir(this.workingDir);
44969
45168
  try {
44970
- addDir(fs19.realpathSync.native(this.workingDir));
45169
+ addDir(fs20.realpathSync.native(this.workingDir));
44971
45170
  } catch {
44972
45171
  }
44973
45172
  return Array.from(dirs);
@@ -45004,7 +45203,7 @@ ${effect.notification.body || ""}`.trim();
45004
45203
  };
45005
45204
 
45006
45205
  // src/providers/acp-provider-instance.ts
45007
- var path27 = __toESM(require("path"));
45206
+ var path28 = __toESM(require("path"));
45008
45207
  var import_stream = require("stream");
45009
45208
  var import_child_process7 = require("child_process");
45010
45209
  var import_sdk = require("@agentclientprotocol/sdk");
@@ -45794,7 +45993,7 @@ var AcpProviderInstance = class {
45794
45993
  return b.uri ? {
45795
45994
  type: "resource_link",
45796
45995
  uri: b.uri,
45797
- name: path27.basename(b.uri),
45996
+ name: path28.basename(b.uri),
45798
45997
  mimeType: b.mimeType,
45799
45998
  ...b.transcript ? { description: b.transcript } : {}
45800
45999
  } : { type: "text", text: b.transcript || `[Video attachment: ${b.mimeType}]` };
@@ -46266,11 +46465,11 @@ function shouldRestoreHostedRuntime(record, managerTag) {
46266
46465
  // src/commands/cli-manager.ts
46267
46466
  function isExplicitCommand(command) {
46268
46467
  const trimmed = command.trim();
46269
- return path28.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
46468
+ return path29.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
46270
46469
  }
46271
46470
  function expandExecutable(command) {
46272
46471
  const trimmed = command.trim();
46273
- return trimmed.startsWith("~") ? path28.join(os21.homedir(), trimmed.slice(1)) : trimmed;
46472
+ return trimmed.startsWith("~") ? path29.join(os22.homedir(), trimmed.slice(1)) : trimmed;
46274
46473
  }
46275
46474
  function commandExists(command) {
46276
46475
  const trimmed = command.trim();
@@ -46415,10 +46614,10 @@ function hasConfigOverride(args, key2) {
46415
46614
  return false;
46416
46615
  }
46417
46616
  function ensureEmptyDelegatedMcpConfig(workspace) {
46418
- const baseDir = path28.join(os21.tmpdir(), "adhdev-delegated-agent-empty-mcp");
46617
+ const baseDir = path29.join(os22.tmpdir(), "adhdev-delegated-agent-empty-mcp");
46419
46618
  (0, import_fs16.mkdirSync)(baseDir, { recursive: true });
46420
- const workspaceHash = shortHash(path28.resolve(workspace || os21.tmpdir()));
46421
- const filePath = path28.join(baseDir, `${workspaceHash}.json`);
46619
+ const workspaceHash = shortHash(path29.resolve(workspace || os22.tmpdir()));
46620
+ const filePath = path29.join(baseDir, `${workspaceHash}.json`);
46422
46621
  (0, import_fs16.writeFileSync)(filePath, JSON.stringify({ mcpServers: {} }, null, 2), "utf-8");
46423
46622
  return filePath;
46424
46623
  }
@@ -46572,7 +46771,7 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
46572
46771
  if (!supportsExplicitSessionStart(resume)) {
46573
46772
  return { cliArgs: baseArgs, launchMode: "new" };
46574
46773
  }
46575
- const providerSessionId = crypto5.randomUUID();
46774
+ const providerSessionId = crypto6.randomUUID();
46576
46775
  const newSessionArgs = expandResumeArgs(resume.newSessionArgs, providerSessionId);
46577
46776
  return {
46578
46777
  cliArgs: [...baseArgs || [], ...newSessionArgs || []],
@@ -46756,7 +46955,7 @@ var DaemonCliManager = class {
46756
46955
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
46757
46956
  const trimmed = (workingDir || "").trim();
46758
46957
  if (!trimmed) throw new Error("working directory required");
46759
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os21.homedir()) : path28.resolve(trimmed);
46958
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os22.homedir()) : path29.resolve(trimmed);
46760
46959
  const normalizedType = this.providerLoader.resolveAlias(cliType);
46761
46960
  const rawProvider = this.providerLoader.getByAlias(cliType);
46762
46961
  const provider = rawProvider ? this.providerLoader.resolve(normalizedType) || rawProvider : void 0;
@@ -46767,7 +46966,7 @@ var DaemonCliManager = class {
46767
46966
  Enable and detect this provider from the Machine Providers page before starting a runtime.`
46768
46967
  );
46769
46968
  }
46770
- const key2 = crypto5.randomUUID();
46969
+ const key2 = crypto6.randomUUID();
46771
46970
  {
46772
46971
  const coordinatorMeshId = options?.settingsOverride?.meshCoordinatorFor;
46773
46972
  if (typeof coordinatorMeshId === "string" && coordinatorMeshId.trim()) {
@@ -47608,13 +47807,13 @@ var cliAgentHandlers = {
47608
47807
  // src/launch.ts
47609
47808
  var import_child_process9 = require("child_process");
47610
47809
  var net = __toESM(require("net"));
47611
- var os26 = __toESM(require("os"));
47612
- var path36 = __toESM(require("path"));
47810
+ var os27 = __toESM(require("os"));
47811
+ var path37 = __toESM(require("path"));
47613
47812
 
47614
47813
  // src/providers/provider-loader.ts
47615
- var fs25 = __toESM(require("fs"));
47616
- var path35 = __toESM(require("path"));
47617
- var os25 = __toESM(require("os"));
47814
+ var fs26 = __toESM(require("fs"));
47815
+ var path36 = __toESM(require("path"));
47816
+ var os26 = __toESM(require("os"));
47618
47817
  var chokidar = __toESM(require("chokidar"));
47619
47818
  init_hash();
47620
47819
  init_logger();
@@ -48006,13 +48205,13 @@ function validateControl(control, errors) {
48006
48205
  init_external_sources();
48007
48206
 
48008
48207
  // src/providers/native-history/dispatcher.ts
48009
- var fs24 = __toESM(require("fs"));
48010
- var os24 = __toESM(require("os"));
48011
- var path33 = __toESM(require("path"));
48208
+ var fs25 = __toESM(require("fs"));
48209
+ var os25 = __toESM(require("os"));
48210
+ var path34 = __toESM(require("path"));
48012
48211
 
48013
48212
  // src/providers/native-history/claude-cli-transcript.ts
48014
- var fs20 = __toESM(require("fs"));
48015
- var path29 = __toESM(require("path"));
48213
+ var fs21 = __toESM(require("fs"));
48214
+ var path30 = __toESM(require("path"));
48016
48215
  function extractTimestampValue(value) {
48017
48216
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
48018
48217
  if (typeof value === "string") {
@@ -48025,7 +48224,7 @@ function extractTimestampValue(value) {
48025
48224
  }
48026
48225
  function statMtimeMs(filePath) {
48027
48226
  try {
48028
- return fs20.statSync(filePath).mtimeMs;
48227
+ return fs21.statSync(filePath).mtimeMs;
48029
48228
  } catch {
48030
48229
  return 0;
48031
48230
  }
@@ -48095,7 +48294,7 @@ function extractUserContentParts(content) {
48095
48294
  function parseTranscriptFile(filePath, sessionId, workspaceFallback) {
48096
48295
  let raw;
48097
48296
  try {
48098
- raw = fs20.readFileSync(filePath, "utf-8");
48297
+ raw = fs21.readFileSync(filePath, "utf-8");
48099
48298
  } catch {
48100
48299
  return [];
48101
48300
  }
@@ -48168,10 +48367,10 @@ function parseTranscriptFile(filePath, sessionId, workspaceFallback) {
48168
48367
  return records;
48169
48368
  }
48170
48369
  function readSession(sessionPath) {
48171
- if (!sessionPath || !path29.isAbsolute(sessionPath)) return null;
48172
- const basename14 = path29.basename(sessionPath, ".jsonl");
48370
+ if (!sessionPath || !path30.isAbsolute(sessionPath)) return null;
48371
+ const basename14 = path30.basename(sessionPath, ".jsonl");
48173
48372
  if (!isSafeSessionId(basename14)) return null;
48174
- if (!fs20.existsSync(sessionPath)) return null;
48373
+ if (!fs21.existsSync(sessionPath)) return null;
48175
48374
  const sourceMtimeMs = statMtimeMs(sessionPath);
48176
48375
  const messages = parseTranscriptFile(sessionPath, basename14);
48177
48376
  if (messages.length === 0) return null;
@@ -48189,8 +48388,8 @@ function readSession(sessionPath) {
48189
48388
  }
48190
48389
 
48191
48390
  // src/providers/native-history/codex-cli-transcript.ts
48192
- var fs21 = __toESM(require("fs"));
48193
- var path30 = __toESM(require("path"));
48391
+ var fs22 = __toESM(require("fs"));
48392
+ var path31 = __toESM(require("path"));
48194
48393
  function extractTimestampValue2(value) {
48195
48394
  if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
48196
48395
  if (typeof value === "string") {
@@ -48203,7 +48402,7 @@ function extractTimestampValue2(value) {
48203
48402
  }
48204
48403
  function statMtimeMs2(filePath) {
48205
48404
  try {
48206
- return fs21.statSync(filePath).mtimeMs;
48405
+ return fs22.statSync(filePath).mtimeMs;
48207
48406
  } catch {
48208
48407
  return 0;
48209
48408
  }
@@ -48300,7 +48499,7 @@ function pushAssistantStandardMessage(records, sessionId, receivedAt, content, w
48300
48499
  }
48301
48500
  function readSessionMeta(filePath) {
48302
48501
  try {
48303
- const firstLine = fs21.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
48502
+ const firstLine = fs22.readFileSync(filePath, "utf-8").split("\n").find(Boolean);
48304
48503
  if (!firstLine) return null;
48305
48504
  const parsed = JSON.parse(firstLine);
48306
48505
  if (String(parsed.type ?? "") !== "session_meta") return null;
@@ -48312,7 +48511,7 @@ function readSessionMeta(filePath) {
48312
48511
  function parseSessionFile(filePath, sessionId, workspaceFallback) {
48313
48512
  let raw;
48314
48513
  try {
48315
- raw = fs21.readFileSync(filePath, "utf-8");
48514
+ raw = fs22.readFileSync(filePath, "utf-8");
48316
48515
  } catch {
48317
48516
  return [];
48318
48517
  }
@@ -48427,11 +48626,11 @@ function parseSessionFile(filePath, sessionId, workspaceFallback) {
48427
48626
  return records;
48428
48627
  }
48429
48628
  function readSession2(sessionPath) {
48430
- if (!sessionPath || !path30.isAbsolute(sessionPath)) return null;
48431
- if (!fs21.existsSync(sessionPath)) return null;
48629
+ if (!sessionPath || !path31.isAbsolute(sessionPath)) return null;
48630
+ if (!fs22.existsSync(sessionPath)) return null;
48432
48631
  const meta = readSessionMeta(sessionPath);
48433
48632
  const metaId = String(meta?.id ?? "").trim();
48434
- const basename14 = path30.basename(sessionPath, ".jsonl");
48633
+ const basename14 = path31.basename(sessionPath, ".jsonl");
48435
48634
  const uuidMatch = basename14.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
48436
48635
  const filenameUuid2 = uuidMatch ? uuidMatch[1] : "";
48437
48636
  if (metaId && filenameUuid2 && metaId !== filenameUuid2) return null;
@@ -48455,9 +48654,9 @@ function readSession2(sessionPath) {
48455
48654
  }
48456
48655
 
48457
48656
  // src/providers/native-history/antigravity-cli-transcript.ts
48458
- var fs22 = __toESM(require("fs"));
48459
- var path31 = __toESM(require("path"));
48460
- var os22 = __toESM(require("os"));
48657
+ var fs23 = __toESM(require("fs"));
48658
+ var path32 = __toESM(require("path"));
48659
+ var os23 = __toESM(require("os"));
48461
48660
  init_load_better_sqlite3();
48462
48661
  init_logger();
48463
48662
  function extractTimestampValue3(value) {
@@ -48472,7 +48671,7 @@ function extractTimestampValue3(value) {
48472
48671
  }
48473
48672
  function statMtimeMs3(filePath) {
48474
48673
  try {
48475
- return fs22.statSync(filePath).mtimeMs;
48674
+ return fs23.statSync(filePath).mtimeMs;
48476
48675
  } catch {
48477
48676
  return 0;
48478
48677
  }
@@ -48481,13 +48680,13 @@ function isUuidLike(value) {
48481
48680
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
48482
48681
  }
48483
48682
  function antigravityRoot() {
48484
- return path31.join(os22.homedir(), ".gemini", "antigravity-cli");
48683
+ return path32.join(os23.homedir(), ".gemini", "antigravity-cli");
48485
48684
  }
48486
48685
  function historyJsonlPath() {
48487
- return path31.join(antigravityRoot(), "history.jsonl");
48686
+ return path32.join(antigravityRoot(), "history.jsonl");
48488
48687
  }
48489
48688
  function brainRoot() {
48490
- return path31.join(antigravityRoot(), "brain");
48689
+ return path32.join(antigravityRoot(), "brain");
48491
48690
  }
48492
48691
  function extractUserRequestContent(content) {
48493
48692
  const raw = content.trim();
@@ -48503,7 +48702,7 @@ function antigravityRowKind(rowType) {
48503
48702
  function parseBrainTranscript(filePath, sessionId, workspace) {
48504
48703
  let raw;
48505
48704
  try {
48506
- raw = fs22.readFileSync(filePath, "utf-8");
48705
+ raw = fs23.readFileSync(filePath, "utf-8");
48507
48706
  } catch {
48508
48707
  return null;
48509
48708
  }
@@ -48563,7 +48762,7 @@ function readHistoryRows() {
48563
48762
  const sourcePath = historyJsonlPath();
48564
48763
  let lines = [];
48565
48764
  try {
48566
- lines = fs22.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
48765
+ lines = fs23.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
48567
48766
  } catch {
48568
48767
  return [];
48569
48768
  }
@@ -48611,7 +48810,7 @@ function extractStringsFromBuffer(buf) {
48611
48810
  function parsePbFile(filePath, sessionId) {
48612
48811
  let buf;
48613
48812
  try {
48614
- buf = fs22.readFileSync(filePath);
48813
+ buf = fs23.readFileSync(filePath);
48615
48814
  } catch {
48616
48815
  return null;
48617
48816
  }
@@ -48781,7 +48980,7 @@ function parseConversationDb(filePath, sessionId, workspace) {
48781
48980
  } catch (err) {
48782
48981
  LOG.warn(
48783
48982
  "NativeHistory",
48784
- `antigravity .db reader could not load better-sqlite3 for ${path31.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (native binding unavailable \u2014 assistant answers in this .db will not surface)`
48983
+ `antigravity .db reader could not load better-sqlite3 for ${path32.basename(filePath)}: ${err instanceof Error ? err.message : String(err)} (native binding unavailable \u2014 assistant answers in this .db will not surface)`
48785
48984
  );
48786
48985
  return null;
48787
48986
  }
@@ -48811,13 +49010,13 @@ function parseConversationDb(filePath, sessionId, workspace) {
48811
49010
  }
48812
49011
  LOG.warn(
48813
49012
  "NativeHistory",
48814
- `antigravity .db ${path31.basename(filePath)} stayed locked (SQLITE_BUSY) after ${AGY_DB_MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)} (WAL write/checkpoint lock contention \u2014 assistant answers may transiently not surface this read)`
49013
+ `antigravity .db ${path32.basename(filePath)} stayed locked (SQLITE_BUSY) after ${AGY_DB_MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)} (WAL write/checkpoint lock contention \u2014 assistant answers may transiently not surface this read)`
48815
49014
  );
48816
49015
  return null;
48817
49016
  }
48818
49017
  LOG.debug(
48819
49018
  "NativeHistory",
48820
- `antigravity .db ${path31.basename(filePath)} not readable: ${err instanceof Error ? err.message : String(err)}`
49019
+ `antigravity .db ${path32.basename(filePath)} not readable: ${err instanceof Error ? err.message : String(err)}`
48821
49020
  );
48822
49021
  return null;
48823
49022
  } finally {
@@ -48844,12 +49043,12 @@ function parseConversationDb(filePath, sessionId, workspace) {
48844
49043
  content = recovered;
48845
49044
  LOG.debug(
48846
49045
  "NativeHistory",
48847
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}): user prompt absent at field 19; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
49046
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}): user prompt absent at field 19; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48848
49047
  );
48849
49048
  } else {
48850
49049
  LOG.debug(
48851
49050
  "NativeHistory",
48852
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no user prompt text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}])`
49051
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no user prompt text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}])`
48853
49052
  );
48854
49053
  continue;
48855
49054
  }
@@ -48874,12 +49073,12 @@ function parseConversationDb(filePath, sessionId, workspace) {
48874
49073
  content = recovered;
48875
49074
  LOG.debug(
48876
49075
  "NativeHistory",
48877
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}): answer absent at field 20; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
49076
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}): answer absent at field 20; recovered ${content.length} chars via printable-run fallback \u2014 possible step_payload schema drift`
48878
49077
  );
48879
49078
  } else {
48880
49079
  LOG.debug(
48881
49080
  "NativeHistory",
48882
- `antigravity .db ${path31.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no answer text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}], reasoningOnly=${reasoning ? "yes" : "no"})`
49081
+ `antigravity .db ${path32.basename(filePath)} step ${row.idx} (type ${row.step_type}) dropped: no answer text (payload ${payload.length}B, top-level fields [${topLevelFieldNumbers(payload).join(",")}], reasoningOnly=${reasoning ? "yes" : "no"})`
48883
49082
  );
48884
49083
  continue;
48885
49084
  }
@@ -48900,13 +49099,13 @@ function parseConversationDb(filePath, sessionId, workspace) {
48900
49099
  return messages.length > 0 ? messages : null;
48901
49100
  }
48902
49101
  function readSession3(sessionPath, sessionId, workspace) {
48903
- if (!sessionPath || !path31.isAbsolute(sessionPath)) return null;
48904
- if (!fs22.existsSync(sessionPath)) return null;
49102
+ if (!sessionPath || !path32.isAbsolute(sessionPath)) return null;
49103
+ if (!fs23.existsSync(sessionPath)) return null;
48905
49104
  const sourceMtimeMs = statMtimeMs3(sessionPath);
48906
49105
  const brainRootPath = brainRoot();
48907
- if (sessionPath.startsWith(brainRootPath + path31.sep) && sessionPath.endsWith(".jsonl")) {
49106
+ if (sessionPath.startsWith(brainRootPath + path32.sep) && sessionPath.endsWith(".jsonl")) {
48908
49107
  const relative5 = sessionPath.slice(brainRootPath.length + 1);
48909
- const uuidFromPath = relative5.split(path31.sep)[0];
49108
+ const uuidFromPath = relative5.split(path32.sep)[0];
48910
49109
  const resolvedSessionId = sessionId || (isUuidLike(uuidFromPath) ? uuidFromPath : "");
48911
49110
  if (!resolvedSessionId) return null;
48912
49111
  const messages = parseBrainTranscript(sessionPath, resolvedSessionId, workspace);
@@ -48922,7 +49121,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48922
49121
  };
48923
49122
  }
48924
49123
  if (sessionPath.endsWith(".db")) {
48925
- const dbSessionId = sessionId || path31.basename(sessionPath, ".db");
49124
+ const dbSessionId = sessionId || path32.basename(sessionPath, ".db");
48926
49125
  if (!isUuidLike(dbSessionId)) return null;
48927
49126
  const messages = parseConversationDb(sessionPath, dbSessionId, workspace);
48928
49127
  if (!messages || messages.length === 0) return null;
@@ -48937,7 +49136,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48937
49136
  };
48938
49137
  }
48939
49138
  if (sessionPath.endsWith(".pb")) {
48940
- const pbSessionId = sessionId || path31.basename(sessionPath, ".pb");
49139
+ const pbSessionId = sessionId || path32.basename(sessionPath, ".pb");
48941
49140
  if (!isUuidLike(pbSessionId)) return null;
48942
49141
  const messages = parsePbFile(sessionPath, pbSessionId);
48943
49142
  if (!messages || messages.length === 0) return null;
@@ -48951,7 +49150,7 @@ function readSession3(sessionPath, sessionId, workspace) {
48951
49150
  partialReason: "antigravity_cli_pb_raw_text_extraction"
48952
49151
  };
48953
49152
  }
48954
- if (path31.basename(sessionPath) === "history.jsonl") {
49153
+ if (path32.basename(sessionPath) === "history.jsonl") {
48955
49154
  const resolvedSessionId = sessionId || "";
48956
49155
  if (!resolvedSessionId || !isUuidLike(resolvedSessionId)) return null;
48957
49156
  const rows = readHistoryRows().filter((r) => r.conversationId === resolvedSessionId);
@@ -48998,21 +49197,21 @@ function readSession3(sessionPath, sessionId, workspace) {
48998
49197
  }
48999
49198
 
49000
49199
  // src/providers/native-history/hermes-cli-transcript.ts
49001
- var fs23 = __toESM(require("fs"));
49002
- var path32 = __toESM(require("path"));
49003
- var os23 = __toESM(require("os"));
49200
+ var fs24 = __toESM(require("fs"));
49201
+ var path33 = __toESM(require("path"));
49202
+ var os24 = __toESM(require("os"));
49004
49203
  init_load_better_sqlite3();
49005
- var HERMES_STATE_DB = path32.join(os23.homedir(), ".hermes", "state.db");
49006
- var HERMES_LEGACY_SESSIONS_DIR = path32.join(os23.homedir(), ".hermes", "sessions");
49204
+ var HERMES_STATE_DB = path33.join(os24.homedir(), ".hermes", "state.db");
49205
+ var HERMES_LEGACY_SESSIONS_DIR = path33.join(os24.homedir(), ".hermes", "sessions");
49007
49206
  function statMtimeMs4(p) {
49008
49207
  try {
49009
- return Math.floor(fs23.statSync(p).mtimeMs);
49208
+ return Math.floor(fs24.statSync(p).mtimeMs);
49010
49209
  } catch {
49011
49210
  return 0;
49012
49211
  }
49013
49212
  }
49014
49213
  function openDb() {
49015
- if (!fs23.existsSync(HERMES_STATE_DB)) return null;
49214
+ if (!fs24.existsSync(HERMES_STATE_DB)) return null;
49016
49215
  try {
49017
49216
  const Database = loadBetterSqlite3();
49018
49217
  return new Database(HERMES_STATE_DB, { readonly: true, fileMustExist: true });
@@ -49108,10 +49307,10 @@ function readSession4(sessionPath, requestedSessionId) {
49108
49307
  }
49109
49308
  }
49110
49309
  }
49111
- if (!path32.isAbsolute(sessionPath) || !fs23.existsSync(sessionPath)) return null;
49310
+ if (!path33.isAbsolute(sessionPath) || !fs24.existsSync(sessionPath)) return null;
49112
49311
  let raw;
49113
49312
  try {
49114
- raw = JSON.parse(fs23.readFileSync(sessionPath, "utf8"));
49313
+ raw = JSON.parse(fs24.readFileSync(sessionPath, "utf8"));
49115
49314
  } catch {
49116
49315
  return null;
49117
49316
  }
@@ -49134,7 +49333,7 @@ function readSession4(sessionPath, requestedSessionId) {
49134
49333
  });
49135
49334
  }
49136
49335
  if (messages.length === 0) return null;
49137
- const sessionId = typeof raw.session_id === "string" && raw.session_id ? raw.session_id : path32.basename(sessionPath, ".json").replace(/^session_/, "");
49336
+ const sessionId = typeof raw.session_id === "string" && raw.session_id ? raw.session_id : path33.basename(sessionPath, ".json").replace(/^session_/, "");
49138
49337
  return {
49139
49338
  messages,
49140
49339
  providerSessionId: sessionId,
@@ -49164,7 +49363,7 @@ function createNativeHistoryDispatcher(reader) {
49164
49363
  if (!sourcePath) return null;
49165
49364
  if (input.forceRefresh === true || input.args?.forceRefresh === true) {
49166
49365
  try {
49167
- fs24.statSync(sourcePath);
49366
+ fs25.statSync(sourcePath);
49168
49367
  } catch {
49169
49368
  }
49170
49369
  }
@@ -49201,11 +49400,11 @@ function resolveSourcePath(reader, workspace, sessionId, sessionStartedAtMs, ins
49201
49400
  }
49202
49401
  }
49203
49402
  function resolveClaudePath(workspace, sessionId) {
49204
- const dir = path33.join(os24.homedir(), ".claude", "projects", cwdAsDashes(workspace));
49205
- if (!fs24.existsSync(dir)) return null;
49403
+ const dir = path34.join(os25.homedir(), ".claude", "projects", cwdAsDashes(workspace));
49404
+ if (!fs25.existsSync(dir)) return null;
49206
49405
  if (sessionId) {
49207
- const candidate = path33.join(dir, `${sessionId}.jsonl`);
49208
- if (fs24.existsSync(candidate)) return candidate;
49406
+ const candidate = path34.join(dir, `${sessionId}.jsonl`);
49407
+ if (fs25.existsSync(candidate)) return candidate;
49209
49408
  }
49210
49409
  return null;
49211
49410
  }
@@ -49217,7 +49416,7 @@ function resolveCodexPath(workspace, sessionId, sessionStartedAtMs) {
49217
49416
  return findCodexPathByRuntime(root, workspace, sessionStartedAtMs);
49218
49417
  }
49219
49418
  function findCodexPathBySessionId(root, sessionId) {
49220
- if (!fs24.existsSync(root)) return null;
49419
+ if (!fs25.existsSync(root)) return null;
49221
49420
  const needle = sessionId.toLowerCase();
49222
49421
  const matches = [];
49223
49422
  const stack = [root];
@@ -49225,12 +49424,12 @@ function findCodexPathBySessionId(root, sessionId) {
49225
49424
  const current = stack.pop();
49226
49425
  let entries = [];
49227
49426
  try {
49228
- entries = fs24.readdirSync(current, { withFileTypes: true });
49427
+ entries = fs25.readdirSync(current, { withFileTypes: true });
49229
49428
  } catch {
49230
49429
  continue;
49231
49430
  }
49232
49431
  for (const entry of entries) {
49233
- const entryPath = path33.join(current, entry.name);
49432
+ const entryPath = path34.join(current, entry.name);
49234
49433
  if (entry.isDirectory()) {
49235
49434
  stack.push(entryPath);
49236
49435
  continue;
@@ -49245,7 +49444,7 @@ function findCodexPathBySessionId(root, sessionId) {
49245
49444
  return matches[0]?.p ?? null;
49246
49445
  }
49247
49446
  function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49248
- if (!fs24.existsSync(root) || !workspace) return null;
49447
+ if (!fs25.existsSync(root) || !workspace) return null;
49249
49448
  const workspaceResolved = resolveRealPath(workspace);
49250
49449
  const cutoff = Date.now() - RECENT_WINDOW_MS;
49251
49450
  const matches = [];
@@ -49254,12 +49453,12 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49254
49453
  const current = stack.pop();
49255
49454
  let entries = [];
49256
49455
  try {
49257
- entries = fs24.readdirSync(current, { withFileTypes: true });
49456
+ entries = fs25.readdirSync(current, { withFileTypes: true });
49258
49457
  } catch {
49259
49458
  continue;
49260
49459
  }
49261
49460
  for (const entry of entries) {
49262
- const entryPath = path33.join(current, entry.name);
49461
+ const entryPath = path34.join(current, entry.name);
49263
49462
  if (entry.isDirectory()) {
49264
49463
  stack.push(entryPath);
49265
49464
  continue;
@@ -49279,10 +49478,10 @@ function findCodexPathByRuntime(root, workspace, sessionStartedAtMs) {
49279
49478
  }
49280
49479
  function readCodexSessionMeta(filePath) {
49281
49480
  try {
49282
- const fd = fs24.openSync(filePath, "r");
49481
+ const fd = fs25.openSync(filePath, "r");
49283
49482
  try {
49284
49483
  const buffer = Buffer.alloc(8192);
49285
- const bytes = fs24.readSync(fd, buffer, 0, buffer.length, 0);
49484
+ const bytes = fs25.readSync(fd, buffer, 0, buffer.length, 0);
49286
49485
  if (bytes <= 0) return null;
49287
49486
  const text = buffer.subarray(0, bytes).toString("utf8");
49288
49487
  const firstLine = text.slice(0, text.indexOf("\n") >= 0 ? text.indexOf("\n") : text.length).trim();
@@ -49297,7 +49496,7 @@ function readCodexSessionMeta(filePath) {
49297
49496
  timestampMs: Number.isFinite(timestampMs) ? timestampMs : void 0
49298
49497
  };
49299
49498
  } finally {
49300
- fs24.closeSync(fd);
49499
+ fs25.closeSync(fd);
49301
49500
  }
49302
49501
  } catch {
49303
49502
  return null;
@@ -49305,35 +49504,35 @@ function readCodexSessionMeta(filePath) {
49305
49504
  }
49306
49505
  function resolveRealPath(value) {
49307
49506
  try {
49308
- return fs24.realpathSync(value);
49507
+ return fs25.realpathSync(value);
49309
49508
  } catch {
49310
49509
  return value;
49311
49510
  }
49312
49511
  }
49313
49512
  var AGY_SPAWN_CLAIM_GRACE_MS = 2e3;
49314
49513
  function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instanceId) {
49315
- const agyRoot = path33.join(os24.homedir(), ".gemini", "antigravity-cli");
49514
+ const agyRoot = path34.join(os25.homedir(), ".gemini", "antigravity-cli");
49316
49515
  const owner = antigravityOwnerToken(workspace, sessionStartedAtMs, instanceId);
49317
49516
  if (sessionId && isUuidLikeSessionId2(sessionId)) {
49318
- const dbPath = path33.join(agyRoot, "conversations", `${sessionId}.db`);
49319
- if (fs24.existsSync(dbPath)) {
49517
+ const dbPath = path34.join(agyRoot, "conversations", `${sessionId}.db`);
49518
+ if (fs25.existsSync(dbPath)) {
49320
49519
  if (owner) claimAntigravityConversation(sessionId, owner);
49321
49520
  return dbPath;
49322
49521
  }
49323
49522
  }
49324
- const brainRoot2 = path33.join(agyRoot, "brain");
49325
- if (fs24.existsSync(brainRoot2)) {
49523
+ const brainRoot2 = path34.join(agyRoot, "brain");
49524
+ if (fs25.existsSync(brainRoot2)) {
49326
49525
  const cutoff = spawnAwareCutoff(sessionStartedAtMs);
49327
- const entries = fs24.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => ({ uuid: e.name, p: path33.join(brainRoot2, e.name), mtime: safeMtime(path33.join(brainRoot2, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49526
+ const entries = fs25.readdirSync(brainRoot2, { withFileTypes: true }).filter((e) => e.isDirectory() && isUuidLikeSessionId2(e.name)).filter((e) => !isAntigravityConversationClaimedByOther(e.name, owner)).map((e) => ({ uuid: e.name, p: path34.join(brainRoot2, e.name), mtime: safeMtime(path34.join(brainRoot2, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49328
49527
  for (const e of entries) {
49329
- const t = path33.join(e.p, ".system_generated", "logs", "transcript.jsonl");
49330
- if (fs24.existsSync(t) && safeSize(t) > 0) {
49528
+ const t = path34.join(e.p, ".system_generated", "logs", "transcript.jsonl");
49529
+ if (fs25.existsSync(t) && safeSize(t) > 0) {
49331
49530
  if (owner) claimAntigravityConversation(e.uuid, owner);
49332
49531
  return t;
49333
49532
  }
49334
49533
  }
49335
49534
  }
49336
- const convRoot = path33.join(agyRoot, "conversations");
49535
+ const convRoot = path34.join(agyRoot, "conversations");
49337
49536
  const picked = pickUnboundConversationDb(convRoot, sessionStartedAtMs, owner);
49338
49537
  if (picked) {
49339
49538
  if (owner) claimAntigravityConversation(picked.uuid, owner);
@@ -49344,7 +49543,7 @@ function resolveAntigravityPath(workspace, sessionId, sessionStartedAtMs, instan
49344
49543
  function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
49345
49544
  let entries = [];
49346
49545
  try {
49347
- entries = fs24.readdirSync(convRoot, { withFileTypes: true });
49546
+ entries = fs25.readdirSync(convRoot, { withFileTypes: true });
49348
49547
  } catch {
49349
49548
  return null;
49350
49549
  }
@@ -49356,7 +49555,7 @@ function pickUnboundConversationDb(convRoot, sessionFloorMs, owner) {
49356
49555
  if (!match || !isUuidLikeSessionId2(match[1])) continue;
49357
49556
  const uuid = match[1];
49358
49557
  if (isAntigravityConversationClaimedByOther(uuid, owner)) continue;
49359
- const p = path33.join(convRoot, entry.name);
49558
+ const p = path34.join(convRoot, entry.name);
49360
49559
  const mtime = safeMtime(p);
49361
49560
  if (mtime < recencyCutoff) continue;
49362
49561
  candidates.push({ path: p, uuid, mtime, birth: safeBirthtime(p) });
@@ -49380,10 +49579,10 @@ function spawnAwareCutoff(sessionStartedAtMs) {
49380
49579
  function resolveHermesPath(workspace, sessionId) {
49381
49580
  void workspace;
49382
49581
  void sessionId;
49383
- const dbPath = path33.join(os24.homedir(), ".hermes", "state.db");
49384
- if (fs24.existsSync(dbPath)) return dbPath;
49385
- const dir = path33.join(os24.homedir(), ".hermes", "sessions");
49386
- if (!fs24.existsSync(dir)) return null;
49582
+ const dbPath = path34.join(os25.homedir(), ".hermes", "state.db");
49583
+ if (fs25.existsSync(dbPath)) return dbPath;
49584
+ const dir = path34.join(os25.homedir(), ".hermes", "sessions");
49585
+ if (!fs25.existsSync(dir)) return null;
49387
49586
  return newestRecentFile2(dir, /^session_.*\.json$/);
49388
49587
  }
49389
49588
  function readByReader(reader, sourcePath, sessionId, workspace, requestedProviderSid) {
@@ -49408,7 +49607,7 @@ function cwdAsDashes(cwd) {
49408
49607
  return cwd.replace(/\//g, "-");
49409
49608
  }
49410
49609
  function codexSessionsRoot() {
49411
- return path33.join(os24.homedir(), ".codex", "sessions");
49610
+ return path34.join(os25.homedir(), ".codex", "sessions");
49412
49611
  }
49413
49612
  function isUuidLikeSessionId2(sessionId) {
49414
49613
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId);
@@ -49420,7 +49619,7 @@ var RECENT_WINDOW_MS = 5 * 60 * 1e3;
49420
49619
  function newestRecentFile2(dir, pattern) {
49421
49620
  try {
49422
49621
  const cutoff = Date.now() - RECENT_WINDOW_MS;
49423
- const entries = fs24.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path33.join(dir, e.name), mtime: safeMtime(path33.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49622
+ const entries = fs25.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && pattern.test(e.name)).map((e) => ({ p: path34.join(dir, e.name), mtime: safeMtime(path34.join(dir, e.name)) })).filter((e) => e.mtime >= cutoff).sort((a, b) => b.mtime - a.mtime);
49424
49623
  return entries[0]?.p ?? null;
49425
49624
  } catch {
49426
49625
  return null;
@@ -49428,14 +49627,14 @@ function newestRecentFile2(dir, pattern) {
49428
49627
  }
49429
49628
  function safeMtime(p) {
49430
49629
  try {
49431
- return Math.floor(fs24.statSync(p).mtimeMs);
49630
+ return Math.floor(fs25.statSync(p).mtimeMs);
49432
49631
  } catch {
49433
49632
  return 0;
49434
49633
  }
49435
49634
  }
49436
49635
  function safeBirthtime(p) {
49437
49636
  try {
49438
- const st = fs24.statSync(p);
49637
+ const st = fs25.statSync(p);
49439
49638
  const birth = Math.floor(st.birthtimeMs);
49440
49639
  return birth > 0 ? birth : Math.floor(st.mtimeMs);
49441
49640
  } catch {
@@ -49444,7 +49643,7 @@ function safeBirthtime(p) {
49444
49643
  }
49445
49644
  function safeSize(p) {
49446
49645
  try {
49447
- return fs24.statSync(p).size;
49646
+ return fs25.statSync(p).size;
49448
49647
  } catch {
49449
49648
  return 0;
49450
49649
  }
@@ -49538,9 +49737,9 @@ var ProviderLoader = class _ProviderLoader {
49538
49737
  static siblingStderrLogged = /* @__PURE__ */ new Set();
49539
49738
  static looksLikeProviderRoot(candidate) {
49540
49739
  try {
49541
- if (!fs25.existsSync(candidate) || !fs25.statSync(candidate).isDirectory()) return false;
49740
+ if (!fs26.existsSync(candidate) || !fs26.statSync(candidate).isDirectory()) return false;
49542
49741
  return ["ide", "extension", "cli", "acp"].some(
49543
- (category) => fs25.existsSync(path35.join(candidate, category))
49742
+ (category) => fs26.existsSync(path36.join(candidate, category))
49544
49743
  );
49545
49744
  } catch {
49546
49745
  return false;
@@ -49548,20 +49747,20 @@ var ProviderLoader = class _ProviderLoader {
49548
49747
  }
49549
49748
  static hasProviderRootMarker(candidate) {
49550
49749
  try {
49551
- return fs25.existsSync(path35.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
49750
+ return fs26.existsSync(path36.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
49552
49751
  } catch {
49553
49752
  return false;
49554
49753
  }
49555
49754
  }
49556
49755
  detectDefaultUserDir() {
49557
- const fallback = path35.join(os25.homedir(), ".adhdev", "providers");
49756
+ const fallback = path36.join(os26.homedir(), ".adhdev", "providers");
49558
49757
  const envOptIn = process.env[_ProviderLoader.SIBLING_ENV_VAR] === "1";
49559
49758
  const visited = /* @__PURE__ */ new Set();
49560
49759
  for (const start of this.probeStarts) {
49561
- let current = path35.resolve(start);
49760
+ let current = path36.resolve(start);
49562
49761
  while (!visited.has(current)) {
49563
49762
  visited.add(current);
49564
- const siblingCandidate = path35.join(path35.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
49763
+ const siblingCandidate = path36.join(path36.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
49565
49764
  if (_ProviderLoader.looksLikeProviderRoot(siblingCandidate)) {
49566
49765
  const hasMarker = _ProviderLoader.hasProviderRootMarker(siblingCandidate);
49567
49766
  if (envOptIn || hasMarker) {
@@ -49583,7 +49782,7 @@ var ProviderLoader = class _ProviderLoader {
49583
49782
  return { path: siblingCandidate, source };
49584
49783
  }
49585
49784
  }
49586
- const parent = path35.dirname(current);
49785
+ const parent = path36.dirname(current);
49587
49786
  if (parent === current) break;
49588
49787
  current = parent;
49589
49788
  }
@@ -49595,11 +49794,11 @@ var ProviderLoader = class _ProviderLoader {
49595
49794
  this.probeStarts = options?.probeStarts ?? [process.cwd(), __dirname];
49596
49795
  this.registryBaseUrl = resolveRegistryBaseUrl(options?.registryUrl);
49597
49796
  this.providerTarballUrl = resolveProviderTarballUrl(options?.providerTarballUrl);
49598
- this.defaultProvidersDir = path35.join(os25.homedir(), ".adhdev", "providers");
49797
+ this.defaultProvidersDir = path36.join(os26.homedir(), ".adhdev", "providers");
49599
49798
  const detected = this.detectDefaultUserDir();
49600
49799
  this.userDir = detected.path;
49601
49800
  this.userDirSource = detected.source;
49602
- this.upstreamDir = path35.join(this.defaultProvidersDir, ".upstream");
49801
+ this.upstreamDir = path36.join(this.defaultProvidersDir, ".upstream");
49603
49802
  this.disableUpstream = false;
49604
49803
  this.applySourceConfig({
49605
49804
  userDir: options?.userDir,
@@ -49610,15 +49809,15 @@ var ProviderLoader = class _ProviderLoader {
49610
49809
  }
49611
49810
  migrateMarketplaceDirToExternal() {
49612
49811
  try {
49613
- const home = os25.homedir();
49614
- const oldDir = path35.join(home, ".adhdev", "marketplace");
49615
- const newDir = path35.join(home, ".adhdev", "external");
49616
- if (!fs25.existsSync(oldDir)) return;
49617
- if (fs25.existsSync(newDir)) {
49812
+ const home = os26.homedir();
49813
+ const oldDir = path36.join(home, ".adhdev", "marketplace");
49814
+ const newDir = path36.join(home, ".adhdev", "external");
49815
+ if (!fs26.existsSync(oldDir)) return;
49816
+ if (fs26.existsSync(newDir)) {
49618
49817
  this.log(`Migration skipped: both ~/.adhdev/marketplace and ~/.adhdev/external exist (marketplace dir is now inert and can be removed manually).`);
49619
49818
  return;
49620
49819
  }
49621
- fs25.renameSync(oldDir, newDir);
49820
+ fs26.renameSync(oldDir, newDir);
49622
49821
  this.log(`Migrated ~/.adhdev/marketplace \u2192 ~/.adhdev/external (one-time rename after provider source-layer cleanup).`);
49623
49822
  } catch (e) {
49624
49823
  this.log(`Marketplace\u2192external migration failed: ${e?.message || e}`);
@@ -49648,7 +49847,7 @@ var ProviderLoader = class _ProviderLoader {
49648
49847
  * Highest-priority editable overrides come first.
49649
49848
  */
49650
49849
  getProviderRoots() {
49651
- const externalDir = path35.join(os25.homedir(), ".adhdev", "external");
49850
+ const externalDir = path36.join(os26.homedir(), ".adhdev", "external");
49652
49851
  return [this.userDir, externalDir, this.upstreamDir];
49653
49852
  }
49654
49853
  getSourceConfig() {
@@ -49676,7 +49875,7 @@ var ProviderLoader = class _ProviderLoader {
49676
49875
  this.userDir = detected.path;
49677
49876
  this.userDirSource = detected.source;
49678
49877
  }
49679
- this.upstreamDir = path35.join(this.defaultProvidersDir, ".upstream");
49878
+ this.upstreamDir = path36.join(this.defaultProvidersDir, ".upstream");
49680
49879
  this.disableUpstream = this.sourceMode === "no-upstream";
49681
49880
  if (this.explicitProviderDir) {
49682
49881
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
@@ -49690,7 +49889,7 @@ var ProviderLoader = class _ProviderLoader {
49690
49889
  * Canonical provider directory shape for a given root.
49691
49890
  */
49692
49891
  getProviderDir(root, category, type) {
49693
- return path35.join(root, category, type);
49892
+ return path36.join(root, category, type);
49694
49893
  }
49695
49894
  /**
49696
49895
  * Canonical user override directory for a provider.
@@ -49717,7 +49916,7 @@ var ProviderLoader = class _ProviderLoader {
49717
49916
  resolveProviderFile(type, ...segments) {
49718
49917
  const dir = this.findProviderDirInternal(type);
49719
49918
  if (!dir) return null;
49720
- return path35.join(dir, ...segments);
49919
+ return path36.join(dir, ...segments);
49721
49920
  }
49722
49921
  /**
49723
49922
  * Load all providers (3-tier priority)
@@ -49733,7 +49932,7 @@ var ProviderLoader = class _ProviderLoader {
49733
49932
  this.providers.clear();
49734
49933
  this.providerAvailability.clear();
49735
49934
  let upstreamCount = 0;
49736
- if (!this.disableUpstream && fs25.existsSync(this.upstreamDir)) {
49935
+ if (!this.disableUpstream && fs26.existsSync(this.upstreamDir)) {
49737
49936
  upstreamCount = this.loadDir(this.upstreamDir);
49738
49937
  if (upstreamCount > 0) {
49739
49938
  this.log(`Loaded ${upstreamCount} upstream providers (auto-updated)`);
@@ -49741,11 +49940,11 @@ var ProviderLoader = class _ProviderLoader {
49741
49940
  } else if (this.disableUpstream) {
49742
49941
  this.log("Upstream loading disabled (sourceMode=no-upstream)");
49743
49942
  }
49744
- const externalDir = path35.join(os25.homedir(), ".adhdev", "external");
49745
- if (fs25.existsSync(externalDir)) {
49943
+ const externalDir = path36.join(os26.homedir(), ".adhdev", "external");
49944
+ if (fs26.existsSync(externalDir)) {
49746
49945
  const rootEntries = (() => {
49747
49946
  try {
49748
- return fs25.readdirSync(externalDir, { withFileTypes: true });
49947
+ return fs26.readdirSync(externalDir, { withFileTypes: true });
49749
49948
  } catch {
49750
49949
  return [];
49751
49950
  }
@@ -49763,7 +49962,7 @@ var ProviderLoader = class _ProviderLoader {
49763
49962
  const ambiguousTypes = [];
49764
49963
  for (const sourceEntry of rootEntries) {
49765
49964
  if (!sourceEntry.isDirectory()) continue;
49766
- const sourceDir = path35.join(externalDir, sourceEntry.name);
49965
+ const sourceDir = path36.join(externalDir, sourceEntry.name);
49767
49966
  const sourceLoaded = this.loadDir(sourceDir);
49768
49967
  if (sourceLoaded > 0) {
49769
49968
  totalLoaded += sourceLoaded;
@@ -49779,7 +49978,7 @@ var ProviderLoader = class _ProviderLoader {
49779
49978
  ambiguousTypes.push({ type, chosen: resolved.source ?? "?", candidates: resolved.candidates });
49780
49979
  }
49781
49980
  if (resolved.source && resolved.source !== "?") {
49782
- const sourceDir = path35.join(externalDir, resolved.source);
49981
+ const sourceDir = path36.join(externalDir, resolved.source);
49783
49982
  const reloadCount = this.loadDir(sourceDir);
49784
49983
  if (reloadCount === 0) {
49785
49984
  this.log(`Active source "${resolved.source}" no longer provides ${type}`);
@@ -49794,7 +49993,7 @@ var ProviderLoader = class _ProviderLoader {
49794
49993
  }
49795
49994
  }
49796
49995
  }
49797
- if (fs25.existsSync(this.userDir)) {
49996
+ if (fs26.existsSync(this.userDir)) {
49798
49997
  const userCount = this.loadDir(this.userDir, [".upstream"]);
49799
49998
  if (userCount > 0) {
49800
49999
  this.log(`Loaded ${userCount} user custom providers (never auto-updated)`);
@@ -49809,10 +50008,10 @@ var ProviderLoader = class _ProviderLoader {
49809
50008
  * Check if upstream directory exists and has providers.
49810
50009
  */
49811
50010
  hasUpstream() {
49812
- if (!fs25.existsSync(this.upstreamDir)) return false;
50011
+ if (!fs26.existsSync(this.upstreamDir)) return false;
49813
50012
  try {
49814
- return fs25.readdirSync(this.upstreamDir).some(
49815
- (d) => fs25.statSync(path35.join(this.upstreamDir, d)).isDirectory()
50013
+ return fs26.readdirSync(this.upstreamDir).some(
50014
+ (d) => fs26.statSync(path36.join(this.upstreamDir, d)).isDirectory()
49816
50015
  );
49817
50016
  } catch {
49818
50017
  return false;
@@ -50310,8 +50509,8 @@ var ProviderLoader = class _ProviderLoader {
50310
50509
  resolved._resolvedScriptDir = entry.scriptDir;
50311
50510
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
50312
50511
  if (providerDir) {
50313
- const fullDir = path35.join(providerDir, entry.scriptDir);
50314
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50512
+ const fullDir = path36.join(providerDir, entry.scriptDir);
50513
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50315
50514
  }
50316
50515
  matched = true;
50317
50516
  }
@@ -50329,8 +50528,8 @@ var ProviderLoader = class _ProviderLoader {
50329
50528
  resolved._resolvedScriptDir = base.defaultScriptDir;
50330
50529
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
50331
50530
  if (providerDir) {
50332
- const fullDir = path35.join(providerDir, base.defaultScriptDir);
50333
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50531
+ const fullDir = path36.join(providerDir, base.defaultScriptDir);
50532
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50334
50533
  }
50335
50534
  }
50336
50535
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -50347,8 +50546,8 @@ var ProviderLoader = class _ProviderLoader {
50347
50546
  resolved._resolvedScriptDir = dirOverride;
50348
50547
  resolved._resolvedScriptsSource = `versions:${range}`;
50349
50548
  if (providerDir) {
50350
- const fullDir = path35.join(providerDir, dirOverride);
50351
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50549
+ const fullDir = path36.join(providerDir, dirOverride);
50550
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50352
50551
  }
50353
50552
  }
50354
50553
  } else if (override.scripts) {
@@ -50364,8 +50563,8 @@ var ProviderLoader = class _ProviderLoader {
50364
50563
  resolved._resolvedScriptDir = base.defaultScriptDir;
50365
50564
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
50366
50565
  if (providerDir) {
50367
- const fullDir = path35.join(providerDir, base.defaultScriptDir);
50368
- resolved._resolvedScriptsPath = fs25.existsSync(path35.join(fullDir, "scripts.js")) ? path35.join(fullDir, "scripts.js") : fullDir;
50566
+ const fullDir = path36.join(providerDir, base.defaultScriptDir);
50567
+ resolved._resolvedScriptsPath = fs26.existsSync(path36.join(fullDir, "scripts.js")) ? path36.join(fullDir, "scripts.js") : fullDir;
50369
50568
  }
50370
50569
  }
50371
50570
  }
@@ -50382,13 +50581,13 @@ var ProviderLoader = class _ProviderLoader {
50382
50581
  if (providerDir2) {
50383
50582
  for (const [scriptName, override] of Object.entries(base.overrides)) {
50384
50583
  if (!override || typeof override.path !== "string") continue;
50385
- const fullPath = path35.join(providerDir2, override.path);
50386
- if (!fs25.existsSync(fullPath)) {
50584
+ const fullPath = path36.join(providerDir2, override.path);
50585
+ if (!fs26.existsSync(fullPath)) {
50387
50586
  this.log(` [overrides] ${base.type}: ${scriptName} path not found: ${fullPath}`);
50388
50587
  continue;
50389
50588
  }
50390
50589
  try {
50391
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(providerDir2)));
50590
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(providerDir2)));
50392
50591
  delete require.cache[require.resolve(fullPath)];
50393
50592
  const fn = require(fullPath);
50394
50593
  const target = typeof fn === "function" ? fn : fn && fn[scriptName];
@@ -50413,25 +50612,25 @@ var ProviderLoader = class _ProviderLoader {
50413
50612
  }
50414
50613
  if (providerDir) {
50415
50614
  try {
50416
- const fs40 = require("fs");
50417
- const path44 = require("path");
50615
+ const fs41 = require("fs");
50616
+ const path45 = require("path");
50418
50617
  const candidates = [];
50419
50618
  if (Array.isArray(base.compatibility)) {
50420
50619
  for (const entry of base.compatibility) {
50421
50620
  if (typeof entry?.spec !== "string") continue;
50422
50621
  const matches = !entry.ideVersion || currentVersion && this.matchesVersion(currentVersion, entry.ideVersion) || !currentVersion;
50423
- if (matches) candidates.push(path44.join(providerDir, entry.spec));
50622
+ if (matches) candidates.push(path45.join(providerDir, entry.spec));
50424
50623
  }
50425
50624
  }
50426
- candidates.push(path44.join(providerDir, "specs", "default.json"));
50427
- candidates.push(path44.join(providerDir, "spec.json"));
50428
- const specPath = candidates.find((p) => fs40.existsSync(p));
50625
+ candidates.push(path45.join(providerDir, "specs", "default.json"));
50626
+ candidates.push(path45.join(providerDir, "spec.json"));
50627
+ const specPath = candidates.find((p) => fs41.existsSync(p));
50429
50628
  if (specPath) {
50430
50629
  resolved._resolvedSpecPath = specPath;
50431
50630
  let specControls;
50432
50631
  let nh;
50433
50632
  try {
50434
- const rawSpec = JSON.parse(fs40.readFileSync(specPath, "utf8"));
50633
+ const rawSpec = JSON.parse(fs41.readFileSync(specPath, "utf8"));
50435
50634
  specControls = rawSpec.control_bar;
50436
50635
  nh = rawSpec.native_history;
50437
50636
  } catch {
@@ -50462,10 +50661,10 @@ var ProviderLoader = class _ProviderLoader {
50462
50661
  format = `spec-${nh.source.kind}`;
50463
50662
  reader = (input) => executeNativeHistory(nh, input);
50464
50663
  } else if (nh.override_path) {
50465
- const overrideFile = path44.resolve(providerDir, nh.override_path);
50466
- if (fs40.existsSync(overrideFile)) {
50664
+ const overrideFile = path45.resolve(providerDir, nh.override_path);
50665
+ if (fs41.existsSync(overrideFile)) {
50467
50666
  try {
50468
- registerProviderScriptRootSafely(path44.dirname(path44.dirname(providerDir)));
50667
+ registerProviderScriptRootSafely(path45.dirname(path45.dirname(providerDir)));
50469
50668
  delete require.cache[require.resolve(overrideFile)];
50470
50669
  const mod = require(overrideFile);
50471
50670
  const fn = typeof mod === "function" ? mod : mod && typeof mod.default === "function" ? mod.default : null;
@@ -50508,16 +50707,16 @@ var ProviderLoader = class _ProviderLoader {
50508
50707
  this.debugLog(`[loadScriptsFromDir] ${type}: providerDir not found`);
50509
50708
  return null;
50510
50709
  }
50511
- const dir = path35.join(providerDir, scriptDir);
50512
- if (!fs25.existsSync(dir)) {
50710
+ const dir = path36.join(providerDir, scriptDir);
50711
+ if (!fs26.existsSync(dir)) {
50513
50712
  this.debugLog(`[loadScriptsFromDir] ${type}: dir not found: ${dir}`);
50514
50713
  return null;
50515
50714
  }
50516
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(providerDir)));
50715
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(providerDir)));
50517
50716
  const cached3 = this.scriptsCache.get(dir);
50518
50717
  if (cached3) return cached3;
50519
- const scriptsJs = path35.join(dir, "scripts.js");
50520
- if (fs25.existsSync(scriptsJs)) {
50718
+ const scriptsJs = path36.join(dir, "scripts.js");
50719
+ if (fs26.existsSync(scriptsJs)) {
50521
50720
  try {
50522
50721
  delete require.cache[require.resolve(scriptsJs)];
50523
50722
  const loaded = require(scriptsJs);
@@ -50538,9 +50737,9 @@ var ProviderLoader = class _ProviderLoader {
50538
50737
  watch() {
50539
50738
  this.stopWatch();
50540
50739
  const watchDir = (dir) => {
50541
- if (!fs25.existsSync(dir)) {
50740
+ if (!fs26.existsSync(dir)) {
50542
50741
  try {
50543
- fs25.mkdirSync(dir, { recursive: true });
50742
+ fs26.mkdirSync(dir, { recursive: true });
50544
50743
  } catch {
50545
50744
  return;
50546
50745
  }
@@ -50561,7 +50760,7 @@ var ProviderLoader = class _ProviderLoader {
50561
50760
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
50562
50761
  if (reloadTimer) clearTimeout(reloadTimer);
50563
50762
  reloadTimer = setTimeout(() => {
50564
- this.log(`File changed: ${path35.basename(filePath)}, reloading...`);
50763
+ this.log(`File changed: ${path36.basename(filePath)}, reloading...`);
50565
50764
  this.reload();
50566
50765
  }, 300);
50567
50766
  }
@@ -50629,11 +50828,11 @@ var ProviderLoader = class _ProviderLoader {
50629
50828
  }
50630
50829
  this.log(`Registry sync starting (${this.registryBaseUrl})...`);
50631
50830
  const https = require("https");
50632
- const regMetaPath = path35.join(this.upstreamDir, _ProviderLoader.REGISTRY_META_FILE);
50831
+ const regMetaPath = path36.join(this.upstreamDir, _ProviderLoader.REGISTRY_META_FILE);
50633
50832
  let cachedChecksums = {};
50634
50833
  try {
50635
- if (fs25.existsSync(regMetaPath)) {
50636
- cachedChecksums = JSON.parse(fs25.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
50834
+ if (fs26.existsSync(regMetaPath)) {
50835
+ cachedChecksums = JSON.parse(fs26.readFileSync(regMetaPath, "utf-8")).checksums ?? {};
50637
50836
  }
50638
50837
  } catch {
50639
50838
  }
@@ -50684,15 +50883,15 @@ var ProviderLoader = class _ProviderLoader {
50684
50883
  this.log(`\u26A0 Registry checksum mismatch for ${type}@${version} \u2014 skipping`);
50685
50884
  continue;
50686
50885
  }
50687
- const providerDir = path35.join(this.upstreamDir, category, type);
50688
- fs25.mkdirSync(providerDir, { recursive: true });
50689
- fs25.writeFileSync(path35.join(providerDir, "provider.json"), manifestBody, "utf-8");
50886
+ const providerDir = path36.join(this.upstreamDir, category, type);
50887
+ fs26.mkdirSync(providerDir, { recursive: true });
50888
+ fs26.writeFileSync(path36.join(providerDir, "provider.json"), manifestBody, "utf-8");
50690
50889
  cachedChecksums[cacheKey] = checksum;
50691
50890
  updatedCount++;
50692
50891
  this.log(`\u2713 Registry updated: ${category}/${type}@${version}`);
50693
50892
  }
50694
- fs25.mkdirSync(this.upstreamDir, { recursive: true });
50695
- fs25.writeFileSync(regMetaPath, JSON.stringify({
50893
+ fs26.mkdirSync(this.upstreamDir, { recursive: true });
50894
+ fs26.writeFileSync(regMetaPath, JSON.stringify({
50696
50895
  checksums: cachedChecksums,
50697
50896
  syncedAt: (/* @__PURE__ */ new Date()).toISOString(),
50698
50897
  providerCount: list.providers.length
@@ -50713,12 +50912,12 @@ var ProviderLoader = class _ProviderLoader {
50713
50912
  const { exec: exec7 } = require("child_process");
50714
50913
  const { promisify: promisify8 } = require("util");
50715
50914
  const execAsync5 = promisify8(exec7);
50716
- const metaPath = path35.join(this.upstreamDir, _ProviderLoader.META_FILE);
50915
+ const metaPath = path36.join(this.upstreamDir, _ProviderLoader.META_FILE);
50717
50916
  let prevEtag = "";
50718
50917
  let prevTimestamp = 0;
50719
50918
  try {
50720
- if (fs25.existsSync(metaPath)) {
50721
- const meta = JSON.parse(fs25.readFileSync(metaPath, "utf-8"));
50919
+ if (fs26.existsSync(metaPath)) {
50920
+ const meta = JSON.parse(fs26.readFileSync(metaPath, "utf-8"));
50722
50921
  prevEtag = meta.etag || "";
50723
50922
  prevTimestamp = meta.timestamp || 0;
50724
50923
  }
@@ -50774,39 +50973,39 @@ var ProviderLoader = class _ProviderLoader {
50774
50973
  return { updated: false };
50775
50974
  }
50776
50975
  this.log("Downloading latest providers from GitHub...");
50777
- const tmpTar = path35.join(os25.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
50778
- const tmpExtract = path35.join(os25.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
50976
+ const tmpTar = path36.join(os26.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
50977
+ const tmpExtract = path36.join(os26.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
50779
50978
  await this.downloadFile(tarballTarget.url, tmpTar);
50780
- fs25.mkdirSync(tmpExtract, { recursive: true });
50979
+ fs26.mkdirSync(tmpExtract, { recursive: true });
50781
50980
  await execAsync5(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
50782
- const extracted = fs25.readdirSync(tmpExtract);
50981
+ const extracted = fs26.readdirSync(tmpExtract);
50783
50982
  const rootDir = extracted.find(
50784
- (d) => fs25.statSync(path35.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
50983
+ (d) => fs26.statSync(path36.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
50785
50984
  );
50786
50985
  if (!rootDir) throw new Error("Unexpected tarball structure");
50787
- const sourceDir = path35.join(tmpExtract, rootDir);
50986
+ const sourceDir = path36.join(tmpExtract, rootDir);
50788
50987
  const backupDir = this.upstreamDir + ".bak";
50789
- if (fs25.existsSync(this.upstreamDir)) {
50790
- if (fs25.existsSync(backupDir)) fs25.rmSync(backupDir, { recursive: true, force: true });
50791
- fs25.renameSync(this.upstreamDir, backupDir);
50988
+ if (fs26.existsSync(this.upstreamDir)) {
50989
+ if (fs26.existsSync(backupDir)) fs26.rmSync(backupDir, { recursive: true, force: true });
50990
+ fs26.renameSync(this.upstreamDir, backupDir);
50792
50991
  }
50793
50992
  try {
50794
50993
  this.copyDirRecursive(sourceDir, this.upstreamDir);
50795
50994
  this.writeMeta(metaPath, etag || `ts-${Date.now()}`, Date.now());
50796
- if (fs25.existsSync(backupDir)) fs25.rmSync(backupDir, { recursive: true, force: true });
50995
+ if (fs26.existsSync(backupDir)) fs26.rmSync(backupDir, { recursive: true, force: true });
50797
50996
  } catch (e) {
50798
- if (fs25.existsSync(backupDir)) {
50799
- if (fs25.existsSync(this.upstreamDir)) fs25.rmSync(this.upstreamDir, { recursive: true, force: true });
50800
- fs25.renameSync(backupDir, this.upstreamDir);
50997
+ if (fs26.existsSync(backupDir)) {
50998
+ if (fs26.existsSync(this.upstreamDir)) fs26.rmSync(this.upstreamDir, { recursive: true, force: true });
50999
+ fs26.renameSync(backupDir, this.upstreamDir);
50801
51000
  }
50802
51001
  throw e;
50803
51002
  }
50804
51003
  try {
50805
- fs25.rmSync(tmpTar, { force: true });
51004
+ fs26.rmSync(tmpTar, { force: true });
50806
51005
  } catch {
50807
51006
  }
50808
51007
  try {
50809
- fs25.rmSync(tmpExtract, { recursive: true, force: true });
51008
+ fs26.rmSync(tmpExtract, { recursive: true, force: true });
50810
51009
  } catch {
50811
51010
  }
50812
51011
  const upstreamCount = this.countProviders(this.upstreamDir);
@@ -50838,7 +51037,7 @@ var ProviderLoader = class _ProviderLoader {
50838
51037
  reject(new Error(`HTTP ${res.statusCode}`));
50839
51038
  return;
50840
51039
  }
50841
- const ws = fs25.createWriteStream(destPath);
51040
+ const ws = fs26.createWriteStream(destPath);
50842
51041
  res.pipe(ws);
50843
51042
  ws.on("finish", () => {
50844
51043
  ws.close();
@@ -50857,22 +51056,22 @@ var ProviderLoader = class _ProviderLoader {
50857
51056
  }
50858
51057
  /** Recursive directory copy */
50859
51058
  copyDirRecursive(src, dest) {
50860
- fs25.mkdirSync(dest, { recursive: true });
50861
- for (const entry of fs25.readdirSync(src, { withFileTypes: true })) {
50862
- const srcPath = path35.join(src, entry.name);
50863
- const destPath = path35.join(dest, entry.name);
51059
+ fs26.mkdirSync(dest, { recursive: true });
51060
+ for (const entry of fs26.readdirSync(src, { withFileTypes: true })) {
51061
+ const srcPath = path36.join(src, entry.name);
51062
+ const destPath = path36.join(dest, entry.name);
50864
51063
  if (entry.isDirectory()) {
50865
51064
  this.copyDirRecursive(srcPath, destPath);
50866
51065
  } else {
50867
- fs25.copyFileSync(srcPath, destPath);
51066
+ fs26.copyFileSync(srcPath, destPath);
50868
51067
  }
50869
51068
  }
50870
51069
  }
50871
51070
  /** .meta.json save */
50872
51071
  writeMeta(metaPath, etag, timestamp) {
50873
51072
  try {
50874
- fs25.mkdirSync(path35.dirname(metaPath), { recursive: true });
50875
- fs25.writeFileSync(metaPath, JSON.stringify({
51073
+ fs26.mkdirSync(path36.dirname(metaPath), { recursive: true });
51074
+ fs26.writeFileSync(metaPath, JSON.stringify({
50876
51075
  etag,
50877
51076
  timestamp,
50878
51077
  lastCheck: new Date(timestamp).toISOString(),
@@ -50883,15 +51082,15 @@ var ProviderLoader = class _ProviderLoader {
50883
51082
  }
50884
51083
  /** Count provider files (provider.v1.json or provider.json — at most one per dir). */
50885
51084
  countProviders(dir) {
50886
- if (!fs25.existsSync(dir)) return 0;
51085
+ if (!fs26.existsSync(dir)) return 0;
50887
51086
  let count = 0;
50888
51087
  const scan = (d) => {
50889
51088
  try {
50890
- const entries = fs25.readdirSync(d, { withFileTypes: true });
51089
+ const entries = fs26.readdirSync(d, { withFileTypes: true });
50891
51090
  const hasManifest = entries.some((e) => e.name === "provider.v1.json" || e.name === "provider.json");
50892
51091
  if (hasManifest) count++;
50893
51092
  for (const entry of entries) {
50894
- if (entry.isDirectory()) scan(path35.join(d, entry.name));
51093
+ if (entry.isDirectory()) scan(path36.join(d, entry.name));
50895
51094
  }
50896
51095
  } catch {
50897
51096
  }
@@ -51117,13 +51316,13 @@ var ProviderLoader = class _ProviderLoader {
51117
51316
  if (!provider) return null;
51118
51317
  const cat = provider.category;
51119
51318
  const searchRoots = this.getProviderRoots();
51120
- const hasManifest = (dir) => fs25.existsSync(path35.join(dir, "provider.v1.json")) || fs25.existsSync(path35.join(dir, "provider.json"));
51319
+ const hasManifest = (dir) => fs26.existsSync(path36.join(dir, "provider.v1.json")) || fs26.existsSync(path36.join(dir, "provider.json"));
51121
51320
  const readManifestType = (dir) => {
51122
51321
  for (const file of ["provider.v1.json", "provider.json"]) {
51123
- const p = path35.join(dir, file);
51124
- if (!fs25.existsSync(p)) continue;
51322
+ const p = path36.join(dir, file);
51323
+ if (!fs26.existsSync(p)) continue;
51125
51324
  try {
51126
- const data = JSON.parse(fs25.readFileSync(p, "utf-8"));
51325
+ const data = JSON.parse(fs26.readFileSync(p, "utf-8"));
51127
51326
  if (typeof data?.type === "string") return data.type;
51128
51327
  } catch {
51129
51328
  }
@@ -51131,15 +51330,15 @@ var ProviderLoader = class _ProviderLoader {
51131
51330
  return null;
51132
51331
  };
51133
51332
  for (const root of searchRoots) {
51134
- if (!fs25.existsSync(root)) continue;
51333
+ if (!fs26.existsSync(root)) continue;
51135
51334
  const candidate = this.getProviderDir(root, cat, type);
51136
51335
  if (hasManifest(candidate)) return candidate;
51137
- const catDir = path35.join(root, cat);
51138
- if (fs25.existsSync(catDir)) {
51336
+ const catDir = path36.join(root, cat);
51337
+ if (fs26.existsSync(catDir)) {
51139
51338
  try {
51140
- for (const entry of fs25.readdirSync(catDir, { withFileTypes: true })) {
51339
+ for (const entry of fs26.readdirSync(catDir, { withFileTypes: true })) {
51141
51340
  if (!entry.isDirectory()) continue;
51142
- const entryDir = path35.join(catDir, entry.name);
51341
+ const entryDir = path36.join(catDir, entry.name);
51143
51342
  const manifestType = readManifestType(entryDir);
51144
51343
  if (manifestType === type) return entryDir;
51145
51344
  }
@@ -51155,8 +51354,8 @@ var ProviderLoader = class _ProviderLoader {
51155
51354
  * (template substitution is NOT applied here — scripts.js handles that)
51156
51355
  */
51157
51356
  buildScriptWrappersFromDir(dir) {
51158
- const scriptsJs = path35.join(dir, "scripts.js");
51159
- if (fs25.existsSync(scriptsJs)) {
51357
+ const scriptsJs = path36.join(dir, "scripts.js");
51358
+ if (fs26.existsSync(scriptsJs)) {
51160
51359
  try {
51161
51360
  delete require.cache[require.resolve(scriptsJs)];
51162
51361
  return require(scriptsJs);
@@ -51166,13 +51365,13 @@ var ProviderLoader = class _ProviderLoader {
51166
51365
  const toCamel = (name) => name.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
51167
51366
  const result = {};
51168
51367
  try {
51169
- for (const file of fs25.readdirSync(dir)) {
51368
+ for (const file of fs26.readdirSync(dir)) {
51170
51369
  if (!file.endsWith(".js")) continue;
51171
51370
  const scriptName = toCamel(file.replace(".js", ""));
51172
- const filePath = path35.join(dir, file);
51371
+ const filePath = path36.join(dir, file);
51173
51372
  result[scriptName] = (...args) => {
51174
51373
  try {
51175
- let content = fs25.readFileSync(filePath, "utf-8");
51374
+ let content = fs26.readFileSync(filePath, "utf-8");
51176
51375
  if (args[0] && typeof args[0] === "object") {
51177
51376
  for (const [key2, val] of Object.entries(args[0])) {
51178
51377
  let v = val;
@@ -51218,12 +51417,12 @@ var ProviderLoader = class _ProviderLoader {
51218
51417
  * Structure: dir/category/agent-name/provider.{json,js}
51219
51418
  */
51220
51419
  loadDir(dir, excludeDirs) {
51221
- if (!fs25.existsSync(dir)) return 0;
51420
+ if (!fs26.existsSync(dir)) return 0;
51222
51421
  let count = 0;
51223
51422
  const scan = (d) => {
51224
51423
  let entries;
51225
51424
  try {
51226
- entries = fs25.readdirSync(d, { withFileTypes: true });
51425
+ entries = fs26.readdirSync(d, { withFileTypes: true });
51227
51426
  } catch {
51228
51427
  return;
51229
51428
  }
@@ -51231,9 +51430,9 @@ var ProviderLoader = class _ProviderLoader {
51231
51430
  const hasJson = entries.some((e) => e.name === "provider.json");
51232
51431
  if (hasV1 || hasJson) {
51233
51432
  const manifestFile = hasV1 ? "provider.v1.json" : "provider.json";
51234
- const jsonPath = path35.join(d, manifestFile);
51433
+ const jsonPath = path36.join(d, manifestFile);
51235
51434
  try {
51236
- const raw = fs25.readFileSync(jsonPath, "utf-8");
51435
+ const raw = fs26.readFileSync(jsonPath, "utf-8");
51237
51436
  const mod = JSON.parse(raw);
51238
51437
  if (hasV1 && mod?.category === "cli") {
51239
51438
  try {
@@ -51271,10 +51470,10 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51271
51470
  this.log(`\u26A0 Invalid provider at ${jsonPath}: ${validation.errors.join("; ")}`);
51272
51471
  } else {
51273
51472
  const hasCompatibility = Array.isArray(normalizedProvider.compatibility);
51274
- const scriptsPath = path35.join(d, "scripts.js");
51275
- if (!hasCompatibility && fs25.existsSync(scriptsPath)) {
51473
+ const scriptsPath = path36.join(d, "scripts.js");
51474
+ if (!hasCompatibility && fs26.existsSync(scriptsPath)) {
51276
51475
  try {
51277
- registerProviderScriptRootSafely(path35.dirname(path35.dirname(d)));
51476
+ registerProviderScriptRootSafely(path36.dirname(path36.dirname(d)));
51278
51477
  delete require.cache[require.resolve(scriptsPath)];
51279
51478
  const scripts = require(scriptsPath);
51280
51479
  normalizedProvider.scripts = scripts;
@@ -51282,7 +51481,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51282
51481
  this.log(`\u26A0 Failed to load scripts: ${scriptsPath}: ${e.message}`);
51283
51482
  }
51284
51483
  }
51285
- const externalDirAbs = path35.join(os25.homedir(), ".adhdev", "external");
51484
+ const externalDirAbs = path36.join(os26.homedir(), ".adhdev", "external");
51286
51485
  const layer = d.startsWith(externalDirAbs) ? "external" : d.startsWith(this.userDir) && !d.includes(".upstream") ? "user" : "upstream";
51287
51486
  try {
51288
51487
  const { inspectManifestShape: inspectManifestShape2, classifyTrust: classifyTrust2 } = (init_provider_trust(), __toCommonJS(provider_trust_exports));
@@ -51292,8 +51491,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51292
51491
  normalizedProvider._sourceTrust = trust;
51293
51492
  normalizedProvider._manifestShape = shape;
51294
51493
  if (layer === "external") {
51295
- const rel = path35.relative(externalDirAbs, d);
51296
- const firstSeg = rel.split(path35.sep)[0];
51494
+ const rel = path36.relative(externalDirAbs, d);
51495
+ const firstSeg = rel.split(path36.sep)[0];
51297
51496
  if (firstSeg && firstSeg !== "..") normalizedProvider._sourceName = firstSeg;
51298
51497
  }
51299
51498
  } catch {
@@ -51317,7 +51516,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
51317
51516
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
51318
51517
  if (d === dir && entry.name === "examples") continue;
51319
51518
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
51320
- scan(path35.join(d, entry.name));
51519
+ scan(path36.join(d, entry.name));
51321
51520
  }
51322
51521
  }
51323
51522
  };
@@ -51515,7 +51714,7 @@ async function isCdpActive(port) {
51515
51714
  });
51516
51715
  }
51517
51716
  async function killIdeProcess(ideId) {
51518
- const plat = os26.platform();
51717
+ const plat = os27.platform();
51519
51718
  const appName = getMacAppIdentifiers()[ideId];
51520
51719
  const winProcesses = getWinProcessNames()[ideId];
51521
51720
  try {
@@ -51576,7 +51775,7 @@ async function killIdeProcess(ideId) {
51576
51775
  }
51577
51776
  }
51578
51777
  async function isIdeRunning(ideId) {
51579
- const plat = os26.platform();
51778
+ const plat = os27.platform();
51580
51779
  try {
51581
51780
  if (plat === "darwin") {
51582
51781
  const appName = getMacAppIdentifiers()[ideId];
@@ -51631,7 +51830,7 @@ async function isIdeRunning(ideId) {
51631
51830
  }
51632
51831
  }
51633
51832
  async function detectCurrentWorkspace(ideId) {
51634
- const plat = os26.platform();
51833
+ const plat = os27.platform();
51635
51834
  if (plat === "darwin") {
51636
51835
  try {
51637
51836
  const appName = getMacAppIdentifiers()[ideId];
@@ -51646,17 +51845,17 @@ async function detectCurrentWorkspace(ideId) {
51646
51845
  }
51647
51846
  } else if (plat === "win32") {
51648
51847
  try {
51649
- const fs40 = require("fs");
51848
+ const fs41 = require("fs");
51650
51849
  const appNameMap = getMacAppIdentifiers();
51651
51850
  const appName = appNameMap[ideId];
51652
51851
  if (appName) {
51653
- const storagePath = path36.join(
51654
- process.env.APPDATA || path36.join(os26.homedir(), "AppData", "Roaming"),
51852
+ const storagePath = path37.join(
51853
+ process.env.APPDATA || path37.join(os27.homedir(), "AppData", "Roaming"),
51655
51854
  appName,
51656
51855
  "storage.json"
51657
51856
  );
51658
- if (fs40.existsSync(storagePath)) {
51659
- const data = JSON.parse(fs40.readFileSync(storagePath, "utf-8"));
51857
+ if (fs41.existsSync(storagePath)) {
51858
+ const data = JSON.parse(fs41.readFileSync(storagePath, "utf-8"));
51660
51859
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
51661
51860
  if (workspaces.length > 0) {
51662
51861
  const recent = workspaces[0];
@@ -51673,7 +51872,7 @@ async function detectCurrentWorkspace(ideId) {
51673
51872
  return void 0;
51674
51873
  }
51675
51874
  async function launchWithCdp(options = {}) {
51676
- const platform10 = os26.platform();
51875
+ const platform10 = os27.platform();
51677
51876
  let targetIde;
51678
51877
  const ides = await detectIDEs(getProviderLoader());
51679
51878
  if (options.ideId) {
@@ -52176,11 +52375,11 @@ var meshCrudHandlers = {
52176
52375
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
52177
52376
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
52178
52377
  const { mkdirSync: mkdirSync22, writeFileSync: writeFileSync24 } = await import("fs");
52179
- const { dirname: dirname17, join: join50 } = await import("path");
52378
+ const { dirname: dirname17, join: join51 } = await import("path");
52180
52379
  const scaffold = buildMeshJsonConfigScaffold2(mesh);
52181
52380
  const scaffoldJson = serializeMeshJsonConfigScaffold2(scaffold);
52182
52381
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
52183
- const absolutePath = join50(workspace, relativePath);
52382
+ const absolutePath = join51(workspace, relativePath);
52184
52383
  const validation = normalizeRepoMeshDeclarativeConfig2(scaffold);
52185
52384
  if (!validation.valid) {
52186
52385
  return { success: false, meshId, error: `invalid mesh.json scaffold: ${validation.errors.join("; ")}` };
@@ -53633,7 +53832,7 @@ var meshEventsHandlers = {
53633
53832
 
53634
53833
  // src/commands/high-family/mesh-coordinator-launch.ts
53635
53834
  var import_path13 = require("path");
53636
- var fs26 = __toESM(require("fs"));
53835
+ var fs27 = __toESM(require("fs"));
53637
53836
  init_logger();
53638
53837
  init_mesh_host_ownership();
53639
53838
  init_coordinator_registry();
@@ -53868,15 +54067,15 @@ ${ptyResult.output.slice(-2e3)}`);
53868
54067
  }
53869
54068
  if (cliType === "codex-cli") {
53870
54069
  const repoMcpConfigPath = (0, import_path13.join)(workspace, ".mcp.json");
53871
- if (fs26.existsSync(repoMcpConfigPath)) {
54070
+ if (fs27.existsSync(repoMcpConfigPath)) {
53872
54071
  try {
53873
54072
  const repoMcpConfig = parseMeshCoordinatorMcpConfig(
53874
- fs26.readFileSync(repoMcpConfigPath, "utf-8"),
54073
+ fs27.readFileSync(repoMcpConfigPath, "utf-8"),
53875
54074
  "claude_mcp_json"
53876
54075
  );
53877
54076
  const existingServers2 = repoMcpConfig.mcpServers;
53878
54077
  if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
53879
- fs26.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
54078
+ fs27.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
53880
54079
  ...repoMcpConfig,
53881
54080
  mcpServers: {
53882
54081
  ...existingServers2,
@@ -54159,7 +54358,7 @@ ${ptyResult.output.slice(-2e3)}`);
54159
54358
  };
54160
54359
 
54161
54360
  // src/commands/high-family/mesh-status.ts
54162
- var fs27 = __toESM(require("fs"));
54361
+ var fs28 = __toESM(require("fs"));
54163
54362
  var import_os3 = require("os");
54164
54363
  init_config();
54165
54364
  init_git_status();
@@ -54206,10 +54405,10 @@ function runGit2(repoRoot, args) {
54206
54405
  }
54207
54406
  }
54208
54407
  function readRecord6(repoRoot) {
54209
- const path44 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
54210
- if (!(0, import_node_fs4.existsSync)(path44)) return null;
54408
+ const path45 = (0, import_node_path2.resolve)(repoRoot, PREVIEW_DEPLOY_RECORD);
54409
+ if (!(0, import_node_fs4.existsSync)(path45)) return null;
54211
54410
  try {
54212
- const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path44, "utf8"));
54411
+ const parsed = JSON.parse((0, import_node_fs4.readFileSync)(path45, "utf8"));
54213
54412
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
54214
54413
  } catch {
54215
54414
  return null;
@@ -54520,7 +54719,7 @@ var meshStatusHandlers = {
54520
54719
  }
54521
54720
  }
54522
54721
  if (workspace) {
54523
- if (!fs27.existsSync(workspace)) {
54722
+ if (!fs28.existsSync(workspace)) {
54524
54723
  const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
54525
54724
  let remoteProbeApplied = false;
54526
54725
  if (inlineTransitGit) {
@@ -54650,7 +54849,7 @@ var meshStatusHandlers = {
54650
54849
  backstop: { ...getMeshV2BackstopCounters() }
54651
54850
  };
54652
54851
  const previewFreshness = (() => {
54653
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs27.existsSync(candidate));
54852
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs28.existsSync(candidate));
54654
54853
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
54655
54854
  })();
54656
54855
  const asyncRefineJobs = buildMeshAsyncRefineJobs({
@@ -54850,15 +55049,15 @@ init_dist();
54850
55049
  init_logger();
54851
55050
 
54852
55051
  // src/logging/command-log.ts
54853
- var fs28 = __toESM(require("fs"));
54854
- var path37 = __toESM(require("path"));
54855
- var os27 = __toESM(require("os"));
54856
- var ADHDEV_HOME2 = process.env.ADHDEV_CONFIG_DIR && process.env.ADHDEV_CONFIG_DIR.trim() ? process.env.ADHDEV_CONFIG_DIR.trim() : path37.join(os27.homedir(), ".adhdev");
54857
- var LOG_DIR2 = path37.join(ADHDEV_HOME2, "logs");
55052
+ var fs29 = __toESM(require("fs"));
55053
+ var path38 = __toESM(require("path"));
55054
+ var os28 = __toESM(require("os"));
55055
+ var ADHDEV_HOME2 = process.env.ADHDEV_CONFIG_DIR && process.env.ADHDEV_CONFIG_DIR.trim() ? process.env.ADHDEV_CONFIG_DIR.trim() : path38.join(os28.homedir(), ".adhdev");
55056
+ var LOG_DIR2 = path38.join(ADHDEV_HOME2, "logs");
54858
55057
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
54859
55058
  var MAX_DAYS = 7;
54860
55059
  try {
54861
- fs28.mkdirSync(LOG_DIR2, { recursive: true });
55060
+ fs29.mkdirSync(LOG_DIR2, { recursive: true });
54862
55061
  } catch {
54863
55062
  }
54864
55063
  var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
@@ -54892,19 +55091,19 @@ function getDateStr2() {
54892
55091
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
54893
55092
  }
54894
55093
  var currentDate2 = getDateStr2();
54895
- var currentFile = path37.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
55094
+ var currentFile = path38.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54896
55095
  var writeCount2 = 0;
54897
55096
  function checkRotation() {
54898
55097
  const today = getDateStr2();
54899
55098
  if (today !== currentDate2) {
54900
55099
  currentDate2 = today;
54901
- currentFile = path37.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
55100
+ currentFile = path38.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
54902
55101
  cleanOldFiles();
54903
55102
  }
54904
55103
  }
54905
55104
  function cleanOldFiles() {
54906
55105
  try {
54907
- const files = fs28.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
55106
+ const files = fs29.readdirSync(LOG_DIR2).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
54908
55107
  const cutoff = /* @__PURE__ */ new Date();
54909
55108
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
54910
55109
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -54912,7 +55111,7 @@ function cleanOldFiles() {
54912
55111
  const dateMatch = file.match(/commands-(\d{4}-\d{2}-\d{2})/);
54913
55112
  if (dateMatch && dateMatch[1] < cutoffStr) {
54914
55113
  try {
54915
- fs28.unlinkSync(path37.join(LOG_DIR2, file));
55114
+ fs29.unlinkSync(path38.join(LOG_DIR2, file));
54916
55115
  } catch {
54917
55116
  }
54918
55117
  }
@@ -54922,14 +55121,14 @@ function cleanOldFiles() {
54922
55121
  }
54923
55122
  function checkSize() {
54924
55123
  try {
54925
- const stat2 = fs28.statSync(currentFile);
55124
+ const stat2 = fs29.statSync(currentFile);
54926
55125
  if (stat2.size > MAX_FILE_SIZE) {
54927
55126
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
54928
55127
  try {
54929
- fs28.unlinkSync(backup);
55128
+ fs29.unlinkSync(backup);
54930
55129
  } catch {
54931
55130
  }
54932
- fs28.renameSync(currentFile, backup);
55131
+ fs29.renameSync(currentFile, backup);
54933
55132
  }
54934
55133
  } catch {
54935
55134
  }
@@ -54962,14 +55161,14 @@ function logCommand(entry) {
54962
55161
  ...entry.error ? { err: entry.error } : {},
54963
55162
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
54964
55163
  });
54965
- fs28.appendFileSync(currentFile, line + "\n");
55164
+ fs29.appendFileSync(currentFile, line + "\n");
54966
55165
  } catch {
54967
55166
  }
54968
55167
  }
54969
55168
  function getRecentCommands(count = 50) {
54970
55169
  try {
54971
- if (!fs28.existsSync(currentFile)) return [];
54972
- const content = fs28.readFileSync(currentFile, "utf-8");
55170
+ if (!fs29.existsSync(currentFile)) return [];
55171
+ const content = fs29.readFileSync(currentFile, "utf-8");
54973
55172
  const lines = content.trim().split("\n").filter(Boolean);
54974
55173
  return lines.slice(-count).map((line) => {
54975
55174
  try {
@@ -54997,7 +55196,7 @@ cleanOldFiles();
54997
55196
  // src/commands/router.ts
54998
55197
  init_debug_trace();
54999
55198
  init_mesh_host_ownership();
55000
- var fs33 = __toESM(require("fs"));
55199
+ var fs34 = __toESM(require("fs"));
55001
55200
 
55002
55201
  // src/mesh/mesh-node-identity.ts
55003
55202
  init_cli_detector();
@@ -55005,7 +55204,7 @@ init_git_status();
55005
55204
  init_dist();
55006
55205
  init_logger();
55007
55206
  init_mesh_warmup_deadline();
55008
- var fs29 = __toESM(require("fs"));
55207
+ var fs30 = __toESM(require("fs"));
55009
55208
  init_runtime_defaults();
55010
55209
  function readProviderPriorityFromPolicy(policy) {
55011
55210
  const record = policy && typeof policy === "object" && !Array.isArray(policy) ? policy : {};
@@ -55392,7 +55591,7 @@ function isDeadLocalWorktreeNode(node) {
55392
55591
  if (node?.isLocalWorktree !== true) return false;
55393
55592
  const workspace = readStringValue(node?.workspace);
55394
55593
  if (!workspace) return false;
55395
- return !fs29.existsSync(workspace);
55594
+ return !fs30.existsSync(workspace);
55396
55595
  }
55397
55596
  function foldMeshNodeIdentityToCanonical(node) {
55398
55597
  if (!node || typeof node !== "object" || Array.isArray(node)) return node;
@@ -55640,7 +55839,7 @@ function summarizeInlineMeshBranchConvergence(nodes) {
55640
55839
  const followUps = nodes.filter((node) => {
55641
55840
  if (readObjectRecord(node.branchConvergence).needsConvergence !== true) return false;
55642
55841
  const workspace = typeof node.workspace === "string" ? node.workspace : "";
55643
- if (workspace && !fs29.existsSync(workspace)) return false;
55842
+ if (workspace && !fs30.existsSync(workspace)) return false;
55644
55843
  return true;
55645
55844
  }).map((node) => {
55646
55845
  const convergence = readObjectRecord(node.branchConvergence);
@@ -56070,7 +56269,7 @@ async function hydrateInlineMeshDirectTruth(args) {
56070
56269
  if (!workspace) {
56071
56270
  return !isSelfNode && daemonId ? { kind: "unavailable", nodeId } : { kind: "skip" };
56072
56271
  }
56073
- if (fs29.existsSync(workspace)) {
56272
+ if (fs30.existsSync(workspace)) {
56074
56273
  try {
56075
56274
  const runLocalProbe = () => getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
56076
56275
  const localGit = args.probeCache ? await args.probeCache.probeLocal(workspace, runLocalProbe) : await runLocalProbe();
@@ -56217,7 +56416,7 @@ function readLiveMeshNodeWorkspace(args) {
56217
56416
  }
56218
56417
  function collectLiveMeshSessionRecords(args) {
56219
56418
  const nodeWorkspace = readStringValue(args.node?.workspace);
56220
- const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs29.existsSync(nodeWorkspace);
56419
+ const nodeIsMissingLocalWorktree = args.node?.isLocalWorktree === true && !!nodeWorkspace && !fs30.existsSync(nodeWorkspace);
56221
56420
  const matches = args.liveSessionRecords.filter((record) => {
56222
56421
  const recordNodeId = readStringValue(record?.meta?.meshNodeId);
56223
56422
  if (recordNodeId && !daemonIdsEquivalent(recordNodeId, args.nodeId)) return false;
@@ -56244,7 +56443,7 @@ function buildHistoricalMeshSessions(args) {
56244
56443
  const workspace = readStringValue(node?.workspace);
56245
56444
  if (nodeId) liveNodeIds.add(nodeId);
56246
56445
  if (workspace) liveWorkspaces.add(workspace);
56247
- if (nodeId && node?.isLocalWorktree === true && workspace && !fs29.existsSync(workspace)) {
56446
+ if (nodeId && node?.isLocalWorktree === true && workspace && !fs30.existsSync(workspace)) {
56248
56447
  missingLocalWorktreeNodeIds.add(nodeId);
56249
56448
  }
56250
56449
  }
@@ -56340,9 +56539,9 @@ init_resolve_executable();
56340
56539
  var execFileAsync3 = (0, import_node_util4.promisify)(import_node_child_process5.execFile);
56341
56540
  var GIT = process.platform === "win32" ? resolveWin32Executable("git") : "git";
56342
56541
  var MAX_CHANGED_FILES2 = 500;
56343
- function topLevel(path44) {
56344
- const slash = path44.indexOf("/");
56345
- return slash === -1 ? path44 : path44.slice(0, slash);
56542
+ function topLevel(path45) {
56543
+ const slash = path45.indexOf("/");
56544
+ return slash === -1 ? path45 : path45.slice(0, slash);
56346
56545
  }
56347
56546
  async function analyzeMeshRefineNodeChangeArea(args) {
56348
56547
  const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
@@ -56430,7 +56629,7 @@ init_git_status();
56430
56629
  init_refine_config();
56431
56630
  init_worktree_bootstrap_config();
56432
56631
  var import_path14 = require("path");
56433
- var fs30 = __toESM(require("fs"));
56632
+ var fs31 = __toESM(require("fs"));
56434
56633
  var import_node_child_process6 = require("child_process");
56435
56634
  init_resolve_executable();
56436
56635
  var GIT2 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
@@ -56490,7 +56689,7 @@ async function computeGitPatchId(cwd, fromRef, toRef, excludePaths = []) {
56490
56689
  const { execFileSync: execFileSync10 } = await import("child_process");
56491
56690
  const diffArgs = ["diff", "--patch", "--full-index", fromRef, toRef];
56492
56691
  if (excludePaths.length > 0) {
56493
- diffArgs.push("--", ".", ...excludePaths.map((path44) => `:(exclude)${path44}`));
56692
+ diffArgs.push("--", ".", ...excludePaths.map((path45) => `:(exclude)${path45}`));
56494
56693
  }
56495
56694
  const diff = execFileSync10(GIT2, diffArgs, {
56496
56695
  cwd,
@@ -56691,9 +56890,9 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
56691
56890
  if (!trimmed) continue;
56692
56891
  if (trimmed.startsWith("+")) {
56693
56892
  const parts = trimmed.slice(1).trim().split(/\s+/);
56694
- const path44 = parts[1] || parts[0] || "(unknown)";
56893
+ const path45 = parts[1] || parts[0] || "(unknown)";
56695
56894
  submoduleHints.push({
56696
- path: path44,
56895
+ path: path45,
56697
56896
  reason: "submodule checked-out commit differs from the committed gitlink (pointer bump not committed on the root branch)"
56698
56897
  });
56699
56898
  }
@@ -56723,10 +56922,10 @@ async function runMeshRefineEffectiveDiffGate(repoRoot, baseHead, branchHead) {
56723
56922
  }
56724
56923
  function buildPatchEquivalenceSubmoduleConflictHint(repoRoot, baseHead, branchHead, output) {
56725
56924
  if (!/(submodule|160000)/i.test(output) || !/(conflict|failed to merge)/i.test(output)) return void 0;
56726
- const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => ({
56727
- path: path44,
56728
- baseCommit: readTreeObject(repoRoot, baseHead, path44),
56729
- branchCommit: readTreeObject(repoRoot, branchHead, path44)
56925
+ const conflicts = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path45) => ({
56926
+ path: path45,
56927
+ baseCommit: readTreeObject(repoRoot, baseHead, path45),
56928
+ branchCommit: readTreeObject(repoRoot, branchHead, path45)
56730
56929
  }));
56731
56930
  if (conflicts.length === 0) return void 0;
56732
56931
  return {
@@ -56752,11 +56951,11 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
56752
56951
  if (!line.trim()) continue;
56753
56952
  const metaAndPath = line.split(" ");
56754
56953
  const meta = metaAndPath[0] || "";
56755
- const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
56756
- if (!path44) continue;
56954
+ const path45 = metaAndPath[metaAndPath.length - 1]?.trim();
56955
+ if (!path45) continue;
56757
56956
  const parts = meta.split(/\s+/);
56758
56957
  if (parts[0]?.includes("160000") || parts[1]?.includes("160000")) {
56759
- paths.add(path44);
56958
+ paths.add(path45);
56760
56959
  }
56761
56960
  }
56762
56961
  return [...paths].sort();
@@ -56764,9 +56963,9 @@ function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
56764
56963
  return [];
56765
56964
  }
56766
56965
  }
56767
- function readTreeObject(repoRoot, ref, path44) {
56966
+ function readTreeObject(repoRoot, ref, path45) {
56768
56967
  try {
56769
- const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path44], {
56968
+ const output = (0, import_node_child_process6.execFileSync)(GIT2, ["ls-tree", ref, "--", path45], {
56770
56969
  cwd: repoRoot,
56771
56970
  encoding: "utf8",
56772
56971
  maxBuffer: 1024 * 1024
@@ -56789,7 +56988,7 @@ function isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit) {
56789
56988
  if (!baseCommit || !branchCommit) return false;
56790
56989
  if (baseCommit === branchCommit) return true;
56791
56990
  try {
56792
- if (!fs30.existsSync(submoduleRepoPath)) return false;
56991
+ if (!fs31.existsSync(submoduleRepoPath)) return false;
56793
56992
  (0, import_node_child_process6.execFileSync)(GIT2, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
56794
56993
  (0, import_node_child_process6.execFileSync)(GIT2, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
56795
56994
  (0, import_node_child_process6.execFileSync)(GIT2, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
@@ -56811,12 +57010,12 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
56811
57010
  if (!line.trim()) continue;
56812
57011
  const metaAndPath = line.split(" ");
56813
57012
  const meta = metaAndPath[0] || "";
56814
- const path44 = metaAndPath[metaAndPath.length - 1]?.trim();
56815
- if (!path44 || seen.has(path44)) continue;
56816
- seen.add(path44);
57013
+ const path45 = metaAndPath[metaAndPath.length - 1]?.trim();
57014
+ if (!path45 || seen.has(path45)) continue;
57015
+ seen.add(path45);
56817
57016
  const parts = meta.split(/\s+/);
56818
57017
  const isGitlink = !!(parts[0]?.includes("160000") || parts[1]?.includes("160000"));
56819
- result.push({ path: path44, isGitlink });
57018
+ result.push({ path: path45, isGitlink });
56820
57019
  }
56821
57020
  return result;
56822
57021
  } catch {
@@ -56824,20 +57023,20 @@ function readChangedPathKinds(repoRoot, fromRef, toRef) {
56824
57023
  }
56825
57024
  }
56826
57025
  function collectFastForwardGitlinkPaths(repoRoot, baseHead, branchHead) {
56827
- return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path44) => {
56828
- const baseCommit = readTreeObject(repoRoot, baseHead, path44);
56829
- const branchCommit = readTreeObject(repoRoot, branchHead, path44);
57026
+ return readChangedGitlinkPaths(repoRoot, baseHead, branchHead).filter((path45) => {
57027
+ const baseCommit = readTreeObject(repoRoot, baseHead, path45);
57028
+ const branchCommit = readTreeObject(repoRoot, branchHead, path45);
56830
57029
  if (!baseCommit || !branchCommit) return false;
56831
- return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path44), baseCommit, branchCommit);
57030
+ return isSubmoduleFastForward((0, import_path14.resolve)(repoRoot, path45), baseCommit, branchCommit);
56832
57031
  });
56833
57032
  }
56834
57033
  function evaluateGitlinkTrivialFastForward(repoRoot, baseHead, branchHead) {
56835
- const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path44) => {
56836
- const baseCommit = readTreeObject(repoRoot, baseHead, path44);
56837
- const branchCommit = readTreeObject(repoRoot, branchHead, path44);
56838
- const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path44);
57034
+ const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path45) => {
57035
+ const baseCommit = readTreeObject(repoRoot, baseHead, path45);
57036
+ const branchCommit = readTreeObject(repoRoot, branchHead, path45);
57037
+ const submoduleRepoPath = (0, import_path14.resolve)(repoRoot, path45);
56839
57038
  const fastForward = !!baseCommit && !!branchCommit && isSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit);
56840
- return { path: path44, baseCommit, branchCommit, fastForward };
57039
+ return { path: path45, baseCommit, branchCommit, fastForward };
56841
57040
  });
56842
57041
  if (changedGitlinks.length === 0) {
56843
57042
  return { trivial: false, reason: "no_changed_gitlinks", gitlinks: changedGitlinks };
@@ -56888,7 +57087,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
56888
57087
  maxBuffer: 1024 * 1024
56889
57088
  }).trim();
56890
57089
  if (!tree) return void 0;
56891
- const updates = paths.map((path44) => `160000 commit ${placeholderCommit} ${path44}`).join("\n");
57090
+ const updates = paths.map((path45) => `160000 commit ${placeholderCommit} ${path45}`).join("\n");
56892
57091
  if (!updates) return tree;
56893
57092
  const tmpIndex = (0, import_path14.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
56894
57093
  const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
@@ -56906,7 +57105,7 @@ function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderC
56906
57105
  return newTree || void 0;
56907
57106
  } finally {
56908
57107
  try {
56909
- fs30.rmSync(tmpIndex, { force: true });
57108
+ fs31.rmSync(tmpIndex, { force: true });
56910
57109
  } catch {
56911
57110
  }
56912
57111
  }
@@ -56981,7 +57180,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
56981
57180
  return newTree || void 0;
56982
57181
  } finally {
56983
57182
  try {
56984
- fs30.rmSync(tmpIndex, { force: true });
57183
+ fs31.rmSync(tmpIndex, { force: true });
56985
57184
  } catch {
56986
57185
  }
56987
57186
  }
@@ -56991,7 +57190,7 @@ function synthesizeTrivialFastForwardMergeTree(repoRoot, baseHead, branchHead, g
56991
57190
  }
56992
57191
  async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, currentHead, options = {}) {
56993
57192
  const startedAt = Date.now();
56994
- const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path44) => !(options.submoduleIgnorePaths || []).includes(path44));
57193
+ const changedGitlinkPaths = readChangedGitlinkPaths(repoRoot, previousBaseHead, currentHead).filter((path45) => !(options.submoduleIgnorePaths || []).includes(path45));
56995
57194
  const preStatus = await getGitRepoStatus(repoRoot, {
56996
57195
  includeSubmodules: true,
56997
57196
  submoduleIgnorePaths: options.submoduleIgnorePaths,
@@ -57038,7 +57237,7 @@ async function alignRefinerySubmodulesAfterMerge(repoRoot, previousBaseHead, cur
57038
57237
  changedGitlinkPaths,
57039
57238
  outOfSyncPaths,
57040
57239
  updatedPaths: updatePaths,
57041
- verifiedPaths: updatePaths.filter((path44) => !remaining.some((submodule) => submodule.path === path44)),
57240
+ verifiedPaths: updatePaths.filter((path45) => !remaining.some((submodule) => submodule.path === path45)),
57042
57241
  durationMs: Date.now() - startedAt,
57043
57242
  command: `git ${commandArgs.join(" ")}`,
57044
57243
  stdout: truncateValidationOutput(result.stdout),
@@ -57093,7 +57292,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
57093
57292
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
57094
57293
  };
57095
57294
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
57096
- if (!fs30.existsSync(worktreeSubmodulePath)) return false;
57295
+ if (!fs31.existsSync(worktreeSubmodulePath)) return false;
57097
57296
  try {
57098
57297
  await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
57099
57298
  } catch {
@@ -57117,7 +57316,7 @@ async function runMeshRefineSubmoduleReachabilityGate(repoRoot, mergedTree, opti
57117
57316
  };
57118
57317
  let submoduleDefaultBranch = "main";
57119
57318
  try {
57120
- if (!fs30.existsSync(submodulePath)) {
57319
+ if (!fs31.existsSync(submodulePath)) {
57121
57320
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
57122
57321
  entry.publishRequired = true;
57123
57322
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -57359,9 +57558,9 @@ async function runMeshRefineValidationGate(mesh, workspace, opts) {
57359
57558
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
57360
57559
  };
57361
57560
  const dependenciesLikelyMissing = (cwd) => {
57362
- if (!fs30.existsSync((0, import_path14.join)(cwd, "package.json"))) return false;
57363
- if (fs30.existsSync((0, import_path14.join)(cwd, "node_modules"))) return false;
57364
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs30.existsSync((0, import_path14.join)(cwd, lock)));
57561
+ if (!fs31.existsSync((0, import_path14.join)(cwd, "package.json"))) return false;
57562
+ if (fs31.existsSync((0, import_path14.join)(cwd, "node_modules"))) return false;
57563
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs31.existsSync((0, import_path14.join)(cwd, lock)));
57365
57564
  };
57366
57565
  if (runLegacyBootstrapCommands) {
57367
57566
  summary.bootstrap = { stage: "legacy" };
@@ -58775,7 +58974,7 @@ async function startMeshRefineJob(self, meshId, nodeId, args) {
58775
58974
  }
58776
58975
 
58777
58976
  // src/commands/router-worktree-cleanup.ts
58778
- var fs31 = __toESM(require("fs"));
58977
+ var fs32 = __toESM(require("fs"));
58779
58978
  var import_path15 = require("path");
58780
58979
  init_logger();
58781
58980
  init_dist();
@@ -58790,14 +58989,14 @@ function sessionMatchesMeshNode(self, record, node, nodeId, sessionIds) {
58790
58989
  return false;
58791
58990
  }
58792
58991
  async function bestEffortRemoveWorktreeDir(self, dir) {
58793
- if (!dir || !fs31.existsSync(dir)) return { removed: true, residue: false };
58992
+ if (!dir || !fs32.existsSync(dir)) return { removed: true, residue: false };
58794
58993
  const sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
58795
58994
  const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
58796
58995
  let lastErr;
58797
58996
  for (let attempt = 0; attempt < 4; attempt++) {
58798
58997
  try {
58799
- fs31.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
58800
- if (!fs31.existsSync(dir)) return { removed: true, residue: false };
58998
+ fs32.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
58999
+ if (!fs32.existsSync(dir)) return { removed: true, residue: false };
58801
59000
  lastErr = new Error("directory still present after rmSync");
58802
59001
  } catch (e) {
58803
59002
  lastErr = e;
@@ -58808,7 +59007,7 @@ async function bestEffortRemoveWorktreeDir(self, dir) {
58808
59007
  }
58809
59008
  await sleep3(150 * (attempt + 1));
58810
59009
  }
58811
- return fs31.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
59010
+ return fs32.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
58812
59011
  }
58813
59012
  async function precheckLocalWorktreeRemovable(self, args) {
58814
59013
  const sessionPreservedNote = " The delegated session was left running (not stopped) \u2014 resolve the issue and retry mesh_remove_node.";
@@ -58821,10 +59020,10 @@ async function precheckLocalWorktreeRemovable(self, args) {
58821
59020
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains." + sessionPreservedNote
58822
59021
  };
58823
59022
  }
58824
- if (!fs31.existsSync(workspace)) return { ok: true };
59023
+ if (!fs32.existsSync(workspace)) return { ok: true };
58825
59024
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
58826
59025
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
58827
- if (!repoRoot || !fs31.existsSync(repoRoot)) {
59026
+ if (!repoRoot || !fs32.existsSync(repoRoot)) {
58828
59027
  return {
58829
59028
  ok: false,
58830
59029
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -58844,7 +59043,7 @@ async function precheckLocalWorktreeRemovable(self, args) {
58844
59043
  const normalizePath = (value) => {
58845
59044
  const resolved = (0, import_path15.resolve)(value);
58846
59045
  try {
58847
- return fs31.realpathSync(resolved);
59046
+ return fs32.realpathSync(resolved);
58848
59047
  } catch {
58849
59048
  return resolved;
58850
59049
  }
@@ -58906,13 +59105,13 @@ async function cleanupLocalWorktreeNode(self, args) {
58906
59105
  recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
58907
59106
  };
58908
59107
  }
58909
- const worktreeExists = fs31.existsSync(workspace);
59108
+ const worktreeExists = fs32.existsSync(workspace);
58910
59109
  const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => meshNodeIdMatches(n, args.node.clonedFromNodeId)) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
58911
59110
  const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
58912
59111
  if (!worktreeExists) {
58913
59112
  return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
58914
59113
  }
58915
- if (!repoRoot || !fs31.existsSync(repoRoot)) {
59114
+ if (!repoRoot || !fs32.existsSync(repoRoot)) {
58916
59115
  return {
58917
59116
  success: false,
58918
59117
  code: "mesh_worktree_cleanup_missing_source_repo",
@@ -58932,7 +59131,7 @@ async function cleanupLocalWorktreeNode(self, args) {
58932
59131
  const normalizePath = (value) => {
58933
59132
  const resolved = (0, import_path15.resolve)(value);
58934
59133
  try {
58935
- return fs31.realpathSync(resolved);
59134
+ return fs32.realpathSync(resolved);
58936
59135
  } catch {
58937
59136
  return resolved;
58938
59137
  }
@@ -59566,7 +59765,7 @@ init_logger();
59566
59765
  var yaml5 = __toESM(require("js-yaml"));
59567
59766
  var import_os4 = require("os");
59568
59767
  var import_path16 = require("path");
59569
- var fs32 = __toESM(require("fs"));
59768
+ var fs33 = __toESM(require("fs"));
59570
59769
  function loadYamlModule() {
59571
59770
  return yaml5;
59572
59771
  }
@@ -59590,9 +59789,9 @@ function resolveHermesUserHome() {
59590
59789
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
59591
59790
  const sourceHome = resolveHermesUserHome();
59592
59791
  const sourceConfigPath = (0, import_path16.join)(sourceHome, "config.yaml");
59593
- if (!fs32.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59792
+ if (!fs33.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59594
59793
  if ((0, import_path16.resolve)(sourceConfigPath) === (0, import_path16.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
59595
- const parsed = parseMeshCoordinatorMcpConfig(fs32.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
59794
+ const parsed = parseMeshCoordinatorMcpConfig(fs33.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
59596
59795
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
59597
59796
  return { config: baseConfig, sourceHome, sourceConfigPath };
59598
59797
  }
@@ -59629,9 +59828,9 @@ function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
59629
59828
  for (const fileName of [".env", "auth.json"]) {
59630
59829
  const sourcePath = (0, import_path16.join)(sourceHome, fileName);
59631
59830
  const targetPath = (0, import_path16.join)(targetHome, fileName);
59632
- if (!fs32.existsSync(sourcePath)) continue;
59831
+ if (!fs33.existsSync(sourcePath)) continue;
59633
59832
  try {
59634
- fs32.copyFileSync(sourcePath, targetPath);
59833
+ fs33.copyFileSync(sourcePath, targetPath);
59635
59834
  } catch (error) {
59636
59835
  LOG.warn("MeshCoordinator", `Could not copy Hermes ${fileName} into isolated coordinator home: ${error?.message || error}`);
59637
59836
  }
@@ -60023,7 +60222,7 @@ var DaemonCommandRouter = class {
60023
60222
  const nodeId = readInlineMeshNodeId(node);
60024
60223
  if (!nodeId || !tombstones.has(nodeId)) return true;
60025
60224
  const workspace = readStringValue(node?.workspace);
60026
- if (workspace && fs33.existsSync(workspace)) {
60225
+ if (workspace && fs34.existsSync(workspace)) {
60027
60226
  tombstones.delete(nodeId);
60028
60227
  return true;
60029
60228
  }
@@ -61942,12 +62141,12 @@ init_io_contracts();
61942
62141
  init_chat_message_normalization();
61943
62142
 
61944
62143
  // src/providers/version-archive.ts
61945
- var fs34 = __toESM(require("fs"));
61946
- var path38 = __toESM(require("path"));
61947
- var os28 = __toESM(require("os"));
62144
+ var fs35 = __toESM(require("fs"));
62145
+ var path39 = __toESM(require("path"));
62146
+ var os29 = __toESM(require("os"));
61948
62147
  var import_os5 = require("os");
61949
62148
  var import_child_process10 = require("child_process");
61950
- var ARCHIVE_PATH = path38.join(os28.homedir(), ".adhdev", "version-history.json");
62149
+ var ARCHIVE_PATH = path39.join(os29.homedir(), ".adhdev", "version-history.json");
61951
62150
  var MAX_ENTRIES_PER_PROVIDER = 20;
61952
62151
  var VersionArchive = class {
61953
62152
  history = {};
@@ -61956,8 +62155,8 @@ var VersionArchive = class {
61956
62155
  }
61957
62156
  load() {
61958
62157
  try {
61959
- if (fs34.existsSync(ARCHIVE_PATH)) {
61960
- this.history = JSON.parse(fs34.readFileSync(ARCHIVE_PATH, "utf-8"));
62158
+ if (fs35.existsSync(ARCHIVE_PATH)) {
62159
+ this.history = JSON.parse(fs35.readFileSync(ARCHIVE_PATH, "utf-8"));
61961
62160
  }
61962
62161
  } catch {
61963
62162
  this.history = {};
@@ -61994,8 +62193,8 @@ var VersionArchive = class {
61994
62193
  }
61995
62194
  save() {
61996
62195
  try {
61997
- fs34.mkdirSync(path38.dirname(ARCHIVE_PATH), { recursive: true });
61998
- fs34.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
62196
+ fs35.mkdirSync(path39.dirname(ARCHIVE_PATH), { recursive: true });
62197
+ fs35.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
61999
62198
  } catch {
62000
62199
  }
62001
62200
  }
@@ -62018,10 +62217,10 @@ function findBinary2(name) {
62018
62217
  for (const p of paths) {
62019
62218
  if (!p) continue;
62020
62219
  for (const ext of exes) {
62021
- const fullPath = path38.join(p, name + ext);
62220
+ const fullPath = path39.join(p, name + ext);
62022
62221
  try {
62023
- if (fs34.existsSync(fullPath)) {
62024
- const stat2 = fs34.statSync(fullPath);
62222
+ if (fs35.existsSync(fullPath)) {
62223
+ const stat2 = fs35.statSync(fullPath);
62025
62224
  if (stat2.isFile() && (isWin || stat2.mode & 73)) {
62026
62225
  return fullPath;
62027
62226
  }
@@ -62066,19 +62265,19 @@ async function getVersion(binary, versionCommand) {
62066
62265
  function checkPathExists2(paths) {
62067
62266
  for (const p of paths) {
62068
62267
  if (p.includes("*")) {
62069
- const home = os28.homedir();
62070
- const resolved = p.replace(/\*/g, home.split(path38.sep).pop() || "");
62071
- if (fs34.existsSync(resolved)) return resolved;
62268
+ const home = os29.homedir();
62269
+ const resolved = p.replace(/\*/g, home.split(path39.sep).pop() || "");
62270
+ if (fs35.existsSync(resolved)) return resolved;
62072
62271
  } else {
62073
- if (fs34.existsSync(p)) return p;
62272
+ if (fs35.existsSync(p)) return p;
62074
62273
  }
62075
62274
  }
62076
62275
  return null;
62077
62276
  }
62078
62277
  async function getMacAppVersion(appPath) {
62079
62278
  if ((0, import_os5.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
62080
- const plistPath = path38.join(appPath, "Contents", "Info.plist");
62081
- if (!fs34.existsSync(plistPath)) return null;
62279
+ const plistPath = path39.join(appPath, "Contents", "Info.plist");
62280
+ if (!fs35.existsSync(plistPath)) return null;
62082
62281
  const raw = await runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
62083
62282
  return raw || null;
62084
62283
  }
@@ -62104,8 +62303,8 @@ async function detectAllVersions(loader, archive) {
62104
62303
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
62105
62304
  let resolvedBin = cliBin;
62106
62305
  if (!resolvedBin && appPath && currentOs === "darwin") {
62107
- const bundled = path38.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
62108
- if (provider.cli && fs34.existsSync(bundled)) resolvedBin = bundled;
62306
+ const bundled = path39.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
62307
+ if (provider.cli && fs35.existsSync(bundled)) resolvedBin = bundled;
62109
62308
  }
62110
62309
  info.installed = !!(appPath || resolvedBin);
62111
62310
  info.path = appPath || null;
@@ -62153,8 +62352,8 @@ async function detectAllVersions(loader, archive) {
62153
62352
 
62154
62353
  // src/daemon/dev-server.ts
62155
62354
  var http2 = __toESM(require("http"));
62156
- var fs38 = __toESM(require("fs"));
62157
- var path42 = __toESM(require("path"));
62355
+ var fs39 = __toESM(require("fs"));
62356
+ var path43 = __toESM(require("path"));
62158
62357
  init_config();
62159
62358
 
62160
62359
  // src/daemon/scaffold-template.ts
@@ -62505,8 +62704,8 @@ init_logger();
62505
62704
  init_builders();
62506
62705
 
62507
62706
  // src/daemon/dev-cdp-handlers.ts
62508
- var fs35 = __toESM(require("fs"));
62509
- var path39 = __toESM(require("path"));
62707
+ var fs36 = __toESM(require("fs"));
62708
+ var path40 = __toESM(require("path"));
62510
62709
  init_logger();
62511
62710
  async function handleCdpEvaluate(ctx, req, res) {
62512
62711
  const body = await ctx.readBody(req);
@@ -62685,18 +62884,18 @@ async function handleScriptHints(ctx, type, _req, res) {
62685
62884
  return;
62686
62885
  }
62687
62886
  let scriptsPath = "";
62688
- const directScripts = path39.join(dir, "scripts.js");
62689
- if (fs35.existsSync(directScripts)) {
62887
+ const directScripts = path40.join(dir, "scripts.js");
62888
+ if (fs36.existsSync(directScripts)) {
62690
62889
  scriptsPath = directScripts;
62691
62890
  } else {
62692
- const scriptsDir = path39.join(dir, "scripts");
62693
- if (fs35.existsSync(scriptsDir)) {
62694
- const versions = fs35.readdirSync(scriptsDir).filter((d) => {
62695
- return fs35.statSync(path39.join(scriptsDir, d)).isDirectory();
62891
+ const scriptsDir = path40.join(dir, "scripts");
62892
+ if (fs36.existsSync(scriptsDir)) {
62893
+ const versions = fs36.readdirSync(scriptsDir).filter((d) => {
62894
+ return fs36.statSync(path40.join(scriptsDir, d)).isDirectory();
62696
62895
  }).sort().reverse();
62697
62896
  for (const ver of versions) {
62698
- const p = path39.join(scriptsDir, ver, "scripts.js");
62699
- if (fs35.existsSync(p)) {
62897
+ const p = path40.join(scriptsDir, ver, "scripts.js");
62898
+ if (fs36.existsSync(p)) {
62700
62899
  scriptsPath = p;
62701
62900
  break;
62702
62901
  }
@@ -62708,7 +62907,7 @@ async function handleScriptHints(ctx, type, _req, res) {
62708
62907
  return;
62709
62908
  }
62710
62909
  try {
62711
- const source = fs35.readFileSync(scriptsPath, "utf-8");
62910
+ const source = fs36.readFileSync(scriptsPath, "utf-8");
62712
62911
  const hints = {};
62713
62912
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
62714
62913
  let match;
@@ -63523,8 +63722,8 @@ async function handleDomContext(ctx, type, req, res) {
63523
63722
  }
63524
63723
 
63525
63724
  // src/daemon/dev-cli-debug.ts
63526
- var fs36 = __toESM(require("fs"));
63527
- var path40 = __toESM(require("path"));
63725
+ var fs37 = __toESM(require("fs"));
63726
+ var path41 = __toESM(require("path"));
63528
63727
  function slugifyFixtureName(value) {
63529
63728
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
63530
63729
  return normalized || `fixture-${Date.now()}`;
@@ -63534,15 +63733,15 @@ function getCliFixtureDir(ctx, type) {
63534
63733
  if (!providerDir) {
63535
63734
  throw new Error(`Provider directory not found for '${type}'`);
63536
63735
  }
63537
- return path40.join(providerDir, "fixtures");
63736
+ return path41.join(providerDir, "fixtures");
63538
63737
  }
63539
63738
  function readCliFixture(ctx, type, name) {
63540
63739
  const fixtureDir = getCliFixtureDir(ctx, type);
63541
- const filePath = path40.join(fixtureDir, `${name}.json`);
63542
- if (!fs36.existsSync(filePath)) {
63740
+ const filePath = path41.join(fixtureDir, `${name}.json`);
63741
+ if (!fs37.existsSync(filePath)) {
63543
63742
  throw new Error(`Fixture not found: ${filePath}`);
63544
63743
  }
63545
- return JSON.parse(fs36.readFileSync(filePath, "utf-8"));
63744
+ return JSON.parse(fs37.readFileSync(filePath, "utf-8"));
63546
63745
  }
63547
63746
  function getExerciseTranscriptText(result) {
63548
63747
  const parts = [];
@@ -64287,7 +64486,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
64287
64486
  return;
64288
64487
  }
64289
64488
  const fixtureDir = getCliFixtureDir(ctx, type);
64290
- fs36.mkdirSync(fixtureDir, { recursive: true });
64489
+ fs37.mkdirSync(fixtureDir, { recursive: true });
64291
64490
  const name = slugifyFixtureName(String(body?.name || `${type}-${Date.now()}`));
64292
64491
  const result = await runCliExerciseInternal(ctx, { ...request, type });
64293
64492
  const fixture = {
@@ -64314,8 +64513,8 @@ async function handleCliFixtureCapture(ctx, req, res) {
64314
64513
  },
64315
64514
  notes: typeof body?.notes === "string" ? body.notes : void 0
64316
64515
  };
64317
- const filePath = path40.join(fixtureDir, `${name}.json`);
64318
- fs36.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
64516
+ const filePath = path41.join(fixtureDir, `${name}.json`);
64517
+ fs37.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
64319
64518
  ctx.json(res, 200, {
64320
64519
  saved: true,
64321
64520
  name,
@@ -64333,14 +64532,14 @@ async function handleCliFixtureCapture(ctx, req, res) {
64333
64532
  async function handleCliFixtureList(ctx, type, _req, res) {
64334
64533
  try {
64335
64534
  const fixtureDir = getCliFixtureDir(ctx, type);
64336
- if (!fs36.existsSync(fixtureDir)) {
64535
+ if (!fs37.existsSync(fixtureDir)) {
64337
64536
  ctx.json(res, 200, { fixtures: [], count: 0 });
64338
64537
  return;
64339
64538
  }
64340
- const fixtures = fs36.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
64341
- const fullPath = path40.join(fixtureDir, file);
64539
+ const fixtures = fs37.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
64540
+ const fullPath = path41.join(fixtureDir, file);
64342
64541
  try {
64343
- const raw = JSON.parse(fs36.readFileSync(fullPath, "utf-8"));
64542
+ const raw = JSON.parse(fs37.readFileSync(fullPath, "utf-8"));
64344
64543
  return {
64345
64544
  name: raw.name || file.replace(/\.json$/i, ""),
64346
64545
  path: fullPath,
@@ -64473,9 +64672,9 @@ async function handleCliRaw(ctx, req, res) {
64473
64672
  }
64474
64673
 
64475
64674
  // src/daemon/dev-auto-implement.ts
64476
- var fs37 = __toESM(require("fs"));
64477
- var path41 = __toESM(require("path"));
64478
- var os29 = __toESM(require("os"));
64675
+ var fs38 = __toESM(require("fs"));
64676
+ var path42 = __toESM(require("path"));
64677
+ var os30 = __toESM(require("os"));
64479
64678
  var import_session_host_core9 = require("@adhdev/session-host-core");
64480
64679
  function getAutoImplPid(ctx) {
64481
64680
  const pid = ctx.autoImplProcess?.pid;
@@ -64522,38 +64721,38 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
64522
64721
  return fallback?.type || null;
64523
64722
  }
64524
64723
  function getLatestScriptVersionDir(scriptsDir) {
64525
- if (!fs37.existsSync(scriptsDir)) return null;
64526
- const versions = fs37.readdirSync(scriptsDir).filter((d) => {
64724
+ if (!fs38.existsSync(scriptsDir)) return null;
64725
+ const versions = fs38.readdirSync(scriptsDir).filter((d) => {
64527
64726
  try {
64528
- return fs37.statSync(path41.join(scriptsDir, d)).isDirectory();
64727
+ return fs38.statSync(path42.join(scriptsDir, d)).isDirectory();
64529
64728
  } catch {
64530
64729
  return false;
64531
64730
  }
64532
64731
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
64533
64732
  if (versions.length === 0) return null;
64534
- return path41.join(scriptsDir, versions[0]);
64733
+ return path42.join(scriptsDir, versions[0]);
64535
64734
  }
64536
64735
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
64537
- const canonicalUserDir = path41.resolve(ctx.providerLoader.getUserProviderDir(category, type));
64538
- const desiredDir = requestedDir ? path41.resolve(requestedDir) : canonicalUserDir;
64539
- const upstreamRoot = path41.resolve(ctx.providerLoader.getUpstreamDir());
64540
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path41.sep}`)) {
64736
+ const canonicalUserDir = path42.resolve(ctx.providerLoader.getUserProviderDir(category, type));
64737
+ const desiredDir = requestedDir ? path42.resolve(requestedDir) : canonicalUserDir;
64738
+ const upstreamRoot = path42.resolve(ctx.providerLoader.getUpstreamDir());
64739
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path42.sep}`)) {
64541
64740
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
64542
64741
  }
64543
- if (path41.basename(desiredDir) !== type) {
64742
+ if (path42.basename(desiredDir) !== type) {
64544
64743
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
64545
64744
  }
64546
64745
  const sourceDir = ctx.findProviderDir(type);
64547
64746
  if (!sourceDir) {
64548
64747
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
64549
64748
  }
64550
- if (!fs37.existsSync(desiredDir)) {
64551
- fs37.mkdirSync(path41.dirname(desiredDir), { recursive: true });
64552
- fs37.cpSync(sourceDir, desiredDir, { recursive: true });
64749
+ if (!fs38.existsSync(desiredDir)) {
64750
+ fs38.mkdirSync(path42.dirname(desiredDir), { recursive: true });
64751
+ fs38.cpSync(sourceDir, desiredDir, { recursive: true });
64553
64752
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
64554
64753
  }
64555
- const providerJson = path41.join(desiredDir, "provider.json");
64556
- if (!fs37.existsSync(providerJson)) {
64754
+ const providerJson = path42.join(desiredDir, "provider.json");
64755
+ if (!fs38.existsSync(providerJson)) {
64557
64756
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
64558
64757
  }
64559
64758
  return { dir: desiredDir };
@@ -64561,15 +64760,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
64561
64760
  function loadAutoImplReferenceScripts(ctx, referenceType) {
64562
64761
  if (!referenceType) return {};
64563
64762
  const refDir = ctx.findProviderDir(referenceType);
64564
- if (!refDir || !fs37.existsSync(refDir)) return {};
64763
+ if (!refDir || !fs38.existsSync(refDir)) return {};
64565
64764
  const referenceScripts = {};
64566
- const scriptsDir = path41.join(refDir, "scripts");
64765
+ const scriptsDir = path42.join(refDir, "scripts");
64567
64766
  const latestDir = getLatestScriptVersionDir(scriptsDir);
64568
64767
  if (!latestDir) return referenceScripts;
64569
- for (const file of fs37.readdirSync(latestDir)) {
64768
+ for (const file of fs38.readdirSync(latestDir)) {
64570
64769
  if (!file.endsWith(".js")) continue;
64571
64770
  try {
64572
- referenceScripts[file] = fs37.readFileSync(path41.join(latestDir, file), "utf-8");
64771
+ referenceScripts[file] = fs38.readFileSync(path42.join(latestDir, file), "utf-8");
64573
64772
  } catch {
64574
64773
  }
64575
64774
  }
@@ -64677,16 +64876,16 @@ async function handleAutoImplement(ctx, type, req, res) {
64677
64876
  });
64678
64877
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
64679
64878
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
64680
- const tmpDir = path41.join(os29.tmpdir(), "adhdev-autoimpl");
64681
- if (!fs37.existsSync(tmpDir)) fs37.mkdirSync(tmpDir, { recursive: true });
64682
- const promptFile = path41.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
64683
- fs37.writeFileSync(promptFile, prompt, "utf-8");
64879
+ const tmpDir = path42.join(os30.tmpdir(), "adhdev-autoimpl");
64880
+ if (!fs38.existsSync(tmpDir)) fs38.mkdirSync(tmpDir, { recursive: true });
64881
+ const promptFile = path42.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
64882
+ fs38.writeFileSync(promptFile, prompt, "utf-8");
64684
64883
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
64685
64884
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
64686
64885
  const spawn5 = agentProvider?.spawn;
64687
64886
  if (!spawn5?.command) {
64688
64887
  try {
64689
- fs37.unlinkSync(promptFile);
64888
+ fs38.unlinkSync(promptFile);
64690
64889
  } catch {
64691
64890
  }
64692
64891
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -64788,7 +64987,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64788
64987
  } catch {
64789
64988
  }
64790
64989
  try {
64791
- fs37.unlinkSync(promptFile);
64990
+ fs38.unlinkSync(promptFile);
64792
64991
  } catch {
64793
64992
  }
64794
64993
  ctx.log(`Auto-implement (ACP) ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -64832,7 +65031,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64832
65031
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
64833
65032
  const baseArgs = [...spawn5.args || []].filter((a) => !interactiveFlags.includes(a));
64834
65033
  let shellCmd;
64835
- const isWin = os29.platform() === "win32";
65034
+ const isWin = os30.platform() === "win32";
64836
65035
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
64837
65036
  const promptMode = autoImpl?.promptMode ?? "stdin";
64838
65037
  const extraArgs = autoImpl?.extraArgs ?? [];
@@ -64871,7 +65070,7 @@ async function handleAutoImplement(ctx, type, req, res) {
64871
65070
  try {
64872
65071
  const pty = require("node-pty");
64873
65072
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
64874
- const isWin2 = os29.platform() === "win32";
65073
+ const isWin2 = os30.platform() === "win32";
64875
65074
  child = pty.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
64876
65075
  name: "xterm-256color",
64877
65076
  cols: import_session_host_core9.DEFAULT_SESSION_HOST_COLS,
@@ -65014,7 +65213,7 @@ async function handleAutoImplement(ctx, type, req, res) {
65014
65213
  }
65015
65214
  });
65016
65215
  try {
65017
- fs37.unlinkSync(promptFile);
65216
+ fs38.unlinkSync(promptFile);
65018
65217
  } catch {
65019
65218
  }
65020
65219
  ctx.log(`Auto-implement ${success ? "completed" : "failed"}: ${type} (exit: ${code})${verificationSummary ? ` verify=${verificationSummary.pass ? "pass" : "fail"}` : ""}`);
@@ -65111,7 +65310,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65111
65310
  setMode: "set_mode.js"
65112
65311
  };
65113
65312
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
65114
- const scriptsDir = path41.join(providerDir, "scripts");
65313
+ const scriptsDir = path42.join(providerDir, "scripts");
65115
65314
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
65116
65315
  if (latestScriptsDir) {
65117
65316
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -65119,10 +65318,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65119
65318
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
65120
65319
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
65121
65320
  lines.push("");
65122
- for (const file of fs37.readdirSync(latestScriptsDir)) {
65321
+ for (const file of fs38.readdirSync(latestScriptsDir)) {
65123
65322
  if (file.endsWith(".js") && targetFileNames.has(file)) {
65124
65323
  try {
65125
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65324
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65126
65325
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
65127
65326
  lines.push("```javascript");
65128
65327
  lines.push(content);
@@ -65132,14 +65331,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65132
65331
  }
65133
65332
  }
65134
65333
  }
65135
- const refFiles = fs37.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65334
+ const refFiles = fs38.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65136
65335
  if (refFiles.length > 0) {
65137
65336
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
65138
65337
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
65139
65338
  lines.push("");
65140
65339
  for (const file of refFiles) {
65141
65340
  try {
65142
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65341
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65143
65342
  lines.push(`### \`${file}\` \u{1F512}`);
65144
65343
  lines.push("```javascript");
65145
65344
  lines.push(content);
@@ -65180,11 +65379,11 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
65180
65379
  lines.push("");
65181
65380
  }
65182
65381
  }
65183
- const docsDir = path41.join(providerDir, "../../docs");
65382
+ const docsDir = path42.join(providerDir, "../../docs");
65184
65383
  const loadGuide = (name) => {
65185
65384
  try {
65186
- const p = path41.join(docsDir, name);
65187
- if (fs37.existsSync(p)) return fs37.readFileSync(p, "utf-8");
65385
+ const p = path42.join(docsDir, name);
65386
+ if (fs38.existsSync(p)) return fs38.readFileSync(p, "utf-8");
65188
65387
  } catch {
65189
65388
  }
65190
65389
  return null;
@@ -65420,7 +65619,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65420
65619
  parseApproval: "parse_approval.js"
65421
65620
  };
65422
65621
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
65423
- const scriptsDir = path41.join(providerDir, "scripts");
65622
+ const scriptsDir = path42.join(providerDir, "scripts");
65424
65623
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
65425
65624
  if (latestScriptsDir) {
65426
65625
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -65428,11 +65627,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65428
65627
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
65429
65628
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
65430
65629
  lines.push("");
65431
- for (const file of fs37.readdirSync(latestScriptsDir)) {
65630
+ for (const file of fs38.readdirSync(latestScriptsDir)) {
65432
65631
  if (!file.endsWith(".js")) continue;
65433
65632
  if (!targetFileNames.has(file)) continue;
65434
65633
  try {
65435
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65634
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65436
65635
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
65437
65636
  lines.push("```javascript");
65438
65637
  lines.push(content);
@@ -65441,14 +65640,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65441
65640
  } catch {
65442
65641
  }
65443
65642
  }
65444
- const refFiles = fs37.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65643
+ const refFiles = fs38.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
65445
65644
  if (refFiles.length > 0) {
65446
65645
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
65447
65646
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
65448
65647
  lines.push("");
65449
65648
  for (const file of refFiles) {
65450
65649
  try {
65451
- const content = fs37.readFileSync(path41.join(latestScriptsDir, file), "utf-8");
65650
+ const content = fs38.readFileSync(path42.join(latestScriptsDir, file), "utf-8");
65452
65651
  lines.push(`### \`${file}\` \u{1F512}`);
65453
65652
  lines.push("```javascript");
65454
65653
  lines.push(content);
@@ -65481,11 +65680,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
65481
65680
  lines.push("");
65482
65681
  }
65483
65682
  }
65484
- const docsDir = path41.join(providerDir, "../../docs");
65683
+ const docsDir = path42.join(providerDir, "../../docs");
65485
65684
  const loadGuide = (name) => {
65486
65685
  try {
65487
- const p = path41.join(docsDir, name);
65488
- if (fs37.existsSync(p)) return fs37.readFileSync(p, "utf-8");
65686
+ const p = path42.join(docsDir, name);
65687
+ if (fs38.existsSync(p)) return fs38.readFileSync(p, "utf-8");
65489
65688
  } catch {
65490
65689
  }
65491
65690
  return null;
@@ -65931,8 +66130,8 @@ var DevServer = class _DevServer {
65931
66130
  }
65932
66131
  getEndpointList() {
65933
66132
  return this.routes.map((r) => {
65934
- const path44 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
65935
- return `${r.method.padEnd(5)} ${path44}`;
66133
+ const path45 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
66134
+ return `${r.method.padEnd(5)} ${path45}`;
65936
66135
  });
65937
66136
  }
65938
66137
  async start(port = DEV_SERVER_PORT) {
@@ -66220,12 +66419,12 @@ var DevServer = class _DevServer {
66220
66419
  // ─── DevConsole SPA ───
66221
66420
  getConsoleDistDir() {
66222
66421
  const candidates = [
66223
- path42.resolve(__dirname, "../../web-devconsole/dist"),
66224
- path42.resolve(__dirname, "../../../web-devconsole/dist"),
66225
- path42.join(process.cwd(), "packages/web-devconsole/dist")
66422
+ path43.resolve(__dirname, "../../web-devconsole/dist"),
66423
+ path43.resolve(__dirname, "../../../web-devconsole/dist"),
66424
+ path43.join(process.cwd(), "packages/web-devconsole/dist")
66226
66425
  ];
66227
66426
  for (const dir of candidates) {
66228
- if (fs38.existsSync(path42.join(dir, "index.html"))) return dir;
66427
+ if (fs39.existsSync(path43.join(dir, "index.html"))) return dir;
66229
66428
  }
66230
66429
  return null;
66231
66430
  }
@@ -66235,9 +66434,9 @@ var DevServer = class _DevServer {
66235
66434
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
66236
66435
  return;
66237
66436
  }
66238
- const htmlPath = path42.join(distDir, "index.html");
66437
+ const htmlPath = path43.join(distDir, "index.html");
66239
66438
  try {
66240
- const html = fs38.readFileSync(htmlPath, "utf-8");
66439
+ const html = fs39.readFileSync(htmlPath, "utf-8");
66241
66440
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
66242
66441
  res.end(html);
66243
66442
  } catch (e) {
@@ -66260,15 +66459,15 @@ var DevServer = class _DevServer {
66260
66459
  this.json(res, 404, { error: "Not found" });
66261
66460
  return;
66262
66461
  }
66263
- const safePath = path42.normalize(pathname).replace(/^\.\.\//, "");
66264
- const filePath = path42.join(distDir, safePath);
66462
+ const safePath = path43.normalize(pathname).replace(/^\.\.\//, "");
66463
+ const filePath = path43.join(distDir, safePath);
66265
66464
  if (!filePath.startsWith(distDir)) {
66266
66465
  this.json(res, 403, { error: "Forbidden" });
66267
66466
  return;
66268
66467
  }
66269
66468
  try {
66270
- const content = fs38.readFileSync(filePath);
66271
- const ext = path42.extname(filePath);
66469
+ const content = fs39.readFileSync(filePath);
66470
+ const ext = path43.extname(filePath);
66272
66471
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
66273
66472
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
66274
66473
  res.end(content);
@@ -66376,14 +66575,14 @@ var DevServer = class _DevServer {
66376
66575
  const files = [];
66377
66576
  const scan = (d, prefix) => {
66378
66577
  try {
66379
- for (const entry of fs38.readdirSync(d, { withFileTypes: true })) {
66578
+ for (const entry of fs39.readdirSync(d, { withFileTypes: true })) {
66380
66579
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
66381
66580
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
66382
66581
  if (entry.isDirectory()) {
66383
66582
  files.push({ path: rel, size: 0, type: "dir" });
66384
- scan(path42.join(d, entry.name), rel);
66583
+ scan(path43.join(d, entry.name), rel);
66385
66584
  } else {
66386
- const stat2 = fs38.statSync(path42.join(d, entry.name));
66585
+ const stat2 = fs39.statSync(path43.join(d, entry.name));
66387
66586
  files.push({ path: rel, size: stat2.size, type: "file" });
66388
66587
  }
66389
66588
  }
@@ -66406,16 +66605,16 @@ var DevServer = class _DevServer {
66406
66605
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
66407
66606
  return;
66408
66607
  }
66409
- const fullPath = path42.resolve(dir, path42.normalize(filePath));
66608
+ const fullPath = path43.resolve(dir, path43.normalize(filePath));
66410
66609
  if (!fullPath.startsWith(dir)) {
66411
66610
  this.json(res, 403, { error: "Forbidden" });
66412
66611
  return;
66413
66612
  }
66414
- if (!fs38.existsSync(fullPath) || fs38.statSync(fullPath).isDirectory()) {
66613
+ if (!fs39.existsSync(fullPath) || fs39.statSync(fullPath).isDirectory()) {
66415
66614
  this.json(res, 404, { error: `File not found: ${filePath}` });
66416
66615
  return;
66417
66616
  }
66418
- const content = fs38.readFileSync(fullPath, "utf-8");
66617
+ const content = fs39.readFileSync(fullPath, "utf-8");
66419
66618
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
66420
66619
  }
66421
66620
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -66431,15 +66630,15 @@ var DevServer = class _DevServer {
66431
66630
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
66432
66631
  return;
66433
66632
  }
66434
- const fullPath = path42.resolve(dir, path42.normalize(filePath));
66633
+ const fullPath = path43.resolve(dir, path43.normalize(filePath));
66435
66634
  if (!fullPath.startsWith(dir)) {
66436
66635
  this.json(res, 403, { error: "Forbidden" });
66437
66636
  return;
66438
66637
  }
66439
66638
  try {
66440
- if (fs38.existsSync(fullPath)) fs38.copyFileSync(fullPath, fullPath + ".bak");
66441
- fs38.mkdirSync(path42.dirname(fullPath), { recursive: true });
66442
- fs38.writeFileSync(fullPath, content, "utf-8");
66639
+ if (fs39.existsSync(fullPath)) fs39.copyFileSync(fullPath, fullPath + ".bak");
66640
+ fs39.mkdirSync(path43.dirname(fullPath), { recursive: true });
66641
+ fs39.writeFileSync(fullPath, content, "utf-8");
66443
66642
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
66444
66643
  this.providerLoader.reload();
66445
66644
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -66455,9 +66654,9 @@ var DevServer = class _DevServer {
66455
66654
  return;
66456
66655
  }
66457
66656
  for (const name of ["scripts.js", "provider.json"]) {
66458
- const p = path42.join(dir, name);
66459
- if (fs38.existsSync(p)) {
66460
- const source = fs38.readFileSync(p, "utf-8");
66657
+ const p = path43.join(dir, name);
66658
+ if (fs39.existsSync(p)) {
66659
+ const source = fs39.readFileSync(p, "utf-8");
66461
66660
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
66462
66661
  return;
66463
66662
  }
@@ -66476,11 +66675,11 @@ var DevServer = class _DevServer {
66476
66675
  this.json(res, 404, { error: `Provider not found: ${type}` });
66477
66676
  return;
66478
66677
  }
66479
- const target = fs38.existsSync(path42.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
66480
- const targetPath = path42.join(dir, target);
66678
+ const target = fs39.existsSync(path43.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
66679
+ const targetPath = path43.join(dir, target);
66481
66680
  try {
66482
- if (fs38.existsSync(targetPath)) fs38.copyFileSync(targetPath, targetPath + ".bak");
66483
- fs38.writeFileSync(targetPath, source, "utf-8");
66681
+ if (fs39.existsSync(targetPath)) fs39.copyFileSync(targetPath, targetPath + ".bak");
66682
+ fs39.writeFileSync(targetPath, source, "utf-8");
66484
66683
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
66485
66684
  this.providerLoader.reload();
66486
66685
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -66624,21 +66823,21 @@ var DevServer = class _DevServer {
66624
66823
  }
66625
66824
  let targetDir;
66626
66825
  targetDir = this.providerLoader.getUserProviderDir(category, type);
66627
- const jsonPath = path42.join(targetDir, "provider.json");
66628
- if (fs38.existsSync(jsonPath)) {
66826
+ const jsonPath = path43.join(targetDir, "provider.json");
66827
+ if (fs39.existsSync(jsonPath)) {
66629
66828
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
66630
66829
  return;
66631
66830
  }
66632
66831
  try {
66633
66832
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version, osPaths, processNames });
66634
- fs38.mkdirSync(targetDir, { recursive: true });
66635
- fs38.writeFileSync(jsonPath, result["provider.json"], "utf-8");
66833
+ fs39.mkdirSync(targetDir, { recursive: true });
66834
+ fs39.writeFileSync(jsonPath, result["provider.json"], "utf-8");
66636
66835
  const createdFiles = ["provider.json"];
66637
66836
  if (result.files) {
66638
66837
  for (const [relPath, content] of Object.entries(result.files)) {
66639
- const fullPath = path42.join(targetDir, relPath);
66640
- fs38.mkdirSync(path42.dirname(fullPath), { recursive: true });
66641
- fs38.writeFileSync(fullPath, content, "utf-8");
66838
+ const fullPath = path43.join(targetDir, relPath);
66839
+ fs39.mkdirSync(path43.dirname(fullPath), { recursive: true });
66840
+ fs39.writeFileSync(fullPath, content, "utf-8");
66642
66841
  createdFiles.push(relPath);
66643
66842
  }
66644
66843
  }
@@ -66687,38 +66886,38 @@ var DevServer = class _DevServer {
66687
66886
  }
66688
66887
  // ─── Phase 2: Auto-Implement Backend ───
66689
66888
  getLatestScriptVersionDir(scriptsDir) {
66690
- if (!fs38.existsSync(scriptsDir)) return null;
66691
- const versions = fs38.readdirSync(scriptsDir).filter((d) => {
66889
+ if (!fs39.existsSync(scriptsDir)) return null;
66890
+ const versions = fs39.readdirSync(scriptsDir).filter((d) => {
66692
66891
  try {
66693
- return fs38.statSync(path42.join(scriptsDir, d)).isDirectory();
66892
+ return fs39.statSync(path43.join(scriptsDir, d)).isDirectory();
66694
66893
  } catch {
66695
66894
  return false;
66696
66895
  }
66697
66896
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
66698
66897
  if (versions.length === 0) return null;
66699
- return path42.join(scriptsDir, versions[0]);
66898
+ return path43.join(scriptsDir, versions[0]);
66700
66899
  }
66701
66900
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
66702
- const canonicalUserDir = path42.resolve(this.providerLoader.getUserProviderDir(category, type));
66703
- const desiredDir = requestedDir ? path42.resolve(requestedDir) : canonicalUserDir;
66704
- const upstreamRoot = path42.resolve(this.providerLoader.getUpstreamDir());
66705
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path42.sep}`)) {
66901
+ const canonicalUserDir = path43.resolve(this.providerLoader.getUserProviderDir(category, type));
66902
+ const desiredDir = requestedDir ? path43.resolve(requestedDir) : canonicalUserDir;
66903
+ const upstreamRoot = path43.resolve(this.providerLoader.getUpstreamDir());
66904
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path43.sep}`)) {
66706
66905
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
66707
66906
  }
66708
- if (path42.basename(desiredDir) !== type) {
66907
+ if (path43.basename(desiredDir) !== type) {
66709
66908
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
66710
66909
  }
66711
66910
  const sourceDir = this.findProviderDir(type);
66712
66911
  if (!sourceDir) {
66713
66912
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
66714
66913
  }
66715
- if (!fs38.existsSync(desiredDir)) {
66716
- fs38.mkdirSync(path42.dirname(desiredDir), { recursive: true });
66717
- fs38.cpSync(sourceDir, desiredDir, { recursive: true });
66914
+ if (!fs39.existsSync(desiredDir)) {
66915
+ fs39.mkdirSync(path43.dirname(desiredDir), { recursive: true });
66916
+ fs39.cpSync(sourceDir, desiredDir, { recursive: true });
66718
66917
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
66719
66918
  }
66720
- const providerJson = path42.join(desiredDir, "provider.json");
66721
- if (!fs38.existsSync(providerJson)) {
66919
+ const providerJson = path43.join(desiredDir, "provider.json");
66920
+ if (!fs39.existsSync(providerJson)) {
66722
66921
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
66723
66922
  }
66724
66923
  return { dir: desiredDir };
@@ -67560,9 +67759,9 @@ async function listHostedCliRuntimes(endpoint) {
67560
67759
 
67561
67760
  // src/session-host/managed-host.ts
67562
67761
  var import_child_process11 = require("child_process");
67563
- var fs39 = __toESM(require("fs"));
67564
- var os30 = __toESM(require("os"));
67565
- var path43 = __toESM(require("path"));
67762
+ var fs40 = __toESM(require("fs"));
67763
+ var os31 = __toESM(require("os"));
67764
+ var path44 = __toESM(require("path"));
67566
67765
  var import_session_host_core13 = require("@adhdev/session-host-core");
67567
67766
  init_runtime_defaults();
67568
67767
  function createManagedSessionHost(options) {
@@ -67577,24 +67776,24 @@ function createManagedSessionHost(options) {
67577
67776
  }
67578
67777
  function resolveEntry() {
67579
67778
  const packagedCandidates = [
67580
- path43.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
67581
- path43.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
67779
+ path44.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
67780
+ path44.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
67582
67781
  ];
67583
67782
  for (const candidate of packagedCandidates) {
67584
- if (fs39.existsSync(candidate)) {
67783
+ if (fs40.existsSync(candidate)) {
67585
67784
  return candidate;
67586
67785
  }
67587
67786
  }
67588
67787
  return require.resolve("@adhdev/session-host-daemon");
67589
67788
  }
67590
67789
  function getPidFile() {
67591
- return path43.join(os30.homedir(), ".adhdev", `${appName}-session-host.pid`);
67790
+ return path44.join(os31.homedir(), ".adhdev", `${appName}-session-host.pid`);
67592
67791
  }
67593
67792
  function getPid() {
67594
67793
  try {
67595
67794
  const pidFile = getPidFile();
67596
- if (!fs39.existsSync(pidFile)) return null;
67597
- const pid = Number.parseInt(fs39.readFileSync(pidFile, "utf8").trim(), 10);
67795
+ if (!fs40.existsSync(pidFile)) return null;
67796
+ const pid = Number.parseInt(fs40.readFileSync(pidFile, "utf8").trim(), 10);
67598
67797
  return Number.isFinite(pid) ? pid : null;
67599
67798
  } catch {
67600
67799
  return null;
@@ -67619,9 +67818,9 @@ function createManagedSessionHost(options) {
67619
67818
  let stdio = "ignore";
67620
67819
  let logFd = null;
67621
67820
  if (options.spawnStdio === "logfile") {
67622
- const logDir = path43.join(os30.homedir(), ".adhdev", "logs");
67623
- fs39.mkdirSync(logDir, { recursive: true });
67624
- logFd = fs39.openSync(path43.join(logDir, "session-host.log"), "a");
67821
+ const logDir = path44.join(os31.homedir(), ".adhdev", "logs");
67822
+ fs40.mkdirSync(logDir, { recursive: true });
67823
+ logFd = fs40.openSync(path44.join(logDir, "session-host.log"), "a");
67625
67824
  stdio = ["ignore", logFd, logFd];
67626
67825
  }
67627
67826
  const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
@@ -67633,7 +67832,7 @@ function createManagedSessionHost(options) {
67633
67832
  child.unref();
67634
67833
  if (logFd !== null) {
67635
67834
  try {
67636
- fs39.closeSync(logFd);
67835
+ fs40.closeSync(logFd);
67637
67836
  } catch {
67638
67837
  }
67639
67838
  }
@@ -67642,8 +67841,8 @@ function createManagedSessionHost(options) {
67642
67841
  let stopped = false;
67643
67842
  const pidFile = getPidFile();
67644
67843
  try {
67645
- if (fs39.existsSync(pidFile)) {
67646
- const pid = Number.parseInt(fs39.readFileSync(pidFile, "utf8").trim(), 10);
67844
+ if (fs40.existsSync(pidFile)) {
67845
+ const pid = Number.parseInt(fs40.readFileSync(pidFile, "utf8").trim(), 10);
67647
67846
  if (Number.isFinite(pid) && pid !== process.pid && isManagedPid(pid)) {
67648
67847
  stopped = killPid2(pid) || stopped;
67649
67848
  }
@@ -67651,7 +67850,7 @@ function createManagedSessionHost(options) {
67651
67850
  } catch {
67652
67851
  } finally {
67653
67852
  try {
67654
- fs39.unlinkSync(pidFile);
67853
+ fs40.unlinkSync(pidFile);
67655
67854
  } catch {
67656
67855
  }
67657
67856
  }
@@ -67837,8 +68036,8 @@ async function installExtension(ide, extension) {
67837
68036
  const res = await fetch(extension.vsixUrl);
67838
68037
  if (res.ok) {
67839
68038
  const buffer = Buffer.from(await res.arrayBuffer());
67840
- const fs40 = await import("fs");
67841
- fs40.writeFileSync(vsixPath, buffer);
68039
+ const fs41 = await import("fs");
68040
+ fs41.writeFileSync(vsixPath, buffer);
67842
68041
  return new Promise((resolve25) => {
67843
68042
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
67844
68043
  (0, import_child_process12.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {