@adhdev/daemon-standalone 1.0.58-rc.14 → 1.0.58-rc.16

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
@@ -36882,10 +36882,10 @@ var require_dist3 = __commonJS({
36882
36882
  }
36883
36883
  function getDaemonBuildInfo() {
36884
36884
  if (cached2) return cached2;
36885
- const commit = readInjected(true ? "3f1bf15bd8ba7a0e9c7e1ff028dfc00efd1115f4" : void 0) ?? "unknown";
36886
- const commitShort = readInjected(true ? "3f1bf15b" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36887
- const version2 = readInjected(true ? "1.0.58-rc.14" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36888
- const builtAt = readInjected(true ? "2026-08-25T17:44:27.365Z" : void 0);
36885
+ const commit = readInjected(true ? "0ff2241634e4035f73e2d9a41eb69f223706ff3c" : void 0) ?? "unknown";
36886
+ const commitShort = readInjected(true ? "0ff22416" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36887
+ const version2 = readInjected(true ? "1.0.58-rc.16" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36888
+ const builtAt = readInjected(true ? "2026-08-26T06:35:36.671Z" : void 0);
36889
36889
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
36890
36890
  return cached2;
36891
36891
  }
@@ -38284,11 +38284,11 @@ var require_dist3 = __commonJS({
38284
38284
  const override = env2.ADHDEV_CONFIG_DIR;
38285
38285
  if (!override || !override.trim()) return false;
38286
38286
  const sibling = otherTrackConfigDir(env2, homeDir2);
38287
- const normalize5 = (p) => {
38287
+ const normalize6 = (p) => {
38288
38288
  const unified = p.trim().replace(/[\\/]+$/, "").replace(/\\/g, "/");
38289
38289
  return platform11 === "win32" ? unified.toLowerCase() : unified;
38290
38290
  };
38291
- return normalize5(override) === normalize5(sibling);
38291
+ return normalize6(override) === normalize6(sibling);
38292
38292
  }
38293
38293
  function configDirChannelMismatch(resolvedConfigDir, resolvedChannel, hasExplicitChannelSignal) {
38294
38294
  if (hasExplicitChannelSignal) return null;
@@ -46233,6 +46233,20 @@ Next step: ${nextStep}`;
46233
46233
  `[System] Refinery async job for ${args.nodeLabel} failed${details ? ` (${details})` : ""}${error48 ? `: ${error48}` : "."}`,
46234
46234
  nextStep ? `Next step: ${nextStep}` : "Review the terminal refine event/ledger before retrying."
46235
46235
  ];
46236
+ const batchResults = result?.batch === true && Array.isArray(result?.results) ? result.results : [];
46237
+ const failedNodes = batchResults.filter((entry) => entry && entry.convergence !== "merged_to_main" && entry.convergence !== "skipped_patch_equivalent");
46238
+ if (failedNodes.length > 0) {
46239
+ parts.push("Per-node failures:");
46240
+ for (const entry of failedNodes) {
46241
+ const nodeId = readNonEmptyString(entry.nodeId) || "(unknown node)";
46242
+ const nodeConvergence = readNonEmptyString(entry.convergence);
46243
+ const nodeCode = readNonEmptyString(entry.code);
46244
+ const nodeStage = readNonEmptyString(entry.stage);
46245
+ const nodeError = readNonEmptyString(entry.error);
46246
+ const codeStage = [nodeCode ? `code=${nodeCode}` : "", nodeStage ? `stage=${nodeStage}` : ""].filter(Boolean).join(", ");
46247
+ parts.push(`- ${nodeId}${nodeConvergence ? `: ${nodeConvergence}` : ""}${codeStage ? ` (${codeStage})` : ""}${nodeError ? ` \u2014 ${nodeError.length > 200 ? `${nodeError.slice(0, 200)}\u2026` : nodeError}` : ""}`);
46248
+ }
46249
+ }
46236
46250
  return parts.join("\n");
46237
46251
  }
46238
46252
  return "";
@@ -52084,6 +52098,15 @@ The instruction it carried was never delivered to anyone. If it still matters, r
52084
52098
  const reclaims = (entry.strandedReclaimCount || 0) + 1;
52085
52099
  const prevNode = entry.assignedNodeId;
52086
52100
  const prevSession = entry.assignedSessionId;
52101
+ const prevProvider = entry.assignedProviderType;
52102
+ entry.lastReclaim = {
52103
+ ...prevProvider ? { providerType: prevProvider } : {},
52104
+ ...prevNode ? { nodeId: prevNode } : {},
52105
+ ...prevSession ? { sessionId: prevSession } : {},
52106
+ reason,
52107
+ reclaimCount: reclaims,
52108
+ at: now
52109
+ };
52087
52110
  delete entry.assignedNodeId;
52088
52111
  delete entry.assignedSessionId;
52089
52112
  delete entry.assignedProviderType;
@@ -52116,9 +52139,15 @@ The instruction it carried was never delivered to anyone. If it still matters, r
52116
52139
  kind: "task_reclaimed",
52117
52140
  nodeId: prevNode,
52118
52141
  sessionId: prevSession,
52142
+ // REDRIVE-PROVIDER-FLIP (a): name the provider being torn down. This is the
52143
+ // "before" half of the flip; the "after" half is the redriveProvenance block
52144
+ // on the next task_dispatched, so the comparison no longer needs a manual
52145
+ // two-entry join.
52146
+ ...prevProvider ? { providerType: prevProvider } : {},
52119
52147
  payload: {
52120
52148
  taskId,
52121
52149
  reason,
52150
+ ...prevProvider ? { providerType: prevProvider } : {},
52122
52151
  ...typeof opts?.ageMs === "number" ? { ageMs: opts.ageMs } : {},
52123
52152
  reclaimCount: reclaims,
52124
52153
  outcome: entry.status
@@ -59154,7 +59183,11 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
59154
59183
  "p2p_dispatch_failed",
59155
59184
  "dispatch_failed",
59156
59185
  "dispatch_duplicate_rebound",
59157
- "queue_hold_hard_deadline"
59186
+ "queue_hold_hard_deadline",
59187
+ // REDRIVE-PROVIDER-FLIP (a): joinable by kind+taskId alongside the task's
59188
+ // task_dispatched/task_reclaimed rows — the whole point is to read a task's
59189
+ // redrive history without an O(n) payload scan.
59190
+ "redrive_provider_changed"
59158
59191
  ]);
59159
59192
  LEDGER_DIR_NAME = "mesh-ledger";
59160
59193
  MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
@@ -60646,7 +60679,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
60646
60679
  const remote = opts.remote?.trim() || "origin";
60647
60680
  const localTimeout = opts.timeoutMs ?? 1e4;
60648
60681
  const git3 = resolveWin32Executable("git");
60649
- const execFileAsync7 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
60682
+ const execFileAsync8 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
60650
60683
  if (opts.superprojectWorkspace && opts.submodulePath) {
60651
60684
  try {
60652
60685
  const normalized = opts.submodulePath.replace(/\\/g, "/").replace(/\/+$/, "");
@@ -60656,7 +60689,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
60656
60689
  }
60657
60690
  }
60658
60691
  try {
60659
- const { stdout } = await execFileAsync7(
60692
+ const { stdout } = await execFileAsync8(
60660
60693
  git3,
60661
60694
  ["symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`],
60662
60695
  { cwd: opts.submoduleRepoPath, encoding: "utf8", timeout: localTimeout, windowsHide: true }
@@ -60668,7 +60701,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
60668
60701
  } catch {
60669
60702
  }
60670
60703
  try {
60671
- const { stdout } = await execFileAsync7(
60704
+ const { stdout } = await execFileAsync8(
60672
60705
  git3,
60673
60706
  ["ls-remote", "--symref", remote, "HEAD"],
60674
60707
  { cwd: opts.submoduleRepoPath, encoding: "utf8", timeout: Math.max(localTimeout, 3e4), windowsHide: true }
@@ -60839,7 +60872,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
60839
60872
  if (!validation.valid) {
60840
60873
  return { status: "failed", required: required2, configSource: loaded.path || loaded.source, configSourceType: "invalid", error: String(validation.rejectedCommands[0]?.reason || validation.errors.join("; ")), commandsRun: [] };
60841
60874
  }
60842
- const execFileAsync7 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
60875
+ const execFileAsync8 = (0, import_node_util3.promisify)(import_node_child_process4.execFile);
60843
60876
  const state = {
60844
60877
  status: "running",
60845
60878
  required: required2,
@@ -60867,7 +60900,7 @@ When the user asks to **set up / configure / onboard** this repo for Repo Mesh (
60867
60900
  const resolvedCommand = resolveWin32Executable(command.command);
60868
60901
  const spawn7 = buildWin32ExecFileSpawn(resolvedCommand, command.args);
60869
60902
  try {
60870
- const result = await execFileAsync7(spawn7.file, spawn7.args, {
60903
+ const result = await execFileAsync8(spawn7.file, spawn7.args, {
60871
60904
  cwd,
60872
60905
  encoding: "utf8",
60873
60906
  timeout: command.timeoutMs || DEFAULT_TIMEOUT_MS2,
@@ -65185,7 +65218,22 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
65185
65218
  if (wb.confidence !== wa.confidence) return wb.confidence - wa.confidence;
65186
65219
  return wb.remainingPercent - wa.remainingPercent;
65187
65220
  });
65188
- return { clear, gated };
65221
+ const rankingEvidence = clear.map((providerType) => {
65222
+ const session = sessionByProvider?.get(providerType);
65223
+ const reading = session ?? weeklyByProvider.get(providerType);
65224
+ const axis = session ? "session" : "weekly";
65225
+ return {
65226
+ providerType,
65227
+ axis,
65228
+ ...reading ? {
65229
+ risk: reading.risk,
65230
+ confidence: reading.confidence,
65231
+ rankedRisk: rankedRisk(reading),
65232
+ remainingPercent: reading.remainingPercent
65233
+ } : {}
65234
+ };
65235
+ });
65236
+ return { clear, gated, sessionAxisActive, rankingEvidence };
65189
65237
  }
65190
65238
  function resolveRecoveryRelaunchProvider(node, failedProviderType, nodeProviderTypes = [], policy, now = Date.now(), context) {
65191
65239
  if (!failedProviderType) return { action: "block" };
@@ -66158,6 +66206,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
66158
66206
  providerType: candidate.providerType,
66159
66207
  ...candidate.slot.model ? { model: candidate.slot.model } : {},
66160
66208
  selectionRank,
66209
+ fitnessInputRank: selectionRank,
66161
66210
  capacitySortKey: selectionCapacity.available ? 1 : 0,
66162
66211
  capacityAvailable: selectionCapacity.available,
66163
66212
  capacity: taskCapacity,
@@ -66184,8 +66233,16 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
66184
66233
  ...args.ranked.clear,
66185
66234
  ...args.ranked.gated.map((entry) => entry.providerType)
66186
66235
  ]);
66236
+ const evidenceByProvider = new Map(
66237
+ (args.ranked.rankingEvidence ?? []).map((entry, clearOrderIndex) => {
66238
+ const { providerType, ...rest } = entry;
66239
+ return [providerType, { ...rest, clearOrderIndex }];
66240
+ })
66241
+ );
66187
66242
  const quotaDiagnostics = bonusDiagnostics.map((detail) => {
66188
66243
  const { providerType, ...bonus } = detail;
66244
+ const ranking = evidenceByProvider.get(detail.providerType);
66245
+ const withRanking = ranking ? { ranking } : {};
66189
66246
  const gated = args.ranked.gated.find((entry) => entry.providerType === detail.providerType);
66190
66247
  if (!rankedProviders.has(detail.providerType)) {
66191
66248
  return { providerType, bonus, gate: { outcome: "not-evaluated-floor" } };
@@ -66204,7 +66261,8 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
66204
66261
  return {
66205
66262
  providerType,
66206
66263
  bonus,
66207
- gate: failOpen ? { outcome: "fail-open", reason: detail.zeroReason } : { outcome: "clear" }
66264
+ gate: failOpen ? { outcome: "fail-open", reason: detail.zeroReason } : { outcome: "clear" },
66265
+ ...withRanking
66208
66266
  };
66209
66267
  });
66210
66268
  const previewOnly = args.unbounded ? {
@@ -68884,6 +68942,65 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
68884
68942
  init_chat_history();
68885
68943
  }
68886
68944
  });
68945
+ function normalize3(value) {
68946
+ const trimmed = typeof value === "string" ? value.trim() : "";
68947
+ return trimmed ? trimmed : void 0;
68948
+ }
68949
+ function buildRedriveProvenance(lastReclaim, dispatchedProviderType) {
68950
+ if (!lastReclaim) return null;
68951
+ const previousProviderType = normalize3(lastReclaim.providerType);
68952
+ const providerType = normalize3(dispatchedProviderType) ?? dispatchedProviderType;
68953
+ const providerChanged = !!previousProviderType && !!normalize3(dispatchedProviderType) && previousProviderType !== providerType;
68954
+ return {
68955
+ reason: lastReclaim.reason,
68956
+ reclaimCount: lastReclaim.reclaimCount,
68957
+ ...previousProviderType ? { previousProviderType } : {},
68958
+ ...normalize3(lastReclaim.nodeId) ? { previousNodeId: normalize3(lastReclaim.nodeId) } : {},
68959
+ ...normalize3(lastReclaim.sessionId) ? { previousSessionId: normalize3(lastReclaim.sessionId) } : {},
68960
+ reclaimedAt: lastReclaim.at,
68961
+ providerType,
68962
+ providerChanged
68963
+ };
68964
+ }
68965
+ function describeRedriveProviderFlip(provenance, taskId, meshId) {
68966
+ return `Redrive of task ${taskId} on mesh ${meshId} CHANGED PROVIDER: ${provenance.previousProviderType ?? "?"} \u2192 ${provenance.providerType} (reason ${provenance.reason}, reclaim #${provenance.reclaimCount}, previous node=${provenance.previousNodeId ?? "?"} session=${provenance.previousSessionId ?? "?"}). The reclaim path re-claims an idle session WITHOUT recomputing routing, so the task is now running on a provider it was not routed to. Recorded for measurement; no behavior changed here.`;
68967
+ }
68968
+ var init_mesh_redrive_provenance = __esm2({
68969
+ "src/mesh/mesh-redrive-provenance.ts"() {
68970
+ "use strict";
68971
+ }
68972
+ });
68973
+ async function waitForRemoteSessionReady(meshId, nodeId, sessionId, opts) {
68974
+ if (!sessionId) return false;
68975
+ const timeoutMs = opts.timeoutMs ?? REMOTE_LAUNCH_READY_TIMEOUT_MS;
68976
+ const pollMs = opts.pollMs ?? REMOTE_LAUNCH_READY_POLL_MS;
68977
+ const now = opts.now ?? (() => Date.now());
68978
+ const sleep3 = opts.sleep ?? ((ms) => new Promise((resolve31) => setTimeout(resolve31, ms)));
68979
+ const deadline = now() + timeoutMs;
68980
+ for (; ; ) {
68981
+ let ready = false;
68982
+ try {
68983
+ ready = opts.isReady();
68984
+ } catch {
68985
+ return false;
68986
+ }
68987
+ if (ready) return true;
68988
+ if (now() >= deadline) break;
68989
+ await sleep3(pollMs);
68990
+ }
68991
+ LOG2.warn("MeshQueue", `Remote auto-launched session ${sessionId} on node ${nodeId} (mesh ${meshId}) did not report agent:ready within ${timeoutMs}ms; proceeding optimistically \u2014 unchanged behavior, the claim still fires via the normal event/reconcile path`);
68992
+ return false;
68993
+ }
68994
+ var REMOTE_LAUNCH_READY_TIMEOUT_MS;
68995
+ var REMOTE_LAUNCH_READY_POLL_MS;
68996
+ var init_mesh_remote_ready_wait = __esm2({
68997
+ "src/mesh/mesh-remote-ready-wait.ts"() {
68998
+ "use strict";
68999
+ init_logger();
69000
+ REMOTE_LAUNCH_READY_TIMEOUT_MS = 15e3;
69001
+ REMOTE_LAUNCH_READY_POLL_MS = 100;
69002
+ }
69003
+ });
68887
69004
  function isAnthropicProvider(providerType) {
68888
69005
  const p = typeof providerType === "string" ? providerType.trim().toLowerCase() : "";
68889
69006
  return p.length > 0 && ANTHROPIC_PROVIDER_TYPES.has(p);
@@ -70287,6 +70404,9 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
70287
70404
  }
70288
70405
  LOG2.warn("MeshQueue", `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
70289
70406
  }
70407
+ function remoteSessionReadyProbe(meshId, nodeId, sessionId) {
70408
+ return () => MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId).some((s2) => sessionIdsEquivalent(s2.sessionId, sessionId) && meshNodeIdMatches({ nodeId: s2.nodeId }, nodeId));
70409
+ }
70290
70410
  function recordTaskDispatchedLedger(ctx, deliveryId) {
70291
70411
  const task = ctx.task;
70292
70412
  const routing = ctx.routingDecision;
@@ -70313,6 +70433,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
70313
70433
  ...routing?.selectionTrajectory ? { selectionTrajectory: routing.selectionTrajectory } : {},
70314
70434
  ...routing?.reason ? { reason: routing.reason } : {}
70315
70435
  };
70436
+ const redriveProvenance = buildRedriveProvenance(task.lastReclaim, ctx.providerType);
70316
70437
  appendLedgerEntry(ctx.meshId, {
70317
70438
  kind: "task_dispatched",
70318
70439
  nodeId: ctx.nodeId,
@@ -70327,9 +70448,30 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
70327
70448
  ...ctx.sourceCoordinatorSessionId ? { coordinatorSessionId: ctx.sourceCoordinatorSessionId } : {},
70328
70449
  ...ctx.sourceCoordinatorDaemonId ? { coordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {},
70329
70450
  ...Array.isArray(task.requiredTags) && task.requiredTags.length ? { requiredTags: task.requiredTags } : {},
70330
- routingDecision
70451
+ routingDecision,
70452
+ ...redriveProvenance ? { redriveProvenance } : {}
70331
70453
  }
70332
70454
  });
70455
+ if (redriveProvenance?.providerChanged) {
70456
+ LOG2.warn("MeshQueue", describeRedriveProviderFlip(redriveProvenance, task.id, ctx.meshId));
70457
+ traceMeshEventStage("redrive_provider_changed", {
70458
+ taskId: task.id,
70459
+ sessionId: ctx.sessionId,
70460
+ nodeId: ctx.nodeId,
70461
+ meshId: ctx.meshId
70462
+ }, `${redriveProvenance.previousProviderType} \u2192 ${redriveProvenance.providerType} (${redriveProvenance.reason}, reclaim #${redriveProvenance.reclaimCount})`);
70463
+ try {
70464
+ appendLedgerEntry(ctx.meshId, {
70465
+ kind: "redrive_provider_changed",
70466
+ nodeId: ctx.nodeId,
70467
+ sessionId: ctx.sessionId,
70468
+ providerType: ctx.providerType,
70469
+ taskId: task.id,
70470
+ payload: { taskId: task.id, deliveryId, transport: ctx.transport, ...redriveProvenance }
70471
+ });
70472
+ } catch {
70473
+ }
70474
+ }
70333
70475
  }
70334
70476
  function deliverTaskToSession(dispatchThunk, ctx, warmup) {
70335
70477
  const delivery = createSessionDelivery({
@@ -71306,6 +71448,11 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
71306
71448
  logAutoLaunchQuotaFallbackSuccess(resolved, task.id, nodeId, remoteSessionId || void 0);
71307
71449
  autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
71308
71450
  sweepExpiredCooldowns();
71451
+ if (remoteSessionId) {
71452
+ await waitForRemoteSessionReady(meshId, nodeId, remoteSessionId, {
71453
+ isReady: remoteSessionReadyProbe(meshId, nodeId, remoteSessionId)
71454
+ }).catch(() => false);
71455
+ }
71309
71456
  return true;
71310
71457
  }
71311
71458
  markAutoLaunch(meshId, task.id, { status: "started", nodeId, providerType: effectiveProviderType, ...effectiveModel ? { model: effectiveModel } : {}, ...effectiveThinkingLevel ? { thinkingLevel: effectiveThinkingLevel } : {} });
@@ -71563,6 +71710,8 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
71563
71710
  init_mesh_runtime_store();
71564
71711
  init_mesh_claim_refusal();
71565
71712
  init_mesh_event_trace();
71713
+ init_mesh_redrive_provenance();
71714
+ init_mesh_remote_ready_wait();
71566
71715
  init_mesh_warmup_deadline();
71567
71716
  init_repo_mesh_types();
71568
71717
  init_mesh_json_config();
@@ -76631,9 +76780,9 @@ ${cleanBody}`;
76631
76780
  }
76632
76781
  }
76633
76782
  async function defaultRunGit(args, cwd) {
76634
- const { execFile: execFile8 } = await import("child_process");
76635
- const { promisify: promisify11 } = await import("util");
76636
- const { stdout } = await promisify11(execFile8)("git", args, {
76783
+ const { execFile: execFile9 } = await import("child_process");
76784
+ const { promisify: promisify12 } = await import("util");
76785
+ const { stdout } = await promisify12(execFile9)("git", args, {
76637
76786
  cwd,
76638
76787
  encoding: "utf8",
76639
76788
  timeout: 3e4,
@@ -79028,7 +79177,7 @@ ${cleanBody}`;
79028
79177
  nodeId: row.assignedNodeId,
79029
79178
  meshId,
79030
79179
  event: "agent:generating_started"
79031
- }, `delivered_not_consumed ${Math.round(ageMs2 / 1e3)}s \u2192 ${redriven.status}`);
79180
+ }, `delivered_not_consumed ${Math.round(ageMs2 / 1e3)}s \u2192 ${redriven.status}${row.assignedProviderType ? ` (provider ${row.assignedProviderType} released; the re-claim adopts an idle session without re-ranking, so it may differ)` : ""}`);
79032
79181
  continue;
79033
79182
  }
79034
79183
  }
@@ -83316,435 +83465,9 @@ ${cleanBody}`;
83316
83465
  _acpValidator = null;
83317
83466
  }
83318
83467
  });
83319
- function topLevel(path63) {
83320
- const slash = path63.indexOf("/");
83321
- return slash === -1 ? path63 : path63.slice(0, slash);
83322
- }
83323
- async function analyzeMeshRefineNodeChangeArea(args) {
83324
- const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
83325
- const base = {
83326
- nodeId,
83327
- workspace,
83328
- branch,
83329
- changedTopLevelPaths: [],
83330
- changedFiles: [],
83331
- touchedSubmodulePaths: [],
83332
- touchesSubmodule: false,
83333
- aheadCount: 0
83334
- };
83335
- try {
83336
- let mergeBase = baseRef;
83337
- try {
83338
- const { stdout } = await execFileAsync5(GIT2, ["merge-base", baseRef, branchRef], { cwd: diffCwd, encoding: "utf8" });
83339
- const resolved = stdout.trim();
83340
- if (resolved) mergeBase = resolved;
83341
- } catch {
83342
- }
83343
- const { stdout: countStdout } = await execFileAsync5(
83344
- GIT2,
83345
- ["rev-list", "--count", `${mergeBase}..${branchRef}`],
83346
- { cwd: diffCwd, encoding: "utf8" }
83347
- );
83348
- base.aheadCount = Number.parseInt(countStdout.trim(), 10) || 0;
83349
- const { stdout: nameStdout } = await execFileAsync5(
83350
- GIT2,
83351
- ["diff", "--name-only", `${mergeBase}..${branchRef}`],
83352
- { cwd: diffCwd, encoding: "utf8" }
83353
- );
83354
- const files = nameStdout.split("\n").map((line) => line.trim()).filter(Boolean).slice(0, MAX_CHANGED_FILES2);
83355
- base.changedFiles = files;
83356
- const topSet = /* @__PURE__ */ new Set();
83357
- const submoduleSet = /* @__PURE__ */ new Set();
83358
- for (const file2 of files) {
83359
- const top = topLevel(file2);
83360
- topSet.add(top);
83361
- if (submodulePaths.has(file2) || submodulePaths.has(top)) {
83362
- submoduleSet.add(submodulePaths.has(file2) ? file2 : top);
83363
- }
83364
- }
83365
- base.changedTopLevelPaths = [...topSet].sort();
83366
- base.touchedSubmodulePaths = [...submoduleSet].sort();
83367
- base.touchesSubmodule = submoduleSet.size > 0;
83368
- return base;
83369
- } catch (e) {
83370
- base.error = e?.message || String(e);
83371
- return base;
83372
- }
83373
- }
83374
- function orderMeshRefineBatchNodes(changeAreas) {
83375
- const areaById = {};
83376
- for (const area of changeAreas) areaById[area.nodeId] = area;
83377
- const ranked = [...changeAreas].sort((a, b) => {
83378
- const aSub = a.touchesSubmodule ? 1 : 0;
83379
- const bSub = b.touchesSubmodule ? 1 : 0;
83380
- if (aSub !== bSub) return aSub - bSub;
83381
- const aBreadth = a.changedTopLevelPaths.length;
83382
- const bBreadth = b.changedTopLevelPaths.length;
83383
- if (aBreadth !== bBreadth) return aBreadth - bBreadth;
83384
- return a.nodeId.localeCompare(b.nodeId);
83385
- });
83386
- const rationale = [];
83387
- const nonSub = ranked.filter((a) => !a.touchesSubmodule).map((a) => a.nodeId);
83388
- const sub = ranked.filter((a) => a.touchesSubmodule).map((a) => a.nodeId);
83389
- if (nonSub.length) {
83390
- rationale.push(`Non-submodule nodes first (no submodule-main advance, conflict-free ordering): ${nonSub.join(", ")}`);
83391
- }
83392
- if (sub.length) {
83393
- rationale.push(`Submodule-touching nodes last, serialized (each merge advances submodule main, forcing rebase of the next): ${sub.join(", ")}`);
83394
- }
83395
- for (const area of ranked) {
83396
- if (area.error) rationale.push(`Node ${area.nodeId}: change-area analysis degraded (${area.error}); placed with neutral priority.`);
83397
- }
83398
- return { order: ranked.map((a) => a.nodeId), changeAreas: areaById, rationale };
83399
- }
83400
- var import_node_child_process10;
83401
- var import_node_util6;
83402
- var execFileAsync5;
83403
- var GIT2;
83404
- var MAX_CHANGED_FILES2;
83405
- var init_mesh_refine_batch = __esm2({
83406
- "src/mesh/mesh-refine-batch.ts"() {
83407
- "use strict";
83408
- import_node_child_process10 = require("child_process");
83409
- import_node_util6 = require("util");
83410
- init_resolve_executable();
83411
- execFileAsync5 = (0, import_node_util6.promisify)(import_node_child_process10.execFile);
83412
- GIT2 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
83413
- MAX_CHANGED_FILES2 = 500;
83414
- }
83415
- });
83416
- async function git2(cwd, args) {
83417
- const { stdout } = await execFileAsync6(GIT3, args, {
83418
- cwd,
83419
- encoding: "utf8",
83420
- timeout: 15e3,
83421
- windowsHide: true
83422
- });
83423
- return String(stdout || "").trim();
83424
- }
83425
- async function isAncestor(cwd, ancestor, descendant) {
83426
- try {
83427
- await git2(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
83428
- return true;
83429
- } catch {
83430
- return false;
83431
- }
83432
- }
83433
- async function assessScope(cwd, path63, baseRef, branchRef) {
83434
- try {
83435
- if (!(0, import_node_fs7.existsSync)(cwd)) return { path: path63, verdict: "unknown", error: `path does not exist: ${cwd}` };
83436
- const liveBaseHead = await git2(cwd, ["rev-parse", baseRef]);
83437
- const branchHead = await git2(cwd, ["rev-parse", branchRef]);
83438
- if (!liveBaseHead || !branchHead) {
83439
- return { path: path63, verdict: "unknown", error: "could not resolve base or branch head" };
83440
- }
83441
- if (await isAncestor(cwd, liveBaseHead, branchHead)) {
83442
- return { path: path63, verdict: "clear", liveBaseHead };
83443
- }
83444
- let mergeBase;
83445
- try {
83446
- mergeBase = await git2(cwd, ["merge-base", liveBaseHead, branchHead]);
83447
- } catch {
83448
- return { path: path63, verdict: "unknown", liveBaseHead, error: "no common merge base" };
83449
- }
83450
- if (!mergeBase) return { path: path63, verdict: "unknown", liveBaseHead, error: "empty merge base" };
83451
- return { path: path63, verdict: "diverged", liveBaseHead, mergeBase };
83452
- } catch (e) {
83453
- return { path: path63, verdict: "unknown", error: e?.message || String(e) };
83454
- }
83455
- }
83456
- async function resolveSubmodulePaths(repoRoot) {
83457
- try {
83458
- const stdout = await git2(repoRoot, ["config", "--file", ".gitmodules", "--get-regexp", "path"]);
83459
- const paths = /* @__PURE__ */ new Set();
83460
- for (const line of stdout.split("\n")) {
83461
- const trimmed = line.trim();
83462
- const spaceIdx = trimmed.indexOf(" ");
83463
- if (spaceIdx === -1) continue;
83464
- const value = trimmed.slice(spaceIdx + 1).trim();
83465
- if (value) paths.add(value);
83466
- }
83467
- return paths;
83468
- } catch {
83469
- return /* @__PURE__ */ new Set();
83470
- }
83471
- }
83472
- async function assessRefineBaseDivergence(args) {
83473
- const started = Date.now();
83474
- const { repoRoot, workspace, baseBranch, branch } = args;
83475
- const scopes = [];
83476
- let touchedSubmodulePaths = [];
83477
- const rootBaseRef = await (async () => {
83478
- for (const ref of [`origin/${baseBranch}`, baseBranch, "HEAD"]) {
83479
- try {
83480
- await git2(repoRoot, ["rev-parse", "--verify", `${ref}^{commit}`]);
83481
- return ref;
83482
- } catch {
83483
- }
83484
- }
83485
- return `origin/${baseBranch}`;
83486
- })();
83487
- scopes.push(await assessScope(workspace, ".", rootBaseRef, branch));
83488
- try {
83489
- const submodulePaths = await resolveSubmodulePaths(repoRoot);
83490
- if (submodulePaths.size > 0) {
83491
- const baseRefSha = await git2(repoRoot, ["rev-parse", rootBaseRef]).catch(() => "");
83492
- const branchRefSha = await git2(workspace, ["rev-parse", branch]).catch(() => "");
83493
- if (baseRefSha && branchRefSha) {
83494
- const area = await analyzeMeshRefineNodeChangeArea({
83495
- nodeId: "(accept-precheck)",
83496
- workspace,
83497
- branch,
83498
- baseRef: baseRefSha,
83499
- branchRef: branchRefSha,
83500
- diffCwd: workspace,
83501
- submodulePaths
83502
- });
83503
- touchedSubmodulePaths = area.touchedSubmodulePaths;
83504
- for (const subPath of touchedSubmodulePaths) {
83505
- const subCwd = (0, import_node_path5.resolve)(workspace, subPath);
83506
- const subBaseRef = await (async () => {
83507
- for (const ref of ["origin/main", "origin/master", "main", "master"]) {
83508
- try {
83509
- await git2(subCwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
83510
- return ref;
83511
- } catch {
83512
- }
83513
- }
83514
- return "origin/main";
83515
- })();
83516
- scopes.push(await assessScope(subCwd, subPath, subBaseRef, "HEAD"));
83517
- }
83518
- }
83519
- }
83520
- } catch {
83521
- }
83522
- const verdict = scopes.some((s2) => s2.verdict === "diverged") ? "diverged" : scopes.some((s2) => s2.verdict === "unknown") ? "unknown" : "clear";
83523
- return { verdict, scopes, touchedSubmodulePaths, durationMs: Date.now() - started };
83524
- }
83525
- var import_node_child_process11;
83526
- var import_node_util7;
83527
- var import_node_path5;
83528
- var import_node_fs7;
83529
- var execFileAsync6;
83530
- var GIT3;
83531
- var init_mesh_refine_base_divergence = __esm2({
83532
- "src/mesh/mesh-refine-base-divergence.ts"() {
83533
- "use strict";
83534
- import_node_child_process11 = require("child_process");
83535
- import_node_util7 = require("util");
83536
- import_node_path5 = require("path");
83537
- import_node_fs7 = require("fs");
83538
- init_resolve_executable();
83539
- init_mesh_refine_batch();
83540
- execFileAsync6 = (0, import_node_util7.promisify)(import_node_child_process11.execFile);
83541
- GIT3 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
83542
- }
83543
- });
83544
- var mesh_refine_zombie_sweep_exports = {};
83545
- __export2(mesh_refine_zombie_sweep_exports, {
83546
- classifyRefineDispatch: () => classifyRefineDispatch,
83547
- refineArchivePairKey: () => refineArchivePairKey,
83548
- selectOpenRefineDispatches: () => selectOpenRefineDispatches,
83549
- shouldNotifyRefineCloseOut: () => shouldNotifyRefineCloseOut
83550
- });
83551
- function classifyRefineDispatch(record2, opts) {
83552
- if (opts.isRunning(record2.nodeId)) return void 0;
83553
- const dispatchedAtMs = new Date(record2.timestamp).getTime();
83554
- const ageMs2 = Number.isFinite(dispatchedAtMs) ? opts.nowMs - dispatchedAtMs : void 0;
83555
- const base = { nodeId: record2.nodeId, jobId: record2.jobId, ...ageMs2 !== void 0 ? { ageMs: ageMs2 } : {} };
83556
- if (!opts.nodeExists(record2.nodeId)) {
83557
- return { ...base, disposition: "close_removed_node" };
83558
- }
83559
- if (opts.executorLiveness) {
83560
- let liveness;
83561
- try {
83562
- liveness = opts.executorLiveness(record2);
83563
- } catch {
83564
- liveness = "unknown";
83565
- }
83566
- if (liveness === "alive") {
83567
- return { ...base, disposition: "defer_executor_alive" };
83568
- }
83569
- }
83570
- if (ageMs2 !== void 0 && ageMs2 >= 0 && ageMs2 < opts.graceMs) {
83571
- return { ...base, disposition: "defer_grace" };
83572
- }
83573
- if (ageMs2 !== void 0 && ageMs2 >= opts.zombieCutoffMs) {
83574
- return { ...base, disposition: "close_stale" };
83575
- }
83576
- return { ...base, disposition: "resume" };
83577
- }
83578
- function selectOpenRefineDispatches(entries, archivedTerminalKeys) {
83579
- const terminalKeys = /* @__PURE__ */ new Set();
83580
- for (const e of entries) {
83581
- if (e.kind !== "task_completed" && e.kind !== "task_failed") continue;
83582
- if (!e.nodeId) continue;
83583
- const jobId = e.payload?.refineJob?.jobId;
83584
- if (jobId) terminalKeys.add(`${e.nodeId}:${jobId}`);
83585
- }
83586
- const open = [];
83587
- const seen = /* @__PURE__ */ new Set();
83588
- for (const e of entries) {
83589
- if (e.kind !== "task_dispatched" || !e.nodeId) continue;
83590
- const payload = e.payload;
83591
- if (payload?.source !== "refine_mesh_node_async_job") continue;
83592
- const jobId = payload?.refineJob?.jobId;
83593
- if (!jobId) continue;
83594
- const key2 = `${e.nodeId}:${jobId}`;
83595
- if (terminalKeys.has(key2) || seen.has(key2)) continue;
83596
- if (archivedTerminalKeys?.has(refineArchivePairKey(e.nodeId, jobId))) continue;
83597
- seen.add(key2);
83598
- const executor = payload?.refineJob?.executor;
83599
- open.push({ nodeId: e.nodeId, jobId, timestamp: e.timestamp, ...executor ? { executor } : {} });
83600
- }
83601
- return open;
83602
- }
83603
- function refineArchivePairKey(nodeId, jobId) {
83604
- return `refine:${nodeId}:${jobId}`;
83605
- }
83606
- function shouldNotifyRefineCloseOut(decision, notifyHorizonMs) {
83607
- if (decision.disposition === "close_removed_node") return false;
83608
- if (decision.disposition !== "close_stale") return false;
83609
- if (decision.ageMs === void 0) return true;
83610
- return decision.ageMs < notifyHorizonMs;
83611
- }
83612
- var init_mesh_refine_zombie_sweep = __esm2({
83613
- "src/mesh/mesh-refine-zombie-sweep.ts"() {
83614
- "use strict";
83615
- }
83616
- });
83617
- function classifyRefineTerminal(result) {
83618
- const refineCode = typeof result.code === "string" ? result.code : "";
83619
- const landing = extractRefineMergeLanding(result);
83620
- const isPostMergeWarning = result.success !== true && landing.merged && landing.pushed;
83621
- const kind = result.success === true ? "completed" : isPostMergeWarning ? "completed_with_warnings" : refineCode === "blocked_review" || refineCode === "worktree_missing" || refineCode === "worktree_dirty" || refineCode === "rebase_precondition_failed" || refineCode === "rebase_failed" ? "blocked_review" : refineCode === "validation_failed" || refineCode === "validation_dependencies_missing" || refineCode === "missing_dependencies" || refineCode === "dependency_bootstrap_failed" || refineCode === "spawn_resolution_failed" || refineCode === "validation_unavailable" || refineCode === "output_limit_exceeded" ? "validation_failed" : refineCode === "submodule_reachability_failed" ? "submodule_reachability_failed" : refineCode === "merge_failed" || refineCode === "patch_equivalence_failed" || refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "merge_failed" : refineCode === "cleanup_failed" ? "cleanup_failed" : "merge_failed";
83622
- const clean = kind === "completed";
83623
- return { kind, landing, isPostMergeWarning, converged: clean || isPostMergeWarning, clean };
83624
- }
83625
- function refineTerminalNextStep(kind) {
83626
- switch (kind) {
83627
- case "blocked_review":
83628
- return "Request user review/approval before attempting to merge again.";
83629
- case "validation_failed":
83630
- return "Fix failing tests or configure validation.bootstrapCommands and retry mesh_refine_node.";
83631
- case "submodule_reachability_failed":
83632
- return "Push unreachable submodule commits to origin/main, then retry mesh_refine_node.";
83633
- case "merge_failed":
83634
- return "Resolve merge conflicts or patch equivalence issues, then retry mesh_refine_node.";
83635
- case "cleanup_failed":
83636
- return "Manually remove the worktree and retry or use mesh_remove_node.";
83637
- case "completed_with_warnings":
83638
- return "The merge IS on origin \u2014 do NOT re-run mesh_refine_node. Only the post-merge step below needs attention (worktree cleanup / submodule alignment); treat the branch as merged_to_main.";
83639
- default:
83640
- return "Inspect refineStages for the failing stage and retry.";
83641
- }
83642
- }
83643
- function buildRefineWorktreeMissingResult(nodeId, workspace, refineStages) {
83644
- return {
83645
- success: false,
83646
- code: "worktree_missing",
83647
- convergenceStatus: "blocked_review",
83648
- // Never auto-retried: re-running cannot recreate the worktree, and the node has
83649
- // most likely already converged.
83650
- retryable: false,
83651
- workspaceMissing: true,
83652
- error: `The worktree directory for node '${nodeId}' no longer exists (${workspace}); nothing was merged by this run. Worktree removal is the final step of a SUCCESSFUL refine, so this node was most likely already merged and cleaned up by an earlier job \u2014 verify with 'git -C <repoRoot> log --oneline' before acting. Do NOT re-run refine to "fix" this.`,
83653
- nextStep: "Verify whether the branch already merged into the base (it most likely did). If so, treat the node as merged_to_main and remove it from the mesh; only re-clone if the work is genuinely missing.",
83654
- refineStages,
83655
- finalBranchConvergenceState: {
83656
- baseBranch: void 0,
83657
- merged: false,
83658
- removed: true,
83659
- status: "blocked_review"
83660
- }
83661
- };
83662
- }
83663
- function extractRefineMergeLanding(result) {
83664
- const fbcs = result.finalBranchConvergenceState && typeof result.finalBranchConvergenceState === "object" ? result.finalBranchConvergenceState : void 0;
83665
- const merged = result.merged === true || result.mergedLocal === true || fbcs?.merged === true;
83666
- const pushed = result.pushed === true || fbcs?.pushed === true;
83667
- return { merged: !!merged, pushed: !!pushed && !!merged };
83668
- }
83669
- function buildRefineBlockerContext(result, opts) {
83670
- if (opts.isTerminalClean) return void 0;
83671
- const refineTerminalKind = opts.terminalKind;
83672
- const refineCode = typeof result.code === "string" ? result.code : "";
83673
- const code = typeof result.code === "string" ? result.code : refineTerminalKind;
83674
- const stage = refineTerminalKind === "validation_failed" ? "validation" : refineTerminalKind === "submodule_reachability_failed" ? "submodule_reachability" : refineCode === "patch_equivalence_failed" ? "patch_equivalence" : refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "patch_equivalence" : refineCode === "worktree_dirty" || refineCode === "rebase_precondition_failed" || refineCode === "rebase_failed" ? "patch_equivalence" : refineTerminalKind === "merge_failed" ? "merge" : refineTerminalKind === "cleanup_failed" ? "cleanup" : refineTerminalKind === "completed_with_warnings" ? refineCode === "post_merge_submodule_alignment_failed" ? "submodule_alignment" : "cleanup" : "unknown";
83675
- const ctx = { stage, reason: code, terminalKind: refineTerminalKind };
83676
- if (typeof result.error === "string") ctx.error = result.error;
83677
- if (typeof result.blockedReason === "string") ctx.blockedReason = result.blockedReason;
83678
- if (typeof result.detailedReason === "string") ctx.detailedReason = result.detailedReason;
83679
- if (typeof result.detailedReasonDescription === "string") ctx.detailedReasonDescription = result.detailedReasonDescription;
83680
- if (typeof result.recommendedAction === "string") ctx.recommendedAction = result.recommendedAction;
83681
- if (result.evidence && typeof result.evidence === "object") ctx.evidence = result.evidence;
83682
- if (typeof result.rebaseStderr === "string") ctx.rebaseStderr = result.rebaseStderr;
83683
- if (typeof result.rebaseFailureDetail === "string") ctx.rebaseFailureDetail = result.rebaseFailureDetail;
83684
- if (typeof result.rebaseConflict === "boolean") ctx.rebaseConflict = result.rebaseConflict;
83685
- if (stage === "patch_equivalence" && result.patchEquivalence) {
83686
- const pe = result.patchEquivalence;
83687
- ctx.details = {
83688
- expectedPatchId: pe.expectedPatchId,
83689
- actualPatchId: pe.actualPatchId,
83690
- status: pe.status,
83691
- actionableHint: pe.actionableHint,
83692
- error: pe.error,
83693
- ...typeof result.detailedReason === "string" ? { detailedReason: result.detailedReason } : {},
83694
- ...typeof result.recommendedAction === "string" ? { recommendedAction: result.recommendedAction } : {},
83695
- ...result.evidence && typeof result.evidence === "object" ? { evidence: result.evidence } : {}
83696
- };
83697
- }
83698
- if (stage === "submodule_reachability" && Array.isArray(result.unreachableSubmoduleCommits)) {
83699
- ctx.details = {
83700
- unreachableCount: result.unreachableSubmoduleCommits.length,
83701
- paths: result.unreachableSubmoduleCommits.map((e) => e.path),
83702
- autoPublishAllowed: result.unreachableSubmoduleCommits[0]?.autoPublishAllowed
83703
- };
83704
- }
83705
- if (stage === "validation" && result.validationSummary) {
83706
- const vs = result.validationSummary;
83707
- const diagnostics = opts.extractValidationDiagnostics?.(vs);
83708
- ctx.details = {
83709
- failureCode: vs.failureCode,
83710
- failureKind: vs.failureKind,
83711
- commandsRun: Array.isArray(vs.commandsRun) ? vs.commandsRun.length : void 0,
83712
- ...diagnostics ? { failure: diagnostics } : {}
83713
- };
83714
- }
83715
- return ctx;
83716
- }
83717
- var init_mesh_refine_landing = __esm2({
83718
- "src/mesh/mesh-refine-landing.ts"() {
83719
- "use strict";
83720
- }
83721
- });
83722
- function resolveRefineVitestMaxWorkers(env2 = process.env) {
83723
- const raw = env2[REFINE_VITEST_MAX_WORKERS_ENV];
83724
- if (raw === void 0 || raw.trim() === "") return DEFAULT_REFINE_VITEST_MAX_WORKERS;
83725
- const parsed = Number.parseInt(raw, 10);
83726
- if (!Number.isFinite(parsed)) return DEFAULT_REFINE_VITEST_MAX_WORKERS;
83727
- if (parsed === 0) return null;
83728
- return Math.max(1, parsed);
83729
- }
83730
- function refineGateChildEnv(env2 = process.env) {
83731
- if (env2.VITEST_MAX_WORKERS) return {};
83732
- const cap = resolveRefineVitestMaxWorkers(env2);
83733
- if (cap === null) return {};
83734
- return { VITEST_MAX_WORKERS: String(cap) };
83735
- }
83736
- var REFINE_VITEST_MAX_WORKERS_ENV;
83737
- var DEFAULT_REFINE_VITEST_MAX_WORKERS;
83738
- var init_mesh_refine_worker_cap = __esm2({
83739
- "src/mesh/mesh-refine-worker-cap.ts"() {
83740
- "use strict";
83741
- REFINE_VITEST_MAX_WORKERS_ENV = "ADHDEV_REFINE_VITEST_MAX_WORKERS";
83742
- DEFAULT_REFINE_VITEST_MAX_WORKERS = 2;
83743
- }
83744
- });
83745
83468
  function readChangedGitlinkPaths(repoRoot, fromRef, toRef) {
83746
83469
  try {
83747
- const output = (0, import_node_child_process12.execFileSync)(GIT4, ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
83470
+ const output = (0, import_node_child_process9.execFileSync)(GIT2, ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
83748
83471
  cwd: repoRoot,
83749
83472
  encoding: "utf8",
83750
83473
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -83768,7 +83491,7 @@ ${cleanBody}`;
83768
83491
  }
83769
83492
  function readTreeObject(repoRoot, ref, path63) {
83770
83493
  try {
83771
- const output = (0, import_node_child_process12.execFileSync)(GIT4, ["ls-tree", ref, "--", path63], {
83494
+ const output = (0, import_node_child_process9.execFileSync)(GIT2, ["ls-tree", ref, "--", path63], {
83772
83495
  cwd: repoRoot,
83773
83496
  encoding: "utf8",
83774
83497
  maxBuffer: 1024 * 1024
@@ -83783,7 +83506,7 @@ ${cleanBody}`;
83783
83506
  for (const ref of refs) {
83784
83507
  if (!ref) return false;
83785
83508
  try {
83786
- (0, import_node_child_process12.execFileSync)(GIT4, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { cwd, stdio: "ignore", windowsHide: true });
83509
+ (0, import_node_child_process9.execFileSync)(GIT2, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { cwd, stdio: "ignore", windowsHide: true });
83787
83510
  } catch {
83788
83511
  return false;
83789
83512
  }
@@ -83792,13 +83515,13 @@ ${cleanBody}`;
83792
83515
  }
83793
83516
  function probeGitAncestry(cwd, ancestor, descendant) {
83794
83517
  try {
83795
- if (!fs53.existsSync(cwd)) return "undeterminable";
83518
+ if (!fs50.existsSync(cwd)) return "undeterminable";
83796
83519
  } catch {
83797
83520
  return "undeterminable";
83798
83521
  }
83799
83522
  if (!gitRefsResolvable(cwd, [ancestor, descendant])) return "undeterminable";
83800
83523
  try {
83801
- (0, import_node_child_process12.execFileSync)(GIT4, ["merge-base", "--is-ancestor", ancestor, descendant], { cwd, stdio: "ignore", windowsHide: true });
83524
+ (0, import_node_child_process9.execFileSync)(GIT2, ["merge-base", "--is-ancestor", ancestor, descendant], { cwd, stdio: "ignore", windowsHide: true });
83802
83525
  return true;
83803
83526
  } catch (e) {
83804
83527
  return e?.status === 1 ? false : "undeterminable";
@@ -83806,8 +83529,8 @@ ${cleanBody}`;
83806
83529
  }
83807
83530
  function probeSubmoduleGitlinkReachability(input) {
83808
83531
  const { path: path63, baseCommit, branchCommit, probeRoot, baseRepoRoot } = input;
83809
- const submoduleRepo = (0, import_path17.resolve)(probeRoot, path63);
83810
- const baseSubmoduleRepo = (0, import_path17.resolve)(baseRepoRoot, path63);
83532
+ const submoduleRepo = (0, import_path16.resolve)(probeRoot, path63);
83533
+ const baseSubmoduleRepo = (0, import_path16.resolve)(baseRepoRoot, path63);
83811
83534
  if (baseCommit) ensureSubmoduleCommitLocal(submoduleRepo, baseSubmoduleRepo, baseCommit);
83812
83535
  if (branchCommit) ensureSubmoduleCommitLocal(submoduleRepo, baseSubmoduleRepo, branchCommit);
83813
83536
  let fastForward;
@@ -83845,7 +83568,7 @@ ${cleanBody}`;
83845
83568
  function submoduleCommitPresent(submoduleRepoPath, commit) {
83846
83569
  if (!commit) return false;
83847
83570
  try {
83848
- (0, import_node_child_process12.execFileSync)(GIT4, ["cat-file", "-e", `${commit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83571
+ (0, import_node_child_process9.execFileSync)(GIT2, ["cat-file", "-e", `${commit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83849
83572
  return true;
83850
83573
  } catch {
83851
83574
  return false;
@@ -83855,7 +83578,7 @@ ${cleanBody}`;
83855
83578
  if (!commit) return false;
83856
83579
  const present = () => {
83857
83580
  try {
83858
- (0, import_node_child_process12.execFileSync)(GIT4, ["cat-file", "-e", `${commit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83581
+ (0, import_node_child_process9.execFileSync)(GIT2, ["cat-file", "-e", `${commit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83859
83582
  return true;
83860
83583
  } catch {
83861
83584
  return false;
@@ -83863,7 +83586,7 @@ ${cleanBody}`;
83863
83586
  };
83864
83587
  if (present()) return true;
83865
83588
  try {
83866
- if (!fs53.existsSync(submoduleRepoPath) || !fs53.existsSync(baseSubmoduleRepoPath)) return false;
83589
+ if (!fs50.existsSync(submoduleRepoPath) || !fs50.existsSync(baseSubmoduleRepoPath)) return false;
83867
83590
  } catch {
83868
83591
  return false;
83869
83592
  }
@@ -83877,7 +83600,7 @@ ${cleanBody}`;
83877
83600
  ];
83878
83601
  for (const args of strategies) {
83879
83602
  try {
83880
- (0, import_node_child_process12.execFileSync)(GIT4, ["-c", "protocol.file.allow=always", ...args], {
83603
+ (0, import_node_child_process9.execFileSync)(GIT2, ["-c", "protocol.file.allow=always", ...args], {
83881
83604
  cwd: submoduleRepoPath,
83882
83605
  stdio: ["ignore", "ignore", "pipe"]
83883
83606
  });
@@ -83907,7 +83630,7 @@ ${cleanBody}`;
83907
83630
  }
83908
83631
  function readChangedPathKinds(repoRoot, fromRef, toRef) {
83909
83632
  try {
83910
- const output = (0, import_node_child_process12.execFileSync)(GIT4, ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
83633
+ const output = (0, import_node_child_process9.execFileSync)(GIT2, ["diff", "--raw", "--no-abbrev", fromRef, toRef], {
83911
83634
  cwd: repoRoot,
83912
83635
  encoding: "utf8",
83913
83636
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -83930,25 +83653,25 @@ ${cleanBody}`;
83930
83653
  return [];
83931
83654
  }
83932
83655
  }
83933
- async function verifyRemoteBranchContainsCommit(runGit3, submodulePath, commit, branch = "main") {
83656
+ async function verifyRemoteBranchContainsCommit(runGit4, submodulePath, commit, branch = "main") {
83934
83657
  try {
83935
- await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
83658
+ await runGit4(submodulePath, ["-c", "protocol.file.allow=always", "fetch", "origin", `refs/heads/${branch}:refs/remotes/origin/${branch}`]);
83936
83659
  } catch (fetchError) {
83937
83660
  return { state: "undeterminable", error: fetchError };
83938
83661
  }
83939
83662
  const remoteRef = `refs/remotes/origin/${branch}`;
83940
83663
  try {
83941
- await runGit3(submodulePath, ["rev-parse", "--verify", "--quiet", `${remoteRef}^{commit}`]);
83664
+ await runGit4(submodulePath, ["rev-parse", "--verify", "--quiet", `${remoteRef}^{commit}`]);
83942
83665
  } catch (resolveError) {
83943
83666
  return { state: "undeterminable", error: resolveError };
83944
83667
  }
83945
83668
  try {
83946
- await runGit3(submodulePath, ["rev-parse", "--verify", "--quiet", `${commit}^{commit}`]);
83669
+ await runGit4(submodulePath, ["rev-parse", "--verify", "--quiet", `${commit}^{commit}`]);
83947
83670
  } catch (missingCandidate) {
83948
83671
  return { state: "absent", error: missingCandidate };
83949
83672
  }
83950
83673
  try {
83951
- await runGit3(submodulePath, ["merge-base", "--is-ancestor", commit, remoteRef]);
83674
+ await runGit4(submodulePath, ["merge-base", "--is-ancestor", commit, remoteRef]);
83952
83675
  return { state: "contained" };
83953
83676
  } catch (ancestryError) {
83954
83677
  return ancestryError?.code === 1 ? { state: "absent", error: ancestryError } : { state: "undeterminable", error: ancestryError };
@@ -83975,45 +83698,68 @@ ${cleanBody}`;
83975
83698
  parts.push("Do not merge the root branch until every submodule gitlink commit is reachable from submodule origin/main.");
83976
83699
  return parts.join(" ");
83977
83700
  }
83978
- var fs53;
83979
- var import_node_child_process12;
83980
- var import_path17;
83981
- var GIT4;
83701
+ var fs50;
83702
+ var import_node_child_process9;
83703
+ var import_path16;
83704
+ var GIT2;
83982
83705
  var REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES;
83983
83706
  var init_mesh_refine_gitlink_utils = __esm2({
83984
83707
  "src/mesh/mesh-refine-gitlink-utils.ts"() {
83985
83708
  "use strict";
83986
- fs53 = __toESM2(require("fs"));
83987
- import_node_child_process12 = require("child_process");
83988
- import_path17 = require("path");
83709
+ fs50 = __toESM2(require("fs"));
83710
+ import_node_child_process9 = require("child_process");
83711
+ import_path16 = require("path");
83989
83712
  init_logger();
83990
83713
  init_resolve_executable();
83991
- GIT4 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
83714
+ GIT2 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
83992
83715
  REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES = 4 * 1024 * 1024;
83993
83716
  }
83994
83717
  });
83718
+ function resolveRefineVitestMaxWorkers(env2 = process.env) {
83719
+ const raw = env2[REFINE_VITEST_MAX_WORKERS_ENV];
83720
+ if (raw === void 0 || raw.trim() === "") return DEFAULT_REFINE_VITEST_MAX_WORKERS;
83721
+ const parsed = Number.parseInt(raw, 10);
83722
+ if (!Number.isFinite(parsed)) return DEFAULT_REFINE_VITEST_MAX_WORKERS;
83723
+ if (parsed === 0) return null;
83724
+ return Math.max(1, parsed);
83725
+ }
83726
+ function refineGateChildEnv(env2 = process.env) {
83727
+ if (env2.VITEST_MAX_WORKERS) return {};
83728
+ const cap = resolveRefineVitestMaxWorkers(env2);
83729
+ if (cap === null) return {};
83730
+ return { VITEST_MAX_WORKERS: String(cap) };
83731
+ }
83732
+ var REFINE_VITEST_MAX_WORKERS_ENV;
83733
+ var DEFAULT_REFINE_VITEST_MAX_WORKERS;
83734
+ var init_mesh_refine_worker_cap = __esm2({
83735
+ "src/mesh/mesh-refine-worker-cap.ts"() {
83736
+ "use strict";
83737
+ REFINE_VITEST_MAX_WORKERS_ENV = "ADHDEV_REFINE_VITEST_MAX_WORKERS";
83738
+ DEFAULT_REFINE_VITEST_MAX_WORKERS = 2;
83739
+ }
83740
+ });
83995
83741
  function classifySubmoduleDivergence(submoduleRepoPath, baseCommit, branchCommit) {
83996
83742
  if (!baseCommit || !branchCommit) return "undeterminable";
83997
83743
  if (baseCommit === branchCommit) return "not_diverged";
83998
83744
  try {
83999
- if (!fs54.existsSync(submoduleRepoPath)) return "undeterminable";
84000
- (0, import_node_child_process13.execFileSync)(GIT4, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
84001
- (0, import_node_child_process13.execFileSync)(GIT4, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83745
+ if (!fs51.existsSync(submoduleRepoPath)) return "undeterminable";
83746
+ (0, import_node_child_process10.execFileSync)(GIT2, ["cat-file", "-e", `${baseCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
83747
+ (0, import_node_child_process10.execFileSync)(GIT2, ["cat-file", "-e", `${branchCommit}^{commit}`], { cwd: submoduleRepoPath, stdio: "ignore" });
84002
83748
  } catch {
84003
83749
  return "undeterminable";
84004
83750
  }
84005
83751
  try {
84006
- (0, import_node_child_process13.execFileSync)(GIT4, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
83752
+ (0, import_node_child_process10.execFileSync)(GIT2, ["merge-base", "--is-ancestor", baseCommit, branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
84007
83753
  return "not_diverged";
84008
83754
  } catch {
84009
83755
  }
84010
83756
  try {
84011
- (0, import_node_child_process13.execFileSync)(GIT4, ["merge-base", "--is-ancestor", branchCommit, baseCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
83757
+ (0, import_node_child_process10.execFileSync)(GIT2, ["merge-base", "--is-ancestor", branchCommit, baseCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
84012
83758
  return "not_diverged";
84013
83759
  } catch {
84014
83760
  }
84015
83761
  try {
84016
- const mb = (0, import_node_child_process13.execFileSync)(GIT4, ["merge-base", baseCommit, branchCommit], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
83762
+ const mb = (0, import_node_child_process10.execFileSync)(GIT2, ["merge-base", baseCommit, branchCommit], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
84017
83763
  return mb ? "diverged" : "not_diverged";
84018
83764
  } catch {
84019
83765
  return "not_diverged";
@@ -84021,13 +83767,13 @@ ${cleanBody}`;
84021
83767
  }
84022
83768
  function resolveSubmoduleRemoteMainRef(submoduleRepoPath) {
84023
83769
  try {
84024
- const sym = (0, import_node_child_process13.execFileSync)(GIT4, ["symbolic-ref", "-q", "refs/remotes/origin/HEAD"], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
83770
+ const sym = (0, import_node_child_process10.execFileSync)(GIT2, ["symbolic-ref", "-q", "refs/remotes/origin/HEAD"], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
84025
83771
  if (sym) return sym;
84026
83772
  } catch {
84027
83773
  }
84028
83774
  for (const branch of ["main", "master"]) {
84029
83775
  try {
84030
- (0, import_node_child_process13.execFileSync)(GIT4, ["rev-parse", "--verify", "-q", `refs/remotes/origin/${branch}`], { cwd: submoduleRepoPath, stdio: ["ignore", "pipe", "pipe"] });
83776
+ (0, import_node_child_process10.execFileSync)(GIT2, ["rev-parse", "--verify", "-q", `refs/remotes/origin/${branch}`], { cwd: submoduleRepoPath, stdio: ["ignore", "pipe", "pipe"] });
84031
83777
  return `refs/remotes/origin/${branch}`;
84032
83778
  } catch {
84033
83779
  }
@@ -84036,24 +83782,24 @@ ${cleanBody}`;
84036
83782
  }
84037
83783
  function findEquivalentPublishedSubmoduleCommit(submoduleRepoPath, baseCommit, branchCommit, remoteRef) {
84038
83784
  try {
84039
- const mergeTreeOut = (0, import_node_child_process13.execFileSync)(GIT4, ["merge-tree", "--write-tree", baseCommit, branchCommit], {
83785
+ const mergeTreeOut = (0, import_node_child_process10.execFileSync)(GIT2, ["merge-tree", "--write-tree", baseCommit, branchCommit], {
84040
83786
  cwd: submoduleRepoPath,
84041
83787
  encoding: "utf8",
84042
83788
  stdio: ["ignore", "pipe", "pipe"]
84043
83789
  });
84044
83790
  const mergedTree = mergeTreeOut.trim().split(/\s+/)[0] || "";
84045
83791
  if (!mergedTree) return void 0;
84046
- const candidates = (0, import_node_child_process13.execFileSync)(GIT4, ["rev-list", "--max-count=100", remoteRef, "--not", baseCommit], {
83792
+ const candidates = (0, import_node_child_process10.execFileSync)(GIT2, ["rev-list", "--max-count=100", remoteRef, "--not", baseCommit], {
84047
83793
  cwd: submoduleRepoPath,
84048
83794
  encoding: "utf8"
84049
83795
  }).split("\n").map((s2) => s2.trim()).filter(Boolean);
84050
83796
  for (const candidate of candidates) {
84051
83797
  try {
84052
- (0, import_node_child_process13.execFileSync)(GIT4, ["merge-base", "--is-ancestor", baseCommit, candidate], { cwd: submoduleRepoPath, stdio: "ignore" });
83798
+ (0, import_node_child_process10.execFileSync)(GIT2, ["merge-base", "--is-ancestor", baseCommit, candidate], { cwd: submoduleRepoPath, stdio: "ignore" });
84053
83799
  } catch {
84054
83800
  continue;
84055
83801
  }
84056
- const tree = (0, import_node_child_process13.execFileSync)(GIT4, ["rev-parse", `${candidate}^{tree}`], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
83802
+ const tree = (0, import_node_child_process10.execFileSync)(GIT2, ["rev-parse", `${candidate}^{tree}`], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
84057
83803
  if (tree === mergedTree) return candidate;
84058
83804
  }
84059
83805
  } catch {
@@ -84062,7 +83808,7 @@ ${cleanBody}`;
84062
83808
  }
84063
83809
  function submoduleHasOriginRemote(submoduleRepoPath) {
84064
83810
  try {
84065
- const url2 = (0, import_node_child_process13.execFileSync)(GIT4, ["remote", "get-url", "origin"], {
83811
+ const url2 = (0, import_node_child_process10.execFileSync)(GIT2, ["remote", "get-url", "origin"], {
84066
83812
  cwd: submoduleRepoPath,
84067
83813
  encoding: "utf8",
84068
83814
  stdio: ["ignore", "pipe", "ignore"]
@@ -84088,9 +83834,9 @@ ${cleanBody}`;
84088
83834
  for (const path63 of changed) {
84089
83835
  const baseCommit = readTreeObject(baseRepoRoot, baseHead, path63);
84090
83836
  const branchCommit = readTreeObject(worktreeRoot, branchHead, path63);
84091
- const submoduleRepoPath = (0, import_path18.resolve)(worktreeRoot, path63);
83837
+ const submoduleRepoPath = (0, import_path17.resolve)(worktreeRoot, path63);
84092
83838
  if (baseCommit) {
84093
- ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path18.resolve)(baseRepoRoot, path63), baseCommit);
83839
+ ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path17.resolve)(baseRepoRoot, path63), baseCommit);
84094
83840
  }
84095
83841
  const markUndeterminable = () => {
84096
83842
  const unavailable = [];
@@ -84116,7 +83862,7 @@ ${cleanBody}`;
84116
83862
  const originConfigured = submoduleHasOriginRemote(submoduleRepoPath);
84117
83863
  let remoteFetched = true;
84118
83864
  try {
84119
- (0, import_node_child_process13.execFileSync)(GIT4, ["-c", "protocol.file.allow=always", "fetch", "-q", "origin"], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
83865
+ (0, import_node_child_process10.execFileSync)(GIT2, ["-c", "protocol.file.allow=always", "fetch", "-q", "origin"], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
84120
83866
  } catch {
84121
83867
  remoteFetched = false;
84122
83868
  }
@@ -84124,7 +83870,7 @@ ${cleanBody}`;
84124
83870
  const publishedEquivalent = remoteMainRef ? findEquivalentPublishedSubmoduleCommit(submoduleRepoPath, baseCommit, branchCommit, remoteMainRef) : void 0;
84125
83871
  if (publishedEquivalent) {
84126
83872
  try {
84127
- (0, import_node_child_process13.execFileSync)(GIT4, ["checkout", "-q", "--detach", publishedEquivalent], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
83873
+ (0, import_node_child_process10.execFileSync)(GIT2, ["checkout", "-q", "--detach", publishedEquivalent], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
84128
83874
  } catch {
84129
83875
  }
84130
83876
  gitlinks.push({ path: path63, baseCommit, branchCommit, rebasedCommit: publishedEquivalent, action: "converged_to_published" });
@@ -84136,7 +83882,7 @@ ${cleanBody}`;
84136
83882
  const willMintUnpublishedCommit = branchPublished !== true;
84137
83883
  const wouldConflict = (() => {
84138
83884
  try {
84139
- (0, import_node_child_process13.execFileSync)(GIT4, ["merge-tree", "--write-tree", baseCommit, branchCommit], {
83885
+ (0, import_node_child_process10.execFileSync)(GIT2, ["merge-tree", "--write-tree", baseCommit, branchCommit], {
84140
83886
  cwd: submoduleRepoPath,
84141
83887
  encoding: "utf8",
84142
83888
  stdio: ["ignore", "pipe", "pipe"]
@@ -84169,16 +83915,16 @@ ${cleanBody}`;
84169
83915
  }
84170
83916
  let rebasedCommit;
84171
83917
  try {
84172
- (0, import_node_child_process13.execFileSync)(GIT4, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
84173
- (0, import_node_child_process13.execFileSync)(GIT4, ["rebase", baseCommit], { cwd: submoduleRepoPath, stdio: ["ignore", "pipe", "pipe"] });
84174
- rebasedCommit = (0, import_node_child_process13.execFileSync)(GIT4, ["rev-parse", "HEAD"], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
83918
+ (0, import_node_child_process10.execFileSync)(GIT2, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: ["ignore", "ignore", "pipe"] });
83919
+ (0, import_node_child_process10.execFileSync)(GIT2, ["rebase", baseCommit], { cwd: submoduleRepoPath, stdio: ["ignore", "pipe", "pipe"] });
83920
+ rebasedCommit = (0, import_node_child_process10.execFileSync)(GIT2, ["rev-parse", "HEAD"], { cwd: submoduleRepoPath, encoding: "utf8" }).trim();
84175
83921
  } catch {
84176
83922
  try {
84177
- (0, import_node_child_process13.execFileSync)(GIT4, ["rebase", "--abort"], { cwd: submoduleRepoPath, stdio: "ignore" });
83923
+ (0, import_node_child_process10.execFileSync)(GIT2, ["rebase", "--abort"], { cwd: submoduleRepoPath, stdio: "ignore" });
84178
83924
  } catch {
84179
83925
  }
84180
83926
  try {
84181
- (0, import_node_child_process13.execFileSync)(GIT4, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
83927
+ (0, import_node_child_process10.execFileSync)(GIT2, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
84182
83928
  } catch {
84183
83929
  }
84184
83930
  gitlinks.push({ path: path63, baseCommit, branchCommit, action: "rebase_conflict" });
@@ -84189,7 +83935,7 @@ ${cleanBody}`;
84189
83935
  if (rebasedCommit === branchCommit) return true;
84190
83936
  if (rebasedCommit === baseCommit) return false;
84191
83937
  try {
84192
- const replayed = (0, import_node_child_process13.execFileSync)(GIT4, ["rev-list", "--count", `${baseCommit}..${rebasedCommit}`], {
83938
+ const replayed = (0, import_node_child_process10.execFileSync)(GIT2, ["rev-list", "--count", `${baseCommit}..${rebasedCommit}`], {
84193
83939
  cwd: submoduleRepoPath,
84194
83940
  encoding: "utf8"
84195
83941
  }).trim();
@@ -84200,7 +83946,7 @@ ${cleanBody}`;
84200
83946
  })();
84201
83947
  if (!branchWorkSurvived) {
84202
83948
  try {
84203
- (0, import_node_child_process13.execFileSync)(GIT4, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
83949
+ (0, import_node_child_process10.execFileSync)(GIT2, ["checkout", "-q", "--detach", branchCommit], { cwd: submoduleRepoPath, stdio: "ignore" });
84204
83950
  } catch {
84205
83951
  }
84206
83952
  gitlinks.push({ path: path63, baseCommit, branchCommit, rebasedCommit, action: "rebase_dropped_branch_commits" });
@@ -84257,7 +84003,7 @@ ${cleanBody}`;
84257
84003
  const resolveByPath = new Map(resolutions.map((r) => [r.path, r.rebasedCommit]));
84258
84004
  const runRebase = (args) => {
84259
84005
  try {
84260
- (0, import_node_child_process13.execFileSync)(GIT4, args, {
84006
+ (0, import_node_child_process10.execFileSync)(GIT2, args, {
84261
84007
  cwd: worktreeRoot,
84262
84008
  stdio: ["ignore", "pipe", "pipe"],
84263
84009
  // A rebase editor prompt would hang; keep it non-interactive.
@@ -84270,14 +84016,14 @@ ${cleanBody}`;
84270
84016
  };
84271
84017
  const unmergedPaths = () => {
84272
84018
  try {
84273
- return (0, import_node_child_process13.execFileSync)(GIT4, ["diff", "--name-only", "--diff-filter=U"], { cwd: worktreeRoot, encoding: "utf8" }).split("\n").map((s2) => s2.trim()).filter(Boolean);
84019
+ return (0, import_node_child_process10.execFileSync)(GIT2, ["diff", "--name-only", "--diff-filter=U"], { cwd: worktreeRoot, encoding: "utf8" }).split("\n").map((s2) => s2.trim()).filter(Boolean);
84274
84020
  } catch {
84275
84021
  return [];
84276
84022
  }
84277
84023
  };
84278
84024
  const abort = (reason, conflictPaths) => {
84279
84025
  try {
84280
- (0, import_node_child_process13.execFileSync)(GIT4, ["rebase", "--abort"], { cwd: worktreeRoot, stdio: "ignore" });
84026
+ (0, import_node_child_process10.execFileSync)(GIT2, ["rebase", "--abort"], { cwd: worktreeRoot, stdio: "ignore" });
84281
84027
  } catch {
84282
84028
  }
84283
84029
  return { ok: false, reason, conflictPaths };
@@ -84294,7 +84040,7 @@ ${cleanBody}`;
84294
84040
  if (unresolvable.length > 0) {
84295
84041
  const unresolvableGitlink = unresolvable.some((p) => {
84296
84042
  try {
84297
- const staged = (0, import_node_child_process13.execFileSync)(GIT4, ["ls-files", "--stage", "--", p], { cwd: worktreeRoot, encoding: "utf8" });
84043
+ const staged = (0, import_node_child_process10.execFileSync)(GIT2, ["ls-files", "--stage", "--", p], { cwd: worktreeRoot, encoding: "utf8" });
84298
84044
  return /^160000\s/m.test(staged);
84299
84045
  } catch {
84300
84046
  return false;
@@ -84302,7 +84048,7 @@ ${cleanBody}`;
84302
84048
  });
84303
84049
  const allGitlink = unresolvable.every((p) => {
84304
84050
  try {
84305
- const staged = (0, import_node_child_process13.execFileSync)(GIT4, ["ls-files", "--stage", "--", p], { cwd: worktreeRoot, encoding: "utf8" });
84051
+ const staged = (0, import_node_child_process10.execFileSync)(GIT2, ["ls-files", "--stage", "--", p], { cwd: worktreeRoot, encoding: "utf8" });
84306
84052
  return /^160000\s/m.test(staged);
84307
84053
  } catch {
84308
84054
  return false;
@@ -84313,11 +84059,11 @@ ${cleanBody}`;
84313
84059
  for (const p of conflicts) {
84314
84060
  const commit = resolveByPath.get(p);
84315
84061
  try {
84316
- (0, import_node_child_process13.execFileSync)(GIT4, ["checkout", "-q", "--detach", commit], { cwd: (0, import_path18.resolve)(worktreeRoot, p), stdio: "ignore" });
84062
+ (0, import_node_child_process10.execFileSync)(GIT2, ["checkout", "-q", "--detach", commit], { cwd: (0, import_path17.resolve)(worktreeRoot, p), stdio: "ignore" });
84317
84063
  } catch {
84318
84064
  }
84319
84065
  try {
84320
- (0, import_node_child_process13.execFileSync)(GIT4, ["add", p], { cwd: worktreeRoot, stdio: "ignore" });
84066
+ (0, import_node_child_process10.execFileSync)(GIT2, ["add", p], { cwd: worktreeRoot, stdio: "ignore" });
84321
84067
  } catch {
84322
84068
  return abort("rebase_error", conflicts);
84323
84069
  }
@@ -84326,22 +84072,22 @@ ${cleanBody}`;
84326
84072
  }
84327
84073
  let branchHead;
84328
84074
  try {
84329
- branchHead = (0, import_node_child_process13.execFileSync)(GIT4, ["rev-parse", "HEAD"], { cwd: worktreeRoot, encoding: "utf8" }).trim();
84075
+ branchHead = (0, import_node_child_process10.execFileSync)(GIT2, ["rev-parse", "HEAD"], { cwd: worktreeRoot, encoding: "utf8" }).trim();
84330
84076
  } catch {
84331
84077
  }
84332
84078
  return { ok: true, branchHead };
84333
84079
  }
84334
- var fs54;
84335
- var import_path18;
84336
- var import_node_child_process13;
84080
+ var fs51;
84081
+ var import_path17;
84082
+ var import_node_child_process10;
84337
84083
  var SUBMODULE_PUBLISH_REQUIRED_RECOMMENDED_ACTION;
84338
84084
  var SUBMODULE_PUBLICATION_UNDETERMINABLE_RECOMMENDED_ACTION;
84339
84085
  var init_mesh_refine_submodule_converge = __esm2({
84340
84086
  "src/mesh/mesh-refine-submodule-converge.ts"() {
84341
84087
  "use strict";
84342
- fs54 = __toESM2(require("fs"));
84343
- import_path18 = require("path");
84344
- import_node_child_process13 = require("child_process");
84088
+ fs51 = __toESM2(require("fs"));
84089
+ import_path17 = require("path");
84090
+ import_node_child_process10 = require("child_process");
84345
84091
  init_mesh_refine_gitlink_utils();
84346
84092
  SUBMODULE_PUBLISH_REQUIRED_RECOMMENDED_ACTION = "Publish the branch-side submodule commit(s) to submodule origin main, then rerun mesh_refine_node. Do NOT retry the rebase: the branch was intentionally left unrewritten because a rebase here would mint a submodule commit the reachability gate must reject.";
84347
84093
  SUBMODULE_PUBLICATION_UNDETERMINABLE_RECOMMENDED_ACTION = "Restore access to the submodule remote (the publication check could not be run), then rerun mesh_refine_node. Do NOT publish and do NOT retry the rebase on this evidence: it is unknown whether the branch-side commit is already on origin, so minting or pushing here can synthesize a redundant twin of a published commit.";
@@ -84364,13 +84110,13 @@ ${tail}`;
84364
84110
  }
84365
84111
  function writeValidationFailureLog(workspace, index, candidate, streams, now = () => /* @__PURE__ */ new Date()) {
84366
84112
  try {
84367
- const dir = (0, import_path19.join)(workspace, REFINE_VALIDATION_LOG_DIR);
84368
- fs55.mkdirSync(dir, { recursive: true });
84113
+ const dir = (0, import_path18.join)(workspace, REFINE_VALIDATION_LOG_DIR);
84114
+ fs52.mkdirSync(dir, { recursive: true });
84369
84115
  const stamp = now().toISOString().replace(/[:.]/g, "-");
84370
- const file2 = (0, import_path19.join)(dir, `refine-${stamp}-${index}.log`);
84116
+ const file2 = (0, import_path18.join)(dir, `refine-${stamp}-${index}.log`);
84371
84117
  const asText = (v) => typeof v === "string" ? v : v == null ? "" : String(v);
84372
84118
  const shown = candidate.displayCommand || [candidate.command, ...candidate.args || []].join(" ");
84373
- fs55.writeFileSync(
84119
+ fs52.writeFileSync(
84374
84120
  file2,
84375
84121
  `# refine validation failure
84376
84122
  # command: ${shown}
@@ -84434,13 +84180,13 @@ ${asText(streams.stderr)}
84434
84180
  if (excludePaths.length > 0) {
84435
84181
  diffArgs.push("--", ".", ...excludePaths.map((path63) => `:(exclude)${path63}`));
84436
84182
  }
84437
- const diff = execFileSync16(GIT4, diffArgs, {
84183
+ const diff = execFileSync16(GIT2, diffArgs, {
84438
84184
  cwd,
84439
84185
  encoding: "utf8",
84440
84186
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
84441
84187
  });
84442
84188
  if (!diff.trim()) return "";
84443
- const patchId = execFileSync16(GIT4, ["patch-id", "--stable"], {
84189
+ const patchId = execFileSync16(GIT2, ["patch-id", "--stable"], {
84444
84190
  cwd,
84445
84191
  input: diff,
84446
84192
  encoding: "utf8",
@@ -84452,7 +84198,7 @@ ${asText(streams.stderr)}
84452
84198
  const startedAt = Date.now();
84453
84199
  try {
84454
84200
  const { execFileSync: execFileSync16 } = await import("child_process");
84455
- const git3 = (args) => execFileSync16(GIT4, args, {
84201
+ const git3 = (args) => execFileSync16(GIT2, args, {
84456
84202
  cwd: repoRoot,
84457
84203
  encoding: "utf8",
84458
84204
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -84560,7 +84306,7 @@ ${e?.stderr || ""}`
84560
84306
  ...autoPublish !== void 0 ? { autoPublishSubmoduleMainCommits: autoPublish } : {}
84561
84307
  };
84562
84308
  try {
84563
- const git3 = (args) => (0, import_node_child_process14.execFileSync)(GIT4, args, {
84309
+ const git3 = (args) => (0, import_node_child_process11.execFileSync)(GIT2, args, {
84564
84310
  cwd: repoRoot,
84565
84311
  encoding: "utf8",
84566
84312
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES,
@@ -84700,7 +84446,7 @@ ${e?.stderr || ""}`
84700
84446
  const startedAt = Date.now();
84701
84447
  try {
84702
84448
  const { execFileSync: execFileSync16 } = await import("child_process");
84703
- const git3 = (gitArgs) => execFileSync16(GIT4, gitArgs, {
84449
+ const git3 = (gitArgs) => execFileSync16(GIT2, gitArgs, {
84704
84450
  cwd: repoRoot,
84705
84451
  encoding: "utf8",
84706
84452
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -84765,7 +84511,7 @@ ${mergeTreeErr?.stderr || ""}`;
84765
84511
  const startedAt = Date.now();
84766
84512
  try {
84767
84513
  const { execFileSync: execFileSync16 } = await import("child_process");
84768
- const git3 = (args, opts) => execFileSync16(GIT4, args, {
84514
+ const git3 = (args, opts) => execFileSync16(GIT2, args, {
84769
84515
  cwd: opts?.cwd || repoRoot,
84770
84516
  encoding: "utf8",
84771
84517
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -84840,7 +84586,7 @@ ${mergeTreeErr?.stderr || ""}`;
84840
84586
  };
84841
84587
  }
84842
84588
  function resolveGitDir(repoRoot) {
84843
- const out = (0, import_node_child_process14.execFileSync)(GIT4, ["rev-parse", "--absolute-git-dir"], {
84589
+ const out = (0, import_node_child_process11.execFileSync)(GIT2, ["rev-parse", "--absolute-git-dir"], {
84844
84590
  cwd: repoRoot,
84845
84591
  encoding: "utf8",
84846
84592
  maxBuffer: 1024 * 1024
@@ -84852,7 +84598,7 @@ ${mergeTreeErr?.stderr || ""}`;
84852
84598
  const baseCommit = readTreeObject(repoRoot, baseHead, path63);
84853
84599
  const branchCommit = readTreeObject(repoRoot, branchHead, path63);
84854
84600
  if (!baseCommit || !branchCommit) return false;
84855
- return isSubmoduleFastForward((0, import_path19.resolve)(repoRoot, path63), baseCommit, branchCommit);
84601
+ return isSubmoduleFastForward((0, import_path18.resolve)(repoRoot, path63), baseCommit, branchCommit);
84856
84602
  });
84857
84603
  }
84858
84604
  function collectTrivialFastForwardGitlinkResolutions(worktreeRoot, baseRepoRoot, baseHead, branchHead) {
@@ -84861,8 +84607,8 @@ ${mergeTreeErr?.stderr || ""}`;
84861
84607
  const baseCommit = readTreeObject(baseRepoRoot, baseHead, path63);
84862
84608
  const branchCommit = readTreeObject(worktreeRoot, branchHead, path63);
84863
84609
  if (!baseCommit || !branchCommit) continue;
84864
- const submoduleRepoPath = (0, import_path19.resolve)(worktreeRoot, path63);
84865
- ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path19.resolve)(baseRepoRoot, path63), baseCommit);
84610
+ const submoduleRepoPath = (0, import_path18.resolve)(worktreeRoot, path63);
84611
+ ensureSubmoduleCommitLocal(submoduleRepoPath, (0, import_path18.resolve)(baseRepoRoot, path63), baseCommit);
84866
84612
  if (baseCommit === branchCommit) {
84867
84613
  continue;
84868
84614
  }
@@ -84878,7 +84624,7 @@ ${mergeTreeErr?.stderr || ""}`;
84878
84624
  const changedGitlinks = readChangedGitlinkPaths(repoRoot, baseHead, branchHead).map((path63) => {
84879
84625
  const baseCommit = readTreeObject(repoRoot, baseHead, path63);
84880
84626
  const branchCommit = readTreeObject(repoRoot, branchHead, path63);
84881
- const submoduleRepoPath = (0, import_path19.resolve)(repoRoot, path63);
84627
+ const submoduleRepoPath = (0, import_path18.resolve)(repoRoot, path63);
84882
84628
  const probe = !!baseCommit && !!branchCommit ? probeSubmoduleFastForward(submoduleRepoPath, baseCommit, branchCommit) : "undeterminable";
84883
84629
  return {
84884
84630
  path: path63,
@@ -84903,7 +84649,7 @@ ${mergeTreeErr?.stderr || ""}`;
84903
84649
  }
84904
84650
  let mergeBase = "";
84905
84651
  try {
84906
- mergeBase = (0, import_node_child_process14.execFileSync)(GIT4, ["merge-base", baseHead, branchHead], {
84652
+ mergeBase = (0, import_node_child_process11.execFileSync)(GIT2, ["merge-base", baseHead, branchHead], {
84907
84653
  cwd: repoRoot,
84908
84654
  encoding: "utf8",
84909
84655
  maxBuffer: 1024 * 1024
@@ -84933,7 +84679,7 @@ ${mergeTreeErr?.stderr || ""}`;
84933
84679
  }
84934
84680
  function buildTreeWithGitlinksEqualized(repoRoot, commitish, paths, placeholderCommit) {
84935
84681
  try {
84936
- const tree = (0, import_node_child_process14.execFileSync)(GIT4, ["rev-parse", `${commitish}^{tree}`], {
84682
+ const tree = (0, import_node_child_process11.execFileSync)(GIT2, ["rev-parse", `${commitish}^{tree}`], {
84937
84683
  cwd: repoRoot,
84938
84684
  encoding: "utf8",
84939
84685
  maxBuffer: 1024 * 1024
@@ -84941,11 +84687,11 @@ ${mergeTreeErr?.stderr || ""}`;
84941
84687
  if (!tree) return void 0;
84942
84688
  const updates = paths.map((path63) => `160000 commit ${placeholderCommit} ${path63}`).join("\n");
84943
84689
  if (!updates) return tree;
84944
- const tmpIndex = (0, import_path19.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
84690
+ const tmpIndex = (0, import_path18.join)(resolveGitDir(repoRoot), `adhdev-refine-eq-${commitish.slice(0, 12)}.index`);
84945
84691
  const env2 = { ...process.env, GIT_INDEX_FILE: tmpIndex };
84946
84692
  try {
84947
- (0, import_node_child_process14.execFileSync)(GIT4, ["read-tree", tree], { cwd: repoRoot, env: env2, stdio: "ignore" });
84948
- (0, import_node_child_process14.execFileSync)(GIT4, ["update-index", "--index-info"], {
84693
+ (0, import_node_child_process11.execFileSync)(GIT2, ["read-tree", tree], { cwd: repoRoot, env: env2, stdio: "ignore" });
84694
+ (0, import_node_child_process11.execFileSync)(GIT2, ["update-index", "--index-info"], {
84949
84695
  cwd: repoRoot,
84950
84696
  env: env2,
84951
84697
  input: `${updates}
@@ -84953,11 +84699,11 @@ ${mergeTreeErr?.stderr || ""}`;
84953
84699
  encoding: "utf8",
84954
84700
  stdio: ["pipe", "ignore", "ignore"]
84955
84701
  });
84956
- const newTree = (0, import_node_child_process14.execFileSync)(GIT4, ["write-tree"], { cwd: repoRoot, env: env2, encoding: "utf8" }).trim();
84702
+ const newTree = (0, import_node_child_process11.execFileSync)(GIT2, ["write-tree"], { cwd: repoRoot, env: env2, encoding: "utf8" }).trim();
84957
84703
  return newTree || void 0;
84958
84704
  } finally {
84959
84705
  try {
84960
- fs55.rmSync(tmpIndex, { force: true });
84706
+ fs52.rmSync(tmpIndex, { force: true });
84961
84707
  } catch {
84962
84708
  }
84963
84709
  }
@@ -84969,7 +84715,7 @@ ${mergeTreeErr?.stderr || ""}`;
84969
84715
  try {
84970
84716
  const branchGitlinks = gitlinks.filter((entry) => entry.branchCommit);
84971
84717
  const gitlinkPaths = branchGitlinks.map((entry) => entry.path);
84972
- const mergeBase = (0, import_node_child_process14.execFileSync)(GIT4, ["merge-base", baseHead, branchHead], {
84718
+ const mergeBase = (0, import_node_child_process11.execFileSync)(GIT2, ["merge-base", baseHead, branchHead], {
84973
84719
  cwd: repoRoot,
84974
84720
  encoding: "utf8",
84975
84721
  maxBuffer: 1024 * 1024
@@ -84982,22 +84728,22 @@ ${mergeTreeErr?.stderr || ""}`;
84982
84728
  const theirsEqTree = buildTreeWithGitlinksEqualized(repoRoot, branchHead, gitlinkPaths, placeholder);
84983
84729
  if (baseEqTree && oursEqTree && theirsEqTree) {
84984
84730
  try {
84985
- const baseEqCommit = (0, import_node_child_process14.execFileSync)(GIT4, ["commit-tree", baseEqTree, "-m", "refine-ff-base"], {
84731
+ const baseEqCommit = (0, import_node_child_process11.execFileSync)(GIT2, ["commit-tree", baseEqTree, "-m", "refine-ff-base"], {
84986
84732
  cwd: repoRoot,
84987
84733
  encoding: "utf8",
84988
84734
  maxBuffer: 1024 * 1024
84989
84735
  }).trim();
84990
- const oursEqCommit = (0, import_node_child_process14.execFileSync)(GIT4, ["commit-tree", oursEqTree, "-p", baseEqCommit, "-m", "refine-ff-ours"], {
84736
+ const oursEqCommit = (0, import_node_child_process11.execFileSync)(GIT2, ["commit-tree", oursEqTree, "-p", baseEqCommit, "-m", "refine-ff-ours"], {
84991
84737
  cwd: repoRoot,
84992
84738
  encoding: "utf8",
84993
84739
  maxBuffer: 1024 * 1024
84994
84740
  }).trim();
84995
- const theirsEqCommit = (0, import_node_child_process14.execFileSync)(GIT4, ["commit-tree", theirsEqTree, "-p", baseEqCommit, "-m", "refine-ff-theirs"], {
84741
+ const theirsEqCommit = (0, import_node_child_process11.execFileSync)(GIT2, ["commit-tree", theirsEqTree, "-p", baseEqCommit, "-m", "refine-ff-theirs"], {
84996
84742
  cwd: repoRoot,
84997
84743
  encoding: "utf8",
84998
84744
  maxBuffer: 1024 * 1024
84999
84745
  }).trim();
85000
- const mergeOut = (0, import_node_child_process14.execFileSync)(GIT4, ["merge-tree", "--write-tree", oursEqCommit, theirsEqCommit], {
84746
+ const mergeOut = (0, import_node_child_process11.execFileSync)(GIT2, ["merge-tree", "--write-tree", oursEqCommit, theirsEqCommit], {
85001
84747
  cwd: repoRoot,
85002
84748
  encoding: "utf8",
85003
84749
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES
@@ -85008,7 +84754,7 @@ ${mergeTreeErr?.stderr || ""}`;
85008
84754
  }
85009
84755
  }
85010
84756
  }
85011
- const contentTree = mergedContentTree || (0, import_node_child_process14.execFileSync)(GIT4, ["rev-parse", `${baseHead}^{tree}`], {
84757
+ const contentTree = mergedContentTree || (0, import_node_child_process11.execFileSync)(GIT2, ["rev-parse", `${baseHead}^{tree}`], {
85012
84758
  cwd: repoRoot,
85013
84759
  encoding: "utf8",
85014
84760
  maxBuffer: 1024 * 1024
@@ -85016,11 +84762,11 @@ ${mergeTreeErr?.stderr || ""}`;
85016
84762
  if (!contentTree) return void 0;
85017
84763
  const updates = branchGitlinks.map((entry) => `160000 commit ${entry.branchCommit} ${entry.path}`).join("\n");
85018
84764
  if (!updates) return contentTree;
85019
- const tmpIndex = (0, import_path19.join)(resolveGitDir(repoRoot), `adhdev-refine-ff-${baseHead.slice(0, 12)}-${branchHead.slice(0, 12)}.index`);
84765
+ const tmpIndex = (0, import_path18.join)(resolveGitDir(repoRoot), `adhdev-refine-ff-${baseHead.slice(0, 12)}-${branchHead.slice(0, 12)}.index`);
85020
84766
  const env2 = { ...process.env, GIT_INDEX_FILE: tmpIndex };
85021
84767
  try {
85022
- (0, import_node_child_process14.execFileSync)(GIT4, ["read-tree", contentTree], { cwd: repoRoot, env: env2, stdio: "ignore" });
85023
- (0, import_node_child_process14.execFileSync)(GIT4, ["update-index", "--index-info"], {
84768
+ (0, import_node_child_process11.execFileSync)(GIT2, ["read-tree", contentTree], { cwd: repoRoot, env: env2, stdio: "ignore" });
84769
+ (0, import_node_child_process11.execFileSync)(GIT2, ["update-index", "--index-info"], {
85024
84770
  cwd: repoRoot,
85025
84771
  env: env2,
85026
84772
  input: `${updates}
@@ -85028,11 +84774,11 @@ ${mergeTreeErr?.stderr || ""}`;
85028
84774
  encoding: "utf8",
85029
84775
  stdio: ["pipe", "ignore", "ignore"]
85030
84776
  });
85031
- const newTree = (0, import_node_child_process14.execFileSync)(GIT4, ["write-tree"], { cwd: repoRoot, env: env2, encoding: "utf8" }).trim();
84777
+ const newTree = (0, import_node_child_process11.execFileSync)(GIT2, ["write-tree"], { cwd: repoRoot, env: env2, encoding: "utf8" }).trim();
85032
84778
  return newTree || void 0;
85033
84779
  } finally {
85034
84780
  try {
85035
- fs55.rmSync(tmpIndex, { force: true });
84781
+ fs52.rmSync(tmpIndex, { force: true });
85036
84782
  } catch {
85037
84783
  }
85038
84784
  }
@@ -85066,10 +84812,10 @@ ${mergeTreeErr?.stderr || ""}`;
85066
84812
  }
85067
84813
  const commandArgs = ["submodule", "update", "--init", "--recursive", "--", ...updatePaths];
85068
84814
  try {
85069
- const { execFile: execFile8 } = await import("child_process");
85070
- const { promisify: promisify11 } = await import("util");
85071
- const execFileAsync7 = promisify11(execFile8);
85072
- const result = await execFileAsync7(GIT4, commandArgs, {
84815
+ const { execFile: execFile9 } = await import("child_process");
84816
+ const { promisify: promisify12 } = await import("util");
84817
+ const execFileAsync8 = promisify12(execFile9);
84818
+ const result = await execFileAsync8(GIT2, commandArgs, {
85073
84819
  cwd: repoRoot,
85074
84820
  encoding: "utf8",
85075
84821
  maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES,
@@ -85115,11 +84861,11 @@ ${mergeTreeErr?.stderr || ""}`;
85115
84861
  const startedAt = Date.now();
85116
84862
  const entries = [];
85117
84863
  try {
85118
- const { execFile: execFile8 } = await import("child_process");
85119
- const { promisify: promisify11 } = await import("util");
85120
- const execFileAsync7 = promisify11(execFile8);
85121
- const runGit3 = async (cwd, args) => {
85122
- const { stdout } = await execFileAsync7(GIT4, args, {
84864
+ const { execFile: execFile9 } = await import("child_process");
84865
+ const { promisify: promisify12 } = await import("util");
84866
+ const execFileAsync8 = promisify12(execFile9);
84867
+ const runGit4 = async (cwd, args) => {
84868
+ const { stdout } = await execFileAsync8(GIT2, args, {
85123
84869
  cwd,
85124
84870
  encoding: "utf8",
85125
84871
  timeout: 3e4,
@@ -85128,10 +84874,10 @@ ${mergeTreeErr?.stderr || ""}`;
85128
84874
  });
85129
84875
  return String(stdout || "");
85130
84876
  };
85131
- const verifyRemoteMainContainsCommit = (submodulePath, commit, branch = "main") => verifyRemoteBranchContainsCommit(runGit3, submodulePath, commit, branch);
84877
+ const verifyRemoteMainContainsCommit = (submodulePath, commit, branch = "main") => verifyRemoteBranchContainsCommit(runGit4, submodulePath, commit, branch);
85132
84878
  const publishCommitToRemoteMain = async (submodulePath, commit, branch = "main") => {
85133
84879
  const refspec = `${commit}:refs/heads/${branch}`;
85134
- const { stdout, stderr } = await execFileAsync7(GIT4, ["push", "origin", refspec], {
84880
+ const { stdout, stderr } = await execFileAsync8(GIT2, ["push", "origin", refspec], {
85135
84881
  cwd: submodulePath,
85136
84882
  encoding: "utf8",
85137
84883
  timeout: 3e4,
@@ -85141,25 +84887,25 @@ ${mergeTreeErr?.stderr || ""}`;
85141
84887
  return { stdout: String(stdout || ""), stderr: String(stderr || ""), refspec };
85142
84888
  };
85143
84889
  const importCommitFromWorktreeSubmodule = async (submodulePath, worktreeSubmodulePath, commit) => {
85144
- if (!fs55.existsSync(worktreeSubmodulePath)) return false;
84890
+ if (!fs52.existsSync(worktreeSubmodulePath)) return false;
85145
84891
  try {
85146
- await runGit3(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
84892
+ await runGit4(worktreeSubmodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
85147
84893
  } catch {
85148
84894
  return false;
85149
84895
  }
85150
- await runGit3(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
85151
- await runGit3(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
84896
+ await runGit4(submodulePath, ["-c", "protocol.file.allow=always", "fetch", worktreeSubmodulePath, commit]);
84897
+ await runGit4(submodulePath, ["cat-file", "-e", `${commit}^{commit}`]);
85152
84898
  return true;
85153
84899
  };
85154
84900
  const findEquivalentPublishedCommit = async (submodulePath, commit, remoteRef) => {
85155
84901
  try {
85156
- const targetTree = (await runGit3(submodulePath, ["rev-parse", `${commit}^{tree}`])).trim();
84902
+ const targetTree = (await runGit4(submodulePath, ["rev-parse", `${commit}^{tree}`])).trim();
85157
84903
  if (!targetTree) return void 0;
85158
- const candidates = (await runGit3(submodulePath, ["rev-list", "--max-count=100", remoteRef])).split("\n").map((s2) => s2.trim()).filter(Boolean);
84904
+ const candidates = (await runGit4(submodulePath, ["rev-list", "--max-count=100", remoteRef])).split("\n").map((s2) => s2.trim()).filter(Boolean);
85159
84905
  for (const candidate of candidates) {
85160
84906
  let tree = "";
85161
84907
  try {
85162
- tree = (await runGit3(submodulePath, ["rev-parse", `${candidate}^{tree}`])).trim();
84908
+ tree = (await runGit4(submodulePath, ["rev-parse", `${candidate}^{tree}`])).trim();
85163
84909
  } catch {
85164
84910
  continue;
85165
84911
  }
@@ -85169,13 +84915,13 @@ ${mergeTreeErr?.stderr || ""}`;
85169
84915
  }
85170
84916
  return void 0;
85171
84917
  };
85172
- const treeOutput = await runGit3(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
84918
+ const treeOutput = await runGit4(repoRoot, ["ls-tree", "-r", "-z", mergedTree]);
85173
84919
  const gitlinks = treeOutput.split("\0").filter(Boolean).map((record2) => {
85174
84920
  const match = /^160000\s+commit\s+([0-9a-f]{40})\t(.+)$/.exec(record2);
85175
84921
  return match ? { commit: match[1], path: match[2] } : null;
85176
84922
  }).filter((entry) => !!entry);
85177
84923
  for (const gitlink of gitlinks) {
85178
- const submodulePath = (0, import_path19.resolve)(repoRoot, gitlink.path);
84924
+ const submodulePath = (0, import_path18.resolve)(repoRoot, gitlink.path);
85179
84925
  const entry = {
85180
84926
  path: gitlink.path,
85181
84927
  commit: gitlink.commit,
@@ -85183,7 +84929,7 @@ ${mergeTreeErr?.stderr || ""}`;
85183
84929
  };
85184
84930
  let submoduleDefaultBranch = "main";
85185
84931
  try {
85186
- if (!fs55.existsSync(submodulePath)) {
84932
+ if (!fs52.existsSync(submodulePath)) {
85187
84933
  entry.error = `Submodule checkout missing at ${gitlink.path}`;
85188
84934
  entry.publishRequired = true;
85189
84935
  if (options.allowAutoPublishSubmoduleMainCommits === true) {
@@ -85196,13 +84942,13 @@ ${mergeTreeErr?.stderr || ""}`;
85196
84942
  }
85197
84943
  entry.checkedLocal = true;
85198
84944
  try {
85199
- await runGit3(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
84945
+ await runGit4(submodulePath, ["cat-file", "-e", `${gitlink.commit}^{commit}`]);
85200
84946
  entry.localReachable = true;
85201
84947
  } catch {
85202
84948
  entry.localReachable = false;
85203
84949
  if (options.allowAutoPublishSubmoduleMainCommits === true && options.worktreeRoot) {
85204
84950
  try {
85205
- const imported = await importCommitFromWorktreeSubmodule(submodulePath, (0, import_path19.resolve)(options.worktreeRoot, gitlink.path), gitlink.commit);
84951
+ const imported = await importCommitFromWorktreeSubmodule(submodulePath, (0, import_path18.resolve)(options.worktreeRoot, gitlink.path), gitlink.commit);
85206
84952
  if (imported) {
85207
84953
  entry.localReachable = true;
85208
84954
  entry.importedFromWorktree = true;
@@ -85216,7 +84962,7 @@ ${mergeTreeErr?.stderr || ""}`;
85216
84962
  entry.remote = "origin";
85217
84963
  let remoteUrl = "";
85218
84964
  try {
85219
- remoteUrl = (await runGit3(submodulePath, ["remote", "get-url", "origin"])).trim();
84965
+ remoteUrl = (await runGit4(submodulePath, ["remote", "get-url", "origin"])).trim();
85220
84966
  if (!remoteUrl) throw new Error("origin remote has no URL");
85221
84967
  entry.remoteUrl = remoteUrl;
85222
84968
  } catch {
@@ -85373,9 +85119,9 @@ ${mergeTreeErr?.stderr || ""}`;
85373
85119
  };
85374
85120
  }
85375
85121
  async function runMeshRefineValidationGate(mesh, workspace, opts) {
85376
- const { execFile: execFile8 } = await import("child_process");
85377
- const { promisify: promisify11 } = await import("util");
85378
- const execFileAsync7 = promisify11(execFile8);
85122
+ const { execFile: execFile9 } = await import("child_process");
85123
+ const { promisify: promisify12 } = await import("util");
85124
+ const execFileAsync8 = promisify12(execFile9);
85379
85125
  const selection = resolveMeshRefineValidationPlan(mesh, workspace);
85380
85126
  const summary = {
85381
85127
  status: "skipped",
@@ -85454,13 +85200,13 @@ ${mergeTreeErr?.stderr || ""}`;
85454
85200
  ...extras
85455
85201
  });
85456
85202
  const isPackageManagerValidation = (candidate) => {
85457
- const command = (0, import_path19.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
85203
+ const command = (0, import_path18.basename)(candidate.command).replace(/\.(?:cmd|exe)$/i, "");
85458
85204
  return ["npm", "pnpm", "yarn", "bun"].includes(command) && candidate.args.some((arg) => arg === "run" || arg === "test" || arg === "exec");
85459
85205
  };
85460
85206
  const dependenciesLikelyMissing = (cwd) => {
85461
- if (!fs55.existsSync((0, import_path19.join)(cwd, "package.json"))) return false;
85462
- if (fs55.existsSync((0, import_path19.join)(cwd, "node_modules"))) return false;
85463
- return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs55.existsSync((0, import_path19.join)(cwd, lock)));
85207
+ if (!fs52.existsSync((0, import_path18.join)(cwd, "package.json"))) return false;
85208
+ if (fs52.existsSync((0, import_path18.join)(cwd, "node_modules"))) return false;
85209
+ return ["package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((lock) => fs52.existsSync((0, import_path18.join)(cwd, lock)));
85464
85210
  };
85465
85211
  const needsNodeModules = (candidate, cwd) => isPackageManagerValidation(candidate) && dependenciesLikelyMissing(cwd);
85466
85212
  const isDaemonScopedCommand = (candidate) => {
@@ -85527,12 +85273,12 @@ ${mergeTreeErr?.stderr || ""}`;
85527
85273
  summary.bootstrap = { stage: "legacy" };
85528
85274
  for (const candidate of selection.bootstrapCommands) {
85529
85275
  const startedAt = Date.now();
85530
- const cwd = candidate.cwd ? (0, import_path19.resolve)(workspace, candidate.cwd) : workspace;
85276
+ const cwd = candidate.cwd ? (0, import_path18.resolve)(workspace, candidate.cwd) : workspace;
85531
85277
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
85532
85278
  const resolvedCommand = resolveWin32Executable(candidate.command);
85533
85279
  const spawn7 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
85534
85280
  try {
85535
- const result = await execFileAsync7(spawn7.file, spawn7.args, {
85281
+ const result = await execFileAsync8(spawn7.file, spawn7.args, {
85536
85282
  cwd,
85537
85283
  encoding: "utf8",
85538
85284
  timeout,
@@ -85560,7 +85306,7 @@ ${mergeTreeErr?.stderr || ""}`;
85560
85306
  let missingDepsBlocked = false;
85561
85307
  for (const candidate of commandsToRun) {
85562
85308
  const startedAt = Date.now();
85563
- const cwd = candidate.cwd ? (0, import_path19.resolve)(workspace, candidate.cwd) : workspace;
85309
+ const cwd = candidate.cwd ? (0, import_path18.resolve)(workspace, candidate.cwd) : workspace;
85564
85310
  const timeout = candidate.timeoutMs || REFINE_VALIDATION_TIMEOUT_MS;
85565
85311
  const bootstrapProvidedDependencies = summary.bootstrap?.stage === "cached" || summary.bootstrap?.stage === "ran" || summary.bootstrap?.stage === "legacy";
85566
85312
  if (!bootstrapProvidedDependencies && needsNodeModules(candidate, cwd)) {
@@ -85577,7 +85323,7 @@ ${mergeTreeErr?.stderr || ""}`;
85577
85323
  const resolvedCommand = resolveWin32Executable(candidate.command);
85578
85324
  const spawn7 = buildWin32ExecFileSpawn(resolvedCommand, candidate.args);
85579
85325
  try {
85580
- const result = await execFileAsync7(spawn7.file, spawn7.args, {
85326
+ const result = await execFileAsync8(spawn7.file, spawn7.args, {
85581
85327
  cwd,
85582
85328
  encoding: "utf8",
85583
85329
  timeout,
@@ -85627,9 +85373,9 @@ ${mergeTreeErr?.stderr || ""}`;
85627
85373
  summary.status = "passed";
85628
85374
  return summary;
85629
85375
  }
85630
- var import_path19;
85631
- var fs55;
85632
- var import_node_child_process14;
85376
+ var import_path18;
85377
+ var fs52;
85378
+ var import_node_child_process11;
85633
85379
  var REFINE_VALIDATION_TIMEOUT_MS;
85634
85380
  var REFINE_VALIDATION_OUTPUT_LIMIT_BYTES;
85635
85381
  var REFINE_VALIDATION_SUMMARY_HEAD_CHARS;
@@ -85642,9 +85388,9 @@ ${mergeTreeErr?.stderr || ""}`;
85642
85388
  init_git_status();
85643
85389
  init_refine_config();
85644
85390
  init_worktree_bootstrap_config();
85645
- import_path19 = require("path");
85646
- fs55 = __toESM2(require("fs"));
85647
- import_node_child_process14 = require("child_process");
85391
+ import_path18 = require("path");
85392
+ fs52 = __toESM2(require("fs"));
85393
+ import_node_child_process11 = require("child_process");
85648
85394
  init_resolve_executable();
85649
85395
  init_mesh_refine_worker_cap();
85650
85396
  init_mesh_refine_gitlink_utils();
@@ -85655,7 +85401,597 @@ ${mergeTreeErr?.stderr || ""}`;
85655
85401
  REFINE_VALIDATION_SUMMARY_HEAD_CHARS = 2e3;
85656
85402
  REFINE_VALIDATION_SUMMARY_TAIL_CHARS = 6e3;
85657
85403
  REFINE_VALIDATION_SUMMARY_CHARS = REFINE_VALIDATION_SUMMARY_HEAD_CHARS + REFINE_VALIDATION_SUMMARY_TAIL_CHARS;
85658
- REFINE_VALIDATION_LOG_DIR = (0, import_path19.join)(".adhdev", "logs");
85404
+ REFINE_VALIDATION_LOG_DIR = (0, import_path18.join)(".adhdev", "logs");
85405
+ }
85406
+ });
85407
+ async function runMeshRefineSubmoduleReachabilityPreflight(args) {
85408
+ const startedAt = Date.now();
85409
+ const touched = args.touchedSubmodulePaths ?? readChangedGitlinkPaths(args.worktreeRoot, args.baseRef, args.branchRef);
85410
+ if (touched.length === 0) return void 0;
85411
+ const entries = [];
85412
+ for (const path63 of touched) {
85413
+ const probedRepo = (0, import_path19.resolve)(args.worktreeRoot, path63);
85414
+ const commit = readTreeObject(args.worktreeRoot, args.branchRef, path63);
85415
+ if (!commit) {
85416
+ entries.push({
85417
+ path: path63,
85418
+ verdict: "undeterminable",
85419
+ probedRepo,
85420
+ error: `No gitlink commit recorded at '${path63}' on ${args.branchRef}`
85421
+ });
85422
+ continue;
85423
+ }
85424
+ let remoteMainBranch = "main";
85425
+ try {
85426
+ remoteMainBranch = await resolveSubmoduleDefaultBranch({
85427
+ submoduleRepoPath: probedRepo,
85428
+ superprojectWorkspace: args.worktreeRoot,
85429
+ submodulePath: path63
85430
+ });
85431
+ } catch {
85432
+ }
85433
+ const verdict = await verifyRemoteBranchContainsCommit(runGit2, probedRepo, commit, remoteMainBranch);
85434
+ if (verdict.state === "contained") {
85435
+ entries.push({ path: path63, commit, verdict: "reachable", remoteMainBranch, probedRepo });
85436
+ } else if (verdict.state === "absent") {
85437
+ entries.push({
85438
+ path: path63,
85439
+ commit,
85440
+ verdict: "unreachable",
85441
+ remoteMainBranch,
85442
+ probedRepo,
85443
+ error: `Submodule gitlink commit is not reachable from origin/${remoteMainBranch} (publish required before the root branch can merge).`
85444
+ });
85445
+ } else {
85446
+ entries.push({
85447
+ path: path63,
85448
+ commit,
85449
+ verdict: "undeterminable",
85450
+ remoteMainBranch,
85451
+ probedRepo,
85452
+ error: `Reachability against origin/${remoteMainBranch} could not be determined (the submodule remote was not successfully consulted). This is NOT evidence the commit is unpublished.`
85453
+ });
85454
+ }
85455
+ }
85456
+ const blocked = entries.filter((entry) => entry.verdict !== "reachable");
85457
+ const summary = {
85458
+ status: blocked.length ? "warning" : "passed",
85459
+ checked: entries.length,
85460
+ entries,
85461
+ durationMs: Date.now() - startedAt
85462
+ };
85463
+ if (blocked.length) {
85464
+ const gateEntries = blocked.map((entry) => ({
85465
+ path: entry.path,
85466
+ commit: entry.commit || "",
85467
+ reachable: false,
85468
+ publishRequired: entry.verdict === "unreachable",
85469
+ ...entry.verdict === "undeterminable" ? { remoteMainUndeterminable: true } : {}
85470
+ }));
85471
+ summary.nextStep = buildSubmodulePublishRequiredNextStep(gateEntries);
85472
+ }
85473
+ return summary;
85474
+ }
85475
+ async function resolveRefinePlanBaseRef(repoRoot) {
85476
+ let baseBranch = "main";
85477
+ try {
85478
+ const { stdout } = await execFileAsync5(GIT2, ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" });
85479
+ if (stdout.trim()) baseBranch = stdout.trim();
85480
+ } catch {
85481
+ }
85482
+ try {
85483
+ await execFileAsync5(GIT2, ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8" });
85484
+ } catch {
85485
+ }
85486
+ try {
85487
+ const { stdout } = await execFileAsync5(GIT2, ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8" });
85488
+ if (stdout.trim()) return stdout.trim();
85489
+ } catch {
85490
+ }
85491
+ try {
85492
+ const { stdout } = await execFileAsync5(GIT2, ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" });
85493
+ if (stdout.trim()) return stdout.trim();
85494
+ } catch {
85495
+ }
85496
+ return "HEAD";
85497
+ }
85498
+ async function planMeshRefineNodeSubmodulePreflight(args) {
85499
+ const { mesh, node } = args;
85500
+ const workspace = typeof node?.workspace === "string" ? node.workspace : "";
85501
+ if (!workspace) return void 0;
85502
+ const allNodes = Array.isArray(mesh?.nodes) ? mesh.nodes : [];
85503
+ const sourceNode = node.clonedFromNodeId ? allNodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : allNodes.find((n) => !n.isLocalWorktree);
85504
+ const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
85505
+ if (!repoRoot) return void 0;
85506
+ let branch = typeof node.worktreeBranch === "string" ? node.worktreeBranch : "";
85507
+ try {
85508
+ const { stdout } = await execFileAsync5(GIT2, ["branch", "--show-current"], { cwd: workspace, encoding: "utf8" });
85509
+ if (stdout.trim()) branch = stdout.trim();
85510
+ } catch {
85511
+ }
85512
+ if (!branch) return void 0;
85513
+ let branchRef = branch;
85514
+ try {
85515
+ const { stdout } = await execFileAsync5(GIT2, ["rev-parse", branch], { cwd: workspace, encoding: "utf8" });
85516
+ branchRef = stdout.trim() || branch;
85517
+ } catch {
85518
+ }
85519
+ const baseRef = await resolveRefinePlanBaseRef(repoRoot);
85520
+ return runMeshRefineSubmoduleReachabilityPreflight({
85521
+ worktreeRoot: workspace,
85522
+ baseRef,
85523
+ branchRef,
85524
+ ...args.touchedSubmodulePaths ? { touchedSubmodulePaths: args.touchedSubmodulePaths } : {}
85525
+ });
85526
+ }
85527
+ async function buildMeshRefineBatchDryRunResult(args) {
85528
+ const { mesh, orderedNodes, ordering } = args;
85529
+ const warnings = [];
85530
+ for (const node of orderedNodes) {
85531
+ const area = ordering.changeAreas[node.id];
85532
+ if (!area?.touchesSubmodule || area.error) continue;
85533
+ let preflight;
85534
+ try {
85535
+ preflight = await planMeshRefineNodeSubmodulePreflight({
85536
+ mesh,
85537
+ node,
85538
+ touchedSubmodulePaths: area.touchedSubmodulePaths
85539
+ });
85540
+ } catch {
85541
+ }
85542
+ if (!preflight) continue;
85543
+ area.submoduleReachabilityPreflight = preflight;
85544
+ if (preflight.status === "warning") {
85545
+ warnings.push(`Node ${area.nodeId}: submodule reachability preflight warns \u2014 ${preflight.nextStep || "see changeAreas for details."}`);
85546
+ }
85547
+ }
85548
+ return {
85549
+ success: true,
85550
+ batch: true,
85551
+ dryRun: true,
85552
+ nodeCount: orderedNodes.length,
85553
+ order: ordering.order,
85554
+ orderingRationale: ordering.rationale,
85555
+ changeAreas: ordering.changeAreas,
85556
+ plan: orderedNodes.map((node) => ({
85557
+ nodeId: node.id,
85558
+ workspace: node.workspace,
85559
+ validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
85560
+ mergeWillRun: false
85561
+ })),
85562
+ ...warnings.length ? { submodulePreflightWarnings: warnings } : {},
85563
+ note: "Dry-run: no validation, rebase, or merge was executed. Re-run with execute=true to converge nodes in this order."
85564
+ };
85565
+ }
85566
+ var import_node_child_process12;
85567
+ var import_node_util6;
85568
+ var import_path19;
85569
+ var execFileAsync5;
85570
+ var runGit2;
85571
+ var init_mesh_refine_submodule_preflight = __esm2({
85572
+ "src/mesh/mesh-refine-submodule-preflight.ts"() {
85573
+ "use strict";
85574
+ import_node_child_process12 = require("child_process");
85575
+ import_node_util6 = require("util");
85576
+ import_path19 = require("path");
85577
+ init_dist();
85578
+ init_mesh_refine_gitlink_utils();
85579
+ init_mesh_refine_gates();
85580
+ init_worktree_bootstrap_config();
85581
+ execFileAsync5 = (0, import_node_util6.promisify)(import_node_child_process12.execFile);
85582
+ runGit2 = async (cwd, args) => {
85583
+ const { stdout } = await execFileAsync5(GIT2, args, {
85584
+ cwd,
85585
+ encoding: "utf8",
85586
+ timeout: 3e4,
85587
+ maxBuffer: REFINE_PATCH_EQUIVALENCE_OUTPUT_LIMIT_BYTES,
85588
+ windowsHide: true
85589
+ });
85590
+ return String(stdout || "");
85591
+ };
85592
+ }
85593
+ });
85594
+ function topLevel(path63) {
85595
+ const slash = path63.indexOf("/");
85596
+ return slash === -1 ? path63 : path63.slice(0, slash);
85597
+ }
85598
+ async function analyzeMeshRefineNodeChangeArea(args) {
85599
+ const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
85600
+ const base = {
85601
+ nodeId,
85602
+ workspace,
85603
+ branch,
85604
+ changedTopLevelPaths: [],
85605
+ changedFiles: [],
85606
+ touchedSubmodulePaths: [],
85607
+ touchesSubmodule: false,
85608
+ aheadCount: 0
85609
+ };
85610
+ try {
85611
+ let mergeBase = baseRef;
85612
+ try {
85613
+ const { stdout } = await execFileAsync6(GIT3, ["merge-base", baseRef, branchRef], { cwd: diffCwd, encoding: "utf8" });
85614
+ const resolved = stdout.trim();
85615
+ if (resolved) mergeBase = resolved;
85616
+ } catch {
85617
+ }
85618
+ const { stdout: countStdout } = await execFileAsync6(
85619
+ GIT3,
85620
+ ["rev-list", "--count", `${mergeBase}..${branchRef}`],
85621
+ { cwd: diffCwd, encoding: "utf8" }
85622
+ );
85623
+ base.aheadCount = Number.parseInt(countStdout.trim(), 10) || 0;
85624
+ const { stdout: nameStdout } = await execFileAsync6(
85625
+ GIT3,
85626
+ ["diff", "--name-only", `${mergeBase}..${branchRef}`],
85627
+ { cwd: diffCwd, encoding: "utf8" }
85628
+ );
85629
+ const files = nameStdout.split("\n").map((line) => line.trim()).filter(Boolean).slice(0, MAX_CHANGED_FILES2);
85630
+ base.changedFiles = files;
85631
+ const topSet = /* @__PURE__ */ new Set();
85632
+ const submoduleSet = /* @__PURE__ */ new Set();
85633
+ for (const file2 of files) {
85634
+ const top = topLevel(file2);
85635
+ topSet.add(top);
85636
+ if (submodulePaths.has(file2) || submodulePaths.has(top)) {
85637
+ submoduleSet.add(submodulePaths.has(file2) ? file2 : top);
85638
+ }
85639
+ }
85640
+ base.changedTopLevelPaths = [...topSet].sort();
85641
+ base.touchedSubmodulePaths = [...submoduleSet].sort();
85642
+ base.touchesSubmodule = submoduleSet.size > 0;
85643
+ return base;
85644
+ } catch (e) {
85645
+ base.error = e?.message || String(e);
85646
+ return base;
85647
+ }
85648
+ }
85649
+ function orderMeshRefineBatchNodes(changeAreas) {
85650
+ const areaById = {};
85651
+ for (const area of changeAreas) areaById[area.nodeId] = area;
85652
+ const ranked = [...changeAreas].sort((a, b) => {
85653
+ const aSub = a.touchesSubmodule ? 1 : 0;
85654
+ const bSub = b.touchesSubmodule ? 1 : 0;
85655
+ if (aSub !== bSub) return aSub - bSub;
85656
+ const aBreadth = a.changedTopLevelPaths.length;
85657
+ const bBreadth = b.changedTopLevelPaths.length;
85658
+ if (aBreadth !== bBreadth) return aBreadth - bBreadth;
85659
+ return a.nodeId.localeCompare(b.nodeId);
85660
+ });
85661
+ const rationale = [];
85662
+ const nonSub = ranked.filter((a) => !a.touchesSubmodule).map((a) => a.nodeId);
85663
+ const sub = ranked.filter((a) => a.touchesSubmodule).map((a) => a.nodeId);
85664
+ if (nonSub.length) {
85665
+ rationale.push(`Non-submodule nodes first (no submodule-main advance, conflict-free ordering): ${nonSub.join(", ")}`);
85666
+ }
85667
+ if (sub.length) {
85668
+ rationale.push(`Submodule-touching nodes last, serialized (each merge advances submodule main, forcing rebase of the next): ${sub.join(", ")}`);
85669
+ }
85670
+ for (const area of ranked) {
85671
+ if (area.error) rationale.push(`Node ${area.nodeId}: change-area analysis degraded (${area.error}); placed with neutral priority.`);
85672
+ }
85673
+ return { order: ranked.map((a) => a.nodeId), changeAreas: areaById, rationale };
85674
+ }
85675
+ var import_node_child_process14;
85676
+ var import_node_util7;
85677
+ var execFileAsync6;
85678
+ var GIT3;
85679
+ var MAX_CHANGED_FILES2;
85680
+ var init_mesh_refine_batch = __esm2({
85681
+ "src/mesh/mesh-refine-batch.ts"() {
85682
+ "use strict";
85683
+ import_node_child_process14 = require("child_process");
85684
+ import_node_util7 = require("util");
85685
+ init_resolve_executable();
85686
+ execFileAsync6 = (0, import_node_util7.promisify)(import_node_child_process14.execFile);
85687
+ GIT3 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
85688
+ MAX_CHANGED_FILES2 = 500;
85689
+ }
85690
+ });
85691
+ async function git2(cwd, args) {
85692
+ const { stdout } = await execFileAsync7(GIT4, args, {
85693
+ cwd,
85694
+ encoding: "utf8",
85695
+ timeout: 15e3,
85696
+ windowsHide: true
85697
+ });
85698
+ return String(stdout || "").trim();
85699
+ }
85700
+ async function isAncestor(cwd, ancestor, descendant) {
85701
+ try {
85702
+ await git2(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]);
85703
+ return true;
85704
+ } catch {
85705
+ return false;
85706
+ }
85707
+ }
85708
+ async function assessScope(cwd, path63, baseRef, branchRef) {
85709
+ try {
85710
+ if (!(0, import_node_fs7.existsSync)(cwd)) return { path: path63, verdict: "unknown", error: `path does not exist: ${cwd}` };
85711
+ const liveBaseHead = await git2(cwd, ["rev-parse", baseRef]);
85712
+ const branchHead = await git2(cwd, ["rev-parse", branchRef]);
85713
+ if (!liveBaseHead || !branchHead) {
85714
+ return { path: path63, verdict: "unknown", error: "could not resolve base or branch head" };
85715
+ }
85716
+ if (await isAncestor(cwd, liveBaseHead, branchHead)) {
85717
+ return { path: path63, verdict: "clear", liveBaseHead };
85718
+ }
85719
+ let mergeBase;
85720
+ try {
85721
+ mergeBase = await git2(cwd, ["merge-base", liveBaseHead, branchHead]);
85722
+ } catch {
85723
+ return { path: path63, verdict: "unknown", liveBaseHead, error: "no common merge base" };
85724
+ }
85725
+ if (!mergeBase) return { path: path63, verdict: "unknown", liveBaseHead, error: "empty merge base" };
85726
+ return { path: path63, verdict: "diverged", liveBaseHead, mergeBase };
85727
+ } catch (e) {
85728
+ return { path: path63, verdict: "unknown", error: e?.message || String(e) };
85729
+ }
85730
+ }
85731
+ async function resolveSubmodulePaths(repoRoot) {
85732
+ try {
85733
+ const stdout = await git2(repoRoot, ["config", "--file", ".gitmodules", "--get-regexp", "path"]);
85734
+ const paths = /* @__PURE__ */ new Set();
85735
+ for (const line of stdout.split("\n")) {
85736
+ const trimmed = line.trim();
85737
+ const spaceIdx = trimmed.indexOf(" ");
85738
+ if (spaceIdx === -1) continue;
85739
+ const value = trimmed.slice(spaceIdx + 1).trim();
85740
+ if (value) paths.add(value);
85741
+ }
85742
+ return paths;
85743
+ } catch {
85744
+ return /* @__PURE__ */ new Set();
85745
+ }
85746
+ }
85747
+ async function assessRefineBaseDivergence(args) {
85748
+ const started = Date.now();
85749
+ const { repoRoot, workspace, baseBranch, branch } = args;
85750
+ const scopes = [];
85751
+ let touchedSubmodulePaths = [];
85752
+ const rootBaseRef = await (async () => {
85753
+ for (const ref of [`origin/${baseBranch}`, baseBranch, "HEAD"]) {
85754
+ try {
85755
+ await git2(repoRoot, ["rev-parse", "--verify", `${ref}^{commit}`]);
85756
+ return ref;
85757
+ } catch {
85758
+ }
85759
+ }
85760
+ return `origin/${baseBranch}`;
85761
+ })();
85762
+ scopes.push(await assessScope(workspace, ".", rootBaseRef, branch));
85763
+ try {
85764
+ const submodulePaths = await resolveSubmodulePaths(repoRoot);
85765
+ if (submodulePaths.size > 0) {
85766
+ const baseRefSha = await git2(repoRoot, ["rev-parse", rootBaseRef]).catch(() => "");
85767
+ const branchRefSha = await git2(workspace, ["rev-parse", branch]).catch(() => "");
85768
+ if (baseRefSha && branchRefSha) {
85769
+ const area = await analyzeMeshRefineNodeChangeArea({
85770
+ nodeId: "(accept-precheck)",
85771
+ workspace,
85772
+ branch,
85773
+ baseRef: baseRefSha,
85774
+ branchRef: branchRefSha,
85775
+ diffCwd: workspace,
85776
+ submodulePaths
85777
+ });
85778
+ touchedSubmodulePaths = area.touchedSubmodulePaths;
85779
+ for (const subPath of touchedSubmodulePaths) {
85780
+ const subCwd = (0, import_node_path5.resolve)(workspace, subPath);
85781
+ const subBaseRef = await (async () => {
85782
+ for (const ref of ["origin/main", "origin/master", "main", "master"]) {
85783
+ try {
85784
+ await git2(subCwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
85785
+ return ref;
85786
+ } catch {
85787
+ }
85788
+ }
85789
+ return "origin/main";
85790
+ })();
85791
+ scopes.push(await assessScope(subCwd, subPath, subBaseRef, "HEAD"));
85792
+ }
85793
+ }
85794
+ }
85795
+ } catch {
85796
+ }
85797
+ const verdict = scopes.some((s2) => s2.verdict === "diverged") ? "diverged" : scopes.some((s2) => s2.verdict === "unknown") ? "unknown" : "clear";
85798
+ return { verdict, scopes, touchedSubmodulePaths, durationMs: Date.now() - started };
85799
+ }
85800
+ var import_node_child_process15;
85801
+ var import_node_util8;
85802
+ var import_node_path5;
85803
+ var import_node_fs7;
85804
+ var execFileAsync7;
85805
+ var GIT4;
85806
+ var init_mesh_refine_base_divergence = __esm2({
85807
+ "src/mesh/mesh-refine-base-divergence.ts"() {
85808
+ "use strict";
85809
+ import_node_child_process15 = require("child_process");
85810
+ import_node_util8 = require("util");
85811
+ import_node_path5 = require("path");
85812
+ import_node_fs7 = require("fs");
85813
+ init_resolve_executable();
85814
+ init_mesh_refine_batch();
85815
+ execFileAsync7 = (0, import_node_util8.promisify)(import_node_child_process15.execFile);
85816
+ GIT4 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
85817
+ }
85818
+ });
85819
+ var mesh_refine_zombie_sweep_exports = {};
85820
+ __export2(mesh_refine_zombie_sweep_exports, {
85821
+ classifyRefineDispatch: () => classifyRefineDispatch,
85822
+ refineArchivePairKey: () => refineArchivePairKey,
85823
+ selectOpenRefineDispatches: () => selectOpenRefineDispatches,
85824
+ shouldNotifyRefineCloseOut: () => shouldNotifyRefineCloseOut
85825
+ });
85826
+ function classifyRefineDispatch(record2, opts) {
85827
+ if (opts.isRunning(record2.nodeId)) return void 0;
85828
+ const dispatchedAtMs = new Date(record2.timestamp).getTime();
85829
+ const ageMs2 = Number.isFinite(dispatchedAtMs) ? opts.nowMs - dispatchedAtMs : void 0;
85830
+ const base = { nodeId: record2.nodeId, jobId: record2.jobId, ...ageMs2 !== void 0 ? { ageMs: ageMs2 } : {} };
85831
+ if (!opts.nodeExists(record2.nodeId)) {
85832
+ return { ...base, disposition: "close_removed_node" };
85833
+ }
85834
+ if (opts.executorLiveness) {
85835
+ let liveness;
85836
+ try {
85837
+ liveness = opts.executorLiveness(record2);
85838
+ } catch {
85839
+ liveness = "unknown";
85840
+ }
85841
+ if (liveness === "alive") {
85842
+ return { ...base, disposition: "defer_executor_alive" };
85843
+ }
85844
+ }
85845
+ if (ageMs2 !== void 0 && ageMs2 >= 0 && ageMs2 < opts.graceMs) {
85846
+ return { ...base, disposition: "defer_grace" };
85847
+ }
85848
+ if (ageMs2 !== void 0 && ageMs2 >= opts.zombieCutoffMs) {
85849
+ return { ...base, disposition: "close_stale" };
85850
+ }
85851
+ return { ...base, disposition: "resume" };
85852
+ }
85853
+ function selectOpenRefineDispatches(entries, archivedTerminalKeys) {
85854
+ const terminalKeys = /* @__PURE__ */ new Set();
85855
+ for (const e of entries) {
85856
+ if (e.kind !== "task_completed" && e.kind !== "task_failed") continue;
85857
+ if (!e.nodeId) continue;
85858
+ const jobId = e.payload?.refineJob?.jobId;
85859
+ if (jobId) terminalKeys.add(`${e.nodeId}:${jobId}`);
85860
+ }
85861
+ const open = [];
85862
+ const seen = /* @__PURE__ */ new Set();
85863
+ for (const e of entries) {
85864
+ if (e.kind !== "task_dispatched" || !e.nodeId) continue;
85865
+ const payload = e.payload;
85866
+ if (payload?.source !== "refine_mesh_node_async_job") continue;
85867
+ const jobId = payload?.refineJob?.jobId;
85868
+ if (!jobId) continue;
85869
+ const key2 = `${e.nodeId}:${jobId}`;
85870
+ if (terminalKeys.has(key2) || seen.has(key2)) continue;
85871
+ if (archivedTerminalKeys?.has(refineArchivePairKey(e.nodeId, jobId))) continue;
85872
+ seen.add(key2);
85873
+ const executor = payload?.refineJob?.executor;
85874
+ open.push({ nodeId: e.nodeId, jobId, timestamp: e.timestamp, ...executor ? { executor } : {} });
85875
+ }
85876
+ return open;
85877
+ }
85878
+ function refineArchivePairKey(nodeId, jobId) {
85879
+ return `refine:${nodeId}:${jobId}`;
85880
+ }
85881
+ function shouldNotifyRefineCloseOut(decision, notifyHorizonMs) {
85882
+ if (decision.disposition === "close_removed_node") return false;
85883
+ if (decision.disposition !== "close_stale") return false;
85884
+ if (decision.ageMs === void 0) return true;
85885
+ return decision.ageMs < notifyHorizonMs;
85886
+ }
85887
+ var init_mesh_refine_zombie_sweep = __esm2({
85888
+ "src/mesh/mesh-refine-zombie-sweep.ts"() {
85889
+ "use strict";
85890
+ }
85891
+ });
85892
+ function classifyRefineTerminal(result) {
85893
+ const refineCode = typeof result.code === "string" ? result.code : "";
85894
+ const landing = extractRefineMergeLanding(result);
85895
+ const isPostMergeWarning = result.success !== true && landing.merged && landing.pushed;
85896
+ const kind = result.success === true ? "completed" : isPostMergeWarning ? "completed_with_warnings" : refineCode === "blocked_review" || refineCode === "worktree_missing" || refineCode === "worktree_dirty" || refineCode === "rebase_precondition_failed" || refineCode === "rebase_failed" ? "blocked_review" : refineCode === "validation_failed" || refineCode === "validation_dependencies_missing" || refineCode === "missing_dependencies" || refineCode === "dependency_bootstrap_failed" || refineCode === "spawn_resolution_failed" || refineCode === "validation_unavailable" || refineCode === "output_limit_exceeded" ? "validation_failed" : refineCode === "submodule_reachability_failed" ? "submodule_reachability_failed" : refineCode === "merge_failed" || refineCode === "patch_equivalence_failed" || refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "merge_failed" : refineCode === "cleanup_failed" ? "cleanup_failed" : "merge_failed";
85897
+ const clean = kind === "completed";
85898
+ return { kind, landing, isPostMergeWarning, converged: clean || isPostMergeWarning, clean };
85899
+ }
85900
+ function refineTerminalNextStep(kind) {
85901
+ switch (kind) {
85902
+ case "blocked_review":
85903
+ return "Request user review/approval before attempting to merge again.";
85904
+ case "validation_failed":
85905
+ return "Fix failing tests or configure validation.bootstrapCommands and retry mesh_refine_node.";
85906
+ case "submodule_reachability_failed":
85907
+ return "Push unreachable submodule commits to origin/main, then retry mesh_refine_node.";
85908
+ case "merge_failed":
85909
+ return "Resolve merge conflicts or patch equivalence issues, then retry mesh_refine_node.";
85910
+ case "cleanup_failed":
85911
+ return "Manually remove the worktree and retry or use mesh_remove_node.";
85912
+ case "completed_with_warnings":
85913
+ return "The merge IS on origin \u2014 do NOT re-run mesh_refine_node. Only the post-merge step below needs attention (worktree cleanup / submodule alignment); treat the branch as merged_to_main.";
85914
+ default:
85915
+ return "Inspect refineStages for the failing stage and retry.";
85916
+ }
85917
+ }
85918
+ function buildRefineWorktreeMissingResult(nodeId, workspace, refineStages) {
85919
+ return {
85920
+ success: false,
85921
+ code: "worktree_missing",
85922
+ convergenceStatus: "blocked_review",
85923
+ // Never auto-retried: re-running cannot recreate the worktree, and the node has
85924
+ // most likely already converged.
85925
+ retryable: false,
85926
+ workspaceMissing: true,
85927
+ error: `The worktree directory for node '${nodeId}' no longer exists (${workspace}); nothing was merged by this run. Worktree removal is the final step of a SUCCESSFUL refine, so this node was most likely already merged and cleaned up by an earlier job \u2014 verify with 'git -C <repoRoot> log --oneline' before acting. Do NOT re-run refine to "fix" this.`,
85928
+ nextStep: "Verify whether the branch already merged into the base (it most likely did). If so, treat the node as merged_to_main and remove it from the mesh; only re-clone if the work is genuinely missing.",
85929
+ refineStages,
85930
+ finalBranchConvergenceState: {
85931
+ baseBranch: void 0,
85932
+ merged: false,
85933
+ removed: true,
85934
+ status: "blocked_review"
85935
+ }
85936
+ };
85937
+ }
85938
+ function extractRefineMergeLanding(result) {
85939
+ const fbcs = result.finalBranchConvergenceState && typeof result.finalBranchConvergenceState === "object" ? result.finalBranchConvergenceState : void 0;
85940
+ const merged = result.merged === true || result.mergedLocal === true || fbcs?.merged === true;
85941
+ const pushed = result.pushed === true || fbcs?.pushed === true;
85942
+ return { merged: !!merged, pushed: !!pushed && !!merged };
85943
+ }
85944
+ function buildRefineBlockerContext(result, opts) {
85945
+ if (opts.isTerminalClean) return void 0;
85946
+ const refineTerminalKind = opts.terminalKind;
85947
+ const refineCode = typeof result.code === "string" ? result.code : "";
85948
+ const code = typeof result.code === "string" ? result.code : refineTerminalKind;
85949
+ const stage = refineTerminalKind === "validation_failed" ? "validation" : refineTerminalKind === "submodule_reachability_failed" ? "submodule_reachability" : refineCode === "patch_equivalence_failed" ? "patch_equivalence" : refineCode === "needs_rebase" || refineCode === "needs_rebase_with_conflicts" ? "patch_equivalence" : refineCode === "worktree_dirty" || refineCode === "rebase_precondition_failed" || refineCode === "rebase_failed" ? "patch_equivalence" : refineTerminalKind === "merge_failed" ? "merge" : refineTerminalKind === "cleanup_failed" ? "cleanup" : refineTerminalKind === "completed_with_warnings" ? refineCode === "post_merge_submodule_alignment_failed" ? "submodule_alignment" : "cleanup" : "unknown";
85950
+ const ctx = { stage, reason: code, terminalKind: refineTerminalKind };
85951
+ if (typeof result.error === "string") ctx.error = result.error;
85952
+ if (typeof result.blockedReason === "string") ctx.blockedReason = result.blockedReason;
85953
+ if (typeof result.detailedReason === "string") ctx.detailedReason = result.detailedReason;
85954
+ if (typeof result.detailedReasonDescription === "string") ctx.detailedReasonDescription = result.detailedReasonDescription;
85955
+ if (typeof result.recommendedAction === "string") ctx.recommendedAction = result.recommendedAction;
85956
+ if (result.evidence && typeof result.evidence === "object") ctx.evidence = result.evidence;
85957
+ if (typeof result.rebaseStderr === "string") ctx.rebaseStderr = result.rebaseStderr;
85958
+ if (typeof result.rebaseFailureDetail === "string") ctx.rebaseFailureDetail = result.rebaseFailureDetail;
85959
+ if (typeof result.rebaseConflict === "boolean") ctx.rebaseConflict = result.rebaseConflict;
85960
+ if (stage === "patch_equivalence" && result.patchEquivalence) {
85961
+ const pe = result.patchEquivalence;
85962
+ ctx.details = {
85963
+ expectedPatchId: pe.expectedPatchId,
85964
+ actualPatchId: pe.actualPatchId,
85965
+ status: pe.status,
85966
+ actionableHint: pe.actionableHint,
85967
+ error: pe.error,
85968
+ ...typeof result.detailedReason === "string" ? { detailedReason: result.detailedReason } : {},
85969
+ ...typeof result.recommendedAction === "string" ? { recommendedAction: result.recommendedAction } : {},
85970
+ ...result.evidence && typeof result.evidence === "object" ? { evidence: result.evidence } : {}
85971
+ };
85972
+ }
85973
+ if (stage === "submodule_reachability" && Array.isArray(result.unreachableSubmoduleCommits)) {
85974
+ ctx.details = {
85975
+ unreachableCount: result.unreachableSubmoduleCommits.length,
85976
+ paths: result.unreachableSubmoduleCommits.map((e) => e.path),
85977
+ autoPublishAllowed: result.unreachableSubmoduleCommits[0]?.autoPublishAllowed
85978
+ };
85979
+ }
85980
+ if (stage === "validation" && result.validationSummary) {
85981
+ const vs = result.validationSummary;
85982
+ const diagnostics = opts.extractValidationDiagnostics?.(vs);
85983
+ ctx.details = {
85984
+ failureCode: vs.failureCode,
85985
+ failureKind: vs.failureKind,
85986
+ commandsRun: Array.isArray(vs.commandsRun) ? vs.commandsRun.length : void 0,
85987
+ ...diagnostics ? { failure: diagnostics } : {}
85988
+ };
85989
+ }
85990
+ return ctx;
85991
+ }
85992
+ var init_mesh_refine_landing = __esm2({
85993
+ "src/mesh/mesh-refine-landing.ts"() {
85994
+ "use strict";
85659
85995
  }
85660
85996
  });
85661
85997
  function findOpenRefineDispatchForNode(args) {
@@ -85946,28 +86282,28 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
85946
86282
  "use strict";
85947
86283
  }
85948
86284
  });
85949
- async function hasOriginRemote(execFileAsync7, repoRoot, env2) {
86285
+ async function hasOriginRemote(execFileAsync8, repoRoot, env2) {
85950
86286
  try {
85951
- const { stdout } = await execFileAsync7("git", ["remote", "get-url", "origin"], { cwd: repoRoot, encoding: "utf8", env: env2 });
86287
+ const { stdout } = await execFileAsync8("git", ["remote", "get-url", "origin"], { cwd: repoRoot, encoding: "utf8", env: env2 });
85952
86288
  return !!stdout.trim();
85953
86289
  } catch {
85954
86290
  return false;
85955
86291
  }
85956
86292
  }
85957
86293
  async function probeRefineBaseCas(params) {
85958
- const { execFileAsync: execFileAsync7, repoRoot, baseBranch, pinnedBaseHead, branchHead, env: env2 } = params;
85959
- if (!await hasOriginRemote(execFileAsync7, repoRoot, env2)) {
86294
+ const { execFileAsync: execFileAsync8, repoRoot, baseBranch, pinnedBaseHead, branchHead, env: env2 } = params;
86295
+ if (!await hasOriginRemote(execFileAsync8, repoRoot, env2)) {
85960
86296
  return { state: "no_origin" };
85961
86297
  }
85962
86298
  try {
85963
- await execFileAsync7("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: env2 });
86299
+ await execFileAsync8("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: env2 });
85964
86300
  } catch (e) {
85965
86301
  const fetchError = e?.message || String(e);
85966
86302
  return { state: "undeterminable", reason: `git fetch origin ${baseBranch} failed: ${fetchError}`, fetchError };
85967
86303
  }
85968
86304
  let liveBaseHead;
85969
86305
  try {
85970
- const { stdout } = await execFileAsync7("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: env2 });
86306
+ const { stdout } = await execFileAsync8("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: env2 });
85971
86307
  liveBaseHead = stdout.trim();
85972
86308
  } catch (e) {
85973
86309
  return { state: "undeterminable", reason: `git rev-parse origin/${baseBranch} failed: ${e?.message || String(e)}` };
@@ -85978,23 +86314,23 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
85978
86314
  if (liveBaseHead !== pinnedBaseHead) {
85979
86315
  return { state: "moved", liveBaseHead };
85980
86316
  }
85981
- const localBaseHead = branchHead ? await resolveLocalBaseHead(execFileAsync7, repoRoot, env2) : void 0;
85982
- if (localBaseHead && branchHead && localBaseHead !== pinnedBaseHead && await isAncestor2(execFileAsync7, repoRoot, pinnedBaseHead, localBaseHead, env2) && !await isAncestor2(execFileAsync7, repoRoot, localBaseHead, branchHead, env2) && !await isAncestor2(execFileAsync7, repoRoot, branchHead, localBaseHead, env2)) {
86317
+ const localBaseHead = branchHead ? await resolveLocalBaseHead(execFileAsync8, repoRoot, env2) : void 0;
86318
+ if (localBaseHead && branchHead && localBaseHead !== pinnedBaseHead && await isAncestor2(execFileAsync8, repoRoot, pinnedBaseHead, localBaseHead, env2) && !await isAncestor2(execFileAsync8, repoRoot, localBaseHead, branchHead, env2) && !await isAncestor2(execFileAsync8, repoRoot, branchHead, localBaseHead, env2)) {
85983
86319
  return { state: "moved", liveBaseHead, localBaseHead };
85984
86320
  }
85985
86321
  return { state: "unmoved", liveBaseHead };
85986
86322
  }
85987
- async function resolveLocalBaseHead(execFileAsync7, repoRoot, env2) {
86323
+ async function resolveLocalBaseHead(execFileAsync8, repoRoot, env2) {
85988
86324
  try {
85989
- const { stdout } = await execFileAsync7("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: env2 });
86325
+ const { stdout } = await execFileAsync8("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: env2 });
85990
86326
  return stdout.trim() || void 0;
85991
86327
  } catch {
85992
86328
  return void 0;
85993
86329
  }
85994
86330
  }
85995
- async function isAncestor2(execFileAsync7, repoRoot, maybeAncestor, descendant, env2) {
86331
+ async function isAncestor2(execFileAsync8, repoRoot, maybeAncestor, descendant, env2) {
85996
86332
  try {
85997
- await execFileAsync7("git", ["merge-base", "--is-ancestor", maybeAncestor, descendant], { cwd: repoRoot, encoding: "utf8", env: env2 });
86333
+ await execFileAsync8("git", ["merge-base", "--is-ancestor", maybeAncestor, descendant], { cwd: repoRoot, encoding: "utf8", env: env2 });
85998
86334
  return true;
85999
86335
  } catch {
86000
86336
  return false;
@@ -86632,30 +86968,30 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86632
86968
  const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : mesh?.nodes.find((n) => !n.isLocalWorktree);
86633
86969
  const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
86634
86970
  if (!repoRoot) return { kind: "terminal", result: { success: false, error: "Source node repoRoot not found", refineStages } };
86635
- const { execFile: execFile8 } = await import("child_process");
86636
- const { promisify: promisify11 } = await import("util");
86637
- const execFileAsync7 = promisify11(execFile8);
86971
+ const { execFile: execFile9 } = await import("child_process");
86972
+ const { promisify: promisify12 } = await import("util");
86973
+ const execFileAsync8 = promisify12(execFile9);
86638
86974
  const resolveStarted = Date.now();
86639
- const { stdout: branchStdout } = await execFileAsync7("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
86975
+ const { stdout: branchStdout } = await execFileAsync8("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
86640
86976
  const branch = branchStdout.trim();
86641
86977
  if (!branch) return { kind: "terminal", result: { success: false, error: "Could not determine branch of the worktree node", refineStages } };
86642
- const { stdout: baseBranchStdout } = await execFileAsync7("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86978
+ const { stdout: baseBranchStdout } = await execFileAsync8("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86643
86979
  const baseBranch = baseBranchStdout.trim();
86644
86980
  let fetchWarning;
86645
86981
  try {
86646
- await execFileAsync7("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86982
+ await execFileAsync8("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86647
86983
  } catch (e) {
86648
86984
  fetchWarning = `git fetch origin ${baseBranch} failed (proceeding with local HEAD): ${e?.message}`;
86649
86985
  }
86650
86986
  let baseHeadRaw;
86651
86987
  try {
86652
- const { stdout } = await execFileAsync7("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86988
+ const { stdout } = await execFileAsync8("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86653
86989
  baseHeadRaw = stdout.trim();
86654
86990
  } catch {
86655
- const { stdout: localHead } = await execFileAsync7("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86991
+ const { stdout: localHead } = await execFileAsync8("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
86656
86992
  baseHeadRaw = localHead.trim();
86657
86993
  }
86658
- const { stdout: branchHeadStdout } = await execFileAsync7("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
86994
+ const { stdout: branchHeadStdout } = await execFileAsync8("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
86659
86995
  const baseHead = baseHeadRaw;
86660
86996
  const branchHead = branchHeadStdout.trim();
86661
86997
  let changeImpact;
@@ -86679,7 +87015,7 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86679
87015
  nodeId,
86680
87016
  args,
86681
87017
  refineStages,
86682
- execFileAsync: execFileAsync7,
87018
+ execFileAsync: execFileAsync8,
86683
87019
  mesh,
86684
87020
  node,
86685
87021
  sourceNode,
@@ -86695,17 +87031,17 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86695
87031
  }
86696
87032
  };
86697
87033
  }
86698
- async function computeBranchBaseDivergence(execFileAsync7, cwd, baseHead, branchHead) {
87034
+ async function computeBranchBaseDivergence(execFileAsync8, cwd, baseHead, branchHead) {
86699
87035
  let mergeBase;
86700
87036
  try {
86701
- const { stdout } = await execFileAsync7("git", ["merge-base", baseHead, branchHead], { cwd, encoding: "utf8", env: gitChildEnv() });
87037
+ const { stdout } = await execFileAsync8("git", ["merge-base", baseHead, branchHead], { cwd, encoding: "utf8", env: gitChildEnv() });
86702
87038
  mergeBase = stdout.trim() || void 0;
86703
87039
  } catch {
86704
87040
  }
86705
87041
  let ahead = 0;
86706
87042
  let behind = 0;
86707
87043
  try {
86708
- const { stdout } = await execFileAsync7("git", ["rev-list", "--left-right", "--count", `${baseHead}...${branchHead}`], { cwd, encoding: "utf8", env: gitChildEnv() });
87044
+ const { stdout } = await execFileAsync8("git", ["rev-list", "--left-right", "--count", `${baseHead}...${branchHead}`], { cwd, encoding: "utf8", env: gitChildEnv() });
86709
87045
  const [left, right] = stdout.trim().split(/\s+/).map((n) => Number.parseInt(n, 10));
86710
87046
  behind = Number.isFinite(left) ? left : 0;
86711
87047
  ahead = Number.isFinite(right) ? right : 0;
@@ -86722,11 +87058,11 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86722
87058
  };
86723
87059
  }
86724
87060
  async function refineSyncBaseStage(self, ctx) {
86725
- const { repoRoot, baseHead, node, branch, baseBranch, refineStages, execFileAsync: execFileAsync7 } = ctx;
87061
+ const { repoRoot, baseHead, node, branch, baseBranch, refineStages, execFileAsync: execFileAsync8 } = ctx;
86726
87062
  let branchHead = ctx.branchHead;
86727
87063
  let gitlinkResolutions = [];
86728
87064
  const syncStarted = Date.now();
86729
- const divergence = await computeBranchBaseDivergence(execFileAsync7, node.workspace, baseHead, branchHead);
87065
+ const divergence = await computeBranchBaseDivergence(execFileAsync8, node.workspace, baseHead, branchHead);
86730
87066
  if (divergence.behind === 0) {
86731
87067
  recordMeshRefineStage(refineStages, "sync_base", "passed", syncStarted, {
86732
87068
  ahead: divergence.ahead,
@@ -86820,12 +87156,12 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86820
87156
  throw err;
86821
87157
  }
86822
87158
  } else {
86823
- (0, import_node_child_process15.execFileSync)("git", ["rebase", baseHead], { cwd: node.workspace, stdio: ["ignore", "pipe", "pipe"] });
87159
+ (0, import_node_child_process16.execFileSync)("git", ["rebase", baseHead], { cwd: node.workspace, stdio: ["ignore", "pipe", "pipe"] });
86824
87160
  }
86825
87161
  } catch (rebaseErr) {
86826
87162
  if (!rebaseErr?.alreadyAborted) {
86827
87163
  try {
86828
- (0, import_node_child_process15.execFileSync)("git", ["rebase", "--abort"], { cwd: node.workspace, stdio: "ignore" });
87164
+ (0, import_node_child_process16.execFileSync)("git", ["rebase", "--abort"], { cwd: node.workspace, stdio: "ignore" });
86829
87165
  } catch {
86830
87166
  }
86831
87167
  }
@@ -86930,7 +87266,7 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
86930
87266
  }
86931
87267
  } };
86932
87268
  }
86933
- const { stdout: rebasedHeadStdout } = await execFileAsync7("git", ["rev-parse", "HEAD"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
87269
+ const { stdout: rebasedHeadStdout } = await execFileAsync8("git", ["rev-parse", "HEAD"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
86934
87270
  branchHead = rebasedHeadStdout.trim();
86935
87271
  ctx.branchHead = branchHead;
86936
87272
  let changeImpact = ctx.changeImpact;
@@ -87360,7 +87696,7 @@ ${hintLines.join("\n")}` : "",
87360
87696
  }
87361
87697
  }
87362
87698
  async function refineMergeAndFinalizeStage(self, ctx) {
87363
- const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, sourceNode, validationSummary, patchEquivalence, submoduleReachability, mesh, refineStages, execFileAsync: execFileAsync7 } = ctx;
87699
+ const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, sourceNode, validationSummary, patchEquivalence, submoduleReachability, mesh, refineStages, execFileAsync: execFileAsync8 } = ctx;
87364
87700
  const leaseKey = `${repoRoot}::${baseBranch}`;
87365
87701
  const leaseHolder = buildRefineJobKey(self, meshId, nodeId);
87366
87702
  const alreadyHeld = self.refineBaseLeases.get(leaseKey) === leaseHolder;
@@ -87399,10 +87735,10 @@ ${hintLines.join("\n")}` : "",
87399
87735
  }
87400
87736
  }
87401
87737
  async function runRefineMergeAndFinalizeLocked(self, ctx) {
87402
- const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, sourceNode, validationSummary, patchEquivalence, submoduleReachability, mesh, refineStages, execFileAsync: execFileAsync7 } = ctx;
87738
+ const { meshId, nodeId, args, repoRoot, baseHead, node, branch, baseBranch, sourceNode, validationSummary, patchEquivalence, submoduleReachability, mesh, refineStages, execFileAsync: execFileAsync8 } = ctx;
87403
87739
  const casStarted = Date.now();
87404
87740
  const cas = await probeRefineBaseCas({
87405
- execFileAsync: execFileAsync7,
87741
+ execFileAsync: execFileAsync8,
87406
87742
  repoRoot,
87407
87743
  baseBranch,
87408
87744
  pinnedBaseHead: baseHead,
@@ -87426,7 +87762,7 @@ ${hintLines.join("\n")}` : "",
87426
87762
  let mergeResult;
87427
87763
  const mergeStarted = Date.now();
87428
87764
  try {
87429
- const result = await execFileAsync7("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87765
+ const result = await execFileAsync8("git", ["merge", "--no-ff", branch, "-m", `Auto-merge branch '${branch}' via Refinery`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87430
87766
  mergeResult = {
87431
87767
  stdout: truncateValidationOutput(result.stdout),
87432
87768
  stderr: truncateValidationOutput(result.stderr),
@@ -87438,7 +87774,7 @@ ${hintLines.join("\n")}` : "",
87438
87774
  ${e?.stderr || ""}`;
87439
87775
  const conflictPaths = [...mergeOutput.matchAll(/Merge conflict in (.+)/g)].map((m) => m[1].trim()).filter(Boolean);
87440
87776
  try {
87441
- await execFileAsync7("git", ["merge", "--abort"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87777
+ await execFileAsync8("git", ["merge", "--abort"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87442
87778
  } catch {
87443
87779
  }
87444
87780
  recordMeshRefineStage(refineStages, "merge", "failed", mergeStarted, {
@@ -87521,7 +87857,7 @@ ${e?.stderr || ""}`;
87521
87857
  if (!requireApprovalForPush) {
87522
87858
  const pushStarted = Date.now();
87523
87859
  try {
87524
- await execFileAsync7("git", ["push", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87860
+ await execFileAsync8("git", ["push", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87525
87861
  pushResult = { pushed: true, remote: "origin", branch: baseBranch, durationMs: Date.now() - pushStarted };
87526
87862
  recordMeshRefineStage(refineStages, "push", "passed", pushStarted, pushResult);
87527
87863
  } catch (e) {
@@ -87765,9 +88101,9 @@ ${e?.stderr || ""}`;
87765
88101
  if (targetNodes.length === 0) {
87766
88102
  return { success: true, batch: true, dryRun: args?.dryRun !== false, nodeCount: 0, order: [], results: [], note: "No convergeable local worktree nodes found." };
87767
88103
  }
87768
- const { execFile: execFile8 } = await import("child_process");
87769
- const { promisify: promisify11 } = await import("util");
87770
- const execFileAsync7 = promisify11(execFile8);
88104
+ const { execFile: execFile9 } = await import("child_process");
88105
+ const { promisify: promisify12 } = await import("util");
88106
+ const execFileAsync8 = promisify12(execFile9);
87771
88107
  const resolveRepoRootFor = (node) => {
87772
88108
  const sourceNode = node.clonedFromNodeId ? allNodes.find((n) => meshNodeIdMatches(n, node.clonedFromNodeId)) : allNodes.find((n) => !n.isLocalWorktree);
87773
88109
  return sourceNode?.repoRoot || sourceNode?.workspace;
@@ -87779,21 +88115,21 @@ ${e?.stderr || ""}`;
87779
88115
  if (cached5) return cached5;
87780
88116
  let baseBranch = "main";
87781
88117
  try {
87782
- const { stdout } = await execFileAsync7("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
88118
+ const { stdout } = await execFileAsync8("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87783
88119
  if (stdout.trim()) baseBranch = stdout.trim();
87784
88120
  } catch {
87785
88121
  }
87786
88122
  let baseRef = "HEAD";
87787
88123
  try {
87788
- await execFileAsync7("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
88124
+ await execFileAsync8("git", ["fetch", "origin", baseBranch], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87789
88125
  } catch {
87790
88126
  }
87791
88127
  try {
87792
- const { stdout } = await execFileAsync7("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
88128
+ const { stdout } = await execFileAsync8("git", ["rev-parse", `origin/${baseBranch}`], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87793
88129
  baseRef = stdout.trim();
87794
88130
  } catch {
87795
88131
  try {
87796
- const { stdout } = await execFileAsync7("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
88132
+ const { stdout } = await execFileAsync8("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87797
88133
  baseRef = stdout.trim();
87798
88134
  } catch {
87799
88135
  }
@@ -87806,7 +88142,7 @@ ${e?.stderr || ""}`;
87806
88142
  const repoRoot = resolveRepoRootFor(node);
87807
88143
  let branch = typeof node.worktreeBranch === "string" ? node.worktreeBranch : "";
87808
88144
  try {
87809
- const { stdout } = await execFileAsync7("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
88145
+ const { stdout } = await execFileAsync8("git", ["branch", "--show-current"], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
87810
88146
  if (stdout.trim()) branch = stdout.trim();
87811
88147
  } catch {
87812
88148
  }
@@ -87827,7 +88163,7 @@ ${e?.stderr || ""}`;
87827
88163
  if (!submodulePathsByRepoRoot.has(repoRoot)) {
87828
88164
  let subPaths = /* @__PURE__ */ new Set();
87829
88165
  try {
87830
- const { stdout } = await execFileAsync7("git", ["config", "--file", ".gitmodules", "--get-regexp", "path"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
88166
+ const { stdout } = await execFileAsync8("git", ["config", "--file", ".gitmodules", "--get-regexp", "path"], { cwd: repoRoot, encoding: "utf8", env: gitChildEnv() });
87831
88167
  for (const line of stdout.split("\n")) {
87832
88168
  const trimmed = line.trim();
87833
88169
  const spaceIdx = trimmed.indexOf(" ");
@@ -87843,7 +88179,7 @@ ${e?.stderr || ""}`;
87843
88179
  const baseRef = await resolveBaseRef(repoRoot);
87844
88180
  let branchRef = branch;
87845
88181
  try {
87846
- const { stdout } = await execFileAsync7("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
88182
+ const { stdout } = await execFileAsync8("git", ["rev-parse", branch], { cwd: node.workspace, encoding: "utf8", env: gitChildEnv() });
87847
88183
  branchRef = stdout.trim() || branch;
87848
88184
  } catch {
87849
88185
  }
@@ -87861,22 +88197,7 @@ ${e?.stderr || ""}`;
87861
88197
  const orderedNodes = ordering.order.map((nodeId) => targetNodes.find((n) => meshNodeIdMatches(n, nodeId))).filter((n) => !!n);
87862
88198
  const dryRun = args?.dryRun !== false && args?.execute !== true;
87863
88199
  if (dryRun) {
87864
- return {
87865
- success: true,
87866
- batch: true,
87867
- dryRun: true,
87868
- nodeCount: orderedNodes.length,
87869
- order: ordering.order,
87870
- orderingRationale: ordering.rationale,
87871
- changeAreas: ordering.changeAreas,
87872
- plan: orderedNodes.map((node) => ({
87873
- nodeId: node.id,
87874
- workspace: node.workspace,
87875
- validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
87876
- mergeWillRun: false
87877
- })),
87878
- note: "Dry-run: no validation, rebase, or merge was executed. Re-run with execute=true to converge nodes in this order."
87879
- };
88200
+ return buildMeshRefineBatchDryRunResult({ mesh, orderedNodes, ordering });
87880
88201
  }
87881
88202
  return runMeshRefineBatchConvergence(self, meshId, orderedNodes, ordering, args);
87882
88203
  }
@@ -87951,7 +88272,9 @@ ${e?.stderr || ""}`;
87951
88272
  allConverged,
87952
88273
  results,
87953
88274
  ...allConverged ? {} : {
87954
- nextStep: "Resolve blocked_review / not_mergeable nodes manually (see per-node code/stage/error), then re-run mesh_refine_batch for the remaining nodes."
88275
+ // Name the failed nodes inline — the aggregate nextStep used to hide
88276
+ // WHICH nodes blocked, forcing a manual git-log cross-check.
88277
+ nextStep: `Resolve blocked_review / not_mergeable nodes manually \u2014 failed: ${results.filter((r) => r.convergence === "blocked_review" || r.convergence === "not_mergeable").map((r) => `${r.nodeId}${r.code ? ` [${r.code}]` : ""}`).join(", ")} (see per-node code/stage/error), then re-run mesh_refine_batch for the remaining nodes.`
87955
88278
  }
87956
88279
  };
87957
88280
  }
@@ -88263,7 +88586,7 @@ ${e?.stderr || ""}`;
88263
88586
  if (!repoRoot || !workspace) return;
88264
88587
  const branch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : (() => {
88265
88588
  try {
88266
- return (0, import_node_child_process15.execFileSync)("git", ["branch", "--show-current"], { cwd: workspace, encoding: "utf8" }).trim();
88589
+ return (0, import_node_child_process16.execFileSync)("git", ["branch", "--show-current"], { cwd: workspace, encoding: "utf8" }).trim();
88267
88590
  } catch {
88268
88591
  return "";
88269
88592
  }
@@ -88271,7 +88594,7 @@ ${e?.stderr || ""}`;
88271
88594
  if (!branch) return;
88272
88595
  const baseBranch = (() => {
88273
88596
  try {
88274
- return (0, import_node_child_process15.execFileSync)("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" }).trim() || "main";
88597
+ return (0, import_node_child_process16.execFileSync)("git", ["branch", "--show-current"], { cwd: repoRoot, encoding: "utf8" }).trim() || "main";
88275
88598
  } catch {
88276
88599
  return "main";
88277
88600
  }
@@ -88339,13 +88662,13 @@ ${e?.stderr || ""}`;
88339
88662
  });
88340
88663
  return handle;
88341
88664
  }
88342
- var import_node_child_process15;
88665
+ var import_node_child_process16;
88343
88666
  var import_node_fs9;
88344
88667
  var RETRYABLE_BASE_MOVEMENT_CODES;
88345
88668
  var init_router_refine = __esm2({
88346
88669
  "src/commands/router-refine.ts"() {
88347
88670
  "use strict";
88348
- import_node_child_process15 = require("child_process");
88671
+ import_node_child_process16 = require("child_process");
88349
88672
  import_node_fs9 = require("fs");
88350
88673
  init_logger();
88351
88674
  init_debug_trace();
@@ -88354,6 +88677,7 @@ ${e?.stderr || ""}`;
88354
88677
  init_mesh_reconcile_identity();
88355
88678
  init_mesh_fast_forward();
88356
88679
  init_mesh_refine_batch();
88680
+ init_mesh_refine_submodule_preflight();
88357
88681
  init_mesh_refine_base_divergence();
88358
88682
  init_mesh_refine_inflight();
88359
88683
  init_mesh_refine_inflight();
@@ -92353,6 +92677,7 @@ ${e?.stderr || ""}`;
92353
92677
  init_mesh_routing_decision();
92354
92678
  init_mesh_scheduling_fitness();
92355
92679
  init_mesh_work_queue();
92680
+ var QUOTA_STAGE_NOTE = "fitnessOrder/fitnessWinner(=fitnessOrderHead) are the INPUT order to quota ranking, not a result. The selected provider is `winner`; per-candidate ranking numbers are in quotaDiagnostics[].ranking.";
92356
92681
  function providerReportedDisabled(node, providerType) {
92357
92682
  return node?.nodeFacts?.providerEnablement?.[providerType]?.enabled === false;
92358
92683
  }
@@ -92398,7 +92723,15 @@ ${e?.stderr || ""}`;
92398
92723
  stages: {
92399
92724
  difficultyFloor: { required: difficultyFloorRequired, admittedSlots: [], excludedSlots: [] },
92400
92725
  fitness: [],
92401
- quota: { fitnessOrder: [], clearOrder: [], gated: [], reordered: false }
92726
+ quota: {
92727
+ fitnessOrder: [],
92728
+ clearOrder: [],
92729
+ gated: [],
92730
+ reordered: false,
92731
+ note: QUOTA_STAGE_NOTE,
92732
+ axis: "weekly",
92733
+ sessionAxisActive: false
92734
+ }
92402
92735
  },
92403
92736
  quotaDiagnostics: []
92404
92737
  };
@@ -92426,7 +92759,7 @@ ${e?.stderr || ""}`;
92426
92759
  return { ...slotIdentity(candidate), reason: reason2 };
92427
92760
  });
92428
92761
  const fitnessOrder = selection.candidates.map((candidate) => candidate.providerType);
92429
- const fitnessWinner = fitnessOrder[0];
92762
+ const fitnessOrderHead = fitnessOrder[0];
92430
92763
  const winner = selection.winner?.providerType;
92431
92764
  const winnerIndex = selection.winner ? usableSlots.indexOf(selection.winner) : -1;
92432
92765
  const winnerScore = winnerIndex >= 0 ? scores[winnerIndex] : void 0;
@@ -92456,10 +92789,13 @@ ${e?.stderr || ""}`;
92456
92789
  providerType: entry.providerType,
92457
92790
  reason: entry.block.reason
92458
92791
  })),
92459
- ...fitnessWinner ? { fitnessWinner } : {},
92792
+ ...fitnessOrderHead ? { fitnessWinner: fitnessOrderHead, fitnessOrderHead } : {},
92793
+ note: QUOTA_STAGE_NOTE,
92460
92794
  ...winner ? { winner } : {},
92461
- reordered: !!winner && !!fitnessWinner && winner !== fitnessWinner,
92462
- ...winner && fitnessWinner && winner !== fitnessWinner ? { displacedFitnessWinner: fitnessWinner } : {}
92795
+ reordered: !!winner && !!fitnessOrderHead && winner !== fitnessOrderHead,
92796
+ ...winner && fitnessOrderHead && winner !== fitnessOrderHead ? { displacedFitnessWinner: fitnessOrderHead } : {},
92797
+ axis: selection.ranked.sessionAxisActive ? "session" : "weekly",
92798
+ sessionAxisActive: selection.ranked.sessionAxisActive === true
92463
92799
  }
92464
92800
  },
92465
92801
  quotaDiagnostics: selection.diagnostics.quotaDiagnostics ?? []
@@ -109694,8 +110030,8 @@ ${marker}`,
109694
110030
  const landedQuestion = readFocusedClaudeTuiQuestion(landed.screenText);
109695
110031
  const rereadQuestion = readFocusedClaudeTuiQuestion(reread);
109696
110032
  if (!landedQuestion || !rereadQuestion) return true;
109697
- const normalize5 = (text) => text.replace(/\s+/g, " ").trim();
109698
- return normalize5(landedQuestion.question) === normalize5(rereadQuestion.question);
110033
+ const normalize6 = (text) => text.replace(/\s+/g, " ").trim();
110034
+ return normalize6(landedQuestion.question) === normalize6(rereadQuestion.question);
109699
110035
  }
109700
110036
  async captureClaudeTuiPrompt(firstScreen, headers) {
109701
110037
  if (this.claudeTuiCaptureSuppressed) return;
@@ -109912,8 +110248,8 @@ ${marker}`,
109912
110248
  };
109913
110249
  }
109914
110250
  function isPathInsideWorkspace(configPath, workspace) {
109915
- const normalize5 = (value) => value.replace(/[\\/]+$/, "");
109916
- const ws = normalize5(workspace);
110251
+ const normalize6 = (value) => value.replace(/[\\/]+$/, "");
110252
+ const ws = normalize6(workspace);
109917
110253
  if (!ws) return false;
109918
110254
  const separatorAgnostic = (value) => value.replace(/\\/g, "/");
109919
110255
  const normalizedPath = separatorAgnostic(configPath);
@@ -123280,9 +123616,9 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
123280
123616
  }
123281
123617
  }
123282
123618
  compareVersions(a, b) {
123283
- const normalize5 = (v) => v.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
123284
- const pa = normalize5(a);
123285
- const pb = normalize5(b);
123619
+ const normalize6 = (v) => v.split(/[-_+]/)[0].split(".").map((x) => parseInt(x, 10) || 0);
123620
+ const pa = normalize6(a);
123621
+ const pb = normalize6(b);
123286
123622
  for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
123287
123623
  const va = pa[i] || 0;
123288
123624
  const vb = pb[i] || 0;
@@ -125027,8 +125363,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125027
125363
  let submodulesInitialized2 = false;
125028
125364
  if (initSubmodules) {
125029
125365
  try {
125030
- const { runGit: runGit3 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
125031
- await runGit3(
125366
+ const { runGit: runGit4 } = await Promise.resolve().then(() => (init_git_executor(), git_executor_exports));
125367
+ await runGit4(
125032
125368
  { workspace: result.worktreePath, repoRoot: result.worktreePath, isGitRepo: true },
125033
125369
  ["submodule", "update", "--init", "--recursive"],
125034
125370
  { timeoutMs: 12e4 }
@@ -125591,6 +125927,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125591
125927
  init_dist();
125592
125928
  init_mesh_fast_forward();
125593
125929
  init_cli_detector();
125930
+ init_mesh_refine_submodule_preflight();
125594
125931
  var fastForwardHandlers = {
125595
125932
  mesh_init: async (ctx, args) => {
125596
125933
  const workspace = typeof args?.workspace === "string" && args.workspace.trim() ? args.workspace.trim() : process.cwd();
@@ -125613,6 +125950,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125613
125950
  const mesh = meshRecord?.mesh;
125614
125951
  const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
125615
125952
  if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
125953
+ const submoduleReachabilityPreflight = await planMeshRefineNodeSubmodulePreflight({ mesh, node }).catch(() => void 0);
125616
125954
  return {
125617
125955
  success: true,
125618
125956
  dryRun: true,
@@ -125620,7 +125958,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125620
125958
  workspace: node.workspace,
125621
125959
  validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
125622
125960
  mergeWillRun: false,
125623
- cleanupWillRun: false
125961
+ cleanupWillRun: false,
125962
+ ...submoduleReachabilityPreflight ? { submoduleReachabilityPreflight } : {}
125624
125963
  };
125625
125964
  },
125626
125965
  fast_forward_mesh_node: async (ctx, args) => {
@@ -125717,6 +126056,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125717
126056
  const mesh = meshRecord?.mesh;
125718
126057
  const node = mesh?.nodes?.find((n) => meshNodeIdMatches(n, nodeId));
125719
126058
  if (!node?.workspace) return { success: false, error: `Node '${nodeId}' workspace not found` };
126059
+ const submoduleReachabilityPreflight = await planMeshRefineNodeSubmodulePreflight({ mesh, node }).catch(() => void 0);
125720
126060
  return {
125721
126061
  success: true,
125722
126062
  dryRun: true,
@@ -125725,6 +126065,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
125725
126065
  validationPlan: buildMeshRefineValidationPlan(mesh, node.workspace),
125726
126066
  mergeWillRun: false,
125727
126067
  cleanupWillRun: false,
126068
+ ...submoduleReachabilityPreflight ? { submoduleReachabilityPreflight } : {},
125728
126069
  hint: "Dry-run only \u2014 no merge/push/cleanup performed. Re-invoke with execute:true to converge this node."
125729
126070
  };
125730
126071
  }
@@ -126324,8 +126665,8 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
126324
126665
  }
126325
126666
  }
126326
126667
  };
126327
- var import_path16 = require("path");
126328
- var fs50 = __toESM2(require("fs"));
126668
+ var import_path20 = require("path");
126669
+ var fs53 = __toESM2(require("fs"));
126329
126670
  init_logger();
126330
126671
  init_mesh_host_ownership();
126331
126672
  init_coordinator_registry();
@@ -126365,9 +126706,9 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
126365
126706
  }
126366
126707
  }
126367
126708
  function isWorkspaceLocalPath(configPath, workspace) {
126368
- const resolvedConfig = (0, import_path16.resolve)(configPath);
126369
- const resolvedWorkspace = (0, import_path16.resolve)(workspace);
126370
- return resolvedConfig === resolvedWorkspace || resolvedConfig.startsWith(resolvedWorkspace + import_path16.sep);
126709
+ const resolvedConfig = (0, import_path20.resolve)(configPath);
126710
+ const resolvedWorkspace = (0, import_path20.resolve)(workspace);
126711
+ return resolvedConfig === resolvedWorkspace || resolvedConfig.startsWith(resolvedWorkspace + import_path20.sep);
126371
126712
  }
126372
126713
  var meshCoordinatorLaunchHandlers = {
126373
126714
  launch_mesh_coordinator: async (ctx, args) => {
@@ -126629,16 +126970,16 @@ ${ptyResult.output.slice(-2e3)}`);
126629
126970
  };
126630
126971
  }
126631
126972
  if (cliType === "codex-cli") {
126632
- const repoMcpConfigPath = (0, import_path16.join)(workspace, ".mcp.json");
126633
- if (fs50.existsSync(repoMcpConfigPath)) {
126973
+ const repoMcpConfigPath = (0, import_path20.join)(workspace, ".mcp.json");
126974
+ if (fs53.existsSync(repoMcpConfigPath)) {
126634
126975
  try {
126635
126976
  const repoMcpConfig = parseMeshCoordinatorMcpConfig(
126636
- fs50.readFileSync(repoMcpConfigPath, "utf-8"),
126977
+ fs53.readFileSync(repoMcpConfigPath, "utf-8"),
126637
126978
  "claude_mcp_json"
126638
126979
  );
126639
126980
  const existingServers2 = repoMcpConfig.mcpServers;
126640
126981
  if (existingServers2 && typeof existingServers2 === "object" && !Array.isArray(existingServers2) && existingServers2[coordinatorSetup.serverName]) {
126641
- fs50.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
126982
+ fs53.writeFileSync(repoMcpConfigPath, serializeMeshCoordinatorMcpConfig({
126642
126983
  ...repoMcpConfig,
126643
126984
  mcpServers: {
126644
126985
  ...existingServers2,
@@ -127009,7 +127350,7 @@ ${ptyResult.output.slice(-2e3)}`);
127009
127350
  }
127010
127351
  }
127011
127352
  };
127012
- var fs51 = __toESM2(require("fs"));
127353
+ var fs54 = __toESM2(require("fs"));
127013
127354
  var import_os4 = require("os");
127014
127355
  init_config();
127015
127356
  init_git_status();
@@ -127018,7 +127359,7 @@ ${ptyResult.output.slice(-2e3)}`);
127018
127359
  init_mesh_turn_presentation();
127019
127360
  init_mesh_routing();
127020
127361
  init_mesh_host_ownership();
127021
- var import_node_child_process9 = require("child_process");
127362
+ var import_node_child_process13 = require("child_process");
127022
127363
  var import_node_fs6 = require("fs");
127023
127364
  init_git_locale();
127024
127365
  var import_node_path4 = require("path");
@@ -127043,9 +127384,9 @@ ${ptyResult.output.slice(-2e3)}`);
127043
127384
  if (PREVIEW_PIPELINE_SCRIPTS.some((rel) => (0, import_node_fs6.existsSync)((0, import_node_path4.resolve)(repoRoot, rel)))) return true;
127044
127385
  return hasDeployPreviewNpmScript(repoRoot);
127045
127386
  }
127046
- function runGit2(repoRoot, args) {
127387
+ function runGit3(repoRoot, args) {
127047
127388
  try {
127048
- return (0, import_node_child_process9.execFileSync)("git", args, {
127389
+ return (0, import_node_child_process13.execFileSync)("git", args, {
127049
127390
  cwd: repoRoot,
127050
127391
  encoding: "utf8",
127051
127392
  stdio: ["ignore", "pipe", "ignore"],
@@ -127084,11 +127425,11 @@ ${ptyResult.output.slice(-2e3)}`);
127084
127425
  return result;
127085
127426
  }
127086
127427
  function readCurrentMainCommit(repoRoot) {
127087
- const originMain = runGit2(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
127428
+ const originMain = runGit3(repoRoot, ["rev-parse", "--verify", "origin/main^{commit}"]);
127088
127429
  if (originMain) {
127089
127430
  return { currentMainCommit: originMain, currentMainCommitSource: "origin/main" };
127090
127431
  }
127091
- const head = runGit2(repoRoot, ["rev-parse", "--verify", "HEAD"]);
127432
+ const head = runGit3(repoRoot, ["rev-parse", "--verify", "HEAD"]);
127092
127433
  if (head) {
127093
127434
  return { currentMainCommit: head, currentMainCommitSource: "HEAD" };
127094
127435
  }
@@ -127392,7 +127733,7 @@ ${ptyResult.output.slice(-2e3)}`);
127392
127733
  }
127393
127734
  }
127394
127735
  if (workspace) {
127395
- if (!fs51.existsSync(workspace)) {
127736
+ if (!fs54.existsSync(workspace)) {
127396
127737
  const inlineTransitGit = buildInlineMeshTransitGitStatus(node);
127397
127738
  let remoteProbeApplied = false;
127398
127739
  if (inlineTransitGit) {
@@ -127533,7 +127874,7 @@ ${ptyResult.output.slice(-2e3)}`);
127533
127874
  const pendingRetentionCounters2 = { ...getPendingRetentionCounters() };
127534
127875
  const turnPresentationCounters = getTurnPresentationMetrics();
127535
127876
  const previewFreshness = (() => {
127536
- const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs51.existsSync(candidate));
127877
+ const localRepoRoot = nodeStatuses.map((node) => readStringValue(node?.git?.repoRoot, node?.repoRoot, node?.workspace)).find((candidate) => !!candidate && fs54.existsSync(candidate));
127537
127878
  return localRepoRoot ? buildPreviewFreshness(localRepoRoot) : void 0;
127538
127879
  })();
127539
127880
  const asyncRefineJobs = buildMeshAsyncRefineJobs({
@@ -127731,7 +128072,7 @@ ${ptyResult.output.slice(-2e3)}`);
127731
128072
  );
127732
128073
  init_dist();
127733
128074
  init_logger();
127734
- var fs52 = __toESM2(require("fs"));
128075
+ var fs55 = __toESM2(require("fs"));
127735
128076
  var path56 = __toESM2(require("path"));
127736
128077
  init_config_dir();
127737
128078
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
@@ -127780,7 +128121,7 @@ ${ptyResult.output.slice(-2e3)}`);
127780
128121
  currentFile = path56.join(dir, `commands-${today}.jsonl`);
127781
128122
  if (dirChanged) {
127782
128123
  try {
127783
- fs52.mkdirSync(dir, { recursive: true });
128124
+ fs55.mkdirSync(dir, { recursive: true });
127784
128125
  } catch {
127785
128126
  }
127786
128127
  cleanOldFiles();
@@ -127788,7 +128129,7 @@ ${ptyResult.output.slice(-2e3)}`);
127788
128129
  }
127789
128130
  function cleanOldFiles() {
127790
128131
  try {
127791
- const files = fs52.readdirSync(currentDir).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
128132
+ const files = fs55.readdirSync(currentDir).filter((f) => f.startsWith("commands-") && f.endsWith(".jsonl"));
127792
128133
  const cutoff = /* @__PURE__ */ new Date();
127793
128134
  cutoff.setDate(cutoff.getDate() - MAX_DAYS);
127794
128135
  const cutoffStr = cutoff.toISOString().slice(0, 10);
@@ -127796,7 +128137,7 @@ ${ptyResult.output.slice(-2e3)}`);
127796
128137
  const dateMatch = file2.match(/commands-(\d{4}-\d{2}-\d{2})/);
127797
128138
  if (dateMatch && dateMatch[1] < cutoffStr) {
127798
128139
  try {
127799
- fs52.unlinkSync(path56.join(currentDir, file2));
128140
+ fs55.unlinkSync(path56.join(currentDir, file2));
127800
128141
  } catch {
127801
128142
  }
127802
128143
  }
@@ -127806,14 +128147,14 @@ ${ptyResult.output.slice(-2e3)}`);
127806
128147
  }
127807
128148
  function checkSize() {
127808
128149
  try {
127809
- const stat2 = fs52.statSync(currentFile);
128150
+ const stat2 = fs55.statSync(currentFile);
127810
128151
  if (stat2.size > MAX_FILE_SIZE) {
127811
128152
  const backup = currentFile.replace(".jsonl", ".1.jsonl");
127812
128153
  try {
127813
- fs52.unlinkSync(backup);
128154
+ fs55.unlinkSync(backup);
127814
128155
  } catch {
127815
128156
  }
127816
- fs52.renameSync(currentFile, backup);
128157
+ fs55.renameSync(currentFile, backup);
127817
128158
  }
127818
128159
  } catch {
127819
128160
  }
@@ -127846,15 +128187,15 @@ ${ptyResult.output.slice(-2e3)}`);
127846
128187
  ...entry.error ? { err: entry.error } : {},
127847
128188
  ...entry.durationMs !== void 0 ? { ms: entry.durationMs } : {}
127848
128189
  });
127849
- fs52.appendFileSync(currentFile, line + "\n");
128190
+ fs55.appendFileSync(currentFile, line + "\n");
127850
128191
  } catch {
127851
128192
  }
127852
128193
  }
127853
128194
  function getRecentCommands(count = 50) {
127854
128195
  try {
127855
128196
  refreshCurrentFile();
127856
- if (!fs52.existsSync(currentFile)) return [];
127857
- const content = fs52.readFileSync(currentFile, "utf-8");
128197
+ if (!fs55.existsSync(currentFile)) return [];
128198
+ const content = fs55.readFileSync(currentFile, "utf-8");
127858
128199
  const lines = content.trim().split("\n").filter(Boolean);
127859
128200
  return lines.slice(-count).map((line) => {
127860
128201
  try {
@@ -127886,7 +128227,7 @@ ${ptyResult.output.slice(-2e3)}`);
127886
128227
  init_router_refine();
127887
128228
  var fs56 = __toESM2(require("fs"));
127888
128229
  var import_node_os22 = require("os");
127889
- var import_path20 = require("path");
128230
+ var import_path21 = require("path");
127890
128231
  init_logger();
127891
128232
  init_git_locale();
127892
128233
  init_dist();
@@ -127898,7 +128239,7 @@ ${ptyResult.output.slice(-2e3)}`);
127898
128239
  function acceptableManagedWorktreePaths(resolveWorktreePath2, normalizePath2, repoRoot, meshName, branch, worktreeBaseDir) {
127899
128240
  const safeBranch = branch.replace(/[/\\:*?"<>|]/g, "-").replace(/^\.+|\.+$/g, "");
127900
128241
  const safeMeshName = meshName.replace(/[/\\:*?"<>|]/g, "-").replace(/^\.+|\.+$/g, "");
127901
- const legacyPath = (0, import_path20.join)((0, import_path20.dirname)(repoRoot), LEGACY_WORKTREE_DIR_NAME, safeMeshName, safeBranch);
128242
+ const legacyPath = (0, import_path21.join)((0, import_path21.dirname)(repoRoot), LEGACY_WORKTREE_DIR_NAME, safeMeshName, safeBranch);
127902
128243
  const candidates = [
127903
128244
  resolveWorktreePath2(repoRoot, meshName, branch, worktreeBaseDir),
127904
128245
  legacyPath
@@ -127925,8 +128266,8 @@ ${ptyResult.output.slice(-2e3)}`);
127925
128266
  function looksLikeCrossTrackWorktreePath(actualPath, normalizePath2) {
127926
128267
  const home = normalizePath2((0, import_node_os22.homedir)());
127927
128268
  return TRACK_CONFIG_DIR_NAMES.some((trackDirName) => {
127928
- const trackWorktreesDir = (0, import_path20.join)(home, trackDirName, "worktrees");
127929
- return actualPath === normalizePath2(trackWorktreesDir) || actualPath.startsWith(normalizePath2(trackWorktreesDir) + import_path20.sep);
128269
+ const trackWorktreesDir = (0, import_path21.join)(home, trackDirName, "worktrees");
128270
+ return actualPath === normalizePath2(trackWorktreesDir) || actualPath.startsWith(normalizePath2(trackWorktreesDir) + import_path21.sep);
127930
128271
  });
127931
128272
  }
127932
128273
  function unexpectedPathRecoveryHint(actualPath, normalizePath2, suffix) {
@@ -127953,11 +128294,11 @@ ${ptyResult.output.slice(-2e3)}`);
127953
128294
  }
127954
128295
  async function hasUnpushedWorktreeCommits(workspace) {
127955
128296
  try {
127956
- const { execFile: execFile8 } = await import("child_process");
127957
- const { promisify: promisify11 } = await import("util");
127958
- const execFileAsync7 = promisify11(execFile8);
128297
+ const { execFile: execFile9 } = await import("child_process");
128298
+ const { promisify: promisify12 } = await import("util");
128299
+ const execFileAsync8 = promisify12(execFile9);
127959
128300
  const git3 = async (gitArgs) => {
127960
- const { stdout } = await execFileAsync7("git", gitArgs, {
128301
+ const { stdout } = await execFileAsync8("git", gitArgs, {
127961
128302
  cwd: workspace,
127962
128303
  encoding: "utf8",
127963
128304
  timeout: 3e4,
@@ -128036,7 +128377,7 @@ ${ptyResult.output.slice(-2e3)}`);
128036
128377
  }
128037
128378
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
128038
128379
  const normalizePath2 = (value) => {
128039
- const resolved = (0, import_path20.resolve)(value);
128380
+ const resolved = (0, import_path21.resolve)(value);
128040
128381
  try {
128041
128382
  return fs56.realpathSync(resolved);
128042
128383
  } catch {
@@ -128092,11 +128433,11 @@ ${ptyResult.output.slice(-2e3)}`);
128092
128433
  }
128093
128434
  }
128094
128435
  if (args.force !== true) {
128095
- const { execFile: execFile8 } = await import("child_process");
128096
- const { promisify: promisify11 } = await import("util");
128097
- const execFileAsync7 = promisify11(execFile8);
128436
+ const { execFile: execFile9 } = await import("child_process");
128437
+ const { promisify: promisify12 } = await import("util");
128438
+ const execFileAsync8 = promisify12(execFile9);
128098
128439
  try {
128099
- const { stdout } = await execFileAsync7("git", ["status", "--porcelain"], {
128440
+ const { stdout } = await execFileAsync8("git", ["status", "--porcelain"], {
128100
128441
  cwd: workspace,
128101
128442
  encoding: "utf8",
128102
128443
  timeout: 3e4,
@@ -128163,7 +128504,7 @@ ${ptyResult.output.slice(-2e3)}`);
128163
128504
  }
128164
128505
  const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
128165
128506
  const normalizePath2 = (value) => {
128166
- const resolved = (0, import_path20.resolve)(value);
128507
+ const resolved = (0, import_path21.resolve)(value);
128167
128508
  try {
128168
128509
  return fs56.realpathSync(resolved);
128169
128510
  } catch {
@@ -128192,10 +128533,10 @@ ${ptyResult.output.slice(-2e3)}`);
128192
128533
  const managedEntry = entries.find((entry) => normalizePath2(entry.path) === actualPath);
128193
128534
  if (!managedEntry) {
128194
128535
  try {
128195
- const { execFile: execFile8 } = await import("child_process");
128196
- const { promisify: promisify11 } = await import("util");
128197
- const execFileAsync7 = promisify11(execFile8);
128198
- await execFileAsync7("git", ["worktree", "prune"], {
128536
+ const { execFile: execFile9 } = await import("child_process");
128537
+ const { promisify: promisify12 } = await import("util");
128538
+ const execFileAsync8 = promisify12(execFile9);
128539
+ await execFileAsync8("git", ["worktree", "prune"], {
128199
128540
  cwd: repoRoot,
128200
128541
  encoding: "utf8",
128201
128542
  timeout: 3e4,
@@ -128284,15 +128625,15 @@ ${ptyResult.output.slice(-2e3)}`);
128284
128625
  const isSubmoduleGuard = /working trees containing submodules cannot be moved or removed/i.test(message);
128285
128626
  const submoduleForceBlocked = isSubmoduleGuard && !forceFallbackConvergence.allow;
128286
128627
  if (forceFallbackConvergence.allow && !dirty) {
128287
- const { execFile: execFile8 } = await import("child_process");
128288
- const { promisify: promisify11 } = await import("util");
128289
- const execFileAsync7 = promisify11(execFile8);
128628
+ const { execFile: execFile9 } = await import("child_process");
128629
+ const { promisify: promisify12 } = await import("util");
128630
+ const execFileAsync8 = promisify12(execFile9);
128290
128631
  const GIT_TIMEOUT_CLEANUP = 3e4;
128291
128632
  const GIT_MAX_BUFFER_CLEANUP = 4 * 1024 * 1024;
128292
128633
  const fallbackReason = isSubmoduleGuard ? "working_trees_containing_submodules" : "worktree_remove_failed";
128293
128634
  try {
128294
128635
  if (isSubmoduleGuard) {
128295
- await execFileAsync7("git", ["-C", workspace, "submodule", "deinit", "--all", "-f"], {
128636
+ await execFileAsync8("git", ["-C", workspace, "submodule", "deinit", "--all", "-f"], {
128296
128637
  encoding: "utf8",
128297
128638
  timeout: GIT_TIMEOUT_CLEANUP,
128298
128639
  maxBuffer: GIT_MAX_BUFFER_CLEANUP,
@@ -128300,7 +128641,7 @@ ${ptyResult.output.slice(-2e3)}`);
128300
128641
  env: gitChildEnv()
128301
128642
  });
128302
128643
  }
128303
- await execFileAsync7("git", ["worktree", "remove", "--force", workspace], {
128644
+ await execFileAsync8("git", ["worktree", "remove", "--force", workspace], {
128304
128645
  cwd: repoRoot,
128305
128646
  encoding: "utf8",
128306
128647
  timeout: GIT_TIMEOUT_CLEANUP,
@@ -128322,7 +128663,7 @@ ${ptyResult.output.slice(-2e3)}`);
128322
128663
  } catch (deinitError) {
128323
128664
  const rm = await self.bestEffortRemoveWorktreeDir(workspace);
128324
128665
  try {
128325
- await execFileAsync7("git", ["worktree", "prune"], {
128666
+ await execFileAsync8("git", ["worktree", "prune"], {
128326
128667
  cwd: repoRoot,
128327
128668
  encoding: "utf8",
128328
128669
  timeout: GIT_TIMEOUT_CLEANUP,
@@ -128368,11 +128709,11 @@ ${ptyResult.output.slice(-2e3)}`);
128368
128709
  if (refinedConvergence === "merged_pushed" || refinedConvergence === "merged_to_main") {
128369
128710
  return { allow: true, status: refinedConvergence, source: "node_refine_state" };
128370
128711
  }
128371
- const { execFile: execFile8 } = await import("child_process");
128372
- const { promisify: promisify11 } = await import("util");
128373
- const execFileAsync7 = promisify11(execFile8);
128374
- const runGit3 = async (gitArgs, cwd) => {
128375
- const { stdout } = await execFileAsync7("git", gitArgs, {
128712
+ const { execFile: execFile9 } = await import("child_process");
128713
+ const { promisify: promisify12 } = await import("util");
128714
+ const execFileAsync8 = promisify12(execFile9);
128715
+ const runGit4 = async (gitArgs, cwd) => {
128716
+ const { stdout } = await execFileAsync8("git", gitArgs, {
128376
128717
  cwd,
128377
128718
  encoding: "utf8",
128378
128719
  timeout: 3e4,
@@ -128393,7 +128734,7 @@ ${ptyResult.output.slice(-2e3)}`);
128393
128734
  return { allow: false, error: "worktree path is missing and worktreeBranch metadata is absent, so the branch tip cannot be resolved" };
128394
128735
  }
128395
128736
  try {
128396
- head = await runGit3(["rev-parse", "--verify", `${branch}^{commit}`], args.repoRoot);
128737
+ head = await runGit4(["rev-parse", "--verify", `${branch}^{commit}`], args.repoRoot);
128397
128738
  } catch {
128398
128739
  return { allow: true, status: "worktree_and_branch_absent", source: "git_branch_absent" };
128399
128740
  }
@@ -128402,7 +128743,7 @@ ${ptyResult.output.slice(-2e3)}`);
128402
128743
  }
128403
128744
  } else {
128404
128745
  try {
128405
- head = await runGit3(["rev-parse", "HEAD"], args.workspace);
128746
+ head = await runGit4(["rev-parse", "HEAD"], args.workspace);
128406
128747
  } catch (e) {
128407
128748
  return { allow: false, error: `could not resolve worktree HEAD: ${e?.message || e}` };
128408
128749
  }
@@ -128410,7 +128751,7 @@ ${ptyResult.output.slice(-2e3)}`);
128410
128751
  }
128411
128752
  const candidateRefs = [];
128412
128753
  try {
128413
- const defaultBranch = await runGit3(["branch", "--show-current"], args.repoRoot);
128754
+ const defaultBranch = await runGit4(["branch", "--show-current"], args.repoRoot);
128414
128755
  if (defaultBranch) {
128415
128756
  candidateRefs.push(defaultBranch, `origin/${defaultBranch}`);
128416
128757
  }
@@ -128425,14 +128766,14 @@ ${ptyResult.output.slice(-2e3)}`);
128425
128766
  seen.add(ref);
128426
128767
  let commit = "";
128427
128768
  try {
128428
- commit = await runGit3(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
128769
+ commit = await runGit4(["rev-parse", "--verify", `${ref}^{commit}`], args.repoRoot);
128429
128770
  } catch {
128430
128771
  continue;
128431
128772
  }
128432
128773
  checkedRefs.push(ref);
128433
128774
  resolvedRefCommits.push({ ref, commit });
128434
128775
  try {
128435
- await runGit3(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
128776
+ await runGit4(["merge-base", "--is-ancestor", head, commit], args.repoRoot);
128436
128777
  return { allow: true, status: "merged_to_default_ref", source: "git_merge_base", ref };
128437
128778
  } catch {
128438
128779
  }
@@ -128831,7 +129172,7 @@ ${ptyResult.output.slice(-2e3)}`);
128831
129172
  init_logger();
128832
129173
  var yaml5 = __toESM2(require_js_yaml());
128833
129174
  var import_os5 = require("os");
128834
- var import_path21 = require("path");
129175
+ var import_path222 = require("path");
128835
129176
  var fs57 = __toESM2(require("fs"));
128836
129177
  var MESH_COORDINATOR_AUTO_IMPORT_FORMATS = ["claude_mcp_json", "hermes_config_yaml", "opencode_json"];
128837
129178
  function isSupportedMeshCoordinatorConfigFormat(format) {
@@ -128872,13 +129213,13 @@ ${ptyResult.output.slice(-2e3)}`);
128872
129213
  }
128873
129214
  function resolveHermesUserHome() {
128874
129215
  const explicitHome = process.env.HERMES_HOME?.trim();
128875
- return explicitHome || (0, import_path21.join)((0, import_os5.homedir)(), ".hermes");
129216
+ return explicitHome || (0, import_path222.join)((0, import_os5.homedir)(), ".hermes");
128876
129217
  }
128877
129218
  function loadHermesCoordinatorBaseConfig(targetConfigPath) {
128878
129219
  const sourceHome = resolveHermesUserHome();
128879
- const sourceConfigPath = (0, import_path21.join)(sourceHome, "config.yaml");
129220
+ const sourceConfigPath = (0, import_path222.join)(sourceHome, "config.yaml");
128880
129221
  if (!fs57.existsSync(sourceConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
128881
- if ((0, import_path21.resolve)(sourceConfigPath) === (0, import_path21.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
129222
+ if ((0, import_path222.resolve)(sourceConfigPath) === (0, import_path222.resolve)(targetConfigPath)) return { config: {}, sourceHome, sourceConfigPath };
128882
129223
  const parsed = parseMeshCoordinatorMcpConfig(fs57.readFileSync(sourceConfigPath, "utf-8"), "hermes_config_yaml");
128883
129224
  const { mcp_servers: _mcpServers, ...baseConfig } = parsed;
128884
129225
  return { config: baseConfig, sourceHome, sourceConfigPath };
@@ -128912,10 +129253,10 @@ ${ptyResult.output.slice(-2e3)}`);
128912
129253
  return sanitized;
128913
129254
  }
128914
129255
  function copyHermesCoordinatorCredentialFiles(sourceHome, targetHome) {
128915
- if ((0, import_path21.resolve)(sourceHome) === (0, import_path21.resolve)(targetHome)) return;
129256
+ if ((0, import_path222.resolve)(sourceHome) === (0, import_path222.resolve)(targetHome)) return;
128916
129257
  for (const fileName of [".env", "auth.json"]) {
128917
- const sourcePath = (0, import_path21.join)(sourceHome, fileName);
128918
- const targetPath = (0, import_path21.join)(targetHome, fileName);
129258
+ const sourcePath = (0, import_path222.join)(sourceHome, fileName);
129259
+ const targetPath = (0, import_path222.join)(targetHome, fileName);
128919
129260
  if (!fs57.existsSync(sourcePath)) continue;
128920
129261
  try {
128921
129262
  fs57.copyFileSync(sourcePath, targetPath);
@@ -138296,7 +138637,7 @@ data: ${JSON.stringify(msg.data)}
138296
138637
  init_mesh_events();
138297
138638
  init_mesh_reconcile_loop();
138298
138639
  var import_fs20 = require("fs");
138299
- var import_path222 = require("path");
138640
+ var import_path23 = require("path");
138300
138641
  var import_crypto18 = require("crypto");
138301
138642
  init_logger();
138302
138643
  init_mesh_ledger();
@@ -138374,7 +138715,7 @@ data: ${JSON.stringify(msg.data)}
138374
138715
  }
138375
138716
  for (const name of names) {
138376
138717
  if (!isPendingEventsFile(name)) continue;
138377
- const path63 = (0, import_path222.join)(dir, name);
138718
+ const path63 = (0, import_path23.join)(dir, name);
138378
138719
  result.filesScanned++;
138379
138720
  const claimed = `${path63}.migrating`;
138380
138721
  try {