CLI Internals
Technical reference for understanding CLI internals.
Package Structure
Section titled βPackage Structureβpackages/cli/βββ src/β βββ cli.ts # Entry point, argument parsing, routingβ βββ commands/β β βββ workflow.ts # workflow route module: re-exports every subcommand; reset-sessions/cleanup/eventβ β βββ workflow-control.ts # workflow resume/abandon/cancel/answer/approve/reject/respond (delegate to @archon/core/operations)β β βββ workflow-query.ts # workflow list/test/status/get/runs/logs/waitβ β βββ workflow-run-*.ts # workflow run: select, admit, launch, executeβ β βββ isolation.ts # isolation list/cleanup (list/merged-cleanup delegate to @archon/core/operations)β β βββ setup.ts # setup command implementationβ β βββ chat.ts # chat command implementationβ β βββ validate.ts # validate command implementationβ β βββ version.ts # version commandβ βββ adapters/β βββ cli-adapter.ts # IPlatformAdapter for stdoutβββ package.json # Defines "archon" binaryEntry Point Flow
Section titled βEntry Point Flowβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ archon <command> [subcommand] [options] [arguments] ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ strip-cwd-env-boot (first import, side-effect) ββ stripCwdEnv(): deletes Bun-auto-loaded <cwd>/.env* keys from ββ process.env + CLAUDE_CODE_* session markers. Emits ββ [archon] stripped N keys from <cwd> (...) when N > 0. ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ loadCliEnv(cwd) β wraps loadArchonEnv with identity protection ββ 1. ~/.archon/.env (home scope) ββ 2. <cwd>/.archon/.env (repo scope, exceptions below) ββ Emits one [archon] loaded N keys from <path> line per file ββ when N > 0 and ARCHON_VERBOSE_BOOT=1 or LOG_LEVEL=debug/trace.ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ cli.ts Parse arguments ββ --cwd, --branch, --no-worktree, --help ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ cli.ts Project resolution ββ Honor folder selection and registered folders; ββ otherwise resolve the nearest Git checkout ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ cli.ts Route to command handler ββ switch(command) β workflow | isolation | versionββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ cli.ts Exit with code, always closeDatabase() ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCode: packages/cli/src/cli.ts
Repository env normally overrides home env. The CLI preserves the user-scope GH_CONFIG_DIR (including its absence), so repository env cannot redirect the stored gh login. Inside a workflow, inherited GitHub identity values take precedence over both env files, including empty values that disable host credentials. See forge plugin configuration.
Project resolution:
workflow run --folderuses the supplied canonical directory, even inside Git, and explicitly registers it as a folder project.- A registered folder and its ordinary descendants resolve to the folder directory. Archon runs folder workflows in place without managing a worktree, branch or PR.
- A Git repository nested inside a registered folder retains its own repository identity. Other Git paths resolve to the nearest repository root, preserving linked-checkout ownership.
- Unregistered non-Git execution requires folder registration; first-use CLI execution uses
workflow run --folder. Without registration or that flag, execution exits with code 1. - File-only dry runs and fixture tests can inspect local files without registration. On a readable registry they honor folder ownership; if lookup fails they use the proven Git root or supplied directory.
workflow listandvalidateretain their Git-root fallback when the registry cannot open. version,help,setup, andchatbypass project resolution.
workflow list Flow
Section titled βworkflow list Flowββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ archon workflow list [name] [--full] [--json] βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ workflow-query.ts workflowListCommand(cwd, { name, full, json })βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ @archon/workflows/workflow-discovery ββ discoverWorkflowsWithConfig(cwd, loadConfig, providerRegistry) ββ - Loads bundled defaults ββ - Searches .archon/workflows/ recursively ββ - Merges (repo overrides defaults by name) βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Optional name resolution; project errors remain in the result ββ full=false: bounded description + structured truncation state ββ full=true: exact authored description βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βββββββββββββββββ΄ββββββββββββββββ β json=true β json=false βΌ βΌββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββ JSON output to stdout β β Human-readable list to stdout ββ descriptionTruncated β β shortened descriptions carry ββ { workflows, errors } β β the ` [truncated]` marker βββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββCode: packages/cli/src/commands/workflow-query.ts
workflow run Flow
Section titled βworkflow run Flowβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ archon workflow run <name> [message] [--branch X] [--detach] β¦ ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ selectRunWorkflow() ββ - Locate the run a continuation resumes ββ - Capture the workflow source, then discover from the capture ββ - Find the workflow by name (error lists available) ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ admitRunExecution() (--dry-run stops before this) ββ - Flag, worktree policy, input and capability gates ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βββββββββββββββ΄ββββββββββββββ β β --detach (default) β β βΌ βΌβββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββ launchDetachedOwnedRun() β β prepareForegroundLaunch() ββ Pre-flight, write the run β β Destination, project, adoption ββ row, fork the child β β lane, --resume binding, AI config ββββββββββββββββββββββββββββββ βββββββββββββββββ¬ββββββββββββββββββββ β βΌ βββββββββββββββββββββββββββββββββββββ β provisionWorkspace() β β Folder seam, reused --branch β β worktree, or a new worktree β βββββββββββββββββ¬ββββββββββββββββββββ β βΌ βββββββββββββββββββββββββββββββββββββ β executeOwnedRun() β β Signal guard, progress, engine β β submit or resume, wait, teardown, β β result β βββββββββββββββββββββββββββββββββββββCode: workflowRunCommand in packages/cli/src/commands/workflow-run-owned.ts, which owns the captured source and the durable-wait loop. The phases live in workflow-run-admission.ts, workflow-run-launch.ts and workflow-run-execution.ts beside it.
Worktree Provider: packages/isolation/src/providers/worktree.ts
workflow event emit Flow
Section titled βworkflow event emit Flowββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ archon workflow event emit --run-id <run-id> --type <type> [...] βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ cli.ts Validate --run-id, --type (required) ββ Validate --type against WORKFLOW_EVENT_TYPES ββ Parse --data as JSON (warn + skip if invalid) βββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ β βΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ workflow.ts workflowEventEmitCommand(..., cwd) ββ Resolve an unambiguous run-id prefix ββ Node state: persistWorkflowEvent(...) ββ Observability: createWorkflowEvent(...) ββ Run-ID resolution may fail βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCode: packages/cli/src/cli.ts (case βeventβ), packages/cli/src/commands/workflow.ts:workflowEventEmitCommand
Contract: The shared isNodeStateEventType predicate routes node-state events through
persistWorkflowEvent, which propagates storage failures. The CLI prints Event persisted
only after that write succeeds. Other events use createWorkflowEvent and retain best-effort
persistence: Event submitted (best-effort) does not guarantee storage. Run-ID resolution
can fail before either write.
isolation list Flow
Section titled βisolation list Flowβarchon isolation list β isolationListCommand() β ββ @archon/core listEnvironments() β ββ isolationDb.listAllActiveWithCodebase() β ββ For each codebase: isolationDb.listByCodebaseWithAge() β β ββ Reconcile missing worktrees, preserving live-run ownership β ββ Return environments grouped by codebase and reconciliation totals β ββ Print worktree details and totals (return early if no codebases) β ββ @archon/core listContainerEnvironments() β ββ isolationDb.listActiveContainerEnvironments() β ββ getRunByIsolationEnvId() for each container β β ββ Return matched run or null; throw on query/status errors β ββ Build summaries; catch lookup errors and set runStatus: lookup-failed β ββ Print container details and totals: run status, no run (orphan), or run lookup failedCode: packages/cli/src/commands/isolation.ts (isolationListCommand),
packages/core/src/operations/isolation-operations.ts
(listEnvironments), packages/core/src/services/cleanup/containers.ts
(listContainerEnvironments), packages/core/src/db/workflow-run-reads.ts
(getRunByIsolationEnvId).
The container listing matches metadata.isolation_env_id; no match does not
establish that cleanup can remove the container. Cleanup checks wider live
ownership. A failed lookup is logged and displayed as run lookup failed.
isolation cleanup Flow
Section titled βisolation cleanup Flowβarchon isolation cleanup [days] (default: 7) β ββ Reconcile missing worktrees (preserve container rows) β ββ findStaleEnvironments(days) β ββ Filter provider = 'worktree' β ββ For each stale worktree: β ββ Skip environments owned by resumable runs β ββ Skip any with a commit on no remote (getCleanupRunLock) β ββ provider.destroy(path, options) β ββ Mark destroyed only after complete removal β ββ cleanupContainerEnvironments(days), even when no worktrees are stale ββ Skip containers owned by resumable runs ββ Container backend removes container and volume ββ Mark destroyed only after successful removalCode: isolationCleanupCommand in packages/cli/src/commands/isolation.ts
isolation cleanup --merged Flow
Section titled βisolation cleanup --merged Flowβββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ archon isolation cleanup --merged [--include-closed] ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ isolation.ts isolationCleanupMergedCommand({ includeClosed }) ββ For each codebase β cleanupMergedWorktrees(codebaseId, path) ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β For each active environment β βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ judgeBranchForRemoval() β three-signal union ββ localBranchExists() gate: (a) and (b) need the local ref ββ (a) isBranchMerged() git ancestry (fast-forward/merge) ββ (b) isPatchEquivalent() git cherry (1-commit squash-merge) ββ (c) getPrState() gh CLI (MERGED/CLOSED/OPEN/NONE/ ββ UNAVAILABLE) ββ ββ any git signal β 'merged' if the worktree HEAD ββ also passes `git cherry <base> HEAD` ββ MERGED β 'merged' if the worktree HEAD ββ and the branch ref (where each ββ exists) are at or behind the PR head ββ CLOSED β 'pr-closed' the same way, only if ββ includeClosed ββ OPEN β 'open-pr', always kept ββ UNAVAILABLE β 'pr-unavailable', kept and reported ββ NONE and ref present β 'unmerged', not reclaimed ββ NONE and ref gone β 'unjudgeable', kept and reported ββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ β 'merged' or 'pr-closed' βΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Guard checks: no uncommitted changes, no run lock (checkRemoval ββ β getCleanupRunLock; a failed run's lock is released by the ββ verdict, running/pending/paused runs always lock) ββ provider.destroy() β remove worktree and local branch ββ β commit registration retirement; retain remote branch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCompletion and merged cleanup retain remote branches, including with force, because registration ownership cannot be proved after retirement. Retention is logged as a warning and displayed in both completion and merged-cleanup reports. Enable GitHubβs Automatically delete head branches setting for merged pull requests, or follow manual remote branch recovery.
Signals are evaluated in order β the first positive match short-circuits to avoid
unnecessary gh API calls. The gh CLI is a soft dependency: when it is not installed or
the remote is not GitHub, only git signals are used (NONE). When gh is there but fails
(auth, rate limit, unreadable output) the result is UNAVAILABLE, and the environment is
kept and reported rather than passed to the staleness sweep.
A multi-commit squash merge is invisible to both git signals, so PR state is the only
one that sees it. Both git signals also need the local branch ref: once it is gone, the
PR is the only judge, and a branch with no PR is reported as unverifiable instead of
failing the check. A MERGED or CLOSED PR only covers the commits it carried. Run
branch names are reused, and removal deletes both the worktree and the branch, so each
local tip that still exists, the worktreeβs HEAD and the branch ref, must be the PRβs head
commit or an ancestor of it (isRevCoveredBy). A detached HEAD or a reused branch with
commits past the PR head is unmerged work. The same holds when git proves the merge: the worktreeβs
HEAD must also pass git cherry <base> HEAD, which answers for both git signals (an
ancestor of the base lists nothing, a squash-merged commit lists as -). A HEAD it
cannot answer for is reported as a failed merge check. A PR head pushed from elsewhere and never fetched here is
fetched by SHA from the branchβs remote first; if that fetch fails, the check fails and
the worktree is kept, with the fetch error in the reason. The scheduled sweep (runScheduledCleanup) makes the same call, so
both paths agree on what counts as merged.
Code: packages/core/src/services/cleanup/ β judgeBranchForRemoval() in merge-verdict.ts, cleanupMergedWorktrees() in merged-sweep.ts, getCleanupRunLock() in run-lock.ts; runScheduledCleanup() in packages/core/src/services/cleanup-service.ts
Code: packages/isolation/src/pr-state.ts β getPrState()
Code: packages/git/src/branch.ts β isPatchEquivalent(), localBranchExists()
CLI Adapter
Section titled βCLI AdapterβImplements IPlatformAdapter for terminal output.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ CLIAdapter ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€β sendMessage(convId, msg) β Output to stdout ββ getStreamingMode() β 'batch' ββ getPlatformType() β 'cli' ββ ensureThread() β passthrough ββ start() / stop() β no-op ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCode: packages/cli/src/adapters/cli-adapter.ts:13-47
Key Dependencies
Section titled βKey Dependenciesβ| Function | Package | Location | Purpose |
|---|---|---|---|
discoverWorkflowsWithConfig(cwd, loadConfig, providerRegistry) | @archon/workflows/workflow-discovery | workflows/src/workflow-discovery.ts | Find and parse workflow YAML |
executeWorkflow(...) | @archon/workflows/executor | workflows/src/executor.ts | Run workflow steps |
getIsolationProvider() | @archon/isolation | isolation/src/factory.ts | Get WorktreeProvider singleton |
conversationDb.* | @archon/core | core/src/db/conversations.ts | Conversation CRUD |
codebaseDb.* | @archon/core | core/src/db/codebases.ts | Codebase CRUD |
isolationDb.* | @archon/core | core/src/db/isolation-environments.ts | Worktree tracking |
git.* | @archon/git | packages/git/src/ | Git operations |
closeDatabase() | @archon/core | core/src/db/connection.ts | Clean shutdown |
Conversation ID Format
Section titled βConversation ID FormatβCLI conversations use ID format: cli-{timestamp}-{random}
The random suffix contains 16 cryptographically random bytes encoded as 32 hex characters.
Generated at: packages/cli/src/utils/conversation-id.ts
Worktree Reuse Logic
Section titled βWorktree Reuse LogicβWhen --branch is provided:
- Lookup:
isolationDb.findActiveByWorkflow(codebaseId, 'task', branchName) - Health check:
provider.healthCheck(path)on existing - Reuse: If found and healthy (warns if
--fromwas specified but not applied) - Create: If not found or unhealthy β passes a
taskBranch: { kind: 'new', fromBranch }selection to the provider when--fromis specified. Adoption instead passestaskBranch: { kind: 'existing', branch }, which checks out that exact local branch without creating a child branch or syncing it to a remote.
Worktrees stored at: ~/.archon/workspaces/<owner>/<repo>/worktrees/<branch-slug>/
Code: provisionWorktree in packages/cli/src/commands/workflow-run-launch.ts
Exit Codes
Section titled βExit Codesβ| Code | Meaning |
|---|---|
| 0 | Success, except for the JSON control refusals noted below. |
| 1 | Error. Answer commands (answer, respond, approve, reject) and resume --detach also return 1 on refusal. Human-mode diagnostics go to stderr; JSON refusals emit ok: false with the reason on stdout. |
Non-detached JSON resume, abandon, and cancel can return 0 with ok: false.
Check ok when consuming those acknowledgments.
Database Connection
Section titled βDatabase Connectionβ- Connection opened on first database call
- Always closed in
finallyblock after command completes - Default: SQLite at
~/.archon/archon.db(zero setup, auto-initialized) - Optional: PostgreSQL when
DATABASE_URLis set (for cloud/advanced deployments)
Code: packages/cli/src/cli.ts
