@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.mjs CHANGED
@@ -308,10 +308,10 @@ function readInjected(value) {
308
308
  }
309
309
  function getDaemonBuildInfo() {
310
310
  if (cached) return cached;
311
- const commit = readInjected(true ? "9ee42155ad394578ced8959105e9a2c35d0af11b" : void 0) ?? "unknown";
312
- const commitShort = readInjected(true ? "9ee42155" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
313
- const version = readInjected(true ? "0.9.82-rc.326" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
314
- const builtAt = readInjected(true ? "2026-06-19T10:16:19.073Z" : void 0);
311
+ const commit = readInjected(true ? "38ede5a48ea8a2e21b5ea014880b9af37c6e3537" : void 0) ?? "unknown";
312
+ const commitShort = readInjected(true ? "38ede5a4" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
313
+ const version = readInjected(true ? "0.9.82-rc.328" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
314
+ const builtAt = readInjected(true ? "2026-06-19T13:57:32.496Z" : void 0);
315
315
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
316
316
  return cached;
317
317
  }
@@ -1940,6 +1940,8 @@ function updateNode(meshId, nodeId, opts) {
1940
1940
  const node = mesh.nodes.find((n) => n.id === nodeId);
1941
1941
  if (!node) return void 0;
1942
1942
  if (opts.userOverrides) node.userOverrides = { ...node.userOverrides, ...opts.userOverrides };
1943
+ if (opts.reportedPlatform && opts.reportedPlatform.trim()) node.reportedPlatform = opts.reportedPlatform.trim();
1944
+ if (opts.reportedArch && opts.reportedArch.trim()) node.reportedArch = opts.reportedArch.trim();
1943
1945
  if (opts.policy) node.policy = { ...node.policy, ...opts.policy };
1944
1946
  if (opts.worktreeBootstrap) node.worktreeBootstrap = opts.worktreeBootstrap;
1945
1947
  if (Object.prototype.hasOwnProperty.call(opts, "systemPrompt")) {
@@ -3104,11 +3106,15 @@ function readNodeOverride(node, key) {
3104
3106
  const value = overrides[key];
3105
3107
  return typeof value === "string" && value.trim() ? value.trim() : null;
3106
3108
  }
3109
+ function readNodeReporter(node, key) {
3110
+ const value = key === "platform" ? node?.reportedPlatform : node?.reportedArch;
3111
+ return typeof value === "string" && value.trim() ? value.trim() : null;
3112
+ }
3107
3113
  function buildMeshNodeCapabilityTags(node, providerType) {
3108
3114
  const provider = typeof providerType === "string" && providerType.trim() ? providerType.trim() : firstProviderPriority(node?.policy);
3109
3115
  const worktreeBranch = typeof node?.worktreeBranch === "string" && node.worktreeBranch.trim() ? node.worktreeBranch.trim() : null;
3110
- const os30 = readNodeOverride(node, "platform") ?? process.platform;
3111
- const arch2 = readNodeOverride(node, "arch") ?? process.arch;
3116
+ const os30 = readNodeOverride(node, "platform") ?? readNodeReporter(node, "platform") ?? process.platform;
3117
+ const arch2 = readNodeOverride(node, "arch") ?? readNodeReporter(node, "arch") ?? process.arch;
3112
3118
  return normalizeMeshCapabilityTags([
3113
3119
  ...Array.isArray(node?.capabilities) ? node.capabilities : [],
3114
3120
  `os=${os30}`,
@@ -6964,6 +6970,410 @@ var init_dist = __esm({
6964
6970
  }
6965
6971
  });
6966
6972
 
6973
+ // src/mesh/mesh-active-work.ts
6974
+ function readString6(value) {
6975
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
6976
+ }
6977
+ function summarizeMessage(message) {
6978
+ const oneLine2 = message.replace(/\s+/g, " ").trim();
6979
+ const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
6980
+ return { title: title || "(untitled task)", summary: oneLine2 };
6981
+ }
6982
+ function elapsedSince(value, now) {
6983
+ const started = value ? new Date(value).getTime() : Number.NaN;
6984
+ return Number.isFinite(started) ? Math.max(0, now - started) : 0;
6985
+ }
6986
+ function sessionStatusFromNodes(nodes, nodeId, sessionId) {
6987
+ if (!Array.isArray(nodes)) return {};
6988
+ if (!nodeId) return { staleReason: "direct task has no node id" };
6989
+ const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
6990
+ if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
6991
+ if (!sessionId) return {};
6992
+ const candidates = [];
6993
+ for (const value of [
6994
+ node.sessions,
6995
+ node.activeSessions,
6996
+ node.active_sessions,
6997
+ node.activeSessionDetails,
6998
+ node.active_session_details,
6999
+ node.sessionDetails,
7000
+ node.session_details,
7001
+ node.lastProbe?.sessions,
7002
+ node.last_probe?.sessions,
7003
+ node.lastProbe?.status?.sessions,
7004
+ node.last_probe?.status?.sessions
7005
+ ]) {
7006
+ if (Array.isArray(value)) candidates.push(...value);
7007
+ }
7008
+ for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
7009
+ if (value && typeof value === "object") candidates.push(value);
7010
+ }
7011
+ const session = candidates.find((item) => {
7012
+ if (typeof item === "string") return item === sessionId;
7013
+ const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
7014
+ return id === sessionId;
7015
+ });
7016
+ if (!session) return { staleReason: "direct task session is not present in live session records" };
7017
+ if (typeof session === "string") return {};
7018
+ const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
7019
+ if (raw.includes("approval")) return { status: "awaiting_approval" };
7020
+ if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
7021
+ if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
7022
+ if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
7023
+ return {};
7024
+ }
7025
+ function isDirectDispatch(entry) {
7026
+ if (entry.kind !== "task_dispatched") return false;
7027
+ const payload = entry.payload || {};
7028
+ if (payload.source === "direct") return true;
7029
+ const via = readString6(payload.via);
7030
+ return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
7031
+ }
7032
+ function directDispatchTaskId(entry) {
7033
+ return readString6(entry.payload?.taskId) || entry.id;
7034
+ }
7035
+ function terminalMatchesDispatch(terminal, dispatch, taskId) {
7036
+ const terminalTaskId = readString6(terminal.payload?.taskId);
7037
+ if (terminalTaskId && terminalTaskId === taskId) return true;
7038
+ if (terminalTaskId && terminalTaskId !== taskId) return false;
7039
+ if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
7040
+ return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
7041
+ }
7042
+ function statusFromTerminal(entry) {
7043
+ if (entry.kind === "task_approval_needed") return "awaiting_approval";
7044
+ if (entry.kind === "task_completed") return "idle";
7045
+ return "failed";
7046
+ }
7047
+ function buildMeshActiveWorkSummary(activeWork) {
7048
+ const statusCounts = {
7049
+ pending: 0,
7050
+ assigned: 0,
7051
+ generating: 0,
7052
+ idle: 0,
7053
+ failed: 0,
7054
+ awaiting_approval: 0
7055
+ };
7056
+ const sourceCounts = { queue: 0, direct: 0 };
7057
+ for (const item of activeWork) {
7058
+ sourceCounts[item.source] += 1;
7059
+ statusCounts[item.status] += 1;
7060
+ }
7061
+ const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
7062
+ const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
7063
+ return {
7064
+ totalActiveCount: activeWork.length,
7065
+ queueActiveCount: sourceCounts.queue,
7066
+ directActiveCount: sourceCounts.direct,
7067
+ awaitingApprovalCount: statusCounts.awaiting_approval,
7068
+ generatingCount: statusCounts.generating,
7069
+ failedCount: statusCounts.failed,
7070
+ idleCount: statusCounts.idle,
7071
+ sourceCounts,
7072
+ statusCounts,
7073
+ staleDirectCount,
7074
+ ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
7075
+ ...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." } : {}
7076
+ };
7077
+ }
7078
+ function buildMeshActiveWork(opts) {
7079
+ const now = opts.now ?? Date.now();
7080
+ const records = [];
7081
+ const staleDirectWork = [];
7082
+ const terminalDirectWork = [];
7083
+ for (const task of opts.queue || []) {
7084
+ if (task.status !== "pending" && task.status !== "assigned") continue;
7085
+ const { title, summary: summary2 } = summarizeMessage(task.message || "");
7086
+ records.push({
7087
+ taskId: task.id,
7088
+ source: "queue",
7089
+ status: task.status,
7090
+ nodeId: task.assignedNodeId || task.targetNodeId,
7091
+ sessionId: task.assignedSessionId || task.targetSessionId,
7092
+ taskTitle: title,
7093
+ taskSummary: summary2,
7094
+ message: task.message,
7095
+ taskMode: task.taskMode,
7096
+ createdAt: task.createdAt,
7097
+ updatedAt: task.updatedAt,
7098
+ dispatchedAt: task.dispatchTimestamp,
7099
+ elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
7100
+ });
7101
+ }
7102
+ if (opts.directDispatches !== void 0) {
7103
+ const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7104
+ for (const dispatch of opts.directDispatches) {
7105
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
7106
+ const dbStatus = dispatch.status;
7107
+ const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
7108
+ const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
7109
+ const isNoTransition = !isTerminal && !live.status;
7110
+ const isIdleUnacknowledged = status === "idle" && !isTerminal;
7111
+ const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7112
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7113
+ const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
7114
+ const record = {
7115
+ taskId: dispatch.taskId,
7116
+ source: "direct",
7117
+ status,
7118
+ nodeId: dispatch.nodeId ?? void 0,
7119
+ sessionId: dispatch.sessionId ?? void 0,
7120
+ providerType: dispatch.providerType ?? void 0,
7121
+ taskTitle: title,
7122
+ taskSummary: summary2,
7123
+ message: dispatch.message,
7124
+ taskMode: dispatch.taskMode ?? void 0,
7125
+ createdAt: dispatch.dispatchedAt,
7126
+ updatedAt: dispatch.updatedAt,
7127
+ dispatchedAt: dispatch.dispatchedAt,
7128
+ elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
7129
+ terminal: isTerminal,
7130
+ terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
7131
+ terminalAt: isTerminal ? dispatch.updatedAt : void 0,
7132
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7133
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7134
+ };
7135
+ if (isTerminal) {
7136
+ terminalDirectWork.push(record);
7137
+ if (opts.includeTerminalDirect !== true) continue;
7138
+ }
7139
+ if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
7140
+ staleDirectWork.push(record);
7141
+ continue;
7142
+ }
7143
+ records.push(record);
7144
+ }
7145
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7146
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7147
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7148
+ const taskId = directDispatchTaskId(dispatch);
7149
+ if (dbTaskIds.has(taskId)) continue;
7150
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7151
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7152
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7153
+ const status = terminalStatus || live.status || "assigned";
7154
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7155
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7156
+ const isNoTransition = !terminalStatus && !live.status;
7157
+ const isIdleUnacknowledged = status === "idle";
7158
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7159
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7160
+ const { title, summary: summary2 } = summarizeMessage(message);
7161
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7162
+ const record = {
7163
+ taskId,
7164
+ source: "direct",
7165
+ status,
7166
+ nodeId: dispatch.nodeId,
7167
+ sessionId: dispatch.sessionId,
7168
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7169
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7170
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7171
+ message,
7172
+ taskMode: readString6(dispatch.payload?.taskMode),
7173
+ createdAt: dispatch.timestamp,
7174
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7175
+ dispatchedAt: dispatch.timestamp,
7176
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7177
+ terminal: terminalRow,
7178
+ terminalKind: terminal?.kind,
7179
+ terminalAt: terminal?.timestamp,
7180
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7181
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7182
+ };
7183
+ if (terminalRow) {
7184
+ terminalDirectWork.push(record);
7185
+ if (opts.includeTerminalDirect !== true) continue;
7186
+ }
7187
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7188
+ staleDirectWork.push(record);
7189
+ continue;
7190
+ }
7191
+ records.push(record);
7192
+ }
7193
+ } else {
7194
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7195
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7196
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7197
+ const taskId = directDispatchTaskId(dispatch);
7198
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7199
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7200
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7201
+ const status = terminalStatus || live.status || "assigned";
7202
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7203
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7204
+ const isNoTransition = !terminalStatus && !live.status;
7205
+ const isIdleUnacknowledged = status === "idle";
7206
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7207
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7208
+ const { title, summary: summary2 } = summarizeMessage(message);
7209
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7210
+ const record = {
7211
+ taskId,
7212
+ source: "direct",
7213
+ status,
7214
+ nodeId: dispatch.nodeId,
7215
+ sessionId: dispatch.sessionId,
7216
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7217
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7218
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7219
+ message,
7220
+ taskMode: readString6(dispatch.payload?.taskMode),
7221
+ createdAt: dispatch.timestamp,
7222
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7223
+ dispatchedAt: dispatch.timestamp,
7224
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7225
+ terminal: terminalRow,
7226
+ terminalKind: terminal?.kind,
7227
+ terminalAt: terminal?.timestamp,
7228
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7229
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7230
+ };
7231
+ if (terminalRow) {
7232
+ terminalDirectWork.push(record);
7233
+ if (opts.includeTerminalDirect !== true) continue;
7234
+ }
7235
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7236
+ staleDirectWork.push(record);
7237
+ continue;
7238
+ }
7239
+ records.push(record);
7240
+ }
7241
+ }
7242
+ records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7243
+ staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7244
+ terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7245
+ const summary = buildMeshActiveWorkSummary(records);
7246
+ summary.staleDirectCount = staleDirectWork.length;
7247
+ const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
7248
+ if (unacknowledgedCount > 0) {
7249
+ summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
7250
+ }
7251
+ 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;
7252
+ if (staleDirectWorkNote) {
7253
+ summary.staleDirectNote = staleDirectWorkNote;
7254
+ }
7255
+ return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
7256
+ }
7257
+ function classifyStaleDirectForPrune(record, opts = {}) {
7258
+ if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
7259
+ if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
7260
+ if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
7261
+ return "preserve_active";
7262
+ }
7263
+ function pruneStaleDirectDispatches(opts) {
7264
+ const now = opts.now ?? Date.now();
7265
+ const includeTerminal = opts.includeTerminal === true;
7266
+ const execute = opts.execute === true;
7267
+ const minAgeMs = Math.max(0, opts.minAgeMs ?? 0);
7268
+ const activeWorkEvidence = buildMeshActiveWork({
7269
+ meshId: opts.meshId,
7270
+ queue: opts.queue,
7271
+ ledgerEntries: opts.ledgerEntries,
7272
+ directDispatches: opts.directDispatches,
7273
+ nodes: opts.nodes,
7274
+ now,
7275
+ includeTerminalDirect: includeTerminal
7276
+ });
7277
+ const candidates = [
7278
+ ...activeWorkEvidence.staleDirectWork,
7279
+ ...includeTerminal ? activeWorkEvidence.terminalDirectWork : []
7280
+ ];
7281
+ const storeTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7282
+ const prunable = [];
7283
+ const skippedTooYoung = [];
7284
+ const preservedUnacknowledged = [];
7285
+ const preservedLedgerOnly = [];
7286
+ const preservedNotOrphan = [];
7287
+ for (const record of candidates) {
7288
+ const classification = classifyStaleDirectForPrune(record, { includeTerminal });
7289
+ if (classification === "preserve_unacknowledged") {
7290
+ preservedUnacknowledged.push(record);
7291
+ continue;
7292
+ }
7293
+ if (classification === "preserve_active") {
7294
+ preservedNotOrphan.push(record);
7295
+ continue;
7296
+ }
7297
+ if (!storeTaskIds.has(record.taskId)) {
7298
+ preservedLedgerOnly.push(record);
7299
+ continue;
7300
+ }
7301
+ if (minAgeMs > 0) {
7302
+ const ageRef = record.dispatchedAt || record.createdAt;
7303
+ const ageMs = elapsedSince(ageRef, now);
7304
+ if (ageMs < minAgeMs) {
7305
+ skippedTooYoung.push(record);
7306
+ continue;
7307
+ }
7308
+ }
7309
+ prunable.push(record);
7310
+ }
7311
+ let prunedCount = 0;
7312
+ if (execute && prunable.length) {
7313
+ prunedCount = deleteDirectDispatchesByTaskId(opts.meshId, prunable.map((r) => r.taskId));
7314
+ appendLedgerEntry(opts.meshId, {
7315
+ kind: "direct_dispatch_pruned",
7316
+ payload: {
7317
+ source: opts.source || "prune_stale_direct",
7318
+ prunedCount,
7319
+ taskIds: prunable.map((r) => r.taskId),
7320
+ reasons: Array.from(new Set(prunable.map((r) => r.staleReason || (r.terminal ? "terminal" : "unknown"))))
7321
+ }
7322
+ });
7323
+ }
7324
+ return {
7325
+ mode: execute ? "execute" : "dry_run",
7326
+ includeTerminal,
7327
+ candidateCount: candidates.length,
7328
+ prunable,
7329
+ prunedCount,
7330
+ skippedTooYoung,
7331
+ preservedUnacknowledged,
7332
+ preservedLedgerOnly,
7333
+ preservedNotOrphan
7334
+ };
7335
+ }
7336
+ function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
7337
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
7338
+ const reasonCounts = {};
7339
+ for (const entry of staleDirectWork) {
7340
+ const reason = entry.staleReason || "unknown";
7341
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
7342
+ }
7343
+ return {
7344
+ count: staleDirectWork.length,
7345
+ sampleLimit,
7346
+ sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
7347
+ taskId: entry.taskId,
7348
+ status: entry.status,
7349
+ nodeId: entry.nodeId,
7350
+ sessionId: entry.sessionId,
7351
+ taskTitle: entry.taskTitle,
7352
+ createdAt: entry.createdAt,
7353
+ staleReason: entry.staleReason
7354
+ })),
7355
+ reasonCounts,
7356
+ 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.",
7357
+ ...opts.note ? { note: opts.note } : {}
7358
+ };
7359
+ }
7360
+ var DIRECT_DISPATCH_VIA, TERMINAL_LEDGER_KINDS, PRUNABLE_ORPHAN_STALE_REASONS;
7361
+ var init_mesh_active_work = __esm({
7362
+ "src/mesh/mesh-active-work.ts"() {
7363
+ "use strict";
7364
+ init_mesh_ledger();
7365
+ init_mesh_work_queue();
7366
+ init_dist();
7367
+ DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
7368
+ TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
7369
+ PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
7370
+ "direct task node is no longer in the live mesh",
7371
+ "direct task session is not present in live session records",
7372
+ "direct task has no node id"
7373
+ ]);
7374
+ }
7375
+ });
7376
+
6967
7377
  // src/mesh/mesh-events-utils.ts
6968
7378
  function readNonEmptyString2(value) {
6969
7379
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -10769,6 +11179,14 @@ var init_chat_message_normalization = __esm({
10769
11179
  });
10770
11180
 
10771
11181
  // src/mesh/mesh-reconcile-loop.ts
11182
+ function resolveAutoPruneMinAgeMs() {
11183
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
11184
+ if (raw) {
11185
+ const parsed = Number.parseInt(raw, 10);
11186
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
11187
+ }
11188
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11189
+ }
10772
11190
  function resolveReconcileIntervalMs() {
10773
11191
  const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
10774
11192
  if (raw) {
@@ -10880,6 +11298,18 @@ async function runMeshReconcileTick(components) {
10880
11298
  LOG.warn("MeshReconcile", `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
10881
11299
  }
10882
11300
  }
11301
+ {
11302
+ const minAgeMs = resolveAutoPruneMinAgeMs();
11303
+ for (const mesh of listMeshes()) {
11304
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
11305
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
11306
+ try {
11307
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
11308
+ } catch (e) {
11309
+ LOG.warn("MeshReconcile", `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
11310
+ }
11311
+ }
11312
+ }
10883
11313
  const coordinators = findLiveCoordinators(components);
10884
11314
  if (coordinators.length === 0) {
10885
11315
  return;
@@ -11062,6 +11492,68 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
11062
11492
  }
11063
11493
  }
11064
11494
  }
11495
+ async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs) {
11496
+ const directDispatches = getActiveDirectDispatches(mesh.id);
11497
+ if (directDispatches.length === 0) return;
11498
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
11499
+ const result = pruneStaleDirectDispatches({
11500
+ meshId: mesh.id,
11501
+ queue: getQueue(mesh.id),
11502
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
11503
+ directDispatches,
11504
+ nodes: liveNodes,
11505
+ execute: true,
11506
+ minAgeMs,
11507
+ source: "daemon_reconcile_auto_prune"
11508
+ });
11509
+ if (result.prunedCount > 0) {
11510
+ LOG.info("MeshReconcile", `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
11511
+ }
11512
+ }
11513
+ async function collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId) {
11514
+ const dispatchMeshCommand = components.dispatchMeshCommand;
11515
+ return Promise.all(mesh.nodes.map(async (node) => {
11516
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
11517
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId;
11518
+ let statusResult;
11519
+ try {
11520
+ if (isLocalNode) {
11521
+ statusResult = await components.commandHandler.handle("get_status_metadata", {});
11522
+ } else if (dispatchMeshCommand) {
11523
+ statusResult = await dispatchMeshCommand(nodeDaemonId, "get_status_metadata", {});
11524
+ } else {
11525
+ return node;
11526
+ }
11527
+ } catch {
11528
+ return node;
11529
+ }
11530
+ const sessions = extractStatusMetadataSessions(statusResult);
11531
+ return sessions.length > 0 ? { ...node, sessions } : node;
11532
+ }));
11533
+ }
11534
+ function extractStatusMetadataSessions(raw) {
11535
+ let cursor = raw;
11536
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
11537
+ const record = cursor;
11538
+ const status = record.status && typeof record.status === "object" ? record.status : void 0;
11539
+ if (status && Array.isArray(status.sessions)) return status.sessions;
11540
+ if (Array.isArray(record.sessions)) return record.sessions;
11541
+ if (record.payload && typeof record.payload === "object") {
11542
+ cursor = record.payload;
11543
+ continue;
11544
+ }
11545
+ if (record.result && typeof record.result === "object") {
11546
+ cursor = record.result;
11547
+ continue;
11548
+ }
11549
+ if (record.data && typeof record.data === "object") {
11550
+ cursor = record.data;
11551
+ continue;
11552
+ }
11553
+ break;
11554
+ }
11555
+ return [];
11556
+ }
11065
11557
  function extractPendingEvents(raw) {
11066
11558
  if (Array.isArray(raw)) return raw;
11067
11559
  if (raw && typeof raw === "object") {
@@ -11099,7 +11591,7 @@ function setupMeshReconcileLoop(components) {
11099
11591
  }
11100
11592
  };
11101
11593
  }
11102
- var DEFAULT_RECONCILE_INTERVAL_MS;
11594
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11103
11595
  var init_mesh_reconcile_loop = __esm({
11104
11596
  "src/mesh/mesh-reconcile-loop.ts"() {
11105
11597
  "use strict";
@@ -11112,9 +11604,12 @@ var init_mesh_reconcile_loop = __esm({
11112
11604
  init_mesh_unresolved_forward_outbox();
11113
11605
  init_mesh_events_utils();
11114
11606
  init_mesh_work_queue();
11607
+ init_mesh_ledger();
11608
+ init_mesh_active_work();
11115
11609
  init_mesh_events_stale();
11116
11610
  init_chat_message_normalization();
11117
11611
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
11612
+ DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
11118
11613
  }
11119
11614
  });
11120
11615
 
@@ -19081,331 +19576,7 @@ function buildMeshLedgerReconciliationEvidence(meshId, replicas) {
19081
19576
 
19082
19577
  // src/index.ts
19083
19578
  init_mesh_work_queue();
19084
-
19085
- // src/mesh/mesh-active-work.ts
19086
- init_dist();
19087
- var DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
19088
- var TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
19089
- function readString6(value) {
19090
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
19091
- }
19092
- function summarizeMessage(message) {
19093
- const oneLine2 = message.replace(/\s+/g, " ").trim();
19094
- const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
19095
- return { title: title || "(untitled task)", summary: oneLine2 };
19096
- }
19097
- function elapsedSince(value, now) {
19098
- const started = value ? new Date(value).getTime() : Number.NaN;
19099
- return Number.isFinite(started) ? Math.max(0, now - started) : 0;
19100
- }
19101
- function sessionStatusFromNodes(nodes, nodeId, sessionId) {
19102
- if (!Array.isArray(nodes)) return {};
19103
- if (!nodeId) return { staleReason: "direct task has no node id" };
19104
- const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
19105
- if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
19106
- if (!sessionId) return {};
19107
- const candidates = [];
19108
- for (const value of [
19109
- node.sessions,
19110
- node.activeSessions,
19111
- node.active_sessions,
19112
- node.activeSessionDetails,
19113
- node.active_session_details,
19114
- node.sessionDetails,
19115
- node.session_details,
19116
- node.lastProbe?.sessions,
19117
- node.last_probe?.sessions,
19118
- node.lastProbe?.status?.sessions,
19119
- node.last_probe?.status?.sessions
19120
- ]) {
19121
- if (Array.isArray(value)) candidates.push(...value);
19122
- }
19123
- for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
19124
- if (value && typeof value === "object") candidates.push(value);
19125
- }
19126
- const session = candidates.find((item) => {
19127
- if (typeof item === "string") return item === sessionId;
19128
- const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
19129
- return id === sessionId;
19130
- });
19131
- if (!session) return { staleReason: "direct task session is not present in live session records" };
19132
- if (typeof session === "string") return {};
19133
- const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
19134
- if (raw.includes("approval")) return { status: "awaiting_approval" };
19135
- if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
19136
- if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
19137
- if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
19138
- return {};
19139
- }
19140
- function isDirectDispatch(entry) {
19141
- if (entry.kind !== "task_dispatched") return false;
19142
- const payload = entry.payload || {};
19143
- if (payload.source === "direct") return true;
19144
- const via = readString6(payload.via);
19145
- return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
19146
- }
19147
- function directDispatchTaskId(entry) {
19148
- return readString6(entry.payload?.taskId) || entry.id;
19149
- }
19150
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
19151
- const terminalTaskId = readString6(terminal.payload?.taskId);
19152
- if (terminalTaskId && terminalTaskId === taskId) return true;
19153
- if (terminalTaskId && terminalTaskId !== taskId) return false;
19154
- if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
19155
- return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
19156
- }
19157
- function statusFromTerminal(entry) {
19158
- if (entry.kind === "task_approval_needed") return "awaiting_approval";
19159
- if (entry.kind === "task_completed") return "idle";
19160
- return "failed";
19161
- }
19162
- function buildMeshActiveWorkSummary(activeWork) {
19163
- const statusCounts = {
19164
- pending: 0,
19165
- assigned: 0,
19166
- generating: 0,
19167
- idle: 0,
19168
- failed: 0,
19169
- awaiting_approval: 0
19170
- };
19171
- const sourceCounts = { queue: 0, direct: 0 };
19172
- for (const item of activeWork) {
19173
- sourceCounts[item.source] += 1;
19174
- statusCounts[item.status] += 1;
19175
- }
19176
- const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
19177
- const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
19178
- return {
19179
- totalActiveCount: activeWork.length,
19180
- queueActiveCount: sourceCounts.queue,
19181
- directActiveCount: sourceCounts.direct,
19182
- awaitingApprovalCount: statusCounts.awaiting_approval,
19183
- generatingCount: statusCounts.generating,
19184
- failedCount: statusCounts.failed,
19185
- idleCount: statusCounts.idle,
19186
- sourceCounts,
19187
- statusCounts,
19188
- staleDirectCount,
19189
- ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
19190
- ...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." } : {}
19191
- };
19192
- }
19193
- function buildMeshActiveWork(opts) {
19194
- const now = opts.now ?? Date.now();
19195
- const records = [];
19196
- const staleDirectWork = [];
19197
- const terminalDirectWork = [];
19198
- for (const task of opts.queue || []) {
19199
- if (task.status !== "pending" && task.status !== "assigned") continue;
19200
- const { title, summary: summary2 } = summarizeMessage(task.message || "");
19201
- records.push({
19202
- taskId: task.id,
19203
- source: "queue",
19204
- status: task.status,
19205
- nodeId: task.assignedNodeId || task.targetNodeId,
19206
- sessionId: task.assignedSessionId || task.targetSessionId,
19207
- taskTitle: title,
19208
- taskSummary: summary2,
19209
- message: task.message,
19210
- taskMode: task.taskMode,
19211
- createdAt: task.createdAt,
19212
- updatedAt: task.updatedAt,
19213
- dispatchedAt: task.dispatchTimestamp,
19214
- elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
19215
- });
19216
- }
19217
- if (opts.directDispatches !== void 0) {
19218
- const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
19219
- for (const dispatch of opts.directDispatches) {
19220
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
19221
- const dbStatus = dispatch.status;
19222
- const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
19223
- const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
19224
- const isNoTransition = !isTerminal && !live.status;
19225
- const isIdleUnacknowledged = status === "idle" && !isTerminal;
19226
- const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19227
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19228
- const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
19229
- const record = {
19230
- taskId: dispatch.taskId,
19231
- source: "direct",
19232
- status,
19233
- nodeId: dispatch.nodeId ?? void 0,
19234
- sessionId: dispatch.sessionId ?? void 0,
19235
- providerType: dispatch.providerType ?? void 0,
19236
- taskTitle: title,
19237
- taskSummary: summary2,
19238
- message: dispatch.message,
19239
- taskMode: dispatch.taskMode ?? void 0,
19240
- createdAt: dispatch.dispatchedAt,
19241
- updatedAt: dispatch.updatedAt,
19242
- dispatchedAt: dispatch.dispatchedAt,
19243
- elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
19244
- terminal: isTerminal,
19245
- terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
19246
- terminalAt: isTerminal ? dispatch.updatedAt : void 0,
19247
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19248
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19249
- };
19250
- if (isTerminal) {
19251
- terminalDirectWork.push(record);
19252
- if (opts.includeTerminalDirect !== true) continue;
19253
- }
19254
- if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
19255
- staleDirectWork.push(record);
19256
- continue;
19257
- }
19258
- records.push(record);
19259
- }
19260
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19261
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19262
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19263
- const taskId = directDispatchTaskId(dispatch);
19264
- if (dbTaskIds.has(taskId)) continue;
19265
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19266
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19267
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19268
- const status = terminalStatus || live.status || "assigned";
19269
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19270
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19271
- const isNoTransition = !terminalStatus && !live.status;
19272
- const isIdleUnacknowledged = status === "idle";
19273
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19274
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19275
- const { title, summary: summary2 } = summarizeMessage(message);
19276
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19277
- const record = {
19278
- taskId,
19279
- source: "direct",
19280
- status,
19281
- nodeId: dispatch.nodeId,
19282
- sessionId: dispatch.sessionId,
19283
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19284
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19285
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19286
- message,
19287
- taskMode: readString6(dispatch.payload?.taskMode),
19288
- createdAt: dispatch.timestamp,
19289
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19290
- dispatchedAt: dispatch.timestamp,
19291
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19292
- terminal: terminalRow,
19293
- terminalKind: terminal?.kind,
19294
- terminalAt: terminal?.timestamp,
19295
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19296
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19297
- };
19298
- if (terminalRow) {
19299
- terminalDirectWork.push(record);
19300
- if (opts.includeTerminalDirect !== true) continue;
19301
- }
19302
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19303
- staleDirectWork.push(record);
19304
- continue;
19305
- }
19306
- records.push(record);
19307
- }
19308
- } else {
19309
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19310
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19311
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19312
- const taskId = directDispatchTaskId(dispatch);
19313
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19314
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19315
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19316
- const status = terminalStatus || live.status || "assigned";
19317
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19318
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19319
- const isNoTransition = !terminalStatus && !live.status;
19320
- const isIdleUnacknowledged = status === "idle";
19321
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19322
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19323
- const { title, summary: summary2 } = summarizeMessage(message);
19324
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19325
- const record = {
19326
- taskId,
19327
- source: "direct",
19328
- status,
19329
- nodeId: dispatch.nodeId,
19330
- sessionId: dispatch.sessionId,
19331
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19332
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19333
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19334
- message,
19335
- taskMode: readString6(dispatch.payload?.taskMode),
19336
- createdAt: dispatch.timestamp,
19337
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19338
- dispatchedAt: dispatch.timestamp,
19339
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19340
- terminal: terminalRow,
19341
- terminalKind: terminal?.kind,
19342
- terminalAt: terminal?.timestamp,
19343
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19344
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19345
- };
19346
- if (terminalRow) {
19347
- terminalDirectWork.push(record);
19348
- if (opts.includeTerminalDirect !== true) continue;
19349
- }
19350
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19351
- staleDirectWork.push(record);
19352
- continue;
19353
- }
19354
- records.push(record);
19355
- }
19356
- }
19357
- records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19358
- staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19359
- terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19360
- const summary = buildMeshActiveWorkSummary(records);
19361
- summary.staleDirectCount = staleDirectWork.length;
19362
- const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
19363
- if (unacknowledgedCount > 0) {
19364
- summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
19365
- }
19366
- 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;
19367
- if (staleDirectWorkNote) {
19368
- summary.staleDirectNote = staleDirectWorkNote;
19369
- }
19370
- return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
19371
- }
19372
- var PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
19373
- "direct task node is no longer in the live mesh",
19374
- "direct task session is not present in live session records",
19375
- "direct task has no node id"
19376
- ]);
19377
- function classifyStaleDirectForPrune(record, opts = {}) {
19378
- if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
19379
- if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
19380
- if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
19381
- return "preserve_active";
19382
- }
19383
- function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
19384
- const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
19385
- const reasonCounts = {};
19386
- for (const entry of staleDirectWork) {
19387
- const reason = entry.staleReason || "unknown";
19388
- reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
19389
- }
19390
- return {
19391
- count: staleDirectWork.length,
19392
- sampleLimit,
19393
- sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
19394
- taskId: entry.taskId,
19395
- status: entry.status,
19396
- nodeId: entry.nodeId,
19397
- sessionId: entry.sessionId,
19398
- taskTitle: entry.taskTitle,
19399
- createdAt: entry.createdAt,
19400
- staleReason: entry.staleReason
19401
- })),
19402
- reasonCounts,
19403
- 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.",
19404
- ...opts.note ? { note: opts.note } : {}
19405
- };
19406
- }
19407
-
19408
- // src/index.ts
19579
+ init_mesh_active_work();
19409
19580
  init_mesh_refine_status();
19410
19581
  init_mesh_host_ownership();
19411
19582
  init_mesh_events();
@@ -42856,7 +43027,9 @@ function buildLivePeerGitConnection(connection, timestamp = (/* @__PURE__ */ new
42856
43027
  };
42857
43028
  }
42858
43029
  function recordInlineMeshDirectGitTruth(node, git, source) {
42859
- if (!node || typeof node !== "object" || Array.isArray(node)) return;
43030
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
43031
+ return { reporterPlatform: null, reporterArch: null };
43032
+ }
42860
43033
  const checkedAt = readNumberValue(git.lastCheckedAt) ?? Date.now();
42861
43034
  const updatedAt = new Date(checkedAt).toISOString();
42862
43035
  const nextGit = {
@@ -42878,6 +43051,9 @@ function recordInlineMeshDirectGitTruth(node, git, source) {
42878
43051
  const reporterPlatform = readStringValue(git.reporterPlatform) ?? (isLocalSource ? process.platform : null);
42879
43052
  const reporterArch = readStringValue(git.reporterArch) ?? (isLocalSource ? process.arch : null);
42880
43053
  stampNodeReporterPlatform(node, reporterPlatform, reporterArch);
43054
+ if (reporterPlatform) node.reportedPlatform = reporterPlatform;
43055
+ if (reporterArch) node.reportedArch = reporterArch;
43056
+ return { reporterPlatform, reporterArch };
42881
43057
  }
42882
43058
  function stampNodeReporterPlatform(node, platform10, arch2) {
42883
43059
  if (!node || typeof node !== "object" || Array.isArray(node)) return;
@@ -42894,6 +43070,16 @@ function stampNodeReporterPlatform(node, platform10, arch2) {
42894
43070
  }
42895
43071
  if (changed) node.userOverrides = overrides;
42896
43072
  }
43073
+ function persistNodeReporterPlatform(meshSource, mesh, nodeId, reporter) {
43074
+ if (meshSource !== "local_config") return;
43075
+ const meshId = readStringValue(mesh?.id);
43076
+ if (!meshId || !nodeId) return;
43077
+ const reportedPlatform = reporter.reporterPlatform ?? void 0;
43078
+ const reportedArch = reporter.reporterArch ?? void 0;
43079
+ if (!reportedPlatform && !reportedArch) return;
43080
+ void Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports)).then(({ updateNode: updateNode2 }) => updateNode2(meshId, nodeId, { reportedPlatform, reportedArch })).catch(() => {
43081
+ });
43082
+ }
42897
43083
  function buildCachedInlineMeshGitStatus(node) {
42898
43084
  const liveGit = buildInlineMeshTransitGitStatus(node);
42899
43085
  if (liveGit) return liveGit;
@@ -43475,7 +43661,8 @@ async function hydrateInlineMeshDirectTruth(args) {
43475
43661
  try {
43476
43662
  const localGit = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
43477
43663
  if (localGit?.isGitRepo) {
43478
- recordInlineMeshDirectGitTruth(node, localGit, "selected_coordinator_local_git");
43664
+ const reporter = recordInlineMeshDirectGitTruth(node, localGit, "selected_coordinator_local_git");
43665
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
43479
43666
  localConfirmedCount += 1;
43480
43667
  continue;
43481
43668
  }
@@ -43505,7 +43692,8 @@ async function hydrateInlineMeshDirectTruth(args) {
43505
43692
  });
43506
43693
  const remoteGit = args.probeCache ? await args.probeCache.probe(daemonId, workspace, runProbe) : await runProbe();
43507
43694
  if (remoteGit) {
43508
- recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
43695
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
43696
+ persistNodeReporterPlatform(args.meshSource, args.mesh, nodeId, reporter);
43509
43697
  peerConfirmedCount += 1;
43510
43698
  continue;
43511
43699
  }
@@ -49722,7 +49910,8 @@ ${ptyResult.output.slice(-2e3)}`);
49722
49910
  if (!connectionReported || connectionState === "unknown") {
49723
49911
  status.connection = buildLivePeerGitConnection(connection, refreshedAt);
49724
49912
  }
49725
- recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
49913
+ const reporter = recordInlineMeshDirectGitTruth(node, remoteGit, "selected_coordinator_mesh_p2p_git");
49914
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
49726
49915
  remoteProbeApplied = true;
49727
49916
  }
49728
49917
  }
@@ -49754,7 +49943,8 @@ ${ptyResult.output.slice(-2e3)}`);
49754
49943
  try {
49755
49944
  const gitStatus = await getGitRepoStatus(workspace, { timeoutMs: 1e4, refreshUpstream: true });
49756
49945
  status.git = gitStatus;
49757
- recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
49946
+ const reporter = recordInlineMeshDirectGitTruth(node, gitStatus, "selected_coordinator_local_git");
49947
+ persistNodeReporterPlatform(meshRecord.source, mesh, nodeId, reporter);
49758
49948
  if (gitStatus.isGitRepo) {
49759
49949
  status.health = deriveMeshNodeHealthFromGit(gitStatus);
49760
49950
  } else {
@@ -58799,6 +58989,7 @@ export {
58799
58989
  prepareSessionChatTailUpdate,
58800
58990
  prepareSessionModalUpdate,
58801
58991
  probeCdpPort,
58992
+ pruneStaleDirectDispatches,
58802
58993
  queuePendingMeshCoordinatorEvent,
58803
58994
  readSession3 as readAntigravityCliSession,
58804
58995
  readCachedInlineMeshActiveSessionDetails,