@adhdev/daemon-core 0.9.82-rc.259 → 0.9.82-rc.260

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.
@@ -0,0 +1,197 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+
4
+ const execFileAsync = promisify(execFile);
5
+
6
+ /**
7
+ * Change-area analysis for one worktree node, used to order sibling nodes for
8
+ * batch refinement so that nodes least likely to conflict merge first.
9
+ *
10
+ * The heuristic is deliberately git-only and side-effect-free: it inspects the
11
+ * commits the node's branch adds on top of the base (`base..branch`) and records
12
+ * - whether any submodule gitlink path is touched (high-conflict signal: the
13
+ * batch must rebase later siblings onto the advanced submodule main), and
14
+ * - the set of changed top-level paths (so siblings touching disjoint trees can
15
+ * be ordered ahead of ones that overlap).
16
+ */
17
+ export interface MeshRefineBatchNodeChangeArea {
18
+ nodeId: string;
19
+ workspace: string;
20
+ branch: string;
21
+ /** Top-level path segments changed by the branch vs. base (e.g. 'oss', 'packages'). */
22
+ changedTopLevelPaths: string[];
23
+ /** Full changed file list (bounded) for overlap detection. */
24
+ changedFiles: string[];
25
+ /** Submodule gitlink paths touched by the branch (subset of changedTopLevelPaths). */
26
+ touchedSubmodulePaths: string[];
27
+ /** True when the branch touches at least one submodule gitlink. */
28
+ touchesSubmodule: boolean;
29
+ /** Number of commits the branch is ahead of base; 0 means nothing to merge. */
30
+ aheadCount: number;
31
+ /** Non-fatal analysis error (e.g. base/branch unresolved); ordering falls back to neutral. */
32
+ error?: string;
33
+ }
34
+
35
+ export interface MeshRefineBatchOrderingResult {
36
+ /** Node IDs in the order they should be refined. */
37
+ order: string[];
38
+ /** Per-node change areas, keyed by node id, for plan transparency. */
39
+ changeAreas: Record<string, MeshRefineBatchNodeChangeArea>;
40
+ /** Human-readable explanation of why the order was chosen. */
41
+ rationale: string[];
42
+ }
43
+
44
+ const MAX_CHANGED_FILES = 500;
45
+
46
+ function topLevel(path: string): string {
47
+ const slash = path.indexOf('/');
48
+ return slash === -1 ? path : path.slice(0, slash);
49
+ }
50
+
51
+ /**
52
+ * Resolve the set of submodule gitlink paths declared in a repo's .gitmodules,
53
+ * relative to the repo root. Used to classify which changed paths are submodule
54
+ * pointer bumps vs. ordinary file edits.
55
+ */
56
+ async function resolveSubmodulePaths(repoRoot: string): Promise<Set<string>> {
57
+ try {
58
+ const { stdout } = await execFileAsync(
59
+ 'git',
60
+ ['config', '--file', '.gitmodules', '--get-regexp', 'path'],
61
+ { cwd: repoRoot, encoding: 'utf8' },
62
+ );
63
+ const paths = new Set<string>();
64
+ for (const line of stdout.split('\n')) {
65
+ const trimmed = line.trim();
66
+ if (!trimmed) continue;
67
+ // Format: "submodule.<name>.path <path>"
68
+ const spaceIdx = trimmed.indexOf(' ');
69
+ if (spaceIdx === -1) continue;
70
+ const value = trimmed.slice(spaceIdx + 1).trim();
71
+ if (value) paths.add(value);
72
+ }
73
+ return paths;
74
+ } catch {
75
+ // No .gitmodules (or git error) → repo has no submodules to classify.
76
+ return new Set();
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Analyze one worktree node's change area against its merge base.
82
+ *
83
+ * @param baseRef ref that the node will merge into (e.g. 'origin/main' or a SHA)
84
+ * @param branchRef the node's branch tip
85
+ * @param diffCwd repo to run the diff in (the worktree itself is authoritative for
86
+ * `branch` resolution, but the diff `base..branch` is symmetric, so
87
+ * the worktree cwd works for both refs once base is a reachable SHA).
88
+ */
89
+ export async function analyzeMeshRefineNodeChangeArea(args: {
90
+ nodeId: string;
91
+ workspace: string;
92
+ branch: string;
93
+ baseRef: string;
94
+ branchRef: string;
95
+ diffCwd: string;
96
+ submodulePaths: Set<string>;
97
+ }): Promise<MeshRefineBatchNodeChangeArea> {
98
+ const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
99
+ const base: MeshRefineBatchNodeChangeArea = {
100
+ nodeId,
101
+ workspace,
102
+ branch,
103
+ changedTopLevelPaths: [],
104
+ changedFiles: [],
105
+ touchedSubmodulePaths: [],
106
+ touchesSubmodule: false,
107
+ aheadCount: 0,
108
+ };
109
+ try {
110
+ // Use the merge-base so we compare only the node's own commits, not changes
111
+ // that already landed on base via a sibling earlier in the batch.
112
+ let mergeBase = baseRef;
113
+ try {
114
+ const { stdout } = await execFileAsync('git', ['merge-base', baseRef, branchRef], { cwd: diffCwd, encoding: 'utf8' });
115
+ const resolved = stdout.trim();
116
+ if (resolved) mergeBase = resolved;
117
+ } catch { /* fall back to baseRef directly */ }
118
+
119
+ const { stdout: countStdout } = await execFileAsync(
120
+ 'git',
121
+ ['rev-list', '--count', `${mergeBase}..${branchRef}`],
122
+ { cwd: diffCwd, encoding: 'utf8' },
123
+ );
124
+ base.aheadCount = Number.parseInt(countStdout.trim(), 10) || 0;
125
+
126
+ const { stdout: nameStdout } = await execFileAsync(
127
+ 'git',
128
+ ['diff', '--name-only', `${mergeBase}..${branchRef}`],
129
+ { cwd: diffCwd, encoding: 'utf8' },
130
+ );
131
+ const files = nameStdout.split('\n').map(line => line.trim()).filter(Boolean).slice(0, MAX_CHANGED_FILES);
132
+ base.changedFiles = files;
133
+ const topSet = new Set<string>();
134
+ const submoduleSet = new Set<string>();
135
+ for (const file of files) {
136
+ const top = topLevel(file);
137
+ topSet.add(top);
138
+ // A changed path is a submodule touch if the file path IS a declared
139
+ // submodule path (gitlink bumps surface as the submodule path itself).
140
+ if (submodulePaths.has(file) || submodulePaths.has(top)) {
141
+ submoduleSet.add(submodulePaths.has(file) ? file : top);
142
+ }
143
+ }
144
+ base.changedTopLevelPaths = [...topSet].sort();
145
+ base.touchedSubmodulePaths = [...submoduleSet].sort();
146
+ base.touchesSubmodule = submoduleSet.size > 0;
147
+ return base;
148
+ } catch (e: any) {
149
+ base.error = e?.message || String(e);
150
+ return base;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Order nodes for batch refinement to minimize cross-sibling conflicts.
156
+ *
157
+ * Heuristic (deterministic, stable):
158
+ * 1. Nodes that do NOT touch any submodule come first — they cannot advance the
159
+ * submodule main, so they never force a later submodule rebase.
160
+ * 2. Within each group, fewer touched top-level paths first (smaller blast radius).
161
+ * 3. Tie-break by node id for determinism.
162
+ *
163
+ * Submodule-touching siblings are intrinsically serial: each one that merges
164
+ * advances oss main, so the next must rebase. Ordering them last keeps the
165
+ * non-submodule merges (which never need a submodule rebase) clean and up front.
166
+ */
167
+ export function orderMeshRefineBatchNodes(
168
+ changeAreas: MeshRefineBatchNodeChangeArea[],
169
+ ): MeshRefineBatchOrderingResult {
170
+ const areaById: Record<string, MeshRefineBatchNodeChangeArea> = {};
171
+ for (const area of changeAreas) areaById[area.nodeId] = area;
172
+
173
+ const ranked = [...changeAreas].sort((a, b) => {
174
+ const aSub = a.touchesSubmodule ? 1 : 0;
175
+ const bSub = b.touchesSubmodule ? 1 : 0;
176
+ if (aSub !== bSub) return aSub - bSub;
177
+ const aBreadth = a.changedTopLevelPaths.length;
178
+ const bBreadth = b.changedTopLevelPaths.length;
179
+ if (aBreadth !== bBreadth) return aBreadth - bBreadth;
180
+ return a.nodeId.localeCompare(b.nodeId);
181
+ });
182
+
183
+ const rationale: string[] = [];
184
+ const nonSub = ranked.filter(a => !a.touchesSubmodule).map(a => a.nodeId);
185
+ const sub = ranked.filter(a => a.touchesSubmodule).map(a => a.nodeId);
186
+ if (nonSub.length) {
187
+ rationale.push(`Non-submodule nodes first (no submodule-main advance, conflict-free ordering): ${nonSub.join(', ')}`);
188
+ }
189
+ if (sub.length) {
190
+ rationale.push(`Submodule-touching nodes last, serialized (each merge advances submodule main, forcing rebase of the next): ${sub.join(', ')}`);
191
+ }
192
+ for (const area of ranked) {
193
+ if (area.error) rationale.push(`Node ${area.nodeId}: change-area analysis degraded (${area.error}); placed with neutral priority.`);
194
+ }
195
+
196
+ return { order: ranked.map(a => a.nodeId), changeAreas: areaById, rationale };
197
+ }
@@ -142,3 +142,90 @@ export function buildMeshAsyncRefineJobs(args: {
142
142
  return (Number.isFinite(bTime) ? bTime : 0) - (Number.isFinite(aTime) ? aTime : 0);
143
143
  });
144
144
  }
145
+
146
+ const TERMINAL_REFINE_STATUSES = new Set<MeshAsyncRefineJobStatus>(['completed', 'failed']);
147
+
148
+ /** Terminal refine jobs older than this (relative to the newest job in the set) are
149
+ * "stale" — already-resolved historical refinery rejections/successes that should not
150
+ * keep inflating the status counts in mesh_status. 6h covers a long working session
151
+ * while still folding multi-day-old residue. */
152
+ export const STALE_TERMINAL_REFINE_WINDOW_MS = 6 * 60 * 60 * 1000;
153
+
154
+ /** Cap on how many recent terminal jobs are counted even if all fall inside the freshness
155
+ * window — prevents a burst of refines from dominating the summary. */
156
+ export const RECENT_TERMINAL_REFINE_CAP = 8;
157
+
158
+ export interface MeshAsyncRefineJobsSummary {
159
+ /** Count of jobs reflected in `byStatus` (active jobs + recent terminal jobs). */
160
+ total: number;
161
+ byStatus: Record<string, number>;
162
+ /** Terminal jobs dropped from the counts because they are stale residue. */
163
+ staleTerminal: number;
164
+ /** Non-terminal (accepted/running) jobs still in flight. */
165
+ activeJobs: MeshAsyncRefineJobSummary[];
166
+ }
167
+
168
+ function jobActivityTime(job: MeshAsyncRefineJobSummary): number {
169
+ const raw = job.lastUpdatedAt || job.completedAt || job.startedAt || '';
170
+ const t = new Date(raw).getTime();
171
+ return Number.isFinite(t) ? t : 0;
172
+ }
173
+
174
+ /**
175
+ * Build a compact summary of refine jobs that folds stale terminal jobs.
176
+ *
177
+ * The full job list (from `buildMeshAsyncRefineJobs`) is derived from a recent ledger
178
+ * window and deduped by jobId, but it still includes every terminal (completed/failed)
179
+ * job that happens to fall in that window — including multi-day-old refinery rejections
180
+ * that have long since been resolved. Those stale terminals inflate `byStatus.failed`
181
+ * and read as "current breakage" when they are historical noise.
182
+ *
183
+ * Active (accepted/running) jobs are always counted. Terminal jobs are counted only when
184
+ * they are recent: within `STALE_TERMINAL_REFINE_WINDOW_MS` of the newest job's activity
185
+ * time AND among the `RECENT_TERMINAL_REFINE_CAP` most-recent terminals. Everything else
186
+ * is folded into `staleTerminal` and excluded from `byStatus`.
187
+ *
188
+ * Freshness is measured relative to the newest job in the set (not wall-clock), so the
189
+ * result is deterministic for a given input — important for tests and for stale-clock
190
+ * environments.
191
+ */
192
+ export function summarizeMeshAsyncRefineJobs(
193
+ jobs: MeshAsyncRefineJobSummary[],
194
+ ): MeshAsyncRefineJobsSummary {
195
+ const activeJobs: MeshAsyncRefineJobSummary[] = [];
196
+ const terminalJobs: MeshAsyncRefineJobSummary[] = [];
197
+ for (const job of jobs) {
198
+ if (TERMINAL_REFINE_STATUSES.has(job.status)) terminalJobs.push(job);
199
+ else activeJobs.push(job);
200
+ }
201
+
202
+ // Newest activity across ALL jobs anchors the freshness window.
203
+ let newest = 0;
204
+ for (const job of jobs) newest = Math.max(newest, jobActivityTime(job));
205
+ const cutoff = newest - STALE_TERMINAL_REFINE_WINDOW_MS;
206
+
207
+ const terminalByRecency = [...terminalJobs].sort(
208
+ (a, b) => jobActivityTime(b) - jobActivityTime(a),
209
+ );
210
+ const freshTerminal = terminalByRecency
211
+ .filter(job => jobActivityTime(job) >= cutoff)
212
+ .slice(0, RECENT_TERMINAL_REFINE_CAP);
213
+ const freshTerminalIds = new Set(freshTerminal.map(job => job.jobId));
214
+
215
+ const byStatus: Record<string, number> = {};
216
+ for (const job of activeJobs) {
217
+ byStatus[job.status] = (byStatus[job.status] ?? 0) + 1;
218
+ }
219
+ for (const job of freshTerminal) {
220
+ byStatus[job.status] = (byStatus[job.status] ?? 0) + 1;
221
+ }
222
+
223
+ const staleTerminal = terminalJobs.length - freshTerminalIds.size;
224
+
225
+ return {
226
+ total: activeJobs.length + freshTerminal.length,
227
+ byStatus,
228
+ staleTerminal,
229
+ activeJobs,
230
+ };
231
+ }
@@ -330,6 +330,68 @@ export function enqueueTask(
330
330
  });
331
331
  }
332
332
 
333
+ /**
334
+ * Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
335
+ * entry so it is attributable to a mission.
336
+ *
337
+ * Direct dispatch normally bypasses the queue entirely — the task lives only in
338
+ * the ledger + mesh_direct_dispatches table, neither of which carries a
339
+ * missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
340
+ * (which both scan the queue for `task.missionId`) count it as 0. When a
341
+ * mission is attached, we materialise the same queue entry shape an enqueued
342
+ * task would have, but pre-assigned to the dispatched node/session and stamped
343
+ * with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
344
+ * → findAssignedBySession) then flips it to completed/failed exactly like a
345
+ * pulled task, so mission total + completed aggregates work with no extra wiring.
346
+ *
347
+ * Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
348
+ * work for the queue to assign, whereas this records work already dispatched
349
+ * out-of-band. They share the missionId stamping rule and mode validation.
350
+ */
351
+ export function recordDirectDispatchTask(
352
+ meshId: string,
353
+ message: string,
354
+ opts: {
355
+ id: string;
356
+ missionId: string;
357
+ assignedNodeId?: string;
358
+ assignedSessionId?: string;
359
+ taskMode?: MeshTaskMode | string;
360
+ dispatchedAt?: string;
361
+ },
362
+ ): MeshWorkQueueEntry | null {
363
+ const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
364
+ if (!missionId) return null;
365
+ const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
366
+ if (!taskId) return null;
367
+ const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
368
+ if (!modeValidation.valid) {
369
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
370
+ }
371
+ const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
372
+ return withQueueLock(meshId, () => {
373
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
374
+ // Already materialised (e.g. retry of the same dispatch) — leave it untouched.
375
+ return null;
376
+ }
377
+ const entry: MeshWorkQueueEntry = {
378
+ id: taskId,
379
+ meshId,
380
+ message,
381
+ status: 'assigned',
382
+ ...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
383
+ missionId,
384
+ ...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
385
+ ...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
386
+ dispatchTimestamp: now,
387
+ createdAt: now,
388
+ updatedAt: now,
389
+ };
390
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
391
+ return entry;
392
+ });
393
+ }
394
+
333
395
  /**
334
396
  * Get all tasks in the queue, optionally filtered by status.
335
397
  */
@@ -1394,7 +1394,18 @@ export class CliProviderInstance implements ProviderInstance {
1394
1394
  // surface the modal so the user can decide.
1395
1395
  return autoApproveActive;
1396
1396
  }
1397
+ // Include the FSM's approval entry seq: two distinct back-to-back
1398
+ // approvals can carry identical message/buttons (common with
1399
+ // claude-cli). Without the seq their signatures collide and the 5s
1400
+ // busy-window re-entry guard below swallows the second auto-approve,
1401
+ // leaving it stuck. The seq is bumped by the FSM on every fresh
1402
+ // waiting_approval entry, so a new approval always yields a new
1403
+ // signature and fires through.
1404
+ const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
1405
+ ? adapterStatus.approvalEntrySeq
1406
+ : 0;
1397
1407
  const signature = [
1408
+ approvalEntrySeq,
1398
1409
  typeof modal?.message === 'string' ? modal.message.trim() : '',
1399
1410
  buttons.join('|'),
1400
1411
  buttonIndex,