From b39c4a1dfa77aedab164aa1aa4770424f86a5cfb Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 19:56:08 +0300 Subject: [PATCH 1/7] docs(adr): ADR-0055 named and concurrent sc ws sessions (ref #215) --- docs/adr/0030-agent-sessions-and-automerge.md | 6 +- docs/adr/0050-sessions-on-partial-clones.md | 2 +- docs/adr/0055-named-concurrent-ws-sessions.md | 71 +++++++++++++++++++ docs/adr/README.md | 3 +- 4 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 docs/adr/0055-named-concurrent-ws-sessions.md diff --git a/docs/adr/0030-agent-sessions-and-automerge.md b/docs/adr/0030-agent-sessions-and-automerge.md index fc01d694..ce38765a 100644 --- a/docs/adr/0030-agent-sessions-and-automerge.md +++ b/docs/adr/0030-agent-sessions-and-automerge.md @@ -1,6 +1,6 @@ # ADR-0030: Agent sessions and auto-merge of clean results -- **Status:** Accepted +- **Status:** Accepted; the one-session-per-repo rule is superseded by ADR-0055 (named and concurrent sessions) - **Date:** 2026-07-07 - **Phase:** 20 - **Builds on:** ADR-0023 (agent workspaces), ADR-0012 (three-way merge), ADR-0024 (oplog) @@ -16,7 +16,9 @@ mechanical toil the tool can absorb. ## Decision Durable sessions whose workspace state IS the checkout directory. One -unnamed session per repo: `sc ws fork --agents N` materializes N +unnamed session per repo (ADR-0055 later added named sessions beside it, +each in its own `.sc/ws-/` root; the unnamed session described here is +unchanged): `sc ws fork --agents N` materializes N checkouts from the current tip into `.sc/ws//` (P7-aware) and writes an atomic manifest (`.sc/ws/session.toml`: base snapshot, base branch, dirs; never key material). Agents work in the dirs directly across diff --git a/docs/adr/0050-sessions-on-partial-clones.md b/docs/adr/0050-sessions-on-partial-clones.md index 37086d29..5b649bfd 100644 --- a/docs/adr/0050-sessions-on-partial-clones.md +++ b/docs/adr/0050-sessions-on-partial-clones.md @@ -24,7 +24,7 @@ ADR-0049 left sessions "undecided" as a product question. The question was wheth 4. **Landing uses the ADR-0049 engine.** `ws_harvest` lands a clean workspace with `merge_with_identity`, which on a partial clone is the tree-recursive merge. The probe that decides "lands cleanly or falls back to `work-`" is the same question answered by `tree_merge_filled` (`would_merge_cleanly_partial`): any conflict, inside the view or not, is "not clean", and the workspace becomes a `work-` branch exactly as on a full clone. A conflict outside the view cannot arise from a workspace edit, which holds only the view, but it can arise from the host moving on; it falls back like any other. -5. **Nothing else changes.** The one-session-per-repo rule, the landing-branch rule, `ws run`/`list`/`abandon`, scanner gating, protected-path carry and the oplog are unchanged. A `sc work` session still leaves no residue. +5. **Nothing else changes.** The landing-branch rule (the one-session-per-repo rule was relaxed by ADR-0055, which keeps this ADR's view rules per session), `ws run`/`list`/`abandon`, scanner gating, protected-path carry and the oplog are unchanged. A `sc work` session still leaves no residue. ## Consequences diff --git a/docs/adr/0055-named-concurrent-ws-sessions.md b/docs/adr/0055-named-concurrent-ws-sessions.md new file mode 100644 index 00000000..28993e20 --- /dev/null +++ b/docs/adr/0055-named-concurrent-ws-sessions.md @@ -0,0 +1,71 @@ +# ADR-0055: Named and concurrent `sc ws` sessions (P20, #215) + +- **Status:** Accepted (built, except workspace refresh, which is designed here and deferred) +- **Date:** 2026-10-20 +- **Phase:** 20 (follow-on) +- **Builds on:** ADR-0030 (agent sessions), ADR-0050 (sessions on partial clones), ADR-0023 (agent workspaces), ADR-0043 (per-checkout protected cache) + +## Context + +ADR-0030 allows one unnamed session per repo: `sc ws fork` writes `.sc/ws/session.toml` and `.sc/ws//`, and refuses while a manifest exists. Two agent teams working on the same repo cannot each hold a session, and issue #215 asks for named, concurrently open sessions and a way to move a workspace onto a newer tip. + +Reading the code turned up one fact that shapes the design. `Repo::open` takes the single-writer lock (`.sc/lock`) for the life of the process, and `sc ws run` spawned the agent command while its `Repo` was still open. While an agent ran in one workspace, every other `sc` command on the repo (`list`, `harvest`, `abandon`, another `run`) failed with `Locked`. Two sessions could exist on disk but not be used at the same time. + +## Decisions + +1. **Named sessions are additive.** `sc ws fork --name ` opens a session called ``. Omitting `--name` addresses the unnamed session exactly as before. A name takes the branch-name grammar (`validate_branch_name`): it becomes a directory under `.sc/` and the prefix of the session's fallback branches. A name that is already open is refused with the existing "already open" message plus the name and the `abandon --session` command to run. Forking the unnamed session while only named ones are open is allowed, and the reverse too. + +2. **Addressing.** A session is picked with `--session ` on `list`, `run`, `harvest` and `abandon`; a workspace inside it stays addressed by its index (`run `, `abandon []`). With no `--session` the command means the unnamed session. It never guesses a named one: if only named sessions are open, the error lists them and says to pass `--session`. `sc ws list` with no flag prints every open session (the unnamed one first, then named ones sorted by name); the unnamed session's header line is unchanged. + +3. **On-disk layout: no migration.** The unnamed session keeps `.sc/ws/session.toml`, `.sc/ws//` and `.sc/ws/cache-`, byte for byte. A named session lives in a sibling root, `.sc/ws-/`, with the same inner shape. A sibling and not a child, so every teardown (`remove_dir_all` of a session root on abandon, harvest end and fork-residue cleanup) touches only its own session, and no reserved names are needed inside a root. The manifest format is unchanged; the session name is derived from the directory and never stored. A `.sc/ws-*` directory without a manifest is crash residue and is ignored. + - Downgrade hazard: a binary from before this change does not look at `.sc/ws-*`, so its `sc gc` would not root a named session's base snapshot. Do not run an old `sc` against a repo with named sessions open. + +4. **Fallback branches and labels follow the name.** The unnamed session still falls back to `work-`. A named session falls back to `-`, and `SC_WORKSPACE` is the same string, matching `sc work --name` and the ADR-0030 rule that the label equals the branch name. The existing collision suffix (`-2`, `-3`) still applies, so a clash across sessions (for example a session named `work`) cannot overwrite a branch. The candidate commit message is `ws- harvest` (unnamed) or `ws - harvest`. + +5. **Concurrency: serialized by the repo lock, with the lock released while an agent runs.** + - Fork, harvest and abandon run under the repo lock for the whole command. Two harvests therefore never overlap; the second `sc` process gets `Locked` and nothing has changed. Each harvest builds its candidate from its own session's fork-time base and probes it against the landing tip as it is then, so the existing logic already covers "the branch moved on since fork". No new merge code. + - **Outcome rule.** Within a session, workspaces land in ascending index order (ADR-0030). Across sessions, the order is the order the harvests are invoked: the first lands, a later one merges cleanly over it or, when its change conflicts, falls back to its own `-` branch and leaves the landing branch untouched. Disjoint edits land to the same tree in either order; overlapping edits go to whoever harvests first. There is no implicit ordering and no `harvest --all`; a script that wants a fixed order calls `harvest --session` in that order. + - Each session has its own manifest, so no manifest is shared between sessions. Abandoning or harvesting one session never writes another's files. + - **`sc ws run` no longer holds the lock while the command runs.** `Repo::ws_run_plan` resolves the live workspace, its label and (with `--with-secrets`) the decrypted environment under the lock; the CLI drops the repo and then spawns the command (`WsRunPlan::run`). Other sessions can be listed, harvested or abandoned meanwhile. `Repo::ws_run` stays as the two steps together for library callers. + - Abandoning a workspace under a running agent removes its directory; the agent sees its files vanish. That is the caller's choice, as it was before. + +6. **Protected caches.** `Layout::ws_cache_path(session, i)` is `/cache-`, beside the checkout like before, so each session's stat caches live and die with that session. Nothing else about ADR-0043 changes: the cache is never committed or transferred, and a lost cache costs a re-seal, not correctness. + +7. **Sparse view and partial clones.** Each session records the host's sparse spec in its own manifest at fork, and harvest diffs and commits against that recorded view (ADR-0030's fork-time rule, per session). ADR-0050 holds per session: fork fills the view or refuses with the gap error before anything is written, a harvest grafts out-of-view subtrees from its base, and landing uses the ADR-0049 merge. Two sessions forked under different host views each keep their own. + +8. **gc.** Every open session's base snapshot is a gc root (`list_sessions`), not only the unnamed one. + +9. **`sc work` is unchanged.** It uses temporary directories and never touches `.sc/ws*`. + +## Workspace refresh (designed, not built) + +`sc ws refresh ` would move a session onto the landing branch's newer tip while keeping the agents' work. The smaller design, recommended for a follow-up: + +- For each live workspace, commit its checkout to a temporary candidate with the same pipeline harvest uses (scanner gate, protected re-encryption), so a scanner rejection refuses the refresh. +- Replay that candidate onto the new tip with the ADR-0049 tree engine (`tree_merge_filled`), in memory. Any conflict, in the view or not, refuses the whole refresh with the conflicting paths, and the session is untouched. +- Only when every workspace replays cleanly: re-materialize each checkout from its replayed tree under the session's recorded view, rewrite the manifest base to the new tip, then drop the temporary candidates. Order the manifest write after the checkouts, and keep the old checkouts until the new ones are complete, so a crash leaves either the old or the new state. + +It is deferred, not rejected, for these reasons: + +- The merge path is head-centric (ADR-0030, as-shipped note), so refresh needs a headless "merge a candidate into a tree" entry point plus "re-materialize a checkout from a tree while keeping unrelated files". Neither exists, and the second one rewrites files an agent may have open. +- Harvest already integrates work forked from an older base by three-way merge, so a stale base costs a possible fallback branch, not data. Abandon and re-fork covers the need to see newer code. +- The acceptance criteria for this issue (independent sessions, deterministic outcomes) do not depend on it, and refresh deserves its own crash-safety tests. + +## Consequences + +- Several named sessions can be open at once and used in parallel, including while an agent command runs, with deterministic first-harvest-wins outcomes. +- Existing repos and scripts keep working untouched: the unnamed layout, command lines, output, `work-` names and manifests are the same. +- A harvest that finds the landing branch moved by another session's landing takes the ordinary merge path; conflicts end up as `-` branches for manual `sc merge`. +- Not built: refresh, `harvest --all`, and a per-entry record of the branch a workspace landed on (the existing `sc ws list` caveat about `--into` stands). + +## Alternatives considered + +- **Nest named sessions under `.sc/ws//`:** every `remove_dir_all(.sc/ws)` would take other sessions with it, and names would need reserving against `session.toml`, `cache-*` and digits. Rejected for the sibling root. +- **One manifest holding several sessions, base per workspace:** a schema change that needs a migration path and makes every manifest write a shared read-modify-write. Rejected. +- **Pick the only named session when no `--session` is given:** convenient, but a script's meaning would change when a second session is opened. Rejected for an explicit error. +- **A second lock for harvest instead of the repo lock:** the repo lock already serializes every writer and is held across the whole harvest. Rejected as redundant. +- **Make the lock re-entrant or per-session:** a much larger change to a core invariant. Releasing it around the child process is enough. + +## Tests + +`ws.rs`: named and unnamed sessions coexist in separate roots with their own cache paths; collisions and invalid names are refused; addressing a missing session lists what is open and never guesses; the first of two conflicting harvests wins and the second falls back to `-1`, in both orders; disjoint sessions land to the same tree in either order; abandoning one session leaves another's checkout, edit and manifest intact and still runnable and harvestable; `SC_WORKSPACE` and fallback branches carry the name and are suffixed on a clash; gc roots every open base. `partial_sessions.rs`: two named sessions on a partial clone see only the view, land one after the other, and carry `docs/` unread. `crates/cli/tests/ws_sessions.rs`: the same through the binary, plus listing and harvesting another session from inside a running `sc ws run`. `demo/run_ws_demo.sh` gains a named-sessions section. diff --git a/docs/adr/README.md b/docs/adr/README.md index f3ba57be..7a9f8f4a 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -40,7 +40,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0027](0027-bulk-rewrap-and-multi-escrow.md) | Bulk re-wrap and multiple escrow keys | Accepted | 17 | | [0028](0028-network-git-remotes.md) | Network Git remotes (GitHub over https/ssh) | Accepted | 18 | | [0029](0029-history-editing-polish.md) | History-editing polish — amend, resumable rebase, pick abort, merge replay | Accepted | 19 | -| [0030](0030-agent-sessions-and-automerge.md) | Agent sessions and auto-merge of clean results | Accepted | 20 | +| [0030](0030-agent-sessions-and-automerge.md) | Agent sessions and auto-merge of clean results | Accepted; one-session rule superseded by 0055 | 20 | | [0031](0031-hardening-consolidation.md) | Hardening & consolidation sweep — closing the P16–P20 review tail | Accepted | 21 | | [0032](0032-signed-commits-provenance.md) | Signed commits & provenance | Accepted | 22 | | [0033](0033-merge-ergonomics.md) | Merge ergonomics — conflict UX beyond markers | Accepted | 23 | @@ -65,6 +65,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0052](0052-secret-injection-by-fd.md) | Secret injection by file descriptor (`sc run --secrets-fd`) | Accepted (built) | — | | [0053](0053-tls-pin-management.md) | TLS pin management (`sc tls`) | Accepted (built) | — | | [0054](0054-tls-ca-validation.md) | CA-path validation for `sc+https://` | Accepted (built) | — | +| [0055](0055-named-concurrent-ws-sessions.md) | Named and concurrent `sc ws` sessions | Accepted (built; refresh designed, deferred) | 20 | See [`ROADMAP.md`](../../ROADMAP.md) for the phase sequence. ADR numbers are assigned in creation order, so 0017 — the secret scanner — sequences as phase P5, From cfbb833c9f02fbdc0ada24309ada8f19c0012c96 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 19:56:09 +0300 Subject: [PATCH 2/7] feat(repo,cli): named and concurrent sc ws sessions; ws run releases the repo lock (ref #215) --- crates/cli/src/main.rs | 92 +++- crates/cli/tests/ws_sessions.rs | 152 ++++++ crates/repo/src/gc.rs | 2 +- crates/repo/src/layout.rs | 20 +- crates/repo/src/lib.rs | 2 +- crates/repo/src/partial_sessions.rs | 89 +++- crates/repo/src/ws.rs | 726 ++++++++++++++++++++++------ crates/repo/tests/exec_bit.rs | 4 +- demo/run_ws_demo.sh | 56 ++- 9 files changed, 955 insertions(+), 188 deletions(-) create mode 100644 crates/cli/tests/ws_sessions.rs diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 26269204..a141eeeb 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -726,8 +726,14 @@ enum EscrowOp { #[derive(Subcommand)] enum WsOp { - /// Fork N durable workspaces from HEAD under `.sc/ws//`. + /// Fork N durable workspaces from HEAD under `.sc/ws//` (or, with + /// `--name`, a separate named session under `.sc/ws-//`). Fork { + /// Name the session so several can be open at once; its fallback + /// branches and `SC_WORKSPACE` become `-`. Omit for the one + /// unnamed session (`work-`). + #[arg(long)] + name: Option, /// Number of workspaces to fork. #[arg(long, default_value_t = 2)] agents: u32, @@ -741,10 +747,20 @@ enum WsOp { #[arg(long)] author: Option, }, - /// List the open session's workspaces (changed/unchanged vs base). - List, + /// List the open sessions' workspaces (changed/unchanged vs base), or one + /// session's with `--session`. + List { + /// Session to address: the name given to `sc ws fork --name`. Omit + /// for the unnamed session. + #[arg(long)] + session: Option, + }, /// Run a command in one workspace checkout. Run { + /// Session to address: the name given to `sc ws fork --name`. Omit + /// for the unnamed session. + #[arg(long)] + session: Option, /// Workspace index to run in. index: u32, /// Decrypt and inject registered secrets into the command's environment @@ -760,6 +776,10 @@ enum WsOp { }, /// Abandon one workspace (by index) or the whole session. Abandon { + /// Session to address: the name given to `sc ws fork --name`. Omit + /// for the unnamed session. + #[arg(long)] + session: Option, /// Workspace index to abandon. Omit to abandon the whole session. index: Option, }, @@ -768,6 +788,10 @@ enum WsOp { /// branch). Conflicted/rejected workspaces fall back to a `work-` /// branch for manual resolution and keep the session open. Harvest { + /// Session to address: the name given to `sc ws fork --name`. Omit + /// for the unnamed session. + #[arg(long)] + session: Option, /// Landing branch; must be the currently-checked-out branch /// (default: the session's base branch). #[arg(long)] @@ -3406,12 +3430,18 @@ fn run_ws(op: WsOp) -> Result<()> { let repo = open_repo()?; match op { WsOp::Fork { + name, agents, identity, author, } => { let sk = resolve_identity_opt(identity)?; - let session = repo.ws_fork(agents, &resolve_author(author), sk.as_ref())?; + let session = repo.ws_fork( + name.as_deref(), + agents, + &resolve_author(author), + sk.as_ref(), + )?; println!( "forked {} workspace(s) from branch {} @ {}", session.workspaces.len(), @@ -3422,22 +3452,32 @@ fn run_ws(op: WsOp) -> Result<()> { println!(" {:<3} {}", entry.index, entry.dir.display()); } } - WsOp::List => match repo.ws_session()? { - None => println!("no workspace session open"), - Some(session) => { - println!( - "session base: branch {} @ {}", - session.base_branch, - session.base_snapshot.short() - ); + WsOp::List { session } => { + let sessions = match session { + None => repo.ws_sessions()?, + Some(n) => vec![repo + .ws_session(Some(&n))? + .ok_or_else(|| anyhow::anyhow!("no workspace session named '{n}' open"))?], + }; + if sessions.is_empty() { + println!("no workspace session open"); + } + for s in &sessions { + // The unnamed session keeps its historical header verbatim. + match &s.name { + None => print!("session base:"), + Some(n) => print!("session {n} base:"), + } + println!(" branch {} @ {}", s.base_branch, s.base_snapshot.short()); println!("index status dir"); - for entry in &session.workspaces { - let status = repo.ws_status_label(&session, entry)?; + for entry in &s.workspaces { + let status = repo.ws_status_label(s, entry)?; println!("{:<6} {:<28} {}", entry.index, status, entry.dir.display()); } } - }, + } WsOp::Run { + session, index, with_secrets, identity, @@ -3450,20 +3490,22 @@ fn run_ws(op: WsOp) -> Result<()> { } else { resolve_identity_opt(identity)? }; - let code = repo.ws_run(index, &cmd, with_secrets, sk.as_ref())?; - // Drop the repo before process::exit to ensure the RepoLock's Drop - // runs and releases .sc/lock (process::exit skips destructors). + let plan = repo.ws_run_plan(session.as_deref(), index, with_secrets, sk.as_ref())?; + // Release the repo lock before the (possibly long) command runs, so + // other sessions can be listed, harvested or abandoned meanwhile + // (ADR-0055); process::exit would skip the RepoLock's Drop anyway. drop(repo); - std::process::exit(code); + std::process::exit(plan.run(&cmd)?); } - WsOp::Abandon { index } => { - let remaining = repo.ws_abandon(index)?; + WsOp::Abandon { session, index } => { + let remaining = repo.ws_abandon(session.as_deref(), index)?; match index { Some(i) => println!("abandoned workspace {i}; {remaining} still live"), None => println!("abandoned the session ({remaining} workspace(s) remain)"), } } WsOp::Harvest { + session, into, identity, author, @@ -3471,8 +3513,12 @@ fn run_ws(op: WsOp) -> Result<()> { sign, } => { let sk = resolve_identity_opt(identity.clone())?; - let outcomes = - repo.ws_harvest(into.as_deref(), &resolve_author(author), sk.as_ref())?; + let outcomes = repo.ws_harvest( + session.as_deref(), + into.as_deref(), + &resolve_author(author), + sk.as_ref(), + )?; // ws_harvest has already moved the landing refs by this point — // print the per-workspace landing status FIRST, unconditionally, diff --git a/crates/cli/tests/ws_sessions.rs b/crates/cli/tests/ws_sessions.rs new file mode 100644 index 00000000..8b3f2698 --- /dev/null +++ b/crates/cli/tests/ws_sessions.rs @@ -0,0 +1,152 @@ +//! Named, concurrently open `sc ws` sessions through the real binary +//! (ADR-0055): addressing by `--session`, independent harvests with first-wins +//! ordering, and `sc ws run` not holding the repo lock while its command runs. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const SC: &str = env!("CARGO_BIN_EXE_sc"); + +fn sc(dir: &Path, args: &[&str]) -> Output { + Command::new(SC) + .args(args) + .current_dir(dir) + .env_remove("SC_AUTHOR") + .output() + .expect("sc runs") +} + +fn ok(dir: &Path, args: &[&str]) -> String { + let out = sc(dir, args); + assert!( + out.status.success(), + "sc {args:?} failed:\n{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).into_owned() +} + +/// The checkout dir of the single workspace `sc ws fork` printed. +fn forked_dir(fork_out: &str) -> PathBuf { + let line = fork_out.lines().nth(1).expect("one workspace line"); + PathBuf::from(line.split_whitespace().nth(1).expect("dir column")) +} + +fn setup(tag: &str) -> PathBuf { + let root = + std::env::temp_dir().join(format!("scl-cli-ws-sessions-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + ok(&root, &["init"]); + std::fs::write(root.join("shared.txt"), "base\n").unwrap(); + ok(&root, &["commit", "-m", "base", "--author", "t"]); + root +} + +#[test] +fn two_named_sessions_fork_list_run_and_harvest_independently() { + let root = setup("two"); + let a = forked_dir(&ok(&root, &["ws", "fork", "--agents", "1", "--name", "a"])); + let b = forked_dir(&ok(&root, &["ws", "fork", "--agents", "1", "--name", "b"])); + assert!(a.ends_with(".sc/ws-a/1") && b.ends_with(".sc/ws-b/1")); + + // A second session of the same name is refused; the first is untouched. + let dup = sc(&root, &["ws", "fork", "--name", "a"]); + assert!(!dup.status.success()); + assert!(String::from_utf8_lossy(&dup.stderr).contains("session 'a' is already open")); + + // `list` shows every session, or just the one asked for. + let list = ok(&root, &["ws", "list"]); + assert!( + list.contains("session a base:") && list.contains("session b base:"), + "{list}" + ); + let only_b = ok(&root, &["ws", "list", "--session", "b"]); + assert!( + only_b.contains("session b base:") && !only_b.contains("session a"), + "{only_b}" + ); + + // With no unnamed session, the default does not guess. + let guess = sc(&root, &["ws", "harvest"]); + assert!(!guess.status.success()); + let err = String::from_utf8_lossy(&guess.stderr); + assert!( + err.contains("open: a, b") && err.contains("--session"), + "{err}" + ); + + // Run labels the workspace with the session name. + let label = ok( + &root, + &[ + "ws", + "run", + "--session", + "a", + "1", + "--", + "sh", + "-c", + "printf %s \"$SC_WORKSPACE\"", + ], + ); + assert_eq!(label, "a-1"); + + // Both edit the same file: the first harvest wins, the second falls back. + std::fs::write(a.join("shared.txt"), "from a\n").unwrap(); + std::fs::write(b.join("shared.txt"), "from b\n").unwrap(); + let first = ok(&root, &["ws", "harvest", "--session", "b", "--author", "t"]); + assert!(first.contains("landed"), "{first}"); + let second = sc(&root, &["ws", "harvest", "--session", "a", "--author", "t"]); + assert_eq!(second.status.code(), Some(1)); + let second = String::from_utf8_lossy(&second.stdout); + assert!(second.contains("fallback: branch a-1"), "{second}"); + assert_eq!( + std::fs::read_to_string(root.join("shared.txt")).unwrap(), + "from b\n" + ); + + assert!(!root.join(".sc/ws-a").exists() && !root.join(".sc/ws-b").exists()); + assert!(ok(&root, &["ws", "list"]).contains("no workspace session open")); + std::fs::remove_dir_all(&root).unwrap(); +} + +/// While one session's command runs, the repo is free: another `sc` can list, +/// harvest or abandon the other session. (Before ADR-0055 the run held the +/// single-writer lock for the child's whole life and these failed with `Locked`.) +#[test] +fn a_running_session_does_not_block_the_others() { + let root = setup("run"); + ok(&root, &["ws", "fork", "--agents", "1", "--name", "a"]); + let b = forked_dir(&ok(&root, &["ws", "fork", "--agents", "1", "--name", "b"])); + std::fs::write(b.join("from-b.txt"), "b\n").unwrap(); + + let inside = |args: &[&str]| -> Vec { + ["ws", "run", "--session", "a", "1", "--", SC] + .iter() + .chain(args) + .map(|s| s.to_string()) + .collect() + }; + // The child is `sc` itself, run from inside a's workspace dir. + for args in [ + &["ws", "list", "--session", "b"][..], + &["ws", "harvest", "--session", "b", "--author", "t"][..], + ] { + let argv = inside(args); + let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); + let out = ok(&root, &argv); + assert!(!out.is_empty(), "{args:?}"); + } + assert!( + root.join("from-b.txt").exists(), + "b landed while a was running" + ); + + // Once its command has finished, a is abandoned like any session. + ok(&root, &["ws", "abandon", "--session", "a"]); + assert!(!root.join(".sc/ws-a").exists()); + std::fs::remove_dir_all(&root).unwrap(); +} diff --git a/crates/repo/src/gc.rs b/crates/repo/src/gc.rs index 93859881..41b7f5ba 100644 --- a/crates/repo/src/gc.rs +++ b/crates/repo/src/gc.rs @@ -72,7 +72,7 @@ fn roots(layout: &Layout) -> Result> { if let Some(st) = rebase_state::read(layout)? { set.insert(st.acc_tip); } - if let Some(s) = ws::read_manifest(layout)? { + for s in ws::list_sessions(layout)? { set.insert(s.base_snapshot); } for id in oplog::referenced_ids(layout)? { diff --git a/crates/repo/src/layout.rs b/crates/repo/src/layout.rs index 607a63f0..ed965ed0 100644 --- a/crates/repo/src/layout.rs +++ b/crates/repo/src/layout.rs @@ -150,10 +150,20 @@ impl Layout { self.dot_sc.join("protected-cache") } - /// `.sc/ws/cache-` — workspace `i`'s P33 stat cache. Lives BESIDE the - /// checkout dir (`.sc/ws//`), never inside it, so harvest's worktree - /// read can't pick it up as an untracked file. - pub fn ws_cache_path(&self, i: usize) -> PathBuf { - self.dot_sc.join("ws").join(format!("cache-{i}")) + /// A `sc ws` session's root: `.sc/ws` for the unnamed session (the + /// original layout, unchanged) or `.sc/ws-` for a named one (ADR-0055). + /// A sibling, not a child, so tearing one session down never touches another. + pub fn ws_root(&self, session: Option<&str>) -> PathBuf { + match session { + None => self.dot_sc.join("ws"), + Some(name) => self.dot_sc.join(format!("ws-{name}")), + } + } + + /// `/cache-` — workspace `i`'s P33 stat cache. Lives + /// BESIDE the checkout dir (`//`), never inside it, so + /// harvest's worktree read can't pick it up as an untracked file. + pub fn ws_cache_path(&self, session: Option<&str>, i: usize) -> PathBuf { + self.ws_root(session).join(format!("cache-{i}")) } } diff --git a/crates/repo/src/lib.rs b/crates/repo/src/lib.rs index 18c4202d..c3819dd3 100644 --- a/crates/repo/src/lib.rs +++ b/crates/repo/src/lib.rs @@ -84,4 +84,4 @@ pub use sparse::Sparse; pub use stdio_transport::{open_transport, SshUrl, StdioTransport}; pub use workspace::{HarvestResult, WorkOptions, WorkspaceOutcome}; pub use worktree::Diff; -pub use ws::{WsEntry, WsHarvestOutcome, WsSession}; +pub use ws::{WsEntry, WsHarvestOutcome, WsRunPlan, WsSession}; diff --git a/crates/repo/src/partial_sessions.rs b/crates/repo/src/partial_sessions.rs index a14e6832..0f0ac652 100644 --- a/crates/repo/src/partial_sessions.rs +++ b/crates/repo/src/partial_sessions.rs @@ -18,15 +18,15 @@ const SRC_LAST: &[u8] = b"one\ntwo\nTHREE\n"; fn fork_materializes_only_the_view() { let fx = Fx::origin("ws-view", |_| {}); let clone = fx.clone(false); - let session = clone.ws_fork(2, "t", None).unwrap(); + let session = clone.ws_fork(None, 2, "t", None).unwrap(); assert_eq!(session.workspaces.len(), 2); for ws in &session.workspaces { assert_eq!(std::fs::read(ws.dir.join("src/a.txt")).unwrap(), SRC_A); assert!(!ws.dir.join("docs").exists(), "docs is outside the view"); assert!(!ws.dir.join("lib").exists()); } - clone.ws_abandon(None).unwrap(); - assert!(clone.ws_session().unwrap().is_none()); + clone.ws_abandon(None, None).unwrap(); + assert!(clone.ws_session(None).unwrap().is_none()); drop(clone); fx.cleanup(); } @@ -41,14 +41,14 @@ fn harvest_lands_a_clean_merge_and_carries_the_out_of_view_subtrees() { .unwrap() .unwrap(); let docs = dir_id(&clone, &base, "docs"); - let session = clone.ws_fork(1, "t", None).unwrap(); + let session = clone.ws_fork(None, 1, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("src/a.txt"), SRC_FIRST).unwrap(); // The host moves on in the same file, on another line. std::fs::write(fx.clone_root.join("src/a.txt"), SRC_LAST).unwrap(); let host_tip = clone.commit("t", "host edit").unwrap(); - let outcomes = clone.ws_harvest(None, "t", None).unwrap(); + let outcomes = clone.ws_harvest(None, None, "t", None).unwrap(); let merged = match outcomes.as_slice() { [WsHarvestOutcome::Landed { merged_tip, .. }] => *merged_tip, other => panic!("expected a clean landing, got {other:?}"), @@ -63,7 +63,10 @@ fn harvest_lands_a_clean_merge_and_carries_the_out_of_view_subtrees() { assert_eq!(dir_id(&clone, &merged, "docs"), docs, "docs is unchanged"); assert!(!has(&clone, &docs), "and was never read or fetched"); assert!(!fx.clone_root.join("docs").exists()); - assert!(clone.ws_session().unwrap().is_none(), "the session ended"); + assert!( + clone.ws_session(None).unwrap().is_none(), + "the session ended" + ); drop(clone); fx.cleanup(); } @@ -74,12 +77,12 @@ fn harvest_lands_a_clean_merge_and_carries_the_out_of_view_subtrees() { fn harvest_conflict_falls_back_to_a_branch() { let fx = Fx::origin("ws-conflict", |_| {}); let clone = fx.clone(false); - let session = clone.ws_fork(1, "t", None).unwrap(); + let session = clone.ws_fork(None, 1, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("src/a.txt"), SRC_FIRST).unwrap(); std::fs::write(fx.clone_root.join("src/a.txt"), b"uno\ntwo\nthree\n").unwrap(); let host_tip = clone.commit("t", "host edit").unwrap(); - let outcomes = clone.ws_harvest(None, "t", None).unwrap(); + let outcomes = clone.ws_harvest(None, None, "t", None).unwrap(); match outcomes.as_slice() { [WsHarvestOutcome::FallbackBranch { branch, .. }] => { assert_eq!(branch, "work-1"); @@ -99,13 +102,67 @@ fn harvest_conflict_falls_back_to_a_branch() { fx.cleanup(); } +/// Two named sessions on one partial clone (ADR-0055): each is forked under the +/// host's view, they edit different lines of one file, and they land one after +/// the other. The second is a real merge over the first, and `docs/` is carried +/// by id the whole time, never read. +#[test] +fn two_named_sessions_land_independently_under_the_view() { + let fx = Fx::origin("ws-named", |_| {}); + let clone = fx.clone(false); + let base = refs::read_branch_tip(clone.layout(), "main") + .unwrap() + .unwrap(); + let docs = dir_id(&clone, &base, "docs"); + + let a = clone.ws_fork(Some("a"), 1, "t", None).unwrap(); + let b = clone.ws_fork(Some("b"), 1, "t", None).unwrap(); + for ws in a.workspaces.iter().chain(&b.workspaces) { + assert_eq!(std::fs::read(ws.dir.join("src/a.txt")).unwrap(), SRC_A); + assert!(!ws.dir.join("docs").exists(), "docs is outside the view"); + } + std::fs::write(a.workspaces[0].dir.join("src/a.txt"), SRC_FIRST).unwrap(); + std::fs::write(b.workspaces[0].dir.join("src/a.txt"), SRC_LAST).unwrap(); + + let first = match clone + .ws_harvest(Some("a"), None, "t", None) + .unwrap() + .as_slice() + { + [WsHarvestOutcome::Landed { merged_tip, .. }] => *merged_tip, + other => panic!("expected a landing, got {other:?}"), + }; + assert!( + clone.ws_session(Some("b")).unwrap().is_some(), + "b is still open" + ); + let merged = match clone + .ws_harvest(Some("b"), None, "t", None) + .unwrap() + .as_slice() + { + [WsHarvestOutcome::Landed { merged_tip, .. }] => *merged_tip, + other => panic!("expected a landing, got {other:?}"), + }; + assert_eq!(clone.snapshot(&merged).unwrap().parents[0], first); + assert_eq!( + std::fs::read(fx.clone_root.join("src/a.txt")).unwrap(), + b"ONE\ntwo\nTHREE\n" + ); + assert_eq!(dir_id(&clone, &merged, "docs"), docs, "docs is unchanged"); + assert!(!has(&clone, &docs), "and was never read or fetched"); + assert!(clone.ws_sessions().unwrap().is_empty()); + drop(clone); + fx.cleanup(); +} + /// An untouched workspace harvests as unchanged, with no branch minted. #[test] fn harvest_of_an_untouched_workspace_is_unchanged() { let fx = Fx::origin("ws-unchanged", |_| {}); let clone = fx.clone(false); - clone.ws_fork(1, "t", None).unwrap(); - let outcomes = clone.ws_harvest(None, "t", None).unwrap(); + clone.ws_fork(None, 1, "t", None).unwrap(); + let outcomes = clone.ws_harvest(None, None, "t", None).unwrap(); assert!(matches!( outcomes.as_slice(), [WsHarvestOutcome::Unchanged { .. }] @@ -192,12 +249,12 @@ fn fork_and_work_refuse_a_view_gap_before_writing_anything() { "premise: a gap" ); - let err = clone.ws_fork(1, "t", None).unwrap_err(); + let err = clone.ws_fork(None, 1, "t", None).unwrap_err(); assert!( matches!(err, crate::error::Error::GapInView { .. }), "got {err:?}" ); - assert!(clone.ws_session().unwrap().is_none()); + assert!(clone.ws_session(None).unwrap().is_none()); assert!(!clone.layout().dot_sc.join("ws").exists(), "no session dir"); let scratch = std::env::temp_dir().join(format!("scl-work-gap-{}", std::process::id())); @@ -223,7 +280,7 @@ fn a_failing_probe_leaves_no_candidate_branch() { let fx = crate::partial_merge::protected_origin("ws-probe", &pk); let b1 = fx.origin_branch("b1", &[("vault/s.txt", b"L1\nl2\nl3\n")]); let clone = fx.clone(false); - let session = clone.ws_fork(1, "t", None).unwrap(); + let session = clone.ws_fork(None, 1, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("src/a.txt"), SRC_FIRST).unwrap(); // The host fast-forwards to a commit that changed the protected vault/, // which the clone does not hold and cannot fetch. @@ -233,7 +290,7 @@ fn a_failing_probe_leaves_no_candidate_branch() { Some(b1) ); - let err = clone.ws_harvest(None, "t", None).unwrap_err(); + let err = clone.ws_harvest(None, None, "t", None).unwrap_err(); eprintln!("probe error: {err:?}"); assert!( refs::read_branch_tip(clone.layout(), "work-1") @@ -242,14 +299,14 @@ fn a_failing_probe_leaves_no_candidate_branch() { "no candidate branch may survive a failed harvest ({err:?})" ); assert!( - clone.ws_session().unwrap().is_some(), + clone.ws_session(None).unwrap().is_some(), "the workspace stays live" ); assert_eq!( refs::read_branch_tip(clone.layout(), "main").unwrap(), Some(b1) ); - clone.ws_abandon(None).unwrap(); + clone.ws_abandon(None, None).unwrap(); drop(clone); fx.cleanup(); } diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index 523827b6..bb405d79 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -53,6 +53,10 @@ pub struct WsEntry { /// The session manifest (`.sc/ws/session.toml`). Never stores key material. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WsSession { + /// `None` for the unnamed session (`.sc/ws`), `Some(name)` for a named one + /// (`.sc/ws-`, ADR-0055). Derived from where the manifest lives and + /// never stored in it, so the format is unchanged. + pub name: Option, /// The snapshot every workspace was forked from. pub base_snapshot: ObjectId, /// The branch `base_snapshot` was the tip of at fork time (display only). @@ -73,12 +77,27 @@ pub struct WsSession { pub workspaces: Vec, } -fn ws_dir(layout: &Layout) -> PathBuf { - layout.dot_sc.join("ws") +fn ws_dir(layout: &Layout, name: Option<&str>) -> PathBuf { + layout.ws_root(name) } -fn manifest_path(layout: &Layout) -> PathBuf { - ws_dir(layout).join("session.toml") +fn manifest_path(layout: &Layout, name: Option<&str>) -> PathBuf { + ws_dir(layout, name).join("session.toml") +} + +/// The prefix of a session's fallback branches and `SC_WORKSPACE` label: +/// `work` for the unnamed session (unchanged), the session name otherwise, +/// matching `sc work --name`. +fn label_prefix(name: Option<&str>) -> &str { + name.unwrap_or("work") +} + +/// A session name is a branch-name component (its fallback branches are +/// `-`) and a directory name under `.sc/`, so it takes the branch-name +/// grammar. +fn validate_session_name(name: &str) -> Result<()> { + crate::repo::validate_branch_name(name) + .map_err(|_| Error::InvalidArgument(format!("invalid session name: {name:?}"))) } fn bad(msg: impl Into) -> Error { @@ -131,9 +150,8 @@ impl From<&WsSession> for SessionToml { } } -impl TryFrom for WsSession { - type Error = Error; - fn try_from(raw: SessionToml) -> Result { +impl SessionToml { + fn into_session(raw: SessionToml, name: Option<&str>) -> Result { let base_snapshot = ObjectId::from_str(&raw.base_snapshot) .map_err(|_| bad(format!("bad base_snapshot: {}", raw.base_snapshot)))?; let workspaces = raw @@ -155,6 +173,7 @@ impl TryFrom for WsSession { }) .collect::>>()?; Ok(WsSession { + name: name.map(str::to_string), base_snapshot, base_branch: raw.base_branch, author: raw.author, @@ -164,26 +183,67 @@ impl TryFrom for WsSession { } } -/// Read the open session's manifest, if any. `pub(crate)` so `gc.rs` can root -/// the base snapshot without going through a `Repo`. -pub(crate) fn read_manifest(layout: &Layout) -> Result> { - match std::fs::read_to_string(manifest_path(layout)) { +/// Read one session's manifest (`None` = the unnamed session), if open. +pub(crate) fn read_manifest(layout: &Layout, name: Option<&str>) -> Result> { + match std::fs::read_to_string(manifest_path(layout, name)) { Ok(text) => { let raw: SessionToml = toml::from_str(&text).map_err(|e| bad(format!("malformed: {e}")))?; - raw.try_into().map(Some) + SessionToml::into_session(raw, name).map(Some) } Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e.into()), } } +/// Every open session: the unnamed one first, then named ones by name. A +/// `.sc/ws-*` directory with no manifest is crash residue and is skipped. +/// `pub(crate)` so `gc.rs` can root every base snapshot without a `Repo`. +pub(crate) fn list_sessions(layout: &Layout) -> Result> { + let mut out: Vec = read_manifest(layout, None)?.into_iter().collect(); + let mut names = Vec::new(); + for e in std::fs::read_dir(&layout.dot_sc)? { + let file = e?.file_name(); + if let Some(n) = file.to_str().and_then(|f| f.strip_prefix("ws-")) { + names.push(n.to_string()); + } + } + names.sort(); + for n in names { + out.extend(read_manifest(layout, Some(&n))?); + } + Ok(out) +} + +/// The open session called `name`, or an error naming what is open instead. +fn open_session(layout: &Layout, name: Option<&str>) -> Result { + if let Some(s) = read_manifest(layout, name)? { + return Ok(s); + } + let open: Vec = list_sessions(layout)? + .iter() + .map(|s| s.name.clone().unwrap_or_else(|| "(unnamed)".into())) + .collect(); + Err(Error::InvalidArgument(match (name, open.is_empty()) { + (_, true) => "no workspace session open".into(), + (None, false) => format!( + "no unnamed workspace session open (open: {}); pass --session ", + open.join(", ") + ), + (Some(n), false) => format!( + "no workspace session named '{n}' open (open: {})", + open.join(", ") + ), + })) +} + /// Write the session manifest atomically. The parent dir must already exist /// (fork/abandon create it before the first write). fn write_manifest(layout: &Layout, session: &WsSession) -> Result<()> { let raw: SessionToml = session.into(); let text = toml::to_string(&raw).map_err(|e| Error::BadConfig(e.to_string()))?; - scl_core::fsutil::atomic_write_durable(&manifest_path(layout), text.as_bytes())?; + let path = manifest_path(layout, session.name.as_deref()); + scl_core::fsutil::atomic_write_durable(&path, text.as_bytes())?; Ok(()) } @@ -196,6 +256,7 @@ impl Repo { /// branch, or the user's working tree. pub fn ws_fork( &self, + name: Option<&str>, agents: u32, author: &str, identity: Option<&scl_crypto::SecretKey>, @@ -204,10 +265,17 @@ impl Repo { if agents == 0 { return Err(Error::InvalidArgument("agents must be >= 1".into())); } - if let Some(existing) = read_manifest(self.layout())? { + if let Some(n) = name { + validate_session_name(n)?; + } + if let Some(existing) = read_manifest(self.layout(), name)? { + let (which, abandon) = match name { + None => (String::new(), "sc ws abandon".to_string()), + Some(n) => (format!(" '{n}'"), format!("sc ws abandon --session {n}")), + }; return Err(Error::InvalidArgument(format!( - "a workspace session is already open ({} workspace(s) forked from branch {} @ {}); \ - run `sc ws abandon` first", + "a workspace session{which} is already open ({} workspace(s) forked from branch {} @ {}); \ + run `{abandon}` first", existing.workspaces.len(), existing.base_branch, existing.base_snapshot.short(), @@ -235,7 +303,7 @@ impl Repo { crate::worktree::preflight_view(self.layout(), &mut store, tip_root, &sparse)?; } - let root = ws_dir(self.layout()); + let root = ws_dir(self.layout(), name); // No manifest proves any .sc/ws content is crash residue from a // killed fork — always safe to clear before materializing. let _ = std::fs::remove_dir_all(&root); @@ -253,7 +321,7 @@ impl Repo { let mut cache = crate::cache::ProtectedCache::open( key, dir.clone(), - Some(self.layout().ws_cache_path(i as usize)), + Some(self.layout().ws_cache_path(name, i as usize)), ); if let Err(e) = crate::workspace::materialize_workspace( self, @@ -279,6 +347,7 @@ impl Repo { } let session = WsSession { + name: name.map(str::to_string), base_snapshot: tip, base_branch: branch, author: author.to_string(), @@ -289,9 +358,14 @@ impl Repo { Ok(session) } - /// The open session's manifest, if any. - pub fn ws_session(&self) -> Result> { - read_manifest(self.layout()) + /// The manifest of session `name` (`None` = the unnamed one), if open. + pub fn ws_session(&self, name: Option<&str>) -> Result> { + read_manifest(self.layout(), name) + } + + /// Every open session, the unnamed one first, then named ones by name. + pub fn ws_sessions(&self) -> Result> { + list_sessions(self.layout()) } /// True if `entry`'s checkout has diverged from the session's base @@ -302,9 +376,8 @@ impl Repo { /// re-parses the manifest on every call; callers that already hold a /// loaded `WsSession` (e.g. `sc ws list`'s and `ws_harvest`'s per-entry /// loops) should call [`Self::ws_changed_for`] instead (P21). - pub fn ws_changed(&self, entry: &WsEntry) -> Result { - let session = read_manifest(self.layout())? - .ok_or_else(|| Error::InvalidArgument("no workspace session open".into()))?; + pub fn ws_changed(&self, name: Option<&str>, entry: &WsEntry) -> Result { + let session = open_session(self.layout(), name)?; self.ws_changed_for(&session, entry) } @@ -336,7 +409,10 @@ impl Repo { crate::cache::ProtectedCache::open( key, entry.dir.clone(), - Some(self.layout().ws_cache_path(entry.index as usize)), + Some( + self.layout() + .ws_cache_path(session.name.as_deref(), entry.index as usize), + ), ) }); let d = worktree::diff_worktree( @@ -401,9 +477,8 @@ impl Repo { /// removes the checkout dir(s) and rewrites the manifest, or removes /// `.sc/ws/` entirely once no live workspace remains. Returns the /// remaining live count. No oplog record — fork never touched a ref. - pub fn ws_abandon(&self, index: Option) -> Result { - let mut session = read_manifest(self.layout())? - .ok_or_else(|| Error::InvalidArgument("no workspace session open".into()))?; + pub fn ws_abandon(&self, name: Option<&str>, index: Option) -> Result { + let mut session = open_session(self.layout(), name)?; match index { Some(i) => { let entry = session @@ -415,7 +490,9 @@ impl Repo { let _ = std::fs::remove_dir_all(&entry.dir); // Drop the workspace's P33 stat cache too (sibling file, // not under the checkout dir) — P33 Task 7 item 3. - let _ = std::fs::remove_file(self.layout().ws_cache_path(entry.index as usize)); + let _ = std::fs::remove_file( + self.layout().ws_cache_path(name, entry.index as usize), + ); entry.live = false; } } @@ -427,40 +504,50 @@ impl Repo { } let remaining = session.workspaces.iter().filter(|e| e.live).count(); if remaining == 0 { - let _ = std::fs::remove_dir_all(ws_dir(self.layout())); + let _ = std::fs::remove_dir_all(ws_dir(self.layout(), name)); } else { write_manifest(self.layout(), &session)?; } Ok(remaining) } - /// Run a command in one workspace checkout: spawns `cmd` in `entry.dir` - /// with SC_WORKSPACE and SC_WORKSPACE_DIR env vars set, optionally injecting - /// decrypted secrets, and returns the child's exit code. The workspace must be - /// live (not abandoned); the session must be open. No oplog record, no harvest, - /// no manifest rewrite — the workspace checkout persists for later harvest. + /// Run a command in one workspace checkout. Convenience over + /// [`Self::ws_run_plan`] + [`WsRunPlan::run`] that keeps this `Repo` (and so + /// the single-writer lock) alive for the child's lifetime; the CLI drops the + /// repo between the two so other sessions stay usable meanwhile (ADR-0055). pub fn ws_run( &self, + name: Option<&str>, index: u32, cmd: &[String], with_secrets: bool, identity: Option<&scl_crypto::SecretKey>, ) -> Result { - let session = read_manifest(self.layout())? - .ok_or_else(|| Error::InvalidArgument("no workspace session open".into()))?; + self.ws_run_plan(name, index, with_secrets, identity)? + .run(cmd) + } + + /// Resolve everything `ws_run` needs from the repo (the live workspace's + /// dir, its `SC_WORKSPACE` label and, with `with_secrets`, the decrypted + /// secret environment) so the caller can release the repo lock before + /// spawning the possibly long-running command. The workspace must be live + /// and the session open. No oplog record, no harvest, no manifest rewrite. + pub fn ws_run_plan( + &self, + name: Option<&str>, + index: u32, + with_secrets: bool, + identity: Option<&scl_crypto::SecretKey>, + ) -> Result { + let session = open_session(self.layout(), name)?; let entry = session .workspaces .iter() - .find(|e| e.index == index) + .find(|e| e.index == index && e.live) .ok_or_else(|| Error::InvalidArgument(format!("no such workspace: {index}")))?; - if !entry.live { - return Err(Error::InvalidArgument(format!( - "no such workspace: {index}" - ))); - } // Build secret env vars if requested (strict mode, mirroring `sc work`). - let secret_envs = if with_secrets { + let envs = if with_secrets { let sk = identity.ok_or_else(|| { Error::InvalidArgument("--with-secrets requires an identity".into()) })?; @@ -468,24 +555,13 @@ impl Repo { } else { Vec::new() }; - - // Spawn the command in the workspace directory with env vars set. - let (exe, args) = cmd - .split_first() - .ok_or_else(|| Error::InvalidArgument("empty command".into()))?; - let mut command = std::process::Command::new(exe); - command - .args(args) - .current_dir(&entry.dir) - // Label matches the work- branch namespace a harvest fallback would mint (P13 parity: label == branch name). - .env("SC_WORKSPACE", format!("work-{}", entry.index)) - .env("SC_WORKSPACE_DIR", &entry.dir); - for (k, v) in &secret_envs { - command.env(k, v); - } - - let status = command.status()?; - Ok(status.code().unwrap_or(1)) + Ok(WsRunPlan { + dir: entry.dir.clone(), + // Label matches the fallback-branch namespace a harvest would mint + // (P13 parity: label == branch name). + label: format!("{}-{}", label_prefix(name), entry.index), + envs, + }) } /// Read-only conflict probe: would merging `theirs` into `ours` land @@ -646,6 +722,7 @@ impl Repo { /// accident. pub fn ws_harvest( &self, + name: Option<&str>, into: Option<&str>, author: &str, identity: Option<&scl_crypto::SecretKey>, @@ -659,8 +736,7 @@ impl Repo { if crate::rebase_state::in_progress(&self.layout) { return Err(Error::RebaseInProgress); } - let mut session = read_manifest(self.layout())? - .ok_or_else(|| Error::InvalidArgument("no workspace session open".into()))?; + let mut session = open_session(self.layout(), name)?; let landing = into.unwrap_or(&session.base_branch).to_string(); let current = refs::current_branch(self.layout())?; @@ -733,10 +809,11 @@ impl Repo { // Step 2: pick a fallback candidate branch name, suffixed on // collision (a prior harvest or a pre-existing branch of the // same name). - let mut branch = format!("work-{i}"); + let base = format!("{}-{i}", label_prefix(name)); + let mut branch = base.clone(); let mut suffix = 2; while refs::resolve_tip(self.layout(), &branch)?.is_some() { - branch = format!("work-{i}-{suffix}"); + branch = format!("{base}-{suffix}"); suffix += 1; } @@ -745,7 +822,10 @@ impl Repo { // candidate branch. `tip` is the candidate's parent, which per // P13's contract is the session's base snapshot, not the // landing branch's current (possibly since-advanced) tip. - let msg = format!("ws-{i} harvest"); + let msg = match name { + None => format!("ws-{i} harvest"), + Some(n) => format!("ws {n}-{i} harvest"), + }; // The session's fork-time spec, not the host's current one (P24 // final-review fix, Critical 1) — same reasoning as // `ws_changed_for` above, now threaded into the commit carry too @@ -761,7 +841,7 @@ impl Repo { let mut cache = crate::cache::ProtectedCache::open( key, dir.clone(), - Some(self.layout().ws_cache_path(i as usize)), + Some(self.layout().ws_cache_path(name, i as usize)), ); let harvested = crate::workspace::harvest_workspace( self, @@ -909,7 +989,7 @@ impl Repo { } if session.workspaces.iter().all(|e| !e.live) { - let _ = std::fs::remove_dir_all(ws_dir(self.layout())); + let _ = std::fs::remove_dir_all(ws_dir(self.layout(), name)); } Ok(outcomes) @@ -946,10 +1026,39 @@ fn resolve_and_teardown( // Drop this workspace's P33 stat cache alongside its checkout dir (P33 // Task 7 item 3): the cache file lives beside the dir, not inside it, so // removing the dir doesn't remove it. - let _ = std::fs::remove_file(layout.ws_cache_path(index as usize)); + let _ = std::fs::remove_file(layout.ws_cache_path(session.name.as_deref(), index as usize)); Ok(()) } +/// A resolved `sc ws run`: where to run, the `SC_WORKSPACE` label, and any +/// injected secrets. Holds no repo handle, so running it does not hold the +/// repo lock. +pub struct WsRunPlan { + dir: PathBuf, + label: String, + envs: Vec<(String, std::ffi::OsString)>, +} + +impl WsRunPlan { + /// Spawn `cmd` in the workspace dir with `SC_WORKSPACE` and + /// `SC_WORKSPACE_DIR` set and return its exit code. + pub fn run(&self, cmd: &[String]) -> Result { + let (exe, args) = cmd + .split_first() + .ok_or_else(|| Error::InvalidArgument("empty command".into()))?; + let mut command = std::process::Command::new(exe); + command + .args(args) + .current_dir(&self.dir) + .env("SC_WORKSPACE", &self.label) + .env("SC_WORKSPACE_DIR", &self.dir); + for (k, v) in &self.envs { + command.env(k, v); + } + Ok(command.status()?.code().unwrap_or(1)) + } +} + /// Outcome of harvesting one live workspace. #[derive(Debug)] pub enum WsHarvestOutcome { @@ -989,7 +1098,7 @@ mod tests { let repo = init(&root); let tip = repo.head_tip().unwrap().unwrap(); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); assert_eq!(session.base_snapshot, tip); assert_eq!(session.base_branch, "main"); assert_eq!(session.workspaces.len(), 2); @@ -1001,7 +1110,7 @@ mod tests { ); } - let err = repo.ws_fork(1, "t", None).unwrap_err(); + let err = repo.ws_fork(None, 1, "t", None).unwrap_err(); match err { Error::InvalidArgument(msg) => assert!( msg.contains("workspace session is already open"), @@ -1029,7 +1138,7 @@ mod tests { repo.set_sparse(&["src/".into()], None).unwrap(); assert!(!root.join("docs/x").exists()); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); let entry = &session.workspaces[0]; assert!( entry.dir.join("src/a.txt").exists(), @@ -1042,7 +1151,7 @@ mod tests { // Harvest carries the untouched out-of-sparse subtree verbatim. std::fs::write(entry.dir.join("src/a.txt"), b"a v2").unwrap(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 1); match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, .. } => {} @@ -1093,7 +1202,7 @@ mod tests { // 1. Narrow to src/ and fork — the workspace only ever sees src/. repo.set_sparse(&["src/".into()], None).unwrap(); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); let entry = &session.workspaces[0]; assert!(entry.dir.join("src/a.txt").exists()); assert!(!entry.dir.join("docs/x.txt").exists()); @@ -1115,7 +1224,7 @@ mod tests { // 4. Harvest. The workspace's absent docs/x.txt must be carried // (never materialized, not a user deletion), not committed as a // deletion. - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 1); match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, .. } => {} @@ -1172,19 +1281,19 @@ mod tests { // Simulate a kill -9 mid-fork: a workspace dir exists with a stray // file but no manifest was ever written to announce the session. - let ws_root = ws_dir(repo.layout()); + let ws_root = ws_dir(repo.layout(), None); std::fs::create_dir_all(ws_root.join("1")).unwrap(); std::fs::write(ws_root.join("1").join("residue.txt"), "stale\n").unwrap(); - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); assert_eq!(session.base_snapshot, tip); assert_eq!(session.workspaces.len(), 2); // Neither freshly forked workspace shows the residue as a change. for entry in &session.workspaces { assert!( - !repo.ws_changed(entry).unwrap(), + !repo.ws_changed(None, entry).unwrap(), "residue must not leak into a freshly forked workspace" ); } @@ -1201,11 +1310,11 @@ mod tests { // Harvesting the untouched workspaces lands nothing and leaves the // base branch tip unchanged. let base_before = repo.head_tip().unwrap().unwrap(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert!(outcomes .iter() .all(|o| matches!(o, WsHarvestOutcome::Unchanged { .. }))); - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); assert_eq!(repo.head_tip().unwrap().unwrap(), base_before); drop(repo); @@ -1232,25 +1341,25 @@ mod tests { let root = tmp_root("boundary"); { let repo = init(&root); - repo.ws_fork(2, "t", None).unwrap(); + repo.ws_fork(None, 2, "t", None).unwrap(); } // repo (and its lock) dropped: simulates the process exiting let repo = Repo::open(&root).unwrap(); let session = repo - .ws_session() + .ws_session(None) .unwrap() .expect("manifest must survive reopen"); assert_eq!(session.workspaces.len(), 2); for entry in &session.workspaces { assert!( - !repo.ws_changed(entry).unwrap(), + !repo.ws_changed(None, entry).unwrap(), "freshly forked checkout must be unchanged" ); } std::fs::write(session.workspaces[0].dir.join("a.txt"), "edited\n").unwrap(); - assert!(repo.ws_changed(&session.workspaces[0]).unwrap()); - assert!(!repo.ws_changed(&session.workspaces[1]).unwrap()); + assert!(repo.ws_changed(None, &session.workspaces[0]).unwrap()); + assert!(!repo.ws_changed(None, &session.workspaces[1]).unwrap()); drop(repo); std::fs::remove_dir_all(&root).unwrap(); @@ -1260,22 +1369,22 @@ mod tests { fn abandon_one_and_all() { let root = tmp_root("abandon"); let repo = init(&root); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); let dir1 = session.workspaces[0].dir.clone(); let dir2 = session.workspaces[1].dir.clone(); - let remaining = repo.ws_abandon(Some(1)).unwrap(); + let remaining = repo.ws_abandon(None, Some(1)).unwrap(); assert_eq!(remaining, 1); assert!(!dir1.exists()); - let after = repo.ws_session().unwrap().expect("session still open"); + let after = repo.ws_session(None).unwrap().expect("session still open"); let e1 = after.workspaces.iter().find(|e| e.index == 1).unwrap(); assert!(!e1.live); assert!(dir2.exists()); - let remaining = repo.ws_abandon(None).unwrap(); + let remaining = repo.ws_abandon(None, None).unwrap(); assert_eq!(remaining, 0); assert!(!dir2.exists()); - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); drop(repo); std::fs::remove_dir_all(&root).unwrap(); @@ -1292,8 +1401,8 @@ mod tests { std::fs::write(root.join("a.txt"), "still base\n").unwrap(); repo.commit("t", "protect a.txt").unwrap(); - repo.ws_fork(1, "t", Some(&sk)).unwrap(); - let text = std::fs::read_to_string(manifest_path(repo.layout())).unwrap(); + repo.ws_fork(None, 1, "t", Some(&sk)).unwrap(); + let text = std::fs::read_to_string(manifest_path(repo.layout(), None)).unwrap(); assert!( !text.contains("scl-sk"), "manifest must never contain key material: {text}" @@ -1342,14 +1451,14 @@ mod tests { // Fork two workspaces WITH identity: the protected file materializes // decrypted AND is recorded in each workspace's own cache at fork. - let session = repo.ws_fork(2, "t", Some(&sk)).unwrap(); + let session = repo.ws_fork(None, 2, "t", Some(&sk)).unwrap(); let dir1 = session.workspaces[0].dir.clone(); let dir2 = session.workspaces[1].dir.clone(); // Each workspace edits ONLY its own plain file; secret/x is untouched. std::fs::write(dir1.join("p1.txt"), "one edited\n").unwrap(); std::fs::write(dir2.join("p2.txt"), "two edited\n").unwrap(); - let outcomes = repo.ws_harvest(None, "t", Some(&sk)).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", Some(&sk)).unwrap(); assert_eq!(outcomes.len(), 2); for o in &outcomes { let merged_tip = match o { @@ -1386,9 +1495,9 @@ mod tests { std::fs::write(root.join("secret/gone"), "doomed\n").unwrap(); repo.commit("t", "add protected").unwrap(); - let session = repo.ws_fork(1, "t", Some(&sk)).unwrap(); + let session = repo.ws_fork(None, 1, "t", Some(&sk)).unwrap(); let dir = session.workspaces[0].dir.clone(); - let cache_file = repo.layout().ws_cache_path(1); + let cache_file = repo.layout().ws_cache_path(None, 1); let cached = |name: &str| { std::fs::read_to_string(&cache_file) .unwrap() @@ -1400,7 +1509,7 @@ mod tests { std::fs::remove_file(dir.join("secret/gone")).unwrap(); // An AWS-style key id trips the P5 scanner, so the workspace stays live. std::fs::write(dir.join("leak.txt"), "AKIAIOSFODNN7EXAMPLE\n").unwrap(); - let outcomes = repo.ws_harvest(None, "t", Some(&sk)).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", Some(&sk)).unwrap(); assert!( matches!(outcomes[0], WsHarvestOutcome::Rejected { index: 1, .. }), "got {outcomes:?}" @@ -1450,7 +1559,7 @@ mod tests { // Fork WITH identity so the protected file materializes decrypted // and is recorded in the workspace's own cache at fork time; leave // it completely untouched. - let session = repo.ws_fork(1, "t", Some(&sk)).unwrap(); + let session = repo.ws_fork(None, 1, "t", Some(&sk)).unwrap(); assert!( !repo .ws_changed_for(&session, &session.workspaces[0]) @@ -1491,7 +1600,7 @@ mod tests { // Point the branch at `tip` (bypassing `commit`/oplog) just long // enough for `ws_fork` to read it as HEAD, then rewind to `base`. crate::refs::write_branch_tip(repo.layout(), "main", &tip).unwrap(); - repo.ws_fork(1, "t", None).unwrap(); + repo.ws_fork(None, 1, "t", None).unwrap(); crate::refs::write_branch_tip(repo.layout(), "main", &base).unwrap(); repo.gc(std::time::Duration::from_secs(0)).unwrap(); @@ -1503,7 +1612,7 @@ mod tests { ); drop(s); - repo.ws_abandon(None).unwrap(); + repo.ws_abandon(None, None).unwrap(); repo.gc(std::time::Duration::from_secs(0)).unwrap(); let arc = repo.vfs().store(); let s = arc.lock().unwrap(); @@ -1521,12 +1630,13 @@ mod tests { fn ws_run_sets_env_and_cwd() { let root = tmp_root("ws_run_env"); let repo = init(&root); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); let entry = &session.workspaces[1]; // work-2 // Run a command that writes SC_WORKSPACE and pwd to files. let exit = repo .ws_run( + None, entry.index, &[ "sh".to_string(), @@ -1561,11 +1671,12 @@ mod tests { let (sk, pk) = scl_crypto::generate_keypair(); repo.secret_add("DEMO_TOKEN", b"tok-123", &[pk]).unwrap(); - let session = repo.ws_fork(1, "t", Some(&sk)).unwrap(); + let session = repo.ws_fork(None, 1, "t", Some(&sk)).unwrap(); let entry = &session.workspaces[0]; let exit = repo .ws_run( + None, entry.index, &[ "sh".to_string(), @@ -1591,11 +1702,12 @@ mod tests { fn ws_run_bad_index_errors() { let root = tmp_root("ws_run_bad"); let repo = init(&root); - let _session = repo.ws_fork(2, "t", None).unwrap(); + let _session = repo.ws_fork(None, 2, "t", None).unwrap(); // Non-existent workspace index. let err = repo .ws_run( + None, 999, &["sh".to_string(), "-c".to_string(), "true".to_string()], false, @@ -1606,9 +1718,10 @@ mod tests { assert!(err.to_string().contains("no such workspace: 999")); // Abandon workspace 1, then try to run in it. - repo.ws_abandon(Some(1)).unwrap(); + repo.ws_abandon(None, Some(1)).unwrap(); let err = repo .ws_run( + None, 1, &["sh".to_string(), "-c".to_string(), "true".to_string()], false, @@ -1626,12 +1739,12 @@ mod tests { fn harvest_lands_clean_results_cumulatively() { let root = tmp_root("harvest-clean"); let repo = init(&root); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("a.txt"), "edited-a\n").unwrap(); std::fs::write(session.workspaces[1].dir.join("b.txt"), "new-b\n").unwrap(); let oplog_before = repo.oplog().unwrap().len(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 2); match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, .. } => {} @@ -1665,7 +1778,7 @@ mod tests { .is_none()); // Session ended. - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); assert!(!repo.layout().dot_sc.join("ws").exists()); // sc undo reverts ONLY the second landing: a.txt edit still present, @@ -1692,12 +1805,12 @@ mod tests { std::fs::write(root.join("keep.txt"), "k\n").unwrap(); repo.commit("t", "base").unwrap(); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("n"), "file\n").unwrap(); std::fs::create_dir_all(session.workspaces[1].dir.join("n")).unwrap(); std::fs::write(session.workspaces[1].dir.join("n/child"), "nested\n").unwrap(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 2); assert!( matches!(&outcomes[0], WsHarvestOutcome::Landed { index: 1, .. }), @@ -1720,7 +1833,7 @@ mod tests { std::fs::write(root.join("x.txt"), "base-x\n").unwrap(); repo.commit("t", "add x").unwrap(); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("a.txt"), "edited-a\n").unwrap(); std::fs::write(session.workspaces[1].dir.join("x.txt"), "ws2-x\n").unwrap(); @@ -1729,7 +1842,7 @@ mod tests { std::fs::write(root.join("x.txt"), "main-x\n").unwrap(); repo.commit("t", "conflict x on main").unwrap(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 2); match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, .. } => {} @@ -1773,7 +1886,7 @@ mod tests { assert!(!crate::merge_state::in_progress(repo.layout())); // Session ended. - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); drop(repo); std::fs::remove_dir_all(&root).unwrap(); @@ -1784,10 +1897,10 @@ mod tests { let root = tmp_root("harvest-notcheckedout"); let repo = init(&root); repo.branch("other").unwrap(); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); repo.switch("other").unwrap(); - let err = repo.ws_harvest(None, "t", None).unwrap_err(); + let err = repo.ws_harvest(None, None, "t", None).unwrap_err(); match err { Error::InvalidArgument(msg) => { assert!( @@ -1804,7 +1917,7 @@ mod tests { // Session still open; nothing moved. let after = repo - .ws_session() + .ws_session(None) .unwrap() .expect("session must still be open"); assert_eq!(after.workspaces.len(), session.workspaces.len()); @@ -1821,7 +1934,7 @@ mod tests { std::fs::write(root.join("x.txt"), "base-x\n").unwrap(); repo.commit("t", "add x").unwrap(); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("a.txt"), "edited-a\n").unwrap(); std::fs::write(session.workspaces[1].dir.join("x.txt"), "ws2-x\n").unwrap(); std::fs::write(root.join("x.txt"), "main-x\n").unwrap(); @@ -1831,7 +1944,7 @@ mod tests { repo.branch("work-2").unwrap(); // --into with the checked-out branch name behaves as default. - let outcomes = repo.ws_harvest(Some("main"), "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, Some("main"), "t", None).unwrap(); match &outcomes[1] { WsHarvestOutcome::FallbackBranch { index: 2, branch } => { assert_eq!(branch, "work-2-2"); @@ -1840,9 +1953,9 @@ mod tests { } // --into a non-checked-out branch errors. - let _session2 = repo.ws_fork(1, "t", None).unwrap(); + let _session2 = repo.ws_fork(None, 1, "t", None).unwrap(); let err = repo - .ws_harvest(Some("nonexistent-branch"), "t", None) + .ws_harvest(None, Some("nonexistent-branch"), "t", None) .unwrap_err(); assert!(matches!(err, Error::InvalidArgument(_))); @@ -1854,19 +1967,19 @@ mod tests { fn harvest_guards_and_dirty_tree() { let root = tmp_root("harvest-guards"); let repo = init(&root); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); // (a) merge/pick/rebase in progress -> typed errors. crate::merge_state::write(repo.layout(), &ObjectId::of(b"theirs"), &[], None).unwrap(); assert!(matches!( - repo.ws_harvest(None, "t", None), + repo.ws_harvest(None, None, "t", None), Err(Error::MergeInProgress) )); crate::merge_state::clear(repo.layout()).unwrap(); crate::pick_state::write(repo.layout(), &ObjectId::of(b"picked"), &[], None, None).unwrap(); assert!(matches!( - repo.ws_harvest(None, "t", None), + repo.ws_harvest(None, None, "t", None), Err(Error::PickInProgress) )); crate::pick_state::clear(repo.layout()).unwrap(); @@ -1886,7 +1999,7 @@ mod tests { }; crate::rebase_state::write(repo.layout(), &st).unwrap(); assert!(matches!( - repo.ws_harvest(None, "t", None), + repo.ws_harvest(None, None, "t", None), Err(Error::RebaseInProgress) )); crate::rebase_state::clear(repo.layout()).unwrap(); @@ -1897,11 +2010,11 @@ mod tests { // Session intact. std::fs::write(session.workspaces[0].dir.join("a.txt"), "ws-edit\n").unwrap(); std::fs::write(root.join("a.txt"), "dirty-uncommitted\n").unwrap(); - let err = repo.ws_harvest(None, "t", None).unwrap_err(); + let err = repo.ws_harvest(None, None, "t", None).unwrap_err(); assert!(matches!(err, Error::InvalidArgument(_))); let after = repo - .ws_session() + .ws_session(None) .unwrap() .expect("session must still be open"); assert!( @@ -1926,7 +2039,7 @@ mod tests { fn harvest_partial_leaves_session_open() { let root = tmp_root("harvest-partial"); let repo = init(&root); - let session = repo.ws_fork(2, "t", None).unwrap(); + let session = repo.ws_fork(None, 2, "t", None).unwrap(); std::fs::write(session.workspaces[0].dir.join("a.txt"), "edited-a\n").unwrap(); // An AWS-style key id trips the P5 scanner in ws-2's checkout. std::fs::write( @@ -1935,7 +2048,7 @@ mod tests { ) .unwrap(); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes.len(), 2); match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, .. } => {} @@ -1949,7 +2062,7 @@ mod tests { // ws-2 stays LIVE (rejected != resolved); session still open with // ws-2 only. let after = repo - .ws_session() + .ws_session(None) .unwrap() .expect("session must still be open"); assert_eq!(after.workspaces.len(), 2); @@ -1977,7 +2090,7 @@ mod tests { "base\n" ); let after_undo = repo - .ws_session() + .ws_session(None) .unwrap() .expect("ws-2 still live keeps the session open"); let e1_after_undo = after_undo.workspaces.iter().find(|e| e.index == 1).unwrap(); @@ -1988,13 +2101,13 @@ mod tests { // Fixing the file then re-harvesting completes and ends the session. std::fs::remove_file(e2.dir.join("leak.txt")).unwrap(); - let outcomes2 = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes2 = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes2.len(), 1); match &outcomes2[0] { WsHarvestOutcome::Unchanged { index: 2 } => {} other => panic!("expected Unchanged(2) once the leak is removed, got {other:?}"), } - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); drop(repo); std::fs::remove_dir_all(&root).unwrap(); @@ -2004,7 +2117,7 @@ mod tests { fn harvest_reharvest_after_crash_window_is_idempotent() { let root = tmp_root("harvest-reharvest"); let repo = init(&root); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); let dir = session.workspaces[0].dir.clone(); std::fs::write(dir.join("a.txt"), "edited-a\n").unwrap(); @@ -2013,7 +2126,7 @@ mod tests { // the re-minted candidate id matches regardless of load. crate::repo::TEST_NOW.with(|c| c.set(Some(1_700_000_000))); - let outcomes = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes = repo.ws_harvest(None, None, "t", None).unwrap(); let landed_tip = match &outcomes[0] { WsHarvestOutcome::Landed { index: 1, @@ -2022,7 +2135,7 @@ mod tests { other => panic!("expected Landed(1), got {other:?}"), }; assert!( - repo.ws_session().unwrap().is_none(), + repo.ws_session(None).unwrap().is_none(), "session must have ended" ); @@ -2034,6 +2147,7 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("a.txt"), "edited-a\n").unwrap(); let crashed = WsSession { + name: None, base_snapshot: session.base_snapshot, base_branch: session.base_branch.clone(), author: session.author.clone(), @@ -2049,7 +2163,7 @@ mod tests { // Re-harvest: no error, resolves as a no-op Landed at the existing // tip, and leaves no stray branch behind. - let outcomes2 = repo.ws_harvest(None, "t", None).unwrap(); + let outcomes2 = repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(outcomes2.len(), 1); match &outcomes2[0] { WsHarvestOutcome::Landed { @@ -2069,10 +2183,346 @@ mod tests { .is_none(), "no stray candidate branch after the UpToDate no-op resolution" ); - assert!(repo.ws_session().unwrap().is_none()); + assert!(repo.ws_session(None).unwrap().is_none()); crate::repo::TEST_NOW.with(|c| c.set(None)); drop(repo); std::fs::remove_dir_all(&root).unwrap(); } + + // ---- Named and concurrent sessions (ADR-0055) ------------------------- + + /// Fork a one-workspace session called `name` and write `file` in it. + fn fork_and_edit(repo: &Repo, name: Option<&str>, file: &str, content: &str) -> WsEntry { + let session = repo.ws_fork(name, 1, "t", None).unwrap(); + let entry = session.workspaces[0].clone(); + std::fs::write(entry.dir.join(file), content).unwrap(); + entry + } + + #[test] + fn named_and_unnamed_sessions_coexist_in_separate_roots() { + let root = tmp_root("named-coexist"); + let repo = init(&root); + + let plain = repo.ws_fork(None, 1, "t", None).unwrap(); + let a = repo.ws_fork(Some("a"), 2, "t", None).unwrap(); + let b = repo.ws_fork(Some("b"), 1, "t", None).unwrap(); + + // The unnamed session keeps the original layout; named ones sit beside it. + let dot = &repo.layout().dot_sc; + assert_eq!(plain.workspaces[0].dir, dot.join("ws/1")); + assert_eq!(a.workspaces[1].dir, dot.join("ws-a/2")); + assert_eq!(b.workspaces[0].dir, dot.join("ws-b/1")); + // Each session's P33 stat cache sits in its own root, beside its checkouts. + assert_eq!(repo.layout().ws_cache_path(None, 1), dot.join("ws/cache-1")); + assert_eq!( + repo.layout().ws_cache_path(Some("b"), 1), + dot.join("ws-b/cache-1") + ); + for p in ["ws/session.toml", "ws-a/session.toml", "ws-b/session.toml"] { + assert!(dot.join(p).is_file(), "{p}"); + } + + let all = repo.ws_sessions().unwrap(); + let names: Vec<_> = all.iter().map(|s| s.name.as_deref()).collect(); + assert_eq!(names, [None, Some("a"), Some("b")]); + assert_eq!( + repo.ws_session(Some("a")) + .unwrap() + .unwrap() + .workspaces + .len(), + 2 + ); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn session_name_collisions_and_bad_names_are_refused() { + let root = tmp_root("named-collide"); + let repo = init(&root); + repo.ws_fork(Some("a"), 1, "t", None).unwrap(); + + match repo.ws_fork(Some("a"), 1, "t", None).unwrap_err() { + Error::InvalidArgument(m) => { + assert!(m.contains("session 'a' is already open"), "{m}"); + assert!(m.contains("sc ws abandon --session a"), "{m}"); + } + other => panic!("expected InvalidArgument, got {other:?}"), + } + // A named session does not occupy the unnamed slot, nor vice versa. + repo.ws_fork(None, 1, "t", None).unwrap(); + assert!(repo.ws_fork(None, 1, "t", None).is_err()); + repo.ws_fork(Some("b"), 1, "t", None).unwrap(); + + for bad in ["", "a/b", "..", ".hidden", "has space"] { + assert!( + matches!( + repo.ws_fork(Some(bad), 1, "t", None), + Err(Error::InvalidArgument(_)) + ), + "{bad:?} must be refused" + ); + } + // A refused fork leaves nothing behind. + assert_eq!(repo.ws_sessions().unwrap().len(), 3); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn addressing_a_missing_session_names_what_is_open() { + let root = tmp_root("named-missing"); + let repo = init(&root); + assert!(matches!( + repo.ws_abandon(Some("x"), None), + Err(Error::InvalidArgument(m)) if m == "no workspace session open" + )); + repo.ws_fork(Some("a"), 1, "t", None).unwrap(); + // No unnamed session: the default does not silently pick a named one. + for err in [ + repo.ws_harvest(None, None, "t", None).unwrap_err(), + repo.ws_abandon(None, None).unwrap_err(), + repo.ws_run(None, 1, &["true".into()], false, None) + .unwrap_err(), + ] { + let Error::InvalidArgument(m) = err else { + panic!("{err:?}") + }; + assert!(m.contains("open: a") && m.contains("--session"), "{m}"); + } + match repo.ws_harvest(Some("nope"), None, "t", None).unwrap_err() { + Error::InvalidArgument(m) => assert!(m.contains("named 'nope'"), "{m}"), + other => panic!("{other:?}"), + } + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + /// Two sessions edit the same file from the same base. Whichever harvest + /// runs first lands; the second finds the landing branch moved on, cannot + /// merge cleanly, and falls back to its own `-` branch. + #[test] + fn first_harvest_wins_and_the_later_conflicting_one_falls_back() { + for (tag, first, second) in [("ab", "a", "b"), ("ba", "b", "a")] { + let root = tmp_root(&format!("order-conflict-{tag}")); + let repo = init(&root); + fork_and_edit(&repo, Some("a"), "a.txt", "from a\n"); + fork_and_edit(&repo, Some("b"), "a.txt", "from b\n"); + let base = repo.head_tip().unwrap().unwrap(); + + let out = repo.ws_harvest(Some(first), None, "t", None).unwrap(); + assert!(matches!( + out[..], + [WsHarvestOutcome::Landed { index: 1, .. }] + )); + let out = repo.ws_harvest(Some(second), None, "t", None).unwrap(); + match &out[..] { + [WsHarvestOutcome::FallbackBranch { index: 1, branch }] => { + assert_eq!(*branch, format!("{second}-1")); + } + other => panic!("expected a fallback, got {other:?}"), + } + + let want = format!("from {first}\n"); + assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), want); + assert_ne!(repo.head_tip().unwrap().unwrap(), base); + // The loser's work is intact on its branch, parented on the base. + let kept = crate::refs::read_branch_tip(repo.layout(), &format!("{second}-1")) + .unwrap() + .unwrap(); + assert_eq!(repo.snapshot(&kept).unwrap().parents, vec![base]); + // Both sessions ended; nothing is left under .sc. + assert!(repo.ws_sessions().unwrap().is_empty()); + assert!(!repo.layout().dot_sc.join("ws-a").exists()); + assert!(!repo.layout().dot_sc.join("ws-b").exists()); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + } + + /// Disjoint edits from two sessions land in either order, to the same tree; + /// the second landing is a real merge over the first. + #[test] + fn disjoint_sessions_land_in_either_order_to_the_same_tree() { + let mut trees = Vec::new(); + for (tag, first, second) in [("ab", "a", "b"), ("ba", "b", "a")] { + let root = tmp_root(&format!("order-disjoint-{tag}")); + let repo = init(&root); + fork_and_edit(&repo, Some("a"), "file-a.txt", "A\n"); + fork_and_edit(&repo, Some("b"), "file-b.txt", "B\n"); + + repo.ws_harvest(Some(first), None, "t", None).unwrap(); + let one = repo.head_tip().unwrap().unwrap(); + // The other session is untouched by the first landing. + assert!(repo.ws_session(Some(second)).unwrap().unwrap().workspaces[0].live); + + let out = repo.ws_harvest(Some(second), None, "t", None).unwrap(); + let tip = match out[..] { + [WsHarvestOutcome::Landed { merged_tip, .. }] => merged_tip, + ref other => panic!("expected a landing, got {other:?}"), + }; + let snap = repo.snapshot(&tip).unwrap(); + assert_eq!(snap.parents.len(), 2, "second landing is a merge"); + assert_eq!(snap.parents[0], one); + for f in ["file-a.txt", "file-b.txt"] { + assert!(root.join(f).exists()); + } + trees.push(snap.root); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + assert_eq!( + trees[0], trees[1], + "same content whichever session lands first" + ); + } + + #[test] + fn abandoning_one_session_leaves_another_usable() { + let root = tmp_root("named-abandon"); + let repo = init(&root); + let a = fork_and_edit(&repo, Some("a"), "file-a.txt", "A\n"); + let b = fork_and_edit(&repo, Some("b"), "file-b.txt", "B\n"); + let plain = fork_and_edit(&repo, None, "file-p.txt", "P\n"); + let b_manifest = repo.layout().ws_root(Some("b")).join("session.toml"); + + // Abandon the whole of `a` and the unnamed session while `b` is live. + assert_eq!(repo.ws_abandon(Some("a"), None).unwrap(), 0); + assert_eq!(repo.ws_abandon(None, None).unwrap(), 0); + assert!(!a.dir.exists() && !plain.dir.exists()); + assert!(!repo.layout().dot_sc.join("ws-a").exists()); + assert!(!repo.layout().dot_sc.join("ws").exists()); + + // `b` still has its checkout, its edit and its manifest, and still runs. + assert_eq!( + std::fs::read_to_string(b.dir.join("file-b.txt")).unwrap(), + "B\n" + ); + assert!(b_manifest.is_file()); + assert_eq!( + repo.ws_run(Some("b"), 1, &["true".into()], false, None) + .unwrap(), + 0 + ); + assert!(repo + .ws_run(Some("a"), 1, &["true".into()], false, None) + .is_err()); + + // ...and still harvests. + let out = repo.ws_harvest(Some("b"), None, "t", None).unwrap(); + assert!(matches!( + out[..], + [WsHarvestOutcome::Landed { index: 1, .. }] + )); + assert!(root.join("file-b.txt").exists()); + assert!(!root.join("file-a.txt").exists() && !root.join("file-p.txt").exists()); + assert!(repo.ws_sessions().unwrap().is_empty()); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn abandoning_one_workspace_of_a_named_session_keeps_its_siblings() { + let root = tmp_root("named-abandon-one"); + let repo = init(&root); + let s = repo.ws_fork(Some("a"), 2, "t", None).unwrap(); + assert_eq!(repo.ws_abandon(Some("a"), Some(1)).unwrap(), 1); + assert!(!s.workspaces[0].dir.exists() && s.workspaces[1].dir.exists()); + let after = repo.ws_session(Some("a")).unwrap().unwrap(); + assert!(!after.workspaces[0].live && after.workspaces[1].live); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_named_session_labels_its_workspaces_and_branches_with_its_name() { + let root = tmp_root("named-label"); + let repo = init(&root); + let out_file = root.join("label.txt"); + repo.ws_fork(Some("feat"), 1, "t", None).unwrap(); + let script = format!("printf %s \"$SC_WORKSPACE\" > {}", out_file.display()); + let code = repo + .ws_run( + Some("feat"), + 1, + &["sh".into(), "-c".into(), script], + false, + None, + ) + .unwrap(); + assert_eq!(code, 0); + assert_eq!(std::fs::read_to_string(&out_file).unwrap(), "feat-1"); + std::fs::remove_file(&out_file).unwrap(); + + // A pre-existing branch of the fallback name is suffixed, not clobbered. + repo.ws_abandon(Some("feat"), None).unwrap(); + let entry = fork_and_edit(&repo, Some("feat"), "a.txt", "ws\n"); + std::fs::write(root.join("a.txt"), "host\n").unwrap(); + repo.commit("t", "host edit").unwrap(); + repo.branch("feat-1").unwrap(); + let out = repo.ws_harvest(Some("feat"), None, "t", None).unwrap(); + match &out[..] { + [WsHarvestOutcome::FallbackBranch { branch, .. }] => assert_eq!(branch, "feat-1-2"), + other => panic!("{other:?}"), + } + assert!(!entry.dir.exists()); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn gc_roots_the_base_of_every_open_session() { + let root = tmp_root("gc-named"); + let repo = init(&root); + let base = repo.head_tip().unwrap().unwrap(); + let standalone = |msg: &str| { + let arc = repo.vfs().store(); + let mut s = arc.lock().unwrap(); + let snap = s.get_snapshot(&base).unwrap(); + s.put(scl_core::Object::Snapshot(scl_core::Snapshot { + root: snap.root, + parents: vec![base], + author: "t".into(), + timestamp: snap.timestamp, + message: msg.into(), + secrets: Default::default(), + protection: Default::default(), + })) + .unwrap() + }; + // Each session's base is reachable from no ref: only its manifest keeps it. + let mut tips = Vec::new(); + for name in [None, Some("a"), Some("b")] { + let tip = standalone(name.unwrap_or("plain")); + crate::refs::write_branch_tip(repo.layout(), "main", &tip).unwrap(); + repo.ws_fork(name, 1, "t", None).unwrap(); + tips.push((name, tip)); + } + crate::refs::write_branch_tip(repo.layout(), "main", &base).unwrap(); + + let has = |tip: &ObjectId| repo.vfs().store().lock().unwrap().contains(tip); + repo.gc(std::time::Duration::from_secs(0)).unwrap(); + assert!( + tips.iter().all(|(_, t)| has(t)), + "every open base survives gc" + ); + + repo.ws_abandon(Some("a"), None).unwrap(); + repo.gc(std::time::Duration::from_secs(0)).unwrap(); + for (name, tip) in &tips { + assert_eq!(has(tip), *name != Some("a"), "{name:?}"); + } + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/repo/tests/exec_bit.rs b/crates/repo/tests/exec_bit.rs index 9578d586..87eb06e3 100644 --- a/crates/repo/tests/exec_bit.rs +++ b/crates/repo/tests/exec_bit.rs @@ -211,13 +211,13 @@ fn ws_checkout_keeps_exec_bit() { put(&root, "plain.txt", "p", false); repo.commit("t", "add").unwrap(); - let session = repo.ws_fork(1, "t", None).unwrap(); + let session = repo.ws_fork(None, 1, "t", None).unwrap(); let dir = &session.workspaces[0].dir; assert!(on_disk_exec(dir, "run.sh")); assert!(!on_disk_exec(dir, "plain.txt")); // Harvesting an edit of another file must not demote the script. std::fs::write(dir.join("plain.txt"), "edited").unwrap(); - repo.ws_harvest(None, "t", None).unwrap(); + repo.ws_harvest(None, None, "t", None).unwrap(); assert_eq!(committed(&repo, "run.sh"), FileMode::EXEC); assert_eq!(committed(&repo, "plain.txt"), FileMode::FILE); } diff --git a/demo/run_ws_demo.sh b/demo/run_ws_demo.sh index 008ef78d..0e4004d8 100755 --- a/demo/run_ws_demo.sh +++ b/demo/run_ws_demo.sh @@ -3,7 +3,8 @@ # edit across separate `sc` process invocations, list, cumulative # auto-merge harvest (some workspaces land, a conflicting one falls back), # undo/redo of the landings, then manual conflict resolution of the -# fallback branch. Ends with zero `.sc/ws` residue. +# fallback branch, then two named sessions open at once (ADR-0055). Ends +# with zero `.sc/ws*` residue. # # Self-checking: every claim is an assertion; any failure exits non-zero # before the RESULT line. @@ -153,8 +154,59 @@ echo "=== 8: zero residue — .sc/ws does not exist ===" [ -d .sc/ws ] && fail "workspace session directory .sc/ws must not exist after the session ended" echo "no .sc/ws residue ✔" +echo +echo "=== 9: two named sessions open at once (ADR-0055) ===" +fork_a=$("$SC" ws fork --agents 1 --name a --author demo) +fork_b=$("$SC" ws fork --agents 1 --name b --author demo) +dir_a=$(echo "$fork_a" | sed -n 2p | awk '{print $2}') +dir_b=$(echo "$fork_b" | sed -n 2p | awk '{print $2}') +[ -d "$dir_a" ] && [ -d "$dir_b" ] || fail "named session dirs missing: $dir_a $dir_b" +case "$dir_a" in */.sc/ws-a/1) ;; *) fail "session a must live in .sc/ws-a: $dir_a" ;; esac +printf 'from a\n' > "$dir_a/shared.txt" +printf 'only a\n' > "$dir_a/only-a.txt" +printf 'from b\n' > "$dir_b/shared.txt" +printf 'only b\n' > "$dir_b/only-b.txt" + +list_all=$("$SC" ws list) +case "$list_all" in *"session a base:"*"session b base:"*) ;; *) fail "list must show both sessions: $list_all" ;; esac +echo "sc ws list shows both named sessions ✔" + +# With no unnamed session open, an unqualified command must not guess. +if "$SC" ws harvest --author demo >/dev/null 2>"$work/err.txt"; then + fail "harvest without --session must fail when only named sessions are open" +fi +grep -q "pass --session" "$work/err.txt" || fail "error must point at --session: $(cat "$work/err.txt")" +echo "an unqualified harvest refuses instead of guessing ✔" + +# sc ws run releases the repo lock: another sc process works while it runs. +inner=$("$SC" ws run --session a 1 -- "$SC" ws list --session b) +case "$inner" in *"session b base:"*) ;; *) fail "sc inside a running ws command must see session b: $inner" ;; esac +label=$("$SC" ws run --session b 1 -- sh -c 'printf %s "$SC_WORKSPACE"') +[ "$label" = "b-1" ] || fail "SC_WORKSPACE must be b-1, got $label" +echo "another sc ran inside a running ws command; SC_WORKSPACE is b-1 ✔" + +# First harvest wins: b lands, a conflicts on shared.txt and falls back to a-1. +"$SC" ws harvest --session b --author demo | grep -q "landed" || fail "session b must land" +test -f only-b.txt || fail "b's file must be on main" +[ "$(cat shared.txt)" = "from b" ] || fail "main must carry b's shared.txt" +set +e +a_out=$("$SC" ws harvest --session a --author demo) +a_rc=$? +set -e +echo "$a_out" +[ "$a_rc" -eq 1 ] || fail "conflicting second harvest must exit 1, got $a_rc" +case "$a_out" in *"fallback: branch a-1"*) ;; *) fail "session a must fall back to a-1: $a_out" ;; esac +[ "$(cat shared.txt)" = "from b" ] || fail "fallback must leave main untouched" +test -f only-a.txt && fail "a's file must not be on main" +echo "first harvest won, the second fell back to a-1 ✔" + +for d in .sc/ws .sc/ws-a .sc/ws-b; do + [ -d "$d" ] && fail "$d must not exist after both sessions ended" +done +echo "no .sc/ws* residue ✔" echo echo "RESULT: durable multi-invocation ws session — fork/edit/list across separate" echo "sc invocations, cumulative auto-merge harvest (2 landed, 1 fallback, exit 1)," echo "undo/redo of the landings, manual conflict resolution of the fallback branch," -echo "zero .sc/ws residue ✔" +echo "zero .sc/ws residue ✔; then two named sessions open at once, first-wins" +echo "harvest with a-1 fallback, ws run not holding the repo lock ✔" From a13747afc075abcb8f42a6db315b0322b52e2ea0 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 19:56:10 +0300 Subject: [PATCH 3/7] docs: sync CLAUDE.md, ROADMAP, ARCHITECTURE, README and sc-cli-reference with named ws sessions (ref #215) --- .claude/skills/sc-cli-reference/SKILL.md | 23 +++++++++++++++-------- ARCHITECTURE.md | 17 +++++++++++++++-- CLAUDE.md | 14 ++++++++++---- README.md | 4 ++-- ROADMAP.md | 19 +++++++++++++++---- 5 files changed, 57 insertions(+), 20 deletions(-) diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 3e93947c..979ce262 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -159,19 +159,26 @@ cargo run --bin sc -- work --agents 3 [--name ] -- # fork agent wo # (--with-secrets --identity injects # decrypted secrets into each agent env) bash demo/run_work_demo.sh # parallel-agents round-trip proof -cargo run --bin sc -- ws fork --agents N [--identity ] # durable multi-invocation +cargo run --bin sc -- ws fork --agents N [--name ] [--identity ] # durable multi-invocation # session: materializes N checkouts under - # .sc/ws// and persists a manifest (P20) -cargo run --bin sc -- ws list # open session's workspaces, changed/unchanged -cargo run --bin sc -- ws run [--with-secrets --identity ] -- # run in + # .sc/ws// and persists a manifest (P20). + # --name opens a further named session in + # .sc/ws-/ beside the unnamed one (ADR-0055); + # a name already open is refused +cargo run --bin sc -- ws list [--session ] # every open session's workspaces, changed/unchanged + # (or just session 's) +cargo run --bin sc -- ws run [--session ] [--with-secrets --identity ] -- # run in # workspace i (SC_WORKSPACE/SC_WORKSPACE_DIR set) -cargo run --bin sc -- ws harvest [--into ] [--identity ] # probe + auto-merge +cargo run --bin sc -- ws harvest [--session ] [--into ] [--identity ] # probe + auto-merge # every live workspace onto the landing branch # (default the session's base branch, which must # be checked out); clean lands cumulatively, - # conflicts fall back to work- (always `work`; - # `--name` is `sc work` only) -cargo run --bin sc -- ws abandon [] # drop one workspace or the whole session + # conflicts fall back to work- (- for a + # named session); with several sessions the first + # harvest wins, a later conflicting one falls back. + # Omitting --session means the unnamed session, + # never a guessed named one +cargo run --bin sc -- ws abandon [--session ] [] # drop one workspace or the whole session bash demo/run_ws_demo.sh # multi-invocation session + auto-merge proof (P20) cargo run --bin sc -- cherry-pick [--identity ] # replay one commit onto the # current branch (--identity as above) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 8ea729d1..740cc9af 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -346,11 +346,11 @@ phases but the shape is stable: - `promisor-lazy` — empty marker: this partial clone may fill gaps by object id (P37a); `sparse-prev` — the previous sparse spec while a `sparse set` is in flight (P37b). -- `local-key`, `protected-cache` (and `ws/cache-`) — the P33 keyed stat cache +- `local-key`, `protected-cache` (and `ws/cache-`, `ws-/cache-`) — the P33 keyed stat cache for protected paths; never committed, never transferred. - `tmp/` — guard-cleaned scratch for streaming pack transfer (P25). - `ws/` — durable agent-session workspaces: `session.toml` manifest + per-agent - checkouts (P20). `git-remotes//` — the `git_oid ↔ sc_id` marks map and a + checkouts (P20); `ws-/` — the same for a named session (ADR-0055). `git-remotes//` — the `git_oid ↔ sc_id` marks map and a lazily-built bare `mirror.git` for network Git (P10/P18). - Transient in-progress state (removed on completion/abort): `MERGE_HEAD`, `PICK_HEAD`, `REBASE_STATE`, and their `*_DECIDED_ROOT` records, plus @@ -781,6 +781,19 @@ guard family as a ref-mover. directory, so a crash between the two never strands a `live = true` entry pointing at a directory that no longer exists. See ADR-0030. +Named sessions (ADR-0055). `sc ws fork --name ` opens a further session in a +sibling root, `.sc/ws-/` (manifest, `/` checkouts and `cache-` inside), +so the unnamed session's layout is untouched and tearing one session down never +touches another. `list`/`run`/`harvest`/`abandon` take `--session `; without +it they mean the unnamed session and never guess a named one. Fallback branches +and `SC_WORKSPACE` are `-` (`work-` unnamed). The repo lock serializes +every `sc` command, so harvests of different sessions run one at a time in +invocation order: the first lands, a later one merges over it or falls back. +`sc ws run` resolves its workspace and secret environment under the lock, then +releases it before spawning the command (`WsRunPlan`), so other sessions stay +usable while an agent runs. gc roots every open session's base snapshot. +Workspace refresh is designed in the ADR and not built. + ## Phase 21 — hardening & consolidation sweep (built) No new capability axis — a sweep closing the P16–P20 review tail. Every diff --git a/CLAUDE.md b/CLAUDE.md index bb2bde70..68f7bc56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,7 +135,7 @@ the code, those win. | P17 | `sc rewrap`: one-commit bulk cutover of secrets + protected wrap lists to current recipients/escrow; escrow is a managed list; `--rotate` also re-seals every protected blob under a fresh key | [0027](docs/adr/0027-bulk-rewrap-and-multi-escrow.md), [0051](docs/adr/0051-rotate-protected-paths.md) | | P18 | Hosted Git (GitHub https/ssh) via system-git mirror bridge (`SC_GIT` overrides); auth delegated to git | [0028](docs/adr/0028-network-git-remotes.md) | | P19 | Resumable rebase (stop → resolve → `--continue`; one oplog record total), `cherry-pick --abort`/`--mainline `, `sc amend` | [0029](docs/adr/0029-history-editing-polish.md) | -| P20 | Durable multi-invocation agent sessions: `sc ws fork/list/run/harvest/abandon` under `.sc/ws/`; harvest auto-merges, conflicts fall back to `work-` | [0030](docs/adr/0030-agent-sessions-and-automerge.md) | +| P20 | Durable multi-invocation agent sessions: `sc ws fork/list/run/harvest/abandon` under `.sc/ws/`; harvest auto-merges, conflicts fall back to `work-`. `fork --name ` opens a further named session in `.sc/ws-/` (`--session ` on the other verbs; fallback branches and `SC_WORKSPACE` are `-`); sessions are harvested independently, first harvest wins; `ws run` releases the repo lock while the command runs; refresh is designed, not built (#215) | [0030](docs/adr/0030-agent-sessions-and-automerge.md), [0055](docs/adr/0055-named-concurrent-ws-sessions.md) | | P21 | Hardening sweep: in-progress guards on all policy ops, git-marks self-heal, abort protected-skip parity, ws `"landed"` status | [0031](docs/adr/0031-hardening-consolidation.md) | | P22 | Signed commits: v2 identities (one seed → X25519 + Ed25519), signatures as CAS objects, `sc sign`/`sc verify [--require]` | [0032](docs/adr/0032-signed-commits-provenance.md) | | P23 | `sc conflicts`/`sc resolve --ours\|--theirs`: whole-file conflict resolution without hand-edited markers | [0033](docs/adr/0033-merge-ergonomics.md) | @@ -209,7 +209,7 @@ transport-adjacent. The rest, imperatively: to randomized, or with `--rotate`; only a plain rewrap over an all-randomized tip is policy-only. - **`.sc/local-key` and the per-checkout protected caches - (`.sc/protected-cache`, `.sc/ws/cache-`) are never committed and never + (`.sc/protected-cache`, `/cache-`) are never committed and never transferred.** Cache saves are best-effort and ordered after ref moves; a cache failure may cause a spurious re-seal but never incorrectness. The key is owner-only on unix only; non-unix keeps default permissions and warns once @@ -275,7 +275,13 @@ transport-adjacent. The rest, imperatively: safe (reconstructed on next use). Stale marks self-heal on push/export. - **`sc ws harvest` lands on the currently-checked-out branch** (default the session's base; `--into` must also be checked out) — it refuses with a - `sc switch` hint otherwise. + `sc switch` hint otherwise. Several `sc ws` sessions may be open (the unnamed + one in `.sc/ws/`, named ones in `.sc/ws-/`); `list`/`run`/`harvest`/ + `abandon` take `--session ` and never guess a named session when none + is given. Harvests of different sessions run one at a time (repo lock), in + invocation order: the first lands, a later conflicting one falls back to + `-`. Do not run a pre-ADR-0055 `sc` against a repo with named + sessions open (its gc would not root their bases). - **A stopped merge/pick/rebase lists the paths it wrote as plaintext in `.sc/CONFLICT_PLAINTEXT`.** Protected conflict text never enters the CAS, so no tree records it; completion treats a listed path absent from disk as deleted, @@ -304,7 +310,7 @@ transport-adjacent. The rest, imperatively: Deferred work is tracked in **`ROADMAP.md` → Deferred** (single source of truth — do not re-list items here); entries that name an issue mirror the open -GitHub issues. Standing entries: named/concurrent `sc ws` sessions (#215), +GitHub issues. Standing entries: `sc ws` workspace refresh (#215), blob-size clone filters (#217), bucket compaction and gc (#216), the non-unix `.sc/local-key` ACL (#214), transcript-drop delivery gaps (#230), and the open sparse, private-branch and abort edge cases (#241, #246, #247, #248). diff --git a/README.md b/README.md index edb031f2..7f478bee 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ and Git (including hosted GitHub) network transports, plus private branches sealed to a recipient set until publish and a read-only Tauri desktop browser. All 36 phases and P37a-37d are implemented and tested; `demo/` holds 27 independent end-to-end proofs, one per major capability. Remaining -follow-ons (transcript drop delivery gaps, bucket compaction and gc, named -concurrent `sc ws` sessions, size/count clone filters, and similar hardening +follow-ons (transcript drop delivery gaps, bucket compaction and gc, `sc ws` +workspace refresh, size/count clone filters, and similar hardening items) are tracked in [ROADMAP.md](ROADMAP.md)'s Deferred section and as open GitHub issues rather than being open MVP scope. diff --git a/ROADMAP.md b/ROADMAP.md index c21a54c4..2a2104dd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -190,7 +190,15 @@ across every phase. the session's base snapshot gated on manifest presence. Proven by `demo/run_ws_demo.sh` (fork/edit/harvest across separate invocations: two cumulative clean auto-merges, one conflict fallback, an `sc undo` - of a landing, zero residue at session end). (ADR-0030.) + of a landing, zero residue at session end). (ADR-0030.) Follow-on (#215, + ADR-0055): `sc ws fork --name ` opens further named sessions beside the + unnamed one, each in `.sc/ws-/` with its own manifest and caches + (`--session ` on `list`/`run`/`harvest`/`abandon`; fallback branches and + `SC_WORKSPACE` are `-`); the unnamed layout is unchanged, no migration. + Harvests of different sessions are serialized by the repo lock and land in + invocation order (first wins, a later conflict falls back); `sc ws run` + releases the repo lock while its command runs, so other sessions stay usable. + Workspace refresh is designed in ADR-0055 and still deferred. - **Phase 21 — Hardening & consolidation.** Closes the P16–P20 review tail with no new capability axis. Every commit-creating policy op (`protect`/`grant`/`revoke`/`secret add`/`secret rotate`/`secret @@ -750,9 +758,12 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in - **Remaining history-editing depth:** operation objects in the CAS (Jujutsu-deep upgrade to the file oplog), oplog entries for remote-tracking refs. -- **Named/multiple concurrent ws sessions (#215, P20).** P20 ships one unnamed - session per repo; named or concurrent sessions and workspace re-fork/refresh - from a newer tip need a design decision first. +- **`sc ws` workspace refresh (#215, P20).** Named and concurrent sessions + shipped (ADR-0055). Moving a live workspace onto a newer tip is designed there + (replay the workspace's commit with the ADR-0049 engine, refuse on any + conflict, re-materialize under the recorded view) but not built: it needs a + headless merge-into-tree entry point and a re-materialize that keeps files an + agent may have open. Abandon and re-fork covers it meanwhile. - **Transcript drop delivery gaps (#230, ADR-0038 addendum).** A tombstone is not sent after the dropper's gc removed its snapshot, and a tombstone a push-only remote received before trusting the signer is not re-evaluated From f8b54ca91f1acd13499e4f785395dd206da66d9a Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 20:06:35 +0300 Subject: [PATCH 4/7] fix(repo,cli): block harvest/abandon while ws run is live; validate --session; skip stray ws-* entries (ref #215) --- crates/cli/src/main.rs | 5 +- crates/cli/tests/ws_sessions.rs | 4 +- crates/repo/src/lock.rs | 2 +- crates/repo/src/ws.rs | 154 +++++++++++++++++- docs/THREAT-MODEL.md | 5 +- docs/adr/0055-named-concurrent-ws-sessions.md | 7 +- 6 files changed, 166 insertions(+), 11 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a141eeeb..3cf68346 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -786,7 +786,8 @@ enum WsOp { /// Read-only conflict probe + cumulative auto-merge of every live /// workspace onto the landing branch (default: the session's base /// branch). Conflicted/rejected workspaces fall back to a `work-` - /// branch for manual resolution and keep the session open. + /// branch (`-` for a named session) for manual resolution and + /// keep the session open. Harvest { /// Session to address: the name given to `sc ws fork --name`. Omit /// for the unnamed session. @@ -3541,7 +3542,7 @@ fn run_ws(op: WsOp) -> Result<()> { } scl_repo::WsHarvestOutcome::Rejected { index, report } => { failed = true; - println!("{index:<3} REJECTED by secret scanner: {report} — fix and re-run `sc ws harvest`"); + println!("{index:<3} REJECTED by secret scanner: {report} — fix and re-run `sc ws harvest{}`", session.as_deref().map(|n| format!(" --session {n}")).unwrap_or_default()); } } } diff --git a/crates/cli/tests/ws_sessions.rs b/crates/cli/tests/ws_sessions.rs index 8b3f2698..608f4856 100644 --- a/crates/cli/tests/ws_sessions.rs +++ b/crates/cli/tests/ws_sessions.rs @@ -138,7 +138,9 @@ fn a_running_session_does_not_block_the_others() { let argv = inside(args); let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); let out = ok(&root, &argv); - assert!(!out.is_empty(), "{args:?}"); + if args[1] == "list" { + assert!(out.contains("session b base:"), "{out}"); + } } assert!( root.join("from-b.txt").exists(), diff --git a/crates/repo/src/lock.rs b/crates/repo/src/lock.rs index 9a24d25a..f341e0e4 100644 --- a/crates/repo/src/lock.rs +++ b/crates/repo/src/lock.rs @@ -57,7 +57,7 @@ impl RepoLock { /// True only when the lock file names a PID we can *prove* is not running. /// Unreadable file, no parseable PID, or an inconclusive probe all return /// false (respect the lock). -fn holder_is_dead(path: &std::path::Path) -> bool { +pub(crate) fn holder_is_dead(path: &std::path::Path) -> bool { let Ok(text) = std::fs::read_to_string(path) else { return false; }; diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index bb405d79..f5925582 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -92,6 +92,33 @@ fn label_prefix(name: Option<&str>) -> &str { name.unwrap_or("work") } +/// `/running-`: written (with the pid of the `sc` process +/// that owns the command) while a `sc ws run` command is live in workspace `i`, +/// so harvest and abandon, which now work while the command runs, can refuse +/// instead of landing a half-written checkout or deleting it under the agent. +/// Beside the checkout dir, never inside it, like the stat cache. +fn running_path(layout: &Layout, name: Option<&str>, i: u32) -> PathBuf { + ws_dir(layout, name).join(format!("running-{i}")) +} + +/// Refuse if a `sc ws run` command is still live in workspace `i`. A marker +/// left by a process that is provably dead (killed before it could remove it) +/// is cleared, using the same probe as the repo lock. +fn ensure_idle(layout: &Layout, name: Option<&str>, i: u32) -> Result<()> { + let path = running_path(layout, name, i); + if path.exists() { + if !crate::lock::holder_is_dead(&path) { + return Err(Error::InvalidArgument(format!( + "workspace {i} has a `sc ws run` command still running ({}); \ + wait for it to exit", + path.display() + ))); + } + let _ = std::fs::remove_file(&path); + } + Ok(()) +} + /// A session name is a branch-name component (its fallback branches are /// `-`) and a directory name under `.sc/`, so it takes the branch-name /// grammar. @@ -185,6 +212,10 @@ impl SessionToml { /// Read one session's manifest (`None` = the unnamed session), if open. pub(crate) fn read_manifest(layout: &Layout, name: Option<&str>) -> Result> { + if let Some(n) = name { + // `--session` reaches here unchecked; a `..` must not leave `.sc/`. + validate_session_name(n)?; + } match std::fs::read_to_string(manifest_path(layout, name)) { Ok(text) => { let raw: SessionToml = @@ -203,9 +234,13 @@ pub(crate) fn list_sessions(layout: &Layout) -> Result> { let mut out: Vec = read_manifest(layout, None)?.into_iter().collect(); let mut names = Vec::new(); for e in std::fs::read_dir(&layout.dot_sc)? { - let file = e?.file_name(); + let e = e?; + let file = e.file_name(); + // A stray file or oddly named entry must not break gc or `ws list`. if let Some(n) = file.to_str().and_then(|f| f.strip_prefix("ws-")) { - names.push(n.to_string()); + if e.path().is_dir() && validate_session_name(n).is_ok() { + names.push(n.to_string()); + } } } names.sort(); @@ -479,6 +514,14 @@ impl Repo { /// remaining live count. No oplog record — fork never touched a ref. pub fn ws_abandon(&self, name: Option<&str>, index: Option) -> Result { let mut session = open_session(self.layout(), name)?; + // Refuse before removing anything if an agent command is live. + for e in session + .workspaces + .iter() + .filter(|e| e.live && index.is_none_or(|i| i == e.index)) + { + ensure_idle(self.layout(), name, e.index)?; + } match index { Some(i) => { let entry = session @@ -555,7 +598,14 @@ impl Repo { } else { Vec::new() }; + // Mark the workspace busy until the command ends (see `running_path`). + // The marker names this process, which outlives the repo handle: the + // CLI keeps running the command after dropping the lock. + ensure_idle(self.layout(), name, index)?; + let marker = running_path(self.layout(), name, index); + std::fs::write(&marker, std::process::id().to_string())?; Ok(WsRunPlan { + marker, dir: entry.dir.clone(), // Label matches the fallback-branch namespace a harvest would mint // (P13 parity: label == branch name). @@ -753,6 +803,11 @@ impl Repo { .map(|e| e.index) .collect(); live_indices.sort_unstable(); + // A workspace whose `sc ws run` command is still live is mid-edit: + // refuse before reading or minting anything. + for &i in &live_indices { + ensure_idle(self.layout(), name, i)?; + } // Preflight: if any live workspace actually diverged, a candidate // branch is about to be minted for it and landed via @@ -1034,6 +1089,8 @@ fn resolve_and_teardown( /// injected secrets. Holds no repo handle, so running it does not hold the /// repo lock. pub struct WsRunPlan { + /// The `running-` marker; removed when the plan is dropped. + marker: PathBuf, dir: PathBuf, label: String, envs: Vec<(String, std::ffi::OsString)>, @@ -1042,7 +1099,7 @@ pub struct WsRunPlan { impl WsRunPlan { /// Spawn `cmd` in the workspace dir with `SC_WORKSPACE` and /// `SC_WORKSPACE_DIR` set and return its exit code. - pub fn run(&self, cmd: &[String]) -> Result { + pub fn run(self, cmd: &[String]) -> Result { let (exe, args) = cmd .split_first() .ok_or_else(|| Error::InvalidArgument("empty command".into()))?; @@ -1059,6 +1116,12 @@ impl WsRunPlan { } } +impl Drop for WsRunPlan { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.marker); + } +} + /// Outcome of harvesting one live workspace. #[derive(Debug)] pub enum WsHarvestOutcome { @@ -2525,4 +2588,89 @@ mod tests { drop(repo); std::fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn a_running_command_blocks_harvest_and_abandon_of_its_workspace_only() { + let root = tmp_root("named-busy"); + let repo = init(&root); + fork_and_edit(&repo, Some("a"), "file-a.txt", "A\n"); + fork_and_edit(&repo, Some("b"), "file-b.txt", "B\n"); + + let plan = repo.ws_run_plan(Some("a"), 1, false, None).unwrap(); + let busy = |e: Error| match e { + Error::InvalidArgument(m) => assert!(m.contains("still running"), "{m}"), + other => panic!("{other:?}"), + }; + busy(repo.ws_harvest(Some("a"), None, "t", None).unwrap_err()); + busy(repo.ws_abandon(Some("a"), None).unwrap_err()); + busy(repo.ws_abandon(Some("a"), Some(1)).unwrap_err()); + // A second run in the same workspace is refused too. + busy(repo.ws_run_plan(Some("a"), 1, false, None).err().unwrap()); + // Nothing was touched, and the other session is unaffected. + assert!(repo.ws_session(Some("a")).unwrap().unwrap().workspaces[0].live); + let out = repo.ws_harvest(Some("b"), None, "t", None).unwrap(); + assert!(matches!(out[..], [WsHarvestOutcome::Landed { .. }])); + + // Once the command is over, the workspace harvests normally. + assert_eq!(plan.run(&["true".into()]).unwrap(), 0); + let out = repo.ws_harvest(Some("a"), None, "t", None).unwrap(); + assert!(matches!(out[..], [WsHarvestOutcome::Landed { .. }])); + + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn dropping_an_unused_run_plan_releases_the_workspace() { + let root = tmp_root("named-busy-drop"); + let repo = init(&root); + repo.ws_fork(None, 1, "t", None).unwrap(); + drop(repo.ws_run_plan(None, 1, false, None).unwrap()); + assert_eq!(repo.ws_abandon(None, None).unwrap(), 0); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[cfg(unix)] + #[test] + fn a_run_marker_from_a_dead_process_is_cleared() { + let root = tmp_root("named-busy-stale"); + let repo = init(&root); + repo.ws_fork(None, 1, "t", None).unwrap(); + // The pid of a child that has already exited. + let mut child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id(); + child.wait().unwrap(); + std::fs::write(running_path(repo.layout(), None, 1), pid.to_string()).unwrap(); + assert_eq!(repo.ws_abandon(None, None).unwrap(), 0); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn session_names_from_the_command_line_cannot_leave_the_sc_dir() { + let root = tmp_root("named-escape"); + let repo = init(&root); + repo.ws_fork(Some("a"), 1, "t", None).unwrap(); + for bad in ["a/../../ws", "../x", ".."] { + assert!(matches!( + repo.ws_abandon(Some(bad), None), + Err(Error::InvalidArgument(_)) + )); + assert!(repo.ws_session(Some(bad)).is_err()); + } + // A stray file or oddly named entry does not hide the real sessions. + std::fs::write(repo.layout().dot_sc.join("ws-stray"), "x").unwrap(); + std::fs::create_dir(repo.layout().dot_sc.join("ws-.hidden")).unwrap(); + let names: Vec<_> = repo + .ws_sessions() + .unwrap() + .into_iter() + .map(|s| s.name) + .collect(); + assert_eq!(names, [Some("a".to_string())]); + repo.gc(std::time::Duration::from_secs(0)).unwrap(); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 5d73de0d..09cc2e11 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -521,7 +521,10 @@ too, not just the src-control-side metadata. reach: an agent is a same-user process that can read the host repository's store and working tree and, on a lazy clone, fetch more (`sc sparse set`, `sc cat`, `sc backfill`). It is not an isolation boundary (compare Secret - injection). + injection). A command run by `sc ws run` + no longer holds the repo lock (ADR-0055), so an `sc` it runs from inside the + workspace finds the host repo and can change it, as a hand-started agent always + could. - **Operations that need a complete closure refuse on a partial clone, fail closed:** `sc export`, `sc rewrap`, `sc grant`/`revoke`, private branches, and `sc push` to a git remote. They refuse rather than run on partial data. diff --git a/docs/adr/0055-named-concurrent-ws-sessions.md b/docs/adr/0055-named-concurrent-ws-sessions.md index 28993e20..615b104c 100644 --- a/docs/adr/0055-named-concurrent-ws-sessions.md +++ b/docs/adr/0055-named-concurrent-ws-sessions.md @@ -17,7 +17,7 @@ Reading the code turned up one fact that shapes the design. `Repo::open` takes t 2. **Addressing.** A session is picked with `--session ` on `list`, `run`, `harvest` and `abandon`; a workspace inside it stays addressed by its index (`run `, `abandon []`). With no `--session` the command means the unnamed session. It never guesses a named one: if only named sessions are open, the error lists them and says to pass `--session`. `sc ws list` with no flag prints every open session (the unnamed one first, then named ones sorted by name); the unnamed session's header line is unchanged. -3. **On-disk layout: no migration.** The unnamed session keeps `.sc/ws/session.toml`, `.sc/ws//` and `.sc/ws/cache-`, byte for byte. A named session lives in a sibling root, `.sc/ws-/`, with the same inner shape. A sibling and not a child, so every teardown (`remove_dir_all` of a session root on abandon, harvest end and fork-residue cleanup) touches only its own session, and no reserved names are needed inside a root. The manifest format is unchanged; the session name is derived from the directory and never stored. A `.sc/ws-*` directory without a manifest is crash residue and is ignored. +3. **On-disk layout: no migration.** The unnamed session keeps `.sc/ws/session.toml`, `.sc/ws//` and `.sc/ws/cache-`, byte for byte. A named session lives in a sibling root, `.sc/ws-/`, with the same inner shape. A sibling and not a child, so every teardown (`remove_dir_all` of a session root on abandon, harvest end and fork-residue cleanup) touches only its own session, and no reserved names are needed inside a root. The manifest format is unchanged; the session name is derived from the directory and never stored. A `.sc/ws-*` entry that is not a directory, whose name is not a valid session name, or that has no manifest is ignored (crash residue or a stray file), so it cannot break `list` or gc. A name given with `--session` is validated before any path is built, so `..` cannot leave `.sc/`. On a case-insensitive filesystem `A` and `a` are the same directory: forking `A` while `a` is open is refused, but `--session A` addresses `a` and names its fallback branches `A-`. - Downgrade hazard: a binary from before this change does not look at `.sc/ws-*`, so its `sc gc` would not root a named session's base snapshot. Do not run an old `sc` against a repo with named sessions open. 4. **Fallback branches and labels follow the name.** The unnamed session still falls back to `work-`. A named session falls back to `-`, and `SC_WORKSPACE` is the same string, matching `sc work --name` and the ADR-0030 rule that the label equals the branch name. The existing collision suffix (`-2`, `-3`) still applies, so a clash across sessions (for example a session named `work`) cannot overwrite a branch. The candidate commit message is `ws- harvest` (unnamed) or `ws - harvest`. @@ -27,7 +27,8 @@ Reading the code turned up one fact that shapes the design. `Repo::open` takes t - **Outcome rule.** Within a session, workspaces land in ascending index order (ADR-0030). Across sessions, the order is the order the harvests are invoked: the first lands, a later one merges cleanly over it or, when its change conflicts, falls back to its own `-` branch and leaves the landing branch untouched. Disjoint edits land to the same tree in either order; overlapping edits go to whoever harvests first. There is no implicit ordering and no `harvest --all`; a script that wants a fixed order calls `harvest --session` in that order. - Each session has its own manifest, so no manifest is shared between sessions. Abandoning or harvesting one session never writes another's files. - **`sc ws run` no longer holds the lock while the command runs.** `Repo::ws_run_plan` resolves the live workspace, its label and (with `--with-secrets`) the decrypted environment under the lock; the CLI drops the repo and then spawns the command (`WsRunPlan::run`). Other sessions can be listed, harvested or abandoned meanwhile. `Repo::ws_run` stays as the two steps together for library callers. - - Abandoning a workspace under a running agent removes its directory; the agent sees its files vanish. That is the caller's choice, as it was before. + - **A live command marks its workspace busy.** Because the lock is no longer held, harvest and abandon could now run against a workspace an agent is still writing. `ws_run_plan` therefore writes `/running-` (the owning `sc` pid, beside the checkout like the cache) and `WsRunPlan` removes it when the command ends or the plan is dropped. Harvest and abandon of that session refuse before reading or removing anything while a marker's holder is alive; a marker whose process is provably dead is cleared (the `RepoLock` probe; on non-unix it stays, and the error names the file). A second `ws run` in the same workspace is refused. Other workspaces and sessions are unaffected. The marker covers `sc ws run` only: an agent started by hand in the checkout directory, as ADR-0030 always allowed, is not tracked. + - **A command in a workspace can reach the host repo.** A workspace lives under the host's `.sc/`, so `sc` run from inside it finds the host repo (`Layout::discover` walks up). With the lock released, such a command can now succeed (before, it failed with `Locked`), and `sc commit` or `sc switch` there acts on the host working tree and branches. A hand-started agent already had this. The tool does not guard against it; it is not an isolation boundary (compare ADR-0050). 6. **Protected caches.** `Layout::ws_cache_path(session, i)` is `/cache-`, beside the checkout like before, so each session's stat caches live and die with that session. Nothing else about ADR-0043 changes: the cache is never committed or transferred, and a lost cache costs a re-seal, not correctness. @@ -68,4 +69,4 @@ It is deferred, not rejected, for these reasons: ## Tests -`ws.rs`: named and unnamed sessions coexist in separate roots with their own cache paths; collisions and invalid names are refused; addressing a missing session lists what is open and never guesses; the first of two conflicting harvests wins and the second falls back to `-1`, in both orders; disjoint sessions land to the same tree in either order; abandoning one session leaves another's checkout, edit and manifest intact and still runnable and harvestable; `SC_WORKSPACE` and fallback branches carry the name and are suffixed on a clash; gc roots every open base. `partial_sessions.rs`: two named sessions on a partial clone see only the view, land one after the other, and carry `docs/` unread. `crates/cli/tests/ws_sessions.rs`: the same through the binary, plus listing and harvesting another session from inside a running `sc ws run`. `demo/run_ws_demo.sh` gains a named-sessions section. +`ws.rs`: named and unnamed sessions coexist in separate roots with their own cache paths; collisions and invalid names are refused; addressing a missing session lists what is open and never guesses; the first of two conflicting harvests wins and the second falls back to `-1`, in both orders; disjoint sessions land to the same tree in either order; abandoning one session leaves another's checkout, edit and manifest intact and still runnable and harvestable; `SC_WORKSPACE` and fallback branches carry the name and are suffixed on a clash; gc roots every open base; a live `ws run` blocks harvest and abandon of its own session only, a dropped plan or a dead holder releases it; a `--session` with path components is refused, and a stray `.sc/ws-*` file does not break listing or gc. `partial_sessions.rs`: two named sessions on a partial clone see only the view, land one after the other, and carry `docs/` unread. `crates/cli/tests/ws_sessions.rs`: the same through the binary, plus listing and harvesting another session from inside a running `sc ws run`. `demo/run_ws_demo.sh` gains a named-sessions section. From 95b6da866c0d12620d8d3c88d2c7189604b7e01e Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 20:35:10 +0300 Subject: [PATCH 5/7] fix(repo): track the ws run child in the busy marker and create it exclusively (ref #215) --- crates/repo/src/lock.rs | 5 ++ crates/repo/src/ws.rs | 70 +++++++++++++++++-- docs/adr/0055-named-concurrent-ws-sessions.md | 2 +- 3 files changed, 70 insertions(+), 7 deletions(-) diff --git a/crates/repo/src/lock.rs b/crates/repo/src/lock.rs index f341e0e4..5b2c667c 100644 --- a/crates/repo/src/lock.rs +++ b/crates/repo/src/lock.rs @@ -64,6 +64,11 @@ pub(crate) fn holder_is_dead(path: &std::path::Path) -> bool { let Ok(pid) = text.trim().parse::() else { return false; }; + pid_is_dead(pid) +} + +/// True only when `pid` is provably not running (see [`holder_is_dead`]). +pub(crate) fn pid_is_dead(pid: u32) -> bool { if pid == std::process::id() { return false; // our own pid: definitely alive } diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index f5925582..179f829e 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -101,13 +101,20 @@ fn running_path(layout: &Layout, name: Option<&str>, i: u32) -> PathBuf { ws_dir(layout, name).join(format!("running-{i}")) } -/// Refuse if a `sc ws run` command is still live in workspace `i`. A marker -/// left by a process that is provably dead (killed before it could remove it) -/// is cleared, using the same probe as the repo lock. +/// Refuse if a `sc ws run` command is still live in workspace `i`. The marker +/// names the `sc` process and, once spawned, its child (an orphaned child keeps +/// the workspace busy after `sc` is killed). It is cleared only when every +/// recorded pid is provably dead (the repo lock's probe); an unreadable or +/// empty marker counts as busy. fn ensure_idle(layout: &Layout, name: Option<&str>, i: u32) -> Result<()> { let path = running_path(layout, name, i); if path.exists() { - if !crate::lock::holder_is_dead(&path) { + let pids: Vec = std::fs::read_to_string(&path) + .unwrap_or_default() + .split_whitespace() + .filter_map(|p| p.parse().ok()) + .collect(); + if pids.is_empty() || !pids.iter().all(|&p| crate::lock::pid_is_dead(p)) { return Err(Error::InvalidArgument(format!( "workspace {i} has a `sc ws run` command still running ({}); \ wait for it to exit", @@ -603,7 +610,24 @@ impl Repo { // CLI keeps running the command after dropping the lock. ensure_idle(self.layout(), name, index)?; let marker = running_path(self.layout(), name, index); - std::fs::write(&marker, std::process::id().to_string())?; + // Exclusive, so two plans for one workspace cannot both hold it. + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&marker) + { + Ok(mut f) => { + std::io::Write::write_all(&mut f, std::process::id().to_string().as_bytes())? + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + return Err(Error::InvalidArgument(format!( + "workspace {index} has a `sc ws run` command still running ({}); \ + wait for it to exit", + marker.display() + ))) + } + Err(e) => return Err(e.into()), + } Ok(WsRunPlan { marker, dir: entry.dir.clone(), @@ -1112,7 +1136,14 @@ impl WsRunPlan { for (k, v) in &self.envs { command.env(k, v); } - Ok(command.status()?.code().unwrap_or(1)) + let mut child = command.spawn()?; + // Record the child too: if `sc` is killed first, the orphan keeps the + // workspace busy. Best effort; the parent pid is already in the file. + let _ = scl_core::fsutil::atomic_write_durable( + &self.marker, + format!("{} {}", std::process::id(), child.id()).as_bytes(), + ); + Ok(child.wait()?.code().unwrap_or(1)) } } @@ -2647,6 +2678,33 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } + /// `sc` is killed but the command it started lives on: the workspace stays busy. + #[cfg(unix)] + #[test] + fn an_orphaned_child_keeps_its_workspace_busy() { + let root = tmp_root("named-busy-orphan"); + let repo = init(&root); + repo.ws_fork(None, 1, "t", None).unwrap(); + let mut dead = std::process::Command::new("true").spawn().unwrap(); + let dead_pid = dead.id(); + dead.wait().unwrap(); + let mut orphan = std::process::Command::new("sleep") + .arg("30") + .spawn() + .unwrap(); + std::fs::write( + running_path(repo.layout(), None, 1), + format!("{dead_pid} {}", orphan.id()), + ) + .unwrap(); + assert!(repo.ws_abandon(None, None).is_err(), "child still runs"); + orphan.kill().unwrap(); + orphan.wait().unwrap(); + assert_eq!(repo.ws_abandon(None, None).unwrap(), 0); + drop(repo); + std::fs::remove_dir_all(&root).unwrap(); + } + #[test] fn session_names_from_the_command_line_cannot_leave_the_sc_dir() { let root = tmp_root("named-escape"); diff --git a/docs/adr/0055-named-concurrent-ws-sessions.md b/docs/adr/0055-named-concurrent-ws-sessions.md index 615b104c..23b879e5 100644 --- a/docs/adr/0055-named-concurrent-ws-sessions.md +++ b/docs/adr/0055-named-concurrent-ws-sessions.md @@ -27,7 +27,7 @@ Reading the code turned up one fact that shapes the design. `Repo::open` takes t - **Outcome rule.** Within a session, workspaces land in ascending index order (ADR-0030). Across sessions, the order is the order the harvests are invoked: the first lands, a later one merges cleanly over it or, when its change conflicts, falls back to its own `-` branch and leaves the landing branch untouched. Disjoint edits land to the same tree in either order; overlapping edits go to whoever harvests first. There is no implicit ordering and no `harvest --all`; a script that wants a fixed order calls `harvest --session` in that order. - Each session has its own manifest, so no manifest is shared between sessions. Abandoning or harvesting one session never writes another's files. - **`sc ws run` no longer holds the lock while the command runs.** `Repo::ws_run_plan` resolves the live workspace, its label and (with `--with-secrets`) the decrypted environment under the lock; the CLI drops the repo and then spawns the command (`WsRunPlan::run`). Other sessions can be listed, harvested or abandoned meanwhile. `Repo::ws_run` stays as the two steps together for library callers. - - **A live command marks its workspace busy.** Because the lock is no longer held, harvest and abandon could now run against a workspace an agent is still writing. `ws_run_plan` therefore writes `/running-` (the owning `sc` pid, beside the checkout like the cache) and `WsRunPlan` removes it when the command ends or the plan is dropped. Harvest and abandon of that session refuse before reading or removing anything while a marker's holder is alive; a marker whose process is provably dead is cleared (the `RepoLock` probe; on non-unix it stays, and the error names the file). A second `ws run` in the same workspace is refused. Other workspaces and sessions are unaffected. The marker covers `sc ws run` only: an agent started by hand in the checkout directory, as ADR-0030 always allowed, is not tracked. + - **A live command marks its workspace busy.** Because the lock is no longer held, harvest and abandon could now run against a workspace an agent is still writing. `ws_run_plan` therefore creates `/running-` exclusively (beside the checkout like the cache), holding the owning `sc` pid; once the command is spawned the marker also records the child's pid, so an orphaned command keeps the workspace busy after `sc` is killed. `WsRunPlan` removes the marker when the command ends or the plan is dropped. Harvest and abandon of that session refuse before reading or removing anything while any recorded pid is alive or the marker is unreadable; a marker whose pids are all provably dead is cleared (the `RepoLock` probe; on non-unix it stays, and the error names the file). A second `ws run` in the same workspace is refused. Other workspaces and sessions are unaffected. The marker covers `sc ws run` only: an agent started by hand in the checkout directory, as ADR-0030 always allowed, is not tracked. - **A command in a workspace can reach the host repo.** A workspace lives under the host's `.sc/`, so `sc` run from inside it finds the host repo (`Layout::discover` walks up). With the lock released, such a command can now succeed (before, it failed with `Locked`), and `sc commit` or `sc switch` there acts on the host working tree and branches. A hand-started agent already had this. The tool does not guard against it; it is not an isolation boundary (compare ADR-0050). 6. **Protected caches.** `Layout::ws_cache_path(session, i)` is `/cache-`, beside the checkout like before, so each session's stat caches live and die with that session. Nothing else about ADR-0043 changes: the cache is never committed or transferred, and a lost cache costs a re-seal, not correctness. From cb82778d4ff8c78c9e9bced69d3d034c7c278309 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 20:51:12 +0300 Subject: [PATCH 6/7] fix(repo): remove the busy marker if its pid write fails; warn if the child pid cannot be recorded (ref #215) --- crates/repo/src/ws.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index 179f829e..008e982c 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -617,7 +617,13 @@ impl Repo { .open(&marker) { Ok(mut f) => { - std::io::Write::write_all(&mut f, std::process::id().to_string().as_bytes())? + if let Err(e) = + std::io::Write::write_all(&mut f, std::process::id().to_string().as_bytes()) + { + // An empty marker would read as busy forever. + let _ = std::fs::remove_file(&marker); + return Err(e.into()); + } } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { return Err(Error::InvalidArgument(format!( @@ -1139,10 +1145,15 @@ impl WsRunPlan { let mut child = command.spawn()?; // Record the child too: if `sc` is killed first, the orphan keeps the // workspace busy. Best effort; the parent pid is already in the file. - let _ = scl_core::fsutil::atomic_write_durable( + if let Err(e) = scl_core::fsutil::atomic_write_durable( &self.marker, format!("{} {}", std::process::id(), child.id()).as_bytes(), - ); + ) { + eprintln!( + "warning: could not record the command's pid ({e}); the workspace is \ + protected from harvest and abandon only while `sc` itself runs" + ); + } Ok(child.wait()?.code().unwrap_or(1)) } } From a3e8b6e26d345397ccbf5fa9ecad49364803d1c3 Mon Sep 17 00:00:00 2001 From: Toni Bergholm Date: Tue, 20 Oct 2026 21:10:52 +0300 Subject: [PATCH 7/7] docs: renumber the named-sessions ADR to 0056 (ref #215) --- .claude/skills/sc-cli-reference/SKILL.md | 2 +- ARCHITECTURE.md | 4 ++-- CLAUDE.md | 4 ++-- ROADMAP.md | 6 +++--- crates/cli/src/main.rs | 2 +- crates/cli/tests/ws_sessions.rs | 4 ++-- crates/repo/src/layout.rs | 2 +- crates/repo/src/partial_sessions.rs | 2 +- crates/repo/src/ws.rs | 6 +++--- demo/run_ws_demo.sh | 4 ++-- docs/THREAT-MODEL.md | 2 +- docs/adr/0030-agent-sessions-and-automerge.md | 4 ++-- docs/adr/0050-sessions-on-partial-clones.md | 2 +- ...-ws-sessions.md => 0056-named-concurrent-ws-sessions.md} | 2 +- docs/adr/README.md | 4 ++-- 15 files changed, 25 insertions(+), 25 deletions(-) rename docs/adr/{0055-named-concurrent-ws-sessions.md => 0056-named-concurrent-ws-sessions.md} (99%) diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md index 979ce262..e453a50e 100644 --- a/.claude/skills/sc-cli-reference/SKILL.md +++ b/.claude/skills/sc-cli-reference/SKILL.md @@ -163,7 +163,7 @@ cargo run --bin sc -- ws fork --agents N [--name ] [--identity ] # dura # session: materializes N checkouts under # .sc/ws// and persists a manifest (P20). # --name opens a further named session in - # .sc/ws-/ beside the unnamed one (ADR-0055); + # .sc/ws-/ beside the unnamed one (ADR-0056); # a name already open is refused cargo run --bin sc -- ws list [--session ] # every open session's workspaces, changed/unchanged # (or just session 's) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 740cc9af..436be01a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -350,7 +350,7 @@ phases but the shape is stable: for protected paths; never committed, never transferred. - `tmp/` — guard-cleaned scratch for streaming pack transfer (P25). - `ws/` — durable agent-session workspaces: `session.toml` manifest + per-agent - checkouts (P20); `ws-/` — the same for a named session (ADR-0055). `git-remotes//` — the `git_oid ↔ sc_id` marks map and a + checkouts (P20); `ws-/` — the same for a named session (ADR-0056). `git-remotes//` — the `git_oid ↔ sc_id` marks map and a lazily-built bare `mirror.git` for network Git (P10/P18). - Transient in-progress state (removed on completion/abort): `MERGE_HEAD`, `PICK_HEAD`, `REBASE_STATE`, and their `*_DECIDED_ROOT` records, plus @@ -781,7 +781,7 @@ guard family as a ref-mover. directory, so a crash between the two never strands a `live = true` entry pointing at a directory that no longer exists. See ADR-0030. -Named sessions (ADR-0055). `sc ws fork --name ` opens a further session in a +Named sessions (ADR-0056). `sc ws fork --name ` opens a further session in a sibling root, `.sc/ws-/` (manifest, `/` checkouts and `cache-` inside), so the unnamed session's layout is untouched and tearing one session down never touches another. `list`/`run`/`harvest`/`abandon` take `--session `; without diff --git a/CLAUDE.md b/CLAUDE.md index 68f7bc56..43d9d40c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,7 +135,7 @@ the code, those win. | P17 | `sc rewrap`: one-commit bulk cutover of secrets + protected wrap lists to current recipients/escrow; escrow is a managed list; `--rotate` also re-seals every protected blob under a fresh key | [0027](docs/adr/0027-bulk-rewrap-and-multi-escrow.md), [0051](docs/adr/0051-rotate-protected-paths.md) | | P18 | Hosted Git (GitHub https/ssh) via system-git mirror bridge (`SC_GIT` overrides); auth delegated to git | [0028](docs/adr/0028-network-git-remotes.md) | | P19 | Resumable rebase (stop → resolve → `--continue`; one oplog record total), `cherry-pick --abort`/`--mainline `, `sc amend` | [0029](docs/adr/0029-history-editing-polish.md) | -| P20 | Durable multi-invocation agent sessions: `sc ws fork/list/run/harvest/abandon` under `.sc/ws/`; harvest auto-merges, conflicts fall back to `work-`. `fork --name ` opens a further named session in `.sc/ws-/` (`--session ` on the other verbs; fallback branches and `SC_WORKSPACE` are `-`); sessions are harvested independently, first harvest wins; `ws run` releases the repo lock while the command runs; refresh is designed, not built (#215) | [0030](docs/adr/0030-agent-sessions-and-automerge.md), [0055](docs/adr/0055-named-concurrent-ws-sessions.md) | +| P20 | Durable multi-invocation agent sessions: `sc ws fork/list/run/harvest/abandon` under `.sc/ws/`; harvest auto-merges, conflicts fall back to `work-`. `fork --name ` opens a further named session in `.sc/ws-/` (`--session ` on the other verbs; fallback branches and `SC_WORKSPACE` are `-`); sessions are harvested independently, first harvest wins; `ws run` releases the repo lock while the command runs; refresh is designed, not built (#215) | [0030](docs/adr/0030-agent-sessions-and-automerge.md), [0056](docs/adr/0056-named-concurrent-ws-sessions.md) | | P21 | Hardening sweep: in-progress guards on all policy ops, git-marks self-heal, abort protected-skip parity, ws `"landed"` status | [0031](docs/adr/0031-hardening-consolidation.md) | | P22 | Signed commits: v2 identities (one seed → X25519 + Ed25519), signatures as CAS objects, `sc sign`/`sc verify [--require]` | [0032](docs/adr/0032-signed-commits-provenance.md) | | P23 | `sc conflicts`/`sc resolve --ours\|--theirs`: whole-file conflict resolution without hand-edited markers | [0033](docs/adr/0033-merge-ergonomics.md) | @@ -280,7 +280,7 @@ transport-adjacent. The rest, imperatively: `abandon` take `--session ` and never guess a named session when none is given. Harvests of different sessions run one at a time (repo lock), in invocation order: the first lands, a later conflicting one falls back to - `-`. Do not run a pre-ADR-0055 `sc` against a repo with named + `-`. Do not run a pre-ADR-0056 `sc` against a repo with named sessions open (its gc would not root their bases). - **A stopped merge/pick/rebase lists the paths it wrote as plaintext in `.sc/CONFLICT_PLAINTEXT`.** Protected conflict text never enters the CAS, so no diff --git a/ROADMAP.md b/ROADMAP.md index 2a2104dd..757968ff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -191,14 +191,14 @@ across every phase. `demo/run_ws_demo.sh` (fork/edit/harvest across separate invocations: two cumulative clean auto-merges, one conflict fallback, an `sc undo` of a landing, zero residue at session end). (ADR-0030.) Follow-on (#215, - ADR-0055): `sc ws fork --name ` opens further named sessions beside the + ADR-0056): `sc ws fork --name ` opens further named sessions beside the unnamed one, each in `.sc/ws-/` with its own manifest and caches (`--session ` on `list`/`run`/`harvest`/`abandon`; fallback branches and `SC_WORKSPACE` are `-`); the unnamed layout is unchanged, no migration. Harvests of different sessions are serialized by the repo lock and land in invocation order (first wins, a later conflict falls back); `sc ws run` releases the repo lock while its command runs, so other sessions stay usable. - Workspace refresh is designed in ADR-0055 and still deferred. + Workspace refresh is designed in ADR-0056 and still deferred. - **Phase 21 — Hardening & consolidation.** Closes the P16–P20 review tail with no new capability axis. Every commit-creating policy op (`protect`/`grant`/`revoke`/`secret add`/`secret rotate`/`secret @@ -759,7 +759,7 @@ P28 review follow-ons, the port de-flake, the clippy allow-list) are recorded in (Jujutsu-deep upgrade to the file oplog), oplog entries for remote-tracking refs. - **`sc ws` workspace refresh (#215, P20).** Named and concurrent sessions - shipped (ADR-0055). Moving a live workspace onto a newer tip is designed there + shipped (ADR-0056). Moving a live workspace onto a newer tip is designed there (replay the workspace's commit with the ADR-0049 engine, refuse on any conflict, re-materialize under the recorded view) but not built: it needs a headless merge-into-tree entry point and a re-materialize that keeps files an diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 3cf68346..f172d982 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3494,7 +3494,7 @@ fn run_ws(op: WsOp) -> Result<()> { let plan = repo.ws_run_plan(session.as_deref(), index, with_secrets, sk.as_ref())?; // Release the repo lock before the (possibly long) command runs, so // other sessions can be listed, harvested or abandoned meanwhile - // (ADR-0055); process::exit would skip the RepoLock's Drop anyway. + // (ADR-0056); process::exit would skip the RepoLock's Drop anyway. drop(repo); std::process::exit(plan.run(&cmd)?); } diff --git a/crates/cli/tests/ws_sessions.rs b/crates/cli/tests/ws_sessions.rs index 608f4856..4b93c59d 100644 --- a/crates/cli/tests/ws_sessions.rs +++ b/crates/cli/tests/ws_sessions.rs @@ -1,5 +1,5 @@ //! Named, concurrently open `sc ws` sessions through the real binary -//! (ADR-0055): addressing by `--session`, independent harvests with first-wins +//! (ADR-0056): addressing by `--session`, independent harvests with first-wins //! ordering, and `sc ws run` not holding the repo lock while its command runs. use std::path::{Path, PathBuf}; @@ -114,7 +114,7 @@ fn two_named_sessions_fork_list_run_and_harvest_independently() { } /// While one session's command runs, the repo is free: another `sc` can list, -/// harvest or abandon the other session. (Before ADR-0055 the run held the +/// harvest or abandon the other session. (Before ADR-0056 the run held the /// single-writer lock for the child's whole life and these failed with `Locked`.) #[test] fn a_running_session_does_not_block_the_others() { diff --git a/crates/repo/src/layout.rs b/crates/repo/src/layout.rs index ed965ed0..030153d4 100644 --- a/crates/repo/src/layout.rs +++ b/crates/repo/src/layout.rs @@ -151,7 +151,7 @@ impl Layout { } /// A `sc ws` session's root: `.sc/ws` for the unnamed session (the - /// original layout, unchanged) or `.sc/ws-` for a named one (ADR-0055). + /// original layout, unchanged) or `.sc/ws-` for a named one (ADR-0056). /// A sibling, not a child, so tearing one session down never touches another. pub fn ws_root(&self, session: Option<&str>) -> PathBuf { match session { diff --git a/crates/repo/src/partial_sessions.rs b/crates/repo/src/partial_sessions.rs index 0f0ac652..02c99fec 100644 --- a/crates/repo/src/partial_sessions.rs +++ b/crates/repo/src/partial_sessions.rs @@ -102,7 +102,7 @@ fn harvest_conflict_falls_back_to_a_branch() { fx.cleanup(); } -/// Two named sessions on one partial clone (ADR-0055): each is forked under the +/// Two named sessions on one partial clone (ADR-0056): each is forked under the /// host's view, they edit different lines of one file, and they land one after /// the other. The second is a real merge over the first, and `docs/` is carried /// by id the whole time, never read. diff --git a/crates/repo/src/ws.rs b/crates/repo/src/ws.rs index 008e982c..67c6c97c 100644 --- a/crates/repo/src/ws.rs +++ b/crates/repo/src/ws.rs @@ -54,7 +54,7 @@ pub struct WsEntry { #[derive(Debug, Clone, PartialEq, Eq)] pub struct WsSession { /// `None` for the unnamed session (`.sc/ws`), `Some(name)` for a named one - /// (`.sc/ws-`, ADR-0055). Derived from where the manifest lives and + /// (`.sc/ws-`, ADR-0056). Derived from where the manifest lives and /// never stored in it, so the format is unchanged. pub name: Option, /// The snapshot every workspace was forked from. @@ -564,7 +564,7 @@ impl Repo { /// Run a command in one workspace checkout. Convenience over /// [`Self::ws_run_plan`] + [`WsRunPlan::run`] that keeps this `Repo` (and so /// the single-writer lock) alive for the child's lifetime; the CLI drops the - /// repo between the two so other sessions stay usable meanwhile (ADR-0055). + /// repo between the two so other sessions stay usable meanwhile (ADR-0056). pub fn ws_run( &self, name: Option<&str>, @@ -2295,7 +2295,7 @@ mod tests { std::fs::remove_dir_all(&root).unwrap(); } - // ---- Named and concurrent sessions (ADR-0055) ------------------------- + // ---- Named and concurrent sessions (ADR-0056) ------------------------- /// Fork a one-workspace session called `name` and write `file` in it. fn fork_and_edit(repo: &Repo, name: Option<&str>, file: &str, content: &str) -> WsEntry { diff --git a/demo/run_ws_demo.sh b/demo/run_ws_demo.sh index 0e4004d8..3fd20335 100755 --- a/demo/run_ws_demo.sh +++ b/demo/run_ws_demo.sh @@ -3,7 +3,7 @@ # edit across separate `sc` process invocations, list, cumulative # auto-merge harvest (some workspaces land, a conflicting one falls back), # undo/redo of the landings, then manual conflict resolution of the -# fallback branch, then two named sessions open at once (ADR-0055). Ends +# fallback branch, then two named sessions open at once (ADR-0056). Ends # with zero `.sc/ws*` residue. # # Self-checking: every claim is an assertion; any failure exits non-zero @@ -155,7 +155,7 @@ echo "=== 8: zero residue — .sc/ws does not exist ===" echo "no .sc/ws residue ✔" echo -echo "=== 9: two named sessions open at once (ADR-0055) ===" +echo "=== 9: two named sessions open at once (ADR-0056) ===" fork_a=$("$SC" ws fork --agents 1 --name a --author demo) fork_b=$("$SC" ws fork --agents 1 --name b --author demo) dir_a=$(echo "$fork_a" | sed -n 2p | awk '{print $2}') diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 09cc2e11..edd7753e 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -522,7 +522,7 @@ too, not just the src-control-side metadata. store and working tree and, on a lazy clone, fetch more (`sc sparse set`, `sc cat`, `sc backfill`). It is not an isolation boundary (compare Secret injection). A command run by `sc ws run` - no longer holds the repo lock (ADR-0055), so an `sc` it runs from inside the + no longer holds the repo lock (ADR-0056), so an `sc` it runs from inside the workspace finds the host repo and can change it, as a hand-started agent always could. - **Operations that need a complete closure refuse on a partial clone, fail diff --git a/docs/adr/0030-agent-sessions-and-automerge.md b/docs/adr/0030-agent-sessions-and-automerge.md index ce38765a..47f298d3 100644 --- a/docs/adr/0030-agent-sessions-and-automerge.md +++ b/docs/adr/0030-agent-sessions-and-automerge.md @@ -1,6 +1,6 @@ # ADR-0030: Agent sessions and auto-merge of clean results -- **Status:** Accepted; the one-session-per-repo rule is superseded by ADR-0055 (named and concurrent sessions) +- **Status:** Accepted; the one-session-per-repo rule is superseded by ADR-0056 (named and concurrent sessions) - **Date:** 2026-07-07 - **Phase:** 20 - **Builds on:** ADR-0023 (agent workspaces), ADR-0012 (three-way merge), ADR-0024 (oplog) @@ -16,7 +16,7 @@ mechanical toil the tool can absorb. ## Decision Durable sessions whose workspace state IS the checkout directory. One -unnamed session per repo (ADR-0055 later added named sessions beside it, +unnamed session per repo (ADR-0056 later added named sessions beside it, each in its own `.sc/ws-/` root; the unnamed session described here is unchanged): `sc ws fork --agents N` materializes N checkouts from the current tip into `.sc/ws//` (P7-aware) and writes diff --git a/docs/adr/0050-sessions-on-partial-clones.md b/docs/adr/0050-sessions-on-partial-clones.md index 5b649bfd..3be73408 100644 --- a/docs/adr/0050-sessions-on-partial-clones.md +++ b/docs/adr/0050-sessions-on-partial-clones.md @@ -24,7 +24,7 @@ ADR-0049 left sessions "undecided" as a product question. The question was wheth 4. **Landing uses the ADR-0049 engine.** `ws_harvest` lands a clean workspace with `merge_with_identity`, which on a partial clone is the tree-recursive merge. The probe that decides "lands cleanly or falls back to `work-`" is the same question answered by `tree_merge_filled` (`would_merge_cleanly_partial`): any conflict, inside the view or not, is "not clean", and the workspace becomes a `work-` branch exactly as on a full clone. A conflict outside the view cannot arise from a workspace edit, which holds only the view, but it can arise from the host moving on; it falls back like any other. -5. **Nothing else changes.** The landing-branch rule (the one-session-per-repo rule was relaxed by ADR-0055, which keeps this ADR's view rules per session), `ws run`/`list`/`abandon`, scanner gating, protected-path carry and the oplog are unchanged. A `sc work` session still leaves no residue. +5. **Nothing else changes.** The landing-branch rule (the one-session-per-repo rule was relaxed by ADR-0056, which keeps this ADR's view rules per session), `ws run`/`list`/`abandon`, scanner gating, protected-path carry and the oplog are unchanged. A `sc work` session still leaves no residue. ## Consequences diff --git a/docs/adr/0055-named-concurrent-ws-sessions.md b/docs/adr/0056-named-concurrent-ws-sessions.md similarity index 99% rename from docs/adr/0055-named-concurrent-ws-sessions.md rename to docs/adr/0056-named-concurrent-ws-sessions.md index 23b879e5..4c18fb7b 100644 --- a/docs/adr/0055-named-concurrent-ws-sessions.md +++ b/docs/adr/0056-named-concurrent-ws-sessions.md @@ -1,4 +1,4 @@ -# ADR-0055: Named and concurrent `sc ws` sessions (P20, #215) +# ADR-0056: Named and concurrent `sc ws` sessions (P20, #215) - **Status:** Accepted (built, except workspace refresh, which is designed here and deferred) - **Date:** 2026-10-20 diff --git a/docs/adr/README.md b/docs/adr/README.md index 7a9f8f4a..76205858 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -40,7 +40,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0027](0027-bulk-rewrap-and-multi-escrow.md) | Bulk re-wrap and multiple escrow keys | Accepted | 17 | | [0028](0028-network-git-remotes.md) | Network Git remotes (GitHub over https/ssh) | Accepted | 18 | | [0029](0029-history-editing-polish.md) | History-editing polish — amend, resumable rebase, pick abort, merge replay | Accepted | 19 | -| [0030](0030-agent-sessions-and-automerge.md) | Agent sessions and auto-merge of clean results | Accepted; one-session rule superseded by 0055 | 20 | +| [0030](0030-agent-sessions-and-automerge.md) | Agent sessions and auto-merge of clean results | Accepted; one-session rule superseded by 0056 | 20 | | [0031](0031-hardening-consolidation.md) | Hardening & consolidation sweep — closing the P16–P20 review tail | Accepted | 21 | | [0032](0032-signed-commits-provenance.md) | Signed commits & provenance | Accepted | 22 | | [0033](0033-merge-ergonomics.md) | Merge ergonomics — conflict UX beyond markers | Accepted | 23 | @@ -65,7 +65,7 @@ supersedes the old one and update the **Status** line of the superseded record. | [0052](0052-secret-injection-by-fd.md) | Secret injection by file descriptor (`sc run --secrets-fd`) | Accepted (built) | — | | [0053](0053-tls-pin-management.md) | TLS pin management (`sc tls`) | Accepted (built) | — | | [0054](0054-tls-ca-validation.md) | CA-path validation for `sc+https://` | Accepted (built) | — | -| [0055](0055-named-concurrent-ws-sessions.md) | Named and concurrent `sc ws` sessions | Accepted (built; refresh designed, deferred) | 20 | +| [0056](0056-named-concurrent-ws-sessions.md) | Named and concurrent `sc ws` sessions | Accepted (built; refresh designed, deferred) | 20 | See [`ROADMAP.md`](../../ROADMAP.md) for the phase sequence. ADR numbers are assigned in creation order, so 0017 — the secret scanner — sequences as phase P5,