@buildaharness/aielia 0.3.8 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/dist/_memory-core-generated.d.ts +6 -0
- package/dist/action-approval-service.d.ts +2 -0
- package/dist/ask-draft.d.ts +22 -0
- package/dist/assistant-options.d.ts +35 -0
- package/dist/assistant-session.d.ts +1 -1
- package/dist/assistant.d.ts +11 -0
- package/dist/{bin-DETwedpj.js → bin-Cz3FY6Ew.js} +144 -254
- package/dist/bin-Cz3FY6Ew.js.map +1 -0
- package/dist/claude-cli-llm-client.d.ts +2 -0
- package/dist/claude-cli-prompt.d.ts +7 -0
- package/dist/cli-config.d.ts +2 -2
- package/dist/cli-session.d.ts +2 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1 -1
- package/dist/commands.d.ts +32 -0
- package/dist/config-keys.d.ts +43 -0
- package/dist/doctor-checks.d.ts +1 -2
- package/dist/fact-extraction.d.ts +4 -0
- package/dist/fact-repository.contract.d.ts +2 -0
- package/dist/fact-repository.d.ts +44 -0
- package/dist/file-tools-mcp-server.mjs +29 -0
- package/dist/goal-graph-store.d.ts +6 -0
- package/dist/harness-bridge.d.ts +5 -5
- package/dist/html-to-markdown.d.ts +11 -0
- package/dist/index.d.ts +98 -3
- package/dist/index.js +5003 -150
- package/dist/index.js.map +1 -1
- package/dist/layer-settings.d.ts +16 -3
- package/dist/llm-client-factory.d.ts +13 -0
- package/dist/memory-events.d.ts +177 -0
- package/dist/memory-service.d.ts +17 -0
- package/dist/model-pricing.d.ts +15 -9
- package/dist/node-display-names.d.ts +1 -1
- package/dist/project-command.d.ts +16 -0
- package/dist/{provider-setup-wX2IBw2X.js → provider-setup-DG8iYm_F.js} +14471 -13032
- package/dist/provider-setup-DG8iYm_F.js.map +1 -0
- package/dist/proxy-health.d.ts +8 -0
- package/dist/redact-url.d.ts +2 -0
- package/dist/reply-audit.d.ts +2 -0
- package/dist/response-service.d.ts +10 -0
- package/dist/run-explain.d.ts +58 -0
- package/dist/scripted-llm-client.d.ts +1 -1
- package/dist/{tui-app-CcxiwZyM.js → tui-app-oWbIUcBW.js} +3 -3
- package/dist/{tui-app-CcxiwZyM.js.map → tui-app-oWbIUcBW.js.map} +1 -1
- package/dist/turn-abort.d.ts +5 -0
- package/dist/turn-cost.d.ts +12 -0
- package/dist/turn-presentation.d.ts +86 -0
- package/dist/undo-action-command.d.ts +12 -0
- package/dist/undo-plan.d.ts +13 -0
- package/dist/version.d.ts +1 -1
- package/dist/web-fetch-core.d.ts +0 -14
- package/dist/writer/article-autosave.d.ts +12 -0
- package/dist/writer/article-change-summary.d.ts +28 -0
- package/dist/writer/article-claims.d.ts +49 -0
- package/dist/writer/article-comments.d.ts +20 -0
- package/dist/writer/article-consistency.d.ts +27 -0
- package/dist/writer/article-decorations.d.ts +23 -0
- package/dist/writer/article-dependencies.d.ts +44 -0
- package/dist/writer/article-draft.d.ts +23 -0
- package/dist/writer/article-edit-outline.d.ts +16 -0
- package/dist/writer/article-edit-suggest.d.ts +30 -0
- package/dist/writer/article-folder.d.ts +29 -0
- package/dist/writer/article-history.d.ts +73 -0
- package/dist/writer/article-ideas.d.ts +34 -0
- package/dist/writer/article-issues.d.ts +47 -0
- package/dist/writer/article-marks.d.ts +25 -0
- package/dist/writer/article-memory-store.d.ts +3 -0
- package/dist/writer/article-model.d.ts +1337 -0
- package/dist/writer/article-outline.d.ts +43 -0
- package/dist/writer/article-resolver.d.ts +55 -0
- package/dist/writer/article-revisions.d.ts +30 -0
- package/dist/writer/article-rules.d.ts +60 -0
- package/dist/writer/article-sections.d.ts +26 -0
- package/dist/writer/article-selection.d.ts +26 -0
- package/dist/writer/article-service.d.ts +542 -0
- package/dist/writer/article-source-links.d.ts +42 -0
- package/dist/writer/article-sources.d.ts +82 -0
- package/dist/writer/article-style-derive.d.ts +26 -0
- package/dist/writer/article-style.d.ts +31 -0
- package/dist/writer/article-suggestions.d.ts +33 -0
- package/dist/writer/article-support.d.ts +33 -0
- package/dist/writer/article-verify.d.ts +42 -0
- package/dist/writer/local-folder.d.ts +49 -0
- package/dist/writer/model-failure-hint.d.ts +7 -0
- package/dist/writer/repo-reader.d.ts +29 -0
- package/dist/writer/repo-search.d.ts +33 -0
- package/dist/writer/repo-verify-loop.d.ts +61 -0
- package/dist/writer/text-tool-calls.d.ts +11 -0
- package/dist/writer/work-progress.d.ts +51 -0
- package/dist/writer/write-activity.d.ts +61 -0
- package/dist/writer/write-models.d.ts +12 -0
- package/dist/writer/write-parameters.d.ts +31 -0
- package/dist/writer/write-permissions.d.ts +89 -0
- package/dist/writer/write-spend.d.ts +16 -0
- package/dist/writer/writer-chat-capture.d.ts +25 -0
- package/dist/writer/writer-chat-history.d.ts +17 -0
- package/dist/writer/writer-chat-state.d.ts +358 -0
- package/dist/writer/writer-chat-turn.d.ts +52 -0
- package/dist/writer/writer-intent.d.ts +20 -0
- package/package.json +3 -3
- package/dist/bin-DETwedpj.js.map +0 -1
- package/dist/provider-setup-wX2IBw2X.js.map +0 -1
package/dist/bin-DETwedpj.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bin-DETwedpj.js","sources":["../src/git-exclude.ts","../src/activity-log.ts","../src/node-fs-backend.ts","../src/version.ts","../src/sea-cache.ts","../src/mcp-server-asset.ts","../src/claude-cli-llm-client.ts","../src/network-containment.ts","../src/shell-executor.ts","../src/node-config-store.ts","../src/doctor-checks.ts","../src/non-interactive-mode.ts","../../../node_modules/@dagrejs/dagre/dist/dagre.esm.js","../src/plan-viz/plan-width.ts","../src/plan-viz/plan-layout.ts","../src/plan-viz/plan-raster.ts","../src/first-run.ts","../src/cli-icons.ts","../src/cli-args.ts","../src/self-update.ts","../src/cli.ts","../src/bin.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, statSync, appendFileSync } from 'node:fs'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\n\n/** Directories Aielia keeps inside the workspace for its own state. */\nexport const AIELIA_STATE_DIRS = ['.pending-actions', '.undo-log', '.buildaharness'] as const\n\n/** The git directory of the repository containing `start` (walking up), following a `.git` file (worktrees/submodules). */\nfunction findGitDir(start: string): string | undefined {\n let dir = resolve(start)\n for (;;) {\n const dotGit = join(dir, '.git')\n if (existsSync(dotGit)) {\n const stat = statSync(dotGit)\n if (stat.isDirectory()) return dotGit\n const line = readFileSync(dotGit, 'utf8').split('\\n').find((l) => l.startsWith('gitdir:'))\n if (!line) return undefined\n const target = line.slice('gitdir:'.length).trim()\n const gitDir = isAbsolute(target) ? target : resolve(dir, target)\n // A linked worktree's info/exclude lives in the shared (common) git directory.\n const commonFile = join(gitDir, 'commondir')\n if (existsSync(commonFile)) return resolve(gitDir, readFileSync(commonFile, 'utf8').trim())\n return gitDir\n }\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\n/**\n * Keeps Aielia's own state directories out of version control when the workspace is inside a git repo, by adding them to\n * `<gitdir>/info/exclude` — the per-clone ignore file git itself provides for this. The user's tracked `.gitignore` is never\n * touched, and a non-git directory is left exactly as it was. Idempotent and best-effort: returns the entries it added and\n * never throws (a read-only .git must not stop the assistant from starting).\n */\nexport function excludeAieliaStateFromGit(workspaceRoot: string): string[] {\n try {\n const gitDir = findGitDir(workspaceRoot)\n if (!gitDir) return []\n const excludeFile = join(gitDir, 'info', 'exclude')\n const existing = existsSync(excludeFile) ? readFileSync(excludeFile, 'utf8') : ''\n const present = new Set(existing.split('\\n').map((l) => l.trim()))\n const missing = AIELIA_STATE_DIRS.map((d) => `${d}/`).filter((entry) => !present.has(entry) && !present.has(entry.slice(0, -1)))\n if (missing.length === 0) return []\n mkdirSync(dirname(excludeFile), { recursive: true })\n const prefix = existing === '' || existing.endsWith('\\n') ? '' : '\\n'\n appendFileSync(excludeFile, `${prefix}# Aielia state (added automatically)\\n${missing.join('\\n')}\\n`)\n return missing\n } catch {\n return []\n }\n}\n","/**\n * Opt-in, append-only activity log for the terminal CLI: one JSON object per line in\n * `<dataDir>/activity-log.jsonl`, fed by the assistant's existing `onDebugLog` hook (user messages,\n * assistant replies, every tool call with its arguments and result, approval requests and decisions).\n *\n * Why: the per-message transcript (transcripts/transcript-msg_*.json) deliberately holds only plain\n * user/assistant text, so after a session there was no durable record of which tools ran, what they\n * returned, or what the user approved. Plain content is written (not scrubbed), so it is OFF unless\n * ASSISTANT_ACTIVITY_LOG is set to 1/true/on/yes, the same trade-off DebugLogEntry documents.\n * Node-only (fs): imported by cli.ts, never by the browser build.\n */\nimport { appendFileSync, chmodSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { DebugLogEntry } from './debug-log.js'\n\nexport function activityLogEnabled(env: NodeJS.ProcessEnv): boolean {\n return /^(1|true|on|yes|enabled)$/i.test(env.ASSISTANT_ACTIVITY_LOG ?? '')\n}\n\n/** Returns an `onDebugLog` callback appending `{at, sessionId, kind, content}` lines to `filePath`. Never throws. */\nexport function createActivityLogger(filePath: string, now: () => Date = () => new Date()): (entry: DebugLogEntry) => void {\n let ready = false\n return (entry) => {\n try {\n if (!ready) {\n mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 })\n }\n appendFileSync(filePath, JSON.stringify({ at: now().toISOString(), sessionId: entry.sessionId, kind: entry.kind, content: entry.content }) + '\\n', { mode: 0o600 })\n if (!ready) {\n // `mode` only applies when the file is created; a log left over from an older version may be world-readable.\n try { chmodSync(filePath, 0o600) } catch { /* not ours to change; the entry is written */ }\n ready = true\n }\n } catch (err) {\n // A logging problem must never break a turn.\n console.error('[activity-log] could not write an entry:', err)\n }\n }\n}\n","import { mkdir, readFile, writeFile, readdir, unlink, realpath, stat, rename } from 'node:fs/promises'\nimport type { FsBackend } from '@buildaharness/runtime'\n\nfunction isEnoent(err: unknown): boolean {\n return (err as NodeJS.ErrnoException)?.code === 'ENOENT'\n}\n\n/**\n * node:fs/promises-backed FsBackend for the CLI. Deliberately not exported from\n * this package's index — only cli.ts imports it, so a browser build (chat-ui)\n * that only ever imports the package root never pulls a Node builtin into its\n * bundle.\n */\nexport function createNodeFsBackend(): FsBackend {\n return {\n async readTextFile(path) {\n try {\n return await readFile(path, 'utf-8')\n } catch (err) {\n if (isEnoent(err)) return undefined\n throw err\n }\n },\n async writeTextFile(path, contents) {\n await writeFile(path, contents, 'utf-8')\n },\n async removeFile(path) {\n try {\n await unlink(path)\n } catch (err) {\n if (!isEnoent(err)) throw err\n }\n },\n async mkdir(path) {\n await mkdir(path, { recursive: true })\n },\n async readDir(path) {\n try {\n return await readdir(path)\n } catch (err) {\n if (isEnoent(err)) return []\n throw err\n }\n },\n async realpath(path) {\n return realpath(path)\n },\n async stat(path) {\n try {\n const info = await stat(path)\n return { isDirectory: info.isDirectory(), size: info.size }\n } catch (err) {\n if (isEnoent(err)) return undefined\n throw err\n }\n },\n async rename(from, to) {\n await rename(from, to)\n },\n }\n}\n","/**\n * The CLI's own version, checked into git so it is available without reading package.json at\n * runtime (a bundled/SEA binary has no package.json beside it). `scripts/check-cli-version-sync.mjs`\n * fails CI if this drifts from `package.json`'s `version` — bump both together.\n */\nexport const CLI_VERSION = '0.3.8'\n","/**\n * Shared \"extract an embedded SEA asset to disk once\" helpers, used by both\n * bin-sea-bootstrap.ts (the CJS SEA entry, which pulls out the real ESM app bundle) and\n * mcp-server-asset.ts (which pulls out file-tools-mcp-server.mjs). Deliberately free of\n * `import.meta` and of any `node:sea` import so it bundles cleanly into the CJS bootstrap.\n *\n * A Node Single Executable Application can't execute an embedded asset in place, and the\n * `claude` CLI needs a real on-disk path to spawn the MCP server from — so each asset is written\n * under a per-version directory and reused on every later launch.\n */\nimport { mkdirSync, existsSync, writeFileSync, renameSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\n/** `~/.buildaharness/personal-assistant/sea-cache/<version>` — same data dir as cli.ts's `defaultDataDir`. */\nexport function seaCacheDir(version: string, home: string = homedir()): string {\n return join(home, '.buildaharness', 'personal-assistant', 'sea-cache', version)\n}\n\n/**\n * Writes `read()`'s bytes to `<dir>/<fileName>` unless that exact path already exists, and returns\n * the path. Version-gated by construction: `dir` embeds the CLI version, so a new release never\n * reuses a stale extraction. Written via a temp file + rename so a crash or a concurrent second\n * launch can never observe (and then import) a half-written file.\n */\nexport function extractAssetOnce(dir: string, fileName: string, read: () => string | ArrayBuffer): string {\n const target = join(dir, fileName)\n if (existsSync(target)) return target\n mkdirSync(dir, { recursive: true })\n const tmp = `${target}.${process.pid}.tmp`\n const data = read()\n writeFileSync(tmp, typeof data === 'string' ? data : new Uint8Array(data))\n renameSync(tmp, target)\n return target\n}\n","import { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport { join } from 'node:path'\nimport { CLI_VERSION } from './version.js'\nimport { extractAssetOnce, seaCacheDir } from './sea-cache.js'\n\nexport const MCP_SERVER_FILE_NAME = 'file-tools-mcp-server.mjs'\n\n/**\n * The lexical pattern files file-tools-mcp-server.mjs reads at startup via\n * `join(__dirname, 'lexical/patterns/<name>')` — they have to sit beside the extracted server,\n * so they are embedded as SEA assets (under this same relative key) and extracted with it.\n */\nexport const MCP_SERVER_PATTERN_FILES = ['injection-patterns.json', 'fact-markers.json', 'risk-patterns.json'] as const\n\nexport interface SeaModule {\n isSea(): boolean\n getRawAsset(key: string): ArrayBuffer\n}\n\n/** `node:sea` if this process is a Node single executable application, else null. Never throws. */\nexport function loadSea(): SeaModule | null {\n try {\n // createRequire keeps this out of the bundlers' static import graph — `node:sea` is absent on\n // older Node versions, and only meaningful inside a SEA.\n const sea = createRequire(import.meta.url)('node:sea') as SeaModule\n return sea.isSea() ? sea : null\n } catch {\n return null\n }\n}\n\n/**\n * Absolute on-disk path to file-tools-mcp-server.mjs, which the claude-cli backend hands to the\n * separate `claude` binary to spawn as a `node <path>` MCP subprocess.\n *\n * - Inside a SEA binary, `import.meta.url` is not a real file location, so the embedded asset is\n * extracted once (version-gated, see sea-cache.ts) and that path returned.\n * - Otherwise (npm install, tsx), it is the file sitting next to this module, as before.\n *\n * `seaOverride` and `home` exist for tests; production callers pass nothing.\n */\nexport function resolveMcpServerPath(seaOverride?: SeaModule | null, home?: string): string {\n const sea = seaOverride === undefined ? loadSea() : seaOverride\n if (sea) {\n const dir = seaCacheDir(CLI_VERSION, home)\n for (const name of MCP_SERVER_PATTERN_FILES) {\n const key = `lexical/patterns/${name}`\n extractAssetOnce(join(dir, 'lexical', 'patterns'), name, () => sea.getRawAsset(key))\n }\n return extractAssetOnce(dir, MCP_SERVER_FILE_NAME, () => sea.getRawAsset(MCP_SERVER_FILE_NAME))\n }\n // Deliberately not `new URL('./file-tools-mcp-server.mjs', import.meta.url)` as a single literal —\n // Vite's asset-URL plugin statically detects that exact pattern and inlines the whole file as a\n // base64 data: URL at build time, which fileURLToPath can't turn back into a real path.\n return fileURLToPath(new URL(MCP_SERVER_FILE_NAME, import.meta.url))\n}\n","/*\n * DEVELOPER TESTING ONLY. Not offered in the welcome/first-run flow, and not for use by end users\n * or with anyone else's credentials. Anthropic's terms do not permit third-party products to route\n * requests through Free/Pro/Max subscription credentials\n * (https://code.claude.com/docs/en/legal-and-compliance) — use the anthropic/openai/openrouter\n * API-key backends for anything beyond local testing on your own machine.\n */\nimport { spawn } from 'node:child_process'\nimport { readdir, readFile, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { createServer, type Server } from 'node:net'\nimport type { ILLMClient, ChatMessage, ChatOptions, ToolDefinition, LLMStructuredResponse, ToolStepEvent, ToolProposalDecision } from '@buildaharness/runtime'\nimport type { PendingActionRecord } from './file-tools.js'\nimport { buildClaudePrompt, parseClaudeCliOutput, stripJsonCodeFence, ALREADY_STAGED_ACTION_TOOL, stagedActionInput, type ParsedClaudeCliOutput } from './claude-cli-prompt.js'\nimport { stripMcpToolPrefix } from './tool-step.js'\nimport { resolveMcpServerPath } from './mcp-server-asset.js'\nimport { lexicalOffEnvValue } from './lexical/lexical-mode.js'\nimport { recallToolEnabled } from './recall-tool.js'\n\n/**\n * `--tools \"\"` only disables Claude Code's own built-in tools (Read/Write/Bash/etc.) — it\n * has no effect on MCP servers, which are controlled entirely by --mcp-config/\n * --strict-mcp-config. Without this, a plain callChatSync call silently inherits whatever\n * MCP servers happen to be configured ambiently (a project .mcp.json, or the user's own\n * global Claude Code config) — an ordinary PersonalAssistant chat turn must not pick up\n * unrelated tools the user happens to have configured for their own interactive sessions.\n * An empty --mcp-config plus --strict-mcp-config guarantees zero MCP servers, the same way\n * --tools \"\" guarantees zero built-ins.\n */\nconst EMPTY_MCP_CONFIG = JSON.stringify({ mcpServers: {} })\n\nexport interface ClaudeCliLLMClientOptions {\n /** Path to the claude binary. Defaults to CLAUDE_PATH env var, then 'claude' on PATH. */\n claudePath?: string\n /**\n * When set, callChatStructured wires in the file-tools MCP server (read_file/\n * list_directory/write_file, scoped to workspaceRoot) via --mcp-config instead\n * of throwing when tools are supplied. Absent by default — an ordinary chat\n * turn through this backend stays fully tool-free, exactly as before.\n */\n fileTools?: { workspaceRoot: string }\n /**\n * When set (and fileTools is also set — the MCP server only starts at all\n * when fileTools is configured), also registers create_reminder/list_reminders\n * on the same MCP server, backed by this file. Must point at the exact file a\n * `FileSystemAdapter` (namespace \"reminders\") would use for the key\n * \"reminders\" — see file-tools-mcp-server.mjs's doc comment — so this\n * subprocess and the parent process's own ReminderStore share one reminder\n * list instead of drifting into two disconnected ones. Absent by default —\n * those two tools stay unregistered, same as before this option existed.\n * fetch_url needs no such option: it's registered unconditionally whenever\n * fileTools is set, since it has no shared-state dependency to configure.\n */\n remindersFile?: string\n /**\n * When set, also registers run_shell_command on the same MCP server (started\n * whenever fileTools or shellTools is configured) — gated behind an env var\n * the same way reminders are gated behind `remindersFile`. Bash itself is\n * never added to --tools regardless of this setting — see the class doc\n * comment. Kept as a separate option from fileTools so a caller can enable\n * shell without file access or vice versa, even though `workspaceRoot` is\n * typically the same value for both on this backend.\n */\n shellTools?: { workspaceRoot: string }\n /**\n * When set, also registers `web_search` on the same MCP server (started\n * whenever fileTools, shellTools, or webTools is configured), backed by the\n * Brave Search API (the only backend — see web-search-provider.ts). Gated\n * behind the `BRAVE_SEARCH_API_KEY` env var passed to the server, the same\n * way shell is gated behind `ENABLE_SHELL_TOOLS`. `fetch_url` is registered\n * independently whenever the server runs at all — this option only adds the\n * search half.\n */\n webTools?: { braveApiKey?: string }\n /**\n * When set, also registers send_email on the same MCP server (started whenever any of\n * fileTools/shellTools/webTools/actionTools is configured), gated behind an env var the same\n * way run_shell_command is. The MCP server only ever *stages* the message — the parent process\n * delivers it, after approval, through its own configured SendEmail transport (email.ts /\n * email-smtp.ts). Kept separate from fileTools so email can be enabled without file access.\n */\n actionTools?: { workspaceRoot: string }\n /**\n * Default model passed as `--model` to every `claude -p` call when the per-call\n * `ChatOptions.model` doesn't already set one. The benchmark (Plan A1) uses this to pin every\n * audit run to a stated model instead of silently inheriting the CLI default. `undefined` keeps\n * the pre-A1 behaviour (no `--model` flag → CLI default).\n */\n model?: string\n}\n\n/**\n * Runs `claude` with cwd pinned to the OS temp directory, never the caller's actual\n * working directory — `claude` has no flag to suppress project-context loading, it\n * infers it entirely from the process's cwd (project instruction files, .mcp.json, skills, all\n * auto-loaded regardless of --system-prompt/--tools). Since PersonalAssistant's whole\n * point is a plain personal-assistant persona, not a coding agent scoped to whatever\n * repo happens to be the launch directory, every invocation runs from a directory that's\n * essentially guaranteed to have none of that project-level config to auto-load.\n */\nfunction invokeClaude(claudePath: string, args: string[]): Promise<ParsedClaudeCliOutput> {\n return new Promise((resolvePromise, reject) => {\n const proc = spawn(claudePath, args, { cwd: tmpdir(), stdio: ['ignore', 'pipe', 'pipe'] })\n let stdout = ''\n let stderr = ''\n proc.stdout.on('data', (chunk) => { stdout += chunk })\n proc.stderr.on('data', (chunk) => { stderr += chunk })\n proc.on('error', reject)\n proc.on('close', (code) => {\n if (code !== 0) {\n reject(new Error(stderr.trim() || `claude exited with code ${code}`))\n return\n }\n resolvePromise(parseClaudeCliOutput(stdout))\n })\n })\n}\n\n/**\n * Same subprocess-invocation contract as invokeClaude, but for a `--output-format\n * stream-json` call (requires `--verbose` — enforced by whichever caller builds `args`):\n * parses newline-delimited JSON events as they arrive so tool_use blocks can be reported\n * live via onToolStep — otherwise invisible, since Claude Code's own agentic loop resolves\n * every tool call inside this one subprocess call before returning. The final answer still\n * comes from the last `result`-type event, in the exact same shape/field names\n * --output-format json's single object uses, so parseClaudeCliOutput's existing\n * result/content/fallback logic covers it unchanged — just handed one line instead of the\n * whole stdout.\n */\nfunction invokeClaudeStreaming(claudePath: string, args: string[], onToolStep?: (event: ToolStepEvent) => void): Promise<ParsedClaudeCliOutput> {\n return new Promise((resolvePromise, reject) => {\n const proc = spawn(claudePath, args, { cwd: tmpdir(), stdio: ['ignore', 'pipe', 'pipe'] })\n let buffer = ''\n let stderr = ''\n let finalResultLine: string | undefined\n\n const handleLine = (line: string): void => {\n {\n if (!line.trim()) return\n\n let event: { type?: string; message?: { content?: unknown[] } }\n try {\n event = JSON.parse(line)\n } catch {\n return // stream-json is one complete JSON object per line — an unparseable line is never expected, but must never crash the stream\n }\n\n if (event.type === 'assistant' && onToolStep) {\n for (const block of event.message?.content ?? []) {\n if ((block as { type?: string }).type !== 'tool_use') continue\n const toolUse = block as { name: string; input?: Record<string, unknown> }\n onToolStep({ tool: stripMcpToolPrefix(toolUse.name), input: toolUse.input ?? {} })\n }\n } else if (event.type === 'result') {\n finalResultLine = line\n }\n }\n }\n proc.stdout.on('data', (chunk: Buffer) => {\n buffer += chunk.toString('utf-8')\n let newlineIndex: number\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex)\n buffer = buffer.slice(newlineIndex + 1)\n handleLine(line)\n }\n })\n proc.stderr.on('data', (chunk) => { stderr += chunk })\n proc.on('error', reject)\n proc.on('close', (code) => {\n if (code !== 0) {\n reject(new Error(stderr.trim() || `claude exited with code ${code}`))\n return\n }\n handleLine(buffer) // a final line with no trailing newline is still a complete event\n buffer = ''\n resolvePromise(parseClaudeCliOutput(finalResultLine ?? ''))\n })\n })\n}\n\n/**\n * Phase D0 (harness_consolidation_and_control_plane_plan.html): a synchronous, per-call gate the\n * file-tools MCP server (spawned as this `claude` subprocess's own child — see\n * file-tools-mcp-server.mjs) blocks on before executing a read-only tool (read_file/\n * list_directory/fetch_url/web_search/create_reminder/list_reminders/recall_memory). write_file/\n * run_shell_command/send_email are unaffected — they already stage unconditionally and never\n * call this gate.\n *\n * Without this, Claude Code's own agentic loop resolves those read-only calls entirely inside\n * this one subprocess call: the deterministic, harness-informed check the proxy backend's manual\n * tool loop already runs before every call (agent-loop.ts's checkToolPolicy) never ran for this\n * backend at all — onToolStep only reports the call after Claude Code has already decided to\n * make it, too late to gate.\n *\n * Listens on an ephemeral loopback TCP port for the lifetime of one callChatStructured call;\n * newline-delimited JSON request/response, one request per tool call (`{tool, input}` in,\n * `{decision, reason?}` out — see ChatOptions.onToolProposal; a `{kind: 'result', tool, input, text}`\n * message reports an executed tool's raw result instead — see ChatOptions.onToolResult; a\n * `{kind: 'execute', tool, input}` message asks the caller to run fetch_url/web_search itself — see\n * ChatOptions.onToolExecute). Absent `onToolProposal` (a caller\n * that hasn't wired the gate), or an unparseable request, every proposal is allowed — the\n * pre-D0 behavior, unchanged.\n */\nfunction startToolGateServer(\n onToolProposal?: (tool: string, input: Record<string, unknown>) => Promise<ToolProposalDecision>,\n onToolResult?: (tool: string, input: Record<string, unknown>, resultText: string, ok: boolean, notFound?: boolean) => void | Promise<void>,\n onToolExecute?: (tool: string, input: Record<string, unknown>) => Promise<string | undefined>,\n): Promise<{ server: Server; port: number }> {\n return new Promise((resolvePromise, reject) => {\n const server = createServer((socket) => {\n // A peer that dies mid-request (the MCP subprocess killed, a reset) emits 'error' on the socket; with no listener that is an uncaught exception that would crash the process.\n socket.on('error', () => {})\n let buffer = ''\n socket.on('data', (chunk: Buffer) => {\n buffer += chunk.toString('utf-8')\n let newlineIndex: number\n while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {\n const line = buffer.slice(0, newlineIndex)\n buffer = buffer.slice(newlineIndex + 1)\n if (!line.trim()) continue\n void (async (requestLine: string) => {\n let request: { kind?: unknown; tool?: unknown; input?: unknown; text?: unknown; ok?: unknown; notFound?: unknown }\n try {\n request = JSON.parse(requestLine)\n } catch {\n socket.write(`${JSON.stringify({ decision: 'allow' })}\\n`)\n return\n }\n // A `kind: 'result'` message reports what an already-executed read-only tool returned\n // (see ChatOptions.onToolResult) rather than proposing a call. It rides the same socket\n // and the same one-request-one-response shape — no request ids exist, so the MCP side\n // queues it like any proposal — and is acked with the same `allow` shape.\n // A `kind: 'execute'` message asks the caller to run a network tool itself (see\n // ChatOptions.onToolExecute). `{handled: false}` tells the MCP server to fetch locally as\n // before; an error is reported as `{handled: true, error}` so the model sees a failed\n // tool, not a silent second attempt over the real network the caller meant to control.\n if (request.kind === 'execute') {\n let reply: { handled: boolean; text?: string; error?: string } = { handled: false }\n try {\n if (onToolExecute && typeof request.tool === 'string') {\n const text = await onToolExecute(request.tool, (request.input as Record<string, unknown>) ?? {})\n if (text !== undefined) reply = { handled: true, text }\n }\n } catch (err) {\n reply = { handled: true, error: err instanceof Error ? err.message : String(err) }\n }\n socket.write(`${JSON.stringify(reply)}\\n`)\n return\n }\n if (request.kind === 'result') {\n try {\n if (onToolResult && typeof request.tool === 'string' && typeof request.text === 'string') {\n await onToolResult(request.tool, (request.input as Record<string, unknown>) ?? {}, request.text, request.ok !== false, request.notFound === true)\n }\n } catch (err) {\n console.error('claude-cli tool gate: onToolResult threw — ignoring:', err)\n }\n socket.write(`${JSON.stringify({ decision: 'allow' })}\\n`)\n return\n }\n let decision: ToolProposalDecision\n try {\n decision =\n onToolProposal && typeof request.tool === 'string'\n ? await onToolProposal(request.tool, (request.input as Record<string, unknown>) ?? {})\n : { decision: 'allow' }\n } catch (err) {\n // onToolProposal (agent-loop.ts's wiring) can throw — e.g. a tracing hook\n // (onTrace) called from inside checkToolPolicy. Left uncaught, this rejection\n // is unhandled inside the fire-and-forget IIFE below and crashes the whole\n // process under Node's default throw-on-unhandledRejection. Fail open here,\n // the same posture file-tools-mcp-server.mjs's requestToolGate already takes\n // on its own transport errors (ADR-003 decision 10's injection-detector\n // fail-open) — this is defense-in-depth on top of the real sandboxing/staging\n // boundaries, not itself the security control.\n console.error('claude-cli tool gate: onToolProposal threw — failing open:', err)\n decision = { decision: 'allow' }\n }\n socket.write(`${JSON.stringify(decision)}\\n`)\n })(line)\n }\n })\n })\n server.on('error', reject)\n server.listen(0, '127.0.0.1', () => {\n const address = server.address()\n if (address === null || typeof address === 'string') {\n reject(new Error('tool gate server failed to bind to a loopback TCP port'))\n return\n }\n resolvePromise({ server, port: address.port })\n })\n })\n}\n\n/**\n * ILLMClient backed by a local `claude -p` subprocess instead of a hosted API key —\n * runs PersonalAssistant against an already-authenticated Claude Code CLI session.\n * Always passes --system-prompt (so the CLI's own default prompt/project instructions/skills\n * never leak into an ordinary chat turn) and --tools \"\" (PersonalAssistant only\n * ever calls callChatSync — there's nothing here that expects tool use). **Bash is\n * never added to --tools, under any configuration** — run_shell_command instead goes\n * through the same MCP server as the file tools, which only stages (never executes),\n * exactly like write_file: once a built-in like Bash is active, Claude Code's own\n * agentic loop would execute it autonomously within the single `claude -p` call, with\n * no point at which our code sees the command before it runs.\n *\n * **onUsage's costUsd caveat:** token counts (`inputTokens`/`outputTokens`) are always real —\n * they come straight from `claude --output-format json`'s `usage` field. `costUsd` comes from\n * that same response's `total_cost_usd`, which reflects real API billing when the underlying\n * `claude` session is authenticated with an API key, but may read `0` when it's authenticated\n * against a Pro/Max subscription instead (no per-call dollar cost to report). A caller\n * presenting this to a user (see personal-assistant's /cost) must not read a `0` here as \"this\n * turn was free\" without that context.\n */\nexport class ClaudeCliLLMClient implements ILLMClient {\n private readonly claudePath: string\n private readonly fileTools?: { workspaceRoot: string }\n private readonly remindersFile?: string\n private readonly shellTools?: { workspaceRoot: string }\n private readonly webTools?: { braveApiKey?: string }\n private readonly actionTools?: { workspaceRoot: string }\n private readonly model?: string\n /**\n * The concrete model id the last `claude -p` call actually reported running against (read from\n * the response's own `model` field, not the CLI alias). `undefined` until a call resolves one.\n * Plan A1 records this into the benchmark report so a published table can name the model.\n */\n resolvedModelId?: string\n\n constructor(options: ClaudeCliLLMClientOptions = {}) {\n this.claudePath = options.claudePath ?? process.env.CLAUDE_PATH ?? 'claude'\n this.fileTools = options.fileTools\n this.remindersFile = options.remindersFile\n this.shellTools = options.shellTools\n this.webTools = options.webTools\n this.actionTools = options.actionTools\n this.model = options.model\n }\n\n async *callChat(messages: ChatMessage[], options: ChatOptions = {}): AsyncIterable<string> {\n yield await this.callChatSync(messages, options)\n }\n\n async callChatSync(messages: ChatMessage[], options: ChatOptions = {}): Promise<string> {\n const { systemPrompt, prompt } = buildClaudePrompt(messages)\n const args = [\n '--print',\n '--output-format', 'json',\n '--tools', '',\n '--no-session-persistence',\n '--system-prompt', systemPrompt,\n '--mcp-config', EMPTY_MCP_CONFIG,\n '--strict-mcp-config', // ignore any ambient project/user MCP config — see EMPTY_MCP_CONFIG's doc comment\n ]\n const model = options.model ?? this.model\n if (model) args.push('--model', model)\n // `--` ends option parsing: a message that starts with \"-\" (a markdown list, \"-5 degrees\") would otherwise be rejected as an unknown option.\n args.push('--', prompt)\n const { reply, usage, model: resolved } = await invokeClaude(this.claudePath, args)\n if (resolved) this.resolvedModelId = resolved\n if (usage) options.onUsage?.(usage)\n return reply\n }\n\n /**\n * When `tools` is non-empty and `fileTools`/`shellTools` was configured, wires the\n * file-tools MCP server into a single `claude -p` call and lets Claude Code's own\n * agentic loop call read_file/list_directory/write_file/fetch_url/create_reminder/\n * list_reminders/run_shell_command autonomously — we don't get to intercept each\n * call the way the proxy backend's manual tool loop does (see\n * the internal plan, T6). fetch_url is always\n * registered on that server; create_reminder/list_reminders only when\n * `remindersFile` is set; run_shell_command only when `shellTools` is set;\n * web_search only when `webTools` is set (Brave Search — see the `webTools`\n * option). Three\n * possible outcomes: a final text reply (no tool call this backend needs to\n * surface), a write or shell command staged by the MCP server mid-call (surfaced\n * as a synthetic `__staged_action` tool call so assistant.ts's tool loop treats it\n * the same as a manually staged action without staging it a second time), or —\n * for fetch_url/create_reminder/list_reminders — the tool's result text folded\n * directly into Claude Code's own reply, since (unlike the proxy backend's\n * `executeToolCall`) there's no outer loop here to intercept each call and\n * re-apply trust-tagging itself; the MCP server tags fetch_url's result before\n * Claude Code ever sees it instead (see file-tools-mcp-server.mjs).\n */\n async callChatStructured(messages: ChatMessage[], tools?: ToolDefinition[], options: ChatOptions = {}): Promise<LLMStructuredResponse> {\n if (!tools || tools.length === 0) {\n // See stripJsonCodeFence's doc comment: this backend has no real schema-constrained\n // output mode, so a caller expecting bare JSON in `content` (per options.structuredOutput)\n // needs any markdown fence the model wrapped it in removed here, once, rather than in\n // every individual JSON.parse(response.content) call site.\n const content = await this.callChatSync(messages, options)\n return { content: options.structuredOutput ? stripJsonCodeFence(content) : content }\n }\n // M3: recall_memory is served by the parent (onToolExecute), so a client with no other tool family still has a real tool to offer when it is enabled.\n if (!this.fileTools && !this.shellTools && !this.webTools && !this.actionTools && !recallToolEnabled()) {\n throw new Error(\n 'ClaudeCliLLMClient does not support tool calls unless constructed with fileTools, shellTools, webTools, or actionTools configured',\n )\n }\n\n const { systemPrompt, prompt } = buildClaudePrompt(messages)\n // web_search / send_email need no workspace; fall back to the temp dir when one of those is\n // the only capability configured (the CLI always sets fileTools for this backend, so in\n // practice this is the real workspace root).\n const workspaceRoot =\n this.fileTools?.workspaceRoot ?? this.shellTools?.workspaceRoot ?? this.actionTools?.workspaceRoot ?? tmpdir()\n // The current turn's raw user message, before Claude Code's own agentic loop (and any\n // rewording it does before calling a tool) ever sees it — passed through to the MCP\n // server so create_reminder can check the *original* phrasing against fact-shaped\n // markers, not just whatever `text` the model decided to pass as the tool argument\n // (which is routinely reworded to third person, e.g. \"I'm allergic to peanuts, please\n // remember that\" → \"User is allergic to peanuts\", dodging a check against `text` alone).\n const lastUserMessage = [...messages].reverse().find((m) => m.role === 'user')?.content ?? ''\n // See mcp-server-asset.ts — the non-SEA branch keeps the old import.meta.url resolution.\n const mcpServerPath = resolveMcpServerPath()\n // Phase D0: gates read_file/list_directory/fetch_url/web_search/create_reminder/\n // list_reminders — see startToolGateServer's doc comment. Started before the config is\n // built (its port needs to go into TOOL_GATE_PORT) and always closed once this call\n // finishes, gate-decision or not.\n const gate = await startToolGateServer(options.onToolProposal, options.onToolResult, options.onToolExecute)\n try {\n const mcpConfig = JSON.stringify({\n mcpServers: {\n 'file-tools': {\n command: 'node',\n args: [mcpServerPath],\n env: {\n WORKSPACE_ROOT: workspaceRoot,\n TOOL_GATE_PORT: String(gate.port),\n ...(this.remindersFile ? { REMINDERS_FILE: this.remindersFile, CURRENT_USER_MESSAGE: lastUserMessage } : {}),\n ...(this.shellTools ? { ENABLE_SHELL_TOOLS: '1' } : {}),\n ...(this.webTools?.braveApiKey ? { BRAVE_SEARCH_API_KEY: this.webTools.braveApiKey } : {}),\n ...(this.actionTools ? { ENABLE_EMAIL_TOOL: '1' } : {}),\n // M3: recall_memory is registered (gated, then served by the parent via onToolExecute) only under AUDIT_RECALL_TOOL.\n ...(recallToolEnabled() ? { ENABLE_RECALL_TOOL: '1' } : {}),\n // Always passed (even empty): the server reads an unset value as the default, every family off.\n ASSISTANT_LEXICAL_RESOLVED_OFF: lexicalOffEnvValue(),\n },\n },\n },\n })\n\n const args = [\n '--print',\n '--output-format', 'stream-json', // streamed (not the single-object 'json') so tool_use events can be reported live via onToolStep — see invokeClaudeStreaming\n '--verbose', // required by --print when --output-format is stream-json\n '--tools', '', // still disable Claude Code's own built-in Read/Write/Bash tools — Bash is never added, regardless of shellTools\n '--no-session-persistence',\n '--system-prompt', systemPrompt,\n '--mcp-config', mcpConfig,\n '--strict-mcp-config', // ignore any ambient project .mcp.json — the tool surface must be exactly this plan's tools\n '--dangerously-skip-permissions', // headless -p mode has no way to answer an interactive tool-permission prompt\n ]\n const model = options.model ?? this.model\n if (model) args.push('--model', model)\n args.push('--', prompt) // see callChatSync: a prompt starting with \"-\" must not be parsed as an option\n\n const callStartedAt = Date.now()\n const { reply, usage, model: resolved } = await invokeClaudeStreaming(this.claudePath, args, options.onToolStep)\n if (resolved) this.resolvedModelId = resolved\n if (usage) options.onUsage?.(usage)\n const staged = await this.findPendingActionStagedSince(workspaceRoot, callStartedAt)\n\n if (staged) {\n return {\n content: '',\n toolCalls: [{ id: `cli-staged-${staged.id}`, name: ALREADY_STAGED_ACTION_TOOL, input: stagedActionInput(staged) }],\n }\n }\n return { content: reply }\n } finally {\n gate.server.close()\n }\n }\n\n /** Diffs .pending-actions/ against the call's start time to detect a write or shell command the MCP server staged during this subprocess call. */\n /**\n * When the MCP server staged more than one action this call (e.g. \"run X AND write Y\" —\n * see file-tools-mcp-server.mjs's stagePendingAction doc comment), every one of them lands\n * in `.pending-actions/` with an mtime after `startTimeMs`, in `readdir`-arbitrary order —\n * not necessarily staging order. Must return the *chain head* (earliest `stagedAt`)\n * specifically, since resolvePendingAction (assistant.ts) walks `nextPendingActionId`\n * forward from whichever record it's handed; returning a later link here would surface the\n * chain out of order and orphan the earlier, still-unresolved action.\n */\n private async findPendingActionStagedSince(workspaceRoot: string, startTimeMs: number): Promise<PendingActionRecord | undefined> {\n const dir = `${workspaceRoot}/.pending-actions`\n let names: string[]\n try {\n names = await readdir(dir)\n } catch {\n return undefined\n }\n let earliest: PendingActionRecord | undefined\n for (const name of names) {\n if (!name.endsWith('.json')) continue\n const filePath = `${dir}/${name}`\n let record: PendingActionRecord\n try {\n const stats = await stat(filePath)\n // Small buffer against filesystem mtime rounding (e.g. 1s resolution on some\n // filesystems) being coarser than Date.now()'s precision.\n if (stats.mtimeMs < startTimeMs - 1000) continue\n record = JSON.parse(await readFile(filePath, 'utf-8')) as PendingActionRecord\n } catch {\n continue // a record deleted or half-written mid-scan must not fail the whole call (and lose a staged action's sibling)\n }\n if (!earliest || record.stagedAt < earliest.stagedAt) earliest = record\n }\n return earliest\n }\n}\n","import { createServer, connect as netConnect, type Socket, type Server } from 'node:net'\n\n/**\n * Node-level network containment for an approved run_shell_command execution — Decision 6 of\n * the internal plan (Phase 4 step 2). This is the network-reachability\n * half of that decision; the env-stripping half already existed in shell-executor.ts's\n * allowlistedEnv(). Deliberately not a real OS sandbox (see the plan's Decision 6 for why that\n * tradeoff was chosen): a minimal loopback-only forward proxy that relays a CONNECT tunnel\n * (HTTPS) or a plain-HTTP proxy request only when its target host matches an entry in the\n * caller-supplied allowlist (exact match or subdomain), and otherwise closes the connection with\n * a 403. The spawned subprocess's HTTP(S)_PROXY env vars are forced to point here, so a tool that\n * honors those (curl, wget, most language HTTP clients) can only reach an allowlisted host. This\n * does NOT stop a tool that opens raw sockets and ignores proxy env vars entirely — that\n * limitation is Decision 6's explicitly accepted tradeoff for a dependency-free, Node-only\n * implementation identical across CLI and desktop.\n */\n\nexport interface NetworkContainmentProxy {\n port: number\n close: () => Promise<void>\n}\n\nconst MAX_HEADER_BYTES = 16_384\n\nfunction hostAllowed(host: string, allowlist: readonly string[]): boolean {\n const normalized = host.toLowerCase()\n return allowlist.some((entry) => {\n const allowed = entry.toLowerCase()\n return normalized === allowed || normalized.endsWith(`.${allowed}`)\n })\n}\n\nfunction parseConnectTarget(requestLine: string): { host: string; port: number } | null {\n const match = /^CONNECT\\s+([^:\\s]+):(\\d+)\\s+HTTP/i.exec(requestLine)\n return match ? { host: match[1], port: Number(match[2]) } : null\n}\n\nfunction parsePlainHttpTarget(requestLine: string, headerText: string): { host: string; port: number } | null {\n const absoluteUri = /^[A-Z]+\\s+https?:\\/\\/([^/:\\s]+)(?::(\\d+))?/i.exec(requestLine)\n if (absoluteUri) return { host: absoluteUri[1], port: Number(absoluteUri[2] ?? 80) }\n\n const hostHeader = /^host:\\s*([^\\s:]+)(?::(\\d+))?/im.exec(headerText)\n return hostHeader ? { host: hostHeader[1], port: Number(hostHeader[2] ?? 80) } : null\n}\n\nfunction handleConnection(clientSocket: Socket, allowlist: readonly string[]): void {\n let buffered = Buffer.alloc(0)\n\n const onData = (chunk: Buffer): void => {\n buffered = Buffer.concat([buffered, chunk])\n const headerEnd = buffered.indexOf('\\r\\n\\r\\n')\n if (headerEnd === -1) {\n if (buffered.length > MAX_HEADER_BYTES) clientSocket.destroy()\n return\n }\n clientSocket.removeListener('data', onData)\n // With no 'data' listener a flowing socket silently drops what arrives next; hold it (e.g. the\n // rest of a plain-HTTP request body) until the upstream connection exists and pipe() resumes it.\n clientSocket.pause()\n\n const headerText = buffered.slice(0, headerEnd).toString('utf-8')\n const requestLine = headerText.split('\\r\\n')[0] ?? ''\n const isConnect = /^CONNECT\\s/i.test(requestLine)\n const target = isConnect ? parseConnectTarget(requestLine) : parsePlainHttpTarget(requestLine, headerText)\n\n if (!target || !hostAllowed(target.host, allowlist)) {\n clientSocket.end('HTTP/1.1 403 Forbidden\\r\\nContent-Length: 0\\r\\n\\r\\n')\n return\n }\n\n const upstream = netConnect(target.port, target.host, () => {\n if (isConnect) {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n\\r\\n')\n const tunnelBytes = buffered.slice(headerEnd + 4)\n if (tunnelBytes.length > 0) upstream.write(tunnelBytes)\n } else {\n upstream.write(buffered)\n }\n clientSocket.pipe(upstream)\n upstream.pipe(clientSocket)\n })\n upstream.on('error', () => clientSocket.destroy())\n // pipe() does not tear down the other side on an error or a premature close; without this a\n // client that vanishes leaves its upstream socket open indefinitely.\n clientSocket.on('close', () => upstream.destroy())\n }\n\n clientSocket.on('data', onData)\n clientSocket.on('error', () => clientSocket.destroy())\n}\n\nfunction startProxyServer(allowlist: readonly string[]): Promise<NetworkContainmentProxy> {\n return new Promise((resolveStart, rejectStart) => {\n const server: Server = createServer((socket) => handleConnection(socket, allowlist))\n server.on('error', rejectStart)\n server.listen(0, '127.0.0.1', () => {\n const address = server.address()\n if (address === null || typeof address === 'string') {\n rejectStart(new Error('Failed to bind network containment proxy to a loopback port'))\n return\n }\n resolveStart({\n port: address.port,\n close: () => new Promise((resolveClose) => server.close(() => resolveClose())),\n })\n })\n })\n}\n\n/**\n * Lazily starts (or reuses) a loopback-only proxy scoped to `allowlist`, keyed by its\n * (order-independent, case-insensitive) contents so repeated calls with the same allowlist reuse\n * one long-lived proxy instead of spawning a new server per shell command. Left running for the\n * process's lifetime — acceptable for a CLI/desktop session, not meant to be torn down mid-run.\n */\nconst proxyCache = new Map<string, Promise<NetworkContainmentProxy>>()\n\nexport function getNetworkContainmentProxy(allowlist: readonly string[]): Promise<NetworkContainmentProxy> {\n const key = JSON.stringify([...allowlist].map((host) => host.toLowerCase()).sort())\n let proxy = proxyCache.get(key)\n if (!proxy) {\n proxy = startProxyServer(allowlist)\n proxyCache.set(key, proxy)\n }\n return proxy\n}\n\n/** Test-only: drops all cached proxies so a test's allowlist doesn't leak into another test's expectations. */\nexport async function resetNetworkContainmentProxiesForTests(): Promise<void> {\n const proxies = [...proxyCache.values()]\n proxyCache.clear()\n for (const proxyPromise of proxies) {\n const proxy = await proxyPromise\n await proxy.close()\n }\n}\n","import { spawn } from 'node:child_process'\nimport type { ShellExecutionResult } from './file-tools.js'\nimport type { ShellCommandExecutor } from './shell-tools.js'\nimport { getNetworkContainmentProxy } from './network-containment.js'\n\n/**\n * The real child_process.spawn-based implementation of ShellCommandExecutor — deliberately\n * not exported from this package's index (mirrors node-fs-backend.ts): assistant.ts is bundled\n * into the browser build too, so only a Node-only caller (cli.ts) may import this module and\n * wire it in as PersonalAssistantOptions.shellTools.executeCommand.\n */\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_OUTPUT_BYTES = 20_000\n/** Never the parent process's full env (which would carry ASSISTANT_PROXY_TOKEN/ANTHROPIC_API_KEY/etc. into the command) — only these three. */\nconst ALLOWED_ENV_VARS = ['PATH', 'HOME', 'LANG'] as const\n\nfunction allowlistedEnv(): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {}\n for (const key of ALLOWED_ENV_VARS) {\n const value = process.env[key]\n if (value !== undefined) env[key] = value\n }\n return env\n}\n\n/**\n * Forces the child's HTTP(S)_PROXY env vars at a loopback-only containment proxy scoped to\n * `networkAllowlist` (see network-containment.ts) — Decision 6's network-reachability half,\n * alongside allowlistedEnv()'s existing secret-stripping half. An empty/undefined allowlist still\n * starts the proxy, just with nothing in it, so every attempt is refused with a 403 rather than\n * skipping containment entirely — deny-all is the safe default until the user opts a host in.\n *\n * Deliberately does NOT set NO_PROXY/no_proxy for 127.0.0.1/localhost: most HTTP clients (curl\n * included) skip the configured proxy entirely for any host listed in NO_PROXY, which would let a\n * command reach an arbitrary loopback service (a local metadata endpoint, an unauthenticated\n * internal API, a Docker socket proxy) without ever going through the allowlist check — a\n * loopback target is not inherently safe and must be subject to the same allowlist as anything\n * else. The one loopback address that does need to stay reachable unconditionally is the\n * containment proxy's own listener, which this env never routes through itself (a client connects\n * to it directly via the proxy env vars, not through the proxy), so no exemption is needed there.\n */\nasync function networkContainmentEnv(networkAllowlist: readonly string[]): Promise<NodeJS.ProcessEnv> {\n const proxy = await getNetworkContainmentProxy(networkAllowlist)\n const proxyUrl = `http://127.0.0.1:${proxy.port}`\n return {\n HTTP_PROXY: proxyUrl,\n http_proxy: proxyUrl,\n HTTPS_PROXY: proxyUrl,\n https_proxy: proxyUrl,\n }\n}\n\nfunction truncateOutput(text: string, maxBytes: number): string {\n const encoded = new TextEncoder().encode(text)\n if (encoded.length <= maxBytes) return text\n const truncated = new TextDecoder('utf-8', { fatal: false }).decode(encoded.slice(0, maxBytes))\n return `${truncated}\\n… (truncated)`\n}\n\n/**\n * Actually runs a previously staged, already-sandboxed command — the real child_process.spawn call,\n * invoked only at approval time via file-tools.ts's applyPendingAction(..., { executeShell }). `cwd`\n * is pinned to the staged (already-validated) path; `env` is reduced to an explicit allowlist so a\n * secret like ASSISTANT_PROXY_TOKEN/ANTHROPIC_API_KEY can't leak into the command's environment,\n * plus network-containment.ts's loopback-only proxy forced via HTTP(S)_PROXY (Decision 6 — see\n * networkContainmentEnv's doc comment). A hard timeout SIGKILLs the whole process group (not just\n * the immediate child — `detached: true` + a negative-pid kill reaches anything the shell itself\n * spawned) rather than leaving it running. A non-zero exit code is not a thrown error — it's\n * reported normally, same as a real shell; only a spawn failure (e.g. the shell itself couldn't\n * start) throws.\n */\nexport const runApprovedShellCommand: ShellCommandExecutor = async (\n command: string,\n cwd: string,\n options: { timeoutMs?: number; maxOutputBytes?: number; networkAllowlist?: string[] } = {},\n): Promise<ShellExecutionResult> => {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES\n const containmentEnv = await networkContainmentEnv(options.networkAllowlist ?? [])\n\n return new Promise((resolvePromise, reject) => {\n const proc = spawn(command, {\n shell: true,\n cwd,\n env: { ...allowlistedEnv(), ...containmentEnv },\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n let output = ''\n let timedOut = false\n let settled = false\n\n const finish = (exitCode: number | null): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolvePromise({\n output: truncateOutput(output, maxOutputBytes),\n exitCode: timedOut ? null : exitCode,\n timedOut,\n })\n }\n\n const timer = setTimeout(() => {\n timedOut = true\n try {\n if (proc.pid) process.kill(-proc.pid, 'SIGKILL')\n else proc.kill('SIGKILL')\n } catch {\n proc.kill('SIGKILL')\n }\n // 'close' waits for every stdout/stderr pipe to end; a descendant that left the process group\n // (setsid) keeps them open and would otherwise leave this promise pending forever.\n setTimeout(() => {\n proc.stdout?.destroy()\n proc.stderr?.destroy()\n finish(null)\n }, 2000).unref?.()\n }, timeoutMs)\n\n // Keep only what truncateOutput could ever return (plus a little slack for multi-byte chars):\n // a command that floods stdout for the whole timeout must not grow this string without bound.\n const append = (chunk: Buffer): void => {\n if (output.length <= maxOutputBytes * 2) output += chunk.toString('utf-8')\n }\n proc.stdout?.on('data', append)\n proc.stderr?.on('data', append)\n proc.on('error', (err: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(err)\n })\n proc.on('close', (exitCode: number | null) => finish(exitCode))\n })\n}\n","import { readFile, writeFile, rename, mkdir } from 'node:fs/promises'\nimport { randomBytes } from 'node:crypto'\nimport { dirname } from 'node:path'\nimport type { AssistantConfig, ConfigStore } from './config.js'\n\nfunction isEnoent(err: unknown): boolean {\n return (err as NodeJS.ErrnoException)?.code === 'ENOENT'\n}\n\n/**\n * JSON-file-backed ConfigStore for the CLI, at a single `config.json` path (typically\n * `<dataDir>/config.json`). Deliberately not exported from this package's index — only cli.ts\n * imports it, same reasoning as node-fs-backend.ts — so a browser build never pulls in\n * node:fs/promises.\n *\n * save() merges the patch onto whatever's already persisted (never a blind overwrite of\n * unrelated keys) and writes through a temp-file-then-rename so a crash mid-write can never\n * leave a half-written config.json behind — the same failure mode file-tools.ts's\n * .pending-actions staging already avoids the same way. Setting a key to `undefined` in a\n * patch removes it from the persisted file (JSON.stringify drops undefined-valued\n * properties), which is what /config reset relies on.\n *\n * Concurrent save() calls on the same instance are serialized through an internal queue —\n * cli.ts's readline 'line' handler doesn't wait for one command to finish before dispatching\n * the next (e.g. piped stdin with two /config set lines back to back), so without this a\n * second save()'s load-modify-write could race the first's: reading stale state before the\n * first's write lands and silently clobbering it, or (with a timestamp-only temp filename)\n * colliding on the exact same temp path within the same millisecond.\n */\nexport class NodeConfigStore implements ConfigStore {\n private queue: Promise<unknown> = Promise.resolve()\n\n constructor(private readonly path: string) {}\n\n async load(): Promise<Partial<AssistantConfig>> {\n let raw: string\n try {\n raw = await readFile(this.path, 'utf-8')\n } catch (err) {\n if (isEnoent(err)) return {}\n throw err\n }\n try {\n const parsed: unknown = JSON.parse(raw)\n // `null`, a number or an array parses fine but is not a config object; treat it like corrupt JSON.\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('not an object')\n return parsed as Partial<AssistantConfig>\n } catch {\n console.error(`Warning: ${this.path} is not valid JSON — ignoring it and falling back to defaults.`)\n return {}\n }\n }\n\n save(patch: Partial<AssistantConfig>): Promise<void> {\n const task = this.queue.then(() => this.writePatch(patch))\n // A failed save must not poison the queue for saves queued after it.\n this.queue = task.catch(() => {})\n return task\n }\n\n private async writePatch(patch: Partial<AssistantConfig>): Promise<void> {\n const existing = await this.load()\n const merged = { ...existing, ...patch }\n await mkdir(dirname(this.path), { recursive: true, mode: 0o700 })\n const tempPath = `${this.path}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`\n // The file holds API keys and the SMTP password in plain text: owner-only, never world-readable (the temp file is\n // new on every save, so the mode always applies and the rename carries it over the old, possibly 0644, file).\n await writeFile(tempPath, JSON.stringify(merged, null, 2), { encoding: 'utf-8', mode: 0o600 })\n await rename(tempPath, this.path)\n }\n}\n","import { stat } from 'node:fs/promises'\nimport { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport type { FsBackend } from '@buildaharness/runtime'\nimport { memoryStatusChecks, type DoctorCheck } from './cli-session.js'\nimport { redactUrlCredentials } from './cli-config.js'\nimport type { MemoryStatus } from './memory-service.js'\n\n/**\n * Real I/O backing /doctor's checks (network fetch, subprocess spawn, filesystem stat) —\n * split out of cli.ts, deliberately not exported from this package's index (mirrors\n * shell-executor.ts/node-fs-backend.ts): only cli.ts, a Node-only caller, imports this.\n * cli-session.ts's formatDoctorReport does the actual rendering — this file only produces\n * the DoctorCheck[] input to that.\n */\n\nconst DOCTOR_CHECK_TIMEOUT_MS = 3000\n\n/** GET <proxyUrl>/health, expecting {status:'ok'} (see packages/proxy/src/index.ts) — hard-timed so a dead proxy can't hang /doctor. */\nexport async function checkProxyHealth(proxyUrl: string): Promise<DoctorCheck> {\n const label = `proxy reachable (${redactUrlCredentials(proxyUrl)}/health)`\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), DOCTOR_CHECK_TIMEOUT_MS)\n try {\n const res = await fetch(`${proxyUrl}/health`, { signal: controller.signal })\n if (!res.ok) return { label, ok: false, detail: `HTTP ${res.status}` }\n const body = (await res.json().catch(() => undefined)) as { status?: string } | undefined\n return body?.status === 'ok' ? { label, ok: true } : { label, ok: false, detail: 'unexpected response body' }\n } catch (err) {\n const timedOut = err instanceof Error && err.name === 'AbortError'\n return { label, ok: false, detail: timedOut ? 'timed out' : err instanceof Error ? err.message : String(err) }\n } finally {\n clearTimeout(timeout)\n }\n}\n\n/** Spawns `<claudePath> --version`, same path resolution ClaudeCliLLMClient uses — hard-timed so a hung/missing binary can't hang /doctor. */\nexport function checkClaudeCli(claudePath: string): Promise<DoctorCheck> {\n const label = `claude binary (${claudePath})`\n return new Promise((resolvePromise) => {\n let settled = false\n const proc = spawn(claudePath, ['--version'], { stdio: ['ignore', 'ignore', 'ignore'] })\n const timeout = setTimeout(() => {\n if (settled) return\n settled = true\n proc.kill()\n resolvePromise({ label, ok: false, detail: 'timed out' })\n }, DOCTOR_CHECK_TIMEOUT_MS)\n proc.on('error', () => {\n if (settled) return\n settled = true\n clearTimeout(timeout)\n resolvePromise({ label, ok: false, detail: 'not found' })\n })\n proc.on('close', (code) => {\n if (settled) return\n settled = true\n clearTimeout(timeout)\n resolvePromise({ label, ok: code === 0, detail: code === 0 ? undefined : `exited with code ${code}` })\n })\n })\n}\n\n/** M6: memory store size vs budget, pending count, last consolidation, audit-log size. The rendering is the shared pure `memoryStatusChecks` (chat-ui calls it too). */\nexport function checkMemoryHealth(status: MemoryStatus): DoctorCheck[] {\n return memoryStatusChecks(status)\n}\n\nexport async function checkWorkspaceRoot(workspaceRoot: string): Promise<DoctorCheck> {\n const label = `workspace root exists (${workspaceRoot})`\n try {\n const info = await stat(workspaceRoot)\n return info.isDirectory() ? { label, ok: true } : { label, ok: false, detail: 'not a directory' }\n } catch {\n return { label, ok: false, detail: 'not found' }\n }\n}\n\nexport async function checkDataDirWritable(backend: FsBackend, dataDir: string): Promise<DoctorCheck> {\n const label = `data dir writable (${dataDir})`\n const probePath = join(dataDir, '.doctor-check')\n try {\n await backend.mkdir(dataDir)\n await backend.writeTextFile(probePath, 'ok')\n await backend.removeFile(probePath)\n return { label, ok: true }\n } catch (err) {\n return { label, ok: false, detail: err instanceof Error ? err.message : String(err) }\n }\n}\n","export type NonInteractiveApprovalMode = 'decline' | 'require-tty'\n\n/**\n * Pure logic backing cli.ts's ASSISTANT_NON_INTERACTIVE_APPROVAL handling — split out so it's\n * unit-testable in isolation, the same way error-classifier.ts and node-display-names.ts are\n * split out of cli.ts for the same reason (cli.ts runs `main()` at import time, so it can't be\n * imported directly by a test).\n *\n * Turns the piped/scripted-stdin approval-gate behavior into an explicit, documented choice\n * instead of an incidental side effect of readline hitting closed stdin (see cli.ts's askYesNo,\n * whose fail-closed catch stays the unset-env-var default and is unaffected by this — nothing\n * changes for an interactive TTY session either way). 'decline': every approval gate\n * auto-declines immediately, without ever touching stdin — the right choice for a scripted/CI\n * caller that expects every HIGH-risk/staged action to be rejected outright, no exceptions.\n * 'require-tty': cli.ts fails fast at startup with a clear, actionable error if stdin isn't a\n * real TTY, instead of running an entire session that can only surface the problem deep in, at\n * the first approval prompt, as a generic \"[could not read a response]\". An unrecognized value is\n * ignored (falls back to unset) with a startup warning, so a typo can't silently produce\n * different behavior than intended — mirrors ASSISTANT_LLM_BACKEND's own typo-tolerance in\n * cli-config.ts, but warns here since a silently-ignored approval-mode typo is safety-relevant in\n * a way a silently-ignored backend typo (which still resolves to a working default) isn't.\n */\nexport function resolveNonInteractiveApprovalMode(env: NodeJS.ProcessEnv): NonInteractiveApprovalMode | undefined {\n const raw = env.ASSISTANT_NON_INTERACTIVE_APPROVAL\n if (raw === undefined) return undefined\n if (raw === 'decline' || raw === 'require-tty') return raw\n console.error(`[warning] ASSISTANT_NON_INTERACTIVE_APPROVAL=\"${raw}\" is not \"decline\" or \"require-tty\" — ignoring.`)\n return undefined\n}\n","var Te=Object.defineProperty;var In=(e,n,t)=>n in e?Te(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var Sn=(e,n)=>{for(var t in n)Te(e,t,{get:n[t],enumerable:!0})};var je=(e,n,t)=>In(e,typeof n!=\"symbol\"?n+\"\":n,t);var ie={};Sn(ie,{Graph:()=>T,alg:()=>H});var Mn=Object.defineProperty,Se=(e,n)=>{for(var t in n)Mn(e,t,{get:n[t],enumerable:!0})},Q=class{constructor(e){this._isDirected=!0,this._isMultigraph=!1,this._isCompound=!1,this._nodes={},this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={},this._nodeCount=0,this._edgeCount=0,this._defaultNodeLabelFn=()=>{},this._defaultEdgeLabelFn=()=>{},e&&(this._isDirected=\"directed\"in e?e.directed:!0,this._isMultigraph=\"multigraph\"in e?e.multigraph:!1,this._isCompound=\"compound\"in e?e.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[\"\\0\"]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return typeof e!=\"function\"?this._defaultNodeLabelFn=()=>e:this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){return this.nodes().filter(e=>Object.keys(this._in[e]).length===0)}sinks(){return this.nodes().filter(e=>Object.keys(this._out[e]).length===0)}setNodes(e,n){return e.forEach(t=>{n!==void 0?this.setNode(t,n):this.setNode(t)}),this}setNode(e,n){return e in this._nodes?(arguments.length>1&&(this._nodes[e]=n),this):(this._nodes[e]=arguments.length>1?n:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=\"\\0\",this._children[e]={},this._children[\"\\0\"][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return e in this._nodes}removeNode(e){if(e in this._nodes){let n=t=>this.removeEdge(this._edgeObjs[t]);delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],this.children(e).forEach(t=>{this.setParent(t)}),delete this._children[e]),Object.keys(this._in[e]).forEach(n),delete this._in[e],delete this._preds[e],Object.keys(this._out[e]).forEach(n),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,n){if(!this._isCompound)throw new Error(\"Cannot set parent in a non-compound graph\");if(n===void 0)n=\"\\0\";else{n+=\"\";for(let t=n;t!==void 0;t=this.parent(t))if(t===e)throw new Error(\"Setting \"+n+\" as parent of \"+e+\" would create a cycle\");this.setNode(n)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=n,this._children[n][e]=!0,this}parent(e){if(this._isCompound){let n=this._parent[e];if(n!==\"\\0\")return n}}children(e=\"\\0\"){if(this._isCompound){let n=this._children[e];if(n)return Object.keys(n)}else{if(e===\"\\0\")return this.nodes();if(this.hasNode(e))return[]}return[]}predecessors(e){let n=this._preds[e];if(n)return Object.keys(n)}successors(e){let n=this._sucs[e];if(n)return Object.keys(n)}neighbors(e){let n=this.predecessors(e);if(n){let t=new Set(n),r=this.successors(e);if(r)for(let o of r)t.add(o);return Array.from(t.values())}}isLeaf(e){var n;let t;return this.isDirected()?t=this.successors(e):t=this.neighbors(e),((n=t==null?void 0:t.length)!=null?n:0)===0}filterNodes(e){let n=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});n.setGraph(this.graph()),Object.entries(this._nodes).forEach(([o,i])=>{e(o)&&n.setNode(o,i)}),Object.values(this._edgeObjs).forEach(o=>{n.hasNode(o.v)&&n.hasNode(o.w)&&n.setEdge(o,this.edge(o))});let t={},r=o=>{let i=this.parent(o);return!i||n.hasNode(i)?(t[o]=i,i):i in t?t[i]:r(i)};return this._isCompound&&n.nodes().forEach(o=>n.setParent(o,r(o))),n}setDefaultEdgeLabel(e){return typeof e!=\"function\"?this._defaultEdgeLabelFn=()=>e:this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(e,n){return e.reduce((t,r)=>(n!==void 0?this.setEdge(t,r,n):this.setEdge(t,r),r)),this}setEdge(e,n,t,r){let o,i,s,a,l=!1;typeof e==\"object\"&&e!==null&&\"v\"in e?(o=e.v,i=e.w,s=e.name,arguments.length===2&&(a=n,l=!0)):(o=e,i=n,s=r,arguments.length>2&&(a=t,l=!0)),o=\"\"+o,i=\"\"+i,s!==void 0&&(s=\"\"+s);let u=z(this._isDirected,o,i,s);if(u in this._edgeLabels)return l&&(this._edgeLabels[u]=a),this;if(s!==void 0&&!this._isMultigraph)throw new Error(\"Cannot set a named edge when isMultigraph = false\");this.setNode(o),this.setNode(i),this._edgeLabels[u]=l?a:this._defaultEdgeLabelFn(o,i,s);let d=Pn(this._isDirected,o,i,s);return o=d.v,i=d.w,Object.freeze(d),this._edgeObjs[u]=d,Re(this._preds[i],o),Re(this._sucs[o],i),this._in[i][u]=d,this._out[o][u]=d,this._edgeCount++,this}edge(e,n,t){let r=arguments.length===1?oe(this._isDirected,e):z(this._isDirected,e,n,t);return this._edgeLabels[r]}edgeAsObj(e,n,t){let r=arguments.length===1?this.edge(e):this.edge(e,n,t);return typeof r!=\"object\"||r===null?{label:r}:r}hasEdge(e,n,t){return(arguments.length===1?oe(this._isDirected,e):z(this._isDirected,e,n,t))in this._edgeLabels}removeEdge(e,n,t){let r=arguments.length===1?oe(this._isDirected,e):z(this._isDirected,e,n,t),o=this._edgeObjs[r];if(o){let i=o.v,s=o.w;delete this._edgeLabels[r],delete this._edgeObjs[r],Ie(this._preds[s],i),Ie(this._sucs[i],s),delete this._in[s][r],delete this._out[i][r],this._edgeCount--}return this}inEdges(e,n){return this.isDirected()?this.filterEdges(this._in[e],e,n):this.nodeEdges(e,n)}outEdges(e,n){return this.isDirected()?this.filterEdges(this._out[e],e,n):this.nodeEdges(e,n)}nodeEdges(e,n){if(e in this._nodes)return this.filterEdges({...this._in[e],...this._out[e]},e,n)}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}filterEdges(e,n,t){if(!e)return;let r=Object.values(e);return t?r.filter(o=>o.v===n&&o.w===t||o.v===t&&o.w===n):r}};function Re(e,n){e[n]?e[n]++:e[n]=1}function Ie(e,n){e[n]!==void 0&&!--e[n]&&delete e[n]}function z(e,n,t,r){let o=\"\"+n,i=\"\"+t;if(!e&&o>i){let s=o;o=i,i=s}return o+\"\u0001\"+i+\"\u0001\"+(r===void 0?\"\\0\":r)}function Pn(e,n,t,r){let o=\"\"+n,i=\"\"+t;if(!e&&o>i){let a=o;o=i,i=a}let s={v:o,w:i};return r&&(s.name=r),s}function oe(e,n){return z(e,n.v,n.w,n.name)}var Fn={};Se(Fn,{read:()=>Yn,write:()=>An});function An(e){let n={options:{directed:e.isDirected(),multigraph:e.isMultigraph(),compound:e.isCompound()},nodes:Vn(e),edges:Dn(e)},t=e.graph();return t!==void 0&&(n.value=structuredClone(t)),n}function Vn(e){return e.nodes().map(n=>{let t=e.node(n),r=e.parent(n),o={v:n};return t!==void 0&&(o.value=t),r!==void 0&&(o.parent=r),o})}function Dn(e){return e.edges().map(n=>{let t=e.edge(n),r={v:n.v,w:n.w};return n.name!==void 0&&(r.name=n.name),t!==void 0&&(r.value=t),r})}function Yn(e){let n=new Q(e.options);return e.value!==void 0&&n.setGraph(e.value),e.nodes.forEach(t=>{n.setNode(t.v,t.value),t.parent&&n.setParent(t.v,t.parent)}),e.edges.forEach(t=>{n.setEdge({v:t.v,w:t.w,name:t.name},t.value)}),n}var H={};Se(H,{CycleException:()=>K,bellmanFord:()=>Me,components:()=>Xn,dijkstra:()=>J,dijkstraAll:()=>qn,findCycles:()=>$n,floydWarshall:()=>Jn,isAcyclic:()=>Qn,postorder:()=>et,preorder:()=>nt,prim:()=>tt,shortestPaths:()=>rt,tarjan:()=>Fe,topsort:()=>Ae});var Wn=()=>1;function Me(e,n,t,r){return Bn(e,String(n),t||Wn,r||function(o){var i;return(i=e.outEdges(o))!=null?i:[]})}function Bn(e,n,t,r){let o={},i,s=0,a=e.nodes(),l=function(c){let f=o[c.v],h=o[c.w];if(!f||!h)return;let p=t(c);f.distance+p<h.distance&&(o[c.w]={distance:f.distance+p,predecessor:c.v},i=!0)},u=function(){a.forEach(function(c){r(c).forEach(function(f){let h=f.v===c?f.v:f.w,p=h===f.v?f.w:f.v;l({v:h,w:p})})})};a.forEach(function(c){let f=c===n?0:Number.POSITIVE_INFINITY;o[c]={distance:f,predecessor:\"\"}});let d=a.length;for(let c=1;c<d&&(i=!1,s++,u(),!!i);c++);if(s===d-1&&(i=!1,u(),i))throw new Error(\"The graph contains a negative weight cycle\");return o}function Xn(e){let n={},t=[],r;function o(i){var s,a;i in n||(n[i]=!0,r.push(i),(s=e.successors(i))==null||s.forEach(o),(a=e.predecessors(i))==null||a.forEach(o))}return e.nodes().forEach(function(i){r=[],o(i),r.length&&t.push(r)}),t}var Pe=class{constructor(){this._arr=[],this._keyIndices={}}size(){return this._arr.length}keys(){return this._arr.map(e=>e.key)}has(e){return e in this._keyIndices}priority(e){let n=this._keyIndices[e];if(n!==void 0)return this._arr[n].priority}min(){if(this.size()===0)throw new Error(\"Queue underflow\");return this._arr[0].key}add(e,n){let t=this._keyIndices,r=String(e);if(!(r in t)){let o=this._arr,i=o.length;return t[r]=i,o.push({key:r,priority:n}),this._decrease(i),!0}return!1}removeMin(){if(this.size()===0)throw new Error(\"Queue underflow\");this._swap(0,this._arr.length-1);let e=this._arr.pop();return delete this._keyIndices[e.key],this._heapify(0),e.key}decrease(e,n){let t=this._keyIndices[e];if(t===void 0)throw new Error(`Key not found: ${e}`);let r=this._arr[t].priority;if(n>r)throw new Error(`New priority is greater than current priority. Key: ${e} Old: ${r} New: ${n}`);this._arr[t].priority=n,this._decrease(t)}_heapify(e){let n=this._arr,t=2*e,r=t+1,o=e;t<n.length&&(o=n[t].priority<n[o].priority?t:o,r<n.length&&(o=n[r].priority<n[o].priority?r:o),o!==e&&(this._swap(e,o),this._heapify(o)))}_decrease(e){let n=this._arr,t=n[e].priority,r;for(;e!==0&&(r=e>>1,!(n[r].priority<t));)this._swap(e,r),e=r}_swap(e,n){let t=this._arr,r=this._keyIndices,o=t[e],i=t[n];t[e]=i,t[n]=o,r[i.key]=e,r[o.key]=n}},zn=()=>1;function J(e,n,t,r){let o=function(i){var s;return(s=e.outEdges(i))!=null?s:[]};return Hn(e,String(n),t||zn,r||o)}function Hn(e,n,t,r){let o={},i=new Pe,s,a,l=function(u){let d=u.v!==s?u.v:u.w,c=o[d];if(!c)return;let f=t(u),h=a.distance+f;if(f<0)throw new Error(\"dijkstra does not allow negative edge weights. Bad edge: \"+u+\" Weight: \"+f);h<c.distance&&(c.distance=h,c.predecessor=s,i.decrease(d,h))};for(e.nodes().forEach(function(u){let d=u===n?0:Number.POSITIVE_INFINITY;o[u]={distance:d,predecessor:\"\"},i.add(u,d)});i.size()>0;){s=i.removeMin();let u=o[s];if(!u||u.distance===Number.POSITIVE_INFINITY)break;a=u,r(s).forEach(l)}return o}function qn(e,n,t){return e.nodes().reduce(function(r,o){return r[o]=J(e,o,n,t),r},{})}function Fe(e){let n=0,t=[],r={},o=[];function i(s){var a;let l=r[s]={onStack:!0,lowlink:n,index:n++};if(t.push(s),(a=e.successors(s))==null||a.forEach(function(u){if(u in r){let d=r[u];d!=null&&d.onStack&&(l.lowlink=Math.min(l.lowlink,d.index))}else{i(u);let d=r[u];d&&(l.lowlink=Math.min(l.lowlink,d.lowlink))}}),l.lowlink===l.index){let u=[],d;do{d=t.pop();let c=r[d];c&&(c.onStack=!1),u.push(d)}while(s!==d);o.push(u)}}return e.nodes().forEach(function(s){s in r||i(s)}),o}function $n(e){return Fe(e).filter(function(n){var t;let r=n[0];return r?n.length>1||n.length===1&&((t=e.outEdges(r,r))!=null?t:[]).length>0:!1})}var Un=()=>1;function Jn(e,n,t){return Kn(e,n||Un,t||function(r){var o;return(o=e.outEdges(r))!=null?o:[]})}function Kn(e,n,t){let r={},o=e.nodes();return o.forEach(function(i){let s={};r[i]=s,s[i]={distance:0,predecessor:\"\"},o.forEach(function(a){i!==a&&(s[a]={distance:Number.POSITIVE_INFINITY,predecessor:\"\"})}),t(i).forEach(function(a){let l=a.v===i?a.w:a.v,u=n(a);s[l]={distance:u,predecessor:i}})}),o.forEach(function(i){let s=r[i];s&&o.forEach(function(a){let l=r[a];l&&o.forEach(function(u){let d=l[i],c=s[u],f=l[u];if(d&&c&&f){let h=d.distance+c.distance;h<f.distance&&(f.distance=h,f.predecessor=c.predecessor)}})})}),r}var K=class extends Error{constructor(e){super(e),this.name=\"CycleException\"}};function Ae(e){let n={},t={},r=[];function o(i){var s;if(i in t)throw new K;i in n||(t[i]=!0,n[i]=!0,(s=e.predecessors(i))==null||s.forEach(o),delete t[i],r.push(i))}if(e.sinks().forEach(o),Object.keys(n).length!==e.nodeCount())throw new K;return r}function Qn(e){try{Ae(e)}catch(n){if(n instanceof K)return!1;throw n}return!0}function Zn(e,n,t,r,o){Array.isArray(n)||(n=[n]);let i=(a=>{var l;return(l=e.isDirected()?e.successors(a):e.neighbors(a))!=null?l:[]}),s={};return n.forEach(function(a){if(!e.hasNode(a))throw new Error(\"Graph does not have node: \"+a);o=Ve(e,a,t===\"post\",s,i,r,o)}),o}function Ve(e,n,t,r,o,i,s){return n in r||(r[n]=!0,t||(s=i(s,n)),o(n).forEach(function(a){s=Ve(e,a,t,r,o,i,s)}),t&&(s=i(s,n))),s}function De(e,n,t){return Zn(e,n,t,function(r,o){return r.push(o),r},[])}function et(e,n){return De(e,n,\"post\")}function nt(e,n){return De(e,n,\"pre\")}function tt(e,n){var t;let r=new Q,o={},i=new Pe,s;function a(d){let c=d.v===s?d.w:d.v,f=i.priority(c);if(f!==void 0){let h=n(d);h<f&&(o[c]=s,i.decrease(c,h))}}if(e.nodeCount()===0)return r;e.nodes().forEach(function(d){i.add(d,Number.POSITIVE_INFINITY),r.setNode(d)});let l=e.nodes()[0];l!==void 0&&i.decrease(l,0);let u=!1;for(;i.size()>0;){if(s=i.removeMin(),s in o)r.setEdge(s,o[s]);else{if(u)throw new Error(\"Input graph is not connected: \"+e);u=!0}(t=e.nodeEdges(s))==null||t.forEach(a)}return r}function rt(e,n,t,r){return ot(e,n,t,r!=null?r:(o=>{var i;return(i=e.outEdges(o))!=null?i:[]}))}function ot(e,n,t,r){if(t===void 0)return J(e,n,t,r);let o=!1,i=e.nodes();for(let s=0;s<i.length;s++){let a=i[s];if(a===void 0)continue;let l=r(a);for(let u=0;u<l.length;u++){let d=l[u];if(!d)continue;let c=d.v===a?d.v:d.w,f=c===d.v?d.w:d.v;t({v:c,w:f})<0&&(o=!0)}if(o)return Me(e,n,t,r)}return J(e,n,t,r)}var T=Q;function M(e,n,t,r){let o=r;for(;e.hasNode(o);)o=$(r);return t.dummy=n,e.setNode(o,t),o}function Ye(e){let n=new T().setGraph(e.graph());return e.nodes().forEach(t=>n.setNode(t,e.node(t))),e.edges().forEach(t=>{let r=n.edge(t.v,t.w)||{weight:0,minlen:1},o=e.edge(t);n.setEdge(t.v,t.w,{weight:r.weight+o.weight,minlen:Math.max(r.minlen,o.minlen)})}),n}function Z(e){let n=new T({multigraph:e.isMultigraph()}).setGraph(e.graph());return e.nodes().forEach(t=>{e.children(t).length||n.setNode(t,e.node(t))}),e.edges().forEach(t=>{n.setEdge(t,e.edge(t))}),n}function se(e,n){let t=e.x,r=e.y,o=n.x-t,i=n.y-r,s=e.width/2,a=e.height/2;if(!o&&!i)throw new Error(\"Not possible to find intersection inside of the rectangle\");let l,u;return Math.abs(i)*s>Math.abs(o)*a?(i<0&&(a=-a),l=a*o/i,u=a):(o<0&&(s=-s),l=s,u=s*i/o),{x:t+l,y:r+u}}function P(e){let n=A(de(e)+1).map(()=>[]);return e.nodes().forEach(t=>{let r=e.node(t),o=r.rank;o!==void 0&&(n[o]||(n[o]=[]),n[o][r.order]=t)}),n}function We(e){let n=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MAX_VALUE:o}),t=R(Math.min,n);e.nodes().forEach(r=>{let o=e.node(r);Object.hasOwn(o,\"rank\")&&(o.rank-=t)})}function Be(e){let n=e.nodes().map(s=>e.node(s).rank).filter(s=>s!==void 0),t=R(Math.min,n),r=[];e.nodes().forEach(s=>{let a=e.node(s).rank-t;r[a]||(r[a]=[]),r[a].push(s)});let o=0,i=e.graph().nodeRankFactor;Array.from(r).forEach((s,a)=>{s===void 0&&a%i!==0?--o:s!==void 0&&o&&s.forEach(l=>e.node(l).rank+=o)})}function ae(e,n,t,r){let o={width:0,height:0};return arguments.length>=4&&(o.rank=t,o.order=r),M(e,\"border\",o,n)}function it(e,n=Xe){let t=[];for(let r=0;r<e.length;r+=n){let o=e.slice(r,r+n);t.push(o)}return t}var Xe=65535;function R(e,n){if(n.length>Xe){let t=it(n);return e(...t.map(r=>e(...r)))}else return e(...n)}function de(e){let t=e.nodes().map(r=>{let o=e.node(r).rank;return o===void 0?Number.MIN_VALUE:o});return R(Math.max,t)}function ze(e,n){let t={lhs:[],rhs:[]};return e.forEach(r=>{n(r)?t.lhs.push(r):t.rhs.push(r)}),t}function le(e,n){let t=Date.now();try{return n()}finally{console.log(e+\" time: \"+(Date.now()-t)+\"ms\")}}function q(e,n){return n()}var st=0;function $(e){let n=++st;return e+(\"\"+n)}function A(e,n,t=1){n==null&&(n=e,e=0);let r=i=>i<n;t<0&&(r=i=>n<i);let o=[];for(let i=e;r(i);i+=t)o.push(i);return o}function B(e,n){let t={};for(let r of n)e[r]!==void 0&&(t[r]=e[r]);return t}function X(e,n){let t;return typeof n==\"string\"?t=r=>r[n]:t=n,Object.entries(e).reduce((r,[o,i])=>(r[o]=t(i,o),r),{})}function He(e,n){return e.reduce((t,r,o)=>(t[r]=n[o],t),{})}var D=\"\\0\";function ee(e,n,t){var u,d,c,f,h,p;if(!(e&&n&&t&&n.dummy===\"edge\"&&t.dummy===\"edge\"&&n.edgeObj&&t.edgeObj&&e[n.edgeObj.v]&&e[t.edgeObj.v]&&e[n.edgeObj.w]&&e[t.edgeObj.w]))return 0;let r=!0;n.edgeObj.w===t.edgeObj.w&&(r=!1);let o=r?(d=(u=e[n.edgeObj.v])==null?void 0:u.rank)!=null?d:NaN+1:(f=(c=e[n.edgeObj.w])==null?void 0:c.rank)!=null?f:NaN-1,i=Object.entries(e).find(E=>{var y,L;return((y=E[1].edgeObj)==null?void 0:y.v)===n.edgeObj.v&&((L=E[1].edgeObj)==null?void 0:L.w)===n.edgeObj.w&&E[1].rank===o}),s=Object.entries(e).find(E=>{var y,L;return((y=E[1].edgeObj)==null?void 0:y.v)===t.edgeObj.v&&((L=E[1].edgeObj)==null?void 0:L.w)===t.edgeObj.w&&E[1].rank===o});if(!i||!s)return 0;let a=(h=i[1].order)!=null?h:NaN,l=(p=s[1].order)!=null?p:NaN;return isNaN(a-l)?0:a-l}var ue=\"3.1.1\";var ce=class{constructor(){je(this,\"_sentinel\");let n={};n._next=n._prev=n,this._sentinel=n}dequeue(){let n=this._sentinel,t=n._prev;if(t!==n)return qe(t),t}enqueue(n){let t=this._sentinel;n._prev&&n._next&&qe(n),n._next=t._next,t._next._prev=n,t._next=n,n._prev=t}toString(){let n=[],t=this._sentinel,r=t._prev;for(;r!==t;)n.push(JSON.stringify(r,at)),r=r._prev;return\"[\"+n.join(\", \")+\"]\"}};function qe(e){e._prev._next=e._next,e._next._prev=e._prev,delete e._next,delete e._prev}function at(e,n){if(e!==\"_next\"&&e!==\"_prev\")return n}var $e=ce;var dt=()=>1;function be(e,n){if(e.nodeCount()<=1)return[];let t=ut(e,n||dt);return lt(t.graph,t.buckets,t.zeroIdx).flatMap(o=>e.outEdges(o.v,o.w)||[])}function lt(e,n,t){var a;let r=[],o=n[n.length-1],i=n[0],s;for(;e.nodeCount();){for(;s=i.dequeue();)fe(e,n,t,s);for(;s=o.dequeue();)fe(e,n,t,s);if(e.nodeCount()){for(let l=n.length-2;l>0;--l)if(s=(a=n[l])==null?void 0:a.dequeue(),s){r=r.concat(fe(e,n,t,s,!0)||[]);break}}}return r}function fe(e,n,t,r,o){let i=[],s=o?i:void 0;return(e.inEdges(r.v)||[]).forEach(a=>{let l=e.edge(a),u=e.node(a.v);o&&i.push({v:a.v,w:a.w}),u.out-=l,he(n,t,u)}),(e.outEdges(r.v)||[]).forEach(a=>{let l=e.edge(a),u=a.w,d=e.node(u);d.in-=l,he(n,t,d)}),e.removeNode(r.v),s}function ut(e,n){let t=new T,r=0,o=0;e.nodes().forEach(a=>{t.setNode(a,{v:a,in:0,out:0})}),e.edges().forEach(a=>{let l=t.edge(a.v,a.w)||0,u=n(a),d=l+u;t.setEdge(a.v,a.w,d);let c=t.node(a.v),f=t.node(a.w);o=Math.max(o,c.out+=u),r=Math.max(r,f.in+=u)});let i=ct(o+r+3).map(()=>new $e),s=r+1;return t.nodes().forEach(a=>{he(i,s,t.node(a))}),{graph:t,buckets:i,zeroIdx:s}}function he(e,n,t){var r,o,i;t.out?t.in?(i=e[t.out-t.in+n])==null||i.enqueue(t):(o=e[e.length-1])==null||o.enqueue(t):(r=e[0])==null||r.enqueue(t)}function ct(e){let n=[];for(let t=0;t<e;t++)n.push(t);return n}function Ue(e,n){(e.graph().acyclicer===\"greedy\"?be(e,r(e)):ft(e,n!=null?n:null)).forEach(o=>{let i=e.edge(o);e.removeEdge(o),i.forwardName=o.name,i.reversed=!0,e.setEdge(o.w,o.v,i,$(\"rev\"))});function r(o){return i=>o.edge(i).weight}}function ft(e,n){let t=[],r={},o={};function i(l){Object.hasOwn(o,l)||(o[l]=!0,r[l]=!0,e.outEdges(l).forEach(u=>{Object.hasOwn(r,u.w)?t.push(u):i(u.w)}),delete r[l])}function s(l){var u;Object.hasOwn(o,l)||(o[l]=!0,r[l]=!0,(u=e.outEdges(l))==null||u.forEach(d=>{var c,f;Object.hasOwn(r,d.w)||((c=n.node(l))==null?void 0:c.rank)>((f=n.node(d.w))==null?void 0:f.rank)&&ht(e,d.w,d)?t.push(d):s(d.w)}),delete r[l])}let a=i;return n&&typeof n.node==\"function\"&&(a=s),e.sources().forEach(a),e.nodes().forEach(a),t}function Je(e){e.edges().forEach(n=>{let t=e.edge(n);if(t.reversed){e.removeEdge(n);let r=t.forwardName;delete t.reversed,delete t.forwardName,e.setEdge(n.w,n.v,t,r)}})}function ht(e,n,t){let r=new Set;function o(i){var s;if(e.sources().includes(i))return!0;r.add(i);for(let a of(s=e.inEdges(i))!=null?s:[])if(!(a.v===t.v&&a.w===t.w)&&!r.has(a.v)&&o(a.v))return!0;return!1}return o(n)}function Ke(e){e.graph().dummyChains=[],e.edges().forEach(n=>gt(e,n))}function gt(e,n){let t=n.v,r=e.node(t).rank,o=n.w,i=e.node(o).rank,s=n.name,a=e.edge(n),l=a.labelRank;if(i===r+1)return;e.removeEdge(n);let u,d,c;for(c=0,++r;r<i;++c,++r)a.points=[],d={width:0,height:0,edgeLabel:a,edgeObj:n,rank:r},u=M(e,\"edge\",d,\"_d\"),r===l&&(d.width=a.width,d.height=a.height,d.dummy=\"edge-label\",d.labelpos=a.labelpos),e.setEdge(t,u,{weight:a.weight},s),c===0&&e.graph().dummyChains.push(u),t=u;e.setEdge(t,o,{weight:a.weight},s)}function Qe(e){e.graph().dummyChains.forEach(n=>{let t=e.node(n),r=t.edgeLabel,o;for(e.setEdge(t.edgeObj,r);t.dummy;)o=e.successors(n)[0],e.removeNode(n),r.points.push({x:t.x,y:t.y}),t.dummy===\"edge-label\"&&(r.x=t.x,r.y=t.y,r.width=t.width,r.height=t.height),n=o,t=e.node(n)})}function U(e){let n={};function t(r){let o=e.node(r);if(Object.hasOwn(n,r))return o.rank;n[r]=!0;let i=e.outEdges(r),s=i?i.map(l=>l==null?Number.POSITIVE_INFINITY:t(l.w)-e.edge(l).minlen):[],a=R(Math.min,s);return a===Number.POSITIVE_INFINITY&&(a=0),o.rank=a}e.sources().forEach(t)}function V(e,n){return e.node(n.w).rank-e.node(n.v).rank-e.edge(n).minlen}var ne=mt;function mt(e){let n=new T({directed:!1}),t=e.nodes();if(t.length===0)throw new Error(\"Graph must have at least one node\");let r=t[0],o=e.nodeCount();n.setNode(r,{});let i,s;for(;Et(n,e)<o&&(i=Lt(n,e),!!i);)s=n.hasNode(i.v)?V(e,i):-V(e,i),yt(n,e,s);return n}function Et(e,n){function t(r){let o=n.nodeEdges(r);o&&o.forEach(i=>{let s=i.v,a=r===s?i.w:s;!e.hasNode(a)&&!V(n,i)&&(e.setNode(a,{}),e.setEdge(r,a,{}),t(a))})}return e.nodes().forEach(t),e.nodeCount()}function Lt(e,n){return n.edges().reduce((r,o)=>{let i=Number.POSITIVE_INFINITY;return e.hasNode(o.v)!==e.hasNode(o.w)&&(i=V(n,o)),i<r[0]?[i,o]:r},[Number.POSITIVE_INFINITY,null])[1]}function yt(e,n,t){e.nodes().forEach(r=>n.node(r).rank+=t)}var{preorder:wt,postorder:Nt}=H,en=Y;Y.initLowLimValues=pe;Y.initCutValues=ge;Y.calcCutValue=nn;Y.leaveEdge=rn;Y.enterEdge=on;Y.exchangeEdges=sn;function Y(e){e=Ye(e),U(e);let n=ne(e);pe(n),ge(n,e);let t,r;for(;t=rn(n);)r=on(n,e,t),sn(n,e,t,r)}function ge(e,n){let t=Nt(e,e.nodes());t=t.slice(0,t.length-1),t.forEach(r=>Gt(e,n,r))}function Gt(e,n,t){let o=e.node(t).parent,i=e.edge(t,o);i.cutvalue=nn(e,n,t)}function nn(e,n,t){let o=e.node(t).parent,i=!0,s=n.edge(t,o),a=0;s||(i=!1,s=n.edge(o,t)),a=s.weight;let l=n.nodeEdges(t);return l&&l.forEach(u=>{let d=u.v===t,c=d?u.w:u.v;if(c!==o){let f=d===i,h=n.edge(u).weight;if(a+=f?h:-h,kt(e,t,c)){let E=e.edge(t,c).cutvalue;a+=f?-E:E}}}),a}function pe(e,n){arguments.length<2&&(n=e.nodes()[0]),tn(e,{},1,n)}function tn(e,n,t,r,o){let i=t,s=e.node(r);n[r]=!0;let a=e.neighbors(r);return a&&a.forEach(l=>{Object.hasOwn(n,l)||(t=tn(e,n,t,l,r))}),s.low=i,s.lim=t++,o?s.parent=o:delete s.parent,t}function rn(e){return e.edges().find(n=>e.edge(n).cutvalue<0)}function on(e,n,t){let r=t.v,o=t.w;n.hasEdge(r,o)||(r=t.w,o=t.v);let i=e.node(r),s=e.node(o),a=i,l=!1;return i.lim>s.lim&&(a=s,l=!0),n.edges().filter(d=>l===Ze(e,e.node(d.v),a)&&l!==Ze(e,e.node(d.w),a)).reduce((d,c)=>V(n,c)<V(n,d)?c:d)}function sn(e,n,t,r){let o=t.v,i=t.w;e.removeEdge(o,i),e.setEdge(r.v,r.w,{}),pe(e),ge(e,n),vt(e,n)}function vt(e,n){let t=e.nodes().find(o=>!e.node(o).parent);if(!t)return;let r=wt(e,[t]);r=r.slice(1),r.forEach(o=>{let s=e.node(o).parent,a=n.edge(o,s),l=!1;a||(a=n.edge(s,o),l=!0),n.node(o).rank=n.node(s).rank+(l?a.minlen:-a.minlen)})}function kt(e,n,t){return e.hasEdge(n,t)}function Ze(e,n,t){return t.low<=n.lim&&n.lim<=t.lim}var dn=xt;function xt(e){let n=e.graph().ranker;if(typeof n==\"function\")return n(e);switch(n){case\"network-simplex\":an(e);break;case\"tight-tree\":Ot(e);break;case\"longest-path\":_t(e);break;case\"none\":break;default:an(e)}}var _t=U;function Ot(e){U(e),ne(e)}function an(e){en(e)}var ln=Ct;function Ct(e){let n=jt(e),t=e.graph();if(!Array.isArray(t.dummyChains))return;t.dummyChains.forEach(o=>{let i=e.node(o),s=i.edgeObj,a=Tt(e,n,s.v,s.w),l=a.path,u=a.lca,d=0,c=l[d],f=!0;for(;o!==s.w;){if(i=e.node(o),f){for(;(c=l[d])!==u&&e.node(c).maxRank<i.rank;)d++;c===u&&(f=!1)}if(!f){for(;d<l.length-1&&e.node(l[d+1]).minRank<=i.rank;)d++;c=l[d]}c!==void 0&&e.setParent(o,c),o=e.successors(o)[0]}})}function Tt(e,n,t,r){let o=[],i=[],s=Math.min(n[t].low,n[r].low),a=Math.max(n[t].lim,n[r].lim),l;l=t;do l=e.parent(l),o.push(l);while(l&&(n[l].low>s||a>n[l].lim));let u=l,d=r;for(;(d=e.parent(d))!==u;)i.push(d);return{path:o.concat(i.reverse()),lca:u}}function jt(e){let n={},t=0;function r(o){let i=t;e.children(o).forEach(r),n[o]={low:i,lim:t++}}return e.children(D).forEach(r),n}function un(e){let n=M(e,\"root\",{},\"_root\"),t=Rt(e),r=Object.values(t),o=R(Math.max,r)-1,i=2*o+1;e.graph().nestingRoot=n,e.edges().forEach(a=>e.edge(a).minlen*=i);let s=It(e)+1;e.children(D).forEach(a=>{cn(e,n,i,s,o,t,a)}),e.graph().nodeRankFactor=i}function cn(e,n,t,r,o,i,s){var c;let a=e.children(s);if(!a.length){s!==n&&e.setEdge(n,s,{weight:0,minlen:t});return}let l=ae(e,\"_bt\"),u=ae(e,\"_bb\"),d=e.node(s);e.setParent(l,s),d.borderTop=l,e.setParent(u,s),d.borderBottom=u,a.forEach(f=>{var b;cn(e,n,t,r,o,i,f);let h=e.node(f),p=h.borderTop?h.borderTop:f,E=h.borderBottom?h.borderBottom:f,y=h.borderTop?r:2*r,L=p!==E?1:o-((b=i[s])!=null?b:0)+1;e.setEdge(l,p,{weight:y,minlen:L,nestingEdge:!0}),e.setEdge(E,u,{weight:y,minlen:L,nestingEdge:!0})}),e.parent(s)||e.setEdge(n,l,{weight:0,minlen:o+((c=i[s])!=null?c:0)})}function Rt(e){let n={};function t(r,o){let i=e.children(r);i&&i.length&&i.forEach(s=>t(s,o+1)),n[r]=o}return e.children(D).forEach(r=>t(r,1)),n}function It(e){return e.edges().reduce((n,t)=>n+e.edge(t).weight,0)}function fn(e){let n=e.graph();e.removeNode(n.nestingRoot),delete n.nestingRoot,e.edges().forEach(t=>{e.edge(t).nestingEdge&&e.removeEdge(t)})}var bn=Mt;function Mt(e){function n(t){let r=e.children(t),o=e.node(t);if(r.length&&r.forEach(n),o&&Object.hasOwn(o,\"minRank\")){o.borderLeft=[],o.borderRight=[];for(let i=o.minRank,s=o.maxRank+1;i<s;++i)hn(e,\"borderLeft\",\"_bl\",t,o,i),hn(e,\"borderRight\",\"_br\",t,o,i)}}e.children(D).forEach(n)}function hn(e,n,t,r,o,i){let s={width:0,height:0,rank:i,borderType:n},a=o[n][i-1],l=M(e,\"border\",s,t);o[n][i]=l,e.setParent(l,r),a&&e.setEdge(a,l,{weight:1})}function pn(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n===\"lr\"||n===\"rl\")&&En(e)}function mn(e){var t;let n=(t=e.graph().rankdir)==null?void 0:t.toLowerCase();(n===\"bt\"||n===\"rl\")&&Pt(e),(n===\"lr\"||n===\"rl\")&&(Ft(e),En(e))}function En(e){e.nodes().forEach(n=>gn(e.node(n))),e.edges().forEach(n=>gn(e.edge(n)))}function gn(e){let n=e.width;e.width=e.height,e.height=n}function Pt(e){e.nodes().forEach(n=>me(e.node(n))),e.edges().forEach(n=>{var r;let t=e.edge(n);(r=t.points)==null||r.forEach(me),Object.hasOwn(t,\"y\")&&me(t)})}function me(e){e.y=-e.y}function Ft(e){e.nodes().forEach(n=>Ee(e.node(n))),e.edges().forEach(n=>{var r;let t=e.edge(n);(r=t.points)==null||r.forEach(Ee),Object.hasOwn(t,\"x\")&&Ee(t)})}function Ee(e){let n=e.x;e.x=e.y,e.y=n}function Le(e,n=null){let t={},r=e.nodes().filter(d=>!e.children(d).length),o=r.map(d=>e.node(d).rank),i=R(Math.max,o),s=A(i+1).map(()=>[]);function a(d){if(t[d])return;t[d]=!0;let c=e.node(d);s[c.rank].push(d);let f=e.successors(d);f&&[...f].sort((p,E)=>u(p,E)).forEach(a)}r.sort((d,c)=>e.node(d).rank-e.node(c).rank).forEach(a);function u(d,c){let f=e.node(d),h=e.node(c);return ee(n,f,h)}return s}function ye(e,n){let t=0;for(let r=1;r<n.length;++r)t+=Vt(e,n[r-1],n[r]);return t}function Vt(e,n,t){let r=He(t,t.map((u,d)=>d)),o=n.flatMap(u=>{let d=e.outEdges(u);return d?d.map(c=>({pos:r[c.w],weight:e.edge(c).weight})).sort((c,f)=>c.pos-f.pos):[]}),i=1;for(;i<t.length;)i<<=1;let s=2*i-1;i-=1;let a=new Array(s).fill(0),l=0;return o.forEach(u=>{let d=u.pos+i;a[d]+=u.weight;let c=0;for(;d>0;)d%2&&(c+=a[d+1]),d=d-1>>1,a[d]+=u.weight;l+=u.weight*c}),l}function we(e,n=[]){return n.map(t=>{let r=e.inEdges(t);if(!r||!r.length)return{v:t};{let o=r.reduce((i,s)=>{let a=e.edge(s),l=e.node(s.v);return{sum:i.sum+a.weight*l.order,weight:i.weight+a.weight}},{sum:0,weight:0});return{v:t,barycenter:o.sum/o.weight,weight:o.weight}}})}function Ne(e,n){let t={};e.forEach((o,i)=>{let s={indegree:0,in:[],out:[],vs:[o.v],i};o.barycenter!==void 0&&(s.barycenter=o.barycenter,s.weight=o.weight),t[o.v]=s}),n.edges().forEach(o=>{let i=t[o.v],s=t[o.w];i!==void 0&&s!==void 0&&(s.indegree++,i.out.push(s))});let r=Object.values(t).filter(o=>!o.indegree);return Dt(r)}function Dt(e){let n=[];function t(o){return i=>{i.merged||(i.barycenter===void 0||o.barycenter===void 0||i.barycenter>=o.barycenter)&&Yt(o,i)}}function r(o){return i=>{i.in.push(o),--i.indegree===0&&e.push(i)}}for(;e.length;){let o=e.pop();n.push(o),o.in.reverse().forEach(t(o)),o.out.forEach(r(o))}return n.filter(o=>!o.merged).map(o=>B(o,[\"vs\",\"i\",\"barycenter\",\"weight\"]))}function Yt(e,n){let t=0,r=0;e.weight&&(t+=e.barycenter*e.weight,r+=e.weight),n.weight&&(t+=n.barycenter*n.weight,r+=n.weight),e.vs=n.vs.concat(e.vs),e.barycenter=t/r,e.weight=r,e.i=Math.min(n.i,e.i),n.merged=!0}function Ge(e,n,t,r,o){let i={},s=null,a=null,l=o;typeof n==\"boolean\"?(l=n,i={}):n&&(i=n,s=t!=null?t:null,a=r!=null?r:null);let u=ze(e,L=>Object.hasOwn(L,\"barycenter\")),d=u.lhs,c=u.rhs.sort((L,b)=>b.i-L.i),f=[],h=0,p=0,E=0;d.sort(Wt(a,s,!!l));for(let[L,b]of Object.entries(i)){let g=d.findIndex(m=>m.vs[0]===L);d.splice(g+1,0,b)}E=Ln(f,c,E),d.forEach(L=>{E+=L.vs.length,f.push(L.vs),h+=L.barycenter*L.weight,p+=L.weight,E=Ln(f,c,E)});let y={vs:f.flat(1)};return p&&(y.barycenter=h/p,y.weight=p),y}function Ln(e,n,t){let r;for(;n.length&&(r=n[n.length-1]).i<=t;)n.pop(),e.push(r.vs),t++;return t}function Wt(e,n,t){return(r,o)=>{if(r.barycenter<o.barycenter)return-1;if(r.barycenter>o.barycenter)return 1;if(e&&(typeof r.vs[0]==\"string\"||typeof o.vs[0]==\"string\")){let i=e.node(r.vs[0]),s=e.node(o.vs[0]),a=ee(n,i,s);if(a!==0)return a}return t?o.i-r.i:r.i-o.i}}function te(e,n,t,r,o){var L,b,g,m,w,k,_,C,j,I,S;let i=null,s=o;typeof r==\"boolean\"?(s=r,i=null):r!==void 0&&(i=r);let a=e.children(n),l=e.node(n),u=l?l.borderLeft:void 0,d=l?l.borderRight:void 0,c={};u&&(a=a.filter(G=>G!==u&&G!==d));let f=we(e,a);f.forEach(G=>{if(e.children(G.v).length){let{result:x}=te(e,G.v,t,i,s);c[G.v]=x,Object.hasOwn(x,\"barycenter\")&&Xt(G,x)}});let h=Ne(f,t);Bt(h,c);let p={},E=!1;for(let G=0;G<h.length;G++)for(let x=G+1;x<h.length;x++)if(!(!h[G]||!h[x]||!((L=h[G])!=null&&L.barycenter)||!((b=h[x])!=null&&b.barycenter))&&((g=h[G])==null?void 0:g.barycenter)===h[x].barycenter){let v=(w=(m=h[G])==null?void 0:m.vs[0])!=null?w:\"\",N=(_=(k=h[x])==null?void 0:k.vs[0])!=null?_:\"\",O=e.node(v),W=e.node(N);if(O.dummy===\"edge\"&&W.dummy===\"edge\"&&((C=O.edgeObj)==null?void 0:C.v)===((j=W.edgeObj)==null?void 0:j.v)&&((I=O.edgeObj)==null?void 0:I.w)===((S=W.edgeObj)==null?void 0:S.w))if(O.edgeLabel.reversed){p[N]=h[G],h.splice(G,1),G--;break}else p[v]=h[x],h.splice(x,1),x--;else E=!0}let y=Ge(h,p,i,e,s);if(u&&d){y.vs=[u,y.vs,d].flat(1);let G=e.predecessors(u);if(G&&G.length){let x=e.node(G[0]),v=e.predecessors(d),N=e.node(v[0]);Object.hasOwn(y,\"barycenter\")||(y.barycenter=0,y.weight=0),y.barycenter=(y.barycenter*y.weight+x.order+N.order)/(y.weight+2),y.weight+=2}}return Object.defineProperty(y,\"result\",{value:y,enumerable:!1,configurable:!0,writable:!0}),Object.defineProperty(y,\"usedBias\",{value:E,enumerable:!1,configurable:!0,writable:!0}),y}function Bt(e,n){e.forEach(t=>{t.vs=t.vs.flatMap(r=>n[r]?n[r].vs:r)})}function Xt(e,n){e.barycenter!==void 0?(e.barycenter=(e.barycenter*e.weight+n.barycenter*n.weight)/(e.weight+n.weight),e.weight+=n.weight):(e.barycenter=n.barycenter,e.weight=n.weight)}function ve(e,n,t,r){r||(r=e.nodes());let o=zt(e),i=new T({compound:!0}).setGraph({root:o}).setDefaultNodeLabel(s=>e.node(s));return r.forEach(s=>{let a=e.node(s),l=e.parent(s);if(a.rank===n||a.minRank<=n&&n<=a.maxRank){i.setNode(s),i.setParent(s,l||o);let u=e[t](s);u&&u.forEach(d=>{let c=d.v===s?d.w:d.v,f=i.edge(c,s),h=f!==void 0?f.weight:0;i.setEdge(c,s,{weight:e.edge(d).weight+h})}),Object.hasOwn(a,\"minRank\")&&i.setNode(s,{borderLeft:a.borderLeft[n],borderRight:a.borderRight[n]})}}),i}function zt(e){let n;for(;e.hasNode(n=$(\"_root\")););return n}function ke(e,n,t){let r={},o;t.forEach(i=>{let s=e.parent(i),a,l;for(;s;){if(a=e.parent(s),a?(l=r[a],r[a]=s):(l=o,o=s),l&&l!==s){n.setEdge(l,s);return}s=a}})}function re(e,n={},t=null){if(typeof n.customOrder==\"function\"){n.customOrder(e,re);return}let r=de(e),o=yn(e,A(1,r+1),\"inEdges\"),i=yn(e,A(r-1,-1,-1),\"outEdges\"),s=Le(e,t);if(wn(e,s),n.disableOptimalOrderHeuristic)return;let a=Number.POSITIVE_INFINITY,l,u=n.constraints||[];for(let d=0,c=0;c<4;++d,++c){Ht(d%2?o:i,d%4>=2,u,t),s=P(e);let f=ye(e,s);f<a?(c=0,l=Object.assign({},s),a=f):f===a&&(l=structuredClone(s))}wn(e,l)}function yn(e,n,t){let r=new Map,o=(i,s)=>{r.has(i)||r.set(i,[]),r.get(i).push(s)};for(let i of e.nodes()){let s=e.node(i);if(typeof s.rank==\"number\"&&o(s.rank,i),typeof s.minRank==\"number\"&&typeof s.maxRank==\"number\")for(let a=s.minRank;a<=s.maxRank;a++)a!==s.rank&&o(a,i)}return n.map(function(i){return ve(e,i,t,r.get(i)||[])})}function Ht(e,n,t,r){let o=!0,i=new T;e.forEach(function(s){t.forEach(d=>i.setEdge(d.left,d.right));let a=s.graph().root,{result:l,usedBias:u}=te(s,a,i,r,o);n&&u&&(o=!o),l.vs.forEach((d,c)=>s.node(d).order=c),ke(s,i,l.vs)})}function wn(e,n){Object.values(n).forEach(t=>t.forEach((r,o)=>e.node(r).order=o))}function qt(e,n){let t={};function r(o,i){let s=0,a=0,l=o.length,u=i[i.length-1];return i.forEach((d,c)=>{let f=Ut(e,d),h=f?e.node(f).order:l;(f||d===u)&&(i.slice(a,c+1).forEach(p=>{let E=e.predecessors(p);E&&E.forEach(y=>{let L=e.node(y),b=L.order;(b<s||h<b)&&!(L.dummy&&e.node(p).dummy)&&Gn(t,y,p)})}),a=c+1,s=h)}),i}return n.length&&n.reduce(r),t}function $t(e,n){let t={};function r(i,s,a,l,u){A(s,a).forEach(d=>{let c=i[d];if(c!==void 0&&e.node(c).dummy){let f=e.predecessors(c);f&&f.forEach(h=>{if(h===void 0)return;let p=e.node(h);p.dummy&&(p.order<l||p.order>u)&&Gn(t,h,c)})}})}function o(i,s){let a=-1,l=-1,u=0;return s.forEach((d,c)=>{if(e.node(d).dummy===\"border\"){let f=e.predecessors(d);if(f&&f.length){let h=f[0];if(h===void 0)return;l=e.node(h).order,r(s,u,c,a,l),u=c,a=l}}r(s,u,s.length,l,i.length)}),s}return n.length&&n.reduce(o),t}function Ut(e,n){if(e.node(n).dummy){let t=e.predecessors(n);if(t)return t.find(r=>e.node(r).dummy)}}function Gn(e,n,t){if(n>t){let o=n;n=t,t=o}let r=e[n];r||(e[n]=r={}),r[t]=!0}function Jt(e,n,t){if(n>t){let o=n;n=t,t=o}let r=e[n];return r!==void 0&&Object.hasOwn(r,t)}function Kt(e,n,t,r,o){let i={},s={},a={};return n.forEach(l=>{l.forEach((u,d)=>{i[u]=u,s[u]=u,a[u]=d})}),n.forEach(l=>{let u=-1,d=-1,c=!1,f=l,h=l.findIndex(p=>(o==null?void 0:o.includes(p))||Nn(p,e,o));h>0&&(f=[l[h],...l.slice(0,h),...l.slice(h+1)],c=!0),f.forEach(p=>{var y;let E=r(p);if(E&&E.length){o!=null&&o.includes(p)&&(E=E.filter(g=>Nn(g,e,o)));let L=E.sort((g,m)=>{let w=a[g],k=a[m];return(w!==void 0?w:0)-(k!==void 0?k:0)}),b=(L.length-1)/2;for(let g=Math.floor(b),m=Math.ceil(b);g<=m;++g){let w=L[g];if(w===void 0)continue;let k=a[w];if(k!==void 0&&s[p]===p&&u<k&&a[w]!==d&&!Jt(t,p,w)){let _=i[w];_!==void 0&&(s[w]=p,s[p]=i[p]=_,u=k,c&&(u=-1,d=(y=a[w])!=null?y:-1,c=!1))}}}})}),{root:i,align:s}}function Qt(e,n,t,r,o=!1){let i={},s=Zt(e,n,t,o),a=o?\"borderLeft\":\"borderRight\";function l(h,p){let E=s.nodes().slice(),y={},L=E.pop();for(;L;){if(y[L])h(L);else{y[L]=!0,E.push(L);for(let b of p(L))E.push(b)}L=E.pop()}}function u(h){let p=s.inEdges(h);p?i[h]=p.reduce((E,y)=>{var g;let L=(g=i[y.v])!=null?g:0,b=s.edge(y);return Math.max(E,L+(b!==void 0?b:0))},0):i[h]=0}function d(h){let p=s.outEdges(h),E=Number.POSITIVE_INFINITY;p&&(E=p.reduce((L,b)=>{let g=i[b.w],m=s.edge(b);return Math.min(L,(g!==void 0?g:0)-(m!==void 0?m:0))},Number.POSITIVE_INFINITY));let y=e.node(h);E!==Number.POSITIVE_INFINITY&&y.borderType!==a&&(i[h]=Math.max(i[h]!==void 0?i[h]:0,E))}function c(h){return s.predecessors(h)||[]}function f(h){return s.successors(h)||[]}return l(u,c),l(d,f),Object.keys(r).forEach(h=>{var E;let p=t[h];p!==void 0&&(i[h]=(E=i[p])!=null?E:0)}),i}function Zt(e,n,t,r){let o=new T,i=e.graph(),s=rr(i.nodesep,i.edgesep,r);return n.forEach(a=>{let l;a.forEach(u=>{let d=t[u];if(d!==void 0){if(o.setNode(d),l!==void 0){let c=t[l];if(c!==void 0){let f=o.edge(c,d);o.setEdge(c,d,Math.max(s(e,u,l),f||0))}}l=u}})}),o}function er(e,n){return Object.values(n).reduce((t,r)=>{let o=Number.NEGATIVE_INFINITY,i=Number.POSITIVE_INFINITY;Object.entries(r).forEach(([a,l])=>{let u=or(e,a)/2;o=Math.max(l+u,o),i=Math.min(l-u,i)});let s=o-i;return s<t[0]&&(t=[s,r]),t},[Number.POSITIVE_INFINITY,null])[1]}function nr(e,n){let t=Object.values(n),r=R(Math.min,t),o=R(Math.max,t);[\"u\",\"d\"].forEach(i=>{[\"l\",\"r\"].forEach(s=>{let a=i+s,l=e[a];if(!l||l===n)return;let u=Object.values(l),d=r-R(Math.min,u);s!==\"l\"&&(d=o-R(Math.max,u)),d&&(e[a]=X(l,c=>c+d))})})}function tr(e,n=void 0){let t=e.ul;return t?X(t,(r,o)=>{var s,a;if(n){let l=n.toLowerCase(),u=e[l];if(u&&u[o]!==void 0)return u[o]}let i=Object.values(e).map(l=>{let u=l[o];return u!==void 0?u:0}).sort((l,u)=>l-u);return(((s=i[1])!=null?s:0)+((a=i[2])!=null?a:0))/2}):{}}function vn(e,n){let t=P(e),r=Object.assign(qt(e,t),$t(e,t)),o={},i;[\"u\",\"d\"].forEach(a=>{i=a===\"u\"?t:Object.values(t).reverse(),[\"l\",\"r\"].forEach(l=>{l===\"r\"&&(i=i.map(f=>Object.values(f).reverse()));let d=Kt(e,i,r,f=>(a===\"u\"?e.predecessors(f):e.successors(f))||[],n),c=Qt(e,i,d.root,d.align,l===\"r\");l===\"r\"&&(c=X(c,f=>-f)),o[a+l]=c})});let s=er(e,o);return nr(o,s),tr(o,e.graph().align)}function rr(e,n,t){return(r,o,i)=>{let s=r.node(o),a=r.node(i),l=0,u;if(l+=s.width/2,Object.hasOwn(s,\"labelpos\"))switch(s.labelpos.toLowerCase()){case\"l\":u=-s.width/2;break;case\"r\":u=s.width/2;break}if(u&&(l+=t?u:-u),u=void 0,l+=(s.dummy?n:e)/2,l+=(a.dummy?n:e)/2,l+=a.width/2,Object.hasOwn(a,\"labelpos\"))switch(a.labelpos.toLowerCase()){case\"l\":u=a.width/2;break;case\"r\":u=-a.width/2;break}return u&&(l+=t?u:-u),l}}function or(e,n){return e.node(n).width}function Nn(e,n,t){var s;if(!t)return!1;let r=(s=n.node(e))==null?void 0:s.edgeObj;if(!r||n.node(e).edgeLabel.reversed)return!1;let o=t.indexOf(r==null?void 0:r.v),i=t.indexOf(r==null?void 0:r.w);return o!==-1&&i!==-1&&o===(i+1)%t.length||o===(i-1)%t.length}function kn(e,n){e=Z(e),ir(e),Object.entries(vn(e,n)).forEach(([t,r])=>e.node(t).x=r)}function ir(e){let n=P(e),t=e.graph(),r=t.ranksep,o=t.rankalign,i=0;n.forEach(s=>{let a=s.reduce((l,u)=>{var c;let d=(c=e.node(u).height)!=null?c:0;return l>d?l:d},0);s.forEach(l=>{let u=e.node(l);o===\"top\"?u.y=i+u.height/2:o===\"bottom\"?u.y=i+a-u.height/2:u.y=i+a/2}),i+=a+r})}var xn=new WeakMap;function Oe(e,n={}){return Rn(e,q,n),e}function _n(e,n,t){let r=n;for(;r!==void 0;){let o=e.parent(r);if(o===t)return r;r=o}}function Rn(e,n,t){var L;let r=e.nodes().filter(b=>e.children(b).length),o={};r.forEach(b=>{let g=e.node(b);if(g&&g.rankdir){let m=new T({multigraph:!0,compound:!0});m.setGraph({rankdir:g.rankdir});let w=e.children(b);w.forEach(v=>{let N={...e.node(v)};m.setNode(v,N);let O=e.parent(v);O&&O!==b&&w.includes(O)&&m.setParent(v,O)});let k=new Set;e.edges().forEach(v=>{let N=_n(e,v.v,b),O=_n(e,v.w,b);if(N&&O&&N!==O){let W=`${N}\\0${O}`;k.has(W)||(k.add(W),m.setEdge(N,O,{...e.edge(v)}))}}),Rn(m,n,t);let _=jn(m);On(_,n,t,null),Cn(m,_);let C=1/0,j=1/0,I=-1/0,S=-1/0;m.nodes().forEach(v=>{if(v===b)return;let N=m.node(v);N&&typeof N.x==\"number\"&&typeof N.y==\"number\"&&typeof N.width==\"number\"&&typeof N.height==\"number\"&&(C=Math.min(C,N.x-N.width/2),I=Math.max(I,N.x+N.width/2),j=Math.min(j,N.y-N.height/2),S=Math.max(S,N.y+N.height/2))}),(!isFinite(C)||!isFinite(j)||!isFinite(I)||!isFinite(S))&&(C=j=0,I=S=0);let G=I-C,x=S-j;o[b]={minX:C,minY:j,maxX:I,maxY:S,width:G,height:x,offsetX:C,offsetY:j},g._dagreClusterSubgraph=m}});let i=[],s=b=>{let g=[],m=(e.children(b)||[]).filter(w=>w!==b);for(;m.length>0;){let w=m.shift();g.push(w),(e.children(w)||[]).filter(k=>k!==w).forEach(k=>m.push(k))}return g},a=new Map;r.forEach(b=>{let g=e.node(b);g&&g.rankdir&&o[b]&&a.set(b,(e.children(b)||[]).filter(m=>m!==b))});let l=new Set([...a.values()].flat()),u=new Map;a.forEach((b,g)=>{l.has(g)||u.set(g,s(g))});let d=new Set([...u.values()].flat()),c=b=>{for(let[g,m]of u)if(m.includes(b))return g;return b},f=[];e.edges().forEach(b=>{(d.has(b.v)||d.has(b.w))&&f.push({edge:b,label:e.edge(b)})});let h=new Map;d.forEach(b=>{let g=e.parent(b);h.set(b,typeof g==\"string\"?g:void 0)}),u.forEach((b,g)=>{let m=e.node(g),w=[];b.forEach(C=>{let j=e.node(C);j&&(w.push({id:C,node:j,parent:h.get(C)}),e.removeNode(C))});let k=f.filter(({edge:C})=>b.includes(C.v)||b.includes(C.w)),_=o[g];m&&(i.push({clusterId:g,subgraph:m._dagreClusterSubgraph,bounds:_,children:b,removedNodes:w,removedEdges:k}),m.width=_.width,m.height=_.height)});let p=new Set;f.forEach(({edge:b,label:g})=>{let m=c(b.v),w=c(b.w);if(m!==w&&e.hasNode(m)&&e.hasNode(w)){let k=`${m}\\0${w}`;p.has(k)||(p.add(k),e.setEdge(m,w,{...g,width:0,height:0}))}});let E=jn(e),y=On(E,n,t,(L=xn.get(e))!=null?L:null);xn.set(e,y),Cn(e,E),p.forEach(b=>{let g=b.indexOf(\"\\0\"),m=b.slice(0,g),w=b.slice(g+1);e.hasEdge(m,w)&&e.removeEdge(m,w)}),i.forEach(({clusterId:b,subgraph:g,bounds:m,removedNodes:w,removedEdges:k})=>{var G,x;let _=e.node(b),C=(G=_==null?void 0:_.x)!=null?G:0,j=(x=_==null?void 0:_.y)!=null?x:0,I=(m.minX+m.maxX)/2,S=(m.minY+m.maxY)/2;w.forEach(({id:v,node:N,parent:O})=>{e.setNode(v,N),O!==void 0&&e.setParent(v,O)}),k.forEach(({edge:v,label:N})=>{e.setEdge(v,N)}),g.nodes().forEach(v=>{if(v===b)return;let N=g.node(v),O=e.node(v);O&&N&&typeof N.x==\"number\"&&typeof N.y==\"number\"&&(O.x=C+(N.x-I),O.y=j+(N.y-S))}),delete _._dagreClusterSubgraph}),r.forEach(b=>{var w,k;let g=e.node(b),m=o[b];if(g&&g.rankdir&&g._dagreClusterSubgraph&&m){let _=g._dagreClusterSubgraph,C=(w=g.x)!=null?w:0,j=(k=g.y)!=null?k:0,I=(m.minX+m.maxX)/2,S=(m.minY+m.maxY)/2;_.nodes().forEach(G=>{if(G===b)return;let x=_.node(G),v=e.node(G);if(v&&x&&typeof x.x==\"number\"&&typeof x.y==\"number\"){let N=x.x-I,O=x.y-S;v.x=C+N,v.y=j+O}}),delete g._dagreClusterSubgraph}})}function On(e,n,t,r=null){var l,u;let o=(t==null?void 0:t.useDynamic)!==!1,i=o&&(l=r==null?void 0:r.graph)!=null?l:null,s=o&&(u=r==null?void 0:r.rawNodes)!=null?u:null;n(\" makeSpaceForEdgeLabels\",()=>hr(e)),n(\" removeSelfEdges\",()=>Nr(e)),n(\" acyclic\",()=>Ue(e,i)),n(\" nestingGraph.run\",()=>un(e)),n(\" rank\",()=>dn(Z(e))),n(\" injectEdgeLabelProxies\",()=>br(e)),n(\" removeEmptyRanks\",()=>Be(e)),n(\" nestingGraph.cleanup\",()=>fn(e)),n(\" normalizeRanks\",()=>We(e)),n(\" assignRankMinMax\",()=>gr(e)),n(\" removeEdgeLabelProxies\",()=>pr(e)),n(\" normalize.run\",()=>Ke(e)),n(\" parentDummyChains\",()=>ln(e)),n(\" addBorderSegments\",()=>bn(e)),n(\" order\",()=>re(e,t,s)),n(\" insertSelfEdges\",()=>Gr(e)),n(\" adjustCoordinateSystem\",()=>pn(e)),n(\" position\",()=>kn(e,t.corePath)),n(\" positionSelfEdges\",()=>vr(e));let a=JSON.parse(JSON.stringify(e._nodes));return n(\" removeBorderNodes\",()=>wr(e)),n(\" normalize.undo\",()=>Qe(e)),n(\" fixupEdgeLabelCoords\",()=>Lr(e)),n(\" undoCoordinateSystem\",()=>mn(e)),n(\" translateGraph\",()=>mr(e)),n(\" assignNodeIntersects\",()=>Er(e)),n(\" reversePoints\",()=>yr(e)),n(\" acyclic.undo\",()=>Je(e)),{graph:e,rawNodes:a}}function Cn(e,n){e.nodes().forEach(t=>{let r=e.node(t),o=n.node(t);r&&(r.x=o.x,r.y=o.y,r.order=o.order,r.rank=o.rank,n.children(t).length&&(r.width=o.width,r.height=o.height))}),e.edges().forEach(t=>{let r=e.edge(t),o=n.edge(t);r.points=o.points,Object.hasOwn(o,\"x\")&&(r.x=o.x,r.y=o.y)}),e.graph().width=n.graph().width,e.graph().height=n.graph().height}var sr=[\"nodesep\",\"edgesep\",\"ranksep\",\"marginx\",\"marginy\"],ar={ranksep:50,edgesep:20,nodesep:50,rankdir:\"TB\",rankalign:\"center\"},dr=[\"acyclicer\",\"ranker\",\"rankdir\",\"align\",\"rankalign\"],lr=[\"width\",\"height\",\"rank\"],Tn={width:0,height:0},ur=[\"minlen\",\"weight\",\"width\",\"height\",\"labeloffset\"],cr={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:\"r\"},fr=[\"labelpos\"];function jn(e){let n=new T({multigraph:!0,compound:!0}),t=_e(e.graph());return n.setGraph(Object.assign({},ar,xe(t,sr),B(t,dr))),e.nodes().forEach(r=>{let o=_e(e.node(r)),i=xe(o,lr);Object.keys(Tn).forEach(a=>{i[a]===void 0&&(i[a]=Tn[a])}),n.setNode(r,i);let s=e.parent(r);s!==void 0&&n.setParent(r,s)}),e.edges().forEach(r=>{let o=_e(e.edge(r));n.setEdge(r,Object.assign({},cr,xe(o,ur),B(o,fr)))}),n}function hr(e){let n=e.graph();n.ranksep/=2,e.edges().forEach(t=>{var o;let r=e.edge(t);r.minlen*=2,((o=r.labelpos)!=null?o:\"r\").toLowerCase()!==\"c\"&&(n.rankdir===\"TB\"||n.rankdir===\"BT\"?r.width+=r.labeloffset:r.height+=r.labeloffset)})}function br(e){e.edges().forEach(n=>{let t=e.edge(n);if(t.width&&t.height){let r=e.node(n.v),i={rank:(e.node(n.w).rank-r.rank)/2+r.rank,e:n};M(e,\"edge-proxy\",i,\"_ep\")}})}function gr(e){let n=0;e.nodes().forEach(t=>{let r=e.node(t);r.borderTop&&(r.minRank=e.node(r.borderTop).rank,r.maxRank=e.node(r.borderBottom).rank,n=Math.max(n,r.maxRank))}),e.graph().maxRank=n}function pr(e){e.nodes().forEach(n=>{let t=e.node(n);if(t.dummy===\"edge-proxy\"){let r=t;e.edge(r.e).labelRank=t.rank,e.removeNode(n)}})}function mr(e){let n=Number.POSITIVE_INFINITY,t=0,r=Number.POSITIVE_INFINITY,o=0,i=e.graph(),s=i.marginx||0,a=i.marginy||0;function l(u){let d=u.x,c=u.y,f=u.width,h=u.height;n=Math.min(n,d-f/2),t=Math.max(t,d+f/2),r=Math.min(r,c-h/2),o=Math.max(o,c+h/2)}e.nodes().forEach(u=>l(e.node(u))),e.edges().forEach(u=>{let d=e.edge(u);Object.hasOwn(d,\"x\")&&l(d)}),n-=s,r-=a,e.nodes().forEach(u=>{let d=e.node(u);d.x-=n,d.y-=r}),e.edges().forEach(u=>{let d=e.edge(u);d.points.forEach(c=>{c.x-=n,c.y-=r}),Object.hasOwn(d,\"x\")&&(d.x-=n),Object.hasOwn(d,\"y\")&&(d.y-=r)}),i.width=t-n+s,i.height=o-r+a}function Er(e){e.edges().forEach(n=>{if(n.v===n.w)return;let t=e.edge(n),r=e.node(n.v),o=e.node(n.w),i,s;t.points?(i=t.points[0],s=t.points[t.points.length-1]):(t.points=[],i=o,s=r),t.points.unshift(se(r,i)),t.points.push(se(o,s))})}function Lr(e){e.edges().forEach(n=>{let t=e.edge(n);if(Object.hasOwn(t,\"x\"))switch((t.labelpos===\"l\"||t.labelpos===\"r\")&&(t.width-=t.labeloffset),t.labelpos){case\"l\":t.x-=t.width/2+t.labeloffset;break;case\"r\":t.x+=t.width/2+t.labeloffset;break}})}function yr(e){e.edges().forEach(n=>{let t=e.edge(n);t.reversed&&t.points.reverse()})}function wr(e){e.nodes().forEach(n=>{if(e.children(n).length){let t=e.node(n),r=e.node(t.borderTop),o=e.node(t.borderBottom),i=e.node(t.borderLeft[t.borderLeft.length-1]),s=e.node(t.borderRight[t.borderRight.length-1]);t.width=Math.abs(s.x-i.x),t.height=Math.abs(o.y-r.y),t.x=i.x+t.width/2,t.y=r.y+t.height/2}}),e.nodes().forEach(n=>{e.node(n).dummy===\"border\"&&e.removeNode(n)})}function Nr(e){e.edges().forEach(n=>{if(n.v===n.w){let t=e.node(n.v);t.selfEdges||(t.selfEdges=[]),t.selfEdges.push({e:n,label:e.edge(n)}),e.removeEdge(n)}})}function Gr(e){P(e).forEach(t=>{let r=0;t.forEach((o,i)=>{let s=e.node(o);typeof s.rank!=\"number\"&&(s.rank=0),s.order=i+r,(s.selfEdges||[]).forEach(a=>{M(e,\"selfedge\",{width:a.label.width,height:a.label.height,rank:s.rank,order:i+ ++r,e:a.e,edgeLabel:a.label},\"_se\"),(!Array.isArray(a.label.points)||a.label.points.length!==7)&&(a.label.points=[{x:0,y:-10},{x:0,y:-10},{x:0,y:0},{x:0,y:10},{x:0,y:10},{x:0,y:0},{x:0,y:0}])}),delete s.selfEdges})})}function vr(e){e.nodes().forEach(n=>{let t=e.node(n),r=o=>typeof o==\"number\"&&isFinite(o);if(t.dummy===\"selfedge\"){let o=t,i=e.node(o.e.v),s=r(i==null?void 0:i.x)?i.x:0,a=r(i==null?void 0:i.y)?i.y:0,l=r(i==null?void 0:i.width)?i.width:0,u=r(i==null?void 0:i.height)?i.height:0,d=r(t.x)?t.x:s,c=r(t.y)?t.y:a,f=l/2,h=u/2;o.edgeLabel.points=[{x:d+f,y:c-h},{x:d+f,y:c-h},{x:d,y:c},{x:d-f,y:c+h},{x:d-f,y:c+h},{x:d,y:c},{x:d,y:c}],o.edgeLabel.x=d,o.edgeLabel.y=c,e.setEdge(o.e,o.edgeLabel),e.removeNode(n)}else t&&Array.isArray(t.selfEdges)&&t.selfEdges.forEach(o=>{if(!Array.isArray(o.label.points)||o.label.points.length!==7){let i=r(t.x)?t.x:0,s=r(t.y)?t.y:0,a=r(t.width)?t.width:0,l=r(t.height)?t.height:0,u=a/2,d=l/2;o.label.points=[{x:i+u,y:s-d},{x:i+u,y:s-d},{x:i,y:s},{x:i-u,y:s+d},{x:i-u,y:s+d},{x:i,y:s},{x:i,y:s}]}})})}function xe(e,n){return X(B(e,n),Number)}function _e(e){let n={};return e&&Object.entries(e).forEach(([t,r])=>{typeof t==\"string\"&&(t=t.toLowerCase()),n[t]=r}),n}function Ce(e){let n=P(e),t=new T({compound:!0,multigraph:!0}).setGraph({});return e.nodes().forEach(r=>{t.setNode(r,{label:r}),t.setParent(r,\"layer\"+e.node(r).rank)}),e.edges().forEach(r=>t.setEdge(r.v,r.w,{},r.name)),n.forEach((r,o)=>{let i=\"layer\"+o;t.setNode(i,{rank:\"same\"}),r.reduce((s,a)=>(t.setEdge(s,a,{style:\"invis\"}),a))}),t}var qo={time:le,notime:q},kr={graphlib:ie,version:ue,layout:Oe,debug:Ce,util:{time:le,notime:q}},$o=kr;export{T as Graph,Ce as debug,$o as default,ie as graphlib,Oe as layout,qo as util,ue as version};\n/*! For license information please see dagre.esm.js.LEGAL.txt */\n//# sourceMappingURL=dagre.esm.js.map\n","/**\n * Terminal cell widths for the plan renderer. Same tables as testkit/display-width.ts (copied, not imported: production code must not depend on the test kit);\n * the oracles cross-check it against that independent copy. Covers the ranges that matter for plan labels, not all of Unicode.\n */\n\nconst WIDE_RANGES: ReadonlyArray<readonly [number, number]> = [\n [0x1100, 0x115f], [0x2e80, 0xa4cf], [0xac00, 0xd7a3], [0xf900, 0xfaff], [0xfe30, 0xfe6f],\n [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f300, 0x1f64f], [0x1f680, 0x1f6ff], [0x1f7e0, 0x1f7eb], [0x1f900, 0x1f9ff], [0x20000, 0x3fffd],\n // single-codepoint emoji that are East Asian Wide (✅ ❌ ⚡ ⭐ ❓ ➕): drawn two cells wide\n [0x2705, 0x2705], [0x274c, 0x274c], [0x26a1, 0x26a1], [0x2b50, 0x2b50], [0x2753, 0x2755], [0x2795, 0x2797],\n]\nconst ZERO_WIDTH_RANGES: ReadonlyArray<readonly [number, number]> = [[0x0300, 0x036f], [0x200b, 0x200d], [0xfe00, 0xfe0f]]\n\nexport function cellWidth(ch: string): 0 | 1 | 2 {\n const cp = ch.codePointAt(0) ?? 0\n if (ZERO_WIDTH_RANGES.some(([a, b]) => cp >= a && cp <= b)) return 0\n if (WIDE_RANGES.some(([a, b]) => cp >= a && cp <= b)) return 2\n return 1\n}\n\nexport function displayWidth(s: string): number {\n let w = 0\n for (const ch of s) w += cellWidth(ch)\n return w\n}\n\n/** Marks the second cell of a double-width character in a cell grid. */\nexport const WIDE_TAIL = '\\u0000'\n\n/** Expands a line into one entry per terminal cell (a wide character becomes [char, WIDE_TAIL]). */\nexport function toCells(line: string): string[] {\n const out: string[] = []\n for (const ch of line) {\n const w = cellWidth(ch)\n if (w === 0) continue\n out.push(ch)\n if (w === 2) out.push(WIDE_TAIL)\n }\n return out\n}\n\nexport function toGrid(lines: readonly string[]): string[][] {\n const rows = lines.map(toCells)\n const width = Math.max(0, ...rows.map((r) => r.length))\n return rows.map((r) => (r.length < width ? [...r, ...Array<string>(width - r.length).fill(' ')] : r))\n}\n\n// ── label handling (production additions) ──\n\nconst ZERO_WIDTH = /[\\u0300-\\u036f\\u200b-\\u200d\\ufe00-\\ufe0f]/g\nconst CONTROL = /[\\u0000-\\u001f\\u007f-\\u009f--]/g\n\n/** One printable line: control, escape and bidi characters are removed, whitespace runs collapse, ends are trimmed. */\nexport function sanitizeLabel(raw: string): string {\n return String(raw ?? '').normalize('NFC').replace(/[\\n\\r\\t]+/g, ' ').replace(CONTROL, '').replace(ZERO_WIDTH, '').replace(/ {2,}/g, ' ').trim()\n}\n\n/** Cuts `s` to at most `max` cells, ending with an ellipsis when something was removed. Never splits a wide character. */\nexport function fitLabel(s: string, max: number): string {\n if (displayWidth(s) <= max) return s\n let out = ''\n let w = 0\n for (const ch of s) {\n const cw = cellWidth(ch)\n if (w + cw > max - 1) break\n out += ch\n w += cw\n }\n return out + '…'\n}\n","import dagre from '@dagrejs/dagre'\nimport { normalizePlanNodes } from './normalize.js'\nimport { displayWidth, fitLabel, sanitizeLabel } from './plan-width.js'\nimport type { VizNode } from './types.js'\n\n/** Above this many nodes the picture is not useful in a terminal; callers fall back to the checklist. */\nexport const MAX_PLAN_NODES = 150\n/** Dense plans (hundreds of dependencies) turn into a wall of lines; same checklist fallback as the node cap. */\nexport const MAX_PLAN_EDGES = 600\nexport const BOX_HEIGHT = 3\n/** Cells a box adds around its label region: two borders, a pad either side, the glyph and a space. */\nconst BOX_CHROME = 6\nconst MIN_LABEL = 8\nconst GAP_BOX = 3\nconst GAP_OTHER = 2\n\n/** A box (real) or a one-column waypoint of an edge that skips ranks (virtual). */\nexport interface LayoutItem {\n uid: number\n rank: number\n x: number\n w: number\n virtual: boolean\n /** Real items only. */\n node?: VizNode\n /** Visible label text of a real item (sanitized and shortened). */\n label?: string\n /** Virtual items: the chain they belong to, so adjacent-rank waypoints of one edge may share a column. */\n chain?: number\n}\n\nexport interface EdgeChain {\n from: string\n to: string\n /** Source box, waypoints in rank order, target box. */\n items: LayoutItem[]\n}\n\nexport interface PlanLayout {\n ok: true\n nodes: VizNode[]\n ranks: LayoutItem[][]\n chains: EdgeChain[]\n byId: Map<string, LayoutItem>\n width: number\n warnings: string[]\n}\n\nexport type LayoutFailure = { ok: false; reason: 'empty' | 'too_large' | 'cannot_draw'; message: string }\n\nexport const LABEL_FLOOR = MIN_LABEL\n\n/**\n * Layered layout in character units. dagre decides the ranks and the left-to-right order (dummy nodes\n * included); positions are then legalized per rank so boxes never touch and waypoints keep clear of boxes.\n * Deterministic: nodes and edges are inserted in task order and nothing in the input depends on status, so\n * a status change never moves a box.\n */\nexport function layoutPlan(input: readonly VizNode[], labelMax: number): PlanLayout | LayoutFailure {\n const { nodes, warnings } = normalizePlanNodes(input)\n if (!nodes.length) return { ok: false, reason: 'empty', message: 'the plan has no tasks' }\n if (nodes.length > MAX_PLAN_NODES) return { ok: false, reason: 'too_large', message: `the plan has ${nodes.length} tasks (the graph shows at most ${MAX_PLAN_NODES})` }\n\n const edgeCount = nodes.reduce((a, n) => a + n.deps.length, 0)\n if (edgeCount > MAX_PLAN_EDGES) return { ok: false, reason: 'too_large', message: `the plan has ${edgeCount} dependencies (the graph shows at most ${MAX_PLAN_EDGES})` }\n\n const items: LayoutItem[] = nodes.map((node, i) => {\n const label = fitLabel(sanitizeLabel(node.label) || sanitizeLabel(node.id) || '?', Math.max(MIN_LABEL, labelMax))\n return { uid: i, rank: 0, x: 0, w: Math.max(displayWidth(label), 1) + BOX_CHROME, virtual: false, node, label }\n })\n const byId = new Map(items.map((it) => [it.node!.id, it]))\n\n const g = new dagre.graphlib.Graph()\n g.setGraph({ rankdir: 'TB', nodesep: GAP_BOX + 1, edgesep: GAP_OTHER + 1, ranksep: 4, marginx: 0, marginy: 0 })\n g.setDefaultEdgeLabel(() => ({}))\n items.forEach((it, i) => g.setNode(`n${i}`, { width: it.w, height: BOX_HEIGHT }))\n const idx = new Map(nodes.map((n, i) => [n.id, i]))\n for (const n of nodes) for (const d of n.deps) g.setEdge(`n${idx.get(d)}`, `n${idx.get(n.id)}`)\n dagre.layout(g)\n\n const ys = [...new Set(items.map((_, i) => Math.round(g.node(`n${i}`).y)))].sort((a, b) => a - b)\n items.forEach((it, i) => {\n const p = g.node(`n${i}`)\n it.rank = ys.indexOf(Math.round(p.y))\n it.x = Math.round(p.x - it.w / 2)\n })\n\n const ranks: LayoutItem[][] = ys.map(() => [])\n items.forEach((it) => ranks[it.rank].push(it))\n const chains: EdgeChain[] = []\n let uid = items.length\n for (const n of nodes) for (const d of n.deps) {\n const a = items[idx.get(d)!]\n const b = items[idx.get(n.id)!]\n const span = b.rank - a.rank\n if (span < 1) return { ok: false, reason: 'cannot_draw', message: `${n.id} is not ranked below ${d}` }\n const pts = (g.edge(`n${idx.get(d)}`, `n${idx.get(n.id)}`) as { points?: Array<{ x: number }> }).points ?? []\n const chain: LayoutItem[] = [a]\n for (let k = 1; k < span; k++) {\n const px = pts.length === span + 1 ? pts[k].x : (a.x + a.w / 2) + ((b.x + b.w / 2) - (a.x + a.w / 2)) * (k / span)\n const v: LayoutItem = { uid: uid++, rank: a.rank + k, x: Math.round(px), w: 1, virtual: true, chain: chains.length }\n ranks[v.rank].push(v)\n chain.push(v)\n }\n chain.push(b)\n chains.push({ from: d, to: n.id, items: chain })\n }\n\n const legalize = (row: LayoutItem[]): void => {\n row.sort((p, q) => p.x - q.x || p.uid - q.uid)\n for (let i = 1; i < row.length; i++) {\n const gap = row[i - 1].virtual || row[i].virtual ? GAP_OTHER : GAP_BOX\n row[i].x = Math.max(row[i].x, row[i - 1].x + row[i - 1].w + gap)\n }\n }\n ranks.forEach(legalize)\n const minX = Math.min(...ranks.flat().map((it) => it.x))\n if (minX !== 0) ranks.flat().forEach((it) => { it.x -= minX })\n\n // Waypoints of unrelated edges in adjacent ranks must not share a column (their stems would merge in the gap between).\n const clashes = (v: LayoutItem): boolean => [v.rank - 1, v.rank + 1].some((r) => (ranks[r] ?? []).some((o) => o.virtual && o.x === v.x && o.chain !== v.chain))\n for (let pass = 0; pass < 40; pass++) {\n let changed = false\n for (const row of ranks) for (const v of row) if (v.virtual && clashes(v)) { v.x += 1; legalize(row); changed = true }\n if (!changed) break\n }\n if (ranks.flat().some((v) => v.virtual && clashes(v))) return { ok: false, reason: 'cannot_draw', message: 'edge waypoints could not be separated' }\n\n const width = Math.max(...ranks.flat().map((it) => it.x + it.w))\n return { ok: true, nodes, ranks, chains, byId, width, warnings }\n}\n","import { BOX_HEIGHT, LABEL_FLOOR, layoutPlan, type LayoutFailure, type LayoutItem, type PlanLayout } from './plan-layout.js'\nimport { cellWidth, WIDE_TAIL } from './plan-width.js'\nimport type { Box, Edge, RenderResult, VizNode, VizStatus } from './types.js'\n\nexport interface PlanRenderOptions {\n /** Terminal width in cells; labels shrink (down to a floor) until the picture fits. Omit for the natural size. */\n maxCols?: number\n ascii?: boolean\n color?: boolean\n selectedId?: string\n}\n\n/** What a successful render returns beyond what the grid oracles need. */\nexport interface PlanRender extends RenderResult {\n ok: true\n width: number\n height: number\n /** False when even the shortest labels do not fit `maxCols`; the caller pans a viewport over the full grid. */\n fits: boolean\n /** The label text each box shows (after sanitizing and shortening). */\n labels: Record<string, string>\n /** Cells (row, column) every edge is drawn through, keyed `${from}>${to}`. */\n routes: Record<string, Array<[number, number]>>\n /** One entry per terminal cell (a double-width character is followed by WIDE_TAIL) and its SGR parameters ('' = none). */\n cells: string[][]\n styles: string[][]\n warnings: string[]\n}\n\nexport type PlanRenderFailure = LayoutFailure\n\nexport const GLYPHS: Record<VizStatus, string> = { done: '✓', running: '▶', failed: '✗', pending: '○', ready: '◔', awaiting_user: '~', awaiting_input: '⏸', cancelled: '⊘' }\nexport const ASCII_GLYPHS: Record<VizStatus, string> = { done: '+', running: '>', failed: 'x', pending: 'o', ready: '*', awaiting_user: '~', awaiting_input: '=', cancelled: '/' }\nconst STATUS_SGR: Record<VizStatus, string> = { done: '32', running: '33', failed: '31', pending: '2', ready: '36', awaiting_user: '35', awaiting_input: '35', cancelled: '2' }\n\nconst U = 1\nconst D = 2\nconst L = 4\nconst R = 8\nconst UNICODE_GLYPH: Record<number, string> = {\n [U]: '│', [D]: '│', [U | D]: '│', [L]: '─', [R]: '─', [L | R]: '─', [D | R]: '┌', [D | L]: '┐', [U | R]: '└', [U | L]: '┘',\n [U | D | R]: '├', [U | D | L]: '┤', [L | R | D]: '┬', [L | R | U]: '┴', [U | D | L | R]: '┼',\n}\nconst LABEL_STEPS = [40, 30, 24, 20, 16, 13, 10, LABEL_FLOOR]\n\ntype Cell = [number, number]\n\ninterface GapPlan {\n rows: number\n /** Relative to the gap's first row. */\n vlines: Array<{ col: number; r1: number; r2: number; top: boolean; bot: boolean }>\n hlines: Array<{ row: number; c1: number; c2: number }>\n arrows: Array<{ row: number; col: number }>\n routes: Array<{ chain: number; cells: Cell[] }>\n maxCol: number\n}\n\nclass CannotDraw extends Error {}\n\nconst cV = (col: number, r1: number, r2: number): Cell[] => Array.from({ length: r2 - r1 + 1 }, (_, i) => [r1 + i, col] as Cell)\nconst cH = (row: number, c1: number, c2: number): Cell[] => {\n const lo = Math.min(c1, c2)\n return Array.from({ length: Math.abs(c2 - c1) + 1 }, (_, i) => [row, lo + i] as Cell)\n}\nconst portRange = (it: LayoutItem): [number, number] => (it.virtual ? [it.x, it.x] : [it.x + 1, it.x + it.w - 2])\n\n/**\n * Channel routing for the gap between rank g and g+1. Every edge of the gap is a stem down from its source,\n * an optional bus row, a drop column and an optional bus row on the target, then one arrow column. Columns\n * of stems, drops and arrows are all distinct, so a vertical only ever meets a horizontal as a crossing\n * (┼) and unrelated edges never share a cell. Rows: source buses, target buses, then the arrow row.\n */\nfunction planGap(layout: PlanLayout, g: number): GapPlan {\n const top = layout.ranks[g]\n const bot = layout.ranks[g + 1]\n const segs: Array<{ a: LayoutItem; b: LayoutItem; chain: number }> = []\n layout.chains.forEach((c, ci) => {\n for (let k = 0; k + 1 < c.items.length; k++) if (c.items[k].rank === g) segs.push({ a: c.items[k], b: c.items[k + 1], chain: ci })\n })\n const outN = new Map<number, number>()\n const inN = new Map<number, number>()\n for (const s of segs) { outN.set(s.a.uid, (outN.get(s.a.uid) ?? 0) + 1); inN.set(s.b.uid, (inN.get(s.b.uid) ?? 0) + 1) }\n\n const limit = layout.width + 24\n const used = new Set<number>()\n for (const it of [...top, ...bot]) if (it.virtual) used.add(it.x)\n const pickFree = (lo: number, hi: number, pref: number): number | undefined => {\n const p = Math.min(hi, Math.max(lo, pref))\n for (let d = 0; d <= hi - lo; d++) for (const c of d === 0 ? [p] : [p - d, p + d]) if (c >= lo && c <= hi && !used.has(c)) return c\n return undefined\n }\n const sc = new Map<number, number>()\n const tc = new Map<number, number>()\n for (const it of top) if (it.virtual) sc.set(it.uid, it.x)\n for (const it of bot) if (it.virtual) tc.set(it.uid, it.x)\n\n const straight = new Set<(typeof segs)[number]>()\n for (const s of segs) {\n if (outN.get(s.a.uid) !== 1 || inN.get(s.b.uid) !== 1) continue\n const [alo, ahi] = portRange(s.a)\n const [blo, bhi] = portRange(s.b)\n const lo = Math.max(alo, blo)\n const hi = Math.min(ahi, bhi)\n if (lo > hi) continue\n let c: number | undefined\n if (s.a.virtual || s.b.virtual) c = s.a.virtual ? s.a.x : s.b.x\n else c = pickFree(lo, hi, Math.round((s.a.x + s.a.w / 2 + s.b.x + s.b.w / 2) / 2))\n if (c === undefined || c < lo || c > hi) continue\n used.add(c)\n sc.set(s.a.uid, c)\n tc.set(s.b.uid, c)\n straight.add(s)\n }\n for (const [items, ports, counts] of [[top, sc, outN], [bot, tc, inN]] as const) {\n for (const it of items) {\n if (!counts.get(it.uid) || ports.has(it.uid)) continue\n const [lo, hi] = portRange(it)\n const c = pickFree(lo, hi, Math.round(it.x + it.w / 2))\n if (c === undefined) throw new CannotDraw('no free port column')\n used.add(c)\n ports.set(it.uid, c)\n }\n }\n\n const dropOf = new Map<(typeof segs)[number], number>()\n const needSrc = new Set<number>()\n const needTgt = new Set<number>()\n for (const s of segs) {\n if (straight.has(s)) continue\n const srcSingle = outN.get(s.a.uid) === 1\n const tgtSingle = inN.get(s.b.uid) === 1\n if (srcSingle && !tgtSingle) { dropOf.set(s, sc.get(s.a.uid)!); needTgt.add(s.b.uid) }\n else if (tgtSingle) { dropOf.set(s, tc.get(s.b.uid)!); needSrc.add(s.a.uid) }\n }\n for (const s of segs) {\n if (straight.has(s) || dropOf.has(s)) continue\n const c = pickFree(0, limit, Math.round((sc.get(s.a.uid)! + tc.get(s.b.uid)!) / 2))\n if (c === undefined) throw new CannotDraw('no free drop column')\n used.add(c)\n dropOf.set(s, c)\n needSrc.add(s.a.uid)\n needTgt.add(s.b.uid)\n }\n\n const srcRow = new Map<number, number>()\n const tgtRow = new Map<number, number>()\n top.filter((it) => needSrc.has(it.uid)).forEach((it, i) => srcRow.set(it.uid, i))\n bot.filter((it) => needTgt.has(it.uid)).forEach((it, i) => tgtRow.set(it.uid, srcRow.size + i))\n const rows = Math.max(srcRow.size + tgtRow.size + 1, 2)\n const last = rows - 1\n\n const plan: GapPlan = { rows, vlines: [], hlines: [], arrows: [], routes: [], maxCol: Math.max(0, ...used) }\n const arrive = (b: LayoutItem, col: number): void => { if (!b.virtual) plan.arrows.push({ row: last, col }) }\n for (const s of segs) {\n const a = sc.get(s.a.uid)!\n const t = tc.get(s.b.uid)!\n const botOpen = s.b.virtual\n const cells: Cell[] = []\n if (straight.has(s)) {\n plan.vlines.push({ col: a, r1: 0, r2: last, top: true, bot: botOpen })\n arrive(s.b, a)\n cells.push(...cV(a, 0, last))\n } else {\n const d = dropOf.get(s)!\n const sr = srcRow.get(s.a.uid)\n const tr = tgtRow.get(s.b.uid)\n const haveSrc = sr !== undefined && needSrc.has(s.a.uid) && d !== a\n const haveTgt = tr !== undefined && needTgt.has(s.b.uid) && d !== t\n if (haveSrc) {\n plan.vlines.push({ col: a, r1: 0, r2: sr!, top: true, bot: false })\n plan.hlines.push({ row: sr!, c1: Math.min(a, d), c2: Math.max(a, d) })\n cells.push(...cV(a, 0, sr!), ...cH(sr!, a, d))\n }\n const y1 = haveSrc ? sr! : 0\n const y2 = haveTgt ? tr! : last\n plan.vlines.push({ col: d, r1: y1, r2: y2, top: !haveSrc, bot: !haveTgt && botOpen })\n cells.push(...cV(d, y1, y2))\n if (haveTgt) {\n plan.hlines.push({ row: tr!, c1: Math.min(d, t), c2: Math.max(d, t) })\n plan.vlines.push({ col: t, r1: tr!, r2: last, top: false, bot: botOpen })\n cells.push(...cH(tr!, d, t), ...cV(t, tr!, last))\n arrive(s.b, t)\n } else arrive(s.b, d)\n }\n plan.routes.push({ chain: s.chain, cells })\n plan.maxCol = Math.max(plan.maxCol, ...cells.map((c) => c[1]))\n }\n return plan\n}\n\nfunction drawOnce(layout: PlanLayout, opts: PlanRenderOptions): PlanRender {\n const ascii = opts.ascii ?? false\n const gaps = layout.ranks.slice(0, -1).map((_, g) => planGap(layout, g))\n const rankY: number[] = [0]\n gaps.forEach((gp, g) => rankY.push(rankY[g] + BOX_HEIGHT + gp.rows))\n const height = rankY[rankY.length - 1] + BOX_HEIGHT\n const width = Math.max(layout.width, ...gaps.map((gp) => gp.maxCol + 1))\n\n const bits = Array.from({ length: height }, () => new Uint8Array(width))\n const arrows: Cell[] = []\n // Route pieces are ordered along the edge: waypoint rows at even positions, gaps at odd ones.\n const parts: Array<Array<{ at: number; cells: Cell[] }>> = layout.chains.map(() => [])\n gaps.forEach((gp, g) => {\n const y0 = rankY[g] + BOX_HEIGHT\n for (const v of gp.vlines) for (let r = v.r1; r <= v.r2; r++) bits[y0 + r][v.col] |= (r > v.r1 || v.top ? U : 0) | (r < v.r2 || v.bot ? D : 0)\n for (const h of gp.hlines) for (let c = h.c1; c <= h.c2; c++) bits[y0 + h.row][c] |= (c > h.c1 ? L : 0) | (c < h.c2 ? R : 0)\n for (const a of gp.arrows) arrows.push([y0 + a.row, a.col])\n for (const rt of gp.routes) parts[rt.chain].push({ at: g * 2 + 1, cells: rt.cells.map(([r, c]) => [y0 + r, c] as Cell) })\n })\n layout.chains.forEach((ch, ci) => {\n for (const it of ch.items) if (it.virtual) {\n for (let r = 0; r < BOX_HEIGHT; r++) bits[rankY[it.rank] + r][it.x] |= U | D\n parts[ci].push({ at: it.rank * 2, cells: [0, 1, 2].map((r) => [rankY[it.rank] + r, it.x] as Cell) })\n }\n })\n\n const routes: Record<string, Cell[]> = Object.fromEntries(layout.chains.map((c, ci) => [`${c.from}>${c.to}`, parts[ci].sort((p, q) => p.at - q.at).flatMap((p) => p.cells)]))\n\n const cells: string[][] = bits.map((row) => Array.from(row, (b) => (b ? (ascii ? (b & (L | R) && b & (U | D) ? '+' : b & (L | R) ? '-' : '|') : UNICODE_GLYPH[b]) : ' ')))\n for (const [r, c] of arrows) cells[r][c] = ascii ? 'v' : '▼'\n const styles: string[][] = cells.map((row) => row.map(() => ''))\n\n const glyphs = ascii ? ASCII_GLYPHS : GLYPHS\n const boxes: Box[] = []\n const labels: Record<string, string> = {}\n const put = (r: number, c: number, ch: string, style = ''): number => {\n const w = cellWidth(ch)\n if (w === 0) return 0\n cells[r][c] = ch\n styles[r][c] = style\n if (w === 2) { cells[r][c + 1] = WIDE_TAIL; styles[r][c + 1] = style }\n return w\n }\n const color = opts.color ?? false\n for (const node of layout.nodes) {\n const it = layout.byId.get(node.id)!\n const y = rankY[it.rank]\n const { x, w } = it\n boxes.push({ id: node.id, x, y, w, h: BOX_HEIGHT })\n labels[node.id] = it.label!\n const selected = opts.selectedId === node.id\n const [tl, tr, bl, br, h, v] = ascii ? ['+', '+', '+', '+', '-', '|'] : ['┌', '┐', '└', '┘', '─', '│']\n for (let c = x; c < x + w; c++) { put(y, c, c === x ? tl : c === x + w - 1 ? tr : h); put(y + 2, c, c === x ? bl : c === x + w - 1 ? br : h) }\n for (let c = x; c < x + w; c++) put(y + 1, c, ' ', color && selected ? '7' : '')\n put(y + 1, x, v)\n put(y + 1, x + w - 1, v)\n const mid = color && selected ? '7' : ''\n if (selected && !color) put(y + 1, x + 1, '>')\n put(y + 1, x + 2, glyphs[node.status] ?? '?', color ? (selected ? '7;' : '') + STATUS_SGR[node.status] : '')\n let c = x + 4\n for (const ch of it.label!) c += put(y + 1, c, ch, mid)\n }\n\n if (color && opts.selectedId) {\n for (const [key, route] of Object.entries(routes)) {\n const e = layout.chains.find((ch) => `${ch.from}>${ch.to}` === key)!\n if (e.from === opts.selectedId || e.to === opts.selectedId) for (const [r, c] of route) if (!styles[r][c]) styles[r][c] = '1;36'\n }\n }\n\n const edges: Edge[] = layout.chains.map((c) => ({ from: c.from, to: c.to }))\n return { ok: true, lines: toLines(cells, styles), boxes, edges, width, height, fits: true, labels, routes, cells, styles, warnings: layout.warnings }\n}\n\n/** Joins cells into text lines, emitting SGR sequences only where the style changes. Trailing blanks are dropped. */\nexport function toLines(cells: readonly string[][], styles: readonly string[][], rows?: [number, number], cols?: [number, number]): string[] {\n const [r0, r1] = rows ?? [0, cells.length]\n const out: string[] = []\n for (let r = r0; r < r1; r++) {\n const row = cells[r]\n const [c0, c1] = cols ?? [0, row.length]\n let end = c1\n while (end > c0 && (row[end - 1] === ' ' && !styles[r][end - 1])) end--\n let line = ''\n let cur = ''\n for (let c = c0; c < end; c++) {\n if (row[c] === WIDE_TAIL) continue\n if (styles[r][c] !== cur) { line += cur ? '\\u001b[0m' : ''; cur = styles[r][c]; line += cur ? `\\u001b[${cur}m` : '' }\n line += row[c]\n }\n out.push(line + (cur ? '\\u001b[0m' : ''))\n }\n return out\n}\n\n/**\n * Lays out and draws a plan. Labels shrink (down to a floor) until the picture fits `maxCols`; when it still\n * does not, the full-size grid is returned with `fits: false` so the caller can pan over it. Never throws:\n * a plan that cannot be drawn comes back as `{ ok: false, reason, message }` and the caller shows the checklist.\n */\nexport function renderPlan(nodes: readonly VizNode[], opts: PlanRenderOptions = {}): PlanRender | PlanRenderFailure {\n try {\n let result: PlanRender | undefined\n for (const labelMax of LABEL_STEPS) {\n const layout = layoutPlan(nodes, labelMax)\n if (!layout.ok) return layout\n result = drawOnce(layout, opts)\n if (opts.maxCols === undefined || result.width <= opts.maxCols) return result\n }\n return { ...result!, fits: false }\n } catch (err) {\n return { ok: false, reason: 'cannot_draw', message: err instanceof Error ? err.message : String(err) }\n }\n}\n","/**\n * First-run setup for the CLI. `npx @buildaharness/aielia` with no\n * env vars and no persisted config used to land on the default `proxy` backend\n * pointed at `http://localhost:8787` — a proxy almost nobody running it for the\n * first time has, so every turn failed with a connection error and no hint about\n * what to do. This runs one short interactive pass instead: ask for a provider\n * + API key, and persist the choice via the same ConfigStore `/config set`\n * writes to.\n *\n * Split out of cli.ts (like non-interactive-mode.ts / error-classifier.ts) so it\n * can be unit-tested without a live REPL: every side-effecting dependency —\n * reading a line, testing a key — is injected.\n */\n\nimport type { AssistantConfig, ConfigStore } from './config.js'\nimport { PROVIDER_SETUP, checkApiKeyFormat, cleanApiKey, type KeyTestResult, type KeyedBackend } from './provider-setup.js'\n\nexport interface FirstRunDeps {\n configStore: ConfigStore\n /** Result of `configStore.load()` — the setup is skipped entirely if this already names a backend/key. */\n persisted: Partial<AssistantConfig>\n /** Keys pinned by an env var (ASSISTANT_LLM_BACKEND etc.) — also a signal the user has already chosen. */\n overriddenKeys: ReadonlySet<keyof AssistantConfig>\n /** False for piped/scripted stdin — setup is skipped and today's behavior (proxy default) is kept. */\n isInteractive: boolean\n /** Reads one line from the user, already trimmed. */\n ask: (question: string) => Promise<string>\n /** Where to print prompts/status (defaults to process.stdout in cli.ts). */\n log: (line: string) => void\n /** Live-checks a key against the provider. Optional so unit tests can skip the network; cli.ts passes the real testApiKey. */\n testKey?: (backend: KeyedBackend, key: string) => Promise<KeyTestResult>\n}\n\n/** How many times the user may re-paste a rejected key before we stop nagging and let them out. */\nconst MAX_KEY_ATTEMPTS = 3\n\n/** Any of these present means the user has already configured a backend — don't re-prompt. */\nfunction alreadyConfigured(deps: FirstRunDeps): boolean {\n const { persisted, overriddenKeys } = deps\n if (persisted.llmBackend !== undefined) return true\n if (persisted.apiKey !== undefined || persisted.authToken !== undefined) return true\n for (const key of ['llmBackend', 'apiKey', 'authToken', 'proxyUrl'] as const) {\n if (overriddenKeys.has(key)) return true\n }\n return false\n}\n\n/**\n * Runs the first-run pass if needed. Returns the persisted config to use from\n * here on — unchanged when setup was skipped or the user bailed out, or a fresh\n * object reflecting what was just written.\n */\nexport async function maybeRunFirstRunSetup(deps: FirstRunDeps): Promise<Partial<AssistantConfig>> {\n const { configStore, persisted, isInteractive, ask, log, testKey } = deps\n\n if (alreadyConfigured(deps)) return persisted\n if (!isInteractive) return persisted\n\n log('')\n log('Welcome to Aielia! 👋 Let’s get you set up — it takes about a minute.')\n log('')\n log('Aielia needs an AI model to think with. Pick where that comes from below.')\n log('(You can change this any time with /config, or press Ctrl+C to skip.)')\n log('')\n\n const patch: Partial<AssistantConfig> = {}\n\n log('Which AI provider do you have (or want to use)?')\n log('')\n PROVIDER_SETUP.forEach((p, i) => {\n log(` ${i + 1}) ${p.name}`)\n log(` ${p.blurb}`)\n })\n log('')\n const choice = (await ask(`Type 1-${PROVIDER_SETUP.length} and press Enter (or just Enter to skip): `)).trim()\n const picked = PROVIDER_SETUP[Number(choice) - 1]\n if (!picked) {\n log('')\n log('Skipped. Until you set a provider, Aielia will try the \"proxy\" backend (needs')\n log('@buildaharness/proxy running on :8787). To set one up later, run:')\n log(' /config set llmBackend <anthropic|openai|openrouter>')\n log(' /config set apiKey <your key>')\n log('')\n return persisted\n }\n\n log('')\n log(`To connect ${picked.name}, you need an “API key” — a password-like code that lets Aielia use your account.`)\n log('Here’s how to get one:')\n log('')\n picked.steps.forEach((step, i) => log(` ${i + 1}. ${step}`))\n if (picked.safety) {\n log('')\n log(` ${picked.safety.title}:`)\n picked.safety.steps.forEach((step, i) => log(` ${i + 1}. ${step}`))\n log(` (${picked.safety.urlLabel})`)\n }\n log('')\n log(`The key starts with \"${picked.keyPrefix}\". Paste it below when you have it.`)\n log('')\n\n let key = ''\n for (let attempt = 1; attempt <= MAX_KEY_ATTEMPTS; attempt++) {\n const candidate = cleanApiKey(await ask('Paste your API key (or just Enter to skip): '))\n if (candidate === '') break\n const formatProblem = checkApiKeyFormat(picked.backend, candidate)\n if (formatProblem) {\n log(` ✗ ${formatProblem}`)\n continue\n }\n if (testKey) {\n log(' Checking your key…')\n const result = await testKey(picked.backend, candidate)\n if (result.status === 'invalid') {\n log(` ✗ ${result.message}`)\n continue\n }\n if (result.status === 'unverified') log(` ! ${result.message}`)\n }\n key = candidate\n break\n }\n\n if (!key) {\n log('')\n log('No working key entered, so nothing was saved. Run Aielia again to retry, or use')\n log('/config set llmBackend ' + picked.backend + ' then /config set apiKey <key>')\n log('')\n return persisted\n }\n\n patch.llmBackend = picked.backend\n patch.apiKey = key\n await configStore.save(patch)\n log('')\n log(`✓ You’re all set — using ${picked.name}. Say hello!`)\n log(' Your key is saved on this computer in ~/.buildaharness/personal-assistant/config.json')\n log(' (plain text, like a .env file) — don’t share that file.')\n log('')\n return { ...persisted, ...patch }\n}\n","/**\n * Central glyph-to-meaning vocabulary for status marks printed by the CLI/TUI. Added because the\n * live terminal comparison (`reports/cli_appearance_comparison_2026-09-17.md`) found `⚙` used for\n * two unrelated meanings at once — `writeToolStep` (cli.ts) prefixed *every* tool-call step with\n * it, so \"Proposing to run: rm -rf /tmp/x\" (about to ask for approval) and \"Fetching\n * https://…\" (a routine, no-approval-needed read) were visually indistinguishable at a glance,\n * unlike Codex's distinct glyph-per-state convention. The status-mark glyphs already used\n * elsewhere in cli.ts (`✓`/`✗`/`○`/`▶`/`~` for plan tasks, layer-fired marks, batch outcomes) were\n * already each used for one consistent meaning — only the tool-step glyph needed splitting.\n */\nexport const ICONS = {\n /** A routine, no-approval-needed tool step (read_file, fetch_url, web_search, list_reminders, …). */\n toolStep: '⚙',\n /** A tool step that is itself the proposal of a state-changing action (write_file, run_shell_command) — printed on the same in-flight step line, before the separate \"[needs approval — …]\" prompt appears. */\n proposalStep: '⚠',\n /** A read-only tool call `tool-policy.ts` denied before it executed — deliberately not `✗` (cli.ts already uses that, unprefixed, as the leading character of several unrelated config/undo-action error lines; reusing it here would misclassify those as `'tool'`-kind in tui-app.tsx's `TOOL_STEP_PREFIXES` match). */\n deniedStep: '⛔',\n} as const\n\n/**\n * Marker `cli.ts`'s `printPlan()` prepends to its combined plan-status block (Phase 6, \"distinct\n * plan-mode UI\") so `tui-app.tsx`'s `classifyLineKind` renders it as a dedicated `PlanBox` instead\n * of plain `'system'` text — lives here rather than in `tui-app.tsx` itself so `cli.ts` (which\n * `tui-app.tsx` already imports) doesn't need a reverse import back to it, the same reason the\n * tool-step glyphs above live here instead of in either of those two files.\n */\nexport const PLAN_LINE_PREFIX = '▤PLAN▤'\n\n/** Tool names whose step line should use {@link ICONS.proposalStep} instead of {@link ICONS.toolStep} — the same two tools `risk-classifier.ts` treats as state-changing/approval-gated. */\nconst PROPOSAL_TOOLS = new Set(['write_file', 'run_shell_command'])\n\n/** Picks the right glyph for one `AssistantToolStep`'s in-flight summary line — shared so `cli.ts` and any other surface printing a tool-step line stay in sync with the same mapping. */\nexport function toolStepIcon(tool: string): string {\n return PROPOSAL_TOOLS.has(tool) ? ICONS.proposalStep : ICONS.toolStep\n}\n","/**\n * Argv parsing for the `aielia` CLI. Pure — no process access — so it is unit-testable.\n *\n * Before this existed `main()` ignored argv entirely, so recognizing a few explicit cases is\n * strictly additive: anything unrecognized (including no args at all) resolves to `'repl'`,\n * exactly today's behavior.\n */\nexport type CliCommand =\n | { command: 'repl' }\n | { command: 'version' }\n | { command: 'help' }\n | { command: 'update'; dryRun: boolean }\n\n/** `argv` is the user-supplied arguments only, i.e. `process.argv.slice(2)`. */\nexport function parseCliArgs(argv: readonly string[]): CliCommand {\n const first = argv[0]\n if (first === '--version' || first === '-v' || first === 'version') return { command: 'version' }\n if (first === '--help' || first === '-h' || first === 'help') return { command: 'help' }\n if (first === 'update') return { command: 'update', dryRun: argv.slice(1).includes('--dry-run') }\n return { command: 'repl' }\n}\n\nexport function cliHelpText(version: string): string {\n return [\n `aielia ${version} — an agent you can hand real work to, held in bounds by a harness.`,\n '',\n 'Usage:',\n ' aielia start the interactive assistant',\n ' aielia update update to the latest release (standalone binary installs)',\n ' aielia update --dry-run check for an update without installing it',\n ' aielia --version print the version',\n ' aielia --help show this help',\n '',\n 'https://myaielia.com',\n ].join('\\n')\n}\n","/**\n * Self-update for the standalone (Node SEA) `aielia` binary, plus the passive \"an update is\n * available\" check that runs alongside the interactive session.\n *\n * Release discovery never uses GitHub's `/releases/latest` — this repo publishes many product\n * lines (`harness-v*`, `pa-v*`, `aielia-v*`, …) into one Releases list, so \"latest\" is repo-wide,\n * not per product. Instead the product-scoped manifest at myaielia.com is tried first, then the\n * Releases API filtered to `aielia-v*` tags.\n *\n * Every network function takes injectable `fetchFn`/URLs/clock/paths so self-update.test.ts can\n * exercise the whole download → verify → replace flow against a local mock HTTP server.\n */\nimport { createHash } from 'node:crypto'\nimport { createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync, renameSync, chmodSync, rmSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type { ReadableStream as WebReadableStream } from 'node:stream/web'\nimport { CLI_VERSION } from './version.js'\nimport { loadSea } from './mcp-server-asset.js'\n\nexport const MANIFEST_URL = 'https://myaielia.com/aielia-latest.json'\nexport const RELEASES_API_URL = 'https://api.github.com/repos/3IVIS/buildaharness/releases?per_page=50'\nexport const RELEASE_TAG_PREFIX = 'aielia-v'\nexport const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\nconst REQUEST_TIMEOUT_MS = 5_000\nconst DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000\nconst NPM_UPDATE_HINT = 'npm update -g @buildaharness/aielia'\n\nexport interface ReleaseAsset {\n url: string\n /** From the manifest — the trusted hash (a different origin than the binary's github.com URL). Absent on the GitHub-API fallback. */\n sha256?: string\n size?: number\n}\n\nexport interface ReleaseInfo {\n tag: string\n version: string\n /** Keyed `<process.platform>-<process.arch>`, e.g. `linux-x64`, `darwin-arm64`, `win32-x64`. */\n assets: Record<string, ReleaseAsset>\n source: 'manifest' | 'github'\n}\n\nexport interface UpdateCheckCache {\n checkedAt: number\n latestVersion?: string\n latestTag?: string\n /** ETag of the GitHub Releases API response, for conditional re-requests. */\n etag?: string\n}\n\nexport interface SelfUpdateOptions {\n fetchFn?: typeof fetch\n manifestUrl?: string\n releasesApiUrl?: string\n /** Test-only: permit http:// manifest/asset URLs (a local mock server). Production never sets this. */\n allowInsecureHttp?: boolean\n now?: () => number\n /** Defaults to `~/.buildaharness/personal-assistant`. */\n dataDir?: string\n currentVersion?: string\n platform?: NodeJS.Platform\n arch?: string\n /** Path of the running binary. Defaults to `process.execPath` (which, in a SEA, is the binary itself). */\n execPath?: string\n /** Defaults to whether `node:sea` reports a SEA. */\n isSea?: boolean\n log?: (line: string) => void\n}\n\nconst defaultDataDir = (): string => join(homedir(), '.buildaharness', 'personal-assistant')\nconst cachePath = (dataDir: string): string => join(dataDir, 'update-check.json')\n\n/** Numeric `major.minor.patch` comparison; a `-prerelease` suffix sorts below the same release. Returns <0, 0, >0. */\nexport function compareVersions(a: string, b: string): number {\n const parse = (v: string): { nums: number[]; pre: boolean } => {\n const [core, pre] = v.replace(/^v/, '').split('-', 2)\n const nums = core.split('.').map((n) => Number.parseInt(n, 10) || 0)\n while (nums.length < 3) nums.push(0)\n return { nums, pre: pre !== undefined }\n }\n const pa = parse(a)\n const pb = parse(b)\n for (let i = 0; i < 3; i++) if (pa.nums[i] !== pb.nums[i]) return pa.nums[i] - pb.nums[i]\n if (pa.pre !== pb.pre) return pa.pre ? -1 : 1\n return 0\n}\n\n/** Throws on anything but https:// (unless the test-only override is set) — applied to the manifest URL and every asset URL. */\nexport function assertHttps(url: string, allowInsecureHttp = false): void {\n let protocol: string\n try {\n protocol = new URL(url).protocol\n } catch {\n throw new Error(`Refusing malformed URL: ${url}`)\n }\n if (protocol === 'https:') return\n if (protocol === 'http:' && allowInsecureHttp) return\n throw new Error(`Refusing non-HTTPS URL: ${url}`)\n}\n\n/**\n * Whether the passive check may make its unsolicited outbound request at all. Off for scripted/CI\n * runs (stdin not a TTY, or `ASSISTANT_NON_INTERACTIVE_APPROVAL` set) and when opted out via\n * `ASSISTANT_UPDATE_CHECK=disabled` / `/config set updateCheck disabled`.\n */\nexport function shouldRunPassiveUpdateCheck(input: {\n updateCheck: 'enabled' | 'disabled' | undefined\n env: NodeJS.ProcessEnv\n stdinIsTty: boolean\n}): boolean {\n if (input.updateCheck === 'disabled') return false\n if (!input.stdinIsTty) return false\n if (input.env.ASSISTANT_NON_INTERACTIVE_APPROVAL !== undefined) return false\n return true\n}\n\nfunction platformKey(o: SelfUpdateOptions): string {\n return `${o.platform ?? process.platform}-${o.arch ?? process.arch}`\n}\n\nfunction readCache(dataDir: string): UpdateCheckCache | null {\n try {\n const parsed = JSON.parse(readFileSync(cachePath(dataDir), 'utf8')) as Partial<UpdateCheckCache>\n if (typeof parsed.checkedAt !== 'number') return null\n return parsed as UpdateCheckCache\n } catch {\n return null\n }\n}\n\nfunction writeCache(dataDir: string, cache: UpdateCheckCache): void {\n try {\n mkdirSync(dataDir, { recursive: true })\n writeFileSync(cachePath(dataDir), JSON.stringify(cache))\n } catch {\n // A read-only home dir just means the check isn't throttled — never worth failing a session over.\n }\n}\n\nfunction parseManifest(json: unknown, allowInsecureHttp: boolean): ReleaseInfo {\n const m = json as { tag?: unknown; version?: unknown; assets?: unknown }\n if (typeof m?.tag !== 'string' || typeof m.version !== 'string' || typeof m.assets !== 'object' || m.assets === null) {\n throw new Error('Malformed update manifest')\n }\n const assets: Record<string, ReleaseAsset> = {}\n for (const [key, raw] of Object.entries(m.assets as Record<string, Record<string, unknown>>)) {\n if (typeof raw?.url !== 'string') continue\n assertHttps(raw.url, allowInsecureHttp)\n assets[key] = {\n url: raw.url,\n sha256: typeof raw.sha256 === 'string' ? raw.sha256.toLowerCase() : undefined,\n size: typeof raw.size === 'number' ? raw.size : undefined,\n }\n }\n return { tag: m.tag, version: m.version, assets, source: 'manifest' }\n}\n\ninterface GithubRelease {\n tag_name: string\n draft?: boolean\n prerelease?: boolean\n assets?: Array<{ name: string; browser_download_url: string; size?: number }>\n}\n\n/** `aielia-linux-x64` / `aielia-win32-x64.exe` → `linux-x64` / `win32-x64`; sidecar `.sha256` files are not binaries. */\nfunction assetKeyFromName(name: string): string | null {\n const m = /^aielia-([a-z0-9]+-[a-z0-9]+?)(?:\\.exe)?$/.exec(name)\n return m ? m[1] : null\n}\n\nfunction parseGithubReleases(releases: GithubRelease[], allowInsecureHttp: boolean): ReleaseInfo | null {\n let best: ReleaseInfo | null = null\n for (const r of releases) {\n if (r.draft || r.prerelease || !r.tag_name.startsWith(RELEASE_TAG_PREFIX)) continue\n const version = r.tag_name.slice(RELEASE_TAG_PREFIX.length)\n if (best && compareVersions(version, best.version) <= 0) continue\n const assets: Record<string, ReleaseAsset> = {}\n for (const a of r.assets ?? []) {\n const key = assetKeyFromName(a.name)\n if (!key) continue\n assertHttps(a.browser_download_url, allowInsecureHttp)\n assets[key] = { url: a.browser_download_url, size: a.size }\n }\n best = { tag: r.tag_name, version, assets, source: 'github' }\n }\n return best\n}\n\n/** `redirect: 'follow'` would silently accept an https -> http hop; refuse a response whose final URL is not https. */\nfunction assertFinalUrlHttps(res: Response, allowInsecureHttp: boolean): void {\n if (res.url) assertHttps(res.url, allowInsecureHttp)\n}\n\nasync function getJson(fetchFn: typeof fetch, url: string, headers: Record<string, string> = {}, allowInsecureHttp = false): Promise<Response> {\n const res = await fetchFn(url, { headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), redirect: 'follow' })\n assertFinalUrlHttps(res, allowInsecureHttp)\n return res\n}\n\n/**\n * Resolves the latest release: the product-scoped manifest first, the GitHub Releases API (filtered\n * to `aielia-v*` tags, ETag-cached) as fallback. A plain GET each — no query string, no\n * identifiers, default User-Agent only. Returns `notModified` when the API answered 304 to the\n * cached ETag; the caller then keeps the cached version.\n */\nexport async function fetchLatestRelease(\n options: SelfUpdateOptions,\n etag?: string,\n): Promise<{ release: ReleaseInfo; etag?: string } | { notModified: true }> {\n const fetchFn = options.fetchFn ?? fetch\n const insecure = options.allowInsecureHttp ?? false\n const manifestUrl = options.manifestUrl ?? MANIFEST_URL\n const apiUrl = options.releasesApiUrl ?? RELEASES_API_URL\n assertHttps(manifestUrl, insecure)\n assertHttps(apiUrl, insecure)\n\n let manifestError: unknown\n try {\n const res = await getJson(fetchFn, manifestUrl, {}, insecure)\n if (res.ok) return { release: parseManifest(await res.json(), insecure) }\n manifestError = new Error(`manifest HTTP ${res.status}`)\n } catch (err) {\n manifestError = err\n }\n\n const headers: Record<string, string> = { Accept: 'application/vnd.github+json' }\n if (etag) headers['If-None-Match'] = etag\n const res = await getJson(fetchFn, apiUrl, headers, insecure)\n if (res.status === 304 && etag) return { notModified: true }\n if (!res.ok) {\n throw new Error(`Could not check for updates (manifest: ${(manifestError as Error)?.message ?? manifestError}; GitHub: HTTP ${res.status})`)\n }\n const release = parseGithubReleases((await res.json()) as GithubRelease[], insecure)\n if (!release) throw new Error(`No ${RELEASE_TAG_PREFIX}* release found`)\n return { release, etag: res.headers.get('etag') ?? undefined }\n}\n\nexport interface UpdateCheckResult {\n latestVersion: string\n latestTag?: string\n updateAvailable: boolean\n}\n\n/**\n * The passive check: 24h-throttled via `<dataDir>/update-check.json`. Never throws — any failure\n * (offline, malformed manifest, …) resolves to `null`, since an unsolicited background check must\n * never disturb a session. Callers are responsible for gating it with `shouldRunPassiveUpdateCheck`\n * first and for not awaiting it before the prompt renders.\n */\nexport async function checkForUpdate(options: SelfUpdateOptions = {}): Promise<UpdateCheckResult | null> {\n const now = (options.now ?? Date.now)()\n const dataDir = options.dataDir ?? defaultDataDir()\n const current = options.currentVersion ?? CLI_VERSION\n const cached = readCache(dataDir)\n try {\n if (cached?.latestVersion && now - cached.checkedAt < CHECK_INTERVAL_MS) {\n return { latestVersion: cached.latestVersion, latestTag: cached.latestTag, updateAvailable: compareVersions(cached.latestVersion, current) > 0 }\n }\n const result = await fetchLatestRelease(options, cached?.etag)\n if ('notModified' in result) {\n writeCache(dataDir, { ...cached!, checkedAt: now })\n const v = cached!.latestVersion!\n return { latestVersion: v, latestTag: cached!.latestTag, updateAvailable: compareVersions(v, current) > 0 }\n }\n writeCache(dataDir, { checkedAt: now, latestVersion: result.release.version, latestTag: result.release.tag, etag: result.etag })\n return { latestVersion: result.release.version, latestTag: result.release.tag, updateAvailable: compareVersions(result.release.version, current) > 0 }\n } catch {\n return null\n }\n}\n\n/** One-line notice; the instruction branches on how this copy was installed. */\nexport function updateAvailableNotice(latestVersion: string, currentVersion: string, isSea: boolean): string {\n const how = isSea ? 'run `aielia update`' : `run \\`${NPM_UPDATE_HINT}\\``\n return `A newer aielia is available (${currentVersion} → ${latestVersion}) — ${how}.`\n}\n\n/** `isSea` the way the rest of the CLI decides it — false under npm/tsx, where nothing can be self-replaced. */\nexport function isRunningAsSea(): boolean {\n return loadSea() !== null\n}\n\n/** Removes leftovers of a previous update (the Windows `.old` rename-aside copy, an interrupted temp download). Never throws. */\nexport function cleanupStaleUpdateFiles(execPath: string = process.execPath): void {\n for (const stale of [`${execPath}.old`, `${execPath}.update.tmp`]) {\n try {\n if (existsSync(stale)) rmSync(stale, { force: true })\n } catch {\n // Still locked (e.g. the previous process hasn't fully exited) — the next launch retries.\n }\n }\n}\n\n/**\n * Replaces the binary at `execPath` with the already-verified file at `newFile` (same directory).\n * Unix: `rename` over the running binary — POSIX lets a still-open inode be replaced. Windows can't\n * overwrite a running exe, so the current one is renamed aside to `.old` first (cleaned up on the\n * next launch by `cleanupStaleUpdateFiles`), rolling back if the second rename fails.\n */\nexport function replaceBinary(execPath: string, newFile: string, platform: NodeJS.Platform = process.platform): void {\n if (platform === 'win32') {\n const aside = `${execPath}.old`\n rmSync(aside, { force: true })\n renameSync(execPath, aside)\n try {\n renameSync(newFile, execPath)\n } catch (err) {\n renameSync(aside, execPath)\n throw err\n }\n return\n }\n chmodSync(newFile, 0o755)\n renameSync(newFile, execPath)\n}\n\n/** Streams `url` to `dest`, returning the lowercase hex sha256 of exactly the bytes written. */\nasync function downloadTo(fetchFn: typeof fetch, url: string, dest: string, allowInsecureHttp = false): Promise<string> {\n const res = await fetchFn(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), redirect: 'follow' })\n if (!res.ok || !res.body) throw new Error(`Download failed: HTTP ${res.status} for ${url}`)\n // fetch follows redirects, and the HTTPS check above only saw the first URL: refuse a response\n // that ended up served over plain http (a downgrade redirect).\n if (res.url) assertHttps(res.url, allowInsecureHttp)\n const hash = createHash('sha256')\n // Start from nothing and refuse to write through anything already at the path (a planted symlink,\n // or another `aielia update` mid-download): 'wx' fails instead of following/sharing it.\n rmSync(dest, { force: true })\n await pipeline(\n Readable.fromWeb(res.body as unknown as WebReadableStream<Uint8Array>),\n async function* (source: AsyncIterable<Buffer>) {\n for await (const chunk of source) {\n hash.update(chunk)\n yield chunk\n }\n },\n createWriteStream(dest, { flags: 'wx' }),\n )\n return hash.digest('hex')\n}\n\n/** sha256 of the file as it is on disk right now — what `replaceBinary` will actually install, not what the stream carried. */\nasync function sha256OfFile(path: string): Promise<string> {\n const hash = createHash('sha256')\n for await (const chunk of createReadStream(path)) hash.update(chunk)\n return hash.digest('hex')\n}\n\nasync function fetchSidecarHash(fetchFn: typeof fetch, assetUrl: string, allowInsecureHttp = false): Promise<string | null> {\n try {\n const res = await getJson(fetchFn, `${assetUrl}.sha256`, {}, allowInsecureHttp)\n if (!res.ok) return null\n const m = /[0-9a-fA-F]{64}/.exec(await res.text())\n return m ? m[0].toLowerCase() : null\n } catch {\n return null\n }\n}\n\n/**\n * `aielia update [--dry-run]`. Returns the process exit code (0 = up to date / updated / dry-run\n * reported; 1 = refused or failed) and reports through `options.log`. Always does a fresh check —\n * never the throttled cache — and works regardless of the `updateCheck` opt-out.\n */\nexport async function runUpdateCommand(input: { dryRun?: boolean } & SelfUpdateOptions = {}): Promise<number> {\n const log = input.log ?? ((line: string) => console.log(line))\n const isSea = input.isSea ?? isRunningAsSea()\n const current = input.currentVersion ?? CLI_VERSION\n const dataDir = input.dataDir ?? defaultDataDir()\n const fetchFn = input.fetchFn ?? fetch\n const insecure = input.allowInsecureHttp ?? false\n\n if (!isSea) {\n log(`aielia update only replaces the standalone binary. This copy was installed with npm — run: ${NPM_UPDATE_HINT}`)\n return 1\n }\n\n let release: ReleaseInfo\n try {\n const result = await fetchLatestRelease(input) // no etag: an explicit update always wants a full answer\n if ('notModified' in result) throw new Error('unexpected 304')\n release = result.release\n writeCache(dataDir, { checkedAt: (input.now ?? Date.now)(), latestVersion: release.version, latestTag: release.tag, etag: result.etag })\n } catch (err) {\n log(`Could not check for updates: ${(err as Error).message}`)\n return 1\n }\n\n if (compareVersions(release.version, current) <= 0) {\n log(`aielia ${current} is up to date.`)\n return 0\n }\n\n const key = platformKey(input)\n const asset = release.assets[key]\n if (!asset) {\n log(`Release ${release.tag} has no build for ${key}.`)\n return 1\n }\n if (input.dryRun) {\n log(`Update available: ${current} → ${release.version} (${release.tag}). Would download ${asset.url}`)\n return 0\n }\n\n const execPath = input.execPath ?? process.execPath\n const tmp = `${execPath}.update.tmp`\n try {\n assertHttps(asset.url, insecure)\n log(`Downloading aielia ${release.version} (${key})…`)\n const actual = await downloadTo(fetchFn, asset.url, tmp, insecure)\n // Trust split: the binary comes from github.com, its hash from the manifest on myaielia.com —\n // verify against the manifest's hash so compromising one origin isn't enough. The sidecar file\n // next to the binary is only a cross-check (and the sole hash source on the GitHub-API fallback,\n // where both come from the same origin).\n const sidecar = await fetchSidecarHash(fetchFn, asset.url, insecure)\n const expected = asset.sha256 ?? sidecar\n if (!expected) throw new Error('No checksum available for this release — refusing to install an unverified binary')\n // Re-hash what is on disk: the streamed hash alone can't see the file being altered after it was written.\n const onDisk = await sha256OfFile(tmp)\n if (onDisk !== actual) throw new Error('Downloaded file changed on disk during verification — download discarded')\n if (actual !== expected) throw new Error(`Checksum mismatch (expected ${expected}, got ${actual}) — download discarded`)\n if (asset.sha256 && sidecar && sidecar !== asset.sha256) {\n throw new Error('Checksum sidecar disagrees with the release manifest — download discarded')\n }\n mkdirSync(dirname(execPath), { recursive: true })\n replaceBinary(execPath, tmp, input.platform)\n log(`Updated aielia ${current} → ${release.version}. Restart to use the new version.`)\n return 0\n } catch (err) {\n rmSync(tmp, { force: true })\n log(`Update failed: ${(err as Error).message}`)\n return 1\n }\n}\n","#!/usr/bin/env node\nimport { excludeAieliaStateFromGit } from './git-exclude.js'\nimport { createInterface } from 'node:readline'\nimport { writeFile } from 'node:fs/promises'\nimport { realpathSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join, resolve as resolvePath } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport {\n LLMClient,\n AnthropicLLMClient,\n OpenAICompatibleLLMClient,\n ANTHROPIC_DEFAULT_MODEL,\n OPENAI_BASE_URL,\n OPENAI_DEFAULT_MODEL,\n OPENROUTER_BASE_URL,\n OPENROUTER_DEFAULT_MODEL,\n defaultModelForBackend,\n OPENROUTER_EXTRA_HEADERS,\n FileSystemAdapter,\n FileSystemExperienceStore,\n InMemoryReminderStore,\n type ILLMClient,\n type TokenUsage,\n type FsBackend,\n} from '@buildaharness/runtime'\nimport type { AskAnswer, AskQuestion, AskQuestionOption, AskResponse } from '@buildaharness/harness'\nimport { PersonalAssistant, type AssistantProgress, type AssistantTrace, type AssistantSource, type AssistantTurnResult } from './assistant.js'\nimport { memoryAuditLogEnabled } from './memory-service.js'\nimport { activityLogEnabled, createActivityLogger } from './activity-log.js'\nimport type { AssistantToolStep } from './tool-step.js'\nimport type { PlanDecision, PlanApprovalEdits } from './plan-approval-service.js'\nimport { nodeDisplayName, nodeToLayer, buildWhyChain, LAYER_ORDER, LAYER_DISPLAY_NAME, LAYER_SHORT_CODE } from './node-display-names.js'\nimport { classifyError } from './error-classifier.js'\nimport { createNodeFsBackend } from './node-fs-backend.js'\nimport { ClaudeCliLLMClient } from './claude-cli-llm-client.js'\nimport { runApprovedShellCommand } from './shell-executor.js'\nimport { createResendSender, type SendEmail } from './email.js'\nimport { createSmtpSender } from './email-smtp.js'\nimport { braveSearch } from './web-search-provider.js'\nimport { resolveConfig, validateConfig, ConfigValidationError, type AssistantConfig, type ConfigStore } from './config.js'\nimport { NodeConfigStore } from './node-config-store.js'\nimport { applyLayerSettings, formatLayerListing, sanitizeLayerChoices, withLayerChoice, LayerSettingError } from './layer-settings.js'\nimport { isConfigKey, findInvalidNumericSettings, envOverridesFromProcessEnv, parseConfigValue, ConfigValueParseError, formatConfigListing, ENV_VAR_FOR_CONFIG_KEY, CONFIG_KEYS } from './cli-config.js'\nimport { stripTerminalControls, formatHelp, isQuitCommand, formatStatus, formatTranscriptMarkdown, defaultExportFilename, formatMemorySummary, formatMemoryExport, defaultMemoryExportFilename, formatSearchResults, formatGoalGraphState, formatNextSteps, formatCostSummary, formatDoctorReport, formatUndoLogListing, formatMemoryPendingOutcome, formatMemoryHistory, formatMemoryArchive, formatMemoryInjection, formatMemoryStatus } from './cli-session.js'\nimport { estimateCostUsd } from './model-pricing.js'\nimport { formatSpendCapStatus } from './spend-cap.js'\nimport { checkProxyHealth, checkClaudeCli, checkWorkspaceRoot, checkDataDirWritable, checkMemoryHealth } from './doctor-checks.js'\nimport { resolveNonInteractiveApprovalMode, type NonInteractiveApprovalMode } from './non-interactive-mode.js'\nimport { LiveSteeringChannel } from './live-steering-channel.js'\nimport { isGoalGraphEnabled } from './goal-graph-flag.js'\nimport { isPlanGraphEnabled } from './plan-graph-flag.js'\nimport { planToSnapshot } from './plan-viz/plan-snapshot.js'\nimport { renderPlan } from './plan-viz/plan-raster.js'\nimport type { VizNode } from './plan-viz/types.js'\nimport type { TaskStatus } from '@buildaharness/harness'\nimport { isGoalGraphSuggestEnabled } from './goal-graph-suggest-flag.js'\nimport type { NextStepSuggestion } from './next-step-proposer.js'\nimport { maybeRunFirstRunSetup } from './first-run.js'\nimport { testApiKey, type KeyedBackend, type KeyTestResult } from './provider-setup.js'\nimport { DEFAULT_TUI_MODE, shouldLaunchTuiApp } from './tui-mode-flag.js'\nimport { ICONS, toolStepIcon, PLAN_LINE_PREFIX } from './cli-icons.js'\nimport { parseCliArgs, cliHelpText } from './cli-args.js'\nimport {\n runUpdateCommand,\n checkForUpdate,\n cleanupStaleUpdateFiles,\n isRunningAsSea,\n shouldRunPassiveUpdateCheck,\n updateAvailableNotice,\n} from './self-update.js'\nimport { CLI_VERSION } from './version.js'\n\n/** console.log for any text that can carry stored, model, tool or web content: terminal escape sequences and other control characters are removed (same filter as stripTerminalControls), plain text is unchanged. */\nfunction printSafe(...args: unknown[]): void {\n console.log(...args.map((a) => (typeof a === 'string' ? stripTerminalControls(a) : a)))\n}\n\n\nconst defaultDataDir = join(homedir(), '.buildaharness', 'personal-assistant')\nconst defaultConfigStore = new NodeConfigStore(join(defaultDataDir, 'config.json'))\n\n// Must match the exact path a FileSystemAdapter({ baseDir: dataDir, namespace:\n// 'reminders' }) uses for the key \"reminders\" — see file-tools-mcp-server.mjs's\n// doc comment — so the claude-cli backend's MCP subprocess and this process's\n// own reminderStore (below) read/write the same file instead of two disconnected\n// reminder lists. FileSystemAdapter's path formula is `${baseDir}/${namespace}/${sanitize(key)}.json`,\n// and \"reminders\" sanitizes to itself (no special characters).\nconst defaultRemindersFile = join(defaultDataDir, 'reminders', 'reminders.json')\n\n// Env vars still win over persisted config — see cli-config.ts's envOverridesFromProcessEnv\n// and config.ts's resolveConfig — so this stays a behavior-preserving migration for anyone\n// who already sets ASSISTANT_ENABLE_WEB etc. and never touches /config.\nconst defaultEnvOverrides = envOverridesFromProcessEnv(process.env)\n\nconst defaultNonInteractiveApprovalMode = resolveNonInteractiveApprovalMode(process.env)\n\n// create() only supplies a default for storage the caller didn't already pass in (and falls\n// back to in-memory outside a browser) — passing this explicit, filesystem-backed store is\n// what gives the CLI real persistence across runs. See the internal plan Phase 3.\nconst defaultBackend = createNodeFsBackend()\n\n/**\n * Builds the SendEmail transport for an approved `send_email` action, or undefined when email\n * isn't fully configured (validateConfig already rejects `enableEmail` without a usable transport,\n * so in practice this only returns undefined when `enableEmail` is off). The model never reaches\n * this — it only ever proposes; delivery happens here after approval.\n */\nfunction buildEmailSender(config: AssistantConfig): SendEmail | undefined {\n if (!config.enableEmail || !config.emailFrom) return undefined\n if (config.emailProvider === 'smtp' && config.smtpHost && config.smtpPort) {\n return createSmtpSender({\n host: config.smtpHost,\n port: config.smtpPort,\n auth: config.smtpUser && config.smtpPass ? { user: config.smtpUser, pass: config.smtpPass } : undefined,\n from: config.emailFrom,\n })\n }\n if (config.emailProvider === 'resend' && config.resendApiKey) {\n return createResendSender({ apiKey: config.resendApiKey, from: config.emailFrom })\n }\n return undefined\n}\n\n/**\n * Picks the ILLMClient for config.llmBackend — one branch per backend, shared in shape with\n * chat-ui's App.tsx createLlmClient() (both switch over the same 5 values), but this one stays\n * CLI-only: claude-cli here is a real node:child_process subprocess (ClaudeCliLLMClient), not\n * the Tauri-bridged equivalent chat-ui's desktop build uses, and it's the only backend always\n * available on this surface (no \"unsupported on this platform\" branch needed, unlike a plain\n * browser tab which can't spawn `claude` at all).\n */\nfunction buildLlmClient(config: AssistantConfig, workspaceRoot: string, remindersFile: string): ILLMClient {\n switch (config.llmBackend) {\n case 'claude-cli':\n return new ClaudeCliLLMClient({\n fileTools: { workspaceRoot },\n remindersFile,\n shellTools: config.enableShell ? { workspaceRoot } : undefined,\n webTools: config.enableWeb ? { braveApiKey: config.braveApiKey as string | undefined } : undefined,\n actionTools: config.enableEmail ? { workspaceRoot } : undefined,\n })\n case 'anthropic':\n return new AnthropicLLMClient({ apiKey: config.apiKey ?? '' })\n case 'openai':\n return new OpenAICompatibleLLMClient({ apiKey: config.apiKey ?? '', baseUrl: OPENAI_BASE_URL, defaultModel: OPENAI_DEFAULT_MODEL })\n case 'openrouter':\n return new OpenAICompatibleLLMClient({\n apiKey: config.apiKey ?? '',\n baseUrl: OPENROUTER_BASE_URL,\n defaultModel: OPENROUTER_DEFAULT_MODEL,\n extraHeaders: OPENROUTER_EXTRA_HEADERS,\n })\n case 'proxy':\n return new LLMClient({ proxyUrl: config.proxyUrl, authToken: config.authToken })\n }\n}\n\n/**\n * Builds a fresh PersonalAssistant (and the llmClient/search function it depends on) from a\n * resolved AssistantConfig — called once at startup and again after any /config change that\n * takes effect, so nothing requires a process restart. Reuses the same dataDir-backed stores\n * each time, so transcripts/experience/checkpoints/reminders carry over across a rebuild.\n */\ninterface BuildAssistantDeps {\n backend: FsBackend\n dataDir: string\n remindersFile: string\n}\n\nasync function buildAssistant(config: AssistantConfig, { backend, dataDir, remindersFile }: BuildAssistantDeps): Promise<PersonalAssistant> {\n const workspaceRoot = config.workspaceRoot ?? process.cwd()\n // Aielia's state dirs must not show up in the user's `git status` or end up in their commits. Only for the real disk\n // backend: an injected one (tests) does not write into the working tree, and must not edit a real repo's git config.\n if (backend === defaultBackend) excludeAieliaStateFromGit(workspaceRoot)\n const search = (query: string) => braveSearch(query, config.braveApiKey as string)\n\n // `search` above is the proxy backend's injected web_search implementation (its manual\n // tool loop calls it directly). The claude-cli backend can't take an injected function —\n // its tools run inside the `claude -p` subprocess — so buildLlmClient passes the same\n // Brave key through to the file-tools MCP server as env instead. Either way, `enableWeb`\n // now wires web_search on both backends.\n const llmClient = buildLlmClient(config, workspaceRoot, remindersFile)\n\n return PersonalAssistant.create({\n llmClient,\n // Name the backend's real default when none is set, so spend tracking prices the model that actually runs (not the Anthropic default).\n model: config.model ?? defaultModelForBackend(config.llmBackend),\n // config.activeProject (set via /project <name>) overrides the default of \"the workspace\n // I'm running in\" — see PersonalAssistantOptions.activeProject's doc comment.\n activeProject: config.activeProject || workspaceRoot,\n memoryBudgetChars: config.memoryBudgetChars,\n memoryWriteMode: config.memoryWriteMode,\n // M5: consolidation proposals are staged for /memory consolidate; the CLI has the controls, so it may raise them on /new.\n consolidateOnNewSession: true,\n memory: new FileSystemAdapter({ backend, baseDir: dataDir, namespace: 'transcripts' }),\n experienceStore: await FileSystemExperienceStore.create({ backend, baseDir: dataDir, namespace: 'experience' }),\n checkpointStore: new FileSystemAdapter({ backend, baseDir: dataDir, namespace: 'checkpoints' }),\n reminderStore: new InMemoryReminderStore(new FileSystemAdapter({ backend, baseDir: dataDir, namespace: 'reminders' })),\n fileTools: { backend, workspaceRoot },\n webTools: config.enableWeb ? { search } : undefined,\n // executeCommand is the real child_process.spawn-based implementation (shell-executor.ts) —\n // wired in here, not inside assistant.ts, so the browser build never needs node:child_process.\n shellTools: config.enableShell\n ? { backend, workspaceRoot, timeoutMs: config.shellTimeoutMs, networkAllowlist: config.shellNetworkAllowlist, executeCommand: runApprovedShellCommand }\n : undefined,\n // The Resend/SMTP transport is wired in here, not inside assistant.ts, so the browser build\n // never needs nodemailer or a mail server — same split as shellTools' executeCommand.\n actionTools: (() => {\n const sendEmail = buildEmailSender(config)\n return sendEmail ? { backend, workspaceRoot, sendEmail } : undefined\n })(),\n dangerouslySkipPermissions: config.dangerouslySkipPermissions,\n // Opt-in durable record of tool calls/results and approvals (see activity-log.ts).\n onDebugLog: activityLogEnabled(process.env) ? createActivityLogger(join(dataDir, 'activity-log.jsonl')) : undefined,\n spendCap:\n config.sessionCostLimitUsd !== undefined || config.sessionCallLimit !== undefined\n ? { sessionCostLimitUsd: config.sessionCostLimitUsd, sessionCallLimit: config.sessionCallLimit }\n : undefined,\n // Resolved through the shared config seam (cli-config.ts's envOverridesFromProcessEnv reads\n // ASSISTANT_ONE_LOOP into config.oneLoopMode; /config set oneLoopMode persists it) so the CLI,\n // chat-ui, and the Tauri desktop build all decide this the same way. Undefined here means\n // PersonalAssistant falls back to DEFAULT_ONE_LOOP_MODE.\n oneLoopMode: config.oneLoopMode,\n layerPolicyMode: config.layerPolicyMode,\n // R7: turn-end next-step options and DONE-thread suggestions. Undefined config means the\n // package default (enabled); PersonalAssistant itself defaults to disabled, so this is where\n // the front end opts in.\n goalGraphSuggestMode: isGoalGraphSuggestEnabled(config.goalGraphSuggestMode) ? 'enabled' : 'disabled',\n // P11 of the internal plan — resolved through the same shared config\n // seam as oneLoopMode above (ASSISTANT_PLAN_MODE / `/config set planMode`). Undefined here\n // means PersonalAssistant falls back to DEFAULT_PLAN_MODE ('legacy').\n planMode: config.planMode,\n ambiguityGuardMode: config.ambiguityGuardMode,\n })\n}\n\n/**\n * One choice in a structured multi-option prompt (Phase 7 of the internal plan\n * — the numbered/arrow-key approval selector). `key` is both the single-character shortcut shown\n * inline next to the option and the value `askSelect` resolves with; callers order options with\n * the safe/fail-closed choice last, matching `askYesNo`'s own \"no real answer → treat as declined\"\n * convention (see `askSelect`'s default implementation below, and `ink-select-prompt.tsx`'s\n * `SelectPrompt`, which renders this same list with arrow-key highlight + per-key shortcuts).\n */\nexport interface SelectOption {\n key: string\n label: string\n}\n\nexport interface RunCliOptions {\n /**\n * The Ink shell's seam for `/plan graph` (planGraphMode enabled): called with the drawable nodes to open the\n * full-screen pane. Without it (plain REPL, piped input) `/plan graph` prints one static render instead.\n */\n openPlanGraph?: (nodes: VizNode[]) => void\n /** Live per-task statuses from a running turn, forwarded for the open plan graph pane. */\n onPlanProgress?: (tasks: { id: string; status: TaskStatus }[]) => void\n /**\n * Called with true when a conversational turn starts being worked on and false when it has finished (in a\n * `finally`, so also after an error) — including turns run as deferred follow-ups, which no `dispatchLine()`\n * promise covers. The TUI's liveness indicator follows this rather than guessing from output events.\n */\n onTurnBusyChange?: (busy: boolean) => void\n dataDir?: string\n configStore?: ConfigStore\n backend?: FsBackend\n remindersFile?: string\n envOverrides?: Partial<AssistantConfig>\n nonInteractiveApprovalMode?: NonInteractiveApprovalMode\n input?: NodeJS.ReadableStream\n output?: NodeJS.WritableStream\n /**\n * Bypasses buildAssistant()'s config-driven backend selection entirely — the seam tests use\n * to hand runCli a PersonalAssistant wired to a scripted ILLMClient (same pattern as\n * assistant.test.ts) for deterministic command-dispatch/approval-flow coverage. When set, a\n * /config change that would otherwise rebuild the assistant leaves this instance in place.\n */\n assistant?: PersonalAssistant\n /** Overrides the rl.question-based approval prompt — lets tests script approve/decline answers without faking stdin/a real TTY. */\n askYesNo?: (question: string) => Promise<boolean>\n /** Overrides the rl.question-based free-text prompt the clarification sub-loop uses for option numbers, edit notes, and \"Other\" free text — lets tests script a multi-step answer without faking stdin/a real TTY. */\n askLine?: (question: string) => Promise<string>\n /** Overrides the rl.question-based structured multi-option prompt (Phase 7's approval selector) — lets tests script a selection by key without faking stdin/a real TTY. Resolves with the chosen `SelectOption.key`. */\n askSelect?: (question: string, options: SelectOption[]) => Promise<string>\n /** Test seam: skip the interactive first-run setup regardless of TTY state (also implied when `assistant` is passed). */\n skipFirstRunSetup?: boolean\n /** Test seam: script the first-run setup's line reads. */\n firstRunAsk?: (question: string) => Promise<string>\n /** Test seam: stub the live API-key check in the first-run setup (defaults to a real call to the provider). */\n firstRunTestKey?: (backend: KeyedBackend, key: string) => Promise<KeyTestResult>\n}\n\nexport interface CliInstance {\n /** Parses and dispatches one line of input exactly as the REPL's 'line' handler does (same dispatchQueue serialization) — the seam cli.test.ts drives command dispatch through without a live TTY. */\n dispatchLine(line: string): Promise<void>\n close(): void\n /**\n * Additive, read-only accessor for the pinned-input TUI shell's status line\n * (the internal plan Phase 3) — the same two signals\n * printStatus() already renders as part of `/status` (lastPlanStatus !== undefined,\n * spendCapStatusLine()), just exposed here instead of only printed. Returns short indicator\n * strings in priority order; empty when there's nothing to report. Not used by the ordinary\n * readline REPL or by non-interactive/piped mode — only the TUI shell polls this.\n */\n getStatusIndicators(): Promise<string[]>\n /** Read-only: the plan graph's drawable nodes (with `live` statuses overlaid), or undefined when planGraphMode is disabled or there is no plan. Feeds the TUI's open plan graph pane. */\n getPlanGraphNodes(live?: { id: string; status: TaskStatus }[]): Promise<VizNode[] | undefined>\n}\n\n/**\n * The CLI's REPL, parameterized so cli.test.ts can import and drive it directly instead of only\n * through a live process (see non-interactive-mode.ts's doc comment for why that mattered before\n * this export existed — this is T1's answer to it). `main()` below calls this with no options,\n * getting exactly today's behavior; every option here has a real-filesystem/real-stdio default.\n */\nexport async function runCli(options: RunCliOptions = {}): Promise<CliInstance> {\n const dataDir = options.dataDir ?? defaultDataDir\n const configStore = options.configStore ?? defaultConfigStore\n const backend = options.backend ?? defaultBackend\n const remindersFile = options.remindersFile ?? defaultRemindersFile\n const envOverrides = options.envOverrides ?? defaultEnvOverrides\n const nonInteractiveApprovalMode = options.nonInteractiveApprovalMode ?? defaultNonInteractiveApprovalMode\n\n const inputStream = options.input ?? process.stdin\n const outputStream = options.output ?? process.stdout\n\n let persisted = await configStore.load()\n let { config, overriddenKeys } = resolveConfig(persisted, envOverrides)\n // The layers' AUDIT_* flags are the single source each layer reads, so the saved /layers choices are written onto process.env\n // (a flag the operator already set stays and is reported pinned). Re-run after every config change.\n let layerPins = applyLayerSettings(sanitizeLayerChoices(config.layers), process.env).pinned\n\n // First run with nothing configured: offer a one-line setup rather than\n // silently starting on the proxy backend against a proxy that isn't running.\n if (!options.skipFirstRunSetup && !options.assistant) {\n const isInteractive = (inputStream as NodeJS.ReadStream).isTTY === true\n let setupRl: ReturnType<typeof createInterface> | undefined\n const firstRunAsk =\n options.firstRunAsk ??\n ((question: string) => {\n setupRl ??= createInterface({ input: inputStream, output: outputStream })\n return new Promise<string>((resolvePrompt) => {\n setupRl!.question(question, (answer) => resolvePrompt(answer.trim()))\n })\n })\n try {\n persisted = await maybeRunFirstRunSetup({\n configStore,\n persisted,\n overriddenKeys,\n isInteractive,\n ask: firstRunAsk,\n log: (line) => outputStream.write(`${line}\\n`),\n testKey: options.firstRunTestKey ?? ((backend, key) => testApiKey(backend, key)),\n })\n } finally {\n setupRl?.close()\n }\n ;({ config, overriddenKeys } = resolveConfig(persisted, envOverrides))\n layerPins = applyLayerSettings(sanitizeLayerChoices(config.layers), process.env).pinned\n }\n\n try {\n validateConfig({}, config)\n const numericProblems = findInvalidNumericSettings(config)\n if (numericProblems.length > 0) throw new ConfigValidationError(numericProblems.join(' '))\n } catch (err) {\n if (!(err instanceof ConfigValidationError)) throw err\n // Thrown, not printed + process.exit()ed here: under the Ink TUI console/stderr are captured into the (never rendered)\n // event log at this point, so a message printed here was lost and the process vanished without a word. main() prints\n // it on the real stderr, after the capture is restored, and sets a non-zero exit code.\n throw new StartupError(\n `Aielia cannot start with this configuration: ${err.message}\\n` +\n `Fix it by setting the missing value (in the config file under ${dataDir}, or via the matching ASSISTANT_* environment variable), ` +\n 'or by turning that feature off, then start again.',\n )\n }\n\n // Checked before anything else starts, not lazily at the first approval prompt — a session\n // that ran tool calls for several turns before hitting a HIGH-risk gate would otherwise fail\n // deep in, with no chance to recover the work already done, instead of failing immediately\n // with a clear explanation of what to do about it.\n if (nonInteractiveApprovalMode === 'require-tty' && !process.stdin.isTTY) {\n throw new StartupError(\n 'ASSISTANT_NON_INTERACTIVE_APPROVAL=require-tty is set, but stdin is not a real TTY ' +\n '(piped/scripted input). Refusing to start rather than fail confusingly at the first ' +\n 'approval prompt — see README.md\\'s \"Non-interactive / scripted use\" section for the ' +\n 'alternative (ASSISTANT_NON_INTERACTIVE_APPROVAL=decline).',\n )\n }\n\n let assistant = options.assistant ?? (await buildAssistant(config, { dataDir, backend, remindersFile }))\n\n const rl = createInterface({ input: options.input ?? process.stdin, output: options.output ?? process.stdout, prompt: 'you> ' })\n // Paused immediately, synchronously, before any awaits below get a chance to yield the event\n // loop: createInterface() switches its input stream to flowing mode as soon as it attaches its\n // own internal 'data' listener, so once we hit e.g. the listUndoLogEntries() await further\n // down, a piped/heredoc input whose lines are already fully buffered by the OS gets parsed into\n // 'line' events right then — and since EventEmitter#emit never queues an event for a listener\n // that isn't there yet, every line parsed before rl.on('line', ...) near the bottom of this\n // function runs is silently dropped, not just delayed. rl.prompt() below auto-resumes if\n // paused, but that resume is itself deferred (stream.resume() only schedules a nextTick flow\n // start) and everything from here to the rl.on('line', ...)/rl.resume() pair at the bottom\n // runs synchronously with no further awaits, so the listener is always in place first.\n rl.pause()\n\n // With no 'SIGINT' listener, readline's own Ctrl+C handling just pauses the interface\n // instead of exiting (see readline's 'SIGINT' event docs) — silently contradicting the\n // startup banner's \"Ctrl+C to exit\". Registering this listener makes Ctrl+C actually exit.\n rl.on('SIGINT', () => {\n printSafe('\\nExiting.')\n process.exit(0)\n })\n\n // Display-only defaults, mirroring each backend's own fallback so the banner shows the\n // model that will actually be used even when config.model is unset — not authoritative\n // (each llmClient picks its own default independently), but sourced from the same\n // @buildaharness/runtime constants those clients use so the banner can't drift from them.\n const backendDisplayModel: Record<AssistantConfig['llmBackend'], string> = {\n proxy: ANTHROPIC_DEFAULT_MODEL,\n 'claude-cli': '(your Claude Code default)',\n anthropic: ANTHROPIC_DEFAULT_MODEL,\n openai: OPENAI_DEFAULT_MODEL,\n openrouter: OPENROUTER_DEFAULT_MODEL,\n }\n const backendLine = `${config.llmBackend} · ${config.model ?? backendDisplayModel[config.llmBackend]}`\n\n // No silent default: capabilities only appear in the banner when actually configured,\n // so the banner never implies something is available that isn't.\n const enabledCapabilities: string[] = []\n if (config.enableWeb) enabledCapabilities.push('web search/fetch (brave)')\n if (config.enableShell) enabledCapabilities.push(`shell commands (${config.dangerouslySkipPermissions ? 'NOT approval-gated' : 'approval-gated'})`)\n const capabilityRow = enabledCapabilities.length > 0 ? `\\n tools ${enabledCapabilities.join(', ')}` : ''\n // Loud and separate from the capability list above (which is easy to skim past) —\n // this changes the trust model for every HIGH-risk action, not just shell.\n const dangerBanner = config.dangerouslySkipPermissions\n ? '\\n ⚠ dangerouslySkipPermissions is ON — every approval prompt is skipped automatically.'\n : ''\n // Same \"never silently in effect\" reasoning as dangerBanner above — the opposite trust\n // direction (declines instead of skips), but just as important to surface up front.\n const nonInteractiveBanner =\n nonInteractiveApprovalMode === 'decline'\n ? '\\n ⚠ ASSISTANT_NON_INTERACTIVE_APPROVAL=decline — every approval prompt auto-declines.'\n : ''\n\n // The undo-log persists across sessions (it's on disk under the workspace, not in-memory) —\n // surfaced here so a user doesn't discover leftover revertible actions from a prior session\n // only by happening to run /undo-action or /status (T6).\n const startupUndoLogEntries = await assistant.listUndoLogEntries()\n const undoableFromBefore = startupUndoLogEntries.filter((e) => e.undoable).length\n const undoBanner =\n undoableFromBefore > 0\n ? `\\n undo ${undoableFromBefore} earlier action${undoableFromBefore === 1 ? '' : 's'} can be reverted with /undo-action`\n : ''\n\n // The ledger is lifetime-cumulative (persisted across runs), so the status line's \"this session\" figures are the delta from here.\n const startupSpend = await assistant.getSpendState('cli')\n const fmtUsage = (input: number, output: number, cost: number): string => `↑${input.toLocaleString()} ↓${output.toLocaleString()} tokens (~$${cost.toFixed(4)})`\n const totalUsageRow = `\\n total ${fmtUsage(startupSpend.cumulativeInputTokens, startupSpend.cumulativeOutputTokens, startupSpend.cumulativeCostUsd)} across all sessions`\n printSafe(\n [\n `Aielia v${CLI_VERSION}`,\n 'Your personal assistant, one turn at a time.',\n ' ',\n ` backend ${backendLine}${capabilityRow}${undoBanner}${totalUsageRow}${dangerBanner}${nonInteractiveBanner}`,\n ' ',\n ' /help commands /config settings Ctrl+C exit',\n ' Alpha software: it can make mistakes, so verify anything important.',\n ' ',\n ].join('\\n'),\n )\n // M5: session start consolidates what earlier sessions left. Background, fail-open, a no-op unless AUDIT_MEMORY_CONSOLIDATION is on.\n void assistant.proposeMemoryConsolidation('cli').catch(() => undefined)\n rl.prompt()\n\n let lastTrace: AssistantTrace | undefined\n let lastSources: AssistantSource[] | undefined\n let lastPlanStatus: AssistantTurnResult['planStatus']\n // A whole-plan approval that was staged but not yet resolved (status 'needs_plan_approval') —\n // kept so the /plan approve|decline|edit commands can resolve it after the turn has already\n // returned control to the prompt. Cleared the moment a decision is dispatched. Without this,\n // a staged plan had no way to be approved or declined at all from the CLI (chat-ui's\n // PlanApprovalCard + its handlers were the only surface that could resolve one).\n let pendingPlanApproval: { id: string; message: string; snapshot: AssistantTurnResult['planApproval'] } | undefined\n let lastTurnUsage: TokenUsage | undefined\n // Tool calls made by the most recent turn — used only so /undo can warn about a real\n // side effect (e.g. a created reminder) it's about to claim to have removed but can't\n // actually reverse. Reset at the start of every handleTurn call, see writeToolStep below.\n let lastTurnToolSteps: AssistantToolStep[] = []\n // Set whenever the last turn was blocked on an approval gate (message-level risk or a\n // staged write/shell command) and then declined, or escalated — lastTrace stays whatever it\n // was before in either case (neither path ever runs the harness), so without this /why and\n // /layers would fall back to the generic \"nothing to explain yet, or it took the fast path\"\n // message even right after a real, user-visible decline. That reads as if nothing happened,\n // when something very much did. Cleared whenever a turn actually produces a trace, and on /new.\n let lastNoTraceReason: string | undefined\n\n // Phase 7's \"don't ask again\" option, session-scoped only (reset on every process start, never\n // written to `configStore`). `tool-policy.ts`'s `ControlState` (the harness's own per-turn\n // permission/escalation resolver) was checked as the natural home for this and rejected: it's\n // recomputed fresh from world-model evidence every turn with no persisted-preference field at\n // all, so wiring a durable \"remembered\" flag through it would mean inventing new cross-turn\n // state inside a module that's deliberately a pure, stateless decision function today. A plain\n // in-memory Set scoped to this `runCli()` closure gets the same \"stop asking me this\" behavior\n // Codex/Claude Code's own selector offers, without that architectural change — at the cost of\n // not surviving a restart, which matches this being explicitly a per-session convenience, not a\n // durable trust decision. Keyed coarsely (pendingActionKind / riskLevel), not per fine-grained\n // command pattern — a finer key would need the same new persisted-state work this deliberately\n // avoids.\n const rememberedActionKinds = new Set<string>()\n const rememberedRiskLevels = new Set<string>()\n\n /** The three choices every approval prompt offers (Phase 7) — \"No\" last, so `askSelect`'s fail-closed fallback (no real answer read) always resolves to declining, never approving. */\n const APPROVAL_OPTIONS: SelectOption[] = [\n { key: 'y', label: 'Yes' },\n { key: 'a', label: \"Yes, don't ask again this session\" },\n { key: 'n', label: 'No' },\n ]\n\n /** claude-cli is the only backend that returns a real dollar cost (--output-format json's total_cost_usd) — every other backend (proxy, and now anthropic/openai/openrouter, none of which surface billing via TokenUsage.costUsd) gets an approximate estimate instead, see model-pricing.ts. */\n function withCostEstimate(usage: TokenUsage): TokenUsage {\n if (config.llmBackend === 'claude-cli' || usage.costUsd !== undefined) return usage\n const estimated = estimateCostUsd(config.model ?? ANTHROPIC_DEFAULT_MODEL, usage)\n return estimated !== undefined ? { ...usage, costUsd: estimated } : usage\n }\n\n const PLAN_TASK_STATUS_ICON: Record<string, string> = {\n PENDING: '○', RUNNING: '▶', COMPLETE: '✓', FAILED: '✗', BLOCKED: '✗', HUMAN_REQUIRED: '~',\n }\n\n function printPlan(): void {\n if (!lastPlanStatus) {\n printSafe('\\nNo active plan for this session.\\n')\n return\n }\n // Phase 6 of the CLI formatting plan (\"distinct plan-mode UI\") — one combined console.log\n // call, prefixed with PLAN_LINE_PREFIX, so the TUI's classifyLineKind (tui-app.tsx) renders\n // the whole block as a single bordered PlanBox instead of plain 'system' text one line at a\n // time. Prefix goes on its own leading line (stripped for display, same convention as\n // ASSISTANT_REPLY_PREFIX) rather than glued onto \"Plan: …\" so it can never visually collide\n // with real plan content. The plain (non-TUI) CLI path also goes through this same\n // console.log call — startCapture's classify() there just emits the marker line as-is; the\n // TUI-specific stripping never runs, and the marker glyph is unusual enough not to be\n // mistaken for real output outside the TUI, matching how ASSISTANT_REPLY_PREFIX already\n // behaves in non-TUI mode.\n const lines = [\n PLAN_LINE_PREFIX,\n `Plan: ${lastPlanStatus.templateName ?? 'custom plan'} (${lastPlanStatus.completionPct.toFixed(1)}% complete)`,\n ...lastPlanStatus.tasks.flatMap((task) => [\n ` ${PLAN_TASK_STATUS_ICON[task.status] ?? '?'} [${task.status}] ${task.id} — ${task.description}`,\n ...(task.note ? [` not accepted as done: ${task.note}`] : []),\n ]),\n `Success criteria: ${lastPlanStatus.successCriteria}`,\n ]\n console.log(stripTerminalControls(`\\n${lines.join('\\n')}\\n`))\n }\n\n /**\n * P9 of the internal plan — `/plan sketch <request>` invokes the\n * lightweight plan-sketch delegate (PersonalAssistant.sketchPlan): one bounded, advisory LLM\n * call that prints a proposed task list directly, with no approve/decline controls (nothing was\n * staged — INV-35) and no effect on `/plan`'s own drafting-plan display above.\n */\n async function handlePlanSketch(args: string[]): Promise<void> {\n const request = args.join(' ').trim()\n if (!request) {\n printSafe('\\nUsage: /plan sketch <request>\\n')\n return\n }\n printSafe('\\nSketching a plan (read-only grounding only, nothing staged)...\\n')\n const result = await assistant.sketchPlan('cli', request)\n // Phase 6 of the CLI formatting plan: this is genuine LLM-authored prose (often markdown —\n // headers, `- [ ]` checklists), not deterministic CLI-controlled text, so it's routed through\n // the same 'Aielia>' marker as an ordinary chat reply rather than left to default-classify as\n // plain 'system' text — the TUI's classifyLineKind (tui-app.tsx) then renders it through the\n // existing assistant-reply markdown path (markdown-line.tsx) instead of printing literal\n // '##'/'- [ ]' characters, the same gap the underlying report flagged for the legacy\n // (DEFAULT_PLAN_MODE) prose path specifically.\n console.log(stripTerminalControls(`Aielia> ${result.reply ?? '(no reply)'}\\n`))\n if (result.usage) lastTurnUsage = withCostEstimate(result.usage)\n }\n\n /**\n * The choices a staged whole-plan approval offers — the CLI counterpart to chat-ui's\n * `PlanApprovalCard` buttons, resolved through the exact same `PlanApprovalService`. `'d'`\n * (\"decide later\") is CLI-specific: unlike the action-approval prompt above, a plan is a\n * document worth reading before signing off, so returning control to the REPL (with the\n * /plan approve|edit|decline commands) beats forcing an answer under the prompt. `'n'` (Decline)\n * stays last so `askSelect`'s fail-closed fallback can only ever decline, never approve.\n */\n const PLAN_APPROVAL_OPTIONS: SelectOption[] = [\n { key: 'y', label: 'Approve' },\n { key: 'e', label: 'Approve with edits' },\n { key: 't', label: 'Approve & trust this plan (its write/shell steps stop re-prompting)' },\n { key: 'd', label: 'Decide later — /plan approve|edit|decline' },\n { key: 'n', label: 'Decline' },\n ]\n\n /** Renders a plan staged for approval — same PLAN_LINE_PREFIX-wrapped single console.log as printPlan, so the TUI's classifyLineKind (tui-app.tsx) draws it as one bordered PlanBox. */\n function printPlanApproval(snapshot: NonNullable<AssistantTurnResult['planApproval']>): void {\n const lines = [\n PLAN_LINE_PREFIX,\n `Plan ready for approval${snapshot.templateName ? `: ${snapshot.templateName}` : ' (custom plan)'}`,\n `Success criteria: ${snapshot.successCriteria}`,\n ...(snapshot.rationale ? [`Why: ${snapshot.rationale}`] : []),\n ...snapshot.tasks.map((task) => ` ${task.riskLevel === 'HIGH' ? '!' : task.riskLevel === 'MEDIUM' ? '·' : '○'} [${task.riskLevel ?? 'LOW'}] ${task.id} — ${task.description}`),\n ...(snapshot.reviewNotes && snapshot.reviewNotes.length > 0\n ? ['Review notes:', ...snapshot.reviewNotes.map((note) => ` - ${note}`)]\n : []),\n ]\n console.log(stripTerminalControls(`\\n${lines.join('\\n')}\\n`))\n }\n\n /**\n * Reads the \"approve with edits\" payload — the CLI counterpart to `PlanApprovalCard`'s\n * checkbox-cancel + inline-edit controls, the only other surface that builds `PlanApprovalEdits`.\n * Unknown task ids are dropped here (with a warning) rather than passed through:\n * `resolvePendingPlanApproval` throws on an unrecognized id and fails the whole approval closed,\n * so a single typo would otherwise re-stage the plan with a bare \"couldn't apply\" reason.\n */\n async function promptPlanEdits(snapshot: NonNullable<AssistantTurnResult['planApproval']>): Promise<PlanApprovalEdits> {\n const knownIds = new Set(snapshot.tasks.map((task) => task.id))\n const cancelRaw = await askLine('Task ids to cancel (comma-separated, blank for none): ')\n const editRaw = await askLine('Edits as \"id=new description\" pairs separated by \";\", e.g. t2=Reword this. (blank for none): ')\n const cancelTaskIds = cancelRaw.split(/[\\s,]+/).map((s) => s.trim()).filter(Boolean)\n const parsedEdits = editRaw\n .split(';')\n .map((pair) => pair.trim())\n .filter(Boolean)\n .map((pair) => {\n const sep = pair.indexOf('=')\n return sep >= 0 ? { id: pair.slice(0, sep).trim(), description: pair.slice(sep + 1).trim() } : { id: pair, description: '' }\n })\n const validCancels = cancelTaskIds.filter((id) => knownIds.has(id))\n const validEdits = parsedEdits.filter((edit) => knownIds.has(edit.id) && edit.description)\n const unknown = [...cancelTaskIds.filter((id) => !knownIds.has(id)), ...parsedEdits.filter((e) => !knownIds.has(e.id)).map((e) => e.id)]\n if (unknown.length > 0) printSafe(` [ignoring unknown task id(s): ${[...new Set(unknown)].join(', ')}]`)\n return {\n ...(validCancels.length > 0 ? { cancelTaskIds: validCancels } : {}),\n ...(validEdits.length > 0 ? { editedTasks: validEdits } : {}),\n }\n }\n\n /**\n * `/plan approve|trust|edit|decline` — resolves the plan stashed by the `needs_plan_approval`\n * branch of handleTurn (the \"decide later\" path), re-entering the ordinary turn pipeline with\n * the same originating message so an approve runs the now-active plan's first task exactly the\n * way a freshly template-matched plan would.\n */\n async function handlePlanApprovalCommand(sub: string): Promise<void> {\n if (!pendingPlanApproval) {\n printSafe('\\nNo plan is awaiting approval.\\n')\n return\n }\n const { id, message, snapshot } = pendingPlanApproval\n let decision: PlanDecision\n let edits: PlanApprovalEdits | undefined\n if (sub === 'approve') {\n decision = 'approve'\n } else if (sub === 'trust') {\n decision = 'approve_trusted'\n } else if (sub === 'edit') {\n if (!snapshot) {\n printSafe('\\n[tasks unavailable for editing — /plan approve or /plan decline]\\n')\n return\n }\n printPlanApproval(snapshot)\n edits = await promptPlanEdits(snapshot)\n decision = 'approve_with_edits'\n } else {\n decision = 'decline'\n }\n pendingPlanApproval = undefined\n lastTrace = undefined\n lastNoTraceReason = `No harness trace — the last turn staged a plan that was ${decision === 'decline' ? 'declined' : 'approved'} before the harness ran.`\n await handleTurn(message, false, undefined, undefined, undefined, id, decision, edits)\n }\n\n /** The plan graph's nodes (live statuses overlaid), optionally narrowed to one goal thread; undefined when there is nothing to draw. */\n async function loadPlanGraphNodes(live?: { id: string; status: TaskStatus }[], threadId?: string): Promise<VizNode[] | undefined> {\n const record = await assistant.getPlanGraph('cli')\n if (!record) return undefined\n let nodes = planToSnapshot(record, live ?? []).nodes\n if (threadId) nodes = nodes.filter((n) => n.id.startsWith(`${threadId}__`))\n return nodes.length ? nodes : undefined\n }\n\n /** `/plan graph [thread-id]` — read-only plan graph. TUI: opens the pane. Plain CLI: one static render at the terminal width (checklist when it cannot be drawn). */\n async function handlePlanGraph(args: string[]): Promise<void> {\n const nodes = await loadPlanGraphNodes(undefined, args[0])\n if (!nodes) {\n printSafe(args[0] ? `\\nNo plan graph for thread \"${args[0]}\".\\n` : '\\nNo active plan for this session.\\n')\n return\n }\n if (options.openPlanGraph) {\n const probe = renderPlan(nodes, { maxCols: 80 })\n if (probe.ok) {\n options.openPlanGraph(nodes)\n return\n }\n printSafe(`\\n[plan graph unavailable: ${probe.message}] showing the checklist instead.`)\n printPlan()\n return\n }\n const cols = process.stdout.columns || 80\n const color = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR\n const result = renderPlan(nodes, { maxCols: cols, color })\n if (!result.ok) {\n printSafe(`\\n[plan graph unavailable: ${result.message}] showing the checklist instead.`)\n printPlan()\n return\n }\n if (!result.fits) {\n printSafe(`\\n[plan graph is wider than ${cols} columns] dependency list:\\n`)\n for (const n of nodes) printSafe(` [${n.status}] ${n.id} — ${n.label}${n.deps.length ? ` (after: ${n.deps.join(', ')})` : ''}`)\n printSafe('')\n return\n }\n printSafe(`\\n${result.lines.join('\\n')}\\n`)\n }\n\n async function handlePlan(args: string[]): Promise<void> {\n const sub = args[0]\n if (sub === 'graph' && isPlanGraphEnabled(config.planGraphMode)) {\n await handlePlanGraph(args.slice(1))\n return\n }\n if (sub === 'sketch') {\n await handlePlanSketch(args.slice(1))\n return\n }\n if (sub === 'approve' || sub === 'trust' || sub === 'edit' || sub === 'decline') {\n await handlePlanApprovalCommand(sub)\n return\n }\n // A plan staged for approval is what \"/plan\" should show while it's pending — the\n // \"Decide later — /plan to review\" option points here. lastPlanStatus isn't set on a\n // needs_plan_approval turn (the branch returns before the ordinary render), so without this\n // /plan would show the previous plan or \"No active plan\" instead of the draft awaiting a decision.\n if (pendingPlanApproval?.snapshot) {\n printPlanApproval(pendingPlanApproval.snapshot)\n return\n }\n printPlan()\n }\n\n function verificationHealthLabel({ strength, feasibility }: AssistantTrace['verificationHealth']): string {\n const confidence = Math.min(strength, feasibility)\n if (confidence >= 0.7) return 'High confidence'\n if (confidence >= 0.4) return 'Reasonably confident'\n return 'Worth double-checking'\n }\n\n /** One-line summary of AssistantTrace.batchBudget — the same found/not_found/truncated_while_productive\n * counts a batch turn's synthesized reply is already built from, just as a glance-able tally\n * rather than prose. Shared by /why's compact view and /layers' fuller per-item breakdown. */\n function batchBudgetSummaryLine(batchBudget: NonNullable<AssistantTrace['batchBudget']>): string {\n const found = batchBudget.perItemOutcomes.filter((o) => o.status === 'found').length\n const notFound = batchBudget.perItemOutcomes.filter((o) => o.status === 'not_found').length\n const truncated = batchBudget.perItemOutcomes.filter((o) => o.status === 'truncated_while_productive').length\n return (\n `Batch: ${batchBudget.itemCount} items — ${found} found, ${notFound} not found, ${truncated} truncated ` +\n `(${batchBudget.totalCallsUsed} calls used, projected ~${Math.ceil(batchBudget.projectedTotal)})`\n )\n }\n\n function printWhy(): void {\n // What the reply could have known (M6): printed with or without a harness trace, since a fast-path turn still saw memory.\n const memoryLine = formatMemoryInjection(assistant.getLastMemoryInjection())\n if (!lastTrace) {\n printSafe(`\\n${lastNoTraceReason ?? 'No harness trace for the last turn (nothing to explain yet, or it took the fast path).'}\\n${memoryLine}\\n`)\n return\n }\n printSafe(`\\n${verificationHealthLabel(lastTrace.verificationHealth)}`)\n // Only the layers that actually fired, chained in the order they fired — quiet otherwise\n // (Design Principle 3 of the harness layer activation plan: the common, unremarkable case\n // stays quiet, matching the existing \"don't badge LOW risk\" convention). Use /layers for\n // the full fired/skipped picture across all 11.\n const chain = buildWhyChain(lastTrace.layerActivity)\n if (chain.length > 0) {\n printSafe(' ' + chain.map((item) => `${LAYER_SHORT_CODE[item.layer]} (${item.reason})`).join(' > '))\n }\n // Absent on every non-batch turn (see AssistantTrace.batchBudget's doc comment) — only a\n // batch-research turn ever has this to show.\n if (lastTrace.batchBudget) {\n printSafe(' ' + batchBudgetSummaryLine(lastTrace.batchBudget))\n }\n printSafe(memoryLine)\n printSafe('')\n }\n\n /** Full fired/skipped picture across all 11 harness layers for the last turn — pure text rendering of the same layer_activity data /why's \"What I checked\" summarizes selectively. */\n function printLayers(): void {\n if (!lastTrace) {\n printSafe(`\\n${lastNoTraceReason ?? 'No harness trace for the last turn (nothing to explain yet, or it took the fast path).'}\\n`)\n return\n }\n printSafe('')\n const byLayer = new Map(lastTrace.layerActivity.map((e) => [e.layer, e]))\n for (const layer of LAYER_ORDER) {\n const e = byLayer.get(layer)\n const mark = e?.fired ? '✓' : '·'\n const reason = e?.reason ?? 'not evaluated this turn'\n printSafe(` [${mark}] ${LAYER_DISPLAY_NAME[layer].padEnd(22)} ${reason}`)\n }\n // The full per-item breakdown behind /why's one-line batchBudgetSummaryLine tally — same\n // \"absent on every non-batch turn\" gating as that summary.\n if (lastTrace.batchBudget) {\n printSafe('')\n printSafe(` ${batchBudgetSummaryLine(lastTrace.batchBudget)}`)\n const STATUS_MARK: Record<'found' | 'not_found' | 'truncated_while_productive', string> = {\n found: '✓', not_found: '✗', truncated_while_productive: '~',\n }\n for (const outcome of lastTrace.batchBudget.perItemOutcomes) {\n printSafe(` [${STATUS_MARK[outcome.status]}] ${outcome.item.padEnd(30)} ${outcome.status} (${outcome.callsUsed} calls)`)\n }\n }\n printSafe('')\n }\n\n const SOURCE_TOOL_LABEL: Record<AssistantSource['tool'], string> = {\n read_file: 'Read',\n list_directory: 'Listed',\n web_search: 'Searched',\n fetch_url: 'Fetched',\n }\n\n function printSources(): void {\n if (!lastSources || lastSources.length === 0) {\n printSafe('\\nNo sources for the last turn (it used no file/web tool calls).\\n')\n return\n }\n printSafe('')\n for (const source of lastSources) {\n printSafe(` - ${SOURCE_TOOL_LABEL[source.tool]} ${source.path}`)\n }\n printSafe('')\n }\n\n function printHelp(): void {\n printSafe(`\\n${formatHelp()}\\n`)\n }\n\n /** Ends the current conversation: clears transcript/facts/plan state and resets local display state so /why, /sources, /plan immediately reflect the fresh session instead of showing stale data. */\n async function handleClear(): Promise<void> {\n await assistant.clearSession('cli')\n lastTrace = undefined\n lastSources = undefined\n lastPlanStatus = undefined\n pendingPlanApproval = undefined\n lastTurnUsage = undefined\n lastNoTraceReason = undefined\n printSafe('\\n✓ Started a fresh conversation.\\n')\n }\n\n /**\n * Explicit inspect/clear for a stuck harness checkpoint — a scoped alternative to `/clear`\n * (which also wipes transcript/facts/plan) or moving the whole\n * `~/.buildaharness/personal-assistant/` directory aside by hand, previously the only way to\n * recover from a checkpoint that keeps failing to resume (e.g. left behind by a process killed\n * mid-turn — see assistant.ts's runId doc comment). Bare `/checkpoint` inspects without\n * clearing; `/checkpoint clear` clears it, matching `/config`/`/config set`'s own\n * bare-vs-subcommand shape.\n */\n async function handleCheckpoint(args: string[]): Promise<void> {\n if (args[0] === 'clear') {\n const result = await assistant.clearCheckpoint('cli')\n printSafe(\n result.cleared\n ? `\\n✓ Cleared the stuck checkpoint (was at step ${result.stepsUsed}, node \"${result.currentNode}\"). Conversation history is untouched — your next message starts a fresh harness run.\\n`\n : '\\nNo checkpoint to clear — the last turn either completed normally or there was nothing in progress.\\n',\n )\n return\n }\n const status = await assistant.getCheckpointStatus('cli')\n if (!status.present) {\n printSafe('\\nNo checkpoint present — the last turn completed normally or there was nothing in progress.\\n')\n return\n }\n const attemptsNote =\n status.failedResumeAttempts > 0\n ? ` — failed to resume ${status.failedResumeAttempts} time${status.failedResumeAttempts === 1 ? '' : 's'} in a row so far`\n : ''\n printSafe(\n `\\nA checkpoint is present: step ${status.stepsUsed}, last node \"${status.currentNode}\"${attemptsNote}.\\n` +\n `Your next message will try to resume it automatically. Run /checkpoint clear to discard it and start fresh instead.\\n`,\n )\n }\n\n async function printStatus(): Promise<void> {\n const transcript = await assistant.getTranscript('cli')\n const undoLogEntries = await assistant.listUndoLogEntries()\n const spendCapLine = await spendCapStatusLine()\n printSafe(\n `\\n${formatStatus({ config, overriddenKeys, transcriptLength: transcript.length, planActive: lastPlanStatus !== undefined, undoLogEntries, spendCapLine })}\\n`,\n )\n }\n\n /** Shared by /status and /cost (plan T2 step 5: \"not a separate display\") — undefined when no ceiling is configured. */\n async function spendCapStatusLine(): Promise<string | undefined> {\n if (config.sessionCostLimitUsd === undefined && config.sessionCallLimit === undefined) return undefined\n const state = await assistant.getSpendState('cli')\n return formatSpendCapStatus(state, { sessionCostLimitUsd: config.sessionCostLimitUsd, sessionCallLimit: config.sessionCallLimit })\n }\n\n /** Writes the session transcript to a markdown file — an explicit argument overrides the default filename, resolved relative to process.cwd() if not absolute. */\n async function handleExport(args: string[]): Promise<void> {\n const transcript = await assistant.getTranscript('cli')\n if (transcript.length === 0) {\n printSafe('\\nNothing to export yet.\\n')\n return\n }\n // The whole remainder is the path: a name with spaces must not be cut at the first one.\n const filename = resolvePath(process.cwd(), args.length > 0 ? args.join(' ') : defaultExportFilename())\n try {\n await writeFile(filename, formatTranscriptMarkdown(transcript), 'utf-8')\n printSafe(`\\n✓ Exported ${transcript.length} message${transcript.length === 1 ? '' : 's'} to ${filename}\\n`)\n } catch (err) {\n // Mirrors handleTurn's catch convention (below) — a failed write is reported, not thrown.\n const { message } = classifyError(err)\n printSafe(`\\n[error] ${message}\\n`)\n }\n }\n\n /**\n * Removes the last exchange from conversation history. Only affects what the model\n * remembers — a real write_file/run_shell_command effect from the undone turn is not\n * reversed (see the plan's Known limitations). Peeks at the transcript before calling\n * undoLastTurn so the confirmation message can name which side was removed, without\n * changing undoLastTurn's return shape just for that.\n *\n * create_reminder is the one tool call this reversible-sounding command can silently fail\n * to revert without the user realizing it — reminders need no approval (see risk-classifier.ts),\n * so unlike write_file/run_shell_command there's no prior \"Proceed?\" prompt that already told\n * the user this was consequential. ReminderStore has no delete/remove method to actually undo\n * it with (adding one is a packages/runtime change, out of scope here), so the best available\n * fix is surfacing the caveat explicitly instead of letting \"Removed the last exchange\" imply\n * the reminder went away too.\n */\n async function handleUndo(): Promise<void> {\n const transcriptBefore = await assistant.getTranscript('cli')\n if (transcriptBefore.length === 0) {\n printSafe('\\nNothing to undo.\\n')\n return\n }\n const wasPendingApproval = transcriptBefore[transcriptBefore.length - 1].role !== 'assistant'\n const undoneReminders = lastTurnToolSteps.filter((s) => s.tool === 'create_reminder')\n\n const result = await assistant.undoLastTurn('cli')\n if (!result.undone) {\n printSafe('\\nNothing to undo.\\n')\n return\n }\n // The display state described the now-undone turn — there's no cheap way to recover the\n // exact prior turn's trace/sources without storing turn-scoped snapshots (accepted limitation).\n lastTrace = undefined\n lastSources = undefined\n lastPlanStatus = undefined\n lastTurnToolSteps = []\n const caveat = undoneReminders.length > 0\n ? ` Note: ${undoneReminders.length === 1 ? 'a reminder' : `${undoneReminders.length} reminders`} created in that exchange (${undoneReminders.map((s) => `\"${s.input.text}\"`).join(', ')}) ${undoneReminders.length === 1 ? 'is' : 'are'} still active — /undo only removes chat history, not that side effect.`\n : ''\n printSafe(\n `\\n✓ Removed ${wasPendingApproval ? 'the pending message awaiting approval' : 'the last exchange (1 user message, 1 assistant reply)'}.${caveat}\\n`,\n )\n }\n\n /**\n * `/undo-action` with no argument lists real filesystem effects still on record as revertible\n * (T3 step 1). `/undo-action <id>` stages a revert of that entry as its own approval-gated\n * action (T3 step 2) — same \"yes/no, then re-call turn() to apply or discard\" shape as any\n * other staged write/shell action, except staging itself happens synchronously here (via\n * assistant.stageUndoAction) rather than by the model calling a tool, so the confirmation\n * prompt is driven directly rather than via handleTurn's needs_approval branch.\n */\n async function handleUndoAction(args: string[]): Promise<void> {\n if (args.length === 0) {\n const entries = await assistant.listUndoLogEntries()\n printSafe(`\\n${formatUndoLogListing(entries)}\\n`)\n return\n }\n\n const staged = await assistant.stageUndoAction(args[0])\n if (staged.status === 'error') {\n printSafe(`\\n✗ ${staged.message}\\n`)\n return\n }\n\n console.log(stripTerminalControls(`\\n[needs approval — revert] ${staged.reason}`))\n const confirmed = await askYesNo('Apply this revert? (y/N) ')\n lastTrace = undefined\n lastNoTraceReason = `No harness trace — the last turn was a staged revert that was ${confirmed ? 'approved' : 'declined'} before the harness ran.`\n await handleTurn('', confirmed, staged.pendingActionId)\n }\n\n async function printMemory(): Promise<void> {\n const summary = await assistant.getMemorySummary('cli')\n const digests = await assistant.listSessionDigests()\n const digestLine = digests.length > 0 ? `\\nSession digests stored: ${digests.length} (/memory forget digest [id] erases them; /memory export includes them).\\n` : ''\n printSafe(`\\n${formatMemoryStatus(await assistant.getMemoryStatus('cli'))}\\n\\n${formatMemorySummary(summary)}\\n${digestLine}`)\n }\n\n /**\n * `/memory export [file]` — writes the full, unbounded learned-experience contents (every\n * strategy weight/decomposition/recovery sequence, not just the 20-entry preview `/memory`\n * prints) plus facts/reminders to a JSON file. Mirrors handleExport's shape: explicit\n * argument overrides the default filename, resolved relative to process.cwd() if not\n * absolute, a failed write is reported rather than thrown. Read-only over already-persisted\n * data — never an LLM call or network request.\n */\n async function handleMemoryExport(args: string[]): Promise<void> {\n const data = await assistant.exportMemory('cli')\n const filename = resolvePath(process.cwd(), args.length > 0 ? args.join(' ') : defaultMemoryExportFilename())\n try {\n await writeFile(filename, formatMemoryExport(data), 'utf-8')\n printSafe(`\\n✓ Exported learned memory to ${filename}\\n`)\n } catch (err) {\n const { message } = classifyError(err)\n printSafe(`\\n[error] ${message}\\n`)\n }\n }\n\n /** `/memory confirm <n|category>` / `/memory reject <n|category>` — see PersonalAssistant.confirmPendingFact/rejectPendingFact's doc comments for `selector`'s shape. */\n async function handleMemoryPending(action: 'confirm' | 'reject', args: string[]): Promise<void> {\n const selector = args[0]\n if (!selector) {\n printSafe(`\\nUsage: /memory ${action} <n> or /memory ${action} <category>\\n`)\n return\n }\n const outcome = action === 'confirm' ? await assistant.confirmPendingFact(selector) : await assistant.rejectPendingFact(selector)\n printSafe(`\\n${formatMemoryPendingOutcome(action === 'confirm' ? 'confirmed' : 'rejected', outcome)}\\n`)\n }\n\n /** `/memory forget <n>` — removes an already-durable/session fact by its `/memory` display number. Unlike confirm/reject, there's no category form (see PersonalAssistant.forgetFact's doc comment). */\n async function handleMemoryForget(args: string[]): Promise<void> {\n const selector = args[0]\n if (!selector) {\n printSafe('\\nUsage: /memory forget <n> [erase]\\n')\n return\n }\n const erase = args[1] === 'erase'\n const outcome = await assistant.forgetFact(selector, 'cli', erase)\n const note = outcome.ok && !erase && memoryAuditLogEnabled() ? ' The audit log still holds its text (see /memory history); use `/memory forget <n> erase` to remove that too.' : ''\n printSafe(`\\n${formatMemoryPendingOutcome('forgotten', outcome)}${note}\\n`)\n }\n\n /** `/memory` with no args shows a preview; `/memory export [file]` writes the full contents to disk (see handleMemoryExport); `/memory confirm|reject <n|category>` resolves a pending-confirmation guess (see handleMemoryPending); `/memory forget <n>` removes an already-learned fact (see handleMemoryForget). */\n async function handleMemory(args: string[]): Promise<void> {\n if (args[0] === 'export') {\n await handleMemoryExport(args.slice(1))\n return\n }\n if (args[0] === 'confirm' || args[0] === 'reject') {\n await handleMemoryPending(args[0], args.slice(1))\n return\n }\n if (args[0] === 'forget' && (args[1] === 'digest' || args[1] === 'digests')) {\n // D4: episodic digests are covered by /memory forget — one by id, or all of them.\n const removed = await assistant.forgetDigests(args[2])\n printSafe(`\\nForgot ${removed} session digest${removed === 1 ? '' : 's'}.\\n`)\n return\n }\n if (args[0] === 'forget') {\n await handleMemoryForget(args.slice(1))\n return\n }\n if (args[0] === 'history') {\n printSafe(`\\n${formatMemoryHistory(await assistant.memoryHistory())}\\n`)\n return\n }\n if (args[0] === 'status') {\n printSafe(`\\n${formatMemoryStatus(await assistant.getMemoryStatus('cli'))}\\n`)\n return\n }\n if (args[0] === 'archive') {\n // One numbered listing (set-aside + replaced entries); `restore` and `forget` index the same list.\n if (args[1] === 'forget') {\n const outcome = await assistant.forgetArchivedFact(args[2] ?? '')\n printSafe(`\\n${formatMemoryPendingOutcome('forgotten', outcome)}\\n`)\n return\n }\n if (args[1] === 'restore') {\n const outcome = await assistant.restoreArchivedMemory(args[2] ?? '', 'cli')\n printSafe(`\\n${outcome.message}\\n`)\n return\n }\n printSafe(`\\n${formatMemoryArchive(await assistant.listArchivedFacts(), await assistant.restorableArchiveCount())}\\n`)\n return\n }\n if (args[0] === 'off' || args[0] === 'on') {\n await assistant.setMemoryEnabled(args[0] === 'on')\n printSafe(args[0] === 'off'\n ? '\\nMemory writes are OFF for this install: nothing new will be saved (facts, pending guesses, digests). What is already stored stays readable; /memory forget and /memory reject still work. /memory on resumes.\\n'\n : '\\nMemory writes are on.\\n')\n return\n }\n if (args[0] === 'undo') {\n const outcome = await assistant.undoMemoryChange(args[1] ?? '', 'cli')\n printSafe(`\\n${outcome.message}\\n`)\n return\n }\n if (args[0] === 'consolidate') {\n await handleMemoryConsolidate(args.slice(1))\n return\n }\n await printMemory()\n }\n\n /** `/memory consolidate [accept <n>|dismiss <n>]` — M5. Bare form runs the proposal pass now (forcing the model pass) and lists what is staged; nothing is applied until `accept`. */\n async function handleMemoryConsolidate(args: string[]): Promise<void> {\n if (args[0] === 'accept' || args[0] === 'dismiss') {\n const outcome = args[0] === 'accept' ? await assistant.acceptMemoryProposal(args[1] ?? '', 'cli') : await assistant.dismissMemoryProposal(args[1] ?? '')\n printSafe(`\\n${outcome.message}\\n`)\n return\n }\n // Runs whichever consolidator is registered (PersonalAssistant registers M5's), then lists what is staged.\n const outcome = await assistant.consolidateMemory('cli')\n const proposals = await assistant.memoryProposals()\n if (proposals.length === 0) { printSafe(`\\n${outcome.message}\\n`); return }\n printSafe(`\\n${outcome.status === 'done' ? '' : `${outcome.message}\\n`}Proposed changes (nothing applied yet):\\n${proposals.map((p, i) => ` ${i + 1}. [${p.kind}]${p.touchesUserAsserted ? ' (touches something you said yourself)' : ''} ${p.text ? `-> \"${p.text}\" ` : ''}${p.reason}`).join('\\n')}\\n Use /memory consolidate accept <n> or dismiss <n>.\\n`)\n }\n\n /** `/search <query>` — ranked search over past messages (see PersonalAssistant.searchTranscript), never an LLM call or network request. A query with no terms is treated the same as no results, not an error. */\n async function handleSearch(args: string[]): Promise<void> {\n const query = args.join(' ')\n if (!query.trim()) {\n printSafe('\\nUsage: /search <query>\\n')\n return\n }\n const hits = await assistant.searchTranscript(query)\n printSafe(`\\n${formatSearchResults(hits, query)}\\n`)\n }\n\n /** `/goals` — R5's review surface (see plans/hierarchical_goal_tree_and_steering_plan.html Phase 7): every known goal thread this session, tagged with its visibility bucket. A pure read, same \"never an LLM call\" discipline as /search — works whether or not goalGraphMode is enabled, since it just shows whatever the session's GoalGraphRecord already holds (empty for a session that never touched goal-thread machinery). */\n async function handleGoals(): Promise<void> {\n const state = await assistant.getGoalGraphState('cli')\n printSafe(`\\n${formatGoalGraphState(state)}\\n`)\n }\n\n async function printCost(): Promise<void> {\n const spendCapLine = await spendCapStatusLine()\n // Source \"This session\" from the persisted spend ledger (assistant.getSpendState) — the same\n // cross-turn, cross-/new store the spend-cap line above is drawn from (recordSpend() always\n // updates it, regardless of backend or whether a cap is configured). An earlier version of\n // this tracked tokens separately in an in-process variable that reset on /new and on every\n // fresh CLI process, while the persisted ledger did not — sourcing the two numbers from\n // different scopes used to show e.g. \"0 in / 0 out tokens\" next to a real nonzero dollar cost\n // once any turn had run before the current /new.\n const spendState = await assistant.getSpendState('cli')\n const session = { inputTokens: spendState.cumulativeInputTokens, outputTokens: spendState.cumulativeOutputTokens, costUsd: spendState.cumulativeCostUsd }\n printSafe(`\\n${formatCostSummary({ lastTurn: lastTurnUsage, session, backend: config.llmBackend, spendCapLine })}\\n`)\n }\n\n async function handleDoctor(): Promise<void> {\n const workspaceRoot = config.workspaceRoot ?? process.cwd()\n const checks = await Promise.all([\n // Backend-specific checks only run for the backend actually in use — skipped, not\n // reported as failing, for the one that's inactive.\n ...(config.llmBackend === 'proxy' ? [checkProxyHealth(config.proxyUrl)] : []),\n ...(config.llmBackend === 'claude-cli' ? [checkClaudeCli(process.env.CLAUDE_PATH ?? 'claude')] : []),\n checkWorkspaceRoot(workspaceRoot),\n checkDataDirWritable(backend, dataDir),\n ...checkMemoryHealth(await assistant.getMemoryStatus('cli')),\n // Informational only (always ok:true) — surfaces the active backend/flags so a user has\n // one command to confirm config, rather than none (see file's own config summary gap).\n { label: `llmBackend: ${config.llmBackend}`, ok: true },\n { label: `enableShell: ${config.enableShell ?? false}, enableWeb: ${config.enableWeb ?? false}`, ok: true },\n // Provider API keys are stored plaintext in config.json, not an OS keychain — confirming\n // that explicitly here rather than leaving it unstated (no keychain integration exists).\n { label: 'provider keys stored: plaintext in config.json (no OS keychain integration)', ok: true },\n ])\n printSafe(`\\n${formatDoctorReport(checks)}\\n`)\n }\n\n let lastProgressLineLength = 0\n function writeProgress(progress: AssistantProgress): void {\n // Layer name instead of the raw node id even on a non-plan turn (Phase 3.3: \"Step 3/5 —\n // Verification…\" reads better than \"Step 3/5 — verify…\") — falls back to the node's own\n // display name for loop-scaffolding nodes (context_compression etc.) that map to no layer.\n const layer = nodeToLayer(progress.currentNode)\n const label = layer ? LAYER_DISPLAY_NAME[layer] : nodeDisplayName(progress.currentNode)\n // A plan-driven turn gets a plan-aware prefix instead of the generic step counter for the\n // duration of the run (Phase 3.2) — the node/layer name is still shown after it, and full\n // harness-internal detail is still available via /why once the turn finishes.\n const prefix = progress.planPosition\n ? `[${progress.planPosition.templateName ?? 'custom plan'} — step ${progress.planPosition.stepIndex}/${progress.planPosition.stepCount} (${progress.planPosition.completionPct.toFixed(0)}%)]`\n : `[step ${progress.stepsUsed}/${progress.maxSteps}]`\n const line = stripTerminalControls(`${prefix}${label ? ` ${label}…` : ''}`)\n process.stdout.write(`\\r${line.padEnd(lastProgressLineLength)}`)\n lastProgressLineLength = line.length\n }\n function clearProgress(): void {\n if (lastProgressLineLength === 0) return\n process.stdout.write(`\\r${' '.repeat(lastProgressLineLength)}\\r`)\n lastProgressLineLength = 0\n }\n\n // A discrete event, not a progress bar — each call gets its own scrolled-past line\n // (unlike writeProgress's single overwritten \\r line), the way Claude Code's own CLI\n // shows a running log of what it's doing. Clears the progress line first so a tool step\n // never gets mangled mid-overwrite.\n function writeToolStep(step: AssistantToolStep): void {\n clearProgress()\n // A denied call reports twice — see AssistantToolStep.deniedReason's doc comment — so the\n // proposal line (\"Reading X\") a viewer already saw a moment earlier stays on screen and this\n // second line closes the loop instead of replacing it.\n if (step.deniedReason) {\n console.log(stripTerminalControls(` ${ICONS.deniedStep} Denied: ${step.summary} — ${step.deniedReason}`))\n } else {\n console.log(stripTerminalControls(` ${toolStepIcon(step.tool)} ${step.summary}`))\n }\n lastTurnToolSteps.push(step)\n }\n\n /** One question's in-progress answer — the CLI's text-mode counterpart of AskQuestionCard.tsx's QuestionDraft (chat-ui's Q5 rendering). No `showEdit` flag: a note is only ever entered via the explicit `e<n>` command below, so its presence in `editText` already says whether one exists. */\n interface ClarificationDraft {\n selectedLabels: string[]\n editText: string\n freeText: string\n }\n function emptyClarificationDraft(): ClarificationDraft {\n return { selectedLabels: [], editText: '', freeText: '' }\n }\n\n /** Recommended option(s) first, stable otherwise — mirrors AskQuestionCard.tsx's orderedOptions exactly, so the same question renders its options in the same order on both surfaces. */\n function orderedAskOptions(question: AskQuestion): AskQuestionOption[] {\n const options = question.options ?? []\n return options\n .map((option, index) => ({ option, index }))\n .sort((a, b) => Number(b.option.recommended ?? false) - Number(a.option.recommended ?? false) || a.index - b.index)\n .map(({ option }) => option)\n }\n\n /** Collapses one question's draft into the wire AskAnswer shape, or null while still unanswered (INV-28) — mirrors AskQuestionCard.tsx's draftToAnswer. */\n function clarificationDraftToAnswer(questionId: string, draft: ClarificationDraft): AskAnswer | null {\n if (draft.selectedLabels.length > 0) {\n return draft.editText.trim()\n ? { questionId, kind: 'selected_with_edit', selectedLabels: draft.selectedLabels, editText: draft.editText.trim() }\n : { questionId, kind: 'selected', selectedLabels: draft.selectedLabels }\n }\n if (draft.freeText.trim()) {\n return { questionId, kind: 'free_text', freeText: draft.freeText.trim() }\n }\n return null\n }\n\n function printClarificationQuestion(question: AskQuestion, draft: ClarificationDraft, index: number, total: number): void {\n const options = orderedAskOptions(question)\n const allowFreeText = question.allowFreeText !== false\n printSafe('')\n if (question.header) console.log(stripTerminalControls(`[${question.header}]`))\n if (total > 1) printSafe(`Question ${index + 1} of ${total}`)\n console.log(stripTerminalControls(question.question))\n options.forEach((option, i) => {\n const n = i + 1\n const picked = draft.selectedLabels.includes(option.label) ? '✓' : ' '\n const recommended = option.recommended ? ' (recommended)' : ''\n console.log(stripTerminalControls(` [${picked}] ${n}) ${option.label}${recommended}`))\n if (option.description) console.log(stripTerminalControls(` ${option.description}`))\n if (option.preview) console.log(stripTerminalControls(` preview: ${option.preview}`))\n })\n if (draft.editText) console.log(stripTerminalControls(` note: ${draft.editText}`))\n if (draft.freeText) console.log(stripTerminalControls(` other: ${draft.freeText}`))\n const commands = [\n options.length > 0 ? (question.allowMultiple ? '<n>/t<n> toggle option' : '<n> select option') : undefined,\n options.length > 0 ? 'e<n> add a note to a selected option' : undefined,\n allowFreeText ? 'o other (free text)' : undefined,\n total > 1 ? 'b back, n next' : undefined,\n 's submit',\n ].filter((c): c is string => c !== undefined)\n printSafe(` (${commands.join(' | ')})`)\n }\n\n /**\n * Text-mode equivalent of AskQuestionCard.tsx (Q6 of the internal plan):\n * runs a self-contained prompt loop over `result.questions`, then resumes the paused turn by\n * calling back into handleTurn with `pendingClarificationId`/the assembled AskResponse — same\n * \"resolved by ID, never re-derived\" shape as the write/shell/email pause above. Only reached\n * once the harness has already staged the questions (AskClarificationService.stageAndRespond);\n * this function only collects and validates the answer, it never talks to the harness directly.\n */\n async function handleClarification(result: AssistantTurnResult): Promise<void> {\n const questions = result.questions ?? []\n const pendingClarificationId = result.pendingClarificationId\n if (questions.length === 0 || !pendingClarificationId) {\n // Mirrors shouldRenderAskQuestionCard's guard in chat-ui — shouldn't happen in practice\n // (AskClarificationService always sets both together), but fails safe to the plain-text\n // escalation copy rather than entering a loop with nothing to ask.\n lastTrace = undefined\n lastNoTraceReason = `No harness trace — the last turn needed clarification (${result.reason ?? 'no further detail'}) but had no answerable questions.`\n console.log(stripTerminalControls(`\\n[needs clarification] ${result.reason ?? 'This request needs clarification.'}\\n`))\n return\n }\n\n // Same \"never touches stdin, always resolves the same way\" shape as askYesNo's own decline\n // branch — a piped/scripted run has no one to answer these questions, so it falls through to\n // the plain-text escalation copy instead of blocking on a readline read of closed stdin.\n if (nonInteractiveApprovalMode === 'decline') {\n printSafe(`\\n[non-interactive mode: auto-declining — ASSISTANT_NON_INTERACTIVE_APPROVAL=decline]`)\n console.log(stripTerminalControls(`\\n[needs clarification] ${result.reason ?? 'This request needs clarification.'}`))\n for (const q of questions) console.log(stripTerminalControls(` - ${q.question}`))\n printSafe('')\n lastTrace = undefined\n lastNoTraceReason = 'No harness trace — the last turn needed clarification and was auto-declined (non-interactive mode) before the harness resumed.'\n return\n }\n\n printSafe(`\\n[needs clarification] ${questions.length} question${questions.length === 1 ? '' : 's'} to answer.`)\n const drafts = new Map<string, ClarificationDraft>(questions.map((q) => [q.id, emptyClarificationDraft()]))\n let index = 0\n\n while (true) {\n const question = questions[index]\n const draft = drafts.get(question.id)!\n printClarificationQuestion(question, draft, index, questions.length)\n const token = (await askLine('clarify> ')).trim()\n const lower = token.toLowerCase()\n // The input stream is gone (EOF / Ctrl+D): every further read would come back blank forever, so stop asking.\n if (inputUnavailable) {\n printSafe('\\n[no input available — leaving the clarification unanswered]\\n')\n lastTrace = undefined\n lastNoTraceReason = 'No harness trace — the last turn needed clarification and input closed before it was answered.'\n return\n }\n\n if (lower === 's' || lower === 'submit') {\n const answers = questions.map((q) => clarificationDraftToAnswer(q.id, drafts.get(q.id)!))\n const missing = questions.filter((q, i) => answers[i] === null)\n if (missing.length > 0) {\n printSafe(`\\nStill need an answer for: ${missing.map((q) => q.question).join('; ')}\\n`)\n continue\n }\n const response: AskResponse = { answers: answers as AskAnswer[] }\n await handleTurn('', false, undefined, pendingClarificationId, response)\n return\n }\n if (lower === 'b' && questions.length > 1) {\n index = Math.max(0, index - 1)\n continue\n }\n if (lower === 'n' && questions.length > 1) {\n index = Math.min(questions.length - 1, index + 1)\n continue\n }\n if (lower === 'o') {\n if (question.allowFreeText === false) {\n printSafe('\\nThis question does not accept a free-text answer.\\n')\n continue\n }\n const text = await askLine('Other — type your own answer: ')\n if (!text.trim()) {\n printSafe('\\nEmpty answer ignored.\\n')\n continue\n }\n drafts.set(question.id, { selectedLabels: [], editText: '', freeText: text.trim() })\n continue\n }\n const editMatch = /^e(\\d+)$/i.exec(token)\n if (editMatch) {\n const options = orderedAskOptions(question)\n const option = options[Number(editMatch[1]) - 1]\n if (!option) {\n printSafe(`\\nNo option ${editMatch[1]}.\\n`)\n continue\n }\n if (!draft.selectedLabels.includes(option.label)) {\n printSafe(`\\nSelect option ${editMatch[1]} first, then add a note with e${editMatch[1]}.\\n`)\n continue\n }\n const note = await askLine('Note: ')\n drafts.set(question.id, { ...draft, editText: note.trim() })\n continue\n }\n const toggleMatch = /^t(\\d+)$/i.exec(token) ?? /^(\\d+)$/.exec(token)\n if (toggleMatch) {\n const options = orderedAskOptions(question)\n const option = options[Number(toggleMatch[1]) - 1]\n if (!option) {\n printSafe(`\\nNo option ${toggleMatch[1]}.\\n`)\n continue\n }\n if (question.allowMultiple) {\n const already = draft.selectedLabels.includes(option.label)\n drafts.set(question.id, {\n ...draft,\n selectedLabels: already ? draft.selectedLabels.filter((l) => l !== option.label) : [...draft.selectedLabels, option.label],\n freeText: '',\n })\n } else {\n drafts.set(question.id, { ...draft, selectedLabels: [option.label], freeText: '' })\n }\n continue\n }\n\n printSafe(`\\nUnrecognized input \"${token}\".\\n`)\n }\n }\n\n async function handleTurn(\n message: string,\n approved = false,\n pendingActionId?: string,\n pendingClarificationId?: string,\n clarificationAnswer?: AskResponse,\n planApprovalId?: string,\n planDecision?: PlanDecision,\n planEdits?: PlanApprovalEdits,\n ): Promise<void> {\n lastTurnToolSteps = []\n // Set only once the first token of an actual streamed reply arrives — the\n // message-level approval gate and the file-tools loop both produce a full\n // reply with no streaming, so this stays false for those turns and the\n // final branch below falls back to printing the whole reply at once.\n let streamedAnyTokens = false\n function writeToken(token: string): void {\n if (!streamedAnyTokens) {\n process.stdout.write('\\nAielia> ')\n streamedAnyTokens = true\n }\n process.stdout.write(stripTerminalControls(token))\n }\n\n try {\n const result = await assistant.turn(message, {\n sessionId: 'cli',\n approved,\n pendingActionId,\n pendingClarificationId,\n clarificationAnswer,\n planApprovalId,\n planDecision,\n planEdits,\n // Gated on streamedAnyTokens: onProgress keeps firing for layers (Memory,\n // Verification) that run after the LLM call, i.e. after writeToken has already put\n // the reply on the current line with no trailing newline. writeProgress's \\r-based\n // overwrite doesn't know that — on a real TTY it wrote the \"[step N/5] ...\" text\n // over the tail of the just-streamed reply, and the following clearProgress() then\n // blanked that same line, so the end of the assistant's answer visibly vanished\n // right after it finished streaming. Once streaming has started this turn, further\n // progress has nothing safe to overwrite, so it's dropped instead.\n onProgress: (progress) => {\n if (progress.planTasks) options.onPlanProgress?.(progress.planTasks)\n if (!streamedAnyTokens) writeProgress(progress)\n },\n onToken: writeToken,\n onToolStep: writeToolStep,\n // Phase 4 — real intra-turn absorption via checkCallerUpdates, replacing Phase 3's\n // drain-as-follow-up-turns fallback in dispatchOne's `finally` below (kept there, but\n // only as a backstop: turn() re-enqueues anything it didn't get around to classifying\n // this turn — e.g. a trivial turn that never calls harnessBridge.run() at all — back onto\n // this same channel, see TurnOptions.steeringChannel's doc comment). Passed unconditionally:\n // with goalGraphMode off, routeMessage (below) never enqueues into steeringChannel, so it's\n // always empty and this resolves to exactly today's behavior (INV-43).\n steeringChannel,\n })\n // Same streamedAnyTokens gate as onProgress above: lastProgressLineLength describes a\n // pre-streaming progress line that a leading \"\\n\" in writeToken already scrolled past,\n // not the current line (the tail of the streamed reply) — clearing unconditionally here\n // would \\r back onto the reply's last line and blank the start of it with stale-length\n // spaces.\n if (!streamedAnyTokens) clearProgress()\n\n // A write_file/run_shell_command tool call, gated at the point of the call itself\n // rather than by the message text — see the file-tools and web+shell-tools plans'\n // Diagnosis tabs. Unlike the message-level gate below, both a yes and a no need to\n // re-call turn() (to apply or discard the staged action), not just a yes.\n if (result.status === 'needs_approval' && result.pendingActionId) {\n // 'batch' (a projected-search-count confirmation, not a staged write/shell action) has\n // its own label and prompt — falling through to the 'write' case here would print\n // \"[needs approval — write]\" and \"Apply this write?\" over a message that's actually\n // about how many more searches a batch research turn is projected to need.\n const kindLabel =\n result.pendingActionKind === 'shell'\n ? 'shell command'\n : result.pendingActionKind === 'email'\n ? 'send email'\n : result.pendingActionKind === 'batch'\n ? 'batch research'\n : 'write'\n const promptText =\n result.pendingActionKind === 'shell'\n ? 'Run this command?'\n : result.pendingActionKind === 'email'\n ? 'Send this email?'\n : result.pendingActionKind === 'batch'\n ? 'Continue?'\n : 'Apply this write?'\n console.log(stripTerminalControls(`\\n[needs approval — ${kindLabel}] ${result.reason}`))\n let confirmed: boolean\n if (result.pendingActionKind && rememberedActionKinds.has(result.pendingActionKind)) {\n printSafe(`[\"don't ask again\" active this session for ${kindLabel} — auto-approved]`)\n confirmed = true\n } else {\n const decision = await askSelect(promptText, APPROVAL_OPTIONS)\n confirmed = decision === 'y' || decision === 'a'\n if (decision === 'a' && result.pendingActionKind) rememberedActionKinds.add(result.pendingActionKind)\n }\n lastTrace = undefined\n lastNoTraceReason = `No harness trace — the last turn was a staged ${kindLabel} that was ${confirmed ? 'approved' : 'declined'} before the harness ran.`\n await handleTurn(message, confirmed, result.pendingActionId)\n return\n }\n\n if (result.status === 'needs_approval') {\n console.log(stripTerminalControls(`\\n[needs approval — ${result.riskLevel}] ${result.reason}`))\n printSafe(` \"${message}\"`)\n let confirmed: boolean\n if (result.riskLevel && rememberedRiskLevels.has(result.riskLevel)) {\n printSafe(`[\"don't ask again\" active this session for risk level ${result.riskLevel} — auto-approved]`)\n confirmed = true\n } else {\n const decision = await askSelect('Proceed?', APPROVAL_OPTIONS)\n confirmed = decision === 'y' || decision === 'a'\n if (decision === 'a' && result.riskLevel) rememberedRiskLevels.add(result.riskLevel)\n }\n if (confirmed) {\n await handleTurn(message, true)\n } else {\n // Without clearing lastTrace here, /why and /layers only fall back to\n // lastNoTraceReason when lastTrace is unset — so once any earlier turn in the\n // session had produced a real trace, a later decline left that stale trace in\n // place and printWhy/printLayers displayed the wrong (already-finished) turn's\n // explanation instead of this decline's reason.\n lastTrace = undefined\n lastNoTraceReason = 'No harness trace — the last turn was blocked on an approval gate and declined before the harness ran.'\n // Recorded now (not inside turn() itself) because the outcome is only known here —\n // see recordDeclinedRequest's doc comment for why this is safe unlike an eager append\n // inside runTurn. Without it, a later \"did that actually happen?\" question found no\n // trace of the request at all and confidently denied it was ever made.\n await assistant.recordDeclinedRequest('cli', message, result.reason ?? 'This request needed approval.')\n printSafe('Cancelled.\\n')\n }\n return\n }\n\n if (result.status === 'needs_clarification') {\n await handleClarification(result)\n return\n }\n\n // P2's whole-plan approval gate — the CLI surface for it, mirroring chat-ui's\n // PlanApprovalCard + its approve/approve-with-edits/approve-trusted/decline handlers, all\n // resolving through the same PlanApprovalService. Before this branch existed the CLI fell\n // through to the ordinary render below, so a staged plan (whose result carries reply: null)\n // printed as a bare \"- null\" and could not be approved, edited, or declined at all.\n if (result.status === 'needs_plan_approval') {\n if (!result.planApprovalId) {\n printSafe(`\\n[needs plan approval] ${result.reason ?? 'A plan is awaiting approval, but its approval id is missing.'}\\n`)\n return\n }\n const id = result.planApprovalId\n const snapshot = result.planApproval\n if (result.reason) printSafe(`\\n${result.reason}`)\n if (snapshot) printPlanApproval(snapshot)\n // Stashed (not just resolved inline) so the /plan approve|edit|decline commands can finish\n // the job if the user picks \"decide later\" below.\n pendingPlanApproval = { id, message, snapshot }\n lastTrace = undefined\n lastNoTraceReason = 'No harness trace — the last turn staged a plan for approval (pending /plan approve|decline|edit).'\n if (!snapshot) {\n printSafe('Decide with /plan approve or /plan decline.\\n')\n return\n }\n const choice = await askSelect('Approve this plan?', PLAN_APPROVAL_OPTIONS)\n if (choice === 'd') {\n printSafe('Left pending — /plan to review, /plan approve|edit|decline to decide.\\n')\n return\n }\n pendingPlanApproval = undefined\n let decision: PlanDecision\n let edits: PlanApprovalEdits | undefined\n if (choice === 't') {\n decision = 'approve_trusted'\n } else if (choice === 'e') {\n edits = await promptPlanEdits(snapshot)\n decision = 'approve_with_edits'\n } else if (choice === 'y') {\n decision = 'approve'\n } else {\n decision = 'decline'\n }\n lastNoTraceReason = `No harness trace — the last turn staged a plan that was ${decision === 'decline' ? 'declined' : 'approved'} before the harness ran.`\n // Same originating message, so an approve falls through to the ordinary pipeline with the\n // now-active plan (see PlanApprovalService.resolvePendingPlanApproval's doc comment) exactly\n // the way a freshly template-matched plan already does.\n await handleTurn(message, false, undefined, undefined, undefined, id, decision, edits)\n return\n }\n\n if (result.status === 'escalated') {\n lastTrace = undefined\n lastNoTraceReason = `No harness trace — the last turn escalated (${result.reason}) before completing.`\n console.log(stripTerminalControls(`\\n[escalated] ${result.reason}\\n`))\n return\n }\n\n // A trivial turn's trace is present-but-empty (see assistant.ts's triviality branch) so\n // chat-ui can still render its \"Why?\"/\"Run detail\" panels with an explanation and an\n // all-unfired grid — the CLI has no such grid, so it keeps printing its existing plain\n // \"took the fast path\" copy instead of an empty/misleading confidence readout.\n //\n // A resolved write_file/run_shell_command/revert pendingAction (assistant.ts's\n // resolvePendingAction, reached whenever this call passed a `pendingActionId`) returns\n // neither harnessSkipped nor trace at all — it's not the trivial fast path, it just never\n // runs the per-turn HarnessRuntime. Both call sites that recurse into this same handleTurn()\n // to resolve one (the pendingActionKind branch below and handleUndoAction) already set\n // lastNoTraceReason to a specific, accurate \"staged ${kind} that was approved/declined\n // before the harness ran\" message right before recursing — unconditionally falling through\n // to the generic fallback here clobbered that back to undefined, which is exactly what made\n // /why and /layers report the wrong (fully generic) reason after any staged tool-call\n // resolution. Guard on the `pendingActionId` parameter (not the result shape, which a test\n // mock may reasonably leave sparse) so this block is skipped entirely for a pendingAction\n // resolution, leaving the caller's already-correct state alone.\n if (!pendingActionId) {\n lastTrace = result.harnessSkipped ? undefined : result.trace\n lastNoTraceReason = result.harnessSkipped\n ? 'No harness trace — the last turn was a simple, self-contained question answered directly without activating the harness (fast path).'\n : undefined\n }\n lastSources = result.sources\n // A trivial fast-path turn never touches plan state at all (assistant.ts's triviality\n // branch returns before ever loading/updating activePlan) — result.planStatus is always\n // undefined there regardless of whether a plan is genuinely active, so clobbering\n // lastPlanStatus on every turn made /plan wrongly report \"No active plan\" right after any\n // ordinary Q&A aside during an in-progress plan (planStatus's own doc comment: it \"can be\n // non-null across many consecutive turns\" — a harness-skipped turn just doesn't know either\n // way). Same reasoning applies to a resolved pendingAction (resolvePendingAction never\n // touches plan state either, same as the trivial path) — the `pendingActionId` guard above\n // covers both cases.\n //\n // The plan-mode drafting path is the one deliberate exception: PlanDraftingService's\n // results are harnessSkipped (INV-30 — drafting runs no tool loop) yet DO carry a real\n // planStatus for the draft they just built or revised, and so does TurnInterpreter's\n // plan-task-cancel bypass. The old `!result.harnessSkipped` gate silently dropped those —\n // the drafting reply printed its inline \"(plan: 0% — /plan)\" hint (line below, which reads\n // result.planStatus directly) while /plan then answered \"No active plan for this session\".\n // Record whenever the turn ran the pipeline OR actually reported a planStatus; a\n // harness-skipped turn with no planStatus (trivial fast path, plan sketch) still leaves the\n // last known plan untouched, and a non-skipped turn reporting none still clears it.\n if (!pendingActionId && (!result.harnessSkipped || result.planStatus)) lastPlanStatus = result.planStatus\n lastTurnUsage = result.usage ? withCostEstimate(result.usage) : undefined\n const riskSuffix = result.riskLevel && result.riskLevel !== 'LOW' ? ` [risk: ${result.riskLevel}]` : ''\n const sourcesHint = result.sources && result.sources.length > 0 ? ` (${result.sources.length} source${result.sources.length > 1 ? 's' : ''} — /sources)` : ''\n const planHint = result.planStatus ? ` (plan: ${result.planStatus.completionPct.toFixed(0)}% — /plan)` : ''\n // Printed as its own line, not folded into riskSuffix/sourcesHint/planHint's inline\n // \"${...}\" style — this is a full sentence, not a short bracketed tag. Must be handled the\n // same way in both branches below (like the other hints), since result.contradictionNotice\n // is only known once HarnessRuntime.run() finishes, well after writeToken already streamed\n // `reply` itself to the screen — see assistant.ts's findContradictionNotice doc comment.\n const contradictionNotice = result.contradictionNotice ? `\\n\\n${result.contradictionNotice}` : ''\n // Same treatment for the change reviewer's advisory notice (see AssistantTurnResult.reviewNotice).\n const reviewNotice = (result.reviewNotice ? `\\n\\n${result.reviewNotice}` : '') + (result.auditNotice ? `\\n\\n${result.auditNotice}` : '')\n // R7: the turn-end next-step options, under the reply. Remembered so a bare 1/2/3 typed as\n // the very next input runs that option (see dispatchOne); any other input clears them.\n lastNextSteps = result.nextSteps && result.nextSteps.length > 0 ? result.nextSteps : undefined\n const nextStepsBlock = lastNextSteps ? `\\n\\n${formatNextSteps(lastNextSteps)}` : ''\n if (streamedAnyTokens) {\n // The reply text is already on screen, printed token-by-token as it streamed in — but\n // onToken only ever saw draftReply, not a Phase 4.1 pausedNote appended afterward (see\n // AssistantTurnResult.pausedNote's doc comment), so that part still needs printing here.\n const pausedNoteText = result.pausedNote ? `\\n\\n${result.pausedNote}` : ''\n process.stdout.write(stripTerminalControls(`${pausedNoteText}${riskSuffix}${sourcesHint}${planHint}${contradictionNotice}${reviewNotice}${nextStepsBlock}\\n\\n`))\n } else {\n console.log(stripTerminalControls(`\\nAielia>${riskSuffix} ${result.reply}${sourcesHint}${planHint}${contradictionNotice}${reviewNotice}${nextStepsBlock}\\n`))\n }\n } catch (err) {\n // Mirrors chat-ui's error bubble: a failed turn (e.g. proxy down) shouldn't\n // crash the REPL via an unhandled rejection — just report it and keep going.\n clearProgress()\n const { message: errorMessage, retryable } = classifyError(err, config.llmBackend)\n console.log(stripTerminalControls(`\\n[error] ${errorMessage}${retryable ? ' Type the message again to retry.' : ''}\\n`))\n }\n }\n\n // Fails closed: a non-TTY (piped/scripted) stdin is read and closed eagerly by readline,\n // often before a slow turn (one that ran tool calls before hitting a risk gate) even reaches\n // this prompt — rl.question() then throws ERR_USE_AFTER_CLOSE instead of ever reading an\n // answer. Left uncaught, that exception unwound past this function entirely: the caller's\n // `confirmed` was never assigned, \"Cancelled.\" was never logged, and the line meant as the\n // answer was left to be dispatched as its own ordinary chat turn instead (readline had already\n // queued it as a 'line' event before this prompt ever ran) — a HIGH-risk/destructive request\n // was silently neither approved nor declined rather than being safely stopped. Any failure to\n // read a real answer must resolve to \"no\" (never \"yes\"), so a broken/absent confirmation\n // channel can't be mistaken for approval.\n function askYesNo(question: string): Promise<boolean> {\n // Test-only seam: bypasses stdin/readline entirely, same \"never touches stdin\" shape as the\n // nonInteractiveApprovalMode === 'decline' branch below, just with a caller-scripted answer\n // instead of a hardcoded decline.\n if (options.askYesNo) return options.askYesNo(question)\n // A designed decision, not a fallback: never touches stdin, so there's no readline race to\n // land in — unlike the catch below, this path is reached deterministically on every\n // approval gate, not only when reading the answer happens to fail.\n if (nonInteractiveApprovalMode === 'decline') {\n printSafe(`\\n[non-interactive mode: auto-declining — ASSISTANT_NON_INTERACTIVE_APPROVAL=decline]`)\n return Promise.resolve(false)\n }\n return new Promise((resolve) => {\n try {\n rl.question(question, (answer) => resolve(answer.trim().toLowerCase().startsWith('y')))\n } catch {\n printSafe(`\\n[could not read a response — treating as declined]`)\n resolve(false)\n }\n })\n }\n\n /**\n * Free-text counterpart of askYesNo, for the clarification sub-loop's option numbers, edit\n * notes, and \"Other\" free text. handleClarification's own nonInteractiveApprovalMode ===\n * 'decline' branch returns before ever calling this, so — unlike askYesNo — there's no decline\n * branch to mirror here; the same fail-closed \"never throw past the caller\" shape still applies\n * for the read-failure case, just resolving to an empty string (an unrecognized/ignored answer,\n * see printClarificationQuestion's callers) instead of askYesNo's \"treat as declined\" boolean.\n */\n let inputUnavailable = false\n function askLine(question: string): Promise<string> {\n // Test-only seam — same shape as askYesNo's own.\n if (options.askLine) return options.askLine(question)\n return new Promise((resolve) => {\n try {\n rl.question(question, (answer) => resolve(answer.trim()))\n } catch {\n inputUnavailable = true\n printSafe(`\\n[could not read a response — treating as blank]`)\n resolve('')\n }\n })\n }\n\n /**\n * Structured multi-option counterpart of askYesNo/askLine (Phase 7's approval selector). The\n * Ink shell overrides this with `PromptBridge.askSelect`, which routes to `SelectPrompt`'s\n * real arrow-key/shortcut-key UI (`ink-select-prompt.tsx`); this plain-`readline` fallback is\n * what a non-TUI REPL (or a piped/non-interactive session) actually reads from. Resolves with\n * the chosen option's `key` — never the option's index or label. `selectOptions` is ordered by\n * every call site with its safe/fail-closed choice last (mirroring askYesNo's own \"no real\n * answer → treat as declined\" direction), and every failure-to-read path here resolves to that\n * last option's key, never the first — same fail-closed reasoning as askYesNo's own doc comment\n * above.\n */\n function askSelect(question: string, selectOptions: SelectOption[]): Promise<string> {\n // Test-only seam — same shape as askYesNo's/askLine's own.\n if (options.askSelect) return options.askSelect(question, selectOptions)\n const fallbackKey = selectOptions[selectOptions.length - 1]!.key\n if (nonInteractiveApprovalMode === 'decline') {\n printSafe(`\\n[non-interactive mode: auto-declining — ASSISTANT_NON_INTERACTIVE_APPROVAL=decline]`)\n return Promise.resolve(fallbackKey)\n }\n const optionLines = selectOptions.map((option, i) => ` ${i + 1}) [${option.key}] ${option.label}`).join('\\n')\n return new Promise((resolve) => {\n try {\n rl.question(`${question}\\n${optionLines}\\n> `, (answer) => {\n const trimmed = answer.trim().toLowerCase()\n const byKey = selectOptions.find((option) => option.key.toLowerCase() === trimmed)\n const byIndex = /^\\d+$/.test(trimmed) ? selectOptions[Number(trimmed) - 1] : undefined\n resolve((byKey ?? byIndex)?.key ?? fallbackKey)\n })\n } catch {\n printSafe(`\\n[could not read a response — treating as declined]`)\n resolve(fallbackKey)\n }\n })\n }\n\n // Refreshes `config`/`overriddenKeys` from disk and rebuilds `assistant` so a persisted\n // change (set or reset) takes effect on the very next turn — no restart needed. Cheap\n // enough to call unconditionally rather than special-casing which keys \"matter\": it's\n // just re-running the same wiring buildAssistant/main already do once at startup.\n async function reloadAssistant(): Promise<void> {\n const nextPersisted = await configStore.load()\n ;({ config, overriddenKeys } = resolveConfig(nextPersisted, envOverrides))\n layerPins = applyLayerSettings(sanitizeLayerChoices(config.layers), process.env).pinned\n assistant = options.assistant ?? (await buildAssistant(config, { dataDir, backend, remindersFile }))\n }\n\n async function handleConfigCommand(args: string[]): Promise<void> {\n if (args.length === 0) {\n printSafe(`\\n${formatConfigListing(config, overriddenKeys)}\\n`)\n return\n }\n\n if (args[0] === 'set') {\n const key = args[1]\n const raw = args.slice(2).join(' ')\n if (!key || !isConfigKey(key)) {\n printSafe(`\\n✗ Unknown config key \"${key ?? ''}\". Known keys: ${CONFIG_KEYS.join(', ')}\\n`)\n return\n }\n if (!raw) {\n printSafe(`\\nUsage: /config set ${key} <value>\\n`)\n return\n }\n if (overriddenKeys.has(key)) {\n printSafe(`\\n✗ \"${key}\" is pinned by ${ENV_VAR_FOR_CONFIG_KEY[key]} — unset that env var to change it here.\\n`)\n return\n }\n\n let value: unknown\n try {\n value = parseConfigValue(key, raw)\n } catch (err) {\n if (!(err instanceof ConfigValueParseError)) throw err\n printSafe(`\\n✗ ${err.message}\\n`)\n return\n }\n\n const patch = { [key]: value } as Partial<AssistantConfig>\n try {\n validateConfig(patch, config)\n } catch (err) {\n if (!(err instanceof ConfigValidationError)) throw err\n printSafe(`\\n✗ ${err.message}\\n`)\n return\n }\n\n await configStore.save(patch)\n await reloadAssistant()\n printSafe(`\\n✓ ${key} updated (took effect immediately, no restart needed)\\n`)\n return\n }\n\n if (args[0] === 'reset') {\n const key = args[1]\n if (key && !isConfigKey(key)) {\n printSafe(`\\n✗ Unknown config key \"${key}\". Known keys: ${CONFIG_KEYS.join(', ')}\\n`)\n return\n }\n // Takes effect immediately, same as /config set — and can silently break the active\n // session (e.g. reverting llmBackend mid-conversation, see conv81's finding), so this asks\n // first, same as any other consequential action (shell commands, writes, HIGH-risk\n // requests) — /config set is left as-is (a single, explicit, intentional value the user\n // just typed, not a broad \"wipe back to defaults\" that's easy to trigger without meaning to\n // reset something specific).\n // The reset must not leave a configuration that cannot start (e.g. dropping the apiKey of an API backend): the\n // next launch would refuse to run at all, and /config could no longer be used to repair it.\n const remaining: Partial<AssistantConfig> = { ...(await configStore.load()) }\n for (const k of key ? [key] : CONFIG_KEYS) delete remaining[k as keyof AssistantConfig]\n try {\n validateConfig({}, resolveConfig(remaining, envOverrides).config)\n } catch (err) {\n if (!(err instanceof ConfigValidationError)) throw err\n printSafe(`\\n✗ Not reset: ${err.message}\\n`)\n return\n }\n const target = key ? `\"${key}\"` : 'ALL settings'\n const confirmed = await askYesNo(`\\nReset ${target} to default? This takes effect immediately. (y/N) `)\n if (!confirmed) {\n printSafe('\\nCancelled — nothing was reset.\\n')\n return\n }\n const clearPatch = key\n ? ({ [key]: undefined } as Partial<AssistantConfig>)\n : (Object.fromEntries(CONFIG_KEYS.map((k) => [k, undefined])) as Partial<AssistantConfig>)\n await configStore.save(clearPatch)\n await reloadAssistant()\n printSafe(`\\n✓ Reset ${key ?? 'all settings'} to default\\n`)\n return\n }\n\n printSafe('\\nUsage: /config | /config set <key> <value> | /config reset [key]\\n')\n }\n\n /**\n * `/layers settings|on|off|reset` — list the reasoning layers and switch one on or off (bare `/layers` is printLayers' last-turn view). Persists `config.layers` through the same store as /config and\n * re-applies the flags immediately; floor layers are locked and an operator-set AUDIT_* flag is reported as pinned.\n */\n async function handleLayers(args: string[]): Promise<void> {\n const [sub, id] = args\n if (sub === 'settings' || sub === 'list') {\n printSafe(`\\n${formatLayerListing(sanitizeLayerChoices(config.layers), layerPins, process.env)}\\n`)\n return\n }\n try {\n if (sub === 'on' || sub === 'off') {\n if (!id) { printSafe(`\\nUsage: /layers ${sub} <id>\\n`); return }\n const layers = withLayerChoice(sanitizeLayerChoices(config.layers), id, sub === 'on')\n await configStore.save({ layers })\n } else if (sub === 'reset') {\n const layers = id ? withLayerChoice(sanitizeLayerChoices(config.layers), id, undefined) : {}\n await configStore.save({ layers })\n } else {\n printSafe('\\nUsage: /layers settings | /layers on <id> | /layers off <id> | /layers reset [id]\\n')\n return\n }\n } catch (err) {\n if (!(err instanceof LayerSettingError)) throw err\n printSafe(`\\n✗ ${err.message}\\n`)\n return\n }\n await reloadAssistant()\n const pinned = id !== undefined && layerPins.has(id)\n printSafe(pinned ? `\\n✗ Saved, but \"${id}\" is pinned by its AUDIT_* env flag, so the saved choice has no effect until that is unset.\\n` : `\\n✓ Layers updated (took effect immediately, no restart needed)\\n`)\n }\n\n /** Thin convenience wrapper over /config set model — not a second mechanism. Bare /model shows the current value. */\n async function handleModel(args: string[]): Promise<void> {\n if (args.length === 0) {\n printSafe(`\\n${config.model ?? \"(using each backend's default)\"}\\n`)\n return\n }\n await handleConfigCommand(['set', 'model', args.join(' ')])\n }\n\n /**\n * Thin convenience wrapper over /config set|reset activeProject — same relationship handleModel\n * has to /config set model. Bare /project shows the resolved current value (an explicit override\n * if one is set, else the workspace root buildAssistant derived it from — see\n * PersonalAssistant.getActiveProject's doc comment for why this is never itself undefined once\n * the assistant is built). /project clear reverts to that workspace-derived default.\n */\n async function handleProject(args: string[]): Promise<void> {\n if (args.length === 0) {\n printSafe(`\\n${assistant.getActiveProject() || '(none)'}\\n`)\n return\n }\n if (args[0] === 'clear') {\n await handleConfigCommand(['reset', 'activeProject'])\n return\n }\n await handleConfigCommand(['set', 'activeProject', args.join(' ')])\n }\n\n // Phase 3 of plans/hierarchical_goal_tree_and_steering_plan.html (R1, mid-task steering).\n // `turnInProgress` is true only while dispatchOne is awaiting an actual conversational\n // handleTurn() call, never while a command handler (e.g. /config) is running — so a /config\n // dispatch in flight is completely unaffected and keeps its existing dispatchQueue\n // serialization (the race-avoidance this queue exists for in the first place). `steeringChannel`\n // has no consumer yet beyond the drain in dispatchOne's `finally` below — Phase 4 replaces that\n // drain with real intra-turn absorption via checkCallerUpdates.\n let turnInProgress = false\n // The next-step options the last full turn offered — consumed by the next input (see dispatchOne).\n let lastNextSteps: NextStepSuggestion[] | undefined\n const steeringChannel = new LiveSteeringChannel()\n\n // A lookup keyed by the message's first whitespace-separated token — replaces what used to\n // be a growing `if (message === '/why') ... if (message === '/sources') ...` chain. Each\n // handler receives the remaining tokens as `args` (empty for commands that take none).\n // Rebuilt on every dispatch rather than hoisted to module scope because several handlers\n // close over `config`/`overriddenKeys`/`assistant`, which reloadAssistant() reassigns.\n const commands: Record<string, (args: string[]) => void | Promise<void>> = {\n '/why': () => printWhy(),\n // Bare /layers is the last-turn fired/skipped view; its subcommands (settings/on/off/reset) edit the on/off choices.\n '/layers': (args) => (args.length === 0 ? printLayers() : handleLayers(args)),\n '/sources': () => printSources(),\n '/plan': (args) => handlePlan(args),\n '/help': () => printHelp(),\n '/clear': () => handleClear(),\n '/new': () => handleClear(),\n '/status': () => printStatus(),\n '/export': (args) => handleExport(args),\n '/undo': () => handleUndo(),\n '/undo-action': (args) => handleUndoAction(args),\n '/memory': (args) => handleMemory(args),\n '/search': (args) => handleSearch(args),\n '/goals': () => handleGoals(),\n '/model': (args) => handleModel(args),\n '/project': (args) => handleProject(args),\n '/cost': () => printCost(),\n '/doctor': () => handleDoctor(),\n '/config': (args) => handleConfigCommand(args),\n '/checkpoint': (args) => handleCheckpoint(args),\n }\n\n // readline's 'line' event fires for every buffered line as soon as it's parsed — it does\n // not wait for a previous line's async handler to finish, so piped/pasted multi-line input\n // can dispatch several commands concurrently. That's harmless for read-only commands\n // (/why, /sources, a plain turn) but not for /config: two concurrent handleConfigCommand\n // calls read and validate against the same in-memory `config` before either's update lands,\n // which can both corrupt the on-screen result and validate against stale state. Chaining\n // every dispatch onto `dispatchQueue` makes the loop a real REPL — one command fully\n // resolves before the next begins — matching what a human typing into the prompt would\n // experience anyway.\n async function dispatchOne(message: string): Promise<void> {\n if (quitting) return\n // The documented piped workflow ends with a bare `exit` line (`printf 'msg\\nexit\\n' | node dist/cli.js`);\n // with no handler it used to go to the model as an ordinary turn (and mint a goal thread). Only the\n // bare word counts — \"exit strategy for my startup\" is still a message.\n if (isQuitCommand(message)) {\n quitting = true\n // M3: refresh the conversation's handoff digest at the session edge (no-op unless AUDIT_EPISODIC_DIGEST is on; fail-open).\n try { await assistant.endSession('cli') } catch { /* a digest failure must never block exit */ }\n printSafe('Exiting.')\n rl.close()\n return\n }\n // A bare 1/2/3 right after a turn's next-step options runs that option; anything else drops them.\n const pick = /^[1-3]$/.test(message) && lastNextSteps ? lastNextSteps[Number(message) - 1] : undefined\n lastNextSteps = undefined\n if (pick) {\n printSafe(` → ${pick.description}`)\n message = pick.description\n }\n const [token, ...args] = message.split(/\\s+/)\n // An own-property lookup: `commands['constructor']` / `['toString']` would otherwise resolve to an inherited\n // function, swallowing a message that merely starts with such a word. A picked next-step option is model-written\n // text: it is always sent as an ordinary message, never run as a slash command.\n const handler = !pick && Object.hasOwn(commands, token) ? commands[token] : undefined\n if (handler) {\n await handler(args)\n return\n }\n turnInProgress = true\n options.onTurnBusyChange?.(true)\n try {\n await handleTurn(message)\n } finally {\n turnInProgress = false\n options.onTurnBusyChange?.(false)\n // Phase 4: assistant.turn() above now absorbs queued steering messages in real time via\n // checkCallerUpdates (goal-graph-reconcile.ts), and re-enqueues onto steeringChannel\n // anything it didn't get around to this turn (a trivial turn that skipped harnessBridge.run\n // entirely, or a run that ended before the queue fully drained). This drain is the backstop\n // for exactly that leftover case — dispatched as ordinary follow-up turns, in arrival order,\n // rather than left queued indefinitely. Still satisfies \"never silently drop the new ask\"\n // (R4) the same way it always has; it's just no longer the *only* absorption path.\n if (isGoalGraphEnabled(config.goalGraphMode)) {\n for (const event of steeringChannel.poll()) {\n void enqueue(event.message)\n }\n }\n }\n }\n\n let quitting = false\n let dispatchQueue: Promise<void> = Promise.resolve()\n // One command fully resolves before the next begins — see the comment this used to carry\n // inline here (still true): readline's 'line' event doesn't wait for a previous line's async\n // handler, so piped/pasted multi-line input (or a test calling dispatchLine back to back)\n // could otherwise dispatch several commands concurrently, corrupting /config's read-modify-write.\n function enqueue(message: string): Promise<void> {\n const result = dispatchQueue\n .then(() => dispatchOne(message))\n // An unexpected throw here must not poison the queue for lines dispatched after it.\n .catch((err) => {\n console.error('[unexpected error]', err)\n })\n dispatchQueue = result\n return result\n }\n\n function isKnownCommand(message: string): boolean {\n const [token] = message.split(/\\s+/)\n return Object.hasOwn(commands, token) || isQuitCommand(message)\n }\n\n /**\n * Phase 3's routing split: with goalGraphMode off (the default — INV-43), this is exactly\n * `enqueue(message)`, byte-identical to before. With it on, a plain-turn message (not a slash\n * command — those must keep dispatchQueue's strict serialization, see dispatchOne's\n * turnInProgress comment above) arriving while a turn is already running is absorbed into\n * steeringChannel instead of waiting in line, so the composer/prompt never blocks on it (R1).\n */\n function routeMessage(message: string): Promise<void> {\n if (isGoalGraphEnabled(config.goalGraphMode) && turnInProgress && !isKnownCommand(message)) {\n steeringChannel.enqueue(message)\n assistant.logQueuedMessage('cli', message)\n printSafe('\\n[queued — the current turn is still running; this will be taken into account once it finishes]\\n')\n return Promise.resolve()\n }\n return enqueue(message)\n }\n\n rl.on('line', (line) => {\n const message = line.trim()\n if (!message) { rl.prompt(); return }\n void routeMessage(message).finally(() => rl.prompt())\n })\n // Safe to resume now — the 'line' listener right above is in place, so anything already\n // buffered on stdin (see the rl.pause() call up top) gets parsed and delivered, not dropped.\n rl.resume()\n\n return {\n dispatchLine: async (line: string) => {\n const message = line.trim()\n if (!message) return\n await routeMessage(message)\n },\n close: () => rl.close(),\n getPlanGraphNodes: async (live) => (isPlanGraphEnabled(config.planGraphMode) ? loadPlanGraphNodes(live) : undefined),\n getStatusIndicators: async () => {\n const indicators: string[] = []\n // Persistent context, not a notable/active state — always shown, same reasoning as the\n // spend-cap gauge below (once relevant, stays visible rather than only flashing on\n // change). fileTools is wired unconditionally in buildAssistant() (unlike shell/web/email\n // tools), so there's always an effective workspace root to show; mirrors the same\n // `config.workspaceRoot ?? process.cwd()` fallback buildAssistant() itself uses.\n indicators.push(`Workspace: ${config.workspaceRoot ?? process.cwd()}`)\n // A standing risk state, not a one-off event — worth keeping visible for the rest of the\n // session the same way dangerBanner warns once at startup (line ~349), since that startup\n // line scrolls out of view long before the session ends. Only shown when ON, mirroring\n // every other indicator here (\"blank when nothing to report\").\n if (config.dangerouslySkipPermissions) indicators.push('⚠ Permissions: auto-approved (dangerouslySkipPermissions)')\n if (lastPlanStatus !== undefined) indicators.push('Plan mode: active')\n // Persistent model/token/cost chrome (aielia_cli_formatting_plan.html Phase 1) — reuses\n // the same cumulative spendState counters /cost already reads, so fetching it here once\n // covers both the token/cost indicator and the cap-relative line below (replacing the\n // separate spendCapStatusLine() call, which would otherwise re-fetch the same state).\n indicators.push(`Model: ${config.model ?? backendDisplayModel[config.llmBackend]}`)\n const spendState = await assistant.getSpendState('cli')\n indicators.push(\n `This session: ${fmtUsage(\n spendState.cumulativeInputTokens - startupSpend.cumulativeInputTokens,\n spendState.cumulativeOutputTokens - startupSpend.cumulativeOutputTokens,\n spendState.cumulativeCostUsd - startupSpend.cumulativeCostUsd,\n )}`,\n )\n const spendCapLine = formatSpendCapStatus(spendState, { sessionCostLimitUsd: config.sessionCostLimitUsd, sessionCallLimit: config.sessionCallLimit })\n if (spendCapLine) indicators.push(spendCapLine)\n return indicators\n },\n }\n}\n\n/**\n * Phase 4 of the internal plan: `tuiMode` is resolved from the\n * same persisted-config + env-override chain every other config key uses (not just the env var\n * alone), so `/config set tuiMode enabled` works exactly like `/config set oneLoopMode enabled`\n * already does. This is a second, separate `configStore.load()` from the one `runCli()` performs\n * internally — an accepted duplication (one extra small JSON read at startup) rather than\n * threading a pre-resolved config through `runCli()`'s options, since `runCli()` must remain\n * callable on its own (tests, `non-interactive-mode.ts`) with no knowledge of this gate.\n *\n * `shouldLaunchTuiApp` (tui-mode-flag.ts) additionally requires both stdio streams to be a real\n * TTY — this repo's documented piped/scripted workflow (`printf 'msg\\nexit\\n' | node dist/cli.js`)\n * and every non-interactive shell always take the `runCli()` branch below regardless of the flag.\n * `runTuiApp` is imported dynamically so a disabled (the default) or non-TTY run never loads Ink\n * at all — `main()` behaves byte-for-byte as it does today in both those cases.\n */\n/** A reason the assistant refuses to start (invalid configuration, unusable environment): shown to the user verbatim, exit code 1. */\nexport class StartupError extends Error {}\n\nexport async function main(argv: readonly string[] = process.argv.slice(2)): Promise<void> {\n try {\n await mainInner(argv)\n } catch (err) {\n if (!(err instanceof StartupError)) throw err\n // The real stderr, written synchronously so it is flushed before the process ends; by now any TUI capture is restored.\n process.stderr.write(`${err.message}\\n`)\n process.exitCode = 1\n }\n}\n\nasync function mainInner(argv: readonly string[]): Promise<void> {\n const parsed = parseCliArgs(argv)\n if (parsed.command === 'version') {\n console.log(CLI_VERSION)\n return\n }\n if (parsed.command === 'help') {\n console.log(cliHelpText(CLI_VERSION))\n return\n }\n if (parsed.command === 'update') {\n process.exitCode = await runUpdateCommand({ dryRun: parsed.dryRun })\n return\n }\n\n const persisted = await defaultConfigStore.load()\n const { config } = resolveConfig(persisted, defaultEnvOverrides)\n\n // Startup housekeeping + passive update check. Fire-and-forget: never awaited before the prompt\n // renders, never throws (checkForUpdate resolves null on any failure), and gated off entirely for\n // non-interactive sessions and when opted out (see shouldRunPassiveUpdateCheck).\n const isSea = isRunningAsSea()\n if (isSea) cleanupStaleUpdateFiles()\n if (shouldRunPassiveUpdateCheck({ updateCheck: config.updateCheck, env: process.env, stdinIsTty: Boolean(process.stdin.isTTY) })) {\n void checkForUpdate().then((result) => {\n if (result?.updateAvailable) console.log(updateAvailableNotice(result.latestVersion, CLI_VERSION, isSea))\n })\n }\n\n if (shouldLaunchTuiApp(config.tuiMode ?? DEFAULT_TUI_MODE, Boolean(process.stdout.isTTY), Boolean(process.stdin.isTTY))) {\n const { runTuiApp } = await import('./tui-app.js')\n await runTuiApp()\n return\n }\n\n await runCli()\n}\n\n/**\n * True when `entryArg` (a `process.argv[1]` value) refers to the same file as\n * `moduleHref` (an `import.meta.url`).\n *\n * The naive check — `moduleHref === pathToFileURL(entryArg).href` — breaks\n * whenever the script is launched through the npm bin: `npx\n * @buildaharness/aielia`, a global install, or any\n * `node_modules/.bin` shim all pass a **symlink** to this file as\n * `process.argv[1]`, while Node reports `import.meta.url` as the resolved real\n * path. So resolve `entryArg` to its real path before comparing. `resolveReal`\n * is injected for tests; it defaults to `fs.realpathSync`.\n */\nexport function entryArgMatchesModule(\n entryArg: string | undefined,\n moduleHref: string,\n resolveReal: (p: string) => string = realpathSync,\n): boolean {\n if (entryArg === undefined) return false\n try {\n return moduleHref === pathToFileURL(resolveReal(entryArg)).href\n } catch {\n return false\n }\n}\n\nfunction isEntryModule(): boolean {\n return entryArgMatchesModule(process.argv[1], import.meta.url)\n}\n\n// Guarded so importing this module (e.g. from cli.test.ts, which drives runCli() directly\n// instead) never starts a second live REPL against the real process.stdin/stdout and the real\n// ~/.buildaharness/personal-assistant data directory. Correctly resolves argv[1] vs.\n// import.meta.url for `tsx src/cli.ts` and other unbundled invocations, but this comparison\n// is fundamentally unreliable once this module is bundled: Vite/Rollup hoists this file's code\n// into a shared chunk (tui-app.ts statically imports runCli/SelectOption from here), so\n// import.meta.url inside the built dist/cli.js is that shared chunk's own URL, never\n// dist/cli.js's — the guard silently evaluates false and the packaged CLI exits 0 with no\n// REPL. bin.ts is the real, never-shared entry for the packaged binary (see its own comment)\n// and calls main() unconditionally instead of relying on this check.\nif (isEntryModule()) void main()\n","/**\n * The packaged CLI's actual entry point (vite.config.lib.ts's \"cli\" build entry — the source\n * of dist/cli.js, referenced by package.json's \"bin\"). Deliberately not cli.ts itself: cli.ts's\n * own `if (isEntryModule()) void main()` guard compares `import.meta.url` against\n * `process.argv[1]`, which only works when cli.ts's code ends up in the exact file Node was\n * invoked with — true for `tsx src/cli.ts`, but not once bundled, since tui-app.tsx's static\n * import of cli.ts forces Vite/Rollup to hoist cli.ts's code into a shared chunk and turn\n * dist/cli.js into a facade re-exporting it; import.meta.url inside that shared chunk is never\n * dist/cli.js's own URL, so the guard silently evaluates false and the packaged CLI exited 0\n * with no REPL. This file has no other importers, so Rollup has no reason to ever share or\n * facade it — it's guaranteed to be the literal content of dist/cli.js — and it calls main()\n * unconditionally rather than trying to detect \"am I the entry point\" at all.\n */\nimport { main } from './cli.js'\n\nvoid main()\n"],"names":["stat","isEnoent","_e","netConnect","_b","_a","R","D","L","U","it","dagre","q","sr","tr","rt","br","c","defaultDataDir","res","backend","resolvePath","outcome","options","commands","resolve"],"mappings":";;;;;;;;;;;;;;;;;AAIO,MAAM,oBAAoB,CAAC,oBAAoB,aAAa,gBAAgB;AAGnF,SAAS,WAAW,OAAmC;AACrD,MAAI,MAAM,QAAQ,KAAK;AACvB,aAAS;AACP,UAAM,SAAS,KAAK,KAAK,MAAM;AAC/B,QAAI,WAAW,MAAM,GAAG;AACtB,YAAMA,QAAO,SAAS,MAAM;AAC5B,UAAIA,MAAK,YAAA,EAAe,QAAO;AAC/B,YAAM,OAAO,aAAa,QAAQ,MAAM,EAAE,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,SAAS,CAAC;AACzF,UAAI,CAAC,KAAM,QAAO;AAClB,YAAM,SAAS,KAAK,MAAM,UAAU,MAAM,EAAE,KAAA;AAC5C,YAAM,SAAS,WAAW,MAAM,IAAI,SAAS,QAAQ,KAAK,MAAM;AAEhE,YAAM,aAAa,KAAK,QAAQ,WAAW;AAC3C,UAAI,WAAW,UAAU,EAAG,QAAO,QAAQ,QAAQ,aAAa,YAAY,MAAM,EAAE,MAAM;AAC1F,aAAO;AAAA,IACT;AACA,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK,QAAO;AAC3B,UAAM;AAAA,EACR;AACF;AAQO,SAAS,0BAA0B,eAAiC;AACzE,MAAI;AACF,UAAM,SAAS,WAAW,aAAa;AACvC,QAAI,CAAC,OAAQ,QAAO,CAAA;AACpB,UAAM,cAAc,KAAK,QAAQ,QAAQ,SAAS;AAClD,UAAM,WAAW,WAAW,WAAW,IAAI,aAAa,aAAa,MAAM,IAAI;AAC/E,UAAM,UAAU,IAAI,IAAI,SAAS,MAAM,IAAI,EAAE,IAAI,CAAC,MAAM,EAAE,KAAA,CAAM,CAAC;AACjE,UAAM,UAAU,kBAAkB,IAAI,CAAC,MAAM,GAAG,CAAC,GAAG,EAAE,O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