@adhdev/daemon-standalone 0.9.82-rc.253 → 0.9.82-rc.254

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.js CHANGED
@@ -32404,6 +32404,30 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
32404
32404
  updateTaskStatus: () => updateTaskStatus,
32405
32405
  validateMeshTaskModeRequest: () => validateMeshTaskModeRequest
32406
32406
  });
32407
+ function detectGitMutation(message) {
32408
+ const re = /\bgit\s+([a-z][a-z0-9-]*)/gi;
32409
+ let match;
32410
+ while ((match = re.exec(message)) !== null) {
32411
+ const sub = match[1].toLowerCase();
32412
+ if (GIT_MUTATION_SUBCOMMANDS.has(sub)) return true;
32413
+ if (sub === "stash") {
32414
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
32415
+ const next = after ? after[1].toLowerCase() : "";
32416
+ if (!GIT_STASH_READONLY_SUBCOMMANDS.has(next)) return true;
32417
+ } else if (sub === "checkout") {
32418
+ return true;
32419
+ } else if (sub === "submodule") {
32420
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
32421
+ const next = after ? after[1].toLowerCase() : "";
32422
+ if (next === "update" || next === "add" || next === "sync" || next === "deinit") return true;
32423
+ } else if (sub === "worktree") {
32424
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
32425
+ const next = after ? after[1].toLowerCase() : "";
32426
+ if (next === "add" || next === "remove" || next === "move" || next === "prune") return true;
32427
+ }
32428
+ }
32429
+ return false;
32430
+ }
32407
32431
  function normalizeMeshTaskMode(value) {
32408
32432
  if (typeof value !== "string") return void 0;
32409
32433
  const normalized = value.trim();
@@ -32417,7 +32441,11 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
32417
32441
  if (taskMode !== "live_debug_readonly") {
32418
32442
  return { valid: true, taskMode, violations: [] };
32419
32443
  }
32420
- const violations = LIVE_DEBUG_READONLY_FORBIDDEN.filter((rule) => rule.pattern.test(message || "")).map((rule) => rule.label);
32444
+ const text = message || "";
32445
+ const violations = LIVE_DEBUG_READONLY_FORBIDDEN.filter((rule) => rule.pattern.test(text)).map((rule) => rule.label);
32446
+ if (detectGitMutation(text)) {
32447
+ violations.push("git_mutation");
32448
+ }
32421
32449
  return {
32422
32450
  valid: violations.length === 0,
32423
32451
  taskMode,
@@ -32744,6 +32772,8 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
32744
32772
  var HISTORICAL_MESH_QUEUE_STATUSES;
32745
32773
  var MESH_TASK_MODES;
32746
32774
  var LIVE_DEBUG_READONLY_FORBIDDEN;
32775
+ var GIT_MUTATION_SUBCOMMANDS;
32776
+ var GIT_STASH_READONLY_SUBCOMMANDS;
32747
32777
  var DEPENDENCY_FAILURE_TERMINALS;
32748
32778
  var init_mesh_work_queue = __esm2({
32749
32779
  "src/mesh/mesh-work-queue.ts"() {
@@ -32757,13 +32787,35 @@ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
32757
32787
  MESH_TASK_MODES = ["code_change", "validation", "live_debug_readonly", "launch_app", "convergence"];
32758
32788
  LIVE_DEBUG_READONLY_FORBIDDEN = [
32759
32789
  { label: "source_edit", pattern: /\b(edit|modify|patch|apply\s+patch|write\s+(?:to\s+)?(?:file|source)|overwrite|delete\s+file|remove\s+file|create\s+file|touch\s+file)\b/i },
32760
- { label: "git_mutation", pattern: /\b(?:git\s+(?:add|commit|push|reset|rebase|clean|checkout|switch|merge|tag|restore|rm|mv|stash|worktree\s+(?:add|remove|move))|push\b)/i },
32761
32790
  { label: "checkpoint", pattern: /\b(checkpoint|mesh_checkpoint)\b/i },
32762
32791
  { label: "deploy_or_version_bump", pattern: /\b(deploy|wrangler\s+deploy|version[-\s]?bump|npm\s+version|release|npm\s+publish|yarn\s+publish|pnpm\s+publish)\b/i },
32763
32792
  { label: "destructive_shell", pattern: /\b(rm\s+-rf|mv\s+\S+\s+\S+|truncate\s|tee\s+\S+|sed\s+-i|shred\b)\b/i },
32764
32793
  { label: "package_install", pattern: /\b(npm\s+(?:install|i|add|link|uninstall|remove)|yarn\s+(?:add|remove|link)|pnpm\s+(?:add|remove|link)|pip\s+install|brew\s+install|apt\s+install|cargo\s+install)\b/i },
32765
32794
  { label: "container_mutation", pattern: /\b(docker\s+(?:build|run|exec|push|tag|rmi|rm|create|start|stop|kill)|kubectl\s+(?:apply|delete|patch|replace|create|scale))\b/i }
32766
32795
  ];
32796
+ GIT_MUTATION_SUBCOMMANDS = /* @__PURE__ */ new Set([
32797
+ "add",
32798
+ "commit",
32799
+ "push",
32800
+ "reset",
32801
+ "rebase",
32802
+ "clean",
32803
+ "switch",
32804
+ "merge",
32805
+ "tag",
32806
+ "restore",
32807
+ "rm",
32808
+ "mv",
32809
+ "cherry-pick",
32810
+ "revert",
32811
+ "pull",
32812
+ "fetch",
32813
+ "am",
32814
+ "apply",
32815
+ "gc",
32816
+ "prune"
32817
+ ]);
32818
+ GIT_STASH_READONLY_SUBCOMMANDS = /* @__PURE__ */ new Set(["list", "show"]);
32767
32819
  DEPENDENCY_FAILURE_TERMINALS = /* @__PURE__ */ new Set(["failed", "cancelled"]);
32768
32820
  }
32769
32821
  });
@@ -35593,12 +35645,11 @@ Next step: ${nextStep}`;
35593
35645
  }
35594
35646
  function reconcilePendingMeshCoordinatorEvents(meshId, events) {
35595
35647
  const backfilled = refineTerminalEventFromLedger(meshId, events);
35596
- if (backfilled.length === 0) return events;
35597
- const terminalJobIds = new Set(backfilled.map((event) => readRefineJobId2(event)).filter(Boolean));
35598
- return [
35599
- ...events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event)))),
35600
- ...backfilled
35601
- ];
35648
+ const terminalJobIds = new Set(
35649
+ [...events.filter((event) => REFINE_TERMINAL_EVENTS.has(event.event)), ...backfilled].map((event) => readRefineJobId2(event)).filter(Boolean)
35650
+ );
35651
+ const reconciled = terminalJobIds.size === 0 ? events : events.filter((event) => !(event.event === "refine:accepted" && terminalJobIds.has(readRefineJobId2(event))));
35652
+ return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
35602
35653
  }
35603
35654
  function trimPendingEventsIfNeeded(path39) {
35604
35655
  try {
@@ -36587,7 +36638,15 @@ Next step: ${nextStep}`;
36587
36638
  return getQueue(meshId, { status: ["assigned"] }).some((task) => task.assignedNodeId === nodeId);
36588
36639
  }
36589
36640
  function sessionHasActiveAssignment(meshId, sessionId) {
36590
- return getQueue(meshId, { status: ["assigned"] }).some((task) => task.assignedSessionId === sessionId);
36641
+ if (getQueue(meshId, { status: ["assigned"] }).some((task) => task.assignedSessionId === sessionId)) {
36642
+ return true;
36643
+ }
36644
+ try {
36645
+ if (getActiveDirectDispatches(meshId).some((d) => d.sessionId === sessionId)) return true;
36646
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
36647
+ } catch {
36648
+ }
36649
+ return false;
36591
36650
  }
36592
36651
  function liveSessionCountForNode(components, meshId, nodeId) {
36593
36652
  return components.instanceManager.getByCategory("cli").filter((inst) => {
@@ -36954,6 +37013,9 @@ Next step: ${nextStep}`;
36954
37013
  function isMeshCoordinatorEvent(eventName) {
36955
37014
  return typeof eventName === "string" && MESH_COORDINATOR_EVENTS.has(eventName);
36956
37015
  }
37016
+ function shouldForceInjectMeshEvent(eventName) {
37017
+ return typeof eventName === "string" && MESH_FORCE_INJECT_EVENTS.has(eventName);
37018
+ }
36957
37019
  function injectMeshSystemMessage(components, args) {
36958
37020
  const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
36959
37021
  const eventNodeId = readNonEmptyString2(args.nodeId) || readNonEmptyString2(args.metadataEvent.meshNodeId);
@@ -37344,10 +37406,14 @@ Next step: ${nextStep}`;
37344
37406
  })) {
37345
37407
  LOG2.info("MeshEvents", `Queued ${args.event} for MCP coordinator (mesh ${args.meshId})`);
37346
37408
  }
37409
+ const forceInject = shouldForceInjectMeshEvent(args.event);
37347
37410
  for (const coord of coordinatorInstances) {
37348
37411
  const coordState = coord.getState();
37349
- LOG2.info("MeshEvents", `Forwarding mesh event to coordinator ${coordState.instanceId}`);
37350
- coord.onEvent("send_message", { input: { text: messageText, textFallback: messageText } });
37412
+ LOG2.info("MeshEvents", `Forwarding mesh event to coordinator ${coordState.instanceId}${forceInject ? " (force)" : ""}`);
37413
+ coord.onEvent("send_message", {
37414
+ input: { text: messageText, textFallback: messageText },
37415
+ ...forceInject ? { force: true } : {}
37416
+ });
37351
37417
  }
37352
37418
  return { success: true, forwarded: coordinatorInstances.length };
37353
37419
  }
@@ -37400,6 +37466,45 @@ Next step: ${nextStep}`;
37400
37466
  }
37401
37467
  function setupMeshEventForwarding(components) {
37402
37468
  components.instanceManager.onEvent((event) => {
37469
+ if (event.event === "agent:ready" || event.event === "agent:generating_completed") {
37470
+ const flushInstanceId = readNonEmptyString2(event.instanceId);
37471
+ if (flushInstanceId) {
37472
+ const flushSource = components.instanceManager.getInstance(flushInstanceId);
37473
+ if (flushSource && flushSource.category === "cli") {
37474
+ const flushState = flushSource.getState();
37475
+ const flushSettings = flushState.settings && typeof flushState.settings === "object" ? flushState.settings : {};
37476
+ const coordinatorMeshId2 = readNonEmptyString2(flushSettings.meshCoordinatorFor);
37477
+ if (coordinatorMeshId2) {
37478
+ const status = readNonEmptyString2(flushState.status).toLowerCase();
37479
+ if (status === "idle") {
37480
+ try {
37481
+ const localDaemonId = readNonEmptyString2(loadConfig2().machineId) || void 0;
37482
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId2, localDaemonId);
37483
+ if (pendingEvents.length > 0) {
37484
+ LOG2.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId2} on coordinator idle`);
37485
+ for (const pending of pendingEvents) {
37486
+ if (!pending.coordinatorMessage) continue;
37487
+ const forcePending = shouldForceInjectMeshEvent(pending.event);
37488
+ flushSource.onEvent("send_message", {
37489
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
37490
+ ...forcePending ? { force: true } : {}
37491
+ });
37492
+ }
37493
+ }
37494
+ } catch (e) {
37495
+ LOG2.warn("MeshEvents", `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
37496
+ }
37497
+ }
37498
+ let hasDirectDispatch = false;
37499
+ try {
37500
+ hasDirectDispatch = getActiveDirectDispatches(coordinatorMeshId2).some((d) => d.sessionId === flushInstanceId) || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId2, flushInstanceId);
37501
+ } catch {
37502
+ }
37503
+ if (!hasDirectDispatch) return;
37504
+ }
37505
+ }
37506
+ }
37507
+ }
37403
37508
  if (!isMeshCoordinatorEvent(event.event)) return;
37404
37509
  const instanceId = readNonEmptyString2(event.instanceId);
37405
37510
  if (!instanceId) return;
@@ -37438,31 +37543,6 @@ Next step: ${nextStep}`;
37438
37543
  metadataEvent: event
37439
37544
  });
37440
37545
  });
37441
- components.instanceManager.onEvent((event) => {
37442
- if (event.event !== "agent:ready" && event.event !== "agent:generating_completed") return;
37443
- const instanceId = readNonEmptyString2(event.instanceId);
37444
- if (!instanceId) return;
37445
- const sourceInstance = components.instanceManager.getInstance(instanceId);
37446
- if (!sourceInstance || sourceInstance.category !== "cli") return;
37447
- const state = sourceInstance.getState();
37448
- const settings = state.settings && typeof state.settings === "object" ? state.settings : {};
37449
- const coordinatorMeshId = readNonEmptyString2(settings.meshCoordinatorFor);
37450
- if (!coordinatorMeshId) return;
37451
- const status = readNonEmptyString2(state.status).toLowerCase();
37452
- if (status !== "idle") return;
37453
- try {
37454
- const localDaemonId = readNonEmptyString2(loadConfig2().machineId) || void 0;
37455
- const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, localDaemonId);
37456
- if (pendingEvents.length === 0) return;
37457
- LOG2.info("MeshEvents", `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
37458
- for (const pending of pendingEvents) {
37459
- if (!pending.coordinatorMessage) continue;
37460
- sourceInstance.onEvent("send_message", { input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage } });
37461
- }
37462
- } catch (e) {
37463
- LOG2.warn("MeshEvents", `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
37464
- }
37465
- });
37466
37546
  }
37467
37547
  var import_fs10;
37468
37548
  var REMOTE_IDLE_SESSION_TTL_MS;
@@ -37477,6 +37557,7 @@ Next step: ${nextStep}`;
37477
37557
  var AUTO_LAUNCH_COOLDOWN_MS;
37478
37558
  var MESH_COORDINATOR_EVENTS;
37479
37559
  var EVENT_TO_LEDGER_KIND;
37560
+ var MESH_FORCE_INJECT_EVENTS;
37480
37561
  var init_mesh_events_coordinator = __esm2({
37481
37562
  "src/mesh/mesh-events-coordinator.ts"() {
37482
37563
  "use strict";
@@ -37522,6 +37603,15 @@ Next step: ${nextStep}`;
37522
37603
  "agent:stopped": "task_failed",
37523
37604
  "monitor:long_generating": "task_stalled"
37524
37605
  };
37606
+ MESH_FORCE_INJECT_EVENTS = /* @__PURE__ */ new Set([
37607
+ "agent:generating_completed",
37608
+ "agent:stopped",
37609
+ "agent:waiting_approval",
37610
+ "refine:completed",
37611
+ "refine:failed",
37612
+ "worktree_bootstrap_complete",
37613
+ "worktree_bootstrap_failed"
37614
+ ]);
37525
37615
  }
37526
37616
  });
37527
37617
  var mesh_events_exports = {};
@@ -58303,7 +58393,12 @@ ${formatManifestValidationIssues2(validation.issues)}`,
58303
58393
  const controls = this.deriveControls(state.id);
58304
58394
  const title = modal?.title ?? this.deriveTitle(state, sections, lines.join("\n"));
58305
58395
  const next = {
58306
- state: { id: state.id, label: state.label, title },
58396
+ // status is derived from the FSM state itself (statusForState), NOT from
58397
+ // whether a modal was parsed this frame. A modal state whose buttons briefly
58398
+ // fail to parse (PTY repaint → deriveModal returns null) must still report
58399
+ // its authoritative status (e.g. 'approval'), so the adapter never collapses
58400
+ // an approval/busy state to idle on a transient modal-parse miss.
58401
+ state: { id: state.id, label: state.label, title, status: statusForState(state) },
58307
58402
  modal,
58308
58403
  controls
58309
58404
  };
@@ -59400,20 +59495,18 @@ ${formatManifestValidationIssues2(validation.issues)}`,
59400
59495
  const state = this.latestState;
59401
59496
  if (!state) return { status: "starting", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
59402
59497
  const modal = this.latestModal;
59403
- const lc = state.id.toLowerCase();
59404
- if (modal) {
59498
+ if (state.status === "approval") {
59405
59499
  return {
59406
59500
  status: "waiting_approval",
59407
59501
  messages: [],
59408
- activeModal: {
59409
- message: modal.title ?? state.label,
59410
- buttons: modal.buttons.map((b) => b.label)
59411
- },
59502
+ // Surface buttons when we have them; an approval state with no parsed
59503
+ // modal this frame still stays waiting_approval (no activeModal yet).
59504
+ activeModal: modal ? { message: modal.title ?? state.label, buttons: modal.buttons.map((b) => b.label) } : null,
59412
59505
  activeInteractivePrompt: this.activeInteractivePrompt,
59413
59506
  ...sessionFields
59414
59507
  };
59415
59508
  }
59416
- if (lc === "busy" || lc === "generating") {
59509
+ if (state.status === "generating") {
59417
59510
  return { status: "generating", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
59418
59511
  }
59419
59512
  return { status: "idle", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
@@ -60126,7 +60219,6 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60126
60219
  runtimeMessages = [];
60127
60220
  lastPersistedHistoryMessages = [];
60128
60221
  lastAcknowledgedUserInputAt = 0;
60129
- externalBusyIdleFingerprint = "";
60130
60222
  lastNativeSourceCanonicalCheckAt = 0;
60131
60223
  lastNativeSourceCanonicalCacheKey = void 0;
60132
60224
  cachedSqliteDb = null;
@@ -60257,10 +60349,6 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60257
60349
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
60258
60350
  const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === "idle";
60259
60351
  let visibleStatus = parseErrorMessage || parsedStatus?.status === "error" ? "error" : autoApproveActive || autoApproveHoldIdle ? "generating" : adapterStatus.status;
60260
- const externalNativeFinal = this.getExternalNativeFinalReconciliation(parsedStatus?.messages, adapterStatus);
60261
- if (externalNativeFinal && isCliGeneratingLikeStatus(visibleStatus)) {
60262
- visibleStatus = "idle";
60263
- }
60264
60352
  if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === "idle") {
60265
60353
  visibleStatus = "idle";
60266
60354
  }
@@ -60493,7 +60581,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60493
60581
  assertProviderSupportsDeclaredInput(this.provider, input);
60494
60582
  const promptText = buildCliStructuredInputPrompt(input);
60495
60583
  if (promptText) {
60496
- void this.adapter.sendMessage(promptText).catch((e) => {
60584
+ const force = data?.force === true;
60585
+ void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e) => {
60497
60586
  LOG2.warn("CLI", `[${this.type}] send_message failed: ${e?.message || e}`);
60498
60587
  });
60499
60588
  }
@@ -60538,7 +60627,6 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60538
60627
  if (!content) return;
60539
60628
  const receivedAt = Date.now();
60540
60629
  this.lastAcknowledgedUserInputAt = receivedAt;
60541
- this.externalBusyIdleFingerprint = "";
60542
60630
  const dedupKey = `user_input_ack:${crypto4.createHash("sha256").update(`${this.instanceId}:${content}:${receivedAt}`).digest("hex").slice(0, 24)}`;
60543
60631
  this.appendRuntimeMessage(buildChatMessage({
60544
60632
  role: "user",
@@ -60687,50 +60775,6 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60687
60775
  const evidence = this.completionFinalAssistantEvidence(parsedMessages);
60688
60776
  return extractFinalSummaryFromMessages(evidence.messages);
60689
60777
  }
60690
- externalNativeFinalFingerprint(evidence) {
60691
- const messages = Array.isArray(evidence.messages) ? evidence.messages : [];
60692
- const visibleMessages = messages.filter((message) => isUserFacingChatMessage(message));
60693
- const lastVisible = visibleMessages[visibleMessages.length - 1];
60694
- const content = lastVisible ? flattenContent(lastVisible.content).trim() : "";
60695
- const receivedAt = lastVisible ? getMessageTime(lastVisible) : 0;
60696
- const probe = this.lastExternalCompletionProbe;
60697
- return crypto4.createHash("sha256").update([
60698
- this.type,
60699
- this.providerSessionId || "",
60700
- probe?.sourcePath || "",
60701
- String(probe?.sourceMtimeMs || 0),
60702
- String(receivedAt || 0),
60703
- content.slice(-500)
60704
- ].join("\0")).digest("hex").slice(0, 24);
60705
- }
60706
- getExternalNativeFinalReconciliation(parsedMessages, adapterStatus) {
60707
- const rawStatus = typeof adapterStatus?.status === "string" ? adapterStatus.status.trim() : "";
60708
- if (!isCliGeneratingLikeStatus(rawStatus)) return null;
60709
- if (hasNonEmptyCliModalButtons(adapterStatus?.activeModal ?? adapterStatus?.modal)) return null;
60710
- const evidence = this.completionFinalAssistantEvidence(parsedMessages);
60711
- if (evidence.source !== "external-native" || !evidence.present) return null;
60712
- const messages = Array.isArray(evidence.messages) ? evidence.messages : [];
60713
- const visibleMessages = messages.filter((message) => isUserFacingChatMessage(message));
60714
- const lastVisible = visibleMessages[visibleMessages.length - 1];
60715
- const lastMessageAt = lastVisible ? getMessageTime(lastVisible) : 0;
60716
- const sourceMtimeMs = Number(this.lastExternalCompletionProbe?.sourceMtimeMs || 0);
60717
- const minEvidenceAt = Math.max(
60718
- this.startedAt > 0 ? this.startedAt - 5e3 : 0,
60719
- this.generatingStartedAt > 0 ? this.generatingStartedAt - 5e3 : 0,
60720
- this.lastAcknowledgedUserInputAt > 0 ? this.lastAcknowledgedUserInputAt - 1e3 : 0
60721
- );
60722
- if (minEvidenceAt > 0 && lastMessageAt > 0 && lastMessageAt < minEvidenceAt && sourceMtimeMs < minEvidenceAt) {
60723
- return null;
60724
- }
60725
- const finalSummary = extractFinalSummaryFromMessages(evidence.messages);
60726
- if (!finalSummary) return null;
60727
- const fingerprint = this.externalNativeFinalFingerprint(evidence);
60728
- if (fingerprint === this.externalBusyIdleFingerprint) {
60729
- return { fingerprint, finalSummary, evidence };
60730
- }
60731
- this.externalBusyIdleFingerprint = fingerprint;
60732
- return { fingerprint, finalSummary, evidence };
60733
- }
60734
60778
  buildCompletedFinalizationDiagnostic(args) {
60735
60779
  let parsed = null;
60736
60780
  let parseError;
@@ -60801,18 +60845,17 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60801
60845
  if (typeof adapterAny?.responseBuffer === "string" && adapterAny.responseBuffer.trim()) return false;
60802
60846
  return true;
60803
60847
  }
60804
- getCompletedFinalizationBlock(latestVisibleStatus, pending, opts) {
60848
+ getCompletedFinalizationBlock(latestVisibleStatus, pending) {
60805
60849
  if (latestVisibleStatus !== "idle") return { reason: `status:${latestVisibleStatus}`, terminal: true };
60806
60850
  const adapterAny = this.adapter;
60807
60851
  const approvalResolvedIdle = pending.previousStatus === "waiting_approval";
60808
- const externalNativeFinal = opts?.externalNativeFinal || null;
60809
- if (!approvalResolvedIdle && !externalNativeFinal) {
60852
+ if (!approvalResolvedIdle) {
60810
60853
  if (adapterAny?.isWaitingForResponse === true) return { reason: "adapter_waiting_for_response", terminal: true };
60811
60854
  if (adapterAny?.currentTurnScope) return { reason: "adapter_turn_scope_active", terminal: true };
60812
60855
  if (this.hasAdapterPendingResponse()) return { reason: "adapter_pending_response", terminal: true };
60813
60856
  }
60814
60857
  const partial2 = typeof this.adapter.getPartialResponse === "function" ? this.adapter.getPartialResponse() : "";
60815
- if (!externalNativeFinal && typeof partial2 === "string" && partial2.trim()) return { reason: "partial_response_pending", terminal: true };
60858
+ if (typeof partial2 === "string" && partial2.trim()) return { reason: "partial_response_pending", terminal: true };
60816
60859
  let parsed;
60817
60860
  try {
60818
60861
  parsed = this.adapter.getScriptParsedStatus();
@@ -60822,7 +60865,6 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60822
60865
  const parsedStatus = typeof parsed?.status === "string" ? parsed.status : "unknown";
60823
60866
  if (parsedStatus !== "idle") {
60824
60867
  const adapterStatus = this.adapter.getStatus({ allowParse: false });
60825
- if (externalNativeFinal && isCliGeneratingLikeStatus(parsedStatus)) return null;
60826
60868
  if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
60827
60869
  return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
60828
60870
  }
@@ -60884,16 +60926,15 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60884
60926
  }
60885
60927
  const latestStatus = this.adapter.getStatus({ allowParse: false });
60886
60928
  const latestAutoApproveActive = latestStatus.status === "waiting_approval" && this.shouldAutoApprove();
60887
- const externalNativeFinal = this.getExternalNativeFinalReconciliation(void 0, latestStatus);
60888
- const latestVisibleStatus = externalNativeFinal && isCliGeneratingLikeStatus(latestStatus.status) ? "idle" : latestAutoApproveActive || this.autoApproveBusy ? "generating" : latestStatus.status;
60889
- LOG2.debug("CLI", `[${this.type}] flush attempt: adapterStatus=${latestStatus.status} latestVisible=${latestVisibleStatus} externalNativeFinal=${!!externalNativeFinal} generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!this.adapter?.isWaitingForResponse} hasPartial=${!!this.adapter.getPartialResponse?.()}`);
60929
+ const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? "generating" : latestStatus.status;
60930
+ LOG2.debug("CLI", `[${this.type}] flush attempt: adapterStatus=${latestStatus.status} latestVisible=${latestVisibleStatus} generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!this.adapter?.isWaitingForResponse} hasPartial=${!!this.adapter.getPartialResponse?.()}`);
60890
60931
  if (latestVisibleStatus !== "idle") {
60891
60932
  LOG2.info("CLI", `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
60892
60933
  this.completedDebouncePending = null;
60893
60934
  this.completedDebounceTimer = null;
60894
60935
  return;
60895
60936
  }
60896
- const block2 = this.getCompletedFinalizationBlock(latestVisibleStatus, pending, { externalNativeFinal });
60937
+ const block2 = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
60897
60938
  if (block2) {
60898
60939
  const blockReason = block2.reason;
60899
60940
  const waitedMs = Date.now() - pending.firstObservedAt;
@@ -60935,18 +60976,7 @@ ${formatManifestValidationIssues2(validation.issues)}`,
60935
60976
  chatTitle: pending.chatTitle,
60936
60977
  duration: pending.duration,
60937
60978
  timestamp: pending.timestamp,
60938
- finalSummary: externalNativeFinal?.finalSummary || this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
60939
- ...externalNativeFinal ? {
60940
- completionDiagnostic: {
60941
- providerType: this.type,
60942
- sessionId: this.instanceId,
60943
- providerSessionId: this.providerSessionId || null,
60944
- reconciliationReason: "external_native_final_assistant_while_adapter_busy",
60945
- finalAssistantPresent: true,
60946
- finalAssistantEvidenceSource: externalNativeFinal.evidence.source,
60947
- externalFinalFingerprint: externalNativeFinal.fingerprint
60948
- }
60949
- } : {}
60979
+ finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages)
60950
60980
  });
60951
60981
  this.completedDebouncePending = null;
60952
60982
  this.completedDebounceTimer = null;
@@ -61002,9 +61032,8 @@ ${formatManifestValidationIssues2(validation.issues)}`,
61002
61032
  const parsedStatus = null;
61003
61033
  const rawStatus = adapterStatus.status;
61004
61034
  const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
61005
- const externalNativeFinal = this.getExternalNativeFinalReconciliation(void 0, adapterStatus);
61006
61035
  const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === "idle";
61007
- const newStatus = externalNativeFinal && isCliGeneratingLikeStatus(rawStatus) ? "idle" : autoApproveActive || autoApproveHoldIdle ? "generating" : rawStatus;
61036
+ const newStatus = autoApproveActive || autoApproveHoldIdle ? "generating" : rawStatus;
61008
61037
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
61009
61038
  const chatTitle = `${this.provider.name} \xB7 ${dirName}`;
61010
61039
  const partial2 = this.adapter.getPartialResponse();
@@ -69101,16 +69130,26 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
69101
69130
  const nodeId = readInlineMeshNodeId(node);
69102
69131
  if (nodeId) cachedById.set(nodeId, node);
69103
69132
  }
69133
+ const mergedIncomingIds = /* @__PURE__ */ new Set();
69104
69134
  const nodes = incomingNodes.map((incomingNode) => {
69105
69135
  const nodeId = readInlineMeshNodeId(incomingNode);
69106
69136
  const cachedNode = nodeId ? cachedById.get(nodeId) : void 0;
69107
69137
  if (!cachedNode && preserveCachedMembership) return null;
69138
+ if (nodeId) mergedIncomingIds.add(nodeId);
69108
69139
  if (!cachedNode) return incomingNode;
69109
69140
  if (hasInlineMeshTransientNodeState(incomingNode)) {
69110
69141
  return { ...cachedNode, ...incomingNode };
69111
69142
  }
69112
69143
  return { ...stripInlineMeshTransientNodeState(cachedNode), ...incomingNode };
69113
69144
  }).filter(Boolean);
69145
+ if (preserveCachedMembership) {
69146
+ for (const cachedNode of cachedNodes) {
69147
+ const nodeId = readInlineMeshNodeId(cachedNode);
69148
+ if (nodeId && !mergedIncomingIds.has(nodeId)) {
69149
+ nodes.push(cachedNode);
69150
+ }
69151
+ }
69152
+ }
69114
69153
  return {
69115
69154
  ...cached2,
69116
69155
  ...incoming,
@@ -73522,7 +73561,7 @@ ${tail}` : ""
73522
73561
  const ownerFailure = await this.requireMeshHostMutationOwner(meshId, args?.inlineMesh, "worktree clone");
73523
73562
  if (ownerFailure) return ownerFailure;
73524
73563
  try {
73525
- const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh);
73564
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
73526
73565
  const mesh = meshRecord?.mesh;
73527
73566
  if (!mesh) return { success: false, error: "Mesh not found" };
73528
73567
  const sourceNode = mesh.nodes?.find((n) => n.id === sourceNodeId || n.nodeId === sourceNodeId);
@@ -73573,6 +73612,8 @@ ${tail}` : ""
73573
73612
  policy: { ...sourceNode.policy || {} }
73574
73613
  });
73575
73614
  if (!node) return { success: false, error: "Failed to register worktree node" };
73615
+ const inlineForReconcile = this.getCachedInlineMesh(meshId);
73616
+ if (inlineForReconcile) this.updateInlineMeshNode(meshId, inlineForReconcile, node);
73576
73617
  this.invalidateAggregateMeshStatus(meshId);
73577
73618
  }
73578
73619
  const persistWorktreeSetupState = async (bootstrapState2) => {