@adhdev/daemon-standalone 0.9.82-rc.327 → 0.9.82-rc.328

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
@@ -30033,10 +30033,10 @@ var require_dist3 = __commonJS({
30033
30033
  }
30034
30034
  function getDaemonBuildInfo() {
30035
30035
  if (cached2) return cached2;
30036
- const commit = readInjected(true ? "993e3922de8abe554822450e2b4c26c2c9f5f64a" : void 0) ?? "unknown";
30037
- const commitShort = readInjected(true ? "993e3922" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30038
- const version2 = readInjected(true ? "0.9.82-rc.327" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30039
- const builtAt = readInjected(true ? "2026-06-19T12:31:51.466Z" : void 0);
30036
+ const commit = readInjected(true ? "38ede5a48ea8a2e21b5ea014880b9af37c6e3537" : void 0) ?? "unknown";
30037
+ const commitShort = readInjected(true ? "38ede5a4" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
30038
+ const version2 = readInjected(true ? "0.9.82-rc.328" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
30039
+ const builtAt = readInjected(true ? "2026-06-19T13:57:56.784Z" : void 0);
30040
30040
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
30041
30041
  return cached2;
30042
30042
  }
@@ -36748,197 +36748,601 @@ ${rendered}`, "utf-8");
36748
36748
  "use strict";
36749
36749
  }
36750
36750
  });
36751
- function readNonEmptyString2(value) {
36752
- return typeof value === "string" && value.trim() ? value.trim() : "";
36751
+ function readString6(value) {
36752
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
36753
36753
  }
36754
- function readRecord4(value) {
36755
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
36754
+ function summarizeMessage(message) {
36755
+ const oneLine2 = message.replace(/\s+/g, " ").trim();
36756
+ const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
36757
+ return { title: title || "(untitled task)", summary: oneLine2 };
36756
36758
  }
36757
- function buildMeshWorkerRelayStamp(currentSettings, meshContext) {
36758
- if (!meshContext) return void 0;
36759
- const settings = currentSettings && typeof currentSettings === "object" ? currentSettings : {};
36760
- const stamp = {};
36761
- const meshId = readNonEmptyString2(meshContext.meshId);
36762
- if (meshId && !readNonEmptyString2(settings.meshNodeFor)) stamp.meshNodeFor = meshId;
36763
- const nodeId = readNonEmptyString2(meshContext.nodeId);
36764
- if (nodeId && !readNonEmptyString2(settings.meshNodeId)) stamp.meshNodeId = nodeId;
36765
- const coordinatorDaemonId = readNonEmptyString2(meshContext.coordinatorDaemonId);
36766
- if (coordinatorDaemonId && !readNonEmptyString2(settings.meshCoordinatorDaemonId)) {
36767
- stamp.meshCoordinatorDaemonId = coordinatorDaemonId;
36759
+ function elapsedSince(value, now) {
36760
+ const started = value ? new Date(value).getTime() : Number.NaN;
36761
+ return Number.isFinite(started) ? Math.max(0, now - started) : 0;
36762
+ }
36763
+ function sessionStatusFromNodes(nodes, nodeId, sessionId) {
36764
+ if (!Array.isArray(nodes)) return {};
36765
+ if (!nodeId) return { staleReason: "direct task has no node id" };
36766
+ const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
36767
+ if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
36768
+ if (!sessionId) return {};
36769
+ const candidates = [];
36770
+ for (const value of [
36771
+ node.sessions,
36772
+ node.activeSessions,
36773
+ node.active_sessions,
36774
+ node.activeSessionDetails,
36775
+ node.active_session_details,
36776
+ node.sessionDetails,
36777
+ node.session_details,
36778
+ node.lastProbe?.sessions,
36779
+ node.last_probe?.sessions,
36780
+ node.lastProbe?.status?.sessions,
36781
+ node.last_probe?.status?.sessions
36782
+ ]) {
36783
+ if (Array.isArray(value)) candidates.push(...value);
36768
36784
  }
36769
- if ((meshId || nodeId || coordinatorDaemonId) && settings.launchedByCoordinator !== true) {
36770
- stamp.launchedByCoordinator = true;
36785
+ for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
36786
+ if (value && typeof value === "object") candidates.push(value);
36771
36787
  }
36772
- return Object.keys(stamp).length > 0 ? stamp : void 0;
36788
+ const session = candidates.find((item) => {
36789
+ if (typeof item === "string") return item === sessionId;
36790
+ const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
36791
+ return id === sessionId;
36792
+ });
36793
+ if (!session) return { staleReason: "direct task session is not present in live session records" };
36794
+ if (typeof session === "string") return {};
36795
+ const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
36796
+ if (raw.includes("approval")) return { status: "awaiting_approval" };
36797
+ if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
36798
+ if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
36799
+ if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
36800
+ return {};
36773
36801
  }
36774
- function resolveEventSessionId(event, fallback) {
36775
- return readNonEmptyString2(event.targetSessionId) || readNonEmptyString2(event.sessionId) || readNonEmptyString2(event.instanceId) || readNonEmptyString2(fallback);
36802
+ function isDirectDispatch(entry) {
36803
+ if (entry.kind !== "task_dispatched") return false;
36804
+ const payload = entry.payload || {};
36805
+ if (payload.source === "direct") return true;
36806
+ const via = readString6(payload.via);
36807
+ return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
36776
36808
  }
36777
- function readRefineJobId(event) {
36778
- const metadata = readRecord4(event.metadataEvent) || event;
36779
- const result = readRecord4(metadata.result);
36780
- const refineJob = readRecord4(result?.refineJob);
36781
- return readNonEmptyString2(metadata.jobId) || readNonEmptyString2(refineJob?.jobId);
36809
+ function directDispatchTaskId(entry) {
36810
+ return readString6(entry.payload?.taskId) || entry.id;
36782
36811
  }
36783
- function readWorkerResultMetadata(event) {
36784
- return readRecord4(event.workerResult) || readRecord4(event.meshWorkerResult) || readRecord4(event.structuredResult);
36812
+ function terminalMatchesDispatch(terminal, dispatch, taskId) {
36813
+ const terminalTaskId = readString6(terminal.payload?.taskId);
36814
+ if (terminalTaskId && terminalTaskId === taskId) return true;
36815
+ if (terminalTaskId && terminalTaskId !== taskId) return false;
36816
+ if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
36817
+ return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
36785
36818
  }
36786
- function formatCompletionMetadata(event) {
36787
- const completionDiagnostic = event.completionDiagnostic && typeof event.completionDiagnostic === "object" ? event.completionDiagnostic : null;
36788
- const diagnosticReason = completionDiagnostic ? readNonEmptyString2(completionDiagnostic.blockReason) || "present" : "";
36789
- const finalAssistantPresent = typeof completionDiagnostic?.finalAssistantPresent === "boolean" ? String(completionDiagnostic.finalAssistantPresent) : "";
36790
- const evidenceLevel = readNonEmptyString2(event.evidenceLevel);
36791
- const parts = [
36792
- readNonEmptyString2(event.targetSessionId) ? `session_id=${readNonEmptyString2(event.targetSessionId)}` : "",
36793
- readNonEmptyString2(event.providerType) ? `provider=${readNonEmptyString2(event.providerType)}` : "",
36794
- readNonEmptyString2(event.providerSessionId) ? `provider_session_id=${readNonEmptyString2(event.providerSessionId)}` : "",
36795
- diagnosticReason ? `completion_diagnostic=${diagnosticReason}` : "",
36796
- finalAssistantPresent ? `final_assistant=${finalAssistantPresent}` : "",
36797
- evidenceLevel && evidenceLevel !== "sufficient" ? `evidence_level=${evidenceLevel}` : ""
36798
- ].filter(Boolean);
36799
- return parts.length > 0 ? ` (${parts.join("; ")})` : "";
36819
+ function statusFromTerminal(entry) {
36820
+ if (entry.kind === "task_approval_needed") return "awaiting_approval";
36821
+ if (entry.kind === "task_completed") return "idle";
36822
+ return "failed";
36800
36823
  }
36801
- function buildMeshSystemMessage(args) {
36802
- const metadata = formatCompletionMetadata(args.metadataEvent);
36803
- if (args.event === "agent:generating_completed") {
36804
- if (args.metadataEvent.source === "long_generating_reconciliation") {
36805
- return `[System] ${args.nodeLabel} already has completion evidence${metadata}. The long-generating monitor reconciled the terminal handoff and marked the session complete; wait for the queued completion event/status refresh before doing any manual transcript check.`;
36806
- }
36807
- const reviewNote = args.metadataEvent.reviewRecommended === true ? " Completion evidence is insufficient \u2014 verify via git status or provider_session_id before assuming the task is done. Use mesh_read_chat once if needed, but do not poll repeatedly." : " Use mesh_read_chat once to review its final progress, but do not poll repeatedly.";
36808
- return `[System] ${args.nodeLabel} has completed its task and is now idle${metadata}. This completion came from the agent status event path;${reviewNote}`;
36824
+ function buildMeshActiveWorkSummary(activeWork) {
36825
+ const statusCounts = {
36826
+ pending: 0,
36827
+ assigned: 0,
36828
+ generating: 0,
36829
+ idle: 0,
36830
+ failed: 0,
36831
+ awaiting_approval: 0
36832
+ };
36833
+ const sourceCounts = { queue: 0, direct: 0 };
36834
+ for (const item of activeWork) {
36835
+ sourceCounts[item.source] += 1;
36836
+ statusCounts[item.status] += 1;
36809
36837
  }
36810
- if (args.event === "agent:waiting_approval") {
36811
- return `[System] ${args.nodeLabel} is waiting for approval to proceed${metadata}. You may use mesh_read_chat and mesh_approve to handle it.`;
36838
+ const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
36839
+ const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
36840
+ return {
36841
+ totalActiveCount: activeWork.length,
36842
+ queueActiveCount: sourceCounts.queue,
36843
+ directActiveCount: sourceCounts.direct,
36844
+ awaitingApprovalCount: statusCounts.awaiting_approval,
36845
+ generatingCount: statusCounts.generating,
36846
+ failedCount: statusCounts.failed,
36847
+ idleCount: statusCounts.idle,
36848
+ sourceCounts,
36849
+ statusCounts,
36850
+ staleDirectCount,
36851
+ ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
36852
+ ...staleDirectCount > 0 ? { staleDirectNote: "Stale direct records are orphaned ledger entries whose node/session no longer exists. They are historical recovery evidence only \u2014 not active or unresolved work. The queue (source: queue) is authoritative for pending/assigned tasks." } : {}
36853
+ };
36854
+ }
36855
+ function buildMeshActiveWork(opts) {
36856
+ const now = opts.now ?? Date.now();
36857
+ const records = [];
36858
+ const staleDirectWork = [];
36859
+ const terminalDirectWork = [];
36860
+ for (const task of opts.queue || []) {
36861
+ if (task.status !== "pending" && task.status !== "assigned") continue;
36862
+ const { title, summary: summary2 } = summarizeMessage(task.message || "");
36863
+ records.push({
36864
+ taskId: task.id,
36865
+ source: "queue",
36866
+ status: task.status,
36867
+ nodeId: task.assignedNodeId || task.targetNodeId,
36868
+ sessionId: task.assignedSessionId || task.targetSessionId,
36869
+ taskTitle: title,
36870
+ taskSummary: summary2,
36871
+ message: task.message,
36872
+ taskMode: task.taskMode,
36873
+ createdAt: task.createdAt,
36874
+ updatedAt: task.updatedAt,
36875
+ dispatchedAt: task.dispatchTimestamp,
36876
+ elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
36877
+ });
36812
36878
  }
36813
- if (args.event === "agent:stopped") {
36814
- const rc = args.recoveryContext;
36815
- if (rc && rc.consecutiveNodeFailures > 0) {
36816
- const parts = [
36817
- `[System] ${args.nodeLabel} has stopped unexpectedly${metadata}.`,
36818
- `
36819
-
36820
- **Recovery Context:**`,
36821
- `- Consecutive failures on this node: ${rc.consecutiveNodeFailures}`,
36822
- rc.taskAttemptCount > 0 ? `- This task has been attempted ${rc.taskAttemptCount} time(s)` : "",
36823
- `- Recommendation: ${rc.advice}`
36824
- ];
36825
- if (rc.retryRecommended && rc.lastTaskMessage) {
36826
- parts.push(
36827
- `
36828
-
36829
- **Original task to retry:**`,
36830
- `> ${rc.lastTaskMessage.length > 300 ? rc.lastTaskMessage.slice(0, 300) + "..." : rc.lastTaskMessage}`,
36831
- `
36832
- To retry: call \`mesh_launch_session\` for this node, then \`mesh_send_task\` with the original task.`
36833
- );
36834
- } else if (!rc.retryRecommended) {
36835
- parts.push(
36836
- `
36837
- Do NOT retry on this node. Consider reassigning to a different node or asking the user for guidance.`
36838
- );
36879
+ if (opts.directDispatches !== void 0) {
36880
+ const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
36881
+ for (const dispatch of opts.directDispatches) {
36882
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
36883
+ const dbStatus = dispatch.status;
36884
+ const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
36885
+ const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
36886
+ const isNoTransition = !isTerminal && !live.status;
36887
+ const isIdleUnacknowledged = status === "idle" && !isTerminal;
36888
+ const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
36889
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
36890
+ const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
36891
+ const record2 = {
36892
+ taskId: dispatch.taskId,
36893
+ source: "direct",
36894
+ status,
36895
+ nodeId: dispatch.nodeId ?? void 0,
36896
+ sessionId: dispatch.sessionId ?? void 0,
36897
+ providerType: dispatch.providerType ?? void 0,
36898
+ taskTitle: title,
36899
+ taskSummary: summary2,
36900
+ message: dispatch.message,
36901
+ taskMode: dispatch.taskMode ?? void 0,
36902
+ createdAt: dispatch.dispatchedAt,
36903
+ updatedAt: dispatch.updatedAt,
36904
+ dispatchedAt: dispatch.dispatchedAt,
36905
+ elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
36906
+ terminal: isTerminal,
36907
+ terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
36908
+ terminalAt: isTerminal ? dispatch.updatedAt : void 0,
36909
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
36910
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
36911
+ };
36912
+ if (isTerminal) {
36913
+ terminalDirectWork.push(record2);
36914
+ if (opts.includeTerminalDirect !== true) continue;
36839
36915
  }
36840
- return parts.filter(Boolean).join("\n");
36916
+ if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
36917
+ staleDirectWork.push(record2);
36918
+ continue;
36919
+ }
36920
+ records.push(record2);
36921
+ }
36922
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
36923
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
36924
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
36925
+ const taskId = directDispatchTaskId(dispatch);
36926
+ if (dbTaskIds.has(taskId)) continue;
36927
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
36928
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
36929
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
36930
+ const status = terminalStatus || live.status || "assigned";
36931
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
36932
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
36933
+ const isNoTransition = !terminalStatus && !live.status;
36934
+ const isIdleUnacknowledged = status === "idle";
36935
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
36936
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
36937
+ const { title, summary: summary2 } = summarizeMessage(message);
36938
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
36939
+ const record2 = {
36940
+ taskId,
36941
+ source: "direct",
36942
+ status,
36943
+ nodeId: dispatch.nodeId,
36944
+ sessionId: dispatch.sessionId,
36945
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
36946
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
36947
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
36948
+ message,
36949
+ taskMode: readString6(dispatch.payload?.taskMode),
36950
+ createdAt: dispatch.timestamp,
36951
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
36952
+ dispatchedAt: dispatch.timestamp,
36953
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
36954
+ terminal: terminalRow,
36955
+ terminalKind: terminal?.kind,
36956
+ terminalAt: terminal?.timestamp,
36957
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
36958
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
36959
+ };
36960
+ if (terminalRow) {
36961
+ terminalDirectWork.push(record2);
36962
+ if (opts.includeTerminalDirect !== true) continue;
36963
+ }
36964
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
36965
+ staleDirectWork.push(record2);
36966
+ continue;
36967
+ }
36968
+ records.push(record2);
36969
+ }
36970
+ } else {
36971
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
36972
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
36973
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
36974
+ const taskId = directDispatchTaskId(dispatch);
36975
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
36976
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
36977
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
36978
+ const status = terminalStatus || live.status || "assigned";
36979
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
36980
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
36981
+ const isNoTransition = !terminalStatus && !live.status;
36982
+ const isIdleUnacknowledged = status === "idle";
36983
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
36984
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
36985
+ const { title, summary: summary2 } = summarizeMessage(message);
36986
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
36987
+ const record2 = {
36988
+ taskId,
36989
+ source: "direct",
36990
+ status,
36991
+ nodeId: dispatch.nodeId,
36992
+ sessionId: dispatch.sessionId,
36993
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
36994
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
36995
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
36996
+ message,
36997
+ taskMode: readString6(dispatch.payload?.taskMode),
36998
+ createdAt: dispatch.timestamp,
36999
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
37000
+ dispatchedAt: dispatch.timestamp,
37001
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
37002
+ terminal: terminalRow,
37003
+ terminalKind: terminal?.kind,
37004
+ terminalAt: terminal?.timestamp,
37005
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
37006
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
37007
+ };
37008
+ if (terminalRow) {
37009
+ terminalDirectWork.push(record2);
37010
+ if (opts.includeTerminalDirect !== true) continue;
37011
+ }
37012
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
37013
+ staleDirectWork.push(record2);
37014
+ continue;
37015
+ }
37016
+ records.push(record2);
36841
37017
  }
36842
- return `[System] ${args.nodeLabel} has stopped${metadata}. Use mesh_read_chat once if you need to inspect its last output.`;
36843
- }
36844
- if (args.event === "monitor:long_generating") {
36845
- return `[System] ${args.nodeLabel} is still reported as generating after a long interval${metadata}. Wait for pendingCoordinatorEvents or a completion/status event; if the user explicitly asks for status, make one bounded status check and then wait again.`;
36846
- }
36847
- if (args.event === "worktree_bootstrap_complete") {
36848
- const worktreePath = readNonEmptyString2(args.metadataEvent.worktreePath);
36849
- const durationMs = typeof args.metadataEvent.durationMs === "number" ? args.metadataEvent.durationMs : void 0;
36850
- return `[System] ${args.nodeLabel} worktree bootstrap completed${worktreePath ? ` at ${worktreePath}` : ""}${durationMs !== void 0 ? ` in ${Math.round(durationMs / 1e3)}s` : ""}. The worktree is ready \u2014 use \`mesh_launch_session\` to start an agent.`;
36851
- }
36852
- if (args.event === "worktree_bootstrap_failed") {
36853
- const error48 = readNonEmptyString2(args.metadataEvent.error);
36854
- return `[System] ${args.nodeLabel} worktree bootstrap failed${error48 ? `: ${error48}` : "."}. Use \`mesh_retry_node_bootstrap\` to retry or inspect the node state.`;
36855
- }
36856
- if (args.event === "refine:accepted") {
36857
- const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
36858
- return `[System] Refinery accepted async job${jobId ? ` ${jobId}` : ""} for ${args.nodeLabel}. Completion/failure will be delivered as a terminal refine event; do not poll repeatedly.`;
36859
- }
36860
- if (args.event === "refine:completed") {
36861
- const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
36862
- const result = readRecord4(args.metadataEvent.result);
36863
- const validationSummary = readRecord4(result?.validationSummary);
36864
- const patchEquivalence = readRecord4(result?.patchEquivalence);
36865
- const finalConvergence = readRecord4(result?.finalBranchConvergenceState);
36866
- const validationStatus = readNonEmptyString2(validationSummary?.status);
36867
- const patchStatus = readNonEmptyString2(patchEquivalence?.status) || (patchEquivalence?.equivalent === true ? "passed" : "");
36868
- const into = readNonEmptyString2(result?.into);
36869
- const branch = readNonEmptyString2(result?.branch);
36870
- const mergeStatus = result?.merged === true ? "merged" : readNonEmptyString2(finalConvergence?.status);
36871
- const convergenceStatus = readNonEmptyString2(finalConvergence?.status);
36872
- const nextStep = readNonEmptyString2(result?.nextStep) || readNonEmptyString2(finalConvergence?.nextStep) || "Continue from the updated mesh state.";
36873
- const details = [
36874
- jobId ? `job_id=${jobId}` : "",
36875
- branch && into ? `${branch}\u2192${into}` : "",
36876
- validationStatus ? `validation=${validationStatus}` : "",
36877
- patchStatus ? `patch_equivalence=${patchStatus}` : "",
36878
- mergeStatus ? `merge=${mergeStatus}` : "",
36879
- convergenceStatus ? `final_convergence=${convergenceStatus}` : ""
36880
- ].filter(Boolean).join("; ");
36881
- return `[System] Refinery async job for ${args.nodeLabel} completed successfully${details ? ` (${details})` : ""}.
36882
- Next step: ${nextStep}`;
36883
37018
  }
36884
- if (args.event === "refine:failed") {
36885
- const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
36886
- const result = readRecord4(args.metadataEvent.result);
36887
- const validationSummary = readRecord4(result?.validationSummary);
36888
- const patchEquivalence = readRecord4(result?.patchEquivalence);
36889
- const finalConvergence = readRecord4(result?.finalBranchConvergenceState);
36890
- const code = readNonEmptyString2(result?.code);
36891
- const error48 = readNonEmptyString2(result?.error);
36892
- const validationStatus = readNonEmptyString2(validationSummary?.status);
36893
- const patchStatus = readNonEmptyString2(patchEquivalence?.status) || (patchEquivalence?.equivalent === true ? "passed" : "");
36894
- const mergeStatus = result?.merged === true ? "merged" : finalConvergence?.merged === false ? "not_merged" : "";
36895
- const convergenceStatus = readNonEmptyString2(result?.convergenceStatus) || readNonEmptyString2(finalConvergence?.status);
36896
- const blockedReason = readNonEmptyString2(result?.blockedReason);
36897
- const nextStep = readNonEmptyString2(result?.nextStep) || readNonEmptyString2(finalConvergence?.nextStep);
36898
- const details = [
36899
- jobId ? `job_id=${jobId}` : "",
36900
- code ? `code=${code}` : "",
36901
- validationStatus ? `validation=${validationStatus}` : "",
36902
- patchStatus ? `patch_equivalence=${patchStatus}` : "",
36903
- mergeStatus ? `merge=${mergeStatus}` : "",
36904
- convergenceStatus ? `convergence=${convergenceStatus}` : "",
36905
- blockedReason ? `reason=${blockedReason}` : ""
36906
- ].filter(Boolean).join("; ");
36907
- const parts = [
36908
- `[System] Refinery async job for ${args.nodeLabel} failed${details ? ` (${details})` : ""}${error48 ? `: ${error48}` : "."}`,
36909
- nextStep ? `Next step: ${nextStep}` : "Review the terminal refine event/ledger before retrying."
36910
- ];
36911
- return parts.join("\n");
37019
+ records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
37020
+ staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
37021
+ terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
37022
+ const summary = buildMeshActiveWorkSummary(records);
37023
+ summary.staleDirectCount = staleDirectWork.length;
37024
+ const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
37025
+ if (unacknowledgedCount > 0) {
37026
+ summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
36912
37027
  }
36913
- return "";
37028
+ const staleDirectWorkNote = staleDirectWork.length > 0 ? unacknowledgedCount > 0 && unacknowledgedCount === staleDirectWork.length ? `${unacknowledgedCount} direct dispatch(es) were not acknowledged by the target session \u2014 the session received the agent_command but never transitioned to generating. This is a fresh dispatch failure, not historical noise. Recovery: launch a fresh session on the same node and retry the task, or use mesh_enqueue_task for queue-based assignment.` : unacknowledgedCount > 0 ? `${unacknowledgedCount} of ${staleDirectWork.length} stale direct record(s) are fresh unacknowledged dispatch failures (session still live but never transitioned to generating); the rest are orphaned historical entries whose node/session no longer exists. Fresh unacknowledged dispatches need recovery: launch a fresh session and retry. Orphaned entries are historical evidence only \u2014 not active or unresolved work.` : "These are orphaned ledger entries whose original node or session no longer exists in the live mesh. They are historical/recovery evidence only \u2014 not active or unresolved work. Do not treat staleDirectCount as a status mismatch; use the queue (source: queue) as authoritative for pending/assigned tasks." : void 0;
37029
+ if (staleDirectWorkNote) {
37030
+ summary.staleDirectNote = staleDirectWorkNote;
37031
+ }
37032
+ return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
36914
37033
  }
36915
- var init_mesh_events_utils = __esm2({
36916
- "src/mesh/mesh-events-utils.ts"() {
37034
+ function classifyStaleDirectForPrune(record2, opts = {}) {
37035
+ if (record2.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
37036
+ if (record2.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
37037
+ if (record2.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record2.staleReason)) return "prunable_orphan";
37038
+ return "preserve_active";
37039
+ }
37040
+ function pruneStaleDirectDispatches(opts) {
37041
+ const now = opts.now ?? Date.now();
37042
+ const includeTerminal = opts.includeTerminal === true;
37043
+ const execute = opts.execute === true;
37044
+ const minAgeMs = Math.max(0, opts.minAgeMs ?? 0);
37045
+ const activeWorkEvidence = buildMeshActiveWork({
37046
+ meshId: opts.meshId,
37047
+ queue: opts.queue,
37048
+ ledgerEntries: opts.ledgerEntries,
37049
+ directDispatches: opts.directDispatches,
37050
+ nodes: opts.nodes,
37051
+ now,
37052
+ includeTerminalDirect: includeTerminal
37053
+ });
37054
+ const candidates = [
37055
+ ...activeWorkEvidence.staleDirectWork,
37056
+ ...includeTerminal ? activeWorkEvidence.terminalDirectWork : []
37057
+ ];
37058
+ const storeTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
37059
+ const prunable = [];
37060
+ const skippedTooYoung = [];
37061
+ const preservedUnacknowledged = [];
37062
+ const preservedLedgerOnly = [];
37063
+ const preservedNotOrphan = [];
37064
+ for (const record2 of candidates) {
37065
+ const classification = classifyStaleDirectForPrune(record2, { includeTerminal });
37066
+ if (classification === "preserve_unacknowledged") {
37067
+ preservedUnacknowledged.push(record2);
37068
+ continue;
37069
+ }
37070
+ if (classification === "preserve_active") {
37071
+ preservedNotOrphan.push(record2);
37072
+ continue;
37073
+ }
37074
+ if (!storeTaskIds.has(record2.taskId)) {
37075
+ preservedLedgerOnly.push(record2);
37076
+ continue;
37077
+ }
37078
+ if (minAgeMs > 0) {
37079
+ const ageRef = record2.dispatchedAt || record2.createdAt;
37080
+ const ageMs = elapsedSince(ageRef, now);
37081
+ if (ageMs < minAgeMs) {
37082
+ skippedTooYoung.push(record2);
37083
+ continue;
37084
+ }
37085
+ }
37086
+ prunable.push(record2);
37087
+ }
37088
+ let prunedCount = 0;
37089
+ if (execute && prunable.length) {
37090
+ prunedCount = deleteDirectDispatchesByTaskId(opts.meshId, prunable.map((r) => r.taskId));
37091
+ appendLedgerEntry(opts.meshId, {
37092
+ kind: "direct_dispatch_pruned",
37093
+ payload: {
37094
+ source: opts.source || "prune_stale_direct",
37095
+ prunedCount,
37096
+ taskIds: prunable.map((r) => r.taskId),
37097
+ reasons: Array.from(new Set(prunable.map((r) => r.staleReason || (r.terminal ? "terminal" : "unknown"))))
37098
+ }
37099
+ });
37100
+ }
37101
+ return {
37102
+ mode: execute ? "execute" : "dry_run",
37103
+ includeTerminal,
37104
+ candidateCount: candidates.length,
37105
+ prunable,
37106
+ prunedCount,
37107
+ skippedTooYoung,
37108
+ preservedUnacknowledged,
37109
+ preservedLedgerOnly,
37110
+ preservedNotOrphan
37111
+ };
37112
+ }
37113
+ function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
37114
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
37115
+ const reasonCounts = {};
37116
+ for (const entry of staleDirectWork) {
37117
+ const reason = entry.staleReason || "unknown";
37118
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
37119
+ }
37120
+ return {
37121
+ count: staleDirectWork.length,
37122
+ sampleLimit,
37123
+ sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
37124
+ taskId: entry.taskId,
37125
+ status: entry.status,
37126
+ nodeId: entry.nodeId,
37127
+ sessionId: entry.sessionId,
37128
+ taskTitle: entry.taskTitle,
37129
+ createdAt: entry.createdAt,
37130
+ staleReason: entry.staleReason
37131
+ })),
37132
+ reasonCounts,
37133
+ detailHint: opts.detailHint || "Stale direct records are historical recovery evidence only. Use mesh_task_history for full ledger details, or request includeStaleDirectWorkDetails when supported by the caller.",
37134
+ ...opts.note ? { note: opts.note } : {}
37135
+ };
37136
+ }
37137
+ var DIRECT_DISPATCH_VIA;
37138
+ var TERMINAL_LEDGER_KINDS;
37139
+ var PRUNABLE_ORPHAN_STALE_REASONS;
37140
+ var init_mesh_active_work = __esm2({
37141
+ "src/mesh/mesh-active-work.ts"() {
36917
37142
  "use strict";
37143
+ init_mesh_ledger();
37144
+ init_mesh_work_queue();
37145
+ init_dist();
37146
+ DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
37147
+ TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
37148
+ PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
37149
+ "direct task node is no longer in the live mesh",
37150
+ "direct task session is not present in live session records",
37151
+ "direct task has no node id"
37152
+ ]);
36918
37153
  }
36919
37154
  });
36920
- function normalizeCoordinatorDaemonIds(coordinatorDaemonId) {
36921
- const raw = Array.isArray(coordinatorDaemonId) ? coordinatorDaemonId : coordinatorDaemonId != null ? [coordinatorDaemonId] : [];
36922
- const seen = /* @__PURE__ */ new Set();
36923
- const out = [];
36924
- for (const id of raw) {
36925
- if (typeof id !== "string") continue;
36926
- const trimmed = id.trim();
36927
- if (!trimmed || seen.has(trimmed)) continue;
36928
- seen.add(trimmed);
36929
- out.push(trimmed);
37155
+ function readNonEmptyString2(value) {
37156
+ return typeof value === "string" && value.trim() ? value.trim() : "";
37157
+ }
37158
+ function readRecord4(value) {
37159
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
37160
+ }
37161
+ function buildMeshWorkerRelayStamp(currentSettings, meshContext) {
37162
+ if (!meshContext) return void 0;
37163
+ const settings = currentSettings && typeof currentSettings === "object" ? currentSettings : {};
37164
+ const stamp = {};
37165
+ const meshId = readNonEmptyString2(meshContext.meshId);
37166
+ if (meshId && !readNonEmptyString2(settings.meshNodeFor)) stamp.meshNodeFor = meshId;
37167
+ const nodeId = readNonEmptyString2(meshContext.nodeId);
37168
+ if (nodeId && !readNonEmptyString2(settings.meshNodeId)) stamp.meshNodeId = nodeId;
37169
+ const coordinatorDaemonId = readNonEmptyString2(meshContext.coordinatorDaemonId);
37170
+ if (coordinatorDaemonId && !readNonEmptyString2(settings.meshCoordinatorDaemonId)) {
37171
+ stamp.meshCoordinatorDaemonId = coordinatorDaemonId;
36930
37172
  }
36931
- return out;
37173
+ if ((meshId || nodeId || coordinatorDaemonId) && settings.launchedByCoordinator !== true) {
37174
+ stamp.launchedByCoordinator = true;
37175
+ }
37176
+ return Object.keys(stamp).length > 0 ? stamp : void 0;
36932
37177
  }
36933
- function readRefineJobId2(event) {
37178
+ function resolveEventSessionId(event, fallback) {
37179
+ return readNonEmptyString2(event.targetSessionId) || readNonEmptyString2(event.sessionId) || readNonEmptyString2(event.instanceId) || readNonEmptyString2(fallback);
37180
+ }
37181
+ function readRefineJobId(event) {
36934
37182
  const metadata = readRecord4(event.metadataEvent) || event;
36935
37183
  const result = readRecord4(metadata.result);
36936
37184
  const refineJob = readRecord4(result?.refineJob);
36937
37185
  return readNonEmptyString2(metadata.jobId) || readNonEmptyString2(refineJob?.jobId);
36938
37186
  }
36939
- function hasPendingRefineTerminalEventDuplicate(event) {
36940
- if (!REFINE_TERMINAL_EVENTS.has(event.event)) return false;
36941
- const jobId = readRefineJobId2(event);
37187
+ function readWorkerResultMetadata(event) {
37188
+ return readRecord4(event.workerResult) || readRecord4(event.meshWorkerResult) || readRecord4(event.structuredResult);
37189
+ }
37190
+ function formatCompletionMetadata(event) {
37191
+ const completionDiagnostic = event.completionDiagnostic && typeof event.completionDiagnostic === "object" ? event.completionDiagnostic : null;
37192
+ const diagnosticReason = completionDiagnostic ? readNonEmptyString2(completionDiagnostic.blockReason) || "present" : "";
37193
+ const finalAssistantPresent = typeof completionDiagnostic?.finalAssistantPresent === "boolean" ? String(completionDiagnostic.finalAssistantPresent) : "";
37194
+ const evidenceLevel = readNonEmptyString2(event.evidenceLevel);
37195
+ const parts = [
37196
+ readNonEmptyString2(event.targetSessionId) ? `session_id=${readNonEmptyString2(event.targetSessionId)}` : "",
37197
+ readNonEmptyString2(event.providerType) ? `provider=${readNonEmptyString2(event.providerType)}` : "",
37198
+ readNonEmptyString2(event.providerSessionId) ? `provider_session_id=${readNonEmptyString2(event.providerSessionId)}` : "",
37199
+ diagnosticReason ? `completion_diagnostic=${diagnosticReason}` : "",
37200
+ finalAssistantPresent ? `final_assistant=${finalAssistantPresent}` : "",
37201
+ evidenceLevel && evidenceLevel !== "sufficient" ? `evidence_level=${evidenceLevel}` : ""
37202
+ ].filter(Boolean);
37203
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
37204
+ }
37205
+ function buildMeshSystemMessage(args) {
37206
+ const metadata = formatCompletionMetadata(args.metadataEvent);
37207
+ if (args.event === "agent:generating_completed") {
37208
+ if (args.metadataEvent.source === "long_generating_reconciliation") {
37209
+ return `[System] ${args.nodeLabel} already has completion evidence${metadata}. The long-generating monitor reconciled the terminal handoff and marked the session complete; wait for the queued completion event/status refresh before doing any manual transcript check.`;
37210
+ }
37211
+ const reviewNote = args.metadataEvent.reviewRecommended === true ? " Completion evidence is insufficient \u2014 verify via git status or provider_session_id before assuming the task is done. Use mesh_read_chat once if needed, but do not poll repeatedly." : " Use mesh_read_chat once to review its final progress, but do not poll repeatedly.";
37212
+ return `[System] ${args.nodeLabel} has completed its task and is now idle${metadata}. This completion came from the agent status event path;${reviewNote}`;
37213
+ }
37214
+ if (args.event === "agent:waiting_approval") {
37215
+ return `[System] ${args.nodeLabel} is waiting for approval to proceed${metadata}. You may use mesh_read_chat and mesh_approve to handle it.`;
37216
+ }
37217
+ if (args.event === "agent:stopped") {
37218
+ const rc = args.recoveryContext;
37219
+ if (rc && rc.consecutiveNodeFailures > 0) {
37220
+ const parts = [
37221
+ `[System] ${args.nodeLabel} has stopped unexpectedly${metadata}.`,
37222
+ `
37223
+
37224
+ **Recovery Context:**`,
37225
+ `- Consecutive failures on this node: ${rc.consecutiveNodeFailures}`,
37226
+ rc.taskAttemptCount > 0 ? `- This task has been attempted ${rc.taskAttemptCount} time(s)` : "",
37227
+ `- Recommendation: ${rc.advice}`
37228
+ ];
37229
+ if (rc.retryRecommended && rc.lastTaskMessage) {
37230
+ parts.push(
37231
+ `
37232
+
37233
+ **Original task to retry:**`,
37234
+ `> ${rc.lastTaskMessage.length > 300 ? rc.lastTaskMessage.slice(0, 300) + "..." : rc.lastTaskMessage}`,
37235
+ `
37236
+ To retry: call \`mesh_launch_session\` for this node, then \`mesh_send_task\` with the original task.`
37237
+ );
37238
+ } else if (!rc.retryRecommended) {
37239
+ parts.push(
37240
+ `
37241
+ Do NOT retry on this node. Consider reassigning to a different node or asking the user for guidance.`
37242
+ );
37243
+ }
37244
+ return parts.filter(Boolean).join("\n");
37245
+ }
37246
+ return `[System] ${args.nodeLabel} has stopped${metadata}. Use mesh_read_chat once if you need to inspect its last output.`;
37247
+ }
37248
+ if (args.event === "monitor:long_generating") {
37249
+ return `[System] ${args.nodeLabel} is still reported as generating after a long interval${metadata}. Wait for pendingCoordinatorEvents or a completion/status event; if the user explicitly asks for status, make one bounded status check and then wait again.`;
37250
+ }
37251
+ if (args.event === "worktree_bootstrap_complete") {
37252
+ const worktreePath = readNonEmptyString2(args.metadataEvent.worktreePath);
37253
+ const durationMs = typeof args.metadataEvent.durationMs === "number" ? args.metadataEvent.durationMs : void 0;
37254
+ return `[System] ${args.nodeLabel} worktree bootstrap completed${worktreePath ? ` at ${worktreePath}` : ""}${durationMs !== void 0 ? ` in ${Math.round(durationMs / 1e3)}s` : ""}. The worktree is ready \u2014 use \`mesh_launch_session\` to start an agent.`;
37255
+ }
37256
+ if (args.event === "worktree_bootstrap_failed") {
37257
+ const error48 = readNonEmptyString2(args.metadataEvent.error);
37258
+ return `[System] ${args.nodeLabel} worktree bootstrap failed${error48 ? `: ${error48}` : "."}. Use \`mesh_retry_node_bootstrap\` to retry or inspect the node state.`;
37259
+ }
37260
+ if (args.event === "refine:accepted") {
37261
+ const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
37262
+ return `[System] Refinery accepted async job${jobId ? ` ${jobId}` : ""} for ${args.nodeLabel}. Completion/failure will be delivered as a terminal refine event; do not poll repeatedly.`;
37263
+ }
37264
+ if (args.event === "refine:completed") {
37265
+ const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
37266
+ const result = readRecord4(args.metadataEvent.result);
37267
+ const validationSummary = readRecord4(result?.validationSummary);
37268
+ const patchEquivalence = readRecord4(result?.patchEquivalence);
37269
+ const finalConvergence = readRecord4(result?.finalBranchConvergenceState);
37270
+ const validationStatus = readNonEmptyString2(validationSummary?.status);
37271
+ const patchStatus = readNonEmptyString2(patchEquivalence?.status) || (patchEquivalence?.equivalent === true ? "passed" : "");
37272
+ const into = readNonEmptyString2(result?.into);
37273
+ const branch = readNonEmptyString2(result?.branch);
37274
+ const mergeStatus = result?.merged === true ? "merged" : readNonEmptyString2(finalConvergence?.status);
37275
+ const convergenceStatus = readNonEmptyString2(finalConvergence?.status);
37276
+ const nextStep = readNonEmptyString2(result?.nextStep) || readNonEmptyString2(finalConvergence?.nextStep) || "Continue from the updated mesh state.";
37277
+ const details = [
37278
+ jobId ? `job_id=${jobId}` : "",
37279
+ branch && into ? `${branch}\u2192${into}` : "",
37280
+ validationStatus ? `validation=${validationStatus}` : "",
37281
+ patchStatus ? `patch_equivalence=${patchStatus}` : "",
37282
+ mergeStatus ? `merge=${mergeStatus}` : "",
37283
+ convergenceStatus ? `final_convergence=${convergenceStatus}` : ""
37284
+ ].filter(Boolean).join("; ");
37285
+ return `[System] Refinery async job for ${args.nodeLabel} completed successfully${details ? ` (${details})` : ""}.
37286
+ Next step: ${nextStep}`;
37287
+ }
37288
+ if (args.event === "refine:failed") {
37289
+ const jobId = readRefineJobId({ metadataEvent: args.metadataEvent });
37290
+ const result = readRecord4(args.metadataEvent.result);
37291
+ const validationSummary = readRecord4(result?.validationSummary);
37292
+ const patchEquivalence = readRecord4(result?.patchEquivalence);
37293
+ const finalConvergence = readRecord4(result?.finalBranchConvergenceState);
37294
+ const code = readNonEmptyString2(result?.code);
37295
+ const error48 = readNonEmptyString2(result?.error);
37296
+ const validationStatus = readNonEmptyString2(validationSummary?.status);
37297
+ const patchStatus = readNonEmptyString2(patchEquivalence?.status) || (patchEquivalence?.equivalent === true ? "passed" : "");
37298
+ const mergeStatus = result?.merged === true ? "merged" : finalConvergence?.merged === false ? "not_merged" : "";
37299
+ const convergenceStatus = readNonEmptyString2(result?.convergenceStatus) || readNonEmptyString2(finalConvergence?.status);
37300
+ const blockedReason = readNonEmptyString2(result?.blockedReason);
37301
+ const nextStep = readNonEmptyString2(result?.nextStep) || readNonEmptyString2(finalConvergence?.nextStep);
37302
+ const details = [
37303
+ jobId ? `job_id=${jobId}` : "",
37304
+ code ? `code=${code}` : "",
37305
+ validationStatus ? `validation=${validationStatus}` : "",
37306
+ patchStatus ? `patch_equivalence=${patchStatus}` : "",
37307
+ mergeStatus ? `merge=${mergeStatus}` : "",
37308
+ convergenceStatus ? `convergence=${convergenceStatus}` : "",
37309
+ blockedReason ? `reason=${blockedReason}` : ""
37310
+ ].filter(Boolean).join("; ");
37311
+ const parts = [
37312
+ `[System] Refinery async job for ${args.nodeLabel} failed${details ? ` (${details})` : ""}${error48 ? `: ${error48}` : "."}`,
37313
+ nextStep ? `Next step: ${nextStep}` : "Review the terminal refine event/ledger before retrying."
37314
+ ];
37315
+ return parts.join("\n");
37316
+ }
37317
+ return "";
37318
+ }
37319
+ var init_mesh_events_utils = __esm2({
37320
+ "src/mesh/mesh-events-utils.ts"() {
37321
+ "use strict";
37322
+ }
37323
+ });
37324
+ function normalizeCoordinatorDaemonIds(coordinatorDaemonId) {
37325
+ const raw = Array.isArray(coordinatorDaemonId) ? coordinatorDaemonId : coordinatorDaemonId != null ? [coordinatorDaemonId] : [];
37326
+ const seen = /* @__PURE__ */ new Set();
37327
+ const out = [];
37328
+ for (const id of raw) {
37329
+ if (typeof id !== "string") continue;
37330
+ const trimmed = id.trim();
37331
+ if (!trimmed || seen.has(trimmed)) continue;
37332
+ seen.add(trimmed);
37333
+ out.push(trimmed);
37334
+ }
37335
+ return out;
37336
+ }
37337
+ function readRefineJobId2(event) {
37338
+ const metadata = readRecord4(event.metadataEvent) || event;
37339
+ const result = readRecord4(metadata.result);
37340
+ const refineJob = readRecord4(result?.refineJob);
37341
+ return readNonEmptyString2(metadata.jobId) || readNonEmptyString2(refineJob?.jobId);
37342
+ }
37343
+ function hasPendingRefineTerminalEventDuplicate(event) {
37344
+ if (!REFINE_TERMINAL_EVENTS.has(event.event)) return false;
37345
+ const jobId = readRefineJobId2(event);
36942
37346
  if (!jobId) return false;
36943
37347
  return readPendingMeshCoordinatorEventsFromDisk(event.meshId).some(
36944
37348
  (pending) => pending.event === event.event && readRefineJobId2(pending) === jobId
@@ -40572,6 +40976,14 @@ Next step: ${nextStep}`;
40572
40976
  INTERNAL_SOURCE_SET = new Set(CHAT_MESSAGE_INTERNAL_SOURCES);
40573
40977
  }
40574
40978
  });
40979
+ function resolveAutoPruneMinAgeMs() {
40980
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
40981
+ if (raw) {
40982
+ const parsed = Number.parseInt(raw, 10);
40983
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
40984
+ }
40985
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
40986
+ }
40575
40987
  function resolveReconcileIntervalMs() {
40576
40988
  const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
40577
40989
  if (raw) {
@@ -40683,6 +41095,18 @@ Next step: ${nextStep}`;
40683
41095
  LOG2.warn("MeshReconcile", `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
40684
41096
  }
40685
41097
  }
41098
+ {
41099
+ const minAgeMs = resolveAutoPruneMinAgeMs();
41100
+ for (const mesh of listMeshes()) {
41101
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
41102
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
41103
+ try {
41104
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
41105
+ } catch (e) {
41106
+ LOG2.warn("MeshReconcile", `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
41107
+ }
41108
+ }
41109
+ }
40686
41110
  const coordinators = findLiveCoordinators(components);
40687
41111
  if (coordinators.length === 0) {
40688
41112
  return;
@@ -40865,6 +41289,68 @@ Next step: ${nextStep}`;
40865
41289
  }
40866
41290
  }
40867
41291
  }
41292
+ async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs) {
41293
+ const directDispatches = getActiveDirectDispatches(mesh.id);
41294
+ if (directDispatches.length === 0) return;
41295
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
41296
+ const result = pruneStaleDirectDispatches({
41297
+ meshId: mesh.id,
41298
+ queue: getQueue(mesh.id),
41299
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
41300
+ directDispatches,
41301
+ nodes: liveNodes,
41302
+ execute: true,
41303
+ minAgeMs,
41304
+ source: "daemon_reconcile_auto_prune"
41305
+ });
41306
+ if (result.prunedCount > 0) {
41307
+ LOG2.info("MeshReconcile", `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
41308
+ }
41309
+ }
41310
+ async function collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId) {
41311
+ const dispatchMeshCommand = components.dispatchMeshCommand;
41312
+ return Promise.all(mesh.nodes.map(async (node) => {
41313
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
41314
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId;
41315
+ let statusResult;
41316
+ try {
41317
+ if (isLocalNode) {
41318
+ statusResult = await components.commandHandler.handle("get_status_metadata", {});
41319
+ } else if (dispatchMeshCommand) {
41320
+ statusResult = await dispatchMeshCommand(nodeDaemonId, "get_status_metadata", {});
41321
+ } else {
41322
+ return node;
41323
+ }
41324
+ } catch {
41325
+ return node;
41326
+ }
41327
+ const sessions = extractStatusMetadataSessions(statusResult);
41328
+ return sessions.length > 0 ? { ...node, sessions } : node;
41329
+ }));
41330
+ }
41331
+ function extractStatusMetadataSessions(raw) {
41332
+ let cursor = raw;
41333
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
41334
+ const record2 = cursor;
41335
+ const status = record2.status && typeof record2.status === "object" ? record2.status : void 0;
41336
+ if (status && Array.isArray(status.sessions)) return status.sessions;
41337
+ if (Array.isArray(record2.sessions)) return record2.sessions;
41338
+ if (record2.payload && typeof record2.payload === "object") {
41339
+ cursor = record2.payload;
41340
+ continue;
41341
+ }
41342
+ if (record2.result && typeof record2.result === "object") {
41343
+ cursor = record2.result;
41344
+ continue;
41345
+ }
41346
+ if (record2.data && typeof record2.data === "object") {
41347
+ cursor = record2.data;
41348
+ continue;
41349
+ }
41350
+ break;
41351
+ }
41352
+ return [];
41353
+ }
40868
41354
  function extractPendingEvents(raw) {
40869
41355
  if (Array.isArray(raw)) return raw;
40870
41356
  if (raw && typeof raw === "object") {
@@ -40903,6 +41389,7 @@ Next step: ${nextStep}`;
40903
41389
  };
40904
41390
  }
40905
41391
  var DEFAULT_RECONCILE_INTERVAL_MS;
41392
+ var DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
40906
41393
  var init_mesh_reconcile_loop = __esm2({
40907
41394
  "src/mesh/mesh-reconcile-loop.ts"() {
40908
41395
  "use strict";
@@ -40915,9 +41402,12 @@ Next step: ${nextStep}`;
40915
41402
  init_mesh_unresolved_forward_outbox();
40916
41403
  init_mesh_events_utils();
40917
41404
  init_mesh_work_queue();
41405
+ init_mesh_ledger();
41406
+ init_mesh_active_work();
40918
41407
  init_mesh_events_stale();
40919
41408
  init_chat_message_normalization();
40920
41409
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
41410
+ DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
40921
41411
  }
40922
41412
  });
40923
41413
  var mesh_events_exports = {};
@@ -46833,6 +47323,7 @@ ${lastSnapshot}`;
46833
47323
  prepareSessionChatTailUpdate: () => prepareSessionChatTailUpdate2,
46834
47324
  prepareSessionModalUpdate: () => prepareSessionModalUpdate2,
46835
47325
  probeCdpPort: () => probeCdpPort,
47326
+ pruneStaleDirectDispatches: () => pruneStaleDirectDispatches,
46836
47327
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
46837
47328
  readAntigravityCliSession: () => readSession3,
46838
47329
  readCachedInlineMeshActiveSessionDetails: () => readCachedInlineMeshActiveSessionDetails2,
@@ -49191,327 +49682,7 @@ ${lastSnapshot}`;
49191
49682
  };
49192
49683
  }
49193
49684
  init_mesh_work_queue();
49194
- init_dist();
49195
- var DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
49196
- var TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
49197
- function readString6(value) {
49198
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
49199
- }
49200
- function summarizeMessage(message) {
49201
- const oneLine2 = message.replace(/\s+/g, " ").trim();
49202
- const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
49203
- return { title: title || "(untitled task)", summary: oneLine2 };
49204
- }
49205
- function elapsedSince(value, now) {
49206
- const started = value ? new Date(value).getTime() : Number.NaN;
49207
- return Number.isFinite(started) ? Math.max(0, now - started) : 0;
49208
- }
49209
- function sessionStatusFromNodes(nodes, nodeId, sessionId) {
49210
- if (!Array.isArray(nodes)) return {};
49211
- if (!nodeId) return { staleReason: "direct task has no node id" };
49212
- const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
49213
- if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
49214
- if (!sessionId) return {};
49215
- const candidates = [];
49216
- for (const value of [
49217
- node.sessions,
49218
- node.activeSessions,
49219
- node.active_sessions,
49220
- node.activeSessionDetails,
49221
- node.active_session_details,
49222
- node.sessionDetails,
49223
- node.session_details,
49224
- node.lastProbe?.sessions,
49225
- node.last_probe?.sessions,
49226
- node.lastProbe?.status?.sessions,
49227
- node.last_probe?.status?.sessions
49228
- ]) {
49229
- if (Array.isArray(value)) candidates.push(...value);
49230
- }
49231
- for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
49232
- if (value && typeof value === "object") candidates.push(value);
49233
- }
49234
- const session = candidates.find((item) => {
49235
- if (typeof item === "string") return item === sessionId;
49236
- const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
49237
- return id === sessionId;
49238
- });
49239
- if (!session) return { staleReason: "direct task session is not present in live session records" };
49240
- if (typeof session === "string") return {};
49241
- const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
49242
- if (raw.includes("approval")) return { status: "awaiting_approval" };
49243
- if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
49244
- if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
49245
- if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
49246
- return {};
49247
- }
49248
- function isDirectDispatch(entry) {
49249
- if (entry.kind !== "task_dispatched") return false;
49250
- const payload = entry.payload || {};
49251
- if (payload.source === "direct") return true;
49252
- const via = readString6(payload.via);
49253
- return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
49254
- }
49255
- function directDispatchTaskId(entry) {
49256
- return readString6(entry.payload?.taskId) || entry.id;
49257
- }
49258
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
49259
- const terminalTaskId = readString6(terminal.payload?.taskId);
49260
- if (terminalTaskId && terminalTaskId === taskId) return true;
49261
- if (terminalTaskId && terminalTaskId !== taskId) return false;
49262
- if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
49263
- return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
49264
- }
49265
- function statusFromTerminal(entry) {
49266
- if (entry.kind === "task_approval_needed") return "awaiting_approval";
49267
- if (entry.kind === "task_completed") return "idle";
49268
- return "failed";
49269
- }
49270
- function buildMeshActiveWorkSummary(activeWork) {
49271
- const statusCounts = {
49272
- pending: 0,
49273
- assigned: 0,
49274
- generating: 0,
49275
- idle: 0,
49276
- failed: 0,
49277
- awaiting_approval: 0
49278
- };
49279
- const sourceCounts = { queue: 0, direct: 0 };
49280
- for (const item of activeWork) {
49281
- sourceCounts[item.source] += 1;
49282
- statusCounts[item.status] += 1;
49283
- }
49284
- const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
49285
- const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
49286
- return {
49287
- totalActiveCount: activeWork.length,
49288
- queueActiveCount: sourceCounts.queue,
49289
- directActiveCount: sourceCounts.direct,
49290
- awaitingApprovalCount: statusCounts.awaiting_approval,
49291
- generatingCount: statusCounts.generating,
49292
- failedCount: statusCounts.failed,
49293
- idleCount: statusCounts.idle,
49294
- sourceCounts,
49295
- statusCounts,
49296
- staleDirectCount,
49297
- ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
49298
- ...staleDirectCount > 0 ? { staleDirectNote: "Stale direct records are orphaned ledger entries whose node/session no longer exists. They are historical recovery evidence only \u2014 not active or unresolved work. The queue (source: queue) is authoritative for pending/assigned tasks." } : {}
49299
- };
49300
- }
49301
- function buildMeshActiveWork(opts) {
49302
- const now = opts.now ?? Date.now();
49303
- const records = [];
49304
- const staleDirectWork = [];
49305
- const terminalDirectWork = [];
49306
- for (const task of opts.queue || []) {
49307
- if (task.status !== "pending" && task.status !== "assigned") continue;
49308
- const { title, summary: summary2 } = summarizeMessage(task.message || "");
49309
- records.push({
49310
- taskId: task.id,
49311
- source: "queue",
49312
- status: task.status,
49313
- nodeId: task.assignedNodeId || task.targetNodeId,
49314
- sessionId: task.assignedSessionId || task.targetSessionId,
49315
- taskTitle: title,
49316
- taskSummary: summary2,
49317
- message: task.message,
49318
- taskMode: task.taskMode,
49319
- createdAt: task.createdAt,
49320
- updatedAt: task.updatedAt,
49321
- dispatchedAt: task.dispatchTimestamp,
49322
- elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
49323
- });
49324
- }
49325
- if (opts.directDispatches !== void 0) {
49326
- const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
49327
- for (const dispatch of opts.directDispatches) {
49328
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
49329
- const dbStatus = dispatch.status;
49330
- const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
49331
- const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
49332
- const isNoTransition = !isTerminal && !live.status;
49333
- const isIdleUnacknowledged = status === "idle" && !isTerminal;
49334
- const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
49335
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
49336
- const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
49337
- const record2 = {
49338
- taskId: dispatch.taskId,
49339
- source: "direct",
49340
- status,
49341
- nodeId: dispatch.nodeId ?? void 0,
49342
- sessionId: dispatch.sessionId ?? void 0,
49343
- providerType: dispatch.providerType ?? void 0,
49344
- taskTitle: title,
49345
- taskSummary: summary2,
49346
- message: dispatch.message,
49347
- taskMode: dispatch.taskMode ?? void 0,
49348
- createdAt: dispatch.dispatchedAt,
49349
- updatedAt: dispatch.updatedAt,
49350
- dispatchedAt: dispatch.dispatchedAt,
49351
- elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
49352
- terminal: isTerminal,
49353
- terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
49354
- terminalAt: isTerminal ? dispatch.updatedAt : void 0,
49355
- staleReason: live.staleReason || ledgerOnlyStaleReason,
49356
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
49357
- };
49358
- if (isTerminal) {
49359
- terminalDirectWork.push(record2);
49360
- if (opts.includeTerminalDirect !== true) continue;
49361
- }
49362
- if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
49363
- staleDirectWork.push(record2);
49364
- continue;
49365
- }
49366
- records.push(record2);
49367
- }
49368
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
49369
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
49370
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
49371
- const taskId = directDispatchTaskId(dispatch);
49372
- if (dbTaskIds.has(taskId)) continue;
49373
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
49374
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
49375
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
49376
- const status = terminalStatus || live.status || "assigned";
49377
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
49378
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
49379
- const isNoTransition = !terminalStatus && !live.status;
49380
- const isIdleUnacknowledged = status === "idle";
49381
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
49382
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
49383
- const { title, summary: summary2 } = summarizeMessage(message);
49384
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
49385
- const record2 = {
49386
- taskId,
49387
- source: "direct",
49388
- status,
49389
- nodeId: dispatch.nodeId,
49390
- sessionId: dispatch.sessionId,
49391
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
49392
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
49393
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
49394
- message,
49395
- taskMode: readString6(dispatch.payload?.taskMode),
49396
- createdAt: dispatch.timestamp,
49397
- updatedAt: terminal?.timestamp || dispatch.timestamp,
49398
- dispatchedAt: dispatch.timestamp,
49399
- elapsedMs: elapsedSince(dispatch.timestamp, now),
49400
- terminal: terminalRow,
49401
- terminalKind: terminal?.kind,
49402
- terminalAt: terminal?.timestamp,
49403
- staleReason: live.staleReason || ledgerOnlyStaleReason,
49404
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
49405
- };
49406
- if (terminalRow) {
49407
- terminalDirectWork.push(record2);
49408
- if (opts.includeTerminalDirect !== true) continue;
49409
- }
49410
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
49411
- staleDirectWork.push(record2);
49412
- continue;
49413
- }
49414
- records.push(record2);
49415
- }
49416
- } else {
49417
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
49418
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
49419
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
49420
- const taskId = directDispatchTaskId(dispatch);
49421
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
49422
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
49423
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
49424
- const status = terminalStatus || live.status || "assigned";
49425
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
49426
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
49427
- const isNoTransition = !terminalStatus && !live.status;
49428
- const isIdleUnacknowledged = status === "idle";
49429
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
49430
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
49431
- const { title, summary: summary2 } = summarizeMessage(message);
49432
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
49433
- const record2 = {
49434
- taskId,
49435
- source: "direct",
49436
- status,
49437
- nodeId: dispatch.nodeId,
49438
- sessionId: dispatch.sessionId,
49439
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
49440
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
49441
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
49442
- message,
49443
- taskMode: readString6(dispatch.payload?.taskMode),
49444
- createdAt: dispatch.timestamp,
49445
- updatedAt: terminal?.timestamp || dispatch.timestamp,
49446
- dispatchedAt: dispatch.timestamp,
49447
- elapsedMs: elapsedSince(dispatch.timestamp, now),
49448
- terminal: terminalRow,
49449
- terminalKind: terminal?.kind,
49450
- terminalAt: terminal?.timestamp,
49451
- staleReason: live.staleReason || ledgerOnlyStaleReason,
49452
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
49453
- };
49454
- if (terminalRow) {
49455
- terminalDirectWork.push(record2);
49456
- if (opts.includeTerminalDirect !== true) continue;
49457
- }
49458
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
49459
- staleDirectWork.push(record2);
49460
- continue;
49461
- }
49462
- records.push(record2);
49463
- }
49464
- }
49465
- records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
49466
- staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
49467
- terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
49468
- const summary = buildMeshActiveWorkSummary(records);
49469
- summary.staleDirectCount = staleDirectWork.length;
49470
- const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
49471
- if (unacknowledgedCount > 0) {
49472
- summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
49473
- }
49474
- const staleDirectWorkNote = staleDirectWork.length > 0 ? unacknowledgedCount > 0 && unacknowledgedCount === staleDirectWork.length ? `${unacknowledgedCount} direct dispatch(es) were not acknowledged by the target session \u2014 the session received the agent_command but never transitioned to generating. This is a fresh dispatch failure, not historical noise. Recovery: launch a fresh session on the same node and retry the task, or use mesh_enqueue_task for queue-based assignment.` : unacknowledgedCount > 0 ? `${unacknowledgedCount} of ${staleDirectWork.length} stale direct record(s) are fresh unacknowledged dispatch failures (session still live but never transitioned to generating); the rest are orphaned historical entries whose node/session no longer exists. Fresh unacknowledged dispatches need recovery: launch a fresh session and retry. Orphaned entries are historical evidence only \u2014 not active or unresolved work.` : "These are orphaned ledger entries whose original node or session no longer exists in the live mesh. They are historical/recovery evidence only \u2014 not active or unresolved work. Do not treat staleDirectCount as a status mismatch; use the queue (source: queue) as authoritative for pending/assigned tasks." : void 0;
49475
- if (staleDirectWorkNote) {
49476
- summary.staleDirectNote = staleDirectWorkNote;
49477
- }
49478
- return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
49479
- }
49480
- var PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
49481
- "direct task node is no longer in the live mesh",
49482
- "direct task session is not present in live session records",
49483
- "direct task has no node id"
49484
- ]);
49485
- function classifyStaleDirectForPrune(record2, opts = {}) {
49486
- if (record2.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
49487
- if (record2.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
49488
- if (record2.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record2.staleReason)) return "prunable_orphan";
49489
- return "preserve_active";
49490
- }
49491
- function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
49492
- const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
49493
- const reasonCounts = {};
49494
- for (const entry of staleDirectWork) {
49495
- const reason = entry.staleReason || "unknown";
49496
- reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
49497
- }
49498
- return {
49499
- count: staleDirectWork.length,
49500
- sampleLimit,
49501
- sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
49502
- taskId: entry.taskId,
49503
- status: entry.status,
49504
- nodeId: entry.nodeId,
49505
- sessionId: entry.sessionId,
49506
- taskTitle: entry.taskTitle,
49507
- createdAt: entry.createdAt,
49508
- staleReason: entry.staleReason
49509
- })),
49510
- reasonCounts,
49511
- detailHint: opts.detailHint || "Stale direct records are historical recovery evidence only. Use mesh_task_history for full ledger details, or request includeStaleDirectWorkDetails when supported by the caller.",
49512
- ...opts.note ? { note: opts.note } : {}
49513
- };
49514
- }
49685
+ init_mesh_active_work();
49515
49686
  init_mesh_refine_status();
49516
49687
  init_mesh_host_ownership();
49517
49688
  init_mesh_events();