diff --git a/.gitignore b/.gitignore index 509500a..d280c02 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ target/ .DS_Store .forge/logs/ +.forge/state/ *.log diff --git a/Cargo.lock b/Cargo.lock index 93e5d53..06ea21c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -67,18 +67,36 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + [[package]] name = "atomic-waker" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.11.1" @@ -215,7 +233,7 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6" dependencies = [ - "bitflags", + "bitflags 2.11.1", "crossterm_winapi", "futures-core", "mio", @@ -310,6 +328,12 @@ dependencies = [ "syn", ] +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "either" version = "1.15.0" @@ -332,6 +356,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -352,6 +387,8 @@ dependencies = [ "crossterm", "dirs", "futures", + "libc", + "portable-pty", "ratatui", "reqwest", "serde", @@ -750,6 +787,15 @@ dependencies = [ "syn", ] +[[package]] +name = "ioctl-rs" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7970510895cee30b3e9128319f2cefd4bde883a39f38baa279567ba3a7eb97d" +dependencies = [ + "libc", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -877,6 +923,15 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + [[package]] name = "mio" version = "1.2.0" @@ -889,6 +944,20 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset", + "pin-utils", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -963,6 +1032,33 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "portable-pty" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806ee80c2a03dbe1a9fb9534f8d19e4c0546b790cde8fd1fea9d6390644cb0be" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix", + "serial", + "shared_library", + "shell-words", + "winapi", + "winreg", +] + [[package]] name = "potential_utf" version = "0.1.5" @@ -1101,7 +1197,7 @@ version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b" dependencies = [ - "bitflags", + "bitflags 2.11.1", "cassowary", "compact_str", "crossterm", @@ -1122,7 +1218,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.11.1", ] [[package]] @@ -1217,7 +1313,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags", + "bitflags 2.11.1", "errno", "libc", "linux-raw-sys", @@ -1341,6 +1437,48 @@ dependencies = [ "serde", ] +[[package]] +name = "serial" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1237a96570fc377c13baa1b88c7589ab66edced652e43ffb17088f003db3e86" +dependencies = [ + "serial-core", + "serial-unix", + "serial-windows", +] + +[[package]] +name = "serial-core" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f46209b345401737ae2125fe5b19a77acce90cd53e1658cda928e4fe9a64581" +dependencies = [ + "libc", +] + +[[package]] +name = "serial-unix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f03fbca4c9d866e24a459cbca71283f545a37f8e3e002ad8c70593871453cab7" +dependencies = [ + "ioctl-rs", + "libc", + "serial-core", + "termios", +] + +[[package]] +name = "serial-windows" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15c6d3b776267a75d31bbdfd5d36c0ca051251caafc285827052bc53bcdc8162" +dependencies = [ + "libc", + "serial-core", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -1350,6 +1488,22 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "1.3.0" @@ -1492,6 +1646,15 @@ dependencies = [ "syn", ] +[[package]] +name = "termios" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5d9cf598a6d7ce700a4e6a9199da127e6819a61e64b68609683cc9a01b5683a" +dependencies = [ + "libc", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -1696,7 +1859,7 @@ version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ - "bitflags", + "bitflags 2.11.1", "bytes", "futures-util", "http", @@ -2173,6 +2336,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 1e1fce6..0872f60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,8 @@ clap = { version = "4.5", features = ["derive"] } crossterm = { version = "0.28", features = ["event-stream"] } dirs = "5.0" futures = "0.3" +libc = "0.2" +portable-pty = "0.8" ratatui = "0.29" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } serde = { version = "1.0", features = ["derive"] } diff --git a/README.md b/README.md index e69de29..048b85e 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,309 @@ +# Forge + +Forge is a terminal-native DevOps command center built in Rust. + +It combines a command execution surface, an operational dashboard, structured runtime state, AI-assisted diagnosis, and safety-gated actions into one terminal application. Forge is intended for engineers who want a single local control surface for running commands, watching services, reading logs, inspecting Git and test state, and asking context-aware AI questions without giving up operator control. + +Forge is designed as a serious developer tool: terminal-native first, strongly typed, observable, safe by default, and packaged as a single native binary. + +--- + +## What Forge Is For + +Forge is intended to be launched inside a project directory and used as a daily operational workspace. + +The product goal is to let a user: + +- run shell commands +- stream stdout and stderr +- track foreground commands and background jobs +- inspect service and process health +- watch logs and important events +- inspect repository state +- understand test failures +- ask AI-grounded operational questions +- review and approve proposed actions before execution +- keep a visible record of commands, approvals, and outcomes + +Forge should feel like an operator cockpit for local development and DevOps workflows, not a generic chatbot or a thin command wrapper. + +--- + +## Current Status + +Forge currently has a working foundation: + +- Ratatui terminal UI with status bar, command pane, dashboard, event stream, and modals +- async runtime loop built on Tokio and Crossterm events +- managed shell command execution +- streaming command output into structured logs +- command, job, process, service, Git, log, test, timeline, approval, and AI domain models +- slash command parser and command suggestions +- safety classification and approval routing +- AI provider abstraction with mock, OpenAI, disabled, and unconfigured providers +- TOML configuration loading from defaults, global config, project config, environment, and CLI flags +- structured tracing to `.forge/logs/forge.log` +- foundation tests for parsing, state transitions, safety routing, AI proposal handling, and rendering + +Forge is not yet complete end to end. The remaining work is tracked in `docs/IMPLEMENTATION_PLAN.md`. + +Major remaining areas include: + +- persistent PTY shell sessions and interactive shell polish +- approval audit history and session restore hardening +- real service discovery, port inspection, and health checks +- process CPU/memory monitoring +- file and service log ingestion +- test result adapters +- expanded Git context and diff summaries +- richer AI workflows and patch proposals behind approvals +- scrollback, inspectors, and complete keyboard workflows +- release packaging and install documentation + +--- + +## Technology + +Forge uses the following core stack: + +- Language: Rust +- UI: Ratatui +- Terminal events: Crossterm +- Async runtime: Tokio +- Serialization: Serde +- Configuration: TOML +- Logging/telemetry: tracing +- Packaging target: single native binary + +--- + +## Running Forge + +From the repository root: + +```sh +cargo run +``` + +Show CLI options: + +```sh +cargo run -- --help +``` + +Run Forge in a specific working directory: + +```sh +cargo run -- --cwd /path/to/project +``` + +Run with debug logging: + +```sh +cargo run -- --debug +``` + +Forge writes internal logs to: + +```text +.forge/logs/forge.log +``` + +--- + +## Basic Usage + +Launch Forge inside a project: + +```sh +cargo run -- --cwd /path/to/project +``` + +Inside Forge, type commands into the command pane. + +Examples: + +```text +pwd +git status +cargo test +/bg cargo run +/ai summarize the latest failure +/diagnose why tests are failing +/apply 1 +/clear +/quit +``` + +Plain `clear` is treated as a Forge built-in clear action. It should not spawn the OS `clear` command or create a successful command record. + +--- + +## Slash Commands + +Currently supported slash commands include: + +```text +/help +/ai +/diagnose +/apply +/bg +/cancel +/approve +/deny +/tab next +/tab prev +/clear +/quit +/exit +/next-tab +/prev-tab +/run-proposal +``` + +Plain shell commands are also supported. A trailing `&` marks a command as background work. + +--- + +## Safety Model + +Forge classifies actions before execution. + +Current safety classes: + +- Passive: read-only inspection +- Safe: low-risk command execution +- Caution: visible inline review before execution when configured +- Risky: modal approval required +- Destructive: explicit confirmation required by default + +AI-proposed commands are not trusted blindly. When a user applies an AI proposal, Forge reclassifies the command locally at runtime and routes it through the same approval pipeline as user-entered commands. + +--- + +## AI Configuration + +AI is enabled by default in configuration, but no provider is selected by default. + +Use the mock provider for local testing: + +```sh +cargo run -- --ai-provider mock +``` + +Use OpenAI: + +```sh +OPENAI_API_KEY=... cargo run -- --ai-provider openai +``` + +Optionally choose a model: + +```sh +OPENAI_API_KEY=... cargo run -- --ai-provider openai --ai-model gpt-5-mini +``` + +AI requests are grounded in Forge's current state: project context, Git snapshot, recent commands, services, tests, logs, and timeline entries. + +--- + +## Configuration + +Forge loads configuration from: + +1. built-in defaults +2. global config at the platform config directory under `forge/config.toml` +3. project config at `.forge/config.toml` +4. environment variables +5. CLI flags + +Example project config: + +```toml +[ui] +tick_rate_ms = 120 +main_split_pct = 40 +event_stream_height = 8 + +[commands] +history_limit = 200 +scrollback_limit = 2000 + +[safety] +caution_requires_review = true +destructive_requires_confirmation = true + +[ai] +enabled = true +provider = "mock" +model = "gpt-5-mini" +request_timeout_secs = 30 + +[observability] +log_level = "info" +log_to_file = true +``` + +Environment overrides include: + +```text +FORGE_TICK_RATE_MS +FORGE_LOG_LEVEL +FORGE_SHELL +FORGE_AI_ENABLED +FORGE_AI_PROVIDER +FORGE_AI_MODEL +FORGE_AI_TIMEOUT_SECS +FORGE_EVENT_STREAM_HEIGHT +FORGE_MAIN_SPLIT_PCT +``` + +--- + +## Development + +Run the full local verification set: + +```sh +cargo fmt --check +cargo test +cargo clippy --all-targets --all-features -- -D warnings +``` + +Useful focused checks: + +```sh +cargo test parses_plain_clear_as_forge_builtin +cargo test foundation +cargo run -- --help +``` + +--- + +## Repository Documents + +Important project documents: + +- `AGENTS.md`: repository instructions and engineering principles for coding agents +- `PROJECT_BRIEF.md`: product goals, intended users, use cases, and requirements +- `ARCHITECTURE.md`: system architecture and subsystem boundaries +- `docs/IMPLEMENTATION_PLAN.md`: remaining implementation work required for end-to-end completion +- `docs/README.md`: documentation layout + +--- + +## Project Direction + +Forge should remain: + +- terminal-native +- production-grade +- modular +- strongly typed +- observable +- safe by default +- extensible without large rewrites +- packaged as a single installable binary + +The core standard for every change is whether it moves Forge closer to being a polished, trustworthy, production-grade terminal-native DevOps system. diff --git a/docs/IMPLEMENTATION_PLAN.md b/docs/IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..cd1e1be --- /dev/null +++ b/docs/IMPLEMENTATION_PLAN.md @@ -0,0 +1,1220 @@ +# Forge End-to-End Implementation Plan + +## Document Purpose + +This document defines the remaining implementation work required to complete Forge as a production-grade, terminal-native DevOps command center. + +It is intended for coding agents and contributors who need enough context to implement meaningful slices without rediscovering the product direction. It should be read alongside: + +- `AGENTS.md` +- `PROJECT_BRIEF.md` +- `ARCHITECTURE.md` +- `README.md` + +The plan is organized as implementation tracks. Each track includes the product outcome, expected module ownership, concrete implementation tasks, acceptance criteria, and validation commands. Agents should complete work in coherent slices that compile and preserve the architectural boundaries described in `ARCHITECTURE.md`. + +--- + +## 1. Current Implementation Baseline + +Forge already has a meaningful foundation: + +- Rust crate with Ratatui, Crossterm, Tokio, Serde, tracing, TOML configuration, and Clap. +- Modular source layout across `app`, `domain`, `runtime`, `infra`, `ui`, `ai`, `safety`, `config`, `observability`, and `shared`. +- Typed application state in `domain`. +- Central application store and effect dispatch in `app`. +- Async runtime loop that handles terminal input, ticks, supervisor events, rendering, and shutdown. +- Managed shell command execution through the configured shell. +- Line-oriented stdout/stderr streaming into typed log events. +- Command/job/process state transitions for managed commands. +- Background command parsing through `/bg ` and trailing `&`. +- Basic service records for background managed commands. +- Slash command parsing and command suggestions. +- Safety classifier and approval routing for caution, risky, and destructive commands. +- AI provider abstraction with `mock`, `openai`, disabled, and unconfigured providers. +- AI context bundling from project, git, command, service, test, log, and timeline state. +- OpenAI Responses API request construction and structured JSON response parsing. +- Ratatui UI with status bar, command/AI pane, dashboard tabs, modals, and event stream. +- Config loading from defaults, global config, project config, environment variables, and CLI overrides. +- Structured file logging and panic hook terminal restoration. +- Foundation test coverage for parsing, store transitions, safety routing, AI proposal reclassification, and UI rendering. + +This baseline should be preserved and extended. Do not collapse the architecture into a single file or bypass the state/effect/runtime model. + +--- + +## 2. Completion Definition + +Forge should be considered end-to-end complete when a user can launch it inside a real project and use it continuously to: + +- run interactive and non-interactive shell commands +- maintain shell/session awareness +- run foreground and background jobs +- stream and inspect command output and logs +- discover and monitor local services +- inspect process, port, and resource state +- track Git state, diffs, and repository changes +- track test runs and failures +- ask AI-grounded questions using current runtime and repository context +- review and approve proposed operational actions +- persist command history, approvals, and relevant session state +- diagnose failures with observable evidence +- exit cleanly without corrupting terminal state + +Forge should be considered production-ready only when the implementation has: + +- reliable PTY-backed shell execution +- bounded async queues and supervised background tasks +- robust cancellation and process cleanup +- durable state where users expect continuity +- tested safety and approval boundaries +- tested AI provider failure handling +- tested terminal rendering and resizing behavior +- release packaging for supported platforms +- clear user documentation and troubleshooting guidance + +--- + +## 3. Implementation Rules for Agents + +### 3.1 Work in vertical slices + +Each implementation slice should connect domain types, app store transitions, runtime effects, infrastructure behavior, UI visibility, and tests where applicable. Avoid adding unused domain structures without a real integration path. + +### 3.2 Keep module boundaries intact + +- Domain models belong in `src/domain`. +- State transitions and effects belong in `src/app`. +- Async task supervision belongs in `src/runtime`. +- External system access belongs in `src/infra`. +- Provider-specific AI code belongs in `src/ai/providers`. +- Rendering belongs in `src/ui`. +- Configuration schema and loading belong in `src/config`. +- Safety rules and approval policy belong in `src/safety`. + +### 3.3 Preserve safety by default + +Any command, workflow step, AI proposal, or service action that can modify files, kill processes, restart services, install dependencies, change Git state, or delete data must pass through the safety classifier and approval pipeline. + +### 3.4 Validate every slice + +At minimum, run: + +```sh +cargo fmt --check +cargo test +cargo clippy --all-targets --all-features -- -D warnings +``` + +For terminal, PTY, rendering, and AI work, add focused tests or documented manual smoke checks as described in the relevant track. + +--- + +## 4. Track A: Shell and Command Execution + +## Outcome + +Forge should behave like a trustworthy terminal-native command surface. Users should be able to run normal shell commands, interactive commands, foreground tasks, background jobs, and command replays without losing context or corrupting terminal state. + +## Current state + +Managed non-interactive shell execution exists. Commands are spawned through the configured shell, stdout/stderr are streamed line-by-line, and lifecycle events update command, job, process, log, and timeline state. + +Forge-managed shell session state exists for cwd, last exit status, and command history persistence and replay. PTY-backed interactive foreground command execution is implemented for Unix-like systems. Persistent PTY shell sessions across multiple commands are not implemented yet. + +## Primary modules + +- `src/domain/command.rs` +- `src/domain/job.rs` +- `src/app/store.rs` +- `src/app/effects.rs` +- `src/runtime/engine.rs` +- `src/runtime/supervisor.rs` +- `src/infra/shell` +- `src/ui/views/command_pane.rs` +- `src/config/schema.rs` +- `tests/` + +## Implementation tasks + +### A1. Add a PTY execution backend + +Implement a Rust-native PTY backend for interactive commands. + +Requirements: + +- Add a PTY-capable executor behind a shell execution abstraction. +- Support Unix-like systems first with a clean path for Windows support. +- Preserve terminal raw mode and alternate screen behavior. +- Stream PTY output into the existing event pipeline. +- Support resize propagation from Forge terminal resize events into active PTY sessions. +- Ensure PTY child processes are cleaned up on cancellation and Forge shutdown. + +Expected shape: + +- Introduce a shell executor trait or enum-backed backend in `src/infra/shell`. +- Keep `ExecutionMode::Managed` for piped non-interactive commands. +- Implement `ExecutionMode::Pty` for interactive commands and persistent shell sessions. +- Add typed errors for PTY setup, read/write, resize, and shutdown failures. + +Acceptance criteria: + +- Interactive commands such as `less`, `top`, and shell prompts can run without corrupting Forge. +- Terminal resize events are reflected in PTY-backed commands. +- Cancelling a PTY command terminates the full process group where supported. +- Forge restores the terminal after PTY failures and panics. + +Validation: + +```sh +cargo test shell +cargo test +cargo clippy --all-targets --all-features -- -D warnings +``` + +Manual smoke checks: + +- Run `pwd`. +- Run `clear` and confirm it triggers Forge's built-in clear behavior, not an OS command record. +- Run an interactive command through the PTY path. +- Cancel a long-running PTY command. +- Resize the terminal while output is streaming. + +### A2. Implement persistent shell/session state + +Users should not lose shell context between commands. + +Requirements: + +- Track session cwd, shell, environment overlays, and last exit status. +- Support `cd` as a state-changing shell built-in for the Forge session. +- Reflect current cwd in status or command pane metadata. +- Run commands from the session cwd unless explicitly overridden. +- Keep command provenance visible. + +Acceptance criteria: + +- `cd some/path` changes the Forge session cwd. +- A later `pwd` reflects the updated cwd. +- Failed `cd` surfaces a user-visible diagnostic and does not change state. +- AI context includes current cwd and recent command status. + +### A3. Improve command history and replay + +Requirements: + +- Persist command history across Forge launches. +- Support rerun of recent commands through slash command and UI affordance. +- Preserve command metadata: cwd, shell, provenance, background flag, safety class, timestamps, exit status. +- Avoid re-running risky/destructive commands without approval. + +Suggested commands: + +- `/history` +- `/rerun ` +- `/rerun-last` + +Acceptance criteria: + +- History survives restart. +- Replayed commands go through safety classification again. +- UI shows replay provenance distinctly from original user input. + +### A4. Harden cancellation and process cleanup + +Requirements: + +- Track child process ids and process groups. +- Cancel foreground and background commands reliably. +- Escalate from graceful termination to force kill after a timeout. +- Mark commands, jobs, services, and processes consistently after cancellation. +- Clean up cancellation registry entries on all exit paths. + +Acceptance criteria: + +- Cancelling `sleep 30` marks the command cancelled and removes it from active state. +- Cancelling a background service marks service health as stopped. +- Forge shutdown cancels or detaches processes according to explicit policy. + +--- + +## 5. Track B: Runtime, Events, and Supervision + +## Outcome + +Forge should have a predictable async runtime that can supervise long-running background work without blocking the UI or leaking tasks. + +## Current state + +The runtime loop uses a bounded channel for app events and dispatches effects to a supervisor. Git and project scans run in background tasks. Commands and AI requests are spawned asynchronously. + +## Primary modules + +- `src/app/effects.rs` +- `src/app/store.rs` +- `src/runtime/engine.rs` +- `src/runtime/supervisor.rs` +- `src/domain/timeline.rs` +- `src/domain/diagnostics.rs` + +## Implementation tasks + +### B1. Introduce a typed task registry + +Requirements: + +- Track supervised tasks by id, kind, status, start time, and cancellation handle. +- Distinguish command tasks, AI requests, project scans, Git refreshes, service monitors, log tails, and health checks. +- Surface task failures into diagnostics and timeline state. +- Ensure repeated refreshes do not spawn unbounded overlapping work. + +Acceptance criteria: + +- The dashboard can show active background tasks. +- Refresh tasks are deduplicated or coalesced where appropriate. +- Task failures are visible and do not crash the UI loop. + +### B2. Add backpressure and event coalescing + +Requirements: + +- Prevent high-volume logs from starving UI input. +- Coalesce repetitive process/resource updates. +- Preserve important command lifecycle events. +- Drop or summarize low-value high-volume events only under explicit policy. + +Acceptance criteria: + +- A command producing thousands of lines does not freeze input. +- Log buffers stay bounded. +- Timeline remains readable under high output volume. + +### B3. Define shutdown semantics + +Requirements: + +- Implement graceful shutdown sequence for UI, command tasks, AI tasks, log tails, monitors, and observability guard. +- Decide and document whether background commands are cancelled or detached by default. +- Provide config for background shutdown policy. + +Acceptance criteria: + +- Ctrl-C and `/quit` perform the same clean shutdown path. +- Terminal state is restored after normal shutdown and task failures. +- Long-running tasks do not keep Forge hanging indefinitely. + +--- + +## 6. Track C: Safety, Approvals, and Auditability + +## Outcome + +Forge should make user-impacting actions reviewable, auditable, and safe by default. + +## Current state + +Command classification exists. Caution commands route to inline review. Risky and destructive commands route to modal confirmation. AI proposals are reclassified at runtime instead of trusting model-provided safety hints. + +## Primary modules + +- `src/safety` +- `src/domain/approval.rs` +- `src/domain/command.rs` +- `src/app/store.rs` +- `src/ui/views/modal.rs` +- `src/ui/views/command_pane.rs` +- `src/config/schema.rs` + +## Implementation tasks + +### C1. Replace pattern-only classification with structured command analysis + +Requirements: + +- Parse command strings into structured command features where practical. +- Identify shell operators, redirects, pipes, subshells, globs, variable expansion, destructive verbs, filesystem targets, package managers, Git state changes, service/process operations, and network operations. +- Return classification plus reasons. +- Keep conservative defaults for commands that cannot be understood. + +Acceptance criteria: + +- `rm -rf`, `git reset --hard`, `git clean`, redirection, dependency installs, `kill`, service restarts, and Docker prune are classified with explicit reasons. +- AI proposal approval detail shows runtime classification reasons. +- Unit tests cover common safe, caution, risky, and destructive cases. + +### C2. Add approval policy configuration + +Requirements: + +- Add config for class thresholds, remembered approvals, command allowlists, command blocklists, and per-workspace policy. +- Prevent config from disabling destructive confirmation unless explicitly allowed by a hard-coded development override. +- Include policy source in approval detail. + +Acceptance criteria: + +- Project config can require approval for all non-passive commands. +- Blocklisted commands cannot execute and surface a clear diagnostic. +- Destructive commands remain gated by default. + +### C3. Persist audit history + +Requirements: + +- Persist proposed action, classification, approval decision, timestamp, user note if provided, command id, provenance, and execution outcome. +- Include AI request id and model/provider for AI-proposed actions. +- Provide a UI and slash command path to inspect recent approvals. + +Suggested commands: + +- `/approvals` +- `/audit` + +Acceptance criteria: + +- Approval history survives restart. +- AI-suggested commands can be traced from prompt to proposal to approval to execution. + +--- + +## 7. Track D: Services, Processes, Ports, and Health + +## Outcome + +Forge should provide real operational visibility across local services and processes, not just command lifecycle records. + +## Current state + +Domain models exist for services and processes. Background managed commands create service records. There is no general process monitor, port inspector, health evaluator, or configured service registry yet. + +## Primary modules + +- `src/domain/service.rs` +- `src/domain/process.rs` +- `src/infra/monitor` +- `src/runtime/supervisor.rs` +- `src/app/effects.rs` +- `src/app/store.rs` +- `src/ui/views/dashboard.rs` +- `src/config/schema.rs` + +## Implementation tasks + +### D1. Implement process snapshots + +Requirements: + +- Collect local process snapshots at bounded intervals. +- Include pid, parent pid where available, command/name, status, CPU, memory, observed timestamp. +- Associate managed command processes with Forge command/job ids. +- Avoid platform-specific assumptions leaking into domain models. + +Acceptance criteria: + +- Processes dashboard shows real CPU and memory for tracked commands. +- Process monitor failures produce diagnostics, not panics. +- Polling interval is configurable and bounded. + +### D2. Implement port discovery + +Requirements: + +- Detect listening ports and owning pids where available. +- Associate ports with managed services and configured services. +- Support partial data when OS permissions restrict inspection. + +Acceptance criteria: + +- A background web server shows its listening port in the service dashboard. +- Missing permission or unsupported platform is surfaced as degraded observability, not failure. + +### D3. Add configured services + +Requirements: + +- Extend TOML config with service definitions. +- Support service name, command, cwd, env, health check, log sources, tags, restart policy, and expected ports. +- Add start, stop, restart, and inspect actions through safety pipeline. + +Suggested config shape: + +```toml +[[services]] +name = "api" +command = "cargo run" +cwd = "." +tags = ["rust", "local"] +ports = [8080] + +[services.health] +kind = "http" +url = "http://localhost:8080/health" +timeout_ms = 1000 +``` + +Acceptance criteria: + +- Configured services appear before they are started. +- Starting a service creates command, job, process, service, log, and timeline records. +- Restart and stop actions require appropriate safety review. + +### D4. Implement health checks + +Requirements: + +- Support basic TCP, HTTP, process-alive, and command health checks. +- Record health reasons and last check timestamp. +- Distinguish unknown, starting, healthy, degraded, unhealthy, and stopped. +- Avoid aggressive polling. + +Acceptance criteria: + +- Service cards show health status with reason. +- Health checks continue while UI remains responsive. +- Health failures can be included in AI diagnosis context. + +--- + +## 8. Track E: Log Ingestion, Filtering, and Search + +## Outcome + +Forge should treat logs as structured operational data that can be filtered, searched, associated with services/jobs, and passed to AI workflows. + +## Current state + +Command stdout/stderr is normalized into log entries with inferred severity. Logs are stored in bounded global and per-source buffers. There is no file tailing, container log ingestion, search UI, or structured parser pipeline yet. + +## Primary modules + +- `src/domain/log.rs` +- `src/infra/logs` +- `src/runtime/supervisor.rs` +- `src/app/store.rs` +- `src/ui/views/dashboard.rs` +- `src/ai/context.rs` +- `src/config/schema.rs` + +## Implementation tasks + +### E1. Add log source configuration + +Requirements: + +- Support file log sources in project config. +- Associate file logs with services where configured. +- Tail files from the end by default with configurable initial read size. +- Handle rotation and truncation. + +Acceptance criteria: + +- Configured log files stream into the Logs dashboard. +- Log tail tasks are supervised and cancellable. +- Missing files produce diagnostics and can retry if configured. + +### E2. Implement log filtering and search + +Requirements: + +- Add UI state for text filters, severity filters, source filters, and service filters. +- Add slash commands and keyboard flow for search. +- Preserve bounded memory behavior. + +Suggested commands: + +- `/logs` +- `/logs service ` +- `/logs grep ` +- `/logs level ` + +Acceptance criteria: + +- Logs dashboard reflects active filters. +- Clearing filters is discoverable. +- AI context receives filtered and recent high-signal logs. + +### E3. Add structured log parsing + +Requirements: + +- Detect JSON log lines and extract fields. +- Preserve raw text. +- Infer severity from common keys such as `level`, `severity`, `msg`, `message`, and `error`. +- Support future parser plugins by keeping parser logic isolated. + +Acceptance criteria: + +- JSON logs display with severity and message correctly. +- Unknown formats remain visible as raw logs. + +--- + +## 9. Track F: Git, Project Context, and Test Awareness + +## Outcome + +Forge should understand the repository and test state well enough to support diagnosis, safe action suggestions, and operational awareness. + +## Current state + +Project scan detects root, some common files, stack hints, and config paths. Git snapshot reads branch, short head, dirty flag, and changed file names. Test domain models exist but no adapters populate test state. + +## Primary modules + +- `src/domain/project.rs` +- `src/domain/git.rs` +- `src/domain/test.rs` +- `src/infra/project` +- `src/infra/git` +- `src/app/store.rs` +- `src/ai/context.rs` +- `src/ui/views/dashboard.rs` + +## Implementation tasks + +### F1. Expand Git context + +Requirements: + +- Track staged, unstaged, untracked, conflicted, and ignored states separately. +- Track ahead/behind upstream counts where available. +- Track recent commits with hash, author, date, and subject. +- Provide bounded diff stats and optional detailed diff excerpts for AI context. +- Avoid expensive Git commands on every tick. + +Acceptance criteria: + +- Git dashboard shows branch, head, upstream relation, changed files grouped by state, and recent commits. +- AI context can cite changed files and diff stats. +- Git refresh remains bounded and does not block the UI. + +### F2. Improve project scanning + +Requirements: + +- Detect Rust, Node, Python, Docker Compose, Make, Just, and common CI files. +- Discover likely commands from `Cargo.toml`, `package.json`, `Makefile`, `justfile`, and project config. +- Detect candidate services from Docker Compose and config files. +- Keep scanning bounded and cache expensive results. + +Acceptance criteria: + +- Project dashboard or AI context includes stack hints and likely commands. +- Discovered service hints can be promoted into service records only through clear policy. + +### F3. Implement test adapters + +Requirements: + +- Start with Rust `cargo test`. +- Detect when a command is a test run. +- Parse pass/fail summary and failed test names where practical. +- Track duration and source command id. +- Keep parser code outside UI rendering. + +Acceptance criteria: + +- Running `cargo test` updates `TestState`. +- Failed tests appear in dashboard and AI context. +- Test parsing failures do not mark the command itself failed unless the process failed. + +### F4. Add test workflow commands + +Suggested commands: + +- `/test` +- `/test last` +- `/test failed` +- `/diagnose tests` + +Acceptance criteria: + +- Test slash commands create command/job records and go through safety policy. +- AI diagnosis can reference recent test failures. + +--- + +## 10. Track G: AI Workflows and Provider Reliability + +## Outcome + +Forge's AI features should be grounded, inspectable, provider-aware, and safe. AI should assist the operator without becoming unrestricted automation. + +## Current state + +AI request state, context bundling, mock provider, OpenAI provider, structured response parsing, and AI proposal application exist. Runtime reclassifies proposal commands before execution. + +## Primary modules + +- `src/domain/ai.rs` +- `src/ai/context.rs` +- `src/ai/provider.rs` +- `src/ai/providers` +- `src/app/store.rs` +- `src/commands/mod.rs` +- `src/ui/views/command_pane.rs` +- `src/config/schema.rs` + +## Implementation tasks + +### G1. Harden provider configuration and diagnostics + +Requirements: + +- Validate provider configuration at startup. +- Clearly show provider status: disabled, unconfigured, ready, missing API key, failed. +- Add provider timeout, retry, and cancellation behavior. +- Avoid exposing secrets in logs, diagnostics, or UI. + +Acceptance criteria: + +- Missing API key produces an actionable UI diagnostic. +- Provider HTTP errors show status and truncated safe body. +- AI request cancellation is possible. + +### G2. Improve context budgeting + +Requirements: + +- Add context budgets for commands, logs, diffs, tests, services, and timeline. +- Prioritize failed commands, error logs, unhealthy services, failed tests, and dirty Git files. +- Include citations that map back to local state. + +Acceptance criteria: + +- AI context remains bounded under long sessions. +- Diagnosis requests prioritize failures over generic recent events. + +### G3. Add structured workflow proposals + +Requirements: + +- Extend AI proposals beyond single commands to typed plans. +- Each plan step must have a safety class, rationale, command/action payload, and dependencies. +- Require approval at step or plan level depending on risk. +- Preserve full audit trail. + +Suggested domain model: + +- `AiPlan` +- `AiPlanStep` +- `WorkflowRun` +- `WorkflowStepStatus` + +Acceptance criteria: + +- AI can propose a multi-step diagnosis plan without executing it automatically. +- Applying a plan schedules steps through the safety pipeline. +- Failed steps stop the plan unless policy says otherwise. + +### G4. Support patch proposals safely + +Requirements: + +- AI may suggest file patches as proposed artifacts, not direct writes. +- Patches must be reviewable before application. +- Applying a patch is risky and requires approval. +- Patch application must preserve user changes and surface conflicts. + +Acceptance criteria: + +- AI patch proposals are visible and can be approved or denied. +- Patch application uses a safe, reviewable pathway. +- Tests can be rerun after approved patch application. + +--- + +## 11. Track H: Terminal UI and Interaction Completeness + +## Outcome + +Forge should feel polished and efficient for daily terminal use. UI should remain stable under resizing, streaming output, approvals, background jobs, and long sessions. + +## Current state + +The UI renders a top status bar, command/AI pane, dashboard pane, bottom event stream, help modal, error modal, and approval modal. Dashboard tabs include Services, Processes, Logs, Git, and Tests. + +## Primary modules + +- `src/ui` +- `src/ui/views` +- `src/domain/app.rs` +- `src/app/store.rs` +- `tests/foundation.rs` + +## Implementation tasks + +### H1. Add scrollback and selection + +Requirements: + +- Support scrolling command output, logs, event stream, and dashboard lists. +- Track scroll state per pane. +- Keep input editing ergonomic while other panes are focused. +- Add keyboard hints in help modal. + +Acceptance criteria: + +- Users can inspect old output without losing new output. +- Scroll state behaves predictably when new events arrive. + +### H2. Add detail inspectors + +Requirements: + +- Inspect command details, job details, service details, log entry details, Git file details, test failures, and approval audit records. +- Keep inspector rendering separate from state transition logic. + +Acceptance criteria: + +- Selecting an item opens a focused detail view. +- Detail views include ids needed for slash command references. + +### H3. Improve command palette and slash command UX + +Requirements: + +- Add command categories. +- Show command usage and risk where relevant. +- Complete ids from recent commands/services/tests where possible. +- Ensure built-ins such as `clear` do not accidentally run as shell commands when Forge owns the behavior. + +Acceptance criteria: + +- Slash commands are discoverable. +- Built-ins and shell commands have unambiguous behavior. + +### H4. Add render regression tests + +Requirements: + +- Use Ratatui `TestBackend` for stable layout tests. +- Cover narrow, normal, and wide terminal sizes. +- Cover empty state, active command state, approval modal, failed command, background service, logs, and AI response. + +Acceptance criteria: + +- UI tests catch text overlap, missing modal content, and broken status/dashboard rendering. + +--- + +## 12. Track I: Configuration, Persistence, and Local State + +## Outcome + +Forge should support durable user preferences, workspace configuration, command history, approval audit history, and session continuity without requiring external services. + +## Current state + +Config defaults, partial config merging, global/project config discovery, environment overrides, and CLI overrides exist. Runtime state is mostly in memory. + +## Primary modules + +- `src/config` +- `src/domain` +- `src/app/store.rs` +- `src/infra` +- `src/observability` + +## Implementation tasks + +### I1. Define local state layout + +Requirements: + +- Store user-level state under platform config/data directories. +- Store workspace-level Forge state under `.forge/`. +- Separate logs, history, audit, cache, and session files. +- Avoid writing secrets. + +Suggested layout: + +```text +.forge/ + config.toml + logs/ + forge.log + state/ + session.toml + command-history.jsonl + approvals.jsonl + ai-history.jsonl + cache/ + project-scan.json + git-snapshot.json +``` + +Acceptance criteria: + +- State directories are created only when needed. +- Files are written atomically where corruption matters. + +### I2. Persist history and audit logs + +Requirements: + +- Persist command history. +- Persist approval decisions. +- Persist AI request/response summaries without secrets. +- Provide retention limits and compaction policy. + +Acceptance criteria: + +- Restarting Forge restores recent command history. +- Audit logs can be inspected and exported. + +### I3. Version configuration schema + +Requirements: + +- Add schema version to config. +- Validate unknown or unsupported fields where helpful. +- Provide clear errors for malformed config. +- Document config examples. + +Acceptance criteria: + +- Invalid config gives file path and field context where possible. +- Config docs match actual schema. + +--- + +## 13. Track J: Observability, Diagnostics, and Troubleshooting + +## Outcome + +Forge should be easy to debug when it fails and should surface actionable errors to users. + +## Current state + +Tracing to `.forge/logs/forge.log` exists. Diagnostics state exists. Panic hook restores terminal state. + +## Primary modules + +- `src/observability` +- `src/domain/diagnostics.rs` +- `src/app/store.rs` +- `src/ui/views/dashboard.rs` +- `src/shared/error.rs` + +## Implementation tasks + +### J1. Add diagnostics export + +Requirements: + +- Export config summary, runtime state summary, recent diagnostics, recent timeline, active tasks, recent command failures, provider status, and log path. +- Exclude secrets and large raw logs by default. + +Suggested command: + +- `/diagnostics export` + +Acceptance criteria: + +- Export file can be attached to bug reports. +- Export does not include API keys or environment secrets. + +### J2. Improve error taxonomy + +Requirements: + +- Add structured error kinds for shell, PTY, config, Git, AI, monitoring, logs, persistence, and rendering. +- Surface recovery suggestions where possible. + +Acceptance criteria: + +- Common failures produce actionable messages. +- UI and logs include enough context to debug. + +### J3. Add health reporting for Forge itself + +Requirements: + +- Track internal queue depth, active task count, dropped/coalesced event count, last render time, and diagnostic count. +- Show internal health in debug mode. + +Acceptance criteria: + +- Debug mode can reveal runtime pressure without external tools. + +--- + +## 14. Track K: Packaging, Distribution, and Release Readiness + +## Outcome + +Forge should build and ship as a single cross-platform binary with documented installation and upgrade paths. + +## Current state + +The crate builds as a Rust binary. Release packaging is not yet implemented. + +## Primary modules and files + +- `Cargo.toml` +- `Cargo.lock` +- `.github/` +- `README.md` +- release scripts or workflows + +## Implementation tasks + +### K1. Define supported platforms + +Requirements: + +- Decide initial target triples. +- Document terminal compatibility expectations. +- Document unsupported or degraded features per platform. + +Suggested initial platforms: + +- macOS arm64 +- macOS x86_64 +- Linux x86_64 +- Linux arm64 + +Windows support should remain architecturally planned but may require separate PTY and process inspection work. + +### K2. Add release builds + +Requirements: + +- Add CI workflow for check, test, clippy, fmt, and release artifacts. +- Build optimized binaries. +- Generate checksums. +- Attach release artifacts. + +Acceptance criteria: + +- A tagged release produces downloadable binaries and checksums. + +### K3. Document installation + +Requirements: + +- Document `cargo install --path .` for local development. +- Document binary install once release artifacts exist. +- Document config locations and first-run behavior. + +Acceptance criteria: + +- A new user can install, launch, configure AI, and run basic workflows from README instructions. + +--- + +## 15. Track L: End-to-End Testing Strategy + +## Outcome + +Forge should have automated confidence across domain logic, runtime behavior, terminal rendering, shell execution, safety, AI providers, and integration flows. + +## Current state + +Unit and foundation integration tests exist. There are no PTY integration tests, process monitor tests, persistence tests, or full terminal-flow tests yet. + +## Test categories + +### L1. Domain and parser tests + +Cover: + +- slash commands +- shell built-ins +- safety classifier +- approval policy +- command/session state +- service health transitions +- Git/test/log parsers + +### L2. Store transition tests + +Cover: + +- command lifecycle events +- background service lifecycle +- approval accept/deny +- AI request success/failure +- AI proposal application +- cancellation +- persistence restore + +### L3. Runtime and infrastructure tests + +Cover: + +- managed command execution +- PTY execution where available +- cancellation +- project scan +- Git snapshot +- log tailing +- process/port monitor behavior + +### L4. UI render tests + +Cover: + +- empty state +- active command +- logs dashboard +- services dashboard +- approval modal +- AI response +- error modal +- narrow terminal +- resize behavior + +### L5. End-to-end smoke scenarios + +Automate or document: + +1. Launch Forge in a Rust repo. +2. Run `pwd`. +3. Run `clear` and confirm no shell command record is created. +4. Run `cargo test` and approve caution review. +5. Start a background service with `/bg `. +6. Observe process, service, logs, and port. +7. Ask `/diagnose ` with mock provider. +8. Apply an AI proposal and verify safety routing. +9. Cancel a running command. +10. Quit and restart, verifying persisted history and audit records. + +--- + +## 16. Suggested Implementation Order + +### Phase 1: Command Surface Reliability + +1. Harden shell built-ins such as `clear`, `cd`, `exit`, and history behavior. +2. Add persistent session cwd and command history. +3. Add managed command integration tests. +4. Improve cancellation and process cleanup. + +Why first: + +The command surface is the center of Forge. Every other subsystem depends on reliable command lifecycle state. + +### Phase 2: PTY and Interactive Shell + +1. Add PTY backend. +2. Add resize propagation. +3. Add PTY cancellation and cleanup. +4. Add manual and automated smoke coverage. + +Why second: + +Without PTY support Forge cannot meet the terminal-native product bar. + +### Phase 3: Services, Processes, and Logs + +1. Implement process snapshots. +2. Implement port discovery. +3. Add configured services. +4. Add health checks. +5. Add file log tailing. + +Why third: + +Operational visibility depends on real producers feeding service, process, and log state. + +### Phase 4: Git, Tests, and Diagnosis Context + +1. Expand Git status and diff metadata. +2. Improve project scan. +3. Add Rust test adapter. +4. Feed failures into AI context. + +Why fourth: + +AI diagnosis should be grounded in reliable local facts before workflow automation expands. + +### Phase 5: AI Workflows and Audit + +1. Harden provider diagnostics. +2. Add context budgeting and prioritization. +3. Add structured plan proposals. +4. Add patch proposals behind approval. +5. Persist audit history. + +Why fifth: + +AI actions should build on mature safety, command, and context foundations. + +### Phase 6: Persistence, UI Completion, and Release + +1. Persist session, history, approvals, and AI summaries. +2. Add scrollback, inspectors, and full keyboard UX. +3. Add diagnostics export. +4. Add release workflows and installation docs. +5. Complete end-to-end smoke testing. + +Why sixth: + +These steps turn the integrated system into something users can rely on daily. + +--- + +## 17. Production Readiness Checklist + +Forge is not production-ready until all of the following are true: + +- `cargo fmt --check` passes. +- `cargo test` passes. +- `cargo clippy --all-targets --all-features -- -D warnings` passes. +- PTY command execution works for supported platforms. +- Managed and PTY command cancellation are reliable. +- Shell session cwd and history persist correctly. +- Risky and destructive actions require approval by default. +- Approval audit history persists. +- Background services can be started, stopped, restarted, and inspected. +- Process CPU/memory and port state are visible where supported. +- Logs can be ingested from commands and configured files. +- Git state includes staged, unstaged, untracked, and diff summary data. +- Rust test runs update `TestState`. +- AI provider status is explicit and failure modes are tested. +- AI proposals route through runtime safety classification. +- UI supports scrolling, resize, detail inspection, and modal flows. +- Terminal state restores after normal exit, Ctrl-C, command failure, and panic. +- Local state files avoid secrets and handle corruption gracefully. +- Diagnostics export is available. +- Release artifacts are produced for supported platforms. +- README documents installation, usage, config, AI setup, safety behavior, and troubleshooting. + +--- + +## 18. Agent Handoff Template + +When assigning a slice to an agent, use this shape: + +```text +Implement : . + +Context: +- Read AGENTS.md, ARCHITECTURE.md, PROJECT_BRIEF.md, README.md, and docs/IMPLEMENTATION_PLAN.md. +- Preserve module boundaries. +- Route risky/destructive actions through safety approvals. + +Scope: +- Owned files/modules: + - +- Do not edit: + - + +Requirements: +- +- +- + +Acceptance criteria: +- +- +- + +Validation: +- cargo fmt --check +- cargo test +- cargo clippy --all-targets --all-features -- -D warnings +``` + +Agents should update this implementation plan when completing major tracks so future work reflects the actual system state. diff --git a/docs/README.md b/docs/README.md index c10c44f..0a1720f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,3 +13,8 @@ turning the repository root into a dumping ground, for example: - subsystem design notes - runtime flow documentation - operator or contributor guides + +Current documents: + +- `IMPLEMENTATION_PLAN.md`: remaining end-to-end implementation work, organized into + agent-sized tracks with acceptance criteria and validation commands. diff --git a/src/ai/context.rs b/src/ai/context.rs index 1670295..11e8d0a 100644 --- a/src/ai/context.rs +++ b/src/ai/context.rs @@ -1,7 +1,7 @@ use crate::domain::{ AiCommandContext, AiContextBundle, AiGitContext, AiLogContext, AiProjectContext, - AiServiceContext, AiTestContext, AiTimelineContext, AiUiContext, AppState, FocusTarget, - LogSource, ModalState, + AiServiceContext, AiShellSessionContext, AiTestContext, AiTimelineContext, AiUiContext, + AppState, FocusTarget, LogSource, ModalState, }; pub fn build_context(state: &AppState) -> AiContextBundle { @@ -39,6 +39,12 @@ pub fn build_context(state: &AppState) -> AiContextBundle { .cloned() .collect(), }, + session: AiShellSessionContext { + cwd: state.commands.session.cwd.clone(), + shell: state.commands.session.shell.clone(), + env_overlay_count: state.commands.session.env.len(), + last_exit_status: state.commands.session.last_exit_status, + }, commands: state .commands .records @@ -48,6 +54,7 @@ pub fn build_context(state: &AppState) -> AiContextBundle { .map(|record| AiCommandContext { id: record.id, raw: record.raw.clone(), + cwd: record.cwd.clone(), provenance: record.provenance, status: record.status, exit_code: record.exit_code, @@ -128,6 +135,7 @@ fn modal_label(modal: &ModalState) -> String { match modal { ModalState::Approval(id) => format!("approval:{id}"), ModalState::Help => "help".to_string(), + ModalState::History => "history".to_string(), ModalState::Error(_) => "error".to_string(), } } diff --git a/src/ai/providers/openai.rs b/src/ai/providers/openai.rs index 5a0bb80..f70f3be 100644 --- a/src/ai/providers/openai.rs +++ b/src/ai/providers/openai.rs @@ -191,6 +191,9 @@ fn build_developer_prompt(request: &AiRequest) -> String { "Dashboard tab: {}\n", "Repo: {}\n", "Project root: {}\n", + "Session cwd: {}\n", + "Session shell: {}\n", + "Last exit status: {}\n", "Git branch: {}\n", "Git head: {}\n", "Git dirty: {}\n", @@ -206,6 +209,14 @@ fn build_developer_prompt(request: &AiRequest) -> String { request.context.ui.dashboard_tab, request.context.project.name, request.context.project.root.display(), + request.context.session.cwd.display(), + request.context.session.shell, + request + .context + .session + .last_exit_status + .map(|status| status.to_string()) + .unwrap_or_else(|| "none".to_string()), request .context .git @@ -233,7 +244,13 @@ fn build_developer_prompt(request: &AiRequest) -> String { .context .commands .iter() - .map(|command| format!("#{} {:?} {}", command.id, command.status, command.raw)) + .map(|command| format!( + "#{} {:?} cwd={} {}", + command.id, + command.status, + command.cwd.display(), + command.raw + )) .collect::>() ), render_list( diff --git a/src/app/bootstrap.rs b/src/app/bootstrap.rs index af1f31d..24efc8a 100644 --- a/src/app/bootstrap.rs +++ b/src/app/bootstrap.rs @@ -1,8 +1,10 @@ use crate::ai::AiRuntime; use crate::app::AppStore; use crate::config::{load_config, CliArgs}; -use crate::domain::{AppState, GitSnapshot, ProjectContext, TimelineKind}; -use crate::infra::{git, project}; +use crate::domain::{ + AppState, DiagnosticLevel, DiagnosticRecord, GitSnapshot, ProjectContext, TimelineKind, +}; +use crate::infra::{git, project, state as local_state}; use crate::observability::{init_observability, install_panic_hook}; use crate::runtime::Runtime; use crate::shared::error::AppResult; @@ -27,6 +29,44 @@ pub async fn bootstrap(cli: CliArgs) -> AppResult { }; let mut state = AppState::new(loaded.config.clone(), project, git); + match local_state::load_command_history( + &state.project.root, + state.config.commands.history_limit, + ) { + Ok(history) => { + state.commands.history = history; + } + Err(error) => { + state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level: DiagnosticLevel::Warn, + message: format!("failed to load command history: {error}"), + context: Some(state.project.root.display().to_string()), + }); + } + } + match local_state::load_shell_session(&state.project.root) { + Ok(Some(session)) if session.cwd.is_dir() => { + state.commands.session = session; + } + Ok(Some(session)) => { + state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level: DiagnosticLevel::Warn, + message: "saved shell session cwd is no longer available".to_string(), + context: Some(session.cwd.display().to_string()), + }); + } + Ok(None) => {} + Err(error) => { + state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level: DiagnosticLevel::Warn, + message: format!("failed to load shell session: {error}"), + context: Some(state.project.root.display().to_string()), + }); + } + } state.diagnostics.log_file = observability.log_file.clone(); state.timeline.entries.push(crate::domain::TimelineEntry { id: crate::shared::ids::TimelineId(0), diff --git a/src/app/store.rs b/src/app/store.rs index daf6ed8..e7f778e 100644 --- a/src/app/store.rs +++ b/src/app/store.rs @@ -1,15 +1,16 @@ -use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; use crate::ai; use crate::app::{AppAction, AppEvent, Effect, UiIntent}; use crate::commands::{parse_input, parse_shell_input, slash_command_suggestions, ParsedInput}; use crate::domain::{ AiActionProposal, AiMessage, AiMessageRole, AiRequest, AiRequestKind, AiStatus, AppState, - ApprovalDecision, ApprovalMode, ApprovalRequest, CommandRecord, CommandStatus, DashboardTab, - DiagnosticLevel, DiagnosticRecord, ExecutionMode, ExecutionRequest, FocusTarget, InputMode, - JobRecord, JobStatus, ModalState, Notification, NotificationLevel, ProcessSnapshot, + ApprovalDecision, ApprovalMode, ApprovalRequest, CommandHistoryEntry, CommandRecord, + CommandStatus, DashboardTab, DiagnosticLevel, DiagnosticRecord, ExecutionRequest, FocusTarget, + InputMode, JobRecord, JobStatus, ModalState, Notification, NotificationLevel, ProcessSnapshot, ProcessStatus, ServiceHealth, ServiceRecord, ServiceSource, TimelineEntry, TimelineKind, }; +use crate::infra::shell; use crate::safety::{approval_message, approval_mode_for, classify_command}; use crate::shared::ids::{ApprovalId, CommandId, IdGenerator}; use crate::shared::time::now_utc; @@ -21,9 +22,10 @@ pub struct AppStore { impl AppStore { pub fn new(state: AppState) -> Self { + let next_id = next_id_after_restored_state(&state); Self { state, - ids: IdGenerator::new(), + ids: IdGenerator::starting_at(next_id), } } @@ -139,13 +141,18 @@ impl AppStore { service_id, pid, } => { + let started_at = now_utc(); if let Some(command) = self.find_command_mut(command_id) { command.status = CommandStatus::Running; - command.started_at = Some(now_utc()); + command.started_at = Some(started_at); } + self.update_history_for_command(command_id, |entry| { + entry.status = CommandStatus::Running; + entry.started_at = Some(started_at); + }); if let Some(job) = self.find_job_mut(job_id) { job.status = JobStatus::Running; - job.started_at = Some(now_utc()); + job.started_at = Some(started_at); job.pid = pid; } let process = ProcessSnapshot { @@ -233,6 +240,7 @@ impl AppStore { exit_code, } => { let succeeded = exit_code == 0; + let ended_at = now_utc(); if let Some(command) = self.find_command_mut(command_id) { command.status = if succeeded { CommandStatus::Succeeded @@ -240,15 +248,25 @@ impl AppStore { CommandStatus::Failed }; command.exit_code = Some(exit_code); - command.ended_at = Some(now_utc()); + command.ended_at = Some(ended_at); } + self.update_history_for_command(command_id, |entry| { + entry.status = if succeeded { + CommandStatus::Succeeded + } else { + CommandStatus::Failed + }; + entry.exit_code = Some(exit_code); + entry.ended_at = Some(ended_at); + }); + self.state.commands.session.last_exit_status = Some(exit_code); if let Some(job) = self.find_job_mut(job_id) { job.status = if succeeded { JobStatus::Succeeded } else { JobStatus::Failed }; - job.ended_at = Some(now_utc()); + job.ended_at = Some(ended_at); } if let Some(service_id) = service_id { if let Some(service) = self.find_service_mut(service_id) { @@ -285,13 +303,20 @@ impl AppStore { job_id, service_id, } => { + let ended_at = now_utc(); if let Some(command) = self.find_command_mut(command_id) { command.status = CommandStatus::Cancelled; - command.ended_at = Some(now_utc()); + command.ended_at = Some(ended_at); } + self.update_history_for_command(command_id, |entry| { + entry.status = CommandStatus::Cancelled; + entry.exit_code = Some(130); + entry.ended_at = Some(ended_at); + }); + self.state.commands.session.last_exit_status = Some(130); if let Some(job) = self.find_job_mut(job_id) { job.status = JobStatus::Cancelled; - job.ended_at = Some(now_utc()); + job.ended_at = Some(ended_at); } if let Some(service_id) = service_id { if let Some(service) = self.find_service_mut(service_id) { @@ -374,7 +399,7 @@ impl AppStore { ModalState::Approval(_) => { self.dispatch_action(AppAction::Ui(UiIntent::ApproveCurrent)) } - ModalState::Help | ModalState::Error(_) => { + ModalState::Help | ModalState::History | ModalState::Error(_) => { self.close_modal(); Vec::new() } @@ -526,7 +551,9 @@ impl AppStore { Some(ModalState::Approval(_)) => { self.dispatch_action(AppAction::Ui(UiIntent::DenyCurrent)) } - Some(ModalState::Help) | Some(ModalState::Error(_)) => { + Some(ModalState::Help) + | Some(ModalState::History) + | Some(ModalState::Error(_)) => { self.close_modal(); Vec::new() } @@ -547,6 +574,9 @@ impl AppStore { background, provenance, } => self.prepare_execution(command, background, provenance), + ParsedInput::ChangeDirectory { target } => self.change_directory(target), + ParsedInput::SetEnv { key, value } => self.set_session_env(key, value), + ParsedInput::UnsetEnv { key } => self.unset_session_env(key), ParsedInput::Quit => self.dispatch_action(AppAction::Ui(UiIntent::Quit)), ParsedInput::Clear => { self.state.ui.input.clear(); @@ -589,6 +619,14 @@ impl AppStore { } } ParsedInput::Cancel(command_id) => self.dispatch_action(AppAction::Cancel(command_id)), + ParsedInput::History => { + self.state.ui.modal = Some(ModalState::History); + self.state.ui.focus = FocusTarget::Modal; + self.append_timeline(TimelineKind::System, "opened command history".to_string()); + Vec::new() + } + ParsedInput::Rerun(command_id) => self.rerun_command(command_id), + ParsedInput::RerunLast => self.rerun_last_command(), ParsedInput::Help => { self.state.ui.modal = Some(ModalState::Help); self.state.ui.focus = FocusTarget::Modal; @@ -716,7 +754,13 @@ impl AppStore { fn history_entries_for_mode(&self) -> Vec { match self.state.ui.input.mode { - InputMode::Shell => self.state.commands.history.clone(), + InputMode::Shell => self + .state + .commands + .history + .iter() + .map(|entry| entry.raw.clone()) + .collect(), InputMode::AiAssist => self .state .ai @@ -736,6 +780,180 @@ impl AppStore { } } + fn rerun_command(&mut self, command_id: CommandId) -> Vec { + let entry = self + .state + .commands + .history + .iter() + .rev() + .find(|entry| entry.command_id == Some(command_id)) + .cloned(); + + let Some(entry) = entry else { + self.push_notification( + NotificationLevel::Warn, + format!("no command history entry found for #{command_id}"), + ); + self.append_timeline( + TimelineKind::Error, + format!("rerun requested for missing command #{command_id}"), + ); + return Vec::new(); + }; + + self.replay_history_entry(entry, format!("command #{command_id}")) + } + + fn rerun_last_command(&mut self) -> Vec { + let Some(entry) = self.state.commands.history.last().cloned() else { + self.push_notification( + NotificationLevel::Info, + "no shell history is available to rerun".to_string(), + ); + return Vec::new(); + }; + + self.replay_history_entry(entry, "latest history entry".to_string()) + } + + fn replay_history_entry(&mut self, entry: CommandHistoryEntry, source: String) -> Vec { + self.append_timeline( + TimelineKind::Command, + format!( + "replaying {source}: {}", + truncate_for_timeline(&entry.raw, 96) + ), + ); + + let parsed = match parse_input(&entry.raw) { + Ok(parsed) => parsed, + Err(message) => { + self.push_notification(NotificationLevel::Warn, message.clone()); + self.append_timeline(TimelineKind::Error, message); + return Vec::new(); + } + }; + + match parsed { + ParsedInput::Execute { command, .. } => self.prepare_execution_internal( + command, + entry.background, + crate::domain::CommandProvenance::SlashCommand, + None, + Some(entry.cwd), + Some(entry.shell), + ), + ParsedInput::ChangeDirectory { target } => self.change_directory(target), + ParsedInput::SetEnv { key, value } => self.set_session_env(key, value), + ParsedInput::UnsetEnv { key } => self.unset_session_env(key), + ParsedInput::Clear => self.handle_parsed_input(ParsedInput::Clear), + ParsedInput::Quit => { + self.push_notification( + NotificationLevel::Warn, + "refusing to replay a quit command".to_string(), + ); + Vec::new() + } + _ => { + self.push_notification( + NotificationLevel::Warn, + format!("history entry is not replayable: {}", entry.raw), + ); + Vec::new() + } + } + } + + fn change_directory(&mut self, target: Option) -> Vec { + let submitted_at = now_utc(); + let current = self.state.commands.session.cwd.clone(); + let previous = self.state.commands.session.previous_cwd.clone(); + match resolve_cd_target(¤t, previous.as_deref(), target.as_deref()) { + Ok(next_cwd) => { + self.push_shell_history(CommandHistoryEntry::builtin( + cd_history_entry(target.as_deref()), + current.clone(), + self.state.commands.session.shell.clone(), + crate::domain::SafetyClass::Passive, + CommandStatus::Succeeded, + Some(0), + submitted_at, + )); + self.state.commands.session.previous_cwd = Some(current); + self.state.commands.session.cwd = next_cwd.clone(); + self.state.commands.session.last_exit_status = Some(0); + self.append_timeline( + TimelineKind::Command, + format!("session cwd changed to {}", next_cwd.display()), + ); + self.push_notification( + NotificationLevel::Info, + format!("cwd: {}", next_cwd.display()), + ); + } + Err(message) => { + self.push_shell_history(CommandHistoryEntry::builtin( + cd_history_entry(target.as_deref()), + current.clone(), + self.state.commands.session.shell.clone(), + crate::domain::SafetyClass::Passive, + CommandStatus::Failed, + Some(1), + submitted_at, + )); + self.state.commands.session.last_exit_status = Some(1); + self.state.diagnostics.records.push(DiagnosticRecord { + at: now_utc(), + level: DiagnosticLevel::Warn, + message: message.clone(), + context: Some(format!("cwd: {}", current.display())), + }); + self.append_timeline(TimelineKind::Error, message.clone()); + self.push_notification(NotificationLevel::Warn, message); + } + } + + Vec::new() + } + + fn set_session_env(&mut self, key: String, value: String) -> Vec { + let submitted_at = now_utc(); + let raw = format!("export {key}={value}"); + self.push_shell_history(CommandHistoryEntry::builtin( + raw, + self.state.commands.session.cwd.clone(), + self.state.commands.session.shell.clone(), + crate::domain::SafetyClass::Safe, + CommandStatus::Succeeded, + Some(0), + submitted_at, + )); + self.state.commands.session.env.insert(key.clone(), value); + self.state.commands.session.last_exit_status = Some(0); + self.append_timeline(TimelineKind::Command, format!("session env set: {key}")); + self.push_notification(NotificationLevel::Info, format!("env set: {key}")); + Vec::new() + } + + fn unset_session_env(&mut self, key: String) -> Vec { + let submitted_at = now_utc(); + self.push_shell_history(CommandHistoryEntry::builtin( + format!("unset {key}"), + self.state.commands.session.cwd.clone(), + self.state.commands.session.shell.clone(), + crate::domain::SafetyClass::Safe, + CommandStatus::Succeeded, + Some(0), + submitted_at, + )); + self.state.commands.session.env.remove(&key); + self.state.commands.session.last_exit_status = Some(0); + self.append_timeline(TimelineKind::Command, format!("session env unset: {key}")); + self.push_notification(NotificationLevel::Info, format!("env unset: {key}")); + Vec::new() + } + fn prepare_ai_request(&mut self, prompt: String, kind: AiRequestKind) -> Vec { if !self.state.ai.enabled { let message = "AI is disabled in the current Forge configuration.".to_string(); @@ -785,13 +1003,22 @@ impl AppStore { vec![Effect::RunAiRequest(Box::new(request))] } + fn push_shell_history(&mut self, entry: CommandHistoryEntry) { + self.state.commands.history.push(entry); + if self.state.commands.history.len() > self.state.config.commands.history_limit { + let overflow = + self.state.commands.history.len() - self.state.config.commands.history_limit; + self.state.commands.history.drain(0..overflow); + } + } + fn prepare_execution( &mut self, raw: String, background: bool, provenance: crate::domain::CommandProvenance, ) -> Vec { - self.prepare_execution_internal(raw, background, provenance, None) + self.prepare_execution_internal(raw, background, provenance, None, None, None) } fn prepare_execution_internal( @@ -800,20 +1027,23 @@ impl AppStore { background: bool, provenance: crate::domain::CommandProvenance, proposal_context: Option<(usize, &AiActionProposal)>, + cwd_override: Option, + shell_override: Option, ) -> Vec { let safety_class = classify_command(&raw); let command_id = self.ids.next_command(); let job_id = self.ids.next_job(); let service_id = background.then(|| self.ids.next_service()); + let submitted_at = now_utc(); let request = ExecutionRequest { command_id, job_id, service_id, raw: raw.clone(), - cwd: self.state.project.root.clone(), - env: BTreeMap::new(), - shell: self.state.config.commands.default_shell.clone(), - mode: ExecutionMode::Managed, + cwd: cwd_override.unwrap_or_else(|| self.state.commands.session.cwd.clone()), + env: self.state.commands.session.env.clone(), + shell: shell_override.unwrap_or_else(|| self.state.commands.session.shell.clone()), + mode: shell::execution_mode_for(&raw, background), provenance, background, safety_class, @@ -825,12 +1055,11 @@ impl AppStore { None => CommandStatus::Queued, }; - self.state.commands.history.push(raw.clone()); - if self.state.commands.history.len() > self.state.config.commands.history_limit { - let overflow = - self.state.commands.history.len() - self.state.config.commands.history_limit; - self.state.commands.history.drain(0..overflow); - } + self.push_shell_history(CommandHistoryEntry::from_request( + &request, + status, + submitted_at, + )); self.state .commands @@ -961,6 +1190,8 @@ impl AppStore { background, provenance, Some((proposal_index, &proposal)), + None, + None, ), _ => Vec::new(), } @@ -992,6 +1223,9 @@ impl AppStore { if let Some(command) = self.find_command_mut(request.command_id) { command.status = CommandStatus::Queued; } + self.update_history_for_command(request.command_id, |entry| { + entry.status = CommandStatus::Queued; + }); self.append_timeline( TimelineKind::Approval, format!("approved command #{}", request.command_id), @@ -999,13 +1233,18 @@ impl AppStore { return vec![Effect::ExecuteCommand(request.execution)]; } + let denied_at = now_utc(); if let Some(command) = self.find_command_mut(request.command_id) { command.status = CommandStatus::Denied; - command.ended_at = Some(now_utc()); + command.ended_at = Some(denied_at); } + self.update_history_for_command(request.command_id, |entry| { + entry.status = CommandStatus::Denied; + entry.ended_at = Some(denied_at); + }); if let Some(job) = self.find_job_by_command_mut(request.command_id) { job.status = JobStatus::Cancelled; - job.ended_at = Some(now_utc()); + job.ended_at = Some(denied_at); } self.append_timeline( TimelineKind::Approval, @@ -1018,7 +1257,7 @@ impl AppStore { if let Some(modal) = self.state.ui.modal.as_ref() { return match modal { ModalState::Approval(id) => Some(*id), - ModalState::Help | ModalState::Error(_) => None, + ModalState::Help | ModalState::History | ModalState::Error(_) => None, }; } self.current_inline_approval_id() @@ -1092,6 +1331,23 @@ impl AppStore { .find(|record| record.id == id) } + fn update_history_for_command( + &mut self, + id: CommandId, + update: impl FnOnce(&mut CommandHistoryEntry), + ) { + if let Some(entry) = self + .state + .commands + .history + .iter_mut() + .rev() + .find(|entry| entry.command_id == Some(id)) + { + update(entry); + } + } + fn find_job_mut(&mut self, id: crate::shared::ids::JobId) -> Option<&mut JobRecord> { self.state .jobs @@ -1167,6 +1423,72 @@ fn truncate_for_timeline(message: &str, max_len: usize) -> String { format!("{}...", &trimmed[..max_len.saturating_sub(3)]) } +fn cd_history_entry(target: Option<&str>) -> String { + target + .map(str::trim) + .filter(|target| !target.is_empty()) + .map(|target| format!("cd {target}")) + .unwrap_or_else(|| "cd".to_string()) +} + +fn next_id_after_restored_state(state: &AppState) -> u64 { + state + .commands + .history + .iter() + .filter_map(|entry| entry.command_id.map(|id| id.0)) + .chain(state.commands.records.iter().map(|record| record.id.0)) + .chain(state.jobs.records.iter().map(|record| record.id.0)) + .chain(state.services.registry.iter().map(|record| record.id.0)) + .chain(state.approvals.pending.iter().map(|record| record.id.0)) + .chain(state.timeline.entries.iter().map(|record| record.id.0)) + .max() + .unwrap_or(0) + .saturating_add(1) +} + +fn resolve_cd_target( + current: &Path, + previous: Option<&Path>, + target: Option<&str>, +) -> Result { + let candidate = match target.map(str::trim).filter(|target| !target.is_empty()) { + None => dirs::home_dir().ok_or_else(|| "cd: home directory is unavailable".to_string())?, + Some("-") => previous + .map(Path::to_path_buf) + .ok_or_else(|| "cd: no previous directory recorded".to_string())?, + Some(raw) => expand_cd_target(raw)?, + }; + + let candidate = if candidate.is_absolute() { + candidate + } else { + current.join(candidate) + }; + + let canonical = std::fs::canonicalize(&candidate) + .map_err(|error| format!("cd: {}: {error}", candidate.display()))?; + if !canonical.is_dir() { + return Err(format!("cd: not a directory: {}", canonical.display())); + } + + Ok(canonical) +} + +fn expand_cd_target(raw: &str) -> Result { + if raw == "~" { + return dirs::home_dir().ok_or_else(|| "cd: home directory is unavailable".to_string()); + } + + if let Some(rest) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) { + let home = + dirs::home_dir().ok_or_else(|| "cd: home directory is unavailable".to_string())?; + return Ok(home.join(rest)); + } + + Ok(PathBuf::from(raw)) +} + fn approval_detail( background: bool, safety_class: crate::domain::SafetyClass, diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 2f78486..354dc50 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -14,7 +14,7 @@ impl SlashCommandSpec { } } -const SLASH_COMMANDS: [SlashCommandSpec; 12] = [ +const SLASH_COMMANDS: [SlashCommandSpec; 15] = [ SlashCommandSpec { usage: "/help", completion: "/help", @@ -45,6 +45,21 @@ const SLASH_COMMANDS: [SlashCommandSpec; 12] = [ completion: "/cancel ", summary: "Cancel a tracked managed command.", }, + SlashCommandSpec { + usage: "/history", + completion: "/history", + summary: "Open recent shell command history.", + }, + SlashCommandSpec { + usage: "/rerun ", + completion: "/rerun ", + summary: "Replay a tracked command through safety checks.", + }, + SlashCommandSpec { + usage: "/rerun-last", + completion: "/rerun-last", + summary: "Replay the latest shell history entry.", + }, SlashCommandSpec { usage: "/approve", completion: "/approve", @@ -84,6 +99,16 @@ pub enum ParsedInput { background: bool, provenance: CommandProvenance, }, + ChangeDirectory { + target: Option, + }, + SetEnv { + key: String, + value: String, + }, + UnsetEnv { + key: String, + }, Quit, Clear, NextTab, @@ -91,6 +116,9 @@ pub enum ParsedInput { ApprovePending, DenyPending, Cancel(CommandId), + History, + Rerun(CommandId), + RerunLast, Help, AiPrompt { prompt: String, @@ -137,6 +165,22 @@ pub fn parse_input(input: &str) -> Result { return Err("input is empty".to_string()); } + if trimmed == "clear" { + return Ok(ParsedInput::Clear); + } + if trimmed == "exit" || trimmed == "quit" { + return Ok(ParsedInput::Quit); + } + if let Some(target) = parse_cd_builtin(trimmed) { + return Ok(ParsedInput::ChangeDirectory { target }); + } + if let Some((key, value)) = parse_export_builtin(trimmed) { + return Ok(ParsedInput::SetEnv { key, value }); + } + if let Some(key) = parse_unset_builtin(trimmed) { + return Ok(ParsedInput::UnsetEnv { key }); + } + if !trimmed.starts_with('/') { return parse_shell_input(trimmed, CommandProvenance::UserInput); } @@ -162,6 +206,12 @@ pub fn parse_input(input: &str) -> Result { if trimmed == "/help" { return Ok(ParsedInput::Help); } + if trimmed == "/history" { + return Ok(ParsedInput::History); + } + if trimmed == "/rerun-last" { + return Ok(ParsedInput::RerunLast); + } if let Some(rest) = trimmed.strip_prefix("/bg ") { return Ok(ParsedInput::Execute { command: rest.trim().to_string(), @@ -176,6 +226,13 @@ pub fn parse_input(input: &str) -> Result { .map_err(|_| "cancel expects a numeric command id".to_string())?; return Ok(ParsedInput::Cancel(CommandId(id))); } + if let Some(rest) = trimmed.strip_prefix("/rerun ") { + let id = rest + .trim() + .parse::() + .map_err(|_| "rerun expects a numeric command id".to_string())?; + return Ok(ParsedInput::Rerun(CommandId(id))); + } if let Some(rest) = trimmed.strip_prefix("/ai ") { return Ok(ParsedInput::AiPrompt { prompt: rest.trim().to_string(), @@ -236,3 +293,74 @@ fn parse_shell(input: &str) -> (String, bool) { } (trimmed.to_string(), false) } + +fn parse_cd_builtin(input: &str) -> Option> { + if input == "cd" { + return Some(None); + } + + let target = input.strip_prefix("cd ")?; + let target = target.trim(); + if target_contains_shell_operator(target) { + return None; + } + + Some((!target.is_empty()).then(|| strip_matching_quotes(target).to_string())) +} + +fn parse_export_builtin(input: &str) -> Option<(String, String)> { + let assignment = input.strip_prefix("export ")?; + let (key, value) = assignment.trim().split_once('=')?; + let key = key.trim(); + if !is_valid_env_key(key) || value_contains_shell_evaluation(value) { + return None; + } + + Some(( + key.to_string(), + strip_matching_quotes(value.trim()).to_string(), + )) +} + +fn parse_unset_builtin(input: &str) -> Option { + let key = input.strip_prefix("unset ")?.trim(); + if !is_valid_env_key(key) { + return None; + } + + Some(key.to_string()) +} + +fn is_valid_env_key(key: &str) -> bool { + let mut chars = key.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !(first == '_' || first.is_ascii_alphabetic()) { + return false; + } + + chars.all(|char| char == '_' || char.is_ascii_alphanumeric()) +} + +fn value_contains_shell_evaluation(value: &str) -> bool { + ["`", "$("].iter().any(|operator| value.contains(operator)) +} + +fn target_contains_shell_operator(target: &str) -> bool { + ["&&", "||", ";", "|", ">", "<", "`", "$("] + .iter() + .any(|operator| target.contains(operator)) +} + +fn strip_matching_quotes(value: &str) -> &str { + let bytes = value.as_bytes(); + if bytes.len() >= 2 + && ((bytes.first() == Some(&b'"') && bytes.last() == Some(&b'"')) + || (bytes.first() == Some(&b'\'') && bytes.last() == Some(&b'\''))) + { + &value[1..value.len() - 1] + } else { + value + } +} diff --git a/src/domain/ai.rs b/src/domain/ai.rs index 6493f41..60a5329 100644 --- a/src/domain/ai.rs +++ b/src/domain/ai.rs @@ -86,10 +86,19 @@ pub struct AiGitContext { pub changed_files: Vec, } +#[derive(Debug, Clone)] +pub struct AiShellSessionContext { + pub cwd: PathBuf, + pub shell: String, + pub env_overlay_count: usize, + pub last_exit_status: Option, +} + #[derive(Debug, Clone)] pub struct AiCommandContext { pub id: CommandId, pub raw: String, + pub cwd: PathBuf, pub provenance: CommandProvenance, pub status: CommandStatus, pub exit_code: Option, @@ -139,6 +148,7 @@ pub struct AiContextBundle { pub ui: AiUiContext, pub project: AiProjectContext, pub git: AiGitContext, + pub session: AiShellSessionContext, pub commands: Vec, pub services: Vec, pub tests: Vec, diff --git a/src/domain/app.rs b/src/domain/app.rs index 290ad40..3e09404 100644 --- a/src/domain/app.rs +++ b/src/domain/app.rs @@ -58,6 +58,7 @@ impl DashboardTab { pub enum ModalState { Approval(ApprovalId), Help, + History, Error(String), } @@ -301,6 +302,8 @@ impl AppState { pub fn new(config: ForgeConfig, project: ProjectContext, git: GitSnapshot) -> Self { let diagnostics_capacity = config.observability.diagnostics_capacity; let global_log_capacity = config.logs.global_capacity; + let session_cwd = project.root.clone(); + let session_shell = config.commands.default_shell.clone(); Self { app: AppMetaState { started_at: now_utc(), @@ -319,7 +322,7 @@ impl AppState { config: config.clone(), project, git, - commands: CommandState::default(), + commands: CommandState::new(session_cwd, session_shell), jobs: JobState::default(), services: ServiceState::default(), processes: ProcessState::default(), diff --git a/src/domain/command.rs b/src/domain/command.rs index ca6a7ca..f8d09c3 100644 --- a/src/domain/command.rs +++ b/src/domain/command.rs @@ -5,13 +5,13 @@ use std::time::SystemTime; use crate::domain::approval::SafetyClass; use crate::shared::ids::{CommandId, JobId, ServiceId}; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum ExecutionMode { Managed, Pty, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum CommandProvenance { UserInput, SlashCommand, @@ -19,7 +19,7 @@ pub enum CommandProvenance { AiSuggestion, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum CommandStatus { PendingReview, PendingApproval, @@ -31,7 +31,7 @@ pub enum CommandStatus { Denied, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum OutputStream { Stdout, Stderr, @@ -85,9 +85,123 @@ impl CommandRecord { } } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct CommandHistoryEntry { + pub command_id: Option, + pub raw: String, + pub cwd: PathBuf, + pub shell: String, + pub provenance: CommandProvenance, + pub background: bool, + pub safety_class: SafetyClass, + pub status: CommandStatus, + pub submitted_at: SystemTime, + pub started_at: Option, + pub ended_at: Option, + pub exit_code: Option, +} + +impl CommandHistoryEntry { + pub fn from_request( + request: &ExecutionRequest, + status: CommandStatus, + submitted_at: SystemTime, + ) -> Self { + Self { + command_id: Some(request.command_id), + raw: request.raw.clone(), + cwd: request.cwd.clone(), + shell: request.shell.clone(), + provenance: request.provenance, + background: request.background, + safety_class: request.safety_class, + status, + submitted_at, + started_at: None, + ended_at: None, + exit_code: None, + } + } + + pub fn builtin( + raw: String, + cwd: PathBuf, + shell: String, + safety_class: SafetyClass, + status: CommandStatus, + exit_code: Option, + submitted_at: SystemTime, + ) -> Self { + let ended_at = matches!( + status, + CommandStatus::Succeeded + | CommandStatus::Failed + | CommandStatus::Cancelled + | CommandStatus::Denied + ) + .then_some(submitted_at); + + Self { + command_id: None, + raw, + cwd, + shell, + provenance: CommandProvenance::UserInput, + background: false, + safety_class, + status, + submitted_at, + started_at: Some(submitted_at), + ended_at, + exit_code, + } + } +} + #[derive(Debug, Clone, Default)] pub struct CommandState { - pub history: Vec, + pub session: ShellSessionState, + pub history: Vec, pub records: Vec, pub active_command: Option, } + +impl CommandState { + pub fn new(cwd: PathBuf, shell: String) -> Self { + Self { + session: ShellSessionState::new(cwd, shell), + history: Vec::new(), + records: Vec::new(), + active_command: None, + } + } +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ShellSessionState { + pub cwd: PathBuf, + pub previous_cwd: Option, + pub shell: String, + pub env: BTreeMap, + pub last_exit_status: Option, +} + +impl ShellSessionState { + pub fn new(cwd: PathBuf, shell: String) -> Self { + Self { + cwd, + previous_cwd: None, + shell, + env: BTreeMap::new(), + last_exit_status: None, + } + } +} + +impl Default for ShellSessionState { + fn default() -> Self { + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()); + Self::new(cwd, shell) + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 101c73a..024e3ac 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -15,7 +15,8 @@ pub mod timeline; pub use ai::{ AiActionProposal, AiCitation, AiCommandContext, AiContextBundle, AiGitContext, AiLogContext, AiMessage, AiMessageRole, AiProjectContext, AiRequest, AiRequestKind, AiResponse, - AiServiceContext, AiSessionState, AiStatus, AiTestContext, AiTimelineContext, AiUiContext, + AiServiceContext, AiSessionState, AiShellSessionContext, AiStatus, AiTestContext, + AiTimelineContext, AiUiContext, }; pub use app::{ AppMetaState, AppState, DashboardTab, FocusTarget, InputEditorState, InputMode, ModalState, @@ -23,8 +24,8 @@ pub use app::{ }; pub use approval::{ApprovalDecision, ApprovalMode, ApprovalRequest, ApprovalState, SafetyClass}; pub use command::{ - CommandProvenance, CommandRecord, CommandState, CommandStatus, ExecutionMode, ExecutionRequest, - OutputStream, + CommandHistoryEntry, CommandProvenance, CommandRecord, CommandState, CommandStatus, + ExecutionMode, ExecutionRequest, OutputStream, ShellSessionState, }; pub use diagnostics::{DiagnosticLevel, DiagnosticRecord, DiagnosticsState}; pub use git::GitSnapshot; diff --git a/src/infra/mod.rs b/src/infra/mod.rs index 727a82a..3225789 100644 --- a/src/infra/mod.rs +++ b/src/infra/mod.rs @@ -3,3 +3,4 @@ pub mod logs; pub mod monitor; pub mod project; pub mod shell; +pub mod state; diff --git a/src/infra/shell/mod.rs b/src/infra/shell/mod.rs index 44bdccc..a2a3397 100644 --- a/src/infra/shell/mod.rs +++ b/src/infra/shell/mod.rs @@ -1,17 +1,38 @@ use std::collections::HashMap; +use std::io::{Read, Write}; use std::process::Stdio; +use std::sync::mpsc::{self as std_mpsc, RecvTimeoutError}; use std::sync::Arc; +use std::time::{Duration, Instant}; +use portable_pty::{native_pty_system, CommandBuilder, PtySize}; use tokio::io::{AsyncBufReadExt, BufReader}; -use tokio::process::Command; +use tokio::process::{Child, Command}; use tokio::sync::{mpsc, oneshot, Mutex}; use crate::app::AppEvent; use crate::domain::{ExecutionMode, ExecutionRequest, OutputStream}; -use crate::shared::error::{AppResult, InfraError}; +use crate::shared::error::{AppResult, InfraError, PtyPhase}; use crate::shared::ids::CommandId; -pub type CancellationRegistry = Arc>>>; +pub type CancellationRegistry = Arc>>>>; + +const INTERACTIVE_COMMANDS: &[&str] = &[ + "bash", "bpython", "fish", "htop", "ipython", "irb", "less", "man", "more", "nano", "node", + "nvim", "python", "screen", "sh", "sqlite3", "ssh", "sudo", "tmux", "top", "vim", "watch", + "zsh", +]; +const MANAGED_CANCEL_GRACE: Duration = Duration::from_millis(750); + +pub fn execution_mode_for(raw: &str, background: bool) -> ExecutionMode { + if background { + ExecutionMode::Managed + } else if is_likely_interactive_command(raw) { + ExecutionMode::Pty + } else { + ExecutionMode::Managed + } +} pub fn spawn_managed_command( request: ExecutionRequest, @@ -19,7 +40,9 @@ pub fn spawn_managed_command( cancellations: CancellationRegistry, ) -> AppResult<()> { if !matches!(request.mode, ExecutionMode::Managed) { - return Err(InfraError::Runtime("PTY execution is not implemented yet".to_string()).into()); + return Err( + InfraError::Runtime("managed executor requires managed mode".to_string()).into(), + ); } let mut command = build_shell_command(&request); @@ -44,7 +67,7 @@ pub fn spawn_managed_command( tokio::spawn(async move { { let mut registry = cancellations_for_task.lock().await; - registry.insert(command_id, cancel_tx); + registry.insert(command_id, Some(cancel_tx)); } let _ = events_tx_for_task @@ -79,16 +102,19 @@ pub fn spawn_managed_command( tokio::select! { _ = &mut cancel_rx => { - if let Err(error) = child.kill().await { - let _ = events_tx_for_task.send(AppEvent::Error(format!( - "failed to cancel command `{raw}`: {error}" - ))).await; - } else { - let _ = events_tx_for_task.send(AppEvent::CommandCancelled { - command_id, - job_id, - service_id, - }).await; + match cancel_managed_child(&mut child, pid, &raw).await { + Ok(()) => { + let _ = events_tx_for_task.send(AppEvent::CommandCancelled { + command_id, + job_id, + service_id, + }).await; + } + Err(error) => { + let _ = events_tx_for_task.send(AppEvent::Error(format!( + "failed to cancel command `{raw}`: {error}" + ))).await; + } } } status = child.wait() => { @@ -117,22 +143,173 @@ pub fn spawn_managed_command( Ok(()) } +pub struct AttachedPtySession { + command_id: CommandId, + control_tx: std_mpsc::Sender, +} + +impl AttachedPtySession { + pub fn command_id(&self) -> CommandId { + self.command_id + } + + pub fn send_input(&self, bytes: Vec) -> AppResult<()> { + self.control_tx.send(PtyControl::Input(bytes)).map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Shutdown, + message: "pty session is no longer active".to_string(), + } + .into() + }) + } + + pub fn resize(&self, cols: u16, rows: u16) -> AppResult<()> { + self.control_tx + .send(PtyControl::Resize(PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + })) + .map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Shutdown, + message: "pty session is no longer active".to_string(), + } + .into() + }) + } + + pub fn interrupt(&self) -> AppResult<()> { + self.control_tx.send(PtyControl::Interrupt).map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Shutdown, + message: "pty session is no longer active".to_string(), + } + .into() + }) + } + + pub fn cancel(&self) -> AppResult<()> { + self.control_tx.send(PtyControl::Cancel).map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Shutdown, + message: "pty session is no longer active".to_string(), + } + .into() + }) + } +} + +enum PtyControl { + Input(Vec), + Resize(PtySize), + Interrupt, + Cancel, +} + +pub fn spawn_attached_pty_command( + request: ExecutionRequest, + events_tx: mpsc::Sender, +) -> AppResult { + if !matches!(request.mode, ExecutionMode::Pty) { + return Err(InfraError::Runtime("pty executor requires pty mode".to_string()).into()); + } + + #[cfg(unix)] + { + spawn_attached_pty_command_unix(request, events_tx) + } + + #[cfg(not(unix))] + { + let _ = request; + let _ = events_tx; + Err(InfraError::Pty { + phase: PtyPhase::Setup, + message: "PTY execution is only implemented on Unix-like systems".to_string(), + } + .into()) + } +} + +fn is_likely_interactive_command(raw: &str) -> bool { + if contains_shell_operators(raw) { + return false; + } + + let Some(token) = first_command_token(raw) else { + return false; + }; + let command = token.rsplit(['/', '\\']).next().unwrap_or(token); + INTERACTIVE_COMMANDS.contains(&command) +} + +fn contains_shell_operators(raw: &str) -> bool { + ["&&", "||", ";", "|", ">", "<"] + .iter() + .any(|operator| raw.contains(operator)) +} + +fn first_command_token(raw: &str) -> Option<&str> { + raw.split_whitespace().next() +} + +async fn cancel_managed_child(child: &mut Child, pid: Option, raw: &str) -> AppResult<()> { + terminate_managed_child(child, pid).await?; + match tokio::time::timeout(MANAGED_CANCEL_GRACE, child.wait()).await { + Ok(Ok(_status)) => Ok(()), + Ok(Err(error)) => Err(InfraError::Runtime(format!( + "failed waiting for cancelled command `{raw}`: {error}" + )) + .into()), + Err(_elapsed) => { + kill_managed_child(child, pid).await?; + match tokio::time::timeout(MANAGED_CANCEL_GRACE, child.wait()).await { + Ok(Ok(_status)) => Ok(()), + Ok(Err(error)) => Err(InfraError::Runtime(format!( + "failed waiting for force-killed command `{raw}`: {error}" + )) + .into()), + Err(_elapsed) => Err(InfraError::Runtime(format!( + "timed out waiting for force-killed command `{raw}`" + )) + .into()), + } + } + } +} + +#[cfg(unix)] +async fn terminate_managed_child(_child: &mut Child, pid: Option) -> AppResult<()> { + signal_managed_process(pid, libc::SIGTERM) +} + +#[cfg(not(unix))] +async fn terminate_managed_child(child: &mut Child, _pid: Option) -> AppResult<()> { + child.start_kill()?; + Ok(()) +} + +#[cfg(unix)] +async fn kill_managed_child(_child: &mut Child, pid: Option) -> AppResult<()> { + signal_managed_process(pid, libc::SIGKILL) +} + +#[cfg(not(unix))] +async fn kill_managed_child(child: &mut Child, _pid: Option) -> AppResult<()> { + child.kill().await?; + Ok(()) +} + fn build_shell_command(request: &ExecutionRequest) -> Command { let mut command = if cfg!(windows) { - let shell = if request.shell.trim().is_empty() { - "cmd".to_string() - } else { - request.shell.clone() - }; + let shell = effective_shell(&request.shell, true); let mut command = Command::new(shell); command.arg("/C").arg(&request.raw); command } else { - let shell = if request.shell.trim().is_empty() { - "/bin/sh".to_string() - } else { - request.shell.clone() - }; + let shell = effective_shell(&request.shell, false); let mut command = Command::new(shell); command.arg("-lc").arg(&request.raw); command @@ -142,10 +319,46 @@ fn build_shell_command(request: &ExecutionRequest) -> Command { for (key, value) in &request.env { command.env(key, value); } + #[cfg(unix)] + { + command.process_group(0); + } command.kill_on_drop(true); command } +fn build_pty_command(request: &ExecutionRequest) -> CommandBuilder { + let mut command = if cfg!(windows) { + let mut builder = CommandBuilder::new(effective_shell(&request.shell, true)); + builder.arg("/C"); + builder.arg(&request.raw); + builder + } else { + let mut builder = CommandBuilder::new(effective_shell(&request.shell, false)); + builder.arg("-lc"); + builder.arg(&request.raw); + builder + }; + + command.cwd(&request.cwd); + for (key, value) in &request.env { + command.env(key, value); + } + command +} + +fn effective_shell(shell: &str, windows: bool) -> String { + if shell.trim().is_empty() { + if windows { + "cmd".to_string() + } else { + "/bin/sh".to_string() + } + } else { + shell.to_string() + } +} + fn spawn_stream_reader( reader: R, events_tx: mpsc::Sender, @@ -184,3 +397,477 @@ fn spawn_stream_reader( } }); } + +#[cfg(unix)] +fn spawn_attached_pty_command_unix( + request: ExecutionRequest, + events_tx: mpsc::Sender, +) -> AppResult { + let pty_system = native_pty_system(); + let pair = pty_system + .openpty(current_pty_size()?) + .map_err(|error| InfraError::Pty { + phase: PtyPhase::Setup, + message: format!("failed to open pty: {error}"), + })?; + let command = build_pty_command(&request); + let mut child = pair + .slave + .spawn_command(command) + .map_err(|error| InfraError::Pty { + phase: PtyPhase::Setup, + message: format!("failed to spawn pty command: {error}"), + })?; + drop(pair.slave); + + let pid = child.process_id(); + let process_group = pair + .master + .process_group_leader() + .and_then(|leader| u32::try_from(leader).ok()) + .or(pid); + let reader = pair + .master + .try_clone_reader() + .map_err(|error| InfraError::Pty { + phase: PtyPhase::Setup, + message: format!("failed to clone pty reader: {error}"), + })?; + let mut writer = pair.master.take_writer().map_err(|error| InfraError::Pty { + phase: PtyPhase::Setup, + message: format!("failed to open pty writer: {error}"), + })?; + let (control_tx, control_rx) = std_mpsc::channel(); + let command_id = request.command_id; + let job_id = request.job_id; + let service_id = request.service_id; + let raw = request.raw.clone(); + let output_events_tx = events_tx.clone(); + + std::thread::spawn(move || { + let _ = events_tx.blocking_send(AppEvent::CommandStarted { + command_id, + job_id, + service_id, + pid, + }); + + let output_thread = std::thread::spawn(move || { + stream_pty_output(reader, output_events_tx, command_id, job_id, service_id) + }); + + let result = drive_pty_session( + &mut child, + &*pair.master, + &mut writer, + process_group, + &raw, + control_rx, + ); + drop(writer); + let output_result = output_thread + .join() + .map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Read, + message: "pty output thread panicked".to_string(), + } + .into() + }) + .and_then(|result| result); + + match result { + Ok(completion) => { + if let Err(error) = output_result { + let _ = events_tx.blocking_send(AppEvent::Error(error.to_string())); + } + if completion.cancelled { + let _ = events_tx.blocking_send(AppEvent::CommandCancelled { + command_id, + job_id, + service_id, + }); + } else { + let _ = events_tx.blocking_send(AppEvent::CommandExited { + command_id, + job_id, + service_id, + exit_code: completion.exit_code, + }); + } + } + Err(error) => { + let _ = terminate_process_group(process_group); + let _ = events_tx.blocking_send(AppEvent::Error(error.to_string())); + let _ = events_tx.blocking_send(AppEvent::CommandCancelled { + command_id, + job_id, + service_id, + }); + } + } + }); + + Ok(AttachedPtySession { + command_id, + control_tx, + }) +} + +#[cfg(unix)] +fn current_pty_size() -> AppResult { + let (cols, rows) = crossterm::terminal::size().map_err(|error| InfraError::Pty { + phase: PtyPhase::Setup, + message: format!("failed to determine terminal size for pty: {error}"), + })?; + Ok(PtySize { + rows, + cols, + pixel_width: 0, + pixel_height: 0, + }) +} + +#[cfg(unix)] +fn stream_pty_output( + mut reader: Box, + events_tx: mpsc::Sender, + command_id: CommandId, + job_id: crate::shared::ids::JobId, + service_id: Option, +) -> AppResult<()> { + let mut stdout = std::io::stdout(); + let mut buffer = [0_u8; 4096]; + let mut pending = Vec::new(); + + loop { + let bytes = reader.read(&mut buffer).map_err(|error| InfraError::Pty { + phase: PtyPhase::Read, + message: format!("failed reading pty output: {error}"), + })?; + if bytes == 0 { + break; + } + + stdout + .write_all(&buffer[..bytes]) + .map_err(|error| InfraError::Pty { + phase: PtyPhase::Read, + message: format!("failed writing pty output to terminal: {error}"), + })?; + stdout.flush().map_err(|error| InfraError::Pty { + phase: PtyPhase::Read, + message: format!("failed flushing pty output to terminal: {error}"), + })?; + pending.extend_from_slice(&buffer[..bytes]); + + while let Some(index) = pending.iter().position(|byte| *byte == b'\n') { + let mut line = pending.drain(..=index).collect::>(); + if matches!(line.last(), Some(b'\n')) { + line.pop(); + } + if matches!(line.last(), Some(b'\r')) { + line.pop(); + } + emit_pty_line( + &events_tx, + command_id, + job_id, + service_id, + String::from_utf8_lossy(&line).to_string(), + )?; + } + } + + if !pending.is_empty() { + emit_pty_line( + &events_tx, + command_id, + job_id, + service_id, + String::from_utf8_lossy(&pending).to_string(), + )?; + } + + Ok(()) +} + +#[cfg(unix)] +fn emit_pty_line( + events_tx: &mpsc::Sender, + command_id: CommandId, + job_id: crate::shared::ids::JobId, + service_id: Option, + line: String, +) -> AppResult<()> { + if line.is_empty() { + return Ok(()); + } + events_tx + .blocking_send(AppEvent::CommandOutput { + command_id, + job_id, + service_id, + stream: OutputStream::Stdout, + chunk: line, + }) + .map_err(|_| { + InfraError::Pty { + phase: PtyPhase::Read, + message: "failed to publish pty output".to_string(), + } + .into() + }) +} + +#[cfg(unix)] +struct PtyCompletion { + exit_code: i32, + cancelled: bool, +} + +#[cfg(unix)] +fn drive_pty_session( + child: &mut Box, + master: &(dyn portable_pty::MasterPty + Send), + writer: &mut Box, + pid: Option, + raw: &str, + control_rx: std_mpsc::Receiver, +) -> AppResult { + let mut cancelled = false; + let mut interrupted = false; + let mut kill_deadline = None; + + loop { + if let Some(status) = child.try_wait().map_err(|error| InfraError::Pty { + phase: PtyPhase::Shutdown, + message: format!("failed waiting for pty command `{raw}`: {error}"), + })? { + let exit_code = status.exit_code() as i32; + return Ok(PtyCompletion { + exit_code, + cancelled: cancelled || (interrupted && exit_code == 130), + }); + } + + if let Some(deadline) = kill_deadline { + if Instant::now() >= deadline { + signal_process(pid, libc::SIGKILL)?; + kill_deadline = None; + } + } + + match control_rx.recv_timeout(Duration::from_millis(16)) { + Ok(PtyControl::Input(bytes)) => { + writer.write_all(&bytes).map_err(|error| InfraError::Pty { + phase: PtyPhase::Write, + message: format!("failed forwarding stdin to pty: {error}"), + })?; + writer.flush().map_err(|error| InfraError::Pty { + phase: PtyPhase::Write, + message: format!("failed flushing pty stdin: {error}"), + })?; + } + Ok(PtyControl::Resize(size)) => { + master.resize(size).map_err(|error| InfraError::Pty { + phase: PtyPhase::Resize, + message: format!("failed resizing pty: {error}"), + })?; + } + Ok(PtyControl::Interrupt) => { + interrupted = true; + signal_process(pid, libc::SIGINT)?; + } + Ok(PtyControl::Cancel) => { + cancelled = true; + signal_process(pid, libc::SIGTERM)?; + kill_deadline = Some(Instant::now() + Duration::from_millis(250)); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => { + cancelled = true; + signal_process(pid, libc::SIGTERM)?; + kill_deadline = Some(Instant::now() + Duration::from_millis(250)); + } + } + } +} + +#[cfg(unix)] +fn terminate_process_group(pid: Option) -> AppResult<()> { + signal_process(pid, libc::SIGTERM)?; + std::thread::sleep(Duration::from_millis(50)); + signal_process(pid, libc::SIGKILL) +} + +#[cfg(unix)] +fn signal_process(pid: Option, signal: i32) -> AppResult<()> { + let Some(pid) = pid else { + return Ok(()); + }; + let pid = pid as i32; + + if unsafe { libc::killpg(pid, signal) } == 0 { + return Ok(()); + } + let process_group_error = std::io::Error::last_os_error(); + if matches!(process_group_error.raw_os_error(), Some(code) if code == libc::ESRCH) { + return Ok(()); + } + + if unsafe { libc::kill(pid, signal) } == 0 { + return Ok(()); + } + let process_error = std::io::Error::last_os_error(); + if matches!(process_error.raw_os_error(), Some(code) if code == libc::ESRCH) { + return Ok(()); + } + + Err(InfraError::Pty { + phase: PtyPhase::Shutdown, + message: format!("failed signaling pty process {pid}: {process_error}"), + } + .into()) +} + +#[cfg(unix)] +fn signal_managed_process(pid: Option, signal: i32) -> AppResult<()> { + let Some(pid) = pid else { + return Ok(()); + }; + let pid = pid as i32; + + if unsafe { libc::killpg(pid, signal) } == 0 { + return Ok(()); + } + let process_group_error = std::io::Error::last_os_error(); + if matches!(process_group_error.raw_os_error(), Some(code) if code == libc::ESRCH) { + return Ok(()); + } + + if unsafe { libc::kill(pid, signal) } == 0 { + return Ok(()); + } + let process_error = std::io::Error::last_os_error(); + if matches!(process_error.raw_os_error(), Some(code) if code == libc::ESRCH) { + return Ok(()); + } + + Err(InfraError::Runtime(format!( + "failed signaling managed process {pid}: {process_error}" + )) + .into()) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use std::sync::Arc; + + use tokio::sync::{mpsc, Mutex}; + + use super::{execution_mode_for, spawn_managed_command, CancellationRegistry, ExecutionMode}; + use crate::app::AppEvent; + use crate::domain::{CommandProvenance, ExecutionRequest, SafetyClass}; + use crate::shared::ids::{CommandId, JobId}; + + #[test] + fn chooses_pty_for_interactive_foreground_commands() { + assert!(matches!( + execution_mode_for("top", false), + ExecutionMode::Pty + )); + assert!(matches!( + execution_mode_for("bash", false), + ExecutionMode::Pty + )); + } + + #[test] + fn keeps_managed_mode_for_background_and_operator_commands() { + assert!(matches!( + execution_mode_for("top", true), + ExecutionMode::Managed + )); + assert!(matches!( + execution_mode_for("echo hi | less", false), + ExecutionMode::Managed + )); + assert!(matches!( + execution_mode_for("pwd", false), + ExecutionMode::Managed + )); + } + + #[cfg(unix)] + #[tokio::test] + async fn managed_command_cancellation_emits_cancelled_event() { + let (events_tx, mut events_rx) = mpsc::channel(16); + let cancellations: CancellationRegistry = Arc::new(Mutex::new(Default::default())); + let request = ExecutionRequest { + command_id: CommandId(1), + job_id: JobId(2), + service_id: None, + raw: "sleep 30".to_string(), + cwd: std::env::current_dir().expect("current dir should exist"), + env: BTreeMap::new(), + shell: std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()), + mode: ExecutionMode::Managed, + provenance: CommandProvenance::UserInput, + background: false, + safety_class: SafetyClass::Passive, + }; + + spawn_managed_command(request, events_tx, cancellations.clone()) + .expect("managed command should spawn"); + + let started = tokio::time::timeout(std::time::Duration::from_secs(2), events_rx.recv()) + .await + .expect("command should start") + .expect("start event should be sent"); + assert!(matches!( + started, + AppEvent::CommandStarted { + command_id: CommandId(1), + .. + } + )); + + let cancel_tx = { + let mut registry = cancellations.lock().await; + registry + .get_mut(&CommandId(1)) + .and_then(Option::take) + .expect("command should be cancellable") + }; + let _ = cancel_tx.send(()); + + loop { + let event = tokio::time::timeout(std::time::Duration::from_secs(2), events_rx.recv()) + .await + .expect("cancelled event should arrive") + .expect("cancelled event should be sent"); + if matches!( + event, + AppEvent::CommandCancelled { + command_id: CommandId(1), + .. + } + ) { + break; + } + } + + tokio::time::timeout(std::time::Duration::from_secs(2), async { + loop { + if cancellations.lock().await.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .expect("cancellation registry should be cleaned up"); + } +} diff --git a/src/infra/state/mod.rs b/src/infra/state/mod.rs new file mode 100644 index 0000000..83e56d8 --- /dev/null +++ b/src/infra/state/mod.rs @@ -0,0 +1,121 @@ +use std::fs::{self, File}; +use std::io::{BufRead, BufReader, BufWriter, Write}; +use std::path::{Path, PathBuf}; + +use tracing::warn; + +use crate::domain::{CommandHistoryEntry, ShellSessionState}; +use crate::shared::error::{AppResult, InfraError}; + +const COMMAND_HISTORY_FILE: &str = "command-history.jsonl"; +const SESSION_FILE: &str = "session.toml"; + +pub fn workspace_state_dir(project_root: &Path) -> PathBuf { + project_root.join(".forge").join("state") +} + +pub fn command_history_path(project_root: &Path) -> PathBuf { + workspace_state_dir(project_root).join(COMMAND_HISTORY_FILE) +} + +pub fn shell_session_path(project_root: &Path) -> PathBuf { + workspace_state_dir(project_root).join(SESSION_FILE) +} + +pub fn load_command_history( + project_root: &Path, + limit: usize, +) -> AppResult> { + let path = command_history_path(project_root); + if !path.exists() { + return Ok(Vec::new()); + } + + let file = File::open(&path)?; + let reader = BufReader::new(file); + let mut entries = Vec::new(); + + for (line_number, line) in reader.lines().enumerate() { + let line = line?; + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + + match serde_json::from_str::(trimmed) { + Ok(entry) => entries.push(entry), + Err(error) => { + warn!( + path = %path.display(), + line = line_number + 1, + %error, + "skipping invalid command history entry" + ); + } + } + } + + trim_history(&mut entries, limit); + Ok(entries) +} + +pub fn save_command_history( + project_root: &Path, + entries: &[CommandHistoryEntry], +) -> AppResult> { + if entries.is_empty() { + return Ok(None); + } + + let path = command_history_path(project_root); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + + let tmp_path = path.with_extension("jsonl.tmp"); + { + let file = File::create(&tmp_path)?; + let mut writer = BufWriter::new(file); + for entry in entries { + serde_json::to_writer(&mut writer, entry)?; + writer.write_all(b"\n")?; + } + writer.flush()?; + } + + fs::rename(&tmp_path, &path)?; + Ok(Some(path)) +} + +pub fn load_shell_session(project_root: &Path) -> AppResult> { + let path = shell_session_path(project_root); + if !path.exists() { + return Ok(None); + } + + let raw = fs::read_to_string(&path)?; + let session = toml::from_str::(&raw)?; + Ok(Some(session)) +} + +pub fn save_shell_session(project_root: &Path, session: &ShellSessionState) -> AppResult { + let path = shell_session_path(project_root); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + + let raw = toml::to_string_pretty(session).map_err(|error| { + InfraError::Runtime(format!("failed to serialize shell session state: {error}")) + })?; + let tmp_path = path.with_extension("toml.tmp"); + fs::write(&tmp_path, raw)?; + fs::rename(&tmp_path, &path)?; + Ok(path) +} + +fn trim_history(entries: &mut Vec, limit: usize) { + if entries.len() > limit { + let overflow = entries.len() - limit; + entries.drain(0..overflow); + } +} diff --git a/src/runtime/engine.rs b/src/runtime/engine.rs index 935644c..b0f48f3 100644 --- a/src/runtime/engine.rs +++ b/src/runtime/engine.rs @@ -1,3 +1,4 @@ +use std::collections::VecDeque; use std::time::Duration; use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; @@ -8,10 +9,11 @@ use tracing::{error, info}; use crate::ai::AiRuntime; use crate::app::{AppAction, AppEvent, AppStore, Effect, UiIntent}; use crate::commands::{slash_palette_active, ParsedInput}; -use crate::domain::FocusTarget; +use crate::domain::{ExecutionMode, FocusTarget}; +use crate::infra::{shell, state as local_state}; use crate::observability::ObservabilityHandle; use crate::runtime::RuntimeSupervisor; -use crate::shared::error::AppResult; +use crate::shared::error::{AppResult, InfraError, PtyPhase}; use crate::ui::{render, terminal::TerminalUi}; pub struct Runtime { @@ -19,6 +21,7 @@ pub struct Runtime { terminal: TerminalUi, supervisor: RuntimeSupervisor, events_rx: mpsc::Receiver, + active_pty: Option, _observability: ObservabilityHandle, } @@ -36,6 +39,7 @@ impl Runtime { terminal, supervisor, events_rx, + active_pty: None, _observability: observability, } } @@ -61,28 +65,36 @@ impl Runtime { if let Some(result) = maybe_event { match result { Ok(event) => { - let effects = self.handle_terminal_event(event); + let effects = self.handle_terminal_event(event)?; self.apply_effects(effects).await?; - self.render()?; + if !self.pty_active() { + self.render()?; + } } Err(error) => { error!(%error, "terminal input error"); let effects = self.store.dispatch_event(AppEvent::Error(error.to_string())); self.apply_effects(effects).await?; - self.render()?; + if !self.pty_active() { + self.render()?; + } } } } } Some(event) = self.events_rx.recv() => { - let effects = self.store.dispatch_event(event); + let effects = self.process_app_event(event)?; self.apply_effects(effects).await?; - self.render()?; + if !self.pty_active() { + self.render()?; + } } _ = tick.tick() => { let effects = self.store.dispatch_action(AppAction::Ui(UiIntent::Tick)); self.apply_effects(effects).await?; - self.render()?; + if !self.pty_active() { + self.render()?; + } } signal = tokio::signal::ctrl_c() => { if signal.is_ok() { @@ -94,21 +106,58 @@ impl Runtime { } info!("forge runtime shutting down"); + self.shutdown_active_pty().await?; + self.supervisor + .shutdown_commands(Duration::from_secs(2)) + .await?; + let persist_result = self.persist_local_state(); self.terminal.restore()?; + persist_result?; + Ok(()) + } + + fn persist_local_state(&self) -> AppResult<()> { + if let Some(path) = local_state::save_command_history( + &self.store.state().project.root, + &self.store.state().commands.history, + )? { + info!(path = %path.display(), "command history persisted"); + } + let session_path = local_state::save_shell_session( + &self.store.state().project.root, + &self.store.state().commands.session, + )?; + info!(path = %session_path.display(), "shell session persisted"); Ok(()) } async fn apply_effects(&mut self, effects: Vec) -> AppResult<()> { - for effect in effects { + let mut pending = VecDeque::from(effects); + while let Some(effect) = pending.pop_front() { match effect { Effect::RunAiRequest(request) => { self.supervisor.run_ai_request(*request).await?; } Effect::ExecuteCommand(request) => { - self.supervisor.execute_command(request).await?; + if matches!(request.mode, ExecutionMode::Pty) { + self.start_pty_command(request)?; + } else { + self.supervisor.execute_command(request).await?; + } } Effect::CancelCommand(command_id) => { - self.supervisor.cancel_command(command_id).await?; + if self + .active_pty + .as_ref() + .is_some_and(|session| session.command_id() == command_id) + { + self.active_pty + .as_ref() + .expect("active pty should exist") + .cancel()?; + } else { + self.supervisor.cancel_command(command_id).await?; + } } Effect::RefreshProjectContext(path) => { self.supervisor.refresh_project(path); @@ -125,23 +174,180 @@ impl Runtime { Ok(()) } + fn start_pty_command(&mut self, request: crate::domain::ExecutionRequest) -> AppResult<()> { + self.terminal.begin_pty_session()?; + match shell::spawn_attached_pty_command(request, self.supervisor.events_tx()) { + Ok(session) => { + self.active_pty = Some(session); + Ok(()) + } + Err(error) => { + self.terminal.end_pty_session()?; + Err(error) + } + } + } + fn render(&mut self) -> AppResult<()> { self.terminal .draw(|frame| render(frame, self.store.state()))?; Ok(()) } - fn handle_terminal_event(&mut self, event: Event) -> Vec { + fn process_app_event(&mut self, event: AppEvent) -> AppResult> { + let should_finish = self + .active_pty + .as_ref() + .is_some_and(|session| matches!( + event, + AppEvent::CommandExited { command_id, .. } | AppEvent::CommandCancelled { command_id, .. } + if command_id == session.command_id() + )); + + let effects = self.store.dispatch_event(event); + if should_finish { + self.finish_pty_session()?; + } + Ok(effects) + } + + fn handle_terminal_event(&mut self, event: Event) -> AppResult> { + if self.pty_active() { + self.handle_pty_terminal_event(event)?; + return Ok(Vec::new()); + } + let action = match event { Event::Key(key) => map_key_event(key, self.store.state()), Event::Resize(width, height) => Some(AppAction::Ui(UiIntent::Resize(width, height))), _ => None, }; - action + Ok(action .map(|action| self.store.dispatch_action(action)) - .unwrap_or_default() + .unwrap_or_default()) + } + + fn handle_pty_terminal_event(&mut self, event: Event) -> AppResult<()> { + let Some(session) = self.active_pty.as_ref() else { + return Ok(()); + }; + + match event { + Event::Key(key) => { + if !matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) { + return Ok(()); + } + + if matches!(key.code, KeyCode::Char('c')) + && key.modifiers.contains(KeyModifiers::CONTROL) + { + session.interrupt()?; + return Ok(()); + } + + if let Some(bytes) = encode_pty_key(key) { + session.send_input(bytes)?; + } + } + Event::Resize(width, height) => { + session.resize(width, height)?; + } + _ => {} + } + Ok(()) + } + + fn finish_pty_session(&mut self) -> AppResult<()> { + if self.active_pty.take().is_some() { + self.terminal.end_pty_session()?; + } + Ok(()) + } + + async fn shutdown_active_pty(&mut self) -> AppResult<()> { + if let Some(session) = self.active_pty.as_ref() { + session.cancel()?; + } else { + return Ok(()); + } + + let timeout = tokio::time::sleep(Duration::from_secs(2)); + tokio::pin!(timeout); + loop { + if !self.pty_active() { + return Ok(()); + } + + tokio::select! { + _ = &mut timeout => { + return Err(InfraError::Pty { + phase: PtyPhase::Shutdown, + message: "timed out waiting for PTY session shutdown".to_string(), + } + .into()); + } + maybe_event = self.events_rx.recv() => { + if let Some(event) = maybe_event { + let effects = self.process_app_event(event)?; + self.apply_effects(effects).await?; + } + } + } + } + } + + fn pty_active(&self) -> bool { + self.active_pty.is_some() + } +} + +fn encode_pty_key(key: KeyEvent) -> Option> { + match key.code { + KeyCode::Char(c) => { + if key.modifiers.contains(KeyModifiers::CONTROL) { + return control_char_bytes(c); + } + + let mut bytes = Vec::new(); + if key.modifiers.contains(KeyModifiers::ALT) { + bytes.push(0x1b); + } + let mut encoded = [0_u8; 4]; + let slice = c.encode_utf8(&mut encoded); + bytes.extend_from_slice(slice.as_bytes()); + Some(bytes) + } + KeyCode::Enter => Some(vec![b'\r']), + KeyCode::Tab => Some(vec![b'\t']), + KeyCode::Backspace => Some(vec![0x7f]), + KeyCode::Esc => Some(vec![0x1b]), + KeyCode::Left => Some(b"\x1b[D".to_vec()), + KeyCode::Right => Some(b"\x1b[C".to_vec()), + KeyCode::Up => Some(b"\x1b[A".to_vec()), + KeyCode::Down => Some(b"\x1b[B".to_vec()), + KeyCode::Home => Some(b"\x1b[H".to_vec()), + KeyCode::End => Some(b"\x1b[F".to_vec()), + KeyCode::Delete => Some(b"\x1b[3~".to_vec()), + KeyCode::PageUp => Some(b"\x1b[5~".to_vec()), + KeyCode::PageDown => Some(b"\x1b[6~".to_vec()), + _ => None, + } +} + +fn control_char_bytes(c: char) -> Option> { + if !c.is_ascii() { + return None; + } + + let upper = c.to_ascii_uppercase(); + if upper == ' ' { + return Some(vec![0x00]); + } + if ('@'..='_').contains(&upper) { + return Some(vec![(upper as u8) - b'@']); } + None } fn map_key_event(key: KeyEvent, state: &crate::domain::AppState) -> Option { diff --git a/src/runtime/supervisor.rs b/src/runtime/supervisor.rs index 941f026..f8c6ac1 100644 --- a/src/runtime/supervisor.rs +++ b/src/runtime/supervisor.rs @@ -1,21 +1,22 @@ use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; +use std::time::{Duration, Instant}; -use tokio::sync::{mpsc, oneshot, Mutex}; +use tokio::sync::{mpsc, Mutex}; use crate::ai::AiRuntime; use crate::app::AppEvent; use crate::domain::{AiRequest, ExecutionRequest}; use crate::infra::{git, project, shell}; -use crate::shared::error::AppResult; +use crate::shared::error::{AppResult, InfraError}; use crate::shared::ids::CommandId; #[derive(Clone)] pub struct RuntimeSupervisor { events_tx: mpsc::Sender, ai_runtime: AiRuntime, - cancellations: Arc>>>, + cancellations: shell::CancellationRegistry, } impl RuntimeSupervisor { @@ -69,12 +70,37 @@ impl RuntimeSupervisor { pub async fn cancel_command(&self, command_id: CommandId) -> AppResult<()> { let mut registry = self.cancellations.lock().await; - if let Some(cancel_tx) = registry.remove(&command_id) { + if let Some(cancel_tx) = registry.get_mut(&command_id).and_then(Option::take) { let _ = cancel_tx.send(()); } Ok(()) } + pub async fn shutdown_commands(&self, timeout: Duration) -> AppResult<()> { + { + let mut registry = self.cancellations.lock().await; + for cancel_tx in registry.values_mut().filter_map(Option::take) { + let _ = cancel_tx.send(()); + } + } + + let deadline = Instant::now() + timeout; + loop { + if self.cancellations.lock().await.is_empty() { + return Ok(()); + } + + if Instant::now() >= deadline { + return Err(InfraError::Runtime( + "timed out waiting for managed commands to shut down".to_string(), + ) + .into()); + } + + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + pub fn refresh_project(&self, start_dir: PathBuf) { let events_tx = self.events_tx.clone(); tokio::spawn(async move { diff --git a/src/shared/error.rs b/src/shared/error.rs index 35834b6..d0f040d 100644 --- a/src/shared/error.rs +++ b/src/shared/error.rs @@ -15,6 +15,8 @@ pub enum AppError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] + Json(#[from] serde_json::Error), + #[error(transparent)] TomlDe(#[from] toml::de::Error), #[error(transparent)] Join(#[from] tokio::task::JoinError), @@ -68,12 +70,28 @@ pub enum InfraError { Project { path: PathBuf, message: String }, #[error("ai provider `{provider}` failed: {message}")] Ai { provider: String, message: String }, + #[error("pty {phase} failed: {message}")] + Pty { phase: PtyPhase, message: String }, #[error("terminal failure: {0}")] Terminal(String), #[error("runtime failure: {0}")] Runtime(String), } +#[derive(Debug, Clone, Copy, Error)] +pub enum PtyPhase { + #[error("setup")] + Setup, + #[error("read")] + Read, + #[error("write")] + Write, + #[error("resize")] + Resize, + #[error("shutdown")] + Shutdown, +} + impl AppError { pub fn message(message: impl Into) -> Self { Self::Message(message.into()) diff --git a/src/shared/ids.rs b/src/shared/ids.rs index fd0e97c..c7a09cb 100644 --- a/src/shared/ids.rs +++ b/src/shared/ids.rs @@ -42,8 +42,12 @@ pub struct IdGenerator { impl IdGenerator { pub fn new() -> Self { + Self::starting_at(1) + } + + pub fn starting_at(next: u64) -> Self { Self { - next: AtomicU64::new(1), + next: AtomicU64::new(next.max(1)), } } diff --git a/src/ui/terminal.rs b/src/ui/terminal.rs index e160f2a..0969a01 100644 --- a/src/ui/terminal.rs +++ b/src/ui/terminal.rs @@ -1,8 +1,8 @@ -use std::io::{self, Stdout}; +use std::io::{self, Stdout, Write}; use crossterm::execute; use crossterm::terminal::{ - disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen, + disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen, }; use ratatui::backend::CrosstermBackend; use ratatui::Terminal; @@ -37,6 +37,23 @@ impl TerminalUi { self.terminal.show_cursor()?; Ok(()) } + + pub fn begin_pty_session(&mut self) -> AppResult<()> { + self.terminal.show_cursor()?; + let mut stdout = io::stdout(); + execute!( + stdout, + Clear(ClearType::All), + crossterm::cursor::MoveTo(0, 0) + )?; + stdout.flush()?; + Ok(()) + } + + pub fn end_pty_session(&mut self) -> AppResult<()> { + self.terminal.hide_cursor()?; + Ok(()) + } } impl Drop for TerminalUi { diff --git a/src/ui/views/modal.rs b/src/ui/views/modal.rs index ec6c69c..7ab70c5 100644 --- a/src/ui/views/modal.rs +++ b/src/ui/views/modal.rs @@ -95,8 +95,14 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { Line::from("/apply run AI proposal n through safety checks"), Line::from("/bg run a background command"), Line::from("/cancel cancel a running command"), + Line::from("/history show recent shell command history"), + Line::from("/rerun replay command id through safety checks"), + Line::from("/rerun-last replay the latest shell history entry"), Line::from("/approve approve the current pending action"), Line::from("/deny deny the current pending action"), + Line::from("cd update Forge session cwd"), + Line::from("export K=V set a Forge session env value"), + Line::from("unset K remove a Forge session env value"), Line::from("/tab next next dashboard tab"), Line::from("/tab prev previous dashboard tab"), Line::from("/clear clear input and visible logs"), @@ -129,6 +135,69 @@ pub fn render(frame: &mut Frame<'_>, state: &AppState) { area, ); } + ModalState::History => { + let mut lines = vec![ + Line::from(Span::styled( + "Command History", + Style::default() + .fg(theme::ACCENT) + .add_modifier(Modifier::BOLD), + )), + Line::raw(""), + ]; + + if state.commands.history.is_empty() { + lines.push(Line::from("No shell history recorded yet.")); + } else { + lines.push(Line::from(vec![ + Span::styled("id", theme::subtle()), + Span::raw(" "), + Span::styled("status", theme::subtle()), + Span::raw(" "), + Span::styled("cwd", theme::subtle()), + Span::raw(" "), + Span::styled("command", theme::subtle()), + ])); + lines.push(Line::raw("")); + + for entry in state.commands.history.iter().rev().take(12) { + let id = entry + .command_id + .map(|id| id.to_string()) + .unwrap_or_else(|| "-".to_string()); + let status = status_label(entry.status); + lines.push(Line::from(vec![ + Span::styled(format!("{id:<4}"), theme::accent()), + Span::styled(format!("{status:<10}"), theme::muted()), + Span::styled( + format!("{:<18}", truncate_path(&entry.cwd, 18)), + theme::subtle(), + ), + Span::styled(truncate(&entry.raw, 72), theme::primary()), + ])); + } + + lines.push(Line::raw("")); + lines.push(Line::from( + "/rerun replays a command with approval checks.", + )); + lines.push(Line::from("/rerun-last replays the newest history entry.")); + } + + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Left) + .wrap(Wrap { trim: false }) + .block( + Block::default() + .title("History") + .borders(Borders::ALL) + .border_style(theme::pane_border(true)) + .style(theme::panel_surface(true)), + ), + area, + ); + } ModalState::Error(message) => { frame.render_widget( Paragraph::new(message.clone()) @@ -156,6 +225,35 @@ fn provenance_label(provenance: CommandProvenance) -> &'static str { } } +fn status_label(status: crate::domain::CommandStatus) -> &'static str { + use crate::domain::CommandStatus::*; + match status { + PendingReview => "review", + PendingApproval => "pending", + Queued => "queued", + Running => "running", + Succeeded => "done", + Failed => "failed", + Cancelled => "cancelled", + Denied => "denied", + } +} + +fn truncate(value: &str, max_chars: usize) -> String { + if value.chars().count() <= max_chars { + return value.to_string(); + } + let kept = value + .chars() + .take(max_chars.saturating_sub(1)) + .collect::(); + format!("{kept}…") +} + +fn truncate_path(path: &std::path::Path, max_chars: usize) -> String { + truncate(&path.display().to_string(), max_chars) +} + fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect { let popup_layout = Layout::default() .direction(Direction::Vertical) diff --git a/src/ui/views/status_bar.rs b/src/ui/views/status_bar.rs index a0744c0..e5dae26 100644 --- a/src/ui/views/status_bar.rs +++ b/src/ui/views/status_bar.rs @@ -21,8 +21,6 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { .unwrap_or_else(|| "------".to_string()); let dirty = if state.git.is_dirty { "dirty" } else { "clean" }; - let project = truncate_end(&state.project.name, 18); - let running = state .services .registry @@ -37,25 +35,6 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { }) .count(); - let branch_display = truncate_middle(&branch_leaf(&branch), 28); - let left = if project.eq_ignore_ascii_case("forge") { - vec![ - Span::raw(" "), - Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), - Span::styled(branch_display, theme::status_context()), - ] - } else { - vec![ - Span::raw(" "), - Span::styled("forge", theme::italic_serif()), - Span::styled(" / ", theme::subtle()), - Span::styled(project, theme::status_context()), - Span::styled(" / ", theme::subtle()), - Span::styled(branch_display, theme::status_context()), - ] - }; - let mut right: Vec> = Vec::new(); if running > 0 { right.push(Span::styled("●", theme::accent())); @@ -63,6 +42,11 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { right.push(Span::styled(format!("{running} running"), theme::primary())); right.push(Span::styled(" · ", theme::subtle())); } + right.push(Span::styled( + truncate_middle(&state.commands.session.cwd.display().to_string(), 28), + theme::subtle(), + )); + right.push(Span::styled(" · ", theme::subtle())); right.push(Span::styled( dirty, if state.git.is_dirty { @@ -97,6 +81,16 @@ pub fn render(frame: &mut Frame<'_>, area: Rect, state: &AppState) { width: text_area.width.saturating_sub(mid), height: 1, }; + let branch_display = truncate_middle( + &normalize_branch(&branch), + left_area.width.saturating_sub(14) as usize, + ); + let left = vec![ + Span::raw(" "), + Span::styled("forge", theme::italic_serif()), + Span::styled(" | ", theme::subtle()), + Span::styled(branch_display, theme::status_context()), + ]; frame.render_widget( Paragraph::new(Line::from(left)).style(theme::chrome_surface()), @@ -155,11 +149,6 @@ fn truncate_middle(value: &str, max_chars: usize) -> String { format!("{start}…{end}") } -fn branch_leaf(branch: &str) -> String { - branch - .rsplit('/') - .next() - .filter(|value| !value.is_empty()) - .unwrap_or(branch) - .to_string() +fn normalize_branch(branch: &str) -> String { + branch.replace('\\', "/") } diff --git a/tests/foundation.rs b/tests/foundation.rs index 797d918..dccd77c 100644 --- a/tests/foundation.rs +++ b/tests/foundation.rs @@ -3,13 +3,14 @@ use std::time::SystemTime; use ratatui::{backend::TestBackend, style::Modifier, Terminal}; -use forge::app::{AppAction, AppStore, Effect}; +use forge::app::{AppAction, AppEvent, AppStore, Effect}; use forge::commands::{parse_input, slash_command_suggestions, ParsedInput}; use forge::config::ForgeConfig; use forge::domain::{ - AiActionProposal, AiRequestKind, AiResponse, AppState, ApprovalMode, CommandProvenance, - CommandStatus, DashboardTab, FocusTarget, GitSnapshot, InputMode, LogEntry, LogSeverity, - LogSource, LogStream, ModalState, ProjectContext, SafetyClass, + AiActionProposal, AiRequestKind, AiResponse, AppState, ApprovalMode, CommandHistoryEntry, + CommandProvenance, CommandStatus, DashboardTab, DiagnosticLevel, ExecutionMode, FocusTarget, + GitSnapshot, InputMode, LogEntry, LogSeverity, LogSource, LogStream, ModalState, + ProjectContext, SafetyClass, ShellSessionState, }; use forge::safety::classify_command; use forge::shared::ids::{AiRequestId, CommandId, LogId}; @@ -32,10 +33,61 @@ fn parses_background_shell_execution() { } } +#[test] +fn parses_plain_clear_as_forge_builtin() { + assert!(matches!(parse_input("clear").unwrap(), ParsedInput::Clear)); +} + +#[test] +fn parses_cd_as_forge_builtin() { + match parse_input("cd src").expect("cd should parse as a builtin") { + ParsedInput::ChangeDirectory { target } => { + assert_eq!(target.as_deref(), Some("src")); + } + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("cd \"path with spaces\"").expect("quoted cd target should parse") { + ParsedInput::ChangeDirectory { target } => { + assert_eq!(target.as_deref(), Some("path with spaces")); + } + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("cd src && pwd").expect("compound shell command should remain shell input") { + ParsedInput::Execute { command, .. } => assert_eq!(command, "cd src && pwd"), + other => panic!("unexpected parse result: {:?}", other), + } +} + +#[test] +fn parses_session_env_builtins() { + match parse_input("export FORGE_MODE=local").expect("export should parse as a session builtin") + { + ParsedInput::SetEnv { key, value } => { + assert_eq!(key, "FORGE_MODE"); + assert_eq!(value, "local"); + } + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("unset FORGE_MODE").expect("unset should parse as a session builtin") { + ParsedInput::UnsetEnv { key } => assert_eq!(key, "FORGE_MODE"), + other => panic!("unexpected parse result: {:?}", other), + } + + match parse_input("export 1BAD=value").expect("invalid export should remain shell input") { + ParsedInput::Execute { command, .. } => assert_eq!(command, "export 1BAD=value"), + other => panic!("unexpected parse result: {:?}", other), + } +} + #[test] fn parses_supported_slash_commands() { assert!(matches!(parse_input("/quit").unwrap(), ParsedInput::Quit)); assert!(matches!(parse_input("/exit").unwrap(), ParsedInput::Quit)); + assert!(matches!(parse_input("exit").unwrap(), ParsedInput::Quit)); + assert!(matches!(parse_input("quit").unwrap(), ParsedInput::Quit)); assert!(matches!(parse_input("/clear").unwrap(), ParsedInput::Clear)); assert!(matches!( parse_input("/tab next").unwrap(), @@ -61,6 +113,18 @@ fn parses_supported_slash_commands() { parse_input("/deny").unwrap(), ParsedInput::DenyPending )); + assert!(matches!( + parse_input("/history").unwrap(), + ParsedInput::History + )); + assert!(matches!( + parse_input("/rerun-last").unwrap(), + ParsedInput::RerunLast + )); + assert!(matches!( + parse_input("/rerun 12").unwrap(), + ParsedInput::Rerun(CommandId(12)) + )); match parse_input("/bg cargo run").unwrap() { ParsedInput::Execute { @@ -157,6 +221,26 @@ fn store_executes_passive_shell_command_immediately() { .expect("command record should exist"); assert_eq!(command.raw, "pwd"); assert!(matches!(command.status, CommandStatus::Queued)); + assert!(matches!( + effects.as_slice(), + [Effect::ExecuteCommand(request)] if matches!(request.mode, ExecutionMode::Managed) + )); +} + +#[test] +fn store_routes_interactive_foreground_commands_to_pty() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "top".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + assert!(matches!( + effects.as_slice(), + [Effect::ExecuteCommand(request)] if matches!(request.mode, ExecutionMode::Pty) + )); } #[test] @@ -311,6 +395,269 @@ fn store_clear_resets_input_and_visible_logs() { assert!(store.state().logs.recent.is_empty()); } +#[test] +fn store_cd_changes_session_cwd_without_command_record() { + let mut store = test_store(); + let expected = std::env::current_dir() + .expect("current dir should exist") + .join("src") + .canonicalize() + .expect("src dir should exist"); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::ChangeDirectory { + target: Some("src".to_string()), + })); + + assert!(effects.is_empty()); + assert_eq!(store.state().commands.session.cwd, expected); + assert_eq!(store.state().commands.session.last_exit_status, Some(0)); + let history = store.state().commands.history.last().unwrap(); + assert_eq!(history.raw, "cd src"); + assert_eq!(history.status, CommandStatus::Succeeded); + assert_eq!(history.exit_code, Some(0)); + assert!(store.state().commands.records.is_empty()); + assert!(store.state().jobs.records.is_empty()); +} + +#[test] +fn store_failed_cd_surfaces_diagnostic_without_changing_cwd() { + let mut store = test_store(); + let before = store.state().commands.session.cwd.clone(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::ChangeDirectory { + target: Some("does-not-exist-for-forge-session".to_string()), + })); + + assert!(effects.is_empty()); + assert_eq!(store.state().commands.session.cwd, before); + assert_eq!(store.state().commands.session.last_exit_status, Some(1)); + assert!(store.state().commands.records.is_empty()); + let diagnostic = store + .state() + .diagnostics + .records + .iter() + .last() + .expect("failed cd should record a diagnostic"); + assert!(matches!(diagnostic.level, DiagnosticLevel::Warn)); + assert!(diagnostic.message.contains("cd:")); +} + +#[test] +fn store_executes_commands_from_session_cwd() { + let mut store = test_store(); + store.dispatch_action(AppAction::ParsedInput(ParsedInput::ChangeDirectory { + target: Some("src".to_string()), + })); + let expected_cwd = store.state().commands.session.cwd.clone(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "pwd".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + match effects.as_slice() { + [Effect::ExecuteCommand(request)] => { + assert_eq!(request.cwd, expected_cwd); + assert_eq!(request.shell, store.state().commands.session.shell); + } + other => panic!("unexpected effects: {:?}", other), + } +} + +#[test] +fn store_executes_commands_with_session_env_overlay() { + let mut store = test_store(); + let set_effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::SetEnv { + key: "FORGE_MODE".to_string(), + value: "local".to_string(), + })); + assert!(set_effects.is_empty()); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "echo $FORGE_MODE".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + match effects.as_slice() { + [Effect::ExecuteCommand(request)] => { + assert_eq!( + request.env.get("FORGE_MODE").map(String::as_str), + Some("local") + ); + } + other => panic!("unexpected effects: {:?}", other), + } + + let unset_effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::UnsetEnv { + key: "FORGE_MODE".to_string(), + })); + assert!(unset_effects.is_empty()); + assert!(!store + .state() + .commands + .session + .env + .contains_key("FORGE_MODE")); + assert_eq!(store.state().commands.session.last_exit_status, Some(0)); +} + +#[test] +fn store_history_command_opens_modal() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::History)); + + assert!(effects.is_empty()); + assert!(matches!(store.state().ui.modal, Some(ModalState::History))); + assert!(matches!(store.state().ui.focus, FocusTarget::Modal)); +} + +#[test] +fn command_history_preserves_execution_metadata() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "pwd".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + assert!(matches!(effects.as_slice(), [Effect::ExecuteCommand(_)])); + let command = store.state().commands.records.last().unwrap(); + let history = store.state().commands.history.last().unwrap(); + assert_eq!(history.command_id, Some(command.id)); + assert_eq!(history.raw, "pwd"); + assert_eq!(history.cwd, command.cwd); + assert_eq!(history.shell, store.state().commands.session.shell); + assert_eq!(history.provenance, CommandProvenance::UserInput); + assert_eq!(history.safety_class, SafetyClass::Passive); + assert_eq!(history.status, CommandStatus::Queued); +} + +#[test] +fn command_exit_updates_session_last_status() { + let mut store = test_store(); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "pwd".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + let [Effect::ExecuteCommand(request)] = effects.as_slice() else { + panic!("expected execute command effect: {:?}", effects); + }; + + store.dispatch_event(AppEvent::CommandExited { + command_id: request.command_id, + job_id: request.job_id, + service_id: request.service_id, + exit_code: 7, + }); + + assert_eq!(store.state().commands.session.last_exit_status, Some(7)); + let history = store.state().commands.history.last().unwrap(); + assert_eq!(history.status, CommandStatus::Failed); + assert_eq!(history.exit_code, Some(7)); +} + +#[test] +fn store_rerun_last_uses_recorded_cwd_and_safety_pipeline() { + let mut store = test_store(); + let replay_cwd = std::env::current_dir() + .expect("current dir should exist") + .join("src") + .canonicalize() + .expect("src dir should exist"); + store.state_mut().commands.history = vec![history_entry_with( + Some(CommandId(42)), + "pwd", + replay_cwd.clone(), + false, + SafetyClass::Passive, + )]; + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::RerunLast)); + + match effects.as_slice() { + [Effect::ExecuteCommand(request)] => { + assert_eq!(request.raw, "pwd"); + assert_eq!(request.cwd, replay_cwd); + assert!(matches!( + request.provenance, + CommandProvenance::SlashCommand + )); + } + other => panic!("unexpected effects: {:?}", other), + } +} + +#[test] +fn store_rerun_risky_command_requires_approval_again() { + let mut store = test_store(); + let replay_cwd = store.state().commands.session.cwd.clone(); + store.state_mut().commands.history = vec![history_entry_with( + Some(CommandId(42)), + "echo hi > /tmp/forge-test.txt", + replay_cwd.clone(), + false, + SafetyClass::Risky, + )]; + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Rerun(CommandId(42)))); + + assert!(matches!(effects.as_slice(), [Effect::QueueApproval(_)])); + let approval = store.state().approvals.pending.last().unwrap(); + assert_eq!(approval.execution.raw, "echo hi > /tmp/forge-test.txt"); + assert_eq!(approval.execution.cwd, replay_cwd); + assert!(matches!(approval.mode, ApprovalMode::ModalConfirm)); +} + +#[test] +fn restored_history_advances_new_command_ids() { + let mut state = AppState::new( + ForgeConfig::default(), + ProjectContext::default(), + GitSnapshot::default(), + ); + state.commands.history = vec![history_entry_with( + Some(CommandId(42)), + "pwd", + state.commands.session.cwd.clone(), + false, + SafetyClass::Passive, + )]; + let mut store = AppStore::new(state); + + let effects = store.dispatch_action(AppAction::ParsedInput(ParsedInput::Execute { + command: "pwd".to_string(), + background: false, + provenance: CommandProvenance::UserInput, + })); + + let [Effect::ExecuteCommand(request)] = effects.as_slice() else { + panic!("expected execute command effect: {:?}", effects); + }; + assert!(request.command_id.0 > 42); +} + +#[test] +fn ai_context_includes_shell_session_state() { + let mut store = test_store(); + store.dispatch_action(AppAction::ParsedInput(ParsedInput::ChangeDirectory { + target: Some("src".to_string()), + })); + + let context = forge::ai::build_context(store.state()); + + assert_eq!(context.session.cwd, store.state().commands.session.cwd); + assert_eq!(context.session.shell, store.state().commands.session.shell); + assert_eq!(context.session.last_exit_status, Some(0)); +} + #[test] fn store_submits_plain_prompt_in_ai_mode() { let mut store = test_store(); @@ -334,7 +681,7 @@ fn store_submits_plain_prompt_in_ai_mode() { #[test] fn store_recalls_shell_history() { let mut store = test_store(); - store.state_mut().commands.history = vec!["pwd".to_string(), "cargo test".to_string()]; + store.state_mut().commands.history = vec![history_entry("pwd"), history_entry("cargo test")]; store.dispatch_action(AppAction::Ui(forge::app::UiIntent::RecallPreviousHistory)); assert_eq!(store.state().ui.input.buffer, "cargo test"); @@ -419,8 +766,8 @@ fn ui_renders_prompt_first_wireframe_details() { let buffer = terminal.backend().buffer(); let rows = buffer_rows(buffer); assert!( - rows[1].contains("forge / foundation"), - "status identity should read like the uploaded wireframe" + rows[1].contains("forge | forge/foundation"), + "status identity should show the app name and full branch" ); assert!( rows[2].contains("────"), @@ -459,12 +806,104 @@ fn ui_renders_prompt_first_wireframe_details() { ); } +#[test] +fn command_history_persists_as_jsonl() { + let root = unique_temp_root(); + let entries = vec![history_entry("pwd")]; + + let path = forge::infra::state::save_command_history(&root, &entries) + .expect("history should save") + .expect("history path should be returned"); + let loaded = forge::infra::state::load_command_history(&root, 10).expect("history should load"); + + assert!(path.ends_with(".forge/state/command-history.jsonl")); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].raw, "pwd"); + assert_eq!(loaded[0].status, CommandStatus::Succeeded); + + let _ = std::fs::remove_dir_all(root); +} + +#[test] +fn shell_session_persists_as_toml() { + let root = unique_temp_root(); + let mut session = ShellSessionState::new( + std::env::current_dir().expect("current dir should exist"), + "/bin/zsh".to_string(), + ); + session.previous_cwd = Some(root.clone()); + session + .env + .insert("FORGE_MODE".to_string(), "local".to_string()); + session.last_exit_status = Some(7); + + let path = + forge::infra::state::save_shell_session(&root, &session).expect("session should save"); + let loaded = forge::infra::state::load_shell_session(&root) + .expect("session should load") + .expect("session should exist"); + + assert!(path.ends_with(".forge/state/session.toml")); + assert_eq!(loaded.cwd, session.cwd); + assert_eq!(loaded.previous_cwd, session.previous_cwd); + assert_eq!(loaded.shell, "/bin/zsh"); + assert_eq!( + loaded.env.get("FORGE_MODE").map(String::as_str), + Some("local") + ); + assert_eq!(loaded.last_exit_status, Some(7)); + + let _ = std::fs::remove_dir_all(root); +} + fn test_store() -> AppStore { let config = ForgeConfig::default(); let state = AppState::new(config, ProjectContext::default(), GitSnapshot::default()); AppStore::new(state) } +fn history_entry(raw: &str) -> CommandHistoryEntry { + history_entry_with( + None, + raw, + std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")), + false, + classify_command(raw), + ) +} + +fn history_entry_with( + command_id: Option, + raw: &str, + cwd: std::path::PathBuf, + background: bool, + safety_class: SafetyClass, +) -> CommandHistoryEntry { + let now = now_utc(); + CommandHistoryEntry { + command_id, + raw: raw.to_string(), + cwd, + shell: std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()), + provenance: CommandProvenance::UserInput, + background, + safety_class, + status: CommandStatus::Succeeded, + submitted_at: now, + started_at: Some(now), + ended_at: Some(now), + exit_code: Some(0), + } +} + +fn unique_temp_root() -> std::path::PathBuf { + let nanos = SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system time should be after epoch") + .as_nanos(); + std::env::temp_dir().join(format!("forge-history-test-{}-{nanos}", std::process::id())) +} + fn buffer_rows(buffer: &ratatui::buffer::Buffer) -> Vec { let area = *buffer.area(); (0..area.height)