@adhdev/daemon-standalone 1.0.56-rc.19 → 1.0.56-rc.20

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
@@ -36622,10 +36622,10 @@ var require_dist3 = __commonJS({
36622
36622
  }
36623
36623
  function getDaemonBuildInfo() {
36624
36624
  if (cached2) return cached2;
36625
- const commit = readInjected(true ? "6d9cfa28a604d36d2b29cf1cdd21499c13171ab4" : void 0) ?? "unknown";
36626
- const commitShort = readInjected(true ? "6d9cfa28" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36627
- const version2 = readInjected(true ? "1.0.56-rc.19" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36628
- const builtAt = readInjected(true ? "2026-08-20T17:59:03.306Z" : void 0);
36625
+ const commit = readInjected(true ? "cc85ef744099479d57036518cd809b2c0a2ea5dc" : void 0) ?? "unknown";
36626
+ const commitShort = readInjected(true ? "cc85ef74" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36627
+ const version2 = readInjected(true ? "1.0.56-rc.20" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36628
+ const builtAt = readInjected(true ? "2026-08-21T01:12:48.071Z" : void 0);
36629
36629
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
36630
36630
  return cached2;
36631
36631
  }
@@ -53591,6 +53591,58 @@ The instruction it carried was never delivered to anyone. If it still matters, r
53591
53591
  MAX_CLONE_CHAIN = 16;
53592
53592
  }
53593
53593
  });
53594
+ function selectClaimCandidate(candidates, gates) {
53595
+ let deepestIndex = -1;
53596
+ let deepestReason;
53597
+ let deepest;
53598
+ for (const candidate of candidates) {
53599
+ const failedAt = gates.findIndex((gate) => !gate.test(candidate));
53600
+ if (failedAt === -1) return { entry: candidate };
53601
+ if (failedAt > deepestIndex) {
53602
+ deepestIndex = failedAt;
53603
+ deepestReason = gates[failedAt].reason;
53604
+ deepest = candidate;
53605
+ }
53606
+ }
53607
+ return { reason: deepestReason ?? "no_pending_candidates", ...deepest !== void 0 ? { deepest } : {} };
53608
+ }
53609
+ function claimDeferralKey(meshId, nodeId) {
53610
+ return `${meshId}::${nodeId}`;
53611
+ }
53612
+ function noteClaimDeferredForNode(meshId, nodeId) {
53613
+ if (!nodeId) return;
53614
+ const key2 = claimDeferralKey(meshId, nodeId);
53615
+ claimDeferredByFastForward.set(key2, (claimDeferredByFastForward.get(key2) || 0) + 1);
53616
+ if (claimDeferredByFastForward.size > CLAIM_DEFERRAL_MAX_ENTRIES) {
53617
+ const oldest = claimDeferredByFastForward.keys().next().value;
53618
+ if (oldest !== void 0) claimDeferredByFastForward.delete(oldest);
53619
+ }
53620
+ }
53621
+ function claimDeferralOwedForNode(meshId, nodeId) {
53622
+ if (!nodeId) return false;
53623
+ const seen = claimDeferredByFastForward.get(claimDeferralKey(meshId, nodeId)) || 0;
53624
+ return seen > 0 && seen <= MAX_FAST_FORWARD_CLAIM_REDRIVES;
53625
+ }
53626
+ function shouldRedriveDeferredClaim(meshId, nodeId, sessionId, leaseHeld) {
53627
+ if (!nodeId || !sessionId) return false;
53628
+ if (!claimDeferralOwedForNode(meshId, nodeId)) return false;
53629
+ return !leaseHeld();
53630
+ }
53631
+ function clearClaimDeferralForNode(meshId, nodeId) {
53632
+ if (!nodeId) return;
53633
+ claimDeferredByFastForward.delete(claimDeferralKey(meshId, nodeId));
53634
+ }
53635
+ var claimDeferredByFastForward;
53636
+ var MAX_FAST_FORWARD_CLAIM_REDRIVES;
53637
+ var CLAIM_DEFERRAL_MAX_ENTRIES;
53638
+ var init_mesh_claim_refusal = __esm2({
53639
+ "src/mesh/mesh-claim-refusal.ts"() {
53640
+ "use strict";
53641
+ claimDeferredByFastForward = /* @__PURE__ */ new Map();
53642
+ MAX_FAST_FORWARD_CLAIM_REDRIVES = 3;
53643
+ CLAIM_DEFERRAL_MAX_ENTRIES = 2e3;
53644
+ }
53645
+ });
53594
53646
  function meshTurnAttemptFromRow(r) {
53595
53647
  return {
53596
53648
  attemptId: r.attempt_id,
@@ -53740,6 +53792,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
53740
53792
  init_slot_model_enforcement();
53741
53793
  init_mesh_daemon_slot_axis();
53742
53794
  init_dist();
53795
+ init_mesh_claim_refusal();
53743
53796
  init_mesh_runtime_store_turn_rows();
53744
53797
  init_mesh_runtime_store_turn_rows();
53745
53798
  loggedMigrationFailure = false;
@@ -54647,7 +54700,14 @@ The instruction it carried was never delivered to anyone. If it still matters, r
54647
54700
  claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags = [], opts) {
54648
54701
  return this.transaction(() => {
54649
54702
  this.ensureLegacyQueueMigrated(meshId);
54650
- if (this.hasActiveSessionAssignment(meshId, sessionId)) return null;
54703
+ const refuse = (reason, detail) => {
54704
+ if (opts?.outRefusal) {
54705
+ opts.outRefusal.reason = reason;
54706
+ if (detail) opts.outRefusal.detail = detail;
54707
+ }
54708
+ return null;
54709
+ };
54710
+ if (this.hasActiveSessionAssignment(meshId, sessionId)) return refuse("session_already_assigned");
54651
54711
  const nodeBusy = this.hasActiveNodeAssignment(meshId, nodeId);
54652
54712
  const providerType = typeof opts?.providerType === "string" ? opts.providerType.trim() : "";
54653
54713
  const providerMaxParallel = opts?.providerMaxParallel;
@@ -54720,8 +54780,22 @@ The instruction it carried was never delivered to anyone. If it still matters, r
54720
54780
  const allowedTaskDifficulties = opts?.allowedTaskDifficulties;
54721
54781
  const difficultyAllows = (candidate) => !allowedTaskDifficulties || candidate.difficulty === "freeform" || !candidate.difficulty || allowedTaskDifficulties.includes(candidate.difficulty);
54722
54782
  const notParked = (candidate) => !taskIsParked(candidate);
54723
- const entry = candidates.find((candidate) => nodeSatisfiesRequiredTags(candidate.requiredTags, capabilityTags) && dependenciesSatisfied(candidate) && notBeforeReady(candidate) && notParked(candidate) && convergenceAllows(candidate) && targetMatches(candidate) && difficultyAllows(candidate) && parallelCapsAllow(candidate) && nodeConflictAllows(candidate));
54724
- if (!entry) return null;
54783
+ const selected = selectClaimCandidate(candidates, [
54784
+ { reason: "required_tags_unsatisfied", test: (c) => nodeSatisfiesRequiredTags(c.requiredTags, capabilityTags) },
54785
+ { reason: "dependencies_unsatisfied", test: dependenciesSatisfied },
54786
+ { reason: "not_before_delayed", test: notBeforeReady },
54787
+ { reason: "task_parked", test: notParked },
54788
+ { reason: "convergence_target_is_worktree", test: convergenceAllows },
54789
+ { reason: "target_pin_unmatched", test: targetMatches },
54790
+ { reason: "difficulty_floor_unmet", test: difficultyAllows },
54791
+ { reason: "parallel_cap_reached", test: parallelCapsAllow },
54792
+ { reason: "node_busy_with_active_assignment", test: nodeConflictAllows }
54793
+ ]);
54794
+ if (!selected.entry) {
54795
+ if (!candidates.length) return refuse("no_pending_candidates");
54796
+ return refuse(selected.reason, selected.deepest ? `closest candidate ${selected.deepest.id} of ${candidates.length}` : void 0);
54797
+ }
54798
+ const entry = selected.entry;
54725
54799
  const now = (/* @__PURE__ */ new Date()).toISOString();
54726
54800
  entry.status = "assigned";
54727
54801
  entry.assignedNodeId = nodeId;
@@ -63557,6 +63631,16 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
63557
63631
  function getLastQuotaRanking(nodeId) {
63558
63632
  return lastQuotaRankingByNode.get(nodeId);
63559
63633
  }
63634
+ function recordLastQuotaRankingOutcome(nodeId, outcome, refusalReason) {
63635
+ if (!nodeId) return;
63636
+ const existing = lastQuotaRankingByNode.get(nodeId);
63637
+ if (!existing) return;
63638
+ lastQuotaRankingByNode.set(nodeId, {
63639
+ ...existing,
63640
+ claimOutcome: outcome,
63641
+ ...outcome === "refused" && refusalReason ? { claimRefusalReason: refusalReason } : {}
63642
+ });
63643
+ }
63560
63644
  function quotaSpreadBonusByProvider(node, policy, now = Date.now(), context) {
63561
63645
  const resolved = resolveQuotaRoutingPolicy(policy);
63562
63646
  const out = {};
@@ -64642,6 +64726,19 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
64642
64726
  }
64643
64727
  return 0;
64644
64728
  }
64729
+ function trimInProgressTurnToolTail(messages) {
64730
+ if (!Array.isArray(messages) || messages.length === 0) return Array.isArray(messages) ? messages : [];
64731
+ const isTrailingToolBubble = (msg) => {
64732
+ if (!msg) return false;
64733
+ const classification = classifyChatMessageVisibility(msg);
64734
+ if (classification.role !== "assistant" && classification.role !== "model") return false;
64735
+ return classification.kind === "tool" || classification.kind === "terminal";
64736
+ };
64737
+ if (!isTrailingToolBubble(messages[messages.length - 1])) return messages;
64738
+ let cut = messages.length - 1;
64739
+ while (cut >= 0 && isTrailingToolBubble(messages[cut])) cut -= 1;
64740
+ return messages.slice(0, cut + 1);
64741
+ }
64645
64742
  function canonicalizeKindHint(value) {
64646
64743
  return value.trim().toLowerCase().replace(/[\s-]+/g, "_");
64647
64744
  }
@@ -67010,6 +67107,36 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67010
67107
  function clearAllQuotaClaimCandidatesBlockedState(meshId) {
67011
67108
  lastAllQuotaClaimBlockedLog.delete(meshId);
67012
67109
  }
67110
+ function claimRefusalKey(meshId, nodeId, sessionId) {
67111
+ return `${meshId}:${nodeId}:${sessionId}`;
67112
+ }
67113
+ function recordClaimRefusal(meshId, args) {
67114
+ if (!args.reason || args.reason === "no_pending_candidates") {
67115
+ clearClaimRefusalState(meshId, args.nodeId, args.sessionId);
67116
+ return;
67117
+ }
67118
+ const key2 = claimRefusalKey(meshId, args.nodeId, args.sessionId);
67119
+ const fingerprint = `${args.reason}|${args.detail || ""}`;
67120
+ if (lastClaimRefusalLog.get(key2) === fingerprint) return;
67121
+ rememberBounded(lastClaimRefusalLog, key2, fingerprint);
67122
+ LOG2.info("MeshQueue", `CLAIM REFUSED on node ${args.nodeId} (${args.sessionId}${args.providerType ? `, ${args.providerType}` : ""}) for mesh ${meshId}: ${args.reason}${args.detail ? ` \u2014 ${args.detail}` : ""}`);
67123
+ try {
67124
+ appendLedgerEntry(meshId, {
67125
+ kind: "claim_refused",
67126
+ nodeId: args.nodeId,
67127
+ sessionId: args.sessionId,
67128
+ ...args.providerType ? { providerType: args.providerType } : {},
67129
+ payload: {
67130
+ reason: args.reason,
67131
+ ...args.detail ? { detail: args.detail } : {}
67132
+ }
67133
+ });
67134
+ } catch {
67135
+ }
67136
+ }
67137
+ function clearClaimRefusalState(meshId, nodeId, sessionId) {
67138
+ lastClaimRefusalLog.delete(claimRefusalKey(meshId, nodeId, sessionId));
67139
+ }
67013
67140
  function logAutoLaunchQuotaFallbackSuccess(resolved, taskId, nodeId, sessionId) {
67014
67141
  if (!resolved.providerType || !resolved.quotaGated?.length) return;
67015
67142
  const detail = resolved.quotaGated.map((item) => quotaClaimBlockDescription(item.providerType, item.block)).join("; ");
@@ -67050,6 +67177,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67050
67177
  }
67051
67178
  var lastQuotaClaimBlockLog;
67052
67179
  var lastAllQuotaClaimBlockedLog;
67180
+ var lastClaimRefusalLog;
67053
67181
  var lastAutoLaunchLedgerKey;
67054
67182
  var AUTO_LAUNCH_LEDGER_DEDUP_MAX;
67055
67183
  var init_mesh_queue_observability = __esm2({
@@ -67060,6 +67188,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67060
67188
  init_mesh_quota_routing();
67061
67189
  lastQuotaClaimBlockLog = /* @__PURE__ */ new Map();
67062
67190
  lastAllQuotaClaimBlockedLog = /* @__PURE__ */ new Map();
67191
+ lastClaimRefusalLog = /* @__PURE__ */ new Map();
67063
67192
  lastAutoLaunchLedgerKey = /* @__PURE__ */ new Map();
67064
67193
  AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2e3;
67065
67194
  }
@@ -67874,7 +68003,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67874
68003
  }
67875
68004
  }
67876
68005
  }
67877
- function autoLaunchWriteWouldClobberWinner(meshId, taskId, args, awaitClaimWindowMs2) {
68006
+ function autoLaunchWriteWouldClobberWinner(meshId, taskId, args, awaitClaimWindowMs3) {
67878
68007
  if (args.status === "completed" && readNonEmptyString(args.sessionId)) return false;
67879
68008
  let existing;
67880
68009
  try {
@@ -67885,7 +68014,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67885
68014
  const heldSessionId = existing ? readNonEmptyString(existing.sessionId) : "";
67886
68015
  if (!existing || existing.status !== "completed" || !heldSessionId) return false;
67887
68016
  const heldAtMs = Date.parse(existing.updatedAt);
67888
- if (!Number.isFinite(heldAtMs) || Date.now() - heldAtMs >= awaitClaimWindowMs2) return false;
68017
+ if (!Number.isFinite(heldAtMs) || Date.now() - heldAtMs >= awaitClaimWindowMs3) return false;
67889
68018
  if (sessionIdsEquivalent(readNonEmptyString(args.sessionId), heldSessionId)) return false;
67890
68019
  LOG2.info("MeshQueue", `AUTOLAUNCH-WINNER-CLOBBER: suppressed a '${args.status}' autoLaunch write for task ${taskId} (mesh ${meshId}) that would have overwritten the in-window launch record for session ${heldSessionId}; the field keeps pointing at the actually-launched session.`);
67891
68020
  return true;
@@ -67916,6 +68045,43 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
67916
68045
  }
67917
68046
  return out;
67918
68047
  }
68048
+ function driveExpiredAwaitClaim(components, meshId, task, ctx, assignQueueTask) {
68049
+ const { sessionId, nodeId, providerType } = ctx;
68050
+ const backoffKey = `${meshId}::${task.id}`;
68051
+ const nowMs = Date.now();
68052
+ const state = autoLaunchAwaitClaimBackoff.get(backoffKey) || { cycles: 0, nextAttemptAtMs: 0 };
68053
+ if (state.nextAttemptAtMs && nowMs < state.nextAttemptAtMs) return "backoff";
68054
+ const atCap = state.cycles >= AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES;
68055
+ const live = remoteSessionAppearsLive(meshId, sessionId);
68056
+ if ((live || atCap) && nodeId && providerType) {
68057
+ try {
68058
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(meshId, nodeId, sessionId, providerType, nowMs + AUTO_LAUNCH_REMOTE_IDLE_TTL_MS);
68059
+ } catch {
68060
+ }
68061
+ const assigned = assignQueueTask(components, meshId, nodeId, sessionId, providerType);
68062
+ if (assigned) {
68063
+ autoLaunchAwaitClaimBackoff.delete(backoffKey);
68064
+ const isFallback = atCap && !live;
68065
+ recordAutoLaunchEvent(meshId, {
68066
+ phase: "completed",
68067
+ taskId: task.id,
68068
+ reason: isFallback ? "await_claim_direct_dispatch_fallback" : "await_claim_redriven",
68069
+ nodeId,
68070
+ sessionId
68071
+ });
68072
+ LOG2.info("MeshQueue", `Auto-launch await-claim ${isFallback ? "direct-dispatch fallback" : "re-drive"} claimed task ${task.id} into existing session ${sessionId} on node ${nodeId} (mesh ${meshId})`);
68073
+ return isFallback ? "fallback" : "claimed";
68074
+ }
68075
+ if (atCap) {
68076
+ autoLaunchAwaitClaimBackoff.delete(backoffKey);
68077
+ return "respawn";
68078
+ }
68079
+ }
68080
+ const cycles = Math.min(state.cycles + 1, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES);
68081
+ autoLaunchAwaitClaimBackoff.set(backoffKey, { cycles, nextAttemptAtMs: nowMs + awaitClaimWindowMs(cycles) });
68082
+ recordAutoLaunchEvent(meshId, { phase: "skipped", taskId: task.id, reason: "awaiting_launched_session_claim_backoff", nodeId, sessionId });
68083
+ return "backoff";
68084
+ }
67919
68085
  var AUTO_LAUNCH_AWAIT_CLAIM_MS;
67920
68086
  var AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES;
67921
68087
  var AUTO_LAUNCH_REMOTE_IDLE_TTL_MS;
@@ -68372,6 +68538,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
68372
68538
  }
68373
68539
  if (isWorkspaceAutoFastForwardInFlight(readNonEmptyString(node?.workspace))) {
68374
68540
  LOG2.info("MeshQueue", `Deferring queue claim for node ${nodeId} (${sessionId}): an auto fast-forward is mutating its workspace \u2014 task left pending, claim re-fires next tick`);
68541
+ noteClaimDeferredForNode(meshId, nodeId);
68375
68542
  return false;
68376
68543
  }
68377
68544
  const quotaClaimBlock = evaluateProviderQuotaGate(node, providerType, mesh?.policy?.quotaRouting ?? null, Date.now(), quotaFactsContextForLiveRouting(mesh, isLocalAutoLaunchNode, components.providerLoader));
@@ -68433,6 +68600,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
68433
68600
  const nodeIsWorktree = node?.isLocalWorktree === true;
68434
68601
  const assignedTranscriptProfile = resolveClaimingSessionTranscriptProfile(components, sessionId);
68435
68602
  const daemonNodeIds = resolveDaemonSiblingNodeIds(nodeId, mesh?.nodes);
68603
+ const claimRefusal = {};
68436
68604
  const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
68437
68605
  providerType,
68438
68606
  ...providerMaxParallel !== void 0 ? { providerMaxParallel } : {},
@@ -68441,11 +68609,24 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
68441
68609
  daemonNodeIds,
68442
68610
  nodeIsWorktree,
68443
68611
  ...allowedTaskDifficulties ? { allowedTaskDifficulties } : {},
68444
- ...assignedTranscriptProfile ? { assignedTranscriptProfile } : {}
68612
+ ...assignedTranscriptProfile ? { assignedTranscriptProfile } : {},
68613
+ outRefusal: claimRefusal
68445
68614
  });
68446
68615
  if (!task) {
68616
+ const refusalReason = claimRefusal.reason || "no_pending_candidates";
68617
+ recordClaimRefusal(meshId, {
68618
+ nodeId,
68619
+ sessionId,
68620
+ ...providerType ? { providerType } : {},
68621
+ reason: refusalReason,
68622
+ ...claimRefusal.detail ? { detail: claimRefusal.detail } : {}
68623
+ });
68624
+ recordLastQuotaRankingOutcome(nodeId, "refused", refusalReason);
68447
68625
  return false;
68448
68626
  }
68627
+ clearClaimRefusalState(meshId, nodeId, sessionId);
68628
+ clearClaimDeferralForNode(meshId, nodeId);
68629
+ recordLastQuotaRankingOutcome(nodeId, "claimed");
68449
68630
  if (quotaClaimTrace?.blocked.length) {
68450
68631
  logQuotaClaimFallbackSuccess(quotaClaimTrace.blocked, task.id, { nodeId, sessionId, providerType });
68451
68632
  quotaClaimTrace.blocked = [];
@@ -68931,43 +69112,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
68931
69112
  function readMeshNodeId(node) {
68932
69113
  return normalizeMeshNodeId(node) ?? "";
68933
69114
  }
68934
- function driveExpiredAwaitClaim(components, meshId, task, ctx) {
68935
- const { sessionId, nodeId, providerType } = ctx;
68936
- const backoffKey = `${meshId}::${task.id}`;
68937
- const nowMs = Date.now();
68938
- const state = autoLaunchAwaitClaimBackoff.get(backoffKey) || { cycles: 0, nextAttemptAtMs: 0 };
68939
- if (state.nextAttemptAtMs && nowMs < state.nextAttemptAtMs) return "backoff";
68940
- const atCap = state.cycles >= AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES2;
68941
- const live = remoteSessionAppearsLive(meshId, sessionId);
68942
- if ((live || atCap) && nodeId && providerType) {
68943
- try {
68944
- MeshRuntimeStore.getInstance().setRemoteIdleSession(meshId, nodeId, sessionId, providerType, nowMs + AUTO_LAUNCH_REMOTE_IDLE_TTL_MS);
68945
- } catch {
68946
- }
68947
- const assigned = tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
68948
- if (assigned) {
68949
- autoLaunchAwaitClaimBackoff.delete(backoffKey);
68950
- const isFallback = atCap && !live;
68951
- recordAutoLaunchEvent(meshId, {
68952
- phase: "completed",
68953
- taskId: task.id,
68954
- reason: isFallback ? "await_claim_direct_dispatch_fallback" : "await_claim_redriven",
68955
- nodeId,
68956
- sessionId
68957
- });
68958
- LOG2.info("MeshQueue", `Auto-launch await-claim ${isFallback ? "direct-dispatch fallback" : "re-drive"} claimed task ${task.id} into existing session ${sessionId} on node ${nodeId} (mesh ${meshId})`);
68959
- return isFallback ? "fallback" : "claimed";
68960
- }
68961
- if (atCap) {
68962
- autoLaunchAwaitClaimBackoff.delete(backoffKey);
68963
- return "respawn";
68964
- }
68965
- }
68966
- const cycles = Math.min(state.cycles + 1, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES2);
68967
- autoLaunchAwaitClaimBackoff.set(backoffKey, { cycles, nextAttemptAtMs: nowMs + awaitClaimWindowMs(cycles) });
68968
- recordAutoLaunchEvent(meshId, { phase: "skipped", taskId: task.id, reason: "awaiting_launched_session_claim_backoff", nodeId, sessionId });
68969
- return "backoff";
68970
- }
68971
69115
  async function maybeAutoLaunchOneQueueSession(components, meshId, mesh) {
68972
69116
  const queue = getQueue(meshId);
68973
69117
  const statusById = new Map(queue.map((task) => [task.id, task.status]));
@@ -69048,11 +69192,22 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
69048
69192
  const alNodeId = readNonEmptyString(task.autoLaunch.nodeId);
69049
69193
  const alProvider = readNonEmptyString(task.autoLaunch.providerType);
69050
69194
  if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
69195
+ if (shouldRedriveDeferredClaim(meshId, alNodeId, alSessionId, () => isWorkspaceAutoFastForwardInFlight(readNonEmptyString(
69196
+ (Array.isArray(mesh?.nodes) ? mesh.nodes.find((n) => meshNodeIdMatches(n, alNodeId)) : void 0)?.workspace
69197
+ )))) {
69198
+ if (tryAssignQueueTask(components, meshId, alNodeId, alSessionId, alProvider)) {
69199
+ clearClaimDeferralForNode(meshId, alNodeId);
69200
+ recordAutoLaunchEvent(meshId, { phase: "completed", taskId: task.id, reason: "fast_forward_deferred_claim_redriven", nodeId: alNodeId, sessionId: alSessionId });
69201
+ LOG2.info("MeshQueue", `Auto-launch re-drove the auto-fast-forward-deferred claim for task ${task.id} into session ${alSessionId} on node ${alNodeId} (mesh ${meshId})`);
69202
+ return true;
69203
+ }
69204
+ noteClaimDeferredForNode(meshId, alNodeId);
69205
+ }
69051
69206
  recordAutoLaunchEvent(meshId, { phase: "skipped", taskId: task.id, reason: "awaiting_launched_session_claim", nodeId: alNodeId, sessionId: alSessionId });
69052
69207
  continue;
69053
69208
  }
69054
69209
  if (Number.isFinite(launchedAtMs) && alSessionId && alNodeId) {
69055
- const outcome = driveExpiredAwaitClaim(components, meshId, task, { sessionId: alSessionId, nodeId: alNodeId, providerType: alProvider });
69210
+ const outcome = driveExpiredAwaitClaim(components, meshId, task, { sessionId: alSessionId, nodeId: alNodeId, providerType: alProvider }, tryAssignQueueTask);
69056
69211
  if (outcome === "claimed" || outcome === "fallback") return true;
69057
69212
  if (outcome === "backoff") continue;
69058
69213
  }
@@ -69502,7 +69657,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
69502
69657
  var autoLaunchTaskInProgress;
69503
69658
  var autoLaunchCooldownUntil;
69504
69659
  var AUTO_LAUNCH_COOLDOWN_MS;
69505
- var AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES2;
69506
69660
  var init_mesh_queue_assignment = __esm2({
69507
69661
  "src/mesh/mesh-queue-assignment.ts"() {
69508
69662
  "use strict";
@@ -69516,6 +69670,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
69516
69670
  init_transcript_evidence();
69517
69671
  init_mesh_delivery_policy();
69518
69672
  init_mesh_runtime_store();
69673
+ init_mesh_claim_refusal();
69519
69674
  init_mesh_event_trace();
69520
69675
  init_mesh_warmup_deadline();
69521
69676
  init_repo_mesh_types();
@@ -69545,6 +69700,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
69545
69700
  init_mesh_auto_fast_forward();
69546
69701
  init_mesh_skip_notify();
69547
69702
  init_mesh_scheduling_fitness();
69703
+ init_mesh_claim_refusal();
69548
69704
  init_mesh_autolaunch_integrity();
69549
69705
  BOOTSTRAP_TERMINAL_STATUSES = /* @__PURE__ */ new Set(["complete", "failed"]);
69550
69706
  DISPATCH_CONFIRM_TIMEOUT_MS = 12e4;
@@ -69556,7 +69712,6 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
69556
69712
  autoLaunchTaskInProgress = /* @__PURE__ */ new Set();
69557
69713
  autoLaunchCooldownUntil = /* @__PURE__ */ new Map();
69558
69714
  AUTO_LAUNCH_COOLDOWN_MS = 5e3;
69559
- AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES2 = 2;
69560
69715
  }
69561
69716
  });
69562
69717
  function readSettings(state) {
@@ -73956,6 +74111,9 @@ ${cleanBody}`;
73956
74111
  function resolveAckedTranscriptFastTrackGraceMs() {
73957
74112
  return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_TRANSCRIPT_FASTTRACK_GRACE_MS", 4e4, 0, 5 * 6e4);
73958
74113
  }
74114
+ function resolveAckedHoldHardCeilingMs() {
74115
+ return resolveTunedReconcileMs("MESH_INFLIGHT_ACKED_HOLD_HARD_CEILING_MS", 90 * 6e4, 0, 24 * 60 * 6e4);
74116
+ }
73959
74117
  function inFlightSynthKey(meshId, taskId) {
73960
74118
  return `${meshId}::${taskId}`;
73961
74119
  }
@@ -73985,20 +74143,32 @@ ${cleanBody}`;
73985
74143
  const state = {
73986
74144
  liveConfirmedSinceAck: row.holdReason === "live",
73987
74145
  consecutiveReadFailures: row.readFailureCount ?? 0,
73988
- ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {}
74146
+ ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {},
74147
+ ...row.heldAt !== null && row.heldAt !== void 0 ? { heldSinceMs: row.heldAt } : {}
73989
74148
  };
73990
74149
  inFlightAckedHoldState.set(synthKey, state);
73991
74150
  return state;
73992
74151
  }
73993
74152
  function setHoldState(synthKey, meshId, state) {
73994
- inFlightAckedHoldState.set(synthKey, state);
73995
74153
  const store = holdStore();
74154
+ let priorHeldSinceMs = state.heldSinceMs ?? inFlightAckedHoldState.get(synthKey)?.heldSinceMs;
74155
+ if (priorHeldSinceMs === void 0 && store) {
74156
+ try {
74157
+ priorHeldSinceMs = store.getInflightHold(taskIdFromSynthKey(meshId, synthKey))?.heldAt ?? void 0;
74158
+ } catch {
74159
+ }
74160
+ }
74161
+ const heldSinceMs = priorHeldSinceMs ?? Date.now();
74162
+ inFlightAckedHoldState.set(synthKey, { ...state, heldSinceMs });
73996
74163
  if (!store) return;
73997
74164
  try {
73998
74165
  store.upsertInflightHold({
73999
74166
  taskId: taskIdFromSynthKey(meshId, synthKey),
74000
74167
  meshId,
74001
74168
  holdReason: state.liveConfirmedSinceAck ? "live" : "unconfirmed",
74169
+ // Only meaningful when the row is NEW — upsertInflightHold deliberately
74170
+ // preserves held_at on conflict, so an existing row keeps its original anchor.
74171
+ heldAt: heldSinceMs,
74002
74172
  firstIdleSinceAck: state.transcriptIdleSinceMs ?? null,
74003
74173
  readFailureCount: state.consecutiveReadFailures
74004
74174
  });
@@ -74031,7 +74201,8 @@ ${cleanBody}`;
74031
74201
  inFlightAckedHoldState.set(synthKey, {
74032
74202
  liveConfirmedSinceAck: row.holdReason === "live",
74033
74203
  consecutiveReadFailures: row.readFailureCount ?? 0,
74034
- ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {}
74204
+ ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {},
74205
+ ...row.heldAt !== null && row.heldAt !== void 0 ? { heldSinceMs: row.heldAt } : {}
74035
74206
  });
74036
74207
  }
74037
74208
  if (rows.length > 0) {
@@ -75516,6 +75687,29 @@ ${cleanBody}`;
75516
75687
  }
75517
75688
  return fp;
75518
75689
  }
75690
+ function terminalizeAckedHold(args) {
75691
+ const { meshId, taskId, sessionId, nodeId, providerType, synthKey, reason, detail } = args;
75692
+ updateDirectDispatchStatus(meshId, sessionId, "stale", taskId);
75693
+ deleteHoldState(synthKey, meshId);
75694
+ try {
75695
+ appendLedgerEntry(meshId, {
75696
+ kind: "acked_hold_terminalized",
75697
+ nodeId,
75698
+ sessionId,
75699
+ ...providerType ? { providerType } : {},
75700
+ taskId,
75701
+ payload: { taskId, reason, ...detail }
75702
+ });
75703
+ } catch {
75704
+ }
75705
+ traceMeshEventStage("acked_hold_terminalized", {
75706
+ taskId,
75707
+ sessionId,
75708
+ nodeId,
75709
+ meshId,
75710
+ event: "agent:generating_completed"
75711
+ }, `${reason} \u2014 dispatch row marked stale, synth hold deleted`);
75712
+ }
75519
75713
  async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId) {
75520
75714
  const dispatches = getActiveDirectDispatches(mesh.id);
75521
75715
  rehydrateAckedHoldsForMesh(mesh.id);
@@ -75539,7 +75733,9 @@ ${cleanBody}`;
75539
75733
  if (!sessionId || !nodeId || !taskId) continue;
75540
75734
  const node = nodeById.get(nodeId);
75541
75735
  const nodeDaemonId = readNonEmptyString(node?.daemonId);
75542
- const isLocalNode = !nodeDaemonId || daemonIdListIncludes(selfIds, nodeDaemonId) || daemonIdsEquivalent(nodeDaemonId, localDaemonId) || !!components.instanceManager.getInstance(sessionId);
75736
+ const sessionLiveHere = !!components.instanceManager.getInstance(sessionId);
75737
+ const nodeIsGone = !node && !sessionLiveHere;
75738
+ const isLocalNode = !nodeIsGone && (!nodeDaemonId || daemonIdListIncludes(selfIds, nodeDaemonId) || daemonIdsEquivalent(nodeDaemonId, localDaemonId) || sessionLiveHere);
75543
75739
  const providerType = readNonEmptyString(dispatch.providerType);
75544
75740
  const readArgs = {
75545
75741
  sessionId,
@@ -75550,10 +75746,41 @@ ${cleanBody}`;
75550
75746
  };
75551
75747
  const synthKey = inFlightSynthKey(mesh.id, taskId);
75552
75748
  const isAcked = dispatch.status === "acked";
75749
+ if (isAcked) {
75750
+ const ceilingMs = resolveAckedHoldHardCeilingMs();
75751
+ const heldSinceMs = getHoldState(synthKey, mesh.id)?.heldSinceMs;
75752
+ if (heldSinceMs !== void 0) {
75753
+ const heldMs = Date.now() - heldSinceMs;
75754
+ if (Number.isFinite(heldMs) && heldMs >= ceilingMs) {
75755
+ LOG2.warn("MeshReconcile", `Acked-hold HARD CEILING exceeded: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) has held its synth for ${Math.round(heldMs / 6e4)}min (> ${Math.round(ceilingMs / 6e4)}min ceiling) without ever reaching a release condition \u2014 marking the dispatch row STALE and deleting the synth hold (no completion is asserted). A hold this old is presumed wedged, not slow.`);
75756
+ terminalizeAckedHold({
75757
+ meshId: mesh.id,
75758
+ taskId,
75759
+ sessionId,
75760
+ nodeId,
75761
+ ...providerType ? { providerType } : {},
75762
+ synthKey,
75763
+ reason: "acked_hold_time_ceiling",
75764
+ detail: { heldMs, ceilingMs }
75765
+ });
75766
+ continue;
75767
+ }
75768
+ }
75769
+ }
75553
75770
  let backstopKind;
75554
75771
  let payload = null;
75555
75772
  let readFailed = false;
75556
75773
  try {
75774
+ if (nodeIsGone) {
75775
+ traceMeshEventDrop("reconcile_synth_node_gone_no_transport", {
75776
+ taskId,
75777
+ sessionId,
75778
+ nodeId,
75779
+ meshId: mesh.id,
75780
+ event: "agent:generating_completed"
75781
+ }, `nodeId not present in mesh.nodes and no live local session \u2014 orphan-prune owns this row`);
75782
+ continue;
75783
+ }
75557
75784
  if (isLocalNode) {
75558
75785
  const result = await components.commandHandler.handle("read_chat", readArgs);
75559
75786
  if (result && result.success === false) {
@@ -75582,7 +75809,17 @@ ${cleanBody}`;
75582
75809
  const liveConfirmedSinceAck = prior?.liveConfirmedSinceAck ?? false;
75583
75810
  setHoldState(synthKey, mesh.id, { liveConfirmedSinceAck, consecutiveReadFailures: failures });
75584
75811
  if (liveConfirmedSinceAck && failures >= ACKED_DEATH_CONSECUTIVE_READ_FAILURES) {
75585
- LOG2.warn("MeshReconcile", `Acked-hold death signal: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read_chat failed ${failures}x consecutively after a live-confirmed ack \u2014 worker session presumed gone mid-turn; releasing the indefinite synth hold to the stranded-reclaim / orphan-prune nets`);
75812
+ LOG2.warn("MeshReconcile", `Acked-hold death signal: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read_chat failed ${failures}x consecutively after a live-confirmed ack \u2014 worker session presumed gone mid-turn; marking the dispatch row STALE and deleting the synth hold (no completion is asserted \u2014 the transcript never showed one). Orphan-prune reaps the record on its own schedule.`);
75813
+ terminalizeAckedHold({
75814
+ meshId: mesh.id,
75815
+ taskId,
75816
+ sessionId,
75817
+ nodeId,
75818
+ ...providerType ? { providerType } : {},
75819
+ synthKey,
75820
+ reason: "acked_read_failure_death",
75821
+ detail: { consecutiveReadFailures: failures, threshold: ACKED_DEATH_CONSECUTIVE_READ_FAILURES }
75822
+ });
75586
75823
  }
75587
75824
  }
75588
75825
  continue;
@@ -106928,8 +107165,15 @@ ${buttons.join("\n")}`;
106928
107165
  // turn's half-written tail is hidden from the user. The completion gate needs the
106929
107166
  // exact opposite — it exists to judge the turn that JUST finished, so excluding the
106930
107167
  // in-progress turn would hide the very evidence it is looking for and would make
106931
- // missing_final_assistant strictly more common. Codex's manifest sets
106932
- // excludeInProgressTurn:true for its own read path; that must not leak here.
107168
+ // missing_final_assistant strictly more common.
107169
+ //
107170
+ // Codex's provider.v1.json carries `nativeHistory.excludeInProgressTurn: true`,
107171
+ // but that declaration is NOT what drives the read path and never reaches this
107172
+ // call: the manifest field has no reader anywhere in daemon-core. The live
107173
+ // behaviour comes from the per-call flag read_chat computes, which the loader's
107174
+ // readNativeHistory wrapper applies (provider-loader.ts). The distinction matters
107175
+ // — omitting the flag here is what keeps the in-progress turn visible to the gate,
107176
+ // and no manifest declaration can override that.
106933
107177
  });
106934
107178
  host.lastNativeTurnTerminalMarkers = Array.isArray(restoredHistory.turnTerminalMarkers) ? restoredHistory.turnTerminalMarkers : null;
106935
107179
  if (restoredHistory.source !== "provider-native") {
@@ -113982,6 +114226,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
113982
114226
  }
113983
114227
  init_external_sources();
113984
114228
  init_config();
114229
+ init_chat_message_normalization();
113985
114230
  var fs41 = __toESM2(require("fs"));
113986
114231
  var os28 = __toESM2(require("os"));
113987
114232
  var path46 = __toESM2(require("path"));
@@ -118204,7 +118449,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
118204
118449
  }
118205
118450
  if (reader) {
118206
118451
  resolved.scripts = { ...resolved.scripts || {} };
118207
- resolved.scripts.readNativeHistory = reader;
118452
+ resolved.scripts.readNativeHistory = (input) => {
118453
+ const result = reader(input);
118454
+ const wantsTrim = input?.excludeInProgressTurn === true || input?.args?.excludeInProgressTurn === true;
118455
+ if (!wantsTrim || !result || !Array.isArray(result.messages)) return result;
118456
+ const trimmed = trimInProgressTurnToolTail(result.messages);
118457
+ return trimmed === result.messages ? result : { ...result, messages: trimmed };
118458
+ };
118208
118459
  const scriptsMarker = { readSession: "readNativeHistory" };
118209
118460
  if (lister) {
118210
118461
  resolved.scripts.listNativeHistory = lister;