@wrongstack/cli 0.296.3 → 0.297.0

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.
Files changed (83) hide show
  1. package/dist/boot/dispatch-webui.d.ts +7 -0
  2. package/dist/boot/dispatch-webui.d.ts.map +1 -1
  3. package/dist/boot/launch-banner.d.ts +22 -0
  4. package/dist/boot/launch-banner.d.ts.map +1 -0
  5. package/dist/boot/launch-menu.d.ts.map +1 -1
  6. package/dist/boot/tui-settings-adapter.d.ts.map +1 -1
  7. package/dist/{chunk-OI7GWJDS.js → chunk-7JABKXET.js} +372 -10
  8. package/dist/chunk-7JABKXET.js.map +7 -0
  9. package/dist/{chunk-WY7KKOUK.js → chunk-JW75HY4F.js} +31 -10
  10. package/dist/chunk-JW75HY4F.js.map +7 -0
  11. package/dist/{chunk-Z7YGASQP.js → chunk-QZKWRNIP.js} +19 -18
  12. package/dist/chunk-QZKWRNIP.js.map +7 -0
  13. package/dist/{chunk-BQCAJ7FI.js → chunk-XTIXVJXP.js} +16 -3
  14. package/dist/chunk-XTIXVJXP.js.map +7 -0
  15. package/dist/{cli-main-RTY35OPD.js → cli-main-GOY5YGVL.js} +25199 -25112
  16. package/dist/cli-main-GOY5YGVL.js.map +7 -0
  17. package/dist/cli-main-helpers.d.ts +1 -1
  18. package/dist/cli-main-helpers.d.ts.map +1 -1
  19. package/dist/cli-main.d.ts.map +1 -1
  20. package/dist/{execution-O7I5DYE6.js → execution-A4PGK4XV.js} +39 -9
  21. package/dist/execution-A4PGK4XV.js.map +7 -0
  22. package/dist/execution.d.ts.map +1 -1
  23. package/dist/fleet-statusline.d.ts.map +1 -1
  24. package/dist/goal-host.d.ts +1 -1
  25. package/dist/goal-host.d.ts.map +1 -1
  26. package/dist/{hq-JUYKUNJX.js → hq-GBPGXIR5.js} +2 -2
  27. package/dist/hq-publisher.d.ts +3 -2
  28. package/dist/hq-publisher.d.ts.map +1 -1
  29. package/dist/hq-server/types.d.ts +8 -0
  30. package/dist/hq-server/types.d.ts.map +1 -1
  31. package/dist/hq-server/ws.d.ts +61 -2
  32. package/dist/hq-server/ws.d.ts.map +1 -1
  33. package/dist/{hq-server-6AQ3BXZA.js → hq-server-YQUUMTPU.js} +2 -2
  34. package/dist/index.js +293 -26
  35. package/dist/index.js.map +4 -4
  36. package/dist/kanban-hq-sync.d.ts +13 -1
  37. package/dist/kanban-hq-sync.d.ts.map +1 -1
  38. package/dist/live-settings-input.d.ts +9 -0
  39. package/dist/live-settings-input.d.ts.map +1 -1
  40. package/dist/{mailbox-serve-2UWHEN3M.js → mailbox-serve-DBOOOOWZ.js} +50 -8
  41. package/dist/mailbox-serve-DBOOOOWZ.js.map +7 -0
  42. package/dist/{sdd-runtime-JG4EEKL6.js → sdd-runtime-AIJCJGWC.js} +2 -2
  43. package/dist/services/sdd/state.d.ts +3 -3
  44. package/dist/services/sdd/state.d.ts.map +1 -1
  45. package/dist/services/sdd/task-manager.d.ts.map +1 -1
  46. package/dist/session-stats.d.ts.map +1 -1
  47. package/dist/settings-menu.d.ts.map +1 -1
  48. package/dist/slash-commands/command-context.d.ts +2 -0
  49. package/dist/slash-commands/command-context.d.ts.map +1 -1
  50. package/dist/slash-commands/goal.d.ts +1 -1
  51. package/dist/slash-commands/goal.d.ts.map +1 -1
  52. package/dist/slash-commands/sdd.d.ts.map +1 -1
  53. package/dist/webui-server/kanban-host-adapter.d.ts +1 -1
  54. package/dist/webui-server/kanban-host-adapter.d.ts.map +1 -1
  55. package/dist/webui-server/session-start-payload.d.ts +4 -0
  56. package/dist/webui-server/session-start-payload.d.ts.map +1 -1
  57. package/dist/{webui-server-ZF5KVGC5.js → webui-server-XKFUOKMJ.js} +155 -132
  58. package/dist/webui-server-XKFUOKMJ.js.map +7 -0
  59. package/dist/webui-server-options.d.ts +7 -0
  60. package/dist/webui-server-options.d.ts.map +1 -1
  61. package/dist/webui-server.d.ts.map +1 -1
  62. package/dist/wiring/command-host-state.d.ts.map +1 -1
  63. package/dist/wiring/hq-telemetry.d.ts +4 -3
  64. package/dist/wiring/hq-telemetry.d.ts.map +1 -1
  65. package/dist/wiring/lifecycle-plugins.d.ts +5 -8
  66. package/dist/wiring/lifecycle-plugins.d.ts.map +1 -1
  67. package/dist/wiring/metrics.d.ts +1 -1
  68. package/dist/wiring/metrics.d.ts.map +1 -1
  69. package/dist/wiring/runtime-lifecycle-deps.d.ts.map +1 -1
  70. package/dist/wiring/sage.d.ts.map +1 -1
  71. package/dist/wiring/sdd-handlers.d.ts.map +1 -1
  72. package/package.json +22 -22
  73. package/dist/chunk-BQCAJ7FI.js.map +0 -7
  74. package/dist/chunk-OI7GWJDS.js.map +0 -7
  75. package/dist/chunk-WY7KKOUK.js.map +0 -7
  76. package/dist/chunk-Z7YGASQP.js.map +0 -7
  77. package/dist/cli-main-RTY35OPD.js.map +0 -7
  78. package/dist/execution-O7I5DYE6.js.map +0 -7
  79. package/dist/mailbox-serve-2UWHEN3M.js.map +0 -7
  80. package/dist/webui-server-ZF5KVGC5.js.map +0 -7
  81. /package/dist/{hq-JUYKUNJX.js.map → hq-GBPGXIR5.js.map} +0 -0
  82. /package/dist/{hq-server-6AQ3BXZA.js.map → hq-server-YQUUMTPU.js.map} +0 -0
  83. /package/dist/{sdd-runtime-JG4EEKL6.js.map → sdd-runtime-AIJCJGWC.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/execution.ts", "../src/boot/dispatch-singleshot.ts", "../src/context-overflow-diagnostic.ts", "../src/boot/dispatch-tui.ts", "../src/boot/dispatch-webui.ts", "../src/boot/execution-mode.ts", "../src/boot/tui-coordinator-callbacks.ts", "../src/boot/tui-coordinator-setup.ts", "../src/boot/tui-debug-stream.ts", "../src/boot/tui-goal-wiring.ts", "../src/boot/tui-live-sessions.ts", "../src/boot/tui-project-picker-callback.ts", "../src/boot/tui-project-spawn.ts", "../src/boot/tui-project-switch.ts", "../src/boot/tui-sdd-callback.ts", "../src/boot/tui-session-resume.ts", "../src/boot/tui-settings-adapter.ts", "../src/brain-menu/panel-service.ts", "../src/chimera-review-task.ts", "../src/chimera-reviewer-policy.ts", "../src/execution-cleanup.ts", "../src/execution-kanban-dispatch.ts", "../src/kanban-dispatch-route.ts", "../src/execution-repl-fleet-callbacks.ts", "../src/fleet-statusline.ts", "../src/execution-chimera-ask.ts", "../src/execution-chimera-cascade.ts", "../src/execution-storage-observability.ts", "../src/next-task-predictor.ts", "../src/repl.ts", "../src/repl-suggestions.ts", "../src/repl-auto-proceed.ts", "../src/repl-input.ts", "../src/repl-rendering.ts", "../src/repl-client-registration.ts", "../src/execution-tui-next-step-callbacks.ts"],
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto';\nimport * as path from 'node:path';\nimport { setQueuedMessagesSnapshot } from '@wrongstack/core/agent';\nimport { type CoordinatorEvent, isMailboxLeader } from '@wrongstack/core/coordination';\nimport {\n CHIMERA_REVIEW_PROMPT,\n type ChimeraReviewCompletePayload,\n type ChimeraReviewNeededPayload,\n} from '@wrongstack/core/plugin';\nimport { attachTodosCheckpoint } from '@wrongstack/core/storage';\nimport {\n normalizeTokenSavingTier,\n type StopReason,\n type SubagentConfig,\n} from '@wrongstack/core/types';\nimport { mergeCustomModelDefs } from '@wrongstack/core/utils';\nimport { capabilitiesFor } from '@wrongstack/providers';\nimport { createToolVisionAdapters } from '@wrongstack/runtime/vision';\nimport { runSingleShotDispatch } from './boot/dispatch-singleshot.js';\nimport { runTuiDispatch } from './boot/dispatch-tui.js';\nimport { runWebUIDispatch } from './boot/dispatch-webui.js';\nimport { resolveExecutionMode } from './boot/execution-mode.js';\nimport { createTuiCoordinatorCallbacks } from './boot/tui-coordinator-callbacks.js';\nimport { setupAutonomousCoordinator } from './boot/tui-coordinator-setup.js';\nimport {\n registerDebugStreamCallback,\n restoreDebugStreamCallback,\n} from './boot/tui-debug-stream.js';\nimport { wireGoal } from './boot/tui-goal-wiring.js';\nimport { getLiveSessions, onSwitchToSession } from './boot/tui-live-sessions.js';\nimport {\n getProjectPickerItems,\n onProjectSelect,\n type ProjectPickerContext,\n} from './boot/tui-project-picker-callback.js';\nimport { handleProjectSwitchSpawn } from './boot/tui-project-spawn.js';\nimport {\n type ProjectSwitchContext,\n switchProjectInPlace as switchProjectInPlaceExtracted,\n} from './boot/tui-project-switch.js';\nimport type { TuiRuntimeState } from './boot/tui-runtime-state.js';\nimport {\n getSDDContext as getSDDContextExtracted,\n onSDDOutput as onSDDOutputExtracted,\n} from './boot/tui-sdd-callback.js';\nimport { resumeSession } from './boot/tui-session-resume.js';\nimport { createSettingsAdapter } from './boot/tui-settings-adapter.js';\nimport { createBrainPanelHost } from './brain-menu/panel-service.js';\nimport {\n buildChimeraReviewTaskDescription,\n isChimeraAllClearReview,\n truncateAtCodePointBoundary,\n} from './chimera-review-task.js';\nimport {\n applyChimeraReviewerReadOnlyPolicy,\n assignReviewerModelsRoundRobin,\n resolveReviewerFallbackModels,\n} from './chimera-reviewer-policy.js';\nimport type { ExecuteDeps } from './execute-deps.js';\nimport { finalizeExecutionCleanup } from './execution-cleanup.js';\nimport { createKanbanDispatchHandler } from './execution-kanban-dispatch.js';\nimport { createReplFleetCallbacks } from './execution-repl-fleet-callbacks.js';\nimport { FleetStatusLine } from './fleet-statusline.js';\n\nexport type { LiveSettingsInput } from './live-settings-input.js';\n\nimport { waitForChimeraAskApproval } from './execution-chimera-ask.js';\nimport { installChimeraCascadeHandler } from './execution-chimera-cascade.js';\nimport { installStorageObservability } from './execution-storage-observability.js';\nimport { createTuiNextStepCallbacks } from './execution-tui-next-step-callbacks.js';\nimport { resolveActiveApiKey } from './provider-config-utils.js';\nimport { runRepl } from './repl.js';\nimport type { UpdateInfo } from './update-check.js';\nimport { CLI_VERSION } from './version.js';\n\nexport {\n __resetReviewerRoundRobinCursor,\n applyChimeraReviewerReadOnlyPolicy,\n assignReviewerModelsRoundRobin,\n CHIMERA_REVIEW_READ_ONLY_TOOLS,\n resolveReviewerFallbackModels,\n} from './chimera-reviewer-policy.js';\n\nexport type {\n BrainData,\n BrainLogEntry,\n ExecuteDeps,\n McpPickerItem,\n PluginPickerItem,\n RestoredToolCall,\n ToolPickerItem,\n} from './execute-deps.js';\n\nexport async function execute(deps: ExecuteDeps): Promise<number> {\n const {\n core: {\n agent,\n events,\n config,\n configStore,\n wpaths: initialWpaths,\n projectRoot: initialProjectRoot,\n flags,\n positional,\n slashRegistry,\n tokenCounter,\n activateSessionIdentity,\n updateInfo: initialUpdateInfo,\n },\n session: {\n session,\n context,\n attachments,\n queueStore,\n mcpRegistry,\n mailbox,\n sessionStore,\n memoryStore,\n modeStore,\n detachTodosCheckpoint,\n rebindTodosCheckpoint,\n restoredMessages,\n restoredToolCalls,\n restoredEvents,\n needsSetup,\n },\n provider: {\n modelsRegistry,\n savedProviderCfg,\n resolvedProvider,\n statusTracker,\n getPickableProviders,\n switchProviderAndModel,\n onModelContextResolved,\n sddSubagentFactory,\n },\n ui: {\n renderer,\n reader,\n secretInputController,\n stats,\n effectiveMaxContext,\n getEffectiveMaxContext,\n skillLoader,\n promptLoader,\n modeId,\n },\n fleet: {\n director,\n getDirector,\n coordinatorController,\n fleetRoster,\n fleetStreamController,\n agentsMonitorController,\n agentTranscripts,\n authHost,\n onPanelOpen,\n },\n controllers: {\n interruptController,\n enhanceController,\n getEnhancerReasoning,\n buildEnhancerProvider,\n getEnhanceFallbackRef,\n getConfiguredRefinerRef,\n statuslineHiddenItems,\n setStatuslineHiddenItems,\n saveStatuslineHiddenItems,\n getYolo,\n onYolo,\n getAutonomy,\n onAutonomy,\n getNextPredict,\n applyLiveSettings,\n onCountdownTick,\n },\n picker: {\n getPluginItems,\n onPluginToggle,\n getMcpServers,\n onMcpToggle,\n onMcpRestart,\n getToolsItems,\n onToolToggle,\n getBrainData,\n onBrainRiskLevel,\n getBrainLog,\n brain,\n brainSettings,\n brainRuntime,\n getShadowData,\n onShadowStart,\n onShadowStop,\n } = {},\n lifecycles: {\n getSuggestions,\n getAutoSuggestions,\n onSuggestionsParsed,\n autonomyNextPrompt,\n autoProceedDelayMs,\n autoProceedMaxIterations,\n onValidateAutoProceed,\n getEternalEngine,\n getParallelEngine,\n getSddRun,\n onSddLifecycle,\n subscribeEternalIteration,\n subscribeEternalStage,\n onDestroy,\n onCoordinatorStop,\n } = {},\n } = deps;\n\n let onCoordinatorStopImpl: (() => void) | undefined = onCoordinatorStop;\n\n const wpaths = initialWpaths;\n const projectRoot = initialProjectRoot;\n const activeSessionStore = sessionStore;\n const detachActiveTodosCheckpoint: (() => void | Promise<void>) | undefined =\n detachTodosCheckpoint;\n const profileName = config.activeProfile ?? 'default';\n const bootUpdateInfo: UpdateInfo | undefined = initialUpdateInfo;\n\n const offStorageObservability = installStorageObservability(events, context.traceId);\n\n let pendingChimeraWork: Promise<void> | undefined;\n\n events.onPattern('chimera.review_needed', (_event, payload) => {\n const p = payload as ChimeraReviewNeededPayload;\n const dir = director;\n if (!dir) {\n return;\n }\n if (p.files.length === 0) return;\n\n pendingChimeraWork = (async () => {\n let subagentId: string | undefined;\n try {\n const taskDesc = buildChimeraReviewTaskDescription(p);\n\n const tProvider = config.provider?.trim() || undefined;\n const tModel = config.model?.trim() || undefined;\n const rawProvider = p.reviewFallbackModels\n ? p.config.provider?.trim() || undefined\n : tProvider;\n const rawModel = p.reviewFallbackModels ? p.config.model?.trim() || undefined : tModel;\n const baseProvider = rawProvider || tProvider || config.provider;\n const baseModel = rawModel || tModel || config.model;\n const baseFallbacks = p.reviewFallbackModels\n ? [...p.reviewFallbackModels]\n : resolveReviewerFallbackModels(undefined);\n const assigned = assignReviewerModelsRoundRobin(baseProvider, baseModel, baseFallbacks);\n const cfg = applyChimeraReviewerReadOnlyPolicy({\n name: 'chimera-review',\n role: 'reviewer',\n systemPromptOverride: CHIMERA_REVIEW_PROMPT,\n maxIterations: 50,\n maxToolCalls: 250,\n timeoutMs: 900_000,\n provider: assigned.provider,\n model: assigned.model,\n fallbackModels: assigned.fallbackModels,\n });\n\n subagentId = await dir.spawn(cfg);\n const taskId = randomUUID();\n await dir.assign({\n id: taskId,\n description: taskDesc,\n subagentId,\n });\n\n const results = await dir.awaitTasks([taskId]);\n const result = results[0];\n if (result?.status !== 'success') {\n try {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera review subagent ${result?.status ?? 'unknown'}: ${result?.error?.message ?? 'no result'}`,\n phase: 'agent',\n });\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.chimera_append_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n events.emitCustom('chimera.review_complete', {\n bundle: p,\n reviewText: '',\n status: result?.status ?? 'unknown',\n cwd: p.cwd,\n sessionId: session.id,\n } satisfies ChimeraReviewCompletePayload);\n return;\n }\n\n const reviewText =\n typeof result.result === 'string' ? result.result.trim() : JSON.stringify(result.result);\n\n events.emitCustom('chimera.review_complete', {\n bundle: p,\n reviewText,\n status: 'success',\n cwd: p.cwd,\n sessionId: session.id,\n } satisfies ChimeraReviewCompletePayload);\n\n if (reviewText) {\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [{ type: 'text', text: reviewText }],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n\n const autoFix =\n (agent.ctx.meta['chimeraAutoFix'] as string | undefined) ?? p.config.autoFix ?? 'off';\n const reviewHasFindings = !isChimeraAllClearReview(reviewText);\n const isAskMode = autoFix === 'ask' && reviewHasFindings;\n const mailboxType = isAskMode ? 'ask' : 'result';\n const subject = isAskMode\n ? `\uD83E\uDD82 Chimera review \u2014 ${p.files.length} file(s) changed. Shall I fix the findings?`\n : `\uD83E\uDD82 Chimera review \u2014 ${p.files.length} file(s) changed`;\n\n let leaderApproved = false;\n let spawnedFix = false;\n let askMailMsgId: string | undefined;\n\n let leaderOnline = false;\n if (isAskMode) {\n try {\n const onlineAgents = await mailbox.getOnlineAgents();\n leaderOnline = onlineAgents.some(\n (a) => a.online && isMailboxLeader(a.agentId, a.role),\n );\n } catch (leaderCheckErr) {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_leader_check_failed',\n message:\n leaderCheckErr instanceof Error\n ? leaderCheckErr.message\n : String(leaderCheckErr),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n if (!leaderOnline) {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_mailbox_leader_offline',\n message: `Leader not online \u2014 mailbox ${mailboxType} from chimera-review to leader will be delivered when leader reconnects`,\n fileCount: p.files.length,\n autoFix,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n } else {\n leaderOnline = true;\n console.debug(\n JSON.stringify({\n level: 'debug',\n event: 'execution.chimera_auto_no_presence_check',\n message:\n 'Result mode: leader presence not checked \u2014 mailbox message delivered regardless',\n fileCount: p.files.length,\n autoFix,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n\n try {\n const askTimeoutRaw =\n (agent.ctx.meta['chimeraAskTimeoutMs'] as number | undefined) ?? 30_000;\n const ASK_TIMEOUT_MS = Number.isFinite(askTimeoutRaw)\n ? Math.max(0, askTimeoutRaw)\n : 30_000;\n const directive = isAskMode\n ? `LEADER ACTION REQUIRED: The Chimera review below found issues. Reply with \"yes\" to auto-fix, or \"no\" to skip (${ASK_TIMEOUT_MS / 1000}s timeout).`\n : reviewHasFindings\n ? 'LEADER ACTION REQUIRED: The Chimera review below found issues. Read the report and fix any Critical or High findings automatically using the edit tool. Verify with typecheck and linter.'\n : 'Chimera review completed with no findings. Read the report summary below; no fix action is requested.';\n const reviewBody =\n reviewText.length > 7500\n ? truncateAtCodePointBoundary(reviewText, 7500) +\n '\\n\\n\u2026(truncated, full report in session transcript)'\n : reviewText;\n const body = `${directive}\\n\\n${reviewBody}`;\n\n const mailMsg = await mailbox.send({\n from: 'chimera-review',\n to: 'leader',\n type: mailboxType,\n audience: 'leaders',\n subject,\n body,\n priority: 'normal',\n });\n if (!mailMsg?.id) throw new Error('mailbox.send returned no message id');\n askMailMsgId = mailMsg.id;\n\n if (isAskMode) {\n leaderApproved = await waitForChimeraAskApproval({\n mailbox,\n messageId: askMailMsgId,\n meta: agent.ctx.meta,\n session: agent.ctx.session ?? session,\n askTimeoutMs: ASK_TIMEOUT_MS,\n });\n }\n } catch (mailErr) {\n const errMsg = mailErr instanceof Error ? mailErr.message : String(mailErr);\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.chimera_mailbox_failed',\n message: errMsg,\n timestamp: new Date().toISOString(),\n }),\n );\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera auto-fix skipped \u2014 mailbox unreachable: ${errMsg}. Falling back to manual review mode.`,\n phase: 'agent',\n });\n }\n\n events.emitCustom('chimera.mailbox_delivered', {\n subject,\n autoFixMode: autoFix,\n fileCount: p.files.length,\n reviewLength: reviewText.length,\n });\n\n if (!leaderOnline) {\n try {\n await mailbox.send({\n from: 'chimera-review',\n to: 'leader',\n type: 'note',\n audience: 'leaders',\n subject: `\u23F0 Chimera review pending \u2014 ${p.files.length} file(s) checked`,\n body: `The leader was offline when a chimera review completed. A full review result with \"LEADER ACTION REQUIRED\" directive is waiting in this mailbox from chimera-review. Open it, read the findings, and fix any Critical or High issues.`,\n priority: 'high',\n });\n } catch (wakeErr) {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_wakeup_companion_failed',\n message: wakeErr instanceof Error ? wakeErr.message : String(wakeErr),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n }\n\n const shouldSpawnFix =\n !spawnedFix &&\n reviewHasFindings &&\n (autoFix === 'auto' || (isAskMode && leaderApproved)) &&\n reviewText.length > 0;\n\n if (shouldSpawnFix) {\n spawnedFix = true; // guard against double-spawn from poll race\n const fixTaskDesc = [\n `You are a fix agent. Apply the fixes requested in this review report.`,\n ``,\n `Repository: ${p.cwd}`,\n ``,\n `--- Review report ---`,\n truncateAtCodePointBoundary(reviewText, 12_000),\n ``,\n `--- Changed files ---`,\n p.files.map((f) => `- ${f.path}`).join('\\n'),\n ``,\n `Read each file, understand the issue, apply fixes using the edit tool.`,\n `After fixing, run the project's typecheck and linter to verify.`,\n `Do NOT remove or reorder existing code unless the bug requires it.`,\n ].join('\\n');\n\n try {\n const fixCfg: SubagentConfig = {\n name: 'chimera-fix',\n role: 'fixer',\n maxIterations: 60,\n maxToolCalls: 350,\n timeoutMs: 1_200_000,\n };\n const fixSubagentId = await dir.spawn(fixCfg);\n try {\n const fixTaskId = randomUUID();\n await dir.assign({\n id: fixTaskId,\n description: fixTaskDesc,\n subagentId: fixSubagentId,\n });\n const fixResults = await dir.awaitTasks([fixTaskId]);\n const fixResult = fixResults[0];\n if (fixResult?.status === 'success') {\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n { type: 'text', text: `Chimera fix subagent completed: ${fixResult.result}` },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n } else {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `Chimera fix subagent ${fixResult?.status ?? 'unknown'}: ${fixResult?.error?.message ?? 'no result'}`,\n phase: 'agent',\n });\n }\n } finally {\n try {\n await dir.terminate(fixSubagentId);\n } catch {\n /* best-effort */\n }\n }\n } catch (fixErr) {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera auto-fix failed: ${fixErr instanceof Error ? fixErr.message : String(fixErr)}`,\n phase: 'agent',\n });\n }\n }\n }\n } catch (err) {\n try {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera review failed: ${err instanceof Error ? err.message : String(err)}`,\n phase: 'agent',\n });\n } catch (appendErr) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.chimera_review_append_failed',\n message: appendErr instanceof Error ? appendErr.message : String(appendErr),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n } finally {\n if (subagentId) {\n try {\n await dir.terminate(subagentId);\n } catch {\n /* best-effort \u2014 subagent may already be gone */\n }\n }\n }\n })();\n });\n\n installChimeraCascadeHandler({\n events,\n director,\n session,\n getPendingWork: () => pendingChimeraWork,\n setPendingWork: (work) => {\n pendingChimeraWork = work;\n },\n });\n\n let code = 0;\n let fleetStatusLine: FleetStatusLine | null = null;\n try {\n const visionAdapters = () => createToolVisionAdapters(agent.tools);\n const supportsVision = async (): Promise<boolean> => {\n try {\n const providerConfig = config.providers?.[context.provider.id];\n const mergedModels = mergeCustomModelDefs(providerConfig?.customModels, config.models);\n const caps = await capabilitiesFor(\n modelsRegistry,\n context.provider.id,\n context.model,\n mergedModels,\n );\n return caps.vision;\n } catch {\n return context.provider.capabilities.vision;\n }\n };\n const promptFlag = typeof flags['prompt'] === 'string' ? flags['prompt'] : undefined;\n if (promptFlag) {\n positional.unshift(promptFlag);\n }\n const goalFlag = typeof flags['goal'] === 'string' ? flags['goal'] : undefined;\n const askFlag = typeof flags['ask'] === 'string' ? flags['ask'] : undefined;\n if ((goalFlag || askFlag) && positional.length === 0 && !promptFlag) {\n flags.tui = true;\n }\n const executionMode = resolveExecutionMode(positional, flags);\n const enteringTui = executionMode === 'tui';\n if (!enteringTui) {\n fleetStatusLine = new FleetStatusLine({ events, version: CLI_VERSION });\n fleetStatusLine.start();\n }\n if (executionMode === 'single-shot') {\n code = await runSingleShotDispatch({\n agent,\n query: positional.join(' '),\n flags,\n tokenCounter,\n renderer,\n });\n } else if (executionMode === 'tui') {\n agent.disableInteractiveConfirmation();\n\n const state: TuiRuntimeState = {\n projectRoot,\n wpaths,\n activeSessionStore,\n activateSessionIdentity,\n detachActiveTodosCheckpoint,\n pendingProjectSwitch: null,\n autonomousCoordinator: null,\n coordinatorRun: null,\n coordinatorEvents: new Set(),\n };\n\n const banneredFamily = savedProviderCfg?.family ?? resolvedProvider?.family;\n const banneredKey =\n (savedProviderCfg ? resolveActiveApiKey(savedProviderCfg) : undefined) ??\n config.apiKey ??\n (resolvedProvider?.envVars ?? savedProviderCfg?.envVars ?? [])\n .map((v) => process.env[v])\n .find((v): v is string => !!v);\n const banneredKeyTail =\n banneredKey && banneredKey.length >= 3 ? banneredKey.slice(-3) : undefined;\n\n const goalWiring = wireGoal(events);\n const subscribeGoal = goalWiring.subscribe;\n\n const coordinatorEvents = new Set<(event: CoordinatorEvent) => void>();\n state.coordinatorEvents = coordinatorEvents;\n const autonomousCoordinationEnabled = config.features.autonomousCoordination !== false;\n const coordinatorSetup = autonomousCoordinationEnabled\n ? setupAutonomousCoordinator({\n state,\n events,\n context,\n wpaths,\n mailbox,\n director,\n getDirector,\n coordinatorController,\n onCoordinatorStopSetter: (fn) => {\n onCoordinatorStopImpl = fn ?? undefined;\n },\n })\n : {\n ensure: () => null,\n cleanup: () => undefined,\n };\n const ensureAutonomousCoordinator = coordinatorSetup.ensure;\n const offDirectorSpawned = coordinatorSetup.cleanup;\n\n const switchCtx: ProjectSwitchContext = {\n state,\n context,\n events,\n agent,\n config,\n tokenCounter,\n modeId,\n modeStore,\n memoryStore,\n skillLoader,\n attachTodosCheckpoint,\n };\n const switchProjectInPlace = async (targetRoot: string, displayName: string) => {\n return switchProjectInPlaceExtracted(switchCtx, targetRoot, displayName);\n };\n\n const pickerCtx: ProjectPickerContext = {\n state,\n renderer,\n director,\n getEternalEngine,\n getParallelEngine,\n switchCtx,\n switchProjectInPlace,\n };\n\n renderer.setTuiActive(true);\n try {\n code = await runTuiDispatch({\n agent,\n events,\n slashRegistry,\n secretInputController,\n attachments,\n tokenCounter,\n visionAdapters,\n supportsVision,\n model: context.model,\n banner: !flags['no-banner'],\n queueStore,\n onQueueChange: (items: string[]) => {\n setQueuedMessagesSnapshot(context, items);\n },\n mouse: flags.mouse ? true : undefined,\n yolo: !!config.yolo,\n getYolo,\n onYolo,\n getAutonomy,\n ...createTuiNextStepCallbacks({\n context,\n getNextPredict,\n getAutonomy,\n getSuggestions,\n }),\n getEternalEngine,\n getSddRun,\n onSddLifecycle,\n subscribeEternalIteration,\n subscribeEternalStage,\n subscribeGoal,\n appVersion: CLI_VERSION,\n latestVersion: bootUpdateInfo?.latest,\n updateAvailable: bootUpdateInfo?.outdated,\n provider: config.provider,\n family: banneredFamily,\n keyTail: banneredKeyTail,\n profile: profileName,\n profileConfigPath: (() => {\n const abs = wpaths.profileConfig(profileName);\n const home = wpaths.homeDir;\n return home && abs.startsWith(home) ? `~${abs.slice(home.length)}` : abs;\n })(),\n getPickableProviders,\n switchProviderAndModel,\n switchAutonomy: (mode: 'off' | 'suggest' | 'auto' | 'eternal' | 'eternal-parallel') => {\n onAutonomy?.(mode);\n return null;\n },\n ...createSettingsAdapter({\n configStore,\n wpaths,\n fleetStreamController,\n applyLiveSettings,\n }),\n effectiveMaxContext,\n titleAnimation:\n ((config.autonomy as Record<string, unknown> | undefined)?.[\n 'terminalTitleAnimation'\n ] as boolean) ?? true,\n chime:\n ((config.autonomy as Record<string, unknown> | undefined)?.['chime'] as boolean) ??\n false,\n confirmExit:\n ((config.autonomy as Record<string, unknown> | undefined)?.[\n 'confirmExit'\n ] as boolean) ?? true,\n director,\n getDirector,\n fleetRoster,\n ...createTuiCoordinatorCallbacks({\n state,\n context,\n coordinatorEvents,\n ensureAutonomousCoordinator,\n }),\n onClearHistory: (\n dispatch: (\n action:\n | {\n type: 'clearHistory';\n model?: string | undefined;\n provider?: string | undefined;\n }\n | { type: 'resetContextChip' }\n | { type: 'streamReset' }\n | { type: 'toolStreamClear' },\n ) => void,\n ) => {\n dispatch({ type: 'clearHistory', model: context.model, provider: context.provider.id });\n dispatch({ type: 'resetContextChip' });\n dispatch({ type: 'streamReset' });\n dispatch({ type: 'toolStreamClear' });\n },\n fleetStreamController,\n interruptController,\n enhanceController,\n getEnhancerReasoning,\n buildEnhancerProvider,\n getEnhanceFallbackRef,\n getConfiguredRefinerRef,\n statuslineHiddenItems,\n setStatuslineHiddenItems,\n saveStatuslineHiddenItems,\n getPluginItems,\n onPluginToggle,\n getMcpServers,\n onMcpToggle,\n onMcpRestart,\n getToolsItems,\n onToolToggle,\n getBrainData,\n onBrainRiskLevel,\n brainPanelHost: brainRuntime ? createBrainPanelHost({ brainRuntime }) : undefined,\n getShadowData,\n onShadowStart,\n onShadowStop,\n authHost,\n agentsMonitorController,\n agentTranscripts,\n getLiveSessions: () => getLiveSessions({ state }),\n onSwitchToSession: (_sessionId: string, targetRoot: string, projectName: string) =>\n onSwitchToSession({ state }, _sessionId, targetRoot, projectName),\n initialGoal: goalFlag,\n initialAsk: askFlag,\n projectRoot,\n appConfig: config,\n hqTelemetryOwnedExternally: true,\n getSessionId: () => agent.ctx.session?.id ?? session.id,\n getSDDContext: () => getSDDContextExtracted(),\n onSDDOutput: (output: string) => onSDDOutputExtracted(output),\n modeLabel: modeId,\n getModeLabel: () => {\n const metaMode = context.meta?.['mode'];\n return typeof metaMode === 'string' ? metaMode : (modeId ?? 'default');\n },\n getModes: modeStore\n ? async () => {\n const [modes, active] = await Promise.all([\n modeStore.listModes(),\n modeStore.getActiveMode(),\n ]);\n return { modes, activeId: active?.id ?? null };\n }\n : undefined,\n switchMode: modeStore\n ? async (id: string) => {\n const prev = await modeStore.getActiveMode();\n await modeStore.setActiveMode(id);\n const active = await modeStore.getActiveMode();\n const from = prev?.id ?? 'default';\n if (agent.ctx.session && from !== id) {\n void agent.ctx.session\n .append({ type: 'mode_changed', ts: new Date().toISOString(), from, to: id })\n .catch(() => {});\n }\n return active?.name ?? null;\n }\n : undefined,\n registerDebugStreamCallback,\n restoreDebugStreamCallback,\n restoredMessages,\n restoredToolCalls,\n restoredEvents,\n listSessions: async (limit = 20) => {\n if (!activeSessionStore) return [];\n const summaries = await activeSessionStore.list(limit);\n const currentId = agent.ctx.session?.id ?? session.id;\n return summaries.map((s) => ({\n id: s.id,\n title: s.title ?? '',\n name: s.name,\n lastUserMessage: s.lastUserMessage,\n messageCount: s.messageCount,\n lastActivityAt: s.lastActivityAt,\n startedAt: s.startedAt ?? '',\n endedAt: s.endedAt,\n tokenTotal: s.tokenTotal ?? 0,\n iterationCount: s.iterationCount ?? 0,\n toolCallCount: s.toolCallCount ?? 0,\n toolErrorCount: s.toolErrorCount ?? 0,\n outcome: s.outcome,\n isCurrent: s.id === currentId,\n }));\n },\n onResumeSession: (sessionId: string) =>\n resumeSession(\n { state, agent, tokenCounter, switchProviderAndModel, events },\n sessionId,\n ),\n getProjectPickerItems: () => getProjectPickerItems(pickerCtx),\n onProjectSelect: (slug: string, kind: 'project' | 'action') =>\n onProjectSelect(pickerCtx, slug, kind),\n initialAgentsMonitorOpen: !!flags.quick,\n tokenSavingMode: normalizeTokenSavingTier(config.features.tokenSavingMode),\n toolCount: agent.tools.list().length,\n onPanelOpen,\n memoryStore,\n } as never as import('@wrongstack/tui').RunTuiOptions);\n\n const spawnResult = await handleProjectSwitchSpawn({\n code,\n pendingProjectSwitch: state.pendingProjectSwitch,\n });\n if (spawnResult !== null) return spawnResult;\n } finally {\n renderer.setTuiActive(false);\n offDirectorSpawned();\n }\n } else if (executionMode === 'webui') {\n code = await runWebUIDispatch({\n agent,\n events,\n session,\n config,\n flags,\n projectRoot,\n globalConfigPath: wpaths.globalConfig,\n profileConfigPath: wpaths.profileConfig(profileName),\n projectSessionsDir: wpaths.projectSessions,\n modelsRegistry,\n mcpRegistry,\n brain,\n brainSettings,\n brainRuntime,\n getBrainLog,\n subscribeEternalIteration,\n sessionStore: activeSessionStore,\n memoryStore,\n skillLoader,\n promptLoader,\n modeStore,\n modeId,\n needsSetup,\n renderer,\n onAutonomy,\n applyLiveSettings,\n activateSessionIdentity,\n rebindTodosCheckpoint,\n agentTranscripts,\n onModelContextResolved,\n sddSubagentFactory,\n statusTracker,\n updateInfo: bootUpdateInfo,\n ...createKanbanDispatchHandler({ config, events, skillLoader, sddSubagentFactory }),\n });\n } else {\n // Imported here rather than at module scope: this is the ONLY static\n // path from the always-loaded CLI graph into `@wrongstack/webui-server`\n // (831KB, +38.7MB heap / +80.2MB RSS standalone). `webui-server.ts`\n // itself is already loaded lazily from `boot/dispatch-webui.ts`, so this\n // one import was single-handedly defeating that boundary and making every\n // `wstack` invocation pay for a WebUI server that is off by default.\n const headlessKanbanMirror = projectRoot\n ? (await import('./webui-server/kanban-run-mirror.js')).createKanbanRunMirror({\n projectRoot,\n events,\n broadcast: () => {},\n log: (m) => console.log(m),\n })\n : null;\n try {\n code = await runRepl({\n agent,\n renderer,\n reader,\n slashRegistry,\n tokenCounter,\n visionAdapters,\n supportsVision,\n attachments,\n effectiveMaxContext,\n getEffectiveMaxContext,\n projectName: path.basename(projectRoot) || undefined,\n projectRoot,\n appConfig: config,\n getSessionId: () => agent.ctx.session?.id ?? session.id,\n getAutonomy,\n onAutonomy,\n getNextPredict,\n onSuggestionsParsed,\n getSuggestions,\n getAutoSuggestions,\n getYolo,\n autonomyNextPrompt,\n autoProceedDelayMs,\n onValidateAutoProceed,\n autoProceedMaxIterations,\n getEternalEngine,\n getParallelEngine,\n getSddRun,\n skillLoader,\n agentsMonitorController,\n fleetStreamController,\n interruptController,\n ...createReplFleetCallbacks({ director, getDirector }),\n onCountdownTick,\n onDestroy,\n });\n } finally {\n headlessKanbanMirror?.dispose();\n }\n }\n } finally {\n await finalizeExecutionCleanup({\n offStorageObservability,\n fleetStatusLine,\n onCoordinatorStop: onCoordinatorStopImpl,\n stats,\n renderer,\n detachTodosCheckpoint,\n mcpRegistry,\n agent,\n session,\n tokenCounter,\n events,\n getPendingChimeraWork: () => pendingChimeraWork,\n director,\n reader,\n });\n }\n return code;\n}\n", "/**\n * Single-shot dispatch \u2014 extracted from the tail of `execute()`.\n *\n * Follow-up to PR 6 (partial). The single-shot branch runs one\n * `agent.run()` turn from a positional/prompt argument, renders the\n * result, and returns an exit code. It is the simplest of the four\n * dispatch branches: no event loops, no server, no streaming UI \u2014\n * just run, render, exit.\n *\n * Returns the exit code (0 success, 1 failure/max-iterations, 130\n * aborted) so the caller assigns it to its `code` variable without a\n * closure mutation.\n */\nimport type { Agent } from '@wrongstack/core/agent';\nimport type { TokenCounter } from '@wrongstack/core/types';\nimport { color, writeOut } from '@wrongstack/core/utils';\nimport type { TerminalRenderer } from '../renderer.js';\nimport { contextOverflowHint } from '../context-overflow-diagnostic.js';\nimport { fmtTok } from '../utils.js';\n\nexport interface SingleShotDispatchContext {\n /** The agent to run. */\n agent: Agent;\n /** Joined positional args forming the query string. */\n query: string;\n /** Parsed top-level CLI flags (e.g. `--output-json`). */\n flags: Record<string, string | boolean>;\n /** Token counter for usage delta computation. */\n tokenCounter: TokenCounter;\n /** Terminal renderer for output. */\n renderer: TerminalRenderer;\n}\n\n/**\n * Run a single `agent.run()` turn and render the result.\n *\n * Returns the exit code: 0 success, 1 failure or max-iterations, 130\n * aborted.\n */\nexport async function runSingleShotDispatch(\n ctx: SingleShotDispatchContext,\n): Promise<number> {\n const { agent, query, flags, tokenCounter, renderer } = ctx;\n\n const ctrl = new AbortController();\n const onSigint = () => ctrl.abort();\n process.on('SIGINT', onSigint);\n const startedAt = Date.now();\n const before = tokenCounter.total();\n const costBefore = tokenCounter.estimateCost().total;\n let result: import('@wrongstack/core/agent').RunResult;\n try {\n result = await agent.run(query, { signal: ctrl.signal });\n } finally {\n process.off('SIGINT', onSigint);\n // Clean up any lingering bash/exec processes.\n const { getProcessRegistry } = await import('@wrongstack/tools');\n getProcessRegistry().killAll({ preserveBackground: true });\n }\n const after = tokenCounter.total();\n const costAfter = tokenCounter.estimateCost().total;\n const usage = {\n input: after.input - before.input,\n output: after.output - before.output,\n iterations: result.iterations,\n cost: costAfter - costBefore,\n elapsedMs: Date.now() - startedAt,\n };\n if (flags['output-json']) {\n const json = JSON.stringify({\n status: result.status,\n finalText: result.finalText ?? null,\n error: result.error\n ? {\n code: result.error.code,\n subsystem: result.error.subsystem,\n severity: result.error.severity,\n recoverable: result.error.recoverable,\n message: result.error.message,\n context: result.error.context ?? null,\n }\n : null,\n usage,\n });\n writeOut(json + '\\n');\n return 0;\n }\n\n let code = 0;\n if (result.status === 'failed') {\n code = 1;\n const err = result.error;\n if (err) {\n const tag = err.recoverable ? ' (recoverable)' : '';\n renderer.writeError(`Failed [${err.severity}]${tag}: ${err.describe()}`);\n const hint = contextOverflowHint(err);\n if (hint) renderer.writeWarning(hint);\n } else {\n renderer.writeError('Failed.');\n }\n } else if (result.status === 'aborted') {\n code = 130;\n renderer.writeWarning('Aborted.');\n } else if (result.status === 'max_iterations') {\n code = 1;\n renderer.writeWarning(`Hit max iterations (${result.iterations}).`);\n }\n if (result.finalText) renderer.write('\\n' + result.finalText + '\\n');\n // Surface any delegate subagent completion banners.\n const r = result as {\n delegateSummaries?: Array<{ summary: string | undefined; ok: boolean }>;\n messages?: Array<unknown> | undefined;\n };\n renderer.writeDelegateSummaries(r);\n renderer.write(\n '\\n' +\n color.dim(\n `[in: ${fmtTok(usage.input)} out: ${fmtTok(usage.output)} iters: ${usage.iterations} cost: ${usage.cost.toFixed(4)} ${(usage.elapsedMs / 1000).toFixed(1)}s]`,\n ) +\n '\\n',\n );\n return code;\n}\n", "import { ERROR_CODES, type WrongStackError } from '@wrongstack/core/types';\n\nconst CONTEXT_OVERFLOW_RE = /context window|exceeds the context|too many tokens|context.*tokens/i;\n\nexport function contextOverflowHint(err: WrongStackError): string | null {\n const structured =\n err.code === ERROR_CODES.PROVIDER_CONTEXT_OVERFLOW ||\n err.code === ERROR_CODES.AGENT_CONTEXT_OVERFLOW;\n const textual = CONTEXT_OVERFLOW_RE.test(`${err.message}\\n${err.describe()}`);\n if (!structured && !textual) return null;\n\n return [\n 'Provider rejected the request as over its effective context window.',\n 'If you use a custom baseUrl/proxy, the real limit may be lower than models.dev reports.',\n 'Try: /context limit 220k',\n 'Then, if needed: /context thresholds 50% 70% 85%',\n 'Persistent config: set context.effectiveMaxContext.',\n ].join('\\n');\n}\n", "/** Thin production boundary around the optional, dynamically loaded TUI. */\nimport type { RunTuiOptions } from '@wrongstack/tui';\n\nexport async function runTuiDispatch(options: RunTuiOptions): Promise<number> {\n const { runTui } = await import('@wrongstack/tui');\n return runTui(options);\n}\n", "/**\n * WebUI dispatch \u2014 extracted from the tail of `execute()`.\n *\n * PR 6 of Issue #29 (partial). The TUI-vs-REPL-vs-WebUI fork at the\n * end of `execute()` is a ~1,600-line `if/else if/else if/else`\n * chain. The WebUI branch is the most self-contained of the four: it\n * constructs a `runWebUI` options object from already-available deps,\n * wires SIGINT handling, and returns an exit code. Extracting it\n * first lets `execute()` shrink by ~100 lines and isolates the\n * WebUI-specific wiring (port resolution, browser banner and autonomy\n * forwarding) in a single named module.\n *\n * The TUI branch (~1,388 lines) and the single-shot branch are left\n * inline \u2014 they are too deeply coupled to local mutable state for a\n * single-PR extraction.\n */\nimport type { Agent } from '@wrongstack/core/agent';\nimport type { BrainArbiter } from '@wrongstack/core/coordination';\nimport type { JournalEntry } from '@wrongstack/core/goal';\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport type {\n Config,\n MemoryPort,\n ModelsRegistry,\n ModeStore,\n SessionStore,\n SessionWriter,\n SkillLoader,\n} from '@wrongstack/core/types';\nimport { color } from '@wrongstack/core/utils';\nimport type { MCPRegistry } from '@wrongstack/mcp';\nimport type { TerminalRenderer } from '../renderer.js';\nimport type { AutonomyMode } from '../services/autonomy-mode.js';\n\nexport interface WebUIDispatchContext {\n agent: Agent;\n events: EventBus;\n statusTracker?: import('@wrongstack/core/coordination').ProviderModelStatusTracker | undefined;\n session: SessionWriter;\n config: Config;\n flags: Record<string, string | boolean>;\n projectRoot: string;\n globalConfigPath: string;\n /** Resolved profile config path: ~/.wrongstack/profiles/<activeProfile>/config.json */\n profileConfigPath: string;\n projectSessionsDir: string;\n modelsRegistry: ModelsRegistry;\n mcpRegistry: MCPRegistry;\n brain: BrainArbiter | undefined;\n brainSettings:\n | {\n maxAutoRisk: import('@wrongstack/core/execution').BrainAutoRisk;\n mode?: import('@wrongstack/core/coordination').BrainEscalationMode | undefined;\n poolLabels?: string[] | undefined;\n councilLabels?: string[] | undefined;\n }\n | undefined;\n getBrainLog:\n | (() => Array<{ at: number; kind: string; question: string; outcome: string }>)\n | undefined;\n /** Live-editable Brain config owner (brain.config.get/set WS handlers). */\n brainRuntime?: import('@wrongstack/core/execution').BrainRuntime | undefined;\n subscribeEternalIteration: ((fn: (entry: JournalEntry) => void) => () => void) | undefined;\n sessionStore: SessionStore | undefined;\n memoryStore: MemoryPort | undefined;\n skillLoader: SkillLoader | undefined;\n promptLoader: import('@wrongstack/core/types').PromptLoader | undefined;\n modeStore: ModeStore | undefined;\n modeId: string | undefined;\n needsSetup: boolean | undefined;\n renderer: TerminalRenderer;\n onAutonomy: ((mode: AutonomyMode) => void) | undefined;\n applyLiveSettings?: ((settings: { yolo?: boolean }) => void) | undefined;\n onModelContextResolved?:\n | ((providerId: string, modelId: string, maxContext: number) => void)\n | undefined;\n activateSessionIdentity?:\n | ((\n sessionId: string,\n target?: import('../wiring/session-registry.js').SessionIdentityTarget,\n ) => Promise<void>)\n | undefined;\n rebindTodosCheckpoint?:\n | ((sessionId: string, sessionsDir?: string) => void | Promise<void>)\n | undefined;\n /** Read-only worker transcript snapshot used for browser refresh replay. */\n agentTranscripts?:\n | {\n getAllSessions(): import('@wrongstack/core/coordination').AgentVirtualSession[];\n loadSessionsFromDisk(): Promise<\n import('@wrongstack/core/coordination').AgentVirtualSession[]\n >;\n }\n | undefined;\n /**\n * Pre-computed update info from the CLI's preflight version check.\n * When present, surfaces (WebUI, SimpleUI) receive appVersion,\n * latestVersion, and updateAvailable fields in their session.start\n * payload to display an \"update available\" warning.\n */\n updateInfo?: import('../webui-server/session-start-payload.js').BootUpdateInfo | undefined;\n /** Per-task agent factory for the SDD wizard's multi-agent run. */\n sddSubagentFactory?: import('@wrongstack/core/coordination').AgentFactory | undefined;\n onKanbanDispatch?:\n | ((\n description: string,\n opts?: {\n provider?: string | undefined;\n model?: string | undefined;\n fallbackModels?: string[] | undefined;\n fallbackProfile?: string | undefined;\n skills?: string[] | undefined;\n tools?: string[] | undefined;\n name?: string | undefined;\n allowedCapabilities?: readonly string[] | undefined;\n onDone?:\n | ((result: {\n status: 'completed' | 'failed';\n result?: string | undefined;\n error?: string | undefined;\n }) => void | Promise<void>)\n | undefined;\n },\n ) => Promise<string>)\n | undefined;\n}\n\n/**\n * Run the WebUI server and block until it shuts down.\n *\n * Returns the exit code: 0 on clean shutdown, 1 on server error.\n */\nexport async function runWebUIDispatch(ctx: WebUIDispatchContext): Promise<number> {\n const {\n agent,\n events,\n statusTracker,\n session,\n config,\n flags,\n projectRoot,\n globalConfigPath,\n projectSessionsDir,\n modelsRegistry,\n mcpRegistry,\n brain,\n brainSettings,\n brainRuntime,\n getBrainLog,\n subscribeEternalIteration,\n sessionStore,\n memoryStore,\n skillLoader,\n promptLoader,\n modeStore,\n modeId,\n needsSetup,\n renderer,\n onAutonomy,\n applyLiveSettings,\n onModelContextResolved,\n activateSessionIdentity,\n rebindTodosCheckpoint,\n agentTranscripts,\n sddSubagentFactory,\n onKanbanDispatch,\n } = ctx;\n const isSimpleUi = flags['simpleui'] === true;\n\n // Route permission confirmations to the browser (tool.confirm_needed\n // events) instead of inline terminal prompts \u2014 runWebUI forwards them to\n // the WebUI and resolves on the client's tool.confirm_result. Without\n // this, approvals appear in the terminal even when you're driving the\n // agent from the browser.\n agent.disableInteractiveConfirmation();\n // Silence CLI rendering \u2014 WebUI owns the output surface. The writeInfo\n // calls below still flow (stderr), but streaming text/tool events are\n // suppressed so they don't appear in both the terminal and the browser.\n renderer.setSilent(true);\n const { runWebUI } = await import('../webui-server.js');\n\n const flagValue = (names: string[]): string | undefined => {\n for (const name of names) {\n if (!Object.hasOwn(flags, name)) continue;\n const value = flags[name];\n if (typeof value === 'string' && value.trim() !== '') return value.trim();\n throw new Error(`--${name} requires a value`);\n }\n return undefined;\n };\n const flagBoolean = (names: string[]): boolean | undefined => {\n for (const name of names) {\n if (!Object.hasOwn(flags, name)) continue;\n const value = flags[name];\n if (value === undefined) continue;\n if (typeof value === 'boolean') return value;\n const normalized = value.trim().toLowerCase();\n if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;\n if (['0', 'false', 'no', 'off'].includes(normalized)) return false;\n throw new Error(`--${name} must be a boolean value`);\n }\n return undefined;\n };\n const envFlag = (name: string): boolean => {\n const value = process.env[name]?.trim().toLowerCase();\n return value === '1' || value === 'true' || value === 'yes' || value === 'on';\n };\n const parsePort = (value: string | undefined, fallback: number, label: string): number => {\n if (value === undefined) return fallback;\n const parsed = Number.parseInt(value, 10);\n if (!Number.isInteger(parsed) || parsed <= 0 || parsed > 65535) {\n throw new Error(`${label} must be a port between 1 and 65535`);\n }\n return parsed;\n };\n\n let webuiHost: string;\n let webuiPort: number;\n let webuiAccessToken: string | undefined;\n let webuiPublicUrl: string | undefined;\n let webuiPublicWsUrl: string | undefined;\n let webuiRequireToken: boolean;\n let frontendDistDir: string | undefined;\n try {\n webuiHost =\n flagValue(['webui-host', 'host']) ??\n process.env['WEBUI_HOST'] ??\n process.env['WS_HOST'] ??\n '127.0.0.1';\n // HTTP and WebSocket upgrades share one listener. Keep the older\n // --http-port/--ws-port and environment names as aliases, but resolve\n // exactly one port so `--port` also controls the page users open.\n const defaultPort = isSimpleUi ? 3466 : 3456;\n webuiPort = parsePort(\n flagValue(['webui-port', 'http-port', 'port', 'ws-port']) ??\n process.env['WEBUI_PORT'] ??\n process.env['PORT'] ??\n process.env['WS_PORT'],\n defaultPort,\n '--port',\n );\n webuiAccessToken =\n flagValue(['webui-token']) ?? process.env['WEBUI_TOKEN'] ?? process.env['WEBUI_AUTH_TOKEN'];\n webuiPublicUrl =\n flagValue(['webui-public-url', 'public-url']) ?? process.env['WEBUI_PUBLIC_URL'];\n webuiPublicWsUrl =\n flagValue(['webui-public-ws-url', 'public-ws-url']) ?? process.env['WEBUI_PUBLIC_WS_URL'];\n webuiRequireToken =\n flagBoolean(['webui-require-token', 'require-token']) ?? envFlag('WEBUI_REQUIRE_TOKEN');\n if (isSimpleUi) {\n const { ensureSimpleUiDistDir } = await import('../simpleui-dist.js');\n frontendDistDir = await ensureSimpleUiDistDir();\n }\n } catch (err) {\n renderer.setSilent(false);\n renderer.writeInfo(color.red(` ${err instanceof Error ? err.message : String(err)}`));\n return 1;\n }\n\n const webuiPromise = runWebUI({\n agent,\n events,\n statusTracker,\n session,\n surface: isSimpleUi ? 'simpleui' : 'webui',\n host: webuiHost,\n port: webuiPort,\n frontendDistDir,\n accessToken: webuiAccessToken,\n publicUrl: webuiPublicUrl,\n publicWsUrl: webuiPublicWsUrl,\n requireToken: webuiRequireToken,\n projectRoot,\n appConfig: config,\n open: !!flags.open,\n agentTranscripts,\n hqAllowExec: flagBoolean(['hq-allow-exec']) ?? false,\n modelsRegistry,\n globalConfigPath,\n profileConfigPath: ctx.profileConfigPath,\n mcpRegistry,\n subscribeEternalIteration,\n sessionStore,\n sessionsDir: projectSessionsDir,\n claimSession: activateSessionIdentity\n ? async (sessionId: string) => {\n const previousSessionId = agent.ctx.session?.id ?? session.id;\n await activateSessionIdentity(sessionId);\n return async () => activateSessionIdentity(previousSessionId);\n }\n : undefined,\n brain,\n brainSettings,\n brainRuntime,\n getBrainLog,\n onBeforeSessionTodosReplaced: (sessionId, sessionsDir) =>\n rebindTodosCheckpoint?.(sessionId, sessionsDir),\n onSessionSwapped: async (sessionId, target) => {\n if (target && activateSessionIdentity) {\n await activateSessionIdentity(sessionId, target);\n }\n void import('@wrongstack/tools/session-kanban').then(({ hydrateSessionKanban }) =>\n hydrateSessionKanban(agent.ctx),\n );\n },\n onModelContextResolved,\n memoryStore,\n skillLoader,\n promptLoader,\n modeStore,\n modeId,\n needsSetup,\n sddSubagentFactory,\n updateInfo: ctx.updateInfo,\n onKanbanDispatch,\n // Print the \"open this\" banner only once the server is actually\n // listening, using the RESOLVED port. Requested ports auto-advance past\n // busy ports inside runWebUI, so a banner printed up-front lies whenever\n // the default when it is taken (a second instance, leftover socket).\n onListening: ({ url }) => {\n const surface = isSimpleUi ? 'SimpleUI' : 'WebUI';\n renderer.writeInfo(color.green(` \u2726 ${surface} running \u2192 ${color.bold(url)}`));\n renderer.writeInfo(\n color.dim(` Press Ctrl+C in this terminal to stop the ${surface} server.\\n`),\n );\n },\n // Make autonomy.switch from the browser flip the CLI's real\n // autonomy mode \u2014 context.meta alone never reaches the run loop.\n onAutonomySwitch: (mode: string) => {\n if (\n mode === 'off' ||\n mode === 'suggest' ||\n mode === 'auto' ||\n mode === 'eternal' ||\n mode === 'eternal-parallel'\n ) {\n onAutonomy?.(mode as AutonomyMode);\n }\n },\n onYoloSwitch: (enabled: boolean) => {\n applyLiveSettings?.({ yolo: enabled });\n },\n });\n // In --webui mode, skip the full REPL \u2014 just keep the process alive\n // until the WebUI server shuts down. The WebUI WS handler listens for\n // /exit or abort signals and resolves webuiPromise when the server stops.\n // The ready banner is printed from `onListening` above (with the resolved\n // ports), not here \u2014 printing it up-front with the requested port lied\n // whenever the port auto-advanced.\n const webuiExit = new Promise<number>((resolve) => {\n // SIGINT/SIGTERM handlers are owned by `runWebUI` itself (via\n // registerWebuiSignalHandlers + createWebuiShutdown, which does the\n // real teardown chain: abort in-flight runs \u2192 unsubscribe events \u2192\n // close clients \u2192 unregister \u2192 close HTTP/WS \u2192 resolve). The dispatch\n // does NOT install its own SIGINT handlers \u2014 doing so races the\n // internal shutdown and was the source of the SIGINT bug where the\n // outer promise resolved with 0 immediately while the WebUI server\n // kept running until the parent process exited.\n webuiPromise\n .then(() => {\n renderer.setSilent(false);\n renderer.write('\\n');\n renderer.writeInfo(\n color.yellow(` Shutting down ${isSimpleUi ? 'SimpleUI' : 'WebUI'} server\u2026`),\n );\n resolve(0);\n })\n .catch((err) => {\n renderer.setSilent(false);\n console.debug(`[execution] webui error: ${err}`);\n resolve(1);\n });\n });\n return webuiExit;\n}\n", "/**\n * Canonical execution-surface selection for the CLI composition root.\n *\n * Keep precedence here instead of duplicating flag checks across boot tests,\n * launchers, and execute(): a one-shot prompt owns the process, WebUI owns\n * stdout when requested alongside TUI, and --no-tui falls back to REPL.\n */\nexport type ExecutionMode = 'single-shot' | 'tui' | 'webui' | 'repl';\n\nexport function resolveExecutionMode(\n positional: readonly string[],\n flags: Readonly<Record<string, string | boolean>>,\n): ExecutionMode {\n const prompt = typeof flags['prompt'] === 'string' ? flags['prompt'] : '';\n if (positional.length > 0 || prompt.length > 0) return 'single-shot';\n if (flags.tui && flags['no-tui'] !== true && !flags.webui) return 'tui';\n if (flags.webui) return 'webui';\n return 'repl';\n}\n", "import type { Context } from '@wrongstack/core/agent';\nimport type { AutonomousCoordinator, CoordinatorEvent } from '@wrongstack/core/coordination';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\n\nexport interface TuiCoordinatorCallbacksContext {\n state: TuiRuntimeState;\n context: Context;\n coordinatorEvents: Set<(event: CoordinatorEvent) => void>;\n ensureAutonomousCoordinator: () => AutonomousCoordinator | null;\n}\n\nexport function createTuiCoordinatorCallbacks({\n state,\n context,\n coordinatorEvents,\n ensureAutonomousCoordinator,\n}: TuiCoordinatorCallbacksContext) {\n return {\n getAutonomousCoordinator: () => ensureAutonomousCoordinator(),\n subscribeCoordinatorEvents: (fn: (event: CoordinatorEvent) => void) => {\n coordinatorEvents.add(fn);\n return () => {\n coordinatorEvents.delete(fn);\n };\n },\n onCoordinatorStart: (goal?: string) => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'coordinator.not_ready',\n message: 'no director available',\n timestamp: new Date().toISOString(),\n }),\n );\n return;\n }\n if (state.coordinatorRun) return;\n state.coordinatorRun = coordinator\n .run({ goal: goal ?? 'Improve the codebase', runUntilComplete: true })\n .then(() => undefined)\n .catch((err) => {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'coordinator.run_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n })\n .finally(() => {\n state.coordinatorRun = null;\n });\n },\n onCoordinatorStop: () => {\n state.autonomousCoordinator?.stop();\n },\n onCoordinatorTasks: async () => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) return null;\n await coordinator.graph.load();\n return coordinator.auction.getPendingTasks().map((task) => ({\n id: task.id,\n title: task.title,\n priority: task.priority,\n tags: task.tags,\n }));\n },\n onCoordinatorClaim: async (taskId: string) => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) return 'No coordinator is active.';\n await coordinator.graph.load();\n const goal = coordinator.graph.get(taskId) as\n | import('@wrongstack/core/coordination').GoalNode\n | undefined;\n if (goal?.type !== 'goal') {\n return `Task ${taskId.slice(0, 8)} not found in the coordinator graph.`;\n }\n if (goal.status !== 'pending') {\n return `Task ${taskId.slice(0, 8)} is ${goal.status}, not claimable.`;\n }\n const ok = await coordinator.auction.claim(\n taskId,\n `terminal@${context.session.id ?? 'unknown'}`,\n 'Terminal worker',\n );\n if (!ok) {\n return `Task ${taskId.slice(0, 8)} could not be claimed (status changed?).`;\n }\n return { description: goal.description };\n },\n onCoordinatorComplete: async (taskId: string, result?: string) => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) return 'No coordinator is active.';\n await coordinator.graph.load();\n const goal = coordinator.graph.get(taskId) as\n | import('@wrongstack/core/coordination').GoalNode\n | undefined;\n if (goal?.type !== 'goal') {\n return `Task ${taskId.slice(0, 8)} not found in the coordinator graph.`;\n }\n if (goal.status !== 'in_progress') {\n return `Task ${taskId.slice(0, 8)} is ${goal.status}, cannot complete.`;\n }\n await coordinator.reportTaskCompletion(\n taskId,\n result ?? 'Terminal worker completed the task',\n );\n return null;\n },\n onCoordinatorFail: async (taskId: string, error: string) => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) return 'No coordinator is active.';\n await coordinator.graph.load();\n const goal = coordinator.graph.get(taskId) as\n | import('@wrongstack/core/coordination').GoalNode\n | undefined;\n if (goal?.type !== 'goal') {\n return `Task ${taskId.slice(0, 8)} not found in the coordinator graph.`;\n }\n if (goal.status !== 'in_progress') {\n return `Task ${taskId.slice(0, 8)} is ${goal.status}, cannot fail.`;\n }\n await coordinator.reportTaskFailure(taskId, error);\n return null;\n },\n onCoordinatorStatus: async () => {\n const coordinator = ensureAutonomousCoordinator();\n if (!coordinator) return null;\n await coordinator.syncFromGraph();\n const stats = coordinator.getStats();\n return {\n goals: {\n total: stats.goals.total,\n done: stats.goals.done,\n pending: stats.goals.pending,\n failed: stats.goals.failed,\n },\n dag: {\n running: stats.dag.running,\n ready: stats.dag.ready,\n done: stats.dag.done,\n failed: stats.dag.failed,\n },\n auction: {\n pending: stats.auction.pending,\n inProgress: stats.auction.in_progress,\n },\n };\n },\n };\n}\n", "/**\n * AutonomousCoordinator setup \u2014 extracted from the TUI branch of execute().\n *\n * Phase B step 1. The coordinator tracks goals, tasks, knowledge, and\n * consensus across all active sessions in the same project. It is\n * initialized lazily when the Director becomes available so we have\n * access to director.fleet for cross-session events.\n *\n * This module owns:\n * - The `ensureAutonomousCoordinator()` factory (constructs the\n * coordinator, wires the LLM provider adapter, populates the\n * mutable controller with 7 task-management callbacks)\n * - The Director lifecycle hook (immediate wire if director exists,\n * or deferred until the first `subagent.spawned` event)\n *\n * Mutations are written to `state.autonomousCoordinator` and\n * `state.coordinatorEvents` (both on the shared TuiRuntimeState).\n */\nimport * as path from 'node:path';\nimport { AutonomousCoordinator, type Director, type Mailbox } from '@wrongstack/core/coordination';\nimport type { Context } from '@wrongstack/core/agent';\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport type { LLMProvider } from '@wrongstack/core/coordination';\nimport type { WstackPaths } from '@wrongstack/core/utils';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\n\nexport interface CoordinatorSetupContext {\n /** The shared mutable runtime state. */\n state: TuiRuntimeState;\n /** The main EventBus \u2014 used for the Director lifecycle hook. */\n events: EventBus;\n /** The agent's Context \u2014 provides provider, model, session id, transcript path. */\n context: Context;\n /** Resolved WrongStack paths \u2014 used for session-dir resolution. */\n wpaths: WstackPaths;\n /** The mailbox \u2014 cast to the core Mailbox interface for the coordinator. */\n mailbox: unknown;\n /** The Director (may be null \u2014 coordinator waits for lazy spawn). */\n director: Director | null | undefined;\n /** Optional getter for a lazily-created Director. */\n getDirector: (() => Director | null | undefined) | undefined;\n /** The mutable controller object slash commands read/write. */\n coordinatorController: Record<string, unknown> | undefined;\n /** Set by this module so execute()'s finally block can stop the coordinator. */\n onCoordinatorStopSetter: (fn: (() => void) | undefined) => void;\n}\n\nexport interface CoordinatorSetupResult {\n /** The ensureAutonomousCoordinator function (idempotent). */\n ensure: () => AutonomousCoordinator | null;\n /** Call to remove the Director lifecycle listener (for TUI cleanup). */\n cleanup: () => void;\n}\n\n/**\n * Wire the AutonomousCoordinator and its Director lifecycle hook.\n *\n * Returns the `ensure` function (idempotent \u2014 returns the existing\n * coordinator if already created) and a `cleanup` function that removes\n * the event listener.\n */\nexport function setupAutonomousCoordinator(\n ctx: CoordinatorSetupContext,\n): CoordinatorSetupResult {\n const { state, events, context, wpaths, mailbox, director, getDirector, coordinatorController, onCoordinatorStopSetter } = ctx;\n\n const ensure = (): AutonomousCoordinator | null => {\n if (state.autonomousCoordinator) return state.autonomousCoordinator;\n const currentDirector = getDirector?.() ?? director;\n if (!currentDirector) return null;\n\n // Resolve the session dir from the transcript path (e.g.\n // \"~/.wrongstack/.../sessions/<date>/sess_<ULID>.jsonl\" \u2192 parent dir). Fall back\n // to the global project dir when the writer is in-memory.\n const transcript = context.session.transcriptPath;\n const sessionDir = transcript\n ? path.dirname(transcript)\n : wpaths.projectDir;\n\n // Adapt Context.provider (Wire provider) to AutonomousBrain.LLMProvider\n // (one-method LLM call). The brain calls decide(prompt) \u2192 option+rationale.\n const llmProvider: LLMProvider = {\n decide: async (prompt) => {\n const sysPrompt = [\n {\n type: 'text' as const,\n text: 'You are the autonomous brain of a multi-agent coordination system. '\n + 'Pick the best option for the decision described and reply with JSON: '\n + '{\"optionId\":\"<id>\",\"rationale\":\"<short why>\"}.',\n },\n ];\n const userPrompt = {\n type: 'text' as const,\n text: `Decision: ${prompt.question}\\n\\n`\n + `Context: ${JSON.stringify(prompt.context)}\\n\\n`\n + `Options:\\n${prompt.options\n .map((o, i) => ` ${i + 1}. [${o.id}] ${o.label}${o.consequence ? ` \u2014 ${o.consequence}` : ''}`)\n .join('\\n')}\\n\\n`\n + `Risk: ${prompt.risk}\\n\\n`\n + 'Reply with ONLY the JSON object.',\n };\n const resp = await context.provider.complete(\n {\n model: context.model,\n system: sysPrompt,\n messages: [\n {\n role: 'user',\n content: [userPrompt],\n },\n ],\n maxTokens: 1024,\n temperature: 0,\n },\n { signal: context.signal },\n );\n const text = resp.content\n .filter((b): b is { type: 'text'; text: string } => (b as { type?: string }).type === 'text')\n .map((b) => b.text)\n .join('\\n')\n .trim();\n // Parse the JSON, tolerate code fences.\n const cleaned = text.replace(/^```(?:json)?\\s*/i, '').replace(/```$/, '').trim();\n try {\n const parsed = JSON.parse(cleaned) as { optionId?: string; rationale?: string };\n const optId = parsed.optionId ?? prompt.options[0]?.id ?? '';\n return { optionId: optId, rationale: parsed.rationale ?? '' };\n } catch {\n // Fallback: pick the first option.\n return { optionId: prompt.options[0]?.id ?? '', rationale: text };\n }\n },\n };\n\n state.autonomousCoordinator = new AutonomousCoordinator({\n sessionDir,\n fleet: currentDirector.fleet,\n fleetManager: currentDirector.fleetManager,\n director: currentDirector,\n mailbox: mailbox as never as Mailbox,\n selfAgentId: `leader@${context.session.id ?? 'unknown'}`,\n selfAgentName: 'Leader',\n llmProvider,\n onCoordinatorEvent: (event) => {\n for (const fn of state.coordinatorEvents) fn(event);\n },\n });\n\n // Wire the stop call so execute()'s finally block can cleanly shut down\n // the coordinator when the TUI exits (Ctrl+C, /exit, or session end).\n onCoordinatorStopSetter(() => state.autonomousCoordinator?.dispose());\n\n // Populate the mutable controller so slash commands (built before\n // execute() was called) can reach the coordinator callbacks.\n if (coordinatorController) {\n coordinatorController['onCoordinatorStart'] = (goal?: string) => {\n const coordinator = state.autonomousCoordinator;\n if (!coordinator) return;\n coordinator.run({ goal: goal ?? 'Improve the codebase', runUntilComplete: true })\n .then(() => undefined)\n .catch((err: unknown) =>\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'coordinator.run_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n ),\n );\n };\n coordinatorController['onCoordinatorStop'] = () => state.autonomousCoordinator?.stop();\n coordinatorController['onCoordinatorTasks'] = async () => {\n if (!state.autonomousCoordinator) return null;\n await state.autonomousCoordinator.graph.load();\n return state.autonomousCoordinator.auction\n .getPendingTasks()\n .map((task) => ({ id: task.id, title: task.title, priority: task.priority, tags: task.tags }));\n };\n coordinatorController['onCoordinatorClaim'] = async (taskId: string) => {\n if (!state.autonomousCoordinator) return 'No coordinator is active.';\n await state.autonomousCoordinator.graph.load();\n const goal = state.autonomousCoordinator.graph.get(taskId) as import('@wrongstack/core/coordination').GoalNode | undefined;\n if (goal?.type !== 'goal') return `Task ${taskId.slice(0, 8)} not found.`;\n if (goal.status !== 'pending') return `Task ${taskId.slice(0, 8)} is ${goal.status}, not claimable.`;\n const ok = await state.autonomousCoordinator.auction.claim(\n taskId, `terminal@${context.session.id ?? 'unknown'}`, 'Terminal worker',\n );\n if (!ok) return `Task ${taskId.slice(0, 8)} could not be claimed.`;\n return { description: goal.description };\n };\n coordinatorController['onCoordinatorComplete'] = async (taskId: string, result?: string) => {\n if (!state.autonomousCoordinator) return 'No coordinator is active.';\n await state.autonomousCoordinator.graph.load();\n const goal = state.autonomousCoordinator.graph.get(taskId) as import('@wrongstack/core/coordination').GoalNode | undefined;\n if (goal?.type !== 'goal') return `Task ${taskId.slice(0, 8)} not found.`;\n if (goal.status !== 'in_progress') return `Task ${taskId.slice(0, 8)} is ${goal.status}, cannot complete.`;\n await state.autonomousCoordinator.reportTaskCompletion(taskId, result ?? 'Terminal worker completed the task');\n return null;\n };\n coordinatorController['onCoordinatorFail'] = async (taskId: string, error: string) => {\n if (!state.autonomousCoordinator) return 'No coordinator is active.';\n await state.autonomousCoordinator.graph.load();\n const goal = state.autonomousCoordinator.graph.get(taskId) as import('@wrongstack/core/coordination').GoalNode | undefined;\n if (goal?.type !== 'goal') return `Task ${taskId.slice(0, 8)} not found.`;\n if (goal.status !== 'in_progress') return `Task ${taskId.slice(0, 8)} is ${goal.status}, cannot fail.`;\n await state.autonomousCoordinator.reportTaskFailure(taskId, error);\n return null;\n };\n coordinatorController['onCoordinatorStatus'] = async () => {\n if (!state.autonomousCoordinator) return null;\n await state.autonomousCoordinator.syncFromGraph();\n const stats = state.autonomousCoordinator.getStats();\n return {\n goals: { total: stats.goals.total, done: stats.goals.done, pending: stats.goals.pending, failed: stats.goals.failed },\n dag: { running: stats.dag.running, ready: stats.dag.ready, done: stats.dag.done, failed: stats.dag.failed },\n auction: { pending: stats.auction.pending, inProgress: stats.auction.in_progress },\n };\n };\n }\n\n return state.autonomousCoordinator;\n };\n\n // Hook into Director lifecycle: Director is created lazily on first subagent.spawned.\n // If it already exists, wire immediately; otherwise wait for the spawn event.\n if (director) ensure();\n const offDirectorSpawned = events.onPattern('subagent.spawned', () => {\n if (ensure()) offDirectorSpawned();\n });\n\n return {\n ensure,\n cleanup: () => offDirectorSpawned(),\n };\n}\n", "/**\n * TUI debug-stream callbacks \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 6. registerDebugStreamCallback swaps the debug-stream\n * callback from stderr \u2192 TUI reducer; restoreDebugStreamCallback reverts\n * to the default on TUI unmount. Both are pure delegates to\n * @wrongstack/providers with structured error logging.\n */\n\n/**\n * Swap the debug-stream callback to the TUI reducer.\n * Restored on TUI unmount via restoreDebugStreamCallback.\n */\nexport async function registerDebugStreamCallback(\n cb: import('@wrongstack/providers').DebugStreamCallback,\n): Promise<void> {\n try {\n const { setDebugStreamCallback } = await import('@wrongstack/providers');\n setDebugStreamCallback(cb);\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.debug_stream_register_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n}\n\n/**\n * Restore the default debug-stream callback (stderr).\n */\nexport async function restoreDebugStreamCallback(): Promise<void> {\n try {\n const { setDebugStreamCallback, defaultDebugStreamCallback } = await import(\n '@wrongstack/providers'\n );\n setDebugStreamCallback(defaultDebugStreamCallback);\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.debug_stream_restore_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n}\n", "/**\n * Goal event forwarding \u2014 extracted from the TUI branch of execute().\n *\n * Subscribes to PhaseOrchestrator events on the main EventBus and forwards\n * them to a TUI handler so the PhaseMonitor/PhasePanel stay in sync with\n * the running graph. The event list is static; the only runtime input is\n * the EventBus instance.\n *\n * Returns a subscribe function (called by runTui) and a cleanup function\n * (called on TUI teardown).\n */\nimport { PHASE_EVENT_NAMES } from '@wrongstack/core/goal';\nimport type { EventBus } from '@wrongstack/core/kernel';\n\n/**\n * The full set of events forwarded from the EventBus to the TUI's\n * Goal/Coordinator/Worktree/Countdown monitors.\n *\n * Imported from `@wrongstack/core`'s `PHASE_EVENT_NAMES` const array so the\n * compiler catches drift when events are added or renamed.\n */\nconst GOAL_EVENTS: readonly string[] = [\n ...PHASE_EVENT_NAMES,\n // Extra events not in PhaseEventMap (sourced from other subsystems)\n 'sdd.board.snapshot',\n 'worktree.allocated',\n 'worktree.committed',\n 'worktree.merged',\n 'worktree.conflict',\n 'worktree.released',\n 'worktree.failed',\n 'countdown.tick',\n];\n\nexport interface GoalWiring {\n /**\n * Called by the TUI to receive forwarded events. Each call registers\n * one listener per event name; the returned function unregisters all.\n */\n subscribe: (handler: (event: string, payload: unknown) => void) => () => void;\n /** Remove all listeners. Safe to call multiple times. */\n cleanup: () => void;\n}\n\n/**\n * Wire Goal event forwarding on the given EventBus.\n *\n * Goal events are emitted on the untyped surface of the bus (the\n * orchestrator casts `emit` to a string-keyed signature), so we subscribe\n * through the same untyped view rather than the typed event-name overloads.\n *\n * Bind to `events` \u2014 pulling the method off the bus as a bare reference\n * loses `this`, so `on`/`off` would read `this.listeners` off `undefined`\n * and throw the moment Goal subscribes.\n */\nexport function wireGoal(events: EventBus): GoalWiring {\n const handlers = new Map<string, (payload: unknown) => void>();\n\n const onUntyped = events.on.bind(events) as never as (\n event: string,\n handler: (payload: unknown) => void,\n ) => void;\n const offUntyped = events.off.bind(events) as never as (\n event: string,\n handler: (payload: unknown) => void,\n ) => void;\n\n const subscribe = (handler: (event: string, payload: unknown) => void): (() => void) => {\n const registrations: Array<() => void> = [];\n for (const ev of GOAL_EVENTS) {\n const h = (p: unknown) => handler(ev, p);\n handlers.set(ev, h);\n onUntyped(ev, h);\n registrations.push(() => offUntyped(ev, h));\n }\n return () => {\n for (const unregister of registrations) unregister();\n handlers.clear();\n };\n };\n\n const cleanup = (): void => {\n for (const [ev, h] of handlers) {\n offUntyped(ev, h);\n }\n handlers.clear();\n };\n\n return { subscribe, cleanup };\n}\n", "/**\n * TUI live sessions callbacks \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 4. getLiveSessions queries the SessionRegistry for live\n * sessions across all projects; onSwitchToSession records a pending\n * project switch for the spawn-after-exit path.\n *\n * Reads mutable state (wpaths, pendingProjectSwitch) through TuiRuntimeState.\n */\nimport * as path from 'node:path';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\n\nexport interface LiveSessionsContext {\n state: TuiRuntimeState;\n}\n\n/**\n * List live sessions from the global SessionRegistry.\n * Filters out 'stale' entries. Called when the F10 sessions panel opens.\n */\nexport async function getLiveSessions(ctx: LiveSessionsContext) {\n const { SessionRegistry } = await import('@wrongstack/core/storage');\n const globalRoot = path.dirname(ctx.state.wpaths.globalConfig);\n const registry = new SessionRegistry(globalRoot);\n const sessions = await registry.list();\n return sessions\n .filter((s) => s.status !== 'stale')\n .map((s) => ({\n sessionId: s.sessionId,\n projectName: s.projectName,\n projectSlug: s.projectSlug,\n projectRoot: s.projectRoot,\n workingDir: s.workingDir,\n gitBranch: s.gitBranch,\n status: s.status,\n pid: s.pid,\n startedAt: s.startedAt,\n agentCount: s.agentCount,\n agents: s.agents.map((a) => ({\n id: a.id,\n name: a.name,\n status: a.status,\n currentTool: a.currentTool,\n iterations: a.iterations,\n toolCalls: a.toolCalls,\n lastActivityAt: a.lastActivityAt,\n })),\n }));\n}\n\n/**\n * Record a pending project switch for a live session.\n *\n * Deliberately NOT `--resume <sessionId>`: the F10 panel lists LIVE\n * sessions (their owner processes are alive \u2014 'stale' is filtered out),\n * and resuming one would put two processes on the same session JSONL.\n * We open the target project fresh instead.\n */\nexport function onSwitchToSession(\n ctx: LiveSessionsContext,\n _sessionId: string,\n targetRoot: string,\n projectName: string,\n): void {\n ctx.state.pendingProjectSwitch = { root: targetRoot, name: projectName };\n}\n", "/**\n * TUI project picker callbacks \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 3. getProjectPickerItems loads project items from the\n * global manifest; onProjectSelect re-roots the live TUI process to the\n * selected project via switchProjectInPlace, with warnings for active\n * background work.\n *\n * Reads mutable state (projectRoot, wpaths) from TuiRuntimeState.\n */\nimport * as path from 'node:path';\nimport type { Director } from '@wrongstack/core/coordination';\nimport { color } from '@wrongstack/core/utils';\nimport type { TerminalRenderer } from '../renderer.js';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\nimport type { ProjectSwitchContext } from './tui-project-switch.js';\n\nexport interface ProjectPickerContext {\n state: TuiRuntimeState;\n renderer: TerminalRenderer;\n director: Director | null | undefined;\n getEternalEngine: (() => { currentState: string } | null) | undefined;\n getParallelEngine: (() => { currentState: string } | null) | undefined;\n switchCtx: ProjectSwitchContext;\n switchProjectInPlace: (targetRoot: string, displayName: string) => Promise<string | null>;\n}\n\n/**\n * Load project picker items from the global manifest.\n * Called each time the project picker panel opens (F1).\n */\nexport async function getProjectPickerItems(ctx: ProjectPickerContext) {\n const { buildPickerItems } = await import('../project-picker.js');\n return buildPickerItems({\n globalConfigPath: ctx.state.wpaths.globalConfig,\n currentProjectRoot: ctx.state.projectRoot,\n });\n}\n\n/**\n * Called when the user selects a project in the picker.\n * Re-roots the live TUI process in place: new Context root, fresh\n * per-project session writer, rebuilt system prompt, and no spawned\n * replacement process.\n */\nexport async function onProjectSelect(\n ctx: ProjectPickerContext,\n slug: string,\n kind: 'project' | 'action',\n): Promise<void> {\n const { state, renderer, director, getEternalEngine, getParallelEngine, switchProjectInPlace } = ctx;\n\n try {\n if (kind === 'action') {\n if (slug === 'new-session') {\n const name = path.basename(state.projectRoot) || state.projectRoot;\n const err = await switchProjectInPlace(state.projectRoot, name);\n if (err) renderer.write(color.red(`Project switch failed: ${err}\\n`));\n }\n // prev-sessions is handled inside the TUI (/resume picker).\n return;\n }\n\n const { loadManifest, saveManifest } = await import('../services/project-manifest.js');\n const manifest = await loadManifest(state.wpaths.globalConfig);\n const project = manifest.projects.find((p) => p.slug === slug);\n if (!project) return;\n\n const targetRoot = path.resolve(project.root);\n if (path.resolve(state.projectRoot) === targetRoot) return;\n\n const fleetStatus = director?.status();\n const fleetRunning =\n fleetStatus?.subagents.filter((a) => a.status === 'running').length ?? 0;\n const eternalActive = getEternalEngine?.()?.currentState === 'running';\n const parallelActive = getParallelEngine?.()?.currentState === 'running';\n const hasActiveAgents = fleetRunning > 0 || eternalActive || parallelActive;\n\n if (hasActiveAgents) {\n const parts: string[] = [\n color.yellow('\u26A0 Switching project in place; active background work is still tied to the previous project:'),\n ];\n if (fleetRunning > 0) parts.push(color.dim(` \u2022 ${fleetRunning} subagent(s) currently running`));\n if (eternalActive) parts.push(color.dim(' \u2022 Eternal engine is active'));\n if (parallelActive) parts.push(color.dim(' \u2022 Parallel engine is active'));\n parts.push('');\n parts.push(color.dim(` New project: ${project.name}`));\n renderer.write(`\\n${parts.join('\\n')}\\n`);\n }\n\n project.lastSeen = new Date().toISOString();\n await saveManifest(manifest, state.wpaths.globalConfig);\n\n const err = await switchProjectInPlace(targetRoot, project.name);\n if (err) renderer.write(color.red(`Project switch failed: ${err}\\n`));\n } catch (err) {\n renderer.write(\n color.red(\n `Project switch failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n ),\n );\n }\n}\n", "/**\n * Post-runTui project-switch spawn \u2014 extracted from the TUI branch of execute().\n *\n * After the TUI exits with PROJECT_SWITCH_EXIT_CODE (42), a new wstack\n * process is spawned in the target project directory. This replaces the\n * old behavior of spawning mid-session (which left the TUI running and\n * corrupted the terminal state).\n *\n * Returns the exit code when a spawn happened (0), or `null` when the\n * TUI exited normally and the caller should continue its cleanup path.\n */\nimport { spawn } from 'node:child_process';\nimport { createRequire } from 'node:module';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { color } from '@wrongstack/core/utils';\n\nexport const PROJECT_SWITCH_EXIT_CODE = 42;\n\nexport interface PendingProjectSwitch {\n root: string;\n name: string;\n resumeSessionId?: string | undefined;\n}\n\ninterface ProjectSwitchSpawnOptions {\n /** The TUI's exit code. */\n code: number;\n /** The pending switch info set by onProjectSelect / onSwitchToSession. */\n pendingProjectSwitch: PendingProjectSwitch | null;\n}\n\n/**\n * If the TUI exited with PROJECT_SWITCH_EXIT_CODE and a pending switch\n * is set, spawn a new wstack in the target project and return 0.\n * Otherwise return null (no spawn happened \u2014 caller continues cleanup).\n */\nexport async function handleProjectSwitchSpawn(\n opts: ProjectSwitchSpawnOptions,\n): Promise<number | null> {\n const PROJECT_SWITCH_EXIT_CODE = 42;\n if (opts.code !== PROJECT_SWITCH_EXIT_CODE || !opts.pendingProjectSwitch) {\n return null;\n }\n\n const { root, name, resumeSessionId } = opts.pendingProjectSwitch;\n\n // Clear screen before spawning \u2014 removes TUI artifacts so the new wstack\n // banner starts fresh. \\x1b[2J clears visible screen, \\x1b[H homes cursor.\n process.stdout.write('\\x1b[2J\\x1b[H');\n\n let cliPath: string;\n try {\n const req = createRequire(import.meta.url);\n const pkgPath = req.resolve('@wrongstack/cli/package.json');\n const pkgDir = path.dirname(pkgPath);\n cliPath = path.join(pkgDir, 'dist', 'index.js');\n await fs.access(cliPath);\n } catch {\n cliPath = process.argv[1] ?? '';\n if (!cliPath) {\n console.error(color.red('Could not locate the CLI entry point.\\n'));\n return 1;\n }\n }\n\n const nodeExe = process.execPath;\n const spawnArgs = [cliPath, '--no-interactive'];\n if (resumeSessionId) spawnArgs.push('--resume', resumeSessionId);\n // No abort signal here: the spawned wstack OUTLIVES this process\n // (we exit right after). A previous AbortSignal.timeout(30_000)\n // on this spawn killed the successor 30 seconds in whenever the\n // parent lingered.\n // Use stdio: 'ignore' + detached: true so the child truly outlives\n // the parent \u2014 stdio: 'inherit' would pipe the child's stdin to\n // the parent's, and when the parent exits the pipes close, crashing\n // a child that is still initializing (module load, provider connect).\n spawn(nodeExe, spawnArgs, {\n cwd: root,\n stdio: 'ignore',\n detached: true,\n }).on('error', (err: Error) => {\n console.error(color.red(`Failed to spawn wstack: ${err.message}`));\n });\n\n console.log(\n [\n '',\n color.green(` Switched to ${name}`),\n color.dim(` Root: ${root}`),\n color.dim(' (current session stays open \u2014 Ctrl+C to return)'),\n '',\n ].join('\\n'),\n );\n\n return 0;\n}\n", "/**\n * switchProjectInPlace \u2014 extracted from the TUI branch of execute().\n *\n * Phase B step 2. Re-roots the live TUI process to a new project: new\n * paths, session store, writer, rebuilt system prompt, old session\n * close and project.switched event emission.\n *\n * All mutable state mutations go through `state.*` (TuiRuntimeState).\n * The caller syncs locals back after the TUI branch ends.\n */\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport {\n type Agent,\n type Context,\n DefaultSystemPromptBuilder,\n setQueuedMessagesSnapshot,\n} from '@wrongstack/core/agent';\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport { DefaultSessionStore } from '@wrongstack/core/storage';\nimport type { Config, MemoryPort, ModeStore, SkillLoader } from '@wrongstack/core/types';\nimport { resolveWstackPaths, sessionScopedPath } from '@wrongstack/core/utils';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\n\nexport interface ProjectSwitchContext {\n state: TuiRuntimeState;\n context: Context;\n events: EventBus;\n agent: Agent;\n config: Config;\n tokenCounter: import('@wrongstack/core/types').TokenCounter;\n modeId: string | undefined;\n modeStore: ModeStore | undefined;\n memoryStore: MemoryPort | undefined;\n skillLoader: SkillLoader | undefined;\n /** attachTodosCheckpoint \u2014 from execute() scope. */\n attachTodosCheckpoint: (\n state: import('@wrongstack/core/agent').ConversationState,\n todosPath: string,\n sessionId: string,\n events: EventBus,\n traceId: string | undefined,\n ) => () => void;\n}\n\n/**\n * Re-root the live TUI process to a new project directory.\n *\n * Returns `null` on success, or an error message string on failure.\n * Mutates `state.*` (projectRoot, wpaths, activeSessionStore,\n * detachActiveTodosCheckpoint).\n */\nexport async function switchProjectInPlace(\n ctx: ProjectSwitchContext,\n targetRoot: string,\n displayName: string,\n): Promise<string | null> {\n const {\n state,\n context,\n events,\n agent,\n config,\n tokenCounter,\n modeId,\n modeStore,\n memoryStore,\n skillLoader,\n attachTodosCheckpoint,\n } = ctx;\n\n const resolved = path.resolve(targetRoot);\n const stat = await fs.stat(resolved).catch(() => null);\n if (!stat?.isDirectory()) return `Cannot switch: not a directory: ${resolved}`;\n\n const oldWriter = context.session;\n const oldUsage = tokenCounter.total();\n const oldProjectRoot = state.projectRoot;\n const nextWpaths = resolveWstackPaths({\n projectRoot: resolved,\n globalRoot: state.wpaths.globalRoot,\n });\n await fs.mkdir(nextWpaths.projectSessions, { recursive: true });\n const nextSessionStore = new DefaultSessionStore({\n dir: nextWpaths.projectSessions,\n projectRoot: resolved,\n });\n const nextWriter = await nextSessionStore.create({\n id: '',\n title: '',\n model: context.model,\n provider: (context.provider as { id?: string }).id ?? config.provider,\n });\n const previousCwd = process.cwd();\n try {\n process.chdir(resolved);\n process.chdir(previousCwd);\n } catch (err) {\n await nextWriter.close().catch(() => undefined);\n await nextSessionStore.delete(nextWriter.id).catch(() => undefined);\n return `Cannot switch: ${err instanceof Error ? err.message : String(err)}`;\n }\n if (!state.activateSessionIdentity) {\n await nextWriter.close().catch(() => undefined);\n await nextSessionStore.delete(nextWriter.id).catch(() => undefined);\n return 'Cannot switch: session ownership registry is unavailable.';\n }\n try {\n await state.activateSessionIdentity(nextWriter.id, {\n projectSlug: nextWpaths.projectSlug,\n projectRoot: resolved,\n projectName: displayName || path.basename(resolved),\n workingDir: resolved,\n });\n } catch (err) {\n await nextWriter.close().catch(() => undefined);\n await nextSessionStore.delete(nextWriter.id).catch(() => undefined);\n return `Cannot switch: ${err instanceof Error ? err.message : String(err)}`;\n }\n\n await Promise.resolve(state.detachActiveTodosCheckpoint?.()).catch(() => undefined);\n process.chdir(resolved);\n state.projectRoot = resolved;\n state.wpaths = nextWpaths;\n state.activeSessionStore = nextSessionStore;\n\n context.cwd = resolved;\n context.projectRoot = resolved;\n context.workingDir = resolved;\n context.session = nextWriter;\n context.state.replaceMessages([]);\n context.state.replaceTodos([]);\n context.clearFileTracking();\n context.tokenCounter.reset();\n context.meta['packageTrackerOpts'] = { storageDir: nextWpaths.projectDir, projectRoot: resolved };\n context.state.setMeta(\n 'plan.path',\n sessionScopedPath(nextWpaths.projectSessions, nextWriter.id, '.plan.json'),\n );\n context.state.setMeta(\n 'task.path',\n sessionScopedPath(nextWpaths.projectSessions, nextWriter.id, '.tasks.json'),\n );\n try {\n state.detachActiveTodosCheckpoint = attachTodosCheckpoint(\n context.state,\n sessionScopedPath(nextWpaths.projectSessions, nextWriter.id, '.todos.json'),\n nextWriter.id,\n events,\n context.traceId,\n );\n } catch {\n state.detachActiveTodosCheckpoint = undefined;\n }\n setQueuedMessagesSnapshot(context, []);\n\n try {\n const switchMode =\n modeId && modeId !== 'default' && modeStore ? await modeStore.getMode(modeId) : undefined;\n const switchBuilder = new DefaultSystemPromptBuilder({\n memoryStore: memoryStore ?? undefined,\n // Single injection channel: SAGE turn middleware, not a static section.\n injectMemory: false,\n skillLoader,\n modeStore,\n modeId: modeId ?? 'default',\n modePrompt: switchMode?.prompt ?? '',\n instructionPaths: {\n globalDir: nextWpaths.globalInstructions,\n projectDir: nextWpaths.inProjectInstructions,\n systemVariant: config.systemPrompt?.variant,\n },\n });\n context.systemPrompt = await switchBuilder.build({\n cwd: resolved,\n projectRoot: resolved,\n tools: agent.tools.list(),\n provider: (context.provider as { id?: string }).id,\n model: context.model,\n });\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'warn',\n event: 'execution.project_switch_prompt_rebuild_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n\n try {\n await oldWriter.append({ type: 'session_end', ts: new Date().toISOString(), usage: oldUsage });\n await oldWriter.close();\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'warn',\n event: 'execution.project_switch_old_session_close_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n const emitUntyped = events.emit as never as (event: string, payload: unknown) => void;\n emitUntyped('project.switched', { from: oldProjectRoot, to: resolved, name: displayName });\n return null;\n}\n", "/**\n * TUI SDD callbacks \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 5. getSDDContext returns the active spec-driven-development\n * context; onSDDOutput parses assistant output for spec/plan/task artifacts,\n * auto-saves them, and returns status messages for the TUI to display.\n *\n * No closure dependencies \u2014 both functions delegate to the shared SDD\n * runtime service.\n */\n\n/**\n * Get the active SDD context for the current session.\n */\nexport async function getSDDContext(): Promise<unknown> {\n const { getActiveSDDContext } = await import('../services/sdd-runtime.js');\n return getActiveSDDContext();\n}\n\n/**\n * Parse assistant output for SDD artifacts (spec, plan, tasks), auto-save\n * them, and return status messages for the TUI.\n */\nexport async function onSDDOutput(output: string): Promise<string[]> {\n const {\n trySaveSpecFromAIOutput,\n trySaveImplementationPlan,\n trySaveTasksFromAIOutput,\n autoDetectTaskCompletion,\n getTaskProgress,\n getActiveSDDPhase,\n } = await import('../services/sdd-runtime.js');\n const messages: string[] = [];\n const specSaved = await trySaveSpecFromAIOutput(output);\n if (specSaved)\n messages.push('\u2713 Spec detected and saved! Use /sdd approve to continue.');\n const planSaved = trySaveImplementationPlan(output);\n if (planSaved) messages.push('\u2713 Implementation plan saved!');\n const tasksSaved = await trySaveTasksFromAIOutput(output);\n if (tasksSaved) {\n const progress = getTaskProgress();\n const count = progress?.total ?? 0;\n messages.push(`\u2713 ${count} tasks detected and saved! Use /sdd approve to execute.`);\n }\n const sddPhase = getActiveSDDPhase();\n if (sddPhase === 'executing') {\n const autoCompleted = autoDetectTaskCompletion(output);\n if (autoCompleted > 0) {\n const progress = getTaskProgress();\n if (progress) {\n messages.push(\n `\u2713 ${autoCompleted} task(s) auto-completed! Progress: ${progress.completed}/${progress.total} (${progress.percentComplete}%)`,\n );\n }\n }\n }\n return messages;\n}\n", "/**\n * TUI session resume \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 2. The onResumeSession callback swaps the agent's session\n * writer, resets token accounting, and replays the JSONL events as TUI\n * history entries.\n *\n * Reads mutable state from TuiRuntimeState (activeSessionStore, wpaths).\n */\nimport * as path from 'node:path';\nimport type { Agent } from '@wrongstack/core/agent';\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport { attachTodosCheckpoint, loadTodosCheckpoint } from '@wrongstack/core/storage';\nimport type { SessionWriter, TokenCounter } from '@wrongstack/core/types';\nimport { sessionScopedPath } from '@wrongstack/core/utils';\nimport type { TuiRuntimeState } from './tui-runtime-state.js';\n\nexport interface SessionResumeContext {\n state: TuiRuntimeState;\n agent: Agent;\n tokenCounter: TokenCounter;\n switchProviderAndModel:\n | ((providerId: string, modelId: string) => string | null | void | Promise<unknown>)\n | undefined;\n /** App EventBus \u2014 forwarded to the re-pointed todos checkpoint for storage.* events. */\n events?: EventBus | undefined;\n}\n\nexport interface SessionResumeResult {\n entries: unknown[];\n nextId: number;\n sessionId: string;\n}\n\n/**\n * Resume a past session by id.\n *\n * Returns the replayed history entries + new session id, or null on\n * failure. Throws if the session is live in another process.\n */\nexport async function resumeSession(\n ctx: SessionResumeContext,\n sessionId: string,\n): Promise<SessionResumeResult | null> {\n const { state, agent, tokenCounter, switchProviderAndModel, events } = ctx;\n\n if (!state.activeSessionStore) return null;\n // Import before claiming/opening the target so a packaging failure leaves\n // the current writer and registry identity untouched.\n const { replaySessionMessages } = await import('@wrongstack/tui');\n\n // Refuse to resume a session that a LIVE process owns \u2014 two\n // writers on one session JSONL corrupt it. Thrown (not null) so\n // the resume picker surfaces the reason instead of a generic\n // failure. Best-effort: a broken registry must not block resume.\n let canonicalSessionId = sessionId;\n try {\n if (state.activeSessionStore.resolveId) {\n canonicalSessionId = await state.activeSessionStore.resolveId(sessionId);\n }\n } catch (err) {\n // Fail closed: without a canonical id the live-session registry cannot\n // prove that another process is not already writing the same journal.\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.resume_id_resolve_failed',\n sessionId,\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n return null;\n }\n try {\n const { SessionRegistry } = await import('@wrongstack/core/storage');\n const registry = new SessionRegistry(path.dirname(state.wpaths.globalConfig));\n const live = (await registry.list()).find(\n (s) => s.sessionId === canonicalSessionId && s.status !== 'stale' && s.pid !== process.pid,\n );\n if (live) {\n throw new Error(\n `Session is open in another running wstack (pid ${live.pid}) \u2014 it cannot be resumed here while live.`,\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('Session is open')) throw err;\n // registry unreadable \u2014 fall through to the normal resume path\n }\n\n const previousSessionId = agent.ctx.session?.id;\n let identityClaimed = false;\n let writerSwapped = false;\n let openedWriter: SessionWriter | undefined;\n try {\n if (state.activateSessionIdentity) {\n await state.activateSessionIdentity(canonicalSessionId);\n identityClaimed = true;\n }\n const resumed = await state.activeSessionStore.resume(canonicalSessionId);\n openedWriter = resumed.writer;\n const meta = resumed.data.metadata;\n const entries = replaySessionMessages(\n resumed.data.messages,\n resumed.data.events,\n /* startId */ 1,\n );\n const sessionsDir = state.wpaths.projectSessions;\n const resumedTodosPath = sessionScopedPath(sessionsDir, resumed.writer.id, '.todos.json');\n const restoredTodos = await loadTodosCheckpoint(\n resumedTodosPath,\n events,\n agent.ctx.traceId,\n resumed.writer.id,\n ).catch(() => null);\n\n // Capture and swap writers BEFORE hydrating. replaceMessages emits the\n // exact recovery snapshot through Context's conversation journal; it must\n // land in the resumed session, never the session we are leaving.\n const oldWriter = agent.ctx.session;\n const oldMessages = [...agent.ctx.messages];\n agent.ctx.session = resumed.writer;\n try {\n // Rebuild the agent's conversation context from the resumed messages.\n // Go through the observable state wrapper so subscribers fire and\n // tool-use adjacency is re-checked on the next request.\n agent.ctx.state.replaceMessages(resumed.data.messages);\n } catch (err) {\n agent.ctx.session = oldWriter;\n agent.ctx.state.replaceMessages(oldMessages);\n throw err;\n }\n writerSwapped = true;\n await agent.ctx.flushConversationJournal().catch((err) => {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.resume_journal_flush_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n });\n\n // \u2500\u2500 Re-point session-scoped sidecars (todos/plan/task) to the resumed\n // session and restore its todo board. Without this the picker resume keeps\n // writing todo edits to the PREVIOUS session's .todos.json and shows an\n // empty board \u2014 the boot `--resume` path already restores todos, so this\n // closes that asymmetry. Detach the old checkpoint BEFORE mutating todos so\n // the restore can't leak into the session we are leaving.\n await Promise.resolve(state.detachActiveTodosCheckpoint?.()).catch(() => undefined);\n agent.ctx.state.setMeta(\n 'plan.path',\n sessionScopedPath(sessionsDir, resumed.writer.id, '.plan.json'),\n );\n agent.ctx.state.setMeta(\n 'task.path',\n sessionScopedPath(sessionsDir, resumed.writer.id, '.tasks.json'),\n );\n agent.ctx.state.replaceTodos(restoredTodos ?? []);\n // Re-attach so subsequent todo edits persist to the RESUMED session file.\n try {\n state.detachActiveTodosCheckpoint = attachTodosCheckpoint(\n agent.ctx.state,\n resumedTodosPath,\n resumed.writer.id,\n events,\n agent.ctx.traceId,\n );\n } catch {\n state.detachActiveTodosCheckpoint = undefined;\n }\n\n // Sync the agent's provider/model to what was used in the resumed session.\n // Route all changes through the live switch callback when available so the\n // provider instance, ConfigStore, auto-compactor denominator, and context\n // chip are refreshed together.\n const currentProviderId = (agent.ctx.provider as { id?: string }).id;\n const targetProviderId =\n typeof meta.provider === 'string' && meta.provider.length > 0\n ? meta.provider\n : currentProviderId;\n const targetModel =\n typeof meta.model === 'string' && meta.model.length > 0 ? meta.model : agent.ctx.model;\n if (\n switchProviderAndModel &&\n targetProviderId &&\n (targetProviderId !== currentProviderId || targetModel !== agent.ctx.model)\n ) {\n await Promise.resolve(switchProviderAndModel(targetProviderId, targetModel)).catch(\n (err: unknown) => {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.resume_model_restore_failed',\n provider: targetProviderId,\n model: targetModel,\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n },\n );\n } else if (targetModel !== agent.ctx.model) {\n agent.ctx.model = targetModel;\n }\n\n // Finalize the current session: append a session_end (so the\n // log ends cleanly and recovery/summaries see a completed\n // session), then close (flush + summary sidecar + index). Use\n // agent.ctx.session (the currently active writer) rather than\n // the captured `session` variable \u2014 the user may have resumed\n // before, in which case `session` is stale.\n // Fire-and-forget: don't block resume on the close.\n if (oldWriter && oldWriter !== resumed.writer) {\n // Capture the OLD session's usage synchronously \u2014 the counter\n // is reset for the resumed session below, and this closure\n // runs after that reset.\n const endedUsage = tokenCounter.total();\n void (async () => {\n let appendOk = false;\n try {\n await oldWriter.append({\n type: 'session_end',\n ts: new Date().toISOString(),\n usage: endedUsage,\n });\n appendOk = true;\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.session_end_append_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n // Only close if session_end was successfully appended \u2014 closing\n // a partially-written session file corrupts recovery/summaries.\n if (appendOk) {\n try {\n await oldWriter.close();\n } catch (err) {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.session_close_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n }\n })();\n }\n\n // Token accounting is per-session: without a reset the resumed\n // session's summary/cost chips inherit the old session's totals.\n tokenCounter.reset();\n tokenCounter.account(resumed.data.usage, targetModel, targetProviderId);\n\n return {\n entries,\n nextId: entries.length + 1,\n sessionId: resumed.writer.id,\n };\n } catch (err) {\n if (identityClaimed && !writerSwapped && previousSessionId) {\n await state.activateSessionIdentity?.(previousSessionId).catch((rollbackErr) => {\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.resume_identity_rollback_failed',\n sessionId: previousSessionId,\n message: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),\n timestamp: new Date().toISOString(),\n }),\n );\n });\n }\n if (!writerSwapped) {\n await openedWriter?.close().catch(() => undefined);\n }\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'execution.resume_session_failed',\n message: err instanceof Error ? err.message : String(err),\n timestamp: new Date().toISOString(),\n }),\n );\n return null;\n }\n}\n", "/**\n * TUI Settings adapter \u2014 extracted from the runTui() options literal.\n *\n * Phase C step 1. The getSettings/saveSettings pair (~337 lines) reads\n * config from the ConfigStore and persists changes to disk. This module\n * owns both functions, receiving its dependencies through a typed context.\n *\n * `getSettings()` maps the full Config into the flat LiveSettingsInput\n * shape the TUI SettingsPicker consumes. `saveSettings()` does the\n * reverse: read \u2192 modify \u2192 encrypt \u2192 atomic-write for every section,\n * then syncs the in-memory store and applies live runtime effects.\n */\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { decryptConfigSecrets, encryptConfigSecrets, noOpVault } from '@wrongstack/core/security';\nimport type { Config, ConfigStore, FleetChatVerbosity } from '@wrongstack/core/types';\nimport { normalizeTokenSavingTier, resolveFleetChatVerbosity } from '@wrongstack/core/types';\nimport { atomicWrite, type WstackPaths } from '@wrongstack/core/utils';\nimport { getProcessRegistry } from '@wrongstack/tools';\nimport type { LiveSettingsInput } from '../live-settings-input.js';\nimport {\n deriveFsAccessPair,\n filterSafeForProject,\n resolveActualTarget,\n resolvePersistPath,\n} from '../settings-menu.js';\nimport { normalizeTuiThinkingWord } from '../tui-thinking-word.js';\n\nexport interface SettingsAdapterContext {\n configStore: ConfigStore;\n wpaths: WstackPaths;\n fleetStreamController: { setMode?: ((mode: FleetChatVerbosity) => void) | undefined } | undefined;\n applyLiveSettings: ((s: LiveSettingsInput) => void) | undefined;\n}\n\nexport interface SettingsAdapter {\n getSettings: () => Record<string, unknown>;\n saveSettings: (s: LiveSettingsInput) => Promise<string | null>;\n}\n\nconst ANIMATION_STYLES = ['rainbow', 'wave', 'pulse', 'dots', 'breathe', 'cycle'] as const;\ntype AnimationStyleValue = (typeof ANIMATION_STYLES)[number];\n\n/** Widen an untyped config value to the animation-style union; default 'rainbow'. */\nfunction normalizeAnimationStyle(raw: unknown): AnimationStyleValue {\n return typeof raw === 'string' && (ANIMATION_STYLES as readonly string[]).includes(raw)\n ? (raw as AnimationStyleValue)\n : 'rainbow';\n}\n\n/**\n * Build the getSettings/saveSettings pair for the TUI SettingsPicker.\n *\n * `getSettings` reads from the live ConfigStore on every call.\n * `saveSettings` persists to disk (global or project-local config),\n * syncs the in-memory store, and applies runtime effects immediately.\n */\nexport function createSettingsAdapter(ctx: SettingsAdapterContext): SettingsAdapter {\n const { configStore, wpaths, fleetStreamController, applyLiveSettings } = ctx;\n\n // Filesystem-access pair derivation is shared with the slash command\n // and the cli-main live-apply path. See settings-menu.ts for the\n // single source of truth and the precedence rules.\n const deriveFsAccess = deriveFsAccessPair;\n\n function getSettings(): Record<string, unknown> {\n const cfg = configStore.get();\n const autonomy = cfg.autonomy as Record<string, unknown> | undefined;\n const rawMode = autonomy?.defaultMode as string | undefined;\n const mode: 'off' | 'suggest' | 'auto' =\n rawMode === 'suggest' || rawMode === 'auto' ? rawMode : 'off';\n const modelRuntime = (\n cfg as {\n modelRuntime?: {\n reasoning?: { mode?: string; effort?: string; preserve?: boolean };\n cache?: { ttl?: string };\n };\n }\n ).modelRuntime;\n const contextModeRaw = cfg.context?.mode;\n const contextMode =\n contextModeRaw === 'frugal' || contextModeRaw === 'deep' ? contextModeRaw : 'balanced';\n const reasoningEffortRaw = modelRuntime?.reasoning?.effort;\n const reasoningEffort =\n reasoningEffortRaw === 'none' ||\n reasoningEffortRaw === 'minimal' ||\n reasoningEffortRaw === 'low' ||\n reasoningEffortRaw === 'medium' ||\n reasoningEffortRaw === 'high' ||\n reasoningEffortRaw === 'xhigh' ||\n reasoningEffortRaw === 'max'\n ? reasoningEffortRaw\n : 'high';\n // Resolve the filesystem-access pair from whichever side of the\n // duplicated config (features.allowOutsideProjectRoot vs\n // tools.restrictToProjectRoot) the user actually wrote. They MUST\n // round-trip as inverses of each other \u2014 otherwise the picker would\n // show contradictory values, and saving would silently flip the\n // user's intent. Source of truth order matches `deriveFsAccessPair`\n // in settings-menu.ts: features.allowOutsideProjectRoot wins if set.\n const featuresAllow = cfg.features?.allowOutsideProjectRoot;\n const toolsRestrict = cfg.tools?.restrictToProjectRoot;\n const resolvedAllow =\n featuresAllow !== undefined\n ? featuresAllow\n : toolsRestrict !== undefined\n ? !toolsRestrict\n : true;\n const resolvedRestrict = !resolvedAllow;\n return {\n mode,\n delayMs: (autonomy?.autoProceedDelayMs as number) ?? 45_000,\n titleAnimation: autonomy?.terminalTitleAnimation !== false,\n yolo: cfg.yolo ?? (autonomy?.yolo as boolean | undefined) ?? false,\n fleetChatVerbosity: resolveFleetChatVerbosity(cfg.autonomy),\n chime: (autonomy?.chime as boolean) ?? false,\n confirmExit: autonomy?.confirmExit !== false,\n nextPrediction: cfg.nextPrediction ?? false,\n featureMcp: cfg.features?.mcp !== false,\n featurePlugins: cfg.features?.plugins !== false,\n featureMemory: cfg.features?.memory !== false,\n featureSkills: cfg.features?.skills !== false,\n featureModelsRegistry: cfg.features?.modelsRegistry !== false,\n // Preserve the 'auto' sentinel for the picker DISPLAY (normalize would\n // collapse it to 'off', which would then overwrite 'auto' on save);\n // everything else normalizes to a concrete tier.\n featureTokenSaving:\n cfg.features?.tokenSavingMode === 'auto'\n ? 'auto'\n : normalizeTokenSavingTier(cfg.features?.tokenSavingMode),\n allowOutsideProjectRoot: resolvedAllow,\n contextAutoCompact: cfg.context?.autoCompact !== false,\n contextStrategy: cfg.context?.strategy ?? 'hybrid',\n contextMode,\n maxConcurrent: cfg.maxConcurrent ?? 4,\n logLevel: cfg.log?.level ?? 'info',\n auditLevel: cfg.session?.auditLevel ?? 'standard',\n indexOnStart: cfg.indexing?.onSessionStart !== false,\n maxIterations: cfg.tools?.maxIterations ?? 500,\n restrictFsToRoot: resolvedRestrict,\n autoProceedMaxIterations:\n ((cfg.autonomy as Record<string, unknown> | undefined)\n ?.autoProceedMaxIterations as number) ?? 50,\n debugStream: cfg.debugStream ?? false,\n shellBangWarningDontShowAgain: autonomy?.shellBangWarningDontShowAgain === true,\n statuslineMode:\n autonomy?.statuslineMode === 'no-color'\n ? 'no-color'\n : autonomy?.statuslineMode === 'minimum'\n ? 'minimum'\n : 'detailed',\n thinkingWord: normalizeTuiThinkingWord(autonomy?.thinkingWord),\n animationStyle: normalizeAnimationStyle(autonomy?.animationStyle),\n configScope: cfg.configScope ?? 'global',\n enhanceDelayMs:\n ((cfg.autonomy as Record<string, unknown> | undefined)?.enhanceDelayMs as number) ?? 60_000,\n enhanceEnabled:\n ((cfg.autonomy as Record<string, unknown> | undefined)?.enhance as boolean) ?? true,\n enhanceLanguage:\n (cfg.autonomy as Record<string, unknown> | undefined)?.enhanceLanguage === 'english'\n ? ('english' as const)\n : ('original' as const),\n midRunSendPicker:\n ((cfg.autonomy as Record<string, unknown> | undefined)?.midRunSendPicker as boolean) ??\n true,\n mouseMode: (autonomy?.mouseMode as boolean) ?? false,\n autonomyNextPrompt:\n ((cfg.autonomy as Record<string, unknown> | undefined)?.autonomyNextPrompt as\n | string\n | undefined) ?? 'auto {{suggestion}}',\n reasoningMode:\n modelRuntime?.reasoning?.mode === 'on' || modelRuntime?.reasoning?.mode === 'off'\n ? modelRuntime.reasoning.mode\n : 'auto',\n reasoningEffort,\n reasoningPreserve: modelRuntime?.reasoning?.preserve === true,\n cacheTtl:\n modelRuntime?.cache?.ttl === '5m' || modelRuntime?.cache?.ttl === '1h'\n ? modelRuntime.cache.ttl\n : 'default',\n breakerEnabled: cfg.circuitBreaker?.enabled === true,\n breakerAutoKillResetMs: cfg.circuitBreaker?.autoKillResetMs ?? 60_000,\n showModelReasoning: autonomy?.showModelReasoning ?? true,\n showAgentSwarmPanel: autonomy?.showAgentSwarmPanel ?? true,\n showSageMemoryInject: autonomy?.showSageMemoryInject ?? false,\n readSymbols: autonomy?.readAdvancedMode ?? false,\n sageMemoryInjectThreshold: (cfg.Sage as Record<string, unknown> | undefined)?.inject\n ? ((cfg.Sage as Record<string, unknown>).inject as Record<string, unknown>)?.relationFloor\n : undefined,\n };\n }\n\n async function saveSettings(s: LiveSettingsInput): Promise<string | null> {\n try {\n // Persist the full TUI settings snapshot to one target file. This keeps\n // global/project scope switches coherent: autonomy, UX, refine, and the\n // other settings all land in the newly selected scope together.\n if (\n s.mode !== undefined ||\n s.delayMs !== undefined ||\n s.titleAnimation !== undefined ||\n s.yolo !== undefined ||\n s.fleetChatVerbosity !== undefined ||\n s.chime !== undefined ||\n s.confirmExit !== undefined ||\n s.mouseMode !== undefined ||\n s.featureMcp !== undefined ||\n s.featurePlugins !== undefined ||\n s.featureMemory !== undefined ||\n s.featureSkills !== undefined ||\n s.featureModelsRegistry !== undefined ||\n s.featureTokenSaving !== undefined ||\n s.allowOutsideProjectRoot !== undefined ||\n s.contextAutoCompact !== undefined ||\n s.contextStrategy !== undefined ||\n s.contextMode !== undefined ||\n s.maxConcurrent !== undefined ||\n s.logLevel !== undefined ||\n s.auditLevel !== undefined ||\n s.indexOnStart !== undefined ||\n s.maxIterations !== undefined ||\n s.restrictFsToRoot !== undefined ||\n s.nextPrediction !== undefined ||\n s.debugStream !== undefined ||\n s.shellBangWarningDontShowAgain !== undefined ||\n s.configScope !== undefined ||\n s.enhanceDelayMs !== undefined ||\n s.enhanceEnabled !== undefined ||\n s.enhanceLanguage !== undefined ||\n s.midRunSendPicker !== undefined ||\n s.statuslineMode !== undefined ||\n s.thinkingWord !== undefined ||\n s.animationStyle !== undefined ||\n s.autonomyNextPrompt !== undefined ||\n s.autoProceedMaxIterations !== undefined ||\n s.reasoningMode !== undefined ||\n s.reasoningEffort !== undefined ||\n s.reasoningPreserve !== undefined ||\n s.cacheTtl !== undefined ||\n s.breakerEnabled !== undefined ||\n s.breakerAutoKillResetMs !== undefined ||\n s.showModelReasoning !== undefined ||\n s.showAgentSwarmPanel !== undefined ||\n s.showSageMemoryInject !== undefined ||\n s.sageMemoryInjectThreshold !== undefined ||\n s.readSymbols !== undefined\n ) {\n const cfg = configStore.get();\n // Delegate path resolution to the canonical resolver. This keeps\n // the three-way routing (project \u2192 profile \u2192 bootstrap) consistent\n // with the settings-menu.ts slash commands and the run-tui live-apply\n // path; a future fourth target (e.g. org config) only needs one update.\n const activeProfileName = (cfg as { activeProfile?: string }).activeProfile ?? 'default';\n const persistDeps = {\n configStore,\n profileConfigPath: wpaths.profileConfig(activeProfileName),\n inProjectConfigPath: wpaths.inProjectConfig,\n vault: noOpVault,\n resolveProfilePath: (name: string) => wpaths.profileConfig(name),\n };\n const targetPath = resolvePersistPath(persistDeps);\n let raw: string;\n try {\n raw = await fs.readFile(targetPath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw new Error(\n `Failed to read config at ${targetPath}: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n raw = '{}';\n }\n const parsed = JSON.parse(raw) as Record<string, unknown>;\n const decrypted = decryptConfigSecrets(parsed, noOpVault) as Record<string, unknown>;\n\n const autonomy = (decrypted.autonomy as Record<string, unknown>) ?? {};\n if (s.mode !== undefined) autonomy.defaultMode = s.mode;\n if (s.delayMs !== undefined) autonomy.autoProceedDelayMs = s.delayMs;\n if (s.titleAnimation !== undefined) autonomy.terminalTitleAnimation = s.titleAnimation;\n if (s.yolo !== undefined) autonomy.yolo = s.yolo;\n if (s.fleetChatVerbosity !== undefined) {\n autonomy.fleetChatVerbosity = s.fleetChatVerbosity;\n }\n if (s.chime !== undefined) autonomy.chime = s.chime;\n if (s.confirmExit !== undefined) autonomy.confirmExit = s.confirmExit;\n if (s.mouseMode !== undefined) autonomy.mouseMode = s.mouseMode;\n if (s.enhanceDelayMs !== undefined) autonomy.enhanceDelayMs = s.enhanceDelayMs;\n if (s.enhanceEnabled !== undefined) autonomy.enhance = s.enhanceEnabled;\n if (s.enhanceLanguage !== undefined) autonomy.enhanceLanguage = s.enhanceLanguage;\n if (s.midRunSendPicker !== undefined) autonomy.midRunSendPicker = s.midRunSendPicker;\n if (s.shellBangWarningDontShowAgain !== undefined)\n autonomy.shellBangWarningDontShowAgain = s.shellBangWarningDontShowAgain;\n if (s.statuslineMode !== undefined) autonomy.statuslineMode = s.statuslineMode;\n if (s.thinkingWord !== undefined)\n autonomy.thinkingWord = normalizeTuiThinkingWord(s.thinkingWord);\n if (s.animationStyle !== undefined) autonomy.animationStyle = s.animationStyle;\n if (s.showModelReasoning !== undefined) autonomy.showModelReasoning = s.showModelReasoning;\n if (s.showAgentSwarmPanel !== undefined)\n autonomy.showAgentSwarmPanel = s.showAgentSwarmPanel;\n if (s.showSageMemoryInject !== undefined)\n autonomy.showSageMemoryInject = s.showSageMemoryInject;\n if (s.readSymbols !== undefined)\n autonomy.readAdvancedMode = s.readSymbols;\n if (s.autonomyNextPrompt !== undefined) autonomy.autonomyNextPrompt = s.autonomyNextPrompt;\n if (s.autoProceedMaxIterations !== undefined)\n autonomy.autoProceedMaxIterations = s.autoProceedMaxIterations;\n decrypted.autonomy = autonomy;\n\n if (s.nextPrediction !== undefined) decrypted.nextPrediction = s.nextPrediction;\n if (s.yolo !== undefined) decrypted.yolo = s.yolo;\n // Derive the filesystem-access pair ONCE here, so both the\n // `features.allowOutsideProjectRoot` and `tools.restrictToProjectRoot`\n // writes below stay consistent. The previous implementation had three\n // separate write sites that could disagree when both picker knobs\n // were set in the same save.\n const fsAccess = deriveFsAccess(s);\n if (\n s.featureMcp !== undefined ||\n s.featurePlugins !== undefined ||\n s.featureMemory !== undefined ||\n s.featureSkills !== undefined ||\n s.featureModelsRegistry !== undefined ||\n s.featureTokenSaving !== undefined ||\n fsAccess !== undefined\n ) {\n const feats = (decrypted.features as Record<string, unknown>) ?? {};\n if (s.featureMcp !== undefined) feats.mcp = s.featureMcp;\n if (s.featurePlugins !== undefined) feats.plugins = s.featurePlugins;\n if (s.featureMemory !== undefined) feats.memory = s.featureMemory;\n if (s.featureSkills !== undefined) feats.skills = s.featureSkills;\n if (s.featureModelsRegistry !== undefined) feats.modelsRegistry = s.featureModelsRegistry;\n if (s.featureTokenSaving !== undefined) feats.tokenSavingMode = s.featureTokenSaving;\n if (fsAccess !== undefined)\n feats.allowOutsideProjectRoot = fsAccess.allowOutsideProjectRoot;\n decrypted.features = feats;\n }\n if (\n s.contextAutoCompact !== undefined ||\n s.contextStrategy !== undefined ||\n s.contextMode !== undefined\n ) {\n const c = (decrypted.context as Record<string, unknown>) ?? {};\n if (s.contextAutoCompact !== undefined) c.autoCompact = s.contextAutoCompact;\n if (s.contextStrategy !== undefined) c.strategy = s.contextStrategy;\n if (s.contextMode !== undefined) c.mode = s.contextMode;\n decrypted.context = c;\n }\n if (s.maxConcurrent !== undefined) decrypted.maxConcurrent = s.maxConcurrent;\n if (s.logLevel !== undefined) {\n const log = (decrypted.log as Record<string, unknown>) ?? {};\n log.level = s.logLevel;\n decrypted.log = log;\n }\n if (s.auditLevel !== undefined) {\n const sess = (decrypted.session as Record<string, unknown>) ?? {};\n sess.auditLevel = s.auditLevel;\n decrypted.session = sess;\n }\n if (s.indexOnStart !== undefined) {\n const idx = (decrypted.indexing as Record<string, unknown>) ?? {};\n idx.onSessionStart = s.indexOnStart;\n decrypted.indexing = idx;\n }\n if (s.maxIterations !== undefined || fsAccess !== undefined) {\n const tools = (decrypted.tools as Record<string, unknown>) ?? {};\n if (s.maxIterations !== undefined) tools.maxIterations = s.maxIterations;\n // Single source of truth for the inverse: deriveFsAccess above.\n if (fsAccess !== undefined) tools.restrictToProjectRoot = fsAccess.restrictToProjectRoot;\n decrypted.tools = tools;\n }\n if (s.debugStream !== undefined) {\n decrypted.debugStream = s.debugStream;\n const { setDebugStreamEnabled } = await import('@wrongstack/providers');\n setDebugStreamEnabled(s.debugStream);\n }\n if (s.configScope !== undefined) decrypted.configScope = s.configScope;\n if (\n s.reasoningMode !== undefined ||\n s.reasoningEffort !== undefined ||\n s.reasoningPreserve !== undefined ||\n s.cacheTtl !== undefined\n ) {\n const modelRuntime = (decrypted.modelRuntime as Record<string, unknown>) ?? {};\n if (\n s.reasoningMode !== undefined ||\n s.reasoningEffort !== undefined ||\n s.reasoningPreserve !== undefined\n ) {\n const reasoning = (modelRuntime.reasoning as Record<string, unknown>) ?? {};\n if (s.reasoningMode !== undefined) reasoning.mode = s.reasoningMode;\n if (s.reasoningEffort !== undefined) reasoning.effort = s.reasoningEffort;\n if (s.reasoningPreserve !== undefined) reasoning.preserve = s.reasoningPreserve;\n modelRuntime.reasoning = reasoning;\n }\n if (s.cacheTtl !== undefined) {\n const cache = (modelRuntime.cache as Record<string, unknown>) ?? {};\n if (s.cacheTtl === 'default') {\n delete cache.ttl;\n } else {\n cache.ttl = s.cacheTtl;\n }\n if (Object.keys(cache).length > 0) modelRuntime.cache = cache;\n else delete modelRuntime.cache;\n }\n decrypted.modelRuntime = modelRuntime;\n }\n if (s.sageMemoryInjectThreshold !== undefined) {\n const sageSec = (decrypted.Sage as Record<string, unknown>) ?? {};\n const inject = (sageSec.inject as Record<string, unknown>) ?? {};\n inject.relationFloor = s.sageMemoryInjectThreshold;\n sageSec.inject = inject;\n decrypted.Sage = sageSec;\n }\n if (s.breakerEnabled !== undefined || s.breakerAutoKillResetMs !== undefined) {\n const cb = (decrypted.circuitBreaker as Record<string, unknown>) ?? {};\n if (s.breakerEnabled !== undefined) cb.enabled = s.breakerEnabled;\n if (s.breakerAutoKillResetMs !== undefined) cb.autoKillResetMs = s.breakerAutoKillResetMs;\n decrypted.circuitBreaker = cb;\n }\n // Re-resolve the target path after the mutation block: the mutator\n // may have changed configScope (or another field the canonical\n // resolveActualTarget checks), so the pre-mutation snapshot is stale.\n const actualTarget = resolveActualTarget(\n persistDeps,\n decrypted as Record<string, unknown>,\n targetPath,\n );\n // Only filter for project safety when writing to the in-project\n // config (.wrongstack/config.json). The active profile config stores\n // the full trusted user settings; the root bootstrap is never targeted.\n const isProjectTarget = actualTarget === wpaths.inProjectConfig;\n const toWrite = isProjectTarget ? filterSafeForProject(decrypted) : decrypted;\n const encrypted = encryptConfigSecrets(toWrite, noOpVault);\n await fs.mkdir(path.dirname(actualTarget), { recursive: true });\n await atomicWrite(actualTarget, JSON.stringify(encrypted, null, 2), { mode: 0o600 });\n\n const currentConfig = configStore.get();\n const nextModelRuntime = {\n ...currentConfig.modelRuntime,\n ...((decrypted.modelRuntime as Record<string, unknown> | undefined) ?? {}),\n } as Record<string, unknown>;\n if (s.cacheTtl === 'default') {\n delete nextModelRuntime.cache;\n }\n\n configStore.update({\n ...(s.nextPrediction !== undefined ? { nextPrediction: s.nextPrediction } : {}),\n ...(s.yolo !== undefined ? { yolo: s.yolo } : {}),\n ...(s.featureMcp !== undefined ||\n s.featurePlugins !== undefined ||\n s.featureMemory !== undefined ||\n s.featureSkills !== undefined ||\n s.featureModelsRegistry !== undefined ||\n s.featureTokenSaving !== undefined ||\n fsAccess !== undefined\n ? {\n features: {\n ...currentConfig.features,\n ...((decrypted.features as Record<string, unknown> | undefined) ?? {}),\n } as Config['features'],\n }\n : {}),\n ...(s.contextAutoCompact !== undefined ||\n s.contextStrategy !== undefined ||\n s.contextMode !== undefined\n ? {\n context: {\n ...currentConfig.context,\n ...((decrypted.context as Record<string, unknown> | undefined) ?? {}),\n } as Config['context'],\n }\n : {}),\n ...(s.maxConcurrent !== undefined ? { maxConcurrent: s.maxConcurrent } : {}),\n ...(s.logLevel !== undefined\n ? {\n log: {\n ...currentConfig.log,\n ...((decrypted.log as Record<string, unknown> | undefined) ?? {}),\n } as Config['log'],\n }\n : {}),\n ...(s.auditLevel !== undefined\n ? {\n session: {\n ...currentConfig.session,\n ...((decrypted.session as Record<string, unknown> | undefined) ?? {}),\n } as Config['session'],\n }\n : {}),\n ...(s.indexOnStart !== undefined\n ? {\n indexing: {\n ...currentConfig.indexing,\n ...((decrypted.indexing as Record<string, unknown> | undefined) ?? {}),\n } as Config['indexing'],\n }\n : {}),\n ...(s.maxIterations !== undefined || fsAccess !== undefined\n ? {\n tools: {\n ...currentConfig.tools,\n ...((decrypted.tools as Record<string, unknown> | undefined) ?? {}),\n } as Config['tools'],\n }\n : {}),\n ...(s.debugStream !== undefined ? { debugStream: s.debugStream } : {}),\n ...(s.configScope !== undefined\n ? { configScope: s.configScope as 'global' | 'project' }\n : {}),\n autonomy: {\n ...currentConfig.autonomy,\n ...((decrypted.autonomy as Record<string, unknown> | undefined) ?? {}),\n } as Config['autonomy'],\n ...(s.reasoningMode !== undefined ||\n s.reasoningEffort !== undefined ||\n s.reasoningPreserve !== undefined ||\n s.cacheTtl !== undefined\n ? {\n modelRuntime: nextModelRuntime as Config['modelRuntime'],\n }\n : {}),\n ...(s.breakerEnabled !== undefined || s.breakerAutoKillResetMs !== undefined\n ? {\n circuitBreaker: {\n ...currentConfig.circuitBreaker,\n ...((decrypted.circuitBreaker as Record<string, unknown> | undefined) ?? {}),\n } as Config['circuitBreaker'],\n }\n : {}),\n ...(s.sageMemoryInjectThreshold !== undefined\n ? {\n Sage: {\n ...currentConfig.Sage,\n ...((decrypted.Sage as Record<string, unknown> | undefined) ?? {}),\n inject: {\n ...(currentConfig.Sage?.inject as Record<string, unknown> | undefined) ?? {},\n ...(((decrypted.Sage as Record<string, unknown> | undefined)\n ?.inject as Record<string, unknown> | undefined) ?? {}),\n } as Record<string, unknown>,\n } as Config['Sage'],\n }\n : {}),\n });\n }\n\n if (s.breakerEnabled !== undefined || s.breakerAutoKillResetMs !== undefined) {\n getProcessRegistry().setBreakerConfig({\n ...(s.breakerEnabled !== undefined ? { enabled: s.breakerEnabled } : {}),\n ...(s.breakerAutoKillResetMs !== undefined\n ? { autoKillResetMs: s.breakerAutoKillResetMs }\n : {}),\n });\n }\n if (s.fleetChatVerbosity !== undefined) {\n if (fleetStreamController?.setMode) fleetStreamController.setMode(s.fleetChatVerbosity);\n }\n applyLiveSettings?.(s);\n return null;\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.debug(\n JSON.stringify({\n level: 'error',\n event: 'execution.settings_persist_failed',\n message,\n errorName: err instanceof Error ? err.name : undefined,\n timestamp: new Date().toISOString(),\n }),\n );\n return message;\n }\n }\n\n return { getSettings, saveSettings };\n}\n", "/**\n * TUI Brain panel host \u2014 the CLI side of the BrainPanelHost bridge.\n *\n * Mirrors the auth-panel pattern: the TUI never touches config files or the\n * BrainRuntime directly; every mutation funnels through this service, which\n * calls `runtime.apply()` (live rebuild + persist to the GLOBAL config) and\n * returns an error string (panel hint) or null on success.\n */\n\nimport type { BrainConfigPatch, BrainRuntime } from '@wrongstack/core/execution';\nimport type { BrainCouncilVoterConfig, BrainModelEntry } from '@wrongstack/core/types';\nimport type { BrainPanelHost, BrainPanelSettings } from '@wrongstack/tui';\n\nexport interface BrainPanelServiceDeps {\n brainRuntime: BrainRuntime;\n}\n\nconst PERSONA_CYCLE = ['executor', 'skeptic', 'auditor'] as const;\n\nfunction compactEntry(entry: BrainModelEntry): string {\n return entry.provider ? `${entry.provider}/${entry.model}` : entry.model;\n}\n\nexport function createBrainPanelHost(deps: BrainPanelServiceDeps): BrainPanelHost {\n const { brainRuntime } = deps;\n\n const apply = async (patch: BrainConfigPatch): Promise<string | null> => {\n try {\n const { persisted } = brainRuntime.apply(patch);\n const result = await persisted;\n return result.ok ? null : `Applied live but NOT saved: ${result.error ?? 'unknown error'}`;\n } catch (err) {\n return err instanceof Error ? err.message : String(err);\n }\n };\n\n const currentPool = (): string[] => brainRuntime.getSnapshot().models.map(compactEntry);\n const currentVoters = (): BrainCouncilVoterConfig[] =>\n brainRuntime.getSnapshot().council.voters.map((v) => ({ ...v }));\n const applyVoters = (voters: BrainCouncilVoterConfig[]): Promise<string | null> =>\n apply({ council: { voters: voters.length > 0 ? voters : null } });\n\n return {\n getSettings(): BrainPanelSettings {\n const snap = brainRuntime.getSnapshot();\n return {\n mode: snap.mode,\n riskLevel: snap.maxAutoRisk,\n strategy: snap.strategy,\n decisionTimeoutMs: snap.decisionTimeoutMs,\n humanTimeoutMs: snap.humanTimeoutMs,\n pool: snap.models.map(compactEntry),\n poolResolved: snap.poolLabels,\n usingSessionModel: snap.usingSessionModel,\n councilEnabled: snap.council.enabled,\n councilMinRisk: snap.council.minRisk,\n voters: snap.council.voters.map((v) => ({\n label: compactEntry(v),\n persona: v.persona,\n veto: v.veto,\n weight: v.weight,\n })),\n councilSeats: snap.councilLabels,\n // The EFFECTIVE judge, not `council.judge`. The configured one is\n // usually absent, so the panel used to read \"auto\" and say nothing\n // about who actually breaks the panel's ties \u2014 including when that is\n // one of the seats that produced the tie.\n judgeLabel: snap.judgeLabel,\n judgeConfigured: snap.council.judge !== undefined,\n judgeIsVoter: snap.judgeIsVoter,\n ledgerEnabled: snap.ledger.enabled,\n autoDenyAfterFailures: snap.ledger.autoDenyAfterFailures,\n terminalPolicy: snap.terminalPolicy,\n heuristics: {\n lowRiskAutoAnswer: snap.heuristics.lowRiskAutoAnswer,\n blockedResolved: snap.heuristics.blockedResolved,\n deadlockSkip: snap.heuristics.deadlockSkip,\n retryExhausted: snap.heuristics.retryExhausted,\n continuePing: snap.heuristics.continuePing,\n blockedResolvedMarkers: snap.heuristics.blockedResolvedMarkers,\n },\n llmMaxTokens: snap.llm.maxTokens,\n llmRejectUncertain: snap.llm.rejectUncertain,\n llmMinConfidence: snap.llm.minConfidence,\n llmDenyIsTerminal: snap.llm.denyIsTerminal,\n cacheEnabled: snap.cache.enabled,\n cacheTtlMs: snap.cache.ttlMs,\n cacheMaxEntries: snap.cache.maxEntries,\n cacheHits: snap.cache.hits,\n cacheMisses: snap.cache.misses,\n cacheSize: snap.cache.size,\n traceEnabled: snap.trace.enabled,\n traceContent: snap.trace.content,\n tracePath: snap.trace.path,\n circuitState: snap.circuit?.state,\n circuitFailures: snap.circuit?.consecutiveFailures,\n ruleCount: snap.rules.length,\n ruleErrors: [...snap.ruleErrors],\n };\n },\n setMode: (mode) => apply({ mode }),\n setRisk: (level) => apply({ maxAutoRisk: level }),\n setStrategy: (strategy) => apply({ strategy }),\n setDecisionTimeout: (ms) => apply({ decisionTimeoutMs: ms ?? null }),\n setHumanTimeout: (ms) => apply({ humanTimeoutMs: ms ?? null }),\n addPoolModel: (providerId, model) =>\n apply({ models: [...currentPool(), `${providerId}/${model}`] }),\n removePoolModel: (index) => {\n const next = currentPool().filter((_, i) => i !== index);\n return apply({ models: next.length > 0 ? next : null });\n },\n clearPool: () => apply({ models: null }),\n setCouncilEnabled: (on) => apply({ council: { enabled: on } }),\n setCouncilMinRisk: (risk) => apply({ council: { minRisk: risk } }),\n addVoter: (providerId, model) => {\n const voters = currentVoters();\n const persona = PERSONA_CYCLE[voters.length % PERSONA_CYCLE.length] as string;\n return applyVoters([...voters, { provider: providerId, model, persona }]);\n },\n removeVoter: (index) => applyVoters(currentVoters().filter((_, i) => i !== index)),\n cycleVoterPersona: (index) => {\n const voters = currentVoters();\n const voter = voters[index];\n if (!voter) return Promise.resolve('No such voter.');\n const at = PERSONA_CYCLE.indexOf(voter.persona as (typeof PERSONA_CYCLE)[number]);\n voter.persona = PERSONA_CYCLE[(at + 1) % PERSONA_CYCLE.length] as string;\n return applyVoters(voters);\n },\n toggleVoterVeto: (index) => {\n const voters = currentVoters();\n const voter = voters[index];\n if (!voter) return Promise.resolve('No such voter.');\n voter.veto = !voter.veto;\n return applyVoters(voters);\n },\n setJudge: (providerId, model) => apply({ council: { judge: `${providerId}/${model}` } }),\n clearJudge: () => apply({ council: { judge: null } }),\n setLedgerEnabled: (on) => apply({ ledger: { enabled: on } }),\n setAutoDeny: (count) => apply({ ledger: { autoDenyAfterFailures: count ?? null } }),\n setTerminalPolicy: (policy) => apply({ terminalPolicy: policy }),\n // Every sub-block below is MERGED field-by-field by `mergePatch`, so a\n // single-key patch leaves the operator's other knobs alone.\n setHeuristic: (key, on) => apply({ heuristics: { [key]: on } }),\n setLlmMaxTokens: (tokens) => apply({ llm: { maxTokens: tokens } }),\n setLlmRejectUncertain: (on) => apply({ llm: { rejectUncertain: on } }),\n setLlmMinConfidence: (value) => apply({ llm: { minConfidence: value } }),\n setLlmDenyIsTerminal: (mode) => apply({ llm: { denyIsTerminal: mode } }),\n setCacheEnabled: (on) => apply({ cache: { enabled: on } }),\n setCacheTtl: (ms) => apply({ cache: { ttlMs: ms } }),\n setCacheMaxEntries: (count) => apply({ cache: { maxEntries: count } }),\n setTraceEnabled: (on) => apply({ trace: { enabled: on } }),\n setTraceContent: (content) => apply({ trace: { content } }),\n };\n}\n", "import type {\n CascadeAgentKind,\n ChimeraCascadeNeededPayload,\n ChimeraReviewNeededPayload,\n} from '@wrongstack/core/plugin';\nimport { parseReviewSeverity } from '@wrongstack/core/plugin';\n\n// Plain .slice() operates on UTF-16 code units and can split a surrogate pair.\nexport function truncateAtCodePointBoundary(text: string, maxCodeUnits: number): string {\n if (text.length <= maxCodeUnits) return text;\n let result = '';\n for (const ch of text) {\n if (result.length + ch.length > maxCodeUnits) break;\n result += ch;\n }\n return result;\n}\n\nexport function isChimeraAllClearReview(text: string): boolean {\n const severities = parseReviewSeverity(text);\n if (severities.critical > 0 || severities.high > 0 || severities.medium > 0) {\n return false;\n }\n\n const normalized = text.trim().toLowerCase();\n return (\n normalized.startsWith('## \uD83E\uDD82 chimera review \u2014 all clear') ||\n normalized.includes('chimera review: all clear')\n );\n}\n\nexport function buildChimeraReviewTaskDescription(p: ChimeraReviewNeededPayload): string {\n const lines: string[] = [];\n lines.push(`Review the following ${p.files.length} file(s) changed in this session at ${p.cwd}.`);\n lines.push('');\n for (const f of p.files) {\n lines.push(`## [${f.status.toUpperCase()}] ${f.path}`);\n if (f.diff) {\n lines.push('');\n lines.push('```diff');\n lines.push(f.diff);\n lines.push('```');\n } else if (f.status === 'added') {\n lines.push('');\n lines.push('(New file \u2014 full content provided)');\n }\n lines.push('');\n }\n\n if (p.allChangedFiles && p.allChangedFiles.length > p.files.length) {\n const reviewedPaths = new Set(p.files.map((f) => f.path));\n const siblings = p.allChangedFiles\n .filter((s) => !reviewedPaths.has(s.path))\n .map((s) => ` ${s.path} (${s.status})`);\n if (siblings.length > 0) {\n lines.push('---');\n lines.push('');\n lines.push(\n `**Also changed this session (${siblings.length} files \u2014 for context, NOT in your review scope):**`,\n );\n lines.push(siblings.slice(0, 30).join('\\n'));\n lines.push('');\n }\n }\n\n if (p.recentCommits && p.recentCommits.length > 0) {\n lines.push('---');\n lines.push('');\n lines.push('**Recent commits (newest first):**');\n for (const c of p.recentCommits) lines.push(` ${c}`);\n lines.push('');\n }\n\n if (p.activeTodos && p.activeTodos.length > 0) {\n lines.push('---');\n lines.push('');\n lines.push(`**Active task items (${p.activeTodos.length}):**`);\n for (const t of p.activeTodos) {\n lines.push(` [${t.status}] ${t.content}`);\n }\n lines.push('');\n }\n\n if (p.kanbanCard) {\n lines.push('---');\n lines.push('');\n lines.push(`**Kanban card: ${p.kanbanCard.title}**`);\n if (p.kanbanCard.description) {\n lines.push(` ${p.kanbanCard.description.slice(0, 500)}`);\n }\n if (p.kanbanCard.successCriteria && p.kanbanCard.successCriteria.length > 0) {\n lines.push(' **Success criteria:**');\n for (const sc of p.kanbanCard.successCriteria) lines.push(` - ${sc}`);\n }\n lines.push('');\n }\n\n if (p.fileProvenance && p.fileProvenance.length > 0) {\n lines.push('---');\n lines.push('');\n lines.push('**File provenance (Chronicle):**');\n for (const fp of p.fileProvenance) {\n const parts: string[] = [];\n if (fp.agentId) parts.push(`agent: ${fp.agentId}`);\n if (fp.taskId) parts.push(`task: ${fp.taskId}`);\n if (fp.eventType) parts.push(fp.eventType);\n if (fp.observedAt) parts.push(fp.observedAt);\n lines.push(` ${fp.path} \u2014 ${parts.join(', ')}`);\n }\n lines.push('');\n }\n\n lines.push('---');\n lines.push('');\n lines.push('Read each file using the read tool. For modified files, focus on the');\n lines.push('diff above \u2014 do not re-review unchanged pre-existing code.');\n lines.push('Check for bugs, type issues, security problems, and produce a');\n lines.push('structured review report.');\n\n return lines.join('\\n');\n}\n\nexport function buildChimeraCascadeTaskDescription(\n agentKind: CascadeAgentKind,\n p: ChimeraCascadeNeededPayload,\n): string {\n const fileList = p.bundle.files.map((f) => `- ${f.path}`).join('\\n');\n const reportSlice = truncateAtCodePointBoundary(p.reviewText, 12_000);\n const severityLine = `Critical: ${p.severities.critical}, High: ${p.severities.high}, Medium: ${p.severities.medium}`;\n\n if (agentKind === 'security-scanner') {\n return [\n `You are a security cascade agent. A Chimera code review flagged security-relevant findings.`,\n ``,\n `Repository: ${p.bundle.cwd}`,\n `Severity summary: ${severityLine}`,\n ``,\n `--- Review report ---`,\n reportSlice,\n ``,\n `--- Changed files ---`,\n fileList,\n ``,\n `Investigate the security findings above. Read the flagged files, confirm or refute`,\n `each finding, and **apply fixes** for confirmed vulnerabilities using the edit tool.`,\n `Use severity (Critical/High/Medium), file:line citations, and remediation steps.`,\n `After fixing, run the project's typecheck and linter to verify. If a finding is a`,\n `false positive, say so and do not modify the file.`,\n ].join('\\n');\n }\n return [\n `You are a bug-hunter cascade agent. A Chimera code review flagged correctness defects.`,\n ``,\n `Repository: ${p.bundle.cwd}`,\n `Severity summary: ${severityLine}`,\n ``,\n `--- Review report ---`,\n reportSlice,\n ``,\n `--- Changed files ---`,\n fileList,\n ``,\n `Hunt for the bugs flagged above. Read the affected files, trace each finding to its`,\n `root cause, and **apply minimal fixes** for confirmed bugs using the edit tool.`,\n `Use severity (Critical/High/Medium), file:line citations. After fixing, run the`,\n `project's typecheck and linter to verify. If a finding is a false positive, say so`,\n `and do not modify the file.`,\n ].join('\\n');\n}\n", "import {\n buildReviewerModelPool,\n selectRoundRobinReviewerAssignment,\n} from '@wrongstack/core/plugin';\nimport type { SubagentConfig } from '@wrongstack/core/types';\n\n/**\n * Resolve the fallback-model chain used when spawning the chimera-review\n * reviewer subagent.\n *\n * Auto-review bundles pass the chain already resolved from the active fallback\n * profile/config. Manual and ordinary Chimera reviews do not inject their own\n * hard-coded model list; they rely on the selected session provider/model unless\n * the caller supplies a resolved fallback chain.\n */\nexport function resolveReviewerFallbackModels(\n reviewFallbackModels?: readonly string[] | undefined,\n /** Append session ref as a final fallback chain entry. */\n sessionRef?: string,\n): string[] {\n const base = reviewFallbackModels && reviewFallbackModels.length > 0\n ? [...reviewFallbackModels]\n : [];\n if (sessionRef && !base.includes(sessionRef)) {\n base.push(sessionRef);\n }\n return base;\n}\n\n/**\n * Process-local round-robin cursor for Chimera reviewer model assignment.\n * Advances on every successful assignment so concurrent/successive reviewers\n * start on different providers and share rate-limit budget across the pool.\n */\nlet reviewerRoundRobinCursor = 0;\n\n/** Test hook \u2014 reset the process-local reviewer round-robin cursor. */\nexport function __resetReviewerRoundRobinCursor(value = 0): void {\n reviewerRoundRobinCursor = value;\n}\n\n/**\n * Assign provider/model/fallbackModels for a Chimera reviewer spawn.\n *\n * Builds the pool from the configured primary + fallback chain, then picks\n * the next entry via round-robin. When the pool has <=1 usable entry the\n * original primary/fallbacks are returned unchanged.\n */\nexport function assignReviewerModelsRoundRobin(\n provider: string,\n model: string,\n fallbackModels: readonly string[],\n): { provider: string; model: string; fallbackModels: string[] } {\n const pool = buildReviewerModelPool(provider, model, fallbackModels);\n if (pool.length <= 1) {\n return {\n provider,\n model,\n fallbackModels: [...fallbackModels],\n };\n }\n const assignment = selectRoundRobinReviewerAssignment(\n pool,\n reviewerRoundRobinCursor,\n provider,\n model,\n );\n reviewerRoundRobinCursor = assignment.nextCursor;\n return {\n provider: assignment.provider,\n model: assignment.model,\n fallbackModels: assignment.fallbackModels,\n };\n}\n\n/**\n * Chimera reviewers only inspect code and return a report. They never repair\n * files themselves; bug-hunter/security-scanner/fix agents own all mutations.\n */\nexport const CHIMERA_REVIEW_READ_ONLY_TOOLS = Object.freeze([\n 'read',\n 'grep',\n 'glob',\n 'tree',\n 'codebase-search',\n 'codebase-stats',\n] as const);\n\nexport function applyChimeraReviewerReadOnlyPolicy(config: SubagentConfig): SubagentConfig {\n return {\n ...config,\n // A security boundary, not an additive default: discard any inherited\n // mutation tools/capabilities so Chimera reviewers cannot repair files.\n tools: [...CHIMERA_REVIEW_READ_ONLY_TOOLS],\n allowedCapabilities: ['fs.read'],\n worktree: 'off',\n };\n}\n", "import type { Director } from '@wrongstack/core/coordination';\nimport type { ExecuteDeps } from './execute-deps.js';\nimport type { FleetStatusLine } from './fleet-statusline.js';\n\nexport interface ExecutionCleanupInput {\n offStorageObservability: () => void;\n fleetStatusLine: FleetStatusLine | null;\n onCoordinatorStop?: (() => void) | undefined;\n stats: ExecuteDeps['ui']['stats'];\n renderer: ExecuteDeps['ui']['renderer'];\n detachTodosCheckpoint?: (() => void | Promise<void>) | undefined;\n mcpRegistry: ExecuteDeps['session']['mcpRegistry'];\n agent: ExecuteDeps['core']['agent'];\n session: ExecuteDeps['session']['session'];\n tokenCounter: ExecuteDeps['core']['tokenCounter'];\n events: ExecuteDeps['core']['events'];\n /** Getter for chimera's in-flight work promise \u2014 avoids stale captures. */\n getPendingChimeraWork?: () => Promise<void> | undefined;\n /** Optional director reference for fleet cleanup at session end. */\n director?: Director | null | undefined;\n reader: ExecuteDeps['ui']['reader'];\n}\n\nexport async function finalizeExecutionCleanup(input: ExecutionCleanupInput): Promise<void> {\n const {\n offStorageObservability,\n fleetStatusLine,\n onCoordinatorStop,\n stats,\n renderer,\n detachTodosCheckpoint,\n mcpRegistry,\n agent,\n session,\n tokenCounter,\n events,\n getPendingChimeraWork,\n director,\n reader,\n } = input;\n\n offStorageObservability();\n // Tear down the live fleet status line first so the scroll region is\n // restored before any end-of-session output prints.\n fleetStatusLine?.stop();\n // Stop the AutonomousCoordinator so its while-loop exits cleanly.\n // This sets running=false; the loop terminates at the next iteration check.\n onCoordinatorStop?.();\n // stats.render is synchronous but can throw - isolate it so cleanup\n // always runs regardless.\n try {\n stats.render(renderer);\n } catch (_err) {\n /* best-effort */\n }\n await Promise.resolve(detachTodosCheckpoint?.()).catch(() => undefined);\n // Each cleanup step is independently guarded so a single failure\n // (e.g. MCP registry stop rejecting) cannot skip subsequent\n // durability steps (session_end, lock clear, reader close).\n await mcpRegistry.stopAll().catch((err) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.mcp_stop_failed',\n message: `MCP registry stopAll failed: ${err instanceof Error ? err.message : String(err)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n // Use the CURRENT writer, not the one captured at startup - an in-app\n // resume (TUI/WebUI) swaps agent.ctx.session to the resumed session's\n // writer; session_end and close must land in THAT JSONL or the resumed\n // session never gets finalized (no summary sidecar, no index entry).\n const activeSession = agent.ctx.session ?? session;\n const pending = activeSession.pendingToolUses;\n await activeSession\n .append({\n type: 'session_end',\n ts: new Date().toISOString(),\n usage: tokenCounter.total(),\n pendingToolUses: pending.length > 0 ? pending : undefined,\n })\n .catch((err) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.session_end_append_failed',\n message: `session_end append failed: ${err instanceof Error ? err.message : String(err)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n events.emit('session.ended', {\n id: activeSession.id,\n sessionId: activeSession.id,\n usage: tokenCounter.total(),\n });\n // Await chimera's in-flight work so the review result is written to the JSONL\n // before we close - without this, session.close() races against the subagent\n // and the review text is silently dropped because append returns early on closed.\n if (getPendingChimeraWork) {\n const chimeraWork = getPendingChimeraWork();\n if (chimeraWork) {\n await chimeraWork.catch((err) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.chimera_work_failed',\n message: `Pending chimera work failed: ${err instanceof Error ? err.message : String(err)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n }\n }\n // Safety net: terminate any remaining fleet subagents after chimera work\n // completes. Individual per-agent termination (reviewer, fix, cascade) runs\n // inside each handler, but this catches stragglers if an error path or\n // unexpected state left a subagent alive.\n if (director) {\n try {\n await director.terminateAll();\n } catch (termErr) {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.director_terminate_all_failed',\n message: termErr instanceof Error ? termErr.message : String(termErr),\n timestamp: new Date().toISOString(),\n }),\n );\n }\n }\n await activeSession.close().catch((err) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.session_close_failed',\n message: `Session close failed: ${err instanceof Error ? err.message : String(err)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n await reader.close().catch((err) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'shutdown.reader_close_failed',\n message: `Input reader close failed: ${err instanceof Error ? err.message : String(err)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n}\n", "import { randomUUID } from 'node:crypto';\nimport { WIDE_SUBAGENT_CAPABILITIES } from '@wrongstack/core/security';\nimport type { WebUIDispatchContext } from './boot/dispatch-webui.js';\nimport type { ExecuteDeps } from './execute-deps.js';\nimport { resolveKanbanDispatchRoute } from './kanban-dispatch-route.js';\n\ntype KanbanDispatchHandler = NonNullable<WebUIDispatchContext['onKanbanDispatch']>;\n\nexport type CreateKanbanDispatchHandlerOptions = {\n config: ExecuteDeps['core']['config'];\n events: ExecuteDeps['core']['events'];\n skillLoader: ExecuteDeps['ui']['skillLoader'];\n sddSubagentFactory: ExecuteDeps['provider']['sddSubagentFactory'];\n};\n\nexport function createKanbanDispatchHandler({\n config,\n events,\n skillLoader,\n sddSubagentFactory,\n}: CreateKanbanDispatchHandlerOptions): Pick<WebUIDispatchContext, 'onKanbanDispatch'> {\n if (!sddSubagentFactory) return {};\n\n const onKanbanDispatch: KanbanDispatchHandler = async (description, spawnOpts) => {\n const subagentId = `kanban-${randomUUID().slice(0, 8)}`;\n const taskId = randomUUID();\n const name = spawnOpts?.name ?? 'kanban-agent';\n const {\n provider: resolvedProvider,\n model: resolvedModel,\n fallbackModels: resolvedFallbackModels,\n } = resolveKanbanDispatchRoute(config, spawnOpts);\n let agentDescription = description;\n if (spawnOpts?.skills?.length && skillLoader) {\n const loaded = await Promise.all(\n spawnOpts.skills.map(async (skillName) => {\n const manifest = await skillLoader.find(skillName);\n if (!manifest) throw new Error(`Kanban skill not found: ${skillName}`);\n const body = await skillLoader.readBody(skillName);\n return `## Required skill: ${skillName}\\n\\n${body}`;\n }),\n );\n agentDescription = `${description}\\n\\n# Required agentic skill instructions\\n\\n${loaded.join('\\n\\n')}`;\n }\n void (async () => {\n const built = await sddSubagentFactory({\n id: subagentId,\n name,\n role: 'kanban-agent',\n prompt: agentDescription,\n allowedCapabilities: spawnOpts?.allowedCapabilities ?? WIDE_SUBAGENT_CAPABILITIES,\n ...(resolvedProvider ? { provider: resolvedProvider } : {}),\n ...(resolvedModel ? { model: resolvedModel } : {}),\n ...(resolvedFallbackModels ? { fallbackModels: resolvedFallbackModels } : {}),\n ...(spawnOpts?.tools ? { tools: spawnOpts.tools } : {}),\n });\n try {\n const result = await built.agent.run(agentDescription);\n await spawnOpts?.onDone?.({\n status: result.status === 'done' ? 'completed' : 'failed',\n result: result.finalText,\n ...('error' in result && result.error?.message ? { error: result.error.message } : {}),\n });\n } catch (err) {\n await spawnOpts?.onDone?.({\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n } finally {\n await built.dispose?.();\n }\n })().catch((err) => {\n events.emit('error', {\n err: err instanceof Error ? err : new Error(String(err)),\n phase: 'kanban.dispatch',\n });\n });\n const tags: string[] = [];\n if (resolvedProvider) tags.push(resolvedProvider);\n if (resolvedModel) tags.push(resolvedModel);\n if (resolvedFallbackModels?.length) {\n tags.push(`fallback=${resolvedFallbackModels.join(',')}`);\n }\n if (spawnOpts?.fallbackProfile) tags.push(`profile=${spawnOpts.fallbackProfile}`);\n if (spawnOpts?.skills?.length) tags.push(`skills=${spawnOpts.skills.join(',')}`);\n if (spawnOpts?.name) tags.push(`\"${spawnOpts.name}\"`);\n const tag = tags.length > 0 ? ` (${tags.join(' / ')})` : '';\n return `Spawned subagent ${subagentId}${tag} for task ${taskId}.`;\n };\n\n return { onKanbanDispatch };\n}\n", "import {\n fallbackProfileChain,\n parseModelRef,\n} from '@wrongstack/core/agent';\nimport type { Config } from '@wrongstack/core/types';\n\nexport interface KanbanDispatchRouteInput {\n provider?: string | undefined;\n model?: string | undefined;\n fallbackModels?: string[] | undefined;\n fallbackProfile?: string | undefined;\n}\n\nexport interface KanbanDispatchRoute {\n provider?: string | undefined;\n model?: string | undefined;\n fallbackModels?: string[] | undefined;\n}\n\nexport function resolveKanbanDispatchRoute(\n config: Config,\n spawnOpts?: KanbanDispatchRouteInput | undefined,\n): KanbanDispatchRoute {\n let provider = spawnOpts?.provider;\n let model = spawnOpts?.model;\n let fallbackModels = spawnOpts?.fallbackModels;\n if (spawnOpts?.fallbackProfile) {\n const chain = fallbackProfileChain(config, spawnOpts.fallbackProfile);\n const primary = chain[0] ? parseModelRef(chain[0]) : undefined;\n if (primary?.model) {\n provider = primary.provider ?? config.provider;\n model = primary.model;\n fallbackModels = spawnOpts.fallbackModels ?? chain.slice(1);\n }\n }\n return { provider, model, fallbackModels };\n}\n", "import type { Director } from '@wrongstack/core/coordination';\n\nexport interface ReplFleetCallbacksOptions {\n director: Director | null | undefined;\n getDirector: (() => Director | null | undefined) | undefined;\n}\n\nexport interface ReplFleetCallbacks {\n onInterruptFleet: () => number;\n onAgentIterationComplete: (tokens: number) => void;\n}\n\nexport function createReplFleetCallbacks({\n director,\n getDirector,\n}: ReplFleetCallbacksOptions): ReplFleetCallbacks {\n const resolveDirector = () => getDirector?.() ?? director;\n\n return {\n onInterruptFleet: () => {\n // Mirror the slash /fleet kill path: remove every running/idle subagent\n // so Ctrl+C stops the whole fleet, including lazily-created Directors.\n const dir = resolveDirector();\n if (!dir) return 0;\n let killed = 0;\n for (const sa of dir.status().subagents) {\n if (sa.status === 'running' || sa.status === 'idle') {\n try {\n void dir.remove(sa.id);\n killed++;\n } catch {\n /* best-effort */\n }\n }\n }\n return killed;\n },\n onAgentIterationComplete: (tokens) => {\n const dir = resolveDirector();\n dir?.setLeaderContextPressure(tokens);\n },\n };\n}\n", "/**\n * Live fleet status line for the plain (non-TUI) REPL and single-shot modes.\n *\n * The TUI already renders a rich per-agent 4th line; the plain terminal had\n * nothing live while subagents ran. This reserves the bottom terminal row via\n * a DECSTBM scroll region (`\\x1b[1;{rows-1}r`) so normal streamed output keeps\n * scrolling in the region above while a continuously-updated status line stays\n * pinned to the bottom. It activates only when \u22651 subagent is running on a TTY,\n * and fully restores the scroll region when the fleet goes idle or on dispose.\n *\n * State is fed entirely by host EventBus events (the coordinator + the\n * multi-agent factory bridge both emit onto the host bus):\n * subagent.spawned / task_started / tool_executed / iteration_summary /\n * task_completed.\n */\n\nimport type { EventBus } from '@wrongstack/core/kernel';\nimport { color } from '@wrongstack/core/utils';\nimport { onResize } from '@wrongstack/core/utils';\n\nexport interface FleetAgentState {\n id: string;\n name: string;\n status: 'running' | 'done' | 'failed';\n iterations: number;\n toolCalls: number;\n lastTool?: string | undefined;\n startedAt: number;\n endedAt?: number | undefined;\n /** Cumulative budget auto-extensions \u2014 rendered as a \"\u26A1N\" suffix. */\n extensions?: number | undefined;\n}\n\nexport interface FleetStatusLineOptions {\n events: EventBus;\n out?: NodeJS.WriteStream | undefined;\n /** Minimum ms between repaints. Default 150. */\n throttleMs?: number | undefined;\n /** Inject a clock for tests. */\n now?: (() => number) | undefined;\n /** App version (e.g. \"0.7.0\") prefixed as a `WS v\u2026` chip on the pinned line. */\n version?: string | undefined;\n}\n\nfunction fmtElapsed(ms: number): string {\n const s = Math.floor(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n const rem = s % 60;\n if (m < 60) return `${m}m${rem.toString().padStart(2, '0')}s`;\n const h = Math.floor(m / 60);\n return `${h}h${(m % 60).toString().padStart(2, '0')}m`;\n}\n\n/**\n * Pure formatter \u2014 turns the agent map into a single status string. Exposed\n * for testing; contains no ANSI cursor movement, only color codes + the width\n * cap. Returns '' when there is nothing worth showing.\n */\nexport function renderFleetLine(\n states: Map<string, FleetAgentState>,\n now: number,\n columns: number,\n version?: string | undefined,\n): string {\n const all = [...states.values()];\n if (all.length === 0) return '';\n const running = all.filter((a) => a.status === 'running');\n const done = all.filter((a) => a.status === 'done').length;\n const failed = all.filter((a) => a.status === 'failed').length;\n\n const versionChip = version\n ? `${color.bold('WS')}${color.dim(` v${version}`)} ${color.dim('\u2502')} `\n : '';\n const counts =\n versionChip +\n `${color.cyan('\u27F3 fleet')} ` +\n `${color.yellow(`\u25B6${running.length}`)} ` +\n `${color.green(`\u2713${done}`)}` +\n (failed > 0 ? ` ${color.red(`\u2717${failed}`)}` : '');\n\n // Show running agents first (most relevant), newest activity first.\n const shown = running\n .sort((a, b) => a.startedAt - b.startedAt)\n .slice(0, 4)\n .map((a) => {\n const elapsed = fmtElapsed(Math.max(0, now - a.startedAt));\n const tool = a.lastTool ? ` ${color.dim(a.lastTool)}` : '';\n const ext = a.extensions && a.extensions > 0 ? ` ${color.yellow(`\u26A1${a.extensions}`)}` : '';\n return (\n `${color.bold(a.name)} ` +\n `${color.yellow('\u25B6')} ${color.dim(elapsed)} ` +\n `${color.dim(`L${a.iterations}`)} ${color.dim(`${a.toolCalls}t`)}${tool}${ext}`\n );\n });\n\n let line =\n shown.length > 0 ? `${counts} ${color.dim('\u2502')} ${shown.join(color.dim(' \u00B7 '))}` : counts;\n\n // Hard cap to terminal width so the line never wraps and corrupts the\n // scroll region. Strip-aware truncation isn't worth it here \u2014 cap on the\n // raw length minus a safety margin; ANSI codes are short and the margin\n // absorbs them.\n const max = Math.max(20, columns - 1);\n // Rough visible-length guard: count only non-ANSI chars.\n const visible = line.replace(/\\x1b\\[[0-9;]*m/g, '');\n if (visible.length > max) {\n // Re-truncate the visible portion; rebuild without trailing partial codes.\n let count = 0;\n const out: string[] = [];\n let i = 0;\n while (i < line.length && count < max - 1) {\n if (line[i] === '\\x1b') {\n const end = line.indexOf('m', i);\n if (end !== -1) {\n out.push(line.slice(i, end + 1));\n i = end + 1;\n continue;\n }\n }\n if (line[i] !== undefined) out.push(line[i]!);\n count++;\n i++;\n }\n line = out.join('') + '\u2026';\n }\n return line;\n}\n\nexport class FleetStatusLine {\n private readonly events: EventBus;\n private readonly out: NodeJS.WriteStream;\n private readonly throttleMs: number;\n private readonly now: () => number;\n private readonly version?: string | undefined;\n private readonly states = new Map<string, FleetAgentState>();\n private readonly unsubs: Array<() => void> = [];\n private active = false;\n private rows = 0;\n private repaintTimer: ReturnType<typeof setTimeout> | null = null;\n private tickTimer: ReturnType<typeof setInterval> | null = null;\n private resizeCleanup: (() => void) | null = null;\n private lastPaint = 0;\n private readonly onResize = () => {\n if (this.active) {\n this.rows = this.out.rows ?? 24;\n this.out.write(`\\x1b[1;${this.rows - 1}r`);\n this.paint(true);\n }\n };\n\n constructor(opts: FleetStatusLineOptions) {\n this.events = opts.events;\n this.out = opts.out ?? process.stdout;\n this.throttleMs = opts.throttleMs ?? 150;\n this.now = opts.now ?? Date.now;\n this.version = opts.version;\n }\n\n /** Subscribe to host fleet events. No terminal output until a subagent spawns. */\n start(): void {\n const ensure = (id: string, name?: string): FleetAgentState => {\n let s = this.states.get(id);\n if (!s) {\n s = {\n id,\n name: name ?? id,\n status: 'running',\n iterations: 0,\n toolCalls: 0,\n startedAt: this.now(),\n };\n this.states.set(id, s);\n } else if (name && s.name === s.id) {\n s.name = name;\n }\n return s;\n };\n\n this.unsubs.push(\n this.events.on('subagent.spawned', (e) => {\n ensure(e.subagentId, e.name);\n this.activate();\n this.schedulePaint();\n }),\n this.events.on('subagent.task_started', (e) => {\n const s = ensure(e.subagentId);\n s.status = 'running';\n this.activate();\n this.schedulePaint();\n }),\n this.events.on('subagent.tool_executed', (e) => {\n const s = ensure(e.subagentId);\n s.toolCalls++;\n s.lastTool = e.name;\n this.activate();\n this.schedulePaint();\n }),\n this.events.on('subagent.iteration_summary', (e) => {\n const s = ensure(e.subagentId);\n s.iterations = e.iteration;\n if (typeof e.toolCalls === 'number') s.toolCalls = e.toolCalls;\n if (e.currentTool) s.lastTool = e.currentTool;\n this.schedulePaint();\n }),\n this.events.on('subagent.budget_extended', (e) => {\n const s = ensure(e.subagentId);\n s.extensions = e.totalExtensions;\n this.activate();\n this.schedulePaint();\n }),\n this.events.on('subagent.task_completed', (e) => {\n const s = ensure(e.subagentId);\n s.status = e.status === 'success' ? 'done' : 'failed';\n s.iterations = e.iterations;\n s.toolCalls = e.toolCalls;\n s.endedAt = this.now();\n this.schedulePaint();\n // When nothing is running anymore, retract the status line.\n if (![...this.states.values()].some((a) => a.status === 'running')) {\n // Small delay so the final \u2713/\u2717 counts are visible briefly.\n setTimeout(() => {\n if (![...this.states.values()].some((a) => a.status === 'running')) {\n this.deactivate();\n }\n }, 800);\n }\n }),\n this.events.on('subagent.removed', (e) => {\n // Drop terminal-state entries so a long-running REPL doesn't keep one\n // entry per retired subagent for the process lifetime (RAM-leak audit\n // 2026-07-31, LOW). Mirrors `cli/src/fleet/status-broadcast.ts`.\n this.states.delete(e.subagentId);\n this.schedulePaint();\n }),\n );\n }\n\n /** Unsubscribe and restore the terminal. Idempotent. */\n stop(): void {\n for (const u of this.unsubs.splice(0)) u();\n this.deactivate();\n }\n\n private isTty(): boolean {\n return !!this.out.isTTY;\n }\n\n private activate(): void {\n if (this.active || !this.isTty()) return;\n this.active = true;\n this.rows = this.out.rows ?? 24;\n // Make room for the reserved row, then carve out the scroll region.\n this.out.write('\\n');\n this.out.write(`\\x1b[1;${this.rows - 1}r`);\n this.out.write(`\\x1b[${this.rows - 1};1H`);\n this.resizeCleanup = onResize(() => this.onResize(), this.out);\n this.tickTimer = setInterval(() => this.paint(true), 1000);\n if (this.tickTimer.unref) this.tickTimer.unref();\n this.paint(true);\n }\n\n private deactivate(): void {\n if (!this.active) return;\n this.active = false;\n if (this.tickTimer) {\n clearInterval(this.tickTimer);\n this.tickTimer = null;\n }\n if (this.repaintTimer) {\n clearTimeout(this.repaintTimer);\n this.repaintTimer = null;\n }\n this.resizeCleanup?.();\n this.resizeCleanup = null;\n if (this.isTty()) {\n // Clear the reserved line and reset the scroll region to full screen.\n this.out.write('\\x1b7');\n this.out.write(`\\x1b[${this.rows};1H`);\n this.out.write('\\x1b[2K');\n this.out.write('\\x1b8');\n this.out.write('\\x1b[r');\n }\n }\n\n private schedulePaint(): void {\n if (!this.active) return;\n const since = this.now() - this.lastPaint;\n if (since >= this.throttleMs) {\n this.paint(false);\n return;\n }\n if (this.repaintTimer) return;\n this.repaintTimer = setTimeout(() => {\n this.repaintTimer = null;\n this.paint(false);\n }, this.throttleMs - since);\n if (this.repaintTimer.unref) this.repaintTimer.unref();\n }\n\n private paint(force: boolean): void {\n if (!this.active || !this.isTty()) return;\n if (!force) this.lastPaint = this.now();\n else this.lastPaint = this.now();\n const line = renderFleetLine(this.states, this.now(), this.out.columns ?? 80, this.version);\n this.out.write('\\x1b7'); // save cursor\n this.out.write(`\\x1b[${this.rows};1H`); // last row\n this.out.write('\\x1b[2K'); // clear\n this.out.write(line);\n this.out.write('\\x1b8'); // restore cursor\n }\n}\n", "import { createHash } from 'node:crypto';\nimport type { Mailbox } from '@wrongstack/core/coordination';\nimport type { SessionWriter, StopReason } from '@wrongstack/core/types';\n\nexport async function waitForChimeraAskApproval(opts: {\n mailbox: Mailbox;\n messageId: string;\n meta: Record<string, unknown>;\n session: SessionWriter;\n askTimeoutMs: number;\n}): Promise<boolean> {\n const rawPoll = (opts.meta['chimeraPollIntervalMs'] as number | undefined) ?? 2_000;\n const pollIntervalMs = Number.isFinite(rawPoll) ? Math.max(0, rawPoll) : 2_000;\n const abortSignal = opts.meta['chimeraAbortSignal'] as AbortSignal | undefined;\n const askStartTime = Date.now();\n\n let leaderApproved = false;\n let repliesFound = false;\n let nonLeaderReplyCount = 0;\n let pollDone = false;\n\n const pollNext = (): Promise<void> => {\n if (pollDone) return Promise.resolve();\n const elapsed = Date.now() - askStartTime;\n const remaining = opts.askTimeoutMs - elapsed;\n if (remaining <= 0 || abortSignal?.aborted) {\n pollDone = true;\n return Promise.resolve();\n }\n return new Promise((r) => setTimeout(r, Math.min(pollIntervalMs, remaining))).then(() =>\n pollForReply(),\n );\n };\n\n const pollForReply = async (): Promise<void> => {\n if (pollDone) return;\n const replies = await opts.mailbox.query({ replyTo: opts.messageId, limit: 5 });\n if (replies.length > 0) {\n repliesFound = true;\n const firstReply = replies[0];\n if (!firstReply) return pollNext();\n\n const replyFromBase = (firstReply.from ?? '').split('@')[0];\n if (replyFromBase !== 'leader' || firstReply.audience === 'leaders') {\n nonLeaderReplyCount++;\n if (nonLeaderReplyCount >= 5) {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_ask_non_leader_threshold',\n message: `${nonLeaderReplyCount} non-leader replies seen on chimera ask \u2014 stopping poll`,\n timestamp: new Date().toISOString(),\n }),\n );\n pollDone = true;\n return;\n }\n console.warn(\n JSON.stringify({\n level: nonLeaderReplyCount <= 1 ? 'warn' : 'debug',\n event: 'execution.chimera_ask_non_leader_reply',\n message: `Ignoring non-leader reply #${nonLeaderReplyCount} from ${firstReply.from}`,\n timestamp: new Date().toISOString(),\n }),\n );\n return pollNext();\n }\n\n await opts.mailbox\n .ack({\n messageId: firstReply.id,\n readerId: 'chimera-review',\n read: true,\n completed: true,\n })\n .catch((_ackErr) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_ask_ack_failed',\n message: _ackErr instanceof Error ? _ackErr.message : String(_ackErr),\n replyMessageId: firstReply.id,\n timestamp: new Date().toISOString(),\n }),\n );\n });\n\n const body = firstReply.body.toLowerCase();\n if (body.trim().length === 0) {\n pollDone = true;\n return;\n }\n leaderApproved =\n /^\\s*(?:y(?:es)?|sure|ok(?:ay)?|go ahead|proceed|approve|fix it|please do|do it|yep|yeah)\\b/.test(\n body,\n ) || /^\\s*\uD83D\uDC4D/.test(body);\n if (leaderApproved) {\n pollDone = true;\n return;\n }\n if (/^\\s*(no|don'?t|stop|skip|ignore|cancel|reject|decline)\\b/.test(body)) {\n pollDone = true;\n return;\n }\n\n leaderApproved = /\\b(?:y(?:es)?|sure|approve|proceed|go ahead)\\b/i.test(body);\n if (leaderApproved) {\n pollDone = true;\n return;\n }\n\n const hash = createHash('sha256').update(body).digest('hex').slice(0, 12);\n console.warn(\n JSON.stringify({\n level: 'debug',\n event: 'execution.chimera_ask_reply_unmatched',\n replyBodyHash: hash,\n replyBodyLength: body.length,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n\n return pollNext();\n };\n\n await pollForReply();\n if (!leaderApproved) {\n await recordChimeraAskFallback(opts.session, opts.askTimeoutMs, repliesFound);\n }\n return leaderApproved;\n}\n\nasync function recordChimeraAskFallback(\n session: SessionWriter,\n askTimeoutMs: number,\n repliesFound: boolean,\n): Promise<void> {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: repliesFound ? 'execution.chimera_ask_rejected' : 'execution.chimera_ask_timeout',\n message: repliesFound\n ? 'Leader replied to ask but did not approve'\n : 'Ask timeout expired, falling back to off mode (no auto-fix)',\n timestamp: new Date().toISOString(),\n }),\n );\n\n await session\n .append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n {\n type: 'text',\n text: `\uD83E\uDD82 Chimera auto-fix request sent to leader \u2014 no approval received within ${askTimeoutMs / 1000}s timeout. Falling back to manual review mode. Set autoFix via \\`/chimera autoFix auto\\` to auto-approve future reviews.`,\n },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n })\n .catch((_appendErr) => {\n console.warn(\n JSON.stringify({\n level: 'warn',\n event: 'execution.chimera_timeout_append_failed',\n message: _appendErr instanceof Error ? _appendErr.message : String(_appendErr),\n timestamp: new Date().toISOString(),\n }),\n );\n });\n}\n", "import { randomUUID } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type {\n ChimeraCascadeNeededPayload,\n ChimeraReviewNeededPayload,\n} from '@wrongstack/core/plugin';\nimport { emitReviewIfChanged } from '@wrongstack/core/plugin';\nimport type { StopReason, SubagentConfig } from '@wrongstack/core/types';\nimport { buildChimeraCascadeTaskDescription } from './chimera-review-task.js';\nimport type { ExecuteDeps } from './execute-deps.js';\n\ntype Director = NonNullable<ExecuteDeps['fleet']['director']>;\ntype Events = ExecuteDeps['core']['events'];\ntype Session = ExecuteDeps['session']['session'];\n\ntype PendingChimeraWork = Promise<void> | undefined;\n\nexport type InstallChimeraCascadeHandlerOptions = {\n events: Events;\n director: Director | null | undefined;\n session: Session;\n getPendingWork: () => PendingChimeraWork;\n setPendingWork: (work: PendingChimeraWork) => void;\n};\n\nexport function installChimeraCascadeHandler({\n events,\n director,\n session,\n getPendingWork,\n setPendingWork,\n}: InstallChimeraCascadeHandlerOptions): void {\n events.onPattern('chimera.cascade_needed', (_event, payload) => {\n const p = payload as ChimeraCascadeNeededPayload;\n const dir = director;\n if (!dir) return; // Director not available \u2014 cascade skipped.\n if (p.agents.length === 0) return;\n\n const previousWork = getPendingWork();\n\n // Track in pending work so the execution finally block awaits cascade\n // completion before session.close(). Chain onto any prior in-flight\n // work so cascades run after their parent review, not concurrently.\n const pendingWork = (async () => {\n // Await any prior pending work (the parent review) before spawning.\n try {\n await previousWork;\n } catch {\n // Parent failed \u2014 proceed with cascade anyway; the review text\n // is carried in the payload, independent of subagent success.\n }\n\n for (const agentKind of p.agents) {\n try {\n const taskDesc = buildChimeraCascadeTaskDescription(agentKind, p);\n const role = agentKind === 'security-scanner' ? 'security-scanner' : 'bug-hunter';\n const cfg: SubagentConfig = {\n name: `chimera-cascade-${agentKind}`,\n role,\n maxIterations: 40,\n maxToolCalls: 200,\n timeoutMs: 600_000,\n };\n const subagentId = await dir.spawn(cfg);\n try {\n const taskId = randomUUID();\n await dir.assign({ id: taskId, description: taskDesc, subagentId });\n const results = await dir.awaitTasks([taskId]);\n const result = results[0];\n\n if (result?.status === 'success') {\n const resultText =\n typeof result.result === 'string' ? result.result : JSON.stringify(result.result);\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n {\n type: 'text',\n text: `\uD83E\uDD82 Chimera cascade (${agentKind}) \u2014 ${resultText}`,\n },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n } else {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera cascade (${agentKind}) ${result?.status ?? 'unknown'}: ${result?.error?.message ?? 'no result'}`,\n phase: 'agent',\n });\n }\n } finally {\n try { await dir.terminate(subagentId); } catch { /* best-effort */ }\n }\n } catch (err) {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera cascade (${agentKind}) failed: ${err instanceof Error ? err.message : String(err)}`,\n phase: 'agent',\n });\n }\n }\n\n await maybeReReviewCascade({ events, session, bundle: p.bundle });\n })();\n\n setPendingWork(pendingWork);\n });\n}\n\nasync function maybeReReviewCascade({\n events,\n session,\n bundle,\n}: {\n events: Events;\n session: Session;\n bundle: ChimeraCascadeNeededPayload['bundle'];\n}): Promise<void> {\n // After the cascade fix agents finish, re-read the (now possibly modified)\n // files and re-emit chimera.review_needed to trigger a fresh review. The\n // loop is bounded by maxCascadeDepth.\n const maxDepth = bundle.maxCascadeDepth ?? 0;\n const currentDepth = bundle.cascadeDepth ?? 0;\n if (maxDepth > 0 && currentDepth < maxDepth) {\n try {\n const reReadFiles: ChimeraReviewNeededPayload['files'] = [];\n for (const f of bundle.files) {\n try {\n const absPath = path.join(bundle.cwd, f.path);\n const content = await fsp.readFile(absPath, 'utf8');\n reReadFiles.push({ path: f.path, status: 'modified', content });\n } catch {\n // File deleted or unreadable \u2014 skip it.\n }\n }\n\n if (reReadFiles.length > 0) {\n const reReviewBundle: ChimeraReviewNeededPayload = {\n ...bundle,\n files: reReadFiles,\n cascadeDepth: currentDepth + 1,\n };\n\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n {\n type: 'text',\n text: `\uD83E\uDD82 Chimera cascade re-review (depth ${currentDepth + 1}/${maxDepth}) \u2014 re-reviewing ${reReadFiles.length} file(s) after fixes`,\n },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n\n // Use emitReviewIfChanged so content-fingerprint dedup protects\n // against re-reviewing files the fix agent didn't actually change.\n // emitCustom() is the safe passthrough the function needs.\n const emitted = emitReviewIfChanged(\n { events, emitCustom: events.emitCustom.bind(events) },\n reReviewBundle,\n );\n if (!emitted) {\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n {\n type: 'text',\n text: `\uD83E\uDD82 Chimera cascade re-review skipped \u2014 content unchanged since previous review (depth ${currentDepth + 1}/${maxDepth})`,\n },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n }\n }\n } catch (err) {\n await session.append({\n type: 'error',\n ts: new Date().toISOString(),\n message: `\uD83E\uDD82 Chimera cascade re-review failed: ${err instanceof Error ? err.message : String(err)}`,\n phase: 'agent',\n });\n }\n } else if (maxDepth > 0 && currentDepth >= maxDepth) {\n await session.append({\n type: 'llm_response',\n ts: new Date().toISOString(),\n content: [\n {\n type: 'text',\n text: `\uD83E\uDD82 Chimera cascade stopped at depth limit (${currentDepth}/${maxDepth}) \u2014 manual review recommended if issues persist`,\n },\n ],\n stopReason: 'end_turn' as StopReason,\n usage: { input: 0, output: 0 },\n });\n }\n}\n", "import type { EventBus } from '@wrongstack/core/kernel';\n\nexport function installStorageObservability(\n events: EventBus,\n rootTraceId: string | undefined,\n): () => void {\n const isStorageNamespace = (event: string): boolean =>\n event === 'storage.read' ||\n event === 'storage.write' ||\n event === 'storage.error' ||\n event.startsWith('storage.');\n const storageLog = (event: string, payload: Record<string, unknown>) => {\n // `storage.*` events are routine atomic-write telemetry (e.g. the\n // ctx.todos checkpoint at packages/core/src/storage/todos-checkpoint.ts\n // emitting a JSON line on every save). Successful reads/writes\n // (`outcome: 'success'`) are not user-actionable signals and would\n // clutter the CLI's stdout chat pane (the SimpleUI protocol decoder\n // also rejects these frames before they reach the timeline; see\n // packages/webui-server/src/protocol/decoder.ts).\n //\n // However, failure paths must NOT be silently swallowed here. Many\n // emitters publish failure telemetry only on `storage.error` (and\n // some on `storage.read`/`storage.write` with `outcome: 'failure'`)\n // \u2014 they do not consistently publish a duplicate `agent.error` or\n // `error` event. Hiding them on this filter would lose non-fatal\n // but user-actionable diagnostics (e.g. project-manifest write\n // failures in plan-store.ts, audit-log record failures in\n // tool-audit-log.ts). So we keep three exception channels:\n // 1. `storage.error` \u2014 always surface (warning level).\n // 2. `storage.read` / `storage.write` carrying `outcome: 'failure'`.\n // 3. Any other `storage.<token>` whose payload reports a failure.\n // Everything else in the `storage.*` namespace (successful routine\n // telemetry) is dropped so the terminal stays clean.\n //\n // Prefix-boundary check: explicit equality for the three known\n // kinds, then a dot-anchored prefix for any future `storage.<token>`\n // the host may add. `startsWith('storage.')` alone would also match\n // `storagex.write` (a typosquat), so the dot anchor pins the\n // namespace exactly.\n if (isStorageNamespace(event)) {\n const outcome = payload.outcome;\n const isErrorEvent = event === 'storage.error';\n const reportsFailure = outcome === 'failure' || outcome === 'error';\n const isFailure = isErrorEvent || reportsFailure;\n if (!isFailure) {\n return;\n }\n const traceId = (payload.traceId as string | undefined) ?? rootTraceId;\n // eslint-disable-next-line no-console\n console.warn(\n JSON.stringify({\n ...payload,\n level: 'warning',\n event,\n timestamp: new Date().toISOString(),\n traceId,\n }),\n );\n return;\n }\n const traceId = (payload.traceId as string | undefined) ?? rootTraceId;\n // eslint-disable-next-line no-console\n console.warn(\n JSON.stringify({\n ...payload,\n level: 'info',\n event,\n timestamp: new Date().toISOString(),\n traceId,\n }),\n );\n };\n const onStorageRead = (...args: unknown[]) =>\n storageLog('storage.read', args[0] as Record<string, unknown>);\n const onStorageWrite = (...args: unknown[]) =>\n storageLog('storage.write', args[0] as Record<string, unknown>);\n const onStorageError = (...args: unknown[]) =>\n storageLog('storage.error', args[0] as Record<string, unknown>);\n const offStorageRead = events.on('storage.read', onStorageRead);\n const offStorageWrite = events.on('storage.write', onStorageWrite);\n const offStorageError = events.on('storage.error', onStorageError);\n return () => {\n offStorageRead();\n offStorageWrite();\n offStorageError();\n };\n}\n", "/**\n * Next-task prediction \u2014 a lightweight, single-shot LLM call that guesses the\n * user's most likely next steps after an agent turn completes.\n *\n * Unlike `/autonomy suggest` (which replays a full `agent.run` with every tool\n * available), this issues ONE direct `provider.complete` with a tiny prompt and\n * a low token cap. No tools, no context replay \u2014 cheap and fast. It mirrors the\n * one-shot pattern used by `generateCommitMessageWithLLM` and `dispatch-llm`.\n *\n * The result is display-only: predictions are shown to the user, never executed.\n */\n\nimport { readBundledInstructionText } from '@wrongstack/core/utils';\nimport type { TodoItem } from '@wrongstack/core/agent';\nimport type { CommitLLMProvider } from './services/commit-message.js';\n\n/** Provider shape required to predict \u2014 same structural contract as commit-llm. */\nexport type PredictLLMProvider = CommitLLMProvider;\n\nexport interface PredictionInput {\n /** The user's request that kicked off the turn we just finished. */\n userRequest: string;\n /** The agent's final assistant text for the turn (its summary of what it did). */\n assistantSummary: string;\n /** The current live todo list, used as a strong signal for what's left. */\n todos: readonly TodoItem[];\n}\n\nexport interface PredictOpts {\n provider: PredictLLMProvider;\n model: string;\n /** Max predictions to return. Default 3. */\n maxPredictions?: number | undefined;\n /** Abort signal \u2014 when omitted, an internal 12s timeout is used. */\n signal?: AbortSignal | undefined;\n}\n\nconst SYSTEM_PROMPT = readBundledInstructionText('cli/next-task-predictor.md');\n\nconst MAX_REQUEST_CHARS = 1200;\nconst MAX_SUMMARY_CHARS = 1200;\n\n/** Clamp a string to `n` chars, appending an ellipsis when truncated. */\nfunction clamp(text: string, n: number): string {\n const t = text.trim();\n return t.length <= n ? t : `${t.slice(0, n)}\u2026`;\n}\n\n/** Build the user-message text from the turn context. Pure + testable. */\nexport function buildPredictionPrompt(input: PredictionInput): string {\n const parts: string[] = [];\n parts.push(`The user asked:\\n${clamp(input.userRequest, MAX_REQUEST_CHARS) || '(no text)'}`);\n if (input.assistantSummary.trim()) {\n parts.push(\n `The assistant just finished and reported:\\n${clamp(input.assistantSummary, MAX_SUMMARY_CHARS)}`,\n );\n }\n const pending = input.todos.filter((t) => t.status !== 'completed');\n if (pending.length > 0) {\n const list = pending\n .slice(0, 8)\n .map((t) => `- [${t.status}] ${t.content}`)\n .join('\\n');\n parts.push(`Open todo items:\\n${list}`);\n }\n parts.push(\n 'Predict the 1-3 most likely exact prompt messages the user could submit back to the agent through the TUI or WebUI. Each must ask the agent to perform the work, never assign a manual chore to the user.',\n );\n return parts.join('\\n\\n');\n}\n\n/**\n * Parse a numbered/bulleted list of predictions out of raw model text.\n * Pure + testable. Returns [] for the NONE sentinel or unparseable output.\n */\nexport function parsePredictions(raw: string, max = 3): string[] {\n const text = raw.trim();\n if (!text) return [];\n // Sentinel: the model says there's nothing meaningful left.\n if (/^none\\b/i.test(text) || /no further steps/i.test(text)) return [];\n\n const out: string[] = [];\n for (const lineRaw of text.split('\\n')) {\n const line = lineRaw.trim();\n if (!line) continue;\n // Strip a leading \"1.\", \"2)\", \"-\", \"*\", \"\u2022\" marker if present.\n const stripped = line.replace(/^\\s*(?:\\d+[.)]|[-*\u2022])\\s+/, '').trim();\n const candidate = stripped || line;\n // Skip a stray \"NONE\" that slipped into a list.\n if (/^none$/i.test(candidate)) continue;\n if (candidate) out.push(candidate);\n if (out.length >= max) break;\n }\n return out;\n}\n\nfunction extractText(content: unknown): string {\n if (Array.isArray(content)) {\n return (content[0] as { text?: string | undefined } | undefined)?.text ?? '';\n }\n if (content && typeof content === 'object') {\n return (content as { text?: string | undefined }).text ?? '';\n }\n return typeof content === 'string' ? content : '';\n}\n\n/**\n * Predict the user's likely next steps. Best-effort: any failure (timeout,\n * provider error, abort) resolves to `[]` so the caller can stay silent and\n * never let prediction break the turn.\n */\nexport async function predictNextTasks(\n input: PredictionInput,\n opts: PredictOpts,\n): Promise<string[]> {\n const max = opts.maxPredictions ?? 3;\n const internal = new AbortController();\n const timeout = setTimeout(() => internal.abort(), 12_000);\n const onParentAbort = () => internal.abort();\n if (opts.signal) {\n if (opts.signal.aborted) internal.abort();\n else opts.signal.addEventListener('abort', onParentAbort, { once: true });\n }\n try {\n const resp = await opts.provider.complete(\n {\n model: opts.model,\n system: [{ type: 'text', text: SYSTEM_PROMPT }],\n messages: [\n { role: 'user', content: [{ type: 'text', text: buildPredictionPrompt(input) }] },\n ],\n maxTokens: 160,\n temperature: 0.3,\n },\n { signal: internal.signal },\n );\n return parsePredictions(extractText(resp.content), max);\n } catch {\n return [];\n } finally {\n clearTimeout(timeout);\n if (opts.signal) opts.signal.removeEventListener('abort', onParentAbort);\n }\n}\n", "import { toErrorMessage } from '@wrongstack/core/utils';\nimport type { GoalFile } from '@wrongstack/core/goal';\nimport { color, estimateRequestTokensCalibrated, expectDefined, hasOpenTodos } from '@wrongstack/core/utils';\nimport { detectContinueIntent, InputBuilder, resolveContinuation } from '@wrongstack/core/agent';\nimport { goalFilePath, loadGoal, summarizeUsage } from '@wrongstack/core/goal';\nimport { readClipboardImage, routeImagesForModel } from '@wrongstack/runtime';\nimport { contextOverflowHint } from './context-overflow-diagnostic.js';\nimport { type PredictLLMProvider, predictNextTasks } from './next-task-predictor.js';\nimport {\n advanceToNextTask,\n autoDetectTaskCompletion,\n getActiveSDDContext,\n getActiveSDDPhase,\n getCurrentExecutingContext,\n getTaskListText,\n getTaskProgress,\n renderTaskListWithProgress,\n trySaveImplementationPlan,\n trySaveSpecFromAIOutput,\n trySaveTasksFromAIOutput,\n} from './services/sdd-runtime.js';\nimport { fmtTok } from './utils.js';\nimport { getSuggestions } from './services/suggestion-store.js';\nimport { parseSuggestionsFromOutput } from './repl-suggestions.js';\nimport { runAutoProceed } from './repl-auto-proceed.js';\nimport { readPossiblyMultiline } from './repl-input.js';\nimport { printBanner, renderContextChip } from './repl-rendering.js';\nimport { registerReplClient } from './repl-client-registration.js';\nimport type { ReplOptions } from './repl-options.js';\nimport { createAutoProceedLoopGuard } from '@wrongstack/tools/auto-proceed-loop-guard';\n\n/** Default ceiling on consecutive auto-proceed turns; 0 in settings means unlimited. */\nconst DEFAULT_MAX_CONSECUTIVE_AUTO_PROCEED = 50;\n\nexport { parseSuggestionsFromOutput, parseAutoSuggestionsFromOutput } from './repl-suggestions.js';\nexport type { ReplOptions } from './repl-options.js';\n\nexport async function runRepl(opts: ReplOptions): Promise<number> {\n if (opts.banner !== false) printBanner(opts.renderer, opts.projectName);\n // Surface active goal + crash-recovery hint under the banner.\n await renderGoalBanner(opts);\n\n // Per-iteration abort controller; refreshed before every agent.run.\n let activeCtrl: AbortController | undefined;\n let interrupts = 0;\n // Install the leader-abort handler for `/interrupt`; Ctrl+C is the mid-run path.\n if (opts.interruptController) {\n opts.interruptController.abortLeader = () => {\n if (activeCtrl) {\n activeCtrl.abort();\n return true;\n }\n return false;\n };\n }\n // Consecutive auto-proceed turns since the last manual input.\n let autoIterCount = 0;\n let autoCapWarned = false;\n // Repetition guard: when the same prompt is fed 2 times in a row, the\n // model is in a self-feeding loop. Manual input resets this too; the\n // 50-iteration cap above remains the runaway safety net for genuinely\n // novel prompts.\n const autoProceedLoopGuard = createAutoProceedLoopGuard();\n let exiting = false;\n const onSigint = () => {\n interrupts++;\n // Third (or later) press \u2014 the graceful exit itself is stuck; leave NOW.\n if (interrupts >= 3) {\n process.exit(130);\n }\n if (interrupts >= 2) {\n opts.renderer.writeWarning('Exiting.');\n exiting = true;\n // Abort whatever is still in flight so the read/run loop can observe\n // `exiting` and unwind gracefully\u2026\n activeCtrl?.abort();\n // \u2026and if it CAN'T (a run wedged past every abort layer), force the\n // process down after a short grace instead of letting \"Exiting.\" be\n // a lie. unref'd so a clean exit is never delayed by this timer.\n const hardExit = setTimeout(() => process.exit(130), 2_000);\n hardExit.unref?.();\n return;\n }\n // In eternal or parallel mode, the first Ctrl+C should stop the engine \u2014\n // aborting the in-flight agent.run and flipping autonomy back to 'off'\n // so the outer for-loop returns to reading user input on the next tick.\n if (opts.getAutonomy?.() === 'eternal' || opts.getAutonomy?.() === 'eternal-parallel') {\n opts.getEternalEngine?.()?.stop();\n opts.getParallelEngine?.()?.stop();\n opts.onAutonomy?.('off');\n opts.renderer.writeWarning('Engine stop requested. Press Ctrl+C again to exit.');\n interrupts = 0;\n return;\n }\n // A `/sdd parallel` run blocks the REPL prompt while it awaits completion, so\n // `/sdd stop` can never be typed mid-run \u2014 Ctrl+C is the only stop path. The\n // run has its own coordinator (not the autonomy engines above), so it is\n // unreachable from the generic activeCtrl branch; stop it explicitly here.\n // stop() aborts the in-flight workers; the run drains and the prompt returns.\n const sddRun = opts.getSddRun?.();\n if (sddRun?.isRunning()) {\n sddRun.stop();\n opts.renderer.writeWarning('SDD run stop requested. Press Ctrl+C again to exit.');\n interrupts = 0;\n return;\n }\n if (activeCtrl) {\n activeCtrl.abort();\n // Stop subagents too \u2014 \"interrupt\" means stop everything, not just the\n // leader. Without this the fleet keeps running on the old direction and\n // finishes minutes later. Matches the TUI's ESC-interrupt behavior.\n const killed = opts.onInterruptFleet?.() ?? 0;\n opts.renderer.writeWarning(\n killed > 0\n ? `Iteration cancelled \u00B7 stopped ${killed} subagent${killed === 1 ? '' : 's'}. Press Ctrl+C again to exit.`\n : 'Iteration cancelled. Press Ctrl+C again to exit.',\n );\n } else {\n opts.renderer.writeWarning('Press Ctrl+C again to exit.');\n }\n };\n process.on('SIGINT', onSigint);\n\n const replClientRegistration = registerReplClient(opts);\n\n const builder = new InputBuilder({ store: opts.attachments });\n\n // Wrap the entire loop so SIGINT and reader teardown run on every exit\n // path \u2014 exceptions, EOF, breakouts. Previously a throw between `on`\n // and the final `off` left the listener installed across REPL restarts.\n try {\n for (;;) {\n if (exiting) break;\n // \u2500\u2500 Eternal autonomy: drive the engine instead of reading input. \u2500\u2500\n // While autonomy mode is 'eternal' we own the REPL turn \u2014 the engine\n // generates its own directive and runs `agent.run` for us. Stop is\n // signaled by the engine flipping to 'stopped' (via /autonomy stop or\n // SIGINT). On exit from this branch the for-loop continues normally\n // and the next iteration reads user input again.\n if (opts.getAutonomy?.() === 'eternal') {\n const engine = opts.getEternalEngine?.();\n if (!engine) {\n opts.renderer.writeWarning('Eternal mode set but no engine wired \u2014 falling back to off.');\n // Best-effort: nothing more to do here; the engine controller\n // was supposed to be primed by /autonomy eternal.\n } else {\n // Snapshot iteration counter before/after so the log line tells\n // the user where they are in the goal lifetime \u2014 useful when\n // the loop runs for hours and the journal scrolls off screen.\n const beforeGoal = await loadGoalSafe(opts);\n const beforeIter = beforeGoal?.iterations ?? 0;\n opts.renderer.write(color.dim(`\\n \u21B3 [eternal #${beforeIter + 1}] running iteration\u2026\\n`));\n interrupts = 0;\n try {\n const ok = await engine.runOneIteration();\n const afterGoal = await loadGoalSafe(opts);\n const last = afterGoal?.journal[afterGoal.journal.length - 1];\n if (!ok && !last) {\n opts.renderer.write(color.dim(' \u21B3 [eternal] iteration produced no progress.\\n'));\n } else if (last) {\n const mark =\n last.status === 'success'\n ? color.green('\u2713')\n : last.status === 'failure'\n ? color.red('\u2717')\n : color.amber('\u2298');\n const tail = last.note ? color.dim(` \u2014 ${last.note.slice(0, 80)}`) : '';\n opts.renderer.write(\n ` ${mark} ${color.dim(`#${last.iteration}`)} ${color.dim(`[${last.source}]`)} ${last.task}${tail}\\n`,\n );\n }\n // Check if the engine stopped because the goal completed.\n // The engine calls onEternalStop internally, which calls stop(),\n // but the REPL needs to flip autonomy mode so the loop exits\n // eternal mode and returns to reading user input.\n if (engine.currentState === 'stopped') {\n const goal = await loadGoalSafe(opts);\n if (goal?.goalState === 'completed') {\n const u = goal.journal.length > 0 ? summarizeUsage(goal) : null;\n const costLine =\n u && u.iterationsWithUsage > 0\n ? color.dim(\n ` \u2014 ${u.totalCostUsd.toFixed(4)} \u00B7 ${u.totalInputTokens} in / ${u.totalOutputTokens} out \u00B7 ${goal.iterations} iterations`,\n )\n : goal.iterations > 0\n ? color.dim(` \u2014 ${goal.iterations} iterations`)\n : '';\n opts.renderer.write(\n color.green(`\\n \uD83C\uDFAF Goal completed!${costLine}\\n\\n`) +\n color.dim(' Goal cleared. Use /goal set <mission> to create a new goal.\\n'),\n );\n // Auto-clear the goal file so the completed goal doesn't\n // linger across restarts. The goal's journal is already\n // in the session log.\n if (opts.projectRoot) {\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(goalFilePath(opts.projectRoot));\n } catch {\n // best-effort \u2014 file may already be gone\n }\n }\n }\n opts.onAutonomy?.('auto');\n continue;\n }\n } catch (err) {\n opts.renderer.writeError(\n `[eternal] ${toErrorMessage(err)}`,\n );\n }\n // Yield to the event loop so a SIGINT delivered during this\n // iteration can be processed before the next one fires.\n await new Promise((resolve) => setTimeout(resolve, 250));\n continue;\n }\n } else if (opts.getAutonomy?.() === 'eternal-parallel') {\n const engine = opts.getParallelEngine?.();\n if (!engine) {\n opts.renderer.writeWarning(\n 'Parallel mode set but no engine wired \u2014 falling back to off.',\n );\n } else {\n const beforeGoal = await loadGoalSafe(opts);\n const beforeIter = beforeGoal?.iterations ?? 0;\n\n // Show subagent stats before launching\n const coord = engine.getCoordinator();\n if (coord) {\n const stats = coord.getStats();\n opts.renderer.write(\n color.dim(\n ` \u250C\u2500 Fleet: ${stats.running} running, ${stats.idle} idle, ${stats.pending} pending, ${stats.completed} done`,\n ) + '\\n',\n );\n }\n\n opts.renderer.write(\n color.magenta(` \u21B3 [parallel #${beforeIter + 1}] launching fan-out\u2026\\n`),\n );\n interrupts = 0;\n try {\n await engine.runOneIteration();\n const afterGoal = await loadGoalSafe(opts);\n const last = afterGoal?.journal[afterGoal.journal.length - 1];\n\n // Show results with subagent stats\n if (coord) {\n const stats = coord.getStats();\n opts.renderer.write(\n color.dim(\n ` \u2514\u2500 Fleet: ${stats.running} running, ${stats.idle} idle, ${stats.completed} done\\n`,\n ),\n );\n }\n\n if (last) {\n const mark =\n last.status === 'success'\n ? color.green('\u2713')\n : last.status === 'failure'\n ? color.red('\u2717')\n : color.amber('\u2298');\n const tail = last.note ? color.dim(` \u2014 ${last.note.slice(0, 80)}`) : '';\n opts.renderer.write(\n ` ${mark} ${color.dim(`#${last.iteration}`)} ${color.dim(`[${last.source}]`)} ${last.task}${tail}\\n`,\n );\n }\n // Exit parallel mode if the engine stopped (goal completed or user stopped).\n if (engine.currentState === 'stopped') {\n const goal = await loadGoalSafe(opts);\n if (goal?.goalState === 'completed') {\n const u = goal.journal.length > 0 ? summarizeUsage(goal) : null;\n const costLine =\n u && u.iterationsWithUsage > 0\n ? color.dim(\n ` \u2014 ${u.totalCostUsd.toFixed(4)} \u00B7 ${u.totalInputTokens} in / ${u.totalOutputTokens} out \u00B7 ${goal.iterations} iterations`,\n )\n : goal.iterations > 0\n ? color.dim(` \u2014 ${goal.iterations} iterations`)\n : '';\n opts.renderer.write(\n color.green(`\\n \uD83C\uDFAF Goal completed!${costLine}\\n\\n`) +\n color.dim(' Goal cleared. Use /goal set <mission> to create a new goal.\\n'),\n );\n // Auto-clear the goal file so the completed goal doesn't\n // linger across restarts. The goal's journal is already\n // in the session log.\n if (opts.projectRoot) {\n try {\n const { unlink } = await import('node:fs/promises');\n await unlink(goalFilePath(opts.projectRoot));\n } catch {\n // best-effort \u2014 file may already be gone\n }\n }\n }\n opts.onAutonomy?.('auto');\n continue;\n }\n } catch (err) {\n opts.renderer.writeError(\n `[parallel] ${toErrorMessage(err)}`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, 250));\n continue;\n }\n }\n\n // \u2500\u2500 Auto-proceed / suggest: autonomy-driven next-step flow \u2500\u2500\n // After every agent turn, suggestions are parsed and stored in\n // currentSuggestions via onSuggestionsParsed. Here at the top of\n // the loop (before reading user input) we check the autonomy mode:\n //\n // 'auto' \u2014 brief cooldown (runs compaction), then auto-feed\n // suggestion#1. No validation gate, no hard cap.\n // 'suggest' \u2014 display suggestions prominently, wait for user input\n //\n // Both modes stop when suggestions are exhausted. Ctrl+C interrupts\n // the cooldown (reuses the existing activeCtrl SIGINT pattern).\n {\n const mode = opts.getAutonomy?.() ?? 'off';\n const suggestions = opts.getSuggestions?.() ?? [];\n\n // \u2500\u2500 'suggest' mode: display-only \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (mode === 'suggest' && suggestions.length > 0) {\n const lines = suggestions.map((s, i) => ` ${color.bold(`${i + 1}.`)} ${color.dim(s)}`);\n opts.renderer.write(\n `\\n${color.cyan(' \uD83D\uDCA1 Suggested next steps')} ${color.dim('(use /next 1, /next 2, or /next 1 2 3)')}\\n${lines.join('\\n')}\\n\\n`,\n );\n }\n\n // \u2500\u2500 'auto' mode: brief cooldown \u2192 feed directly \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (mode === 'auto') {\n // Resolve the next auto-feed target: first from suggestions, then\n // from open todos (suggestions are suppressed while todos are\n // pending \u2014 see parseSuggestionsFromOutput \u2014 so skipping to todos\n // prevents the session from idling after a turn with no nextsteps).\n let top: string;\n let groundedTodo = false;\n if (suggestions.length > 0) {\n const isYolo = opts.getYolo?.() ?? false;\n const autoSuggestions = opts.getAutoSuggestions?.() ?? [];\n const useAutoSuggestions = isYolo && autoSuggestions.length > 0;\n top = useAutoSuggestions ? autoSuggestions[0] ?? '' : suggestions[0] ?? '';\n } else {\n const todos = opts.agent.ctx.todos ?? [];\n const resolved = resolveContinuation({ todos, suggestions: [] });\n top = resolved.source === 'todo' ? resolved.text : '';\n groundedTodo = top !== '';\n }\n\n if (!top) {\n // Fall through to the input read below \u2014 nothing to auto-feed.\n } else {\n // The cap pauses the loop but NEVER flips autonomy off \u2014 the mode\n // is the user's setting; only the user changes it.\n const maxAuto = opts.autoProceedMaxIterations ?? DEFAULT_MAX_CONSECUTIVE_AUTO_PROCEED;\n if (maxAuto > 0 && autoIterCount >= maxAuto) {\n if (!autoCapWarned) {\n autoCapWarned = true;\n opts.renderer.writeWarning(\n `Auto-proceed paused after ${maxAuto} consecutive automatic turns \u2014 ` +\n 'enter input to continue (resets the counter). Autonomy stays on.',\n );\n }\n // Fall through to the input read below instead of looping.\n } else {\n const delay = opts.autoProceedDelayMs ?? 1_000;\n const ctrl = new AbortController();\n activeCtrl = ctrl;\n try {\n // For YOLO+auto, apply the autonomy_next prompt template.\n const isYolo = opts.getYolo?.() ?? false;\n const autoSuggestions = opts.getAutoSuggestions?.() ?? [];\n const useAutoSuggestions = isYolo && autoSuggestions.length > 0;\n const promptToFeed = useAutoSuggestions && opts.autonomyNextPrompt\n ? opts.autonomyNextPrompt.replace('{{suggestion}}', top)\n : top;\n const submitted = await runAutoProceed(\n opts,\n promptToFeed,\n delay,\n ctrl,\n autoProceedLoopGuard,\n groundedTodo,\n );\n if (submitted) {\n autoIterCount++;\n continue;\n }\n } finally {\n activeCtrl = undefined;\n }\n // Countdown cancellation, autonomy changes, and repetition\n // halts all return control to manual input.\n }\n }\n }\n }\n\n let raw: string;\n try {\n raw = await readPossiblyMultiline(opts);\n } catch {\n break; // EOF (Ctrl+D)\n }\n const trimmed = raw.trim();\n if (!trimmed) {\n interrupts = 0;\n continue;\n }\n interrupts = 0;\n // Manual input re-arms auto-proceed.\n autoIterCount = 0;\n autoCapWarned = false;\n autoProceedLoopGuard.reset();\n\n // Plain `q` quits immediately without needing a slash.\n if (trimmed === 'q') {\n opts.renderer.write(color.dim(' Goodbye!\\n'));\n break;\n }\n\n // `cd` and `wd` shortcuts \u2192 dispatch to /working_dir\n if (trimmed === 'wd' || trimmed.startsWith('cd ')) {\n const args = trimmed.startsWith('cd ') ? trimmed.slice(3).trim() : '';\n try {\n const res = await opts.slashRegistry.dispatch(`/working_dir ${args}`, opts.agent.ctx);\n if (res?.message) opts.renderer.write(`${res.message}\\n`);\n } catch (err) {\n opts.renderer.writeError(toErrorMessage(err));\n }\n continue;\n }\n\n if (trimmed === '/image' || trimmed === '/paste-image' || raw === '\\x1bv') {\n await pasteClipboardImage(builder, opts);\n continue;\n }\n\n if (trimmed.startsWith('/')) {\n try {\n const res = await opts.slashRegistry.dispatch(trimmed, opts.agent.ctx);\n if (res?.message) opts.renderer.write(`${res.message}\\n`);\n if (res?.exit) break;\n\n // \u2500\u2500 runText: Auto-trigger AI after slash command \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When a slash command returns runText (e.g. /sdd new, /sdd approve),\n // automatically send it to the AI agent so the conversation continues\n // without the user having to type anything extra.\n if (res?.runText) {\n const runBlocks = [{ type: 'text' as const, text: res.runText }];\n const runCtrl = new AbortController();\n activeCtrl = runCtrl;\n try {\n const runResult = await opts.agent.run(runBlocks, { signal: runCtrl.signal });\n opts.onAgentIterationComplete?.(\n estimateRequestTokensCalibrated(\n opts.agent.ctx.messages,\n opts.agent.ctx.systemPrompt,\n opts.agent.ctx.tools ?? [],\n ).total,\n );\n if (runResult.status === 'done' && runResult.finalText) {\n // SDD auto-detection: spec, implementation plan, tasks\n const specSaved = await trySaveSpecFromAIOutput(runResult.finalText);\n if (specSaved) {\n opts.renderer.write(\n `\\n${color.cyan(' \u2713 Spec detected and saved! Use /sdd approve to continue.')}\\n`,\n );\n }\n const planSaved = trySaveImplementationPlan(runResult.finalText);\n if (planSaved) {\n opts.renderer.write(`\\n${color.cyan(' \u2713 Implementation plan saved!')}\\n`);\n }\n const tasksSaved = await trySaveTasksFromAIOutput(runResult.finalText);\n if (tasksSaved) {\n const progress = getTaskProgress();\n const count = progress?.total ?? 0;\n opts.renderer.write(\n `\\n${color.cyan(` \u2713 ${count} tasks detected and saved! Use /sdd approve to execute.`)}\\n`,\n );\n }\n // Auto-detect task completion during execution phase\n const sddPhase = getActiveSDDPhase();\n if (sddPhase === 'executing') {\n const autoCompleted = autoDetectTaskCompletion(runResult.finalText);\n if (autoCompleted > 0) {\n const progress = getTaskProgress();\n if (progress) {\n opts.renderer.write(\n `\\n${color.cyan(` \u2713 ${autoCompleted} task(s) auto-completed! Progress: ${progress.completed}/${progress.total} (${progress.percentComplete}%)`)}\\n`,\n );\n // Show live task list after auto-completion\n const taskList = renderTaskListWithProgress();\n if (taskList) {\n opts.renderer.write(`\\n${color.dim(taskList)}\\n`);\n }\n }\n } else {\n // Still show task list even if nothing was auto-completed\n const taskList = renderTaskListWithProgress();\n if (taskList) {\n opts.renderer.write(`\\n${color.dim(taskList)}\\n`);\n }\n }\n }\n\n // \u2500\u2500 Suggestion auto-parsing (from runText-triggered turn) \u2500\u2500\n // When a slash command like /next triggers an agent turn,\n // parse \"\uD83D\uDCA1 Next steps\" from the agent's output so\n // subsequent /next 1 calls use the latest suggestions,\n // not stale ones from a prior /suggest. The live todo\n // list is passed through so we suppress <nextsteps> while\n // the in-flight todo loop is still in progress.\n if (opts.onSuggestionsParsed) {\n const parsed = parseSuggestionsFromOutput(\n runResult.finalText,\n opts.agent.ctx.todos,\n );\n opts.onSuggestionsParsed(parsed);\n }\n }\n } catch (_runErr) {\n // Non-fatal \u2014 user can continue manually\n opts.renderer.writeWarning('AI auto-trigger failed. You can continue manually.');\n }\n }\n } catch (err) {\n opts.renderer.writeError(toErrorMessage(err));\n }\n continue;\n }\n\n // \u2500\u2500 Bare \"continue\" \u2192 resolve against live plan state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // A lone \"continue\" / \"devam\" / \"go on\" carries no instruction. Resolve\n // it against what we already track \u2014 the next open todo, else the top\n // stored suggestion, else an open continuation that keeps the agent\n // working without fabricating busywork \u2014 and inject that concrete text\n // in place of the bare word. Skips paste collapsing (the injected text\n // is prose, not a paste).\n if (detectContinueIntent(trimmed)) {\n const resolved = resolveContinuation({\n todos: opts.agent.ctx.todos,\n suggestions: getSuggestions(),\n });\n // Make the resolution \u2014 and its drift risk \u2014 visible instead of\n // silently guessing. A grounded resolution (todo/suggestion) prints\n // its target and proceeds; the `open` guess warns that \"continue\" has\n // no anchor and asks before letting the model pick a step itself.\n if (resolved.source === 'open') {\n opts.renderer.write(\n ` ${color.amber('\u26A0')} ${color.bold(\"'continue' has no anchor\")} ${color.dim('\u2014 no pending todo or suggestion.')}\\n` +\n color.dim(\" If you proceed, I'll choose the next step from context; that can drift.\\n\"),\n );\n const ans = (\n await opts.reader.readLine(color.dim(' Proceed anyway? [Y/n \u00B7 e = type your own] '))\n )\n .trim()\n .toLowerCase();\n if (ans === 'n' || ans === 'no') {\n opts.renderer.write(color.dim(' Cancelled \u2014 nothing sent.\\n'));\n continue;\n }\n if (ans === 'e' || ans === 'edit') {\n opts.renderer.write(color.dim(' Okay \u2014 type what to continue with.\\n'));\n continue;\n }\n } else {\n opts.renderer.write(color.dim(` ${resolved.label}\\n`));\n }\n builder.appendText(resolved.text);\n } else {\n // Route through InputBuilder so big pastes collapse to placeholders.\n const ph = await builder.appendPaste(raw);\n if (ph) {\n const lineCount = raw.split('\\n').length;\n opts.renderer.write(color.dim(` \u21B3 ${ph} (${lineCount} lines)\\n`));\n }\n }\n const blocks = await builder.submit();\n\n // \u2500\u2500 SDD Session Integration \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When an SDD session is active, inject the session context so the AI\n // knows to ask questions, generate specs, etc.\n const sddContext = getActiveSDDContext();\n const taskList = getTaskListText();\n const taskProgress = getTaskProgress();\n const sddPhase = getActiveSDDPhase();\n\n let sddPrefix = '';\n if (sddContext) {\n sddPrefix = `[SDD SESSION ACTIVE]\\n${sddContext}`;\n // During executing phase: tell AI exactly which task it's working on\n if (sddPhase === 'executing') {\n const currentCtx = getCurrentExecutingContext();\n if (currentCtx) {\n sddPrefix += `\\n\\n${currentCtx}`;\n }\n }\n if (taskList) {\n sddPrefix += `\\n\\n**Current Task List:**\\n${taskList}`;\n }\n if (taskProgress && taskProgress.total > 0) {\n sddPrefix += `\\n**Progress:** ${taskProgress.completed}/${taskProgress.total} (${taskProgress.percentComplete}%)`;\n }\n if (sddPhase === 'executing' && taskProgress && taskProgress.percentComplete === 100) {\n sddPrefix += '\\n\\n**All tasks completed! Provide a summary of everything implemented.**';\n }\n sddPrefix += '\\n\\n---\\nUser message:\\n';\n }\n\n const effectiveBlocks = sddPrefix\n ? [{ type: 'text' as const, text: sddPrefix }, ...blocks]\n : blocks;\n\n const runCtrl = new AbortController();\n activeCtrl = runCtrl;\n try {\n const startedAt = Date.now();\n const before = opts.tokenCounter?.total();\n const costBefore = opts.tokenCounter?.estimateCost().total ?? 0;\n const routed = effectiveBlocks.some((block) => block.type === 'image')\n ? await routeImagesForModel(effectiveBlocks, {\n supportsVision: opts.supportsVision\n ? await opts.supportsVision()\n : opts.agent.ctx.provider.capabilities.vision,\n adapters: opts.visionAdapters ?? [],\n ctx: opts.agent.ctx,\n signal: runCtrl.signal,\n providerId: opts.agent.ctx.provider.id,\n model: opts.agent.ctx.model,\n })\n : { blocks: effectiveBlocks, route: 'none' as const, convertedImages: 0 };\n if (routed.route === 'adapter') {\n opts.renderer.write(\n color.dim(\n ` \u21B3 image analyzed via ${routed.adapterName ?? 'vision adapter'} (${routed.convertedImages} image${routed.convertedImages === 1 ? '' : 's'})\\n`,\n ),\n );\n }\n const result = await opts.agent.run(routed.blocks, { signal: runCtrl.signal });\n // Report context pressure to the Director (for spawn pre-checks) and\n // update the calibration state so the next estimate is more accurate.\n opts.onAgentIterationComplete?.(\n estimateRequestTokensCalibrated(\n opts.agent.ctx.messages,\n opts.agent.ctx.systemPrompt,\n opts.agent.ctx.tools ?? [],\n ).total,\n );\n if (result.status === 'aborted') {\n opts.renderer.writeWarning('Aborted.');\n } else if (result.status === 'failed') {\n const err = result.error;\n if (err) {\n const tag = err.recoverable ? ' (recoverable)' : '';\n opts.renderer.writeError(`Failed [${err.severity}]${tag}: ${err.describe()}`);\n const hint = contextOverflowHint(err);\n if (hint) opts.renderer.writeWarning(hint);\n } else {\n opts.renderer.writeError('Failed.');\n }\n } else if (result.status === 'max_iterations') {\n opts.renderer.writeWarning(`Hit max iterations (${result.iterations}).`);\n }\n\n // \u2500\u2500 SDD Auto-Detection \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // When an SDD session is active, auto-detect spec and task JSON\n // in the AI output and save them to the session.\n if (result.status === 'done' && result.finalText && sddContext) {\n // Try to detect and save a spec\n const specSaved = await trySaveSpecFromAIOutput(result.finalText);\n if (specSaved) {\n opts.renderer.write(\n `\\n${color.cyan(' \u2713 Spec detected and saved! Use /sdd approve to continue.')}\\n`,\n );\n }\n\n // Try to save implementation plan (text before task JSON)\n const planSaved = trySaveImplementationPlan(result.finalText);\n if (planSaved) {\n opts.renderer.write(`\\n${color.cyan(' \u2713 Implementation plan saved!')}\\n`);\n }\n\n // Try to detect and save tasks\n const tasksSaved = await trySaveTasksFromAIOutput(result.finalText);\n if (tasksSaved) {\n const progress = getTaskProgress();\n const count = progress?.total ?? 0;\n opts.renderer.write(\n `\\n${color.cyan(` \u2713 ${count} tasks detected and saved! Use /sdd approve to execute.`)}\\n`,\n );\n }\n\n // Auto-detect task completion during execution phase\n const phase = getActiveSDDPhase();\n if (phase === 'executing') {\n const autoCompleted = autoDetectTaskCompletion(result.finalText);\n if (autoCompleted > 0) {\n const progress = getTaskProgress();\n if (progress) {\n opts.renderer.write(\n `\\n${color.cyan(` \u2713 ${autoCompleted} task(s) auto-completed! Progress: ${progress.completed}/${progress.total} (${progress.percentComplete}%)`)}\\n`,\n );\n if (progress.percentComplete === 100) {\n opts.renderer.write(\n `\\n${color.green(' \uD83C\uDF89 All tasks completed! Use /sdd cancel to end the session.')}\\n`,\n );\n }\n }\n // Auto-advance: set the next ready task to in_progress\n advanceToNextTask();\n // Show updated task list after auto-advance\n const taskList = renderTaskListWithProgress();\n if (taskList) {\n opts.renderer.write(`\\n${color.dim(taskList)}\\n`);\n }\n } else {\n // Still show task list even if nothing was auto-completed\n const taskList = renderTaskListWithProgress();\n if (taskList) {\n opts.renderer.write(`\\n${color.dim(taskList)}\\n`);\n }\n }\n }\n }\n\n // \u2500\u2500 Suggestion auto-parsing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Extract \"\uD83D\uDCA1 Next steps\" from the agent's final output and store\n // them so the user can select with /next 1, /next 1 2 3. The live\n // todo list is passed through so we suppress <nextsteps> while\n // the in-flight todo loop is still in progress \u2014 finishing the\n // open todos comes before offering new prompt options.\n if (result.status === 'done' && result.finalText && opts.onSuggestionsParsed) {\n const parsed = parseSuggestionsFromOutput(result.finalText, opts.agent.ctx.todos);\n opts.onSuggestionsParsed(parsed);\n }\n\n if (opts.tokenCounter && before) {\n const after = opts.tokenCounter.total();\n const costAfter = opts.tokenCounter.estimateCost().total;\n const effectiveMaxContext =\n opts.getEffectiveMaxContext?.() ?? opts.effectiveMaxContext;\n const ctxChip =\n effectiveMaxContext && effectiveMaxContext > 0\n ? ` ctx: ${renderContextChip(after.input, effectiveMaxContext)}`\n : '';\n opts.renderer.write(\n `\\n${color.dim(\n `[in: ${fmtTok(after.input - before.input)} out: ${fmtTok(after.output - before.output)} iters: ${result.iterations} cost: ${(costAfter - costBefore).toFixed(4)} ${((Date.now() - startedAt) / 1000).toFixed(1)}s]${ctxChip}`,\n )}\\n`,\n );\n }\n\n // Suggest mode asks for explicit next-step options after a successful\n // turn. Auto mode is driven exclusively by the guarded queue at the\n // top of the REPL loop; issuing another agent.run() here would bypass\n // suggestion consumption and the repetition guard.\n if (result.status === 'done' && opts.getAutonomy) {\n const autonomy = opts.getAutonomy();\n if (autonomy === 'suggest' && !hasOpenTodos(opts.agent.ctx.todos)) {\n // Suggest mode: ask the agent what to do next, show to user.\n const suggestPrompt =\n 'Based on what you just did, suggest 3 exact prompt messages that can be submitted back to you through the TUI or WebUI. Each prompt must ask the agent to perform work; never assign a manual chore to the user. ' +\n 'If you include suggestions, wrap them in a balanced <nextsteps>...</nextsteps> block, ' +\n 'with one numbered prompt per line and no explanation. ' +\n 'If there is nothing meaningful left, say \"No further steps needed.\"';\n const suggestBlocks = [{ type: 'text' as const, text: suggestPrompt }];\n const suggestCtrl = new AbortController();\n activeCtrl = suggestCtrl;\n try {\n const suggestResult = await opts.agent.run(suggestBlocks, {\n signal: suggestCtrl.signal,\n });\n opts.onAgentIterationComplete?.(\n estimateRequestTokensCalibrated(\n opts.agent.ctx.messages,\n opts.agent.ctx.systemPrompt,\n opts.agent.ctx.tools ?? [],\n ).total,\n );\n if (suggestResult.status === 'done' && suggestResult.finalText) {\n opts.renderer.write(\n `\\n${color.cyan(' Suggested next steps:')}\\n${suggestResult.finalText}\\n`,\n );\n // Parse and store the autonomy-generated suggestions too\n if (opts.onSuggestionsParsed) {\n const parsed = parseSuggestionsFromOutput(\n suggestResult.finalText,\n opts.agent.ctx.todos,\n );\n opts.onSuggestionsParsed(parsed);\n }\n }\n } catch {\n // Silently skip suggestion errors\n } finally {\n activeCtrl = undefined;\n }\n }\n }\n\n // \u2500\u2500 Next-task prediction (/next) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Opt-in: after a completed turn, a cheap single-shot LLM call\n // guesses the user's likely next steps and shows them dimly.\n // Display-only \u2014 never executed. Only runs when autonomy is off\n // (auto/suggest/eternal already drive or print their own next\n // steps). Best-effort: any failure is swallowed so prediction can\n // never break the turn.\n //\n // Skipped while a todo list is in flight: the next step is the\n // next todo, not a /next prediction. A second \"likely next\"\n // line under the in-flight todo list would be noise.\n if (\n result.status === 'done' &&\n opts.getNextPredict?.() &&\n !hasOpenTodos(opts.agent.ctx.todos)\n ) {\n const autonomy = opts.getAutonomy?.() ?? 'off';\n if (autonomy === 'off') {\n const predictCtrl = new AbortController();\n activeCtrl = predictCtrl;\n try {\n const predictions = await predictNextTasks(\n {\n userRequest: trimmed,\n assistantSummary: result.finalText ?? '',\n todos: opts.agent.ctx.todos,\n },\n {\n provider: opts.agent.ctx.provider as never as PredictLLMProvider,\n model: opts.agent.ctx.model,\n signal: predictCtrl.signal,\n },\n );\n if (predictions.length > 0) {\n const lines = predictions.map((p, i) => ` ${i + 1}. ${p}`).join('\\n');\n opts.renderer.write(`\\n${color.dim(' \u21B3 likely next:')}\\n${color.dim(lines)}\\n`);\n }\n } catch {\n // Best-effort \u2014 never let prediction break the turn.\n } finally {\n activeCtrl = undefined;\n }\n }\n }\n } catch (err) {\n opts.renderer.writeError(toErrorMessage(err));\n } finally {\n activeCtrl = undefined;\n }\n }\n\n return 0;\n } finally {\n // Ensure listener + reader cleanup happens on every exit path: normal\n // EOF, /quit, an uncaught throw, etc. Without this, a thrown exception\n // mid-loop would leave the SIGINT handler attached for the rest of\n // the process lifetime (and the reader's terminal handle open).\n process.off('SIGINT', onSigint);\n await opts.reader.close().catch(() => {\n /* best-effort */\n });\n replClientRegistration.close();\n // Run user-provided cleanup (e.g., SessionStats event listener removal).\n opts.onDestroy?.();\n }\n}\n\nasync function pasteClipboardImage(builder: InputBuilder, opts: ReplOptions): Promise<void> {\n try {\n const img = await readClipboardImage();\n if (!img) {\n opts.renderer.write(color.dim(' no image on clipboard\\n'));\n return;\n }\n const placeholder = await builder.appendImage(img.base64, img.mediaType);\n const kb = (img.bytes / 1024).toFixed(0);\n opts.renderer.write(color.dim(` \u21B3 ${placeholder} (PNG ${kb}KB)\\n`));\n } catch (err) {\n opts.renderer.writeError(\n `Clipboard image error: ${toErrorMessage(err)}`,\n );\n }\n}\n\n/**\n * Read the persisted goal file safely. Returns null on any error so the\n * REPL never crashes because /goal infrastructure is missing.\n */\nasync function loadGoalSafe(opts: ReplOptions): Promise<GoalFile | null> {\n if (!opts.projectRoot) return null;\n try {\n return await loadGoal(goalFilePath(opts.projectRoot));\n } catch {\n return null;\n }\n}\n\n/**\n * Print a one-line status banner about the active goal \u2014 only when a\n * goal file exists. If the previous session left the engine in 'running'\n * state, prompt the user (y/N) to resume eternal mode directly so they\n * don't have to retype the slash command. Default is N (safe path) \u2014 a\n * stray Enter after an unexpected crash shouldn't auto-burn tokens.\n */\nasync function renderGoalBanner(opts: ReplOptions): Promise<void> {\n const goal = await loadGoalSafe(opts);\n if (!goal) return;\n\n const summary = goal.goal.length > 80 ? `${goal.goal.slice(0, 77)}\u2026` : goal.goal;\n\n // Color based on goalState\n const stateColor =\n goal.goalState === 'active'\n ? color.green\n : goal.goalState === 'paused'\n ? color.amber\n : goal.goalState === 'completed'\n ? color.green\n : goal.goalState === 'abandoned'\n ? color.dim\n : color.dim;\n\n opts.renderer.write(\n color.dim('Goal: ') +\n stateColor(summary) +\n color.dim(` [${goal.goalState}] (iter ${goal.iterations})`) +\n '\\n',\n );\n\n // Show journal summary if there are recent entries\n if (goal.journal.length > 0) {\n const lastEntry = expectDefined(goal.journal[goal.journal.length - 1]);\n const statusIcon =\n lastEntry.status === 'success'\n ? '\u2713'\n : lastEntry.status === 'failure'\n ? '\u2717'\n : lastEntry.status === 'aborted'\n ? '\u2298'\n : lastEntry.status === 'skipped'\n ? '\u229D'\n : '\u00B7';\n opts.renderer.write(\n color.dim(` Last: ${statusIcon} ${lastEntry.task} (${lastEntry.status})`) + '\\n',\n );\n }\n\n if (goal.engineState === 'running') {\n opts.renderer.write(\n color.amber(' \u21BA Eternal engine was running when last session ended.') + '\\n',\n );\n // Try an interactive y/N prompt. If reader is unavailable or throws\n // (non-TTY, redirected stdin, etc.) fall back to the static hint.\n try {\n const answer = (await opts.reader.readLine(color.dim(' Resume eternal mode? [y/N] ')))\n .trim()\n .toLowerCase();\n if (answer === 'y' || answer === 'yes') {\n // Dispatch /autonomy eternal as if the user typed it. Routes\n // through the normal slash path so YOLO force-on, prime(), banner\n // semantics all kick in consistently.\n try {\n await opts.slashRegistry.dispatch('/autonomy eternal', opts.agent.ctx);\n } catch (err) {\n opts.renderer.writeError(\n `Auto-resume failed: ${toErrorMessage(err)}`,\n );\n }\n } else {\n opts.renderer.write(\n color.dim(' Not resuming. Use `/autonomy eternal` later to continue.') + '\\n',\n );\n }\n } catch {\n // Non-interactive path: just hint.\n opts.renderer.write(color.dim(' Use `/autonomy eternal` to resume.') + '\\n');\n }\n } else if (goal.goalState === 'paused') {\n // Paused goal - prompt to resume\n opts.renderer.write(color.amber(' \u23F8 Goal is paused. Use `/goal resume` to continue.') + '\\n');\n } else if (goal.goalState === 'completed') {\n opts.renderer.write(\n color.green(' \u2713 Goal completed! Use `/goal clear` to set a new goal.') + '\\n',\n );\n } else if (goal.goalState === 'abandoned') {\n opts.renderer.write(color.dim(' Use `/goal clear` to set a new goal.') + '\\n');\n }\n opts.renderer.write('\\n');\n}\n", "import type { TodoItem } from '@wrongstack/core/agent';\nimport { hasOpenTodos } from '@wrongstack/core/utils';\nimport { parseNextSteps } from '@wrongstack/tools/next-steps';\nimport { setAutoSuggestions } from './services/suggestion-store.js';\n\n/**\n * Extract canonical \"<nextsteps>\" suggestions from the agent's final output.\n * Loose \"Next steps\" prose is intentionally ignored; `/next` requires the tagged block.\n * Returns null when no suggestions are found.\n *\n * Gated on the live todo list: when the agent still has open todos\n * (`pending` or `in_progress`), we suppress `<nextsteps>` entirely and clear\n * the auto-suggestion store. Surfacing suggestions mid-task would race the\n * todo loop \u2014 YOLO+auto could pick the top suggestion and pivot away from\n * the unfinished work, and `/next 1` would replace the next todo with an\n * arbitrary prompt. Finishing the todo list comes first; suggestions re-arm\n * on the next turn once everything is `completed`.\n */\nexport function parseSuggestionsFromOutput(\n finalText: string,\n todos?: readonly TodoItem[] | null,\n): string[] | null {\n if (hasOpenTodos(todos)) {\n // Clear auto-suggestion store too; stale auto=\"true\" items would otherwise\n // survive into the next turn after regular suggestions were suppressed.\n setAutoSuggestions([]);\n return null;\n }\n const { texts, autoTexts } = parseNextSteps(finalText, false);\n if (autoTexts.length > 0) {\n setAutoSuggestions(autoTexts);\n }\n return texts.length > 0 ? texts : null;\n}\n\n/**\n * Extract only the auto=\"true\" items from next_steps output.\n * Used by YOLO+auto autonomy mode.\n */\nexport function parseAutoSuggestionsFromOutput(finalText: string): string[] | null {\n const { autoTexts } = parseNextSteps(finalText, false);\n return autoTexts.length > 0 ? autoTexts : null;\n}\n", "import { color, estimateRequestTokensCalibrated } from '@wrongstack/core/utils';\nimport { GROUNDED_NO_PROGRESS_STEER, type AutoProceedLoopGuard } from '@wrongstack/tools/auto-proceed-loop-guard';\nimport { setAutoSuggestions, setSuggestions } from './services/suggestion-store.js';\nimport { parseSuggestionsFromOutput } from './repl-suggestions.js';\nimport type { ReplOptions } from './repl-options.js';\n\n/**\n * Run the full auto-proceed cycle: countdown, feed suggestion to agent,\n * parse new suggestions from the response. Returns normally when the\n * agent turn completes, throws on abort (Ctrl+C).\n *\n * The caller must set `activeCtrl` before calling and clear it after.\n */\nexport async function runAutoProceed(\n opts: ReplOptions,\n suggestion: string,\n delayMs: number,\n ctrl: AbortController,\n loopGuard: AutoProceedLoopGuard,\n /**\n * True when `suggestion` was synthesized from the durable todo board rather\n * than parsed from model output. Grounded prompts go through the guard's\n * steer-then-halt path: the first identical re-feed appends an explicit\n * \"the board has not moved \u2014 update it\" note instead of halting, and the\n * halt only fires if the board stays frozen after that steer.\n */\n grounded = false,\n): Promise<boolean> {\n const truncated = suggestion.length > 80 ? `${suggestion.slice(0, 77)}\u2026` : suggestion;\n console.log(\n JSON.stringify({\n level: 'info',\n event: 'auto_proceed_started',\n suggestion: truncated,\n delayMs,\n }),\n );\n try {\n // \u2500\u2500 Productive cooldown: compact context while we wait \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const proceed = await autoProceedCooldown(opts, delayMs, suggestion, ctrl.signal);\n if (!proceed) {\n // Countdown was cancelled (host callback or abort signal) \u2014 do NOT\n // feed the suggestion. Resolving here without running keeps the\n // \"cancel\" semantics honest instead of fast-forwarding the run.\n console.log(\n JSON.stringify({\n level: 'info',\n event: 'auto_proceed_cancelled',\n suggestion: truncated,\n }),\n );\n return false;\n }\n if ((opts.getAutonomy?.() ?? 'off') !== 'auto') {\n console.log(\n JSON.stringify({\n level: 'info',\n event: 'auto_proceed_cancelled',\n suggestion: truncated,\n reason: 'autonomy_not_auto',\n }),\n );\n return false;\n }\n\n // Record at the authoritative submission boundary: cancelled countdowns\n // and autonomy changes above never count as feeds because no prompt left\n // the client. A repeated prompt halts before `agent.run()`.\n const repetition = grounded ? loopGuard.recordGrounded(suggestion) : loopGuard.record(suggestion);\n if (repetition.shouldHalt) {\n setSuggestions([]);\n setAutoSuggestions([]);\n opts.onSuggestionsParsed?.(null);\n opts.renderer.writeWarning(\n `Auto-proceed halted: the same prompt was fed ${repetition.runLength} times in a row. ` +\n `Autonomy mode is still on, but no automatic next step will run until you provide input. ` +\n `Type anything to continue (resets the guard). ` +\n `Last seen prompt: \"${suggestion.length > 100 ? `${suggestion.slice(0, 97)}\u2026` : suggestion}\"`,\n );\n return false;\n }\n\n // \u2500\u2500 Feed the suggestion as if it were runText \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const steered = 'action' in repetition && repetition.action === 'steer';\n if (steered) {\n opts.renderer.writeWarning(\n 'Todo board unchanged since the last automatic turn \u2014 steering the agent to update the board before continuing.',\n );\n }\n const runBlocks = [\n {\n type: 'text' as const,\n text: steered ? `${suggestion}\\n\\n${GROUNDED_NO_PROGRESS_STEER}` : suggestion,\n },\n ];\n const runResult = await opts.agent.run(runBlocks, { signal: ctrl.signal });\n console.log(\n JSON.stringify({\n level: 'info',\n event: 'auto_proceed_completed',\n suggestion: truncated,\n status: runResult.status,\n iterations: runResult.iterations,\n }),\n );\n opts.onAgentIterationComplete?.(\n estimateRequestTokensCalibrated(\n opts.agent.ctx.messages,\n opts.agent.ctx.systemPrompt,\n opts.agent.ctx.tools ?? [],\n ).total,\n );\n // Parse suggestions from the auto-triggered turn. The live todo list\n // is passed through so we suppress <nextsteps> while the in-flight\n // todo loop is still in progress \u2014 finishing the open todos comes\n // before offering new prompt options.\n if (runResult.status === 'done' && opts.onSuggestionsParsed) {\n const parsed = runResult.finalText\n ? parseSuggestionsFromOutput(runResult.finalText, opts.agent.ctx.todos)\n : null;\n opts.onSuggestionsParsed(parsed);\n }\n return true;\n } finally {\n // activeCtrl cleanup is handled by the caller\n }\n}\n/**\n * Productive cooldown between auto-proceed iterations.\n * Instead of a dead countdown, runs context compaction in the background\n * and only waits the full delay if compaction finishes early\n * (so the user gets a responsive Ctrl+C while still compacting).\n *\n * When delayMs is 0, skips straight to feeding the suggestion.\n *\n * Resolves `true` when the countdown ran to completion (proceed with the\n * suggestion) and `false` when it was cancelled \u2014 either by the abort\n * signal or by `onCountdownTick` returning true. A final `onCountdownTick(0)`\n * fires on every exit path so display consumers can clear their chip.\n */\nasync function autoProceedCooldown(\n opts: ReplOptions,\n delayMs: number,\n suggestion: string,\n signal: AbortSignal,\n): Promise<boolean> {\n if (delayMs <= 0) return true; // immediate \u2014 no wait at all\n\n const truncated = suggestion.length > 100 ? `${suggestion.slice(0, 97)}\u2026` : suggestion;\n const sec = Math.ceil(delayMs / 1000);\n\n opts.renderer.write(`\\n${color.cyan('\u23F3 Auto')} ${color.dim('(Ctrl+C to cancel)')}\\n`);\n opts.renderer.write(`${color.dim(' \u25B8')} ${color.dim(truncated)}\\n`);\n\n // \u2500\u2500 Run compaction during the cooldown \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n void runContextCompaction(opts, signal);\n\n const start = Date.now();\n let interval: ReturnType<typeof setInterval> | undefined;\n let lastTickedSecond = sec + 1; // Start one ahead so first tick fires immediately\n let onAbort: (() => void) | undefined;\n\n return new Promise<boolean>((resolve) => {\n onAbort = () => resolve(false);\n signal.addEventListener('abort', onAbort, { once: true });\n\n interval = setInterval(() => {\n if (signal.aborted) {\n resolve(false);\n return;\n }\n const elapsed = Date.now() - start;\n const remaining = Math.max(0, Math.ceil((delayMs - elapsed) / 1000));\n if (remaining <= 0) {\n opts.renderer.write(color.dim(` \u21B3 ${truncated}\\n`));\n resolve(true);\n return;\n }\n // Surface the tick to the host once per second; a `true` return\n // cancels the countdown (and the pending suggestion with it).\n if (opts.onCountdownTick && remaining !== lastTickedSecond) {\n lastTickedSecond = remaining;\n try {\n const shouldAbort = opts.onCountdownTick(remaining);\n if (shouldAbort === true) {\n opts.renderer.write(\n color.yellow(' \u21B3 Countdown cancelled \u2014 switching to manual mode\\n'),\n );\n resolve(false);\n return;\n }\n } catch {\n // Host callback errors must not break the countdown\n }\n }\n if (remaining % 5 === 0 || remaining === sec) {\n opts.renderer.write(color.dim(` \u23F3 ${remaining}s\u2026\\n`));\n }\n }, 1000);\n }).finally(() => {\n if (interval) clearInterval(interval);\n if (onAbort) signal.removeEventListener('abort', onAbort);\n // Final 0-tick on every exit path \u2014 lets display consumers (TUI\n // status-bar chip) clear instead of freezing at the last value.\n try {\n opts.onCountdownTick?.(0);\n } catch {\n /* display-only */\n }\n });\n}\n\n/**\n * Run context compaction best-effort. Catches all errors silently so it\n * never interrupts the auto-proceed flow. Returns immediately if the\n * agent's context has no compactor wired up.\n */\nasync function runContextCompaction(opts: ReplOptions, _signal: AbortSignal): Promise<void> {\n try {\n const ctx = opts.agent.ctx as never as {\n messages?: Array<unknown>;\n compactor?: { compact(ctx: unknown, opts: { aggressive: boolean }): Promise<void> };\n };\n if (!ctx?.compactor) return;\n // Quick check: only compact if we've added meaningful message volume\n // since the last compaction (heuristic: >50 messages).\n if ((ctx.messages?.length ?? 0) < 50) return;\n await ctx.compactor.compact(ctx, { aggressive: false });\n } catch {\n // Best-effort \u2014 never let compaction break the auto loop\n }\n}\n", "import { color } from '@wrongstack/core/utils';\nimport { theme } from './theme.js';\nimport type { ReplOptions } from './repl-options.js';\n\n/**\n * Read a line, but support two multiline patterns:\n * 1. Trailing `\\` \u2192 continue on the next line (shell-style line continuation).\n * 2. A line that is exactly `\"\"\"` \u2192 start a heredoc; keep reading until\n * another bare `\"\"\"`. Useful for pasting code snippets.\n * Returns the assembled text and whether it came from a heredoc block (so\n * the caller can decide to always collapse heredocs as pastes).\n */\nexport async function readPossiblyMultiline(opts: ReplOptions): Promise<string> {\n const firstPrompt = theme.primary('\u203A ');\n const contPrompt = color.dim('\u00B7 ');\n const first = await opts.reader.readLine(firstPrompt);\n\n if (first.trim() === '\"\"\"') {\n const parts: string[] = [];\n try {\n for (;;) {\n const next = await opts.reader.readLine(contPrompt);\n if (next.trim() === '\"\"\"') break;\n parts.push(next);\n }\n } catch {\n // EOF (Ctrl+D) during heredoc \u2014 user typed \"\"\" then quit.\n // Return what we have; the outer catch breaks the main loop.\n return parts.join('\\n');\n }\n return parts.join('\\n');\n }\n\n let buf = first;\n while (buf.endsWith('\\\\')) {\n buf = buf.slice(0, -1); // drop the trailing backslash\n const cont = await opts.reader.readLine(contPrompt);\n buf += '\\n' + cont;\n }\n return buf;\n}\n", "import { theme } from './theme.js';\nimport { fmtTok } from './utils.js';\nimport { CLI_VERSION } from './version.js';\nimport type { TerminalRenderer } from './renderer.js';\nimport { color } from '@wrongstack/core/utils';\n\nconst FILLED = '\u2588';\nconst EMPTY = '\u2591';\n\nexport function renderContextChip(used: number, max: number): string {\n const ratio = Math.max(0, Math.min(1, used / max));\n const pct = Math.round(ratio * 100);\n const bar = renderProgress(ratio, 6);\n return `${bar} ${pct}% (${fmtTok(used)}/${fmtTok(max)})`;\n}\n\nfunction renderProgress(ratio: number, width: number): string {\n const clamped = Math.max(0, Math.min(1, ratio));\n const filled = clamped === 0 ? 0 : Math.max(1, Math.round(clamped * width));\n const capped = Math.min(width, filled);\n return FILLED.repeat(capped) + EMPTY.repeat(width - capped);\n}\n\nexport function printBanner(renderer: TerminalRenderer, projectName?: string): void {\n const lines = [\n theme.primary(theme.bold('WrongStack')) + color.dim(` v${CLI_VERSION}`),\n color.dim('Built on the wrong stack. Shipped anyway.'),\n ];\n if (projectName && projectName.length > 0) {\n lines.push(color.dim('Project: ') + theme.bold(projectName));\n }\n lines.push(color.dim('Type /help for commands, /exit or q to quit.'), '');\n renderer.write(`${lines.join('\\n')}\\n`);\n}\n", "import * as crypto from 'node:crypto';\nimport * as path from 'node:path';\nimport {\n getSharedProjectMailbox,\n resolveProjectDir,\n} from '@wrongstack/core/coordination';\nimport { wstackGlobalRoot } from '@wrongstack/core/utils';\nimport { startCliHqConnection } from './hq-publisher.js';\nimport type { ReplOptions } from './repl-options.js';\n\nexport interface ReplClientRegistration {\n clientId: string;\n close(): void;\n}\n\nexport function registerReplClient(opts: ReplOptions): ReplClientRegistration {\n // Register REPL as a client in the shared mailbox so other REPL/TUI/WebUI\n // instances on the same project know this REPL is running, even when no\n // agents are active.\n const replProjectRoot = opts.projectRoot ?? process.cwd();\n const projectDir = resolveProjectDir(replProjectRoot, wstackGlobalRoot());\n const clientId = `repl@${crypto.randomUUID().slice(0, 8)}`;\n // The REPL never runs a session telemetry bridge, so it must not advertise\n // `session.summary` \u2014 HQ would render it as a permanent \"waiting for\n // session telemetry\" terminal and orphan-evict the socket every 30s.\n const hqConnection = startCliHqConnection({\n clientKind: 'repl',\n projectRoot: replProjectRoot,\n projectName: path.basename(replProjectRoot),\n appConfig: opts.appConfig,\n capabilities: ['telemetry.publish', 'mailbox.summary'],\n });\n const clientMailbox = getSharedProjectMailbox(\n projectDir,\n undefined,\n () => hqConnection.getPublisher(),\n );\n let clientHeartbeat: ReturnType<typeof setInterval> | undefined;\n clientMailbox\n .registerClient({\n clientId,\n sessionId: opts.getSessionId?.() ?? replProjectRoot,\n name: `REPL [${path.basename(replProjectRoot)}]`,\n source: 'repl',\n pid: process.pid,\n })\n .then(() => {\n clientHeartbeat = setInterval(() => {\n clientMailbox\n .clientHeartbeat({ clientId, sessionId: opts.getSessionId?.() ?? replProjectRoot })\n .catch(() => {\n // best-effort \u2014 if the registry is gone, don't spam errors\n });\n }, 15_000);\n })\n .catch(() => {\n // best-effort \u2014 if another instance has the lock, skip registration\n });\n\n return {\n clientId,\n close() {\n if (clientHeartbeat) clearInterval(clientHeartbeat);\n clientMailbox.deregisterClient(clientId).catch(() => undefined);\n hqConnection.stop();\n },\n };\n}\n", "import type { TodoItem } from '@wrongstack/core/agent';\n\nimport { type PredictLLMProvider, predictNextTasks } from './next-task-predictor.js';\nimport { parseSuggestionsFromOutput } from './repl.js';\nimport { setSuggestions } from './services/suggestion-store.js';\n\nexport function createTuiNextStepCallbacks(input: {\n context: {\n todos?: readonly TodoItem[] | null | undefined;\n provider: unknown;\n model: string;\n };\n getNextPredict?: (() => boolean) | undefined;\n getAutonomy?: (() => string) | undefined;\n getSuggestions?: (() => string[]) | undefined;\n}): {\n predictNext(input: { userRequest: string; assistantSummary: string }): Promise<string[]>;\n onSuggestionsParsed(finalText: string): void;\n getSuggestions(): string[];\n setSuggestions(suggestions: string[]): void;\n} {\n const { context, getNextPredict, getAutonomy, getSuggestions } = input;\n return {\n async predictNext(request: { userRequest: string; assistantSummary: string }) {\n if (!getNextPredict?.()) return [];\n if ((getAutonomy?.() ?? 'off') !== 'off') return [];\n return predictNextTasks(\n { ...request, todos: context.todos ?? [] },\n {\n provider: context.provider as PredictLLMProvider,\n model: context.model,\n },\n );\n },\n onSuggestionsParsed(finalText: string) {\n const parsed = parseSuggestionsFromOutput(finalText, context.todos);\n setSuggestions(parsed ?? []);\n },\n getSuggestions: () => getSuggestions?.() ?? [],\n setSuggestions,\n };\n}\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B;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,uBAAuB,MAAM;AAAA,MAC7B;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;",
6
+ "names": ["randomUUID", "path", "setQueuedMessagesSnapshot", "attachTodosCheckpoint", "normalizeTokenSavingTier", "getProcessRegistry", "color", "resolve", "path", "path", "color", "switchProjectInPlace", "err", "path", "color", "color", "fs", "path", "attachTodosCheckpoint", "stat", "getActiveSDDContext", "trySaveSpecFromAIOutput", "trySaveImplementationPlan", "trySaveTasksFromAIOutput", "autoDetectTaskCompletion", "getTaskProgress", "getActiveSDDPhase", "path", "sessionScopedPath", "fs", "path", "color", "randomUUID", "path", "randomUUID", "traceId", "color", "estimateRequestTokensCalibrated", "hasOpenTodos", "color", "color", "resolve", "color", "color", "color", "path", "color", "resolve", "runCtrl", "estimateRequestTokensCalibrated", "sddPhase", "taskList", "hasOpenTodos", "getSuggestions", "getSuggestions", "randomUUID", "attachTodosCheckpoint", "switchProjectInPlace", "setQueuedMessagesSnapshot", "normalizeTokenSavingTier"]
7
+ }