1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// The binary is a thin shell over the library (src/lib.rs), which holds every module.
use forge_orchestrator::{cli, fleet};
use clap::Parser;
use cli::{Cli, Commands};
use std::path::PathBuf;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load .env from CWD first (default dotenvy behavior)
dotenvy::dotenv().ok();
// Initialize tracing — only active when RUST_LOG is set.
// Writes to stderr by default; also writes to .forge/debug.log when active.
init_tracing();
let cli = Cli::parse();
// Project-binding priority (DIRECTIVE-16 — per-invocation authority):
// 1. an explicit `--project` (anything but the `.` default) — authoritative,
// 2. else `FORGE_PROJECT_ROOT` — the per-connection binding the plugin's `.mcp.json` sets
// (previously read NOWHERE, so the contract was silently dropped) — authoritative,
// 3. else the current directory (`.`) — unbound; a server started this way may still switch
// via `forge_set_project` (global active-project as default-when-unspecified only).
// An authoritative binding must never be overridden by another consumer's `set_project`.
let (raw_project, explicit_binding) = if cli.project != "." {
(cli.project.clone(), true)
} else if let Some(env_root) = std::env::var_os("FORGE_PROJECT_ROOT").filter(|v| !v.is_empty())
{
(env_root.to_string_lossy().into_owned(), true)
} else {
(cli.project.clone(), false)
};
let project_root = PathBuf::from(&raw_project)
.canonicalize()
.unwrap_or_else(|_| PathBuf::from(&raw_project));
// Also try loading .env from the project root (for --project /other/dir usage)
dotenvy::from_path(project_root.join(".env")).ok();
// And from forge's own config dir (~/.forge/.env)
if let Ok(home) = std::env::var("HOME") {
dotenvy::from_path(PathBuf::from(&home).join(".forge").join(".env")).ok();
}
match cli.command {
Commands::Init { name } => {
cli::init::execute(&project_root, name)?;
}
Commands::Plan {
generate,
spec,
from_findings,
} => {
cli::plan::execute(&project_root, generate, spec, from_findings)?;
}
Commands::Status {
events,
budget,
json,
all,
} => {
if budget {
// Fleet-wide and project-independent — deliberately NOT gated on `.forge/`.
let rows = fleet::read_fleet();
if json {
println!("{}", fleet::render_json(&rows));
} else {
print!("{}", fleet::render_table(&rows, all));
}
} else {
cli::status::execute(&project_root, events)?;
}
}
Commands::Run {
task,
agent,
parallel,
dry_run,
} => {
if let (Some(task_id), Some(agent_name)) = (&task, &agent) {
cli::run::execute(&project_root, task_id, agent_name).await?;
} else if task.is_none() && agent.is_none() {
cli::run::execute_all(&project_root, parallel, dry_run).await?;
} else {
anyhow::bail!(
"Specify both --task and --agent for single-task mode, or omit both for autonomous mode."
);
}
}
Commands::Start {
agent,
r#loop,
accept_subscription_risk,
} => {
// DX-038: Check subscription risk before starting
if !accept_subscription_risk {
let forge_dir = project_root.join(".forge");
if forge_dir.exists() {
let state_mgr = cli::start::load_state_for_risk_check(&forge_dir);
if let Some(warning) = state_mgr {
println!("{warning}");
return Ok(());
}
}
}
if r#loop {
cli::start::execute_loop(&project_root, agent.as_deref()).await?;
} else {
cli::start::execute(&project_root, agent.as_deref()).await?;
}
}
Commands::Pod { verb } => {
// Pod is Unix-only (tmux + flock(2)). On non-Unix the verb parses but there is no
// handler — fail closed with exit 2 rather than pretend. Both branches diverge
// (`process::exit`), so the arm still type-checks.
#[cfg(not(unix))]
{
let _ = verb;
eprintln!(
"forge pod requires a Unix host (tmux + flock); it is not available on this platform"
);
std::process::exit(2);
}
#[cfg(unix)]
{
use cli::PodVerb;
// Pod verbs carry cosmux-parity exit codes (2 = uncovered preflight targets), so the
// verdict is the process status, as it is for `forge doctor`.
let result = match verb {
PodVerb::Start {
name,
force,
attach,
} => cli::pod::start(&name, force, attach),
PodVerb::Stop { name } => cli::pod::stop(&name),
PodVerb::List => cli::pod::list(),
PodVerb::Validate { name } => cli::pod::validate(&name),
PodVerb::Show { name } => cli::pod::show(&name),
PodVerb::State => cli::pod::show_state(),
PodVerb::Ps => cli::pod::ps(),
PodVerb::Gc => cli::pod::gc(),
PodVerb::Reload { name, force } => cli::pod::reload(&name, force),
PodVerb::Completions { shell } => cli::pod::completions(shell),
PodVerb::Preflight { pod, against } => cli::pod::preflight_cmd(
pod.as_deref(),
against.as_deref().map(std::path::Path::new),
),
PodVerb::Adopt { repair, abort } => {
if repair {
forge_orchestrator::pod::adopt::repair()
} else if abort {
forge_orchestrator::pod::adopt::abort()
} else {
forge_orchestrator::pod::adopt::adopt()
}
}
PodVerb::Unadopt => forge_orchestrator::pod::adopt::unadopt(),
PodVerb::PaneRecover { session } => cli::pod::pane_recover(&session),
PodVerb::AfterDetach { session } => cli::pod::after_detach(&session),
};
use std::io::Write;
let code = match result {
Ok(code) => code,
Err(error) => {
// Operational errors exit 1, matching cosmux; a check that RAN and found
// problems exits 2 via its own return value.
eprintln!("forge pod: {error}");
1
}
};
std::io::stdout().flush().ok();
std::process::exit(code);
}
}
Commands::Doctor { strict, json } => {
let code = cli::doctor::execute(&project_root, strict, json)?;
// Fail-closed: the verdict IS the exit status, so CI can gate on it directly.
// Flush explicitly — process::exit does not run destructors or flush stdout.
use std::io::Write;
std::io::stdout().flush().ok();
std::process::exit(code);
}
Commands::Verify => {
cli::verify::execute(&project_root)?;
}
Commands::Uat { finding } => {
cli::uat::execute(&project_root, finding)?;
}
Commands::Sync => {
cli::sync::execute(&project_root)?;
}
Commands::Mcp => {
cli::mcp::execute(&project_root, explicit_binding)?;
}
Commands::Dashboard {
watch,
parallel,
accept_subscription_risk,
pty,
} => {
// DX-038: Check subscription risk before launching dashboard
// PTY mode is interactive TUI — Anthropic's preferred pattern, no risk
let pty_from_config = {
let forge_dir = project_root.join(".forge");
if forge_dir.exists() {
let state_mgr = forge_orchestrator::core::state::StateManager::new(&forge_dir);
state_mgr
.load()
.map(|s| s.dashboard_mode == "pty")
.unwrap_or(false)
} else {
false
}
};
let is_pty = pty || pty_from_config;
if !accept_subscription_risk && !is_pty {
let forge_dir = project_root.join(".forge");
if forge_dir.exists() {
let state_mgr = forge_orchestrator::core::state::StateManager::new(&forge_dir);
if let Ok(state) = state_mgr.load() {
let has_claude_sub = state
.agent_auth
.get("claude")
.map(|v| v == "subscription")
.unwrap_or(true);
if has_claude_sub {
println!();
println!(
" \u{26A0}\u{26A0}\u{26A0} SUBSCRIPTION RISK DETECTED \u{26A0}\u{26A0}\u{26A0}"
);
println!();
println!(" Claude is configured to use subscription auth.");
println!(" Anthropic ACTIVELY BLOCKS third-party CLI orchestration");
println!(" and has BANNED accounts for this pattern.");
println!();
println!(" Options:");
println!(" 1. Switch to API mode (RECOMMENDED):");
println!(" forge config claude.auth api");
println!();
println!(" 2. Accept the risk:");
println!(" forge dashboard --i-accept-subscription-risk");
println!();
println!(" See: docs/research/cli-subscription-gating-analysis.md");
return Ok(());
}
}
}
}
cli::dashboard::execute(&project_root, parallel, watch, pty).await?;
}
Commands::Ship { auto, dry_run } => {
cli::ship::execute(&project_root, auto, dry_run)?;
}
Commands::Uninstall { force } => {
cli::uninstall::execute(&project_root, force)?;
}
Commands::Config { key, value } => {
if let Some(key) = key {
if let Some(value) = value {
cli::config::execute(&project_root, &key, &value)?;
} else {
anyhow::bail!(
"Missing value.\n\nUsage: forge config <key> <value>\n\nExamples:\n forge config brain openai\n forge config brain.model gpt-4.1"
);
}
} else {
cli::config::show(&project_root)?;
}
}
}
Ok(())
}
/// Initialize tracing infrastructure. Only active when RUST_LOG is set.
/// Logs to stderr + .forge/debug.log (non-blocking file appender).
fn init_tracing() {
use tracing_subscriber::EnvFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
// Only activate if RUST_LOG is set — zero overhead otherwise.
let filter = match EnvFilter::try_from_default_env() {
Ok(f) => f,
Err(_) => return, // RUST_LOG not set — no tracing
};
// File appender: writes to .forge/debug.log (non-blocking)
let forge_dir = std::env::current_dir().unwrap_or_default().join(".forge");
std::fs::create_dir_all(&forge_dir).ok();
let file_appender = tracing_appender::rolling::never(&forge_dir, "debug.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
// Leak the guard so the file writer stays alive for the process lifetime
std::mem::forget(_guard);
tracing_subscriber::registry()
.with(filter)
.with(
tracing_subscriber::fmt::layer()
.with_writer(non_blocking)
.with_ansi(false),
)
.init();
}