Skip to content

Code architecture

This is a map of the code: which process does what, which package owns which responsibility, and which functions a command passes through. Read it before changing code you have not touched before.

It describes structure, not rules. The behavior that must be preserved (state layout, fallback chains, locking, path rules) is in contracts/README.md. User-facing behavior is in the README and the guides it links to.

Processes

Rotari is one binary, but at runtime it plays several roles. Knowing which process a piece of code runs in explains most of the structure.

flowchart LR
  subgraph clients["user shell"]
    runcli(["rotari run / retry"])
    waitcli(["rotari wait"])
    direct(["rotari add / copy / change / cancel<br/>show / jobs / export ..."])
    webcli(["rotari web<br/>(HTTP)"])
      mcpcli(["rotari mcp<br/>(stdio MCP)"])
  end
  subgraph sup["one per active run of a project"]
    supervisor["supervisor<br/>rotari __server<br/>executes the run's jobs"]
  end
  files[("&lt;basedir&gt;/projects/&lt;project&gt;/<br/>queue.json, meta.json, runs/..., .rotari-attachments/...")]
   nodes["wrapper scripts on<br/>Slurm / PBS / LSF / SGE / SSH nodes"]

  runcli -->|"starts as a child"| supervisor
  runcli -->|"request / acceptance over startup pipes"| supervisor
  runcli -->|"session, progress journal, summary"| files
  waitcli -->|"session, progress journal, summary"| files
  supervisor -->|read / write| files
  direct -->|"read / write under state lock"| files
  webcli -->|"read, edit queue"| files
   mcpcli -->|"read job report"| files
  nodes -->|write attempt status.json| files

   classDef command fill:#e0e7ff,stroke:#4f46e5,color:#1e1b4b
  class runcli,direct,webcli command
  • CLI client. Every rotari <command> invocation. Most commands (add, copy, change, show, jobs, export, ...) read and write the project files directly under the project's state lock. Only run and retry go through the supervisor; cancel, suspend, and resume signal jobs from the calling process, as the Web UI does.
  • Supervisor. rotari __server, started by run and retry through startSupervisor (cmd/rotari/server.go) for each run, and stopped when that run ends. The source still calls it the server. It serves one run of one project. Pipes inherited as descriptors 3 and 4 carry only the initial request and acceptance/rejection (including the accepted run ID); they are closed after that handoff. It holds a lease (server.lock, server.pid) in the project directory. Because it is a child of the run command, it and the run's jobs inherit that command's working directory and environment, which is why a supervisor is never reused (RUN-3 in contracts). It is not an authority for state: everything it knows is also on disk.
  • Run execution. Every run, sync or async, executes inside its supervisor; see Sync and async runs. Before execution, projectrun saves its coordinator identity (host, PID, PID namespace, and process start time) in the run's context.json, separate from the removable execution lock. It records successful management completion after finalization and lock cleanup, without treating that marker as process death. project.AssessCoordinator owns the read-only live/stopped/unknown assessment used by info, including when the run lock has disappeared. project.Unlock reuses it to gate recovery: live refuses, unknown requires explicit attestation, and stopped permits recovery. Execution probes run outside the state lock; unlock then reacquires it and compares a recovery fingerprint covering queue/meta and relevant run evidence before applying. CLI dry-run, MCP preview, and the Web's GET /api/unlock return the same policy evidence without mutation; CLI, MCP, Python, and the Web's Recover dialog (internal/webui/unlock.go) expose the attestation. Recovery authorization is recorded in the existing run context, without changing the coordinator record. project's repair.go validates summary completeness against expanded commands, carried origins/status marks and all relevant attempts. Unlock either finalizes matching interrupted metadata through state.FinalizeRun with the recorded finish time and applicable client cleanup, or explains a release to collecting. It never replays projectrun.Runner callbacks. Unknown executions require explicit attestation for repair; terminal records are not termination evidence. Expanded array origins use model.TaskOrigin, the same domain rule that run planning and model.Queue.OriginOf use; pinned and unpinned origins keep their respective attempt semantics. project.AssessExecutions reuses the repair inventory's job/attempt/origin traversal for read-only info. Executor-owned ExecutionProber classifies local groups, fresh scheduler queue/accounting observations using backend parsers, and SSH remote groups through a private per-attempt token. Local attempts durably publish host/PID namespace/start identity in job.json; incomplete publication stays unknown. Probes are bounded and rate-limited, with per-assessment SGE whole-queue caching. Verified active evidence blocks recovery even with attestation and terminal outcomes; stopped evidence removes execution attestation. Unknown/unsupported evidence remains explicit. Process-group and scheduler scopes are not machine-wide audits. SSH state is retained for 30 days and safely pruned only when no matching process group remains; the remote wrapper prunes in the background after its job has started, examining only expired state. Both finalization and ordinary release use the execution assessment; stale snapshots are rejected after lock reacquisition.
  • Web server. rotari web (cmd/rotari/web.go parses flags; internal/webui serves). It lists registered basedirs and lightweight project/run metadata, checks project locks across the selected basedir, and loads a project's queue and run summaries only when that project is opened. Job/attempt details load only for the selected run or active runs. The notification inbox reads the records runs left in the master directory (/api/notifications), not the run state. Beside the handlers, cmd/rotari/web.go runs runwatch.ReportInterrupted at startup and every 30 seconds, which records runs project.Inspect finds interrupted, since a killed run cannot. The dedicated history-search API scans only the user-selected basedir, project, and run scopes, or every registered basedir when asked for all, without expanding the lightweight /api/state index. The activity API (/api/activity) lists runs across every registered basedir through internal/runlist, as rotari runs does, for one bounded time range: runs outside it are skipped by run ID and directory time without being opened, and details are read for listed runs only. Expanding another basedir reads only its project directory names. Static export remains a complete snapshot. Its control endpoints (/api/copy, /api/cancel-job, ...) call the same internal operations as the CLI. With --allow-exec, it also starts the commands registered in the global launchers.toml through one internal/launcher manager (cmd/rotari/web_launch.go builds it; internal/webui/launches.go serves the API). Each launch runs under its own rotari __launch wrapper process, which holds the read end of a pipe only the Web server can write: when the Web server exits, even by SIGKILL, every wrapper stops its command's process group. A service launch listens on a loopback port the manager picks; once launcher.VerifyListener shows that the listener belongs to the launch and its readiness path answers, /_launch/ID/ (internal/webui/launch_proxy.go) forwards requests to it unchanged, checking ownership again for every new upstream connection. Launches are not runs: they take no project lock and write nothing under a basedir; their output lives in a private $TMPDIR/rotari-web-launches-* directory removed at shutdown, or by the next Web server if this one was killed. Open in VS Code, or another editor, runs nothing on the server: the page frame's web_editor.js opens a URL of the editor's scheme, from where the browser keeps which editor it uses and how that reaches this host, and /api/editor-target (internal/webui/editor.go) says where an artifact is; /api/log-links (internal/webui/log_links.go, which also finds the paths in shells' output) which paths in a job's log are files. With --allow-terminal, it holds shells in an internal/terminal Keeper (cmd/rotari/web_terminal.go builds it; internal/webui/terminal.go serves them at /_terminal/shells, /_terminal/here, and /_terminal/ws, groups them by project, by basedir for a basedir's own pages, or as of no project, and serves the panel's own window at /_terminal/window; /_terminal/projects says what each project with shells last ran, counted by the run page's Jobs card groups (jobCountGroup, in Go and JS alike); /_terminal/shells/ID/links which words of its output are run IDs, job IDs, or paths that exist, with a file's line (internal/webui/terminal_links.go); /_terminal/shells/ID/dirs the directories of its group's history and where its project's recent runs started (internal/webui/terminal_dirs.go); /_terminal/shells/ID/preview says where a shell is and what it runs, which internal/terminal finds from its process without attaching; the panel's Explorer lists a shell's directory or any other at /_terminal/files, changes, downloads, and uploads files under /_terminal/files/ through internal/fileops, (internal/webui/terminal_files.go) and opens files through /api/tableview-sources with a path). Pages only attach to shells, since each link reloads the page, and the panel in web_shell.js loads xterm.js when first opened and connects only to the tab shown. Its project link can be turned off per browser tab, keeping the terminal's selected group and pane layout across page loads and handing them to its separate window and back. A per-window identifier lets the window save that state in its opening tab's session storage even while the page reloads. On macOS, internal/terminal reads a foreground process's argument vector through kern.procargs2, keeping argument boundaries without starting ps for every output chunk. A shell is not a run: it takes no project lock and writes nothing under a basedir. With --detach (cmd/rotari/web_detach.go), the command checks its options, then starts itself again in a session of its own with its output in <masterdir>/web/<host>.log, and returns once that process reports its address on an inherited pipe. The background process holds the host's flock lease and writes <masterdir>/web/<host>.json; internal/webdetach finds, records, and compares detached servers and keeps the log bounded, and internal/lease holds and probes the lease for it and for the run supervisor's server.lock. At a terminal, or with --disconnect-action detach, rotari web is a client (cmd/rotari/web_client.go). It starts the server the same way, but with pipes for its output and a lifeline whose end the server watches, and stays attached. Ctrl-C asks the server to stop, and Ctrl-D asks it to detach: it takes the host's lease, records itself, and moves its output onto the log with dup3. A disconnect, or the lifeline closing however the client went, follows the disconnect action. Without a terminal, with the default action, rotari web serves in its own process. When a detached server runs with the options given, the client attaches to it instead (cmd/rotari/web_reattach.go): with no pipe to that server, it follows its log (webdetach.TailLog), watches its lease and record (webdetach.Ended), and stops it with SIGTERM on Ctrl-C. rotari web --shutdown (cmd/rotari/web_shutdown.go) finds that server the same way. It reads what its shells run from the process table (terminal.ServerShells), since it has no token to ask the server, then sends SIGTERM and waits for the lease. POST /_server/shutdown (internal/webui/shutdown.go) calls Options.Shutdown, which serveWeb wires to the same shutdown as SIGINT and SIGTERM.
  • Jobs and wrappers. Local jobs are child processes of the supervisor. Scheduler jobs run elsewhere through a generated wrapper script that writes the attempt's status.json, which the supervisor polls.

Sync and async runs

Both modes run the same lifecycle, projectrun.Runner.Run, inside the run's supervisor; they differ only in whether the client stays attached.

Sync run (rotari run) Async run (rotari run --async)
Client Enters the shared file-backed attachment/follower flow Returns after the startup acceptance
Process that executes the jobs The supervisor The supervisor
PID in running.lock The supervisor The supervisor
Entry point supervisor.Operations.Run (internal/supervisor/run.go) supervisor.Operations.StartRun, which runs Runner.Run in a goroutine
sync:   client ─request/accept─▶ supervisor: Begin → Run (Execute → Finish)
  └─ attachment session ──▶ progress journal / summary / controls
async:  client ─request/accept─▶ supervisor: Begin ──▶ "Run started" to client
                                     └─ Run (Execute → Finish), then the supervisor exits

The supervisor is started with setsid, detached from the client's terminal session, so a run keeps going when an async client returns or an attached client detaches with Ctrl-D. Synchronous run/retry and wait use the same post-start follower and session lifecycle. Each client has its own process-held lock and record under .rotari-attachments/; attachment state is derived from valid sessions, not a count or the legacy run-lock boolean. The supervisor checks sessions while the run executes. A same-host client death, including SIGKILL, releases its lock; Linux process start-time identity prevents a reused PID from being mistaken for the original process, and a suspended client keeps its lock. A remote host cannot be verified locally, so its session is conservatively treated as live. Unexpected disconnects detach by default; --disconnect-action cancel or ROTARI_DISCONNECT_ACTION=cancel asks the supervisor to cancel a run after it proves the client dead. Explicit Ctrl-C still cancels, Ctrl-D detaches, and Ctrl-Z suspends the client.

Both modes use the same progress observer. The supervisor records run-start, job-start, retry, failure, and completion-count events in the run's progress.jsonl, independently of the starting client's quiet setting, and clients read the journal after startup acceptance. Journaling is best-effort and does not determine execution or finalization. A colliding job ID disables journaling rather than changing the job's behavior; reader I/O failures warn and fall back to result-only waiting. rotari wait incrementally reads these events while waiting for the authoritative finalized summary and uses the same CLI progress renderer and cancellation boundary as synchronous run/retry. JSON wait omits text events but still holds an attachment while following an active run. See progress observer, journal I/O, and attachment sessions and the shared wait.

Because the filesystem is the shared medium, any process can die and the next one can reconstruct what happened from the files. That is why so much code takes a state.ProjectPaths and not an in-memory object.

Packages

Dependencies point one way: cmd/rotari imports every internal package, and no internal package imports cmd/rotari.

flowchart TB
  cmd["cmd/rotari<br/>CLI flags, wiring, output"]
   mcpadapter["internal/mcp<br/>MCP tools over shared packages"]
  projectrun["projectrun<br/>run lifecycle"]
  project["project<br/>state machine, idle edits"]
  resolve["resolve<br/>selectors to run and job"]
  queueops["queueops<br/>queue and history edits"]
  report["report<br/>diagnosis evidence"]
  bugreport["bugreport<br/>bug report bundle"]
  joblist["joblist<br/>recent jobs"]
  runwatch["runwatch<br/>interrupted runs for the inbox"]
  supervisor["supervisor<br/>server request work"]
  webui["webui<br/>Web handlers and assets"]
  launcher["launcher<br/>launched commands<br/>(imports nothing from rotari)"]
  tableview["tableview<br/>Table viewer reads<br/>(imports nothing from rotari)"]
  subgraph l2["orchestration and projections"]
    server
    run
    jobcontrol
    web
    jobstatus
    workflow
    queueedit
   runlineage
    diagnose
      jobfilter
      artifact
      artifactsource
  end
  subgraph l1["adapters"]
    executor
    state
    runregistry
    notificationlog
    stickies
    attachment
    config
  end
  model["model<br/>(imports nothing from rotari)"]

  cmd --> projectrun
  cmd --> project
  cmd --> resolve
  cmd --> queueops
  queueops --> project
  queueops --> resolve
  queueops --> queueedit
  queueops --> executor
  queueops --> state
  queueops --> jobstatus
  queueops --> attachment
  cmd --> report
  cmd --> bugreport
  bugreport --> report
  bugreport --> web
  bugreport --> executor
  bugreport --> config
  bugreport --> state
  cmd --> mcpadapter
   mcpadapter --> report
   mcpadapter --> resolve
   mcpadapter --> runview
   mcpadapter --> project
   mcpadapter --> state
   mcpadapter --> jobcontrol
  report --> web
  report --> project
  report --> diagnose
  cmd --> joblist
  joblist --> jobstatus
  joblist --> project
  cmd --> supervisor
  cmd --> attachment
  supervisor --> server
  supervisor --> attachment
  runview --> attachment
  supervisor --> projectrun
  supervisor --> jobcontrol
  cmd --> webui
  cmd --> launcher
  webui --> web
  webui --> queueops
  webui --> jobcontrol
  webui --> report
  webui --> joblist
  webui --> tableview
  config --> state
  resolve --> project
  resolve --> runregistry
  resolve --> state
  project --> jobstatus
  project --> executor
  project --> state
   run --> jobfilter
   queueedit --> jobfilter
   server --> jobfilter
  cmd --> l2
  projectrun --> run
  projectrun --> executor
  projectrun --> state
  projectrun --> jobstatus
  server --> executor
  run --> executor
  jobcontrol --> executor
  jobcontrol --> state
  jobcontrol --> jobstatus
   jobcontrol --> resolve
  web --> jobstatus
  web --> runview
  web --> diagnose
  web --> state
  jobstatus --> executor
  jobstatus --> state
  jobstatus --> jobfilter
  jobstatus --> diagnose
  workflow --> state
  artifactsource --> artifact
  projectrun --> artifactsource
  jobstatus --> artifact
  executor --> state
  runregistry --> state
  notificationlog --> state
  stickies --> state
  webui --> stickies
  webui --> notificationlog
  runwatch --> project
  runwatch --> notificationlog
  attachment --> state
  l1 --> model
  l2 --> model

Arrows mean "imports". cmd/rotari imports every internal package, and every package imports model; those edges are drawn once per group.

go list -f '{{.ImportPath}}: {{join .Imports " "}}' ./internal/... prints the current graph if this list drifts.

The boundary rules in contracts/00-overview.md are checked against this graph by internal/archtest.

Package Owns Start reading at
internal/model Domain types and pure rules: queue, queued command, job spec, result, summary, selections, command selectors, dependencies, arrays, and a failed result's failure kinds and the one cause failure summaries and --filter-failure-cause share. No I/O. model.go, selection.go, command_selector.go, dependencies.go, failure_cause.go (FailureCause)
internal/state The filesystem: path resolution and validation, JSON load/write, locks, run and attempt directory listing. A run's commands.json, summary.json, and carried.json are read together, once, as a RunSnapshot; a job's latest attempt is found with one listing (LatestAttempt); readers read independent runs and jobs with ReadEach, at most ReadConcurrency at a time. A basedir's projects are listed only by ProjectNames, which tells a missing basedir (ErrBaseDirMissing) from one without projects. Runs are ordered only by RunsNewestFirst, next to the run ID format (NewRunID, RunIDStart). Whether a recorded process can be observed from here is decided only by ObserveProcess and ObserveProcessGroup, from the platform facts PIDNamespace and ProcessStart (per-platform files: /proc on Linux, none and sysctl on macOS). No execution policy. paths.go, project_paths.go, store.go, lock.go, run_files.go (LoadRunSnapshot), read_each.go, project_names.go, run_order.go, process_identity.go, process_platform*.go
internal/executor How one job attempt is started, waited for, cancelled, and suspended: local processes, Slurm, PBS, LSF, SGE, SSH, wrapper scripts. No run semantics. contracts.go (JobExecutor), local.go, slurm.go, sge.go
internal/project A project's run state (idle, running, interrupted) from running.lock and meta.json, removing a stale local lock the one way every reader does (SAFE-11), one run's phase (running, interrupted, finished, ended) for wait and the MCP run summary, consistency checks, recovery, and the queue-edit sequence: state lock, state check, load, edit, then the queue write, preceded by the metadata write only while idle. The recovery commands it prints use a location renderer that CLI commands install (SetCommandLocation), so they omit an implicit --basedir (CLI-22). inspect.go (Inspect, InspectRunLock, EnsureIdle), run_phase.go (RunPhaseOf), edit.go (EditQueue, CreateQueueGuarded), reset.go (Reset), unlock.go (Unlock)
internal/resolve Location and job-name rules shared by the commands that read existing state: a run ID through the run registry, an att_ attempt ID, the latest-run fallback, run names, and job IDs or names looked up in the queue and latest runs, in one state directory or, for read-only commands without --basedir, across the default and registered ones. show's and wait's own selector orders build on it. resolve.go (ExistingRun, RunID, Jobs, JobIDsByName), scope.go (Scope)
internal/config Scope-aware global/cwd workspace/basedir/project discovery, location-key cycle validation, recursive file-value merging and immutable canonical TOML snapshots; YAML, TOML, JSON parsing. Runtime option meanings stay in cmd/rotari. layers.go (LoadScope, Load, Merge, Loaded.Snapshot), config.go
internal/notification notifications.toml: its schema, scope lookup, validation, serialization, and the shared job/run event and batch model used by both webhook and browser notifications, including the browser inbox text (NewBrowserMessage) and the event facts a record may keep (Event.Recordable). It also owns the Web UI basedir route (WebBaseDirID) that internal/webui serves and webhook links point to. Delivery stays in cmd/rotari (runNotificationManager batches a run's events for the Webhook and the record) and internal/webui. config.go (Load, Marshal), event.go (NewBatch), browser.go (NewBrowserMessage)
internal/notificationlog The master directory's notification records for the Web inbox, <masterdir>/notifications/<run-id>.jsonl, one file per run appended only by that run's process (and, once it stopped, one run.interrupted through AppendOnce), kept for 10 days, and the inbox's shared read/cleared cursors of each basedir (inbox-state.json). Entries renders records with each project's current browser settings for both the Web inbox and rotari notifications. Knows nothing of HTTP. log.go (Append, Records, Advance), entries.go (Entries)
internal/stickies The sticky notes users put on Web UI pages, <basedir>/stickies.json, a map from a page key (the Web UI route, an arbitrary string rather than a path) to that page's notes, saved atomically under a lock file with limits on notes, pages, and text. Independent of run notes and of every job, run, and result. Knows nothing of HTTP. stickies.go (Load, Save, Pages, Search)
internal/runwatch Finds runs whose coordinator stopped without finishing them, with the shared project.Inspect rule under the shared state lock, and records each once as run.interrupted through notificationlog.Log.AppendOnce; rotari web calls it on a timer. Inbox only, never the Webhook. runwatch.go (ReportInterrupted)
internal/runregistry The master directory's run index, <masterdir>/runs/<run-id>.json: register, look up, unregister, and find stale entries for gc. registry.go
internal/attachment Per-client run attachments: process-held locks, host and PID-start identity, attachment aggregation, stale-client policy handoff, initiating-client startup reservations, and removal of a deleted run's attachment state (ForgetRun, called by delete). It does not render CLI output. session.go
internal/projectrun One project's run against its files: Begin (context, command snapshot, run lock, registry, running metadata; consumes the queue only for queue-based runs), Execute (snapshot, plan, source revisions of the executed jobs, dispatch, summary), and Finish (final context, metadata finalization, lock removal). Saved-run snapshots are constructed under the project state lock without editing the next queue. Shared by sync and async runs and by cancellation. Also checks that a queue can run with the known executors (ValidateQueue). lifecycle.go, execute.go, plan.go, plan_revision.go (PlanRevision, the revision a run preview prints and a start checks), validate.go
internal/run Run rules without file access: which jobs execute or are carried forward, dependency unblocking, retries, per-executor lanes and concurrency, the summary contents. rerun.go (PlanRerun), engine.go (ExecuteJobs), dispatch.go (Dispatcher)
internal/jobstatus Read side: turns attempt files and the run's recorded results (the summary, or before it the carried results a run records at start) into one displayed result and timestamps, and reads the hosts, times, and log that job filters judge, and the artifact candidates an attempt recorded, following carried jobs to their attempt. Shared by CLI and Web. job.go (RecordedResults), attempt.go, times.go, facts.go, artifacts.go
internal/runview Read-side loading of a persisted run snapshot and resolution of each job's displayed status, a project's runs in start order, the run lifecycle and initiating-client connection projection, the one-run summary, and the failures with no retry left that wait --until-failure stops on. Shared by run comparison, history views, CLI status displays, the Web run lineage summary, and the MCP tools. run.go (LoadRun, LineageStatus), client.go (ClientStatus, RunLifecycleLabel), order.go (RunsByStart, Summary, FinalFailureGroups)
internal/supervisor The work behind supervisor requests: sync and async runs, including preflight selection planning. Implements server.Operations and returns plain-text messages; the completion message the client prints is built in cmd/rotari from the run's files. run.go (Operations.Run, StartRun)
internal/server Supervisor startup transport: request/acceptance types, inherited startup pipes, the lease and liveness check, and idle shutdown. The pipe is closed after run acceptance; ongoing progress and attachment are file-backed. Work is delegated to an Operations interface. protocol.go, serve.go, client.go, lease.go
internal/jobcontrol Cancel, suspend, resume of running jobs through executors. jobcontrol.go
internal/webui The Web UI: HTTP handlers and JSON API, static export, embedded assets, the auth wrapper and its narrow authentication-event interface, the launch API, its Host/Origin guard, the /_launch/ service proxy, and the Table viewer's page and API (/tableview/, TableViewHandler for rotari tableview, and GenerateStaticTableView for its static snapshot). CLI metadata, environment definitions, the config template, and the launcher manager come in through Options. webui.go (handler), auth.go (WithAuthToken), options.go, artifacts.go, artifact_files.go, launches.go, launch_guard.go, launch_proxy.go, table_view.go, table_view_static.go, table_view_shell.go (a terminal shell's directory, or a path from the Explorer, in the Table viewer), terminal.go and terminal_files.go (the terminal's routes and the Explorer's listing), assets/
internal/weblog Bounded Web server startup and authentication evidence under the master directory: allow-listed JSON Lines records, nonblocking delivery from requests, cross-process single-write appends, rotation, and event rate limits. Used by live rotari web and rotari tableview; static exports write nothing. log.go (Recorder)
internal/webdetach The one detached rotari web per user and host: its files under <masterdir>/web/ named by host, finding it through its lease (removing a crashed one's record), holding the lease and publishing its record (never the token), comparing a request's settings with its own, and its log's rotation at start and copy-and-truncate while it runs. Knows nothing of HTTP or of starting processes. webdetach.go (Find, Hold, Settings.Differences, OpenLog, KeepLogBounded)
internal/lease A process's flock claim on a file for its lifetime, and the non-blocking probe that reports a holder or an error, never a dead holder. Used by internal/server's supervisor lease and internal/webdetach. lease.go (Hold, TryLock, Probe)
internal/launcher Commands a user registered in launchers.toml and runs against an artifact from the Web UI: the file's schema and the StrictModes-style check that no other user can change it, the manager of one Web server's launches (start, reuse, stop, limits, rotating output), the rotari __launch wrapper that stops a launch's process group when the Web process exits for any reason, and the check that a service port belongs to the launch. Knows nothing of jobs, runs, or HTTP. manager.go (Manager), registry.go (LoadRegistry), wrapper.go (RunWrapper), listener.go (VerifyListener)
internal/terminal Interactive shells on pseudo-terminals: starting one in a session of its own with exactly the environment it is given, input, output, and resizing, and ending it when its terminal closes. Keeper holds up to a limit of shells, overall and per group, that outlive their attachments, each with recent output to replay, how much of it was taken before, and take-over by its newest attachment, a limit on how long they run with nothing attached to any of them, and each group's recent directories, read at a shell's prompt after Enter and kept only in memory. Knows nothing of jobs, runs, or HTTP. session.go (Start, Session), keeper.go (Keeper, Attachment)
internal/tableview What the Table viewer reads: delimited files split on a chosen separator, JSON Lines files, Markdown and supported source/config document kinds, or a directory's immediate children and explicitly expanded subdirectories as rows or as files grouped by stem, indexed once per version so a page is read from a nearby checkpoint, filtered, sorted, described, and paged, and properties of image, audio, video, and PDF files its cells name. Callers supply a Target, the file and the roots it may be read under; every file is opened through os.Root. Knows nothing of jobs, runs, or HTTP. target.go (Target, RootOf, MediaTypes), delimited.go, jsonl.go, table.go (Table), filter.go, describe.go, media.go (Probe), directory.go (OpenDirectory)
internal/fileops Changes to files for the terminal's Explorer: making a folder or an empty file, moving without replacing anything (renameat2 with RENAME_NOREPLACE on Linux) and never across file systems, copying a file or link (never a folder) with a name of its own beside it on request, removing, writing an upload under a temporary name renamed into place (WriteNew), and writing a folder as a zip while reading it (WriteZip). Every new name is one path element (CheckName). Knows nothing of jobs, runs, or HTTP. fileops.go (CheckName, Mkdir, CreateFile, Move, CopyFile, CopyName, Remove), transfer.go (WriteNew, WriteZip, ZipName), rename_linux.go, rename_other.go
internal/web JSON projections of runs, jobs, attempts, and timelines for the Web UI. loader.go
internal/queueops Queue and run-history edits shared by the CLI and Web UI: add, change, remove, copy, deleting runs or a whole project (DeleteProject), and adding notes to a run (AddNote). Loads and saves the files around internal/queueedit through the internal/project edit sequence, owns ValidateJobs, and builds saved-run command snapshots in memory for projectrun. editor.go (Editor), change.go, copy.go
internal/queueedit Pure queue edits, such as building a queue from an earlier run (copy, retry). copy.go
internal/workflow Workflow manifests: export merge and import reconciliation. manifest.go, export.go, reconcile.go
internal/workflowstate Applies workflow manifests to saved project state: reads saved runs as sources to reconcile a manifest, imports a manifest into the queue under a project.Guard, and loads a settled run for export. Shared by rotari import, rotari export, and the MCP import and export tools. import.go (Import.Apply), sources.go, export.go (LoadSettledRun)
internal/runlist Runs across state directories for rotari runs: which runs are listed, their lifecycle, client status, and order, as recorded values. runlist.go (Collect, Recent)
internal/joblist Recent job attempts across a base directory's projects for rotari jobs and the Web UI's jobs page: which attempts are listed, their order, and how their times read. joblist.go (Collect)
internal/report The redacted evidence report for AI-assisted diagnosis, shared by show --report and the Web UI. Reads jobs through internal/web's projection. report.go (Build)
internal/bugreport rotari bug-report: collects the executable identity, host, basedir filesystem and clock, registered basedirs, Web events, configuration, server.log, and a run's state files, job output, and scheduler queries (executor.ProbeSchedulerJob) into a Markdown summary or a .tar.gz bundle. Secrets are always removed; paths and hostnames unless asked not to. info and check results come from cmd/rotari as files. bugreport.go (Collect), environment.go, run.go, redact.go, tar.go (WriteTarGz)
internal/mcp MCP tools that rotari mcp (cmd/rotari/mcp.go) serves: read-only project list, run summary, bounded run wait, job report, project check, run comparison, and redacted run export, previewed, revision-guarded import and run start, job control of a running run, and previewed, revision-guarded reset/unlock. Run preview/start share source snapshot planning and report jobs omitted by a non-empty queue. They present the shared functions the CLI uses (project.Overviews, basedirregistry.Discover, runview.Summary, projectrun.Runner.Check, runlineage.Compare, report.Build, workflowstate.Import, projectrun.RunSource, projectrun.Runner.PreviewRun), locate runs only through the master directory's run registry (resolve.RegisteredRun), and return no absolute paths; every tool is added through addTool, which hides state directories in errors. Starting a supervisor and new job IDs come from cmd/rotari as Options; it does not import cmd/rotari. server.go (NewServer), tools.go, wait.go, export.go, write.go, control.go, reset.go, unlock.go
internal/runlineage Comparison and summaries of loaded runs for lineage, including whether each repository's code changed between two runs, and the grouping of a run's failures by cause that show, lineage, and the Web UI share. runlineage.go, failures.go (FailureGroups), sources.go (CompareSources)
internal/jobfilter The conditions of the --filter-* options that narrow a job selection, evaluated without file access; callers supply what a condition needs about each job, and an error when they cannot read it. filter.go (Filter, Selects)
internal/artifact Artifact candidate discovery: the one classifier that decides whether a command argument, environment value, or configuration string is a file or directory reference, with the accepting rule and provenance, the structural YAML/JSON/TOML walk of referenced configuration files, static inspection of shell code with mvdan.cc/sh, and lexical inspection of Python files. Reads no files; callers supply the job definition and a SourceReader. classify.go (Classify), command.go, discover.go (FromJob), config.go (Discover, ConfigReader), shell.go, python.go
internal/artifactsource The only file access of artifact discovery: reads a referenced configuration file if it is a regular file within the size limit, without blocking on FIFOs or devices, and caches each configuration file's parse and each script's contents per version for one run. read.go (Read), cache.go (Cache)
internal/sourcerev Reads the git or jj revision of the repository holding a directory, for the run's sources.json. A jj working copy is snapshotted first, so its commit ID covers uncommitted edits. Holds no run rules: projectrun chooses the directories. sourcerev.go (Read, ReadAll)
internal/diagnose Rule-based failure diagnosis. analysis.go
internal/archtest Tests only: the package boundary rules checked against the import graph. boundaries_test.go
internal/doclinks Tests only: relative links and #anchor links in the root Markdown files, contracts/, and docs/. links_test.go
conformance Tests only: contract checks against the built binary and the Web API, importing only the standard library and their own harness, conformance/support. Document-to-directory mapping is in layout.json; tests are being migrated under the matching contract groups. harness_test.go, contracts_test.go, layout.json

The interface flag-pair suites are split between 03-interfaces, pairedits, and pairruns, pairweb, and pairjobcontrol to keep each Go package within the default test timeout. They share the public-binary fixture, schema sampling, bounded subprocess invocation, and restored state through conformance/support/pairs.go. No pair is skipped in short or race mode.

Many internal functions take callbacks or hook fields (projectrun.Runner, run.BatchLaneCallbacks, run.OriginResults, server.Operations). This is how cmd/rotari supplies file access and output without the internal package importing it. When a callback's body is long, the logic probably belongs in an internal package.

Where does new code go?

  • Can it be explained without paths, files, or locks, and does it only define or validate rotari concepts? internal/model.
  • Does it read or write a file or directory layout? internal/state.
  • Does it decide the next execution step of a run? internal/run.
  • Does it start, record, or finish a project's run on disk? internal/projectrun.
  • Does it decide whether a project may be edited, or save an idle edit? internal/project.
  • Does it edit a project's queue or run history on disk for more than one interface (CLI, Web, supervisor)? internal/queueops, with the pure queue transformation in internal/queueedit.
  • Does it talk to a process or scheduler? internal/executor.
  • Does it decide what status a job shows? internal/jobstatus.
  • Does it decide which base directory, project, run, or job a selector names? internal/resolve.
  • Is it a Web handler, the static export, or a Web asset? internal/webui.
  • Does it start or stop a command the user registered for artifacts? internal/launcher.
  • Does it read, filter, or page what the Table viewer shows? internal/tableview; its page and API are internal/webui (table_view.go, and table_view_static.go for a static snapshot).
  • Is it flag parsing, message wording, or colors? cmd/rotari.

Files in cmd/rotari

Configuration loading in config.go stages global/workspace → basedir selection → basedir config → project selection → project config. config_selectors.go retains location provenance when file defaults meet registry selectors. init_workspace.go writes only cwd defaults. The run client passes captured file values through server.Request.FileConfig to projectrun.Start, so Begin writes the merged snapshot without reopening ordinary source files. Notification discovery/snapshots stay independent. Web options capture the startup workspace directory; current views select validated real sources and run views read saved snapshots.

cmd/rotari is the largest package. Each command has a cmdXxx function, dispatched from run in main.go.

Role Files
Entry and dispatch main.go
Flag metadata, help, config defaults, completion cli_spec.go, config.go, completion.go, schema.go, guide.go, environment.go
Queue editing (flags and output; add, change, copy, remove, delete, and note call internal/queueops) add.go, change.go, copy.go, remove.go, reset.go, delete.go, gc.go, unlock.go, note.go
Starting a run (client side; the supervisor side is internal/supervisor) run_command.go, job_executor.go
Default run registry wiring (registerRun, resolveRunLocation) run_registry.go
Wiring the run lifecycle (projectRunner) and its failure diagnosis project_run.go, diagnosis.go
Supervisor process wiring and its server registry server.go, registry.go
Read-only context, configuration, supervisor, and run overview (info) info.go
Bug report options, run selection, and the info and check facts it passes to internal/bugreport bug_report.go
basedirs, projects, and runs command flags and dispatch lists.go
stickies command and /api/stickies: sticky notes read (and, from the Web UI only, saved) through internal/stickies stickies.go
notifications command: recorded notifications rendered by notificationlog.Entries, as the Web inbox renders them notifications.go
Project discovery and list rendering (showProjectsForBaseDirs) projects.go
Registered basedir list rendering basedirs.go
Job control job_control.go, wait.go
Reading results show.go, show_artifacts.go, jobs.go, diff.go, check.go
Workflow manifests export.go, import.go, workflow_source.go
web command and the Web UI's CLI metadata (webOptions) web.go
web --allow-exec (launcher file, manager, token, allowed hosts) and config --launchers web_launch.go
tableview command (the Table viewer for one path) tableview.go
Notifications and terminal output webhook.go, webhook_batch.go, color.go, terminal*.go
Failures by cause, the completion message that run and wait print (formatRunCompletion), and the location options of printed next-step commands (hintLocation) failure_groups.go, run_completion.go, hint_location.go

Walkthroughs

rotari add

  1. cmdAdd (add.go) parses flags into model.QueuedCommand values.
  2. queueops.Editor.Add (internal/queueops/add.go) resolves state.ProjectPaths and calls project.EditQueue (internal/project/edit.go), which takes the state lock, checks the project is idle, loads queue.json, runs the callback that appends the new commands, and writes meta.json and then queue.json.

change, copy, and remove follow the same path through their queueops.Editor methods, and import through its own callback; delete uses project.Edit for the lock and idle check alone, and delete --project (Editor.DeleteProject) moves the project directory out of projects/ under the lock and removes it after. copy --to-project (Editor.CopyTo) reads the run from the source project and edits, or creates, the destination's queue under the destination's lock only. The Web UI and the supervisor call the same queueops.Editor methods.

No supervisor is involved.

rotari run

Client side, in run_command.go:

  1. cmdRun resolves the target project and, for --run-id, --failed, or --job-id, first repopulates the queue from an earlier run (queueops.Editor.Copy, backed by internal/queueedit). With --to-project, the request names the destination project and carries the source project in SourceProject; planning (projectrun.PlanRun) builds the snapshot from the source run with the selection already applied.
  2. startSupervisor starts a new supervisor for this run as a child process, so it inherits the command's working directory and environment, and waits for its ready message on the inherited pipes. It fails if the project already has one.
  3. Before a synchronous request it reserves a client session. It sends server.Request{Op: OpRun}; the server accepts once the run is committed and returns the run ID. It then closes the startup pipe and enters the same file-backed follower as wait. The async path reads its single start response and returns without attaching.

Supervisor side:

  1. server.Server.Handle (internal/server/serve.go) dispatches OpRun to supervisor.Operations.Run (sync) or StartRun (async) in internal/supervisor/run.go; server.go only builds the Operations.
  2. Run / StartRun share prepareRun: take the state lock, check the project is idle, and validate the queue. Then projectrun.Runner.Begin (internal/projectrun/lifecycle.go) writes context.json and the queue as runs/<run-id>/commands.json, takes the run lock (running.lock), registers the run, marks meta.json as running, and empties the queue, keeping its defaults.
  3. Runner.Run then executes the run in the supervisor. Both sync and async runs journal progress; a supervisor monitor checks bound client sessions and applies same-host disconnect cancellation when configured. Sync Run returns after execution while its startup response has already been sent; async StartRun answers once and continues in a goroutine. The supervisor stops once the run ends.

Execution, in Runner.Execute (internal/projectrun/execute.go):

  1. Load the run's commands.json, the queue Begin took, convert it to model.JobSpecs, and validate IDs and dependencies.
  2. Runner.PlanSelection → run.PlanRerun: decide which jobs execute and which results are carried from an earlier run.
  3. Rewrite runs/<run-id>/commands.json with fingerprint matches and carried origins.
  4. run.NewDispatcher builds one lane per executor with its own concurrency. run.ExecuteJobs (internal/run/engine.go) is the loop: start jobs whose dependencies are satisfied, collect results, retry, and stop if the project is being cancelled.
  5. Each lane calls the executor's Submit and Wait (internal/executor/contracts.go). The executor writes attempt files under runs/<run-id>/<job-id>/attempts/<attempt-id>/. The run discovers each attempt's artifact candidates (internal/artifact) when it assigns the attempt ID and writes them to the attempt's artifacts.json once the attempt has been submitted (artifactRecorder in internal/projectrun/artifacts.go).
  6. run.BuildRunSummary builds the summary, with diagnoses attached, and it is written to summary.json.

Finish, in Runner.Finish:

  1. Record the final load in context.json.
  2. Finalize finalizes meta.json (state.FinalizeRun) after checking that the run lock is still this run's, then reports the finished run to the notification hook, which flushes any pending job events with it: the batch is appended to the master directory's notification record and, when configured, sent to the Webhook.
  3. Remove the run lock.

rotari show and the Web UI

  1. cmdShow (show.go) or a Web handler (internal/webui) resolves the run and job directories through internal/state.
  2. Each job's outcome comes from internal/jobstatus (ReadJob, ResolveAttempt, Timestamps), which falls back from the attempt's status file to its wrapper status.json to summary.json.
  3. The CLI formats text; internal/web (loader.go) builds JSON for the browser.

Never read status files directly in a renderer; go through jobstatus so the CLI and Web UI agree.

rotari cancel

  1. cmdCancel (job_control.go) resolves the project, the run a run or attempt ID names, and the job IDs with resolve.JobSelection, and calls jobcontrol.Controller.Cancel in its own process.
  2. jobcontrol.Controller.Cancel (internal/jobcontrol/jobcontrol.go), which finds the running run through its run lock, rejects a named run that is not the active one, expands array job IDs to tasks, marks meta.json as cancelling for a whole-run cancel, and calls the executor's Cancel for each running job. For a job not submitted yet it writes a cancelled marker, then checks again whether the run has submitted it meanwhile.
  3. The run loop sees the cancelled results and the cancelling phase, and stops starting or retrying jobs. Once it has submitted a job, the dispatcher (Dispatcher.afterSubmit) cancels it if the phase or a marker shows that a cancel reached it during submission.
  4. With --wait, Cancel polls until the run lock is released, or for a job selection until each selected job has stopped (Controller.finishJobCancelMessage).

rotari mcp

rotari mcp (mcp.go) serves the MCP tools of internal/mcp over stdio. The user guide is docs/MCP.md, the rules are MCP-1 to MCP-7 in contracts/03-server-and-command-interfaces.md, and how the design was chosen is in the agent interface plan.

  • A presentation layer. Each tool calls the functions the CLI uses:
  • runview and runlineage for summaries and comparisons;
  • workflowstate for import and export;
  • projectrun to plan a run;
  • jobcontrol for cancel, suspend, and resume;
  • project.Reset for reset.

internal/mcp adds no selection, status, or grouping rule of its own, so a fix in a shared package reaches the CLI, the Web UI, and MCP together. What only the binary can do comes in as mcp.Options: starting a supervisor (startRunForMCP) and new job IDs. internal/mcp does not import cmd/rotari. - Add tools for demonstrated MCP-only gaps. Do not expose CLI commands or flags through MCP just for parity. Add a task-shaped tool when an MCP-only agent trial shows that an existing workflow cannot be completed, or takes disproportionate calls or output; otherwise, do not expand the MCP surface. Record the trial outcome and update the plan's shared behavior map when adding a capability. - Located through the master directory. A run is found by its ID in the run registry (resolve.RegisteredRun). A project is found by basedir_ref, a hash from the basedir registry, and its name. No tool takes or returns a path. Every tool is added through addTool, which replaces registered directories in error messages with BASEDIR. - Preview, then apply at a revision. Each tool that changes a project comes as a read-only preview and a write: - the preview returns project.Revision, a hash of queue.json and meta.json; - the write requires that revision and applies through the same project.Guard as the CLI's --dry-run / --if-revision, so it fails without effect if anything wrote the project in between.

Job control guards by run ID instead, because a running run's state changes continuously: it acts only while that run is the active one. The MCP client's per-tool permission is the approval. Previews are annotated read-only, and rotari_cancel and rotari_reset destructive. - Starting and following a run. rotari_start_run copies from the last run under the guard when projectrun.RunSource says to, then sends an async run request whose IfRevision the supervisor checks again before Begin. It returns the run ID. rotari_wait_run and rotari_run_summary read the run's state through project.RunPhaseOf, which rotari wait also uses. - Bounded, redacted output. Evidence lines and the export view are redacted by pattern, and the full manifest stays with rotari export. Summaries list 10 jobs per failure group, and comparisons list 20 changed jobs, unless all_jobs is set; the rest are counted.

Naming pitfalls

  • Project vs. queue. A project owns one queue, and much of the code still uses queue or QueueName for the project name (server.Request.QueueName, queueName variables). They mean the project.
  • Server vs. supervisor. The background coordinating process is called the supervisor in documentation, and server in code (internal/server, rotari server). The HTTP process is the Web server.
  • Import aliases. cmd/rotari imports internal/run as runcontract and internal/server as serverinternal, because run and server are already function names in package main.
  • Job vs. attempt. A job has a stable ID within a run; each execution of it (including retries) is an attempt with its own directory and an att_ ID.