Skip to content
Back to search

ntm

SkillWorks with Claude CodeGitHub

Run NTM for multi-agent tmux orchestration, work triage, robot mode, safety, coordination, and local APIs. Use when spawning swarms, dispatching work, or operating `ntm` as an agent or human operator.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 16 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Dicklesworthstone/ntm with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Dicklesworthstone/ntm'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dicklesworthstone--ntm/badge.svg)](/listings/dicklesworthstone--ntm)

HTML

<a href="/listings/dicklesworthstone--ntm"><img src="/api/listings/dicklesworthstone--ntm/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

Requirements

NTM is a pure Go project, but the runtime experience is intentionally integration-heavy.

- Required: `tmux` - Required for agent spawning: whichever CLIs you want to run, typically Claude Code, Codex, Antigravity CLI, Oh My Pi (`omp`), or Grok Build (Gemini CLI is supported as legacy) - Optional but powerful: `br`, `bv`, Agent Mail, `cass`, `dcg`, `pt` - Sanity check everything with `ntm deps -v`

First Session

# Install
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh?$(date +%s)" | bash -s -- --easy-mode

# Enable shell integration
eval "$(ntm shell zsh)"

# Verify tools and integrations
ntm deps -v

# Scaffold a project directory
ntm quick api --template=go

# Launch a mixed swarm
ntm spawn api --cc=2 --cod=1 --agy=1

# Open the live operator surfaces
ntm dashboard api
ntm palette api

# Dispatch work
ntm send api --cc "Map the auth layer and propose a refactor plan."

# If the repo uses br/bv, inspect the work graph
ntm work triage --format=markdown

# Save a recoverable checkpoint
ntm checkpoint save api -m "before auth refactor"

# Expose local APIs for dashboards, scripts, and agents
ntm serve --port 7337
ntm --robot-snapshot

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 335 lines · 1 finding marked
  1. ---
  2. name: ntm
  3. description: >-
  4. Run NTM for multi-agent tmux orchestration, work triage, robot mode, safety,
  5. coordination, and local APIs. Use when spawning swarms, dispatching work, or
  6. operating `ntm` as an agent or human operator.
  7. ---
  8. <!-- TOC: Quick Start | Session Orchestration | Dispatch & Reusable Assets | Reasoning Ensembles | Work Intelligence | Coordination | Safety | Robot Mode | Serve API | Project Resolution | References | Related Skills -->
  9. # NTM — Named Tmux Manager
  10. > **Core capability:** Turn `tmux` into a structured, recoverable multi-agent workspace.
  11. > **Read the repo first.** If the target repository has `AGENTS.md` or `README.md`, read those before applying this skill. Repo-local instructions override generic NTM advice.
  12. > **Interactive vs automation:**
  13. > - `ntm dashboard`, `ntm palette`, `ntm web`, and other TUI/web surfaces are for humans.
  14. > - For machine-readable automation, prefer `--robot-*`.
  15. > - Non-interactive CLI commands such as `ntm send`, `ntm work triage`, `ntm attention list`, `ntm locks list`, `ntm pipeline status`, and `ntm serve` are fine when they are the clearest tool.
  16. > **Coordination and isolation:**
  17. > - Agent Mail reservations are the default coordination primitive.
  18. > - `--worktrees` and `ntm worktrees ...` are supported isolation tools when the repo policy allows them.
  19. > - If a repo `AGENTS.md` prefers reservations-only or has worktree-specific rules, follow that repo.
  20. ## Quick Start
  21. ```bash
  22. # Install / sanity check
  23. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh?$(date +%s)" | bash -s -- --easy-mode
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 31 on GitHub
  24. ntm deps -v
  25. # Create or resolve a project
  26. ntm quick myproject --template=go
  27. # Launch a mixed swarm
  28. ntm spawn myproject --cc=2 --cod=1 --agy=1
  29. # Dispatch work
  30. ntm send myproject --cc "Map the auth layer and propose a refactor plan."
  31. # Inspect the current work graph and system state
  32. ntm work triage --format=markdown
  33. ntm --robot-snapshot
  34. ```
  35. ## Session Orchestration
  36. Use these for day-to-day session lifecycle management:
  37. ```bash
  38. ntm spawn myproject --cc=3 --cod=2 --agy=1
  39. ntm spawn myproject --grok=1 --omp=1 --oc=1
  40. ntm spawn myproject --label frontend --cc=2
  41. ntm spawn myproject --label backend --cc=2 --worktrees
  42. ntm add myproject --cc=1
  43. ntm add myproject --label frontend --cod=1
  44. ntm list
  45. ntm status myproject
  46. ntm view myproject
  47. ntm zoom myproject 3
  48. ntm attach myproject
  49. ntm dashboard myproject
  50. ntm palette myproject
  51. ntm web
  52. ```
  53. In `ntm palette`, target selection keys cover every built-in harness: `1-5` (All / Claude / Codex / Gemini / Antigravity), `7` Oh My Pi (`omp`), `8` Grok (`grok`), `9` OpenCode (`oc`), and `6` to pick individual agent panes.
  54. Useful spawn patterns:
  55. ```bash
  56. ntm spawn myproject --prompt "Read AGENTS.md and start on ready work"
  57. ntm spawn myproject -r full-stack
  58. ntm spawn myproject -t red-green
  59. ntm spawn myproject --persona=architect --persona=implementer:2
  60. ntm spawn myproject --stagger-mode=smart --cc=6 --cod=4
  61. ```
  62. Stagger defaults can live in config so every spawn paces prompts (flags win):
  63. ```toml
  64. [spawn]
  65. stagger_mode = "fixed" # none | fixed | smart
  66. stagger_delay = "90s" # 0-5m
  67. ```
  68. ## Dispatch and Reusable Assets
  69. High-leverage NTM usage is not just `spawn` plus `send`. The real power shows up when
  70. you combine richer dispatch patterns with reusable session and prompt assets.
  71. ```bash
  72. ntm send myproject --all "Checkpoint and summarize blockers."
  73. ntm send myproject --pane=2 "Own the auth migration."
  74. ntm send --project myproject "Sync to main and report conflicts."
  75. ntm send myproject -c internal/auth/service.go "Review this subsystem"
  76. ntm send myproject -t fix --var issue="nil pointer" --file internal/auth/service.go
  77. ntm send myproject --route=affinity "Take the auth follow-up in internal/auth/service.go"
  78. ntm send myproject --distribute --dist-strategy=dependency
  79. ntm recipes list
  80. ntm recipes show full-stack
  81. ntm workflows list
  82. ntm workflows show red-green
  83. ntm template list
  84. ntm template show refactor
  85. ntm session-templates list
  86. ntm session-templates show refactor
  87. ```
  88. User-level and project-level assets both matter. NTM can resolve configuration from
  89. `~/.config/ntm/...` and project-local `.ntm/...` trees, so check the repo before
  90. assuming defaults.
  91. ## Reasoning Ensembles
  92. Multi-mode reasoning ensembles are graduated into default NTM builds for structured diagnosis, adversarial review, synthesis, run comparison, and finding provenance:
  93. ```bash
  94. ntm modes list --tier core
  95. ntm ensemble suggest "What security issues exist in the auth layer?" --json
  96. ntm ensemble spawn myensemble --preset project-diagnosis --question "What are the main architectural risks?"
  97. ntm ensemble status myensemble --format=json
  98. ntm ensemble synthesize myensemble --format=json
  99. ntm ensemble compare myensemble-v1 myensemble-v2 --format=json
  100. ntm ensemble provenance --all --format=json
  101. ```
  102. ## Work Intelligence
  103. NTM is no longer just a pane launcher. It has first-class work selection and assignment:
  104. ```bash
  105. ntm work triage
  106. ntm work triage --by-track
  107. ntm work alerts
  108. ntm work search "JWT auth"
  109. ntm work impact internal/api/auth.go
  110. ntm work next
  111. ntm work graph
  112. ntm assign myproject --auto --strategy=dependency
  113. ntm assign myproject --beads=br-123,br-124 --agent=codex
  114. ```
  115. Use `ntm work ...` when you want NTM to wrap `bv` and present work in operator-friendly form.
  116. Use raw `bv --robot-*` when you specifically want the graph engine's native robot output.
  117. ## Coordination and Recovery
  118. NTM now exposes the surrounding coordination stack directly:
  119. ```bash
  120. ntm mail send myproject --all "Report blockers and current file focus."
  121. ntm mail inbox myproject
  122. ntm locks list myproject --all-agents
  123. ntm locks renew myproject
  124. ntm locks force-release myproject 42 --note "agent inactive"
  125. ntm coordinator status myproject
  126. ntm coordinator digest myproject
  127. ntm coordinator conflicts myproject
  128. ntm attention list --json
  129. ntm attention ack 42 --reason "investigating pane_2"
  130. ntm attention snooze 42 --until 30m --reason "waiting on build"
  131. ntm attention pin 42 --reason "release blocker"
  132. ntm attention dismiss 42 --reason "false alarm"
  133. ntm checkpoint save myproject -m "before risky refactor"
  134. ntm checkpoint list myproject
  135. ntm checkpoint restore myproject
  136. ntm timeline list
  137. ntm timeline show <session-id>
  138. ntm history search "authentication error"
  139. ntm audit show myproject
  140. ntm conflicts myproject
  141. ntm resume myproject
  142. ```
  143. `ntm locks force-release` is approval-gated by default (`automation.force_release: approval`): the first run files a durable approval request, a second operator grants it with `ntm approve <id>` (self-approval is rejected), and re-running the command consumes the approval and executes once. A solo operator can set `ntm policy automation --force-release auto` to allow unattended force-release.
  144. Treat `ntm checkpoint save` as a routine cadence, not just a pre-disaster snapshot. Good points to checkpoint: once prompts are confirmed received after a spawn or restore, after an investigation isolates a root cause, before risky edits, after significant uncommitted work but before verification, after a green verification, and before a merge/cleanup/handoff. Cheap checkpoints make any later `ntm checkpoint restore` land on a known-good state.
  145. Note that Agent Mail may run as an external MCP or service-manager process **outside** the tmux session. If Agent Mail and tmux appear to fail together, don't assume tmux took Agent Mail down — check the service manager, process/cgroup ancestry, and OOM/memory signals at the service boundary before relaunching workers.
  146. Isolation options:
  147. ```bash
  148. # Coordination-first
  149. ntm locks list myproject
  150. # Isolation-first when policy allows it
  151. ntm spawn myproject --cc=3 --worktrees
  152. ntm worktrees list
  153. ntm worktrees merge claude_1
  154. ```
  155. ## Safety and Approvals
  156. NTM has built-in safety, policy, and approval surfaces. Use them instead of ad hoc shell habits:
  157. ```bash
  158. ntm safety status
  159. ntm safety check -- git reset --hard
  160. ntm safety blocked --hours 24
  161. ntm safety install # also registers the Claude hook in ~/.claude/settings.json
  162. ntm policy show --all
  163. ntm policy validate
  164. ntm policy edit
  165. ntm policy automation
  166. ntm approve list
  167. ntm approve show abc123
  168. ntm approve abc123
  169. ntm approve deny abc123 --reason "wrong target branch"
  170. ```
  171. If the repo instructions require offloading builds or tests through another tool such as `rch`, obey the repo instructions.
  172. ## Canonical Robot Mode
  173. Start with these:
  174. ```bash
  175. ntm --robot-help
  176. ntm --robot-capabilities
  177. ntm --robot-status
  178. ntm --robot-snapshot
  179. ntm --robot-plan
  180. ntm --robot-dashboard
  181. ntm --robot-markdown --compact
  182. ntm --robot-terse
  183. ```
  184. Common task-specific robot surfaces:
  185. ```bash
  186. ntm --robot-spawn=myproject --spawn-cc=3 --spawn-prompt="Read AGENTS.md and start on ready work" --spawn-stagger-mode=fixed --spawn-stagger-delay=90s
  187. ntm --robot-send=myproject --msg="Summarize blockers." --type=claude
  188. ntm --robot-ack=myproject --timeout=30s
  189. ntm --robot-tail=myproject --lines=50
  190. ntm --robot-mail-check --mail-project=myproject --urgent-only
  191. ntm --robot-cass-search="authentication error"
  192. ntm --robot-beads-list --status=open
  193. ntm --robot-bead-claim=br-123 --bead-assignee=agent1
  194. ntm --robot-bead-close=br-123 --bead-close-reason="Completed"
  195. ntm --robot-ensemble=myensemble
  196. ntm --robot-ensemble-modes --tier=core
  197. ntm --robot-ensemble-presets
  198. ntm --robot-ensemble-suggest="What security issues exist?"
  199. ntm --robot-ensemble-synthesize=myensemble --synth-force
  200. ntm --robot-send=myproject --msg="Apply schema migration" --op-id=deploy-42
  201. ntm --robot-action-status=deploy-42
  202. ntm --robot-wait-request=deploy-42 --timeout=30s
  203. ntm --robot-cancel-request=deploy-42
  204. ntm --robot-handoff=myproject
  205. ntm --robot-handoff=myproject --handoff-create --handoff-goal="Implemented auth" --handoff-now="Run E2E suite"
  206. ntm --robot-handoff=myproject --handoff-create --handoff-auto
  207. ntm --robot-analytics
  208. ntm --robot-analytics --analytics-days=7 --analytics-sessions
  209. ntm --robot-analytics --analytics-since=2026-01-01
  210. ntm --robot-audit=myproject --audit-verify
  211. ntm --robot-audit --audit-search=spawn --audit-days=7
  212. ntm --robot-timeline=myproject --timeline-events
  213. ntm --robot-timeline --timeline-stats
  214. ntm --robot-doctor --doctor-contention
  215. ntm --robot-preflight="fix the bug in auth.go" --preflight-strict
  216. ntm audit http --limit=20 --json
  217. ```
  218. `--spawn-prompt` (or `--spawn-prompt-file`) waits for readiness, then reaches
  219. each agent through robot send's dispatch path; the JSON reports the
  220. `stagger.schedule[]` (per-agent `delay_ms`/`scheduled_at`) and
  221. `prompt_deliveries[]` (per-agent `prompt_sent`/`delivered_at`). The same
  222. `--spawn-stagger-*` flags pace `--spawn-assign-work` prompts.
  223. Operator loop:
  224. ```text
  225. 1. Bootstrap with --robot-snapshot
  226. 2. Tend with --robot-attention or --robot-wait
  227. 3. Act with --robot-send, ntm send, ntm assign, ntm locks, or ntm mail
  228. 4. Re-bootstrap with --robot-snapshot if the cursor expires
  229. ```
  230. Prefer `--robot-*` when another agent or script needs structured output.
  231. ## Serve API and Pipeline Surfaces
  232. NTM also exposes the embedded web cockpit, local REST/SSE/WebSocket API, and durable workflow surfaces:
  233. ```bash
  234. ntm web
  235. ntm serve --port 7337
  236. ntm openapi generate
  237. ntm pipeline run .ntm/pipelines/review.yaml --session myproject
  238. ntm pipeline status run-20241230-123456-abcd
  239. ntm pipeline list
  240. ntm pipeline resume run-20241230-123456-abcd
  241. ntm pipeline cleanup --older=7d
  242. ```
  243. `ntm web` mounts the embedded browser cockpit at `http://127.0.0.1:7337` alongside the REST/SSE/WebSocket API and live OpenAPI 3.1 spec at `http://127.0.0.1:7337/api/v1/openapi.json`. Use `ntm serve` for headless local integrations, and `--robot-*` for single-shot agent control.
  244. ## Project Resolution
  245. `ntm spawn` needs a project directory that NTM can resolve.
  246. ```bash
  247. ntm config get projects_base
  248. ntm quick myproject --template=go
  249. # Or point projects_base at an existing repo layout / create a symlink when needed
  250. ```
  251. The session name usually matches the project directory name. Labels extend the session name as `project--label`.
  252. ## Reference Index
  253. Read these when you need deeper detail without bloating the main skill body:
  254. | Topic | Reference |
  255. | --- | --- |
  256. | High-leverage command patterns, output capture, monitoring, reusable assets | [COMMANDS.md](references/COMMANDS.md) |
  257. | Attention feed, robot output formats, wait conditions, mail/cass/bead robot flows | [ROBOT-MODE.md](references/ROBOT-MODE.md) |
  258. | Human dashboard, palette, keybindings, and TUI implementation notes | [DASHBOARD.md](references/DASHBOARD.md) |
  259. | Project resolution, `projects_base`, config paths, and project-local assets | [CONFIG.md](references/CONFIG.md) |
  260. ## Related Skills
  261. - `agent-mail` for inboxes, contact handshakes, and file reservations
  262. - `br` for bead state changes and syncing
  263. - `bv` for graph-aware task prioritization
  264. - `cass` for prior-session retrieval
README.md · README · 2,050 lines · 4 findings marked
  1. # NTM - Named Tmux Manager
  2. <div align="center">
  3. <img src="ntm_dashboard.webp" alt="NTM dashboard">
  4. </div>
  5. <div align="center">
  6. ![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-blue.svg)
  7. ![Go Version](https://img.shields.io/badge/go-1.26.10+-00ADD8.svg)
  8. ![License](https://img.shields.io/badge/License-MIT%2BOpenAI%2FAnthropic%20Rider-blue.svg)
  9. ![Release](https://img.shields.io/github/v/release/Dicklesworthstone/ntm?include_prereleases)
  10. </div>
  11. NTM turns `tmux` into a local control plane for multi-agent software development.
  12. It combines session orchestration, graph-aware work triage, safety policy and approvals,
  13. Agent Mail coordination, durable state capture, machine-readable robot surfaces, and a
  14. local REST/WebSocket API in one Go binary.
  15. <div align="center">
  16. ```bash
  17. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh?$(date +%s)" | bash -s -- --easy-mode
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 24 on GitHub
  18. ```
  19. </div>
  20. ## TL;DR
  21. ### The Problem
  22. Running several coding agents in parallel is easy to start and annoying to sustain.
  23. Plain `tmux` gives you panes, but it does not give you durable coordination, work
  24. selection, safety policy, approvals, history, replayable automation surfaces, or a
  25. shared control model that both humans and agents can use.
  26. ### The Solution
  27. NTM gives you a single local system for:
  28. - spawning labeled multi-agent sessions in `tmux`
  29. - sending work, interrupts, and follow-ups across panes
  30. - triaging what to do next with `br` and `bv`
  31. - coordinating agents with Agent Mail, file reservations, and assignments
  32. - protecting dangerous operations with policy, approvals, and guards
  33. - exposing the whole system through `--robot-*`, REST, SSE, WebSocket, and OpenAPI
  34. - capturing state with checkpoints, timelines, audit trails, and pipeline state
  35. ### Why NTM
  36. | Area | What NTM provides | Typical commands |
  37. | --- | --- | --- |
  38. | Session orchestration | Spawn, label, inspect, zoom, dashboard, palette | `ntm spawn`, `ntm dashboard`, `ntm palette` |
  39. | Work intelligence | Graph-aware triage, next-step selection, impact analysis, assignment | `ntm work triage`, `ntm work next`, `ntm assign` |
  40. | Coordination | Human overseer mail, inbox views, file reservations, worktrees | `ntm mail`, `ntm locks`, `ntm worktrees` |
  41. | Safety | Destructive-command protection, policy editing, approval workflows | `ntm safety`, `ntm policy`, `ntm approve`, `ntm guards` |
  42. | Durable operations | Checkpoints, timelines, audit logs, saved sessions, pipelines | `ntm checkpoint`, `ntm timeline`, `ntm audit`, `ntm pipeline` |
  43. | Automation surfaces | Robot JSON, REST API, SSE/WebSocket streams, OpenAPI | `ntm --robot-snapshot`, `ntm serve`, `ntm openapi generate` |
  44. ## Quick Start
  45. ### Requirements
  46. NTM is a pure Go project, but the runtime experience is intentionally integration-heavy.
  47. - Required: `tmux`
  48. - Required for agent spawning: whichever CLIs you want to run, typically Claude Code, Codex, Antigravity CLI, Oh My Pi (`omp`), or Grok Build (Gemini CLI is supported as legacy)
  49. - Optional but powerful: `br`, `bv`, Agent Mail, `cass`, `dcg`, `pt`
  50. - Sanity check everything with `ntm deps -v`
  51. ### First Session
  52. ```bash
  53. # Install
  54. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh?$(date +%s)" | bash -s -- --easy-mode
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 76 on GitHub
  55. # Enable shell integration
  56. eval "$(ntm shell zsh)"
  57. # Verify tools and integrations
  58. ntm deps -v
  59. # Scaffold a project directory
  60. ntm quick api --template=go
  61. # Launch a mixed swarm
  62. ntm spawn api --cc=2 --cod=1 --agy=1
  63. # Open the live operator surfaces
  64. ntm dashboard api
  65. ntm palette api
  66. # Dispatch work
  67. ntm send api --cc "Map the auth layer and propose a refactor plan."
  68. # If the repo uses br/bv, inspect the work graph
  69. ntm work triage --format=markdown
  70. # Save a recoverable checkpoint
  71. ntm checkpoint save api -m "before auth refactor"
  72. # Expose local APIs for dashboards, scripts, and agents
  73. ntm serve --port 7337
  74. ntm --robot-snapshot
  75. ```
  76. ## Core Workflows
  77. ### 1. Multi-Agent Session Orchestration
  78. NTM is built around named `tmux` sessions with explicit agent panes and a user pane.
  79. It handles session naming, pane layout, agent startup, labels, and inspection so you
  80. can treat a swarm like a manageable unit instead of a pile of terminals.
  81. ```bash
  82. ntm quick payments --template=go
  83. ntm spawn payments --cc=3 --cod=2 --agy=1
  84. ntm add payments --cc=1
  85. ntm list
  86. ntm status payments
  87. ntm view payments
  88. ntm zoom payments 3
  89. ntm attach payments
  90. ```
  91. A bare `--cc=N` passes no `--model`, so Claude Code starts with its own default
  92. or saved model and context setting. Pin one with `--cc=N:MODEL` (the built-in
  93. aliases `opus`, `sonnet`, and `haiku` pass Claude Code's own family aliases,
  94. which track the newest model) or set `[models] default_claude` in
  95. `~/.config/ntm/config.toml`; `default_claude = ""` restores the delegate
  96. behaviour.
  97. #### Grok Build
  98. NTM recognizes the official xAI Grok Build CLI as the canonical `grok` agent
  99. type. Install it using [xAI's current instructions](https://docs.x.ai/build/overview),
  100. then authenticate without putting credentials in NTM configuration:
  101. ```bash
  102. curl -fsSL https://x.ai/cli/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 141 on GitHub
  103. grok login # browser authentication
  104. grok login --device-auth # SSH/headless alternative
  105. ntm deps -v
  106. ```
  107. A bare spec delegates model selection to Grok Build. Use `grok models` to inspect
  108. the models available to the authenticated account, then pass an exact model ID
  109. only when an override is needed:
  110. ```bash
  111. ntm spawn research --grok=1
  112. ntm spawn research --grok=1:MODEL_ID
  113. ntm spawn research --grok=1:MODEL_ID:EFFORT
  114. ntm --robot-spawn=research --spawn-grok=1
  115. ```
  116. NTM launches Grok Build with its official `--always-approve` automation flag.
  117. Phase 2 (GH#251) implements the interactive TUI protocol against live Grok Build
  118. captures: readiness and working-state detection, composer-gated and
  119. submission-verified prompt delivery (send, assign, `--robot-spawn --spawn-wait`
  120. and `--spawn-assign-work`), interrupt, restart, and restore-time relaunch. The
  121. one deliberate refusal is personas: the Grok Build CLI has no system-prompt
  122. flag or environment variable, so a persona on a Grok agent fails the launch
  123. instead of being silently dropped.
  124. #### Oh My Pi (`omp`)
  125. NTM operates [Oh My Pi](https://omp.sh) as the built-in `omp` agent type (panes
  126. are named `session__omp_N`; `oh-my-pi` is accepted as an alias). Finish omp's
  127. own setup once before the first spawn, otherwise the first prompt lands in the
  128. setup wizard:
  129. ```bash
  130. omp setup
  131. ntm deps -v # probes the omp binary
  132. ntm spawn swarm --omp=8 # omp picks its default model
  133. ntm spawn swarm --omp=2:MODEL # pins MODEL (omp fuzzy-matches it)
  134. ntm spawn swarm --omp=2:MODEL:high # also sets the thinking level (or MODEL@high)
  135. ntm add swarm --omp=1
  136. ntm adopt swarm --omp=1,2,3 # adopt existing omp panes
  137. ntm --robot-spawn=swarm --spawn-omp=8 --spawn-wait
  138. ntm send swarm --omp "Run the test suite and report failures"
  139. ```
  140. The launch command is `omp --auto-approve`, plus `--model`, `--thinking`, and
  141. `--append-system-prompt <file>` (personas) when requested. Override it with
  142. `[agents] omp = "..."` (a template; keep `{{.ReasoningEffort}}` if you want
  143. effort specs honoured, otherwise NTM rejects them rather than dropping them),
  144. set `[models] default_omp` or `[models.omp]` aliases, and `[prompts]
  145. omp_default`. `[spawn_pacing.agent_caps] omp_max_concurrent` (default 8) is
  146. omp's share of the host-wide agent budget robot spawn admission enforces
  147. (running plus requested agents may not exceed the sum of all agent caps);
  148. launches are never serialized per type, and the default admits a full
  149. `--spawn-omp=8` swarm alongside the default Claude/Codex/Gemini budget.
  150. Everything NTM does to an omp pane is derived from omp's live TUI (v18.2.3,
  151. across its nerd, unicode and ascii symbol presets):
  152. - **Ready / working / idle.** omp keeps a bordered composer at the bottom of the
  153. pane. A turn in flight shows a spinner and elapsed timer in the composer's top
  154. border (`╭── ⠧ 1s`), an Esc-hint activity line above it (`⎋ Working…` or an
  155. intent label), a queued `Steering · N` block, or a ` Subagents` panel listing
  156. running subagents. A ` TODO` tree alone is not read as working, since a plan
  157. can outlive its turn. A quiet composer with nothing below it is idle.
  158. - **Delivery.** Enter submits. A message sent to a busy pane is queued by omp
  159. as steering; delivery is confirmed when the payload leaves the composer. A
  160. staged large paste (`#1` token) is reported by `--robot-dialogs` as paste
  161. limbo and cleared with Ctrl+C.
  162. - **Interrupt and exit.** omp interrupts on **Escape** (Ctrl+C only clears the
  163. draft, and a double Ctrl+C quits), so `ntm interrupt`, `--robot-interrupt`,
  164. restart, and the REST interrupt send Escape to omp panes. Graceful exit is
  165. Escape, Ctrl+C, then Ctrl+D.
  166. - **Context.** `--robot-context`, `--robot-snapshot`, `ntm status`, and the
  167. coordinator's context-rotation trigger read omp's own context gauge from the
  168. composer border (`7%` … `262K`), reported as `source: "status_bar"`, so the
  169. reading stays per-pane even when many omp panes share one directory. Compaction
  170. uses native `/compact` and verifies a fresh reduction in the context gauge.
  171. - **Sessions.** `ntm sessions save` binds each pane to its omp session (omp
  172. holds its transcript under `~/.omp/agent/sessions/` open, so the binding is
  173. exact per pane; profile, XDG and `PI_CODING_AGENT_*` stores are honoured), and
  174. resume relaunches with `omp --auto-approve --resume <id>`.
  175. - **Errors.** A failed turn leaves a provider-error block framed by rules
  176. directly above the quiet composer (`server_error: ERROR`, `401 Invalid API
  177. Key`, then `Dismissed when you send your next message.`). NTM reports it as
  178. an error, never as idle-after-completion: `--robot-is-working` returns
  179. `ERROR_STATE` with `indicator_basis: "provider_error"` and a retry hint, the
  180. status observation and coordinator report an error (`auth` for 401/403,
  181. otherwise generic), and assignment will not feed the pane new work. An
  182. `F5 to Retry` hint may sit between the block and the input box. Press `F5`
  183. (omp's retry key) to re-run the failed turn, or send any message, such as a
  184. continue prompt, which dismisses the block and retries.
  185. `Error: No model selected.` is an error too. No omp rate-limit screen has
  186. been captured yet, so omp panes are never marked rate-limited from
  187. transcript text; a provider 429 surfaces as a provider error.
  188. - **Quota.** omp has no quota or usage command. `ntm quota` lists omp panes as
  189. "no quota API (provider-error classification)", `ntm rotate all-limited`
  190. skips them with that reason, and `--robot-quota-check --provider=omp` answers
  191. `NOT_IMPLEMENTED` (exit 2) naming the same fallback.
  192. - **Palette, assignment, boot checks.** In `ntm palette`, key `7` targets omp
  193. panes (`6` still picks individual agents). `--assign` scores omp with the
  194. per-task midpoint of the Claude and Codex capability profiles, since omp's
  195. strengths follow whichever model it runs. `--verify-boot` counts a pane as
  196. booted when it is idle, or when it received a spawn prompt (recovery context,
  197. CASS context, or your prompt) and is working on it.
  198. #### OpenCode (`oc`)
  199. [OpenCode](https://opencode.ai) panes are named `session__oc_N`. The model is
  200. OpenCode's `provider/model` form; with no model, OpenCode uses its own default.
  201. ```bash
  202. ntm spawn swarm --oc=2 # OpenCode picks its default model
  203. ntm spawn swarm --oc=2:opencode/big-pickle # pins the model
  204. ntm add swarm --oc=1
  205. ntm --robot-spawn=swarm --spawn-oc=2:opencode/big-pickle --spawn-wait
  206. ntm send swarm --oc "Run the test suite and report failures"
  207. ```
  208. The launch command is `opencode --model <model>`. There is no effort knob: the
  209. TUI has no `--variant` flag (only `opencode run` does), so an effort in the
  210. spec is ignored. Override the command with `[agents] oc = "..."` (a template;
  211. keep `{{if .Model}} --model {{shellQuote .Model}}{{end}}` if you want model
  212. specs honoured), and set `[models] default_opencode` or `[models.opencode]`
  213. aliases. Prompts are delivered with bracketed paste and verified against the
  214. composer: a prompt the TUI drops fails the send instead of reporting success.
  215. **Unattended panes and permissions.** OpenCode asks before actions its
  216. permission config marks `ask` (by default this includes paths outside the
  217. project, `external_directory`). With nobody at the pane, the request is
  218. auto-rejected and the turn stops. Two ways to pre-approve:
  219. - Launch with `--auto` (OpenCode 1.18.0+), which approves every request that
  220. is not explicitly denied, for that pane only:
  221. ```toml
  222. [agents]
  223. oc = "opencode --auto{{if .Model}} --model {{shellQuote .Model}}{{end}}"
  224. ```
  225. `deny` rules still apply, so you can pair `--auto` with deny rules for
  226. anything a pane must never do.
  227. - Set OpenCode's own `"permission"` config. It is global for every OpenCode
  228. session that reads it, not per pane: `~/.config/opencode/opencode.json`, a
  229. project `opencode.json`, or the `OPENCODE_CONFIG` /
  230. `OPENCODE_CONFIG_CONTENT` environment variables. Each key takes `allow`,
  231. `ask` or `deny`, and `"permission": "allow"` sets them all at once:
  232. ```json
  233. {
  234. "$schema": "https://opencode.ai/config.json",
  235. "permission": {
  236. "edit": "allow",
  237. "bash": "allow",
  238. "external_directory": { "~/shared/fixtures/**": "allow" }
  239. }
  240. }
  241. ```
  242. Path patterns support `*`, `?` and a leading `~`. Use `**` to cover a
  243. directory tree: OpenCode may check the parent directory's glob rather than
  244. the exact path it touches, so a pattern for one leaf directory can still be
  245. rejected.
  246. Use labels when you want multiple coordinated swarms on the same project while
  247. keeping a shared project directory:
  248. ```bash
  249. ntm quick payments --template=go
  250. ntm spawn payments --label backend --cc=2 --cod=1
  251. ntm spawn payments --label frontend --cc=2
  252. ntm add payments --label frontend --cc=1
  253. ```
  254. #### Staggered prompts (thundering-herd prevention)
  255. When several agents boot together and all pick work from `bv`/`br` at once,
  256. they race for the same bead. Stagger their initial prompts so each agent has
  257. claimed something before the next one starts looking:
  258. ```bash
  259. ntm spawn payments --cc=3 --prompt="Read AGENTS.md, then pick ready work" --stagger-mode=fixed --stagger-delay=90s
  260. ntm spawn payments --cc=5 --prompt="..." --stagger-mode=smart # learned rate-limit spacing
  261. ntm --robot-spawn=payments --spawn-cc=3 --spawn-prompt="Read AGENTS.md, then pick ready work" \
  262. --spawn-stagger-mode=fixed --spawn-stagger-delay=90s
  263. ```
  264. The agent at position `i` receives its prompt `i × interval` after the first.
  265. `--robot-spawn --spawn-prompt` (or `--spawn-prompt-file`, `-` for stdin)
  266. waits for readiness, delivers through robot send's dispatch path, and reports
  267. `stagger.schedule[]` and per-agent `prompt_deliveries[]`; the same
  268. `--spawn-stagger-*` flags pace `--spawn-assign-work` prompts. Set defaults for
  269. both commands in `~/.config/ntm/config.toml` (flags still win):
  270. ```toml
  271. [spawn]
  272. stagger_mode = "fixed" # none (default), fixed, or smart
  273. stagger_delay = "90s" # fixed-mode interval, 0-5m (default 30s)
  274. ```
  275. #### Worktree isolation and reservations
  276. Use `--worktrees` when agents need independent Git checkouts as well as separate
  277. tmux panes. NTM creates one `ntm/<session>/<agent>` branch and worktree per
  278. agent, so filesystem changes and destructive Git operations stay isolated until
  279. you deliberately merge them:
  280. ```bash
  281. ntm spawn payments --cc=3 --worktrees
  282. ntm worktrees list
  283. ntm worktrees merge cc_1
  284. ntm worktrees clean --session payments
  285. ```
  286. Worktrees do not replace Agent Mail reservations. Continue to reserve the files
  287. or areas an agent owns: reservations communicate intent, reduce merge conflicts,
  288. and give operators an auditable ownership record; worktrees provide the separate
  289. checkout boundary. Merge reviewed agent branches into `main`, then clean the
  290. session's worktrees when that session is finished.
  291. Reservations are enforced at commit time: the pre-commit hook `ntm init`
  292. installs runs `ntm guards check --staged`, which refuses a commit touching files
  293. another agent holds an exclusive reservation on and names the holder (when Agent
  294. Mail is unreachable it warns and records a degraded run for `ntm doctor`; set
  295. `NTM_GUARD_STRICT=1` to fail closed). `ntm guards install` adds the check to a
  296. repository without that hook, or updates an older `ntm init` hook in place.
  297. ### 2. Dispatch, Monitoring, and Recovery
  298. Humans can broadcast prompts, interrupt panes, stream output, inspect health, compare
  299. responses, search pane history, and keep an eye on activity without dropping to raw
  300. `tmux` commands.
  301. ```bash
  302. ntm send payments --all "Checkpoint and summarize current progress."
  303. ntm interrupt payments
  304. ntm activity payments --watch
  305. ntm health payments
  306. ntm watch payments --cc
  307. ntm extract payments --lang=go
  308. ntm diff payments cc_1 cod_1
  309. ntm grep "timeout" payments -C 3
  310. ntm analytics --days 7
  311. ```
  312. Pending context rotations can be acted on directly:
  313. ```bash
  314. ntm rotate context pending
  315. ntm rotate context confirm payments__cc_1 --action=rotate
  316. ntm rotate context confirm payments__cc_1 --action=compact
  317. ```
  318. CLI and dashboard confirmation execute the selected action and report its actual
  319. result. Rotation verifies the original process, requests a fresh handoff, and
  320. delivers it to a ready replacement before retiring the old pane. Confirmation
  321. ownership and results survive process interruption: repeating a completed choice
  322. returns its saved result, while a failed or interrupted choice remains visible in
  323. `pending`. The pending output identifies the execution, both physical panes, the
  324. handoff phase, and the available recovery actions. Inspect the affected panes
  325. before using the indicated retry or recovery action.
  326. Rotation transfers the existing task, Agent Mail identity, file reservations, and
  327. restart configuration to the replacement. Both panes are fenced against new task
  328. dispatch and automatic restarts while ownership is being transferred; existing
  329. reservation leases continue to renew. If an accepted handoff is interrupted during
  330. ownership transfer, `--retry` finishes that transfer without launching another
  331. agent or resending the handoff. When handoff delivery is uncertain, the pending
  332. record and pane fences remain in place for inspection, and retry or ignore cannot
  333. silently discard that unresolved state.
  334. Resolve an interrupted rotation with an explicit operator decision:
  335. ```bash
  336. ntm rotate context pending --json
  337. ntm rotate context recover payments__cc_1 --execution-id=EXECUTION_ID \
  338. --action=accept --reason="Replacement is working on the handed-off task"
  339. # Alternatively, stop the replacement and keep the original agent:
  340. ntm rotate context recover payments__cc_1 --execution-id=EXECUTION_ID \
  341. --action=abort --reason="Continue the task in the original pane"
  342. ```
  343. `accept` records the operator's observation of an uncertain handoff and finishes
  344. the existing ownership transfer without spawning or sending again. `abort`
  345. verifies the original ownership, stops only the recorded replacement, and verifies
  346. its absence before releasing the original task's rotation barrier. Work already
  347. performed by the replacement is preserved. An accepted ownership transfer cannot
  348. be aborted. Both actions require the exact execution ID and a nonempty reason;
  349. the decision is recorded durably, conflicting decisions are rejected, and the
  350. same command can resume recovery after another interruption. Changed process
  351. identities, foreign ownership, and unaccounted-for panes keep the recovery fenced
  352. for further inspection.
  353. Native compaction preserves the conversation and requires fresh provider context
  354. accounting to prove a reduction; it does not automatically clear history. Claude
  355. compaction reads the transcript the pane's own Claude process names in its
  356. session record, so it works when many Claude panes share one project directory.
  357. Without that binding it falls back to the directory's newest transcript and
  358. refuses ambiguous scope, including another Claude pane in a different session
  359. using the same transcript directory.
  360. ### 3. Work Graph Triage and Assignment
  361. NTM integrates with `br` and `bv` so the operator loop is not just "send prompts and
  362. hope." It can surface the best next task, highlight blockers, analyze impact, forecast
  363. work, and push assignments to specific panes or agent types.
  364. ```bash
  365. ntm work triage
  366. ntm work triage --by-track
  367. ntm work alerts
  368. ntm work search "JWT auth"
  369. ntm work impact internal/api/auth.go
  370. ntm work next
  371. ntm work graph
  372. ntm assign payments --auto --strategy=dependency
  373. ntm assign payments --beads=br-123,br-124 --agent=codex
  374. ```
  375. Automated assignment treats tracker labels as an authorization boundary. Add
  376. organization-specific approval labels globally or in `.ntm/config.toml`; project
  377. labels extend the global list and cannot remove built-in gates:
  378. ```toml
  379. [assign]
  380. operator_gated_labels = ["security-review", "legal-approval"]
  381. ```
  382. Matching is case-insensitive. NTM requires a structurally valid full actionable
  383. plan, uses scored triage only to rank IDs authorized by that plan, and restores
  384. every candidate's labels from both `br ready` and `br list --status open` so
  385. epics are covered. Any plan command, parse, structure, ID, label lookup, or
  386. coverage failure stops automated assignment before dispatch.
  387. Executing assignment paths can recover a corrupt local Beads SQLite index
  388. before reading the evidence needed to claim work. This includes automatic and
  389. watch assignment, coordinator assignment, and robot assignment preparation.
  390. NTM retries the failed read once after rebuilding from authoritative JSONL. If
  391. `br` refuses that rebuild because corruption prevents tombstone enumeration,
  392. NTM independently checks that the tombstone indexes agree and JSONL preserves
  393. every known tombstone before running `br doctor --repair --json`. It requires a
  394. verified database, validates the structured preservation evidence, and checks
  395. the known tombstones again after repair. An accepted partial repair retains
  396. its warnings, verified backups, and recovery marker. Unreadable indexes,
  397. missing tombstones, invalid JSONL, or failed verification stop assignment.
  398. Preview and dry-run commands do not request this repair. Recovery never replays
  399. a claim, reservation, or dispatch, and the normal eligibility and ownership
  400. checks still run against freshly read evidence.
  401. When `br` and `bv` report that no ready work exists, use the queue-dry flow to
  402. distinguish a genuinely empty queue from stale coordination state:
  403. ```bash
  404. # Confirm the work queue first. Do not run bare bv; use robot output.
  405. br ready --json
  406. bv --robot-triage | jq '.triage.quick_ref'
  407. # Diagnose why the queue appears dry.
  408. ntm work queue-dry --format=json | jq '{queue_dry, evidence, recommendations}'
  409. # Render an advisory roadmap only after the dry queue is confirmed.
  410. ntm work queue-dry --ideate --format=json | jq '{
  411. queue_dry,
  412. ideation: {
  413. status: .ideation.status,
  414. guard: .ideation.guard.recommendation,
  415. rendered: .ideation.roadmap.rendered_count,
  416. preview: .ideation.creation.remaining_commands
  417. },
  418. warnings
  419. }'
  420. # The same plan is available as markdown for human review.
  421. ntm work queue-dry --ideate --format=markdown
  422. ```
  423. Review the duplicate and novelty evidence before creating anything. If `br ready`
  424. has work, or `bv --robot-triage` shows actionable recommendations, claim that work
  425. instead of ideating. `--force` is only for an explicit preview when an operator wants
  426. to inspect the plan despite ready work or degraded tracker state.
  427. Gated creation is opt-in and still uses Beads as the source of truth:
  428. ```bash
  429. # Re-check the preview and guard before mutating Beads.
  430. ntm work queue-dry --ideate --format=json | jq '.ideation.creation.remaining_commands'
  431. # Create proposed beads only after review. The plan version is an audit token.
  432. ntm work queue-dry --ideate --create-beads --yes --plan-version="$(git rev-parse --short HEAD)"
  433. # Validate the graph and export Beads state after any mutation.
  434. br dep cycles --json
  435. bv --robot-triage | jq '.triage.quick_ref'
  436. br sync --flush-only
  437. git add .beads/issues.jsonl
  438. ```
  439. If Agent Mail, CASS, or CM are unavailable, `queue-dry --ideate` keeps running and
  440. marks those sources as degraded in `warnings`. Treat degraded Agent Mail reservation
  441. visibility as a coordination stop sign for mutating creation; fix coordination or use
  442. the non-mutating preview. Never edit `.beads/*.jsonl` directly, and use
  443. `ntm work queue-dry --help` for the current flag surface.
  444. ### 4. Coordination, Reservations, and Human Oversight
  445. NTM exposes Agent Mail and reservation workflows directly from the CLI. You can act as
  446. Human Overseer, inspect inbox state, review reservations, renew or force-release stale
  447. locks, and coordinate work without inventing an ad hoc protocol.
  448. ```bash
  449. ntm mail send payments --all "Sync to main and report blockers."
  450. ntm mail inbox payments
  451. ntm locks list payments --all-agents
  452. ntm locks renew payments
  453. ntm locks force-release payments 42 --note "agent inactive"
  454. ntm coordinator status payments
  455. ntm coordinator digest payments
  456. ntm coordinator conflicts payments
  457. ntm coordinator enable auto-assign
  458. ntm coordinator enable digest --interval=30m
  459. ntm coordinator disable conflict-negotiate
  460. ```
  461. `ntm locks force-release` is approval-gated by default (`automation.force_release:
  462. approval`): the first invocation files a durable approval request, a second operator
  463. grants it with `ntm approve <id>` (self-approval is rejected), and re-running the
  464. command consumes that approval and executes exactly once. Use
  465. `ntm policy automation --force-release auto` to allow unattended force-release, or
  466. `never` to disable it entirely; the serve HTTP endpoint and the dashboard conflict
  467. action honor the same policy setting.
  468. #### Pane identity badges
  469. In a mixed session, pane titles name the harness (`payments__cc_1`) while
  470. coordination happens under Agent Mail names (`BlueLake`). NTM can show each managed
  471. pane's assigned name in its tmux pane border next to the existing title:
  472. ```toml
  473. [agent_mail]
  474. enabled = true
  475. pane_badges = true # default false (opt-in)
  476. # pane_badge_format = "[{name}{drift}]{lifecycle}"
  477. ```
  478. The badge is NTM's assigned identity (the session agent registry, keyed by stable
  479. pane id), never whatever a later process wrote to the pane identity file. At every
  480. reconciliation NTM compares the assignment with the canonical Agent Mail identity
  481. file (legacy plain-text name or the structured record Agent Mail >= 0.3.31 writes)
  482. and caches the outcome in per-pane tmux user options
  483. (`@ntm_agent_mail_name`, `@ntm_agent_mail_state`, `@ntm_agent_mail_lifecycle`,
  484. `@ntm_agent_mail_label`); the window's `pane-border-format` gains a fragment that
  485. renders only the cached label, so tmux never calls Agent Mail while drawing.
  486. | Border | Meaning |
  487. |---|---|
  488. | `[BlueLake]` | current assignment; names agree (binding verified, or a legacy file that cannot be verified) |
  489. | `[BlueLake!]` | current assignment; the identity file disagrees (`name-disagreement`), is `missing-file` / `unreadable-file` / `invalid-file`, or its binding is `binding-unverifiable` / `binding-stale` — the assigned name is retained |
  490. | `[?!]` | no current assignment: `assignment-stale` (pane generation changed), `assignment-unobservable` (tmux unreadable) or `assignment-unregistered` |
  491. | `… (starting)`, `… (exited)`, `… (unknown)` | lifecycle observed at the last reconciliation; running agents carry no marker |
  492. Badges are written alongside identity assignment before the agent launches
  493. (`(starting)`) and reconciled on `ntm spawn`, `ntm add`, `ntm adopt`, restart/respawn
  494. and on explicit refresh with `ntm mapping --session <session>`, which also prints the
  495. discrepancy report (assigned vs resolved name, source path, assignment/observation
  496. state, `last_attempt_at` / `last_success_at`) and carries the same data under
  497. `identity` and `discrepancies` in `--json`. They describe the last reconciliation, not
  498. continuous liveness. Badge failures warn and never block a launch or change an
  499. assignment.
  500. Set `pane_badges = false` and run `ntm mapping --session <session>` to withdraw the
  501. pane options and restore the window's previous `pane-border-format` (including
  502. inheritance). Opt a single session out with
  503. `tmux set-option -t =<session>: @ntm_agent_mail_badges off`. A `pane-border-format`
  504. you wrote yourself that references `@ntm_agent_mail_*` is left untouched, and windows
  505. linked into several sessions are skipped with a diagnostic.
  506. Every session started by `ntm spawn` runs the coordinator inside its session
  507. monitor; `ntm coordinator status` shows it under Runtime (`runtime` in
  508. `--json`). The monitor always maintains assignment leases: it renews the file
  509. reservations of in-progress assignments, including those taken by a one-shot
  510. `ntm assign`, before their one-hour leases lapse, and releases them when the
  511. assigned bead closes. Every other coordinator action (`auto-assign`, `digest`,
  512. `conflict-negotiate`, `mail-nudge`) is off until enabled. `conflict-notify`
  513. never runs in the session monitor, only under `ntm coordinator run`: older
  514. `ntm config init` files set it to true, and it mails every holder of
  515. overlapping reservations in the project (`ntm coordinator status` notes when it
  516. is set). A foreground `ntm coordinator run` or a reservation-maintaining
  517. `ntm assign --watch` pauses the monitor's coordinator while it runs, so a
  518. session is never coordinated twice.
  519. `coordinator enable` and `disable` persist the selected `--config` file, or the
  520. global config by default, without replacing unrelated settings or comments.
  521. Session monitors apply a toggle within 15 seconds; restart an already running
  522. foreground `ntm coordinator run` to apply it there.
  523. The selected file may use a `[coordinator]` table or root dotted assignments
  524. such as `coordinator.auto_assign = false`. A whole-section inline assignment
  525. such as `coordinator = { auto_assign = false }` is rejected without changing
  526. the file; convert it to either supported form before toggling a feature.
  527. `ntm assign <session> --watch --reserve-files` maintains the saved file
  528. reservations for active assignments immediately on startup and every 30 seconds,
  529. including while scans or completion handlers are busy. Each maintenance pass is
  530. bounded to 30 seconds. The watcher renews the exact recorded leases only after
  531. verifying the current task claim and pane owner, and releases recorded leases
  532. when the task is confirmed terminal. It does not recreate expired or missing
  533. leases; failures remain visible, including under `--quiet`, and are retried.
  534. The monitor-hosted coordinator and `ntm coordinator run` use the same
  535. maintenance path before admitting new work.
  536. If one pane cannot be observed, independently verified healthy assignments can
  537. still renew and confirmed terminal work can still be cleaned up. Unverified
  538. assignments remain in the ledger, and a degraded coordinator cycle reports an
  539. error without dispatching new work. Watch mode checks the current saved ledger
  540. before exiting with `--stop-when-done`.
  541. The coordinator also recovers a delivered assignment when its original physical
  542. pane disappears. It verifies absence across the entire tmux server, rereads agent
  543. registries to rule out a moved or rebound owner, and checks the exact current
  544. Beads claim and recorded reservations. Only then does it persist task failure,
  545. release that assignment's leases, and reopen its claim for ordinary reassignment.
  546. Incomplete observations, a remaining pane, changed ownership, or failed cleanup
  547. keep the assignment protected. Interrupted cleanup resumes from its durable
  548. record; the previous prompt remains recorded as sent and is not replayed.
  549. ### 5. Safety Policy and Approvals
  550. NTM includes a first-class safety system for destructive or sensitive actions. Policy
  551. rules define what is allowed, blocked, or approval-gated. Approvals are durable, auditable,
  552. and support SLB-style two-person workflows for high-risk operations.
  553. ```bash
  554. ntm safety status
  555. ntm safety check -- git reset --hard
  556. ntm safety blocked --hours 24
  557. ntm safety install
  558. ntm policy show --all
  559. ntm policy validate
  560. ntm policy edit
  561. ntm policy automation
  562. ntm approve list
  563. ntm approve show abc123
  564. ntm approve abc123
  565. ntm approve deny abc123 --reason "wrong target branch"
  566. ```
  567. Every Claude agent NTM launches (spawn, add, robot spawn, restart, restore, rotation,
  568. swarm) gets a Claude Code `PreToolUse` hook through `--settings` that checks each Bash
  569. command against this policy and refuses blocked ones (`[safety] claude_policy_hook`,
  570. default on). Claude Code runs `PreToolUse` hooks even under
  571. `--dangerously-skip-permissions`, and runs only hooks a settings file or `--settings`
  572. lists, so `ntm safety install` also registers its hook script in
  573. `~/.claude/settings.json` for Claude sessions started outside NTM, and `ntm safety status`
  574. reports the hook as installed only when it is registered. dcg and rch hooks ride on the
  575. same `--settings` when those integrations are enabled and installed. A custom
  576. `[agents] claude` command whose last shell command is not the `claude` invocation (a
  577. pipe, a subshell, a wrapper script) must place the hooks itself with
  578. `--settings {{shellQuote .ClaudeSettings}}`; otherwise NTM launches it without them and
  579. warns at every launch.
  580. With `[integrations.dcg] enabled = true`, command lines in messages bound for non-Claude
  581. agents are checked by dcg before delivery. `ntm send`, `--robot-send` (including `--track`)
  582. and REST sends all refuse a blocked command — robot callers get `DESTRUCTIVE_COMMAND_BLOCKED`
  583. — and each refusal counts toward `ntm metrics` destructive-command incidents. A missing dcg
  584. binary skips the check; a check that errors or is interrupted refuses the send instead.
  585. ### 6. Pipelines, Templates, Recipes, and Workflow Assets
  586. NTM supports several layers of reusable automation:
  587. - `recipes`: reusable session presets
  588. - `workflows`: runnable orchestration patterns such as pipeline, ping-pong, and review-gate — `ntm workflow run <name>` executes a template's coordination loop against a live session (`ntm spawn -t <name>` only uses a template's agent counts to size a session)
  589. - `template`: prompt templates and substitutions
  590. - `pipeline`: executable multi-step agent workflows with variables, dependencies, resume, and cleanup
  591. - `session-templates`: higher-level session layouts
  592. ```bash
  593. ntm recipes list
  594. ntm recipes show full-stack
  595. ntm workflows list
  596. ntm workflows show red-green
  597. ntm workflow run red-green --var feature="parser rewrite"
  598. ntm workflow run ./my-flow.toml --session payments
  599. ntm template list
  600. ntm template show fix-bug
  601. ntm send payments --cc -t marching_orders --bead bd-123 # rendered per pane: own {{agent_num}}/{{agent_type}}
  602. ntm pipeline run .ntm/pipelines/review.yaml --session payments
  603. ntm pipeline status run-20241230-123456-abcd
  604. ntm pipeline list
  605. ntm pipeline resume run-20241230-123456-abcd --mode=continue
  606. ntm pipeline cleanup --older=7d
  607. ```
  608. Workflow templates with manual gates, including `review-pipeline` and
  609. `specialist-team`, can wait for an operator to select a specific transition:
  610. ```bash
  611. ntm workflow status --session payments --json
  612. ntm workflow trigger --session payments --token "MANUAL_GATE_TOKEN_FROM_STATUS" \
  613. --transition 0 --reason "Design reviewed and ready for implementation"
  614. ```
  615. Choose the exact index from `manual_gate.transitions`, together with that gate's
  616. `token`. A gate appears after the stage's prompts have been delivered. Its token
  617. stays stable while output is observed, and changes when work is retried, an agent
  618. is replaced, or another stage visit begins. The command records one immutable
  619. decision; the active runner applies it on its next poll and records it in stage
  620. history. Repeating the same choice and reason returns the original receipt.
  621. Decisions can also be recorded while a runner is offline or paused. Continue
  622. with `ntm workflow run TEMPLATE --session payments --resume` to apply the saved
  623. decision and continue from the existing delivery checkpoint. Each later manual
  624. gate requires its own choice. Use `--project-root DIR` with status and trigger
  625. when the project is elsewhere; `workflow run --fire-manual` remains the explicit
  626. option for automatically advancing every manual gate.
  627. Workflow checkpoints also retain the selected tmux endpoint: local, or the exact
  628. SSH target. `workflow status` reports it, and `--resume` requires that original
  629. endpoint even if another host has matching pane IDs and PIDs. Legacy checkpoints
  630. without an endpoint remain inspectable, but require independent inspection and
  631. an explicit `--restart` before running the workflow again. Changing an endpoint
  632. also invalidates its manual gate decisions.
  633. SSH workflows can use agent-output, idle, elapsed-time, and manual triggers.
  634. File and command triggers require NTM to run on the agents' host; remote workflows
  635. reject those triggers before starting, including triggers in later stages.
  636. A same-named local directory or explicit `--project-root` does not establish a
  637. shared filesystem. For SSH workflows, `--project-root` selects the local project
  638. directory containing the checkpoint and defaults to the local current directory.
  639. Workflow `stage_timeout_minutes` deadlines are saved before each prompt round.
  640. Downtime counts toward the deadline: `--resume` handles an expired stage before
  641. sending any remaining prompts. A timeout policy of `retry` starts another timed
  642. round, bounded by `max_retries_per_stage`; retry and agent-restart allowances
  643. remain consumed across resumes. Command checks and pane observations are bounded
  644. by the current round's remaining time.
  645. Successful timeout `pause` and `notify` actions retain receipts, so resuming does
  646. not repeat them or silently grant a fresh timeout for the same round. A timeout
  647. `abort`, an interrupted action with an unknown outcome, or an older timed
  648. checkpoint without its original deadline requires inspection and a deliberate
  649. `--restart`. Timeout-driven skips commit the destination stage before its prompts
  650. are sent, including transitions that revisit the same stage.
  651. The dashboard resumes pipelines in a detached worker, so closing the browser or
  652. restarting the HTTP server does not cancel an authorized resume. REST clients can
  653. request the same lifetime with `POST /api/v1/pipelines/{id}/resume` and
  654. `{"background":true}`. HTTP `202 Accepted` acknowledges worker startup, not
  655. workflow completion. Poll the existing pipeline status endpoint and cancel
  656. through `POST /api/v1/pipelines/{id}/cancel`; the run ID stays unchanged.
  657. The worker acquires exclusive run ownership before reloading the saved state and
  658. validating its workflow inside the configured project. Omit `session` to use the
  659. session from that owned checkpoint. Detached resume retains saved variables and
  660. rejects nonempty variable overrides. Omitting `background`, or setting it to
  661. `false`, retains synchronous REST resume; `pipeline_resume` jobs also keep their
  662. own execution and cancellation lifetime.
  663. Pipeline cleanup removes old checkpoints only after acquiring the run's ownership
  664. lock and verifying that execution and every saved command, selector, delivery,
  665. mail, and reservation receipt have settled. Active runs and unresolved receipts
  666. remain available for recovery, even when their checkpoint is old. Legacy,
  667. malformed, oversized, or otherwise uninspectable states are also retained;
  668. cleanup never treats missing evidence as permission to replay work.
  669. Use `ntm pipeline cleanup --older=7d --dry-run` to inspect the same eligibility
  670. checks without removing files. Human and JSON output include retained run IDs
  671. and reason codes, without command output or message contents. Shared workflow
  672. snapshots and stable ownership lock files are preserved. The REST cleanup
  673. endpoint applies the same checks and returns deleted, eligible, and retained
  674. counts with per-run results.
  675. Pipeline resume preserves completed step outputs. Prompt and template steps also
  676. save their delivery and response evidence: `--mode=continue` resumes observing a
  677. confirmed request on its original tmux host and physical pane without submitting
  678. it again. Partial output survives interruption, and a completed response can be
  679. restored even if the process stopped before saving the enclosing step result.
  680. Recognized composer and footer redraws are excluded from response evidence; an
  681. idle pane showing only the submitted prompt is not counted as completed work.
  682. Unknown submission outcomes, replaced pane processes or hosts, and missing output
  683. boundaries stop recovery with the receipt preserved. If you verify that the
  684. original agent received an uncertain submission, record that observation and
  685. continue without resending:
  686. ```bash
  687. # Inspect saved identities and obtain the exact receipt token.
  688. ntm pipeline recover run-20241230-123456-abcd --json
  689. # Accept only the inspected delivery, after checking the original agent.
  690. ntm pipeline recover run-20241230-123456-abcd --step-id review \
  691. --receipt <token-from-inspection> --accept-delivery \
  692. --reason "The original agent is working on the submitted review"
  693. # Collect the original response and continue dependent steps.
  694. ntm pipeline resume run-20241230-123456-abcd --mode=continue
  695. ```
  696. Recovery runs from the project containing the saved pipeline state. Inspection
  697. shows receipt identities without prompt or transcript contents. Acceptance
  698. requires the original tmux endpoint, physical pane and process, an intact output
  699. boundary, and the frozen workflow. It records the reason and time without sending
  700. input, completing the task, or starting dependent steps. Resume keeps its existing
  701. step-definition checks. A live run owner, stale receipt, or conflicting decision
  702. is refused; repeating the same receipt and reason returns the saved decision,
  703. including after the run completes.
  704. Structured `on_failure` recovery has its own delivery receipt, identified by
  705. the failed step's runtime ID followed by `.on_failure`. Use the exact ID and
  706. receipt token from inspection, including any enclosing branch or iteration
  707. namespace. After an uncertain fallback is accepted, resume finishes that
  708. original fallback without repeating the native command that triggered it.
  709. The original command receipt remains intact. Parent and fallback definition
  710. checks still apply, and the parent failure is suppressed only when the saved
  711. workflow explicitly configures `suppress_failure: true`.
  712. The dashboard exposes these decisions for failed or cancelled runs under
  713. **Recovery decisions**. Review the original agent or process, open the relevant
  714. receipt, enter your observation, and explicitly confirm what you verified.
  715. Command and selector decisions require the original exit code and complete
  716. output, including an explicitly verified empty output. Changed receipts require
  717. a fresh review. Recording a decision does not restart execution; use **Resume**
  718. separately when ready to continue in the detached worker.
  719. REST clients can perform the same recovery through the server's configured
  720. project. `GET /api/v1/pipelines/{id}/recover` requires `pipelines:read` and returns
  721. the `deliveries`, `commands`, and `selectors` arrays, including receipt identities,
  722. acceptance eligibility, refusal reasons, and exact `receipt_token` values. To record
  723. an agent-delivery observation, send `POST /api/v1/pipelines/{id}/recover` with
  724. `pipelines:write` permission, `Content-Type: application/json`, and this JSON body:
  725. ```json
  726. {
  727. "step_id": "review",
  728. "receipt": "<receipt_token from GET>",
  729. "accept_delivery": true,
  730. "reason": "The original agent is working on the submitted review"
  731. }
  732. ```
  733. To accept a command outcome after independently verifying that the original
  734. command **and all descendants have finished**, use the command receipt from GET:
  735. ```json
  736. {
  737. "step_id": "migrate",
  738. "receipt": "<command receipt_token from GET>",
  739. "accept_command": true,
  740. "exit_code": 0,
  741. "output": "Migration completed\n",
  742. "reason": "Verified the migration and all child processes finished successfully"
  743. }
  744. ```
  745. Use `accept_selector: true` and a selector receipt for an interrupted branch,
  746. foreach, or bead-query source. Exactly one acceptance flag must be true. Command
  747. and selector decisions require an explicit `exit_code` from 0 to 255 and `output`;
  748. an empty string records observed empty output, while omission or `null` is refused.
  749. Delivery decisions cannot include outcome values. Requests use UTF-8 JSON and must
  750. fit the server's 10 MiB encoded-body limit, including metadata and escaping, as
  751. well as the frozen workflow's capture limits. Output is never truncated or
  752. silently repaired. Use the CLI for binary selector output or larger captures
  753. within its 16 MiB limit. Enabled request redaction rejects detected secrets in
  754. output or reasons before persistence.
  755. Acceptance records the same durable decision as the CLI without launching work,
  756. signalling processes, or inferring settlement from a saved PID. Continue with
  757. `POST /api/v1/pipelines/{id}/resume`, or submit a `pipeline_resume` job for
  758. pollable execution. Inspection and acceptance expose receipt metadata without
  759. prompt, transcript, or captured output contents. Recovery requests cannot select another project
  760. or replace the saved session. Stale receipts, conflicting observations, and a live
  761. run owner produce a conflict response without changing the checkpoint.
  762. Each REST pipeline request retains the project selected when it was admitted.
  763. Changing `project_dir` through the configuration API affects subsequent requests;
  764. it cannot redirect an admitted request's workflow lookup, run ownership,
  765. execution, or cancellation. HTTP idempotency keys use that same project scope,
  766. so retrying a key after switching projects cannot replay the previous project's
  767. success. Clearing the configured project also cannot replay a cached file-based
  768. operation that required it. File-based run, validation, and resume still require
  769. a configured project; recovery additionally requires an accessible absolute
  770. project directory.
  771. Foreground command steps in the main workflow have an explicit recovery path
  772. for the case where the command finished but its final checkpoint was lost. `pipeline recover`
  773. includes these command receipts in its `commands` JSON array, with eligibility
  774. and refusal information. Before accepting one, independently verify that the
  775. original command **and all its descendants have finished**, then supply its
  776. observed exit code and complete captured output.
  777. A `wait: none` launch acknowledgement does not establish successful execution.
  778. A later unsuccessful exit makes the final workflow fail, while healthy sidecars
  779. stopped at normal workflow completion remain expected shutdowns. On Linux, a
  780. leader failure observed before cleanup signals retains its original exit error
  781. even if workflow shutdown begins before its receipt is saved. Failed, settled
  782. background receipts follow the existing resume reconciliation: the failed command
  783. runs again while completed dependent steps retain their results. Uncertain
  784. settlement still refuses replay.
  785. A background command inside a parallel group or parallel foreach keeps running
  786. after its container finishes normally. It remains available to downstream steps
  787. and post-pipeline hooks until workflow finalization stops and joins it. Explicit
  788. cancellation and fail-fast still stop affected commands.
  789. An explicit command or enclosing parallel-group deadline remains in force even
  790. after the container returns; expiry is recorded as a background failure. Moving a
  791. sidecar into a nested container therefore does not shorten its healthy lifetime
  792. or remove its cancellation and timeout boundaries.
  793. A fatal main step failure requests cancellation of its main sidecars and joins
  794. their supervision before running post-pipeline hooks. This lets SIGTERM handlers
  795. and receipt persistence finish before hooks release resources. The workflow context stays
  796. live for those hooks; caller cancellation during the wait switches to `on_cancel`
  797. cleanup. Returned uncertainty still leaves an unresolved receipt and refuses
  798. replay.
  799. Cancellation before the first execution attempt retains explicit no-dispatch
  800. evidence. Native commands cancelled before launch retain a settled receipt with
  801. process ID zero. Ordinary resume can continue this proven-unstarted work; prior
  802. attempts and unresolved receipts keep their existing replay restrictions.
  803. For a command with `wait: none`, an explicit step `timeout` applies to the
  804. background process's whole lifetime. Expiry requests normal command cleanup,
  805. records a timeout outcome, and prevents the final workflow from reporting success.
  806. Already-admitted dependent work keeps its existing scheduling. A later workflow
  807. cancellation does not erase the original timeout cause. Without an explicit
  808. timeout, a sidecar retains the workflow's lifetime instead of inheriting the
  809. foreground command default. Uncertain cleanup still leaves an unresolved receipt
  810. and refuses replay, even when the deadline has expired.
  811. On Unix, a failed process-group observation keeps the command under supervision
  812. and is retried within its existing execution deadline. It does not request
  813. cancellation or shorten the five-second SIGTERM grace period. After the final
  814. group signal, NTM retries observation for up to one second while retaining the
  815. original group leader's identity. If that final census remains unknown after a
  816. successful signal, a separate five-second recovery window retries observation
  817. without sending another signal. The original leader and exclusive run ownership
  818. remain held until recovery finishes, so later quiet evidence can settle the exact
  819. foreground, background, or selector receipt before the run returns. A confirmed
  820. live group or failed final signal keeps the original cleanup budget. A complete
  821. quiet-group observation and complete output capture are both required for a
  822. `settled` receipt.
  823. The stdin feeder must also finish copying or receive a kernel broken-pipe
  824. response confirming that its readers closed. A forced stdin-pipe closure during
  825. the wait timeout leaves the receipt unresolved, including when a nonzero command
  826. exit would otherwise hide that pipe error. Completing the feed does not establish
  827. containment of descendants that deliberately leave the group and no longer keep
  828. NTM's I/O open.
  829. Linux observes the original leader through its stable pidfd when supported.
  830. Transient leader-observation failures then retain supervision within the existing
  831. execution deadline, so later recovery can still settle the receipt. Cancellation
  832. allows a separate 250 ms of observation recovery before falling back to leader
  833. cleanup. A system without a stable handle or pidfd-based wait support retains the
  834. bounded 250 ms observation fallback. An explicit loss of child ownership ends
  835. observation and signalling immediately; a saved numeric PID cannot authorize a
  836. later signal.
  837. Linux requires cancellation of the command's own context before group cleanup,
  838. even when an observation error contains a cancellation or deadline error. It rechecks the
  839. original leader's waitability before SIGTERM, before SIGKILL, and before accepting
  840. settlement. Lost ownership during observation or grace leaves the receipt
  841. unresolved and prevents further group signals, preserving the ordinary-resume
  842. replay barrier.
  843. If leader observation remains unavailable during explicit cancellation, NTM can
  844. still send SIGTERM through the original leader's pidfd and wait up to five seconds
  845. for graceful exit. Failed pidfd observations preserve that grace period before
  846. SIGKILL. This fallback never signals a numeric PID or process group. Stopping
  847. only the leader cannot settle the command's receipt because descendants may
  848. remain alive. If no stable handle is available, the command remains unresolved
  849. without a fallback numeric signal.
  850. For normal Linux completion, NTM checks that the kernel's process-creation counter
  851. did not change during a quiet census and that zombie process leaders have no
  852. surviving threads. A child that forks and exits during enumeration therefore
  853. cannot hide a still-running grandchild. A raced census is retried; natural
  854. completion sends no termination signal. Host-wide process churn can delay this
  855. proof, while the command's existing deadline and cancellation remain effective.
  856. The same proof requires a complete, stable `/proc` mount view. Modes that hide
  857. process directories, such as `hidepid=2` or `hidepid=4`, cannot authorize a settled
  858. receipt; an apparently empty visible group does not prove hidden work ended.
  859. The mount must also expose the observer's own PID namespace: a single `NSpid`
  860. value in `/proc/self/status` must match its process ID before and after the
  861. census. An ancestor namespace's process numbers can alias unrelated local
  862. processes, so matching numeric group IDs alone cannot prove settlement. Missing
  863. namespace evidence (including kernels without `NSpid` support or `CONFIG_PID_NS`)
  864. also leaves observation uncertain; use a complete procfs mount for the process's
  865. own namespace on a kernel that supplies this evidence.
  866. If cleanup returns without that proof, the receipt becomes `unresolved`, with the
  867. failed or cancelled outcome and cleanup details preserved, rather than remaining
  868. `running` after supervision ended. Ordinary resume and automatic retry refuse
  869. these receipts. A saved PID disappearing later is not sufficient evidence for
  870. automatic reconciliation: its original group identity is no longer pinned.
  871. Use the explicit recovery procedure below only after independently verifying the
  872. original command and its effects.
  873. Handling a command or selector error with `on_error: continue` can let other
  874. steps finish, but it cannot establish process settlement. At finalization, any
  875. remaining unsettled process receipt prevents a successful workflow outcome.
  876. The original receipts remain unchanged for inspection and supported recovery;
  877. confirmed settled failures keep their existing error-policy behavior.
  878. An `on_failure` action or fallback waits until its failed source and owned
  879. process work have a known outcome. Unresolved command and selector receipts keep
  880. their failed scheduler results, without publishing failure-action variables or
  881. dispatching fallback work that would prevent later acceptance. Once the original
  882. outcome is explicitly accepted, ordinary resume applies the authored failure
  883. policy. Unrelated scopes and healthy supervised background children keep their
  884. normal failure handling.
  885. Ordinary execution checks owned command and selector receipts before publishing
  886. successful scheduler results. An uncertain success hook leaves its parent failed
  887. and stops later hooks. An uncertain foreach body also stops its iteration before
  888. a completed-round checkpoint is written. Explicit acceptance and resume can then revisit the
  889. unfinished work while retaining the successful parent's native receipt, earlier
  890. completed hooks, and immutable accepted outcomes. Ordinary settled hook failures
  891. keep their existing logging behavior; healthy background acknowledgements remain
  892. valid while their command supervision is active.
  893. Success-hook sequences now checkpoint the completed parent body before the first
  894. hook, then checkpoint each consumed hook outcome before starting the next one.
  895. Cancellation leaves the parent unfinished until its remaining hooks settle.
  896. Ordinary resume reuses the successful body and earlier consumed outcomes,
  897. including advisory hooks that returned a known failure after producing effects.
  898. The same continuation applies inside branches, parallel groups, foreach
  899. iterations, and nested success hooks. A delivered agent prompt resumes observation;
  900. an unconfirmed delivery still requires its existing explicit recovery decision.
  901. These checkpoints bind both the authored and materialized step definitions,
  902. ordered hook identities, results, and output bindings. Missing or altered
  903. consumption evidence stops resume before downstream work. Completed hook outputs
  904. can be rebuilt from the saved evidence even when the variable cache is missing.
  905. Explicit whole-run reset and valid forced-iteration scopes clear the matching
  906. hook progress; restarting a consumed failed hook alone refuses a replay that
  907. would leave its containing work inconsistent. Background commands retain their
  908. existing supervised relaunch behavior. This records orchestration progress; it
  909. does not make a remote side effect and its local checkpoint one atomic operation.
  910. An older checkpoint may already report `completed` while retaining an unfinished
  911. foreground command or selector receipt. If that step's scheduler result is
  912. failed or cancelled, recovery inspection can offer the same explicit acceptance
  913. procedure. Acceptance retains all existing identity, ownership, and
  914. enclosing-work checks, then saves the observed outcome and changes the
  915. contradictory workflow status to `failed` in one checkpoint, with a recovery
  916. diagnostic. Ordinary resume then applies the accepted outcome. Completed work
  917. and any other unresolved receipts retain their evidence; repeating an accepted
  918. decision after successful resume does not reopen the run.
  919. A failed or cancelled scheduler result from an older checkpoint is not evidence
  920. that a command group stopped. Without an execution receipt, ordinary resume also
  921. refuses these steps and background rerun markers; an intentional replay requires
  922. `--mode=restart-failed` or an explicit reset. Proven-settled failures retain normal
  923. retry behavior. Newly cancelled parallel children that never entered their executor
  924. carry separate scheduler evidence, so they can resume without being mistaken for
  925. previously launched work.
  926. During cancellation, NTM saves the cancelled state before waiting for background
  927. command supervision to return and persist its receipts. Only then does it start
  928. authored `on_cancel` cleanup, so graceful sidecar shutdown can finish before
  929. cleanup releases its resources. Each cleanup step receives its full configured
  930. timeout after this wait. Returned uncertainty still leaves an unresolved receipt;
  931. it does not suppress authored cleanup or prove that every process has exited.
  932. Background commands started by cleanup are also joined before the run returns.
  933. Shell branch predicates, external foreach sources, and bead queries also persist
  934. launch intent before starting their command. Their output is usable only after
  935. the owned group settles and both captured streams reach EOF. A returned cleanup
  936. failure leaves an `unresolved` entry in `command_evaluations`; automatic retries
  937. and ordinary resume refuse it even when a failure handler completed the enclosing
  938. step. If the original source and its descendants finished and its final outcome
  939. can be independently verified, `pipeline recover --accept-selector` can record
  940. that outcome without repeating its effects. Inspect the original work before
  941. deliberately authorizing `restart-failed`, a containing `force-iter` scope, or a
  942. whole-run reset. Unfinished external selectors
  943. from older checkpoints without sufficient source or decision evidence require the
  944. same explicit decision.
  945. Successful evaluations retain their complete bounded output in the checkpoint
  946. before it can choose a branch or admit iterations. Ordinary resume reuses that
  947. output, including after a crash between command completion and decision storage,
  948. instead of repeating source effects. Reuse requires the same step definition,
  949. expanded executable and arguments, working directory, effective environment, and
  950. capture limits. Changed inputs require restoring the original inputs or an
  951. explicit replay of the affected scope. A failed child does not discard an already
  952. admitted branch choice or foreach item list. A normal nonzero source exit with
  953. proven cleanup still clears its receipt and retains configured retry behavior.
  954. External branch, foreach, and bead-query sources use `step.timeout`, or the
  955. executor's default timeout when no step override is set, and the workflow's
  956. `max_command_stdout_bytes` and `max_command_stderr_bytes` limits. A source deadline
  957. applies to source evaluation; branch and foreach bodies keep their own lifetimes.
  958. The run also limits retained selector stdout and outstanding stdout reservations
  959. with `settings.limits.max_selector_output_bytes_total` (default **32 MiB**).
  960. Before a new source starts, it reserves its entire `max_command_stdout_bytes`
  961. allowance. Successful completion replaces that reservation with the exact saved
  962. bytes; uncertain completion keeps the full reservation and its replay barrier.
  963. Parallel sources wait within their existing deadlines when active captures can
  964. free enough capacity. If saved output or unresolved receipts leave insufficient
  965. capacity, the next source fails before launch, without creating a receipt or
  966. performing its command's effects. Already saved outcomes remain reusable even
  967. when an older checkpoint exceeds the current budget.
  968. For sources that return small records, a smaller `max_command_stdout_bytes`
  969. allows more concurrent reservations. To raise capacity for an existing frozen
  970. run without resetting its evidence, use
  971. `ntm pipeline resume <run-id> --max-selector-output-bytes-total 67108864`.
  972. This positive byte override applies only to that resume attempt; it preserves
  973. the frozen workflow, original capture limits, and cached output identities.
  974. The REST resume endpoint and `pipeline_resume` jobs accept the corresponding
  975. `max_selector_output_bytes_total` field. This budget covers selector stdout and
  976. reservations; other checkpoint fields, parsed items, and temporary serialization
  977. buffers have separate memory and storage costs.
  978. Dynamic step expansion is bounded separately by
  979. `settings.limits.max_step_count_total` and `max_materialized_step_nodes`, both
  980. defaulting to **100,000**. The first limits distinct concrete runtime IDs across
  981. the run; retries, ordinary resume, and explicit scope resets reuse the existing
  982. admission ledger. The second limits literal definitions and active planner
  983. copies, checked before eager foreach expansion, branch decoding, and parallel
  984. body allocation. Nested planners refuse insufficient capacity promptly.
  985. Neither limit is a byte cap for all pipeline memory or checkpoint data.
  986. Main work stops on admission exhaustion even under continue or retry policies.
  987. Authored cancellation and post-pipeline roots reserve a separate bounded ID
  988. allowance before main execution, so an earlier dynamic cleanup cannot consume
  989. a later release root's slot. Existing process cleanup and uncertain-execution
  990. replay barriers remain authoritative; an admission is never proof of execution
  991. or termination. A successful command whose success hook exceeds capacity keeps
  992. its receipt, allowing the hook to finish on resume without repeating the command.
  993. For a frozen run, raise either limit for the current attempt with
  994. `ntm pipeline resume <run-id> --max-step-count-total 200000
  995. --max-materialized-step-nodes 200000`. The REST resume endpoint and
  996. `pipeline_resume` jobs accept the corresponding snake_case fields. Positive
  997. overrides preserve the frozen workflow and native receipts; zero uses the
  998. frozen policy, and negative values are rejected before checkpoint mutation.
  999. See [step admission limits](docs/WORKFLOW_SCHEMA.md#step-admission-and-materialization-limits)
  1000. for accounting and cleanup details.
  1001. Dry runs preview dynamic foreach sources without executing their shell commands
  1002. or `br` queries; static item and model lists can still be expanded for preview.
  1003. Foreach item bindings also apply to command `stdin`, native `bead_query` fields,
  1004. Agent Mail send and inbox requests, and reservation acquisition and release
  1005. requests. For example, a loop with `as: assignment` can send mail to
  1006. `${assignment.agent}`, reserve `${assignment.path}`, and query beads labelled
  1007. `${assignment.label}`. Each iteration receives its own request values, including
  1008. inside selected branches, success hooks, and failure recovery handlers. Nested
  1009. loops retain their own item bindings; round variables and downstream step
  1010. outputs resolve when the corresponding operation executes.
  1011. For a foreground command receipt:
  1012. ```bash
  1013. ntm pipeline recover run-20241230-123456-abcd --json
  1014. ntm pipeline recover run-20241230-123456-abcd --step-id migrate \
  1015. --receipt <command-receipt-from-inspection> --accept-command \
  1016. --exit-code 0 --output-file migration-output.txt \
  1017. --reason "Verified the migration and all child processes finished successfully"
  1018. ntm pipeline resume run-20241230-123456-abcd --mode=continue
  1019. ```
  1020. Both `--exit-code` and `--output-file` must be supplied explicitly; an empty
  1021. regular file records an observed empty output. Use complete UTF-8 stdout for a
  1022. step with `output_parse`, or captured combined stdout and stderr otherwise.
  1023. Recovery enforces a 16 MiB bound and the frozen workflow's stdout limit.
  1024. Inspection and acceptance responses contain identities and output fingerprints,
  1025. without command text, environment values, or captured output.
  1026. Command acceptance records an immutable observation without starting a process,
  1027. parsing output, or executing dependent work. Ordinary resume checks the exact
  1028. materialized command definition and applies the existing output parser and
  1029. failure policy, including parsed output and named variables used by dependents.
  1030. A nonzero exit code does not authorize an automatic rerun. Repeating the same
  1031. receipt, reason, exit code, and exact output returns the saved decision, including
  1032. after completion; a conflicting observation is refused. A live run owner,
  1033. background command, cleanup or post-pipeline command, or command whose enclosing
  1034. work already completed prevents acceptance. Recorded PIDs are diagnostic only: recovery neither infers completion
  1035. from PID disappearance nor signals a saved process ID.
  1036. For an interrupted selector receipt, inspection includes a `selectors` array
  1037. with its exact receipt token, acceptance eligibility, and refusal reason:
  1038. ```bash
  1039. ntm pipeline recover run-20241230-123456-abcd --json
  1040. ntm pipeline recover run-20241230-123456-abcd --step-id choose \
  1041. --receipt <selector-receipt-from-inspection> --accept-selector \
  1042. --exit-code 0 --output-file selector-stdout.bin \
  1043. --reason "Verified the original selector and all descendants finished"
  1044. ntm pipeline resume run-20241230-123456-abcd --mode=continue
  1045. ```
  1046. First independently verify that the original selector **and all its descendants
  1047. have finished**. Supply its observed exit code and complete stdout, including an
  1048. empty regular file when it emitted no stdout. Selector output is retained as
  1049. exact bytes, including non-UTF-8 data, and is bounded by the original capture
  1050. limit, the frozen workflow's limit, and the 16 MiB recovery limit. Recovery
  1051. responses expose only identity, decision metadata, byte counts, and hashes.
  1052. Acceptance writes a distinct `accepted` receipt with an immutable decision hash.
  1053. It preserves the original intent or cleanup status, timestamps, diagnostic error,
  1054. and recorded PID. An intent whose PID was never checkpointed stays without a PID;
  1055. the operator's observation does not invent native process-settlement evidence.
  1056. No command, signal, branch selection, or item admission occurs during acceptance.
  1057. Ordinary resume checks the exact selector definition and expanded invocation
  1058. before consuming successful output. A nonzero accepted exit follows normal
  1059. failure handling without relaunching the source, even when retry is configured.
  1060. The exact receipt, reason, exit code, and stdout replay the same saved decision;
  1061. changing any part is refused. Recovery also refuses a live run owner, a stale or
  1062. corrupt receipt, legacy evidence without an invocation identity, changed frozen
  1063. definitions, already-admitted output, completed enclosing work, and selectors in
  1064. cleanup or post-pipeline phases. An intentional reevaluation requires the normal
  1065. explicit replay scope. Older executors that do not understand `accepted` refuse
  1066. that receipt rather than interpreting it as native settlement.
  1067. Pipeline `mail_send` steps also checkpoint their send intent and delivery receipt.
  1068. If a response is lost or the run stops while a send is unresolved, automatic
  1069. retries and ordinary resume refuse to send the message again: the recipient may
  1070. already have received it. Inspect the recipient's inbox and original thread
  1071. before deliberately choosing `--mode=restart-failed` to resend. A saved successful
  1072. receipt restores the original output and parsed variables without another send,
  1073. even if the scheduler's final step checkpoint was lost. A local output-parsing
  1074. failure does not authorize resending delivered mail. Explicit server refusals
  1075. remain eligible for the step's normal retry policy. Interrupted sends from older
  1076. checkpoints without a receipt require the same deliberate replay decision.
  1077. Pipeline file reservations retain their resolved request, exact lease identities,
  1078. and partial grant evidence. A lost acquisition response or unverified grant never
  1079. triggers automatic reacquisition. Resume checks that retained protection still
  1080. has the original IDs, owner, paths, mode, and creation identity, with live expiry,
  1081. before dispatching further work. A same-ID renewal is accepted; a replacement
  1082. lease on the same path is not adopted. Release steps for this run's acquisitions
  1083. select only the recorded IDs and verify their disappearance, so another run's
  1084. same-path reservations remain intact. Standalone release steps without acquisition
  1085. evidence retain their explicit path behavior.
  1086. Verified partial grants remain available for exact-ID cleanup. Unverified handles
  1087. are inspection evidence, not authority to release somebody else's leases. Finish
  1088. releasing known active leases before resetting acquisition history. If an authored
  1089. cancellation or finalization hook already released protection, resuming unfinished
  1090. protected work requires a whole-workflow reset to acquire it again; iteration
  1091. replay cannot retain those released locks. Cleanup-only resume can finish when the
  1092. original IDs have already expired or disappeared.
  1093. While a pipeline is running, a heartbeat renews its verified reservation IDs
  1094. before expiry, including during long commands, agent waits, and post-pipeline
  1095. work. Independent readback must confirm the original lease identities and an
  1096. extended expiry; a lost renewal reply is accepted only when that readback proves
  1097. protection. Dispatch also checks ownership immediately before sending more work.
  1098. Lost, replaced, expired, or unverifiable protection fails the run and cancels
  1099. active waits and commands. Input already delivered to an external agent cannot
  1100. be recalled. Authored `on_cancel` cleanup still runs; reservations are never
  1101. automatically reacquired or released. Use explicit workflow release steps.
  1102. If you instead intend to repeat failed or interrupted agent work, inspect the
  1103. original pane before using `--mode=restart-failed`; that mode still preserves
  1104. completed delivery receipts. Use
  1105. `--keep-state=false` or `--mode=force-iter --step-id=<id> --iteration=<n>` for an
  1106. intentional reset or iteration replay. Commands with a normally settled outcome
  1107. retain ordinary retry behavior; operator-accepted outcomes require an explicit
  1108. reset before repeating them. An unresolved command is never automatically
  1109. repeated. Before deliberately restarting one, inspect its side effects and stop
  1110. any surviving command processes. These restart choices can repeat side effects.
  1111. ### 7. Durable State, Audit, and Recovery
  1112. NTM treats recoverability as a core feature. Sessions can be checkpointed, timelines can
  1113. be replayed, audit records can be exported, and prompt/session history remains available
  1114. for analysis or resumption.
  1115. ```bash
  1116. ntm checkpoint save payments -m "pre-migration"
  1117. ntm checkpoint list payments
  1118. ntm checkpoint restore payments
  1119. ntm checkpoint restore payments last --as payments-recovered --directory /path/to/recovery-worktree
  1120. ntm sessions save payments
  1121. ntm sessions restore payments --name payments-restored --launch
  1122. ntm sessions resume payments --name payments-resumed
  1123. ntm timeline list
  1124. ntm timeline show <session-id>
  1125. ntm history search "authentication error"
  1126. ntm audit show payments
  1127. ntm conflicts payments
  1128. ntm resume payments
  1129. ```
  1130. Ordinary `ntm spawn payments --cc=2` also restores the latest readable local handoff for
  1131. that session from the resolved project directory. The previous goal, immediate
  1132. task, decisions, and next steps are delivered before the new user prompt through
  1133. the same readiness and submission checks as other spawn prompts. This works
  1134. without Beads, Agent Mail, or CM being installed. The handoff uses a bounded
  1135. recovery budget, and JSON output reports its source as `recovery.handoff_path`.
  1136. `--no-recovery`, `recovery.enabled = false`, or
  1137. `recovery.auto_inject_on_spawn = false` disables this injection. The shared
  1138. handoff reader can fall back to an older readable file if the newest is corrupt;
  1139. the reported source identifies the file actually used. If no handoff can be read,
  1140. or its session or project does not match, spawn reports partial recovery and can
  1141. proceed with its other available context.
  1142. Remote tmux sessions skip local handoffs and report that source as unavailable;
  1143. NTM does not treat a matching local path as proof of the remote project's identity.
  1144. To continue a specific Agent Mail conversation in newly spawned agents, use
  1145. `--thread`:
  1146. ```bash
  1147. ntm spawn payments --cc=2 --thread=FEAT-123
  1148. ntm spawn payments --label=follow-up --cc=2 --thread=FEAT-123 --prompt="Finish the agreed tests"
  1149. # For servers requiring an authenticated thread reader:
  1150. ntm spawn payments --cc=1 --thread=FEAT-123 --thread-agent=BlueLake
  1151. ```
  1152. NTM reads the thread summary once from the resolved project's Agent Mail scope,
  1153. then includes its key points and action items in each agent's initial prompt.
  1154. Per-agent defaults, `--prompt`, and pane-specific marching orders follow that
  1155. context. Delivery uses the existing readiness checks and configured secret
  1156. redaction. The new agents keep their own assigned identities; the read does not
  1157. create an extra identity. `--thread-agent` uses an existing registration token
  1158. cached by NTM for that project when the server requires authenticated reads.
  1159. Thread continuation requires `agent_mail.enabled = true` and the server's
  1160. `summarize_thread` tool. It requests a deterministic summary with LLM refinement
  1161. and raw message examples disabled. A missing, unavailable, mismatched, empty,
  1162. or oversized summary stops the command before project-directory creation,
  1163. hooks, or tmux changes; the prepared context is limited to 32 KiB. The flag
  1164. accepts one thread ID and is unavailable with remote tmux sessions. It remains
  1165. active with `--no-recovery` and `--no-cass-context`, since it is an explicit
  1166. request. Successful JSON output identifies the context with `thread_id` without
  1167. echoing the conversation contents.
  1168. Checkpoint restoration accepts `--as` to recover into a different tmux session
  1169. without replacing the source session or rewriting its checkpoint. The REST
  1170. restore endpoint accepts the same option as `target_session`. A separate session
  1171. still uses the checkpoint's working directory unless `--directory` (REST:
  1172. `custom_directory`) selects another working tree. Restores honor cancellation;
  1173. JSON responses retain the last restore stage, pane count, warnings, and
  1174. interruption status so partially restored sessions can be inspected before retrying.
  1175. Newly spawned agents also record their rendered launch command independently of
  1176. the pane title. Checkpoints preserve that command and its model, persona,
  1177. reasoning effort, and account-profile reference. Restore validates these inputs
  1178. before replacing an existing session, then recreates any configured Claude
  1179. credential isolation for the destination pane. Prepared persona prompt files
  1180. remain external references: a missing file or changed contents stops automatic
  1181. replay. Explicit pane or plugin environment values are not copied into this
  1182. record; recovery reports missing inputs instead of silently substituting the
  1183. current environment. Older panes without a launch record retain the existing
  1184. command-reconstruction path.
  1185. Saved sessions preserve each pane's working directory and the same recorded
  1186. launch settings, so panes in separate worktrees return to their own directories.
  1187. `sessions restore --launch` replays those settings; `sessions resume` also
  1188. replaces the native conversation selector when the save contains a fresh
  1189. provider binding. Recorded commands keep their model, reasoning, persona, and
  1190. account settings instead of taking current defaults. Native resume refuses
  1191. ambiguous shell commands or conflicting conversation selectors before `--force`
  1192. replaces a live session. Older saves without a recorded command retain the
  1193. existing CASR preference. Missing worktrees, changed persona files, unavailable
  1194. profiles, and omitted environment inputs prevent automatic relaunch. Agent
  1195. counts report successful command dispatch; they do not assert that an agent has
  1196. finished starting.
  1197. ### 8. Multi-Project Swarm Execution
  1198. `ntm swarm --json` launches the requested swarm and returns an execution receipt.
  1199. Use `swarm plan` or `--dry-run` to preview allocations without creating sessions.
  1200. ```bash
  1201. ntm swarm plan --scan-dir=/projects --json
  1202. ntm swarm --scan-dir=/projects --json --wait-ready
  1203. ntm swarm --scan-dir=/projects --json --prompt="Run the tests and report failures"
  1204. ```
  1205. The receipt distinguishes planned allocations, created sessions and physical
  1206. panes, agent launches, initial prompt delivery, and optional readiness results.
  1207. Partial failures and cancellation return a nonzero exit status while retaining
  1208. the actual outcomes. Prompts go only to successfully launched agents that pass
  1209. readiness and identity checks; surviving sessions remain available for inspection.
  1210. `--auto-rotate-accounts` starts an acknowledged resident monitor for eligible
  1211. local Claude and Codex panes. It checks CAAM account availability and the actual
  1212. configured launch commands before creating sessions. JSON receipts identify
  1213. eligible panes, declined providers, and each monitor's PID and generation;
  1214. `swarm status --json` checks the resident's live process and heartbeat.
  1215. If monitor startup partially fails, the command returns a nonzero exit status
  1216. and preserves launched agents, successful monitors, and their startup receipts.
  1217. ```bash
  1218. ntm swarm --scan-dir=/projects --auto-rotate-accounts --json
  1219. ntm swarm --scan-dir=/projects --auto-rotate-accounts --force-global-auth-clobber --json
  1220. ```
  1221. This recovery lane requires Linux, default global credentials, and a live
  1222. provider process with a verifiable open main conversation transcript. Codex
  1223. also requires consent through the global-auth flag above or
  1224. `swarm.force_global_auth_clobber = true` in the configuration. Scoped profiles,
  1225. isolated credentials, custom credential homes or providers, and ambiguous
  1226. commands for otherwise eligible panes fail preflight before session creation.
  1227. Unsupported or excluded providers and Codex without global-auth consent can
  1228. launch unmonitored, provided at least one eligible pane remains. A temporary
  1229. lack of transcript evidence defers recovery until another observation; NTM does
  1230. not infer a conversation from the newest file in a worktree. Configured provider
  1231. restrictions and reset horizons still apply.
  1232. Recovery preserves the recorded command and native conversation, verifies the
  1233. replacement process and conversation, and reports account activation separately
  1234. from successful conversation recovery. A provider lock and durable activation
  1235. receipt coordinate multiple sessions: stalled sibling panes can resume using
  1236. the already activated account without repeatedly switching the global account.
  1237. Local session kill and forced checkpoint or saved-session replacement wait for
  1238. their resident to finish any in-flight recovery before destroying the session.
  1239. Remote tmux operations leave local monitors and processes untouched.
  1240. ## Robot Mode and Local API
  1241. NTM has two automation layers:
  1242. - `--robot-*` for local, machine-readable CLI interactions
  1243. - `ntm serve` for REST, SSE, WebSocket, and OpenAPI-backed integrations
  1244. ### Canonical Robot Surfaces
  1245. Start with these:
  1246. ```bash
  1247. ntm --robot-help
  1248. ntm --robot-capabilities
  1249. ntm --robot-status
  1250. ntm --robot-snapshot
  1251. ntm --robot-plan
  1252. ntm --robot-dashboard
  1253. ntm --robot-markdown --compact
  1254. ntm --robot-terse
  1255. ```
  1256. Common task-specific surfaces:
  1257. ```bash
  1258. ntm --robot-send=payments --msg="Summarize current blockers." --type=claude
  1259. ntm --robot-ack=payments --timeout=30s
  1260. ntm --robot-tail=payments --lines=50
  1261. ntm --robot-mail-check --mail-project=payments --urgent-only
  1262. ntm --robot-cass-search="authentication error"
  1263. ```
  1264. Optional CM memory injection (`--with-memory` or `memory.send_injection`) uses
  1265. the selected panes' verified project directory and the target session's daemon.
  1266. Running the command from another checkout cannot select that checkout's memory,
  1267. including when both projects have the same directory name. The JSON memory
  1268. receipt identifies the queried workspace or explains why injection was skipped.
  1269. Remote sessions and unresolved or mixed project scopes skip local CM retrieval
  1270. and continue ordinary prompt delivery. Context-pack builds use the same explicit
  1271. workspace scope.
  1272. With `--track`, successful acknowledgment reports memory feedback to the daemon
  1273. that supplied the rules. Changing daemon PID records while the send is pending
  1274. does not redirect that feedback. Canceling the command stops pending memory
  1275. retrieval and acknowledgment tracking.
  1276. ### REST, SSE, WebSocket, and OpenAPI
  1277. Run the local server:
  1278. ```bash
  1279. ntm serve
  1280. ```
  1281. Set the default project with `ntm serve --project-dir /absolute/project/path`.
  1282. `PATCH /api/v1/config` changes it at runtime for every caller:
  1283. `{"project_dir": "/absolute/other/project"}` selects another project, and
  1284. `{"project_dir": ""}` or `{"project_dir": null}` resets it to the
  1285. `--project-dir` value (no project if the server started without one). Omitting
  1286. `project_dir` leaves it unchanged. `GET /api/v1/config` reports the current
  1287. `project_dir` and the reset target as `startup_project_dir`.
  1288. The selection scopes later requests on every project-scoped route, including
  1289. mail, beads, jobs, and pipelines. Jobs and pipeline runs already admitted, and
  1290. mail requests already in flight, keep the project they started with. The
  1291. target must be an existing directory, so a reset returns 400 and changes
  1292. nothing if the startup directory has since been removed.
  1293. Agent Mail operations under `/api/v1/mail/` and file reservation operations under
  1294. `/api/v1/reservations` also accept a `project` query parameter, so agents in
  1295. multiple projects can share one server:
  1296. ```bash
  1297. curl --get http://localhost:7337/api/v1/mail/inbox \
  1298. --data-urlencode 'project=/absolute/other/project' \
  1299. --data-urlencode 'agent_name=BlueLake'
  1300. curl --get http://localhost:7337/api/v1/reservations \
  1301. --data-urlencode 'project=/absolute/other/project' \
  1302. --data-urlencode 'agent_name=BlueLake'
  1303. ```
  1304. The override must name an existing absolute directory on the server host.
  1305. It applies to that request's mail agents, messages, inbox, search, threads, and
  1306. contacts, and to reservation creation, listing, lookup, conflict inspection,
  1307. release, renewal, and force-release. Omit it to use the server's configured
  1308. project. Each request keeps its chosen project throughout execution, including
  1309. retries with an `Idempotency-Key`; selecting a project does not change the server
  1310. configuration. Changing the default project separates subsequent retries from
  1311. the previous project's cached results. Force-release approvals remain bound to
  1312. the project and reservation the operator reviewed.
  1313. Mail read and acknowledgement events, reservation events, and reservation
  1314. approval-request events include `project_key` so subscribers can distinguish
  1315. identically named agents and reservation IDs in different projects. The mail
  1316. health endpoint checks the shared service and takes no project selector. Other
  1317. API groups continue to use the configured server project.
  1318. Important surfaces:
  1319. - REST API under `/api/v1`
  1320. - server-sent events at `/events`
  1321. - WebSocket subscriptions at `/api/v1/ws`
  1322. - health check at `/health`
  1323. - generated OpenAPI spec at [`docs/openapi.json`](docs/openapi.json)
  1324. Generate or refresh the OpenAPI document:
  1325. ```bash
  1326. ntm openapi generate
  1327. ntm openapi generate --stdout
  1328. ```
  1329. ### Embedded Web Dashboard (`ntm web`)
  1330. Launch the embedded Next.js operator dashboard together with the REST and WebSocket control plane:
  1331. ```bash
  1332. # Local loopback mode (binds 127.0.0.1:7337)
  1333. ntm web
  1334. # Remote / LAN deployment with API-key authentication
  1335. ntm web --host 0.0.0.0 --port 7337 --auth-mode api_key --api-key "$NTM_API_KEY"
  1336. # OIDC JWT authentication
  1337. ntm web --host 0.0.0.0 --port 7337 --auth-mode oidc --oidc-issuer https://idp.example.com --oidc-audience ntm-web --oidc-jwks-url https://idp.example.com/.well-known/jwks.json
  1338. # Mutual TLS (mTLS) client-certificate authentication
  1339. ntm web --host 0.0.0.0 --port 7337 --auth-mode mtls --mtls-cert server.pem --mtls-key server-key.pem --mtls-ca ca.pem
  1340. ```
  1341. When `--auth-mode` is set to `api_key`, `oidc`, or `mtls`:
  1342. - Static dashboard HTML/JS/CSS assets (`/`, `/connect`, `/_next/*`) load without credentials so the browser can render `/connect` and prompt for an API key or bearer token.
  1343. - Every `/api/*`, `/ws/*`, and `/events` endpoint enforces authentication and RBAC.
  1344. - Real-time WebSocket connections exchange the credential via `POST /api/v1/auth/ws-ticket` for a 30-second single-use upgrade ticket (`GET /api/v1/ws?ticket=...`) so bearer tokens and API keys never appear in URLs or request logs.
  1345. ## Command Map
  1346. | Command group | Commands | What it covers |
  1347. | --- | --- | --- |
  1348. | **Bootstrap & Setup** | `quick`, `init`, `setup`, `deps`, `doctor`, `shell`, `bind`, `completion`, `level`, `tutorial`, `version`, `upgrade` | Project initialization, environment diagnostics, shell/tmux integration, and CLI lifecycle |
  1349. | **Session Lifecycle & Navigation** | `create`, `spawn`, `add`, `adopt`, `scale`, `respawn`, `list`, `sessions`, `status`, `attach`, `view`, `zoom`, `switch`, `overlay`, `dashboard`, `palette`, `kill`, `cleanup` | Creating, scaling, adopting, inspecting, focusing, and tearing down tmux agent sessions |
  1350. | **Prompting & Operator Loop** | `send`, `preflight`, `replay`, `interrupt`, `wait`, `watch`, `codex`, `controller`, `rotate`, `quota` | Prompt validation/delivery, state waits, live pane control, controller agents, and seat/quota rotation |
  1351. | **Output Inspection & Analytics** | `activity`, `attention`, `summary`, `health`, `logs`, `errors`, `extract`, `copy`, `save`, `get-all-session-text`, `diff`, `grep`, `analytics`, `metrics` | Pane output capture, operator attention state (`ack`/`snooze`/`pin`/`dismiss`), error/code extraction, cross-pane diffs, regex search, and telemetry |
  1352. | **Work Triage & Swarm Orchestration** | `work`, `work-snapshot`, `beads`, `claim`, `assign`, `rebalance`, `review-queue`, `coordinator`, `swarm` | Graph-aware Beads prioritization, restart-safe snapshots, assignment, load balancing, and multi-project swarms |
  1353. | **Agent Mail, Git & File Locks** | `mail`, `message`, `mapping`, `lock`, `locks`, `unlock`, `conflicts`, `git`, `repo`, `worktrees` | Agent Mail messaging, pane-to-agent identity mapping, advisory file reservations, and Git worktree isolation |
  1354. | **Context, Memory & Search** | `context`, `cass`, `search`, `memory`, `handoff`, `resume` | Token-budgeted context packs, CASS cross-agent search, procedural memory (`cm`), and session handoffs |
  1355. | **Safety, Policy & Redaction** | `safety`, `policy`, `approve`, `guards`, `hooks`, `scan`, `bugs`, `redact`, `scrub` | Destructive command protection, SLB approvals, pre-commit guards, UBS bug scanning, and secret redaction |
  1356. | **Durable State & Forensics** | `checkpoint`, `rollback`, `timeline`, `history`, `audit`, `changes`, `support-bundle`, `webhook-outbox` | Session checkpoints/rollbacks, cryptographic audit trails, file attribution, support bundles, and webhook recovery |
  1357. | **Ensembles, Pipelines & Templates** | `ensemble`, `modes`, `pipeline`, `workflows`, `recipes`, `template`, `session-templates`, `agents`, `personas`, `profiles`, `profile`, `models`, `plugins` | Multi-agent reasoning ensembles, DAG pipelines, reusable recipes/personas, local models, and plugins |
  1358. | **Control Plane & Web Surfaces** | `serve`, `web`, `openapi`, `kernel`, `config`, `help` | HTTP/REST/SSE/WebSocket daemon, embedded Next.js dashboard, OpenAPI schema generation, kernel registry, and strict TOML config |
  1359. `ntm --help` remains the canonical full command reference.
  1360. ## Configuration and Project Assets
  1361. NTM supports user-level and project-level assets.
  1362. ### User-Level
  1363. - main config: `~/.config/ntm/config.toml`
  1364. - recipes: `~/.config/ntm/recipes.toml`
  1365. - workflows: `~/.config/ntm/workflows/`
  1366. - personas/profiles: `~/.config/ntm/personas.toml`
  1367. - policy: `~/.ntm/policy.yaml`
  1368. ### Project-Level
  1369. Project-local assets live under `.ntm/` and override built-ins and user defaults where appropriate.
  1370. - `.ntm/workflows/`
  1371. - `.ntm/pipelines/`
  1372. - `.ntm/personas.toml`
  1373. - `.ntm/recipes.toml`
  1374. - `.ntm/config.toml` for project-scoped settings such as additional assignment approval labels
  1375. Checkpoints are per user, not per project: they live under
  1376. `~/.local/share/ntm/checkpoints/<session>/`.
  1377. Useful config commands:
  1378. ```bash
  1379. ntm config init
  1380. ntm config show
  1381. ntm config diff
  1382. ntm config get projects_base
  1383. ntm config edit
  1384. ntm config reset
  1385. ```
  1386. Configuration loading is strict: unknown fields are errors. The unused TOML
  1387. `[health]` section has been removed; migrate restart and monitoring settings to
  1388. `[resilience]` (`auto_restart`, `max_restarts`, `restart_delay_seconds`,
  1389. `health_check_seconds`, and `crash_threshold`). The `ntm health` command remains
  1390. available and is unrelated to that removed config section.
  1391. ### CAAM Seat Selection (opt-in, default off)
  1392. If you run several interchangeable subscription seats through
  1393. [CAAM](https://github.com/Dicklesworthstone/caam) — three Codex Pro logins, say
  1394. — NTM can choose which one a new pane launches on instead of leaving that to
  1395. whatever your agent command template pins:
  1396. ```toml
  1397. [integrations.caam]
  1398. seat_selection = true
  1399. ```
  1400. With the key on, a `spawn`/`add` pane that carries **no** persona asks
  1401. `caam limits <provider> --rank earliest-reset-headroom` and launches under the
  1402. matching `codex-<profile>` / `claude-<profile>` persona. The rank spends the
  1403. included allowance that refreshes **soonest while it still has headroom** and
  1404. preserves the later-resetting reserve seat. (It is deliberately not
  1405. `caam precheck --best`, which ranks lowest utilization and would pick the idle
  1406. reserve — the opposite of the policy.)
  1407. The semantics, exactly:
  1408. - **A pin always wins.** `--persona=codex-acme`, `--profile-set`, and recipe
  1409. personas are never re-ranked and never overridden. Only a pane with no
  1410. persona at all is placed.
  1411. - **One query per provider per command.** `ntm add --cod=4` shells out to caam
  1412. once, not four times; the ranked seat is a property of the pool.
  1413. - **Later `ntm add`s re-rank.** A pane added to a running swarm is a new pane
  1414. and gets the seat that is right now, not the one that was right at spawn.
  1415. (Answers are memoized for 20 seconds, so two adds in quick succession share
  1416. one ranking — provider windows do not move on that timescale.) Credentials
  1417. inside an already-running pane are never rotated.
  1418. - **An unreadable pool skips those panes, loudly.** If caam is missing, times
  1419. out, or ranks the pool and finds nothing with included headroom, no agent is
  1420. launched into the affected panes and the reason is printed (and reported in
  1421. `seat_skips` under `--json`). In `ntm add` the pane is never created at all;
  1422. in `ntm spawn` the panes were already split before seats were resolved, so a
  1423. refused one is left as a plain shell and named in the warning. Siblings on a
  1424. provider that answered still come up: `ntm add --cod=2 --cc=2` with an
  1425. exhausted Codex pool brings up the two Claude panes. A skipped pane never
  1426. falls through to a static profile pin — that fallthrough is the failure this
  1427. exists to prevent.
  1428. - **`ntm scale` honors it too.** Scale-up reports the number of panes that
  1429. actually launched, not the number requested, and surfaces each refusal.
  1430. - **Only Claude and Codex are affected.** `caam limits` answers for no other
  1431. provider, so gemini/grok/ollama/plugin panes are untouched.
  1432. `seat_selection` is unrelated to `auto_failover` in the same table, despite
  1433. sitting next to it: `auto_failover` swaps the **host** credential mid-session
  1434. for a pane that hit a rate limit; `seat_selection` only chooses which account a
  1435. **new** pane launches under. Enabling one does not enable the other, and
  1436. `seat_selection` starts no caam subprocess when it is off.
  1437. Requires caam >= v0.1.19 (the release that added the
  1438. `earliest-reset-headroom` rank mode).
  1439. ### Rano Network Activity
  1440. [rano](https://github.com/Dicklesworthstone/rano)'s monitor records each agent
  1441. process's connect/close events into an SQLite database. ntm reads that history
  1442. (`rano export`) for `--robot-rano-stats`, the dashboard's Network Activity panel
  1443. and the process-triage monitor's network signal; it never starts the monitor.
  1444. Point ntm at the database the monitor writes (rano's default is
  1445. `observer.sqlite` in the monitor's working directory):
  1446. ```toml
  1447. [integrations.rano]
  1448. sqlite_path = "/path/to/observer.sqlite" # what you pass as `rano --sqlite`
  1449. ```
  1450. The counts are connections, not requests or bytes. With no database at that
  1451. path, `--robot-rano-stats` fails with `DEPENDENCY_MISSING` and the panel shows
  1452. why, instead of reporting zero traffic. Details: `docs/rano-stats.md`.
  1453. ### Agent Plugins
  1454. Custom agent types load from the `agents/` directory that sits next to the
  1455. selected config file: `~/.config/ntm/agents/*.toml` by default,
  1456. `$XDG_CONFIG_HOME/ntm/agents/` under an XDG override, or
  1457. `<dir-of-config>/agents/` with an explicit `--config`. Each TOML declares a
  1458. name/alias (which become `--<name>`/`--<alias>` spawn, `resume --spawn`, and `send` selectors), a
  1459. command template, and optional `[agent.readiness]` regexes that drive
  1460. idle/working/error classification for `status`, `activity`, `--robot-tail`,
  1461. `--robot-activity`, `--robot-is-working`, `--robot-health`, and `--verify-boot`
  1462. exactly like the built-in agents. NTM never modifies files in
  1463. `agents/` — an existing preset you have customised is yours.
  1464. Oh My Pi is now a built-in agent type (see [Oh My Pi](#oh-my-pi-omp)), so the
  1465. former `examples/agents/omp.toml` plugin preset is no longer needed. A leftover
  1466. `~/.config/ntm/agents/omp.toml` is harmless: built-in flags and the built-in
  1467. omp detectors take precedence over a plugin of the same name.
  1468. #### Pi coding agent (`pi`)
  1469. Install the [pi preset](examples/agents/pi.toml) as `agents/pi.toml` beside
  1470. your selected NTM configuration. Authenticate pi and configure its project
  1471. trust before automated launches. The preset preserves pi's own defaults;
  1472. model, thinking level, and persona system prompts are supplied when requested.
  1473. ```bash
  1474. ntm spawn swarm --pi=2
  1475. ntm spawn swarm --pi=1:MODEL:high
  1476. ntm --robot-spawn=automated --spawn-pi=2:MODEL:high --spawn-wait
  1477. ntm send swarm --pi "Review the changes and run the tests"
  1478. ntm sessions save swarm
  1479. ntm sessions resume swarm --name recovered --native
  1480. ntm resume next-session --from path/to/handoff --spawn --pi=2 --omp=1
  1481. ```
  1482. Pi has its own session provider and terminal parser. Its JSONL header supplies
  1483. the session ID and working directory, including when a transcript was renamed.
  1484. Discovery honors `--session-dir`, `PI_CODING_AGENT_SESSION_DIR`, and
  1485. `PI_CODING_AGENT_DIR`, with `~/.pi/agent/sessions/<encoded-cwd>/` as the default.
  1486. Files in a shared store are matched by their header's working directory;
  1487. malformed headers and ambiguous ID prefixes are not promoted to exact bindings.
  1488. Explicit `--session` and `--session-id` selectors are recognized during
  1489. discovery. Saved-session resume resolves the exact saved ID to an existing
  1490. transcript before launching `pi --session <path>`, retaining the original
  1491. model, thinking, prompt, and environment settings. A missing or ambiguous
  1492. transcript stops resume before an existing tmux session can be replaced.
  1493. Saved sessions retain the exact discovered pi transcript path in their private
  1494. save file, so resume still selects the original transcript when the caller's
  1495. session directory, agent directory, or home environment changes. A missing or
  1496. changed original transcript is an error even if another store contains the same
  1497. session ID. This additional stored reference is omitted from public state
  1498. fields; native resume commands still contain the selected transcript path.
  1499. Managed `spawn` and `add` launches assign each fresh pi pane a distinct
  1500. `--session-id` and record it with the launch command. Simultaneous panes in the
  1501. same working directory can therefore be saved and resumed without guessing
  1502. from transcript timestamps. Explicit pi session selectors remain authoritative.
  1503. Workflow template profiles named `pi` also retain their plugin type and count.
  1504. Robot spawning loads registered agents from the selected configuration and
  1505. accepts the same count, model, and thinking-level grammar through
  1506. `--spawn-<agent>` flags, including registered aliases. Recipes can mix pi with
  1507. built-in agents and retain each instance's model and thinking level. Plugin
  1508. readiness is shared by initial startup and pane restart, and the detached
  1509. monitor retains the selected configuration. Plugin environment values travel
  1510. through the private launch transport; saved launch metadata records their
  1511. names rather than their values.
  1512. For pipelines and workflows, pi's standard composer, unsent draft, cwd, and
  1513. usage rows are excluded from response evidence. Blank redraws retain the last
  1514. trusted boundary. A complete repaint can recover through a unique echo of the
  1515. current delivered prompt; an idle pane alone cannot establish that a
  1516. replacement screen answers the current turn. Unknown custom chrome, lost
  1517. prompt boundaries, and unrelated replacement screens remain conservative
  1518. refusals. Oh My Pi continues to use its separate `omp` session and terminal
  1519. behavior.
  1520. Response detection also accounts for pi rendering submitted Markdown. A
  1521. waiting pipeline step requires a unique echo of its current delivered prompt
  1522. and response text after that echo; workflow verdict matches must start after
  1523. the echo without changing the original regular-expression anchors. Supported
  1524. headings, emphasis, lists, and code retain their expected visible identity.
  1525. Bare URLs, angle-delimited URLs and email addresses also work, as do Markdown
  1526. links whose plain label exactly matches the destination. Named or formatted
  1527. links remain unsupported when their visible text depends on terminal hyperlink
  1528. support.
  1529. Prompts with unsupported or terminal-dependent rendering are refused before
  1530. automated response-waiting delivery; use plain text for those prompts. Explicit
  1531. pipeline `wait: none` remains fire-and-forget. Operator acceptance of an
  1532. uncertain pi delivery uses the same repaint checks, and normal resume collects
  1533. the response without sending the prompt again. Old in-flight pi receipts that
  1534. lack the rendered prompt identity require inspection and a deliberate restart.
  1535. ## Design Principles
  1536. ### No Silent Data Loss
  1537. Stateful operations are designed to leave artifacts behind: checkpoints, timelines, audit
  1538. records, pipeline state, and serialized robot/API responses.
  1539. ### Graceful Degradation
  1540. Optional integrations such as Agent Mail, `bv`, `cass`, or worktree helpers make NTM stronger,
  1541. but the system is designed to remain locally useful without pretending missing tools are present.
  1542. ### Idempotent Orchestration
  1543. Robot mode, durable stores, and resumable workflows are designed so operators and agents can
  1544. re-issue state queries and recover from interruptions without inventing undocumented side channels.
  1545. ### Recoverable State
  1546. Sessions, pipelines, attention feeds, approvals, and history all have explicit recovery paths.
  1547. ### Auditable Actions
  1548. NTM favors explicit logs, status surfaces, and durable state over invisible orchestration magic.
  1549. ### Safe by Default
  1550. Destructive operations, guard rails, and approval workflows are treated as core product behavior,
  1551. not bolt-on scripts.
  1552. ## Architecture
  1553. ```text
  1554. +---------------------------+
  1555. | Human Operator / Agent |
  1556. | CLI, TUI, Robot, REST |
  1557. +-------------+-------------+
  1558. |
  1559. v
  1560. +---------------------------+
  1561. | NTM |
  1562. |---------------------------|
  1563. | session orchestration |
  1564. | dashboard + palette |
  1565. | work triage + assignment |
  1566. | safety + policy + approve |
  1567. | pipelines + checkpoints |
  1568. | serve + robot surfaces |
  1569. +------+------+-------------+
  1570. | |
  1571. | +--------------------------+
  1572. | |
  1573. v v
  1574. +---------------------------+ +---------------------------+
  1575. | Durable state + event bus | | Optional integrations |
  1576. | checkpoints, history, | | br, bv, Agent Mail, cass, |
  1577. | timelines, audit, alerts | | dcg, pt, worktrees |
  1578. +-------------+-------------+ +---------------------------+
  1579. |
  1580. v
  1581. +------------------------------+
  1582. | tmux sessions and panes |
  1583. | Claude / Codex / AGY / Grok |
  1584. | labeled multi-agent work |
  1585. +------------------------------+
  1586. ```
  1587. ## Installation
  1588. ### Install Script
  1589. ```bash
  1590. curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh?$(date +%s)" | bash -s -- --easy-mode
  1591. ```
  1592. ### Homebrew
  1593. ```bash
  1594. brew install dicklesworthstone/tap/ntm
  1595. ```
  1596. ### Docker
  1597. Multi-arch images (`linux/amd64`, `linux/arm64`) are published to GitHub
  1598. Container Registry via DSR (`ghcr.io/dicklesworthstone/ntm`), tagged by semver
  1599. (`1`, `1.38`, `1.38.0`) and commit SHA:
  1600. ```bash
  1601. docker pull ghcr.io/dicklesworthstone/ntm:1
  1602. docker run --rm -it ghcr.io/dicklesworthstone/ntm:1
  1603. ```
  1604. Or build locally:
  1605. ```bash
  1606. docker build -t ntm .
  1607. docker run --rm -it ntm
  1608. ```
  1609. ### From Source
  1610. ```bash
  1611. git clone https://github.com/Dicklesworthstone/ntm.git
  1612. cd ntm
  1613. go install ./cmd/ntm # or: make build
  1614. ```
  1615. ## Troubleshooting
  1616. ### `tmux not found`
  1617. Install `tmux` first, then re-run:
  1618. ```bash
  1619. ntm deps -v
  1620. ```
  1621. ### Agent panes start empty or an agent CLI fails immediately
  1622. NTM can only launch tools that are installed and discoverable in `PATH`.
  1623. Use `ntm deps -v` to check what it sees.
  1624. ### `claude`, `codex`, `agy`, `grok`, or `gemini` not detected over SSH / tmux / non-login shells
  1625. NTM discovers agent CLIs via the `PATH` of the **runtime environment it is launched in** —
  1626. not the `PATH` of your interactive login shell. Tools installed under npm-global or
  1627. `~/.local/bin` are often added to `PATH` by your `~/.bashrc` / `~/.zshrc` / `~/.profile`,
  1628. which a non-interactive or non-login shell (a bare SSH command, a detached tmux server, a
  1629. systemd unit, a CI runner) does not source. In that case `ntm deps -v` reports the agents as
  1630. missing even though they work fine in your normal terminal.
  1631. First, confirm what *NTM's* environment actually resolves, under the same shell/SSH/tmux
  1632. context where you run NTM:
  1633. ```bash
  1634. command -v claude
  1635. command -v codex
  1636. command -v agy
  1637. command -v grok
  1638. command -v gemini
  1639. ntm deps -v
  1640. ```
  1641. If those `command -v` checks come up empty here but succeed in your interactive shell, the
  1642. fix is to put the missing directories on `PATH` before launching NTM. The most robust option
  1643. is a small wrapper that exports the right `PATH` and then `exec`s NTM (paths vary by host):
  1644. ```bash
  1645. #!/usr/bin/env bash
  1646. # ~/bin/ntm-wrapper — ensure agent CLIs are on PATH, then hand off to ntm.
  1647. export PATH="$HOME/.npm-global/bin:$HOME/.local/bin:$PATH"
  1648. exec ntm "$@"
  1649. ```
  1650. Make it executable (`chmod +x ~/bin/ntm-wrapper`) and invoke that instead of `ntm`. Re-run
  1651. `ntm deps -v` through the wrapper to confirm all listed CLIs are now detected.
  1652. ### A work command has nothing useful to say
  1653. `ntm work ...` depends on running inside a repo with Beads/BV data available.
  1654. If you are outside the project root, change directories or bootstrap the repo first.
  1655. ### Mail, locks, or overseer commands say the server is unavailable
  1656. Those surfaces depend on Agent Mail being configured and reachable. NTM will still work for
  1657. session orchestration without it.
  1658. ### Pipeline resume or cleanup does not see the state you expect
  1659. Make sure the relevant session/project is using the intended project directory. Project-scoped
  1660. state lives under that directory's `.ntm/` tree.
  1661. ## FAQ
  1662. ### Does NTM replace tmux?
  1663. No. NTM is a structured orchestration layer on top of `tmux`.
  1664. ### Can I use it with one agent instead of a swarm?
  1665. Yes. It is perfectly fine to start with one Claude or Codex pane and only scale up when needed.

Lines 2,001–2,050 are not shown. The link to the file on GitHub has every line.

install.sh · Bundled script · 998 lines · 5 findings marked
  1. #!/usr/bin/env bash
  2. #
  3. # NTM Install Script
  4. # https://github.com/Dicklesworthstone/ntm
  5. #
  6. # Usage:
  7. # curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 7 on GitHub
  8. #
  9. # Options:
  10. # --version=TAG Install specific version (default: latest)
  11. # --dir=PATH Install to custom directory (default: /usr/local/bin or ~/.local/bin)
  12. # --no-shell Skip shell integration prompt
  13. # --easy-mode Non-interactive: auto-configure shell integration and PATH
  14. #
  15. # The script will:
  16. # 1. Detect your platform (OS and architecture)
  17. # 2. Download the pre-compiled binary from GitHub releases
  18. # 3. Install to a directory in your PATH
  19. # 4. Optionally set up shell integration
  20. set -euo pipefail
  21. REPO_OWNER="Dicklesworthstone"
  22. REPO_NAME="ntm"
  23. BIN_NAME="ntm"
  24. # Temp directory management
  25. TMP_DIRS=()
  26. cleanup_tmp_dirs() {
  27. local dir
  28. for dir in "${TMP_DIRS[@]:-}"; do
  29. # Use if statement to avoid set -e triggering on empty dir check
  30. if [ -n "$dir" ]; then
  31. rm -rf "$dir"
  32. fi
  33. done
  34. }
  35. trap cleanup_tmp_dirs EXIT
  36. # Defaults
  37. VERSION=""
  38. INSTALL_DIR=""
  39. NO_SHELL=false
  40. EASY_MODE=false
  41. # Parse arguments
  42. for arg in "$@"; do
  43. case $arg in
  44. --version=*)
  45. VERSION="${arg#*=}"
  46. ;;
  47. --dir=*)
  48. INSTALL_DIR="${arg#*=}"
  49. ;;
  50. --no-shell)
  51. NO_SHELL=true
  52. ;;
  53. --easy-mode)
  54. EASY_MODE=true
  55. ;;
  56. --help|-h)
  57. cat << 'EOF'
  58. NTM Install Script
  59. Usage: curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 67 on GitHub
  60. Options:
  61. --version=TAG Install specific version (default: latest)
  62. --dir=PATH Install to custom directory
  63. --no-shell Skip shell integration prompt
  64. --easy-mode Non-interactive: auto-configure shell integration and PATH
  65. --help Show this help
  66. Examples:
  67. # Install latest version
  68. curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 78 on GitHub
  69. # Install specific version
  70. curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh | bash -s -- --version=v1.0.0
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 81 on GitHub
  71. # Install to custom directory
  72. curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/ntm/main/install.sh | bash -s -- --dir=/opt/bin
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 84 on GitHub
  73. EOF
  74. exit 0
  75. ;;
  76. *)
  77. echo "Unknown option: $arg"
  78. exit 1
  79. ;;
  80. esac
  81. done
  82. # Output helpers
  83. print_info() { printf "\033[1;34m==>\033[0m %s\n" "$1"; }
  84. print_success() { printf "\033[1;32m==>\033[0m %s\n" "$1"; }
  85. print_error() { printf "\033[1;31mError:\033[0m %s\n" "$1" >&2; }
  86. print_warn() { printf "\033[1;33mWarning:\033[0m %s\n" "$1"; }
  87. # Detect OS and architecture
  88. detect_platform() {
  89. local os arch
  90. os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  91. arch="$(uname -m)"
  92. case "$os" in
  93. linux) os="linux" ;;
  94. darwin) os="darwin" ;;
  95. mingw*|msys*|cygwin*) os="windows" ;;
  96. freebsd) os="freebsd" ;;
  97. *) print_error "Unsupported OS: $os"; return 1 ;;
  98. esac
  99. case "$arch" in
  100. x86_64|amd64) arch="amd64" ;;
  101. arm64|aarch64) arch="arm64" ;;
  102. armv7*|armhf) arch="armv7" ;;
  103. *) print_error "Unsupported architecture: $arch"; return 1 ;;
  104. esac
  105. echo "${os}_${arch}"
  106. }
  107. # Get the best install directory
  108. default_install_dir() {
  109. if [ -n "${INSTALL_DIR:-}" ]; then
  110. echo "$INSTALL_DIR"
  111. return
  112. fi
  113. # Prefer writable standard prefixes
  114. for dir in /usr/local/bin /opt/homebrew/bin /opt/local/bin; do
  115. if [ -d "$dir" ] && [ -w "$dir" ]; then
  116. echo "$dir"
  117. return
  118. fi
  119. done
  120. # Fall back to the first writable entry in PATH
  121. IFS=: read -r -a path_entries <<<"${PATH:-}"
  122. for dir in "${path_entries[@]}"; do
  123. if [ -d "$dir" ] && [ -w "$dir" ]; then
  124. echo "$dir"
  125. return
  126. fi
  127. done
  128. # Last resort: ~/.local/bin
  129. echo "${HOME}/.local/bin"
  130. }
  131. # Check if a command exists
  132. has_cmd() {
  133. command -v "$1" >/dev/null 2>&1
  134. }
  135. # Print the platform-appropriate tmux install command
  136. tmux_install_hint() {
  137. local os
  138. os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  139. if [ "$os" = "darwin" ]; then
  140. echo "brew install tmux"
  141. return
  142. fi
  143. if has_cmd apt-get || has_cmd apt; then
  144. echo "sudo apt install tmux"
  145. elif has_cmd dnf; then
  146. echo "sudo dnf install tmux"
  147. elif has_cmd pacman; then
  148. echo "sudo pacman -S tmux"
  149. elif has_cmd brew; then
  150. echo "brew install tmux"
  151. else
  152. echo "install tmux with your system package manager"
  153. fi
  154. }
  155. # tmux is NTM's one hard runtime dependency. Check for it and print the exact
  156. # install command for this platform. Deliberately warn-and-continue: the
  157. # binary install itself does not need tmux, and package-manager side effects
  158. # are not an installer's call — so we do NOT auto-install.
  159. check_tmux() {
  160. if has_cmd tmux; then
  161. print_info "Found tmux: $(command -v tmux)"
  162. return 0
  163. fi
  164. print_warn "tmux not found — NTM requires tmux to run (it is the one hard dependency)."
  165. echo ""
  166. echo " Install it with:"
  167. echo " $(tmux_install_hint)"
  168. echo ""
  169. echo " Then re-run 'ntm doctor' to verify your setup."
  170. echo ""
  171. print_warn "Continuing the install; ntm will not work until tmux is installed."
  172. return 0
  173. }
  174. is_release_version() {
  175. local version="${1#v}"
  176. [[ "$version" =~ ^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z][0-9A-Za-z.-]*)?([+][0-9A-Za-z][0-9A-Za-z.-]*)?$ ]]
  177. }
  178. normalize_release_version() {
  179. local version="$1"
  180. if ! is_release_version "$version"; then
  181. print_error "Invalid version: $version (expected vX.Y.Z or X.Y.Z)"
  182. return 1
  183. fi
  184. printf 'v%s\n' "${version#v}"
  185. }
  186. # Download a file
  187. download_file() {
  188. local url="$1"
  189. local dest="$2"
  190. if has_cmd curl; then
  191. curl -fsSL "$url" -o "$dest" || return 1
  192. elif has_cmd wget; then
  193. wget -q "$url" -O "$dest" || return 1
  194. else
  195. print_error "Neither curl nor wget found. Please install one."
  196. return 1
  197. fi
  198. }
  199. # Probe-download a file that is allowed to be missing. Identical to
  200. # download_file except the transport tool's own stderr is suppressed, so an
  201. # expected 404 on one candidate does not print a scary error while a later
  202. # candidate goes on to succeed. Real failures are still reported via the
  203. # non-zero return code, which callers must handle.
  204. try_download_file() {
  205. local url="$1"
  206. local dest="$2"
  207. if has_cmd curl; then
  208. curl -fsSL "$url" -o "$dest" 2>/dev/null || return 1
  209. elif has_cmd wget; then
  210. wget -q "$url" -O "$dest" 2>/dev/null || return 1
  211. else
  212. print_error "Neither curl nor wget found. Please install one."
  213. return 1
  214. fi
  215. }
  216. # Get the latest release info from GitHub
  217. get_latest_release() {
  218. local url="https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/releases/latest"
  219. if has_cmd curl; then
  220. curl -fsSL "$url" 2>/dev/null || return 1
  221. elif has_cmd wget; then
  222. wget -qO- "$url" 2>/dev/null || return 1
  223. else
  224. return 1
  225. fi
  226. }
  227. resolve_latest_version_from_redirect() {
  228. local url="https://github.com/${REPO_OWNER}/${REPO_NAME}/releases/latest"
  229. local effective_url tag
  230. if has_cmd curl; then
  231. effective_url=$(curl -fsSL -o /dev/null -w '%{url_effective}' "$url" 2>/dev/null) || return 1
  232. elif has_cmd wget; then
  233. effective_url=$(
  234. wget -S --spider "$url" 2>&1 |
  235. awk 'tolower($1) == "location:" { loc = $2 } END { sub(/\r$/, "", loc); print loc }'
  236. ) || return 1
  237. [[ -n "$effective_url" ]] || return 1
  238. else
  239. return 1
  240. fi
  241. tag="${effective_url##*/}"
  242. if is_release_version "$tag"; then
  243. normalize_release_version "$tag"
  244. return 0
  245. fi
  246. return 1
  247. }
  248. # Get a specific tagged release info from GitHub
  249. get_release_by_tag() {
  250. local version="$1"
  251. local url="https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/releases/tags/${version}"
  252. if has_cmd curl; then
  253. curl -fsSL "$url" 2>/dev/null || return 1
  254. elif has_cmd wget; then
  255. wget -qO- "$url" 2>/dev/null || return 1
  256. else
  257. return 1
  258. fi
  259. }
  260. # Extract version from release JSON
  261. extract_version() {
  262. # GitHub emits one release object with a unique, unescaped top-level
  263. # tag_name. Track strings and nesting so compact JSON, nested metadata,
  264. # and quoted release prose cannot change which field supplies the tag.
  265. # This is a bounded field scanner, not a general JSON decoder: escapes
  266. # are retained, and normalize_release_version still validates the result.
  267. # Drain the input after finding the tag to avoid SIGPIPE under pipefail.
  268. LC_ALL=C awk '
  269. found || finished || invalid { next }
  270. {
  271. for (i = 1; i <= length($0); i++) {
  272. ch = substr($0, i, 1)
  273. if (quoted) {
  274. if (escaped) {
  275. if (collect) token = token "\\" ch
  276. escaped = 0
  277. } else if (ch == "\\") {
  278. escaped = 1
  279. } else if (ch == "\"") {
  280. quoted = 0
  281. if (depth == 1 && state == "key") {
  282. key = token
  283. state = "colon"
  284. } else if (depth == 1 && state == "value") {
  285. if (key == "tag_name") {
  286. version = token
  287. found = 1
  288. next
  289. }
  290. state = "done"
  291. }
  292. } else if (collect) {
  293. token = token ch
  294. }
  295. continue
  296. }
  297. if (ch ~ /^[[:space:]]$/) {
  298. continue
  299. }
  300. if (!started) {
  301. if (ch != "{") {
  302. invalid = 1
  303. next
  304. }
  305. started = 1
  306. depth = 1
  307. state = "key"
  308. } else if (ch == "\"") {
  309. quoted = 1
  310. token = ""
  311. collect = depth == 1 && (state == "key" || (state == "value" && key == "tag_name"))
  312. } else if (ch == "{" || ch == "[") {
  313. depth++
  314. } else if (ch == "}" || ch == "]") {
  315. depth--
  316. if (depth == 0) {
  317. finished = 1
  318. next
  319. }
  320. } else if (depth == 1 && ch == ":" && state == "colon") {
  321. state = "value"
  322. } else if (depth == 1 && ch == ",") {
  323. state = "key"
  324. } else if (depth == 1 && state == "value") {
  325. state = "done"
  326. }
  327. }
  328. # JSON strings cannot contain literal newlines.
  329. if (quoted) {
  330. invalid = 1
  331. }
  332. }
  333. END { if (found && !invalid) print version }
  334. '
  335. }
  336. # Find the best asset name for a platform from release JSON
  337. find_asset_name() {
  338. local platform="$1"
  339. local release_json="$2"
  340. local asset_name
  341. if [[ "$platform" == windows_* ]]; then
  342. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_${platform}\\.zip\"" | \
  343. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  344. if [ -n "$asset_name" ]; then
  345. printf '%s\n' "$asset_name"
  346. return 0
  347. fi
  348. fi
  349. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_[^\"]*_${platform}\\.tar\\.gz\"" | \
  350. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  351. if [ -n "$asset_name" ]; then
  352. printf '%s\n' "$asset_name"
  353. return 0
  354. fi
  355. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_${platform}\\.tar\\.gz\"" | \
  356. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  357. if [ -n "$asset_name" ]; then
  358. printf '%s\n' "$asset_name"
  359. return 0
  360. fi
  361. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_[^\"]*_${platform}\\.zip\"" | \
  362. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  363. if [ -n "$asset_name" ]; then
  364. printf '%s\n' "$asset_name"
  365. return 0
  366. fi
  367. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_${platform}\\.zip\"" | \
  368. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  369. if [ -n "$asset_name" ]; then
  370. printf '%s\n' "$asset_name"
  371. return 0
  372. fi
  373. asset_name=$(printf '%s\n' "$release_json" | grep -o "\"name\":[[:space:]]*\"${BIN_NAME}_${platform}\"" | \
  374. sed -E 's/.*"name":[[:space:]]*"([^"]+)".*/\1/' | head -1 || true)
  375. printf '%s\n' "$asset_name"
  376. }
  377. build_download_url() {
  378. local version="$1"
  379. local asset_name="$2"
  380. printf 'https://github.com/%s/%s/releases/download/%s/%s\n' "$REPO_OWNER" "$REPO_NAME" "$version" "$asset_name"
  381. }
  382. download_release_checksums() {
  383. local version="$1"
  384. local asset_name="$2"
  385. local dest_dir="$3"
  386. local candidate checksum_url checksum_path
  387. # SHA256SUMS is what current releases actually publish, so probe it first;
  388. # the other names are legacy/per-asset fallbacks that usually 404.
  389. local -a candidates=(
  390. "SHA256SUMS"
  391. "checksums.txt"
  392. "${asset_name}.sha256"
  393. )
  394. # Only transport failures fall through to the next release asset. Once a
  395. # checksum document downloads, verification treats it as authoritative and
  396. # fails closed rather than accepting a different checksum source.
  397. for candidate in "${candidates[@]}"; do
  398. checksum_url=$(build_download_url "$version" "$candidate")
  399. checksum_path="${dest_dir}/${candidate}"
  400. if try_download_file "$checksum_url" "$checksum_path"; then
  401. printf '%s\n' "$checksum_path"
  402. return 0
  403. fi
  404. done
  405. return 1
  406. }
  407. verify_downloaded_asset() {
  408. local asset_path="$1"
  409. local checksum_path="$2"
  410. local asset_name="$3"
  411. local expected actual
  412. if [ ! -f "$checksum_path" ]; then
  413. print_error "Checksums file not found: $checksum_path"
  414. return 1
  415. fi
  416. expected=$(
  417. awk -v name="$asset_name" '
  418. {
  419. filename = $NF
  420. sub(/\r$/, "", filename)
  421. if (filename == name) {
  422. print $1
  423. exit
  424. }
  425. }
  426. ' "$checksum_path"
  427. )
  428. if ! printf '%s\n' "$expected" | grep -Eq '^[0-9A-Fa-f]{64}$'; then
  429. print_error "No SHA256 checksum found for $asset_name"
  430. return 1
  431. fi
  432. if has_cmd sha256sum; then
  433. actual=$(sha256sum "$asset_path" | awk '{print $1}')
  434. elif has_cmd shasum; then
  435. actual=$(shasum -a 256 "$asset_path" | awk '{print $1}')
  436. else
  437. print_error "Need sha256sum or shasum to verify downloaded asset"
  438. return 1
  439. fi
  440. expected=$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')
  441. actual=$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')
  442. if [ "$expected" != "$actual" ]; then
  443. print_error "Checksum mismatch for $asset_name"
  444. return 1
  445. fi
  446. }
  447. asset_url_exists() {
  448. local url="$1"
  449. if has_cmd curl; then
  450. curl -fsIL -o /dev/null "$url" 2>/dev/null
  451. return $?
  452. elif has_cmd wget; then
  453. wget -q --spider "$url" 2>/dev/null
  454. return $?
  455. fi
  456. return 1
  457. }
  458. find_downloadable_asset_name() {
  459. local platform="$1"
  460. local version="$2"
  461. local clean_version="${version#v}"
  462. local alt_platform="${platform//_/-}"
  463. local candidate url
  464. local -a candidates=(
  465. "${BIN_NAME}_${clean_version}_${platform}.tar.gz"
  466. "${BIN_NAME}_${version}_${platform}.tar.gz"
  467. "${BIN_NAME}_${platform}.tar.gz"
  468. "${BIN_NAME}-${clean_version}-${alt_platform}.tar.gz"
  469. "${BIN_NAME}_${clean_version}_${platform}.zip"
  470. "${BIN_NAME}_${version}_${platform}.zip"
  471. "${BIN_NAME}_${platform}.zip"
  472. )
  473. for candidate in "${candidates[@]}"; do
  474. url=$(build_download_url "$version" "$candidate")
  475. if asset_url_exists "$url"; then
  476. printf '%s\n' "$candidate"
  477. return 0
  478. fi
  479. done
  480. return 1
  481. }
  482. extract_downloaded_asset() {
  483. local asset_name="$1"
  484. local downloaded_path="$2"
  485. local tmp_dir="$3"
  486. case "$asset_name" in
  487. *.tar.gz)
  488. tar -xzf "$downloaded_path" -C "$tmp_dir"
  489. ;;
  490. *.zip)
  491. if has_cmd unzip; then
  492. unzip -q "$downloaded_path" -d "$tmp_dir"
  493. elif has_cmd bsdtar; then
  494. bsdtar -xf "$downloaded_path" -C "$tmp_dir"
  495. else
  496. print_error "Need unzip or bsdtar to extract $asset_name"
  497. return 1
  498. fi
  499. ;;
  500. *)
  501. return 0
  502. ;;
  503. esac
  504. return 0
  505. }
  506. # Ensure install directory exists
  507. ensure_install_dir() {
  508. local dir="$1"
  509. if [ -d "$dir" ]; then
  510. return 0
  511. fi
  512. if mkdir -p "$dir" 2>/dev/null; then
  513. return 0
  514. fi
  515. print_info "Creating $dir requires sudo..."
  516. sudo mkdir -p "$dir"
  517. }
  518. # Easy-mode PATH setup: append the install dir to existing shell rc files.
  519. # When NO writable rc file exists this must never silently no-op — it prints
  520. # the exact export line the user has to add by hand.
  521. easy_mode_path_setup() {
  522. local install_dir="$1"
  523. local path_updated=0
  524. local rc
  525. for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
  526. if [ -e "$rc" ] && [ -w "$rc" ]; then
  527. if ! grep -F "$install_dir" "$rc" >/dev/null 2>&1; then
  528. {
  529. echo ""
  530. echo "# Added by ntm installer"
  531. echo "export PATH=\"\$PATH:${install_dir}\""
  532. } >> "$rc"
  533. path_updated=1
  534. fi
  535. fi
  536. done
  537. if [ "$path_updated" -eq 1 ]; then
  538. print_info "PATH updated in shell rc files; restart shell to use ntm"
  539. elif ! grep -F "$install_dir" "$HOME/.zshrc" >/dev/null 2>&1 \
  540. && ! grep -F "$install_dir" "$HOME/.bashrc" >/dev/null 2>&1; then
  541. print_warn "Could not update PATH automatically: no writable ~/.zshrc or ~/.bashrc found."
  542. echo ""
  543. echo " ${install_dir} is not in your PATH."
  544. echo " Add this line to your shell rc file (create it if needed):"
  545. echo " export PATH=\"\$PATH:${install_dir}\""
  546. echo ""
  547. fi
  548. }
  549. # Main installation function
  550. install_ntm() {
  551. local platform version install_dir tmp_dir asset_name download_url download_path binary_path checksum_path
  552. print_info "Installing ${BIN_NAME}..."
  553. # Detect platform
  554. platform=$(detect_platform) || exit 1
  555. print_info "Detected platform: $platform"
  556. # Check the one hard runtime dependency up front (warn-and-continue)
  557. check_tmux
  558. # Determine install directory
  559. install_dir=$(default_install_dir)
  560. print_info "Install directory: $install_dir"
  561. # Get version
  562. if [ -z "$VERSION" ]; then
  563. print_info "Fetching latest version..."
  564. local release_json
  565. version=$(resolve_latest_version_from_redirect || true)
  566. if [ -n "$version" ]; then
  567. release_json=""
  568. else
  569. release_json=$(get_latest_release) || {
  570. print_error "Could not fetch release info from GitHub"
  571. exit 1
  572. }
  573. version=$(printf '%s\n' "$release_json" | extract_version)
  574. fi
  575. if [ -z "$version" ]; then
  576. print_error "Could not determine latest version"
  577. exit 1
  578. fi
  579. else
  580. version="$VERSION"
  581. fi
  582. if ! version=$(normalize_release_version "$version"); then
  583. exit 1
  584. fi
  585. if [ -n "$VERSION" ]; then
  586. # Fetch release info for this version
  587. local release_json
  588. release_json=$(get_release_by_tag "$version" || true)
  589. if [ -z "$release_json" ]; then
  590. print_warn "Could not fetch release info for ${version} from GitHub; trying known asset names"
  591. fi
  592. fi
  593. print_info "Installing ${BIN_NAME} ${version} for ${platform}"
  594. # Fetch release info if we don't have it. If the API is rate-limited, fall
  595. # back to probing the deterministic release asset names below.
  596. if [ -z "${release_json:-}" ]; then
  597. release_json=$(get_release_by_tag "$version" || true)
  598. fi
  599. # Find download asset
  600. asset_name=$(find_asset_name "$platform" "$release_json")
  601. if [ -z "$asset_name" ]; then
  602. # Try alternate naming conventions
  603. # Some releases use dashes instead of underscores
  604. local alt_platform="${platform//_/-}"
  605. asset_name=$(find_asset_name "$alt_platform" "$release_json")
  606. fi
  607. if [ -z "$asset_name" ]; then
  608. # macOS uses universal binary (darwin_all) instead of arch-specific
  609. case "$platform" in
  610. darwin_amd64|darwin_arm64)
  611. asset_name=$(find_asset_name "darwin_all" "$release_json")
  612. if [ -z "$asset_name" ]; then
  613. asset_name=$(find_downloadable_asset_name "darwin_all" "$version" || true)
  614. fi
  615. ;;
  616. esac
  617. fi
  618. if [ -z "$asset_name" ]; then
  619. asset_name=$(find_downloadable_asset_name "$platform" "$version" || true)
  620. fi
  621. if [ -z "$asset_name" ]; then
  622. print_error "No pre-built binary found for $platform"
  623. print_info "You can build this version from source with: git clone --branch ${version} --depth 1 https://github.com/${REPO_OWNER}/${REPO_NAME}.git && cd ${REPO_NAME} && go install ./cmd/${BIN_NAME}"
  624. exit 1
  625. fi
  626. download_url=$(build_download_url "$version" "$asset_name")
  627. print_info "Downloading from $download_url..."
  628. # Create temp directory
  629. tmp_dir=$(mktemp -d)
  630. TMP_DIRS+=("$tmp_dir")
  631. download_path="${tmp_dir}/${asset_name}"
  632. binary_path="${tmp_dir}/${BIN_NAME}"
  633. # Download
  634. if ! download_file "$download_url" "$download_path"; then
  635. print_error "Download failed"
  636. exit 1
  637. fi
  638. print_info "Verifying checksum..."
  639. if ! checksum_path=$(download_release_checksums "$version" "$asset_name" "$tmp_dir"); then
  640. print_error "Could not download release checksums"
  641. exit 1
  642. fi
  643. if ! verify_downloaded_asset "$download_path" "$checksum_path" "$asset_name"; then
  644. exit 1
  645. fi
  646. if ! extract_downloaded_asset "$asset_name" "$download_path" "$tmp_dir"; then
  647. print_error "Could not extract downloaded archive"
  648. exit 1
  649. fi
  650. if [ ! -f "$binary_path" ] && [ -f "${tmp_dir}/${BIN_NAME}.exe" ]; then
  651. binary_path="${tmp_dir}/${BIN_NAME}.exe"
  652. fi
  653. if [ ! -f "$binary_path" ]; then
  654. print_error "Could not find ${BIN_NAME} in downloaded asset"
  655. exit 1
  656. fi
  657. # Make executable
  658. chmod +x "$binary_path"
  659. # Verify it runs
  660. if ! "$binary_path" version >/dev/null 2>&1; then
  661. print_error "Downloaded binary failed verification"
  662. exit 1
  663. fi
  664. # Install
  665. ensure_install_dir "$install_dir"
  666. local dest_path="${install_dir}/${BIN_NAME}"
  667. if [ -w "$install_dir" ]; then
  668. mv "$binary_path" "$dest_path"
  669. else
  670. print_info "Installing to $install_dir requires sudo..."
  671. sudo mv "$binary_path" "$dest_path"
  672. fi
  673. print_success "Installed ${BIN_NAME} ${version} to ${dest_path}"
  674. # Check PATH
  675. if ! echo "$PATH" | grep -q "$install_dir"; then
  676. if [ "$EASY_MODE" = true ]; then
  677. easy_mode_path_setup "$install_dir"
  678. else
  679. print_warn "${install_dir} is not in your PATH"
  680. echo ""
  681. echo "Add to your shell rc file:"
  682. echo " export PATH=\"\$PATH:${install_dir}\""
  683. echo ""
  684. fi
  685. fi
  686. # Shell integration
  687. if [ "$NO_SHELL" != true ]; then
  688. setup_shell_integration
  689. fi
  690. echo ""
  691. print_success "Installation complete!"
  692. echo ""
  693. echo "Quick start:"
  694. echo " ntm spawn myproject --cc=2 --cod=2 # Create session with agents"
  695. echo " ntm attach myproject # Attach to session"
  696. echo " ntm palette # Open command palette"
  697. echo " ntm tutorial # Interactive tutorial"
  698. echo ""
  699. echo "Tip: You can also install via Homebrew:"
  700. echo " brew install dicklesworthstone/tap/ntm"
  701. echo ""
  702. echo "Run 'ntm --help' for full documentation."
  703. }
  704. # Get the shell integration command for the installed version
  705. # v1.5.0 and earlier use "ntm init <shell>", v1.6.0+ use "ntm shell <shell>"
  706. get_shell_cmd() {
  707. local shell_name="$1"
  708. local installed_version="$2"
  709. # Determine which command to use based on version
  710. # v1.5.0 and earlier use "ntm init", v1.6.0+ use "ntm shell"
  711. local use_init=false
  712. if [ -n "$installed_version" ]; then
  713. # Strip 'v' prefix for comparison
  714. local ver="${installed_version#v}"
  715. local major minor
  716. major=$(echo "$ver" | cut -d. -f1)
  717. minor=$(echo "$ver" | cut -d. -f2)
  718. # Use "ntm init" for v1.5.x and earlier
  719. if [ "$major" -eq 1 ] && [ "$minor" -le 5 ] 2>/dev/null; then
  720. use_init=true
  721. fi
  722. fi
  723. local cmd_name="shell"
  724. if [ "$use_init" = true ]; then
  725. cmd_name="init"
  726. fi
  727. case "$shell_name" in
  728. fish)
  729. echo "ntm $cmd_name fish | source"
  730. ;;
  731. *)
  732. echo "eval \"\$(ntm $cmd_name $shell_name)\""
  733. ;;
  734. esac
  735. }
  736. # Update legacy "ntm init" entries to "ntm shell" in a shell rc file
  737. upgrade_shell_integration() {
  738. local rc_file="$1"
  739. if [ ! -f "$rc_file" ]; then
  740. return 1
  741. fi
  742. # Check if the file has legacy "ntm init" entries
  743. if ! grep -q 'ntm init' "$rc_file"; then
  744. return 1
  745. fi
  746. # Create a backup
  747. local backup_file="${rc_file}.ntm-backup"
  748. cp "$rc_file" "$backup_file"
  749. # Replace "ntm init" with "ntm shell" in the file
  750. # Handle both eval "$(ntm init bash)" and ntm init fish | source patterns
  751. if sed -i.bak 's/ntm init/ntm shell/g' "$rc_file" 2>/dev/null; then
  752. rm -f "${rc_file}.bak"
  753. print_success "Updated shell integration in ${rc_file}"
  754. print_info "Backup saved to ${backup_file}"
  755. return 0
  756. else
  757. # macOS sed requires different syntax
  758. if sed -i '' 's/ntm init/ntm shell/g' "$rc_file" 2>/dev/null; then
  759. print_success "Updated shell integration in ${rc_file}"
  760. print_info "Backup saved to ${backup_file}"
  761. return 0
  762. fi
  763. fi
  764. # Restore from backup if sed failed
  765. mv "$backup_file" "$rc_file"
  766. return 1
  767. }
  768. # Setup shell integration
  769. setup_shell_integration() {
  770. local shell_name rc_file init_cmd
  771. # Detect shell
  772. shell_name=$(basename "${SHELL:-bash}")
  773. case "$shell_name" in
  774. zsh)
  775. rc_file="${HOME}/.zshrc"
  776. ;;
  777. bash)
  778. rc_file="${HOME}/.bashrc"
  779. ;;
  780. fish)
  781. rc_file="${HOME}/.config/fish/config.fish"
  782. ;;
  783. *)
  784. return
  785. ;;
  786. esac
  787. # Get the appropriate shell command for the installed version
  788. init_cmd=$(get_shell_cmd "$shell_name" "$VERSION")
  789. # Check if already configured with current "ntm shell" command
  790. if [ -f "$rc_file" ] && grep -q "ntm shell" "$rc_file"; then
  791. print_info "Shell integration already configured in ${rc_file}"
  792. return
  793. fi
  794. # Check for legacy "ntm init" entries that need upgrading
  795. if [ -f "$rc_file" ] && grep -q "ntm init" "$rc_file"; then
  796. print_warn "Legacy shell integration detected in ${rc_file}"
  797. print_info "The 'ntm init' command was renamed to 'ntm shell' in v1.6.0."
  798. # In easy-mode, auto-upgrade
  799. if [ "$EASY_MODE" = true ]; then
  800. if upgrade_shell_integration "$rc_file"; then
  801. print_info "Restart your shell or run 'source ${rc_file}' to activate."
  802. else
  803. print_warn "Could not auto-update. Please manually replace 'ntm init' with 'ntm shell'."
  804. fi
  805. return
  806. fi
  807. # Only prompt if interactive
  808. if [ -t 0 ] && [ -t 1 ]; then
  809. printf "Update to 'ntm shell' automatically? [Y/n]: "
  810. read -r answer
  811. case "$answer" in
  812. n|N|no|NO)
  813. print_info "Please manually replace 'ntm init' with 'ntm shell' in ${rc_file}"
  814. ;;
  815. *)
  816. if upgrade_shell_integration "$rc_file"; then
  817. print_info "Restart your shell or run 'source ${rc_file}' to activate."
  818. else
  819. print_warn "Could not auto-update. Please manually replace 'ntm init' with 'ntm shell'."
  820. fi
  821. ;;
  822. esac
  823. else
  824. print_info "Run installer with --easy-mode to auto-update, or manually replace 'ntm init' with 'ntm shell'."
  825. fi
  826. return
  827. fi
  828. echo ""
  829. echo "Shell Integration"
  830. echo ""
  831. echo "Add this to ${rc_file}:"
  832. echo " ${init_cmd}"
  833. echo ""
  834. # In easy-mode, auto-add without prompting
  835. if [ "$EASY_MODE" = true ]; then
  836. {
  837. echo ""
  838. echo "# NTM - Named Tmux Manager"
  839. echo "$init_cmd"
  840. } >> "$rc_file"
  841. print_success "Added shell integration to ${rc_file}"
  842. print_info "Restart your shell or run 'source ${rc_file}' to activate."
  843. return
  844. fi
  845. # Only prompt if interactive
  846. if [ -t 0 ] && [ -t 1 ]; then
  847. printf "Add it now? [y/N]: "
  848. read -r answer
  849. case "$answer" in
  850. y|Y|yes|YES)
  851. echo "" >> "$rc_file"
  852. echo "# NTM - Named Tmux Manager" >> "$rc_file"
  853. echo "$init_cmd" >> "$rc_file"
  854. print_success "Added to ${rc_file}"
  855. echo ""
  856. echo "Run 'source ${rc_file}' or restart your shell to activate."
  857. ;;
  858. *)
  859. echo "Skipped. Add it manually when ready."
  860. ;;
  861. esac
  862. fi
  863. }
  864. # Run installation (skipped when sourced under NTM_INSTALL_SH_NO_MAIN=1,
  865. # which the shell-function test harness uses to exercise the guidance paths)
  866. if [ "${NTM_INSTALL_SH_NO_MAIN:-0}" != "1" ]; then
  867. install_ntm
  868. fi

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.