diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fbdadd9..3b81d912 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ and listed with their assets on the ## [Unreleased] +### Added + +- **`prepare.link`** (ADR-0044, #159): directories `prepare` installs in a + lane's copy (`link = ["web/node_modules"]`) are linked into the lane's + worktree, a junction on Windows, so git hooks there (`npx eslint` in a + pre-commit hook) find them without a second `npm ci`. Only where the + worktree has nothing of that name; only when git ignores the link (write + `node_modules`, not `node_modules/`); removed when the lane stops. Stop the + lane before `git worktree remove`, which on Windows trips over a junction. + ### Fixed - Docs: a viewer of a shared lane reads its containers' logs, as it has diff --git a/Cargo.lock b/Cargo.lock index 8ee8663d..d90cb4d1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -611,6 +611,7 @@ dependencies = [ "hyper-util", "ignore", "jiff", + "junction", "notify", "rand 0.10.3", "regex", @@ -1202,6 +1203,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "junction" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cde48f36530cbd91b65f050101e6c056d6eb743cea2a8f0f19beef69c6742ff8" +dependencies = [ + "scopeguard", + "windows-sys 0.61.2", +] + [[package]] name = "kqueue" version = "1.2.1" @@ -1852,6 +1863,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "security-framework" version = "3.7.0" diff --git a/Cargo.toml b/Cargo.toml index f2699447..16ee055d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ http-body-util = "0.1" hyper = { version = "1", features = ["client", "server", "http1"] } hyper-util = { version = "0.1", features = ["tokio"] } include_dir = "0.7" +junction = { version = "2", default-features = false } jiff = "0.2" libc = "0.2" notify = "8" diff --git a/crates/devstack-config/src/model.rs b/crates/devstack-config/src/model.rs index df1c5f49..6f13eb1a 100644 --- a/crates/devstack-config/src/model.rs +++ b/crates/devstack-config/src/model.rs @@ -618,6 +618,12 @@ pub struct Prepare { /// empty: once per copy. #[serde(default)] pub inputs: Vec, + /// Directories it installs that a lane's worktree gets linked to, e.g. + /// `["web/node_modules"]` (ADR-0044): the worktree's git hooks and + /// editor find them there. Relative to the repository; only where the + /// worktree has nothing of that name, and removed when the lane stops. + #[serde(default)] + pub link: Vec, } /// Hot-reload mode of a built service: the toolchain's own watcher, from diff --git a/crates/devstack-config/src/validate.rs b/crates/devstack-config/src/validate.rs index 21166233..69cdb0ed 100644 --- a/crates/devstack-config/src/validate.rs +++ b/crates/devstack-config/src/validate.rs @@ -493,6 +493,19 @@ pub fn validate(stack: &Stack) -> Vec { c.repo_path(&format!("{p}.prepare.cwd"), d); } c.globs(&format!("{p}.prepare.inputs"), &prep.inputs); + for l in &prep.link { + let at = format!("{p}.prepare.link"); + c.literal(&at, l); + c.repo_path(&at, l); + if l.trim_matches(['/', '\\', '.']).is_empty() { + c.err( + &at, + format!( + "`{l}`: a directory below the repository, not the repository itself" + ), + ); + } + } } if svc.kind == Kind::Job && (svc.port.is_some() || svc.health.is_some()) { c.err( diff --git a/crates/devstack-config/tests/stack_files.rs b/crates/devstack-config/tests/stack_files.rs index 685a5331..607415e8 100644 --- a/crates/devstack-config/tests/stack_files.rs +++ b/crates/devstack-config/tests/stack_files.rs @@ -664,6 +664,39 @@ fn a_dev_server_with_a_port_of_its_own_is_fronted() { ); } +#[test] +fn prepare_links_are_directories_inside_the_repository() { + let ok = MINIMAL.replace( + "port = 5000", + "port = 5000 +prepare = { run = \"npm ci\", link = [\"web/node_modules\"] }", + ); + let stack = from_str(&ok, Path::new("test.toml")).expect("loads"); + let link = &stack.services["api"].prepare.as_ref().unwrap().link; + assert_eq!(link, &["web/node_modules"]); + for bad in [ + "../node_modules", + "/abs", + "C:/x", + ".", + "{repo}/node_modules", + ] { + let issues = invalid(&MINIMAL.replace( + "port = 5000", + &format!( + "port = 5000 +prepare = {{ run = \"npm ci\", link = [\"{bad}\"] }}" + ), + )); + assert!( + issues + .iter() + .any(|i| i.contains("services.api.prepare.link")), + "{bad}: {issues:?}" + ); + } +} + #[test] fn working_directories_and_the_output_stay_inside_the_repository() { let issues = invalid(&format!( diff --git a/crates/devstack-daemon/Cargo.toml b/crates/devstack-daemon/Cargo.toml index 4566ecd4..11f7df37 100644 --- a/crates/devstack-daemon/Cargo.toml +++ b/crates/devstack-daemon/Cargo.toml @@ -34,6 +34,9 @@ tokio.workspace = true tokio-stream.workspace = true ureq.workspace = true +[target.'cfg(windows)'.dependencies] +junction.workspace = true + [dev-dependencies] tempfile.workspace = true diff --git a/crates/devstack-daemon/src/lanes.rs b/crates/devstack-daemon/src/lanes.rs index 7387eb8a..6f1f899f 100644 --- a/crates/devstack-daemon/src/lanes.rs +++ b/crates/devstack-daemon/src/lanes.rs @@ -1832,6 +1832,7 @@ impl Lanes { let lanes: Vec> = self.map.lock().unwrap().values().cloned().collect(); for l in lanes { l.sup.down(false); + l.sup.unlink_prepared(); } // A daemon that stops releases its lanes on nodes (ADR-0025 point 7). let remote: Vec> = std::mem::take(&mut *self.remote.lock().unwrap()) diff --git a/crates/devstack-daemon/src/supervisor/artifacts.rs b/crates/devstack-daemon/src/supervisor/artifacts.rs index e7ad6f77..96114554 100644 --- a/crates/devstack-daemon/src/supervisor/artifacts.rs +++ b/crates/devstack-daemon/src/supervisor/artifacts.rs @@ -165,6 +165,7 @@ impl Supervisor { self.run_prepare(name, job, cancel)?; snap = self.snapshot.lock().unwrap(); } + self.link_prepared(name, svc); let t0 = Instant::now(); let mut running = self .builder diff --git a/crates/devstack-daemon/src/supervisor/copy.rs b/crates/devstack-daemon/src/supervisor/copy.rs index a2609105..a7d54ed3 100644 --- a/crates/devstack-daemon/src/supervisor/copy.rs +++ b/crates/devstack-daemon/src/supervisor/copy.rs @@ -6,7 +6,7 @@ use devstack_build::Snapshot; use devstack_config::model::Service; use devstack_proc::Spec; use std::collections::BTreeMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; @@ -58,7 +58,11 @@ impl Supervisor { } let key = h.finalize().to_hex().to_string(); let mark = self.layout.lane("main").join("prepared").join(name); - if std::fs::read_to_string(&mark).is_ok_and(|k| k == key) { + // A linked directory that is gone (a `git worktree remove` followed + // the link into it, ADR-0044) is prepared again. + let linked_there = + !self.links_prepared() || p.link.iter().all(|l| snap.dir.join(l).is_dir()); + if linked_there && std::fs::read_to_string(&mark).is_ok_and(|k| k == key) { return Ok(None); } Ok(Some(PrepareJob { @@ -132,9 +136,99 @@ impl Supervisor { snap.sync().map_err(|e| e.to_string())?; self.prepare_job(name, svc, &snap)? }; - match job { - Some(job) => self.run_prepare(name, job, cancel), - None => Ok(()), + if let Some(job) = job { + self.run_prepare(name, job, cancel)?; + } + self.link_prepared(name, svc); + Ok(()) + } + + /// Whether what `prepare` installs is linked into the worktree + /// (ADR-0044): in a lane on this machine. The main tree runs in place + /// with its own; a lane on a node has no worktree there. + fn links_prepared(&self) -> bool { + !self.lane.is_empty() && !crate::remote_lane() + } + + /// After `prepare` of `svc`: each of its `link` paths the worktree does + /// not have, linked to the prepared directory in the copy (a junction on + /// Windows, which needs no privilege), so the worktree's git hooks find + /// it (ADR-0044). What the worktree has already, a developer's own + /// install or a link of before, stays as it is. A link git does not + /// ignore is taken away again: `git add -A` would commit it. + pub(super) fn link_prepared(&self, name: &str, svc: &Service) { + let Some(p) = &svc.prepare else { + return; + }; + if !self.links_prepared() { + return; + } + let copy = self.run_root(); + for rel in &p.link { + let (link, target) = (self.repo.join(rel), copy.join(rel)); + if std::fs::symlink_metadata(&link).is_ok() { + continue; + } + let not_linked = |why: String| { + crate::diag::warn( + "prepare_not_linked", + serde_json::json!({ "lane": self.lane, "service": name, "path": rel, "why": why }), + ); + }; + if !target.is_dir() { + not_linked(format!( + "`prepare` made no directory `{rel}` in the lane's copy" + )); + continue; + } + if !link.parent().is_some_and(Path::is_dir) { + not_linked("its parent directory is not in the worktree".into()); + continue; + } + if let Err(e) = make_link(&target, &link) { + not_linked(e.to_string()); + continue; + } + if !git_ignores(&self.repo, rel) { + let _ = remove_link(&link); + not_linked(format!( + "git does not ignore `{rel}` as a link: ignore it without a trailing slash (`node_modules`, not `node_modules/`)" + )); + continue; + } + crate::diag::info( + "prepare_linked", + serde_json::json!({ "lane": self.lane, "service": name, "path": rel }), + ); + } + } + + /// The links [`Self::link_prepared`] made, removed: a lane that stops + /// leaves no link in its worktree for `git worktree remove` to follow + /// into its copy (ADR-0044). Only links to the copy; anything else at + /// those paths is the developer's. + pub(crate) fn unlink_prepared(&self) { + if !self.links_prepared() { + return; + } + let copy = self.run_root(); + for rel in self + .stack + .services + .values() + .filter_map(|s| s.prepare.as_ref()) + .flat_map(|p| &p.link) + { + let link = self.repo.join(rel); + if !links_to(&link, ©.join(rel)) { + continue; + } + let r = remove_link(&link); + crate::diag::info( + "prepare_unlinked", + serde_json::json!({ "lane": self.lane, "path": rel, + "error": r.err().map(|e| e.to_string()) }), + ); } } @@ -210,3 +304,88 @@ pub(super) struct PrepareJob { cwd: PathBuf, run: String, } + +/// A directory link at `link` to `target`: a junction on Windows (no +/// privilege needed, unlike a symbolic link), a symbolic link elsewhere. +fn make_link(target: &Path, link: &Path) -> std::io::Result<()> { + #[cfg(windows)] + return junction::create(target, link); + #[cfg(not(windows))] + return std::os::unix::fs::symlink(target, link); +} + +/// Removes the link itself, never what it points to. +fn remove_link(link: &Path) -> std::io::Result<()> { + // A junction is a directory to Windows; removing it leaves its target. + if cfg!(windows) { + std::fs::remove_dir(link) + } else { + std::fs::remove_file(link) + } +} + +/// Is `link` a link (a junction on Windows) to `target`? +fn links_to(link: &Path, target: &Path) -> bool { + let is_link = std::fs::symlink_metadata(link).is_ok_and(|m| m.file_type().is_symlink()); + let norm = |p: &Path| { + let s = p.to_string_lossy().replace('\\', "/"); + let s = s + .strip_prefix("//?/") + .or_else(|| s.strip_prefix("/??/")) + .unwrap_or(&s) + .trim_end_matches('/') + .to_string(); + if cfg!(windows) { s.to_lowercase() } else { s } + }; + is_link && std::fs::read_link(link).is_ok_and(|t| norm(&t) == norm(target)) +} + +/// Does git ignore `rel` in `repo` as it is now? Unknown counts as no. +fn git_ignores(repo: &Path, rel: &str) -> bool { + std::process::Command::new("git") + .args(["ls-files", "-o", "--exclude-standard", "-z", "--", rel]) + .current_dir(repo) + .output() + .is_ok_and(|o| o.status.success() && o.stdout.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_link_points_at_its_target_and_goes_without_it() { + let d = tempfile::tempdir().unwrap(); + let target = d.path().join("copy").join("node_modules"); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("x.js"), "1").unwrap(); + let link = d.path().join("node_modules"); + make_link(&target, &link).unwrap(); + assert!(link.join("x.js").is_file()); + assert!(links_to(&link, &target)); + assert!(!links_to(&link, &d.path().join("elsewhere"))); + assert!(!links_to(&target, &target), "a directory is no link"); + remove_link(&link).unwrap(); + assert!(std::fs::symlink_metadata(&link).is_err()); + assert!(target.join("x.js").is_file(), "the target stays"); + } + + #[test] + fn a_link_git_does_not_ignore_is_seen() { + let d = tempfile::tempdir().unwrap(); + let (repo, target) = (d.path().join("repo"), d.path().join("copy")); + std::fs::create_dir_all(repo.join("web")).unwrap(); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("x.js"), "1").unwrap(); + let init = std::process::Command::new("git") + .args(["init", "-q"]) + .current_dir(&repo) + .status() + .unwrap(); + assert!(init.success()); + make_link(&target, &repo.join("web/node_modules")).unwrap(); + assert!(!git_ignores(&repo, "web/node_modules")); + std::fs::write(repo.join(".gitignore"), "node_modules\n").unwrap(); + assert!(git_ignores(&repo, "web/node_modules")); + } +} diff --git a/crates/devstack-daemon/src/supervisor/handover.rs b/crates/devstack-daemon/src/supervisor/handover.rs index 6412e9e7..c0b44004 100644 --- a/crates/devstack-daemon/src/supervisor/handover.rs +++ b/crates/devstack-daemon/src/supervisor/handover.rs @@ -37,6 +37,7 @@ impl Supervisor { /// A removed lane: stop its services, release its ports, end its threads. pub(crate) fn close(&self) { self.down(false); + self.unlink_prepared(); self.closed.store(true, Ordering::SeqCst); for (_, p) in std::mem::take(&mut *self.proxies.lock().unwrap()) { p.close(); diff --git a/crates/devstack/tests/daemon_lifecycle.rs b/crates/devstack/tests/daemon_lifecycle.rs index b28fff4b..89df7735 100644 --- a/crates/devstack/tests/daemon_lifecycle.rs +++ b/crates/devstack/tests/daemon_lifecycle.rs @@ -1840,7 +1840,7 @@ fn a_worktree_runs_as_a_lane() { let tray_port = free_port(); let mut toml = std::fs::read_to_string(s.file()).unwrap(); toml.push_str(&format!( - "\n[services.web]\nkind = \"devserver\"\nrun = '\"{BIN}\" serve-static src/Site --port {{port}}'\nport = {web_port}\nprepare = {{ run = \"echo x>>prepared.count\" }}\n" + "\n[services.web]\nkind = \"devserver\"\nrun = '\"{BIN}\" serve-static src/Site --port {{port}}'\nport = {web_port}\nprepare = {{ run = \"mkdir deps && echo x>>prepared.count\" }}\n" )); toml.push_str(&format!( "\n[services.tray]\nkind = \"tool\"\nlanes = false\nrun = '\"{BIN}\" serve-static src/Site --port {{port}}'\nport = {tray_port}\n" @@ -1908,7 +1908,8 @@ fn a_worktree_runs_as_a_lane() { }; std::fs::write( s.dir.path().join(".gitignore"), - ".devstack/\nprep.count\nprepared.count\n", + // `deps` without a slash: git ignores the link to it too (ADR-0044). + ".devstack/\nprep.count\nprepared.count\ndeps\n", ) .unwrap(); // Checkouts as the files are (no CRLF on Windows), so main and worktree hash alike. @@ -2187,7 +2188,16 @@ fn a_worktree_runs_as_a_lane() { "the lane stopped with its worktree\n{}", s.diag() ); - assert!(!s.ok(&["lane", "list"]).contains(&lane)); + // Its services stop first; it leaves the list once its containers are + // gone too, which takes a moment longer. + assert!( + wait_for( + || !s.ok(&["lane", "list"]).contains(&lane), + Duration::from_secs(30) + ), + "the lane is forgotten with its worktree\n{}", + s.diag() + ); assert!(s.api("/health").is_some(), "main still runs"); // 6. A worktree added with git is a lane at once: the daemon notices it @@ -2224,6 +2234,17 @@ fn a_worktree_runs_as_a_lane() { status.contains("lanes: 1 worktree(s), 0 started"), "{status}" ); + // This lane links what `prepare` made (ADR-0044); the one of step 5 does + // not: its worktree is removed while it runs, which a link gets in the + // way of. + let file = extra.join("devstack.toml"); + let toml = std::fs::read_to_string(&file).unwrap(); + let toml = toml.replace( + "echo x>>prepared.count\" }", + "echo x>>prepared.count\", link = [\"deps\"] }", + ); + assert!(toml.contains("link = [\"deps\"]"), "{toml}"); + std::fs::write(&file, toml).unwrap(); let out = s.cli(&["lane", "start", &extra_name], None); // `broken` fails, the rest runs let started = String::from_utf8_lossy(&out.stdout).to_string(); assert!( @@ -2246,8 +2267,28 @@ fn a_worktree_runs_as_a_lane() { s.ok(&["status"]) .contains(&format!("1 started ({extra_name})")) ); + // What `prepare` made is linked into the worktree while the lane runs, + // for its git hooks (ADR-0044); `lane stop` takes the link, not the copy's. + let linked = extra.join("deps"); + let is_link = || std::fs::symlink_metadata(&linked).is_ok_and(|m| m.file_type().is_symlink()); + assert!( + wait_for(is_link, Duration::from_secs(30)), + "prepare's directory is linked into the worktree\n{}", + s.diag() + ); s.ok(&["lane", "stop", &extra_name]); assert!(row(&extra_name).contains("stopped"), "{}", row(&extra_name)); + assert!( + std::fs::symlink_metadata(&linked).is_err(), + "the link goes with the lane" + ); + let extra_copy = s + .dir + .path() + .join(".devstack") + .join(format!("lane-{extra_name}")) + .join("lanes/main/src/deps"); + assert!(extra_copy.is_dir(), "the copy keeps what prepare made"); // 8. A profile from the lane's own stack file (ADR-0041): its branch adds // one; it says what starts, and `--run` runs its command in the lane. diff --git a/docs/adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md b/docs/adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md index be21a6c9..483636e4 100644 --- a/docs/adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md +++ b/docs/adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md @@ -3,7 +3,7 @@ - **Status:** Accepted, amended 2026-10-15 twice (the lanes are the worktrees; git owns them, lanes run from a copy); point 4 replaced by [ADR-0030](0030-each-lane-has-its-own-infrastructure.md) (2026-10-16) - **Date:** 2026-10-15 - **Deciders:** project owner -- **Related:** plan §3.5, [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0008](0008-background-workers-run-only-in-the-active-slot.md), [ADR-0010](0010-promotion-mechanism.md), [ADR-0012](0012-shared-infrastructure-between-lanes.md), [ADR-0016](0016-a-daemon-restart-is-a-clean-restart.md), [ADR-0025](0025-a-lane-can-run-on-another-node.md) to [ADR-0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) (remote lanes, accepted 2026-10-16) +- **Related:** plan §3.5, [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0008](0008-background-workers-run-only-in-the-active-slot.md), [ADR-0010](0010-promotion-mechanism.md), [ADR-0012](0012-shared-infrastructure-between-lanes.md), [ADR-0016](0016-a-daemon-restart-is-a-clean-restart.md), [ADR-0025](0025-a-lane-can-run-on-another-node.md) to [ADR-0029](0029-source-sync-and-port-forwarding-for-remote-lanes.md) (remote lanes, accepted 2026-10-16); [ADR-0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md) (prepared directories linked into the worktree) ## Context diff --git a/docs/adr/0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md b/docs/adr/0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md new file mode 100644 index 00000000..96865dba --- /dev/null +++ b/docs/adr/0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md @@ -0,0 +1,98 @@ +# ADR-0044: A lane's prepared directories can be linked into its worktree + +- **Status:** Accepted (2026-10-21) +- **Date:** 2026-10-21 +- **Deciders:** project owner +- **Related:** [#159](https://github.com/nuetzliches/devstack/issues/159), [ADR-0002](0002-processes-run-from-immutable-artifacts.md), [ADR-0015](0015-devstack-is-optional.md), [ADR-0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md) (a lane runs from a copy), plan §3.5 + +## Context + +A lane runs from a copy of its worktree (ADR-0024), and `prepare` (`npm ci`) +runs in that copy. The worktree itself never gets a `node_modules`, by design. + +Git does not know about the copy: `git commit` runs the repository's hooks in +the worktree. A pre-commit hook that lints staged files with `npx eslint` +fails in every lane worktree (`Cannot find module` from `eslint.config.js`), +although the lane has a prepared `node_modules` a few directories away. The +way out, `npm ci` by hand in the worktree, took three minutes and a second +copy of `node_modules` on a downstream Windows machine. + +The hook cannot find the copy itself without depending on devstack's +internal layout (`.devstack/lane-/lanes/main/src`), which is no +contract, and an application that depends on devstack breaks ADR-0015. + +Measured on Windows (Git 2.43): `git worktree remove` follows a junction and +empties the directory it points to. A junction named `node_modules` is +ignored by a `node_modules/` rule; a symbolic link is not a directory to git +elsewhere, and a rule with a trailing slash does not ignore it. + +## Decision + +`prepare` takes `link`, directories relative to the repository +(`link = ["web/node_modules"]`). In a lane on this machine, after `prepare` +ran (or found its inputs unchanged), devstack links each of them in the +worktree to the same directory in the lane's copy: a junction on Windows, +which needs no privilege, a symbolic link elsewhere. + +1. Only where the worktree has nothing of that name: a developer's own + install, or a link they made, stays and is never touched. +2. A link git does not ignore is removed again at once, and the diagnostic + log says how to ignore it (no trailing slash): `git add -A` would + commit it otherwise. +3. When the lane stops (`lane stop`, its removal, a move to a node, the + daemon stopping) devstack removes the links that point into its copy, + and nothing else, so a `git worktree remove` after it cannot follow one. +4. A linked directory that is gone from the copy runs `prepare` again, + even with unchanged inputs. +5. The main working tree runs in place with its own directories, and a + lane on a node has no worktree there: neither links. + +## Alternatives considered + +- **The hook finds the copy.** Couples the downstream repository to a + layout devstack may change, and makes it depend on devstack (ADR-0015). +- **`devstack lane path `**, a stable command a hook opts into. A + contract instead of a guess, but every repository's hooks have to be + written for devstack, and a hook that runs without it has to handle both. + The link serves the common case without the repository knowing. +- **`prepare` in the worktree too.** The second install the issue is about: + minutes per lane, and a process of the lane writing inside a worktree that + git or a tool may remove at any moment (ADR-0024). +- **Adding the link paths to `.git/info/exclude`.** Shared by every + worktree of the repository, and a file of the developer's that devstack + would edit. Checking with git and saying what to change keeps devstack + out of it. + +## Consequences + +- A `git worktree remove` *while the lane runs* no longer works cleanly on + Windows. Git 2.43 follows the junction and empties the copy's directory + (the running dev server loses it; point 4 repairs the copy at the next + start). A newer Git for Windows (CI's runner) reported success and left + the worktree directory behind, the junction still in it. The opt-in `link` + is what makes this possible: without it the worktree holds nothing of the + lane. The docs say: `devstack lane stop` before removing the worktree. +- A daemon that is killed leaves its links; the next start of the lane + finds them (point 1) and its stop removes them. +- On Linux and macOS a `node_modules/` rule does not ignore the link: + such a repository needs `node_modules` (no slash) for links to be made. +- Not shown in `status` or the dashboard yet; the diagnostic log has + `prepare_linked`, `prepare_not_linked` (with why) and `prepare_unlinked`. + +## Enforced by + +- `crates/devstack-config/src/model.rs` (`Prepare::link`), + `crates/devstack-config/src/validate.rs` (inside the repository, literal). +- `crates/devstack-daemon/src/supervisor/copy.rs` (`link_prepared`, + `unlink_prepared`, `prepare_job` for point 4), called from `copy_ready`, + `artifacts.rs` (after a build's `prepare`), `handover.rs` (`close`) and + `lanes.rs` (`down_all`). +- `crates/devstack/tests/daemon_lifecycle.rs` (`a_worktree_runs_as_a_lane`). +- `docs/stack-file.md` (`prepare`). + +## What this ADR does not say + +- That anything of the lane runs in its worktree: a link is a name in the + worktree, the processes still run from the copy. +- That devstack links files, or paths `prepare` did not make: `link` names + directories in the copy, and one missing there is reported, not created. diff --git a/docs/adr/README.md b/docs/adr/README.md index 5738ac36..b5683728 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -92,3 +92,4 @@ stay. | [0041](0041-a-profile-says-how-a-lane-runs-for-a-purpose.md) | A profile says how a lane (or the main tree) runs for a purpose, chosen when it starts | Accepted | | [0042](0042-a-dev-servers-rebuilds-show-like-builds.md) | A dev server's rebuilds show like builds, read from its output | Accepted | | [0043](0043-a-dev-servers-fixed-port-is-devstacks.md) | A dev server's fixed port is devstack's, forwarded to its instance | Accepted | +| [0044](0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md) | A lane's prepared directories can be linked into its worktree | Accepted | diff --git a/docs/stack-file.md b/docs/stack-file.md index 354a4dae..9ffa226e 100644 --- a/docs/stack-file.md +++ b/docs/stack-file.md @@ -395,9 +395,24 @@ kind = "devserver" cwd = "web" run = "npx ng serve --port {port}" port = 4200 -prepare = { run = "npm ci", inputs = ["web/package-lock.json"] } +prepare = { run = "npm ci", inputs = ["web/package-lock.json"], link = ["web/node_modules"] } ``` +`link` ([ADR-0044](adr/0044-a-lanes-prepared-directories-can-be-linked-into-its-worktree.md)) +makes what `prepare` installed usable in a lane's worktree, where git runs its +hooks (a pre-commit hook with `npx eslint`): each directory, relative to the +repository, is linked from the worktree to the lane's copy (a junction on +Windows, a symbolic link elsewhere) once `prepare` ran. Only where the +worktree has nothing of that name: your own `npm ci` there wins. Git has to +ignore the link: write `node_modules` in `.gitignore`, not `node_modules/`, +which on Linux and macOS ignores directories only (the daemon log says +`prepare_not_linked` with why). `devstack lane stop` removes the links again; +**stop the lane before `git worktree remove`**: on Windows, depending on the +Git version, it follows the junction and empties the copy's directory (the +next start prepares it again), or leaves the worktree behind with the junction +in it. +The main tree and lanes on a node make no links. + ## `[lanes]`: other worktrees ([ADR-0024](adr/0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md), [ADR-0030](adr/0030-each-lane-has-its-own-infrastructure.md); on other machines [ADR-0025](adr/0025-a-lane-can-run-on-another-node.md), [ADR-0028](adr/0028-lane-images.md), [ADR-0029](adr/0029-source-sync-and-port-forwarding-for-remote-lanes.md), [ADR-0035](adr/0035-lanes-can-be-shared-with-the-pool.md), and [pool.md](pool.md)) ```toml @@ -431,8 +446,9 @@ and nothing of a lane runs inside its worktree. Builds run in the lane's snapshot, and so do its dev servers, tools and hot-reload mode; the snapshot follows the worktree within moments of a change (hot module replacement keeps working), and `{repo}` is the snapshot for them. So `git worktree remove` -works while the lane runs, and the lane stops with it. Ignored files are not -in the snapshot: `prepare` installs what is missing. +works while the lane runs, and the lane stops with it (with `prepare.link`, +stop the lane first: see `prepare`). Ignored files are not in the snapshot: +`prepare` installs what is missing. - A lane's containers are a Compose project of their own, `-`, from its worktree's Compose files, with an overlay diff --git a/skills/devstack-config/SKILL.md b/skills/devstack-config/SKILL.md index 4da4da90..ffe78432 100644 --- a/skills/devstack-config/SKILL.md +++ b/skills/devstack-config/SKILL.md @@ -54,6 +54,10 @@ without a stack file starts from `devstack init` (a draft with TODOs). per lane (a telemetry dashboard, a fake SMTP server) can stay shared: `[compose.] shared = ["mailbox"]`. A dev server's `run` needs `{port}` to run in a lane. +- **A lane's worktree has no `node_modules`**: the lane runs from a copy, + where `prepare` installs. When git hooks need it (`npx eslint` in a + pre-commit hook), `prepare.link = ["web/node_modules"]` links it into the + worktree; `.gitignore` then needs `node_modules` without a trailing slash. - **Lanes on other machines** (`devstack up --on `) run in a Linux container: `[lanes] image` (a toolchain image) or `[lanes] dockerfile`. Files git ignores do not go there unless `[lanes] sync` names them (a dev