From a072e831e7b64deca1f69e986c8379d89a13cac8 Mon Sep 17 00:00:00 2001 From: Christophe Dervieux Date: Wed, 2 Dec 2026 14:49:32 +0100 Subject: [PATCH] feat(cli): read prose fields from a file or stdin Agents on Windows pass strand text through Git Bash, which mangles it: MSYS rewrites an argument starting with `/` into a Windows path (`/proj` becomes `C:/Program Files/Git/proj`), and some agent shells collapse `\\` to `\`. Reading the text from a file sidesteps the shell. Every prose field gets a file variant: `--description-file` on create; `--description-file`, `--design-file`, `--acceptance-criteria-file` and `--notes-file` on update; `--reason-file` on close; and `-F`/`--file` on comment, after `git commit -F`. `-` reads stdin, and only one flag per command may use it. The bytes are stored as read, with no trimming or newline translation; non-UTF-8 input is rejected. Each file flag conflicts with its inline counterpart. Adding four fields to `Update` trips clippy's `large_enum_variant` on `Cmd`; it is allowed in place, since the enum is parsed once per process. --- crates/braid/src/agents-info.md | 18 ++- crates/braid/src/main.rs | 177 +++++++++++++++++------ crates/braid/tests/text_file_cli.rs | 213 ++++++++++++++++++++++++++++ 3 files changed, 363 insertions(+), 45 deletions(-) create mode 100644 crates/braid/tests/text_file_cli.rs diff --git a/crates/braid/src/agents-info.md b/crates/braid/src/agents-info.md index 6c1787a..03e96d3 100644 --- a/crates/braid/src/agents-info.md +++ b/crates/braid/src/agents-info.md @@ -64,6 +64,16 @@ braid create "Fix the frobnicator" \ --deps discovered-from: ``` +Prose your shell might mangle (a leading `/`, doubled backslashes, several +lines) can come from a file instead: `--description-file`, `--design-file`, +`--acceptance-criteria-file`, `--notes-file`, `--reason-file`, and +`comment -F`. `-` reads stdin. The text is stored byte for byte. + +```sh +braid comment -F note.md +braid close --reason-file - < reason.txt +``` + ## Command reference | command | purpose | @@ -73,14 +83,14 @@ braid create "Fix the frobnicator" \ | `braid list [--status S] [--all] [--label L]... [--assignee A] [--type T] [--priority N]... [--json]` | open (non-closed) strands; `--all` includes closed. Same field filters as `ready` | | `braid show [--json]` | one strand (unique id fragments work: `braid show 6j42`) | | `braid search [--json]` | case-insensitive substring over titles, prose, labels, comments | -| `braid create [flags]` | new strand; prints its id. Flags: `--description --type --priority --label --slug --assignee --deps --json`. `--deps <type>:<target-id>` attaches dependencies atomically (repeatable and comma-separated; the new strand depends on each target). A missing target fails the create, like `dep add` | -| `braid update <id> [flags]` | change fields: `--title --description --design --acceptance-criteria --notes --status --priority --type --assignee --external-ref --add-label --remove-label`; empty string clears | -| `braid close <id>... [--reason R] [--force]` | close; refuses if open children unless `--force` | +| `braid create <title> [flags]` | new strand; prints its id. Flags: `--description --description-file --type --priority --label --slug --assignee --deps --json`. `--deps <type>:<target-id>` attaches dependencies atomically (repeatable and comma-separated; the new strand depends on each target). A missing target fails the create, like `dep add` | +| `braid update <id> [flags]` | change fields: `--title --description --design --acceptance-criteria --notes` (each prose field also takes `--<field>-file PATH`), `--status --priority --type --assignee --external-ref --add-label --remove-label`; empty string clears | +| `braid close <id>... [--reason R \| --reason-file PATH] [--force]` | close; refuses if open children unless `--force` | | `braid reopen <id>...` | reopen closed strands | | `braid defer <id>... [--until W]` | park strands. `--until` takes RFC 3339 (`2026-07-01T09:00:00Z`), a date (`2026-07-01`), or a duration (`36h`, `7d`, `2w`); once it passes, the strand counts as ready again (no daemon — readers compute the wake). Without `--until` it sleeps until `undefer` | | `braid undefer <id>...` | wake deferred strands now (status back to `open`) | | `braid delete <id>... [--force]` | remove strands entirely. Prefer `close` — a delete wins over concurrent edits and cannot be undone; `--force` needed if other strands reference the target | -| `braid comment <id> <text>` | append a comment | +| `braid comment <id> (<text> \| -F PATH)` | append a comment; `-F`/`--file` reads it from a file | | `braid dep add <id> <target> [--type T]` | `<id>` depends on `<target>`; default type `blocks` | | `braid dep remove <id> <target> [--type T]` | remove dependency | | `braid dep list <id>` | dependencies in both directions | diff --git a/crates/braid/src/main.rs b/crates/braid/src/main.rs index 1ce286d..1a371d9 100644 --- a/crates/braid/src/main.rs +++ b/crates/braid/src/main.rs @@ -1,3 +1,7 @@ +use std::io::Read; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, bail}; use clap::{Parser, Subcommand}; use braid::commands; @@ -10,6 +14,8 @@ struct Cli { } #[derive(Subcommand)] +// parsed once per process, so the variant size difference costs nothing +#[allow(clippy::large_enum_variant)] enum Cmd { /// Create a new skein (or join an existing one) and write .braid.toml Init { @@ -34,6 +40,9 @@ enum Cmd { title: String, #[arg(short, long)] description: Option<String>, + /// Read the description from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "description")] + description_file: Option<PathBuf>, /// Issue type: task|bug|feature|epic|chore|docs|question #[arg(short = 't', long = "type", default_value = "task")] issue_type: String, @@ -94,12 +103,24 @@ enum Cmd { title: Option<String>, #[arg(short, long)] description: Option<String>, + /// Read the description from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "description")] + description_file: Option<PathBuf>, #[arg(long)] design: Option<String>, + /// Read the design from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "design")] + design_file: Option<PathBuf>, #[arg(long)] acceptance_criteria: Option<String>, + /// Read the acceptance criteria from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "acceptance_criteria")] + acceptance_criteria_file: Option<PathBuf>, #[arg(long)] notes: Option<String>, + /// Read the notes from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "notes")] + notes_file: Option<PathBuf>, /// open|in_progress|blocked|deferred|closed #[arg(long)] status: Option<String>, @@ -126,6 +147,9 @@ enum Cmd { ids: Vec<String>, #[arg(long)] reason: Option<String>, + /// Read the reason from a file (`-` for stdin), byte for byte + #[arg(long, value_name = "PATH", conflicts_with = "reason")] + reason_file: Option<PathBuf>, /// Close even if the strand still has open children #[arg(long)] force: bool, @@ -160,7 +184,19 @@ enum Cmd { force: bool, }, /// Add a comment to a strand; prints the comment id - Comment { id: String, text: String }, + Comment { + id: String, + text: Option<String>, + /// Read the comment from a file (`-` for stdin), byte for byte + #[arg( + short = 'F', + long, + value_name = "PATH", + conflicts_with = "text", + required_unless_present = "text" + )] + file: Option<PathBuf>, + }, /// Manage dependencies between strands Dep { #[command(subcommand)] @@ -291,6 +327,33 @@ enum DepCmd { Cycles, } +/// Fill each prose field from its `--<field>-file` PATH, if given. `-` reads +/// stdin, which only one field per command can use. Text is kept byte for +/// byte (no trimming, no newline translation) but must be UTF-8. +fn read_text_files(fields: Vec<(&mut Option<String>, Option<PathBuf>)>) -> anyhow::Result<()> { + let stdin = Path::new("-"); + if fields.iter().filter(|(_, file)| file.as_deref() == Some(stdin)).count() > 1 { + bail!("only one --*-file flag can read from stdin (-)"); + } + for (field, file) in fields { + let Some(path) = file else { continue }; + let (bytes, source) = if path == stdin { + let mut buf = Vec::new(); + std::io::stdin().read_to_end(&mut buf).context("cannot read stdin")?; + (buf, "stdin".to_string()) + } else { + let bytes = + std::fs::read(&path).with_context(|| format!("cannot read {}", path.display()))?; + (bytes, path.display().to_string()) + }; + *field = Some( + String::from_utf8(bytes) + .map_err(|e| anyhow::anyhow!("{source} is not valid UTF-8: {e}"))?, + ); + } + Ok(()) +} + #[tokio::main] async fn main() { let cli = Cli::parse(); @@ -309,7 +372,8 @@ async fn main() { } Cmd::Create { title, - description, + mut description, + description_file, issue_type, priority, label, @@ -318,20 +382,24 @@ async fn main() { deps, json, } => { - commands::create( - &cwd, - commands::CreateOpts { - title, - description, - issue_type, - priority, - labels: label, - slug, - assignee, - deps, - json, - }, - ) + async { + read_text_files(vec![(&mut description, description_file)])?; + commands::create( + &cwd, + commands::CreateOpts { + title, + description, + issue_type, + priority, + labels: label, + slug, + assignee, + deps, + json, + }, + ) + .await + } .await } Cmd::Show { id, json } => commands::show(&cwd, &id, json).await, @@ -343,10 +411,14 @@ async fn main() { Cmd::Update { id, title, - description, - design, - acceptance_criteria, - notes, + mut description, + description_file, + mut design, + design_file, + mut acceptance_criteria, + acceptance_criteria_file, + mut notes, + notes_file, status, priority, issue_type, @@ -356,33 +428,56 @@ async fn main() { remove_label, json, } => { - commands::update( - &cwd, - &id, - commands::UpdateOpts { - title, - description, - design, - acceptance_criteria, - notes, - status, - priority, - issue_type, - assignee, - external_ref, - add_labels: add_label, - remove_labels: remove_label, - json, - }, - ) + async { + read_text_files(vec![ + (&mut description, description_file), + (&mut design, design_file), + (&mut acceptance_criteria, acceptance_criteria_file), + (&mut notes, notes_file), + ])?; + commands::update( + &cwd, + &id, + commands::UpdateOpts { + title, + description, + design, + acceptance_criteria, + notes, + status, + priority, + issue_type, + assignee, + external_ref, + add_labels: add_label, + remove_labels: remove_label, + json, + }, + ) + .await + } + .await + } + Cmd::Close { ids, mut reason, reason_file, force } => { + async { + read_text_files(vec![(&mut reason, reason_file)])?; + commands::close(&cwd, &ids, reason, force).await + } .await } - Cmd::Close { ids, reason, force } => commands::close(&cwd, &ids, reason, force).await, Cmd::Reopen { ids } => commands::reopen(&cwd, &ids).await, Cmd::Defer { ids, until } => commands::defer(&cwd, &ids, until).await, Cmd::Undefer { ids } => commands::undefer(&cwd, &ids).await, Cmd::Delete { ids, force } => commands::delete(&cwd, &ids, force).await, - Cmd::Comment { id, text } => commands::comment(&cwd, &id, &text).await, + Cmd::Comment { id, mut text, file } => { + async { + read_text_files(vec![(&mut text, file)])?; + // clap requires TEXT or --file, so one of them filled `text` + let text = text.unwrap_or_default(); + commands::comment(&cwd, &id, &text).await + } + .await + } Cmd::Dep { cmd } => match cmd { DepCmd::Add { issue, target, dep_type } => { commands::dep_add(&cwd, &issue, &target, &dep_type).await diff --git a/crates/braid/tests/text_file_cli.rs b/crates/braid/tests/text_file_cli.rs new file mode 100644 index 0000000..daea156 --- /dev/null +++ b/crates/braid/tests/text_file_cli.rs @@ -0,0 +1,213 @@ +//! e2e tests for reading prose fields from a file or stdin (`--<field>-file`, +//! `comment -F`). Text must round-trip byte for byte: no trimming, no newline +//! translation. All offline (dead server). + +use std::path::{Path, PathBuf}; + +use predicates::prelude::*; + +const DEAD_SERVER: &str = "tcp://127.0.0.1:1"; + +/// Text that shells mangle: a doubled backslash (Windows verbatim path), a +/// line starting with `/` (MSYS path conversion), several lines, one CRLF +/// line ending and a trailing newline. +const TRICKY: &str = "verbatim path: \\\\?\\C:\\x\n/proj starts this line\r\nlast line\n"; + +struct Skein { + home: PathBuf, + work: PathBuf, +} + +impl Skein { + fn new() -> (tempfile::TempDir, Skein) { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let work = tmp.path().join("work"); + std::fs::create_dir_all(&home).unwrap(); + std::fs::create_dir_all(&work).unwrap(); + let t = Skein { home, work }; + t.braid().args(["init", "--name", "text", "--sync-server", DEAD_SERVER]).assert().success(); + (tmp, t) + } + + fn braid(&self) -> assert_cmd::Command { + let mut c = assert_cmd::Command::cargo_bin("braid").unwrap(); + c.current_dir(&self.work) + .env_clear() + .env("PATH", std::env::var("PATH").unwrap()) + .env("HOME", &self.home) + .env("BRAID_SYNC_TIMEOUT", "0.3"); + c + } + + fn create(&self, args: &[&str]) -> String { + let out = self.braid().arg("create").args(args).assert().success(); + String::from_utf8(out.get_output().stdout.clone()).unwrap().trim().to_string() + } + + fn show_json(&self, id: &str) -> serde_json::Value { + let out = self.braid().args(["show", id, "--json"]).assert().success(); + serde_json::from_slice(&out.get_output().stdout).unwrap() + } + + /// Write `text` to `name` in the working directory, returning its path. + fn write(&self, name: &str, text: &str) -> String { + let p = self.work.join(name); + std::fs::write(&p, text).unwrap(); + p.to_str().unwrap().to_string() + } +} + +fn single_comment_text(json: &serde_json::Value) -> String { + let comments = json["comments"].as_object().unwrap(); + assert_eq!(comments.len(), 1, "expected exactly one comment: {json}"); + comments.values().next().unwrap()["text"].as_str().unwrap().to_string() +} + +#[test] +fn create_description_from_file_and_stdin() { + let (_tmp, t) = Skein::new(); + let f = t.write("desc.txt", TRICKY); + + let from_file = t.create(&["from file", "--description-file", &f]); + assert_eq!(t.show_json(&from_file)["description"], TRICKY); + + let out = t + .braid() + .args(["create", "from stdin", "--description-file", "-"]) + .write_stdin(TRICKY) + .assert() + .success(); + let from_stdin = String::from_utf8(out.get_output().stdout.clone()).unwrap().trim().to_string(); + assert_eq!(t.show_json(&from_stdin)["description"], TRICKY); +} + +#[test] +fn update_prose_fields_from_files_and_stdin() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["target"]); + let desc = t.write("desc.txt", &format!("desc {TRICKY}")); + let design = t.write("design.txt", &format!("design {TRICKY}")); + let ac = t.write("ac.txt", &format!("ac {TRICKY}")); + + t.braid() + .args(["update", &id, "--description-file", &desc, "--design-file", &design]) + .args(["--acceptance-criteria-file", &ac, "--notes-file", "-"]) + .write_stdin(format!("notes {TRICKY}")) + .assert() + .success(); + + let json = t.show_json(&id); + assert_eq!(json["description"], format!("desc {TRICKY}")); + assert_eq!(json["design"], format!("design {TRICKY}")); + assert_eq!(json["acceptance_criteria"], format!("ac {TRICKY}")); + assert_eq!(json["notes"], format!("notes {TRICKY}")); +} + +#[test] +fn close_reason_from_file_and_stdin() { + let (_tmp, t) = Skein::new(); + let a = t.create(&["a"]); + let b = t.create(&["b"]); + let f = t.write("reason.txt", TRICKY); + + t.braid().args(["close", &a, "--reason-file", &f]).assert().success(); + assert_eq!(t.show_json(&a)["close_reason"], TRICKY); + + t.braid().args(["close", &b, "--reason-file", "-"]).write_stdin(TRICKY).assert().success(); + assert_eq!(t.show_json(&b)["close_reason"], TRICKY); +} + +#[test] +fn comment_from_file_and_stdin() { + let (_tmp, t) = Skein::new(); + let a = t.create(&["a"]); + let b = t.create(&["b"]); + let c = t.create(&["c"]); + let f = t.write("comment.txt", TRICKY); + + t.braid().args(["comment", &a, "-F", &f]).assert().success(); + assert_eq!(single_comment_text(&t.show_json(&a)), TRICKY); + + t.braid().args(["comment", &b, "--file", "-"]).write_stdin(TRICKY).assert().success(); + assert_eq!(single_comment_text(&t.show_json(&b)), TRICKY); + + // the positional form still works + t.braid().args(["comment", &c, "inline text"]).assert().success(); + assert_eq!(single_comment_text(&t.show_json(&c)), "inline text"); +} + +#[test] +fn inline_and_file_flags_are_mutually_exclusive() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["a"]); + let f = t.write("x.txt", "x"); + + t.braid() + .args(["create", "t", "-d", "inline", "--description-file", &f]) + .assert() + .failure() + .stderr(predicate::str::contains("cannot be used with")); + t.braid() + .args(["update", &id, "--notes", "inline", "--notes-file", &f]) + .assert() + .failure() + .stderr(predicate::str::contains("cannot be used with")); + t.braid() + .args(["close", &id, "--reason", "inline", "--reason-file", &f]) + .assert() + .failure() + .stderr(predicate::str::contains("cannot be used with")); + t.braid() + .args(["comment", &id, "inline", "-F", &f]) + .assert() + .failure() + .stderr(predicate::str::contains("cannot be used with")); +} + +#[test] +fn comment_requires_text_or_file() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["a"]); + t.braid().args(["comment", &id]).assert().failure().stderr(predicate::str::contains("--file")); +} + +#[test] +fn stdin_can_feed_only_one_field() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["a"]); + t.braid() + .args(["update", &id, "--design-file", "-", "--notes-file", "-"]) + .write_stdin("x") + .assert() + .failure() + .stderr(predicate::str::contains("stdin")); + // nothing was written + let json = t.show_json(&id); + assert!(json["design"].is_null() || json["design"] == "", "design changed: {json}"); +} + +#[test] +fn unreadable_file_errors_with_its_path() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["a"]); + let missing = Path::new(&t.work).join("nope.txt"); + t.braid() + .args(["comment", &id, "-F", missing.to_str().unwrap()]) + .assert() + .failure() + .stderr(predicate::str::contains("nope.txt")); +} + +#[test] +fn non_utf8_file_is_rejected() { + let (_tmp, t) = Skein::new(); + let id = t.create(&["a"]); + let p = t.work.join("latin1.txt"); + std::fs::write(&p, b"caf\xe9\n").unwrap(); + t.braid() + .args(["comment", &id, "-F", p.to_str().unwrap()]) + .assert() + .failure() + .stderr(predicate::str::contains("UTF-8")); +}