#!/usr/bin/env node import * as os from 'node:os'; import * as path from 'node:path'; import { execFileSync } from 'node:child_process'; import { loadRubric } from './rubric.ts'; import { loadManifest, loadManifestAt, loadOverrides } from './manifest.ts'; import { autoDetectStack, type Ctx } from './facts.ts'; import { at, errorMessage } from './narrow.ts'; import { LIFECYCLE_VERBS, type LifecycleVerb, resolveLifecycleVerb, renderResolveError } from './run.ts'; import { audit } from './audit.ts'; import { reportMarkdown, reportJson, reportAnsi, reportDoctorMarkdown, reportDoctorJson, reportDoctorAnsi, } from './report.ts'; import { checkClaudeMemory, fixDoctorMemory, runDoctorStaged, runDoctor, runDoctorCheck, runDoctorFix, resolveDoctorCtx, looksLikeProject, readCliVersion, } from './doctor.ts'; import { memoryState } from './memory.ts'; import { planInit, writeInit, renderPlanSummary } from './init.ts'; import { planPublish, preflightFixable, renderPublishPlan, executePublish, defaultPublishDeps, type BumpKind, type PublishOptions, } from './publish.ts'; import { resolveDefaultRubric } from './defaults.ts'; import { defaultGateDeps, GATE_PREFIX, planGate, pushThroughGate } from './gate.ts'; import { askLine, runAi, runAiCheck, runAiState, runAiRestore, runAiClose, runAiTab, runAiReport, runAiRemote, defaultDeps, hostLabel, normalizeTopic, REMOTE_HOST_RE, resolveProjectRoot, sleepSync, } from './ai.ts'; import { isConversationId } from './conversations.ts'; import { defaultMoveDeps, runMove } from './move.ts'; const DEFAULT_RUBRIC = resolveDefaultRubric(); const USAGE = `Usage: vdx run lifecycle verb (via mise run ) vdx audit [project_path] [--rubric ] [--stack ] [--format=ansi|markdown|json] [--json] (default: cwd) vdx init [project_path] [--stack ] [--baseline ] [--dry-run] [--force] (default: cwd) vdx publish [--dry-run] [--force] [--no-push] vdx push [project_path] [--dry-run] (default: cwd; through the branch's required checks) vdx doctor [project_path] [--check | --fix] [--format=ansi|markdown|json] [--json] (default: cwd) vdx ai[@host] [project_path] [--new | --conversation ] [--focused [] | --intercom | --hq] [--restart] [--detach] [--dry-run] (default: cwd; @host: over ssh, in tmux there) vdx move ... [--dry-run] (on every machine of the profile, with its Claude Code memory and conversations) vdx --help what the command does; an unknown option is refused (exit 2) vdx --version `; function usage(): never { process.stderr.write(USAGE); process.exit(1); } /** What a command reads from its arguments; the rest is refused. */ interface CommandSpec { usage: string; /** Printed under the usage line by `--help`. */ help: string; /** Flags that take no value. */ bools?: string[]; /** Flags that take one (`--stack node`, `--format=json`). */ values?: string[]; /** Flags that stand alone or take one (`--focused`, `--focused ""`). */ optional?: string[]; /** How many positional arguments the command takes. */ positionals: number; /** Short flags, as Linux tools have them: `-y` → `yes`. */ shorts?: Record; } const AI_HELP = `Starts your agent in the project, or attaches to the one already running there. Not plain which: one list of what runs on every machine and what can be continued. Which agent, its flags and whether it runs in tmux come from your profile: $VDX_ENVIRONMENT, else ~/.vdx-environment.yaml, else a plain claude/codex. Launch flags live in the profile, not in a command to type: agent.args for every project, agent.when[] for a class of projects (a rubric predicate over the project's files), and with session: hq, intercom or focused for that kind of session only (0.67). Hand a person \`vdx ai\`, not \` --\`. project_path the project (default: cwd); its git toplevel is used @host the same command on over ssh: its vdx, profile and tmux --new a new conversation instead of continuing the last one; an agent already running here keeps running, the new one starts next to it, in a tmux session of its own (-2, -3, …) --focused [] a new conversation, as --new, in a session nothing wakes: the agent, its hooks and MCP servers get VDX_FOCUSED=1 — for the plugins that wake sessions to leave it alone — and the profile's rules marked \`wakes: true\` (a channel flag) are left out. Back to it: --focused --conversation . A running agent keeps its mode: plain vdx ai attaches to it as it is. A focused session here already on is the one: vdx ai attaches to it (0.51) — what the session is about: the option @vdx_topic of the agent's tmux pane, one per agent where a tmux session holds two (0.59; the terminal's title can show it), and the vdx plugin keeps the conversation in it. A new conversation opens with it as its first prompt, unless --prompt names another. The focused sessions running (with no topic all of them, with one those on a topic like it) come first as a list: a row attaches to one, n (Enter) starts a new one; with fzf on PATH the list has a cursor and what you type is the new one's topic (0.60). Without a topic and no list, a terminal asks — Enter leaves it to the agent, which takes it from your first message; what you type there is the topic, not a prompt. A restart keeps the session's topic, and --conversation brings back the conversation's. Run by the session's own agent, it changes the topic and starts nothing. A word that is a folder, with no path named, is the path. Needs tmux. Attached from a cmux terminal (here or @host), the workspace shows the topic as its description while vdx ai holds the attach, and drops it after; one you set by hand stays --prompt with --focused: the first message of the new session, apart from its topic — the topic is what lists show and other agents compare, so a few words of the subject; what to do goes here (0.60). A start that goes on in a conversation does not send it --intercom the project's intercom session: a new conversation in a tmux session of its own (-intercom), one per project and machine — a running or starting one is attached to, never a second. The agent, its hooks and MCP servers get VDX_INTERCOM=1: letters and wakes for the project go there, and your own session stays quiet; the profile's \`wakes\` rules stay. It starts with agent.intercom_args (its first prompt). Every other start leaves it alone, and its conversations are not continued unless named with --conversation. Started by the agent that has a letter and nobody to wake: vdx ai --intercom --detach . A machine runs at most one such session per 5 GB of memory, two at least (0.63; the ones the user started or joined are not counted, nor one stalled on a waiting screen past 30 minutes): over that, the start is queued, not refused — one line on stdout, ⏸ queued: with the place, exit 5 — and the project's session starts when one closes --hq the project's HQ session, for what comes from outside: a new conversation in a tmux session of its own (-hq), one per project and machine — a running one is attached to, never a second. You sit at it and keep it running; nothing starts it for you. The agent, its hooks and MCP servers get VDX_HQ=1, the profile's \`wakes\` rules stay, its rules with session: hq hold here alone, on every start (0.67), and it opens with agent.hq_args (its first prompt). Its sign: @vdx_topic and, attached from a cmux terminal, the workspace's description. --hq only narrows the choice to it: on a plain start's list it is a row whose number attaches to it as it is (0.52); Enter, a start without a terminal, --new and --focused leave it alone. --restore brings it back. --restart keeps its conversation, with --new it gets a new one; --conversation brings it back to that one. Not with --focused or --intercom; --close is not for it. In a hand — a project whose HQ is another one, as echelon hq says (found through the intercom directory's access layer, 0.66) — it asks to open that one's HQ session instead, and Enter does; without a terminal, and with --no-input, it refuses with that line, exit 2 --close [--waiting ] inside the intercom session, or a focused one (0.56): it ends itself — its pane closes 2 s later; one you started or attached to from a terminal stays, and only the mark changes. A focused step an HQ started with --detach closes once its step is done. --waiting : n questions to you still unanswered; the project's other tmux sessions here get @vdx_waiting = n (without it the mark is cleared). Anywhere else: refused, nothing closed --conversation continue this Claude Code conversation: attach to the agent in it, or start one next to the agents running here --restart restart the running agent in its pane — applies a changed profile; with --new or --conversation, it is replaced by that; with --focused it goes on focused in the conversation it is in, a new one with --new too (0.59); with --intercom, the intercom session gets a new conversation. Run inside an agent's session (its shell, ! at its prompt), it restarts that session, from a vdx apart from its pane, output in ~/.cache/vdx/restart/.log; a focused one only with --focused. With several agents here, none its own and no terminal: nothing restarted, the line for each (0.52.1). Without it, an agent running without the profile's flags is a question in a terminal: Enter attaches to it as is, r restarts it, q leaves it --detach start without attaching; print the command that attaches. In a folder Claude Code does not trust yet, nothing starts (exit 4): its trust window would wait with nobody at it — start once without --detach and answer it. Any start or restart waits up to 60 s while Claude Code's transcripts (~/.claude/projects) lead nowhere — a link to a volume not mounted yet — then nothing starts (exit 4): Claude Code would run without them (0.62) -y, --yes every question answered by vdx, as Linux tools take it: y to a [y/N] one, Enter to the rest (the list: its marked row; a topic: left to the agent); each answer is said on a line (0.58) --no-input no question put, as without a terminal: the safe way, or a refusal that names the flag or command that would do it — for agents (0.58) --dry-run print the plan and the project's running agents; start nothing. Claude Code: the list as well, and what a start without a terminal takes --list Claude Code: the list a plain start shows; ask nothing, start nothing. Under each row, the command that reaches it from here (0.51). In a folder that is no project (~) the list shows every tmux session of the machines (0.65): NOT OPEN HERE first — what no terminal at this seat shows — then RUNNING NOW, then OTHER TMUX SESSIONS (a shell, an agent outside ~); a session's row only attaches to it, as it is (vdx ai --attach ), and the terminals on it stay --find Claude Code: the list of the project's conversations whose replies — yours and the agent's — have the phrase, with the text around it: a piece of a screen left after tmux fell finds its conversation. Case, punctuation and the screen's line breaks do not count. Pick one as from the list; without a terminal, or with --list or --dry-run, it is printed with the command for each row. / at the list's question searches the same way --restore Claude Code: bring back what a fall took down — a crash of tmux, of cmux or of the machine, a kill-server, a reboot — without a question. First every agent a fallen tmux server took down on this machine, of every project: each in its tmux session (its old name, or the next free one), conversation, mode and topic, attached to by nobody. One with nothing typed since /clear, or finished with a wrap, comes back in a new conversation, as a place. The intercom session you started or attached to comes back, to stay; one a letter started is left out, and a running one is not doubled. Left out: a conversation running now (here or on another machine) or continued on another machine since. Claude Code's transcripts (~/.claude/projects) and the projects that lead nowhere yet — a link to a volume not mounted, as at login — are waited for up to 10 minutes; transcripts still nowhere: no agent starts, exit 4, the line begins with ✗ and the path; a project still nowhere keeps its record for the next restore (0.62). Then the same on the profile's other machines (session.machines), over ssh (0.59). Then the cmux tabs here that lost their sessions (0.59): a tab at its shell gets vdx ai --tab typed into it, a tab cmux lost opens again in its folder; where a tab went is the note vdx ai keeps (--tab below), or the tmux session cmux noticed in it before cmux last started. cmux takes this only from its own tabs: run elsewhere, the tabs are named, with where to run it. Run in one of those tabs, that tab goes back last. With --dry-run: what it would do. With --forget: no agent is started — they are forgotten, each named with whether work was in it (a conversation with work stays, to continue by its id). A plain start offers the same as r. A terminal vdx ai attached waits for its session when the server falls under it, and attaches again once a restore brings it back --tab for the shell of a cmux tab, started again after cmux restarted: back into the session the tab showed. vdx ai, while it holds an attach in a cmux tab, notes the session in ~/.local/state/vdx/cmux-tabs/ .json and drops the note when the attach ends; gone down with cmux, or refused by tmux, it leaves it (0.59). A session on another machine (vdx ai@) is found there by the mark @vdx_tab. No note, but cmux started minutes ago with a tmux attach noticed in the tab: that session, if no terminal of this machine shows it (0.61). Neither: nothing, exit 0; the session not running: exit 4, the note stays (0.53) — while a restore brings that session back after a reboot, the tab waits for it up to 3 minutes (0.59). cmux types "cmux restore --surface" into a tab it brings back itself (cmux 0.65): --tab reads that line off the terminal before it attaches, up to 5 s, unless a restore typed the command (VDX_TAB_NOW=1); what it took goes to ~/.cache/vdx/tab.log (0.61). In a cmux tab, vdx ai tells cmux the project directory while it holds the attach (0.61). The terminal tmux gets is the tab's own device, even when the caller hands /dev/tty (0.59) --report for the vdx of another machine, over ssh: this machine on the project, as JSON — what runs here, what its terminals show, its transcripts --check for the agent's own session: how the agent here is launched, whether this session carries the profile's flags, and whether it runs the installed Claude Code and plugins (the vdx plugin's SessionStart hook); prints nothing without a profile; exit 3 on drift. It also keeps a record of the agent's tmux pane, for --restore, and of any agent pane here that has none (a plain start and --restore do too); --conversation — the conversation the hook says starts. It also sets @vdx_state, as --state does --state for the agent's own session (the vdx plugin's Stop hook): the tmux option @vdx_state of its session — empty (nothing typed since /clear) or finished (a wrap skill of session.wrap_skills ran, and nothing was typed since), from the transcript of the conversation --conversation names; unset when neither. The cmux sidebar shows it. Prints nothing; outside tmux does nothing -h, --help this help What a plain start does (Claude Code). The other machines (session.machines in the profile, and those the conversations name) are asked over ssh what runs there now; each conversation is marked with the machine it was last started on (the vdx plugin's hook writes it in, or that machine's prompt history). Silent in three cases only: one agent of the project runs on all the machines and no terminal at your seat shows it — attach to it; none runs, and the newest conversation is this machine's and not finished — continue it; the project has none — a new one. Otherwise one list: the agents running on every machine (its state — working, waiting, a draft in its input line, empty since /clear, finished with a wrap skill of session.wrap_skills, idle N days — and which seat's terminal shows it), then the newest conversations nobody runs, unfinished, left after a look (/clear more than a day after the last word, 0.57) or finished, and how many more there are — each group under its title, its rows in columns: the machine, the state, the mode, one caption (the title; the topic of one with no title). Enter takes the marked row (→): an agent with work in it that no terminal at your seat shows, else the newest unfinished conversation. a — every conversation; / — the conversations that have it (--find); n — a new one; f — a new focused one. With fzf on PATH the list has a cursor instead of a typed answer: move over the rows, type to filter them, the row under the cursor is told whole in a panel; all, new and new focused are rows, ctrl-s searches what was said for the typed phrase, ctrl-y prints the row's command and starts nothing, Esc starts nothing. VDX_PLAIN_LIST=1 keeps the numbered list. Another machine's conversation is continued on that machine (if it does not answer, vdx asks before continuing it here), and one whose copy here is behind that machine's — Syncthing has not brought it yet — too. After the tmux server here fell, the list opens with what it took down (of this project; of every project where session.restore_all holds), and in a cmux tab with the tabs here that lost their sessions (0.59), never silent: Enter and r bring back everything, as --restore does, and the start goes on; agents of other projects only — one note under the list, with whether work was in them. Without a terminal it takes this machine's agent, else its newest conversation, else a new one. A new conversation while an agent of the project runs on another machine starts only after a yes — unless you picked it from a list that showed that agent: the one list, or the list of --focused (focused sessions only). --new and --focused take an empty session of the project (nothing typed since /clear) when one is there and no terminal at your seat shows it; a session with work in it they leave running, and so one started in the last two minutes: its first message may not be written yet (0.60.1). A new session does not take the name of one where an agent is still starting. Claude Code's memory of the project (Claude Code only): when it is not inside the project, .claude/memory/, or the folder was moved, a start in a terminal asks to put it there — Enter does, as vdx doctor --fix; with an agent of the project running, or no terminal, it only names that command. Exit codes: 0 the agent runs per the profile; 2 profile or usage error; 3 the running agent lacks profile flags, or is not focused under --focused, and was left as is — no terminal, or q (rerun with --restart); 4 the start was not confirmed. Profile format: https://github.com/VoDmAl/vdx/blob/main/docs/specs/environment-format.md `; const COMMANDS: Record = { audit: { usage: 'vdx audit [project_path] [--rubric ] [--stack ] [--format=ansi|markdown|json] [--json]', help: `Scores the project (default: cwd) against the rubric and prints the report. Reads only. The rubric is the bundled one unless --rubric or $VDX_RUBRIC names another. For branch-protection it asks the hosting of origin whether its default branch takes changes only after a check required of everyone: GitHub, with a token from $GH_TOKEN, $GITHUB_TOKEN or gh when there is one; GitLab, with glab's token for that host, or $GITLAB_TOKEN when the host is $GITLAB_HOST (gitlab.com unless set) — no other host gets it; Bitbucket Server, with the login git keeps for that host (git credential), or $BITBUCKET_TOKEN when the host is $BITBUCKET_HOST. Another hosting is unknown; VDX_OFFLINE=1 does not ask, and the axis says unknown. `, bools: ['json'], values: ['rubric', 'stack', 'format'], positionals: 1, }, init: { usage: 'vdx init [project_path] [--stack ] [--baseline ] [--dry-run] [--force]', help: `Writes mise.toml for the project (default: cwd): the lifecycle verbs mapped to the project's own scripts. --dry-run prints it and writes nothing; an existing mise.toml is overwritten only with --force. `, bools: ['dry-run', 'force'], values: ['stack', 'baseline'], positionals: 1, }, publish: { usage: 'vdx publish [--dry-run] [--force] [--no-push]', help: `Releases the library in the current directory, start to finish: pre-flight checks — at a terminal an expired npm login is renewed (\`npm login\`) and the checks run again; the version bump in package.json and package-lock.json; npm publish (npm asks for an OTP or a confirmation in the browser; Ctrl-C there puts the version back); git commit and tag, then \`git push --follow-tags\` to the branch's upstream — through its checks when it requires some, as \`vdx push\` does: the pre-flight then refuses local commits not pushed yet, npm would get them before CI; a wait until the registry shows the new version (up to 10 min from npm publish; Ctrl-C there stops only the wait). Nothing in the package's directory changed since the tag of its version: the same package under a new number — at a terminal a question, Enter releases nothing. Without a terminal it releases nothing: npm would ask for an OTP nobody sees. --dry-run runs the pre-flight and prints the plan; --force goes on past a failed pre-flight, and without a terminal; --no-push leaves the commit and the tag local. `, bools: ['dry-run', 'force', 'no-push'], positionals: 1, }, push: { usage: 'vdx push [project_path] [--dry-run]', help: `Pushes the current branch to its upstream. When the upstream is on GitHub and requires checks (branch protection or a ruleset), the commit goes to ${GATE_PREFIX} first: CI checks it there, vdx waits for the checks and then pushes the same commit to the branch, with its annotated tags (--follow-tags). A failed check leaves the branch as it was and names the check. A branch that requires no checks, a remote not on GitHub, a GitHub that does not answer: a plain \`git push\`, hooks and all. The pushes through the checks carry VDX_GATE_PUSH=1: a pre-push hook that runs what CI runs may step aside. GitHub is asked with a token from $GH_TOKEN, $GITHUB_TOKEN or gh when there is one — without one it answers 60 requests an hour, and a push takes about ten; VDX_OFFLINE=1 does not ask. project_path the repository (default: cwd) --dry-run say which way the push goes; push nothing Exit codes: 0 pushed; 2 nowhere to push it (no branch, no upstream, behind it); 3 the branch did not take the commit — a check failed, did not finish in 20 min, or GitHub stopped answering; a plain git push exits with git's own code. `, bools: ['dry-run'], positionals: 1, }, doctor: { usage: 'vdx doctor [project_path] [--check | --fix | --staged] [--format=ansi|markdown|json] [--json]', help: `Checks this machine for what vdx needs (Node, git, mise, npm auth, docker, the Claude Code plugin) and, inside a project (default: cwd, when it looks like one; a folder named here is one, git or not — the home directory never), its commit author and its git hooks: are the hooks the repository declares on in this clone, and do the personal hooks of your profile (git.hooks) run on this machine; with origin on GitHub, the token vdx asks GitHub with ($GH_TOKEN, $GITHUB_TOKEN or gh) and whether it works — without one GitHub answers 60 requests an hour; and where Claude Code keeps the project's memory: inside it, .claude/memory/, a moved folder takes it along. Reads only, unless --fix. Exit 2 when something is missing. --check for the agent's own session (the vdx plugin's SessionStart hook): one line per hook that is declared but does not run here, and one when the memory is not inside; nothing when in order --fix write the profile's personal hooks into ~/.gitconfig where they are missing or differ (repository hooks are switched on by the project's install step, which the report names); and put the memory inside: notes from ~/.claude/projects//memory into .claude/memory/, none overwritten, the old place renamed, autoMemoryDirectory written — into .claude/settings.json in a personal project (only you read where its commits go — see --staged), else into .claude/settings.local.json, with the memory kept out of git (.git/info/exclude) unless you say yes. After a folder is moved: the path follows it, and the project's conversations move to the new path; a folder Claude Code has not trusted yet is named. Notes a session that started before the move wrote at the old place come in, with their MEMORY.md lines. A path the repo's settings.json gives to another clone of the same repo is the repo's choice and stays; one to another folder goes, for this clone, into its .claude/settings.local.json --staged the profile's pre-commit hook: refuses a commit that stages .claude/memory/ unless only you read every place the commit reaches — origin on a host of git.personal_hosts or a private GitHub repo with nobody else, and each mirror the profile names (GitHub asked with gh's token); no answer, no token — refused. Silent otherwise `, bools: ['json', 'check', 'fix', 'staged'], values: ['format'], positionals: 1, }, move: { usage: 'vdx move ... [--dry-run]', help: `Moves the projects into (made if missing; a project keeps its own name) on this machine and on every other machine of your profile (session.machines) that has them, and takes along what Claude Code keeps by the folder's path: the memory path (autoMemoryDirectory), the conversations, the trust in the folder. Any move works: within a Syncthing folder, from one into another, out of Syncthing, into it, or beside it. Each machine says where the old and the new path lie in Syncthing (syncthing-caught-up --json), and the plan names the case. Nothing changes until every check passed: the new place is free on every machine, every machine answers over ssh, Syncthing has caught up with both paths there (changes on the way are waited for a minute), no container mounts the folder, and no Claude Code session of a project is in a turn or waiting for an answer. An idle session is a question at a terminal — Enter closes it and starts it again in the new place, in the same conversation (an intercom session: the next letter starts it); without a terminal the move is refused. A process working in the folder is named; when the new place is on another volume (mv copies, then deletes), it refuses the move until it stops — a shell does not. The Syncthing folders of both paths are paused on every machine that has them while the mv runs on each, and resumed whatever happens, Ctrl-C too: else one machine gets the other's deletion of the old path before its own mv. The mv runs on every machine of a synced folder, so what Syncthing does not carry (node_modules, builds, a container's database) moves with it and no old folder is left behind; a folder on a network disk or in a cloud folder is one copy, moved once. Copies Syncthing would merge at the new place — the project kept apart on two machines, going into a synced folder — cannot all go: a terminal asks which one (commit and uncommitted files shown, Enter takes the one where you are), the others stay. Peers of the folders outside the profile are named with what they get; when Syncthing would delete the project there, a terminal asks first ([y/N]). A machine whose mv fails puts the others back. git keeps a worktree's links by absolute paths, both ways: a repository with worktrees, or a worktree, that moves is named in the plan, and after the mv each machine runs git worktree repair from the main repository's place. On every machine with zoxide whose copy moved, zoxide's paths under the old place go to the new one with their scores (0.64). Then, on this machine, the profile's move.after commands run with VDX_MOVE_FROM and VDX_MOVE_TO — for tools that keep the project's path in their own files. --dry-run print the plan — what moves where, the Syncthing case and pauses, peers, copies, sessions, processes; move nothing Exit codes: 0 moved; 2 usage or profile error; 3 refused by a check, nothing moved; 4 a step failed — what was moved is put back where it could be, and named. `, bools: ['dry-run'], positionals: 64, }, ai: { usage: 'vdx ai[@host] [project_path] [--new | --conversation | --find ] [--focused [] [--prompt ] | --intercom | --hq] [--restart] [--detach] [-y | --yes | --no-input] [--dry-run | --list] | vdx ai --restore [--forget] [--dry-run] | vdx ai --tab', help: AI_HELP, // `--resume` asked to continue in 0.12; continuing is the default now. bools: [ 'new', 'intercom', 'hq', 'restart', 'resume', 'detach', 'dry-run', 'check', 'forget', 'close', 'list', 'report', 'restore', 'state', 'tab', 'yes', 'no-input', ], values: ['conversation', 'waiting', 'find', 'prompt', 'attach'], optional: ['focused'], positionals: 1, shorts: { '-y': 'yes' }, }, ...Object.fromEntries( LIFECYCLE_VERBS.map((verb) => [ verb, { usage: `vdx ${verb}`, help: `Runs \`mise run ${verb}\` in the current directory — the project's own ${verb} command, as mise.toml maps it. Takes no arguments. `, positionals: 0, }, ]), ), }; interface ParsedArgs { cmd: string; positionals: string[]; flags: Record; } function parseArgs(argv: string[]): ParsedArgs { const cmd = argv[2] ?? ''; const rest = argv.slice(3); const positionals: string[] = []; const flags: Record = {}; for (let i = 0; i < rest.length; i++) { const a = rest[i]!; if (a.startsWith('--')) { const body = a.slice(2); const eqIdx = body.indexOf('='); if (eqIdx >= 0) { flags[body.slice(0, eqIdx)] = body.slice(eqIdx + 1); } else { const next = rest[i + 1]; if (next !== undefined && !next.startsWith('--')) { flags[body] = next; i++; } else { flags[body] = true; } } } else { positionals.push(a); } } return { cmd, positionals, flags }; } /** * Keeps what the command reads and refuses the rest, before anything runs: a * misread argument must not run the command. `vdx ai --help` started an agent, * `vdx init --help` wrote mise.toml, `vdx down --help` ran `mise run down`. */ function checkArgs(name: string, opts: ParsedArgs): ParsedArgs { const spec = COMMANDS[name]!; const bools = [...(spec.bools ?? []), 'help']; const values = [...(spec.values ?? []), ...(spec.optional ?? [])]; // parseArgs hands the token after a bare flag to that flag as its value; a // flag that takes none gives it back — it is the path (or `-h`). const positionals = [...opts.positionals]; const flags: Record = {}; for (const [flag, value] of Object.entries(opts.flags)) { if (bools.includes(flag) && typeof value === 'string') { positionals.push(value); flags[flag] = true; } else { flags[flag] = value; } } for (const [short, long] of Object.entries(spec.shorts ?? {})) while (positionals.includes(short)) { positionals.splice(positionals.indexOf(short), 1); flags[long] = true; } if (flags.help || positionals.includes('-h')) { process.stdout.write(`Usage: ${spec.usage}\n\n${spec.help}`); process.exit(0); } const fail = (message: string): never => { process.stderr.write(`vdx ${name}: ${message}\nUsage: ${spec.usage}\nMore: vdx ${name} --help\n`); process.exit(2); }; const unknown = [ ...Object.keys(flags) .filter((f) => !bools.includes(f) && !values.includes(f)) .map((f) => `--${f}`), ...positionals.filter((p) => p.startsWith('-')), ]; if (unknown.length > 0) fail(`unknown option ${unknown.join(', ')}`); const bare = (spec.values ?? []).filter((f) => flags[f] === true).map((f) => `--${f}`); if (bare.length > 0) fail(`${bare.join(', ')} needs a value`); if (positionals.length > spec.positionals) { fail(`unexpected argument ${positionals.slice(spec.positionals).join(' ')}`); } return { cmd: opts.cmd, positionals, flags }; } function cmdAudit(opts: ParsedArgs): void { const projectArg = opts.positionals[0] ?? '.'; const projectRoot = path.resolve(projectArg); if (!looksLikeProject(projectRoot)) { process.stderr.write( `vdx: ${projectRoot} doesn't look like a project root ` + `(no package.json / composer.json / pyproject.toml / Makefile / mise.toml / .git found)\n` + `hint: try \`vdx doctor\` to check your environment, or \`vdx audit \`.\n\n`, ); } const found = loadManifestAt(projectRoot); const manifest = found?.manifest ?? null; if (found?.place === 'vdx') { process.stderr.write( 'note: the manifest is in [vdx] of mise.toml, and mise 2026.10 warns about it on every run; ' + 'its place is [_.vdx], once every machine of the project runs vdx 0.26 or newer\n', ); } const overrides = loadOverrides(projectRoot); const rubricPath = (opts.flags.rubric as string) || DEFAULT_RUBRIC; const rubric = loadRubric(rubricPath); const stack = (opts.flags.stack as string) || manifest?.stack || autoDetectStack(projectRoot); const ctx: Ctx = { projectRoot, stack, cache: new Map(), }; const baselineRef = manifest?.baseline ?? `file://${rubricPath}`; const result = audit(rubric, ctx, overrides, baselineRef, manifest); const formatFlag = typeof opts.flags.format === 'string' ? opts.flags.format : undefined; const wantJson = opts.flags.json === true || formatFlag === 'json'; const wantMarkdown = formatFlag === 'markdown' || formatFlag === 'md'; const wantAnsi = formatFlag === 'ansi'; const isTty = process.stdout.isTTY === true; if (wantJson) { process.stdout.write(reportJson(result) + '\n'); } else if (wantMarkdown) { process.stdout.write(reportMarkdown(result)); } else if (wantAnsi || (isTty && !formatFlag)) { process.stdout.write(reportAnsi(result)); } else { process.stdout.write(reportMarkdown(result)); } } function cmdInit(opts: ParsedArgs): void { const projectArg = opts.positionals[0] ?? '.'; const projectRoot = path.resolve(projectArg); const baselineFlag = opts.flags.baseline; const baseline = typeof baselineFlag === 'string' ? baselineFlag : undefined; const stackFlag = opts.flags.stack; const stackOverride = typeof stackFlag === 'string' ? stackFlag : undefined; const plan = planInit(projectRoot, { ...(baseline ? { baseline } : {}), ...(stackOverride ? { stack: stackOverride } : {}), }); const dryRun = Boolean(opts.flags['dry-run']); process.stdout.write(renderPlanSummary(plan, { verbose: dryRun })); for (const w of plan.warnings) { process.stderr.write(`\n⚠ ${w}\n`); } if (dryRun) { process.stderr.write('\n[dry-run] mise.toml не записан.\n'); return; } try { writeInit(plan, { force: Boolean(opts.flags.force) }); process.stderr.write(`\n✓ wrote ${plan.miseTomlPath}\n`); } catch (e) { process.stderr.write(`\nerror: ${errorMessage(e)}\n`); process.exit(2); } } function cmdPublish(opts: ParsedArgs): void { const bumpArg = opts.positionals[0]; if (!bumpArg || !['patch', 'minor', 'major'].includes(bumpArg)) { process.stderr.write('Usage: vdx publish [--dry-run] [--force] [--no-push]\n'); process.exit(1); } const bump = bumpArg as BumpKind; const projectRoot = process.cwd(); // npm asks for an OTP or a confirmation in the browser, after the bump: without a // terminal nobody answers. Claude Code's Bash tool has none, and `!` there moves a // command past 120 s to the background (publish-npm-outage-preflight, 2026-10-22). if (!opts.flags['dry-run'] && !opts.flags.force && process.stdin.isTTY !== true) { process.stderr.write( `vdx publish: no terminal here — npm asks for a one-time password or a confirmation in the browser, ` + `and nobody could answer. Run it in your own terminal: vdx publish ${bump}. ` + `--dry-run shows the plan; --force releases without a terminal (an automation token)\n`, ); process.exit(2); } const manifest = loadManifest(projectRoot); const overrides = loadOverrides(projectRoot); const rubric = loadRubric(DEFAULT_RUBRIC); const stack = manifest?.stack || autoDetectStack(projectRoot); const ctx: Ctx = { projectRoot, stack, cache: new Map() }; const baselineRef = manifest?.baseline ?? `file://${DEFAULT_RUBRIC}`; const auditResult = audit(rubric, ctx, overrides, baselineRef, manifest); const planOpts: PublishOptions = { projectRoot, bump, dryRun: Boolean(opts.flags['dry-run']), force: Boolean(opts.flags.force), push: !opts.flags['no-push'], }; const replan = () => { try { return planPublish(planOpts, auditResult, ctx); } catch (e) { process.stderr.write(`error: ${errorMessage(e)}\n`); process.exit(2); } }; let plan = replan(); process.stdout.write(renderPublishPlan(plan)); if (planOpts.dryRun) { process.stderr.write('\n[dry-run] не выполнено.\n'); return; } // A failure a command fixes (an expired npm login): run it here, then check again. const deps = defaultPublishDeps(); const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true; if (!plan.preflightPassed && !planOpts.force && interactive && preflightFixable(plan)) { const fixes = plan.preflight.filter((c) => !c.ok && c.fix); for (const c of fixes) { process.stderr.write(`\n→ ${c.name}: ${c.fix!.cmd} ${c.fix!.args.join(' ')}\n`); try { deps.run(c.fix!.cmd, c.fix!.args, projectRoot); } catch { process.stderr.write(`error: \`${c.fix!.cmd} ${c.fix!.args.join(' ')}\` failed\n`); process.exit(2); } } if (fixes.length > 0) { plan = replan(); process.stdout.write('\n' + renderPublishPlan(plan)); } } // A failure the person may waive (nothing changed since the release): a question, Enter no. let waived = false; const left = plan.preflight.filter((c) => !c.ok); if (!planOpts.force && interactive && left.length > 0 && left.every((c) => c.waive)) { for (const c of left) { process.stderr.write(`\n${c.name}: ${c.message}\n`); if (!/^y(es)?$/i.test(askLine(c.waive!) ?? '')) { process.stderr.write('nothing released\n'); process.exit(2); } } waived = true; } if (!plan.preflightPassed && !planOpts.force && !waived) { process.stderr.write('\nerror: pre-flight failed (use --force to bypass)\n'); process.exit(2); } try { executePublish(plan, deps); } catch (e) { process.stderr.write(`\nerror: ${errorMessage(e)}\n`); process.exit(3); } } function cmdPush(opts: ParsedArgs): void { const root = path.resolve(opts.positionals[0] ?? '.'); const deps = defaultGateDeps(root); const plan = planGate(deps.io); if (plan.kind === 'refuse') { process.stderr.write(`vdx push: ${plan.message}\n`); process.exit(2); } if (plan.kind === 'plain') { process.stderr.write(`→ git push — ${plan.why}\n`); if (opts.flags['dry-run']) return; try { execFileSync('git', ['-C', root, 'push'], { stdio: 'inherit' }); } catch (e) { const status = at(e, 'status'); process.exit(typeof status === 'number' ? status : 1); } return; } const t = plan.target; process.stderr.write( `→ ${t.remote}/${t.branch} requires ${t.checks.join(', ')}: through ${GATE_PREFIX}${t.branch}, ` + `then ${t.branch} once they pass\n`, ); if (opts.flags['dry-run']) return; try { pushThroughGate(t, deps); } catch (e) { process.stderr.write(`\nerror: ${errorMessage(e)}\n`); process.exit(3); } } function cmdRun(verb: LifecycleVerb): void { const projectRoot = process.cwd(); const res = resolveLifecycleVerb(projectRoot, verb); if (!res.ok) { process.stderr.write(renderResolveError(res, projectRoot, verb)); process.exit(2); } try { execFileSync('mise', ['run', verb], { cwd: projectRoot, stdio: 'inherit' }); } catch (e) { if (at(e, 'code') === 'ENOENT') { process.stderr.write( `vdx: \`mise\` binary not found on PATH\n` + `hint: install mise — https://mise.jdx.dev/getting-started.html\n`, ); process.exit(127); } const status = at(e, 'status'); process.exit(typeof status === 'number' ? status : 1); } } function cmdDoctor(opts: ParsedArgs): void { const ctx = resolveDoctorCtx(path.resolve(opts.positionals[0] ?? '.'), opts.positionals[0] !== undefined); if ([opts.flags.check, opts.flags.fix, opts.flags.staged].filter((f) => f === true).length > 1) { process.stderr.write('vdx doctor: --check reports, --fix writes, --staged guards a commit — pick one\n'); process.exit(2); } if (opts.flags.staged === true) { const root = resolveProjectRoot(ctx.projectRoot ?? '.') ?? process.cwd(); const refusal = runDoctorStaged(root); if (refusal) { process.stderr.write(refusal + '\n'); process.exit(1); } return; } if (opts.flags.check === true) { const text = runDoctorCheck(ctx); if (text) process.stdout.write(text + '\n'); return; } if (opts.flags.fix === true) { try { const done = runDoctorFix(); process.stderr.write( done.length > 0 ? done.map((d) => `✓ ${d}`).join('\n') + '\n' : 'nothing to fix in ~/.gitconfig\n', ); } catch (e) { process.stderr.write(`vdx doctor --fix: ${errorMessage(e)}\n`); process.exit(2); } const root = ctx.projectRoot ? resolveProjectRoot(ctx.projectRoot) : null; const memory = root ? checkClaudeMemory({ projectRoot: root }) : null; if (root && memory?.remedy) { try { // The question goes to stderr: the report on stdout may be redirected. const interactive = process.stdin.isTTY === true && process.stderr.isTTY === true; const done = fixDoctorMemory(root, memoryState(root, { env: process.env, home: os.homedir() }), { ask: (prompt) => (interactive ? askLine(prompt) : null), log: (line) => process.stderr.write(line + '\n'), today: new Date().toLocaleDateString('sv-SE'), }); process.stderr.write(done.map((d) => `✓ ${d}`).join('\n') + (done.length ? '\n' : '')); } catch (e) { process.stderr.write(`vdx doctor --fix: Claude memory — ${errorMessage(e)}\n`); process.exit(2); } } } const report = runDoctor(ctx); const formatFlag = typeof opts.flags.format === 'string' ? opts.flags.format : undefined; const wantJson = opts.flags.json === true || formatFlag === 'json'; const wantMarkdown = formatFlag === 'markdown' || formatFlag === 'md'; const wantAnsi = formatFlag === 'ansi'; const isTty = process.stdout.isTTY === true; if (wantJson) { process.stdout.write(reportDoctorJson(report) + '\n'); } else if (wantMarkdown) { process.stdout.write(reportDoctorMarkdown(report)); } else if (wantAnsi || (isTty && !formatFlag)) { process.stdout.write(reportDoctorAnsi(report)); } else { process.stdout.write(reportDoctorMarkdown(report)); } if (report.missing > 0) process.exit(2); } function cmdAi(opts: ParsedArgs): void { if (opts.flags.check === true) { // About the session this runs in — there is nothing to start, and no other machine. The vdx // plugin's hook names the conversation that starts (0.46): the record for a restore keeps it. const others = Object.keys(opts.flags).filter((f) => f !== 'check' && f !== 'conversation'); if (others.length > 0 || opts.cmd !== 'ai') { process.stderr.write( `vdx ai: --check takes only the project path and --conversation (not ${opts.cmd !== 'ai' ? opts.cmd : `--${others.join(', --')}`})\n`, ); process.exit(2); } const id = opts.flags.conversation; if (id !== undefined && !(typeof id === 'string' && isConversationId(id))) { process.stderr.write(`vdx ai: --conversation takes a conversation id (a UUID), not "${String(id)}"\n`); process.exit(2); } process.exit(runAiCheck(opts.positionals[0] ?? '.', defaultDeps(), process.pid, id)); } if (opts.flags.state === true) { // About the session this runs in, from its Stop hook: one tmux option, nothing printed. const others = Object.keys(opts.flags).filter((f) => f !== 'state' && f !== 'conversation'); if (others.length > 0 || opts.cmd !== 'ai') { process.stderr.write( `vdx ai: --state takes only the project path and --conversation (not ${opts.cmd !== 'ai' ? opts.cmd : `--${others.join(', --')}`})\n`, ); process.exit(2); } const id = opts.flags.conversation; if (id !== undefined && !(typeof id === 'string' && isConversationId(id))) { process.stderr.write(`vdx ai: --conversation takes a conversation id (a UUID), not "${String(id)}"\n`); process.exit(2); } process.exit(runAiState(opts.positionals[0] ?? '.', defaultDeps(), process.pid, id)); } if (opts.flags.forget === true && opts.flags.restore !== true) { process.stderr.write('vdx ai: --forget goes with --restore — vdx ai --restore --forget [--dry-run]\n'); process.exit(2); } if (opts.flags.restore === true) { // Every project's agents a fallen tmux server took down on this machine: no project to name. const others = Object.keys(opts.flags).filter((f) => f !== 'restore' && f !== 'dry-run' && f !== 'forget'); if (others.length > 0 || opts.cmd !== 'ai' || opts.positionals.length > 0) { process.stderr.write( `vdx ai: --restore brings back every project's agents on this machine — it takes only --forget and --dry-run (not ${ opts.cmd !== 'ai' ? `${opts.cmd}; there: ssh ${opts.cmd.slice(3)} vdx ai --restore` : others.length ? `--${others.join(', --')}` : opts.positionals.join(' ') })\n`, ); process.exit(2); } process.exit(runAiRestore(opts.flags['dry-run'] === true, defaultDeps(), opts.flags.forget === true)); } if (opts.flags.tab === true) { // The shell of a cmux tab after cmux restarted (or the vdx there, over ssh): nothing else to say. const others = Object.keys(opts.flags).filter((f) => f !== 'tab'); if (others.length > 0 || opts.cmd !== 'ai') { process.stderr.write( `vdx ai: --tab takes nothing else (not ${opts.cmd !== 'ai' ? opts.cmd : `--${others.join(', --')}`}) — the tab's note says where it goes\n`, ); process.exit(2); } process.exit(runAiTab(opts.positionals[0] ?? '.', { ...defaultDeps(), version: readCliVersion() })); } if (opts.flags.report === true) { // What another machine's vdx asks over ssh: this machine's facts on the project, as JSON. const others = Object.keys(opts.flags).filter((f) => f !== 'report'); if (others.length > 0 || opts.cmd !== 'ai') { process.stderr.write( `vdx ai: --report takes only the project path (not ${opts.cmd !== 'ai' ? opts.cmd : `--${others.join(', --')}`})\n`, ); process.exit(2); } process.exit(runAiReport(opts.positionals[0] ?? '.', { ...defaultDeps(), version: readCliVersion() })); } if (opts.flags.close === true || opts.flags.waiting !== undefined) { // Run inside the intercom session, about that session: nothing to start, no other machine. const others = Object.keys(opts.flags).filter((f) => f !== 'close' && f !== 'waiting'); if (opts.flags.close !== true || others.length > 0 || opts.cmd !== 'ai') { process.stderr.write( opts.flags.close !== true ? 'vdx ai: --waiting goes with --close\n' : `vdx ai: --close takes only the project path and --waiting (not ${opts.cmd !== 'ai' ? opts.cmd : `--${others.join(', --')}`})\n`, ); process.exit(2); } const raw = opts.flags.waiting; const waiting = raw === undefined ? 0 : typeof raw === 'string' && /^\d+$/.test(raw) ? Number(raw) : NaN; if (Number.isNaN(waiting)) { process.stderr.write( `vdx ai: --waiting takes the number of questions to the user (0, 1, 2…), not "${String(raw)}"\n`, ); process.exit(2); } process.exit(runAiClose(opts.positionals[0] ?? '.', waiting, defaultDeps())); } const conversation = typeof opts.flags.conversation === 'string' ? opts.flags.conversation : undefined; if (conversation !== undefined && !isConversationId(conversation)) { process.stderr.write(`vdx ai: --conversation takes a conversation id (a UUID), not "${conversation}"\n`); process.exit(2); } const prompt = typeof opts.flags.prompt === 'string' ? opts.flags.prompt.trim() : undefined; if (prompt !== undefined && (!prompt || opts.flags.focused === undefined)) { process.stderr.write( 'vdx ai: --prompt is the first message of a new focused session: vdx ai --focused "" --prompt ""\n', ); process.exit(2); } const find = typeof opts.flags.find === 'string' ? opts.flags.find : undefined; if (find !== undefined && !find.trim()) { process.stderr.write('vdx ai: --find takes a phrase to search for: --find "a piece of the screen"\n'); process.exit(2); } if (conversation !== undefined && opts.flags.new === true) { process.stderr.write('vdx ai: --new and --conversation ask for different conversations — pick one\n'); process.exit(2); } // `--focused `: the session's topic — or, with no path named, a folder that exists: the // project's path, as before the topic (focused-topic DL #3). const focusedWord = typeof opts.flags.focused === 'string' ? opts.flags.focused : undefined; let projectPath = opts.positionals[0]; let topic: string | undefined; if (focusedWord !== undefined) { if (projectPath === undefined && resolveProjectRoot(focusedWord) !== null) projectPath = focusedWord; else topic = normalizeTopic(focusedWord) || undefined; } const options = { path: projectPath ?? '.', restart: opts.flags.restart === true, fresh: opts.flags.new === true, conversation, detach: opts.flags.detach === true, dryRun: opts.flags['dry-run'] === true, focused: opts.flags.focused !== undefined, topic, prompt, intercom: opts.flags.intercom === true, hq: opts.flags.hq === true, list: opts.flags.list === true, find: find?.trim(), // `--attach `: the row of a session in the list of `~` — attaches to it, starts nothing (DL #32). attach: typeof opts.flags.attach === 'string' ? opts.flags.attach : undefined, yes: opts.flags.yes === true, noInput: opts.flags['no-input'] === true, }; const deps = { ...defaultDeps(), version: readCliVersion() }; // `ai@m3`: the same command on another machine. Its own label runs here. const host = opts.cmd.startsWith('ai@') ? opts.cmd.slice(3) : null; if (host !== null) { if (!REMOTE_HOST_RE.test(host)) { process.stderr.write(`vdx ai@host: "${host}" is not a host name (an ssh destination such as m3)\n`); process.exit(2); } if (host.toLowerCase() !== hostLabel().toLowerCase()) { process.exit(runAiRemote(options, host, deps)); } } process.exit(runAi(options, deps)); } function cmdMove(opts: ParsedArgs): void { if (opts.positionals.length < 2) { process.stderr.write( `vdx move: name the project(s) and the folder to move them into\nUsage: ${COMMANDS['move']!.usage}\n`, ); process.exit(2); } const ai = { ...defaultDeps(), version: readCliVersion() }; const restart = (input: { host: string | null; path: string; conversation: string; focused: boolean; hq: boolean; }): number => { const options = { path: input.path, conversation: input.conversation, focused: input.focused, hq: input.hq, detach: true, restart: false, fresh: false, dryRun: false, }; return input.host === null ? runAi(options, ai) : runAiRemote(options, input.host, ai); }; const deps = defaultMoveDeps({ env: process.env, home: os.homedir(), interactive: process.stdin.isTTY === true && process.stderr.isTTY === true, log: (line) => process.stderr.write(line + '\n'), ask: askLine, sleep: sleepSync, restart, }); process.exit( runMove( { sources: opts.positionals.slice(0, -1), folder: opts.positionals[opts.positionals.length - 1]!, dryRun: opts.flags['dry-run'] === true, }, deps, ), ); } const parsed = parseArgs(process.argv); if (parsed.cmd === '--version') process.stdout.write(readCliVersion() + '\n'); else if (['--help', '-h', 'help'].includes(parsed.cmd)) process.stdout.write(USAGE); else if (parsed.cmd === 'audit') cmdAudit(checkArgs('audit', parsed)); else if (parsed.cmd === 'init') cmdInit(checkArgs('init', parsed)); else if (parsed.cmd === 'publish') cmdPublish(checkArgs('publish', parsed)); else if (parsed.cmd === 'push') cmdPush(checkArgs('push', parsed)); else if (parsed.cmd === 'doctor') cmdDoctor(checkArgs('doctor', parsed)); else if (parsed.cmd === 'ai' || parsed.cmd.startsWith('ai@')) cmdAi(checkArgs('ai', parsed)); else if (parsed.cmd === 'move') cmdMove(checkArgs('move', parsed)); else if ((LIFECYCLE_VERBS as readonly string[]).includes(parsed.cmd)) { checkArgs(parsed.cmd, parsed); cmdRun(parsed.cmd as LifecycleVerb); } else { if (parsed.cmd !== '') process.stderr.write(`vdx: unknown command "${parsed.cmd}"\n`); usage(); }