返回 CodeWhale
runtime.rs
根目录 / crates / lane / src / runtime.rs
1 //! Runtime backends: tmux durability and inline (#4176). The never-implemented
2 //! `vm` / `ci` kinds are retired and only load from historical records (#6516).
3 //!
4 //! Runtime owns process/session lifecycle and stream-json log capture.
5 //! Fleet modules must not import this module.
6
7 use std::fs::{self, OpenOptions};
8 use std::io::{BufRead, BufReader, Write};
9 use std::path::{Path, PathBuf};
10 use std::process::{Command, ExitStatus, Stdio};
11 use std::thread;
12
13 use anyhow::{Context, Result, bail};
14 use serde::{Deserialize, Serialize};
15
16 use crate::registry::{LaneRecord, LaneRegistry, LaneStatus, TerminalTransition};
17 use crate::worktree::{WorktreeProvision, provision_worktree, remove_worktree_if_expired};
18
19 /// Execution backend for a lane.
20 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21 #[serde(rename_all = "snake_case")]
22 pub enum RuntimeBackendKind {
23 Tmux,
24 Inline,
25 /// Retired (#6516): `vm` and `ci` were advertised but never implemented.
26 /// [`Self::parse`] no longer accepts them; the variants stay only so lane
27 /// records written by earlier releases (always `failed`) still load
28 /// instead of being skipped as corrupt.
29 Vm,
30 Ci,
31 }
32
33 impl RuntimeBackendKind {
34 pub fn as_str(self) -> &'static str {
35 match self {
36 Self::Tmux => "tmux",
37 Self::Inline => "inline",
38 Self::Vm => "vm",
39 Self::Ci => "ci",
40 }
41 }
42
43 pub fn parse(raw: &str) -> Result<Self> {
44 match raw.trim().to_ascii_lowercase().as_str() {
45 "tmux" => Ok(Self::Tmux),
46 "inline" => Ok(Self::Inline),
47 "vm" | "ci" => bail!(
48 "runtime backend `{}` is not available; use tmux or inline",
49 raw.trim().to_ascii_lowercase()
50 ),
51 other => bail!("unknown runtime backend `{other}` (use tmux|inline)"),
52 }
53 }
54 }
55
56 /// Inputs for starting a lane under a runtime backend.
57 #[derive(Clone)]
58 pub struct LaneStartSpec {
59 /// Command argv to run inside the backend (e.g. `codewhale exec …`).
60 pub command: Vec<String>,
61 /// Working directory for the command (defaults to worktree or cwd).
62 pub cwd: Option<PathBuf>,
63 /// Process-local runtime overrides. Values are never written into the
64 /// Lane record or command argv; tmux bridges them through a private 0600
65 /// environment file that the detached shell removes before execution.
66 pub environment: Vec<(String, String)>,
67 /// Executable that exposes Codewhale's hidden `lane-log-proxy` command.
68 /// Required by tmux so arbitrary/binary child output is framed as valid
69 /// NDJSON without trusting a shell pipeline.
70 pub log_proxy: Option<PathBuf>,
71 /// When set, provision an isolated git worktree + branch under this repo.
72 pub worktree: Option<WorktreeProvision>,
73 }
74
75 impl std::fmt::Debug for LaneStartSpec {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 f.debug_struct("LaneStartSpec")
78 .field("command", &self.command)
79 .field("cwd", &self.cwd)
80 .field(
81 "environment_keys",
82 &self
83 .environment
84 .iter()
85 .map(|(key, _)| key)
86 .collect::<Vec<_>>(),
87 )
88 .field("log_proxy", &self.log_proxy)
89 .field("worktree", &self.worktree)
90 .finish()
91 }
92 }
93
94 /// Runtime adapter contract.
95 pub trait RuntimeBackend {
96 fn kind(&self) -> RuntimeBackendKind;
97
98 /// Start the lane process/session; mutates record with attach/log metadata.
99 fn start(
100 &self,
101 registry: &LaneRegistry,
102 record: &mut LaneRecord,
103 spec: &LaneStartSpec,
104 ) -> Result<()>;
105
106 /// Human attach command, if any (tmux).
107 fn attach_command(&self, record: &LaneRecord) -> Option<String>;
108
109 /// Stop the running session/process.
110 ///
111 /// `fence` pins the durable lifecycle generation the caller observed. It is
112 /// evaluated under the registry's per-Lane lock, so a record that moved on
113 /// between the caller's read and this call is refused rather than stopped.
114 /// The return value distinguishes "this call stopped it" from "it was
115 /// already terminal" and "the fence did not match", so a caller can report
116 /// a truthful outcome instead of claiming a transition someone else made.
117 fn stop(
118 &self,
119 registry: &LaneRegistry,
120 record: &mut LaneRecord,
121 fence: Option<u64>,
122 ) -> Result<TerminalTransition>;
123
124 /// Reconcile durable backend state into the Lane record before display.
125 /// Most backends update synchronously and need no refresh; tmux records
126 /// the detached process exit in a private sidecar and folds it in on the
127 /// next read.
128 ///
129 /// Returns `true` when reconciliation *changed durable state*. Reads are
130 /// allowed to fold a finished Runtime exit into the record, but a surface
131 /// that calls this must be able to say so rather than reporting a pure
132 /// observation (#4022).
133 fn reconcile(&self, _registry: &LaneRegistry, _record: &mut LaneRecord) -> Result<bool> {
134 Ok(false)
135 }
136
137 /// Optional worktree TTL cleanup after stop.
138 fn cleanup_worktree(&self, record: &LaneRecord) -> Result<()> {
139 if let Some(path) = record.worktree_path.as_ref() {
140 remove_worktree_if_expired(
141 path,
142 record.worktree_ttl_secs,
143 record.stopped_at.as_deref(),
144 )?;
145 }
146 Ok(())
147 }
148 }
149
150 pub fn resolve_backend(kind: RuntimeBackendKind) -> Box<dyn RuntimeBackend> {
151 match kind {
152 RuntimeBackendKind::Tmux => Box::new(TmuxRuntime),
153 RuntimeBackendKind::Inline => Box::new(InlineRuntime),
154 RuntimeBackendKind::Vm => Box::new(RetiredRuntime {
155 kind: RuntimeBackendKind::Vm,
156 }),
157 RuntimeBackendKind::Ci => Box::new(RetiredRuntime {
158 kind: RuntimeBackendKind::Ci,
159 }),
160 }
161 }
162
163 pub fn backend_for(record: &LaneRecord) -> Box<dyn RuntimeBackend> {
164 resolve_backend(record.runtime)
165 }
166
167 fn append_log_event(log_path: &Path, event: serde_json::Value) -> Result<()> {
168 let mut options = OpenOptions::new();
169 options.create(true).append(true);
170 #[cfg(unix)]
171 {
172 use std::os::unix::fs::OpenOptionsExt;
173 options.mode(0o600);
174 }
175 let mut file = options
176 .open(log_path)
177 .with_context(|| format!("open lane log {}", log_path.display()))?;
178 let mut encoded = serde_json::to_vec(&event).context("serialize lane log event")?;
179 encoded.push(b'\n');
180 file.write_all(&encoded)
181 .with_context(|| format!("write lane log {}", log_path.display()))?;
182 Ok(())
183 }
184
185 const MAX_EXIT_RECEIPT_BYTES: u64 = 4 * 1024;
186 const MAX_ENVIRONMENT_BYTES: u64 = 1024 * 1024;
187 const MAX_CHILD_LOG_FRAME_BYTES: usize = 64 * 1024;
188 const LANE_PROXY_FAILURE_EXIT_CODE: i32 = 125;
189
190 #[derive(Debug, Deserialize, Serialize)]
191 struct LaneExitReceipt {
192 lane_id: String,
193 exit_code: i32,
194 }
195
196 /// Inputs to the hidden Rust log proxy used by detached runtimes.
197 ///
198 /// The proxy is deliberately exposed by the Lane crate so the thin CLI
199 /// facade can invoke it before loading user configuration. Secrets travel in
200 /// the private environment file, never in argv or the Lane record.
201 #[derive(Debug, Clone)]
202 pub struct LaneLogProxySpec {
203 pub command: Vec<String>,
204 pub log_path: PathBuf,
205 pub receipt_path: PathBuf,
206 pub receipt_tmp_path: PathBuf,
207 pub environment_path: Option<PathBuf>,
208 pub lane_id: String,
209 }
210
211 fn lane_exit_receipt_path(log_path: &Path) -> PathBuf {
212 log_path.with_extension("exit.json")
213 }
214
215 fn lane_exit_receipt_tmp_path(log_path: &Path) -> PathBuf {
216 log_path.with_extension("exit.json.tmp")
217 }
218
219 fn lane_environment_path(log_path: &Path) -> PathBuf {
220 log_path.with_extension("env.json")
221 }
222
223 fn lane_environment_tmp_path(path: &Path) -> PathBuf {
224 path.with_extension("json.tmp")
225 }
226
227 fn remove_file_if_present(path: &Path) -> Result<()> {
228 match std::fs::remove_file(path) {
229 Ok(()) => Ok(()),
230 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
231 Err(err) => Err(err).with_context(|| format!("remove {}", path.display())),
232 }
233 }
234
235 fn valid_environment_key(key: &str) -> bool {
236 let mut chars = key.chars();
237 chars
238 .next()
239 .is_some_and(|ch| ch == '_' || ch.is_ascii_alphabetic())
240 && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
241 }
242
243 fn write_lane_environment(path: &Path, environment: &[(String, String)]) -> Result<()> {
244 for (key, _) in environment {
245 if !valid_environment_key(key) {
246 bail!("invalid lane environment key {key:?}");
247 }
248 }
249 let encoded = serde_json::to_vec(environment).context("serialize private lane environment")?;
250 if encoded.len() as u64 > MAX_ENVIRONMENT_BYTES {
251 bail!(
252 "private lane environment exceeds {} bytes",
253 MAX_ENVIRONMENT_BYTES
254 );
255 }
256
257 let tmp_path = lane_environment_tmp_path(path);
258 remove_file_if_present(path)?;
259 remove_file_if_present(&tmp_path)?;
260 let mut options = OpenOptions::new();
261 options.create_new(true).write(true);
262 #[cfg(unix)]
263 {
264 use std::os::unix::fs::OpenOptionsExt;
265 options.mode(0o600);
266 }
267 let result = (|| {
268 let mut file = options
269 .open(&tmp_path)
270 .with_context(|| format!("create private lane environment {}", tmp_path.display()))?;
271 file.write_all(&encoded)
272 .with_context(|| format!("write private lane environment {}", tmp_path.display()))?;
273 file.sync_all()
274 .with_context(|| format!("sync private lane environment {}", tmp_path.display()))?;
275 fs::rename(&tmp_path, path)
276 .with_context(|| format!("publish private lane environment {}", path.display()))?;
277 Ok(())
278 })();
279 if result.is_err() {
280 let _ = remove_file_if_present(&tmp_path);
281 let _ = remove_file_if_present(path);
282 }
283 result
284 }
285
286 fn append_child_output(log_path: &Path, stream: &str, bytes: &[u8]) -> Result<()> {
287 let mut line = bytes;
288 if let Some(stripped) = line.strip_suffix(b"\n") {
289 line = stripped;
290 }
291 if let Some(stripped) = line.strip_suffix(b"\r") {
292 line = stripped;
293 }
294 if line.is_empty() {
295 return Ok(());
296 }
297 if let Ok(event) = serde_json::from_slice::<serde_json::Value>(line) {
298 append_log_event(log_path, event)
299 } else {
300 append_log_event(
301 log_path,
302 serde_json::json!({
303 "type": "lane_log",
304 "stream": stream,
305 "message": String::from_utf8_lossy(line),
306 }),
307 )
308 }
309 }
310
311 fn stream_child_output(
312 reader: impl std::io::Read,
313 log_path: PathBuf,
314 stream: &'static str,
315 ) -> Result<()> {
316 let mut reader = BufReader::new(reader);
317 let mut line = Vec::new();
318 loop {
319 line.clear();
320 let mut reached_eof = false;
321 while line.len() < MAX_CHILD_LOG_FRAME_BYTES {
322 let buffer = reader
323 .fill_buf()
324 .with_context(|| format!("read lane child {stream}"))?;
325 if buffer.is_empty() {
326 reached_eof = true;
327 break;
328 }
329 let available = buffer
330 .iter()
331 .position(|byte| *byte == b'\n')
332 .map_or(buffer.len(), |position| position + 1);
333 let take = available.min(MAX_CHILD_LOG_FRAME_BYTES - line.len());
334 let ended_line = buffer.get(take.saturating_sub(1)) == Some(&b'\n');
335 line.extend_from_slice(&buffer[..take]);
336 reader.consume(take);
337 if ended_line {
338 break;
339 }
340 }
341 if line.is_empty() && reached_eof {
342 return Ok(());
343 }
344 append_child_output(&log_path, stream, &line)?;
345 if reached_eof {
346 return Ok(());
347 }
348 }
349 }
350
351 fn read_lane_environment(path: &Path) -> Result<Vec<(String, String)>> {
352 let metadata = fs::metadata(path).with_context(|| format!("stat {}", path.display()))?;
353 if metadata.len() > MAX_ENVIRONMENT_BYTES {
354 bail!(
355 "private lane environment {} exceeds {} bytes",
356 path.display(),
357 MAX_ENVIRONMENT_BYTES
358 );
359 }
360 let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
361 if bytes.len() as u64 > MAX_ENVIRONMENT_BYTES {
362 bail!(
363 "private lane environment {} exceeds {} bytes",
364 path.display(),
365 MAX_ENVIRONMENT_BYTES
366 );
367 }
368 let environment: Vec<(String, String)> =
369 serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))?;
370 for (key, _) in &environment {
371 if !valid_environment_key(key) {
372 bail!("invalid lane environment key {key:?}");
373 }
374 }
375 Ok(environment)
376 }
377
378 fn write_lane_exit_receipt(
379 receipt_path: &Path,
380 receipt_tmp_path: &Path,
381 lane_id: &str,
382 exit_code: i32,
383 ) -> Result<()> {
384 let encoded = serde_json::to_vec(&LaneExitReceipt {
385 lane_id: lane_id.to_string(),
386 exit_code,
387 })
388 .context("serialize lane exit receipt")?;
389 if encoded.len() as u64 > MAX_EXIT_RECEIPT_BYTES {
390 bail!("serialized lane exit receipt exceeds size bound");
391 }
392 remove_file_if_present(receipt_tmp_path)?;
393 let mut options = OpenOptions::new();
394 options.create_new(true).write(true);
395 #[cfg(unix)]
396 {
397 use std::os::unix::fs::OpenOptionsExt;
398 options.mode(0o600);
399 }
400 let result = (|| {
401 let mut file = options
402 .open(receipt_tmp_path)
403 .with_context(|| format!("create {}", receipt_tmp_path.display()))?;
404 file.write_all(&encoded)
405 .with_context(|| format!("write {}", receipt_tmp_path.display()))?;
406 file.sync_all()
407 .with_context(|| format!("sync {}", receipt_tmp_path.display()))?;
408 fs::rename(receipt_tmp_path, receipt_path)
409 .with_context(|| format!("publish {}", receipt_path.display()))?;
410 Ok(())
411 })();
412 if result.is_err() {
413 let _ = remove_file_if_present(receipt_tmp_path);
414 }
415 result
416 }
417
418 fn exit_status_code(status: ExitStatus) -> i32 {
419 if let Some(code) = status.code() {
420 return code;
421 }
422 #[cfg(unix)]
423 {
424 use std::os::unix::process::ExitStatusExt;
425 if let Some(signal) = status.signal() {
426 return 128 + signal;
427 }
428 }
429 LANE_PROXY_FAILURE_EXIT_CODE
430 }
431
432 fn append_proxy_failure(log_path: &Path, lane_id: &str, error: &anyhow::Error) -> Result<()> {
433 append_log_event(
434 log_path,
435 serde_json::json!({
436 "type": "lane_proxy_error",
437 "lane_id": lane_id,
438 "error": format!("{error:#}"),
439 }),
440 )
441 }
442
443 /// Run a child command while framing all output as NDJSON and atomically
444 /// publishing a private exit receipt. Returns the process-style exit code the
445 /// hidden CLI should propagate to tmux.
446 pub fn run_lane_log_proxy(spec: LaneLogProxySpec) -> Result<i32> {
447 let LaneLogProxySpec {
448 command,
449 log_path,
450 receipt_path,
451 receipt_tmp_path,
452 environment_path,
453 lane_id,
454 } = spec;
455
456 let fail = |error: anyhow::Error, exit_code: i32| -> Result<i32> {
457 append_proxy_failure(&log_path, &lane_id, &error)?;
458 write_lane_exit_receipt(&receipt_path, &receipt_tmp_path, &lane_id, exit_code)?;
459 Ok(exit_code)
460 };
461
462 if command.is_empty() {
463 return fail(anyhow::anyhow!("lane log proxy requires a command"), 127);
464 }
465
466 let environment = if let Some(path) = environment_path.as_deref() {
467 let loaded = read_lane_environment(path);
468 let removed = remove_file_if_present(path);
469 match (loaded, removed) {
470 (Ok(environment), Ok(())) => environment,
471 (Err(error), Ok(())) => return fail(error, LANE_PROXY_FAILURE_EXIT_CODE),
472 (Ok(_), Err(error)) | (Err(_), Err(error)) => return Err(error),
473 }
474 } else {
475 Vec::new()
476 };
477
478 let mut child_command = Command::new(&command[0]);
479 child_command.args(&command[1..]);
480 child_command.envs(environment);
481 child_command.stdout(Stdio::piped()).stderr(Stdio::piped());
482 let mut child = match child_command.spawn() {
483 Ok(child) => child,
484 Err(error) => {
485 return fail(
486 anyhow::Error::from(error).context(format!("spawn lane child command {command:?}")),
487 127,
488 );
489 }
490 };
491 let stdout = match child.stdout.take() {
492 Some(stdout) => stdout,
493 None => return fail(anyhow::anyhow!("lane child stdout was not piped"), 125),
494 };
495 let stderr = match child.stderr.take() {
496 Some(stderr) => stderr,
497 None => return fail(anyhow::anyhow!("lane child stderr was not piped"), 125),
498 };
499 let stdout_log = log_path.clone();
500 let stderr_log = log_path.clone();
501 let stdout_thread = thread::spawn(move || stream_child_output(stdout, stdout_log, "stdout"));
502 let stderr_thread = thread::spawn(move || stream_child_output(stderr, stderr_log, "stderr"));
503
504 let status = match child.wait() {
505 Ok(status) => status,
506 Err(error) => {
507 return fail(
508 anyhow::Error::from(error).context(format!("wait for lane child {command:?}")),
509 LANE_PROXY_FAILURE_EXIT_CODE,
510 );
511 }
512 };
513 let stdout_result = stdout_thread
514 .join()
515 .map_err(|_| anyhow::anyhow!("lane proxy stdout logger panicked"))?;
516 let stderr_result = stderr_thread
517 .join()
518 .map_err(|_| anyhow::anyhow!("lane proxy stderr logger panicked"))?;
519 let mut exit_code = exit_status_code(status);
520 if let Some(error) = stdout_result.err().or_else(|| stderr_result.err()) {
521 append_proxy_failure(&log_path, &lane_id, &error)?;
522 exit_code = LANE_PROXY_FAILURE_EXIT_CODE;
523 }
524 write_lane_exit_receipt(&receipt_path, &receipt_tmp_path, &lane_id, exit_code)?;
525 Ok(exit_code)
526 }
527
528 fn read_lane_exit_receipt(log_path: &Path, lane_id: &str) -> Result<Option<LaneExitReceipt>> {
529 let path = lane_exit_receipt_path(log_path);
530 let metadata = match std::fs::metadata(&path) {
531 Ok(metadata) => metadata,
532 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
533 Err(err) => return Err(err).with_context(|| format!("stat {}", path.display())),
534 };
535 if metadata.len() > MAX_EXIT_RECEIPT_BYTES {
536 bail!(
537 "lane exit receipt {} exceeds {} bytes",
538 path.display(),
539 MAX_EXIT_RECEIPT_BYTES
540 );
541 }
542 let bytes = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
543 let receipt: LaneExitReceipt =
544 serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))?;
545 if receipt.lane_id != lane_id {
546 bail!(
547 "lane exit receipt {} belongs to {}, expected {}",
548 path.display(),
549 receipt.lane_id,
550 lane_id
551 );
552 }
553 Ok(Some(receipt))
554 }
555
556 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
557 enum TmuxSessionState {
558 Present,
559 Absent,
560 }
561
562 fn tmux_command(socket: &Path) -> Command {
563 let mut command = Command::new("tmux");
564 command.arg("-S").arg(socket);
565 command
566 }
567
568 fn ensure_tmux_available() -> Result<()> {
569 let output = Command::new("tmux")
570 .arg("-V")
571 .output()
572 .context("tmux runtime requires the `tmux` executable")?;
573 if !output.status.success() {
574 bail!(
575 "tmux runtime is unavailable: `tmux -V` failed with {}: {}",
576 output.status,
577 String::from_utf8_lossy(&output.stderr).trim()
578 );
579 }
580 Ok(())
581 }
582
583 fn tmux_session_state(socket: &Path, session: &str) -> Result<TmuxSessionState> {
584 let output = tmux_command(socket)
585 .args(["has-session", "-t", session])
586 .stdout(Stdio::null())
587 .stderr(Stdio::piped())
588 .output()
589 .with_context(|| format!("query tmux session {session}"))?;
590 if output.status.success() {
591 return Ok(TmuxSessionState::Present);
592 }
593 let stderr = String::from_utf8_lossy(&output.stderr).to_ascii_lowercase();
594 if stderr.contains("can't find session:")
595 || stderr.contains("no server running on")
596 || (stderr.contains("error connecting to") && stderr.contains("no such file or directory"))
597 {
598 return Ok(TmuxSessionState::Absent);
599 }
600 bail!(
601 "tmux has-session for {session} failed with {}: {}",
602 output.status,
603 stderr.trim()
604 )
605 }
606
607 fn stop_tmux_session(socket: &Path, session: &str) -> Result<()> {
608 let status = tmux_command(socket)
609 .args(["kill-session", "-t", session])
610 .stdout(Stdio::null())
611 .stderr(Stdio::null())
612 .status()
613 .with_context(|| format!("kill tmux session {session}"))?;
614 match tmux_session_state(socket, session).with_context(|| {
615 format!(
616 "confirm tmux session {session} on {} stopped after kill-session ({status})",
617 socket.display()
618 )
619 })? {
620 TmuxSessionState::Absent => {}
621 TmuxSessionState::Present => {
622 bail!("tmux session {session} remains active after kill-session ({status})")
623 }
624 }
625 // A nonzero kill can be benign when the process and session exited in the
626 // same instant. The explicit absence check above is the source of truth.
627 Ok(())
628 }
629
630 fn tmux_log_proxy_command(
631 proxy: &Path,
632 command: &[String],
633 log_path: &Path,
634 receipt_path: &Path,
635 receipt_tmp_path: &Path,
636 environment_path: Option<&Path>,
637 lane_id: &str,
638 ) -> String {
639 let mut argv = vec![
640 proxy.display().to_string(),
641 "lane-log-proxy".to_string(),
642 "--log-path".to_string(),
643 log_path.display().to_string(),
644 "--receipt-path".to_string(),
645 receipt_path.display().to_string(),
646 "--receipt-tmp-path".to_string(),
647 receipt_tmp_path.display().to_string(),
648 "--lane-id".to_string(),
649 lane_id.to_string(),
650 ];
651 if let Some(path) = environment_path {
652 argv.push("--environment-path".to_string());
653 argv.push(path.display().to_string());
654 }
655 argv.push("--".to_string());
656 argv.extend(command.iter().cloned());
657 format!("exec {}", shell_join(&argv))
658 }
659
660 /// The tmux dry-run hook, honoured only in this crate's own unit tests.
661 ///
662 /// It records a Running lane with no process, skips the tmux kill on stop,
663 /// and blinds reconcile, so an inherited `CODEWHALE_LANE_TMUX_DRY_RUN` in a
664 /// real build would fabricate lane state. Release builds ignore it.
665 fn tmux_dry_run() -> bool {
666 cfg!(test) && std::env::var_os("CODEWHALE_LANE_TMUX_DRY_RUN").is_some()
667 }
668
669 fn apply_worktree(record: &mut LaneRecord, spec: &LaneStartSpec) -> Result<Option<PathBuf>> {
670 let Some(wt) = spec.worktree.as_ref() else {
671 return Ok(spec.cwd.clone());
672 };
673 let provisioned = provision_worktree(wt)?;
674 record.worktree_path = Some(provisioned.path.clone());
675 record.branch = Some(provisioned.branch.clone());
676 Ok(Some(provisioned.path))
677 }
678
679 fn fail_provisioned_start(
680 backend: &dyn RuntimeBackend,
681 registry: &LaneRegistry,
682 record: &mut LaneRecord,
683 error: anyhow::Error,
684 ) -> anyhow::Error {
685 let mut failed_record = record.clone();
686 let _ = registry.mark_terminal_if_active(record, LaneStatus::Failed);
687 failed_record.stopped_at = record.stopped_at.clone();
688 let _ = backend.cleanup_worktree(&failed_record);
689 error
690 }
691
692 fn prepare_tmux_launch(
693 registry: &LaneRegistry,
694 record: &mut LaneRecord,
695 spec: &LaneStartSpec,
696 cwd: Option<&Path>,
697 session: &str,
698 socket: &Path,
699 dry_run: bool,
700 ) -> Result<Option<(Command, Option<PathBuf>)>> {
701 if spec.worktree.is_some() {
702 registry.persist_worktree(record)?;
703 }
704 append_log_event(
705 &record.log_path,
706 serde_json::json!({
707 "type": "lane_started",
708 "lane_id": record.id,
709 "runtime": "tmux",
710 "session": session,
711 "workflow": record.workflow,
712 "fleet": record.fleet,
713 "issue": record.issue,
714 "dry_run": dry_run,
715 }),
716 )?;
717
718 if dry_run {
719 append_log_event(
720 &record.log_path,
721 serde_json::json!({
722 "type": "lane_log",
723 "message": "tmux dry-run: session recorded without spawning process",
724 "command": spec.command,
725 "cwd": cwd.map(|p| p.display().to_string()),
726 }),
727 )?;
728 if !registry.mark_running_if_pending(record)? {
729 bail!(
730 "lane `{}` was stopped before tmux dry-run start completed",
731 record.id
732 );
733 }
734 return Ok(None);
735 }
736
737 let log_proxy = spec
738 .log_proxy
739 .as_deref()
740 .context("tmux runtime requires a lane log proxy executable")?;
741
742 // Detached session: child output remains an operator journal only.
743 // Terminal control state goes through a separate bounded, atomically
744 // renamed receipt so child stdout cannot forge Lane completion.
745 let receipt_path = lane_exit_receipt_path(&record.log_path);
746 let receipt_tmp_path = lane_exit_receipt_tmp_path(&record.log_path);
747 let environment_path = lane_environment_path(&record.log_path);
748 remove_file_if_present(&receipt_path)?;
749 remove_file_if_present(&receipt_tmp_path)?;
750 remove_file_if_present(&environment_path)?;
751 let environment_path = if spec.environment.is_empty() {
752 None
753 } else {
754 write_lane_environment(&environment_path, &spec.environment)?;
755 Some(environment_path)
756 };
757 let shell_cmd = tmux_log_proxy_command(
758 log_proxy,
759 &spec.command,
760 &record.log_path,
761 &receipt_path,
762 &receipt_tmp_path,
763 environment_path.as_deref(),
764 &record.id,
765 );
766
767 let mut cmd = tmux_command(socket);
768 cmd.args(["new-session", "-d", "-s", session]);
769 if let Some(cwd) = cwd {
770 cmd.arg("-c").arg(cwd);
771 }
772 cmd.arg(shell_cmd);
773 Ok(Some((cmd, environment_path)))
774 }
775
776 /// Durable local tmux sessions + attach + stream-json log file.
777 #[derive(Debug, Default)]
778 pub struct TmuxRuntime;
779
780 impl RuntimeBackend for TmuxRuntime {
781 fn kind(&self) -> RuntimeBackendKind {
782 RuntimeBackendKind::Tmux
783 }
784
785 fn start(
786 &self,
787 registry: &LaneRegistry,
788 record: &mut LaneRecord,
789 spec: &LaneStartSpec,
790 ) -> Result<()> {
791 if spec.command.is_empty() {
792 bail!("tmux runtime requires a non-empty command");
793 }
794 // Dry-run is an explicit test hook only. A missing/broken tmux binary
795 // must fail closed rather than persisting a fictional Running Lane.
796 let dry_run = tmux_dry_run();
797 if !dry_run && let Err(error) = ensure_tmux_available() {
798 append_log_event(
799 &record.log_path,
800 serde_json::json!({
801 "type": "lane_failed",
802 "lane_id": record.id,
803 "runtime": "tmux",
804 "error": error.to_string(),
805 }),
806 )?;
807 let _ = registry.mark_terminal_if_active(record, LaneStatus::Failed)?;
808 return Err(error);
809 }
810
811 let cwd = apply_worktree(record, spec)?;
812 let session = format!("cw-{}", record.id);
813 let socket = registry.root().join("tmux.sock");
814 record.tmux_session = Some(session.clone());
815 record.tmux_socket = Some(socket.clone());
816 record.attach_target = Some(format!(
817 "tmux -S {} attach -t {}",
818 shell_escape(&socket.display().to_string()),
819 shell_escape(&session)
820 ));
821
822 let prepared = match prepare_tmux_launch(
823 registry,
824 record,
825 spec,
826 cwd.as_deref(),
827 &session,
828 &socket,
829 dry_run,
830 ) {
831 Ok(prepared) => prepared,
832 Err(error) => return Err(fail_provisioned_start(self, registry, record, error)),
833 };
834 let Some((mut cmd, environment_path)) = prepared else {
835 return Ok(());
836 };
837 let proposed_record = record.clone();
838 let spawned = std::cell::Cell::new(false);
839 let rolled_back = std::cell::Cell::new(false);
840 match registry.mark_running_if_pending_with(
841 record,
842 || {
843 let status = cmd
844 .status()
845 .with_context(|| format!("spawn tmux session {session}"))?;
846 if !status.success() {
847 bail!("tmux new-session failed with {status}");
848 }
849 spawned.set(true);
850 Ok(())
851 },
852 || {
853 stop_tmux_session(&socket, &session)?;
854 rolled_back.set(true);
855 Ok(())
856 },
857 ) {
858 Ok(true) => {}
859 Ok(false) => {
860 if let Some(path) = environment_path.as_deref() {
861 remove_file_if_present(path)?;
862 }
863 let mut stopped_record = proposed_record;
864 stopped_record.stopped_at = record.stopped_at.clone();
865 self.cleanup_worktree(&stopped_record)?;
866 bail!("lane `{}` was stopped before tmux launch", record.id);
867 }
868 Err(error) => {
869 if let Some(path) = environment_path.as_deref() {
870 let _ = remove_file_if_present(path);
871 }
872 if !spawned.get() || rolled_back.get() {
873 let _ = registry.mark_terminal_if_active(record, LaneStatus::Failed)?;
874 let mut failed_record = proposed_record;
875 failed_record.stopped_at = record.stopped_at.clone();
876 self.cleanup_worktree(&failed_record)?;
877 }
878 return Err(error);
879 }
880 }
881 Ok(())
882 }
883
884 fn attach_command(&self, record: &LaneRecord) -> Option<String> {
885 if record.status != LaneStatus::Running {
886 return None;
887 }
888 let socket = record.tmux_socket.as_ref()?;
889 let session = record.tmux_session.as_deref()?;
890 Some(format!(
891 "tmux -S {} attach -t {}",
892 shell_escape(&socket.display().to_string()),
893 shell_escape(session)
894 ))
895 }
896
897 fn stop(
898 &self,
899 registry: &LaneRegistry,
900 record: &mut LaneRecord,
901 fence: Option<u64>,
902 ) -> Result<TerminalTransition> {
903 let dry_run = tmux_dry_run();
904 let transition = registry.mark_terminal_if_active_fenced(
905 record,
906 LaneStatus::Stopped,
907 fence,
908 |current| {
909 if !dry_run {
910 match (
911 current.tmux_socket.as_deref(),
912 current.tmux_session.as_deref(),
913 ) {
914 (Some(socket), Some(session)) => stop_tmux_session(socket, session)?,
915 _ if current.status == LaneStatus::Running => {
916 bail!(
917 "running tmux lane `{}` has incomplete pinned session metadata; refusing unsafe stop",
918 current.id
919 );
920 }
921 _ => {}
922 }
923 }
924 Ok(())
925 },
926 )?;
927 if transition.transitioned() {
928 append_log_event(
929 &record.log_path,
930 serde_json::json!({
931 "type": "lane_stopped",
932 "lane_id": record.id,
933 "session": record.tmux_session,
934 }),
935 )?;
936 remove_file_if_present(&lane_environment_path(&record.log_path))?;
937 self.cleanup_worktree(record)?;
938 }
939 Ok(transition)
940 }
941
942 fn reconcile(&self, registry: &LaneRegistry, record: &mut LaneRecord) -> Result<bool> {
943 // Pending is the pre-launch state. Never reconcile it: a concurrent
944 // status read must not race a fast `tmux new-session` and overwrite
945 // the start path's later Running transition.
946 if record.status != LaneStatus::Running {
947 return Ok(false);
948 }
949
950 let receipt = read_lane_exit_receipt(&record.log_path, &record.id)?;
951 let (lane_status, exit_code, reason) = if let Some(receipt) = receipt {
952 (
953 if receipt.exit_code == 0 {
954 LaneStatus::Completed
955 } else {
956 LaneStatus::Failed
957 },
958 Some(receipt.exit_code),
959 "process_exit_receipt",
960 )
961 } else {
962 if tmux_dry_run() {
963 return Ok(false);
964 }
965 let (Some(socket), Some(session)) = (
966 record.tmux_socket.as_deref(),
967 record.tmux_session.as_deref(),
968 ) else {
969 bail!(
970 "running tmux lane `{}` lacks pinned socket/session metadata; refusing unsafe reconciliation",
971 record.id
972 );
973 };
974 match tmux_session_state(socket, session)? {
975 TmuxSessionState::Present => return Ok(false),
976 TmuxSessionState::Absent => {}
977 }
978 (
979 LaneStatus::Failed,
980 None,
981 "tmux_session_missing_without_exit_receipt",
982 )
983 };
984
985 if registry.mark_terminal_if_active(record, lane_status)? {
986 append_log_event(
987 &record.log_path,
988 serde_json::json!({
989 "type": "lane_reconciled",
990 "lane_id": record.id,
991 "exit_code": exit_code,
992 "status": lane_status.as_str(),
993 "reason": reason,
994 }),
995 )?;
996 remove_file_if_present(&lane_environment_path(&record.log_path))?;
997 self.cleanup_worktree(record)?;
998 return Ok(true);
999 }
1000 Ok(false)
1001 }
1002 }
1003
1004 /// In-process / local command runtime (no tmux). Used for tests and headless.
1005 #[derive(Debug, Default)]
1006 pub struct InlineRuntime;
1007
1008 impl RuntimeBackend for InlineRuntime {
1009 fn kind(&self) -> RuntimeBackendKind {
1010 RuntimeBackendKind::Inline
1011 }
1012
1013 fn start(
1014 &self,
1015 registry: &LaneRegistry,
1016 record: &mut LaneRecord,
1017 spec: &LaneStartSpec,
1018 ) -> Result<()> {
1019 if spec.command.is_empty() {
1020 bail!("inline runtime requires a non-empty command");
1021 }
1022 let cwd = apply_worktree(record, spec)?;
1023 let proposed_record = record.clone();
1024 let announced = (|| -> Result<()> {
1025 if spec.worktree.is_some() {
1026 registry.persist_worktree(record)?;
1027 }
1028 append_log_event(
1029 &record.log_path,
1030 serde_json::json!({
1031 "type": "lane_started",
1032 "lane_id": record.id,
1033 "runtime": "inline",
1034 "command": spec.command,
1035 }),
1036 )
1037 })();
1038 if let Err(error) = announced {
1039 return Err(fail_provisioned_start(self, registry, record, error));
1040 }
1041 if !registry.mark_running_if_pending(record)? {
1042 let mut stopped_record = proposed_record;
1043 stopped_record.stopped_at = record.stopped_at.clone();
1044 self.cleanup_worktree(&stopped_record)?;
1045 bail!(
1046 "lane `{}` was stopped before inline start completed",
1047 record.id
1048 );
1049 }
1050
1051 let mut cmd = Command::new(&spec.command[0]);
1052 if spec.command.len() > 1 {
1053 cmd.args(&spec.command[1..]);
1054 }
1055 if let Some(cwd) = cwd.as_ref() {
1056 cmd.current_dir(cwd);
1057 }
1058 cmd.envs(spec.environment.iter().map(|(key, value)| (key, value)));
1059 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
1060 let mut child = match cmd.spawn() {
1061 Ok(child) => child,
1062 Err(err) => {
1063 append_log_event(
1064 &record.log_path,
1065 serde_json::json!({
1066 "type": "lane_failed",
1067 "lane_id": record.id,
1068 "error": err.to_string(),
1069 }),
1070 )?;
1071 let _ = registry.mark_terminal_if_active(record, LaneStatus::Failed)?;
1072 // Terminal now, so no later stop will clean the worktree up.
1073 self.cleanup_worktree(record)?;
1074 return Err(err).with_context(|| format!("run inline command {:?}", spec.command));
1075 }
1076 };
1077 let stdout = child
1078 .stdout
1079 .take()
1080 .context("inline lane child stdout was not piped")?;
1081 let stderr = child
1082 .stderr
1083 .take()
1084 .context("inline lane child stderr was not piped")?;
1085 let stdout_log = record.log_path.clone();
1086 let stderr_log = record.log_path.clone();
1087 let stdout_thread =
1088 thread::spawn(move || stream_child_output(stdout, stdout_log, "stdout"));
1089 let stderr_thread =
1090 thread::spawn(move || stream_child_output(stderr, stderr_log, "stderr"));
1091 let status = child
1092 .wait()
1093 .with_context(|| format!("wait for inline command {:?}", spec.command))?;
1094 let stdout_result = stdout_thread
1095 .join()
1096 .map_err(|_| anyhow::anyhow!("inline stdout logger panicked"))?;
1097 let stderr_result = stderr_thread
1098 .join()
1099 .map_err(|_| anyhow::anyhow!("inline stderr logger panicked"))?;
1100 let logging_error = stdout_result.err().or_else(|| stderr_result.err());
1101
1102 if status.success() && logging_error.is_none() {
1103 append_log_event(
1104 &record.log_path,
1105 serde_json::json!({"type": "lane_completed", "lane_id": record.id}),
1106 )?;
1107 let _ = registry.mark_terminal_if_active(record, LaneStatus::Completed)?;
1108 } else {
1109 append_log_event(
1110 &record.log_path,
1111 serde_json::json!({
1112 "type": "lane_failed",
1113 "lane_id": record.id,
1114 "status": format!("{status}"),
1115 "logging_error": logging_error.as_ref().map(ToString::to_string),
1116 }),
1117 )?;
1118 let _ = registry.mark_terminal_if_active(record, LaneStatus::Failed)?;
1119 }
1120 if let Some(err) = logging_error {
1121 return Err(err).context("stream inline lane output");
1122 }
1123 Ok(())
1124 }
1125
1126 fn attach_command(&self, _record: &LaneRecord) -> Option<String> {
1127 None
1128 }
1129
1130 fn stop(
1131 &self,
1132 registry: &LaneRegistry,
1133 record: &mut LaneRecord,
1134 fence: Option<u64>,
1135 ) -> Result<TerminalTransition> {
1136 let transition = registry.mark_terminal_if_active_fenced(
1137 record,
1138 LaneStatus::Stopped,
1139 fence,
1140 |current| {
1141 if current.status == LaneStatus::Running {
1142 bail!(
1143 "inline lane `{}` cannot be stopped safely from another process",
1144 current.id
1145 );
1146 }
1147 Ok(())
1148 },
1149 )?;
1150 if transition.transitioned() {
1151 self.cleanup_worktree(record)?;
1152 }
1153 Ok(transition)
1154 }
1155 }
1156
1157 /// Backend for a lane record written by an earlier release under the retired
1158 /// `vm` / `ci` runtimes. It never starts anything: [`RuntimeBackendKind::parse`]
1159 /// cannot produce these kinds, so only historical records reach it, and they
1160 /// can still be listed, reconciled, and stopped.
1161 #[derive(Debug)]
1162 struct RetiredRuntime {
1163 kind: RuntimeBackendKind,
1164 }
1165
1166 impl RuntimeBackend for RetiredRuntime {
1167 fn kind(&self) -> RuntimeBackendKind {
1168 self.kind
1169 }
1170
1171 fn start(
1172 &self,
1173 _registry: &LaneRegistry,
1174 _record: &mut LaneRecord,
1175 _spec: &LaneStartSpec,
1176 ) -> Result<()> {
1177 bail!(
1178 "{} runtime is not available; use tmux or inline",
1179 self.kind.as_str()
1180 )
1181 }
1182
1183 fn attach_command(&self, _record: &LaneRecord) -> Option<String> {
1184 None
1185 }
1186
1187 fn stop(
1188 &self,
1189 registry: &LaneRegistry,
1190 record: &mut LaneRecord,
1191 fence: Option<u64>,
1192 ) -> Result<TerminalTransition> {
1193 registry.mark_terminal_if_active_fenced(record, LaneStatus::Stopped, fence, |_| Ok(()))
1194 }
1195 }
1196
1197 fn shell_escape(s: &str) -> String {
1198 format!("'{}'", s.replace('\'', "'\\''"))
1199 }
1200
1201 fn shell_join(args: &[String]) -> String {
1202 args.iter()
1203 .map(|a| shell_escape(a))
1204 .collect::<Vec<_>>()
1205 .join(" ")
1206 }
1207
1208 #[cfg(test)]
1209 mod tests {
1210 use super::*;
1211 use std::ffi::OsString;
1212 use std::sync::{Mutex, MutexGuard, OnceLock};
1213 use tempfile::tempdir;
1214
1215 fn tmux_env_lock() -> MutexGuard<'static, ()> {
1216 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1217 LOCK.get_or_init(|| Mutex::new(()))
1218 .lock()
1219 .unwrap_or_else(|poisoned| poisoned.into_inner())
1220 }
1221
1222 struct ScopedEnvVar {
1223 name: &'static str,
1224 previous: Option<OsString>,
1225 }
1226
1227 impl ScopedEnvVar {
1228 fn set(name: &'static str, value: &std::ffi::OsStr) -> Self {
1229 let previous = std::env::var_os(name);
1230 // SAFETY: tmux environment tests hold `tmux_env_lock` and restore
1231 // the process environment in Drop.
1232 unsafe { std::env::set_var(name, value) };
1233 Self { name, previous }
1234 }
1235
1236 #[cfg(unix)]
1237 fn remove(name: &'static str) -> Self {
1238 let previous = std::env::var_os(name);
1239 // SAFETY: tmux environment tests hold `tmux_env_lock` and restore
1240 // the process environment in Drop.
1241 unsafe { std::env::remove_var(name) };
1242 Self { name, previous }
1243 }
1244 }
1245
1246 impl Drop for ScopedEnvVar {
1247 fn drop(&mut self) {
1248 // SAFETY: paired with the serialized mutation above.
1249 unsafe {
1250 if let Some(previous) = self.previous.take() {
1251 std::env::set_var(self.name, previous);
1252 } else {
1253 std::env::remove_var(self.name);
1254 }
1255 }
1256 }
1257 }
1258
1259 #[test]
1260 fn tmux_dry_run_start_attach_stop_roundtrip() {
1261 let _env_guard = tmux_env_lock();
1262 let _dry_run = ScopedEnvVar::set("CODEWHALE_LANE_TMUX_DRY_RUN", std::ffi::OsStr::new("1"));
1263 let dir = tempdir().unwrap();
1264 let reg = LaneRegistry::open(dir.path()).unwrap();
1265 let mut record = reg
1266 .create_pending(
1267 Some("stopship".into()),
1268 Some("stopship".into()),
1269 Some("4375".into()),
1270 None,
1271 RuntimeBackendKind::Tmux,
1272 None,
1273 )
1274 .unwrap();
1275 let backend = TmuxRuntime;
1276 backend
1277 .start(
1278 &reg,
1279 &mut record,
1280 &LaneStartSpec {
1281 command: vec!["echo".into(), "hello-lane".into()],
1282 cwd: None,
1283 environment: Vec::new(),
1284 log_proxy: None,
1285 worktree: None,
1286 },
1287 )
1288 .unwrap();
1289 assert_eq!(record.status, LaneStatus::Running);
1290 assert!(record.tmux_session.is_some());
1291 let expected_socket = reg.root().join("tmux.sock");
1292 assert_eq!(
1293 record.tmux_socket.as_deref(),
1294 Some(expected_socket.as_path())
1295 );
1296 let attach = backend.attach_command(&record).expect("attach");
1297 assert!(attach.contains("tmux -S"));
1298 assert!(attach.contains(&expected_socket.display().to_string()));
1299 assert!(attach.contains("attach -t"));
1300 let log = std::fs::read_to_string(&record.log_path).unwrap();
1301 assert!(log.contains("lane_started"));
1302
1303 backend.stop(&reg, &mut record, None).unwrap();
1304 assert_eq!(record.status, LaneStatus::Stopped);
1305 let reloaded = reg.load(&record.id).unwrap();
1306 assert_eq!(reloaded.status, LaneStatus::Stopped);
1307 }
1308
1309 #[cfg(unix)]
1310 #[test]
1311 fn unavailable_tmux_fails_lane_instead_of_faking_running() {
1312 use std::os::unix::fs::symlink;
1313
1314 let _env_guard = tmux_env_lock();
1315 let dir = tempdir().unwrap();
1316 let bin_dir = dir.path().join("bin");
1317 fs::create_dir(&bin_dir).unwrap();
1318 symlink("/usr/bin/false", bin_dir.join("tmux")).unwrap();
1319 let prior_path = std::env::var_os("PATH").unwrap_or_default();
1320 let combined_path = std::env::join_paths(
1321 std::iter::once(bin_dir).chain(std::env::split_paths(&prior_path)),
1322 )
1323 .unwrap();
1324 let _path = ScopedEnvVar::set("PATH", &combined_path);
1325 let _dry_run = ScopedEnvVar::remove("CODEWHALE_LANE_TMUX_DRY_RUN");
1326
1327 let reg = LaneRegistry::open(dir.path().join("registry")).unwrap();
1328 let mut record = reg
1329 .create_pending(None, None, None, None, RuntimeBackendKind::Tmux, None)
1330 .unwrap();
1331 let error = TmuxRuntime
1332 .start(
1333 &reg,
1334 &mut record,
1335 &LaneStartSpec {
1336 command: vec!["/bin/true".to_string()],
1337 cwd: None,
1338 environment: Vec::new(),
1339 log_proxy: Some(PathBuf::from("/bin/true")),
1340 worktree: None,
1341 },
1342 )
1343 .unwrap_err();
1344 assert!(error.to_string().contains("tmux runtime is unavailable"));
1345 assert_eq!(record.status, LaneStatus::Failed);
1346 assert_eq!(reg.load(&record.id).unwrap().status, LaneStatus::Failed);
1347 assert!(
1348 String::from_utf8_lossy(&fs::read(&record.log_path).unwrap()).contains("lane_failed")
1349 );
1350 }
1351
1352 #[test]
1353 fn retired_remote_runtimes_are_rejected_before_a_lane_is_created() {
1354 for raw in ["vm", "ci", " VM "] {
1355 let error = RuntimeBackendKind::parse(raw).unwrap_err().to_string();
1356 assert!(error.contains("not available"), "{error}");
1357 assert!(error.contains("tmux or inline"), "{error}");
1358 }
1359 assert_eq!(
1360 RuntimeBackendKind::parse("inline").unwrap(),
1361 RuntimeBackendKind::Inline
1362 );
1363 }
1364
1365 #[test]
1366 fn historical_retired_runtime_records_still_load_and_stop() {
1367 for kind in [RuntimeBackendKind::Vm, RuntimeBackendKind::Ci] {
1368 let dir = tempdir().unwrap();
1369 let reg = LaneRegistry::open(dir.path()).unwrap();
1370 let mut record = reg
1371 .create_pending(None, None, None, None, kind, None)
1372 .unwrap();
1373 assert_eq!(reg.list().unwrap().len(), 1, "record must not be skipped");
1374 assert_eq!(reg.load(&record.id).unwrap().runtime, kind);
1375 resolve_backend(kind)
1376 .stop(&reg, &mut record, None)
1377 .expect("a retired-runtime record can still be stopped");
1378 assert!(resolve_backend(kind).attach_command(&record).is_none());
1379 }
1380 }
1381
1382 #[test]
1383 fn inline_runtime_writes_stream_json_log() {
1384 let dir = tempdir().unwrap();
1385 let reg = LaneRegistry::open(dir.path()).unwrap();
1386 let mut record = reg
1387 .create_pending(
1388 Some("demo".into()),
1389 None,
1390 None,
1391 Some("echo".into()),
1392 RuntimeBackendKind::Inline,
1393 None,
1394 )
1395 .unwrap();
1396 InlineRuntime
1397 .start(
1398 &reg,
1399 &mut record,
1400 &LaneStartSpec {
1401 command: vec!["echo".into(), "inline-ok".into()],
1402 cwd: None,
1403 environment: Vec::new(),
1404 log_proxy: None,
1405 worktree: None,
1406 },
1407 )
1408 .unwrap();
1409 assert_eq!(record.status, LaneStatus::Completed);
1410 let log = std::fs::read_to_string(&record.log_path).unwrap();
1411 assert!(log.contains("inline-ok"), "log={log}");
1412 assert!(log.contains("lane_completed"));
1413 }
1414
1415 /// Audit R06-05: an inline command that cannot spawn marks the lane
1416 /// failed and cleans up the worktree it provisioned. The lane is terminal
1417 /// at that point, so no later stop would.
1418 #[test]
1419 fn inline_spawn_failure_cleans_up_its_worktree() {
1420 let dir = tempdir().unwrap();
1421 let repo = dir.path().join("repo");
1422 std::fs::create_dir_all(&repo).unwrap();
1423 crate::worktree::tests::init_repo(&repo);
1424 let wt_path = dir.path().join("wt-inline");
1425 let reg = LaneRegistry::open(dir.path().join("lanes")).unwrap();
1426 let mut record = reg
1427 .create_pending(None, None, None, None, RuntimeBackendKind::Inline, Some(0))
1428 .unwrap();
1429 let result = InlineRuntime.start(
1430 &reg,
1431 &mut record,
1432 &LaneStartSpec {
1433 command: vec!["/nonexistent/codewhale-lane-test-binary".into()],
1434 cwd: None,
1435 environment: Vec::new(),
1436 log_proxy: None,
1437 worktree: Some(WorktreeProvision {
1438 repo_root: repo,
1439 branch: "codex/lane-spawn-fail".into(),
1440 path: wt_path.clone(),
1441 base_ref: Some("main".into()),
1442 }),
1443 },
1444 );
1445 assert!(result.is_err());
1446 assert_eq!(record.status, LaneStatus::Failed);
1447 assert!(
1448 !wt_path.exists(),
1449 "the failed lane's worktree was left behind"
1450 );
1451 }
1452
1453 #[test]
1454 fn start_failure_after_provisioning_keeps_the_worktree_accounted_for() {
1455 for ttl in [Some(0), None] {
1456 let dir = tempdir().unwrap();
1457 let repo = dir.path().join("repo");
1458 std::fs::create_dir_all(&repo).unwrap();
1459 crate::worktree::tests::init_repo(&repo);
1460 let wt_path = dir.path().join("wt-unwritable-log");
1461 let reg = LaneRegistry::open(dir.path().join("lanes")).unwrap();
1462 let mut record = reg
1463 .create_pending(None, None, None, None, RuntimeBackendKind::Inline, ttl)
1464 .unwrap();
1465 let id = record.id.clone();
1466 record.log_path = dir.path().join("missing-dir").join("lane.ndjson");
1467 let result = InlineRuntime.start(
1468 &reg,
1469 &mut record,
1470 &LaneStartSpec {
1471 command: vec!["echo".into(), "never-runs".into()],
1472 cwd: None,
1473 environment: Vec::new(),
1474 log_proxy: None,
1475 worktree: Some(WorktreeProvision {
1476 repo_root: repo,
1477 branch: "codex/lane-log-fail".into(),
1478 path: wt_path.clone(),
1479 base_ref: Some("main".into()),
1480 }),
1481 },
1482 );
1483 let error = result.unwrap_err().to_string();
1484 assert!(error.contains("open lane log"), "ttl={ttl:?}: {error}");
1485 assert_eq!(record.status, LaneStatus::Failed, "ttl={ttl:?}");
1486 let stored = reg.load(&id).unwrap();
1487 assert_eq!(stored.status, LaneStatus::Failed, "ttl={ttl:?}");
1488 assert_eq!(stored.worktree_path.as_deref(), Some(wt_path.as_path()));
1489 assert_eq!(stored.branch.as_deref(), Some("codex/lane-log-fail"));
1490 assert_eq!(wt_path.exists(), ttl.is_none(), "ttl={ttl:?}");
1491 }
1492 }
1493
1494 #[test]
1495 fn lane_start_spec_debug_redacts_environment_values() {
1496 let spec = LaneStartSpec {
1497 command: vec!["codewhale-tui".into()],
1498 cwd: None,
1499 environment: vec![("DEEPSEEK_API_KEY".into(), "secret-value".into())],
1500 log_proxy: None,
1501 worktree: None,
1502 };
1503 let rendered = format!("{spec:?}");
1504 assert!(rendered.contains("DEEPSEEK_API_KEY"));
1505 assert!(!rendered.contains("secret-value"));
1506 }
1507
1508 #[cfg(unix)]
1509 #[test]
1510 fn inline_runtime_persists_typed_receipts_before_process_exit() {
1511 let dir = tempdir().unwrap();
1512 let reg = LaneRegistry::open(dir.path()).unwrap();
1513 let record = reg
1514 .create_pending(
1515 Some("demo".into()),
1516 None,
1517 None,
1518 None,
1519 RuntimeBackendKind::Inline,
1520 None,
1521 )
1522 .unwrap();
1523 let log_path = record.log_path.clone();
1524 let (done_tx, done_rx) = std::sync::mpsc::channel();
1525 let handle = thread::spawn(move || {
1526 let mut record = record;
1527 let result = InlineRuntime.start(
1528 &reg,
1529 &mut record,
1530 &LaneStartSpec {
1531 command: vec![
1532 "sh".into(),
1533 "-c".into(),
1534 "printf '%s\\n' '{\"type\":\"workflow_event\",\"run_id\":\"workflow_live\",\"event\":{\"type\":\"run_started\"}}'; sleep 0.25; printf done"
1535 .into(),
1536 ],
1537 cwd: None,
1538 environment: Vec::new(),
1539 log_proxy: None,
1540 worktree: None,
1541 },
1542 );
1543 let _ = done_tx.send(result);
1544 });
1545
1546 let mut observed_live = false;
1547 for _ in 0..50 {
1548 let log = std::fs::read_to_string(&log_path).unwrap_or_default();
1549 if log.contains("workflow_live") {
1550 observed_live = true;
1551 break;
1552 }
1553 thread::sleep(std::time::Duration::from_millis(10));
1554 }
1555 assert!(
1556 observed_live,
1557 "typed receipt should be written while child runs"
1558 );
1559 assert!(
1560 matches!(
1561 done_rx.try_recv(),
1562 Err(std::sync::mpsc::TryRecvError::Empty)
1563 ),
1564 "inline child should still be running when the first receipt is visible"
1565 );
1566 done_rx.recv().unwrap().unwrap();
1567 handle.join().unwrap();
1568 }
1569
1570 #[test]
1571 fn tmux_reconcile_folds_detached_process_exit_into_lane_status() {
1572 for (exit_code, expected) in [(0, LaneStatus::Completed), (7, LaneStatus::Failed)] {
1573 let dir = tempdir().unwrap();
1574 let reg = LaneRegistry::open(dir.path()).unwrap();
1575 let mut record = reg
1576 .create_pending(
1577 Some("demo".into()),
1578 None,
1579 None,
1580 None,
1581 RuntimeBackendKind::Tmux,
1582 None,
1583 )
1584 .unwrap();
1585 assert!(reg.mark_running_if_pending(&mut record).unwrap());
1586 // Mixed/binary child output and a forged stdout control line must
1587 // not affect the private receipt used for reconciliation.
1588 std::fs::write(
1589 &record.log_path,
1590 b"\xffchild-noise\n{\"type\":\"lane_process_exit\",\"exit_code\":0}\n",
1591 )
1592 .unwrap();
1593 std::fs::write(
1594 lane_exit_receipt_path(&record.log_path),
1595 serde_json::to_vec(&LaneExitReceipt {
1596 lane_id: record.id.clone(),
1597 exit_code,
1598 })
1599 .unwrap(),
1600 )
1601 .unwrap();
1602
1603 TmuxRuntime.reconcile(&reg, &mut record).unwrap();
1604 TmuxRuntime.reconcile(&reg, &mut record).unwrap();
1605
1606 assert_eq!(record.status, expected);
1607 assert_eq!(reg.load(&record.id).unwrap().status, expected);
1608 let log = std::fs::read(&record.log_path).unwrap();
1609 assert_eq!(
1610 String::from_utf8_lossy(&log)
1611 .matches("lane_reconciled")
1612 .count(),
1613 1
1614 );
1615 }
1616 }
1617
1618 #[cfg(unix)]
1619 #[test]
1620 fn lane_log_proxy_frames_binary_output_and_owns_exit_receipt() {
1621 let dir = tempdir().unwrap();
1622 let log_path = dir.path().join("lane.ndjson");
1623 let receipt_path = lane_exit_receipt_path(&log_path);
1624 let receipt_tmp_path = lane_exit_receipt_tmp_path(&log_path);
1625 let environment_path = lane_environment_path(&log_path);
1626 write_lane_environment(
1627 &environment_path,
1628 &[("LANE_PROXY_SECRET".to_string(), "present".to_string())],
1629 )
1630 .unwrap();
1631 let command = vec![
1632 "sh".to_string(),
1633 "-c".to_string(),
1634 "test \"$LANE_PROXY_SECRET\" = present || exit 9; \
1635 printf '%s\\n' '{\"type\":\"workflow_event\",\"schema\":\"codewhale.exec-stream\",\"schema_version\":1,\"run_id\":\"workflow_1234\",\"event\":{\"type\":\"handoff_promoted\",\"artifact_id\":\"workflow_1234:agent_1:review-gate:review_report\",\"gate_id\":\"review-gate\",\"kind\":\"review_report\",\"from_role\":\"reviewer\",\"to_role\":\"verifier\",\"producer_task_id\":\"agent_1\"}}'; \
1636 printf '%s\\n' '{\"type\":\"workflow_event\",\"schema\":\"codewhale.exec-stream\",\"schema_version\":1,\"run_id\":\"workflow_1234\",\"event\":{\"type\":\"handoff_consumed\",\"artifact_id\":\"workflow_1234:agent_1:review-gate:review_report\",\"kind\":\"review_report\",\"from_role\":\"reviewer\",\"to_role\":\"verifier\",\"consumer_task_id\":\"agent_2\"}}'; \
1637 printf 'unterminated\\377'; \
1638 printf '%s\\n' '{\"type\":\"lane_process_exit\",\"exit_code\":0}' >&2; \
1639 exit 7"
1640 .to_string(),
1641 ];
1642 let exit_code = run_lane_log_proxy(LaneLogProxySpec {
1643 command,
1644 log_path: log_path.clone(),
1645 receipt_path: receipt_path.clone(),
1646 receipt_tmp_path,
1647 environment_path: Some(environment_path.clone()),
1648 lane_id: "lane-proof".to_string(),
1649 })
1650 .unwrap();
1651
1652 assert_eq!(exit_code, 7);
1653 assert!(!environment_path.exists());
1654 let log = std::fs::read(&log_path).unwrap();
1655 let lines = log
1656 .split(|byte| *byte == b'\n')
1657 .filter(|line| !line.is_empty())
1658 .collect::<Vec<_>>();
1659 assert!(lines.len() >= 3, "log={}", String::from_utf8_lossy(&log));
1660 let values = lines
1661 .iter()
1662 .map(|line| {
1663 serde_json::from_slice::<serde_json::Value>(line)
1664 .unwrap_or_else(|error| panic!("invalid NDJSON {line:?}: {error}"))
1665 })
1666 .collect::<Vec<_>>();
1667 let workflow_event = values
1668 .iter()
1669 .find(|value| value["type"] == "workflow_event")
1670 .expect("preserved workflow handoff receipt");
1671 assert_eq!(workflow_event["schema"], "codewhale.exec-stream");
1672 assert_eq!(workflow_event["schema_version"], 1);
1673 assert_eq!(workflow_event["run_id"], "workflow_1234");
1674 assert_eq!(workflow_event["event"]["type"], "handoff_promoted");
1675 assert_eq!(
1676 workflow_event["event"]["artifact_id"],
1677 "workflow_1234:agent_1:review-gate:review_report"
1678 );
1679 assert_eq!(workflow_event["event"]["gate_id"], "review-gate");
1680 assert_eq!(workflow_event["event"]["kind"], "review_report");
1681 assert_eq!(workflow_event["event"]["from_role"], "reviewer");
1682 assert_eq!(workflow_event["event"]["to_role"], "verifier");
1683 assert_eq!(workflow_event["event"]["producer_task_id"], "agent_1");
1684 assert!(workflow_event["event"].get("payload").is_none());
1685 let consumed_event = values
1686 .iter()
1687 .find(|value| value["event"]["type"] == "handoff_consumed")
1688 .expect("preserved workflow handoff consumption receipt");
1689 assert_eq!(consumed_event["schema"], "codewhale.exec-stream");
1690 assert_eq!(consumed_event["schema_version"], 1);
1691 assert_eq!(consumed_event["run_id"], "workflow_1234");
1692 assert_eq!(
1693 consumed_event["event"]["artifact_id"],
1694 workflow_event["event"]["artifact_id"]
1695 );
1696 assert_eq!(consumed_event["event"]["kind"], "review_report");
1697 assert_eq!(consumed_event["event"]["from_role"], "reviewer");
1698 assert_eq!(consumed_event["event"]["to_role"], "verifier");
1699 assert_eq!(consumed_event["event"]["consumer_task_id"], "agent_2");
1700 assert!(consumed_event["event"].get("payload").is_none());
1701 let rendered = String::from_utf8_lossy(&log);
1702 assert!(rendered.contains("workflow_event"));
1703 assert!(rendered.contains("lane_process_exit"));
1704 assert!(rendered.contains("lane_log"));
1705 let receipt = read_lane_exit_receipt(&log_path, "lane-proof")
1706 .unwrap()
1707 .expect("private receipt");
1708 assert_eq!(receipt.exit_code, 7);
1709 }
1710
1711 #[test]
1712 fn invalid_environment_key_never_leaves_a_partial_secret_file() {
1713 let dir = tempdir().unwrap();
1714 let path = dir.path().join("lane.env.json");
1715 let result = write_lane_environment(
1716 &path,
1717 &[
1718 ("VALID_KEY".to_string(), "first-secret".to_string()),
1719 ("INVALID-KEY".to_string(), "second-secret".to_string()),
1720 ],
1721 );
1722 assert!(result.is_err());
1723 assert!(!path.exists());
1724 assert!(!lane_environment_tmp_path(&path).exists());
1725 }
1726
1727 #[cfg(unix)]
1728 #[test]
1729 fn private_environment_is_mode_0600_and_malformed_input_is_removed() {
1730 use std::os::unix::fs::PermissionsExt;
1731
1732 let dir = tempdir().unwrap();
1733 let path = dir.path().join("lane.env.json");
1734 write_lane_environment(&path, &[("SECRET".to_string(), "sensitive".to_string())]).unwrap();
1735 assert_eq!(
1736 fs::metadata(&path).unwrap().permissions().mode() & 0o777,
1737 0o600
1738 );
1739
1740 fs::write(&path, b"{malformed").unwrap();
1741 let log_path = dir.path().join("lane.ndjson");
1742 let exit_code = run_lane_log_proxy(LaneLogProxySpec {
1743 command: vec!["/bin/true".to_string()],
1744 receipt_path: lane_exit_receipt_path(&log_path),
1745 receipt_tmp_path: lane_exit_receipt_tmp_path(&log_path),
1746 environment_path: Some(path.clone()),
1747 lane_id: "lane-malformed-env".to_string(),
1748 log_path: log_path.clone(),
1749 })
1750 .unwrap();
1751 assert_eq!(exit_code, LANE_PROXY_FAILURE_EXIT_CODE);
1752 assert!(!path.exists());
1753 assert!(String::from_utf8_lossy(&fs::read(log_path).unwrap()).contains("lane_proxy_error"));
1754 }
1755
1756 #[cfg(unix)]
1757 #[test]
1758 fn tmux_stop_failure_keeps_lane_running_and_preserves_cleanup_targets() {
1759 use std::os::unix::fs::symlink;
1760
1761 let _env_guard = tmux_env_lock();
1762 let dir = tempdir().unwrap();
1763 let bin_dir = dir.path().join("bin");
1764 fs::create_dir(&bin_dir).unwrap();
1765 symlink("/usr/bin/false", bin_dir.join("tmux")).unwrap();
1766 let prior_path = std::env::var_os("PATH").unwrap_or_default();
1767 let combined_path = std::env::join_paths(
1768 std::iter::once(bin_dir.clone()).chain(std::env::split_paths(&prior_path)),
1769 )
1770 .unwrap();
1771 let _path = ScopedEnvVar::set("PATH", &combined_path);
1772 let _dry_run = ScopedEnvVar::remove("CODEWHALE_LANE_TMUX_DRY_RUN");
1773
1774 let reg = LaneRegistry::open(dir.path().join("registry")).unwrap();
1775 let mut record = reg
1776 .create_pending(
1777 Some("demo".into()),
1778 None,
1779 None,
1780 None,
1781 RuntimeBackendKind::Tmux,
1782 Some(0),
1783 )
1784 .unwrap();
1785 record.tmux_session = Some(format!("cw-{}", record.id));
1786 record.tmux_socket = Some(reg.root().join("tmux.sock"));
1787 let worktree = dir.path().join("worktree");
1788 fs::create_dir(&worktree).unwrap();
1789 record.worktree_path = Some(worktree.clone());
1790 let environment_path = lane_environment_path(&record.log_path);
1791 write_lane_environment(
1792 &environment_path,
1793 &[("SECRET".to_string(), "still-private".to_string())],
1794 )
1795 .unwrap();
1796 assert!(reg.mark_running_if_pending(&mut record).unwrap());
1797
1798 let error = TmuxRuntime.stop(&reg, &mut record, None).unwrap_err();
1799 assert!(format!("{error:#}").contains("tmux has-session"));
1800 assert_eq!(record.status, LaneStatus::Running);
1801 assert_eq!(reg.load(&record.id).unwrap().status, LaneStatus::Running);
1802 assert!(environment_path.exists());
1803 assert!(worktree.exists());
1804 }
1805
1806 #[cfg(unix)]
1807 #[test]
1808 fn tmux_reconcile_marks_vanished_session_failed_without_receipt() {
1809 use std::os::unix::fs::PermissionsExt;
1810
1811 let _env_guard = tmux_env_lock();
1812 let dir = tempdir().unwrap();
1813 let bin_dir = dir.path().join("bin");
1814 fs::create_dir(&bin_dir).unwrap();
1815 let tmux = bin_dir.join("tmux");
1816 fs::write(
1817 &tmux,
1818 "#!/bin/sh\nprintf '%s\\n' 'no server running on /tmp/codewhale-test.sock' >&2\nexit 1\n",
1819 )
1820 .unwrap();
1821 let mut permissions = fs::metadata(&tmux).unwrap().permissions();
1822 permissions.set_mode(0o755);
1823 fs::set_permissions(&tmux, permissions).unwrap();
1824 let prior_path = std::env::var_os("PATH").unwrap_or_default();
1825 let combined_path = std::env::join_paths(
1826 std::iter::once(bin_dir).chain(std::env::split_paths(&prior_path)),
1827 )
1828 .unwrap();
1829 let _path = ScopedEnvVar::set("PATH", &combined_path);
1830 let _dry_run = ScopedEnvVar::remove("CODEWHALE_LANE_TMUX_DRY_RUN");
1831
1832 let reg = LaneRegistry::open(dir.path()).unwrap();
1833 let mut record = reg
1834 .create_pending(
1835 Some("demo".into()),
1836 None,
1837 None,
1838 None,
1839 RuntimeBackendKind::Tmux,
1840 None,
1841 )
1842 .unwrap();
1843 record.tmux_session = Some(format!("missing-{}", record.id));
1844 record.tmux_socket = Some(reg.root().join("tmux.sock"));
1845 assert!(reg.mark_running_if_pending(&mut record).unwrap());
1846
1847 TmuxRuntime.reconcile(&reg, &mut record).unwrap();
1848
1849 assert_eq!(record.status, LaneStatus::Failed);
1850 let log = std::fs::read_to_string(&record.log_path).unwrap();
1851 assert!(log.contains("tmux_session_missing_without_exit_receipt"));
1852 }
1853 }
1854
1854 lines RUST