@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.js CHANGED
@@ -313,10 +313,10 @@ function readInjected(value) {
313
313
  }
314
314
  function getDaemonBuildInfo() {
315
315
  if (cached) return cached;
316
- const commit = readInjected(true ? "993e3922de8abe554822450e2b4c26c2c9f5f64a" : void 0) ?? "unknown";
317
- const commitShort = readInjected(true ? "993e3922" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
318
- const version = readInjected(true ? "0.9.82-rc.327" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
319
- const builtAt = readInjected(true ? "2026-06-19T12:31:25.870Z" : void 0);
316
+ const commit = readInjected(true ? "38ede5a48ea8a2e21b5ea014880b9af37c6e3537" : void 0) ?? "unknown";
317
+ const commitShort = readInjected(true ? "38ede5a4" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
318
+ const version = readInjected(true ? "0.9.82-rc.328" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
319
+ const builtAt = readInjected(true ? "2026-06-19T13:57:32.496Z" : void 0);
320
320
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
321
321
  return cached;
322
322
  }
@@ -6976,6 +6976,410 @@ var init_dist = __esm({
6976
6976
  }
6977
6977
  });
6978
6978
 
6979
+ // src/mesh/mesh-active-work.ts
6980
+ function readString6(value) {
6981
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
6982
+ }
6983
+ function summarizeMessage(message) {
6984
+ const oneLine2 = message.replace(/\s+/g, " ").trim();
6985
+ const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
6986
+ return { title: title || "(untitled task)", summary: oneLine2 };
6987
+ }
6988
+ function elapsedSince(value, now) {
6989
+ const started = value ? new Date(value).getTime() : Number.NaN;
6990
+ return Number.isFinite(started) ? Math.max(0, now - started) : 0;
6991
+ }
6992
+ function sessionStatusFromNodes(nodes, nodeId, sessionId) {
6993
+ if (!Array.isArray(nodes)) return {};
6994
+ if (!nodeId) return { staleReason: "direct task has no node id" };
6995
+ const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
6996
+ if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
6997
+ if (!sessionId) return {};
6998
+ const candidates = [];
6999
+ for (const value of [
7000
+ node.sessions,
7001
+ node.activeSessions,
7002
+ node.active_sessions,
7003
+ node.activeSessionDetails,
7004
+ node.active_session_details,
7005
+ node.sessionDetails,
7006
+ node.session_details,
7007
+ node.lastProbe?.sessions,
7008
+ node.last_probe?.sessions,
7009
+ node.lastProbe?.status?.sessions,
7010
+ node.last_probe?.status?.sessions
7011
+ ]) {
7012
+ if (Array.isArray(value)) candidates.push(...value);
7013
+ }
7014
+ for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
7015
+ if (value && typeof value === "object") candidates.push(value);
7016
+ }
7017
+ const session = candidates.find((item) => {
7018
+ if (typeof item === "string") return item === sessionId;
7019
+ const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
7020
+ return id === sessionId;
7021
+ });
7022
+ if (!session) return { staleReason: "direct task session is not present in live session records" };
7023
+ if (typeof session === "string") return {};
7024
+ const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
7025
+ if (raw.includes("approval")) return { status: "awaiting_approval" };
7026
+ if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
7027
+ if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
7028
+ if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
7029
+ return {};
7030
+ }
7031
+ function isDirectDispatch(entry) {
7032
+ if (entry.kind !== "task_dispatched") return false;
7033
+ const payload = entry.payload || {};
7034
+ if (payload.source === "direct") return true;
7035
+ const via = readString6(payload.via);
7036
+ return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
7037
+ }
7038
+ function directDispatchTaskId(entry) {
7039
+ return readString6(entry.payload?.taskId) || entry.id;
7040
+ }
7041
+ function terminalMatchesDispatch(terminal, dispatch, taskId) {
7042
+ const terminalTaskId = readString6(terminal.payload?.taskId);
7043
+ if (terminalTaskId && terminalTaskId === taskId) return true;
7044
+ if (terminalTaskId && terminalTaskId !== taskId) return false;
7045
+ if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
7046
+ return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
7047
+ }
7048
+ function statusFromTerminal(entry) {
7049
+ if (entry.kind === "task_approval_needed") return "awaiting_approval";
7050
+ if (entry.kind === "task_completed") return "idle";
7051
+ return "failed";
7052
+ }
7053
+ function buildMeshActiveWorkSummary(activeWork) {
7054
+ const statusCounts = {
7055
+ pending: 0,
7056
+ assigned: 0,
7057
+ generating: 0,
7058
+ idle: 0,
7059
+ failed: 0,
7060
+ awaiting_approval: 0
7061
+ };
7062
+ const sourceCounts = { queue: 0, direct: 0 };
7063
+ for (const item of activeWork) {
7064
+ sourceCounts[item.source] += 1;
7065
+ statusCounts[item.status] += 1;
7066
+ }
7067
+ const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
7068
+ const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
7069
+ return {
7070
+ totalActiveCount: activeWork.length,
7071
+ queueActiveCount: sourceCounts.queue,
7072
+ directActiveCount: sourceCounts.direct,
7073
+ awaitingApprovalCount: statusCounts.awaiting_approval,
7074
+ generatingCount: statusCounts.generating,
7075
+ failedCount: statusCounts.failed,
7076
+ idleCount: statusCounts.idle,
7077
+ sourceCounts,
7078
+ statusCounts,
7079
+ staleDirectCount,
7080
+ ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
7081
+ ...staleDirectCount > 0 ? { staleDirectNote: "Stale direct records are orphaned ledger entries whose node/session no longer exists. They are historical recovery evidence only \u2014 not active or unresolved work. The queue (source: queue) is authoritative for pending/assigned tasks." } : {}
7082
+ };
7083
+ }
7084
+ function buildMeshActiveWork(opts) {
7085
+ const now = opts.now ?? Date.now();
7086
+ const records = [];
7087
+ const staleDirectWork = [];
7088
+ const terminalDirectWork = [];
7089
+ for (const task of opts.queue || []) {
7090
+ if (task.status !== "pending" && task.status !== "assigned") continue;
7091
+ const { title, summary: summary2 } = summarizeMessage(task.message || "");
7092
+ records.push({
7093
+ taskId: task.id,
7094
+ source: "queue",
7095
+ status: task.status,
7096
+ nodeId: task.assignedNodeId || task.targetNodeId,
7097
+ sessionId: task.assignedSessionId || task.targetSessionId,
7098
+ taskTitle: title,
7099
+ taskSummary: summary2,
7100
+ message: task.message,
7101
+ taskMode: task.taskMode,
7102
+ createdAt: task.createdAt,
7103
+ updatedAt: task.updatedAt,
7104
+ dispatchedAt: task.dispatchTimestamp,
7105
+ elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
7106
+ });
7107
+ }
7108
+ if (opts.directDispatches !== void 0) {
7109
+ const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7110
+ for (const dispatch of opts.directDispatches) {
7111
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
7112
+ const dbStatus = dispatch.status;
7113
+ const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
7114
+ const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
7115
+ const isNoTransition = !isTerminal && !live.status;
7116
+ const isIdleUnacknowledged = status === "idle" && !isTerminal;
7117
+ const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7118
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7119
+ const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
7120
+ const record = {
7121
+ taskId: dispatch.taskId,
7122
+ source: "direct",
7123
+ status,
7124
+ nodeId: dispatch.nodeId ?? void 0,
7125
+ sessionId: dispatch.sessionId ?? void 0,
7126
+ providerType: dispatch.providerType ?? void 0,
7127
+ taskTitle: title,
7128
+ taskSummary: summary2,
7129
+ message: dispatch.message,
7130
+ taskMode: dispatch.taskMode ?? void 0,
7131
+ createdAt: dispatch.dispatchedAt,
7132
+ updatedAt: dispatch.updatedAt,
7133
+ dispatchedAt: dispatch.dispatchedAt,
7134
+ elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
7135
+ terminal: isTerminal,
7136
+ terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
7137
+ terminalAt: isTerminal ? dispatch.updatedAt : void 0,
7138
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7139
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7140
+ };
7141
+ if (isTerminal) {
7142
+ terminalDirectWork.push(record);
7143
+ if (opts.includeTerminalDirect !== true) continue;
7144
+ }
7145
+ if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
7146
+ staleDirectWork.push(record);
7147
+ continue;
7148
+ }
7149
+ records.push(record);
7150
+ }
7151
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7152
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7153
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7154
+ const taskId = directDispatchTaskId(dispatch);
7155
+ if (dbTaskIds.has(taskId)) continue;
7156
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7157
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7158
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7159
+ const status = terminalStatus || live.status || "assigned";
7160
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7161
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7162
+ const isNoTransition = !terminalStatus && !live.status;
7163
+ const isIdleUnacknowledged = status === "idle";
7164
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7165
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7166
+ const { title, summary: summary2 } = summarizeMessage(message);
7167
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7168
+ const record = {
7169
+ taskId,
7170
+ source: "direct",
7171
+ status,
7172
+ nodeId: dispatch.nodeId,
7173
+ sessionId: dispatch.sessionId,
7174
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7175
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7176
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7177
+ message,
7178
+ taskMode: readString6(dispatch.payload?.taskMode),
7179
+ createdAt: dispatch.timestamp,
7180
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7181
+ dispatchedAt: dispatch.timestamp,
7182
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7183
+ terminal: terminalRow,
7184
+ terminalKind: terminal?.kind,
7185
+ terminalAt: terminal?.timestamp,
7186
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7187
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7188
+ };
7189
+ if (terminalRow) {
7190
+ terminalDirectWork.push(record);
7191
+ if (opts.includeTerminalDirect !== true) continue;
7192
+ }
7193
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7194
+ staleDirectWork.push(record);
7195
+ continue;
7196
+ }
7197
+ records.push(record);
7198
+ }
7199
+ } else {
7200
+ const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
7201
+ const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
7202
+ for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
7203
+ const taskId = directDispatchTaskId(dispatch);
7204
+ const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
7205
+ const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
7206
+ const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
7207
+ const status = terminalStatus || live.status || "assigned";
7208
+ const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
7209
+ const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
7210
+ const isNoTransition = !terminalStatus && !live.status;
7211
+ const isIdleUnacknowledged = status === "idle";
7212
+ const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
7213
+ const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
7214
+ const { title, summary: summary2 } = summarizeMessage(message);
7215
+ const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
7216
+ const record = {
7217
+ taskId,
7218
+ source: "direct",
7219
+ status,
7220
+ nodeId: dispatch.nodeId,
7221
+ sessionId: dispatch.sessionId,
7222
+ providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
7223
+ taskTitle: readString6(dispatch.payload?.taskTitle) || title,
7224
+ taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
7225
+ message,
7226
+ taskMode: readString6(dispatch.payload?.taskMode),
7227
+ createdAt: dispatch.timestamp,
7228
+ updatedAt: terminal?.timestamp || dispatch.timestamp,
7229
+ dispatchedAt: dispatch.timestamp,
7230
+ elapsedMs: elapsedSince(dispatch.timestamp, now),
7231
+ terminal: terminalRow,
7232
+ terminalKind: terminal?.kind,
7233
+ terminalAt: terminal?.timestamp,
7234
+ staleReason: live.staleReason || ledgerOnlyStaleReason,
7235
+ ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
7236
+ };
7237
+ if (terminalRow) {
7238
+ terminalDirectWork.push(record);
7239
+ if (opts.includeTerminalDirect !== true) continue;
7240
+ }
7241
+ if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
7242
+ staleDirectWork.push(record);
7243
+ continue;
7244
+ }
7245
+ records.push(record);
7246
+ }
7247
+ }
7248
+ records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7249
+ staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7250
+ terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
7251
+ const summary = buildMeshActiveWorkSummary(records);
7252
+ summary.staleDirectCount = staleDirectWork.length;
7253
+ const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
7254
+ if (unacknowledgedCount > 0) {
7255
+ summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
7256
+ }
7257
+ const staleDirectWorkNote = staleDirectWork.length > 0 ? unacknowledgedCount > 0 && unacknowledgedCount === staleDirectWork.length ? `${unacknowledgedCount} direct dispatch(es) were not acknowledged by the target session \u2014 the session received the agent_command but never transitioned to generating. This is a fresh dispatch failure, not historical noise. Recovery: launch a fresh session on the same node and retry the task, or use mesh_enqueue_task for queue-based assignment.` : unacknowledgedCount > 0 ? `${unacknowledgedCount} of ${staleDirectWork.length} stale direct record(s) are fresh unacknowledged dispatch failures (session still live but never transitioned to generating); the rest are orphaned historical entries whose node/session no longer exists. Fresh unacknowledged dispatches need recovery: launch a fresh session and retry. Orphaned entries are historical evidence only \u2014 not active or unresolved work.` : "These are orphaned ledger entries whose original node or session no longer exists in the live mesh. They are historical/recovery evidence only \u2014 not active or unresolved work. Do not treat staleDirectCount as a status mismatch; use the queue (source: queue) as authoritative for pending/assigned tasks." : void 0;
7258
+ if (staleDirectWorkNote) {
7259
+ summary.staleDirectNote = staleDirectWorkNote;
7260
+ }
7261
+ return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
7262
+ }
7263
+ function classifyStaleDirectForPrune(record, opts = {}) {
7264
+ if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
7265
+ if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
7266
+ if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
7267
+ return "preserve_active";
7268
+ }
7269
+ function pruneStaleDirectDispatches(opts) {
7270
+ const now = opts.now ?? Date.now();
7271
+ const includeTerminal = opts.includeTerminal === true;
7272
+ const execute = opts.execute === true;
7273
+ const minAgeMs = Math.max(0, opts.minAgeMs ?? 0);
7274
+ const activeWorkEvidence = buildMeshActiveWork({
7275
+ meshId: opts.meshId,
7276
+ queue: opts.queue,
7277
+ ledgerEntries: opts.ledgerEntries,
7278
+ directDispatches: opts.directDispatches,
7279
+ nodes: opts.nodes,
7280
+ now,
7281
+ includeTerminalDirect: includeTerminal
7282
+ });
7283
+ const candidates = [
7284
+ ...activeWorkEvidence.staleDirectWork,
7285
+ ...includeTerminal ? activeWorkEvidence.terminalDirectWork : []
7286
+ ];
7287
+ const storeTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
7288
+ const prunable = [];
7289
+ const skippedTooYoung = [];
7290
+ const preservedUnacknowledged = [];
7291
+ const preservedLedgerOnly = [];
7292
+ const preservedNotOrphan = [];
7293
+ for (const record of candidates) {
7294
+ const classification = classifyStaleDirectForPrune(record, { includeTerminal });
7295
+ if (classification === "preserve_unacknowledged") {
7296
+ preservedUnacknowledged.push(record);
7297
+ continue;
7298
+ }
7299
+ if (classification === "preserve_active") {
7300
+ preservedNotOrphan.push(record);
7301
+ continue;
7302
+ }
7303
+ if (!storeTaskIds.has(record.taskId)) {
7304
+ preservedLedgerOnly.push(record);
7305
+ continue;
7306
+ }
7307
+ if (minAgeMs > 0) {
7308
+ const ageRef = record.dispatchedAt || record.createdAt;
7309
+ const ageMs = elapsedSince(ageRef, now);
7310
+ if (ageMs < minAgeMs) {
7311
+ skippedTooYoung.push(record);
7312
+ continue;
7313
+ }
7314
+ }
7315
+ prunable.push(record);
7316
+ }
7317
+ let prunedCount = 0;
7318
+ if (execute && prunable.length) {
7319
+ prunedCount = deleteDirectDispatchesByTaskId(opts.meshId, prunable.map((r) => r.taskId));
7320
+ appendLedgerEntry(opts.meshId, {
7321
+ kind: "direct_dispatch_pruned",
7322
+ payload: {
7323
+ source: opts.source || "prune_stale_direct",
7324
+ prunedCount,
7325
+ taskIds: prunable.map((r) => r.taskId),
7326
+ reasons: Array.from(new Set(prunable.map((r) => r.staleReason || (r.terminal ? "terminal" : "unknown"))))
7327
+ }
7328
+ });
7329
+ }
7330
+ return {
7331
+ mode: execute ? "execute" : "dry_run",
7332
+ includeTerminal,
7333
+ candidateCount: candidates.length,
7334
+ prunable,
7335
+ prunedCount,
7336
+ skippedTooYoung,
7337
+ preservedUnacknowledged,
7338
+ preservedLedgerOnly,
7339
+ preservedNotOrphan
7340
+ };
7341
+ }
7342
+ function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
7343
+ const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
7344
+ const reasonCounts = {};
7345
+ for (const entry of staleDirectWork) {
7346
+ const reason = entry.staleReason || "unknown";
7347
+ reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
7348
+ }
7349
+ return {
7350
+ count: staleDirectWork.length,
7351
+ sampleLimit,
7352
+ sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
7353
+ taskId: entry.taskId,
7354
+ status: entry.status,
7355
+ nodeId: entry.nodeId,
7356
+ sessionId: entry.sessionId,
7357
+ taskTitle: entry.taskTitle,
7358
+ createdAt: entry.createdAt,
7359
+ staleReason: entry.staleReason
7360
+ })),
7361
+ reasonCounts,
7362
+ detailHint: opts.detailHint || "Stale direct records are historical recovery evidence only. Use mesh_task_history for full ledger details, or request includeStaleDirectWorkDetails when supported by the caller.",
7363
+ ...opts.note ? { note: opts.note } : {}
7364
+ };
7365
+ }
7366
+ var DIRECT_DISPATCH_VIA, TERMINAL_LEDGER_KINDS, PRUNABLE_ORPHAN_STALE_REASONS;
7367
+ var init_mesh_active_work = __esm({
7368
+ "src/mesh/mesh-active-work.ts"() {
7369
+ "use strict";
7370
+ init_mesh_ledger();
7371
+ init_mesh_work_queue();
7372
+ init_dist();
7373
+ DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
7374
+ TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
7375
+ PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
7376
+ "direct task node is no longer in the live mesh",
7377
+ "direct task session is not present in live session records",
7378
+ "direct task has no node id"
7379
+ ]);
7380
+ }
7381
+ });
7382
+
6979
7383
  // src/mesh/mesh-events-utils.ts
6980
7384
  function readNonEmptyString2(value) {
6981
7385
  return typeof value === "string" && value.trim() ? value.trim() : "";
@@ -10779,6 +11183,14 @@ var init_chat_message_normalization = __esm({
10779
11183
  });
10780
11184
 
10781
11185
  // src/mesh/mesh-reconcile-loop.ts
11186
+ function resolveAutoPruneMinAgeMs() {
11187
+ const raw = readNonEmptyString2(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
11188
+ if (raw) {
11189
+ const parsed = Number.parseInt(raw, 10);
11190
+ if (Number.isFinite(parsed) && parsed >= 60 * 6e4 && parsed <= 30 * 24 * 60 * 6e4) return parsed;
11191
+ }
11192
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11193
+ }
10782
11194
  function resolveReconcileIntervalMs() {
10783
11195
  const raw = readNonEmptyString2(process.env.MESH_RECONCILE_INTERVAL_MS);
10784
11196
  if (raw) {
@@ -10890,6 +11302,18 @@ async function runMeshReconcileTick(components) {
10890
11302
  LOG.warn("MeshReconcile", `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
10891
11303
  }
10892
11304
  }
11305
+ {
11306
+ const minAgeMs = resolveAutoPruneMinAgeMs();
11307
+ for (const mesh of listMeshes()) {
11308
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
11309
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
11310
+ try {
11311
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
11312
+ } catch (e) {
11313
+ LOG.warn("MeshReconcile", `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
11314
+ }
11315
+ }
11316
+ }
10893
11317
  const coordinators = findLiveCoordinators(components);
10894
11318
  if (coordinators.length === 0) {
10895
11319
  return;
@@ -11072,6 +11496,68 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
11072
11496
  }
11073
11497
  }
11074
11498
  }
11499
+ async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs) {
11500
+ const directDispatches = getActiveDirectDispatches(mesh.id);
11501
+ if (directDispatches.length === 0) return;
11502
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
11503
+ const result = pruneStaleDirectDispatches({
11504
+ meshId: mesh.id,
11505
+ queue: getQueue(mesh.id),
11506
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
11507
+ directDispatches,
11508
+ nodes: liveNodes,
11509
+ execute: true,
11510
+ minAgeMs,
11511
+ source: "daemon_reconcile_auto_prune"
11512
+ });
11513
+ if (result.prunedCount > 0) {
11514
+ LOG.info("MeshReconcile", `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
11515
+ }
11516
+ }
11517
+ async function collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId) {
11518
+ const dispatchMeshCommand = components.dispatchMeshCommand;
11519
+ return Promise.all(mesh.nodes.map(async (node) => {
11520
+ const nodeDaemonId = readNonEmptyString2(node.daemonId);
11521
+ const isLocalNode = !nodeDaemonId || selfIds.includes(nodeDaemonId) || localDaemonId !== void 0 && nodeDaemonId === localDaemonId;
11522
+ let statusResult;
11523
+ try {
11524
+ if (isLocalNode) {
11525
+ statusResult = await components.commandHandler.handle("get_status_metadata", {});
11526
+ } else if (dispatchMeshCommand) {
11527
+ statusResult = await dispatchMeshCommand(nodeDaemonId, "get_status_metadata", {});
11528
+ } else {
11529
+ return node;
11530
+ }
11531
+ } catch {
11532
+ return node;
11533
+ }
11534
+ const sessions = extractStatusMetadataSessions(statusResult);
11535
+ return sessions.length > 0 ? { ...node, sessions } : node;
11536
+ }));
11537
+ }
11538
+ function extractStatusMetadataSessions(raw) {
11539
+ let cursor = raw;
11540
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
11541
+ const record = cursor;
11542
+ const status = record.status && typeof record.status === "object" ? record.status : void 0;
11543
+ if (status && Array.isArray(status.sessions)) return status.sessions;
11544
+ if (Array.isArray(record.sessions)) return record.sessions;
11545
+ if (record.payload && typeof record.payload === "object") {
11546
+ cursor = record.payload;
11547
+ continue;
11548
+ }
11549
+ if (record.result && typeof record.result === "object") {
11550
+ cursor = record.result;
11551
+ continue;
11552
+ }
11553
+ if (record.data && typeof record.data === "object") {
11554
+ cursor = record.data;
11555
+ continue;
11556
+ }
11557
+ break;
11558
+ }
11559
+ return [];
11560
+ }
11075
11561
  function extractPendingEvents(raw) {
11076
11562
  if (Array.isArray(raw)) return raw;
11077
11563
  if (raw && typeof raw === "object") {
@@ -11109,7 +11595,7 @@ function setupMeshReconcileLoop(components) {
11109
11595
  }
11110
11596
  };
11111
11597
  }
11112
- var DEFAULT_RECONCILE_INTERVAL_MS;
11598
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
11113
11599
  var init_mesh_reconcile_loop = __esm({
11114
11600
  "src/mesh/mesh-reconcile-loop.ts"() {
11115
11601
  "use strict";
@@ -11122,9 +11608,12 @@ var init_mesh_reconcile_loop = __esm({
11122
11608
  init_mesh_unresolved_forward_outbox();
11123
11609
  init_mesh_events_utils();
11124
11610
  init_mesh_work_queue();
11611
+ init_mesh_ledger();
11612
+ init_mesh_active_work();
11125
11613
  init_mesh_events_stale();
11126
11614
  init_chat_message_normalization();
11127
11615
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
11616
+ DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
11128
11617
  }
11129
11618
  });
11130
11619
 
@@ -17038,6 +17527,7 @@ __export(index_exports, {
17038
17527
  prepareSessionChatTailUpdate: () => prepareSessionChatTailUpdate,
17039
17528
  prepareSessionModalUpdate: () => prepareSessionModalUpdate,
17040
17529
  probeCdpPort: () => probeCdpPort,
17530
+ pruneStaleDirectDispatches: () => pruneStaleDirectDispatches,
17041
17531
  queuePendingMeshCoordinatorEvent: () => queuePendingMeshCoordinatorEvent,
17042
17532
  readAntigravityCliSession: () => readSession3,
17043
17533
  readCachedInlineMeshActiveSessionDetails: () => readCachedInlineMeshActiveSessionDetails,
@@ -19440,331 +19930,7 @@ function buildMeshLedgerReconciliationEvidence(meshId, replicas) {
19440
19930
 
19441
19931
  // src/index.ts
19442
19932
  init_mesh_work_queue();
19443
-
19444
- // src/mesh/mesh-active-work.ts
19445
- init_dist();
19446
- var DIRECT_DISPATCH_VIA = /* @__PURE__ */ new Set(["p2p_direct", "local_direct", "mesh_send_task"]);
19447
- var TERMINAL_LEDGER_KINDS = /* @__PURE__ */ new Set(["task_completed", "task_failed", "task_stalled"]);
19448
- function readString6(value) {
19449
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
19450
- }
19451
- function summarizeMessage(message) {
19452
- const oneLine2 = message.replace(/\s+/g, " ").trim();
19453
- const title = oneLine2.length > 96 ? `${oneLine2.slice(0, 93)}...` : oneLine2;
19454
- return { title: title || "(untitled task)", summary: oneLine2 };
19455
- }
19456
- function elapsedSince(value, now) {
19457
- const started = value ? new Date(value).getTime() : Number.NaN;
19458
- return Number.isFinite(started) ? Math.max(0, now - started) : 0;
19459
- }
19460
- function sessionStatusFromNodes(nodes, nodeId, sessionId) {
19461
- if (!Array.isArray(nodes)) return {};
19462
- if (!nodeId) return { staleReason: "direct task has no node id" };
19463
- const node = nodes.find((item) => meshNodeIdMatches(item, nodeId));
19464
- if (!node) return { staleReason: "direct task node is no longer in the live mesh" };
19465
- if (!sessionId) return {};
19466
- const candidates = [];
19467
- for (const value of [
19468
- node.sessions,
19469
- node.activeSessions,
19470
- node.active_sessions,
19471
- node.activeSessionDetails,
19472
- node.active_session_details,
19473
- node.sessionDetails,
19474
- node.session_details,
19475
- node.lastProbe?.sessions,
19476
- node.last_probe?.sessions,
19477
- node.lastProbe?.status?.sessions,
19478
- node.last_probe?.status?.sessions
19479
- ]) {
19480
- if (Array.isArray(value)) candidates.push(...value);
19481
- }
19482
- for (const value of [node.activeSession, node.active_session, node.currentSession, node.current_session, node.runtimeSession, node.runtime_session, node.session]) {
19483
- if (value && typeof value === "object") candidates.push(value);
19484
- }
19485
- const session = candidates.find((item) => {
19486
- if (typeof item === "string") return item === sessionId;
19487
- const id = readString6(item?.id) || readString6(item?.sessionId) || readString6(item?.session_id) || readString6(item?.runtimeSessionId) || readString6(item?.instanceId);
19488
- return id === sessionId;
19489
- });
19490
- if (!session) return { staleReason: "direct task session is not present in live session records" };
19491
- if (typeof session === "string") return {};
19492
- const raw = `${readString6(session.status) || ""} ${readString6(session.lifecycle) || ""} ${readString6(session.state) || ""} ${readString6(session.activeChat?.status) || ""}`.toLowerCase();
19493
- if (raw.includes("approval")) return { status: "awaiting_approval" };
19494
- if (raw.includes("generating") || raw.includes("running") || raw.includes("busy")) return { status: "generating" };
19495
- if (raw.includes("failed") || raw.includes("stopped") || raw.includes("terminated") || raw.includes("exited")) return { status: "failed" };
19496
- if (raw.includes("idle") || raw.includes("waiting_input") || raw.includes("ready")) return { status: "idle" };
19497
- return {};
19498
- }
19499
- function isDirectDispatch(entry) {
19500
- if (entry.kind !== "task_dispatched") return false;
19501
- const payload = entry.payload || {};
19502
- if (payload.source === "direct") return true;
19503
- const via = readString6(payload.via);
19504
- return Boolean(via && DIRECT_DISPATCH_VIA.has(via) && payload.source !== "queue");
19505
- }
19506
- function directDispatchTaskId(entry) {
19507
- return readString6(entry.payload?.taskId) || entry.id;
19508
- }
19509
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
19510
- const terminalTaskId = readString6(terminal.payload?.taskId);
19511
- if (terminalTaskId && terminalTaskId === taskId) return true;
19512
- if (terminalTaskId && terminalTaskId !== taskId) return false;
19513
- if (dispatch.sessionId && terminal.sessionId === dispatch.sessionId) return true;
19514
- return Boolean(dispatch.nodeId && terminal.nodeId === dispatch.nodeId && !dispatch.sessionId);
19515
- }
19516
- function statusFromTerminal(entry) {
19517
- if (entry.kind === "task_approval_needed") return "awaiting_approval";
19518
- if (entry.kind === "task_completed") return "idle";
19519
- return "failed";
19520
- }
19521
- function buildMeshActiveWorkSummary(activeWork) {
19522
- const statusCounts = {
19523
- pending: 0,
19524
- assigned: 0,
19525
- generating: 0,
19526
- idle: 0,
19527
- failed: 0,
19528
- awaiting_approval: 0
19529
- };
19530
- const sourceCounts = { queue: 0, direct: 0 };
19531
- for (const item of activeWork) {
19532
- sourceCounts[item.source] += 1;
19533
- statusCounts[item.status] += 1;
19534
- }
19535
- const staleDirectCount = activeWork.filter((item) => item.source === "direct" && item.staleReason).length;
19536
- const staleDirectUnacknowledgedCount = activeWork.filter((item) => item.source === "direct" && item.staleDispatchUnacknowledged).length;
19537
- return {
19538
- totalActiveCount: activeWork.length,
19539
- queueActiveCount: sourceCounts.queue,
19540
- directActiveCount: sourceCounts.direct,
19541
- awaitingApprovalCount: statusCounts.awaiting_approval,
19542
- generatingCount: statusCounts.generating,
19543
- failedCount: statusCounts.failed,
19544
- idleCount: statusCounts.idle,
19545
- sourceCounts,
19546
- statusCounts,
19547
- staleDirectCount,
19548
- ...staleDirectUnacknowledgedCount > 0 ? { staleDirectUnacknowledgedCount } : {},
19549
- ...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." } : {}
19550
- };
19551
- }
19552
- function buildMeshActiveWork(opts) {
19553
- const now = opts.now ?? Date.now();
19554
- const records = [];
19555
- const staleDirectWork = [];
19556
- const terminalDirectWork = [];
19557
- for (const task of opts.queue || []) {
19558
- if (task.status !== "pending" && task.status !== "assigned") continue;
19559
- const { title, summary: summary2 } = summarizeMessage(task.message || "");
19560
- records.push({
19561
- taskId: task.id,
19562
- source: "queue",
19563
- status: task.status,
19564
- nodeId: task.assignedNodeId || task.targetNodeId,
19565
- sessionId: task.assignedSessionId || task.targetSessionId,
19566
- taskTitle: title,
19567
- taskSummary: summary2,
19568
- message: task.message,
19569
- taskMode: task.taskMode,
19570
- createdAt: task.createdAt,
19571
- updatedAt: task.updatedAt,
19572
- dispatchedAt: task.dispatchTimestamp,
19573
- elapsedMs: elapsedSince(task.dispatchTimestamp || task.createdAt, now)
19574
- });
19575
- }
19576
- if (opts.directDispatches !== void 0) {
19577
- const dbTaskIds = new Set(opts.directDispatches.map((d) => d.taskId));
19578
- for (const dispatch of opts.directDispatches) {
19579
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId ?? void 0, dispatch.sessionId ?? void 0);
19580
- const dbStatus = dispatch.status;
19581
- const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
19582
- const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : live.status || (dbStatus === "acked" ? "generating" : "assigned");
19583
- const isNoTransition = !isTerminal && !live.status;
19584
- const isIdleUnacknowledged = status === "idle" && !isTerminal;
19585
- const ledgerOnlyStaleReason = !isTerminal && (isIdleUnacknowledged || isNoTransition || dispatch.dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19586
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19587
- const { title, summary: summary2 } = summarizeMessage(dispatch.message || "");
19588
- const record = {
19589
- taskId: dispatch.taskId,
19590
- source: "direct",
19591
- status,
19592
- nodeId: dispatch.nodeId ?? void 0,
19593
- sessionId: dispatch.sessionId ?? void 0,
19594
- providerType: dispatch.providerType ?? void 0,
19595
- taskTitle: title,
19596
- taskSummary: summary2,
19597
- message: dispatch.message,
19598
- taskMode: dispatch.taskMode ?? void 0,
19599
- createdAt: dispatch.dispatchedAt,
19600
- updatedAt: dispatch.updatedAt,
19601
- dispatchedAt: dispatch.dispatchedAt,
19602
- elapsedMs: elapsedSince(dispatch.dispatchedAt, now),
19603
- terminal: isTerminal,
19604
- terminalKind: isTerminal ? dbStatus === "completed" ? "task_completed" : "task_failed" : void 0,
19605
- terminalAt: isTerminal ? dispatch.updatedAt : void 0,
19606
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19607
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19608
- };
19609
- if (isTerminal) {
19610
- terminalDirectWork.push(record);
19611
- if (opts.includeTerminalDirect !== true) continue;
19612
- }
19613
- if ((live.staleReason || ledgerOnlyStaleReason) && !isTerminal) {
19614
- staleDirectWork.push(record);
19615
- continue;
19616
- }
19617
- records.push(record);
19618
- }
19619
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19620
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19621
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19622
- const taskId = directDispatchTaskId(dispatch);
19623
- if (dbTaskIds.has(taskId)) continue;
19624
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19625
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19626
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19627
- const status = terminalStatus || live.status || "assigned";
19628
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19629
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19630
- const isNoTransition = !terminalStatus && !live.status;
19631
- const isIdleUnacknowledged = status === "idle";
19632
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19633
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19634
- const { title, summary: summary2 } = summarizeMessage(message);
19635
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19636
- const record = {
19637
- taskId,
19638
- source: "direct",
19639
- status,
19640
- nodeId: dispatch.nodeId,
19641
- sessionId: dispatch.sessionId,
19642
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19643
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19644
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19645
- message,
19646
- taskMode: readString6(dispatch.payload?.taskMode),
19647
- createdAt: dispatch.timestamp,
19648
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19649
- dispatchedAt: dispatch.timestamp,
19650
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19651
- terminal: terminalRow,
19652
- terminalKind: terminal?.kind,
19653
- terminalAt: terminal?.timestamp,
19654
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19655
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19656
- };
19657
- if (terminalRow) {
19658
- terminalDirectWork.push(record);
19659
- if (opts.includeTerminalDirect !== true) continue;
19660
- }
19661
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19662
- staleDirectWork.push(record);
19663
- continue;
19664
- }
19665
- records.push(record);
19666
- }
19667
- } else {
19668
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
19669
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
19670
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
19671
- const taskId = directDispatchTaskId(dispatch);
19672
- const terminal = terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).find((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
19673
- const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
19674
- const live = sessionStatusFromNodes(opts.nodes, dispatch.nodeId, dispatch.sessionId);
19675
- const status = terminalStatus || live.status || "assigned";
19676
- const terminalRow = Boolean(terminal && terminal.kind !== "task_approval_needed");
19677
- const dispatchedToIdleSession = dispatch.payload?.dispatchedToIdleSession === true;
19678
- const isNoTransition = !terminalStatus && !live.status;
19679
- const isIdleUnacknowledged = status === "idle";
19680
- const ledgerOnlyStaleReason = !terminalRow && (isIdleUnacknowledged || isNoTransition || dispatchedToIdleSession && isIdleUnacknowledged) ? "direct task dispatch has no provider acknowledgement, transcript append, or active runtime transition" : void 0;
19681
- const message = readString6(dispatch.payload?.message) || readString6(dispatch.payload?.summary) || "";
19682
- const { title, summary: summary2 } = summarizeMessage(message);
19683
- const isFreshUnacknowledged = Boolean(ledgerOnlyStaleReason && !live.staleReason);
19684
- const record = {
19685
- taskId,
19686
- source: "direct",
19687
- status,
19688
- nodeId: dispatch.nodeId,
19689
- sessionId: dispatch.sessionId,
19690
- providerType: dispatch.providerType || readString6(dispatch.payload?.providerType),
19691
- taskTitle: readString6(dispatch.payload?.taskTitle) || title,
19692
- taskSummary: readString6(dispatch.payload?.taskSummary) || summary2,
19693
- message,
19694
- taskMode: readString6(dispatch.payload?.taskMode),
19695
- createdAt: dispatch.timestamp,
19696
- updatedAt: terminal?.timestamp || dispatch.timestamp,
19697
- dispatchedAt: dispatch.timestamp,
19698
- elapsedMs: elapsedSince(dispatch.timestamp, now),
19699
- terminal: terminalRow,
19700
- terminalKind: terminal?.kind,
19701
- terminalAt: terminal?.timestamp,
19702
- staleReason: live.staleReason || ledgerOnlyStaleReason,
19703
- ...isFreshUnacknowledged ? { staleDispatchUnacknowledged: true } : {}
19704
- };
19705
- if (terminalRow) {
19706
- terminalDirectWork.push(record);
19707
- if (opts.includeTerminalDirect !== true) continue;
19708
- }
19709
- if ((live.staleReason || ledgerOnlyStaleReason) && !terminalRow) {
19710
- staleDirectWork.push(record);
19711
- continue;
19712
- }
19713
- records.push(record);
19714
- }
19715
- }
19716
- records.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19717
- staleDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19718
- terminalDirectWork.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
19719
- const summary = buildMeshActiveWorkSummary(records);
19720
- summary.staleDirectCount = staleDirectWork.length;
19721
- const unacknowledgedCount = staleDirectWork.filter((r) => r.staleDispatchUnacknowledged).length;
19722
- if (unacknowledgedCount > 0) {
19723
- summary.staleDirectUnacknowledgedCount = unacknowledgedCount;
19724
- }
19725
- 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;
19726
- if (staleDirectWorkNote) {
19727
- summary.staleDirectNote = staleDirectWorkNote;
19728
- }
19729
- return { activeWork: records, staleDirectWork, staleDirectWorkNote, terminalDirectWork, summary };
19730
- }
19731
- var PRUNABLE_ORPHAN_STALE_REASONS = /* @__PURE__ */ new Set([
19732
- "direct task node is no longer in the live mesh",
19733
- "direct task session is not present in live session records",
19734
- "direct task has no node id"
19735
- ]);
19736
- function classifyStaleDirectForPrune(record, opts = {}) {
19737
- if (record.staleDispatchUnacknowledged === true) return "preserve_unacknowledged";
19738
- if (record.terminal === true) return opts.includeTerminal ? "prunable_terminal" : "preserve_active";
19739
- if (record.staleReason && PRUNABLE_ORPHAN_STALE_REASONS.has(record.staleReason)) return "prunable_orphan";
19740
- return "preserve_active";
19741
- }
19742
- function buildCompactStaleDirectWorkSummary(staleDirectWork, opts = {}) {
19743
- const sampleLimit = Math.max(0, Math.min(10, Math.floor(opts.sampleLimit ?? 3)));
19744
- const reasonCounts = {};
19745
- for (const entry of staleDirectWork) {
19746
- const reason = entry.staleReason || "unknown";
19747
- reasonCounts[reason] = (reasonCounts[reason] || 0) + 1;
19748
- }
19749
- return {
19750
- count: staleDirectWork.length,
19751
- sampleLimit,
19752
- sample: staleDirectWork.slice(0, sampleLimit).map((entry) => ({
19753
- taskId: entry.taskId,
19754
- status: entry.status,
19755
- nodeId: entry.nodeId,
19756
- sessionId: entry.sessionId,
19757
- taskTitle: entry.taskTitle,
19758
- createdAt: entry.createdAt,
19759
- staleReason: entry.staleReason
19760
- })),
19761
- reasonCounts,
19762
- 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.",
19763
- ...opts.note ? { note: opts.note } : {}
19764
- };
19765
- }
19766
-
19767
- // src/index.ts
19933
+ init_mesh_active_work();
19768
19934
  init_mesh_refine_status();
19769
19935
  init_mesh_host_ownership();
19770
19936
  init_mesh_events();
@@ -59166,6 +59332,7 @@ var V1_CONTRACT_VERSION = "1.0.0";
59166
59332
  prepareSessionChatTailUpdate,
59167
59333
  prepareSessionModalUpdate,
59168
59334
  probeCdpPort,
59335
+ pruneStaleDirectDispatches,
59169
59336
  queuePendingMeshCoordinatorEvent,
59170
59337
  readAntigravityCliSession,
59171
59338
  readCachedInlineMeshActiveSessionDetails,