diff --git a/.claude/skills/sc-cli-reference/SKILL.md b/.claude/skills/sc-cli-reference/SKILL.md
index f40d30ad..202f35d4 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-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)
+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 fe2b2d60..080920dc 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-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,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-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
+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 c2cda897..fc9f471e 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), [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) |
@@ -211,7 +211,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
@@ -277,7 +277,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-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
tree records it; completion treats a listed path absent from disk as deleted,
@@ -306,7 +312,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), 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 30a615f7..f09c39b5 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-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-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
@@ -755,9 +763,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-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
+ agent may have open. Abandon and re-fork covers it meanwhile.
- **Sparse untracked-file guard edge cases.** #241: on a case-insensitive
filesystem the untracked-file guard can alias an old-view path with a newly
in-view one. #248: an untracked file at an out-of-view path that the other side adds wins
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 26269204..f172d982 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,14 +776,23 @@ 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,
},
/// 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.
+ #[arg(long)]
+ session: Option,
/// Landing branch; must be the currently-checked-out branch
/// (default: the session's base branch).
#[arg(long)]
@@ -3406,12 +3431,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 +3453,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 +3491,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-0056); 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 +3514,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,
@@ -3495,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
new file mode 100644
index 00000000..4b93c59d
--- /dev/null
+++ b/crates/cli/tests/ws_sessions.rs
@@ -0,0 +1,154 @@
+//! Named, concurrently open `sc ws` sessions through the real binary
+//! (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};
+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-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() {
+ 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);
+ if args[1] == "list" {
+ assert!(out.contains("session b base:"), "{out}");
+ }
+ }
+ 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 a8857b1a..90e82fe3 100644
--- a/crates/repo/src/layout.rs
+++ b/crates/repo/src/layout.rs
@@ -163,10 +163,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-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 {
+ 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/lock.rs b/crates/repo/src/lock.rs
index 9a24d25a..5b2c667c 100644
--- a/crates/repo/src/lock.rs
+++ b/crates/repo/src/lock.rs
@@ -57,13 +57,18 @@ 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;
};
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/partial_sessions.rs b/crates/repo/src/partial_sessions.rs
index a14e6832..02c99fec 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-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.
+#[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..67c6c97c 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-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.
pub base_snapshot: ObjectId,
/// The branch `base_snapshot` was the tip of at fork time (display only).
@@ -73,12 +77,61 @@ 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")
+}
+
+/// `/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`. 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() {
+ 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",
+ 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.
+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 +184,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 +207,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 +217,75 @@ 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