@adhdev/daemon-core 0.9.82-rc.297 → 0.9.82-rc.299

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.
@@ -2,6 +2,11 @@ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
2
2
  export declare function __resetIdleAutoFastForwardForTests(): void;
3
3
  export declare function __resetMeshWorkspaceCacheForTests(): void;
4
4
  export declare function tryAssignQueueTask(components: DaemonComponents, meshId: string, nodeId: string, sessionId: string, providerType: string): boolean;
5
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
6
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
7
+ export declare function activeWriteAssignedCount(meshId: string): number;
8
+ /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
9
+ export declare function activeReadonlyAssignedCount(meshId: string): number;
5
10
  export interface MeshQueueTriggerResult {
6
11
  success: true;
7
12
  meshId: string;
@@ -30,6 +30,10 @@ export declare class MeshRuntimeStore {
30
30
  updateQueueEntry(entry: MeshWorkQueueEntry): void;
31
31
  findQueueEntryById(meshId: string, id: string): MeshWorkQueueEntry | null;
32
32
  hasActiveAssignment(meshId: string, sessionId: string, nodeId: string): boolean;
33
+ /** A session may only execute one task at a time, regardless of task mode. */
34
+ private hasActiveSessionAssignment;
35
+ /** A node may only execute one write task at a time (worktree isolation). */
36
+ private hasActiveNodeAssignment;
33
37
  claimNextQueueTask(meshId: string, nodeId: string, sessionId: string, capabilityTags?: string[]): MeshWorkQueueEntry | null;
34
38
  getQueueStatsByStatus(meshId: string): {
35
39
  status: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "0.9.82-rc.297",
3
+ "version": "0.9.82-rc.299",
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.297",
49
+ "@adhdev/mesh-shared": "0.9.82-rc.299",
50
50
  "@adhdev/session-host-core": "*",
51
51
  "@agentclientprotocol/sdk": "^0.16.1",
52
52
  "ajv": "^8.20.0",
@@ -15,7 +15,7 @@ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
15
15
  import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent, isUnroutableDelegateRejection } from './mesh-routing.js';
16
16
  import { enqueueUnresolvedDelegateForward, peekUnresolvedDelegateForwards, ackUnresolvedDelegateForward } from './mesh-unresolved-forward-outbox.js';
17
17
  import { resolveDelegatedWorkerAutoApprove } from '../repo-mesh-types.js';
18
- import { normalizeMeshNodeId, meshNodeIdMatches } from '@adhdev/mesh-shared';
18
+ import { normalizeMeshNodeId, meshNodeIdMatches, type MeshNodeIdentified } from '@adhdev/mesh-shared';
19
19
  import {
20
20
  findRecentTerminalLedgerEvidence,
21
21
  hasDispatchAfterTerminal,
@@ -109,7 +109,10 @@ function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nod
109
109
  if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
110
110
  if (!isIntentionalCleanupStopEntry(entry)) continue;
111
111
  if (sessionId && entry.sessionId === sessionId) return true;
112
- if (!sessionId && nodeId && entry.nodeId === nodeId) return true;
112
+ // Normalized node-id match (P4): the cleanup-stop entry's node id may be stored as
113
+ // `nodeId` or `node_id` and the `nodeId` arg can be in either form — a raw `===`
114
+ // would miss a genuine intentional-cleanup entry and fail to suppress the stop event.
115
+ if (!sessionId && nodeId && meshNodeIdMatches(entry as unknown as MeshNodeIdentified, nodeId)) return true;
113
116
  }
114
117
  return false;
115
118
  }
@@ -471,6 +474,19 @@ function activeAssignedCount(meshId: string): number {
471
474
  return getQueue(meshId, { status: ['assigned'] as any }).length;
472
475
  }
473
476
 
477
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
478
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
479
+ export function activeWriteAssignedCount(meshId: string): number {
480
+ return getQueue(meshId, { status: ['assigned'] as any })
481
+ .filter(task => task.taskMode !== 'live_debug_readonly').length;
482
+ }
483
+
484
+ /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
485
+ export function activeReadonlyAssignedCount(meshId: string): number {
486
+ return getQueue(meshId, { status: ['assigned'] as any })
487
+ .filter(task => task.taskMode === 'live_debug_readonly').length;
488
+ }
489
+
474
490
  function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
475
491
  return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
476
492
  }
@@ -625,10 +641,22 @@ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, mesh
625
641
  if (!pending.length) return false;
626
642
 
627
643
  const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
644
+ // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
645
+ // write-task parallel cap. To prevent runaway auto-launch they get their own,
646
+ // higher safety cap (2x the write cap).
647
+ const maxReadonlyParallelTasks = Math.max(2, maxParallelTasks * 2);
628
648
  for (const task of pending) {
629
- if (activeAssignedCount(meshId) >= maxParallelTasks) {
649
+ const isReadonly = task.taskMode === 'live_debug_readonly';
650
+ if (isReadonly) {
651
+ if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
652
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
653
+ continue;
654
+ }
655
+ } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
656
+ // Write tasks are capped; skip this one but keep scanning so a later
657
+ // read-only task in the queue can still launch under its own cap.
630
658
  markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
631
- return false;
659
+ continue;
632
660
  }
633
661
  if (task.targetSessionId) {
634
662
  markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
@@ -684,7 +712,10 @@ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, mesh
684
712
  markAutoLaunch(meshId, task.id, { status: 'skipped', reason: localSkipReason, nodeId });
685
713
  continue;
686
714
  }
687
- if (nodeHasActiveAssignment(meshId, nodeId)) {
715
+ // Write tasks keep the one-active-per-node invariant (worktree isolation);
716
+ // read-only (live_debug_readonly) diagnoses may auto-launch onto a node
717
+ // that already has an active assignment.
718
+ if (task.taskMode !== 'live_debug_readonly' && nodeHasActiveAssignment(meshId, nodeId)) {
688
719
  markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
689
720
  continue;
690
721
  }
@@ -4,6 +4,7 @@ import { updateDirectDispatchStatus, cleanupTerminalDirectDispatches } from './m
4
4
  import { markSessionDeliveriesTerminal } from './mesh-delivery-policy.js';
5
5
  import { queuePendingMeshCoordinatorEvent } from './mesh-events-pending.js';
6
6
  import { readNonEmptyString, readRecord, resolveEventSessionId, readWorkerResultMetadata } from './mesh-events-utils.js';
7
+ import { meshNodeIdMatches, type MeshNodeIdentified } from '@adhdev/mesh-shared';
7
8
 
8
9
  // ---------------------------------------------------------------------------
9
10
  // Stale direct-dispatch detection & transcript reconciliation
@@ -25,7 +26,13 @@ export function findRecentTerminalLedgerEvidence(args: {
25
26
  if (args.sessionId && entry.sessionId === args.sessionId) {
26
27
  return { id: entry.id, kind: entry.kind, payload: entry.payload || {}, timestamp: entry.timestamp };
27
28
  }
28
- if (!args.sessionId && args.nodeId && entry.nodeId === args.nodeId) {
29
+ // Normalized node-id match (P4): a ledger entry may store its node id as `nodeId`
30
+ // (runtime form) or `node_id` (DB column form leaked onto the object). A raw `===`
31
+ // against args.nodeId drops the entry when the entry's stored form differs from the
32
+ // form the caller passes, so a valid terminal completion goes unfound. meshNodeIdMatches
33
+ // normalizes the entry across all 3 forms before comparing. (The entry's typed shape
34
+ // omits the open index signature MeshNodeIdentified declares, hence the cast.)
35
+ if (!args.sessionId && args.nodeId && meshNodeIdMatches(entry as unknown as MeshNodeIdentified, args.nodeId)) {
29
36
  return { id: entry.id, kind: entry.kind, payload: entry.payload || {}, timestamp: entry.timestamp };
30
37
  }
31
38
  }
@@ -4,6 +4,7 @@ import { hasUnterminalDirectDispatchLedgerEntry } from './mesh-events-stale.js';
4
4
  import { appendLedgerEntry, readLedgerEntries } from './mesh-ledger.js';
5
5
  import { LOG } from '../logging/logger.js';
6
6
  import { readNonEmptyString } from './mesh-events-utils.js';
7
+ import { meshNodeIdMatches } from '@adhdev/mesh-shared';
7
8
 
8
9
  // ---------------------------------------------------------------------------
9
10
  // R1: single-source coordinator routing resolution
@@ -141,13 +142,28 @@ export function resolveWorkerDelegateRouting(
141
142
  const meshId = meshIdFromRuntime || readNonEmptyString(mesh?.id);
142
143
  if (!meshId) return reject('mesh_unresolved');
143
144
 
144
- const targetNode = mesh?.nodes?.find((n: any) => n.workspace === workspace);
145
- const nodeId = readNonEmptyString(targetNode?.id) || runtimeNodeId;
146
- const nodeLabel = targetNode
147
- ? `Node '${targetNode.id}'`
148
- : runtimeNodeId
149
- ? `Node '${runtimeNodeId}'`
150
- : `Agent at ${workspace}`;
145
+ // Node resolution authority: the runtime stamp (meshNodeId) is the worker's
146
+ // own identity, set when the coordinator dispatched/launched it. Trust it FIRST,
147
+ // matched against mesh.nodes with the 3-form normalizer (id / nodeId / node_id).
148
+ // Workspace lookup is only a fallback for workers that never carried a node stamp.
149
+ //
150
+ // This is the P1 fix: a worktree clone and its base node can share the same
151
+ // `workspace`, or a freshly-cloned node may not yet be in mesh.nodes — in either
152
+ // case `.find(n => n.workspace === workspace)` would match the BASE node (or
153
+ // undefined) and stamp the completion event with the wrong/absent nodeId, so the
154
+ // event fails post-hoc node matching and the coordinator never sees the completion.
155
+ // The stamped meshNodeId splits base vs worktree correctly even on shared workspace.
156
+ const stampedNode = runtimeNodeId
157
+ ? mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, runtimeNodeId))
158
+ : undefined;
159
+ const targetNode = stampedNode || mesh?.nodes?.find((n: any) => n.workspace === workspace);
160
+ const nodeId = runtimeNodeId || readNonEmptyString(targetNode?.id);
161
+ // Label off the resolved nodeId (which now prefers the stamp) so a node matched
162
+ // by its `nodeId`/`node_id` form — where `targetNode.id` may be absent — never
163
+ // renders as `Node 'undefined'`.
164
+ const nodeLabel = nodeId
165
+ ? `Node '${nodeId}'`
166
+ : `Agent at ${workspace}`;
151
167
 
152
168
  return {
153
169
  isDelegate: true,
@@ -459,11 +459,37 @@ export class MeshRuntimeStore {
459
459
  return row !== undefined;
460
460
  }
461
461
 
462
+ /** A session may only execute one task at a time, regardless of task mode. */
463
+ private hasActiveSessionAssignment(meshId: string, sessionId: string): boolean {
464
+ const row = this.db.prepare(`
465
+ SELECT 1 FROM mesh_queue
466
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_session_id = ?
467
+ LIMIT 1
468
+ `).get(meshId, sessionId);
469
+ return row !== undefined;
470
+ }
471
+
472
+ /** A node may only execute one write task at a time (worktree isolation). */
473
+ private hasActiveNodeAssignment(meshId: string, nodeId: string): boolean {
474
+ const row = this.db.prepare(`
475
+ SELECT 1 FROM mesh_queue
476
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
477
+ LIMIT 1
478
+ `).get(meshId, nodeId);
479
+ return row !== undefined;
480
+ }
481
+
462
482
  // O(1) claim: transaction ensures only one session claims a pending task
463
483
  claimNextQueueTask(meshId: string, nodeId: string, sessionId: string, capabilityTags: string[] = []): MeshWorkQueueEntry | null {
464
484
  return this.transaction(() => {
465
485
  this.ensureLegacyQueueMigrated(meshId);
466
- if (this.hasActiveAssignment(meshId, sessionId, nodeId)) return null;
486
+ // A session executes one task at a time regardless of mode — block early.
487
+ // The node-level conflict is evaluated per-candidate below so that
488
+ // read-only (live_debug_readonly) tasks can claim concurrently on a node
489
+ // that already has an active assignment, while write tasks keep the
490
+ // one-active-per-node invariant (worktree isolation).
491
+ if (this.hasActiveSessionAssignment(meshId, sessionId)) return null;
492
+ const nodeBusy = this.hasActiveNodeAssignment(meshId, nodeId);
467
493
 
468
494
  // Priority: session-targeted > node-targeted (no session) > unconstrained
469
495
  const rows = [
@@ -508,9 +534,18 @@ export class MeshRuntimeStore {
508
534
  return deps.every(depId => depStatus.get(depId) === 'completed');
509
535
  };
510
536
 
537
+ // Per-candidate node-conflict gate: write tasks (anything other than
538
+ // live_debug_readonly) require an idle node; read-only tasks bypass the
539
+ // node-busy check so N read-only diagnoses can run on one node at once.
540
+ const nodeConflictAllows = (candidate: MeshWorkQueueEntry): boolean => {
541
+ if (candidate.taskMode === 'live_debug_readonly') return true;
542
+ return !nodeBusy;
543
+ };
544
+
511
545
  const entry = candidates.find(candidate =>
512
546
  nodeSatisfiesRequiredTags(candidate.requiredTags, capabilityTags)
513
- && dependenciesSatisfied(candidate));
547
+ && dependenciesSatisfied(candidate)
548
+ && nodeConflictAllows(candidate));
514
549
  if (!entry) return null;
515
550
 
516
551
  const now = new Date().toISOString();