From a928bcaf4d84a8a259a3d42061b1e13a4ef1809a Mon Sep 17 00:00:00 2001 From: mtoohey Date: Wed, 18 Nov 2026 23:07:08 +0000 Subject: [PATCH 1/4] feat(staged): move and copy notes between projects from stagedctl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An agent driving Staged through stagedctl could read a note but not send it to another project. Only the note dialogs' "Move to project…" and "Copy to project…" could. Add a `note` noun with `move` and `copy` verbs that run the same transfer: stagedctl note move '#note:' --to stagedctl note copy '#project-note:' --to is the hashtag reference the CLI prints: `#note:` for a branch note, `#project-note:` for a project note. The leading # may be left off, because an unquoted # starts a shell comment. --to resolves like every other , by name or id. The noun has the hidden plural alias `notes` and takes the global --json, like its neighbours. The output says where the note landed: the destination project, the repo and branch a branch note is on now, and for a copy the new note's reference. Each repo the transfer added to the destination is named. --json carries the same as `{ ok, mode, projectId, reference, note, addedRepos }`, plus `branch` and `repo` for a branch note, built from the app's rows. One code path. The four commands the dialogs already call (`move_note_to_project`, `copy_note_to_project` and their project-note twins) join the control server's allowlist, and their dispatch arms call `transfer_branch_note` and `transfer_project_note` as before. The transfer's rules are untouched, and its refusals reach the CLI verbatim as `app_error` (exit 1). A Staged from before this change answers with the "update Staged" hint the other late commands get. Authorization. All four are writes with a new scope rule: the project the note is in, found through the note, and the destination must both be within the credential's reach, by the reach test every other write uses. A read-only grant is refused, as is a note or a destination outside that reach (exit 4, `scope_denied`). What a session's credential reaches is unchanged: its own project and the projects it created. The one refactor is in what a control caller is answered, not in the transfer. A window has the note open and is answered with the note alone, as before. A control caller named a note by id, so its answer is `{ note, branch, repo, addedRepos }` for a branch note and `{ note, addedRepos }` for a project note. Which repos were added is known only while the transfer runs, so the arms wrap the existing repo-adding step in `note_transfer::control::AddedRepos`, which notes each repo once its add has succeeded. The transfer functions, the Tauri commands and the web answer are as they were. `note move --help` and `note copy --help` say what a move carries (the note's id, its session, a project note's child notes) and what a copy produces (a new standalone note), with the refusals and the repo a destination can gain. The help pins and the session guide are updated. Tests: reference parsing, the request for each kind and verb, the output, pass-through of refusals and scope denials in the CLI; the scope rule for a note out of reach, a destination out of reach, a read-only grant and an unconfined one; the control answer over real transfers; and a pin that every caller's arm runs the one transfer. Co-Authored-By: Claude Fable 5.2 Signed-off-by: mtoohey --- .../src-tauri/crates/stagedctl/src/cli.rs | 202 +++++ .../src-tauri/crates/stagedctl/src/client.rs | 54 ++ .../crates/stagedctl/src/commands.rs | 29 +- .../src-tauri/crates/stagedctl/src/lib.rs | 3 + .../src-tauri/crates/stagedctl/src/notes.rs | 334 ++++++++ .../crates/stagedctl/src/notes/tests.rs | 747 ++++++++++++++++++ .../crates/stagedctl/tests/fixtures/help.txt | 162 ++++ .../src-tauri/resources/stagedctl/guide.md | 33 + apps/staged/src-tauri/src/control_server.rs | 33 +- apps/staged/src-tauri/src/note_transfer.rs | 2 + .../src-tauri/src/note_transfer/control.rs | 112 +++ .../src/note_transfer/control/tests.rs | 247 ++++++ apps/staged/src-tauri/src/web_server.rs | 139 +++- .../src-tauri/src/web_server/control_scope.rs | 371 ++++++++- 14 files changed, 2439 insertions(+), 29 deletions(-) create mode 100644 apps/staged/src-tauri/crates/stagedctl/src/notes.rs create mode 100644 apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs create mode 100644 apps/staged/src-tauri/src/note_transfer/control.rs create mode 100644 apps/staged/src-tauri/src/note_transfer/control/tests.rs diff --git a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs index 5c56c6be8..a2460ed39 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs @@ -31,6 +31,9 @@ Addressing: a tag id, /, or a bare tag name when only one tag has it, as printed by `stagedctl tag list` a tag group name or id, as printed by `stagedctl tag list` + a note's hashtag reference, #note: or #project-note:, + as printed by `stagedctl timeline show`; quote it, or leave + the # off (an unquoted # starts a shell comment) Ids print in hashtag reference form (#note:, #project-note:, #review:, #commit:) so they can be pasted directly into session @@ -88,6 +91,10 @@ pub enum Noun { #[command(alias = "images", subcommand)] Image(ImageVerb), + /// Move and copy notes between projects + #[command(alias = "notes", subcommand)] + Note(NoteVerb), + /// Read and edit the tag catalog: tag groups, tags, and which projects /// carry them #[command(alias = "tags", subcommand)] @@ -1012,6 +1019,133 @@ The file is read from this machine's filesystem: it must exist, be at most }, } +#[derive(Subcommand, Debug)] +pub enum NoteVerb { + /// Move a note, with its session, to another project + #[command(long_about = "\ +Move a note to another project. is a hashtag reference as +`stagedctl timeline show` prints it: #note: for a branch note, +#project-note: for a project note. Quote it, or leave the # off: an +unquoted # starts a shell comment. --to is the destination, a project +name or id (see `stagedctl project list`). + +This is \"Move to project\" in the note's menu in the app. The note keeps +its id, so its reference still resolves, and what comes with it depends +on its kind: + + branch note lands on the destination's branch for the repo and + subpath the note's branch tracks (the oldest such + branch, when the destination has several). Its session + comes with it, so the transcript stays with the note, + and so do the images and videos in its body. Its link + to the project note it was written under is dropped, + and moving it back does not restore that link. A title + another note on the landing branch has gets a number: + \" (2)\". + project note lands in the destination project with its session and + media, and takes its child notes along. Each child + lands, with its own session, on the destination's + branch for its repo and subpath, still linked to the + project note. + +Commits and code reviews are not part of a note. They stay on the branch +they were made on. + +A destination that does not track a repo the move needs gets it first, +the way `stagedctl project add-repo` adds one without --branch: a new +branch named after the project, set up in the background (a worktree, +or a clone into a remote project's workspace). The output names each +repo added this way. Such a repo stays in the project when a later step +of the move fails. A project note's error names it; a branch note's +does not, so look at `stagedctl project get`. + +The app refuses a move, with the note left where it was (exit 1, +`app_error`, the app's own message), when: + - the note is already in the destination project; + - the note is still being written, or its session or a child note's + is queued or running. Wait for it with `stagedctl session wait`; + - the note's branch, or a child note's, tracks no repo; + - a project note has child notes and either project runs on a remote + workspace, or a child note is on a remote branch or on a branch + outside the project note's own project. + +Needs write access to both projects, the one the note is in and the +destination. A read-only credential is refused (exit 4, `scope_denied`), +and so is a note in a project the credential does not reach. A +destination it does not reach is not among its projects and exits 1 +(`not_found`). A session may move notes between its own project and the +projects it created, in either direction, and nowhere else. + +A move shows at once in both projects. The user can move the note back +in the app, and `stagedctl note move` can too. stagedctl has no delete, +and cannot remove a repo a move added.")] + Move { + /// The note: '#note:<id>' or '#project-note:<id>' (see `stagedctl + /// timeline show`) + #[arg(value_name = "NOTE")] + note: String, + + /// The destination project, by name or id (see `stagedctl project + /// list`) + #[arg(long, value_name = "PROJECT")] + to: String, + }, + + /// Copy a note into a project as a new standalone note + #[command(long_about = "\ +Copy a note into a project. <NOTE> and --to are as in `stagedctl note +move`: a hashtag reference (#note:<id> or #project-note:<id>, quoted or +without the #) and a project name or id. + +This is \"Copy to project\" in the note's menu in the app. The original +is left exactly as it is. The copy is a new note with its own id, which +this command prints as a hashtag reference. It holds the original's +title and body as they read now, with its own copies of the images and +videos in the body, and nothing else: + + - no session. The transcript stays with the original, and the copy is + editable in the app like a note the user wrote; + - no link to a parent project note and no child notes. Copying a + project note copies that one note; + - no suggested next steps. + +A copy of a branch note lands on the destination's branch for the repo +and subpath the note's branch tracks. A destination that does not track +that repo gets it first, as in `stagedctl note move`, and the output +names it. A title another note on the landing branch has gets a number: +\"<title> (2)\". A copy of a project note lands in the destination +project and never adds a repo. + +--to may be the project the note is already in. That duplicates the +note beside the original, on the same branch for a branch note. + +The app refuses a copy (exit 1, `app_error`, the app's own message) +when the note has never finished being written, or when a branch +note's branch tracks no repo. A finished note whose session was resumed +and is running again can be copied, where it could not be moved: the +copy is the note as it reads now. + +Needs write access to both projects, the one the note is in and the +destination, as `stagedctl note move` does: exit 4 (`scope_denied`) +under a read-only credential or for a note in a project the credential +does not reach, exit 1 (`not_found`) for a destination it does not +reach. + +A copy shows at once in the destination, where the user can delete it. +stagedctl has no delete.")] + Copy { + /// The note: '#note:<id>' or '#project-note:<id>' (see `stagedctl + /// timeline show`) + #[arg(value_name = "NOTE")] + note: String, + + /// The destination project, by name or id (see `stagedctl project + /// list`) + #[arg(long, value_name = "PROJECT")] + to: String, + }, +} + /// What a repo-scoped session produces. Mirrors the app's /// `BranchSessionType` wire values. #[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] @@ -1077,9 +1211,11 @@ mod tests { ("timelines", "show"), ("sessions", "list"), ("images", "add"), + ("notes", "move"), ("tags", "list"), ] { let args: Vec<&str> = match (plural, singular) { + ("notes", _) => vec!["stagedctl", plural, "move", "#note:n1", "--to", "proj"], ("images", _) => vec![ "stagedctl", plural, @@ -1186,6 +1322,72 @@ mod tests { assert!(matches!(cli.command, Noun::Disconnect { client: Some(c) } if c == "x")); } + #[test] + fn note_verbs_take_a_note_and_a_destination() { + for noun in ["note", "notes"] { + let cli = + Cli::try_parse_from(["stagedctl", noun, "move", "#note:n1", "--to", "My Project"]) + .unwrap(); + assert!( + matches!(cli.command, Noun::Note(NoteVerb::Move { note, to }) if note == "#note:n1" && to == "My Project") + ); + // The reference is one argument however it is spelled, and + // --json stays global. + let cli = Cli::try_parse_from([ + "stagedctl", + noun, + "copy", + "--to", + "p2", + "project-note:pn1", + "--json", + ]) + .unwrap(); + assert!(cli.json); + assert!( + matches!(cli.command, Noun::Note(NoteVerb::Copy { note, to }) if note == "project-note:pn1" && to == "p2") + ); + } + // Both are required: a move with nowhere to go, or nothing to move, + // is a usage error. The second is what an unquoted #note:... leaves + // behind once the shell has dropped it as a comment. + for args in [ + vec!["stagedctl", "note", "move", "#note:n1"], + vec!["stagedctl", "note", "move", "--to", "p2"], + vec!["stagedctl", "note", "copy", "#note:n1"], + vec!["stagedctl", "note", "copy", "--to", "p2"], + vec![ + "stagedctl", + "note", + "move", + "#note:n1", + "#note:n2", + "--to", + "p2", + ], + // The destination is a flag, not a second positional. + vec!["stagedctl", "note", "move", "#note:n1", "p2"], + ] { + assert!(Cli::try_parse_from(&args).is_err(), "{args:?}"); + } + // A bare `note` has no default verb. + assert!(Cli::try_parse_from(["stagedctl", "note"]).is_err()); + } + + #[test] + fn help_rendering_reaches_the_note_verbs() { + let help = render_all_help(); + for section in [ + "=== stagedctl note --help ===", + "=== stagedctl note move --help ===", + "=== stagedctl note copy --help ===", + ] { + assert!(help.contains(section), "help lacks {section}"); + } + // The root teaches how a note is named, beside the other addresses. + assert!(help.contains(" <note> a note's hashtag reference")); + } + #[test] fn project_open_takes_at_most_one_project() { for noun in ["project", "projects"] { diff --git a/apps/staged/src-tauri/crates/stagedctl/src/client.rs b/apps/staged/src-tauri/crates/stagedctl/src/client.rs index 1e94da40a..f6d56e4ef 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/client.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/client.rs @@ -1107,6 +1107,8 @@ fn older_app_hint(command: &str) -> Option<&'static str> { Some("this Staged cannot create projects or add repos through stagedctl yet; update it") } else if command == crate::open::OPEN_PROJECT_COMMAND { Some("this Staged cannot open a project from the command line yet; update it") + } else if crate::notes::is_note_transfer_command(command) { + Some("this Staged cannot move or copy notes through stagedctl yet; update it") } else { None } @@ -1261,6 +1263,58 @@ pub(crate) mod tests { assert_eq!(err.to_string(), "app_error: Project not found: p1"); } + #[test] + fn a_404_on_a_note_transfer_hints_at_updating_staged() { + // The four transfer commands reached the control server without a + // protocol bump, so an older Staged answers them as it answers any + // unknown command. + for command in crate::notes::NOTE_TRANSFER_COMMANDS { + let err = classify( + command, + 404, + serde_json::json!({ + "error": format!("command not available through stagedctl: {command}") + }), + ) + .unwrap_err(); + assert_eq!(err.exit_code(), 1); + assert_eq!( + err.to_string(), + format!( + "app_error: command not available through stagedctl: {command} (this \ + Staged cannot move or copy notes through stagedctl yet; update it)" + ) + ); + } + // A current app's refusal of a transfer is passed through as it is. + let err = classify( + "move_note_to_project", + 400, + serde_json::json!({"error": "\"Findings\" is already in Target."}), + ) + .unwrap_err(); + assert_eq!(err.exit_code(), 1); + assert_eq!( + err.to_string(), + "app_error: \"Findings\" is already in Target." + ); + // A scope refusal keeps its own code and exit 4. + let err = classify( + "move_note_to_project", + 403, + serde_json::json!({ + "code": "scope_denied", + "error": "the destination is a project outside this credential's reach", + }), + ) + .unwrap_err(); + assert_eq!(err.exit_code(), 4); + assert_eq!( + err.to_string(), + "scope_denied: the destination is a project outside this credential's reach" + ); + } + #[test] fn a_404_on_a_project_write_hints_at_updating_staged() { // `create_project` and `add_project_repo` reached the control server diff --git a/apps/staged/src-tauri/crates/stagedctl/src/commands.rs b/apps/staged/src-tauri/crates/stagedctl/src/commands.rs index 9d6247565..546d1737a 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/commands.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/commands.rs @@ -13,7 +13,7 @@ use serde::Deserialize; use serde_json::{json, Value}; use crate::cli::{ - Cli, ImageVerb, Noun, ProjectVerb, SessionType, SessionVerb, TagGroupVerb, TagVerb, + Cli, ImageVerb, NoteVerb, Noun, ProjectVerb, SessionType, SessionVerb, TagGroupVerb, TagVerb, TimelineVerb, }; use crate::client::{ @@ -22,6 +22,7 @@ use crate::client::{ }; use crate::grants::{self, GrantFile}; use crate::launch; +use crate::notes; use crate::open; use crate::projects; use crate::tags; @@ -245,6 +246,18 @@ pub fn run(cli: Cli) -> Result<CmdOutput, CtlError> { branch, file, }) => image_add(&client, &project, &repo, branch.as_deref(), &file), + Noun::Note(NoteVerb::Move { note, to }) => notes::note_transfer( + &client, + notes::Transfer::Move, + ¬es::NoteRef::parse(¬e)?, + &to, + ), + Noun::Note(NoteVerb::Copy { note, to }) => notes::note_transfer( + &client, + notes::Transfer::Copy, + ¬es::NoteRef::parse(¬e)?, + &to, + ), Noun::Project(ProjectVerb::Open { .. }) | Noun::Connect { .. } | Noun::Disconnect { .. } => { @@ -362,6 +375,9 @@ fn validate(command: &Noun) -> Result<(), CtlError> { Noun::Tag(TagVerb::Group(TagGroupVerb::SetSidebar { on, off, .. })) if !on && !off => { invalid("pass --on to pin the group's board to the sidebar, or --off to unpin it") } + Noun::Note(NoteVerb::Move { note, .. } | NoteVerb::Copy { note, .. }) => { + notes::NoteRef::parse(note).map(|_| ()) + } Noun::Connect { client, .. } if client.trim().is_empty() => { invalid("--client must not be empty") } @@ -2446,6 +2462,15 @@ mod tests { &["stagedctl", "project", "add-repo", "p", "--repo", "widgets"], "--repo must look like <owner>/<repo>[:<subpath>]", ), + // A <NOTE> that is not a note reference needs no app to refuse. + ( + &["stagedctl", "note", "move", "n1", "--to", "p"], + "<NOTE> must be '#note:<id>' or '#project-note:<id>'", + ), + ( + &["stagedctl", "note", "copy", "#review:r1", "--to", "p"], + "only notes move between projects", + ), ]; for (args, expected) in cases { let err = validate(&parse_cli(args)).unwrap_err(); @@ -2581,6 +2606,8 @@ mod tests { &["stagedctl", "project", "tag", "p", "q4", "--create"], &["stagedctl", "project", "untag", "p", "q4", "Status/Done"], &["stagedctl", "project", "untag", "p", "--group", "Status"], + &["stagedctl", "note", "move", "#note:n1", "--to", "p"], + &["stagedctl", "note", "copy", "project-note:pn1", "--to", "p"], ]; for args in good { assert!(validate(&parse_cli(args)).is_ok(), "{args:?}"); diff --git a/apps/staged/src-tauri/crates/stagedctl/src/lib.rs b/apps/staged/src-tauri/crates/stagedctl/src/lib.rs index 67a1d22bd..0064e93c5 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/lib.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/lib.rs @@ -6,6 +6,8 @@ //! - [`commands`]: verb implementations and output rendering //! - [`launch`]: starts Staged for `project open` when no instance is //! running: the decision, the bundle path, the wait, and the one spawn +//! - [`notes`]: the `note move` and `note copy` writes: the `<NOTE>` +//! reference, the request, and the rendering of where the note landed //! - [`open`]: `project open`: finds the project, by name, id or the current //! directory, asks a window to show it and words what the window did //! - [`projects`]: the `project create` and `project add-repo` writes: @@ -23,6 +25,7 @@ pub mod client; pub mod commands; pub mod grants; pub mod launch; +pub mod notes; pub mod open; pub mod projects; pub mod tags; diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs new file mode 100644 index 000000000..4169317f6 --- /dev/null +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs @@ -0,0 +1,334 @@ +//! The `note move` and `note copy` writes: how a `<NOTE>` is read, the +//! request each sends, and the rendering of where the note landed. +//! +//! Like [`crate::commands`], this is a flag→JSON mapper. The transfer is the +//! app's (`note_transfer` in the app), the one its "Move to project" and +//! "Copy to project" menus run: what a move carries, what a copy leaves +//! behind, which repo the destination gains, and every refusal are decided +//! there and pass through verbatim. Two things are decided here: which of +//! the app's two kinds of note a reference names, and which project `--to` +//! names, answered from a read the caller can make anyway. +//! +//! Each verb is one write with no read after it. The app's answer carries +//! the branch the note landed on and the repos the transfer added, which +//! only the transfer knows. An answer that cannot be read is a +//! [`CtlError::Partial`], so the caller still learns the write landed. + +use serde::Deserialize; +use serde_json::{json, Map, Value}; + +use crate::client::{Client, CtlError}; +use crate::commands::{find_project, parse, repo_address, BranchRow, CmdOutput, Project}; + +/// The dispatch commands behind the two verbs. A Staged from before they +/// reached the control server refuses them as not allowlisted (404), which +/// on the wire is the answer to any unknown command, so the transport +/// appends an "update Staged" hint to exactly these. +pub const NOTE_TRANSFER_COMMANDS: &[&str] = &[ + "move_note_to_project", + "copy_note_to_project", + "move_project_note_to_project", + "copy_project_note_to_project", +]; + +pub fn is_note_transfer_command(command: &str) -> bool { + NOTE_TRANSFER_COMMANDS.contains(&command) +} + +/// Which of the two verbs is running. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Transfer { + Move, + Copy, +} + +impl Transfer { + /// The value of `mode` under `--json`, which is the verb. + fn as_str(self) -> &'static str { + match self { + Self::Move => "move", + Self::Copy => "copy", + } + } + + fn past(self) -> &'static str { + match self { + Self::Move => "moved", + Self::Copy => "copied", + } + } +} + +// ============================================================================= +// The <NOTE> argument +// ============================================================================= + +/// A `<NOTE>` argument: a hashtag reference as `timeline show` prints one. +/// The two kinds are separate tables in the app with separate commands, so +/// the kind is part of the address and a bare id is not accepted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum NoteRef { + /// `#note:<id>`: a note on a repo's branch. + Branch(String), + /// `#project-note:<id>`: a note on the project itself. + Project(String), +} + +impl NoteRef { + /// Read `#note:<id>` or `#project-note:<id>`. The leading `#` may be + /// left off: unquoted, a shell reads it as the start of a comment, and + /// the argument never arrives. + pub fn parse(input: &str) -> Result<Self, CtlError> { + let invalid = |why: &str| { + CtlError::command( + "invalid_arguments", + format!( + "{why}: <NOTE> must be '#note:<id>' or '#project-note:<id>', got {input:?} \ + (copy one from `stagedctl timeline show`, and quote it: an unquoted # \ + starts a shell comment)" + ), + ) + }; + let reference = input.trim(); + let reference = reference.strip_prefix('#').unwrap_or(reference); + let Some((kind, id)) = reference.split_once(':') else { + return Err(invalid("not a hashtag reference")); + }; + if id.is_empty() || id.chars().any(char::is_whitespace) { + return Err(invalid("the reference has no id")); + } + match kind { + "note" => Ok(Self::Branch(id.to_string())), + "project-note" => Ok(Self::Project(id.to_string())), + "review" | "commit" => Err(invalid( + "only notes move between projects; commits and reviews stay on their branch", + )), + _ => Err(invalid("not a note reference")), + } + } + + fn id(&self) -> &str { + match self { + Self::Branch(id) | Self::Project(id) => id, + } + } + + /// What the output calls this kind of note. + fn kind(&self) -> &'static str { + match self { + Self::Branch(_) => "note", + Self::Project(_) => "project note", + } + } + + /// The hashtag reference of the note `id` of this kind. A copy is a + /// note of the same kind as its original. + fn reference_to(&self, id: &str) -> String { + match self { + Self::Branch(_) => format!("#note:{id}"), + Self::Project(_) => format!("#project-note:{id}"), + } + } + + fn command(&self, transfer: Transfer) -> &'static str { + match (self, transfer) { + (Self::Branch(_), Transfer::Move) => "move_note_to_project", + (Self::Branch(_), Transfer::Copy) => "copy_note_to_project", + (Self::Project(_), Transfer::Move) => "move_project_note_to_project", + (Self::Project(_), Transfer::Copy) => "copy_project_note_to_project", + } + } + + /// The request, under the names the app's transfer commands take. + fn args(&self, target_project_id: &str) -> Value { + match self { + Self::Branch(id) => json!({ "noteId": id, "targetProjectId": target_project_id }), + Self::Project(id) => { + json!({ "projectNoteId": id, "targetProjectId": target_project_id }) + } + } + } +} + +// ============================================================================= +// The app's answer +// ============================================================================= + +/// What the app answers a control caller: the note as it stands after the +/// transfer and the repos the transfer added to the destination. For a +/// branch note, also the branch it landed on and the repo that branch +/// tracks. Either is `null` when the app could not read the row back after +/// the transfer committed. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Landed { + note: LandedNote, + #[serde(default)] + branch: Option<BranchRow>, + #[serde(default)] + repo: Option<RepoName>, + #[serde(default)] + added_repos: Vec<RepoName>, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LandedNote { + id: String, + #[serde(default)] + title: String, +} + +/// A repo by its address. An added repo is answered as this alone. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct RepoName { + github_repo: String, + #[serde(default)] + subpath: Option<String>, +} + +impl RepoName { + fn address(&self) -> String { + repo_address(&self.github_repo, self.subpath.as_deref()) + } +} + +// ============================================================================= +// note move / note copy +// ============================================================================= + +pub fn note_transfer( + client: &Client, + transfer: Transfer, + note: &NoteRef, + to: &str, +) -> Result<CmdOutput, CtlError> { + transfer_with( + |command, args| client.invoke(command, args), + transfer, + note, + to, + ) +} + +/// [`note_transfer`] over any `invoke`, so it can be tested without a +/// Client. +/// +/// `--to` resolves among the projects `list_projects` returns, which for a +/// session is its own project and the ones it created. Anything else is +/// `not_found`, by name or by id, and the app is asked nothing more. The +/// note is not looked up first: the app finds it, checks that its project +/// is within the credential's reach, and answers for both. +pub(crate) fn transfer_with( + mut invoke: impl FnMut(&str, Value) -> Result<Value, CtlError>, + transfer: Transfer, + note: &NoteRef, + to: &str, +) -> Result<CmdOutput, CtlError> { + let projects_raw = invoke("list_projects", json!({}))?; + let projects: Vec<Project> = parse(&projects_raw, "project list")?; + let project = find_project(&projects, to)?.clone(); + + let command = note.command(transfer); + let args = note.args(&project.id); + let answer = invoke(command, args.clone())?; + + match parse::<Landed>(&answer, "note transfer answer") { + Ok(landed) => Ok(render(transfer, note, &project, &landed, &answer)), + Err(error) => { + let human = format!( + "{} {} {} to project {:?}\n ({}; the app's answer could not be read)\n\ + next: stagedctl timeline show {}", + note.kind(), + note.reference_to(note.id()), + transfer.past(), + project.name, + transfer.past(), + project.id + ); + Err(CtlError::Partial { + error: Box::new(error), + applied: vec![json!({ "command": command, "args": args, "result": answer })], + human, + }) + } + } +} + +/// The output of both verbs: the note's reference, the project it is in +/// now, the branch it landed on, and each repo the transfer added. `--json` +/// is `{ ok, mode, projectId, reference, note, addedRepos }` with the app's +/// rows, and for a branch note `branch` and `repo` as well. `reference` is +/// the hashtag reference of the note where it is now: the same note after a +/// move, the new one after a copy. +fn render( + transfer: Transfer, + note: &NoteRef, + project: &Project, + landed: &Landed, + answer: &Value, +) -> CmdOutput { + let source = note.reference_to(note.id()); + let mut human = vec![match transfer { + Transfer::Move => format!( + "{} {source} moved to project {:?}", + note.kind(), + project.name + ), + Transfer::Copy => format!( + "{} {source} copied to project {:?} as {}", + note.kind(), + project.name, + note.reference_to(&landed.note.id) + ), + }]; + human.push(format!(" project id: {}", project.id)); + if !landed.note.title.trim().is_empty() { + human.push(format!(" title: {}", landed.note.title)); + } + let address = landed.repo.as_ref().map(RepoName::address); + match (&landed.branch, &address) { + (Some(branch), Some(address)) => human.push(format!( + " landed on: {address}, branch {}", + branch.branch_name + )), + (Some(branch), None) => human.push(format!(" landed on: branch {}", branch.branch_name)), + (None, _) => {} + } + for repo in &landed.added_repos { + human.push(format!( + " added repo: {} (the project did not track it; its branch is set up in the \ + background)", + repo.address() + )); + } + human.push(match (&landed.branch, &address) { + (Some(branch), Some(address)) => format!( + "next: stagedctl timeline show {} --repo {address} --branch {}", + project.id, branch.branch_name + ), + _ => format!("next: stagedctl timeline show {}", project.id), + }); + + let mut json = Map::new(); + json.insert("ok".into(), json!(true)); + json.insert("mode".into(), json!(transfer.as_str())); + json.insert("projectId".into(), json!(project.id)); + json.insert( + "reference".into(), + json!(note.reference_to(&landed.note.id)), + ); + for key in ["note", "branch", "repo", "addedRepos"] { + if let Some(value) = answer.get(key) { + json.insert(key.into(), value.clone()); + } + } + CmdOutput { + json: Value::Object(json), + human: human.join("\n"), + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs new file mode 100644 index 000000000..a89057a97 --- /dev/null +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs @@ -0,0 +1,747 @@ +use std::cell::RefCell; +use std::collections::HashMap; + +use super::*; + +// ----------------------------------------------------------------------- +// A scripted app +// ----------------------------------------------------------------------- + +/// Answers each command from a table and records every call, so a test can +/// say what the app was asked and in what order. +#[derive(Default)] +struct App { + answers: HashMap<&'static str, Result<Value, (&'static str, &'static str)>>, + calls: RefCell<Vec<(String, Value)>>, +} + +impl App { + /// An app whose caller reaches "Source" (p1) and "Target" (p2). + fn with_projects() -> Self { + Self::default().answer( + "list_projects", + json!([ + { "id": "p1", "name": "Source", "location": "local" }, + { "id": "p2", "name": "Target", "location": "local" }, + ]), + ) + } + + fn answer(mut self, command: &'static str, value: Value) -> Self { + self.answers.insert(command, Ok(value)); + self + } + + /// `command` fails the way the app's own refusal does (HTTP 400). + fn refuse(mut self, command: &'static str, message: &'static str) -> Self { + self.answers.insert(command, Err(("app_error", message))); + self + } + + /// `command` is refused by scope (HTTP 403, exit 4). + fn deny(mut self, command: &'static str, message: &'static str) -> Self { + self.answers.insert(command, Err(("scope_denied", message))); + self + } + + fn invoke(&self) -> impl FnMut(&str, Value) -> Result<Value, CtlError> + '_ { + move |command, args| { + self.calls.borrow_mut().push((command.to_string(), args)); + match self.answers.get(command) { + Some(Ok(value)) => Ok(value.clone()), + Some(Err(("scope_denied", message))) => Err(CtlError::Authorization { + code: "scope_denied".to_string(), + message: message.to_string(), + }), + Some(Err((code, message))) => Err(CtlError::command(code, *message)), + None => Err(CtlError::Transport(format!("{command}: connection reset"))), + } + } + } + + fn commands(&self) -> Vec<String> { + self.calls.borrow().iter().map(|(c, _)| c.clone()).collect() + } + + fn args_of(&self, command: &str) -> Value { + self.calls + .borrow() + .iter() + .find(|(c, _)| c == command) + .map(|(_, args)| args.clone()) + .unwrap_or_else(|| panic!("{command} was not called")) + } +} + +fn branch_note() -> NoteRef { + NoteRef::Branch("n1".to_string()) +} + +fn project_note() -> NoteRef { + NoteRef::Project("pn1".to_string()) +} + +fn note_row(id: &str, title: &str) -> Value { + json!({ "id": id, "title": title, "content": "body", "sessionId": null }) +} + +fn branch_row() -> Value { + json!({ + "id": "b9", + "projectId": "p2", + "projectRepoId": "r9", + "branchName": "max/target", + "baseBranch": "origin/main", + "worktreePath": null, + }) +} + +fn repo_row() -> Value { + json!({ + "id": "r9", + "projectId": "p2", + "githubRepo": "acme/widgets", + "subpath": "apps/web", + "branchName": "max/target", + "isPrimary": true, + }) +} + +/// The app's answer for a branch note that landed on `max/target`. +fn landed_on_branch(note: Value, added: Value) -> Value { + json!({ "note": note, "branch": branch_row(), "repo": repo_row(), "addedRepos": added }) +} + +fn message(err: &CtlError) -> String { + err.to_string() +} + +// ----------------------------------------------------------------------- +// The <NOTE> argument +// ----------------------------------------------------------------------- + +#[test] +fn a_note_is_named_by_the_hashtag_reference_the_cli_prints() { + for (input, expected) in [ + ("#note:n1", branch_note()), + ("#project-note:pn1", project_note()), + // Unquoted, a shell drops everything from the #, so it may be left + // off. + ("note:n1", branch_note()), + ("project-note:pn1", project_note()), + (" #note:n1\n", branch_note()), + ] { + assert_eq!(NoteRef::parse(input).unwrap(), expected, "{input:?}"); + } + // What is printed back is the form that was read. + assert_eq!(branch_note().reference_to("n1"), "#note:n1"); + assert_eq!(project_note().reference_to("pn1"), "#project-note:pn1"); +} + +#[test] +fn anything_but_a_note_reference_is_refused() { + for input in [ + "", + "#", + // A bare id does not say which kind of note it is. + "n1", + "#note:", + "#project-note:", + "#note: n1", + "#Note:n1", + "#image:i1", + "##note:n1", + ] { + let err = NoteRef::parse(input).unwrap_err(); + assert_eq!(err.exit_code(), 1, "{input:?}"); + assert_eq!(err.code(), "invalid_arguments", "{input:?}"); + let text = message(&err); + assert!( + text.contains("'#note:<id>' or '#project-note:<id>'"), + "{text}" + ); + assert!(text.contains(&format!("got {input:?}")), "{text}"); + assert!(text.contains("stagedctl timeline show"), "{text}"); + } + // The other things a timeline prints are references too, and do not + // move. + for input in ["#review:r1", "#commit:abc123"] { + let err = NoteRef::parse(input).unwrap_err(); + assert_eq!(err.code(), "invalid_arguments", "{input:?}"); + assert!( + message(&err).contains("commits and reviews stay on their branch"), + "{err}" + ); + } +} + +// ----------------------------------------------------------------------- +// The request +// ----------------------------------------------------------------------- + +#[test] +fn each_kind_and_verb_sends_its_own_command_with_the_destinations_id() { + for (transfer, note, command, args) in [ + ( + Transfer::Move, + branch_note(), + "move_note_to_project", + json!({ "noteId": "n1", "targetProjectId": "p2" }), + ), + ( + Transfer::Copy, + branch_note(), + "copy_note_to_project", + json!({ "noteId": "n1", "targetProjectId": "p2" }), + ), + ( + Transfer::Move, + project_note(), + "move_project_note_to_project", + json!({ "projectNoteId": "pn1", "targetProjectId": "p2" }), + ), + ( + Transfer::Copy, + project_note(), + "copy_project_note_to_project", + json!({ "projectNoteId": "pn1", "targetProjectId": "p2" }), + ), + ] { + // The destination by name, by id, and by a name in another case. + for to in ["Target", "p2", "target"] { + let app = App::with_projects().answer( + command, + json!({ "note": note_row("x", "Findings"), "addedRepos": [] }), + ); + transfer_with(app.invoke(), transfer, ¬e, to).unwrap(); + // One read to find the destination, then the one write. Nothing + // is read afterwards: the answer says where the note landed. + assert_eq!(app.commands(), vec!["list_projects", command], "{to}"); + assert_eq!(app.args_of(command), args, "{command} --to {to}"); + } + } +} + +#[test] +fn a_copy_may_name_the_notes_own_project() { + // The CLI does not know which project the note is in, and a copy into + // it is a duplicate, which the app allows. + let app = App::with_projects().answer( + "copy_note_to_project", + landed_on_branch(note_row("n9", "Findings (2)"), json!([])), + ); + transfer_with(app.invoke(), Transfer::Copy, &branch_note(), "Source").unwrap(); + assert_eq!( + app.args_of("copy_note_to_project"), + json!({ "noteId": "n1", "targetProjectId": "p1" }) + ); +} + +// ----------------------------------------------------------------------- +// The output +// ----------------------------------------------------------------------- + +#[test] +fn a_moved_branch_note_prints_where_it_landed() { + let answer = landed_on_branch(note_row("n1", "Findings"), json!([])); + let app = App::with_projects().answer("move_note_to_project", answer.clone()); + let out = transfer_with(app.invoke(), Transfer::Move, &branch_note(), "Target").unwrap(); + + assert_eq!( + out.human, + "note #note:n1 moved to project \"Target\"\n\ + \x20 project id: p2\n\ + \x20 title: Findings\n\ + \x20 landed on: acme/widgets:apps/web, branch max/target\n\ + next: stagedctl timeline show p2 --repo acme/widgets:apps/web --branch max/target" + ); + assert_eq!( + out.json, + json!({ + "ok": true, + "mode": "move", + "projectId": "p2", + "reference": "#note:n1", + "note": answer["note"], + "branch": branch_row(), + "repo": repo_row(), + "addedRepos": [], + }) + ); +} + +#[test] +fn a_transfer_that_added_a_repo_to_the_destination_says_so() { + let added = json!([{ "githubRepo": "acme/widgets", "subpath": "apps/web" }]); + for (transfer, command) in [ + (Transfer::Move, "move_note_to_project"), + (Transfer::Copy, "copy_note_to_project"), + ] { + let app = App::with_projects().answer( + command, + landed_on_branch(note_row("n1", "Findings"), added.clone()), + ); + let out = transfer_with(app.invoke(), transfer, &branch_note(), "Target").unwrap(); + assert!( + out.human.contains( + "\n added repo: acme/widgets:apps/web (the project did not track it; its \ + branch is set up in the background)\n" + ), + "{}", + out.human + ); + assert_eq!(out.json["addedRepos"], added); + } +} + +#[test] +fn a_copy_prints_the_new_notes_reference() { + // The copy has its own id, and the title the app gave it on a branch + // that already had the original's. + let answer = landed_on_branch(note_row("n9", "Findings (2)"), json!([])); + let app = App::with_projects().answer("copy_note_to_project", answer.clone()); + let out = transfer_with(app.invoke(), Transfer::Copy, &branch_note(), "Target").unwrap(); + + assert_eq!( + out.human, + "note #note:n1 copied to project \"Target\" as #note:n9\n\ + \x20 project id: p2\n\ + \x20 title: Findings (2)\n\ + \x20 landed on: acme/widgets:apps/web, branch max/target\n\ + next: stagedctl timeline show p2 --repo acme/widgets:apps/web --branch max/target" + ); + assert_eq!(out.json["mode"], "copy"); + assert_eq!(out.json["reference"], "#note:n9"); + assert_eq!(out.json["note"]["id"], "n9"); +} + +#[test] +fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought() { + let answer = json!({ + "note": { "id": "pn1", "projectId": "p2", "title": "Plan", "content": "body" }, + "addedRepos": [ + { "githubRepo": "acme/widgets", "subpath": "apps/web" }, + { "githubRepo": "acme/gadgets", "subpath": null }, + ], + }); + let app = App::with_projects().answer("move_project_note_to_project", answer.clone()); + let out = transfer_with(app.invoke(), Transfer::Move, &project_note(), "Target").unwrap(); + + assert_eq!( + out.human, + "project note #project-note:pn1 moved to project \"Target\"\n\ + \x20 project id: p2\n\ + \x20 title: Plan\n\ + \x20 added repo: acme/widgets:apps/web (the project did not track it; its branch is \ + set up in the background)\n\ + \x20 added repo: acme/gadgets (the project did not track it; its branch is set up in \ + the background)\n\ + next: stagedctl timeline show p2" + ); + // A project note is on no branch, so the app answers neither row and + // none is invented. + assert_eq!( + out.json, + json!({ + "ok": true, + "mode": "move", + "projectId": "p2", + "reference": "#project-note:pn1", + "note": answer["note"], + "addedRepos": answer["addedRepos"], + }) + ); + + let copy = json!({ + "note": { "id": "pn9", "projectId": "p2", "title": "Plan", "content": "body" }, + "addedRepos": [], + }); + let app = App::with_projects().answer("copy_project_note_to_project", copy); + let out = transfer_with(app.invoke(), Transfer::Copy, &project_note(), "Target").unwrap(); + assert_eq!( + out.human, + "project note #project-note:pn1 copied to project \"Target\" as #project-note:pn9\n\ + \x20 project id: p2\n\ + \x20 title: Plan\n\ + next: stagedctl timeline show p2" + ); +} + +#[test] +fn a_landing_row_the_app_could_not_read_back_is_left_out() { + // The app answers `null` for a row it could not read after the transfer + // committed. The note still landed, and the output does not guess. + for (branch, repo, line) in [ + (Value::Null, Value::Null, None), + ( + branch_row(), + Value::Null, + Some(" landed on: branch max/target"), + ), + ] { + let app = App::with_projects().answer( + "move_note_to_project", + json!({ + "note": note_row("n1", ""), + "branch": branch, + "repo": repo, + "addedRepos": [], + }), + ); + let out = transfer_with(app.invoke(), Transfer::Move, &branch_note(), "Target").unwrap(); + let mut expected = vec![ + "note #note:n1 moved to project \"Target\"", + " project id: p2", + ]; + expected.extend(line); + expected.push("next: stagedctl timeline show p2"); + // An untitled note prints no title line either. + assert_eq!(out.human, expected.join("\n")); + assert_eq!(out.json["ok"], true); + } +} + +// ----------------------------------------------------------------------- +// Failures +// ----------------------------------------------------------------------- + +#[test] +fn a_destination_the_credential_does_not_list_is_not_found_and_nothing_is_written() { + // A session's project list holds its own project and the ones it + // created. Any other project is unknown to it, by name and by id. + for to in ["Elsewhere", "p3"] { + let app = App::with_projects(); + let err = transfer_with(app.invoke(), Transfer::Move, &branch_note(), to).unwrap_err(); + assert_eq!(err.exit_code(), 1, "{to}"); + assert_eq!(err.code(), "not_found", "{to}"); + assert_eq!(app.commands(), vec!["list_projects"], "{to}"); + } + + let app = App::default().answer( + "list_projects", + json!([{ "id": "p1", "name": "Target" }, { "id": "p2", "name": "TARGET" }]), + ); + let err = transfer_with(app.invoke(), Transfer::Copy, &project_note(), "target").unwrap_err(); + assert_eq!(err.code(), "ambiguous"); + assert_eq!(app.commands(), vec!["list_projects"]); +} + +#[test] +fn the_transfers_refusals_pass_through_as_command_failures() { + for (transfer, note, command, refusal) in [ + ( + Transfer::Move, + branch_note(), + "move_note_to_project", + "\"Findings\" is already in Target.", + ), + ( + Transfer::Move, + branch_note(), + "move_note_to_project", + "\"Findings\"'s session is running again; wait for it to finish before moving \ + the note.", + ), + ( + Transfer::Copy, + branch_note(), + "copy_note_to_project", + "\"Findings\" is still being generated; wait for its session to finish before \ + copying it.", + ), + ( + Transfer::Copy, + branch_note(), + "copy_note_to_project", + "Branch 'scratch' is not bound to a repository, so its notes cannot be copied to \ + another project.", + ), + ( + Transfer::Move, + project_note(), + "move_project_note_to_project", + "Project 'Target' runs on a remote workspace; \"Plan\" has child notes, which can \ + only move between local projects.", + ), + ( + Transfer::Move, + project_note(), + "move_project_note_to_project", + "Could not add acme/gadgets to Target: clone failed. acme/widgets at apps/web was \ + added to Target along the way and remains tracked there.", + ), + ( + Transfer::Copy, + project_note(), + "copy_project_note_to_project", + "Project note not found: pn1", + ), + ] { + let app = App::with_projects().refuse(command, refusal); + let err = transfer_with(app.invoke(), transfer, ¬e, "Target").unwrap_err(); + assert_eq!(err.exit_code(), 1, "{refusal}"); + assert_eq!(message(&err), format!("app_error: {refusal}")); + // Nothing landed, so nothing is reported as applied. + assert_eq!(err.partial_output(false), None); + assert_eq!(err.partial_output(true), None); + } +} + +#[test] +fn a_scope_refusal_keeps_its_code_and_exit_4() { + for refusal in [ + // The note is in a project the credential does not reach. + "the note belongs to another project; this credential covers project p1 and the \ + projects it created", + // The destination is one, which the project list hid from this + // caller but not from the app. + "the destination is a project outside this credential's reach; this credential \ + covers project p1 and the projects it created", + "move_note_to_project changes the app and this credential is read-only", + ] { + for (note, command) in [ + (branch_note(), "move_note_to_project"), + (project_note(), "move_project_note_to_project"), + ] { + let app = App::with_projects().deny(command, refusal); + let err = transfer_with(app.invoke(), Transfer::Move, ¬e, "Target").unwrap_err(); + assert_eq!(err.exit_code(), 4, "{refusal}"); + assert_eq!(message(&err), format!("scope_denied: {refusal}")); + assert_eq!(err.partial_output(false), None); + } + } +} + +#[test] +fn a_failed_project_list_stops_before_the_write() { + let app = App::default(); + let err = transfer_with(app.invoke(), Transfer::Move, &branch_note(), "Target").unwrap_err(); + assert_eq!(err.exit_code(), 2); + assert_eq!(app.commands(), vec!["list_projects"]); +} + +#[test] +fn a_transfer_whose_answer_cannot_be_read_is_still_reported_as_landed() { + // The app answered, so the transfer ran. The caller is told, with the + // read's own error and exit code, and with what the app said. + let app = App::with_projects().answer("copy_note_to_project", json!({ "unexpected": true })); + let err = transfer_with(app.invoke(), Transfer::Copy, &branch_note(), "Target").unwrap_err(); + + assert_eq!(err.exit_code(), 2); + assert!( + message(&err).starts_with("transport: unexpected note transfer answer shape"), + "{err}" + ); + assert_eq!( + err.partial_output(false).unwrap(), + "note #note:n1 copied to project \"Target\"\n\ + \x20 (copied; the app's answer could not be read)\n\ + next: stagedctl timeline show p2" + ); + let partial: Value = serde_json::from_str(&err.partial_output(true).unwrap()).unwrap(); + assert_eq!(partial["ok"], false); + assert_eq!( + partial["applied"], + json!([{ + "command": "copy_note_to_project", + "args": { "noteId": "n1", "targetProjectId": "p2" }, + "result": { "unexpected": true }, + }]) + ); +} + +// ----------------------------------------------------------------------- +// What the help promises, held to the app +// ----------------------------------------------------------------------- + +#[test] +fn the_commands_are_allowlisted_by_the_control_server() { + let source = include_str!("../../../../src/control_server.rs"); + let start = source.find("pub const ALLOWED_COMMANDS").unwrap(); + let end = start + source[start..].find("];").unwrap(); + let listed: Vec<&str> = source[start..end] + .lines() + .filter_map(|line| line.trim().strip_prefix('"')) + .filter_map(|rest| rest.split('"').next()) + .collect(); + for command in NOTE_TRANSFER_COMMANDS { + assert!(listed.contains(command), "{command} is not allowlisted"); + assert!(is_note_transfer_command(command)); + } + // The read both verbs make first. + assert!(listed.contains(&"list_projects")); + assert!(!is_note_transfer_command("list_projects")); + + // Every kind and verb goes out as one of them. + for note in [branch_note(), project_note()] { + for transfer in [Transfer::Move, Transfer::Copy] { + assert!(is_note_transfer_command(note.command(transfer))); + } + } +} + +#[test] +fn the_requests_use_the_argument_names_the_apps_commands_read() { + let dispatch = include_str!("../../../../src/web_server.rs"); + for (arm, id_arg) in [ + ( + "\"move_note_to_project\" | \"copy_note_to_project\" => {", + "\"noteId\"", + ), + ( + "\"move_project_note_to_project\" | \"copy_project_note_to_project\" => {", + "\"projectNoteId\"", + ), + ] { + let start = dispatch.find(arm).unwrap_or_else(|| panic!("no arm {arm}")); + let body = &dispatch[start..start + 600]; + assert!(body.contains(id_arg), "{arm} no longer reads {id_arg}"); + assert!(body.contains("\"targetProjectId\""), "{arm}"); + } +} + +/// The help of one verb, as `--help` prints it. +fn help_of(verb: &str) -> String { + let help = crate::cli::render_all_help(); + help.split(&format!("=== stagedctl note {verb} --help ===")) + .nth(1) + .and_then(|rest| rest.split("\n=== ").next()) + .unwrap_or_else(|| panic!("note {verb} has help")) + .to_string() +} + +#[test] +fn help_states_the_transfers_rules_as_the_app_has_them() { + let move_help = help_of("move"); + let copy_help = help_of("copy"); + let transfer = include_str!("../../../../src/note_transfer.rs"); + + // The refusals the help lists are the ones the transfer makes. If one + // of these is reworded or removed there, read the help again. + for (refusal, verbs, promise) in [ + ( + "\"{} is already in {}.\"", + &[&move_help][..], + "already in the destination project", + ), + ( + "is still being generated; wait for its session to finish before", + &[&move_help][..], + "still being written", + ), + ( + "is still being generated; wait for its session to finish before", + &[©_help][..], + "never finished being written", + ), + ( + "'s session is {} again; wait for it to finish before", + &[&move_help][..], + "queued or running", + ), + ( + "is not bound to a repository", + &[&move_help, ©_help][..], + "tracks no repo", + ), + ( + "runs on a remote workspace", + &[&move_help][..], + "either project runs on a remote\n workspace", + ), + ( + "notes on remote branches can't move between projects", + &[&move_help][..], + "on a remote branch", + ), + ( + "which is in a different project", + &[&move_help][..], + "outside the project note's own project", + ), + ] { + assert!( + transfer.contains(refusal), + "the transfer no longer says {refusal:?}; update `note move`/`note copy` --help" + ); + for help in verbs { + assert!(help.contains(promise), "help lacks {promise:?}:\n{help}"); + } + } + // A copy is refused only for a note that never finished: the second + // check is skipped for it. + assert!(transfer.contains("if mode == TransferMode::Copy {\n return Ok(());")); + assert!( + copy_help.contains("is running again can be copied"), + "{copy_help}" + ); + + // What a copy is: a standalone note of the user's own. + assert!(transfer.contains(".with_subtype(Note::SUBTYPE_WRITTEN)")); + for promise in [ + "new note with its own id", + "no session", + "editable in the app like a note the user wrote", + "no link to a parent project note and no child notes", + "no suggested next steps", + "never adds a repo", + ] { + assert!(copy_help.contains(promise), "copy help lacks {promise:?}"); + } + + // What a move carries. + for promise in [ + "The note keeps\nits id", + "Its session\n comes with it", + "takes its child notes along", + "Commits and code reviews are not part of a note", + "moving it back does not restore that link", + ] { + assert!(move_help.contains(promise), "move help lacks {promise:?}"); + } + + // The title a note gets on a branch that has one by that name. + let notes = include_str!("../../../../src/store/notes.rs"); + assert!(notes.contains("Ok(format!(\"{base} ({})\", max_n + 1))")); + for help in [&move_help, ©_help] { + assert!(help.contains("\"<title> (2)\""), "{help}"); + } + + // The repo is added with nothing but its name and subpath, which is + // `project add-repo` without --branch. + assert!(transfer.contains("github_repo: key.github_repo,\n subpath: key.subpath,\n ..Default::default()")); + assert!( + move_help.contains("the way `stagedctl project add-repo` adds one without --branch"), + "{move_help}" + ); + + // Both verbs are writes on two projects. + for help in [&move_help, ©_help] { + assert!( + help.contains("Needs write access to both projects"), + "{help}" + ); + assert!(help.contains("`scope_denied`"), "{help}"); + assert!(help.contains("`not_found`"), "{help}"); + assert!(help.contains("stagedctl has no delete"), "{help}"); + } +} + +#[test] +fn the_guide_describes_both_verbs() { + // The guide ships with the app and is named in every session's prompt. + let guide = include_str!("../../../../resources/stagedctl/guide.md"); + // One paragraph per line of thought, whatever the wrapping. + let flat = guide.split_whitespace().collect::<Vec<_>>().join(" "); + for expected in [ + "`stagedctl note move`", + "`stagedctl note copy`", + "'#note:<id>'", + "'#project-note:<id>'", + "an unquoted `#` starts a shell comment", + "both projects", + "the user can move the note back or delete the copy", + ] { + assert!(flat.contains(expected), "the guide lacks {expected:?}"); + } +} diff --git a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt index e4786736d..246e886db 100644 --- a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt +++ b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt @@ -24,6 +24,9 @@ Addressing: <tag> a tag id, <group>/<name>, or a bare tag name when only one tag has it, as printed by `stagedctl tag list` <group> a tag group name or id, as printed by `stagedctl tag list` + <note> a note's hashtag reference, #note:<id> or #project-note:<id>, + as printed by `stagedctl timeline show`; quote it, or leave + the # off (an unquoted # starts a shell comment) Ids print in hashtag reference form (#note:<id>, #project-note:<id>, #review:<id>, #commit:<sha>) so they can be pasted directly into session @@ -48,6 +51,7 @@ Commands: timeline Read project and repo timelines (commits, notes, reviews, images) session Start, observe, wait for, and cancel agent sessions image Attach images to a repo's timeline + note Move and copy notes between projects tag Read and edit the tag catalog: tag groups, tags, and which projects carry them connect Ask the Staged user to approve this client (outside a spawned session) disconnect Forget this machine's connected-app grants and revoke them in Staged @@ -792,6 +796,164 @@ Options: -h, --help Print help (see a summary with '-h') +=== stagedctl note --help === +Move and copy notes between projects + +Usage: stagedctl note [OPTIONS] <COMMAND> + +Commands: + move Move a note, with its session, to another project + copy Copy a note into a project as a new standalone note + help Print this message or the help of the given subcommand(s) + +Options: + --lock-path <PATH> + Path to the app's control file (defaults to $STAGEDCTL_LOCK, then live ~/.staged/control/<pid>/discovery.json files, newest first) + + --json + Print machine-readable JSON on stdout instead of human-readable text + + -h, --help + Print help + +=== stagedctl note move --help === +Move a note to another project. <NOTE> is a hashtag reference as +`stagedctl timeline show` prints it: #note:<id> for a branch note, +#project-note:<id> for a project note. Quote it, or leave the # off: an +unquoted # starts a shell comment. --to is the destination, a project +name or id (see `stagedctl project list`). + +This is "Move to project" in the note's menu in the app. The note keeps +its id, so its reference still resolves, and what comes with it depends +on its kind: + + branch note lands on the destination's branch for the repo and + subpath the note's branch tracks (the oldest such + branch, when the destination has several). Its session + comes with it, so the transcript stays with the note, + and so do the images and videos in its body. Its link + to the project note it was written under is dropped, + and moving it back does not restore that link. A title + another note on the landing branch has gets a number: + "<title> (2)". + project note lands in the destination project with its session and + media, and takes its child notes along. Each child + lands, with its own session, on the destination's + branch for its repo and subpath, still linked to the + project note. + +Commits and code reviews are not part of a note. They stay on the branch +they were made on. + +A destination that does not track a repo the move needs gets it first, +the way `stagedctl project add-repo` adds one without --branch: a new +branch named after the project, set up in the background (a worktree, +or a clone into a remote project's workspace). The output names each +repo added this way. Such a repo stays in the project when a later step +of the move fails. A project note's error names it; a branch note's +does not, so look at `stagedctl project get`. + +The app refuses a move, with the note left where it was (exit 1, +`app_error`, the app's own message), when: + - the note is already in the destination project; + - the note is still being written, or its session or a child note's + is queued or running. Wait for it with `stagedctl session wait`; + - the note's branch, or a child note's, tracks no repo; + - a project note has child notes and either project runs on a remote + workspace, or a child note is on a remote branch or on a branch + outside the project note's own project. + +Needs write access to both projects, the one the note is in and the +destination. A read-only credential is refused (exit 4, `scope_denied`), +and so is a note in a project the credential does not reach. A +destination it does not reach is not among its projects and exits 1 +(`not_found`). A session may move notes between its own project and the +projects it created, in either direction, and nowhere else. + +A move shows at once in both projects. The user can move the note back +in the app, and `stagedctl note move` can too. stagedctl has no delete, +and cannot remove a repo a move added. + +Usage: stagedctl note move [OPTIONS] --to <PROJECT> <NOTE> + +Arguments: + <NOTE> + The note: '#note:<id>' or '#project-note:<id>' (see `stagedctl timeline show`) + +Options: + --lock-path <PATH> + Path to the app's control file (defaults to $STAGEDCTL_LOCK, then live ~/.staged/control/<pid>/discovery.json files, newest first) + + --to <PROJECT> + The destination project, by name or id (see `stagedctl project list`) + + --json + Print machine-readable JSON on stdout instead of human-readable text + + -h, --help + Print help (see a summary with '-h') + +=== stagedctl note copy --help === +Copy a note into a project. <NOTE> and --to are as in `stagedctl note +move`: a hashtag reference (#note:<id> or #project-note:<id>, quoted or +without the #) and a project name or id. + +This is "Copy to project" in the note's menu in the app. The original +is left exactly as it is. The copy is a new note with its own id, which +this command prints as a hashtag reference. It holds the original's +title and body as they read now, with its own copies of the images and +videos in the body, and nothing else: + + - no session. The transcript stays with the original, and the copy is + editable in the app like a note the user wrote; + - no link to a parent project note and no child notes. Copying a + project note copies that one note; + - no suggested next steps. + +A copy of a branch note lands on the destination's branch for the repo +and subpath the note's branch tracks. A destination that does not track +that repo gets it first, as in `stagedctl note move`, and the output +names it. A title another note on the landing branch has gets a number: +"<title> (2)". A copy of a project note lands in the destination +project and never adds a repo. + +--to may be the project the note is already in. That duplicates the +note beside the original, on the same branch for a branch note. + +The app refuses a copy (exit 1, `app_error`, the app's own message) +when the note has never finished being written, or when a branch +note's branch tracks no repo. A finished note whose session was resumed +and is running again can be copied, where it could not be moved: the +copy is the note as it reads now. + +Needs write access to both projects, the one the note is in and the +destination, as `stagedctl note move` does: exit 4 (`scope_denied`) +under a read-only credential or for a note in a project the credential +does not reach, exit 1 (`not_found`) for a destination it does not +reach. + +A copy shows at once in the destination, where the user can delete it. +stagedctl has no delete. + +Usage: stagedctl note copy [OPTIONS] --to <PROJECT> <NOTE> + +Arguments: + <NOTE> + The note: '#note:<id>' or '#project-note:<id>' (see `stagedctl timeline show`) + +Options: + --lock-path <PATH> + Path to the app's control file (defaults to $STAGEDCTL_LOCK, then live ~/.staged/control/<pid>/discovery.json files, newest first) + + --to <PROJECT> + The destination project, by name or id (see `stagedctl project list`) + + --json + Print machine-readable JSON on stdout instead of human-readable text + + -h, --help + Print help (see a summary with '-h') + === stagedctl tag --help === Read and edit the tag catalog: tag groups, tags, and which projects carry them diff --git a/apps/staged/src-tauri/resources/stagedctl/guide.md b/apps/staged/src-tauri/resources/stagedctl/guide.md index a0a98fa9c..c4a43dee0 100644 --- a/apps/staged/src-tauri/resources/stagedctl/guide.md +++ b/apps/staged/src-tauri/resources/stagedctl/guide.md @@ -137,6 +137,39 @@ chain. A session may add a repo to its own project and to the projects it created. A connected app approved for one project can add repos to that project and cannot create projects. +Moving and copying a note (`stagedctl note move`, `stagedctl note copy`) +fit the invariant: they are "Move to project" and "Copy to project" in a +note's menu in the app, the note shows at once where it was sent, and the +user can move the note back or delete the copy. Name the note by the +reference `stagedctl timeline show` prints, `'#note:<id>'` for a branch +note or `'#project-note:<id>'` for a project note, in quotes or without the +`#`: an unquoted `#` starts a shell comment, so the note never reaches the +command. Both verbs write to both projects, the one the note is in and the +destination, so a session can send notes between its own project and the +projects it created, and nowhere else. Know what each one leaves behind +before choosing: + +- A move takes the note itself. It keeps its id and its session, and a + project note takes its child notes along with theirs. A branch note + moved on its own loses its link to the project note it was written + under, and moving it back does not restore that link. Commits and code + reviews stay on their branch. +- A copy is a new, standalone note with its own id: the title and body as + they read now, with no session, no parent or child notes, and no + suggested next steps. The original is untouched. +- A branch note lands on the destination's branch for the repo and subpath + its own branch tracks. A destination that lacks that repo gets it first, + the way `stagedctl project add-repo` adds one: a new branch, then a + worktree or a clone into the remote workspace and the setup actions, in + the background. The output names each repo added. It stays in the + project if the transfer then fails, and only the user can remove it. + +The app refuses a transfer it cannot make whole, with exit 1 and its own +reason: a note whose session is still writing it, a move into the project +the note is already in, a note whose branch tracks no repo, a project note +with child notes when either project is remote. Wait for the session, or +pick another destination. Do not work around a refusal. + Tag assignments (`stagedctl project tag`, `stagedctl project untag`) fit the invariant: they show at once as the pills and chips in the project header, where the user can undo them with a group pill's None or a chip's ×. A tag diff --git a/apps/staged/src-tauri/src/control_server.rs b/apps/staged/src-tauri/src/control_server.rs index 2780489f9..6d5502c3b 100644 --- a/apps/staged/src-tauri/src/control_server.rs +++ b/apps/staged/src-tauri/src/control_server.rs @@ -75,12 +75,24 @@ //! commands as the user, so that adds no reach to the machine, and a //! session may hold only a fixed number of created projects. A caller's //! request is checked in the app the way the desktop forms check theirs -//! (`project_commands::control`). No deletes — `delete_project` and -//! `remove_project_repo` stay off the table, and `delete_tag` and -//! `delete_tag_group` drop assignments on every project carrying the tag, -//! which nothing in the UI undoes — no history rewrites, no `create_pr` / -//! `push_branch`. Exposing a destructive verb reopens the auth design and -//! must come with a [`PROTOCOL_VERSION`] bump. +//! (`project_commands::control`). +//! +//! It includes moving and copying a note to another project too +//! (`move_note_to_project`, `copy_note_to_project` and their project-note +//! twins): the transfer behind the note dialogs' "Move to project…" and +//! "Copy to project…", with its rules and refusals as they are (see +//! [`note_transfer`](crate::note_transfer)). The user undoes a copy by +//! deleting it and a move by moving the note back, and removes a repo the +//! transfer added like any other. One link does not come back with the +//! note: a branch note moved on its own is detached from its parent project +//! note. The note's project and the destination must both be within the +//! caller's reach. +//! +//! No deletes — `delete_project` and `remove_project_repo` stay off the +//! table, and `delete_tag` and `delete_tag_group` drop assignments on every +//! project carrying the tag, which nothing in the UI undoes — no history +//! rewrites, no `create_pr` / `push_branch`. Exposing a destructive verb +//! reopens the auth design and must come with a [`PROTOCOL_VERSION`] bump. //! //! One verb reaches past the data into the user's view: `open_project` //! raises a window and asks it to show a project (see @@ -211,6 +223,11 @@ pub const ALLOWED_COMMANDS: &[&str] = &[ "set_icon_tag_group", "set_tag_group_sidebar", "reorder_tag_groups", + // note move / copy + "move_note_to_project", + "copy_note_to_project", + "move_project_note_to_project", + "copy_project_note_to_project", ]; /// Request body cap for `POST /api/invoke/{command}`. Control payloads are @@ -1641,6 +1658,8 @@ mod tests { let expected = [ "add_project_repo", "cancel_session", + "copy_note_to_project", + "copy_project_note_to_project", "create_image", "create_project", "create_tag", @@ -1654,6 +1673,8 @@ mod tests { "list_project_notes", "list_project_repos", "list_projects", + "move_note_to_project", + "move_project_note_to_project", "move_tag", "open_project", "rename_tag_group", diff --git a/apps/staged/src-tauri/src/note_transfer.rs b/apps/staged/src-tauri/src/note_transfer.rs index b0ae294bd..69b6f087f 100644 --- a/apps/staged/src-tauri/src/note_transfer.rs +++ b/apps/staged/src-tauri/src/note_transfer.rs @@ -64,6 +64,8 @@ //! note to have finished once; a session that was resumed does not hold a //! copy back, since the copy leaves the session where it is. +pub(crate) mod control; + use std::collections::{HashMap, HashSet}; use std::future::Future; use std::io::ErrorKind; diff --git a/apps/staged/src-tauri/src/note_transfer/control.rs b/apps/staged/src-tauri/src/note_transfer/control.rs new file mode 100644 index 000000000..e7b20a200 --- /dev/null +++ b/apps/staged/src-tauri/src/note_transfer/control.rs @@ -0,0 +1,112 @@ +//! What a control caller (`stagedctl note move`, `stagedctl note copy`) is +//! told about a transfer. +//! +//! The app's windows open a note where it is and know its surroundings, so +//! the transfer commands answer them with the note alone. A control caller +//! named a note by id and a project, and is told what the transfer did with +//! them: the branch the note landed on, and the repos the transfer added to +//! the destination to make room for it. Only the transfer knows the second. +//! Once added, a repo reads like any other the project tracks, so each one +//! is noted as its add succeeds ([`AddedRepos`]). +//! +//! Nothing here decides anything about a transfer. Every caller runs the +//! same [`transfer_branch_note`](super::transfer_branch_note) or +//! [`transfer_project_note`](super::transfer_project_note) with the same +//! repo-adding step. This module watches that step and words the answer. + +use std::future::Future; +use std::sync::{Mutex, PoisonError}; + +use serde_json::{json, Value}; + +use super::RepoKey; +use crate::store::Store; + +/// The repos one transfer added to its destination, in the order it added +/// them. +#[derive(Debug, Default)] +pub(crate) struct AddedRepos(Mutex<Vec<RepoKey>>); + +impl AddedRepos { + /// Run `add`, the transfer's repo-adding step for `key`, and note the + /// repo once it is added. A failed add is the transfer's to report and + /// is not noted. + pub(crate) async fn watch<Fut>(&self, key: RepoKey, add: Fut) -> Result<(), String> + where + Fut: Future<Output = Result<(), String>>, + { + add.await?; + self.0 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .push(key); + Ok(()) + } + + /// `[{ githubRepo, subpath }]`, the names `list_project_repos` uses. + fn into_json(self) -> Value { + self.0 + .into_inner() + .unwrap_or_else(PoisonError::into_inner) + .into_iter() + .map(|key| json!({ "githubRepo": key.github_repo, "subpath": key.subpath })) + .collect() + } +} + +/// A control caller's answer for a branch note: `note`, the value the UI +/// gets; `branch`, the branch it landed on, as `list_branches_for_project` +/// lists one (without the commit count only that list fills in); `repo`, +/// the repo that branch tracks, as `list_project_repos` lists one; and +/// `addedRepos`. +/// +/// The transfer has committed by the time this runs. A row that cannot be +/// read back is answered as `null`: the note is where it was sent, and an +/// error here would say it is not. +pub(crate) fn branch_note_answer( + store: &Store, + note: Value, + branch_id: &str, + added: AddedRepos, +) -> Value { + let branch = store.get_branch(branch_id).unwrap_or_else(|e| { + log::warn!("Note transfer: cannot read back branch {branch_id}: {e}"); + None + }); + let repo = branch + .as_ref() + .and_then(|branch| branch.project_repo_id.as_deref()) + .and_then(|repo_id| { + store.get_project_repo(repo_id).unwrap_or_else(|e| { + log::warn!("Note transfer: cannot read back repo {repo_id}: {e}"); + None + }) + }); + let branch = branch.map(|branch| { + let workdir = store + .get_workdir_for_branch(&branch.id) + .unwrap_or_else(|e| { + log::warn!( + "Note transfer: cannot read back the workdir of branch {branch_id}: {e}" + ); + None + }); + crate::branches::to_branch_with_workdir(branch, workdir.map(|workdir| workdir.path)) + }); + json!({ + "note": note, + "branch": branch, + "repo": repo, + "addedRepos": added.into_json(), + }) +} + +/// A control caller's answer for a project note: `note`, the value the UI +/// gets, which names the project it is in now, and `addedRepos`, the repos +/// its child notes brought along. +pub(crate) fn project_note_answer(note: Value, added: AddedRepos) -> Value { + json!({ "note": note, "addedRepos": added.into_json() }) +} + +#[cfg(test)] +mod tests; diff --git a/apps/staged/src-tauri/src/note_transfer/control/tests.rs b/apps/staged/src-tauri/src/note_transfer/control/tests.rs new file mode 100644 index 000000000..68d0d67fb --- /dev/null +++ b/apps/staged/src-tauri/src/note_transfer/control/tests.rs @@ -0,0 +1,247 @@ +use serde_json::json; + +use super::*; +use crate::note_transfer::{transfer_branch_note, transfer_project_note, TransferMode}; +use crate::store::models::{Branch, Note, Project, ProjectNote, ProjectRepo}; + +/// `source` tracks `acme/widgets` at `apps/web` and `acme/gadgets`, with a +/// branch on each. `target` tracks nothing. +struct Fixture { + store: Store, + source: Project, + target: Project, + widgets: Branch, + gadgets: Branch, +} + +fn fixture() -> Fixture { + let store = Store::in_memory().unwrap(); + let source = Project::named("source"); + let target = Project::named("target"); + store.create_project(&source).unwrap(); + store.create_project(&target).unwrap(); + let branch_on = |github_repo: &str, subpath: Option<&str>, name: &str| { + let repo = ProjectRepo::new(&source.id, github_repo, name, subpath.map(str::to_owned)); + store.create_project_repo(&repo).unwrap(); + let branch = Branch::new(&source.id, name, "origin/main").with_project_repo(&repo.id); + store.create_branch(&branch).unwrap(); + branch + }; + let widgets = branch_on("acme/widgets", Some("apps/web"), "feature"); + let gadgets = branch_on("acme/gadgets", None, "feature-2"); + Fixture { + store, + source, + target, + widgets, + gadgets, + } +} + +impl Fixture { + fn note_on(&self, branch: &Branch, title: &str) -> Note { + let note = Note::new_standalone(&branch.id, title, "body"); + self.store.create_note(¬e).unwrap(); + note + } + + /// What the app's repo add leaves in `target`, minus git: the repo row + /// and a branch that tracks it. + fn attach(&self, key: RepoKey) -> Result<(), String> { + let name = format!("target-{}", key.github_repo.replace('/', "-")); + let repo = ProjectRepo::new(&self.target.id, &key.github_repo, &name, key.subpath); + self.store + .create_project_repo(&repo) + .map_err(|e| e.to_string())?; + let branch = Branch::new(&self.target.id, &name, "origin/main").with_project_repo(&repo.id); + self.store.create_branch(&branch).map_err(|e| e.to_string()) + } + + /// A branch-note transfer as the dispatch arm runs it: the repo add + /// watched, then the control answer. + async fn transfer(&self, note: &Note, mode: TransferMode) -> Result<Value, String> { + let added = AddedRepos::default(); + let landed = transfer_branch_note(&self.store, ¬e.id, &self.target.id, mode, |key| { + added.watch(key.clone(), std::future::ready(self.attach(key))) + }) + .await?; + let item = json!({ "id": landed.id, "title": landed.title }); + Ok(branch_note_answer( + &self.store, + item, + &landed.branch_id, + added, + )) + } +} + +fn widgets_key() -> Value { + json!({ "githubRepo": "acme/widgets", "subpath": "apps/web" }) +} + +#[tokio::test] +async fn a_move_that_adds_the_repo_names_it_and_where_the_note_landed() { + let f = fixture(); + let note = f.note_on(&f.widgets, "Findings"); + + let answer = f.transfer(¬e, TransferMode::Move).await.unwrap(); + + assert_eq!(answer["addedRepos"], json!([widgets_key()])); + assert_eq!(answer["note"]["id"], note.id, "a move keeps the note's id"); + assert_eq!(answer["branch"]["projectId"], f.target.id); + assert_eq!(answer["branch"]["branchName"], "target-acme-widgets"); + assert_eq!(answer["repo"]["githubRepo"], "acme/widgets"); + assert_eq!(answer["repo"]["subpath"], "apps/web"); + assert_eq!( + answer["branch"]["projectRepoId"], answer["repo"]["id"], + "the repo is the one the landing branch tracks" + ); + assert_eq!( + answer["branch"].get("worktreePath"), + Some(&Value::Null), + "the branch reads as the branch list gives one, worktree included" + ); +} + +#[tokio::test] +async fn a_transfer_into_a_project_that_tracks_the_repo_adds_nothing() { + let f = fixture(); + let note = f.note_on(&f.widgets, "Findings"); + f.attach(RepoKey { + github_repo: "acme/widgets".into(), + subpath: Some("apps/web".into()), + }) + .unwrap(); + + for mode in [TransferMode::Copy, TransferMode::Move] { + let answer = f.transfer(¬e, mode).await.unwrap(); + assert_eq!(answer["addedRepos"], json!([]), "{mode:?}"); + assert_eq!(answer["branch"]["projectId"], f.target.id, "{mode:?}"); + assert_eq!(answer["repo"]["githubRepo"], "acme/widgets", "{mode:?}"); + } +} + +#[tokio::test] +async fn a_copy_answers_with_the_new_note_and_leaves_the_original() { + let f = fixture(); + let note = f.note_on(&f.widgets, "Findings"); + + let answer = f.transfer(¬e, TransferMode::Copy).await.unwrap(); + + let copy_id = answer["note"]["id"].as_str().unwrap(); + assert_ne!(copy_id, note.id, "a copy is a new note"); + assert_eq!(answer["addedRepos"], json!([widgets_key()])); + assert_eq!( + f.store.get_note(¬e.id).unwrap().unwrap().branch_id, + f.widgets.id + ); + assert_eq!( + f.store.get_note(copy_id).unwrap().unwrap().branch_id, + answer["branch"]["id"].as_str().unwrap() + ); +} + +#[tokio::test] +async fn a_repo_whose_add_failed_is_not_reported_as_added() { + let f = fixture(); + let note = f.note_on(&f.widgets, "Findings"); + let added = AddedRepos::default(); + + let err = transfer_branch_note( + &f.store, + ¬e.id, + &f.target.id, + TransferMode::Move, + |key| added.watch(key, std::future::ready(Err("clone failed".to_string()))), + ) + .await + .unwrap_err(); + + assert_eq!( + err, + "Could not add acme/widgets at apps/web to target: clone failed" + ); + assert_eq!(added.into_json(), json!([])); +} + +/// A moved project note brings its children, and each child's repo is added +/// where the destination lacks it: the answer lists those, in the order the +/// transfer added them, and not a repo the destination already had. +#[tokio::test] +async fn a_project_note_move_lists_the_repos_its_children_brought() { + let f = fixture(); + let parent = ProjectNote::new(&f.source.id, "Plan", "body"); + f.store.create_project_note(&parent).unwrap(); + for (branch, title) in [(&f.widgets, "Web"), (&f.gadgets, "Gadgets")] { + let child = + Note::new_standalone(&branch.id, title, "body").with_parent_project_note(&parent.id); + f.store.create_note(&child).unwrap(); + } + f.attach(RepoKey { + github_repo: "acme/widgets".into(), + subpath: Some("apps/web".into()), + }) + .unwrap(); + + let added = AddedRepos::default(); + let moved = transfer_project_note( + &f.store, + &parent.id, + &f.target.id, + TransferMode::Move, + |key| added.watch(key.clone(), std::future::ready(f.attach(key))), + ) + .await + .unwrap(); + let answer = project_note_answer(serde_json::to_value(&moved).unwrap(), added); + + assert_eq!(answer["note"]["id"], parent.id); + assert_eq!(answer["note"]["projectId"], f.target.id); + assert_eq!( + answer["addedRepos"], + json!([{ "githubRepo": "acme/gadgets", "subpath": null }]) + ); +} + +#[tokio::test] +async fn a_project_note_copy_adds_no_repo() { + let f = fixture(); + let parent = ProjectNote::new(&f.source.id, "Plan", "body"); + f.store.create_project_note(&parent).unwrap(); + let child = + Note::new_standalone(&f.widgets.id, "Web", "body").with_parent_project_note(&parent.id); + f.store.create_note(&child).unwrap(); + + let added = AddedRepos::default(); + let copy = transfer_project_note( + &f.store, + &parent.id, + &f.target.id, + TransferMode::Copy, + |key| added.watch(key.clone(), std::future::ready(f.attach(key))), + ) + .await + .unwrap(); + let answer = project_note_answer(serde_json::to_value(©).unwrap(), added); + + assert_ne!(answer["note"]["id"], parent.id); + assert_eq!(answer["note"]["projectId"], f.target.id); + assert_eq!(answer["addedRepos"], json!([])); +} + +/// The transfer has committed before the answer is worded, so a landing row +/// that cannot be read back is left out of the answer. It is not an error. +#[test] +fn a_landing_branch_that_cannot_be_read_back_is_answered_as_null() { + let f = fixture(); + let answer = branch_note_answer( + &f.store, + json!({ "id": "n1" }), + "no-such-branch", + AddedRepos::default(), + ); + assert_eq!( + answer, + json!({ "note": { "id": "n1" }, "branch": null, "repo": null, "addedRepos": [] }) + ); +} diff --git a/apps/staged/src-tauri/src/web_server.rs b/apps/staged/src-tauri/src/web_server.rs index 1b7ff8128..d6673bd00 100644 --- a/apps/staged/src-tauri/src/web_server.rs +++ b/apps/staged/src-tauri/src/web_server.rs @@ -3246,21 +3246,26 @@ pub(crate) async fn dispatch( } else { crate::note_transfer::TransferMode::Copy }; + let added = crate::note_transfer::control::AddedRepos::default(); let note = crate::note_transfer::transfer_branch_note( &store, ¬e_id, &target_project_id, mode, |key| { - crate::note_transfer::add_repo_to_project( - app_handle.clone(), - Arc::clone(&store), - target_project_id.clone(), - key, + added.watch( + key.clone(), + crate::note_transfer::add_repo_to_project( + app_handle.clone(), + Arc::clone(&store), + target_project_id.clone(), + key, + ), ) }, ) .await?; + let branch_id = note.branch_id.clone(); let item = match mode { crate::note_transfer::TransferMode::Move => { crate::note_commands::note_to_timeline_item(&store, note) @@ -3269,7 +3274,16 @@ pub(crate) async fn dispatch( crate::note_commands::standalone_note_to_timeline_item(note) } }; - Ok(serde_json::to_value(item).unwrap()) + let item = serde_json::to_value(item).unwrap(); + Ok(match &caller { + // A window has the note open and knows where it sent it. A + // control caller is told: the branch the note landed on and + // the repos the transfer added. + DispatchCaller::Control(_) => crate::note_transfer::control::branch_note_answer( + &store, item, &branch_id, added, + ), + DispatchCaller::Web => item, + }) } "move_project_note_to_project" | "copy_project_note_to_project" => { let store = get_store(store_mutex)?; @@ -3280,22 +3294,34 @@ pub(crate) async fn dispatch( } else { crate::note_transfer::TransferMode::Copy }; + let added = crate::note_transfer::control::AddedRepos::default(); let note = crate::note_transfer::transfer_project_note( &store, &project_note_id, &target_project_id, mode, |key| { - crate::note_transfer::add_repo_to_project( - app_handle.clone(), - Arc::clone(&store), - target_project_id.clone(), - key, + added.watch( + key.clone(), + crate::note_transfer::add_repo_to_project( + app_handle.clone(), + Arc::clone(&store), + target_project_id.clone(), + key, + ), ) }, ) .await?; - Ok(serde_json::to_value(note).unwrap()) + let note = serde_json::to_value(note).unwrap(); + Ok(match &caller { + // As for a branch note: a control caller is told which repos + // the note's children brought along. + DispatchCaller::Control(_) => { + crate::note_transfer::control::project_note_answer(note, added) + } + DispatchCaller::Web => note, + }) } // ===================================================================== @@ -5417,6 +5443,95 @@ mod tests { } } + /// A note moved or copied through the control server goes through the + /// transfer the app's windows run: one call, with the app's own + /// repo-adding step, whoever asks. The caller decides nothing until the + /// transfer has returned, and then only how much the answer says: a + /// control caller is told where the note landed and which repos were + /// added, a window gets the note alone, as it always has. + #[test] + fn note_transfers_run_the_one_transfer_whoever_asks() { + let source = include_str!("web_server.rs"); + let desktop = include_str!("note_transfer.rs"); + for (command, transfer, answer, web) in [ + ( + "move_note_to_project", + "transfer_branch_note(", + "note_transfer::control::branch_note_answer(", + "DispatchCaller::Web => item,", + ), + ( + "copy_note_to_project", + "transfer_branch_note(", + "note_transfer::control::branch_note_answer(", + "DispatchCaller::Web => item,", + ), + ( + "move_project_note_to_project", + "transfer_project_note(", + "note_transfer::control::project_note_answer(", + "DispatchCaller::Web => note,", + ), + ( + "copy_project_note_to_project", + "transfer_project_note(", + "note_transfer::control::project_note_answer(", + "DispatchCaller::Web => note,", + ), + ] { + let (_, arm) = dispatch_arms(source) + .into_iter() + .find(|(patterns, _)| patterns.iter().any(|p| p == command)) + .unwrap_or_else(|| panic!("dispatch should have a `{command}` arm")); + assert_eq!( + arm.matches(&format!("note_transfer::{transfer}")).count(), + 1, + "the `{command}` arm must run the transfer once, for every caller: {arm}" + ); + // The repo is added by the app's own step. The arm watches it + // and does not stand in for it. + assert!( + arm.contains("added.watch(") + && arm.contains("crate::note_transfer::add_repo_to_project("), + "the `{command}` arm must add a repo through the shared step: {arm}" + ); + // Nothing about the caller comes before the transfer. + let transfer_at = arm.find(transfer).unwrap(); + let caller_at = arm + .find("caller") + .unwrap_or_else(|| panic!("the `{command}` arm should answer by caller: {arm}")); + assert!( + transfer_at < caller_at, + "the `{command}` arm must not branch on its caller before the transfer: {arm}" + ); + let answers = &arm[caller_at..]; + assert!( + answers.contains("DispatchCaller::Control(_) =>") && answers.contains(answer), + "a control `{command}` must be answered through `{answer}`: {arm}" + ); + assert!( + answers.contains(web), + "a web `{command}` must be answered with the note alone: {arm}" + ); + + // The desktop command is the same transfer with the same step. + let marker = format!("pub async fn {command}("); + let start = desktop + .find(&marker) + .unwrap_or_else(|| panic!("note_transfer.rs should define `{command}`")); + let rest = &desktop[start..]; + let end = rest[1..] + .find("#[tauri::command") + .or_else(|| rest.find("#[cfg(test)]")) + .unwrap_or(rest.len()); + assert!( + rest[..end].contains(transfer), + "the `{command}` Tauri command must call `{transfer}`: {}", + &rest[..end] + ); + } + } + /// The web editor saves through the same body as the desktop one, so the /// two can't drift apart; in particular, neither collects the media an /// edit removed (see `note_commands::update_note_impl`). diff --git a/apps/staged/src-tauri/src/web_server/control_scope.rs b/apps/staged/src-tauri/src/web_server/control_scope.rs index e3e023bb4..d3ca5239b 100644 --- a/apps/staged/src-tauri/src/web_server/control_scope.rs +++ b/apps/staged/src-tauri/src/web_server/control_scope.rs @@ -4,15 +4,15 @@ //! A `DispatchCaller::Control(grant)` carries the project its credential is //! scoped to and whether it may write. Every allowlisted control command //! has a row in [`CONTROL_SCOPE`] saying how to find the project a call -//! addresses — a `projectId` argument, a branch id, a session id, or the -//! `create_image` pair — and whether the command changes the app. The check -//! runs before any arm, so a confined credential cannot read or touch the -//! rows of a project outside its reach however it spells the request, and a -//! read-only credential never reaches a writing arm. The two commands that -//! take no identifier (`list_projects`, `get_active_sessions`) are filtered -//! inside their arms instead, through [`reach`]. `create_project` addresses -//! no project either, since the project does not exist yet. It has its own -//! rule, below. +//! addresses — a `projectId` argument, a branch id, a session id, the +//! `create_image` pair, or a note and the project it is sent to — and +//! whether the command changes the app. The check runs before any arm, so a +//! confined credential cannot read or touch the rows of a project outside +//! its reach however it spells the request, and a read-only credential +//! never reaches a writing arm. The two commands that take no identifier +//! (`list_projects`, `get_active_sessions`) are filtered inside their arms +//! instead, through [`reach`]. `create_project` addresses no project either, +//! since the project does not exist yet. It has its own rule, below. //! //! # Reach //! @@ -61,6 +61,23 @@ //! request (`assignProjectId`), which is what the tag picker's "Create tag" //! row does. The two deletes are not allowlisted at all. //! +//! # Moving and copying notes +//! +//! The four note transfers (`move_note_to_project`, `copy_note_to_project` +//! and their project-note twins) address two projects: the one the note is +//! in, found through the note, and the `targetProjectId` it is sent to. Both +//! must be within reach. A credential that reached only the source could +//! push a note, its session and its repo into a project it was never given; +//! one that reached only the destination could pull a note out of a project +//! it cannot read. A copy into the note's own project names one project +//! twice and needs no more than that one. +//! +//! Nothing else a transfer touches lies outside those two. A moved project +//! note takes its child notes along, and the transfer refuses a child whose +//! branch is in another project. The repo it adds to the destination is one +//! the source already tracks, which `add_project_repo` would let the same +//! credential attach. +//! //! # Table shape //! //! `open_project` is the one command decided by who holds the grant as well @@ -117,6 +134,13 @@ pub(crate) enum ScopeKey { /// credential is refused, so an agent cannot pull the user's window to /// its project. OpenProject, + /// A branch note's `noteId` and the `targetProjectId` it moves or copies + /// to: the note's project, through its branch, and the destination. Both + /// must be within reach. + NoteTransfer, + /// [`ScopeKey::NoteTransfer`] for a project note: `projectNoteId`, whose + /// row names its project, and `targetProjectId`. + ProjectNoteTransfer, } /// One row per allowlisted control command: how to resolve its project, @@ -190,6 +214,26 @@ pub(crate) const CONTROL_SCOPE: &[(&str, ScopeKey, Access)] = &[ ScopeKey::Unconfined, Access::ReadWrite, ), + ( + "move_note_to_project", + ScopeKey::NoteTransfer, + Access::ReadWrite, + ), + ( + "copy_note_to_project", + ScopeKey::NoteTransfer, + Access::ReadWrite, + ), + ( + "move_project_note_to_project", + ScopeKey::ProjectNoteTransfer, + Access::ReadWrite, + ), + ( + "copy_project_note_to_project", + ScopeKey::ProjectNoteTransfer, + Access::ReadWrite, + ), ]; /// The projects a caller's results are confined to. @@ -365,6 +409,26 @@ pub(crate) fn check_with_store( let project_id: String = arg(args, "projectId")?; require_in_scope(store, grant, &project_id, "project") } + ScopeKey::NoteTransfer => { + let note_id: String = arg(args, "noteId")?; + let target_project_id: String = arg(args, "targetProjectId")?; + if scope.is_some() { + let project_id = note_project(store, ¬e_id)?; + require_in_scope(store, grant, &project_id, "note")?; + require_destination_in_scope(store, grant, &target_project_id)?; + } + Ok(()) + } + ScopeKey::ProjectNoteTransfer => { + let note_id: String = arg(args, "projectNoteId")?; + let target_project_id: String = arg(args, "targetProjectId")?; + if scope.is_some() { + let project_id = project_note_project(store, ¬e_id)?; + require_in_scope(store, grant, &project_id, "project note")?; + require_destination_in_scope(store, grant, &target_project_id)?; + } + Ok(()) + } } } @@ -398,6 +462,27 @@ fn require_in_scope( ))) } +/// [`require_in_scope`] for the project a note transfer is sent to, which +/// the caller named itself. A destination that does not exist is refused the +/// same way, so a confined caller learns nothing about projects it cannot +/// reach. +fn require_destination_in_scope( + store: &Store, + grant: &ControlGrant, + target_project_id: &str, +) -> Result<(), String> { + let Some(allowed) = grant.project_scope() else { + return Ok(()); + }; + if within_reach(store, grant, allowed, target_project_id)? { + return Ok(()); + } + Err(denied(format!( + "the destination is a project outside this credential's reach; {}", + covers(allowed) + ))) +} + /// Whether a grant confined to `allowed` reaches `project_id`: it is that /// project, or one whose `created_by` is the grant's actor. The read is one /// row, and only for a project other than the grant's own. A project that @@ -453,6 +538,24 @@ fn branch_project(store: &Store, branch_id: &str) -> Result<String, String> { .ok_or_else(|| denied(format!("branch {branch_id} not found"))) } +/// A branch note's project: its branch's. +fn note_project(store: &Store, note_id: &str) -> Result<String, String> { + let note = store + .get_note(note_id) + .map_err(|e| e.to_string())? + .ok_or_else(|| denied(format!("note {note_id} not found")))?; + branch_project(store, ¬e.branch_id) +} + +/// A project note's project, which its row names. +fn project_note_project(store: &Store, note_id: &str) -> Result<String, String> { + store + .get_project_note(note_id) + .map_err(|e| e.to_string())? + .map(|note| note.project_id) + .ok_or_else(|| denied(format!("project note {note_id} not found"))) +} + /// A session's project: its project note's or its branch's, else — for a /// diagram child, which has neither — its parent session's, one level up. fn session_project(store: &Store, session_id: &str) -> Result<String, String> { @@ -483,7 +586,7 @@ fn session_project(store: &Store, session_id: &str) -> Result<String, String> { mod tests { use super::*; use crate::control_server::Scope; - use crate::store::{Branch, Image, Project, Session}; + use crate::store::{Branch, Image, Note, Project, ProjectNote, Session}; use serde_json::json; /// Two projects, a branch, a branch session, a diagram child of that @@ -1686,6 +1789,10 @@ mod tests { ), ]; writes.extend(catalog_writes()); + writes + .extend(note_transfers().map(|(cmd, id_arg)| { + (cmd, json!({ id_arg: "n", "targetProjectId": f.project_a })) + })); for (cmd, args) in &writes { assert_denied(check_with_store(cmd, args, &g, &f.store), "read-only"); } @@ -1760,6 +1867,250 @@ mod tests { .unwrap(); } + // ------------------------------------------------------------------- + // Note transfers + // ------------------------------------------------------------------- + + /// The four transfers, each with the argument that names its note. + fn note_transfers() -> [(&'static str, &'static str); 4] { + [ + ("move_note_to_project", "noteId"), + ("copy_note_to_project", "noteId"), + ("move_project_note_to_project", "projectNoteId"), + ("copy_project_note_to_project", "projectNoteId"), + ] + } + + /// A branch note and a project note in each of the fixture's projects. + struct Notes { + branch_a: String, + branch_b: String, + project_a: String, + project_b: String, + } + + impl Notes { + fn in_fixture(f: &Fixture) -> Self { + let branch_note = |branch_id: &str| { + let note = Note::new_standalone(branch_id, "Findings", "body"); + f.store.create_note(¬e).unwrap(); + note.id + }; + let project_note = |project_id: &str| { + let note = ProjectNote::new(project_id, "Plan", "body"); + f.store.create_project_note(¬e).unwrap(); + note.id + }; + Self { + branch_a: branch_note(&f.branch_a), + branch_b: branch_note(&f.branch_b), + project_a: project_note(&f.project_a), + project_b: project_note(&f.project_b), + } + } + + /// The note of `cmd`'s kind in project A, then the one in B. + fn of(&self, id_arg: &str) -> (&str, &str) { + match id_arg { + "noteId" => (&self.branch_a, &self.branch_b), + _ => (&self.project_a, &self.project_b), + } + } + } + + fn transfer(id_arg: &str, note_id: &str, target_project_id: &str) -> serde_json::Value { + json!({ id_arg: note_id, "targetProjectId": target_project_id }) + } + + #[test] + fn note_transfers_pass_between_the_own_project_and_a_created_one() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + let created = create_project_by(&f, "gamma", CALLER); + let created_branch_note = Note::new_standalone(&created.branch, "Created", "body"); + f.store.create_note(&created_branch_note).unwrap(); + let created_project_note = ProjectNote::new(&created.project, "Created plan", "body"); + f.store.create_project_note(&created_project_note).unwrap(); + let g = scoped(&f.project_a); + for (cmd, id_arg) in note_transfers() { + let (own, _) = notes.of(id_arg); + let from_created = match id_arg { + "noteId" => &created_branch_note.id, + _ => &created_project_note.id, + }; + for (note_id, target) in [ + (own, created.project.as_str()), + (from_created.as_str(), f.project_a.as_str()), + // The note's own project: a duplicate for a copy, and the + // transfer's own "already in" refusal for a move. + (own, f.project_a.as_str()), + ] { + check_with_store(cmd, &transfer(id_arg, note_id, target), &g, &f.store) + .unwrap_or_else(|e| panic!("{cmd} {note_id} -> {target}: {e}")); + } + } + } + + #[test] + fn note_transfers_are_refused_when_the_note_is_in_a_project_out_of_reach() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + let created = create_project_by(&f, "gamma", CALLER); + let g = scoped(&f.project_a); + for (cmd, id_arg) in note_transfers() { + let (_, foreign) = notes.of(id_arg); + // Into the caller's own project, into one it created, and back + // into the note's own: wherever it would land, the note is not + // the caller's to take or to copy. + for target in [&f.project_a, &created.project, &f.project_b] { + assert_denied( + check_with_store(cmd, &transfer(id_arg, foreign, target), &g, &f.store), + "belongs to another project", + ); + } + assert_denied( + check_with_store(cmd, &transfer(id_arg, "nope", &f.project_a), &g, &f.store), + "not found", + ); + } + } + + #[test] + fn note_transfers_are_refused_when_the_destination_is_out_of_reach() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + // A project another session created is no nearer than one the user + // made. + let theirs = create_project_by(&f, "delta", "session:other"); + let g = scoped(&f.project_a); + for (cmd, id_arg) in note_transfers() { + let (own, _) = notes.of(id_arg); + for target in [f.project_b.as_str(), theirs.project.as_str(), "nope"] { + assert_denied( + check_with_store(cmd, &transfer(id_arg, own, target), &g, &f.store), + "the destination is a project outside this credential's reach", + ); + } + } + } + + /// Reach is the actor's: another session reaches neither this one's + /// project nor what it created, as source or as destination. + #[test] + fn note_transfers_follow_the_callers_own_reach() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + let created = create_project_by(&f, "gamma", CALLER); + let other = session_grant("other", 1, &f.project_b); + for (cmd, id_arg) in note_transfers() { + let (in_a, in_b) = notes.of(id_arg); + assert_denied( + check_with_store(cmd, &transfer(id_arg, in_a, &f.project_b), &other, &f.store), + "belongs to another project", + ); + assert_denied( + check_with_store( + cmd, + &transfer(id_arg, in_b, &created.project), + &other, + &f.store, + ), + "the destination is a project outside this credential's reach", + ); + // A connected app approved for one project is confined the same + // way. + let app = app_grant("grant-1", &f.project_a); + assert_denied( + check_with_store(cmd, &transfer(id_arg, in_a, &f.project_b), &app, &f.store), + "the destination is a project outside this credential's reach", + ); + } + } + + #[test] + fn note_transfers_by_an_unconfined_grant_skip_the_lookups() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + let g = ControlGrant::test_all_projects(); + for (cmd, id_arg) in note_transfers() { + let (in_a, in_b) = notes.of(id_arg); + for (note_id, target) in [ + (in_a, f.project_b.as_str()), + (in_b, f.project_a.as_str()), + // Unknown ids are the transfer's to report. + ("nope", f.project_a.as_str()), + (in_a, "nope"), + ] { + check_with_store(cmd, &transfer(id_arg, note_id, target), &g, &f.store) + .unwrap_or_else(|e| panic!("{cmd} {note_id} -> {target}: {e}")); + } + } + } + + /// Both arguments are read before anything is looked up, for every + /// grant, so a request that names no destination never reaches the arm. + #[test] + fn note_transfers_need_both_arguments() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + for g in [scoped(&f.project_a), ControlGrant::test_all_projects()] { + for (cmd, id_arg) in note_transfers() { + let (own, _) = notes.of(id_arg); + let err = check_with_store(cmd, &json!({ id_arg: own }), &g, &f.store).unwrap_err(); + assert!( + err.contains("missing argument: targetProjectId"), + "{cmd}: {err}" + ); + let err = check_with_store( + cmd, + &json!({ "targetProjectId": f.project_a }), + &g, + &f.store, + ) + .unwrap_err(); + assert!( + err.contains(&format!("missing argument: {id_arg}")), + "{cmd}: {err}" + ); + } + } + } + + /// A branch note is found through `noteId` only and a project note + /// through `projectNoteId` only: the two live in different tables, and a + /// request that names the other kind's id must not be let through on it. + #[test] + fn note_transfers_look_the_note_up_in_its_own_table() { + let f = fixture(); + let notes = Notes::in_fixture(&f); + let g = scoped(&f.project_a); + for cmd in ["move_note_to_project", "copy_note_to_project"] { + assert_denied( + check_with_store( + cmd, + &transfer("noteId", ¬es.project_a, &f.project_a), + &g, + &f.store, + ), + "not found", + ); + } + for cmd in [ + "move_project_note_to_project", + "copy_project_note_to_project", + ] { + assert_denied( + check_with_store( + cmd, + &transfer("projectNoteId", ¬es.branch_a, &f.project_a), + &g, + &f.store, + ), + "not found", + ); + } + } + #[test] fn a_command_without_a_scope_row_is_refused() { let f = fixture(); From 9e63668f73bcefb0291211463011649bedec22f6 Mon Sep 17 00:00:00 2001 From: Matt Toohey <contact@matttoohey.com> Date: Thu, 19 Nov 2026 12:10:10 +1100 Subject: [PATCH 2/4] fix(staged): confine stagedctl note transfers' media and report what moved MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review 1164ab6a of a928bcaf found that `stagedctl note move` and `stagedctl note copy` let embedded media escape the scope rule, and that their answers and help left gaps. This addresses its findings. The transfer itself, the Tauri commands and what a window is answered are unchanged. Embedded media. A note's body embeds stored images and videos by id, and the transfer puts each one in the destination whichever project its row is in. A confined caller that knew an id could have a note of its own embed it and copy the file into a project it reaches. The scope check now refuses a transfer (exit 4, `scope_denied`) whose note body embeds media from a project outside the credential's reach, the way `require_images_in_scope` refuses an attached `imageIds` entry. A project-note move is held to the same for each child note, since the children travel with it. A copy leaves them behind and is not. A reference with no row carries nothing and passes. Unconfined grants and the app's windows are not checked. The bodies are read when the request arrives. A transfer that adds a repo reads them again afterwards, so a body saved during the add is not re-checked; closing that needs a check inside the transfer, which this commit does not touch. The module docs say so. Session status of a moved project note. The row the move's transaction returns resolves no session, so the control answer said `sessionStatus: null` for a note whose session had completed. `project_note_answer` now reads the note again with `get_project_note_with_status`, and falls back to the transfer's value if that read fails. Children of a moved project note. The control answer gains `children`, one `{ reference, title, branch, repo }` per child note that came along: its `#note:<id>` reference and the branch and repo it is on now, read back as a branch note's are. A copy answers an empty list. The CLI prints a `child note …` line for each and passes the list through under `--json`. This extends a backend answer type, which AGENTS.md asks a human to review before it lands. Failure after a repo was added. A branch-note transfer that failed once its repo was in the destination returned an error that did not mention the repo. For a control caller the error now ends with the sentence a project-note failure already has: "<repo> was added to <project> along the way and remains tracked there." A window's error is as it was. The help no longer sends the caller to `stagedctl project get`. Exit 4 for a note that is not there. Under a confined credential, an id that names no note of its kind (unknown, or the other kind's) exits 4 with "not found", where an unconfined one gets the transfer's exit 1. The behaviour stays. Both verbs' help and the guide now say it, list the media refusal beside it, and the help pins are refreshed. One reach helper. `require_in_scope` now takes the refusal's wording and holds the reach test itself. `require_destination_in_scope` and `within_reach` are gone, and the image check goes through it too. Tests. `dispatch` takes the app's own handle, which no test can build, so the bodies of the four arms move to `web_server::note_transfer_arms` and take the repo-adding step as a parameter. `dispatch` passes `add_repo_to_project`. The new tests run the scope check and then those bodies as a control caller, over real transfers, and assert the JSON answered: the exact keys of each answer and of the note item, the session status of a moved branch note and project note, the children and their landing rows, a copy's standalone note, and a window's note-alone answer. They cover a failure after a repo was added for both kinds and both callers, a failed add, a missing and a wrong-kind id for confined and unconfined grants, and media from a third project in a note, in a child note and on a copy into the note's own project. The scope tests add the same media cases at the check, with media in reach and a reference with no row passing. The source pin on the arms is narrowed to what cannot be run, and its slice no longer stops one byte early. The CLI tests cover the children lines, unreadable landing rows, and pin the answer's key names to the app's source. Signed-off-by: Matt Toohey <contact@matttoohey.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src-tauri/crates/stagedctl/src/cli.rs | 47 +- .../src-tauri/crates/stagedctl/src/notes.rs | 72 +- .../crates/stagedctl/src/notes/tests.rs | 188 ++++- .../crates/stagedctl/tests/fixtures/help.txt | 47 +- .../src-tauri/resources/stagedctl/guide.md | 24 +- apps/staged/src-tauri/src/control_server.rs | 3 +- .../src-tauri/src/note_transfer/control.rs | 119 ++- .../src/note_transfer/control/tests.rs | 99 ++- apps/staged/src-tauri/src/web_server.rs | 183 ++--- .../src-tauri/src/web_server/control_scope.rs | 386 +++++++--- .../src/web_server/note_transfer_arms.rs | 118 +++ .../web_server/note_transfer_arms/tests.rs | 702 ++++++++++++++++++ 12 files changed, 1706 insertions(+), 282 deletions(-) create mode 100644 apps/staged/src-tauri/src/web_server/note_transfer_arms.rs create mode 100644 apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs diff --git a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs index a2460ed39..3afa3c0f2 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs @@ -1046,7 +1046,8 @@ on its kind: media, and takes its child notes along. Each child lands, with its own session, on the destination's branch for its repo and subpath, still linked to the - project note. + project note. The output lists each child by its + reference, with the repo and branch it landed on. Commits and code reviews are not part of a note. They stay on the branch they were made on. @@ -1056,8 +1057,8 @@ the way `stagedctl project add-repo` adds one without --branch: a new branch named after the project, set up in the background (a worktree, or a clone into a remote project's workspace). The output names each repo added this way. Such a repo stays in the project when a later step -of the move fails. A project note's error names it; a branch note's -does not, so look at `stagedctl project get`. +of the move fails, and the error then names it: \"<repo> was added to +<project> along the way and remains tracked there.\" The app refuses a move, with the note left where it was (exit 1, `app_error`, the app's own message), when: @@ -1070,9 +1071,20 @@ The app refuses a move, with the note left where it was (exit 1, outside the project note's own project. Needs write access to both projects, the one the note is in and the -destination. A read-only credential is refused (exit 4, `scope_denied`), -and so is a note in a project the credential does not reach. A -destination it does not reach is not among its projects and exits 1 +destination. A read-only credential is refused (exit 4, `scope_denied`). +A credential confined to some projects, which a session's is, also +exits 4 (`scope_denied`) for: + - a note in a project it does not reach; + - a <NOTE> that names no note of that kind: an id that does not + exist, or a project note's id written as #note:<id>, or the other + way round. So exit 4 can mean a mistyped reference and not a + missing permission; the message then says \"not found\". A + credential for every project gets the app's own error for it + (exit 1, `app_error`); + - a note whose body embeds an image or video from a project it does + not reach, or a project note with such a child note. The move would + carry that media into the destination. +A destination it does not reach is not among its projects and exits 1 (`not_found`). A session may move notes between its own project and the projects it created, in either direction, and nowhere else. @@ -1112,9 +1124,10 @@ videos in the body, and nothing else: A copy of a branch note lands on the destination's branch for the repo and subpath the note's branch tracks. A destination that does not track that repo gets it first, as in `stagedctl note move`, and the output -names it. A title another note on the landing branch has gets a number: -\"<title> (2)\". A copy of a project note lands in the destination -project and never adds a repo. +names it. The repo stays in the project when the copy then fails, and +the error names it. A title another note on the landing branch has gets +a number: \"<title> (2)\". A copy of a project note lands in the +destination project and never adds a repo. --to may be the project the note is already in. That duplicates the note beside the original, on the same branch for a branch note. @@ -1126,10 +1139,18 @@ and is running again can be copied, where it could not be moved: the copy is the note as it reads now. Needs write access to both projects, the one the note is in and the -destination, as `stagedctl note move` does: exit 4 (`scope_denied`) -under a read-only credential or for a note in a project the credential -does not reach, exit 1 (`not_found`) for a destination it does not -reach. +destination, as `stagedctl note move` does. A read-only credential is +refused (exit 4, `scope_denied`). A credential confined to some +projects, which a session's is, also exits 4 (`scope_denied`) for: + - a note in a project it does not reach; + - a <NOTE> that names no note of that kind: an id that does not + exist, or the other kind's id. The message then says \"not found\", + and a credential for every project gets exit 1 (`app_error`); + - a note whose body embeds an image or video from a project it does + not reach. The copy would duplicate that media in the destination. + A project note's child notes are not copied, so theirs do not + count. +A destination it does not reach exits 1 (`not_found`). A copy shows at once in the destination, where the user can delete it. stagedctl has no delete.")] diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs index 4169317f6..e9cbcb900 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs @@ -10,9 +10,10 @@ //! names, answered from a read the caller can make anyway. //! //! Each verb is one write with no read after it. The app's answer carries -//! the branch the note landed on and the repos the transfer added, which -//! only the transfer knows. An answer that cannot be read is a -//! [`CtlError::Partial`], so the caller still learns the write landed. +//! the branch the note landed on, the child notes a moved project note +//! took along, and the repos the transfer added, which only the transfer +//! knows. An answer that cannot be read is a [`CtlError::Partial`], so the +//! caller still learns the write landed. use serde::Deserialize; use serde_json::{json, Map, Value}; @@ -158,7 +159,8 @@ impl NoteRef { /// transfer and the repos the transfer added to the destination. For a /// branch note, also the branch it landed on and the repo that branch /// tracks. Either is `null` when the app could not read the row back after -/// the transfer committed. +/// the transfer committed. For a project note, also the child notes that +/// came with it, which is none for a copy. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct Landed { @@ -168,9 +170,26 @@ struct Landed { #[serde(default)] repo: Option<RepoName>, #[serde(default)] + children: Vec<LandedChild>, + #[serde(default)] added_repos: Vec<RepoName>, } +/// A child note that moved with its project note: its hashtag reference, +/// which the move does not change, and where it is now, as for a branch +/// note. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LandedChild { + reference: String, + #[serde(default)] + title: String, + #[serde(default)] + branch: Option<BranchRow>, + #[serde(default)] + repo: Option<RepoName>, +} + #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct LandedNote { @@ -257,11 +276,13 @@ pub(crate) fn transfer_with( } /// The output of both verbs: the note's reference, the project it is in -/// now, the branch it landed on, and each repo the transfer added. `--json` -/// is `{ ok, mode, projectId, reference, note, addedRepos }` with the app's -/// rows, and for a branch note `branch` and `repo` as well. `reference` is -/// the hashtag reference of the note where it is now: the same note after a -/// move, the new one after a copy. +/// now, the branch it landed on, each child note that came with a project +/// note and the branch that landed on, and each repo the transfer added. +/// `--json` is `{ ok, mode, projectId, reference, note, addedRepos }` with +/// the app's rows. A branch note has `branch` and `repo` as well. A project +/// note has `children`, each `{ reference, title, branch, repo }`. +/// `reference` is the hashtag reference of the note where it is now: the +/// same note after a move, the new one after a copy. fn render( transfer: Transfer, note: &NoteRef, @@ -288,13 +309,19 @@ fn render( human.push(format!(" title: {}", landed.note.title)); } let address = landed.repo.as_ref().map(RepoName::address); - match (&landed.branch, &address) { - (Some(branch), Some(address)) => human.push(format!( - " landed on: {address}, branch {}", - branch.branch_name - )), - (Some(branch), None) => human.push(format!(" landed on: branch {}", branch.branch_name)), - (None, _) => {} + if let Some(place) = landing(landed.branch.as_ref(), address.as_deref()) { + human.push(format!(" landed on: {place}")); + } + for child in &landed.children { + let mut line = format!(" child note {}", child.reference); + if !child.title.trim().is_empty() { + line.push_str(&format!(" {:?}", child.title)); + } + let address = child.repo.as_ref().map(RepoName::address); + if let Some(place) = landing(child.branch.as_ref(), address.as_deref()) { + line.push_str(&format!(" landed on: {place}")); + } + human.push(line); } for repo in &landed.added_repos { human.push(format!( @@ -319,7 +346,7 @@ fn render( "reference".into(), json!(note.reference_to(&landed.note.id)), ); - for key in ["note", "branch", "repo", "addedRepos"] { + for key in ["note", "branch", "repo", "children", "addedRepos"] { if let Some(value) = answer.get(key) { json.insert(key.into(), value.clone()); } @@ -330,5 +357,16 @@ fn render( } } +/// Where a note is, as the output says it: the repo's address and the +/// branch, or the branch alone when the app could not read the repo back. +/// `None` when it could not read the branch. +fn landing(branch: Option<&BranchRow>, address: Option<&str>) -> Option<String> { + let branch = branch?; + Some(match address { + Some(address) => format!("{address}, branch {}", branch.branch_name), + None => format!("branch {}", branch.branch_name), + }) +} + #[cfg(test)] mod tests; diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs index a89057a97..ec72d5559 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs @@ -316,9 +316,37 @@ fn a_copy_prints_the_new_notes_reference() { } #[test] -fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought() { +fn a_project_note_lands_in_the_project_and_lists_its_children_and_their_repos() { let answer = json!({ "note": { "id": "pn1", "projectId": "p2", "title": "Plan", "content": "body" }, + "children": [ + { + "reference": "#note:c1", + "title": "Web", + "branch": branch_row(), + "repo": repo_row(), + }, + { + "reference": "#note:c2", + "title": "", + "branch": { + "id": "b10", + "projectId": "p2", + "projectRepoId": "r10", + "branchName": "max/gadgets", + "baseBranch": "origin/main", + "worktreePath": null, + }, + "repo": { + "id": "r10", + "projectId": "p2", + "githubRepo": "acme/gadgets", + "subpath": null, + "branchName": "max/gadgets", + "isPrimary": false, + }, + }, + ], "addedRepos": [ { "githubRepo": "acme/widgets", "subpath": "apps/web" }, { "githubRepo": "acme/gadgets", "subpath": null }, @@ -332,6 +360,8 @@ fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought( "project note #project-note:pn1 moved to project \"Target\"\n\ \x20 project id: p2\n\ \x20 title: Plan\n\ + \x20 child note #note:c1 \"Web\" landed on: acme/widgets:apps/web, branch max/target\n\ + \x20 child note #note:c2 landed on: acme/gadgets, branch max/gadgets\n\ \x20 added repo: acme/widgets:apps/web (the project did not track it; its branch is \ set up in the background)\n\ \x20 added repo: acme/gadgets (the project did not track it; its branch is set up in \ @@ -339,7 +369,7 @@ fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought( next: stagedctl timeline show p2" ); // A project note is on no branch, so the app answers neither row and - // none is invented. + // none is invented. Its children are the app's rows as they came. assert_eq!( out.json, json!({ @@ -348,12 +378,14 @@ fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought( "projectId": "p2", "reference": "#project-note:pn1", "note": answer["note"], + "children": answer["children"], "addedRepos": answer["addedRepos"], }) ); let copy = json!({ "note": { "id": "pn9", "projectId": "p2", "title": "Plan", "content": "body" }, + "children": [], "addedRepos": [], }); let app = App::with_projects().answer("copy_project_note_to_project", copy); @@ -365,6 +397,42 @@ fn a_project_note_lands_in_the_project_and_lists_the_repos_its_children_brought( \x20 title: Plan\n\ next: stagedctl timeline show p2" ); + assert_eq!(out.json["children"], json!([])); +} + +#[test] +fn a_child_whose_landing_rows_could_not_be_read_back_is_still_listed() { + // As for the note itself: the child moved, and the output does not + // guess where a row the app could not read would have put it. + let answer = json!({ + "note": { "id": "pn1", "projectId": "p2", "title": "Plan" }, + "children": [ + { "reference": "#note:c1", "title": "Web", "branch": null, "repo": null }, + { "reference": "#note:c2", "title": "Api", "branch": branch_row(), "repo": null }, + ], + "addedRepos": [], + }); + let app = App::with_projects().answer("move_project_note_to_project", answer); + let out = transfer_with(app.invoke(), Transfer::Move, &project_note(), "Target").unwrap(); + assert_eq!( + out.human, + "project note #project-note:pn1 moved to project \"Target\"\n\ + \x20 project id: p2\n\ + \x20 title: Plan\n\ + \x20 child note #note:c1 \"Web\"\n\ + \x20 child note #note:c2 \"Api\" landed on: branch max/target\n\ + next: stagedctl timeline show p2" + ); +} + +#[test] +fn an_answer_without_children_lists_none() { + // A branch note's answer has no `children`, and none is added to it. + let answer = landed_on_branch(note_row("n1", "Findings"), json!([])); + let app = App::with_projects().answer("move_note_to_project", answer); + let out = transfer_with(app.invoke(), Transfer::Move, &branch_note(), "Target").unwrap(); + assert!(!out.human.contains("child note"), "{}", out.human); + assert_eq!(out.json.get("children"), None); } #[test] @@ -582,21 +650,55 @@ fn the_commands_are_allowlisted_by_the_control_server() { #[test] fn the_requests_use_the_argument_names_the_apps_commands_read() { + // `dispatch` hands each pair of commands to a body in + // `note_transfer_arms`, which reads the arguments. let dispatch = include_str!("../../../../src/web_server.rs"); - for (arm, id_arg) in [ + let bodies = include_str!("../../../../src/web_server/note_transfer_arms.rs"); + for (arm, body, id_arg) in [ ( "\"move_note_to_project\" | \"copy_note_to_project\" => {", + "branch_note", "\"noteId\"", ), ( "\"move_project_note_to_project\" | \"copy_project_note_to_project\" => {", + "project_note", "\"projectNoteId\"", ), ] { let start = dispatch.find(arm).unwrap_or_else(|| panic!("no arm {arm}")); - let body = &dispatch[start..start + 600]; - assert!(body.contains(id_arg), "{arm} no longer reads {id_arg}"); - assert!(body.contains("\"targetProjectId\""), "{arm}"); + let call = format!("note_transfer_arms::{body}(&store, command, &args,"); + assert!( + dispatch[start..start + 300].contains(&call), + "{arm} no longer runs {body}" + ); + let start = bodies + .find(&format!("pub(super) async fn {body}<")) + .unwrap_or_else(|| panic!("no body {body}")); + let code = &bodies[start..start + 700]; + assert!(code.contains(id_arg), "{body} no longer reads {id_arg}"); + assert!(code.contains("\"targetProjectId\""), "{body}"); + } +} + +/// What the output reads from the app's answer is what the app puts there. +#[test] +fn the_answer_is_read_under_the_names_the_app_writes() { + let control = include_str!("../../../../src/note_transfer/control.rs"); + for written in [ + "\"note\": note,", + "\"branch\": branch,", + "\"repo\": repo,", + "\"children\": children,", + "\"addedRepos\": added.into_json(),", + "\"reference\": format!(\"#note:{}\", child.id),", + "\"title\": child.title,", + "json!({ \"githubRepo\": key.github_repo, \"subpath\": key.subpath })", + ] { + assert!( + control.contains(written), + "the app's answer no longer has {written}; read `Landed` again" + ); } } @@ -725,6 +827,73 @@ fn help_states_the_transfers_rules_as_the_app_has_them() { assert!(help.contains("`not_found`"), "{help}"); assert!(help.contains("stagedctl has no delete"), "{help}"); } + + // The scope refusals beyond the two projects, as the app's scope check + // makes them. A confined credential is refused a note it cannot be + // shown in the words of a note that is not there, with exit 4. + let scope = include_str!("../../../../src/web_server/control_scope.rs"); + for refusal in [ + "denied(format!(\"note {note_id} not found\"))", + "denied(format!(\"project note {note_id} not found\"))", + "embeds media {media_id}, which belongs to another project", + "its child note #note:{}", + ] { + assert!( + scope.contains(refusal), + "the scope check no longer says {refusal:?}; update `note move`/`note copy` --help" + ); + } + for help in [&move_help, ©_help] { + for promise in [ + "A credential confined to some", + "a <NOTE> that names no note of that kind", + "says \"not found\"", + "`app_error`", + "embeds an image or video from a project it does\n not reach", + ] { + assert!(help.contains(promise), "help lacks {promise:?}:\n{help}"); + } + } + // A moved project note's children travel, so their media counts. A + // copy leaves them, so theirs does not. + assert!( + scope.contains("with_children: true"), + "the move's scope row" + ); + assert!( + move_help.contains("or a project note with such a child note"), + "{move_help}" + ); + assert!( + copy_help.contains("A project note's child notes are not copied"), + "{copy_help}" + ); + + // A repo the transfer added stays when it then fails, and the error + // names it, for a branch note as for a project note. + assert!(transfer.contains("along the way and {remain} tracked there.")); + assert!( + move_help.contains("along the way and remains tracked there."), + "{move_help}" + ); + assert!( + copy_help.contains( + "The repo stays in the project when the copy then fails, and\nthe error names it" + ), + "{copy_help}" + ); + for help in [&move_help, ©_help] { + assert!( + !help.contains("stagedctl project get"), + "the error names the repo; nothing else has to be looked up: {help}" + ); + } + + // The output of a project note's move lists its children. + assert!( + move_help.contains("The output lists each child by its\n reference"), + "{move_help}" + ); } #[test] @@ -741,6 +910,13 @@ fn the_guide_describes_both_verbs() { "an unquoted `#` starts a shell comment", "both projects", "the user can move the note back or delete the copy", + "The output lists each child by its reference", + "the error names it", + "Exit 4 (`scope_denied`)", + "A reference that names no note of its kind also exits 4", + "a message that says \"not found\"", + "embeds an image or video from such a project", + "refused for media a child note embeds too", ] { assert!(flat.contains(expected), "the guide lacks {expected:?}"); } diff --git a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt index 246e886db..9b985b145 100644 --- a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt +++ b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt @@ -840,7 +840,8 @@ on its kind: media, and takes its child notes along. Each child lands, with its own session, on the destination's branch for its repo and subpath, still linked to the - project note. + project note. The output lists each child by its + reference, with the repo and branch it landed on. Commits and code reviews are not part of a note. They stay on the branch they were made on. @@ -850,8 +851,8 @@ the way `stagedctl project add-repo` adds one without --branch: a new branch named after the project, set up in the background (a worktree, or a clone into a remote project's workspace). The output names each repo added this way. Such a repo stays in the project when a later step -of the move fails. A project note's error names it; a branch note's -does not, so look at `stagedctl project get`. +of the move fails, and the error then names it: "<repo> was added to +<project> along the way and remains tracked there." The app refuses a move, with the note left where it was (exit 1, `app_error`, the app's own message), when: @@ -864,9 +865,20 @@ The app refuses a move, with the note left where it was (exit 1, outside the project note's own project. Needs write access to both projects, the one the note is in and the -destination. A read-only credential is refused (exit 4, `scope_denied`), -and so is a note in a project the credential does not reach. A -destination it does not reach is not among its projects and exits 1 +destination. A read-only credential is refused (exit 4, `scope_denied`). +A credential confined to some projects, which a session's is, also +exits 4 (`scope_denied`) for: + - a note in a project it does not reach; + - a <NOTE> that names no note of that kind: an id that does not + exist, or a project note's id written as #note:<id>, or the other + way round. So exit 4 can mean a mistyped reference and not a + missing permission; the message then says "not found". A + credential for every project gets the app's own error for it + (exit 1, `app_error`); + - a note whose body embeds an image or video from a project it does + not reach, or a project note with such a child note. The move would + carry that media into the destination. +A destination it does not reach is not among its projects and exits 1 (`not_found`). A session may move notes between its own project and the projects it created, in either direction, and nowhere else. @@ -913,9 +925,10 @@ videos in the body, and nothing else: A copy of a branch note lands on the destination's branch for the repo and subpath the note's branch tracks. A destination that does not track that repo gets it first, as in `stagedctl note move`, and the output -names it. A title another note on the landing branch has gets a number: -"<title> (2)". A copy of a project note lands in the destination -project and never adds a repo. +names it. The repo stays in the project when the copy then fails, and +the error names it. A title another note on the landing branch has gets +a number: "<title> (2)". A copy of a project note lands in the +destination project and never adds a repo. --to may be the project the note is already in. That duplicates the note beside the original, on the same branch for a branch note. @@ -927,10 +940,18 @@ and is running again can be copied, where it could not be moved: the copy is the note as it reads now. Needs write access to both projects, the one the note is in and the -destination, as `stagedctl note move` does: exit 4 (`scope_denied`) -under a read-only credential or for a note in a project the credential -does not reach, exit 1 (`not_found`) for a destination it does not -reach. +destination, as `stagedctl note move` does. A read-only credential is +refused (exit 4, `scope_denied`). A credential confined to some +projects, which a session's is, also exits 4 (`scope_denied`) for: + - a note in a project it does not reach; + - a <NOTE> that names no note of that kind: an id that does not + exist, or the other kind's id. The message then says "not found", + and a credential for every project gets exit 1 (`app_error`); + - a note whose body embeds an image or video from a project it does + not reach. The copy would duplicate that media in the destination. + A project note's child notes are not copied, so theirs do not + count. +A destination it does not reach exits 1 (`not_found`). A copy shows at once in the destination, where the user can delete it. stagedctl has no delete. diff --git a/apps/staged/src-tauri/resources/stagedctl/guide.md b/apps/staged/src-tauri/resources/stagedctl/guide.md index c4a43dee0..ff4a3cc7d 100644 --- a/apps/staged/src-tauri/resources/stagedctl/guide.md +++ b/apps/staged/src-tauri/resources/stagedctl/guide.md @@ -150,10 +150,11 @@ projects it created, and nowhere else. Know what each one leaves behind before choosing: - A move takes the note itself. It keeps its id and its session, and a - project note takes its child notes along with theirs. A branch note - moved on its own loses its link to the project note it was written - under, and moving it back does not restore that link. Commits and code - reviews stay on their branch. + project note takes its child notes along with theirs. The output lists + each child by its reference, with the repo and branch it landed on. A + branch note moved on its own loses its link to the project note it was + written under, and moving it back does not restore that link. Commits + and code reviews stay on their branch. - A copy is a new, standalone note with its own id: the title and body as they read now, with no session, no parent or child notes, and no suggested next steps. The original is untouched. @@ -162,7 +163,8 @@ before choosing: the way `stagedctl project add-repo` adds one: a new branch, then a worktree or a clone into the remote workspace and the setup actions, in the background. The output names each repo added. It stays in the - project if the transfer then fails, and only the user can remove it. + project if the transfer then fails, the error names it, and only the + user can remove it. The app refuses a transfer it cannot make whole, with exit 1 and its own reason: a note whose session is still writing it, a move into the project @@ -170,6 +172,18 @@ the note is already in, a note whose branch tracks no repo, a project note with child notes when either project is remote. Wait for the session, or pick another destination. Do not work around a refusal. +Exit 4 (`scope_denied`) from either verb is about the credential's reach, +with one trap. A reference that names no note of its kind also exits 4 +under a session's credential, with a message that says "not found": an id +that does not exist, or a project note's id written as `#note:<id>` or the +other way round. Check the reference against `stagedctl timeline show` +before reading that as a missing permission. The other reach refusals are +a note in a project the session does not reach, and a note whose body +embeds an image or video from such a project. A moved project note is +refused for media a child note embeds too, since the child travels with +it. Embedded media goes wherever the note goes, so it has to be within +reach as well. + Tag assignments (`stagedctl project tag`, `stagedctl project untag`) fit the invariant: they show at once as the pills and chips in the project header, where the user can undo them with a group pill's None or a chip's ×. A tag diff --git a/apps/staged/src-tauri/src/control_server.rs b/apps/staged/src-tauri/src/control_server.rs index 6d5502c3b..2eccc9f57 100644 --- a/apps/staged/src-tauri/src/control_server.rs +++ b/apps/staged/src-tauri/src/control_server.rs @@ -86,7 +86,8 @@ //! transfer added like any other. One link does not come back with the //! note: a branch note moved on its own is detached from its parent project //! note. The note's project and the destination must both be within the -//! caller's reach. +//! caller's reach, and so must the media the note's body embeds, which +//! the transfer carries with it. //! //! No deletes — `delete_project` and `remove_project_repo` stay off the //! table, and `delete_tag` and `delete_tag_group` drop assignments on every diff --git a/apps/staged/src-tauri/src/note_transfer/control.rs b/apps/staged/src-tauri/src/note_transfer/control.rs index e7b20a200..e2954b3de 100644 --- a/apps/staged/src-tauri/src/note_transfer/control.rs +++ b/apps/staged/src-tauri/src/note_transfer/control.rs @@ -4,15 +4,19 @@ //! The app's windows open a note where it is and know its surroundings, so //! the transfer commands answer them with the note alone. A control caller //! named a note by id and a project, and is told what the transfer did with -//! them: the branch the note landed on, and the repos the transfer added to -//! the destination to make room for it. Only the transfer knows the second. -//! Once added, a repo reads like any other the project tracks, so each one -//! is noted as its add succeeds ([`AddedRepos`]). +//! them: the branch the note landed on, the child notes a moved project +//! note took along and where each of those landed, and the repos the +//! transfer added to the destination to make room. Only the transfer knows +//! the last. Once added, a repo reads like any other the project tracks, so +//! each one is noted as its add succeeds ([`AddedRepos`]). The same list +//! lets a failure say which repos the destination gained before it +//! ([`AddedRepos::explain`]). //! //! Nothing here decides anything about a transfer. Every caller runs the //! same [`transfer_branch_note`](super::transfer_branch_note) or //! [`transfer_project_note`](super::transfer_project_note) with the same -//! repo-adding step. This module watches that step and words the answer. +//! repo-adding step. This module watches that step and words the answer, +//! from rows it reads back once the transfer has committed. use std::future::Future; use std::sync::{Mutex, PoisonError}; @@ -20,6 +24,7 @@ use std::sync::{Mutex, PoisonError}; use serde_json::{json, Value}; use super::RepoKey; +use crate::store::models::ProjectNote; use crate::store::Store; /// The repos one transfer added to its destination, in the order it added @@ -43,6 +48,28 @@ impl AddedRepos { Ok(()) } + /// A branch-note transfer failed with `err`. When it had already added + /// a repo to `target_project_id`, the repo stays tracked there, and the + /// error says so in the words a project-note failure uses + /// ([`with_added_repos`](super::with_added_repos)). The transfer words + /// that sentence itself for a project note, so this is not for one. + /// + /// A failed add is not noted, so its error comes back as it is. + pub(crate) fn explain(&self, store: &Store, target_project_id: &str, err: String) -> String { + let added = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if added.is_empty() { + return err; + } + match store.get_project(target_project_id) { + Ok(Some(target)) => super::with_added_repos(err, &added, &target), + Ok(None) => err, + Err(e) => { + log::warn!("Note transfer: cannot read back project {target_project_id}: {e}"); + err + } + } + } + /// `[{ githubRepo, subpath }]`, the names `list_project_repos` uses. fn into_json(self) -> Value { self.0 @@ -69,6 +96,74 @@ pub(crate) fn branch_note_answer( branch_id: &str, added: AddedRepos, ) -> Value { + let (branch, repo) = landing(store, branch_id); + json!({ + "note": note, + "branch": branch, + "repo": repo, + "addedRepos": added.into_json(), + }) +} + +/// A control caller's answer for a project note: `note`, the note as +/// `list_project_notes` lists one, which names the project it is in now; +/// `children`, the child notes that came with it; and `addedRepos`, the +/// repos those children brought along. +/// +/// `note` is the transfer's own value, which a window is answered with as +/// it is. A moved note's is the row the move's transaction returned, with +/// no session status resolved: `sessionStatus` would read `null` for a note +/// whose session finished. So the note is read again here, the way the +/// project's note list reads it. If that read fails the transfer's value +/// stands, as the rows of a branch note's answer do. +/// +/// Each of `children` is `{ reference, title, branch, repo }`: the child's +/// hashtag reference (`#note:<id>`, unchanged by the move), and the branch +/// and repo it is on now, as in a branch note's answer. A move takes every +/// child or is refused, so these are the note's children as they read +/// after it. A copy has none. +pub(crate) fn project_note_answer(store: &Store, note: ProjectNote, added: AddedRepos) -> Value { + let note = match store.get_project_note_with_status(¬e.id) { + Ok(Some(resolved)) => resolved, + Ok(None) => note, + Err(e) => { + log::warn!( + "Note transfer: cannot read back project note {}: {e}", + note.id + ); + note + } + }; + let children: Vec<Value> = store + .list_child_notes(¬e.id) + .unwrap_or_else(|e| { + log::warn!( + "Note transfer: cannot read back the child notes of {}: {e}", + note.id + ); + Vec::new() + }) + .into_iter() + .map(|child| { + let (branch, repo) = landing(store, &child.branch_id); + json!({ + "reference": format!("#note:{}", child.id), + "title": child.title, + "branch": branch, + "repo": repo, + }) + }) + .collect(); + json!({ + "note": note, + "children": children, + "addedRepos": added.into_json(), + }) +} + +/// The branch a note is on and the repo that branch tracks, as the answers +/// give them. Either is `null` when its row cannot be read back. +fn landing(store: &Store, branch_id: &str) -> (Value, Value) { let branch = store.get_branch(branch_id).unwrap_or_else(|e| { log::warn!("Note transfer: cannot read back branch {branch_id}: {e}"); None @@ -93,19 +188,7 @@ pub(crate) fn branch_note_answer( }); crate::branches::to_branch_with_workdir(branch, workdir.map(|workdir| workdir.path)) }); - json!({ - "note": note, - "branch": branch, - "repo": repo, - "addedRepos": added.into_json(), - }) -} - -/// A control caller's answer for a project note: `note`, the value the UI -/// gets, which names the project it is in now, and `addedRepos`, the repos -/// its child notes brought along. -pub(crate) fn project_note_answer(note: Value, added: AddedRepos) -> Value { - json!({ "note": note, "addedRepos": added.into_json() }) + (json!(branch), json!(repo)) } #[cfg(test)] diff --git a/apps/staged/src-tauri/src/note_transfer/control/tests.rs b/apps/staged/src-tauri/src/note_transfer/control/tests.rs index 68d0d67fb..6fdff2cb4 100644 --- a/apps/staged/src-tauri/src/note_transfer/control/tests.rs +++ b/apps/staged/src-tauri/src/note_transfer/control/tests.rs @@ -2,7 +2,9 @@ use serde_json::json; use super::*; use crate::note_transfer::{transfer_branch_note, transfer_project_note, TransferMode}; -use crate::store::models::{Branch, Note, Project, ProjectNote, ProjectRepo}; +use crate::store::models::{ + Branch, Note, Project, ProjectNote, ProjectRepo, Session, SessionStatus, +}; /// `source` tracks `acme/widgets` at `apps/web` and `acme/gadgets`, with a /// branch on each. `target` tracks nothing. @@ -166,16 +168,25 @@ async fn a_repo_whose_add_failed_is_not_reported_as_added() { /// A moved project note brings its children, and each child's repo is added /// where the destination lacks it: the answer lists those, in the order the -/// transfer added them, and not a repo the destination already had. +/// transfer added them, and not a repo the destination already had. It +/// names each child and the branch it landed on, and it says how the note's +/// session stands, which the row the move returns does not. #[tokio::test] -async fn a_project_note_move_lists_the_repos_its_children_brought() { +async fn a_project_note_move_lists_its_children_and_the_repos_they_brought() { let f = fixture(); - let parent = ProjectNote::new(&f.source.id, "Plan", "body"); + let session = Session::new_running("plan", std::path::Path::new("/tmp/wt")); + f.store.create_session(&session).unwrap(); + f.store + .update_session_status(&session.id, SessionStatus::Completed, None, None) + .unwrap(); + let parent = ProjectNote::new(&f.source.id, "Plan", "body").with_session(&session.id); f.store.create_project_note(&parent).unwrap(); + let mut children = Vec::new(); for (branch, title) in [(&f.widgets, "Web"), (&f.gadgets, "Gadgets")] { let child = Note::new_standalone(&branch.id, title, "body").with_parent_project_note(&parent.id); f.store.create_note(&child).unwrap(); + children.push(child); } f.attach(RepoKey { github_repo: "acme/widgets".into(), @@ -193,18 +204,41 @@ async fn a_project_note_move_lists_the_repos_its_children_brought() { ) .await .unwrap(); - let answer = project_note_answer(serde_json::to_value(&moved).unwrap(), added); + assert_eq!( + moved.session_status, None, + "the move's own row resolves no session, which is why the answer reads it again" + ); + let answer = project_note_answer(&f.store, moved, added); assert_eq!(answer["note"]["id"], parent.id); assert_eq!(answer["note"]["projectId"], f.target.id); + assert_eq!(answer["note"]["sessionId"], session.id); + assert_eq!(answer["note"]["sessionStatus"], "completed"); assert_eq!( answer["addedRepos"], json!([{ "githubRepo": "acme/gadgets", "subpath": null }]) ); + let listed = answer["children"].as_array().unwrap(); + assert_eq!(listed.len(), 2); + for (child, github_repo, branch_name) in [ + (&children[0], "acme/widgets", "target-acme-widgets"), + (&children[1], "acme/gadgets", "target-acme-gadgets"), + ] { + let reference = format!("#note:{}", child.id); + let row = listed + .iter() + .find(|row| row["reference"] == reference.as_str()) + .unwrap_or_else(|| panic!("{reference} is not among {listed:?}")); + assert_eq!(row["title"], child.title); + assert_eq!(row["branch"]["projectId"], f.target.id); + assert_eq!(row["branch"]["branchName"], branch_name); + assert_eq!(row["repo"]["githubRepo"], github_repo); + assert_eq!(row["repo"]["id"], row["branch"]["projectRepoId"]); + } } #[tokio::test] -async fn a_project_note_copy_adds_no_repo() { +async fn a_project_note_copy_adds_no_repo_and_has_no_children() { let f = fixture(); let parent = ProjectNote::new(&f.source.id, "Plan", "body"); f.store.create_project_note(&parent).unwrap(); @@ -222,13 +256,64 @@ async fn a_project_note_copy_adds_no_repo() { ) .await .unwrap(); - let answer = project_note_answer(serde_json::to_value(©).unwrap(), added); + let answer = project_note_answer(&f.store, copy, added); assert_ne!(answer["note"]["id"], parent.id); assert_eq!(answer["note"]["projectId"], f.target.id); + assert_eq!(answer["note"]["sessionStatus"], Value::Null); + assert_eq!(answer["children"], json!([])); assert_eq!(answer["addedRepos"], json!([])); } +/// As for a branch note's rows: a project note that cannot be read again is +/// answered as the transfer returned it, and it is not an error. +#[test] +fn a_project_note_that_cannot_be_read_back_is_answered_as_the_transfer_gave_it() { + let f = fixture(); + let note = ProjectNote::new(&f.target.id, "Plan", "body"); + let answer = project_note_answer(&f.store, note.clone(), AddedRepos::default()); + assert_eq!( + answer, + json!({ "note": note, "children": [], "addedRepos": [] }) + ); +} + +/// A failure is given the repos the transfer had added by then, in the +/// sentence a project-note failure ends with. With none added, or for a +/// destination that is not there, the error is left as it came. +#[tokio::test] +async fn a_failure_names_the_repos_added_before_it() { + let f = fixture(); + let added = AddedRepos::default(); + assert_eq!( + added.explain(&f.store, &f.target.id, "It failed".to_string()), + "It failed" + ); + + let key = RepoKey { + github_repo: "acme/widgets".into(), + subpath: Some("apps/web".into()), + }; + added + .watch(key.clone(), std::future::ready(Ok(()))) + .await + .unwrap(); + assert_eq!( + added.explain(&f.store, &f.target.id, "It failed".to_string()), + "It failed. acme/widgets at apps/web was added to target along the way and remains \ + tracked there." + ); + assert_eq!( + added.explain(&f.store, "no-such-project", "It failed".to_string()), + "It failed" + ); + // Explaining a failure does not use the list up. + assert_eq!( + added.into_json(), + json!([{ "githubRepo": "acme/widgets", "subpath": "apps/web" }]) + ); +} + /// The transfer has committed before the answer is worded, so a landing row /// that cannot be read back is left out of the answer. It is not an error. #[test] diff --git a/apps/staged/src-tauri/src/web_server.rs b/apps/staged/src-tauri/src/web_server.rs index d6673bd00..962e1b6dc 100644 --- a/apps/staged/src-tauri/src/web_server.rs +++ b/apps/staged/src-tauri/src/web_server.rs @@ -900,6 +900,7 @@ pub(crate) fn preferences_store( mod control_project_args; pub(crate) mod control_scope; +mod note_transfer_arms; pub(crate) use control_scope::SCOPE_DENIED_PREFIX; /// Who is calling [`dispatch`]. A handful of commands encode same-host-only @@ -3237,91 +3238,32 @@ pub(crate) async fn dispatch( }) .await } + // The four note transfers. Their bodies are in `note_transfer_arms`, + // where they can be run under test; all an arm adds is the app's own + // repo-adding step. "move_note_to_project" | "copy_note_to_project" => { let store = get_store(store_mutex)?; - let note_id: String = arg(&args, "noteId")?; - let target_project_id: String = arg(&args, "targetProjectId")?; - let mode = if command == "move_note_to_project" { - crate::note_transfer::TransferMode::Move - } else { - crate::note_transfer::TransferMode::Copy - }; - let added = crate::note_transfer::control::AddedRepos::default(); - let note = crate::note_transfer::transfer_branch_note( - &store, - ¬e_id, - &target_project_id, - mode, - |key| { - added.watch( - key.clone(), - crate::note_transfer::add_repo_to_project( - app_handle.clone(), - Arc::clone(&store), - target_project_id.clone(), - key, - ), - ) - }, - ) - .await?; - let branch_id = note.branch_id.clone(); - let item = match mode { - crate::note_transfer::TransferMode::Move => { - crate::note_commands::note_to_timeline_item(&store, note) - } - crate::note_transfer::TransferMode::Copy => { - crate::note_commands::standalone_note_to_timeline_item(note) - } - }; - let item = serde_json::to_value(item).unwrap(); - Ok(match &caller { - // A window has the note open and knows where it sent it. A - // control caller is told: the branch the note landed on and - // the repos the transfer added. - DispatchCaller::Control(_) => crate::note_transfer::control::branch_note_answer( - &store, item, &branch_id, added, - ), - DispatchCaller::Web => item, + note_transfer_arms::branch_note(&store, command, &args, &caller, |project_id, key| { + crate::note_transfer::add_repo_to_project( + app_handle.clone(), + Arc::clone(&store), + project_id, + key, + ) }) + .await } "move_project_note_to_project" | "copy_project_note_to_project" => { let store = get_store(store_mutex)?; - let project_note_id: String = arg(&args, "projectNoteId")?; - let target_project_id: String = arg(&args, "targetProjectId")?; - let mode = if command == "move_project_note_to_project" { - crate::note_transfer::TransferMode::Move - } else { - crate::note_transfer::TransferMode::Copy - }; - let added = crate::note_transfer::control::AddedRepos::default(); - let note = crate::note_transfer::transfer_project_note( - &store, - &project_note_id, - &target_project_id, - mode, - |key| { - added.watch( - key.clone(), - crate::note_transfer::add_repo_to_project( - app_handle.clone(), - Arc::clone(&store), - target_project_id.clone(), - key, - ), - ) - }, - ) - .await?; - let note = serde_json::to_value(note).unwrap(); - Ok(match &caller { - // As for a branch note: a control caller is told which repos - // the note's children brought along. - DispatchCaller::Control(_) => { - crate::note_transfer::control::project_note_answer(note, added) - } - DispatchCaller::Web => note, + note_transfer_arms::project_note(&store, command, &args, &caller, |project_id, key| { + crate::note_transfer::add_repo_to_project( + app_handle.clone(), + Arc::clone(&store), + project_id, + key, + ) }) + .await } // ===================================================================== @@ -5445,73 +5387,87 @@ mod tests { /// A note moved or copied through the control server goes through the /// transfer the app's windows run: one call, with the app's own - /// repo-adding step, whoever asks. The caller decides nothing until the - /// transfer has returned, and then only how much the answer says: a - /// control caller is told where the note landed and which repos were - /// added, a window gets the note alone, as it always has. + /// repo-adding step, whoever asks. `note_transfer_arms` runs the arm + /// bodies for real, with a stand-in for that step. What it cannot run is + /// pinned here: that `dispatch` hands each command to its body with the + /// app's step and nothing else, that the body does not branch on its + /// caller ahead of the transfer, and that the desktop command is the + /// same transfer. #[test] fn note_transfers_run_the_one_transfer_whoever_asks() { let source = include_str!("web_server.rs"); + let bodies = include_str!("web_server/note_transfer_arms.rs"); let desktop = include_str!("note_transfer.rs"); - for (command, transfer, answer, web) in [ + for (command, body, transfer) in [ ( "move_note_to_project", + "branch_note", "transfer_branch_note(", - "note_transfer::control::branch_note_answer(", - "DispatchCaller::Web => item,", ), ( "copy_note_to_project", + "branch_note", "transfer_branch_note(", - "note_transfer::control::branch_note_answer(", - "DispatchCaller::Web => item,", ), ( "move_project_note_to_project", + "project_note", "transfer_project_note(", - "note_transfer::control::project_note_answer(", - "DispatchCaller::Web => note,", ), ( "copy_project_note_to_project", + "project_note", "transfer_project_note(", - "note_transfer::control::project_note_answer(", - "DispatchCaller::Web => note,", ), ] { let (_, arm) = dispatch_arms(source) .into_iter() .find(|(patterns, _)| patterns.iter().any(|p| p == command)) .unwrap_or_else(|| panic!("dispatch should have a `{command}` arm")); + // The arm passes the request and the caller on as they came, + // with the app's own step for adding a repo. + assert!( + arm.contains(&format!( + "note_transfer_arms::{body}(&store, command, &args, &caller, |project_id, key| {{" + )) && arm.contains("crate::note_transfer::add_repo_to_project("), + "the `{command}` arm must run `{body}` with the shared repo-adding step: {arm}" + ); + for inline in [ + "DispatchCaller::", + "transfer_branch_note", + "transfer_project_note", + ] { + assert!( + !arm.contains(inline), + "the `{command}` arm must leave `{inline}` to its body: {arm}" + ); + } + + // The body: one transfer, the step watched and not stood in + // for, and nothing about the caller before the transfer. + let marker = format!("pub(super) async fn {body}<"); + let start = bodies + .find(&marker) + .unwrap_or_else(|| panic!("note_transfer_arms.rs should define `{body}`")); + let rest = &bodies[start..]; + let end = rest.find("\n}\n").expect("the body should end"); + let code = &rest[rest.find("{\n").unwrap()..end]; assert_eq!( - arm.matches(&format!("note_transfer::{transfer}")).count(), + code.matches(transfer).count(), 1, - "the `{command}` arm must run the transfer once, for every caller: {arm}" + "`{body}` must run the transfer once, for every caller: {code}" ); - // The repo is added by the app's own step. The arm watches it - // and does not stand in for it. assert!( - arm.contains("added.watch(") - && arm.contains("crate::note_transfer::add_repo_to_project("), - "the `{command}` arm must add a repo through the shared step: {arm}" + code.contains("added.watch(key.clone(), add_repo(target_project_id.clone(), key))"), + "`{body}` must add a repo through the step it was given: {code}" ); - // Nothing about the caller comes before the transfer. - let transfer_at = arm.find(transfer).unwrap(); - let caller_at = arm - .find("caller") - .unwrap_or_else(|| panic!("the `{command}` arm should answer by caller: {arm}")); + let transfer_at = code.find(transfer).unwrap(); + let caller_at = code + .find("match caller {") + .unwrap_or_else(|| panic!("`{body}` should answer by caller: {code}")); assert!( transfer_at < caller_at, - "the `{command}` arm must not branch on its caller before the transfer: {arm}" - ); - let answers = &arm[caller_at..]; - assert!( - answers.contains("DispatchCaller::Control(_) =>") && answers.contains(answer), - "a control `{command}` must be answered through `{answer}`: {arm}" - ); - assert!( - answers.contains(web), - "a web `{command}` must be answered with the note alone: {arm}" + "`{body}` must not branch on its caller before the transfer: {code}" ); // The desktop command is the same transfer with the same step. @@ -5522,6 +5478,7 @@ mod tests { let rest = &desktop[start..]; let end = rest[1..] .find("#[tauri::command") + .map(|at| at + 1) .or_else(|| rest.find("#[cfg(test)]")) .unwrap_or(rest.len()); assert!( diff --git a/apps/staged/src-tauri/src/web_server/control_scope.rs b/apps/staged/src-tauri/src/web_server/control_scope.rs index d3ca5239b..7d8d57dea 100644 --- a/apps/staged/src-tauri/src/web_server/control_scope.rs +++ b/apps/staged/src-tauri/src/web_server/control_scope.rs @@ -72,6 +72,22 @@ //! it cannot read. A copy into the note's own project names one project //! twice and needs no more than that one. //! +//! One thing a transfer carries can come from outside those two: media. A +//! note's body embeds stored images and videos by id +//! (`staged-media://<id>`), and the transfer puts each one in the +//! destination whichever project its row is in. A confined caller that knew +//! an id could otherwise have a note of its own embed it, and copy the file +//! into a project it reaches. So the media a note embeds must be within +//! reach as well, as the `imageIds` of a start command must +//! ([`require_note_media_in_scope`]). A moved project note's child notes are +//! held to the same, since their bodies travel with it. A reference with no +//! row carries nothing and is let through, as the transfer leaves it. +//! +//! The bodies are read when the request arrives. A transfer that has to add +//! a repo reads them again once the repo is in, so a body saved during that +//! add is carried unchecked. Closing that takes a check inside the +//! transfer, which this module does not reach into. +//! //! Nothing else a transfer touches lies outside those two. A moved project //! note takes its child notes along, and the transfer refuses a child whose //! branch is in another project. The repo it adds to the destination is one @@ -97,6 +113,7 @@ use serde_json::Value; use super::{arg, control_create_image_args, get_store, opt_arg, DispatchCaller}; use crate::control_server::{Access, Actor, ControlGrant}; +use crate::note_media::refs; use crate::store::Store; /// Prefix on a `dispatch` error that denotes a scope refusal, so the control @@ -139,8 +156,10 @@ pub(crate) enum ScopeKey { /// must be within reach. NoteTransfer, /// [`ScopeKey::NoteTransfer`] for a project note: `projectNoteId`, whose - /// row names its project, and `targetProjectId`. - ProjectNoteTransfer, + /// row names its project, and `targetProjectId`. A move takes the note's + /// child notes along (`with_children`), so the media their bodies embed + /// is checked with the note's own. + ProjectNoteTransfer { with_children: bool }, } /// One row per allowlisted control command: how to resolve its project, @@ -226,12 +245,16 @@ pub(crate) const CONTROL_SCOPE: &[(&str, ScopeKey, Access)] = &[ ), ( "move_project_note_to_project", - ScopeKey::ProjectNoteTransfer, + ScopeKey::ProjectNoteTransfer { + with_children: true, + }, Access::ReadWrite, ), ( "copy_project_note_to_project", - ScopeKey::ProjectNoteTransfer, + ScopeKey::ProjectNoteTransfer { + with_children: false, + }, Access::ReadWrite, ), ]; @@ -269,7 +292,7 @@ impl Reach { /// unconfined caller (a web caller, or an all-projects grant), else the /// grant's own project and the projects its actor created. Lists the /// actor's created projects, so it is for the arms. The check ahead of them -/// does single-row reads only (see [`require_in_scope`]). +/// lists no projects (see [`check_with_store`]). pub(super) fn reach(caller: &DispatchCaller, store: &Store) -> Result<Reach, String> { let DispatchCaller::Control(grant) = caller else { return Ok(Reach::All); @@ -299,8 +322,10 @@ pub(super) fn check( check_with_store(cmd, args, grant, &store) } -/// The scope decision. Store reads here are single-row lookups only: this -/// runs inline on the runtime, ahead of the arm. +/// The scope decision. Store reads here are single-row lookups, since this +/// runs inline on the runtime, ahead of the arm. The one exception is a +/// project-note move, which lists the note's child notes: their bodies +/// travel with it. pub(crate) fn check_with_store( cmd: &str, args: &Value, @@ -322,7 +347,7 @@ pub(crate) fn check_with_store( ScopeKey::ResultFilter => Ok(()), ScopeKey::ProjectArg => { let project_id: String = arg(args, "projectId")?; - require_in_scope(store, grant, &project_id, "project")?; + require_in_scope(store, grant, &project_id, &elsewhere("project"))?; require_images_in_scope(store, args, grant) } ScopeKey::NewProject => match (&grant.actor, scope) { @@ -337,7 +362,7 @@ pub(crate) fn check_with_store( let branch_id: String = arg(args, "branchId")?; if scope.is_some() { let project_id = branch_project(store, &branch_id)?; - require_in_scope(store, grant, &project_id, "branch")?; + require_in_scope(store, grant, &project_id, &elsewhere("branch"))?; } require_images_in_scope(store, args, grant) } @@ -345,7 +370,7 @@ pub(crate) fn check_with_store( let session_id: String = arg(args, "sessionId")?; if scope.is_some() { let project_id = session_project(store, &session_id)?; - require_in_scope(store, grant, &project_id, "session")?; + require_in_scope(store, grant, &project_id, &elsewhere("session"))?; } Ok(()) } @@ -361,7 +386,7 @@ pub(crate) fn check_with_store( {project_id}" ))); } - require_in_scope(store, grant, &project_id, "project") + require_in_scope(store, grant, &project_id, &elsewhere("project")) } ScopeKey::Catalog => Ok(()), ScopeKey::CreateTag => { @@ -381,7 +406,9 @@ pub(crate) fn check_with_store( } let assign_project_id: Option<String> = opt_arg(args, "assignProjectId")?; match assign_project_id { - Some(project_id) => require_in_scope(store, grant, &project_id, "project"), + Some(project_id) => { + require_in_scope(store, grant, &project_id, &elsewhere("project")) + } None => Err(denied(format!( "{cmd} edits the shared tag catalog; {}, and it may only create a tag it \ assigns to one of them (assignProjectId)", @@ -407,25 +434,55 @@ pub(crate) fn check_with_store( ))); } let project_id: String = arg(args, "projectId")?; - require_in_scope(store, grant, &project_id, "project") + require_in_scope(store, grant, &project_id, &elsewhere("project")) } ScopeKey::NoteTransfer => { let note_id: String = arg(args, "noteId")?; let target_project_id: String = arg(args, "targetProjectId")?; if scope.is_some() { - let project_id = note_project(store, ¬e_id)?; - require_in_scope(store, grant, &project_id, "note")?; - require_destination_in_scope(store, grant, &target_project_id)?; + let note = store + .get_note(¬e_id) + .map_err(|e| e.to_string())? + .ok_or_else(|| denied(format!("note {note_id} not found")))?; + let project_id = branch_project(store, ¬e.branch_id)?; + require_in_scope(store, grant, &project_id, &elsewhere("note"))?; + require_in_scope(store, grant, &target_project_id, DESTINATION_OUT_OF_REACH)?; + require_note_media_in_scope(store, grant, &project_id, "the note", ¬e.content)?; } Ok(()) } - ScopeKey::ProjectNoteTransfer => { + ScopeKey::ProjectNoteTransfer { with_children } => { let note_id: String = arg(args, "projectNoteId")?; let target_project_id: String = arg(args, "targetProjectId")?; if scope.is_some() { - let project_id = project_note_project(store, ¬e_id)?; - require_in_scope(store, grant, &project_id, "project note")?; - require_destination_in_scope(store, grant, &target_project_id)?; + let note = store + .get_project_note(¬e_id) + .map_err(|e| e.to_string())? + .ok_or_else(|| denied(format!("project note {note_id} not found")))?; + let project_id = ¬e.project_id; + require_in_scope(store, grant, project_id, &elsewhere("project note"))?; + require_in_scope(store, grant, &target_project_id, DESTINATION_OUT_OF_REACH)?; + require_note_media_in_scope( + store, + grant, + project_id, + "the project note", + ¬e.content, + )?; + if *with_children { + for child in store + .list_child_notes(¬e.id) + .map_err(|e| e.to_string())? + { + require_note_media_in_scope( + store, + grant, + project_id, + &format!("its child note #note:{}", child.id), + &child.content, + )?; + } + } } Ok(()) } @@ -442,65 +499,46 @@ fn covers(allowed: &str) -> String { format!("this credential covers project {allowed} and the projects it created") } -/// `Ok` when the grant is unconfined, `project_id` is its own project, or -/// its actor created `project_id` (see the module docs). -fn require_in_scope( - store: &Store, - grant: &ControlGrant, - project_id: &str, - what: &str, -) -> Result<(), String> { - let Some(allowed) = grant.project_scope() else { - return Ok(()); - }; - if within_reach(store, grant, allowed, project_id)? { - return Ok(()); - } - Err(denied(format!( - "the {what} belongs to another project; {}", - covers(allowed) - ))) +/// The refusal for a row the caller named that is in a project outside its +/// reach: "the branch belongs to another project". +fn elsewhere(what: &str) -> String { + format!("the {what} belongs to another project") } -/// [`require_in_scope`] for the project a note transfer is sent to, which -/// the caller named itself. A destination that does not exist is refused the -/// same way, so a confined caller learns nothing about projects it cannot +/// The refusal for the project a note transfer is sent to, which the caller +/// named itself. A destination that does not exist is refused in the same +/// words, so a confined caller learns nothing about projects it cannot /// reach. -fn require_destination_in_scope( +const DESTINATION_OUT_OF_REACH: &str = + "the destination is a project outside this credential's reach"; + +/// The reach test, for every check that needs one: `Ok` when the grant is +/// unconfined, `project_id` is its own project, or its actor created +/// `project_id` (see the module docs). Anything else is refused with +/// `refusal`, followed by what the credential does cover. +/// +/// The read is one row, and only for a project other than the grant's own. +/// A project that does not exist is outside every reach. +fn require_in_scope( store: &Store, grant: &ControlGrant, - target_project_id: &str, + project_id: &str, + refusal: &str, ) -> Result<(), String> { let Some(allowed) = grant.project_scope() else { return Ok(()); }; - if within_reach(store, grant, allowed, target_project_id)? { - return Ok(()); - } - Err(denied(format!( - "the destination is a project outside this credential's reach; {}", - covers(allowed) - ))) -} - -/// Whether a grant confined to `allowed` reaches `project_id`: it is that -/// project, or one whose `created_by` is the grant's actor. The read is one -/// row, and only for a project other than the grant's own. A project that -/// does not exist is outside every reach. -fn within_reach( - store: &Store, - grant: &ControlGrant, - allowed: &str, - project_id: &str, -) -> Result<bool, String> { if allowed == project_id { - return Ok(true); + return Ok(()); } let creator = store .get_project(project_id) .map_err(|e| e.to_string())? .and_then(|project| project.created_by); - Ok(creator.is_some_and(|creator| creator == grant.actor.started_by())) + if creator.is_some_and(|creator| creator == grant.actor.started_by()) { + return Ok(()); + } + Err(denied(format!("{refusal}; {}", covers(allowed)))) } /// The project of each `imageIds` entry, for the two start commands: an @@ -511,21 +549,59 @@ fn require_images_in_scope( args: &Value, grant: &ControlGrant, ) -> Result<(), String> { - let Some(allowed) = grant.project_scope() else { + if grant.project_scope().is_none() { return Ok(()); - }; + } let image_ids: Option<Vec<String>> = opt_arg(args, "imageIds")?; for image_id in image_ids.unwrap_or_default() { let image = store .get_image(&image_id) .map_err(|e| e.to_string())? .ok_or_else(|| denied(format!("image {image_id} not found")))?; - if !within_reach(store, grant, allowed, &image.project_id)? { - return Err(denied(format!( - "image {image_id} belongs to another project; {}", - covers(allowed) - ))); + require_in_scope( + store, + grant, + &image.project_id, + &format!("image {image_id} belongs to another project"), + )?; + } + Ok(()) +} + +/// The project of each stored image or video `content` embeds, for the note +/// transfers: the transfer puts every one of them in the destination, so +/// media from a project outside the grant's reach cannot ride along in a +/// note's body. `content` is the body of `whose` ("the note"), a note in +/// `home_project_id`, which the caller has been found to reach. +/// +/// A reference with no row is passed over. The transfer leaves it as it is +/// and carries nothing for it. +fn require_note_media_in_scope( + store: &Store, + grant: &ControlGrant, + home_project_id: &str, + whose: &str, + content: &str, +) -> Result<(), String> { + if grant.project_scope().is_none() { + return Ok(()); + } + // Sorted, so the refusal names the same id every time. + let mut media_ids: Vec<String> = refs::media_ids(content).into_iter().collect(); + media_ids.sort(); + for media_id in media_ids { + let Some(image) = store.get_image(&media_id).map_err(|e| e.to_string())? else { + continue; + }; + if image.project_id == home_project_id { + continue; } + require_in_scope( + store, + grant, + &image.project_id, + &format!("{whose} embeds media {media_id}, which belongs to another project"), + )?; } Ok(()) } @@ -538,24 +614,6 @@ fn branch_project(store: &Store, branch_id: &str) -> Result<String, String> { .ok_or_else(|| denied(format!("branch {branch_id} not found"))) } -/// A branch note's project: its branch's. -fn note_project(store: &Store, note_id: &str) -> Result<String, String> { - let note = store - .get_note(note_id) - .map_err(|e| e.to_string())? - .ok_or_else(|| denied(format!("note {note_id} not found")))?; - branch_project(store, ¬e.branch_id) -} - -/// A project note's project, which its row names. -fn project_note_project(store: &Store, note_id: &str) -> Result<String, String> { - store - .get_project_note(note_id) - .map_err(|e| e.to_string())? - .map(|note| note.project_id) - .ok_or_else(|| denied(format!("project note {note_id} not found"))) -} - /// A session's project: its project note's or its branch's, else — for a /// diagram child, which has neither — its parent session's, one level up. fn session_project(store: &Store, session_id: &str) -> Result<String, String> { @@ -2111,6 +2169,156 @@ mod tests { } } + // ------------------------------------------------------------------- + // The media a transferred note embeds + // ------------------------------------------------------------------- + + fn embedding(image_ids: &[&str]) -> String { + image_ids + .iter() + .map(|id| format!("![shot](staged-media://{id}.png)")) + .collect::<Vec<_>>() + .join("\n\n") + } + + /// A branch note and a project note in project A whose bodies are + /// `body`, as (`cmd`, id argument, note id) for each of the four + /// transfers. + fn notes_embedding(f: &Fixture, body: &str) -> Vec<(&'static str, &'static str, String)> { + let branch_note = Note::new_standalone(&f.branch_a, "Findings", body); + f.store.create_note(&branch_note).unwrap(); + let project_note = ProjectNote::new(&f.project_a, "Plan", body); + f.store.create_project_note(&project_note).unwrap(); + note_transfers() + .into_iter() + .map(|(cmd, id_arg)| { + let id = match id_arg { + "noteId" => branch_note.id.clone(), + _ => project_note.id.clone(), + }; + (cmd, id_arg, id) + }) + .collect() + } + + /// The transfer puts every image a note's body embeds in the + /// destination, whichever project the image is in. One from a project + /// out of reach would ride along, so it is refused, as an attached + /// `imageIds` entry is. + #[test] + fn note_transfers_are_refused_for_embedded_media_from_a_project_out_of_reach() { + let f = fixture(); + let created = create_project_by(&f, "gamma", CALLER); + let g = scoped(&f.project_a); + // In reach beside it, so the refusal is for the one that is not. + let body = embedding(&[&f.image_a, &f.image_b, &created.image]); + for (cmd, id_arg, note_id) in notes_embedding(&f, &body) { + // Into a created project, and for a copy into the note's own: + // either way the image would be duplicated where the caller + // reaches it. + for target in [&created.project, &f.project_a] { + let err = check_with_store(cmd, &transfer(id_arg, ¬e_id, target), &g, &f.store) + .expect_err("should be denied"); + let whose = match id_arg { + "noteId" => "the note", + _ => "the project note", + }; + assert_eq!( + err, + format!( + "{SCOPE_DENIED_PREFIX}{whose} embeds media {}, which belongs to another \ + project; this credential covers project {} and the projects it created", + f.image_b, f.project_a + ), + "{cmd}" + ); + } + // The destination is judged first, in its own words. + assert_denied( + check_with_store(cmd, &transfer(id_arg, ¬e_id, &f.project_b), &g, &f.store), + "the destination is a project outside this credential's reach", + ); + // An unconfined grant carries what it likes. + check_with_store( + cmd, + &transfer(id_arg, ¬e_id, &created.project), + &ControlGrant::test_all_projects(), + &f.store, + ) + .unwrap_or_else(|e| panic!("{cmd} by an unconfined grant: {e}")); + } + } + + /// Media of the note's own project, of the caller's own project and of a + /// project it created are all within reach, wherever the note is. A + /// reference with no row carries nothing, and the transfer leaves it as + /// it is. + #[test] + fn note_transfers_carry_embedded_media_that_is_within_reach() { + let f = fixture(); + let created = create_project_by(&f, "gamma", CALLER); + let g = scoped(&f.project_a); + let body = embedding(&[&f.image_a, &created.image, "no-such-image"]); + for (cmd, id_arg, note_id) in notes_embedding(&f, &body) { + for target in [&created.project, &f.project_a] { + check_with_store(cmd, &transfer(id_arg, ¬e_id, target), &g, &f.store) + .unwrap_or_else(|e| panic!("{cmd} -> {target}: {e}")); + } + } + // A note in the created project that embeds the own project's image, + // sent home. + let from_created = Note::new_standalone(&created.branch, "Created", &body); + f.store.create_note(&from_created).unwrap(); + for cmd in ["move_note_to_project", "copy_note_to_project"] { + check_with_store( + cmd, + &transfer("noteId", &from_created.id, &f.project_a), + &g, + &f.store, + ) + .unwrap_or_else(|e| panic!("{cmd}: {e}")); + } + } + + /// A moved project note takes its child notes along, bodies and media + /// included, so a child's media is held to the same rule. A copy leaves + /// the children behind and is not. + #[test] + fn a_project_note_move_is_refused_for_media_a_child_note_embeds() { + let f = fixture(); + let created = create_project_by(&f, "gamma", CALLER); + let g = scoped(&f.project_a); + let parent = ProjectNote::new(&f.project_a, "Plan", "body"); + f.store.create_project_note(&parent).unwrap(); + let fine = Note::new_standalone(&f.branch_a, "Fine", &embedding(&[&f.image_a])) + .with_parent_project_note(&parent.id); + let carrier = Note::new_standalone(&f.branch_a, "Carrier", &embedding(&[&f.image_b])) + .with_parent_project_note(&parent.id); + f.store.create_note(&fine).unwrap(); + f.store.create_note(&carrier).unwrap(); + let args = transfer("projectNoteId", &parent.id, &created.project); + + let err = check_with_store("move_project_note_to_project", &args, &g, &f.store) + .expect_err("should be denied"); + assert_eq!( + err, + format!( + "{SCOPE_DENIED_PREFIX}its child note #note:{} embeds media {}, which belongs to \ + another project; this credential covers project {} and the projects it created", + carrier.id, f.image_b, f.project_a + ) + ); + check_with_store("copy_project_note_to_project", &args, &g, &f.store) + .expect("a copy takes no child along"); + check_with_store( + "move_project_note_to_project", + &args, + &ControlGrant::test_all_projects(), + &f.store, + ) + .expect("an unconfined grant is not held to reach"); + } + #[test] fn a_command_without_a_scope_row_is_refused() { let f = fixture(); diff --git a/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs b/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs new file mode 100644 index 000000000..b99d8fa53 --- /dev/null +++ b/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs @@ -0,0 +1,118 @@ +//! The bodies of the four note-transfer arms of `dispatch`: +//! `move_note_to_project`, `copy_note_to_project` and their project-note +//! twins. +//! +//! They live here, not in the arm table, so they can be run. `dispatch` +//! takes the app's own handle, which no test can make, and these take the +//! one thing the handle is for: `add_repo`, the step that adds a repo to +//! the destination. `dispatch` passes +//! [`add_repo_to_project`](crate::note_transfer::add_repo_to_project), and +//! a test passes a stand-in without git. Everything else an arm does is +//! here, for every caller: the arguments, the transfer, and the answer. +//! +//! One transfer, whoever asks. The caller decides nothing until the +//! transfer has returned, and then only how much it is told. A window has +//! the note open and is answered with the note alone, or with the +//! transfer's error as it is. A control caller named the note by id, so it +//! is told where the note landed and which repos the destination gained +//! (see [`control`](crate::note_transfer::control)), on failure as well. + +use std::future::Future; + +use serde_json::Value; + +use super::{arg, DispatchCaller}; +use crate::note_transfer::control::{self, AddedRepos}; +use crate::note_transfer::{transfer_branch_note, transfer_project_note, RepoKey, TransferMode}; +use crate::store::Store; + +/// The transfer a command asks for. `dispatch` routes only the four +/// commands here, a `move_` and a `copy_` for each kind of note. +fn mode_of(command: &str) -> TransferMode { + if command.starts_with("move_") { + TransferMode::Move + } else { + TransferMode::Copy + } +} + +/// `move_note_to_project` and `copy_note_to_project`. `add_repo` adds the +/// repo `RepoKey` names to the project whose id it is given. +pub(super) async fn branch_note<F, Fut>( + store: &Store, + command: &str, + args: &Value, + caller: &DispatchCaller, + add_repo: F, +) -> Result<Value, String> +where + F: Fn(String, RepoKey) -> Fut, + Fut: Future<Output = Result<(), String>>, +{ + let note_id: String = arg(args, "noteId")?; + let target_project_id: String = arg(args, "targetProjectId")?; + let mode = mode_of(command); + let added = AddedRepos::default(); + let note = transfer_branch_note(store, ¬e_id, &target_project_id, mode, |key| { + added.watch(key.clone(), add_repo(target_project_id.clone(), key)) + }) + .await + .map_err(|e| match caller { + // The repo this transfer added stays in the destination. A control + // caller cannot see that it did, so its error says so, as a + // project note's does for every caller. + DispatchCaller::Control(_) => added.explain(store, &target_project_id, e), + DispatchCaller::Web => e, + })?; + let branch_id = note.branch_id.clone(); + let item = match mode { + TransferMode::Move => crate::note_commands::note_to_timeline_item(store, note), + TransferMode::Copy => crate::note_commands::standalone_note_to_timeline_item(note), + }; + let item = serde_json::to_value(item).unwrap(); + Ok(match caller { + // A window has the note open and knows where it sent it. A control + // caller is told: the branch the note landed on and the repos the + // transfer added. + DispatchCaller::Control(_) => control::branch_note_answer(store, item, &branch_id, added), + DispatchCaller::Web => item, + }) +} + +/// `move_project_note_to_project` and `copy_project_note_to_project`. +/// `add_repo` is as in [`branch_note`], and runs once for each repo a moved +/// note's children need. +pub(super) async fn project_note<F, Fut>( + store: &Store, + command: &str, + args: &Value, + caller: &DispatchCaller, + add_repo: F, +) -> Result<Value, String> +where + F: Fn(String, RepoKey) -> Fut, + Fut: Future<Output = Result<(), String>>, +{ + let project_note_id: String = arg(args, "projectNoteId")?; + let target_project_id: String = arg(args, "targetProjectId")?; + let added = AddedRepos::default(); + // A failure here already names the repos added before it, for every + // caller: the transfer words that itself. + let note = transfer_project_note( + store, + &project_note_id, + &target_project_id, + mode_of(command), + |key| added.watch(key.clone(), add_repo(target_project_id.clone(), key)), + ) + .await?; + Ok(match caller { + // As for a branch note: a control caller is told which child notes + // came along, where each landed, and the repos they brought. + DispatchCaller::Control(_) => control::project_note_answer(store, note, added), + DispatchCaller::Web => serde_json::to_value(note).unwrap(), + }) +} + +#[cfg(test)] +mod tests; diff --git a/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs new file mode 100644 index 000000000..a0cd619ec --- /dev/null +++ b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs @@ -0,0 +1,702 @@ +//! The note-transfer arms, run the way `dispatch` runs them for a control +//! caller: the scope check, then the arm's body, with a stand-in for the +//! app's repo add. The transfers are real and so are the answers, which are +//! asserted as the JSON a caller receives. + +use std::collections::BTreeSet; +use std::path::Path; + +use serde_json::{json, Value}; + +use super::*; +use crate::control_server::{Access, Actor, ControlGrant, Scope}; +use crate::store::models::{ + Branch, Image, Note, Project, ProjectNote, ProjectRepo, Session, SessionStatus, +}; +use crate::web_server::control_scope::{self, SCOPE_DENIED_PREFIX}; + +/// What the stand-in for the app's repo add does. +#[derive(Clone, Copy)] +enum Add { + /// What the app's add leaves, minus git: the repo row and a branch that + /// tracks it. + Attach, + /// The add fails. + Fail, + /// The add succeeds and the session `Fixture::resumed` names is running + /// again when it returns, so the transfer's next read refuses the note. + AttachAndResume, +} + +/// The caller is a session in `own`. It created `created`, which tracks no +/// repo, and the user made `third`, which it does not reach. `own` tracks +/// `acme/widgets` at `apps/web` and `acme/gadgets`, with a branch on each. +struct Fixture { + store: Store, + own: Project, + created: Project, + third: Project, + widgets: Branch, + gadgets: Branch, + third_branch: Branch, + resumed: std::cell::RefCell<Option<String>>, +} + +const CALLER: &str = "session:caller"; + +fn fixture() -> Fixture { + let store = Store::in_memory().unwrap(); + let own = Project::named("own"); + let created = Project::named("created").with_created_by(CALLER); + let third = Project::named("third"); + for project in [&own, &created, &third] { + store.create_project(project).unwrap(); + } + let branch_on = |project: &Project, github_repo: &str, subpath: Option<&str>, name: &str| { + let repo = ProjectRepo::new(&project.id, github_repo, name, subpath.map(str::to_owned)); + store.create_project_repo(&repo).unwrap(); + let branch = Branch::new(&project.id, name, "origin/main").with_project_repo(&repo.id); + store.create_branch(&branch).unwrap(); + branch + }; + let widgets = branch_on(&own, "acme/widgets", Some("apps/web"), "feature"); + let gadgets = branch_on(&own, "acme/gadgets", None, "feature-2"); + let third_branch = branch_on(&third, "acme/widgets", Some("apps/web"), "theirs"); + Fixture { + store, + own, + created, + third, + widgets, + gadgets, + third_branch, + resumed: Default::default(), + } +} + +/// The caller's credential: a session's, confined to `own`. +fn session_grant(f: &Fixture) -> ControlGrant { + ControlGrant { + actor: Actor::Session { + session_id: "caller".to_string(), + epoch: 1, + }, + scope: Scope::Project(f.own.id.clone()), + branch_id: None, + access: Access::ReadWrite, + } +} + +impl Fixture { + /// A session that ran on `branch_id` and has completed. + fn finished_session(&self, branch_id: Option<&str>) -> Session { + let mut session = Session::new_running("write it up", Path::new("/tmp/wt")); + if let Some(branch_id) = branch_id { + session = session.with_branch(branch_id); + } + self.store.create_session(&session).unwrap(); + self.store + .update_session_status(&session.id, SessionStatus::Completed, None, None) + .unwrap(); + session + } + + /// A branch note a finished session wrote. + fn session_note(&self, branch: &Branch, title: &str) -> (Note, Session) { + let session = self.finished_session(Some(&branch.id)); + let note = Note::new_standalone(&branch.id, title, "body").with_session(&session.id); + self.store.create_note(¬e).unwrap(); + (note, session) + } + + /// A project note in `own` a finished session wrote, with a child note + /// on each of `own`'s branches, each with its own finished session. + fn family(&self) -> (ProjectNote, Vec<Note>) { + let session = self.finished_session(None); + let parent = ProjectNote::new(&self.own.id, "Plan", "body").with_session(&session.id); + self.store.create_project_note(&parent).unwrap(); + let children = [(&self.widgets, "Web"), (&self.gadgets, "Gadgets")] + .into_iter() + .map(|(branch, title)| { + let session = self.finished_session(Some(&branch.id)); + let child = Note::new_standalone(&branch.id, title, "child body") + .with_session(&session.id) + .with_parent_project_note(&parent.id); + self.store.create_note(&child).unwrap(); + child + }) + .collect(); + (parent, children) + } + + /// An image row in `project_id`. No file is written: these tests stop at + /// the scope check or carry no media. + fn image_in(&self, project_id: &str, branch_id: Option<&str>) -> Image { + let image = Image::new(branch_id, project_id, "shot.png", "image/png", 1, false); + self.store.create_image(&image).unwrap(); + image + } + + fn attach(&self, project_id: &str, key: RepoKey) -> Result<(), String> { + let name = format!("landing-{}", key.github_repo.replace('/', "-")); + let repo = ProjectRepo::new(project_id, &key.github_repo, &name, key.subpath); + self.store + .create_project_repo(&repo) + .map_err(|e| e.to_string())?; + let branch = Branch::new(project_id, &name, "origin/main").with_project_repo(&repo.id); + self.store.create_branch(&branch).map_err(|e| e.to_string()) + } + + fn add(&self, how: Add, project_id: &str, key: RepoKey) -> Result<(), String> { + match how { + Add::Attach => self.attach(project_id, key), + Add::Fail => Err("clone failed".to_string()), + Add::AttachAndResume => { + let session_id = self.resumed.borrow().clone().expect("a session to resume"); + self.store + .update_session_status(&session_id, SessionStatus::Running, None, None) + .unwrap(); + self.attach(project_id, key) + } + } + } + + /// `command` as `dispatch` runs it: for a control caller the scope check + /// ahead of every arm, then the arm's body. + async fn dispatch( + &self, + caller: DispatchCaller, + command: &str, + args: Value, + how: Add, + ) -> Result<Value, String> { + if let DispatchCaller::Control(grant) = &caller { + control_scope::check_with_store(command, &args, grant, &self.store)?; + } + let add_repo = + |project_id: String, key: RepoKey| std::future::ready(self.add(how, &project_id, key)); + match command { + "move_note_to_project" | "copy_note_to_project" => { + branch_note(&self.store, command, &args, &caller, add_repo).await + } + "move_project_note_to_project" | "copy_project_note_to_project" => { + project_note(&self.store, command, &args, &caller, add_repo).await + } + other => panic!("{other} is not a note transfer"), + } + } + + /// [`Self::dispatch`] as the session, with a repo add that works. + async fn control(&self, command: &str, args: Value) -> Result<Value, String> { + self.dispatch( + DispatchCaller::Control(session_grant(self)), + command, + args, + Add::Attach, + ) + .await + } + + fn branch_of(&self, note_id: &str) -> String { + self.store.get_note(note_id).unwrap().unwrap().branch_id + } +} + +fn keys(value: &Value) -> BTreeSet<&str> { + value + .as_object() + .unwrap_or_else(|| panic!("an object: {value}")) + .keys() + .map(String::as_str) + .collect() +} + +/// The fields of a branch note as every caller is answered one: the +/// timeline's note item. +const NOTE_ITEM_KEYS: [&str; 19] = [ + "chatReadAt", + "completedAt", + "completionReason", + "content", + "createdAt", + "id", + "isPollingForNote", + "lastChatMessageAt", + "rateLimitKind", + "rateLimitResetsAt", + "readAt", + "sessionErrorMessage", + "sessionId", + "sessionStatus", + "subtype", + "suggestedNextCommitStep", + "suggestedNextNoteStep", + "title", + "updatedAt", +]; + +fn widgets_key() -> Value { + json!({ "githubRepo": "acme/widgets", "subpath": "apps/web" }) +} + +fn gadgets_key() -> Value { + json!({ "githubRepo": "acme/gadgets", "subpath": null }) +} + +// --------------------------------------------------------------------------- +// Branch notes +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn a_moved_branch_note_is_answered_with_its_note_item_and_where_it_landed() { + let f = fixture(); + let (note, session) = f.session_note(&f.widgets, "Findings"); + + let answer = f + .control( + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + + assert_eq!( + keys(&answer), + BTreeSet::from(["addedRepos", "branch", "note", "repo"]) + ); + // The note is the item a window gets, with its session resolved. + assert_eq!(keys(&answer["note"]), BTreeSet::from(NOTE_ITEM_KEYS)); + assert_eq!(answer["note"]["id"], note.id, "a move keeps the note's id"); + assert_eq!(answer["note"]["title"], "Findings"); + assert_eq!(answer["note"]["content"], "body"); + assert_eq!(answer["note"]["sessionId"], session.id); + assert_eq!(answer["note"]["sessionStatus"], "completed"); + // Where it landed, as the branch list and the repo list give a row. + let landed = f.branch_of(¬e.id); + assert_eq!(answer["branch"]["id"], landed); + assert_eq!(answer["branch"]["projectId"], f.created.id); + assert_eq!(answer["branch"]["branchName"], "landing-acme-widgets"); + assert_eq!(answer["branch"].get("worktreePath"), Some(&Value::Null)); + assert_eq!(answer["repo"]["id"], answer["branch"]["projectRepoId"]); + assert_eq!(answer["repo"]["projectId"], f.created.id); + assert_eq!(answer["repo"]["githubRepo"], "acme/widgets"); + assert_eq!(answer["repo"]["subpath"], "apps/web"); + assert_eq!(answer["addedRepos"], json!([widgets_key()])); +} + +#[tokio::test] +async fn a_copied_branch_note_is_answered_with_the_new_standalone_note() { + let f = fixture(); + let (note, _) = f.session_note(&f.widgets, "Findings"); + + let answer = f + .control( + "copy_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + + assert_eq!( + keys(&answer), + BTreeSet::from(["addedRepos", "branch", "note", "repo"]) + ); + assert_eq!(keys(&answer["note"]), BTreeSet::from(NOTE_ITEM_KEYS)); + let copy_id = answer["note"]["id"].as_str().unwrap(); + assert_ne!(copy_id, note.id, "a copy is a new note"); + assert_eq!(answer["note"]["title"], "Findings"); + assert_eq!(answer["note"]["sessionId"], Value::Null); + assert_eq!(answer["note"]["sessionStatus"], Value::Null); + assert_eq!(answer["note"]["subtype"], "written"); + assert_eq!(answer["branch"]["id"], f.branch_of(copy_id)); + assert_eq!(answer["branch"]["projectId"], f.created.id); + assert_eq!(answer["repo"]["githubRepo"], "acme/widgets"); + assert_eq!(answer["addedRepos"], json!([widgets_key()])); + assert_eq!(f.branch_of(¬e.id), f.widgets.id, "the original stays"); +} + +/// The transfer is the one a window runs, and a window is answered with the +/// note alone, as it was before a control caller could ask. +#[tokio::test] +async fn a_window_is_answered_with_the_note_alone() { + let f = fixture(); + let (note, _) = f.session_note(&f.widgets, "Findings"); + let answer = f + .dispatch( + DispatchCaller::Web, + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + Add::Attach, + ) + .await + .unwrap(); + assert_eq!(keys(&answer), BTreeSet::from(NOTE_ITEM_KEYS)); + assert_eq!(answer["id"], note.id); + + let (parent, _) = f.family(); + let before = f.store.get_project_note(&parent.id).unwrap().unwrap(); + let answer = f + .dispatch( + DispatchCaller::Web, + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + Add::Attach, + ) + .await + .unwrap(); + assert_eq!(keys(&answer), keys(&serde_json::to_value(&before).unwrap())); + assert_eq!(answer["id"], parent.id); + assert_eq!(answer["projectId"], f.created.id); +} + +// --------------------------------------------------------------------------- +// Project notes +// --------------------------------------------------------------------------- + +/// A moved project note keeps its session, and the answer says how that +/// session stands. The row the move returns does not, so the answer reads +/// the note again. +#[tokio::test] +async fn a_moved_project_note_is_answered_with_its_session_status_and_its_children() { + let f = fixture(); + let (parent, children) = f.family(); + // The destination already tracks one of the two repos. + f.attach( + &f.created.id, + RepoKey { + github_repo: "acme/widgets".into(), + subpath: Some("apps/web".into()), + }, + ) + .unwrap(); + + let answer = f + .control( + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + + assert_eq!( + keys(&answer), + BTreeSet::from(["addedRepos", "children", "note"]) + ); + assert_eq!(answer["note"]["id"], parent.id); + assert_eq!(answer["note"]["projectId"], f.created.id); + assert_eq!(answer["note"]["title"], "Plan"); + assert_eq!( + answer["note"]["sessionId"], + parent.session_id.clone().unwrap() + ); + assert_eq!(answer["note"]["sessionStatus"], "completed"); + // The note reads as the project's note list gives it. + let listed = f + .store + .list_project_notes_with_status(&f.created.id) + .unwrap(); + assert_eq!(answer["note"], serde_json::to_value(&listed[0]).unwrap()); + + // Each child, by its reference, on the destination's branch for its + // repo. + let listed: Vec<&Value> = answer["children"].as_array().unwrap().iter().collect(); + assert_eq!(listed.len(), 2); + for (child, title, github_repo, subpath, branch_name) in [ + ( + &children[0], + "Web", + "acme/widgets", + json!("apps/web"), + "landing-acme-widgets", + ), + ( + &children[1], + "Gadgets", + "acme/gadgets", + Value::Null, + "landing-acme-gadgets", + ), + ] { + let reference = format!("#note:{}", child.id); + let row = listed + .iter() + .find(|row| row["reference"] == reference.as_str()) + .unwrap_or_else(|| panic!("{reference} is not among {listed:?}")); + assert_eq!( + keys(row), + BTreeSet::from(["branch", "reference", "repo", "title"]) + ); + assert_eq!(row["title"], title); + assert_eq!(row["branch"]["id"], f.branch_of(&child.id)); + assert_eq!(row["branch"]["projectId"], f.created.id); + assert_eq!(row["branch"]["branchName"], branch_name); + assert_eq!(row["repo"]["id"], row["branch"]["projectRepoId"]); + assert_eq!(row["repo"]["githubRepo"], github_repo); + assert_eq!(row["repo"]["subpath"], subpath); + } + // Only the repo the destination lacked was added. + assert_eq!(answer["addedRepos"], json!([gadgets_key()])); +} + +#[tokio::test] +async fn a_copied_project_note_is_answered_without_children_or_repos() { + let f = fixture(); + let (parent, children) = f.family(); + + let answer = f + .control( + "copy_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + + assert_eq!( + keys(&answer), + BTreeSet::from(["addedRepos", "children", "note"]) + ); + assert_ne!(answer["note"]["id"], parent.id); + assert_eq!(answer["note"]["projectId"], f.created.id); + assert_eq!(answer["note"]["sessionId"], Value::Null); + assert_eq!(answer["note"]["sessionStatus"], Value::Null); + assert_eq!(answer["children"], json!([])); + assert_eq!(answer["addedRepos"], json!([])); + for child in &children { + assert_eq!(f.branch_of(&child.id), child.branch_id, "children stay"); + } +} + +// --------------------------------------------------------------------------- +// A failure after a repo was added +// --------------------------------------------------------------------------- + +/// The repo is in the destination by the time the transfer refuses the +/// note. A control caller cannot see that, so its error says so. A window's +/// is the transfer's, as it was. +#[tokio::test] +async fn a_branch_note_failure_after_the_repo_was_added_names_it_to_a_control_caller() { + const REFUSAL: &str = + "\"Findings\"'s session is running again; wait for it to finish before moving the note."; + for (caller_is_control, expected) in [ + ( + true, + format!( + "{REFUSAL} acme/widgets at apps/web was added to created along the way and \ + remains tracked there." + ), + ), + (false, REFUSAL.to_string()), + ] { + let f = fixture(); + let (note, session) = f.session_note(&f.widgets, "Findings"); + *f.resumed.borrow_mut() = Some(session.id.clone()); + let caller = if caller_is_control { + DispatchCaller::Control(session_grant(&f)) + } else { + DispatchCaller::Web + }; + + let err = f + .dispatch( + caller, + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + Add::AttachAndResume, + ) + .await + .unwrap_err(); + + assert_eq!(err, expected); + assert_eq!(f.branch_of(¬e.id), f.widgets.id, "the note stays put"); + assert!( + f.store + .find_project_repo(&f.created.id, "acme/widgets", Some("apps/web")) + .unwrap() + .is_some(), + "the repo stays added" + ); + } +} + +/// A project note's failure names the added repo for every caller, in the +/// transfer's own words. The control answer must not say it a second time. +#[tokio::test] +async fn a_project_note_failure_after_a_repo_was_added_names_it_once() { + let f = fixture(); + let (parent, children) = f.family(); + *f.resumed.borrow_mut() = parent.session_id.clone(); + + let err = f + .dispatch( + DispatchCaller::Control(session_grant(&f)), + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + Add::AttachAndResume, + ) + .await + .unwrap_err(); + + // The children's repos are added in the order the children are listed. + let said = |first: &str, second: &str| { + format!( + "\"Plan\"'s session is running again; wait for it to finish before moving the \ + note. {first} and {second} were added to created along the way and remain tracked \ + there." + ) + }; + assert!( + err == said("acme/widgets at apps/web", "acme/gadgets") + || err == said("acme/gadgets", "acme/widgets at apps/web"), + "{err}" + ); + assert_eq!( + f.store + .get_project_note(&parent.id) + .unwrap() + .unwrap() + .project_id, + f.own.id + ); + for child in &children { + assert_eq!(f.branch_of(&child.id), child.branch_id); + } +} + +/// A repo whose add failed was not added, and the error does not say it +/// was. +#[tokio::test] +async fn a_failed_repo_add_is_reported_as_the_transfer_words_it() { + let f = fixture(); + let (note, _) = f.session_note(&f.widgets, "Findings"); + + let err = f + .dispatch( + DispatchCaller::Control(session_grant(&f)), + "copy_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + Add::Fail, + ) + .await + .unwrap_err(); + + assert_eq!( + err, + "Could not add acme/widgets at apps/web to created: clone failed" + ); +} + +// --------------------------------------------------------------------------- +// Scope, end to end +// --------------------------------------------------------------------------- + +/// A note in the caller's own project whose body embeds media from a +/// project out of its reach is refused before the transfer runs: nothing +/// moves, and nothing of that media lands in the destination. +#[tokio::test] +async fn media_from_a_project_out_of_reach_stops_the_transfer_before_it_runs() { + let f = fixture(); + let foreign = f.image_in(&f.third.id, Some(&f.third_branch.id)); + let body = format!("see ![theirs](staged-media://{}.png)", foreign.id); + let (note, _) = f.session_note(&f.widgets, "Findings"); + f.store.update_note_content(¬e.id, &body).unwrap(); + let (parent, children) = f.family(); + f.store.update_note_content(&children[1].id, &body).unwrap(); + + for (command, args) in [ + ( + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ), + ( + "copy_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ), + // Into the note's own project too: a copy there duplicates the + // media just the same. + ( + "copy_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.own.id }), + ), + // Through a child note, which a move takes along. + ( + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ), + ] { + let err = f.control(command, args).await.unwrap_err(); + assert!( + err.starts_with(SCOPE_DENIED_PREFIX), + "{command} must be refused by scope: {err}" + ); + assert!( + err.contains(&format!("embeds media {}", foreign.id)) + && err.contains("belongs to another project"), + "{command}: {err}" + ); + } + + assert_eq!(f.branch_of(¬e.id), f.widgets.id); + assert_eq!( + f.store + .get_project_note(&parent.id) + .unwrap() + .unwrap() + .project_id, + f.own.id + ); + assert!( + f.store + .list_project_repos(&f.created.id) + .unwrap() + .is_empty(), + "a refused transfer adds no repo" + ); + let still = f.store.get_image(&foreign.id).unwrap().unwrap(); + assert_eq!(still.project_id, f.third.id); + + // A copy of the project note leaves its children where they are, so + // what a child embeds is not the copy's to answer for. + let answer = f + .control( + "copy_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + assert_eq!(answer["children"], json!([])); +} + +/// A note the confined caller cannot be shown is a scope refusal, whether +/// its id is unknown or names the other kind of note. An unconfined caller +/// is told by the transfer. +#[tokio::test] +async fn a_note_id_that_names_no_note_of_that_kind_is_refused_by_scope_when_confined() { + let f = fixture(); + let (parent, _) = f.family(); + for (command, args, wording) in [ + ( + "move_note_to_project", + json!({ "noteId": "nope", "targetProjectId": f.created.id }), + "note nope not found".to_string(), + ), + ( + "copy_note_to_project", + json!({ "noteId": parent.id, "targetProjectId": f.created.id }), + format!("note {} not found", parent.id), + ), + ] { + let err = f.control(command, args.clone()).await.unwrap_err(); + assert_eq!(err, format!("{SCOPE_DENIED_PREFIX}{wording}")); + + let err = f + .dispatch( + DispatchCaller::Control(ControlGrant::test_all_projects()), + command, + args, + Add::Attach, + ) + .await + .unwrap_err(); + assert!(err.starts_with("Note not found: "), "{err}"); + } +} From b09b00a7b34275474ea204dca7da1fbfae110edd Mon Sep 17 00:00:00 2001 From: Matt Toohey <contact@matttoohey.com> Date: Thu, 19 Nov 2026 12:36:50 +1100 Subject: [PATCH 3/4] fix(staged): answer unreadable child notes as null and pin note answers to a fixture Review beb7cbf7 of 9e63668f left small items on `stagedctl note move` and `stagedctl note copy`. This applies them. The transfer, the Tauri commands, what a window is answered and the UI are unchanged. Children that cannot be read back. A project note's control answer listed its child notes by reading them after the transfer committed, and a failed read was answered as an empty list. A caller could not tell that from a note with no children, though the children had moved. `project_note_answer` now answers `children: null` for a failed read, as `branch` and `repo` already answer `null` for a row that cannot be read back. The docs describe the list as what it is: the note's children as they read after the transfer, not the move's own plan. This makes a field of a backend answer nullable, which AGENTS.md asks a human to review before it lands. The CLI reads the key as absent, `null` or a list (`Children`). A move whose answer has `children: null` prints "child notes: the app could not read them back; any the note has moved with it". A copy prints nothing, since its note is new and has none. `--json` passes `null` through as the app said it. `note move --help` and the session guide say so, and the help pin is refreshed. Dangling media references in tests. The scope test for a reference with no row used `no-such-image`, which is not a UUID, so it was never a media reference and never reached the row lookup in `require_note_media_in_scope`. It now uses a fresh UUID and asserts the body parses to that id. The end-to-end test the review names, `media_from_a_project_out_of_reach_stops_the_transfer_before_it_runs`, embeds a well-formed id with no row that sorts ahead of the foreign one, so the check passes over it before it refuses. A new arm test moves and copies a branch note, and moves a project note with a child, whose bodies embed such an id, as a confined caller: each transfer goes through and the reference is left as written. With the skip turned into a refusal, the scope test and the new arm test both fail. A media row whose file is gone. The scope module docs now say the check goes by the row: a row with no file carries nothing either, so a note the user moved after a file was lost can be refused for media that would not have travelled. One fixture for the answer's names. stagedctl pinned the answer's keys by matching formatted source lines of `control.rs`. That test is gone. `src/note_transfer/control/fixtures/answers.json` holds one branch-note and one project-note answer. An arm test runs both moves for real, names the ids, zeroes the timestamps and asserts the result equal to the file (`STAGED_UPDATE_NOTE_TRANSFER_ANSWERS=1` rewrites it). The CLI tests answer with the same file and assert the full output, where every line is a field `Landed` reads, and that each key of the answer comes out under `--json`. Tests removed. The body half of the source pin in `web_server.rs` matched literal lines of the arm bodies, which the arm tests prove with real transfers for both callers. The arm-delegation and desktop-command halves stay, since `dispatch` cannot be run. The hand-built `{ id, title }` helper in `note_transfer/control/tests.rs` and its three tests are gone too. The one case only they covered, a branch note sent to a project that already tracks its repo, is now an arm test. Left for the human reviewer, as asked: the residual media race while a transfer adds a repo (`stage_media` is untouched), and whether a confined caller may move a child note away from its parent. Checked from this worktree, built into a private cargo target so the running app's binaries were not replaced: `cargo fmt --check`, `cargo clippy --workspace -- -D warnings`, all 246 stagedctl unit tests and the help pin, and the app's `note_transfer`, `web_server`, `control_server` and `note_media` tests (330). The rest of the app's suite was not run locally. Signed-off-by: Matt Toohey <contact@matttoohey.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src-tauri/crates/stagedctl/src/cli.rs | 3 + .../src-tauri/crates/stagedctl/src/notes.rs | 89 ++++-- .../crates/stagedctl/src/notes/tests.rs | 152 ++++++++-- .../crates/stagedctl/tests/fixtures/help.txt | 3 + .../src-tauri/resources/stagedctl/guide.md | 10 +- .../src-tauri/src/note_transfer/control.rs | 55 ++-- .../control/fixtures/answers.json | 188 +++++++++++++ .../src/note_transfer/control/tests.rs | 130 ++++----- apps/staged/src-tauri/src/web_server.rs | 37 +-- .../src-tauri/src/web_server/control_scope.rs | 22 +- .../src/web_server/note_transfer_arms.rs | 4 +- .../web_server/note_transfer_arms/tests.rs | 262 +++++++++++++++++- 12 files changed, 756 insertions(+), 199 deletions(-) create mode 100644 apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json diff --git a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs index 3afa3c0f2..6840e4768 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/cli.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/cli.rs @@ -1048,6 +1048,9 @@ on its kind: branch for its repo and subpath, still linked to the project note. The output lists each child by its reference, with the repo and branch it landed on. + If the app cannot read the children back once the + move is done, the output says so and --json has + `children: null`. They moved all the same. Commits and code reviews are not part of a note. They stay on the branch they were made on. diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs index e9cbcb900..01547c4a3 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs @@ -10,12 +10,12 @@ //! names, answered from a read the caller can make anyway. //! //! Each verb is one write with no read after it. The app's answer carries -//! the branch the note landed on, the child notes a moved project note -//! took along, and the repos the transfer added, which only the transfer -//! knows. An answer that cannot be read is a [`CtlError::Partial`], so the -//! caller still learns the write landed. +//! the branch the note landed on, a moved project note's child notes as +//! they read after the move, and the repos the transfer added, which only +//! the transfer knows. An answer that cannot be read is a +//! [`CtlError::Partial`], so the caller still learns the write landed. -use serde::Deserialize; +use serde::{Deserialize, Deserializer}; use serde_json::{json, Map, Value}; use crate::client::{Client, CtlError}; @@ -159,8 +159,8 @@ impl NoteRef { /// transfer and the repos the transfer added to the destination. For a /// branch note, also the branch it landed on and the repo that branch /// tracks. Either is `null` when the app could not read the row back after -/// the transfer committed. For a project note, also the child notes that -/// came with it, which is none for a copy. +/// the transfer committed. For a project note, also its child notes as the +/// app read them after the transfer ([`Children`]). #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct Landed { @@ -170,14 +170,41 @@ struct Landed { #[serde(default)] repo: Option<RepoName>, #[serde(default)] - children: Vec<LandedChild>, + children: Children, #[serde(default)] added_repos: Vec<RepoName>, } -/// A child note that moved with its project note: its hashtag reference, -/// which the move does not change, and where it is now, as for a branch -/// note. +/// The `children` of an answer: a project note's child notes, as the app +/// read them once the transfer had committed. +#[derive(Debug, Clone, Default)] +enum Children { + /// The answer has no `children`. A branch note's does not. + #[default] + Absent, + /// `null`: the app could not read the list back. This is not an empty + /// list. A move takes every child or is refused, so whatever children + /// the note has moved with it. + Unread, + /// The children, which is none for a copy and for a note without any. + Listed(Vec<LandedChild>), +} + +impl<'de> Deserialize<'de> for Children { + /// Reads a key that is there: a list, or `null`. A key that is not + /// there is the field's default, [`Children::Absent`]. + fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { + Ok( + match Option::<Vec<LandedChild>>::deserialize(deserializer)? { + Some(children) => Self::Listed(children), + None => Self::Unread, + }, + ) + } +} + +/// A child note of a moved project note: its hashtag reference, which the +/// move does not change, and where it is now, as for a branch note. #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] struct LandedChild { @@ -276,11 +303,13 @@ pub(crate) fn transfer_with( } /// The output of both verbs: the note's reference, the project it is in -/// now, the branch it landed on, each child note that came with a project -/// note and the branch that landed on, and each repo the transfer added. -/// `--json` is `{ ok, mode, projectId, reference, note, addedRepos }` with -/// the app's rows. A branch note has `branch` and `repo` as well. A project -/// note has `children`, each `{ reference, title, branch, repo }`. +/// now, the branch it landed on, each child note of a moved project note +/// and the branch that is on, and each repo the transfer added. `--json` is +/// `{ ok, mode, projectId, reference, note, addedRepos }` with the app's +/// rows. A branch note has `branch` and `repo` as well. A project note has +/// `children`, each `{ reference, title, branch, repo }`, or `null` when +/// the app could not read them back. A move then says so in a line of its +/// own, since the children moved all the same. A copy has none to report. /// `reference` is the hashtag reference of the note where it is now: the /// same note after a move, the new one after a copy. fn render( @@ -312,16 +341,26 @@ fn render( if let Some(place) = landing(landed.branch.as_ref(), address.as_deref()) { human.push(format!(" landed on: {place}")); } - for child in &landed.children { - let mut line = format!(" child note {}", child.reference); - if !child.title.trim().is_empty() { - line.push_str(&format!(" {:?}", child.title)); - } - let address = child.repo.as_ref().map(RepoName::address); - if let Some(place) = landing(child.branch.as_ref(), address.as_deref()) { - line.push_str(&format!(" landed on: {place}")); + match &landed.children { + Children::Listed(children) => { + for child in children { + let mut line = format!(" child note {}", child.reference); + if !child.title.trim().is_empty() { + line.push_str(&format!(" {:?}", child.title)); + } + let address = child.repo.as_ref().map(RepoName::address); + if let Some(place) = landing(child.branch.as_ref(), address.as_deref()) { + line.push_str(&format!(" landed on: {place}")); + } + human.push(line); + } } - human.push(line); + Children::Unread if transfer == Transfer::Move => human.push( + " child notes: the app could not read them back; any the note has moved with it" + .to_string(), + ), + // A copy is a new note with no children, read or not. + Children::Unread | Children::Absent => {} } for repo in &landed.added_repos { human.push(format!( diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs index ec72d5559..033968628 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs @@ -425,6 +425,47 @@ fn a_child_whose_landing_rows_could_not_be_read_back_is_still_listed() { ); } +#[test] +fn children_the_app_could_not_read_back_are_not_reported_as_none() { + // `children: null` is the app saying it could not list them once the + // transfer had committed. That is not a note without children. + let answer = json!({ + "note": { "id": "pn1", "projectId": "p2", "title": "Plan" }, + "children": null, + "addedRepos": [{ "githubRepo": "acme/gadgets", "subpath": null }], + }); + let app = App::with_projects().answer("move_project_note_to_project", answer.clone()); + let out = transfer_with(app.invoke(), Transfer::Move, &project_note(), "Target").unwrap(); + assert_eq!( + out.human, + "project note #project-note:pn1 moved to project \"Target\"\n\ + \x20 project id: p2\n\ + \x20 title: Plan\n\ + \x20 child notes: the app could not read them back; any the note has moved with it\n\ + \x20 added repo: acme/gadgets (the project did not track it; its branch is set up in \ + the background)\n\ + next: stagedctl timeline show p2" + ); + // Under --json it stays what the app said, and is not turned into a + // list or left out. + assert_eq!(out.json.get("children"), Some(&Value::Null)); + assert_eq!(out.json["ok"], true); + + // A moved note that has no children says nothing about them. + let mut none = answer.clone(); + none["children"] = json!([]); + let app = App::with_projects().answer("move_project_note_to_project", none); + let out = transfer_with(app.invoke(), Transfer::Move, &project_note(), "Target").unwrap(); + assert!(!out.human.contains("child note"), "{}", out.human); + assert_eq!(out.json["children"], json!([])); + + // A copy is a new note, which has no children to lose track of. + let app = App::with_projects().answer("copy_project_note_to_project", answer); + let out = transfer_with(app.invoke(), Transfer::Copy, &project_note(), "Target").unwrap(); + assert!(!out.human.contains("child note"), "{}", out.human); + assert_eq!(out.json.get("children"), Some(&Value::Null)); +} + #[test] fn an_answer_without_children_lists_none() { // A branch note's answer has no `children`, and none is added to it. @@ -681,23 +722,93 @@ fn the_requests_use_the_argument_names_the_apps_commands_read() { } } -/// What the output reads from the app's answer is what the app puts there. +/// One answer of each kind, as the app gives it to a control caller. The +/// app's own tests run a real move of a branch note and of a project note +/// and hold the answers to this file +/// (`web_server/note_transfer_arms/tests.rs`), with ids named and +/// timestamps zeroed. Reading the same file here holds the names the CLI +/// reads to the names the app writes. +const APP_ANSWERS: &str = + include_str!("../../../../src/note_transfer/control/fixtures/answers.json"); + +/// The app answering `command` with its `kind` of answer from +/// [`APP_ANSWERS`], for a caller whose one project is the destination the +/// answers name. +fn app_answering(command: &'static str, kind: &str) -> (App, Value) { + let answers: Value = serde_json::from_str(APP_ANSWERS).expect("the app's answers are JSON"); + let answer = answers[kind].clone(); + assert!(answer.is_object(), "the app's answers have no {kind}"); + let app = App::default() + .answer( + "list_projects", + json!([{ "id": "project-created", "name": "created", "location": "local" }]), + ) + .answer(command, answer.clone()); + (app, answer) +} + +/// Every key of the app's answer comes out under `--json` as it came in. +/// A key the app adds fails here until the output carries it. +fn assert_passed_through(out: &CmdOutput, answer: &Value) { + for (key, value) in answer.as_object().unwrap() { + assert_eq!(out.json.get(key), Some(value), "{key} under --json"); + } +} + +/// Everything the output says about a branch note comes out of the app's +/// answer. Each line below is a field `Landed` reads, and every one of +/// those is optional to it, so a name the app no longer writes would drop +/// its line here and nowhere else. #[test] -fn the_answer_is_read_under_the_names_the_app_writes() { - let control = include_str!("../../../../src/note_transfer/control.rs"); - for written in [ - "\"note\": note,", - "\"branch\": branch,", - "\"repo\": repo,", - "\"children\": children,", - "\"addedRepos\": added.into_json(),", - "\"reference\": format!(\"#note:{}\", child.id),", - "\"title\": child.title,", - "json!({ \"githubRepo\": key.github_repo, \"subpath\": key.subpath })", - ] { - assert!( - control.contains(written), - "the app's answer no longer has {written}; read `Landed` again" +fn the_apps_answer_for_a_branch_note_is_read_in_full() { + let (app, answer) = app_answering("move_note_to_project", "branchNote"); + let note = NoteRef::Branch("note-findings".to_string()); + let out = transfer_with(app.invoke(), Transfer::Move, ¬e, "created").unwrap(); + + assert_eq!( + out.human, + "note #note:note-findings moved to project \"created\"\n\ + \x20 project id: project-created\n\ + \x20 title: Findings\n\ + \x20 landed on: acme/widgets:apps/web, branch landing-acme-widgets\n\ + \x20 added repo: acme/widgets:apps/web (the project did not track it; its branch is \ + set up in the background)\n\ + next: stagedctl timeline show project-created --repo acme/widgets:apps/web --branch \ + landing-acme-widgets" + ); + // The reference is made from the id the answer's note has. + assert_eq!(out.json["reference"], "#note:note-findings"); + assert_passed_through(&out, &answer); + assert_eq!(out.json.get("children"), None, "a branch note has none"); +} + +/// As above, for a project note and the children that moved with it. +#[test] +fn the_apps_answer_for_a_project_note_is_read_in_full() { + let (app, answer) = app_answering("move_project_note_to_project", "projectNote"); + let note = NoteRef::Project("project-note-plan".to_string()); + let out = transfer_with(app.invoke(), Transfer::Move, ¬e, "created").unwrap(); + + assert_eq!( + out.human, + "project note #project-note:project-note-plan moved to project \"created\"\n\ + \x20 project id: project-created\n\ + \x20 title: Plan\n\ + \x20 child note #note:note-gadgets \"Gadgets\" landed on: acme/gadgets, branch \ + landing-acme-gadgets\n\ + \x20 child note #note:note-web \"Web\" landed on: acme/widgets:apps/web, branch \ + landing-acme-widgets\n\ + \x20 added repo: acme/gadgets (the project did not track it; its branch is set up in \ + the background)\n\ + next: stagedctl timeline show project-created" + ); + assert_eq!(out.json["reference"], "#project-note:project-note-plan"); + assert_passed_through(&out, &answer); + for absent in ["branch", "repo"] { + assert_eq!( + out.json.get(absent), + None, + "a project note is on no {absent}" ); } } @@ -889,11 +1000,17 @@ fn help_states_the_transfers_rules_as_the_app_has_them() { ); } - // The output of a project note's move lists its children. + // The output of a project note's move lists its children, or says that + // the app could not. assert!( move_help.contains("The output lists each child by its\n reference"), "{move_help}" ); + assert!( + move_help + .contains("--json has\n `children: null`. They moved all the same."), + "{move_help}" + ); } #[test] @@ -911,6 +1028,7 @@ fn the_guide_describes_both_verbs() { "both projects", "the user can move the note back or delete the copy", "The output lists each child by its reference", + "(`children: null` under `--json`), they moved all the same", "the error names it", "Exit 4 (`scope_denied`)", "A reference that names no note of its kind also exits 4", diff --git a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt index 9b985b145..5cb3bc52e 100644 --- a/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt +++ b/apps/staged/src-tauri/crates/stagedctl/tests/fixtures/help.txt @@ -842,6 +842,9 @@ on its kind: branch for its repo and subpath, still linked to the project note. The output lists each child by its reference, with the repo and branch it landed on. + If the app cannot read the children back once the + move is done, the output says so and --json has + `children: null`. They moved all the same. Commits and code reviews are not part of a note. They stay on the branch they were made on. diff --git a/apps/staged/src-tauri/resources/stagedctl/guide.md b/apps/staged/src-tauri/resources/stagedctl/guide.md index ff4a3cc7d..cf4f87b01 100644 --- a/apps/staged/src-tauri/resources/stagedctl/guide.md +++ b/apps/staged/src-tauri/resources/stagedctl/guide.md @@ -151,10 +151,12 @@ before choosing: - A move takes the note itself. It keeps its id and its session, and a project note takes its child notes along with theirs. The output lists - each child by its reference, with the repo and branch it landed on. A - branch note moved on its own loses its link to the project note it was - written under, and moving it back does not restore that link. Commits - and code reviews stay on their branch. + each child by its reference, with the repo and branch it landed on. If + it says the children could not be read back (`children: null` under + `--json`), they moved all the same. A branch note moved on its own loses + its link to the project note it was written under, and moving it back + does not restore that link. Commits and code reviews stay on their + branch. - A copy is a new, standalone note with its own id: the title and body as they read now, with no session, no parent or child notes, and no suggested next steps. The original is untouched. diff --git a/apps/staged/src-tauri/src/note_transfer/control.rs b/apps/staged/src-tauri/src/note_transfer/control.rs index e2954b3de..595b2021f 100644 --- a/apps/staged/src-tauri/src/note_transfer/control.rs +++ b/apps/staged/src-tauri/src/note_transfer/control.rs @@ -4,9 +4,9 @@ //! The app's windows open a note where it is and know its surroundings, so //! the transfer commands answer them with the note alone. A control caller //! named a note by id and a project, and is told what the transfer did with -//! them: the branch the note landed on, the child notes a moved project -//! note took along and where each of those landed, and the repos the -//! transfer added to the destination to make room. Only the transfer knows +//! them: the branch the note landed on, a moved project note's child notes +//! and where each of those is now, and the repos the transfer added to the +//! destination to make room. Only the transfer knows //! the last. Once added, a repo reads like any other the project tracks, so //! each one is noted as its add succeeds ([`AddedRepos`]). The same list //! lets a failure say which repos the destination gained before it @@ -107,8 +107,8 @@ pub(crate) fn branch_note_answer( /// A control caller's answer for a project note: `note`, the note as /// `list_project_notes` lists one, which names the project it is in now; -/// `children`, the child notes that came with it; and `addedRepos`, the -/// repos those children brought along. +/// `children`, the note's child notes as they read once the transfer has +/// committed; and `addedRepos`, the repos a move added for those children. /// /// `note` is the transfer's own value, which a window is answered with as /// it is. A moved note's is the row the move's transaction returned, with @@ -119,9 +119,15 @@ pub(crate) fn branch_note_answer( /// /// Each of `children` is `{ reference, title, branch, repo }`: the child's /// hashtag reference (`#note:<id>`, unchanged by the move), and the branch -/// and repo it is on now, as in a branch note's answer. A move takes every -/// child or is refused, so these are the note's children as they read -/// after it. A copy has none. +/// and repo it is on now, as in a branch note's answer. The list is read +/// here, after the commit, and is not the move's own plan. A move takes +/// every child or is refused, so the two agree unless a child was deleted, +/// detached or added in between, and then the list is the note's children +/// as they are. A copy's note is new and has none. +/// +/// `children` is `null` when the list cannot be read back. That is not an +/// empty list: a moved note's children moved with it all the same, and the +/// answer does not say it has none. pub(crate) fn project_note_answer(store: &Store, note: ProjectNote, added: AddedRepos) -> Value { let note = match store.get_project_note_with_status(¬e.id) { Ok(Some(resolved)) => resolved, @@ -134,26 +140,27 @@ pub(crate) fn project_note_answer(store: &Store, note: ProjectNote, added: Added note } }; - let children: Vec<Value> = store - .list_child_notes(¬e.id) - .unwrap_or_else(|e| { + let children = match store.list_child_notes(¬e.id) { + Ok(children) => children + .into_iter() + .map(|child| { + let (branch, repo) = landing(store, &child.branch_id); + json!({ + "reference": format!("#note:{}", child.id), + "title": child.title, + "branch": branch, + "repo": repo, + }) + }) + .collect(), + Err(e) => { log::warn!( "Note transfer: cannot read back the child notes of {}: {e}", note.id ); - Vec::new() - }) - .into_iter() - .map(|child| { - let (branch, repo) = landing(store, &child.branch_id); - json!({ - "reference": format!("#note:{}", child.id), - "title": child.title, - "branch": branch, - "repo": repo, - }) - }) - .collect(); + Value::Null + } + }; json!({ "note": note, "children": children, diff --git a/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json b/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json new file mode 100644 index 000000000..e8574eedd --- /dev/null +++ b/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json @@ -0,0 +1,188 @@ +{ + "branchNote": { + "note": { + "id": "note-findings", + "title": "Findings", + "content": "body", + "sessionId": "session-findings", + "sessionStatus": "completed", + "completionReason": null, + "sessionErrorMessage": null, + "rateLimitResetsAt": null, + "rateLimitKind": null, + "isPollingForNote": false, + "createdAt": 0, + "updatedAt": 0, + "completedAt": 0, + "suggestedNextCommitStep": null, + "suggestedNextNoteStep": null, + "subtype": null, + "lastChatMessageAt": null, + "chatReadAt": null, + "readAt": null + }, + "branch": { + "id": "branch-widgets", + "projectId": "project-created", + "projectRepoId": "repo-widgets", + "branchName": "landing-acme-widgets", + "baseBranch": "origin/main", + "prNumber": null, + "branchType": "local", + "workspaceName": null, + "workstationId": null, + "workspaceStatus": null, + "prState": null, + "prChecksStatus": null, + "prReviewDecision": null, + "prMergeable": null, + "prDraft": null, + "prUrl": null, + "prUpdatedAt": null, + "prFetchedAt": null, + "prHeadSha": null, + "prTitle": null, + "setupComplete": false, + "deferredPush": null, + "deferredPushRequestedAt": null, + "worktreePath": null, + "createdAt": 0, + "updatedAt": 0 + }, + "repo": { + "id": "repo-widgets", + "projectId": "project-created", + "githubRepo": "acme/widgets", + "branchName": "landing-acme-widgets", + "subpath": "apps/web", + "isPrimary": false, + "reason": null, + "headRepo": null, + "createdAt": 0, + "updatedAt": 0 + }, + "addedRepos": [ + { + "githubRepo": "acme/widgets", + "subpath": "apps/web" + } + ] + }, + "projectNote": { + "note": { + "id": "project-note-plan", + "projectId": "project-created", + "sessionId": "session-plan", + "title": "Plan", + "content": "body", + "createdAt": 0, + "updatedAt": 0, + "completedAt": 0, + "suggestedNextCommitStep": null, + "suggestedNextNoteStep": null, + "readAt": null, + "sessionStatus": "completed", + "completionReason": null, + "lastChatMessageAt": null, + "chatReadAt": null, + "rateLimitResetsAt": null, + "rateLimitKind": null + }, + "children": [ + { + "reference": "#note:note-gadgets", + "title": "Gadgets", + "branch": { + "id": "branch-gadgets", + "projectId": "project-created", + "projectRepoId": "repo-gadgets", + "branchName": "landing-acme-gadgets", + "baseBranch": "origin/main", + "prNumber": null, + "branchType": "local", + "workspaceName": null, + "workstationId": null, + "workspaceStatus": null, + "prState": null, + "prChecksStatus": null, + "prReviewDecision": null, + "prMergeable": null, + "prDraft": null, + "prUrl": null, + "prUpdatedAt": null, + "prFetchedAt": null, + "prHeadSha": null, + "prTitle": null, + "setupComplete": false, + "deferredPush": null, + "deferredPushRequestedAt": null, + "worktreePath": null, + "createdAt": 0, + "updatedAt": 0 + }, + "repo": { + "id": "repo-gadgets", + "projectId": "project-created", + "githubRepo": "acme/gadgets", + "branchName": "landing-acme-gadgets", + "subpath": null, + "isPrimary": false, + "reason": null, + "headRepo": null, + "createdAt": 0, + "updatedAt": 0 + } + }, + { + "reference": "#note:note-web", + "title": "Web", + "branch": { + "id": "branch-widgets", + "projectId": "project-created", + "projectRepoId": "repo-widgets", + "branchName": "landing-acme-widgets", + "baseBranch": "origin/main", + "prNumber": null, + "branchType": "local", + "workspaceName": null, + "workstationId": null, + "workspaceStatus": null, + "prState": null, + "prChecksStatus": null, + "prReviewDecision": null, + "prMergeable": null, + "prDraft": null, + "prUrl": null, + "prUpdatedAt": null, + "prFetchedAt": null, + "prHeadSha": null, + "prTitle": null, + "setupComplete": false, + "deferredPush": null, + "deferredPushRequestedAt": null, + "worktreePath": null, + "createdAt": 0, + "updatedAt": 0 + }, + "repo": { + "id": "repo-widgets", + "projectId": "project-created", + "githubRepo": "acme/widgets", + "branchName": "landing-acme-widgets", + "subpath": "apps/web", + "isPrimary": false, + "reason": null, + "headRepo": null, + "createdAt": 0, + "updatedAt": 0 + } + } + ], + "addedRepos": [ + { + "githubRepo": "acme/gadgets", + "subpath": null + } + ] + } +} diff --git a/apps/staged/src-tauri/src/note_transfer/control/tests.rs b/apps/staged/src-tauri/src/note_transfer/control/tests.rs index 6fdff2cb4..60278ae32 100644 --- a/apps/staged/src-tauri/src/note_transfer/control/tests.rs +++ b/apps/staged/src-tauri/src/note_transfer/control/tests.rs @@ -58,89 +58,6 @@ impl Fixture { let branch = Branch::new(&self.target.id, &name, "origin/main").with_project_repo(&repo.id); self.store.create_branch(&branch).map_err(|e| e.to_string()) } - - /// A branch-note transfer as the dispatch arm runs it: the repo add - /// watched, then the control answer. - async fn transfer(&self, note: &Note, mode: TransferMode) -> Result<Value, String> { - let added = AddedRepos::default(); - let landed = transfer_branch_note(&self.store, ¬e.id, &self.target.id, mode, |key| { - added.watch(key.clone(), std::future::ready(self.attach(key))) - }) - .await?; - let item = json!({ "id": landed.id, "title": landed.title }); - Ok(branch_note_answer( - &self.store, - item, - &landed.branch_id, - added, - )) - } -} - -fn widgets_key() -> Value { - json!({ "githubRepo": "acme/widgets", "subpath": "apps/web" }) -} - -#[tokio::test] -async fn a_move_that_adds_the_repo_names_it_and_where_the_note_landed() { - let f = fixture(); - let note = f.note_on(&f.widgets, "Findings"); - - let answer = f.transfer(¬e, TransferMode::Move).await.unwrap(); - - assert_eq!(answer["addedRepos"], json!([widgets_key()])); - assert_eq!(answer["note"]["id"], note.id, "a move keeps the note's id"); - assert_eq!(answer["branch"]["projectId"], f.target.id); - assert_eq!(answer["branch"]["branchName"], "target-acme-widgets"); - assert_eq!(answer["repo"]["githubRepo"], "acme/widgets"); - assert_eq!(answer["repo"]["subpath"], "apps/web"); - assert_eq!( - answer["branch"]["projectRepoId"], answer["repo"]["id"], - "the repo is the one the landing branch tracks" - ); - assert_eq!( - answer["branch"].get("worktreePath"), - Some(&Value::Null), - "the branch reads as the branch list gives one, worktree included" - ); -} - -#[tokio::test] -async fn a_transfer_into_a_project_that_tracks_the_repo_adds_nothing() { - let f = fixture(); - let note = f.note_on(&f.widgets, "Findings"); - f.attach(RepoKey { - github_repo: "acme/widgets".into(), - subpath: Some("apps/web".into()), - }) - .unwrap(); - - for mode in [TransferMode::Copy, TransferMode::Move] { - let answer = f.transfer(¬e, mode).await.unwrap(); - assert_eq!(answer["addedRepos"], json!([]), "{mode:?}"); - assert_eq!(answer["branch"]["projectId"], f.target.id, "{mode:?}"); - assert_eq!(answer["repo"]["githubRepo"], "acme/widgets", "{mode:?}"); - } -} - -#[tokio::test] -async fn a_copy_answers_with_the_new_note_and_leaves_the_original() { - let f = fixture(); - let note = f.note_on(&f.widgets, "Findings"); - - let answer = f.transfer(¬e, TransferMode::Copy).await.unwrap(); - - let copy_id = answer["note"]["id"].as_str().unwrap(); - assert_ne!(copy_id, note.id, "a copy is a new note"); - assert_eq!(answer["addedRepos"], json!([widgets_key()])); - assert_eq!( - f.store.get_note(¬e.id).unwrap().unwrap().branch_id, - f.widgets.id - ); - assert_eq!( - f.store.get_note(copy_id).unwrap().unwrap().branch_id, - answer["branch"]["id"].as_str().unwrap() - ); } #[tokio::test] @@ -278,6 +195,53 @@ fn a_project_note_that_cannot_be_read_back_is_answered_as_the_transfer_gave_it() ); } +/// Child notes that cannot be read back are answered as `null`, which is +/// not the empty list of a note without any: the move took them along, and +/// the answer must not read as though the note has none. The rest of the +/// answer stands. +#[tokio::test] +async fn children_that_cannot_be_read_back_are_answered_as_null() { + let f = fixture(); + let parent = ProjectNote::new(&f.source.id, "Plan", "body"); + f.store.create_project_note(&parent).unwrap(); + let child = + Note::new_standalone(&f.widgets.id, "Web", "body").with_parent_project_note(&parent.id); + f.store.create_note(&child).unwrap(); + + let added = AddedRepos::default(); + let moved = transfer_project_note( + &f.store, + &parent.id, + &f.target.id, + TransferMode::Move, + |key| added.watch(key.clone(), std::future::ready(f.attach(key))), + ) + .await + .unwrap(); + assert_eq!( + f.store.list_child_notes(&parent.id).unwrap().len(), + 1, + "the child came along" + ); + + // The move has committed. From here the notes cannot be listed. + f.store + .hold_connection() + .execute_batch("ALTER TABLE notes RENAME COLUMN parent_project_note_id TO unreadable") + .unwrap(); + assert!(f.store.list_child_notes(&parent.id).is_err()); + + let answer = project_note_answer(&f.store, moved, added); + + assert_eq!(answer["children"], Value::Null); + assert_eq!(answer["note"]["id"], parent.id); + assert_eq!(answer["note"]["projectId"], f.target.id); + assert_eq!( + answer["addedRepos"], + json!([{ "githubRepo": "acme/widgets", "subpath": "apps/web" }]) + ); +} + /// A failure is given the repos the transfer had added by then, in the /// sentence a project-note failure ends with. With none added, or for a /// destination that is not there, the error is left as it came. diff --git a/apps/staged/src-tauri/src/web_server.rs b/apps/staged/src-tauri/src/web_server.rs index 962e1b6dc..885b06368 100644 --- a/apps/staged/src-tauri/src/web_server.rs +++ b/apps/staged/src-tauri/src/web_server.rs @@ -5388,15 +5388,13 @@ mod tests { /// A note moved or copied through the control server goes through the /// transfer the app's windows run: one call, with the app's own /// repo-adding step, whoever asks. `note_transfer_arms` runs the arm - /// bodies for real, with a stand-in for that step. What it cannot run is - /// pinned here: that `dispatch` hands each command to its body with the - /// app's step and nothing else, that the body does not branch on its - /// caller ahead of the transfer, and that the desktop command is the - /// same transfer. + /// bodies for real, for both callers, with a stand-in for that step. + /// What it cannot run is pinned here: that `dispatch` hands each command + /// to its body with the app's step and nothing else, and that the + /// desktop command is the same transfer. #[test] fn note_transfers_run_the_one_transfer_whoever_asks() { let source = include_str!("web_server.rs"); - let bodies = include_str!("web_server/note_transfer_arms.rs"); let desktop = include_str!("note_transfer.rs"); for (command, body, transfer) in [ ( @@ -5443,33 +5441,6 @@ mod tests { ); } - // The body: one transfer, the step watched and not stood in - // for, and nothing about the caller before the transfer. - let marker = format!("pub(super) async fn {body}<"); - let start = bodies - .find(&marker) - .unwrap_or_else(|| panic!("note_transfer_arms.rs should define `{body}`")); - let rest = &bodies[start..]; - let end = rest.find("\n}\n").expect("the body should end"); - let code = &rest[rest.find("{\n").unwrap()..end]; - assert_eq!( - code.matches(transfer).count(), - 1, - "`{body}` must run the transfer once, for every caller: {code}" - ); - assert!( - code.contains("added.watch(key.clone(), add_repo(target_project_id.clone(), key))"), - "`{body}` must add a repo through the step it was given: {code}" - ); - let transfer_at = code.find(transfer).unwrap(); - let caller_at = code - .find("match caller {") - .unwrap_or_else(|| panic!("`{body}` should answer by caller: {code}")); - assert!( - transfer_at < caller_at, - "`{body}` must not branch on its caller before the transfer: {code}" - ); - // The desktop command is the same transfer with the same step. let marker = format!("pub async fn {command}("); let start = desktop diff --git a/apps/staged/src-tauri/src/web_server/control_scope.rs b/apps/staged/src-tauri/src/web_server/control_scope.rs index 7d8d57dea..86251004a 100644 --- a/apps/staged/src-tauri/src/web_server/control_scope.rs +++ b/apps/staged/src-tauri/src/web_server/control_scope.rs @@ -83,6 +83,14 @@ //! held to the same, since their bodies travel with it. A reference with no //! row carries nothing and is let through, as the transfer leaves it. //! +//! The check goes by the row and does not look for the file. A row whose +//! file is gone carries nothing either: the transfer leaves that reference +//! as it is, and the row in the project it is in. So a note the user moved +//! after such a file was lost still embeds a row of the project it left. If +//! that project is out of reach, a transfer of the note is refused for +//! media that would not have travelled. It takes a lost file to get there, +//! and the check keeps to the row. +//! //! The bodies are read when the request arrives. A transfer that has to add //! a repo reads them again once the repo is in, so a body saved during that //! add is carried unchecked. Closing that takes a check inside the @@ -575,7 +583,9 @@ fn require_images_in_scope( /// `home_project_id`, which the caller has been found to reach. /// /// A reference with no row is passed over. The transfer leaves it as it is -/// and carries nothing for it. +/// and carries nothing for it. A row whose file is gone is not passed over, +/// though the transfer carries nothing for that either (see the module +/// docs). fn require_note_media_in_scope( store: &Store, grant: &ControlGrant, @@ -2258,7 +2268,15 @@ mod tests { let f = fixture(); let created = create_project_by(&f, "gamma", CALLER); let g = scoped(&f.project_a); - let body = embedding(&[&f.image_a, &created.image, "no-such-image"]); + // A well-formed id with no row. Anything else is not a reference to + // stored media at all, and would never reach the row lookup. + let dangling = uuid::Uuid::new_v4().to_string(); + assert_eq!(f.store.get_image(&dangling).unwrap().map(|i| i.id), None); + let body = embedding(&[&f.image_a, &created.image, &dangling]); + assert!( + refs::media_ids(&body).contains(&dangling), + "the dangling reference must be one the check looks up" + ); for (cmd, id_arg, note_id) in notes_embedding(&f, &body) { for target in [&created.project, &f.project_a] { check_with_store(cmd, &transfer(id_arg, ¬e_id, target), &g, &f.store) diff --git a/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs b/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs index b99d8fa53..b6e58a833 100644 --- a/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs +++ b/apps/staged/src-tauri/src/web_server/note_transfer_arms.rs @@ -107,8 +107,8 @@ where ) .await?; Ok(match caller { - // As for a branch note: a control caller is told which child notes - // came along, where each landed, and the repos they brought. + // As for a branch note: a control caller is told the note's child + // notes as they read now, where each is, and the repos they brought. DispatchCaller::Control(_) => control::project_note_answer(store, note, added), DispatchCaller::Web => serde_json::to_value(note).unwrap(), }) diff --git a/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs index a0cd619ec..2b989268d 100644 --- a/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs +++ b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs @@ -239,6 +239,13 @@ fn widgets_key() -> Value { json!({ "githubRepo": "acme/widgets", "subpath": "apps/web" }) } +fn widgets_repo() -> RepoKey { + RepoKey { + github_repo: "acme/widgets".into(), + subpath: Some("apps/web".into()), + } +} + fn gadgets_key() -> Value { json!({ "githubRepo": "acme/gadgets", "subpath": null }) } @@ -315,6 +322,38 @@ async fn a_copied_branch_note_is_answered_with_the_new_standalone_note() { assert_eq!(f.branch_of(¬e.id), f.widgets.id, "the original stays"); } +/// Only a repo the transfer added is named as added. A destination that +/// tracks the note's repo already gains nothing, and the note lands on the +/// branch it has for that repo. +#[tokio::test] +async fn a_branch_note_sent_to_a_project_that_tracks_its_repo_adds_none() { + let f = fixture(); + let (note, _) = f.session_note(&f.widgets, "Findings"); + f.attach(&f.created.id, widgets_repo()).unwrap(); + + for command in ["copy_note_to_project", "move_note_to_project"] { + let answer = f + .control( + command, + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + assert_eq!(answer["addedRepos"], json!([]), "{command}"); + assert_eq!(answer["branch"]["projectId"], f.created.id, "{command}"); + assert_eq!( + answer["branch"]["branchName"], "landing-acme-widgets", + "{command}" + ); + assert_eq!(answer["repo"]["githubRepo"], "acme/widgets", "{command}"); + } + assert_eq!( + f.store.list_project_repos(&f.created.id).unwrap().len(), + 1, + "the destination tracks the one repo it had" + ); +} + /// The transfer is the one a window runs, and a window is answered with the /// note alone, as it was before a control caller could ask. #[tokio::test] @@ -361,14 +400,7 @@ async fn a_moved_project_note_is_answered_with_its_session_status_and_its_childr let f = fixture(); let (parent, children) = f.family(); // The destination already tracks one of the two repos. - f.attach( - &f.created.id, - RepoKey { - github_repo: "acme/widgets".into(), - subpath: Some("apps/web".into()), - }, - ) - .unwrap(); + f.attach(&f.created.id, widgets_repo()).unwrap(); let answer = f .control( @@ -596,7 +628,17 @@ async fn a_failed_repo_add_is_reported_as_the_transfer_words_it() { async fn media_from_a_project_out_of_reach_stops_the_transfer_before_it_runs() { let f = fixture(); let foreign = f.image_in(&f.third.id, Some(&f.third_branch.id)); - let body = format!("see ![theirs](staged-media://{}.png)", foreign.id); + // Beside a reference with no row, which is no reason to refuse. Its id + // sorts ahead of any the store makes, so the check passes over it first + // and the refusal is for the media that is someone else's. + const NO_ROW: &str = "00000000-0000-4000-8000-000000000000"; + assert!(NO_ROW < foreign.id.as_str()); + assert!(f.store.get_image(NO_ROW).unwrap().is_none()); + let body = format!( + "see ![gone](staged-media://{NO_ROW}.png) and ![theirs](staged-media://{}.png)", + foreign.id + ); + assert_eq!(crate::note_media::refs::media_ids(&body).len(), 2); let (note, _) = f.session_note(&f.widgets, "Findings"); f.store.update_note_content(¬e.id, &body).unwrap(); let (parent, children) = f.family(); @@ -666,6 +708,69 @@ async fn media_from_a_project_out_of_reach_stops_the_transfer_before_it_runs() { assert_eq!(answer["children"], json!([])); } +/// A reference to media that has no row carries nothing, so it is nobody +/// else's to protect. The scope check lets it through and the transfer +/// leaves it as written, for a confined caller as for the app's windows. +/// +/// The id is a well-formed one. Anything else is not a reference to stored +/// media at all, and would reach neither the check's row lookup nor the +/// transfer's. +#[tokio::test] +async fn a_reference_to_media_with_no_row_is_let_through_and_left_as_written() { + let f = fixture(); + let dangling = uuid::Uuid::new_v4().to_string(); + assert!(f.store.get_image(&dangling).unwrap().is_none()); + let body = format!("see ![gone](staged-media://{dangling}.png)"); + assert!( + crate::note_media::refs::media_ids(&body).contains(&dangling), + "the reference must be one the check and the transfer look up" + ); + let (note, _) = f.session_note(&f.widgets, "Findings"); + f.store.update_note_content(¬e.id, &body).unwrap(); + let (parent, children) = f.family(); + f.store + .update_project_note_title_and_content(&parent.id, "Plan", &body, None, None) + .unwrap(); + f.store.update_note_content(&children[1].id, &body).unwrap(); + + let copy = f + .control( + "copy_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + assert_eq!(copy["note"]["content"], body.as_str()); + let moved = f + .control( + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + assert_eq!(moved["note"]["content"], body.as_str()); + assert_ne!(f.branch_of(¬e.id), f.widgets.id, "the note moved"); + + // In a project note and in a child that travels with it. + let moved = f + .control( + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + assert_eq!(moved["note"]["projectId"], f.created.id); + assert_eq!(moved["note"]["content"], body.as_str()); + let child = f.store.get_note(&children[1].id).unwrap().unwrap(); + assert_eq!(child.content, body); + assert_ne!(child.branch_id, children[1].branch_id, "the child moved"); + + assert!( + f.store.get_image(&dangling).unwrap().is_none(), + "no row is made for it" + ); +} + /// A note the confined caller cannot be shown is a scope refusal, whether /// its id is unknown or names the other kind of note. An unconfined caller /// is told by the transfer. @@ -700,3 +805,142 @@ async fn a_note_id_that_names_no_note_of_that_kind_is_refused_by_scope_when_conf assert!(err.starts_with("Note not found: "), "{err}"); } } + +// --------------------------------------------------------------------------- +// The answers stagedctl reads +// --------------------------------------------------------------------------- + +/// One answer of each kind, as a control caller receives it. `stagedctl` +/// parses this same file in its own tests (`notes/tests.rs`), so the names +/// the app writes and the names the CLI reads are held to one document, and +/// a change to either side fails a test until both agree. +const ANSWERS_FIXTURE: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/src/note_transfer/control/fixtures/answers.json" +); + +/// Set to rewrite the fixture from what the app answers now. +const UPDATE_ANSWERS_FIXTURE: &str = "STAGED_UPDATE_NOTE_TRANSFER_ANSWERS"; + +/// `answer` with what differs from run to run made the same: each id is +/// replaced by the name `names` gives it, and each timestamp by `0`. An id +/// left without a name is a mistake in the test, since it would never +/// compare equal twice. +fn settled(answer: &Value, names: &[(String, &str)]) -> Value { + match answer { + Value::Object(fields) => fields + .iter() + .map(|(key, value)| { + let value = if key.ends_with("At") && value.is_number() { + json!(0) + } else { + settled(value, names) + }; + (key.clone(), value) + }) + .collect::<serde_json::Map<_, _>>() + .into(), + Value::Array(items) => items.iter().map(|item| settled(item, names)).collect(), + Value::String(text) => { + let named = names + .iter() + .fold(text.clone(), |text, (id, name)| text.replace(id, name)); + let id = named.rsplit(':').next().unwrap_or(&named); + assert!( + uuid::Uuid::parse_str(id).is_err(), + "{text:?} is an id the fixture has no name for" + ); + json!(named) + } + other => other.clone(), + } +} + +/// The landing branch of `note_id` and the repo it tracks, by id. +fn landing_ids(f: &Fixture, note_id: &str) -> (String, String) { + let branch_id = f.branch_of(note_id); + let branch = f.store.get_branch(&branch_id).unwrap().unwrap(); + (branch_id, branch.project_repo_id.expect("a tracked repo")) +} + +/// A move of a branch note and a move of a project note, each into a +/// project that has to gain a repo for it, answered to the session. These +/// are the two shapes `stagedctl` reads, with every part of them filled in: +/// the note item, the landing branch and repo, the children and theirs, and +/// the repos added. +#[tokio::test] +async fn the_answers_are_the_ones_stagedctl_is_tested_against() { + // A branch note, whose repo the destination lacks. + let f = fixture(); + let (note, session) = f.session_note(&f.widgets, "Findings"); + let answer = f + .control( + "move_note_to_project", + json!({ "noteId": note.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + let (branch_id, repo_id) = landing_ids(&f, ¬e.id); + let branch_note = settled( + &answer, + &[ + (note.id, "note-findings"), + (session.id, "session-findings"), + (f.created.id.clone(), "project-created"), + (branch_id, "branch-widgets"), + (repo_id, "repo-widgets"), + ], + ); + + // A project note with two children. The destination tracks the repo of + // one and gains the other's. + let f = fixture(); + let (parent, children) = f.family(); + f.attach(&f.created.id, widgets_repo()).unwrap(); + let mut answer = f + .control( + "move_project_note_to_project", + json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), + ) + .await + .unwrap(); + // The app lists children newest first, and these two were written in + // the same instant. By title, so the fixture has one order. + answer["children"] + .as_array_mut() + .expect("the children were read back") + .sort_by_key(|child| child["title"].as_str().map(str::to_owned)); + let (web_branch, web_repo) = landing_ids(&f, &children[0].id); + let (gadgets_branch, gadgets_repo) = landing_ids(&f, &children[1].id); + let project_note = settled( + &answer, + &[ + (parent.id, "project-note-plan"), + (parent.session_id.expect("a session"), "session-plan"), + (f.created.id.clone(), "project-created"), + (children[0].id.clone(), "note-web"), + (web_branch, "branch-widgets"), + (web_repo, "repo-widgets"), + (children[1].id.clone(), "note-gadgets"), + (gadgets_branch, "branch-gadgets"), + (gadgets_repo, "repo-gadgets"), + ], + ); + + let answers = json!({ "branchNote": branch_note, "projectNote": project_note }); + if std::env::var_os(UPDATE_ANSWERS_FIXTURE).is_some() { + let mut text = serde_json::to_string_pretty(&answers).unwrap(); + text.push('\n'); + std::fs::write(ANSWERS_FIXTURE, text).expect("write the answers fixture"); + return; + } + let pinned: Value = serde_json::from_str( + &std::fs::read_to_string(ANSWERS_FIXTURE).expect("the answers fixture"), + ) + .expect("the answers fixture is JSON"); + assert_eq!( + answers, pinned, + "a control caller's answer changed. If that is meant, rewrite the fixture with \ + {UPDATE_ANSWERS_FIXTURE}=1 and run stagedctl's tests, which read the same file" + ); +} From d1d62f7d33df147cbea2abd0a4760ce1014f8000 Mon Sep 17 00:00:00 2001 From: Matt Toohey <contact@matttoohey.com> Date: Thu, 19 Nov 2026 13:11:18 +1100 Subject: [PATCH 4/4] fix(staged): hold note answers to a trimmed fixture by containment Review c20aea8b of b09b00a7 left three optional items on `stagedctl note move` and `stagedctl note copy`. This applies them. It touches tests and one line of output. The transfer, the answers the app gives and the help are unchanged. The fixture pinned too much. `answers.json` held every field of the branch row, the repo row, the note item and the project note, and the app's test asserted its answers equal to it. stagedctl reads about nine of those names. A PR that added a field to one of those models failed the test until the fixture was rewritten, and two such PRs that were each green could turn main red together. The app's test now asserts containment. `pinned_part` takes from the real answer the fields the fixture names, and that part has to equal the fixture. A field the answer gains passes. A pinned field that is renamed or removed fails with its path, such as "the answer has no `projectNote.children[0].reference`", and one answered with another value fails the comparison. A field pinned as `null` has to be there. A list is held item for item, so one of another length fails too. The fixture is cut to what `Landed` reads in stagedctl: the note's `id` and `title`, the branch's `id` and `branchName`, the repo's `githubRepo` and `subpath`, each child's `reference`, `title`, `branch` and `repo`, and `addedRepos`. It has no timestamps or session, project and repo ids left, so the test names fewer ids. stagedctl's tests parse the same file as before and assert the same output from it. The update variable. `STAGED_UPDATE_NOTE_TRANSFER_ANSWERS` rewrote the fixture when it was set to anything, an empty value or `0` included. It now has to equal `1`. A rewrite refreshes the values of the fields the fixture already pins and keeps it trimmed. A pinned field the answer no longer has stops the rewrite, so update mode no longer passes whatever the app answers. The output line. A move whose answer has `children: null` printed "child notes: the app could not read them back; any the note has moved with it". It now ends "any child notes it has moved with it", as the review suggests. The CLI test that asserts the line is updated. The help, the guide and the help pin do not quote it. Tests. A new test runs `pinned_part` on made-up answers: added fields pass, and a renamed field, a removed one, a changed value, a row answered as `null` and a grown list do not. The check was also proved against the app, with each change reverted afterwards. Renaming `reference` in `control.rs`, removing a branch note's `addedRepos` and changing a child's reference each failed the test. Adding unpinned fields to the answer and to a child passed. With `addedRepos` removed, the variable set to `0`, to empty and to `1` all failed and left the fixture alone. On the unchanged source, `=1` rewrote the fixture byte for byte. Checked from this worktree, built into a private cargo target so the running app's binaries were not replaced: `cargo fmt --check`, `cargo clippy --workspace -- -D warnings`, all 246 stagedctl unit tests and the help pin, and the app's `note_transfer`, `web_server`, `control_server`, `control_scope` and `note_media` tests (336). The rest of the app's suite was not run locally. Signed-off-by: Matt Toohey <contact@matttoohey.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src-tauri/crates/stagedctl/src/notes.rs | 3 +- .../crates/stagedctl/src/notes/tests.rs | 15 +- .../control/fixtures/answers.json | 144 +------------ .../web_server/note_transfer_arms/tests.rs | 202 +++++++++++++----- 4 files changed, 166 insertions(+), 198 deletions(-) diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs index 01547c4a3..2fd3d8240 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes.rs @@ -356,7 +356,8 @@ fn render( } } Children::Unread if transfer == Transfer::Move => human.push( - " child notes: the app could not read them back; any the note has moved with it" + " child notes: the app could not read them back; any child notes it has moved \ + with it" .to_string(), ), // A copy is a new note with no children, read or not. diff --git a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs index 033968628..d0c25e1dc 100644 --- a/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs +++ b/apps/staged/src-tauri/crates/stagedctl/src/notes/tests.rs @@ -441,7 +441,8 @@ fn children_the_app_could_not_read_back_are_not_reported_as_none() { "project note #project-note:pn1 moved to project \"Target\"\n\ \x20 project id: p2\n\ \x20 title: Plan\n\ - \x20 child notes: the app could not read them back; any the note has moved with it\n\ + \x20 child notes: the app could not read them back; any child notes it has moved with \ + it\n\ \x20 added repo: acme/gadgets (the project did not track it; its branch is set up in \ the background)\n\ next: stagedctl timeline show p2" @@ -722,12 +723,12 @@ fn the_requests_use_the_argument_names_the_apps_commands_read() { } } -/// One answer of each kind, as the app gives it to a control caller. The -/// app's own tests run a real move of a branch note and of a project note -/// and hold the answers to this file -/// (`web_server/note_transfer_arms/tests.rs`), with ids named and -/// timestamps zeroed. Reading the same file here holds the names the CLI -/// reads to the names the app writes. +/// One answer of each kind, as the app gives it to a control caller, cut +/// down to the fields the CLI reads. The app's own tests run a real move of +/// a branch note and of a project note and assert that the answers contain +/// this file (`web_server/note_transfer_arms/tests.rs`), with ids named. +/// Reading the same file here holds the names the CLI reads to the names +/// the app writes. const APP_ANSWERS: &str = include_str!("../../../../src/note_transfer/control/fixtures/answers.json"); diff --git a/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json b/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json index e8574eedd..66cc6311a 100644 --- a/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json +++ b/apps/staged/src-tauri/src/note_transfer/control/fixtures/answers.json @@ -2,64 +2,15 @@ "branchNote": { "note": { "id": "note-findings", - "title": "Findings", - "content": "body", - "sessionId": "session-findings", - "sessionStatus": "completed", - "completionReason": null, - "sessionErrorMessage": null, - "rateLimitResetsAt": null, - "rateLimitKind": null, - "isPollingForNote": false, - "createdAt": 0, - "updatedAt": 0, - "completedAt": 0, - "suggestedNextCommitStep": null, - "suggestedNextNoteStep": null, - "subtype": null, - "lastChatMessageAt": null, - "chatReadAt": null, - "readAt": null + "title": "Findings" }, "branch": { "id": "branch-widgets", - "projectId": "project-created", - "projectRepoId": "repo-widgets", - "branchName": "landing-acme-widgets", - "baseBranch": "origin/main", - "prNumber": null, - "branchType": "local", - "workspaceName": null, - "workstationId": null, - "workspaceStatus": null, - "prState": null, - "prChecksStatus": null, - "prReviewDecision": null, - "prMergeable": null, - "prDraft": null, - "prUrl": null, - "prUpdatedAt": null, - "prFetchedAt": null, - "prHeadSha": null, - "prTitle": null, - "setupComplete": false, - "deferredPush": null, - "deferredPushRequestedAt": null, - "worktreePath": null, - "createdAt": 0, - "updatedAt": 0 + "branchName": "landing-acme-widgets" }, "repo": { - "id": "repo-widgets", - "projectId": "project-created", "githubRepo": "acme/widgets", - "branchName": "landing-acme-widgets", - "subpath": "apps/web", - "isPrimary": false, - "reason": null, - "headRepo": null, - "createdAt": 0, - "updatedAt": 0 + "subpath": "apps/web" }, "addedRepos": [ { @@ -71,22 +22,7 @@ "projectNote": { "note": { "id": "project-note-plan", - "projectId": "project-created", - "sessionId": "session-plan", - "title": "Plan", - "content": "body", - "createdAt": 0, - "updatedAt": 0, - "completedAt": 0, - "suggestedNextCommitStep": null, - "suggestedNextNoteStep": null, - "readAt": null, - "sessionStatus": "completed", - "completionReason": null, - "lastChatMessageAt": null, - "chatReadAt": null, - "rateLimitResetsAt": null, - "rateLimitKind": null + "title": "Plan" }, "children": [ { @@ -94,43 +30,11 @@ "title": "Gadgets", "branch": { "id": "branch-gadgets", - "projectId": "project-created", - "projectRepoId": "repo-gadgets", - "branchName": "landing-acme-gadgets", - "baseBranch": "origin/main", - "prNumber": null, - "branchType": "local", - "workspaceName": null, - "workstationId": null, - "workspaceStatus": null, - "prState": null, - "prChecksStatus": null, - "prReviewDecision": null, - "prMergeable": null, - "prDraft": null, - "prUrl": null, - "prUpdatedAt": null, - "prFetchedAt": null, - "prHeadSha": null, - "prTitle": null, - "setupComplete": false, - "deferredPush": null, - "deferredPushRequestedAt": null, - "worktreePath": null, - "createdAt": 0, - "updatedAt": 0 + "branchName": "landing-acme-gadgets" }, "repo": { - "id": "repo-gadgets", - "projectId": "project-created", "githubRepo": "acme/gadgets", - "branchName": "landing-acme-gadgets", - "subpath": null, - "isPrimary": false, - "reason": null, - "headRepo": null, - "createdAt": 0, - "updatedAt": 0 + "subpath": null } }, { @@ -138,43 +42,11 @@ "title": "Web", "branch": { "id": "branch-widgets", - "projectId": "project-created", - "projectRepoId": "repo-widgets", - "branchName": "landing-acme-widgets", - "baseBranch": "origin/main", - "prNumber": null, - "branchType": "local", - "workspaceName": null, - "workstationId": null, - "workspaceStatus": null, - "prState": null, - "prChecksStatus": null, - "prReviewDecision": null, - "prMergeable": null, - "prDraft": null, - "prUrl": null, - "prUpdatedAt": null, - "prFetchedAt": null, - "prHeadSha": null, - "prTitle": null, - "setupComplete": false, - "deferredPush": null, - "deferredPushRequestedAt": null, - "worktreePath": null, - "createdAt": 0, - "updatedAt": 0 + "branchName": "landing-acme-widgets" }, "repo": { - "id": "repo-widgets", - "projectId": "project-created", "githubRepo": "acme/widgets", - "branchName": "landing-acme-widgets", - "subpath": "apps/web", - "isPrimary": false, - "reason": null, - "headRepo": null, - "createdAt": 0, - "updatedAt": 0 + "subpath": "apps/web" } } ], diff --git a/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs index 2b989268d..4f98ac344 100644 --- a/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs +++ b/apps/staged/src-tauri/src/web_server/note_transfer_arms/tests.rs @@ -810,18 +810,67 @@ async fn a_note_id_that_names_no_note_of_that_kind_is_refused_by_scope_when_conf // The answers stagedctl reads // --------------------------------------------------------------------------- -/// One answer of each kind, as a control caller receives it. `stagedctl` -/// parses this same file in its own tests (`notes/tests.rs`), so the names -/// the app writes and the names the CLI reads are held to one document, and -/// a change to either side fails a test until both agree. +/// One answer of each kind, as a control caller receives it, cut down to +/// the fields `stagedctl` reads. `stagedctl` parses this same file in its +/// own tests (`notes/tests.rs`), so the names the app writes and the names +/// the CLI reads are held to one document. The app's answer has to contain +/// it. A field it pins that is renamed, removed or answered differently +/// fails a test until both sides agree. A field it does not pin, such as +/// one a model gains, passes. const ANSWERS_FIXTURE: &str = concat!( env!("CARGO_MANIFEST_DIR"), "/src/note_transfer/control/fixtures/answers.json" ); -/// Set to rewrite the fixture from what the app answers now. +/// Set to `1` to rewrite the fixture's values from what the app answers +/// now. The fields it pins stay the ones it has, so add or drop one by +/// hand. A field the answer no longer has stops the rewrite. const UPDATE_ANSWERS_FIXTURE: &str = "STAGED_UPDATE_NOTE_TRANSFER_ANSWERS"; +/// The part of `answer` that `pinned` names: of an object, the fields +/// `pinned` has, and of a list, each item against the item `pinned` has in +/// its place. Anything else is `answer` as it stands. `answer` contains +/// `pinned` when this is equal to `pinned`, whatever else `answer` carries. +/// +/// A field `pinned` has and `answer` lacks is an error that names it, and +/// so is a list of another length. `null` is a value like any other: a +/// field pinned as `null` has to be there. +fn pinned_part(answer: &Value, pinned: &Value, path: &str) -> Result<Value, String> { + match (answer, pinned) { + (Value::Object(answer), Value::Object(pinned)) => pinned + .iter() + .map(|(key, pinned)| { + let path = match path { + "" => key.clone(), + path => format!("{path}.{key}"), + }; + let value = answer + .get(key) + .ok_or_else(|| format!("the answer has no `{path}`"))?; + Ok((key.clone(), pinned_part(value, pinned, &path)?)) + }) + .collect::<Result<serde_json::Map<_, _>, _>>() + .map(Value::Object), + (Value::Array(answer), Value::Array(pinned)) => { + if answer.len() != pinned.len() { + return Err(format!( + "`{path}` has {} items in the answer and {} in the fixture", + answer.len(), + pinned.len() + )); + } + answer + .iter() + .zip(pinned) + .enumerate() + .map(|(at, (answer, pinned))| pinned_part(answer, pinned, &format!("{path}[{at}]"))) + .collect::<Result<Vec<_>, _>>() + .map(Value::Array) + } + _ => Ok(answer.clone()), + } +} + /// `answer` with what differs from run to run made the same: each id is /// replaced by the name `names` gives it, and each timestamp by `0`. An id /// left without a name is a mistake in the test, since it would never @@ -856,48 +905,34 @@ fn settled(answer: &Value, names: &[(String, &str)]) -> Value { } } -/// The landing branch of `note_id` and the repo it tracks, by id. -fn landing_ids(f: &Fixture, note_id: &str) -> (String, String) { - let branch_id = f.branch_of(note_id); - let branch = f.store.get_branch(&branch_id).unwrap().unwrap(); - (branch_id, branch.project_repo_id.expect("a tracked repo")) -} - /// A move of a branch note and a move of a project note, each into a /// project that has to gain a repo for it, answered to the session. These -/// are the two shapes `stagedctl` reads, with every part of them filled in: -/// the note item, the landing branch and repo, the children and theirs, and -/// the repos added. +/// are the two shapes `stagedctl` reads: the note item, the landing branch +/// and repo, the children and theirs, and the repos added. Each has to +/// contain what the fixture pins of it. #[tokio::test] -async fn the_answers_are_the_ones_stagedctl_is_tested_against() { +async fn the_answers_contain_the_ones_stagedctl_is_tested_against() { // A branch note, whose repo the destination lacks. let f = fixture(); - let (note, session) = f.session_note(&f.widgets, "Findings"); - let answer = f + let (note, _) = f.session_note(&f.widgets, "Findings"); + let branch_note = f .control( "move_note_to_project", json!({ "noteId": note.id, "targetProjectId": f.created.id }), ) .await .unwrap(); - let (branch_id, repo_id) = landing_ids(&f, ¬e.id); - let branch_note = settled( - &answer, - &[ - (note.id, "note-findings"), - (session.id, "session-findings"), - (f.created.id.clone(), "project-created"), - (branch_id, "branch-widgets"), - (repo_id, "repo-widgets"), - ], - ); + let mut names = vec![ + (f.branch_of(¬e.id), "branch-widgets"), + (note.id, "note-findings"), + ]; // A project note with two children. The destination tracks the repo of // one and gains the other's. let f = fixture(); let (parent, children) = f.family(); f.attach(&f.created.id, widgets_repo()).unwrap(); - let mut answer = f + let mut project_note = f .control( "move_project_note_to_project", json!({ "projectNoteId": parent.id, "targetProjectId": f.created.id }), @@ -906,41 +941,100 @@ async fn the_answers_are_the_ones_stagedctl_is_tested_against() { .unwrap(); // The app lists children newest first, and these two were written in // the same instant. By title, so the fixture has one order. - answer["children"] + project_note["children"] .as_array_mut() .expect("the children were read back") .sort_by_key(|child| child["title"].as_str().map(str::to_owned)); - let (web_branch, web_repo) = landing_ids(&f, &children[0].id); - let (gadgets_branch, gadgets_repo) = landing_ids(&f, &children[1].id); - let project_note = settled( - &answer, - &[ - (parent.id, "project-note-plan"), - (parent.session_id.expect("a session"), "session-plan"), - (f.created.id.clone(), "project-created"), - (children[0].id.clone(), "note-web"), - (web_branch, "branch-widgets"), - (web_repo, "repo-widgets"), - (children[1].id.clone(), "note-gadgets"), - (gadgets_branch, "branch-gadgets"), - (gadgets_repo, "repo-gadgets"), - ], - ); + names.extend([ + (parent.id, "project-note-plan"), + (f.branch_of(&children[0].id), "branch-widgets"), + (children[0].id.clone(), "note-web"), + (f.branch_of(&children[1].id), "branch-gadgets"), + (children[1].id.clone(), "note-gadgets"), + ]); + let pinned: Value = serde_json::from_str( + &std::fs::read_to_string(ANSWERS_FIXTURE).expect("the answers fixture"), + ) + .expect("the answers fixture is JSON"); + let remedy = format!( + "If that is meant, change what stagedctl reads (`Landed` in its `notes.rs`) and the \ + fixture to match. {UPDATE_ANSWERS_FIXTURE}=1 rewrites the fixture's values. \ + stagedctl's tests read the same file" + ); let answers = json!({ "branchNote": branch_note, "projectNote": project_note }); - if std::env::var_os(UPDATE_ANSWERS_FIXTURE).is_some() { + let answers = match pinned_part(&answers, &pinned, "") { + Ok(part) => settled(&part, &names), + Err(gone) => panic!("{gone}, which stagedctl reads. {remedy}"), + }; + if std::env::var(UPDATE_ANSWERS_FIXTURE).as_deref() == Ok("1") { let mut text = serde_json::to_string_pretty(&answers).unwrap(); text.push('\n'); std::fs::write(ANSWERS_FIXTURE, text).expect("write the answers fixture"); return; } - let pinned: Value = serde_json::from_str( - &std::fs::read_to_string(ANSWERS_FIXTURE).expect("the answers fixture"), - ) - .expect("the answers fixture is JSON"); assert_eq!( answers, pinned, - "a control caller's answer changed. If that is meant, rewrite the fixture with \ - {UPDATE_ANSWERS_FIXTURE}=1 and run stagedctl's tests, which read the same file" + "a control caller's answer no longer contains the fixture. {remedy}" + ); +} + +/// The check the fixture is held to, on answers made up for it: a field +/// the answer gains passes, and one that is renamed, removed or answered +/// differently does not. +#[test] +fn an_answer_contains_the_fixture_whatever_else_it_carries() { + let pinned = json!({ + "note": { "id": "n1", "title": "Plan" }, + "repo": { "githubRepo": "acme/widgets", "subpath": null }, + "addedRepos": [{ "githubRepo": "acme/widgets" }], + }); + let answer = json!({ + "note": { "id": "n1", "title": "Plan", "content": "body", "readAt": null }, + "repo": { "id": "r1", "githubRepo": "acme/widgets", "subpath": null }, + "addedRepos": [{ "githubRepo": "acme/widgets", "subpath": null }], + "branch": null, + }); + assert_eq!(pinned_part(&answer, &pinned, ""), Ok(pinned.clone())); + + // Renamed or removed: a pinned field is not there, `null` or not. + let mut renamed = answer.clone(); + let repo = renamed["repo"].as_object_mut().unwrap(); + let name = repo.remove("githubRepo").unwrap(); + repo.insert("github_repo".into(), name); + assert_eq!( + pinned_part(&renamed, &pinned, ""), + Err("the answer has no `repo.githubRepo`".to_string()) + ); + let mut removed = answer.clone(); + removed["repo"].as_object_mut().unwrap().remove("subpath"); + assert_eq!( + pinned_part(&removed, &pinned, ""), + Err("the answer has no `repo.subpath`".to_string()) + ); + + // Answered differently: there, with another value or another shape. + for (field, value) in [ + ("/note/title", json!("Plans")), + ("/repo/subpath", json!("apps/web")), + ("/repo", Value::Null), + ("/addedRepos/0/githubRepo", json!("acme/gadgets")), + ] { + let mut changed = answer.clone(); + *changed.pointer_mut(field).unwrap() = value; + assert_ne!( + pinned_part(&changed, &pinned, ""), + Ok(pinned.clone()), + "{field}" + ); + } + + // A list is held item for item, so one that grew is not contained. + let mut grown = answer.clone(); + let added = grown["addedRepos"].as_array_mut().unwrap(); + added.push(json!({ "githubRepo": "acme/gadgets" })); + assert_eq!( + pinned_part(&grown, &pinned, ""), + Err("`addedRepos` has 2 items in the answer and 1 in the fixture".to_string()) ); }