From 42beee2189001a2130f331b53cfa4011630029a3 Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Mon, 19 Oct 2026 18:40:44 -0500 Subject: [PATCH 1/4] Verifications, and immutable releases --- .github/workflows/verify-release.yml | 15 +++++++++++++++ AGENTS.md | 2 +- README.md | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/verify-release.yml b/.github/workflows/verify-release.yml index 349b5bb..82c7028 100644 --- a/.github/workflows/verify-release.yml +++ b/.github/workflows/verify-release.yml @@ -10,6 +10,21 @@ on: required: true jobs: + attestation: + runs-on: ubuntu-latest + permissions: + contents: read + attestations: read + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ github.event.release.tag_name || inputs.version }} + steps: + - run: | + tag="v${TAG#v}" + gh release verify "$tag" --repo "$GITHUB_REPOSITORY" + gh release download "$tag" --repo "$GITHUB_REPOSITORY" --pattern SHA256SUMS --dir dist + gh release verify-asset "$tag" dist/SHA256SUMS --repo "$GITHUB_REPOSITORY" + install: strategy: fail-fast: false diff --git a/AGENTS.md b/AGENTS.md index 3e384f5..926e936 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ A terminal coding agent for local models. The binary is `quill`; the assistant i CI (`.github/workflows/ci.yml`) builds, lints with `-D warnings` and tests on Windows, Linux and macOS, packs and installs a debug build with both install scripts, and runs `cargo deny check` once. All must stay green. -Releases (`.github/workflows/release.yml`) run on every push to `main` whose workspace version has no published release. The version needs a `## [] - ` section in `CHANGELOG.md`, whose body becomes the release notes. Windows (x64), Linux (x64 and ARM, static musl) and both macOS targets are built, packed by `scripts/package.sh` as `quill--` with a checksum, and attached with `SHA256SUMS`, `install.sh` and `install.ps1` to a draft release `Quill Code v` tagged `v`. Merging again with the same version rebuilds and replaces the draft. It is published by hand, which runs `verify-release.yml`: it installs the release on every system and checks `quill --version`, `quill update` and `quill versions`. Keep the archive names and `SHA256SUMS` as they are, because `quill update ` installs old releases with the newest installer. +Releases (`.github/workflows/release.yml`) run on every push to `main` whose workspace version has no published release. The version needs a `## [] - ` section in `CHANGELOG.md`, whose body becomes the release notes. Windows (x64), Linux (x64 and ARM, static musl) and both macOS targets are built, packed by `scripts/package.sh` as `quill--` with a checksum, and attached with `SHA256SUMS`, `install.sh` and `install.ps1` to a draft release `Quill Code v` tagged `v`. Merging again with the same version rebuilds and replaces the draft. It is published by hand, which runs `verify-release.yml`: it checks the release's attestation with `gh release verify` and `SHA256SUMS` against it with `gh release verify-asset`, installs the release on every system and checks `quill --version`, `quill update` and `quill versions`. The repository has immutable releases turned on, so a published release's files and tag can never change: everything must be attached while it is a draft, and a broken release is fixed with a new version. Keep the archive names and `SHA256SUMS` as they are, because `quill update ` installs old releases with the newest installer. ## Rules that do not bend diff --git a/README.md b/README.md index 15660ff..50247b2 100644 --- a/README.md +++ b/README.md @@ -290,7 +290,7 @@ You need Rust 1.88 or newer from [rustup](https://rustup.rs) and a C compiler: t | `cargo deny check` | Licence and banned-crate policy (`cargo install cargo-deny`) | | `vhs docs/demo/demo.tape` | Record the demo above again (needs [VHS](https://github.com/charmbracelet/vhs) and a running model) | -Releases come from `main`: bump `version` in `Cargo.toml`, add its section to `CHANGELOG.md`, and merge `dev` into `main`. CI builds every target into a draft release, which is published by hand once it has been tried. The architecture and conventions are in [AGENTS.md](AGENTS.md). +Releases come from `main`: bump `version` in `Cargo.toml`, add its section to `CHANGELOG.md`, and merge `dev` into `main`. CI builds every target into a draft release, which is published by hand once it has been tried. Published releases are immutable: their files and tag can never be changed, and `gh release verify-asset v ` checks any download against the release's signed attestation. The architecture and conventions are in [AGENTS.md](AGENTS.md).
From e0804258aad86a55bdc87308310b33301d6ada57 Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Mon, 19 Oct 2026 18:48:54 -0500 Subject: [PATCH 2/4] Update deps, versions and so on. --- .github/workflows/release.yml | 4 ++-- AGENTS.md | 2 +- CHANGELOG.md | 17 ++++++++++---- Cargo.lock | 40 ++++++++++++++++----------------- Cargo.toml | 2 +- crates/quill-code/src/update.rs | 4 ++-- crates/quill-git/src/github.rs | 2 -- 7 files changed, 39 insertions(+), 32 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4310713..f5bf8f3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -115,10 +115,10 @@ jobs: printf '## Install\n\n' printf 'macOS and Linux:\n\n```\ncurl -fsSL https://github.com/%s/releases/latest/download/install.sh | sh\n```\n\n' "$GITHUB_REPOSITORY" printf 'Windows (PowerShell):\n\n```\nirm https://github.com/%s/releases/latest/download/install.ps1 | iex\n```\n\n' "$GITHUB_REPOSITORY" - printf 'Already installed? Run `quill update`, or `quill update ` to switch to another release.\n' + printf 'Already installed? Run `quill update`, or `quill update ` to switch to another release.\n\n' } > ../notes.md for id in $(gh api "repos/$GITHUB_REPOSITORY/releases" --paginate --jq ".[] | select(.draft and .tag_name == \"$TAG\") | .id"); do echo "Replacing the earlier draft of $TAG" gh api -X DELETE "repos/$GITHUB_REPOSITORY/releases/$id" done - gh release create "$TAG" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "Quill Code $TAG" --notes-file ../notes.md --draft \ No newline at end of file + gh release create "$TAG" * --repo "$GITHUB_REPOSITORY" --target "$GITHUB_SHA" --title "${TAG#v}" --notes-file ../notes.md --generate-notes --draft \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 926e936..a7d5318 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ A terminal coding agent for local models. The binary is `quill`; the assistant i CI (`.github/workflows/ci.yml`) builds, lints with `-D warnings` and tests on Windows, Linux and macOS, packs and installs a debug build with both install scripts, and runs `cargo deny check` once. All must stay green. -Releases (`.github/workflows/release.yml`) run on every push to `main` whose workspace version has no published release. The version needs a `## [] - ` section in `CHANGELOG.md`, whose body becomes the release notes. Windows (x64), Linux (x64 and ARM, static musl) and both macOS targets are built, packed by `scripts/package.sh` as `quill--` with a checksum, and attached with `SHA256SUMS`, `install.sh` and `install.ps1` to a draft release `Quill Code v` tagged `v`. Merging again with the same version rebuilds and replaces the draft. It is published by hand, which runs `verify-release.yml`: it checks the release's attestation with `gh release verify` and `SHA256SUMS` against it with `gh release verify-asset`, installs the release on every system and checks `quill --version`, `quill update` and `quill versions`. The repository has immutable releases turned on, so a published release's files and tag can never change: everything must be attached while it is a draft, and a broken release is fixed with a new version. Keep the archive names and `SHA256SUMS` as they are, because `quill update ` installs old releases with the newest installer. +Releases (`.github/workflows/release.yml`) run on every push to `main` whose workspace version has no published release. The version needs a `## [] - ` section in `CHANGELOG.md`, whose body becomes the release notes. Windows (x64), Linux (x64 and ARM, static musl) and both macOS targets are built, packed by `scripts/package.sh` as `quill--` with a checksum, and attached with `SHA256SUMS`, `install.sh` and `install.ps1` to a draft release named `` and tagged `v`. Its notes are the changelog section and the install commands, followed by GitHub's generated "What's Changed" and "Full Changelog". Merging again with the same version rebuilds and replaces the draft. It is published by hand, which runs `verify-release.yml`: it checks the release's attestation with `gh release verify` and `SHA256SUMS` against it with `gh release verify-asset`, installs the release on every system and checks `quill --version`, `quill update` and `quill versions`. The repository has immutable releases turned on, so a published release's files and tag can never change: everything must be attached while it is a draft, and a broken release is fixed with a new version. Keep the archive names and `SHA256SUMS` as they are, because `quill update ` installs old releases with the newest installer. ## Rules that do not bend diff --git a/CHANGELOG.md b/CHANGELOG.md index 25262a3..3d60602 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.0.1] - TBD + +### Changed + +- Releases are named by their version alone, and their notes end with GitHub's list of what changed and a link to the full comparison with the previous release. +- `quill versions` lists each release's version and date without repeating its name. +- Dependencies are updated to their newest versions, including the bundled root certificates. + +### Security + +- Releases are immutable from 1.0.1 on: once published, their files and tag can never change, and each one carries a signed attestation. Check a download with `gh release verify-asset v1.0.1 `. + ## [1.0.0] - 2026-10-19 ### Added @@ -60,7 +72,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Isolated copies (git worktrees) so parallel threads never collide. - A commit dialog that can push, open a pull request page or publish a new GitHub repository, and new projects that can start on GitHub with a first branch of your choosing. - Slash commands, @ file mentions, image and file attachments with previews, pinned models with Ctrl+1 to 9, a context ring, a PowerShell drawer and saved history. -- Models, context windows, vision and thinking controls detected from the server. - -[unreleased]: https://github.com/Smoffyy/quill-code/compare/v1.0.0...HEAD -[1.0.0]: https://github.com/Smoffyy/quill-code/releases/tag/v1.0.0 \ No newline at end of file +- Models, context windows, vision and thinking controls detected from the server. \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index eccafe2..245652d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,9 +144,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cc" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" dependencies = [ "find-msvc-tools", "shlex", @@ -428,9 +428,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" @@ -732,9 +732,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "linux-raw-sys" @@ -1026,7 +1026,7 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" [[package]] name = "quill-code" -version = "1.0.0" +version = "1.0.1" dependencies = [ "arboard", "base64", @@ -1047,7 +1047,7 @@ dependencies = [ [[package]] name = "quill-config" -version = "1.0.0" +version = "1.0.1" dependencies = [ "quill-core", "quill-providers", @@ -1057,7 +1057,7 @@ dependencies = [ [[package]] name = "quill-core" -version = "1.0.0" +version = "1.0.1" dependencies = [ "globset", "ignore", @@ -1071,7 +1071,7 @@ dependencies = [ [[package]] name = "quill-git" -version = "1.0.0" +version = "1.0.1" dependencies = [ "serde_json", "ureq", @@ -1079,7 +1079,7 @@ dependencies = [ [[package]] name = "quill-providers" -version = "1.0.0" +version = "1.0.1" dependencies = [ "serde", "serde_json", @@ -1088,7 +1088,7 @@ dependencies = [ [[package]] name = "quill-weave" -version = "1.0.0" +version = "1.0.1" [[package]] name = "quote" @@ -1258,9 +1258,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -1588,9 +1588,9 @@ dependencies = [ [[package]] name = "ureq-proto" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ "base64", "http", @@ -1652,18 +1652,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] diff --git a/Cargo.toml b/Cargo.toml index d747573..c5db2c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "1.0.0" +version = "1.0.1" edition = "2024" license = "MIT" authors = ["Smoffyy"] diff --git a/crates/quill-code/src/update.rs b/crates/quill-code/src/update.rs index 83281cb..ade0bfa 100644 --- a/crates/quill-code/src/update.rs +++ b/crates/quill-code/src/update.rs @@ -99,7 +99,7 @@ pub fn versions() -> u8 { for release in &releases { let tags = tags(release, newest.as_deref()); let tags = if tags.is_empty() { String::new() } else { format!(" ({})", tags.join(", ")) }; - println!("{:<10} {:<10} {}{tags}", release.version, release.date, release.title); + println!("{:<10} {}{tags}", release.version, release.date); } println!("\nSwitch to one with: quill update "); 0 @@ -202,7 +202,7 @@ mod tests { use super::*; fn release(version: &str, prerelease: bool) -> Release { - Release { version: version.into(), title: String::new(), date: String::new(), prerelease } + Release { version: version.into(), date: String::new(), prerelease } } #[test] diff --git a/crates/quill-git/src/github.rs b/crates/quill-git/src/github.rs index bba751f..0ad2218 100644 --- a/crates/quill-git/src/github.rs +++ b/crates/quill-git/src/github.rs @@ -30,7 +30,6 @@ pub enum PullState { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Release { pub version: String, - pub title: String, pub date: String, pub prerelease: bool, } @@ -151,7 +150,6 @@ fn parse_release(release: &Value) -> Option { } Some(Release { version: release["tag_name"].as_str()?.trim_start_matches('v').to_string(), - title: release["name"].as_str().unwrap_or_default().to_string(), date: release["published_at"].as_str().unwrap_or_default().chars().take(10).collect(), prerelease: release["prerelease"] == true, }) From 9af1538d4c59861a7dea4b398940f58945a61ccf Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Mon, 19 Oct 2026 21:37:52 -0500 Subject: [PATCH 3/4] Major bug fixes --- CHANGELOG.md | 15 ++ crates/quill-code/src/history.rs | 6 + crates/quill-core/src/prompt.rs | 1 + crates/quill-core/src/tools/args.rs | 43 +++- crates/quill-core/src/tools/fs.rs | 341 +++++++++++++++++++++++++-- crates/quill-core/src/tools/plan.rs | 36 ++- crates/quill-core/src/tools/shell.rs | 55 +++++ 7 files changed, 456 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d60602..2092744 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Releases are named by their version alone, and their notes end with GitHub's list of what changed and a link to the full comparison with the previous release. - `quill versions` lists each release's version and date without repeating its name. - Dependencies are updated to their newest versions, including the bundled root certificates. +- `read_file` lists what a folder contains when it is given a folder, and calls to `list_dir`, `list_files` or `ls` go to it. +- Reading a path that does not exist opens the file when exactly one file in the project has that name; otherwise the error names the files with that name, or shows what the nearest folder contains. +- When `find_files`, or `grep` with a file filter, finds nothing, the reply lists the kinds of files the folder has, so a model that guessed the wrong language corrects itself. +- When an edit's text is not in the file, the error names the lines that are missing and shows the file's current lines at that spot, ready to copy. +- A failed PowerShell command that used `&&`, a Unix command such as `grep`, `head` or `touch`, or a Unix flag such as `rm -rf` now ends with the PowerShell way to do it. +- After renaming, moving or deleting something, Quill searches for the old name to make sure nothing still uses it. + +### Fixed + +- Glob patterns with a brace group, such as `**/*.{js,ts}`, no longer fail in `find_files` and `grep`. +- Writes and edits that would replace real code with a placeholder such as `// ... existing code ...` are refused instead of deleting that code. +- An edit that would leave a file unchanged now says so instead of reporting a change, and rewriting a file with its current content no longer asks for approval. +- Reading a file with very long lines, such as minified code, no longer floods the model's context. +- Tool arguments that arrive encoded twice, wrapped in an extra object, followed by stray characters, or with lists sent as text are read correctly. +- Text a model sends with escaped line breaks (`\n`) instead of real ones is written and matched as intended. ### Security diff --git a/crates/quill-code/src/history.rs b/crates/quill-code/src/history.rs index 3ff0d5f..61649f4 100644 --- a/crates/quill-code/src/history.rs +++ b/crates/quill-code/src/history.rs @@ -310,6 +310,10 @@ fn explored_output(tool: &ToolItem, output: &str) -> String { let more = lines.last().and_then(|line| line.strip_prefix("... and ")?.split(' ').next()?.parse::().ok()); let found = lines.iter().filter(|line| **line != "--").count() - usize::from(more.is_some()) + more.unwrap_or(0); match tool.tool.as_str() { + "read_file" if lines.first().is_some_and(|line| line.ends_with(" is empty.")) => "Empty folder".into(), + "read_file" if lines.first().is_some_and(|line| line.ends_with(" contains:")) => { + format!("Listed {}", plural(found - 1, "item")) + } "read_file" => format!( "Read {}", plural(lines.iter().filter(|line| line.trim_start().starts_with(|c: char| c.is_ascii_digit())).count(), "line") @@ -940,6 +944,8 @@ mod tests { assert_eq!(searched("grep", "a.hx:1: sick\n--\na.hx:9: sick\n... and 4 more matches. Narrow it."), " └ Found 6 lines"); assert_eq!(searched("find_files", "No files match \"*.hx\". Use grep."), " └ No files found"); assert_eq!(searched("find_files", "a.hx\nb.hx"), " └ Found 2 files"); + assert_eq!(searched("read_file", "src/ contains:\nlib/\na.js\n... and 3 more."), " └ Listed 5 items"); + assert_eq!(searched("read_file", "src/ is empty."), " └ Empty folder"); } #[test] diff --git a/crates/quill-core/src/prompt.rs b/crates/quill-core/src/prompt.rs index 99c865d..d4f14f3 100644 --- a/crates/quill-core/src/prompt.rs +++ b/crates/quill-core/src/prompt.rs @@ -42,6 +42,7 @@ You are responsible for the code working, not only for writing it. After you cha - Run the checks that cover what you changed: the compiler or type checker (such as cargo check, tsc --noEmit, go build or dotnet build), the linter the project already uses (such as cargo clippy, eslint or ruff), and the tests closest to your change, then the whole test suite when the change is broad. - When a check fails, read the error, fix the cause and run the check again until it passes. Never weaken or delete a test to make it pass unless the user asks. - When you add behaviour and the project has tests, add or update a test for it. +- After you rename, move or delete something, grep for its old name and location to make sure nothing still defines or uses it. - Do not install new tools or dependencies only to check your work. When the project has no way to build or test the change, or a check needs something that is missing, say so instead of claiming it works. - Before your final reply, make sure the last run of every check you used passed."; diff --git a/crates/quill-core/src/tools/args.rs b/crates/quill-core/src/tools/args.rs index 33f2356..a20fff7 100644 --- a/crates/quill-core/src/tools/args.rs +++ b/crates/quill-core/src/tools/args.rs @@ -12,12 +12,39 @@ pub const BRANCH: [&str; 3] = ["branch", "branch_name", "new_branch"]; pub const TITLE: [&str; 2] = ["title", "pr_title"]; pub const BODY: [&str; 3] = ["body", "description", "pr_body"]; +const WRAPPERS: [&str; 4] = ["arguments", "args", "parameters", "input"]; + +fn first_value(text: &str) -> Option { + serde_json::Deserializer::from_str(text).into_iter::().next()?.ok() +} + pub fn parse(arguments: &str) -> Value { let text = arguments.trim(); if text.is_empty() { return json!({}); } - serde_json::from_str(text).unwrap_or_else(|_| json!({ "__invalid": text })) + let mut value = match first_value(text) { + Some(value) => value, + None => return json!({ "__invalid": text }), + }; + if let Some(inner) = value.as_str().and_then(first_value).filter(Value::is_object) { + value = inner; + } + if let Some(object) = value.as_object() + && object.len() == 1 + && let Some(inner) = WRAPPERS.iter().find_map(|key| object.get(*key)).filter(|inner| inner.is_object()) + { + return inner.clone(); + } + value +} + +pub fn list(args: &Value, keys: &[&str]) -> Option> { + keys.iter().find_map(|key| match args.get(*key)? { + Value::Array(items) => Some(items.clone()), + Value::String(text) => first_value(text.trim()).and_then(|value| value.as_array().cloned()), + _ => None, + }) } pub fn invalid(args: &Value) -> Option<&str> { @@ -54,6 +81,20 @@ mod tests { assert_eq!(parse(""), json!({})); } + #[test] + fn wrapped_and_encoded_arguments_are_unwrapped() { + assert_eq!(parse("{\"path\": \"a\"}}")["path"], "a"); + assert_eq!(parse("{\"path\": \"a\"}")["path"], "a"); + assert_eq!(parse("\"{\\\"path\\\": \\\"a\\\"}\"")["path"], "a"); + assert_eq!(parse("{\"arguments\": {\"path\": \"a\"}}")["path"], "a"); + assert_eq!(parse("{\"input\": \"text\"}")["input"], "text"); + let args = json!({ "plan": "[{\"step\": \"a\"}]", "edits": [1], "content": "[1, 2]" }); + assert_eq!(list(&args, &["plan"]).unwrap().len(), 1); + assert_eq!(list(&args, &["edits"]).unwrap(), vec![json!(1)]); + assert!(list(&args, &["missing"]).is_none()); + assert_eq!(text(&args, &CONTENT), Some("[1, 2]")); + } + #[test] fn lenient_keys_and_values_are_read() { let args = json!({ "file_path": "a.rs", "start": "4", "replace_all": "true" }); diff --git a/crates/quill-core/src/tools/fs.rs b/crates/quill-core/src/tools/fs.rs index 9ee07a8..0e5241e 100644 --- a/crates/quill-core/src/tools/fs.rs +++ b/crates/quill-core/src/tools/fs.rs @@ -1,9 +1,10 @@ use std::fs; use std::path::{Path, PathBuf}; +use std::sync::LazyLock; use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; use ignore::WalkBuilder; -use regex::RegexBuilder; +use regex::{Regex, RegexBuilder}; use serde_json::{Value, json}; use super::args::{self, CONTENT, GLOB, NEW, OLD, PATH, PATTERN}; @@ -80,9 +81,28 @@ fn reading(effect: Effect, path: &Path, action: Action) -> Prepared { } } +fn patterns(text: &str) -> Vec<&str> { + let mut parts = Vec::new(); + let mut depth = 0usize; + let mut start = 0; + for (at, c) in text.char_indices() { + match c { + '{' => depth += 1, + '}' => depth = depth.saturating_sub(1), + ',' if depth == 0 => { + parts.push(&text[start..at]); + start = at + 1; + } + _ => {} + } + } + parts.push(&text[start..]); + parts.into_iter().map(str::trim).filter(|part| !part.is_empty()).collect() +} + fn glob_set(pattern: &str) -> Result { let mut builder = GlobSetBuilder::new(); - for part in pattern.split(',').map(str::trim).filter(|part| !part.is_empty()) { + for part in patterns(pattern) { let part = part.replace('\\', "/"); let part = if part.contains(['*', '?', '[', '{']) { part } else { format!("**/*{part}*") }; let glob = GlobBuilder::new(&part).case_insensitive(true).build().map_err(|e| e.to_string())?; @@ -91,6 +111,20 @@ fn glob_set(pattern: &str) -> Result { builder.build().map_err(|e| e.to_string()) } +fn kinds(dir: &Path, limits: &Limits) -> String { + let mut counts: Vec<(String, usize)> = Vec::new(); + for path in files(dir, limits) { + let kind = path.extension().map_or_else(|| "no extension".to_string(), |ext| format!(".{}", ext.to_string_lossy().to_lowercase())); + match counts.iter_mut().find(|(seen, _)| *seen == kind) { + Some((_, count)) => *count += 1, + None => counts.push((kind, 1)), + } + } + counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + let shown: Vec = counts.iter().take(8).map(|(kind, count)| format!("{kind} ({count})")).collect(); + if shown.is_empty() { String::new() } else { format!(" The files there are: {}.", shown.join(", ")) } +} + fn clip_line(line: &str) -> String { let trimmed = line.trim(); if trimmed.chars().count() > 300 { format!("{}…", trimmed.chars().take(300).collect::()) } else { trimmed.to_string() } @@ -156,7 +190,8 @@ impl Tool for FindFiles { } if found.is_empty() { return Output::ok(format!( - "No files match \"{pattern}\". find_files matches file names and paths; to search inside files, use grep." + "No files match \"{pattern}\". find_files matches file names and paths; to search inside files, use grep.{}", + kinds(&dir, ctx.limits) )); } if extra > 0 { @@ -228,11 +263,13 @@ impl Tool for Grep { let mut out = Vec::new(); let mut matches = 0; let mut extra = 0; + let mut scanned = 0; for file in candidates { let rel = display(&base, &file); if [&filter, &within].into_iter().flatten().any(|set| !set.is_match(&rel)) { continue; } + scanned += 1; if fs::metadata(&file).map_or(true, |m| m.len() > MAX_FILE) { continue; } @@ -265,7 +302,8 @@ impl Tool for Grep { } } if out.is_empty() { - return Output::ok(format!("No matches for \"{pattern}\".")); + let hint = if scanned == 0 && !base.is_file() { kinds(&base, ctx.limits) } else { String::new() }; + return Output::ok(format!("No matches for \"{pattern}\".{hint}")); } if extra > 0 { out.push(format!("... and {extra} more matches. Narrow the search with a longer pattern, a path or a glob.")); @@ -281,15 +319,15 @@ pub struct ReadFile; const READ: Spec = Spec { name: "read_file", title: "Read files", - summary: "Reads a file, or part of one, with line numbers.", - aliases: &["read", "view", "cat", "open_file", "view_file", "get_file"], + summary: "Reads a file, or part of one, with line numbers, or lists a folder.", + aliases: &["read", "view", "cat", "open_file", "view_file", "get_file", "list_dir", "list_directory", "list_files", "ls"], toolset: Toolset::Core, category: Category::Explore, active: "Reading", done: "Read", parallel: true, - description: "Read a text file with line numbers. Read a file before changing it. In a large file, read only the lines you need with start_line and end_line.", - guide: "read_file reads a file with line numbers. Read a file before you change it, and in a large file read only the lines you need.", + description: "Read a text file with line numbers, or list what a folder contains. Read a file before changing it. In a large file, read only the lines you need with start_line and end_line.", + guide: "read_file reads a file with line numbers, or lists a folder (\".\" is the project folder). Read a file before you change it, and in a large file read only the lines you need.", }; impl Tool for ReadFile { @@ -336,12 +374,64 @@ fn span(args: &Value) -> (usize, Option) { (start, end) } +fn listing(root: &Path, dir: &Path, limits: &Limits, max: usize) -> String { + let ignored = limits.ignored.clone(); + let entries: Vec = WalkBuilder::new(dir) + .max_depth(Some(1)) + .hidden(false) + .require_git(false) + .filter_entry(move |entry| { + !ignored.iter().any(|name| entry.depth() > 0 && entry.file_name().to_string_lossy().eq_ignore_ascii_case(name)) + }) + .sort_by_file_path(|a, b| a.to_string_lossy().to_lowercase().cmp(&b.to_string_lossy().to_lowercase())) + .build() + .filter_map(Result::ok) + .filter(|entry| entry.depth() == 1) + .map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + if entry.file_type().is_some_and(|t| t.is_dir()) { format!("{name}/") } else { name } + }) + .collect(); + let name = if dir == root { "The project folder".to_string() } else { format!("{}/", display(root, dir)) }; + if entries.is_empty() { + return format!("{name} is empty."); + } + let mut out = format!("{name} contains:\n{}", entries.iter().take(max).cloned().collect::>().join("\n")); + if entries.len() > max { + out.push_str(&format!("\n... and {} more.", entries.len() - max)); + } + out +} + +fn elsewhere(root: &Path, path: &Path, limits: &Limits) -> Vec { + let Some(name) = path.file_name() else { return Vec::new() }; + files(root, limits) + .into_iter() + .filter(|found| found.file_name().is_some_and(|other| other.eq_ignore_ascii_case(name))) + .take(6) + .collect() +} + +fn missing(root: &Path, path: &Path, found: &[PathBuf], limits: &Limits) -> String { + let shown = display(root, path); + if !found.is_empty() { + let names: Vec = found.iter().map(|path| display(root, path)).collect(); + return format!("{shown} does not exist. Files with that name: {}.", names.join(", ")); + } + let folder = path.ancestors().skip(1).find(|dir| inside(dir, root) && dir.is_dir()).unwrap_or(root); + format!("{shown} does not exist. {}", listing(root, folder, limits, 40)) +} + fn read(root: &Path, path: &Path, start: usize, end: Option, limits: &Limits) -> Result { if path.is_dir() { - return Err(format!("{} is a folder. Use find_files to see what is in it.", display(root, path))); + return Ok(listing(root, path, limits, limits.max_matches)); } if !path.is_file() { - return Err(format!("{} does not exist. Use find_files to see what is there.", display(root, path))); + return match elsewhere(root, path, limits).as_slice() { + [only] => read(root, only, start, end, limits) + .map(|text| format!("{} does not exist, so this is {}:\n{text}", display(root, path), display(root, only))), + found => Err(missing(root, path, found, limits)), + }; } let text = read_text(path)?; let lines: Vec<&str> = text.lines().collect(); @@ -351,10 +441,29 @@ fn read(root: &Path, path: &Path, start: usize, end: Option, limits: &Lim if start > lines.len() { return Err(format!("The file only has {} lines.", lines.len())); } - let end = end.unwrap_or(lines.len()).min(lines.len()).min(start + limits.max_read_lines - 1).max(start); - let mut out: Vec = (start..=end) - .map(|n| if lines[n - 1].trim().is_empty() { format!("{n:>5}") } else { format!("{n:>5}→{}", lines[n - 1]) }) - .collect(); + let mut end = end.unwrap_or(lines.len()).min(lines.len()).min(start + limits.max_read_lines - 1).max(start); + let mut out = Vec::new(); + let mut size = 0; + for n in start..=end { + let line = lines[n - 1]; + let shown = if line.trim().is_empty() { + format!("{n:>5}") + } else if line.len() > limits.max_output { + let mut cut = limits.max_output; + while !line.is_char_boundary(cut) { + cut -= 1; + } + format!("{n:>5}→{}… [line {n} is {} characters long and was cut here]", &line[..cut], line.chars().count()) + } else { + format!("{n:>5}→{line}") + }; + size += shown.len(); + if size > limits.max_output && n > start { + end = n - 1; + break; + } + out.push(shown); + } if end < lines.len() || start > 1 { out.push(format!("(showing lines {start}-{end} of {}; pass start_line to read more)", lines.len())); } @@ -364,6 +473,20 @@ fn read(root: &Path, path: &Path, start: usize, end: Option, limits: &Lim Ok(out.join("\n")) } +static PLACEHOLDER: LazyLock = LazyLock::new(|| Regex::new(PLACEHOLDER_PATTERN).expect("placeholder pattern")); + +const PLACEHOLDER_PATTERN: &str = r"(?i)^\s*(?://+|#+|/\*+|)?\s*$"; + +fn placeholder<'a>(text: &'a str, before: &str) -> Option<&'a str> { + text.lines().map(str::trim).find(|line| PLACEHOLDER.is_match(line) && !before.lines().any(|old| old.trim() == *line)) +} + +fn lazy(line: &str, instead: &str) -> String { + format!( + "The text has the placeholder line \"{line}\" where real code should be. Quill writes exactly what you send, so the code it stands for would be deleted. {instead}" + ) +} + struct Change { path: PathBuf, after: String, @@ -467,11 +590,25 @@ impl Tool for WriteFile { fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { let (path, before) = target_file(ctx.root, args, "write_file")?; let content = args::text(args, &CONTENT).ok_or("write_file needs \"content\": the complete text of the file.")?; + let content = if escaped(content) { unescape(content) } else { content.to_string() }; + let content = content.as_str(); + if let Some(before) = &before + && let Some(line) = placeholder(content, before) + { + return Err(lazy( + line, + "write_file replaces the whole file, so send every line of it, or change only part of it with edit_file.", + )); + } let newline = setting(ctx.limits, &path).unwrap_or_else(|| match &before { Some(before) => before.ends_with('\n'), None => editorconfig::final_newline(&path).unwrap_or(true), }); let after = finished(content.to_string(), Some(newline)); + if before.as_deref() == Some(after.as_str()) { + let text = format!("{} already has exactly this content, so nothing changed.", display(ctx.root, &path)); + return Ok(Prepared::read(Box::new(move |_: &Ctx<'_>| Output::ok(text)))); + } let diff = diff_text(&display(ctx.root, &path), before.as_deref(), &after); let title = if diff.created { "Wants to create a file" } else { "Wants to rewrite a file" }; Ok(planned(Change { path, after, diff }, title)) @@ -518,14 +655,27 @@ impl Tool for EditFile { fn prepare(&self, args: &Value, ctx: &Ctx<'_>) -> Result { let (path, before) = target_file(ctx.root, args, "edit_file")?; - let current = before.as_deref().ok_or(format!("{} does not exist. Use write_file to create it.", display(ctx.root, &path)))?; + let current = before.as_deref().ok_or_else(|| { + format!( + "{} To create a new file, use write_file.", + missing(ctx.root, &path, &elsewhere(ctx.root, &path, ctx.limits), ctx.limits) + ) + })?; let edits = edits(args)?; let mut after = current.to_string(); for (index, (old, new, all)) in edits.iter().enumerate() { - after = replace(&after, old, new, *all) - .map_err(|error| if edits.len() > 1 { format!("Edit {}: {error}", index + 1) } else { error })?; + let checked = match placeholder(new, old) { + Some(line) => { + Err(lazy(line, "Send the complete new_text, or make old_text smaller so new_text only needs the lines that change.")) + } + None => replace(&after, old, new, *all), + }; + after = checked.map_err(|error| if edits.len() > 1 { format!("Edit {}: {error}", index + 1) } else { error })?; } let after = finished(after, setting(ctx.limits, &path)); + if after == current { + return Err("This edit would leave the file exactly as it is: new_text gives the same result as the text already there. Put your change in new_text.".into()); + } let diff = diff_text(&display(ctx.root, &path), before.as_deref(), &after); Ok(planned(Change { path, after, diff }, "Wants to change a file")) } @@ -539,7 +689,7 @@ fn edits(args: &Value) -> Result, String> { )?; Ok((old.replace(NEWLINE_NOTE, ""), new.replace(NEWLINE_NOTE, ""), args::flag(value, &["replace_all", "all"]))) }; - match args.get("edits").and_then(Value::as_array) { + match args::list(args, &["edits"]) { Some(list) if !list.is_empty() => list.iter().map(one).collect(), _ => Ok(vec![one(args)?]), } @@ -552,15 +702,44 @@ pub fn replace(current: &str, old: &str, new: &str, all: bool) -> Result loose_replace(current, &old, &new).ok_or_else(|| { - "old_text was not found in the file. Read the file again and copy the text exactly, including indentation.".into() - }), + 0 if escaped(&old) => replace(current, &unescape(&old), &unescape(&new), all), + 0 => loose_replace(current, &old, &new).ok_or_else(|| not_found(current, &old)), 1 => Ok(current.replacen(old.as_str(), &new, 1)), _ if all => Ok(current.replace(old.as_str(), &new)), n => Err(format!("old_text appears {n} times. Include more surrounding lines so it is unique, or set replace_all.")), } } +fn escaped(text: &str) -> bool { + !text.contains('\n') && text.matches("\\n").count() >= 2 +} + +fn unescape(text: &str) -> String { + text.replace("\\r\\n", "\n").replace("\\n", "\n").replace("\\t", "\t").replace("\\\"", "\"") +} + +fn not_found(current: &str, old: &str) -> String { + let old = without_numbers(old.trim_matches(['\r', '\n'])); + let lines: Vec<&str> = current.lines().collect(); + let wanted: Vec<&str> = old.lines().filter(|line| !line.trim().is_empty()).collect(); + let find = |want: &str| lines.iter().position(|line| line.trim() == want.trim()); + let absent: Vec<&str> = wanted.iter().copied().filter(|want| find(want).is_none()).collect(); + let mut text = String::from("old_text was not found in the file."); + if absent.is_empty() { + text.push_str(" Each of its lines is in the file, but not together in that order. Copy one continuous block of lines."); + } else { + let shown: Vec = absent.iter().take(3).map(|line| format!(" {}", line.trim())).collect(); + text.push_str(&format!(" These lines of old_text are not in the file at all:\n{}", shown.join("\n"))); + } + if let Some(at) = wanted.iter().find_map(|want| find(want)) { + let to = (at + wanted.len().max(3)).min(lines.len()).min(at + 15); + let near: Vec = (at..to).map(|n| format!("{:>5}→{}", n + 1, lines[n])).collect(); + text.push_str(&format!("\nThe file has these lines there now:\n{}", near.join("\n"))); + } + text.push_str("\nCopy old_text from the file's current lines, taking only what comes after the →."); + text +} + fn without_numbers(text: &str) -> String { let lines: Vec<&str> = text.lines().collect(); let numbered: Vec> = lines @@ -723,6 +902,118 @@ mod tests { fs::remove_dir_all(&root).unwrap(); } + #[test] + fn folders_are_listed_and_missing_paths_point_the_way() { + let root = temp_root("missing"); + fs::create_dir_all(root.join("src/lib")).unwrap(); + fs::create_dir_all(root.join("node_modules/pkg")).unwrap(); + fs::write(root.join("src/slug.js"), "export {}\n").unwrap(); + fs::write(root.join("package.json"), "{}").unwrap(); + let listed = run(&ReadFile, &root, json!({ "path": "." })).unwrap(); + assert!(listed.ok); + assert_eq!(listed.text, "The project folder contains:\npackage.json\nsrc/"); + assert_eq!(run(&ReadFile, &root, json!({ "path": "src" })).unwrap().text, "src/ contains:\nlib/\nslug.js"); + let found = run(&ReadFile, &root, json!({ "path": "slug.js" })).unwrap().text; + assert!(found.starts_with("slug.js does not exist, so this is src/slug.js:\n 1→export {}"), "{found}"); + let failed = |path: &str| { + let output = run(&ReadFile, &root, json!({ "path": path })).unwrap(); + assert!(!output.ok); + output.text + }; + assert_eq!(failed("Cargo.toml"), "Cargo.toml does not exist. The project folder contains:\npackage.json\nsrc/"); + fs::write(root.join("src/lib/slug.js"), "export {}\n").unwrap(); + assert_eq!(failed("slug.js"), "slug.js does not exist. Files with that name: src/lib/slug.js, src/slug.js."); + let edit = run(&EditFile, &root, json!({ "path": "src/lib/missing.js", "old_text": "a", "new_text": "b" })).unwrap_err(); + assert!( + edit.starts_with("src/lib/missing.js does not exist. src/lib/ contains:\nslug.js") && edit.ends_with("use write_file."), + "{edit}" + ); + assert_eq!(tools_find("list_dir"), Some("read_file")); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn missed_edits_show_what_the_file_has() { + let file = "export function formatPrice(cents) {\n return '$' + (cents / 100).toFixed(2);\n}\n\nexport function parsePrice(text) {\n return 1;\n}\n"; + let invented = + "import { config } from './config.js';\n\nexport function formatPrice(cents) {\n return '$' + (cents / 100).toFixed(2);\n}"; + let error = replace(file, invented, "x", false).unwrap_err(); + assert!(error.contains("not in the file at all:\n import { config } from './config.js';"), "{error}"); + assert!(error.contains("there now:\n 1→export function formatPrice(cents) {\n 2→ return '$'"), "{error}"); + let shuffled = " return 1;\nexport function formatPrice(cents) {"; + assert!(replace(file, shuffled, "x", false).unwrap_err().contains("not together in that order")); + } + + #[test] + fn double_escaped_text_is_unescaped() { + let file = "fn main() {\n println!(\"hi\");\n}\n"; + let fixed = + replace(file, "fn main() {\\n println!(\\\"hi\\\");\\n}", "fn main() {\\n println!(\\\"bye\\\");\\n}", false).unwrap(); + assert_eq!(fixed, "fn main() {\n println!(\"bye\");\n}\n"); + assert_eq!(replace("a = '\\n'\n", "'\\n'", "'\\t'", false).unwrap(), "a = '\\t'\n"); + let root = temp_root("escaped"); + run(&WriteFile, &root, json!({ "path": "a.py", "content": "def a():\\n return 1\\n" })).unwrap(); + assert_eq!(fs::read_to_string(root.join("a.py")).unwrap(), "def a():\n return 1\n"); + run(&WriteFile, &root, json!({ "path": "b.js", "content": "console.log('a\\nb')" })).unwrap(); + assert_eq!(fs::read_to_string(root.join("b.js")).unwrap(), "console.log('a\\nb')\n"); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn placeholders_never_replace_real_code() { + for line in [ + "// ... existing code ...", + " // ...", + "# ... rest of the file unchanged", + "/* ... */", + "", + "// rest of the methods ...", + "// …", + ] { + assert_eq!(placeholder(&format!("a\n{line}\nb"), "a\nb"), Some(line.trim()), "{line}"); + } + for line in ["// Rest of the setup lives in config.js", "const all = [...items];", "# Usage: run ./build.sh", "// TODO: more"] { + assert_eq!(placeholder(line, ""), None, "{line}"); + } + assert_eq!(placeholder("a\n// ...\nb", "a\n// ...\nb"), None); + let root = temp_root("lazy"); + fs::write(root.join("a.js"), "function a() {\n return 1;\n}\n\nfunction b() {\n return 2;\n}\n").unwrap(); + let rewrite = json!({ "path": "a.js", "content": "function a() {\n return 10;\n}\n\n// ... existing code ...\n" }); + assert!(run(&WriteFile, &root, rewrite).unwrap_err().contains("send every line")); + let edit = json!({ "path": "a.js", "old_text": "function a() {\n return 1;\n}", "new_text": "function a() {\n // ...\n}" }); + assert!(run(&EditFile, &root, edit).unwrap_err().contains("placeholder line \"// ...\"")); + assert!(run(&WriteFile, &root, json!({ "path": "new.js", "content": "// ...\n" })).unwrap().ok); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn changes_that_change_nothing_say_so() { + let root = temp_root("noop"); + fs::write(root.join("a.txt"), "one\ntwo\n").unwrap(); + let error = run(&EditFile, &root, json!({ "path": "a.txt", "old_text": "two", "new_text": "two" })).unwrap_err(); + assert!(error.starts_with("This edit would leave the file exactly as it is"), "{error}"); + let same = run(&WriteFile, &root, json!({ "path": "a.txt", "content": "one\ntwo\n" })).unwrap(); + assert!(same.ok && same.diffs.is_empty() && same.text.contains("nothing changed"), "{}", same.text); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn long_lines_do_not_flood_the_context() { + let root = temp_root("long"); + let limits = Limits { max_output: 1000, ..Limits::default() }; + fs::write(root.join("min.js"), format!("{}\nshort\n", "x".repeat(5000))).unwrap(); + let text = run_with(&ReadFile, &root, json!({ "path": "min.js" }), &limits).unwrap().text; + assert!(text.contains("[line 1 is 5000 characters long and was cut here]") && text.len() < 1200, "{}", text.len()); + fs::write(root.join("wide.txt"), format!("{0}\n{0}\n{0}\n", "y".repeat(400))).unwrap(); + let text = run_with(&ReadFile, &root, json!({ "path": "wide.txt" }), &limits).unwrap().text; + assert!(text.ends_with("(showing lines 1-2 of 3; pass start_line to read more)"), "{text}"); + fs::remove_dir_all(&root).unwrap(); + } + + fn tools_find(name: &str) -> Option<&'static str> { + crate::tools::find(&crate::tools::all(), name).map(|tool| tool.spec().name) + } + #[test] fn read_targets_name_the_lines_asked_for() { assert_eq!(ReadFile.target(&json!({ "path": "src\\a.rs" })), "src/a.rs"); @@ -756,6 +1047,14 @@ mod tests { let named = run(&FindFiles, &root, json!({ "pattern": "*Note*", "path": "source/**" })).unwrap().text; assert_eq!(named, "source/Note.hx"); assert_eq!(run(&FindFiles, &root, json!({ "pattern": "note", "path": "source" })).unwrap().text, "source/Note.hx"); + let wrong = run(&FindFiles, &root, json!({ "pattern": "*.rs" })).unwrap().text; + assert!(wrong.ends_with("The files there are: .hx (1), .txt (1)."), "{wrong}"); + let filtered = run(&Grep, &root, json!({ "pattern": "sick", "glob": "*.rs" })).unwrap().text; + assert_eq!(filtered, "No matches for \"sick\". The files there are: .hx (1), .txt (1)."); + assert_eq!(run(&Grep, &root, json!({ "pattern": "absent" })).unwrap().text, "No matches for \"absent\"."); + let braces = run(&FindFiles, &root, json!({ "pattern": "**/*.{hx,txt}" })).unwrap().text; + assert_eq!(braces, "notes.txt\nsource/Note.hx"); + assert_eq!(run(&FindFiles, &root, json!({ "pattern": "*.txt, *.hx" })).unwrap().text, "notes.txt\nsource/Note.hx"); assert!(run(&Grep, &root, json!({ "pattern": "sick", "path": "src" })).unwrap_err().contains("src does not exist")); assert_eq!(Grep.target(&json!({ "pattern": "sick", "path": "source\\" })), "\"sick\" in source/"); fs::remove_dir_all(&root).unwrap(); diff --git a/crates/quill-core/src/tools/plan.rs b/crates/quill-core/src/tools/plan.rs index 0c68b7b..1da8b13 100644 --- a/crates/quill-core/src/tools/plan.rs +++ b/crates/quill-core/src/tools/plan.rs @@ -29,21 +29,21 @@ fn status(value: &str) -> StepStatus { } pub(crate) fn steps(args: &Value) -> Vec { - let list = ["plan", "steps", "items", "todos"].iter().find_map(|key| args.get(*key).and_then(Value::as_array)); - list.map(|items| { - items - .iter() - .filter_map(|item| match item { - Value::String(text) => Some(PlanStep { text: text.trim().to_string(), status: StepStatus::Pending }), - _ => { - let text = args::trimmed(item, &["step", "text", "content", "title", "task"])?; - let state = args::text(item, &["status", "state"]).map_or(StepStatus::Pending, status); - Some(PlanStep { text: text.to_string(), status: state }) - } - }) - .collect() - }) - .unwrap_or_default() + args::list(args, &["plan", "steps", "items", "todos"]) + .map(|items| { + items + .iter() + .filter_map(|item| match item { + Value::String(text) => Some(PlanStep { text: text.trim().to_string(), status: StepStatus::Pending }), + _ => { + let text = args::trimmed(item, &["step", "text", "content", "title", "task"])?; + let state = args::text(item, &["status", "state"]).map_or(StepStatus::Pending, status); + Some(PlanStep { text: text.to_string(), status: state }) + } + }) + .collect() + }) + .unwrap_or_default() } impl Tool for UpdatePlan { @@ -109,9 +109,7 @@ const ASK: Spec = Spec { fn question(value: &Value) -> Option { let question = args::trimmed(value, &["question", "text", "prompt"])?.to_string(); - let options = ["options", "choices"] - .iter() - .find_map(|key| value.get(*key).and_then(Value::as_array)) + let options = args::list(value, &["options", "choices"]) .map(|items| { items .iter() @@ -125,7 +123,7 @@ fn question(value: &Value) -> Option { } fn questions(args: &Value) -> Vec { - match args.get("questions").and_then(Value::as_array) { + match args::list(args, &["questions"]) { Some(items) => items.iter().filter_map(question).collect(), None => question(args).into_iter().collect(), } diff --git a/crates/quill-core/src/tools/shell.rs b/crates/quill-core/src/tools/shell.rs index dcc66d8..53ed286 100644 --- a/crates/quill-core/src/tools/shell.rs +++ b/crates/quill-core/src/tools/shell.rs @@ -191,6 +191,43 @@ pub fn run( (ok, cap(report, max_output)) } +const SEPARATOR: &str = + "Windows PowerShell has no && or ||. Separate commands with ; and use if ($?) { ... } to run one only when the one before it worked."; + +const FLAGS: &str = "That is a Unix flag. In PowerShell, ls, rm, cat and mkdir are cmdlets with their own parameters: Get-ChildItem -Force, Remove-Item -Recurse -Force, Get-Content, New-Item -ItemType Directory -Force."; + +const INSTEAD: [(&str, &str); 9] = [ + ("grep", "Select-String -Pattern 'text' -Path file, or the grep tool to search the project"), + ("head", "Get-Content file -TotalCount 20"), + ("tail", "Get-Content file -Tail 20"), + ("touch", "New-Item -ItemType File name"), + ("which", "Get-Command name"), + ("export", "$env:NAME = 'value'"), + ("sed", "edit_file to change files"), + ("wc", "(Get-Content file | Measure-Object -Line).Lines"), + ("find", "Get-ChildItem -Recurse -Filter name, or the find_files tool"), +]; + +fn hint(shell: Shell, output: &str) -> Option { + if !matches!(shell, Shell::PowerShell | Shell::Pwsh) { + return None; + } + if output.contains("is not a valid statement separator") { + return Some(SEPARATOR.into()); + } + if output.contains("A parameter cannot be found that matches parameter name") { + return Some(FLAGS.into()); + } + if !output.contains("is not recognized as the name of a cmdlet") { + return None; + } + let term = output.split("The term '").nth(1)?.split('\'').next()?; + Some(match INSTEAD.iter().find(|(name, _)| term.eq_ignore_ascii_case(name)) { + Some((name, instead)) => format!("{name} is a Unix command and does not exist in PowerShell. Use {instead}."), + None => format!("{term} is not installed or not on the PATH. Check the name, or use a PowerShell cmdlet that does the same."), + }) +} + pub struct ShellTool; const SHELL: Spec = Spec { @@ -261,6 +298,10 @@ impl Tool for ShellTool { run(ctx.limits.shell, &dir, &command, Duration::from_secs(seconds), ctx.cancel, ctx.limits.max_output, &|chunk| { ctx.host.output(chunk) }); + let text = match hint(ctx.limits.shell, &text).filter(|_| !ok) { + Some(hint) => format!("{text}\n\n{hint}"), + None => text, + }; Output { ok, ..Output::ok(text) } }), ); @@ -324,6 +365,20 @@ mod tests { assert!(capped.starts_with("aaaa") && capped.ends_with("zzzz") && capped.contains("[output cut]")); } + #[test] + fn powershell_mistakes_get_a_hint() { + let separator = "At line:1 char:8\n+ cd src && node a.js\nThe token '&&' is not a valid statement separator in this version."; + assert_eq!(hint(Shell::PowerShell, separator).as_deref(), Some(SEPARATOR)); + let grep = "grep : The term 'grep' is not recognized as the name of a cmdlet, function, script file, or operable program."; + assert!(hint(Shell::PowerShell, grep).unwrap().contains("Select-String")); + let missing = "The term 'pnpm' is not recognized as the name of a cmdlet, function, script file, or operable program."; + assert!(hint(Shell::Pwsh, missing).unwrap().starts_with("pnpm is not installed")); + let flag = "Remove-Item : A parameter cannot be found that matches parameter name 'rf'."; + assert_eq!(hint(Shell::PowerShell, flag).as_deref(), Some(FLAGS)); + assert!(hint(Shell::Bash, separator).is_none()); + assert!(hint(Shell::PowerShell, "Exit code 1\nnpm ERR! test failed").is_none()); + } + #[test] fn similar_commands_use_the_leading_words() { assert_eq!(similar("npm test -- --watch").as_deref(), Some("npm test")); From a9cd03d5e3581803c86203e2a0baeaac4f108d7e Mon Sep 17 00:00:00 2001 From: Smoffyy Date: Mon, 19 Oct 2026 22:25:00 -0500 Subject: [PATCH 4/4] update date --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2092744..9779af9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.0.1] - TBD +## [1.0.1] - 2026-10-19 ### Changed