@adhdev/daemon-core 0.9.82-rc.292 → 0.9.82-rc.293

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.
@@ -37,6 +37,23 @@ export interface MeshMissionTaskAggregate {
37
37
  export interface MeshMissionSummary extends MeshMissionRecord {
38
38
  tasks: MeshMissionTaskAggregate;
39
39
  }
40
+ /**
41
+ * Slim mission summary for the mesh_status compact (default) surface. Drops the
42
+ * full `goal` text — which can be hundreds of chars per mission and is repeated
43
+ * for every mission on every status call — keeping only a short preview plus a
44
+ * `goalTruncated` flag when the original was longer. The stored goal is never
45
+ * mutated; this is an output-only projection. Coordinators that need the full
46
+ * goal call mesh_status with verbose=true, or read the mission directly via
47
+ * mesh_mission_upsert / getMeshMission.
48
+ */
49
+ export interface MeshMissionSlimSummary extends Omit<MeshMissionSummary, 'goal'> {
50
+ /** Short preview of the goal (≤ GOAL_PREVIEW_MAX chars), '' when goal empty. */
51
+ goalPreview: string;
52
+ /** True when the stored goal was longer than the preview (full text elided). */
53
+ goalTruncated: boolean;
54
+ }
55
+ /** Max chars of goal text retained in the slim (compact) mission summary. */
56
+ export declare const GOAL_PREVIEW_MAX = 120;
40
57
  export declare function upsertMeshMission(meshId: string, input: {
41
58
  id?: string;
42
59
  title: string;
@@ -56,10 +73,17 @@ export declare function getActiveMeshMissionSummaries(meshId: string): MeshMissi
56
73
  * the dashboard can render a collapsible "history" section without unbounded
57
74
  * payload growth. Returned newest-first within each group (active/paused first,
58
75
  * then history), so the frontend can split on `status` directly.
76
+ *
77
+ * Compact mode (the default) elides each mission's full `goal` text — which is
78
+ * repeated verbatim on every status poll and dominates the payload when a mesh
79
+ * has many missions — returning only a short `goalPreview` + `goalTruncated`
80
+ * flag. Pass `verbose: true` to get the full `goal` text per mission. The stored
81
+ * goal is untouched in both modes; this is an output-only projection.
59
82
  */
60
83
  export declare function getMeshStatusMissionSummaries(meshId: string, options?: {
61
84
  historyLimit?: number;
62
- }): MeshMissionSummary[];
85
+ verbose?: boolean;
86
+ }): MeshMissionSummary[] | MeshMissionSlimSummary[];
63
87
  /**
64
88
  * M3-3: render active missions as a prompt section for {{mission}}.
65
89
  * Empty string when no active mission — the prompt stays byte-identical to
@@ -342,4 +342,19 @@ export declare class MeshRuntimeStore {
342
342
  /** Remove all pending-event rows (drained included) for a mesh — mesh deletion / test cleanup. */
343
343
  clearPendingEventsForMesh(meshId: string): number;
344
344
  pendingEventCount(meshId: string): number;
345
+ /**
346
+ * Mark specific pending-event rows drained by id (ack). Used by the
347
+ * unresolved-delegate durable-forward outbox: an event is peeked (not drained)
348
+ * while its push to the coordinator is unconfirmed, then marked drained ONLY
349
+ * after the push is acked. A failed push leaves the row undrained so the next
350
+ * reconcile tick retries it. Returns the number of rows newly marked drained.
351
+ */
352
+ markPendingEventsDrainedById(ids: ReadonlyArray<string>): number;
353
+ /**
354
+ * Hard-delete pending-event rows by id (including the dedup fingerprint history).
355
+ * Used to expire an unresolved-delegate outbox entry that has exhausted its retry
356
+ * budget — fully removing it frees the fingerprint so a genuinely new completion
357
+ * for the same task could be re-queued later. Returns the number of rows deleted.
358
+ */
359
+ deletePendingEventsById(ids: ReadonlyArray<string>): number;
345
360
  }
@@ -0,0 +1,30 @@
1
+ export declare const UNRESOLVED_FORWARD_OUTBOX_MESH_ID = "__unresolved_forward_outbox__";
2
+ export interface UnresolvedForwardEntry {
3
+ /** Row id in mesh_pending_events; pass back to ack/expire after a push attempt. */
4
+ id: string;
5
+ /** The coordinator daemon to push this event to (mesh_forward_event target). */
6
+ coordinatorDaemonId: string;
7
+ /** The flat payload to forward (already shaped for handleMeshForwardEvent). */
8
+ payload: Record<string, unknown>;
9
+ /** When the entry was first enqueued (epoch ms) — used for age-based expiry. */
10
+ queuedAt: number;
11
+ }
12
+ /**
13
+ * Durably enqueue an unresolved-delegate forward for a coordinator daemon. The
14
+ * `forwardPayload` is the flat shape handleMeshForwardEvent reads on the coordinator.
15
+ * Idempotent on the event fingerprint. Returns true when a new row was written (or a
16
+ * duplicate was harmlessly ignored), false on a hard persistence failure.
17
+ */
18
+ export declare function enqueueUnresolvedDelegateForward(coordinatorDaemonId: string, eventName: string, forwardPayload: Record<string, unknown>): boolean;
19
+ /** Peek (non-destructive) every undrained outbox entry across all coordinators. */
20
+ export declare function peekUnresolvedDelegateForwards(): UnresolvedForwardEntry[];
21
+ /** Mark an outbox entry delivered (acked) after a successful push. */
22
+ export declare function ackUnresolvedDelegateForward(id: string): void;
23
+ /**
24
+ * Drop outbox entries that have exceeded the max retry age. Returns the count
25
+ * expired so the caller can log a fail-loud trace (a dropped completion is a real
26
+ * loss; it must be visible, not silent).
27
+ */
28
+ export declare function expireStaleUnresolvedDelegateForwards(nowMs?: number): number;
29
+ /** Test helper: purge the entire outbox. */
30
+ export declare function __clearUnresolvedDelegateForwardOutboxForTests(): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "0.9.82-rc.292",
3
+ "version": "0.9.82-rc.293",
4
4
  "description": "ADHDev daemon core — CDP, IDE detection, providers, command execution",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -46,7 +46,7 @@
46
46
  "author": "vilmire",
47
47
  "license": "AGPL-3.0-or-later",
48
48
  "dependencies": {
49
- "@adhdev/mesh-shared": "0.9.82-rc.292",
49
+ "@adhdev/mesh-shared": "0.9.82-rc.293",
50
50
  "@adhdev/session-host-core": "*",
51
51
  "@agentclientprotocol/sdk": "^0.16.1",
52
52
  "ajv": "^8.20.0",
@@ -8267,6 +8267,13 @@ export class DaemonCommandRouter {
8267
8267
  const meshHost = resolveMeshHostStatus(mesh);
8268
8268
 
8269
8269
  const refreshRequested = args?.refresh === true || args?.forceRefresh === true;
8270
+ // Compact (default) elides each mission's full goal text from the
8271
+ // payload — coordinators polling node health don't need every
8272
+ // mission's multi-hundred-char goal repeated. verbose=true (or the
8273
+ // explicit compact=false) restores full goals. Verbose bypasses the
8274
+ // shared (compact) aggregate cache so a verbose call never poisons
8275
+ // the compact cache and vice versa.
8276
+ const verboseMissions = args?.verbose === true || args?.compact === false;
8270
8277
  // See (B3) below: scope the peek to this daemon when the
8271
8278
  // caller doesn't tell us, otherwise scoped events look
8272
8279
  // missing and we falsely return a stale cache.
@@ -8275,7 +8282,7 @@ export class DaemonCommandRouter {
8275
8282
  : (this.deps.statusInstanceId || undefined);
8276
8283
  const pendingCoordinatorEventCount = getPendingMeshCoordinatorEvents(meshId, peekScope).length;
8277
8284
  const hadAggregateCache = this.aggregateMeshStatusCache.has(meshId);
8278
- if (!refreshRequested && pendingCoordinatorEventCount === 0) {
8285
+ if (!refreshRequested && !verboseMissions && pendingCoordinatorEventCount === 0) {
8279
8286
  const cachedStatus = this.getCachedAggregateMeshStatus(meshId, mesh, { requireDirectPeerTruth: args?.requireDirectPeerTruth === true });
8280
8287
  if (cachedStatus) {
8281
8288
  logRepoMeshStatusDebug('return_cached', {
@@ -8649,7 +8656,7 @@ export class DaemonCommandRouter {
8649
8656
  liveSessionRecords: liveMeshSessions,
8650
8657
  });
8651
8658
  const { getMeshStatusMissionSummaries } = await import('../mesh/mesh-missions.js');
8652
- const missions = getMeshStatusMissionSummaries(meshId);
8659
+ const missions = getMeshStatusMissionSummaries(meshId, { verbose: verboseMissions });
8653
8660
  const statusResult = {
8654
8661
  success: true,
8655
8662
  meshId: mesh.id,
@@ -8709,7 +8716,12 @@ export class DaemonCommandRouter {
8709
8716
  })),
8710
8717
  };
8711
8718
  const { pendingCoordinatorEvents: _pendingCoordinatorEvents, unroutableDeliveries: _unroutableDeliveries, ...cacheableStatusResult } = statusResult as any;
8712
- const rememberedStatus = this.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
8719
+ // Verbose carries full mission goals; never store it in the shared
8720
+ // (compact) aggregate cache or a later compact poll would return the
8721
+ // heavy goals from cache. Return it without caching.
8722
+ const rememberedStatus = verboseMissions
8723
+ ? cacheableStatusResult
8724
+ : this.rememberAggregateMeshStatus(meshId, cacheableStatusResult, refreshReason);
8713
8725
  const returnedStatus = {
8714
8726
  ...rememberedStatus,
8715
8727
  ...(pendingCoordinatorEvents.length > 0 ? { pendingCoordinatorEvents } : {}),
@@ -143,11 +143,39 @@ const WEB_ONLY_PACKAGES = new Set([
143
143
  'terminal-render-web',
144
144
  ]);
145
145
 
146
+ /**
147
+ * Root-level (non-package) files that demonstrably cannot change what the daemon
148
+ * runtime executes: convergence/verify markers, documentation, and license/notice
149
+ * text. A root commit that moves the oss gitlink while the oss commit only touched
150
+ * one of these is NOT a reason to rebuild/restart the daemon — flagging it produces
151
+ * the staleDaemonBuild false-positive this guard exists to suppress.
152
+ *
153
+ * Deliberately conservative: anything NOT matched here (root config like
154
+ * package.json / tsconfig / build scripts, `.txt` fixtures, lockfiles, unknown
155
+ * dotfiles) stays daemon-affecting, because a false-negative — staying silent when
156
+ * the daemon really IS stale — is worse than an over-warn. Markers are the common
157
+ * real-world case (e.g. `.verify-patch-equiv-rc292`), so they are matched broadly;
158
+ * docs are matched by the `docs/` prefix or a markdown/text-doc extension at a
159
+ * filename we recognize as documentation (README/CHANGELOG/LICENSE/NOTICE).
160
+ */
161
+ function isNonRuntimeRootFile(file: string): boolean {
162
+ const base = file.slice(file.lastIndexOf('/') + 1);
163
+ // Verify/convergence markers: dotfiles whose name signals a transient marker.
164
+ if (/^\.(?:verify|marker|converge|ff-verify|patch-equiv|live-verify)\b/i.test(base)) return true;
165
+ // Documentation living under a docs/ tree (any depth, root or nested).
166
+ if (/(?:^|\/)docs\//i.test(file)) return true;
167
+ // Recognized top-level documentation / license files.
168
+ if (/^(?:README|CHANGELOG|LICENSE|NOTICE|AUTHORS|CONTRIBUTING|CODEOWNERS)(?:\.[A-Za-z0-9]+)?$/i.test(base)) {
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+
146
174
  /**
147
175
  * Determine whether the changes between buildCommit..HEAD touch any daemon-runtime
148
176
  * package. Returns isDaemonAffecting:true conservatively when the changed-file set
149
177
  * can't be obtained or any changed path is outside the known web-only package set
150
- * (including root-level / non-package files).
178
+ * AND is not a recognized non-runtime root file (marker/doc/license).
151
179
  */
152
180
  async function classifyDaemonBuildChange(
153
181
  repoPath: string,
@@ -166,24 +194,28 @@ async function classifyDaemonBuildChange(
166
194
  return { isDaemonAffecting: true, affectedPackages: [] };
167
195
  }
168
196
  const pkgs = new Set<string>();
169
- let sawNonPackageOrUnknown = false;
197
+ // A non-package path that is NOT a recognized benign root file (marker/doc).
198
+ // Only these force daemon-affecting; benign markers/docs are ignored so a
199
+ // gitlink-moving root commit over a marker-only oss commit no longer over-warns.
200
+ let sawRuntimeAmbiguousNonPackage = false;
170
201
  for (const file of files) {
171
202
  const match = file.match(/(?:^|\/)packages\/([^/]+)\//);
172
203
  if (!match) {
173
- sawNonPackageOrUnknown = true;
204
+ if (!isNonRuntimeRootFile(file)) sawRuntimeAmbiguousNonPackage = true;
174
205
  continue;
175
206
  }
176
207
  pkgs.add(match[1]);
177
208
  }
178
209
  const affectedPackages = [...pkgs].sort();
179
- // Daemon-affecting if: any non-package/root file changed, any unknown package
180
- // changed, or any explicit daemon-runtime package changed. Only when EVERY
181
- // changed file maps to a known web-only package is the daemon unaffected.
182
- const allWebOnly =
183
- !sawNonPackageOrUnknown &&
184
- affectedPackages.length > 0 &&
210
+ // Daemon-affecting if: any runtime-ambiguous non-package file changed, any
211
+ // unknown package changed, or any explicit daemon-runtime package changed.
212
+ // The daemon is unaffected only when every changed file is either a known
213
+ // web-only package or a recognized benign root file (and at least one such
214
+ // file changed) — i.e. nothing runtime-ambiguous remains.
215
+ const allBenign =
216
+ !sawRuntimeAmbiguousNonPackage &&
185
217
  affectedPackages.every((p) => WEB_ONLY_PACKAGES.has(p) && !DAEMON_RUNTIME_PACKAGES.has(p));
186
- return { isDaemonAffecting: !allWebOnly, affectedPackages };
218
+ return { isDaemonAffecting: !allBenign, affectedPackages };
187
219
  } catch {
188
220
  // diff probe failed → can't prove web-only; stay conservative.
189
221
  return { isDaemonAffecting: true, affectedPackages: [] };
@@ -229,11 +261,14 @@ async function detectDaemonBuildBehind(
229
261
  options,
230
262
  );
231
263
  const scopeLabel = scope === 'root' ? 'workspace' : scope;
264
+ const benignDetail = affectedPackages.length > 0
265
+ ? `only web packages changed (${affectedPackages.join(', ')})`
266
+ : 'only non-runtime files changed (markers/docs)';
232
267
  const warning = isDaemonAffecting
233
268
  ? `Live daemon was built from ${build.commitShort} which is behind ${scopeLabel} HEAD ${head.slice(0, 7)}. ` +
234
269
  `Merged code is NOT live until the daemon is rebuilt/redeployed and restarted — a local dist rebuild alone does not update a cloud daemon.`
235
270
  : `Live daemon was built from ${build.commitShort} which is behind ${scopeLabel} HEAD ${head.slice(0, 7)}, ` +
236
- `but only web packages changed (${(affectedPackages || []).join(', ') || 'web'}). ` +
271
+ `but ${benignDetail}. ` +
237
272
  `Daemon restart NOT required — redeploy the web app to reflect the change.`;
238
273
  return {
239
274
  buildCommit: build.commit,
@@ -350,7 +350,7 @@ const WORKFLOW_SECTION = `## Orchestration Workflow
350
350
  c. **Targeted Tasks**: Use \`mesh_send_task\` only when you need to bypass the queue and force a specific node to execute a task immediately.
351
351
  d. For the first dispatch of a new task, provide a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.
352
352
  e. For a continuation of the same issue in an existing session, send a concise **delta instruction**: current verified state, the exact failed/blocked step, the newly approved action, and final reporting requirements. Do not resend the full original task or open a new chat solely to continue the same work; that wastes coordinator and worker context.
353
- 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Do **not** repeatedly call \`mesh_status\` or \`mesh_view_queue\` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for \`pendingCoordinatorEvents\` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact \`mesh_read_chat\` check after a terminal signal. Handle approvals via \`mesh_approve\`.
353
+ 4. **Monitor** — Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Do **not** repeatedly call \`mesh_status\` or \`mesh_view_queue\` just to wait for assigned/generating work. After dispatching a direct or queued task, send one progress update with the task/session handle, then stop. Wait for \`pendingCoordinatorEvents\` or another completion/approval/status signal, an explicit user status request, or a real timeout/stall signal before reading status/chat/queue again. Use at most one compact \`mesh_read_chat\` check after a terminal signal. Handle approvals via \`mesh_approve\`. **Proactively parallelize new work.** When the user reports a new bug or asks for new work, start it immediately if it is independent of in-flight tasks and there is headroom under \`maxParallelTasks\` — do not wait for a current task to finish or for the user to prompt you to parallelize. Read-only diagnosis (\`live_debug_readonly\`) has no isolation or merge cost, so dispatch it in parallel right away. The no-polling / concurrency-limit rules constrain *re-checking or duplicating already-dispatched work*; they are **not** a reason to defer starting a new, independent task.
354
354
  5. **Verify** — When a task reports completion or git work is visible, call \`mesh_git_status\` to verify changes were made.
355
355
  6. **Checkpoint** — Call \`mesh_checkpoint\` to save the work.
356
356
  7. **Converge branches** — Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary. For obvious clean branch catch-up (ahead 0, behind > 0, upstream fresh, no dirty/stash/submodule issues), use \`mesh_fast_forward_node\` dry-run first and execute only when explicitly safe/approved; this avoids consuming an agent session. Use \`mesh_refine_node\` for clean worktree branches when safe. Before/refine merging root commits that contain submodule gitlink changes, require each submodule commit to be reachable from the configured submodule remote main branch, not merely present on a feature ref or local checkout. If \`mesh_refine_node\` returns \`submodule_reachability_failed\` or publish-required evidence, keep the public convergence bucket as \`blocked_review\`; unless \`allowAutoPublishSubmoduleMainCommits\` is explicitly enabled and Refinery reports successful non-force publish plus post-publish verification, ask the user for explicit approval to push/publish the unreachable submodule commit(s) to submodule main, then rerun \`mesh_refine_node\`. Do not merge the root branch until the submodule commit(s) are reachable from submodule origin/main. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
@@ -382,7 +382,7 @@ function buildRulesSection(coordinatorCliType?: string): string {
382
382
  - **Reuse idle sessions.** For follow-up, retry, commit/push, or cleanup on the same issue, send only the delta to the existing idle session. Start fresh only for independent work, provider mismatch, transcript contamination, or required worktree isolation.
383
383
  - **Respect explicit provider requests.** Map: Hermes → \`hermes-cli\`, Claude/Claude Code → \`claude-cli\`, Codex → \`codex-cli\`, Gemini → \`gemini-cli\`, Antigravity → \`antigravity-cli\`. Never substitute the coordinator's own runtime.
384
384
  - **Verify via git, not source.** Use \`mesh_git_status\` to confirm side effects. Treat agent summaries as self-reports, not verification.
385
- - **Limit parallelism.** Start with 1–2 tasks; scale only on success. Never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing.
385
+ - **Limit parallelism.** Start with 1–2 tasks; scale only on success. Never duplicate a session because \`mesh_read_chat\` shows no final message while tool/terminal activity is ongoing. This caps *concurrent* load — it does not mean serialize independent work: when a new, independent request arrives and there is headroom under \`maxParallelTasks\`, dispatch it right away rather than waiting for an in-flight task or a user nudge (read-only diagnosis especially, since it has no merge cost).
386
386
  - **Check history first.** Call \`mesh_task_history\` at session start to avoid duplicate work and inform recovery. On failure, read task history before retrying.
387
387
  - **Converge branches.** After worktree tasks: refine/fast-forward, or classify as \`pushed_feature_branch_needs_merge\` / \`blocked_review\` / \`cleanup_candidate\` / \`not_mergeable\`. Clean up with \`mesh_remove_node\`.
388
388
  - **Refinery is config-driven.** \`mesh_refine_node\` must run validation from \`.adhdev/refine.{json,yaml,yml}\` or \`repo-mesh.refine.*\`. Heuristics are scaffolding only.
@@ -13,6 +13,7 @@ import { MeshRuntimeStore } from './mesh-runtime-store.js';
13
13
  import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
14
14
  import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
15
15
  import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent, isUnroutableDelegateRejection } from './mesh-routing.js';
16
+ import { enqueueUnresolvedDelegateForward, peekUnresolvedDelegateForwards, ackUnresolvedDelegateForward } from './mesh-unresolved-forward-outbox.js';
16
17
  import { resolveDelegatedWorkerAutoApprove } from '../repo-mesh-types.js';
17
18
  import { normalizeMeshNodeId, meshNodeIdMatches } from '@adhdev/mesh-shared';
18
19
  import {
@@ -1539,8 +1540,16 @@ export function handleMeshForwardEvent(components: DaemonComponents, payload: Re
1539
1540
  // - It fires only when the normal queue path did NOT run (isDelegate=false), so the
1540
1541
  // event is never both queued locally and forwarded.
1541
1542
  //
1542
- // Returns true when the event was handed off to the coordinator daemon (so the caller
1543
- // skips the delivery_unroutable diagnostic); false when no fallback was possible.
1543
+ // Returns true when the event was durably accepted for delivery to the coordinator
1544
+ // daemon (so the caller skips the delivery_unroutable diagnostic); false when no
1545
+ // fallback was possible (no coordinator anchor / no dispatch transport).
1546
+ //
1547
+ // Durability: the directed push to the coordinator is the ONLY delivery route for an
1548
+ // unresolved-mesh worker (it is in no mesh.node the coordinator can pull). So instead
1549
+ // of a fire-and-forget push that drops on one transient P2P failure, the event is
1550
+ // persisted to the worker-side outbox FIRST and only acked after a successful push.
1551
+ // A best-effort immediate push keeps latency low on the happy path; a failed or
1552
+ // un-acked push leaves the durable row for setupMeshReconcileLoop's PHASE 0 to retry.
1544
1553
  function forwardUnresolvedDelegateEvent(
1545
1554
  components: DaemonComponents,
1546
1555
  routing: ReturnType<typeof resolveWorkerDelegateRouting>,
@@ -1564,16 +1573,52 @@ function forwardUnresolvedDelegateEvent(
1564
1573
  workspace: readNonEmptyString(routing.workspace) || readNonEmptyString(event.workspace) || undefined,
1565
1574
  };
1566
1575
 
1576
+ // 1) Persist durably FIRST. Idempotent on fingerprint, so a re-fired completion
1577
+ // does not duplicate the outbox row. If persistence fails we still attempt the
1578
+ // push below (degrades to the old at-most-once behaviour rather than dropping
1579
+ // the chance entirely).
1580
+ const persisted = enqueueUnresolvedDelegateForward(coordinatorDaemonId, eventName, payload);
1581
+
1582
+ // 2) Best-effort immediate push for low latency. On success, ack the outbox row so
1583
+ // the retry loop won't re-send it. On failure, leave it queued — PHASE 0 retries.
1567
1584
  Promise.resolve(components.dispatchMeshCommand(coordinatorDaemonId, 'mesh_forward_event', payload))
1585
+ .then((result: any) => {
1586
+ if (result && result.success === false) {
1587
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued for retry`);
1588
+ return;
1589
+ }
1590
+ // Acked. Mark the durable copy delivered so the retry loop skips it.
1591
+ if (persisted) ackUnresolvedDelegateForwardByFingerprint(coordinatorDaemonId, eventName, payload);
1592
+ })
1568
1593
  .catch((e: any) => {
1569
- // The coordinator may be momentarily unreachable; the diagnostic was already
1570
- // skipped, so leave a trace here so an operator can see the relay attempt failed.
1571
- LOG.warn('MeshEvents', `Fallback forward of ${eventName} to coordinator ${coordinatorDaemonId} failed: ${e?.message || e}`);
1594
+ // Coordinator momentarily unreachable; the durable row stays queued and the
1595
+ // reconcile loop retries it. Trace so the relay attempt is visible.
1596
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} failed: ${e?.message || e} — left queued for retry`);
1572
1597
  });
1573
- LOG.info('MeshEvents', `Fallback-forwarded ${eventName} for unresolved-mesh worker at ${routing.workspace || '(no workspace)'} to coordinator daemon ${coordinatorDaemonId}`);
1598
+ LOG.info('MeshEvents', `Durably forwarded ${eventName} for unresolved-mesh worker at ${routing.workspace || '(no workspace)'} to coordinator daemon ${coordinatorDaemonId}`);
1574
1599
  return true;
1575
1600
  }
1576
1601
 
1602
+ // Ack a just-pushed outbox entry by re-deriving its row from the same coordinator +
1603
+ // event + payload. We don't thread the row id back from enqueue (the immediate push is
1604
+ // fire-then-ack), so locate it among the undrained entries by matching coordinator and
1605
+ // the flat payload's forward identity. A miss is harmless — the retry loop's own
1606
+ // receiver-side dedup suppresses a duplicate delivery.
1607
+ function ackUnresolvedDelegateForwardByFingerprint(
1608
+ coordinatorDaemonId: string,
1609
+ eventName: string,
1610
+ payload: Record<string, unknown>,
1611
+ ): void {
1612
+ const match = peekUnresolvedDelegateForwards().find(entry =>
1613
+ entry.coordinatorDaemonId === coordinatorDaemonId
1614
+ && readNonEmptyString(entry.payload.event) === eventName
1615
+ && readNonEmptyString(entry.payload.targetSessionId || entry.payload.sessionId || entry.payload.instanceId)
1616
+ === readNonEmptyString(payload.targetSessionId || payload.sessionId || payload.instanceId)
1617
+ && readNonEmptyString(entry.payload.workspace) === readNonEmptyString(payload.workspace),
1618
+ );
1619
+ if (match) ackUnresolvedDelegateForward(match.id);
1620
+ }
1621
+
1577
1622
  export function setupMeshEventForwarding(components: DaemonComponents) {
1578
1623
  components.instanceManager.onEvent((event) => {
1579
1624
  // --- Coordinator idle auto-flush (fast path) ---
@@ -47,6 +47,25 @@ export interface MeshMissionSummary extends MeshMissionRecord {
47
47
  tasks: MeshMissionTaskAggregate;
48
48
  }
49
49
 
50
+ /**
51
+ * Slim mission summary for the mesh_status compact (default) surface. Drops the
52
+ * full `goal` text — which can be hundreds of chars per mission and is repeated
53
+ * for every mission on every status call — keeping only a short preview plus a
54
+ * `goalTruncated` flag when the original was longer. The stored goal is never
55
+ * mutated; this is an output-only projection. Coordinators that need the full
56
+ * goal call mesh_status with verbose=true, or read the mission directly via
57
+ * mesh_mission_upsert / getMeshMission.
58
+ */
59
+ export interface MeshMissionSlimSummary extends Omit<MeshMissionSummary, 'goal'> {
60
+ /** Short preview of the goal (≤ GOAL_PREVIEW_MAX chars), '' when goal empty. */
61
+ goalPreview: string;
62
+ /** True when the stored goal was longer than the preview (full text elided). */
63
+ goalTruncated: boolean;
64
+ }
65
+
66
+ /** Max chars of goal text retained in the slim (compact) mission summary. */
67
+ export const GOAL_PREVIEW_MAX = 120;
68
+
50
69
  function normalizeMissionStatus(value: unknown): MeshMissionStatus {
51
70
  return MESH_MISSION_STATUSES.includes(value as MeshMissionStatus)
52
71
  ? value as MeshMissionStatus
@@ -125,17 +144,35 @@ export function getActiveMeshMissionSummaries(meshId: string): MeshMissionSummar
125
144
  return getMeshMissions(meshId, ['active']).map(mission => summarizeMeshMission(meshId, mission));
126
145
  }
127
146
 
147
+ /** Project a full mission summary down to the slim (goal-elided) shape. */
148
+ function slimMissionSummary(summary: MeshMissionSummary): MeshMissionSlimSummary {
149
+ const goal = typeof summary.goal === 'string' ? summary.goal : '';
150
+ const goalTruncated = goal.length > GOAL_PREVIEW_MAX;
151
+ const { goal: _omitGoal, ...rest } = summary;
152
+ return {
153
+ ...rest,
154
+ goalPreview: goalTruncated ? goal.slice(0, GOAL_PREVIEW_MAX) : goal,
155
+ goalTruncated,
156
+ };
157
+ }
158
+
128
159
  /**
129
160
  * Mission summaries for the mesh_status dashboard surface: every active/paused
130
161
  * mission plus a capped, newest-first slice of completed/abandoned history so
131
162
  * the dashboard can render a collapsible "history" section without unbounded
132
163
  * payload growth. Returned newest-first within each group (active/paused first,
133
164
  * then history), so the frontend can split on `status` directly.
165
+ *
166
+ * Compact mode (the default) elides each mission's full `goal` text — which is
167
+ * repeated verbatim on every status poll and dominates the payload when a mesh
168
+ * has many missions — returning only a short `goalPreview` + `goalTruncated`
169
+ * flag. Pass `verbose: true` to get the full `goal` text per mission. The stored
170
+ * goal is untouched in both modes; this is an output-only projection.
134
171
  */
135
172
  export function getMeshStatusMissionSummaries(
136
173
  meshId: string,
137
- options?: { historyLimit?: number },
138
- ): MeshMissionSummary[] {
174
+ options?: { historyLimit?: number; verbose?: boolean },
175
+ ): MeshMissionSummary[] | MeshMissionSlimSummary[] {
139
176
  const historyLimit = Math.max(0, options?.historyLimit ?? 10);
140
177
  const all = getMeshMissions(meshId);
141
178
  const live = all.filter(m => m.status === 'active' || m.status === 'paused');
@@ -143,7 +180,8 @@ export function getMeshStatusMissionSummaries(
143
180
  .filter(m => m.status === 'completed' || m.status === 'abandoned')
144
181
  .sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''))
145
182
  .slice(0, historyLimit);
146
- return [...live, ...history].map(mission => summarizeMeshMission(meshId, mission));
183
+ const full = [...live, ...history].map(mission => summarizeMeshMission(meshId, mission));
184
+ return options?.verbose ? full : full.map(slimMissionSummary);
147
185
  }
148
186
 
149
187
  /**
@@ -49,6 +49,11 @@ import { drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
49
49
  import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
50
50
  import { MeshRuntimeStore } from './mesh-runtime-store.js';
51
51
  import { handleMeshForwardEvent, shouldForceInjectMeshEvent, MESH_FORCE_INJECT_EVENTS } from './mesh-events-coordinator.js';
52
+ import {
53
+ peekUnresolvedDelegateForwards,
54
+ ackUnresolvedDelegateForward,
55
+ expireStaleUnresolvedDelegateForwards,
56
+ } from './mesh-unresolved-forward-outbox.js';
52
57
  import { readNonEmptyString } from './mesh-events-utils.js';
53
58
 
54
59
  // Default reconcile cadence. approval/completion notifications to a live CLI
@@ -213,6 +218,20 @@ export async function runMeshReconcileTick(components: DaemonComponents): Promis
213
218
  try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
214
219
  })();
215
220
 
221
+ // ── PHASE 0: retry the worker-side unresolved-delegate forward outbox ──────
222
+ // Cloud-only (needs dispatchMeshCommand). A worker that is NOT a member of the
223
+ // coordinator's mesh cannot be reached by the coordinator's PHASE 1 pull (it is
224
+ // in no mesh.node), so its completion must be PUSHED to the coordinator. This
225
+ // drains the durable outbox enqueued by forwardUnresolvedDelegateEvent and retries
226
+ // any push that has not yet been acked. See mesh-unresolved-forward-outbox.ts.
227
+ if (dispatchMeshCommand) {
228
+ try {
229
+ await retryUnresolvedDelegateForwards(components);
230
+ } catch (e: any) {
231
+ LOG.warn('MeshReconcile', `Unresolved-delegate forward retry failed: ${e?.message || e}`);
232
+ }
233
+ }
234
+
216
235
  // ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
217
236
  // Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
218
237
  // coordinator exists — this is what lets an MCP/LLM coordinator ever see a
@@ -295,6 +314,42 @@ export async function runMeshReconcileTick(components: DaemonComponents): Promis
295
314
  }
296
315
  }
297
316
 
317
+ // Cloud-only: retry the worker-side unresolved-delegate forward outbox. For each
318
+ // durably-queued entry, push it to its coordinator daemon over P2P (mesh_forward_event)
319
+ // and ack (mark drained) ONLY on a successful, non-rejected response. A failed or
320
+ // rejected push leaves the entry queued for the next tick — at-least-once delivery.
321
+ // Stale entries (coordinator unreachable past the max age) are expired first so the
322
+ // outbox can't grow without bound. The coordinator dedups duplicate deliveries on its
323
+ // own fingerprint, so a retry that races the original immediate push is harmless.
324
+ async function retryUnresolvedDelegateForwards(components: DaemonComponents): Promise<void> {
325
+ const dispatchMeshCommand = components.dispatchMeshCommand;
326
+ if (!dispatchMeshCommand) return;
327
+
328
+ // Drop entries that have exhausted their retry budget (fail-loud inside).
329
+ expireStaleUnresolvedDelegateForwards();
330
+
331
+ const entries = peekUnresolvedDelegateForwards();
332
+ if (entries.length === 0) return;
333
+
334
+ for (const entry of entries) {
335
+ let result: any;
336
+ try {
337
+ result = await dispatchMeshCommand(entry.coordinatorDaemonId, 'mesh_forward_event', entry.payload);
338
+ } catch (e: any) {
339
+ // Coordinator unreachable — keep the entry queued and try again next tick.
340
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} failed: ${e?.message || e} — left queued`);
341
+ continue;
342
+ }
343
+ if (result && result.success === false) {
344
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued`);
345
+ continue;
346
+ }
347
+ // Acked — mark the durable copy delivered.
348
+ ackUnresolvedDelegateForward(entry.id);
349
+ LOG.info('MeshReconcile', `Retried+delivered unresolved-delegate ${readNonEmptyString(entry.payload.event)} to coordinator ${entry.coordinatorDaemonId}`);
350
+ }
351
+ }
352
+
298
353
  // Cloud-only: poll each remote worker node daemon for pending coordinator events
299
354
  // and re-inject them locally via handleMeshForwardEvent (which re-queues +
300
355
  // surfaces to the live coordinator on the next tick / immediately if idle).
@@ -1396,4 +1396,34 @@ export class MeshRuntimeStore {
1396
1396
  ).get(meshId) as { cnt: number } | undefined;
1397
1397
  return row?.cnt ?? 0;
1398
1398
  }
1399
+
1400
+ /**
1401
+ * Mark specific pending-event rows drained by id (ack). Used by the
1402
+ * unresolved-delegate durable-forward outbox: an event is peeked (not drained)
1403
+ * while its push to the coordinator is unconfirmed, then marked drained ONLY
1404
+ * after the push is acked. A failed push leaves the row undrained so the next
1405
+ * reconcile tick retries it. Returns the number of rows newly marked drained.
1406
+ */
1407
+ markPendingEventsDrainedById(ids: ReadonlyArray<string>): number {
1408
+ const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
1409
+ if (idList.length === 0) return 0;
1410
+ const now = Date.now();
1411
+ return this.db.prepare(
1412
+ `UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE drained = 0 AND id IN (${idList.map(() => '?').join(',')})`
1413
+ ).run(now, ...idList).changes;
1414
+ }
1415
+
1416
+ /**
1417
+ * Hard-delete pending-event rows by id (including the dedup fingerprint history).
1418
+ * Used to expire an unresolved-delegate outbox entry that has exhausted its retry
1419
+ * budget — fully removing it frees the fingerprint so a genuinely new completion
1420
+ * for the same task could be re-queued later. Returns the number of rows deleted.
1421
+ */
1422
+ deletePendingEventsById(ids: ReadonlyArray<string>): number {
1423
+ const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
1424
+ if (idList.length === 0) return 0;
1425
+ return this.db.prepare(
1426
+ `DELETE FROM mesh_pending_events WHERE id IN (${idList.map(() => '?').join(',')})`
1427
+ ).run(...idList).changes;
1428
+ }
1399
1429
  }