@adhdev/daemon-core 0.9.82-rc.310 → 0.9.82-rc.311

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.
@@ -1,4 +1,5 @@
1
1
  import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
2
+ import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
2
3
  export declare function __resetIdleAutoFastForwardForTests(): void;
3
4
  export declare function __resetMeshWorkspaceCacheForTests(): void;
4
5
  export declare function tryAssignQueueTask(components: DaemonComponents, meshId: string, nodeId: string, sessionId: string, providerType: string): boolean;
@@ -7,6 +8,35 @@ export declare function tryAssignQueueTask(components: DaemonComponents, meshId:
7
8
  export declare function activeWriteAssignedCount(meshId: string): number;
8
9
  /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
9
10
  export declare function activeReadonlyAssignedCount(meshId: string): number;
11
+ /**
12
+ * Order eligible nodes for assignment per the mesh scheduling pipeline:
13
+ * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
14
+ *
15
+ * The caller has already applied the TAG hard-filter and is responsible for the
16
+ * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
17
+ * decides the *preference order* among nodes that are otherwise eligible.
18
+ *
19
+ * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
20
+ * the round-robin cursor — byte-for-byte the pre-feature behavior.
21
+ * - 'priority_only': schedulingPriority desc, then input order (load ignored).
22
+ * - 'least_loaded': schedulingPriority desc, then active load asc, then input order.
23
+ * - 'round_robin': same as least_loaded, but among nodes tied at (priority, load)
24
+ * the input order is rotated by a per-mesh cursor that advances once per pass.
25
+ *
26
+ * `nodes` carries the original config/array index so the tie-break can fall back to
27
+ * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
28
+ * once per scheduling pass (only consulted for 'round_robin').
29
+ */
30
+ interface RankableNode {
31
+ nodeId: string;
32
+ node: any;
33
+ index: number;
34
+ }
35
+ /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
36
+ * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
37
+ export declare function __orderEligibleNodesForTests(meshId: string, strategy: RepoMeshSchedulingStrategy, nodes: RankableNode[], opts?: {
38
+ bumpCursor?: boolean;
39
+ }): RankableNode[];
10
40
  export interface MeshQueueTriggerResult {
11
41
  success: true;
12
42
  meshId: string;
@@ -136,3 +166,4 @@ export declare function handleMeshForwardEvent(components: DaemonComponents, pay
136
166
  error: string;
137
167
  };
138
168
  export declare function setupMeshEventForwarding(components: DaemonComponents): void;
169
+ export {};
@@ -34,6 +34,24 @@ export declare class MeshRuntimeStore {
34
34
  private hasActiveSessionAssignment;
35
35
  /** A node may only execute one write task at a time (worktree isolation). */
36
36
  private hasActiveNodeAssignment;
37
+ /**
38
+ * Count active (status='assigned') tasks on a node, regardless of provider or
39
+ * task mode. This is the load metric for least-loaded / round-robin ranking:
40
+ * the scheduler prefers the node with the fewest active assignments so
41
+ * untargeted work spreads instead of piling onto whichever node asks first.
42
+ */
43
+ nodeActiveAssignmentCount(meshId: string, nodeId: string): number;
44
+ /**
45
+ * Read the current per-mesh round-robin cursor (0 when unset). Used to rotate
46
+ * the tie-break winner among nodes tied at the least load.
47
+ */
48
+ getSchedulerCursor(meshId: string): number;
49
+ /**
50
+ * Atomically advance the per-mesh round-robin cursor by one and return the
51
+ * value that was current BEFORE the bump (the value the caller should rotate
52
+ * by for this pass). UPSERT keeps it lock-free across concurrent passes.
53
+ */
54
+ bumpSchedulerCursor(meshId: string): number;
37
55
  /**
38
56
  * Count active (status='assigned') tasks on a (node, provider) combination,
39
57
  * matched by the assignedProviderType stamped on the payload at claim time.
@@ -85,6 +85,29 @@ export declare function buildMeshNodeCapabilityTags(node: {
85
85
  worktreeBranch?: unknown;
86
86
  } | undefined, providerType?: string): string[];
87
87
  export declare function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean;
88
+ /**
89
+ * Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
90
+ *
91
+ * When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
92
+ * tag is merged into a code_change task's required tags at enqueue time, so the
93
+ * scheduler hard-filters the task onto refine-capable worktree nodes only (on any
94
+ * machine — refine_mesh_node forwards to the owning daemon). Because the tag is
95
+ * persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
96
+ * and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
97
+ * it consistently.
98
+ *
99
+ * Strict backward compatibility — the injection is skipped (returns the explicit tags
100
+ * unchanged) when ANY of:
101
+ * - the mesh does not opt in (autoConvergeCodeChange !== true), or
102
+ * - the task is not code_change (validation / live_debug_readonly / launch_app /
103
+ * convergence carry no merge cost and may run anywhere), or
104
+ * - the task is explicitly targeted (targetNodeId): the operator chose the node, so
105
+ * we do not second-guess it by filtering on convergence capability.
106
+ * Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
107
+ */
108
+ export declare function resolveConvergeRequiredTags(meshId: string, taskMode: MeshTaskMode | undefined, explicitRequiredTags: string[], opts?: {
109
+ targetNodeId?: string;
110
+ }): string[];
88
111
  /**
89
112
  * M1: detect dependency cycles before enqueue. Walks the dependency graph of
90
113
  * existing queue entries plus the new task's edges. Fail-closed: a cycle
@@ -91,9 +91,15 @@ export declare class SpecCliAdapter implements CliAdapter {
91
91
  * drives the dispatch:
92
92
  *
93
93
  * send_keys → click_control (e.g. stop)
94
- * open_picker → click_control then resolve when extract_choices
95
- * surface; choice index comes from args.choiceIndex
96
- * or args.choice (string label match), defaulting to 0
94
+ * open_picker → two roles, driven by the screen, not a hardcoded list:
95
+ * - LIST (no choice arg): open the picker, wait for it
96
+ * to render, parse the on-screen options via
97
+ * `extract_choices`, and return them as
98
+ * `controlResult.options` (+ `currentValue`). This is
99
+ * how the dashboard's Model/Mode controls learn what is
100
+ * actually selectable in this CLI right now.
101
+ * - SELECT (args.choiceIndex / args.choiceLabel): drive
102
+ * the picker to that option using `submit_key`.
97
103
  * attach_image → attach_image dispatch; expects args.blob (data url
98
104
  * or base64) and args.mime
99
105
  *
@@ -101,6 +107,31 @@ export declare class SpecCliAdapter implements CliAdapter {
101
107
  * No control matched, no driver call — keeps the surface honest.
102
108
  */
103
109
  invokeScript(scriptName: string, args?: Record<string, unknown>): Promise<unknown>;
110
+ /**
111
+ * Open an `open_picker` control and return the options the CLI is showing,
112
+ * parsed live from the screen via `extract_choices`. Nothing is selected —
113
+ * the picker is left open so a follow-up SELECT invoke can commit a choice.
114
+ */
115
+ private openPickerAndListChoices;
116
+ /**
117
+ * Drive an already-listable picker to a specific option. The option can be
118
+ * named (choiceLabel — matched against the parsed on-screen labels) or
119
+ * positional (choiceIndex — the on-screen number). The actual keystrokes
120
+ * come from the spec's `submit_key` with `{index}` substituted, so the spec
121
+ * — not this code — decides how a selection is keyed for each CLI.
122
+ */
123
+ private selectPickerChoice;
124
+ /** Poll the live screen until the picker's `wait_for` condition matches,
125
+ * up to a short budget. Returns true if it rendered, false on timeout. */
126
+ private waitForPickerRendered;
127
+ /** Parse the picker's `extract_choices` pattern against the live screen.
128
+ * Each match yields { index, label, current }. `current` is true for the
129
+ * line the CLI marks with its cursor glyph (❯ ›). Purely screen-driven —
130
+ * no model/mode names are baked in. */
131
+ private extractPickerChoices;
132
+ /** Live text of a named screen section (or the whole screen when no
133
+ * section is named), resolved from the driver's current sections. */
134
+ private readScreenSectionText;
104
135
  getDebugSnapshot(): unknown;
105
136
  getRuntimeMetadata(): unknown;
106
137
  updateRuntimeMeta(meta?: Record<string, unknown>): void;
@@ -74,6 +74,42 @@ export interface NativeHistoryMessageMap {
74
74
  content_unwrap?: string[];
75
75
  timestamp_ms?: string;
76
76
  kind?: string;
77
+ /**
78
+ * Declarative tool-bubble extraction. Without it the executor only emits
79
+ * the text-bearing parts of each record, so a turn that is purely a tool
80
+ * call or tool result (no prose) is dropped — the restored transcript
81
+ * loses every tool interaction. When present, the executor walks each
82
+ * record's content blocks and emits an extra `kind:'tool'` message for
83
+ * any block whose `$.type` matches a tool shape.
84
+ *
85
+ * Defaults target the Anthropic-style content-block shape that claude-cli
86
+ * and codex-cli persist (blocks of `{ type: 'tool_use' | 'tool_result',
87
+ * name, input, content }`); a provider with a different on-disk shape
88
+ * overrides the field paths. Set `tools: {}` to opt in with the defaults.
89
+ */
90
+ tools?: NativeHistoryToolMap;
91
+ }
92
+ /**
93
+ * How to surface tool-call / tool-result blocks as `kind:'tool'` bubbles.
94
+ * Every field is optional — the defaults read the Anthropic block shape.
95
+ * Paths are jsonpath-lite evaluated against a single content block (the
96
+ * element of `$.message.content[]`), not the whole record.
97
+ */
98
+ export interface NativeHistoryToolMap {
99
+ /** Path to a block's discriminator. Default `$.type`. */
100
+ block_type?: string;
101
+ /** Block-type values that mean "a tool was invoked". Default
102
+ * `['tool_use', 'function_call', 'custom_tool_call']`. */
103
+ call_types?: string[];
104
+ /** Block-type values that mean "a tool returned". Default
105
+ * `['tool_result', 'function_call_output', 'custom_tool_call_output']`. */
106
+ result_types?: string[];
107
+ /** Path to the tool name on a call block. Default `$.name`. */
108
+ call_name?: string;
109
+ /** Path to the tool arguments on a call block. Default `$.input`. */
110
+ call_args?: string;
111
+ /** Path to the result payload on a result block. Default `$.content`. */
112
+ result_content?: string;
77
113
  }
78
114
  export interface AnchorContext {
79
115
  prev?: string;
@@ -71,6 +71,62 @@ export interface RepoMeshNode {
71
71
  export type RepoMeshNodeHealth = 'online' | 'offline' | 'degraded' | 'dirty' | 'wrong_branch' | 'unknown';
72
72
  export type RepoMeshSessionCleanupMode = 'preserve' | 'stop' | 'delete_stopped' | 'stop_and_delete';
73
73
  export type RepoMeshSpawnedSessionVisibility = 'visible' | 'hidden';
74
+ /**
75
+ * Mesh-wide tie-break strategy for distributing untargeted queue work across
76
+ * eligible nodes. This ONLY governs the final tie-break stage of the scheduler
77
+ * pipeline (TAG hard-filter → MAX-ALLOC capacity gate → PRIORITY soft score →
78
+ * TIE-BREAK); eligibility/capacity/priority are evaluated identically for every
79
+ * strategy.
80
+ *
81
+ * - 'first_eligible' (DEFAULT): preserve today's behavior exactly. Nodes are
82
+ * visited in config/array order and the first that can launch wins. No
83
+ * load-spreading. This is the strict no-change default — a mesh that never
84
+ * sets schedulingStrategy behaves identically to before this feature.
85
+ * - 'least_loaded': prefer the eligible node with the fewest active assignments,
86
+ * so untargeted work spreads instead of piling onto whichever node asks first.
87
+ * - 'round_robin': among nodes tied at the least load, rotate the winner using a
88
+ * per-mesh cursor so distribution stays fair across passes.
89
+ * - 'priority_only': rank purely by schedulingPriority (then config order),
90
+ * ignoring load — always send to the highest-priority eligible node.
91
+ *
92
+ * Distribution is explicit opt-in: a strategy other than 'first_eligible' must be
93
+ * configured for any load-spreading to occur.
94
+ */
95
+ export type RepoMeshSchedulingStrategy = 'first_eligible' | 'least_loaded' | 'round_robin' | 'priority_only';
96
+ export declare const MESH_SCHEDULING_STRATEGIES: RepoMeshSchedulingStrategy[];
97
+ export declare const DEFAULT_MESH_SCHEDULING_STRATEGY: RepoMeshSchedulingStrategy;
98
+ /**
99
+ * Normalize an unknown scheduling-strategy value to a valid strategy, defaulting
100
+ * to 'first_eligible' (strict no-change) for anything missing/blank/unrecognized.
101
+ */
102
+ export declare function normalizeMeshSchedulingStrategy(value: unknown): RepoMeshSchedulingStrategy;
103
+ /**
104
+ * Resolve a node's soft scheduling priority — a single scalar used as the PRIORITY
105
+ * stage rank key (higher = preferred). It is NOT an eligibility gate (the MAX-ALLOC
106
+ * capacity gate alone decides whether a node can take work). Missing/blank/NaN
107
+ * resolves to 0 so unconfigured nodes all share the same neutral priority.
108
+ */
109
+ export declare function resolveNodeSchedulingPriority(nodePolicy: Pick<RepoMeshNodePolicy, 'schedulingPriority'> | null | undefined): number;
110
+ /**
111
+ * Synthetic capability tag advertised by every mesh node describing how it can land
112
+ * its work onto the base branch:
113
+ * - converge=refine: a local worktree node (on any machine — refine_mesh_node
114
+ * forwards to the owning daemon) can run the Refinery merge → push → cleanup.
115
+ * - converge=fast_forward: a non-worktree node (the machine itself) can only
116
+ * fast-forward/push an already-converged branch.
117
+ * Emitted by buildMeshNodeCapabilityTags and matched through the ordinary
118
+ * required-tags filter.
119
+ */
120
+ export declare const MESH_CONVERGE_REFINE_TAG = "converge=refine";
121
+ export declare const MESH_CONVERGE_FAST_FORWARD_TAG = "converge=fast_forward";
122
+ /**
123
+ * Resolve whether the load-balancing scheduler should auto-inject a
124
+ * `converge=refine` required tag onto code_change tasks so they hard-filter onto
125
+ * refine-capable (worktree) nodes only. Strict opt-in: defaults to false, so a mesh
126
+ * that does not set it behaves exactly as before (code_change routes to any eligible
127
+ * node, including a non-worktree machine node when no worktree exists).
128
+ */
129
+ export declare function resolveAutoConvergeCodeChange(policy: Pick<RepoMeshPolicy, 'autoConvergeCodeChange'> | null | undefined): boolean;
74
130
  export interface RepoMeshAutoFastForwardPolicy {
75
131
  /** Defaults to true. Set false to disable daemon-initiated idle fast-forwards. */
76
132
  enabled: boolean;
@@ -94,6 +150,24 @@ export interface RepoMeshPolicy {
94
150
  dirtyWorkspaceBehavior: 'block' | 'warn' | 'checkpoint_then_continue';
95
151
  maxParallelTasks: number;
96
152
  allowedProviders?: string[];
153
+ /**
154
+ * Mesh-wide tie-break strategy for distributing untargeted queue work across
155
+ * eligible nodes. Defaults to 'first_eligible' (today's exact behavior — no
156
+ * load-spreading). Set to 'least_loaded' / 'round_robin' / 'priority_only' to
157
+ * opt into distribution. Only governs the final tie-break stage; eligibility,
158
+ * capacity, and priority are evaluated identically regardless of strategy.
159
+ */
160
+ schedulingStrategy?: RepoMeshSchedulingStrategy;
161
+ /**
162
+ * Convergence routing opt-in: when true, the scheduler auto-injects a
163
+ * `converge=refine` required tag onto every code_change task at enqueue time, so
164
+ * code_change work hard-filters onto refine-capable worktree nodes (on any
165
+ * machine — refine_mesh_node forwards to the owning daemon) and never lands on a
166
+ * non-worktree machine node. Explicit target_node_id routing and any
167
+ * caller-supplied required_tags are preserved (the tag is merged, not replaced).
168
+ * Defaults to false: code_change routing is unchanged unless opted in.
169
+ */
170
+ autoConvergeCodeChange?: boolean;
97
171
  /**
98
172
  * Whether sessions spawned by mesh/coordinator policy should auto-open as visible
99
173
  * dashboard tabs or start hidden. Defaults to 'visible' to preserve existing
@@ -140,12 +214,17 @@ export interface RepoMeshRelatedRepo {
140
214
  *
141
215
  * `role` is a free-form resource-pool label (recommended values:
142
216
  * 'investigation' | 'coding' | 'orchestration') describing what this
143
- * (node, provider) combination is *for*. It is a label/hint only it is
144
- * surfaced to the coordinator and dashboards but the daemon does NOT route
145
- * tasks by role (task routing stays driven by taskMode + requiredTags +
146
- * targetNode/targetSession). role is intentionally orthogonal to taskMode:
147
- * taskMode classifies the *work* (code_change vs live_debug_readonly), role
148
- * classifies the *resource pool*.
217
+ * (node, provider) combination is *for*. As of the load-balancing scheduler it
218
+ * is ALSO routable: each declared role is advertised as a synthetic `role=<x>`
219
+ * capability tag (see buildMeshNodeCapabilityTags), so a task enqueued with
220
+ * requiredTags: ["role=validation"] is hard-filtered to nodes/providers that
221
+ * declare that role — through the same nodeSatisfiesRequiredTags path as any
222
+ * other tag. There is intentionally no separate "advertisedRoles" field: the
223
+ * label and the routing tag are one mechanism. A task that does not require a
224
+ * `role=` tag ignores roles entirely (opt-in, fully backward compatible).
225
+ *
226
+ * role is intentionally orthogonal to taskMode: taskMode classifies the *work*
227
+ * (code_change vs live_debug_readonly), role classifies the *resource pool*.
149
228
  *
150
229
  * `maxParallel` is the only enforced field: the queue will not assign a task
151
230
  * to this (node, provider) once it already has `maxParallel` active
@@ -166,15 +245,24 @@ export interface RepoMeshNodePolicy {
166
245
  readOnly?: boolean;
167
246
  canPush?: boolean;
168
247
  maxConcurrentSessions?: number;
248
+ /**
249
+ * Soft scheduling priority used as the PRIORITY rank key (higher = preferred)
250
+ * when the mesh schedulingStrategy spreads work across nodes. Defaults to 0.
251
+ * This is NOT an eligibility gate — a node with a high priority that is at its
252
+ * capacity (MAX-ALLOC gate) is still skipped; priority only orders nodes that
253
+ * can actually take work. Ignored entirely under 'first_eligible'.
254
+ */
255
+ schedulingPriority?: number;
169
256
  /** Ordered provider preference used when mesh_launch_session omits an explicit type. */
170
257
  providerPriority?: string[];
171
258
  /**
172
259
  * Per-(node, provider) role + parallelism declarations. Each entry binds a
173
260
  * providerType on THIS node to an optional free-form role label and an
174
- * optional maxParallel cap. Only maxParallel is enforced (as an additional,
261
+ * optional maxParallel cap. maxParallel is enforced (as an additional,
175
262
  * stricter-wins constraint on top of the global maxParallelTasks/taskMode
176
- * caps); role is a label/hint surfaced to the coordinator. Missing/empty:
177
- * the node behaves exactly as before (global caps only).
263
+ * caps); role is advertised as a routable `role=<x>` capability tag so tasks
264
+ * can hard-filter by required role. Missing/empty: the node behaves exactly
265
+ * as before (global caps only, no role tags).
178
266
  */
179
267
  providerRoles?: RepoMeshProviderRole[];
180
268
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "0.9.82-rc.310",
3
+ "version": "0.9.82-rc.311",
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.310",
49
+ "@adhdev/mesh-shared": "0.9.82-rc.311",
50
50
  "@adhdev/session-host-core": "*",
51
51
  "@agentclientprotocol/sdk": "^0.16.1",
52
52
  "ajv": "^8.20.0",
@@ -29,7 +29,7 @@ import {
29
29
  } from '../chat/source-resolver.js';
30
30
  import type { ChatMessage } from '../types.js';
31
31
  import type { SessionTransport } from '../shared-types.js';
32
- import { filterUserFacingChatMessages, normalizeChatMessages } from '../providers/chat-message-normalization.js';
32
+ import { filterUserFacingChatMessages, isActivityChatMessage, isUserFacingChatMessage, normalizeChatMessages } from '../providers/chat-message-normalization.js';
33
33
 
34
34
  const RECENT_SEND_WINDOW_MS = 1200;
35
35
  export const READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS = 25_000;
@@ -1531,7 +1531,15 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any, h?:
1531
1531
  const filteredMessages = h
1532
1532
  ? maybeHideCoordinatorPromptMessage(h, providerHint, sessionIdHint, messages)
1533
1533
  : messages;
1534
- const visibleMessages = filterUserFacingChatMessages(filteredMessages);
1534
+ // By default read_chat returns only user-facing prose turns. When the
1535
+ // caller opts in with `includeActivity`, tool/terminal/thought activity
1536
+ // bubbles (e.g. the native transcript's tool calls and results) are kept
1537
+ // inline too, in chronological order, so a restored conversation can show
1538
+ // what the agent actually did — not just the prose around it.
1539
+ const includeActivity = args?.includeActivity === true || args?.includeActivity === 'true';
1540
+ const visibleMessages = includeActivity
1541
+ ? filteredMessages.filter((m) => isUserFacingChatMessage(m) || isActivityChatMessage(m))
1542
+ : filterUserFacingChatMessages(filteredMessages);
1535
1543
  const sync = buildFullTail(visibleMessages, normalizeReadChatTailLimit(args));
1536
1544
  const hiddenMsgCount = Math.max(0, messages.length - visibleMessages.length);
1537
1545
  const preservedPayloadFields = Object.fromEntries(Object.entries(payload).filter(([key]) => shouldPreserveReadChatPayloadField(key)));
@@ -985,6 +985,73 @@ function readMeshTimeoutEnvMs(name: string, defaultMs: number): number {
985
985
  // (still under the P2P REQUEST_TIMEOUT of 30s) and made env-overridable.
986
986
  const MESH_DIRECT_PROBE_TIMEOUT_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_TIMEOUT_MS', 25_000);
987
987
  const MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS', 25_000);
988
+ // How long a successful per-peer git_status probe stays fresh enough to be
989
+ // reused instead of issuing another blocking `refreshUpstream:true` fan-out.
990
+ // A slow (TURN-relayed) peer's probe can take 9-23s, and the dashboard's
991
+ // auto-retry loop re-fires every few seconds; without this gate every retry
992
+ // would start a brand new probe storm to the same peer. Within this window the
993
+ // last successful result is reused so a refresh quiesces instead of looping.
994
+ // Min-clamped to 1s by readMeshTimeoutEnvMs; raise via env for very slow peers.
995
+ const MESH_DIRECT_PROBE_REUSE_MS = readMeshTimeoutEnvMs('MESH_DIRECT_PROBE_REUSE_MS', 12_000);
996
+
997
+ /**
998
+ * De-duplicates and rate-limits per-peer git_status probes so a single mesh
999
+ * refresh — or a burst of refreshes from the dashboard auto-retry loop — cannot
1000
+ * launch a storm of concurrent/back-to-back `refreshUpstream:true` commands to
1001
+ * the same slow peer.
1002
+ *
1003
+ * Two gates, both keyed by `daemonId::workspace`:
1004
+ * - In-flight dedup: a second probe for a key with a probe already running
1005
+ * shares (awaits) the in-flight promise instead of issuing a second command.
1006
+ * - Recently-probed reuse: a successful probe younger than `reuseMs` is reused
1007
+ * verbatim instead of issuing a fresh probe. Failures are NOT cached (so a
1008
+ * transient timeout doesn't pin a peer to "no truth" for the whole window).
1009
+ *
1010
+ * Lives on the router instance so the gate spans separate mesh_status calls,
1011
+ * which is exactly where the refresh storm happens.
1012
+ */
1013
+ class MeshGitProbeCache {
1014
+ private inflight = new Map<string, Promise<Record<string, unknown> | null>>();
1015
+ private recent = new Map<string, { at: number; value: Record<string, unknown> }>();
1016
+
1017
+ constructor(private readonly reuseMs: number, private readonly now: () => number = Date.now) {}
1018
+
1019
+ private key(daemonId: string, workspace: string): string {
1020
+ return `${daemonId}::${workspace}`;
1021
+ }
1022
+
1023
+ /**
1024
+ * Run `probe` for this peer, but reuse a fresh recent result or an in-flight
1025
+ * probe for the same key when one is available. `probe` is only invoked when
1026
+ * neither gate is satisfied.
1027
+ */
1028
+ async probe(
1029
+ daemonId: string,
1030
+ workspace: string,
1031
+ probe: () => Promise<Record<string, unknown> | null>,
1032
+ ): Promise<Record<string, unknown> | null> {
1033
+ const key = this.key(daemonId, workspace);
1034
+ const cached = this.recent.get(key);
1035
+ if (cached && this.now() - cached.at < this.reuseMs) {
1036
+ return cached.value;
1037
+ }
1038
+ const existing = this.inflight.get(key);
1039
+ if (existing) return existing;
1040
+ const pending = (async () => {
1041
+ const result = await probe();
1042
+ if (result) this.recent.set(key, { at: this.now(), value: result });
1043
+ return result;
1044
+ })();
1045
+ this.inflight.set(key, pending);
1046
+ try {
1047
+ return await pending;
1048
+ } finally {
1049
+ // Only clear the slot if it is still ours — a later overlapping call
1050
+ // would have reused this very promise, so it is safe to delete here.
1051
+ if (this.inflight.get(key) === pending) this.inflight.delete(key);
1052
+ }
1053
+ }
1054
+ }
988
1055
 
989
1056
  async function probeRemoteMeshGitStatus(args: {
990
1057
  dispatchMeshCommand?: (daemonId: string, cmd: string, args: Record<string, unknown>) => Promise<unknown>;
@@ -1074,6 +1141,10 @@ async function hydrateInlineMeshDirectTruth(args: {
1074
1141
  // probe was attempted. Only an explicit refresh (probeRemotePeers=true)
1075
1142
  // performs the fan-out and classifies an unreachable peer as unavailable.
1076
1143
  probeRemotePeers: boolean;
1144
+ // Optional shared probe cache: dedups concurrent probes and reuses a
1145
+ // recently-probed peer's result instead of re-issuing a blocking
1146
+ // refreshUpstream probe within the reuse window.
1147
+ probeCache?: MeshGitProbeCache;
1077
1148
  }): Promise<{
1078
1149
  directEvidenceCount: number;
1079
1150
  localConfirmedCount: number;
@@ -1162,8 +1233,10 @@ async function hydrateInlineMeshDirectTruth(args: {
1162
1233
  // Bounded retry, gated on the peer staying `connected`: a slow
1163
1234
  // (TURN-relayed) peer that just exceeds one probe window is recovered
1164
1235
  // instead of being hard-failed. The connection is re-checked before each
1165
- // retry so a peer that actually dropped is abandoned promptly.
1166
- const remoteGit = await probeRemoteMeshGitStatusWithRetry({
1236
+ // retry so a peer that actually dropped is abandoned promptly. Routed
1237
+ // through the shared probe cache so a refresh burst reuses a recent
1238
+ // result / shares an in-flight probe instead of storming the peer.
1239
+ const runProbe = () => probeRemoteMeshGitStatusWithRetry({
1167
1240
  dispatchMeshCommand: args.dispatchMeshCommand,
1168
1241
  daemonId,
1169
1242
  workspace,
@@ -1171,6 +1244,9 @@ async function hydrateInlineMeshDirectTruth(args: {
1171
1244
  retryTimeoutMs: MESH_DIRECT_PROBE_RETRY_TIMEOUT_MS,
1172
1245
  getConnection: args.getMeshPeerConnectionStatus,
1173
1246
  });
1247
+ const remoteGit = args.probeCache
1248
+ ? await args.probeCache.probe(daemonId, workspace, runProbe)
1249
+ : await runProbe();
1174
1250
  if (remoteGit) {
1175
1251
  recordInlineMeshDirectGitTruth(node, remoteGit, 'selected_coordinator_mesh_p2p_git');
1176
1252
  peerConfirmedCount += 1;
@@ -3159,6 +3235,10 @@ export class DaemonCommandRouter {
3159
3235
  private inlineMeshCache = new Map<string, any>();
3160
3236
  /** Coordinator-owned whole-mesh aggregate status snapshots. Browser callers read this by default. */
3161
3237
  private aggregateMeshStatusCache = new Map<string, { builtAt: number; snapshot: any; queueRevision: string }>();
3238
+ /** Shared per-peer git_status probe dedup + recently-probed reuse gate.
3239
+ * Spans separate mesh_status/get_mesh calls so the dashboard auto-retry
3240
+ * loop cannot storm a slow peer with back-to-back refreshUpstream probes. */
3241
+ private meshGitProbeCache = new MeshGitProbeCache(MESH_DIRECT_PROBE_REUSE_MS);
3162
3242
  /** In-memory async Refinery jobs keyed by meshId:nodeId to reject/return duplicate in-flight requests. */
3163
3243
  private runningRefineJobs = new Map<string, MeshRefineJobHandle>();
3164
3244
  /** Terminal async Refinery jobs preserve a clear answer after the worktree node has been removed. */
@@ -6611,6 +6691,7 @@ export class DaemonCommandRouter {
6611
6691
  statusInstanceId: this.deps.statusInstanceId,
6612
6692
  localMachineId: loadConfig().machineId || '',
6613
6693
  probeRemotePeers,
6694
+ probeCache: this.meshGitProbeCache,
6614
6695
  });
6615
6696
  const directTruthSatisfied = meshRecord.source !== 'inline_bootstrap' || directTruth.directEvidenceCount > 0;
6616
6697
  const sourceOfTruth = {
@@ -7293,6 +7374,49 @@ export class DaemonCommandRouter {
7293
7374
  const meshId = typeof args?.meshId === 'string' ? args.meshId.trim() : '';
7294
7375
  const nodeId = typeof args?.nodeId === 'string' ? args.nodeId.trim() : '';
7295
7376
  if (!meshId || !nodeId) return { success: false, error: 'meshId and nodeId required' };
7377
+
7378
+ // Remote forward: a worktree node lives on its OWN daemon's machine, so the
7379
+ // refine (cd into node.workspace, merge → push → cleanup) must run on THAT
7380
+ // daemon — not the coordinator, whose filesystem has no such path. The sibling
7381
+ // fast_forward_mesh_node / clone_mesh_node handlers already forward to the
7382
+ // node's daemon; refine_mesh_node was the gap (the coordinator would cd into a
7383
+ // non-existent local path and fail), so remote-machine worktrees could not be
7384
+ // converged at all. Forward both dry-run (plan reads the worktree git state)
7385
+ // and execute (async merge job) so the same machine that owns the worktree
7386
+ // resolves it.
7387
+ //
7388
+ // coordinatorDaemonId: refine is ASYNC — the completed/failed event is queued
7389
+ // on the executing daemon's pending-events queue scoped to a coordinator id and
7390
+ // recovered by the coordinator's reconcile loop (pullRemoteNodeQueues →
7391
+ // get_pending_mesh_events). Without stamping our own status id, the remote
7392
+ // daemon would fall back to ITS OWN statusInstanceId as the coordinator
7393
+ // (startMeshRefineJob), scoping the terminal event to the wrong inbox where the
7394
+ // real coordinator never pulls it. Stamp the canonical status id (which is in
7395
+ // the coordinator's self-identity set used to scope the remote drain) so the
7396
+ // event routes back here. Preserve any caller-supplied coordinatorDaemonId.
7397
+ //
7398
+ // _meshDirectDispatch prevents re-forwarding (and P2P self-dial) once the call
7399
+ // has landed on the owning daemon — that daemon then executes locally even if
7400
+ // the stored daemonId uses a legacy form that doesn't match its own identity.
7401
+ {
7402
+ const meshRecordForForward = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
7403
+ const forwardNode = meshRecordForForward?.mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId));
7404
+ const nodeDaemonId = typeof forwardNode?.daemonId === 'string' ? forwardNode.daemonId.trim() : undefined;
7405
+ const selfDaemonId = this.deps.statusInstanceId;
7406
+ const isRemote = nodeDaemonId && selfDaemonId && nodeDaemonId !== selfDaemonId;
7407
+ if (isRemote && this.deps.dispatchMeshCommand && !args?._meshDirectDispatch) {
7408
+ const callerCoordinatorDaemonId = typeof args?.coordinatorDaemonId === 'string' && args.coordinatorDaemonId.trim()
7409
+ ? args.coordinatorDaemonId.trim()
7410
+ : undefined;
7411
+ const forwarded = await this.deps.dispatchMeshCommand(nodeDaemonId!, 'refine_mesh_node', {
7412
+ ...(typeof args === 'object' && args !== null ? args as Record<string, unknown> : {}),
7413
+ coordinatorDaemonId: callerCoordinatorDaemonId || selfDaemonId,
7414
+ _meshDirectDispatch: true,
7415
+ });
7416
+ return (forwarded ?? { success: false, error: 'no response from remote node' }) as CommandRouterResult;
7417
+ }
7418
+ }
7419
+
7296
7420
  // Dry-run (plan-only) is the default and stays synchronous: it does no
7297
7421
  // validation/merge/push and returns the plan instantly. Only execute=true
7298
7422
  // (and not dry_run) goes through the async refine job that actually
@@ -8492,6 +8616,11 @@ export class DaemonCommandRouter {
8492
8616
 
8493
8617
  const localMachineId = loadConfig().machineId || '';
8494
8618
  const requireDirectPeerTruth = args?.requireDirectPeerTruth === true;
8619
+ // Shared probe gate for this mesh_status call: the bootstrap
8620
+ // hydrate below and the per-node render loop further down both
8621
+ // probe the same peers — route both through this cache so they
8622
+ // dedup within the call and reuse recent results across calls.
8623
+ const meshGitProbeCache = this.meshGitProbeCache;
8495
8624
  const directTruth = requireDirectPeerTruth
8496
8625
  ? await hydrateInlineMeshDirectTruth({
8497
8626
  mesh,
@@ -8504,6 +8633,7 @@ export class DaemonCommandRouter {
8504
8633
  // out a blocking peer git probe. Default loads return
8505
8634
  // held truth so one slow peer can't block the graph.
8506
8635
  probeRemotePeers: refreshRequested,
8636
+ probeCache: meshGitProbeCache,
8507
8637
  })
8508
8638
  : {
8509
8639
  directEvidenceCount: 0,
@@ -8710,7 +8840,7 @@ export class DaemonCommandRouter {
8710
8840
  // path), gated on the peer staying connected, so a
8711
8841
  // slow TURN-relayed peer is recovered rather than
8712
8842
  // dropped after a single timeout.
8713
- const remoteGit = await probeRemoteMeshGitStatusWithRetry({
8843
+ const runNodeProbe = () => probeRemoteMeshGitStatusWithRetry({
8714
8844
  dispatchMeshCommand: this.deps.dispatchMeshCommand,
8715
8845
  daemonId,
8716
8846
  workspace,
@@ -8719,6 +8849,12 @@ export class DaemonCommandRouter {
8719
8849
  getConnection: this.deps.getMeshPeerConnectionStatus,
8720
8850
  onConnection: connection => { status.connection = connection; },
8721
8851
  });
8852
+ // Same shared cache as the bootstrap hydrate path: within one
8853
+ // mesh_status call this dedups the bootstrap probe against this
8854
+ // per-node probe for the same peer, and across calls it reuses a
8855
+ // recent result so the dashboard auto-retry loop can't restart a
8856
+ // fresh refreshUpstream probe seconds apart.
8857
+ const remoteGit = await meshGitProbeCache.probe(daemonId, workspace, runNodeProbe);
8722
8858
  if (remoteGit) {
8723
8859
  status.git = remoteGit;
8724
8860
  status.health = remoteGit.isGitRepo
@@ -245,6 +245,14 @@ export function normalizeProviderScriptArgs(args: any, scriptName?: string): Rec
245
245
  function buildControlScriptResult(scriptName: string, payload: any): Record<string, unknown> {
246
246
  if (!payload || typeof payload !== 'object') return {};
247
247
 
248
+ // The spec-driven control adapter (open_picker LIST/SELECT) already
249
+ // produced a structured controlResult by parsing the live screen. Honour
250
+ // it verbatim instead of re-deriving one from legacy payload shapes —
251
+ // otherwise the screen-parsed options/currentValue get clobbered.
252
+ if (payload.controlResult && typeof payload.controlResult === 'object') {
253
+ return { controlResult: payload.controlResult };
254
+ }
255
+
248
256
  const legacyListPayload = (() => {
249
257
  if (Array.isArray(payload.options)) return payload;
250
258
  if (/^listmodels$/i.test(scriptName) && Array.isArray(payload.models)) {
@@ -172,6 +172,15 @@ function collapseReplayAssistantTurns(messages: HistoryMessage[], historyBehavio
172
172
  }
173
173
 
174
174
  if (message.role === 'assistant') {
175
+ // Tool / activity bubbles are distinct events, not replayed prose —
176
+ // collapsing them would erase every tool call and result after the
177
+ // turn's first assistant message. Only consecutive *prose* assistant
178
+ // turns are the replay-dedup target this collapse exists for.
179
+ const isActivity = message.kind === 'tool' || message.kind === 'terminal' || message.kind === 'thought';
180
+ if (isActivity) {
181
+ collapsed.push(message);
182
+ continue;
183
+ }
175
184
  if (sawAssistantSinceLastUser) continue;
176
185
  sawAssistantSinceLastUser = true;
177
186
  collapsed.push(message);