@adhdev/daemon-standalone 0.9.77-rc.41 → 0.9.77-rc.43

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.
@@ -25304,13 +25304,25 @@ async function createWorktree(opts) {
25304
25304
  branch
25305
25305
  };
25306
25306
  }
25307
- async function removeWorktree(repoRoot, worktreePath) {
25307
+ async function removeWorktree(repoRoot, worktreePath, opts = {}) {
25308
25308
  if (!(0, import_fs3.existsSync)(worktreePath)) {
25309
25309
  await pruneWorktrees(repoRoot);
25310
25310
  return { success: true, removedPath: worktreePath };
25311
25311
  }
25312
+ if (opts.requireClean) {
25313
+ const { stdout } = await execFileAsync2("git", ["status", "--porcelain"], {
25314
+ cwd: worktreePath,
25315
+ encoding: "utf8",
25316
+ timeout: GIT_TIMEOUT_MS,
25317
+ maxBuffer: GIT_MAX_BUFFER,
25318
+ windowsHide: true
25319
+ });
25320
+ if (stdout.trim()) {
25321
+ throw new Error(`Refusing to remove dirty worktree: ${worktreePath}`);
25322
+ }
25323
+ }
25312
25324
  try {
25313
- await execFileAsync2("git", ["worktree", "remove", worktreePath, "--force"], {
25325
+ await execFileAsync2("git", ["worktree", "remove", worktreePath], {
25314
25326
  cwd: repoRoot,
25315
25327
  encoding: "utf8",
25316
25328
  timeout: GIT_TIMEOUT_MS,
@@ -25674,6 +25686,7 @@ function addNode(meshId, opts) {
25674
25686
  workspace: opts.workspace.trim(),
25675
25687
  repoRoot: opts.repoRoot,
25676
25688
  daemonId: opts.daemonId,
25689
+ machineId: opts.machineId,
25677
25690
  userOverrides: opts.userOverrides || {},
25678
25691
  policy: opts.policy || {},
25679
25692
  isLocalWorktree: opts.isLocalWorktree,
@@ -25794,6 +25807,7 @@ function buildRulesSection(coordinatorCliType) {
25794
25807
  - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
25795
25808
  - **Never fabricate tool results.** Always call the actual tool; never pretend you did.
25796
25809
  - **Clean up worktree nodes.** After a worktree task completes and its changes are merged or checkpointed, call \`mesh_remove_node\` to free resources.
25810
+ - **Do not strand completed branches.** A checkpointed or clean feature/worktree branch is not done by itself. Merge/refine it to the mesh default branch, or explicitly report one of \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\` with the next action.
25797
25811
  - **Name worktree branches meaningfully.** Use descriptive names like \`feat/auth-refactor\` or \`fix/build-123\`.${coordinatorNote}`;
25798
25812
  }
25799
25813
  function getLedgerDir() {
@@ -34389,6 +34403,13 @@ function cleanupStaleMaterializedImages(dir) {
34389
34403
  } catch {
34390
34404
  }
34391
34405
  }
34406
+ function hasNonEmptyCliModalButtons(activeModal) {
34407
+ const buttons = activeModal?.buttons;
34408
+ return Array.isArray(buttons) && buttons.some((button) => String(button || "").trim().length > 0);
34409
+ }
34410
+ function isCliGeneratingLikeStatus(status) {
34411
+ return status === "generating" || status === "streaming" || status === "long_generating" || status === "starting";
34412
+ }
34392
34413
  function buildCliStructuredInputPrompt(input, options = {}) {
34393
34414
  const promptParts = [];
34394
34415
  const imageRefs = [];
@@ -41114,7 +41135,7 @@ async function shutdownDaemonComponents(components) {
41114
41135
  }
41115
41136
  cdpManagers.clear();
41116
41137
  }
41117
- var path4, import_promises4, import_fs3, import_child_process, import_util3, import_os2, import_path, import_fs4, import_crypto2, import_fs5, import_path2, import_crypto3, import_fs6, import_path3, import_crypto4, import_events2, import_fs7, import_path4, import_crypto5, fs2, path8, os22, os8, os9, path14, import_child_process2, os10, path15, os11, import_child_process3, import_fs8, import_promises5, path, import_util4, import_promises6, path22, path32, fs, os4, path5, import_crypto6, path6, path7, import_fs9, import_path5, import_child_process4, import_fs10, import_os3, path9, import_child_process5, os32, path10, import_fs11, os42, import_child_process6, http, crypto2, fs3, path11, os5, fs4, os6, path12, import_crypto7, fs5, path13, os7, os13, path18, crypto4, import_fs12, import_child_process7, os12, path16, crypto3, fs6, import_module, path17, import_stream2, import_child_process8, import_child_process9, net2, os15, path20, fs7, path19, os14, fs8, path21, os16, import_child_process10, import_crypto8, import_fs13, import_module2, os17, import_path6, os18, import_child_process11, import_child_process12, fs9, os19, path222, import_os4, import_path7, fs10, fs11, path23, os20, import_child_process13, import_os5, http2, fs15, path27, fs12, path24, fs13, path25, fs14, path26, os21, import_child_process14, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __require2, __esm2, __export2, __copyProps2, __toCommonJS2, DEFAULT_MESH_POLICY, init_repo_mesh_types, git_worktree_exports, execFileAsync2, WORKTREE_DIR_NAME, GIT_TIMEOUT_MS, GIT_MAX_BUFFER, init_git_worktree, config_exports, DEFAULT_CONFIG, MACHINE_ID_PREFIX, init_config, mesh_config_exports, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, init_mesh_config, coordinator_prompt_exports, TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, init_coordinator_prompt, mesh_ledger_exports, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, meshLedgerEvents, init_mesh_ledger, mesh_work_queue_exports, init_mesh_work_queue, LEVEL_NUM, LEVEL_LABEL, currentLevel, LOG_DIR, MAX_LOG_SIZE, MAX_LOG_DAYS, currentDate, currentLogFile, writeCount, RING_BUFFER_SIZE, ringBuffer, origConsoleLog, origConsoleError, origConsoleWarn, LOG, interceptorInstalled, LOG_PATH, init_logger, mesh_events_exports, remoteIdleSessions, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, init_mesh_events, NORMAL_TRACE_BUFFER_SIZE, DEV_TRACE_BUFFER_SIZE, DEFAULT_CONFIG2, currentConfig, init_debug_config, DEFAULT_BINDING_CANDIDATES, cachedBinding, cachedBindingError, GhosttyVtTerminalBackend, init_ghostty_vt_backend, TerminalCtor, XtermTerminalBackend, init_xterm_backend, DEFAULT_SCROLLBACK, loggedTerminalBackends, TerminalScreen, init_terminal_screen, init_spawn_env, cachedPty, NodePtyRuntimeTransport, NodePtyTransportFactory, init_pty_transport, TerminalTranscriptAccumulator, buildCliSpawnEnv, init_provider_cli_shared, init_provider_cli_parse, init_provider_cli_config, init_provider_cli_runtime, provider_cli_adapter_exports, ProviderCliAdapter, init_provider_cli_adapter, execFileAsync, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_BUFFER, GitCommandError, DEFAULT_MAX_FILES, DEFAULT_MAX_BYTES, summarizeGitStatus, InMemoryGitSnapshotStore, DEFAULT_GIT_WORKSPACE_POLL_INTERVAL_MS, MIN_GIT_WORKSPACE_POLL_INTERVAL_MS, GitWorkspaceMonitor, GIT_COMMAND_NAMES, SNAPSHOT_REASONS, FAILURE_REASONS, defaultSnapshotStore, defaultGitCommandServices, BUSY_STATUSES, TERMINAL_STATUSES, TurnSnapshotTracker, MAX_WORKSPACES, MAX_ACTIVITY, MAX_SAVED_SESSIONS, DEFAULT_STATE, BUILTIN_IDE_DEFINITIONS, registeredIDEs, LIVE_LIFECYCLES, DEFAULT_ACTIVE_CHAT_POLL_STATUSES, DEFAULT_CHAT_TAIL_RECENT_MESSAGE_GRACE_MS, LIVE_RUNTIME_LIFECYCLES, DaemonCdpManager, CdpDomHandlers, DEFAULT_MONITOR_CONFIG, StatusMonitor, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET, HISTORY_DIR, RETAIN_DAYS, SAVED_HISTORY_INDEX_VERSION, SAVED_HISTORY_INDEX_FILE, SAVED_HISTORY_INDEX_LOCK_SUFFIX, SAVED_HISTORY_INDEX_LOCK_WAIT_MS, SAVED_HISTORY_INDEX_LOCK_STALE_MS, SAVED_HISTORY_INDEX_LOCK_POLL_MS, SAVED_HISTORY_ROLLUP_THRESHOLD_BYTES, savedHistorySessionCache, savedHistoryFileSummaryCache, savedHistoryBackgroundRefresh, savedHistoryRollupInFlight, ChatHistoryWriter, IDE_PROVIDER_SESSION_CAPABILITIES_BASE, EXTENSION_PROVIDER_SESSION_CAPABILITIES_BASE, ExtensionProviderInstance, VALID_STATUSES, VALID_ROLES, VALID_BUBBLE_STATES, VALID_TURN_STATUSES, DEFAULT_APPROVAL_POSITIVE_HINTS, IdeProviderInstance, DEFAULT_CDP_SCAN_INTERVAL_MS, DEFAULT_CDP_DISCOVERY_INTERVAL_MS, DEFAULT_STATUS_INITIAL_REPORT_DELAY_MS, DEFAULT_STATUS_SERVER_REPORT_INTERVAL_MS, DEFAULT_STATUS_P2P_REPORT_INTERVAL_MS, MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, DEFAULT_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_READY_TIMEOUT_MS, STANDALONE_CDP_SCAN_INTERVAL_MS, DaemonCdpScanner, DaemonCdpInitializer, WORKING_STATUSES, FULL_STATUS_ACTIVE_CHAT_OPTIONS, LIVE_STATUS_ACTIVE_CHAT_OPTIONS, STATUS_MODAL_MESSAGE_LIMIT, STATUS_MODAL_BUTTON_LIMIT, VALID_INPUT_MEDIA_TYPES, VALID_INPUT_STRATEGIES, TEXT_ONLY_MESSAGE_INPUT_SUPPORT, IDE_SESSION_CAPABILITIES, EXTENSION_SESSION_CAPABILITIES, PTY_SESSION_CAPABILITIES, CLI_CHAT_SESSION_CAPABILITIES, ACP_SESSION_CAPABILITIES, globalStore, RECENT_SEND_WINDOW_MS, READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS, HERMES_CLI_STARTING_SEND_SETTLE_MS, recentSendByTarget, DEFAULT_DEBUG_SANITIZE_OPTIONS, SECRET_KEY_PATTERN, KEY_TO_VK, COMMAND_DEBUG_LEVELS, DaemonCommandHandler, IMAGE_MIME_EXTENSIONS, MATERIALIZED_IMAGE_MAX_AGE_MS, MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS, lastMaterializedImageCleanupAt, CachedDatabaseSync, CliProviderInstance, AcpProviderInstance, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager, VALID_CAPABILITY_MEDIA_TYPES, VALID_INPUT_STRATEGIES2, KNOWN_PROVIDER_FIELDS, VALUE_CONTROL_TYPES, ProviderLoader, _providerLoader, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH, READ_DEBUG_ENABLED, recentReadDebugSignatureBySession, UPGRADE_HELPER_ENV, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter, DaemonStatusReporter, DEFAULT_DAEMON_PORT, DAEMON_WS_PATH, ProviderStreamAdapter, DaemonAgentStreamManager, AgentStreamPoller, ProviderInstanceManager, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive, DEV_SERVER_PORT, DevServer, SessionHostRuntimeTransport, SessionHostPtyTransportFactory, DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME, STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, SessionHostCompatibilityError, EXTENSION_CATALOG, SessionRegistry;
41138
+ var path4, import_promises4, import_fs3, import_child_process, import_util3, import_os2, import_path, import_fs4, import_crypto2, import_fs5, import_path2, import_crypto3, import_fs6, import_path3, import_crypto4, import_events2, import_fs7, import_path4, import_crypto5, fs2, path8, os22, os8, os9, path14, import_child_process2, os10, path15, os11, import_child_process3, import_fs8, import_promises5, path, import_util4, import_promises6, path22, path32, fs, os4, path5, import_crypto6, path6, path7, import_fs9, import_path5, import_child_process4, import_fs10, import_os3, path9, import_child_process5, os32, path10, import_fs11, os42, import_child_process6, http, crypto2, fs3, path11, os5, fs4, os6, path12, import_crypto7, fs5, path13, os7, os13, path18, crypto4, import_fs12, import_child_process7, os12, path16, crypto3, fs6, import_module, path17, import_stream2, import_child_process8, import_child_process9, net2, os15, path20, fs7, path19, os14, fs8, path21, os16, import_child_process10, import_crypto8, import_fs13, import_module2, os17, import_path6, os18, import_child_process11, import_child_process12, fs9, os19, path222, import_os4, import_path7, fs10, fs11, path23, os20, import_child_process13, import_os5, http2, fs15, path27, fs12, path24, fs13, path25, fs14, path26, os21, import_child_process14, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __require2, __esm2, __export2, __copyProps2, __toCommonJS2, DEFAULT_MESH_POLICY, init_repo_mesh_types, git_worktree_exports, execFileAsync2, WORKTREE_DIR_NAME, GIT_TIMEOUT_MS, GIT_MAX_BUFFER, init_git_worktree, config_exports, DEFAULT_CONFIG, MACHINE_ID_PREFIX, init_config, mesh_config_exports, SESSION_CLEANUP_MODES, SPAWNED_SESSION_VISIBILITY_MODES, init_mesh_config, coordinator_prompt_exports, TOOLS_SECTION, TOOL_EXPOSURE_PREFLIGHT_SECTION, WORKFLOW_SECTION, init_coordinator_prompt, mesh_ledger_exports, LEDGER_DIR_NAME, MAX_FILE_SIZE_BYTES, RECENT_FAILURE_WINDOW_MS, meshLedgerEvents, init_mesh_ledger, mesh_work_queue_exports, init_mesh_work_queue, LEVEL_NUM, LEVEL_LABEL, currentLevel, LOG_DIR, MAX_LOG_SIZE, MAX_LOG_DAYS, currentDate, currentLogFile, writeCount, RING_BUFFER_SIZE, ringBuffer, origConsoleLog, origConsoleError, origConsoleWarn, LOG, interceptorInstalled, LOG_PATH, init_logger, mesh_events_exports, remoteIdleSessions, MAX_PENDING_EVENTS, pendingMeshCoordinatorEvents, MESH_COORDINATOR_EVENTS, EVENT_TO_LEDGER_KIND, init_mesh_events, NORMAL_TRACE_BUFFER_SIZE, DEV_TRACE_BUFFER_SIZE, DEFAULT_CONFIG2, currentConfig, init_debug_config, DEFAULT_BINDING_CANDIDATES, cachedBinding, cachedBindingError, GhosttyVtTerminalBackend, init_ghostty_vt_backend, TerminalCtor, XtermTerminalBackend, init_xterm_backend, DEFAULT_SCROLLBACK, loggedTerminalBackends, TerminalScreen, init_terminal_screen, init_spawn_env, cachedPty, NodePtyRuntimeTransport, NodePtyTransportFactory, init_pty_transport, TerminalTranscriptAccumulator, buildCliSpawnEnv, init_provider_cli_shared, init_provider_cli_parse, init_provider_cli_config, init_provider_cli_runtime, provider_cli_adapter_exports, ProviderCliAdapter, init_provider_cli_adapter, execFileAsync, DEFAULT_TIMEOUT_MS, DEFAULT_MAX_BUFFER, GitCommandError, DEFAULT_MAX_FILES, DEFAULT_MAX_BYTES, summarizeGitStatus, InMemoryGitSnapshotStore, DEFAULT_GIT_WORKSPACE_POLL_INTERVAL_MS, MIN_GIT_WORKSPACE_POLL_INTERVAL_MS, GitWorkspaceMonitor, GIT_COMMAND_NAMES, SNAPSHOT_REASONS, FAILURE_REASONS, defaultSnapshotStore, defaultGitCommandServices, BUSY_STATUSES, TERMINAL_STATUSES, TurnSnapshotTracker, MAX_WORKSPACES, MAX_ACTIVITY, MAX_SAVED_SESSIONS, DEFAULT_STATE, BUILTIN_IDE_DEFINITIONS, registeredIDEs, LIVE_LIFECYCLES, DEFAULT_ACTIVE_CHAT_POLL_STATUSES, DEFAULT_CHAT_TAIL_RECENT_MESSAGE_GRACE_MS, LIVE_RUNTIME_LIFECYCLES, DaemonCdpManager, CdpDomHandlers, DEFAULT_MONITOR_CONFIG, StatusMonitor, BUILTIN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_VISIBILITIES, CHAT_MESSAGE_TRANSCRIPT_VISIBILITIES, CHAT_MESSAGE_AUDIENCES, CHAT_MESSAGE_SOURCES, CHAT_MESSAGE_ACTIVITY_SOURCES, CHAT_MESSAGE_INTERNAL_SOURCES, KNOWN_CHAT_MESSAGE_KINDS, CHAT_MESSAGE_KIND_ALIASES, EXPLICIT_HIDDEN_VISIBILITIES, EXPLICIT_VISIBLE_VISIBILITIES, HIDDEN_AUDIENCES, ACTIVITY_SOURCE_SET, INTERNAL_SOURCE_SET, HISTORY_DIR, RETAIN_DAYS, SAVED_HISTORY_INDEX_VERSION, SAVED_HISTORY_INDEX_FILE, SAVED_HISTORY_INDEX_LOCK_SUFFIX, SAVED_HISTORY_INDEX_LOCK_WAIT_MS, SAVED_HISTORY_INDEX_LOCK_STALE_MS, SAVED_HISTORY_INDEX_LOCK_POLL_MS, SAVED_HISTORY_ROLLUP_THRESHOLD_BYTES, savedHistorySessionCache, savedHistoryFileSummaryCache, savedHistoryBackgroundRefresh, savedHistoryRollupInFlight, ChatHistoryWriter, IDE_PROVIDER_SESSION_CAPABILITIES_BASE, EXTENSION_PROVIDER_SESSION_CAPABILITIES_BASE, ExtensionProviderInstance, VALID_STATUSES, VALID_ROLES, VALID_BUBBLE_STATES, VALID_TURN_STATUSES, DEFAULT_APPROVAL_POSITIVE_HINTS, IdeProviderInstance, DEFAULT_CDP_SCAN_INTERVAL_MS, DEFAULT_CDP_DISCOVERY_INTERVAL_MS, DEFAULT_STATUS_INITIAL_REPORT_DELAY_MS, DEFAULT_STATUS_SERVER_REPORT_INTERVAL_MS, DEFAULT_STATUS_P2P_REPORT_INTERVAL_MS, MIN_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, DEFAULT_MACHINE_RUNTIME_SUBSCRIPTION_INTERVAL_MS, MIN_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_DIAGNOSTICS_SUBSCRIPTION_INTERVAL_MS, DEFAULT_SESSION_HOST_READY_TIMEOUT_MS, STANDALONE_CDP_SCAN_INTERVAL_MS, DaemonCdpScanner, DaemonCdpInitializer, WORKING_STATUSES, FULL_STATUS_ACTIVE_CHAT_OPTIONS, LIVE_STATUS_ACTIVE_CHAT_OPTIONS, STATUS_MODAL_MESSAGE_LIMIT, STATUS_MODAL_BUTTON_LIMIT, VALID_INPUT_MEDIA_TYPES, VALID_INPUT_STRATEGIES, TEXT_ONLY_MESSAGE_INPUT_SUPPORT, IDE_SESSION_CAPABILITIES, EXTENSION_SESSION_CAPABILITIES, PTY_SESSION_CAPABILITIES, CLI_CHAT_SESSION_CAPABILITIES, ACP_SESSION_CAPABILITIES, globalStore, RECENT_SEND_WINDOW_MS, READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS, HERMES_CLI_STARTING_SEND_SETTLE_MS, recentSendByTarget, DEFAULT_DEBUG_SANITIZE_OPTIONS, SECRET_KEY_PATTERN, KEY_TO_VK, COMMAND_DEBUG_LEVELS, DaemonCommandHandler, COMPLETED_FINALIZATION_RETRY_MS, COMPLETED_FINALIZATION_MAX_WAIT_MS, IMAGE_MIME_EXTENSIONS, MATERIALIZED_IMAGE_MAX_AGE_MS, MATERIALIZED_IMAGE_CLEANUP_INTERVAL_MS, lastMaterializedImageCleanupAt, CachedDatabaseSync, CliProviderInstance, AcpProviderInstance, chalkModule, chalkApi, COORDINATOR_DELEGATED_ENV_UNSETS, DaemonCliManager, VALID_CAPABILITY_MEDIA_TYPES, VALID_INPUT_STRATEGIES2, KNOWN_PROVIDER_FIELDS, VALUE_CONTROL_TYPES, ProviderLoader, _providerLoader, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS, DEFAULT_SERVER_NAME, DEFAULT_ADHDEV_MCP_COMMAND, HERMES_CLI_TYPE, HERMES_MCP_CONFIG_PATH, READ_DEBUG_ENABLED, recentReadDebugSignatureBySession, UPGRADE_HELPER_ENV, CHANNEL_NPM_TAG, CHANNEL_SERVER_URL, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter, DaemonStatusReporter, DEFAULT_DAEMON_PORT, DAEMON_WS_PATH, ProviderStreamAdapter, DaemonAgentStreamManager, AgentStreamPoller, ProviderInstanceManager, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive, DEV_SERVER_PORT, DevServer, SessionHostRuntimeTransport, SessionHostPtyTransportFactory, DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME, STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, SessionHostCompatibilityError, EXTENSION_CATALOG, SessionRegistry;
41118
41139
  var init_dist2 = __esm({
41119
41140
  "../daemon-core/dist/index.mjs"() {
41120
41141
  "use strict";
@@ -41394,6 +41415,7 @@ var init_dist2 = __esm({
41394
41415
  | \`mesh_checkpoint\` | Create a git checkpoint on a node |
41395
41416
  | \`mesh_approve\` | Approve/reject a pending agent action |
41396
41417
  | \`mesh_clone_node\` | Create a worktree node for isolated parallel branch work |
41418
+ | \`mesh_refine_node\` | Validate and merge a completed worktree node back into its base branch |
41397
41419
  | \`mesh_remove_node\` | Remove a node (cleans up worktree if applicable) |`;
41398
41420
  TOOL_EXPOSURE_PREFLIGHT_SECTION = `## Tool Exposure Preflight
41399
41421
 
@@ -41410,8 +41432,9 @@ Before doing any coordinator work, confirm that the actual callable tool list in
41410
41432
  4. **Monitor** \u2014 Prefer event-driven completion/status notifications. Do **not** poll \`mesh_read_chat\` repeatedly. Use \`mesh_view_queue\` to see the status of all pending, assigned, completed, and failed tasks. Do not call \`mesh_read_chat\` again within a few seconds for the same generating session. Use at most one compact \`mesh_read_chat\` check after a completion/approval signal. Handle approvals via \`mesh_approve\`.
41411
41433
  5. **Verify** \u2014 When a task reports completion or git work is visible, call \`mesh_git_status\` to verify changes were made.
41412
41434
  6. **Checkpoint** \u2014 Call \`mesh_checkpoint\` to save the work.
41413
- 7. **Clean up** \u2014 Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
41414
- 8. **Report** \u2014 Summarize what was done, what changed, and any issues.
41435
+ 7. **Converge branches** \u2014 Before marking any task complete, classify every touched node/branch into exactly one final state: \`merged_to_main\`, \`pushed_feature_branch_needs_merge\`, \`blocked_review\`, \`cleanup_candidate\`, or \`not_mergeable\`. Use \`mesh_status\` branchConvergenceSummary and \`mesh_refine_node\` for clean worktree branches when safe. A task that remains on a non-main branch is not fully complete unless the final report names the follow-up state and next step.
41436
+ 8. **Clean up** \u2014 Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
41437
+ 9. **Report** \u2014 Summarize what was done, what changed, any issues, and the branch convergence state.
41415
41438
 
41416
41439
  ## Failure Recovery
41417
41440
 
@@ -41998,6 +42021,7 @@ Follow these recovery rules:
41998
42021
  this.requirePromptEchoBeforeSubmit = resolvedConfig.requirePromptEchoBeforeSubmit;
41999
42022
  this.providerResolutionMeta = resolvedConfig.providerResolutionMeta;
42000
42023
  this.cliScripts = provider.scripts || {};
42024
+ this.scriptState = typeof this.cliScripts.createState === "function" ? this.cliScripts.createState() ?? null : null;
42001
42025
  const scriptNames = listCliScriptNames(this.cliScripts);
42002
42026
  if (scriptNames.length > 0) {
42003
42027
  LOG.info("CLI", `[${this.cliType}] CLI scripts: [${scriptNames.join(", ")}]`);
@@ -42267,7 +42291,7 @@ ${lastSnapshot}`;
42267
42291
  this.cliScripts = scripts;
42268
42292
  this.parsedStatusCache = null;
42269
42293
  this.parseErrorMessage = null;
42270
- this.scriptState = typeof scripts.createState === "function" ? scripts.createState() : null;
42294
+ this.scriptState = typeof scripts.createState === "function" ? scripts.createState() ?? null : null;
42271
42295
  const scriptNames = listCliScriptNames(scripts);
42272
42296
  LOG.info("CLI", `[${this.cliType}] CLI scripts injected: [${scriptNames.join(", ")}]`);
42273
42297
  }
@@ -43310,7 +43334,7 @@ ${lastSnapshot}`;
43310
43334
  scope: this.currentTurnScope,
43311
43335
  runtimeSettings: this.runtimeSettings
43312
43336
  });
43313
- return await Promise.resolve(fn(this.scriptState, {
43337
+ return await Promise.resolve(this.invokeCliScript(fn, {
43314
43338
  ...input,
43315
43339
  args: args && typeof args === "object" ? { ...args } : {}
43316
43340
  }));
@@ -48050,6 +48074,8 @@ ${effect.notification.body || ""}`.trim();
48050
48074
  init_config();
48051
48075
  init_provider_cli_adapter();
48052
48076
  init_logger();
48077
+ COMPLETED_FINALIZATION_RETRY_MS = 1e3;
48078
+ COMPLETED_FINALIZATION_MAX_WAIT_MS = 3e4;
48053
48079
  IMAGE_MIME_EXTENSIONS = {
48054
48080
  "image/png": ".png",
48055
48081
  "image/jpeg": ".jpg",
@@ -48235,10 +48261,12 @@ ${effect.notification.body || ""}`.trim();
48235
48261
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
48236
48262
  const canonicalBackedHistory = this.syncCanonicalSavedHistoryIfNeeded();
48237
48263
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
48264
+ const parsedChatStatus = typeof parsedStatus?.status === "string" && parsedStatus.status.trim() ? parsedStatus.status.trim() : void 0;
48265
+ const suppressStaleParsedBusyStatus = this.shouldSuppressStaleParsedBusyStatus(parsedStatus, adapterStatus);
48238
48266
  if (parsedMessages.length > 0) {
48239
48267
  const shouldSkipReplayPersist = this.suppressIdleHistoryReplay && adapterStatus.status === "idle" && parsedStatus?.status === "idle";
48240
48268
  let messagesToSave = parsedMessages;
48241
- if (parsedStatus?.status === "generating" || parsedStatus?.status === "long_generating") {
48269
+ if (!suppressStaleParsedBusyStatus && (parsedChatStatus === "generating" || parsedChatStatus === "long_generating")) {
48242
48270
  const lastIdx = messagesToSave.length - 1;
48243
48271
  if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === "assistant") {
48244
48272
  messagesToSave = messagesToSave.slice(0, lastIdx);
@@ -48272,6 +48300,7 @@ ${effect.notification.body || ""}`.trim();
48272
48300
  summaryMetadata: this.summaryMetadata,
48273
48301
  controlValues: this.controlValues
48274
48302
  });
48303
+ const activeChatStatus = parseErrorMessage ? "error" : autoApproveActive && parsedStatus?.status === "waiting_approval" ? "generating" : adapterStatus.status !== "idle" ? visibleStatus : suppressStaleParsedBusyStatus ? visibleStatus : parsedChatStatus || visibleStatus;
48275
48304
  return {
48276
48305
  type: this.type,
48277
48306
  name: this.provider.name,
@@ -48281,7 +48310,7 @@ ${effect.notification.body || ""}`.trim();
48281
48310
  activeChat: {
48282
48311
  id: `${this.type}_${this.workingDir}`,
48283
48312
  title: parsedStatus?.title || dirName,
48284
- status: parseErrorMessage ? "error" : autoApproveActive && parsedStatus?.status === "waiting_approval" ? "generating" : adapterStatus.status !== "idle" ? visibleStatus : parsedStatus?.status || visibleStatus,
48313
+ status: activeChatStatus,
48285
48314
  messages: mergedMessages,
48286
48315
  activeModal: autoApproveActive ? null : parsedStatus?.activeModal ?? adapterStatus.activeModal,
48287
48316
  inputContent: ""
@@ -48411,6 +48440,102 @@ ${effect.notification.body || ""}`.trim();
48411
48440
  }
48412
48441
  this.applyProviderResponse(parsed.payload, { phase: "immediate" });
48413
48442
  }
48443
+ completionHasFinalAssistantMessage(messages) {
48444
+ const visibleMessages = (Array.isArray(messages) ? messages : []).filter((message) => isUserFacingChatMessage(message));
48445
+ const lastVisible = visibleMessages[visibleMessages.length - 1];
48446
+ const role = typeof lastVisible?.role === "string" ? lastVisible.role.trim().toLowerCase() : "";
48447
+ const content = lastVisible ? flattenContent(lastVisible.content).trim() : "";
48448
+ return role === "assistant" && !!content;
48449
+ }
48450
+ hasAdapterPendingResponse() {
48451
+ const adapterAny = this.adapter;
48452
+ if (adapterAny?.isWaitingForResponse === true) return true;
48453
+ if (adapterAny?.currentTurnScope) return true;
48454
+ try {
48455
+ if (typeof this.adapter.isProcessing === "function" && this.adapter.isProcessing()) return true;
48456
+ } catch {
48457
+ }
48458
+ try {
48459
+ const partial2 = typeof this.adapter.getPartialResponse === "function" ? this.adapter.getPartialResponse() : "";
48460
+ if (typeof partial2 === "string" && partial2.trim()) return true;
48461
+ } catch {
48462
+ }
48463
+ return false;
48464
+ }
48465
+ shouldSuppressStaleParsedBusyStatus(parsedStatus, adapterStatus) {
48466
+ const parsedRawStatus = typeof parsedStatus?.status === "string" ? parsedStatus.status.trim() : "";
48467
+ const adapterRawStatus = typeof adapterStatus?.status === "string" ? adapterStatus.status.trim() : "";
48468
+ if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
48469
+ if (adapterRawStatus !== "idle") return false;
48470
+ if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
48471
+ return !this.hasAdapterPendingResponse();
48472
+ }
48473
+ getCompletedFinalizationBlockReason(latestVisibleStatus) {
48474
+ if (latestVisibleStatus !== "idle") return `status:${latestVisibleStatus}`;
48475
+ const adapterAny = this.adapter;
48476
+ if (adapterAny?.isWaitingForResponse === true) return "adapter_waiting_for_response";
48477
+ if (adapterAny?.currentTurnScope) return "adapter_turn_scope_active";
48478
+ const partial2 = typeof this.adapter.getPartialResponse === "function" ? this.adapter.getPartialResponse() : "";
48479
+ if (typeof partial2 === "string" && partial2.trim()) return "partial_response_pending";
48480
+ let parsed;
48481
+ try {
48482
+ parsed = this.adapter.getScriptParsedStatus();
48483
+ } catch (error48) {
48484
+ return `parse_error:${error48?.message || String(error48)}`;
48485
+ }
48486
+ const parsedStatus = typeof parsed?.status === "string" ? parsed.status : "unknown";
48487
+ if (parsedStatus !== "idle") return `parsed_status:${parsedStatus}`;
48488
+ if (parsed?.activeModal || parsed?.modal) return "parsed_modal_active";
48489
+ if (!this.completionHasFinalAssistantMessage(parsed?.messages)) return "missing_final_assistant";
48490
+ return null;
48491
+ }
48492
+ scheduleCompletedDebounceFlush(delayMs) {
48493
+ if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
48494
+ this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
48495
+ }
48496
+ flushCompletedDebounceIfFinalized() {
48497
+ const pending = this.completedDebouncePending;
48498
+ if (!pending) {
48499
+ this.completedDebounceTimer = null;
48500
+ return;
48501
+ }
48502
+ const latestStatus = this.adapter.getStatus({ allowParse: false });
48503
+ const latestAutoApproveActive = latestStatus.status === "waiting_approval" && this.shouldAutoApprove();
48504
+ const latestVisibleStatus = latestAutoApproveActive ? "generating" : latestStatus.status;
48505
+ if (latestVisibleStatus !== "idle") {
48506
+ LOG.info("CLI", `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
48507
+ this.completedDebouncePending = null;
48508
+ this.completedDebounceTimer = null;
48509
+ return;
48510
+ }
48511
+ const blockReason = this.getCompletedFinalizationBlockReason(latestVisibleStatus);
48512
+ if (blockReason) {
48513
+ const waitedMs = Date.now() - pending.firstObservedAt;
48514
+ if (waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
48515
+ if (pending.loggedBlockReason !== blockReason) {
48516
+ LOG.info("CLI", `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
48517
+ pending.loggedBlockReason = blockReason;
48518
+ }
48519
+ this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
48520
+ return;
48521
+ }
48522
+ LOG.warn("CLI", `[${this.type}] suppressed completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
48523
+ this.completedDebouncePending = null;
48524
+ this.completedDebounceTimer = null;
48525
+ this.generatingStartedAt = 0;
48526
+ return;
48527
+ }
48528
+ LOG.info("CLI", `[${this.type}] completed in ${pending.duration}s`);
48529
+ this.pushEvent({
48530
+ event: "agent:generating_completed",
48531
+ chatTitle: pending.chatTitle,
48532
+ duration: pending.duration,
48533
+ timestamp: pending.timestamp
48534
+ });
48535
+ this.completedDebouncePending = null;
48536
+ this.completedDebounceTimer = null;
48537
+ this.generatingStartedAt = 0;
48538
+ }
48414
48539
  maybeAutoApproveStatus(adapterStatus, now = Date.now()) {
48415
48540
  const autoApproveActive = adapterStatus?.status === "waiting_approval" && this.shouldAutoApprove();
48416
48541
  if (autoApproveActive && !this.autoApproveBusy) {
@@ -48508,26 +48633,8 @@ ${effect.notification.body || ""}`.trim();
48508
48633
  this.generatingDebouncePending = null;
48509
48634
  this.generatingStartedAt = 0;
48510
48635
  } else {
48511
- if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
48512
- this.completedDebouncePending = { chatTitle, duration: duration3, timestamp: now };
48513
- this.completedDebounceTimer = setTimeout(() => {
48514
- if (this.completedDebouncePending) {
48515
- const latestStatus = this.adapter.getStatus({ allowParse: false });
48516
- const latestAutoApproveActive = latestStatus.status === "waiting_approval" && this.shouldAutoApprove();
48517
- const latestVisibleStatus = latestAutoApproveActive ? "generating" : latestStatus.status;
48518
- if (latestVisibleStatus !== "idle") {
48519
- LOG.info("CLI", `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
48520
- this.completedDebouncePending = null;
48521
- this.completedDebounceTimer = null;
48522
- return;
48523
- }
48524
- LOG.info("CLI", `[${this.type}] completed in ${this.completedDebouncePending.duration}s`);
48525
- this.pushEvent({ event: "agent:generating_completed", ...this.completedDebouncePending });
48526
- this.completedDebouncePending = null;
48527
- this.generatingStartedAt = 0;
48528
- }
48529
- this.completedDebounceTimer = null;
48530
- }, 3e3);
48636
+ this.completedDebouncePending = { chatTitle, duration: duration3, timestamp: now, firstObservedAt: now };
48637
+ this.scheduleCompletedDebounceFlush(3e3);
48531
48638
  }
48532
48639
  } else if (newStatus === "idle" && this.lastStatus === "starting") {
48533
48640
  this.pushEvent({ event: "agent:ready", chatTitle, timestamp: now });
@@ -52426,6 +52533,89 @@ Run 'adhdev doctor' for detailed diagnostics.`
52426
52533
  if (record2?.meta?.meshNodeId === nodeId) return true;
52427
52534
  return false;
52428
52535
  }
52536
+ async cleanupLocalWorktreeNode(args) {
52537
+ const workspace = typeof args.node?.workspace === "string" ? args.node.workspace.trim() : "";
52538
+ if (!workspace) {
52539
+ return {
52540
+ success: false,
52541
+ code: "mesh_worktree_cleanup_missing_workspace",
52542
+ error: `Worktree node '${args.nodeId}' is missing workspace metadata`,
52543
+ recoveryHint: "Inspect the mesh node record before removing it, or remove stale metadata manually only after confirming no managed worktree remains."
52544
+ };
52545
+ }
52546
+ const worktreeExists = fs10.existsSync(workspace);
52547
+ const sourceNode = args.node?.clonedFromNodeId ? args.mesh?.nodes?.find((n) => n.id === args.node.clonedFromNodeId || n.nodeId === args.node.clonedFromNodeId) : args.mesh?.nodes?.find((n) => !n.isLocalWorktree);
52548
+ const repoRoot = typeof sourceNode?.repoRoot === "string" && sourceNode.repoRoot.trim() ? sourceNode.repoRoot.trim() : typeof sourceNode?.workspace === "string" && sourceNode.workspace.trim() ? sourceNode.workspace.trim() : "";
52549
+ if (!worktreeExists) {
52550
+ return { success: true, skipped: true, removedPath: workspace, repoRoot: repoRoot || void 0, reason: "worktree_path_missing" };
52551
+ }
52552
+ if (!repoRoot || !fs10.existsSync(repoRoot)) {
52553
+ return {
52554
+ success: false,
52555
+ code: "mesh_worktree_cleanup_missing_source_repo",
52556
+ error: `Refusing to remove worktree '${workspace}' because the source repo root is unavailable`,
52557
+ recoveryHint: "Run mesh_remove_node from the machine that owns the source repo, or verify the source node metadata before retrying."
52558
+ };
52559
+ }
52560
+ if (typeof args.node?.worktreeBranch !== "string" || !args.node.worktreeBranch.trim()) {
52561
+ return {
52562
+ success: false,
52563
+ code: "mesh_worktree_cleanup_missing_branch",
52564
+ error: `Refusing to remove worktree '${workspace}' because worktreeBranch metadata is missing`,
52565
+ recoveryHint: "Confirm this is an ADHDev-managed worktree before removing it manually; managed worktree nodes include worktreeBranch metadata."
52566
+ };
52567
+ }
52568
+ const { resolveWorktreePath: resolveWorktreePath2, listWorktrees: listWorktrees2, removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
52569
+ const normalizePath2 = (value) => {
52570
+ const resolved = (0, import_path7.resolve)(value);
52571
+ try {
52572
+ return fs10.realpathSync(resolved);
52573
+ } catch {
52574
+ return resolved;
52575
+ }
52576
+ };
52577
+ const expectedPath = normalizePath2(resolveWorktreePath2(repoRoot, String(args.mesh?.name || args.mesh?.id || "mesh"), args.node.worktreeBranch));
52578
+ const actualPath = normalizePath2(workspace);
52579
+ if (actualPath !== expectedPath) {
52580
+ return {
52581
+ success: false,
52582
+ code: "mesh_worktree_cleanup_unexpected_path",
52583
+ error: `Refusing to remove worktree '${workspace}' because it is not at the expected managed path '${expectedPath}'`,
52584
+ recoveryHint: "Use git worktree list/status to inspect the path. Retry only after confirming the mesh node metadata points to an ADHDev-managed worktree."
52585
+ };
52586
+ }
52587
+ const entries = await listWorktrees2(repoRoot);
52588
+ const managedEntry = entries.find((entry) => normalizePath2(entry.path) === actualPath);
52589
+ if (!managedEntry) {
52590
+ return {
52591
+ success: false,
52592
+ code: "mesh_worktree_cleanup_not_registered",
52593
+ error: `Refusing to remove '${workspace}' because it is not registered in git worktree list for '${repoRoot}'`,
52594
+ recoveryHint: "Inspect git worktree list --porcelain from the source repo. If the path was already removed, prune git worktrees before retrying."
52595
+ };
52596
+ }
52597
+ if (managedEntry.branch && managedEntry.branch !== args.node.worktreeBranch) {
52598
+ return {
52599
+ success: false,
52600
+ code: "mesh_worktree_cleanup_branch_mismatch",
52601
+ error: `Refusing to remove '${workspace}' because git reports branch '${managedEntry.branch}', expected '${args.node.worktreeBranch}'`,
52602
+ recoveryHint: "Inspect the worktree branch and mesh metadata before retrying cleanup."
52603
+ };
52604
+ }
52605
+ try {
52606
+ const result = await removeWorktree2(repoRoot, workspace, { requireClean: true });
52607
+ return { success: true, removedPath: result.removedPath, repoRoot };
52608
+ } catch (e) {
52609
+ const message = String(e?.message || e || "worktree cleanup failed");
52610
+ const dirty = message.includes("dirty worktree") || message.includes("local changes");
52611
+ return {
52612
+ success: false,
52613
+ code: dirty ? "mesh_worktree_cleanup_dirty" : "mesh_worktree_cleanup_failed",
52614
+ error: message,
52615
+ recoveryHint: dirty ? "Commit, stash, or intentionally discard the worktree changes before retrying mesh_remove_node. The mesh registry entry is preserved until cleanup is safe." : "Inspect git worktree status/list from the source repo and retry after resolving the reported cleanup failure."
52616
+ };
52617
+ }
52618
+ }
52429
52619
  isCompletedHostedSession(record2) {
52430
52620
  return record2?.lifecycle === "stopped" || record2?.lifecycle === "failed" || record2?.lifecycle === "interrupted";
52431
52621
  }
@@ -53426,17 +53616,21 @@ Run 'adhdev doctor' for detailed diagnostics.`
53426
53616
  sessionCleanup = await this.cleanupMeshSessions({ meshId, nodeId, node, mode: sessionCleanupMode });
53427
53617
  if (sessionCleanup.success === false) return { success: false, removed: false, sessionCleanup };
53428
53618
  }
53429
- if (node?.isLocalWorktree && node.workspace) {
53430
- try {
53431
- const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => n.id === node.clonedFromNodeId || n.nodeId === node.clonedFromNodeId) : mesh?.nodes.find((n) => !n.isLocalWorktree);
53432
- const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
53433
- if (repoRoot) {
53434
- const { removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
53435
- await removeWorktree2(repoRoot, node.workspace);
53436
- }
53437
- } catch (e) {
53438
- LOG.warn("MeshNode", `Worktree cleanup failed for ${nodeId}: ${e.message}`);
53619
+ let worktreeCleanup;
53620
+ if (node?.isLocalWorktree) {
53621
+ const cleanupResult = await this.cleanupLocalWorktreeNode({ mesh, node, nodeId });
53622
+ if (cleanupResult.success === false) {
53623
+ return {
53624
+ success: false,
53625
+ removed: false,
53626
+ code: cleanupResult.code,
53627
+ error: cleanupResult.error,
53628
+ recoveryHint: cleanupResult.recoveryHint,
53629
+ ...sessionCleanup ? { sessionCleanup } : {},
53630
+ worktreeCleanup: cleanupResult
53631
+ };
53439
53632
  }
53633
+ worktreeCleanup = cleanupResult;
53440
53634
  }
53441
53635
  let removed = false;
53442
53636
  if (meshRecord?.inline) {
@@ -53462,7 +53656,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
53462
53656
  } catch {
53463
53657
  }
53464
53658
  }
53465
- return { success: true, removed, ...sessionCleanup ? { sessionCleanup } : {} };
53659
+ return { success: true, removed, ...sessionCleanup ? { sessionCleanup } : {}, ...worktreeCleanup ? { worktreeCleanup } : {} };
53466
53660
  } catch (e) {
53467
53661
  return { success: false, error: e.message };
53468
53662
  }
@@ -53497,6 +53691,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
53497
53691
  workspace: result.worktreePath,
53498
53692
  repoRoot: result.worktreePath,
53499
53693
  daemonId: sourceNode.daemonId,
53694
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
53500
53695
  userOverrides: { ...sourceNode.userOverrides || {} },
53501
53696
  policy: { ...sourceNode.policy || {} },
53502
53697
  isLocalWorktree: true,
@@ -53510,6 +53705,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
53510
53705
  workspace: result.worktreePath,
53511
53706
  repoRoot: result.worktreePath,
53512
53707
  daemonId: sourceNode.daemonId,
53708
+ machineId: sourceNode.machineId ?? sourceNode.machine_id,
53513
53709
  userOverrides: { ...sourceNode.userOverrides || {} },
53514
53710
  isLocalWorktree: true,
53515
53711
  worktreeBranch: result.branch,
@@ -57960,14 +58156,40 @@ function resolveCoordinatorNode(ctx) {
57960
58156
  if (preferred) return preferred;
57961
58157
  }
57962
58158
  if (ctx.localMachineId) {
57963
- const byMachine = ctx.mesh.nodes.find((n) => n.machineId === ctx.localMachineId);
58159
+ const byMachine = ctx.mesh.nodes.find((n) => readNodeMachineId(n) === ctx.localMachineId);
57964
58160
  if (byMachine) return byMachine;
57965
58161
  }
57966
58162
  if (ctx.localDaemonId) {
57967
- return ctx.mesh.nodes.find((n) => n.daemonId === ctx.localDaemonId);
58163
+ return ctx.mesh.nodes.find((n) => readNodeDaemonId(n) === ctx.localDaemonId);
57968
58164
  }
57969
58165
  return void 0;
57970
58166
  }
58167
+ function readNodeMachineId(node) {
58168
+ return readString(node.machineId) || readString(node.machine_id);
58169
+ }
58170
+ function readNodeDaemonId(node) {
58171
+ return readString(node.daemonId) || readString(node.daemon_id);
58172
+ }
58173
+ function isDirectLocalNode(ctx, node) {
58174
+ const machineId = readNodeMachineId(node);
58175
+ const daemonId = readNodeDaemonId(node);
58176
+ return Boolean(
58177
+ ctx.localMachineId && machineId === ctx.localMachineId || ctx.localDaemonId && daemonId === ctx.localDaemonId
58178
+ );
58179
+ }
58180
+ function findClonedFromNode(ctx, node) {
58181
+ const clonedFromNodeId = readString(node.clonedFromNodeId) || readString(node.cloned_from_node_id);
58182
+ if (!clonedFromNodeId) return void 0;
58183
+ return ctx.mesh.nodes.find((n) => n.id === clonedFromNodeId || n.nodeId === clonedFromNodeId || n.node_id === clonedFromNodeId);
58184
+ }
58185
+ function isLocalControlPlaneNode(ctx, node) {
58186
+ if (isDirectLocalNode(ctx, node)) return true;
58187
+ if (node.isLocalWorktree === true) {
58188
+ const sourceNode = findClonedFromNode(ctx, node);
58189
+ if (sourceNode && isDirectLocalNode(ctx, sourceNode)) return true;
58190
+ }
58191
+ return false;
58192
+ }
57971
58193
  function meshSessionCacheKey(nodeId, runtimeSessionId) {
57972
58194
  return `${nodeId}:${runtimeSessionId}`;
57973
58195
  }
@@ -58051,8 +58273,115 @@ function getNodeLaunchReadiness(node) {
58051
58273
  launchBlockedMessage: missingProviderPriorityMessage(node.id)
58052
58274
  };
58053
58275
  }
58276
+ function readNumeric(value, fallback = 0) {
58277
+ const parsed = Number(value);
58278
+ return Number.isFinite(parsed) ? parsed : fallback;
58279
+ }
58280
+ function buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges) {
58281
+ const defaultBranch = readString(mesh.defaultBranch) ?? "main";
58282
+ const branch = readString(status?.branch) ?? readString(node.worktreeBranch) ?? null;
58283
+ const ahead = readNumeric(status?.ahead);
58284
+ const behind = readNumeric(status?.behind);
58285
+ const upstream = readString(status?.upstream) ?? null;
58286
+ const hasConflicts = status?.hasConflicts === true || Array.isArray(status?.conflictFiles) && status.conflictFiles.length > 0;
58287
+ const base = {
58288
+ defaultBranch,
58289
+ branch,
58290
+ upstream,
58291
+ ahead,
58292
+ behind,
58293
+ isWorktree: node.isLocalWorktree === true,
58294
+ isDefaultBranch: branch === defaultBranch
58295
+ };
58296
+ if (status?.isGitRepo !== true) {
58297
+ return {
58298
+ ...base,
58299
+ status: "blocked_review",
58300
+ needsConvergence: true,
58301
+ reason: "git_status_unavailable",
58302
+ nextStep: `Resolve git status for node '${node.id}' before marking the task complete.`
58303
+ };
58304
+ }
58305
+ if (!branch) {
58306
+ return {
58307
+ ...base,
58308
+ status: "blocked_review",
58309
+ needsConvergence: true,
58310
+ reason: "branch_unknown",
58311
+ nextStep: `Inspect node '${node.id}' git branch before deciding whether it is merged to ${defaultBranch}.`
58312
+ };
58313
+ }
58314
+ if (hasConflicts || dirty || uncommittedChanges > 0) {
58315
+ return {
58316
+ ...base,
58317
+ status: "not_mergeable",
58318
+ needsConvergence: true,
58319
+ reason: hasConflicts ? "conflicts_present" : "dirty_workspace",
58320
+ nextStep: `Commit, checkpoint, or resolve node '${node.id}' before any main convergence step.`
58321
+ };
58322
+ }
58323
+ if (branch === defaultBranch) {
58324
+ if (ahead > 0 || behind > 0) {
58325
+ return {
58326
+ ...base,
58327
+ status: "blocked_review",
58328
+ needsConvergence: true,
58329
+ reason: "default_branch_not_even_with_upstream",
58330
+ nextStep: `Bring ${defaultBranch} even with its upstream before declaring convergence complete.`
58331
+ };
58332
+ }
58333
+ return {
58334
+ ...base,
58335
+ status: "merged_to_main",
58336
+ needsConvergence: false,
58337
+ reason: "clean_default_branch",
58338
+ nextStep: null
58339
+ };
58340
+ }
58341
+ if (node.isLocalWorktree) {
58342
+ return {
58343
+ ...base,
58344
+ status: "cleanup_candidate",
58345
+ needsConvergence: true,
58346
+ reason: "clean_non_default_worktree_branch",
58347
+ nextStep: `Run mesh_refine_node(node_id: "${node.id}") or explicitly classify this worktree as blocked_review/not_mergeable before ending the task.`
58348
+ };
58349
+ }
58350
+ if (!upstream || ahead > 0 || behind > 0) {
58351
+ return {
58352
+ ...base,
58353
+ status: "blocked_review",
58354
+ needsConvergence: true,
58355
+ reason: !upstream ? "feature_branch_missing_upstream" : "feature_branch_not_even_with_upstream",
58356
+ nextStep: `Push or reconcile branch '${branch}', then merge it into ${defaultBranch} or mark it not_mergeable with a reason.`
58357
+ };
58358
+ }
58359
+ return {
58360
+ ...base,
58361
+ status: "pushed_feature_branch_needs_merge",
58362
+ needsConvergence: true,
58363
+ reason: "clean_non_default_branch",
58364
+ nextStep: `Review and merge branch '${branch}' into ${defaultBranch}; do not report the task as fully complete while it remains off main.`
58365
+ };
58366
+ }
58367
+ function summarizeBranchConvergence(nodes) {
58368
+ const followUps = nodes.filter((node) => node?.branchConvergence?.needsConvergence === true).map((node) => ({
58369
+ nodeId: node.nodeId,
58370
+ workspace: node.workspace,
58371
+ branch: node.branchConvergence.branch,
58372
+ status: node.branchConvergence.status,
58373
+ reason: node.branchConvergence.reason,
58374
+ nextStep: node.branchConvergence.nextStep
58375
+ }));
58376
+ return {
58377
+ needsFollowUp: followUps.length > 0,
58378
+ unresolvedCount: followUps.length,
58379
+ requiredFinalStates: ["merged_to_main", "pushed_feature_branch_needs_merge", "blocked_review", "cleanup_candidate", "not_mergeable"],
58380
+ followUps
58381
+ };
58382
+ }
58054
58383
  async function commandForNode(ctx, node, command, args = {}) {
58055
- const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
58384
+ const isLocalNode = isLocalControlPlaneNode(ctx, node);
58056
58385
  if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
58057
58386
  return ctx.transport.meshCommand(node.daemonId, command, args);
58058
58387
  }
@@ -58061,6 +58390,18 @@ async function commandForNode(ctx, node, command, args = {}) {
58061
58390
  }
58062
58391
  throw new Error(`Command '${command}' requires daemon IPC/local transport for node '${node.id}'`);
58063
58392
  }
58393
+ function isP2pTransportUnavailableError(error48) {
58394
+ const message = error48 instanceof Error ? error48.message : String(error48 || "");
58395
+ return /p2p|datachannel|mesh_relay_command|daemon_mesh_p2p_transport_unavailable/i.test(message) && /unavailable|failed|timeout|timed out|not connected|closed/i.test(message);
58396
+ }
58397
+ function buildRemoveNodeArgs(ctx, nodeId, sessionCleanupMode) {
58398
+ return {
58399
+ meshId: ctx.mesh.id,
58400
+ nodeId,
58401
+ ...sessionCleanupMode ? { sessionCleanupMode } : {},
58402
+ inlineMesh: ctx.mesh
58403
+ };
58404
+ }
58064
58405
  var MESH_STATUS_TOOL = {
58065
58406
  name: "mesh_status",
58066
58407
  description: "Get the current status of all nodes in the repo mesh \u2014 health, git state, active sessions, recovery hints, and recommended next steps. Use this to decide which node to send work to or how to recover from failures.",
@@ -58339,6 +58680,7 @@ async function meshStatus(ctx) {
58339
58680
  entry.branch = status?.branch;
58340
58681
  entry.isDirty = dirty;
58341
58682
  entry.uncommittedChanges = uncommittedChanges;
58683
+ entry.branchConvergence = buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges);
58342
58684
  } else if (isLocalTransport(transport)) {
58343
58685
  const statusResult = await commandForNode(ctx, node, "git_status", { workspace: node.workspace });
58344
58686
  const status = extractGitStatus(statusResult);
@@ -58348,6 +58690,7 @@ async function meshStatus(ctx) {
58348
58690
  entry.branch = status?.branch;
58349
58691
  entry.isDirty = dirty;
58350
58692
  entry.uncommittedChanges = uncommittedChanges;
58693
+ entry.branchConvergence = buildBranchConvergence(mesh, node, status, dirty, uncommittedChanges);
58351
58694
  } else {
58352
58695
  entry.health = "unknown";
58353
58696
  entry.note = "No daemonId available for cloud status probe";
@@ -58385,6 +58728,9 @@ async function meshStatus(ctx) {
58385
58728
  } else if (entry.health === "degraded" && entry.error?.includes("git")) {
58386
58729
  nextStepHints.push("Initialize git repository or check workspace path.");
58387
58730
  }
58731
+ if (entry.branchConvergence?.needsConvergence === true && entry.branchConvergence.nextStep) {
58732
+ nextStepHints.push(String(entry.branchConvergence.nextStep));
58733
+ }
58388
58734
  if (recoveryContext.consecutiveNodeFailures > 0) {
58389
58735
  if (recoveryContext.retryRecommended) {
58390
58736
  nextStepHints.push(`Retry task on this node or launch a fresh session.`);
@@ -58405,7 +58751,8 @@ async function meshStatus(ctx) {
58405
58751
  repoIdentity: mesh.repoIdentity,
58406
58752
  policy: mesh.policy,
58407
58753
  refreshedAt: (/* @__PURE__ */ new Date()).toISOString(),
58408
- nodes: results
58754
+ nodes: results,
58755
+ branchConvergenceSummary: summarizeBranchConvergence(results)
58409
58756
  };
58410
58757
  try {
58411
58758
  response.ledgerSummary = ledgerSummary;
@@ -58462,7 +58809,7 @@ async function meshEnqueueTask(ctx, args) {
58462
58809
  });
58463
58810
  const dispatchPromises = [];
58464
58811
  for (const node of ctx.mesh.nodes) {
58465
- const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
58812
+ const isLocalNode = isLocalControlPlaneNode(ctx, node);
58466
58813
  if (isLocalNode || !node.daemonId) continue;
58467
58814
  dispatchPromises.push(
58468
58815
  ipcDispatchToRemoteAgent(ctx, node, { message: args.message }).then((result) => {
@@ -58573,7 +58920,7 @@ async function meshSendTask(ctx, args) {
58573
58920
  });
58574
58921
  return JSON.stringify(res);
58575
58922
  }
58576
- const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
58923
+ const isLocalNode = isLocalControlPlaneNode(ctx, node);
58577
58924
  if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
58578
58925
  const cached2 = meshSessionProviderMetadata.get(meshSessionCacheKey(args.node_id, args.session_id || ""));
58579
58926
  const result = await ipcDispatchToRemoteAgent(ctx, node, {
@@ -58788,7 +59135,7 @@ async function meshLaunchSession(ctx, args) {
58788
59135
  });
58789
59136
  } catch {
58790
59137
  }
58791
- const isLocalNode = ctx.localMachineId && node.machineId === ctx.localMachineId || ctx.localDaemonId && node.daemonId === ctx.localDaemonId;
59138
+ const isLocalNode = isLocalControlPlaneNode(ctx, node);
58792
59139
  if (ctx.transport instanceof IpcTransport && node.daemonId && !isLocalNode) {
58793
59140
  ctx.transport.meshCommand(node.daemonId, "trigger_mesh_queue", { meshId: ctx.mesh.id }).catch(() => {
58794
59141
  });
@@ -59018,12 +59365,28 @@ async function meshCleanupSessions(ctx, args) {
59018
59365
  async function meshRemoveNode(ctx, args) {
59019
59366
  const node = await findNodeWithRefresh(ctx, args.node_id);
59020
59367
  if (isLocalTransport(ctx.transport)) {
59021
- const result = await commandForNode(ctx, node, "remove_mesh_node", {
59022
- meshId: ctx.mesh.id,
59023
- nodeId: args.node_id,
59024
- ...args.session_cleanup_mode ? { sessionCleanupMode: args.session_cleanup_mode } : {},
59025
- inlineMesh: ctx.mesh
59026
- });
59368
+ const removeArgs = buildRemoveNodeArgs(ctx, args.node_id, args.session_cleanup_mode);
59369
+ let result;
59370
+ let transportFallback;
59371
+ try {
59372
+ result = await commandForNode(ctx, node, "remove_mesh_node", removeArgs);
59373
+ } catch (e) {
59374
+ if (ctx.transport instanceof IpcTransport && node.isLocalWorktree && isP2pTransportUnavailableError(e)) {
59375
+ result = await ctx.transport.command("remove_mesh_node", removeArgs);
59376
+ transportFallback = {
59377
+ from: "p2p_mesh_relay",
59378
+ to: "local_control_plane",
59379
+ reason: e?.message || String(e)
59380
+ };
59381
+ } else {
59382
+ return JSON.stringify({
59383
+ success: false,
59384
+ code: isP2pTransportUnavailableError(e) ? "p2p_unavailable" : "mesh_remove_node_failed",
59385
+ error: e?.message || String(e),
59386
+ recoveryHint: isP2pTransportUnavailableError(e) ? "If this is an ADHDev-managed local worktree, retry from a coordinator connected to the daemon that owns the worktree; dashboard command/data-plane traffic still requires P2P." : "Inspect mesh_status and retry after resolving the reported failure."
59387
+ }, null, 2);
59388
+ }
59389
+ }
59027
59390
  if (result?.success && result.removed !== false) {
59028
59391
  const idx = ctx.mesh.nodes.findIndex((n) => n.id === args.node_id);
59029
59392
  if (idx >= 0) {
@@ -59031,7 +59394,7 @@ async function meshRemoveNode(ctx, args) {
59031
59394
  ctx.mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
59032
59395
  }
59033
59396
  }
59034
- return JSON.stringify(result, null, 2);
59397
+ return JSON.stringify({ ...result || {}, ...transportFallback ? { transportFallback } : {} }, null, 2);
59035
59398
  } else if (!isLocalTransport(ctx.transport) && node.daemonId) {
59036
59399
  try {
59037
59400
  const res = await ctx.transport.meshRemoveNode(node.daemonId, {