@adhdev/daemon-core 0.9.82-rc.459 → 0.9.82-rc.460

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -404,10 +404,10 @@ function readInjected(value) {
404
404
  }
405
405
  function getDaemonBuildInfo() {
406
406
  if (cached) return cached;
407
- const commit = readInjected(true ? "7f95d1c8a5f682abdc7de49343d5bee688a9f16f" : void 0) ?? "unknown";
408
- const commitShort = readInjected(true ? "7f95d1c8" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
409
- const version = readInjected(true ? "0.9.82-rc.459" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
410
- const builtAt = readInjected(true ? "2026-07-04T13:20:51.551Z" : void 0);
407
+ const commit = readInjected(true ? "f8ce1329d3bdef9564c4130a1e7f0b607738f3cd" : void 0) ?? "unknown";
408
+ const commitShort = readInjected(true ? "f8ce1329" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
409
+ const version = readInjected(true ? "0.9.82-rc.460" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
410
+ const builtAt = readInjected(true ? "2026-07-04T14:24:11.778Z" : void 0);
411
411
  cached = builtAt ? { commit, commitShort, version, builtAt } : { commit, commitShort, version };
412
412
  return cached;
413
413
  }
@@ -3464,6 +3464,33 @@ import * as fs2 from "fs";
3464
3464
  import * as os2 from "os";
3465
3465
  import * as path8 from "path";
3466
3466
  function buildCoordinatorSystemPrompt(ctx) {
3467
+ let prompt = assembleCoordinatorPrompt(ctx, {});
3468
+ if (byteLength2(prompt) <= PROMPT_SOFT_CAP_BYTES) return prompt;
3469
+ if (usesOverrideBase(ctx)) return prompt;
3470
+ const shed = [];
3471
+ prompt = assembleCoordinatorPrompt(ctx, { dropOperatingNotes: true });
3472
+ shed.push("operating notes");
3473
+ if (byteLength2(prompt) <= PROMPT_SOFT_CAP_BYTES) {
3474
+ return appendTruncationNotice(prompt, shed);
3475
+ }
3476
+ prompt = assembleCoordinatorPrompt(ctx, { dropOperatingNotes: true, dropRecentActivity: true });
3477
+ shed.push("recent activity");
3478
+ return appendTruncationNotice(prompt, shed);
3479
+ }
3480
+ function usesOverrideBase(ctx) {
3481
+ if (ctx.mesh.coordinator?.systemPromptOverride?.trim()) return true;
3482
+ return readUserPromptFile(ctx.coordinatorCliType, "md") !== null;
3483
+ }
3484
+ function byteLength2(s2) {
3485
+ return Buffer.byteLength(s2, "utf8");
3486
+ }
3487
+ function appendTruncationNotice(prompt, shed) {
3488
+ if (shed.length === 0) return prompt;
3489
+ return `${prompt}
3490
+
3491
+ _Prompt exceeded the ${Math.floor(PROMPT_SOFT_CAP_BYTES / 1024)}KB soft cap; omitted to fit: ${shed.join(", ")}. Full detail remains in the ledger (\`mesh_task_history\` / \`mesh_record_note\`)._`;
3492
+ }
3493
+ function assembleCoordinatorPrompt(ctx, drop) {
3467
3494
  const { mesh, userInstruction, coordinatorCliType } = ctx;
3468
3495
  const meshOverride = mesh.coordinator?.systemPromptOverride?.trim();
3469
3496
  let base;
@@ -3474,7 +3501,7 @@ function buildCoordinatorSystemPrompt(ctx) {
3474
3501
  if (userOverride !== null) {
3475
3502
  base = expandPromptPlaceholders(userOverride, ctx);
3476
3503
  } else {
3477
- base = buildDefaultCoordinatorPrompt(ctx);
3504
+ base = buildDefaultCoordinatorPrompt(ctx, drop);
3478
3505
  }
3479
3506
  }
3480
3507
  const sections = [base];
@@ -3492,7 +3519,7 @@ ${userInstruction}`);
3492
3519
  }
3493
3520
  return sections.join("\n\n");
3494
3521
  }
3495
- function buildDefaultCoordinatorPrompt(ctx) {
3522
+ function buildDefaultCoordinatorPrompt(ctx, drop = {}) {
3496
3523
  const { mesh, status, coordinatorCliType } = ctx;
3497
3524
  const sections = [];
3498
3525
  sections.push(`You are a **Repo Mesh Coordinator** \u2014 a technical team lead who orchestrates work across multiple agent sessions on a shared Git repository.
@@ -3510,10 +3537,14 @@ Default branch: \`${mesh.defaultBranch}\`` : ""}`);
3510
3537
  if (ctx.missionSection?.trim()) {
3511
3538
  sections.push(ctx.missionSection.trim());
3512
3539
  }
3513
- const recentActivity = buildRecentActivitySection(ctx.recentActivity);
3514
- if (recentActivity) sections.push(recentActivity);
3515
- const operatingNotes = buildOperatingNotesSection(ctx.operatingNotes);
3516
- if (operatingNotes) sections.push(operatingNotes);
3540
+ if (!drop.dropRecentActivity) {
3541
+ const recentActivity = buildRecentActivitySection(ctx.recentActivity);
3542
+ if (recentActivity) sections.push(recentActivity);
3543
+ }
3544
+ if (!drop.dropOperatingNotes) {
3545
+ const operatingNotes = buildOperatingNotesSection(ctx.operatingNotes);
3546
+ if (operatingNotes) sections.push(operatingNotes);
3547
+ }
3517
3548
  sections.push(buildPolicySection(mergeAndNormalizePolicy(void 0, mesh.policy)));
3518
3549
  sections.push(TOOLS_SECTION);
3519
3550
  sections.push(TOOL_EXPOSURE_PREFLIGHT_SECTION);
@@ -3627,6 +3658,7 @@ function buildRecentActivitySection(activity) {
3627
3658
  const assigned = Number.isFinite(activity.assignedTasks) ? Number(activity.assignedTasks) : 0;
3628
3659
  const stalled = Number.isFinite(activity.stalledTasks) ? Number(activity.stalledTasks) : 0;
3629
3660
  const recentFailureCount = Number.isFinite(activity.recentFailureCount) ? Number(activity.recentFailureCount) : failures.length;
3661
+ const windowMinutes = Number.isFinite(activity.windowMinutes) && Number(activity.windowMinutes) > 0 ? Math.floor(Number(activity.windowMinutes)) : 30;
3630
3662
  if (failures.length === 0 && pending === 0 && assigned === 0 && stalled === 0 && recentFailureCount === 0) {
3631
3663
  return "";
3632
3664
  }
@@ -3637,7 +3669,7 @@ function buildRecentActivitySection(activity) {
3637
3669
  if (pending > 0) counts.push(`**${pending}** pending`);
3638
3670
  if (assigned > 0) counts.push(`**${assigned}** assigned`);
3639
3671
  if (stalled > 0) counts.push(`**${stalled}** stalled`);
3640
- if (recentFailureCount > 0) counts.push(`**${recentFailureCount}** failed in the last 30 min`);
3672
+ if (recentFailureCount > 0) counts.push(`**${recentFailureCount}** failed in the last ${windowMinutes} min`);
3641
3673
  if (counts.length) lines.push(`- Queue/ledger: ${counts.join(", ")}.`);
3642
3674
  if (activity.lastActivityAt) lines.push(`- Last ledger activity: ${activity.lastActivityAt}.`);
3643
3675
  if (failures.length > 0) {
@@ -3661,15 +3693,25 @@ function buildOperatingNotesSection(notes) {
3661
3693
  pattern_to_avoid: "pattern to avoid",
3662
3694
  recovery_lesson: "recovery lesson"
3663
3695
  };
3696
+ const omittedCount = Math.max(0, valid.length - OPERATING_NOTES_PROMPT_CAP);
3697
+ const shown = omittedCount > 0 ? valid.slice(-OPERATING_NOTES_PROMPT_CAP) : valid;
3664
3698
  const lines = ["## Operating Notes", ""];
3665
3699
  lines.push("Lessons earlier coordinators on this mesh recorded via `mesh_record_note`. Treat them as accumulated operating knowledge \u2014 apply them. When you learn a durable lesson (a provider quirk, a pattern to avoid, a recovery lesson), record it with `mesh_record_note` so future coordinators inherit it.");
3666
3700
  lines.push("");
3667
- for (const n of valid) {
3701
+ for (const n of shown) {
3668
3702
  const cat = n.category && categoryLabel[n.category] ? `[${categoryLabel[n.category]}] ` : "";
3669
- lines.push(`- ${cat}${n.text.trim()}`);
3703
+ lines.push(`- ${cat}${truncateNote(n.text.trim())}`);
3704
+ }
3705
+ if (omittedCount > 0) {
3706
+ lines.push("");
3707
+ lines.push(`_${omittedCount} older note${omittedCount === 1 ? "" : "s"} omitted (kept in ledger; prune with \`mesh_forget_note\`)._`);
3670
3708
  }
3671
3709
  return lines.join("\n");
3672
3710
  }
3711
+ function truncateNote(text) {
3712
+ if (text.length <= OPERATING_NOTE_MAX_CHARS) return text;
3713
+ return `${text.slice(0, OPERATING_NOTE_MAX_CHARS).trimEnd()}\u2026 [truncated]`;
3714
+ }
3673
3715
  function buildPolicySection(policy) {
3674
3716
  const rules = [];
3675
3717
  if (policy.requirePreTaskCheckpoint) rules.push("- Create a git checkpoint **before** starting each task");
@@ -3708,13 +3750,24 @@ function buildRulesSection(coordinatorCliType) {
3708
3750
  - **Honor per-node instructions.** When a node carries a \u{1F4CC} Node instruction in the nodes section, include the relevant parts of that instruction in the task message you send to that node. Don't paraphrase the instruction into your own words \u2014 quote it verbatim so the worker agent sees exactly what the user wrote.
3709
3751
  - **Mission status does not update itself.** When a mission's tasks are all done or the work is abandoned, explicitly call \`mesh_mission_upsert\` to set status \`completed\` or \`abandoned\`. Never leave a finished mission in \`active\`. All-cancelled tasks with no further work \u2192 \`abandoned\`.
3710
3752
  - **Never fabricate tool results.** Always call the actual tool.
3711
- - **Keep the user informed.** One or two sentences after each delegation round.${coordinatorNote}`;
3753
+ - **Keep the user informed.** One or two sentences after each delegation round.${coordinatorNote}
3754
+
3755
+ ### Task Messaging Requirements
3756
+
3757
+ When you compose the task message you dispatch to a node, include these requirements so the worker follows repo conventions the daemon can't enforce for it:
3758
+
3759
+ - **OSS English commits.** If a task commits anything under \`oss/\` (an AGPL public repo whose history external contributors read), tell the worker explicitly that commit messages in \`oss/\` MUST be English. Root-level commits (proprietary packages) may use any language.
3760
+ - **Scoped test runs.** For a validation or code-change task, instruct the worker to run only the tests covering the changed files (\`vitest run <path>\` or \`-t <name>\`), not the whole suite. Run the full suite only when the task is explicitly a full-suite gate \u2014 a broad daemon-core run is minutes of wall-clock and the biggest source of worker slowness.
3761
+ - **Branch convergence state.** For a worktree task, require the completion report to classify the touched branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. A task that ends on a non-main branch is not complete unless the report names that state and the next step.`;
3712
3762
  }
3713
- var TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, ONBOARDING_SECTION;
3763
+ var PROMPT_SOFT_CAP_BYTES, OPERATING_NOTES_PROMPT_CAP, OPERATING_NOTE_MAX_CHARS, TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, ONBOARDING_SECTION;
3714
3764
  var init_coordinator_prompt = __esm({
3715
3765
  "src/mesh/coordinator-prompt.ts"() {
3716
3766
  "use strict";
3717
3767
  init_repo_mesh_types();
3768
+ PROMPT_SOFT_CAP_BYTES = 60 * 1024;
3769
+ OPERATING_NOTES_PROMPT_CAP = 20;
3770
+ OPERATING_NOTE_MAX_CHARS = 300;
3718
3771
  TOOLS_SECTION = `## Available Tools
3719
3772
 
3720
3773
  | Tool | Purpose |
@@ -4113,6 +4166,54 @@ var init_load_better_sqlite3 = __esm({
4113
4166
  }
4114
4167
  });
4115
4168
 
4169
+ // src/mesh/contracts.ts
4170
+ function defaultScopeForEvent(eventName) {
4171
+ if (SYSTEM_EVENTS.has(eventName)) return "system";
4172
+ if (TERMINAL_TASK_EVENTS.has(eventName)) return "unicast";
4173
+ return "broadcast";
4174
+ }
4175
+ function coordinatorIdentityFromEmitFields(fields) {
4176
+ const daemonId = typeof fields.daemonId === "string" && fields.daemonId.length > 0 ? fields.daemonId : void 0;
4177
+ if (!daemonId) return void 0;
4178
+ const coordinatorRunId = typeof fields.coordinatorRunId === "string" && fields.coordinatorRunId.length > 0 ? fields.coordinatorRunId : daemonId;
4179
+ const sessionId = typeof fields.sessionId === "string" && fields.sessionId.length > 0 ? fields.sessionId : void 0;
4180
+ return sessionId !== void 0 ? { daemonId, coordinatorRunId, sessionId } : { daemonId, coordinatorRunId };
4181
+ }
4182
+ function buildPendingEventEmitStamp(opts) {
4183
+ if (!opts.dispatchedBy) return void 0;
4184
+ let scope = opts.scope ?? defaultScopeForEvent(opts.eventName);
4185
+ let intendedFor = opts.intendedFor;
4186
+ if (scope === "unicast" && !intendedFor) {
4187
+ scope = "broadcast";
4188
+ }
4189
+ if (scope !== "unicast") intendedFor = void 0;
4190
+ return {
4191
+ protocolVersion: MESH_PROTOCOL_VERSION_V2,
4192
+ eventId: opts.eventId,
4193
+ scope,
4194
+ dispatchedBy: opts.dispatchedBy,
4195
+ ...intendedFor ? { intendedFor } : {}
4196
+ };
4197
+ }
4198
+ var MESH_PROTOCOL_VERSION_V2, TERMINAL_TASK_EVENTS, SYSTEM_EVENTS;
4199
+ var init_contracts = __esm({
4200
+ "src/mesh/contracts.ts"() {
4201
+ "use strict";
4202
+ init_dist();
4203
+ MESH_PROTOCOL_VERSION_V2 = "2.0";
4204
+ TERMINAL_TASK_EVENTS = /* @__PURE__ */ new Set([
4205
+ "agent:generating_completed",
4206
+ "agent:stopped",
4207
+ "refine:completed",
4208
+ "refine:failed",
4209
+ "refine:accepted"
4210
+ ]);
4211
+ SYSTEM_EVENTS = /* @__PURE__ */ new Set([
4212
+ "mesh:dispatch_blocked"
4213
+ ]);
4214
+ }
4215
+ });
4216
+
4116
4217
  // src/mesh/mesh-ledger.ts
4117
4218
  var mesh_ledger_exports = {};
4118
4219
  __export(mesh_ledger_exports, {
@@ -4124,6 +4225,7 @@ __export(mesh_ledger_exports, {
4124
4225
  __clearMeshLedgerForTests: () => __clearMeshLedgerForTests,
4125
4226
  appendLedgerEntry: () => appendLedgerEntry,
4126
4227
  appendRemoteLedgerEntries: () => appendRemoteLedgerEntries,
4228
+ buildLedgerOriginatingCoordinatorStamp: () => buildLedgerOriginatingCoordinatorStamp,
4127
4229
  buildTaskCompletionEvidence: () => buildTaskCompletionEvidence,
4128
4230
  buildWorkerTaskFooter: () => buildWorkerTaskFooter,
4129
4231
  compactLedger: () => compactLedger,
@@ -4412,6 +4514,15 @@ function buildTaskCompletionEvidence(opts) {
4412
4514
  }
4413
4515
  };
4414
4516
  }
4517
+ function buildLedgerOriginatingCoordinatorStamp(fields) {
4518
+ const originatingCoordinator = coordinatorIdentityFromEmitFields({
4519
+ daemonId: fields.coordinatorDaemonId,
4520
+ coordinatorRunId: fields.coordinatorRunId,
4521
+ sessionId: fields.coordinatorSessionId
4522
+ });
4523
+ if (!originatingCoordinator) return void 0;
4524
+ return { originatingCoordinator, protocolVersion: MESH_PROTOCOL_VERSION_V2 };
4525
+ }
4415
4526
  function appendLedgerEntry(meshId, partial) {
4416
4527
  if (partial.kind === OPERATING_NOTE_KIND) {
4417
4528
  const text = operatingNoteText(partial.payload);
@@ -4902,6 +5013,7 @@ var init_mesh_ledger = __esm({
4902
5013
  init_config();
4903
5014
  init_dist();
4904
5015
  init_mesh_runtime_store();
5016
+ init_contracts();
4905
5017
  LEDGER_DIR_NAME = "mesh-ledger";
4906
5018
  MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
4907
5019
  COMPACT_THRESHOLD_BYTES = 2 * 1024 * 1024;
@@ -6179,7 +6291,18 @@ var init_mesh_runtime_store = __esm({
6179
6291
  fingerprint TEXT,
6180
6292
  queued_at INTEGER NOT NULL,
6181
6293
  drained INTEGER NOT NULL DEFAULT 0,
6182
- drained_at INTEGER
6294
+ drained_at INTEGER,
6295
+ -- v2 protocol envelope (B2a). All nullable so pre-v2 rows and events
6296
+ -- emitted before a coordinator identity is known coexist as v1. The
6297
+ -- authoritative copy of each also rides inside the payload column; these
6298
+ -- columns exist for queryable idempotency (event_id) and scope-based drain
6299
+ -- filtering without JSON-parsing every row. dispatched_by / intended_for
6300
+ -- hold the JSON-serialized CoordinatorIdentity.
6301
+ protocol_version TEXT,
6302
+ event_id TEXT,
6303
+ scope TEXT,
6304
+ dispatched_by TEXT,
6305
+ intended_for TEXT
6183
6306
  );
6184
6307
 
6185
6308
  CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_mesh_drained
@@ -6215,6 +6338,38 @@ var init_mesh_runtime_store = __esm({
6215
6338
  mesh_id TEXT PRIMARY KEY,
6216
6339
  cursor INTEGER NOT NULL DEFAULT 0
6217
6340
  );
6341
+
6342
+ -- T2 (B2b): persistent acked-hold state for in-flight direct dispatches.
6343
+ -- The reconcile loop's PHASE-4 acked-hold (death-consequence counter,
6344
+ -- fast-track idle streak, live-confirmed flag) used to live only in a
6345
+ -- process-local Map (mesh-reconcile-loop.ts inFlightAckedHoldState), so a
6346
+ -- daemon restart lost it \u2014 re-opening the door to the duplicate-emit / drop
6347
+ -- window that the PHASE-4 transcript synth backstop then had to correct after
6348
+ -- the fact. Persisting it lets the state survive a restart: the loop
6349
+ -- rehydrates the Map from this table on first touch and stays read-through /
6350
+ -- write-through against it thereafter. Keyed by task_id (one hold per
6351
+ -- in-flight dispatch); mesh_id is carried for per-mesh listing / prune.
6352
+ -- hold_reason \u2014 'live' once a conclusive read confirmed the session
6353
+ -- reachable since the ack, else 'unconfirmed' (drives
6354
+ -- the death-backstop's liveConfirmedSinceAck gate).
6355
+ -- held_at \u2014 ms epoch the hold row was first created.
6356
+ -- first_idle_since_ack \u2014 ms epoch of the FIRST tick in the current continuous
6357
+ -- idle-with-final-assistant run (fast-track streak); NULL
6358
+ -- when the streak is broken / not yet started.
6359
+ -- read_failure_count \u2014 consecutive read_chat failures since the last
6360
+ -- conclusive read (death backstop (a)).
6361
+ CREATE TABLE IF NOT EXISTS mesh_inflight_hold (
6362
+ task_id TEXT PRIMARY KEY,
6363
+ mesh_id TEXT,
6364
+ hold_reason TEXT,
6365
+ held_at INTEGER,
6366
+ first_idle_since_ack INTEGER,
6367
+ read_failure_count INTEGER,
6368
+ updated_at INTEGER
6369
+ );
6370
+
6371
+ CREATE INDEX IF NOT EXISTS idx_mesh_inflight_hold_mesh
6372
+ ON mesh_inflight_hold(mesh_id);
6218
6373
  `);
6219
6374
  this.migrateMeshIsolationColumns();
6220
6375
  }
@@ -6262,6 +6417,17 @@ var init_mesh_runtime_store = __esm({
6262
6417
  if (!missionCols.has("source")) {
6263
6418
  this.db.exec(`ALTER TABLE mesh_missions ADD COLUMN source TEXT`);
6264
6419
  }
6420
+ const pendingCols = this.tableColumns("mesh_pending_events");
6421
+ for (const col of ["protocol_version", "event_id", "scope", "dispatched_by", "intended_for"]) {
6422
+ if (!pendingCols.has(col)) {
6423
+ this.db.exec(`ALTER TABLE mesh_pending_events ADD COLUMN ${col} TEXT`);
6424
+ }
6425
+ }
6426
+ this.db.exec(`
6427
+ CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_event_id
6428
+ ON mesh_pending_events(mesh_id, event_id)
6429
+ WHERE event_id IS NOT NULL
6430
+ `);
6265
6431
  } catch (err) {
6266
6432
  if (!loggedMigrationFailure) {
6267
6433
  loggedMigrationFailure = true;
@@ -6478,6 +6644,62 @@ var init_mesh_runtime_store = __esm({
6478
6644
  return current;
6479
6645
  });
6480
6646
  }
6647
+ // ── Acked-Hold State (T2 / B2b) ──────────────────────────────────────────
6648
+ //
6649
+ // Persistent mirror of the reconcile loop's inFlightAckedHoldState Map. Keyed
6650
+ // by task_id (one in-flight dispatch = one hold). These are plain read/write/
6651
+ // delete/list accessors; the read-through/write-through cache and the restart
6652
+ // rehydrate live in mesh-reconcile-loop.ts.
6653
+ mapInflightHoldRow(r) {
6654
+ if (!r) return null;
6655
+ return {
6656
+ taskId: r.task_id,
6657
+ meshId: r.mesh_id ?? null,
6658
+ holdReason: r.hold_reason ?? null,
6659
+ heldAt: r.held_at ?? null,
6660
+ firstIdleSinceAck: r.first_idle_since_ack ?? null,
6661
+ readFailureCount: r.read_failure_count ?? null,
6662
+ updatedAt: r.updated_at ?? null
6663
+ };
6664
+ }
6665
+ upsertInflightHold(entry) {
6666
+ const now = Date.now();
6667
+ this.db.prepare(`
6668
+ INSERT INTO mesh_inflight_hold
6669
+ (task_id, mesh_id, hold_reason, held_at, first_idle_since_ack, read_failure_count, updated_at)
6670
+ VALUES (@taskId, @meshId, @holdReason, @heldAt, @firstIdleSinceAck, @readFailureCount, @updatedAt)
6671
+ ON CONFLICT(task_id) DO UPDATE SET
6672
+ mesh_id = excluded.mesh_id,
6673
+ hold_reason = excluded.hold_reason,
6674
+ first_idle_since_ack = excluded.first_idle_since_ack,
6675
+ read_failure_count = excluded.read_failure_count,
6676
+ updated_at = excluded.updated_at
6677
+ `).run({
6678
+ taskId: entry.taskId,
6679
+ meshId: entry.meshId ?? null,
6680
+ holdReason: entry.holdReason ?? null,
6681
+ heldAt: entry.heldAt ?? now,
6682
+ firstIdleSinceAck: entry.firstIdleSinceAck ?? null,
6683
+ readFailureCount: entry.readFailureCount ?? null,
6684
+ updatedAt: now
6685
+ });
6686
+ this.maybeCheckpointWal();
6687
+ }
6688
+ getInflightHold(taskId) {
6689
+ const row = this.db.prepare(
6690
+ "SELECT * FROM mesh_inflight_hold WHERE task_id = ?"
6691
+ ).get(taskId);
6692
+ return this.mapInflightHoldRow(row);
6693
+ }
6694
+ listInflightHoldsByMesh(meshId) {
6695
+ const rows = this.db.prepare(
6696
+ "SELECT * FROM mesh_inflight_hold WHERE mesh_id = ?"
6697
+ ).all(meshId);
6698
+ return rows.map((r) => this.mapInflightHoldRow(r)).filter((r) => r !== null);
6699
+ }
6700
+ deleteInflightHold(taskId) {
6701
+ this.db.prepare("DELETE FROM mesh_inflight_hold WHERE task_id = ?").run(taskId);
6702
+ }
6481
6703
  /**
6482
6704
  * Count active (status='assigned') tasks on a (node, provider) combination,
6483
6705
  * matched by the assignedProviderType stamped on the payload at claim time.
@@ -7213,8 +7435,9 @@ var init_mesh_runtime_store = __esm({
7213
7435
  insertPendingEvent(event) {
7214
7436
  const result = this.db.prepare(
7215
7437
  `INSERT OR IGNORE INTO mesh_pending_events
7216
- (id, mesh_id, coordinator_daemon_id, event, payload, fingerprint, queued_at)
7217
- VALUES (?, ?, ?, ?, ?, ?, ?)`
7438
+ (id, mesh_id, coordinator_daemon_id, event, payload, fingerprint, queued_at,
7439
+ protocol_version, event_id, scope, dispatched_by, intended_for)
7440
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
7218
7441
  ).run(
7219
7442
  event.id,
7220
7443
  event.meshId,
@@ -7222,7 +7445,12 @@ var init_mesh_runtime_store = __esm({
7222
7445
  event.event,
7223
7446
  JSON.stringify(event.payload ?? {}),
7224
7447
  event.fingerprint ?? null,
7225
- event.queuedAt
7448
+ event.queuedAt,
7449
+ event.protocolVersion ?? null,
7450
+ event.eventId ?? null,
7451
+ event.scope ?? null,
7452
+ event.dispatchedBy ?? null,
7453
+ event.intendedFor ?? null
7226
7454
  );
7227
7455
  this.maybeCheckpointWal();
7228
7456
  return result.changes > 0;
@@ -11289,7 +11517,35 @@ function trimPendingEventsIfNeeded(path44) {
11289
11517
  } catch {
11290
11518
  }
11291
11519
  }
11292
- function queuePendingMeshCoordinatorEvent(event) {
11520
+ function stampPendingEventV2(event, hint) {
11521
+ if (event.protocolVersion === MESH_PROTOCOL_VERSION_V2 && readNonEmptyString2(event.eventId)) {
11522
+ return event;
11523
+ }
11524
+ const dispatchedBy = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
11525
+ daemonId: event.targetCoordinatorDaemonId,
11526
+ coordinatorRunId: hint?.coordinatorRunId,
11527
+ sessionId: event.targetCoordinatorSessionId
11528
+ });
11529
+ const intendedFor = hint?.intendedFor ?? dispatchedBy;
11530
+ const stamp = buildPendingEventEmitStamp({
11531
+ eventName: event.event,
11532
+ eventId: randomUUID8(),
11533
+ dispatchedBy,
11534
+ intendedFor,
11535
+ scope: hint?.scope
11536
+ });
11537
+ if (!stamp) return event;
11538
+ return {
11539
+ ...event,
11540
+ protocolVersion: stamp.protocolVersion,
11541
+ eventId: stamp.eventId,
11542
+ scope: stamp.scope,
11543
+ dispatchedBy: stamp.dispatchedBy,
11544
+ ...stamp.intendedFor ? { intendedFor: stamp.intendedFor } : {}
11545
+ };
11546
+ }
11547
+ function queuePendingMeshCoordinatorEvent(rawEvent, hint) {
11548
+ const event = stampPendingEventV2(rawEvent, hint);
11293
11549
  try {
11294
11550
  if (hasPendingRefineTerminalEventDuplicate(event)) {
11295
11551
  LOG.info("MeshEvents", `Suppressed duplicate pending ${event.event} for refine job ${readRefineJobId2(event)}`);
@@ -11309,7 +11565,16 @@ function queuePendingMeshCoordinatorEvent(event) {
11309
11565
  event: event.event,
11310
11566
  payload: event,
11311
11567
  fingerprint: fingerprint || null,
11312
- queuedAt: event.queuedAt
11568
+ queuedAt: event.queuedAt,
11569
+ // v2 envelope columns (B2a) — all nullable so v1 rows coexist. The
11570
+ // authoritative copy still rides inside `payload`; these columns exist
11571
+ // for queryable idempotency (event_id) and scope-based drain filtering
11572
+ // (scope / intended_for) without JSON-parsing every row.
11573
+ protocolVersion: event.protocolVersion ?? null,
11574
+ eventId: event.eventId ?? null,
11575
+ scope: event.scope ?? null,
11576
+ dispatchedBy: event.dispatchedBy ? JSON.stringify(event.dispatchedBy) : null,
11577
+ intendedFor: event.intendedFor ? JSON.stringify(event.intendedFor) : null
11313
11578
  });
11314
11579
  sqliteOk = true;
11315
11580
  } catch {
@@ -11529,6 +11794,7 @@ var init_mesh_events_pending = __esm({
11529
11794
  init_mesh_runtime_store();
11530
11795
  init_mesh_events_utils();
11531
11796
  init_dist();
11797
+ init_contracts();
11532
11798
  REFINE_TERMINAL_EVENTS = /* @__PURE__ */ new Set(["refine:completed", "refine:failed"]);
11533
11799
  TERMINAL_COMPLETION_EVENTS = /* @__PURE__ */ new Set(["agent:generating_completed", "agent:stopped"]);
11534
11800
  MAX_PENDING_EVENTS_BYTES = 100 * 1024;
@@ -13237,6 +13503,18 @@ function nodeActiveLoad(meshId, nodeId) {
13237
13503
  function resolveSchedulingStrategy(mesh) {
13238
13504
  return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
13239
13505
  }
13506
+ function buildSchedulingPool(localCandidates, remoteCandidates) {
13507
+ const pool = [...localCandidates, ...remoteCandidates].map((c) => ({
13508
+ ...c,
13509
+ nodeId: normalizeMeshNodeId(c.node) ?? c.nodeId
13510
+ }));
13511
+ const uniqueNodes = [...new Set(pool.map((c) => c.nodeId))].map((nodeId, index) => ({
13512
+ nodeId,
13513
+ node: pool.find((c) => meshNodeIdMatches({ id: c.nodeId }, nodeId))?.node,
13514
+ index
13515
+ }));
13516
+ return { pool, uniqueNodes };
13517
+ }
13240
13518
  function orderEligibleNodes(meshId, strategy, nodes, opts) {
13241
13519
  if (strategy === "first_eligible" || nodes.length <= 1) {
13242
13520
  return nodes;
@@ -13775,12 +14053,11 @@ async function triggerMeshQueue(components, meshId) {
13775
14053
  for (const candidate of localCandidates) assignIdleCandidate(candidate);
13776
14054
  for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
13777
14055
  } else {
13778
- const pool = [...localCandidates, ...remoteCandidates];
14056
+ const { pool, uniqueNodes } = buildSchedulingPool(localCandidates, remoteCandidates);
13779
14057
  const baseIndex = /* @__PURE__ */ new Map();
13780
14058
  pool.forEach((c, i) => {
13781
14059
  if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i);
13782
14060
  });
13783
- const uniqueNodes = [...new Set(pool.map((c) => c.nodeId))].map((nodeId, index) => ({ nodeId, node: pool.find((c) => c.nodeId === nodeId)?.node, index }));
13784
14061
  const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
13785
14062
  const rankIndex = new Map(ranked.map((r, i) => [r.nodeId, i]));
13786
14063
  const remaining = [...pool];
@@ -14898,7 +15175,7 @@ function flattenContent(content) {
14898
15175
  if (typeof content === "string") return content;
14899
15176
  return flattenMessageParts(normalizeMessageParts(content));
14900
15177
  }
14901
- var init_contracts = __esm({
15178
+ var init_contracts2 = __esm({
14902
15179
  "src/providers/contracts.ts"() {
14903
15180
  "use strict";
14904
15181
  init_io_contracts();
@@ -15262,7 +15539,7 @@ var DEFAULT_FINAL_SUMMARY_MAX_CHARS, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VI
15262
15539
  var init_chat_message_normalization = __esm({
15263
15540
  "src/providers/chat-message-normalization.ts"() {
15264
15541
  "use strict";
15265
- init_contracts();
15542
+ init_contracts2();
15266
15543
  DEFAULT_FINAL_SUMMARY_MAX_CHARS = 16e3;
15267
15544
  BUILTIN_CHAT_MESSAGE_KINDS = ["standard", "thought", "tool", "terminal", "system"];
15268
15545
  CHAT_MESSAGE_VISIBILITIES = ["user", "debug", "internal", "hidden"];
@@ -15501,7 +15778,7 @@ ${cleanBody}`;
15501
15778
  var init_control_effects = __esm({
15502
15779
  "src/providers/control-effects.ts"() {
15503
15780
  "use strict";
15504
- init_contracts();
15781
+ init_contracts2();
15505
15782
  init_chat_message_normalization();
15506
15783
  }
15507
15784
  });
@@ -17679,6 +17956,85 @@ function resolveAckedTranscriptFastTrackGraceMs() {
17679
17956
  function inFlightSynthKey(meshId, taskId) {
17680
17957
  return `${meshId}::${taskId}`;
17681
17958
  }
17959
+ function taskIdFromSynthKey(meshId, synthKey) {
17960
+ const prefix = `${meshId}::`;
17961
+ return synthKey.startsWith(prefix) ? synthKey.slice(prefix.length) : synthKey;
17962
+ }
17963
+ function holdStore() {
17964
+ try {
17965
+ return MeshRuntimeStore.getInstance();
17966
+ } catch {
17967
+ return void 0;
17968
+ }
17969
+ }
17970
+ function getHoldState(synthKey, meshId) {
17971
+ const cached3 = inFlightAckedHoldState.get(synthKey);
17972
+ if (cached3) return cached3;
17973
+ const store = holdStore();
17974
+ if (!store) return void 0;
17975
+ let row;
17976
+ try {
17977
+ row = store.getInflightHold(taskIdFromSynthKey(meshId, synthKey));
17978
+ } catch {
17979
+ return void 0;
17980
+ }
17981
+ if (!row) return void 0;
17982
+ const state = {
17983
+ liveConfirmedSinceAck: row.holdReason === "live",
17984
+ consecutiveReadFailures: row.readFailureCount ?? 0,
17985
+ ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {}
17986
+ };
17987
+ inFlightAckedHoldState.set(synthKey, state);
17988
+ return state;
17989
+ }
17990
+ function setHoldState(synthKey, meshId, state) {
17991
+ inFlightAckedHoldState.set(synthKey, state);
17992
+ const store = holdStore();
17993
+ if (!store) return;
17994
+ try {
17995
+ store.upsertInflightHold({
17996
+ taskId: taskIdFromSynthKey(meshId, synthKey),
17997
+ meshId,
17998
+ holdReason: state.liveConfirmedSinceAck ? "live" : "unconfirmed",
17999
+ firstIdleSinceAck: state.transcriptIdleSinceMs ?? null,
18000
+ readFailureCount: state.consecutiveReadFailures
18001
+ });
18002
+ } catch {
18003
+ }
18004
+ }
18005
+ function deleteHoldState(synthKey, meshId) {
18006
+ inFlightAckedHoldState.delete(synthKey);
18007
+ const store = holdStore();
18008
+ if (!store) return;
18009
+ try {
18010
+ store.deleteInflightHold(taskIdFromSynthKey(meshId, synthKey));
18011
+ } catch {
18012
+ }
18013
+ }
18014
+ function rehydrateAckedHoldsForMesh(meshId) {
18015
+ if (rehydratedHoldMeshes.has(meshId)) return;
18016
+ rehydratedHoldMeshes.add(meshId);
18017
+ const store = holdStore();
18018
+ if (!store) return;
18019
+ let rows;
18020
+ try {
18021
+ rows = store.listInflightHoldsByMesh(meshId);
18022
+ } catch {
18023
+ return;
18024
+ }
18025
+ for (const row of rows) {
18026
+ const synthKey = inFlightSynthKey(meshId, row.taskId);
18027
+ if (inFlightAckedHoldState.has(synthKey)) continue;
18028
+ inFlightAckedHoldState.set(synthKey, {
18029
+ liveConfirmedSinceAck: row.holdReason === "live",
18030
+ consecutiveReadFailures: row.readFailureCount ?? 0,
18031
+ ...row.firstIdleSinceAck !== null && row.firstIdleSinceAck !== void 0 ? { transcriptIdleSinceMs: row.firstIdleSinceAck } : {}
18032
+ });
18033
+ }
18034
+ if (rows.length > 0) {
18035
+ LOG.info("MeshReconcile", `Rehydrated ${rows.length} persisted acked-hold row(s) for mesh ${meshId} after (re)start`);
18036
+ }
18037
+ }
17682
18038
  function resolveCoordinatorDaemonIds(components) {
17683
18039
  const statusInstanceId = readNonEmptyString2(components.statusInstanceId);
17684
18040
  const machineId = readNonEmptyString2(loadConfig().machineId);
@@ -18470,15 +18826,27 @@ async function reprobeWorkerStatus(components, args) {
18470
18826
  }
18471
18827
  async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId) {
18472
18828
  const dispatches = getActiveDirectDispatches(mesh.id);
18473
- if (dispatches.length === 0) return;
18829
+ rehydrateAckedHoldsForMesh(mesh.id);
18474
18830
  const activeTaskKeys = new Set(
18475
18831
  dispatches.map((d) => readNonEmptyString2(d.taskId)).filter(Boolean).map((taskId) => inFlightSynthKey(mesh.id, taskId))
18476
18832
  );
18833
+ const heldKeys = /* @__PURE__ */ new Set();
18477
18834
  for (const key2 of inFlightAckedHoldState.keys()) {
18478
- if (key2.startsWith(`${mesh.id}::`) && !activeTaskKeys.has(key2)) {
18479
- inFlightAckedHoldState.delete(key2);
18835
+ if (key2.startsWith(`${mesh.id}::`)) heldKeys.add(key2);
18836
+ }
18837
+ const store = holdStore();
18838
+ if (store) {
18839
+ try {
18840
+ for (const row of store.listInflightHoldsByMesh(mesh.id)) {
18841
+ heldKeys.add(inFlightSynthKey(mesh.id, row.taskId));
18842
+ }
18843
+ } catch {
18480
18844
  }
18481
18845
  }
18846
+ for (const key2 of heldKeys) {
18847
+ if (!activeTaskKeys.has(key2)) deleteHoldState(key2, mesh.id);
18848
+ }
18849
+ if (dispatches.length === 0) return;
18482
18850
  const dispatchMeshCommand = components.dispatchMeshCommand;
18483
18851
  const nodeById = new Map(mesh.nodes.map((n) => [n.id, n]));
18484
18852
  for (const dispatch of dispatches) {
@@ -18525,25 +18893,25 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
18525
18893
  if (!payload && !readFailed) continue;
18526
18894
  if (readFailed || !payload) {
18527
18895
  if (isAcked) {
18528
- const prior = inFlightAckedHoldState.get(synthKey);
18896
+ const prior = getHoldState(synthKey, mesh.id);
18529
18897
  const failures = (prior?.consecutiveReadFailures ?? 0) + 1;
18530
18898
  const liveConfirmedSinceAck = prior?.liveConfirmedSinceAck ?? false;
18531
- inFlightAckedHoldState.set(synthKey, { liveConfirmedSinceAck, consecutiveReadFailures: failures });
18899
+ setHoldState(synthKey, mesh.id, { liveConfirmedSinceAck, consecutiveReadFailures: failures });
18532
18900
  if (liveConfirmedSinceAck && failures >= ACKED_DEATH_CONSECUTIVE_READ_FAILURES) {
18533
18901
  LOG.warn("MeshReconcile", `Acked-hold death signal: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read_chat failed ${failures}x consecutively after a live-confirmed ack \u2014 worker session presumed gone mid-turn; releasing the indefinite synth hold to the stranded-reclaim / orphan-prune nets`);
18534
18902
  }
18535
18903
  }
18536
18904
  continue;
18537
18905
  }
18538
- const priorHoldState = inFlightAckedHoldState.get(synthKey);
18539
- inFlightAckedHoldState.set(synthKey, {
18906
+ const priorHoldState = getHoldState(synthKey, mesh.id);
18907
+ setHoldState(synthKey, mesh.id, {
18540
18908
  liveConfirmedSinceAck: true,
18541
18909
  consecutiveReadFailures: 0,
18542
18910
  ...priorHoldState?.transcriptIdleSinceMs !== void 0 ? { transcriptIdleSinceMs: priorHoldState.transcriptIdleSinceMs } : {}
18543
18911
  });
18544
18912
  const nowMs = Date.now();
18545
18913
  if (readChatPayloadStatus(payload) !== "idle") {
18546
- inFlightAckedHoldState.set(synthKey, { liveConfirmedSinceAck: true, consecutiveReadFailures: 0 });
18914
+ setHoldState(synthKey, mesh.id, { liveConfirmedSinceAck: true, consecutiveReadFailures: 0 });
18547
18915
  continue;
18548
18916
  }
18549
18917
  const messages = Array.isArray(payload.messages) ? payload.messages : [];
@@ -18552,12 +18920,12 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
18552
18920
  const ackedAtMs = Date.parse(readNonEmptyString2(dispatch.updatedAt));
18553
18921
  const sinceAckMs = Number.isFinite(ackedAtMs) ? nowMs - ackedAtMs : Number.POSITIVE_INFINITY;
18554
18922
  const deathDeadlineMs = resolveAckedDeathDeadlineMs();
18555
- const holdState = inFlightAckedHoldState.get(synthKey);
18923
+ const holdState = getHoldState(synthKey, mesh.id);
18556
18924
  let fastTrackReady = false;
18557
18925
  if (evidence.finalSummary) {
18558
18926
  const idleSinceMs = holdState?.transcriptIdleSinceMs ?? nowMs;
18559
18927
  if (holdState && holdState.transcriptIdleSinceMs === void 0) {
18560
- inFlightAckedHoldState.set(synthKey, { ...holdState, transcriptIdleSinceMs: idleSinceMs });
18928
+ setHoldState(synthKey, mesh.id, { ...holdState, transcriptIdleSinceMs: idleSinceMs });
18561
18929
  }
18562
18930
  const fastTrackGraceMs = resolveAckedTranscriptFastTrackGraceMs();
18563
18931
  const idleHeldMs = nowMs - idleSinceMs;
@@ -18566,7 +18934,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
18566
18934
  LOG.info("MeshReconcile", `Acked-hold transcript fast-track: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read idle WITH a final assistant message for ${Math.round(idleHeldMs / 1e3)}s continuous (grace ${Math.round(fastTrackGraceMs / 1e3)}s) \u2014 promoting the synth ahead of the ${Math.round(deathDeadlineMs / 1e3)}s death backstop; the worker's real emit was lost/late and a later one no-ops idempotently.`);
18567
18935
  }
18568
18936
  } else if (holdState?.transcriptIdleSinceMs !== void 0) {
18569
- inFlightAckedHoldState.set(synthKey, { ...holdState, transcriptIdleSinceMs: void 0 });
18937
+ setHoldState(synthKey, mesh.id, { ...holdState, transcriptIdleSinceMs: void 0 });
18570
18938
  }
18571
18939
  if (!fastTrackReady && sinceAckMs < deathDeadlineMs) {
18572
18940
  LOG.info("MeshReconcile", `Acked-hold: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read idle ${Number.isFinite(sinceAckMs) ? Math.round(sinceAckMs / 1e3) + "s" : "\u221E"} since the generating_started ack \u2014 HOLDING synth (worker presumed alive; a later real emit is idempotent). Transcript fast-track promotes at ${Math.round(resolveAckedTranscriptFastTrackGraceMs() / 1e3)}s continuous idle-with-final-assistant; death backstop at ${Math.round(deathDeadlineMs / 1e3)}s or on consecutive read failures.`);
@@ -18577,7 +18945,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
18577
18945
  }
18578
18946
  }
18579
18947
  if (realTerminalEmitPendingForTask(mesh.id, taskId)) {
18580
- inFlightAckedHoldState.delete(synthKey);
18948
+ deleteHoldState(synthKey, mesh.id);
18581
18949
  LOG.info("MeshReconcile", `Worker-emit priority: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) has a real terminal completion already queued \u2014 yielding synth to the worker's own emit`);
18582
18950
  continue;
18583
18951
  }
@@ -18597,7 +18965,7 @@ async function reconcileUnterminatedDirectDispatches(components, mesh, selfIds,
18597
18965
  }
18598
18966
  const reprobeStatus = await reprobeWorkerStatus(components, { isLocalNode, nodeDaemonId, readArgs });
18599
18967
  if (reprobeStatus && reprobeStatus !== "idle") {
18600
- inFlightAckedHoldState.delete(synthKey);
18968
+ deleteHoldState(synthKey, mesh.id);
18601
18969
  LOG.info("MeshReconcile", `Live re-probe defer: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read '${reprobeStatus}' at synth-commit time \u2014 worker resumed generating; deferring synth to a later tick`);
18602
18970
  continue;
18603
18971
  }
@@ -18739,7 +19107,7 @@ function setupMeshReconcileLoop(components) {
18739
19107
  }
18740
19108
  };
18741
19109
  }
18742
- var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
19110
+ var DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS, DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, ACKED_DEATH_CONSECUTIVE_READ_FAILURES, inFlightAckedHoldState, rehydratedHoldMeshes, coordinatorModalParkState, heldEventLedgerRecorded, ASSIGNED_STRANDED_DEADLINE_MS, DELIVERED_NO_TURN_DEADLINE_MS, RECLAIM_UNKNOWN_GRACE_TICKS, deliveredNoTurnUnknownStreak, STRICT_SESSION_MATCH_TTL_MS, unresolvedForwardRejectionCounts, MAX_FORWARD_REJECTIONS;
18743
19111
  var init_mesh_reconcile_loop = __esm({
18744
19112
  "src/mesh/mesh-reconcile-loop.ts"() {
18745
19113
  "use strict";
@@ -18766,6 +19134,7 @@ var init_mesh_reconcile_loop = __esm({
18766
19134
  DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12e3;
18767
19135
  ACKED_DEATH_CONSECUTIVE_READ_FAILURES = 3;
18768
19136
  inFlightAckedHoldState = /* @__PURE__ */ new Map();
19137
+ rehydratedHoldMeshes = /* @__PURE__ */ new Set();
18769
19138
  coordinatorModalParkState = /* @__PURE__ */ new Map();
18770
19139
  heldEventLedgerRecorded = /* @__PURE__ */ new Set();
18771
19140
  ASSIGNED_STRANDED_DEADLINE_MS = 5 * 6e4;
@@ -27460,11 +27829,11 @@ var CdpDomHandlers = class {
27460
27829
  };
27461
27830
 
27462
27831
  // src/providers/ide-provider-instance.ts
27463
- init_contracts();
27832
+ init_contracts2();
27464
27833
  import * as crypto2 from "crypto";
27465
27834
 
27466
27835
  // src/providers/extension-provider-instance.ts
27467
- init_contracts();
27836
+ init_contracts2();
27468
27837
 
27469
27838
  // src/providers/status-monitor.ts
27470
27839
  var DEFAULT_MONITOR_CONFIG = {
@@ -29496,7 +29865,7 @@ init_logger();
29496
29865
  init_control_effects();
29497
29866
 
29498
29867
  // src/providers/read-chat-contract.ts
29499
- init_contracts();
29868
+ init_contracts2();
29500
29869
 
29501
29870
  // src/providers/transcript-v2.ts
29502
29871
  var CHAT_CONTRACT_VERSION_V1 = "1.0";
@@ -30941,7 +31310,7 @@ import * as path17 from "path";
30941
31310
  import { randomUUID as randomUUID11 } from "crypto";
30942
31311
 
30943
31312
  // src/commands/chat-commands-read.ts
30944
- init_contracts();
31313
+ init_contracts2();
30945
31314
  import * as path16 from "path";
30946
31315
  init_coordinator_registry();
30947
31316
  init_logger();
@@ -33197,7 +33566,7 @@ async function handleGetChatDebugBundle(h, args) {
33197
33566
  }
33198
33567
 
33199
33568
  // src/commands/chat-commands-write.ts
33200
- init_contracts();
33569
+ init_contracts2();
33201
33570
  init_provider_input_support();
33202
33571
  init_approval_utils();
33203
33572
  init_logger();
@@ -37939,7 +38308,7 @@ import chalk from "chalk";
37939
38308
  init_summary_metadata();
37940
38309
 
37941
38310
  // src/providers/cli-provider-instance.ts
37942
- init_contracts();
38311
+ init_contracts2();
37943
38312
  init_provider_input_support();
37944
38313
  import * as os20 from "os";
37945
38314
  import * as path26 from "path";
@@ -43711,7 +44080,7 @@ ${effect.notification.body || ""}`.trim();
43711
44080
  };
43712
44081
 
43713
44082
  // src/providers/acp-provider-instance.ts
43714
- init_contracts();
44083
+ init_contracts2();
43715
44084
  init_provider_input_support();
43716
44085
  import * as path27 from "path";
43717
44086
  import { Readable, Writable } from "stream";
@@ -44963,7 +45332,7 @@ ${rawInput}` : rawInput;
44963
45332
  };
44964
45333
 
44965
45334
  // src/commands/cli-manager.ts
44966
- init_contracts();
45335
+ init_contracts2();
44967
45336
  init_provider_input_support();
44968
45337
  init_logger();
44969
45338
 
@@ -56155,7 +56524,8 @@ function queueRefineJobEvent(self, event, handle, result) {
56155
56524
  }
56156
56525
  async function appendRefineJobLedger(self, kind, handle, result) {
56157
56526
  try {
56158
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
56527
+ const { appendLedgerEntry: appendLedgerEntry2, buildLedgerOriginatingCoordinatorStamp: buildLedgerOriginatingCoordinatorStamp2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
56528
+ const originatingStamp = kind === "task_dispatched" ? buildLedgerOriginatingCoordinatorStamp2({ coordinatorDaemonId: handle.targetCoordinatorDaemonId }) : void 0;
56159
56529
  appendLedgerEntry2(handle.meshId, {
56160
56530
  kind,
56161
56531
  nodeId: handle.targetNodeId,
@@ -56176,6 +56546,7 @@ async function appendRefineJobLedger(self, kind, handle, result) {
56176
56546
  },
56177
56547
  async: true,
56178
56548
  retryOfJobId: handle.retryOfJobId,
56549
+ ...originatingStamp ? { originatingCoordinator: originatingStamp } : {},
56179
56550
  ...result ? {
56180
56551
  success: result.success === true,
56181
56552
  result,
@@ -57189,7 +57560,8 @@ function queueRefineBatchJobEvent(self, event, handle, result) {
57189
57560
  }
57190
57561
  async function appendRefineBatchJobLedger(self, kind, handle, result) {
57191
57562
  try {
57192
- const { appendLedgerEntry: appendLedgerEntry2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
57563
+ const { appendLedgerEntry: appendLedgerEntry2, buildLedgerOriginatingCoordinatorStamp: buildLedgerOriginatingCoordinatorStamp2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
57564
+ const originatingStamp = kind === "task_dispatched" ? buildLedgerOriginatingCoordinatorStamp2({ coordinatorDaemonId: handle.targetCoordinatorDaemonId }) : void 0;
57193
57565
  appendLedgerEntry2(handle.meshId, {
57194
57566
  kind,
57195
57567
  nodeId: handle.batchLabel,
@@ -57209,6 +57581,7 @@ async function appendRefineBatchJobLedger(self, kind, handle, result) {
57209
57581
  },
57210
57582
  async: true,
57211
57583
  batch: true,
57584
+ ...originatingStamp ? { originatingCoordinator: originatingStamp } : {},
57212
57585
  ...result ? {
57213
57586
  success: result.success === true,
57214
57587
  result