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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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 ? "993e3922de8abe554822450e2b4c26c2c9f5f64a" : void 0) ?? "unknown";
312
- const commitShort = readInjected(true ? "993e3922" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
313
- const version = readInjected(true ? "0.9.82-rc.327" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
314
- const builtAt = readInjected(true ? "2026-06-19T12:31:25.870Z" : 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
  }
@@ -6970,6 +6970,410 @@ var init_dist = __esm({
6970
6970
  }
6971
6971
  });
6972
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
+
6973
7377
  // src/mesh/mesh-events-utils.ts
6974
7378
  function readNonEmptyString2(value) {
6975
7379
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -10775,6 +11179,14 @@ var init_chat_message_normalization = __esm({
10775
11179
  });
10776
11180
 
10777
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
+ }
10778
11190
  function resolveReconcileIntervalMs() {
10779
11191
  const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
10780
11192
  if (raw) {
@@ -10886,6 +11298,18 @@ async function runMeshReconcileTick(components) {
10886
11298
  LOG.warn("MeshReconcile", `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
10887
11299
  }
10888
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
+ }
10889
11313
  const coordinators = findLiveCoordinators(components);
10890
11314
  if (coordinators.length === 0) {
10891
11315
  return;
@@ -11068,6 +11492,68 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
11068
11492
  }
11069
11493
  }
11070
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
+ }
11071
11557
  function extractPendingEvents(raw) {
11072
11558
  if (Array.isArray(raw)) return raw;
11073
11559
  if (raw && typeof raw === "object") {
@@ -11105,7 +11591,7 @@ function setupMeshReconcileLoop(components) {
11105
11591
  }
11106
11592
  };
11107
11593
  }
11108
- var DEFAULT_RECONCILE_INTERVAL_MS;
11594
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11109
11595
  var init_mesh_reconcile_loop = __esm({
11110
11596
  "src/mesh/mesh-reconcile-loop.ts"() {
11111
11597
  "use strict";
@@ -11118,9 +11604,12 @@ var init_mesh_reconcile_loop = __esm({
11118
11604
  init_mesh_unresolved_forward_outbox();
11119
11605
  init_mesh_events_utils();
11120
11606
  init_mesh_work_queue();
11607
+ init_mesh_ledger();
11608
+ init_mesh_active_work();
11121
11609
  init_mesh_events_stale();
11122
11610
  init_chat_message_normalization();
11123
11611
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
11612
+ DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
11124
11613
  }
11125
11614
  });
11126
11615
 
@@ -19087,331 +19576,7 @@ function buildMeshLedgerReconciliationEvidence(meshId, replicas) {
19087
19576
 
19088
19577
  // src/index.ts
19089
19578
  init_mesh_work_queue();
19090
-
19091
- // src/mesh/mesh-active-work.ts
19092
- init_dist();
19093
- var DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
19094
- var TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
19095
- function readString6(value) {
19096
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
19097
- }
19098
- function summarizeMessage(message) {
19099
- const oneLine2 = message.replace(/\s+/g, " ").trim();
19100
- const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
19101
- return { title: title || "(untitled task)", summary: oneLine2 };
19102
- }
19103
- function elapsedSince(value, now) {
19104
- const started = value ? new Date(value).getTime() : Number.NaN;
19105
- return Number.isFinite(started) ? Math.max(0, now - started) : 0;
19106
- }
19107
- function sessionStatusFromNodes(nodes, nodeId, sessionId) {
19108
- if (!Array.isArray(nodes)) return {};
19109
- if (!nodeId) return { staleReason: "direct task has no node id" };
19110
- const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
19111
- if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
19112
- if (!sessionId) return {};
19113
- const candidates = [];
19114
- for (const value of [
19115
- node.sessions,
19116
- node.activeSessions,
19117
- node.active_sessions,
19118
- node.activeSessionDetails,
19119
- node.active_session_details,
19120
- node.sessionDetails,
19121
- node.session_details,
19122
- node.lastProbe?.sessions,
19123
- node.last_probe?.sessions,
19124
- node.lastProbe?.status?.sessions,
19125
- node.last_probe?.status?.sessions
19126
- ]) {
19127
- if (Array.isArray(value)) candidates.push(...value);
19128
- }
19129
- for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
19130
- if (value && typeof value === "object") candidates.push(value);
19131
- }
19132
- const session = candidates.find((item) => {
19133
- if (typeof item === "string") return item === sessionId;
19134
- const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
19135
- return id === sessionId;
19136
- });
19137
- if (!session) return { staleReason: "direct task session is not present in live session records" };
19138
- if (typeof session === "string") return {};
19139
- const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
19140
- if (raw.includes("approval")) return { status: "awaiting_approval" };
19141
- if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
19142
- if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
19143
- if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
19144
- return {};
19145
- }
19146
- function isDirectDispatch(entry) {
19147
- if (entry.kind !== "task_dispatched") return false;
19148
- const payload = entry.payload || {};
19149
- if (payload.source === "direct") return true;
19150
- const via = readString6(payload.via);
19151
- return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
19152
- }
19153
- function directDispatchTaskId(entry) {
19154
- return readString6(entry.payload?.taskId) || entry.id;
19155
- }
19156
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
19157
- const terminalTaskId = readString6(terminal.payload?.taskId);
19158
- if (terminalTaskId && terminalTaskId === taskId) return true;
19159
- if (terminalTaskId && terminalTaskId !== taskId) return false;
19160
- if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
19161
- return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
19162
- }
19163
- function statusFromTerminal(entry) {
19164
- if (entry.kind === "task_approval_needed") return "awaiting_approval";
19165
- if (entry.kind === "task_completed") return "idle";
19166
- return "failed";
19167
- }
19168
- function buildMeshActiveWorkSummary(activeWork) {
19169
- const statusCounts = {
19170
- pending: 0,
19171
- assigned: 0,
19172
- generating: 0,
19173
- idle: 0,
19174
- failed: 0,
19175
- awaiting_approval: 0
19176
- };
19177
- const sourceCounts = { queue: 0, direct: 0 };
19178
- for (const item of activeWork) {
19179
- sourceCounts[item.source] += 1;
19180
- statusCounts[item.status] += 1;
19181
- }
19182
- const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
19183
- const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
19184
- return {
19185
- totalActiveCount: activeWork.length,
19186
- queueActiveCount: sourceCounts.queue,
19187
- directActiveCount: sourceCounts.direct,
19188
- awaitingApprovalCount: statusCounts.awaiting_approval,
19189
- generatingCount: statusCounts.generating,
19190
- failedCount: statusCounts.failed,
19191
- idleCount: statusCounts.idle,
19192
- sourceCounts,
19193
- statusCounts,
19194
- staleDirectCount,
19195
- ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
19196
- ...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." } : {}
19197
- };
19198
- }
19199
- function buildMeshActiveWork(opts) {
19200
- const now = opts.now ?? Date.now();
19201
- const records = [];
19202
- const staleDirectWork = [];
19203
- const terminalDirectWork = [];
19204
- for (const task of opts.queue || []) {
19205
- if (task.status !== "pending" && task.status !== "assigned") continue;
19206
- const { title, summary: summary2 } = summarizeMessage(task.message || "");
19207
- records.push({
19208
- taskId: task.id,
19209
- source: "queue",
19210
- status: task.status,
19211
- nodeId: task.assignedNodeId || task.targetNodeId,
19212
- sessionId: task.assignedSessionId || task.targetSessionId,
19213
- taskTitle: title,
19214
- taskSummary: summary2,
19215
- message: task.message,
19216
- taskMode: task.taskMode,
19217
- createdAt: task.createdAt,
19218
- updatedAt: task.updatedAt,
19219
- dispatchedAt: task.dispatchTimestamp,
19220
- elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
19221
- });
19222
- }
19223
- if (opts.directDispatches !== void 0) {
19224
- const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
19225
- for (const dispatch of opts.directDispatches) {
19226
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
19227
- const dbStatus = dispatch.status;
19228
- const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
19229
- const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
19230
- const isNoTransition = !isTerminal && !live.status;
19231
- const isIdleUnacknowledged = status === "idle" && !isTerminal;
19232
- const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19233
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19234
- const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
19235
- const record = {
19236
- taskId: dispatch.taskId,
19237
- source: "direct",
19238
- status,
19239
- nodeId: dispatch.nodeId ?? void 0,
19240
- sessionId: dispatch.sessionId ?? void 0,
19241
- providerType: dispatch.providerType ?? void 0,
19242
- taskTitle: title,
19243
- taskSummary: summary2,
19244
- message: dispatch.message,
19245
- taskMode: dispatch.taskMode ?? void 0,
19246
- createdAt: dispatch.dispatchedAt,
19247
- updatedAt: dispatch.updatedAt,
19248
- dispatchedAt: dispatch.dispatchedAt,
19249
- elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
19250
- terminal: isTerminal,
19251
- terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
19252
- terminalAt: isTerminal ? dispatch.updatedAt : void 0,
19253
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19254
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19255
- };
19256
- if (isTerminal) {
19257
- terminalDirectWork.push(record);
19258
- if (opts.includeTerminalDirect !== true) continue;
19259
- }
19260
- if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
19261
- staleDirectWork.push(record);
19262
- continue;
19263
- }
19264
- records.push(record);
19265
- }
19266
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19267
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19268
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19269
- const taskId = directDispatchTaskId(dispatch);
19270
- if (dbTaskIds.has(taskId)) continue;
19271
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19272
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19273
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19274
- const status = terminalStatus || live.status || "assigned";
19275
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19276
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19277
- const isNoTransition = !terminalStatus && !live.status;
19278
- const isIdleUnacknowledged = status === "idle";
19279
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19280
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19281
- const { title, summary: summary2 } = summarizeMessage(message);
19282
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19283
- const record = {
19284
- taskId,
19285
- source: "direct",
19286
- status,
19287
- nodeId: dispatch.nodeId,
19288
- sessionId: dispatch.sessionId,
19289
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19290
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19291
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19292
- message,
19293
- taskMode: readString6(dispatch.payload?.taskMode),
19294
- createdAt: dispatch.timestamp,
19295
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19296
- dispatchedAt: dispatch.timestamp,
19297
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19298
- terminal: terminalRow,
19299
- terminalKind: terminal?.kind,
19300
- terminalAt: terminal?.timestamp,
19301
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19302
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19303
- };
19304
- if (terminalRow) {
19305
- terminalDirectWork.push(record);
19306
- if (opts.includeTerminalDirect !== true) continue;
19307
- }
19308
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19309
- staleDirectWork.push(record);
19310
- continue;
19311
- }
19312
- records.push(record);
19313
- }
19314
- } else {
19315
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19316
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19317
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19318
- const taskId = directDispatchTaskId(dispatch);
19319
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19320
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19321
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19322
- const status = terminalStatus || live.status || "assigned";
19323
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19324
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19325
- const isNoTransition = !terminalStatus && !live.status;
19326
- const isIdleUnacknowledged = status === "idle";
19327
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19328
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19329
- const { title, summary: summary2 } = summarizeMessage(message);
19330
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19331
- const record = {
19332
- taskId,
19333
- source: "direct",
19334
- status,
19335
- nodeId: dispatch.nodeId,
19336
- sessionId: dispatch.sessionId,
19337
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19338
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19339
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19340
- message,
19341
- taskMode: readString6(dispatch.payload?.taskMode),
19342
- createdAt: dispatch.timestamp,
19343
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19344
- dispatchedAt: dispatch.timestamp,
19345
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19346
- terminal: terminalRow,
19347
- terminalKind: terminal?.kind,
19348
- terminalAt: terminal?.timestamp,
19349
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19350
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19351
- };
19352
- if (terminalRow) {
19353
- terminalDirectWork.push(record);
19354
- if (opts.includeTerminalDirect !== true) continue;
19355
- }
19356
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19357
- staleDirectWork.push(record);
19358
- continue;
19359
- }
19360
- records.push(record);
19361
- }
19362
- }
19363
- records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19364
- staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19365
- terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19366
- const summary = buildMeshActiveWorkSummary(records);
19367
- summary.staleDirectCount = staleDirectWork.length;
19368
- const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
19369
- if (unacknowledgedCount > 0) {
19370
- summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
19371
- }
19372
- 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;
19373
- if (staleDirectWorkNote) {
19374
- summary.staleDirectNote = staleDirectWorkNote;
19375
- }
19376
- return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
19377
- }
19378
- var PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
19379
- "direct task node is no longer in the live mesh",
19380
- "direct task session is not present in live session records",
19381
- "direct task has no node id"
19382
- ]);
19383
- function classifyStaleDirectForPrune(record, opts = {}) {
19384
- if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
19385
- if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
19386
- if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
19387
- return "preserve_active";
19388
- }
19389
- function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
19390
- const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
19391
- const reasonCounts = {};
19392
- for (const entry of staleDirectWork) {
19393
- const reason = entry.staleReason || "unknown";
19394
- reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
19395
- }
19396
- return {
19397
- count: staleDirectWork.length,
19398
- sampleLimit,
19399
- sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
19400
- taskId: entry.taskId,
19401
- status: entry.status,
19402
- nodeId: entry.nodeId,
19403
- sessionId: entry.sessionId,
19404
- taskTitle: entry.taskTitle,
19405
- createdAt: entry.createdAt,
19406
- staleReason: entry.staleReason
19407
- })),
19408
- reasonCounts,
19409
- 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.",
19410
- ...opts.note ? { note: opts.note } : {}
19411
- };
19412
- }
19413
-
19414
- // src/index.ts
19579
+ init_mesh_active_work();
19415
19580
  init_mesh_refine_status();
19416
19581
  init_mesh_host_ownership();
19417
19582
  init_mesh_events();
@@ -58824,6 +58989,7 @@ export {
58824
58989
  prepareSessionChatTailUpdate,
58825
58990
  prepareSessionModalUpdate,
58826
58991
  probeCdpPort,
58992
+ pruneStaleDirectDispatches,
58827
58993
  queuePendingMeshCoordinatorEvent,
58828
58994
  readSession3 as readAntigravityCliSession,
58829
58995
  readCachedInlineMeshActiveSessionDetails,