diff --git a/.gitleaksignore b/.gitleaksignore index 861886a35b..7d1f24763f 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -5,3 +5,5 @@ e069b8546c112e5b5c8ab0ec82fd24a4f19ef16b:.hack/tickets/events/events-2026-03.jso 0cb0ff2316b05e833119aeae9cc73a0a14329aeb:tests/feedback-review.test.ts:private-key:112 06f262309db3111e65c8a23324456ef73ac57e83:tests/project-env-hydrate.test.ts:generic-api-key:389 aeca3e02e464ef11dd72531aa8313045bd8561f5:tests/background-command-scanner.test.ts:generic-api-key:172 +# Synthetic authorization-header redaction canary in Config CLI regression history. +399d3d89c685343e0afc0efe36559443677f5168:tests/config-editor-cli.test.ts:curl-auth-header:457 diff --git a/apps/desktop/Cargo.lock b/apps/desktop/Cargo.lock index 7a92744fff..68a8d5cff0 100644 --- a/apps/desktop/Cargo.lock +++ b/apps/desktop/Cargo.lock @@ -3262,6 +3262,7 @@ dependencies = [ "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", + "serde_json", ] [[package]] diff --git a/apps/desktop/DESIGN-V1.md b/apps/desktop/DESIGN-V1.md index fc56b26a50..e0498a76fb 100644 --- a/apps/desktop/DESIGN-V1.md +++ b/apps/desktop/DESIGN-V1.md @@ -89,15 +89,16 @@ Detail content is inset 20 left and right; the sidebar list 6. ## Colour -The dark desktop palette uses Merino Dark from the HACK-2595 frames. - | Token | Light | Dark | Used for | |---|---|---|---| -| `surface` | `#FFFFFF` | `#0D1117` | Detail pane | -| `chrome` | `#F7F7F5` | `#090C10` | Title bar, sidebar, status bar | +| `window` | `#FFFFFF` | `#090C10` | Window background outside Projects, native dark title bar | +| `surface` | `#FFFFFF` | `#0D1117` | Cards and controls | +| `chrome` | `#F7F7F5` | `#06080A` | Title bar, sidebar, status bar | +| `raised` | `#EFEFEC` | `#1C2026` | Menus and tooltips | +| `selection` | `#EFEFEC` | `#24272B` | Selected navigation, tabs, selected file row in dark mode | +| `attention` | `#EFEFEC` | `#21252B` | Running command box | | `surface_1` | `#EFEFEC` | `#1A1E24` | Hover, panel handle, neutral pill | | `surface_2` | `#E6E6E2` | `#1C2026` | Pressed and raised surfaces, selected file row in light mode | -| `selection` | `#EFEFEC` | `#24272B` | Selected navigation, selected file row in dark mode | | `preview_surface` | `#EFEFEC` | `#1E2329` | Read-only file preview body | | `border` | black 9% | `#2B3036` | Hairlines | | `border_strong` | black 18% | `#2B3036` | Button and field outlines | @@ -106,6 +107,10 @@ The dark desktop palette uses Merino Dark from the HACK-2595 frames. | `text_muted` | `#8B8A85` | `#8B9197` | Captions, table header, timestamps | | `accent` | `#2F6FDB` | `#E6EDF3` | Switch on, focus ring | +The dark palette is Merino Dark. GPUI components such as the search field, +tooltips and scrollbars use the same palette. The Projects pane uses its own +Builtin Light and Merino Dark accents for the tree and copy pane. + State colours (dot / pill background / pill text): | State | Light | Dark | Shown as | @@ -278,21 +283,13 @@ above the strip when the panel is docked, below it when maximized. Closing a tab, or the window, ends that tab's whole process session. -Terminal look: the user's Ghostty config when it exists (font family and -size, theme or palette, cursor style, padding), mapped onto the component. -Without one, the fallback terminal theme (`TermPalette::fallback`), dark in -both app modes as in the approved mockup, 12.5 / 19 in the app's mono font: - -| Token | Value | | Token | Value | -|---|---|---|---|---| -| `bg` | `#1C1C1A` | | `green` | `#5DCAA5` | -| `fg`, `cursor` | `#E8E6DC` | | `bright_green` | `#97C459` | -| `dim` | `#8B8A85` | | `blue` | `#85B7EB` | -| `strip` | `#2A2A28` | | `magenta` | `#AFA9EC` | -| `strip_border` | `#3A3A37` | | `yellow` | `#EF9F27` | -| `tab_fg` | `#B4B2A9` | | `red` | `#F07B7A` | -| `badge_warn_bg` / `_fg` | `#633806` / `#FAC775` | | `cyan` | `#6CCFD9` | -| `badge_bg` / `_fg` | `#3A3A37` / `#D3D1C7` | | | | +Terminal look: the user's Ghostty config overrides the terminal's default +font, padding, palette, foreground, background, cursor and selection settings +where provided. In dark mode the grid defaults to Merino Dark, with +`#0D1117` background, `#E6EDF3` foreground and `#2F81F7` cursor. The terminal +panel chrome uses the app palette. Its controls never inherit the user's +Ghostty colors. The light grid follows the light GPUI theme by default. + Prompt themes (zsh, oh-my-zsh, starship) come from the real shell in a real PTY (`TERM`, `COLORTERM=truecolor`); tmux is not involved. diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.md index 8f1f659217..6f0439bf9e 100644 --- a/apps/desktop/DESIGN.md +++ b/apps/desktop/DESIGN.md @@ -238,6 +238,12 @@ run from a banner. Use `command_control::render_history` when a passing check removes its Run and Copy buttons. Closing the drawer retains the latest output until the next command starts or the CLI changes. +While Setup is visible, the `hackd` and Routing and DNS sidebar indicators use +the same evidence as the Setup cards. Skipping a card leaves its evidence +intact. Elsewhere, the DNS indicator uses the latest current Setup or Doctor +report, ordered by when each check started. A Doctor result for an old project +set cannot replace a current check. + Source: `hack doctor --json --path ` per registered project, plus `hack doctor --machine --json` for machine findings, on open and every 10 minutes while visible. The project audit gives `{ok:true,data:{schema:1,checks,summary,counts}}`; the machine variant uses the same envelope with `data.schema: "hack.doctor.machine.v1"` (R7c). Checks include `id`, `status`, `detail`, `area`, `scope` and `fix` (R7a). Until the app switches to the machine variant, it still runs one plain `hack doctor --json` outside any project and de-duplicates machine checks. diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 6adec0339b..853b367a7d 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -825,6 +825,23 @@ Screenshots: [overlays, running](screenshots/env-running-light.png), [required missing](screenshots/env-missing-light.png), [long](screenshots/env-long-dark.png). +## Project Config + +Select Config on a Compose project. Map shows how its routes, dependencies +and env values resolve. Viewing as and Env select one checkout and overlay. +Edit, Env layers and Source share a pending patch. Save validates and writes +the selected files. A file changed by another editor shows Reload in the +save dock. Route changes offer a restart and env-only changes apply at the +next start. The Worktrees toggles show the effective branch and inheritance +settings, including camelCase keys in existing project files. +To override an inherited Env layers value with an empty string, open the +target cell, clear the input, and press Enter. + +The native screenshot harness uses synthetic projects and values. Build with +`bash scripts/build.sh --features screenshots`, then run +`target/debug/hack-desktop --config-screenshots ` for the light and dark +Config frames. + ## Process-cleanup tests The supported desktop test command uses the repository-pinned nextest release diff --git a/apps/desktop/app/Cargo.toml b/apps/desktop/app/Cargo.toml index 99cf1e23eb..a7cdd43c20 100644 --- a/apps/desktop/app/Cargo.toml +++ b/apps/desktop/app/Cargo.toml @@ -22,6 +22,7 @@ screenshots = ["gpui-kit/test-support", "dep:image", "hack-desktop-ui/screenshot terminal = ["dep:hack-desktop-term", "hack-desktop-term/ghostty"] [dependencies] +serde_json.workspace = true hack-desktop-core.workspace = true hack-desktop-ui.workspace = true hack-desktop-term = { workspace = true, optional = true } diff --git a/apps/desktop/app/src/command_control.rs b/apps/desktop/app/src/command_control.rs index b71e0611e8..6ea13ef60b 100644 --- a/apps/desktop/app/src/command_control.rs +++ b/apps/desktop/app/src/command_control.rs @@ -47,6 +47,7 @@ pub(crate) struct CommandCompletion { } type OnExit = Box)>; +type ResolveDirectory = fn(&CommandControl, &CommandSpec) -> Result, String>; #[derive(Default)] pub(crate) struct Drawer { @@ -74,6 +75,7 @@ struct Run { id: CommandRunId, props: CommandControl, spec: CommandSpec, + resolve_directory: ResolveDirectory, phase: Phase, waiting_for_password: bool, fallback: Option, @@ -140,6 +142,16 @@ fn command_directory( Ok(checked_home(spec).map(Path::to_owned)) } +fn init_directory(props: &CommandControl, _: &CommandSpec) -> Result, String> { + let root = props.cwd.as_deref().ok_or("The checkout is unavailable.")?; + hack_desktop_core::source::trusted_init_root(root) + .map(Some) + .map_err(|error| match error { + hack_desktop_core::source::SourceError::Cli { message, .. } => message, + _ => "The checkout is unavailable.".into(), + }) +} + fn command_options(spec: &CommandSpec, cwd: Option) -> Result { if !Path::new(&spec.program).is_absolute() { return Err("The command must use an absolute executable path".into()); @@ -220,13 +232,26 @@ impl HackApp { if !self.live { return false; } - self.start_drawer_command(props, Box::new(on_exit), window, cx) + self.start_drawer_command(props, Box::new(on_exit), command_directory, window, cx) + } + + pub(crate) fn run_init_in_drawer( + &mut self, + props: CommandControl, + on_exit: impl FnOnce(&mut Self, CommandCompletion, &mut Context) + 'static, + window: &mut Window, + cx: &mut Context, + ) { + if self.live { + self.start_drawer_command(props, Box::new(on_exit), init_directory, window, cx); + } } fn start_drawer_command( &mut self, props: CommandControl, on_exit: OnExit, + resolve_directory: ResolveDirectory, window: &mut Window, cx: &mut Context, ) -> bool { @@ -238,7 +263,7 @@ impl HackApp { }; self.user_navigated(); let spec = spec.clone(); - let directory = command_directory(&props, &spec); + let directory = resolve_directory(&props, &spec); let core = directory .clone() .and_then(|cwd| command_core(&props, &spec, cwd)); @@ -252,6 +277,7 @@ impl HackApp { id, props, spec, + resolve_directory, phase: Phase::Running, waiting_for_password: false, fallback: None, @@ -557,6 +583,7 @@ impl HackApp { let id = run.id; let spec = run.spec.clone(); let props = run.props.clone(); + let resolve_directory = run.resolve_directory; cx.spawn(async move |app, cx| { let result = cx .background_executor() @@ -566,7 +593,7 @@ impl HackApp { } else { Platform::Linux }; - let cwd = command_directory(&props, &spec)?; + let cwd = resolve_directory(&props, &spec)?; Script::create_in(&std::env::temp_dir(), &spec, cwd.as_deref())?.open( platform, linux_adapter().as_deref(), @@ -758,7 +785,7 @@ pub(crate) fn render_with_run( .px(px(8.)) .rounded(radius::PANEL) .hairline(p.border) - .when(running, |r| r.bg(p.surface_1)) + .when(running, |r| r.bg(p.attention)) .child(command) }) .child(run) @@ -1128,7 +1155,7 @@ fn command_menu( .shadow_lg() .rounded(radius::PANEL) .hairline(p.border) - .bg(p.surface_1) + .bg(p.raised) .type_step(text::SMALL) .on_mouse_down_out(cx.listener(|app, _, _, cx| { if app.panels.command.menu { @@ -1174,7 +1201,7 @@ fn command_menu( #[cfg(feature = "screenshots")] #[path = "command_screenshots.rs"] -mod screenshots; +pub(crate) mod screenshots; #[cfg(feature = "screenshots")] pub(crate) use screenshots::capture; diff --git a/apps/desktop/app/src/command_screenshots.rs b/apps/desktop/app/src/command_screenshots.rs index 04d8d20198..7cf1ce1b25 100644 --- a/apps/desktop/app/src/command_screenshots.rs +++ b/apps/desktop/app/src/command_screenshots.rs @@ -72,6 +72,7 @@ pub(crate) fn capture(dir: &Path, cx: &mut HeadlessAppContext) { fn fixture(index: usize, window: &mut Window, cx: &mut Context) -> HackApp { let mut app = HackApp::new(crate::source_for(Some(Fixture::Empty)), false, window, cx); + app.use_default_terminal_look(); let daemon = index == 0; let id = if daemon { "daemon" } else { "routing" }; let mut report = setup_fixtures::load("partial").expect("setup fixture"); @@ -141,8 +142,11 @@ fn fixture(index: usize, window: &mut Window, cx: &mut Context) -> Hack .expect("fixture card"); card.status = Status::Passed; card.detail = "All 8 DNS pieces are set up.".into(); - app.show_setup_now(checked); - app.command_checked(completion.run, Ok(()), cx); + // Deliver a synthetic fresh check through the actual Setup + // completion path used by the command control. + let generation = app.setup.begin(); + app.setup_command_check = Some((completion.run, id.into())); + app.setup_checked(generation, checked, cx); } }, window, @@ -199,18 +203,18 @@ fn wait_for_frame(index: usize, app: &Entity, cx: &mut HeadlessAppConte } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use gpui_kit::AnyWindowHandle; use std::sync::Arc; - fn open(index: usize) -> (HeadlessAppContext, AnyWindowHandle, Entity) { + pub(crate) fn open(index: usize) -> (HeadlessAppContext, AnyWindowHandle, Entity) { let mut cx = HeadlessAppContext::with_platform( Arc::new(gpui_kit::NoopTextSystem::new()), Arc::new(hack_desktop_ui::icons::Assets), || Ok(None), ); - cx.update(gpui_kit::init); + cx.update(hack_desktop_ui::tokens::init); let (window, app) = cx .update(|cx| { gpui_kit::open_window( @@ -228,6 +232,44 @@ mod tests { (cx, window, app) } + pub(crate) fn assert_rendered_status( + cx: &mut HeadlessAppContext, + window: AnyWindowHandle, + id: &str, + sidebar: &str, + card: Option<&str>, + ) { + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + assert_eq!(window.find(id.to_owned()).label(), Some(sidebar)); + if let Some(card) = card { + assert_eq!(window.find(("setup-status", 1_usize)).label(), Some(card)); + } + }) + .unwrap(); + } + + #[test] + fn the_rendered_hackd_dot_matches_the_off_card_despite_a_green_project_read() { + let (mut cx, window, app) = open(0); + cx.update(|cx| { + let app = app.read(cx); + assert_eq!( + app.hackd_tone_from_snapshot(), + Some(hack_desktop_core::machine::Tone::Ok) + ); + let card = &app.setup.report.cards[1]; + assert!(card.detail.contains("hackd off")); + }); + assert_rendered_status( + &mut cx, + window, + "hackd", + "hackd: Needs attention", + Some("Needs attention"), + ); + } + #[test] fn closing_hides_a_password_prompt_and_stop_releases_the_machine_gate() { let (mut cx, window, app) = open(2); diff --git a/apps/desktop/app/src/config_view.rs b/apps/desktop/app/src/config_view.rs new file mode 100644 index 0000000000..c94b54b1a5 --- /dev/null +++ b/apps/desktop/app/src/config_view.rs @@ -0,0 +1,1376 @@ +use std::{collections::BTreeMap, path::PathBuf, time::Duration}; + +use gpui_kit::component::{ + button::Button, + input::{EditorState, InputState}, + menu::{DropdownMenu as _, PopupMenuItem}, +}; +use gpui_kit::{ + AnyElement, ClipboardItem, Context, Entity, IntoElement, ParentElement as _, SharedString, + Styled as _, Subscription, Task, Window, div, prelude::*, px, +}; +use hack_desktop_core::{ + config::{ + ConfigChange, ConfigError, ConfigIssue, ConfigPatch, ConfigReport, ConfigSaved, + ConfigState, ConfigTarget, ConfigValidation, + }, + viewmodel::InstanceKey, +}; +use hack_desktop_ui::{ + components::{StyledExt as _, Ui, action_button, icon, primary_button}, + icons::Glyph, + tokens::{space, text}, +}; +use serde_json::Value; + +use crate::view::HackApp; + +mod forms; +mod map; +#[cfg(feature = "screenshots")] +pub(crate) mod screenshots; + +pub(crate) const TAB: usize = 7; +const STATE_ACTION_WIDTH: gpui_kit::Pixels = px(136.); + +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub(super) enum View { + #[default] + Map, + Edit, + Env, + Source, +} + +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum EditSection { + Project, + #[default] + Routes, + Services, + Env, + Worktrees, +} + +#[derive(Clone, Default, PartialEq, Eq, Hash)] +struct Selection { + cli: Option, + root: PathBuf, + target: ConfigTarget, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct SaveOperation { + epoch: u64, + generation: u64, +} + +#[derive(Clone, Default)] +struct Draft { + base: BTreeMap, + changes: BTreeMap, + pending_save: Option, + save_result: Option>, +} + +#[derive(Default)] +pub(crate) struct ConfigPane { + project: Option, + project_root: PathBuf, + selection: Selection, + choices: Vec<(String, Selection)>, + view: View, + edit_section: EditSection, + service: String, + scope: String, + layer: Option, + file: String, + active_cell: Option, + report: Option>, + draft: Draft, + stashed: std::collections::HashMap, + validation: Option, + error: Option, + conflict: bool, + saved: Option, + loading: bool, + save_generation: u64, + restarting: bool, + inputs: BTreeMap, Subscription)>, + editor: Option<(String, Entity, Subscription)>, + watch: Option>, + validation_task: Option>, + load_task: Option>, + copies_task: Option>, + pending_focus: Option, + revision: u64, +} + +impl ConfigPane { + pub(crate) fn switch_cli(&mut self, cli: Option) { + self.stash_draft(); + *self = Self { + selection: Selection { + cli, + ..Selection::default() + }, + stashed: std::mem::take(&mut self.stashed), + save_generation: self.save_generation, + ..Self::default() + }; + } + + fn report(&self) -> Option<&ConfigReport> { + self.report.as_ref()?.as_ref().ok() + } + + fn stage(&mut self, id: String, value: Option) { + if let Some(change) = value { + self.draft.changes.insert(id, change); + } else { + self.draft.changes.remove(&id); + } + self.revision += 1; + self.draft.save_result = None; + self.saved = None; + self.error = None; + self.validation = None; + } + + fn patch(&self) -> ConfigPatch { + ConfigPatch { + base: self.draft.base.clone(), + changes: self.draft.changes.values().cloned().collect(), + } + } + + fn issues(&self) -> &[ConfigIssue] { + if let Some(validation) = &self.validation { + &validation.issues + } else if let Some(error) = &self.error + && !error.issues.is_empty() + { + &error.issues + } else { + self.report().map_or(&[], |report| report.issues.as_slice()) + } + } + + fn can_save(&self) -> bool { + !self.draft.changes.is_empty() + && !self.saving() + && !self.conflict + && !self.loading + && self.validation.as_ref().is_some_and(|check| check.valid) + && self.error.is_none() + } + + fn saving(&self) -> bool { + self.draft.pending_save.is_some() + } + + fn begin_save(&mut self, epoch: u64) -> SaveOperation { + self.save_generation += 1; + let operation = SaveOperation { + epoch, + generation: self.save_generation, + }; + self.draft.pending_save = Some(operation); + self.draft.save_result = None; + operation + } + + fn finish_save( + &mut self, + selection: &Selection, + operation: SaveOperation, + result: Result, + ) -> bool { + let visible = &self.selection == selection; + let draft = if visible { + &mut self.draft + } else if let Some(draft) = self.stashed.get_mut(selection) { + draft + } else { + return false; + }; + if draft.pending_save != Some(operation) { + return false; + } + draft.pending_save = None; + if result.is_ok() { + draft.base.clear(); + draft.changes.clear(); + } + draft.save_result = Some(result); + visible + } + + fn present_save(&mut self) -> bool { + match &self.draft.save_result { + Some(Ok(saved)) => { + self.saved = Some(saved.clone()); + self.draft.save_result = None; + self.validation = None; + self.conflict = false; + self.view = View::Map; + self.clear_editors(); + true + } + Some(Err(error)) => { + self.conflict |= error.code == "E_CONFLICT" || !error.changed.is_empty(); + self.error = Some(error.clone()); + false + } + None => false, + } + } + + fn stash_draft(&mut self) { + if !self.draft.changes.is_empty() || self.draft.save_result.is_some() { + self.stashed + .insert(self.selection.clone(), std::mem::take(&mut self.draft)); + } + } + + fn restore_draft(&mut self) { + self.draft = self.stashed.remove(&self.selection).unwrap_or_default(); + self.present_save(); + } + + fn clear_editors(&mut self) { + self.validation_task = None; + self.inputs.clear(); + self.editor = None; + self.active_cell = None; + self.pending_focus = None; + self.revision += 1; + } + + fn revert_draft(&mut self) { + self.draft.changes.clear(); + self.draft.save_result = None; + self.error = None; + self.validation = None; + self.clear_editors(); + } + + fn settle_report(&mut self, report: Result) { + self.loading = false; + if let Ok(data) = &report { + let current = data.revisions(); + if self.draft.changes.is_empty() { + self.draft.base = current; + } else { + self.conflict |= self.draft.base != current; + } + if !data + .services + .iter() + .any(|service| service.name == self.service) + { + self.service = data + .services + .first() + .map_or_else(String::new, |service| service.name.clone()); + } + if self.scope.is_empty() + || (self.scope != "global" + && self.scope != "host" + && !data + .services + .iter() + .any(|service| service.name == self.scope)) + { + self.scope = if self.service.is_empty() { + "global".into() + } else { + self.service.clone() + }; + } + if data.layer(&self.file).is_none() { + self.file = "1".into(); + } + } + self.report = Some(report); + } +} + +impl HackApp { + pub(crate) fn sync_config_tab(&mut self, cx: &mut Context) { + if self.tab != TAB || !self.live { + self.config.watch = None; + return; + } + let Some((root, native)) = self.selected_root() else { + return; + }; + let key = self.model.selected_key(); + let cli = self + .source + .cli_choice() + .and_then(|choice| choice.selected.map(|install| install.path)); + if native { + self.config.stash_draft(); + self.config = ConfigPane { + project: key, + selection: Selection { + cli, + ..Selection::default() + }, + stashed: std::mem::take(&mut self.config.stashed), + save_generation: self.config.save_generation, + ..ConfigPane::default() + }; + return; + } + if self.config.project != key + || self.config.project_root != root + || self.config.selection.cli != cli + { + #[cfg(hack_terminal)] + self.collapse_detail_terminal(cx); + self.config.stash_draft(); + let branch = key.as_ref().and_then(|key| key.branch.clone()); + let selection = Selection { + cli, + root: root.clone(), + target: ConfigTarget { + branch, + overlay: None, + }, + }; + self.config = ConfigPane { + project: key, + project_root: root, + stashed: std::mem::take(&mut self.config.stashed), + save_generation: self.config.save_generation, + selection, + ..ConfigPane::default() + }; + self.config.restore_draft(); + self.load_config(false, cx); + self.load_config_copies(cx); + } else if self.config.report.is_none() && !self.config.loading { + self.load_config(false, cx); + } + self.watch_config(cx); + } + + fn load_config_copies(&mut self, cx: &mut Context) { + let root = self.config.project_root.clone(); + let cli = self.config.selection.cli.clone(); + let epoch = self.model.source_epoch(); + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + self.config.copies_task = Some(cx.spawn(async move |this, cx| { + let copies = cx + .background_executor() + .spawn(async move { source.copies(&root, false) }) + .await; + let _ = this.update(cx, |app, cx| { + if app.model.source_epoch() != epoch { + return; + } + app.config.copies_task = None; + if let Ok(report) = copies { + app.config.choices = report + .copies + .into_iter() + .map(|copy| { + let label = copy.branch.unwrap_or_else(|| copy.checkout.name.clone()); + ( + label, + Selection { + cli: cli.clone(), + root: PathBuf::from(copy.checkout.root), + target: ConfigTarget { + branch: copy.instance, + overlay: None, + }, + }, + ) + }) + .collect(); + } + cx.notify(); + }); + })); + } + + fn load_config(&mut self, keep: bool, cx: &mut Context) { + let selection = self.config.selection.clone(); + if !self.live || selection.root.as_os_str().is_empty() { + return; + } + if !keep { + self.config.report = None; + } + self.config.loading = true; + let epoch = self.model.source_epoch(); + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + self.config.load_task = Some(cx.spawn(async move |this, cx| { + let result = cx + .background_executor() + .spawn(async move { source.config_show(&selection.root, &selection.target) }) + .await; + let _ = this.update(cx, |app, cx| { + if app.model.source_epoch() != epoch { + return; + } + app.config.load_task = None; + app.config.inputs.clear(); + app.config.editor = None; + app.config.settle_report(result); + app.queue_config_validation(cx); + cx.notify(); + }); + })); + cx.notify(); + } + + fn watch_config(&mut self, cx: &mut Context) { + if self.config.watch.is_some() { + return; + } + self.config.watch = Some(cx.spawn(async move |this, cx| { + loop { + cx.background_executor().timer(Duration::from_secs(4)).await; + let Ok(request) = this.update(cx, |app, _| { + let pane = &app.config; + (app.tab == TAB + && app.pane == crate::doctor_view::Pane::Project + && !pane.loading + && !pane.saving() + && pane.load_task.is_none() + && !pane.conflict + && pane.report().is_some()) + .then(|| { + ( + pane.selection.clone(), + app.source.pinned().unwrap_or_else(|| app.source.clone()), + pane.revision, + app.model.source_epoch(), + ) + }) + }) else { + break; + }; + let Some((selection, source, revision, epoch)) = request else { + continue; + }; + let target = selection.clone(); + let result = cx + .background_executor() + .spawn(async move { source.config_show(&target.root, &target.target) }) + .await; + if this + .update(cx, |app, cx| { + let pane = &mut app.config; + if app.model.source_epoch() != epoch + || pane.selection != selection + || pane.revision != revision + || pane.saving() + || pane.loading + { + return; + } + if let (Some(previous), Ok(next)) = (pane.report(), result) + && (previous.state != next.state + || previous.revisions() != next.revisions()) + { + if previous.state == ConfigState::Missing { + pane.settle_report(Ok(next)); + app.load_config_copies(cx); + } else { + pane.conflict = true; + } + cx.notify(); + } + }) + .is_err() + { + break; + } + } + })); + } + + fn select_config_target(&mut self, selection: Selection, cx: &mut Context) { + if self.config.selection == selection || self.config.saving() || self.config.restarting { + return; + } + self.config.stash_draft(); + self.config.selection = selection; + self.config.clear_editors(); + self.config.conflict = false; + self.config.saved = None; + self.config.error = None; + self.config.validation = None; + self.config.restore_draft(); + self.load_config(false, cx); + } + + fn reload_config(&mut self, cx: &mut Context) { + if self.config.saving() { + return; + } + self.config.draft = Draft::default(); + self.config.error = None; + self.config.conflict = false; + self.config.validation = None; + self.config.clear_editors(); + self.load_config(false, cx); + self.load_config_copies(cx); + } + + fn stage_config(&mut self, id: String, change: Option, cx: &mut Context) { + if self.config.loading || self.config.saving() || self.config.conflict { + return; + } + self.config.stage(id, change); + self.queue_config_validation(cx); + cx.notify(); + } + + fn queue_config_validation(&mut self, cx: &mut Context) { + self.config.validation_task = None; + if !self.live + || self.config.draft.changes.is_empty() + || self.config.conflict + || self.config.saving() + { + return; + } + let revision = self.config.revision; + let epoch = self.model.source_epoch(); + let patch = self.config.patch(); + let selection = self.config.selection.clone(); + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + self.config.validation_task = Some(cx.spawn(async move |this, cx| { + cx.background_executor() + .timer(Duration::from_millis(270)) + .await; + let result = + cx.background_executor() + .spawn(async move { + source.config_validate(&selection.root, &selection.target, &patch) + }) + .await; + let _ = this.update(cx, |app, cx| { + if app.model.source_epoch() != epoch || app.config.revision != revision { + return; + } + app.config.validation_task = None; + match result { + Ok(check) => { + app.config.conflict |= + check.issues.iter().any(|issue| issue.code == "E_CONFLICT"); + app.config.validation = Some(check); + } + Err(error) => app.config.error = Some(error), + } + cx.notify(); + }); + })); + } + + fn save_config(&mut self, cx: &mut Context) { + if !self.live || !self.config.can_save() { + return; + } + let patch = self.config.patch(); + let selection = self.config.selection.clone(); + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + let epoch = self.model.source_epoch(); + let operation = self.config.begin_save(epoch); + cx.spawn(async move |this, cx| { + let result = cx + .background_executor() + .spawn({ + let selection = selection.clone(); + async move { source.config_apply(&selection.root, &selection.target, &patch) } + }) + .await; + let _ = this.update(cx, |app, cx| { + if !app.config.finish_save(&selection, operation, result) { + return; + } + if app.config.present_save() { + app.load_config(true, cx); + } + cx.notify(); + }); + }) + .detach(); + cx.notify(); + } + + fn restart_config(&mut self, cx: &mut Context) { + let Some(report) = self.config.report() else { + return; + }; + let Some(root) = report.checkout.as_ref().map(PathBuf::from) else { + return; + }; + if !self.live || self.config.restarting { + return; + } + let target = ConfigTarget { + branch: report.branch.clone(), + overlay: self.config.selection.target.overlay.clone(), + }; + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + let selection = self.config.selection.clone(); + let epoch = self.model.source_epoch(); + self.config.restarting = true; + cx.spawn(async move |this, cx| { + let outcome = cx + .background_executor() + .spawn(async move { source.config_restart(&root, &target) }) + .await; + let _ = this.update(cx, |app, cx| { + if app.model.source_epoch() != epoch || app.config.selection != selection { + return; + } + app.config.restarting = false; + if outcome.is_ok() { + app.config.saved = None; + app.refresh_now_async(cx); + } else { + app.config.error = Some(ConfigError { + code: "E_RESTART".into(), + message: "Restart failed. Check the copy’s status and try again.".into(), + issues: vec![], + changed: vec![], + }); + } + cx.notify(); + }); + }) + .detach(); + cx.notify(); + } + + pub(crate) fn config_checkout_picker(&self, cx: &mut Context) -> AnyElement { + let pane = &self.config; + let name = pane + .choices + .iter() + .find(|(_, choice)| { + choice.root == pane.selection.root + && choice.target.branch == pane.selection.target.branch + }) + .map(|(name, _)| name.clone()) + .or_else(|| pane.report().and_then(|report| report.branch.clone())) + .unwrap_or_else(|| "main".into()); + let choices = if pane.choices.is_empty() { + vec![("main".into(), pane.selection.clone())] + } else { + pane.choices.clone() + }; + let overlay = pane.selection.target.overlay.clone(); + picker( + "config-checkout", + format!("Viewing as {name}"), + choices, + cx, + move |app, mut selection, cx| { + selection.target.overlay.clone_from(&overlay); + app.select_config_target(selection, cx); + }, + ) + } + + pub(crate) fn config_view( + &mut self, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + if self.model.selected_row().is_some_and(|row| row.is_native()) { + return div() + .px(space::S8) + .child("Config editing is available for Compose projects.") + .into_any_element(); + } + let report = self.config.report().cloned(); + let overlay = report + .as_ref() + .and_then(|report| report.overlay.clone()) + .unwrap_or_else(|| "default".into()); + let overlays = std::iter::once("default".to_owned()) + .chain(report.iter().flat_map(|report| report.overlays.clone())) + .map(|name| (name.clone(), name)) + .collect(); + let mut bar = div().flex().items_center().gap(space::S6).child(picker( + "config-overlay", + format!("Env: {overlay}"), + overlays, + cx, + |app, value, cx| { + let mut selection = app.config.selection.clone(); + selection.target.overlay = Some(value); + app.select_config_target(selection, cx); + }, + )); + for (index, (tab, name)) in [ + (View::Map, "Map"), + (View::Edit, "Edit"), + (View::Env, "Env layers"), + (View::Source, "Source"), + ] + .into_iter() + .enumerate() + { + bar = bar.child( + config_tab(("config-view", index), name, self.config.view == tab, ui).on_click( + cx.listener(move |app, _, _, cx| { + if tab == View::Map && app.config.view == View::Map { + app.config.saved = None; + } + app.config.view = tab; + cx.notify(); + }), + ), + ); + } + bar = bar.child(div().flex_1()); + if self.config.view == View::Env + && let Some(report) = &report + { + bar = bar.child(self.scope_picker(report, cx)); + } else if !self.config.draft.changes.is_empty() { + let count = self.config.draft.changes.len(); + bar = bar.child(muted(format!("{count} {}", change_noun(count)), ui)); + } + let body = match &self.config.report { + Some(Err(error)) => { + let message = error.message.clone(); + self.config_failure(message, ui, cx) + } + _ => match report { + None => config_loading(ui), + Some(report) if report.state == ConfigState::Missing => self.config_missing(ui, cx), + Some(report) if self.config.view == View::Source => { + self.config_source(&report, ui, window, cx) + } + Some(report) if report.state == ConfigState::Invalid => { + self.config_invalid(&report, ui, cx) + } + Some(_) if self.config.saved.is_some() && self.config.view == View::Map => { + self.config_saved(ui, cx) + } + Some(report) => match self.config.view { + View::Map => self.config_map(&report, ui, cx), + View::Edit => self.config_form(&report, ui, window, cx), + View::Env => self.config_env_grid(&report, ui, window, cx), + View::Source => unreachable!(), + }, + }, + }; + let read_only = self + .config + .report() + .is_some_and(|report| report.state == ConfigState::Ready && !report.writable); + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .px(space::S8) + .pb(space::S5) + .gap(space::S4) + .child(bar) + .when(read_only, |d| { + d.child(muted("This checkout is read-only.", ui)) + }) + .child(div().flex_1().min_h_0().flex().flex_col().child(body)) + .children(self.config_dock(ui, cx)) + .into_any_element() + } + + fn config_dock(&self, ui: &Ui, cx: &mut Context) -> Option { + let pane = &self.config; + if pane.conflict { + return Some( + card(ui) + .px(space::S4) + .py(space::S3) + .flex() + .items_center() + .gap(space::S3) + .child("Changed outside Hack") + .child( + action_button("config-reload", Glyph::Restart, "Reload", true, ui) + .on_click(cx.listener(|app, _, _, cx| app.reload_config(cx))), + ) + .into_any_element(), + ); + } + let count = pane.draft.changes.len(); + let error = pane.error.as_ref(); + if count == 0 && error.is_none() { + return None; + } + let first = pane.issues().first().cloned(); + let issue_label = first.as_ref().map(|issue| { + if pane.view == View::Source + && let Some(line) = issue.line + { + format!("Line {line} needs a fix") + } else { + let n = pane.issues().len(); + format!( + "{n} {} need{} a fix", + if n == 1 { "field" } else { "fields" }, + if n == 1 { "s" } else { "" } + ) + } + }); + let can_save = pane.can_save(); + let saved = if can_save { + primary_button("config-save", Glyph::Check, "Save", ui) + .on_click(cx.listener(|app, _, _, cx| app.save_config(cx))) + } else { + action_button( + "config-save", + Glyph::Check, + if pane.saving() { "Saving…" } else { "Save" }, + false, + ui, + ) + }; + Some( + card(ui) + .px(space::S4) + .py(space::S3) + .flex() + .items_center() + .gap(space::S3) + .child(strong( + format!("{count} unsaved {}", change_noun(count)), + ui, + )) + .children(error.map(|error| warning(error.message.clone(), ui))) + .child(div().flex_1()) + .children(first.zip(issue_label).map(|(issue, label)| { + warning(label, ui) + .id("config-jump-issue") + .underline() + .cursor_pointer() + .on_click( + cx.listener(move |app, _, _, cx| app.jump_config_issue(&issue, cx)), + ) + })) + .child( + action_button( + "config-revert", + Glyph::Restart, + "Revert", + !pane.saving(), + ui, + ) + .w(px(96.)) + .on_click(cx.listener(|app, _, _, cx| { + if !app.config.saving() { + app.config.revert_draft(); + cx.notify(); + } + })), + ) + .child(saved.w(px(96.))) + .into_any_element(), + ) + } + + fn config_failure(&self, message: String, ui: &Ui, cx: &mut Context) -> AnyElement { + state_card("Can’t read config", message, ui) + .child( + action_button("config-try", Glyph::Restart, "Reload", true, ui) + .on_click(cx.listener(|app, _, _, cx| app.reload_config(cx))), + ) + .into_any_element() + } + + fn config_invalid(&self, report: &ConfigReport, ui: &Ui, cx: &mut Context) -> AnyElement { + let issue = report + .issues + .iter() + .find(|issue| issue.code == "E_CONFIG_PARSE") + .cloned(); + let layer = issue + .as_ref() + .and_then(|issue| issue.layer.as_deref()) + .and_then(|id| report.layer(id)); + let title = layer.map_or_else( + || "Can’t read config".to_owned(), + |layer| format!("{} has a syntax error", layer.name()), + ); + let detail = issue.as_ref().map_or_else(String::new, |issue| { + issue.line.map_or_else( + || issue.message.clone(), + |line| format!("Line {line} · {}", issue.message), + ) + }); + state_card(title, detail, ui) + .child( + div() + .flex() + .gap(space::S3) + .children(issue.map(|issue| { + action_button("config-error-source", Glyph::Logs, "Open source", true, ui) + .w(STATE_ACTION_WIDTH) + .justify_center() + .on_click( + cx.listener(move |app, _, _, cx| app.jump_config_issue(&issue, cx)), + ) + })) + .children(layer.filter(|layer| layer.exists).map(|layer| { + self.editor_button(layer.file.clone(), ui, cx) + .w(STATE_ACTION_WIDTH) + .justify_center() + })), + ) + .child(muted("Running copies keep using the last good config.", ui)) + .into_any_element() + } + + #[cfg(hack_terminal)] + fn run_config_init(&mut self, window: &mut Window, cx: &mut Context) { + use hack_desktop_core::terminal::{ + CommandAvailability, CommandControl, CommandControlSize, CommandExit, + }; + let selection = self.config.selection.clone(); + let source = self.source.pinned().unwrap_or_else(|| self.source.clone()); + let epoch = self.model.source_epoch(); + let spec = match source.config_init_command() { + Ok(spec) => spec, + Err(message) => { + self.config.error = Some(ConfigError { + message, + ..ConfigError::unavailable() + }); + cx.notify(); + return; + } + }; + self.config.error = None; + self.run_init_in_drawer( + CommandControl { + id: format!("config-init:{}", selection.root.display()), + label: "hack init".into(), + title: "Terminal".into(), + availability: CommandAvailability::Ready(spec), + size: CommandControlSize::Standard, + cwd: Some(selection.root.clone()), + expects_password: false, + }, + move |app, completion, cx| { + if completion.exit == CommandExit::Code(0) { + app.check_config_init(selection, source, epoch, completion.run, cx); + } + }, + window, + cx, + ); + } + + #[cfg(hack_terminal)] + fn check_config_init( + &mut self, + selection: Selection, + source: std::sync::Arc, + epoch: u64, + run: crate::command_control::CommandRunId, + cx: &mut Context, + ) { + cx.spawn(async move |app, cx| { + let target = selection.clone(); + let report = cx + .background_executor() + .spawn(async move { source.config_show(&target.root, &target.target) }) + .await; + let _ = app.update(cx, |app, cx| { + if app.model.source_epoch() != epoch { + return; + } + let check = match &report { + Ok(report) if report.state == ConfigState::Ready => Ok(()), + _ => Err("The checkout’s Config is still unavailable.".into()), + }; + app.command_checked(run, check, cx); + app.refresh_now_async(cx); + if app.config.selection == selection && app.tab == TAB { + app.load_config(true, cx); + app.load_config_copies(cx); + } + }); + }) + .detach(); + } + + fn config_missing(&self, ui: &Ui, cx: &mut Context) -> AnyElement { + let can_run = cfg!(hack_terminal) + && !self.config.selection.root.as_os_str().is_empty() + && !self.machine.busy(); + let run = if can_run { + primary_button("config-init", Glyph::Play, "Run", ui) + } else { + action_button("config-init", Glyph::Play, "Run", false, ui) + }; + state_card( + "This folder has no .hack config", + "Set it up once and every worktree shares it.", + ui, + ) + .child( + card(ui) + .px(space::S3) + .py(space::S2) + .flex() + .items_center() + .gap(space::S2) + .child(mono("hack init", ui).flex_1()) + .child( + run.w(px(76.)) + .on_click(cx.listener(|_app, _, _window, _cx| { + #[cfg(hack_terminal)] + _app.run_config_init(_window, _cx); + })), + ) + .child( + action_button("config-init-copy", Glyph::Copy, "Copy", true, ui) + .w(px(76.)) + .on_click(|_, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string("hack init".into())) + }), + ), + ) + .child(muted( + "Run opens the terminal drawer and runs it there.", + ui, + )) + .children( + self.config + .error + .as_ref() + .map(|error| muted(error.message.clone(), ui)), + ) + .into_any_element() + } + + fn config_saved(&self, ui: &Ui, cx: &mut Context) -> AnyElement { + let Some(saved) = &self.config.saved else { + return div().into_any_element(); + }; + let detail = if saved.restart_offered { + "This copy picks up the changes on its next restart." + } else if saved.changed.is_empty() { + "The files already match these settings." + } else { + "Env changes apply on the next start of each service." + }; + state_card("Saved just now", detail, ui) + .child( + div() + .flex() + .gap(space::S3) + .when(saved.restart_offered, |row| { + row.child( + action_button( + "config-restart", + Glyph::Restart, + if self.config.restarting { + "Restarting…" + } else { + "Restart now" + }, + !self.config.restarting, + ui, + ) + .w(STATE_ACTION_WIDTH) + .justify_center() + .on_click(cx.listener(|app, _, _, cx| app.restart_config(cx))), + ) + }) + .child( + action_button("config-view-changes", Glyph::Eye, "View changes", true, ui) + .w(STATE_ACTION_WIDTH) + .justify_center() + .on_click(cx.listener(|app, _, _, cx| { + if let Some(id) = app + .config + .saved + .as_ref() + .and_then(|saved| saved.changed.first()) + { + app.config.file.clone_from(id); + } + app.config.view = View::Source; + cx.notify(); + })), + ), + ) + .into_any_element() + } +} + +pub(crate) fn config_tab( + id: impl Into, + label: impl Into, + selected: bool, + ui: &Ui, +) -> gpui_kit::Stateful { + div() + .id(id) + .relative() + .h(px(30.)) + .flex() + .items_center() + .cursor_pointer() + .type_step(if selected { + text::BODY_STRONG + } else { + text::BODY + }) + .text_color(if selected { + ui.p.text_primary + } else { + ui.p.text_muted + }) + .child(label.into()) + .when(selected, |d| { + d.child( + div() + .absolute() + .bottom_0() + .left_0() + .right_0() + .h(px(2.)) + .rounded(px(1.)) + .bg(ui.p.text_primary), + ) + }) +} + +fn picker( + id: &'static str, + label: String, + choices: Vec<(String, T)>, + cx: &Context, + select: impl Fn(&mut HackApp, T, &mut Context) + Clone + 'static, +) -> AnyElement { + let view = cx.entity().downgrade(); + Button::new(id) + .outline() + .label(format!("{label} ⌄")) + .dropdown_menu(move |mut menu, _, _| { + for (label, value) in &choices { + let view = view.clone(); + let select = select.clone(); + let value = value.clone(); + menu = menu.item(PopupMenuItem::new(label.clone()).on_click(move |_, _, cx| { + let _ = view.update(cx, |app, cx| select(app, value.clone(), cx)); + })); + } + menu + }) + .into_any_element() +} + +fn card(ui: &Ui) -> gpui_kit::Div { + div().border_1().border_color(ui.p.border).rounded(px(8.)) +} + +fn state_card( + title: impl Into, + detail: impl Into, + ui: &Ui, +) -> gpui_kit::Div { + card(ui) + .max_w(px(480.)) + .p(space::S6) + .flex() + .flex_col() + .gap(space::S4) + .child(div().type_step(text::TITLE).child(title.into())) + .child(div().type_step(text::BODY).child(detail.into())) +} + +fn config_loading(ui: &Ui) -> AnyElement { + div() + .flex() + .flex_col() + .gap(space::S3) + .child(muted("Reading project config…", ui)) + .children((0..5).map(|_| card(ui).h(px(46.)).w(px(230.)))) + .into_any_element() +} + +fn muted(label: impl Into, ui: &Ui) -> gpui_kit::Div { + div() + .type_step(text::SMALL) + .text_color(ui.p.text_muted) + .child(label.into()) +} + +fn change_noun(count: usize) -> &'static str { + if count == 1 { "change" } else { "changes" } +} + +fn strong(label: impl Into, ui: &Ui) -> gpui_kit::Div { + div() + .type_step(text::BODY_STRONG) + .text_color(ui.p.text_primary) + .child(label.into()) +} + +fn mono(label: impl Into, ui: &Ui) -> gpui_kit::Div { + div() + .font_family(ui.mono.clone()) + .type_step(text::MONO) + .child(label.into()) +} + +fn warning(label: impl Into, ui: &Ui) -> gpui_kit::Div { + div() + .flex() + .items_center() + .gap(space::S2) + .type_step(text::SMALL) + .text_color(ui.p.states.failed.fg) + .child(icon(Glyph::CircleAlert, px(13.), ui.p.states.failed.fg)) + .child(label.into()) +} + +fn chip(label: impl Into, active: bool, ui: &Ui) -> gpui_kit::Div { + mono(label, ui) + .flex_shrink_0() + .px(px(4.)) + .rounded(px(4.)) + .border_1() + .border_color(if active { + ui.p.text_primary + } else { + ui.p.border + }) +} + +fn setting<'a>(project: &'a Value, key: &str) -> &'a Value { + key.split('.').fold(project, |value, part| &value[part]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn select(pane: &mut ConfigPane, selection: &Selection) { + pane.stash_draft(); + pane.selection = selection.clone(); + pane.error = None; + pane.restore_draft(); + } + + fn stage_name(pane: &mut ConfigPane) { + pane.stage( + "name".into(), + Some(ConfigChange::Project { + layer: "1".into(), + path: "name".into(), + value: Value::String("storefront".into()), + }), + ); + } + + #[test] + fn a_pending_save_preserves_its_draft_and_failure_across_project_switches() { + let mut pane = ConfigPane::default(); + let storefront = Selection { + root: "/storefront".into(), + ..Selection::default() + }; + let other = Selection { + root: "/other".into(), + ..Selection::default() + }; + select(&mut pane, &storefront); + stage_name(&mut pane); + let operation = pane.begin_save(1); + + select(&mut pane, &other); + select(&mut pane, &storefront); + assert!(pane.saving()); + select(&mut pane, &other); + assert!(!pane.finish_save(&storefront, operation, Err(ConfigError::unavailable()))); + select(&mut pane, &storefront); + assert!(!pane.saving()); + assert!(pane.draft.changes.contains_key("name")); + assert_eq!( + pane.error.as_ref().map(|e| e.code.as_str()), + Some("E_UNAVAILABLE") + ); + + stage_name(&mut pane); + let retry = pane.begin_save(1); + let saved = ConfigSaved { + changed: vec!["1".into()], + restart_offered: true, + }; + assert!(!pane.finish_save(&storefront, operation, Ok(saved.clone()))); + assert!(pane.draft.changes.contains_key("name")); + assert!(pane.finish_save(&storefront, retry, Ok(saved))); + assert!(pane.draft.changes.is_empty()); + } + + #[test] + fn the_previous_cli_cannot_complete_a_new_installations_save() { + let mut pane = ConfigPane::default(); + let first = Selection { + cli: Some("/cli/first/hack".into()), + ..Selection::default() + }; + let second = Selection { + cli: Some("/cli/second/hack".into()), + ..Selection::default() + }; + select(&mut pane, &first); + stage_name(&mut pane); + let first_save = pane.begin_save(1); + + pane.switch_cli(second.cli.clone()); + select(&mut pane, &second); + stage_name(&mut pane); + let second_save = pane.begin_save(2); + assert!(!pane.finish_save(&first, first_save, Err(ConfigError::unavailable()))); + assert!(pane.saving()); + assert!(pane.draft.save_result.is_none()); + + pane.switch_cli(first.cli.clone()); + select(&mut pane, &first); + assert!(!pane.saving()); + assert!(pane.draft.changes.contains_key("name")); + assert!(pane.error.is_some()); + assert!(!pane.finish_save(&second, second_save, Err(ConfigError::unavailable()))); + } + + #[test] + fn reverting_a_failed_save_discards_its_error_with_the_draft() { + let mut pane = ConfigPane::default(); + let first = pane.selection.clone(); + stage_name(&mut pane); + let operation = pane.begin_save(1); + assert!(pane.finish_save(&first, operation, Err(ConfigError::unavailable()))); + assert!(!pane.present_save()); + assert!(pane.error.is_some()); + + pane.revert_draft(); + let other = Selection { + root: "/other".into(), + ..Selection::default() + }; + select(&mut pane, &other); + select(&mut pane, &first); + assert!(pane.draft.changes.is_empty()); + assert!(pane.error.is_none()); + } +} diff --git a/apps/desktop/app/src/config_view/forms.rs b/apps/desktop/app/src/config_view/forms.rs new file mode 100644 index 0000000000..8c43b8166b --- /dev/null +++ b/apps/desktop/app/src/config_view/forms.rs @@ -0,0 +1,1719 @@ +use std::path::PathBuf; + +use gpui_kit::component::input::{Editor, EditorState, Input, InputEvent, InputState, Position}; +use gpui_kit::prelude::*; +use gpui_kit::{ + AnyElement, ClipboardItem, Context, Div, Entity, IntoElement, SharedString, Window, div, px, + relative, +}; +use hack_desktop_core::config::{ + ConfigChange, ConfigIssue, ConfigLayer, ConfigReport, ConfigService, EnvCell, EnvRow, + scalar_label, +}; +use hack_desktop_ui::{ + components::{StyledExt as _, Ui, action_button, icon}, + icons::Glyph, + tokens::space, +}; +use serde_json::Value; + +use super::{ + EditSection, View, card, chip, + map::{caption, layer_chip, layer_description, layer_title}, + mono, muted, picker, setting, strong, warning, +}; +use crate::view::HackApp; + +#[derive(Clone)] +enum Field { + Project(String), + Route { + service: String, + port: bool, + sites: String, + upstream: String, + }, + ServiceImage(String), + ServiceList { + service: String, + field: String, + }, + Env { + layer: String, + scope: String, + key: String, + }, +} + +impl Field { + fn id(&self) -> String { + match self { + Self::Project(path) => format!("project/{path}"), + Self::Route { service, port, .. } => { + format!("route/{service}/{}", if *port { "port" } else { "sites" }) + } + Self::ServiceImage(service) => format!("service/{service}/image"), + Self::ServiceList { service, field } => format!("service/{service}/{field}"), + Self::Env { layer, scope, key } => format!("env/{layer}/{scope}/{key}"), + } + } + + fn item(&self) -> String { + match self { + Self::Route { service, .. } => format!("route/{service}"), + _ => self.id(), + } + } + + fn stage( + &self, + app: &mut HackApp, + value: String, + original: Option<&str>, + cx: &mut Context, + ) { + let id = self.item(); + let text_changed = Some(value.as_str()) != original; + let changed = match self { + Self::Project(path) => text_changed.then(|| ConfigChange::Project { + layer: "1".into(), + path: path.clone(), + value: Value::String(value), + }), + Self::Route { + service, + port, + sites, + upstream, + } => { + let (mut hosts, mut number) = match app.config.draft.changes.get(&id) { + Some(ConfigChange::Route { sites, port, .. }) => (sites.clone(), port.clone()), + _ => (sites.clone(), upstream.clone()), + }; + if *port { + number = value; + } else { + hosts = value; + } + (hosts != *sites || number != *upstream).then(|| ConfigChange::Route { + layer: "2".into(), + service: service.clone(), + sites: hosts, + port: number, + }) + } + Self::ServiceImage(service) => text_changed.then(|| ConfigChange::Service { + layer: "2".into(), + service: service.clone(), + field: "image".into(), + value: Value::String(value), + }), + Self::ServiceList { service, field } => text_changed.then(|| ConfigChange::Service { + layer: "2".into(), + service: service.clone(), + field: field.clone(), + value: Value::Array( + value + .split(',') + .map(str::trim) + .filter(|part| !part.is_empty()) + .map(|part| Value::String(part.into())) + .collect(), + ), + }), + Self::Env { layer, scope, key } => text_changed.then(|| ConfigChange::Env { + layer: layer.clone(), + scope: scope.clone(), + key: key.clone(), + value: Some(value), + }), + }; + app.stage_config(id, changed, cx); + } + + fn value(&self, app: &HackApp, original: &str) -> String { + let Some(edit) = app.config.draft.changes.get(&self.item()) else { + return original.to_owned(); + }; + match edit { + ConfigChange::Project { value, .. } | ConfigChange::Service { value, .. } => { + value.as_array().map_or_else( + || scalar_label(value), + |values| { + values + .iter() + .map(scalar_label) + .collect::>() + .join(", ") + }, + ) + } + ConfigChange::Route { sites, port, .. } => { + if matches!(self, Self::Route { port: true, .. }) { + port.clone() + } else { + sites.clone() + } + } + ConfigChange::Env { value, .. } => value.clone().unwrap_or_default(), + ConfigChange::Source { .. } => original.to_owned(), + } + } +} + +impl HackApp { + fn field_input( + &mut self, + field: Field, + original: Option, + window: &mut Window, + cx: &mut Context, + ) -> Entity { + let id = field.id(); + if let Some((input, _)) = self.config.inputs.get(&id) { + return input.clone(); + } + let value = field.value(self, original.as_deref().unwrap_or_default()); + let state = cx.new(|cx| { + let mut input = InputState::new(window, cx); + input.set_value(value, window, cx); + input + }); + let subscription = cx.subscribe(&state, move |app, state, event, cx| { + if matches!(event, InputEvent::Change) + || (original.is_none() && matches!(event, InputEvent::PressEnter { .. })) + { + field.stage( + app, + state.read(cx).value().to_string(), + original.as_deref(), + cx, + ); + } + }); + self.config.inputs.insert(id, (state.clone(), subscription)); + state + } + + fn field_control( + &mut self, + field: Field, + original: Option, + enabled: bool, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let id = field.id(); + let issue = self + .config + .issues() + .iter() + .find(|issue| issue_field(issue).as_deref() == Some(id.as_str())) + .cloned(); + let input = self.field_input(field, original, window, cx); + if self.config.pending_focus.as_deref() == Some(id.as_str()) { + self.config.pending_focus = None; + input.update(cx, |input, cx| input.focus(window, cx)); + } + div() + .min_w_0() + .flex() + .flex_col() + .gap(space::S1) + .child( + div() + .rounded(px(5.)) + .when(issue.is_some(), |d| { + d.border_1().border_color(ui.p.states.failed.fg) + }) + .child( + Input::new(&input) + .disabled(!enabled) + .font_family(ui.mono.clone()), + ), + ) + .children(issue.map(|issue| warning(issue.message, ui))) + } + + pub(super) fn config_form( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + let groups = [ + (EditSection::Project, "Project", Glyph::Container), + (EditSection::Routes, "Routes", Glyph::Globe), + (EditSection::Services, "Services", Glyph::Logs), + (EditSection::Env, "Env", Glyph::Key), + (EditSection::Worktrees, "Worktrees", Glyph::Branch), + ]; + let sidebar = + div() + .w(relative(0.20)) + .min_w(px(125.)) + .flex_shrink_0() + .flex() + .flex_col() + .gap(space::S1) + .children( + groups + .into_iter() + .enumerate() + .map(|(index, (group, label, glyph))| { + let selected = self.config.edit_section == group; + let issue = self + .config + .issues() + .iter() + .any(|issue| issue_section(issue) == group); + div() + .id(("config-field-group", index)) + .h(px(31.)) + .px(space::S3) + .rounded(px(5.)) + .cursor_pointer() + .flex() + .items_center() + .gap(space::S3) + .when(selected, |d| d.bg(ui.p.surface_2)) + .child(icon(glyph, px(15.), ui.p.text_secondary)) + .child(if selected { + strong(label, ui) + } else { + muted(label, ui) + }) + .child(div().flex_1()) + .children(issue.then(|| { + icon(Glyph::CircleAlert, px(13.), ui.p.states.failed.fg) + })) + .on_click(cx.listener(move |app, _, _, cx| { + app.config.edit_section = group; + cx.notify(); + })) + }), + ); + let body = match self.config.edit_section { + EditSection::Project => self.config_project_form(report, ui, window, cx), + EditSection::Routes => self.config_route_form(report, ui, window, cx), + EditSection::Services => self.config_services_form(report, ui, window, cx), + EditSection::Env => { + let enabled = self.field_enabled(report, "1"); + let path = "env.defaultOverlay"; + let original = report + .default_overlay + .clone() + .unwrap_or_else(|| legacy_default_overlay(&report.project)); + let field = self.field_control( + Field::Project(path.into()), + Some(original), + enabled, + ui, + window, + cx, + ); + div() + .flex() + .flex_col() + .gap(space::S3) + .child(group_title("Environment selection", report, "1", ui)) + .child(field_row( + "Default overlay", + "Used when no overlay is selected", + field, + ui, + )) + .child( + action_button("config-to-env", Glyph::Key, "Open Env layers", true, ui) + .on_click(cx.listener(|app, _, _, cx| { + app.config.view = View::Env; + cx.notify(); + })), + ) + } + EditSection::Worktrees => { + let enabled = self.field_enabled(report, "1"); + div() + .flex() + .flex_col() + .gap(space::S3) + .child(group_title("Worktree defaults", report, "1", ui)) + .child(field_row( + "Branch instances", + "Use the worktree’s branch by default", + self.config_toggle( + report, + "worktree.auto_branch", + "Auto branch", + true, + enabled, + ui, + cx, + ), + ui, + )) + .child(field_row( + "Local environment", + "Read local values from the main checkout", + self.config_toggle( + report, + "worktree.inherit_local", + "Inherit local env", + true, + enabled, + ui, + cx, + ), + ui, + )) + } + }; + div() + .flex() + .min_h_0() + .flex_1() + .gap(space::S4) + .child(sidebar) + .child( + div() + .id("config-edit-scroll") + .min_w_0() + .flex_1() + .overflow_y_scroll() + .child(body), + ) + .into_any_element() + } + + fn field_enabled(&self, report: &ConfigReport, layer: &str) -> bool { + report.layer(layer).is_some_and(|layer| layer.writable) + && !self.config.conflict + && !self.config.saving() + && !self.config.loading + && !self + .config + .draft + .changes + .contains_key(&format!("source/{layer}")) + } + + #[expect( + clippy::too_many_arguments, + reason = "native input rendering needs the window and app context" + )] + fn project_text( + &mut self, + report: &ConfigReport, + name: &str, + fallback: &str, + enabled: bool, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let initial = setting(&report.project, name) + .as_str() + .unwrap_or(fallback) + .to_owned(); + self.field_control( + Field::Project(name.into()), + Some(initial), + enabled, + ui, + window, + cx, + ) + } + + fn config_project_form( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let enabled = self.field_enabled(report, "1"); + div() + .flex() + .flex_col() + .gap(space::S2) + .child(group_title("Project settings", report, "1", ui)) + .child(field_row( + "Name", + "", + self.project_text(report, "name", "", enabled, ui, window, cx), + ui, + )) + .child(field_row( + "Open preference", + "auto, dev or alias", + self.project_text(report, "open.prefer", "auto", enabled, ui, window, cx), + ui, + )) + .child(group_title("Logs", report, "1", ui).mt(space::S4)) + .child(field_row( + "Follow backend", + "compose or loki", + self.project_text( + report, + "logs.follow_backend", + "compose", + enabled, + ui, + window, + cx, + ), + ui, + )) + .child(field_row( + "Snapshot backend", + "compose or loki", + self.project_text( + report, + "logs.snapshot_backend", + "loki", + enabled, + ui, + window, + cx, + ), + ui, + )) + .child(field_row( + "Retention period", + "", + self.project_text(report, "logs.retention_period", "", enabled, ui, window, cx), + ui, + )) + .child(field_row( + "Clear logs on Down", + "", + self.config_toggle( + report, + "logs.clear_on_down", + "Clear logs", + false, + enabled, + ui, + cx, + ), + ui, + )) + } + + fn config_route_form( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let project_enabled = self.field_enabled(report, "1"); + let routes_enabled = self.field_enabled(report, "2"); + let dev_host = self.project_text(report, "dev_host", "", project_enabled, ui, window, cx); + let dns = self.config_toggle(report, "internal.dns", "DNS", true, project_enabled, ui, cx); + let tls = self.config_toggle(report, "internal.tls", "TLS", true, project_enabled, ui, cx); + let alias = self.config_toggle( + report, + "oauth.enabled", + "Enabled", + false, + project_enabled, + ui, + cx, + ); + div() + .flex() + .flex_col() + .gap(space::S2) + .child(group_title("Host and DNS", report, "1", ui)) + .child(field_row( + "Dev host", + "Base name for project routes", + dev_host, + ui, + )) + .child(field_row( + "Internal DNS and TLS", + "Containers reach *.hack too", + div().flex().gap(space::S5).child(dns).child(tls), + ui, + )) + .child(field_row("OAuth alias", "Adds a .hack.gy name", alias, ui)) + .children( + (setting(&report.project, "oauth.enabled").as_bool() == Some(true) + || matches!( + self.config.draft.changes.get("project/oauth.enabled"), + Some(ConfigChange::Project { + value: Value::Bool(true), + .. + }) + )) + .then(|| { + field_row( + "OAuth suffix", + "", + self.project_text( + report, + "oauth.tld", + "hack.gy", + project_enabled, + ui, + window, + cx, + ), + ui, + ) + }), + ) + .child(group_title("Routes", report, "2", ui).mt(space::S5)) + .children( + report + .services + .iter() + .map(|service| self.route_form_row(service, routes_enabled, ui, window, cx)), + ) + .child(muted("Branch copies get their prefix from layer 6.", ui)) + } + + fn route_form_row( + &mut self, + service: &ConfigService, + enabled: bool, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let mut row = div() + .flex() + .items_start() + .gap(space::S3) + .py(space::S2) + .hairline_b(ui.p.border) + .child(strong(service.name.clone(), ui).w(px(72.)).mt(space::S2)); + if let Some(route) = &service.route_edit { + let port = route.port.map_or_else(String::new, |port| port.to_string()); + let field = |is_port| Field::Route { + service: service.name.clone(), + port: is_port, + sites: route.sites.clone(), + upstream: port.clone(), + }; + let hosts = self.field_control( + field(false), + Some(route.sites.clone()), + enabled, + ui, + window, + cx, + ); + let input = self.field_control(field(true), Some(port), enabled, ui, window, cx); + row = row.child(hosts.flex_1()).child(input.w(px(82.))).child( + muted( + if route.sites.is_empty() { + "internal only" + } else if service.routes.first().is_some_and(|route| !route.tls) { + "http" + } else { + "https" + }, + ui, + ) + .w(px(78.)) + .mt(space::S2), + ); + } else { + row = row.child( + action_button( + SharedString::from(format!("config-complex-route-{}", service.name)), + Glyph::Pencil, + "Edit in source", + true, + ui, + ) + .on_click(cx.listener(|app, _, _, cx| app.go_to_source("2", cx))), + ); + } + row + } + + fn config_services_form( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let enabled = self.field_enabled(report, "2"); + div() + .flex() + .flex_col() + .gap(space::S3) + .child(group_title("Services", report, "2", ui)) + .children(report.services.iter().map(|service| { + let fields = [ + ( + "image", + "Image", + "", + Field::ServiceImage(service.name.clone()), + service.image.clone().unwrap_or_default(), + ), + ( + "ports", + "Ports", + "Comma-separated Compose port mappings", + Field::ServiceList { + service: service.name.clone(), + field: "ports".into(), + }, + service + .ports + .iter() + .map(scalar_label) + .collect::>() + .join(", "), + ), + ( + "depends_on", + "Depends on", + "Service names separated by commas", + Field::ServiceList { + service: service.name.clone(), + field: "depends_on".into(), + }, + service.depends_on.join(", "), + ), + ]; + div() + .flex() + .flex_col() + .gap(space::S2) + .child(strong(service.name.clone(), ui)) + .children(fields.into_iter().map(|(id, title, hint, field, initial)| { + let control = if service.source_fields.iter().any(|field| field == id) { + div().child( + action_button( + SharedString::from(format!( + "config-complex-{}-{id}", + service.name + )), + Glyph::Pencil, + "Edit in source", + true, + ui, + ) + .on_click(cx.listener(|app, _, _, cx| app.go_to_source("2", cx))), + ) + } else { + self.field_control(field, Some(initial), enabled, ui, window, cx) + }; + field_row(title, hint, control, ui) + })) + })) + } + + #[expect( + clippy::too_many_arguments, + reason = "native input rendering needs the window and app context" + )] + fn config_toggle( + &self, + report: &ConfigReport, + path: &'static str, + label: &'static str, + fallback: bool, + enabled: bool, + ui: &Ui, + cx: &mut Context, + ) -> Div { + let id = format!("project/{path}"); + let original = project_toggle_value(&report.project, path, fallback); + let on = self + .config + .draft + .changes + .get(&id) + .and_then(|edit| match edit { + ConfigChange::Project { value, .. } => value.as_bool(), + _ => None, + }) + .unwrap_or(original); + div().child( + div() + .id(SharedString::from(format!("config-toggle-{path}"))) + .flex() + .items_center() + .gap(space::S2) + .when(enabled, |d| d.cursor_pointer()) + .child( + div() + .h(px(16.)) + .w(px(28.)) + .p(px(2.)) + .rounded_full() + .flex() + .when(on, |d| d.bg(ui.p.text_primary).justify_end()) + .when(!on, |d| d.bg(ui.p.surface_2)) + .child(div().size(px(12.)).rounded_full().bg(if on { + ui.p.surface + } else { + ui.p.text_muted + })), + ) + .child(muted(label, ui)) + .on_click(cx.listener(move |app, _, _, cx| { + if enabled { + let value = !on; + let edit = (value != original).then(|| ConfigChange::Project { + layer: "1".into(), + path: path.into(), + value: Value::Bool(value), + }); + app.stage_config(id.clone(), edit, cx); + } + })), + ) + } + + pub(super) fn scope_picker(&self, report: &ConfigReport, cx: &Context) -> AnyElement { + let choices = ["global".to_owned(), "host".to_owned()] + .into_iter() + .chain(report.services.iter().map(|service| service.name.clone())) + .map(|name| (name.clone(), name)) + .collect(); + picker( + "config-scope", + format!("Scope: {}", self.config.scope), + choices, + cx, + |app, scope, cx| { + app.config.scope = scope; + app.config.active_cell = None; + cx.notify(); + }, + ) + } + + pub(super) fn config_env_grid( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + let layers: Vec<_> = report + .layers + .iter() + .filter(|layer| layer.kind == "env" && layer.active) + .collect(); + let rows = report.env_for(&self.config.scope); + let header = div() + .flex() + .gap(space::S3) + .py(space::S3) + .hairline_b(ui.p.border) + .child( + div() + .flex_1() + .min_w_0() + .child(strong("Key", ui)) + .child(muted(format!("{} scope", self.config.scope), ui)), + ) + .children(layers.iter().map(|layer| { + let name = layer.overlay.clone().map_or_else( + || match layer.id.as_str() { + "3" => "default".to_owned(), + "4" => "main local".to_owned(), + _ => "this checkout".to_owned(), + }, + |overlay| { + if layer.ownership == "local" { + format!("{overlay} local") + } else { + overlay + } + }, + ); + div() + .flex_1() + .min_w_0() + .child( + div() + .flex() + .gap(space::S1) + .items_center() + .child(chip(layer.chip().to_owned(), false, ui)) + .child(strong(name, ui).truncate()), + ) + .child( + muted( + if layer.inherited == Some(true) { + "inherited" + } else if layer.ownership == "shared" { + "shared, committed" + } else { + "local, not committed" + }, + ui, + ) + .truncate(), + ) + })) + .child( + div() + .flex_1() + .min_w_0() + .child(strong("Resolved", ui)) + .child(muted(format!("what {} gets", self.config.scope), ui)), + ); + div() + .id("config-env-scroll") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child(header) + .when(rows.is_empty(), |d| { + d.child(muted("No keys in this scope.", ui).mt(space::S4)) + }) + .children( + rows.iter() + .map(|row| self.env_grid_row(row, &layers, report, ui, window, cx)), + ) + .into_any_element() + } + + fn env_grid_row( + &mut self, + row: &EnvRow, + layers: &[&ConfigLayer], + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let mut entries = row.values.clone(); + for change in self.config.draft.changes.values() { + let ConfigChange::Env { + layer, + scope, + key, + value, + } = change + else { + continue; + }; + if *key != row.key || (scope != "global" && *scope != self.config.scope) { + continue; + } + entries.retain(|entry| entry.layer != *layer || entry.scope != *scope); + if value.is_some() || (layer.starts_with('5') && report.layer("4").is_some()) { + entries.push(EnvCell { + layer: layer.clone(), + scope: scope.clone(), + unset: value.is_none(), + secret: false, + value: value.clone().map(Value::String), + }); + } + } + entries.sort_by_key(|entry| { + ( + layers + .iter() + .position(|layer| layer.id == entry.layer) + .unwrap_or(usize::MAX), + entry.scope != "global", + ) + }); + let winner = entries.last().filter(|entry| !entry.unset); + div() + .flex() + .items_center() + .gap(space::S3) + .min_h(px(36.)) + .py(space::S1) + .hairline_b(ui.p.border) + .child( + div() + .flex_1() + .min_w_0() + .child(mono(row.key.clone(), ui).truncate()) + .child(muted(row.scope.clone(), ui)), + ) + .children(layers.iter().map(|layer| { + let cell = entries.iter().rev().find(|entry| entry.layer == layer.id); + let original = row + .values + .iter() + .rev() + .find(|entry| entry.layer == layer.id); + let scope = cell + .or(original) + .map_or_else(|| self.config.scope.clone(), |cell| cell.scope.clone()); + let field = Field::Env { + layer: layer.id.clone(), + scope, + key: row.key.clone(), + }; + let id = field.id(); + let editable = self.field_enabled(report, &layer.id) + && !row.values.iter().any(|entry| entry.secret) + && !cell.is_some_and(|entry| entry.secret); + let title = cell.map_or_else(|| "—".into(), EnvCell::label); + let winner = winner.is_some_and(|winner| winner.layer == layer.id); + let mut entry = div().flex_1().min_w_0(); + if self.config.active_cell.as_deref() == Some(&id) && editable { + let initial = original + .filter(|cell| !cell.unset) + .and_then(|cell| cell.value.as_ref()) + .map(scalar_label); + entry = + entry.child(self.field_control(field, initial, editable, ui, window, cx)); + } else { + entry = entry.child( + div() + .id(SharedString::from(format!("config-env-cell-{}", id))) + .when(editable, |d| d.cursor_pointer()) + .child( + mono(title, ui) + .truncate() + .when(winner, |d| d.font_weight(gpui_kit::FontWeight::SEMIBOLD)) + .when(!winner && cell.is_some(), |d| { + d.line_through().text_color(ui.p.text_muted) + }), + ) + .on_click(cx.listener(move |app, _, _, cx| { + if editable { + app.config.active_cell = Some(id.clone()); + app.config.pending_focus = Some(id.clone()); + cx.notify(); + } + })), + ); + } + entry + })) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .items_center() + .gap(space::S1) + .children(winner.map(|winner| { + mono(winner.label(), ui) + .font_weight(gpui_kit::FontWeight::SEMIBOLD) + .truncate() + })) + .children( + winner.map(|winner| chip(layer_chip(report, &winner.layer), true, ui)), + ), + ) + } + + pub(super) fn config_source( + &mut self, + report: &ConfigReport, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + let list = div() + .w(relative(0.24)) + .min_w(px(130.)) + .flex() + .flex_col() + .gap(space::S1) + .child(caption("Files", ui).pb(space::S2)) + .children(report.layers.iter().map(|layer| { + let id = layer.id.clone(); + let selected = id == self.config.file; + let problem = self + .config + .issues() + .iter() + .any(|issue| issue.layer.as_ref() == Some(&id)); + div() + .id(SharedString::from(format!("config-source-file-{}", id))) + .p(space::S2) + .rounded(px(5.)) + .cursor_pointer() + .flex() + .items_center() + .gap(space::S2) + .when(selected, |d| d.bg(ui.p.surface_2)) + .child(chip(layer.chip().to_owned(), selected, ui)) + .child( + div() + .min_w_0() + .flex_1() + .child(mono(layer_title(layer), ui).truncate()) + .child(muted(layer_description(layer), ui).truncate()), + ) + .children( + problem.then(|| icon(Glyph::CircleAlert, px(13.), ui.p.states.failed.fg)), + ) + .on_click(cx.listener(move |app, _, _, cx| { + app.config.file.clone_from(&id); + app.config.editor = None; + cx.notify(); + })) + })); + let file = report + .layer(&self.config.file) + .or_else(|| report.layers.first()); + let pane = file.map_or_else( + || card(ui).child(muted("No files to show.", ui)), + |layer| self.source_file(layer, ui, window, cx), + ); + div() + .flex() + .flex_1() + .min_h_0() + .gap(space::S4) + .child( + div() + .id("config-source-nav") + .overflow_y_scroll() + .child(list.w_full()) + .w(relative(0.24)) + .min_w(px(130.)), + ) + .child(pane.flex_1().min_w_0()) + .into_any_element() + } + + fn source_file( + &mut self, + layer: &ConfigLayer, + ui: &Ui, + window: &mut Window, + cx: &mut Context, + ) -> Div { + let changed_in_form = + self.config.draft.changes.values().any(|edit| { + edit.layer() == layer.id && !matches!(edit, ConfigChange::Source { .. }) + }); + let allow_edit = layer.source_writable + && !changed_in_form + && !self.config.conflict + && !self.config.saving() + && !self.config.loading; + let original = layer.source.as_deref().unwrap_or_default(); + let edit_id = format!("source/{}", layer.id); + let issue = self + .config + .issues() + .iter() + .find(|issue| issue.layer.as_deref() == Some(layer.id.as_str())) + .cloned(); + let draft = self + .config + .draft + .changes + .get(&edit_id) + .and_then(|edit| match edit { + ConfigChange::Source { text, .. } => Some(text.as_str()), + _ => None, + }); + let preview = self + .config + .validation + .as_ref() + .and_then(|check| check.previews.get(&layer.id)) + .and_then(|preview| preview.as_deref()); + let buffer = draft.or(preview).unwrap_or(original).to_owned(); + let path = layer.file.clone(); + let editor = if layer.source.is_some() { + Some(self.config_source_editor( + layer, + &edit_id, + original, + buffer, + issue.as_ref(), + window, + cx, + )) + } else { + None + }; + card(ui) + .flex() + .flex_col() + .min_h_0() + .overflow_hidden() + .child( + div() + .flex() + .items_center() + .gap(space::S2) + .p(space::S2) + .hairline_b(ui.p.border) + .child( + mono(layer.name().to_owned(), ui) + .flex_1() + .min_w_0() + .truncate(), + ) + .when(!allow_edit, |row| row.child(muted("read-only", ui))) + .child( + action_button("config-copy-path", Glyph::Copy, "Copy path", true, ui) + .on_click(move |_, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(path.clone())) + }), + ) + .children( + layer + .exists + .then(|| self.editor_button(layer.file.clone(), ui, cx)), + ), + ) + .children(issue.as_ref().map(|issue| { + let message = issue.line.map_or_else( + || issue.message.clone(), + |line| format!("Line {line} · {}", issue.message), + ); + warning(message, ui) + .px(space::S3) + .py(space::S2) + .bg(ui.p.surface_1) + })) + .child(if let Some(editor) = editor { + div().bg(ui.p.surface_1).flex_1().min_h_0().child( + Editor::new(&editor) + .readonly(!allow_edit) + .appearance(false) + .bordered(false) + .h(relative(1.)) + .aria_label(layer.name().to_owned()), + ) + } else { + div().p(space::S3).child(muted( + if layer.hidden { + "Source preview unavailable. Open the file in your editor." + } else { + "This file is not on disk yet." + }, + ui, + )) + }) + } + + #[expect( + clippy::too_many_arguments, + reason = "native input rendering needs the window and app context" + )] + fn config_source_editor( + &mut self, + layer: &ConfigLayer, + edit_id: &str, + original: &str, + buffer: String, + issue: Option<&ConfigIssue>, + window: &mut Window, + cx: &mut Context, + ) -> Entity { + // Recreate a read-only preview when a structured change updates it. + let preview_key = if self.config.draft.changes.contains_key(edit_id) + || self.config.validation.is_none() + { + layer.id.clone() + } else { + format!("{}-{}", layer.id, self.config.revision) + }; + let editor = if let Some((identity, editor, _)) = &self.config.editor + && *identity == preview_key + { + editor.clone() + } else { + let editor = cx.new(|cx| { + let mut editor = + EditorState::new(window, cx).language(if layer.file.ends_with(".json") { + "json" + } else { + "yaml" + }); + editor.set_value(buffer, window, cx); + editor + }); + let layer_id = layer.id.clone(); + let edit_id = edit_id.to_owned(); + let original = original.to_owned(); + let subscription = cx.subscribe(&editor, move |app, editor, event, cx| { + if matches!(event, InputEvent::Change) { + let text = editor.read(cx).value().to_string(); + let edit = (text != original).then(|| ConfigChange::Source { + layer: layer_id.clone(), + text, + }); + app.stage_config(edit_id.clone(), edit, cx); + } + }); + self.config.editor = Some((preview_key, editor.clone(), subscription)); + editor + }; + let line_issue = issue.and_then(|issue| { + let line = u32::try_from(issue.line?.saturating_sub(1)).ok()?; + let diag = gpui_kit::base::input::Diagnostic::new( + Position::new(line, 0)..Position::new(line.saturating_add(1), 0), + issue.message.clone(), + ) + .with_severity(gpui_kit::base::input::DiagnosticSeverity::Error); + Some(diag) + }); + editor.update(cx, |editor, _| { + if let Some(diagnostics) = editor.diagnostics_mut() { + diagnostics.clear(); + diagnostics.extend(line_issue); + } + }); + if self.config.pending_focus.as_deref() == Some(edit_id) { + self.config.pending_focus = None; + let line = issue + .and_then(|issue| issue.line) + .unwrap_or(1) + .saturating_sub(1); + editor.update(cx, |state, cx| { + state.set_cursor_position( + Position::new(u32::try_from(line).unwrap_or(u32::MAX), 0), + window, + cx, + ) + }); + } + editor + } + + pub(super) fn editor_button( + &self, + file: String, + ui: &Ui, + cx: &mut Context, + ) -> gpui_kit::Stateful
{ + action_button( + "config-open-editor", + Glyph::Pencil, + "Open in editor", + true, + ui, + ) + .on_click(cx.listener(move |app, _, _, cx| { + if !app.live { + return; + } + let path = PathBuf::from(&file); + cx.background_executor() + .spawn(async move { + if !path.is_absolute() { + return; + } + #[cfg(target_os = "macos")] + let _ = std::process::Command::new("/usr/bin/open") + .arg("-t") + .arg(path) + .status(); + #[cfg(not(target_os = "macos"))] + let _ = std::process::Command::new("xdg-open").arg(path).status(); + }) + .detach(); + })) + } + + pub(super) fn jump_config_issue(&mut self, issue: &ConfigIssue, cx: &mut Context) { + if let Some(field) = issue_field(issue) + .filter(|_| self.config.view != View::Source && !issue.path.is_empty()) + { + let section = issue_section(issue); + if section == EditSection::Env { + self.config.view = View::Env; + self.config.scope = issue + .path + .get(1) + .cloned() + .unwrap_or_else(|| "global".into()); + self.config.active_cell = Some(field.clone()); + } else { + self.config.view = View::Edit; + self.config.edit_section = section; + } + self.config.pending_focus = Some(field); + } else if let Some(layer) = &issue.layer { + self.config.view = View::Source; + self.config.file.clone_from(layer); + self.config.pending_focus = Some(format!("source/{layer}")); + } + cx.notify(); + } +} + +fn issue_field(issue: &ConfigIssue) -> Option { + let layer = issue.layer.as_deref()?; + match (layer, issue.path.as_slice()) { + ("1", path) if !path.is_empty() => Some(format!("project/{}", path.join("."))), + ("2", [_, service, field, rest @ ..]) if field == "route" => Some(format!( + "route/{service}/{}", + if rest.first().is_some_and(|part| part == "port") { + "port" + } else { + "sites" + } + )), + ("2", [_, service, field]) => Some(format!("service/{service}/{field}")), + (_, [prefix, scope, key]) if prefix == "values" => { + Some(format!("env/{layer}/{scope}/{key}")) + } + _ => None, + } +} + +fn issue_section(issue: &ConfigIssue) -> EditSection { + match issue.path.first().map(String::as_str) { + Some("services") if issue.path.get(2).is_some_and(|part| part == "route") => { + EditSection::Routes + } + Some("services") => EditSection::Services, + Some("dev_host" | "internal" | "oauth") => EditSection::Routes, + Some("env" | "values") => EditSection::Env, + Some("worktree") => EditSection::Worktrees, + _ => EditSection::Project, + } +} + +fn group_title(title: &str, report: &ConfigReport, id: &str, ui: &Ui) -> Div { + div() + .flex() + .items_center() + .gap(space::S2) + .py(space::S2) + .child(caption(title.to_owned(), ui)) + .child(div().flex_1()) + .children( + report + .layer(id) + .map(|layer| chip(layer.chip().to_owned(), false, ui)), + ) + .children( + report + .layer(id) + .map(|layer| mono(layer.name().to_owned(), ui).text_color(ui.p.text_muted)), + ) +} + +fn project_toggle_value(project: &Value, path: &str, fallback: bool) -> bool { + let authored = setting(project, path); + // The CLI uses nullish precedence before checking the selected value's type. + let effective = match (path, authored.is_null()) { + ("worktree.auto_branch", true) => setting(project, "worktree.autoBranch"), + ("worktree.inherit_local", true) => setting(project, "worktree.inheritLocal"), + _ => authored, + }; + effective.as_bool().unwrap_or(fallback) +} + +#[cfg(test)] +#[test] +fn worktree_toggles_follow_runtime_alias_precedence() { + for (path, snake_case, camel_case) in [ + ("worktree.auto_branch", "auto_branch", "autoBranch"), + ("worktree.inherit_local", "inherit_local", "inheritLocal"), + ] { + let mut project = serde_json::json!({ "worktree": { (camel_case): false } }); + assert!(!project_toggle_value(&project, path, true)); + + project["worktree"][snake_case] = Value::Null; + assert!(!project_toggle_value(&project, path, true)); + + project["worktree"][snake_case] = Value::Bool(true); + assert!(project_toggle_value(&project, path, true)); + + project["worktree"][snake_case] = Value::String("invalid".into()); + assert!(project_toggle_value(&project, path, true)); + } +} + +// Older v1 producers expose only authored fields. Follow the CLI's legacy +// name normalization and precedence without using the active preview overlay. +fn legacy_default_overlay(project: &Value) -> String { + let name = |paths: [&str; 2]| { + let raw = paths + .into_iter() + .find_map(|path| setting(project, path).as_str())? + .trim(); + if raw.starts_with("[redacted") { + return None; + } + let name: String = raw + .to_lowercase() + .replace(['_', ' ', '/'], "-") + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-') + .collect(); + let name = name + .split('-') + .filter(|part| !part.is_empty()) + .collect::>() + .join("-"); + (!name.is_empty()).then_some(name) + }; + name(["env.defaultOverlay", "env.default_overlay"]) + .or_else(|| name(["defaultEnvConfig", "default_env_config"])) + .filter(|name| name.len() <= 128 && !matches!(name.as_str(), "base" | "default" | "none")) + .unwrap_or_else(|| "default".into()) +} + +fn field_row(label: &str, detail: &str, element: impl IntoElement, ui: &Ui) -> Div { + div() + .flex() + .items_start() + .gap(space::S3) + .py(space::S2) + .hairline_b(ui.p.border) + .child( + div() + .w(relative(0.25)) + .min_w(px(110.)) + .flex_shrink_0() + .pt(space::S1) + .child(strong(label.to_owned(), ui)) + .children((!detail.is_empty()).then(|| muted(detail.to_owned(), ui))), + ) + .child(div().flex_1().min_w_0().child(element)) +} + +#[cfg(all(test, feature = "screenshots"))] +mod tests { + use std::sync::Arc; + + use gpui_kit::{AnyWindowHandle, HeadlessAppContext, NoopTextSystem, WindowOptions}; + use hack_desktop_core::{config::ConfigState, fixtures::Fixture}; + + use super::*; + + #[test] + fn the_snapshot_backend_defaults_to_loki_and_can_be_changed_to_compose() { + assert_project_field_can_stage( + ConfigReport::default(), + EditSection::Project, + "logs.snapshot_backend", + "loki", + "compose", + ); + } + + #[test] + fn the_default_overlay_field_uses_the_resolved_project_default() { + assert_project_field_can_stage( + ConfigReport { + project: serde_json::json!({ "defaultEnvConfig": "qa" }), + default_overlay: Some("qa".into()), + overlay: Some("staging".into()), + ..Default::default() + }, + EditSection::Env, + "env.defaultOverlay", + "qa", + "default", + ); + } + + #[test] + fn the_default_overlay_field_resolves_aliases_in_older_reports() { + assert_project_field_can_stage( + ConfigReport { + project: serde_json::json!({ + "env": { "default_overlay": " QA " }, + "defaultEnvConfig": "development", + }), + overlay: Some("staging".into()), + ..Default::default() + }, + EditSection::Env, + "env.defaultOverlay", + "qa", + "default", + ); + assert_eq!( + legacy_default_overlay(&serde_json::json!({"defaultEnvConfig": "qa"})), + "qa" + ); + assert_eq!( + legacy_default_overlay(&serde_json::json!({"default_env_config": " qa_team "})), + "qa-team" + ); + assert_eq!( + legacy_default_overlay(&serde_json::json!({ + "env": { "defaultOverlay": "none", "default_overlay": "qa" }, + "defaultEnvConfig": "qa", + })), + "default" + ); + } + + #[test] + fn env_cells_keep_an_explicit_empty_override() { + let (mut cx, window, app) = headless_config_app(); + let report = ConfigReport { + state: ConfigState::Ready, + writable: true, + layers: vec![ConfigLayer { + id: "5".into(), + file: ".hack/hack.env.local.yaml".into(), + kind: "env".into(), + ownership: "local".into(), + active: true, + writable: true, + revision: "fixture".into(), + exists: true, + source: None, + hidden: false, + source_writable: false, + inherited: None, + overlay: None, + }], + ..Default::default() + }; + for (key, cell) in [ + ("ABSENT", None), + ("UNSET", Some((true, None))), + ("EMPTY", Some((false, Some(Value::String(String::new()))))), + ] { + let id = format!("env/5/global/{key}"); + let mut values = vec![EnvCell { + layer: "3".into(), + scope: "global".into(), + unset: false, + secret: false, + value: Some(Value::String("inherited".into())), + }]; + if let Some((unset, value)) = cell { + values.push(EnvCell { + layer: "5".into(), + scope: "global".into(), + unset, + secret: false, + value, + }); + } + let row = EnvRow { + key: key.into(), + scope: "global".into(), + values, + winning: None, + }; + cx.update_window(window, |_, window, cx| { + app.update(cx, |app, cx| { + app.config.scope = "global".into(); + app.config.active_cell = Some(id.clone()); + app.env_grid_row(&row, &[&report.layers[0]], &report, &app.ui(cx), window, cx); + assert!(app.config.inputs[&id].0.read(cx).value().is_empty()); + assert!(!app.config.draft.changes.contains_key(&id)); + }); + }) + .expect("render the Env cell"); + for value in ["temporary", ""] { + cx.update_window(window, |_, window, cx| { + let input = app.read(cx).config.inputs[&id].0.clone(); + input.update(cx, |input, cx| input.replace_all(value, window, cx)); + }) + .expect("edit the Env cell"); + cx.update(|cx| { + let changes = &app.read(cx).config.draft.changes; + if key == "EMPTY" && value.is_empty() { + assert!(!changes.contains_key(&id)); + } else { + assert!(matches!( + changes.get(&id), + Some(ConfigChange::Env { layer, scope, value: Some(staged), .. }) + if layer == "5" && scope == "global" && staged == value + )); + } + }); + } + if key == "ABSENT" { + cx.update(|cx| { + let input = app.read(cx).config.inputs[&id].0.clone(); + app.update(cx, |app, cx| app.stage_config(id.clone(), None, cx)); + input.update(cx, |_, cx| { + cx.emit(InputEvent::PressEnter { + secondary: false, + shift: false, + }); + }); + }); + cx.update(|cx| { + assert!(matches!( + app.read(cx).config.draft.changes.get(&id), + Some(ConfigChange::Env { value: Some(value), .. }) if value.is_empty() + )); + }); + } + } + } + + fn headless_config_app() -> (HeadlessAppContext, AnyWindowHandle, Entity) { + let mut cx = HeadlessAppContext::with_platform( + Arc::new(NoopTextSystem::new()), + Arc::new(hack_desktop_ui::icons::Assets), + || Ok(None), + ); + cx.update(hack_desktop_ui::tokens::init); + let (window, app) = cx + .update(|cx| { + gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { + cx.new(|cx| { + HackApp::new(crate::source_for(Some(Fixture::Running)), false, window, cx) + }) + }) + }) + .expect("open a headless window"); + (cx, window, app) + } + + fn assert_project_field_can_stage( + mut report: ConfigReport, + section: EditSection, + path: &str, + initial: &str, + edited: &str, + ) { + let (mut cx, window, app) = headless_config_app(); + report.state = ConfigState::Ready; + report.writable = true; + report.layers.push(ConfigLayer { + id: "1".into(), + file: ".hack/hack.config.json".into(), + kind: "project".into(), + ownership: "shared".into(), + active: true, + writable: true, + revision: "fixture".into(), + exists: true, + source: None, + hidden: false, + source_writable: true, + inherited: None, + overlay: None, + }); + let field_id = format!("project/{path}"); + cx.update_window(window, |_, window, cx| { + app.update(cx, |app, cx| { + app.config.edit_section = section; + app.config_form(&report, &app.ui(cx), window, cx); + let original = app.config.inputs[&field_id].0.read(cx).value(); + assert_eq!(original.as_ref(), initial); + Field::Project(path.into()).stage(app, edited.into(), Some(&original), cx); + }); + }) + .expect("edit the project field"); + cx.update(|cx| { + assert!(matches!( + app.read(cx).config.draft.changes.get(&field_id), + Some(ConfigChange::Project { layer, path: staged_path, value }) + if layer == "1" && staged_path == path && value == edited + )); + }); + } +} diff --git a/apps/desktop/app/src/config_view/map.rs b/apps/desktop/app/src/config_view/map.rs new file mode 100644 index 0000000000..5a598f9d27 --- /dev/null +++ b/apps/desktop/app/src/config_view/map.rs @@ -0,0 +1,447 @@ +use gpui_kit::prelude::*; +use gpui_kit::{Context, IntoElement, div, px, relative}; +use hack_desktop_core::config::{ConfigLayer, ConfigReport, ConfigService}; +use hack_desktop_ui::{ + components::{StyledExt as _, Ui, dot}, + status::Status, + tokens::{space, text}, +}; + +use super::{View, card, chip, mono, muted, strong}; +use crate::view::HackApp; + +impl HackApp { + pub(super) fn config_map( + &self, + report: &ConfigReport, + ui: &Ui, + cx: &mut Context, + ) -> gpui_kit::AnyElement { + let selected = report + .services + .iter() + .find(|service| service.name == self.config.service); + let p = ui.p; + let layers = div() + .w(relative(0.22)) + .min_w(px(145.)) + .flex() + .flex_col() + .gap(space::S2) + .child( + div() + .flex() + .justify_between() + .child(caption("Layers", ui)) + .child(muted("later wins", ui)), + ) + .children( + report + .layers + .iter() + .filter(|layer| layer.kind != "internal") + .map(|layer| { + let id = layer.id.clone(); + let selected = self.config.layer.as_ref() == Some(&id); + card(ui) + .id(gpui_kit::SharedString::from(format!("config-layer-{}", id))) + .p(space::S3) + .when(!layer.active || layer.ownership == "generated", |d| { + d.border_dashed() + }) + .flex() + .items_start() + .gap(space::S3) + .cursor_pointer() + .when(selected, |d| d.bg(p.surface_2)) + .child(chip(layer.chip().to_owned(), selected, ui)) + .child( + div() + .min_w_0() + .flex_1() + .child(mono(layer_title(layer), ui).truncate()) + .child(muted(layer_description(layer), ui)), + ) + .on_click(cx.listener(move |app, _, _, cx| { + app.config.layer = if app.config.layer.as_ref() == Some(&id) { + None + } else { + Some(id.clone()) + }; + cx.notify(); + })) + }), + ); + let graph = div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(space::S3) + .child( + div() + .flex() + .justify_between() + .gap(space::S2) + .child(caption("Routes → Services → Depends on", ui)) + .child( + muted(report.branch.as_deref().unwrap_or("main").to_owned(), ui).truncate(), + ), + ) + .children( + report + .services + .iter() + .map(|service| self.config_graph_row(report, service, ui, cx)), + ) + .when(report.services.is_empty(), |d| { + d.child(muted("No services in this Compose file.", ui)) + }) + .child(div().flex_1()) + .child(muted("┄ route · □ service · [2] from layer 2", ui)) + .child(muted("Click a layer to see what it sets", ui)); + let resolved = selected.map_or_else( + || card(ui).p(space::S4).child(muted("Choose a service", ui)), + |service| self.config_resolved(report, service, ui), + ); + div() + .id("config-map-scroll") + .min_h_0() + .flex_1() + .overflow_y_scroll() + .child( + div() + .min_h_full() + .flex() + .items_start() + .gap(space::S4) + .child(layers) + .child(graph) + .child(resolved.w(relative(0.28)).min_w(px(170.))), + ) + .into_any_element() + } + + fn config_service_status(&self, report: &ConfigReport, name: &str) -> Status { + if let Some(detail) = self.model.detail() + && detail.branch == report.branch + && let Some(service) = detail.services.iter().find(|service| service.name == name) + { + return Status::of_service(service); + } + Status::Unknown + } + + fn config_graph_row( + &self, + report: &ConfigReport, + service: &ConfigService, + ui: &Ui, + cx: &mut Context, + ) -> gpui_kit::Div { + let layer = self.config.layer.as_deref(); + let p = ui.p; + let scope = report.env_for(&service.name); + let route_layers = service + .routes + .iter() + .flat_map(|route| route.from.iter().map(String::as_str)) + .collect::>(); + let route_matches = layer.is_some_and(|id| route_layers.contains(&id)); + let service_matches = layer.is_some_and(|id| { + id == "2" + || scope + .iter() + .any(|row| row.values.iter().any(|cell| cell.layer == id)) + }); + let name = service.name.clone(); + let selected = service.name == self.config.service; + let active = card(ui) + .id(gpui_kit::SharedString::from(format!( + "config-service-{}", + name + ))) + .w(px(108.)) + .flex_shrink_0() + .px(space::S2) + .py(space::S2) + .cursor_pointer() + .when(selected, |d| d.border_2().border_color(p.text_primary)) + .when(service_matches, |d| d.bg(p.surface_2)) + .child( + div() + .flex() + .items_center() + .gap(space::S2) + .child(dot(self.config_service_status(report, &name), ui)) + .child(strong(name.clone(), ui).truncate()), + ) + .child( + div() + .flex() + .gap(space::S2) + .child(chip("2", layer == Some("2"), ui)) + .child(muted( + format!( + "{} env", + scope.iter().filter(|row| row.winning.is_some()).count() + ), + ui, + )), + ) + .on_click(cx.listener(move |app, _, _, cx| { + app.config.service.clone_from(&name); + cx.notify(); + })); + let routes = card(ui) + .border_dashed() + .flex_1() + .min_w_0() + .px(space::S2) + .py(space::S2) + .when(route_matches, |d| d.bg(p.surface_2)) + .when(service.routes.is_empty(), |d| { + d.child(muted("Internal only", ui)) + .child(div().flex().child(chip("2", layer == Some("2"), ui))) + }) + .children(service.routes.iter().map(|route| { + div() + .min_w_0() + .child(mono(route.host.clone(), ui).truncate()) + .child( + div() + .flex() + .items_center() + .gap(space::S1) + .children(route.from.iter().map(|id| { + chip(layer_chip(report, id), layer == Some(id.as_str()), ui) + })) + .child(muted(if route.tls { "https" } else { "http" }, ui)), + ) + })); + let dependencies = div() + .w(px(78.)) + .flex_shrink_0() + .flex() + .flex_col() + .gap(space::S1) + .children(service.depends_on.iter().map(|name| { + let key = name.clone(); + card(ui) + .id(gpui_kit::SharedString::from(format!( + "config-dependency-{}/{}", + service.name, name + ))) + .px(space::S2) + .py(space::S1) + .cursor_pointer() + .when(layer == Some("2"), |d| d.bg(p.surface_2)) + .child(strong(name.clone(), ui).truncate()) + .child(chip("2", layer == Some("2"), ui)) + .on_click(cx.listener(move |app, _, _, cx| { + app.config.service.clone_from(&key); + cx.notify(); + })) + })); + div() + .flex() + .items_center() + .child(routes) + .child(arrow(ui)) + .child(active) + .child(if service.depends_on.is_empty() { + div().w(px(16.)) + } else { + arrow(ui) + }) + .child(dependencies) + } + + fn config_resolved( + &self, + report: &ConfigReport, + service: &ConfigService, + ui: &Ui, + ) -> gpui_kit::Div { + let accent = self.config.layer.as_deref(); + let scope = report.env_for(&service.name); + let env_count = scope.iter().filter(|row| row.winning.is_some()).count(); + let ports = service + .ports + .iter() + .map(hack_desktop_core::config::scalar_label) + .collect::>() + .join(", "); + let port = service + .routes + .first() + .and_then(|route| route.port) + .map_or(ports, |port| port.to_string()); + card(ui) + .min_h(px(250.)) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .p(space::S3) + .flex() + .flex_wrap() + .items_center() + .gap(space::S2) + .child(dot(self.config_service_status(report, &service.name), ui)) + .child(strong(service.name.clone(), ui)) + .child(muted( + format!( + "resolved for {}", + report.branch.as_deref().unwrap_or("main") + ), + ui, + )), + ) + .children(service.routes.iter().map(|route| { + self.resolved_row("route", &route.host, &route.from, None, report, ui) + })) + .child(self.resolved_row( + "port", + if port.is_empty() { "—" } else { &port }, + &["2".into()], + None, + report, + ui, + )) + .child(self.resolved_row( + "image", + service.image.as_deref().unwrap_or("—"), + &["2".into()], + None, + report, + ui, + )) + .child(caption(format!("Env · {env_count} keys"), ui).p(space::S3)) + .children(scope.iter().filter_map(|row| { + let winner = row.values.last().filter(|cell| !cell.unset)?; + let prior = row + .values + .iter() + .rev() + .skip(1) + .take_while(|cell| !cell.unset) + .find(|cell| cell.layer != winner.layer); + Some(self.resolved_row( + &row.key, + &winner.label(), + std::slice::from_ref(&winner.layer), + prior.map(|cell| cell.layer.as_str()), + report, + ui, + )) + })) + .when(accent == Some("1"), |d| { + d.child( + div() + .p(space::S3) + .bg(ui.p.surface_2) + .child(caption("Project settings · 1", ui)) + .children(report.project.as_object().into_iter().flatten().map( + |(key, value)| { + let value = value.as_object().map_or_else( + || hack_desktop_core::config::scalar_label(value), + |_| "·".into(), + ); + mono(format!("{key} {value}"), ui).truncate() + }, + )), + ) + }) + } + + fn resolved_row( + &self, + label: &str, + value: &str, + layers: &[String], + over: Option<&str>, + report: &ConfigReport, + ui: &Ui, + ) -> gpui_kit::Div { + let selected = self.config.layer.as_deref(); + div() + .px(space::S3) + .py(space::S2) + .hairline_b(ui.p.border) + .when( + selected + .is_some_and(|id| layers.iter().any(|layer| layer == id) || over == Some(id)), + |d| d.bg(ui.p.surface_2), + ) + .child( + div() + .flex() + .items_center() + .gap(space::S1) + .child(muted(label.to_owned(), ui).flex_1().truncate()) + .children(layers.iter().map(|id| { + chip( + layer_chip(report, id), + selected.is_none_or(|selected| selected == id), + ui, + ) + })) + .children(over.map(|id| muted(format!("over {}", layer_chip(report, id)), ui))), + ) + .child(mono(value.to_owned(), ui).truncate()) + } + + pub(super) fn go_to_source(&mut self, id: &str, cx: &mut Context) { + self.config.view = View::Source; + self.config.file = id.into(); + cx.notify(); + } +} + +fn arrow(ui: &Ui) -> gpui_kit::Div { + div() + .w(px(16.)) + .flex_shrink_0() + .flex() + .justify_center() + .text_color(ui.p.text_muted) + .child("→") +} + +pub(super) fn layer_title(layer: &ConfigLayer) -> String { + if layer.kind == "branch" { + "branch override".into() + } else { + layer.name().into() + } +} + +pub(super) fn layer_description(layer: &ConfigLayer) -> String { + if !layer.active { + return "overlay · not in use".into(); + } + match layer.kind.as_str() { + "project" => "project settings · shared".into(), + "compose" => "services and routes · shared".into(), + "branch" => "generated · branch prefix".into(), + "internal" => "Hack-managed · read-only".into(), + _ if layer.inherited == Some(true) => "env · from the main checkout".into(), + _ if layer.ownership == "local" => "env · this checkout".into(), + _ => "env · shared".into(), + } +} + +pub(super) fn layer_chip(report: &ConfigReport, id: &str) -> String { + report.layer(id).map_or(id, ConfigLayer::chip).to_owned() +} + +pub(super) fn caption(label: impl Into, ui: &Ui) -> gpui_kit::Div { + let label: gpui_kit::SharedString = label.into(); + div() + .type_step(text::SMALL) + .font_weight(gpui_kit::FontWeight::SEMIBOLD) + .text_color(ui.p.text_muted) + .child(label.to_uppercase()) +} diff --git a/apps/desktop/app/src/config_view/screenshots.rs b/apps/desktop/app/src/config_view/screenshots.rs new file mode 100644 index 0000000000..4c8a08256a --- /dev/null +++ b/apps/desktop/app/src/config_view/screenshots.rs @@ -0,0 +1,298 @@ +//! Render each Config frame using the app's actual component and synthetic +//! config. No user's checkout, env or runtime is read for these screenshots. + +use std::{path::Path, sync::Arc}; + +use gpui_kit::{ + AppContext as _, Bounds, HeadlessAppContext, WindowBounds, WindowOptions, + component::{Theme, ThemeMode}, + px, size, + test::TestWindowExt as _, +}; +use hack_desktop_core::{ + config::{ConfigReport, ConfigSaved, ConfigState, ConfigValidation}, + fixtures::{self, Fixture}, +}; +use serde_json::{Value, json}; + +use super::{ConfigChange, Selection, TAB, View}; +use crate::view::HackApp; + +const FILES: [(&str, &str, &str, &str, bool); 7] = [ + ( + "1", + "/work/storefront-search/.hack/hack.config.json", + "project", + "shared", + true, + ), + ( + "2", + "/work/storefront-search/.hack/docker-compose.yml", + "compose", + "shared", + true, + ), + ( + "3", + "/work/storefront-search/.hack/hack.env.default.yaml", + "env", + "shared", + true, + ), + ( + "3:qa", + "/work/storefront-search/.hack/hack.env.qa.yaml", + "env", + "shared", + false, + ), + ( + "4", + "/work/storefront/.hack/hack.env.local.yaml", + "env", + "local", + false, + ), + ( + "5", + "/work/storefront-search/.hack/hack.env.local.yaml", + "env", + "local", + true, + ), + ( + "6", + "/work/storefront-search/.hack/.branch/compose.feature-search.override.yml", + "branch", + "generated", + false, + ), +]; + +const COMPOSE: &str = r#"name: storefront +services: + api: + image: storefront-api:dev + labels: + caddy: "api.storefront.hack, api.shop.hack" + caddy.reverse_proxy: "{{upstreams 3000}}" + depends_on: [db] + db: + image: postgres:17 + environment: + POSTGRES_DB: shop + web: + image: storefront-web:dev +"#; + +fn env(key: &str, scope: &str, values: &[(&str, &str)]) -> Value { + json!({ + "key": key, "scope": scope, "winning": values.last().map(|pair| pair.0), + "values": values.iter().map(|(layer, value)| json!({"layer":layer,"secret":false,"value":value})).collect::>(), + }) +} + +fn service( + name: &str, + image: &str, + port: u16, + dependencies: &[&str], + base_host: &str, + host: &str, +) -> Value { + let routes = if host.is_empty() { + json!([]) + } else { + json!([{"host":host,"port":port,"tls":true,"from":["2","6"]}]) + }; + json!({ + "name": name, "image": image, "ports": [port], "depends_on": dependencies, "routes": routes, + "route_edit": {"sites":base_host,"port":port}, + }) +} + +fn report() -> ConfigReport { + let layers: Vec<_> = FILES + .iter() + .map(|(id, file, kind, ownership, writable)| { + json!({ + "id": id, "file": file, "kind": kind, "ownership": ownership, "writable": writable, + "active": *id != "3:qa", "revision": "fixture", "exists": true, + "source": (*id == "2").then_some(COMPOSE), "hidden": false, + "source_writable": *id == "2", "inherited": *id == "4", + "overlay": (*id == "3:qa").then_some("qa"), + }) + }) + .collect(); + serde_json::from_value(json!({ + "state":"ready", "checkout":"/work/storefront-search", "branch":"feature-search", + "overlay":null, "overlays":["qa"], "writable":true, "issues":[], "layers":layers, + "project":{"name":"storefront","dev_host":"storefront.hack","internal":{"dns":true,"tls":true}}, + "services":[ + service("web","storefront-web:dev",3000,&["api"],"storefront.hack","feature-search.storefront.hack"), + service("api","storefront-api:dev",3000,&["db"],"api.storefront.hack","api.feature-search.storefront.hack"), + service("db","postgres:17",5432,&[],"",""), + service("worker","storefront-worker:dev",9000,&["db"],"",""), + ], + "env":[ + env("API_BASE_URL","global",&[("3","https://storefront.hack"),("5","https://feature-search.storefront.hack")]), + env("SEARCH_INDEX","api",&[("3","products"),("4","products_main"),("5","products_fs")]), + env("LOG_LEVEL","global",&[("3","info"),("4","debug")]), + env("PORT","api",&[("3","3000")]), + env("DATABASE_URL","api",&[("3","postgres://db:5432/shop")]), + {"key":"SERVICE_TOKEN","scope":"api","winning":"3","values":[{"layer":"3","secret":true}]}, + env("FEATURE_FLAGS","global",&[("5","search_v2")]), + ], + })).expect("config screenshot fixture") +} + +fn setup(app: &mut HackApp, frame: &str) { + let mut report = report(); + app.tab = TAB; + app.config.draft.base = report.revisions(); + app.config.selection = Selection { + root: "/work/storefront-search".into(), + ..Default::default() + }; + app.config.service = "api".into(); + app.config.scope = "api".into(); + match frame { + "m08-map" => app.config.layer = Some("5".into()), + "m09-edit" => { + app.config.view = View::Edit; + app.config.stage( + "project/dev_host".into(), + Some(ConfigChange::Project { + layer: "1".into(), + path: "dev_host".into(), + value: json!("storefront hack"), + }), + ); + app.config.stage( + "project/oauth.enabled".into(), + Some(ConfigChange::Project { + layer: "1".into(), + path: "oauth.enabled".into(), + value: json!(true), + }), + ); + app.config.stage( + "route/api".into(), + Some(ConfigChange::Route { + layer: "2".into(), + service: "api".into(), + sites: "api.storefront.hack, api.shop.hack".into(), + port: "3000".into(), + }), + ); + app.config.validation = Some(serde_json::from_value(json!({ + "valid":false, "previews":{}, "issues":[{"layer":"1","path":["dev_host"],"line":2,"code":"E_CONFIG_INVALID","message":"Use letters, digits, dots and dashes, such as storefront.hack."}] + })).expect("edit fixture validation")); + } + "m10-env-layers" => { + app.config.view = View::Env; + app.config.active_cell = Some("env/5/api/SEARCH_INDEX".into()); + app.config.stage( + "env/5/api/SEARCH_INDEX".into(), + Some(ConfigChange::Env { + layer: "5".into(), + scope: "api".into(), + key: "SEARCH_INDEX".into(), + value: Some("products_fs".into()), + }), + ); + app.config.validation = Some(ConfigValidation { + valid: true, + ..Default::default() + }); + } + "m11-source" => { + let draft = COMPOSE.replace("depends_on: [db]", "depends_on: [db, cache]"); + app.config.view = View::Source; + app.config.file = "2".into(); + app.config.stage( + "source/2".into(), + Some(ConfigChange::Source { + layer: "2".into(), + text: draft, + }), + ); + app.config.validation = Some(serde_json::from_value(json!({ + "valid":false, "previews":{}, "issues":[{"layer":"2","path":["services","api","depends_on"],"line":8,"code":"E_CONFIG_INVALID","message":"depends_on names a service that is not defined: cache"}] + })).expect("source fixture validation")); + } + "m12-saved" => { + app.config.saved = Some(ConfigSaved { + changed: vec!["2".into()], + restart_offered: true, + }) + } + "m12-unreadable" => { + report.state = ConfigState::Invalid; + report.issues = serde_json::from_value(json!([ + {"layer":"1","path":[],"line":7,"code":"E_CONFIG_PARSE","message":"Expected a valid JSON object."}, + ])).expect("invalid fixture issues"); + } + "m12-missing" => report = ConfigReport::default(), + _ => unreachable!(), + } + app.config.settle_report(Ok(report)); +} + +/// Uses the same headless native renderer as the existing desktop fixtures. +pub(crate) fn run(dir: &Path) { + std::fs::create_dir_all(dir).expect("config screenshot directory"); + let mut cx = HeadlessAppContext::with_platform( + gpui_kit::platform::current_platform(true).text_system(), + Arc::new(hack_desktop_ui::icons::Assets), + gpui_kit::platform::current_headless_renderer, + ); + cx.update(hack_desktop_ui::tokens::init); + for (mode, suffix) in [(ThemeMode::Light, "light"), (ThemeMode::Dark, "dark")] { + cx.update(|cx| Theme::change(mode, None, cx)); + for frame in [ + "m08-map", + "m09-edit", + "m10-env-layers", + "m11-source", + "m12-saved", + "m12-unreadable", + "m12-missing", + ] { + let opts = WindowOptions { + focus: false, + show: false, + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: Default::default(), + size: size(px(1280.), px(800.)), + })), + ..crate::window_options() + }; + let (handle, _app) = cx + .update(|cx| { + gpui_kit::open_window(opts, cx, |window, cx| { + cx.new(|cx| { + let fixture = Fixture::Running; + let mut app = + HackApp::new(crate::source_for(Some(fixture)), false, window, cx); + app.select(fixtures::selected(fixture)); + setup(&mut app, frame); + app + }) + }) + }) + .expect("config screenshot window"); + cx.update_window(handle, |_, window, cx| window.render_frame(cx)) + .expect("render config"); + let path = dir.join(format!("{frame}-{suffix}.png")); + cx.capture_screenshot(handle) + .expect("capture config") + .save(&path) + .expect("save config"); + println!("{}", path.display()); + cx.update_window(handle, |_, window, _| window.remove_window()) + .ok(); + } + } +} diff --git a/apps/desktop/app/src/main.rs b/apps/desktop/app/src/main.rs index 70a6a59857..a5bee34c85 100644 --- a/apps/desktop/app/src/main.rs +++ b/apps/desktop/app/src/main.rs @@ -23,6 +23,7 @@ mod changes_view; mod clipboard; #[cfg(hack_terminal)] mod command_control; +mod config_view; mod copies_view; mod doctor_view; #[cfg(hack_terminal)] @@ -61,6 +62,7 @@ pub(crate) struct Args { pub fixture: Option, pub logs_fixture: Option, pub theme: Option, + pub config_screenshots: Option, pub screenshots: Option, pub service_screenshots: Option, pub command_screenshots: Option, @@ -78,7 +80,7 @@ pub(crate) struct Args { fn usage() -> ! { eprintln!( - "usage: hack-desktop [--fixtures | --logs-fixture ] [--theme light|dark] [--list-fixtures] [--screenshots | --command-screenshots ] [--drive [--hidden]]" + "usage: hack-desktop [--fixtures | --logs-fixture ] [--theme light|dark] [--list-fixtures] [--screenshots | --command-screenshots | --config-screenshots ] [--drive [--hidden]]" ); std::process::exit(2) } @@ -89,6 +91,7 @@ fn parse_args() -> Args { logs_fixture: None, theme: None, screenshots: None, + config_screenshots: None, service_screenshots: None, command_screenshots: None, sequence: None, @@ -144,6 +147,9 @@ fn parse_args() -> Args { _ => usage(), }); } + "--config-screenshots" => { + a.config_screenshots = Some(it.next().unwrap_or_else(|| usage()).into()) + } "--screenshots" => a.screenshots = Some(it.next().unwrap_or_else(|| usage()).into()), "--service-screenshots" => { a.service_screenshots = Some(it.next().unwrap_or_else(|| usage()).into()) @@ -225,6 +231,11 @@ fn main() { std::process::exit(2); } #[cfg(feature = "screenshots")] + if let Some(dir) = &args.config_screenshots { + config_view::screenshots::run(dir); + return; + } + #[cfg(feature = "screenshots")] if let Some(dir) = &args.sequence { screenshots::sequence(dir); return; @@ -253,14 +264,18 @@ fn main() { } } #[cfg(not(feature = "screenshots"))] - if args.screenshots.is_some() || args.sequence.is_some() || args.service_screenshots.is_some() { - eprintln!("--screenshots and --sequence need a build with --features screenshots"); + if args.screenshots.is_some() + || args.sequence.is_some() + || args.config_screenshots.is_some() + || args.service_screenshots.is_some() + { + eprintln!("Screenshot options need a build with --features screenshots"); std::process::exit(2); } gpui_kit::application() .with_assets(hack_desktop_ui::icons::Assets) .run(move |cx| { - theme::init(cx); + hack_desktop_ui::tokens::init(cx); #[cfg(all(feature = "screenshots", target_os = "linux"))] if args.fixture.is_some() || args.logs_fixture.is_some() { theme::capture_fonts(cx); diff --git a/apps/desktop/app/src/screenshots.rs b/apps/desktop/app/src/screenshots.rs index bba000e782..6cd76d34d4 100644 --- a/apps/desktop/app/src/screenshots.rs +++ b/apps/desktop/app/src/screenshots.rs @@ -22,7 +22,7 @@ fn fixture_context() -> HeadlessAppContext { gpui_kit::platform::current_headless_renderer, ); cx.update(|cx| { - crate::theme::init(cx); + hack_desktop_ui::tokens::init(cx); #[cfg(target_os = "linux")] crate::theme::capture_fonts(cx); }); @@ -391,7 +391,7 @@ pub fn sequence(dir: &Path) { Arc::new(hack_desktop_ui::icons::Assets), gpui_kit::platform::current_headless_renderer, ); - cx.update(gpui_kit::init); + cx.update(hack_desktop_ui::tokens::init); cx.update(crate::view::bind_keys); cx.update(|cx| Theme::change(ThemeMode::Dark, None, cx)); let f = Fixture::Running; diff --git a/apps/desktop/app/src/setup_view.rs b/apps/desktop/app/src/setup_view.rs index ae3d7e805a..4d7d5e9078 100644 --- a/apps/desktop/app/src/setup_view.rs +++ b/apps/desktop/app/src/setup_view.rs @@ -8,6 +8,8 @@ //! global trust`) run in the embedded terminal where available. Skips last for //! this session only and never satisfy a check. +#[cfg(all(test, feature = "screenshots", hack_terminal))] +use gpui_kit::test::TestSupportExt as _; use gpui_kit::{ AnyElement, ClipboardItem, Context, IntoElement, ParentElement, SharedString, Styled, div, prelude::*, px, @@ -18,11 +20,33 @@ use hack_desktop_ui::components::{ StyledExt as _, Ui, action_button, empty_pane, pill, primary_button, }; use hack_desktop_ui::icons::Glyph; +use hack_desktop_ui::status::Status as DotStatus; use hack_desktop_ui::tokens::{radius, space, text}; use crate::doctor_view::Pane; use crate::view::HackApp; +pub(crate) fn evidence_status(status: Status) -> (DotStatus, &'static str) { + match status { + Status::Passed => (DotStatus::Running, "Passed"), + Status::NeedsAttention => (DotStatus::Degraded, "Needs attention"), + Status::Unknown => (DotStatus::Unknown, "Unknown"), + } +} + +pub(crate) fn routing_evidence(report: &hack_desktop_core::setup::Report) -> Option { + report + .cards + .iter() + .filter(|card| card.id == "routing" || card.id.starts_with("dns:")) + .map(|card| card.status) + .max_by_key(|status| match status { + Status::Passed => 0, + Status::Unknown => 1, + Status::NeedsAttention => 2, + }) +} + impl HackApp { /// Fixtures and screenshots: show setup with a canned report. #[cfg_attr(not(feature = "screenshots"), allow(dead_code))] @@ -447,12 +471,12 @@ fn card( let pane = &app.setup; let p = ui.p; let skipped = pane.skipped.contains(&c.id); - let (label, colors) = match (c.status, skipped) { - (_, true) => ("Skipped for now", p.states.unknown), - (Status::Passed, false) => ("Passed", p.states.running), - (Status::NeedsAttention, false) => ("Needs attention", p.states.degraded), - (Status::Unknown, false) => ("Unknown", p.states.unknown), + let (status, label) = if skipped { + (DotStatus::Unknown, "Skipped for now") + } else { + evidence_status(c.status) }; + let colors = status.colors(&p); let cli = pane.report.cli_ready(); let mut actions = div().flex().items_center().gap(space::S3); let mut command_line: Option = None; @@ -607,7 +631,17 @@ fn card( .child(c.title.clone()), ) .child(div().flex_1()) - .child(pill(label, colors.bg, colors.fg)), + .child( + pill(label, colors.bg, colors.fg) + .id(("setup-status", i)) + .role(gpui_kit::Role::Label) + .aria_label(label) + .map(|pill| { + #[cfg(all(test, feature = "screenshots", hack_terminal))] + let pill = pill.test_support(); + pill + }), + ), ) .when(!c.detail.is_empty(), |d| { d.child( diff --git a/apps/desktop/app/src/terminal.rs b/apps/desktop/app/src/terminal.rs index 4562b15b26..88ac211b94 100644 --- a/apps/desktop/app/src/terminal.rs +++ b/apps/desktop/app/src/terminal.rs @@ -623,6 +623,9 @@ impl HackApp { }, ); self.open_tab(&d, NewTab::Logs, window, cx); + if matches!(self.tab, 1 | crate::config_view::TAB) { + self.set_state(&d.key, PanelState::Collapsed, cx); + } } /// Reopen Logs after a target change, or follow once a copy starts. @@ -664,6 +667,12 @@ impl HackApp { .clone() } + /// Keep the native evidence independent of machine-local Ghostty settings. + #[cfg(feature = "screenshots")] + pub(crate) fn use_default_terminal_look(&mut self) { + self.panels.look = Some(GhosttyLook::default()); + } + fn panel_logs_follow(&self, detail: &DetailView) -> bool { logs_should_follow( detail, @@ -1061,6 +1070,12 @@ impl HackApp { } } + pub(crate) fn collapse_detail_terminal(&mut self, cx: &mut Context) { + if let Some(key) = self.model.selected_key() { + self.set_state(&key, PanelState::Collapsed, cx); + } + } + pub(crate) fn toggle_visible_panel(&mut self, window: &mut Window, cx: &mut Context) { if self.selected_service().is_some() && self.service_pane.tab != ServiceTab::Terminal { self.set_service_tab(ServiceTab::Terminal, window, cx); @@ -1359,7 +1374,7 @@ impl HackApp { ui: &Ui, cx: &mut Context, ) -> impl IntoElement { - let mut t = TermPalette::fallback(); + let mut t = TermPalette::for_mode(ui.p.mode); if docked { t.strip = ui.p.chrome; t.bg = ui.p.surface; @@ -1765,12 +1780,15 @@ impl HackApp { return div().into_any_element(); }; let state = panel.state; + if matches!(self.tab, 1 | crate::config_view::TAB) && state == PanelState::Collapsed { + return div().into_any_element(); + } let sessions = panel.sessions.clone(); let strip = self.strip(d, panel, false, ui, cx).into_any_element(); let surface = div() .flex_1() .min_h_0() - .bg(TermPalette::fallback().bg) + .bg(TermPalette::for_mode(ui.p.mode).bg) .child(sessions) .into_any_element(); let base = div().flex().flex_col().min_h_0().relative(); diff --git a/apps/desktop/app/src/theme.rs b/apps/desktop/app/src/theme.rs index 3f0b729004..260993541d 100644 --- a/apps/desktop/app/src/theme.rs +++ b/apps/desktop/app/src/theme.rs @@ -1,28 +1,10 @@ //! Native component colors and deterministic fonts for design captures. -use gpui_kit::{App, component::Theme}; -use std::rc::Rc; - -pub fn init(cx: &mut App) { - gpui_kit::init(cx); - Theme::update(cx, |theme| { - let dark = Rc::make_mut(&mut theme.dark_theme); - dark.name = "Merino Dark".into(); - dark.colors.background = Some("#0d1117".into()); - dark.colors.foreground = Some("#e6edf3".into()); - dark.colors.selection = Some("#24272b".into()); - dark.colors.border = Some("#2b3036".into()); - dark.colors.muted = Some("#1a1e24".into()); - dark.colors.muted_foreground = Some("#8b9197".into()); - dark.colors.primary = Some("#e6edf3".into()); - dark.colors.primary_foreground = Some("#0d1117".into()); - }); - Theme::change(Theme::global(cx).mode, None, cx); -} - #[cfg(all(feature = "screenshots", target_os = "linux"))] -pub fn capture_fonts(cx: &mut App) { +pub fn capture_fonts(cx: &mut gpui_kit::App) { + use gpui_kit::component::Theme; use std::borrow::Cow; + use std::rc::Rc; // Geist 1.4.2, bundled under the SIL Open Font License for Linux captures. let fonts: [&'static [u8]; 2] = [ diff --git a/apps/desktop/app/src/view.rs b/apps/desktop/app/src/view.rs index 2e52b64948..d727068202 100644 --- a/apps/desktop/app/src/view.rs +++ b/apps/desktop/app/src/view.rs @@ -15,6 +15,8 @@ use gpui_kit::component::{ ActiveTheme, Sizable as _, input::{Input, InputEvent, InputState}, }; +#[cfg(all(test, feature = "screenshots", hack_terminal))] +use gpui_kit::test::TestSupportExt as _; use gpui_kit::{ AnyElement, App, ClipboardItem, Context, Entity, IntoElement, KeyBinding, ParentElement, Render, Styled, Task, Window, div, prelude::*, px, @@ -26,6 +28,7 @@ use hack_desktop_core::source::{ }; use crate::doctor_view::Pane; +use crate::setup_view::{evidence_status, routing_evidence}; use hack_desktop_core::doctor::DoctorState as DoctorStateView; use hack_desktop_core::source::target_keys; @@ -134,6 +137,7 @@ pub struct HackApp { pub(crate) source: Arc, pub(crate) logs: crate::logs_view::LogsPane, pub(crate) tab: usize, + pub(crate) config: crate::config_view::ConfigPane, pub(crate) sidebar_menu: Option, pub(crate) changes: crate::changes_view::ChangesPane, pub(crate) catalog: crate::service_catalog::ServiceCatalog, @@ -227,6 +231,7 @@ impl HackApp { source, logs, tab: 0, + config: Default::default(), sidebar_menu: None, changes: Default::default(), catalog: crate::service_catalog::ServiceCatalog { @@ -501,6 +506,7 @@ impl HackApp { self.reset_env_selection(); self.reset_changes(cx); self.refresh_copies_if_open(cx); + self.sync_config_tab(cx); if self.tab == 2 { self.read_env(cx); } @@ -1082,6 +1088,7 @@ impl HackApp { self.refresh_now(); } self.refresh_copies_if_open(cx); + self.sync_config_tab(cx); // A service filter belongs to one project: reset it on every // project change, whichever tab is open. self.logs.model.set_service(None); @@ -1099,8 +1106,13 @@ impl HackApp { return; } self.tab = to; + #[cfg(hack_terminal)] + if matches!(to, 1 | crate::config_view::TAB) { + self.collapse_detail_terminal(cx); + } self.files = Default::default(); self.refresh_copies_if_open(cx); + self.sync_config_tab(cx); self.env_edit = None; self.env.begin(); if to == 1 { @@ -1179,6 +1191,7 @@ impl HackApp { if before != after { self.clear_selected_service(); self.model.source_changed(); + self.config.switch_cli(after.map(|install| install.path)); self.changes = Default::default(); self.action_started.clear(); self.copies = Default::default(); @@ -1213,6 +1226,9 @@ impl HackApp { } #[cfg(hack_terminal)] self.close_all_terminals(window, cx); + if self.pane == Pane::Project { + self.sync_config_tab(cx); + } } let _ = window; self.refresh_now_async(cx); @@ -1240,11 +1256,16 @@ impl HackApp { .detach(); } - fn title_bar(&self, ui: &Ui) -> impl IntoElement { + fn title_bar(&self, ui: &Ui, projects_open: bool) -> impl IntoElement { let p = ui.p; + let background = if projects_open { + p.chrome + } else { + p.title_bar() + }; gpui_kit::component::TitleBar::new() .h(size::TITLE_BAR) - .bg(p.chrome) + .bg(background) .border_color(p.border) .child( div() @@ -1316,6 +1337,8 @@ impl HackApp { } Phase::Empty | Phase::CliMissing | Phase::Error { .. } => {} } + let routing = self.routing_status(); + let hackd = self.hackd_sidebar_status(); let machine = div() .flex_none() .flex() @@ -1328,29 +1351,31 @@ impl HackApp { "routing", Glyph::Globe, "Routing and DNS", - dot(self.routing_status().unwrap_or(Status::Unknown), ui), + dot(routing, ui), ui, ) - .on_click(cx.listener(|this, _, _, cx| this.open_doctor(None, cx))), + .aria_label(format!( + "Routing and DNS: {}", + machine_status_label(routing) + )) + .on_click(cx.listener(|this, _, _, cx| this.open_doctor(None, cx))) + .map(|row| { + #[cfg(all(test, feature = "screenshots", hack_terminal))] + let row = row.test_support(); + row + }), + ) + .child( + machine_row("hackd", Glyph::Power, "hackd", dot(hackd, ui), ui) + .aria_label(format!("hackd: {}", machine_status_label(hackd))) + .when(self.pane == Pane::Hackd, |d| d.bg(p.selection)) + .on_click(cx.listener(|this, _, _, cx| this.open_hackd(cx))) + .map(|row| { + #[cfg(all(test, feature = "screenshots", hack_terminal))] + let row = row.test_support(); + row + }), ) - .child({ - let tone = self - .hackd_card() - .map(|c| c.tone) - .or_else(|| self.hackd_tone_from_snapshot()); - machine_row( - "hackd", - Glyph::Power, - "hackd", - dot( - tone.map_or(Status::Unknown, crate::machine_view::status_of), - ui, - ), - ui, - ) - .when(self.pane == Pane::Hackd, |d| d.bg(p.surface_1)) - .on_click(cx.listener(|this, _, _, cx| this.open_hackd(cx))) - }) .child( machine_row( "upgrade", @@ -1359,12 +1384,12 @@ impl HackApp { dot(self.upgrade_status(), ui), ui, ) - .when(self.pane == Pane::Upgrade, |d| d.bg(p.surface_1)) + .when(self.pane == Pane::Upgrade, |d| d.bg(p.selection)) .on_click(cx.listener(|this, _, _, cx| this.open_upgrade(cx))), ) .child( machine_row("resources", Glyph::Container, "Resources", div(), ui) - .when(self.pane == Pane::Resources, |d| d.bg(p.surface_1)) + .when(self.pane == Pane::Resources, |d| d.bg(p.selection)) .on_click(cx.listener(|this, _, _, cx| this.show_resources(cx))), ) .child( @@ -1375,7 +1400,7 @@ impl HackApp { self.doctor_trailing(list, ui), ui, ) - .when(self.pane == Pane::Doctor, |d| d.bg(p.surface_1)) + .when(self.pane == Pane::Doctor, |d| d.bg(p.selection)) .on_click(cx.listener(|this, _, _, cx| this.open_doctor(None, cx))), ); div() @@ -1408,17 +1433,66 @@ impl HackApp { cx.notify(); } - /// Routing and DNS: from the last completed Doctor run when there is - /// one, else from Doctor checks in the snapshot. `None` (a ring) until - /// either has reported. - fn routing_status(&self) -> Option { - if let DoctorStateView::Loaded(v) = &self.doctor.result { - return routing_from_doctor(v); + fn hackd_sidebar_status(&self) -> Status { + if self.pane == Pane::Setup + && let Some(card) = self + .setup + .report + .cards + .iter() + .find(|card| card.id == "daemon") + { + return evidence_status(card.status).0; + } + self.hackd_card() + .map(|card| card.tone) + .or_else(|| self.hackd_tone_from_snapshot()) + .map_or(Status::Unknown, crate::machine_view::status_of) + } + + /// Setup owns its visible cards and dots. Elsewhere use the newest + /// current report, ordered by read start so a slow older Doctor run + /// cannot replace a post-command Setup check. + fn routing_status(&self) -> Status { + let setup = routing_evidence(&self.setup.report).map(|s| evidence_status(s).0); + if self.pane == Pane::Setup + && let Some(status) = setup + { + return status; } - let checks = &self.model.snapshot()?.doctor.as_ref()?.checks; - hack_desktop_ui::window::routing_status( - checks.iter().map(|c| (c.id.as_str(), c.status.as_str())), - ) + + let now = Instant::now(); + let setup = setup.zip(self.setup.observed_at).filter(|_| { + self.setup.checked_at.is_some_and(|at| { + now.saturating_duration_since(at) < hack_desktop_core::setup::RECHECK_EVERY + }) + }); + let doctor = self.doctor.fresh_observation(now); + if let Some((status, start)) = setup + && doctor.is_none_or(|other| start >= other) + { + return status; + } + if doctor.is_some() { + return match &self.doctor.result { + DoctorStateView::Loaded(view) => routing_from_doctor(view), + _ => None, + } + .unwrap_or(Status::Unknown); + } + self.model + .snapshot() + .filter(|_| self.model.project_list_readable()) + .and_then(|snapshot| snapshot.doctor.as_ref()) + .and_then(|report| { + hack_desktop_ui::window::routing_status( + report + .checks + .iter() + .map(|c| (c.id.as_str(), c.status.as_str())), + ) + }) + .unwrap_or(Status::Unknown) } /// The Doctor row's trailing mark (see [`doctor_mark`]). @@ -1641,7 +1715,11 @@ impl HackApp { .child(t) })) .child(div().flex_1()) - .child(actions), + .child(if self.tab == crate::config_view::TAB && !compact { + self.config_checkout_picker(cx) + } else { + actions.into_any_element() + }), ) .when(!compact, |col| { col.child(url_row).children( @@ -1832,6 +1910,7 @@ impl HackApp { (1, "Logs"), (2, "Env"), (3, "Copies"), + (crate::config_view::TAB, "Config"), (6, "Changes"), (5, "Add service"), (crate::files_view::FILES_TAB, "Files"), @@ -1867,6 +1946,7 @@ impl HackApp { tabs = tabs.child(self.project_files_picker(d, cx)); } let body: AnyElement = match self.tab { + crate::config_view::TAB => self.config_view(ui, window, cx), 5 => div() .id("service-catalog") .flex_1() @@ -2007,6 +2087,17 @@ impl HackApp { } } +fn machine_status_label(status: Status) -> &'static str { + match status { + Status::Running => "Passed", + Status::Degraded => "Needs attention", + Status::Failed => "Failed", + Status::Unknown => "Unknown", + Status::Busy => "In progress", + Status::Stopped => "Off", + } +} + impl HackApp { #[cfg(hack_terminal)] fn stats_tab_open(&self) -> bool { @@ -2120,11 +2211,11 @@ impl Render for HackApp { _ if self.pane == Pane::ErrorsSheet => { crate::health_fixtures::errors(self, &ui, window, cx) } - // Setup applies whatever the project list shows, a missing CLI - // included. _ if self.pane == Pane::Resources => crate::resources_view::render(self, &ui, cx), _ if self.pane == Pane::Hackd => crate::machine_view::render(self, &ui, cx), _ if self.pane == Pane::Upgrade => crate::upgrade_view::render(self, &ui, cx), + // Setup applies whatever the project list shows, a missing CLI + // included. _ if self.pane == Pane::Setup => crate::setup_view::render(self, &ui, cx), // Machine checks matter most before any project exists, so the // Doctor pane renders for an empty registry too. @@ -2227,10 +2318,10 @@ impl Render for HackApp { .size_full() .flex() .flex_col() - .bg(if projects_open { p.chrome } else { p.surface }) + .bg(if projects_open { p.chrome } else { p.window }) .text_color(p.text_primary) .font_family(ui.font.clone()) - .child(self.title_bar(&ui)) + .child(self.title_bar(&ui, projects_open)) .child( div() .flex_1() @@ -2471,6 +2562,111 @@ mod tests { } } +#[cfg(all(test, feature = "screenshots", hack_terminal))] +mod machine_status_render_tests { + use super::*; + use crate::command_control::screenshots::tests::{assert_rendered_status, open}; + use hack_desktop_core::models::{DoctorCheck, DoctorReport}; + use hack_desktop_core::{ + doctor::{DoctorRun, Finish}, + setup::Status, + }; + + #[test] + fn rendered_dns_tracks_a_fresh_setup_check_and_rejects_older_and_stale_reads() { + let (mut cx, window, app) = open(1); + assert_rendered_status( + &mut cx, + window, + "routing", + "Routing and DNS: Needs attention", + Some("Needs attention"), + ); + let warn = DoctorRun::machine(Ok(DoctorReport { + checks: vec![DoctorCheck { + native_pool: None, + id: "resolver:hack".into(), + status: "warn".into(), + detail: "Resolver missing".into(), + fix: None, + }], + ..Default::default() + })); + cx.update(|cx| { + app.update(cx, |a, cx| { + let older_doctor = a.doctor.begin(Some(&[])); + let stale_setup = a.setup.begin(); + let generation = a.setup.begin(); + let before = a.setup.report.clone(); + let mut after = before.clone(); + after.cards[1].status = Status::Passed; + a.setup_checked(generation, after, cx); + a.setup_checked(stale_setup, before, cx); + assert_eq!( + a.doctor.finish( + older_doctor, + std::slice::from_ref(&warn), + Some(&[]), + Instant::now() + ), + Finish::Applied + ); + }) + }); + assert_rendered_status( + &mut cx, + window, + "routing", + "Routing and DNS: Passed", + Some("Passed"), + ); + + cx.update(|cx| { + app.update(cx, |a, cx| { + a.show_project(); + cx.notify(); + }) + }); + assert_rendered_status(&mut cx, window, "routing", "Routing and DNS: Passed", None); + + cx.update(|cx| { + app.update(cx, |a, cx| { + let newer_doctor = a.doctor.begin(None); + assert_eq!( + a.doctor.finish( + newer_doctor, + std::slice::from_ref(&warn), + Some(&[]), + Instant::now() + ), + Finish::AppliedStale + ); + cx.notify(); + }) + }); + assert_rendered_status(&mut cx, window, "routing", "Routing and DNS: Passed", None); + + cx.update(|cx| { + app.update(cx, |a, cx| { + let newer_doctor = a.doctor.begin(Some(&[])); + assert_eq!( + a.doctor + .finish(newer_doctor, &[warn], Some(&[]), Instant::now()), + Finish::Applied + ); + cx.notify(); + }) + }); + assert_rendered_status( + &mut cx, + window, + "routing", + "Routing and DNS: Needs attention", + None, + ); + } +} + /// The live refresh path in a window: list first, then each native `ps`. #[cfg(all(test, feature = "screenshots"))] mod native_fill_tests { diff --git a/apps/desktop/core/src/config.rs b/apps/desktop/core/src/config.rs new file mode 100644 index 0000000000..4dbdce63e0 --- /dev/null +++ b/apps/desktop/core/src/config.rs @@ -0,0 +1,330 @@ +//! Versioned project config contract. Config subprocess errors never surface +//! unstructured output. Drafts travel on stdin and stay in memory. + +use std::{collections::BTreeMap, path::Path, time::Duration}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::runner::{CliRunner, RunError, parse_schema_result}; + +pub const SCHEMA: &str = "hack.config.v1"; + +#[derive(Clone, Default, Deserialize)] +pub struct ConfigReport { + pub state: ConfigState, + pub project: Value, + pub services: Vec, + pub layers: Vec, + pub env: Vec, + pub issues: Vec, + pub checkout: Option, + pub branch: Option, + pub overlay: Option, + pub default_overlay: Option, + pub overlays: Vec, + pub writable: bool, +} + +#[derive(Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ConfigState { + Ready, + Invalid, + #[default] + Missing, +} + +#[derive(Clone, Deserialize)] +pub struct ConfigLayer { + pub id: String, + pub file: String, + pub kind: String, + pub ownership: String, + pub active: bool, + pub writable: bool, + pub revision: String, + pub exists: bool, + pub source: Option, + pub hidden: bool, + pub source_writable: bool, + pub inherited: Option, + pub overlay: Option, +} + +impl ConfigLayer { + pub fn name(&self) -> &str { + Path::new(&self.file) + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or(&self.file) + } + + pub fn chip(&self) -> &str { + if !self.active { + "–" + } else { + self.overlay + .as_deref() + .map_or(&self.id, |_| match self.id.as_bytes().first() { + Some(b'3') => "3a", + Some(b'4') => "4a", + _ => "5a", + }) + } + } +} + +impl ConfigReport { + pub fn revisions(&self) -> BTreeMap { + self.layers + .iter() + .map(|layer| (layer.id.clone(), layer.revision.clone())) + .collect() + } + + pub fn layer(&self, id: &str) -> Option<&ConfigLayer> { + self.layers.iter().find(|layer| layer.id == id) + } + + /// Retain source order. The last assignment wins by layer, then by scope + /// within the layer, including an explicit unset. + pub fn env_for(&self, scope: &str) -> Vec { + let mut result: Vec = Vec::new(); + for entry in self + .env + .iter() + .filter(|entry| entry.scope == "global" || entry.scope == scope) + { + let mut scoped = entry.clone(); + for cell in &mut scoped.values { + cell.scope.clone_from(&entry.scope); + } + if let Some(row) = result.iter_mut().find(|row| row.key == entry.key) { + row.values.extend(scoped.values); + } else { + result.push(scoped); + } + } + for row in &mut result { + row.values.sort_by_key(|cell| { + ( + self.layers + .iter() + .position(|layer| layer.id == cell.layer) + .unwrap_or(usize::MAX), + cell.scope != "global", + ) + }); + if let Some(cell) = row.values.last() { + row.scope.clone_from(&cell.scope); + } + row.winning = row + .values + .last() + .filter(|cell| !cell.unset) + .map(|cell| cell.layer.clone()); + } + result + } +} + +#[derive(Clone, Deserialize)] +pub struct ConfigService { + pub name: String, + pub image: Option, + pub ports: Vec, + pub depends_on: Vec, + pub routes: Vec, + pub route_edit: Option, + #[serde(default)] + pub source_fields: Vec, +} + +#[derive(Clone, Deserialize)] +pub struct ConfigRoute { + pub host: String, + pub port: Option, + pub tls: bool, + pub from: Vec, +} + +#[derive(Clone, Deserialize)] +pub struct RouteEdit { + pub sites: String, + pub port: Option, +} + +#[derive(Clone, Deserialize)] +pub struct EnvRow { + pub key: String, + pub scope: String, + pub values: Vec, + pub winning: Option, +} + +#[derive(Clone, Deserialize)] +pub struct EnvCell { + pub layer: String, + #[serde(default)] + pub scope: String, + #[serde(default)] + pub unset: bool, + pub secret: bool, + pub value: Option, +} + +impl EnvCell { + pub fn label(&self) -> String { + if self.secret { + "secret · set".into() + } else if self.unset { + "unset".into() + } else { + self.value.as_ref().map_or_else(String::new, scalar_label) + } + } +} + +pub fn scalar_label(value: &Value) -> String { + value + .as_str() + .map_or_else(|| value.to_string(), ToOwned::to_owned) +} + +#[derive(Clone, Deserialize)] +pub struct ConfigIssue { + pub layer: Option, + pub path: Vec, + pub line: Option, + pub code: String, + pub message: String, +} + +#[derive(Clone, Default, Deserialize)] +pub struct ConfigValidation { + pub valid: bool, + pub issues: Vec, + pub previews: BTreeMap>, +} + +#[derive(Clone, Deserialize)] +pub struct ConfigSaved { + pub changed: Vec, + pub restart_offered: bool, +} + +#[derive(Clone)] +pub struct ConfigError { + pub code: String, + pub message: String, + pub issues: Vec, + pub changed: Vec, +} + +impl ConfigError { + pub fn unavailable() -> Self { + Self { + code: "E_UNAVAILABLE".into(), + message: + "Hack couldn’t read this project’s Config. Check the selected CLI and try again." + .into(), + issues: Vec::new(), + changed: Vec::new(), + } + } +} + +#[derive(Clone, Default, PartialEq, Eq, Hash)] +pub struct ConfigTarget { + pub branch: Option, + pub overlay: Option, +} + +#[derive(Clone, Serialize)] +pub struct ConfigPatch { + pub base: BTreeMap, + pub changes: Vec, +} + +#[derive(Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ConfigChange { + Project { + layer: String, + path: String, + value: Value, + }, + Route { + layer: String, + service: String, + sites: String, + port: String, + }, + Service { + layer: String, + service: String, + field: String, + value: Value, + }, + Env { + layer: String, + scope: String, + key: String, + value: Option, + }, + Source { + layer: String, + text: String, + }, +} + +impl ConfigChange { + pub fn layer(&self) -> &str { + match self { + Self::Project { layer, .. } + | Self::Route { layer, .. } + | Self::Service { layer, .. } + | Self::Env { layer, .. } + | Self::Source { layer, .. } => layer, + } + } +} + +pub(crate) fn run_config( + runner: CliRunner, + root: &Path, + target: &ConfigTarget, + command: &str, + patch: Option<&ConfigPatch>, +) -> Result { + let mut args = vec!["config", command, "--json"]; + if let Some(branch) = &target.branch { + args.extend(["--branch", branch]); + } + if let Some(overlay) = &target.overlay { + args.extend(["--env", overlay]); + } + let runner = runner.with_env("HACK_DAEMON_AUTOSTART_DISABLE", "1"); + let timeout = Duration::from_secs(15); + let (stdout, _, code) = if let Some(patch) = patch { + let input = serde_json::to_vec(patch).map_err(|_| ConfigError::unavailable())?; + runner.run_raw_with_input(&args, Some(root), timeout, &input) + } else { + runner.run_raw(&args, Some(root), timeout) + } + .map_err(|_| ConfigError::unavailable())?; + let envelope = parse_schema_result(&stdout, "", code, SCHEMA).map_err(|error| match error { + RunError::Cli(error) => { + let detail = error.detail.unwrap_or(Value::Null); + ConfigError { + code: error.code, + message: error.message, + issues: serde_json::from_value(detail["issues"].clone()).unwrap_or_default(), + changed: serde_json::from_value(detail["changed"].clone()).unwrap_or_default(), + } + } + _ => ConfigError::unavailable(), + })?; + serde_json::from_value(envelope).map_err(|_| ConfigError::unavailable()) +} diff --git a/apps/desktop/core/src/doctor.rs b/apps/desktop/core/src/doctor.rs index 5ac20d5e47..e49be3f5f7 100644 --- a/apps/desktop/core/src/doctor.rs +++ b/apps/desktop/core/src/doctor.rs @@ -947,7 +947,8 @@ pub enum Finish { pub struct DoctorPane { pub result: DoctorState, generation: u64, - in_flight: Option<(u64, Option>)>, + in_flight: Option<(u64, Option>, Instant)>, + observed_at: Option, checked_at: Option, /// The targets the shown result checked (`None`: the project list /// could not be read). @@ -965,6 +966,7 @@ impl DoctorPane { pub fn source_changed(&mut self) { self.result = DoctorState::NeverRun; self.in_flight = None; + self.observed_at = None; self.checked_at = None; self.checked_targets = None; self.stale = false; @@ -975,7 +977,7 @@ impl DoctorPane { /// be read, so only machine checks run); returns its generation. pub fn begin(&mut self, targets: Option<&[TargetKey]>) -> u64 { self.generation += 1; - self.in_flight = Some((self.generation, sorted(targets))); + self.in_flight = Some((self.generation, sorted(targets), Instant::now())); self.generation } @@ -1005,11 +1007,11 @@ impl DoctorPane { current: Option<&[TargetKey]>, now: Instant, ) -> Finish { - let Some((g, targets)) = self.in_flight.take() else { + let Some((g, targets, started_at)) = self.in_flight.take() else { return Finish::Discarded; }; if g != generation { - self.in_flight = Some((g, targets)); + self.in_flight = Some((g, targets, started_at)); return Finish::Discarded; } self.result = DoctorState::from_runs(runs); @@ -1017,6 +1019,7 @@ impl DoctorPane { // Machine checks ran, but no project was: never "all clear". v.projects_unread = true; } + self.observed_at = Some(started_at); self.checked_at = Some(now); self.stale = sorted(current) != targets; self.checked_targets = targets; @@ -1037,6 +1040,17 @@ impl DoctorPane { .is_none_or(|t| now.saturating_duration_since(t) >= REFRESH_EVERY)) } + /// Start time of the accepted result while it still describes the current targets. + #[must_use] + pub fn fresh_observation(&self, now: Instant) -> Option { + self.observed_at.filter(|_| { + !self.stale + && self + .checked_at + .is_some_and(|t| now.saturating_duration_since(t) < REFRESH_EVERY) + }) + } + #[must_use] pub fn age_label(&self, now: Instant) -> Option { let mins = now.saturating_duration_since(self.checked_at?).as_secs() / 60; diff --git a/apps/desktop/core/src/fixtures.rs b/apps/desktop/core/src/fixtures.rs index 664023e605..233dd711bf 100644 --- a/apps/desktop/core/src/fixtures.rs +++ b/apps/desktop/core/src/fixtures.rs @@ -106,7 +106,7 @@ pub enum Fixture { } impl Fixture { - pub const ALL: [Self; 64] = [ + pub const ALL: [Self; 68] = [ Self::EnvLoading, Self::EnvError, Self::EnvNormal, diff --git a/apps/desktop/core/src/lib.rs b/apps/desktop/core/src/lib.rs index 914b096a85..357a57bd12 100644 --- a/apps/desktop/core/src/lib.rs +++ b/apps/desktop/core/src/lib.rs @@ -12,6 +12,7 @@ //! history for the current session. Every action is one CLI command. pub mod cli_choice; +pub mod config; pub mod daemon; pub mod doctor; mod doctor_acl; diff --git a/apps/desktop/core/src/setup.rs b/apps/desktop/core/src/setup.rs index fba31a4c1e..dcd32025e6 100644 --- a/apps/desktop/core/src/setup.rs +++ b/apps/desktop/core/src/setup.rs @@ -110,6 +110,9 @@ pub struct Pane { pub result: Option, pub skipped: std::collections::BTreeSet, generation: u64, + started_at: Option, + /// Start time of the accepted report, used to order it against Doctor. + pub observed_at: Option, pub checked_at: Option, /// Bumped when the app switches CLI: an action started under the /// previous one compares it on completion and is dropped. @@ -118,6 +121,7 @@ pub struct Pane { impl Pane { pub fn begin(&mut self) -> u64 { self.generation += 1; + self.started_at = Some(std::time::Instant::now()); self.loading = true; if !self.pending_fix { self.result = None; @@ -128,6 +132,7 @@ impl Pane { if generation == self.generation { self.report = report; self.loading = false; + self.observed_at = self.started_at; self.checked_at = Some(std::time::Instant::now()); } } diff --git a/apps/desktop/core/src/source.rs b/apps/desktop/core/src/source.rs index f4ad4e84a9..12610002b8 100644 --- a/apps/desktop/core/src/source.rs +++ b/apps/desktop/core/src/source.rs @@ -428,7 +428,49 @@ impl From for CopiesError { } } +use crate::config::{ + ConfigError, ConfigPatch, ConfigReport, ConfigSaved, ConfigTarget, ConfigValidation, run_config, +}; + pub trait Source: Send + Sync { + fn config_show( + &self, + _root: &Path, + _target: &ConfigTarget, + ) -> Result { + Err(ConfigError::unavailable()) + } + + fn config_validate( + &self, + _root: &Path, + _target: &ConfigTarget, + _patch: &ConfigPatch, + ) -> Result { + Err(ConfigError::unavailable()) + } + + fn config_apply( + &self, + _root: &Path, + _target: &ConfigTarget, + _patch: &ConfigPatch, + ) -> Result { + Err(ConfigError::unavailable()) + } + + fn config_restart( + &self, + root: &Path, + target: &ConfigTarget, + ) -> Result { + self.act(root, false, target.branch.as_deref(), Action::Restart) + } + + fn config_init_command(&self) -> Result { + Err("The Hack CLI is unavailable.".into()) + } + /// Preview a catalog edit, or save the exact revision previously previewed. /// /// # Errors @@ -2251,6 +2293,73 @@ impl Source for LiveSource { Self::read_native_ps(&Self::native_runner(&self.runner.fixed()), repo_root) } + fn config_show(&self, root: &Path, target: &ConfigTarget) -> Result { + if root.is_absolute() && root.is_dir() && !cli_selects_exactly(root) { + return Ok(ConfigReport::default()); + } + let root = trusted_root(root).map_err(|_| ConfigError::unavailable())?; + run_config(self.runner_for(false), &root, target, "show", None) + } + + fn config_validate( + &self, + root: &Path, + target: &ConfigTarget, + patch: &ConfigPatch, + ) -> Result { + let root = env_root(root).ok_or_else(ConfigError::unavailable)?; + run_config( + self.runner_for(false), + &root, + target, + "validate", + Some(patch), + ) + } + + fn config_apply( + &self, + root: &Path, + target: &ConfigTarget, + patch: &ConfigPatch, + ) -> Result { + let root = env_root(root).ok_or_else(ConfigError::unavailable)?; + run_config(self.runner_for(false), &root, target, "apply", Some(patch)) + } + + fn config_restart( + &self, + root: &Path, + target: &ConfigTarget, + ) -> Result { + let Some(overlay) = target.overlay.as_deref() else { + return self.act(root, false, target.branch.as_deref(), Action::Restart); + }; + let branch = target.branch.as_deref().map(validate_branch).transpose()?; + let root = trusted_root(root)?; + let mut args = with_branch(Action::Restart.cli_args(), branch); + args.extend(["--env", overlay]); + Ok(ActionOutcome::Lifecycle( + self.runner_for(false) + .run_json_to_completion(&args, Some(&root))?, + )) + } + + fn config_init_command(&self) -> Result { + let runner = self.runner_for(false); + let program = runner + .resolve_program() + .map_err(|_| "The Hack CLI is unavailable.")?; + let context = crate::execution::ExecutionContext::capture(&runner)?; + context.bind(&crate::terminal::CommandSpec { + program: program + .to_str() + .ok_or("The Hack CLI path is unavailable.")? + .into(), + args: vec!["init".into()], + }) + } + fn copies(&self, root: &Path, native: bool) -> Result { let root = trusted_root(root).map_err(|error| CopiesError { reason: describe_error(&error), @@ -2485,6 +2594,28 @@ pub fn parse_log_tail(out: &str, err: &str, code: Option) -> Result Result { + trusted_checkout(root, true) +} + +/// Init starts from a checkout before a Hack project marker exists. +pub fn trusted_init_root(root: &Path) -> Result { + let root = trusted_checkout(root, false)?; + let repo = root + .ancestors() + .find(|ancestor| ancestor.join("package.json").exists() || ancestor.join(".git").exists()); + if repo.is_some_and(|repo| repo != root) { + return Err(SourceError::Cli { + code: "E_APP_UNTRUSTED_ROOT".into(), + message: + "Hack init would configure a parent repository. Select that repository to continue." + .into(), + failed: vec![], + }); + } + Ok(root) +} + +fn trusted_checkout(root: &Path, require_config: bool) -> Result { use std::os::unix::fs::MetadataExt; let refuse = |why: String| SourceError::Cli { code: "E_APP_UNTRUSTED_ROOT".into(), @@ -2538,7 +2669,7 @@ pub fn trusted_root(root: &Path) -> Result { Ok(()) }; // The CLI must select exactly this root (see `discoverProjectInputs`). - if !cli_selects_exactly(&real) { + if require_config && !cli_selects_exactly(&real) { return Err(refuse( "the project folder is not the project the CLI would select from it".into(), )); @@ -5062,6 +5193,25 @@ echo '{"ok":true,"data":{"copies":[{"checkout":{"name":"shop","root":"/work/shop let _ = std::fs::remove_dir_all(&b); } + #[test] + fn init_checkout_cannot_resolve_to_a_parent_repository() { + if !host_temp_is_trustworthy() { + return; + } + let root = base("init-root"); + let checkout = root.join("checkout"); + let child = checkout.join("child"); + std::fs::create_dir_all(&child).unwrap(); + std::fs::write(checkout.join("package.json"), "{}").unwrap(); + assert!(untrusted(trusted_init_root(&child))); + assert_eq!( + trusted_init_root(&checkout).unwrap(), + checkout.canonicalize().unwrap() + ); + assert!(untrusted(trusted_root(&checkout))); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn trusted_root_refuses_unsafe_or_ambiguous_roots() { use std::os::unix::fs::PermissionsExt; @@ -5675,7 +5825,7 @@ echo '{"ok":true,"data":{"copies":[{"checkout":{"name":"shop","root":"/work/shop let hack = dir.join("hack"); crate::test_support::script( &hack, - "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$HACK_HOME/argv\"\nif [ \"$1\" = logs ]; then echo '{\"type\":\"start\"}'; echo '{\"type\":\"end\",\"reason\":\"eof\"}'; exit 0; fi\necho '{\"ok\":true,\"data\":{\"action\":\"up\",\"url\":\"https://fix-login.storefront.hack\",\"services\":{\"failed\":[]}}}'\n", + "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$HACK_HOME/argv\"\nprintf '%s\\n' \"$HACK_RUNTIME_BACKEND\" > \"$HACK_HOME/backend\"\nif [ \"$1\" = logs ]; then echo '{\"type\":\"start\"}'; echo '{\"type\":\"end\",\"reason\":\"eof\"}'; exit 0; fi\necho '{\"ok\":true,\"data\":{\"action\":\"up\",\"url\":\"https://fix-login.storefront.hack\",\"services\":{\"failed\":[]}}}'\n", ); hack } @@ -5745,6 +5895,29 @@ echo '{"ok":true,"data":{"copies":[{"checkout":{"name":"shop","root":"/work/shop } src.act(&p, false, None, Action::Start).unwrap(); assert!(!argv(&b).iter().any(|a| a == "--branch")); + let native = LiveSource::new( + fixture_runner(&hack).with_env("HACK_RUNTIME_BACKEND", "native"), + None, + ); + for overlay in [Some("qa"), Some("default"), None] { + native + .config_restart( + &p, + &ConfigTarget { + branch: Some("fix-login".into()), + overlay: overlay.map(str::to_owned), + }, + ) + .unwrap(); + let got = argv(&b); + assert_eq!(got[..3], ["restart", "--branch", "fix-login"]); + let passed = got.windows(2).find(|args| args[0] == "--env"); + assert_eq!(passed.map(|args| args[1].as_str()), overlay); + assert_eq!( + std::fs::read_to_string(b.join("backend")).unwrap().trim(), + "compose" + ); + } } else { eprintln!("skipped actions: temp dir ancestors are not private on this host"); } diff --git a/apps/desktop/screenshots/command-drawer/README.md b/apps/desktop/screenshots/command-drawer/README.md new file mode 100644 index 0000000000..67fadcd039 --- /dev/null +++ b/apps/desktop/screenshots/command-drawer/README.md @@ -0,0 +1,22 @@ +# Command drawer captures + +The current frames were captured from the native macOS app built at +`67bf7327a9cf211d4767b17384ec8b275a86a285`. The fixture runner uses synthetic +Setup reports and real embedded terminal sessions. It uses the built-in +terminal palette for capture. + +| State | Light | Dark | +| --- | --- | --- | +| h05 · Starting hackd | [Light](h05-hackd-running-light.png) | [Dark](h05-hackd-running-dark.png) | +| h08 · DNS needs attention | [Light](h08-dns-needs-action-light.png) | [Dark](h08-dns-needs-action-dark.png) | +| h10 · Waiting for a password | [Light](h10-dns-password-light.png) | [Dark](h10-dns-password-dark.png) | +| h11 · DNS command failed | [Light](h11-dns-failed-light.png) | [Dark](h11-dns-failed-dark.png) | +| h12 · Fresh DNS check passed | [Light](h12-dns-succeeded-light.png) | [Dark](h12-dns-succeeded-dark.png) | +| h13 · Closed drawer with failed history | [Light](h13-drawer-closed-last-run-light.png) | [Dark](h13-drawer-closed-last-run-dark.png) | +| h13 · Closed drawer with successful history | [Light](h13-successful-run-history-light.png) | [Dark](h13-successful-run-history-dark.png) | +| h26 · Drawer actions | [Light](h26-drawer-menu-light.png) | [Dark](h26-drawer-menu-dark.png) | + +The historical before frames show the pre-drawer Setup partial fixture at +`0dac496c13e574936241520c2fdaf75d3d4843a3`, first published with the drawer +evidence in `6111db778efad80a5cbe7900b0eba05c3ab786f1`. +[Light](before-setup-partial-light.png) · [Dark](before-setup-partial-dark.png) diff --git a/apps/desktop/screenshots/command-drawer/h05-hackd-running-dark.png b/apps/desktop/screenshots/command-drawer/h05-hackd-running-dark.png index a8a41f53fd..de23a3a60d 100644 Binary files a/apps/desktop/screenshots/command-drawer/h05-hackd-running-dark.png and b/apps/desktop/screenshots/command-drawer/h05-hackd-running-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h05-hackd-running-light.png b/apps/desktop/screenshots/command-drawer/h05-hackd-running-light.png index 4e54726377..d5f9cd7b8c 100644 Binary files a/apps/desktop/screenshots/command-drawer/h05-hackd-running-light.png and b/apps/desktop/screenshots/command-drawer/h05-hackd-running-light.png differ diff --git a/apps/desktop/screenshots/command-drawer/h08-dns-needs-action-dark.png b/apps/desktop/screenshots/command-drawer/h08-dns-needs-action-dark.png index 00cf8f4e3e..70111fd8c8 100644 Binary files a/apps/desktop/screenshots/command-drawer/h08-dns-needs-action-dark.png and b/apps/desktop/screenshots/command-drawer/h08-dns-needs-action-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h10-dns-password-dark.png b/apps/desktop/screenshots/command-drawer/h10-dns-password-dark.png index ad5d1baa0f..3c7cd921d2 100644 Binary files a/apps/desktop/screenshots/command-drawer/h10-dns-password-dark.png and b/apps/desktop/screenshots/command-drawer/h10-dns-password-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h10-dns-password-light.png b/apps/desktop/screenshots/command-drawer/h10-dns-password-light.png index 86df4a1edb..eece719e54 100644 Binary files a/apps/desktop/screenshots/command-drawer/h10-dns-password-light.png and b/apps/desktop/screenshots/command-drawer/h10-dns-password-light.png differ diff --git a/apps/desktop/screenshots/command-drawer/h11-dns-failed-dark.png b/apps/desktop/screenshots/command-drawer/h11-dns-failed-dark.png index c0d63f854d..afc2704c8b 100644 Binary files a/apps/desktop/screenshots/command-drawer/h11-dns-failed-dark.png and b/apps/desktop/screenshots/command-drawer/h11-dns-failed-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h11-dns-failed-light.png b/apps/desktop/screenshots/command-drawer/h11-dns-failed-light.png index a8fa7f22d1..66430e8613 100644 Binary files a/apps/desktop/screenshots/command-drawer/h11-dns-failed-light.png and b/apps/desktop/screenshots/command-drawer/h11-dns-failed-light.png differ diff --git a/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-dark.png b/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-dark.png index 832e4ff034..a636e139ad 100644 Binary files a/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-dark.png and b/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-light.png b/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-light.png index 7d197caa51..38d04b48bf 100644 Binary files a/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-light.png and b/apps/desktop/screenshots/command-drawer/h12-dns-succeeded-light.png differ diff --git a/apps/desktop/screenshots/command-drawer/h13-drawer-closed-last-run-dark.png b/apps/desktop/screenshots/command-drawer/h13-drawer-closed-last-run-dark.png index 1b2abc105c..25f5792063 100644 Binary files a/apps/desktop/screenshots/command-drawer/h13-drawer-closed-last-run-dark.png and b/apps/desktop/screenshots/command-drawer/h13-drawer-closed-last-run-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h13-successful-run-history-dark.png b/apps/desktop/screenshots/command-drawer/h13-successful-run-history-dark.png index 9f31be8481..0fba9672db 100644 Binary files a/apps/desktop/screenshots/command-drawer/h13-successful-run-history-dark.png and b/apps/desktop/screenshots/command-drawer/h13-successful-run-history-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h13-successful-run-history-light.png b/apps/desktop/screenshots/command-drawer/h13-successful-run-history-light.png index 8bf1640528..18f4a04866 100644 Binary files a/apps/desktop/screenshots/command-drawer/h13-successful-run-history-light.png and b/apps/desktop/screenshots/command-drawer/h13-successful-run-history-light.png differ diff --git a/apps/desktop/screenshots/command-drawer/h26-drawer-menu-dark.png b/apps/desktop/screenshots/command-drawer/h26-drawer-menu-dark.png index 2a991fd8e0..3997271626 100644 Binary files a/apps/desktop/screenshots/command-drawer/h26-drawer-menu-dark.png and b/apps/desktop/screenshots/command-drawer/h26-drawer-menu-dark.png differ diff --git a/apps/desktop/screenshots/command-drawer/h26-drawer-menu-light.png b/apps/desktop/screenshots/command-drawer/h26-drawer-menu-light.png index b5d82522ce..eb634e5a26 100644 Binary files a/apps/desktop/screenshots/command-drawer/h26-drawer-menu-light.png and b/apps/desktop/screenshots/command-drawer/h26-drawer-menu-light.png differ diff --git a/apps/desktop/screenshots/config/before-after-dark.png b/apps/desktop/screenshots/config/before-after-dark.png new file mode 100644 index 0000000000..e66684a3f8 Binary files /dev/null and b/apps/desktop/screenshots/config/before-after-dark.png differ diff --git a/apps/desktop/screenshots/config/before-after-light.png b/apps/desktop/screenshots/config/before-after-light.png new file mode 100644 index 0000000000..db4c0221e7 Binary files /dev/null and b/apps/desktop/screenshots/config/before-after-light.png differ diff --git a/apps/desktop/term/src/color.rs b/apps/desktop/term/src/color.rs index c827df99c8..73aafe61df 100644 --- a/apps/desktop/term/src/color.rs +++ b/apps/desktop/term/src/color.rs @@ -13,6 +13,10 @@ impl Rgb { Self { r, g, b } } + pub const fn from_u32(hex: u32) -> Self { + Self::new((hex >> 16) as u8, (hex >> 8) as u8, hex as u8) + } + /// `0xRRGGBB`. pub fn to_u32(self) -> u32 { (u32::from(self.r) << 16) | (u32::from(self.g) << 8) | u32::from(self.b) diff --git a/apps/desktop/term/src/emulator.rs b/apps/desktop/term/src/emulator.rs index be17599562..f30f6f8b28 100644 --- a/apps/desktop/term/src/emulator.rs +++ b/apps/desktop/term/src/emulator.rs @@ -46,7 +46,9 @@ pub struct TermTheme { pub foreground: Rgb, pub background: Rgb, pub cursor: Rgb, + pub cursor_fg: Option, pub selection_bg: Rgb, + pub selection_fg: Option, pub match_bg: Rgb, pub active_match_bg: Rgb, /// ANSI colours 0-15 (programs may still override them with OSC 4). @@ -54,37 +56,42 @@ pub struct TermTheme { } impl TermTheme { + /// Built-in Merino Dark terminal colors, before user Ghostty overrides. pub const DARK: Self = Self { - foreground: Rgb::new(0xd8, 0xdb, 0xe2), - background: Rgb::new(0x16, 0x18, 0x1d), - cursor: Rgb::new(0xd8, 0xdb, 0xe2), - selection_bg: Rgb::new(0x34, 0x4a, 0x6e), - match_bg: Rgb::new(0x5a, 0x4b, 0x1f), - active_match_bg: Rgb::new(0x9a, 0x6b, 0x10), + foreground: Rgb::from_u32(0xE6EDF3), + background: Rgb::from_u32(0x0D1117), + cursor: Rgb::from_u32(0x2F81F7), + cursor_fg: Some(Rgb::from_u32(0xEFF8FF)), + selection_bg: Rgb::from_u32(0xE6EDF3), + selection_fg: Some(Rgb::from_u32(0x0D1117)), + match_bg: Rgb::from_u32(0x5A4B1F), + active_match_bg: Rgb::from_u32(0x9A6B10), ansi: [ - Rgb::new(0x2a, 0x2e, 0x36), - Rgb::new(0xf0, 0x6b, 0x6b), - Rgb::new(0x8f, 0xd1, 0x7f), - Rgb::new(0xe8, 0xc2, 0x6a), - Rgb::new(0x6f, 0xa8, 0xf5), - Rgb::new(0xc6, 0x8c, 0xf0), - Rgb::new(0x5f, 0xc8, 0xd1), - Rgb::new(0xc8, 0xcc, 0xd4), - Rgb::new(0x6b, 0x72, 0x80), - Rgb::new(0xff, 0x8a, 0x8a), - Rgb::new(0xa8, 0xe0, 0x98), - Rgb::new(0xf2, 0xd4, 0x8a), - Rgb::new(0x93, 0xbf, 0xff), - Rgb::new(0xd8, 0xa8, 0xff), - Rgb::new(0x86, 0xdc, 0xe3), - Rgb::new(0xf3, 0xf4, 0xf6), + Rgb::from_u32(0x484F58), + Rgb::from_u32(0xFF7B72), + Rgb::from_u32(0x3FB950), + Rgb::from_u32(0xD29922), + Rgb::from_u32(0x58A6FF), + Rgb::from_u32(0xBC8CFF), + Rgb::from_u32(0x39C5CF), + Rgb::from_u32(0xB1BAC4), + Rgb::from_u32(0x6E7681), + Rgb::from_u32(0xFFA198), + Rgb::from_u32(0x56D364), + Rgb::from_u32(0xE3B341), + Rgb::from_u32(0x79C0FF), + Rgb::from_u32(0xD2A8FF), + Rgb::from_u32(0x56D4DD), + Rgb::from_u32(0xFFFFFF), ], }; pub const LIGHT: Self = Self { foreground: Rgb::new(0x1f, 0x23, 0x28), background: Rgb::new(0xfb, 0xfb, 0xfc), cursor: Rgb::new(0x1f, 0x23, 0x28), + cursor_fg: None, selection_bg: Rgb::new(0xc5, 0xd9, 0xf7), + selection_fg: None, match_bg: Rgb::new(0xfb, 0xe6, 0xa2), active_match_bg: Rgb::new(0xf5, 0xb9, 0x42), ansi: [ diff --git a/apps/desktop/term/src/ghostty_config.rs b/apps/desktop/term/src/ghostty_config.rs index 9cf543d180..f1e4211b97 100644 --- a/apps/desktop/term/src/ghostty_config.rs +++ b/apps/desktop/term/src/ghostty_config.rs @@ -164,6 +164,10 @@ pub struct GhosttyLook { pub font_size_pt: Option, pub background: Option, pub foreground: Option, + pub cursor_color: Option, + pub cursor_text: Option, + pub selection_background: Option, + pub selection_foreground: Option, /// Palette entries the config sets, by index 0 to 255. pub palette: BTreeMap, pub cursor_style: Option, @@ -221,6 +225,10 @@ struct Raw { font_size_pt: Option>, background: Option>, foreground: Option>, + cursor_color: Option>, + cursor_text: Option>, + selection_background: Option>, + selection_foreground: Option>, /// An empty `palette =` was seen: drop every entry from before it, /// including a theme's. `palette` holds the entries set after it. palette_reset: bool, @@ -245,6 +253,18 @@ impl Raw { if let Some(v) = self.foreground { look.foreground = v; } + if let Some(v) = self.cursor_color { + look.cursor_color = v; + } + if let Some(v) = self.cursor_text { + look.cursor_text = v; + } + if let Some(v) = self.selection_background { + look.selection_background = v; + } + if let Some(v) = self.selection_foreground { + look.selection_foreground = v; + } if self.palette_reset { look.palette.clear(); } @@ -282,6 +302,10 @@ impl Raw { } "background" => set_color(&mut self.background, value), "foreground" => set_color(&mut self.foreground, value), + "cursor-color" => set_color(&mut self.cursor_color, value), + "cursor-text" => set_color(&mut self.cursor_text, value), + "selection-background" => set_color(&mut self.selection_background, value), + "selection-foreground" => set_color(&mut self.selection_foreground, value), "palette" if empty => { self.palette_reset = true; self.palette.clear(); @@ -712,12 +736,14 @@ not a setting line let (_home, env) = fixture(&[ ( ".config/ghostty/config", - "theme = My Theme\nforeground = #ffffff\npalette = 1=#ff0000\n", + "theme = My Theme\nforeground = #ffffff\npalette = 1=#ff0000\n\ + cursor-color = #123456\nselection-background = #abcdef\nselection-foreground =\n", ), ( ".config/ghostty/themes/My Theme", "background = #101010\nforeground = #c0c0c0\npalette = 1=#aa0000\n\ - palette = 2=#00aa00\ncursor-style = underline\n\ + palette = 2=#00aa00\ncursor-style = underline\ncursor-color = #aa4400\n\ + cursor-text = #eeddcc\nselection-background = #111111\nselection-foreground = #cccccc\n\ theme = Other\nconfig-file = ../config-evil\n", ), (".config/ghostty/config-evil", "font-size = 99\n"), @@ -727,6 +753,10 @@ not a setting line assert_eq!(look.foreground, Some(rgb("ffffff")), "the user's wins"); assert_eq!(look.palette[&1], rgb("ff0000"), "the user's wins"); assert_eq!(look.palette[&2], rgb("00aa00"), "from the theme"); + assert_eq!(look.cursor_color, Some(rgb("123456"))); + assert_eq!(look.cursor_text, Some(rgb("eeddcc"))); + assert_eq!(look.selection_background, Some(rgb("abcdef"))); + assert_eq!(look.selection_foreground, None); assert_eq!(look.cursor_style, Some(CursorShape::Underline)); assert_eq!(look.font_size_pt, None, "a theme cannot include files"); } diff --git a/apps/desktop/term/src/view.rs b/apps/desktop/term/src/view.rs index a270cb08f9..af40a4283a 100644 --- a/apps/desktop/term/src/view.rs +++ b/apps/desktop/term/src/view.rs @@ -742,27 +742,18 @@ impl TerminalView { /// theme for the rest. fn sync_theme(&mut self, cx: &App) { let t = cx.theme(); - let mut theme = TermTheme { - foreground: rgb_of(t.foreground), - background: rgb_of(t.background), - cursor: rgb_of(t.foreground), - selection_bg: rgb_of(t.selection), - ..if t.is_dark() { - TermTheme::DARK - } else { - TermTheme::LIGHT + let fallback = if t.is_dark() { + TermTheme::DARK + } else { + TermTheme { + foreground: rgb_of(t.foreground), + background: rgb_of(t.background), + cursor: rgb_of(t.foreground), + selection_bg: rgb_of(t.selection), + ..TermTheme::LIGHT } }; - if let Some(fg) = self.look.foreground { - theme.foreground = fg; - theme.cursor = fg; - } - if let Some(bg) = self.look.background { - theme.background = bg; - } - for (index, color) in self.look.palette.range(..16) { - theme.ansi[usize::from(*index)] = *color; - } + let theme = apply_ghostty_colors(fallback, &self.look); if self.applied_theme != Some(theme) || self.look_pending { let extra: Vec<(u8, Rgb)> = self .look @@ -851,6 +842,62 @@ impl TerminalView { } } +fn apply_ghostty_colors(mut theme: TermTheme, look: &GhosttyLook) -> TermTheme { + if let Some(fg) = look.foreground { + theme.foreground = fg; + // Keep the inherited foreground cursor for configs that set only + // foreground. An explicit cursor color takes precedence below. + theme.cursor = fg; + theme.cursor_fg = None; + } + if let Some(bg) = look.background { + theme.background = bg; + } + if let Some(color) = look.cursor_color { + theme.cursor = color; + } + theme.cursor_fg = look.cursor_text.or(theme.cursor_fg); + if let Some(bg) = look.selection_background { + theme.selection_bg = bg; + } + theme.selection_fg = look.selection_foreground.or(theme.selection_fg); + for (index, color) in look.palette.range(..16) { + theme.ansi[usize::from(*index)] = *color; + } + theme +} + +#[cfg(test)] +mod appearance_tests { + use super::*; + + #[test] + fn ghostty_colors_override_merino_per_setting() { + let dark = TermTheme::DARK; + assert_eq!(apply_ghostty_colors(dark, &GhosttyLook::default()), dark); + + let look = GhosttyLook { + background: Some(Rgb::from_u32(0x171717)), + foreground: Some(Rgb::from_u32(0xFAFAFA)), + cursor_color: Some(Rgb::from_u32(0xFFFF00)), + cursor_text: Some(Rgb::from_u32(0x222222)), + selection_background: Some(Rgb::from_u32(0x335577)), + selection_foreground: Some(Rgb::from_u32(0xFFFFFF)), + palette: [(1, Rgb::from_u32(0xFF2222)), (100, Rgb::from_u32(0x332211))].into(), + ..Default::default() + }; + let theme = apply_ghostty_colors(dark, &look); + assert_eq!(Some(theme.background), look.background); + assert_eq!(Some(theme.foreground), look.foreground); + assert_eq!(Some(theme.cursor), look.cursor_color); + assert_eq!(theme.cursor_fg, look.cursor_text); + assert_eq!(Some(theme.selection_bg), look.selection_background); + assert_eq!(theme.selection_fg, look.selection_foreground); + assert_eq!(theme.ansi[1], look.palette[&1]); + assert_eq!(theme.ansi[2..], dark.ansi[2..]); + } +} + fn rgb_of(h: Hsla) -> Rgb { let c = h.to_rgb(); let q = |v: f32| (v.clamp(0., 1.) * 255.).round() as u8; @@ -1264,10 +1311,6 @@ fn paint_frame(a: &PaintArgs<'_>, window: &mut Window, cx: &mut App) { let n = u16::try_from(x - start).unwrap_or(u16::MAX); window.paint_quad(fill(rect(start as u16, y, n), hsla(bg))); } - if let Some(Some((s, e))) = a.frame.selection.get(y) { - let sel = hsla(a.theme.selection_bg).opacity(0.45); - window.paint_quad(fill(rect(*s, y, e - s + 1), sel)); - } } for &(row, s, e, active) in &a.frame.matches { let c = if active { @@ -1280,8 +1323,19 @@ fn paint_frame(a: &PaintArgs<'_>, window: &mut Window, cx: &mut App) { hsla(c).opacity(0.9), )); } - // A block cursor covers its cell, so the glyph under it is drawn in the - // background colour. Bar, underline and hollow cursors leave it as is. + // Keep selected glyphs paired with their selection background even + // when a Find highlight crosses the selection. + let mut selection = hsla(a.theme.selection_bg); + if a.theme.selection_fg.is_none() { + selection = selection.opacity(0.45); + } + for (row, span) in a.frame.selection.iter().enumerate() { + if let Some((start, end)) = span { + window.paint_quad(fill(rect(*start, row, end - start + 1), selection)); + } + } + // A block cursor covers its cell. Bar, underline and hollow cursors + // leave the lettering as it is. let shape = a.frame.cursor_shape.unwrap_or(CursorShape::Block); let block_cursor = a.show_cursor && a.focused && shape == CursorShape::Block; if let Some((cx_, cy)) = a.frame.cursor.filter(|_| a.show_cursor) { @@ -1310,6 +1364,19 @@ fn paint_frame(a: &PaintArgs<'_>, window: &mut Window, cx: &mut App) { } } + let glyph_fg = |x: usize, y: usize, fg: Rgb| { + let col = x as u16; + if block_cursor && a.frame.cursor == Some((col, y as u16)) { + return a.theme.cursor_fg.unwrap_or(a.frame.background); + } + if let Some(selection_fg) = a.theme.selection_fg + && let Some(Some((start, end))) = a.frame.selection.get(y) + && (*start..=*end).contains(&col) + { + return selection_fg; + } + fg + }; let ts = window.text_system().clone(); for (y, row) in a.frame.rows.iter().enumerate() { let mut x = 0usize; @@ -1320,8 +1387,7 @@ fn paint_frame(a: &PaintArgs<'_>, window: &mut Window, cx: &mut App) { } if let Some(kind) = special(&row[x]) { let c = &row[x]; - let on_cursor = block_cursor && a.frame.cursor == Some((x as u16, y as u16)); - let mut color = hsla(if on_cursor { a.frame.background } else { c.fg }); + let mut color = hsla(glyph_fg(x, y, c.fg)); if c.faint { color = color.opacity(0.6); } @@ -1352,9 +1418,7 @@ fn paint_frame(a: &PaintArgs<'_>, window: &mut Window, cx: &mut App) { } else { c.text.as_str() }; - let on_cursor = block_cursor && a.frame.cursor == Some((x as u16, y as u16)); - let fg = if on_cursor { a.frame.background } else { c.fg }; - let mut color = hsla(fg); + let mut color = hsla(glyph_fg(x, y, c.fg)); if c.faint { color = color.opacity(0.6); } diff --git a/apps/desktop/term/tests/render.rs b/apps/desktop/term/tests/render.rs index 3834263dd8..7eda781f64 100644 --- a/apps/desktop/term/tests/render.rs +++ b/apps/desktop/term/tests/render.rs @@ -34,6 +34,10 @@ fn main() { "pretty_logs_keep_the_clis_colours_and_styles", pretty_logs_keep_the_clis_colours_and_styles, ), + ( + "selection_background_covers_find_highlights", + selection_background_covers_find_highlights, + ), ]); } @@ -114,10 +118,12 @@ use std::sync::Arc; use std::time::Duration; use common::{TempHome, sh_source}; +use gpui_kit::component::{Theme, ThemeMode}; use gpui_kit::test::TestWindowExt as _; use gpui_kit::{ AppContext as _, Bounds, HeadlessAppContext, WindowBounds, WindowOptions, px, size, }; +use hack_desktop_term::emulator::TermTheme; use hack_desktop_term::glyphs::{self, BundledSymbols}; use hack_desktop_term::stream::StreamSource; use hack_desktop_term::view::{GridMetrics, TermFont, TerminalView}; @@ -283,6 +289,16 @@ fn capture_sized( font: Option, dump: &str, (width, height): (f32, f32), +) -> Option { + capture_with_view(text, font, dump, (width, height), |_, _| {}) +} + +fn capture_with_view( + text: &str, + font: Option, + dump: &str, + (width, height): (f32, f32), + prepare: impl FnOnce(&mut TerminalView, &mut gpui_kit::Context), ) -> Option { let required = std::env::var_os("HACK_TERM_REQUIRE_RENDERER").is_some_and(|v| v == "1"); let home = TempHome::new(); @@ -323,6 +339,7 @@ fn capture_sized( cx.update(|cx| { view.update(cx, |v, cx| { v.settle(Duration::from_millis(100), Duration::from_secs(20), cx); + prepare(v, cx); }); }); cx.update_window(window, |_, w, cx| w.render_frame(cx)) @@ -359,6 +376,37 @@ fn capture_sized( }) } +fn selection_background_covers_find_highlights() { + let Some(shot) = capture_with_view( + " MMMM MMMM\n", + None, + "selection-and-find.png", + (560., 120.), + |view, cx| { + Theme::change(ThemeMode::Dark, None, cx); + assert_eq!(view.search("MMMM", cx).total, 2); + view.emulator().select_start(1, 0); + view.emulator().select_to(4, 0); + cx.notify(); + }, + ) else { + return; + }; + assert_eq!(shot.frame.matches.len(), 2, "both matches are visible"); + assert_eq!(shot.frame.selection[0], Some((1, 4))); + let color = TermTheme::DARK.selection_bg; + let selected = [color.r, color.g, color.b]; + let overlap = shot.cells(1, 0, 4).all_ink(selected); + assert!( + (0.01..0.5).contains(&overlap), + "selected text should have visible ink on the selection background ({overlap})" + ); + assert!( + shot.cells(7, 0, 4).all_ink(shot.background()) > 0.8, + "the unselected match should retain its Find highlight" + ); +} + /// How a sample is expected to be drawn. #[derive(Clone, Copy, PartialEq)] enum Drawn { diff --git a/apps/desktop/ui/src/bin/gallery.rs b/apps/desktop/ui/src/bin/gallery.rs index 4aeed51ce0..e2ea0e9bf4 100644 --- a/apps/desktop/ui/src/bin/gallery.rs +++ b/apps/desktop/ui/src/bin/gallery.rs @@ -246,7 +246,7 @@ fn main() { gpui_kit::application() .with_assets(hack_desktop_ui::icons::Assets) .run(move |cx| { - gpui_kit::init(cx); + hack_desktop_ui::tokens::init(cx); gpui_kit::open_window(window_options(), cx, move |window, cx| { Theme::change(theme_mode(mode), Some(window), cx); let font = nerd_font(cx); @@ -280,7 +280,7 @@ mod screenshots { Arc::new(hack_desktop_ui::icons::Assets), gpui_kit::platform::current_headless_renderer, ); - cx.update(gpui_kit::init); + cx.update(hack_desktop_ui::tokens::init); let font = cx.update(|cx| super::nerd_font(cx)); for mode in [Mode::Light, Mode::Dark] { for scene in super::scenes() { diff --git a/apps/desktop/ui/src/components.rs b/apps/desktop/ui/src/components.rs index 6e90753ab5..8458007bec 100644 --- a/apps/desktop/ui/src/components.rs +++ b/apps/desktop/ui/src/components.rs @@ -401,7 +401,7 @@ pub fn title_bar(show_traffic_lights: bool, ui: &Ui) -> Div { .flex_none() .flex() .items_center() - .bg(p.chrome) + .bg(p.title_bar()) .hairline_b(p.border) .child(lights) .child( diff --git a/apps/desktop/ui/src/tokens.rs b/apps/desktop/ui/src/tokens.rs index c984518249..2e0b84264e 100644 --- a/apps/desktop/ui/src/tokens.rs +++ b/apps/desktop/ui/src/tokens.rs @@ -1,10 +1,12 @@ //! Design v1 tokens: type, spacing, radii, borders and colour, light and dark. //! //! Every value here is named in `apps/desktop/DESIGN-V1.md`; change both -//! together. Components read tokens, never raw numbers or gpui-kit theme -//! colours, so the window keeps one look whatever gpui-kit's defaults are. +//! together. The dark palette also supplies gpui-kit's native components. -use gpui_kit::{Hsla, Pixels, Rgba, px, rgb, rgba}; +use std::rc::Rc; + +use gpui_kit::component::{Theme, ThemeMode}; +use gpui_kit::{App, Hsla, Pixels, Rgba, SharedString, px, rgb, rgba}; /// Light or dark. The app follows the system unless `--theme` says otherwise. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -102,10 +104,13 @@ pub const HAIRLINE: Pixels = px(0.5); #[derive(Debug, Clone, Copy)] pub struct Palette { pub mode: Mode, - /// Window and detail pane. + pub window: Hsla, + /// Cards and detail pane. pub surface: Hsla, - /// Sidebar, title bar and status bar. + /// Sidebar and status bar. pub chrome: Hsla, + pub raised: Hsla, + pub attention: Hsla, /// Hover, log block, neutral pills. pub surface_1: Hsla, /// Pressed. @@ -146,6 +151,14 @@ fn c(v: Rgba) -> Hsla { } impl Palette { + #[must_use] + pub fn title_bar(self) -> Hsla { + match self.mode { + Mode::Light => self.chrome, + Mode::Dark => self.window, + } + } + #[must_use] pub fn for_mode(mode: Mode) -> Self { match mode { @@ -197,11 +210,14 @@ impl Palette { pub fn light() -> Self { Self { mode: Mode::Light, + window: c(rgb(0xFFFFFF)), surface: c(rgb(0xFFFFFF)), chrome: c(rgb(0xF7F7F5)), + raised: c(rgb(0xEFEFEC)), + selection: c(rgb(0xEFEFEC)), + attention: c(rgb(0xEFEFEC)), surface_1: c(rgb(0xEFEFEC)), surface_2: c(rgb(0xE6E6E2)), - selection: c(rgb(0xEFEFEC)), preview_surface: c(rgb(0xEFEFEC)), border: c(rgba(0x0000_0017)), border_strong: c(rgba(0x0000_002E)), @@ -253,8 +269,11 @@ impl Palette { let text_muted = c(rgb(0x8B9197)); Self { mode: Mode::Dark, + window: c(rgb(0x090C10)), surface: c(rgb(0x0D1117)), - chrome: c(rgb(0x090C10)), + chrome: c(rgb(0x06080A)), + raised: c(rgb(0x1C2026)), + attention: c(rgb(0x21252B)), surface_1, surface_2: c(rgb(0x1C2026)), selection, @@ -301,9 +320,69 @@ impl Palette { } } -/// Fallback terminal theme, used when the user has no Ghostty config. The -/// panel is dark in both app modes (as in the approved mockup); a Ghostty -/// theme replaces every value here. +/// Initialize GPUI with the desktop app's dark palette for native components. +pub fn init(cx: &mut App) { + gpui_kit::init(cx); + + fn hex(color: Hsla) -> Option { + let color = color.to_rgb(); + let byte = |value: f32| (value * 255.).round() as u8; + Some( + format!( + "#{:02x}{:02x}{:02x}", + byte(color.r), + byte(color.g), + byte(color.b) + ) + .into(), + ) + } + + let p = Palette::dark(); + let mut config = Theme::global(cx).dark_theme.as_ref().clone(); + config.name = "Merino Dark".into(); + let colors = &mut config.colors; + colors.background = hex(p.window); + colors.foreground = hex(p.text_primary); + colors.title_bar = hex(p.title_bar()); + colors.title_bar_border = hex(p.border); + colors.status_bar = hex(p.chrome); + colors.status_bar_border = hex(p.border); + colors.window_border = hex(p.border); + colors.border = hex(p.border); + colors.input = hex(p.border); + colors.caret = hex(p.accent); + colors.ring = hex(p.accent); + colors.selection = hex(p.selection); + colors.list_active = hex(p.selection); + colors.list_active_border = hex(p.border); + colors.list_hover = hex(p.surface_1); + colors.muted = hex(p.surface_1); + colors.muted_foreground = hex(p.text_muted); + colors.popover = hex(p.raised); + colors.popover_foreground = hex(p.text_primary); + colors.primary = hex(p.accent); + colors.primary_foreground = hex(p.surface); + colors.primary_hover = hex(p.text_secondary); + colors.primary_active = hex(p.text_muted); + colors.accent = hex(p.surface_1); + colors.accent_foreground = hex(p.text_primary); + colors.secondary = hex(p.surface); + colors.secondary_foreground = hex(p.text_secondary); + colors.secondary_hover = hex(p.surface_1); + colors.secondary_active = hex(p.surface_2); + colors.danger = hex(p.states.failed.dot); + colors.danger_foreground = hex(p.surface); + colors.scrollbar_thumb = hex(p.border); + colors.scrollbar_thumb_hover = hex(p.text_muted); + Theme::global_mut(cx).dark_theme = Rc::new(config); + if Theme::global(cx).is_dark() { + Theme::change(ThemeMode::Dark, None, cx); + } +} + +/// Terminal panel chrome and the gallery's sample terminal colors. The live +/// grid uses its own palette, including any user Ghostty overrides. #[derive(Debug, Clone, Copy)] pub struct TermPalette { pub bg: Hsla, @@ -330,7 +409,30 @@ pub struct TermPalette { impl TermPalette { #[must_use] - pub fn fallback() -> Self { + pub fn for_mode(mode: Mode) -> Self { + if mode == Mode::Dark { + let p = Palette::dark(); + return Self { + bg: p.surface, + fg: p.text_primary, + dim: p.text_muted, + strip: p.raised, + strip_border: p.border, + tab_fg: p.text_secondary, + green: p.states.running.fg, + bright_green: c(rgb(0x56D364)), + blue: c(rgb(0x58A6FF)), + magenta: c(rgb(0xBC8CFF)), + yellow: p.states.degraded.fg, + red: p.states.failed.fg, + cyan: c(rgb(0x39C5CF)), + cursor: c(rgb(0x2F81F7)), + badge_warn_bg: p.states.degraded.bg, + badge_warn_fg: p.states.degraded.fg, + badge_bg: p.surface_1, + badge_fg: p.text_secondary, + }; + } Self { bg: c(rgb(0x1C1C1A)), fg: c(rgb(0xE8E6DC)), diff --git a/apps/desktop/ui/src/window.rs b/apps/desktop/ui/src/window.rs index 2f7750547a..dd71ffb4f2 100644 --- a/apps/desktop/ui/src/window.rs +++ b/apps/desktop/ui/src/window.rs @@ -486,7 +486,7 @@ impl MainWindow { .is_some_and(|t| *t != TabKind::Logs), menu: self.panel_menu.then(|| new_tab_menu(d)), font: self.term_font.clone().unwrap_or_else(|| ui.mono.clone()), - term: TermPalette::fallback(), + term: TermPalette::for_mode(ui.p.mode), }; div() .flex_1() diff --git a/docs/cli.md b/docs/cli.md index 1248ce7770..8127267be0 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -228,9 +228,12 @@ Historical remote guides are excluded from the supported documentation. - `tui` without a terminal refuses for that reason first. - `env get` never prints a failure reason, since its output is raw values: it prints one fixed line on stderr, with or without `--json`. - - `config validate`, `plan`, `import` and `adopt` read native configuration and keep their own - refusals: `E_NATIVE_PROJECT_UNSUPPORTED` for `validate`/`plan`, a refused preview for - `import --dry-run`, and `E_CONFIG_INVALID` for `adopt`. + - `config show --json` reports `state: "missing"` in a success envelope. `config validate` and + `config apply` in Compose patch mode return `E_CONFLICT` for a missing checkout. Patch mode + requires `--json` and a patch on stdin. For validation, omit `--file`, `--profile` and `--domain`. + - `config validate` in file validation mode and `config plan` return + `E_NATIVE_PROJECT_UNSUPPORTED`. `config import --dry-run` returns a refused preview and + `config adopt` returns `E_CONFIG_INVALID`. - `init`, `doctor`, `crash-capture`, and the `setup`, `mcp` and `agent` commands do not need a project. diff --git a/docs/env.md b/docs/env.md index 6764f88a62..a3301581de 100644 --- a/docs/env.md +++ b/docs/env.md @@ -573,7 +573,9 @@ into a host command, and `--target` on env and host commands chooses the `host` | `hack env shell` | `--env`, `--service`, `--target` | When the shell starts. | Start a new shell. | Runs on the host, not in a container. | | `hack host exec` | `--env`, `--scope`, `--target` | Per invocation, into one host command (host view by default). | Each invocation resolves again. | Runs on the host, not in a container. | | `hack host shell` | `--env`, `--scope`, `--target` | When the shell starts. | Start a new shell. | Runs on the host, not in a container. | -| `hack config validate` | `--env` | Per invocation; resolves the native selection without reading managed env documents. | Not needed. | Authored native projects only; cannot be combined with `--file`. | +| `hack config show` | `--env` | Reads the selected Compose checkout's layers and winning values. Secrets are shown as markers. | Rerun to read current files. | Compose projects. Requires `--json`. No runtime required. | +| `hack config validate` | `--env` | Checks a Compose patch on stdin against the selected layers without decrypting env secrets. Patch mode requires `--json` and omits `--file`, `--profile` and `--domain`. | Not needed. | Native validation with `--env` resolves the selection without reading managed env documents. It requires an authored project and cannot be combined with `--file`. | +| `hack config apply` | `--env` | Checks and writes the Compose patch against the selected layers. | Env edits take effect the next time services start. | Compose projects. Requires `--json` and a patch on stdin. Does not restart services. | | `hack config plan` | `--env` | Per invocation; metadata only (names, scopes, secret flags), never decrypted. | Not needed. | Authored native projects only. | | `hack project target` | `--env`, `--service` | Per invocation, read-only; reports the overlay selection (explicit, project default or base) without reading env files or values. | Not needed. | Selection only: overlay existence is not checked; no runtime required. | | `hack project task list` | `--env` | Per invocation, read-only; selects the overlay that each recipe's reviewed env scope is compared with, without reading env files or values. | Not needed. | Selection only; lists recipes and runs nothing, so no runtime is required. | diff --git a/docs/reference/cli.md b/docs/reference/cli.md index cc7ad114e8..52f01ead2b 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -1121,7 +1121,9 @@ hack config [options] | --- | --- | | `hack config get ` | Read a value from hack.config.json | | `hack config set ` | Update a value in hack.config.json | +| `hack config show` | Show Compose project config, layers, routes and env provenance | | `hack config validate` | Validate project configuration without starting workloads | +| `hack config apply` | Apply a validated Compose project config patch from stdin | | `hack config plan` | Inspect native environment binding completeness without decrypting or starting workloads | | `hack config import` | Preview a bounded legacy config and Compose conversion without writes | | `hack config adopt` | Explicitly adopt a stopped, verified existing Compose instance | @@ -1189,6 +1191,28 @@ hack config set [options] | `--help, -h` | Show help | | `--version, -v` | Show version | +## `hack config show` + +Show Compose project config, layers, routes and env provenance + +### Usage + +```bash +hack config show [options] +``` + +### Options + +| Option | Description | +| --- | --- | +| `--path, -p ` | Run a project command against a repo path (overrides cwd search) | +| `--branch ` | Run against a branch-specific instance (compose name + hostnames) | +| `--env ` | Select an env overlay by name, or use 'base' or 'default' for base layers only; omitted selection follows the command's documented behavior | +| `--json` | Output JSON (machine-readable) | +| `--no-interactive` | Never prompt: apply documented defaults or fail with E_INTERACTIVE_REQUIRED (also via HACK_NO_INTERACTIVE=1) | +| `--help, -h` | Show help | +| `--version, -v` | Show version | + ## `hack config validate` Validate project configuration without starting workloads @@ -1199,7 +1223,7 @@ Validate project configuration without starting workloads hack config validate [options] ``` -Uses the matching bundled Rust compiler. Without --file, discovers a Compose or native project. Native validation resolves permitted worktree-local overlay and routing settings. --file validates only the explicit document. With HACK_RUNTIME_BACKEND=native, a selected workload image that is not a sha256: content ID refuses with the native consumer's native_graph_admission code. Neither mode reads env values, writes state, or starts workloads. +Reads a Compose config patch on stdin with --json when --file, --profile and --domain are omitted. Otherwise checks the on-disk configuration, using the matching bundled Rust compiler for native projects. Without --file, discovers a Compose or native project. Native validation resolves permitted worktree-local overlay and routing settings. --file validates only the explicit document. With HACK_RUNTIME_BACKEND=native, a selected workload image that is not a sha256: content ID refuses with the native consumer's native_graph_admission code. Neither mode decrypts env secrets, writes state, or starts workloads. ### Options @@ -1209,6 +1233,29 @@ Uses the matching bundled Rust compiler. Without --file, discovers a Compose or | `--profile ` | Comma-separated declared native profiles | | `--domain ` | Select the generated native routing domain suffix | | `--path, -p ` | Run a project command against a repo path (overrides cwd search) | +| `--branch ` | Run against a branch-specific instance (compose name + hostnames) | +| `--env ` | Select an env overlay by name, or use 'base' or 'default' for base layers only; omitted selection follows the command's documented behavior | +| `--json` | Output JSON (machine-readable) | +| `--no-interactive` | Never prompt: apply documented defaults or fail with E_INTERACTIVE_REQUIRED (also via HACK_NO_INTERACTIVE=1) | +| `--help, -h` | Show help | +| `--version, -v` | Show version | + +## `hack config apply` + +Apply a validated Compose project config patch from stdin + +### Usage + +```bash +hack config apply [options] +``` + +### Options + +| Option | Description | +| --- | --- | +| `--path, -p ` | Run a project command against a repo path (overrides cwd search) | +| `--branch ` | Run against a branch-specific instance (compose name + hostnames) | | `--env ` | Select an env overlay by name, or use 'base' or 'default' for base layers only; omitted selection follows the command's documented behavior | | `--json` | Output JSON (machine-readable) | | `--no-interactive` | Never prompt: apply documented defaults or fail with E_INTERACTIVE_REQUIRED (also via HACK_NO_INTERACTIVE=1) | diff --git a/docs/reference/machine-readable-output.md b/docs/reference/machine-readable-output.md index 45b72452b3..3939d4b759 100644 --- a/docs/reference/machine-readable-output.md +++ b/docs/reference/machine-readable-output.md @@ -83,9 +83,11 @@ success behavior stays covered by command-specific suites. | `hack commands read --json` | NDJSON events / terminal event, not a single envelope | | `hack commands show --json` | Envelope (`ok`, `data` / `error`); legacy payload has no required schema | | `hack config adopt --json` | Legacy bare object (no `data` envelope) | +| `hack config apply --json` | Envelope; versioned `data.schema`: `hack.config.v1` | | `hack config import --json` | Legacy bare object (no `data` envelope) | | `hack config plan --json` | Native compiler protocol object (`transport_version`, `ok`, result / diagnostics) | -| `hack config validate --json` | Native compiler protocol object (`transport_version`, `ok`, result / diagnostics) | +| `hack config show --json` | Envelope; versioned `data.schema`: `hack.config.v1` | +| `hack config validate --json` | Envelope with `data.schema: hack.config.v1` for a Compose patch on stdin when `--file`, `--profile` and `--domain` are omitted. Otherwise a file validation object with `transport_version` | | `hack daemon install --json` | Envelope; versioned `data.schema`: `hack.daemon-install.v1` | | `hack daemon restart --json` | Envelope; versioned `data.schema`: `hack.daemon-restart.v1` | | `hack daemon start --json` | Envelope; versioned `data.schema`: `hack.daemon-start.v1` | @@ -181,6 +183,80 @@ success behavior stays covered by command-specific suites. | `hack doctor --json --machine` | Envelope; `data.schema: hack.doctor.machine.v1` | +## Compose Config patches + +`hack config show --json [--path ] [--branch ] [--env ]` +reads one Compose checkout and overlay without starting a runtime. Omit +`--env` to use the configured default. Use `--env default` for base layers. +A branch name matching a linked worktree selects that checkout. A branch +instance without its own worktree resolves against the requested checkout. + +The payload contains `project`, `services`, `env`, `layers`, `issues` and +`state` (`ready`, `invalid` or `missing`). Every layer has an `id`, path, +kind, ownership, writability and a revision. The base files use IDs `1` +through `6`. Named env overlays use IDs such as `3:qa`, `4:qa` and +`5:qa`. Route `from` and env `winning` fields reference those IDs. +Env rows identify the stored scope. To resolve a service, use layers in +the reported order and apply global before the service within each layer. +Explicit unsets remove earlier values. The host scope applies only to host +commands. Secure entries are emitted as markers. Source can be redacted +or withheld. Use the Env layers grid or the existing env writer to edit +env values. + +The default overlay uses the same names as `--env`. Use `default` to select +base layers. `default_overlay` reports the resolved project default, including +legacy keys, independently of the selected `overlay`. It is `"default"` for +base layers and `"[redacted]"` when the authored value contains credentials. +A missing checkout or malformed project settings report `null`. A failure +to read the file returns an `E_PERMISSION` error envelope. +When an existing env layer or legacy dotenv filename was derived from a private +setting, move or rename that file before replacing the setting in Config. +If a legacy encrypted store could still supply the overlay, migrate the env +before replacing the setting. +During implicit migration, affected private overlays use `3:[redacted]` or +`5:[redacted]` in `changed`. Migration diagnostics redact known private overlay +names. +Config honors the env migration journal for the selected checkout and any +inherited layers. On the first env write to a project +with a legacy contract, apply migrates that contract through the same +path as `hack env add`. Validation checks the patch against declared legacy +dotenv inputs and project settings without decrypting the legacy store. Apply +checks the complete migration and records the patch's file revisions in the +migration journal so rollback can restore the original files and remove newly +created layers. + +Pass the same checkout and overlay flags to `config validate --json` and +`config apply --json`. Omit `--file`, `--profile` and `--domain` when validating +a patch. Read revisions from a fresh `show` and send the patch on stdin. +Each revision identifies the resolved checkout, layer file and its +contents or absence. The minimum base includes every edited layer. Additional +revisions can protect inputs the client used to prepare the patch. + +```json +{ + "base": { "1": "" }, + "changes": [ + { "layer": "1", "kind": "project", "path": "internal.dns", "value": true } + ] +} +``` + +Changes can set a project field, a simple route (`service`, `sites`, +`port`), a service field (`service`, `field`, `value`), an env entry +(`scope`, `key`, `value`, optional `secret`), or replace editable +`source` (`text`). Use a null env value to unset the entry through the +same writer as `hack env unset`. Secrets submitted by clients must use +`secret: true` and travel on stdin. + +Validation returns `valid`, `issues` and safe source `previews`. An issue +has a layer ID, path segments, a one-based line when available, a code and +message. Apply rejects invalid changes and returns `E_CONFLICT` for a stale +revision or `E_LAYER_READ_ONLY` for an inherited or generated layer. +Files are committed individually. If a later write fails after an earlier +one committed, `error.detail.changed` identifies the committed layers. +Reload before retrying. A successful apply reports changed layers and +whether to offer a restart. The caller starts or restarts services separately. + ## Additive fields Additive fields keep a command's row and shape above; consumers ignore keys they do not know. diff --git a/docs/versions/v5/getting-started.md b/docs/versions/v5/getting-started.md index 4949fdf8d8..01fb26ae39 100644 --- a/docs/versions/v5/getting-started.md +++ b/docs/versions/v5/getting-started.md @@ -64,6 +64,14 @@ found”** when discovery wrote a placeholder `app` service (a Bun image running before `up`. The notice does not appear for a discovered service or when you explicitly chose `--manual` or `--no-discovery`. +The desktop project's **Config** tab shows routes, service dependencies and +which file supplies each setting. Choose **Viewing as** to inspect a checkout +and **Env** to select an overlay. Save edits to the layer shown. Route changes +offer a restart, and env-only changes apply the next time a service starts. +Use `hack config show --json` for the same Compose model from the CLI. +Config omits recognized credentials from service and dependency diagnostics +and hides env overlay names, keys and scopes that contain recognized credentials. + ## Start and open ```sh diff --git a/docs/versions/v5/guides/desktop-app.md b/docs/versions/v5/guides/desktop-app.md index 1dfcd96248..83ba6e85e0 100644 --- a/docs/versions/v5/guides/desktop-app.md +++ b/docs/versions/v5/guides/desktop-app.md @@ -50,6 +50,11 @@ in the Stats charts while the app is open. When the CLI does not report something, the app shows a dash and says why. It does not invent a value. +The `hackd` and **Routing and DNS** sidebar indicators follow the checks shown +in Setup. When a command finishes, the indicator updates with the result of the +fresh check. Dark mode uses Merino Dark. Your Ghostty configuration can override +the embedded terminal's look. + The app samples running Compose services every five seconds, including while you view another pane. For a stopped service, its recent samples age out of the chart. Network rates need two samples with the same known container diff --git a/plugins/hack/skills/hack-diagnose/references/error-codes.md b/plugins/hack/skills/hack-diagnose/references/error-codes.md index 2cdb7c6b50..742c479d9b 100644 --- a/plugins/hack/skills/hack-diagnose/references/error-codes.md +++ b/plugins/hack/skills/hack-diagnose/references/error-codes.md @@ -14,6 +14,8 @@ stay within the request. | `E_GLOBAL_STOPPED` | A global proxy or logging container stopped right after it started. | `docker logs --tail 50 ` | | `E_CONFIG_PARSE` | A Hack configuration file could not be parsed. | `hack doctor --json` | | `E_CONFIG_INVALID` | Project configuration or saved runtime input did not pass validation. | `hack doctor --json` | +| `E_CONFLICT` | A project config layer changed after it was read. | Run hack config show --json again before preparing a new patch. | +| `E_LAYER_READ_ONLY` | The selected project config layer cannot be edited. | Check the layer’s writable flag and edit an authored layer. | | `E_MIN_CLI_VERSION_REQUIRED` | The Compose remote configuration needs a minimum CLI version. | `hack config validate --json` | | `E_INVALID_MIN_CLI_VERSION` | The minimum CLI version is malformed. | `hack config validate --json` | | `E_CLI_VERSION_TOO_OLD` | The running CLI is older than the project minimum. | `hack config validate --json` | @@ -67,4 +69,4 @@ stay within the request. --- -Content revision: `ad7db50d545b`. Generated by Hack; edit the canonical source and regenerate the plugin. +Content revision: `fbf626bdfcb0`. Generated by Hack; edit the canonical source and regenerate the plugin. diff --git a/src/agents/error-code-reference.ts b/src/agents/error-code-reference.ts index af2fa2e752..1424b8f636 100644 --- a/src/agents/error-code-reference.ts +++ b/src/agents/error-code-reference.ts @@ -54,6 +54,15 @@ const ERROR_CODE_GUIDES: Readonly> = { meaning: "A Hack configuration file could not be parsed.", readFirst: "`hack doctor --json`", }, + E_CONFLICT: { + meaning: "A project config layer changed after it was read.", + readFirst: + "Run hack config show --json again before preparing a new patch.", + }, + E_LAYER_READ_ONLY: { + meaning: "The selected project config layer cannot be edited.", + readFirst: "Check the layer’s writable flag and edit an authored layer.", + }, E_CONFIG_INVALID: { meaning: "Project configuration or saved runtime input did not pass validation.", diff --git a/src/cli/json-contracts.ts b/src/cli/json-contracts.ts index b7e82d5192..756378e410 100644 --- a/src/cli/json-contracts.ts +++ b/src/cli/json-contracts.ts @@ -1,3 +1,5 @@ +import { MACHINE_SCHEMAS } from "../lib/machine-output.ts"; + /** Canonical --json inventory. New command paths require an explicit shape decision. */ export const JSON_COMMAND_SHAPES = { "global install": "schema-envelope", @@ -56,7 +58,9 @@ export const JSON_COMMAND_SHAPES = { "env backend status": "legacy-object", "env backend use": "legacy-object", "host ps": "legacy-object", - "config validate": "transport", + "config show": "schema-envelope", + "config apply": "schema-envelope", + "config validate": "config-validation", "config plan": "transport", "config import": "legacy-object", "config adopt": "legacy-object", @@ -118,6 +122,8 @@ export const SCHEMA_JSON_VARIANTS = [ { command: "service add", flags: [], schema: "hack.service-add.v1" }, { command: "env overlay add", flags: [], schema: "hack.env-overlays.v1" }, { command: "env overlay list", flags: [], schema: "hack.env-overlays.v1" }, + { command: "config show", flags: [], schema: MACHINE_SCHEMAS.config }, + { command: "config apply", flags: [], schema: MACHINE_SCHEMAS.config }, { command: "projects", flags: ["--observe"], diff --git a/src/cli/json-reference.ts b/src/cli/json-reference.ts index c8b7eb9bb1..21cfb5c42b 100644 --- a/src/cli/json-reference.ts +++ b/src/cli/json-reference.ts @@ -1,3 +1,4 @@ +import { MACHINE_SCHEMAS } from "../lib/machine-output.ts"; import type { AnyCommandSpec, CliSpec } from "./command.ts"; import { JSON_COMMAND_SHAPES, SCHEMA_JSON_VARIANTS } from "./json-contracts.ts"; @@ -33,6 +34,7 @@ const SHAPES: Record< logs: "NDJSON logs; finite native modes may return a legacy snapshot object", transport: "Native compiler protocol object (`transport_version`, `ok`, result / diagnostics)", + "config-validation": `Envelope with \`data.schema: ${MACHINE_SCHEMAS.config}\` for a Compose patch on stdin when \`--file\`, \`--profile\` and \`--domain\` are omitted. Otherwise a file validation object with \`transport_version\``, "error-only": "Retired: usage-error envelope, no success payload", "runtime-passthrough": "Native runtime result passed through unchanged, with no `data` envelope (setup: `status`, `builder`, `files`, `probe`; recover: the runtime status, such as `phase`)", diff --git a/src/commands/config-editor.ts b/src/commands/config-editor.ts new file mode 100644 index 0000000000..4c80aa41e6 --- /dev/null +++ b/src/commands/config-editor.ts @@ -0,0 +1,180 @@ +import { fstatSync } from "node:fs"; +import { resolve } from "node:path"; +import { CliUsageError, defineCommand, withHandler } from "../cli/command.ts"; +import { resolveRequestedEnvName } from "../cli/env-selection.ts"; +import { optBranch, optEnv, optJson, optPath } from "../cli/options.ts"; +import { + emitCliResult, + errorResult, + HackCliError, + okResult, +} from "../lib/cli-result.ts"; +import { + CONFIG_EDITOR_SCHEMA, + readConfigEditor, + showConfigEditor, +} from "../lib/config-editor-model.ts"; +import { + applyConfigPatch, + assessConfigPatch, + readConfigPatch, +} from "../lib/config-editor-patch.ts"; + +const options = [optPath, optBranch, optEnv, optJson] as const; +const base = { + group: "Project", + options, + positionals: [], + subcommands: [], +} as const; +const show = defineCommand({ + ...base, + name: "show", + summary: "Show Compose project config, layers, routes and env provenance", +} as const); +const apply = defineCommand({ + ...base, + name: "apply", + summary: "Apply a validated Compose project config patch from stdin", +} as const); +const MAX_PATCH_BYTES = 2 * 1024 * 1024; + +type Selection = { + readonly cwd: string; + readonly path?: string; + readonly env?: string; + readonly branch?: string; +}; + +function readSelection(selection: Selection) { + return readConfigEditor({ + start: resolve(selection.cwd, selection.path ?? "."), + branch: selection.branch, + overlay: resolveRequestedEnvName({ envOption: selection.env }), + }); +} + +async function readPatchSelection(selection: Selection) { + const snapshot = await readSelection(selection).catch((error: unknown) => { + if ( + error instanceof HackCliError && + (error.code === "E_PROJECT_NOT_FOUND" || error.code === "E_PATH_CONFLICT") + ) { + return null; + } + throw error; + }); + if (snapshot === null) { + throw new HackCliError({ + code: "E_CONFLICT", + message: + "The selected checkout is no longer available. Reload before saving.", + }); + } + return snapshot; +} + +async function runConfigEditor(work: () => Promise): Promise { + try { + emitCliResult({ result: okResult({ data: await work() }) }); + return 0; + } catch (error) { + const result = + error instanceof HackCliError + ? errorResult({ + code: error.code, + message: error.message, + detail: error.detail, + }) + : errorResult({ + code: "E_CONFIG_INVALID", + message: "Could not read or update the selected config.", + }); + emitCliResult({ result }); + return 1; + } +} + +export const configShowCommand = withHandler(show, async ({ ctx, args }) => { + if (!args.options.json) { + throw new CliUsageError("Use hack config show --json."); + } + return await runConfigEditor(async () => + showConfigEditor(await readSelection({ cwd: ctx.cwd, ...args.options })) + ); +}); + +export const configApplyCommand = withHandler(apply, async ({ ctx, args }) => { + if (!args.options.json) { + throw new CliUsageError( + "Use hack config apply --json with a patch on stdin." + ); + } + return await runConfigEditor(async () => { + const patch = readConfigPatch((await readConfigPatchStdin()) ?? ""); + const snapshot = await readPatchSelection({ + cwd: ctx.cwd, + ...args.options, + }); + return await applyConfigPatch(snapshot, patch); + }); +}); + +/** Keep existing no-patch validation usable with a terminal or /dev/null. */ +export async function readConfigPatchStdin(): Promise { + const descriptor = fstatSync(0, { throwIfNoEntry: false }); + if ( + !( + descriptor && + (descriptor.isFIFO() || descriptor.isFile() || descriptor.isSocket()) + ) + ) { + return null; + } + const decoder = new TextDecoder(); + let size = 0; + let input = ""; + const reader = Bun.stdin.stream().getReader(); + for (;;) { + const { done, value: chunk } = await reader.read(); + if (done) { + break; + } + size += chunk.byteLength; + if (size > MAX_PATCH_BYTES) { + await reader.cancel(); + throw new HackCliError({ + code: "E_USAGE", + message: "Config patch exceeds the 2 MiB limit.", + }); + } + input += decoder.decode(chunk, { stream: true }); + } + return (input + decoder.decode()).trim() || null; +} + +/** Return null only when the invocation is the established compiler command. */ +export async function validateConfigEditorStdin( + selection: Selection +): Promise { + let input: string | null; + try { + input = await readConfigPatchStdin(); + } catch (error) { + return await runConfigEditor(() => Promise.reject(error)); + } + if (input === null && selection.branch === undefined) { + return null; + } + return await runConfigEditor(async () => { + const patch = readConfigPatch(input ?? ""); + const snapshot = await readPatchSelection(selection); + const { issues, previews } = await assessConfigPatch(snapshot, patch); + return { + schema: CONFIG_EDITOR_SCHEMA, + valid: issues.length === 0, + issues, + previews, + }; + }); +} diff --git a/src/commands/config-validate.ts b/src/commands/config-validate.ts index 110b053828..498229301b 100644 --- a/src/commands/config-validate.ts +++ b/src/commands/config-validate.ts @@ -6,7 +6,7 @@ import { withHandler, } from "../cli/command.ts"; import { resolveRequestedEnvName } from "../cli/env-selection.ts"; -import { optEnv, optJson, optPath } from "../cli/options.ts"; +import { optBranch, optEnv, optJson, optPath } from "../cli/options.ts"; import { HackCliError } from "../lib/cli-result.ts"; import { NATIVE_GRAPH_ADMISSION_CODE, @@ -23,13 +23,14 @@ import { import { validateNativeProject } from "../lib/native-project-validation.ts"; import { readProjectConfigInDirectory } from "../lib/project.ts"; import { discoverProjectInputs } from "../lib/project-input-selection.ts"; +import { validateConfigEditorStdin } from "./config-editor.ts"; const spec = defineCommand({ name: "validate", summary: "Validate project configuration without starting workloads", group: "Project", description: - "Uses the matching bundled Rust compiler. Without --file, discovers a Compose or native project. Native validation resolves permitted worktree-local overlay and routing settings. --file validates only the explicit document. With HACK_RUNTIME_BACKEND=native, a selected workload image that is not a sha256: content ID refuses with the native consumer's native_graph_admission code. Neither mode reads env values, writes state, or starts workloads.", + "Reads a Compose config patch on stdin with --json when --file, --profile and --domain are omitted. Otherwise checks the on-disk configuration, using the matching bundled Rust compiler for native projects. Without --file, discovers a Compose or native project. Native validation resolves permitted worktree-local overlay and routing settings. --file validates only the explicit document. With HACK_RUNTIME_BACKEND=native, a selected workload image that is not a sha256: content ID refuses with the native consumer's native_graph_admission code. Neither mode decrypts env secrets, writes state, or starts workloads.", options: [ defineOption({ name: "file", @@ -54,6 +55,7 @@ const spec = defineCommand({ description: "Select the generated native routing domain suffix", } as const), optPath, + optBranch, optEnv, optJson, ], @@ -65,6 +67,15 @@ export const configValidateCommand = withHandler( spec, async ({ ctx, args }) => { const file = args.options.file; + const patch = await validatePatchWhenRequested(ctx.cwd, args.options); + if (patch !== null) { + return patch; + } + if (args.options.branch !== undefined) { + throw new CliUsageError( + "--branch requires a JSON config patch on stdin." + ); + } if (file !== undefined && !file.trim()) { throw new CliUsageError("Native file paths must not be empty."); } @@ -156,6 +167,29 @@ export const configValidateCommand = withHandler( } ); +async function validatePatchWhenRequested( + cwd: string, + options: { + readonly json?: boolean; + readonly file?: string; + readonly profile?: string; + readonly domain?: string; + readonly path?: string; + readonly env?: string; + readonly branch?: string; + } +): Promise { + if ( + !options.json || + options.file !== undefined || + options.profile !== undefined || + options.domain !== undefined + ) { + return null; + } + return await validateConfigEditorStdin({ cwd, ...options }); +} + async function validateComposeConfiguration( startDir: string, json: boolean diff --git a/src/commands/config.ts b/src/commands/config.ts index 0692342c8c..53a2caa088 100644 --- a/src/commands/config.ts +++ b/src/commands/config.ts @@ -18,6 +18,7 @@ import { DEFAULT_DOMAIN_CONFIG_KEY, parseDefaultDomain, } from "../lib/default-domain.ts"; +import { withEnvLayerLock } from "../lib/env-layer-lock.ts"; import { ensureDir, readTextFile, writeTextFileIfChanged } from "../lib/fs.ts"; import { LOGGING_ENABLED_CONFIG_KEY, @@ -36,6 +37,7 @@ import { import { parseSessionsMuxMode } from "../mux/mux-config.ts"; import { logger } from "../ui/logger.ts"; import { configAdoptCommand } from "./config-adopt.ts"; +import { configApplyCommand, configShowCommand } from "./config-editor.ts"; import { configImportCommand } from "./config-import.ts"; import { configPlanCommand } from "./config-plan.ts"; import { configValidateCommand } from "./config-validate.ts"; @@ -177,6 +179,24 @@ const handleConfigSet: CommandHandlerFor = async ({ return 1; } + const write = () => updateConfigValue(project, parsedKey, value); + if (project.scope === "global") { + return await write(); + } + await assertLegacyProjectDirectory({ + projectDir: project.project.projectDir, + }); + return await withEnvLayerLock({ + layerPath: project.project.configFile, + run: write, + }); +}; + +async function updateConfigValue( + project: ConfigTarget, + parsedKey: readonly string[], + value: unknown +): Promise { const read = await readConfigJsonForSet({ target: project }); if (!read.ok) { logger.error({ message: read.error }); @@ -211,14 +231,16 @@ const handleConfigSet: CommandHandlerFor = async ({ message: result.changed ? `Updated ${read.path}` : "No changes needed.", }); return 0; -}; +} export const configCommand = defineCommand({ ...configSpec, subcommands: [ withHandler(configGetSpec, handleConfigGet), withHandler(configSetSpec, handleConfigSet), + configShowCommand, configValidateCommand, + configApplyCommand, configPlanCommand, configImportCommand, configAdoptCommand, diff --git a/src/commands/project.ts b/src/commands/project.ts index 12212ff638..9a0963d791 100644 --- a/src/commands/project.ts +++ b/src/commands/project.ts @@ -493,6 +493,7 @@ import { } from "../lib/open-host.ts"; import { openUrl, urlOpenerAvailable } from "../lib/os.ts"; import { + defaultProjectDevHost, defaultProjectSlugFromPath, findProjectContext, findRepoRootForInit, @@ -3932,7 +3933,7 @@ async function resolveRuntimeDevHost(opts: { } return ( (await readProjectDevHost(opts.project)) ?? - `${defaultProjectSlugFromPath(opts.project.projectRoot)}.${DEFAULT_PROJECT_TLD}` + defaultProjectDevHost(opts.project.projectRoot) ); } diff --git a/src/lib/cli-result.ts b/src/lib/cli-result.ts index c5608087f2..2096bfb48e 100644 --- a/src/lib/cli-result.ts +++ b/src/lib/cli-result.ts @@ -28,6 +28,8 @@ export const HACK_ERROR_CODES = [ "E_GLOBAL_STOPPED", "E_CONFIG_PARSE", "E_CONFIG_INVALID", + "E_CONFLICT", + "E_LAYER_READ_ONLY", "E_MIN_CLI_VERSION_REQUIRED", "E_INVALID_MIN_CLI_VERSION", "E_CLI_VERSION_TOO_OLD", diff --git a/src/lib/config-editor-compose.ts b/src/lib/config-editor-compose.ts new file mode 100644 index 0000000000..08dc2ebf17 --- /dev/null +++ b/src/lib/config-editor-compose.ts @@ -0,0 +1,1035 @@ +import { isIP } from "node:net"; +import { + isAlias, + isMap, + isScalar, + isSeq, + LineCounter, + parseDocument, + type YAMLSeq, +} from "yaml"; +import { + isCaddySiteLabel, + rewriteCaddyLabelForBranch, + splitCaddySites, +} from "./branch-hosts.ts"; +import { isConfigSecret, redactConfigPath } from "./config-editor-source.ts"; +import { isRecord } from "./guards.ts"; + +const ADDRESS = + /^(?:(https?):\/\/)?([a-z\d](?:[a-z\d.-]*[a-z\d])?)(?::(\d+))?$/i; +const UPSTREAM = /^\{\{upstreams ([0-9]+)\}\}$/; +const HOST_LABEL = /^[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?$/i; +const SERVICE_NAME = /^[\w.-]+$/; +const ROUTE_LABEL = /^caddy(?:[._]|$)/; +const PORT_MAX = 65_535; +const PORT_RANGE = /^([\d*]+)(?:-([\d*]+))?$/; +const PORT_NUMBER = /^[\d*]+$/; +const IPV6_TEMPLATE = /^[a-f\d:.*]+$/i; +const ADJACENT_VARIABLES = /\*+/g; +// Eight IPv6 groups, with space for an embedded IPv4 tail and brackets. +const MAX_PORT_HOST_LENGTH = 47; +const VARIABLE_REFERENCE = + /\$(?:\$|\{[A-Za-z_]\w*(?:\}|(:?[-+?]))|[A-Za-z_]\w*)/y; +const PORT_PROTOCOLS = ["tcp", "udp", "sctp"]; +const DEPENDENCY_CONDITIONS = [ + "service_started", + "service_healthy", + "service_completed_successfully", +]; + +export const validHost = (host: string): boolean => + host.length <= 253 && host.split(".").every((part) => HOST_LABEL.test(part)); + +export const validPort = (port: unknown): port is number => + typeof port === "number" && + Number.isInteger(port) && + port >= 1 && + port <= PORT_MAX; + +export function validComposePort(value: unknown): boolean { + if (typeof value !== "string") { + return validPort(value); + } + const template = portTemplate(value); + if (template === null) { + return false; + } + const [mapping, protocol, extra] = template.split("/"); + if ( + mapping === undefined || + extra !== undefined || + (protocol !== undefined && !matchesComposeOption(protocol, PORT_PROTOCOLS)) + ) { + return false; + } + return ( + validPortMapping(mapping) || + validInterpolatedPortPair(mapping) || + validInterpolatedHostMapping(mapping) + ); +} + +function validPortMapping(mapping: string): boolean { + // Split from the target end because a host can be an unbracketed IPv6 address. + const [target, published, ...address] = mapping.split(":").toReversed(); + const host = address.toReversed().join(":"); + return validOptionalPortHost(host) && validPortNumbers(published, target); +} + +function validPortNumbers( + published: string | undefined, + target: string | undefined +): boolean { + return ( + (!published || validPortRange(published, true)) && + target !== undefined && + validPortRange(target) && + (!published || + published.includes("*") || + target.includes("*") || + portRangeSpan(target) === 0 || + portRangeSpan(target) === portRangeSpan(published)) + ); +} + +function validOptionalPortHost(host: string): boolean { + return host === "" || host === "[]" || validPortHost(host); +} + +function validInterpolatedPortPair(mapping: string): boolean { + const separator = mapping.lastIndexOf(":"); + return ( + validOptionalPortHost(mapping.slice(0, Math.max(separator, 0))) && + validVariablePortPair(mapping.slice(separator + 1)) + ); +} + +function validVariablePortPair(tail: string): boolean { + if (!tail.includes("*")) { + return false; + } + const published = new Set(portVariableSplits(tail, false)); + for (const target of portVariableSplits(tail, true)) { + if (published.has(target)) { + return true; + } + } + return false; +} + +function validInterpolatedHostMapping(mapping: string): boolean { + const template = mapping.replace(ADJACENT_VARIABLES, "*"); + let hostLength = 0; + for ( + let index = 0; + index < template.length && hostLength <= MAX_PORT_HOST_LENGTH; + index += 1 + ) { + if (template[index] !== "*") { + hostLength += 1; + continue; + } + const prefix = template.slice(0, index); + if ( + validHostBeforeVariable(prefix) && + validPortsAfterVariable(template.slice(index)) + ) { + return true; + } + } + return false; +} + +function validHostBeforeVariable(prefix: string): boolean { + // A variable can finish the host before supplying its separator. + return ( + validOptionalPortHost(prefix) || + validPortHost(`${prefix}*`) || + (prefix.startsWith("[") && validPortHost(`${prefix}*]`)) + ); +} + +function validPortsAfterVariable(tail: string): boolean { + const separator = tail.indexOf(":"); + if (separator < 0) { + return validVariablePortPair(tail); + } + return ( + separator === tail.lastIndexOf(":") && + validPortNumbers(tail.slice(0, separator), tail.slice(separator + 1)) + ); +} + +/** A split variable can supply the colon and digits on either side of it. */ +function* portVariableSplits(template: string, reverse: boolean) { + let minimum = 0; + let place = 1; + let hasVariable = false; + let hasRange = false; + const step = reverse ? -1 : 1; + for ( + let index = reverse ? template.length - 1 : 0; + index >= 0 && index < template.length; + index += step + ) { + const token = template[index]; + if (token === "*") { + hasVariable = true; + yield index; + continue; + } + if (token === "-") { + if (hasRange || (!hasVariable && minimum === 0)) { + return; + } + hasRange = true; + hasVariable = false; + minimum = 0; + place = 1; + continue; + } + const digit = template.charCodeAt(index) - 48; + minimum = reverse ? minimum + digit * place : minimum * 10 + digit; + if (digit < 0 || digit > 9 || minimum > PORT_MAX) { + return; + } + place = Math.min(place * 10, PORT_MAX + 1); + } +} + +function validPortHost(value: string): boolean { + if (value.includes("%")) { + return false; + } + const bracketed = value.startsWith("[") && value.endsWith("]"); + const host = bracketed ? value.slice(1, -1) : value; + if (!host.includes("*")) { + return isIP(host) !== 0; + } + return bracketed || host.includes(":") || !host.includes(".") + ? validIpv6Template(host) + : validIpv4Template(host); +} + +function validIpv6Template(host: string): boolean { + const sides = host.split("::"); + if ( + !IPV6_TEMPLATE.test(host) || + sides.length > 2 || + (host.startsWith(":") && !host.startsWith("::")) || + (host.endsWith(":") && !host.endsWith("::")) + ) { + return false; + } + const parts = sides.filter(Boolean).flatMap((side) => side.split(":")); + let groups = sides.length === 2 ? 1 : 0; + for (const [index, part] of parts.entries()) { + if (!part.includes(".")) { + groups += minimumIpv6Groups(part); + continue; + } + if (index !== parts.length - 1 || !validIpv4Template(part)) { + return false; + } + groups += 2; + } + return groups <= 8; +} + +/** A substitution can supply a separator between fixed runs of hex digits. */ +function minimumIpv6Groups(part: string): number { + if (!part) { + return Number.POSITIVE_INFINITY; + } + let groups = 1; + let width = 0; + for (const run of part.split("*")) { + if (run.length > 4) { + return Number.POSITIVE_INFINITY; + } + if (width + run.length > 4) { + groups += 1; + width = 0; + } + width += run.length; + } + return groups; +} + +function validIpv4Template(host: string): boolean { + let octets = 0; + for (const part of host.split(".")) { + octets += minimumIpv4Octets(part); + if (octets > 4) { + return false; + } + } + return true; +} + +/** A substitution can fill out the current octet or insert a dot. */ +function minimumIpv4Octets(part: string): number { + if (!PORT_NUMBER.test(part)) { + return Number.POSITIVE_INFINITY; + } + const [first = "", ...rest] = part.split("*"); + let octet = first; + let mayHavePrefix = first === ""; + let count = 1; + for (const run of rest) { + if (canFitIpv4Octet(octet + run, mayHavePrefix)) { + octet += run; + continue; + } + if (!canFitIpv4Octet(octet, mayHavePrefix)) { + return Number.POSITIVE_INFINITY; + } + count += 1; + octet = run; + mayHavePrefix = true; + } + return canFitIpv4Octet(octet, mayHavePrefix) + ? count + : Number.POSITIVE_INFINITY; +} + +function canFitIpv4Octet(digits: string, mayHavePrefix: boolean): boolean { + if (digits.length < 2) { + return true; + } + return ( + digits.length <= 3 && + (digits.startsWith("0") + ? mayHavePrefix && digits.length === 2 + : Number(digits) <= 255) + ); +} + +function matchesComposeOption( + template: string, + options: readonly string[] +): boolean { + const pattern = template + .split("*") + .map((part) => RegExp.escape(part)) + .join(".*"); + const match = new RegExp(`^${pattern}$`); + return options.some((option) => match.test(option)); +} + +function portRangeSpan(value: string): number { + const [first, last = first] = value.split("-"); + return Number(last) - Number(first); +} + +function validPortRange(value: string, allowZero = false): boolean { + const match = PORT_RANGE.exec(value); + const first = match?.[1]; + const last = match?.[2]; + if (!first) { + return false; + } + return ( + validPortNumber(first, allowZero && last === undefined) && + (last === undefined || + (validPortNumber(last) && + (first.includes("*") || + last.includes("*") || + Number(first) <= Number(last)))) + ); +} + +function validPortNumber(value: string, allowZero = false): boolean { + return ( + PORT_NUMBER.test(value) && + ((value.includes("*") && Number(value.replaceAll("*", "")) <= PORT_MAX) || + (allowZero && value === "0") || + validPort(Number(value))) + ); +} + +/** Replace well-formed references with an unknown component without reading any env. */ +function portTemplate(value: unknown): string | null { + if (typeof value !== "string" || value.includes("*")) { + return null; + } + let template = ""; + let depth = 0; + for (let index = 0; index < value.length; index += 1) { + const character = value[index]; + if (character !== "$") { + if (depth === 0) { + template += character; + } else { + depth -= Number(character === "}"); + } + continue; + } + VARIABLE_REFERENCE.lastIndex = index; + const match = VARIABLE_REFERENCE.exec(value); + if (!match) { + return null; + } + const [reference, operator] = match; + if (depth === 0) { + template += reference === "$$" ? "$" : "*"; + } + depth += operator === undefined ? 0 : 1; + index += reference.length - 1; + } + return depth === 0 ? template : null; +} + +function validSourcePort(port: unknown): boolean { + if (!isRecord(port)) { + return validComposePort(port); + } + const { target, published, host_ip } = port; + const targetTemplate = portTemplate(target); + const publishedTemplate = portTemplate( + typeof published === "number" ? String(published) : published + ); + const hostTemplate = portTemplate(host_ip); + return ( + (validPort(target) || + (targetTemplate !== null && validPortNumber(targetTemplate))) && + (published === undefined || + (publishedTemplate !== null && + validPortRange(publishedTemplate, true))) && + (host_ip === undefined || + (hostTemplate !== null && validPortHost(hostTemplate))) + ); +} + +export function parseRouteAddress(site: string) { + const match = ADDRESS.exec(site); + const host = match?.[2]; + const port = match?.[3] === undefined ? null : Number(match[3]); + if (!(host && validHost(host)) || (port !== null && !validPort(port))) { + return null; + } + return { host, port, tls: match?.[1]?.toLowerCase() !== "http" }; +} + +export type ConfigIssue = { + readonly layer: string | null; + readonly path: readonly string[]; + readonly line: number | null; + readonly code: string; + readonly message: string; +}; + +export function parseComposeSource(text: string) { + const lines = new LineCounter(); + const doc = parseDocument(text, { + lineCounter: lines, + merge: true, + prettyErrors: false, + }); + const error = doc.errors[0]; + if (error) { + return { + doc, + lines, + invalid: lines.linePos(error.pos[0]).line, + services: {}, + checksDependencies: false, + }; + } + try { + const compose: unknown = doc.toJS(); + const root = isRecord(compose) ? compose : {}; + const services = isRecord(root.services) ? root.services : null; + const includes = root.include ?? undefined; + const valid = + (includes === undefined || validComposeIncludes(includes)) && + (services !== null || + (root.services === undefined && + Array.isArray(includes) && + includes.length > 0)); + return { + doc, + lines, + invalid: valid ? null : 1, + services: services ?? {}, + checksDependencies: + services !== null && + includes === undefined && + !Object.values(services).some( + (service) => isRecord(service) && service.extends !== undefined + ), + }; + } catch { + return { doc, lines, invalid: 1, services: {}, checksDependencies: false }; + } +} + +function validComposeIncludes(value: unknown): boolean { + return Array.isArray(value) && value.every(validComposeInclude); +} + +function validComposeInclude(entry: unknown): boolean { + if (!isRecord(entry)) { + return nonemptyIncludePath(entry); + } + const { path, project_directory, env_file } = entry; + return ( + (nonemptyIncludePath(path) || + (Array.isArray(path) && + path.length > 0 && + path.every(nonemptyIncludePath))) && + (project_directory === undefined || + project_directory === null || + typeof project_directory === "string") && + (env_file === undefined || + env_file === null || + nonemptyIncludePath(env_file) || + (Array.isArray(env_file) && env_file.every(nonemptyIncludePath))) + ); +} + +function nonemptyIncludePath(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +type ComposeSource = ReturnType; +type Site = { readonly key: string; readonly value: string }; + +function composeLabels(service: Record): readonly Site[] { + if (isRecord(service.labels)) { + return Object.entries(service.labels).flatMap(([key, value]) => + typeof value === "string" ? [{ key, value }] : [{ key, value: "" }] + ); + } + if (!Array.isArray(service.labels)) { + return []; + } + return service.labels.flatMap((label: unknown) => { + if (typeof label !== "string") { + return []; + } + const separator = label.indexOf("="); + return separator < 0 + ? [{ key: label, value: "" }] + : [{ key: label.slice(0, separator), value: label.slice(separator + 1) }]; + }); +} + +function simpleRoute( + service: Record, + labels: readonly Site[] +) { + const caddy = labels.filter((label) => ROUTE_LABEL.test(label.key)); + const site = caddy.find((label) => label.key === "caddy"); + const upstream = caddy.find((label) => label.key === "caddy.reverse_proxy"); + if ( + service.extends !== undefined || + (service.labels !== undefined && + !isRecord(service.labels) && + !Array.isArray(service.labels)) + ) { + return null; + } + if (caddy.length === 0) { + return { sites: "", port: null }; + } + if (caddy.length !== 2 || !site || !upstream) { + return null; + } + const port = upstreamPort(upstream.value); + const sites = splitCaddySites(site.value); + return port !== null && sites.length > 0 && sites.every(parseRouteAddress) + ? { sites: site.value, port } + : null; +} + +function publicCaddySites(value: string): string { + const sites = splitCaddySites(value); + const visible = sites.filter((site) => !isConfigSecret("", site)); + return visible.length === sites.length ? value : visible.join(", "); +} + +function upstreamPort(value: string | undefined): number | null { + const port = Number(value?.match(UPSTREAM)?.[1]); + return validPort(port) ? port : null; +} + +type RouteView = { + readonly host: string; + readonly port: number | null; + readonly tls: boolean; + readonly from: readonly string[]; +}; + +function serviceRoutes(opts: { + readonly labels: readonly Site[]; + readonly branch: string | null; + readonly baseHosts: readonly string[]; +}): { readonly routes: readonly RouteView[]; readonly droppedAll: boolean } { + const { branch, baseHosts } = opts; + // Compose reduces repeated list labels to the last assignment. + const labels = new Map(opts.labels.map(({ key, value }) => [key, value])); + const routes: RouteView[] = []; + let droppedAll = false; + for (const [key, value] of labels) { + if (!isCaddySiteLabel(key)) { + continue; + } + const sites = publicCaddySites(value); + const resolved = + branch === null + ? sites + : rewriteCaddyLabelForBranch({ value: sites, branch, baseHosts }).value; + if (branch !== null && sites.trim() && !resolved) { + droppedAll = true; + } + const port = upstreamPort(labels.get(`${key}.reverse_proxy`)); + for (const site of splitCaddySites(resolved)) { + const address = parseRouteAddress(site); + if (address && !isConfigSecret("", address.host)) { + routes.push({ + ...address, + port: port ?? address.port, + from: branch === null ? ["2"] : ["2", "6"], + }); + } + } + } + return { routes, droppedAll }; +} + +function composePorts(value: unknown): unknown[] { + if (!Array.isArray(value)) { + return []; + } + return value.flatMap((port: unknown): unknown[] => { + if ( + typeof port === "number" || + (typeof port === "string" && !isConfigSecret("", port)) + ) { + return [port]; + } + if (!isRecord(port)) { + return []; + } + return [ + Object.fromEntries( + Object.entries(port).filter( + ([key, item]) => + [ + "target", + "published", + "host_ip", + "protocol", + "mode", + "name", + "app_protocol", + ].includes(key) && + (typeof item === "number" || + (typeof item === "string" && !isConfigSecret("", item))) + ) + ), + ]; + }); +} + +export const COMPOSE_EDIT_FIELDS = ["image", "ports", "depends_on"] as const; + +export function editableComposeField(opts: { + readonly source: ComposeSource; + readonly service: string; + readonly field: (typeof COMPOSE_EDIT_FIELDS)[number]; +}): boolean { + const path = ["services", opts.service]; + const node = opts.source.doc.getIn(path, true); + const raw = opts.source.services[opts.service]; + if ( + !isMap(node) || + node.has("<<") || + !isRecord(raw) || + raw.extends !== undefined + ) { + return false; + } + const field = opts.source.doc.getIn([...path, opts.field], true); + return !( + isMap(field) || + isAlias(field) || + (isSeq(field) && field.items.some((entry) => !isScalar(entry))) + ); +} + +function serviceNames(value: unknown): string[] { + if (Array.isArray(value)) { + return value.filter( + (entry: unknown): entry is string => typeof entry === "string" + ); + } + return isRecord(value) ? Object.keys(value) : []; +} + +function validDependencies(value: unknown, complete: boolean): boolean { + return ( + value === undefined || + (Array.isArray(value) && + value.every( + (entry) => typeof entry === "string" && SERVICE_NAME.test(entry) + )) || + (isRecord(value) && + Object.entries(value).every( + ([name, options]) => + SERVICE_NAME.test(name) && + isRecord(options) && + validDependencyCondition(options.condition, complete) + )) + ); +} + +function validDependencyCondition(value: unknown, complete: boolean): boolean { + const condition = portTemplate(value); + return ( + (condition !== null && + matchesComposeOption(condition, DEPENDENCY_CONDITIONS)) || + (value === undefined && !complete) + ); +} + +function composeDependencyIssue( + source: ComposeSource, + service: string, + dependencies: readonly string[] +): ConfigIssue | null { + const path = ["services", service, "depends_on"]; + if (dependencies.includes(service)) { + return composeFieldIssue( + source, + path, + "A service cannot depend on itself." + ); + } + if (!source.checksDependencies) { + return null; + } + const missing = dependencies.find( + (dependency) => !Object.hasOwn(source.services, dependency) + ); + if (missing === undefined) { + return null; + } + return composeFieldIssue( + source, + path, + SERVICE_NAME.test(missing) && !isConfigSecret("", missing) + ? `depends_on names a service that is not defined: ${missing}` + : "depends_on names a service that is not defined." + ); +} + +function composeDependencyCycle(source: ComposeSource): ConfigIssue | null { + if (!source.checksDependencies) { + return null; + } + const pending = new Map(); + const dependents = new Map(); + for (const [name, service] of Object.entries(source.services)) { + if (!isRecord(service)) { + continue; + } + const dependencies = new Set(serviceNames(service.depends_on)); + dependencies.delete(name); + let count = 0; + for (const dependency of dependencies) { + if ( + !( + Object.hasOwn(source.services, dependency) && + isRecord(source.services[dependency]) + ) + ) { + continue; + } + const downstream = dependents.get(dependency) ?? []; + downstream.push(name); + dependents.set(dependency, downstream); + count += 1; + } + pending.set(name, count); + } + const ready = [...pending] + .filter(([, count]) => count === 0) + .map(([name]) => name); + for (const name of ready) { + pending.delete(name); + for (const downstream of dependents.get(name) ?? []) { + const count = (pending.get(downstream) ?? 0) - 1; + pending.set(downstream, count); + if (count === 0) { + ready.push(downstream); + } + } + } + const unresolved = pending.keys().next().value; + return unresolved === undefined + ? null + : composeFieldIssue( + source, + ["services", unresolved, "depends_on"], + "The service graph has a dependency cycle." + ); +} + +export function composeModel(opts: { + readonly text: string; + readonly branch: string | null; + readonly baseHosts: readonly string[]; +}) { + const source = parseComposeSource(opts.text); + const { doc, services } = source; + const issues: ConfigIssue[] = []; + const resolveRoutes = opts.branch === null || opts.baseHosts.length > 0; + if (source.invalid !== null) { + issues.push({ + layer: "2", + path: [], + line: source.invalid, + code: "E_CONFIG_PARSE", + message: "Expected Compose YAML with a services map or an include list.", + }); + } + const rows = Object.entries(services).flatMap(([name, service]) => { + if (!isRecord(service)) { + issues.push( + composeFieldIssue( + source, + ["services", name], + "A Compose service must be an object.", + "E_CONFIG_PARSE" + ) + ); + return []; + } + const dependencies = serviceNames(service.depends_on); + issues.push(...composeServiceIssues(source, name, service, dependencies)); + const labels = composeLabels(service); + const { routes, droppedAll } = resolveRoutes + ? serviceRoutes({ + labels, + branch: opts.branch, + baseHosts: opts.baseHosts, + }) + : { routes: [], droppedAll: false }; + if (droppedAll) { + issues.push({ + layer: "2", + path: ["services", name, "route"], + line: null, + code: "E_CONFIG_INVALID", + message: + "A Caddy label has no host in this project's route namespaces.", + }); + } + const rawService = doc.getIn(["services", name], true); + const labelsNode = doc.getIn(["services", name, "labels"], true); + const directlyEditable = + isMap(rawService) && + (isMap(labelsNode) || + isSeq(labelsNode) || + (labelsNode === undefined && service.labels === undefined)) && + !rawService.has("<<") && + !(isMap(labelsNode) && labelsNode.has("<<")); + const route = directlyEditable ? simpleRoute(service, labels) : null; + return [ + { + name, + image: + typeof service.image === "string" && + !isConfigSecret("", service.image) + ? service.image + : null, + ports: composePorts(service.ports), + depends_on: dependencies.filter((name) => !isConfigSecret("", name)), + routes, + route_edit: route && { ...route, sites: publicCaddySites(route.sites) }, + source_fields: COMPOSE_EDIT_FIELDS.filter( + (field) => !editableComposeField({ source, service: name, field }) + ), + }, + ]; + }); + const cycle = composeDependencyCycle(source); + if (cycle) { + issues.push(cycle); + } + return { + services: rows.filter(({ name }) => !isConfigSecret("", name)), + issues: issues.map((issue) => ({ + ...issue, + path: redactConfigPath(issue.path), + })), + }; +} + +function composeServiceIssues( + source: ComposeSource, + name: string, + service: Record, + dependencies: readonly string[] +): ConfigIssue[] { + const issues: ConfigIssue[] = []; + if ( + service.ports != null && + !(Array.isArray(service.ports) && service.ports.every(validSourcePort)) + ) { + issues.push( + composeFieldIssue( + source, + ["services", name, "ports"], + "Use valid port mappings with a target port between 1 and 65535." + ) + ); + } + const dependencyIssue = validDependencies( + service.depends_on, + source.checksDependencies + ) + ? composeDependencyIssue(source, name, dependencies) + : composeFieldIssue( + source, + ["services", name, "depends_on"], + "Use a list of services or give each mapped dependency a valid condition." + ); + if (dependencyIssue) { + issues.push(dependencyIssue); + } + return issues; +} +/** Reuse surviving scalar nodes, including each node's comments and style. */ +export function updateComposeServiceField(opts: { + readonly source: ComposeSource; + readonly path: string[]; + readonly value: string | (string | number)[]; +}): void { + const { doc } = opts.source; + const { path, value } = opts; + const node = doc.getIn(path, true); + if (!(Array.isArray(value) && isSeq(node))) { + doc.setIn(path, value); + return; + } + const previous = node.items.filter(isScalar); + const retained = new Set<(typeof previous)[number]>(); + const matching = value.map((entry) => { + const item = previous.find( + (old) => + !retained.has(old) && + (old.value === entry || + (path[2] === "ports" && + typeof old.value === "number" && + typeof entry === "string" && + String(old.value) === entry)) + ); + if (item) { + retained.add(item); + } + return item; + }); + const remaining = previous.filter((item) => !retained.has(item)); + node.items = value.map((entry, index) => { + const retainedItem = matching[index]; + if (retainedItem) { + return retainedItem; + } + const item = remaining.shift(); + if (!item) { + return doc.createNode(entry); + } + item.value = entry; + return item; + }); +} + +function composeFieldIssue( + source: ComposeSource, + path: string[], + message: string, + code = "E_CONFIG_INVALID" +): ConfigIssue { + const node = source.doc.getIn(path, true); + return { + layer: "2", + path, + line: + (isSeq(node) || isMap(node) || isScalar(node)) && node.range + ? source.lines.linePos(node.range[0]).line + : null, + code, + message, + }; +} + +/** Update only the label nodes in the parsed document, keeping pair/item order and comments. */ +export function changeComposeRoute(opts: { + readonly source: ComposeSource; + readonly service: string; + readonly sites: string; + readonly port: number; +}): boolean { + const { source, service, sites, port } = opts; + const path = ["services", service, "labels"]; + const model = source.services[service]; + const node = source.doc.getIn(path, true); + const rawService = source.doc.getIn(path.slice(0, -1), true); + if (!(isRecord(model) && isMap(rawService)) || rawService.has("<<")) { + return false; + } + const route = simpleRoute(model, composeLabels(model)); + if (!route) { + return false; + } + // Route edits contain the visible sites, so retain hidden sites on disk. + const privateSites = splitCaddySites(route.sites).filter((site) => + isConfigSecret("", site) + ); + const editedSites = + privateSites.length === 0 + ? sites + : [...new Set([...splitCaddySites(sites), ...privateSites])].join(", "); + const edits = new Map([ + ["caddy", editedSites], + ["caddy.reverse_proxy", `{{upstreams ${port}}}`], + ]); + if (isSeq(node)) { + updateComposeLabelList(node, edits); + return true; + } + if (node === undefined && model.labels === undefined) { + source.doc.setIn(path, Object.fromEntries(edits)); + return true; + } + if (!isMap(node) || node.has("<<")) { + return false; + } + for (const [key, value] of edits) { + node.set(key, value); + } + return true; +} + +function updateComposeLabelList( + node: YAMLSeq, + edits: Map +): void { + for (const item of node.items) { + if (isScalar(item) && typeof item.value === "string") { + const key = item.value.split("=", 1)[0] ?? ""; + const value = edits.get(key); + if (value !== undefined) { + item.value = `${key}=${value}`; + edits.delete(key); + } + } + } + for (const [key, value] of edits) { + node.add(`${key}=${value}`); + } +} diff --git a/src/lib/config-editor-model.ts b/src/lib/config-editor-model.ts new file mode 100644 index 0000000000..ad15c66d6c --- /dev/null +++ b/src/lib/config-editor-model.ts @@ -0,0 +1,855 @@ +import { constants } from "node:fs"; +import { access, lstat, open, realpath, stat } from "node:fs/promises"; +import { basename, dirname, relative, resolve } from "node:path"; +import { PROJECT_CONFIG_LEGACY_FILENAME } from "../constants.ts"; +import { autoWorktreeBranch, resolveEffectiveBranch } from "./branches.ts"; +import { HackCliError } from "./cli-result.ts"; +import { type ConfigIssue, composeModel } from "./config-editor-compose.ts"; +import { + configLine, + isConfigSecret, + isPrivateConfigOverlay, + isPrivateOverlayValue, + jsonConfigTree, + privateProjectOverlayNames, + safeJsonProject, + safeJsonSource, + safeYamlSource, +} from "./config-editor-source.ts"; +import { + assertEnvMigrationReadable, + EnvMigrationPendingError, +} from "./env-migration-state.ts"; +import { AtomicWriteConflictError } from "./fs.ts"; +import { listGitWorktrees } from "./git-worktree.ts"; +import { isRecord } from "./guards.ts"; +import { MACHINE_SCHEMAS } from "./machine-output.ts"; +import { + defaultProjectDevHost, + findProjectContext, + findProjectContextAtRoot, + legacyProjectDevHost, + type ProjectConfig, + type ProjectContext, + parseEnvConfigSelection, + parseProjectConfigRecord, + projectNameForConfig, + readAuthoredProjectOverlaySettings, + resolveProjectDefaultEnvOverlay, + resolveProjectOauthAliasHost, + resolveProjectRouteBaseHosts, + resolveWorktreeAutoBranch, + sanitizeBranchSlug, +} from "./project.ts"; +import { + listProjectEnvOverlays, + type ProjectEnvStoredValue, + parseProjectEnvConfigText, + resolveProjectEnvConfigPath, + resolveProjectEnvEffectiveLocalConfigPath, + resolveProjectEnvLocalConfigPath, + resolveProjectEnvSelection, +} from "./project-env-config.ts"; +import { assertProjectEnvLayerPath } from "./project-env-layer-path.ts"; +import { + resolvePrimaryLocalProjectDir, + validatePrimaryLocalFile, +} from "./worktree-local-config.ts"; + +export const CONFIG_EDITOR_SCHEMA = MACHINE_SCHEMAS.config; +export const CONFIG_SOURCE_LIMIT = 512 * 1024; + +type Layer = { + readonly id: string; + readonly file: string; + readonly kind: "project" | "compose" | "env" | "branch" | "internal"; + readonly ownership: "shared" | "local" | "generated"; + readonly active: boolean; + readonly inherited?: boolean; + readonly overlay?: string | null; +}; + +export type LayerSnapshot = Layer & { + readonly writable: boolean; + readonly revision: string; + readonly text: string | null; + readonly directory: ConfigDirectory | null; +}; + +type ConfigDirectory = { + readonly path: string; + readonly device: number; + readonly inode: number; +}; + +async function configDirectory(file: string): Promise { + try { + const path = await realpath(dirname(file)); + const info = await stat(path); + if (info.isDirectory()) { + return { path, device: info.dev, inode: info.ino }; + } + } catch (error) { + if (isRecord(error) && error.code === "ENOENT") { + return null; + } + } + throw new HackCliError({ + code: "E_PATH_CONFLICT", + message: "The config layer directory could not be verified.", + }); +} + +export async function assertConfigLayerDirectory( + layer: LayerSnapshot +): Promise { + const current = await configDirectory(layer.file).catch(() => null); + if ( + !current || + current.path !== layer.directory?.path || + current.device !== layer.directory.device || + current.inode !== layer.directory.inode + ) { + throw new AtomicWriteConflictError(); + } +} + +function configRevision( + layer: Layer, + project: ProjectContext, + text: string | null, + directory: ConfigDirectory | null +): string { + // Even an absent file belongs to one checkout and destination. + return new Bun.CryptoHasher("sha256") + .update( + JSON.stringify([ + project.projectRoot, + layer.file, + layer.ownership === "generated" ? null : directory, + text, + ]) + ) + .digest("hex"); +} + +export async function readConfigLayer(file: string): Promise { + try { + // A layer can be replaced by another editor between discovery and read. + // Read the opened object without following a swapped link or waiting on a pipe. + const handle = await open( + file, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK + ); + try { + const info = await handle.stat(); + if (!info.isFile() || info.size > CONFIG_SOURCE_LIMIT) { + throw new Error("Expected a bounded, regular config file."); + } + const bytes = Buffer.alloc( + Math.min(info.size + 1, CONFIG_SOURCE_LIMIT + 1) + ); + let length = 0; + while (length < bytes.length) { + const { bytesRead } = await handle.read( + bytes, + length, + bytes.length - length, + length + ); + if (bytesRead === 0) { + break; + } + length += bytesRead; + } + if (length === bytes.length) { + throw new Error("Config file grew while it was being read."); + } + return bytes.toString("utf8", 0, length); + } finally { + await handle.close(); + } + } catch (error) { + if (isRecord(error) && error.code === "ENOENT") { + return null; + } + throw new HackCliError({ + code: "E_PERMISSION", + message: "Could not read a regular config file within the size limit.", + }); + } +} + +async function writableLayer(layer: Layer, exists: boolean): Promise { + if (!layer.active || layer.inherited || layer.ownership === "generated") { + return false; + } + try { + await access(dirname(layer.file), constants.W_OK); + if (exists) { + await access(layer.file, constants.W_OK); + } + return true; + } catch { + return false; + } +} + +async function snapshotLayer( + layer: Layer, + project: ProjectContext +): Promise { + const root = layer.inherited + ? dirname(dirname(layer.file)) + : project.projectRoot; + if (layer.kind === "env") { + await assertProjectEnvLayerPath({ projectRoot: root, path: layer.file }); + if (layer.inherited) { + await validatePrimaryLocalFile(layer.file); + } + } + // Managed source paths can contain runtime state. Follow only real + // directories inside the selected checkout and never follow a leaf link. + const directory = await configDirectory(layer.file); + if ( + directory !== null && + directory.path !== + resolve( + await realpath(project.projectRoot), + relative(project.projectRoot, dirname(layer.file)) + ) && + !layer.inherited + ) { + throw new HackCliError({ + code: "E_PATH_CONFLICT", + message: "A config layer directory is linked outside its checkout.", + }); + } + const text = await readConfigLayer(layer.file); + return { + ...layer, + text, + directory, + revision: configRevision(layer, project, text, directory), + writable: await writableLayer(layer, text !== null), + }; +} + +async function selectedProject( + start: string, + requestedBranch: string | undefined +) { + const project = await findProjectContext(start); + const branch = requestedBranch?.trim(); + if (!(project && branch)) { + return { project, explicit: null }; + } + const slug = sanitizeBranchSlug(branch); + if (!slug) { + throw new HackCliError({ + code: "E_USAGE", + message: "Use a valid branch instance name.", + }); + } + const worktrees = await listGitWorktrees({ + repoRoot: project.projectRoot, + timeoutMs: 3000, + }); + // The primary checkout's git branch is the base instance. An explicit + // instance with the same name is only a linked checkout if Git lists one. + const linked = worktrees + ?.slice(1) + .find( + (entry) => + entry.branch && + (entry.branch === branch || + autoWorktreeBranch(entry.branch, worktrees) === branch) + ); + if (!linked) { + return { project, explicit: slug }; + } + const checkout = await findProjectContextAtRoot({ + projectRoot: linked.path, + projectDirName: project.projectDirName, + }); + if (!checkout) { + throw new HackCliError({ + code: "E_PROJECT_NOT_FOUND", + message: "The selected worktree has no Hack Compose config.", + }); + } + return { + project: checkout, + explicit: linked.branch + ? autoWorktreeBranch(linked.branch, worktrees) + : slug, + }; +} + +function envLayer(opts: { + readonly id: string; + readonly file: string; + readonly ownership: "local" | "shared"; + readonly overlay?: string | null; + readonly inherited?: boolean; + readonly active?: boolean; +}): Layer { + return { ...opts, kind: "env", active: opts.active ?? true }; +} + +async function readProjectLayer( + project: ProjectContext +): Promise { + const legacy = resolve(project.projectDir, PROJECT_CONFIG_LEGACY_FILENAME); + const json = await snapshotLayer( + { + id: "1", + file: project.configFile, + kind: "project", + ownership: "shared", + active: true, + }, + project + ); + if ( + json.text !== null || + !(await lstat(legacy).then( + () => true, + () => false + )) + ) { + return json; + } + return await snapshotLayer({ ...json, file: legacy }, project); +} + +async function configLayers(opts: { + readonly project: ProjectContext; + readonly projectLayer: LayerSnapshot; + readonly branch: string | null; + readonly overlay: string | null | undefined; + readonly defaultOverlay: string | null; + readonly privateOverlays: ReadonlySet; + readonly config: ProjectConfig; +}) { + const p = opts.project; + const defaultEnv = opts.defaultOverlay; + const inherited = await resolvePrimaryLocalProjectDir({ + ...p, + inheritLocal: opts.config.worktree?.inheritLocal !== false, + }); + await assertConfigEnvReadable(p.projectRoot, inherited); + const [env, overlays] = await Promise.all([ + resolveProjectEnvSelection({ ...p, envName: opts.overlay, defaultEnv }), + listProjectEnvOverlays({ ...p, defaultEnv, primaryDir: inherited }), + ]); + const overlay = env.effectiveEnv; + const names = [ + ...new Set([ + ...overlays.map((entry) => entry.name), + ...(overlay ? [overlay] : []), + ]), + ].filter( + (name) => + !isPrivateConfigOverlay(name, opts.privateOverlays) && + parseEnvConfigSelection(name) === name + ); + const layers: Layer[] = [ + { + id: "2", + file: p.composeFile, + kind: "compose", + ownership: "shared", + active: true, + }, + envLayer({ id: "3", file: env.defaultPath, ownership: "shared" }), + ]; + for (const name of names) { + const file = resolveProjectEnvConfigPath({ + projectDir: p.projectDir, + envName: name, + }); + if (file === env.localDefaultPath || file === env.defaultPath) { + continue; + } + layers.push( + envLayer({ + id: `3:${name}`, + file, + ownership: "shared", + overlay: name, + active: name === overlay, + }) + ); + } + if (inherited) { + layers.push( + envLayer({ + id: "4", + ownership: "local", + inherited: true, + file: await resolveProjectEnvEffectiveLocalConfigPath({ + projectRoot: dirname(inherited), + projectDir: inherited, + envName: null, + }), + }) + ); + if (overlay) { + layers.push( + envLayer({ + id: `4:${overlay}`, + ownership: "local", + inherited: true, + overlay, + file: resolveProjectEnvLocalConfigPath({ + projectDir: inherited, + envName: overlay, + }), + }) + ); + } + } + layers.push( + envLayer({ id: "5", file: env.localDefaultPath, ownership: "local" }) + ); + if (overlay && env.localOverlayPath) { + layers.push( + envLayer({ + id: `5:${overlay}`, + file: env.localOverlayPath, + ownership: "local", + overlay, + }) + ); + } + if (opts.branch) { + layers.push({ + id: "6", + file: resolve( + p.projectDir, + ".branch", + `compose.${opts.branch}.override.yml` + ), + kind: "branch", + ownership: "generated", + active: true, + }); + } + layers.push( + { + id: "7", + file: resolve(p.projectDir, ".internal", "compose.override.yml"), + kind: "internal", + ownership: "generated", + active: true, + }, + { + id: "8", + file: resolve(p.projectDir, ".internal", "extra-hosts.json"), + kind: "internal", + ownership: "generated", + active: true, + } + ); + return { + layers: [ + opts.projectLayer, + ...(await Promise.all(layers.map((layer) => snapshotLayer(layer, p)))), + ], + overlay, + overlays: names, + }; +} + +export async function assertConfigEnvReadable( + projectRoot: string, + inherited: string | null +): Promise { + try { + await assertEnvMigrationReadable({ projectRoot }); + if (inherited) { + await assertEnvMigrationReadable({ projectRoot: dirname(inherited) }); + } + } catch (error) { + throw new HackCliError({ + code: "E_CONFIG_INVALID", + message: + error instanceof EnvMigrationPendingError + ? error.message + : "The env migration journal could not be verified.", + }); + } +} + +export async function readConfigEditor(opts: { + readonly start: string; + readonly branch: string | undefined; + readonly overlay: string | null | undefined; +}) { + const { project, explicit } = await selectedProject(opts.start, opts.branch); + if (!project) { + return null; + } + return await captureConfigEditor({ + project, + projectLayer: await readProjectLayer(project), + explicitBranch: explicit, + requestedOverlay: opts.overlay, + }); +} + +function configOverlaySelection( + raw: Record, + config: ProjectConfig, + requested: string | null | undefined +) { + const configured = resolveProjectDefaultEnvOverlay(config); + const { current, legacy } = readAuthoredProjectOverlaySettings(raw); + const authoredDefault = config.env?.defaultOverlay + ? (current[0] ?? current[1]) + : (legacy[0] ?? legacy[1]); + // Even an overridden alias may have a layer on disk under its normalized name. + const privateOverlays = privateProjectOverlayNames(raw); + const redactDefault = + isConfigSecret("", authoredDefault) || + (configured !== null && + isPrivateConfigOverlay(configured, privateOverlays)); + return { + privateOverlays, + defaultOverlay: redactDefault ? null : configured, + displayDefault: redactDefault ? "[redacted]" : (configured ?? "default"), + requested: + typeof requested === "string" && + isPrivateConfigOverlay(requested, privateOverlays) + ? null + : requested, + }; +} + +/** Observe the selected layers using the supplied, possibly edited project file. */ +export async function captureConfigEditor(opts: { + readonly project: ProjectContext; + readonly projectLayer: LayerSnapshot; + readonly explicitBranch: string | null; + readonly requestedOverlay: string | null | undefined; +}) { + const { project, projectLayer, explicitBranch } = opts; + const raw = parseProjectLayer(projectLayer); + if (raw !== null) { + await assertConfigEnvReadable(project.projectRoot, null); + } + const cfg = parseProjectConfigRecord(raw ?? {}, projectLayer.file); + const selection = configOverlaySelection( + raw ?? {}, + cfg, + opts.requestedOverlay + ); + const branch = ( + await resolveEffectiveBranch({ + explicitBranch, + projectRoot: project.projectRoot, + autoBranchEnabled: resolveWorktreeAutoBranch(cfg), + }) + ).branch; + const devHost = + cfg.devHost ?? + (raw !== null + ? legacyProjectDevHost(await readConfigLayer(project.envFile)) + : null) ?? + (branch === null ? defaultProjectDevHost(project.projectRoot) : null); + const baseHosts = devHost + ? resolveProjectRouteBaseHosts({ + devHost, + aliasHost: resolveProjectOauthAliasHost({ oauth: cfg.oauth, devHost }), + }) + : []; + const layers = + raw === null + ? { + layers: [projectLayer], + overlay: selection.requested ?? null, + overlays: [], + } + : await configLayers({ + project, + projectLayer, + branch, + overlay: selection.requested, + defaultOverlay: selection.defaultOverlay, + privateOverlays: selection.privateOverlays, + config: cfg, + }); + return { + ...layers, + project, + projectName: projectNameForConfig(cfg, project.projectRoot), + branch, + baseHosts, + defaultOverlay: raw === null ? null : selection.displayDefault, + privateOverlays: selection.privateOverlays, + explicitBranch, + requestedOverlay: selection.requested, + }; +} + +export type ConfigSnapshot = NonNullable< + Awaited> +>; + +function parseProjectLayer( + layer: LayerSnapshot +): Record | null { + if (layer.text === null) { + return {}; + } + if (!(layer.file.endsWith(".toml") || jsonConfigTree(layer.text).ok)) { + return null; + } + try { + const raw: unknown = layer.file.endsWith(".toml") + ? Bun.TOML.parse(layer.text) + : JSON.parse(layer.text); + return isRecord(raw) ? raw : null; + } catch { + return null; + } +} + +function projectModel( + layer: LayerSnapshot, + issues: ConfigIssue[] +): Record { + if (layer.text === null) { + return {}; + } + if (basename(layer.file) === PROJECT_CONFIG_LEGACY_FILENAME) { + try { + const raw: unknown = Bun.TOML.parse(layer.text); + return isRecord(raw) + ? scrubLegacyProject(raw, privateProjectOverlayNames(raw)) + : {}; + } catch { + issues.push({ + layer: layer.id, + path: [], + line: 1, + code: "E_CONFIG_PARSE", + message: "Invalid project TOML.", + }); + return {}; + } + } + const safe = safeJsonProject(layer.text); + if (safe === null) { + const tree = jsonConfigTree(layer.text); + issues.push({ + layer: layer.id, + path: [], + line: configLine( + layer.text, + tree.duplicate?.offset ?? tree.error?.offset ?? 0 + ), + code: "E_CONFIG_PARSE", + message: tree.duplicate + ? "Each JSON field must appear once." + : "Expected a valid JSON object.", + }); + return {}; + } + return safe; +} + +function scrubLegacyProject( + record: Record, + privateOverlays: ReadonlySet +): Record { + return Object.fromEntries( + Object.entries(record).flatMap(([key, value]) => { + if (isConfigSecret("", key)) { + return []; + } + const publicOauth = key === "oauth" && isRecord(value); + if ( + ["startup", "lifecycle"].includes(key) || + isPrivateOverlayValue(value, privateOverlays) || + (isConfigSecret(key, value) && !publicOauth) + ) { + return [[key, "[redacted]"]]; + } + if (isRecord(value)) { + return [[key, scrubLegacyProject(value, privateOverlays)]]; + } + return Array.isArray(value) ? [] : [[key, value]]; + }) + ); +} + +function publicLayer( + layer: LayerSnapshot, + privateKeys: ReadonlySet, + invalid: boolean +) { + const { text, directory: _directory, ...rest } = layer; + const legacy = basename(layer.file) === PROJECT_CONFIG_LEGACY_FILENAME; + let source = { source: null as string | null, hidden: legacy || invalid }; + if (text !== null && !(legacy || invalid)) { + source = layer.file.endsWith(".json") + ? safeJsonSource(text) + : safeYamlSource( + text, + layer.kind !== "env", + layer.kind === "env" ? privateKeys : undefined + ); + } + return { + ...rest, + ...source, + exists: text !== null, + writable: layer.writable && !legacy, + source_writable: + layer.writable && + source.source !== null && + (layer.kind === "project" || layer.kind === "compose"), + }; +} + +type EnvEntry = { + layer: string; + secret: boolean; + value?: string | number | boolean; + unset?: boolean; +}; +type EnvRow = { + key: string; + scope: string; + values: EnvEntry[]; + winning: string | null; +}; + +function addEnvLayer(opts: { + readonly rows: Map; + readonly layer: string; + readonly scope: string; + readonly values: Readonly>; + readonly privateKeys: Set; +}): void { + for (const [key, value] of Object.entries(opts.values)) { + if (isConfigSecret("", key)) { + continue; + } + const id = `${opts.scope}/${key}`; + const row = opts.rows.get(id) ?? { + key, + scope: opts.scope, + values: [], + winning: null, + }; + const base = { layer: opts.layer, secret: false }; + if (value === null) { + row.values.push({ ...base, unset: true }); + } else if (typeof value === "object" || isConfigSecret(key, value)) { + opts.privateKeys.add(key); + row.values.push({ ...base, secret: true }); + } else { + row.values.push({ ...base, value }); + } + row.winning = value === null ? null : opts.layer; + opts.rows.set(id, row); + } +} + +function envModel(layers: readonly LayerSnapshot[], issues: ConfigIssue[]) { + const rows = new Map(); + const privateKeys = new Set(); + for (const layer of layers) { + if (layer.kind !== "env" || !layer.active || layer.text === null) { + continue; + } + const read = parseProjectEnvConfigText({ + path: layer.file, + environment: layer.overlay ?? "default", + text: layer.text, + }); + if (read.parseError) { + issues.push({ + layer: layer.id, + path: [], + line: null, + code: "E_CONFIG_PARSE", + message: "Check the env YAML and its values.", + }); + continue; + } + for (const [scope, values] of Object.entries(read.config.values)) { + if (!isConfigSecret("", scope)) { + addEnvLayer({ rows, layer: layer.id, scope, values, privateKeys }); + } + } + } + const env = [...rows.values()].map((row) => { + if (!privateKeys.has(row.key)) { + return row; + } + return { + ...row, + values: row.values.map((cell) => + cell.unset ? cell : { layer: cell.layer, secret: true } + ), + }; + }); + return { env, privateKeys }; +} + +export function showConfigEditor(snapshot: ConfigSnapshot | null) { + const issues: ConfigIssue[] = []; + const layers = snapshot?.layers ?? []; + const projectLayer = layers.find((layer) => layer.id === "1"); + const compose = layers.find((layer) => layer.id === "2"); + const project = projectLayer ? projectModel(projectLayer, issues) : {}; + const missingBranchHost = snapshot?.branch && snapshot.baseHosts.length === 0; + if (missingBranchHost && issues.length === 0) { + issues.push({ + layer: "1", + path: ["dev_host"], + line: null, + code: "E_CONFIG_INVALID", + message: "Set dev_host before starting or restarting this branch.", + }); + } + const result = + compose?.text != null && snapshot + ? composeModel({ + text: compose.text, + branch: snapshot.branch, + baseHosts: snapshot.baseHosts, + }) + : { services: [], issues: [] }; + issues.push(...result.issues); + const { env, privateKeys } = envModel(layers, issues); + const invalid = issues.some((issue) => issue.code === "E_CONFIG_PARSE"); + const state = snapshot ? "ready" : "missing"; + return { + schema: CONFIG_EDITOR_SCHEMA, + state: invalid ? "invalid" : state, + project, + services: result.services, + env, + issues, + layers: layers.map((layer) => + publicLayer( + layer, + privateKeys, + issues.some( + (issue) => issue.layer === layer.id && issue.code === "E_CONFIG_PARSE" + ) + ) + ), + branch: snapshot?.branch ?? null, + overlay: snapshot?.overlay ?? null, + default_overlay: snapshot?.defaultOverlay ?? null, + overlays: snapshot?.overlays ?? [], + checkout: snapshot?.project.projectRoot ?? null, + writable: layers.some((layer) => layer.writable), + }; +} diff --git a/src/lib/config-editor-patch.ts b/src/lib/config-editor-patch.ts new file mode 100644 index 0000000000..393514948e --- /dev/null +++ b/src/lib/config-editor-patch.ts @@ -0,0 +1,1379 @@ +import { lstat } from "node:fs/promises"; +import { basename, dirname, resolve } from "node:path"; +import { isDeepStrictEqual } from "node:util"; +import { applyEdits, findNodeAtLocation, modify } from "jsonc-parser"; +import { z } from "zod"; +import { + ClosedCliError, + HackCliError, + type HackErrorCode, +} from "./cli-result.ts"; +import { + type ConfigIssue, + changeComposeRoute, + editableComposeField, + parseComposeSource, + parseRouteAddress, + updateComposeServiceField, + validComposePort, + validHost, + validPort, +} from "./config-editor-compose.ts"; +import { + assertConfigEnvReadable, + assertConfigLayerDirectory, + CONFIG_EDITOR_SCHEMA, + CONFIG_SOURCE_LIMIT, + type ConfigSnapshot, + captureConfigEditor, + type LayerSnapshot, + readConfigLayer, + showConfigEditor, +} from "./config-editor-model.ts"; +import { + configLine, + hasPrivateOverlayValue, + isConfigSecret, + isPrivateConfigOverlay, + jsonConfigDiagnostic, + jsonConfigTree, + privateProjectOverlayNames, + redactConfigPath, + restoreConfigSource, +} from "./config-editor-source.ts"; +import { + PRIVATE_OVERLAY_MIGRATION_CONFLICT, + privateOverlayFileConflict, +} from "./config-overlay-files.ts"; +import { withEnvLayerLock } from "./env-layer-lock.ts"; +import { + applyEnvMigration, + assertEnvMigrationConsent, + type ImplicitEnvMigrationPlan, + type MigrationConfigWrite, + prepareImplicitEnvMigration, + withEnvMigrationConfigEdits, +} from "./env-migration.ts"; +import { migrationDigest } from "./env-migration-files.ts"; +import { envMigrationSnapshots } from "./env-migration-snapshot.ts"; +import { + AtomicWriteConflictError, + writeTextFileAtomicIfChanged, +} from "./fs.ts"; +import { isRecord } from "./guards.ts"; +import { readHackEnvContract, readHackEnvRuntimeConfig } from "./hack-env.ts"; +import { + ENV_BASE_SELECTION_ALIASES, + ENV_CONFIG_NAME_MAX_LENGTH, + parseEnvConfigSelection, + parseProjectConfigRecord, +} from "./project.ts"; +import { + discoverComposeServiceNames, + isGitIgnoredProjectEnvPath, + isValidProjectEnvScopeName, + mutateProjectEnvLayer, + type ProjectEnvLayerChange, + preflightLegacyEnvContract, + projectEnvConfigExistsForMutation, + projectEnvLayerFits, +} from "./project-env-config.ts"; +import { assertLegacyProjectDirectory } from "./project-input-selection.ts"; +import { resolveFileSecretStorePaths } from "./secret-store.ts"; + +const BASE_REV = /^[a-f0-9]{64}$/; +const ENV_KEY = /^[A-Z_][A-Z0-9_]*$/; +const SERVICE = /^[\w.-]+$/; +const HOSTS = /[\s,]+/; +const PRIVATE_OVERLAY_CONFLICT_MESSAGES = { + existing: + "Move or rename the env layer with a private filename before replacing this setting.", + planned: PRIVATE_OVERLAY_MIGRATION_CONFLICT, +}; +const layerId = z.string().max(ENV_CONFIG_NAME_MAX_LENGTH + "3:".length); +const serviceName = z.string().max(160).regex(SERVICE); + +const changeSchema = z.discriminatedUnion("kind", [ + z.object({ + layer: layerId, + kind: z.literal("project"), + path: z.string().max(120), + value: z.union([z.string(), z.boolean()]), + }), + z.object({ + layer: layerId, + kind: z.literal("route"), + service: serviceName, + sites: z.string(), + port: z.union([z.number(), z.string()]), + }), + z.object({ + layer: layerId, + kind: z.literal("service"), + service: serviceName, + field: z.enum(["image", "ports", "depends_on"]), + value: z.union([z.string(), z.array(z.union([z.string(), z.number()]))]), + }), + z.object({ + layer: layerId, + kind: z.literal("env"), + scope: z.string().max(160), + key: z.string().max(160).regex(ENV_KEY), + value: z.string().nullable(), + secret: z.boolean().default(false), + }), + z.object({ + layer: layerId, + kind: z.literal("source"), + text: z.string().max(CONFIG_SOURCE_LIMIT), + }), +]); +const patchSchema = z.object({ + base: z.record(layerId, z.string().regex(BASE_REV)), + changes: z.array(changeSchema).max(200), +}); +type Patch = z.infer; +type Change = z.infer; + +export function readConfigPatch(input: string): Patch { + try { + const result = patchSchema.safeParse(JSON.parse(input)); + if (result.success) { + return result.data; + } + } catch { + // JSON and schema errors can contain input values. + } + throw new HackCliError({ + code: "E_USAGE", + message: "Expected a config patch with base revisions and a changes array.", + }); +} + +type Prepared = { + readonly layer: LayerSnapshot; + text: string | null; + readonly env: ProjectEnvLayerChange[]; + source: boolean; +}; + +function configIssue( + change: Change, + path: readonly string[], + message: string, + code: HackErrorCode = "E_CONFIG_INVALID", + line: number | null = null +): ConfigIssue { + return { + layer: publicPatchLayerId(change.layer), + path: redactConfigPath(path), + message, + code, + line, + }; +} + +function publicPatchLayerId(id: string): string { + return isConfigSecret("", id) ? "[redacted]" : id; +} + +const PROJECT_TOGGLES = new Set([ + "internal.dns", + "internal.tls", + "oauth.enabled", + "worktree.auto_branch", + "worktree.inherit_local", + "logs.clear_on_down", +]); +const PROJECT_STRINGS = new Set([ + "name", + "dev_host", + "oauth.tld", + "open.prefer", + "logs.follow_backend", + "logs.snapshot_backend", + "logs.retention_period", + "env.defaultOverlay", +]); + +function projectFieldError(path: string, value: unknown): string | null { + if (PROJECT_TOGGLES.has(path)) { + return typeof value === "boolean" ? null : "Choose on or off."; + } + if (!PROJECT_STRINGS.has(path) || typeof value !== "string") { + return "This field is edited in Source."; + } + if (path === "dev_host" || path === "oauth.tld") { + return validHost(value) && (path === "oauth.tld" || value.includes(".")) + ? null + : "Use letters, digits, dots and dashes, such as storefront.hack."; + } + if (path === "name" && !SERVICE.test(value)) { + return "Use letters, digits, dots, underscores and dashes."; + } + if ( + path === "env.defaultOverlay" && + !ENV_BASE_SELECTION_ALIASES.has(value) && + parseEnvConfigSelection(value) !== value + ) { + return "Use up to 128 lowercase letters, digits and dashes, or enter default for base layers."; + } + if (path === "open.prefer" && !["auto", "dev", "alias"].includes(value)) { + return "Choose auto, dev or alias."; + } + if (path.endsWith("_backend") && !["compose", "loki"].includes(value)) { + return "Choose compose or loki."; + } + return null; +} + +function prepareProjectField( + change: Extract, + file: Prepared +) { + const path = change.path.split("."); + const text = file.text ?? "{}\n"; + const tree = jsonConfigTree(text); + const node = tree.root ? findNodeAtLocation(tree.root, path) : undefined; + const line = node ? configLine(text, node.offset) : null; + const error = projectFieldError(change.path, change.value); + if (error || !tree.ok) { + return configIssue( + change, + path, + error ?? "Fix the JSON in Source first.", + "E_CONFIG_INVALID", + line + ); + } + try { + file.text = applyEdits( + text, + modify(text, path, change.value, { + formattingOptions: { insertSpaces: true, tabSize: 2 }, + }) + ); + return null; + } catch { + return configIssue( + change, + path, + "The parent field must be an object.", + "E_CONFIG_INVALID", + line + ); + } +} + +function prepareRoute( + change: Extract, + file: Prepared +) { + const path = ["services", change.service, "route"]; + const addresses = change.sites.trim().split(HOSTS).filter(Boolean); + if (addresses.length === 0 || !addresses.every(parseRouteAddress)) { + return configIssue( + change, + path, + "Enter valid hostnames separated by commas." + ); + } + const port = Number(change.port); + if (!validPort(port)) { + return configIssue( + change, + [...path, "port"], + "Use a port between 1 and 65535." + ); + } + const source = parseComposeSource(file.text ?? ""); + if ( + source.invalid !== null || + !changeComposeRoute({ + source, + service: change.service, + sites: addresses.join(", "), + port, + }) + ) { + return configIssue(change, path, "Edit this route in Source."); + } + file.text = source.doc.toString({ lineWidth: 0 }); + return null; +} + +function prepareService( + change: Extract, + file: Prepared +) { + const path = ["services", change.service, change.field]; + const source = parseComposeSource(file.text ?? ""); + if ( + source.invalid !== null || + !Object.hasOwn(source.services, change.service) + ) { + return configIssue( + change, + path, + "Choose a service from this Compose file." + ); + } + if ( + !editableComposeField({ + source, + service: change.service, + field: change.field, + }) + ) { + return configIssue(change, path, "Edit this service field in Source."); + } + if (change.field === "image") { + if ( + typeof change.value !== "string" || + !change.value.trim() || + isConfigSecret("", change.value) + ) { + return configIssue(change, path, "Enter a container image reference."); + } + } else if ( + !( + Array.isArray(change.value) && + change.value.every((value) => + change.field === "ports" + ? validComposePort(value) + : typeof value === "string" && Object.hasOwn(source.services, value) + ) + ) + ) { + return configIssue( + change, + path, + change.field === "ports" + ? "Enter Compose port mappings." + : "Choose services defined in this Compose file." + ); + } + try { + updateComposeServiceField({ source, path, value: change.value }); + file.text = source.doc.toString({ lineWidth: 0 }); + return null; + } catch { + return configIssue(change, path, "Edit this service in Source."); + } +} + +function prepareSource( + change: Extract, + file: Prepared +) { + if (file.layer.kind === "env") { + return configIssue( + change, + [], + "Edit values in Env layers.", + "E_LAYER_READ_ONLY" + ); + } + const json = file.layer.kind === "project"; + // Diagnose a syntactically invalid draft without passing it to an output + // path that could render a pasted credential from the invalid source. + const invalid = json + ? jsonConfigDiagnostic(change.text) + : composeSourceDiagnostic(change.text); + if (invalid) { + return configIssue( + change, + [], + invalid.message, + "E_CONFIG_PARSE", + invalid.line + ); + } + const restored = restoreConfigSource({ + original: file.layer.text ?? (json ? "{}" : "services: {}"), + draft: change.text, + format: json ? "json" : "yaml", + }); + if (restored === null) { + return configIssue( + change, + [], + "Keep private fields in place or open the file in your editor." + ); + } + file.text = restored; + file.source = true; + return null; +} + +function composeSourceDiagnostic(text: string) { + const line = parseComposeSource(text).invalid; + return line === null + ? null + : { line, message: "Expected valid Compose YAML." }; +} + +function prepareEnv(change: Extract, file: Prepared) { + const path = ["values", change.scope, change.key]; + if (!isValidProjectEnvScopeName({ scopeName: change.scope })) { + return configIssue(change, path, "Choose a valid env scope."); + } + if ( + change.value !== null && + !change.secret && + isConfigSecret(change.key, change.value) + ) { + return configIssue(change, path, "Set this value as a secret."); + } + const { key, scope } = change; + file.env.push( + change.value === null + ? { key, scope, op: "unset" } + : { key, scope, op: "set", value: change.value, secret: change.secret } + ); + return null; +} + +function matchesLayer(change: Change, layer: LayerSnapshot) { + switch (change.kind) { + case "project": + return layer.kind === "project"; + case "route": + case "service": + return layer.kind === "compose"; + case "env": + return layer.kind === "env"; + case "source": + return ( + layer.kind === "project" || + layer.kind === "compose" || + layer.kind === "env" + ); + default: + return false; + } +} + +function prepareChange(change: Change, file: Prepared) { + switch (change.kind) { + case "project": + return prepareProjectField(change, file); + case "route": + return prepareRoute(change, file); + case "service": + return prepareService(change, file); + case "env": + return prepareEnv(change, file); + case "source": + return prepareSource(change, file); + default: + return null; + } +} + +function preparePatch(snapshot: ConfigSnapshot, patch: Patch) { + const issues: ConfigIssue[] = []; + const files = new Map(); + // Check every supplied base, including dependencies of the patched file. + for (const [id, base] of Object.entries(patch.base)) { + const layer = snapshot.layers.find((entry) => entry.id === id); + if (layer?.revision !== base) { + issues.push({ + layer: publicPatchLayerId(id), + path: [], + line: null, + code: "E_CONFLICT", + message: "Changed outside Hack. Reload before saving.", + }); + } + } + if (issues.length > 0) { + return { files, issues }; + } + for (const change of patch.changes) { + const layer = snapshot.layers.find((entry) => entry.id === change.layer); + const mixed = patch.changes.some( + (other) => + other !== change && + other.layer === change.layer && + (other.kind === "source" || change.kind === "source") + ); + if (!layer?.writable || layer.file.endsWith(".toml")) { + issues.push( + configIssue(change, [], "This layer is read-only.", "E_LAYER_READ_ONLY") + ); + } else if (patch.base[layer.id] === undefined) { + issues.push( + configIssue( + change, + [], + "Include the layer's base revision.", + "E_CONFLICT" + ) + ); + } else if (mixed) { + issues.push( + configIssue( + change, + [], + "Use one Source replacement or structured changes for this file." + ) + ); + } else if (matchesLayer(change, layer)) { + const file = files.get(layer.id) ?? { + layer, + text: layer.text, + source: false, + env: [], + }; + const issue = prepareChange(change, file); + if (issue) { + issues.push(issue); + } + files.set(layer.id, file); + } else { + issues.push( + configIssue(change, [], "This change belongs in a different layer.") + ); + } + } + return { files, issues }; +} + +async function prospectiveSnapshot( + snapshot: ConfigSnapshot, + files: Map +) { + const project = files.get("1"); + const prospective = + project?.text !== undefined && project.text !== project.layer.text + ? await captureConfigEditor({ + ...snapshot, + projectLayer: { ...project.layer, text: project.text }, + }) + : snapshot; + const layers = prospective.layers.map((layer) => { + const file = files.get(layer.id); + return file && file.layer.file === layer.file + ? { ...layer, text: file.text } + : layer; + }); + return { ...prospective, layers }; +} + +function sourceIssues(files: Map): ConfigIssue[] { + const project = files.get("1"); + if (!(project?.source && project.text && jsonConfigTree(project.text).ok)) { + return []; + } + const parsed: unknown = JSON.parse(project.text); + const issues: ConfigIssue[] = []; + const tree = jsonConfigTree(project.text); + for (const field of [...PROJECT_TOGGLES, ...PROJECT_STRINGS]) { + const path = field.split("."); + const node = tree.root && findNodeAtLocation(tree.root, path); + if (!node) { + continue; + } + const message = projectFieldError(field, node.value); + if (message) { + issues.push({ + layer: "1", + path, + line: configLine(project.text, node.offset), + code: "E_CONFIG_INVALID", + message, + }); + } + } + if (parseProjectConfigRecord(parsed, project.layer.file).parseError) { + issues.push({ + layer: "1", + path: [], + line: 1, + code: "E_CONFIG_INVALID", + message: "Check the project settings and their types.", + }); + } + return issues; +} + +function removedPrivateOverlays( + before: ConfigSnapshot, + remaining: ReadonlySet +): string[] { + return [...before.privateOverlays].filter((name) => !remaining.has(name)); +} + +/** An existing legacy store may have undiscovered overlays. Inspect metadata only. */ +async function legacyStoreMayContainOverlays( + snapshot: ConfigSnapshot +): Promise { + const { project } = snapshot; + const legacy = await readHackEnvContract(project); + if (!legacy.exists) { + return false; + } + if ( + await projectEnvConfigExistsForMutation({ + ...project, + inheritLocal: inheritedEnvDir(snapshot) !== null, + }) + ) { + return false; + } + const { active, storePath } = await resolveFileSecretStorePaths({ + projectDir: project.projectDir, + strict: true, + }); + if (!active) { + return false; + } + const usesStore = + legacy.parseError || + legacy.contract.vars.some(({ source }) => source === "keychain") || + (await readHackEnvRuntimeConfig(project)).storePlaintextInBackend; + if (!usesStore) { + return false; + } + const store = await lstat(storePath).catch((error: unknown) => { + if (isRecord(error) && error.code === "ENOENT") { + return null; + } + throw error; + }); + return store !== null && (!store.isFile() || store.size > 0); +} + +async function privateOverlayReplacementMessage(opts: { + readonly before: ConfigSnapshot; + readonly after: ConfigSnapshot; + readonly projectText: string | null | undefined; + readonly outputs: ReadonlyMap | null; +}): Promise { + const { before, after, projectText, outputs } = opts; + if (before.privateOverlays.size === 0) { + return null; + } + const layer = before.layers.find(({ id }) => id === "1"); + const migrationText = layer && outputs?.get(layerDestination(layer)); + for (const text of [migrationText, projectText]) { + if (!(text && jsonConfigTree(text).ok)) { + continue; + } + const project: unknown = JSON.parse(text); + if (!isRecord(project)) { + continue; + } + const removed = removedPrivateOverlays( + before, + privateProjectOverlayNames(project) + ); + if (removed.length === 0) { + continue; + } + if (hasPrivateOverlayValue(project, new Set(removed))) { + return "Remove the remaining private overlay reference before replacing this setting."; + } + try { + const conflict = await privateOverlayFileConflict({ + projectDir: before.project.projectDir, + inheritedDirs: [inheritedEnvDir(before), inheritedEnvDir(after)], + names: removed, + planned: outputs, + }); + if (conflict) { + return PRIVATE_OVERLAY_CONFLICT_MESSAGES[conflict]; + } + if (!outputs && (await legacyStoreMayContainOverlays(after))) { + return "The legacy secret store may contain this overlay. Migrate the legacy env before replacing this setting."; + } + } catch { + return "Could not verify the private env inputs before replacing this setting."; + } + } + return null; +} + +function layerSizeIssues( + snapshot: ConfigSnapshot, + files: Map, + envOnly: boolean +): ConfigIssue[] { + const inheritsLocal = snapshot.layers.some((layer) => layer.inherited); + return [...files.values()].flatMap(({ layer, text, env }) => { + if ((layer.kind === "env") !== envOnly) { + return []; + } + const fits = + layer.kind === "env" + ? projectEnvLayerFits({ + path: layer.file, + text, + envName: layer.overlay ?? null, + changes: env, + inheritsLocal: layer.ownership === "local" && inheritsLocal, + maxBytes: CONFIG_SOURCE_LIMIT, + }) + : text === null || Buffer.byteLength(text) <= CONFIG_SOURCE_LIMIT; + return fits + ? [] + : [ + { + layer: layer.id, + path: [], + line: null, + code: "E_CONFIG_INVALID", + message: "The updated file exceeds the 512 KiB limit.", + }, + ]; + }); +} + +export async function assessConfigPatch( + snapshot: ConfigSnapshot, + patch: Patch, + mode: "validate" | "apply" = "validate" +) { + const initial = preparePatch(snapshot, patch); + const { issues } = initial; + const invalid = { + files: initial.files, + previews: {}, + prospective: snapshot, + migration: null, + }; + if (issues.some((issue) => issue.code === "E_CONFLICT")) { + return { ...invalid, issues }; + } + // Bound staged text before deriving a new selection from it. + const sizeIssues = layerSizeIssues(snapshot, initial.files, false); + if (sizeIssues.length > 0) { + return { ...invalid, issues: [...issues, ...sizeIssues] }; + } + const { migration, outputs, issue } = + issues.length === 0 + ? await stageConfigMigration(snapshot, initial.files, mode) + : { migration: null, outputs: null, issue: undefined }; + if (issue) { + return { ...invalid, issues: [...issues, issue] }; + } + const files = outputs + ? prepareAfterMigration({ files: initial.files, outputs, patch, issues }) + : initial.files; + const projectSizes = outputs ? layerSizeIssues(snapshot, files, false) : []; + if (projectSizes.length > 0) { + return { ...invalid, issues: [...issues, ...projectSizes] }; + } + const prospective = await prospectiveSnapshot(snapshot, files); + const privateOverlayIssue = await privateOverlayReplacementMessage({ + before: snapshot, + after: prospective, + projectText: files.get("1")?.text, + outputs, + }); + if (privateOverlayIssue) { + return { + ...invalid, + issues: [ + ...issues, + { + layer: "1", + path: ["env", "defaultOverlay"], + line: null, + code: "E_CONFIG_INVALID", + message: privateOverlayIssue, + } satisfies ConfigIssue, + ], + }; + } + const envSizes = layerSizeIssues(prospective, files, true); + if (envSizes.length > 0) { + return { ...invalid, issues: [...issues, ...envSizes] }; + } + const next = showConfigEditor(prospective); + const previews = Object.fromEntries( + next.layers + .filter((layer) => files.has(layer.id) && layer.kind !== "env") + .map(({ id, source }) => [id, source]) + ); + return { + files, + prospective, + migration, + previews, + issues: [...issues, ...sourceIssues(files), ...next.issues], + }; +} + +function layerDestination(layer: LayerSnapshot): string { + return resolve( + layer.directory?.path ?? dirname(layer.file), + basename(layer.file) + ); +} + +async function writesLocalEnvForMigration( + projectRoot: string, + inheritLocal: boolean, + files: ReadonlyMap +): Promise { + const localFiles = [...files.values()].filter( + ({ layer, env }) => + layer.kind === "env" && layer.ownership === "local" && env.length > 0 + ); + if (localFiles.some(({ env }) => env.some(({ op }) => op === "set"))) { + return true; + } + // A linked unset writes a null override. It only needs a repair when the + // destination is missing effective ignore coverage. + if (inheritLocal) { + for (const { layer } of localFiles) { + if ( + (await isGitIgnoredProjectEnvPath({ + projectRoot, + path: layerDestination(layer), + })) !== true + ) { + return true; + } + } + } + return false; +} + +async function stageConfigMigration( + snapshot: ConfigSnapshot, + files: Map, + mode: "validate" | "apply" +): Promise<{ + migration: ImplicitEnvMigrationPlan | null; + outputs: ReadonlyMap | null; + issue?: ConfigIssue; +}> { + const env = [...files.values()].find(({ layer }) => layer.kind === "env"); + if (!env) { + return { migration: null, outputs: null }; + } + const { project } = snapshot; + try { + await assertConfigLayerDirectory(env.layer); + const prospective = await prospectiveSnapshot(snapshot, files); + const inheritLocal = prospective.layers.some(({ inherited }) => inherited); + if (await projectEnvConfigExistsForMutation({ ...project, inheritLocal })) { + return { migration: null, outputs: null }; + } + const legacy = await readHackEnvContract(project); + if (!legacy.exists) { + return { migration: null, outputs: null }; + } + if (legacy.parseError) { + throw new ClosedCliError( + "Fix the legacy env contract before saving env changes." + ); + } + const writesLocalEnv = await writesLocalEnvForMigration( + project.projectRoot, + inheritLocal, + files + ); + if (mode === "validate") { + const outputs = await preflightLegacyEnvContract({ + ...project, + contract: legacy.contract, + projectText: + snapshot.layers.find( + ({ id, file }) => + id === "1" && basename(file) === "hack.config.json" + )?.text ?? null, + writesLocalEnv, + maxLayerBytes: CONFIG_SOURCE_LIMIT, + }); + await assertEnvMigrationConsent(project, [...outputs.keys()], false); + return { migration: null, outputs }; + } + const migration = await prepareImplicitEnvMigration( + { + ...project, + projectName: snapshot.projectName, + serviceNames: await discoverComposeServiceNames({ + composeFile: project.composeFile, + }), + }, + { + writesLocalEnv, + inheritLocal, + edits: [...files.values()].map(({ layer }) => ({ + path: layerDestination(layer), + text: layer.text, + })), + } + ); + await assertConfigMigrationInputs(snapshot, migration); + return { + migration, + outputs: new Map( + migration.prepared.files.map(({ path }) => [ + path, + migration.prepared.payload(path), + ]) + ), + }; + } catch (error) { + const conflict = error instanceof AtomicWriteConflictError; + return { + migration: null, + outputs: null, + issue: { + layer: env.layer.id, + path: [], + line: null, + code: conflict ? "E_CONFLICT" : "E_CONFIG_INVALID", + message: conflict + ? "Changed outside Hack. Reload before saving." + : configMigrationErrorMessage(error, snapshot.privateOverlays), + }, + }; + } +} + +function configMigrationErrorMessage( + error: unknown, + privateOverlays: ReadonlySet +): string { + if (!(error instanceof ClosedCliError || error instanceof HackCliError)) { + return "Could not prepare the legacy env migration."; + } + let message = error.message; + for (const name of [...privateOverlays].sort((a, b) => b.length - a.length)) { + message = message.replaceAll(name, "[redacted]"); + } + return message; +} + +async function assertConfigMigrationInputs( + snapshot: ConfigSnapshot, + migration: ImplicitEnvMigrationPlan +) { + // The patch can carry only the env base, but migration also uses the + // project identity and the declared services from this snapshot. + for (const layer of snapshot.layers.filter( + ({ id }) => id === "1" || id === "2" + )) { + const observed = migration.sources.find( + (source) => source.path === layerDestination(layer) + ); + const expected = + layer.text === null ? null : migrationDigest(Buffer.from(layer.text)); + const changed = observed + ? observed.sha256 !== expected + : (await readConfigLayer(layer.file)) !== layer.text; + if (changed) { + throw new AtomicWriteConflictError(); + } + } + const { prepared } = migration; + for (const file of prepared.files) { + if ( + ["layer", "local_layer", "config", "compose"].includes(file.kind) && + Buffer.byteLength(prepared.payload(file.path)) > CONFIG_SOURCE_LIMIT + ) { + throw new HackCliError({ + code: "E_CONFIG_INVALID", + message: "A migrated config file exceeds the 512 KiB limit.", + }); + } + } +} + +function prepareAfterMigration(opts: { + readonly files: Map; + readonly outputs: ReadonlyMap; + readonly patch: Patch; + readonly issues: ConfigIssue[]; +}): Map { + for (const file of opts.files.values()) { + const baseline = opts.outputs.get(layerDestination(file.layer)); + if (baseline === undefined) { + continue; + } + const migrated = { ...file, layer: { ...file.layer, text: baseline } }; + opts.files.set(file.layer.id, migrated); + if (file.source) { + const text = mergeMigratedSource(file.layer.text, file.text, baseline); + if (text === null) { + opts.issues.push({ + layer: file.layer.id, + path: [], + line: null, + code: "E_CONFIG_INVALID", + message: + "This Source edit and the env migration change the same setting.", + }); + } + migrated.text = text; + continue; + } + migrated.text = baseline; + for (const change of opts.patch.changes) { + if (change.kind === "project" && change.layer === file.layer.id) { + const issue = prepareProjectField(change, migrated); + if (issue) { + opts.issues.push(issue); + } + } + } + } + return opts.files; +} + +function mergeMigratedSource( + original: string | null, + draft: string | null, + migrated: string +): string | null { + if (!(original && draft)) { + return null; + } + const edits: { path: string[]; value: unknown }[] = []; + if ( + !collectMigrationSourceEdits( + JSON.parse(original), + JSON.parse(draft), + JSON.parse(migrated), + [], + edits + ) + ) { + return null; + } + return edits.reduce( + (text, edit) => + applyEdits( + text, + modify(text, edit.path, edit.value, { + formattingOptions: { insertSpaces: true, tabSize: 2 }, + }) + ), + draft + ); +} + +function collectMigrationSourceEdits( + original: unknown, + edited: unknown, + migrated: unknown, + path: string[], + edits: { path: string[]; value: unknown }[] +): boolean { + if ( + isDeepStrictEqual(original, migrated) || + isDeepStrictEqual(edited, migrated) + ) { + return true; + } + if (isRecord(original) && isRecord(edited) && isRecord(migrated)) { + return [ + ...new Set([...Object.keys(original), ...Object.keys(migrated)]), + ].every((key) => + collectMigrationSourceEdits( + ownJsonProperty(original, key), + ownJsonProperty(edited, key), + ownJsonProperty(migrated, key), + [...path, key], + edits + ) + ); + } + if (isDeepStrictEqual(original, edited)) { + edits.push({ path, value: migrated }); + return true; + } + return false; +} + +function ownJsonProperty( + record: Record, + key: string +): unknown { + return Object.hasOwn(record, key) ? record[key] : undefined; +} + +/** Validate a whole patch before effect and publish each affected file once. */ +export async function applyConfigPatch(snapshot: ConfigSnapshot, patch: Patch) { + const { files, issues, prospective, migration } = await assessConfigPatch( + snapshot, + patch, + "apply" + ); + const code = patchIssueCode(issues); + if (code !== null) { + throw new HackCliError({ + code, + message: "Config could not be saved.", + detail: { issues }, + }); + } + const changed: string[] = []; + try { + await assertConfigBaseUnchanged(snapshot, patch.base); + const manifestPath = migration + ? await publishConfigMigration(snapshot, migration, changed) + : null; + const publication = { + snapshot: prospective, + files, + changed, + removedPrivateOverlays: removedPrivateOverlays( + snapshot, + prospective.privateOverlays + ), + originalInheritedDir: inheritedEnvDir(snapshot), + }; + if (migration && manifestPath) { + await withEnvMigrationConfigEdits({ + project: migration.project, + manifestPath, + run: (edits) => publishPreparedLayers(publication, edits), + }); + } else { + await publishPreparedLayers(publication); + } + } catch (error) { + if (error instanceof AtomicWriteConflictError) { + throw new HackCliError({ + code: "E_CONFLICT", + message: "Changed outside Hack. Reload before saving.", + detail: { changed }, + }); + } + if (error instanceof HackCliError) { + throw new HackCliError({ + code: error.code, + message: "Could not write the selected config layer.", + detail: { changed }, + }); + } + throw new HackCliError({ + code: "E_CONFIG_INVALID", + message: "Could not write the selected config layer.", + detail: { changed }, + }); + } + return { + schema: CONFIG_EDITOR_SCHEMA, + changed, + restart_offered: + changed.includes("2") || + (changed.includes("1") && + patch.changes.some( + (change) => + change.layer === "1" && + !(change.kind === "project" && change.path.startsWith("env.")) + )), + }; +} + +async function assertConfigBaseUnchanged( + snapshot: ConfigSnapshot, + base: Patch["base"] +): Promise { + // Recheck every supplied dependency before the first commit. The + // individual writers recheck again at their locked commit points. + for (const layer of snapshot.layers) { + if (base[layer.id] === undefined) { + continue; + } + if (layer.directory && layer.ownership !== "generated") { + await assertConfigLayerDirectory(layer); + } + if ((await readConfigLayer(layer.file)) !== layer.text) { + throw new AtomicWriteConflictError(); + } + } +} +async function publishPreparedLayers( + opts: { + readonly snapshot: ConfigSnapshot; + readonly files: Map; + readonly changed: string[]; + readonly removedPrivateOverlays: readonly string[]; + readonly originalInheritedDir: string | null; + }, + edits?: { + readonly prepare: (write: MigrationConfigWrite) => Promise; + readonly commit: (path: string) => Promise; + } +) { + const { snapshot, files, changed } = opts; + const ordered = [...files.values()]; + // Apply project policy before the env writer evaluates inheritance for unsets. + for (const file of [ + ...ordered.filter((file) => file.layer.kind !== "env"), + ...ordered.filter((file) => file.layer.kind === "env"), + ]) { + const path = layerDestination(file.layer); + const beforePublish = edits + ? (after: string, mode: number) => + edits.prepare({ path, before: file.layer.text, after, mode }) + : undefined; + if ( + !(await writePreparedLayer( + snapshot, + file, + beforePublish, + opts.removedPrivateOverlays, + opts.originalInheritedDir + )) + ) { + continue; + } + if (!changed.includes(file.layer.id)) { + changed.push(file.layer.id); + } + await edits?.commit(path); + } +} + +function inheritedEnvDir(snapshot: ConfigSnapshot): string | null { + const inherited = snapshot.layers.find((layer) => layer.inherited); + return inherited ? dirname(inherited.file) : null; +} + +async function publishConfigMigration( + snapshot: ConfigSnapshot, + migration: ImplicitEnvMigrationPlan, + changed: string[] +) { + const projectLayer = snapshot.layers.find((layer) => layer.id === "1"); + if (!projectLayer) { + throw new AtomicWriteConflictError(); + } + const layerIds = migrationLayerIds(snapshot, migration); + const result = await applyEnvMigration({ + project: migration.project, + plan: migration, + acceptTrackedChanges: false, + snapshots: envMigrationSnapshots(), + repairCompose: false, + validateDestination: async () => + await assertConfigLayerDirectory(projectLayer), + onPublished: ({ path }) => { + const id = layerIds.get(path); + if (id && !changed.includes(id)) { + changed.push(id); + } + }, + }); + return result.manifestPath; +} + +function migrationLayerIds( + snapshot: ConfigSnapshot, + migration: ImplicitEnvMigrationPlan +): Map { + const layers = new Map( + snapshot.layers.map((layer) => [layerDestination(layer), layer.id]) + ); + for (const file of migration.prepared.files) { + if ( + layers.has(file.path) || + (file.kind !== "layer" && file.kind !== "local_layer") + ) { + continue; + } + const stem = basename(file.path).slice("hack.env.".length, -".yaml".length); + const local = file.kind === "local_layer"; + const overlay = + local && stem.endsWith(".local") ? stem.slice(0, -".local".length) : stem; + const id = local ? "5" : "3"; + const publicOverlay = isPrivateConfigOverlay( + overlay, + snapshot.privateOverlays + ) + ? "[redacted]" + : overlay; + layers.set( + file.path, + ["local", "default"].includes(overlay) ? id : `${id}:${publicOverlay}` + ); + } + return layers; +} +function patchIssueCode(issues: readonly ConfigIssue[]): HackErrorCode | null { + if (issues.length === 0) { + return null; + } + for (const code of ["E_CONFLICT", "E_LAYER_READ_ONLY"] as const) { + if (issues.some((issue) => issue.code === code)) { + return code; + } + } + return "E_CONFIG_INVALID"; +} + +async function writePreparedLayer( + snapshot: ConfigSnapshot, + file: Prepared, + beforePublish: ((text: string, mode: number) => Promise) | undefined, + removedOverlayNames: readonly string[], + originalInheritedDir: string | null +): Promise { + const { layer, text } = file; + const validate = async () => { + await assertConfigLayerDirectory(layer); + await assertLegacyProjectDirectory({ + projectDir: snapshot.project.projectDir, + }); + if (layer.kind === "env") { + await assertConfigEnvReadable( + snapshot.project.projectRoot, + inheritedEnvDir(snapshot) + ); + } + if ( + layer.kind === "project" && + removedOverlayNames.length > 0 && + ((await privateOverlayFileConflict({ + projectDir: snapshot.project.projectDir, + inheritedDirs: [originalInheritedDir, inheritedEnvDir(snapshot)], + names: removedOverlayNames, + })) || + (await legacyStoreMayContainOverlays(snapshot))) + ) { + throw new AtomicWriteConflictError(); + } + }; + if (layer.kind === "env") { + return ( + await mutateProjectEnvLayer({ + ...snapshot.project, + envName: layer.overlay ?? null, + local: layer.ownership === "local", + changes: file.env, + expected: { file: layer.file, text: layer.text, validate }, + beforePublish, + repairGitignore: beforePublish === undefined, + maxBytes: CONFIG_SOURCE_LIMIT, + }) + ).changed; + } + if (text === null || text === layer.text) { + return false; + } + await validate(); + return await withEnvLayerLock({ + layerPath: layer.file, + run: async () => + ( + await writeTextFileAtomicIfChanged(layer.file, text, { + expectedExisting: layer.text, + validatePath: validate, + beforePublish: beforePublish + ? (mode) => beforePublish(text, mode) + : undefined, + noFollowTarget: true, + }) + ).changed, + }); +} diff --git a/src/lib/config-editor-source.ts b/src/lib/config-editor-source.ts new file mode 100644 index 0000000000..b5c9b28431 --- /dev/null +++ b/src/lib/config-editor-source.ts @@ -0,0 +1,455 @@ +import { type Node, type ParseError, parseTree } from "jsonc-parser"; +import { + isAlias, + isMap, + isPair, + isScalar, + isSeq, + parseDocument, + visit, +} from "yaml"; +import { isRecord } from "./guards.ts"; +import { + normalizeEnvConfigName, + readAuthoredProjectOverlaySettings, +} from "./project.ts"; + +const SECRET_KEY = + /(?:access[_-]?key|auth(?:orization)?|credential|pass(?:word|phrase|wd)?\b|secret|secure|token|private[_-]?key|api[_-]?key|(?:^|[_-])pat(?:$|[_-]))/i; +const SECRET_TEXT = + /(?:(? (isConfigSecret("", part) ? "[redacted]" : part)); +} + +export function privateProjectOverlayNames( + project: Record +): ReadonlySet { + const { current, legacy } = readAuthoredProjectOverlaySettings(project); + return new Set( + [...current, ...legacy] + .filter( + (value): value is string => + value !== undefined && isConfigSecret("", value) + ) + .map(normalizeEnvConfigName) + .filter((name) => name !== null) + ); +} + +export function isPrivateConfigOverlay( + name: string, + derivedNames: ReadonlySet +): boolean { + return isConfigSecret("", name) || derivedNames.has(name); +} + +export function isPrivateOverlayValue( + value: unknown, + names: ReadonlySet +): boolean { + if (names.size === 0 || typeof value !== "string") { + return false; + } + const name = normalizeEnvConfigName(value); + return name !== null && names.has(name); +} + +/** A project must retain the redaction source for any surviving private value. */ +export function hasPrivateOverlayValue( + project: Record, + names: ReadonlySet +): boolean { + const pending = Object.values(project); + while (pending.length > 0) { + const value = pending.pop(); + if (isPrivateOverlayValue(value, names)) { + return true; + } + if (isRecord(value) || Array.isArray(value)) { + for (const child of Object.values(value)) { + pending.push(child); + } + } + } + return false; +} + +function secretProperty(key: string): boolean { + // OAuth routing configuration is an object of public settings. + return ( + key !== "oauth" && + key !== "secretsprovider" && + key !== "secretsProvider" && + isConfigSecret(key, null) + ); +} + +export function configLine(text: string, offset: number): number { + return text.slice(0, offset).split("\n").length; +} + +export function jsonConfigTree(text: string) { + const errors: ParseError[] = []; + const root = parseTree(text, errors, { disallowComments: true }); + const duplicate = + root && errors.length === 0 ? duplicateJsonProperty(root) : undefined; + return { + root, + error: errors[0], + duplicate, + ok: + root?.type === "object" && errors.length === 0 && duplicate === undefined, + }; +} + +export function jsonConfigDiagnostic(text: string) { + const tree = jsonConfigTree(text); + return tree.ok + ? null + : { + line: configLine( + text, + tree.duplicate?.offset ?? tree.error?.offset ?? 0 + ), + message: tree.duplicate + ? "Each JSON field must appear once." + : "Expected a valid JSON object.", + }; +} + +function duplicateJsonProperty(root: Node): Node | undefined { + const stack = [root]; + for (let node = stack.pop(); node; node = stack.pop()) { + const children = node.children ?? []; + if (node.type === "object") { + const keys = new Set(); + for (const child of children) { + const key = child.children?.[0]; + if (key && typeof key.value === "string") { + if (keys.has(key.value)) { + return key; + } + keys.add(key.value); + } + } + } + for (const child of children) { + stack.push(child); + } + } + return undefined; +} +type SourcePath = readonly (string | number)[]; +type Range = { + readonly start: number; + readonly length: number; + readonly path: SourcePath; +}; + +const PRIVATE_SLOT = /"\[redacted:\d+\]"/; + +function sourceSlots(text: string, ranges: readonly Range[]) { + return ranges + .toSorted((left, right) => left.start - right.start) + .map(({ start, length, path }, index) => { + const value = text.slice(start, start + length); + const lineBreaks = value.match(/\r?\n/g)?.join("") ?? ""; + return { + start, + length, + path, + value, + marker: `"[redacted:${index + 1}]"${lineBreaks}`, + }; + }); +} + +function redact(text: string, ranges: readonly Range[]) { + let output = text; + const slots = sourceSlots(text, ranges); + for (const { start, length, marker } of slots.toReversed()) { + output = `${output.slice(0, start)}${marker}${output.slice(start + length)}`; + } + return output; +} + +function privateProjectCommand(path: SourcePath): boolean { + return ( + path[0] === "startup" || + (path[0] === "lifecycle" && path.length > 1 && path[1] !== "runner") + ); +} + +function jsonSecretRanges( + node: Node, + path: SourcePath, + ranges: Range[], + privateOverlays: ReadonlySet +): boolean { + const key = path.at(-1); + if (isConfigSecret("", key)) { + return true; + } + if ( + (typeof key === "string" && secretProperty(key)) || + (node.type === "string" && + (privateProjectCommand(path) || + isConfigSecret("", node.value) || + isPrivateOverlayValue(node.value, privateOverlays))) + ) { + ranges.push({ start: node.offset, length: node.length, path }); + return false; + } + let hasPrivateKey = false; + (node.children ?? []).forEach((child, index) => { + if (child.type === "property") { + const [property, value] = child.children ?? []; + if (value && typeof property?.value === "string") { + hasPrivateKey = + jsonSecretRanges( + value, + [...path, property.value], + ranges, + privateOverlays + ) || hasPrivateKey; + } + } else { + hasPrivateKey = + jsonSecretRanges(child, [...path, index], ranges, privateOverlays) || + hasPrivateKey; + } + }); + return hasPrivateKey; +} + +function jsonRedactions(text: string) { + const tree = jsonConfigTree(text); + if (!(tree.ok && tree.root)) { + return null; + } + const ranges: Range[] = []; + const project: unknown = JSON.parse(text); + const privateOverlays = isRecord(project) + ? privateProjectOverlayNames(project) + : new Set(); + const hasPrivateKey = jsonSecretRanges( + tree.root, + [], + ranges, + privateOverlays + ); + return { ranges, hasPrivateKey }; +} + +function jsonRanges(text: string): Range[] | null { + const redactions = jsonRedactions(text); + return redactions && !redactions.hasPrivateKey ? redactions.ranges : null; +} + +/** Keep ordinary fields available when an unsafe key hides the Source preview. */ +export function safeJsonProject(text: string): Record | null { + const redactions = jsonRedactions(text); + if (!redactions) { + return null; + } + const project: unknown = JSON.parse( + redact(text, redactions.ranges), + (key, value: unknown) => (isConfigSecret("", key) ? undefined : value) + ); + return isRecord(project) ? project : null; +} + +/** Location-preserving redaction. Invalid source is kept out of the JSON contract. */ +export function safeJsonSource(text: string) { + const ranges = jsonRanges(text); + return ranges + ? { source: redact(text, ranges), hidden: ranges.length > 0 } + : { source: null, hidden: true }; +} + +function yamlPath(parents: readonly unknown[], key: unknown): SourcePath { + const path: (string | number)[] = []; + parents.forEach((parent, index) => { + const child = parents[index + 1]; + if (isPair(parent) && isScalar(parent.key)) { + path.push(String(parent.key.value)); + } else if (isSeq(parent)) { + const position = child === undefined ? key : parent.items.indexOf(child); + if (typeof position === "number") { + path.push(position); + } + } + }); + return path; +} + +function yamlSecretRanges( + text: string, + compose: boolean, + privateKeys: ReadonlySet +): Range[] | null { + const doc = parseDocument(text, { prettyErrors: false }); + if (doc.errors.length > 0 || privateYamlComment(doc)) { + return null; + } + const ranges: Range[] = []; + let aliases = false; + let hiddenSource = false; + // Check even nodes underneath a private parent which the masking pass skips. + visit(doc, (index, node) => { + if (isAlias(node)) { + aliases = true; + } + if ( + (index === "key" && isScalar(node) && isConfigSecret("", node.value)) || + ((isAlias(node) || isMap(node) || isScalar(node) || isSeq(node)) && + privateYamlComment(node)) + ) { + hiddenSource = true; + return visit.BREAK; + } + }); + if (hiddenSource) { + return null; + } + visit(doc, { + Pair(index, pair, parents) { + const key = + isScalar(pair.key) && typeof pair.key.value === "string" + ? pair.key.value + : ""; + const node = pair.value; + if ( + !( + privateKeys.has(key) || + secretProperty(key) || + (compose && + (PRIVATE_COMPOSE_FIELDS.test(key) || CADDY_HEADER.test(key))) + ) + ) { + return; + } + if (isMap(node) || isSeq(node) || isScalar(node) || isAlias(node)) { + const range = node.range; + if (range && range[0] < range[1]) { + ranges.push({ + start: range[0], + length: range[1] - range[0], + path: [...yamlPath(parents, index), key], + }); + return visit.SKIP; + } + } + }, + Scalar(index, node, parents) { + const value: unknown = node.value; + if (typeof value !== "string" || !node.range || index === "key") { + return; + } + const separator = value.indexOf("="); + const key = separator > 0 ? value.slice(0, separator) : ""; + const assignment = + key !== "" && + (secretProperty(key) || (compose && CADDY_HEADER.test(key))); + if (assignment || isConfigSecret("", value)) { + ranges.push({ + start: node.range[0], + length: node.range[1] - node.range[0], + path: yamlPath(parents, index), + }); + } + }, + }); + // An alias can point at a secret in an otherwise unrelated part of a file. + return aliases && ranges.length > 0 ? null : ranges; +} + +export function safeYamlSource( + text: string, + compose: boolean, + privateKeys: ReadonlySet = new Set() +) { + const ranges = yamlSecretRanges(text, compose, privateKeys); + if (!ranges) { + return { source: null, hidden: true }; + } + return { source: redact(text, ranges), hidden: ranges.length > 0 }; +} + +function privateYamlComment(node: { + readonly comment?: string | null; + readonly commentBefore?: string | null; +}): boolean { + return [node.comment, node.commentBefore].some( + (comment) => + typeof comment === "string" && + (PRIVATE_COMMENT.test(comment) || isConfigSecret("", comment)) + ); +} + +/** + * Keep private source text on disk and in the CLI. An editor gets numbered + * slots. A save restores the original bytes, then re-runs the masking parser + * to prove the same slots are still private, at the same paths and in order. + */ +export function restoreConfigSource(opts: { + readonly original: string; + readonly draft: string; + readonly format: "json" | "yaml"; +}): string | null { + if (PRIVATE_SLOT.test(opts.original)) { + return null; + } + const rangesFor = + opts.format === "json" + ? jsonRanges + : (text: string) => yamlSecretRanges(text, true, new Set()); + const ranges = rangesFor(opts.original); + if (!ranges) { + return null; + } + const slots = sourceSlots(opts.original, ranges); + let input = opts.draft; + let output = ""; + for (const { marker, value } of slots) { + const index = input.indexOf(marker); + if (index < 0) { + return null; + } + output += input.slice(0, index) + value; + input = input.slice(index + marker.length); + } + if (PRIVATE_SLOT.test(input) || PRIVATE_SLOT.test(output)) { + return null; + } + output += input; + const next = rangesFor(output); + if ( + !next || + redact(output, next) !== opts.draft || + sourceSlots(output, next).some( + (slot, index) => + JSON.stringify(slot.path) !== JSON.stringify(slots[index]?.path) + ) + ) { + return null; + } + return output; +} diff --git a/src/lib/config-overlay-files.ts b/src/lib/config-overlay-files.ts new file mode 100644 index 0000000000..50693e7722 --- /dev/null +++ b/src/lib/config-overlay-files.ts @@ -0,0 +1,62 @@ +import { lstat } from "node:fs/promises"; +import { isRecord } from "./guards.ts"; +import { resolveEnvFilePath } from "./hack-env.ts"; +import { parseEnvConfigSelection } from "./project.ts"; +import { + resolveProjectEnvConfigPath, + resolveProjectEnvLocalConfigPath, +} from "./project-env-config.ts"; + +export const PRIVATE_OVERLAY_MIGRATION_CONFLICT = + "Migration would expose a private overlay name. Resolve the conflicting project setting or legacy env input before retrying."; + +/** Probe known private filenames directly, including when a directory cannot be listed. */ +export async function privateOverlayFileConflict(opts: { + readonly projectDir: string; + readonly inheritedDirs: readonly (string | null)[]; + readonly names: readonly string[]; + readonly planned?: Pick, "has"> | null; +}): Promise<"existing" | "planned" | null> { + const dirs = new Set([ + opts.projectDir, + ...opts.inheritedDirs.filter((dir) => dir !== null), + ]); + let plannedConflict = false; + for (const envName of opts.names) { + const selectable = parseEnvConfigSelection(envName) === envName; + const paths = [ + resolveEnvFilePath({ projectDir: opts.projectDir, envName }), + ]; + if (selectable) { + paths.push( + resolveProjectEnvConfigPath({ projectDir: opts.projectDir, envName }) + ); + for (const projectDir of dirs) { + paths.push(resolveProjectEnvLocalConfigPath({ projectDir, envName })); + } + } + for (const path of paths) { + if ( + await lstat(path).then( + () => true, + (error: unknown) => { + // The legacy migrator discovers dotenv files by filename, including + // names outside the selector limit that still fit on disk. + if ( + isRecord(error) && + (error.code === "ENOENT" || + (!selectable && error.code === "ENAMETOOLONG")) + ) { + return false; + } + throw error; + } + ) + ) { + return "existing"; + } + plannedConflict ||= opts.planned?.has(path) === true; + } + } + return plannedConflict ? "planned" : null; +} diff --git a/src/lib/env-migration.ts b/src/lib/env-migration.ts index 20eea4c1b4..5725fe378e 100644 --- a/src/lib/env-migration.ts +++ b/src/lib/env-migration.ts @@ -1,6 +1,14 @@ import { lstat, realpath } from "node:fs/promises"; import { basename, dirname, isAbsolute, join, resolve } from "node:path"; import { ClosedCliError } from "./cli-result.ts"; +import { + hasPrivateOverlayValue, + privateProjectOverlayNames, +} from "./config-editor-source.ts"; +import { + PRIVATE_OVERLAY_MIGRATION_CONFLICT, + privateOverlayFileConflict, +} from "./config-overlay-files.ts"; import { withEnvLayerLock } from "./env-layer-lock.ts"; import { assertMigrationStorageOutsideWorkingTrees as assertOutsideWorkingTrees, @@ -23,6 +31,7 @@ import { migrationJournalPath, withEnvMigrationVerification, } from "./env-migration-state.ts"; +import { AtomicWriteConflictError } from "./fs.ts"; import { isRecord } from "./guards.ts"; import { ensurePrivateDirectory, @@ -32,6 +41,7 @@ import { PRIVATE_STAGING_DIRNAME, preparePrivateStaging, } from "./private-staging.ts"; +import { parseProjectConfigRecord } from "./project.ts"; import { acquireLegacyEnvCleanupContext, assertLegacyEnvMigrationDelivery, @@ -50,12 +60,15 @@ import { resolveProjectEnvSharedKeyLocation, } from "./project-env-config.ts"; import { withProjectsRegistryLock } from "./projects-registry-lock.ts"; +import { resolvePrimaryLocalProjectDir } from "./worktree-local-config.ts"; export const ENV_MIGRATION_VERSION = 1 as const; const FILE_LIMIT = 32 * 1024 * 1024; const SHA256 = /^[a-f0-9]{64}$/; const PAYLOAD_NAME = /^[0-9]+\.payload$/; const ENV_KEY = /^[A-Z_][A-Z0-9_]*$/; +const CONFIG_ENV_LAYER = + /^hack\.env\.[a-z0-9][a-z0-9-]{0,127}(?:\.local)?\.yaml$/; export type EnvMigrationProject = { readonly projectRoot: string; @@ -88,6 +101,12 @@ type Publication = EnvMigrationFileState & { readonly done: boolean; }; +type ConfigPublication = { + readonly before: EnvMigrationFileState; + readonly after: EnvMigrationFileState; + readonly committed: boolean; +}; + type Journal = { readonly version: 1; readonly kind: "hack-env-migration"; @@ -101,6 +120,8 @@ type Journal = { | "rolled_back" | "rolling_back"; readonly sources: readonly EnvMigrationFileState[]; + /** Expected before and after revisions of files in the initiating Config save. */ + readonly configEdits?: readonly ConfigPublication[]; readonly writes: readonly Publication[]; readonly removable: readonly string[]; readonly overlayNames: readonly string[]; @@ -223,6 +244,33 @@ function validState( ); } +function isMigrationConfigEditPath( + project: EnvMigrationProject, + path: string +): boolean { + return ( + path === join(project.projectDir, "hack.config.json") || + path === join(project.projectDir, "docker-compose.yml") || + (dirname(path) === project.projectDir && + CONFIG_ENV_LAYER.test(basename(path))) + ); +} + +function validConfigPublication( + entry: unknown, + project: EnvMigrationProject +): entry is ConfigPublication { + return ( + isRecord(entry) && + validState(entry.before) && + validState(entry.after) && + entry.before.path === entry.after.path && + entry.after.sha256 !== null && + typeof entry.committed === "boolean" && + isMigrationConfigEditPath(project, entry.after.path) + ); +} + function validPublication(entry: unknown, path: string): entry is Publication { return ( validState(entry) && @@ -281,6 +329,7 @@ async function readJournal( isRecord(raw.project) && raw.project.projectRoot === project.projectRoot && raw.project.projectDir === project.projectDir && + typeof raw.project.projectName === "string" && typeof raw.manifestPath === "string" && isAbsolute(raw.manifestPath) && [ @@ -293,6 +342,11 @@ async function readJournal( ].includes(String(raw.state)) && Array.isArray(raw.sources) && raw.sources.every(validState) && + (raw.configEdits === undefined || + (Array.isArray(raw.configEdits) && + raw.configEdits.every((entry) => + validConfigPublication(entry, project) + ))) && (raw.composeRepair === undefined || ["deferred", "applying", "complete"].includes( String(raw.composeRepair) @@ -373,8 +427,67 @@ type Preparation = { readonly sources: readonly EnvMigrationFileState[]; }; +export type ImplicitEnvMigrationPlan = Preparation & { + readonly project: EnvMigrationProject; +}; + +/** Preflight immutable migration payloads as part of a larger validated edit. */ +export async function prepareImplicitEnvMigration( + input: EnvMigrationProject, + { + edits = [], + writesLocalEnv = false, + inheritLocal, + }: { + readonly edits?: readonly { + readonly path: string; + readonly text: string | null; + }[]; + readonly writesLocalEnv?: boolean; + readonly inheritLocal?: boolean; + } = {} +): Promise { + const project = await canonicalProject(input); + assertFreshMigration( + await readJournal(envMigrationJournalPath(project.projectRoot), project) + ); + const plan = await prepareConsistent({ + ...project, + repairCompose: false, + writesLocalEnv, + inheritLocal, + }); + await assertEnvMigrationConsent( + project, + plan.prepared.files.map((file) => file.path), + false + ); + const sources = new Map(plan.sources.map((file) => [file.path, file])); + for (const edit of edits) { + if (!isMigrationConfigEditPath(project, edit.path)) { + throw new AtomicWriteConflictError(); + } + const observed = await readState(edit.path); + if (observed.text !== edit.text) { + throw new AtomicWriteConflictError(); + } + sources.set(edit.path, sources.get(edit.path) ?? observed.state); + } + return { ...plan, sources: [...sources.values()], project }; +} + +function assertFreshMigration(journal: Journal | null): void { + if (journal && journal.state !== "rolled_back") { + throw new AtomicWriteConflictError(); + } +} + async function prepareConsistent( - project: EnvMigrationProject & { readonly repairCompose?: boolean } + project: EnvMigrationProject & { + readonly repairCompose?: boolean; + readonly writesLocalEnv?: boolean; + readonly inheritLocal?: boolean; + } ): Promise { // Discover the complete inventory before the pass whose immutable payloads // will be published. A changed inventory or input refuses before consent. @@ -389,10 +502,26 @@ async function prepareConsistent( ) { throw refuse(); } + const config = prepared.files.find(({ kind }) => kind === "config"); for (const source of sources) { - if (!same(source, (await readState(source.path)).state)) { + const current = await readState(source.path); + if (!same(source, current.state)) { throw refuse(); } + if ( + config?.path === source.path && + (await migrationExposesPrivateOverlay({ + project, + path: config.path, + before: current.text, + after: prepared.payload(config.path), + planned: new Set(prepared.files.map(({ path }) => path)), + })) + ) { + throw new ClosedCliError( + `${PRIVATE_OVERLAY_MIGRATION_CONFLICT} No migration files were changed.` + ); + } } return { prepared, sources }; } @@ -529,8 +658,8 @@ export async function previewEnvCleanup( return { ...preview, files }; } -async function assertConsent( - project: EnvMigrationProject, +export async function assertEnvMigrationConsent( + project: Pick, paths: readonly string[], accept: boolean ): Promise { @@ -565,16 +694,29 @@ async function assertSources( const publication = journal.writes.find( (entry) => entry.path === source.path ); + const edited = revised + ? undefined + : journal.configEdits?.find((entry) => entry.after.path === source.path); const write = - revised && publication?.kind !== "compose" ? undefined : publication; + edited || (revised && publication?.kind !== "compose") + ? undefined + : publication; if ( allowLayerChanges && - (publication?.kind === "layer" || publication?.kind === "local_layer") + (publication?.kind === "layer" || + publication?.kind === "local_layer" || + (dirname(source.path) === journal.project.projectDir && + CONFIG_ENV_LAYER.test(basename(source.path)))) ) { continue; } if ( - !matchesMigrationSource({ current, source, write, allowTighterModes }) + !matchesMigrationSource({ + current, + source: configEditRevision(edited, current) ?? source, + write, + allowTighterModes, + }) ) { throw new ClosedCliError( `Env migration input changed: ${JSON.stringify(source.path)}. Keep the legacy files and snapshot. To restore originals while retaining later edits privately, use hack env migrate --rollback-manifest ${JSON.stringify(journal.manifestPath)} --preserve-changes (values omitted).` @@ -583,6 +725,18 @@ async function assertSources( } } +function configEditRevision( + edit: ConfigPublication | undefined, + current: EnvMigrationFileState +): EnvMigrationFileState | undefined { + if (!edit) { + return undefined; + } + return !edit.committed && same(current, edit.before) + ? edit.before + : edit.after; +} + function matchesMigrationSource({ current, source, @@ -695,6 +849,7 @@ async function prepareDeferredComposeRepair( project: EnvMigrationProject, journal: Journal ): Promise { + const legacy = { ...project, projectName: journal.project.projectName }; const composeFile = join(project.projectDir, "docker-compose.yml"); const before = (await readState(composeFile)).state; const references = await inspectLegacyComposeEnvFileReferences({ @@ -712,7 +867,7 @@ async function prepareDeferredComposeRepair( allowLayerChanges: true, allowTighterModes: true, }); - const preparation = await prepareConsistent(project); + const preparation = await prepareConsistent(legacy); if ( preparation.prepared.files.some( (file) => @@ -727,7 +882,7 @@ async function prepareDeferredComposeRepair( throw refuse(); } await assertLegacyEnvMigrationDelivery({ - ...project, + ...legacy, overlayNames: preparation.prepared.overlayNames, }); return preparation; @@ -747,7 +902,7 @@ async function extendComposeRepair( return completed; } const { prepared, sources } = preparation; - await assertConsent( + await assertEnvMigrationConsent( project, prepared.files.map((file) => file.path), accept @@ -794,11 +949,62 @@ async function publishStagingGuard( } } +/** The retained payload and locked original carry the same privacy check on resume. */ +async function migrationExposesPrivateOverlay(opts: { + readonly project: EnvMigrationProject; + readonly path: string; + readonly before: string | null; + readonly after: string; + readonly planned?: ReadonlySet; +}): Promise { + if (opts.before === null) { + return false; + } + const before: unknown = JSON.parse(opts.before); + const after: unknown = JSON.parse(opts.after); + if (!(isRecord(before) && isRecord(after))) { + return false; + } + const remaining = privateProjectOverlayNames(after); + const removed = [...privateProjectOverlayNames(before)].filter( + (name) => !remaining.has(name) + ); + if (removed.length === 0) { + return false; + } + if (hasPrivateOverlayValue(after, new Set(removed))) { + return true; + } + const inheritLocal = [before, after].some( + (record) => + parseProjectConfigRecord(record, opts.path).worktree?.inheritLocal !== + false + ); + const primary = await resolvePrimaryLocalProjectDir({ + ...opts.project, + inheritLocal, + }); + return ( + (await privateOverlayFileConflict({ + projectDir: opts.project.projectDir, + inheritedDirs: [primary], + names: removed, + planned: opts.planned, + })) !== null + ); +} + async function publishEntry( project: EnvMigrationProject, - entry: Publication + entry: Publication, + publication?: { + readonly validateDestination?: () => Promise; + readonly onPublished?: (file: EnvMigrationFileState) => void; + } ): Promise { + await publication?.validateDestination?.(); const run = async () => { + await publication?.validateDestination?.(); if (entry.kind === "key") { await assertMigrationProjectEnvKeyPrivate({ ...project, @@ -835,12 +1041,14 @@ async function publishEntry( } if (entry.kind === "staging_guard") { await publishStagingGuard(entry, payload.text); + publication?.onPublished?.(entry); return; } + const text = payload.text; await replacePrivateFileAtomic({ path: entry.path, directories: [dirname(entry.path)], - text: payload.text, + text, mode: entry.mode ?? 0o600, refusal: refuse, beforeRename: async () => { @@ -850,10 +1058,24 @@ async function publishEntry( keyPath: entry.path, }); } - if (!same((await readState(entry.path)).state, entry.before)) { + const original = await readState(entry.path); + if (!same(original.state, entry.before)) { throw refuse(); } + if ( + entry.kind === "config" && + (await migrationExposesPrivateOverlay({ + project, + path: entry.path, + before: original.text, + after: text, + })) + ) { + throw new AtomicWriteConflictError(); + } + await publication?.validateDestination?.(); }, + afterRename: () => publication?.onPublished?.(entry), }); if (!same((await readState(entry.path)).state, entry)) { throw refuse(); @@ -904,11 +1126,26 @@ export async function applyEnvMigration(input: { readonly snapshots: EnvMigrationSnapshots; readonly hooks?: EnvMigrationHooks; readonly repairCompose?: boolean; + readonly plan?: ImplicitEnvMigrationPlan; + readonly validateDestination?: () => Promise; + readonly onPublished?: (file: EnvMigrationFileState) => void; }) { + await input.validateDestination?.(); const project = await canonicalProject(input.project); + if ( + input.plan && + (input.plan.project.projectRoot !== project.projectRoot || + input.plan.project.projectDir !== project.projectDir || + input.plan.project.projectName !== project.projectName) + ) { + throw new AtomicWriteConflictError(); + } const path = envMigrationJournalPath(project.projectRoot); await assertOutsideWorkingTrees(path, project); const existing = await readJournal(path, project); + if (input.plan) { + assertFreshMigration(existing); + } assertApplyJournalState(existing); await input.hooks?.beforeLock?.(); if ( @@ -945,10 +1182,10 @@ export async function applyEnvMigration(input: { }, }); } - let preparation: Preparation | null = null; - if (needsComposeRepair(existing, input.repairCompose)) { + let preparation: Preparation | null = input.plan ?? null; + if (!preparation && needsComposeRepair(existing, input.repairCompose)) { preparation = await prepareDeferredComposeRepair(project, existing); - } else if (!existing || existing.state === "rolled_back") { + } else if (!preparation && (!existing || existing.state === "rolled_back")) { preparation = await prepareConsistent({ ...project, repairCompose: input.repairCompose, @@ -959,7 +1196,7 @@ export async function applyEnvMigration(input: { : (existing?.writes .filter((entry) => !entry.done) .map((entry) => entry.path) ?? []); - await assertConsent(project, changed, input.acceptTrackedChanges); + await assertEnvMigrationConsent(project, changed, input.acceptTrackedChanges); if ( preparation && (!existing || existing.state === "rolled_back") && @@ -978,7 +1215,11 @@ export async function applyEnvMigration(input: { lockPath: `${path}.lock`, label: "env migration", run: async () => { + await input.validateDestination?.(); const retained = await readJournal(path, project); + if (input.plan) { + assertFreshMigration(retained); + } assertApplyJournalState(retained); const retain = retainedPayloads(retained); await purgeMigrationPayloads({ @@ -1008,7 +1249,7 @@ export async function applyEnvMigration(input: { input.acceptTrackedChanges ); } - await assertConsent( + await assertEnvMigrationConsent( project, journal.writes .filter((entry) => !entry.done) @@ -1023,6 +1264,7 @@ export async function applyEnvMigration(input: { }; } await input.hooks?.boundary?.({ phase: "prepared", index: -1 }); + await input.validateDestination?.(); await assertSources(journal); // A retained journal is not proof that its original rollback bytes // survived the interruption. Admit them before any further publication. @@ -1036,6 +1278,7 @@ export async function applyEnvMigration(input: { run: () => assertLegacyEnvMigrationDelivery({ ...project, + projectName: journal.project.projectName, overlayNames: journal.overlayNames, }), }); @@ -1048,7 +1291,7 @@ export async function applyEnvMigration(input: { if (journal.composeRepairSources) { await assertSources(journal); } - await publishEntry(project, entry); + await publishEntry(project, entry, input); await input.hooks?.boundary?.({ phase: "published", index }); await input.snapshots.recordAfter({ manifestPath: journal.manifestPath, @@ -1303,7 +1546,7 @@ async function cleanupLocked( journal.store && journal.removable.includes(journal.store.path) ? await prepareLegacyEnvCleanupConfig(project) : null; - await assertConsent( + await assertEnvMigrationConsent( project, [...journal.removable, ...(repair ? [repair.path] : [])], input.acceptTrackedChanges @@ -1318,6 +1561,7 @@ async function cleanupLocked( }); const context = await acquireLegacyEnvCleanupContext({ ...project, + projectName: journal.project.projectName, overlayNames: journal.overlayNames, paths: journal.sources .filter( @@ -1427,6 +1671,105 @@ async function cleanupLocked( }; } +export type MigrationConfigWrite = { + readonly path: string; + readonly before: string | null; + readonly after: string; + readonly mode: number; +}; + +type MigrationConfigEdits = { + readonly prepare: (write: MigrationConfigWrite) => Promise; + readonly commit: (path: string) => Promise; +}; + +/** Hold the migration lock across Config writes so cleanup and rollback see either side of a recorded intent. */ +export async function withEnvMigrationConfigEdits(input: { + readonly project: EnvMigrationProject; + readonly manifestPath: string; + readonly run: (edits: MigrationConfigEdits) => Promise; +}): Promise { + const { project } = input; + const path = envMigrationJournalPath(project.projectRoot); + return await withProjectsRegistryLock({ + lockPath: `${path}.lock`, + label: "env migration", + run: async () => { + const initial = await readJournal(path, project); + if ( + !initial || + initial.state !== "complete" || + initial.manifestPath !== input.manifestPath || + initial.configEdits !== undefined || + initial.composeRepairSources !== undefined + ) { + throw new AtomicWriteConflictError(); + } + let journal: Journal = initial; + const publishIntent = async (intent: ConfigPublication) => { + journal = { + ...journal, + validated: undefined, + configEdits: [ + ...(journal.configEdits ?? []).filter( + (entry) => entry.after.path !== intent.after.path + ), + intent, + ], + }; + await writeMetadata(path, journal); + }; + return await input.run({ + prepare: async (write) => { + const intent = await prepareMigrationConfigWrite(journal, write); + await publishIntent(intent); + }, + commit: async (target) => { + const intent = journal.configEdits?.find( + (entry) => entry.after.path === target + ); + if ( + !(intent && same((await readState(target)).state, intent.after)) + ) { + throw new AtomicWriteConflictError(); + } + await publishIntent({ ...intent, committed: true }); + }, + }); + }, + }); +} + +async function prepareMigrationConfigWrite( + journal: Journal, + write: MigrationConfigWrite +): Promise { + const original = journal.sources.find((entry) => entry.path === write.path); + if ( + !(original && isMigrationConfigEditPath(journal.project, write.path)) || + journal.configEdits?.some((entry) => entry.after.path === write.path) + ) { + throw new AtomicWriteConflictError(); + } + const expected = + journal.writes.find((entry) => entry.path === write.path) ?? original; + const current = await readState(write.path); + if (!same(current.state, expected) || current.text !== write.before) { + throw new AtomicWriteConflictError(); + } + const bytes = Buffer.from(write.after); + return { + before: current.state, + after: { + path: write.path, + sha256: digest(bytes), + size: bytes.length, + mode: write.mode, + }, + committed: false, + }; +} + /** Called only by successful full-project startup paths, never by preview or env resolution. */ export async function recordEnvMigrationProjectRun( input: EnvMigrationProject @@ -1445,12 +1788,20 @@ export async function recordEnvMigrationProjectRun( if (!journal || journal.state !== "complete") { return; } - const validated = await Promise.all( + const layerPaths = new Set( journal.writes .filter( (entry) => entry.kind === "layer" || entry.kind === "local_layer" ) - .map(async (entry) => (await readState(entry.path)).state) + .map((entry) => entry.path) + ); + for (const edit of journal.configEdits ?? []) { + if (CONFIG_ENV_LAYER.test(basename(edit.after.path))) { + layerPaths.add(edit.after.path); + } + } + const validated = await Promise.all( + [...layerPaths].map(async (path) => (await readState(path)).state) ); await writeMetadata(path, { ...journal, validated }); }, @@ -1521,8 +1872,17 @@ async function rollbackLocked( (journal.state === "cleaning" && journal.removable.includes(source.path) && current.sha256 === null); + const publication = journal.writes.find( + (write) => write.path === source.path + ); + const edited = configEditRevision( + journal.configEdits?.find((entry) => entry.after.path === source.path), + current + ); let expected = - journal.writes.find((write) => write.path === source.path) ?? + (publication?.kind === "compose" + ? publication + : (edited ?? publication)) ?? journal.composeRepairSources?.find( (entry) => entry.path === source.path ) ?? diff --git a/src/lib/fs.ts b/src/lib/fs.ts index 884a580cb2..aa5397cda9 100644 --- a/src/lib/fs.ts +++ b/src/lib/fs.ts @@ -436,6 +436,8 @@ export async function writeTextFileAtomicIfChanged( * bits are kept. Without it an existing file keeps its mode exactly. */ readonly tightenExisting?: boolean; + /** Publish a caller's recovery intent before changing the destination. */ + readonly beforePublish?: (mode: number) => Promise; /** * Never resolve the destination through a symlink (HACK-2165): a link * at `absolutePath` is refused, and the commit renames onto @@ -501,6 +503,9 @@ export async function writeTextFileAtomicIfChanged( await file.writeFile(content, "utf8"); await file.sync(); await options.validatePath?.(absolutePath); + if (options.beforePublish) { + await options.beforePublish((await file.stat()).mode & 0o777); + } if ( expectsExisting && targetText(await inspectAtomicWriteTarget(absolutePath)) !== diff --git a/src/lib/machine-output.ts b/src/lib/machine-output.ts index 0e82f14e97..52f8384c2a 100644 --- a/src/lib/machine-output.ts +++ b/src/lib/machine-output.ts @@ -19,6 +19,7 @@ export const MACHINE_SCHEMAS = { daemonInstall: "hack.daemon-install.v1", doctorMachine: "hack.doctor.machine.v1", envOverlays: "hack.env-overlays.v1", + config: "hack.config.v1", } as const; export function machineSuccess(opts: { diff --git a/src/lib/private-file.ts b/src/lib/private-file.ts index 43763a04e8..0bfa21b69f 100644 --- a/src/lib/private-file.ts +++ b/src/lib/private-file.ts @@ -465,6 +465,8 @@ export async function replacePrivateFileAtomic( * make its last compare-and-swap check here. */ readonly beforeRename?: () => Promise; + /** Reports the commit even if a subsequent verification fails. */ + readonly afterRename?: () => void; } ): Promise { const mode = (opts.mode ?? 0o600) & 0o777; @@ -485,6 +487,7 @@ export async function replacePrivateFileAtomic( await opts.beforeRename?.(); await rename(staging, opts.path); committed = true; + opts.afterRename?.(); } catch (error: unknown) { throw closedFileWriteError({ error, path: opts.path, operation: "write" }); } finally { diff --git a/src/lib/project-env-config.ts b/src/lib/project-env-config.ts index 088e2cf759..4777c8538f 100644 --- a/src/lib/project-env-config.ts +++ b/src/lib/project-env-config.ts @@ -995,7 +995,7 @@ async function isLegacyTrackedLocalOverlay(opts: { }); } -async function resolveProjectEnvEffectiveLocalConfigPath(opts: { +export async function resolveProjectEnvEffectiveLocalConfigPath(opts: { readonly projectRoot: string; readonly projectDir: string; readonly envName: string | null; @@ -1055,6 +1055,7 @@ export async function assertProjectEnvLayerPaths(opts: { export async function projectEnvConfigExists(opts: { readonly projectDir: string; + readonly inheritLocal?: boolean; }): Promise { await assertProjectEnvLayerPaths({ projectRoot: dirname(opts.projectDir), @@ -1089,6 +1090,7 @@ export async function projectEnvConfigExists(opts: { return await hasPrimaryLocalInputs({ projectRoot: dirname(opts.projectDir), projectDir: opts.projectDir, + inheritLocal: opts.inheritLocal, }); } @@ -1124,6 +1126,7 @@ export class ProjectEnvLayerPathConflictError extends HackCliError { */ export async function projectEnvConfigExistsForMutation(opts: { readonly projectDir: string; + readonly inheritLocal?: boolean; }): Promise { const entries = await readdir(opts.projectDir, { withFileTypes: true }); let linkedLayer = false; @@ -1263,7 +1266,7 @@ async function readProjectEnvConfigFile(opts: { }); } -function parseProjectEnvConfigText(opts: { +export function parseProjectEnvConfigText(opts: { readonly path: string; readonly environment: string; readonly text: string | null; @@ -1427,11 +1430,13 @@ export async function resolveProjectEnvSelection(opts: { readonly projectRoot: string; readonly projectDir: string; readonly envName?: string | null; + readonly defaultEnv?: string | null; }): Promise { const requestedEnv = opts.envName === undefined ? undefined : opts.envName; - const defaultEnv = await readProjectDefaultEnvConfig({ - projectDir: opts.projectDir, - }); + const defaultEnv = + opts.defaultEnv === undefined + ? await readProjectDefaultEnvConfig(opts) + : opts.defaultEnv; const effectiveEnv = requestedEnv === undefined ? defaultEnv : requestedEnv; const defaultPath = resolveProjectEnvConfigPath({ projectDir: opts.projectDir, @@ -1832,14 +1837,17 @@ function localOverlayLayerNames(entries: readonly string[]): string[] { export async function listProjectEnvOverlays(opts: { readonly projectRoot: string; readonly projectDir: string; + readonly primaryDir?: string | null; + readonly defaultEnv?: string | null; }): Promise { const localSuffix = `.${PROJECT_ENV_LOCAL_SEGMENT}`; const entries = await listOverlayLayerEntryNames(opts.projectDir); // Best effort, like the rest of this listing: an inheritance that cannot // be resolved adds no names (runtime reads report it). - const primaryDir = await resolvePrimaryLocalProjectDir(opts).catch( - () => null - ); + const primaryDir = + opts.primaryDir === undefined + ? await resolvePrimaryLocalProjectDir(opts).catch(() => null) + : opts.primaryDir; const inheritedNames = primaryDir === null ? [] @@ -1872,9 +1880,10 @@ export async function listProjectEnvOverlays(opts: { name !== "default" && name !== PROJECT_ENV_LOCAL_SEGMENT ); - const defaultEnv = await readProjectDefaultEnvConfig({ - projectDir: opts.projectDir, - }); + const defaultEnv = + opts.defaultEnv === undefined + ? await readProjectDefaultEnvConfig(opts) + : opts.defaultEnv; const names = new Set([ ...committed, ...discovered, @@ -3356,13 +3365,24 @@ async function readProjectEnvLayerForMutation(opts: { readonly projectRoot: string; readonly path: string; readonly environment: string; + readonly noFollow?: boolean; + readonly maxBytes?: number; }): Promise<{ readonly read: ProjectEnvConfigReadResult; /** The exact bytes read (null when absent), for the compare-and-swap. */ readonly text: string | null; }> { await assertProjectEnvLayerPath(opts); - const text = await readAtomicWriteTargetText(opts.path); + const text = opts.noFollow + ? (( + await readReplaceablePrivateFile({ + path: opts.path, + directories: [dirname(opts.path)], + maxBytes: opts.maxBytes, + refusal: () => new AtomicWriteConflictError(), + }) + )?.text ?? null) + : await readAtomicWriteTargetText(opts.path); const read = parseProjectEnvConfigText({ path: opts.path, environment: opts.environment, @@ -3627,235 +3647,280 @@ export async function protectProjectEnvEntries( return protectedEntries; } -export async function setProjectEnvValue(opts: { +type ProjectEnvLayerTarget = { readonly projectRoot: string; readonly projectDir: string; readonly envName: string | null; - readonly scope: string; - readonly key: string; - readonly value: string; - readonly secret: boolean; readonly local?: boolean; /** Bounded wait for the layer lock; tests only. */ readonly layerLockTimeoutMs?: number; -}): Promise { - await assertLegacyProjectDirectory({ projectDir: opts.projectDir }); - await assertLegacyProjectInputFamily({ projectRoot: opts.projectRoot }); - if (!PROJECT_ENV_KEY_PATTERN.test(opts.key)) { - throw new ClosedCliError(ENV_KEY_INVALID_MESSAGE); +}; + +export type ProjectEnvLayerChange = { + readonly scope: string; + readonly key: string; +} & ( + | { readonly op: "set"; readonly value: string; readonly secret: boolean } + | { readonly op: "unset" } +); + +/** Measure the env writer's prospective document without accessing a project key. */ +export function projectEnvLayerFits(opts: { + readonly path: string; + readonly text: string | null; + readonly envName: string | null; + readonly changes: readonly ProjectEnvLayerChange[]; + readonly inheritsLocal: boolean; + readonly maxBytes: number; +}): boolean { + const { config, parseError } = parseProjectEnvConfigText({ + path: opts.path, + environment: opts.envName ?? "default", + text: opts.text, + }); + // The caller reports parse errors from the original layer. + if (parseError) { + return true; + } + // AES-GCM ciphertext and its YAML representation depend on length, not + // the project key. The temporary key only exists in memory for this check. + const keyText = opts.changes.some( + (change) => change.op === "set" && change.secret + ) + ? randomBytes(32).toString("base64") + : null; + const next = nextProjectEnvLayer({ ...opts, config, keyText }); + return ( + !next.changed || + Buffer.byteLength(serializeProjectEnvConfig(next.config)) <= opts.maxBytes + ); +} + +export async function setProjectEnvValue( + opts: ProjectEnvLayerTarget & { + readonly scope: string; + readonly key: string; + readonly value: string; + readonly secret: boolean; } - const scope = assertValidProjectEnvScopeName({ - scopeName: opts.scope, +): Promise { + const scope = assertValidProjectEnvScopeName({ scopeName: opts.scope }); + const result = await mutateProjectEnvLayer({ + ...opts, + changes: [ + { + op: "set", + scope, + key: opts.key, + value: opts.value, + secret: opts.secret, + }, + ], }); + return { ...result, scope, local: opts.local === true }; +} +export async function unsetProjectEnvValue( + opts: ProjectEnvLayerTarget & { readonly scope: string; readonly key: string } +): Promise<{ readonly changed: boolean; readonly filePath: string }> { + return await mutateProjectEnvLayer({ + ...opts, + changes: [{ op: "unset", scope: opts.scope, key: opts.key }], + }); +} + +/** Publish all changes to one layer with the same lock and writer as env add/unset. */ +export async function mutateProjectEnvLayer( + opts: ProjectEnvLayerTarget & { + readonly changes: readonly ProjectEnvLayerChange[]; + readonly expected?: { + readonly file: string; + readonly text: string | null; + readonly validate?: () => Promise; + }; + readonly beforePublish?: (text: string, mode: number) => Promise; + /** A migration transaction publishes any needed ignore repair itself. */ + readonly repairGitignore?: boolean; + readonly maxBytes?: number; + } +): Promise<{ + readonly changed: boolean; + readonly filePath: string; + readonly createdKey: boolean; +}> { + await assertLegacyProjectDirectory({ projectDir: opts.projectDir }); + await assertLegacyProjectInputFamily({ projectRoot: opts.projectRoot }); + for (const change of opts.changes) { + if (!PROJECT_ENV_KEY_PATTERN.test(change.key)) { + throw new ClosedCliError(ENV_KEY_INVALID_MESSAGE); + } + assertValidProjectEnvScopeName({ scopeName: change.scope }); + } const filePath = opts.local === true - ? await resolveProjectEnvEffectiveLocalConfigPath({ - projectRoot: opts.projectRoot, - projectDir: opts.projectDir, - envName: opts.envName, - }) - : resolveProjectEnvConfigPath({ - projectDir: opts.projectDir, - envName: opts.envName, - }); + ? await resolveProjectEnvEffectiveLocalConfigPath(opts) + : resolveProjectEnvConfigPath(opts); + if (opts.expected && opts.expected.file !== filePath) { + throw new AtomicWriteConflictError(); + } await assertProjectEnvLayerPath({ projectRoot: opts.projectRoot, path: filePath, }); - // The read, the change and the write form one critical section per layer, - // so a concurrent set or unset of another key is never lost (HACK-1376). return await withEnvLayerLock({ layerPath: filePath, timeoutMs: opts.layerLockTimeoutMs, - run: async () => - await setLockedProjectEnvValue({ ...opts, scope, filePath }), + run: async () => await mutateLockedProjectEnvLayer({ ...opts, filePath }), }); } -async function setLockedProjectEnvValue(opts: { - readonly projectRoot: string; - readonly projectDir: string; - readonly envName: string | null; - readonly scope: string; - readonly key: string; - readonly value: string; - readonly secret: boolean; - readonly local?: boolean; - readonly filePath: string; -}): Promise { - const { filePath, scope } = opts; +async function mutateLockedProjectEnvLayer( + opts: Parameters[0] & { + readonly filePath: string; + } +) { + const { filePath } = opts; + await opts.expected?.validate?.(); + // The index can change after Config classified the legacy overlay. Do + // not write a checkout-local destination as a shared layer. + if ( + opts.expected && + opts.local !== true && + opts.envName === "local" && + filePath === + (await resolveProjectEnvEffectiveLocalConfigPath({ + ...opts, + envName: null, + })) + ) { + throw new AtomicWriteConflictError(); + } const { read, text } = await readProjectEnvLayerForMutation({ projectRoot: opts.projectRoot, path: filePath, environment: opts.envName ?? "default", + noFollow: opts.expected !== undefined, + maxBytes: opts.maxBytes, }); - - const nextValues: ProjectEnvValuesByScope = { - ...read.config.values, - [scope]: { - ...(read.config.values[scope] ?? {}), - }, - }; - - let createdKey = false; - let storedValue: ProjectEnvStoredValue = opts.value; - if (opts.secret) { - // The same key rules as hydration (HACK-2169): every secret already in - // this layer must open with the key readers use, and a key is never - // created while only HACK_ENV_SECRET_KEY is set (the new file would - // shadow it, so existing secrets would stop decrypting). Checked before - // any key or layer is written. - // The entry being replaced is left out: overwriting it (re-encrypting a - // value whose old ciphertext no longer opens) leaves no mixed keys. - const otherScopeValues = { ...(read.config.values[scope] ?? {}) }; - delete otherScopeValues[opts.key]; - const resolvedKey = await resolveProjectEnvHydrationKey({ - projectRoot: opts.projectRoot, - config: { - ...read.config, - values: { ...read.config.values, [scope]: otherScopeValues }, - }, - secret: true, - refuse: projectEnvSetKeyRefusal, - }); - if (resolvedKey.keyText === null) { - throw projectEnvSetKeyRefusal("wrong_key"); - } - createdKey = resolvedKey.createdKey; - storedValue = stableProjectEnvSecretValue({ - previous: read.config.values[scope]?.[opts.key], - plaintext: opts.value, - keyText: resolvedKey.keyText, - }); + if (opts.expected && opts.expected.text !== text) { + throw new AtomicWriteConflictError(); } - if (opts.local === true) { + const secrets = await projectEnvMutationKey(opts, read.config); + const hasSet = opts.changes.some((change) => change.op === "set"); + if (hasSet && opts.local === true && opts.repairGitignore !== false) { await ensureHackDirGitignoreForLocalEnvWrite({ projectDir: opts.projectDir, }); } - - const nextScopeValues = nextValues[scope] ?? {}; - nextScopeValues[opts.key] = storedValue; - nextValues[scope] = nextScopeValues; - if (!("global" in nextValues)) { - nextValues.global = {}; + const inheritsLocal = + opts.local === true && + opts.changes.some((change) => change.op === "unset") && + (await resolvePrimaryLocalProjectDir(opts)) !== null; + const next = nextProjectEnvLayer({ + ...opts, + config: read.config, + inheritsLocal, + keyText: secrets.keyText, + }); + let changed = next.changed; + if (changed || hasSet) { + changed = await writeProjectEnvConfigFile({ + projectRoot: opts.projectRoot, + path: filePath, + config: next.config, + maxBytes: opts.maxBytes, + validate: opts.expected?.validate, + beforePublish: opts.beforePublish, + noFollow: opts.expected !== undefined, + expectedExisting: text, + machineLocal: opts.local === true, + repairGitignore: opts.repairGitignore, + }); } + return { changed, filePath, createdKey: secrets.createdKey }; +} - const nextConfig: ProjectEnvConfig = { - version: PROJECT_ENV_CONFIG_VERSION, - environment: opts.envName ?? "default", - secretsprovider: PROJECT_ENV_SECRETS_PROVIDER, - values: nextValues, - }; - // The lock excludes cooperating writers; the compare-and-swap turns a write - // by anything else since the read into a closed, retryable conflict. - const changed = await writeProjectEnvConfigFile({ - projectRoot: opts.projectRoot, - path: filePath, - config: nextConfig, - expectedExisting: text, - machineLocal: opts.local === true, - }); +function nextProjectEnvLayer(opts: { + readonly config: ProjectEnvConfig; + readonly envName: string | null; + readonly changes: readonly ProjectEnvLayerChange[]; + readonly inheritsLocal: boolean; + readonly keyText: string | null; +}) { + const values: ProjectEnvValuesByScope = structuredClone(opts.config.values); + let changed = false; + for (const change of opts.changes) { + changed = + applyProjectEnvLayerChange({ ...opts, values, change }) || changed; + } return { - filePath, - scope, - createdKey, changed, - local: opts.local === true, + config: { ...opts.config, environment: opts.envName ?? "default", values }, }; } -export async function unsetProjectEnvValue(opts: { - readonly projectRoot: string; - readonly projectDir: string; - readonly envName: string | null; - readonly scope: string; - readonly key: string; - readonly local?: boolean; - /** Bounded wait for the layer lock; tests only. */ - readonly layerLockTimeoutMs?: number; -}): Promise<{ readonly changed: boolean; readonly filePath: string }> { - await assertLegacyProjectDirectory({ projectDir: opts.projectDir }); - await assertLegacyProjectInputFamily({ projectRoot: opts.projectRoot }); - const filePath = - opts.local === true - ? await resolveProjectEnvEffectiveLocalConfigPath({ - projectRoot: opts.projectRoot, - projectDir: opts.projectDir, - envName: opts.envName, - }) - : resolveProjectEnvConfigPath({ - projectDir: opts.projectDir, - envName: opts.envName, - }); - await assertProjectEnvLayerPath({ +async function projectEnvMutationKey( + opts: Parameters[0], + config: ProjectEnvConfig +) { + if (!opts.changes.some((change) => change.op === "set" && change.secret)) { + return { keyText: null, createdKey: false }; + } + // Entries being replaced do not need to open with the current reader key. + // All untouched ciphertext must still open with it. + const values = structuredClone(config.values); + for (const change of opts.changes) { + if (Object.hasOwn(values, change.scope)) { + delete values[change.scope]?.[change.key]; + } + } + const result = await resolveProjectEnvHydrationKey({ projectRoot: opts.projectRoot, - path: filePath, - }); - // Same per-layer critical section as `setProjectEnvValue` (HACK-1376). - return await withEnvLayerLock({ - layerPath: filePath, - timeoutMs: opts.layerLockTimeoutMs, - run: async () => await unsetLockedProjectEnvValue({ ...opts, filePath }), + config: { ...config, values }, + secret: true, + refuse: projectEnvSetKeyRefusal, }); + if (result.keyText === null) { + throw projectEnvSetKeyRefusal("wrong_key"); + } + return result; } -async function unsetLockedProjectEnvValue(opts: { - readonly projectRoot: string; - readonly projectDir: string; - readonly envName: string | null; - readonly scope: string; - readonly key: string; - readonly local?: boolean; - readonly filePath: string; -}): Promise<{ readonly changed: boolean; readonly filePath: string }> { - const { filePath } = opts; - const { read, text } = await readProjectEnvLayerForMutation({ - projectRoot: opts.projectRoot, - path: filePath, - environment: opts.envName ?? "default", - }); - - const scopeValues = { ...(read.config.values[opts.scope] ?? {}) }; - const inheritsLocal = - opts.local === true && (await resolvePrimaryLocalProjectDir(opts)) !== null; - if (inheritsLocal) { - if (scopeValues[opts.key] === null) { - return { changed: false, filePath }; +function applyProjectEnvLayerChange(opts: { + readonly values: ProjectEnvValuesByScope; + readonly change: ProjectEnvLayerChange; + readonly inheritsLocal: boolean; + readonly keyText: string | null; +}): boolean { + const { values, change } = opts; + const entries = { ...values[change.scope] }; + if (change.op === "set") { + entries[change.key] = + change.secret && opts.keyText !== null + ? stableProjectEnvSecretValue({ + previous: entries[change.key], + plaintext: change.value, + keyText: opts.keyText, + }) + : change.value; + } else if (opts.inheritsLocal) { + if (entries[change.key] === null) { + return false; } - scopeValues[opts.key] = null; + entries[change.key] = null; } else { - if (!(opts.key in scopeValues)) { - return { changed: false, filePath }; + if (!Object.hasOwn(entries, change.key)) { + return false; } - delete scopeValues[opts.key]; + delete entries[change.key]; } - const nextValues: ProjectEnvValuesByScope = { - ...read.config.values, - [opts.scope]: scopeValues, - }; - if (opts.scope !== "global" && Object.keys(scopeValues).length === 0) { - delete nextValues[opts.scope]; - } - if (!("global" in nextValues)) { - nextValues.global = {}; + if (change.scope !== "global" && Object.keys(entries).length === 0) { + delete values[change.scope]; + } else { + values[change.scope] = entries; } - - const changed = await writeProjectEnvConfigFile({ - projectRoot: opts.projectRoot, - path: filePath, - config: { - version: PROJECT_ENV_CONFIG_VERSION, - environment: opts.envName ?? "default", - secretsprovider: PROJECT_ENV_SECRETS_PROVIDER, - values: nextValues, - }, - expectedExisting: text, - machineLocal: opts.local === true, - }); - return { changed, filePath }; + return true; } /** Closed reasons `hydrateProjectEnvLocalLayer` refuses with; none writes a layer. */ @@ -4888,6 +4953,11 @@ async function writeProjectEnvConfigFile(opts: { readonly config: ProjectEnvConfig; /** Compare-and-swap guard; see `writeTextFileAtomicIfChanged`. */ readonly expectedExisting?: string | null; + readonly maxBytes?: number; + readonly validate?: () => Promise; + readonly noFollow?: boolean; + readonly beforePublish?: (text: string, mode: number) => Promise; + readonly repairGitignore?: boolean; /** * A machine-local layer, which may hold plaintext values: when this write * creates it, it is private (0600) from creation, and an existing layer @@ -4899,11 +4969,19 @@ async function writeProjectEnvConfigFile(opts: { readonly machineLocal?: boolean; }): Promise { const text = serializeProjectEnvConfig(opts.config); + const beforePublish = opts.beforePublish; + if (opts.maxBytes !== undefined && Buffer.byteLength(text) > opts.maxBytes) { + throw new HackCliError({ + code: "E_CONFIG_INVALID", + message: "The updated env layer exceeds the config file size limit.", + }); + } await assertLegacyProjectDirectory({ projectDir: dirname(opts.path) }); if (opts.machineLocal === true) { await assertMachineLocalLayerWriteDestination({ projectRoot: opts.projectRoot, path: opts.path, + repairGitignore: opts.repairGitignore, }); } // Rename-committed: an interrupted mutation leaves the previous layer intact. @@ -4913,9 +4991,20 @@ async function writeProjectEnvConfigFile(opts: { ? {} : { expectedExisting: opts.expectedExisting }), ...(opts.machineLocal === true - ? { createMode: 0o600, noFollowTarget: true, tightenExisting: true } + ? { createMode: 0o600, tightenExisting: true } : {}), + noFollowTarget: opts.machineLocal === true || opts.noFollow === true, + beforePublish: beforePublish + ? (mode) => beforePublish(text, mode) + : undefined, validatePath: async (path) => { + await opts.validate?.(); + if ( + opts.noFollow && + (await lstat(path).catch(() => null))?.isSymbolicLink() + ) { + throw new AtomicWriteConflictError(); + } await assertProjectEnvLayerPath({ projectRoot: opts.projectRoot, path, @@ -5059,10 +5148,14 @@ export async function assertMachineLocalFileGitPrivate(opts: { async function assertMachineLocalLayerWriteDestination(opts: { readonly projectRoot: string; readonly path: string; + readonly repairGitignore?: boolean; }): Promise { await assertMachineLocalLayerNotLinked(opts); let problem = await machineLocalLayerGitProblem(opts); if (problem === "not_ignored") { + if (opts.repairGitignore === false) { + throw new AtomicWriteConflictError(); + } // Silent: a caller has already warned about a read-only file. await ensureHackDirGitignore({ projectDir: dirname(opts.path) }); problem = await machineLocalLayerGitProblem(opts); @@ -7075,6 +7168,132 @@ export type PreparedLegacyEnvMigration = { readonly payload: (path: string) => string; }; +/** Check declared dotenv inputs without reading a legacy secret-store key or value. */ +export async function preflightLegacyEnvContract(opts: { + readonly projectRoot: string; + readonly projectDir: string; + readonly contract: HackEnvContract; + readonly projectText: string | null; + readonly writesLocalEnv: boolean; + readonly maxLayerBytes: number; +}): Promise> { + const overlayNames = await discoverLegacyOverlayNames({ + ...opts, + includeSymlinks: false, + }); + await assertNoLegacyDotenvLinks({ ...opts, overlayNames }); + await preflightLegacyEnvMigrationPaths({ ...opts, overlayNames }); + await assertContractComposeOverlaysKeepValues({ + projectDir: opts.projectDir, + overlayNames, + contractKeys: new Set(opts.contract.vars.map(({ key }) => key)), + composeRepairFollows: false, + }); + const outputs = new Map(); + const project = migratedProjectConfigText(opts.projectText, opts.projectRoot); + if (project !== null) { + outputs.set(resolve(opts.projectDir, PROJECT_CONFIG_FILENAME), project); + } + const resolved = await resolvePlaintextMigrationLayers({ + ...opts, + overlayNames, + }); + assertContractMigrationLayersAreWritable({ + baseValues: resolved[0]?.values ?? [], + overlays: resolved + .slice(1) + .map(({ name, values }) => ({ name: name ?? "", values })), + }); + let writesLocalEnv = opts.writesLocalEnv; + await prepareContractMigrationLayers( + opts, + resolved, + null, + ({ path, config }, local) => { + outputs.set(path, serializeProjectEnvConfig(config)); + writesLocalEnv ||= local; + } + ); + for (const text of outputs.values()) { + if (Buffer.byteLength(text) > opts.maxLayerBytes) { + throw new ClosedCliError( + `A migrated config file exceeds the ${opts.maxLayerBytes / 1024} KiB limit.` + ); + } + } + if (writesLocalEnv) { + const ignore = await planLocalEnvMigrationIgnore(opts); + if (ignore) { + outputs.set(ignore.path, ignore.text); + } + } + return outputs; +} + +async function resolvePlaintextMigrationLayers(opts: { + readonly projectDir: string; + readonly contract: HackEnvContract; + readonly overlayNames: readonly string[]; +}): Promise { + if ((await readHackEnvRuntimeConfig(opts)).storePlaintextInBackend) { + // The secret store can override either dotenv input. Check sizes on Apply. + return [{ name: null, values: [] }]; + } + const read = async (envName: string | null) => + parseDotEnv( + (await readLegacyDotenvText({ + path: resolveEnvFilePath({ ...opts, envName }), + })) ?? "" + ); + const base = await read(null); + const plain = opts.contract.vars.filter( + ({ source }) => source === "plain_env" + ); + return await Promise.all( + [null, ...opts.overlayNames].map(async (name) => { + const overlay = name === null ? base : await read(name); + return { + name, + values: plain.map((entry) => ({ + ...entry, + source: "plain_env", + // Legacy injection skips empty values before falling back to base. + value: overlay[entry.key] || base[entry.key] || null, + })), + }; + }) + ); +} + +async function planLocalEnvMigrationIgnore(opts: { + readonly projectDir: string; +}) { + const options = hackDirGitignoreFileOptions(opts); + const previous = await readReplaceablePrivateFile(options); + const text = mergeHackDirGitignore({ existing: previous?.text ?? null }); + return text === previous?.text + ? null + : { path: options.path, mode: previous?.mode ?? 0o644, text }; +} + +function migratedProjectConfigText( + text: string | null, + projectRoot: string +): string | null { + const parsed: unknown = text === null ? null : JSON.parse(text); + if (!isRecord(parsed)) { + return null; + } + const normalized = normalizeLegacyProjectTopLevelConfig({ + parsed, + projectRoot, + keepStorePointer: true, + }); + return normalized.changed + ? `${JSON.stringify(normalized.config, null, 2)}\n` + : null; +} + /** * Prepares the explicit, journalled migration without any filesystem mutation. * Legacy sources stay in place throughout publication. The journal owner stages @@ -7086,6 +7305,8 @@ export async function prepareLegacyProjectEnvMigration(opts: { readonly projectName: string; readonly serviceNames: readonly string[]; readonly repairCompose?: boolean; + readonly writesLocalEnv?: boolean; + readonly inheritLocal?: boolean; }): Promise { try { return await prepareLegacyProjectEnvMigrationInternal(opts); @@ -7109,7 +7330,13 @@ type AddPreparedMigrationFile = ( type AddPreparedMigrationLayer = ( write: PlannedEnvLayerWrite, local: boolean -) => Promise; +) => Promise | void; +type ResolvedMigrationLayers = readonly { + readonly name: string | null; + readonly values: readonly (ResolvedContractMigrationValue & { + readonly source: "plain_env" | "keychain"; + })[]; +}[]; type ResolvedMigrationValues = readonly (Awaited< ReturnType > & { readonly name: string | null })[]; @@ -7200,8 +7427,8 @@ async function prepareMigrationKeyIgnore( } async function prepareContractMigrationLayers( - opts: PreparedMigrationProject, - resolved: ResolvedMigrationValues, + opts: Pick, + resolved: ResolvedMigrationLayers, keyText: string | null, addLayer: AddPreparedMigrationLayer ): Promise { @@ -7331,22 +7558,15 @@ async function prepareContractMigration( ), }); const configCandidates = retained.candidates; - const configText = await readTextFile(planned.path); - if (configText) { - const parsed: unknown = JSON.parse(configText); - if (isRecord(parsed)) { - const normalized = normalizeLegacyProjectTopLevelConfig({ - parsed, - projectRoot: opts.projectRoot, - keepStorePointer: true, - }); - if (normalized.changed) { - await add( - { path: planned.path, kind: "config", keys: [], mode: 0o644 }, - `${JSON.stringify(normalized.config, null, 2)}\n` - ); - } - } + const configText = migratedProjectConfigText( + await readTextFile(planned.path), + opts.projectRoot + ); + if (configText !== null) { + await add( + { path: planned.path, kind: "config", keys: [], mode: 0o644 }, + configText + ); } return { overlayNames, store, deliveredValues, configCandidates }; } @@ -7520,6 +7740,8 @@ async function prepareLegacyProjectEnvMigrationInternal(opts: { readonly projectName: string; readonly serviceNames: readonly string[]; readonly repairCompose?: boolean; + readonly writesLocalEnv?: boolean; + readonly inheritLocal?: boolean; }): Promise { await assertLegacyProjectDirectory(opts); await assertLegacyProjectInputFamily(opts); @@ -7601,15 +7823,17 @@ async function prepareLegacyProjectEnvMigrationInternal(opts: { add, addLayer, }); - if (files.some((file) => file.kind === "local_layer")) { - const path = resolve(opts.projectDir, ".gitignore"); - const previous = await readReplaceablePrivateFile( - hackDirGitignoreFileOptions(opts) - ); - await add( - { path, kind: "ignore", keys: [], mode: previous?.mode ?? 0o644 }, - mergeHackDirGitignore({ existing: previous?.text ?? null }) - ); + if ( + opts.writesLocalEnv || + files.some((file) => file.kind === "local_layer") + ) { + const ignore = await planLocalEnvMigrationIgnore(opts); + if (ignore) { + await add( + { path: ignore.path, kind: "ignore", keys: [], mode: ignore.mode }, + ignore.text + ); + } } const composeFile = resolve(opts.projectDir, PROJECT_COMPOSE_FILENAME); if (opts.repairCompose !== false) { diff --git a/src/lib/project.ts b/src/lib/project.ts index 56c483a66b..afca12feef 100644 --- a/src/lib/project.ts +++ b/src/lib/project.ts @@ -216,7 +216,14 @@ export async function resolveEffectiveProjectName( ctx: ProjectContext ): Promise { const cfg = await readProjectConfig(ctx); - const derived = defaultProjectSlugFromPath(ctx.projectRoot); + return projectNameForConfig(cfg, ctx.projectRoot); +} + +export function projectNameForConfig( + cfg: ProjectConfig, + projectRoot: string +): string { + const derived = defaultProjectSlugFromPath(projectRoot); const raw = (cfg.name ?? derived).trim(); return sanitizeProjectSlug(raw.length > 0 ? raw : derived); } @@ -225,13 +232,19 @@ export async function readProjectDevHost( ctx: ProjectContext ): Promise { const cfg = await readProjectConfig(ctx); - if (cfg.devHost) { - return cfg.devHost; - } + return cfg.devHost ?? (await readLegacyProjectDevHost(ctx)); +} +export async function readLegacyProjectDevHost( + ctx: ProjectContext +): Promise { // Legacy fallback: older scaffolds wrote DEV_HOST into `.hack/.env`. const envText = await readTextFile(ctx.envFile); - if (!envText) { + return legacyProjectDevHost(envText); +} + +export function legacyProjectDevHost(envText: string | null): string | null { + if (envText === null) { return null; } @@ -240,6 +253,11 @@ export async function readProjectDevHost( return typeof host === "string" && host.length > 0 ? host : null; } +/** Routing namespace used by base instances without a configured hostname. */ +export function defaultProjectDevHost(projectRoot: string): string { + return `${defaultProjectSlugFromPath(projectRoot)}.${DEFAULT_PROJECT_TLD}`; +} + export async function readProjectDefaultEnvConfig(opts: { readonly projectDir: string; }): Promise { @@ -251,7 +269,17 @@ export async function readProjectDefaultEnvConfig(opts: { envFile: resolve(opts.projectDir, PROJECT_ENV_FILENAME), configFile: resolve(opts.projectDir, PROJECT_CONFIG_FILENAME), }); - return config.env?.defaultOverlay ?? config.defaultEnvConfig ?? null; + return resolveProjectDefaultEnvOverlay(config); +} + +export function resolveProjectDefaultEnvOverlay( + config: ProjectConfig +): string | null { + return ( + parseEnvConfigSelection( + config.env?.defaultOverlay ?? config.defaultEnvConfig + ) ?? null + ); } export interface ProjectConfig { @@ -690,6 +718,23 @@ function parseProjectConfigToml(opts: { return parseProjectConfigRecord(parsed, opts.path); } +/** Return the authored overlay settings before normalization. */ +export function readAuthoredProjectOverlaySettings( + value: Record +) { + const envConfig = getRecord(value, "env"); + return { + legacy: [ + getString(value, "defaultEnvConfig"), + getString(value, "default_env_config"), + ], + current: [ + envConfig ? getString(envConfig, "defaultOverlay") : undefined, + envConfig ? getString(envConfig, "default_overlay") : undefined, + ], + } as const; +} + /** Parse an already bounded configuration observation without additional file reads. */ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Project config parsing keeps schema migration and legacy compatibility explicit in one parser. export function parseProjectConfigRecord( @@ -715,13 +760,9 @@ export function parseProjectConfigRecord( : undefined; const name = getString(value, "name"); const devHost = getString(value, "dev_host"); - const envConfig = getRecord(value, "env"); - const defaultEnvConfigRaw = - getString(value, "defaultEnvConfig") ?? - getString(value, "default_env_config"); - const envDefaultOverlayRaw = - (envConfig ? getString(envConfig, "defaultOverlay") : undefined) ?? - (envConfig ? getString(envConfig, "default_overlay") : undefined); + const { legacy, current } = readAuthoredProjectOverlaySettings(value); + const defaultEnvConfigRaw = legacy[0] ?? legacy[1]; + const envDefaultOverlayRaw = current[0] ?? current[1]; const logs = parseLogsConfig(getRecord(value, "logs")); const oauth = parseOauthConfig(getRecord(value, "oauth")); const parsedOpen = parseOpenConfig(getRecord(value, "open")); diff --git a/src/lib/worktree-local-config.ts b/src/lib/worktree-local-config.ts index 5fe5c7d22a..34901fb35f 100644 --- a/src/lib/worktree-local-config.ts +++ b/src/lib/worktree-local-config.ts @@ -600,9 +600,12 @@ function isLocalInheritanceDisabledByEnv(): boolean { export async function resolvePrimaryLocalProjectDir(opts: { readonly projectRoot: string; readonly projectDir: string; + readonly inheritLocal?: boolean; }): Promise { if ( - !shouldInheritPrimaryLocalInputs({ inheritLocal: true }) || + !shouldInheritPrimaryLocalInputs({ + inheritLocal: opts.inheritLocal ?? true, + }) || isLocalInheritanceDisabledByEnv() ) { return null; @@ -621,15 +624,17 @@ export async function resolvePrimaryLocalProjectDir(opts: { if (!marker?.isFile()) { return null; } - const cfg = await readProjectConfig({ - ...opts, - projectDirName: name, - composeFile: resolve(opts.projectDir, "docker-compose.yml"), - envFile: resolve(opts.projectDir, ".env"), - configFile: resolve(opts.projectDir, "hack.config.json"), - }); - if (cfg.worktree?.inheritLocal === false) { - return null; + if (opts.inheritLocal === undefined) { + const cfg = await readProjectConfig({ + ...opts, + projectDirName: name, + composeFile: resolve(opts.projectDir, "docker-compose.yml"), + envFile: resolve(opts.projectDir, ".env"), + configFile: resolve(opts.projectDir, "hack.config.json"), + }); + if (cfg.worktree?.inheritLocal === false) { + return null; + } } const primaryRoot = await resolveVerifiedPrimaryWorktreeRoot({ projectRoot: opts.projectRoot, @@ -699,6 +704,7 @@ async function assertProjectConfigReadable(opts: { export async function hasPrimaryLocalInputs(opts: { readonly projectRoot: string; readonly projectDir: string; + readonly inheritLocal?: boolean; }): Promise { const primaryDir = await resolvePrimaryLocalProjectDir(opts); if (primaryDir === null) { diff --git a/tests/config-editor-cli.test.ts b/tests/config-editor-cli.test.ts new file mode 100644 index 0000000000..f01a0dd536 --- /dev/null +++ b/tests/config-editor-cli.test.ts @@ -0,0 +1,2592 @@ +import { afterEach, expect, setDefaultTimeout, test } from "bun:test"; +import { + chmod, + mkdir, + mkdtemp, + readFile, + realpath, + rename, + rm, + symlink, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import type { showConfigEditor } from "../src/lib/config-editor-model.ts"; +import { withEnvLayerLock } from "../src/lib/env-layer-lock.ts"; +import { normalizeEnvConfigName } from "../src/lib/project.ts"; +import { runFixtureGitSync } from "./helpers/fixture-git.ts"; +import { privateCliEnv, privateCliHome } from "./helpers/private-cli-env.ts"; +import { waitForFileContent } from "./helpers/wait-for-file-content.ts"; + +setDefaultTimeout(45_000); + +const entry = resolve(import.meta.dir, "../index.ts"); +const scratch: string[] = []; +type Report = ReturnType; + +afterEach(async () => { + for (const path of scratch.splice(0)) { + await rm(path, { force: true, recursive: true }); + } +}); + +const compose = `# Project comment +name: storefront +services: + web: + image: storefront-web:dev # keep image comment + labels: + - caddy=storefront.hack # keep route comment + - caddy.reverse_proxy={{upstreams 3000}} + - unrelated=kept + depends_on: [api] + api: + image: storefront-api:dev + labels: + caddy: "api.storefront.hack, api.external.hack" + caddy.reverse_proxy: "{{upstreams 3000}}" + ports: + - target: 3000 + published: 8300 + worker: + labels: + caddy: worker.storefront.hack + caddy.reverse_proxy: "{{upstreams 9000}}" + caddy.handle_path: "/foo/*" +`; + +function env(contents: string, name = "default"): string { + return `version: 1\nenvironment: ${name}\nsecretsprovider: project_key\nvalues:\n${contents}\n`; +} + +function git(cwd: string, ...args: string[]) { + const result = runFixtureGitSync({ cwd, args }); + expect(result.exitCode, result.stderr).toBe(0); +} + +async function fixture() { + const root = await mkdtemp(join(tmpdir(), "hack-config-editor-")); + scratch.push(root); + const main = join(root, "main"); + const project = join(main, ".hack"); + await mkdir(project, { recursive: true }); + await Promise.all([ + writeFile( + join(project, "hack.config.json"), + '{"name":"storefront","dev_host":"storefront.hack","internal":{"dns":true}}\n' + ), + writeFile(join(project, "docker-compose.yml"), compose), + writeFile( + join(project, "hack.env.default.yaml"), + env( + " global:\n LOG_LEVEL: info\n api:\n SEARCH_INDEX: products\n SERVICE_TOKEN:\n secure: fixture-ciphertext-marker" + ) + ), + writeFile( + join(project, "hack.env.qa.yaml"), + env(" global:\n SEARCH_INDEX: qa-index", "qa") + ), + writeFile( + join(main, ".gitignore"), + ".hack/.internal/\n.hack/hack.env*.local.yaml\n" + ), + ]); + git(main, "init", "-b", "main"); + git(main, "add", "."); + git(main, "commit", "-m", "fixture"); + const linked = join(root, "linked"); + git(main, "worktree", "add", "-b", "feature/search", linked); + await Promise.all([ + writeFile( + join(project, "hack.env.local.yaml"), + env(" global:\n LOG_LEVEL: debug") + ), + writeFile( + join(linked, ".hack/hack.env.local.yaml"), + env(" api:\n SEARCH_INDEX: products_fs") + ), + ]); + return { root, main, linked, project, git }; +} + +async function cli(opts: { + root: string; + cwd: string; + args: string[]; + patch?: unknown; +}) { + const child = Bun.spawn( + [ + process.execPath, + "--no-env-file", + entry, + "config", + ...opts.args, + "--json", + ], + { + cwd: opts.cwd, + env: privateCliEnv({ root: opts.root }), + stdin: + opts.patch === undefined + ? "ignore" + : new Blob([JSON.stringify(opts.patch)]), + stdout: "pipe", + stderr: "pipe", + } + ); + const [out, err, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + expect(`${out}\n${err}`.includes("fixture-ciphertext-marker")).toBe(false); + return { code, payload: JSON.parse(out) }; +} + +async function show( + root: string, + cwd: string, + ...args: string[] +): Promise { + const result = await cli({ root, cwd, args: ["show", ...args] }); + expect(result.code).toBe(0); + expect(result.payload.ok).toBe(true); + expect(result.payload.data.schema).toBe("hack.config.v1"); + return result.payload.data; +} + +function bases(report: Report) { + return Object.fromEntries( + report.layers.map((layer) => [layer.id, layer.revision]) + ); +} + +test("show resolves the selected linked checkout, route namespaces, env layers and redaction", async () => { + const f = await fixture(); + const report = await show( + f.root, + f.main, + "--branch", + "feature/search", + "--env", + "qa" + ); + expect(report.checkout).toBe(f.linked); + expect(report.branch).toBe("feature-search"); + expect(report.overlay).toBe("qa"); + expect(report.layers.find((layer) => layer.id === "4")).toMatchObject({ + inherited: true, + writable: false, + }); + expect(report.layers.find((layer) => layer.id === "6")).toMatchObject({ + ownership: "generated", + writable: false, + }); + expect( + report.services.find((service) => service.name === "api")?.routes + ).toEqual([ + { + host: "api.feature-search.storefront.hack", + port: 3000, + tls: true, + from: ["2", "6"], + }, + ]); + expect(report.env.find((row) => row.key === "SERVICE_TOKEN")).toMatchObject({ + scope: "api", + winning: "3", + values: [{ layer: "3", secret: true }], + }); + expect(report.env.find((row) => row.key === "LOG_LEVEL")).toMatchObject({ + scope: "global", + winning: "4", + }); + expect( + report.env.find((row) => row.scope === "api" && row.key === "SEARCH_INDEX") + ).toMatchObject({ winning: "5" }); + await writeFile( + join(f.main, ".hack/hack.env.preview.local.yaml"), + env(" global:\n MODE: preview", "preview") + ); + const before = await show(f.root, f.main); + expect(before.overlays).toContain("preview"); + expect(before.layers.find((layer) => layer.id === "3:qa")).toMatchObject({ + active: false, + writable: false, + }); + await writeFile( + join(f.linked, ".hack/hack.config.json"), + '{"name":"storefront","dev_host":"storefront.hack","worktree":{"inherit_local":false}}' + ); + const optedOut = await show(f.root, f.linked); + expect(optedOut.layers.some((layer) => layer.id === "4")).toBe(false); +}); + +test("validate is nonmutating and apply publishes one revision per file, retaining Compose comments and order", async () => { + const f = await fixture(); + const report = await show(f.root, f.linked); + const args = { root: f.root, cwd: f.linked }; + const patch = { + base: bases(report), + changes: [ + { layer: "1", kind: "project", path: "internal.tls", value: true }, + { + layer: "2", + kind: "route", + service: "web", + sites: "storefront.hack, shop.storefront.hack", + port: 8080, + }, + { + layer: "5", + kind: "env", + scope: "api", + key: "SEARCH_INDEX", + value: "products_new", + }, + { layer: "5", kind: "env", scope: "api", key: "PAGE_SIZE", value: "50" }, + { layer: "5", kind: "env", scope: "global", key: "LOG_LEVEL", value: "" }, + ], + }; + const validated = await cli({ ...args, args: ["validate"], patch }); + expect(validated.payload.data.valid).toBe(true); + expect(validated.payload.data.previews["2"]).toContain( + "# keep route comment" + ); + expect( + await readFile(join(f.linked, ".hack/docker-compose.yml"), "utf8") + ).toBe(compose); + const applied = await cli({ ...args, args: ["apply"], patch }); + expect(applied.payload.data).toEqual({ + schema: "hack.config.v1", + changed: ["1", "2", "5"], + restart_offered: true, + }); + const next = await show(f.root, f.linked); + const source = next.layers.find((layer) => layer.id === "2")?.source ?? ""; + expect(source).toContain( + "caddy=storefront.hack, shop.storefront.hack # keep route comment" + ); + expect(source).toContain("caddy.reverse_proxy={{upstreams 8080}}"); + expect(source.indexOf(" web:")).toBeLessThan(source.indexOf(" api:")); + expect(next.env.find((row) => row.key === "PAGE_SIZE")?.values).toEqual([ + { layer: "5", secret: false, value: "50" }, + ]); + const logLevel = next.env.find((row) => row.key === "LOG_LEVEL"); + expect(logLevel?.winning).toBe("5"); + expect(logLevel?.values.at(-1)).toEqual({ + layer: "5", + secret: false, + value: "", + }); + expect(next.project.internal).toEqual({ dns: true, tls: true }); + expect( + (await cli({ ...args, args: ["apply"], patch })).payload.error.code + ).toBe("E_CONFLICT"); +}); + +test("refuses generated layers and rejects an invalid prospective source with a line", async () => { + const f = await fixture(); + const report = await show(f.root, f.linked); + const args = { root: f.root, cwd: f.linked }; + const base = bases(report); + const readonly = await cli({ + ...args, + args: ["apply"], + patch: { + base, + changes: [{ layer: "6", kind: "source", text: "services: {}" }], + }, + }); + expect(readonly.payload.error.code).toBe("E_LAYER_READ_ONLY"); + const custom = await cli({ + ...args, + args: ["validate"], + patch: { + base, + changes: [ + { + layer: "2", + kind: "route", + service: "worker", + sites: "worker.storefront.hack", + port: 3000, + }, + ], + }, + }); + expect(custom.payload.data.issues[0]).toMatchObject({ + layer: "2", + message: "Edit this route in Source.", + }); + const text = compose.replace("depends_on: [api]", "depends_on: [cache]"); + const invalid = await cli({ + ...args, + args: ["validate"], + patch: { base, changes: [{ layer: "2", kind: "source", text }] }, + }); + expect(invalid.payload.data.valid).toBe(false); + expect(invalid.payload.data.issues[0]).toMatchObject({ + layer: "2", + path: ["services", "web", "depends_on"], + line: 10, + }); + expect( + await readFile(join(f.linked, ".hack/docker-compose.yml"), "utf8") + ).toBe(compose); +}); + +test("show reports missing, unreadable JSON and read-only layers distinctly", async () => { + const f = await fixture(); + expect((await show(f.root, f.root)).state).toBe("missing"); + const path = join(f.project, "hack.config.json"); + await writeFile(path, '{\n "name": "shop"\n "internal": {}\n}\n'); + const invalid = await show(f.root, f.main); + expect(invalid.state).toBe("invalid"); + expect(invalid.issues[0]).toMatchObject({ + layer: "1", + line: 3, + code: "E_CONFIG_PARSE", + }); + expect(invalid.layers[0]?.source).toBeNull(); + const linkedPath = join(f.linked, ".hack/hack.config.json"); + await writeFile(linkedPath, '{\n "name": "shop"\n "internal": {}\n}\n'); + const linkedInvalid = await show(f.root, f.linked); + expect(linkedInvalid.state).toBe("invalid"); + expect(linkedInvalid.issues[0]).toMatchObject({ + layer: "1", + line: 3, + code: "E_CONFIG_PARSE", + }); + expect(linkedInvalid.layers.some((layer) => layer.inherited)).toBe(false); + await writeFile(path, "{}"); + await chmod(path, 0o444); + expect((await show(f.root, f.main)).layers[0]?.writable).toBe(false); +}); + +test("duplicate project JSON properties are reported on the duplicate line before any form write", async () => { + const f = await fixture(); + const path = join(f.project, "hack.config.json"); + const source = '{\n "name": "first",\n "name": "second"\n}\n'; + await writeFile(path, source); + const report = await show(f.root, f.main); + expect(report.state).toBe("invalid"); + expect(report.issues[0]).toMatchObject({ + layer: "1", + line: 3, + message: "Each JSON field must appear once.", + }); + const result = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(report), + changes: [{ layer: "1", kind: "project", path: "name", value: "new" }], + }, + }); + expect(result.payload.ok).toBe(false); + expect(await readFile(path, "utf8")).toBe(source); +}); + +test("a revision conflict preflights all layers without applying earlier changes", async () => { + const f = await fixture(); + const report = await show(f.root, f.main); + const before = await readFile(join(f.project, "hack.config.json"), "utf8"); + const external = `${compose}\n# changed outside Hack\n`; + await writeFile(join(f.project, "docker-compose.yml"), external); + const result = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(report), + changes: [ + { + layer: "1", + kind: "project", + path: "dev_host", + value: "new.storefront.hack", + }, + ], + }, + }); + expect(result.code).toBe(1); + expect(result.payload.error.code).toBe("E_CONFLICT"); + expect(await readFile(join(f.project, "hack.config.json"), "utf8")).toBe( + before + ); + expect(await readFile(join(f.project, "docker-compose.yml"), "utf8")).toBe( + external + ); +}); + +test("Source saves surrounding edits while preserving private slots", async () => { + const f = await fixture(); + const file = join(f.project, "docker-compose.yml"); + const original = compose.replace( + " image: storefront-web:dev", + " environment:\n SERVICE_TOKEN: fixture-ciphertext-marker\n image: storefront-web:dev" + ); + await writeFile(file, original); + const report = await show(f.root, f.main); + const layer = report.layers.find((item) => item.id === "2"); + expect(layer?.source_writable).toBe(true); + expect(layer?.source).toContain('"[redacted:1]"'); + const before = layer?.source ?? ""; + const patch = { + base: bases(report), + changes: [ + { + layer: "2", + kind: "source", + text: before.replace("storefront-web:dev", "storefront-web:test"), + }, + ], + }; + const applied = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch, + }); + expect(applied.payload.ok).toBe(true); + expect( + (await readFile(file, "utf8")) === + original.replace("storefront-web:dev", "storefront-web:test") + ).toBe(true); + const current = await show(f.root, f.main); + for (const replacement of ["PUBLIC_NAME", "OTHER_TOKEN"]) { + const refused = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(current), + changes: patch.changes.map((change) => ({ + ...change, + text: change.text.replace("SERVICE_TOKEN", replacement), + })), + }, + }); + expect(refused.payload.error.code).toBe("E_CONFIG_INVALID"); + } +}); + +test.each([ + "list", + "map", +] as const)("show omits credential-bearing dependency names in Compose %s syntax", async (syntax) => { + const f = await fixture(); + const marker = "fixture-dependency-sentinel"; + const dependency = `https://fixture:${marker}@registry.example.test`; + const field = + syntax === "list" + ? ` depends_on: [api, "${dependency}"]` + : ` depends_on:\n api: {condition: service_started}\n "${dependency}": {condition: service_started}`; + const path = join(f.project, "docker-compose.yml"); + const text = compose.replace(" depends_on: [api]", field); + await writeFile(path, text); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(marker)).toBe(false); + expect( + report.services.find((service) => service.name === "web")?.depends_on + ).toEqual(["api"]); + expect(report.issues[0]).toMatchObject({ + layer: "2", + code: "E_CONFIG_INVALID", + path: ["services", "web", "depends_on"], + line: syntax === "list" ? 10 : 11, + }); + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test.each([ + "list", + "map", +] as const)("Compose %s dependency diagnostics omit token-shaped names", async (syntax) => { + const f = await fixture(); + const privateDependency = `ghp_${"FixtureOnly".repeat(4)}.example.test`; + const field = + syntax === "list" + ? ` depends_on: [api, ${privateDependency}]` + : ` depends_on:\n api: {condition: service_started}\n ${privateDependency}: {condition: service_started}`; + const path = join(f.project, "docker-compose.yml"); + const text = compose + .replace(" depends_on: [api]", field) + .replace(" worker:\n", " worker:\n depends_on: [public-worker]\n"); + await writeFile(path, text); + + const report = await show(f.root, f.main); + const diagnostic = { + layer: "2", + path: ["services", "web", "depends_on"], + line: syntax === "list" ? 10 : 11, + code: "E_CONFIG_INVALID", + message: "depends_on names a service that is not defined.", + }; + expect(JSON.stringify(report).includes(privateDependency)).toBe(false); + expect(report.issues).toContainEqual(diagnostic); + expect(report.issues).toContainEqual( + expect.objectContaining({ + message: "depends_on names a service that is not defined: public-worker", + }) + ); + + const patch = { + base: bases(report), + changes: [{ layer: "1", kind: "project", path: "name", value: "shop" }], + }; + for (const command of ["validate", "apply"]) { + const result = await cli({ ...f, cwd: f.main, args: [command], patch }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail?.issues; + expect(JSON.stringify(result.payload).includes(privateDependency)).toBe( + false + ); + expect(issues).toContainEqual(diagnostic); + } + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test("show redacts a credential-bearing Compose service key and its issue path", async () => { + const f = await fixture(); + const marker = "fixture-service-sentinel"; + const name = `https://fixture:${marker}@registry.example.test`; + const path = join(f.project, "docker-compose.yml"); + const text = compose.replace( + "services:\n", + `services:\n "${name}": {ports: [70000]}\n` + ); + await writeFile(path, text); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(marker)).toBe(false); + expect(report.services.map((service) => service.name)).toEqual([ + "web", + "api", + "worker", + ]); + expect(report.issues[0]).toMatchObject({ + layer: "2", + code: "E_CONFIG_INVALID", + path: ["services", "[redacted]", "ports"], + line: 4, + }); + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test("Compose report and patch diagnostics redact a token-shaped service name", async () => { + const f = await fixture(); + const name = `glpat-${"FixtureOnly".repeat(3)}`; + const path = join(f.project, "docker-compose.yml"); + const text = compose.replace( + "services:\n", + `services:\n ${name}: {image: alpine}\n` + ); + await writeFile(path, text); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(name)).toBe(false); + expect(report.services.map((service) => service.name)).toEqual([ + "web", + "api", + "worker", + ]); + const patch = { + base: bases(report), + changes: [ + { + layer: "2", + kind: "service", + service: name, + field: "ports", + value: [70_000], + }, + ], + }; + for (const command of ["validate", "apply"]) { + const result = await cli({ ...f, cwd: f.main, args: [command], patch }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail?.issues; + expect(JSON.stringify(result.payload).includes(name)).toBe(false); + expect(issues).toContainEqual( + expect.objectContaining({ + path: ["services", "[redacted]", "ports"], + message: "Enter Compose port mappings.", + }) + ); + } + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test("project reports hide credential-bearing JSON keys and keep ordinary settings editable", async () => { + const f = await fixture(); + const marker = "fixture-project-key-sentinel"; + const name = `https://fixture:${marker}@registry.example.test`; + const tokenKey = `ghp_${"FixtureOnly".repeat(4)}`; + const path = join(f.project, "hack.config.json"); + const config = { + name: "storefront", + dev_host: "storefront.hack", + internal: { dns: true, [name]: "private entry" }, + additional: [{ [tokenKey]: "private array entry", keep: true }], + }; + const text = JSON.stringify(config); + await writeFile(path, text); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(marker)).toBe(false); + expect(JSON.stringify(report).includes(tokenKey)).toBe(false); + expect(report.project).toEqual({ + name: "storefront", + dev_host: "storefront.hack", + internal: { dns: true }, + additional: [{ keep: true }], + }); + expect(report.layers.find((layer) => layer.id === "1")).toMatchObject({ + hidden: true, + source: null, + source_writable: false, + }); + const patch = { + base: bases(report), + changes: [{ layer: "1", kind: "project", path: "name", value: "shop" }], + }; + const validated = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch, + }); + expect(validated.payload.data.valid).toBe(true); + expect(validated.payload.data.previews["1"]).toBeNull(); + expect(JSON.stringify(validated.payload).includes(tokenKey)).toBe(false); + const applied = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch, + }); + expect(applied.payload.ok).toBe(true); + const current = JSON.parse(await readFile(path, "utf8")); + expect( + JSON.stringify(current) === JSON.stringify({ ...config, name: "shop" }) + ).toBe(true); +}); + +test("show omits credential-bearing map keys from legacy project data and env previews", async () => { + const f = await fixture(); + const marker = "fixture-local-map-key-sentinel"; + const key = `https://fixture:${marker}@registry.example.test`; + await Promise.all([ + rm(join(f.project, "hack.config.json")), + writeFile( + join(f.project, "hack.toml"), + `name = "storefront"\n"${key}" = "private entry"\n[internal]\ndns = true\n` + ), + writeFile( + join(f.project, "hack.env.default.yaml"), + `${env(" global:\n LOG_LEVEL: info")}\n"${key}": private entry\n` + ), + ]); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(marker)).toBe(false); + expect(report.project).toEqual({ + name: "storefront", + internal: { dns: true }, + }); + expect(report.env.find((row) => row.key === "LOG_LEVEL")).toMatchObject({ + values: expect.arrayContaining([ + { layer: "3", secret: false, value: "info" }, + ]), + }); + expect(report.layers.find((layer) => layer.id === "3")).toMatchObject({ + hidden: true, + source: null, + }); +}); + +test("legacy OAuth reports redact scalar credentials and preserve routing settings", async () => { + const f = await fixture(); + const credential = `ghp_${"FixtureOnly".repeat(4)}`; + const path = join(f.project, "hack.toml"); + await rm(join(f.project, "hack.config.json")); + + for (const [oauth, expected] of [ + [`oauth = "${credential}"\n`, "[redacted]"], + [ + `[oauth]\nenabled = true\ntld = "oauth.hack"\ntoken = "${credential}"\n`, + { enabled: true, tld: "oauth.hack", token: "[redacted]" }, + ], + ] as const) { + const text = `name = "storefront"\n${oauth}`; + await writeFile(path, text); + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(credential)).toBe(false); + expect(report.project).toEqual({ name: "storefront", oauth: expected }); + expect(report.layers.find((layer) => layer.id === "1")).toMatchObject({ + hidden: true, + source: null, + }); + expect((await readFile(path, "utf8")) === text).toBe(true); + } +}); + +test("show masks plaintext GitHub tokens in local env cells and Source", async () => { + const f = await fixture(); + const byName = "fixture-opaque-pat-sentinel"; + const byValue = `ghp_${"FixtureOnly".repeat(4)}`; + const path = join(f.project, "hack.env.local.yaml"); + const text = env( + ` global:\n GITHUB_PAT: ${byName}\n ADAPTER: ${byValue}\n LOG_LEVEL: debug` + ); + await writeFile(path, text); + + const report = await show(f.root, f.main); + expect(JSON.stringify(report).includes(byName)).toBe(false); + expect(JSON.stringify(report).includes(byValue)).toBe(false); + for (const key of ["GITHUB_PAT", "ADAPTER"]) { + expect(report.env.find((row) => row.key === key)?.values).toEqual([ + { layer: "5", secret: true }, + ]); + } + expect( + report.env.find((row) => row.key === "LOG_LEVEL")?.values + ).toContainEqual({ layer: "5", secret: false, value: "debug" }); + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test("Config hides credential-shaped env keys and scopes from local reports", async () => { + const f = await fixture(); + const privateKey = `AKIA${"FIXTURE9".repeat(2)}`; + const privateScope = `glpat-${"fixtureonly".repeat(3)}`; + const path = join(f.project, "hack.env.local.yaml"); + const text = env( + ` global:\n ${privateKey}: fixture-private-key-value\n LOG_LEVEL: debug\n ${privateScope}:\n ADAPTER: fixture-private-scope-value` + ); + await writeFile(path, text); + + const report = await show(f.root, f.main); + const output = JSON.stringify(report); + for (const marker of [ + privateKey, + privateScope, + "fixture-private-key-value", + "fixture-private-scope-value", + ]) { + expect(output.includes(marker)).toBe(false); + } + expect(report.layers.find((layer) => layer.id === "5")).toMatchObject({ + hidden: true, + source: null, + }); + expect( + report.env.find((row) => row.key === "LOG_LEVEL")?.values + ).toContainEqual({ layer: "5", secret: false, value: "debug" }); + expect((await readFile(path, "utf8")) === text).toBe(true); +}); + +test("Config omits PAT-shaped Caddy hosts from routes and route edits", async () => { + const f = await fixture(); + const privateSite = `glpat-${"FixtureOnly".repeat(3)}`; + const path = join(f.project, "docker-compose.yml"); + const text = compose.replace( + 'caddy: "api.storefront.hack, api.external.hack"', + `caddy: "api.storefront.hack, ${privateSite}"` + ); + await writeFile(path, text); + + const report = await show(f.root, f.main); + const api = report.services.find((service) => service.name === "api"); + expect(api?.routes.map((route) => route.host).includes(privateSite)).toBe( + false + ); + expect(api?.route_edit?.sites.includes(privateSite)).toBe(false); + expect(api?.routes.map((route) => route.host)).toEqual([ + "api.storefront.hack", + ]); + expect(api?.route_edit).toEqual({ sites: "api.storefront.hack", port: 3000 }); + expect(JSON.stringify(report).includes(privateSite)).toBe(false); + + const applied = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(report), + changes: [ + { + layer: "2", + kind: "route", + service: "api", + sites: "api.storefront.hack", + port: 4000, + }, + ], + }, + }); + expect(applied.payload.ok).toBe(true); + const updated = await readFile(path, "utf8"); + expect(updated.includes(privateSite)).toBe(true); + expect(updated).toContain('caddy.reverse_proxy: "{{upstreams 4000}}"'); +}); + +test("show and validation previews omit authorization headers and commands", async () => { + const f = await fixture(); + const [projectPath, composePath] = [ + "hack.config.json", + "docker-compose.yml", + ].map((file) => join(f.project, file)); + if (!(projectPath && composePath)) { + throw new Error("Expected fixture layer paths."); + } + const command = "curl -H 'Authorization: fixture-ciphertext-marker'"; + await Promise.all([ + writeFile( + projectPath, + JSON.stringify({ + name: "storefront", + startup: [{ run: command }], + lifecycle: { up: { before: [command] } }, + }) + ), + writeFile( + composePath, + compose + .replace( + "- unrelated=kept", + "- caddy.reverse_proxy.header_up=Authorization Bearer fixture-ciphertext-marker" + ) + .replace( + ' caddy.handle_path: "/foo/*"', + " caddy.reverse_proxy.header_up: Authorization fixture-ciphertext-marker" + ) + ), + writeFile( + join(f.project, "hack.env.default.yaml"), + env( + " global:\n REDIS_URL: redis://:fixture-ciphertext-marker@redis.example.test:6379\n REGISTRY_URL: https://fixture-ciphertext-marker@registry.example.test" + ) + ), + ]); + const report = await show(f.root, f.main); + expect(report.layers[0]?.hidden).toBe(true); + expect(report.layers[1]?.hidden).toBe(true); + expect( + report.env + .filter((row) => ["REDIS_URL", "REGISTRY_URL"].includes(row.key)) + .map((row) => row.values[0]?.secret) + ).toEqual([true, true]); + const result = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { + base: bases(report), + changes: [ + { layer: "1", kind: "project", path: "name", value: "shop" }, + { + layer: "2", + kind: "service", + service: "web", + field: "image", + value: "test:latest", + }, + ], + }, + }); + expect(result.payload.data.valid).toBe(true); + expect(result.payload.data.previews["1"]).toContain('"[redacted:'); + expect(result.payload.data.previews["2"]).toContain('"[redacted:'); + await writeFile( + composePath, + `${compose}# Registry example https://fixture-ciphertext-marker@registry.example.test\n` + ); + const privateComment = await show(f.root, f.main); + expect(privateComment.layers[1]?.source).toBeNull(); + const commentPreview = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { + base: bases(privateComment), + changes: [ + { + layer: "2", + kind: "service", + service: "web", + field: "image", + value: "test:latest", + }, + ], + }, + }); + expect(commentPreview.payload.data.valid).toBe(true); + expect(commentPreview.payload.data.previews["2"]).toBeNull(); +}); + +test("minimal revisions cannot redirect a stale worktree patch to the main checkout", async () => { + const f = await fixture(); + const branch = ["--branch", "feature/search"]; + const report = await show(f.root, f.main, ...branch); + const base = bases(report); + const main = await show(f.root, f.main); + // The project JSON is identical and the generated override is missing in both. + expect(report.layers.find((layer) => layer.id === "6")?.exists).toBe(false); + expect(base["1"]).not.toBe(bases(main)["1"]); + f.git(f.main, "worktree", "remove", "--force", f.linked); + const stale = await cli({ + root: f.root, + cwd: f.main, + args: ["apply", ...branch], + patch: { + base: { "1": base["1"] }, + changes: [{ layer: "1", kind: "project", path: "name", value: "stale" }], + }, + }); + expect(stale.payload.error.code).toBe("E_CONFLICT"); + expect((await show(f.root, f.main)).project.name).toBe("storefront"); +}); + +test("the local overlay cannot alias the private base layer, while a tracked local overlay still works", async () => { + const f = await fixture(); + const overlay = ["--env", "local"]; + const report = await show(f.root, f.main, ...overlay); + expect(report.layers.find((layer) => layer.id === "3:local")).toBeUndefined(); + const local = report.layers.find((layer) => layer.id === "5"); + expect(local?.file.endsWith("/hack.env.local.yaml")).toBe(true); + expect(local?.ownership).toBe("local"); + f.git(f.main, "add", "-f", ".hack/hack.env.local.yaml"); + const legacy = await show(f.root, f.main, ...overlay); + expect(legacy.layers.find((layer) => layer.id === "3:local")).toMatchObject({ + file: local?.file, + ownership: "shared", + writable: true, + }); + expect(legacy.layers.find((layer) => layer.id === "5")?.file).toEndWith( + "/hack.env.default.local.yaml" + ); +}); + +test("form and Source validation reject invalid Compose ports, services and hostnames", async () => { + const f = await fixture(); + const base = bases(await show(f.root, f.main)); + const invalid = [ + [ + { + layer: "2", + kind: "service", + service: "web", + field: "ports", + value: ["99999"], + }, + "2", + ], + [{ layer: "2", kind: "source", text: "services:\n web: 42\n" }, "2"], + [ + { layer: "1", kind: "source", text: '{\n "dev_host": "bad host"\n}' }, + "1", + ], + ] as const; + for (const [change, layer] of invalid) { + const check = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { base, changes: [change] }, + }); + expect(check.payload.data.valid).toBe(false); + expect(check.payload.data.issues[0]?.layer).toBe(layer); + } +}); + +test("oversized serialized project and env files fail preflight before an earlier layer writes", async () => { + const f = await fixture(); + const base = bases(await show(f.root, f.main)); + const text = "é".repeat(270_000); + const source = { + layer: "1", + kind: "source", + text: JSON.stringify({ example: text }), + }; + const project = { + layer: "1", + kind: "project", + path: "name", + value: "oversize", + }; + for (const changes of [ + [source], + [ + project, + { + layer: "5", + kind: "env", + scope: "global", + key: "LARGE_VALUE", + value: text, + }, + ], + [ + project, + { + layer: "5", + kind: "env", + scope: "global", + key: "LARGE_SECRET", + value: "a".repeat(410_000), + secret: true, + }, + ], + ]) { + const check = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { base, changes }, + }); + expect(check.payload.error.code).toBe("E_CONFIG_INVALID"); + expect(check.payload.error.detail.issues[0]?.message).toContain("512 KiB"); + } + expect(bases(await show(f.root, f.main))).toEqual(base); +}); + +test("branch routes require an authored or legacy dev host", async () => { + const f = await fixture(); + await writeFile(join(f.project, "hack.config.json"), "{}"); + const args = ["--branch", "branch-copy"]; + const report = await show(f.root, f.main, ...args); + expect(report.services.every((service) => service.routes.length === 0)).toBe( + true + ); + expect( + report.issues.some((issue) => issue.path.join(".") === "dev_host") + ).toBe(true); + await writeFile(join(f.project, ".env"), "DEV_HOST=storefront.hack\n"); + const withLegacyHost = await show(f.root, f.main, ...args); + expect( + withLegacyHost.services.find((service) => service.name === "web")?.routes[0] + ?.host + ).toBe("branch-copy.storefront.hack"); +}); + +test("the longest supported overlay can be included in a patch base", async () => { + const f = await fixture(); + const name = "a".repeat(128); + await writeFile( + join(f.project, `hack.env.${name}.yaml`), + env(" global: {}", name) + ); + const base = bases(await show(f.root, f.main)); + expect(base[`3:${name}`]).toBeDefined(); + const result = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base, + changes: [ + { layer: "1", kind: "project", path: "name", value: "long-overlay" }, + ], + }, + }); + expect(result.payload.ok).toBe(true); +}); + +test("config set reads project JSON only after acquiring the editor's writer lock", async () => { + const f = await fixture(); + const layerPath = join(f.project, "hack.config.json"); + const child = await withEnvLayerLock({ + layerPath, + run: async () => { + const pending = Bun.spawn( + [ + process.execPath, + "--no-env-file", + entry, + "config", + "set", + "name", + "shop", + ], + { + cwd: f.main, + env: privateCliEnv({ root: f.root }), + stdout: "ignore", + stderr: "ignore", + } + ); + expect( + await Promise.race([ + pending.exited, + Bun.sleep(700).then(() => "waiting"), + ]) + ).toBe("waiting"); + await writeFile( + layerPath, + '{"name":"storefront","dev_host":"editor.hack"}\n' + ); + return pending; + }, + }); + expect(await child.exited).toBe(0); + expect((await show(f.root, f.main)).project).toMatchObject({ + name: "shop", + dev_host: "editor.hack", + }); +}); + +test("a concurrent apply using the same base can commit only once", async () => { + const f = await fixture(); + const base = bases(await show(f.root, f.main)); + const outcomes = await Promise.all( + ["first", "second"].map((value) => + cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base, + changes: [{ layer: "1", kind: "project", path: "name", value }], + }, + }) + ) + ); + const failures = outcomes.filter((outcome) => outcome.code === 1); + expect(failures).toHaveLength(1); + expect(failures[0]?.payload.error.code).toBe("E_CONFLICT"); +}); + +test("pending env migration blocks the selected checkout and readers of its inherited layers", async () => { + const f = await fixture(); + const base = bases(await show(f.root, f.main)); + const primary = await realpath(f.main); + const hash = new Bun.CryptoHasher("sha256").update(primary).digest("hex"); + const journal = join(privateCliHome(f.root), ".hack/env-migrations", hash); + await mkdir(journal, { recursive: true, mode: 0o700 }); + await writeFile( + join(journal, "journal.json"), + JSON.stringify({ + version: 1, + kind: "hack-env-migration", + project: { projectRoot: primary }, + state: "applying", + }), + { mode: 0o600 } + ); + const [selected, inherited, apply] = await Promise.all([ + cli({ root: f.root, cwd: f.main, args: ["show"] }), + cli({ root: f.root, cwd: f.linked, args: ["show"] }), + cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base, + changes: [ + { + layer: "5", + kind: "env", + scope: "global", + key: "TEST", + value: "new", + }, + ], + }, + }), + ]); + for (const result of [selected, inherited, apply]) { + expect(result.payload.error.message).toContain("migration is unfinished"); + } +}); + +test("the first Config env write migrates an existing legacy contract before publishing its change", async () => { + const root = await mkdtemp(join(tmpdir(), "hack-config-legacy-env-")); + scratch.push(root); + const cwd = join(root, "legacy"); + const project = join(cwd, ".hack"); + await mkdir(project, { recursive: true }); + const storePath = join(cwd, "legacy-secrets.enc.json"); + const keyPath = join(cwd, "legacy-store.key"); + await Promise.all([ + writeFile( + join(project, "hack.config.json"), + JSON.stringify({ + name: "legacy", + dev_host: "legacy.hack", + defaultEnvConfig: "qa", + controlPlane: { + secrets: { + backend: "encrypted_file", + encryptedFile: { path: storePath, keyPath }, + }, + }, + }) + ), + writeFile( + join(project, "docker-compose.yml"), + "services:\n api:\n image: test:dev\n" + ), + writeFile( + join(project, "hack.env.json"), + JSON.stringify({ + version: 1, + vars: [ + { key: "EXISTING", source: "plain_env", services: ["api"] }, + { key: "ANOTHER", source: "plain_env" }, + { key: "SECRET_TOKEN", source: "keychain", services: ["api"] }, + ], + }) + ), + writeFile(join(project, ".env"), "EXISTING=kept\nANOTHER=also-kept\n"), + writeFile(join(project, ".env.qa"), "ANOTHER=qa-override\n"), + ]); + const storeModule = resolve(import.meta.dir, "../src/lib/secret-store.ts"); + const store = Bun.spawn([process.execPath, "--no-env-file", "-"], { + cwd, + env: privateCliEnv({ root }), + stdin: new Blob([ + "import { resolveSecretStore } from ", + JSON.stringify(storeModule), + ';\nconst store = await resolveSecretStore({ projectDir: ".hack", projectName: "legacy" });\n', + 'await store.set({ key: "SECRET_TOKEN", value: "fixture-ciphertext-marker" });\n', + ]), + stdout: "ignore", + stderr: "ignore", + }); + expect(await store.exited).toBe(0); + const selection = ["--env", "new"]; + const before = await show(root, cwd, ...selection); + const source = before.layers.find((layer) => layer.id === "1")?.source ?? ""; + const patch = { + base: bases(before), + changes: [ + { + layer: "1", + kind: "source", + text: source.replace('"legacy"', '"renamed"'), + }, + { layer: "5", kind: "env", scope: "api", key: "NEW", value: "added" }, + { + layer: "5:new", + kind: "env", + scope: "api", + key: "NEW_OVERLAY", + value: "chosen", + }, + ], + }; + const heldKey = join(cwd, "held-test-key"); + await rename(keyPath, heldKey); + const validation = await cli({ + root, + cwd, + args: ["validate", ...selection], + patch, + }); + expect(validation.payload.data.valid).toBe(true); + expect(await Bun.file(keyPath).exists()).toBe(false); + const overlap = await cli({ + root, + cwd, + args: ["validate", ...selection], + patch: { + ...patch, + changes: [ + { + layer: "1", + kind: "source", + text: source.replace('"qa"', '"staging"'), + }, + patch.changes[1], + ], + }, + }); + expect(overlap.payload.data.issues[0]?.message).toContain("same setting"); + await rename(heldKey, keyPath); + const applied = await cli({ + root, + cwd, + args: ["apply", ...selection], + patch, + }); + expect(applied.payload.ok).toBe(true); + expect(applied.payload.data.restart_offered).toBe(true); + expect(applied.payload.data.changed).toEqual( + expect.arrayContaining(["3:qa", "5:qa", "5:new"]) + ); + const after = await show(root, cwd); + expect(after.project.name).toBe("renamed"); + expect(after.project.defaultEnvConfig).toBeUndefined(); + expect(after.project.env).toMatchObject({ defaultOverlay: "qa" }); + expect(after.env.find((row) => row.key === "SECRET_TOKEN")).toMatchObject({ + scope: "api", + values: [expect.objectContaining({ secret: true })], + }); + expect( + after.env.map((row) => [row.key, row.scope, row.values[0]?.value]) + ).toEqual( + expect.arrayContaining([ + ["EXISTING", "api", "kept"], + ["ANOTHER", "global", "also-kept"], + ["NEW", "api", "added"], + ]) + ); +}); + +test("Config preflights malformed and oversized legacy migration data before applying a mixed patch", async () => { + const root = await mkdtemp(join(tmpdir(), "hack-config-legacy-preflight-")); + scratch.push(root); + const project = join(root, ".hack"); + await mkdir(project); + const original = '{"name":"legacy","dev_host":"legacy.hack"}\n'; + const projectFile = join(project, "hack.config.json"); + const contract = join(project, "hack.env.json"); + const oversizedValue = "é".repeat(270_000); + await Promise.all([ + writeFile(projectFile, original), + writeFile( + join(project, "docker-compose.yml"), + "services:\n api:\n image: test:dev\n" + ), + writeFile(contract, "{"), + writeFile( + join(project, ".env"), + ["EXISTING=", oversizedValue, "\n"].join("") + ), + ]); + const before = await show(root, root); + const patch = { + base: bases(before), + changes: [ + { layer: "1", kind: "project", path: "name", value: "renamed" }, + { layer: "5", kind: "env", scope: "api", key: "NEW", value: "added" }, + ], + }; + const malformed = await cli({ root, cwd: root, args: ["validate"], patch }); + expect(malformed.payload.data.issues[0]?.message).toContain("env contract"); + await writeFile( + contract, + '{"version":1,"vars":[{"key":"EXISTING","source":"plain_env"}]}\n' + ); + const oversized = await cli({ root, cwd: root, args: ["apply"], patch }); + expect(oversized.payload.error.detail.issues[0]?.message).toContain( + "512 KiB" + ); + await writeFile(join(project, ".env"), `EXISTING=${"a".repeat(300_000)}\n`); + const combined = await cli({ + root, + cwd: root, + args: ["validate"], + patch: { + ...patch, + changes: [ + { + layer: "5", + kind: "env", + scope: "api", + key: "NEW", + value: "b".repeat(300_000), + }, + ], + }, + }); + expect(combined.payload.data.issues[0]?.message).toContain("512 KiB"); + expect(await readFile(projectFile, "utf8")).toBe(original); + expect(bases(await show(root, root))).toEqual(bases(before)); +}); + +test("legacy env validation accepts TOML and reports migration consent before Apply", async () => { + const root = await mkdtemp(join(tmpdir(), "hack-config-legacy-source-")); + scratch.push(root); + for (const format of ["toml", "json"]) { + const cwd = join(root, format); + const project = join(cwd, ".hack"); + await mkdir(project, { recursive: true }); + await Promise.all([ + writeFile( + join(project, "docker-compose.yml"), + "services:\n api:\n image: alpine\n" + ), + writeFile( + join(project, "hack.env.json"), + '{"version":1,"vars":[{"key":"LEGACY","source":"plain_env"}]}\n' + ), + writeFile( + join(project, ".env"), + format === "toml" ? "" : "LEGACY=retained\n" + ), + format === "toml" + ? writeFile( + join(project, "hack.toml"), + 'name = "legacy"\ndev_host = "legacy.hack"\n' + ) + : writeFile( + join(project, "hack.config.json"), + '{"name":"legacy","dev_host":"legacy.hack","defaultEnvConfig":"qa"}\n' + ), + ]); + if (format === "json") { + git(cwd, "init", "-b", "main"); + git(cwd, "add", ".hack/hack.config.json"); + } + const selection = ["--env", "default"]; + const before = await show(root, cwd, ...selection); + const patch = { + base: bases(before), + changes: [ + { + layer: "5", + kind: "env", + scope: "global", + key: "NEW", + value: "added", + }, + ], + }; + const { payload } = await cli({ + root, + cwd, + patch, + args: ["validate", ...selection], + }); + if (format === "toml") { + expect(payload.data.valid).toBe(true); + expect( + (await cli({ root, cwd, patch, args: ["apply", ...selection] })).payload + .ok + ).toBe(true); + expect(await Bun.file(join(project, ".gitignore")).exists()).toBe(true); + } else { + expect(payload.data.valid).toBe(false); + expect(payload.data.issues[0]?.message).toContain( + "--accept-tracked-env-changes" + ); + } + } +}); + +test("legacy env validation matches empty values, Compose order, and normalized JSON size", async () => { + const root = await mkdtemp(join(tmpdir(), "hack-config-legacy-preflight-")); + scratch.push(root); + const project = join(root, ".hack"); + await mkdir(project); + const json = join(project, "hack.config.json"); + const composeFile = join(project, "docker-compose.yml"); + const ignore = join(project, ".gitignore"); + const settings = { name: "legacy", dev_host: "legacy.hack" }; + const simpleCompose = "services:\n api:\n image: alpine\n"; + await Promise.all([ + writeFile(json, JSON.stringify(settings)), + writeFile(composeFile, simpleCompose), + writeFile(ignore, "# tracked legacy rules\n"), + writeFile(join(project, ".env"), "OPTIONAL=\n"), + writeFile( + join(project, "hack.env.json"), + '{"version":1,"vars":[{"key":"OPTIONAL","source":"plain_env"}]}\n' + ), + ]); + git(root, "init", "-b", "main"); + git(root, "add", ".hack/.gitignore"); + const change = { + layer: "3", + kind: "env", + scope: "global", + key: "NEW", + value: "added", + }; + const selection = ["--env", "default"]; + const validate = async () => + cli({ + root, + cwd: root, + args: ["validate", ...selection], + patch: { + base: bases(await show(root, root, ...selection)), + changes: [change], + }, + }); + expect((await validate()).payload.data.valid).toBe(true); + + const overlaySettings = { ...settings, defaultEnvConfig: "staging" }; + await Promise.all([ + writeFile(json, JSON.stringify(overlaySettings)), + writeFile(join(project, ".env"), "OPTIONAL=base\n"), + writeFile(join(project, ".env.staging"), "OPTIONAL=overlay\n"), + writeFile( + composeFile, + `${simpleCompose} env_file: [.env.staging, .env]\n` + ), + ]); + const order = await validate(); + expect(order.payload.data.issues[0]?.message).toContain( + "order of Compose env_file" + ); + + await writeFile(composeFile, simpleCompose); + await writeFile( + json, + JSON.stringify({ + ...overlaySettings, + custom: Array.from({ length: 100_000 }, () => 0), + }) + ); + const large = await validate(); + expect(large.payload.data.issues[0]?.message).toContain("512 KiB"); +}); + +async function legacyContractWorktree(baseValue: string) { + const f = await fixture(); + const project = join(f.linked, ".hack"); + f.git( + f.linked, + "rm", + "--", + ".hack/hack.env.default.yaml", + ".hack/hack.env.qa.yaml" + ); + await Promise.all([ + rm(join(project, "hack.env.local.yaml")), + writeFile(join(project, ".env"), `LOG_LEVEL=${baseValue}\n`), + writeFile( + join(project, "hack.env.json"), + '{"version":1,"vars":[{"key":"LOG_LEVEL","source":"plain_env"}]}\n' + ), + ]); + return { ...f, linkedProject: project }; +} + +test("a worktree's initial legacy unset journals only a needed ignore repair", async () => { + for (const alreadyIgnored of [false, true]) { + const f = await legacyContractWorktree(""); + const project = f.linkedProject; + const ignore = join(await realpath(project), ".gitignore"); + await rm(join(f.project, "hack.env.local.yaml")); + if (alreadyIgnored) { + await writeFile(ignore, "# tracked old ignore rules\n"); + f.git(f.linked, "add", ".hack/.gitignore"); + } else { + await writeFile(join(f.linked, ".gitignore"), ".hack/.internal/\n"); + } + const selection = ["--env", "default"]; + const before = await show(f.root, f.linked, ...selection); + expect(before.layers.some((layer) => layer.id === "4")).toBe(true); + const patch = { + base: bases(before), + changes: [ + { + layer: "5", + kind: "env", + scope: "global", + key: "LOG_LEVEL", + value: null, + }, + ], + }; + const validate = await cli({ + root: f.root, + cwd: f.linked, + args: ["validate", ...selection], + patch, + }); + expect(validate.payload.data.valid).toBe(true); + const outcome = await cli({ + root: f.root, + cwd: f.linked, + args: ["apply", ...selection], + patch, + }); + expect(outcome.payload.ok).toBe(true); + expect( + await readFile(join(project, "hack.env.local.yaml"), "utf8") + ).toContain("LOG_LEVEL: null"); + const hash = new Bun.CryptoHasher("sha256") + .update(await realpath(f.linked)) + .digest("hex"); + const journal = JSON.parse( + await readFile( + join( + privateCliHome(f.root), + ".hack/env-migrations", + hash, + "journal.json" + ), + "utf8" + ) + ); + expect( + journal.writes.some( + (file: { path: string; done: boolean }) => + file.path === ignore && file.done + ) + ).toBe(!alreadyIgnored); + if (alreadyIgnored) { + expect(await readFile(ignore, "utf8")).toBe( + "# tracked old ignore rules\n" + ); + } + } +}); + +test("disabling worktree inheritance and writing env migrates legacy values in the same save", async () => { + const f = await legacyContractWorktree("legacy-configured"); + const selection = ["--env", "default"]; + const before = await show(f.root, f.linked, ...selection); + expect(before.layers.some((layer) => layer.id === "4" && layer.exists)).toBe( + true + ); + const patch = { + base: bases(before), + changes: [ + { + layer: "1", + kind: "project", + path: "worktree.inherit_local", + value: false, + }, + { layer: "5", kind: "env", scope: "global", key: "NEW", value: "added" }, + ], + }; + const validation = await cli({ + root: f.root, + cwd: f.linked, + args: ["validate", ...selection], + patch, + }); + expect(validation.payload.data.valid).toBe(true); + const apply = await cli({ + root: f.root, + cwd: f.linked, + args: ["apply", ...selection], + patch, + }); + expect(apply.payload.ok).toBe(true); + const saved = await readFile( + join(f.linkedProject, "hack.env.local.yaml"), + "utf8" + ); + expect(saved).toContain("LOG_LEVEL: legacy-configured"); + expect(saved).toContain("NEW: added"); + expect( + (await show(f.root, f.linked, ...selection)).layers.some( + (layer) => layer.id === "4" + ) + ).toBe(false); +}); + +test("an identical replacement layer directory invalidates a revision", async () => { + const f = await fixture(); + const report = await show(f.root, f.main); + const projectPath = join(f.project, "hack.config.json"); + const original = await readFile(projectPath, "utf8"); + const old = join(f.main, ".old-hack"); + await rename(f.project, old); + await mkdir(f.project); + await Promise.all([ + writeFile(projectPath, original), + writeFile(join(f.project, "docker-compose.yml"), compose), + ]); + const result = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: { "1": bases(report)["1"] }, + changes: [{ layer: "1", kind: "project", path: "name", value: "wrong" }], + }, + }); + expect(result.payload.error.code).toBe("E_CONFLICT"); + expect(await readFile(projectPath, "utf8")).toBe(original); +}); + +test("show resolves legacy project defaults independently of the selected overlay", async () => { + const f = await fixture(); + const projectPath = join(f.project, "hack.config.json"); + for (const config of [ + { defaultEnvConfig: " QA " }, + { default_env_config: "qa" }, + { env: { default_overlay: "qa" }, defaultEnvConfig: "staging" }, + ]) { + await writeFile(projectPath, JSON.stringify(config)); + const preview = await show(f.root, f.main, "--env", "default"); + expect(preview.default_overlay).toBe("qa"); + expect(preview.overlay).toBeNull(); + expect(preview.project).toEqual(config); + } + const implicit = await show(f.root, f.main); + expect(implicit.overlay).toBe("qa"); + const saved = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(implicit), + changes: [ + { + layer: "1", + kind: "project", + path: "env.defaultOverlay", + value: "default", + }, + ], + }, + }); + expect(saved.payload.ok).toBe(true); + const base = await show(f.root, f.main); + expect(base.default_overlay).toBe("default"); + expect(base.overlay).toBeNull(); + expect(base.project.env).toEqual({ + defaultOverlay: "default", + default_overlay: "qa", + }); +}); + +test("show withholds a credential-bearing default overlay and its derived layer names", async () => { + const f = await fixture(); + const marker = "overlay-credential-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const derived = normalizeEnvConfigName(authored) ?? "invalid"; + const legacy = `https://fixture:${marker}-legacy@example.invalid`; + const legacySnake = `https://fixture:${marker}-snake@example.invalid`; + await writeFile( + join(f.project, "hack.config.json"), + JSON.stringify({ + env: { default_overlay: authored }, + defaultEnvConfig: legacy, + default_env_config: legacySnake, + }) + ); + for (const value of [authored, legacy, legacySnake]) { + const name = normalizeEnvConfigName(value) ?? "invalid"; + await writeFile( + join(f.project, `hack.env.${name}.yaml`), + env(" global:\n MODE: unsafe-default", name) + ); + } + const initial = await show(f.root, f.main); + for (const args of [[], ["--env", "default"], ["--env", derived]]) { + const report = await show(f.root, f.main, ...args); + expect(JSON.stringify(report).includes(marker)).toBe(false); + expect(report.default_overlay).toBe("[redacted]"); + expect(report.overlay).toBeNull(); + } + const saved = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch: { + base: bases(initial), + changes: [ + { + layer: "1", + kind: "project", + path: "env.defaultOverlay", + value: "default", + }, + ], + }, + }); + expect(saved.payload.ok).toBe(true); + const base = await show(f.root, f.main); + expect(base.default_overlay).toBe("default"); + expect(base.overlay).toBeNull(); + expect(JSON.stringify(base).includes(marker)).toBe(false); + + await writeFile( + join(f.project, "hack.config.json"), + JSON.stringify({ + env: { defaultOverlay: derived, default_overlay: authored }, + defaultEnvConfig: legacy, + default_env_config: legacySnake, + }) + ); + const collision = await show(f.root, f.main, "--env", "default"); + expect(collision.default_overlay).toBe("[redacted]"); + expect(JSON.stringify(collision).includes(marker)).toBe(false); +}); + +test("Config omits discovered and requested credential-shaped overlay names", async () => { + const f = await fixture(); + const shared = `glpat-${"fixtureshared".repeat(2)}`; + const local = `glpat-${"fixturelocal".repeat(2)}`; + const inherited = `glpat-${"fixtureinherited".repeat(2)}`; + const linkedProject = join(f.linked, ".hack"); + const overlays = [ + { project: f.project, name: shared, suffix: ".yaml" }, + { project: linkedProject, name: local, suffix: ".local.yaml" }, + { project: f.project, name: inherited, suffix: ".local.yaml" }, + ]; + const privateSource = " global:\n MODE: fixture-private-overlay-value"; + for (const { project, name, suffix } of overlays) { + await writeFile( + join(project, `hack.env.${name}${suffix}`), + env(privateSource, name) + ); + } + + for (const [cwd, requested] of [ + [f.main, undefined], + [f.main, shared], + [f.linked, undefined], + [f.linked, local], + [f.linked, inherited], + [f.linked, "qa"], + ] as const) { + const args = requested === undefined ? [] : ["--env", requested]; + const report = await show(f.root, cwd, ...args); + expect(report.overlay).toBe(requested === "qa" ? "qa" : null); + expect(report.overlays).toEqual(["qa"]); + expect(report.layers.some((layer) => layer.id === "3:qa")).toBe(true); + const output = JSON.stringify(report); + for (const marker of [ + shared, + local, + inherited, + "fixture-private-overlay-value", + ]) { + expect(output.includes(marker)).toBe(false); + } + } + for (const { project, name, suffix } of overlays) { + const path = join(project, `hack.env.${name}${suffix}`); + expect((await readFile(path, "utf8")) === env(privateSource, name)).toBe( + true + ); + } +}); + +test("Config patch diagnostics hide credential-shaped overlay layer IDs", async () => { + const f = await fixture(); + const name = `glpat-${"fixturelocal".repeat(2)}`; + const report = await show(f.root, f.main); + const base = bases(report); + const layer = `5:${name}`; + const change = { + layer, + kind: "env", + scope: "global", + key: "MODE", + value: "test", + }; + for (const patch of [ + { base, changes: [change] }, + { base: { ...base, [layer]: "0".repeat(64) }, changes: [] }, + ]) { + for (const command of ["validate", "apply"]) { + const result = await cli({ + ...f, + cwd: f.main, + args: [command, "--env", name], + patch, + }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail?.issues; + expect(JSON.stringify(result.payload).includes(name)).toBe(false); + expect(issues).toContainEqual( + expect.objectContaining({ layer: "[redacted]" }) + ); + } + } +}); + +test("replacing a private canonical default cannot expose a derived layer filename", async () => { + const f = await fixture(); + const marker = "canonical-private-overlay-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const path = join(f.project, `hack.env.${name}.local.yaml`); + const projectPath = join(f.project, "hack.config.json"); + const original = JSON.stringify({ env: { defaultOverlay: authored } }); + await writeFile(projectPath, original); + await writeFile(path, env(" global:\n MODE: unsafe-default", name)); + const report = await show(f.root, f.main); + const patch = { + base: bases(report), + changes: [ + { + layer: "1", + kind: "project", + path: "env.defaultOverlay", + value: "default", + }, + ], + }; + for (const command of ["validate", "apply"]) { + const result = await cli({ + root: f.root, + cwd: f.main, + args: [command], + patch, + }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail.issues; + expect(issues).toEqual([ + expect.objectContaining({ layer: "1", code: "E_CONFIG_INVALID" }), + ]); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + } + expect((await readFile(projectPath, "utf8")) === original).toBe(true); + await rm(path); + const saved = await cli({ + root: f.root, + cwd: f.main, + args: ["apply"], + patch, + }); + expect(saved.payload.ok).toBe(true); + const next = await show(f.root, f.main); + expect(next.default_overlay).toBe("default"); + expect(JSON.stringify(next).includes(marker)).toBe(false); + + await writeFile( + projectPath, + JSON.stringify({ + env: { defaultOverlay: authored }, + defaultEnvConfig: name, + }) + ); + patch.base = bases(await show(f.root, f.main)); + for (const command of ["validate", "apply"]) { + const result = await cli({ + root: f.root, + cwd: f.main, + args: [command], + patch, + }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail.issues; + expect(issues[0]?.message).toContain("remaining private overlay reference"); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + } +}); + +test("a linked checkout checks inherited private overlay filenames without listing them", async () => { + const f = await fixture(); + const marker = "inherited-private-overlay-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const projectPath = join(f.linked, ".hack/hack.config.json"); + const original = JSON.stringify({ + dev_host: "storefront.hack", + env: { defaultOverlay: authored }, + }); + await writeFile(projectPath, original); + await writeFile( + join(f.project, `hack.env.${name}.local.yaml`), + env(" global:\n MODE: inherited", name) + ); + const report = await show(f.root, f.linked); + expect(report.layers.some((layer) => layer.inherited)).toBe(true); + await chmod(f.project, 0o111); + try { + const result = await cli({ + root: f.root, + cwd: f.linked, + args: ["apply"], + patch: { + base: { "1": bases(report)["1"] }, + changes: [ + { + layer: "1", + kind: "project", + path: "env.defaultOverlay", + value: "default", + }, + ], + }, + }); + expect(result.payload.error?.code).toBe("E_CONFIG_INVALID"); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + expect((await readFile(projectPath, "utf8")) === original).toBe(true); + } finally { + await chmod(f.project, 0o755); + } +}); + +async function legacyOverlayFixture(config: Record) { + const root = await mkdtemp(join(tmpdir(), "hack-config-private-migration-")); + scratch.push(root); + const cwd = join(root, "legacy"); + const project = join(cwd, ".hack"); + await mkdir(project, { recursive: true }); + const projectPath = join(project, "hack.config.json"); + const original = JSON.stringify(config); + await Promise.all([ + writeFile(projectPath, original), + writeFile( + join(project, "docker-compose.yml"), + "services:\n api:\n image: alpine\n" + ), + writeFile( + join(project, "hack.env.json"), + '{"version":1,"vars":[{"key":"MODE","source":"plain_env"}]}\n' + ), + writeFile(join(project, ".env"), "MODE=base\n"), + ]); + return { root, cwd, project, projectPath, original }; +} + +const addEnvChoice = { + layer: "5", + kind: "env", + scope: "global", + key: "NEW", + value: "added", +}; +const selectBaseChoice = { + layer: "1", + kind: "project", + path: "env.defaultOverlay", + value: "default", +}; + +test("implicit migration receipts withhold private overlay names", async () => { + const marker = "private-overlay-migration-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ env: { defaultOverlay: authored } }); + await writeFile(join(f.project, `.env.${name}`), "MODE=private-layer\n"); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [addEnvChoice], + }; + const result = await cli({ ...f, args: ["apply"], patch }); + expect(result.payload.ok).toBe(true); + expect( + result.payload.data.changed.some((id: string) => id.endsWith(":[redacted]")) + ).toBe(true); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); +}); + +test("implicit migration receipts hide independently discovered credential-shaped overlay names", async () => { + const name = `glpat-${"fixturelegacy".repeat(2)}`; + const f = await legacyOverlayFixture({ name: "legacy" }); + await writeFile(join(f.project, `.env.${name}`), "MODE=private-layer\n"); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [addEnvChoice], + }; + const result = await cli({ ...f, args: ["apply"], patch }); + expect(result.payload.ok).toBe(true); + expect(result.payload.data.changed).toContain("3:[redacted]"); + expect(JSON.stringify(result.payload).includes(name)).toBe(false); + const report = await show(f.root, f.cwd); + expect(JSON.stringify(report).includes(name)).toBe(false); +}); + +test("a project-only save preserves redaction for a later legacy env migration", async () => { + const marker = "private-dotenv-filename-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ env: { defaultOverlay: authored } }); + await writeFile(join(f.project, `.env.${name}`), "MODE=private-layer\n"); + const base = bases(await show(f.root, f.cwd)); + const replacement = { base, changes: [selectBaseChoice] }; + for (const command of ["validate", "apply"]) { + const result = await cli({ ...f, args: [command], patch: replacement }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail.issues; + expect(issues[0]?.message).toContain("private filename"); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + } + expect((await readFile(f.projectPath, "utf8")) === f.original).toBe(true); + const later = await cli({ + ...f, + args: ["apply"], + patch: { base, changes: [addEnvChoice] }, + }); + expect(later.payload.ok).toBe(true); + expect(JSON.stringify(later.payload).includes(marker)).toBe(false); +}); + +test("a project-only save cannot expose an encrypted-store-only overlay", async () => { + const marker = "private-store-overlay-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ + name: "legacy", + env: { defaultOverlay: authored }, + controlPlane: { + secrets: { + backend: "encrypted_file", + encryptedFile: { path: "legacy-store.json", keyPath: "legacy.key" }, + }, + }, + }); + await writeFile( + join(f.project, "hack.env.json"), + '{"version":1,"vars":[{"key":"MODE","source":"plain_env"},{"key":"SECRET_TOKEN","source":"keychain"}]}\n' + ); + const storeModule = resolve(import.meta.dir, "../src/lib/secret-store.ts"); + const store = Bun.spawn([process.execPath, "--no-env-file", "-"], { + cwd: f.cwd, + env: privateCliEnv({ root: f.root }), + stdin: new Blob([ + "import { resolveSecretStore } from ", + JSON.stringify(storeModule), + ';\nconst store = await resolveSecretStore({ projectDir: ".hack", projectName: "legacy" });\n', + "await store.set(", + JSON.stringify({ + key: `env.${name}.SECRET_TOKEN`, + value: "fixture-ciphertext-marker", + }), + ");\n", + ]), + stdout: "ignore", + stderr: "ignore", + }); + expect(await store.exited).toBe(0); + const base = bases(await show(f.root, f.cwd)); + const patch = { base, changes: [selectBaseChoice] }; + const key = join(f.cwd, "legacy.key"); + const held = join(f.cwd, "held-legacy.key"); + await rename(key, held); + try { + for (const command of ["validate", "apply"]) { + const result = await cli({ ...f, args: [command], patch }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail.issues; + expect(issues[0]?.message).toContain("legacy secret store may contain"); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + } + expect(await Bun.file(key).exists()).toBe(false); + expect((await readFile(f.projectPath, "utf8")) === f.original).toBe(true); + } finally { + await rename(held, key); + } + const combined = await cli({ + ...f, + args: ["apply"], + patch: { base, changes: [selectBaseChoice, addEnvChoice] }, + }); + expect(combined.payload.error?.detail.issues[0]?.message).toContain( + "Resolve the conflicting project setting or legacy env input" + ); + expect(JSON.stringify(combined.payload).includes(marker)).toBe(false); + expect((await readFile(f.projectPath, "utf8")) === f.original).toBe(true); + expect(await Bun.file(join(f.project, "hack.env.local.yaml")).exists()).toBe( + false + ); + const migrated = await cli({ + ...f, + args: ["apply"], + patch: { base, changes: [addEnvChoice] }, + }); + expect(migrated.payload.ok).toBe(true); + expect(migrated.payload.data.changed).toContain("3:[redacted]"); + expect(JSON.stringify(migrated.payload).includes(marker)).toBe(false); + expect(JSON.stringify(await show(f.root, f.cwd)).includes(marker)).toBe( + false + ); +}); + +test("modern env layers allow correction of a private overlay despite an inaccessible legacy store", async () => { + const marker = "private-retired-store-fixture"; + const f = await legacyOverlayFixture({ + env: { defaultOverlay: `https://fixture:${marker}@example.invalid` }, + controlPlane: { + secrets: { + backend: "encrypted_file", + storePlaintextInBackend: true, + encryptedFile: { path: "retired-store/legacy.json" }, + }, + }, + }); + await Promise.all([ + writeFile(join(f.cwd, "retired-store"), ""), + writeFile( + join(f.project, "hack.env.default.yaml"), + env(" global:\n MODE: modern") + ), + ]); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [selectBaseChoice], + }; + const validation = await cli({ ...f, args: ["validate"], patch }); + expect(validation.payload.data.valid).toBe(true); + const saved = await cli({ ...f, args: ["apply"], patch }); + expect(saved.payload.ok).toBe(true); + const next = await show(f.root, f.cwd); + expect(next.default_overlay).toBe("default"); + expect(JSON.stringify(next).includes(marker)).toBe(false); +}); + +test("legacy migration errors redact private dotenv filenames", async () => { + const marker = "private-dotenv-error-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ env: { defaultOverlay: authored } }); + await symlink(".env", join(f.project, `.env.${name}`)); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [addEnvChoice], + }; + for (const command of ["validate", "apply"]) { + const result = await cli({ ...f, args: [command], patch }); + const issues = + result.payload.data?.issues ?? result.payload.error?.detail.issues; + expect(issues[0]?.message).toContain('".env.[redacted]" is a symlink'); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + } +}); + +test("env migration rechecks private filenames before replacing the project settings", async () => { + const marker = "private-dotenv-publication-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ + env: { defaultOverlay: authored }, + defaultEnvConfig: "qa", + }); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [addEnvChoice], + }; + const validation = await cli({ ...f, args: ["validate"], patch }); + expect(validation.payload.data.valid).toBe(true); + const pending = await withEnvLayerLock({ + layerPath: f.projectPath, + run: async () => { + const save = cli({ ...f, args: ["apply"], patch }); + await waitForFileContent({ + path: join(f.project, "hack.env.local.yaml"), + complete: (text) => (text.includes("MODE: base") ? true : undefined), + what: "migration local layer", + budgetMs: 7000, + }); + await writeFile(join(f.project, `.env.${name}`), "MODE=private-layer\n"); + return { save }; + }, + }); + const result = await pending.save; + expect(result.payload.error?.code).toBe("E_CONFLICT"); + expect(JSON.stringify(result.payload).includes(marker)).toBe(false); + expect((await readFile(f.projectPath, "utf8")) === f.original).toBe(true); +}); + +test("an overlong private overlay can be replaced when no legacy file exists", async () => { + const marker = "private-long-overlay-fixture"; + for (const length of [128, 280]) { + const authored = `https://fixture:${marker}-${"x".repeat(length)}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const f = await legacyOverlayFixture({ env: { defaultOverlay: authored } }); + const patch = { + base: bases(await show(f.root, f.cwd)), + changes: [selectBaseChoice], + }; + if (length === 128) { + const legacy = join(f.project, `.env.${name}`); + await writeFile(legacy, "MODE=private-layer\n"); + const blocked = await cli({ ...f, args: ["apply"], patch }); + expect(blocked.payload.error?.code).toBe("E_CONFIG_INVALID"); + expect(JSON.stringify(blocked.payload).includes(marker)).toBe(false); + await rm(legacy); + } + const saved = await cli({ ...f, args: ["apply"], patch }); + expect(saved.payload.ok).toBe(true); + const next = await show(f.root, f.cwd); + expect(next.default_overlay).toBe("default"); + expect(JSON.stringify(next).includes(marker)).toBe(false); + } +}); + +test("validation reads newly selected layers and honors an explicit selection", async () => { + const f = await fixture(); + const checkOverlay = async (value: string, args: string[] = []) => + await cli({ + root: f.root, + cwd: f.main, + args: ["validate", ...args], + patch: { + base: bases(await show(f.root, f.main, ...args)), + changes: [ + { layer: "1", kind: "project", path: "env.defaultOverlay", value }, + ], + }, + }); + await writeFile(join(f.project, "hack.env.qa.yaml"), "invalid: ["); + const qa = await checkOverlay("qa"); + expect(qa.payload.data.issues).toEqual( + expect.arrayContaining([ + expect.objectContaining({ layer: "3:qa", code: "E_CONFIG_PARSE" }), + ]) + ); + expect( + (await checkOverlay("qa", ["--env", "default"])).payload.data.valid + ).toBe(true); + expect((await checkOverlay("a".repeat(129))).payload.data.valid).toBe(false); + await writeFile( + join(f.project, "hack.config.json"), + '{"dev_host":"storefront.hack","env":{"defaultOverlay":"default"}}' + ); + const base = await show(f.root, f.main); + expect(base.overlay).toBeNull(); + expect( + base.layers.filter((layer) => layer.file.endsWith("hack.env.default.yaml")) + ).toHaveLength(1); + + await writeFile(join(f.linked, ".hack/hack.config.json"), "{}"); + const cfg = await show(f.root, f.linked); + const patch = { + base: bases(cfg), + changes: [ + { + layer: "1", + kind: "project", + path: "worktree.auto_branch", + value: false, + }, + ], + }; + const implicit = await cli({ + root: f.root, + cwd: f.linked, + args: ["validate"], + patch, + }); + expect(implicit.payload.data.valid).toBe(true); + const explicit = ["--branch", "feature-search"]; + const explicitCheck = await cli({ + root: f.root, + cwd: f.linked, + args: ["validate", ...explicit], + patch: { ...patch, base: bases(await show(f.root, f.linked, ...explicit)) }, + }); + expect(explicitCheck.payload.data.valid).toBe(false); +}); + +test("an include-only Compose root permits project and env edits", async () => { + const f = await fixture(); + const composeFile = join(f.project, "docker-compose.yml"); + const root = + "include:\n - path: [services.yml]\n project_directory: .\n env_file: [include.env]\n"; + await Promise.all([ + writeFile(composeFile, root), + writeFile(join(f.project, "include.env"), ""), + writeFile( + join(f.project, "services.yml"), + "services:\n api:\n image: alpine\n" + ), + ]); + const report = await show(f.root, f.main); + expect(report.state).toBe("ready"); + expect(report.services).toEqual([]); + const optional = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { + base: bases(report), + changes: [ + { + layer: "2", + kind: "source", + text: "include:\n - path: services.yml\n project_directory: null\n env_file: null\n", + }, + ], + }, + }); + expect(optional.payload.data.valid).toBe(true); + for (const field of ["project_directory: []", "env_file: 12"]) { + const invalid = await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { + base: bases(report), + changes: [ + { + layer: "2", + kind: "source", + text: `include:\n - path: services.yml\n ${field}\n`, + }, + ], + }, + }); + expect(invalid.payload.data.valid).toBe(false); + expect(invalid.payload.data.issues[0]?.code).toBe("E_CONFIG_PARSE"); + } + const patch = { + base: bases(report), + changes: [ + { layer: "1", kind: "project", path: "name", value: "renamed" }, + { + layer: "3", + kind: "env", + scope: "global", + key: "ADDED", + value: "shared", + }, + ], + }; + expect( + (await cli({ root: f.root, cwd: f.main, args: ["validate"], patch })) + .payload.data.valid + ).toBe(true); + expect( + (await cli({ root: f.root, cwd: f.main, args: ["apply"], patch })).payload + .ok + ).toBe(true); + expect(await readFile(composeFile, "utf8")).toBe(root); +}); + +test("Compose ports and labels match runtime interpretation and sequence edits keep comments", async () => { + const f = await fixture(); + const file = join(f.project, "docker-compose.yml"); + await writeFile( + file, + compose + .replace( + " depends_on: [api]", + " ports:\n - '127.0.0.1::80' # loopback target\n - '8081:81' # published target\n - 80 # http\n - 443 # https\n - '${PORT:-8080}:80'\n depends_on:\n - api # API dependency" + ) + .replace(" - unrelated=kept", " - caddy=last.storefront.hack") + ); + const report = await show(f.root, f.main); + const web = report.services.find((service) => service.name === "web"); + expect(web?.routes.map((route) => route.host)).toEqual([ + "last.storefront.hack", + ]); + expect(web?.route_edit).toBeNull(); + const check = async (changes: unknown[]) => + await cli({ + root: f.root, + cwd: f.main, + args: ["validate"], + patch: { base: bases(report), changes }, + }); + const valid = await check([ + { + layer: "2", + kind: "service", + service: "web", + field: "ports", + value: [ + "443", + "80", + "${PORT:-8080}:80", + "127.0.0.${OCTET:-1}:8080:80", + "127.0.0.1:${PORT_MAPPING:-8080:80}", + "127.0.0.1:${PUBLISHED_AND_COLON:-8080:}80", + "127.0.0.1:8080${SEPARATOR:-:}80${INSTANCE:-01}", + "127.0.0.1${PUBLISH:-:8080}:80", + "127.0.0.1${PORT_SUFFIX:-:8080:80}", + "127.0.0.1${PUBLISH:-:}8080${TARGET_SEPARATOR:-:}80", + "[::1]${PUBLISH:-:8080}:80", + "[::1${PUBLISH:-]:8080}:80", + "127${MIDDLE:-.0.}0.1:8080:80", + ":8080:80", + "[]:8080:80", + "[::${ADDR:-1}]:8080:80", + "[2001${SEP:-:}db8::1]:8080:80", + "::1:8080:80", + "127.0.0.1::80", + "8082:81", + ], + }, + { + layer: "2", + kind: "service", + service: "web", + field: "depends_on", + value: ["api", "worker"], + }, + ]); + expect(valid.payload.data.valid).toBe(true); + const interpolatedDependency = await check([ + { + layer: "2", + kind: "source", + text: 'services:\n web:\n depends_on:\n api: {condition: "service_${WHEN:-started}"}\n api: {}\n', + }, + ]); + expect(interpolatedDependency.payload.data.valid).toBe(true); + for (const comment of [ + "# loopback target", + "# published target", + "# API dependency", + "443 # https", + "80 # http", + ]) { + expect(valid.payload.data.previews["2"]).toContain(comment); + } + const invalidMappings = [ + "'8082-8081:81'", + "'127.0.0.999:8081:81'", + "{published: 8081}", + "'${PORT:-8080}:70000'", + "'127.0.0.1:${PUBLISHED_AND_COLON:-8080:}70000'", + "'127.0.0.1:8080${SEPARATOR:-:}70000${INSTANCE:-01}'", + "'127.0.0.1${PUBLISH:-:8080}:70000'", + "'${PORT'", + "'invalid-host.${OCTET:-1}:8080:80'", + "'[12345::${ADDR:-1}]:8080:80'", + "'[1:2:3:4:5:6:7:8:${TAIL:-9}]:8080:80'", + "'[fe80::1%${IFACE:-en0}]:8080:80'", + "'[fe80::1%en0]:8080:80'", + ]; + const invalid = await check([ + { + layer: "2", + kind: "source", + text: [ + "services:", + ...invalidMappings.map( + (mapping, index) => ` port-${index}:\n ports: [${mapping}]` + ), + " scalar:\n depends_on: web", + " missing:\n depends_on:\n web: {}", + " typo:\n depends_on:\n web: {condition: typo}", + " web: {}", + ].join("\n"), + }, + ]); + expect(invalid.payload.data.valid).toBe(false); + expect(invalid.payload.data.issues).toHaveLength(invalidMappings.length + 3); + const self = await check([ + { + layer: "2", + kind: "service", + service: "web", + field: "depends_on", + value: ["web"], + }, + ]); + expect(self.payload.data.valid).toBe(false); + const cycles = await check([ + { + layer: "2", + kind: "service", + service: "api", + field: "depends_on", + value: ["web"], + }, + ]); + expect(cycles.payload.data.issues[0]?.message).toContain("dependency cycle"); + const unequal = await check([ + { + layer: "2", + kind: "service", + service: "web", + field: "ports", + value: ["8000-8002:80-81"], + }, + ]); + expect(unequal.payload.data.valid).toBe(false); +}); + +test("an authored dev_host avoids opening a legacy dotenv input", async () => { + const f = await fixture(); + const legacy = join(f.project, ".env"); + await mkdir(legacy); + expect((await show(f.root, f.main)).state).toBe("ready"); + await writeFile(join(f.project, "hack.config.json"), "{}"); + const fallback = await cli({ root: f.root, cwd: f.main, args: ["show"] }); + expect(fallback.payload.error.code).toBe("E_PERMISSION"); +}); diff --git a/tests/env-migration-journal.test.ts b/tests/env-migration-journal.test.ts index c2ee71af9a..ddd329e6b1 100644 --- a/tests/env-migration-journal.test.ts +++ b/tests/env-migration-journal.test.ts @@ -14,20 +14,26 @@ import { import { tmpdir } from "node:os"; import { dirname, join, relative } from "node:path"; import { buildDoctorRemediationPlanLines } from "../src/commands/doctor.ts"; +import { withEnvLayerLock } from "../src/lib/env-layer-lock.ts"; import { applyEnvMigration, cleanupEnvMigration, type EnvMigrationProject, envMigrationJournalPath, migrateLegacyEnvForCommand, + prepareImplicitEnvMigration, previewEnvCleanup, previewEnvMigration, recordEnvMigrationProjectRun, rollbackEnvMigration, + withEnvMigrationConfigEdits, } from "../src/lib/env-migration.ts"; import { migrationDigest } from "../src/lib/env-migration-files.ts"; import { stageMigrationPayloads } from "../src/lib/env-migration-payloads.ts"; import { envMigrationSnapshots } from "../src/lib/env-migration-snapshot.ts"; +import { assertEnvMigrationReadable } from "../src/lib/env-migration-state.ts"; +import { AtomicWriteConflictError } from "../src/lib/fs.ts"; +import { normalizeEnvConfigName } from "../src/lib/project.ts"; import { LegacyEnvCleanupError, resolveProjectEnvConfig, @@ -713,6 +719,133 @@ test("later Compose repair accepts layer additions and tighter modes, invalidate expect(await Bun.file(join(project.projectDir, ".env")).exists()).toBe(false); }); +test("a prepared implicit migration reports committed bytes and keeps an interrupted publication recoverable", async () => { + const plan = await prepareImplicitEnvMigration(project); + const receipts: { path: string; sha256: string | null }[] = []; + const snapshots = fixtureEnvSnapshots(root); + await expect( + applyEnvMigration({ + project: plan.project, + plan, + snapshots, + acceptTrackedChanges: false, + repairCompose: false, + onPublished: (file) => { + if (file.path.endsWith(".yaml")) { + receipts.push(file); + } + }, + hooks: { + boundary: async ({ phase }) => { + if (phase === "published" && receipts.length > 0) { + throw new Error( + "synthetic interruption before recording the write" + ); + } + }, + }, + }) + ).rejects.toThrow("synthetic interruption"); + const committed = receipts[0]; + if (!committed) { + throw new Error("Expected one committed env layer."); + } + expect(committed.sha256).toBe( + migrationDigest(await readFile(committed.path)) + ); + await expect(assertEnvMigrationReadable(project)).rejects.toThrow( + "unfinished" + ); + await expect(prepareImplicitEnvMigration(project)).rejects.toBeInstanceOf( + AtomicWriteConflictError + ); + const resumed = await applyEnvMigration({ + project, + snapshots, + acceptTrackedChanges: false, + repairCompose: false, + }); + expect(resumed.status).toBe("applied"); + await expect(assertEnvMigrationReadable(project)).resolves.toBeUndefined(); +}); + +test("cleanup and rollback recover an interrupted Config save and remove its new env layer", async () => { + const snapshots = envMigrationSnapshots(); + const path = join(project.projectDir, "hack.config.json"); + const overlay = join(project.projectDir, "hack.env.new.local.yaml"); + const ignore = join(project.projectDir, ".gitignore"); + await writeFile(join(project.projectDir, ".env"), ""); + await writeFile(join(project.projectDir, ".env.qa"), ""); + const before = await readFile(path, "utf8"); + const plan = await prepareImplicitEnvMigration(project, { + edits: [ + { path, text: before }, + { path: overlay, text: null }, + ], + writesLocalEnv: true, + }); + expect(plan.prepared.files.some(({ kind }) => kind === "local_layer")).toBe( + false + ); + expect(plan.prepared.files.some(({ path }) => path === ignore)).toBe(true); + const migration = await applyEnvMigration({ + project, + snapshots, + acceptTrackedChanges: false, + repairCompose: false, + plan, + }); + if (!migration.manifestPath) { + throw new Error("Expected a migration snapshot"); + } + const after = '{"name":"renamed"}\n'; + const overlayText = "version: 1\nenvironment: new\nvalues: {}\n"; + await expect( + withEnvMigrationConfigEdits({ + project, + manifestPath: migration.manifestPath, + run: async ({ prepare, commit }) => { + await prepare({ + path: overlay, + before: null, + after: overlayText, + mode: 0o600, + }); + await writeFile(overlay, overlayText, { mode: 0o600 }); + await commit(overlay); + await prepare({ + path, + before, + after, + mode: (await lstat(path)).mode & 0o777, + }); + await writeFile(path, after); + throw new Error("interrupted after rename"); + }, + }) + ).rejects.toThrow("interrupted after rename"); + const renamed = { ...project, projectName: "renamed" }; + await recordEnvMigrationProjectRun(renamed); + const cleanup = { project: renamed, snapshots, acceptTrackedChanges: false }; + await writeFile(overlay, `${overlayText}# edited after start\n`); + await expect(cleanupEnvMigration(cleanup)).rejects.toThrow( + "Env layers changed" + ); + await writeFile(overlay, overlayText); + await writeFile(path, '{"name":"edited-later"}\n'); + await expect(cleanupEnvMigration(cleanup)).rejects.toThrow("input changed"); + await writeFile(path, after); + expect((await cleanupEnvMigration(cleanup)).status).toBe("cleaned"); + await rollbackEnvMigration({ + project: renamed, + snapshots, + manifestPath: migration.manifestPath, + }); + expect(await readFile(path, "utf8")).toBe(before); + expect(await Bun.file(overlay).exists()).toBe(false); + expect(await Bun.file(ignore).exists()).toBe(false); +}, 30_000); + test("later Compose repair refuses damaged originals before changing the completed journal", async () => { const composePath = join(project.projectDir, "docker-compose.yml"); await writeFile( @@ -912,6 +1045,96 @@ test("rollback restores original bytes and refuses a later user edit", async () expectRestored(await projectFiles(), before); }); +test("resumed migration checks private overlay filenames under the project lock", async () => { + const marker = "recovery-private-overlay-fixture"; + const authored = `https://fixture:${marker}@example.invalid`; + const name = normalizeEnvConfigName(authored) ?? "invalid"; + const path = join(project.projectDir, "hack.config.json"); + const original = JSON.stringify({ + name: "journal", + env: { defaultOverlay: authored }, + defaultEnvConfig: "qa", + }); + await writeFile(path, original); + const plan = await prepareImplicitEnvMigration(project); + const projectIndex = plan.prepared.files.findIndex( + (file) => file.path === path + ); + expect(projectIndex).toBeGreaterThanOrEqual(0); + const options = { + project, + snapshots: fixtureEnvSnapshots(root), + acceptTrackedChanges: false, + repairCompose: false, + }; + const expectRefusalBeforePublication = async () => { + const before = await projectFiles(); + await expect(apply(options)).rejects.toThrow( + "Migration would expose a private overlay name" + ); + expect(await projectFiles()).toEqual(before); + expect( + await Bun.file(envMigrationJournalPath(project.projectRoot)).exists() + ).toBe(false); + }; + await writeFile( + path, + JSON.stringify({ + name: "journal", + env: { defaultOverlay: authored }, + defaultEnvConfig: name, + }) + ); + await expectRefusalBeforePublication(); + await writeFile(path, original); + const legacy = join(project.projectDir, `.env.${name}`); + await writeFile(legacy, "TOKEN=present\n"); + await expectRefusalBeforePublication(); + await rm(legacy); + await expect( + apply({ + ...options, + plan, + hooks: { + boundary: async ({ phase, index }) => { + if (phase === "before_publish" && index === projectIndex) { + throw new Error( + "synthetic interruption before project publication" + ); + } + }, + }, + }) + ).rejects.toThrow("synthetic interruption"); + + const result = await withEnvLayerLock({ + layerPath: path, + run: async () => { + const { promise: reachedWrite, resolve: release } = + Promise.withResolvers(); + const resume = apply({ + ...options, + hooks: { + boundary: async ({ phase, index }) => { + if (phase === "before_publish" && index === projectIndex) { + release(); + } + }, + }, + }); + await Promise.race([reachedWrite, resume]); + await writeFile(legacy, "TOKEN=late\n"); + return { resume }; + }, + }); + await expect(result.resume).rejects.toBeInstanceOf(AtomicWriteConflictError); + expect((await readFile(path, "utf8")) === original).toBe(true); + await rm(legacy); + const migrated = await apply(options); + expect(migrated.status).toBe("applied"); + expect((await readFile(path, "utf8")).includes(marker)).toBe(false); +}); + test("a partial publication refuses implicit commands before they can use incomplete layers", async () => { await expect( apply({ diff --git a/tests/machine-output-success-shapes.test.ts b/tests/machine-output-success-shapes.test.ts index 0fd92599f7..fc434adbd9 100644 --- a/tests/machine-output-success-shapes.test.ts +++ b/tests/machine-output-success-shapes.test.ts @@ -29,6 +29,7 @@ type Case = { const CASES: readonly Case[] = [ { command: "version" }, + { command: "config show" }, { command: "activity" }, { command: "projects", flags: ["--observe"] }, { command: "global status", flags: ["--observe"] }, diff --git a/tests/missing-project-error-code.test.ts b/tests/missing-project-error-code.test.ts index d02080b522..21bae4c2e7 100644 --- a/tests/missing-project-error-code.test.ts +++ b/tests/missing-project-error-code.test.ts @@ -40,6 +40,14 @@ type Expectation = | { readonly kind: "line"; readonly argv: Argv } /** The target-inspect E_PROJECT_NOT_FOUND envelope, which adds a detail. */ | { readonly kind: "target-envelope"; readonly argv: Argv } + /** A command with its own JSON result for a missing project. */ + | { + readonly kind: "json-result"; + readonly argv: Argv; + readonly code: 0 | 1; + readonly result: unknown; + readonly stdin?: string; + } /** A documented exception: exact stdout and stderr. */ | { readonly kind: "exception"; @@ -143,6 +151,46 @@ const COMMANDS: Readonly> = { kind: "line", argv: ["config", "set", "name", "x", "-p", "DIR"], }, + "config show": { + kind: "json-result", + argv: ["config", "show", "-p", "DIR", "--json"], + code: 0, + result: { + ok: true, + data: { + schema: "hack.config.v1", + state: "missing", + project: {}, + services: [], + env: [], + issues: [], + layers: [], + branch: null, + overlay: null, + default_overlay: null, + overlays: [], + checkout: null, + writable: false, + }, + }, + }, + "config apply": { + kind: "json-result", + argv: ["config", "apply", "-p", "DIR", "--json"], + code: 1, + stdin: JSON.stringify({ + base: { "1": "0".repeat(64) }, + changes: [{ layer: "1", kind: "project", path: "name", value: "x" }], + }), + result: { + ok: false, + error: { + code: "E_CONFLICT", + message: + "The selected checkout is no longer available. Reload before saving.", + }, + }, + }, "env list": { kind: "envelope", argv: ["env", "list", "-p", "DIR", "--json"], @@ -327,6 +375,7 @@ async function emptyProject() { async function cli(opts: { readonly root: string; readonly args: readonly string[]; + readonly stdin?: string; /** Working directory; defaults to the fixture root. */ readonly cwd?: string; }) { @@ -338,7 +387,7 @@ async function cli(opts: { root: opts.root, env: { HACK_NO_INTERACTIVE: "1", HACK_LOGGER: "console" }, }), - stdin: "ignore", + stdin: opts.stdin === undefined ? "ignore" : new Blob([opts.stdin]), stdout: "pipe", stderr: "pipe", timeout: 20_000, @@ -367,10 +416,18 @@ for (const [name, expectation] of Object.entries(COMMANDS)) { const result = await cli({ root, args: expectation.argv.map((token) => (token === "DIR" ? dir : token)), + stdin: + expectation.kind === "json-result" ? expectation.stdin : undefined, }); - expect(result.code).toBe(1); + expect(result.code).toBe( + expectation.kind === "json-result" ? expectation.code : 1 + ); expect(result.stderr).not.toMatch(STACK_FRAME); switch (expectation.kind) { + case "json-result": + expect(JSON.parse(result.stdout)).toEqual(expectation.result); + expect(result.stderr).toBe(""); + break; case "target-envelope": expect(JSON.parse(result.stdout)).toMatchObject({ ok: false,