@adhdev/daemon-core 0.9.82-rc.326 → 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
@@ -313,10 +313,10 @@ function readInjected(value) {
313
313
  }
314
314
  function getDaemonBuildInfo() {
315
315
  if (cached) return cached;
316
- const commit = readInjected(true ? "9ee42155ad394578ced8959105e9a2c35d0af11b" : void 0) ?? "unknown";
317
- const commitShort = readInjected(true ? "9ee42155" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
318
- const version = readInjected(true ? "0.9.82-rc.326" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
319
- const builtAt = readInjected(true ? "2026-06-19T10:16:19.073Z" : void 0);
316
+ const commit = readInjected(true ? "38ede5a48ea8a2e21b5ea014880b9af37c6e3537" : void 0) ?? "unknown";
317
+ const commitShort = readInjected(true ? "38ede5a4" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
318
+ const version = readInjected(true ? "0.9.82-rc.328" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
319
+ const builtAt = readInjected(true ? "2026-06-19T13:57:32.496Z" : void 0);
320
320
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
321
321
  return cached;
322
322
  }
@@ -1942,6 +1942,8 @@ function updateNode(meshId, nodeId, opts) {
1942
1942
  const node = mesh.nodes.find((n) => n.id === nodeId);
1943
1943
  if (!node) return void 0;
1944
1944
  if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
1945
+ if (opts.reportedPlatform && opts.reportedPlatform.trim()) node.reportedPlatform = opts.reportedPlatform.trim();
1946
+ if (opts.reportedArch && opts.reportedArch.trim()) node.reportedArch = opts.reportedArch.trim();
1945
1947
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
1946
1948
  if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
1947
1949
  if (Object.prototype.hasOwnProperty.call(opts, "systemPrompt")) {
@@ -3108,11 +3110,15 @@ function readNodeOverride(node, key) {
3108
3110
  const value = overrides[key];
3109
3111
  return typeof value === "string" && value.trim() ? value.trim() : null;
3110
3112
  }
3113
+ function readNodeReporter(node, key) {
3114
+ const value = key === "platform" ? node?.reportedPlatform : node?.reportedArch;
3115
+ return typeof value === "string" && value.trim() ? value.trim() : null;
3116
+ }
3111
3117
  function buildMeshNodeCapabilityTags(node, providerType) {
3112
3118
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
3113
3119
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
3114
- const os30 = readNodeOverride(node, "platform") ?? process.platform;
3115
- const arch2 = readNodeOverride(node, "arch") ?? process.arch;
3120
+ const os30 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
3121
+ const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
3116
3122
  return normalizeMeshCapabilityTags([
3117
3123
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
3118
3124
  `os=${os30}`,
@@ -6970,6 +6976,410 @@ var init_dist = __esm({
6970
6976
  }
6971
6977
  });
6972
6978
 
6979
+ // src/mesh/mesh-active-work.ts
6980
+ function readString6(value) {
6981
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
6982
+ }
6983
+ function summarizeMessage(message) {
6984
+ const oneLine2 = message.replace(/\s+/g, " ").trim();
6985
+ const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
6986
+ return { title: title || "(untitled task)", summary: oneLine2 };
6987
+ }
6988
+ function elapsedSince(value, now) {
6989
+ const started = value ? new Date(value).getTime() : Number.NaN;
6990
+ return Number.isFinite(started) ? Math.max(0, now - started) : 0;
6991
+ }
6992
+ function sessionStatusFromNodes(nodes, nodeId, sessionId) {
6993
+ if (!Array.isArray(nodes)) return {};
6994
+ if (!nodeId) return { staleReason: "direct task has no node id" };
6995
+ const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
6996
+ if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
6997
+ if (!sessionId) return {};
6998
+ const candidates = [];
6999
+ for (const value of [
7000
+ node.sessions,
7001
+ node.activeSessions,
7002
+ node.active_sessions,
7003
+ node.activeSessionDetails,
7004
+ node.active_session_details,
7005
+ node.sessionDetails,
7006
+ node.session_details,
7007
+ node.lastProbe?.sessions,
7008
+ node.last_probe?.sessions,
7009
+ node.lastProbe?.status?.sessions,
7010
+ node.last_probe?.status?.sessions
7011
+ ]) {
7012
+ if (Array.isArray(value)) candidates.push(...value);
7013
+ }
7014
+ for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
7015
+ if (value && typeof value === "object") candidates.push(value);
7016
+ }
7017
+ const session = candidates.find((item) => {
7018
+ if (typeof item === "string") return item === sessionId;
7019
+ const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
7020
+ return id === sessionId;
7021
+ });
7022
+ if (!session) return { staleReason: "direct task session is not present in live session records" };
7023
+ if (typeof session === "string") return {};
7024
+ const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
7025
+ if (raw.includes("approval")) return { status: "awaiting_approval" };
7026
+ if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
7027
+ if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
7028
+ if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
7029
+ return {};
7030
+ }
7031
+ function isDirectDispatch(entry) {
7032
+ if (entry.kind !== "task_dispatched") return false;
7033
+ const payload = entry.payload || {};
7034
+ if (payload.source === "direct") return true;
7035
+ const via = readString6(payload.via);
7036
+ return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
7037
+ }
7038
+ function directDispatchTaskId(entry) {
7039
+ return readString6(entry.payload?.taskId) || entry.id;
7040
+ }
7041
+ function terminalMatchesDispatch(terminal, dispatch, taskId) {
7042
+ const terminalTaskId = readString6(terminal.payload?.taskId);
7043
+ if (terminalTaskId && terminalTaskId === taskId) return true;
7044
+ if (terminalTaskId && terminalTaskId !== taskId) return false;
7045
+ if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
7046
+ return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
7047
+ }
7048
+ function statusFromTerminal(entry) {
7049
+ if (entry.kind === "task_approval_needed") return "awaiting_approval";
7050
+ if (entry.kind === "task_completed") return "idle";
7051
+ return "failed";
7052
+ }
7053
+ function buildMeshActiveWorkSummary(activeWork) {
7054
+ const statusCounts = {
7055
+ pending: 0,
7056
+ assigned: 0,
7057
+ generating: 0,
7058
+ idle: 0,
7059
+ failed: 0,
7060
+ awaiting_approval: 0
7061
+ };
7062
+ const sourceCounts = { queue: 0, direct: 0 };
7063
+ for (const item of activeWork) {
7064
+ sourceCounts[item.source] += 1;
7065
+ statusCounts[item.status] += 1;
7066
+ }
7067
+ const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
7068
+ const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
7069
+ return {
7070
+ totalActiveCount: activeWork.length,
7071
+ queueActiveCount: sourceCounts.queue,
7072
+ directActiveCount: sourceCounts.direct,
7073
+ awaitingApprovalCount: statusCounts.awaiting_approval,
7074
+ generatingCount: statusCounts.generating,
7075
+ failedCount: statusCounts.failed,
7076
+ idleCount: statusCounts.idle,
7077
+ sourceCounts,
7078
+ statusCounts,
7079
+ staleDirectCount,
7080
+ ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
7081
+ ...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." } : {}
7082
+ };
7083
+ }
7084
+ function buildMeshActiveWork(opts) {
7085
+ const now = opts.now ?? Date.now();
7086
+ const records = [];
7087
+ const staleDirectWork = [];
7088
+ const terminalDirectWork = [];
7089
+ for (const task of opts.queue || []) {
7090
+ if (task.status !== "pending" && task.status !== "assigned") continue;
7091
+ const { title, summary: summary2 } = summarizeMessage(task.message || "");
7092
+ records.push({
7093
+ taskId: task.id,
7094
+ source: "queue",
7095
+ status: task.status,
7096
+ nodeId: task.assignedNodeId || task.targetNodeId,
7097
+ sessionId: task.assignedSessionId || task.targetSessionId,
7098
+ taskTitle: title,
7099
+ taskSummary: summary2,
7100
+ message: task.message,
7101
+ taskMode: task.taskMode,
7102
+ createdAt: task.createdAt,
7103
+ updatedAt: task.updatedAt,
7104
+ dispatchedAt: task.dispatchTimestamp,
7105
+ elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
7106
+ });
7107
+ }
7108
+ if (opts.directDispatches !== void 0) {
7109
+ const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7110
+ for (const dispatch of opts.directDispatches) {
7111
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
7112
+ const dbStatus = dispatch.status;
7113
+ const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
7114
+ const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
7115
+ const isNoTransition = !isTerminal && !live.status;
7116
+ const isIdleUnacknowledged = status === "idle" && !isTerminal;
7117
+ const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7118
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7119
+ const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
7120
+ const record = {
7121
+ taskId: dispatch.taskId,
7122
+ source: "direct",
7123
+ status,
7124
+ nodeId: dispatch.nodeId ?? void 0,
7125
+ sessionId: dispatch.sessionId ?? void 0,
7126
+ providerType: dispatch.providerType ?? void 0,
7127
+ taskTitle: title,
7128
+ taskSummary: summary2,
7129
+ message: dispatch.message,
7130
+ taskMode: dispatch.taskMode ?? void 0,
7131
+ createdAt: dispatch.dispatchedAt,
7132
+ updatedAt: dispatch.updatedAt,
7133
+ dispatchedAt: dispatch.dispatchedAt,
7134
+ elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
7135
+ terminal: isTerminal,
7136
+ terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
7137
+ terminalAt: isTerminal ? dispatch.updatedAt : void 0,
7138
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7139
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7140
+ };
7141
+ if (isTerminal) {
7142
+ terminalDirectWork.push(record);
7143
+ if (opts.includeTerminalDirect !== true) continue;
7144
+ }
7145
+ if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
7146
+ staleDirectWork.push(record);
7147
+ continue;
7148
+ }
7149
+ records.push(record);
7150
+ }
7151
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7152
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7153
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7154
+ const taskId = directDispatchTaskId(dispatch);
7155
+ if (dbTaskIds.has(taskId)) continue;
7156
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7157
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7158
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7159
+ const status = terminalStatus || live.status || "assigned";
7160
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7161
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7162
+ const isNoTransition = !terminalStatus && !live.status;
7163
+ const isIdleUnacknowledged = status === "idle";
7164
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7165
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7166
+ const { title, summary: summary2 } = summarizeMessage(message);
7167
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7168
+ const record = {
7169
+ taskId,
7170
+ source: "direct",
7171
+ status,
7172
+ nodeId: dispatch.nodeId,
7173
+ sessionId: dispatch.sessionId,
7174
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7175
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7176
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7177
+ message,
7178
+ taskMode: readString6(dispatch.payload?.taskMode),
7179
+ createdAt: dispatch.timestamp,
7180
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7181
+ dispatchedAt: dispatch.timestamp,
7182
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7183
+ terminal: terminalRow,
7184
+ terminalKind: terminal?.kind,
7185
+ terminalAt: terminal?.timestamp,
7186
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7187
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7188
+ };
7189
+ if (terminalRow) {
7190
+ terminalDirectWork.push(record);
7191
+ if (opts.includeTerminalDirect !== true) continue;
7192
+ }
7193
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7194
+ staleDirectWork.push(record);
7195
+ continue;
7196
+ }
7197
+ records.push(record);
7198
+ }
7199
+ } else {
7200
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7201
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7202
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7203
+ const taskId = directDispatchTaskId(dispatch);
7204
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7205
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7206
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7207
+ const status = terminalStatus || live.status || "assigned";
7208
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7209
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7210
+ const isNoTransition = !terminalStatus && !live.status;
7211
+ const isIdleUnacknowledged = status === "idle";
7212
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7213
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7214
+ const { title, summary: summary2 } = summarizeMessage(message);
7215
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7216
+ const record = {
7217
+ taskId,
7218
+ source: "direct",
7219
+ status,
7220
+ nodeId: dispatch.nodeId,
7221
+ sessionId: dispatch.sessionId,
7222
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7223
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7224
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7225
+ message,
7226
+ taskMode: readString6(dispatch.payload?.taskMode),
7227
+ createdAt: dispatch.timestamp,
7228
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7229
+ dispatchedAt: dispatch.timestamp,
7230
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7231
+ terminal: terminalRow,
7232
+ terminalKind: terminal?.kind,
7233
+ terminalAt: terminal?.timestamp,
7234
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7235
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7236
+ };
7237
+ if (terminalRow) {
7238
+ terminalDirectWork.push(record);
7239
+ if (opts.includeTerminalDirect !== true) continue;
7240
+ }
7241
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7242
+ staleDirectWork.push(record);
7243
+ continue;
7244
+ }
7245
+ records.push(record);
7246
+ }
7247
+ }
7248
+ records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7249
+ staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7250
+ terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7251
+ const summary = buildMeshActiveWorkSummary(records);
7252
+ summary.staleDirectCount = staleDirectWork.length;
7253
+ const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
7254
+ if (unacknowledgedCount > 0) {
7255
+ summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
7256
+ }
7257
+ 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;
7258
+ if (staleDirectWorkNote) {
7259
+ summary.staleDirectNote = staleDirectWorkNote;
7260
+ }
7261
+ return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
7262
+ }
7263
+ function classifyStaleDirectForPrune(record, opts = {}) {
7264
+ if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
7265
+ if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
7266
+ if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
7267
+ return "preserve_active";
7268
+ }
7269
+ function pruneStaleDirectDispatches(opts) {
7270
+ const now = opts.now ?? Date.now();
7271
+ const includeTerminal = opts.includeTerminal === true;
7272
+ const execute = opts.execute === true;
7273
+ const minAgeMs = Math.max(0, opts.minAgeMs ?? 0);
7274
+ const activeWorkEvidence = buildMeshActiveWork({
7275
+ meshId: opts.meshId,
7276
+ queue: opts.queue,
7277
+ ledgerEntries: opts.ledgerEntries,
7278
+ directDispatches: opts.directDispatches,
7279
+ nodes: opts.nodes,
7280
+ now,
7281
+ includeTerminalDirect: includeTerminal
7282
+ });
7283
+ const candidates = [
7284
+ ...activeWorkEvidence.staleDirectWork,
7285
+ ...includeTerminal ? activeWorkEvidence.terminalDirectWork : []
7286
+ ];
7287
+ const storeTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7288
+ const prunable = [];
7289
+ const skippedTooYoung = [];
7290
+ const preservedUnacknowledged = [];
7291
+ const preservedLedgerOnly = [];
7292
+ const preservedNotOrphan = [];
7293
+ for (const record of candidates) {
7294
+ const classification = classifyStaleDirectForPrune(record, { includeTerminal });
7295
+ if (classification === "preserve_unacknowledged") {
7296
+ preservedUnacknowledged.push(record);
7297
+ continue;
7298
+ }
7299
+ if (classification === "preserve_active") {
7300
+ preservedNotOrphan.push(record);
7301
+ continue;
7302
+ }
7303
+ if (!storeTaskIds.has(record.taskId)) {
7304
+ preservedLedgerOnly.push(record);
7305
+ continue;
7306
+ }
7307
+ if (minAgeMs > 0) {
7308
+ const ageRef = record.dispatchedAt || record.createdAt;
7309
+ const ageMs = elapsedSince(ageRef, now);
7310
+ if (ageMs < minAgeMs) {
7311
+ skippedTooYoung.push(record);
7312
+ continue;
7313
+ }
7314
+ }
7315
+ prunable.push(record);
7316
+ }
7317
+ let prunedCount = 0;
7318
+ if (execute && prunable.length) {
7319
+ prunedCount = deleteDirectDispatchesByTaskId(opts.meshId, prunable.map((r) => r.taskId));
7320
+ appendLedgerEntry(opts.meshId, {
7321
+ kind: "direct_dispatch_pruned",
7322
+ payload: {
7323
+ source: opts.source || "prune_stale_direct",
7324
+ prunedCount,
7325
+ taskIds: prunable.map((r) => r.taskId),
7326
+ reasons: Array.from(new Set(prunable.map((r) => r.staleReason || (r.terminal ? "terminal" : "unknown"))))
7327
+ }
7328
+ });
7329
+ }
7330
+ return {
7331
+ mode: execute ? "execute" : "dry_run",
7332
+ includeTerminal,
7333
+ candidateCount: candidates.length,
7334
+ prunable,
7335
+ prunedCount,
7336
+ skippedTooYoung,
7337
+ preservedUnacknowledged,
7338
+ preservedLedgerOnly,
7339
+ preservedNotOrphan
7340
+ };
7341
+ }
7342
+ function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
7343
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
7344
+ const reasonCounts = {};
7345
+ for (const entry of staleDirectWork) {
7346
+ const reason = entry.staleReason || "unknown";
7347
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
7348
+ }
7349
+ return {
7350
+ count: staleDirectWork.length,
7351
+ sampleLimit,
7352
+ sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
7353
+ taskId: entry.taskId,
7354
+ status: entry.status,
7355
+ nodeId: entry.nodeId,
7356
+ sessionId: entry.sessionId,
7357
+ taskTitle: entry.taskTitle,
7358
+ createdAt: entry.createdAt,
7359
+ staleReason: entry.staleReason
7360
+ })),
7361
+ reasonCounts,
7362
+ 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.",
7363
+ ...opts.note ? { note: opts.note } : {}
7364
+ };
7365
+ }
7366
+ var DIRECT_DISPATCH_VIA, TERMINAL_LEDGER_KINDS, PRUNABLE_ORPHAN_STALE_REASONS;
7367
+ var init_mesh_active_work = __esm({
7368
+ "src/mesh/mesh-active-work.ts"() {
7369
+ "use strict";
7370
+ init_mesh_ledger();
7371
+ init_mesh_work_queue();
7372
+ init_dist();
7373
+ DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
7374
+ TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
7375
+ PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
7376
+ "direct task node is no longer in the live mesh",
7377
+ "direct task session is not present in live session records",
7378
+ "direct task has no node id"
7379
+ ]);
7380
+ }
7381
+ });
7382
+
6973
7383
  // src/mesh/mesh-events-utils.ts
6974
7384
  function readNonEmptyString2(value) {
6975
7385
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -10773,6 +11183,14 @@ var init_chat_message_normalization = __esm({
10773
11183
  });
10774
11184
 
10775
11185
  // src/mesh/mesh-reconcile-loop.ts
11186
+ function resolveAutoPruneMinAgeMs() {
11187
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
11188
+ if (raw) {
11189
+ const parsed = Number.parseInt(raw, 10);
11190
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
11191
+ }
11192
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11193
+ }
10776
11194
  function resolveReconcileIntervalMs() {
10777
11195
  const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
10778
11196
  if (raw) {
@@ -10884,6 +11302,18 @@ async function runMeshReconcileTick(components) {
10884
11302
  LOG.warn("MeshReconcile", `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
10885
11303
  }
10886
11304
  }
11305
+ {
11306
+ const minAgeMs = resolveAutoPruneMinAgeMs();
11307
+ for (const mesh of listMeshes()) {
11308
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
11309
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
11310
+ try {
11311
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
11312
+ } catch (e) {
11313
+ LOG.warn("MeshReconcile", `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
11314
+ }
11315
+ }
11316
+ }
10887
11317
  const coordinators = findLiveCoordinators(components);
10888
11318
  if (coordinators.length === 0) {
10889
11319
  return;
@@ -11066,6 +11496,68 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
11066
11496
  }
11067
11497
  }
11068
11498
  }
11499
+ async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs) {
11500
+ const directDispatches = getActiveDirectDispatches(mesh.id);
11501
+ if (directDispatches.length === 0) return;
11502
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
11503
+ const result = pruneStaleDirectDispatches({
11504
+ meshId: mesh.id,
11505
+ queue: getQueue(mesh.id),
11506
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
11507
+ directDispatches,
11508
+ nodes: liveNodes,
11509
+ execute: true,
11510
+ minAgeMs,
11511
+ source: "daemon_reconcile_auto_prune"
11512
+ });
11513
+ if (result.prunedCount > 0) {
11514
+ LOG.info("MeshReconcile", `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
11515
+ }
11516
+ }
11517
+ async function collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId) {
11518
+ const dispatchMeshCommand = components.dispatchMeshCommand;
11519
+ return Promise.all(mesh.nodes.map(async (node) => {
11520
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
11521
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId;
11522
+ let statusResult;
11523
+ try {
11524
+ if (isLocalNode) {
11525
+ statusResult = await components.commandHandler.handle("get_status_metadata", {});
11526
+ } else if (dispatchMeshCommand) {
11527
+ statusResult = await dispatchMeshCommand(nodeDaemonId, "get_status_metadata", {});
11528
+ } else {
11529
+ return node;
11530
+ }
11531
+ } catch {
11532
+ return node;
11533
+ }
11534
+ const sessions = extractStatusMetadataSessions(statusResult);
11535
+ return sessions.length > 0 ? { ...node, sessions } : node;
11536
+ }));
11537
+ }
11538
+ function extractStatusMetadataSessions(raw) {
11539
+ let cursor = raw;
11540
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
11541
+ const record = cursor;
11542
+ const status = record.status && typeof record.status === "object" ? record.status : void 0;
11543
+ if (status && Array.isArray(status.sessions)) return status.sessions;
11544
+ if (Array.isArray(record.sessions)) return record.sessions;
11545
+ if (record.payload && typeof record.payload === "object") {
11546
+ cursor = record.payload;
11547
+ continue;
11548
+ }
11549
+ if (record.result && typeof record.result === "object") {
11550
+ cursor = record.result;
11551
+ continue;
11552
+ }
11553
+ if (record.data && typeof record.data === "object") {
11554
+ cursor = record.data;
11555
+ continue;
11556
+ }
11557
+ break;
11558
+ }
11559
+ return [];
11560
+ }
11069
11561
  function extractPendingEvents(raw) {
11070
11562
  if (Array.isArray(raw)) return raw;
11071
11563
  if (raw && typeof raw === "object") {
@@ -11103,7 +11595,7 @@ function setupMeshReconcileLoop(components) {
11103
11595
  }
11104
11596
  };
11105
11597
  }
11106
- var DEFAULT_RECONCILE_INTERVAL_MS;
11598
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11107
11599
  var init_mesh_reconcile_loop = __esm({
11108
11600
  "src/mesh/mesh-reconcile-loop.ts"() {
11109
11601
  "use strict";
@@ -11116,9 +11608,12 @@ var init_mesh_reconcile_loop = __esm({
11116
11608
  init_mesh_unresolved_forward_outbox();
11117
11609
  init_mesh_events_utils();
11118
11610
  init_mesh_work_queue();
11611
+ init_mesh_ledger();
11612
+ init_mesh_active_work();
11119
11613
  init_mesh_events_stale();
11120
11614
  init_chat_message_normalization();
11121
11615
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
11616
+ DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
11122
11617
  }
11123
11618
  });
11124
11619
 
@@ -17032,6 +17527,7 @@ __export(index_exports, {
17032
17527
  prepareSessionChatTailUpdate: () => prepareSessionChatTailUpdate,
17033
17528
  prepareSessionModalUpdate: () => prepareSessionModalUpdate,
17034
17529
  probeCdpPort: () => probeCdpPort,
17530
+ pruneStaleDirectDispatches: () => pruneStaleDirectDispatches,
17035
17531
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
17036
17532
  readAntigravityCliSession: () => readSession3,
17037
17533
  readCachedInlineMeshActiveSessionDetails: () => readCachedInlineMeshActiveSessionDetails,
@@ -19434,331 +19930,7 @@ function buildMeshLedgerReconciliationEvidence(meshId, replicas) {
19434
19930
 
19435
19931
  // src/index.ts
19436
19932
  init_mesh_work_queue();
19437
-
19438
- // src/mesh/mesh-active-work.ts
19439
- init_dist();
19440
- var DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
19441
- var TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
19442
- function readString6(value) {
19443
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
19444
- }
19445
- function summarizeMessage(message) {
19446
- const oneLine2 = message.replace(/\s+/g, " ").trim();
19447
- const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
19448
- return { title: title || "(untitled task)", summary: oneLine2 };
19449
- }
19450
- function elapsedSince(value, now) {
19451
- const started = value ? new Date(value).getTime() : Number.NaN;
19452
- return Number.isFinite(started) ? Math.max(0, now - started) : 0;
19453
- }
19454
- function sessionStatusFromNodes(nodes, nodeId, sessionId) {
19455
- if (!Array.isArray(nodes)) return {};
19456
- if (!nodeId) return { staleReason: "direct task has no node id" };
19457
- const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
19458
- if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
19459
- if (!sessionId) return {};
19460
- const candidates = [];
19461
- for (const value of [
19462
- node.sessions,
19463
- node.activeSessions,
19464
- node.active_sessions,
19465
- node.activeSessionDetails,
19466
- node.active_session_details,
19467
- node.sessionDetails,
19468
- node.session_details,
19469
- node.lastProbe?.sessions,
19470
- node.last_probe?.sessions,
19471
- node.lastProbe?.status?.sessions,
19472
- node.last_probe?.status?.sessions
19473
- ]) {
19474
- if (Array.isArray(value)) candidates.push(...value);
19475
- }
19476
- for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
19477
- if (value && typeof value === "object") candidates.push(value);
19478
- }
19479
- const session = candidates.find((item) => {
19480
- if (typeof item === "string") return item === sessionId;
19481
- const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
19482
- return id === sessionId;
19483
- });
19484
- if (!session) return { staleReason: "direct task session is not present in live session records" };
19485
- if (typeof session === "string") return {};
19486
- const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
19487
- if (raw.includes("approval")) return { status: "awaiting_approval" };
19488
- if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
19489
- if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
19490
- if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
19491
- return {};
19492
- }
19493
- function isDirectDispatch(entry) {
19494
- if (entry.kind !== "task_dispatched") return false;
19495
- const payload = entry.payload || {};
19496
- if (payload.source === "direct") return true;
19497
- const via = readString6(payload.via);
19498
- return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
19499
- }
19500
- function directDispatchTaskId(entry) {
19501
- return readString6(entry.payload?.taskId) || entry.id;
19502
- }
19503
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
19504
- const terminalTaskId = readString6(terminal.payload?.taskId);
19505
- if (terminalTaskId && terminalTaskId === taskId) return true;
19506
- if (terminalTaskId && terminalTaskId !== taskId) return false;
19507
- if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
19508
- return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
19509
- }
19510
- function statusFromTerminal(entry) {
19511
- if (entry.kind === "task_approval_needed") return "awaiting_approval";
19512
- if (entry.kind === "task_completed") return "idle";
19513
- return "failed";
19514
- }
19515
- function buildMeshActiveWorkSummary(activeWork) {
19516
- const statusCounts = {
19517
- pending: 0,
19518
- assigned: 0,
19519
- generating: 0,
19520
- idle: 0,
19521
- failed: 0,
19522
- awaiting_approval: 0
19523
- };
19524
- const sourceCounts = { queue: 0, direct: 0 };
19525
- for (const item of activeWork) {
19526
- sourceCounts[item.source] += 1;
19527
- statusCounts[item.status] += 1;
19528
- }
19529
- const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
19530
- const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
19531
- return {
19532
- totalActiveCount: activeWork.length,
19533
- queueActiveCount: sourceCounts.queue,
19534
- directActiveCount: sourceCounts.direct,
19535
- awaitingApprovalCount: statusCounts.awaiting_approval,
19536
- generatingCount: statusCounts.generating,
19537
- failedCount: statusCounts.failed,
19538
- idleCount: statusCounts.idle,
19539
- sourceCounts,
19540
- statusCounts,
19541
- staleDirectCount,
19542
- ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
19543
- ...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." } : {}
19544
- };
19545
- }
19546
- function buildMeshActiveWork(opts) {
19547
- const now = opts.now ?? Date.now();
19548
- const records = [];
19549
- const staleDirectWork = [];
19550
- const terminalDirectWork = [];
19551
- for (const task of opts.queue || []) {
19552
- if (task.status !== "pending" && task.status !== "assigned") continue;
19553
- const { title, summary: summary2 } = summarizeMessage(task.message || "");
19554
- records.push({
19555
- taskId: task.id,
19556
- source: "queue",
19557
- status: task.status,
19558
- nodeId: task.assignedNodeId || task.targetNodeId,
19559
- sessionId: task.assignedSessionId || task.targetSessionId,
19560
- taskTitle: title,
19561
- taskSummary: summary2,
19562
- message: task.message,
19563
- taskMode: task.taskMode,
19564
- createdAt: task.createdAt,
19565
- updatedAt: task.updatedAt,
19566
- dispatchedAt: task.dispatchTimestamp,
19567
- elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
19568
- });
19569
- }
19570
- if (opts.directDispatches !== void 0) {
19571
- const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
19572
- for (const dispatch of opts.directDispatches) {
19573
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
19574
- const dbStatus = dispatch.status;
19575
- const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
19576
- const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
19577
- const isNoTransition = !isTerminal && !live.status;
19578
- const isIdleUnacknowledged = status === "idle" && !isTerminal;
19579
- const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19580
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19581
- const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
19582
- const record = {
19583
- taskId: dispatch.taskId,
19584
- source: "direct",
19585
- status,
19586
- nodeId: dispatch.nodeId ?? void 0,
19587
- sessionId: dispatch.sessionId ?? void 0,
19588
- providerType: dispatch.providerType ?? void 0,
19589
- taskTitle: title,
19590
- taskSummary: summary2,
19591
- message: dispatch.message,
19592
- taskMode: dispatch.taskMode ?? void 0,
19593
- createdAt: dispatch.dispatchedAt,
19594
- updatedAt: dispatch.updatedAt,
19595
- dispatchedAt: dispatch.dispatchedAt,
19596
- elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
19597
- terminal: isTerminal,
19598
- terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
19599
- terminalAt: isTerminal ? dispatch.updatedAt : void 0,
19600
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19601
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19602
- };
19603
- if (isTerminal) {
19604
- terminalDirectWork.push(record);
19605
- if (opts.includeTerminalDirect !== true) continue;
19606
- }
19607
- if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
19608
- staleDirectWork.push(record);
19609
- continue;
19610
- }
19611
- records.push(record);
19612
- }
19613
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19614
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19615
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19616
- const taskId = directDispatchTaskId(dispatch);
19617
- if (dbTaskIds.has(taskId)) continue;
19618
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19619
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19620
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19621
- const status = terminalStatus || live.status || "assigned";
19622
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19623
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19624
- const isNoTransition = !terminalStatus && !live.status;
19625
- const isIdleUnacknowledged = status === "idle";
19626
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19627
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19628
- const { title, summary: summary2 } = summarizeMessage(message);
19629
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19630
- const record = {
19631
- taskId,
19632
- source: "direct",
19633
- status,
19634
- nodeId: dispatch.nodeId,
19635
- sessionId: dispatch.sessionId,
19636
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19637
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19638
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19639
- message,
19640
- taskMode: readString6(dispatch.payload?.taskMode),
19641
- createdAt: dispatch.timestamp,
19642
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19643
- dispatchedAt: dispatch.timestamp,
19644
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19645
- terminal: terminalRow,
19646
- terminalKind: terminal?.kind,
19647
- terminalAt: terminal?.timestamp,
19648
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19649
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19650
- };
19651
- if (terminalRow) {
19652
- terminalDirectWork.push(record);
19653
- if (opts.includeTerminalDirect !== true) continue;
19654
- }
19655
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19656
- staleDirectWork.push(record);
19657
- continue;
19658
- }
19659
- records.push(record);
19660
- }
19661
- } else {
19662
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19663
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19664
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19665
- const taskId = directDispatchTaskId(dispatch);
19666
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19667
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19668
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19669
- const status = terminalStatus || live.status || "assigned";
19670
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19671
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19672
- const isNoTransition = !terminalStatus && !live.status;
19673
- const isIdleUnacknowledged = status === "idle";
19674
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19675
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19676
- const { title, summary: summary2 } = summarizeMessage(message);
19677
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19678
- const record = {
19679
- taskId,
19680
- source: "direct",
19681
- status,
19682
- nodeId: dispatch.nodeId,
19683
- sessionId: dispatch.sessionId,
19684
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19685
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19686
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19687
- message,
19688
- taskMode: readString6(dispatch.payload?.taskMode),
19689
- createdAt: dispatch.timestamp,
19690
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19691
- dispatchedAt: dispatch.timestamp,
19692
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19693
- terminal: terminalRow,
19694
- terminalKind: terminal?.kind,
19695
- terminalAt: terminal?.timestamp,
19696
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19697
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19698
- };
19699
- if (terminalRow) {
19700
- terminalDirectWork.push(record);
19701
- if (opts.includeTerminalDirect !== true) continue;
19702
- }
19703
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19704
- staleDirectWork.push(record);
19705
- continue;
19706
- }
19707
- records.push(record);
19708
- }
19709
- }
19710
- records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19711
- staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19712
- terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19713
- const summary = buildMeshActiveWorkSummary(records);
19714
- summary.staleDirectCount = staleDirectWork.length;
19715
- const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
19716
- if (unacknowledgedCount > 0) {
19717
- summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
19718
- }
19719
- 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;
19720
- if (staleDirectWorkNote) {
19721
- summary.staleDirectNote = staleDirectWorkNote;
19722
- }
19723
- return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
19724
- }
19725
- var PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
19726
- "direct task node is no longer in the live mesh",
19727
- "direct task session is not present in live session records",
19728
- "direct task has no node id"
19729
- ]);
19730
- function classifyStaleDirectForPrune(record, opts = {}) {
19731
- if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
19732
- if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
19733
- if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
19734
- return "preserve_active";
19735
- }
19736
- function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
19737
- const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
19738
- const reasonCounts = {};
19739
- for (const entry of staleDirectWork) {
19740
- const reason = entry.staleReason || "unknown";
19741
- reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
19742
- }
19743
- return {
19744
- count: staleDirectWork.length,
19745
- sampleLimit,
19746
- sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
19747
- taskId: entry.taskId,
19748
- status: entry.status,
19749
- nodeId: entry.nodeId,
19750
- sessionId: entry.sessionId,
19751
- taskTitle: entry.taskTitle,
19752
- createdAt: entry.createdAt,
19753
- staleReason: entry.staleReason
19754
- })),
19755
- reasonCounts,
19756
- 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.",
19757
- ...opts.note ? { note: opts.note } : {}
19758
- };
19759
- }
19760
-
19761
- // src/index.ts
19933
+ init_mesh_active_work();
19762
19934
  init_mesh_refine_status();
19763
19935
  init_mesh_host_ownership();
19764
19936
  init_mesh_events();
@@ -43204,7 +43376,9 @@ function buildLivePeerGitConnection(connection, timestamp = (/* @__PURE__ */ new
43204
43376
  };
43205
43377
  }
43206
43378
  function recordInlineMeshDirectGitTruth(node, git, source) {
43207
- if (!node || typeof node !== "object" || Array.isArray(node)) return;
43379
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
43380
+ return { reporterPlatform: null, reporterArch: null };
43381
+ }
43208
43382
  const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
43209
43383
  const updatedAt = new Date(checkedAt).toISOString();
43210
43384
  const nextGit = {
@@ -43226,6 +43400,9 @@ function recordInlineMeshDirectGitTruth(node, git, source) {
43226
43400
  const reporterPlatform = readStringValue(git.reporterPlatform) ?? (isLocalSource ? process.platform : null);
43227
43401
  const reporterArch = readStringValue(git.reporterArch) ?? (isLocalSource ? process.arch : null);
43228
43402
  stampNodeReporterPlatform(node, reporterPlatform, reporterArch);
43403
+ if (reporterPlatform) node.reportedPlatform = reporterPlatform;
43404
+ if (reporterArch) node.reportedArch = reporterArch;
43405
+ return { reporterPlatform, reporterArch };
43229
43406
  }
43230
43407
  function stampNodeReporterPlatform(node, platform10, arch2) {
43231
43408
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
@@ -43242,6 +43419,16 @@ function stampNodeReporterPlatform(node, platform10, arch2) {
43242
43419
  }
43243
43420
  if (changed) node.userOverrides = overrides;
43244
43421
  }
43422
+ function persistNodeReporterPlatform(meshSource, mesh, nodeId, reporter) {
43423
+ if (meshSource !== "local_config") return;
43424
+ const meshId = readStringValue(mesh?.id);
43425
+ if (!meshId || !nodeId) return;
43426
+ const reportedPlatform = reporter.reporterPlatform ?? void 0;
43427
+ const reportedArch = reporter.reporterArch ?? void 0;
43428
+ if (!reportedPlatform && !reportedArch) return;
43429
+ void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch })).catch(() => {
43430
+ });
43431
+ }
43245
43432
  function buildCachedInlineMeshGitStatus(node) {
43246
43433
  const liveGit = buildInlineMeshTransitGitStatus(node);
43247
43434
  if (liveGit) return liveGit;
@@ -43823,7 +44010,8 @@ async function hydrateInlineMeshDirectTruth(args) {
43823
44010
  try {
43824
44011
  const localGit = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
43825
44012
  if (localGit?.isGitRepo) {
43826
- recordInlineMeshDirectGitTruth(node, localGit, "selected_coordinator_local_git");
44013
+ const reporter = recordInlineMeshDirectGitTruth(node, localGit, "selected_coordinator_local_git");
44014
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
43827
44015
  localConfirmedCount += 1;
43828
44016
  continue;
43829
44017
  }
@@ -43853,7 +44041,8 @@ async function hydrateInlineMeshDirectTruth(args) {
43853
44041
  });
43854
44042
  const remoteGit = args.probeCache ? await args.probeCache.probe(daemonId, workspace, runProbe) : await runProbe();
43855
44043
  if (remoteGit) {
43856
- recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
44044
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
44045
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
43857
44046
  peerConfirmedCount += 1;
43858
44047
  continue;
43859
44048
  }
@@ -50070,7 +50259,8 @@ ${ptyResult.output.slice(-2e3)}`);
50070
50259
  if (!connectionReported || connectionState === "unknown") {
50071
50260
  status.connection = buildLivePeerGitConnection(connection, refreshedAt);
50072
50261
  }
50073
- recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
50262
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
50263
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
50074
50264
  remoteProbeApplied = true;
50075
50265
  }
50076
50266
  }
@@ -50102,7 +50292,8 @@ ${ptyResult.output.slice(-2e3)}`);
50102
50292
  try {
50103
50293
  const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
50104
50294
  status.git = gitStatus;
50105
- recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
50295
+ const reporter = recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
50296
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
50106
50297
  if (gitStatus.isGitRepo) {
50107
50298
  status.health = deriveMeshNodeHealthFromGit(gitStatus);
50108
50299
  } else {
@@ -59141,6 +59332,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
59141
59332
  prepareSessionChatTailUpdate,
59142
59333
  prepareSessionModalUpdate,
59143
59334
  probeCdpPort,
59335
+ pruneStaleDirectDispatches,
59144
59336
  queuePendingMeshCoordinatorEvent,
59145
59337
  readAntigravityCliSession,
59146
59338
  readCachedInlineMeshActiveSessionDetails,