@adhdev/daemon-standalone 0.9.82-rc.352 → 0.9.82-rc.354

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
@@ -30036,10 +30036,10 @@ var require_dist3 = __commonJS({
30036
30036
  }
30037
30037
  function getDaemonBuildInfo() {
30038
30038
  if (cached2) return cached2;
30039
- const commit = readInjected(true ? "ca5f944b7763a621357fc28a9f62ac398b0ced6c" : void 0) ?? "unknown";
30040
- const commitShort = readInjected(true ? "ca5f944b" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30041
- const version2 = readInjected(true ? "0.9.82-rc.352" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30042
- const builtAt = readInjected(true ? "2026-06-22T07:17:32.309Z" : void 0);
30039
+ const commit = readInjected(true ? "5d100a177f412ae29a58048f0a211c3928b06910" : void 0) ?? "unknown";
30040
+ const commitShort = readInjected(true ? "5d100a17" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30041
+ const version2 = readInjected(true ? "0.9.82-rc.354" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30042
+ const builtAt = readInjected(true ? "2026-06-22T11:32:34.147Z" : void 0);
30043
30043
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
30044
30044
  return cached2;
30045
30045
  }
@@ -30793,6 +30793,9 @@ var require_dist3 = __commonJS({
30793
30793
  getGitDiffSummary: () => getGitDiffSummary,
30794
30794
  getGitFileDiff: () => getGitFileDiff
30795
30795
  });
30796
+ function withCollectionTimeout(options) {
30797
+ return options.timeoutMs === void 0 ? { ...options, timeoutMs: GIT_STATUS_TIMEOUT_MS } : options;
30798
+ }
30796
30799
  function validateBaseRef(ref) {
30797
30800
  const trimmed = ref.trim();
30798
30801
  if (!trimmed || trimmed.startsWith("-") || trimmed.includes("..") || !/^[A-Za-z0-9][A-Za-z0-9._/@-]*$/.test(trimmed)) {
@@ -30802,14 +30805,15 @@ var require_dist3 = __commonJS({
30802
30805
  }
30803
30806
  async function getGitDiffSummary(workspace, options = {}) {
30804
30807
  const lastCheckedAt = Date.now();
30808
+ const effectiveOptions = withCollectionTimeout(options);
30805
30809
  try {
30806
- const repo = await resolveGitRepository(workspace, options);
30810
+ const repo = await resolveGitRepository(workspace, effectiveOptions);
30807
30811
  const repoRoot = repo.repoRoot;
30808
30812
  if (options.baseRef) {
30809
30813
  const range = `${validateBaseRef(options.baseRef)}...HEAD`;
30810
30814
  const [nameStatus, numstat] = await Promise.all([
30811
- runGit(repo, ["diff", "--no-ext-diff", "--name-status", range, "--"], { ...options, cwd: repoRoot }),
30812
- runGit(repo, ["diff", "--no-ext-diff", "--numstat", range, "--"], { ...options, cwd: repoRoot })
30815
+ runGit(repo, ["diff", "--no-ext-diff", "--name-status", range, "--"], { ...effectiveOptions, cwd: repoRoot }),
30816
+ runGit(repo, ["diff", "--no-ext-diff", "--numstat", range, "--"], { ...effectiveOptions, cwd: repoRoot })
30813
30817
  ]);
30814
30818
  const outputBytes2 = byteLength(nameStatus.stdout + numstat.stdout);
30815
30819
  const changes2 = combineDiffEntries(nameStatus.stdout, numstat.stdout, false);
@@ -30828,11 +30832,11 @@ var require_dist3 = __commonJS({
30828
30832
  };
30829
30833
  }
30830
30834
  const [unstagedNameStatus, unstagedNumstat, stagedNameStatus, stagedNumstat, untracked] = await Promise.all([
30831
- runGit(repo, ["diff", "--no-ext-diff", "--name-status"], { ...options, cwd: repoRoot }),
30832
- runGit(repo, ["diff", "--no-ext-diff", "--numstat"], { ...options, cwd: repoRoot }),
30833
- runGit(repo, ["diff", "--cached", "--no-ext-diff", "--name-status"], { ...options, cwd: repoRoot }),
30834
- runGit(repo, ["diff", "--cached", "--no-ext-diff", "--numstat"], { ...options, cwd: repoRoot }),
30835
- runGit(repo, ["ls-files", "--others", "--exclude-standard"], { ...options, cwd: repoRoot })
30835
+ runGit(repo, ["diff", "--no-ext-diff", "--name-status"], { ...effectiveOptions, cwd: repoRoot }),
30836
+ runGit(repo, ["diff", "--no-ext-diff", "--numstat"], { ...effectiveOptions, cwd: repoRoot }),
30837
+ runGit(repo, ["diff", "--cached", "--no-ext-diff", "--name-status"], { ...effectiveOptions, cwd: repoRoot }),
30838
+ runGit(repo, ["diff", "--cached", "--no-ext-diff", "--numstat"], { ...effectiveOptions, cwd: repoRoot }),
30839
+ runGit(repo, ["ls-files", "--others", "--exclude-standard"], { ...effectiveOptions, cwd: repoRoot })
30836
30840
  ]);
30837
30841
  const outputBytes = byteLength(
30838
30842
  unstagedNameStatus.stdout + unstagedNumstat.stdout + stagedNameStatus.stdout + stagedNumstat.stdout + untracked.stdout
@@ -30874,13 +30878,14 @@ var require_dist3 = __commonJS({
30874
30878
  }
30875
30879
  async function getGitFileDiff(workspace, filePath, options = {}) {
30876
30880
  const lastCheckedAt = Date.now();
30877
- const repo = await resolveGitRepository(workspace, options);
30881
+ const effectiveOptions = withCollectionTimeout(options);
30882
+ const repo = await resolveGitRepository(workspace, effectiveOptions);
30878
30883
  const repoRoot = repo.repoRoot;
30879
30884
  const selected = await resolveRepoFilePath(repoRoot, filePath);
30880
30885
  const maxBytes = normalizePositiveInteger(options.maxBytes, DEFAULT_MAX_BYTES);
30881
30886
  if (options.baseRef) {
30882
30887
  const range = `${validateBaseRef(options.baseRef)}...HEAD`;
30883
- const result = await runGit(repo, ["diff", "--no-ext-diff", range, "--", selected.relativePath], { ...options, cwd: repoRoot });
30888
+ const result = await runGit(repo, ["diff", "--no-ext-diff", range, "--", selected.relativePath], { ...effectiveOptions, cwd: repoRoot });
30884
30889
  const bounded2 = truncateText(result.stdout, maxBytes);
30885
30890
  return {
30886
30891
  workspace: repo.workspace,
@@ -30893,13 +30898,13 @@ var require_dist3 = __commonJS({
30893
30898
  };
30894
30899
  }
30895
30900
  const [unstaged, staged] = await Promise.all([
30896
- runGit(repo, ["diff", "--no-ext-diff", "--", selected.relativePath], { ...options, cwd: repoRoot }),
30897
- runGit(repo, ["diff", "--cached", "--no-ext-diff", "--", selected.relativePath], { ...options, cwd: repoRoot })
30901
+ runGit(repo, ["diff", "--no-ext-diff", "--", selected.relativePath], { ...effectiveOptions, cwd: repoRoot }),
30902
+ runGit(repo, ["diff", "--cached", "--no-ext-diff", "--", selected.relativePath], { ...effectiveOptions, cwd: repoRoot })
30898
30903
  ]);
30899
30904
  let diff = [unstaged.stdout, staged.stdout].filter((part) => part.length > 0).join("\n");
30900
30905
  if (!diff) {
30901
30906
  const untracked = await runGit(repo, ["ls-files", "--others", "--exclude-standard", "--", selected.relativePath], {
30902
- ...options,
30907
+ ...effectiveOptions,
30903
30908
  cwd: repoRoot
30904
30909
  });
30905
30910
  const untrackedFiles = untracked.stdout.split("\n").filter(Boolean);
@@ -32442,6 +32447,255 @@ ${error48.message || ""}`;
32442
32447
  SPAWNED_SESSION_VISIBILITY_MODES = /* @__PURE__ */ new Set(["visible", "hidden"]);
32443
32448
  }
32444
32449
  });
32450
+ function readRecord(value) {
32451
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
32452
+ }
32453
+ function readString3(...values) {
32454
+ for (const value of values) {
32455
+ if (typeof value !== "string") continue;
32456
+ const trimmed = value.trim();
32457
+ if (trimmed) return trimmed;
32458
+ }
32459
+ return void 0;
32460
+ }
32461
+ function readNumber(...values) {
32462
+ for (const value of values) {
32463
+ if (typeof value === "number" && Number.isFinite(value)) return value;
32464
+ }
32465
+ return void 0;
32466
+ }
32467
+ function readBoolean(...values) {
32468
+ for (const value of values) {
32469
+ if (typeof value === "boolean") return value;
32470
+ }
32471
+ return void 0;
32472
+ }
32473
+ function joinRepoPath(root, relativePath) {
32474
+ const normalizedRoot = typeof root === "string" ? root.trim().replace(/[\\/]+$/, "") : "";
32475
+ const normalizedPath = typeof relativePath === "string" ? relativePath.trim() : "";
32476
+ if (!normalizedPath) return void 0;
32477
+ if (/^(?:[A-Za-z]:[\\/]|\/)/.test(normalizedPath)) return normalizedPath;
32478
+ if (!normalizedRoot) return void 0;
32479
+ return `${normalizedRoot}/${normalizedPath.replace(/^[\\/]+/, "")}`;
32480
+ }
32481
+ function scoreGitUpstreamFreshness(status) {
32482
+ switch (status) {
32483
+ case "fresh":
32484
+ return 30;
32485
+ case "no_upstream":
32486
+ return 4;
32487
+ case "unchecked":
32488
+ case void 0:
32489
+ return 0;
32490
+ case "stale":
32491
+ return -10;
32492
+ case "unavailable":
32493
+ return -15;
32494
+ default:
32495
+ return 0;
32496
+ }
32497
+ }
32498
+ function readGitSubmodules(value, parentRepoRoot) {
32499
+ if (!Array.isArray(value)) return void 0;
32500
+ const submodules = value.map((entry) => {
32501
+ const submodule = readRecord(entry);
32502
+ const path422 = readString3(submodule.path);
32503
+ const commit = readString3(submodule.commit);
32504
+ const repoPath = readString3(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path422);
32505
+ if (!path422 || !commit) return null;
32506
+ const result = {
32507
+ path: path422,
32508
+ commit,
32509
+ dirty: readBoolean(submodule.dirty) ?? false,
32510
+ outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
32511
+ lastCheckedAt: readNumber(submodule.lastCheckedAt, submodule.last_checked_at) ?? Date.now()
32512
+ };
32513
+ if (repoPath) result.repoPath = repoPath;
32514
+ const error48 = readString3(submodule.error);
32515
+ if (error48) result.error = error48;
32516
+ return result;
32517
+ }).filter((entry) => entry !== null);
32518
+ return submodules.length > 0 ? submodules : void 0;
32519
+ }
32520
+ function hasGitStatusEvidence(status) {
32521
+ return readBoolean(status.isGitRepo) !== void 0 || Boolean(readString3(status.branch, status.upstream, status.upstreamStatus, status.upstream_status, status.headCommit)) || Boolean(readString3(status.repoRoot, status.repo_root, status.workspace)) || readNumber(
32522
+ status.ahead,
32523
+ status.behind,
32524
+ status.staged,
32525
+ status.modified,
32526
+ status.untracked,
32527
+ status.deleted,
32528
+ status.renamed,
32529
+ status.lastCheckedAt,
32530
+ status.last_checked_at
32531
+ ) !== void 0 || Array.isArray(status.submodules) && status.submodules.length > 0;
32532
+ }
32533
+ function normalizeGitStatus(status, node, options) {
32534
+ const explicitIsGitRepo = readBoolean(status.isGitRepo);
32535
+ if (!Object.keys(status).length || !hasGitStatusEvidence(status)) return void 0;
32536
+ const isGitRepo = explicitIsGitRepo ?? true;
32537
+ const conflictFiles = Array.isArray(status.conflictFiles) ? status.conflictFiles.filter((entry) => typeof entry === "string") : [];
32538
+ const conflictCount = readNumber(status.conflicts) ?? conflictFiles.length;
32539
+ const hasConflicts = readBoolean(status.hasConflicts) ?? conflictCount > 0;
32540
+ const repoRoot = readString3(status.repoRoot, status.repo_root, node.repoRoot, node.repo_root, status.workspace, node.workspace) || void 0;
32541
+ const submodules = readGitSubmodules(status.submodules, repoRoot);
32542
+ const upstreamStatus = readString3(status.upstreamStatus, status.upstream_status);
32543
+ const upstreamFetchedAt = readNumber(status.upstreamFetchedAt, status.upstream_fetched_at);
32544
+ const upstreamFetchError = readString3(status.upstreamFetchError, status.upstream_fetch_error);
32545
+ const error48 = readString3(status.error);
32546
+ const staged = readNumber(status.staged) ?? 0;
32547
+ const modified = readNumber(status.modified) ?? 0;
32548
+ const untracked = readNumber(status.untracked) ?? 0;
32549
+ const deleted = readNumber(status.deleted) ?? 0;
32550
+ const renamed = readNumber(status.renamed) ?? 0;
32551
+ return {
32552
+ workspace: readString3(status.workspace, node.workspace) || "",
32553
+ repoRoot: repoRoot ?? null,
32554
+ isGitRepo,
32555
+ branch: readString3(status.branch) ?? null,
32556
+ headCommit: readString3(status.headCommit) ?? null,
32557
+ headMessage: readString3(status.headMessage) ?? null,
32558
+ upstream: readString3(status.upstream) ?? null,
32559
+ upstreamStatus: upstreamStatus ?? "unchecked",
32560
+ ...upstreamFetchedAt !== void 0 ? { upstreamFetchedAt } : {},
32561
+ ...upstreamFetchError ? { upstreamFetchError } : {},
32562
+ ahead: readNumber(status.ahead) ?? 0,
32563
+ behind: readNumber(status.behind) ?? 0,
32564
+ staged,
32565
+ modified,
32566
+ untracked,
32567
+ deleted,
32568
+ renamed,
32569
+ dirty: readBoolean(status.dirty, status.isDirty, status.is_dirty) ?? (staged + modified + untracked + deleted + renamed > 0 || hasConflicts),
32570
+ hasConflicts,
32571
+ conflictFiles,
32572
+ stashCount: readNumber(status.stashCount, status.stash_count) ?? 0,
32573
+ lastCheckedAt: options?.lastCheckedAt ?? readNumber(status.lastCheckedAt, status.last_checked_at) ?? Date.now(),
32574
+ ...submodules ? { submodules } : {},
32575
+ ...error48 ? { error: error48 } : {}
32576
+ };
32577
+ }
32578
+ function scoreGitStatusCandidate(git) {
32579
+ if (!git) return Number.NEGATIVE_INFINITY;
32580
+ let score = 0;
32581
+ if (git.isGitRepo === true) score += 50;
32582
+ if (git.isGitRepo === false) score -= 10;
32583
+ if (git.branch) score += 20;
32584
+ if (git.headCommit) score += 20;
32585
+ if (git.upstream) score += 10;
32586
+ score += scoreGitUpstreamFreshness(git.upstreamStatus);
32587
+ if (typeof git.ahead === "number") score += 2;
32588
+ if (typeof git.behind === "number") score += 2;
32589
+ if (Array.isArray(git.submodules) && git.submodules.length > 0) score += 4 + git.submodules.length;
32590
+ if (git.error) score -= 20;
32591
+ return score;
32592
+ }
32593
+ function pickBestTransitGitStatus(node, options) {
32594
+ const rawGit = readRecord(node.lastGit ?? node.last_git);
32595
+ const gitResult = readRecord(rawGit.result);
32596
+ const directStatus = readRecord(rawGit.status);
32597
+ const nestedStatus = readRecord(gitResult.status);
32598
+ const rawProbe = readRecord(node.lastProbe ?? node.last_probe);
32599
+ const probeGit = readRecord(rawProbe.git);
32600
+ const probeGitResult = readRecord(probeGit.result);
32601
+ const probeDirectStatus = readRecord(probeGit.status);
32602
+ const probeNestedStatus = readRecord(probeGitResult.status);
32603
+ const lastCheckedAt = options?.lastCheckedAt;
32604
+ let best = null;
32605
+ for (const status of [directStatus, nestedStatus, probeDirectStatus, probeNestedStatus]) {
32606
+ const normalized = normalizeGitStatus(status, node, { lastCheckedAt: lastCheckedAt ?? Date.now() });
32607
+ if (!normalized) continue;
32608
+ const score = scoreGitStatusCandidate(normalized);
32609
+ if (!best || score > best.score) best = { git: normalized, score };
32610
+ }
32611
+ return best?.git;
32612
+ }
32613
+ function normalizeMeshNodeId(node) {
32614
+ const record2 = node && typeof node === "object" ? node : {};
32615
+ return readString3(record2.id, record2.nodeId, record2.node_id);
32616
+ }
32617
+ function meshNodeIdMatches(node, candidateId) {
32618
+ if (!candidateId) return false;
32619
+ const trimmed = candidateId.trim();
32620
+ if (!trimmed) return false;
32621
+ return normalizeMeshNodeId(node) === trimmed;
32622
+ }
32623
+ function machineCoreFromDaemonId(id) {
32624
+ const trimmed = readString3(id);
32625
+ if (!trimmed) return void 0;
32626
+ for (const prefix of DAEMON_ID_PREFIXES) {
32627
+ if (trimmed.startsWith(prefix)) {
32628
+ const core = trimmed.slice(prefix.length).trim();
32629
+ return core || void 0;
32630
+ }
32631
+ }
32632
+ return trimmed;
32633
+ }
32634
+ function daemonIdsEquivalent(a, b) {
32635
+ const coreA = machineCoreFromDaemonId(a);
32636
+ const coreB = machineCoreFromDaemonId(b);
32637
+ if (!coreA || !coreB) return false;
32638
+ return coreA === coreB;
32639
+ }
32640
+ function expandDaemonIdForms(ids) {
32641
+ const list = Array.isArray(ids) ? ids : ids != null ? [ids] : [];
32642
+ const out = [];
32643
+ const seen = /* @__PURE__ */ new Set();
32644
+ const add = (value) => {
32645
+ if (!value || seen.has(value)) return;
32646
+ seen.add(value);
32647
+ out.push(value);
32648
+ };
32649
+ for (const raw of list) add(readString3(raw));
32650
+ for (const raw of list) {
32651
+ const core = machineCoreFromDaemonId(readString3(raw));
32652
+ if (!core || !core.startsWith("mach_")) continue;
32653
+ add(core);
32654
+ for (const prefix of DAEMON_ID_PREFIXES) add(`${prefix}${core}`);
32655
+ }
32656
+ return out;
32657
+ }
32658
+ function summarizeGitShape(status) {
32659
+ const record2 = readRecord(status);
32660
+ if (!Object.keys(record2).length) return null;
32661
+ const submodules = Array.isArray(record2.submodules) ? record2.submodules.map((entry) => {
32662
+ const sub = readRecord(entry);
32663
+ return {
32664
+ path: readString3(sub.path) ?? null,
32665
+ commit: readString3(sub.commit)?.slice(0, 12) ?? null,
32666
+ dirty: readBoolean(sub.dirty) ?? false,
32667
+ outOfSync: readBoolean(sub.outOfSync, sub.out_of_sync) ?? false
32668
+ };
32669
+ }) : [];
32670
+ return {
32671
+ isGitRepo: readBoolean(record2.isGitRepo),
32672
+ workspace: readString3(record2.workspace) ?? null,
32673
+ repoRoot: readString3(record2.repoRoot, record2.repo_root) ?? null,
32674
+ branch: readString3(record2.branch) ?? null,
32675
+ upstream: readString3(record2.upstream) ?? null,
32676
+ upstreamStatus: readString3(record2.upstreamStatus, record2.upstream_status) ?? null,
32677
+ headCommit: readString3(record2.headCommit, record2.head_commit)?.slice(0, 12) ?? null,
32678
+ ahead: readNumber(record2.ahead) ?? null,
32679
+ behind: readNumber(record2.behind) ?? null,
32680
+ dirtyCounts: {
32681
+ staged: readNumber(record2.staged) ?? 0,
32682
+ modified: readNumber(record2.modified) ?? 0,
32683
+ untracked: readNumber(record2.untracked) ?? 0,
32684
+ deleted: readNumber(record2.deleted) ?? 0,
32685
+ renamed: readNumber(record2.renamed) ?? 0
32686
+ },
32687
+ lastCheckedAt: readNumber(record2.lastCheckedAt, record2.last_checked_at) ?? null,
32688
+ submoduleCount: submodules.length,
32689
+ submodules
32690
+ };
32691
+ }
32692
+ var DAEMON_ID_PREFIXES;
32693
+ var init_dist = __esm2({
32694
+ "../mesh-shared/dist/index.mjs"() {
32695
+ "use strict";
32696
+ DAEMON_ID_PREFIXES = ["daemon_", "standalone_"];
32697
+ }
32698
+ });
32445
32699
  var coordinator_prompt_exports = {};
32446
32700
  __export2(coordinator_prompt_exports, {
32447
32701
  buildCoordinatorSystemPrompt: () => buildCoordinatorSystemPrompt
@@ -36093,10 +36347,10 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36093
36347
  COMPACT_STATUS_GOAL_PREVIEW_MAX = 80;
36094
36348
  }
36095
36349
  });
36096
- function readString3(value) {
36350
+ function readString4(value) {
36097
36351
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
36098
36352
  }
36099
- function readRecord(value) {
36353
+ function readRecord2(value) {
36100
36354
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
36101
36355
  }
36102
36356
  function eventStatus(event, fallback) {
@@ -36119,7 +36373,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36119
36373
  return "Refine job failed; inspect result/finalBranchConvergenceState in mesh_task_history, fix the blocker, then rerun mesh_refine_node when ready.";
36120
36374
  }
36121
36375
  function mergeJob(jobs, patch) {
36122
- const jobId = readString3(patch.jobId);
36376
+ const jobId = readString4(patch.jobId);
36123
36377
  if (!jobId) return;
36124
36378
  const previous = jobs.get(jobId);
36125
36379
  const status = patch.status || previous?.status || "running";
@@ -36137,54 +36391,54 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36137
36391
  function buildMeshAsyncRefineJobs(args) {
36138
36392
  const jobs = /* @__PURE__ */ new Map();
36139
36393
  for (const entry of args.ledgerEntries || []) {
36140
- const payload = readRecord(entry.payload);
36394
+ const payload = readRecord2(entry.payload);
36141
36395
  if (payload?.source !== "refine_mesh_node_async_job") continue;
36142
- const refineJob = readRecord(payload.refineJob);
36143
- const result = readRecord(payload.result);
36144
- const finalState = readRecord(payload.finalBranchConvergenceState) || readRecord(result?.finalBranchConvergenceState);
36145
- const jobId = readString3(refineJob?.jobId);
36396
+ const refineJob = readRecord2(payload.refineJob);
36397
+ const result = readRecord2(payload.result);
36398
+ const finalState = readRecord2(payload.finalBranchConvergenceState) || readRecord2(result?.finalBranchConvergenceState);
36399
+ const jobId = readString4(refineJob?.jobId);
36146
36400
  if (!jobId) continue;
36147
- const status = ledgerStatus(entry.kind, readString3(refineJob?.status));
36401
+ const status = ledgerStatus(entry.kind, readString4(refineJob?.status));
36148
36402
  mergeJob(jobs, {
36149
36403
  jobId,
36150
- interactionId: readString3(refineJob?.interactionId),
36404
+ interactionId: readString4(refineJob?.interactionId),
36151
36405
  status,
36152
- meshId: readString3(refineJob?.meshId) || args.meshId,
36153
- nodeId: readString3(refineJob?.nodeId) || entry.nodeId,
36154
- targetNodeId: readString3(refineJob?.nodeId) || entry.nodeId,
36155
- targetDaemonId: readString3(refineJob?.targetDaemonId),
36156
- workspace: readString3(refineJob?.workspace),
36157
- branch: readString3(result?.branch) || readString3(finalState?.branch),
36158
- into: readString3(result?.into) || readString3(finalState?.baseBranch),
36159
- startedAt: readString3(refineJob?.startedAt),
36160
- completedAt: readString3(refineJob?.completedAt),
36161
- retryOfJobId: readString3(refineJob?.retryOfJobId) || readString3(payload.retryOfJobId),
36406
+ meshId: readString4(refineJob?.meshId) || args.meshId,
36407
+ nodeId: readString4(refineJob?.nodeId) || entry.nodeId,
36408
+ targetNodeId: readString4(refineJob?.nodeId) || entry.nodeId,
36409
+ targetDaemonId: readString4(refineJob?.targetDaemonId),
36410
+ workspace: readString4(refineJob?.workspace),
36411
+ branch: readString4(result?.branch) || readString4(finalState?.branch),
36412
+ into: readString4(result?.into) || readString4(finalState?.baseBranch),
36413
+ startedAt: readString4(refineJob?.startedAt),
36414
+ completedAt: readString4(refineJob?.completedAt),
36415
+ retryOfJobId: readString4(refineJob?.retryOfJobId) || readString4(payload.retryOfJobId),
36162
36416
  lastLedgerKind: entry.kind,
36163
36417
  lastUpdatedAt: entry.timestamp
36164
36418
  });
36165
36419
  }
36166
36420
  for (const event of args.pendingEvents || []) {
36167
- const metadata = readRecord(event.metadataEvent);
36421
+ const metadata = readRecord2(event.metadataEvent);
36168
36422
  if (metadata?.source !== "refine_mesh_node_async_job") continue;
36169
- const result = readRecord(metadata.result);
36170
- const finalState = readRecord(result?.finalBranchConvergenceState);
36171
- const jobId = readString3(metadata.jobId);
36423
+ const result = readRecord2(metadata.result);
36424
+ const finalState = readRecord2(result?.finalBranchConvergenceState);
36425
+ const jobId = readString4(metadata.jobId);
36172
36426
  if (!jobId) continue;
36173
- const status = eventStatus(event.event, readString3(metadata.status));
36427
+ const status = eventStatus(event.event, readString4(metadata.status));
36174
36428
  mergeJob(jobs, {
36175
36429
  jobId,
36176
- interactionId: readString3(metadata.interactionId),
36430
+ interactionId: readString4(metadata.interactionId),
36177
36431
  ...status ? { status } : {},
36178
- meshId: readString3(metadata.meshId) || event.meshId || args.meshId,
36179
- nodeId: readString3(metadata.nodeId) || event.nodeId,
36180
- targetNodeId: readString3(metadata.nodeId) || event.nodeId,
36181
- targetDaemonId: readString3(metadata.targetDaemonId),
36182
- workspace: readString3(metadata.workspace) || event.workspace,
36183
- branch: readString3(result?.branch) || readString3(finalState?.branch),
36184
- into: readString3(result?.into) || readString3(finalState?.baseBranch),
36185
- startedAt: readString3(metadata.startedAt),
36186
- completedAt: readString3(metadata.completedAt),
36187
- retryOfJobId: readString3(metadata.retryOfJobId),
36432
+ meshId: readString4(metadata.meshId) || event.meshId || args.meshId,
36433
+ nodeId: readString4(metadata.nodeId) || event.nodeId,
36434
+ targetNodeId: readString4(metadata.nodeId) || event.nodeId,
36435
+ targetDaemonId: readString4(metadata.targetDaemonId),
36436
+ workspace: readString4(metadata.workspace) || event.workspace,
36437
+ branch: readString4(result?.branch) || readString4(finalState?.branch),
36438
+ into: readString4(result?.into) || readString4(finalState?.baseBranch),
36439
+ startedAt: readString4(metadata.startedAt),
36440
+ completedAt: readString4(metadata.completedAt),
36441
+ retryOfJobId: readString4(metadata.retryOfJobId),
36188
36442
  lastEvent: event.event,
36189
36443
  lastUpdatedAt: new Date(event.queuedAt).toISOString()
36190
36444
  });
@@ -36245,10 +36499,10 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36245
36499
  __export2(mesh_review_inbox_exports, {
36246
36500
  deriveMeshReviewInboxItems: () => deriveMeshReviewInboxItems
36247
36501
  });
36248
- function readString4(value) {
36502
+ function readString5(value) {
36249
36503
  return typeof value === "string" && value.trim() ? value.trim() : null;
36250
36504
  }
36251
- function readRecord2(value) {
36505
+ function readRecord3(value) {
36252
36506
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
36253
36507
  }
36254
36508
  function readStringArray3(value, max) {
@@ -36258,20 +36512,20 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36258
36512
  }
36259
36513
  function isLocalNodeStatus(node) {
36260
36514
  if (node.isLocalWorktree === true) return true;
36261
- const connection = readRecord2(node.connection);
36262
- return readString4(connection?.state) === "self";
36515
+ const connection = readRecord3(node.connection);
36516
+ return readString5(connection?.state) === "self";
36263
36517
  }
36264
36518
  function readNodeConvergence(node) {
36265
- const convergence = readRecord2(node.branchConvergence);
36266
- const status = readString4(convergence?.status);
36519
+ const convergence = readRecord3(node.branchConvergence);
36520
+ const status = readString5(convergence?.status);
36267
36521
  if (!convergence || !status) return null;
36268
36522
  return {
36269
36523
  status,
36270
- reason: readString4(convergence.reason),
36271
- nextStep: readString4(convergence.nextStep),
36524
+ reason: readString5(convergence.reason),
36525
+ nextStep: readString5(convergence.nextStep),
36272
36526
  needsConvergence: convergence.needsConvergence === true,
36273
- branch: readString4(convergence.branch),
36274
- defaultBranch: readString4(convergence.defaultBranch)
36527
+ branch: readString5(convergence.branch),
36528
+ defaultBranch: readString5(convergence.defaultBranch)
36275
36529
  };
36276
36530
  }
36277
36531
  function isMergeCandidate(convergence) {
@@ -36279,15 +36533,15 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36279
36533
  return convergence.status === "cleanup_candidate" && convergence.reason === "clean_non_default_worktree_branch";
36280
36534
  }
36281
36535
  function readWorkerArtifact(value) {
36282
- const worker = readRecord2(value);
36536
+ const worker = readRecord3(value);
36283
36537
  if (!worker) return null;
36284
36538
  const changed = readStringArray3(worker.changedFiles, MAX_CHANGED_FILES);
36285
36539
  return {
36286
- status: readString4(worker.status) ?? "unknown",
36287
- ...readString4(worker.classification) ? { classification: readString4(worker.classification) } : {},
36540
+ status: readString5(worker.status) ?? "unknown",
36541
+ ...readString5(worker.classification) ? { classification: readString5(worker.classification) } : {},
36288
36542
  changedFiles: changed.values,
36289
36543
  ...changed.truncated ? { changedFilesTruncated: true } : {},
36290
- validationResults: Array.isArray(worker.validationResults) ? worker.validationResults.map((item) => readRecord2(item)).filter((item) => item !== null) : [],
36544
+ validationResults: Array.isArray(worker.validationResults) ? worker.validationResults.map((item) => readRecord3(item)).filter((item) => item !== null) : [],
36291
36545
  errors: readStringArray3(worker.errors, 20).values,
36292
36546
  requiresUserAction: worker.requiresUserAction === true
36293
36547
  };
@@ -36301,43 +36555,43 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36301
36555
  for (let i = ledgerEntries.length - 1; i >= 0; i--) {
36302
36556
  const entry = ledgerEntries[i];
36303
36557
  if (entry.nodeId !== nodeId || !isTerminalLedgerKind(entry.kind)) continue;
36304
- const payload = readRecord2(entry.payload) ?? {};
36558
+ const payload = readRecord3(entry.payload) ?? {};
36305
36559
  if (!evidence.available) {
36306
36560
  if (payload.source === "refine_mesh_node_async_job") {
36307
- const result = readRecord2(payload.result);
36308
- const validationSummary = readRecord2(result?.validationSummary);
36561
+ const result = readRecord3(payload.result);
36562
+ const validationSummary = readRecord3(result?.validationSummary);
36309
36563
  evidence = {
36310
36564
  available: true,
36311
36565
  kind: entry.kind,
36312
36566
  source: "refine_job",
36313
36567
  timestamp: entry.timestamp,
36314
36568
  ...entry.sessionId ? { sessionId: entry.sessionId } : {},
36315
- bootstrap: readRecord2(validationSummary?.bootstrap),
36569
+ bootstrap: readRecord3(validationSummary?.bootstrap),
36316
36570
  validation: validationSummary ? Object.fromEntries(Object.entries(validationSummary).filter(([key]) => key !== "bootstrap")) : null,
36317
- checkpoint: readRecord2(result?.checkpoint),
36571
+ checkpoint: readRecord3(result?.checkpoint),
36318
36572
  worker: null,
36319
- ...readRecord2(payload.finalBranchConvergenceState) ?? readRecord2(result?.finalBranchConvergenceState) ? { finalBranchConvergenceState: readRecord2(payload.finalBranchConvergenceState) ?? readRecord2(result?.finalBranchConvergenceState) } : {},
36320
- ...readRecord2(payload.refineJob) ? { refineJob: readRecord2(payload.refineJob) } : {}
36573
+ ...readRecord3(payload.finalBranchConvergenceState) ?? readRecord3(result?.finalBranchConvergenceState) ? { finalBranchConvergenceState: readRecord3(payload.finalBranchConvergenceState) ?? readRecord3(result?.finalBranchConvergenceState) } : {},
36574
+ ...readRecord3(payload.refineJob) ? { refineJob: readRecord3(payload.refineJob) } : {}
36321
36575
  };
36322
36576
  } else {
36323
- const envelope = readRecord2(payload.evidence);
36577
+ const envelope = readRecord3(payload.evidence);
36324
36578
  evidence = {
36325
36579
  available: true,
36326
36580
  kind: entry.kind,
36327
36581
  source: "task_completion",
36328
36582
  timestamp: entry.timestamp,
36329
- ...readString4(payload.taskId) ? { taskId: readString4(payload.taskId) } : {},
36583
+ ...readString5(payload.taskId) ? { taskId: readString5(payload.taskId) } : {},
36330
36584
  ...entry.sessionId ? { sessionId: entry.sessionId } : {},
36331
36585
  bootstrap: null,
36332
- validation: readRecord2(envelope?.validation),
36333
- checkpoint: readRecord2(envelope?.checkpoint),
36586
+ validation: readRecord3(envelope?.validation),
36587
+ checkpoint: readRecord3(envelope?.checkpoint),
36334
36588
  worker: readWorkerArtifact(envelope?.workerResult ?? payload.workerResult)
36335
36589
  };
36336
36590
  }
36337
36591
  }
36338
36592
  if (!transcriptHandle) {
36339
- const envelope = readRecord2(payload.evidence);
36340
- transcriptHandle = readRecord2(envelope?.transcriptHandle);
36593
+ const envelope = readRecord3(payload.evidence);
36594
+ transcriptHandle = readRecord3(envelope?.transcriptHandle);
36341
36595
  }
36342
36596
  if (evidence.available && transcriptHandle) break;
36343
36597
  }
@@ -36347,11 +36601,11 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36347
36601
  for (let i = ledgerEntries.length - 1; i >= 0; i--) {
36348
36602
  const entry = ledgerEntries[i];
36349
36603
  if (entry.nodeId !== nodeId || !isTerminalLedgerKind(entry.kind)) continue;
36350
- const payload = readRecord2(entry.payload) ?? {};
36604
+ const payload = readRecord3(entry.payload) ?? {};
36351
36605
  if (payload.source !== "refine_mesh_node_async_job") continue;
36352
- const result = readRecord2(payload.result);
36353
- const finalState = readRecord2(payload.finalBranchConvergenceState) ?? readRecord2(result?.finalBranchConvergenceState);
36354
- return readString4(finalState?.status) === "blocked_review" || readString4(result?.code) === "blocked_review";
36606
+ const result = readRecord3(payload.result);
36607
+ const finalState = readRecord3(payload.finalBranchConvergenceState) ?? readRecord3(result?.finalBranchConvergenceState);
36608
+ return readString5(finalState?.status) === "blocked_review" || readString5(result?.code) === "blocked_review";
36355
36609
  }
36356
36610
  return false;
36357
36611
  }
@@ -36360,7 +36614,7 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36360
36614
  const excludedRemoteNodeIds = [];
36361
36615
  const refineJobs = buildMeshAsyncRefineJobs({ ledgerEntries: args.ledgerEntries });
36362
36616
  for (const node of args.nodes) {
36363
- const nodeId = readString4(node.nodeId) ?? readString4(node.id);
36617
+ const nodeId = readString5(node.nodeId) ?? readString5(node.id);
36364
36618
  if (!nodeId) continue;
36365
36619
  if (!isLocalNodeStatus(node)) {
36366
36620
  excludedRemoteNodeIds.push(nodeId);
@@ -36382,8 +36636,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
36382
36636
  ) ?? null;
36383
36637
  items.push({
36384
36638
  nodeId,
36385
- workspace: readString4(node.workspace),
36386
- branch: convergence.branch ?? readString4(node.worktreeBranch),
36639
+ workspace: readString5(node.workspace),
36640
+ branch: convergence.branch ?? readString5(node.worktreeBranch),
36387
36641
  defaultBranch: convergence.defaultBranch,
36388
36642
  isLocalWorktree: node.isLocalWorktree === true,
36389
36643
  reviewReason,
@@ -37599,249 +37853,6 @@ ${rendered}`, "utf-8");
37599
37853
  STATUS_OPTIONS = { refreshUpstream: true, includeSubmodules: true, timeoutMs: 15e3 };
37600
37854
  }
37601
37855
  });
37602
- function readRecord3(value) {
37603
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
37604
- }
37605
- function readString5(...values) {
37606
- for (const value of values) {
37607
- if (typeof value !== "string") continue;
37608
- const trimmed = value.trim();
37609
- if (trimmed) return trimmed;
37610
- }
37611
- return void 0;
37612
- }
37613
- function readNumber(...values) {
37614
- for (const value of values) {
37615
- if (typeof value === "number" && Number.isFinite(value)) return value;
37616
- }
37617
- return void 0;
37618
- }
37619
- function readBoolean(...values) {
37620
- for (const value of values) {
37621
- if (typeof value === "boolean") return value;
37622
- }
37623
- return void 0;
37624
- }
37625
- function joinRepoPath(root, relativePath) {
37626
- const normalizedRoot = typeof root === "string" ? root.trim().replace(/[\\/]+$/, "") : "";
37627
- const normalizedPath = typeof relativePath === "string" ? relativePath.trim() : "";
37628
- if (!normalizedPath) return void 0;
37629
- if (/^(?:[A-Za-z]:[\\/]|\/)/.test(normalizedPath)) return normalizedPath;
37630
- if (!normalizedRoot) return void 0;
37631
- return `${normalizedRoot}/${normalizedPath.replace(/^[\\/]+/, "")}`;
37632
- }
37633
- function scoreGitUpstreamFreshness(status) {
37634
- switch (status) {
37635
- case "fresh":
37636
- return 30;
37637
- case "no_upstream":
37638
- return 4;
37639
- case "unchecked":
37640
- case void 0:
37641
- return 0;
37642
- case "stale":
37643
- return -10;
37644
- case "unavailable":
37645
- return -15;
37646
- default:
37647
- return 0;
37648
- }
37649
- }
37650
- function readGitSubmodules(value, parentRepoRoot) {
37651
- if (!Array.isArray(value)) return void 0;
37652
- const submodules = value.map((entry) => {
37653
- const submodule = readRecord3(entry);
37654
- const path422 = readString5(submodule.path);
37655
- const commit = readString5(submodule.commit);
37656
- const repoPath = readString5(submodule.repoPath, submodule.repo_root) ?? joinRepoPath(parentRepoRoot, path422);
37657
- if (!path422 || !commit) return null;
37658
- const result = {
37659
- path: path422,
37660
- commit,
37661
- dirty: readBoolean(submodule.dirty) ?? false,
37662
- outOfSync: readBoolean(submodule.outOfSync, submodule.out_of_sync) ?? false,
37663
- lastCheckedAt: readNumber(submodule.lastCheckedAt, submodule.last_checked_at) ?? Date.now()
37664
- };
37665
- if (repoPath) result.repoPath = repoPath;
37666
- const error48 = readString5(submodule.error);
37667
- if (error48) result.error = error48;
37668
- return result;
37669
- }).filter((entry) => entry !== null);
37670
- return submodules.length > 0 ? submodules : void 0;
37671
- }
37672
- function hasGitStatusEvidence(status) {
37673
- return readBoolean(status.isGitRepo) !== void 0 || Boolean(readString5(status.branch, status.upstream, status.upstreamStatus, status.upstream_status, status.headCommit)) || Boolean(readString5(status.repoRoot, status.repo_root, status.workspace)) || readNumber(
37674
- status.ahead,
37675
- status.behind,
37676
- status.staged,
37677
- status.modified,
37678
- status.untracked,
37679
- status.deleted,
37680
- status.renamed,
37681
- status.lastCheckedAt,
37682
- status.last_checked_at
37683
- ) !== void 0 || Array.isArray(status.submodules) && status.submodules.length > 0;
37684
- }
37685
- function normalizeGitStatus(status, node, options) {
37686
- const explicitIsGitRepo = readBoolean(status.isGitRepo);
37687
- if (!Object.keys(status).length || !hasGitStatusEvidence(status)) return void 0;
37688
- const isGitRepo = explicitIsGitRepo ?? true;
37689
- const conflictFiles = Array.isArray(status.conflictFiles) ? status.conflictFiles.filter((entry) => typeof entry === "string") : [];
37690
- const conflictCount = readNumber(status.conflicts) ?? conflictFiles.length;
37691
- const hasConflicts = readBoolean(status.hasConflicts) ?? conflictCount > 0;
37692
- const repoRoot = readString5(status.repoRoot, status.repo_root, node.repoRoot, node.repo_root, status.workspace, node.workspace) || void 0;
37693
- const submodules = readGitSubmodules(status.submodules, repoRoot);
37694
- const upstreamStatus = readString5(status.upstreamStatus, status.upstream_status);
37695
- const upstreamFetchedAt = readNumber(status.upstreamFetchedAt, status.upstream_fetched_at);
37696
- const upstreamFetchError = readString5(status.upstreamFetchError, status.upstream_fetch_error);
37697
- const error48 = readString5(status.error);
37698
- const staged = readNumber(status.staged) ?? 0;
37699
- const modified = readNumber(status.modified) ?? 0;
37700
- const untracked = readNumber(status.untracked) ?? 0;
37701
- const deleted = readNumber(status.deleted) ?? 0;
37702
- const renamed = readNumber(status.renamed) ?? 0;
37703
- return {
37704
- workspace: readString5(status.workspace, node.workspace) || "",
37705
- repoRoot: repoRoot ?? null,
37706
- isGitRepo,
37707
- branch: readString5(status.branch) ?? null,
37708
- headCommit: readString5(status.headCommit) ?? null,
37709
- headMessage: readString5(status.headMessage) ?? null,
37710
- upstream: readString5(status.upstream) ?? null,
37711
- upstreamStatus: upstreamStatus ?? "unchecked",
37712
- ...upstreamFetchedAt !== void 0 ? { upstreamFetchedAt } : {},
37713
- ...upstreamFetchError ? { upstreamFetchError } : {},
37714
- ahead: readNumber(status.ahead) ?? 0,
37715
- behind: readNumber(status.behind) ?? 0,
37716
- staged,
37717
- modified,
37718
- untracked,
37719
- deleted,
37720
- renamed,
37721
- dirty: readBoolean(status.dirty, status.isDirty, status.is_dirty) ?? (staged + modified + untracked + deleted + renamed > 0 || hasConflicts),
37722
- hasConflicts,
37723
- conflictFiles,
37724
- stashCount: readNumber(status.stashCount, status.stash_count) ?? 0,
37725
- lastCheckedAt: options?.lastCheckedAt ?? readNumber(status.lastCheckedAt, status.last_checked_at) ?? Date.now(),
37726
- ...submodules ? { submodules } : {},
37727
- ...error48 ? { error: error48 } : {}
37728
- };
37729
- }
37730
- function scoreGitStatusCandidate(git) {
37731
- if (!git) return Number.NEGATIVE_INFINITY;
37732
- let score = 0;
37733
- if (git.isGitRepo === true) score += 50;
37734
- if (git.isGitRepo === false) score -= 10;
37735
- if (git.branch) score += 20;
37736
- if (git.headCommit) score += 20;
37737
- if (git.upstream) score += 10;
37738
- score += scoreGitUpstreamFreshness(git.upstreamStatus);
37739
- if (typeof git.ahead === "number") score += 2;
37740
- if (typeof git.behind === "number") score += 2;
37741
- if (Array.isArray(git.submodules) && git.submodules.length > 0) score += 4 + git.submodules.length;
37742
- if (git.error) score -= 20;
37743
- return score;
37744
- }
37745
- function pickBestTransitGitStatus(node, options) {
37746
- const rawGit = readRecord3(node.lastGit ?? node.last_git);
37747
- const gitResult = readRecord3(rawGit.result);
37748
- const directStatus = readRecord3(rawGit.status);
37749
- const nestedStatus = readRecord3(gitResult.status);
37750
- const rawProbe = readRecord3(node.lastProbe ?? node.last_probe);
37751
- const probeGit = readRecord3(rawProbe.git);
37752
- const probeGitResult = readRecord3(probeGit.result);
37753
- const probeDirectStatus = readRecord3(probeGit.status);
37754
- const probeNestedStatus = readRecord3(probeGitResult.status);
37755
- const lastCheckedAt = options?.lastCheckedAt;
37756
- let best = null;
37757
- for (const status of [directStatus, nestedStatus, probeDirectStatus, probeNestedStatus]) {
37758
- const normalized = normalizeGitStatus(status, node, { lastCheckedAt: lastCheckedAt ?? Date.now() });
37759
- if (!normalized) continue;
37760
- const score = scoreGitStatusCandidate(normalized);
37761
- if (!best || score > best.score) best = { git: normalized, score };
37762
- }
37763
- return best?.git;
37764
- }
37765
- function normalizeMeshNodeId(node) {
37766
- const record2 = node && typeof node === "object" ? node : {};
37767
- return readString5(record2.id, record2.nodeId, record2.node_id);
37768
- }
37769
- function meshNodeIdMatches(node, candidateId) {
37770
- if (!candidateId) return false;
37771
- const trimmed = candidateId.trim();
37772
- if (!trimmed) return false;
37773
- return normalizeMeshNodeId(node) === trimmed;
37774
- }
37775
- function machineCoreFromDaemonId(id) {
37776
- const trimmed = readString5(id);
37777
- if (!trimmed) return void 0;
37778
- for (const prefix of DAEMON_ID_PREFIXES) {
37779
- if (trimmed.startsWith(prefix)) {
37780
- const core = trimmed.slice(prefix.length).trim();
37781
- return core || void 0;
37782
- }
37783
- }
37784
- return trimmed;
37785
- }
37786
- function expandDaemonIdForms(ids) {
37787
- const list = Array.isArray(ids) ? ids : ids != null ? [ids] : [];
37788
- const out = [];
37789
- const seen = /* @__PURE__ */ new Set();
37790
- const add = (value) => {
37791
- if (!value || seen.has(value)) return;
37792
- seen.add(value);
37793
- out.push(value);
37794
- };
37795
- for (const raw of list) add(readString5(raw));
37796
- for (const raw of list) {
37797
- const core = machineCoreFromDaemonId(readString5(raw));
37798
- if (!core || !core.startsWith("mach_")) continue;
37799
- add(core);
37800
- for (const prefix of DAEMON_ID_PREFIXES) add(`${prefix}${core}`);
37801
- }
37802
- return out;
37803
- }
37804
- function summarizeGitShape(status) {
37805
- const record2 = readRecord3(status);
37806
- if (!Object.keys(record2).length) return null;
37807
- const submodules = Array.isArray(record2.submodules) ? record2.submodules.map((entry) => {
37808
- const sub = readRecord3(entry);
37809
- return {
37810
- path: readString5(sub.path) ?? null,
37811
- commit: readString5(sub.commit)?.slice(0, 12) ?? null,
37812
- dirty: readBoolean(sub.dirty) ?? false,
37813
- outOfSync: readBoolean(sub.outOfSync, sub.out_of_sync) ?? false
37814
- };
37815
- }) : [];
37816
- return {
37817
- isGitRepo: readBoolean(record2.isGitRepo),
37818
- workspace: readString5(record2.workspace) ?? null,
37819
- repoRoot: readString5(record2.repoRoot, record2.repo_root) ?? null,
37820
- branch: readString5(record2.branch) ?? null,
37821
- upstream: readString5(record2.upstream) ?? null,
37822
- upstreamStatus: readString5(record2.upstreamStatus, record2.upstream_status) ?? null,
37823
- headCommit: readString5(record2.headCommit, record2.head_commit)?.slice(0, 12) ?? null,
37824
- ahead: readNumber(record2.ahead) ?? null,
37825
- behind: readNumber(record2.behind) ?? null,
37826
- dirtyCounts: {
37827
- staged: readNumber(record2.staged) ?? 0,
37828
- modified: readNumber(record2.modified) ?? 0,
37829
- untracked: readNumber(record2.untracked) ?? 0,
37830
- deleted: readNumber(record2.deleted) ?? 0,
37831
- renamed: readNumber(record2.renamed) ?? 0
37832
- },
37833
- lastCheckedAt: readNumber(record2.lastCheckedAt, record2.last_checked_at) ?? null,
37834
- submoduleCount: submodules.length,
37835
- submodules
37836
- };
37837
- }
37838
- var DAEMON_ID_PREFIXES;
37839
- var init_dist = __esm2({
37840
- "../mesh-shared/dist/index.mjs"() {
37841
- "use strict";
37842
- DAEMON_ID_PREFIXES = ["daemon_", "standalone_"];
37843
- }
37844
- });
37845
37856
  function readString6(value) {
37846
37857
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
37847
37858
  }
@@ -50148,6 +50159,7 @@ ${lastSnapshot}`;
50148
50159
  createNativeHistoryDispatcher: () => createNativeHistoryDispatcher,
50149
50160
  createSessionDelivery: () => createSessionDelivery,
50150
50161
  createWorktree: () => createWorktree,
50162
+ daemonIdsEquivalent: () => daemonIdsEquivalent,
50151
50163
  deleteDirectDispatchesByTaskId: () => deleteDirectDispatchesByTaskId,
50152
50164
  deleteMesh: () => deleteMesh,
50153
50165
  deriveMeshReviewInboxItems: () => deriveMeshReviewInboxItems,
@@ -50161,6 +50173,7 @@ ${lastSnapshot}`;
50161
50173
  ensureSessionHostReady: () => ensureSessionHostReady2,
50162
50174
  evaluateFsm: () => evaluateFsm,
50163
50175
  execNpmCommandSync: () => execNpmCommandSync,
50176
+ expandDaemonIdForms: () => expandDaemonIdForms,
50164
50177
  fastForwardMeshNode: () => fastForwardMeshNode,
50165
50178
  filterActivityChatMessages: () => filterActivityChatMessages,
50166
50179
  filterChatMessagesByVisibility: () => filterChatMessagesByVisibility,
@@ -50251,6 +50264,7 @@ ${lastSnapshot}`;
50251
50264
  loadMeshWorktreeBootstrapConfig: () => loadMeshWorktreeBootstrapConfig,
50252
50265
  loadState: () => loadState,
50253
50266
  logCommand: () => logCommand,
50267
+ machineCoreFromDaemonId: () => machineCoreFromDaemonId,
50254
50268
  markSessionDeliveriesTerminal: () => markSessionDeliveriesTerminal,
50255
50269
  markSetupComplete: () => markSetupComplete,
50256
50270
  markStaleDirectDispatches: () => markStaleDirectDispatches,
@@ -51585,6 +51599,7 @@ ${lastSnapshot}`;
51585
51599
  })).sort((a, b) => b.lastUsedAt - a.lastUsedAt);
51586
51600
  }
51587
51601
  init_mesh_config();
51602
+ init_dist();
51588
51603
  init_coordinator_prompt();
51589
51604
  init_mesh_missions();
51590
51605
  init_mesh_task_stats();
@@ -57144,6 +57159,40 @@ ${effect.notification.body || ""}`.trim();
57144
57159
  }
57145
57160
  return fn() || null;
57146
57161
  }
57162
+ var AUTO_APPROVE_MANUAL_ATTENDANCE_SUPPRESS_MS = 6e4;
57163
+ var ManualAttendanceTracker = class {
57164
+ constructor(suppressMs = AUTO_APPROVE_MANUAL_ATTENDANCE_SUPPRESS_MS) {
57165
+ this.suppressMs = suppressMs;
57166
+ }
57167
+ lastInteractionAt = 0;
57168
+ /** Record that a human just drove this session by hand. */
57169
+ note(now = Date.now()) {
57170
+ this.lastInteractionAt = now;
57171
+ }
57172
+ /** True while a manual interaction is recent enough to suppress auto-approve. */
57173
+ isAttended(now = Date.now()) {
57174
+ return this.lastInteractionAt > 0 && now - this.lastInteractionAt < this.suppressMs;
57175
+ }
57176
+ /**
57177
+ * Milliseconds remaining in the current suppression window, or 0 when not
57178
+ * attended. Used to re-arm a re-check timer so auto-approve fires the moment
57179
+ * the window lapses even if the PTY/agent has since gone silent.
57180
+ */
57181
+ remainingMs(now = Date.now()) {
57182
+ if (this.lastInteractionAt <= 0) return 0;
57183
+ return Math.max(0, this.suppressMs - (now - this.lastInteractionAt));
57184
+ }
57185
+ };
57186
+ var MANUAL_ATTENDANCE_COMMANDS = /* @__PURE__ */ new Set([
57187
+ "select_session",
57188
+ "open_panel",
57189
+ "invoke_provider_script",
57190
+ "set_mode",
57191
+ "change_model",
57192
+ "set_thought_level",
57193
+ "resolve_action",
57194
+ "pty_input"
57195
+ ]);
57147
57196
  var fs7 = __toESM2(require("fs"));
57148
57197
  var os10 = __toESM2(require("os"));
57149
57198
  var path16 = __toESM2(require("path"));
@@ -61458,11 +61507,38 @@ ${effect.notification.body || ""}`.trim();
61458
61507
  setAgentStreamManager(manager) {
61459
61508
  this._agentStream = manager;
61460
61509
  }
61510
+ /**
61511
+ * When a command in the manual-attendance set arrives for a session this
61512
+ * daemon hosts, stamp the live instance so auto-approve holds while the user
61513
+ * drives the session by hand. Provider-common: the signal is the command
61514
+ * (foreground select_session / open_panel, controlbar invoke_provider_script
61515
+ * / set_mode / change_model / set_thought_level, manual resolve_action,
61516
+ * pty_input), never any CLI-specific modal text — so it works identically for
61517
+ * every CLI/ACP provider. send_chat is deliberately excluded because a
61518
+ * coordinator delegating a task to a worker also uses send_chat; counting it
61519
+ * would wrongly suppress the worker's delegated auto-approve. For a remote
61520
+ * mesh worker session the controlbar commands are forwarded to the owning
61521
+ * worker daemon, which runs this same hook there, so attendance is recorded
61522
+ * on the daemon that actually hosts the instance.
61523
+ */
61524
+ noteManualAttendanceIfApplicable(cmd, args) {
61525
+ if (!MANUAL_ATTENDANCE_COMMANDS.has(cmd)) return;
61526
+ const sessionId = this._currentRoute.session?.sessionId || (typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "");
61527
+ if (!sessionId) return;
61528
+ const session = this._ctx.sessionRegistry?.get(sessionId);
61529
+ const instanceKey = session?.adapterKey || session?.instanceKey || sessionId;
61530
+ const instance = this._ctx.instanceManager?.getInstance(instanceKey);
61531
+ try {
61532
+ instance?.noteManualInteraction?.();
61533
+ } catch {
61534
+ }
61535
+ }
61461
61536
  // ─── Command Dispatcher ──────────────────────────
61462
61537
  async handle(cmd, args) {
61463
61538
  this._currentRoute = this.resolveRoute(args);
61464
61539
  const startedAt = Date.now();
61465
61540
  this.logCommandStart(cmd, args);
61541
+ this.noteManualAttendanceIfApplicable(cmd, args);
61466
61542
  let result;
61467
61543
  if (isGitCommandName(cmd)) {
61468
61544
  result = await handleGitCommand(cmd, args, this._ctx.gitCommandServices);
@@ -65384,6 +65460,11 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65384
65460
  // a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
65385
65461
  // brief generating flip does not immediately wipe the settle clock.
65386
65462
  autoApproveInactiveSince = 0;
65463
+ // Provider-common manual-attendance signal: while a human is actively driving
65464
+ // this session from the dashboard, auto-approve holds so they can take manual
65465
+ // control. Background mesh workers are never attended → delegated auto-approve
65466
+ // is unaffected.
65467
+ manualAttendance = new ManualAttendanceTracker();
65387
65468
  controlValues = {};
65388
65469
  summaryMetadata = void 0;
65389
65470
  appliedEffectKeys = /* @__PURE__ */ new Set();
@@ -65659,7 +65740,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65659
65740
  }
65660
65741
  getHotChatSessionState() {
65661
65742
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
65662
- const autoApproveActive = adapterStatus.status === "waiting_approval" && this.shouldAutoApprove();
65743
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status);
65663
65744
  const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === "idle";
65664
65745
  const visibleStatus = autoApproveActive || autoApproveHoldIdle ? "generating" : adapterStatus.status;
65665
65746
  const runtime = this.adapter.getRuntimeMetadata();
@@ -65674,7 +65755,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65674
65755
  }
65675
65756
  getSessionModalState(sessionId) {
65676
65757
  const adapterStatus = this.adapter.getStatus({ allowParse: true });
65677
- const autoApproveActive = adapterStatus.status === "waiting_approval" && this.shouldAutoApprove();
65758
+ const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status);
65678
65759
  const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === "idle";
65679
65760
  const visibleStatus = autoApproveActive || autoApproveHoldIdle ? "generating" : adapterStatus.status;
65680
65761
  const dirName = workingDirBasename(this.workingDir);
@@ -65755,7 +65836,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
65755
65836
  } catch {
65756
65837
  return null;
65757
65838
  }
65758
- if (adapterStatus.status === "waiting_approval" && !this.shouldAutoApprove()) {
65839
+ if (adapterStatus.status === "waiting_approval" && !this.autoApproveEffectivelyActive(adapterStatus.status)) {
65759
65840
  return "waiting_approval";
65760
65841
  }
65761
65842
  return null;
@@ -66201,6 +66282,18 @@ ${formatManifestValidationIssues2(validation.issues)}`,
66201
66282
  this.lastApprovalEventFingerprint = "";
66202
66283
  }
66203
66284
  maybeAutoApproveStatus(adapterStatus, now = Date.now()) {
66285
+ if (adapterStatus?.status === "waiting_approval" && this.shouldAutoApprove() && this.manualAttendance.isAttended(now)) {
66286
+ this.lastAutoApprovalSignature = "";
66287
+ this.pendingAutoApprovalSignature = "";
66288
+ this.pendingAutoApprovalSince = 0;
66289
+ this.autoApproveInactiveSince = 0;
66290
+ if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
66291
+ this.autoApproveSettleTimer = setTimeout(() => {
66292
+ this.autoApproveSettleTimer = null;
66293
+ this.recheckAutoApproveSettled();
66294
+ }, this.manualAttendance.remainingMs(now) + 20);
66295
+ return false;
66296
+ }
66204
66297
  const autoApproveActive = adapterStatus?.status === "waiting_approval" && this.shouldAutoApprove();
66205
66298
  if (!autoApproveActive) {
66206
66299
  this.lastAutoApprovalSignature = "";
@@ -66666,6 +66759,21 @@ ${effect.notification.body || ""}`.trim();
66666
66759
  }
66667
66760
  return false;
66668
66761
  }
66762
+ /** @see ProviderInstance.noteManualInteraction */
66763
+ noteManualInteraction(now = Date.now()) {
66764
+ this.manualAttendance.note(now);
66765
+ }
66766
+ /**
66767
+ * Whether auto-approve should be treated as active *right now* for display
66768
+ * and firing decisions: the configured intent AND the user is not currently
66769
+ * attending this session by hand. When a human is attending, auto-approve is
66770
+ * held so the modal stays visible and they can drive it via the controlbar.
66771
+ * Provider-agnostic — the attendance signal is the command set, never any
66772
+ * CLI-specific modal text.
66773
+ */
66774
+ autoApproveEffectivelyActive(status, now = Date.now()) {
66775
+ return status === "waiting_approval" && this.shouldAutoApprove() && !this.manualAttendance.isAttended(now);
66776
+ }
66669
66777
  recordAutoApproval(modalMessage, buttonLabel, now = Date.now()) {
66670
66778
  this.appendRuntimeSystemMessage(
66671
66779
  formatAutoApprovalMessage(modalMessage, buttonLabel),
@@ -67609,7 +67717,7 @@ ${effect.notification.body || ""}`.trim();
67609
67717
  input: tc.rawInput ? typeof tc.rawInput === "string" ? tc.rawInput : JSON.stringify(tc.rawInput) : void 0
67610
67718
  });
67611
67719
  }
67612
- if (this.settings.autoApprove !== false) {
67720
+ if (this.settings.autoApprove !== false && !this.manualAttendance.isAttended()) {
67613
67721
  const toolTitle = tc.title || tc.toolCallId || "tool call";
67614
67722
  this.log.info(`[${this.type}] Auto-approving: ${toolTitle}`);
67615
67723
  this.appendSystemMessage(`Auto-approved: ${toolTitle}`);
@@ -67840,6 +67948,15 @@ ${effect.notification.body || ""}`.trim();
67840
67948
  this.detectStatusTransition();
67841
67949
  }
67842
67950
  permissionResolvers = [];
67951
+ // Provider-common manual-attendance signal: while a human is actively driving
67952
+ // this session from the dashboard, auto-approve holds so they can decide on
67953
+ // the permission request themselves. Background workers are never attended →
67954
+ // delegated auto-approve is unaffected.
67955
+ manualAttendance = new ManualAttendanceTracker();
67956
+ /** @see ProviderInstance.noteManualInteraction */
67957
+ noteManualInteraction(now = Date.now()) {
67958
+ this.manualAttendance.note(now);
67959
+ }
67843
67960
  async resolvePermission(approved) {
67844
67961
  const resolver = this.permissionResolvers.shift();
67845
67962
  if (resolver) {
@@ -68991,6 +69108,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
68991
69108
  );
68992
69109
  continue;
68993
69110
  }
69111
+ const restoredSettings = { ...this.providerLoader.getSettings(normalizedType) };
69112
+ const coordinatorEntry = getCoordinatorForSession(record2.runtimeId);
69113
+ if (coordinatorEntry?.meshId) {
69114
+ restoredSettings.meshCoordinatorFor = coordinatorEntry.meshId;
69115
+ }
68994
69116
  try {
68995
69117
  await this.registerCliInstance(
68996
69118
  record2.runtimeId,
@@ -68999,7 +69121,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
68999
69121
  record2.workspace,
69000
69122
  record2.cliArgs,
69001
69123
  resolvedProvider,
69002
- {},
69124
+ restoredSettings,
69003
69125
  true,
69004
69126
  {
69005
69127
  providerSessionId: sessionBinding.providerSessionId,
@@ -69040,9 +69162,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
69040
69162
  }
69041
69163
  }
69042
69164
  }
69043
- for (const [k, a] of this.adapters) {
69044
- if (a.cliType === agentType) {
69045
- return { adapter: a, key: k };
69165
+ if (!opts?.instanceKey) {
69166
+ for (const [k, a] of this.adapters) {
69167
+ if (a.cliType === agentType) {
69168
+ return { adapter: a, key: k };
69169
+ }
69046
69170
  }
69047
69171
  }
69048
69172
  return null;
@@ -76347,7 +76471,14 @@ ${mergeTreeErr?.stderr || ""}`;
76347
76471
  "resolve_action",
76348
76472
  "set_mode",
76349
76473
  "change_model",
76350
- "set_thought_level"
76474
+ "set_thought_level",
76475
+ // agent_command (send_chat / clear_history / stop) is session-scoped too: a command
76476
+ // explicitly naming a targetSessionId MUST reach that session wherever it lives, never a
76477
+ // different local session. Without forwarding, a misrouted/relayed send_chat for a REMOTE
76478
+ // worker session that reaches the wrong daemon used to fuzzy-inject the task body into that
76479
+ // daemon's own CLI session (TASKECHO coordinator self-echo). Forwarding to the owning daemon
76480
+ // delivers it to the real worker instead. (findAdapter is also fail-closed as the backstop.)
76481
+ "agent_command"
76351
76482
  ]);
76352
76483
  var READ_DEBUG_ENABLED2 = process.argv.includes("--dev") || process.env.ADHDEV_READ_DEBUG === "1";
76353
76484
  function normalizeCommandSource(source) {
@@ -76700,7 +76831,7 @@ ${mergeTreeErr?.stderr || ""}`;
76700
76831
  if (!collectMeshNodeHostedSessionIds(node).has(trimmed)) continue;
76701
76832
  const nodeDaemonId = readMeshNodeDaemonId(readObjectRecord(node));
76702
76833
  if (!nodeDaemonId) continue;
76703
- if (selfDaemonId && nodeDaemonId === selfDaemonId) return void 0;
76834
+ if (selfDaemonId && daemonIdsEquivalent(nodeDaemonId, selfDaemonId)) return void 0;
76704
76835
  return nodeDaemonId;
76705
76836
  }
76706
76837
  return void 0;
@@ -76855,6 +76986,38 @@ ${mergeTreeErr?.stderr || ""}`;
76855
76986
  if (record2?.meta?.meshNodeId === nodeId) return true;
76856
76987
  return false;
76857
76988
  }
76989
+ /**
76990
+ * Best-effort recursive removal of a managed worktree directory.
76991
+ *
76992
+ * The git-registry de-registration is the safety-critical step of worktree
76993
+ * teardown; a leftover directory must never gate dropping the node from the
76994
+ * mesh. On Windows, `fs.rmSync` can throw EINVAL/EPERM/EBUSY on submodule
76995
+ * gitlink (`.git`) files, long paths, junctions, or while a just-stopped
76996
+ * delegate session is still releasing a handle/cwd on the directory. This
76997
+ * helper absorbs those errors (never throws), with bounded retries + backoff
76998
+ * to give handles time to release, and reports whether residue remains.
76999
+ */
77000
+ async bestEffortRemoveWorktreeDir(dir) {
77001
+ if (!dir || !fs26.existsSync(dir)) return { removed: true, residue: false };
77002
+ const sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
77003
+ const ABSORB = /* @__PURE__ */ new Set(["EINVAL", "EPERM", "EBUSY", "ENOTEMPTY", "EACCES", "EMFILE", "ENFILE"]);
77004
+ let lastErr;
77005
+ for (let attempt = 0; attempt < 4; attempt++) {
77006
+ try {
77007
+ fs26.rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
77008
+ if (!fs26.existsSync(dir)) return { removed: true, residue: false };
77009
+ lastErr = new Error("directory still present after rmSync");
77010
+ } catch (e) {
77011
+ lastErr = e;
77012
+ const code = typeof e?.code === "string" ? e.code : "";
77013
+ if (code && !ABSORB.has(code)) {
77014
+ break;
77015
+ }
77016
+ }
77017
+ await sleep3(150 * (attempt + 1));
77018
+ }
77019
+ return fs26.existsSync(dir) ? { removed: false, residue: true, error: String(lastErr?.message || lastErr || "unknown rm error") } : { removed: true, residue: false };
77020
+ }
76858
77021
  async cleanupLocalWorktreeNode(args) {
76859
77022
  const workspace = typeof args.node?.workspace === "string" ? args.node.workspace.trim() : "";
76860
77023
  if (!workspace) {
@@ -76909,11 +77072,31 @@ ${mergeTreeErr?.stderr || ""}`;
76909
77072
  const entries = await listWorktrees2(repoRoot);
76910
77073
  const managedEntry = entries.find((entry) => normalizePath(entry.path) === actualPath);
76911
77074
  if (!managedEntry) {
77075
+ try {
77076
+ const { execFile: execFile5 } = await import("child_process");
77077
+ const { promisify: promisify8 } = await import("util");
77078
+ const execFileAsync4 = promisify8(execFile5);
77079
+ await execFileAsync4("git", ["worktree", "prune"], {
77080
+ cwd: repoRoot,
77081
+ encoding: "utf8",
77082
+ timeout: 3e4,
77083
+ maxBuffer: 4 * 1024 * 1024,
77084
+ windowsHide: true
77085
+ });
77086
+ } catch {
77087
+ }
77088
+ const rm = await this.bestEffortRemoveWorktreeDir(workspace);
76912
77089
  return {
76913
- success: false,
76914
- code: "mesh_worktree_cleanup_not_registered",
76915
- error: `Refusing to remove '${workspace}' because it is not registered in git worktree list for '${repoRoot}'`,
76916
- recoveryHint: "Inspect git worktree list --porcelain from the source repo. If the path was already removed, prune git worktrees before retrying."
77090
+ success: true,
77091
+ removedPath: workspace,
77092
+ repoRoot,
77093
+ reason: "worktree_unregistered_residue_recovered",
77094
+ recovered: true,
77095
+ ...rm.residue ? {
77096
+ residue: true,
77097
+ residueWarning: `Worktree was already de-registered from git but the directory could not be fully removed (leftover residue at '${workspace}'): ${rm.error || "unknown error"}. The node will be dropped from the mesh; remove the directory manually if needed.`,
77098
+ residueError: rm.error
77099
+ } : {}
76917
77100
  };
76918
77101
  }
76919
77102
  if (managedEntry.branch && managedEntry.branch !== args.node.worktreeBranch) {
@@ -76976,8 +77159,8 @@ ${mergeTreeErr?.stderr || ""}`;
76976
77159
  convergence: forceFallbackConvergence
76977
77160
  };
76978
77161
  } catch (deinitError) {
77162
+ const rm = await this.bestEffortRemoveWorktreeDir(workspace);
76979
77163
  try {
76980
- fs26.rmSync(workspace, { recursive: true, force: true });
76981
77164
  await execFileAsync4("git", ["worktree", "prune"], {
76982
77165
  cwd: repoRoot,
76983
77166
  encoding: "utf8",
@@ -76985,23 +77168,22 @@ ${mergeTreeErr?.stderr || ""}`;
76985
77168
  maxBuffer: GIT_MAX_BUFFER_CLEANUP,
76986
77169
  windowsHide: true
76987
77170
  });
76988
- return {
76989
- success: true,
76990
- removedPath: workspace,
76991
- repoRoot,
76992
- fallback: "fs_rm_worktree_prune",
76993
- forced: true,
76994
- reason: "working_trees_containing_submodules",
76995
- convergence: forceFallbackConvergence
76996
- };
76997
- } catch (rmError) {
76998
- return {
76999
- success: false,
77000
- code: "mesh_worktree_cleanup_failed",
77001
- error: `All removal fallbacks exhausted. deinit+remove: ${deinitError?.message || deinitError}; rmSync+prune: ${rmError?.message || rmError}`,
77002
- recoveryHint: "Manually remove the worktree directory and run git worktree prune from the source repo."
77003
- };
77171
+ } catch {
77004
77172
  }
77173
+ return {
77174
+ success: true,
77175
+ removedPath: workspace,
77176
+ repoRoot,
77177
+ fallback: "fs_rm_worktree_prune",
77178
+ forced: true,
77179
+ reason: "working_trees_containing_submodules",
77180
+ convergence: forceFallbackConvergence,
77181
+ ...rm.residue ? {
77182
+ residue: true,
77183
+ residueWarning: `Worktree was de-registered from git but the directory could not be fully removed (leftover residue at '${workspace}'): ${rm.error || "unknown error"}; deinit+remove first failed with: ${deinitError?.message || deinitError}. The node will be dropped from the mesh; remove the directory manually if needed.`,
77184
+ residueError: rm.error
77185
+ } : {}
77186
+ };
77005
77187
  }
77006
77188
  }
77007
77189
  return {
@@ -80400,7 +80582,14 @@ ${hintLines.join("\n")}` : "",
80400
80582
  } catch {
80401
80583
  }
80402
80584
  }
80403
- return { success: true, removed, ...sessionCleanup ? { sessionCleanup } : {}, ...worktreeCleanup ? { worktreeCleanup } : {} };
80585
+ const residueWarning = worktreeCleanup?.residue === true && typeof worktreeCleanup?.residueWarning === "string" ? worktreeCleanup.residueWarning : void 0;
80586
+ return {
80587
+ success: true,
80588
+ removed,
80589
+ ...residueWarning ? { residueWarning } : {},
80590
+ ...sessionCleanup ? { sessionCleanup } : {},
80591
+ ...worktreeCleanup ? { worktreeCleanup } : {}
80592
+ };
80404
80593
  } catch (e) {
80405
80594
  return { success: false, error: e.message };
80406
80595
  }