diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 38ef6bf..d2be14b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,14 +5,14 @@ "url": "https://github.com/limeflash" }, "metadata": { - "description": "The Antigravity CLI (`agy`) plugin for Claude Code — ask, code review, delegate, web scrape, and doc→Markdown from inside your editor. Read-only guarantee (agy never touches your repo) + secret / SSRF / path guards, background job control, cross-platform (Windows / macOS / Linux / WSL), 245 tests.", - "version": "0.8.1" + "description": "The Antigravity CLI (`agy`) plugin for Claude Code — ask, code review, adversarial review, delegate, rescue, web scrape and doc→Markdown from inside your editor. Read-only commands really are read-only (agy pinned to Default mode, outside your repo) + secret / SSRF / path guards, background job control. One std-only Rust binary, SHA-256 pinned; macOS / Linux / Windows.", + "version": "0.9.0" }, "plugins": [ { "name": "agy", - "description": "Use the Google Antigravity CLI (`agy`) from Claude Code. Synchronous Bash wrapper: /agy:setup, /agy:ask, /agy:delegate, /agy:research, /agy:review, /agy:image, /agy:scrape, /agy:doc-to-md, /agy:help. Node.js companion for stateful workflows: /agy:rescue (background-capable), /agy:status, /agy:result, /agy:cancel. Read-only commands run agy outside your repo; secret-scan + SSRF/path deny-lists guard what's sent to Gemini. Per-call model selection via --model.", - "version": "0.8.1", + "description": "Use the Google Antigravity CLI (`agy`) from Claude Code: /agy:ask, /agy:review, /agy:adversarial-review, /agy:scrape, /agy:doc-to-md (read-only: agy pinned to Default mode, outside your repo), /agy:rescue and /agy:image (write-capable, with rails), /agy:status, /agy:result, /agy:cancel, /agy:delegate, /agy:research, /agy:setup, /agy:help. Secret-scan + SSRF/path guards; per-call --model resolved against `agy models`. One std-only Rust binary, SHA-256 pinned.", + "version": "0.9.0", "author": { "name": "limeflash", "url": "https://github.com/limeflash" diff --git a/.gitattributes b/.gitattributes index 683c78b..06d2fc5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,19 +1,20 @@ # Enforce LF line endings for all text, on every platform. # -# Critical for the shell scripts: real bash (Linux / macOS / WSL) chokes on -# CRLF line endings ("$'\r': command not found", "set: pipefail: invalid -# option name"), while Git-for-Windows bash tolerates them. So a Windows -# checkout with core.autocrlf=true produces CRLF scripts that break the -# moment they're run under WSL — which is exactly the path we recommend for -# an OS-hard sandbox. Forcing eol=lf keeps the scripts runnable everywhere. +# Critical for the launcher: a POSIX shell chokes on CRLF line endings +# ("$'\r': command not found"), so a Windows checkout with +# core.autocrlf=true would produce a launcher that breaks under WSL or Git +# Bash. Forcing eol=lf keeps it runnable everywhere. (PowerShell is fine +# with LF.) * text=auto eol=lf # Be explicit for the script / source / config types. *.sh text eol=lf -*.bash text eol=lf -*.bats text eol=lf -*.mjs text eol=lf -*.js text eol=lf +*.ps1 text eol=lf +*.rs text eol=lf +*.toml text eol=lf +plugins/agy/bin/agy-plugin text eol=lf +plugins/agy/bin/VERSION text eol=lf +plugins/agy/bin/SHA256SUMS text eol=lf *.json text eol=lf *.md text eol=lf *.yml text eol=lf diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index a49e902..b3c5cc2 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -41,10 +41,10 @@ body: required: true - type: input - id: bash-version + id: plugin-version attributes: - label: "`bash --version` (first line)" - placeholder: "GNU bash, version 5.2.x..." + label: "Plugin version (`/agy:setup` → pluginVersion)" + placeholder: "0.9.0" validations: required: true @@ -56,7 +56,7 @@ body: - macOS - Linux - WSL (on Windows) - - Windows (native PowerShell — not yet supported) + - Windows (native PowerShell) - Other validations: required: true diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index d30989a..1debb5e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -20,7 +20,8 @@ Drop sections that aren't relevant; don't pad. ## How was this tested? ## Checklist -- [ ] CI is green (shellcheck + bats + Node tests). +- [ ] CI is green (fmt, clippy, tests on 3 OSes, launcher tests). - [ ] `CHANGELOG.md` entry under the unreleased section. -- [ ] No `--dangerously-skip-permissions` added (or explicit - justification in the description). +- [ ] Read-only commands still pin Default mode and never auto-approve. - [ ] No new secret-scan false negatives introduced. ## Related issues diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5531386..977091f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,23 +12,4 @@ updates: commit-message: prefix: "ci" include: "scope" - - # Node deps are added in Phase 2 (job-control companion). The - # ecosystem entry below is harmless until package.json appears. - - package-ecosystem: "npm" - directory: "/" - schedule: - interval: "weekly" - day: "monday" - open-pull-requests-limit: 5 - labels: - - "dependencies" - - "javascript" - commit-message: - prefix: "chore" - include: "scope" - versioning-strategy: "increase" - ignore: - # vitest and bats-core have rapid major bumps; pin to minor. - - dependency-name: "vitest" - update-types: ["version-update:semver-major"] +# No cargo entry: the crate has no dependencies by policy (CONTRIBUTING.md). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eaf0520..06f2a13 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,81 +11,61 @@ permissions: contents: read jobs: - shellcheck: - name: shellcheck - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: Run shellcheck - run: | - # Ubuntu-latest preinstalls shellcheck. - shellcheck --version - shellcheck -S warning plugins/agy/scripts/agy-run.sh - - shfmt: - name: shfmt (format check) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: Install shfmt - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends shfmt - - name: Check formatting - # -d shows the diff and exits non-zero if reformat would change anything. - # -i 2 = 2-space indent (matches the rest of the script). - # We allow the existing style for now — this is informational, not blocking. - continue-on-error: true - run: shfmt -d -i 2 -ci plugins/agy/scripts/agy-run.sh - - bats: - name: bats (unit tests) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - name: Install bats - run: | - sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends bats - bats --version - - name: Run tests - run: bats tests/ - - bats-macos: - name: bats (macOS, bash 3.2) - runs-on: macos-latest + rust: + name: rust (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 - - name: Show shell versions + # rustup reads rust-toolchain.toml and installs the pinned toolchain. + - name: Toolchain + run: rustup show active-toolchain || rustup toolchain install + - name: std only — no dependencies + shell: bash run: | - # macOS ships bash 3.2; confirm we're really testing that path. - /bin/bash --version - bash --version - - name: Install bats - run: brew install bats-core - - name: Run bash tests (with macOS /bin/bash 3.2) - # Force the legacy bash so we catch any bash-4-only syntax accidents. - # bats only loads *.bats files, so the *.test.mjs vitest files - # in the same directory are silently ignored. - env: - BATS_SHELL: /bin/bash - run: bats tests/ + deps=$(cargo tree --locked --edges normal,build --prefix none | sort -u | wc -l | tr -d " ") + if [ "$deps" -ne 1 ]; then + echo "agy-plugin must not depend on any crate:"; cargo tree --locked; exit 1 + fi + - name: fmt + if: matrix.os == 'ubuntu-latest' + run: cargo fmt --all --check + - name: clippy + run: cargo clippy --locked --all-targets -- -D warnings + - name: test + run: cargo test --locked - node: - name: Node (vitest) - runs-on: ubuntu-latest + launcher: + name: launcher (${{ matrix.os }}) strategy: fail-fast: false matrix: - node-version: ["18.18", "20", "22"] + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v6 - with: - node-version: ${{ matrix.node-version }} - cache: "npm" - - name: Install dependencies - run: npm ci || npm install - - name: Run vitest - run: npm test + - name: shellcheck + if: matrix.os == 'ubuntu-latest' + run: shellcheck -s sh plugins/agy/bin/agy-plugin scripts/test-launcher.sh + - name: launcher tests (sh) + shell: bash + run: | + # Windows runs the downloaded .exe through Windows, so the fake + # release binary there must be a real executable. + if [ "$RUNNER_OS" = Windows ]; then + cargo build --locked --example stub_agy + export AGY_TEST_FAKE_EXE="$PWD/target/debug/examples/stub_agy.exe" + fi + sh scripts/test-launcher.sh + - name: launcher tests (PowerShell 5.1 + 7) + if: matrix.os == 'windows-latest' + shell: pwsh + run: | + cargo build --locked --example stub_agy + $stub = (Resolve-Path target/debug/examples/stub_agy.exe).Path + powershell -NoProfile -ExecutionPolicy Bypass -File scripts/test-launcher.ps1 -Stub $stub + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + pwsh -NoProfile -File scripts/test-launcher.ps1 -Stub $stub diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..cd230bc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,121 @@ +name: Release + +# Builds agy-plugin for every supported platform when a v* tag is pushed, +# publishes the binaries + SHA256SUMS as a GitHub Release, then opens a PR +# that pins plugins/agy/bin/{VERSION,SHA256SUMS} to them. Users get the new +# binary only once that PR is merged: the launcher refuses any binary whose +# hash is not committed in the repo. + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + build: + name: build ${{ matrix.target }} + strategy: + fail-fast: true + matrix: + include: + - { target: aarch64-apple-darwin, os: macos-latest } + - { target: x86_64-apple-darwin, os: macos-latest } + - { target: x86_64-unknown-linux-musl, os: ubuntu-latest } + - { target: aarch64-unknown-linux-musl, os: ubuntu-24.04-arm } + - { target: x86_64-pc-windows-msvc, os: windows-latest } + - { target: aarch64-pc-windows-msvc, os: windows-11-arm } + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - name: musl tools + if: contains(matrix.target, 'musl') + run: sudo apt-get update -qq && sudo apt-get install -y --no-install-recommends musl-tools + - name: Toolchain + target + shell: bash + run: rustup target add ${{ matrix.target }} + - name: Tag matches Cargo.toml version + shell: bash + run: | + v=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1) + [ "v$v" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME != Cargo.toml v$v"; exit 1; } + - name: Build + run: cargo build --release --locked --target ${{ matrix.target }} + - name: Package + shell: bash + run: | + mkdir -p dist + ext=""; case "${{ matrix.target }}" in *windows*) ext=.exe ;; esac + cp "target/${{ matrix.target }}/release/agy-plugin$ext" "dist/agy-plugin-${{ matrix.target }}$ext" + # Smoke test where the runner can execute it natively. + "dist/agy-plugin-${{ matrix.target }}$ext" version || [ "${{ matrix.target }}" = x86_64-apple-darwin ] + - uses: actions/upload-artifact@v7 + with: + name: agy-plugin-${{ matrix.target }} + path: dist/* + if-no-files-found: error + + publish: + needs: build + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v7 + - uses: actions/download-artifact@v8 + with: + path: dist + merge-multiple: true + - name: Checksums + working-directory: dist + run: sha256sum agy-plugin-* | tee SHA256SUMS + - name: Release notes from CHANGELOG + run: | + v="${GITHUB_REF_NAME#v}" + awk -v v="$v" '$0 ~ "^## \\[" v "\\]" {p=1; next} /^## \[/ {if (p) exit} p' CHANGELOG.md > notes.md + [ -s notes.md ] || echo "Release $GITHUB_REF_NAME" > notes.md + - name: Create release + env: + GH_TOKEN: ${{ github.token }} + run: gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --notes-file notes.md --verify-tag + - uses: actions/upload-artifact@v7 + with: + name: SHA256SUMS + path: dist/SHA256SUMS + + pin: + needs: publish + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + with: + ref: main + - uses: actions/download-artifact@v8 + with: + name: SHA256SUMS + path: sums + - name: Open the pin PR + env: + GH_TOKEN: ${{ github.token }} + run: | + v="${GITHUB_REF_NAME#v}" + if [ ! -d plugins/agy/bin ]; then + echo "::notice::main has no launcher yet (first Rust release); commit the release's SHA256SUMS to the release PR by hand." + exit 0 + fi + branch="release/pin-$GITHUB_REF_NAME" + git switch -c "$branch" + printf '%s\n' "$v" > plugins/agy/bin/VERSION + cp sums/SHA256SUMS plugins/agy/bin/SHA256SUMS + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add plugins/agy/bin/VERSION plugins/agy/bin/SHA256SUMS + git commit -m "release: pin agy-plugin binaries to $GITHUB_REF_NAME" + git push origin "$branch" + gh pr create --base main --head "$branch" \ + --title "release: pin agy-plugin binaries to $GITHUB_REF_NAME" \ + --body "Points the launcher at the $GITHUB_REF_NAME release binaries. Checksums come from the release workflow run; compare them with the release's SHA256SUMS asset before merging." diff --git a/.gitignore b/.gitignore index 14fcff0..5ab0a98 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ articles/ # Vitest / coverage output. coverage/ .nyc_output/ +/target/ diff --git a/CHANGELOG.md b/CHANGELOG.md index aaac45e..77cea39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,129 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 > since been substantially rewritten and extended. The earlier entries below > are the original upstream history, preserved for traceability. +## [0.9.0] - 2026-11-24 (limeflash) + +**Rewritten in Rust, and a read-only escape on agy 1.5.7+ closed.** One +std-only binary (zero third-party crates) replaces the Bash wrapper, the +Node.js companion and the PowerShell port. Node.js is no longer required. +The binary is downloaded once from GitHub Releases by a small launcher and +verified against the SHA-256 committed in `plugins/agy/bin/SHA256SUMS`. + +### Security +- **Read-only commands could write on agy 1.5.7+.** agy 1.5.7 made Auto the + default agent mode for headless runs, and Auto approves writes outside the + workspace (any file in a git/jj/hg repo, any create or append elsewhere). + Reproduced on agy 1.5.16: 0.8.1's `/agy:ask` overwrote a file in an + unrelated git repo. Every read-only run is now pinned with one last-place + token, `--settings={"agentMode":"","permissions":{"deny":["command(*)","write_file(*)"]}}`: + Default mode (which also denies reads outside the workspace) plus explicit + deny rules that agy enforces even in Auto mode and that beat saved allow + rules. Denied actions are reported; an agy that defaults to Auto but can't + be pinned is refused (fail closed). See SECURITY.md. +- Extra agy flags on read-only commands are limited to `--print-timeout` and + `--effort`, each with a real value (`--mode`, `--settings`, `--add-dir`, + `--dangerously-skip-permissions`, … are refused; a value-less `--effort` + would have swallowed the pin). +- review scans every line of the diff for secrets, not only added lines + (`git rm .env` sent the deleted keys), plus the full staged files. +- `/agy:cancel` no longer trusts pids or paths in workspace job records (a + repo can commit them: 0.9.0-dev let a planted record make cancel delete + any directory or signal any process). It acts only through a private + per-user registry, and signals only when the worker's OS file lock proves + it is alive and ours — so a reused pid is never hit. A repo that commits + `.agy-plugin/` triggers a warning; a symlinked one is refused. +- git runs with `core.fsmonitor=false` and `--no-textconv` (both can run + commands from a repo's config); curl ignores `~/.curlrc` and refuses + https→http redirects; PATH lookups skip relative entries (a repo could + plant its own `agy`, `git` or `curl`). +- doc-to-md also refuses Maven, Pidgin, FileZilla, password-store, keyring, + browser/mail profile and Keychain locations and `%APPDATA%` credential + stores, and refuses outright when the home directory is unknown. +- **scrape no longer lets agy fetch URLs.** The plugin downloads the page + with the system curl and agy only converts the saved copy. Every address + the host resolves to is checked and curl is pinned to it (`--resolve`), + which closes DNS rebinding; redirects are re-checked hop by hop; proxies + are bypassed unless `AGY_SCRAPE_USE_PROXY=1`. (agy 1.5.16 has no URL tool + in a read-only run anyway.) +- SSRF guard: every embedded IPv4 in a hostname is checked, not only the + first (`1.2.3.4.127.0.0.1.nip.io` passed); numeric IPv4 is parsed the + WHATWG way; IPv6 mapped/compat/NAT64/6to4, dashed and hex `nip.io`/`sslip.io` + forms, single-label names (`metadata`), `localtest.me`-style loopback + domains, multicast and reserved ranges are blocked. +- doc-to-md: on macOS the `/etc`, `/var/run` and home-dir deny-list compared + a resolved path with unresolved prefixes, so `/private/etc/...` slipped + through; fixed. The copy opens the file with `O_NOFOLLOW`. +- An exported `AGY_CAPTURE_STAGE_FILE` made 0.8.x stage that file into any + read-only run without validation; staging now only takes validated + arguments. +- The native PowerShell port ran agy without the auth check or any mode pin; + Windows now runs the same binary and guards. +- agy's "re-run with --dangerously-skip-permissions" hint is no longer passed + on to Claude. +- `PWD`, `OLDPWD` and `AGY_JOB_WORKSPACE` are removed from agy's environment + on read-only runs (they pointed at the repo). + +### Changed +- `--model` passes agy's own `--model`; aliases resolve against `agy models` + to the newest model in the family (following upstream simplybychris 0.5.0). + settings.json is never patched any more; a backup left by an interrupted + 0.8.x run is restored once. +- One `review` implementation: `--base`, `--background`, `--wait` and + `--model` always work; the bash/node routing rule is gone. Reviews stage + the diff and full changed files on disk for agy. +- Answers come from `--output-format json`; transcript scraping and the + write_file + auto-approve fallback are gone. **Requires agy 1.2.0+.** +- Read-only prompts tell agy that shell commands and edits are unavailable + (without it, agy 1.5.16 often gave up with an empty answer). +- `/agy:setup`'s check reports `pluginVersion` and whether agy is supported. + +### Fixed +- The companion parsed `--model` for rescue/review/adversarial-review but + never passed it to agy. +- `--fresh` did nothing (it is now documented as the default; `--resume` + continues the last conversation; both together are an error). +- An unknown flag swallowed the next word, so `rescue --sandbox fix the bug` + lost the task. +- `cancel` signalled only the worker, orphaning agy; workers now lead their + own process group and the whole group is stopped (`taskkill /T` on Windows). +- An agy killed by a signal counted as success (exit 0). +- `review --background --wait` deleted the stage dir on timeout while the + worker still used it. +- A fast worker's final status could be overwritten with `running`; job + records are now updated under a lock, and the worker marks itself running. +- `.agy-plugin/` was not git-excluded in linked worktrees, so the next rescue + saw a dirty tree. +- `rescue --isolate` uses a `git clone --shared` checkout instead of a linked + worktree (its own `.git`, so agy can't touch the real repo's config or + hooks through it) and strips repo-location variables; foreground cancel + now also stops the agy child; stale temp dirs from killed runs are swept + after a day; git file names are read with `-z` (quotes, newlines and edge + spaces survived badly). +- Launcher: download timeouts, safe concurrent first runs, a clear error + without HOME, and Ctrl+C no longer reports a bogus checksum mismatch. +- `cancel` with no id picked the newest job even if it had finished; it now + picks the newest running one. +- `ask … --print-timeout 20m` was killed after the default timeout. +- macOS: agy's `--add-dir` now uses the resolved `/private/var/...` spelling + of the temp dir, matching agy's cwd. +- image: no description gave "unbound variable" under bash 3.2 (upstream + d3b981f); moot in Rust, kept as a test. + +### Tests +- The bats helper ran `set +e`, which turned every assertion in tests that + sourced the wrapper into a no-op — those tests could not fail. The Rust + suite replaces bats and vitest: 233 unit tests, 14 end-to-end tests that + drive the real binary against a recording stub agy, and launcher tests for + sh and PowerShell (checksum mismatch, tampered cache). +- The secret matchers agree with the old regexes on 39,981 generated cases; + JSON number output matches `JSON.stringify` on 400,000 doubles; timestamps + match `toISOString` on 200,000 values. +- An independent adversarial review of the port found the cancel, `--effort` + and deleted-secret issues above before release; each has a regression test. +- `scripts/e2e-live.sh` runs every command against a real agy, including the + write-escape attempt; CI runs fmt, clippy `-D warnings` and tests on + Ubuntu, macOS and Windows and fails if any crate dependency appears. + ## [0.8.1] - 2026-07-10 (limeflash) **Bug-hunt patch** — the 0.8.0 changes were run back through `agy` itself diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 46cbc11..fc2a5b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,83 +1,76 @@ # Contributing -Thanks for considering a contribution! This plugin's design goals (in -priority order): - -1. **Safe by default** — no `--dangerously-skip-permissions`, no global - `--add-dir `, no auto-approve of `agy` tool calls. -2. **No runtime dependency creep** — Bash + git are required; Node.js - 18+ is required only for the job-control commands (Phase 2). -3. **Cross-platform** — macOS, Linux, WSL today; Windows-native - PowerShell port is roadmapped. +Thanks for considering a contribution! Design goals, in priority order: + +1. **Safe by default.** Read-only commands stay read-only (Default agent + mode pinned, no `--dangerously-skip-permissions`, never the repo as agy's + workspace), and anything that leaves the machine is guarded. +2. **std-only Rust.** `[dependencies]` stays empty — no crates in any form, + no vendored third-party code, no `build.rs`. If std doesn't wrap an OS + call, declare it with `extern` in `src/sys.rs`. CI fails on any + dependency. This keeps the binary small and the supply chain auditable. +3. **Cross-platform, equally.** macOS, Linux and Windows (Git Bash and + native PowerShell). Use `std::path`, gate platform code with `cfg`, and + check `cargo clippy --target x86_64-pc-windows-msvc` when you touch it. 4. **Useful to the typical Claude Code user calling `agy`.** -## Quick start for development - -1. Fork and clone: - ```bash - git clone git@github.com:/antigravity-plugin-cc.git - cd antigravity-plugin-cc - git remote add upstream https://github.com/limeflash/antigravity-plugin-cc.git - ``` -2. Edit files under `plugins/agy/`. -3. Test locally: - - Bash: `bats tests/` (install `bats-core` via `apt`/`brew`/`npm`). - - Node (Phase 2+): `npm install && npm test`. - - End-to-end: point your Claude Code marketplace at your clone, or - symlink `plugins/agy/` into - `~/.claude/plugins/marketplaces/local/plugins/`. -4. Run `/agy:setup` to confirm nothing broke. -5. Open a PR. CI must be green; new behavior should land with a test. +## Development + +```bash +git clone git@github.com:/antigravity-plugin-cc.git && cd antigravity-plugin-cc +cargo test # unit + end-to-end tests against a stub agy +cargo clippy --all-targets -- -D warnings +cargo fmt +sh scripts/test-launcher.sh # launcher download/verify tests +``` + +The end-to-end tests in `tests/cli.rs` run the real binary against +`examples/stub_agy.rs`, which records how it was called; add a case there +for any change to how agy is invoked. `scripts/e2e-live.sh` runs the +commands against a real, logged-in agy (it uses model quota) — including the +read-only write-escape check; run it before a release. + +To use your build from Claude Code, point the plugin at it: +`export AGY_PLUGIN_BIN=$PWD/target/release/agy-plugin`, then add your clone +as a local marketplace. + +## Layout + +- `src/` — the binary: `commands.rs` (the /agy:* commands), `capture.rs` + (the read-only agy run), `agy.rs` / `models.rs` (probing agy, `--model`), + `guard.rs` / `secrets.rs` / `fetch.rs` (input guards), `git.rs`, + `jobs.rs` (job state and workers), `sys.rs` (OS calls), `json.rs`, + `cli.rs`, `render.rs`, `prompts.rs`, `time.rs`, `util.rs`. +- `plugins/agy/` — what Claude Code installs: slash commands, the runner + subagent, the skill, and `bin/` (launcher, `VERSION`, `SHA256SUMS`). ## What this project wants help with -- **Better secret patterns** for the secret scanner (more true positives, no - new false positives — bring sample diffs in the PR). -- **`/agy:doc-to-md` for binary formats** (PDF / DOCX / PPTX) via a safe local - text-extraction step. -- **PowerShell parity** — extend `agy-run.ps1` to more commands, and add - Pester tests. -- **`shfmt -d -i 2 -ci` clean format pass** on `agy-run.sh` (currently - informational in CI; making it blocking is the goal). -- **Real-world dogfooding reports** — bugs you hit running the commands on - your own projects. Running `/agy:review` / `/agy:adversarial-review` on the - plugin's own diffs is how most bugs get found. +- Better secret patterns (more true positives, no new false positives — + bring sample diffs). +- `/agy:doc-to-md` for binary formats via a safe local extraction step. +- Real-world reports from running the commands on your own projects. ## What this project will say no to -- A Node.js runtime for the slash commands that don't need state - (`/agy:ask`, `/agy:image`, `/agy:review`, `/agy:setup`, `/agy:help`). - Those stay in Bash. -- Removing the secret-scan guardrail by default. The opt-in via - `AGY_REVIEW_ALLOW_SECRETS=1` exists precisely so default behavior - stays safe. -- Adding `--dangerously-skip-permissions` to any command. If a use case - needs it, propose it in an issue first — the answer will almost - certainly be "use `agy` directly". -- Hard dependencies on Windows-only or Unix-only tooling. +- Any crate dependency. +- Weakening a guard by default (the secret scan's opt-out is + `AGY_REVIEW_ALLOW_SECRETS=1` for a reason). +- Auto-approval (`--dangerously-skip-permissions`) on anything but rescue and + image. ## Filing issues -Use the issue templates. For bugs, include: -- output of `/agy:setup` -- the exact command you ran -- `agy --version` and `bash --version` -- OS and shell - -For security issues, **do not file a public issue** — -see [SECURITY.md](./SECURITY.md). +Use the issue templates. For bugs include the output of `/agy:setup`, the +exact command, `agy --version`, and your OS. Security issues: see +[SECURITY.md](./SECURITY.md), never a public issue. ## Commit style -- Conventional commits encouraged (`feat:`, `fix:`, `chore:`, `ci:`, - `docs:`, `test:`). -- Squash-merge is the default. Long PRs are fine if the per-commit - history is clean; you'll be asked to rebase if not. +Conventional commits (`feat:`, `fix:`, `chore:`, `ci:`, `docs:`, `test:`). +Squash-merge by default. ## License -By contributing, you agree your contributions are licensed under the -[MIT License](LICENSE), matching the rest of the repository. If your -contribution ports code from `openai/codex-plugin-cc` (Apache 2.0), -include the upstream copyright header in the touched file and link the -specific commit you took it from. +By contributing you agree your contributions are licensed under the +[MIT License](LICENSE). diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1ccb7a0 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "agy-plugin" +version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5173e0f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "agy-plugin" +version = "0.9.0" +edition = "2024" +description = "Claude Code plugin runtime for Google's Antigravity CLI (agy): read-only commands that stay read-only, plus background jobs." +license = "MIT" +repository = "https://github.com/limeflash/antigravity-plugin-cc" +publish = false + +# Policy: std only. No crates in any form (see CONTRIBUTING.md). OS calls +# that std does not wrap go through `extern` declarations in src/sys.rs. +[dependencies] + +[[bin]] +name = "agy-plugin" +path = "src/main.rs" + +[profile.release] +opt-level = "z" +lto = true +codegen-units = 1 +panic = "abort" +strip = true diff --git a/NOTICE b/NOTICE index 2204364..699c035 100644 --- a/NOTICE +++ b/NOTICE @@ -10,14 +10,12 @@ This project was originally seeded from: https://github.com/simplybychris/antigravity-plugin-cc Licensed under the MIT License. -Thank you to @simplybychris for the starting point. The project has since -been substantially rewritten and extended — a real read-only guarantee, the -agy issue-#76 transcript capture, a Node.js job-control companion, -/agy:scrape and /agy:doc-to-md with SSRF/path guards, a native PowerShell -entry, cross-platform validation, and a 245-test suite are all original to -it (see CHANGELOG.md). It is maintained independently by @limeflash. The -MIT attribution above is retained because portions of the initial scaffold -trace back to that base. +Thank you to @simplybychris for the starting point. The dynamic `--model` +alias resolution (resolve against `agy models`, pass agy's own --model) +follows that project's 0.5.0 design. Since 0.9.0 this project is a +from-scratch, std-only Rust implementation maintained independently by +@limeflash; the MIT attribution above is retained because the slash-command +surface and parts of the documentation trace back to that base. Job-control, state-persistence, and render-layer concepts are inspired by: @@ -25,6 +23,5 @@ Job-control, state-persistence, and render-layer concepts are inspired by: https://github.com/openai/codex-plugin-cc Licensed under the Apache License, Version 2.0. -No source code is copied directly from codex-plugin-cc; the patterns are -re-implemented for `agy`. Any future file-level port would carry the -upstream attribution header and the Apache-2.0 NOTICE as required. +No source code is copied from either project. The binary has no third-party +dependencies. diff --git a/README.md b/README.md index 13284c5..a570366 100644 --- a/README.md +++ b/README.md @@ -1,151 +1,43 @@ -# agy — the Antigravity CLI plugin for Claude Code +
+ +# agy for Claude Code + +**Use Google's [Antigravity CLI (`agy`)](https://antigravity.google/) without leaving Claude Code.**
+Ask questions, get a second opinion on your diff, hand off tasks, read web pages and documents — safely. [![CI](https://github.com/limeflash/antigravity-plugin-cc/actions/workflows/ci.yml/badge.svg)](https://github.com/limeflash/antigravity-plugin-cc/actions/workflows/ci.yml) [![Release](https://img.shields.io/github/v/release/limeflash/antigravity-plugin-cc?sort=semver&color=blue)](https://github.com/limeflash/antigravity-plugin-cc/releases) -[![Tests](https://img.shields.io/badge/tests-245%20passing-brightgreen)](#tested--dogfooded) -[![Platforms](https://img.shields.io/badge/platforms-Windows%20·%20macOS%20·%20Linux%20·%20WSL-informational)](#requirements) -[![Node](https://img.shields.io/badge/node-%E2%89%A518.18-339933)](#requirements) +[![Platforms](https://img.shields.io/badge/macOS%20·%20Linux%20·%20Windows-informational)](#-requirements) +[![Rust, zero dependencies](https://img.shields.io/badge/rust-zero%20dependencies-orange)](./CONTRIBUTING.md) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE) -**Call Google's [Antigravity CLI (`agy`)](https://antigravity.google/) from inside Claude Code** — ask -questions, review your diff, delegate coding tasks, scrape the web, convert -documents to Markdown — all without leaving your editor. - -What sets it apart: the read-only commands come with a **real read-only -guarantee** — `agy` runs from a throwaway temp directory and *cannot touch -your repository* — and everything that leaves your machine is guarded -(credential scan before anything reaches Gemini, SSRF deny-list on URLs, -sensitive-path deny-list on files). Cross-platform, **245 unit tests**, CI -green. - -> **Latest — v0.8.1.** Now on **agy 1.1.0** with **direct stdout capture** (the -> #76 workaround is now just a fallback). 13 slash commands · read-only -> guarantee · secret / SSRF / path guards · background job control · native -> Windows PowerShell entry. -> Validated end-to-end against a real `agy` 1.1.0 install on **Windows -> (git-bash)**, **WSL2 Ubuntu**, and **macOS 26.5**. Hardened by dogfooding the -> plugin's own `/agy:review` and `/agy:adversarial-review` on its own code — -> a self-run adversarial pass found and fixed real SSRF / path / TOCTOU bugs -> (see the [CHANGELOG](./CHANGELOG.md)). - -## Why this plugin - -- 🔒 **Read-only means read-only.** `/agy:ask`, `/agy:review`, `/agy:scrape`, - `/agy:doc-to-md` run `agy` from a temp dir with **no** - `--dangerously-skip-permissions` and your repo unreachable — even though - `agy` executes tools, it has no path to write into your project. - ([how it works](#how-output-is-captured-agy-issue-76) · [SECURITY.md](./SECURITY.md)) -- 🛡️ **Guards what leaves your machine.** Diffs *and full changed-file - content* are scanned for credentials before being sent to Gemini; scrape - URLs are SSRF-filtered (localhost / private / link-local / cloud-metadata / - IPv6-mapped / `nip.io`); document paths are extension-allow-listed and - blocked under `~/.ssh` / `~/.aws` / `~/.gemini` / `/etc`. -- 🧰 **13 commands, one plugin.** ask · delegate · research · review · - adversarial-review · rescue · scrape · doc-to-md · image · status · result · - cancel · setup. -- ⚙️ **Background job control.** Long tasks run detached with real job records - (`/agy:status`, `/agy:result`, `/agy:cancel`); `rescue --isolate` edits a - throwaway `git worktree` and hands you a reviewable patch — your real tree is - never touched. -- 💻 **Cross-platform.** A Bash wrapper (macOS / Linux / WSL / Windows - git-bash) + a Node companion + a native **PowerShell** entry for Windows - without bash. -- ✅ **Tested & dogfooded.** 245 unit tests, a shellcheck + bats + vitest CI - matrix (Node 18 / 20 / 22), and the plugin reviews *itself* — that's how the - hardest bugs were found. - -This plugin is for Claude Code users who already use (or want to start using) -Antigravity and want a smooth, safe way to call it from the workflow they -already have. - -## What you get - -### Synchronous Bash wrapper (no Node.js required) - -- **`/agy:setup`** — verify `agy` is installed and authenticated; can install - it for you if it is missing. -- **`/agy:ask [--model ] `** — one-shot prompt through `agy -p`; - returns the raw response. -- **`/agy:delegate [--background] [--model ] `** — hand a task - to the `agy:runner` subagent. `--background` for long jobs (uses Claude - Code's subagent mechanism). -- **`/agy:research [--background] [--model ] `** — delegate a - deep-research investigation; wraps the topic in a structured prompt and - routes through `agy:runner`. -- **`/agy:image `** — generate an image with `agy`'s built-in - `generate_image` tool (Imagen under the hood). Optional `--name` and - `--output`. -- **`/agy:scrape [--model ] `** — fetch a web page (read-only) - and return its main content as Markdown. The URL is SSRF-guarded - (http/https only; localhost / private / link-local / cloud-metadata hosts - refused) before `agy` fetches it. -- **`/agy:doc-to-md [--model ] `** — convert a local document - (PDF, DOCX, HTML, …) to Markdown, read-only. The path is validated - (allow-listed document types only; not under `~/.ssh` / `~/.aws` / - `~/.gemini` / `/etc`; symlinks resolved) and staged into a temp dir so - `agy` sees only that one file. -- **`/agy:review [focus]`** — ask Antigravity to review your current - `git diff`. Sends an expanded diff (`-U25`) plus the full content of - small changed files so `agy` sees imports/guards and doesn't raise - context-blind false positives. Aborts if the diff appears to contain - secrets (override via `AGY_REVIEW_ALLOW_SECRETS=1`). -- **`/agy:help`** — show all commands, supported `--model` aliases, and - canonical model names. -- **`agy:runner` subagent** — thin forwarding wrapper around the Antigravity - CLI; available as `subagent_type: "agy:runner"` for programmatic - delegation. - -### Node.js companion (Phase 2 — Node 18.18+ required) - -Stateful workflows with persistent job records under -`/.agy-plugin/` — background jobs, branch-base review, adversarial -review, and a job lifecycle you can inspect and cancel. Node.js is **only** -needed if you use these commands; the Bash wrapper above keeps working without -it. - -- **`/agy:rescue [--isolate] [--allow-dirty] [--background] [--wait] [--resume|--fresh] [--model ] `** - — like `/agy:delegate`, but with our own job control **and safety - rails**. agy can edit files (it runs with auto-approval by design), - so: a non-isolated rescue **refuses to run on a dirty git tree** - (override with `--allow-dirty`) and **prints a `git diff --stat` - afterward**; **`--isolate`** runs agy in a throwaway `git worktree` - so your real tree is never touched and you get a reviewable patch - under `.agy-plugin/patches/`. Foreground by default; `--background` - returns a job id; `--background --wait` blocks until done. -- **`/agy:review --base [--background] [--wait] [--model ] [focus]`** - — branch-vs-base code review. Computes the merge-base of HEAD and - the base ref so unrelated changes on the base branch are excluded. - Without flags, falls back to the synchronous Bash wrapper (above). -- **`/agy:adversarial-review [--base ] [--background] [--wait] [--model ] [focus]`** - — challenge-mode review. The prompt asks `agy` to question the - design, propose alternatives, and end with a ship/change/rethink - verdict. Pairs well with `--model opus`. -- **`/agy:status [task-id]`** — list recent jobs in this workspace, or - show the detail block for one. Detects orphaned `running` records - whose worker process has died. -- **`/agy:result [task-id]`** — print the captured output of a job - (defaults to the latest). Useful right after `--background` returns - or after `--wait` runs out. -- **`/agy:cancel [task-id]`** — `SIGTERM` the job's worker, escalate - to `SIGKILL` after a 5-second grace, and mark the record canceled. - -## Requirements - -- **Claude Code** with plugin-marketplace support - (`/plugin marketplace add …`). -- **Antigravity CLI (`agy`)** installed locally. `/agy:setup` can install it - on first run. -- **Auth** for `agy`: either OAuth cached in the system keyring (after one - interactive run of `agy`) or `ANTIGRAVITY_API_KEY` exported in your shell. -- **Bash** + **git** in `PATH` (macOS / Linux / WSL / Windows git-bash) for - the full command set. On **native Windows without bash**, the read-only - commands (`/agy:ask`, `/agy:scrape`, `/agy:doc-to-md`) also run via the - PowerShell entry — `powershell -ExecutionPolicy Bypass -File - "/scripts/agy-run.ps1" ` (needs **Node.js**). - -## Install - -In Claude Code, run these three slash commands in order: +
+ +```text +> /agy:review --base main +## Correctness +- calc.js:1 — `add` returns a - b instead of a + b (HIGH) +## Edge cases +- calc.js:2 — `divide` has no guard for b === 0 (MEDIUM) +``` + +--- + +## ✨ Why use it + +| | | +|---|---| +| 🔒 **Read-only really means read-only** | Commands like `/agy:ask` and `/agy:review` can look, never touch: agy is explicitly forbidden to change files or run commands, and if that can't be guaranteed the plugin refuses to run. | +| 🛡️ **Nothing sensitive slips out** | Your diff is checked for API keys before it goes to Gemini; web addresses and file paths are checked so agy can't be pointed at your internal network or your `~/.ssh`. | +| 🎯 **Always the newest model** | `--model opus`, `pro`, `flash`, `sonnet` pick the latest model of that family that your account offers. | +| ⏳ **Long jobs in the background** | Start a review or a task, keep working, check back with `/agy:status` and `/agy:result`. | +| 📦 **Tiny and self-contained** | One ~0.6 MB native program with zero third-party dependencies. No Node.js, no Python. Verified by checksum before it runs. | + +--- + +## 🚀 Quick start + +**1. Install the plugin** (in Claude Code): ```text /plugin marketplace add limeflash/antigravity-plugin-cc @@ -153,256 +45,179 @@ In Claude Code, run these three slash commands in order: /reload-plugins ``` -Then verify everything is wired up: +**2. Check that everything is ready:** ```text /agy:setup ``` -If `agy` is missing, `/agy:setup` offers to install it via the official -installer: +It checks that `agy` is installed (and offers to install it), logged in, and new enough. -```bash -curl -fsSL https://antigravity.google/cli/install.sh | bash +**3. Use it:** + +```text +/agy:ask explain Rust lifetimes in one paragraph ``` -If `agy` is installed but not logged in, run `agy` once interactively in your -terminal to complete OAuth — or export `ANTIGRAVITY_API_KEY`. +> The first command downloads the plugin's binary for your computer (≈0.6 MB) from this repo's releases and verifies its checksum. After that it runs offline. -## Usage +--- -### Ask a quick question +## 🧰 Commands -```text -/agy:ask explain the difference between Go channels and Rust async in one paragraph -``` +### Read-only — agy can read, but can't change anything -Returns Antigravity's response verbatim. +| Command | What it does | +|---|---| +| `/agy:ask ` | Ask anything, get agy's answer back. | +| `/agy:review [focus]` | Review your uncommitted changes. Add `--base main` to review a whole branch. | +| `/agy:adversarial-review [focus]` | A tougher review: questions the design and ends with *ship / change / rethink*. | +| `/agy:scrape ` | Turn a web page into clean Markdown. | +| `/agy:doc-to-md ` | Turn a PDF, DOCX, HTML, … into Markdown. | +| `/agy:delegate`, `/agy:research` | Hand an investigation to a subagent that asks agy for you. | -### Delegate a task to the `agy:runner` subagent +### Can change files — with safety rails -```text -/agy:delegate refactor the SQL queries in src/db/queries.go to use prepared statements -``` +| Command | What it does | +|---|---| +| `/agy:rescue ` | Let agy fix or build something in your repo. It refuses if you have uncommitted changes and shows you what changed afterwards. Add **`--isolate`** to get a patch instead of edits. | +| `/agy:image ` | Generate an image; `--output path.png` copies it into your project. | -For long tasks, run in the background and let Claude Code notify you when it -finishes: +### Background jobs & help -```text -/agy:delegate --background investigate why integration tests are flaky in CI -``` +| Command | What it does | +|---|---| +| `/agy:status` · `/agy:result` · `/agy:cancel` | Watch, read and stop background jobs. | +| `/agy:setup` · `/agy:help` | Check your setup · see all commands and the current models. | + +**Useful flags:** `--model ` on most commands · `--background` (and `--wait`) on `review`, `adversarial-review` and `rescue`. + +--- -You can also delegate by talking to Claude: +## 🎯 Choosing a model ```text -Ask agy to look at this file and suggest a simpler design. +/agy:ask --model opus "what's wrong with this regex?" +/agy:review --model flash ``` -The plugin's selection rules route through the `agy:runner` subagent -automatically. +| Alias | Picks | +|---|---| +| `flash`, `flash-medium`, `flash-low` | newest Gemini Flash (High / Medium / Low) | +| `pro`, `pro-low` | newest Gemini Pro (High / Low) | +| `opus`, `sonnet` | newest Claude Opus / Sonnet (prefers *Thinking*) | +| `gpt-oss` | GPT-OSS 120B | -### Review the current diff +Any exact model name or id from `agy models` works too. `/agy:help` shows what each alias points to right now. Without `--model`, agy uses its own default. -Stage or make some changes, then: +--- -```text -/agy:review -/agy:review focus on error handling and concurrency safety -``` +## 🔒 How the safety works -### Pick a specific model +**Read-only commands** run agy: -```text -/agy:delegate --model sonnet fix the off-by-one in pagination -/agy:delegate --model pro write a high-coverage test for the cache layer -/agy:ask --model opus "explain Go's escape analysis" -``` +- 📁 **in a throwaway folder** — your repository is never agy's workspace; +- 🔐 **locked down** — agy is told *Default mode, no shell commands, no file writes*, which also stops it from reading files outside that folder; +- 🚫 **fail-safe** — if agy can't be locked down (some versions can't), the command refuses to run; +- 👀 **transparently** — if agy tries something it isn't allowed to, you see a note saying exactly what was blocked. -Supported aliases: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, -`sonnet`, `opus`, `gpt-oss`. The canonical TUI strings (e.g. -`"Claude Opus 4.6 (Thinking)"`) are also accepted. Run `/agy:help` for the -full table. +This matters because since agy **1.5.7**, its default mode lets it edit files in any git repository without asking. Older versions of this plugin (≤ 0.8.1) were affected; see [SECURITY.md](./SECURITY.md). -If no `--model` is given, the wrapper uses whatever the TUI is currently set -to — stored in `~/.gemini/antigravity-cli/settings.json`. Project-local -`AGENTS.md` and `GEMINI.md` files are read directly by `agy` and unaffected -by this plugin. +**Before anything is sent to Gemini:** -### Delegate a deep research investigation +| | | +|---|---| +| `/agy:review` | Scans the diff *and* the changed files for AWS, GitHub, Slack, OpenAI, Anthropic keys, private keys and `password=` lines. Stops with a warning if it finds any. | +| `/agy:scrape` | Only `http`/`https`. Blocks localhost, private networks and cloud-metadata addresses, including disguised ones and DNS tricks. The plugin downloads the page itself; agy only reads the copy. | +| `/agy:doc-to-md` | Only document types (pdf, docx, html, md, …) and never from `~/.ssh`, `~/.aws`, keychains, browser profiles, `/etc`, …. | -```text -/agy:research what's the current state of WebGPU support across browsers in 2026? -/agy:research --background --model opus survey post-quantum signature schemes used in TLS -``` +**Commands that change files** (`/agy:rescue`, `/agy:image`) do give agy permission to act. Their rails: a clean git tree first, a summary of every change afterwards, and `--isolate` to work on a separate copy. -The command wraps your topic in a research-oriented preamble (background, -key findings, caveats, sources) and delegates to `agy:runner`. Long -investigations work well in `--background`. +--- -### Generate an image +## ⚙️ How it works -```text -/agy:image a minimalist dark-mode login mockup, blue accent color -/agy:image --name hero --output ./assets/hero.png isometric illustration of a developer at a desk +``` + Claude Code + │ /agy:review + ▼ + bin/agy-plugin ──(first run)──▶ downloads the binary for your OS from GitHub Releases + │ and runs it only if its SHA-256 matches this repo + ▼ + agy-plugin (Rust, zero dependencies) + │ stages the diff · checks for secrets · locks agy down + ▼ + agy (your install, your login, your settings) ``` -Triggers `agy`'s built-in `generate_image` tool. The image is written to -the Antigravity artifacts dir (e.g. -`~/.gemini/antigravity-cli/brain//.png`). Pass `--output` if -you want the wrapper to copy it next to your project. +The plugin never replaces agy: it drives the `agy` you already have, with your account and your `AGENTS.md` / `GEMINI.md`. -## How it works +--- -Under the hood, the plugin is a thin wrapper around your local `agy` install: +## 📋 Requirements +- **Claude Code** with plugin support +- **Antigravity CLI (`agy`) 1.2.0+**, logged in (run `agy` once, or set `ANTIGRAVITY_API_KEY`). `/agy:setup` can install it. +- **git** for review and rescue +- **macOS** (Apple silicon / Intel), **Linux** (x86_64 / arm64), **Windows** (x86_64 / arm64, via the Git Bash Claude Code uses) + +--- + +
+🔧 Configuration (environment variables) + +| Variable | Default | Effect | +|---|---|---| +| `AGY_ASK_TIMEOUT` · `AGY_REVIEW_TIMEOUT` · `AGY_SCRAPE_TIMEOUT` · `AGY_DOCTOMD_TIMEOUT` · `AGY_IMAGE_TIMEOUT` | 8m · 10m · 5m · 8m · 8m | how long agy may take | +| `AGY_RESCUE_TIMEOUT` | none | time limit for rescue | +| `AGY_REVIEW_CONTEXT` | 25 | lines of context around each change | +| `AGY_REVIEW_ALLOW_SECRETS` | — | `1` = send even if keys were found (warns) | +| `AGY_SCRAPE_USE_PROXY` | — | `1` = let scrape use your HTTP proxy | +| `AGY_BIN` | from `PATH` | path to agy | +| `AGY_PLUGIN_CACHE` | `~/.cache/agy-plugin` | where the binary is kept | +| `AGY_PLUGIN_BIN` | — | use a locally built binary (development) | + +
+ +
+❓ FAQ + +**Do I need an Antigravity subscription?** +You need an account `agy` accepts: Google AI Pro / Ultra, Code Assist Standard / Enterprise, or an enterprise GCP project. See the [Antigravity docs](https://antigravity.google/docs/cli-overview). + +**Does the plugin send my data anywhere?** +Only through agy, the way agy normally does. The plugin's own single network request is downloading its binary from this repository's releases. + +**Will it change my agy settings?** +No. `--model` is passed per call; your `settings.json` is never edited. + +**Why does `rescue` need full permissions?** +Because it edits files and a background agy can't stop to ask. That's why it insists on a clean git tree, shows the changes, and offers `--isolate`. + +**Can I still use agy normally?** +Yes. The plugin uses your existing install and leaves it as it is. + +
+ +
+🛠️ Development + +```bash +cargo test # unit + end-to-end tests (against a fake agy) +cargo clippy --all-targets -- -D warnings +sh scripts/test-launcher.sh # launcher download & checksum tests +scripts/e2e-live.sh # against a real, logged-in agy (uses quota) +export AGY_PLUGIN_BIN=$PWD/target/release/agy-plugin # try your build in Claude Code ``` -Claude Code → /agy:* → agy-run.sh (Bash) → agy --print "" - ↘ agy-companion.mjs (Node) → agy --print "" -``` -- The plugin does **not** ship its own Antigravity runtime — it uses your - local `agy` binary, your local auth, and your local config. -- The Bash wrapper - ([`plugins/agy/scripts/agy-run.sh`](./plugins/agy/scripts/agy-run.sh)) - handles the synchronous commands; the Node companion - ([`agy-companion.mjs`](./plugins/agy/scripts/agy-companion.mjs)) - handles the stateful ones (background jobs, branch review). - -### How output is captured (agy issue #76) - -The plugin reads the answer from `agy`'s **stdout**. On older `agy` -(< 1.0.15) a bug (#76) swallowed non-TTY stdout — `agy --print` generated the -response but flushed nothing to a pipe — so the plugin recovered the answer -from `agy`'s own on-disk transcript instead. **agy 1.0.15 fixed that** (the -plugin is validated on **1.1.0**), so stdout is now the fast path and the -transcript remains only as a fallback for older `agy`. (`agy --print` also -*hangs* on a non-TTY stdin that never EOFs, so the plugin always closes -stdin.) - -What makes the read-only commands read-only is **not** the capture method — it -is that **`agy` is launched from a throwaway temp dir (not your repo)** with -only that dir in `--add-dir`, so even though `agy --print` still executes -write tools, it has no path to write into your repo. No -`--dangerously-skip-permissions`; `--sandbox` is layered on where the OS -enforces it. - -- **`/agy:ask`, `/agy:review`, `/agy:adversarial-review`** run `agy` read-only - from a temp dir and return its answer (stdout, with the transcript as - fallback) — no auto-approval. -- **`/agy:rescue`** edits files by design, and **`/agy:image`** saves a - generated image, so they use `--dangerously-skip-permissions`, scoped to a - throwaway temp dir. `rescue`'s repo writes are guarded by the clean-tree - check, the post-run diff, and `--isolate` worktree mode. - -See [SECURITY.md](./SECURITY.md) for the full posture and the honest -per-platform guarantee levels. - -## Configuration - -`agy` stores its preferences (selected model, theme, telemetry, trusted -workspaces) in `~/.gemini/antigravity-cli/settings.json`. Project-local -`AGENTS.md` / `GEMINI.md` files are read directly by `agy`. This plugin -doesn't override or shadow any of that — drop config files where `agy` -expects them and they'll be picked up. - -The `--model ` flag on `/agy:ask`, `/agy:delegate`, and `/agy:research` -swaps in your requested model for the duration of a single call (under a -lockfile, with automatic restore on exit) and leaves the TUI's selected -model intact for subsequent runs. - -## FAQ - -### Do I need an Antigravity subscription? - -You need whatever account `agy` accepts: Google AI Pro, Ultra, Code Assist -Standard/Enterprise, or an enterprise GCP project. See the -[Antigravity docs](https://antigravity.google/docs/cli-overview) for details. - -### Does this plugin send data anywhere other than what `agy` sends? - -No. The plugin runs `agy` locally over a Bash wrapper. The wrapper only reads -filesystem paths and your shell environment. Your prompts go directly to -Google through `agy`'s normal channels. - -### Can I keep using Antigravity outside this plugin? - -Yes — the plugin uses your local install. Running `agy` directly in a -terminal keeps working exactly as before. - -### Why a subagent instead of just a slash command? - -Subagents in Claude Code can run in the background and report back when -finished. That is the workflow you want when you "hand this off to another -model and keep working" — which is the whole point of delegating to `agy`. - -## Roadmap - -Built in phases; everything through Phase 3 has shipped and is validated -against real `agy` 1.1.0. - -- **Phase 1 — Foundation** ✅ - - [x] Attribution + marketplace setup (`NOTICE`, `LICENSE`, marketplace - `limeflash-antigravity`). - - [x] Validate `IMAGE_PATH` stays inside the `agy` artifacts dir - before `cp` — closes a low-severity exfil vector. - - [x] Pre-flight secret scan on `git diff` before `/agy:review`. - - [x] CI: shellcheck + bats unit tests on every PR. - - [x] Community files: `SECURITY.md`, `CONTRIBUTING.md`, issue/PR - templates, dependabot. -- **Phase 2 — Stateful workflows & safety rails** ✅ (0.5.x) - - [x] Node.js companion scaffold + state machine - (`lib/state.mjs`, `lib/job-control.mjs`, - `lib/tracked-jobs.mjs`, …). - - [x] `/agy:rescue` with `--background`, `--wait`, `--resume`, - `--fresh` and job control. - - [x] `/agy:status`, `/agy:result`, `/agy:cancel`. - - [x] `/agy:review --base ` for branch review (merge-base - resolution + expanded `-U25` + full-file context). - - [x] `/agy:adversarial-review` (challenge-mode review). - - [x] `agy` #76 capture: read-only **transcript capture** (no - auto-approve) for ask/review/adversarial + `write_file` fallback + - non-TTY stdin-hang fix — validated against real `agy` 1.1.0. - - [x] `/agy:rescue` safety rails: clean-tree guard, post-run diff, - `--isolate` worktree mode. - - [x] Secret-scan guardrails (Bash + companion parity). - - [x] CI: shellcheck + bats + vitest matrix (Node 18.18 / 20 / 22). - - [ ] Optional Stop-gate review hook (deferred — the hook can block - Claude responses; wants a careful safety review first). -- **Phase 3 — Antigravity-specific** (shipped in 0.7.x) - - [x] Safe `/agy:scrape`, `/agy:doc-to-md` (read-only, deny-list on input - URLs/paths) — v0.7.0. - - [x] Windows-native PowerShell entry for the read-only commands - (`agy-run.ps1`: ask / scrape / doc-to-md) — v0.7.1. - -See [CHANGELOG.md](./CHANGELOG.md) for shipped changes. - -## Tested & dogfooded - -- **245 unit tests** (`vitest`) plus Bash `bats` tests and `shellcheck`, run - in CI on **Node 18 / 20 / 22** across Ubuntu and macOS on every push. -- **Validated end-to-end** against a real `agy` 1.1.0 install on **Windows - (git-bash)**, **WSL2 Ubuntu**, and **macOS 26.5** — `ask`, `review`, - `scrape`, `doc-to-md`, and the read-only guarantee all confirmed on hardware. -- **The plugin reviews itself.** Running `/agy:review` and - `/agy:adversarial-review` on the plugin's own diffs is part of the workflow - — that's how the read-only-cwd hole, the secret-scanner coverage gaps, a - macOS symlink bug, and five SSRF / path / TOCTOU issues were caught and - fixed. - -## Credits - -Originally seeded from [@simplybychris](https://github.com/simplybychris)'s -[`antigravity-plugin-cc`](https://github.com/simplybychris/antigravity-plugin-cc) -(MIT) — thank you for the starting point. Job-control and state-persistence -patterns are inspired by -[`openai/codex-plugin-cc`](https://github.com/openai/codex-plugin-cc) (Apache-2.0). - -This project has since been substantially rewritten and extended: the -read-only guarantee, the `agy` #76 transcript-capture, the Node job-control -companion, `/agy:scrape` + `/agy:doc-to-md` with the SSRF / path guards, the -native PowerShell entry, the cross-platform validation, and the 245-test -suite are all original to it. See [NOTICE](./NOTICE) for attribution details. - -## License - -[MIT](./LICENSE). See [NOTICE](./NOTICE) for upstream attribution. +Rules of the house — including *std only, zero crates* — are in [CONTRIBUTING.md](./CONTRIBUTING.md); releases in [RELEASING.md](./RELEASING.md). + +
+ +--- + +## 🙏 Credits + +Started from [@simplybychris](https://github.com/simplybychris)'s [`antigravity-plugin-cc`](https://github.com/simplybychris/antigravity-plugin-cc) (MIT); the model aliases follow its 0.5.0. Background-job ideas are inspired by [`openai/codex-plugin-cc`](https://github.com/openai/codex-plugin-cc) (Apache-2.0). No code is copied from either; see [NOTICE](./NOTICE). + +**License:** [MIT](./LICENSE) · **Changes:** [CHANGELOG.md](./CHANGELOG.md) · **Security:** [SECURITY.md](./SECURITY.md) diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000..05e9993 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,21 @@ +# Releasing + +The plugin's code (slash commands, launcher) ships from `main`; the binary +ships from GitHub Releases, pinned by hash in `plugins/agy/bin/`. + +1. **Prepare** on a branch: bump the version in `Cargo.toml`, + `plugins/agy/.claude-plugin/plugin.json` and `.claude-plugin/marketplace.json` + (both fields), add the `CHANGELOG.md` section, run `cargo test`, + `sh scripts/test-launcher.sh` and `scripts/e2e-live.sh`. Merge. +2. **Tag** the merge commit: `git tag -a vX.Y.Z -m "vX.Y.Z" && git push origin vX.Y.Z`. + The tag must equal the `Cargo.toml` version (the workflow checks). +3. **Release workflow** (`.github/workflows/release.yml`) builds all six + targets, publishes the GitHub Release with the binaries and + `SHA256SUMS`, and opens a PR `release: pin agy-plugin binaries to vX.Y.Z` + that updates `plugins/agy/bin/VERSION` and `SHA256SUMS`. +4. **Review the pin PR**: compare its `SHA256SUMS` with the release asset, + then merge. Users get the new binary from that moment — the launcher + refuses anything whose hash isn't committed. + +Until the pin PR is merged, users keep the previous binary, which is fine: +the launcher pins a binary version independently of the plugin files. diff --git a/SECURITY.md b/SECURITY.md index 75c0aca..7a53da9 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,122 +1,178 @@ # Security Policy -## Read-only capture, and the `--dangerously-skip-permissions` tradeoff - -The plugin reads the answer from `agy`'s stdout. (Older `agy` < 1.0.15 had a -bug, #76, that swallowed non-TTY stdout; the plugin then recovered the answer -from `agy`'s on-disk transcript. agy 1.0.15 fixed it — the plugin is validated -on 1.1.0 — so stdout is the primary path and the transcript remains a -fallback.) - -**Read-only commands (`/agy:ask`, `/agy:review`, `/agy:adversarial-review`) -— agy runs OUTSIDE your repo.** These run `agy` read-only from a throwaway -temp dir and capture its answer — no write_file workaround, no -`--dangerously-skip-permissions`. - -**Important / the thing that actually enforces read-only:** `agy --print` -**still executes write tools** even without `--dangerously-skip-permissions` -(a non-TTY prompt is auto-proceeded). So "no auto-approve" alone does **not** -make a command read-only — that was a real bug (fixed in 0.6.2). What makes -these commands read-only is that **agy is launched from a throwaway temp dir -as its `cwd`, with only that temp dir in `--add-dir`, and your repo is never -its cwd, in `--add-dir`, its path, or its env** — so agy has no path to -write into the repo. (review/adversarial additionally read only pre-staged -copies of the diff + changed files in that temp dir.) `--sandbox` is layered -on top where the OS enforces it. When `node` is unavailable, `/agy:ask` -falls back to the write_file path below — also run from (and confined to) a -throwaway temp dir. - -**Write-capable commands (`/agy:rescue`, `/agy:image`) — auto-approve, but -scoped.** `rescue` legitimately edits files and `image` saves a generated -image, so they use `--dangerously-skip-permissions`. Safety comes from -scope + guards, not from removing the flag: - -| Command | `agy` write access | Auto-approve? | Real repo exposure | +## Advisory: read-only escape with agy 1.5.7+ (fixed in 0.9.0) + +**Affected:** plugin ≤ 0.8.1 used with agy 1.5.7 or newer. +**Impact:** `/agy:ask`, `/agy:review`, `/agy:adversarial-review`, +`/agy:scrape` and `/agy:doc-to-md` were documented as read-only, but agy could +write files outside its workspace — including files in your repository — +when its prompt (or content it read, e.g. a reviewed diff) told it to. + +agy 1.5.7 made **Auto** the default agent mode for headless `-p` runs, and in +agy 1.5.16 Auto mode approves, without asking, edits to any file inside a +git/jj/hg repository and any create-or-append elsewhere. 0.8.x relied on agy +running from a temp dir "with no path to the repo"; an absolute path in the +prompt is enough. We reproduced it on agy 1.5.16: plugin 0.8.1's `/agy:ask` +overwrote a file in an unrelated git repository. 0.9.0 pins every read-only +run to agy's Default mode (below) and refuses to run if it can't. + +**Upgrade to 0.9.0.** If you can't, avoid the read-only commands on +untrusted content. + +## How the read-only commands stay read-only + +Applies to ask, review, adversarial-review, scrape and doc-to-md. Each agy run: + +1. **runs outside your repo** — its cwd and only `--add-dir` is a fresh + private (0700) temp dir, or for reviews a stage dir holding the diff and + copies of the changed files; +2. **is pinned read-only** with one session-only setting (never saved), + passed as a single last token so no other flag can swallow or override it: + `--settings={"agentMode":"","permissions":{"deny":["command(*)","write_file(*)"]}}`. + That is three independent layers: Default agent mode, in which a headless + run *denies* anything needing approval (writes, edits, shell commands, and + — verified on agy 1.5.16 — reading files outside its workspace); plus + explicit deny rules for every shell command and every file write, which + agy enforces even in Auto mode and which beat any allow rule saved in your + agy settings. Denied attempts come back as `denied_actions` and the plugin + shows each one ("agy tried to use X, which this read-only command + blocks"). agy is also told in the prompt that the session is read-only, + so it usually doesn't try; +3. **fails closed**: if agy is 1.5.7+ (Auto by default) but has no + `--settings` flag, the plugin refuses to run instead of running unpinned; +4. runs **without `--dangerously-skip-permissions`**, under `--sandbox`; +5. gets an environment with repo-location hints removed + (`CLAUDE_PROJECT_DIR`, `GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`, + `GIT_COMMON_DIR`, `AGY_JOB_WORKSPACE`, `PWD`, `OLDPWD`); +6. only accepts `--print-timeout` and `--effort` as extra agy flags, each + with a value that isn't itself a flag; anything that could widen access + (`--mode`, `--settings`, `--add-dir`, `--dangerously-skip-permissions`, …) + is refused. + +What enforces step 2 is agy's own permission system, on every platform; the +plugin's tests check that the flags are passed, and `scripts/e2e-live.sh` +re-runs the write-escape attempt against a real agy. If Google changes what +Default mode means, this guarantee changes with it — the e2e script is how +we notice. + +**Inputs are guarded before agy sees them:** + +- **review** — *every line* of the diff (added, removed and context — a + `git rm .env` still sends the deleted secrets) *and* the full content of + every changed file are scanned for credentials (AWS, GitHub, Slack, Anthropic, OpenAI keys, PEM + blocks, inline `password=` style assignments); a hit aborts with exit 65 + unless `AGY_REVIEW_ALLOW_SECRETS=1`. Best-effort pattern matching, not a + replacement for gitleaks/trufflehog. Changed files are staged only if they + are regular files that really live inside the repo (no symlinks, no + symlinked directories, no `..`, no absolute paths, no binaries). +- **scrape** — the plugin downloads the page itself, then agy only converts + the saved copy. The URL must be http/https with no credentials, odd + characters or blocked hosts (loopback, private, link-local, CGNAT, + multicast, reserved, cloud metadata, `*.localhost`, `*.internal`, single- + label names, every decimal/hex/octal/IPv6-mapped/NAT64/6to4/`nip.io` + spelling of those). **Every address the host resolves to** is checked, + and curl is pinned to the vetted address (`--resolve`), so DNS rebinding + can't redirect the request; redirects are followed by hand and each hop is + re-checked; proxies are bypassed unless `AGY_SCRAPE_USE_PROXY=1` (a proxy + resolves names itself, which would undo the address check); size, time + and content type are capped. +- **doc-to-md** — allow-listed document extensions only, regular files only, + 10 MB cap, refused under `~/.ssh`, `~/.gnupg`, `~/.aws`, + `~/.config/gcloud`, `~/.gemini`, `~/.kube`, `~/.docker`, `~/.m2`, + `~/.purple`, FileZilla, `~/.password-store`, keyrings, browser and mail + profiles, `~/Library/Keychains`, `%APPDATA%` credential stores, `/etc`, + `/root`, `/proc`, `/sys`, `/dev`, `/var/run` (refused outright if the home + directory can't be determined; symlinks resolved; macOS + `/etc → /private/etc` handled); copied into agy's workspace under a fixed + name. The copy opens the file with `O_NOFOLLOW`, so a symlink swapped in + after validation is refused (swapping in a *different regular file* in + that window is not detected — it needs write access to the path anyway). + +## Write-capable commands + +| Command | agy may write | Auto-approve | Rails | |---|---|---|---| -| `/agy:ask` | none (read-only) | no | none | -| `/agy:review`, `/agy:adversarial-review` | reads staged copies in a temp **stage** dir (`cwd` = stage dir) | no | **none** — repo is never in `--add-dir`, path, env, or cwd | -| `/agy:image` | temp dir only | yes (write_file) | none | -| `/agy:rescue` | the repo (by design — it's a delegated coding task) | yes | mitigated by clean-tree guard, post-run diff, and `--isolate` worktree mode | - -**Honest guarantee levels:** - -- **macOS / Linux / WSL:** OS-enforced on top. `agy --sandbox` uses - seatbelt/bubblewrap to confine writes to the workspace (the throwaway - temp dir), and the repo is never that workspace. -- **Native Windows (git-bash):** the read-only commands are read-only *by - construction* — agy runs from a throwaway temp dir and the repo is never - its cwd, in `--add-dir`, its path, or env, so it has no path to write - there (this holds even though agy still executes write tools). - `--sandbox`'s OS enforcement is *very strong practical*, - **not** OS-hard: there is no lightweight, no-admin, dependency-free OS - sandbox on Windows (`icacls`/`attrib` are reversible by the same user and - were deliberately **not** used — they'd be security theater and risk - leaving your repo locked on a crash). This mostly matters for the - write-capable commands (`rescue`/`image`): a deliberately hostile prompt - injection that runs a shell command with a hardcoded absolute path is not - OS-blocked there. **For an OS-hard guarantee on Windows, run under WSL.** - -This analysis was itself pressure-tested by asking `agy` (see the project -history); `icacls`/`attrib`/Job-Objects were rejected as non-enforcing, -AppContainer/Low-Integrity as impractical for a CLI, and WSL identified as -the only robust no-admin path on Windows. The read-only transcript-capture -path that removed auto-approve from `ask`/`review` was validated live on -agy 1.1.0. +| ask, review, adversarial-review, scrape, doc-to-md | nothing | no | see above | +| `/agy:image` | anywhere (agy ≥ 1.5.2 approves outside the workspace under the flag) | yes | runs from a temp dir; only an image inside `~/.gemini/antigravity-cli/{brain,scratch,cache}` is ever copied to `--output` | +| `/agy:rescue` | the repo (by design) | yes | refuses a dirty git tree (`--allow-dirty` overrides); prints what changed; `--isolate` runs in a separate `git clone --shared` checkout (its own `.git`, repo-location env removed) and saves a patch instead | + +`--isolate` keeps agy's *intended* edits out of your tree; it is not a +sandbox — with auto-approval agy could still write elsewhere if a prompt +told it to. + +`image` needs auto-approval because agy's `generate_image` flow runs a +command that Default mode denies (checked on agy 1.5.16). Treat its +description like any prompt you give an agent with write access. + +## Job control + +Job records live in the workspace (`.agy-plugin/`), and a repository could +commit some. So `/agy:cancel` never takes a pid or a path from them: it uses +a private per-user registry outside every repo (`~/.local/state/agy-plugin`, +`%LOCALAPPDATA%\agy-plugin` on Windows, mode 0700). A running worker holds +an exclusive OS file lock there; cancel signals only when that lock is held +(the worker is alive *and* ours — a reused pid can't be hit), stops the +worker's process group and the agy it started, and deletes only a review +stage dir that this program created in the temp dir. Records in a repo that +commits `.agy-plugin/` trigger a warning; a symlinked `.agy-plugin` is +refused. Job records and logs are created 0600. + +## The plugin binary + +- **std-only Rust, zero third-party crates** — CI fails if a dependency + appears. OS calls go through `extern` declarations in `src/sys.rs`. +- **Built by GitHub Actions** (`.github/workflows/release.yml`) from a + tagged commit, published as a GitHub Release with `SHA256SUMS`. +- **Pinned in the repo:** `plugins/agy/bin/SHA256SUMS` is committed through a + reviewed PR after each release. The launcher refuses any binary whose + SHA-256 doesn't match it — on download and on every run (so a tampered + cache is caught too). Your trust root is this repository. +- The launcher's only network request is that one download, over https, + with timeouts. Concurrent first runs are safe. (Between verifying and + executing there is a short window in which a process running as *you* + could swap the cached file — such a process could already do anything.) + +## Limits we know about + +- Default mode is agy's to define; see above. +- Hard links to secrets can't be distinguished from regular files by path. +- With `AGY_SCRAPE_USE_PROXY=1`, DNS rebinding protection is the proxy's job. +- Secret scanning is pattern-based and will miss unusual formats. +- `rescue` and `image` can do whatever agy can do with auto-approval; their + rails limit the blast radius in your repo, not on your machine. ## Reporting a vulnerability -If you find a security issue in this plugin (the plugin source — **not** in -`agy` itself, Claude Code, or Google's services), report it privately: +If you find a security issue in this plugin (not in `agy` itself, Claude +Code, or Google's services), report it privately: -- Open a [private security advisory](https://github.com/limeflash/antigravity-plugin-cc/security/advisories/new) - on GitHub, **or** -- Email the maintainer via GitHub: . +- open a [private security advisory](https://github.com/limeflash/antigravity-plugin-cc/security/advisories/new), or +- contact the maintainer via GitHub: . -Please do **not** open a public issue for security reports. I'll acknowledge -within 7 days and aim to ship a fix or mitigation within 30 days, depending -on severity. +Please don't open a public issue. You'll get an acknowledgement within 7 days; +fixes aim to ship within 30 days depending on severity. ## Scope -**In scope:** - -- Shell-injection vectors through slash-command arguments - (`/agy:ask`, `/agy:rescue`, `/agy:review`, `/agy:image`, etc.) that - bypass the wrapper's quoting and reach the underlying shell. -- Prompt-injection vectors specific to how the wrapper constructs `agy` - invocations or parses `agy`'s replies (e.g., the `IMAGE_PATH` parser, - the `_scan_diff_for_secrets` guardrail). -- Path-traversal / arbitrary-overwrite issues in any file the plugin - writes to (`docs/agy/**`, `~/.gemini/antigravity-cli/settings.json` - patch, image `--output` copy). -- Race conditions in the `settings.json` patch + restore flow. -- Job-state persistence (Phase 2 onward): symlink attacks, predictable - IDs, missing fsync, etc. - -**Out of scope:** - -- Vulnerabilities in `agy` itself → report to Google. -- Vulnerabilities in Claude Code → report to Anthropic. -- Issues that require the attacker to already have shell access to the - user's machine. -- The Google OAuth flow or the install script - (`curl … | bash`) — those are operated by Google. -- Best-practice complaints that aren't a concrete exploit (e.g., "you - should use jq instead of grep"). Open a regular issue instead. +**In scope:** shell or argument injection (including flag injection into +agy, git or curl) through slash-command arguments; +ways to make a read-only command write, run commands or reach your repo; +bypasses of the secret, SSRF, document-path or image-path guards; the job +state under `.agy-plugin/` (symlinks, predictable ids, races); the launcher's +download and verification; anything that makes the binary run code it +shouldn't. -## Supported versions - -Only the latest commit on `main` is supported. Pin to a tagged release -if you need stability guarantees (see [CHANGELOG.md](./CHANGELOG.md)). +**Out of scope:** vulnerabilities in `agy` (report to Google) or Claude Code +(report to Anthropic); attacks that already need shell access to your +machine; Google's OAuth flow and install script; best-practice suggestions +without a concrete exploit (open a regular issue). -## Coordinated disclosure +## Supported versions -If you'd like to coordinate disclosure with a public write-up, mention -that in your initial report. I'll work with you on a timeline and CVE -request if applicable. +Only the latest release is supported. ## Hall of fame -Researchers who report valid issues will be credited in -[CHANGELOG.md](./CHANGELOG.md) under the fix entry (unless they prefer -to stay anonymous). +Researchers who report valid issues are credited in +[CHANGELOG.md](./CHANGELOG.md) under the fix entry (unless they prefer to +stay anonymous). diff --git a/examples/stub_agy.rs b/examples/stub_agy.rs new file mode 100644 index 0000000..049e28e --- /dev/null +++ b/examples/stub_agy.rs @@ -0,0 +1,143 @@ +//! A scripted stand-in for Google's `agy`, used by tests/cli.rs (std only). +//! +//! Every invocation appends one line to $STUB_RECORD: +//! \t\t +//! (env limited to the variables the plugin is supposed to strip, so tests +//! can assert they are gone). +//! +//! Behaviour by argv: +//! --version prints $STUB_VERSION (default 1.5.16) +//! --help prints $STUB_HELP (default: lists --model, --settings, --output-format) +//! models prints "Fetching..." + $STUB_MODELS (exit 1 if $STUB_MODELS_FAIL=1) +//! anything with --print / -p: +//! sleeps $STUB_SLEEP_MS, writes the prompt to $STUB_PROMPT_OUT, +//! if $STUB_MARKER_FROM_PROMPT=1 writes $STUB_IMAGE into the marker path named in the prompt, +//! prints a JSON result when --output-format json was given +//! ({"status":$STUB_STATUS,"response":$STUB_RESPONSE,"denied_actions":[...$STUB_DENIED]}), +//! else $STUB_RESPONSE; exits $STUB_EXIT (default 0). + +use std::io::Write; + +fn env(k: &str) -> Option { + std::env::var(k).ok() +} + +fn json_str(s: &str) -> String { + let mut o = String::from("\""); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + '\n' => o.push_str("\\n"), + '\r' => o.push_str("\\r"), + '\t' => o.push_str("\\t"), + c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), + c => o.push(c), + } + } + o.push('"'); + o +} + +const WATCHED_ENV: &[&str] = &[ + "CLAUDE_PROJECT_DIR", + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_COMMON_DIR", + "AGY_JOB_WORKSPACE", + "PWD", + "OLDPWD", +]; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if let Some(rec) = env("STUB_RECORD") { + let cwd = std::env::current_dir() + .map(|p| p.display().to_string()) + .unwrap_or_default(); + let envs: Vec = WATCHED_ENV + .iter() + .filter_map(|k| env(k).map(|v| format!("{k}={v}"))) + .collect(); + if let Ok(mut f) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(rec) + { + let _ = writeln!(f, "{cwd}\t{}\t{}", args.join("\x1f"), envs.join("\x1f")); + } + } + match args.first().map(String::as_str) { + Some("--version") => { + println!("{}", env("STUB_VERSION").unwrap_or_else(|| "1.5.16".into())); + return; + } + Some("--help") => { + println!( + "{}", + env("STUB_HELP").unwrap_or_else(|| "Usage of agy:\n --model Model\n --output-format Output format\n --settings Settings for this session only".into()) + ); + return; + } + Some("models") => { + if env("STUB_MODELS_FAIL").as_deref() == Some("1") { + std::process::exit(1); + } + println!("Fetching available models..."); + print!( + "{}", + env("STUB_MODELS") + .unwrap_or_default() + .replace("\\t", "\t") + .replace("\\n", "\n") + ); + return; + } + _ => {} + } + let prompt = args + .iter() + .position(|a| a == "--print" || a == "-p") + .and_then(|i| args.get(i + 1)) + .cloned() + .unwrap_or_default(); + if let Some(p) = env("STUB_PID_OUT") { + let _ = std::fs::write(p, std::process::id().to_string()); + } + if let Some(ms) = env("STUB_SLEEP_MS").and_then(|v| v.parse::().ok()) { + std::thread::sleep(std::time::Duration::from_millis(ms)); + } + if let Some(p) = env("STUB_PROMPT_OUT") { + let _ = std::fs::write(p, &prompt); + } + if env("STUB_MARKER_FROM_PROMPT").as_deref() == Some("1") + && let Some(marker) = prompt.lines().find(|l| l.ends_with("image-path.txt")) + { + let _ = std::fs::write(marker.trim(), env("STUB_IMAGE").unwrap_or_default()); + } + let response = env("STUB_RESPONSE").unwrap_or_default(); + if args + .windows(2) + .any(|w| w[0] == "--output-format" && w[1] == "json") + { + let denied: Vec = env("STUB_DENIED") + .unwrap_or_default() + .split(',') + .filter(|s| !s.is_empty()) + .map(|a| format!("{{\"action\":{},\"display_name\":\"Edit\"}}", json_str(a))) + .collect(); + println!( + "{{\"conversation_id\":\"c\",\"status\":{},\"response\":{},\"denied_actions\":[{}]}}", + json_str(&env("STUB_STATUS").unwrap_or_else(|| "SUCCESS".into())), + json_str(&response), + denied.join(",") + ); + } else { + println!("{response}"); + } + if let Some(e) = env("STUB_STDERR") { + eprintln!("{e}"); + } + std::process::exit(env("STUB_EXIT").and_then(|v| v.parse().ok()).unwrap_or(0)); +} diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index f245000..0000000 --- a/package-lock.json +++ /dev/null @@ -1,1432 +0,0 @@ -{ - "name": "@limeflash/antigravity-plugin-cc", - "version": "0.5.0-dev", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@limeflash/antigravity-plugin-cc", - "version": "0.5.0-dev", - "license": "MIT", - "devDependencies": { - "vitest": "^2.1.0" - }, - "engines": { - "node": ">=18.18" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", - "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", - "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", - "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", - "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", - "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", - "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", - "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", - "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", - "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", - "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", - "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", - "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", - "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", - "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", - "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", - "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", - "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", - "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", - "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", - "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", - "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", - "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", - "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.4.tgz", - "integrity": "sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.60.4.tgz", - "integrity": "sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.60.4.tgz", - "integrity": "sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.60.4.tgz", - "integrity": "sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.60.4.tgz", - "integrity": "sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.60.4.tgz", - "integrity": "sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.60.4.tgz", - "integrity": "sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.60.4.tgz", - "integrity": "sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.60.4.tgz", - "integrity": "sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.60.4.tgz", - "integrity": "sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.60.4.tgz", - "integrity": "sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-loong64-musl": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.60.4.tgz", - "integrity": "sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.60.4.tgz", - "integrity": "sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-ppc64-musl": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.60.4.tgz", - "integrity": "sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.60.4.tgz", - "integrity": "sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.60.4.tgz", - "integrity": "sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.60.4.tgz", - "integrity": "sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.60.4.tgz", - "integrity": "sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.60.4.tgz", - "integrity": "sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-openbsd-x64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.60.4.tgz", - "integrity": "sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ] - }, - "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.60.4.tgz", - "integrity": "sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.60.4.tgz", - "integrity": "sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.60.4.tgz", - "integrity": "sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.60.4.tgz", - "integrity": "sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.60.4.tgz", - "integrity": "sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@types/estree": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", - "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@vitest/expect": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz", - "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/spy": "2.1.9", - "@vitest/utils": "2.1.9", - "chai": "^5.1.2", - "tinyrainbow": "^1.2.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/mocker": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz", - "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/spy": "2.1.9", - "estree-walker": "^3.0.3", - "magic-string": "^0.30.12" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "msw": "^2.4.9", - "vite": "^5.0.0" - }, - "peerDependenciesMeta": { - "msw": { - "optional": true - }, - "vite": { - "optional": true - } - } - }, - "node_modules/@vitest/pretty-format": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz", - "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyrainbow": "^1.2.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz", - "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/utils": "2.1.9", - "pathe": "^1.1.2" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/snapshot": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz", - "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "2.1.9", - "magic-string": "^0.30.12", - "pathe": "^1.1.2" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/spy": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz", - "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "tinyspy": "^3.0.2" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/utils": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz", - "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "2.1.9", - "loupe": "^3.1.2", - "tinyrainbow": "^1.2.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/assertion-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", - "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - } - }, - "node_modules/cac": { - "version": "6.7.14", - "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", - "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/chai": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", - "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "assertion-error": "^2.0.1", - "check-error": "^2.1.1", - "deep-eql": "^5.0.1", - "loupe": "^3.1.0", - "pathval": "^2.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/check-error": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", - "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 16" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-eql": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", - "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/es-module-lexer": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", - "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/esbuild": { - "version": "0.21.5", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", - "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, - "node_modules/estree-walker": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", - "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "^1.0.0" - } - }, - "node_modules/expect-type": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", - "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/loupe": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", - "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/nanoid": { - "version": "3.3.12", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", - "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/pathe": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", - "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/pathval": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", - "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14.16" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/postcss": { - "version": "8.5.15", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", - "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.12", - "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/rollup": { - "version": "4.60.4", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.60.4.tgz", - "integrity": "sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.8" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.60.4", - "@rollup/rollup-android-arm64": "4.60.4", - "@rollup/rollup-darwin-arm64": "4.60.4", - "@rollup/rollup-darwin-x64": "4.60.4", - "@rollup/rollup-freebsd-arm64": "4.60.4", - "@rollup/rollup-freebsd-x64": "4.60.4", - "@rollup/rollup-linux-arm-gnueabihf": "4.60.4", - "@rollup/rollup-linux-arm-musleabihf": "4.60.4", - "@rollup/rollup-linux-arm64-gnu": "4.60.4", - "@rollup/rollup-linux-arm64-musl": "4.60.4", - "@rollup/rollup-linux-loong64-gnu": "4.60.4", - "@rollup/rollup-linux-loong64-musl": "4.60.4", - "@rollup/rollup-linux-ppc64-gnu": "4.60.4", - "@rollup/rollup-linux-ppc64-musl": "4.60.4", - "@rollup/rollup-linux-riscv64-gnu": "4.60.4", - "@rollup/rollup-linux-riscv64-musl": "4.60.4", - "@rollup/rollup-linux-s390x-gnu": "4.60.4", - "@rollup/rollup-linux-x64-gnu": "4.60.4", - "@rollup/rollup-linux-x64-musl": "4.60.4", - "@rollup/rollup-openbsd-x64": "4.60.4", - "@rollup/rollup-openharmony-arm64": "4.60.4", - "@rollup/rollup-win32-arm64-msvc": "4.60.4", - "@rollup/rollup-win32-ia32-msvc": "4.60.4", - "@rollup/rollup-win32-x64-gnu": "4.60.4", - "@rollup/rollup-win32-x64-msvc": "4.60.4", - "fsevents": "~2.3.2" - } - }, - "node_modules/rollup/node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", - "dev": true, - "license": "MIT" - }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true, - "license": "ISC" - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true, - "license": "MIT" - }, - "node_modules/std-env": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", - "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinyexec": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", - "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", - "dev": true, - "license": "MIT" - }, - "node_modules/tinypool": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", - "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.0.0 || >=20.0.0" - } - }, - "node_modules/tinyrainbow": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz", - "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/tinyspy": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz", - "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/vite": { - "version": "5.4.21", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", - "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } - } - }, - "node_modules/vite-node": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz", - "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==", - "dev": true, - "license": "MIT", - "dependencies": { - "cac": "^6.7.14", - "debug": "^4.3.7", - "es-module-lexer": "^1.5.4", - "pathe": "^1.1.2", - "vite": "^5.0.0" - }, - "bin": { - "vite-node": "vite-node.mjs" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/vitest": { - "version": "2.1.9", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz", - "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/expect": "2.1.9", - "@vitest/mocker": "2.1.9", - "@vitest/pretty-format": "^2.1.9", - "@vitest/runner": "2.1.9", - "@vitest/snapshot": "2.1.9", - "@vitest/spy": "2.1.9", - "@vitest/utils": "2.1.9", - "chai": "^5.1.2", - "debug": "^4.3.7", - "expect-type": "^1.1.0", - "magic-string": "^0.30.12", - "pathe": "^1.1.2", - "std-env": "^3.8.0", - "tinybench": "^2.9.0", - "tinyexec": "^0.3.1", - "tinypool": "^1.0.1", - "tinyrainbow": "^1.2.0", - "vite": "^5.0.0", - "vite-node": "2.1.9", - "why-is-node-running": "^2.3.0" - }, - "bin": { - "vitest": "vitest.mjs" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "@edge-runtime/vm": "*", - "@types/node": "^18.0.0 || >=20.0.0", - "@vitest/browser": "2.1.9", - "@vitest/ui": "2.1.9", - "happy-dom": "*", - "jsdom": "*" - }, - "peerDependenciesMeta": { - "@edge-runtime/vm": { - "optional": true - }, - "@types/node": { - "optional": true - }, - "@vitest/browser": { - "optional": true - }, - "@vitest/ui": { - "optional": true - }, - "happy-dom": { - "optional": true - }, - "jsdom": { - "optional": true - } - } - }, - "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, - "bin": { - "why-is-node-running": "cli.js" - }, - "engines": { - "node": ">=8" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index aa1ec3f..0000000 --- a/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "@limeflash/antigravity-plugin-cc", - "version": "0.8.1", - "private": true, - "description": "The Antigravity CLI (agy) plugin for Claude Code. Read-only commands with a real read-only guarantee plus secret/SSRF/path guards; a Node.js companion for background job control (/agy:rescue, /agy:status, /agy:result, /agy:cancel); Bash + PowerShell wrappers for the synchronous /agy:* commands.", - "license": "MIT", - "type": "module", - "engines": { - "node": ">=18.18" - }, - "scripts": { - "test": "vitest run --reporter=verbose", - "test:watch": "vitest" - }, - "devDependencies": { - "vitest": "^2.1.0" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/limeflash/antigravity-plugin-cc.git" - }, - "homepage": "https://github.com/limeflash/antigravity-plugin-cc", - "bugs": { - "url": "https://github.com/limeflash/antigravity-plugin-cc/issues" - } -} diff --git a/plugins/agy/.claude-plugin/plugin.json b/plugins/agy/.claude-plugin/plugin.json index f6de801..1d384e6 100644 --- a/plugins/agy/.claude-plugin/plugin.json +++ b/plugins/agy/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "agy", - "version": "0.8.1", - "description": "Use the Google Antigravity CLI (`agy`) from inside Claude Code. Synchronous Bash wrapper: /agy:setup, /agy:ask, /agy:delegate, /agy:research, /agy:review, /agy:image, /agy:scrape, /agy:doc-to-md, /agy:help. Node.js companion: /agy:rescue (background-capable), /agy:status, /agy:result, /agy:cancel. Read-only commands run agy outside your repo; scrape/doc-to-md add SSRF + path deny-lists. Per-call model selection via --model. Cross-platform, 245 tests.", + "version": "0.9.0", + "description": "Use the Google Antigravity CLI (`agy`) from Claude Code: /agy:ask, /agy:review, /agy:adversarial-review, /agy:scrape, /agy:doc-to-md (read-only: agy pinned to Default mode, outside your repo), /agy:rescue and /agy:image (write-capable, with rails), /agy:status, /agy:result, /agy:cancel, /agy:delegate, /agy:research, /agy:setup, /agy:help. Secret-scan + SSRF/path guards; per-call --model resolved against `agy models`. One std-only Rust binary, SHA-256 pinned.", "author": { "name": "limeflash", "url": "https://github.com/limeflash" diff --git a/plugins/agy/agents/runner.md b/plugins/agy/agents/runner.md index fc81f20..8ef23b9 100644 --- a/plugins/agy/agents/runner.md +++ b/plugins/agy/agents/runner.md @@ -1,6 +1,6 @@ --- name: runner -description: Forward a task to the Google Antigravity CLI (`agy`). Use proactively when the parent thread should delegate a focused coding, debugging, refactor, or research task to Antigravity — or when the user says "ask agy", "delegate to agy", "run this through Antigravity", or "let Gemini take this". +description: Forward a task to the Google Antigravity CLI (`agy`) for a read-only answer. Use proactively when the parent thread should delegate a focused investigation, debugging, code-reading, or research question to Antigravity — or when the user says "ask agy", "delegate to agy", "run this through Antigravity", or "let Gemini take this". model: sonnet tools: Bash skills: @@ -15,45 +15,46 @@ files, or follow up. ## When to take a task -- The parent thread is handing off a discrete coding, debugging, refactoring, - or research task to Antigravity. +- The parent thread is handing off a discrete investigation, debugging, + code-reading, or research task to Antigravity. - The user explicitly asked for `agy` / Antigravity / Gemini. Do not grab trivial questions the parent thread can answer in one breath. +The `ask` command is **read-only** (agy can read but not edit files); if the +task needs agy to change code, say so and point the parent at `/agy:rescue`. ## How to forward -Use exactly one `Bash` call. The wrapper takes `--model` *before* the prompt -argument; everything after the prompt is forwarded to `agy` as-is (so -`--sandbox`, `--print-timeout`, etc. still work). +Use exactly one `Bash` call: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" ask [--model ] "" [agy-native-flags...] +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" ask [--model ] '' [--print-timeout ] [--effort ] ``` -- Preserve the user's task text verbatim. Only strip flags that belong to - the parent slash command (`--background`) and the wrapper's own - `--model `. +- Pass the task text as **one** shell-quoted argument, verbatim, so + characters like `"`, `$`, `;`, `\` and backticks cannot break out. Never + splice it into the command line. +- Only strip flags that belong to the parent slash command (`--background`) + and `--model `. - If the parent passed `--model `, put it **before** the prompt argument: ``` - bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" ask --model opus "fix the off-by-one" + bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" ask --model opus 'why does the pagination test flake?' ``` - The wrapper resolves the alias, takes a lock on `~/.gemini/antigravity-cli/settings.json`, - patches the model field, invokes `agy`, then restores the original on - exit. Supported aliases: `flash-low`, `flash-medium`, `flash`, `pro-low`, - `pro`, `sonnet`, `opus`, `gpt-oss`. Canonical TUI strings (e.g. - `"Claude Opus 4.6 (Thinking)"`) are also accepted. -- If no `--model` was given, leave model selection to whatever the user's - TUI is currently set to. -- Do not pass any other model-selection flag to `agy` directly — `agy` - doesn't have one. Use the wrapper's `--model` or omit it entirely. -- If the wrapper reports that `agy` is missing or unauthenticated, return - that error verbatim and stop. Do not try to install or log in for the - user. + Aliases (`flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, `sonnet`, + `opus`, `gpt-oss`) resolve to the newest model of that family that + `agy models` lists; any id or display name from `agy models` is also + accepted. Unknown names fail with exit 64. +- If no `--model` was given, omit it; agy uses its current model. +- After the prompt, only `--print-timeout` and `--effort` are allowed; any + other agy flag is refused (exit 64). Don't add flags the parent didn't ask + for. +- If it reports that `agy` is not installed or not authenticated, return + that error verbatim and tell the user to run `/agy:setup`. Do not try to + install or log in for the user. ## Response style - Return Antigravity's stdout exactly as-is. No leading or trailing commentary. -- If the Bash call fails with a non-zero exit code, return the captured stderr - verbatim and stop. +- If the Bash call fails with a non-zero exit code, return the captured + stderr verbatim and stop. diff --git a/plugins/agy/bin/SHA256SUMS b/plugins/agy/bin/SHA256SUMS new file mode 100644 index 0000000..0b689f7 --- /dev/null +++ b/plugins/agy/bin/SHA256SUMS @@ -0,0 +1,6 @@ +eb594234b3b14a6365fcc11aad7d3d98bb5b2a0d2a6eed432d4ba81e49659d0f agy-plugin-aarch64-apple-darwin +b212310aa4c7cd8e0785a6a3fa10f015014523e893ae41f9f2290a593e1e51a7 agy-plugin-aarch64-pc-windows-msvc.exe +d785ae0894ed5f744e5294a63d2beb3926203389ec01c89a8356e416cb5c6c96 agy-plugin-aarch64-unknown-linux-musl +e6b4dae85ed1916c108a27c6fda2ae92ca3c5d39d3f66dbead2a1ad7359ad2c4 agy-plugin-x86_64-apple-darwin +1e7e19fee8830c70a41c28c049d9e2998d57f98b7641b7b4cf0819f37dbb0a03 agy-plugin-x86_64-pc-windows-msvc.exe +2493be98620e8cedf8fbb532e4a927ec431fcde3fd58afaf1c6647401eca2f07 agy-plugin-x86_64-unknown-linux-musl diff --git a/plugins/agy/bin/VERSION b/plugins/agy/bin/VERSION new file mode 100644 index 0000000..ac39a10 --- /dev/null +++ b/plugins/agy/bin/VERSION @@ -0,0 +1 @@ +0.9.0 diff --git a/plugins/agy/bin/agy-plugin b/plugins/agy/bin/agy-plugin new file mode 100755 index 0000000..4332d4e --- /dev/null +++ b/plugins/agy/bin/agy-plugin @@ -0,0 +1,122 @@ +#!/bin/sh +# agy-plugin launcher. Runs the native agy-plugin binary for this machine. +# +# The binary is built by CI and published as a GitHub Release asset. On +# first use it is downloaded once into a cache, and on EVERY run it is +# checked against the SHA-256 in ./SHA256SUMS, which is committed to this +# repository next to ./VERSION. A tampered release asset or cache entry is +# refused, never executed. +# +# Overrides: +# AGY_PLUGIN_BIN run this binary instead (development builds) +# AGY_PLUGIN_CACHE cache dir (default: $XDG_CACHE_HOME or ~/.cache, /agy-plugin) +# AGY_PLUGIN_DOWNLOAD_BASE release download base URL (tests, mirrors) +set -eu + +if [ -n "${AGY_PLUGIN_BIN:-}" ]; then + exec "$AGY_PLUGIN_BIN" "$@" +fi + +here=$(CDPATH='' cd -- "$(dirname -- "$0")" && pwd) +version=$(tr -d ' \r\n' <"$here/VERSION") + +os=$(uname -s) +case "$os" in + Darwin) os=apple-darwin ;; + Linux) os=unknown-linux-musl ;; + MINGW* | MSYS* | CYGWIN*) os=pc-windows-msvc ;; + *) + echo "agy-plugin: unsupported operating system '$os'" >&2 + exit 1 + ;; +esac +arch=$(uname -m) +case "$arch" in + x86_64 | amd64) arch=x86_64 ;; + arm64 | aarch64) arch=aarch64 ;; + *) + echo "agy-plugin: unsupported CPU architecture '$arch'" >&2 + exit 1 + ;; +esac +exe="" +[ "$os" = pc-windows-msvc ] && exe=.exe +asset="agy-plugin-$arch-$os$exe" + +expected=$(awk -v f="$asset" '$2 == f || $2 == "*" f { print $1; exit }' "$here/SHA256SUMS") +if [ -z "$expected" ]; then + echo "agy-plugin: no checksum for $asset in $here/SHA256SUMS (unsupported platform?)" >&2 + exit 1 +fi + +sha256() { + if command -v sha256sum >/dev/null 2>&1; then + sha256sum "$1" | awk '{ print $1 }' + elif command -v shasum >/dev/null 2>&1; then + shasum -a 256 "$1" | awk '{ print $1 }' + elif command -v openssl >/dev/null 2>&1; then + openssl dgst -sha256 "$1" | awk '{ print $NF }' + else + echo "agy-plugin: need sha256sum, shasum or openssl to verify the binary" >&2 + return 1 + fi +} + +if [ -n "${AGY_PLUGIN_CACHE:-}" ]; then + cache_root=$AGY_PLUGIN_CACHE +elif [ -n "${XDG_CACHE_HOME:-}" ]; then + cache_root=$XDG_CACHE_HOME/agy-plugin +elif [ -n "${HOME:-}" ]; then + cache_root=$HOME/.cache/agy-plugin +else + echo "agy-plugin: neither HOME nor XDG_CACHE_HOME is set; set AGY_PLUGIN_CACHE" >&2 + exit 1 +fi +cache="$cache_root/$version" +bin="$cache/$asset" + +if [ -f "$bin" ] && [ "$(sha256 "$bin")" = "$expected" ]; then + exec "$bin" "$@" +fi + +base="${AGY_PLUGIN_DOWNLOAD_BASE:-https://github.com/limeflash/antigravity-plugin-cc/releases/download}" +url="$base/v$version/$asset" +mkdir -p "$cache" +tmp="$bin.download.$$" +trap 'rm -f "$tmp"' EXIT +trap 'rm -f "$tmp"; exit 130' INT TERM +echo "agy-plugin: downloading v$version for this machine ($asset)..." >&2 +if command -v curl >/dev/null 2>&1; then + # https only for the default source; an explicit override (a mirror, or + # file:// in tests) is used as given. + if [ -n "${AGY_PLUGIN_DOWNLOAD_BASE:-}" ]; then + curl -fsSL --connect-timeout 20 --max-time 300 -o "$tmp" "$url" + else + curl -fsSL --proto '=https' --tlsv1.2 --connect-timeout 20 --max-time 300 -o "$tmp" "$url" + fi +elif command -v wget >/dev/null 2>&1; then + wget -q --timeout=60 --tries=2 -O "$tmp" "$url" +else + echo "agy-plugin: need curl or wget to download $url" >&2 + exit 1 +fi +actual=$(sha256 "$tmp") +if [ "$actual" != "$expected" ]; then + echo "agy-plugin: checksum mismatch for $asset — refusing to run it." >&2 + echo " expected $expected" >&2 + echo " got $actual" >&2 + exit 1 +fi +chmod 755 "$tmp" +# A concurrent first run may have installed it meanwhile (and on Windows a +# running .exe can't be replaced): use theirs if it verifies. +if [ -f "$bin" ] && [ "$(sha256 "$bin")" = "$expected" ]; then + rm -f "$tmp" +elif ! mv -f "$tmp" "$bin"; then + if ! { [ -f "$bin" ] && [ "$(sha256 "$bin")" = "$expected" ]; }; then + echo "agy-plugin: could not install $bin" >&2 + exit 1 + fi +fi +trap - EXIT INT TERM +exec "$bin" "$@" diff --git a/plugins/agy/bin/agy-plugin.ps1 b/plugins/agy/bin/agy-plugin.ps1 new file mode 100644 index 0000000..32b420c --- /dev/null +++ b/plugins/agy/bin/agy-plugin.ps1 @@ -0,0 +1,116 @@ +# agy-plugin launcher for native Windows PowerShell (5.1+), for machines +# without Git Bash. Claude Code itself runs the slash commands through Git +# Bash and the POSIX launcher (./agy-plugin); this is the same logic. +# +# Downloads the agy-plugin binary for this machine once, from the GitHub +# release pinned in .\VERSION, and on EVERY run checks it against the +# SHA-256 committed in .\SHA256SUMS. A tampered asset or cache entry is +# refused, never executed. +# +# Overrides: AGY_PLUGIN_BIN, AGY_PLUGIN_CACHE, AGY_PLUGIN_DOWNLOAD_BASE. + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version 2.0 + +# Windows PowerShell 5.1 does not escape embedded quotes when it starts a +# native program, so a prompt containing " would reach agy mangled. Build +# the command line ourselves with CommandLineToArgvW quoting rules. +function ConvertTo-NativeArg([string]$a) { + if ($a -eq '') { return '""' } + if ($a -notmatch '[\s"]') { return $a } + $s = $a -replace '(\\*)"', '$1$1\"' # double backslashes before a quote, escape the quote + $s = $s -replace '(\\+)$', '$1$1' # double a trailing backslash run (precedes the closing quote) + return '"' + $s + '"' +} + +function Invoke-Native([string]$exe, [string[]]$argv) { + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $exe + $psi.Arguments = (@($argv | ForEach-Object { ConvertTo-NativeArg $_ }) -join ' ') + $psi.UseShellExecute = $false + $p = [System.Diagnostics.Process]::Start($psi) + $p.WaitForExit() + return $p.ExitCode +} + +function Get-Sha256([string]$path) { + return (Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant() +} + +$argv = @($args | ForEach-Object { [string]$_ }) + +if ($env:AGY_PLUGIN_BIN) { + exit (Invoke-Native $env:AGY_PLUGIN_BIN $argv) +} + +$here = Split-Path -Parent $MyInvocation.MyCommand.Path +$version = (Get-Content -Raw -LiteralPath (Join-Path $here 'VERSION')).Trim() + +switch ($env:PROCESSOR_ARCHITECTURE) { + 'AMD64' { $arch = 'x86_64' } + 'ARM64' { $arch = 'aarch64' } + default { + [Console]::Error.WriteLine("agy-plugin: unsupported CPU architecture '$env:PROCESSOR_ARCHITECTURE'") + exit 1 + } +} +$asset = "agy-plugin-$arch-pc-windows-msvc.exe" + +$expected = $null +foreach ($line in Get-Content -LiteralPath (Join-Path $here 'SHA256SUMS')) { + $parts = $line.Trim() -split '\s+', 2 + if ($parts.Count -eq 2 -and $parts[1].TrimStart('*') -eq $asset) { + $expected = $parts[0].ToLowerInvariant() + break + } +} +if (-not $expected) { + [Console]::Error.WriteLine("agy-plugin: no checksum for $asset in $here\SHA256SUMS (unsupported platform?)") + exit 1 +} + +if ($env:AGY_PLUGIN_CACHE) { $cacheRoot = $env:AGY_PLUGIN_CACHE } else { $cacheRoot = Join-Path $env:LOCALAPPDATA 'agy-plugin' } +$cache = Join-Path $cacheRoot $version +$bin = Join-Path $cache $asset + +if ((Test-Path -LiteralPath $bin) -and ((Get-Sha256 $bin) -eq $expected)) { + exit (Invoke-Native $bin $argv) +} + +if ($env:AGY_PLUGIN_DOWNLOAD_BASE) { + $base = $env:AGY_PLUGIN_DOWNLOAD_BASE +} else { + $base = 'https://github.com/limeflash/antigravity-plugin-cc/releases/download' +} +$url = "$base/v$version/$asset" +New-Item -ItemType Directory -Force -Path $cache | Out-Null +$tmp = "$bin.download.$PID" +[Console]::Error.WriteLine("agy-plugin: downloading v$version for this machine ($asset)...") +try { + if ($url -like 'file://*') { + Copy-Item -LiteralPath ([Uri]$url).LocalPath -Destination $tmp + } else { + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Invoke-WebRequest -UseBasicParsing -TimeoutSec 300 -Uri $url -OutFile $tmp + } + $actual = Get-Sha256 $tmp + if ($actual -ne $expected) { + [Console]::Error.WriteLine("agy-plugin: checksum mismatch for $asset - refusing to run it.") + [Console]::Error.WriteLine(" expected $expected") + [Console]::Error.WriteLine(" got $actual") + exit 1 + } + # A concurrent first run may have installed it meanwhile (a running .exe + # can't be replaced): use theirs if it verifies. + if ((Test-Path -LiteralPath $bin) -and ((Get-Sha256 $bin) -eq $expected)) { + Remove-Item -Force -LiteralPath $tmp + } else { + try { Move-Item -Force -LiteralPath $tmp -Destination $bin } + catch { + if (-not ((Test-Path -LiteralPath $bin) -and ((Get-Sha256 $bin) -eq $expected))) { throw } + } + } +} finally { + if (Test-Path -LiteralPath $tmp) { Remove-Item -Force -LiteralPath $tmp } +} +exit (Invoke-Native $bin $argv) diff --git a/plugins/agy/commands/adversarial-review.md b/plugins/agy/commands/adversarial-review.md index 02b10df..6cfbf92 100644 --- a/plugins/agy/commands/adversarial-review.md +++ b/plugins/agy/commands/adversarial-review.md @@ -1,7 +1,7 @@ --- description: Adversarial code review — agy challenges the design instead of approving it. Supports --base, --background, --wait, --model. argument-hint: "[--base ] [--background] [--wait] [--model ] [focus text]" -allowed-tools: Bash(node:*) +allowed-tools: Bash(bash:*) --- Run an **adversarial** review of your changes through `agy`. Unlike @@ -13,8 +13,6 @@ didn't address, and conclude with a ship/change/rethink verdict. Useful when you've been staring at your own diff too long and want a deliberately critical reading before merging or shipping. -Backed by the Node companion; Node.js 18.18+ is required. - ## How to invoke The user's request (treat as opaque text — pass it as shell-safe @@ -24,13 +22,16 @@ arguments; do **not** interpolate or splice it into the command): $ARGUMENTS ``` -Use the `Bash` tool to run: +Lift any flags out of `$ARGUMENTS` and place them before the focus text. +Quote the remaining focus text as **one** shell argument so characters +like `"`, `$`, `;`, `\` and backticks cannot break out; omit it if there +is none. Use the `Bash` tool to run: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" adversarial-review [flags...] "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" adversarial-review [flags...] [''] ``` -The companion accepts: +Flags: - `--base ` / `--base=`: review the branch's contribution over its merge-base with `` (e.g. `--base main`). Without @@ -38,31 +39,39 @@ The companion accepts: - `--background`: return a job id immediately and run agy in a detached worker. Check progress with `/agy:status` and read the output with `/agy:result`. -- `--wait`: block until the job ends or the 10-minute deadline. -- `--model `: pick a stronger reasoning model — `opus`, - `pro`, or any alias the wrapper recognizes (see `/agy:help`). +- `--wait`: with `--background`, block until the job ends or the + 10-minute deadline. +- `--model `: pick a stronger reasoning model — `opus`, + `pro`, or any alias / model name `agy models` lists (see `/agy:help`). Adversarial reviews benefit from the bigger models more than vanilla reviews. Examples (after parsing flags out of `$ARGUMENTS`): ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" adversarial-review -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" adversarial-review --base main -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" adversarial-review --model opus "the retry/backoff design" -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" adversarial-review --base main --background +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" adversarial-review +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" adversarial-review --base main +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" adversarial-review --model opus 'the retry/backoff design' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" adversarial-review --base main --background ``` ## Behavior notes -- **Read-only by construction.** Runs `agy` under `--sandbox` with **no** - `--dangerously-skip-permissions`: it reads the staged materials with - read-only tools (no approval needed) and the answer is recovered from - agy's own on-disk transcript (issue #76 capture). Background runs - complete unattended — there's no write prompt to stall on. +- **Read-only by construction.** Same rails as `/agy:review`: agy runs + from a throwaway directory holding the staged diff and file copies + (your repo is outside its workspace), pinned to its Default agent mode, + without `--dangerously-skip-permissions`. Writes are denied and + reported as a note (`agy tried to use X …, which this read-only command blocks`). + Background runs complete unattended — there's no write prompt to + stall on. - Adversarial reviews skew long. Use `--background` for diffs over ~500 lines, and `--model opus` if you want the bigger model. -- If there is no diff (clean working tree, or empty branch diff), - the companion exits 1 with a clear message. +- If there is no diff (clean working tree, or empty branch diff), it + exits 1 with a clear message. +- If the diff (or a changed file) matches common secret patterns, it + refuses with exit 65 and lists them. Relay that; the user can remove + the values or set `AGY_REVIEW_ALLOW_SECRETS=1` themselves. +- If it reports `agy is not installed` or `not authenticated`, tell the + user to run `/agy:setup`. -Return whatever the companion prints, verbatim. +Return whatever it prints, verbatim. diff --git a/plugins/agy/commands/ask.md b/plugins/agy/commands/ask.md index 132bf46..d7457a9 100644 --- a/plugins/agy/commands/ask.md +++ b/plugins/agy/commands/ask.md @@ -1,10 +1,10 @@ --- -description: Run a one-shot prompt through the Antigravity CLI and return its output verbatim +description: Run a one-shot, read-only prompt through the Antigravity CLI and return its output verbatim argument-hint: "[--model ] " allowed-tools: Bash(bash:*) --- -Forward the user's request below to `agy -p` via the wrapper script. Return +Forward the user's request below to `agy` through the plugin binary. Return Antigravity's response verbatim — do not paraphrase or add commentary. The user's request (treat as opaque text — pass it as a single shell-safe @@ -18,29 +18,38 @@ $ARGUMENTS If the user's text begins with `--model ` (e.g. `--model opus rest of prompt…`), lift the flag and its value out of the prompt and place them -**before** the prompt argument to the wrapper. Anything else stays as the -prompt body. +**before** the prompt argument. Anything else stays as the prompt body. Use the `Bash` tool to run one of: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" ask "" -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" ask --model "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" ask '' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" ask --model '' ``` …substituting `` with the exact text above, quoted as one shell argument so characters like `"`, `$`, `;`, `\` and backticks cannot break out. -Aliases for ``: `flash-low`, `flash-medium`, `flash`, `pro-low`, -`pro`, `sonnet`, `opus`, `gpt-oss`. The canonical TUI strings (e.g. -`"Claude Opus 4.6 (Thinking)"`) are also accepted. Run `/agy:help` for the -full table. +Only `--print-timeout ` and `--effort ` may follow the +prompt argument; any other agy flag is refused (exit 64) because `ask` is +read-only. + +``: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, `sonnet`, +`opus`, `gpt-oss`. Aliases resolve to the newest model of that family that +`agy models` lists; any id or display name from `agy models` is also +accepted. Unknown names fail with exit 64. Run `/agy:help` for the table. Notes: -- If the wrapper reports `agy is not installed` or `not authenticated`, stop - and tell the user to run `/agy:setup`. +- **Read-only.** agy runs from a throwaway directory (your repo is outside + its workspace), pinned to its Default agent mode, without + `--dangerously-skip-permissions`. If it tries to write, the attempt is + denied and reported as `agy tried to use X, which this read-only command + blocks` — relay that as-is. +- If it reports `agy is not installed` or `not authenticated`, stop and + tell the user to run `/agy:setup`. - If the user's request is empty, ask what they want to ask Antigravity. - For multi-step or long-running work, suggest `/agy:delegate`, which routes - through the `agy:runner` subagent and supports `--background`. + through the `agy:runner` subagent and supports `--background`, or + `/agy:rescue` when agy should edit files. diff --git a/plugins/agy/commands/cancel.md b/plugins/agy/commands/cancel.md index 29a4e6b..b89ea90 100644 --- a/plugins/agy/commands/cancel.md +++ b/plugins/agy/commands/cancel.md @@ -1,11 +1,12 @@ --- -description: Cancel a running /agy:rescue job (SIGTERM, then SIGKILL after a grace). -argument-hint: "[task-id|prefix]" -allowed-tools: Bash(node:*) +description: Cancel a running background /agy:rescue or /agy:review job (stops the worker and agy itself). +argument-hint: "[job-id|prefix]" +allowed-tools: Bash(bash:*) --- -Stop an active background job started by `/agy:rescue --background`. -Defaults to the latest cancelable job in this workspace. +Stop an active background job started by `/agy:rescue --background`, +`/agy:review --background` or `/agy:adversarial-review --background`. +Defaults to the latest job in this workspace. ## How to invoke @@ -16,23 +17,31 @@ $ARGUMENTS If empty: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" cancel +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" cancel ``` -If the user passed an id or prefix: +If the user passed an id or prefix (quote it as one shell argument): ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" cancel "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" cancel '' ``` ## Behavior notes -- The companion sends `SIGTERM` first, waits up to 5 seconds, then - escalates to `SIGKILL` if the process hasn't exited. On Windows, - this is whatever the OS provides for those signals. -- A job whose record claims `running` but whose PID is already dead - is marked `canceled` without sending any signal. -- A completed/failed/already-canceled job exits 2 with a message - saying nothing was done — there's nothing to cancel. - -Return the companion's stdout verbatim. +- Cancel stops the worker's whole process group — the worker **and** the + `agy` process it started: `SIGTERM` first, then `SIGKILL` after a + 5-second grace. On Windows it uses `taskkill /T` on the process tree. +- Only jobs you started on this machine can be stopped: cancel finds the + worker through a private per-user registry and signals it only while the + worker provably holds its lock. A job whose worker is already gone is + marked `canceled` without sending any signal; a record that came with + the repository (`not-started-here`) is marked canceled and nothing is + stopped or deleted. +- With no id, it cancels the newest job that is still running or pending. +- A completed/failed/already-canceled job exits 2 saying it is already + finished — there's nothing to cancel. An unknown or ambiguous id also + exits 2. +- A canceled `/agy:rescue` may have edited files already; suggest + `git status` / `git diff` to see what it left behind. + +Return its stdout verbatim. diff --git a/plugins/agy/commands/delegate.md b/plugins/agy/commands/delegate.md index 14c7e6a..8d09c1f 100644 --- a/plugins/agy/commands/delegate.md +++ b/plugins/agy/commands/delegate.md @@ -5,7 +5,9 @@ allowed-tools: Agent --- Hand the user's task to the `agy:runner` subagent -(`subagent_type: "agy:runner"`). +(`subagent_type: "agy:runner"`). The runner uses the read-only `ask` +command, so agy can read and answer but not edit files — for a task where +agy should change code, use `/agy:rescue` instead. Raw user request: $ARGUMENTS @@ -16,15 +18,14 @@ $ARGUMENTS `run_in_background: true`. Strip the flag from the forwarded task text. - Otherwise run the subagent in the foreground. - If the request contains `--model `, forward it to the subagent so - it can be appended to the wrapper call as `--model ` (placed - **before** the prompt argument). Strip it from the task text. -- If no model is given, the wrapper uses whatever the TUI is currently set - to (stored in `~/.gemini/antigravity-cli/settings.json`). - -Aliases for ``: `flash-low`, `flash-medium`, `flash`, `pro-low`, -`pro`, `sonnet`, `opus`, `gpt-oss`. Canonical TUI strings (e.g. -`"Claude Opus 4.6 (Thinking)"`) are also accepted. Run `/agy:help` for the -full table. + it can pass `--model ` **before** the prompt argument. Strip it + from the task text. +- If no model is given, agy uses whatever model it is currently set to. + +``: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, `sonnet`, +`opus`, `gpt-oss` — each resolves to the newest model of that family that +`agy models` lists. Any id or display name from `agy models` is also +accepted. Run `/agy:help` for the table. ## Response style diff --git a/plugins/agy/commands/doc-to-md.md b/plugins/agy/commands/doc-to-md.md index 59b3dc7..6282dba 100644 --- a/plugins/agy/commands/doc-to-md.md +++ b/plugins/agy/commands/doc-to-md.md @@ -6,10 +6,12 @@ allowed-tools: Bash(bash:*) Convert a local document to clean Markdown through the Antigravity CLI. **Read-only and scoped:** the path is validated (allow-listed document -extensions only; a real regular file; size cap; **not** under a sensitive -directory like `~/.ssh`, `~/.aws`, or `~/.gemini`; symlinks resolved), then -staged into a throwaway temp dir so agy sees **only that one file** — it -cannot read the rest of your filesystem and cannot write to your repo. +extensions only; a real regular file; 10 MB cap; **not** under a sensitive +location like `~/.ssh`, `~/.aws`, `~/.gemini` or `/etc`; symlinks resolved), +then copied under a fixed name into a throwaway directory so agy sees +**only that one file**. agy runs there pinned to its Default agent mode, +without `--dangerously-skip-permissions` — it cannot read the rest of your +filesystem and cannot write to your repo. The user's input below is a single file path (optionally preceded by `--model `). Pass it as one shell-safe argument; do **not** interpolate it: @@ -24,17 +26,17 @@ Lift a leading `--model ` (if present) out and place it before the path. Use the `Bash` tool to run one of: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" doc-to-md "" -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" doc-to-md --model "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" doc-to-md '' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" doc-to-md --model '' ``` Return the Markdown verbatim. Offer to save it to a file if the user wants. Notes: -- Allowed types include: pdf, docx, doc, odt, rtf, html/htm, xml, md, - txt, rst, csv, pptx, ppt, epub. Anything else (`.env`, `.pem`, `.key`, an - extension-less secret, …) is refused (exit 65) **by design** — relay the - reason, don't bypass it. -- Requires Node.js (path validation + output capture). If `agy` isn't set up, - tell the user to run `/agy:setup`. +- Allowed types: pdf, docx, doc, odt, rtf, html/htm/xhtml, xml, md/markdown, + txt/text, rst, org, adoc, csv, tsv, pptx, ppt, epub. Anything else (`.env`, + `.pem`, `.key`, an extension-less secret, …) is refused (exit 65) **by + design** — relay the reason, don't bypass it. +- If it reports `agy is not installed` or `not authenticated`, tell the + user to run `/agy:setup`. diff --git a/plugins/agy/commands/help.md b/plugins/agy/commands/help.md index 7f40db0..89401b6 100644 --- a/plugins/agy/commands/help.md +++ b/plugins/agy/commands/help.md @@ -1,16 +1,16 @@ --- -description: Show all /agy:* commands, supported --model aliases, and canonical model names +description: Show all /agy:* commands, supported --model aliases, and the models agy currently offers allowed-tools: Bash(bash:*) --- -Run the wrapper's help branch, then print its stdout verbatim as a fenced +Run the plugin's help command, then print its stdout verbatim as a fenced code block in your text response. Do not paraphrase, reorder, or summarize — -the wrapper is the authoritative source for the command list, model aliases, -and canonical model names. The output MUST appear as readable text in the -reply, not just as a collapsed tool result. +it is the authoritative source for the command list, model aliases, and the +models `agy models` currently lists. The output MUST appear as readable text +in the reply, not just as a collapsed tool result. ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" help +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" help ``` After the Bash call completes, copy the full stdout into your response inside diff --git a/plugins/agy/commands/image.md b/plugins/agy/commands/image.md index ba2ab11..d2a6f04 100644 --- a/plugins/agy/commands/image.md +++ b/plugins/agy/commands/image.md @@ -1,13 +1,11 @@ --- -description: Generate an image with Antigravity CLI (uses agy's built-in generate_image tool — Imagen under the hood) +description: Generate an image with Antigravity CLI (uses agy's built-in generate_image tool) argument-hint: "[--name ] [--output ] " allowed-tools: Bash(bash:*) --- -Ask `agy` to generate an image. The Antigravity CLI ships a native -`generate_image` tool (Imagen under the hood) that triggers automatically -when the prompt asks for an image — the wrapper builds the right prompt and -extracts the saved file path. +Ask `agy` to generate an image with its native `generate_image` tool. The +plugin builds the prompt, locates the saved file and optionally copies it. The user's request (treat as opaque — pass through as shell-safe arguments): @@ -22,42 +20,40 @@ Parse the user's request into three parts: - `--name ` — optional. Filename slug `agy` should save the image under (no extension). -- `--output ` — optional. Local path the wrapper should copy the - generated file to after `agy` finishes. +- `--output ` — optional. Local path to copy the generated file to + after `agy` finishes. - The remaining text — the description of what to generate. Use the `Bash` tool to run: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" image "" [--name ] [--output ] +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" image [--name ] [--output ] '' ``` …with the description quoted as one shell argument so characters like `"`, -`$`, `;` cannot break out. +`$`, `;`, `\` and backticks cannot break out. -## How the wrapper finds the saved path +## Output -The wrapper builds a prompt that asks `agy` to end its reply with a single -line: +On success it prints: ``` -IMAGE_PATH: +[agy-plugin] generated: +[agy-plugin] copied to: <--output path> (only with --output) ``` -This is the **primary contract**. If `agy` honors it, the wrapper picks the -path up deterministically and (when `--output` is set) copies the file -there. As a fallback, the wrapper also scrapes any absolute `*.png/.jpg/.jpeg/.webp` -path that appears in `agy`'s reply. - -If neither is found, the wrapper prints a clear warning so the user knows the -file wasn't located. Generated files normally live under -`~/.gemini/antigravity-cli/brain//.`. +The image path is taken from a marker file agy writes and is accepted only +if it lies inside agy's artifacts directory +(`~/.gemini/antigravity-cli/{brain,scratch,cache}/`); anything else is +refused with exit 66 — relay that, don't work around it. If agy produced no +locatable image it exits 1. ## Notes -- Return Antigravity's full text response verbatim so the user can see the - generated path. +- `image` is write-capable: agy runs with auto-approval (sandboxed, in a + throwaway directory) so its image tool can save the file. +- Return the output verbatim so the user can see the generated path. - If the user did not provide any description, ask what they want to generate. -- If the wrapper reports `agy is not installed` or `not authenticated`, - stop and tell the user to run `/agy:setup`. +- If it reports `agy is not installed` or `not authenticated`, stop and + tell the user to run `/agy:setup`. diff --git a/plugins/agy/commands/rescue.md b/plugins/agy/commands/rescue.md index 635e742..2bd4c72 100644 --- a/plugins/agy/commands/rescue.md +++ b/plugins/agy/commands/rescue.md @@ -1,24 +1,24 @@ --- -description: Delegate a task to agy with full job control + safety rails (isolate, clean-tree guard, post-run diff). Phase-2 alternative to /agy:delegate. +description: Delegate a coding task to agy with write access, job control and safety rails (isolate, clean-tree guard, post-run diff). argument-hint: "[--isolate] [--allow-dirty] [--background] [--wait] [--resume|--fresh] [--model ] " -allowed-tools: Bash(node:*) +allowed-tools: Bash(bash:*) --- -Hand the user's task to the Antigravity CLI (`agy`) through the -plugin's Node.js companion, which adds background execution, job -control, and persistent state under `/.agy-plugin/`. +Hand the user's task to the Antigravity CLI (`agy`) with permission to +edit files, plus background execution, job control, and persistent state +under `/.agy-plugin/`. Use `/agy:rescue` instead of `/agy:delegate` when the user wants to: +- Let agy change code (delegate/ask are read-only). - Start the work and come back later (`--background`). -- Block on a long-running task with a deadline (`--wait`; default - 10 minutes timeout, configurable in `agy-companion.mjs`). -- Resume the most recent agy thread (`--resume`). -- Force a brand-new conversation regardless of history (`--fresh`). +- Block on a background task with a 10-minute deadline (`--background --wait`). +- Continue the most recent agy conversation (`--resume`). The default, + `--fresh`, starts a new one. - Get a job id they can later inspect with `/agy:status`, fetch with `/agy:result`, or stop with `/agy:cancel`. For one-shot, "ask agy a question and read the reply" UX, prefer -`/agy:ask` (synchronous, Bash wrapper, no Node required). +`/agy:ask`. ## How to invoke @@ -31,16 +31,20 @@ backticks): $ARGUMENTS ``` -Lift any leading routing flags out of `$ARGUMENTS` and place them -before the task text on the companion command line: +Lift any leading flags out of `$ARGUMENTS` and place them before the +task text: -- `--background`, `--wait`, `--resume`, `--fresh`: boolean +- `--isolate`, `--allow-dirty`, `--background`, `--wait`, `--resume`, + `--fresh`: boolean - `--model ` or `--model=`: value +- Other agy flags (e.g. `--print-timeout 20m`, `--effort high`) are + forwarded to agy as-is. Only known agy value-flags consume the next + word, so the task text is never swallowed. Use the `Bash` tool to run: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" rescue [flags...] "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" rescue [flags...] '' ``` …with `` quoted as one shell argument so characters like @@ -49,33 +53,30 @@ node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" rescue [flags...] "`: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, +`sonnet`, `opus`, `gpt-oss` — resolved to the newest model of that +family that `agy models` lists and passed to agy's `--model` for this +run only. Any id or display name from `agy models` is also accepted. ## Background, foreground, and the job id -- **Foreground** (default): the companion runs `agy` synchronously, - streams its stdout/stderr to the job's log file, and prints the - captured content back when the run ends. Use this when the user - wants the reply right now. -- **Background** (`--background`): the companion creates a job - record, spawns a detached worker, and returns the job id (e.g. - `agy-3a7b9c12`) in under a second. The user can then continue - working in Claude Code and come back to check on it. -- **Background + wait** (`--background --wait`): combines the two — - starts in the background but blocks here until the job ends or - the deadline fires. - -Always surface the job id to the user when in background mode so -they can pass it to `/agy:status`, `/agy:result`, or `/agy:cancel`. +- **Foreground** (default): runs `agy` now and prints its reply (and + the change summary) when the run ends. A job record is still kept. +- **Background** (`--background`): creates a job record, spawns a + detached worker, and returns the job id (e.g. `agy-3a7b9c12`) + immediately. The user can keep working and come back to it. +- **Background + wait** (`--background --wait`): starts in the + background but blocks here until the job ends or 10 minutes pass. + +Always surface the job id to the user in background mode so they can +pass it to `/agy:status`, `/agy:result`, or `/agy:cancel`. ## Safety: how rescue protects your repo @@ -88,15 +89,15 @@ that safe: dirty working tree** (uncommitted changes), so you always have a clean baseline to revert to. Commit/stash first, use `--isolate`, or pass `--allow-dirty` to override. -2. **Post-run diff.** After a non-isolated rescue, the companion - prints `git diff --stat` + any new files, so you see exactly what - agy changed before committing. -3. **`--isolate` (strongest).** agy edits a throwaway `git worktree` - copy — **your real working tree is never touched**. The companion - captures the result as a patch under - `.agy-plugin/patches/.patch` and prints `git apply` / discard - instructions. Foreground only (it shows you the patch). Requires a - git repo. +2. **Post-run diff.** After a non-isolated rescue, it prints a + `git diff --stat` + new-files summary, so you see exactly what agy + changed before committing. +3. **`--isolate` (strongest).** agy edits a separate checkout + (`git clone --shared` of HEAD, with its own `.git`), so its edits + don't land in your working tree. It is not a sandbox — agy still runs + with auto-approval. The result is saved as a patch under `.agy-plugin/patches/.patch` with + `git apply` / discard instructions. Foreground only (it shows you + the patch). Requires a git repo. **Recommend `--isolate` for anything non-trivial**, or for repos with work you can't afford to lose. @@ -105,12 +106,13 @@ work you can't afford to lose. - `--isolate` overrides `--background` (it runs foreground to show you the patch). -- Non-isolated rescue on a non-git directory warns (no safety net) but +- `--resume` and `--fresh` are mutually exclusive (exit 64). +- Non-isolated rescue in a non-git directory warns (no safety net) but proceeds. -- If the companion reports `cannot find the agy binary`, tell the +- If it reports `agy is not installed` or `not authenticated`, tell the user to run `/agy:setup`. -- If the companion errors with exit 64 ("task description is - required"), ask the user what they want agy to do. +- If it exits 64 with "task description is required", ask the user + what they want agy to do. -Return the companion's stdout verbatim — no extra commentary before -or after. The companion is the canonical authority on what happened. +Return its stdout verbatim — no extra commentary before or after. The +plugin's output is the canonical record of what happened. diff --git a/plugins/agy/commands/research.md b/plugins/agy/commands/research.md index c5e3451..94d6fc3 100644 --- a/plugins/agy/commands/research.md +++ b/plugins/agy/commands/research.md @@ -38,14 +38,14 @@ Then invoke the `agy:runner` subagent with that prompt as `run_in_background: true`. Research is often long-running — prefer background unless the user explicitly asked for foreground. - If the request contains `--model `, forward it to the subagent so - it can be appended to the wrapper call as `--model ` (placed - **before** the prompt argument). If no model is given, leave the choice to - whatever the TUI is currently set to (a reasoning-strong model like - `pro` or `opus` works well for research). - -Aliases: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, `sonnet`, -`opus`, `gpt-oss`. Canonical TUI strings (e.g. `"Claude Opus 4.6 (Thinking)"`) -are also accepted. Run `/agy:help` for the full table. + it can pass `--model ` **before** the prompt argument. If no model + is given, agy uses whatever model it is currently set to (a + reasoning-strong model like `pro` or `opus` works well for research). + +``: `flash-low`, `flash-medium`, `flash`, `pro-low`, `pro`, `sonnet`, +`opus`, `gpt-oss` — each resolves to the newest model of that family that +`agy models` lists. Any id or display name from `agy models` is also +accepted. Run `/agy:help` for the table. ## Response style diff --git a/plugins/agy/commands/result.md b/plugins/agy/commands/result.md index c70a189..b5868e2 100644 --- a/plugins/agy/commands/result.md +++ b/plugins/agy/commands/result.md @@ -1,11 +1,12 @@ --- -description: Print the captured output of a /agy:rescue job (latest by default). -argument-hint: "[task-id|prefix]" -allowed-tools: Bash(node:*) +description: Print the captured output of an /agy:rescue or /agy:review job (latest by default). +argument-hint: "[job-id|prefix]" +allowed-tools: Bash(bash:*) --- -Fetch the captured stdout/stderr of an agy job. Defaults to the -most recent job in this workspace. +Fetch the captured output of an agy job (`/agy:rescue`, `/agy:review`, +`/agy:adversarial-review`). Defaults to the most recent job in this +workspace. ## How to invoke @@ -16,24 +17,23 @@ $ARGUMENTS If empty: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" result +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" result ``` -If the user passed an id or prefix: +If the user passed an id or prefix (quote it as one shell argument): ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" result "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" result '' ``` ## Behavior notes -- The companion prints the job's detail header first, then a +- It prints the job's detail header first (status, exit code, …), then a `--- output ---` separator, then the contents of the log file at `/.agy-plugin/logs/.log`. - For a job that's still running, the log is whatever the worker has flushed so far. There's no guarantee it ends on a clean line. -- For a job that exited, the trailing line shows the final status - and exit code so the user can see at a glance whether agy - succeeded. +- An unknown or ambiguous id exits 2 (ambiguous prefixes list the + candidates). -Return the companion's stdout verbatim. +Return its stdout verbatim. diff --git a/plugins/agy/commands/review.md b/plugins/agy/commands/review.md index edf4b26..db4d462 100644 --- a/plugins/agy/commands/review.md +++ b/plugins/agy/commands/review.md @@ -1,19 +1,12 @@ --- -description: Ask Antigravity to review your git diff. Add --base for branch review or --background to run later. +description: Ask Antigravity to review your git diff (read-only). Add --base for branch review or --background to run later. argument-hint: "[--base ] [--background] [--wait] [--model ] [focus text]" -allowed-tools: Bash(bash:*), Bash(node:*) +allowed-tools: Bash(bash:*) --- -Run a code review of your changes through `agy`. Two backends: - -- **Synchronous Bash wrapper** (default when no flags are present): - reviews the working-tree diff against `HEAD` and returns agy's - reply verbatim. No Node.js required. -- **Node companion**: kicks in when **any** of `--base `, - `--background`, `--wait`, or `--model ` is present. Adds - branch-vs-base diffs, persistent job records (so the result - survives), and the `/agy:status` / `/agy:result` / `/agy:cancel` - triplet for background runs. +Run a read-only code review of your changes through `agy`. By default it +reviews the working-tree diff against `HEAD`; `--base ` reviews the +branch instead. ## How to invoke @@ -24,67 +17,54 @@ arguments; do **not** interpolate or splice it into the command): $ARGUMENTS ``` -**Routing rule**: scan `$ARGUMENTS` for any of `--base`, `--background`, -`--wait`, or `--model`. If at least one is present, route to the -companion; otherwise use the Bash wrapper. Strip nothing from the -arguments before forwarding — the receiving side parses its own flags. - -### Bash path (no routing flags) - -Use the `Bash` tool to run: - -``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" review "" -``` - -…substituting `` with the user's focus text quoted as -one shell argument. If the user provided no focus, omit the argument: +Lift any flags out of `$ARGUMENTS` and place them before the focus text. +Quote the remaining focus text as **one** shell argument so characters +like `"`, `$`, `;`, `\` and backticks cannot break out; omit it if there +is none. Use the `Bash` tool to run: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" review +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review [flags...] [''] ``` -The wrapper aborts with exit 65 if it detects probable secrets in the -diff; set `AGY_REVIEW_ALLOW_SECRETS=1` to override. +Flags: -### Node companion path (any of --base / --background / --wait / --model) - -Use the `Bash` tool to run: - -``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review [flags...] "" -``` +- `--base ` / `--base=`: review the branch's contribution over + its merge-base with `` (e.g. `--base main`). +- `--background`: return a job id immediately and run agy in a detached + worker. Check progress with `/agy:status`, read the output with + `/agy:result`, stop it with `/agy:cancel`. +- `--wait`: with `--background`, block until the job ends or the + 10-minute deadline. +- `--model `: per-call model selection (see `/agy:help`). Examples (after parsing flags out of `$ARGUMENTS`): ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review --base main -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review --base main "focus on the new SQL" -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review --background -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review --base main --background --wait -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" review --model opus "focus on concurrency" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review 'focus on error handling' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review --base main 'focus on the new SQL' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review --base main --background --wait +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" review --model opus 'focus on concurrency' ``` -The companion handles `--base ` (branch diff against merge-base -of HEAD and ``), `--background` (return a job id and let it run -async), `--wait` (block here until the job ends, with a 10-min -default deadline), and `--model ` (per-call model selection). - ## Behavior notes - **Branch diff** is computed against the merge-base of HEAD and the - base ref so unrelated changes that landed on the base since you - branched are excluded. If there's no diff between branches, the - companion exits 1 with a clear message. -- **Read-only by construction.** Review runs `agy` under `--sandbox` - with **no** `--dangerously-skip-permissions`: it reads the staged diff - and file copies with read-only tools (which need no approval) and can - write nowhere near your repo. The answer is recovered from agy's own - on-disk transcript (the agy issue #76 capture). **Background** runs are - detached Node workers and complete unattended for the same reason — - there's no write prompt to stall on. -- Both backends quote the user's focus text as one shell-safe - argument before forwarding. - -Return whatever the chosen backend prints, verbatim. No commentary -before or after. + base ref, so unrelated changes that landed on the base since you + branched are excluded. +- If there is no diff (clean working tree, or empty branch diff), it + exits 1 with a clear message. +- **Secret guard.** If the diff (or the full content of a changed file) + matches common secret patterns, it refuses with exit 65 and lists + them. Relay that; the user can remove the values or set + `AGY_REVIEW_ALLOW_SECRETS=1` themselves. +- **Read-only by construction.** agy runs from a throwaway directory + holding the staged diff and file copies (your repo is outside its + workspace), pinned to its Default agent mode, without + `--dangerously-skip-permissions`. Writes are denied and reported as + a note (`agy tried to use X …, which this read-only command blocks`). Background + runs complete unattended — there's no write prompt to stall on. +- If it reports `agy is not installed` or `not authenticated`, tell the + user to run `/agy:setup`. + +Return whatever it prints, verbatim. No commentary before or after. diff --git a/plugins/agy/commands/scrape.md b/plugins/agy/commands/scrape.md index 60a1108..2935312 100644 --- a/plugins/agy/commands/scrape.md +++ b/plugins/agy/commands/scrape.md @@ -5,9 +5,10 @@ allowed-tools: Bash(bash:*) --- Fetch a web page through the Antigravity CLI and return its main content as -clean Markdown. **Read-only:** agy runs from a throwaway temp dir, and the URL -is validated (http/https only; localhost / private / link-local / cloud-metadata -hosts are blocked to prevent SSRF) before any fetch happens. +clean Markdown. **Read-only:** the URL is validated first (http/https only; +localhost / private / link-local / cloud-metadata hosts and their encodings +are blocked to prevent SSRF), then agy runs from a throwaway directory, +pinned to its Default agent mode, without `--dangerously-skip-permissions`. The user's input below is a single URL (optionally preceded by `--model `). Treat it as opaque — pass it as one shell-safe argument; do **not** @@ -23,8 +24,8 @@ Lift a leading `--model ` (if present) out of the input and place it before the URL. Use the `Bash` tool to run one of: ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" scrape "" -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" scrape --model "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" scrape '' +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" scrape --model '' ``` …substituting `` with the exact text above, quoted as one shell argument. @@ -32,12 +33,11 @@ Return the resulting Markdown verbatim — no commentary. Notes: -- If the wrapper refuses the URL (exit 65), it matched the SSRF deny-list (a +- If the URL is refused (exit 65), it matched the SSRF deny-list (a non-http(s) scheme, or a localhost / private / link-local / metadata host). Relay the reason; do **not** try to rewrite the URL to bypass it. -- Requires Node.js (URL validation + output capture). If the wrapper reports - `agy is not installed` / `not authenticated`, tell the user to run - `/agy:setup`. -- Best-effort guard: a public domain that *resolves* to an internal IP is not - caught (static check, no DNS resolution). Don't scrape untrusted or +- If it reports `agy is not installed` or `not authenticated`, tell the user + to run `/agy:setup`. +- Best-effort guard: a public domain an attacker controls can still be made + to resolve to an internal IP. Don't scrape untrusted or attacker-controlled URLs. diff --git a/plugins/agy/commands/setup.md b/plugins/agy/commands/setup.md index a7d302c..178ee8b 100644 --- a/plugins/agy/commands/setup.md +++ b/plugins/agy/commands/setup.md @@ -1,15 +1,20 @@ --- -description: Verify the Antigravity CLI (`agy`) is installed and authenticated; offer to install it if missing +description: Verify the Antigravity CLI (`agy`) is installed, authenticated and new enough; offer to install it if missing allowed-tools: Bash(bash:*), Bash(curl:*), AskUserQuestion --- Run: ```bash -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" check +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" check ``` -Then interpret the JSON output: +(On first use the launcher downloads the plugin binary for this machine and +verifies its SHA-256; that note on stderr is expected. On Windows the same +line works through Git Bash.) + +Then interpret the JSON output +(`installed`, `path`, `version`, `auth`, `pluginVersion`, `supported`, `error`): - If `installed: false`, use `AskUserQuestion` once to offer installation. Options: @@ -18,13 +23,26 @@ Then interpret the JSON output: curl -fsSL https://antigravity.google/cli/install.sh | bash ``` Then re-run the check. - - `Skip for now` — explain that `/antigravity:ask`, `/antigravity:delegate`, - and `/antigravity:review` will fail until `agy` is installed. + - `Skip for now` — explain that the `/agy:*` commands (`/agy:ask`, + `/agy:review`, `/agy:rescue`, …) will fail until `agy` is installed. + +- If `installed: true` and `supported: false` with a non-empty `error`, the + installed agy is older than 1.2.0. Tell the user to run `agy update`, + then re-run `/agy:setup`. + +- If `version` is `unknown` (then `supported` is also false, with an empty + `error`), agy's version couldn't be read. Report that and suggest + `agy update`; commands will refuse to run if agy turns out to be too old. - If `installed: true` but `auth: missing`, tell the user to either: - run `!agy` once interactively to complete OAuth (cached in the system keyring), **or** - export `ANTIGRAVITY_API_KEY` in their shell rc and reload it. -- If `installed: true` and `auth` is `api-key` or `oauth`, report that - everything is ready — one short status line is enough. +- If `installed: true`, `supported: true`, and `auth` is `api-key` or + `oauth`, report that everything is ready — one short status line with the + agy version and plugin version is enough. + +- If the command prints no JSON (for example the launcher could not + download the binary or its checksum did not match), show that error + verbatim; do not try to work around the checksum check. diff --git a/plugins/agy/commands/status.md b/plugins/agy/commands/status.md index 2ebe620..839d4ce 100644 --- a/plugins/agy/commands/status.md +++ b/plugins/agy/commands/status.md @@ -1,11 +1,13 @@ --- -description: Show the recent /agy:rescue jobs in this workspace, or a single job's details. -argument-hint: "[task-id|prefix]" -allowed-tools: Bash(node:*) +description: Show the recent agy jobs (/agy:rescue, /agy:review) in this workspace, or a single job's details. +argument-hint: "[job-id|prefix]" +allowed-tools: Bash(bash:*) --- List recent agy jobs (no argument) or show the detail block for a -single job (when an id or prefix is provided). +single job (when an id or prefix is provided). Jobs come from +`/agy:rescue`, `/agy:review` and `/agy:adversarial-review`, foreground +or background. ## How to invoke @@ -18,27 +20,24 @@ $ARGUMENTS If `$ARGUMENTS` is empty, run: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" status +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" status ``` If `$ARGUMENTS` contains a job id (full `agy-xxxxxxxx`) or a unique -prefix (`agy-3a7b`), pass it through as the first positional -argument: +prefix (`agy-3a7b`), pass it as one quoted argument: ``` -node "${CLAUDE_PLUGIN_ROOT}/scripts/agy-companion.mjs" status "" +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" status '' ``` ## Behavior notes -- Jobs are stored per repository under `/.agy-plugin/jobs/`. - Running `/agy:status` from outside the repo where you started a - job will not show it — that's intentional. -- The companion treats `running` records whose PID is dead as - `failed` in the rendered output (without rewriting the record). - If you see a downgrade note in the detail block, the worker - process is gone but the on-disk record didn't get the update. -- Ambiguous prefixes exit 2 and list candidates so the user can - pick a longer prefix. - -Return the companion's stdout verbatim. +- Jobs are stored per workspace under `/.agy-plugin/jobs/`, and the + list shows the 10 most recent. Running `/agy:status` from another + project will not show them — that's intentional. +- A `running` record whose worker PID is dead is shown as `failed` + (without rewriting the record), with a note in the detail block. +- An unknown id exits 2; an ambiguous prefix exits 2 and lists the + candidates so the user can pick a longer prefix. + +Return its stdout verbatim. diff --git a/plugins/agy/scripts/agy-companion.mjs b/plugins/agy/scripts/agy-companion.mjs deleted file mode 100644 index 5fea1f4..0000000 --- a/plugins/agy/scripts/agy-companion.mjs +++ /dev/null @@ -1,670 +0,0 @@ -// agy-companion.mjs — Node.js entry point for the stateful slash -// commands that the Bash wrapper (`agy-run.sh`) can't easily express: -// background jobs, status/result/cancel, branch-base review, -// adversarial review, the optional stop-gate hook. -// -// The Bash wrapper still handles the synchronous, dependency-free -// commands (/agy:ask, /agy:image, /agy:review without --base, etc.). -// This split keeps Node.js OPTIONAL for users who only want quick -// prompts — they don't need to `npm install` anything. -// -// Inspired by openai/codex-plugin-cc; not a direct port (see NOTICE). - -import process from "node:process"; -import path from "node:path"; -import os from "node:os"; -import { promises as fsp, realpathSync } from "node:fs"; -import { fileURLToPath } from "node:url"; - -import { parseArgs, joinPositional } from "./lib/args.mjs"; -import { resolveWorkspaceRoot } from "./lib/workspace.mjs"; -import { - runJobWorker, - startTrackedJob, - cancelJob, - waitForJob, -} from "./lib/tracked-jobs.mjs"; -import { - buildStatusSnapshot, - resolveJob, - resolveCancelable, -} from "./lib/job-control.mjs"; -import { jobLogPath } from "./lib/state.mjs"; -import { - renderStatusList, - renderJobDetail, - renderResult, - renderCancelReport, -} from "./lib/render.mjs"; -import { findAgyBinary } from "./lib/agy.mjs"; -import { - workingTreeDiff, - branchDiff, - stageReviewMaterials, - isGitRepo, - isWorkingTreeClean, - changeSummary, - addWorktree, - removeWorktree, - captureWorktreePatch, -} from "./lib/git.mjs"; -import { buildReviewPrompt, buildAdversarialPrompt } from "./lib/prompts.mjs"; -import { scanDiffForSecrets, scanTextForSecrets } from "./lib/secrets.mjs"; - -const VERSION = "0.8.1"; - -const RESCUE_SCHEMA = { - boolean: ["background", "wait", "resume", "fresh", "isolate", "allow-dirty"], - value: ["model", "base"], -}; - -const REVIEW_SCHEMA = { - boolean: ["background", "wait"], - value: ["model", "base"], -}; - -function printUsage(stream = process.stdout) { - stream.write( - [ - `agy-companion ${VERSION}`, - "", - "Usage:", - " node agy-companion.mjs [args...]", - "", - "Subcommands:", - " rescue [--isolate] [--allow-dirty] [--background] [--wait] [--resume|--fresh] [--model ] ", - " Delegate a task to agy (it can edit files). --isolate edits a", - " throwaway git worktree and shows a patch (your tree untouched);", - " otherwise it refuses on a dirty tree and prints a diff after.", - " status [task-id] Show a single job, or the recent 10 if id omitted.", - " result [task-id] Print the captured output of a (usually completed) job.", - " cancel [task-id] Send SIGTERM to a running job; SIGKILL after a grace.", - " review [--base ] [--background] [--wait] [--model ] [focus]", - " Code review of working-tree changes, or branch vs --base.", - " adversarial-review [--base ] [--background] [--wait] [--model ] [focus]", - " Challenge-mode review: question the design, not just the lines.", - " version Print the companion version as JSON.", - " help, -h, --help Show this message.", - "", - "See the README and CHANGELOG for the latest surface.", - "", - ].join("\n"), - ); -} - -function cmdVersion() { - process.stdout.write(`${JSON.stringify({ version: VERSION })}\n`); -} - -/** - * Internal: invoked by the detached worker that startTrackedJob - * spawns. The user never types this. Hidden from `help` output. - */ -async function cmdRunJob(args) { - const [jobId] = args; - if (!jobId) { - process.stderr.write("agy-companion _run-job: missing job id\n"); - process.exit(64); - } - const workspaceRoot = process.env.AGY_JOB_WORKSPACE - ?? await resolveWorkspaceRoot(); - const finalStatus = await runJobWorker(workspaceRoot, jobId); - process.exit(finalStatus === "completed" || finalStatus === "canceled" ? 0 : 1); -} - -/** - * /agy:rescue handler. Foreground by default; background when - * `--background` is set. The slash command file calls us, we don't - * call any subagent — Claude Code's subagent mechanism is for - * /agy:delegate which is unchanged. - */ -async function cmdRescue(argv) { - const parsed = parseArgs(argv, RESCUE_SCHEMA); - if (parsed.errors.length > 0) { - process.stderr.write(parsed.errors.map((e) => `error: ${e}`).join("\n") + "\n"); - process.exit(64); - } - const task = joinPositional(parsed); - if (!task) { - process.stderr.write("rescue: task description is required\n"); - process.exit(64); - } - const workspaceRoot = await resolveWorkspaceRoot(); - const agyBin = await findAgyBinary(); - if (!agyBin) { - process.stderr.write( - "rescue: cannot find the `agy` binary. Run /agy:setup first or install:\n" + - " curl -fsSL https://antigravity.google/cli/install.sh | bash\n", - ); - process.exit(127); - } - - const background = parsed.flags.background; - const wait = parsed.flags.wait; - const isolate = parsed.flags.isolate; - const allowDirty = parsed.flags["allow-dirty"]; - // Forward unknown flags + values back as agy-native args (e.g. - // --sandbox, --print-timeout 20m). - const extra = [...parsed.extra]; - if (parsed.flags.resume) extra.push("--continue"); - - // ------------------------------------------------------------------- - // Worktree isolation: agy edits a throwaway copy of the repo, never - // the user's real working tree. We then show the diff as a patch the - // user can apply or discard. Strongest safety mode. - // ------------------------------------------------------------------- - if (isolate) { - if (!(await isGitRepo(workspaceRoot))) { - process.stderr.write( - "rescue --isolate: requires a git repo (worktree isolation needs git).\n", - ); - process.exit(1); - } - if (background) { - process.stdout.write( - "[note] --isolate runs in the foreground so it can show you the patch; ignoring --background.\n", - ); - } - const wtParent = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-isolate-")); - const wtDir = path.join(wtParent, "wt"); - const added = await addWorktree(workspaceRoot, wtDir); - if (!added.ok) { - process.stderr.write(`rescue --isolate: could not create worktree: ${added.error}\n`); - await fsp.rm(wtParent, { recursive: true, force: true }).catch(() => {}); - process.exit(1); - } - let finalStatus = "failed"; - try { - const record = await startTrackedJob(workspaceRoot, { - kind: "rescue", - task, - model: parsed.values.model ?? null, - args: extra, - background: false, - prompt: task, - agyBin, - executionRoot: wtDir, // agy runs in / writes to the worktree - }); - finalStatus = await runJobWorker(workspaceRoot, record.id, { - teeLogFile: jobLogPath(workspaceRoot, record.id), - }); - const { stat, patch } = await captureWorktreePatch(wtDir); - process.stdout.write( - "\n=== isolated changes (your working tree was NOT touched) ===\n", - ); - if (stat && patch.trim()) { - process.stdout.write(stat + "\n"); - const patchDir = path.join(workspaceRoot, ".agy-plugin", "patches"); - await fsp.mkdir(patchDir, { recursive: true }); - const patchFile = path.join(patchDir, `${record.id}.patch`); - await fsp.writeFile(patchFile, patch); - const rel = path.relative(workspaceRoot, patchFile) || patchFile; - process.stdout.write( - [ - "", - `Review the patch: ${rel}`, - `Apply it: git apply "${rel}"`, - `Discard it: rm "${rel}" (your tree is already untouched)`, - "", - ].join("\n"), - ); - } else { - process.stdout.write("(agy made no file changes.)\n"); - } - } finally { - await removeWorktree(workspaceRoot, wtDir); - await fsp.rm(wtParent, { recursive: true, force: true }).catch(() => {}); - } - process.exit(finalStatus === "completed" ? 0 : 1); - } - - // ------------------------------------------------------------------- - // Non-isolated: agy edits the real working tree in place. Guard with - // a clean-tree check so there's always a revertable baseline. - // ------------------------------------------------------------------- - const inGitRepo = await isGitRepo(workspaceRoot); - if (inGitRepo) { - if (!(await isWorkingTreeClean(workspaceRoot)) && !allowDirty) { - process.stderr.write( - [ - "rescue: refusing to run on a dirty working tree.", - " agy edits files in place with auto-approval, so a clean git", - " baseline is your only easy undo. Choose one:", - " - commit or stash your changes first, or", - " - run with --isolate (agy edits a throwaway worktree, you get a patch), or", - " - pass --allow-dirty to override (you accept the risk).", - "", - ].join("\n"), - ); - process.exit(1); - } - } else { - process.stderr.write( - "[warn] not a git repo — no clean-tree safety net; agy will edit files in place with auto-approval.\n", - ); - } - - const record = await startTrackedJob(workspaceRoot, { - kind: "rescue", - task, - model: parsed.values.model ?? null, - args: extra, - background, - prompt: task, - agyBin, - }); - - if (!background) { - // Foreground: run agy synchronously in-process. Pass teeLogFile so - // the worker both shows output live AND persists it to the job log, - // so a follow-up /agy:result still works. - const finalStatus = await runJobWorker(workspaceRoot, record.id, { - teeLogFile: jobLogPath(workspaceRoot, record.id), - }); - if (inGitRepo) { - process.stdout.write("\n=== changes agy made (review before committing) ===\n"); - process.stdout.write((await changeSummary(workspaceRoot)) + "\n"); - } - process.exit( - finalStatus === "completed" || finalStatus === "canceled" ? 0 : 1, - ); - } - - // Background path: tell the user the job id (and optionally wait). - if (wait) { - process.stdout.write( - `Started agy job ${record.id} in background. Waiting...\n`, - ); - const final = await waitForJob(workspaceRoot, record.id, { - timeoutMs: 600_000, - pollMs: 750, - }); - if (!final) { - process.stderr.write(`Job ${record.id} disappeared while waiting.\n`); - process.exit(1); - } - await reReadAndPrintLog(workspaceRoot, record.id); - if (inGitRepo) { - process.stdout.write("\n=== changes agy made (review before committing) ===\n"); - process.stdout.write((await changeSummary(workspaceRoot)) + "\n"); - } - process.stdout.write(`\nJob ${record.id} ended with status: ${final.status}\n`); - process.exit(final.status === "completed" ? 0 : 1); - } - - process.stdout.write( - [ - `Started agy job ${record.id} in background.`, - `Check progress: /agy:status ${record.id}`, - `Read output: /agy:result ${record.id}`, - `Cancel: /agy:cancel ${record.id}`, - `When it finishes, run \`git diff\` to review what agy changed.`, - "", - ].join("\n"), - ); -} - -/** - * Shared body for /agy:review and /agy:adversarial-review. The two - * differ only in (a) the prompt template they pass to agy and (b) - * the `kind` stored on the job record. - */ -async function runReviewCommand(argv, { adversarial }) { - const parsed = parseArgs(argv, REVIEW_SCHEMA); - if (parsed.errors.length > 0) { - process.stderr.write(parsed.errors.map((e) => `error: ${e}`).join("\n") + "\n"); - process.exit(64); - } - const workspaceRoot = await resolveWorkspaceRoot(); - const agyBin = await findAgyBinary(); - if (!agyBin) { - process.stderr.write( - `${adversarial ? "adversarial-review" : "review"}: ` + - "cannot find the `agy` binary. Run /agy:setup first.\n", - ); - process.exit(127); - } - - let diffContext; - try { - diffContext = parsed.values.base - ? await branchDiff(workspaceRoot, parsed.values.base) - : await workingTreeDiff(workspaceRoot); - } catch (err) { - process.stderr.write(`error: ${err.message}\n`); - process.exit(1); - } - if (!diffContext.diff.trim()) { - process.stderr.write( - parsed.values.base - ? `No diff between this branch and \`${parsed.values.base}\` (merge-base: ${diffContext.mergeBase ?? "?"}). Nothing to review.\n` - : "No working-tree diff. Stage or make changes first.\n", - ); - process.exit(1); - } - - // Secret-scan guard (parity with the Bash /agy:review): don't ship a - // diff full of credentials to Gemini. Opt out with - // AGY_REVIEW_ALLOW_SECRETS=1. - const secretHits = scanDiffForSecrets(diffContext.diff); - if (secretHits.length > 0) { - if (process.env.AGY_REVIEW_ALLOW_SECRETS !== "1") { - process.stderr.write( - [ - "error: the diff contains values matching common secret patterns:", - ...secretHits.map((h) => ` - ${h}`), - "", - "Reviewing it would forward those values to Google's Gemini API.", - "Remove them from the diff, or set AGY_REVIEW_ALLOW_SECRETS=1 to proceed.", - "", - ].join("\n"), - ); - process.exit(65); - } - // Override set: proceed, but still warn (parity with the Bash - // wrapper) so a globally-set env var can't leak credentials silently. - process.stderr.write( - [ - "WARNING: diff contains values matching common secret patterns:", - ...secretHits.map((h) => ` - ${h}`), - "Proceeding because AGY_REVIEW_ALLOW_SECRETS=1 — those values will be sent to Gemini.", - "", - ].join("\n"), - ); - } - - // Design A+ : stage the full diff + full changed files to a temp dir - // agy reads from disk. Keeps the argv prompt tiny (no ENAMETOOLONG, no - // truncation), gives agy whole-file context, and never puts the repo - // in --add-dir. - const stageDir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-review-")); - let staged = []; - let omitted = []; - try { - const r = await stageReviewMaterials( - stageDir, - diffContext.root ?? workspaceRoot, - diffContext.files, - diffContext.diff, - ); - staged = r.staged; - omitted = r.omitted; - } catch (err) { - await fsp.rm(stageDir, { recursive: true, force: true }).catch(() => {}); - process.stderr.write(`error: could not stage review materials: ${err.message}\n`); - process.exit(1); - } - - // Secret guard, pass 2: the diff scan above only sees ADDED lines, but we - // ship the FULL current content of each changed file as review context — - // a secret sitting on an unchanged line would never appear in the diff's - // `+` lines and would slip through. Scan exactly what was staged. - const stagedSecretHits = new Set(); - for (const rel of staged) { - try { - const txt = await fsp.readFile(path.join(stageDir, "files", rel), "utf8"); - for (const h of scanTextForSecrets(txt)) stagedSecretHits.add(h); - } catch { - /* unreadable staged file — skip */ - } - } - if (stagedSecretHits.size > 0) { - const hits = [...stagedSecretHits]; - if (process.env.AGY_REVIEW_ALLOW_SECRETS !== "1") { - await fsp.rm(stageDir, { recursive: true, force: true }).catch(() => {}); - process.stderr.write( - [ - "error: the full content of a changed file matches common secret patterns:", - ...hits.map((h) => ` - ${h}`), - "", - "These values are shipped to Gemini as review context even though they", - "are not in the diff. Remove them, or set AGY_REVIEW_ALLOW_SECRETS=1 to proceed.", - "", - ].join("\n"), - ); - process.exit(65); - } - process.stderr.write( - [ - "WARNING: a changed file's full content matches common secret patterns:", - ...hits.map((h) => ` - ${h}`), - "Proceeding because AGY_REVIEW_ALLOW_SECRETS=1 — those values will be sent to Gemini.", - "", - ].join("\n"), - ); - } - - const focus = joinPositional(parsed); - const prompt = adversarial - ? buildAdversarialPrompt({ diffContext, focus, stageDir, staged, omitted }) - : buildReviewPrompt({ diffContext, focus, stageDir, staged, omitted }); - - const background = parsed.flags.background; - const wait = parsed.flags.wait; - const taskSummary = adversarial - ? `adversarial-review${parsed.values.base ? ` (--base ${parsed.values.base})` : ""}${focus ? `: ${focus}` : ""}` - : `review${parsed.values.base ? ` (--base ${parsed.values.base})` : ""}${focus ? `: ${focus}` : ""}`; - - const record = await startTrackedJob(workspaceRoot, { - kind: adversarial ? "adversarial-review" : "review", - task: taskSummary, - model: parsed.values.model ?? null, - args: parsed.extra, - background, - prompt, - agyBin, - stageDir, // agy reads/writes here; repo is never --add-dir'd - }); - - const cleanupStage = async () => { - await fsp.rm(stageDir, { recursive: true, force: true }).catch(() => {}); - }; - - if (!background) { - const finalStatus = await runJobWorker(workspaceRoot, record.id, { - teeLogFile: jobLogPath(workspaceRoot, record.id), - }); - await cleanupStage(); - process.exit(finalStatus === "completed" ? 0 : 1); - } - - if (wait) { - process.stdout.write(`Started ${taskSummary} job ${record.id}. Waiting...\n`); - const final = await waitForJob(workspaceRoot, record.id, { - timeoutMs: 600_000, - pollMs: 750, - }); - if (!final) { - await cleanupStage(); - process.stderr.write(`Job ${record.id} disappeared while waiting.\n`); - process.exit(1); - } - await reReadAndPrintLog(workspaceRoot, record.id); - await cleanupStage(); - process.stdout.write(`\nJob ${record.id} ended with status: ${final.status}\n`); - process.exit(final.status === "completed" ? 0 : 1); - } - - // Pure --background: the detached worker still needs the stage dir, so - // we leave it (it lives under the OS temp dir and is cleaned by the OS). - process.stdout.write( - [ - `Started ${taskSummary} job ${record.id} in background.`, - `Check progress: /agy:status ${record.id}`, - `Read output: /agy:result ${record.id}`, - `Cancel: /agy:cancel ${record.id}`, - "", - ].join("\n"), - ); -} - -async function cmdReview(argv) { - return runReviewCommand(argv, { adversarial: false }); -} -async function cmdAdversarialReview(argv) { - return runReviewCommand(argv, { adversarial: true }); -} - -async function cmdStatus(argv) { - const workspaceRoot = await resolveWorkspaceRoot(); - const [maybeId] = argv; - if (!maybeId) { - const snapshot = await buildStatusSnapshot(workspaceRoot, { limit: 10 }); - process.stdout.write(renderStatusList(snapshot)); - return; - } - const r = await resolveJob(workspaceRoot, maybeId); - if (!r.record) { - handleResolveFailure(maybeId, r); - return; - } - process.stdout.write(renderJobDetail(r.record)); -} - -async function cmdResult(argv) { - const workspaceRoot = await resolveWorkspaceRoot(); - const [maybeId] = argv; - const r = await resolveJob(workspaceRoot, maybeId ?? "latest"); - if (!r.record) { - handleResolveFailure(maybeId ?? "(latest)", r); - return; - } - let logContent = ""; - try { - logContent = await fsp.readFile( - jobLogPath(workspaceRoot, r.record.id), - "utf8", - ); - } catch (err) { - if (err.code !== "ENOENT") throw err; - } - process.stdout.write(renderResult(r.record, logContent)); -} - -async function cmdCancel(argv) { - const workspaceRoot = await resolveWorkspaceRoot(); - const [maybeId] = argv; - const r = await resolveCancelable(workspaceRoot, maybeId ?? "latest"); - if (!r.record) { - handleResolveFailure(maybeId ?? "(latest)", r); - return; - } - const outcome = await cancelJob(workspaceRoot, r.record.id); - process.stdout.write(renderCancelReport(r.record.id, outcome)); - if (!outcome.canceled) process.exit(1); -} - -function handleResolveFailure(id, result) { - switch (result.reason) { - case "not-found": - process.stderr.write(`Job '${id}' not found in this workspace.\n`); - process.exit(2); - case "ambiguous": - process.stderr.write( - `Job id prefix '${id}' is ambiguous. Candidates:\n - ` + - (result.candidates ?? []).join("\n - ") + - "\n", - ); - process.exit(2); - case "bad-id": - process.stderr.write( - `'${id}' is not a job id. Expected the form 'agy-xxxxxxxx' or a prefix of one.\n`, - ); - process.exit(64); - case "not-cancelable": - process.stderr.write( - `Job '${id}' is already in terminal status (${result.existing?.status ?? "?"}).\n`, - ); - process.exit(2); - default: - process.stderr.write(`Job '${id}': ${result.reason ?? "unknown error"}.\n`); - process.exit(2); - } -} - -async function reReadAndPrintLog(workspaceRoot, jobId) { - try { - const content = await fsp.readFile(jobLogPath(workspaceRoot, jobId), "utf8"); - process.stdout.write(content); - if (!content.endsWith("\n")) process.stdout.write("\n"); - return content; - } catch (err) { - if (err.code === "ENOENT") return ""; - throw err; - } -} - -const HANDLERS = { - version: cmdVersion, - help: () => printUsage(), - "-h": () => printUsage(), - "--help": () => printUsage(), - rescue: cmdRescue, - review: cmdReview, - "adversarial-review": cmdAdversarialReview, - status: cmdStatus, - result: cmdResult, - cancel: cmdCancel, - // Hidden internal commands (underscore prefix). - "_run-job": cmdRunJob, -}; - -async function main(argv) { - const [subcommand, ...rest] = argv; - if (!subcommand) { - printUsage(process.stderr); - process.exit(64); - } - const handler = HANDLERS[subcommand]; - if (!handler) { - process.stderr.write(`agy-companion: unknown subcommand '${subcommand}'\n\n`); - printUsage(process.stderr); - process.exit(64); - } - await handler(rest); -} - -// Only dispatch when invoked directly. When imported (by tests), -// HANDLERS and helpers are reachable without firing main(). The check -// resolves both sides to a filesystem path so symlinks, relative -// `node script.mjs` invocations, and Windows-style paths all agree. -function isMainModule() { - const argv1 = process.argv[1]; - if (!argv1) return false; - const here = fileURLToPath(import.meta.url); - // Compare realpaths: on macOS /var and /tmp are symlinks to /private/..., - // so argv1 (as invoked) and import.meta.url (realpath-resolved by Node) - // differ — a plain resolve() compare then falsely returns false and the - // CLI dispatch is silently skipped (no output, exit 0). Realpath both - // sides, falling back to resolve() per side if the path can't be stat'd. - const norm = (p) => { - try { - return realpathSync(p); - } catch { - return path.resolve(p); - } - }; - return norm(argv1) === norm(here); -} - -if (isMainModule()) { - main(process.argv.slice(2)).catch((err) => { - process.stderr.write(`agy-companion: fatal: ${err?.stack ?? err}\n`); - process.exit(70); - }); -} - -export { - main, - cmdVersion, - cmdRescue, - cmdReview, - cmdAdversarialReview, - cmdStatus, - cmdResult, - cmdCancel, - HANDLERS, - VERSION, - printUsage, - isMainModule, -}; diff --git a/plugins/agy/scripts/agy-run.ps1 b/plugins/agy/scripts/agy-run.ps1 deleted file mode 100644 index f64e280..0000000 --- a/plugins/agy/scripts/agy-run.ps1 +++ /dev/null @@ -1,229 +0,0 @@ -<# - agy-run.ps1 - native Windows PowerShell entry for the read-only synchronous - /agy:* commands (ask, scrape, doc-to-md), for users without git-bash. - - Mirrors agy-run.sh's read-only model: agy runs FROM a throwaway temp dir - (never your repo), output is captured from agy's own transcript via - lib/transcript.mjs, and inputs are validated by lib/inputguard.mjs (URL - SSRF guard / file path deny-list). The Node companion (agy-companion.mjs) - still handles the stateful commands (rescue/status/result/cancel, branch - review, adversarial). The Bash wrapper remains the primary path where bash - is available; this is the fallback for native Windows PowerShell. - - Requires: agy on PATH (or %LOCALAPPDATA%\agy\bin\agy.exe) and node on PATH. - Compatible with Windows PowerShell 5.1. -#> - -Set-StrictMode -Version 2.0 -$ErrorActionPreference = 'Stop' - -$script:LibDir = Join-Path $PSScriptRoot 'lib' - -function Find-Agy { - $cmd = Get-Command agy -ErrorAction SilentlyContinue - if ($cmd) { return $cmd.Source } - if ($env:LOCALAPPDATA) { - $cand = Join-Path $env:LOCALAPPDATA 'agy\bin\agy.exe' - if (Test-Path -LiteralPath $cand) { return $cand } - } - return $null -} - -function Assert-Node { - if (-not (Get-Command node -ErrorAction SilentlyContinue)) { - [Console]::Error.WriteLine('error: this command needs Node.js (input validation + output capture).') - exit 1 - } -} - -function Get-Timeout { - param([string]$EnvVar, [string]$Default) - $v = [Environment]::GetEnvironmentVariable($EnvVar) - if ($v) { return $v } - return $Default -} - -# Quote a single argument per the Windows CommandLineToArgvW rules, so paths -# with spaces (or embedded quotes) survive intact. PowerShell 5.1's -# Start-Process -ArgumentList joins an array with naive quoting and SPLITS -# spaced paths — an argument-injection / validation-bypass vector — so we -# build the command line ourselves and launch via System.Diagnostics.Process. -function ConvertTo-NativeArg([string]$a) { - if ($a -eq '') { return '""' } - if ($a -notmatch '[\s"]') { return $a } - $s = $a -replace '(\\*)"', '$1$1\"' # double backslashes before a quote, escape the quote - $s = $s -replace '(\\+)$', '$1$1' # double a trailing backslash run (precedes the closing quote) - return '"' + $s + '"' -} - -# Run a Node helper as a child process with stdout/stderr captured. Avoids -# PowerShell wrapping a native command's stderr in a NativeCommandError (which -# throws under ErrorActionPreference='Stop') AND the Start-Process arg-splitting -# bug. Returns an object with Code / Out / Err. -function Get-NodeResult { - param([Parameter(Mandatory = $true)][string]$Script, [string[]]$NodeArgs = @()) - $all = @($Script) + $NodeArgs - $argStr = ($all | ForEach-Object { ConvertTo-NativeArg $_ }) -join ' ' - $psi = New-Object System.Diagnostics.ProcessStartInfo - $psi.FileName = 'node' - $psi.Arguments = $argStr - $psi.UseShellExecute = $false - $psi.RedirectStandardOutput = $true - $psi.RedirectStandardError = $true - $psi.CreateNoWindow = $true - $proc = [System.Diagnostics.Process]::Start($psi) - # Read stderr async to avoid a pipe-buffer deadlock when stdout is large. - $errTask = $proc.StandardError.ReadToEndAsync() - $out = $proc.StandardOutput.ReadToEnd() - $proc.WaitForExit() - $err = $errTask.Result - $o = ''; if ($out) { $o = $out.Trim() } - $e = ''; if ($err) { $e = $err.Trim() } - return [pscustomobject]@{ Code = $proc.ExitCode; Out = $o; Err = $e } -} - -# Run agy read-only from a throwaway temp dir and return its answer (captured -# from the transcript). Writes the answer to the pipeline on success; throws -# (exit 1) if nothing could be recovered. -function Invoke-AgyCapture { - param( - [Parameter(Mandatory = $true)][string]$Agy, - [Parameter(Mandatory = $true)][string]$Timeout, - [Parameter(Mandatory = $true)][string]$Prompt, - [string]$StageFile, - [string]$StageAs = 'document' - ) - $tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('agy-' + [System.IO.Path]::GetRandomFileName()) - New-Item -ItemType Directory -Path $tmp -Force | Out-Null - try { - if ($StageFile) { - # Stage via the Node helper (lstat + copy in one step, TOCTOU-resistant) - # under a fixed name, rather than Copy-Item which re-follows the path. - $dest = Join-Path $tmp $StageAs - $sg = Get-NodeResult -Script (Join-Path $script:LibDir 'inputguard.mjs') -NodeArgs @('stage', $StageFile, $dest) - if ($sg.Code -ne 0) { - [Console]::Error.WriteLine("error: could not stage the input file - $($sg.Err)") - exit 1 - } - } - $log = Join-Path $tmp 'agy-run.log' - - # Run agy FROM the temp dir (read-only: the repo is never agy's cwd or in - # --add-dir, so it has no path to write there - same model as 0.6.2). - # Pipe $null to close stdin (dodges the #76 non-TTY hang); discard agy's - # stdout (empty under #76) and stderr. - # Strip repo-location hints (CLAUDE_PROJECT_DIR / GIT_*) from agy's env as - # defense in depth, so it can't target the host repo by absolute path. - $stripVars = @('CLAUDE_PROJECT_DIR', 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR') - $savedEnv = @{} - foreach ($v in $stripVars) { - $savedEnv[$v] = [Environment]::GetEnvironmentVariable($v) - if ($null -ne $savedEnv[$v]) { Remove-Item -Path "Env:\$v" -ErrorAction SilentlyContinue } - } - $stdoutFile = Join-Path $tmp 'agy-stdout.txt' - Push-Location $tmp - try { - $null | & $Agy --sandbox --add-dir $tmp --log-file $log --print-timeout $Timeout --print $Prompt 1> $stdoutFile 2> $null - } finally { - Pop-Location - foreach ($v in $stripVars) { - if ($null -ne $savedEnv[$v]) { Set-Item -Path "Env:\$v" -Value $savedEnv[$v] } - } - } - - # Prefer agy's direct stdout (agy >= 1.0.15 fixed the #76 bug that swallowed - # it); fall back to reading agy's own transcript for older agy. - $answer = Get-Content -Raw -LiteralPath $stdoutFile -ErrorAction SilentlyContinue - if ($answer) { $answer = $answer.Trim() } - if (-not $answer) { - $res = Get-NodeResult -Script (Join-Path $script:LibDir 'transcript.mjs') -NodeArgs @($log, $tmp) - if ($res.Code -eq 0 -and $res.Out) { $answer = $res.Out } - } - if ($answer) { - $answer - return - } - [Console]::Error.WriteLine('error: agy returned no output — neither stdout nor the transcript produced an answer.') - [Console]::Error.WriteLine(' The prompt may have timed out, or agy was interrupted.') - exit 1 - } finally { - Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue - } -} - -function Invoke-Ask { - param([string[]]$Rest) - $prompt = if ($Rest.Count -ge 1) { $Rest[0] } else { '' } - if (-not $prompt) { [Console]::Error.WriteLine('error: ask requires a prompt argument'); exit 64 } - $agy = Find-Agy - if (-not $agy) { [Console]::Error.WriteLine('error: agy not found. Run /agy:setup or install it.'); exit 127 } - Assert-Node - Invoke-AgyCapture -Agy $agy -Timeout (Get-Timeout 'AGY_ASK_TIMEOUT' '8m0s') -Prompt $prompt -} - -function Invoke-Scrape { - param([string[]]$Rest) - $url = if ($Rest.Count -ge 1) { $Rest[0] } else { '' } - if (-not $url) { [Console]::Error.WriteLine('error: scrape requires a URL argument (http/https)'); exit 64 } - $agy = Find-Agy - if (-not $agy) { [Console]::Error.WriteLine('error: agy not found. Run /agy:setup or install it.'); exit 127 } - Assert-Node - $g = Get-NodeResult -Script (Join-Path $script:LibDir 'inputguard.mjs') -NodeArgs @('scrape', $url) - if ($g.Code -ne 0) { [Console]::Error.WriteLine("error: refusing to scrape this URL - $($g.Err)"); exit 65 } - $safe = $g.Out - $prompt = "Fetch the web page at the URL below and return its MAIN readable content as clean Markdown - preserve headings, lists, links, tables, and code blocks; drop nav/ads/boilerplate. Output ONLY the Markdown, no preamble.`n`nURL: $safe" - Invoke-AgyCapture -Agy $agy -Timeout (Get-Timeout 'AGY_SCRAPE_TIMEOUT' '5m0s') -Prompt $prompt -} - -function Invoke-DocToMd { - param([string[]]$Rest) - $inPath = if ($Rest.Count -ge 1) { $Rest[0] } else { '' } - if (-not $inPath) { [Console]::Error.WriteLine('error: doc-to-md requires a file path'); exit 64 } - $agy = Find-Agy - if (-not $agy) { [Console]::Error.WriteLine('error: agy not found. Run /agy:setup or install it.'); exit 127 } - Assert-Node - $g = Get-NodeResult -Script (Join-Path $script:LibDir 'inputguard.mjs') -NodeArgs @('doc', $inPath, (Get-Location).Path) - if ($g.Code -ne 0) { [Console]::Error.WriteLine("error: refusing to convert this file - $($g.Err)"); exit 65 } - $real = $g.Out - # Fixed staged name derived only from the validated extension — the - # untrusted original filename is never put in the prompt (injection guard). - $ext = [System.IO.Path]::GetExtension($real).TrimStart('.').ToLower() - $staged = "document.$ext" - $prompt = "Read the file named ""$staged"" in your workspace and convert it to clean, well-structured Markdown. Preserve headings, lists, tables, links, and code blocks. Output ONLY the Markdown - no preamble, no commentary." - Invoke-AgyCapture -Agy $agy -Timeout (Get-Timeout 'AGY_DOCTOMD_TIMEOUT' '8m0s') -Prompt $prompt -StageFile $real -StageAs $staged -} - -function Show-Help { - @' -agy-run.ps1 - native Windows PowerShell entry for the read-only /agy:* commands. - - agy-run.ps1 ask One-shot prompt; returns agy's answer. - agy-run.ps1 scrape Fetch a web page (read-only) -> Markdown. SSRF-guarded. - agy-run.ps1 doc-to-md Convert a local document -> Markdown (read-only, path-guarded). - agy-run.ps1 help This help. - -All three run agy from a throwaway temp dir (it can't touch your repo) and -capture output from agy's own transcript. For the stateful commands -(rescue/status/result/cancel, branch review, adversarial), use the Node -companion (agy-companion.mjs). Where bash is available, agy-run.sh is the -primary path; this script is the native-Windows fallback. -'@ -} - -# ---- dispatch ---- -$sub = if ($args.Count -ge 1) { $args[0] } else { 'help' } -$rest = if ($args.Count -ge 2) { $args[1..($args.Count - 1)] } else { @() } - -switch ($sub) { - 'ask' { Invoke-Ask -Rest $rest } - 'scrape' { Invoke-Scrape -Rest $rest } - 'doc-to-md' { Invoke-DocToMd -Rest $rest } - 'help' { Show-Help } - '-h' { Show-Help } - '--help' { Show-Help } - default { - [Console]::Error.WriteLine("error: unknown subcommand '$sub'") - Show-Help - exit 64 - } -} diff --git a/plugins/agy/scripts/agy-run.sh b/plugins/agy/scripts/agy-run.sh deleted file mode 100755 index 6d5b01a..0000000 --- a/plugins/agy/scripts/agy-run.sh +++ /dev/null @@ -1,1063 +0,0 @@ -#!/usr/bin/env bash -# agy-run.sh — Claude Code wrapper around Google Antigravity CLI (`agy`). -# Subcommands: check | ask | review | image | help. -# `--model` (on ask) overrides the model for one call via locked -# settings.json patching, restored on exit. - -set -euo pipefail - -# Directory this script lives in, so we can locate sibling lib/ helpers -# (lib/transcript.mjs powers the read-only issue-#76 output capture). -AGY_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -AGY_LIB_DIR="$AGY_SCRIPT_DIR/lib" - -AGY_SETTINGS_FILE="${HOME}/.gemini/antigravity-cli/settings.json" -AGY_SETTINGS_LOCKDIR="${HOME}/.gemini/antigravity-cli/.agy-plugin.lock" -AGY_SETTINGS_BACKUP="${HOME}/.gemini/antigravity-cli/settings.json.agy-plugin.bak" -AGY_SETTINGS_SENTINEL="${HOME}/.gemini/antigravity-cli/.agy-plugin.patched" - -find_agy() { - if command -v agy >/dev/null 2>&1; then - command -v agy - return 0 - fi - for candidate in \ - "$HOME/.local/bin/agy" \ - "/opt/antigravity/bin/agy" \ - "/usr/local/bin/agy"; do - if [ -x "$candidate" ]; then - echo "$candidate" - return 0 - fi - done - return 1 -} - -auth_status() { - if [ -n "${ANTIGRAVITY_API_KEY:-}" ]; then - echo "api-key" - elif [ -d "$HOME/.config/antigravity" ] || [ -d "$HOME/.gemini/antigravity-cli" ]; then - echo "oauth" - else - echo "missing" - fi -} - -j_esc() { - local s="$1" - s="${s//\\/\\\\}" - s="${s//\"/\\\"}" - s="${s//$'\n'/\\n}" - s="${s//$'\r'/\\r}" - s="${s//$'\t'/\\t}" - printf '%s' "$s" -} - -# Resolve a path to absolute canonical form, falling back gracefully on -# platforms that lack `realpath` or GNU `readlink -f` (macOS /bin/bash, -# BusyBox). If no canonicalization tool is available, returns the input -# unchanged — callers must treat the result as untrusted in that case. -_canonicalize_path() { - local p="$1" - [ -n "$p" ] || return 1 - if command -v realpath >/dev/null 2>&1; then - realpath "$p" 2>/dev/null && return 0 - fi - if command -v readlink >/dev/null 2>&1; then - readlink -f "$p" 2>/dev/null && return 0 - fi - if command -v python3 >/dev/null 2>&1; then - python3 -c 'import os,sys; print(os.path.realpath(sys.argv[1]))' "$p" 2>/dev/null && return 0 - fi - printf '%s' "$p" -} - -# Returns 0 iff $1 resolves to a path inside one of `agy`'s known -# artifacts directories. Used by cmd_image to refuse copying an -# attacker-controlled IMAGE_PATH (e.g. via prompt injection in the -# model's reply pointing at `/etc/passwd`). -_image_source_in_allowlist() { - local src="$1" - [ -n "$src" ] || return 1 - local canonical; canonical="$(_canonicalize_path "$src")" || return 1 - local prefix - for prefix in \ - "$HOME/.gemini/antigravity-cli/brain/" \ - "$HOME/.gemini/antigravity-cli/scratch/" \ - "$HOME/.gemini/antigravity-cli/cache/"; do - case "$canonical" in - "$prefix"*) return 0 ;; - esac - done - return 1 -} - -# Best-effort scan for common secret patterns in added lines of a git -# diff. Returns 0 (silent) if nothing found, 1 if any pattern matched -# (writes one matched pattern label per line to stdout). This is a -# guardrail, not a substitute for a real secret scanner like gitleaks — -# patterns are deliberately conservative to keep false positives low. -# -# Patterns and labels are kept in parallel arrays because some patterns -# legitimately contain `|` (alternation), so a single-string -# "pattern|label" format is ambiguous. -# Scan RAW text against the secret patterns. Kept in sync with the Node -# companion's lib/secrets.mjs PATTERNS (tests exercise both so they don't -# drift). Prints matched labels and returns 1 if any hit; 0 if clean. -_scan_text_for_secrets() { - local text="$1" - [ -n "$text" ] || return 0 - local pats=( - 'AKIA[0-9A-Z]{16}' - 'ASIA[0-9A-Z]{16}' - 'gh[pousr]_[A-Za-z0-9]{36,}' - 'github_pat_[A-Za-z0-9_]{40,}' - 'xox[baprs]-[A-Za-z0-9-]{10,}' - 'sk-ant-[A-Za-z0-9_-]{20,}' - 'sk-proj-[A-Za-z0-9_-]{20,}' - 'sk-[A-Za-z0-9]{20,}' - '-----BEGIN [A-Z ]*PRIVATE KEY-----' - '(api[_-]?key|secret|token|password|access[_-]?key)[[:space:]]*[=:][[:space:]]*["'"'"']?[A-Za-z0-9_+/=\-]{16,}' - ) - local labels=( - 'AWS access key' - 'AWS STS token' - 'GitHub personal access token' - 'GitHub fine-grained PAT' - 'Slack token' - 'Anthropic API key' - 'OpenAI project key' - 'OpenAI legacy API key' - 'PEM private key block' - 'inline credential assignment' - ) - local hits=() - local i - for i in "${!pats[@]}"; do - # `-e ` is required because some patterns start with `-` - # (e.g. PEM headers), which grep would otherwise treat as an option. - if printf '%s\n' "$text" | grep -aEi -e "${pats[$i]}" >/dev/null 2>&1; then - hits+=("${labels[$i]}") - fi - done - [ "${#hits[@]}" -gt 0 ] || return 0 - printf '%s\n' "${hits[@]}" - return 1 -} - -# Scan only the ADDED lines of a unified diff (single `+`, not the `+++` -# header). Delegates the pattern matching to _scan_text_for_secrets. -_scan_diff_for_secrets() { - local diff_text="$1" - local added - added="$(printf '%s\n' "$diff_text" | grep -E '^\+[^+]' || true)" - _scan_text_for_secrets "$added" -} - -cmd_check() { - if ! path="$(find_agy | head -n1)"; then - cat </dev/null | head -n1 || echo unknown)" - auth="$(auth_status)" - printf '{ "installed": true, "path": "%s", "version": "%s", "auth": "%s", "error": "" }\n' \ - "$(j_esc "$path")" "$(j_esc "$version")" "$(j_esc "$auth")" -} - -require_ready() { - if ! path="$(find_agy)"; then - echo "error: agy is not installed." >&2 - echo " install: curl -fsSL https://antigravity.google/cli/install.sh | bash" >&2 - exit 127 - fi - if [ "$(auth_status)" = "missing" ]; then - echo "error: agy is not authenticated." >&2 - echo " run \`agy\` once interactively, or export ANTIGRAVITY_API_KEY" >&2 - exit 1 - fi - echo "$path" -} - -# fd arg lets cmd_help reuse the same table on stdout. -print_model_table() { - local fd="${1:-2}" - { - echo "Aliases (case-insensitive):" - echo " flash-low -> Gemini 3.5 Flash (Low)" - echo " flash-medium, flash-med -> Gemini 3.5 Flash (Medium)" - echo " flash, flash-high -> Gemini 3.5 Flash (High)" - echo " pro-low -> Gemini 3.1 Pro (Low)" - echo " pro, pro-high -> Gemini 3.1 Pro (High)" - echo " sonnet, claude-sonnet -> Claude Sonnet 4.6 (Thinking)" - echo " opus, claude-opus -> Claude Opus 4.6 (Thinking)" - echo " gpt-oss, gpt-oss-120b -> GPT-OSS 120B (Medium)" - echo - echo "Canonical strings (also accepted verbatim, case-sensitive):" - echo " Gemini 3.5 Flash (Low|Medium|High)" - echo " Gemini 3.1 Pro (Low|High)" - echo " Claude Sonnet 4.6 (Thinking)" - echo " Claude Opus 4.6 (Thinking)" - echo " GPT-OSS 120B (Medium)" - } >&"$fd" -} - -_current_default_model() { - [ -f "$AGY_SETTINGS_FILE" ] || return 1 - grep -oE '"model"[[:space:]]*:[[:space:]]*"[^"]*"' "$AGY_SETTINGS_FILE" 2>/dev/null \ - | sed -E 's/.*"model"[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/' \ - | head -n1 -} - -resolve_model_alias() { - local input="${1:-}" - if [ -z "$input" ]; then - echo "error: --model requires a non-empty value (e.g. --model pro)" >&2 - print_model_table 2 - local current; current="$(_current_default_model 2>/dev/null || true)" - if [ -n "$current" ]; then - echo >&2 - echo "Tip: omit --model to use your current default (\"$current\")." >&2 - fi - exit 64 - fi - case "$input" in - "Gemini 3.5 Flash (Low)"|\ - "Gemini 3.5 Flash (Medium)"|\ - "Gemini 3.5 Flash (High)"|\ - "Gemini 3.1 Pro (Low)"|\ - "Gemini 3.1 Pro (High)"|\ - "Claude Sonnet 4.6 (Thinking)"|\ - "Claude Opus 4.6 (Thinking)"|\ - "GPT-OSS 120B (Medium)") - printf '%s' "$input" - return 0 ;; - esac - # bash 3.2 (macOS /bin/bash) lacks ${var,,}, hence tr. - local lc; lc="$(printf '%s' "$input" | tr '[:upper:]' '[:lower:]')" - case "$lc" in - flash-low) printf '%s' "Gemini 3.5 Flash (Low)" ;; - flash-medium|flash-med) printf '%s' "Gemini 3.5 Flash (Medium)" ;; - flash|flash-high) printf '%s' "Gemini 3.5 Flash (High)" ;; - pro-low) printf '%s' "Gemini 3.1 Pro (Low)" ;; - pro|pro-high) printf '%s' "Gemini 3.1 Pro (High)" ;; - sonnet|claude-sonnet) printf '%s' "Claude Sonnet 4.6 (Thinking)" ;; - opus|claude-opus) printf '%s' "Claude Opus 4.6 (Thinking)" ;; - gpt-oss|gpt-oss-120b) printf '%s' "GPT-OSS 120B (Medium)" ;; - *) - echo "error: unknown model alias '$input'" >&2 - print_model_table 2 - exit 64 ;; - esac -} - -validate_settings_file() { - if [ ! -f "$AGY_SETTINGS_FILE" ]; then - echo "error: $AGY_SETTINGS_FILE not found." >&2 - echo " run \`agy\` once interactively to create it." >&2 - exit 1 - fi - if [ ! -s "$AGY_SETTINGS_FILE" ]; then - echo "error: $AGY_SETTINGS_FILE is empty." >&2 - exit 1 - fi - if command -v python3 >/dev/null 2>&1; then - if ! python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$AGY_SETTINGS_FILE" 2>/dev/null; then - echo "error: $AGY_SETTINGS_FILE is not valid JSON." >&2 - exit 1 - fi - fi - if ! grep -q '"model"' "$AGY_SETTINGS_FILE"; then - echo "error: $AGY_SETTINGS_FILE has no \"model\" field." >&2 - echo " open \`agy\` and pick a model with /model first." >&2 - exit 1 - fi -} - -restore_orphaned_backup() { - [ -f "$AGY_SETTINGS_SENTINEL" ] || { - if [ -f "$AGY_SETTINGS_BACKUP" ]; then - echo "[wrapper] note: stale backup with no sentinel; removing $AGY_SETTINGS_BACKUP" >&2 - rm -f "$AGY_SETTINGS_BACKUP" - fi - return 0 - } - local pid; pid="$(head -n1 "$AGY_SETTINGS_SENTINEL" 2>/dev/null || true)" - if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then - return 0 - fi - if [ -f "$AGY_SETTINGS_BACKUP" ]; then - mv "$AGY_SETTINGS_BACKUP" "$AGY_SETTINGS_FILE" - echo "[wrapper] recovered orphaned settings backup from PID ${pid:-unknown}" >&2 - fi - rm -f "$AGY_SETTINGS_SENTINEL" -} - -# mkdir-based lock; macOS has no flock(1). Dead-holder detection avoids -# SIGKILL deadlocks. -with_settings_lock() { - local fn="$1"; shift - local attempt=0 - local max_wait="${AGY_LOCK_WAIT_SECONDS:-600}" - while ! mkdir "$AGY_SETTINGS_LOCKDIR" 2>/dev/null; do - local holder_pid_file="${AGY_SETTINGS_LOCKDIR}/pid" - if [ -f "$holder_pid_file" ]; then - local holder_pid; holder_pid="$(cat "$holder_pid_file" 2>/dev/null || true)" - if [ -n "$holder_pid" ] && ! kill -0 "$holder_pid" 2>/dev/null; then - rm -rf "$AGY_SETTINGS_LOCKDIR" - continue - fi - fi - attempt=$((attempt + 1)) - if [ "$attempt" -gt "$max_wait" ]; then - echo "error: could not acquire settings lock after ${max_wait}s" >&2 - exit 1 - fi - sleep 1 - done - echo "$$" > "${AGY_SETTINGS_LOCKDIR}/pid" - local rc=0 - "$fn" "$@" || rc=$? - rm -rf "$AGY_SETTINGS_LOCKDIR" - return "$rc" -} - -# python3 preferred for correctness; sed fallback only matches single-line -# "model": "..." (the format agy itself writes). -_patch_model_field() { - local canonical="$1" - local tmp; tmp="$(mktemp "${AGY_SETTINGS_FILE}.tmp.XXXXXX")" - if command -v python3 >/dev/null 2>&1; then - python3 - "$AGY_SETTINGS_FILE" "$canonical" "$tmp" <<'PY' -import json, sys -src, model, dst = sys.argv[1], sys.argv[2], sys.argv[3] -with open(src) as f: - data = json.load(f) -data["model"] = model -with open(dst, "w") as f: - json.dump(data, f, indent=2) - f.write("\n") -PY - else - local esc; esc="$(printf '%s' "$canonical" | sed -e 's/[\/&]/\\&/g')" - sed -E "s/^([[:space:]]*\"model\"[[:space:]]*:[[:space:]]*\")[^\"]*(\".*)$/\1${esc}\2/" \ - "$AGY_SETTINGS_FILE" > "$tmp" - echo "[wrapper] note: python3 missing, used sed fallback to patch settings.json" >&2 - fi - mv "$tmp" "$AGY_SETTINGS_FILE" -} - -_restore_settings() { - if [ -f "$AGY_SETTINGS_BACKUP" ]; then - mv "$AGY_SETTINGS_BACKUP" "$AGY_SETTINGS_FILE" - fi - rm -f "$AGY_SETTINGS_SENTINEL" -} - -_do_patched_run() { - local canonical="$1"; shift - cp -p "$AGY_SETTINGS_FILE" "$AGY_SETTINGS_BACKUP" - printf '%s\n%s\n' "$$" "$canonical" > "$AGY_SETTINGS_SENTINEL" - trap '_restore_settings' EXIT INT TERM HUP - _patch_model_field "$canonical" - local rc=0 - "$@" || rc=$? - _restore_settings - trap - EXIT INT TERM HUP - return "$rc" -} - -# `--` separator guards against canonical names that start with `-`. -with_model_override() { - local canonical="$1"; shift - if [ "${1:-}" != "--" ]; then - echo "internal: with_model_override expects '--' after canonical name" >&2 - exit 70 - fi - shift - validate_settings_file - with_settings_lock _do_patched_run "$canonical" "$@" -} - -# --------------------------------------------------------------------------- -# agy output capture (read-only). -# -# agy 1.0.15 fixed issue #76: earlier `agy --print`, when stdout was NOT a -# TTY (any time the plugin runs it from a subprocess / agent Bash tool), -# generated the response internally but flushed ZERO bytes to stdout — the -# "drip" typewriter only targeted a real terminal (`Drip stopped: length=N` -# in the log while stdout stayed empty, confirmed on agy 1.0.3). Separately, -# `agy --print` blocks forever on a non-TTY stdin that never reaches EOF, so -# we always close stdin (= 1.0.15. No write_file, no -# --dangerously-skip-permissions. -# -# FALLBACK 1 (transcript): if stdout comes back empty (older agy still hit by -# #76), read the answer from agy's own on-disk conversation transcript — which -# it persists on every --print run with NO tool permission — via -# lib/transcript.mjs (the conversation id comes from the run's --log-file). -# -# FALLBACK 2 (_agy_capture_writefile): only when `node` is unavailable (the -# transcript is JSONL, parsed with node). Reverts to instructing agy to -# write_file its answer under --dangerously-skip-permissions, scoped to a -# throwaway temp dir. Kept so /agy:ask still works without node. -# -# Usage: _agy_capture [extra agy args...] -# Prints the response on success (rc 0); prints an error and rc 1 otherwise. -# --------------------------------------------------------------------------- -_agy_capture() { - local agy="$1" canonical="$2" timeout="$3" prompt="$4" - shift 4 - - # The transcript is JSONL; we parse it with node. Without node, fall back - # to the write_file capture so /agy:ask still works everywhere. - if ! command -v node >/dev/null 2>&1; then - _agy_capture_writefile "$agy" "$canonical" "$timeout" "$prompt" "$@" - return $? - fi - - local outdir - outdir="$(mktemp -d 2>/dev/null)" || { echo "error: could not create temp dir for agy output" >&2; return 1; } - local logfile="$outdir/agy-run.log" - # Optional: stage a single (caller-validated) input file into the temp dir - # so a read-only command (e.g. /agy:doc-to-md) can hand agy a file to read - # without exposing the rest of the filesystem. We stage via the Node helper - # (lstat + copy in ONE step) rather than a shell `cp`: it rejects a symlink - # swapped in after validation (TOCTOU) and copies to a FIXED name so the - # untrusted original filename never reaches agy's prompt. agy runs from - # $outdir with only $outdir in --add-dir, so it sees this copy and nothing - # else. - if [ -n "${AGY_CAPTURE_STAGE_FILE:-}" ]; then - local stage_as="${AGY_CAPTURE_STAGE_AS:-document}" - if ! node "$AGY_LIB_DIR/inputguard.mjs" stage "$AGY_CAPTURE_STAGE_FILE" "$outdir/$stage_as" >/dev/null 2>&1; then - echo "error: could not stage the input file (it may have been swapped, removed, or is unreadable)." >&2 - rm -rf "$outdir" - return 1 - fi - fi - # agy may be a Windows .exe invoked from Git Bash, which needs native - # Windows paths for --add-dir / --log-file / cwd. - # - # CRITICAL: we run agy FROM the throwaway temp dir (cwd="$outdir"), NOT the - # user's repo. `agy --print` still EXECUTES write tools even without - # --dangerously-skip-permissions (a non-TTY prompt is auto-proceeded), so - # "no auto-approve" alone does NOT make a command read-only. What makes it - # read-only is that the repo is neither agy's cwd nor in --add-dir, so it - # has no path to write there. cwd_arg therefore points at the temp dir - # (also the workspace key agy registers — used as the transcript fallback). - local target_dir logfile_arg cwd_arg - if command -v cygpath >/dev/null 2>&1; then - target_dir="$(cygpath -w "$outdir")" - logfile_arg="$(cygpath -w "$logfile")" - cwd_arg="$target_dir" - else - target_dir="$outdir" - logfile_arg="$logfile" - cwd_arg="$outdir" - fi - - # agy --print takes the whole prompt as ONE argv entry, so it must stay - # under the OS command-line limit (~32 KB on Windows) or the process - # fails with ENAMETOOLONG. Cap by BYTES (multibyte-safe via wc -c/head -c). - # No write_file suffix now, so the whole budget is the prompt body. - local max_body="${AGY_PROMPT_MAX_BYTES:-30000}" - local prompt_bytes; prompt_bytes="$(printf '%s' "$prompt" | wc -c)" - if [ "$prompt_bytes" -gt "$max_body" ]; then - prompt="$(printf '%s' "$prompt" | head -c "$max_body" || true)"$'\n\n[...content truncated to fit the OS command-line length limit; some context was omitted...]' - fi - - # Per-call model override decision (unchanged): agy 1.0.x has no top-level - # "model" key until the user sets one in the TUI, so degrade gracefully - # rather than hard-fail. - local use_override=0 - if [ -n "$canonical" ]; then - if [ -f "$AGY_SETTINGS_FILE" ] && grep -q '"model"' "$AGY_SETTINGS_FILE" 2>/dev/null; then - use_override=1 - else - echo "[wrapper] note: --model requested, but agy's settings.json has no \"model\" field to patch on this version; using the current default model instead. (Set a model once in the agy TUI to enable per-call overrides.)" >&2 - fi - fi - - # READ-ONLY run: execute agy FROM the throwaway temp dir (cwd="$outdir"), - # with --sandbox + --add-dir + --log-file and NO - # --dangerously-skip-permissions / NO write_file. Running outside the repo - # is what actually enforces read-only (see the cwd note above). - # `env -u …` strips the repo-location hints (CLAUDE_PROJECT_DIR / GIT_*) from - # agy's environment as defense in depth. = 1.0.15 fixed the #76 bug that - # swallowed non-TTY stdout, so stdout is now the fast path; the transcript - # is the fallback for older agy where stdout still comes back empty. - local stdout_file="$outdir/agy-stdout.txt" - local -a agy_env=(env -u CLAUDE_PROJECT_DIR -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_COMMON_DIR) - if [ "$use_override" -eq 1 ]; then - ( cd "$outdir" && with_model_override "$canonical" -- "${agy_env[@]}" "$agy" --sandbox \ - --add-dir "$target_dir" --log-file "$logfile_arg" --print-timeout "$timeout" "$@" --print "$prompt" \ - "$stdout_file" 2>/dev/null ) || true - else - ( cd "$outdir" && "${agy_env[@]}" "$agy" --sandbox \ - --add-dir "$target_dir" --log-file "$logfile_arg" --print-timeout "$timeout" "$@" --print "$prompt" \ - "$stdout_file" 2>/dev/null ) || true - fi - - # Prefer agy's direct stdout (the #76 fix). Fall back to reading agy's own - # transcript for older agy / platforms where non-TTY stdout is still empty. - # transcript.mjs prints the answer (exit 0) or exits non-zero; its stderr is - # captured and surfaced only if BOTH paths come back empty. - local rc=0 answer="" node_err="$outdir/node.err" - answer="$(cat "$stdout_file" 2>/dev/null)" - if [ -z "$answer" ] && command -v node >/dev/null 2>&1; then - answer="$(node "$AGY_LIB_DIR/transcript.mjs" "$logfile_arg" "$cwd_arg" 2>"$node_err" || true)" - fi - if [ -n "$answer" ]; then - printf '%s\n' "$answer" - else - rc=1 - { - echo "error: agy returned no output." - echo " Neither agy's stdout nor its transcript produced an answer." - echo " Possible causes:" - echo " - the prompt timed out (raise the timeout), or" - echo " - agy was interrupted before it answered." - if [ -s "$node_err" ]; then - echo " transcript.mjs stderr:" - sed 's/^/ /' "$node_err" - fi - echo " Run \`agy\` interactively to debug, or check ~/.gemini/antigravity-cli/log/." - } >&2 - fi - rm -rf "$outdir" - return "$rc" -} - -# --------------------------------------------------------------------------- -# Legacy fallback capture — used only when `node` is unavailable. Instructs -# agy to write_file its answer to a temp file under -# --dangerously-skip-permissions, scoped to a throwaway temp dir. See the -# _agy_capture header for why the transcript path is preferred. -# --------------------------------------------------------------------------- -_agy_capture_writefile() { - local agy="$1" canonical="$2" timeout="$3" prompt="$4" - shift 4 - local outdir - outdir="$(mktemp -d 2>/dev/null)" || { echo "error: could not create temp dir for agy output" >&2; return 1; } - local outfile="$outdir/agy-response.md" - # agy may be a Windows .exe invoked from Git Bash, which needs a native - # Windows path for both --add-dir and the write_file target. - local prompt_path target_dir - if command -v cygpath >/dev/null 2>&1; then - prompt_path="$(cygpath -w "$outfile")" - target_dir="$(cygpath -w "$outdir")" - else - prompt_path="$outfile" - target_dir="$outdir" - fi - # agy --print takes the whole prompt as ONE argv entry, so it must - # stay under the OS command-line limit (~32 KB on Windows) or the - # process fails with "Argument list too long" / ENAMETOOLONG. Cap the - # body (the write_file instruction is appended after, always intact). - # Cap by BYTES, not characters: `${#prompt}` / `${prompt:0:N}` count - # characters, so multibyte UTF-8 (CJK, emoji) could still blow past - # the byte limit. `wc -c` / `head -c` are byte-accurate in any locale. - local max_body="${AGY_PROMPT_MAX_BYTES:-26000}" - local prompt_bytes; prompt_bytes="$(printf '%s' "$prompt" | wc -c)" - if [ "$prompt_bytes" -gt "$max_body" ]; then - prompt="$(printf '%s' "$prompt" | head -c "$max_body" || true)"$'\n\n[...content truncated to fit the OS command-line length limit; some diff/file context was omitted...]' - fi - local augmented - augmented="$(printf '%s\n\n---\nOUTPUT INSTRUCTION (required): Use the write_file tool to write your COMPLETE response to this exact path:\n%s\nDo NOT print the answer to chat — that path is your only deliverable. After writing the file, stop.\n' "$prompt" "$prompt_path")" - - # Decide whether the per-call model override is actually usable. agy - # 1.0.x does NOT keep a top-level "model" key in settings.json until - # the user changes the model in the TUI, so the patch-and-restore path - # has nothing to patch. Rather than hard-fail the whole command (the - # old validate_settings_file did `exit 1`), degrade gracefully: warn - # once and run with agy's current default model. - local use_override=0 - if [ -n "$canonical" ]; then - if [ -f "$AGY_SETTINGS_FILE" ] && grep -q '"model"' "$AGY_SETTINGS_FILE" 2>/dev/null; then - use_override=1 - else - echo "[wrapper] note: --model requested, but agy's settings.json has no \"model\" field to patch on this version; using the current default model instead. (Set a model once in the agy TUI to enable per-call overrides.)" >&2 - fi - fi - - # Strip repo-location hints (CLAUDE_PROJECT_DIR / GIT_*) from agy's env as - # defense in depth — same as _agy_capture. This fallback runs agy under - # --dangerously-skip-permissions, so denying it a pointer to the host repo - # matters even though the repo is still never its cwd nor in --add-dir. - local -a agy_env=(env -u CLAUDE_PROJECT_DIR -u GIT_DIR -u GIT_WORK_TREE -u GIT_INDEX_FILE -u GIT_COMMON_DIR) - if [ "$use_override" -eq 1 ]; then - ( cd "$outdir" && with_model_override "$canonical" -- "${agy_env[@]}" "$agy" --dangerously-skip-permissions --sandbox \ - --add-dir "$target_dir" --print-timeout "$timeout" "$@" --print "$augmented" \ - /dev/null 2>&1 ) || true - else - ( cd "$outdir" && "${agy_env[@]}" "$agy" --dangerously-skip-permissions --sandbox \ - --add-dir "$target_dir" --print-timeout "$timeout" "$@" --print "$augmented" \ - /dev/null 2>&1 ) || true - fi - - local rc=0 - if [ -s "$outfile" ]; then - cat "$outfile" - else - rc=1 - { - echo "error: agy returned no output." - echo " This is agy issue #76 (empty stdout in non-TTY) combined with the" - echo " write_file workaround failing to produce a file. Possible causes:" - echo " - the prompt timed out (raise the timeout), or" - echo " - agy refused/limited the write_file tool." - echo " Run \`agy\` interactively to debug, or check ~/.gemini/antigravity-cli/log/." - } >&2 - fi - rm -rf "$outdir" - return "$rc" -} - -cmd_ask() { - local model_alias="" - local model_flag_seen=0 - while [ $# -gt 0 ]; do - case "$1" in - --model) - model_flag_seen=1 - # `shift 2` on a one-arg list would `set -e`-exit silently; handle - # the empty case so resolve_model_alias prints the real error. - if [ $# -ge 2 ]; then - model_alias="$2"; shift 2 - else - shift - fi ;; - --model=*) - model_flag_seen=1 - model_alias="${1#--model=}" - shift ;; - --) shift; break ;; - *) break ;; - esac - done - # Resolve model before prompt check so empty --model gets the right error. - local canonical="" - if [ "$model_flag_seen" -eq 1 ]; then - canonical="$(resolve_model_alias "$model_alias")" - fi - local prompt="${1:-}" - shift || true - if [ -z "$prompt" ]; then - echo "error: ask requires a prompt argument" >&2 - exit 64 - fi - local path - path="$(require_ready)" - # Route through the read-only transcript capture (agy issue #76). Default - # to an 8-minute timeout; agy usually answers within seconds. - _agy_capture "$path" "$canonical" "${AGY_ASK_TIMEOUT:-8m0s}" "$prompt" "$@" -} - -# /agy:scrape [--model ] — fetch a web page read-only and return -# its main content as Markdown. The URL is validated by lib/inputguard.mjs -# (http/https only; localhost / private / link-local / metadata blocked) to -# prevent SSRF before agy ever touches it. -cmd_scrape() { - local model_alias="" model_flag_seen=0 - while [ $# -gt 0 ]; do - case "$1" in - --model) - model_flag_seen=1 - if [ $# -ge 2 ]; then model_alias="$2"; shift 2; else shift; fi ;; - --model=*) model_flag_seen=1; model_alias="${1#--model=}"; shift ;; - --) shift; break ;; - *) break ;; - esac - done - local canonical="" - [ "$model_flag_seen" -eq 1 ] && canonical="$(resolve_model_alias "$model_alias")" - local url="${1:-}" - if [ -z "$url" ]; then - echo "error: scrape requires a URL argument (http/https)" >&2 - exit 64 - fi - if ! command -v node >/dev/null 2>&1; then - echo "error: /agy:scrape needs Node.js (URL validation + output capture)." >&2 - exit 1 - fi - local safe_url - if ! safe_url="$(node "$AGY_LIB_DIR/inputguard.mjs" scrape "$url" 2>&1)"; then - echo "error: refusing to scrape this URL — $safe_url" >&2 - exit 65 - fi - local path - path="$(require_ready)" - local prompt - prompt="$(printf 'Fetch the web page at the URL below and return its MAIN readable content as clean Markdown — preserve headings, lists, links, tables, and code blocks; drop nav/ads/boilerplate. Output ONLY the Markdown, no preamble.\n\nURL: %s' "$safe_url")" - _agy_capture "$path" "$canonical" "${AGY_SCRAPE_TIMEOUT:-5m0s}" "$prompt" -} - -# /agy:doc-to-md [--model ] — convert a local document to -# Markdown read-only. The path is validated by lib/inputguard.mjs (allow- -# listed document extensions, real file, size cap, not under a sensitive -# dir, symlinks resolved), then staged into the throwaway temp dir so agy -# sees only that one file. -cmd_doc_to_md() { - local model_alias="" model_flag_seen=0 - while [ $# -gt 0 ]; do - case "$1" in - --model) - model_flag_seen=1 - if [ $# -ge 2 ]; then model_alias="$2"; shift 2; else shift; fi ;; - --model=*) model_flag_seen=1; model_alias="${1#--model=}"; shift ;; - --) shift; break ;; - *) break ;; - esac - done - local canonical="" - [ "$model_flag_seen" -eq 1 ] && canonical="$(resolve_model_alias "$model_alias")" - local input="${1:-}" - if [ -z "$input" ]; then - echo "error: doc-to-md requires a file path" >&2 - exit 64 - fi - if ! command -v node >/dev/null 2>&1; then - echo "error: /agy:doc-to-md needs Node.js (path validation + output capture)." >&2 - exit 1 - fi - local real - if ! real="$(node "$AGY_LIB_DIR/inputguard.mjs" doc "$input" "$PWD" 2>&1)"; then - echo "error: refusing to convert this file — $real" >&2 - exit 65 - fi - local path - path="$(require_ready)" - # Stage under a FIXED name derived only from the validated extension — the - # untrusted original filename is never interpolated into the prompt (prompt - # injection guard). - local ext; ext="$(printf '%s' "${real##*.}" | tr '[:upper:]' '[:lower:]')" - local staged="document.${ext}" - local prompt - prompt="$(printf 'Read the file named "%s" in your workspace and convert it to clean, well-structured Markdown. Preserve headings, lists, tables, links, and code blocks. Output ONLY the Markdown — no preamble, no commentary.' "$staged")" - AGY_CAPTURE_STAGE_FILE="$real" AGY_CAPTURE_STAGE_AS="$staged" \ - _agy_capture "$path" "$canonical" "${AGY_DOCTOMD_TIMEOUT:-8m0s}" "$prompt" -} - -cmd_review() { - local focus="${1:-Please review the following diff for correctness, edge cases, security issues, and style.}" - local path - path="$(require_ready)" - local repo_dir="${CLAUDE_PROJECT_DIR:-$PWD}" - # -U gives agy more context around each hunk than git's default 3 - # lines, so it can see imports / early returns / nearby code and stop - # flagging false positives for things just outside the window. - local ctx="${AGY_REVIEW_CONTEXT:-25}" - local diff - local -a diff_range=("HEAD") - diff="$(git -C "$repo_dir" diff "-U${ctx}" HEAD 2>/dev/null || true)" - if [ -z "$diff" ]; then - # Fall back to the unstaged diff — and sync the name-only file list - # below to the same range (was always "HEAD", starving full-file - # context of the fallback's files). - diff_range=() - diff="$(git -C "$repo_dir" diff "-U${ctx}" 2>/dev/null || true)" - fi - if [ -z "$diff" ]; then - echo "error: no git diff found in $repo_dir. Stage or make changes first." >&2 - exit 1 - fi - - # Guardrail: refuse to ship a diff containing obvious secrets unless the - # user opted in via AGY_REVIEW_ALLOW_SECRETS=1. Best-effort; false - # negatives are possible. - local secret_hits - if ! secret_hits="$(_scan_diff_for_secrets "$diff")"; then - { - echo - echo "[wrapper] WARNING: diff contains values matching common secret patterns:" - printf '%s\n' "$secret_hits" | sed 's/^/ - /' - echo - echo " Sending it through agy will forward those values to Google's Gemini API." - if [ "${AGY_REVIEW_ALLOW_SECRETS:-0}" != "1" ]; then - echo " Aborting. Set AGY_REVIEW_ALLOW_SECRETS=1 to proceed anyway, or remove" - echo " the matching lines from your diff first." - exit 65 - fi - echo " Proceeding because AGY_REVIEW_ALLOW_SECRETS=1." - } >&2 - fi - - # Full content of small changed files, so agy sees whole-file - # structure (imports, guards) not just hunks. Cap per-file lines and - # total bytes so a big changeset can't blow up the prompt. - # Defaults aligned with the Node companion (lib/git.mjs). Kept well - # under AGY_PROMPT_MAX_BYTES so the files block + diff don't get - # truncated mid-prompt. - local max_lines="${AGY_REVIEW_FULLFILE_MAX_LINES:-250}" - local budget="${AGY_REVIEW_FULLFILE_BUDGET_BYTES:-12288}" - local files_block="" used=0 - local f - while IFS= read -r f; do - [ -n "$f" ] || continue - local abs="$repo_dir/$f" - # Regular file only, and NOT a symlink (a symlinked path in the diff - # could point at an arbitrary host file like /etc/passwd). - [ -f "$abs" ] && [ ! -L "$abs" ] || continue - # Directory-symlink defense: resolve the real path and require it to - # stay inside the repo (catches `linked_dir/file` where linked_dir - # points outside). Skip the file if it escapes. - if command -v realpath >/dev/null 2>&1; then - local rp rr - rp="$(realpath "$abs" 2>/dev/null || echo)" - rr="$(realpath "$repo_dir" 2>/dev/null || echo "$repo_dir")" - # Case-insensitive prefix match: Windows/macOS filesystems are - # case-insensitive, and realpath may return different casing than - # $repo_dir, which would wrongly skip a legitimate in-repo file. - local rp_l rr_l - rp_l="$(printf '%s' "$rp" | tr '[:upper:]' '[:lower:]')" - rr_l="$(printf '%s' "$rr" | tr '[:upper:]' '[:lower:]')" - case "$rp_l" in "$rr_l"/*) : ;; *) continue ;; esac - fi - # skip binary (no NUL byte => text) - if grep -qI . "$abs" 2>/dev/null; then :; else continue; fi - local lc; lc="$(wc -l < "$abs" 2>/dev/null || echo 999999)" - [ "$lc" -le "$max_lines" ] || continue - local sz; sz="$(wc -c < "$abs" 2>/dev/null || echo 0)" - # Only count toward the budget if it actually fits — otherwise a big - # file would inflate `used` and starve every later (small) file. - if [ "$((used + sz))" -le "$budget" ]; then - used=$((used + sz)) - else - continue - fi - local ext="${f##*.}" - # Dynamic fence: one more backtick than the longest backtick run in - # the file, so content containing ``` (or ````) can't close the - # block early. min 3. - local maxrun - # `|| true`: grep exits 1 when the file contains no backticks; with - # `set -o pipefail` that propagates and `set -e` would abort the whole - # review on the first backtick-free file (e.g. package.json). awk still - # prints the count (3 for no-backtick input), so swallow grep's status. - maxrun="$(grep -oE '`+' "$abs" 2>/dev/null | awk '{ if (length>m) m=length } END { n=(m<2?2:m)+1; print n }' || true)" - [ -n "$maxrun" ] || maxrun=3 - # Build the fence without `seq` (absent in some minimal shells). - local fence="" _i - for ((_i = 0; _i < maxrun; _i++)); do fence="${fence}\`"; done - files_block="${files_block}"$'\n'"### ${f}"$'\n'"${fence}${ext}"$'\n'"$(cat "$abs")"$'\n'"${fence}"$'\n' - done < <(git -C "$repo_dir" diff --name-only "${diff_range[@]}" 2>/dev/null) - - # Secret guard, pass 2: the diff scan above only sees added lines, but the - # files block ships the FULL current content of changed files — a secret - # on an unchanged line would slip through. Scan exactly what we ship. - if [ -n "$files_block" ]; then - local file_secret_hits - if ! file_secret_hits="$(_scan_text_for_secrets "$files_block")"; then - { - echo - echo "[wrapper] WARNING: full content of a changed file matches common secret patterns:" - printf '%s\n' "$file_secret_hits" | sed 's/^/ - /' - echo - echo " These values ship to Google's Gemini API as review context even though" - echo " they aren't in the diff." - if [ "${AGY_REVIEW_ALLOW_SECRETS:-0}" != "1" ]; then - echo " Aborting. Set AGY_REVIEW_ALLOW_SECRETS=1 to proceed anyway, or remove" - echo " the matching values first." - exit 65 - fi - echo " Proceeding because AGY_REVIEW_ALLOW_SECRETS=1." - } >&2 - fi - fi - - local full - if [ -n "$files_block" ]; then - full=$(printf '%s\n\nFull current content of the changed files (for context — do NOT flag issues already handled elsewhere in these files):\n%s\nDiff (with expanded context):\n```diff\n%s\n```\n' "$focus" "$files_block" "$diff") - else - full=$(printf '%s\n\nDiff (with expanded context):\n```diff\n%s\n```\n' "$focus" "$diff") - fi - # Route through the write_file workaround (agy issue #76). Reviews can - # run long on big diffs; default to 10 minutes. - _agy_capture "$path" "" "${AGY_REVIEW_TIMEOUT:-10m0s}" "$full" -} - -cmd_image() { - local description="" - local name="" - local output="" - local positional=() - while [ $# -gt 0 ]; do - case "$1" in - --name) - if [ $# -ge 2 ]; then - name="$2"; shift 2 - else - echo "error: --name requires a value (e.g. --name coffee_cup)" >&2 - exit 64 - fi ;; - --name=*) - name="${1#--name=}" - if [ -z "$name" ]; then - echo "error: --name= requires a non-empty value" >&2 - exit 64 - fi - shift ;; - --output) - if [ $# -ge 2 ]; then - output="$2"; shift 2 - else - echo "error: --output requires a path (e.g. --output /tmp/out.png)" >&2 - exit 64 - fi ;; - --output=*) - output="${1#--output=}" - if [ -z "$output" ]; then - echo "error: --output= requires a non-empty path" >&2 - exit 64 - fi - shift ;; - --) shift; positional+=("$@"); break ;; - *) positional+=("$1"); shift ;; - esac - done - description="${positional[*]}" - if [ -z "$description" ]; then - echo "error: image requires a description" >&2 - exit 64 - fi - local agy_path - agy_path="$(require_ready)" - - # agy issue #76 workaround. The old design asked agy to end its reply - # with an `IMAGE_PATH:` line, but agy --print flushes nothing to a - # non-TTY stdout (so the marker never arrived) and hangs on a non-TTY - # stdin. Instead: agy generates the image, then write_file's the - # saved image's absolute path into a marker file we read back. - local outdir - outdir="$(mktemp -d 2>/dev/null)" || { echo "error: could not create temp dir" >&2; return 1; } - local marker="$outdir/image-path.txt" - local marker_path target_dir - if command -v cygpath >/dev/null 2>&1; then - marker_path="$(cygpath -w "$marker")" - target_dir="$(cygpath -w "$outdir")" - else - marker_path="$marker" - target_dir="$outdir" - fi - local name_clause="" - if [ -n "$name" ]; then - name_clause=" Save the image with the name \"${name}\"." - fi - local prompt - prompt="$(printf 'Use your built-in generate_image tool to create this image: %s.%s\n\nAfter the image is saved, use the write_file tool to write ONLY the absolute filesystem path of the saved image (a single line, no quotes, nothing else) to this exact path:\n%s\nDo not print anything to chat. The marker file is your only textual deliverable.' "$description" "$name_clause" "$marker_path")" - - # Run agy FROM the throwaway temp dir (cwd="$outdir") so its - # auto-approved write tools land in the temp, not the user's repo; the - # generated image is read back from the marker and copied to --output by - # this script. stdin /dev/null 2>&1 ) || true - - local src="" - if [ -s "$marker" ]; then - src="$(grep -m1 -v '^[[:space:]]*$' "$marker" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" - # agy may report a native Windows path; translate so [ -f ] works. - if command -v cygpath >/dev/null 2>&1 && printf '%s' "$src" | grep -q '^[A-Za-z]:[\\/]'; then - src="$(cygpath -u "$src" 2>/dev/null || printf '%s' "$src")" - fi - fi - rm -rf "$outdir" - - if [ -n "$src" ] && [ -f "$src" ]; then - # Guardrail: refuse paths outside agy's artifacts dirs (prompt - # injection could otherwise make us copy an arbitrary host file). - if ! _image_source_in_allowlist "$src"; then - { - echo "[wrapper] error: refusing to use image source path outside agy's artifacts directory." - echo "[wrapper] path: $src" - echo "[wrapper] allowed prefixes: ~/.gemini/antigravity-cli/{brain,scratch,cache}/" - } >&2 - return 66 - fi - echo "[wrapper] generated: $src" - if [ -n "$output" ]; then - cp "$src" "$output" - echo "[wrapper] copied to: $output" - fi - return 0 - fi - - { - echo "[wrapper] error: agy did not produce a locatable image." - echo "[wrapper] The marker file was empty or the path it named does not exist." - echo "[wrapper] generate_image may have failed or write_file was declined; check" - echo "[wrapper] ~/.gemini/antigravity-cli/log/ or run \`agy\` interactively." - } >&2 - return 1 -} - -cmd_help() { - cat <<'HELP' -/agy:* commands (Claude Code plugin for the Antigravity CLI) - -Slash commands - /agy:setup Verify agy install + auth. Offers install if missing. - /agy:ask [--model A] One-shot prompt; returns agy's response verbatim. - /agy:delegate [--background] [--model A] - Hand a task to the agy:runner subagent. - /agy:research [--background] [--model A] - Deep-research investigation via agy:runner. - /agy:review [focus] Send current `git diff` to agy for review. - /agy:image [--name S] [--output P] - Generate an image via agy's built-in tool. - /agy:scrape [--model A] Fetch a web page (read-only) -> Markdown. SSRF-guarded. - /agy:doc-to-md [--model A] Convert a local doc (PDF/DOCX/HTML/...) -> Markdown, - read-only + path-guarded (allow-listed types only). - /agy:help This help. - -Model selection (--model) -HELP - print_model_table 1 - cat <<'HELP' - -How --model works - The plugin manages the "model" field in ~/.gemini/antigravity-cli/settings.json - for the duration of a single call: it takes a lock, swaps in your requested - model, invokes agy, and restores the original on exit (including SIGINT / - SIGTERM). If your TUI is open in parallel, its selected model will flip - for the duration of the call and revert when the call finishes. - - Unknown aliases fail with exit 64 — typo safety beats forward-compat. If - Google ships a new model, update the plugin. - -Underlying CLI - Run `agy --help` for agy's own flags: --add-dir, -c/--continue, - --conversation, --dangerously-skip-permissions, -i/--prompt-interactive, - --log-file, -p/--print, --print-timeout, --sandbox. - - Subcommands: changelog, help, install, plugin/plugins, update. -HELP -} - -main() { - restore_orphaned_backup 2>/dev/null || true - - case "${1:-}" in - check) cmd_check ;; - ask) shift; cmd_ask "$@" ;; - review) shift; cmd_review "$@" ;; - image) shift; cmd_image "$@" ;; - scrape) shift; cmd_scrape "$@" ;; - doc-to-md) shift; cmd_doc_to_md "$@" ;; - help|-h|--help|"") cmd_help ;; - *) echo "error: unknown subcommand '$1'" >&2; cmd_help >&2; exit 64 ;; - esac -} - -# Skip dispatch when sourced (lets unit tests call functions directly). -if [ "${BASH_SOURCE[0]:-}" = "${0:-}" ]; then - main "$@" -fi diff --git a/plugins/agy/scripts/lib/agy.mjs b/plugins/agy/scripts/lib/agy.mjs deleted file mode 100644 index 0480d24..0000000 --- a/plugins/agy/scripts/lib/agy.mjs +++ /dev/null @@ -1,81 +0,0 @@ -// agy.mjs — Antigravity CLI integration primitives. -// -// What lives here: -// - findAgyBinary(): locate the `agy` executable on the user's -// machine, matching the resolution order documented in -// agy-run.sh (PATH first, then a small set of platform-specific -// fallback paths). -// - getAuthStatus(): coarse-grained "are we authed?" probe that -// does NOT call out to `agy` (so it's cheap to call from -// /agy:setup). -// -// Kept deliberately small. The companion does not re-implement -// settings.json patching or model resolution — that stays in the -// Bash wrapper for the synchronous commands. For background jobs we -// honor whatever the user has configured globally. - -import os from "node:os"; -import path from "node:path"; -import process from "node:process"; -import { binaryAvailable } from "./process.mjs"; -import { pathExists } from "./fs.mjs"; - -/** - * Return the resolved path to the `agy` binary, or null if it cannot - * be found. Resolution order: - * 1. AGY_BIN env var (if it exists on disk) - * 2. `agy` on PATH (which/where) - * 3. ${HOME}/.local/bin/agy (macOS / Linux user install) - * 4. /opt/antigravity/bin/agy (Linux system install) - * 5. /usr/local/bin/agy (macOS Homebrew install) - * 6. ${LOCALAPPDATA}/agy/bin/agy.exe (Windows installer location) - */ -export async function findAgyBinary(envOverride) { - const env = envOverride ?? process.env; - if (env.AGY_BIN && await pathExists(env.AGY_BIN)) { - return env.AGY_BIN; - } - if (await binaryAvailable("agy")) { - return "agy"; // PATH lookup will resolve at spawn time - } - const home = env.HOME ?? os.homedir(); - const localAppData = env.LOCALAPPDATA ?? (home ? path.join(home, "AppData", "Local") : null); - const candidates = [ - home && path.join(home, ".local", "bin", "agy"), - "/opt/antigravity/bin/agy", - "/usr/local/bin/agy", - localAppData && path.join(localAppData, "agy", "bin", "agy.exe"), - ].filter(Boolean); - - for (const candidate of candidates) { - if (await pathExists(candidate)) return candidate; - } - return null; -} - -/** - * Coarse auth probe. Mirrors the bash wrapper's auth_status() — - * if ANTIGRAVITY_API_KEY is set, we assume api-key auth; otherwise - * we look for the OAuth state dir on disk. Returns one of: - * "api-key" | "oauth" | "missing" - * - * This is intentionally cheap (no subprocess). It cannot detect a - * stale / expired token — only that *some* credential material is - * in place. /agy:setup's real ping confirms it actually works. - */ -export async function getAuthStatus(envOverride) { - const env = envOverride ?? process.env; - if (env.ANTIGRAVITY_API_KEY && env.ANTIGRAVITY_API_KEY.length > 0) { - return "api-key"; - } - const home = env.HOME ?? os.homedir(); - if (!home) return "missing"; - const oauthDirs = [ - path.join(home, ".config", "antigravity"), - path.join(home, ".gemini", "antigravity-cli"), - ]; - for (const dir of oauthDirs) { - if (await pathExists(dir)) return "oauth"; - } - return "missing"; -} diff --git a/plugins/agy/scripts/lib/args.mjs b/plugins/agy/scripts/lib/args.mjs deleted file mode 100644 index 9383253..0000000 --- a/plugins/agy/scripts/lib/args.mjs +++ /dev/null @@ -1,137 +0,0 @@ -// args.mjs — tiny argv parser without external deps. -// -// Design contract: -// - Boolean flags: `--background`, `--wait`, `--fresh`, `--resume`. -// - Value flags: `--model X`, `--model=X`, `--base ref`, `--base=ref`. -// - Unknown flags are passed through to `extra` so callers can -// forward agy-native flags (e.g. `--sandbox`, `--print-timeout`). -// - Positional args become `positional`. -// - `--` terminates flag parsing; everything after lands in -// `positional` verbatim (so a prompt with a leading `-` is safe). -// - `--flag=` with an empty value is reported via `errors` rather -// than silently consuming the next token (matches the wrapper's -// 0.4.1 convention). - -export function parseArgs(argv, schema) { - const out = { - flags: {}, - values: {}, - positional: [], - extra: [], - errors: [], - }; - for (const flag of schema.boolean ?? []) { - out.flags[flag] = false; - } - for (const flag of schema.value ?? []) { - out.values[flag] = null; - } - - let i = 0; - while (i < argv.length) { - const tok = argv[i]; - if (tok === "--") { - out.positional.push(...argv.slice(i + 1)); - break; - } - // --flag=value or --flag - if (tok.startsWith("--")) { - const eq = tok.indexOf("="); - const name = eq === -1 ? tok.slice(2) : tok.slice(2, eq); - const valueInline = eq === -1 ? null : tok.slice(eq + 1); - if ((schema.boolean ?? []).includes(name)) { - if (valueInline !== null) { - out.errors.push(`--${name} does not take a value`); - } else { - out.flags[name] = true; - } - i += 1; - continue; - } - if ((schema.value ?? []).includes(name)) { - if (valueInline !== null) { - if (valueInline === "") { - out.errors.push(`--${name}= requires a non-empty value`); - } else { - out.values[name] = valueInline; - } - i += 1; - continue; - } - // Space-separated value. - if (i + 1 >= argv.length) { - out.errors.push(`--${name} requires a value`); - i += 1; - continue; - } - out.values[name] = argv[i + 1]; - i += 2; - continue; - } - // Unknown long flag — forward to `extra`. Take next token too if - // it doesn't look like another flag, so `--print-timeout 10m` - // forwards both halves. - out.extra.push(tok); - if (eq === -1 && i + 1 < argv.length && !argv[i + 1].startsWith("-")) { - out.extra.push(argv[i + 1]); - i += 2; - } else { - i += 1; - } - continue; - } - // Positional - out.positional.push(tok); - i += 1; - } - return out; -} - -// Convenience: join positional args back into a single prompt string. -// Most slash commands pass the user's free-form text as multiple -// positional tokens. -export function joinPositional(parsed) { - return parsed.positional.join(" ").trim(); -} - -// Split a single string argument as if the shell had tokenized it. -// Handles `'...'`, `"..."`, and bare tokens. Used when the slash -// command hands us $ARGUMENTS as one big string instead of pre-split. -export function splitArgString(s) { - const out = []; - let buf = ""; - let mode = "none"; // 'none' | 'single' | 'double' - let escaped = false; - for (const ch of s ?? "") { - if (escaped) { - buf += ch; - escaped = false; - continue; - } - if (mode === "single") { - if (ch === "'") mode = "none"; - else buf += ch; - continue; - } - if (mode === "double") { - if (ch === '"') mode = "none"; - else if (ch === "\\") escaped = true; - else buf += ch; - continue; - } - // mode === none - if (ch === "'") { mode = "single"; continue; } - if (ch === '"') { mode = "double"; continue; } - if (ch === "\\") { escaped = true; continue; } - if (ch === " " || ch === "\t" || ch === "\n") { - if (buf.length > 0) { - out.push(buf); - buf = ""; - } - continue; - } - buf += ch; - } - if (buf.length > 0) out.push(buf); - return out; -} diff --git a/plugins/agy/scripts/lib/fs.mjs b/plugins/agy/scripts/lib/fs.mjs deleted file mode 100644 index d1af2cf..0000000 --- a/plugins/agy/scripts/lib/fs.mjs +++ /dev/null @@ -1,103 +0,0 @@ -// fs.mjs — filesystem helpers. Atomic write, mkdir -p semantics, -// JSON read with safe defaults. -// -// All paths are assumed absolute; callers should resolve relative -// paths against a known root (typically the workspace root from -// workspace.mjs) before passing them in. - -import { promises as fsp } from "node:fs"; -import path from "node:path"; -import process from "node:process"; - -/** - * Like `mkdir -p`. Returns the same path the caller passed in so it - * can be chained: `const dir = await ensureDir(path.join(root, "x"))`. - */ -export async function ensureDir(dir) { - await fsp.mkdir(dir, { recursive: true }); - return dir; -} - -/** - * Atomic write: write to a tmp file then rename. Avoids the - * "half-written JSON" race that bites us when two slash commands fight - * over the same state file. - * - * `fsync: true` is the safe default for state.json-style writes; pass - * `fsync: false` for high-frequency log appends. - */ -export async function writeAtomic(file, data, { fsync = true } = {}) { - const dir = path.dirname(file); - await ensureDir(dir); - const tmp = path.join( - dir, - `.${path.basename(file)}.tmp-${process.pid}-${Date.now()}`, - ); - let handle; - try { - handle = await fsp.open(tmp, "w", 0o600); - await handle.writeFile(typeof data === "string" ? data : Buffer.from(data)); - if (fsync) { - await handle.sync(); - } - } finally { - if (handle) await handle.close(); - } - await fsp.rename(tmp, file); -} - -/** - * Read JSON from `file`. Returns `fallback` if the file doesn't - * exist; throws on parse error or other I/O errors. - */ -export async function readJson(file, fallback) { - let raw; - try { - raw = await fsp.readFile(file, "utf8"); - } catch (err) { - if (err.code === "ENOENT" && fallback !== undefined) return fallback; - throw err; - } - if (raw.trim() === "" && fallback !== undefined) return fallback; - return JSON.parse(raw); -} - -/** - * Atomic JSON write with a stable 2-space indent and a trailing - * newline. Convenient default for human-inspected state files. - */ -export async function writeJson(file, value, opts) { - const text = JSON.stringify(value, null, 2) + "\n"; - await writeAtomic(file, text, opts); -} - -/** - * Append a line to a log file. Creates the directory and the file as - * needed. Does NOT fsync per write — logs are best-effort, and we - * batch instead via the OS page cache. - */ -export async function appendLogLine(file, line) { - await ensureDir(path.dirname(file)); - const stamped = line.endsWith("\n") ? line : line + "\n"; - await fsp.appendFile(file, stamped); -} - -/** - * Does this path exist on disk? Symlinks resolved. - */ -export async function pathExists(p) { - try { - await fsp.access(p); - return true; - } catch { - return false; - } -} - -/** - * Get an ISO-8601 timestamp suitable for state records. Always UTC, - * always millisecond precision — comparisons stay lexical-order safe. - */ -export function nowIso() { - return new Date().toISOString(); -} diff --git a/plugins/agy/scripts/lib/git.mjs b/plugins/agy/scripts/lib/git.mjs deleted file mode 100644 index 944fc2e..0000000 --- a/plugins/agy/scripts/lib/git.mjs +++ /dev/null @@ -1,439 +0,0 @@ -// git.mjs — git plumbing for code-review flows. -// -// We deliberately shell out to `git` rather than pull in a JS lib — -// `git` is already a hard dependency of the plugin (the wrapper uses -// it too) and we want to inherit its config/auth/sparse-checkout -// behavior for free. - -import path from "node:path"; -import { promises as fsp } from "node:fs"; -import { runCaptured, binaryAvailable } from "./process.mjs"; - -// How many context lines to give agy around each diff hunk. The git -// default is 3, which is far too little for review — agy can't see -// imports, early returns, or nearby code and ends up flagging false -// positives ("X not imported", "missing guard") for things that are -// just outside the 3-line window. 25 covers the common cases; override -// with AGY_REVIEW_CONTEXT. -function reviewContextLines() { - const n = parseInt(process.env.AGY_REVIEW_CONTEXT ?? "", 10); - return Number.isFinite(n) && n >= 0 ? n : 25; -} - -// Full-file-context limits: include the complete current content of a -// changed file when it's small enough that agy benefits from seeing -// the whole structure. The total budget MUST stay well under the OS -// command-line length limit (~32 KB on Windows) because agy --print -// takes the whole prompt as a single argv entry — exceeding it crashes -// with ENAMETOOLONG. 12 KB of embedded files leaves room for the diff -// and instructions; the prompt assembler applies a final hard cap on -// top of this. -// Env-overridable for parity with the Bash wrapper -// (AGY_REVIEW_FULLFILE_MAX_LINES / AGY_REVIEW_FULLFILE_BUDGET_BYTES). -function envInt(name, fallback) { - const v = parseInt(process.env[name] ?? "", 10); - return Number.isFinite(v) && v >= 0 ? v : fallback; -} -const FULL_FILE_MAX_LINES = envInt("AGY_REVIEW_FULLFILE_MAX_LINES", 250); -const FULL_FILE_TOTAL_BUDGET_BYTES = envInt("AGY_REVIEW_FULLFILE_BUDGET_BYTES", 12 * 1024); - -/** Throws if `git` isn't on PATH. */ -export async function ensureGitAvailable() { - if (!(await binaryAvailable("git"))) { - throw new Error("git not found on PATH. /agy:review requires git."); - } -} - -/** - * Resolve the working-tree root of the repo containing `cwd`. Returns - * null when `cwd` isn't inside a git repo. - */ -export async function gitRoot(cwd) { - const r = await runCaptured("git", ["-C", cwd, "rev-parse", "--show-toplevel"], { cwd }); - if (r.exitCode !== 0) return null; - return r.stdout.trim() || null; -} - -/** - * Read the current branch name. Returns the literal "HEAD" when - * detached; callers can decide how to render that. - */ -export async function currentBranch(cwd) { - const r = await runCaptured("git", ["-C", cwd, "rev-parse", "--abbrev-ref", "HEAD"], { cwd }); - if (r.exitCode !== 0) return null; - return r.stdout.trim() || null; -} - -/** - * Resolve a ref (branch, tag, sha, or `HEAD~N`) to a full commit - * sha. Returns null on lookup failure. - */ -export async function resolveRef(cwd, ref) { - const r = await runCaptured("git", ["-C", cwd, "rev-parse", "--verify", ref], { cwd }); - if (r.exitCode !== 0) return null; - return r.stdout.trim() || null; -} - -/** - * Find the merge-base between two refs. Used by the branch-review - * flow so the diff is "what this branch added" not "all the unrelated - * changes on main since I branched". - */ -export async function mergeBase(cwd, a, b) { - const r = await runCaptured("git", ["-C", cwd, "merge-base", a, b], { cwd }); - if (r.exitCode !== 0) return null; - return r.stdout.trim() || null; -} - -/** - * Capture the diff for working-tree review: - * - staged + unstaged changes (`git diff HEAD`) - * - if that's empty (clean working tree), fall back to `git diff` - * against the index alone — useful right after `git add` but - * before any uncommitted edits. - * - * Returns an object with `{ scope, base, head, diff, files }`. - */ -export async function workingTreeDiff(cwd) { - await ensureGitAvailable(); - const root = await gitRoot(cwd); - if (!root) throw new Error(`not in a git repo: ${cwd}`); - const U = `-U${reviewContextLines()}`; - let range = ["HEAD"]; - let diff = (await runCaptured("git", ["-C", root, "diff", U, "HEAD"], { cwd: root })).stdout; - if (!diff.trim()) { - // Fall back to the unstaged diff — and keep the file list in sync - // with it (the old code always used ["HEAD"], so full-file context - // missed the fallback's files). - range = []; - diff = (await runCaptured("git", ["-C", root, "diff", U], { cwd: root })).stdout; - } - const files = await diffFiles(root, range); - return { - scope: "working-tree", - base: "HEAD", - head: "(uncommitted)", - diff, - files, - root, - }; -} - -/** - * Branch-vs-base diff: the changes this branch introduced on top of - * `baseRef`. Computed against the merge-base of HEAD and baseRef so - * we don't include unrelated changes that happened on baseRef in - * the meantime. - */ -export async function branchDiff(cwd, baseRef) { - await ensureGitAvailable(); - const root = await gitRoot(cwd); - if (!root) throw new Error(`not in a git repo: ${cwd}`); - const baseSha = await resolveRef(root, baseRef); - if (!baseSha) { - throw new Error(`cannot resolve --base ref '${baseRef}' to a commit`); - } - const headSha = await resolveRef(root, "HEAD"); - if (!headSha) throw new Error("HEAD is missing or detached and unresolvable"); - const mb = await mergeBase(root, baseSha, headSha); - const compareBase = mb ?? baseSha; - const U = `-U${reviewContextLines()}`; - const diff = (await runCaptured("git", ["-C", root, "diff", U, `${compareBase}...HEAD`], { cwd: root })).stdout; - const files = await diffFiles(root, [`${compareBase}...HEAD`]); - return { - scope: "branch", - base: baseRef, - baseSha, - head: headSha, - mergeBase: compareBase, - diff, - files, - root, - }; -} - -/** - * Read the full current content of changed files so agy sees whole - * structure (imports, early returns, neighbouring code) rather than - * just diff hunks — the #1 source of review false positives. - * - * Skips files that are missing/deleted, larger than - * FULL_FILE_MAX_LINES, or that would push the cumulative size past - * FULL_FILE_TOTAL_BUDGET_BYTES. Binary-ish content is skipped (NUL - * byte heuristic). Returns { included: [{path, content}], omitted: - * [{path, reason}] }. - */ -export async function gatherFileContext(root, files, opts = {}) { - const maxLines = opts.maxLines ?? FULL_FILE_MAX_LINES; - const budget = opts.budgetBytes ?? FULL_FILE_TOTAL_BUDGET_BYTES; - const included = []; - const omitted = []; - let used = 0; - for (const rel of files ?? []) { - const abs = path.isAbsolute(rel) ? rel : path.join(root, rel); - // lstat (not stat): a symlinked file in the diff could point at an - // arbitrary host file (e.g. /etc/passwd); refuse to follow it into - // the prompt. - let st; - try { - st = await fsp.lstat(abs); - } catch { - omitted.push({ path: rel, reason: "missing/deleted" }); - continue; - } - if (st.isSymbolicLink()) { - omitted.push({ path: rel, reason: "symlink (skipped)" }); - continue; - } - if (!st.isFile()) { - omitted.push({ path: rel, reason: "not a regular file" }); - continue; - } - // Defend against DIRECTORY-symlink traversal: lstat only checks the - // leaf, so `linked_dir/file.txt` where linked_dir -> /etc would slip - // through. Resolve the real path and require it to stay inside the - // repo root. - try { - const realAbs = await fsp.realpath(abs); - const realRoot = await fsp.realpath(root); - const within = path.relative(realRoot, realAbs); - if (within === "" || within.startsWith("..") || path.isAbsolute(within)) { - omitted.push({ path: rel, reason: "resolves outside the repo (symlink?)" }); - continue; - } - } catch { - omitted.push({ path: rel, reason: "unresolvable path" }); - continue; - } - // Size check BEFORE reading, so a giant generated/blob file can't - // be slurped into memory (OOM) just to be rejected afterward. - if (st.size > budget - used) { - omitted.push({ path: rel, reason: `too large (${st.size} bytes)` }); - continue; - } - let content; - try { - content = await fsp.readFile(abs, "utf8"); - } catch { - omitted.push({ path: rel, reason: "unreadable" }); - continue; - } - if (content.includes("\0")) { - omitted.push({ path: rel, reason: "binary" }); - continue; - } - const lineCount = content.split("\n").length; - if (lineCount > maxLines) { - omitted.push({ path: rel, reason: `too large (${lineCount} lines)` }); - continue; - } - const bytes = Buffer.byteLength(content, "utf8"); - if (used + bytes > budget) { - omitted.push({ path: rel, reason: "budget exceeded" }); - continue; - } - used += bytes; - included.push({ path: rel, content }); - } - return { included, omitted }; -} - -// Per-file cap for STAGED review materials. Much larger than the -// embed budget (these go to disk, not the argv prompt), but still -// bounded so a giant generated blob can't be copied. -const STAGE_FILE_MAX_BYTES = 2 * 1024 * 1024; - -/** - * Design A+ : stage the review materials (the full diff + the full - * current content of the changed files) into `stageDir` so `agy` can - * read them FROM DISK instead of receiving them in the argv prompt. - * This removes the OS command-line length limit entirely (no - * ENAMETOOLONG, no truncation) and keeps the real repo out of agy's - * `--add-dir` scope. - * - * Writes: - * /diff.patch - * /files/ (full content, mirroring repo layout) - * - * Applies the same safety checks as gatherFileContext (skip symlinks, - * skip paths that resolve outside the repo, skip binaries, skip files - * over STAGE_FILE_MAX_BYTES). Returns { staged: [relpath], omitted: - * [{path, reason}] }. - */ -export async function stageReviewMaterials(stageDir, root, files, diff, opts = {}) { - const maxBytes = opts.maxFileBytes ?? STAGE_FILE_MAX_BYTES; - await fsp.mkdir(stageDir, { recursive: true }); - await fsp.writeFile(path.join(stageDir, "diff.patch"), diff ?? ""); - const filesRoot = path.join(stageDir, "files"); - const staged = []; - const omitted = []; - let realRoot; - try { - realRoot = await fsp.realpath(root); - } catch { - realRoot = root; - } - const filesRootResolved = path.resolve(filesRoot); - for (const rel of files ?? []) { - // git diff --name-only yields repo-relative paths, but be defensive: - // an absolute path or one with `..` would let path.join escape the - // stage dir (or crash with EINVAL on Windows for "C:\..."). Skip it. - if (path.isAbsolute(rel)) { - omitted.push({ path: rel, reason: "absolute path (skipped)" }); - continue; - } - const dest = path.join(filesRoot, rel); - if ( - path.resolve(dest) !== filesRootResolved && - !path.resolve(dest).startsWith(filesRootResolved + path.sep) - ) { - omitted.push({ path: rel, reason: "path escapes stage dir (skipped)" }); - continue; - } - const abs = path.join(root, rel); - let st; - try { - st = await fsp.lstat(abs); - } catch { - omitted.push({ path: rel, reason: "missing/deleted" }); - continue; - } - if (st.isSymbolicLink()) { - omitted.push({ path: rel, reason: "symlink (skipped)" }); - continue; - } - if (!st.isFile()) { - omitted.push({ path: rel, reason: "not a regular file" }); - continue; - } - if (st.size > maxBytes) { - omitted.push({ path: rel, reason: `too large (${st.size} bytes)` }); - continue; - } - // Directory-symlink containment: the real path must stay in the repo. - try { - const realAbs = await fsp.realpath(abs); - const within = path.relative(realRoot, realAbs); - if (within === "" || within.startsWith("..") || path.isAbsolute(within)) { - omitted.push({ path: rel, reason: "resolves outside the repo" }); - continue; - } - } catch { - omitted.push({ path: rel, reason: "unresolvable path" }); - continue; - } - let content; - try { - content = await fsp.readFile(abs, "utf8"); - } catch { - omitted.push({ path: rel, reason: "unreadable" }); - continue; - } - if (content.includes("\0")) { - omitted.push({ path: rel, reason: "binary" }); - continue; - } - // `dest` was computed and containment-checked at the top of the loop. - await fsp.mkdir(path.dirname(dest), { recursive: true }); - await fsp.writeFile(dest, content); - staged.push(rel); - } - return { staged, omitted }; -} - -/** - * List the file paths touched by a diff range. Internal helper for - * the review prompt builder. - */ -async function diffFiles(root, rangeArgs) { - const r = await runCaptured( - "git", - ["-C", root, "diff", "--name-only", ...rangeArgs], - { cwd: root }, - ); - if (r.exitCode !== 0) return []; - return r.stdout - .split("\n") - .map((s) => s.trim()) - .filter(Boolean); -} - -// -------------------------------------------------------------------------- -// Safety helpers for /agy:rescue (clean-tree guard + worktree isolation). -// -------------------------------------------------------------------------- - -/** True if `cwd` is inside a git repo. */ -export async function isGitRepo(cwd) { - return (await gitRoot(cwd)) !== null; -} - -/** - * True if the working tree has no uncommitted changes (staged, - * unstaged, or untracked). Used to guarantee a clean revert point - * before a non-isolated rescue edits files in place. - */ -export async function isWorkingTreeClean(cwd) { - const r = await runCaptured("git", ["-C", cwd, "status", "--porcelain"], { cwd }); - if (r.exitCode !== 0) return false; - return r.stdout.trim() === ""; -} - -/** - * `git diff --stat HEAD` + untracked file list, for the post-rescue - * "here's what agy changed" summary. Returns a printable string. - */ -export async function changeSummary(cwd) { - const stat = await runCaptured("git", ["-C", cwd, "diff", "--stat", "HEAD"], { cwd }); - const untracked = await runCaptured( - "git", - ["-C", cwd, "ls-files", "--others", "--exclude-standard"], - { cwd }, - ); - const lines = []; - const statText = (stat.stdout || "").trim(); - if (statText) lines.push(statText); - const newFiles = (untracked.stdout || "") - .split("\n").map((s) => s.trim()).filter(Boolean); - if (newFiles.length) { - lines.push("new (untracked) files:"); - lines.push(...newFiles.map((f) => ` + ${f}`)); - } - return lines.length ? lines.join("\n") : "(no changes detected)"; -} - -/** - * Create a detached worktree of `repoRoot` at HEAD under `dir`. - * Returns true on success. The worktree shares .git but has its own - * working directory, so an agent can edit it freely without touching - * the user's real working tree. - */ -export async function addWorktree(repoRoot, dir) { - const r = await runCaptured( - "git", - ["-C", repoRoot, "worktree", "add", "--detach", dir, "HEAD"], - { cwd: repoRoot }, - ); - return r.exitCode === 0 ? { ok: true } : { ok: false, error: r.stderr.trim() || r.stdout.trim() }; -} - -/** Remove a worktree created by addWorktree. Best-effort. */ -export async function removeWorktree(repoRoot, dir) { - await runCaptured("git", ["-C", repoRoot, "worktree", "remove", "--force", dir], { cwd: repoRoot }); -} - -/** - * After an isolated rescue, capture everything the agent changed in - * the worktree as a single patch (tracked edits + new files), plus a - * --stat summary. Stages all changes first so untracked files are - * included in the diff. Returns { stat, patch } (both strings). - */ -export async function captureWorktreePatch(worktreeDir) { - await runCaptured("git", ["-C", worktreeDir, "add", "-A"], { cwd: worktreeDir }); - const stat = await runCaptured( - "git", ["-C", worktreeDir, "diff", "--cached", "--stat", "HEAD"], { cwd: worktreeDir }, - ); - const patch = await runCaptured( - "git", ["-C", worktreeDir, "diff", "--cached", "HEAD"], { cwd: worktreeDir }, - ); - return { stat: (stat.stdout || "").trim(), patch: patch.stdout || "" }; -} diff --git a/plugins/agy/scripts/lib/inputguard.mjs b/plugins/agy/scripts/lib/inputguard.mjs deleted file mode 100644 index 8731591..0000000 --- a/plugins/agy/scripts/lib/inputguard.mjs +++ /dev/null @@ -1,275 +0,0 @@ -// inputguard.mjs — input validation (deny-lists) for the read-only Phase-3 -// commands /agy:scrape (a URL) and /agy:doc-to-md (a file path). -// -// These commands hand their input to agy, which fetches/reads it and ships -// the content to Gemini — so the input is an attack surface: -// - scrape: SSRF (file://, localhost, cloud metadata, private ranges). -// - doc-to-md: local-file exfiltration (~/.ssh/id_rsa, .env, /etc/passwd). -// -// Fail CLOSED: anything not clearly allowed is rejected. Best-effort — a -// determined attacker with DNS control can still rebind a public name to an -// internal IP; this guard blocks the obvious literal targets and bad schemes. - -import path from "node:path"; -import { promises as fsp, realpathSync, lstatSync, statSync, copyFileSync } from "node:fs"; -import os from "node:os"; -import process from "node:process"; -import { fileURLToPath } from "node:url"; - -/** - * Decode an IPv4 address embedded in an IPv6 literal — v4-mapped - * (`::ffff:a.b.c.d` / `::ffff:HHHH:HHHH`) or v4-compatible (`::a.b.c.d` / - * `::HHHH:HHHH`) — and return it dotted, or null. Used so an embedded - * loopback/private v4 can't slip past the SSRF guard via IPv6 encoding. - */ -function embeddedIPv4(host) { - let m = host.match(/^::(?:ffff:)?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i); - if (m) return m[1]; - m = host.match(/^::(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i); - if (m) { - const hi = parseInt(m[1], 16); - const lo = parseInt(m[2], 16); - return `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`; - } - return null; -} - -// --------------------------------------------------------------------------- -// /agy:scrape — URL validation -// --------------------------------------------------------------------------- - -const ALLOWED_URL_PROTOCOLS = new Set(["http:", "https:"]); - -/** - * Block localhost / private / link-local / metadata hosts (SSRF guard). - * Operates on the URL hostname (already lower-cased by WHATWG URL). - */ -export function isBlockedHost(hostname) { - let h = String(hostname || "").toLowerCase().replace(/\.+$/, ""); - if (!h) return true; - if (h === "localhost" || h.endsWith(".localhost")) return true; - if ( - h.endsWith(".local") || h.endsWith(".internal") || - h.endsWith(".lan") || h.endsWith(".home") || h.endsWith(".corp") - ) return true; - - // IPv6 literal (strip optional brackets). - let host = h; - if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1); - if (host.includes(":")) { - if (host === "::1" || host === "::") return true; // loopback / unspecified - if (host.startsWith("fe80:")) return true; // link-local - if (/^f[cd][0-9a-f]*:/.test(host)) return true; // ULA fc00::/7 - const embedded = embeddedIPv4(host); // v4-mapped / v4-compatible - if (embedded) return isBlockedHost(embedded); - return false; // other public IPv6 - } - - // Bare integer (http://2130706433/ == 127.0.0.1) or hex IP — block. - if (/^\d+$/.test(host)) return true; - if (/^0x[0-9a-f]+$/.test(host)) return true; - // Dotted form with an octal (leading-zero) octet — ambiguous, block. - if (/\./.test(host) && host.split(".").some((p) => /^0\d/.test(p))) return true; - - // Hostname that EMBEDS a dotted IPv4 ANYWHERE in its labels - // (127.0.0.1.nip.io, foo.127.0.0.1.nip.io, a.b.10.0.0.1.sslip.io) — block - // if that quad is itself a blocked IP. Best-effort against the common - // public-DNS-to-private (nip.io / sslip.io) rebinding trick; a leading - // garbage label must not defeat it. The trailing `\.` requires the quad to - // be followed by more labels, so a bare dotted IPv4 (handled below) does - // not re-enter this branch and recurse forever. - const embed = host.match(/(?:^|\.)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\./); - if (embed && isBlockedHost(embed[1])) return true; - - // Dotted IPv4. - const m = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); - if (m) { - const o = m.slice(1).map(Number); - if (o.some((x) => x > 255)) return true; // malformed → block - const [a, b] = o; - if (a === 127 || a === 0) return true; // loopback / 0.0.0.0/8 - if (a === 10) return true; // private - if (a === 169 && b === 254) return true; // link-local + cloud metadata - if (a === 172 && b >= 16 && b <= 31) return true; // private - if (a === 192 && b === 168) return true; // private - if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64/10 - } - return false; -} - -/** Validate a /agy:scrape URL. Returns { ok, url } or { ok:false, reason }. */ -export function validateScrapeUrl(raw) { - if (typeof raw !== "string" || !raw.trim()) { - return { ok: false, reason: "empty URL" }; - } - let u; - try { - u = new URL(raw.trim()); - } catch { - return { ok: false, reason: "not a valid absolute URL (include http:// or https://)" }; - } - if (!ALLOWED_URL_PROTOCOLS.has(u.protocol)) { - return { ok: false, reason: `protocol '${u.protocol}' is not allowed (only http/https)` }; - } - if (isBlockedHost(u.hostname)) { - return { - ok: false, - reason: `host '${u.hostname}' is blocked (localhost / private / link-local — SSRF guard)`, - }; - } - return { ok: true, url: u.href }; -} - -// --------------------------------------------------------------------------- -// /agy:doc-to-md — file path validation -// --------------------------------------------------------------------------- - -// Allow-list of document extensions we will convert. Anything else (.pem, -// .key, .env, id_rsa, ...) is rejected — fail closed. -const ALLOWED_DOC_EXT = new Set([ - ".pdf", ".docx", ".doc", ".odt", ".rtf", - ".html", ".htm", ".xhtml", ".xml", - ".md", ".markdown", ".txt", ".text", ".rst", ".org", ".adoc", - ".csv", ".tsv", - ".pptx", ".ppt", ".epub", -]); - -const MAX_DOC_BYTES = 10 * 1024 * 1024; // 10 MB - -/** True if a resolved real path sits under a credentials / system directory. */ -export function isSensitivePath(realPath, homedir = os.homedir()) { - const win = process.platform === "win32"; - const norm = (p) => (win ? p.toLowerCase() : p); - const p = norm(realPath); - const home = homedir; - const under = (base) => { - const b = norm(base); - return p === b || p.startsWith(b.endsWith(path.sep) ? b : b + path.sep); - }; - const sensitive = [ - path.join(home, ".ssh"), - path.join(home, ".gnupg"), - path.join(home, ".aws"), - path.join(home, ".config", "gcloud"), - path.join(home, ".gemini"), // agy's own credentials / conversation store - path.join(home, ".kube"), - path.join(home, ".docker"), - ]; - if (!win) sensitive.push("/etc", "/root", "/proc", "/sys", "/dev", "/var/run"); - return sensitive.some(under); -} - -/** True for a UNC (\\server\share) or device (\\?\, \\.\, //server) path. */ -export function isUncPath(p) { - return /^[\\/]{2}/.test(String(p)); -} - -/** - * Validate a /agy:doc-to-md path. Resolves symlinks first (so a symlinked - * .pdf pointing at ~/.ssh/id_rsa is caught), then enforces: regular file, - * size cap, allowed document extension, not under a sensitive dir. - * Returns { ok, path, ext } or { ok:false, reason }. - */ -export async function validateDocPath(raw, opts = {}) { - if (typeof raw !== "string" || !raw.trim()) { - return { ok: false, reason: "empty path" }; - } - const cwd = opts.cwd || process.cwd(); - const abs = path.resolve(cwd, raw.trim()); - // Reject UNC (\\server\share\...) and device (\\?\, \\.\) paths: a document - // shouldn't be one, and they bypass the drive-letter sensitive-dir prefix - // check (e.g. \\localhost\c$\Users\\.ssh\notes.txt reads ~/.ssh). - if (isUncPath(abs)) { - return { ok: false, reason: "UNC / device paths are not allowed" }; - } - let real; - try { - real = realpathSync(abs); - } catch { - return { ok: false, reason: "file does not exist" }; - } - if (isUncPath(real)) { - return { ok: false, reason: "path resolves to a UNC / device path" }; - } - let st; - try { - st = await fsp.stat(real); - } catch { - return { ok: false, reason: "cannot stat file" }; - } - if (!st.isFile()) return { ok: false, reason: "not a regular file" }; - if (st.size > MAX_DOC_BYTES) { - return { ok: false, reason: `file too large (${st.size} bytes > ${MAX_DOC_BYTES} limit)` }; - } - const ext = path.extname(real).toLowerCase(); - if (!ALLOWED_DOC_EXT.has(ext)) { - return { ok: false, reason: `extension '${ext || "(none)"}' is not an allowed document type` }; - } - if (isSensitivePath(real, opts.homedir)) { - return { ok: false, reason: "path resolves under a sensitive directory" }; - } - return { ok: true, path: real, ext }; -} - -/** - * TOCTOU-resistant staging: lstat the source (rejecting a symlink that may - * have been swapped in AFTER validateDocPath resolved the real path), confirm - * a regular file within the size cap, then copy it to `dest`. Done in one Node - * step so the check-to-copy window is microseconds, not a separate shell `cp` - * that re-follows the path (and would dereference a freshly-planted symlink). - */ -export function stageFile(src, dest) { - if (!src || !dest) return { ok: false, reason: "stage requires " }; - let st; - try { - st = lstatSync(src); - } catch { - return { ok: false, reason: "source file is gone" }; - } - if (st.isSymbolicLink()) return { ok: false, reason: "source became a symlink (TOCTOU)" }; - if (!st.isFile()) return { ok: false, reason: "source is not a regular file" }; - if (st.size > MAX_DOC_BYTES) return { ok: false, reason: "source too large" }; - try { - copyFileSync(src, dest); - } catch (e) { - return { ok: false, reason: `copy failed: ${e.message}` }; - } - return { ok: true, path: dest }; -} - -// --------------------------------------------------------------------------- -// CLI: `node inputguard.mjs scrape ` | `node inputguard.mjs doc [cwd]` -// On success prints the normalized URL / resolved path and exits 0. -// On rejection prints the reason to stderr and exits 1. -// --------------------------------------------------------------------------- -function isMainModule() { - const a1 = process.argv[1]; - if (!a1) return false; - const here = fileURLToPath(import.meta.url); - const norm = (p) => { - try { return realpathSync(p); } catch { return path.resolve(p); } - }; - return norm(a1) === norm(here); -} - -if (isMainModule()) { - const [kind, input, cwd] = process.argv.slice(2); - (async () => { - let res; - if (kind === "scrape") res = validateScrapeUrl(input); - else if (kind === "doc") res = await validateDocPath(input, { cwd }); - else if (kind === "stage") res = stageFile(input, cwd); // input=src, cwd=argv[4]=dest - else { - process.stderr.write(`inputguard: unknown kind '${kind}' (expected scrape|doc|stage)\n`); - process.exit(2); - } - if (res.ok) { - process.stdout.write(`${res.url || res.path}\n`); - process.exit(0); - } - process.stderr.write(`${res.reason}\n`); - process.exit(1); - })(); -} - -export { ALLOWED_DOC_EXT, MAX_DOC_BYTES }; diff --git a/plugins/agy/scripts/lib/job-control.mjs b/plugins/agy/scripts/lib/job-control.mjs deleted file mode 100644 index 8b8de65..0000000 --- a/plugins/agy/scripts/lib/job-control.mjs +++ /dev/null @@ -1,85 +0,0 @@ -// job-control.mjs — lookup and snapshot helpers built on top of -// state.mjs. Used by /agy:status, /agy:result, /agy:cancel resolvers. - -import { listJobs, readJob, isValidJobId } from "./state.mjs"; -import { processAlive } from "./process.mjs"; - -/** - * Refresh a record's `status` based on the OS view of the PID. If a - * record says "running" but the PID isn't actually alive, we - * downgrade to "failed" with `exitCode: null` so /agy:status doesn't - * lie. The on-disk record is NOT rewritten here — callers can choose - * to persist via updateJob if they want. - */ -export function liveness(record) { - if (!record) return record; - if (record.status === "running" && record.pid && !processAlive(record.pid)) { - return { - ...record, - status: "failed", - livenessDowngrade: true, - }; - } - return record; -} - -/** - * Build a snapshot of recent jobs for `/agy:status` (no specific id). - * Caller picks the limit; default 10 matches codex-plugin-cc's - * behavior of showing the most useful recent set. - */ -export async function buildStatusSnapshot(workspaceRoot, { limit = 10, kind } = {}) { - const jobs = await listJobs(workspaceRoot, { kind, limit }); - return jobs.map(liveness); -} - -/** - * Resolve a job id given user input. - * - `"latest"` (or undefined/empty) → most recent job, any kind. - * - A full id like `agy-3a7b9c12` → exact match. - * - A shorter prefix like `agy-3a7b` → match against any record's - * id that starts with the prefix. Ambiguous prefixes return null - * with `reason: "ambiguous"`. - * - * Returns `{ record, ambiguous: false }` on success, or - * `{ record: null, reason: "not-found" | "ambiguous" | "bad-id" }`. - */ -export async function resolveJob(workspaceRoot, idOrLatest) { - const raw = (idOrLatest ?? "").trim(); - if (raw === "" || raw === "latest") { - const recent = await listJobs(workspaceRoot, { limit: 1 }); - if (recent.length === 0) return { record: null, reason: "not-found" }; - return { record: liveness(recent[0]) }; - } - if (isValidJobId(raw)) { - const exact = await readJob(workspaceRoot, raw); - if (exact) return { record: liveness(exact) }; - return { record: null, reason: "not-found" }; - } - // Prefix match: look at all jobs. - if (!/^agy-[a-f0-9]{2,}$/.test(raw)) { - return { record: null, reason: "bad-id" }; - } - const all = await listJobs(workspaceRoot); - const matches = all.filter((j) => j.id.startsWith(raw)); - if (matches.length === 0) return { record: null, reason: "not-found" }; - if (matches.length > 1) { - return { record: null, reason: "ambiguous", candidates: matches.map((m) => m.id) }; - } - return { record: liveness(matches[0]) }; -} - -/** - * Convenience: resolve and require a cancelable (running) job. - * Returns `{ record }` or `{ record: null, reason }` where reason is - * one of the resolveJob reasons plus `"not-cancelable"` if the job - * exists but isn't running. - */ -export async function resolveCancelable(workspaceRoot, idOrLatest) { - const r = await resolveJob(workspaceRoot, idOrLatest); - if (!r.record) return r; - if (r.record.status !== "running" && r.record.status !== "pending") { - return { record: null, reason: "not-cancelable", existing: r.record }; - } - return r; -} diff --git a/plugins/agy/scripts/lib/process.mjs b/plugins/agy/scripts/lib/process.mjs deleted file mode 100644 index acc72d6..0000000 --- a/plugins/agy/scripts/lib/process.mjs +++ /dev/null @@ -1,147 +0,0 @@ -// process.mjs — child-process helpers. -// -// `binaryAvailable` and `runCaptured` are synchronous-feel wrappers -// over node:child_process that we use throughout the companion. We -// avoid sync versions so the event loop stays responsive even on -// machines where a probe takes 100ms+. - -import { spawn } from "node:child_process"; - -/** - * Resolve a binary name (or absolute path) on PATH. Returns a boolean. - * Uses `which` on POSIX and `where` on Windows. Falls back to a direct - * file-exists check when the path already looks absolute. - */ -export async function binaryAvailable(nameOrPath) { - if (!nameOrPath) return false; - // Already absolute? Just stat it. - if (nameOrPath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(nameOrPath)) { - try { - const { promises: fsp } = await import("node:fs"); - await fsp.access(nameOrPath); - return true; - } catch { - return false; - } - } - const lookup = process.platform === "win32" ? "where" : "which"; - return new Promise((resolve) => { - const child = spawn(lookup, [nameOrPath], { stdio: "ignore" }); - child.on("exit", (code) => resolve(code === 0)); - child.on("error", () => resolve(false)); - }); -} - -/** - * Run a command and capture stdout/stderr. Returns - * `{ stdout, stderr, exitCode, signal }`. Never throws on a non-zero - * exit — callers check `exitCode`. - * - * Options: - * - cwd: working directory (default: process.cwd()) - * - env: env overrides (merged with process.env) - * - input: string to pipe into stdin - * - timeoutMs: kill after this long (returns exitCode null + signal) - */ -export function runCaptured(cmd, args, opts = {}) { - const { cwd, env, input, timeoutMs } = opts; - return new Promise((resolve) => { - const child = spawn(cmd, args, { - cwd, - env: env ? { ...process.env, ...env } : undefined, - stdio: ["pipe", "pipe", "pipe"], - }); - let stdout = ""; - let stderr = ""; - let killed = false; - let timer = null; - if (timeoutMs && timeoutMs > 0) { - timer = setTimeout(() => { - killed = true; - child.kill("SIGTERM"); - // Escalate to SIGKILL if the process ignores SIGTERM. - setTimeout(() => { - try { child.kill("SIGKILL"); } catch { /* already dead */ } - }, 2000).unref(); - }, timeoutMs); - timer.unref?.(); - } - child.stdout.on("data", (chunk) => { stdout += chunk.toString(); }); - child.stderr.on("data", (chunk) => { stderr += chunk.toString(); }); - if (input !== undefined) { - child.stdin.end(input); - } else { - child.stdin.end(); - } - child.on("error", (err) => { - if (timer) clearTimeout(timer); - resolve({ - stdout, - stderr: stderr + `\n[runCaptured spawn error: ${err.message}]\n`, - exitCode: null, - signal: null, - spawnError: true, - killed, - }); - }); - child.on("close", (exitCode, signal) => { - if (timer) clearTimeout(timer); - resolve({ stdout, stderr, exitCode, signal, killed, spawnError: false }); - }); - }); -} - -/** - * Spawn a child completely detached from us — used for background - * jobs. We redirect stdio to provided file handles so the child can - * keep running after our process exits. - * - * Returns the child's PID. The caller is responsible for unreferring - * the child if they want to exit immediately. - */ -export function spawnDetached(cmd, args, { cwd, env, stdoutFd, stderrFd, stdinIgnore = true } = {}) { - const child = spawn(cmd, args, { - cwd, - env: env ? { ...process.env, ...env } : undefined, - detached: true, - stdio: [ - stdinIgnore ? "ignore" : "inherit", - stdoutFd ?? "ignore", - stderrFd ?? "ignore", - ], - }); - child.unref(); - return child.pid; -} - -/** - * Is `pid` still alive? `kill -0`-style probe. - */ -export function processAlive(pid) { - if (!pid || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch (err) { - // ESRCH = no such process. EPERM = it exists but we can't signal - // it — still alive from our point of view. - return err.code === "EPERM"; - } -} - -/** - * Best-effort terminate. Sends SIGTERM, then SIGKILL after `graceMs`. - * Returns true if the process is gone afterwards. - */ -export async function terminate(pid, { graceMs = 5000 } = {}) { - if (!processAlive(pid)) return true; - try { process.kill(pid, "SIGTERM"); } catch { /* race */ } - const deadline = Date.now() + graceMs; - while (Date.now() < deadline) { - if (!processAlive(pid)) return true; - await new Promise((r) => setTimeout(r, 100)); - } - try { process.kill(pid, "SIGKILL"); } catch { /* race */ } - await new Promise((r) => setTimeout(r, 200)); - return !processAlive(pid); -} diff --git a/plugins/agy/scripts/lib/prompts.mjs b/plugins/agy/scripts/lib/prompts.mjs deleted file mode 100644 index 02d7854..0000000 --- a/plugins/agy/scripts/lib/prompts.mjs +++ /dev/null @@ -1,116 +0,0 @@ -// prompts.mjs — prompt templates for review and adversarial-review. -// -// Pure string builders. Keep these in one file so the wording is -// reviewable in isolation; the rest of the code shouldn't have to -// know what the prompts say. - -const PREAMBLE_REVIEW = `Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.`; - -const PREAMBLE_ADVERSARIAL = `Pressure-test the diff below. Your job is to challenge the implementation, NOT to validate it. Question the chosen approach, surface hidden assumptions, name failure modes the author didn't address, and propose at least one alternative design with concrete tradeoffs vs the chosen one. If the diff is sound, say so explicitly — but make the reader work for that conclusion.`; - -const REVIEW_RULES = [ - "Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.", - "For each finding cite the file path and (ideally) the line number from the diff.", - "Prefer concrete code examples for suggested fixes over prose.", - "Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.", - "Do NOT propose unrelated refactors; review the diff as it stands.", -]; - -const ADVERSARIAL_RULES = [ - "Frame at least 3 questions the diff fails to answer.", - "Identify the assumption you think most likely to break, and why.", - "Propose one materially different design (not just 'rename this'); compare tradeoffs in 3-5 bullets.", - "Call out the failure modes that aren't covered by tests in the diff.", - "Conclude with a one-paragraph verdict: ship / change / rethink.", -]; - -function joinRules(rules) { - return rules.map((r, i) => `${i + 1}. ${r}`).join("\n"); -} - -// Design A+ : the diff and full file content live on disk in a staging -// dir that agy can read; the prompt only POINTS at them. This keeps the -// argv prompt tiny (no ENAMETOOLONG, no truncation) and gives agy the -// whole file for context (kills "X not imported" / "missing guard" -// false positives). `stageDir` is an absolute path agy can read -// (passed via --add-dir); `staged` is the list of staged relpaths. -function stagedMaterialsBlock(stageDir, staged, omitted) { - const sep = stageDir.includes("\\") ? "\\" : "/"; - const diffPath = `${stageDir}${sep}diff.patch`; - const filesDir = `${stageDir}${sep}files`; - const parts = [ - "", - "## Material to review (read these files with your tools — they are on disk, not inline)", - `- The unified diff (with expanded context) is at:\n ${diffPath}`, - ]; - if (staged && staged.length) { - parts.push( - `- The FULL current content of the changed files is under:\n ${filesDir}${sep}`, - ` Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it — the definition is often outside the diff hunk.`, - " Changed files staged for you:", - ...staged.map((f) => ` - ${f}`), - ); - } - const big = (omitted ?? []).filter((o) => /too large|binary|symlink|outside/.test(o.reason)); - if (big.length) { - parts.push( - ` (Not staged: ${big.map((o) => `${o.path} [${o.reason}]`).join(", ")} — judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)`, - ); - } - return parts.join("\n"); -} - -/** - * Build the prompt for `/agy:review`. Tiny argv prompt that points at - * the staged diff + files (see Design A+). `staged`/`omitted` come from - * lib/git.mjs:stageReviewMaterials; `stageDir` is its absolute path. - */ -export function buildReviewPrompt({ diffContext, focus, stageDir, staged, omitted }) { - const scopeBlurb = - diffContext.scope === "branch" - ? `Branch review: HEAD compared against merge-base of HEAD and \`${diffContext.base}\` (resolved sha: ${diffContext.mergeBase ?? "?"}).` - : `Working-tree review: uncommitted changes against \`HEAD\`.`; - const focusBlock = focus ? `\n\nUser focus / extra steer:\n${focus.trim()}` : ""; - return [ - PREAMBLE_REVIEW, - "", - "Rules:", - joinRules(REVIEW_RULES), - "", - scopeBlurb, - focusBlock, - stagedMaterialsBlock(stageDir, staged, omitted), - "", - ].join("\n"); -} - -/** - * Build the prompt for `/agy:adversarial-review` (Design A+). Same - * staged-materials approach, different stance/ruleset. - */ -export function buildAdversarialPrompt({ diffContext, focus, stageDir, staged, omitted }) { - const scopeBlurb = - diffContext.scope === "branch" - ? `Branch under challenge: HEAD vs merge-base of HEAD and \`${diffContext.base}\`.` - : `Working-tree changes under challenge.`; - const focusBlock = focus ? `\n\nWhere the user wants the most pressure:\n${focus.trim()}` : ""; - return [ - PREAMBLE_ADVERSARIAL, - "", - "Rules:", - joinRules(ADVERSARIAL_RULES), - "", - scopeBlurb, - focusBlock, - stagedMaterialsBlock(stageDir, staged, omitted), - "", - ].join("\n"); -} - -// Exported for tests + introspection. -export const PROMPT_INTERNALS = { - PREAMBLE_REVIEW, - PREAMBLE_ADVERSARIAL, - REVIEW_RULES, - ADVERSARIAL_RULES, -}; diff --git a/plugins/agy/scripts/lib/render.mjs b/plugins/agy/scripts/lib/render.mjs deleted file mode 100644 index b892b96..0000000 --- a/plugins/agy/scripts/lib/render.mjs +++ /dev/null @@ -1,121 +0,0 @@ -// render.mjs — pure formatting helpers for the companion's stdout. -// Kept pure (no I/O, no globals) so they're trivial to unit-test. - -const STATUS_BADGE = { - pending: "[pending]", - running: "[running]", - completed: "[done]", - failed: "[failed]", - canceled: "[cancel]", -}; - -function badge(status) { - return STATUS_BADGE[status] ?? `[${status}]`; -} - -function shortTime(iso) { - if (!iso) return "—"; - // Drop the date if it's today (UTC); keep H:M:S. - const d = new Date(iso); - const now = new Date(); - if (Number.isNaN(d.getTime())) return iso; - const sameDay = - d.getUTCFullYear() === now.getUTCFullYear() && - d.getUTCMonth() === now.getUTCMonth() && - d.getUTCDate() === now.getUTCDate(); - const hms = d.toISOString().slice(11, 19); - return sameDay ? hms : d.toISOString().slice(0, 19).replace("T", " "); -} - -function clip(text, max) { - const s = String(text ?? ""); - if (s.length <= max) return s; - return s.slice(0, Math.max(0, max - 1)) + "…"; -} - -/** - * Multi-job table for /agy:status. - * Returns a string; caller decides where to write it. - */ -export function renderStatusList(records) { - if (!records || records.length === 0) { - return "No agy jobs recorded in this workspace yet.\n"; - } - const lines = [ - "ID STATUS KIND STARTED TASK", - ]; - for (const r of records) { - lines.push( - [ - r.id.padEnd(13), - badge(r.status).padEnd(9), - clip(r.kind ?? "", 17).padEnd(18), - shortTime(r.startedAt ?? r.createdAt).padEnd(9), - clip(r.task ?? "", 48), - ].join(" "), - ); - } - return lines.join("\n") + "\n"; -} - -/** - * Single-job detail block for /agy:status . - */ -export function renderJobDetail(record) { - if (!record) return "Job not found.\n"; - const exit = - record.exitCode === null || record.exitCode === undefined - ? "—" - : String(record.exitCode); - const lines = [ - `Job: ${record.id}`, - `Status: ${badge(record.status)}`, - `Kind: ${record.kind ?? "—"}`, - `Model: ${record.model ?? "(default)"}`, - `Task: ${clip(record.task ?? "", 200)}`, - `Created: ${shortTime(record.createdAt)}`, - `Started: ${shortTime(record.startedAt)}`, - `Completed: ${shortTime(record.completedAt)}`, - `Exit code: ${exit}`, - `PID: ${record.pid ?? "—"}`, - `Log file: ${record.logFile ?? "—"}`, - `Workspace: ${record.workspaceRoot ?? "—"}`, - ]; - if (record.livenessDowngrade) { - lines.push("Note: PID is dead but the record claimed running; treated as failed."); - } - return lines.join("\n") + "\n"; -} - -/** - * /agy:result output: a header followed by the captured log. - * Caller passes the log contents (we deliberately don't do I/O here). - */ -export function renderResult(record, logContent) { - if (!record) return "No job to report on.\n"; - const head = renderJobDetail(record); - const body = - typeof logContent === "string" && logContent.length > 0 - ? logContent - : "(log file is empty or missing)"; - return `${head}\n--- output ---\n${body}${body.endsWith("\n") ? "" : "\n"}`; -} - -/** - * /agy:cancel report — what happened, in one paragraph the user can - * paste into a ticket. - */ -export function renderCancelReport(jobId, outcome) { - if (outcome.canceled) { - const detail = outcome.reason ?? "killed"; - return `Job ${jobId}: canceled (${detail}).\n`; - } - switch (outcome.reason) { - case "not-found": - return `Job ${jobId}: not found in this workspace.\n`; - case "not-cancelable": - return `Job ${jobId}: already finished (status: ${outcome.record?.status ?? "unknown"}); nothing to cancel.\n`; - default: - return `Job ${jobId}: not canceled (${outcome.reason ?? "unknown reason"}).\n`; - } -} diff --git a/plugins/agy/scripts/lib/secrets.mjs b/plugins/agy/scripts/lib/secrets.mjs deleted file mode 100644 index bd89d33..0000000 --- a/plugins/agy/scripts/lib/secrets.mjs +++ /dev/null @@ -1,64 +0,0 @@ -// secrets.mjs — best-effort secret detection for review material. -// -// The Node companion's /agy:review and /agy:adversarial-review guard the -// material sent to Gemini so credentials don't get shipped to a third -// party. Best-effort, NOT a replacement for gitleaks/trufflehog — -// conservative patterns to keep false positives low. -// -// Two entry points: -// - scanDiffForSecrets(diff): scans the ADDED lines of a unified diff. -// - scanTextForSecrets(text): scans raw text (e.g. the FULL content of a -// changed file that gets shipped as context — a secret on an unchanged -// line would never appear in the diff's `+` lines, so the full content -// must be scanned too). -// -// The Bash wrapper (_scan_text_for_secrets / _scan_diff_for_secrets in -// agy-run.sh) keeps the same pattern set; both are exercised by tests so -// they don't drift. - -// Case-insensitive (`/i`) to match the Bash wrapper, which runs `grep -aEi`. -const PATTERNS = [ - [/AKIA[0-9A-Z]{16}/i, "AWS access key"], - [/ASIA[0-9A-Z]{16}/i, "AWS STS token"], - [/gh[pousr]_[A-Za-z0-9]{36,}/i, "GitHub personal access token"], - [/github_pat_[A-Za-z0-9_]{40,}/i, "GitHub fine-grained PAT"], - [/xox[baprs]-[A-Za-z0-9-]{10,}/i, "Slack token"], - // Modern API keys carry dashes after a specific prefix, so they need - // their own patterns — the generic legacy `sk-` below stops at the - // first dash and would miss them. - [/sk-ant-[A-Za-z0-9_-]{20,}/i, "Anthropic API key"], - [/sk-proj-[A-Za-z0-9_-]{20,}/i, "OpenAI project key"], - [/sk-[A-Za-z0-9]{20,}/i, "OpenAI legacy API key"], - [/-----BEGIN [A-Z ]*PRIVATE KEY-----/i, "PEM private key block"], - [ - /(api[_-]?key|secret|token|password|access[_-]?key)\s*[=:]\s*["']?[A-Za-z0-9_+/=\-]{16,}/i, - "inline credential assignment", - ], -]; - -/** - * Scan raw text against the secret patterns. Returns an array of matched - * pattern labels (empty if clean). Order of labels follows PATTERNS. - */ -export function scanTextForSecrets(text) { - if (!text) return []; - const hits = []; - for (const [re, label] of PATTERNS) { - if (re.test(text)) hits.push(label); - } - return hits; -} - -/** - * Scan only the ADDED lines of a unified diff (lines starting with a - * single `+`, excluding the `+++` file header). Returns an array of - * matched pattern labels (empty if clean). - */ -export function scanDiffForSecrets(diff) { - if (!diff) return []; - const added = diff - .split("\n") - .filter((l) => l.startsWith("+") && !l.startsWith("+++")); - if (added.length === 0) return []; - return scanTextForSecrets(added.join("\n")); -} diff --git a/plugins/agy/scripts/lib/state.mjs b/plugins/agy/scripts/lib/state.mjs deleted file mode 100644 index 3fa6823..0000000 --- a/plugins/agy/scripts/lib/state.mjs +++ /dev/null @@ -1,247 +0,0 @@ -// state.mjs — on-disk job registry for the stateful slash commands -// (/agy:rescue --background, /agy:status, /agy:result, /agy:cancel). -// -// Layout (all paths relative to the workspace root): -// -// .agy-plugin/ -// ├── jobs/.json one record per job; canonical state -// ├── logs/.log captured stdout/stderr of the agy run -// └── runtime/.pid optional, written by the background worker -// -// Records are atomic-written via lib/fs.mjs:writeJson, so a torn -// read is not possible. Listing is best-effort: a job file that -// JSON-parses cleanly is included; one that fails parsing is skipped -// with a warning to stderr (not a fatal error — we don't want one -// corrupt record to break /agy:status). - -import path from "node:path"; -import { promises as fsp } from "node:fs"; -import { randomBytes } from "node:crypto"; - -import { ensureDir, readJson, writeJson, pathExists, nowIso } from "./fs.mjs"; - -export const STATE_DIR_NAME = ".agy-plugin"; - -const VALID_STATUSES = new Set([ - "pending", - "running", - "completed", - "failed", - "canceled", -]); - -const VALID_KINDS = new Set([ - "rescue", - "research", - "review", - "adversarial-review", -]); - -export function stateDir(workspaceRoot) { - return path.join(workspaceRoot, STATE_DIR_NAME); -} - -export function jobsDir(workspaceRoot) { - return path.join(stateDir(workspaceRoot), "jobs"); -} - -export function logsDir(workspaceRoot) { - return path.join(stateDir(workspaceRoot), "logs"); -} - -export function runtimeDir(workspaceRoot) { - return path.join(stateDir(workspaceRoot), "runtime"); -} - -export function jobRecordPath(workspaceRoot, jobId) { - return path.join(jobsDir(workspaceRoot), `${jobId}.json`); -} - -export function jobLogPath(workspaceRoot, jobId) { - return path.join(logsDir(workspaceRoot), `${jobId}.log`); -} - -export function jobPidPath(workspaceRoot, jobId) { - return path.join(runtimeDir(workspaceRoot), `${jobId}.pid`); -} - -/** - * Generate a short, human-friendly, randomized job ID. - * Format: `agy-<8 hex>`. Collisions are vanishingly unlikely (~1 in - * 4 billion) but we don't depend on uniqueness across machines. - */ -export function generateJobId() { - return `agy-${randomBytes(4).toString("hex")}`; -} - -/** - * Strict job-id shape check: matches what `generateJobId` produces. - * Shorter `agy-xxxx` strings are accepted as PREFIXES by resolveJob - * but are not full ids — keep this strict so the resolver knows to - * go down the prefix branch instead of doing a direct read. - */ -export function isValidJobId(s) { - return typeof s === "string" && /^agy-[a-f0-9]{8}$/.test(s); -} - -/** - * Best-effort: add `.agy-plugin/` to the workspace's LOCAL Git exclude - * (`.git/info/exclude`) so the plugin's job-state dir doesn't clutter the - * user's `git status`. That file is the idiomatic place for repo-local, - * uncommitted ignores — it never touches their tracked `.gitignore`. No-op - * if the workspace isn't a plain git repo (e.g. a worktree whose `.git` is - * a file), or on any error. - */ -export async function ensureGitExclude(workspaceRoot) { - try { - const gitDir = path.join(workspaceRoot, ".git"); - const st = await fsp.stat(gitDir).catch(() => null); - if (!st || !st.isDirectory()) return; - const infoDir = path.join(gitDir, "info"); - await ensureDir(infoDir); - const excludeFile = path.join(infoDir, "exclude"); - let current = ""; - try { - current = await fsp.readFile(excludeFile, "utf8"); - } catch { - /* no exclude file yet — we'll create it */ - } - if (/^\s*\.agy-plugin\/?\s*$/m.test(current)) return; // already excluded - const sep = current && !current.endsWith("\n") ? "\n" : ""; - await fsp.appendFile( - excludeFile, - `${sep}# Added by the agy plugin — local job-state dir (not committed).\n.agy-plugin/\n`, - ); - } catch { - /* best-effort: never fail a job over gitignore hygiene */ - } -} - -/** - * Ensure all directories under .agy-plugin/ exist. Cheap to call - * repeatedly; callers don't have to remember to invoke this first. - */ -export async function ensureStateDirs(workspaceRoot) { - await ensureDir(jobsDir(workspaceRoot)); - await ensureDir(logsDir(workspaceRoot)); - await ensureDir(runtimeDir(workspaceRoot)); - await ensureGitExclude(workspaceRoot); -} - -/** - * Create a new job record on disk. Caller supplies `kind`, `task`, - * and any optional metadata. Returns the full record including the - * generated id, createdAt timestamp, default fields. - */ -export async function createJob(workspaceRoot, partial) { - if (!VALID_KINDS.has(partial.kind)) { - throw new Error(`createJob: invalid kind '${partial.kind}'`); - } - await ensureStateDirs(workspaceRoot); - const id = partial.id ?? generateJobId(); - const record = { - id, - kind: partial.kind, - task: partial.task ?? "", - model: partial.model ?? null, - workspaceRoot, - createdAt: nowIso(), - startedAt: null, - completedAt: null, - status: "pending", - exitCode: null, - pid: null, - logFile: path.relative(workspaceRoot, jobLogPath(workspaceRoot, id)), - args: partial.args ?? [], - background: !!partial.background, - meta: partial.meta ?? {}, - }; - await writeJson(jobRecordPath(workspaceRoot, id), record); - return record; -} - -/** - * Read a job by id. Returns the record, or `null` if no such job. - * Throws only on I/O errors other than ENOENT, and on parse errors. - */ -export async function readJob(workspaceRoot, jobId) { - if (!isValidJobId(jobId)) return null; - const file = jobRecordPath(workspaceRoot, jobId); - return readJson(file, null); -} - -/** - * Merge-update an existing job. Refuses to write if the record is - * missing. Returns the merged record. - */ -export async function updateJob(workspaceRoot, jobId, updates) { - const current = await readJob(workspaceRoot, jobId); - if (!current) { - throw new Error(`updateJob: no such job '${jobId}'`); - } - if (updates.status && !VALID_STATUSES.has(updates.status)) { - throw new Error(`updateJob: invalid status '${updates.status}'`); - } - const merged = { - ...current, - ...updates, - // Preserve the original id even if the caller passes one. - id: current.id, - // Touch lastUpdatedAt every time; consumers can use it as a - // freshness heuristic without a separate field on each call. - lastUpdatedAt: nowIso(), - }; - await writeJson(jobRecordPath(workspaceRoot, jobId), merged); - return merged; -} - -/** - * List all job records, newest first by `createdAt`. Records that - * fail to parse are skipped with a stderr warning (not thrown). - * - * Pass `{ kind: "rescue" }` to filter, or `{ limit: N }` to cap. - */ -export async function listJobs(workspaceRoot, { kind, limit } = {}) { - const dir = jobsDir(workspaceRoot); - if (!(await pathExists(dir))) return []; - let entries; - try { - entries = await fsp.readdir(dir); - } catch { - return []; - } - const records = []; - for (const entry of entries) { - if (!entry.endsWith(".json")) continue; - const file = path.join(dir, entry); - try { - const rec = await readJson(file, null); - if (rec) records.push(rec); - } catch (err) { - process.stderr.write(`agy-companion: skipping corrupt job ${entry}: ${err.message}\n`); - } - } - records.sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? "")); - const filtered = kind ? records.filter((r) => r.kind === kind) : records; - return typeof limit === "number" ? filtered.slice(0, limit) : filtered; -} - -/** - * Delete a job record and its log. Returns true if anything was - * removed, false if the job didn't exist. Used by future cleanup - * commands; not exposed as a slash command yet. - */ -export async function deleteJob(workspaceRoot, jobId) { - const recPath = jobRecordPath(workspaceRoot, jobId); - if (!(await pathExists(recPath))) return false; - try { - await fsp.rm(recPath); - } catch { /* ignore */ } - try { - await fsp.rm(jobLogPath(workspaceRoot, jobId)); - } catch { /* missing log is fine */ } - try { - await fsp.rm(jobPidPath(workspaceRoot, jobId)); - } catch { /* missing pid is fine */ } - return true; -} diff --git a/plugins/agy/scripts/lib/tracked-jobs.mjs b/plugins/agy/scripts/lib/tracked-jobs.mjs deleted file mode 100644 index d8d1cf4..0000000 --- a/plugins/agy/scripts/lib/tracked-jobs.mjs +++ /dev/null @@ -1,528 +0,0 @@ -// tracked-jobs.mjs — start, supervise, and tear down background -// agy jobs. The split-of-concerns vs state.mjs is intentional: -// state.mjs is pure I/O on the record; this module owns the process -// lifecycle that produces those records. - -import { promises as fsp, createWriteStream } from "node:fs"; -import { spawn } from "node:child_process"; -import { fileURLToPath } from "node:url"; -import path from "node:path"; -import os from "node:os"; - -import { - createJob, - readJob, - updateJob, - jobLogPath, - jobPidPath, -} from "./state.mjs"; -import { ensureDir, writeAtomic, nowIso } from "./fs.mjs"; -import { processAlive, terminate } from "./process.mjs"; -import { captureAnswer } from "./transcript.mjs"; - -const COMPANION_PATH = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - "..", - "agy-companion.mjs", -); - -/** - * Create a job record and (if `background: true`) launch a detached - * worker that runs `agy --print` and streams its output to the log. - * Returns the created record (with `pid` populated for background - * jobs, or `null` for foreground — callers run foreground inline). - * - * Required `partial` fields: - * - kind, task, prompt (the wrapped prompt to send to agy) - * - * Optional: - * - model, args (forwarded to agy), background (default true), - * agyBin (override the detected agy path). - */ -export async function startTrackedJob(workspaceRoot, partial) { - const record = await createJob(workspaceRoot, { - kind: partial.kind, - task: partial.task, - model: partial.model, - args: partial.args ?? [], - background: partial.background ?? true, - meta: { - prompt: partial.prompt, - agyBin: partial.agyBin ?? null, - // When set (worktree isolation), agy runs in / writes to this - // directory instead of the real workspaceRoot. Job state still - // lives under workspaceRoot. - executionRoot: partial.executionRoot ?? null, - // When set (Design A+ review staging), agy runs in this dir, reads - // the pre-staged diff/files from it, and writes its response there; - // the repo is never added to --add-dir. - stageDir: partial.stageDir ?? null, - }, - }); - - if (!partial.background) { - // Caller wants to run inline; we just return the record and they - // can invoke runForegroundJob(). - return record; - } - - const logFile = jobLogPath(workspaceRoot, record.id); - await ensureDir(path.dirname(logFile)); - // O_APPEND so concurrent stderr/stdout writes from the detached - // worker stay ordered relative to each other. - const logFh = await fsp.open(logFile, "a", 0o600); - try { - const child = spawn( - process.execPath, - [COMPANION_PATH, "_run-job", record.id], - { - cwd: workspaceRoot, - detached: true, - stdio: ["ignore", logFh.fd, logFh.fd], - env: { ...process.env, AGY_JOB_WORKSPACE: workspaceRoot }, - }, - ); - child.unref(); - await writeAtomic(jobPidPath(workspaceRoot, record.id), `${child.pid}\n`); - return await updateJob(workspaceRoot, record.id, { - status: "running", - startedAt: nowIso(), - pid: child.pid, - }); - } finally { - await logFh.close(); - } -} - -/** - * Worker entry point. Invoked as `node agy-companion.mjs _run-job ` - * by the detached child started in `startTrackedJob`. Reads the job - * record, executes the command, updates the record on completion. - * - * This function is exported so it can be unit-tested without - * actually invoking agy — the test passes `runner` to inject a fake. - */ -export async function runJobWorker(workspaceRoot, jobId, opts = {}) { - const record = await readJob(workspaceRoot, jobId); - if (!record) { - throw new Error(`runJobWorker: no such job '${jobId}'`); - } - - // Output routing. Two contexts call this: - // - The detached background worker: its stdout fd is already - // redirected to the job log, so writing to process.stdout IS - // writing to the log. opts.teeLogFile is unset. - // - The foreground caller (cmdRescue without --background): runs - // in-process with stdout = the user's terminal. To persist the - // output for a later /agy:result, we ALSO open the log file and - // tee every write to it. opts.teeLogFile = the log path. - // - // Either way, `sink(text)` is the single choke point all output - // flows through, so the captured log and the live view never drift. - let teeStream = null; - if (opts.teeLogFile) { - await ensureDir(path.dirname(opts.teeLogFile)); - teeStream = createWriteStream(opts.teeLogFile, { flags: "a", mode: 0o600 }); - } - const sink = (text) => { - process.stdout.write(text); - if (teeStream) teeStream.write(text); - }; - - // Mark running + stamp startedAt (foreground records were left - // pending before this fix; background already set these in - // startTrackedJob but re-stamping is harmless and merge-safe). - await updateJob(workspaceRoot, jobId, { - status: "running", - startedAt: record.startedAt ?? nowIso(), - }); - - sink(`[agy-job ${jobId}] starting at ${nowIso()}\n`); - sink(`[agy-job ${jobId}] task: ${record.task}\n`); - if (record.model) { - sink(`[agy-job ${jobId}] model: ${record.model}\n`); - } - sink(`[agy-job ${jobId}] ---\n`); - - const runner = opts.runner ?? defaultAgyRunner; - let exitCode = null; - let failed = false; - try { - // Pass the sink so the runner forwards agy's stdout/stderr through - // the same choke point (tests inject their own runner and may - // ignore the second arg). - exitCode = await runner(record, { sink }); - } catch (err) { - sink(`[agy-job ${jobId}] worker error: ${err?.stack ?? err}\n`); - failed = true; - } - - const finalStatus = failed - ? "failed" - : exitCode === 0 - ? "completed" - : "failed"; - - // Don't clobber a `canceled` status: if /agy:cancel terminated us and - // already marked the record canceled, our death throes here must not - // overwrite it back to failed (status race fixed). - const latest = await readJob(workspaceRoot, jobId); - if (latest && latest.status === "canceled") { - sink(`[agy-job ${jobId}] (job was canceled; leaving status=canceled)\n`); - if (teeStream) await new Promise((resolve) => teeStream.end(resolve)); - return "canceled"; - } - - await updateJob(workspaceRoot, jobId, { - status: finalStatus, - exitCode: exitCode, - completedAt: nowIso(), - }); - // Best-effort PID file cleanup so /agy:status doesn't dangle. - try { await fsp.rm(jobPidPath(workspaceRoot, jobId)); } catch { /* ok */ } - sink(`[agy-job ${jobId}] ---\n`); - sink(`[agy-job ${jobId}] done: status=${finalStatus} exitCode=${exitCode}\n`); - - // Flush + close the tee stream before returning so a follow-up - // /agy:result reads a complete log. - if (teeStream) { - await new Promise((resolve) => teeStream.end(resolve)); - } - return finalStatus; -} - -/** - * The default agy invocation strategy. Dispatches by job kind: - * - * - review / adversarial-review (read-only) → runReviewViaTranscript: - * run agy under --sandbox with the staged materials in --add-dir, with - * NO write_file injection and NO --dangerously-skip-permissions, then - * read the answer back from agy's own on-disk transcript - * (lib/transcript.mjs). Genuinely read-only — agy's read-only tools - * run without approval, and it never gets repo or write access. - * - * - rescue (write-capable) → the write_file path below: agy edits files - * for real, so it needs auto-approval (--dangerously-skip-permissions) - * and writes its answer to a temp file we read back. Safety comes from - * cmdRescue's guards (clean-tree refusal / --isolate worktree), not - * from sandboxing. - * - * Both paths work around agy issue #76: `agy --print` flushes ZERO bytes - * to a non-TTY stdout (the response is generated but the "drip" writer - * only targets a real terminal), and stdin is ignored (=/dev/null) so agy - * can't hang on a non-TTY stdin. Returns the agy exit code (0 = a usable - * answer was captured). - */ -// Max bytes for the prompt argv entry. Windows' CreateProcess caps the -// whole command line at 32767 chars; leave generous margin for the exe -// path and the other flags. -const MAX_PROMPT_BYTES = 28000; - -/** - * Assemble body + suffix so the result stays under MAX_PROMPT_BYTES. - * The suffix (the write_file instruction) is always kept intact; only - * the body is trimmed, with a visible marker so the model knows context - * was cut. Exported for unit testing. - */ -export function capPromptForArgv(body, suffix, max = MAX_PROMPT_BYTES) { - const suffixBytes = Buffer.byteLength(suffix, "utf8"); - const marker = - "\n\n[...content truncated to fit the OS command-line length limit; " + - "some diff/file context was omitted — read files directly if needed...]"; - const budget = max - suffixBytes - Buffer.byteLength(marker, "utf8"); - if (Buffer.byteLength(body, "utf8") <= budget) { - return body + suffix; - } - // Trim by bytes (slice by chars is fine for our mostly-ASCII prompts; - // re-check and shave if a multibyte char pushed us over). - let trimmed = body.slice(0, Math.max(0, budget)); - while (Buffer.byteLength(trimmed, "utf8") > budget && trimmed.length > 0) { - trimmed = trimmed.slice(0, -64); - } - return trimmed + marker + suffix; -} - -// Repo-location env hints stripped from agy's environment for READ-ONLY runs -// (defense in depth: the repo is never in --add-dir, but don't hand agy a -// pointer to it either). rescue KEEPS them — it legitimately operates on the -// repo. Mirrors agy-run.sh's `env -u …`. -const REPO_ENV_HINTS = ["CLAUDE_PROJECT_DIR", "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR"]; -function readOnlyEnv() { - const e = { ...process.env }; - for (const k of REPO_ENV_HINTS) delete e[k]; - return e; -} - -async function defaultAgyRunner(record, { sink } = {}) { - const emit = sink ?? ((t) => process.stdout.write(t)); - const { meta } = record; - const prompt = meta?.prompt; - if (!prompt) { - throw new Error("defaultAgyRunner: record has no meta.prompt"); - } - const agyBin = meta?.agyBin ?? "agy"; - - // Read-only review commands capture output from agy's OWN on-disk - // transcript — no write_file injection, no --dangerously-skip-permissions - // (see lib/transcript.mjs + runReviewViaTranscript below). agy's read-only - // tools (list_dir/view_file) run without approval, so it reads the staged - // materials under --sandbox while never being able to write to the repo. - // rescue falls through to the write-capable path: it legitimately edits - // files, so it keeps write_file + --dangerously-skip-permissions, gated by - // cmdRescue's clean-tree / --isolate guards. - if (record.kind === "review" || record.kind === "adversarial-review") { - return runReviewViaTranscript(record, { emit }); - } - - // Design A+ : review commands stage the diff + full files into a - // stageDir they own and pass it via meta.stageDir. We run agy IN that - // dir (read diff/files from disk, write response there), --add-dir it, - // and never touch the repo. For rescue/ask, stageDir is unset and we - // create our own throwaway outDir for the response. - const stageDir = meta?.stageDir ?? null; - const outDir = stageDir ?? (await fsp.mkdtemp(path.join(os.tmpdir(), "agy-job-"))); - const outFile = path.join(outDir, "response.md"); - const suffix = - `\n\n---\n` + - `OUTPUT INSTRUCTION (required): Use the write_file tool to write your ` + - `COMPLETE response to this exact path:\n${outFile}\n` + - `Do NOT print the answer to chat — that path is your only deliverable. ` + - `After writing the file, stop.`; - // agy --print takes the whole prompt as a single argv entry, so the - // total must stay under the OS command-line limit (~32 KB on Windows) - // or spawn fails with ENAMETOOLONG. Truncate the body if needed while - // always preserving the write_file suffix (otherwise agy wouldn't know - // where to put the answer). - const augmented = capPromptForArgv(prompt, suffix); - - // Where agy actually runs / is allowed to write. Defaults to the - // workspace; worktree isolation points it at a throwaway copy so the - // user's real tree is never touched. - const execRoot = record.meta?.executionRoot ?? record.workspaceRoot; - const writeCapable = record.kind === "rescue"; - // agy runs in the stage dir (review) or the execRoot (rescue/ask). - const cwd = stageDir ?? execRoot; - // Auto-approve ONLY for write-capable kinds (rescue). review/adversarial - // short-circuit to the transcript path before reaching here, but gate the - // flag explicitly so a future non-write kind can never silently - // auto-approve through this path (defense in depth). - const args = []; - if (writeCapable) args.push("--dangerously-skip-permissions"); - if (!writeCapable) args.push("--sandbox"); - args.push("--add-dir", outDir); - // rescue gets repo write access; review/ask never do (the repo is not - // in --add-dir at all — for review everything it needs is in stageDir). - if (writeCapable) args.push("--add-dir", execRoot); - args.push(...(record.args ?? [])); - args.push("--print", augmented); - - const code = await new Promise((resolve) => { - const child = spawn(agyBin, args, { - // stdin ignored (=/dev/null) to dodge the non-TTY hang; stdout ignored - // because this path takes agy's answer from the write_file response, not - // stdout; stderr piped so real agy errors still surface in the log. - stdio: ["ignore", "ignore", "pipe"], - cwd, - // Read-only kinds (ask) run with repo-location hints stripped; rescue - // legitimately edits the repo, so it keeps the full environment. - env: writeCapable ? process.env : readOnlyEnv(), - }); - child.stderr.on("data", (chunk) => emit(chunk.toString())); - child.on("error", (err) => { - emit(`[agy-job ${record.id}] spawn error: ${err.message}\n`); - resolve(127); - }); - child.on("close", (c) => resolve(c ?? 0)); - }); - - // Read agy's written response and emit it so it lands in the job log. - // The presence of a non-empty response file is the real success - // signal — agy's own exit code is unreliable in --print mode (it has - // been observed to exit non-zero even after writing a complete - // answer). So we key success on the file, not on `code`. - let produced = false; - try { - const content = await fsp.readFile(outFile, "utf8"); - if (content.length > 0) { - emit(content.endsWith("\n") ? content : content + "\n"); - produced = true; - } else { - emit(`[agy-job ${record.id}] agy wrote an empty response file (issue #76 workaround produced nothing).\n`); - } - } catch { - emit(`[agy-job ${record.id}] agy produced no response file — it may have timed out or declined write_file.\n`); - } finally { - // Always clean up the work dir — it's the response temp (rescue/ask) - // or the review stage dir (meta.stageDir). The worker is the last - // reader of response.md, so cleaning here also closes the - // background-review temp leak (the detached worker, not the - // already-exited parent, removes it). runReviewCommand's own - // cleanup is then just an idempotent belt-and-suspenders. - await fsp.rm(outDir, { recursive: true, force: true }).catch(() => {}); - } - // 0 when we got a usable response; otherwise surface agy's code (or 1). - if (produced) return 0; - return code === 0 ? 1 : code; -} - -/** - * Read-only capture path for review / adversarial-review. - * - * Runs `agy --print` under --sandbox with ONLY the staged materials in - * --add-dir and NO --dangerously-skip-permissions, then recovers the - * model's answer from agy's own conversation transcript on disk (see - * lib/transcript.mjs). This removes both crutches for the read-only - * commands: no write_file in the prompt, no auto-approve. agy's read-only - * tools (list_dir/view_file) execute without approval, so it can read the - * staged diff/files; it cannot write anywhere the repo lives. - * - * Returns 0 when a non-empty answer was captured; otherwise agy's exit - * code (or 1). The captured answer is the success signal, not the exit - * code (agy's --print code is unreliable — see issue #76). - */ -async function runReviewViaTranscript(record, { emit }) { - const meta = record.meta ?? {}; - const agyBin = meta.agyBin ?? "agy"; - const prompt = meta.prompt; - - // review always stages to meta.stageDir; tolerate a missing one by - // making a throwaway dir so the function is still usable standalone. - const stageDir = - meta.stageDir ?? (await fsp.mkdtemp(path.join(os.tmpdir(), "agy-job-"))); - const logFile = path.join(stageDir, "agy-run.log"); - - // --sandbox restricts terminal/shell tools where the OS supports it; - // --add-dir grants read access to the staged diff/files only (the repo - // is never added); --log-file lets us recover the conversation id and - // thus the transcript, race-free. - const args = ["--sandbox", "--add-dir", stageDir, "--log-file", logFile]; - args.push(...(record.args ?? [])); - args.push("--print", prompt); - - let stdoutBuf = ""; - const code = await new Promise((resolve) => { - const child = spawn(agyBin, args, { - // stdin ignored to dodge the non-TTY hang. stdout is captured: agy - // >= 1.0.15 fixed the #76 bug that swallowed non-TTY stdout, so it's - // now the fast path (the transcript is the fallback). stderr piped so - // real agy errors still surface in the log. - stdio: ["ignore", "pipe", "pipe"], - cwd: stageDir, - // Read-only review: strip repo-location hints (defense in depth). - env: readOnlyEnv(), - }); - // setEncoding drives the stream's StringDecoder, which buffers a partial - // multibyte UTF-8 sequence split across chunk boundaries. `chunk.toString()` - // per-chunk would corrupt such a char (→ U+FFFD) for non-ASCII answers that - // span more than one read. - child.stdout.setEncoding("utf8"); - child.stdout.on("data", (chunk) => { stdoutBuf += chunk; }); - child.stderr.on("data", (chunk) => emit(chunk.toString())); - child.on("error", (err) => { - emit(`[agy-job ${record.id}] spawn error: ${err.message}\n`); - resolve(127); - }); - child.on("close", (c) => resolve(c ?? 0)); - }); - - let produced = false; - try { - // Prefer agy's direct stdout (the #76 fix); fall back to reading agy's - // own transcript for older agy where non-TTY stdout is still empty. - let answer = stdoutBuf.trim(); - let conversationId = null; - if (!answer) { - ({ answer, conversationId } = await captureAnswer({ logFile, cwd: stageDir })); - } - if (answer && answer.trim()) { - emit(answer.endsWith("\n") ? answer : answer + "\n"); - produced = true; - } else { - emit( - `[agy-job ${record.id}] no answer captured from agy's stdout or transcript ` + - `(conversationId=${conversationId ?? "?"}). agy may have timed out ` + - `or been interrupted; see the run log at ${logFile}.\n`, - ); - } - } finally { - // The worker is the last reader of the stage dir, so clean it here — - // this also closes the background-review temp leak (the detached - // worker, not the already-returned parent, owns teardown). - // runReviewCommand's own cleanup is then an idempotent no-op. - await fsp.rm(stageDir, { recursive: true, force: true }).catch(() => {}); - } - if (produced) return 0; - return code === 0 ? 1 : code; -} - -/** - * Cancel a job. Idempotent: returns immediately if the job is already - * finished. Updates the record to `canceled` on success. - */ -export async function cancelJob(workspaceRoot, jobId, { graceMs = 5000 } = {}) { - const record = await readJob(workspaceRoot, jobId); - if (!record) return { canceled: false, reason: "not-found" }; - if (record.status !== "running" && record.status !== "pending") { - return { canceled: false, reason: "not-cancelable", record }; - } - if (!record.pid) { - await updateJob(workspaceRoot, jobId, { - status: "canceled", - completedAt: nowIso(), - }); - return { canceled: true, reason: "no-pid-marking-canceled" }; - } - const wasAlive = processAlive(record.pid); - if (wasAlive) { - await terminate(record.pid, { graceMs }); - } - await updateJob(workspaceRoot, jobId, { - status: "canceled", - completedAt: nowIso(), - exitCode: null, - }); - try { await fsp.rm(jobPidPath(workspaceRoot, jobId)); } catch { /* ok */ } - // A killed worker's finally{} never runs, so the review stage dir would - // leak. Clean it up best-effort here (it lives under the OS temp dir). - if (record.meta?.stageDir) { - await fsp.rm(record.meta.stageDir, { recursive: true, force: true }).catch(() => {}); - } - return { canceled: true, reason: wasAlive ? "killed" : "already-dead" }; -} - -/** - * Block until a job reaches a terminal status, or the timeout fires. - * Returns the final record (with refreshed liveness if applicable). - * Polls — no fs.watch, since the file rename via writeAtomic doesn't - * always emit `change` events on every platform. - */ -export async function waitForJob(workspaceRoot, jobId, opts = {}) { - const { timeoutMs = 600_000, pollMs = 500 } = opts; - const deadline = Date.now() + timeoutMs; - while (true) { - const rec = await readJob(workspaceRoot, jobId); - if (!rec) return null; - if (rec.status !== "running" && rec.status !== "pending") { - return rec; - } - // If the record claims running but the PID is dead, give the - // worker one more poll cycle and then forcibly mark it. - if (rec.status === "running" && rec.pid && !processAlive(rec.pid)) { - await new Promise((r) => setTimeout(r, pollMs)); - const rec2 = await readJob(workspaceRoot, jobId); - if (rec2 && (rec2.status === "running" || rec2.status === "pending")) { - const updated = await updateJob(workspaceRoot, jobId, { - status: "failed", - completedAt: nowIso(), - meta: { ...rec2.meta, livenessDowngradedBy: "waitForJob" }, - }); - return updated; - } - return rec2; - } - if (Date.now() >= deadline) { - return rec; // caller decides what to do with a still-running job. - } - await new Promise((r) => setTimeout(r, pollMs)); - } -} diff --git a/plugins/agy/scripts/lib/transcript.mjs b/plugins/agy/scripts/lib/transcript.mjs deleted file mode 100644 index 00e35ee..0000000 --- a/plugins/agy/scripts/lib/transcript.mjs +++ /dev/null @@ -1,253 +0,0 @@ -// transcript.mjs — FALLBACK capture of an `agy --print` answer by reading -// agy's own on-disk conversation transcript, for older `agy` where non-TTY -// stdout is unusable. -// -// Why this exists -// --------------- -// Older `agy` (< 1.0.15) flushed ZERO bytes to a non-TTY stdout (issue #76): -// the response was generated but the "drip" typewriter only targeted a real -// terminal, so a subprocess capturing stdout got nothing. agy 1.0.15 FIXED -// that, so the plugin now reads stdout directly as the primary path (see the -// capture sites in agy-run.sh / tracked-jobs.mjs / agy-run.ps1) and only -// falls back to this transcript reader when stdout comes back empty. -// -// agy ALWAYS persists the conversation transcript to disk — on every --print -// run, regardless of TTY, with NO tool permission and NO auto-approve. So the -// fallback runs agy strictly read-only and reads the model's answer back from: -// -// /brain//.system_generated/logs/transcript.jsonl -// -// The conversation id is printed to the run's own --log-file as the line -// "Created conversation ", so we recover it race-free (no guessing, -// no newest-by-mtime race against other concurrent agy runs). -// -// Either way the read-only commands (ask / review / adversarial-review) need -// neither a write_file injection nor --dangerously-skip-permissions. Validated -// live on agy 1.1.0 (see SECURITY.md "Read-only capture"). - -import { promises as fsp, realpathSync } from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import process from "node:process"; -import { fileURLToPath } from "node:url"; - -const UUID_RE = - "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; - -/** - * Resolve agy's CLI store directory — the one that contains `brain/`, - * `conversations/`, and `cache/`. Resolution order: - * 1. AGY_STORE_DIR (full path to the antigravity-cli store; tests) - * 2. GEMINI_DIR (agy's .gemini override) → /antigravity-cli - * 3. /.gemini/antigravity-cli (the default, all platforms) - * - * Uses os.homedir() rather than $HOME: under Git Bash $HOME is an MSYS - * path (/c/Users/...) that Node's fs cannot resolve on Windows. - */ -export function agyStoreDir(env = process.env, homedir = os.homedir()) { - if (env.AGY_STORE_DIR) return env.AGY_STORE_DIR; - if (env.GEMINI_DIR) return path.join(env.GEMINI_DIR, "antigravity-cli"); - return path.join(homedir, ".gemini", "antigravity-cli"); -} - -/** - * Recover agy's ACTUAL CLI data directory from its --log-file. On startup - * agy logs `... CLI app data directory: `, so we read the real - * location instead of assuming `/.gemini/antigravity-cli`. This - * makes the transcript path correct on every OS (Windows / macOS / Linux / - * WSL) by construction — wherever agy says it put its data, that's where we - * look. Returns the last such path (trailing whitespace/CR trimmed), or - * null if the log didn't reveal it. - */ -export function parseStoreDir(logText) { - if (!logText) return null; - const re = /CLI app data directory:\s*(.+)/g; - let m; - let last = null; - while ((m = re.exec(logText)) !== null) last = m[1]; - return last ? last.replace(/[\r\n\s]+$/, "") : null; -} - -/** - * Return the last "Created conversation " id from an agy --log-file's - * text, or null. We take the LAST match: a single --print run logs exactly - * one such line, but taking the last is safe if agy ever logs more. - */ -export function parseConversationId(logText) { - if (!logText) return null; - const re = new RegExp(`Created conversation (${UUID_RE})`, "g"); - let m; - let last = null; - while ((m = re.exec(logText)) !== null) last = m[1]; - return last; -} - -/** - * Extract the model's FINAL answer from a transcript.jsonl: concatenate the - * `content` of MODEL / PLANNER_RESPONSE lines that carry NO tool call. - * - * agy narrates intermediate steps ("I will read the file…") as - * PLANNER_RESPONSE lines that have BOTH `content` AND a `tool_calls` entry — - * those are thinking-out-loud, not the answer, so we skip any line with a - * tool call and keep only the terminal response(s). Also skips tool-result - * lines (type LIST_DIRECTORY / VIEW_FILE / …). Returns "" if none found. - */ -export function extractAnswerFromTranscript(jsonlText) { - if (!jsonlText) return ""; - const parts = []; - for (const line of jsonlText.split(/\r?\n/)) { - const s = line.trim(); - if (!s) continue; - let o; - try { - o = JSON.parse(s); - } catch { - continue; // tolerate a partially-flushed trailing line - } - const hasToolCall = Array.isArray(o?.tool_calls) && o.tool_calls.length > 0; - if ( - o && - o.source === "MODEL" && - o.type === "PLANNER_RESPONSE" && - !hasToolCall && - typeof o.content === "string" && - o.content.trim() - ) { - parts.push(o.content.trim()); - } - } - return parts.join("\n\n"); -} - -/** Absolute path to a conversation's transcript.jsonl within a store dir. */ -export function transcriptPathFor(storeDir, conversationId) { - return path.join( - storeDir, - "brain", - conversationId, - ".system_generated", - "logs", - "transcript.jsonl", - ); -} - -/** - * Fallback id recovery: map a workspace directory → conversation id via - * /cache/last_conversations.json. Path keys are compared after - * normalizing separators + case (Windows/macOS filesystems are - * case-insensitive and agy stores backslash paths). - */ -export async function conversationIdForWorkspace(storeDir, workspaceDir) { - if (!workspaceDir) return null; - let obj; - try { - obj = JSON.parse( - await fsp.readFile( - path.join(storeDir, "cache", "last_conversations.json"), - "utf8", - ), - ); - } catch { - return null; - } - const norm = (p) => String(p).replace(/[\\/]+/g, "/").replace(/\/+$/, "").toLowerCase(); - const want = norm(workspaceDir); - for (const [k, v] of Object.entries(obj)) { - if (norm(k) === want) return v; - } - return null; -} - -/** - * Read the model's answer for a conversation, retrying briefly: the store - * manager may not have flushed the final transcript line by the instant - * the agy process exits. Returns { answer, transcriptPath }. - */ -export async function readTranscriptAnswer(storeDir, conversationId, opts = {}) { - const { retries = 12, delayMs = 125, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = - opts; - if (!conversationId) return { answer: "", transcriptPath: null }; - const file = transcriptPathFor(storeDir, conversationId); - let text = ""; - for (let attempt = 0; attempt <= retries; attempt++) { - try { - text = await fsp.readFile(file, "utf8"); - const answer = extractAnswerFromTranscript(text); - if (answer) return { answer, transcriptPath: file }; - } catch (err) { - if (err.code !== "ENOENT") throw err; - } - if (attempt < retries) await sleep(delayMs); - } - return { answer: extractAnswerFromTranscript(text), transcriptPath: file }; -} - -/** - * High-level capture: given the run's --log-file path (and optionally the - * directory agy was launched from, for the fallback), return the captured - * answer plus diagnostics. Never throws on a missing file. - */ -export async function captureAnswer({ logFile, cwd, env } = {}) { - let logText = ""; - if (logFile) { - try { - logText = await fsp.readFile(logFile, "utf8"); - } catch (err) { - if (err.code !== "ENOENT") throw err; - } - } - // Prefer agy's OWN reported data dir (cross-platform correct); fall back - // to the /.gemini guess only if the log didn't reveal it. - const storeDir = parseStoreDir(logText) ?? agyStoreDir(env ?? process.env); - let conversationId = parseConversationId(logText); - if (!conversationId && cwd) { - conversationId = await conversationIdForWorkspace(storeDir, cwd); - } - if (!conversationId) { - return { answer: "", conversationId: null, transcriptPath: null, storeDir }; - } - const { answer, transcriptPath } = await readTranscriptAnswer(storeDir, conversationId); - return { answer, conversationId, transcriptPath, storeDir }; -} - -// --------------------------------------------------------------------------- -// CLI: `node transcript.mjs [cwd]` -// -// Used by the Bash wrapper (agy-run.sh) so the node-free synchronous -// commands (/agy:ask, simple /agy:review) can capture output without -// write_file. Prints the recovered answer to stdout and exits 0; exits 3 -// (printing nothing) when no answer could be recovered. -// --------------------------------------------------------------------------- -function isMainModule() { - const argv1 = process.argv[1]; - if (!argv1) return false; - const here = fileURLToPath(import.meta.url); - // Realpath both sides: on macOS /var and /tmp symlink to /private/..., - // so argv1 (as invoked) and import.meta.url (realpath-resolved by Node) - // differ and a plain resolve() compare falsely returns false — silently - // skipping the CLI dispatch (empty output, exit 0). Fall back per side. - const norm = (p) => { - try { - return realpathSync(p); - } catch { - return path.resolve(p); - } - }; - return norm(argv1) === norm(here); -} - -if (isMainModule()) { - const [logFile, cwd] = process.argv.slice(2); - captureAnswer({ logFile, cwd }) - .then(({ answer }) => { - if (answer && answer.trim()) { - process.stdout.write(answer.endsWith("\n") ? answer : answer + "\n"); - process.exit(0); - } - process.exit(3); - }) - .catch((err) => { - process.stderr.write(`transcript: ${err?.message ?? err}\n`); - process.exit(1); - }); -} diff --git a/plugins/agy/scripts/lib/workspace.mjs b/plugins/agy/scripts/lib/workspace.mjs deleted file mode 100644 index 9871762..0000000 --- a/plugins/agy/scripts/lib/workspace.mjs +++ /dev/null @@ -1,46 +0,0 @@ -// workspace.mjs — figure out where to put per-project state. -// -// The order of preference matches what feels least surprising: -// 1. `CLAUDE_PROJECT_DIR` env var (Claude Code sets this when a -// slash command runs inside a project). -// 2. Walk up from CWD looking for a `.git/` entry — the repo root. -// 3. CWD as a last resort. -// -// All paths are returned absolute. - -import { promises as fsp } from "node:fs"; -import path from "node:path"; -import process from "node:process"; - -export async function resolveWorkspaceRoot(opts = {}) { - const startCwd = opts.cwd ?? process.cwd(); - const envHint = opts.env?.CLAUDE_PROJECT_DIR ?? process.env.CLAUDE_PROJECT_DIR; - if (envHint) { - try { - const abs = path.resolve(envHint); - const stat = await fsp.stat(abs); - if (stat.isDirectory()) return abs; - } catch { - // Bad env var; fall through. - } - } - const gitRoot = await findGitRoot(startCwd); - if (gitRoot) return gitRoot; - return path.resolve(startCwd); -} - -async function findGitRoot(start) { - let current = path.resolve(start); - while (true) { - const candidate = path.join(current, ".git"); - try { - await fsp.access(candidate); - return current; - } catch { - /* keep walking up */ - } - const parent = path.dirname(current); - if (parent === current) return null; - current = parent; - } -} diff --git a/plugins/agy/skills/antigravity-cli/SKILL.md b/plugins/agy/skills/antigravity-cli/SKILL.md index a6a64cd..86b8f3f 100644 --- a/plugins/agy/skills/antigravity-cli/SKILL.md +++ b/plugins/agy/skills/antigravity-cli/SKILL.md @@ -1,72 +1,78 @@ --- name: antigravity-cli -description: Internal runtime contract for invoking the Antigravity CLI (`agy`) from the `agy` subagent. Not user-invocable. +description: Internal runtime contract for invoking the Antigravity CLI (`agy`) from the `agy:runner` subagent. Not user-invocable. user-invocable: false --- # Antigravity CLI runtime -Use this skill only inside the `agy` subagent. +Use this skill only inside the `agy:runner` subagent. ## Primary helper ``` -bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" ask [--model ] "" [agy-flags...] +bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" ask [--model ] '' [--print-timeout ] [--effort ] ``` -The wrapper: - -- Locates `agy` in `PATH`, `~/.local/bin`, `/opt/antigravity/bin`, or - `/usr/local/bin`. -- Verifies auth (system keyring OAuth or `ANTIGRAVITY_API_KEY`). -- Runs `agy -p ""` non-interactively. -- If `--model ` is supplied **before** the prompt, resolves the - alias and applies it for the duration of the call (atomic patch of - `~/.gemini/antigravity-cli/settings.json` under a lockfile, restored on - exit). -- Forwards any extra arguments **after** the prompt straight to `agy` — so - `… ask "" --sandbox` becomes `agy -p "" --sandbox`. +`bin/agy-plugin` is a launcher for the plugin's native binary: on first use +it downloads the build for this machine and verifies its SHA-256 on every +run. The same line works on macOS, Linux and Windows (Git Bash). No Node.js +is needed. + +`ask`: + +- Locates `agy` and checks it is logged in (system keyring OAuth or + `ANTIGRAVITY_API_KEY`) and is version 1.2.0 or newer. +- Runs agy non-interactively and returns the answer from agy's JSON output. +- Is **read-only**: agy runs from a throwaway directory (the repo is outside + its workspace), pinned to its Default agent mode for that run, without + `--dangerously-skip-permissions`. Writes are denied and reported as + `agy tried to use X, which this read-only command blocks`. +- `--model ` must come **before** the prompt. It is resolved at call + time and passed to agy's own `--model` flag for that call only. +- After the prompt, only `--print-timeout` and `--effort` are accepted; + any other agy flag is refused (exit 64). ## Rules of engagement -One wrapper call per task. The subagent is a forwarder, not an orchestrator — -keep the user's task text intact and let `agy` do the work. +One `ask` call per task. The subagent is a forwarder, not an orchestrator — +keep the user's task text intact (one shell-quoted argument) and let `agy` +do the work. Strip flags that belong to the parent slash command (`--background`) before -forwarding. Pass `--model ` to the wrapper (not to agy directly). -Pass agy-native flags through after the prompt argument. +forwarding. -## Model aliases (consumed by the wrapper) +## Model aliases `flash-low`, `flash-medium` (`flash-med`), `flash` (`flash-high`), `pro-low`, `pro` (`pro-high`), `sonnet` (`claude-sonnet`), -`opus` (`claude-opus`), `gpt-oss` (`gpt-oss-120b`). Canonical TUI strings -are also accepted verbatim (e.g. `"Claude Opus 4.6 (Thinking)"`). - -Run `bash "${CLAUDE_PLUGIN_ROOT}/scripts/agy-run.sh" help` for the -authoritative list. +`opus` (`claude-opus`), `gpt-oss` (`gpt-oss-120b`). Each resolves against +`agy models` to the newest model in its family. Any id or display name that +`agy models` lists is also accepted verbatim. -## agy-native flags worth knowing +Run `bash "${CLAUDE_PLUGIN_ROOT}/bin/agy-plugin" help` for the +authoritative list with the models currently available. -Run `agy --help` for the full list. Useful ones that go **after** the -prompt argument: +## Timeouts -- `--sandbox` — extra-restrictive execution; only when the user asked for it. -- `--print-timeout 10m` — extend the default 5min print timeout. -- `--add-dir ` — add a directory to the workspace (repeatable). +`ask` gives agy 8 minutes by default (`AGY_ASK_TIMEOUT`, a Go duration like +`8m0s`). `--print-timeout` after the prompt overrides agy's limit, but the +plugin itself stops agy 2 minutes after `AGY_ASK_TIMEOUT`, so a longer run +needs that variable raised in the environment. ## What this skill does NOT do - Does not install or authenticate `agy`. That is `/agy:setup`'s job. +- Does not edit files. Write-capable work is `/agy:rescue`. - Does not retry, summarize, or post-process `agy`'s output. -- Does not read files, run `git`, or make HTTP calls outside the wrapper. +- Does not read files, run `git`, or make HTTP calls outside the helper. ## Error handling -If the wrapper exits non-zero, return its stderr verbatim. Standard exit -codes: +If the helper exits non-zero, return its stderr verbatim. Exit codes: -- `127` — `agy` binary not found. -- `1` — not authenticated, no diff found (`review` subcommand), or - settings.json missing/malformed (`--model` path). -- `64` — bad CLI usage of the wrapper itself, or unknown `--model` alias. +- `127` — `agy` is not installed. +- `1` — runtime failure: not authenticated, agy older than 1.2.0, or agy + returned no answer. +- `64` — usage error: missing prompt, a refused flag, or an unknown + `--model` name. diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..640a93b --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.100.0" +components = ["rustfmt", "clippy"] diff --git a/scripts/e2e-live.sh b/scripts/e2e-live.sh new file mode 100755 index 0000000..07e5717 --- /dev/null +++ b/scripts/e2e-live.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# Live end-to-end check against a REAL, logged-in agy (uses model quota). +# Not run in CI. Usage: scripts/e2e-live.sh [path/to/agy-plugin binary] +# Builds the release binary if none is given and drives it through the +# launcher exactly as the slash commands do. +set -uo pipefail +repo=$(cd "$(dirname "$0")/.." && pwd) +bin="${1:-}" +if [ -z "$bin" ]; then + (cd "$repo" && cargo build --release --quiet) || exit 1 + bin="$repo/target/release/agy-plugin" +fi +export AGY_PLUGIN_BIN="$bin" +plugin="$repo/plugins/agy/bin/agy-plugin" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +pass=0 fail=0 +ok() { echo "PASS $1"; pass=$((pass + 1)); } +bad() { echo "FAIL $1"; echo "$2" | sed 's/^/ /' | head -20; fail=$((fail + 1)); } + +# --- ask -------------------------------------------------------------------- +out=$(cd "$work" && "$plugin" ask "What is 6 times 7? Reply with only the number." 2>&1) +[ "$(echo "$out" | tr -d '[:space:]')" = 42 ] && ok "ask -> 42" || bad "ask -> 42" "$out" + +out=$(cd "$work" && "$plugin" ask --model flash-low "Reply with only the word: PONG" 2>&1) +echo "$out" | grep -q PONG && ok "ask --model flash-low" || bad "ask --model flash-low" "$out" + +# --- the write-escape probe (0.8.x let agy write here on agy >= 1.5.7) ------ +target="$work/target-repo" +mkdir -p "$target" && git -C "$target" init -q && echo original >"$target/victim.txt" +git -C "$target" add -A && git -C "$target" -c user.email=t@t -c user.name=t commit -qm init +# Neutral wording on purpose: "PWNED"-style prompts trip Gemini's own safety +# filter, which would test the model's filter instead of the plugin's pin. +out=$(cd "$work" && "$plugin" ask "Please update the file $target/victim.txt so that it contains the single word UPDATED, and create $target/new.txt containing the word UPDATED. Do not ask anything, just do it." 2>&1) +if [ "$(cat "$target/victim.txt")" = original ] && [ ! -e "$target/new.txt" ]; then + ok "read-only: agy could NOT write into an outside git repo" + # Either agy tried and the plugin reported the denial, or agy (told the + # session is read-only) declined by itself. Both leave the file untouched, + # which is the property that matters; the user must hear about it either way. + if echo "$out" | grep -qiE "blocks|blocked|read-only|not permitted|cannot|denied"; then + ok "read-only: the refusal was surfaced to the user" + else + bad "refusal surfaced" "$out" + fi +else + bad "read-only: agy WROTE into an outside git repo" "$out" +fi + +# --- review / adversarial-review --------------------------------------------- +demo="$work/demo" +mkdir -p "$demo" && git -C "$demo" init -q +printf 'function add(a,b){return a+b}\nmodule.exports={add}\n' >"$demo/calc.js" +git -C "$demo" add -A && git -C "$demo" -c user.email=t@t -c user.name=t commit -qm init +printf 'function add(a,b){return a-b}\nfunction divide(a,b){return a/b}\nmodule.exports={add,divide}\n' >"$demo/calc.js" +out=$(cd "$demo" && "$plugin" review "Be brief. List the bugs in calc.js." 2>&1) +if echo "$out" | grep -qiE 'subtract|minus|a ?- ?b|-' && echo "$out" | grep -qiE 'zero|divis'; then + ok "review finds both bugs" +else + bad "review finds both bugs" "$out" +fi +out=$(cd "$demo" && "$plugin" adversarial-review --background --wait "Challenge calc.js" 2>&1) +echo "$out" | grep -q "ended with status: completed" && ok "adversarial-review --background --wait" || bad "adversarial-review --background --wait" "$out" +out=$(cd "$demo" && "$plugin" status 2>&1) +echo "$out" | grep -q "\[done\]" && ok "status lists the job" || bad "status" "$out" +[ "$(git -C "$demo" status --porcelain | grep -v '^ M calc.js$' | grep -c .)" = 0 ] && ok "review left the repo untouched (.agy-plugin excluded)" || bad "repo untouched" "$(git -C "$demo" status --porcelain)" + +# --- scrape / doc-to-md ------------------------------------------------------ +out=$(cd "$work" && "$plugin" scrape https://example.com 2>&1) +echo "$out" | grep -qiE "example domain|documentation examples" && ok "scrape https://example.com" || bad "scrape" "$out" +out=$(cd "$work" && "$plugin" scrape http://169.254.169.254/ 2>&1); rc=$? +[ $rc = 65 ] && ok "scrape refuses the metadata IP (65)" || bad "scrape SSRF" "$out" +printf '

Hello

  • one
  • two
\n' >"$work/page.html" +out=$(cd "$work" && "$plugin" doc-to-md page.html 2>&1) +echo "$out" | grep -q "Hello" && echo "$out" | grep -qE '^[-*] +one' && ok "doc-to-md html -> markdown" || bad "doc-to-md" "$out" + +# --- rescue --isolate + background cancel ------------------------------------ +git -C "$demo" checkout -q -- calc.js +out=$(cd "$demo" && "$plugin" rescue --isolate "Create a file named HELLO.txt containing the word hello. Do nothing else." 2>&1) +if echo "$out" | grep -q "HELLO.txt" && [ ! -e "$demo/HELLO.txt" ]; then + ok "rescue --isolate produced a patch, tree untouched" +else + bad "rescue --isolate" "$out" +fi +out=$(cd "$demo" && "$plugin" rescue --background "Count slowly from 1 to 500, one number per line, then stop." 2>&1) +id=$(echo "$out" | grep -oE 'agy-[0-9a-f]{8}' | head -n1) +sleep 4 +out=$(cd "$demo" && "$plugin" cancel "$id" 2>&1) +echo "$out" | grep -qE "canceled \((killed|already-dead|no-pid-marking-canceled)\)" && ok "cancel background rescue" || bad "cancel" "$out" +pid_alive=$(pgrep -f "_run-job $id" || true) +[ -z "$pid_alive" ] && ok "no worker left running after cancel" || bad "worker left running" "$pid_alive" + +# --- check / help ----------------------------------------------------------- +out=$("$plugin" check) +echo "$out" | grep -q '"supported":true' && ok "check: supported" || bad "check" "$out" +"$plugin" help | grep -q "Available models" && ok "help resolves models live" || bad "help" "" + +echo +echo "e2e: $pass passed, $fail failed" +[ "$fail" = 0 ] diff --git a/scripts/test-launcher.ps1 b/scripts/test-launcher.ps1 new file mode 100644 index 0000000..cc75242 --- /dev/null +++ b/scripts/test-launcher.ps1 @@ -0,0 +1,80 @@ +# Tests for plugins/agy/bin/agy-plugin.ps1 (Windows). Run under both +# `pwsh` and Windows PowerShell 5.1. Arg 1: path to a built stub_agy.exe, +# used as the fake release "binary" (it records its argv). +param([Parameter(Mandatory = $true)][string]$Stub) +$ErrorActionPreference = 'Stop' + +function Fail([string]$m) { [Console]::Error.WriteLine("FAIL: $m"); exit 1 } + +# Run the launcher in a child Windows PowerShell 5.1. +# - Arguments go INSIDE the child's script (-EncodedCommand), as PowerShell +# string literals. Passing them on the command line would cross PS 5.1's +# own native-argument boundary, which mangles embedded quotes and a +# trailing backslash before the launcher ever sees them — the test must +# exercise the launcher's quoting, not PowerShell's. +# - Under ErrorActionPreference=Stop, PS 5.1 turns any stderr line of a +# native program into a terminating NativeCommandError, and the launcher +# legitimately reports "downloading ..." on stderr: relax it for the call. +function Invoke-Launcher([string[]]$launcherArgs, [switch]$MergeStderr) { + $quoted = @($launcherArgs | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ' ' + $script = "& '" + ($launcher -replace "'", "''") + "' $quoted; exit `$LASTEXITCODE" + $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script)) + $old = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + if ($MergeStderr) { + $o = & powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand $enc 2>&1 | ForEach-Object { "$_" } + } else { + $o = & powershell -NoProfile -ExecutionPolicy Bypass -EncodedCommand $enc 2>$null + } + return @{ Out = ($o -join "`n"); Code = $LASTEXITCODE } + } finally { + $ErrorActionPreference = $old + } +} + +$repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path) +$work = Join-Path ([IO.Path]::GetTempPath()) ("agy-ps1-test-" + [Guid]::NewGuid()) +New-Item -ItemType Directory -Path "$work\plugin\bin", "$work\release\v9.9.9" | Out-Null +try { + switch ($env:PROCESSOR_ARCHITECTURE) { 'ARM64' { $arch = 'aarch64' } default { $arch = 'x86_64' } } + $asset = "agy-plugin-$arch-pc-windows-msvc.exe" + Copy-Item -LiteralPath "$repo\plugins\agy\bin\agy-plugin.ps1" -Destination "$work\plugin\bin\" + Set-Content -LiteralPath "$work\plugin\bin\VERSION" -Value '9.9.9' + Copy-Item -LiteralPath $Stub -Destination "$work\release\v9.9.9\$asset" + $good = (Get-FileHash -Algorithm SHA256 -LiteralPath "$work\release\v9.9.9\$asset").Hash.ToLowerInvariant() + Set-Content -LiteralPath "$work\plugin\bin\SHA256SUMS" -Value "$good $asset" + $launcher = "$work\plugin\bin\agy-plugin.ps1" + $env:AGY_PLUGIN_DOWNLOAD_BASE = ([Uri]"$work\release").AbsoluteUri + $env:AGY_PLUGIN_CACHE = "$work\cache" + $env:STUB_RECORD = "$work\record.txt" + $env:STUB_RESPONSE = 'hello from stub' + + # 1. download + verify + exec, with an argument containing quotes and spaces. + $tricky = 'say "hi" to C:\path with spaces\' + $r = Invoke-Launcher @('ask', $tricky) + if ($r.Code -ne 0) { Fail "first run exit $($r.Code)" } + if (-not ($r.Out -match 'hello from stub')) { Fail "unexpected output: $($r.Out)" } + $argv = ((Get-Content -Raw -LiteralPath "$work\record.txt").Split("`t")[1]).Split([char]0x1f) + if ($argv[0] -ne 'ask' -or $argv[1] -ne $tricky) { Fail "argv mangled: $($argv -join ' | ')" } + Write-Output 'ok 1 download + verify + exec, quotes preserved' + + # 2. tampered cache is not executed (re-downloaded instead). + Set-Content -LiteralPath "$work\cache\9.9.9\$asset" -Value 'garbage' + $r = Invoke-Launcher @('version') + if ($r.Code -ne 0) { Fail 're-download failed' } + if ((Get-FileHash -Algorithm SHA256 -LiteralPath "$work\cache\9.9.9\$asset").Hash.ToLowerInvariant() -ne $good) { Fail 'cache not repaired' } + Write-Output 'ok 2 tampered cache refused' + + # 3. tampered release asset is refused. + Remove-Item -Recurse -Force "$work\cache" + Set-Content -LiteralPath "$work\release\v9.9.9\$asset" -Value 'evil' + $r = Invoke-Launcher @('x') -MergeStderr + if ($r.Code -eq 0) { Fail 'tampered asset accepted' } + if (-not ($r.Out -match 'checksum mismatch')) { Fail "no mismatch message: $($r.Out)" } + if (Test-Path -LiteralPath "$work\cache\9.9.9\$asset") { Fail 'tampered asset cached' } + Write-Output 'ok 3 tampered asset refused' + Write-Output 'launcher.ps1: all tests passed' +} finally { + Remove-Item -Recurse -Force -LiteralPath $work -ErrorAction SilentlyContinue +} diff --git a/scripts/test-launcher.sh b/scripts/test-launcher.sh new file mode 100755 index 0000000..bb22cae --- /dev/null +++ b/scripts/test-launcher.sh @@ -0,0 +1,88 @@ +#!/bin/sh +# Tests for plugins/agy/bin/agy-plugin (the download-and-verify launcher). +# Uses a fake release served from file:// and a fake "binary": a shell +# script, or — where a script can't stand in for an executable (Windows Git +# Bash runs the .exe through Windows) — the stub given in AGY_TEST_FAKE_EXE +# (a built examples/stub_agy), which records its argv. +set -eu +repo=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +fail() { echo "FAIL: $*" >&2; exit 1; } +sha256() { + if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'; else shasum -a 256 "$1" | awk '{print $1}'; fi +} + +# Same platform detection as the launcher. +case "$(uname -s)" in Darwin) os=apple-darwin ;; Linux) os=unknown-linux-musl ;; *) os=pc-windows-msvc ;; esac +case "$(uname -m)" in x86_64 | amd64) arch=x86_64 ;; *) arch=aarch64 ;; esac +exe=""; [ "$os" = pc-windows-msvc ] && exe=.exe +asset="agy-plugin-$arch-$os$exe" + +# A plugin copy whose VERSION/SHA256SUMS we control. +mkdir -p "$work/plugin/bin" "$work/release/v9.9.9" +cp "$repo/plugins/agy/bin/agy-plugin" "$work/plugin/bin/" +echo 9.9.9 >"$work/plugin/bin/VERSION" +fake="$work/release/v9.9.9/$asset" +if [ -n "${AGY_TEST_FAKE_EXE:-}" ]; then + cp "$AGY_TEST_FAKE_EXE" "$fake" + export STUB_RECORD="$work/record.txt" STUB_RESPONSE="fake-binary" +else + printf '#!/bin/sh\necho "fake-binary args:$*"\n' >"$fake" +fi +# What the fake printed for "$@": the script echoes its args; the stub +# prints "fake-binary" and records argv (cwd TAB argv joined by 0x1f). +ran_with() { + if [ -n "${AGY_TEST_FAKE_EXE:-}" ]; then + printf 'fake-binary args:%s' "$(tail -n 1 "$STUB_RECORD" | cut -f2 | tr '\037' ' ')" + else + printf '%s' "$1" + fi +} +good=$(sha256 "$work/release/v9.9.9/$asset") +echo "$good $asset" >"$work/plugin/bin/SHA256SUMS" +launcher="$work/plugin/bin/agy-plugin" +# curl on Windows takes C:/... paths, not Git Bash's /tmp/... ones. +release_dir="$work/release" +command -v cygpath >/dev/null 2>&1 && release_dir="/$(cygpath -m "$release_dir")" +export AGY_PLUGIN_DOWNLOAD_BASE="file://$release_dir" AGY_PLUGIN_CACHE="$work/cache" + +# 1. First run downloads, verifies, runs and passes args through. +out=$("$launcher" ask "two words" 2>/dev/null) || fail "first run failed" +out=$(ran_with "$out") +[ "$out" = "fake-binary args:ask two words" ] || fail "unexpected output: $out" +[ -x "$work/cache/9.9.9/$asset" ] || fail "binary not cached" +echo "ok 1 download + verify + exec" + +# 2. Cached run works offline. +AGY_PLUGIN_DOWNLOAD_BASE="file://$release_dir/../nowhere" "$launcher" x >/dev/null 2>&1 || fail "cached run needed the network" +echo "ok 2 cached run" + +# 3. A tampered cache entry is NOT executed; the launcher re-downloads. +printf '#!/bin/sh\necho PWNED\n' >"$work/cache/9.9.9/$asset" +out=$("$launcher" y 2>/dev/null) || fail "re-download failed" +out=$(ran_with "$out") +[ "$out" = "fake-binary args:y" ] || fail "tampered cache was executed: $out" +echo "ok 3 tampered cache refused" + +# 4. A tampered release asset is refused (and not left in the cache). +rm -rf "$work/cache" +printf '#!/bin/sh\necho PWNED\n' >"$work/release/v9.9.9/$asset" +if out=$("$launcher" z 2>&1); then fail "tampered asset was accepted: $out"; fi +case "$out" in *"checksum mismatch"*) ;; *) fail "no mismatch message: $out" ;; esac +[ ! -e "$work/cache/9.9.9/$asset" ] || fail "tampered asset left in cache" +for f in "$work/cache/9.9.9/"*download*; do [ -e "$f" ] && fail "temp file left behind: $f"; done +echo "ok 4 tampered asset refused" + +# 5. No checksum for this platform -> clear error, nothing downloaded. +: >"$work/plugin/bin/SHA256SUMS" +if out=$("$launcher" 2>&1); then fail "ran without a checksum"; fi +case "$out" in *"no checksum"*) ;; *) fail "unexpected: $out" ;; esac +echo "ok 5 missing checksum refused" + +# 6. AGY_PLUGIN_BIN overrides everything (dev builds). +out=$(AGY_PLUGIN_BIN=/bin/echo "$launcher" dev-mode) || fail "override failed" +[ "$out" = "dev-mode" ] || fail "override output: $out" +echo "ok 6 AGY_PLUGIN_BIN override" +echo "launcher: all tests passed" diff --git a/src/agy.rs b/src/agy.rs new file mode 100644 index 0000000..2f7f19c --- /dev/null +++ b/src/agy.rs @@ -0,0 +1,390 @@ +//! Locating and probing Google's `agy` CLI: binary lookup, auth probe, +//! version gates, and the flags that keep a read-only run read-only. + +use std::cell::OnceCell; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use crate::util::{self, Fail}; + +/// Oldest agy this plugin drives. 1.2.0 is the first release where all of +/// these hold: non-TTY stdout carries the answer (the 1.0.15 fix for agy +/// issue #76), `--output-format json` works in print mode, `--model` is +/// honoured in `-p` runs (1.1.10) and `agy models` doesn't hang. +pub(crate) const MIN_AGY_VERSION: &str = "1.2.0"; + +/// agy 1.5.7 made Auto the default Agent Mode for headless `-p` runs. Auto +/// approves writes OUTSIDE the workspace without asking (1.5.16: any file +/// inside a git/jj/hg repo, and any create or append elsewhere). Verified on +/// 1.5.16: a plugin-style run with no --dangerously-skip-permissions +/// overwrote a file in a git repo outside its temp workspace. +pub(crate) const AGY_AUTO_DEFAULT_VERSION: &str = "1.5.7"; + +/// Session-only settings selecting agy's Default agent mode, in which a +/// headless run DENIES anything that would need approval (reported as +/// `denied_actions`). Passed with --settings, never saved. +/// +/// The deny rules are a second, independent layer (verified on agy 1.5.16: +/// a session `--settings` deny rule blocks the action even in Auto mode, and +/// a deny beats any allow rule the user saved): `command(*)` refuses every +/// shell command, `write_file(*)` every file creation or edit. In Default +/// mode agy also refuses to READ files outside its workspace. +pub(crate) const READ_ONLY_SETTINGS: &str = + r#"{"agentMode":"","permissions":{"deny":["command(*)","write_file(*)"]}}"#; + +pub(crate) const INSTALL_HINT: &str = "curl -fsSL https://antigravity.google/cli/install.sh | bash"; + +const PROBE_TIMEOUT: Duration = Duration::from_secs(20); + +/// Compare dotted versions numerically ("1.10" > "1.9"); missing or +/// non-numeric parts count as 0. +pub(crate) fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering { + let part = |s: &str, i: usize| -> u64 { + s.split('.') + .filter(|p| !p.is_empty()) + .nth(i) + .map(|p| { + let digits: String = p.chars().take_while(|c| c.is_ascii_digit()).collect(); + digits.parse().unwrap_or(0) + }) + .unwrap_or(0) + }; + let n = a.split('.').count().max(b.split('.').count()); + for i in 0..n { + match part(a, i).cmp(&part(b, i)) { + std::cmp::Ordering::Equal => continue, + other => return other, + } + } + std::cmp::Ordering::Equal +} + +pub(crate) fn version_at_least(version: &str, min: &str) -> bool { + compare_versions(version, min) != std::cmp::Ordering::Less +} + +/// First `N.N` or `N.N.N` token in `text` ("agy 1.5.16" -> "1.5.16"). +pub(crate) fn parse_version(text: &str) -> Option { + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i].is_ascii_digit() && (i == 0 || !b[i - 1].is_ascii_digit()) { + let mut j = i; + let mut parts = 0; + loop { + let start = j; + while j < b.len() && b[j].is_ascii_digit() { + j += 1; + } + if j == start { + break; + } + parts += 1; + if parts == 3 + || j >= b.len() + || b[j] != b'.' + || j + 1 >= b.len() + || !b[j + 1].is_ascii_digit() + { + break; + } + j += 1; + } + if parts >= 2 { + return Some(text[i..j].to_string()); + } + i = j.max(i + 1); + } else { + i += 1; + } + } + None +} + +/// Where agy is, in the order the 0.8.x wrappers searched: $AGY_BIN, PATH, +/// then the installer's default locations. +pub(crate) fn find_agy() -> Option { + if let Some(p) = util::env_nonempty("AGY_BIN") { + let p = PathBuf::from(p); + if p.is_file() { + return Some(p); + } + } + if let Some(p) = util::which("agy") { + return Some(p); + } + let home = util::home_dir(); + let mut candidates: Vec = Vec::new(); + if let Some(h) = &home { + candidates.push(h.join(".local").join("bin").join("agy")); + } + candidates.push(PathBuf::from("/opt/antigravity/bin/agy")); + candidates.push(PathBuf::from("/usr/local/bin/agy")); + let local_app_data = util::env_nonempty("LOCALAPPDATA") + .map(PathBuf::from) + .or_else(|| home.as_ref().map(|h| h.join("AppData").join("Local"))); + if let Some(l) = local_app_data { + candidates.push(l.join("agy").join("bin").join("agy.exe")); + } + candidates.into_iter().find(|c| { + // On Windows an extension-less file (a POSIX script) can't be run. + let runnable = + !cfg!(windows) || c.extension().is_some_and(|e| e.eq_ignore_ascii_case("exe")); + runnable && util::is_executable_file(c) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Auth { + ApiKey, + Oauth, + Missing, +} + +impl Auth { + pub(crate) fn as_str(self) -> &'static str { + match self { + Auth::ApiKey => "api-key", + Auth::Oauth => "oauth", + Auth::Missing => "missing", + } + } +} + +/// Coarse, offline auth probe: an API key in the environment, or agy's +/// Oauth state directory on disk. It can't tell an expired login from a +/// valid one; /agy:setup's real ping does that. +pub(crate) fn auth_status() -> Auth { + if util::env_nonempty("ANTIGRAVITY_API_KEY").is_some() { + return Auth::ApiKey; + } + match util::home_dir() { + Some(h) + if h.join(".config").join("antigravity").is_dir() + || h.join(".gemini").join("antigravity-cli").is_dir() => + { + Auth::Oauth + } + _ => Auth::Missing, + } +} + +/// A located agy binary with lazily probed `--version` / `--help`. +pub(crate) struct Agy { + path: PathBuf, + version: OnceCell>, + help: OnceCell, +} + +impl Agy { + pub(crate) fn at(path: PathBuf) -> Agy { + Agy { + path, + version: OnceCell::new(), + help: OnceCell::new(), + } + } + + /// Find agy and check it is logged in (exit 127 / 1 like 0.8.x). + pub(crate) fn ready() -> Result { + let Some(path) = find_agy() else { + return Err(Fail::new( + 127, + format!("error: agy is not installed.\n install: {INSTALL_HINT}"), + )); + }; + if auth_status() == Auth::Missing { + return Err(Fail::runtime( + "error: agy is not authenticated.\n run `agy` once interactively, or export ANTIGRAVITY_API_KEY", + )); + } + Ok(Agy::at(path)) + } + + pub(crate) fn path(&self) -> &Path { + &self.path + } + + pub(crate) fn command(&self) -> Command { + Command::new(&self.path) + } + + pub(crate) fn version(&self) -> Option<&str> { + self.version + .get_or_init(|| { + let out = util::run_simple(&self.path, &["--version"], PROBE_TIMEOUT).ok()?; + if !out.ok() { + return None; + } + parse_version(&out.stdout_str()) + }) + .as_deref() + } + + /// `agy --help` text (stdout + stderr; Go's flag package prints usage to + /// stderr on some builds). Empty if agy can't be run. + pub(crate) fn help(&self) -> &str { + self.help.get_or_init( + || match util::run_simple(&self.path, &["--help"], PROBE_TIMEOUT) { + Ok(out) => format!("{}\n{}", out.stdout_str(), out.stderr_str()), + Err(_) => String::new(), + }, + ) + } + + fn has_flag(&self, flag: &str) -> bool { + // Match the flag as a whole word in the usage table, not a substring + // of a longer flag (`--model` must not match `--models-dir`). + self.help().lines().any(|l| { + l.split(|c: char| c.is_whitespace() || c == ',' || c == '=') + .any(|w| w == flag) + }) + } + + /// Refuse agy builds older than MIN_AGY_VERSION. An unreadable version + /// is accepted when the help text shows the JSON output flag we rely on. + pub(crate) fn require_supported(&self) -> Result<(), Fail> { + match self.version() { + Some(v) if !version_at_least(v, MIN_AGY_VERSION) => Err(Fail::runtime(format!( + "error: agy {v} is too old for this plugin (needs {MIN_AGY_VERSION} or newer).\n update it with `agy update`." + ))), + Some(_) => Ok(()), + None if self.has_flag("--output-format") => Ok(()), + None => Err(Fail::runtime(format!( + "error: could not determine the agy version, and `agy --help` does not list --output-format.\n this plugin needs agy {MIN_AGY_VERSION} or newer; update it with `agy update`." + ))), + } + } + + /// Flags that pin a read-only run to Default agent mode. Fails closed: + /// an agy that starts headless runs in Auto mode but has no --settings + /// flag is refused rather than run. + pub(crate) fn readonly_mode_args(&self) -> Result, Fail> { + if self.has_flag("--settings") { + // ONE token (`--settings=`): a separate value token could + // be swallowed by a preceding value-less flag (`--effort + // --settings {...}` would make "--settings" the effort value). + return Ok(vec![format!("--settings={READ_ONLY_SETTINGS}")]); + } + match self.version() { + Some(v) if version_at_least(v, AGY_AUTO_DEFAULT_VERSION) => { + Err(Fail::runtime(format!( + "error: agy {v} starts headless runs in Auto mode, which can write outside\n the workspace, and this build has no --settings flag to pin Default mode.\n Refusing to run a read-only command. Update agy with `agy update`." + ))) + } + // Older builds predate Auto mode: Default is the only mode. + _ => Ok(Vec::new()), + } + } +} + +#[cfg(all(test, unix))] +pub(crate) mod test_support { + //! A scripted fake `agy` for unit tests (Unix shell script). + use std::path::{Path, PathBuf}; + + /// Write an executable stub at dir/agy that prints `version` for + /// --version and `help` for --help. + #[cfg(unix)] + pub(crate) fn stub_agy(dir: &Path, version: &str, help: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let p = dir.join("agy"); + let script = format!( + "#!/bin/sh\ncase \"$1\" in\n --version) printf '%s\\n' '{version}' ;;\n --help) cat <<'EOF'\n{help}\nEOF\n;;\nesac\n" + ); + std::fs::write(&p, script).unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + p + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cmp::Ordering; + + #[test] + fn version_comparison_is_numeric() { + assert_eq!(compare_versions("1.10.0", "1.9.9"), Ordering::Greater); + assert_eq!(compare_versions("1.2", "1.2.0"), Ordering::Equal); + assert_eq!(compare_versions("1.5.16", "1.5.7"), Ordering::Greater); + assert_eq!(compare_versions("1.1.5", "1.2.0"), Ordering::Less); + assert_eq!(compare_versions("2", "1.99.99"), Ordering::Greater); + assert_eq!(compare_versions("1.5-beta", "1.5"), Ordering::Equal); + assert!(version_at_least("1.5.7", AGY_AUTO_DEFAULT_VERSION)); + assert!(!version_at_least("1.5.6", AGY_AUTO_DEFAULT_VERSION)); + } + + #[test] + fn parse_version_finds_the_first_dotted_number() { + assert_eq!(parse_version("1.5.16\n").as_deref(), Some("1.5.16")); + assert_eq!( + parse_version("agy version 1.2.0 (abc)").as_deref(), + Some("1.2.0") + ); + assert_eq!(parse_version("v1.4").as_deref(), Some("1.4")); + assert_eq!(parse_version("1.2.3.4").as_deref(), Some("1.2.3")); + assert_eq!(parse_version("build 42 of 7"), None); + assert_eq!(parse_version(""), None); + assert_eq!(parse_version("1."), None); + } + + #[cfg(unix)] + fn agy_with(version: &str, help: &str) -> (crate::util::TempDir, Agy) { + let d = crate::util::TempDir::new("agy-probe-test-").unwrap(); + let p = test_support::stub_agy(d.path(), version, help); + (d, Agy::at(p)) + } + + #[cfg(unix)] + #[test] + fn readonly_pin_uses_settings_when_available() { + let (_d, a) = agy_with("1.5.16", " --settings Settings for this session only"); + assert_eq!( + a.readonly_mode_args().unwrap(), + vec![format!("--settings={READ_ONLY_SETTINGS}")] + ); + } + + #[cfg(unix)] + #[test] + fn readonly_pin_refuses_auto_by_default_agy_without_settings() { + let (_d, a) = agy_with("1.5.9", "Usage of agy:\n --print x"); + let err = a.readonly_mode_args().unwrap_err(); + assert_eq!(err.code, 1); + assert!(err.message.contains("Refusing to run a read-only command")); + } + + #[cfg(unix)] + #[test] + fn readonly_pin_is_empty_for_agy_that_predates_auto_mode() { + let (_d, a) = agy_with("1.2.0", "Usage of agy:"); + assert!(a.readonly_mode_args().unwrap().is_empty()); + } + + #[cfg(unix)] + #[test] + fn settings_must_match_as_a_whole_flag() { + let (_d, a) = agy_with("1.5.16", " --settings-file something else"); + assert!(a.readonly_mode_args().is_err()); + } + + #[cfg(unix)] + #[test] + fn version_gate() { + let (_d, old) = agy_with("1.1.5", ""); + assert!( + old.require_supported() + .unwrap_err() + .message + .contains("too old") + ); + let (_d2, new) = agy_with("1.5.16", ""); + assert!(new.require_supported().is_ok()); + let (_d3, unknown_ok) = agy_with("unknown", " --output-format Output format"); + assert!(unknown_ok.require_supported().is_ok()); + let (_d4, unknown_bad) = agy_with("unknown", "Usage:"); + assert!(unknown_bad.require_supported().is_err()); + } +} diff --git a/src/capture.rs b/src/capture.rs new file mode 100644 index 0000000..b28106a --- /dev/null +++ b/src/capture.rs @@ -0,0 +1,556 @@ +//! The read-only agy run behind /agy:ask, /agy:scrape, /agy:doc-to-md and +//! the review commands. +//! +//! What keeps it read-only, all at once: +//! - agy's cwd and only `--add-dir` is a throwaway (or review-stage) dir, so +//! the user's repo is outside agy's workspace; +//! - the run is pinned to agy's Default agent mode (`--settings +//! {"agentMode":""}`, placed LAST so caller flags can't override it), so a +//! headless run DENIES writes outside the workspace — agy >= 1.5.7 would +//! otherwise start in Auto mode and approve them (verified on 1.5.16); +//! - no `--dangerously-skip-permissions`; +//! - repo-location hints are stripped from agy's environment. +//! +//! Output comes from `--output-format json` (`response`, `status`, +//! `denied_actions`), so a blocked write is reported as such instead of as +//! "no output". + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use crate::agy::Agy; +use crate::json::{self, Value}; +use crate::util::{self, Fail, TempDir}; + +/// Environment variables that point at the user's repo. agy runs outside +/// the repo; don't hand it the path either. PWD/OLDPWD matter because +/// `Command::current_dir` changes the cwd but not the inherited PWD. +pub(crate) const REPO_ENV_HINTS: &[&str] = &[ + "CLAUDE_PROJECT_DIR", + "GIT_DIR", + "GIT_WORK_TREE", + "GIT_INDEX_FILE", + "GIT_COMMON_DIR", + "AGY_JOB_WORKSPACE", + "PWD", + "OLDPWD", +]; + +/// agy takes the whole prompt as one argv entry; Windows caps a command line +/// at 32767 UTF-16 units. Leave room for the exe path and other flags. +pub(crate) const DEFAULT_PROMPT_MAX_BYTES: usize = 30_000; + +/// Appended to every read-only prompt. +pub(crate) const READONLY_NOTE: &str = "\n\n(This is a read-only session: shell commands and file edits are not available and will be refused. Use only your built-in tools for reading files and listing directories.)"; +const TRUNCATION_MARKER: &str = "\n\n[...content truncated to fit the OS command-line length limit; some context was omitted...]"; + +/// Where agy runs. +pub(crate) enum Workspace<'a> { + /// A fresh private temp dir, optionally with one validated file copied in + /// under a fixed name (doc-to-md). + Fresh { stage: Option<(&'a Path, &'a str)> }, + /// An existing dir prepared by the caller (review stage dir). + Existing(&'a Path), +} + +pub(crate) struct Run<'a> { + pub(crate) prompt: &'a str, + pub(crate) model: Option<&'a str>, + /// agy duration ("8m0s"), passed to --print-timeout. + pub(crate) timeout: &'a str, + /// Extra agy flags, already checked by the caller (see + /// `check_passthrough`). + pub(crate) extra: &'a [String], + pub(crate) workspace: Workspace<'a>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Denied { + pub(crate) action: String, + pub(crate) display_name: String, +} + +#[derive(Debug)] +pub(crate) struct Outcome { + pub(crate) response: String, + /// agy's `status` ("SUCCESS", "ERROR", ...); None if stdout wasn't JSON. + pub(crate) status: Option, + pub(crate) finished_reason: Option, + pub(crate) denied: Vec, + pub(crate) exit_code: Option, + pub(crate) stderr: String, +} + +/// Flags a user may pass through to agy on a read-only command. Anything +/// that could widen what agy may touch (--add-dir, --mode, --settings, +/// --dangerously-skip-permissions, --remote-agent, ...) is refused. +const READONLY_PASSTHROUGH: &[&str] = &["--print-timeout", "--effort"]; + +/// Validate caller-supplied extra agy flags for a read-only command. +/// Accepts `--flag value` and `--flag=value` for allowed flags only. +pub(crate) fn check_passthrough(extra: &[String]) -> Result<(), Fail> { + let refuse = |tok: &str| { + Fail::usage(format!( + "error: '{tok}' can't be passed to agy on a read-only command (allowed: {}, each with a value).", + READONLY_PASSTHROUGH.join(", ") + )) + }; + let mut i = 0; + while i < extra.len() { + let tok = &extra[i]; + let (name, inline) = match tok.split_once('=') { + Some((n, v)) => (n, Some(v)), + None => (tok.as_str(), None), + }; + if !READONLY_PASSTHROUGH.contains(&name) { + return Err(refuse(tok)); + } + // Each allowed flag takes a value. A missing value, or a "value" + // that is itself a flag, would make agy consume the NEXT token — + // possibly our own mode pin — as this flag's value. + let value = match inline { + Some(v) => v, + None => { + i += 1; + extra.get(i).map(String::as_str).unwrap_or("") + } + }; + if value.is_empty() || value.starts_with('-') { + return Err(refuse(tok)); + } + i += 1; + } + Ok(()) +} + +/// Parse a Go duration like "8m0s", "90s", "1h30m", "500ms" into a Duration. +pub(crate) fn parse_go_duration(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() { + return None; + } + if s == "0" { + return Some(Duration::ZERO); + } + let mut total = 0f64; + let b = s.as_bytes(); + let mut i = 0; + while i < b.len() { + let start = i; + while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') { + i += 1; + } + let num: f64 = s[start..i].parse().ok()?; + let ustart = i; + while i < b.len() && b[i].is_ascii_alphabetic() { + i += 1; + } + let mult = match &s[ustart..i] { + "h" => 3600.0, + "m" => 60.0, + "s" => 1.0, + "ms" => 0.001, + "us" | "µs" => 0.000_001, + "ns" => 0.000_000_001, + _ => return None, + }; + total += num * mult; + } + (total.is_finite() && total >= 0.0).then(|| Duration::from_secs_f64(total)) +} + +pub(crate) fn cap_prompt(prompt: &str) -> String { + let max = util::env_nonempty("AGY_PROMPT_MAX_BYTES") + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(DEFAULT_PROMPT_MAX_BYTES); + if prompt.len() <= max { + return prompt.to_string(); + } + format!("{}{TRUNCATION_MARKER}", util::truncate_utf8(prompt, max)) +} + +/// The argv after the agy binary (exposed for tests). +pub(crate) fn build_args( + workspace: &Path, + run: &Run, + model: Option<&str>, + mode_args: &[String], + prompt: &str, +) -> Vec { + let mut a: Vec = vec![ + "--sandbox".into(), + "--add-dir".into(), + workspace.display().to_string(), + "--print-timeout".into(), + run.timeout.into(), + "--output-format".into(), + "json".into(), + ]; + if let Some(m) = model { + a.push("--model".into()); + a.push(m.into()); + } + a.extend(run.extra.iter().cloned()); + // LAST: agy takes the final value of a repeated flag. + a.extend(mode_args.iter().cloned()); + a.push("--print".into()); + a.push(prompt.into()); + a +} + +/// The --print-timeout agy will actually use: a caller-supplied one comes +/// after ours in argv, and agy takes the last value of a repeated flag. +pub(crate) fn effective_print_timeout<'a>(run: &'a Run) -> &'a str { + let mut t = run.timeout; + let mut i = 0; + while i < run.extra.len() { + let a = &run.extra[i]; + if a == "--print-timeout" { + if let Some(v) = run.extra.get(i + 1) { + t = v; + } + i += 1; + } else if let Some(v) = a.strip_prefix("--print-timeout=") { + t = v; + } + i += 1; + } + t +} + +pub(crate) fn run_readonly(agy: &Agy, run: &Run) -> Result { + agy.require_supported()?; + let mode_args = agy.readonly_mode_args()?; + + let temp; + let workspace: PathBuf = match &run.workspace { + Workspace::Existing(p) => p.to_path_buf(), + Workspace::Fresh { stage } => { + temp = TempDir::new("agy-run-").map_err(|e| { + Fail::runtime(format!("error: could not create a temp dir for agy: {e}")) + })?; + if let Some((src, name)) = stage { + crate::guard::stage_file(src, &temp.path().join(name)).map_err(|e| { + Fail::runtime(format!("error: could not stage the input file: {e}")) + })?; + } + temp.path().to_path_buf() + } + }; + + // Tell agy up front which tools it has. In Default mode a shell command + // or edit is refused, and agy 1.5.16 then tends to give up with an empty + // answer instead of falling back to its read tools (seen live on + // adversarial reviews). + let prompt = format!("{}{READONLY_NOTE}", cap_prompt(run.prompt)); + let args = build_args(&workspace, run, run.model, &mode_args, &prompt); + let mut cmd = agy.command(); + cmd.args(&args).current_dir(&workspace); + for k in REPO_ENV_HINTS { + cmd.env_remove(k); + } + // Our own hard stop a bit after agy's --print-timeout, in case agy hangs + // on exit (it did before 1.5.5). + let deadline = parse_go_duration(effective_print_timeout(run)) + .filter(|d| !d.is_zero()) + .map(|d| d + Duration::from_secs(120)); + let out = + util::run_captured_notify(&mut cmd, deadline, &crate::jobs::note_child).map_err(|e| { + Fail::runtime(format!( + "error: could not run agy ({}): {e}", + agy.path().display() + )) + })?; + if out.timed_out { + return Err(Fail::runtime( + "error: agy did not finish within its timeout (raise it with the AGY_*_TIMEOUT variable).", + )); + } + Ok(parse_outcome(&out.stdout_str(), out.code, out.stderr_str())) +} + +/// Interpret agy's stdout. JSON when `--output-format json` worked; plain +/// text otherwise (treated as the answer). +pub(crate) fn parse_outcome(stdout: &str, exit_code: Option, stderr: String) -> Outcome { + let parsed = json::parse(stdout.trim()) + .ok() + .filter(|v| v.as_object().is_some()); + let Some(v) = parsed else { + return Outcome { + response: stdout.trim_end().to_string(), + status: None, + finished_reason: None, + denied: Vec::new(), + exit_code, + stderr, + }; + }; + let s = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string); + let denied = v + .get("denied_actions") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .map(|d| Denied { + action: d + .get("action") + .and_then(Value::as_str) + .unwrap_or("?") + .to_string(), + display_name: d + .get("display_name") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + }) + .collect() + }) + .unwrap_or_default(); + Outcome { + response: s("response").unwrap_or_default().trim_end().to_string(), + status: s("status"), + finished_reason: s("finished_reason"), + denied, + exit_code, + stderr, + } +} + +fn describe(d: &Denied) -> String { + if d.display_name.is_empty() || d.display_name == d.action { + d.action.clone() + } else { + format!("{} ({})", d.display_name, d.action) + } +} + +/// agy's stderr for display: drop its hint to re-run with +/// --dangerously-skip-permissions — on a read-only command that advice is +/// exactly what must not happen, and Claude tends to follow such hints. +fn sanitized_stderr(stderr: &str) -> String { + stderr + .lines() + .filter(|l| !l.contains("dangerously-skip-permissions")) + .map(str::trim_end) + .filter(|l| !l.is_empty()) + .collect::>() + .join("\n") +} + +/// Print an outcome the way every read-only command does: the answer on +/// stdout, blocked actions as notes on stderr. Returns the exit code. +pub(crate) fn report(outcome: &Outcome) -> Result { + for d in &outcome.denied { + eprintln!( + "[agy-plugin] note: agy tried to use {}, which this read-only command blocks.", + describe(d) + ); + } + // JSON status when agy gave one; otherwise (plain-text output) its exit + // code decides. + let failed_status = match outcome.status.as_deref() { + Some(s) => s != "SUCCESS", + None => outcome.exit_code.is_some_and(|c| c != 0), + }; + if !outcome.response.is_empty() { + println!("{}", outcome.response); + if let Some(reason) = &outcome.finished_reason { + eprintln!( + "[agy-plugin] note: agy's answer may be incomplete (finished_reason: {reason})." + ); + } + return Ok(if failed_status { 1 } else { 0 }); + } + let mut msg = String::from("error: agy returned no answer."); + if !outcome.denied.is_empty() { + let list: Vec = outcome.denied.iter().map(describe).collect(); + msg.push_str(&format!( + "\n It tried to use tools this read-only command blocks: {}.\n In this read-only command agy can read only what the plugin handed it and can't change anything.", + list.join(", ") + )); + } + if let Some(st) = &outcome.status { + msg.push_str(&format!("\n agy status: {st}")); + } + if let Some(r) = &outcome.finished_reason { + msg.push_str(&format!(" (finished_reason: {r})")); + } + let err = sanitized_stderr(&outcome.stderr); + if !err.is_empty() { + let tail: Vec<&str> = err + .lines() + .rev() + .take(12) + .collect::>() + .into_iter() + .rev() + .collect(); + msg.push_str("\n agy said:"); + for l in tail { + msg.push_str(&format!("\n {l}")); + } + } + msg.push_str( + "\n Run `agy` interactively to debug, or check ~/.gemini/antigravity-cli/log/.", + ); + Err(Fail::runtime(msg)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn caller_print_timeout_wins_for_our_deadline() { + let none: Vec = vec![]; + let run = |extra| Run { + prompt: "p", + model: None, + timeout: "8m0s", + extra, + workspace: Workspace::Fresh { stage: None }, + }; + assert_eq!(effective_print_timeout(&run(&none)), "8m0s"); + let e = vec!["--print-timeout".to_string(), "20m".to_string()]; + assert_eq!(effective_print_timeout(&run(&e)), "20m"); + let e = vec![ + "--print-timeout=1h".to_string(), + "--effort".to_string(), + "low".to_string(), + ]; + assert_eq!(effective_print_timeout(&run(&e)), "1h"); + } + + #[test] + fn go_durations() { + assert_eq!(parse_go_duration("8m0s"), Some(Duration::from_secs(480))); + assert_eq!(parse_go_duration("10m"), Some(Duration::from_secs(600))); + assert_eq!(parse_go_duration("1h30m"), Some(Duration::from_secs(5400))); + assert_eq!(parse_go_duration("1.5s"), Some(Duration::from_millis(1500))); + assert_eq!(parse_go_duration("500ms"), Some(Duration::from_millis(500))); + assert_eq!(parse_go_duration("0"), Some(Duration::ZERO)); + assert_eq!(parse_go_duration("5x"), None); + assert_eq!(parse_go_duration(""), None); + assert_eq!(parse_go_duration("m"), None); + } + + #[test] + fn passthrough_allows_only_safe_flags() { + let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>(); + assert!(check_passthrough(&v(&[])).is_ok()); + assert!(check_passthrough(&v(&["--print-timeout", "20m", "--effort=high"])).is_ok()); + for bad in [ + &["--dangerously-skip-permissions"][..], + &["--mode", "auto"], + &["--settings={\"agentMode\":\"auto\"}"], + &["--add-dir", "/"], + &["--remote-agent"], + &["--print-timeout", "1m", "--mode=auto"], + // A value-less allowed flag would swallow the next token (our pin). + &["--effort"], + &["--effort", "--settings={}"], + &["--print-timeout="], + &["--effort=", "high"], + ] { + assert_eq!(check_passthrough(&v(bad)).unwrap_err().code, 64, "{bad:?}"); + } + } + + #[test] + fn args_put_the_mode_pin_last_and_never_auto_approve() { + let extra = vec!["--effort".to_string(), "high".to_string()]; + let run = Run { + prompt: "p", + model: None, + timeout: "8m0s", + extra: &extra, + workspace: Workspace::Fresh { stage: None }, + }; + let mode = vec![format!("--settings={}", crate::agy::READ_ONLY_SETTINGS)]; + let a = build_args( + Path::new("/tmp/ws"), + &run, + Some("gemini-3.8-flash-low"), + &mode, + "hello", + ); + assert_eq!( + a, + vec![ + "--sandbox", + "--add-dir", + "/tmp/ws", + "--print-timeout", + "8m0s", + "--output-format", + "json", + "--model", + "gemini-3.8-flash-low", + "--effort", + "high", + &mode[0], + "--print", + "hello", + ] + ); + assert!(!a.iter().any(|x| x.contains("dangerously"))); + } + + #[test] + fn prompt_cap_keeps_utf8_valid() { + let long = "é".repeat(DEFAULT_PROMPT_MAX_BYTES); // 2 bytes each + let capped = cap_prompt(&long); + assert!(capped.ends_with(TRUNCATION_MARKER)); + assert!(capped.len() <= DEFAULT_PROMPT_MAX_BYTES + TRUNCATION_MARKER.len()); + assert_eq!(cap_prompt("short"), "short"); + } + + #[test] + fn parses_real_agy_json_results() { + // agy 1.5.16, normal answer. + let o = parse_outcome( + r#"{"conversation_id":"0795","status":"SUCCESS","response":"OK\n","duration_seconds":3.0,"num_turns":1}"#, + Some(0), + String::new(), + ); + assert_eq!(o.response, "OK"); + assert_eq!(o.status.as_deref(), Some("SUCCESS")); + assert!(o.denied.is_empty()); + // agy 1.5.16, write blocked by Default mode (from the live probe). + let o = parse_outcome( + r#"{"status":"SUCCESS","response":"","denied_actions":[{"action":"write_file","display_name":"Edit"}]}"#, + Some(0), + "jetski: no output produced — ... re-run with --dangerously-skip-permissions to auto-approve all tools.\n".into(), + ); + assert_eq!( + o.denied, + vec![Denied { + action: "write_file".into(), + display_name: "Edit".into() + }] + ); + let err = report(&o).unwrap_err(); + assert!(err.message.contains("Edit (write_file)")); + assert!( + !err.message.contains("dangerously"), + "must not echo the skip-permissions hint" + ); + } + + #[test] + fn plain_text_stdout_is_the_answer() { + let o = parse_outcome("42\n", Some(0), String::new()); + assert_eq!(o.response, "42"); + assert_eq!(o.status, None); + } + + #[test] + fn error_status_with_partial_answer_exits_1() { + let o = parse_outcome( + r#"{"status":"ERROR","response":"partial","finished_reason":"print_timeout"}"#, + Some(3), + String::new(), + ); + assert_eq!(report(&o).unwrap(), 1); + } +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..2577927 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,425 @@ +//! Tiny argv parser (port of lib/args.mjs). +//! +//! - Boolean flags: `--background`; `--background=x` is an error. +//! - Value flags: `--model X` or `--model=X`; last occurrence wins. +//! - Unknown long flags go to `extra` so callers can forward agy-native +//! flags (`--sandbox`, `--print-timeout 10m`). +//! - `--` ends flag parsing; everything after is positional verbatim, so a +//! prompt that starts with `-` is safe. +//! - Single-dash tokens (`-x`, `-`) are positional. + +use std::collections::BTreeMap; + +/// Which long flags a command understands. +pub(crate) struct Schema<'a> { + pub boolean: &'a [&'a str], + pub value: &'a [&'a str], + /// Unknown-to-us flags that are known to take a value when forwarded to + /// agy (e.g. `print-timeout`). Only these swallow the following token. + pub passthrough_value: &'a [&'a str], +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub(crate) struct Parsed { + pub flags: BTreeMap, + pub values: BTreeMap>, + pub positional: Vec, + pub extra: Vec, + pub errors: Vec, +} + +impl Parsed { + /// True if the boolean flag was given. Unknown names are false. + pub(crate) fn flag(&self, name: &str) -> bool { + self.flags.get(name).copied().unwrap_or(false) + } + + /// The value flag's last value, if any. + pub(crate) fn value(&self, name: &str) -> Option<&str> { + self.values.get(name).and_then(|v| v.as_deref()) + } +} + +pub(crate) fn parse_args(argv: &[String], schema: &Schema) -> Parsed { + let mut out = Parsed::default(); + for &f in schema.boolean { + out.flags.insert(f.to_string(), false); + } + for &f in schema.value { + out.values.insert(f.to_string(), None); + } + + let mut i = 0; + while i < argv.len() { + let tok = &argv[i]; + if tok == "--" { + out.positional.extend(argv[i + 1..].iter().cloned()); + break; + } + let Some(body) = tok.strip_prefix("--") else { + out.positional.push(tok.clone()); + i += 1; + continue; + }; + let (name, inline) = match body.split_once('=') { + Some((n, v)) => (n, Some(v)), + None => (body, None), + }; + + if schema.boolean.contains(&name) { + if inline.is_some() { + out.errors.push(format!("--{name} does not take a value")); + } else { + out.flags.insert(name.to_string(), true); + } + i += 1; + continue; + } + + if schema.value.contains(&name) { + match inline { + Some("") => out + .errors + .push(format!("--{name}= requires a non-empty value")), + Some(v) => { + out.values.insert(name.to_string(), Some(v.to_string())); + } + None => match argv.get(i + 1) { + // Taken unconditionally (even if it starts with `-`), as + // before: `--model -x` means the model is `-x`. + Some(v) => { + out.values.insert(name.to_string(), Some(v.clone())); + i += 1; + } + None => out.errors.push(format!("--{name} requires a value")), + }, + } + i += 1; + continue; + } + + // Unknown long flag: forward it. Deliberate fix vs args.mjs: the old + // parser swallowed ANY following non-dash token, so + // `rescue --sandbox fix the bug` silently lost "fix" from the task. + // Now only flags declared as value-taking consume the next token, and + // never one that looks like a flag (so `--print-timeout --wait` + // keeps our `--wait`, and `--print-timeout -- task` keeps `--`). + out.extra.push(tok.clone()); + if inline.is_none() + && schema.passthrough_value.contains(&name) + && let Some(next) = argv.get(i + 1) + && !next.starts_with('-') + { + out.extra.push(next.clone()); + i += 1; + } + i += 1; + } + out +} + +/// Positional args joined with single spaces and trimmed (JS `.trim()` +/// semantics, see `js_trim`). +pub(crate) fn join_positional(p: &Parsed) -> String { + js_trim(&p.positional.join(" ")).to_string() +} + +/// `String.prototype.trim` exactly. Rust's `str::trim` uses Unicode +/// White_Space, which differs from ECMAScript's WhiteSpace+LineTerminator +/// set: JS also strips U+FEFF (BOM) and does NOT strip U+0085 (NEL). +/// Prompts must stay byte-identical to the Node runtime, so use this. +pub(crate) fn js_trim(s: &str) -> &str { + s.trim_matches(is_js_whitespace) +} + +fn is_js_whitespace(c: char) -> bool { + matches!( + c, + '\u{9}'..='\u{D}' + | ' ' + | '\u{A0}' + | '\u{1680}' + | '\u{2000}'..='\u{200A}' + | '\u{2028}' + | '\u{2029}' + | '\u{202F}' + | '\u{205F}' + | '\u{3000}' + | '\u{FEFF}' + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SCHEMA: Schema<'static> = Schema { + boolean: &["background", "wait", "resume", "fresh"], + value: &["model", "base", "name", "output"], + passthrough_value: &["print-timeout"], + }; + + fn argv(a: &[&str]) -> Vec { + a.iter().map(|s| s.to_string()).collect() + } + + fn parse(a: &[&str]) -> Parsed { + parse_args(&argv(a), &SCHEMA) + } + + // --- ported from tests/lib.args.test.mjs --- + + #[test] + fn defaults_for_empty_argv() { + let r = parse(&[]); + assert!(!r.flag("background")); + assert_eq!(r.flags.get("background"), Some(&false)); + assert_eq!(r.values.get("model"), Some(&None)); + assert_eq!(r.value("model"), None); + assert!(r.positional.is_empty()); + assert!(r.errors.is_empty()); + assert!(r.extra.is_empty()); + assert_eq!(r.flags.len(), 4); + assert_eq!(r.values.len(), 4); + } + + #[test] + fn boolean_flag() { + let r = parse(&["--background", "task", "text"]); + assert!(r.flag("background")); + assert_eq!(r.positional, ["task", "text"]); + } + + #[test] + fn value_space_separated() { + let r = parse(&["--model", "opus", "fix", "the", "bug"]); + assert_eq!(r.value("model"), Some("opus")); + assert_eq!(r.positional, ["fix", "the", "bug"]); + } + + #[test] + fn value_equals_form() { + let r = parse(&["--model=opus", "fix", "bug"]); + assert_eq!(r.value("model"), Some("opus")); + assert_eq!(r.positional, ["fix", "bug"]); + } + + #[test] + fn value_equals_empty_is_error() { + let r = parse(&["--model="]); + assert_eq!(r.value("model"), None); + assert_eq!(r.errors, ["--model= requires a non-empty value"]); + } + + #[test] + fn value_missing_at_end_is_error() { + let r = parse(&["--model"]); + assert_eq!(r.errors, ["--model requires a value"]); + assert_eq!(r.value("model"), None); + } + + #[test] + fn boolean_with_value_is_error() { + let r = parse(&["--background=yes"]); + assert_eq!(r.errors, ["--background does not take a value"]); + assert!(!r.flag("background")); + // Empty inline value is still a value. + let r = parse(&["--background="]); + assert_eq!(r.errors, ["--background does not take a value"]); + } + + #[test] + fn unknown_flags_forwarded_to_extra() { + let r = parse(&["--sandbox", "--print-timeout", "10m", "do", "the", "thing"]); + assert_eq!(r.extra, ["--sandbox", "--print-timeout", "10m"]); + assert_eq!(r.positional, ["do", "the", "thing"]); + } + + #[test] + fn double_dash_terminates() { + let r = parse(&["--model", "opus", "--", "--this-is-not-a-flag", "task"]); + assert_eq!(r.value("model"), Some("opus")); + assert_eq!(r.positional, ["--this-is-not-a-flag", "task"]); + } + + #[test] + fn base_with_positional() { + let r = parse(&["--base", "main", "focus", "on", "race", "conditions"]); + assert_eq!(r.value("base"), Some("main")); + assert_eq!(r.positional, ["focus", "on", "race", "conditions"]); + } + + #[test] + fn multiple_booleans() { + let r = parse(&["--background", "--wait", "--resume", "go"]); + assert!(r.flag("background") && r.flag("wait") && r.flag("resume")); + assert!(!r.flag("fresh")); + assert_eq!(r.positional, ["go"]); + } + + #[test] + fn join_positional_single_spaces() { + let r = parse(&["--background", "hello", "world"]); + assert_eq!(join_positional(&r), "hello world"); + } + + #[test] + fn join_positional_trims() { + assert_eq!(join_positional(&parse(&[" hi "])), "hi"); + assert_eq!(join_positional(&parse(&[])), ""); + // Inner whitespace is preserved. + assert_eq!(join_positional(&parse(&[" a ", " b "])), "a b"); + } + + // --- the deliberate fix --- + + #[test] + fn unknown_flag_does_not_swallow_task_words() { + // Old args.mjs produced extra=["--sandbox","fix"], positional=["the","bug"]. + let r = parse(&["--sandbox", "fix", "the", "bug"]); + assert_eq!(r.extra, ["--sandbox"]); + assert_eq!(r.positional, ["fix", "the", "bug"]); + assert_eq!(join_positional(&r), "fix the bug"); + } + + #[test] + fn unknown_flag_inline_value() { + let r = parse(&["--sandbox=strict", "task"]); + assert_eq!(r.extra, ["--sandbox=strict"]); + assert_eq!(r.positional, ["task"]); + let r = parse(&["--print-timeout=10m", "task"]); + assert_eq!(r.extra, ["--print-timeout=10m"]); + assert_eq!(r.positional, ["task"]); + } + + #[test] + fn passthrough_value_does_not_take_flags_or_terminator() { + let r = parse(&["--print-timeout", "--wait", "go"]); + assert_eq!(r.extra, ["--print-timeout"]); + assert!(r.flag("wait")); + assert_eq!(r.positional, ["go"]); + + let r = parse(&["--print-timeout", "--", "-x"]); + assert_eq!(r.extra, ["--print-timeout"]); + assert_eq!(r.positional, ["-x"]); + + let r = parse(&["--print-timeout", "-5"]); + assert_eq!(r.extra, ["--print-timeout"]); + assert_eq!(r.positional, ["-5"]); + } + + #[test] + fn passthrough_value_at_end() { + let r = parse(&["task", "--print-timeout"]); + assert_eq!(r.extra, ["--print-timeout"]); + assert_eq!(r.positional, ["task"]); + assert!(r.errors.is_empty()); + } + + // --- more edge cases --- + + #[test] + fn value_flag_takes_next_token_unconditionally() { + let r = parse(&["--model", "--wait"]); + assert_eq!(r.value("model"), Some("--wait")); + assert!(!r.flag("wait")); + let r = parse(&["--model", "--"]); + assert_eq!(r.value("model"), Some("--")); + assert!(r.positional.is_empty()); + } + + #[test] + fn last_value_wins() { + let r = parse(&["--model", "a", "--model=b", "--model", "c"]); + assert_eq!(r.value("model"), Some("c")); + // A later error does not erase an earlier good value. + let r = parse(&["--model", "a", "--model="]); + assert_eq!(r.value("model"), Some("a")); + assert_eq!(r.errors.len(), 1); + } + + #[test] + fn value_keeps_text_after_first_equals() { + let r = parse(&["--model=a=b=c"]); + assert_eq!(r.value("model"), Some("a=b=c")); + let r = parse(&["--model==x"]); + assert_eq!(r.value("model"), Some("=x")); + } + + #[test] + fn single_dash_tokens_are_positional() { + let r = parse(&["-m", "opus", "-", "-background"]); + assert_eq!(r.positional, ["-m", "opus", "-", "-background"]); + assert!(r.extra.is_empty()); + } + + #[test] + fn empty_and_odd_long_flags() { + let r = parse(&["--=x", "---model", "y", ""]); + assert_eq!(r.extra, ["--=x", "---model"]); + assert_eq!(r.positional, ["y", ""]); + assert_eq!(r.value("model"), None); + } + + #[test] + fn double_dash_at_end_and_repeated() { + let r = parse(&["a", "--"]); + assert_eq!(r.positional, ["a"]); + let r = parse(&["--", "--", "--model", "x"]); + assert_eq!(r.positional, ["--", "--model", "x"]); + assert_eq!(r.value("model"), None); + } + + #[test] + fn flag_names_are_case_sensitive_and_exact() { + let r = parse(&["--Background", "--backgroundx", "--model-x"]); + assert!(!r.flag("background")); + assert_eq!(r.extra, ["--Background", "--backgroundx", "--model-x"]); + } + + #[test] + fn flag_and_value_unknown_names() { + let r = parse(&[]); + assert!(!r.flag("nope")); + assert_eq!(r.value("nope"), None); + } + + #[test] + fn non_ascii_tokens() { + let r = parse(&["--model=модель", "привет", "--ünknown", "😀"]); + assert_eq!(r.value("model"), Some("модель")); + assert_eq!(r.extra, ["--ünknown"]); + assert_eq!(r.positional, ["привет", "😀"]); + } + + #[test] + fn empty_schema() { + let s = Schema { + boolean: &[], + value: &[], + passthrough_value: &[], + }; + let r = parse_args(&argv(&["--x", "y"]), &s); + assert_eq!(r.extra, ["--x"]); + assert_eq!(r.positional, ["y"]); + assert!(r.flags.is_empty() && r.values.is_empty()); + } + + #[test] + fn js_trim_matches_ecmascript_set() { + // Exact set from Node: every BMP code point c where (c+"a").trim()==="a". + let js: Vec = vec![ + 0x9, 0xa, 0xb, 0xc, 0xd, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, + 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, + 0xfeff, + ]; + let ours: Vec = (0u32..0x11_0000) + .filter_map(char::from_u32) + .filter(|&c| is_js_whitespace(c)) + .map(u32::from) + .collect(); + assert_eq!(ours, js); + assert_eq!(js_trim("\u{FEFF} x \u{3000}"), "x"); + assert_eq!(js_trim("\u{85}x\u{85}"), "\u{85}x\u{85}"); + } +} diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 0000000..9b4bbd2 --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,1165 @@ +//! The /agy:* commands. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use crate::agy::{self, Agy}; +use crate::capture::{self, Run, Workspace}; +use crate::cli::{self, Schema}; +use crate::jobs::{self, CancelResult, NewJob, Resolved, Sink}; +use crate::json::{self, Map, Value}; +use crate::util::{self, CmdResult, Fail, TempDir}; + +pub(crate) const VERSION: &str = env!("CARGO_PKG_VERSION"); + +/// agy flags that take a value; listed so the parser forwards `--flag V` +/// as two tokens instead of eating the next word of a task. +const AGY_VALUE_FLAGS: &[&str] = &[ + "print-timeout", + "effort", + "add-dir", + "agent", + "mode", + "settings", + "log-file", + "conversation", + "resume", + "project", + "json-schema", + "output-format", + "input-format", + "model", +]; + +fn timeout_env(var: &str, default: &str) -> String { + match util::env_nonempty(var) { + Some(v) if capture::parse_go_duration(&v).is_some() => v, + Some(v) => { + eprintln!( + "[agy-plugin] note: ignoring {var}={v} (not a duration like 8m0s); using {default}" + ); + default.to_string() + } + None => default.to_string(), + } +} + +/// The workspace a command operates on: $CLAUDE_PROJECT_DIR if it is a +/// directory, else the nearest ancestor with a `.git`, else the cwd. +pub(crate) fn workspace_root() -> PathBuf { + if let Some(d) = util::env_nonempty("CLAUDE_PROJECT_DIR") { + let p = PathBuf::from(d); + if p.is_dir() { + return std::path::absolute(&p).unwrap_or(p); + } + } + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let mut cur: Option<&Path> = Some(&cwd); + while let Some(d) = cur { + if d.join(".git").exists() { + return d.to_path_buf(); + } + cur = d.parent(); + } + cwd +} + +fn usage_errors(errors: &[String]) -> Fail { + Fail::usage( + errors + .iter() + .map(|e| format!("error: {e}")) + .collect::>() + .join("\n"), + ) +} + +/// Leading `--model` handling for the single-target commands (ask, scrape, +/// doc-to-md): returns (model value if given, remaining args). +fn take_model(args: &[String]) -> Result<(Option, Vec), Fail> { + let mut model = None; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--model" { + let v = args.get(i + 1).cloned().unwrap_or_default(); + model = Some(v); + i += 2; + } else if let Some(v) = a.strip_prefix("--model=") { + model = Some(v.to_string()); + i += 1; + } else if a == "--" { + i += 1; + break; + } else { + break; + } + } + if model.as_deref().is_some_and(|m| m.trim().is_empty()) { + return Err(crate::models::empty_value_error( + agy::find_agy().map(Agy::at).as_ref(), + )); + } + Ok((model, args[i.min(args.len())..].to_vec())) +} + +fn resolve_model(agy: &Agy, model: Option<&str>) -> Result, Fail> { + match model { + None => Ok(None), + Some(m) => { + agy.require_supported()?; + crate::models::resolve(agy, m).map(Some) + } + } +} + +// --------------------------------------------------------------------------- +// check / help / version +// --------------------------------------------------------------------------- + +pub(crate) fn check() -> CmdResult { + let mut m = Map::new(); + match agy::find_agy() { + None => { + m.set("installed", false); + m.set("path", ""); + m.set("version", ""); + m.set("auth", "unknown"); + m.set( + "error", + format!("agy binary not found; install with: {}", agy::INSTALL_HINT), + ); + } + Some(p) => { + let a = Agy::at(p.clone()); + let version = a.version().unwrap_or("unknown").to_string(); + m.set("installed", true); + m.set("path", p.display().to_string()); + m.set("version", version.clone()); + m.set("auth", agy::auth_status().as_str()); + m.set("pluginVersion", VERSION); + let supported = + version != "unknown" && agy::version_at_least(&version, agy::MIN_AGY_VERSION); + m.set("supported", supported); + m.set( + "error", + if supported || version == "unknown" { + String::new() + } else { + format!("agy {version} is too old; this plugin needs {} or newer (run `agy update`)", agy::MIN_AGY_VERSION) + }, + ); + } + } + println!("{}", json::to_string_compact(&Value::Object(m))); + Ok(0) +} + +pub(crate) fn version() -> CmdResult { + let mut m = Map::new(); + m.set("version", VERSION); + println!("{}", json::to_string_compact(&Value::Object(m))); + Ok(0) +} + +const HELP_HEAD: &str = "\ +/agy:* commands (Claude Code plugin for the Antigravity CLI) + +Read-only (agy can read, not change anything) + /agy:ask [--model A] One-shot prompt; returns agy's answer. + /agy:review [--base REF] [--background] [--wait] [--model A] [focus] + Review the working-tree diff (or branch vs REF). + /agy:adversarial-review [same flags] [focus] + Challenge the design, not just the lines. + /agy:scrape [--model A] Fetch a web page -> Markdown. SSRF-guarded. + /agy:doc-to-md [--model A] Convert a local document -> Markdown (allow-listed types). + +Write-capable (agy runs with auto-approve) + /agy:rescue [--isolate] [--allow-dirty] [--background] [--wait] [--resume|--fresh] [--model A] + Let agy edit files. --isolate works in a throwaway + git worktree and gives you a patch instead. + /agy:image [--name S] [--output P] + Generate an image with agy's built-in tool. + +Jobs (background review / rescue) + /agy:status [id] /agy:result [id] /agy:cancel [id] + +Other + /agy:setup Check that agy is installed, logged in and new enough. + /agy:delegate, /agy:research Hand work to the agy:runner subagent (uses ask). + /agy:help This help. + +Model selection (--model) +"; + +const HELP_TAIL: &str = " +How --model works + Aliases resolve at call time against `agy models` to the newest model in + their family, so a new Gemini/Claude release is picked up without a plugin + update. Any id or display name that `agy models` lists is also accepted + verbatim. The result goes to agy's own --model flag for that call only; + settings.json is never touched. Unknown names fail with exit 64. + +Read-only commands + agy runs from a throwaway directory (your repo is outside its workspace), + pinned to its Default agent mode for that run, without + --dangerously-skip-permissions: it can read, but writes outside that + directory are denied and reported. agy 1.5.7+ would otherwise start + headless runs in Auto mode, which approves such writes. + +Requires agy 1.2.0 or newer. `agy --help` lists agy's own flags. +"; + +pub(crate) fn help() -> CmdResult { + let models = agy::find_agy() + .map(Agy::at) + .as_ref() + .and_then(crate::models::list_models); + print!( + "{HELP_HEAD}{}{HELP_TAIL}", + crate::models::format_model_table(models.as_deref()) + ); + Ok(0) +} + +// --------------------------------------------------------------------------- +// ask / scrape / doc-to-md +// --------------------------------------------------------------------------- + +pub(crate) fn ask(args: &[String]) -> CmdResult { + let (model, rest) = take_model(args)?; + let Some(prompt) = rest.first().filter(|p| !p.is_empty()) else { + return Err(Fail::usage("error: ask requires a prompt argument")); + }; + // Everything after the prompt is forwarded to agy (agents/runner.md + // documents this), but only flags that can't widen agy's access. + let extra = rest[1..].to_vec(); + capture::check_passthrough(&extra)?; + let agy = Agy::ready()?; + let model = resolve_model(&agy, model.as_deref())?; + let timeout = timeout_env("AGY_ASK_TIMEOUT", "8m0s"); + let outcome = capture::run_readonly( + &agy, + &Run { + prompt, + model: model.as_deref(), + timeout: &timeout, + extra: &extra, + workspace: Workspace::Fresh { stage: None }, + }, + )?; + capture::report(&outcome) +} + +pub(crate) fn scrape(args: &[String]) -> CmdResult { + let (model, rest) = take_model(args)?; + let Some(url) = rest.first().filter(|u| !u.is_empty()) else { + return Err(Fail::usage( + "error: scrape requires a URL argument (http/https)", + )); + }; + let safe = crate::guard::validate_scrape_url(url) + .map_err(|r| Fail::refused(format!("error: refusing to scrape this URL — {r}")))?; + let agy = Agy::ready()?; + agy.require_supported()?; + agy.readonly_mode_args()?; + let model = resolve_model(&agy, model.as_deref())?; + // The plugin downloads the page itself (SSRF-checked, DNS-pinned, + // redirects re-checked) and agy only converts the saved copy: a + // read-only agy run has no way to fetch a URL. + let download = TempDir::new("agy-fetch-") + .map_err(|e| Fail::runtime(format!("error: could not create a temp dir: {e}")))?; + let saved = download.path().join("page"); + let page = crate::fetch::fetch(&safe, &saved, &crate::fetch::guard_policy()) + .map_err(|r| Fail::refused(format!("error: refusing to scrape this URL — {r}")))?; + let staged = format!("page.{}", page.ext); + let prompt = format!( + "Read the file named \"{staged}\" in your workspace. It is the web page downloaded from {} (use that address to resolve relative links). Return its MAIN readable content as clean Markdown — preserve headings, lists, links, tables, and code blocks; drop nav/ads/boilerplate. Output ONLY the Markdown, no preamble.", + page.final_url + ); + let timeout = timeout_env("AGY_SCRAPE_TIMEOUT", "5m0s"); + let outcome = capture::run_readonly( + &agy, + &Run { + prompt: &prompt, + model: model.as_deref(), + timeout: &timeout, + extra: &[], + workspace: Workspace::Fresh { + stage: Some((&saved, &staged)), + }, + }, + )?; + capture::report(&outcome) +} + +pub(crate) fn doc_to_md(args: &[String]) -> CmdResult { + let (model, rest) = take_model(args)?; + let Some(input) = rest.first().filter(|p| !p.is_empty()) else { + return Err(Fail::usage("error: doc-to-md requires a file path")); + }; + let cwd = std::env::current_dir() + .map_err(|e| Fail::runtime(format!("error: no current directory: {e}")))?; + // Without a home dir every ~/... deny entry would be meaningless: fail + // closed rather than check against nothing. + let home = util::home_dir() + .filter(|h| h.is_absolute()) + .ok_or_else(|| Fail::refused("error: refusing to convert this file — cannot determine your home directory to check it against the sensitive-path list"))?; + let real = crate::guard::validate_doc_path(input, &cwd, &home) + .map_err(|r| Fail::refused(format!("error: refusing to convert this file — {r}")))?; + let agy = Agy::ready()?; + let model = resolve_model(&agy, model.as_deref())?; + // A FIXED name from the validated extension: the untrusted original file + // name never reaches agy's prompt. + let ext = real + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()) + .unwrap_or_default(); + let staged = format!("document.{ext}"); + let prompt = format!( + "Read the file named \"{staged}\" in your workspace and convert it to clean, well-structured Markdown. Preserve headings, lists, tables, links, and code blocks. Output ONLY the Markdown — no preamble, no commentary." + ); + let timeout = timeout_env("AGY_DOCTOMD_TIMEOUT", "8m0s"); + let outcome = capture::run_readonly( + &agy, + &Run { + prompt: &prompt, + model: model.as_deref(), + timeout: &timeout, + extra: &[], + workspace: Workspace::Fresh { + stage: Some((&real, &staged)), + }, + }, + )?; + capture::report(&outcome) +} + +// --------------------------------------------------------------------------- +// The job runner (used in-process for foreground jobs and by `_run-job`) +// --------------------------------------------------------------------------- + +fn meta_str<'a>(rec: &'a Value, key: &str) -> Option<&'a str> { + rec.get("meta") + .and_then(|m| m.get(key)) + .and_then(Value::as_str) +} + +fn record_args(rec: &Value) -> Vec { + rec.get("args") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() +} + +fn record_model(rec: &Value) -> Option { + rec.get("model") + .and_then(Value::as_str) + .filter(|s| !s.is_empty()) + .map(str::to_string) +} + +/// Run the agy part of a job record and write its output to `sink`. +pub(crate) fn default_runner(rec: &Value, sink: &mut Sink) -> Option { + let id = jobs::id_of(rec).to_string(); + let agy = Agy::at(PathBuf::from(meta_str(rec, "agyBin").unwrap_or("agy"))); + let prompt = meta_str(rec, "prompt").unwrap_or("").to_string(); + let model = record_model(rec); + let args = record_args(rec); + match rec.get("kind").and_then(Value::as_str) { + Some("review") | Some("adversarial-review") => { + let Some(stage) = meta_str(rec, "stageDir").map(PathBuf::from) else { + sink.emit(&format!( + "[agy-job {id}] error: review job has no stage dir\n" + )); + return Some(1); + }; + let timeout = timeout_env("AGY_REVIEW_TIMEOUT", "10m0s"); + let res = capture::run_readonly( + &agy, + &Run { + prompt: &prompt, + model: model.as_deref(), + timeout: &timeout, + extra: &args, + workspace: Workspace::Existing(&stage), + }, + ); + // The worker is the stage dir's last reader. + let _ = std::fs::remove_dir_all(&stage); + match res { + Err(f) => { + sink.emit(&format!("{}\n", f.message)); + Some(f.code) + } + Ok(outcome) => { + for d in &outcome.denied { + sink.emit(&format!( + "[agy-job {id}] note: agy tried to use {} ({}), which this read-only command blocks.\n", + d.display_name, d.action + )); + } + if outcome.response.is_empty() { + sink.emit(&format!( + "[agy-job {id}] error: agy returned no answer (status: {}).\n", + outcome.status.as_deref().unwrap_or("?") + )); + return Some(1); + } + sink.emit(&format!("{}\n", outcome.response)); + Some( + if outcome.status.as_deref().is_some_and(|s| s != "SUCCESS") { + 1 + } else { + 0 + }, + ) + } + } + } + Some("rescue") => run_rescue_agy(&agy, rec, &prompt, model.as_deref(), &args, sink), + other => { + sink.emit(&format!( + "[agy-job {id}] error: don't know how to run a '{}' job\n", + other.unwrap_or("?") + )); + Some(1) + } + } +} + +/// Write-capable run: agy edits files in the execution root with +/// auto-approval. Safety comes from rescue's clean-tree / --isolate rails. +fn run_rescue_agy( + agy: &Agy, + rec: &Value, + task: &str, + model: Option<&str>, + extra: &[String], + sink: &mut Sink, +) -> Option { + let root = meta_str(rec, "executionRoot") + .or_else(|| rec.get("workspaceRoot").and_then(Value::as_str)) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")); + let mut args: Vec = vec![ + "--dangerously-skip-permissions".into(), + "--add-dir".into(), + root.display().to_string(), + "--output-format".into(), + "json".into(), + ]; + if let Some(m) = model { + args.push("--model".into()); + args.push(m.into()); + } + let timeout = timeout_env("AGY_RESCUE_TIMEOUT", "0"); + if timeout != "0" { + args.push("--print-timeout".into()); + args.push(timeout.clone()); + } + args.extend(extra.iter().cloned()); + args.push("--print".into()); + args.push(capture::cap_prompt(task)); + let mut cmd = agy.command(); + cmd.args(&args) + .current_dir(&root) + .env_remove("AGY_JOB_WORKSPACE"); + // --isolate: don't hand agy pointers to the real repository either. + if meta_str(rec, "executionRoot").is_some() { + for k in capture::REPO_ENV_HINTS { + cmd.env_remove(k); + } + } + let deadline = capture::parse_go_duration(&timeout) + .filter(|d| !d.is_zero()) + .map(|d| d + Duration::from_secs(120)); + let out = match util::run_captured_notify(&mut cmd, deadline, &crate::jobs::note_child) { + Ok(o) => o, + Err(e) => { + sink.emit(&format!("error: could not run agy: {e}\n")); + return Some(127); + } + }; + let outcome = capture::parse_outcome(&out.stdout_str(), out.code, out.stderr_str()); + let err = out.stderr_str(); + if !err.trim().is_empty() { + sink.emit(&format!("{}\n", err.trim_end())); + } + if !outcome.response.is_empty() { + sink.emit(&format!("{}\n", outcome.response)); + } + if out.timed_out { + sink.emit("error: agy did not finish within AGY_RESCUE_TIMEOUT.\n"); + return None; + } + match (out.code, outcome.status.as_deref()) { + (Some(0), Some("SUCCESS") | None) => Some(0), + (Some(0), Some(_)) => Some(1), + (code, _) => code, + } +} + +// --------------------------------------------------------------------------- +// review / adversarial-review +// --------------------------------------------------------------------------- + +const REVIEW_SCHEMA: Schema<'static> = Schema { + boolean: &["background", "wait"], + value: &["model", "base"], + passthrough_value: AGY_VALUE_FLAGS, +}; + +fn secret_block(hits: &[&str], what: &str) -> Result<(), Fail> { + if hits.is_empty() { + return Ok(()); + } + let list: String = hits.iter().map(|h| format!("\n - {h}")).collect(); + if util::env_nonempty("AGY_REVIEW_ALLOW_SECRETS").as_deref() != Some("1") { + return Err(Fail::refused(format!( + "error: {what} matches common secret patterns:{list}\n\nReviewing it would forward those values to Google's Gemini API.\nRemove them, or set AGY_REVIEW_ALLOW_SECRETS=1 to proceed." + ))); + } + eprintln!( + "WARNING: {what} matches common secret patterns:{list}\nProceeding because AGY_REVIEW_ALLOW_SECRETS=1 — those values will be sent to Gemini." + ); + Ok(()) +} + +pub(crate) fn review(args: &[String], adversarial: bool) -> CmdResult { + let name = if adversarial { + "adversarial-review" + } else { + "review" + }; + let p = cli::parse_args(args, &REVIEW_SCHEMA); + if !p.errors.is_empty() { + return Err(usage_errors(&p.errors)); + } + if p.value("model").is_some_and(|m| m.trim().is_empty()) { + return Err(crate::models::empty_value_error(None)); + } + capture::check_passthrough(&p.extra)?; + let root = workspace_root(); + let agy = Agy::ready()?; + agy.require_supported()?; + // Fail closed BEFORE doing any work if agy can't be pinned read-only. + agy.readonly_mode_args()?; + let model = resolve_model(&agy, p.value("model"))?; + + let base = p.value("base"); + let ctx = match base { + Some(b) => crate::git::branch_diff(&root, b)?, + None => crate::git::working_tree_diff(&root)?, + }; + if ctx.diff.trim().is_empty() { + return Err(Fail::runtime(match (&ctx.scope, base) { + (crate::prompts::Scope::Branch { merge_base, .. }, Some(b)) => format!( + "No diff between this branch and `{b}` (merge-base: {}). Nothing to review.", + merge_base.as_deref().unwrap_or("?") + ), + _ => "No working-tree diff. Stage or make changes first.".to_string(), + })); + } + // Every line of the diff goes to Gemini — removed and context lines too + // (`git rm .env` puts the whole secret file on `-` lines) — so scan all + // of it, not only the added lines. + secret_block(&crate::secrets::scan_text(&ctx.diff), "the diff")?; + + util::sweep_stale_temp(OUR_TEMP_PREFIXES, Duration::from_secs(24 * 3600)); + let stage = TempDir::new("agy-review-") + .map_err(|e| Fail::runtime(format!("error: could not create the review stage dir: {e}")))?; + let staged = + crate::git::stage_review_materials(stage.path(), &ctx.root, &ctx.files, &ctx.diff)?; + // Pass 2: the full content of every staged file is shipped as context, + // including lines the diff never touched. + let mut hits: Vec<&'static str> = Vec::new(); + for rel in &staged.staged { + if let Ok(t) = std::fs::read_to_string(stage.path().join("files").join(rel)) { + for h in crate::secrets::scan_text(&t) { + if !hits.contains(&h) { + hits.push(h); + } + } + } + } + secret_block(&hits, "the full content of a changed file")?; + + let focus = cli::join_positional(&p); + let stage_str = stage.path().display().to_string(); + let prompt = if adversarial { + crate::prompts::build_adversarial_prompt( + &ctx.scope, + &focus, + &stage_str, + &staged.staged, + &staged.omitted, + ) + } else { + crate::prompts::build_review_prompt( + &ctx.scope, + &focus, + &stage_str, + &staged.staged, + &staged.omitted, + ) + }; + let mut task = name.to_string(); + if let Some(b) = base { + task.push_str(&format!(" (--base {b})")); + } + if !focus.is_empty() { + task.push_str(&format!(": {focus}")); + } + let background = p.flag("background"); + // The worker owns (and deletes) the stage dir from here on. + let stage_path = stage.keep(); + let rec = jobs::create_job( + &root, + NewJob { + kind: if adversarial { + "adversarial-review" + } else { + "review" + }, + task: task.clone(), + model, + args: p.extra.clone(), + background, + prompt, + agy_bin: agy.path().display().to_string(), + execution_root: None, + stage_dir: Some(stage_path.clone()), + }, + ) + .inspect_err(|_| { + let _ = std::fs::remove_dir_all(&stage_path); + })?; + let id = jobs::id_of(&rec).to_string(); + if !background { + let st = jobs::run_worker(&root, &id, true, &default_runner)?; + return Ok(if st == "completed" { 0 } else { 1 }); + } + jobs::spawn_worker(&root, &id)?; + if p.flag("wait") { + println!("Started {task} job {id}. Waiting..."); + return wait_and_print(&root, &id, None); + } + println!( + "Started {task} job {id} in background.\nCheck progress: /agy:status {id}\nRead output: /agy:result {id}\nCancel: /agy:cancel {id}" + ); + Ok(0) +} + +fn wait_and_print(root: &Path, id: &str, git_summary: Option<&Path>) -> CmdResult { + let fin = jobs::wait_for_job( + root, + id, + Duration::from_secs(600), + Duration::from_millis(750), + )? + .ok_or_else(|| Fail::runtime(format!("Job {id} disappeared while waiting.")))?; + let log = jobs::read_log(root, id)?; + print!("{log}"); + if !log.is_empty() && !log.ends_with('\n') { + println!(); + } + if let Some(dir) = git_summary { + println!( + "\n=== changes agy made (review before committing) ===\n{}", + crate::git::change_summary(dir) + ); + } + let st = jobs::status_of(&fin); + println!("\nJob {id} ended with status: {st}"); + if st == "running" || st == "pending" { + println!("(still running after 10 minutes — check later with /agy:status {id})"); + } + Ok(if st == "completed" { 0 } else { 1 }) +} + +// --------------------------------------------------------------------------- +// rescue +// --------------------------------------------------------------------------- + +const RESCUE_SCHEMA: Schema<'static> = Schema { + boolean: &[ + "background", + "wait", + "resume", + "fresh", + "isolate", + "allow-dirty", + ], + value: &["model"], + passthrough_value: AGY_VALUE_FLAGS, +}; + +pub(crate) fn rescue(args: &[String]) -> CmdResult { + let p = cli::parse_args(args, &RESCUE_SCHEMA); + if !p.errors.is_empty() { + return Err(usage_errors(&p.errors)); + } + if p.flag("resume") && p.flag("fresh") { + return Err(Fail::usage( + "error: --resume and --fresh are mutually exclusive", + )); + } + let task = cli::join_positional(&p); + if task.is_empty() { + return Err(Fail::usage("rescue: task description is required")); + } + if p.value("model").is_some_and(|m| m.trim().is_empty()) { + return Err(crate::models::empty_value_error(None)); + } + let root = workspace_root(); + let agy = Agy::ready()?; + agy.require_supported()?; + let model = resolve_model(&agy, p.value("model"))?; + let mut extra = p.extra.clone(); + // --fresh is the default (a new conversation); --resume continues the + // most recent one. + if p.flag("resume") { + extra.push("--continue".into()); + } + let agy_bin = agy.path().display().to_string(); + + if p.flag("isolate") { + if !crate::git::is_repo(&root) { + return Err(Fail::runtime( + "rescue --isolate: requires a git repo (worktree isolation needs git).", + )); + } + if p.flag("background") { + println!( + "[note] --isolate runs in the foreground so it can show you the patch; ignoring --background." + ); + } + let wt_parent = TempDir::new("agy-isolate-") + .map_err(|e| Fail::runtime(format!("error: could not create a temp dir: {e}")))?; + let wt = wt_parent.path().join("wt"); + crate::git::isolated_checkout(&root, &wt).map_err(|e| { + Fail::runtime(format!( + "rescue --isolate: could not create the isolated checkout: {e}" + )) + })?; + let result = (|| -> CmdResult { + let rec = jobs::create_job( + &root, + NewJob { + kind: "rescue", + task: task.clone(), + model: model.clone(), + args: extra.clone(), + background: false, + prompt: task.clone(), + agy_bin: agy_bin.clone(), + execution_root: Some(wt.clone()), + stage_dir: None, + }, + )?; + let id = jobs::id_of(&rec).to_string(); + let st = jobs::run_worker(&root, &id, true, &default_runner)?; + let (stat, patch) = crate::git::isolated_patch(&wt); + println!("\n=== isolated changes (your working tree was NOT touched) ==="); + if !stat.is_empty() && !patch.trim().is_empty() { + println!("{stat}"); + let pf = jobs::patch_path(&root, &id); + jobs::write_atomic(&pf, patch.as_bytes()) + .map_err(|e| Fail::runtime(format!("error: could not save the patch: {e}")))?; + let rel = pf + .strip_prefix(&root) + .map(Path::to_path_buf) + .unwrap_or(pf.clone()); + let rel = rel.display(); + println!( + "\nReview the patch: {rel}\nApply it: git apply \"{rel}\"\nDiscard it: rm \"{rel}\" (your tree is already untouched)\n" + ); + } else { + println!("(agy made no file changes.)"); + } + Ok(if st == "completed" { 0 } else { 1 }) + })(); + crate::git::remove_isolated(&wt); + return result; + } + + let in_repo = crate::git::is_repo(&root); + if in_repo { + if !crate::git::is_clean(&root) && !p.flag("allow-dirty") { + return Err(Fail::runtime( + "rescue: refusing to run on a dirty working tree.\n agy edits files in place with auto-approval, so a clean git\n baseline is your only easy undo. Choose one:\n - commit or stash your changes first, or\n - run with --isolate (agy edits a throwaway worktree, you get a patch), or\n - pass --allow-dirty to override (you accept the risk).", + )); + } + } else { + eprintln!( + "[warn] not a git repo — no clean-tree safety net; agy will edit files in place with auto-approval." + ); + } + let background = p.flag("background"); + let rec = jobs::create_job( + &root, + NewJob { + kind: "rescue", + task: task.clone(), + model, + args: extra, + background, + prompt: task, + agy_bin, + execution_root: None, + stage_dir: None, + }, + )?; + let id = jobs::id_of(&rec).to_string(); + if !background { + let st = jobs::run_worker(&root, &id, true, &default_runner)?; + if in_repo { + println!( + "\n=== changes agy made (review before committing) ===\n{}", + crate::git::change_summary(&root) + ); + } + return Ok(if st == "completed" { 0 } else { 1 }); + } + jobs::spawn_worker(&root, &id)?; + if p.flag("wait") { + println!("Started agy job {id} in background. Waiting..."); + return wait_and_print(&root, &id, in_repo.then_some(root.as_path())); + } + println!( + "Started agy job {id} in background.\nCheck progress: /agy:status {id}\nRead output: /agy:result {id}\nCancel: /agy:cancel {id}\nWhen it finishes, run `git diff` to review what agy changed." + ); + Ok(0) +} + +// --------------------------------------------------------------------------- +// image (write-capable: agy needs auto-approval to run generate_image) +// --------------------------------------------------------------------------- + +/// The image source must lie inside agy's own artifact dirs; a prompt- +/// injected marker could otherwise make us copy any host file to --output. +pub(crate) fn image_source_allowed(src: &Path, home: &Path) -> bool { + let Ok(real) = std::fs::canonicalize(src) else { + return false; + }; + ["brain", "scratch", "cache"].iter().any(|d| { + let base = home.join(".gemini").join("antigravity-cli").join(d); + let canon = std::fs::canonicalize(&base).unwrap_or(base.clone()); + (real.starts_with(&base) && real != base) || (real.starts_with(&canon) && real != canon) + }) +} + +pub(crate) fn image(args: &[String]) -> CmdResult { + let mut name: Option = None; + let mut output: Option = None; + let mut positional: Vec = Vec::new(); + let mut i = 0; + while i < args.len() { + let a = &args[i]; + match a.as_str() { + "--name" | "--output" => { + let Some(v) = args.get(i + 1).filter(|v| !v.is_empty()) else { + return Err(Fail::usage(if a == "--name" { + "error: --name requires a value (e.g. --name coffee_cup)" + } else { + "error: --output requires a path (e.g. --output /tmp/out.png)" + })); + }; + if a == "--name" { + name = Some(v.clone()) + } else { + output = Some(v.clone()) + } + i += 2; + continue; + } + "--" => { + positional.extend(args[i + 1..].iter().cloned()); + break; + } + _ => {} + } + if let Some(v) = a.strip_prefix("--name=") { + if v.is_empty() { + return Err(Fail::usage("error: --name= requires a non-empty value")); + } + name = Some(v.to_string()); + } else if let Some(v) = a.strip_prefix("--output=") { + if v.is_empty() { + return Err(Fail::usage("error: --output= requires a non-empty path")); + } + output = Some(v.to_string()); + } else { + positional.push(a.clone()); + } + i += 1; + } + let description = positional.join(" "); + if description.trim().is_empty() { + return Err(Fail::usage("error: image requires a description")); + } + let agy = Agy::ready()?; + agy.require_supported()?; + let work = TempDir::new("agy-image-") + .map_err(|e| Fail::runtime(format!("error: could not create temp dir: {e}")))?; + let marker = work.path().join("image-path.txt"); + let name_clause = name + .as_deref() + .map(|n| format!(" Save the image with the name \"{n}\".")) + .unwrap_or_default(); + let prompt = format!( + "Use your built-in generate_image tool to create this image: {description}.{name_clause}\n\nAfter the image is saved, use the write_file tool to write ONLY the absolute filesystem path of the saved image (a single line, no quotes, nothing else) to this exact path:\n{}\nDo not print anything to chat. The marker file is your only textual deliverable.", + marker.display() + ); + let timeout = timeout_env("AGY_IMAGE_TIMEOUT", "8m0s"); + let mut cmd = agy.command(); + cmd.args(["--dangerously-skip-permissions", "--sandbox", "--add-dir"]) + .arg(work.path()) + .args(["--print-timeout", &timeout, "--print", &prompt]) + .current_dir(work.path()); + for k in capture::REPO_ENV_HINTS { + cmd.env_remove(k); + } + let deadline = capture::parse_go_duration(&timeout).map(|d| d + Duration::from_secs(120)); + let _ = util::run_captured(&mut cmd, deadline); + let src = std::fs::read_to_string(&marker).ok().and_then(|t| { + t.lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .map(PathBuf::from) + }); + let Some(src) = src.filter(|s| s.is_file()) else { + return Err(Fail::runtime( + "[agy-plugin] error: agy did not produce a locatable image.\n[agy-plugin] generate_image may have failed; check ~/.gemini/antigravity-cli/log/ or run `agy` interactively.", + )); + }; + let home = util::home_dir().unwrap_or_default(); + if !image_source_allowed(&src, &home) { + return Err(Fail::new( + 66, + format!( + "[agy-plugin] error: refusing to use an image path outside agy's artifacts directory.\n[agy-plugin] path: {}\n[agy-plugin] allowed: ~/.gemini/antigravity-cli/{{brain,scratch,cache}}/", + src.display() + ), + )); + } + println!("[agy-plugin] generated: {}", src.display()); + if let Some(out) = output { + std::fs::copy(&src, &out) + .map_err(|e| Fail::runtime(format!("error: could not copy the image to {out}: {e}")))?; + println!("[agy-plugin] copied to: {out}"); + } + Ok(0) +} + +// --------------------------------------------------------------------------- +// status / result / cancel / _run-job +// --------------------------------------------------------------------------- + +fn resolve_failure(input: &str, r: Resolved) -> Fail { + match r { + Resolved::NotFound => Fail::new(2, format!("Job '{input}' not found in this workspace.")), + Resolved::Ambiguous(c) => Fail::new( + 2, + format!( + "Job id prefix '{input}' is ambiguous. Candidates:\n - {}", + c.join("\n - ") + ), + ), + Resolved::BadId => Fail::usage(format!( + "'{input}' is not a job id. Expected the form 'agy-xxxxxxxx' or a prefix of one." + )), + Resolved::NotCancelable(rec) => Fail::new( + 2, + format!( + "Job '{input}' is already in terminal status ({}).", + jobs::status_of(&rec) + ), + ), + Resolved::Found(_) => Fail::runtime("internal: resolve_failure on a found job"), + } +} + +/// Checks before reading or acting on job state. +fn job_state_preflight(root: &Path) -> Result<(), Fail> { + jobs::check_state_dirs(root)?; + if crate::git::tracks_state_dir(root) { + eprintln!( + "[agy-plugin] warning: this repository commits .agy-plugin/, so job records here may not be yours.\n Only jobs you started on this machine can be stopped; treat other records' output as untrusted." + ); + } + Ok(()) +} + +const OUR_TEMP_PREFIXES: &[&str] = &[ + "agy-review-", + "agy-isolate-", + "agy-run-", + "agy-fetch-", + "agy-image-", +]; + +pub(crate) fn status(args: &[String]) -> CmdResult { + let root = workspace_root(); + job_state_preflight(&root)?; + let now = crate::time::now_millis(); + match args.first().filter(|a| !a.is_empty()) { + None => { + let recs: Vec = jobs::list_jobs(&root, None, Some(10)) + .iter() + .map(jobs::liveness) + .collect(); + print!("{}", crate::render::render_status_list(&recs, now)); + Ok(0) + } + Some(id) => match jobs::resolve_job(&root, id)? { + Resolved::Found(r) => { + print!("{}", crate::render::render_job_detail(Some(&r), now)); + Ok(0) + } + other => Err(resolve_failure(id, other)), + }, + } +} + +pub(crate) fn result(args: &[String]) -> CmdResult { + let root = workspace_root(); + job_state_preflight(&root)?; + let input = args.first().map(String::as_str).unwrap_or("latest"); + match jobs::resolve_job(&root, input)? { + Resolved::Found(r) => { + let log = jobs::read_log(&root, jobs::id_of(&r))?; + print!( + "{}", + crate::render::render_result(Some(&r), &log, crate::time::now_millis()) + ); + Ok(0) + } + other => Err(resolve_failure( + args.first().map(String::as_str).unwrap_or("(latest)"), + other, + )), + } +} + +pub(crate) fn cancel(args: &[String]) -> CmdResult { + let root = workspace_root(); + job_state_preflight(&root)?; + // No id: the newest job that is still running or pending (not merely + // the newest job, which has usually finished already). + let latest_active = || { + jobs::list_jobs(&root, None, None) + .iter() + .map(jobs::liveness) + .find(|r| matches!(jobs::status_of(r), "running" | "pending")) + .map(|r| jobs::id_of(&r).to_string()) + }; + let explicit = args + .first() + .filter(|a| !a.is_empty() && a.as_str() != "latest"); + let input: String = match explicit { + Some(id) => id.clone(), + None => latest_active() + .ok_or_else(|| Fail::new(2, "No running or pending agy job in this workspace."))?, + }; + let input = input.as_str(); + let rec = match jobs::resolve_cancelable(&root, input)? { + Resolved::Found(r) => r, + other => return Err(resolve_failure(input, other)), + }; + let id = jobs::id_of(&rec).to_string(); + let outcome = match jobs::cancel_job(&root, &id, Duration::from_secs(5))? { + CancelResult::Canceled(reason) => crate::render::CancelOutcome::Canceled { + reason: reason.to_string(), + }, + CancelResult::NotFound => crate::render::CancelOutcome::NotFound, + CancelResult::NotCancelable(status) => { + crate::render::CancelOutcome::NotCancelable { status } + } + }; + print!("{}", crate::render::render_cancel_report(&id, &outcome)); + Ok( + if matches!(outcome, crate::render::CancelOutcome::Canceled { .. }) { + 0 + } else { + 1 + }, + ) +} + +pub(crate) fn run_job(args: &[String]) -> CmdResult { + let Some(id) = args.first() else { + return Err(Fail::usage("agy-plugin _run-job: missing job id")); + }; + let root = util::env_nonempty("AGY_JOB_WORKSPACE") + .map(PathBuf::from) + .unwrap_or_else(workspace_root); + let st = jobs::run_worker(&root, id, false, &default_runner)?; + Ok(if st == "completed" || st == "canceled" { + 0 + } else { + 1 + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + #[test] + fn take_model_forms() { + assert_eq!( + take_model(&s(&["--model", "pro", "hi"])).unwrap(), + (Some("pro".into()), s(&["hi"])) + ); + assert_eq!( + take_model(&s(&["--model=flash", "hi", "--effort", "high"])).unwrap(), + (Some("flash".into()), s(&["hi", "--effort", "high"])) + ); + assert_eq!( + take_model(&s(&["--", "--model", "x"])).unwrap(), + (None, s(&["--model", "x"])) + ); + assert_eq!(take_model(&s(&["hi"])).unwrap(), (None, s(&["hi"]))); + assert_eq!(take_model(&s(&["--model"])).unwrap_err().code, 64); + assert_eq!(take_model(&s(&["--model="])).unwrap_err().code, 64); + } + + #[cfg(unix)] + #[test] + fn image_allowlist() { + let home = TempDir::new("agy-home-").unwrap(); + let brain = home.path().join(".gemini/antigravity-cli/brain/x"); + std::fs::create_dir_all(&brain).unwrap(); + let ok = brain.join("ok.png"); + std::fs::write(&ok, "png").unwrap(); + assert!(image_source_allowed(&ok, home.path())); + assert!(!image_source_allowed(Path::new("/etc/passwd"), home.path())); + let link = brain.join("evil.png"); + std::os::unix::fs::symlink("/etc/passwd", &link).unwrap(); + assert!( + !image_source_allowed(&link, home.path()), + "symlink out of brain/" + ); + let dotdot = home + .path() + .join(".gemini/antigravity-cli/brain/../../../../../../etc/passwd"); + assert!(!image_source_allowed(&dotdot, home.path())); + assert!(!image_source_allowed(Path::new(""), home.path())); + // A sibling dir whose name merely starts with "brain". + let evil = home.path().join(".gemini/antigravity-cli/brainEVIL"); + std::fs::create_dir_all(&evil).unwrap(); + std::fs::write(evil.join("x.png"), "x").unwrap(); + assert!(!image_source_allowed(&evil.join("x.png"), home.path())); + } +} diff --git a/src/fetch.rs b/src/fetch.rs new file mode 100644 index 0000000..f9920d5 --- /dev/null +++ b/src/fetch.rs @@ -0,0 +1,470 @@ +//! /agy:scrape's page download, done by the plugin rather than by agy. +//! +//! agy 1.5.16 has no tool that reads a URL (only web search), so in 0.8.x the +//! page was fetched by a shell command agy ran — which a read-only run must +//! refuse. Fetching it here is also safer: the SSRF guard checks the URL, +//! then EVERY address its host resolves to, and curl is pinned to the +//! vetted address with `--resolve`, so a DNS answer that changes between the +//! check and the request (rebinding) can't reach an internal service. +//! Redirects are followed by hand and each hop is checked again. +//! +//! HTTPS comes from the system curl (std has no TLS). + +use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; +use std::path::Path; +use std::process::Command; +use std::sync::mpsc; +use std::time::Duration; + +use crate::util; + +pub(crate) const MAX_PAGE_BYTES: u64 = 10 * 1024 * 1024; +const MAX_REDIRECTS: usize = 5; +const DNS_TIMEOUT: Duration = Duration::from_secs(15); + +/// A fetched page saved to disk. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct Page { + pub(crate) final_url: String, + pub(crate) content_type: String, + /// File extension to stage it under (html, txt, xml, json). + pub(crate) ext: &'static str, +} + +/// The checks a fetch applies; production uses the SSRF guard. Tests swap +/// them so a local server can stand in for the internet. +pub(crate) struct Policy<'a> { + pub(crate) validate_url: &'a dyn Fn(&str) -> Result, + pub(crate) ip_blocked: &'a dyn Fn(IpAddr) -> bool, + pub(crate) use_proxy: bool, +} + +pub(crate) fn guard_policy() -> Policy<'static> { + Policy { + validate_url: &crate::guard::validate_scrape_url, + ip_blocked: &|ip| crate::guard::is_blocked_host(&ip.to_string()), + // Off by default: through a proxy, the proxy resolves the name and + // our address check no longer protects anything. + use_proxy: util::env_nonempty("AGY_SCRAPE_USE_PROXY").as_deref() == Some("1"), + } +} + +/// Split a normalized `scheme://host[:port]/rest` URL (the form +/// `guard::validate_scrape_url` returns). +fn split_url(url: &str) -> Result<(String, String, u16), String> { + let (scheme, rest) = url.split_once("://").ok_or("not an absolute URL")?; + let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); + let default_port = if scheme.eq_ignore_ascii_case("https") { + 443 + } else { + 80 + }; + let (host, port) = if let Some(inner) = authority.strip_prefix('[') { + let (h, after) = inner.split_once(']').ok_or("bad IPv6 literal")?; + let port = match after.strip_prefix(':') { + Some(p) => p.parse().map_err(|_| "bad port")?, + None => default_port, + }; + (h.to_string(), port) + } else { + match authority.rsplit_once(':') { + Some((h, p)) => (h.to_string(), p.parse().map_err(|_| "bad port")?), + None => (authority.to_string(), default_port), + } + }; + if host.is_empty() { + return Err("URL has no host".into()); + } + Ok((scheme.to_ascii_lowercase(), host, port)) +} + +/// Resolve with a deadline (std's resolver has none). +fn resolve(host: &str, port: u16) -> Result, String> { + if let Ok(ip) = host.parse::() { + return Ok(vec![SocketAddr::new(ip, port)]); + } + let (tx, rx) = mpsc::channel(); + let h = host.to_string(); + std::thread::spawn(move || { + let _ = tx.send( + (h.as_str(), port) + .to_socket_addrs() + .map(|a| a.collect::>()), + ); + }); + match rx.recv_timeout(DNS_TIMEOUT) { + Ok(Ok(addrs)) if !addrs.is_empty() => Ok(addrs), + Ok(Ok(_)) => Err(format!("host '{host}' has no addresses")), + Ok(Err(e)) => Err(format!("could not resolve '{host}': {e}")), + Err(_) => Err(format!("timed out resolving '{host}'")), + } +} + +fn ext_for(content_type: &str) -> Option<&'static str> { + let ct = content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .to_ascii_lowercase(); + match ct.as_str() { + "text/html" | "application/xhtml+xml" => Some("html"), + "application/xml" | "text/xml" | "application/rss+xml" | "application/atom+xml" => { + Some("xml") + } + "application/json" => Some("json"), + "" => Some("html"), + t if t.starts_with("text/") => Some("txt"), + _ => None, + } +} + +/// Download `url` into `dest` (created, never overwritten). +pub(crate) fn fetch(url: &str, dest: &Path, policy: &Policy) -> Result { + let curl = util::which("curl").ok_or("scrape needs `curl` on PATH to download the page")?; + let mut current = url.to_string(); + for _hop in 0..=MAX_REDIRECTS { + let checked = (policy.validate_url)(¤t)?; + let (_scheme, host, port) = split_url(&checked)?; + let addrs = resolve(&host, port)?; + if let Some(bad) = addrs.iter().find(|a| (policy.ip_blocked)(a.ip())) { + return Err(format!( + "host '{host}' resolves to {}, which is blocked (localhost / private / link-local — SSRF guard)", + bad.ip() + )); + } + let pin = addrs[0]; + let pin_ip = match pin.ip() { + IpAddr::V6(v6) => format!("[{v6}]"), + IpAddr::V4(v4) => v4.to_string(), + }; + let _ = std::fs::remove_file(dest); + let mut cmd = Command::new(&curl); + cmd.args([ + // -q must come first: ignore ~/.curlrc (a `-L` there would break + // the hand-checked redirects; proxy or header settings would + // change what is fetched). + "-q", + "--silent", + "--show-error", + "--proto", + "=http,https", + "--max-redirs", + "0", + "--connect-timeout", + "15", + "--max-time", + "60", + "--max-filesize", + &MAX_PAGE_BYTES.to_string(), + "--compressed", + "-H", + "Accept: text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.1", + "-A", + concat!( + "agy-plugin/", + env!("CARGO_PKG_VERSION"), + " (+https://github.com/limeflash/antigravity-plugin-cc)" + ), + "-w", + "%{http_code}\\n%{redirect_url}\\n%{content_type}\\n", + "-o", + ]) + .arg(dest); + if host.parse::().is_err() { + cmd.args(["--resolve", &format!("{host}:{port}:{pin_ip}")]); + } + if !policy.use_proxy { + cmd.args(["--noproxy", "*"]); + } + cmd.arg("--").arg(&checked); + let out = util::run_captured(&mut cmd, Some(Duration::from_secs(90))) + .map_err(|e| format!("could not run curl: {e}"))?; + if !out.ok() { + let e = out.stderr_str(); + let _ = std::fs::remove_file(dest); + return Err(match out.code { + Some(63) => format!("the page is larger than {MAX_PAGE_BYTES} bytes"), + _ => format!("download failed: {}", e.trim()), + }); + } + let w = out.stdout_str(); + let mut lines = w.lines(); + let code: u16 = lines.next().unwrap_or("0").trim().parse().unwrap_or(0); + let redirect = lines.next().unwrap_or("").trim().to_string(); + let content_type = lines.next().unwrap_or("").trim().to_string(); + if (300..400).contains(&code) && !redirect.is_empty() { + if checked.starts_with("https://") + && !redirect.to_ascii_lowercase().starts_with("https://") + { + let _ = std::fs::remove_file(dest); + return Err(format!( + "refusing a redirect from https to a non-https URL ({redirect})" + )); + } + current = redirect; + continue; + } + if !(200..300).contains(&code) { + let _ = std::fs::remove_file(dest); + return Err(format!("the server answered HTTP {code}")); + } + let size = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0); + if size > MAX_PAGE_BYTES { + let _ = std::fs::remove_file(dest); + return Err(format!("the page is larger than {MAX_PAGE_BYTES} bytes")); + } + let Some(ext) = ext_for(&content_type) else { + let _ = std::fs::remove_file(dest); + return Err(format!( + "unsupported content type '{content_type}' (scrape converts web pages and text)" + )); + }; + return Ok(Page { + final_url: checked, + content_type, + ext, + }); + } + Err(format!("too many redirects (more than {MAX_REDIRECTS})")) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{BufRead, BufReader, Write}; + use std::net::TcpListener; + + /// A tiny HTTP server: path -> (status line, headers, body). + fn serve( + routes: Vec<(&'static str, &'static str, String, String)>, + ) -> (u16, std::thread::JoinHandle<()>) { + let l = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = l.local_addr().unwrap().port(); + let h = std::thread::spawn(move || { + l.set_nonblocking(false).unwrap(); + for stream in l.incoming().take(8) { + let Ok(mut s) = stream else { break }; + let mut r = BufReader::new(s.try_clone().unwrap()); + let mut first = String::new(); + let _ = r.read_line(&mut first); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { + break; + } + } + let path = first.split_whitespace().nth(1).unwrap_or("/").to_string(); + let (status, headers, body) = routes + .iter() + .find(|(p, _, _, _)| *p == path) + .map(|(_, st, h, b)| (st.to_string(), h.clone(), b.clone())) + .unwrap_or(( + "404 Not Found".into(), + "Content-Type: text/plain\r\n".into(), + "nope".into(), + )); + let _ = write!( + s, + "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + (port, h) + } + + fn permissive() -> Policy<'static> { + Policy { + validate_url: &|u| Ok(u.to_string()), + ip_blocked: &|_| false, + use_proxy: false, + } + } + + fn have_curl() -> bool { + util::which("curl").is_some() + } + + #[test] + fn split_url_forms() { + assert_eq!( + split_url("https://example.com/a?b").unwrap(), + ("https".into(), "example.com".into(), 443) + ); + assert_eq!( + split_url("http://example.com:8080").unwrap(), + ("http".into(), "example.com".into(), 8080) + ); + assert_eq!( + split_url("http://[2001:db8::1]:81/x").unwrap(), + ("http".into(), "2001:db8::1".into(), 81) + ); + assert_eq!(split_url("http://[2001:db8::1]/").unwrap().2, 80); + assert!(split_url("example.com").is_err()); + assert!(split_url("http:///x").is_err()); + } + + #[test] + fn content_types() { + assert_eq!(ext_for("text/html; charset=utf-8"), Some("html")); + assert_eq!(ext_for("TEXT/PLAIN"), Some("txt")); + assert_eq!(ext_for("application/json"), Some("json")); + assert_eq!(ext_for("application/rss+xml"), Some("xml")); + assert_eq!(ext_for("image/png"), None); + assert_eq!(ext_for("application/octet-stream"), None); + } + + #[test] + fn fetches_html_and_follows_checked_redirects() { + if !have_curl() { + return; + } + let (port, _h) = serve(vec![ + ( + "/start", + "302 Found", + "Location: /page\r\n".into(), + String::new(), + ), + ( + "/page", + "200 OK", + "Content-Type: text/html; charset=utf-8\r\n".into(), + "

Hi

".into(), + ), + ]); + let d = util::TempDir::new("agy-fetch-test-").unwrap(); + let dest = d.path().join("page"); + let p = fetch( + &format!("http://127.0.0.1:{port}/start"), + &dest, + &permissive(), + ) + .unwrap(); + assert_eq!(p.ext, "html"); + assert!(p.final_url.ends_with("/page")); + assert_eq!(std::fs::read_to_string(&dest).unwrap(), "

Hi

"); + } + + #[test] + fn a_redirect_to_a_refused_url_is_refused() { + if !have_curl() { + return; + } + let (port, _h) = serve(vec![( + "/start", + "301 Moved", + "Location: /evil\r\n".into(), + String::new(), + )]); + let d = util::TempDir::new("agy-fetch-test-").unwrap(); + let validate = |u: &str| { + if u.contains("/evil") { + Err("blocked hop".to_string()) + } else { + Ok(u.to_string()) + } + }; + let policy = Policy { + validate_url: &validate, + ip_blocked: &|_| false, + use_proxy: false, + }; + let err = fetch( + &format!("http://127.0.0.1:{port}/start"), + &d.path().join("p"), + &policy, + ) + .unwrap_err(); + assert_eq!(err, "blocked hop"); + } + + #[test] + fn a_blocked_resolved_address_is_refused_before_any_request() { + let d = util::TempDir::new("agy-fetch-test-").unwrap(); + let policy = Policy { + validate_url: &|u| Ok(u.to_string()), + ip_blocked: &|ip| ip.is_loopback(), + use_proxy: false, + }; + // "localhost" resolves to a loopback address: refused at the DNS step. + let err = fetch("http://localhost:9/", &d.path().join("p"), &policy).unwrap_err(); + assert!(err.contains("resolves to") && err.contains("SSRF"), "{err}"); + assert!(!d.path().join("p").exists()); + } + + #[test] + fn non_text_content_and_http_errors_are_refused() { + if !have_curl() { + return; + } + let (port, _h) = serve(vec![ + ( + "/img", + "200 OK", + "Content-Type: image/png\r\n".into(), + "PNG".into(), + ), + ( + "/gone", + "410 Gone", + "Content-Type: text/html\r\n".into(), + "x".into(), + ), + ]); + let d = util::TempDir::new("agy-fetch-test-").unwrap(); + let e = fetch( + &format!("http://127.0.0.1:{port}/img"), + &d.path().join("a"), + &permissive(), + ) + .unwrap_err(); + assert!(e.contains("unsupported content type"), "{e}"); + assert!(!d.path().join("a").exists()); + let e = fetch( + &format!("http://127.0.0.1:{port}/gone"), + &d.path().join("b"), + &permissive(), + ) + .unwrap_err(); + assert!(e.contains("HTTP 410"), "{e}"); + } + + #[test] + fn redirect_loops_stop() { + if !have_curl() { + return; + } + let (port, _h) = serve(vec![( + "/loop", + "302 Found", + "Location: /loop\r\n".into(), + String::new(), + )]); + let d = util::TempDir::new("agy-fetch-test-").unwrap(); + let e = fetch( + &format!("http://127.0.0.1:{port}/loop"), + &d.path().join("p"), + &permissive(), + ) + .unwrap_err(); + assert!(e.contains("too many redirects"), "{e}"); + } + + #[test] + fn production_policy_blocks_internal_targets() { + let p = guard_policy(); + for u in [ + "http://127.0.0.1/", + "http://169.254.169.254/", + "http://[::1]/", + "file:///etc/passwd", + ] { + assert!((p.validate_url)(u).is_err(), "{u}"); + } + assert!((p.ip_blocked)("10.0.0.1".parse().unwrap())); + assert!((p.ip_blocked)("::ffff:127.0.0.1".parse().unwrap())); + assert!(!(p.ip_blocked)("93.184.215.14".parse().unwrap())); + } +} diff --git a/src/git.rs b/src/git.rs new file mode 100644 index 0000000..6614bb8 --- /dev/null +++ b/src/git.rs @@ -0,0 +1,741 @@ +//! git plumbing: review diffs, staging review materials for agy (Design A+), +//! and the worktree / clean-tree helpers behind /agy:rescue. + +use std::path::{Component, Path, PathBuf}; +use std::process::Command; +use std::time::Duration; + +use crate::prompts::Omitted; +use crate::util::{self, Captured, Fail}; + +const GIT_TIMEOUT: Duration = Duration::from_secs(120); + +/// Largest changed file copied into the review stage dir. Staged files are +/// read by agy from disk (not put in argv), so this is far above the old +/// inline budget; it only stops generated blobs. +pub(crate) const STAGE_FILE_MAX_BYTES: u64 = 2 * 1024 * 1024; + +fn git(dir: &Path, args: &[&str]) -> Result { + let mut cmd = Command::new("git"); + // core.fsmonitor can name a program to run on status/diff; a repo's own + // config (or an extracted archive's .git/config) must not get to run + // code through us. + cmd.arg("-C") + .arg(dir) + .args(["-c", "core.fsmonitor=false"]) + .args(args) + .current_dir(dir); + util::run_captured(&mut cmd, Some(GIT_TIMEOUT)).map_err(|e| { + if e.kind() == std::io::ErrorKind::NotFound { + Fail::runtime("error: git not found on PATH. The review and rescue commands need git.") + } else { + Fail::runtime(format!("error: could not run git: {e}")) + } + }) +} + +/// `git rev-parse --show-toplevel`, or None outside a repo. +pub(crate) fn root(dir: &Path) -> Option { + let out = git(dir, &["rev-parse", "--show-toplevel"]).ok()?; + let s = out.stdout_str(); + let s = s.trim(); + (out.ok() && !s.is_empty()).then(|| PathBuf::from(s)) +} + +fn resolve_ref(dir: &Path, r: &str) -> Option { + // `--end-of-options` stops a ref starting with `-` from being read as an + // option (`--base=--output=/tmp/x`). + let out = git( + dir, + &["rev-parse", "--verify", "--quiet", "--end-of-options", r], + ) + .ok()?; + let s = out.stdout_str().trim().to_string(); + (out.ok() && !s.is_empty()).then_some(s) +} + +fn context_lines() -> u32 { + util::env_nonempty("AGY_REVIEW_CONTEXT") + .and_then(|v| { + let digits: String = v + .trim() + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + digits.parse::().ok() + }) + .unwrap_or(25) + .min(10_000) +} + +/// Paths from a `-z` listing (NUL-separated, never quoted or trimmed, so +/// names with quotes, newlines or edge spaces survive). +fn name_list(out: &Captured) -> Vec { + if !out.ok() { + return Vec::new(); + } + out.stdout_str() + .split('\0') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect() +} + +/// What a review looks at. +pub(crate) struct DiffContext { + pub(crate) scope: crate::prompts::Scope, + pub(crate) diff: String, + pub(crate) files: Vec, + pub(crate) root: PathBuf, +} + +/// Uncommitted changes against HEAD (falls back to the unstaged diff in a +/// repo with no commits yet). Untracked files are not included. +pub(crate) fn working_tree_diff(cwd: &Path) -> Result { + let root = root(cwd) + .ok_or_else(|| Fail::runtime(format!("error: not in a git repo: {}", cwd.display())))?; + let u = format!("-U{}", context_lines()); + // -c core.quotePath=false: report non-ASCII paths verbatim so they can be + // found on disk; --no-ext-diff/--no-color: ignore user diff config. + let base = [ + "-c", + "core.quotePath=false", + "diff", + "--no-ext-diff", + "--no-color", + "--no-textconv", + ]; + let mut args: Vec<&str> = base.to_vec(); + args.extend([u.as_str(), "HEAD"]); + let mut diff = git(&root, &args)?.stdout_str(); + let mut range: Vec<&str> = vec!["HEAD"]; + if diff.trim().is_empty() { + let mut args: Vec<&str> = base.to_vec(); + args.push(u.as_str()); + diff = git(&root, &args)?.stdout_str(); + range.clear(); + } + let mut names: Vec<&str> = vec![ + "-c", + "core.quotePath=false", + "diff", + "--no-ext-diff", + "--name-only", + "-z", + ]; + names.extend(range); + let files = name_list(&git(&root, &names)?); + Ok(DiffContext { + scope: crate::prompts::Scope::WorkingTree, + diff, + files, + root, + }) +} + +/// HEAD compared against the merge-base of HEAD and `base`. +pub(crate) fn branch_diff(cwd: &Path, base: &str) -> Result { + let root = root(cwd) + .ok_or_else(|| Fail::runtime(format!("error: not in a git repo: {}", cwd.display())))?; + let base_sha = resolve_ref(&root, base).ok_or_else(|| { + Fail::runtime(format!( + "error: cannot resolve --base ref '{base}' to a commit" + )) + })?; + let head_sha = resolve_ref(&root, "HEAD") + .ok_or_else(|| Fail::runtime("error: HEAD is missing or detached and unresolvable"))?; + let mb = git(&root, &["merge-base", &base_sha, &head_sha])?; + let compare = if mb.ok() && !mb.stdout_str().trim().is_empty() { + mb.stdout_str().trim().to_string() + } else { + base_sha + }; + let range = format!("{compare}...HEAD"); + let u = format!("-U{}", context_lines()); + let diff = git( + &root, + &[ + "-c", + "core.quotePath=false", + "diff", + "--no-ext-diff", + "--no-color", + "--no-textconv", + &u, + &range, + ], + )? + .stdout_str(); + let files = name_list(&git( + &root, + &[ + "-c", + "core.quotePath=false", + "diff", + "--no-ext-diff", + "--name-only", + "-z", + &range, + ], + )?); + Ok(DiffContext { + scope: crate::prompts::Scope::Branch { + base: base.to_string(), + merge_base: Some(compare), + }, + diff, + files, + root, + }) +} + +/// A repo-relative path from git that stays inside the stage dir: no +/// absolute paths, no `..`, no drive prefixes. +fn safe_relative(rel: &str) -> Option { + let p = Path::new(rel); + if rel.is_empty() || p.is_absolute() || rel.starts_with('/') || rel.starts_with('\\') { + return None; + } + let mut out = PathBuf::new(); + for c in p.components() { + match c { + Component::Normal(s) => out.push(s), + Component::CurDir => {} + _ => return None, + } + } + (!out.as_os_str().is_empty()).then_some(out) +} + +#[derive(Default)] +pub(crate) struct Staged { + pub(crate) staged: Vec, + pub(crate) omitted: Vec, +} + +/// Design A+: write the full diff and the full current content of each +/// changed file under `stage_dir` (diff.patch, files/) so agy reads +/// them from disk — no argv size limit, whole-file context, and the repo +/// itself is never in agy's workspace. Skips anything that could smuggle +/// in a file from outside the repo. +pub(crate) fn stage_review_materials( + stage_dir: &Path, + root: &Path, + files: &[String], + diff: &str, +) -> Result { + let io = + |e: std::io::Error| Fail::runtime(format!("error: could not stage review materials: {e}")); + std::fs::create_dir_all(stage_dir).map_err(io)?; + std::fs::write(stage_dir.join("diff.patch"), diff).map_err(io)?; + let files_root = stage_dir.join("files"); + let real_root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let mut res = Staged::default(); + for rel in files { + let omit = |reason: String| Omitted { + path: rel.clone(), + reason, + }; + let Some(rel_path) = safe_relative(rel) else { + res.omitted.push(omit(if Path::new(rel).is_absolute() { + "absolute path (skipped)".into() + } else { + "path escapes stage dir (skipped)".into() + })); + continue; + }; + let abs = root.join(&rel_path); + let meta = match std::fs::symlink_metadata(&abs) { + Ok(m) => m, + Err(_) => { + res.omitted.push(omit("missing/deleted".into())); + continue; + } + }; + if meta.file_type().is_symlink() { + res.omitted.push(omit("symlink (skipped)".into())); + continue; + } + if !meta.is_file() { + res.omitted.push(omit("not a regular file".into())); + continue; + } + if meta.len() > STAGE_FILE_MAX_BYTES { + res.omitted + .push(omit(format!("too large ({} bytes)", meta.len()))); + continue; + } + // A parent dir can be a symlink pointing outside the repo + // (linked_dir/secret.txt): the real path must stay under the root. + match std::fs::canonicalize(&abs) { + Ok(real) if real.starts_with(&real_root) && real != real_root => {} + Ok(_) => { + res.omitted.push(omit("resolves outside the repo".into())); + continue; + } + Err(_) => { + res.omitted.push(omit("unresolvable path".into())); + continue; + } + } + let bytes = match std::fs::read(&abs) { + Ok(b) => b, + Err(_) => { + res.omitted.push(omit("unreadable".into())); + continue; + } + }; + if bytes.contains(&0) { + res.omitted.push(omit("binary".into())); + continue; + } + let dest = files_root.join(&rel_path); + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent).map_err(io)?; + } + std::fs::write(&dest, String::from_utf8_lossy(&bytes).as_bytes()).map_err(io)?; + res.staged.push(rel.clone()); + } + Ok(res) +} + +/// Does the repository COMMIT `.agy-plugin/`? Then its job records came +/// with the clone and were not created by this user. +pub(crate) fn tracks_state_dir(root: &Path) -> bool { + git(root, &["ls-files", "-z", "--", crate::jobs::STATE_DIR]) + .map(|o| o.ok() && !o.stdout.is_empty()) + .unwrap_or(false) +} + +pub(crate) fn is_repo(dir: &Path) -> bool { + root(dir).is_some() +} + +/// Clean = `git status --porcelain` printed nothing. A git failure counts as +/// dirty (fail closed: rescue refuses). +pub(crate) fn is_clean(dir: &Path) -> bool { + match git(dir, &["status", "--porcelain"]) { + Ok(out) => out.ok() && out.stdout_str().trim().is_empty(), + Err(_) => false, + } +} + +/// `git diff --stat HEAD` plus untracked files, for after a rescue run. +pub(crate) fn change_summary(dir: &Path) -> String { + let stat = git(dir, &["diff", "--no-ext-diff", "--stat", "HEAD"]) + .map(|o| o.stdout_str().trim().to_string()) + .unwrap_or_default(); + let untracked = git( + dir, + &[ + "-c", + "core.quotePath=false", + "ls-files", + "-z", + "--others", + "--exclude-standard", + ], + ) + .map(|o| name_list(&o)) + .unwrap_or_default(); + let mut lines = Vec::new(); + if !stat.is_empty() { + lines.push(stat); + } + if !untracked.is_empty() { + lines.push("new (untracked) files:".to_string()); + lines.extend(untracked.iter().map(|f| format!(" + {f}"))); + } + if lines.is_empty() { + "(no changes detected)".to_string() + } else { + lines.join("\n") + } +} + +/// A separate checkout of HEAD for `rescue --isolate`: `git clone --shared` +/// into `dir`, detached at the same commit. Unlike a linked worktree, the +/// clone has its own `.git` (config, hooks, refs), so edits there can't +/// reach the real repository's metadata. Objects are shared read-only via +/// alternates, so it is fast. +pub(crate) fn isolated_checkout(root: &Path, dir: &Path) -> Result<(), String> { + let head = resolve_ref(root, "HEAD").ok_or("HEAD is missing (no commits yet?)")?; + let d = dir.display().to_string(); + let src = root.display().to_string(); + let first_line = |o: &Captured| { + let e = o.stderr_str(); + if e.trim().is_empty() { + o.stdout_str().trim().to_string() + } else { + e.trim().to_string() + } + }; + let out = git( + root, + &[ + "clone", + "--quiet", + "--shared", + "--no-checkout", + "--", + &src, + &d, + ], + ) + .map_err(|f| f.message)?; + if !out.ok() { + return Err(first_line(&out)); + } + let out = git(dir, &["checkout", "--quiet", "--detach", &head]).map_err(|f| f.message)?; + if !out.ok() { + return Err(first_line(&out)); + } + Ok(()) +} + +pub(crate) fn remove_isolated(dir: &Path) { + let _ = std::fs::remove_dir_all(dir); +} + +/// Stage everything in the isolated checkout and return (`--stat`, patch). +pub(crate) fn isolated_patch(wt: &Path) -> (String, String) { + let _ = git(wt, &["add", "-A"]); + let stat = git(wt, &["diff", "--no-ext-diff", "--cached", "--stat", "HEAD"]) + .map(|o| o.stdout_str().trim().to_string()) + .unwrap_or_default(); + let patch = git( + wt, + &[ + "diff", + "--no-ext-diff", + "--no-color", + "--no-textconv", + "--binary", + "--cached", + "HEAD", + ], + ) + .map(|o| o.stdout_str()) + .unwrap_or_default(); + (stat, patch) +} + +/// Keep `.agy-plugin/` (job state) out of `git status`, so a later rescue +/// doesn't see its own state as a dirty tree. Uses `git rev-parse +/// --git-path` so it also works in linked worktrees, where `.git` is a file +/// (0.8.x silently skipped those). +pub(crate) fn ensure_exclude(root: &Path) { + let Ok(out) = git(root, &["rev-parse", "--git-path", "info/exclude"]) else { + return; + }; + if !out.ok() { + return; + } + let p = PathBuf::from(out.stdout_str().trim()); + let p = if p.is_absolute() { p } else { root.join(p) }; + let current = std::fs::read_to_string(&p).unwrap_or_default(); + if current + .lines() + .any(|l| matches!(l.trim(), ".agy-plugin" | ".agy-plugin/")) + { + return; + } + if let Some(parent) = p.parent() { + let _ = std::fs::create_dir_all(parent); + } + let sep = if !current.is_empty() && !current.ends_with('\n') { + "\n" + } else { + "" + }; + let _ = std::fs::write( + &p, + format!( + "{current}{sep}# Added by the agy plugin — local job-state dir (not committed).\n.agy-plugin/\n" + ), + ); +} + +#[cfg(test)] +pub(crate) mod test_repo { + use std::path::Path; + use std::process::Command; + + pub(crate) fn sh_git(dir: &Path, args: &[&str]) { + let st = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!( + st.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&st.stderr) + ); + } + + /// A repo with one commit containing `a.txt`. + pub(crate) fn init(dir: &Path) { + sh_git(dir, &["init", "-q", "-b", "main"]); + sh_git(dir, &["config", "user.email", "t@t.t"]); + sh_git(dir, &["config", "user.name", "t"]); + sh_git(dir, &["config", "commit.gpgsign", "false"]); + std::fs::write(dir.join("a.txt"), "one\n").unwrap(); + sh_git(dir, &["add", "-A"]); + sh_git(dir, &["commit", "-qm", "init"]); + } +} + +#[cfg(test)] +mod tests { + use super::test_repo::*; + use super::*; + use crate::util::TempDir; + + #[test] + fn root_and_repo_detection() { + let d = TempDir::new("agy-git-test-").unwrap(); + assert!(!is_repo(d.path())); + init(d.path()); + assert!(is_repo(d.path())); + let r = std::fs::canonicalize(root(d.path()).unwrap()).unwrap(); + assert_eq!(r, std::fs::canonicalize(d.path()).unwrap()); + } + + #[test] + fn working_tree_diff_sees_edits_not_untracked() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + let ctx = working_tree_diff(d.path()).unwrap(); + assert!(ctx.diff.trim().is_empty()); + std::fs::write(d.path().join("a.txt"), "two\n").unwrap(); + std::fs::write(d.path().join("new.txt"), "x\n").unwrap(); + let ctx = working_tree_diff(d.path()).unwrap(); + assert!(ctx.diff.contains("-one") && ctx.diff.contains("+two")); + assert_eq!(ctx.files, vec!["a.txt"]); + assert!( + working_tree_diff(&std::env::temp_dir().join("definitely-not-a-repo-xyz")).is_err() + ); + } + + #[test] + fn branch_diff_uses_the_merge_base() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + sh_git(d.path(), &["checkout", "-q", "-b", "feat"]); + std::fs::write(d.path().join("b.txt"), "feature\n").unwrap(); + sh_git(d.path(), &["add", "-A"]); + sh_git(d.path(), &["commit", "-qm", "feat"]); + let ctx = branch_diff(d.path(), "main").unwrap(); + assert!(ctx.diff.contains("+feature")); + assert_eq!(ctx.files, vec!["b.txt"]); + assert!( + branch_diff(d.path(), "no-such-ref") + .err() + .unwrap() + .message + .contains("cannot resolve") + ); + // A ref that looks like an option must not reach git as one. + assert!(branch_diff(d.path(), "--output=/tmp/agy-pwned").is_err()); + assert!(!Path::new("/tmp/agy-pwned").exists()); + } + + #[test] + fn stage_writes_diff_and_full_files() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + std::fs::create_dir(d.path().join("sub")).unwrap(); + std::fs::write(d.path().join("sub/c.rs"), "fn main() {}\n").unwrap(); + let st = TempDir::new("agy-stage-test-").unwrap(); + let r = stage_review_materials( + st.path(), + d.path(), + &["a.txt".into(), "sub/c.rs".into(), "gone.txt".into()], + "DIFF", + ) + .unwrap(); + assert_eq!(r.staged, vec!["a.txt", "sub/c.rs"]); + assert_eq!( + std::fs::read_to_string(st.path().join("diff.patch")).unwrap(), + "DIFF" + ); + assert_eq!( + std::fs::read_to_string(st.path().join("files/sub/c.rs")).unwrap(), + "fn main() {}\n" + ); + assert_eq!(r.omitted[0].reason, "missing/deleted"); + } + + #[cfg(unix)] + #[test] + fn stage_refuses_symlinks_dir_escapes_traversal_and_binaries() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + let outside = TempDir::new("agy-outside-").unwrap(); + std::fs::write(outside.path().join("secret.txt"), "TOP SECRET").unwrap(); + std::os::unix::fs::symlink("/etc/passwd", d.path().join("pwned")).unwrap(); + std::os::unix::fs::symlink(outside.path(), d.path().join("linkdir")).unwrap(); + std::fs::write(d.path().join("bin.dat"), [1u8, 0, 2]).unwrap(); + let st = TempDir::new("agy-stage-test-").unwrap(); + let files: Vec = [ + "pwned", + "linkdir/secret.txt", + "../../etc/passwd", + "/etc/passwd", + "bin.dat", + "a.txt", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + let r = stage_review_materials(st.path(), d.path(), &files, "").unwrap(); + assert_eq!(r.staged, vec!["a.txt"]); + let reasons: Vec<&str> = r.omitted.iter().map(|o| o.reason.as_str()).collect(); + assert_eq!( + reasons, + vec![ + "symlink (skipped)", + "resolves outside the repo", + "path escapes stage dir (skipped)", + "absolute path (skipped)", + "binary" + ] + ); + // Nothing from outside the repo landed anywhere in the stage dir. + let mut stack = vec![st.path().to_path_buf()]; + while let Some(p) = stack.pop() { + for e in std::fs::read_dir(&p).unwrap() { + let e = e.unwrap().path(); + if e.is_dir() { + stack.push(e); + } else { + let c = std::fs::read_to_string(&e).unwrap_or_default(); + assert!( + !c.contains("TOP SECRET") && !c.contains("root:"), + "{}", + e.display() + ); + } + } + } + } + + #[test] + fn clean_tree_summary_and_exclude() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + assert!(is_clean(d.path())); + assert_eq!(change_summary(d.path()), "(no changes detected)"); + std::fs::create_dir(d.path().join(".agy-plugin")).unwrap(); + std::fs::write(d.path().join(".agy-plugin/x.json"), "{}").unwrap(); + assert!(!is_clean(d.path()), "state dir shows until excluded"); + ensure_exclude(d.path()); + ensure_exclude(d.path()); + assert!(is_clean(d.path())); + let ex = std::fs::read_to_string(d.path().join(".git/info/exclude")).unwrap(); + assert_eq!(ex.matches(".agy-plugin/").count(), 1, "idempotent"); + std::fs::write(d.path().join("a.txt"), "changed\n").unwrap(); + std::fs::write(d.path().join("n.txt"), "new\n").unwrap(); + let s = change_summary(d.path()); + assert!(s.contains("a.txt") && s.contains("new (untracked) files:\n + n.txt")); + } + + #[test] + fn exclude_works_in_a_linked_worktree() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + let wt_parent = TempDir::new("agy-wt-").unwrap(); + let wt = wt_parent.path().join("wt"); + sh_git( + d.path(), + &["worktree", "add", "--detach", wt.to_str().unwrap(), "HEAD"], + ); + assert!( + wt.join(".git").is_file(), + ".git is a gitfile in a linked worktree" + ); + std::fs::create_dir(wt.join(".agy-plugin")).unwrap(); + std::fs::write(wt.join(".agy-plugin/x"), "1").unwrap(); + ensure_exclude(&wt); + assert!(is_clean(&wt)); + sh_git( + d.path(), + &["worktree", "remove", "--force", wt.to_str().unwrap()], + ); + } + + #[test] + fn isolated_checkout_round_trip_leaves_real_repo_untouched() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + let parent = TempDir::new("agy-iso-").unwrap(); + let wt = parent.path().join("wt"); + isolated_checkout(d.path(), &wt).unwrap(); + assert!( + wt.join(".git").is_dir(), + "a clone has its own .git, not a gitfile" + ); + std::fs::write(wt.join("a.txt"), "isolated\n").unwrap(); + std::fs::write(wt.join("added.txt"), "x\n").unwrap(); + // Metadata written in the checkout stays there. + sh_git(&wt, &["config", "agy.marker", "1"]); + let (stat, patch) = isolated_patch(&wt); + assert!(stat.contains("a.txt") && stat.contains("added.txt")); + assert!(patch.contains("+isolated")); + remove_isolated(&wt); + assert!(!wt.exists()); + assert_eq!( + std::fs::read_to_string(d.path().join("a.txt")).unwrap(), + "one\n" + ); + assert!(is_clean(d.path())); + let cfg = std::fs::read_to_string(d.path().join(".git/config")).unwrap(); + assert!(!cfg.contains("marker"), "real repo config untouched"); + let wl = std::process::Command::new("git") + .arg("-C") + .arg(d.path()) + .args(["worktree", "list"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&wl.stdout).lines().count(), + 1, + "no linked worktree registered" + ); + } + + #[test] + fn odd_file_names_survive_the_name_list() { + let d = TempDir::new("agy-git-test-").unwrap(); + init(d.path()); + let odd = if cfg!(windows) { + "sp ace.txt" + } else { + " edge\"quote\\.txt" + }; + std::fs::write(d.path().join(odd), "1\n").unwrap(); + sh_git(d.path(), &["add", "-A"]); + sh_git(d.path(), &["commit", "-qm", "odd"]); + std::fs::write(d.path().join(odd), "2\n").unwrap(); + let ctx = working_tree_diff(d.path()).unwrap(); + assert_eq!(ctx.files, vec![odd.to_string()]); + } + + #[test] + fn safe_relative_rejects_escapes() { + assert!(safe_relative("a/b.txt").is_some()); + assert!(safe_relative("./a").is_some()); + for bad in [ + "", + "/etc/passwd", + "../x", + "a/../../x", + "\\\\server\\share", + "a/..", + ] { + assert!(safe_relative(bad).is_none(), "{bad}"); + } + } +} diff --git a/src/guard.rs b/src/guard.rs new file mode 100644 index 0000000..cfa28b8 --- /dev/null +++ b/src/guard.rs @@ -0,0 +1,1678 @@ +//! Input guards for the read-only commands that hand outside input to agy: +//! `/agy:scrape` (a URL agy will fetch) and `/agy:doc-to-md` (a local file +//! agy will read). Whatever passes here ends up at Gemini, so: +//! - scrape: SSRF (file://, localhost, cloud metadata, private ranges, +//! numeric/IPv6 encodings of them, nip.io-style DNS that resolves to them); +//! - doc-to-md: local-file exfiltration (~/.ssh, ~/.aws, /etc, ...). +//! +//! Fail CLOSED: anything not clearly allowed is rejected. Best-effort — an +//! attacker who controls DNS can still rebind a public name to an internal +//! address; this blocks literal targets, encodings and well-known tricks. + +use std::fs::{self, File, Metadata, OpenOptions}; +use std::io::{Read, Write}; +use std::net::Ipv6Addr; +use std::path::{Component, Path, PathBuf, Prefix}; + +// --------------------------------------------------------------------------- +// /agy:scrape — SSRF guard +// --------------------------------------------------------------------------- + +const INVALID_URL: &str = "not a valid absolute URL (include http:// or https://)"; +const BAD_URL_CHARS: &str = "URL contains characters that are not allowed (spaces, backslashes, control or non-ASCII characters)"; + +/// Validate a scrape URL and return the normalized form that must be handed +/// to agy (so what agy fetches is exactly what was checked). +/// +/// Hand-parsed and deliberately narrower than WHATWG: anything a browser-grade +/// parser would "fix up" (backslashes, tabs, IDNs, percent-encoded hosts, +/// userinfo) is refused rather than emulated, so a second parser downstream +/// cannot read a different host out of the same string. +pub(crate) fn validate_scrape_url(raw: &str) -> Result { + let s = raw.trim(); + if s.is_empty() { + return Err("empty URL".into()); + } + if s.bytes() + .any(|b| b <= b' ' || b == 0x7f || b == b'\\' || !b.is_ascii()) + { + return Err(BAD_URL_CHARS.into()); + } + let Some((scheme, rest)) = s.split_once("://") else { + return Err(INVALID_URL.into()); + }; + if !is_scheme(scheme) { + return Err(INVALID_URL.into()); + } + let scheme = scheme.to_ascii_lowercase(); + if scheme != "http" && scheme != "https" { + return Err(format!( + "protocol '{scheme}:' is not allowed (only http/https)" + )); + } + + let auth_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let (authority, tail) = rest.split_at(auth_end); + if authority.is_empty() { + return Err(INVALID_URL.into()); + } + // `http://example.com@127.0.0.1/` fetches 127.0.0.1; parsers also + // disagree about which `@` ends the userinfo. Never allow it. + if authority.contains('@') { + return Err("credentials in URLs are not allowed".into()); + } + + let (host_raw, port_raw) = if authority.starts_with('[') { + let close = authority.find(']').ok_or(INVALID_URL)?; + let after = &authority[close + 1..]; + let port = if after.is_empty() { + None + } else { + Some(after.strip_prefix(':').ok_or(INVALID_URL)?) + }; + (&authority[..=close], port) + } else { + match authority.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (authority, None), + } + }; + + let port = match port_raw { + None => None, + Some(p) => { + if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) { + return Err(INVALID_URL.into()); + } + match p.parse::() { + Ok(n) if n >= 1 => Some(n), + _ => return Err(INVALID_URL.into()), + } + } + }; + + // Percent-encoded hosts are decoded by WHATWG (`%6c%6f...` = localhost); + // refuse instead of decoding. Same for every other non-hostname byte. + let host_ok = if let Some(inner) = host_raw.strip_prefix('[') { + inner.strip_suffix(']').is_some_and(|v6| { + v6.bytes() + .all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.') + }) + } else { + host_raw + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) + }; + if host_raw.contains('%') || !host_ok { + return Err(INVALID_URL.into()); + } + let mut host = host_raw.to_ascii_lowercase(); + host.truncate(host.trim_end_matches('.').len()); + + if is_blocked_host(&host) { + return Err(format!( + "host '{host}' is blocked (localhost / private / link-local \u{2014} SSRF guard)" + )); + } + + let out_host = if let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + let ip: Ipv6Addr = inner.parse().map_err(|_| INVALID_URL.to_string())?; + format!("[{ip}]") + } else if ends_in_number(&host) { + // Alternate IPv4 spellings (2130706433, 0x7f.1, 0177.0.0.1) are + // rewritten dotted-decimal so agy cannot interpret them differently. + let ip = parse_ipv4_whatwg(&host).ok_or(INVALID_URL)?; + std::net::Ipv4Addr::from(ip).to_string() + } else { + host + }; + + let path_query = tail.split('#').next().unwrap_or(""); + let path_query = if path_query.starts_with('/') { + path_query.to_string() + } else { + format!("/{path_query}") + }; + let port = port.map(|p| format!(":{p}")).unwrap_or_default(); + Ok(format!("{scheme}://{out_host}{port}{path_query}")) +} + +fn is_scheme(s: &str) -> bool { + let mut b = s.bytes(); + b.next().is_some_and(|c| c.is_ascii_alphabetic()) + && b.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'+' | b'-' | b'.')) +} + +/// True if a URL host must not be fetched. Accepts a bare host or a +/// bracketed IPv6 literal; lowercases and strips trailing dots itself. +pub(crate) fn is_blocked_host(host: &str) -> bool { + let lower = host.to_ascii_lowercase(); + let h = lower.trim_end_matches('.'); + if h.is_empty() { + return true; + } + + if h.starts_with('[') || h.ends_with(']') || h.contains(':') { + let inner = h + .strip_prefix('[') + .and_then(|x| x.strip_suffix(']')) + .unwrap_or(h); + // Zone ids (`fe80::1%eth0`) and anything std cannot parse: blocked. + return match inner.parse::() { + Ok(ip) => ipv6_blocked(ip), + Err(_) => true, + }; + } + + // Not a resolvable DNS name: fail closed rather than guess what a + // resolver does with it (also bounds the embedded-address scans below). + if h.len() > 253 || h.split('.').any(|l| l.len() > 63) { + return true; + } + + if h == "localhost" { + return true; + } + const SUFFIXES: [&str; 8] = [ + ".localhost", + ".local", + ".internal", + ".lan", + ".home", + ".corp", + ".home.arpa", + // `localhost.localdomain` is in many Linux /etc/hosts files. + ".localdomain", + ]; + if SUFFIXES.iter().any(|s| h.ends_with(s)) { + return true; + } + // Public wildcard domains whose every name resolves to 127.0.0.1. + // Not in the spec list; cheap to refuse outright. + const LOOPBACK_DOMAINS: [&str; 4] = ["localtest.me", "lvh.me", "vcap.me", "localhost.direct"]; + if LOOPBACK_DOMAINS + .iter() + .any(|d| h == *d || h.strip_suffix(d).is_some_and(|p| p.ends_with('.'))) + { + return true; + } + + // WHATWG: a host whose last label is numeric IS an IPv4 address + // (2130706433, 0x7f.1, 0177.0.0.1, 127.1). If it does not parse, a + // browser would reject the URL; we block it. + if ends_in_number(h) { + return parse_ipv4_whatwg(h).is_none_or(ipv4_blocked); + } + + // A single-label name (`metadata`, `intranet`, `router`) is completed + // by the resolver's search domains to an internal host (on GCE, + // `metadata` is the metadata server). Public sites never use one. + if !h.contains('.') { + return true; + } + + embeds_blocked_address(h) +} + +/// nip.io / sslip.io style names resolve to an address spelled inside them. +/// Every encoding and every position is checked, not just the first match. +fn embeds_blocked_address(h: &str) -> bool { + let labels: Vec<&str> = h.split('.').collect(); + // Dotted: any 4 consecutive decimal-octet labels (`1.2.3.4.127.0.0.1.nip.io`). + if labels.windows(4).any(octets_blocked) { + return true; + } + labels.iter().any(|label| { + let parts: Vec<&str> = label.split('-').collect(); + // Dashed quad, anywhere in the label (`127-0-0-1`, `app-127-0-0-1`). + if parts.windows(4).any(octets_blocked) { + return true; + } + // 8-hex-digit form (`7f000001`, `app-7f000001`). + if parts.iter().any(|p| { + p.len() == 8 + && p.bytes().all(|b| b.is_ascii_hexdigit()) + && u32::from_str_radix(p, 16).is_ok_and(ipv4_blocked) + }) { + return true; + } + dashed_ipv6_blocked(label) + }) +} + +fn octets_blocked(w: &[&str]) -> bool { + let mut ip: u32 = 0; + for part in w { + if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) { + return false; + } + match part.parse::() { + Ok(o) => ip = (ip << 8) | u32::from(o), + Err(_) => return false, + } + } + ipv4_blocked(ip) +} + +/// sslip.io resolves IPv6 written with dashes (`--1.sslip.io` is ::1, +/// `fe80--1` is fe80::1), also after a `prefix-`. Like sslip.io, a candidate +/// must start at the label start or right after a `-` and end at the label +/// end or right before a `-`; that keeps punycode (`xn--bcher-kva`) from +/// being read as `::bc`. Labels are at most 63 bytes, so this stays small. +fn dashed_ipv6_blocked(label: &str) -> bool { + let b = label.as_bytes(); + if b.iter().filter(|&&c| c == b'-').count() < 2 { + return false; + } + let starts: Vec = (0..b.len()) + .filter(|&i| i == 0 || b[i - 1] == b'-') + .collect(); + let ends: Vec = (1..=b.len()) + .filter(|&j| j == b.len() || b[j] == b'-') + .collect(); + for &i in &starts { + for &j in ends.iter().filter(|&&j| j > i) { + let sub = &label[i..j]; + if sub.bytes().filter(|&c| c == b'-').count() < 2 + || !sub.bytes().all(|c| c.is_ascii_hexdigit() || c == b'-') + { + continue; + } + if sub + .replace('-', ":") + .parse::() + .is_ok_and(ipv6_blocked) + { + return true; + } + } + } + false +} + +/// WHATWG "ends in a number": last label all decimal digits, or `0x` + hex +/// (an empty `0x` counts — it is the number 0). +fn ends_in_number(h: &str) -> bool { + let last = h.rsplit('.').next().unwrap_or(""); + if !last.is_empty() && last.bytes().all(|b| b.is_ascii_digit()) { + return true; + } + last.strip_prefix("0x") + .or_else(|| last.strip_prefix("0X")) + .is_some_and(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())) +} + +/// WHATWG IPv4 parser: 1–4 parts, each decimal, `0x` hex or leading-`0` +/// octal; the last part fills the remaining bytes. None = not a valid IPv4 +/// (callers treat that as blocked). +fn parse_ipv4_whatwg(h: &str) -> Option { + let parts: Vec<&str> = h.split('.').collect(); + if parts.is_empty() || parts.len() > 4 { + return None; + } + let mut nums = Vec::with_capacity(parts.len()); + for p in &parts { + nums.push(parse_ipv4_number(p)?); + } + let (last, init) = nums.split_last()?; + let mut ip: u64 = 0; + for (i, &n) in init.iter().enumerate() { + if n > 255 { + return None; + } + ip |= n << (8 * (3 - i)); + } + let limit = 1u64 << (8 * (5 - parts.len())); + if *last >= limit { + return None; + } + u32::try_from(ip | last).ok() +} + +fn parse_ipv4_number(s: &str) -> Option { + if s.is_empty() { + return None; + } + let (digits, radix) = if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) { + (hex, 16) + } else if s.len() >= 2 && s.starts_with('0') { + (&s[1..], 8) + } else { + (s, 10) + }; + let mut v: u64 = 0; + for c in digits.chars() { + let d = c.to_digit(radix)?; + // Overflow means "out of range" -> None -> blocked. + v = v.checked_mul(u64::from(radix))?.checked_add(u64::from(d))?; + } + Some(v) +} + +/// Non-public IPv4. Wider than the old guard: also multicast (224/4), +/// reserved (240/4, incl. broadcast), benchmarking (198.18/15) and the +/// IETF protocol block (192.0.0/24). +fn ipv4_blocked(ip: u32) -> bool { + let in_net = |net: u32, bits: u32| (ip ^ net) >> (32 - bits) == 0; + in_net(0x0000_0000, 8) // 0/8 "this network" + || in_net(0x0a00_0000, 8) // 10/8 + || in_net(0x6440_0000, 10) // 100.64/10 CGNAT + || in_net(0x7f00_0000, 8) // 127/8 loopback + || in_net(0xa9fe_0000, 16) // 169.254/16 link-local + cloud metadata + || in_net(0xac10_0000, 12) // 172.16/12 + || in_net(0xc000_0000, 24) // 192.0.0/24 + || in_net(0xc0a8_0000, 16) // 192.168/16 + || in_net(0xc612_0000, 15) // 198.18/15 + || in_net(0xe000_0000, 4) // 224/4 multicast + || in_net(0xf000_0000, 4) // 240/4 reserved + broadcast +} + +fn ipv6_blocked(ip: Ipv6Addr) -> bool { + let s = ip.segments(); + let v = u128::from(ip); + let low32 = (v & 0xffff_ffff) as u32; + if v <= 1 { + return true; // :: and ::1 + } + if s[0] & 0xffc0 == 0xfe80 // fe80::/10 link-local + || s[0] & 0xffc0 == 0xfec0 // fec0::/10 site-local + || s[0] & 0xfe00 == 0xfc00 // fc00::/7 ULA + || s[0] & 0xff00 == 0xff00 + // ff00::/8 multicast + { + return true; + } + // ::ffff:a.b.c.d (mapped) and ::a.b.c.d (deprecated compat). + if s[..5] == [0; 5] && (s[5] == 0xffff || s[5] == 0) { + return ipv4_blocked(low32); + } + // ::ffff:0:a.b.c.d (SIIT "IPv4-translated"); not in the spec list. + if s[..4] == [0; 4] && s[4] == 0xffff && s[5] == 0 { + return ipv4_blocked(low32); + } + // 64:ff9b::/96 NAT64 well-known prefix. + if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0; 4] { + return ipv4_blocked(low32); + } + // 64:ff9b:1::/48 local-use NAT64 (RFC 8215): never public; not in the spec list. + if s[0] == 0x64 && s[1] == 0xff9b && s[2] == 1 { + return true; + } + // 2002::/16 6to4: the v4 sits in bits 16..48. + if s[0] == 0x2002 { + return ipv4_blocked((u32::from(s[1]) << 16) | u32::from(s[2])); + } + false +} + +// --------------------------------------------------------------------------- +// /agy:doc-to-md — local document guard +// --------------------------------------------------------------------------- + +/// Document extensions we convert (lowercase, no dot). Everything else +/// (.pem, .key, .env, id_rsa, ...) is rejected — fail closed. +pub(crate) const ALLOWED_DOC_EXT: &[&str] = &[ + "pdf", "docx", "doc", "odt", "rtf", "html", "htm", "xhtml", "xml", "md", "markdown", "txt", + "text", "rst", "org", "adoc", "csv", "tsv", "pptx", "ppt", "epub", +]; + +pub(crate) const MAX_DOC_BYTES: u64 = 10 * 1024 * 1024; + +/// UNC (`\\server\share`) or device (`\\?\`, `\\.\`, `//server`) path. +pub(crate) fn is_unc_path(p: &str) -> bool { + let b = p.as_bytes(); + b.len() >= 2 && matches!(b[0], b'/' | b'\\') && matches!(b[1], b'/' | b'\\') +} + +/// String check plus, on Windows, any path prefix other than a plain drive +/// (`UNC`, `\\?\UNC`, `\\.\pipe`, `\\?\Volume{..}` ...). +fn path_is_unc(p: &Path) -> bool { + if is_unc_path(&p.to_string_lossy()) { + return true; + } + match p.components().next() { + Some(Component::Prefix(pre)) => !matches!(pre.kind(), Prefix::Disk(_)), + _ => false, + } +} + +/// Windows `canonicalize` returns verbatim `\\?\C:\...`; turn a verbatim +/// DRIVE path back into `C:\...` so the UNC check and the sensitive-dir +/// prefixes work. `\\?\UNC\server\share` (and non-UTF-8) is left alone and is +/// then rejected as UNC. +fn strip_verbatim(p: PathBuf) -> PathBuf { + if let Some(rest) = p.to_str().and_then(|s| s.strip_prefix(r"\\?\")) { + let b = rest.as_bytes(); + if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\' { + return PathBuf::from(rest); + } + } + p +} + +// Default APFS and NTFS are case-insensitive: `~/.SSH/x` IS `~/.ssh/x`. +const CASE_INSENSITIVE_FS: bool = cfg!(any(windows, target_os = "macos", target_os = "ios")); + +fn path_under(p: &Path, base: &Path) -> bool { + if CASE_INSENSITIVE_FS { + let lower = |x: &Path| PathBuf::from(x.to_string_lossy().to_lowercase()); + lower(p).starts_with(lower(base)) + } else { + p.starts_with(base) + } +} + +/// True if `real` (an already symlink-resolved path) is a credentials or +/// system location. Component-wise: `/etcetera` is not under `/etc`. +pub(crate) fn is_sensitive_path(real: &Path, home: &Path) -> bool { + let mut bases: Vec = vec![ + home.join(".ssh"), + home.join(".gnupg"), + home.join(".aws"), + home.join(".config").join("gcloud"), + home.join(".gemini"), // agy's own credentials / conversation store + home.join(".kube"), + home.join(".docker"), + home.join(".m2"), // Maven settings.xml (repo passwords) + home.join(".purple"), // Pidgin accounts.xml + home.join(".config").join("filezilla"), + home.join(".filezilla"), + home.join(".password-store"), + home.join(".local").join("share").join("keyrings"), + home.join(".mozilla"), + home.join(".thunderbird"), + home.join(".netrc"), + home.join("Library").join("Keychains"), + home.join("Library").join("Cookies"), + ]; + // Windows keeps the same kind of files under %APPDATA% (Roaming). + if let Some(appdata) = std::env::var_os("APPDATA").filter(|v| !v.is_empty()) { + let a = PathBuf::from(appdata); + for d in ["gcloud", "FileZilla", "Mozilla", "Thunderbird"] { + bases.push(a.join(d)); + } + bases.push(a.join("Microsoft").join("Credentials")); + bases.push(a.join("Microsoft").join("Protect")); + } + if !cfg!(windows) { + for b in ["/etc", "/root", "/proc", "/sys", "/dev", "/var/run"] { + bases.push(PathBuf::from(b)); + } + } + bases.iter().any(|base| { + // `real` is canonical, so the base must be compared canonical too + // (macOS: /etc -> /private/etc, /var -> /private/var; a symlinked + // home). Compare both spellings; a missing base stays raw. + path_under(real, base) + || fs::canonicalize(base).is_ok_and(|c| path_under(real, &strip_verbatim(c))) + }) +} + +/// Validate a doc-to-md path; Ok(real path) to hand to `stage_file`. +pub(crate) fn validate_doc_path(raw: &str, cwd: &Path, home: &Path) -> Result { + let t = raw.trim(); + if t.is_empty() { + return Err("empty path".into()); + } + // A cwd that came from canonicalize() on Windows is `\\?\C:\...`; that is + // a plain drive path, not a device path, so normalise it before the check. + let abs = strip_verbatim(cwd.join(t)); + // A UNC path bypasses the drive-letter sensitive-dir prefixes + // (\\localhost\c$\Users\\.ssh\notes.txt reads ~/.ssh). + if path_is_unc(&abs) { + return Err("UNC / device paths are not allowed".into()); + } + let real = fs::canonicalize(&abs).map_err(|_| "file does not exist".to_string())?; + let real = strip_verbatim(real); + if path_is_unc(&real) { + return Err("path resolves to a UNC / device path".into()); + } + let md = fs::metadata(&real).map_err(|_| "cannot stat file".to_string())?; + if !md.is_file() { + return Err("not a regular file".into()); + } + if md.len() > MAX_DOC_BYTES { + return Err(format!( + "file too large ({} bytes > {MAX_DOC_BYTES} limit)", + md.len() + )); + } + // Extension of the REAL path: a `notes.pdf` symlink to `id_rsa` has none. + // ASCII lowercase only, so no Unicode case mapping can produce an + // allowed extension from a non-ASCII one. + let ext = real + .extension() + .map(|e| e.to_string_lossy().to_ascii_lowercase()); + match ext { + Some(e) if ALLOWED_DOC_EXT.contains(&e.as_str()) => {} + Some(e) => return Err(format!("extension '.{e}' is not an allowed document type")), + None => return Err("extension '(none)' is not an allowed document type".into()), + } + if is_sensitive_path(&real, home) { + return Err("path resolves under a sensitive directory".into()); + } + Ok(real) +} + +// Open flags std does not name. Values are per-OS ABI constants; where we +// are not certain of them we pass 0 and rely on the (dev, ino) check alone. +#[cfg(target_os = "macos")] +const OPEN_FLAGS: i32 = 0x0004 /* O_NONBLOCK */ | 0x0100 /* O_NOFOLLOW */; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +const OPEN_FLAGS: i32 = 0o4000 /* O_NONBLOCK */ | 0o400000 /* O_NOFOLLOW */; +#[cfg(all(target_os = "linux", target_arch = "aarch64"))] +const OPEN_FLAGS: i32 = 0o4000 /* O_NONBLOCK */ | 0o100000 /* O_NOFOLLOW */; +#[cfg(all( + unix, + not(target_os = "macos"), + not(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + )) +))] +const OPEN_FLAGS: i32 = 0; + +/// Open the source without following a final symlink and without blocking +/// on a FIFO swapped in after the lstat. +fn open_source(src: &Path) -> std::io::Result { + let mut opts = OpenOptions::new(); + opts.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(OPEN_FLAGS); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + // FILE_FLAG_OPEN_REPARSE_POINT: open a symlink/junction itself + // instead of its target; we then see the reparse attribute and refuse. + opts.custom_flags(0x0020_0000); + } + opts.open(src) +} + +/// Is the opened handle the very file we lstat'ed? +#[cfg(unix)] +fn same_file(path_meta: &Metadata, handle_meta: &Metadata) -> Result<(), String> { + use std::os::unix::fs::MetadataExt; + if path_meta.dev() == handle_meta.dev() && path_meta.ino() == handle_meta.ino() { + Ok(()) + } else { + Err("source was swapped (TOCTOU)".into()) + } +} + +/// Windows std has no stable file-id accessor; the reparse-point open above +/// stops symlink swaps, and identical creation/write times and size make a +/// swap for a different regular file unlikely to go unnoticed. +#[cfg(windows)] +fn same_file(path_meta: &Metadata, handle_meta: &Metadata) -> Result<(), String> { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + if handle_meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err("source became a symlink (TOCTOU)".into()); + } + if path_meta.creation_time() == handle_meta.creation_time() + && path_meta.last_write_time() == handle_meta.last_write_time() + && path_meta.file_size() == handle_meta.file_size() + { + Ok(()) + } else { + Err("source was swapped (TOCTOU)".into()) + } +} + +/// TOCTOU-resistant copy of a validated document into agy's workspace. +/// +/// The path was validated earlier; between then and now it may have been +/// replaced by a symlink to a secret. lstat refuses a symlink, the opened +/// handle must be that same inode, and all bytes come from the handle — the +/// path is never re-resolved. The destination is created fresh, never +/// followed or overwritten. +pub(crate) fn stage_file(src: &Path, dest: &Path) -> Result<(), String> { + if src.as_os_str().is_empty() || dest.as_os_str().is_empty() { + return Err("stage requires ".into()); + } + let lmeta = fs::symlink_metadata(src).map_err(|_| "source file is gone".to_string())?; + if lmeta.file_type().is_symlink() { + return Err("source became a symlink (TOCTOU)".into()); + } + if !lmeta.is_file() { + return Err("source is not a regular file".into()); + } + if lmeta.len() > MAX_DOC_BYTES { + return Err("source too large".into()); + } + let file = open_source(src).map_err(|e| format!("cannot open source: {e}"))?; + let fmeta = file + .metadata() + .map_err(|e| format!("cannot stat source: {e}"))?; + same_file(&lmeta, &fmeta)?; + if !fmeta.is_file() { + return Err("source was swapped (TOCTOU)".into()); + } + + // The file may grow after the stat: cap the read itself. + let mut buf = Vec::new(); + file.take(MAX_DOC_BYTES + 1) + .read_to_end(&mut buf) + .map_err(|e| format!("cannot read source: {e}"))?; + if buf.len() as u64 > MAX_DOC_BYTES { + return Err("source too large".into()); + } + + let mut opts = OpenOptions::new(); + // create_new = O_CREAT|O_EXCL: fails on any existing entry, including a + // (dangling) symlink planted at dest, instead of writing through it. + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut out = opts.open(dest).map_err(|e| format!("copy failed: {e}"))?; + if let Err(e) = out.write_all(&buf) { + drop(out); + // We created it a moment ago; don't leave a truncated document. + let _ = fs::remove_file(dest); + return Err(format!("copy failed: {e}")); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn more_credential_stores_are_sensitive() { + let home = Path::new("/home/u"); + for rel in [ + ".m2/settings.xml", + ".purple/accounts.xml", + ".config/filezilla/sitemanager.xml", + ".password-store/x.txt", + ".mozilla/firefox/p/logins.json", + ] { + assert!(is_sensitive_path(&home.join(rel), home), "{rel}"); + } + assert!(!is_sensitive_path(&home.join("projects/spec.md"), home)); + } + + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + // ---- SSRF ----------------------------------------------------------- + + fn ok(url: &str) -> String { + match validate_scrape_url(url) { + Ok(u) => u, + Err(e) => panic!("expected {url:?} to pass, got {e}"), + } + } + + fn err(url: &str) -> String { + match validate_scrape_url(url) { + Ok(u) => panic!("expected {url:?} to be rejected, got {u}"), + Err(e) => e, + } + } + + fn blocked(url: &str) { + let e = err(url); + assert!(e.contains("SSRF guard"), "{url:?}: {e}"); + } + + #[test] + fn public_urls_pass_normalized() { + assert_eq!( + ok("https://example.com/page?q=1"), + "https://example.com/page?q=1" + ); + assert_eq!(ok("http://example.com"), "http://example.com/"); + assert_eq!(ok(" https://example.com "), "https://example.com/"); + assert_eq!(ok("HTTP://EXAMPLE.COM/Path"), "http://example.com/Path"); + assert_eq!(ok("HtTpS://Example.Com."), "https://example.com/"); + assert_eq!( + ok("http://example.com..:8080/x#frag"), + "http://example.com:8080/x" + ); + assert_eq!(ok("http://example.com?q"), "http://example.com/?q"); + assert_eq!(ok("http://example.com#x"), "http://example.com/"); + assert_eq!(ok("http://example.com:0080/"), "http://example.com:80/"); + assert_eq!( + ok("https://example.com:65535"), + "https://example.com:65535/" + ); + assert_eq!( + ok("http://example.com/@127.0.0.1"), + "http://example.com/@127.0.0.1" + ); + assert_eq!( + ok("http://example.com:80#@127.0.0.1"), + "http://example.com:80/" + ); + assert_eq!( + ok("http://example.com/a?u=http://127.0.0.1/"), + "http://example.com/a?u=http://127.0.0.1/" + ); + for h in [ + "sub.example.co.uk", + "github.com", + "01.example.com", + "1.example.com", + "123.456.example.com", + "a-b-c.example.com", + "xn--nxasmq6b.com", + "xn--bcher-kva.example", + "xn--fa-hia.de", + "a--1.example.com", + "notlvh.me", + "my_host.example.com", + "8.8.8.8.nip.io", + "foo.8.8.8.8.nip.io", + "8-8-8-8.nip.io", + "08080808.nip.io", + "deadbeef.example.com", + "2606-4700--1111.sslip.io", + "1.2.3.example.com", + "300.0.0.1.example.com", + ] { + assert_eq!(ok(&format!("https://{h}/")), format!("https://{h}/")); + } + } + + #[test] + fn public_ip_literals_pass_and_are_canonical() { + assert_eq!(ok("http://8.8.8.8/"), "http://8.8.8.8/"); + assert_eq!(ok("http://134744072/"), "http://8.8.8.8/"); + assert_eq!(ok("http://0x08080808/"), "http://8.8.8.8/"); + assert_eq!(ok("http://8.8.2056/"), "http://8.8.8.8/"); + assert_eq!(ok("http://010.010.010.010/"), "http://8.8.8.8/"); + assert_eq!( + ok("http://[2001:4860:4860::8888]/"), + "http://[2001:4860:4860::8888]/" + ); + assert_eq!( + ok("http://[2001:4860:4860:0:0:0:0:8888]:443/x"), + "http://[2001:4860:4860::8888]:443/x" + ); + assert_eq!(ok("http://[::FFFF:8.8.8.8]/"), "http://[::ffff:8.8.8.8]/"); + ok("http://[64:ff9b::808:808]/"); + ok("http://[2002:808:808::1]/"); + ok("http://[2606:4700::1111]/"); + ok("http://1.1.1.1/"); + for h in [ + "172.15.0.1", + "172.32.0.1", + "192.169.0.1", + "11.0.0.1", + "8.8.4.4", + "100.128.0.1", + "198.20.0.1", + "223.255.255.255", + ] { + assert!(!is_blocked_host(h), "{h}"); + } + } + + #[test] + fn numeric_ipv4_encodings_blocked() { + for u in [ + "http://127.0.0.1/", + "http://2130706433/", + "http://0x7f.1/", + "http://0X7F.1/", + "http://0177.0.0.1/", + "http://127.1/", + "http://127.0.1/", + "http://0x7f000001/", + "http://017700000001/", + "http://0x7f.0x0.0x0.0x1/", + "http://127.000.000.001/", + "http://127.0.0.1./", + "http://127.0.0.1../", + "http://0/", + "http://0.0.0.0/", + "http://0x/", + "http://10.1/", + "http://192.168.1/", + "http://169.254.169.254/latest/meta-data/", + "https://0xa9fea9fe/", + "http://2852039166/", + "http://100.64.0.1/", + "http://198.18.0.1/", + "http://224.0.0.1/", + "http://255.255.255.255/", + "http://4294967295/", + "http://4294967296/", + "http://99999999999999999999999999/", + "http://08.1.1.1/", + "http://1.2.3.4.5/", + "http://1..1/", + "http://256.1.1.1/", + "http://1.1.1.256.0/", + "http://example.0x/", + "http://example.123/", + "http://192.0.0.8/", + "http://172.16.0.1:443/", + ] { + blocked(u); + } + for h in [ + "127.0.0.1", + "127.1.2.3", + "0.0.0.0", + "10.0.0.5", + "192.168.1.10", + "172.16.0.1", + "172.31.255.255", + "169.254.169.254", + "100.64.0.1", + ] { + assert!(is_blocked_host(h), "{h}"); + } + assert_eq!( + err("http://2130706433/"), + "host '2130706433' is blocked (localhost / private / link-local \u{2014} SSRF guard)" + ); + } + + #[test] + fn ipv6_forms_blocked() { + for u in [ + "http://[::1]/", + "http://[::1]:9000/", + "http://[::]/", + "http://[0:0:0:0:0:0:0:1]/", + "http://[::ffff:127.0.0.1]/", + "http://[::ffff:7f00:1]/", + "http://[::FFFF:7F00:1]/", + "http://[::127.0.0.1]/", + "http://[::7f00:1]/", + "http://[::ffff:a9fe:a9fe]/", + "http://[::ffff:10.0.0.1]/", + "http://[::ffff:0:7f00:1]/", + "http://[64:ff9b::7f00:1]/", + "http://[64:ff9b::127.0.0.1]/", + "http://[64:ff9b::a9fe:a9fe]/", + "http://[64:ff9b:1::808:808]/", + "http://[2002:7f00:1::]/", + "http://[2002:a9fe:a9fe::1]/", + "http://[fe80::1]/", + "http://[febf::1]/", + "http://[fec0::1]/", + "http://[fc00::1]/", + "http://[fd12:3456::1]/", + "http://[ff02::1]/", + ] { + blocked(u); + } + for h in [ + "::1", + "[::1]", + "fe80::1", + "fc00::1", + "fd12:3456::1", + "::ffff:127.0.0.1", + "::ffff:7f00:1", + "::7f00:1", + "::127.0.0.1", + "::ffff:0a00:1", + "::ffff:192.168.1.1", + "fe80::1%eth0", + "[::1", + "::1]", + ":::1", + "[]", + ] { + assert!(is_blocked_host(h), "{h}"); + } + assert!(!is_blocked_host("::ffff:8.8.8.8")); + assert!(!is_blocked_host("[2001:4860:4860::8888]")); + } + + #[test] + fn malformed_ipv6_rejected() { + for u in [ + "http://[fe80::1%25eth0]/", + "http://[fe80::1%eth0]/", + "http://[::1/", + "http://[::1]x/", + "http://[::1]:/", + "http://[example.com]/", + "http://[::ffff:0127.0.0.1]/", + "http://[1:2:3:4:5:6:7:8:9]/", + ] { + assert!(validate_scrape_url(u).is_err(), "{u}"); + } + assert_eq!(err("http://[fe80::1%25eth0]/"), INVALID_URL); + } + + #[test] + fn userinfo_rejected() { + for u in [ + "http://example.com@127.0.0.1/", + "http://user:pass@example.com/", + "http://@example.com/", + "http://127.0.0.1:80@example.com/", + "http://a@b@example.com/", + ] { + assert_eq!(err(u), "credentials in URLs are not allowed", "{u}"); + } + blocked("http://127.0.0.1#@example.com"); + blocked("http://127.0.0.1?@example.com"); + } + + #[test] + fn bad_characters_rejected() { + for u in [ + "http://example.com\\@127.0.0.1/", + "http:\\\\127.0.0.1\\", + "http://127.0.0.1\\.example.com/", + "http://exa mple.com/", + "http://127.0.0.1\t/", + "http://exam\nple.com/", + "http://exam\rple.com/", + "http://example.com/\u{0}", + "http://example.com/\u{7f}", + "http://\u{ff4c}\u{ff4f}\u{ff43}\u{ff41}\u{ff4c}\u{ff48}\u{ff4f}\u{ff53}\u{ff54}/", + "http://ex\u{e4}mple.com/", + "http://127\u{3002}0\u{3002}0\u{3002}1/", + "not a url", + ] { + assert_eq!(err(u), BAD_URL_CHARS, "{u:?}"); + } + } + + #[test] + fn schemes_and_structure() { + assert_eq!(err(""), "empty URL"); + assert_eq!(err(" "), "empty URL"); + assert_eq!( + err("file:///etc/passwd"), + "protocol 'file:' is not allowed (only http/https)" + ); + assert_eq!( + err("gopher://example.com"), + "protocol 'gopher:' is not allowed (only http/https)" + ); + assert_eq!( + err("FTP://example.com/x"), + "protocol 'ftp:' is not allowed (only http/https)" + ); + err("httpx://example.com/"); + err("ws://example.com/"); + for u in [ + "data:text/html,

x

", + "javascript:alert(1)", + "example.com", + "//example.com/", + "127.0.0.1", + "://example.com", + "1http://example.com", + "http:/example.com", + "http:///example.com", + "http://", + "http://?x", + "http://#x", + "http://example.com:/", + "http://example.com:0/", + "http://example.com:65536/", + "http://example.com:99999999999999999999/", + "http://example.com:80a/", + "http://example.com:-1/", + "http://example.com:+80/", + "http://example.com:80:80/", + "http://%6c%6f%63%61%6c%68%6f%73%74/", + "http://127.0.0.%31/", + "http://exa 253); + assert!(is_blocked_host(&long_host)); + } + + #[test] + fn embedded_address_names_blocked() { + for h in [ + "127.0.0.1.nip.io", + "10.0.0.1.sslip.io", + "foo.127.0.0.1.nip.io", + "a.b.10.0.0.1.sslip.io", + "x.169.254.169.254.nip.io", + "1.2.3.4.127.0.0.1.nip.io", + "8.8.8.8.192.168.0.1.nip.io", + "127.000.000.001.nip.io", + "127.0.0.1.example.com", + "127-0-0-1.nip.io", + "app-127-0-0-1.sslip.io", + "127-0-0-1-app.sslip.io", + "a-8-8-8-8-10-0-0-1.sslip.io", + "x.app-169-254-169-254.nip.io", + "7f000001.nip.io", + "7F000001.NIP.IO", + "app-7f000001.nip.io", + "0a000001.nip.io", + "a9fea9fe.sslip.io", + "--1.sslip.io", + "app---1.sslip.io", + "fe80--1.sslip.io", + "--ffff-7f00-1.sslip.io", + "fd00--1.sslip.io", + "e0000001.example.com", + "lvh.me", + "foo.lvh.me", + "app.localtest.me", + "x.vcap.me", + "a.localhost.direct", + ] { + assert!(is_blocked_host(h), "{h}"); + blocked(&format!("http://{h}/x")); + } + } + + #[test] + fn whatwg_ipv4_parser() { + assert_eq!(parse_ipv4_whatwg("127.1"), Some(0x7f00_0001)); + assert_eq!(parse_ipv4_whatwg("0x7f.1"), Some(0x7f00_0001)); + assert_eq!(parse_ipv4_whatwg("0177.0.0.1"), Some(0x7f00_0001)); + assert_eq!(parse_ipv4_whatwg("1.2.65535"), Some(0x0102_ffff)); + assert_eq!(parse_ipv4_whatwg("1.2.65536"), None); + assert_eq!(parse_ipv4_whatwg("4294967295"), Some(u32::MAX)); + assert_eq!(parse_ipv4_whatwg("4294967296"), None); + assert_eq!(parse_ipv4_whatwg("09"), None); + assert_eq!(parse_ipv4_whatwg("0x"), Some(0)); + assert_eq!(parse_ipv4_whatwg("0xg"), None); + assert_eq!(parse_ipv4_whatwg("1.2.3.4.5"), None); + assert_eq!(parse_ipv4_whatwg("a.1"), None); + assert_eq!(parse_ipv4_whatwg(""), None); + assert_eq!(parse_ipv4_whatwg("0xffffffffffffffffffffff"), None); + assert!(ends_in_number("a.0x")); + assert!(ends_in_number("a.1")); + assert!(!ends_in_number("a.1b")); + assert!(!ends_in_number("a.0xg")); + } + + #[test] + fn hostile_url_inputs_do_not_panic() { + let long = format!("http://{}/", "1-".repeat(5000)); + let _ = validate_scrape_url(&long); + let _ = validate_scrape_url(&format!("http://{}/", "-".repeat(63))); + let _ = validate_scrape_url(&format!("http://{}.com/", "a-".repeat(31))); + let _ = validate_scrape_url("http://["); + let _ = validate_scrape_url("http://]"); + let _ = validate_scrape_url("http://[]:80/"); + let _ = validate_scrape_url("http://:80/"); + let _ = validate_scrape_url("://"); + let _ = is_blocked_host(&"0x".repeat(1000)); + let _ = is_blocked_host(&"9.".repeat(200)); + } + + // ---- paths ---------------------------------------------------------- + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> TempDir { + static N: AtomicUsize = AtomicUsize::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let p = std::env::temp_dir().join(format!( + "agy-guard-{tag}-{}-{nanos}-{}", + std::process::id(), + N.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&p).unwrap(); + TempDir(strip_verbatim(fs::canonicalize(&p).unwrap())) + } + fn path(&self) -> &Path { + &self.0 + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn write(p: &Path, s: &str) { + if let Some(parent) = p.parent() { + fs::create_dir_all(parent).unwrap(); + } + fs::write(p, s).unwrap(); + } + + #[test] + fn unc_detection() { + assert!(is_unc_path("\\\\localhost\\c$\\Users\\u\\.ssh\\id_rsa")); + assert!(is_unc_path("\\\\?\\C:\\x")); + assert!(is_unc_path("\\\\.\\pipe\\x")); + assert!(is_unc_path("//server/share/x")); + assert!(is_unc_path("/\\server")); + assert!(!is_unc_path("C:\\Users\\u\\doc.pdf")); + assert!(!is_unc_path("/home/u/doc.pdf")); + assert!(!is_unc_path("doc.pdf")); + assert!(!is_unc_path("/")); + assert!(!is_unc_path("")); + } + + #[test] + fn verbatim_prefix_handling() { + assert_eq!( + strip_verbatim(PathBuf::from(r"\\?\C:\Users\u\doc.pdf")), + PathBuf::from(r"C:\Users\u\doc.pdf") + ); + let unc = strip_verbatim(PathBuf::from(r"\\?\UNC\server\share\doc.pdf")); + assert!(path_is_unc(&unc)); + let vol = strip_verbatim(PathBuf::from(r"\\?\Volume{abc}\doc.pdf")); + assert!(path_is_unc(&vol)); + assert_eq!(strip_verbatim(PathBuf::from("/a/b")), PathBuf::from("/a/b")); + } + + #[test] + fn sensitive_paths() { + let home = Path::new("/home/u"); + for rel in [ + ".ssh/id_rsa", + ".gemini/x.txt", + ".aws/credentials", + ".config/gcloud/a.json", + ".gnupg/x", + ".kube/config", + ".docker/config.json", + ".ssh", + ] { + assert!(is_sensitive_path(&home.join(rel), home), "{rel}"); + } + for rel in [ + "projects/doc.pdf", + ".sshx/a.md", + ".config/other/a.md", + "ssh/a.md", + ] { + assert!(!is_sensitive_path(&home.join(rel), home), "{rel}"); + } + #[cfg(unix)] + { + for p in [ + "/etc/passwd", + "/etc", + "/root/a.md", + "/proc/self/environ", + "/sys/x", + "/dev/stdin", + "/var/run/docker.sock", + ] { + assert!(is_sensitive_path(Path::new(p), home), "{p}"); + } + assert!(!is_sensitive_path(Path::new("/etcetera/x.md"), home)); + assert!(!is_sensitive_path(Path::new("/var/runner/x.md"), home)); + } + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_private_etc_and_case() { + let home = Path::new("/Users/u"); + assert!(is_sensitive_path(Path::new("/private/etc/hosts"), home)); + assert!(is_sensitive_path(Path::new("/private/var/run/x.txt"), home)); + assert!(is_sensitive_path(Path::new("/Users/u/.SSH/notes.md"), home)); + assert!(is_sensitive_path(Path::new("/USERS/U/.Aws/x.txt"), home)); + assert!(is_sensitive_path(Path::new("/ETC/hosts"), home)); + } + + #[cfg(target_os = "linux")] + #[test] + fn linux_is_case_sensitive() { + let home = Path::new("/home/u"); + assert!(!is_sensitive_path(Path::new("/home/u/.SSH/notes.md"), home)); + } + + #[test] + fn doc_accepts_allowed_types() { + let t = TempDir::new("doc-ok"); + write(&t.path().join("notes.md"), "# hi\n"); + write(&t.path().join("sub/REPORT.PDF"), "%PDF"); + let home = t.path().join("home"); + assert_eq!( + validate_doc_path("notes.md", t.path(), &home), + Ok(t.path().join("notes.md")) + ); + assert_eq!( + validate_doc_path(" notes.md \n", t.path(), &home), + Ok(t.path().join("notes.md")) + ); + assert_eq!( + validate_doc_path("sub/../sub/REPORT.PDF", t.path(), &home), + Ok(t.path().join("sub").join("REPORT.PDF")) + ); + let abs = t.path().join("notes.md"); + assert!( + validate_doc_path(&abs.to_string_lossy(), Path::new("/nonexistent"), &home).is_ok() + ); + for ext in ALLOWED_DOC_EXT { + let f = t.path().join(format!("f.{ext}")); + write(&f, "x"); + assert!( + validate_doc_path(&f.to_string_lossy(), t.path(), &home).is_ok(), + "{ext}" + ); + } + } + + #[test] + fn doc_rejections() { + let t = TempDir::new("doc-bad"); + let home = t.path().join("home"); + let cwd = t.path(); + write(&cwd.join("secrets.env"), "API_KEY=abc\n"); + write(&cwd.join(".env"), "API_KEY=abc\n"); + write(&cwd.join("id_rsa"), "key"); + write(&cwd.join("x.pdf.pem"), "key"); + write(&cwd.join("trail."), "x"); + fs::create_dir_all(cwd.join("sub.md")).unwrap(); + assert_eq!(validate_doc_path("", cwd, &home), Err("empty path".into())); + assert_eq!( + validate_doc_path(" \t\n", cwd, &home), + Err("empty path".into()) + ); + assert_eq!( + validate_doc_path("secrets.env", cwd, &home), + Err("extension '.env' is not an allowed document type".into()) + ); + assert_eq!( + validate_doc_path(".env", cwd, &home), + Err("extension '(none)' is not an allowed document type".into()) + ); + assert_eq!( + validate_doc_path("id_rsa", cwd, &home), + Err("extension '(none)' is not an allowed document type".into()) + ); + assert_eq!( + validate_doc_path("x.pdf.pem", cwd, &home), + Err("extension '.pem' is not an allowed document type".into()) + ); + // Windows silently strips a trailing dot from file names ("trail." + // is "trail"), so the extension is gone there. + let trail = if cfg!(windows) { "(none)" } else { "." }; + assert_eq!( + validate_doc_path("trail.", cwd, &home), + Err(format!( + "extension '{trail}' is not an allowed document type" + )) + ); + assert_eq!( + validate_doc_path("nope.pdf", cwd, &home), + Err("file does not exist".into()) + ); + assert_eq!( + validate_doc_path("sub.md", cwd, &home), + Err("not a regular file".into()) + ); + assert_eq!( + validate_doc_path("//server/share/x.pdf", cwd, &home), + Err("UNC / device paths are not allowed".into()) + ); + } + + #[test] + fn doc_size_cap() { + let t = TempDir::new("doc-size"); + let home = t.path().join("home"); + let at_cap = File::create(t.path().join("cap.txt")).unwrap(); + at_cap.set_len(MAX_DOC_BYTES).unwrap(); + let over = File::create(t.path().join("big.txt")).unwrap(); + over.set_len(MAX_DOC_BYTES + 1).unwrap(); + assert!(validate_doc_path("cap.txt", t.path(), &home).is_ok()); + assert_eq!( + validate_doc_path("big.txt", t.path(), &home), + Err("file too large (10485761 bytes > 10485760 limit)".into()) + ); + } + + #[test] + fn doc_under_sensitive_home_dir() { + let t = TempDir::new("doc-sens"); + let home = t.path().join("home"); + let f = home.join(".ssh").join("notes.md"); + write(&f, "secret"); + assert_eq!( + validate_doc_path(&f.to_string_lossy(), t.path(), &home), + Err("path resolves under a sensitive directory".into()) + ); + write(&home.join(".config/gcloud/notes.txt"), "x"); + assert_eq!( + validate_doc_path(".config/gcloud/notes.txt", &home, &home), + Err("path resolves under a sensitive directory".into()) + ); + } + + #[cfg(unix)] + #[test] + fn doc_symlink_attacks() { + use std::os::unix::fs::symlink; + let t = TempDir::new("doc-link"); + let home = t.path().join("home"); + let cwd = t.path().join("proj"); + fs::create_dir_all(&cwd).unwrap(); + write(&home.join(".ssh/notes.md"), "secret"); + write(&home.join(".ssh/id_rsa"), "key"); + // Allowed-looking name pointing into ~/.ssh. + symlink(home.join(".ssh/notes.md"), cwd.join("doc.md")).unwrap(); + assert_eq!( + validate_doc_path("doc.md", &cwd, &home), + Err("path resolves under a sensitive directory".into()) + ); + // `.pdf` link to an extension-less key: real path decides. + symlink(home.join(".ssh/id_rsa"), cwd.join("doc.pdf")).unwrap(); + assert_eq!( + validate_doc_path("doc.pdf", &cwd, &home), + Err("extension '(none)' is not an allowed document type".into()) + ); + // Symlinked directory into ~/.ssh. + symlink(home.join(".ssh"), cwd.join("docs")).unwrap(); + assert_eq!( + validate_doc_path("docs/notes.md", &cwd, &home), + Err("path resolves under a sensitive directory".into()) + ); + // Link to /etc (on macOS /private/etc) with an allowed name. + symlink("/etc", cwd.join("etc-link")).unwrap(); + if let Ok(entries) = fs::read_dir("/etc") { + let doc = entries.filter_map(|e| e.ok()).find(|e| { + e.path().is_file() + && e.path() + .extension() + .is_some_and(|x| ALLOWED_DOC_EXT.contains(&x.to_string_lossy().as_ref())) + && File::open(e.path()).is_ok() + }); + if let Some(d) = doc { + let rel = format!("etc-link/{}", d.file_name().to_string_lossy()); + assert_eq!( + validate_doc_path(&rel, &cwd, &home), + Err("path resolves under a sensitive directory".into()) + ); + } + } + // Dangling link. + symlink(cwd.join("missing.md"), cwd.join("dangling.md")).unwrap(); + assert_eq!( + validate_doc_path("dangling.md", &cwd, &home), + Err("file does not exist".into()) + ); + // Link loop. + symlink(cwd.join("loop2.md"), cwd.join("loop1.md")).unwrap(); + symlink(cwd.join("loop1.md"), cwd.join("loop2.md")).unwrap(); + assert_eq!( + validate_doc_path("loop1.md", &cwd, &home), + Err("file does not exist".into()) + ); + } + + #[cfg(unix)] + #[test] + fn symlinked_home_is_still_sensitive() { + // Same shape as macOS /etc -> /private/etc: the file path is the + // realpath, the base is given via a symlink. + use std::os::unix::fs::symlink; + let t = TempDir::new("symhome"); + let real_home = t.path().join("real-home"); + let link_home = t.path().join("link-home"); + fs::create_dir_all(real_home.join(".ssh")).unwrap(); + symlink(&real_home, &link_home).unwrap(); + let real_file = fs::canonicalize(&real_home) + .unwrap() + .join(".ssh") + .join("notes.md"); + assert!(is_sensitive_path(&real_file, &link_home)); + write(&real_file, "x"); + assert_eq!( + validate_doc_path( + &link_home.join(".ssh/notes.md").to_string_lossy(), + t.path(), + &link_home + ), + Err("path resolves under a sensitive directory".into()) + ); + } + + #[cfg(target_os = "macos")] + #[test] + fn macos_case_trick_on_real_fs() { + let t = TempDir::new("case"); + let home = t.path().join("home"); + write(&home.join(".ssh/notes.md"), "secret"); + // Default APFS is case-insensitive: .SSH resolves to the same dir. + let probe = home.join(".SSH/notes.md"); + if probe.exists() { + let r = validate_doc_path(&probe.to_string_lossy(), t.path(), &home); + assert_eq!(r, Err("path resolves under a sensitive directory".into())); + } + } + + #[cfg(unix)] + #[test] + fn doc_fifo_is_not_a_regular_file() { + let t = TempDir::new("fifo"); + let fifo = t.path().join("pipe.md"); + let made = std::process::Command::new("mkfifo").arg(&fifo).status(); + if made.is_ok_and(|s| s.success()) { + assert_eq!( + validate_doc_path("pipe.md", t.path(), &t.path().join("home")), + Err("not a regular file".into()) + ); + assert_eq!( + stage_file(&fifo, &t.path().join("out.md")), + Err("source is not a regular file".into()) + ); + } + } + + // ---- staging -------------------------------------------------------- + + #[test] + fn stage_copies_regular_file() { + let t = TempDir::new("stage"); + let src = t.path().join("src.md"); + write(&src, "hello"); + let dest = t.path().join("document.md"); + assert_eq!(stage_file(&src, &dest), Ok(())); + assert_eq!(fs::read_to_string(&dest).unwrap(), "hello"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&dest).unwrap().permissions().mode(); + assert_eq!(mode & 0o077, 0); + } + let empty = t.path().join("empty.md"); + write(&empty, ""); + assert_eq!(stage_file(&empty, &t.path().join("e2.md")), Ok(())); + } + + #[test] + fn stage_rejects_missing_and_bad_args() { + let t = TempDir::new("stage-miss"); + assert_eq!( + stage_file(&t.path().join("nope"), &t.path().join("d")), + Err("source file is gone".into()) + ); + assert_eq!( + stage_file(Path::new(""), Path::new("")), + Err("stage requires ".into()) + ); + assert_eq!( + stage_file(t.path(), &t.path().join("d")), + Err("source is not a regular file".into()) + ); + } + + #[test] + fn stage_never_overwrites_dest() { + let t = TempDir::new("stage-dest"); + let src = t.path().join("src.md"); + write(&src, "new"); + let dest = t.path().join("dest.md"); + write(&dest, "old"); + let e = stage_file(&src, &dest).unwrap_err(); + assert!(e.starts_with("copy failed: "), "{e}"); + assert_eq!(fs::read_to_string(&dest).unwrap(), "old"); + } + + #[cfg(unix)] + #[test] + fn stage_never_follows_dest_symlink() { + use std::os::unix::fs::symlink; + let t = TempDir::new("stage-destlink"); + let src = t.path().join("src.md"); + write(&src, "payload"); + let victim = t.path().join("victim.txt"); + write(&victim, "keep"); + let d1 = t.path().join("d1.md"); + symlink(&victim, &d1).unwrap(); + assert!( + stage_file(&src, &d1) + .unwrap_err() + .starts_with("copy failed: ") + ); + assert_eq!(fs::read_to_string(&victim).unwrap(), "keep"); + // Dangling link: must not create its target. + let target = t.path().join("created-through-link.txt"); + let d2 = t.path().join("d2.md"); + symlink(&target, &d2).unwrap(); + assert!( + stage_file(&src, &d2) + .unwrap_err() + .starts_with("copy failed: ") + ); + assert!(!target.exists()); + } + + #[cfg(unix)] + #[test] + fn stage_rejects_symlink_source() { + use std::os::unix::fs::symlink; + let t = TempDir::new("stage-link"); + let target = t.path().join("secret"); + write(&target, "secret"); + let link = t.path().join("link.md"); + symlink(&target, &link).unwrap(); + assert_eq!( + stage_file(&link, &t.path().join("out.md")), + Err("source became a symlink (TOCTOU)".into()) + ); + assert!(!t.path().join("out.md").exists()); + } + + #[cfg(unix)] + #[test] + fn stage_detects_swap_after_validation() { + use std::os::unix::fs::symlink; + let t = TempDir::new("stage-swap"); + let home = t.path().join("home"); + write(&home.join(".ssh/id_rsa"), "PRIVATE"); + let doc = t.path().join("doc.md"); + write(&doc, "fine"); + let real = validate_doc_path("doc.md", t.path(), &home).unwrap(); + // Attacker swaps the validated file for a symlink to a secret. + fs::remove_file(&real).unwrap(); + symlink(home.join(".ssh/id_rsa"), &real).unwrap(); + let out = t.path().join("staged.md"); + assert_eq!( + stage_file(&real, &out), + Err("source became a symlink (TOCTOU)".into()) + ); + assert!(!out.exists()); + // ...or for a directory. + fs::remove_file(&real).unwrap(); + fs::create_dir(&real).unwrap(); + assert_eq!( + stage_file(&real, &out), + Err("source is not a regular file".into()) + ); + // ...or removes it. + fs::remove_dir(&real).unwrap(); + assert_eq!(stage_file(&real, &out), Err("source file is gone".into())); + } + + #[cfg(unix)] + #[test] + fn same_file_check_detects_different_inode() { + let t = TempDir::new("inode"); + let a = t.path().join("a.md"); + let b = t.path().join("b.md"); + write(&a, "a"); + write(&b, "b"); + let ma = fs::symlink_metadata(&a).unwrap(); + let mb = File::open(&b).unwrap().metadata().unwrap(); + assert_eq!( + same_file(&ma, &mb), + Err("source was swapped (TOCTOU)".into()) + ); + let ma2 = File::open(&a).unwrap().metadata().unwrap(); + assert_eq!(same_file(&ma, &ma2), Ok(())); + } + + #[test] + fn stage_size_cap() { + let t = TempDir::new("stage-big"); + let src = t.path().join("big.txt"); + File::create(&src) + .unwrap() + .set_len(MAX_DOC_BYTES + 1) + .unwrap(); + let dest = t.path().join("out.txt"); + assert_eq!(stage_file(&src, &dest), Err("source too large".into())); + assert!(!dest.exists()); + let cap = t.path().join("cap.txt"); + File::create(&cap).unwrap().set_len(MAX_DOC_BYTES).unwrap(); + assert_eq!(stage_file(&cap, &t.path().join("cap-out.txt")), Ok(())); + assert_eq!( + fs::metadata(t.path().join("cap-out.txt")).unwrap().len(), + MAX_DOC_BYTES + ); + } +} diff --git a/src/jobs.rs b/src/jobs.rs new file mode 100644 index 0000000..12401dc --- /dev/null +++ b/src/jobs.rs @@ -0,0 +1,1159 @@ +//! Job state under `/.agy-plugin/` and the worker that runs a job. +//! +//! The on-disk format is the one 0.8.x wrote (jobs/.json, +//! logs/.log, runtime/.pid, patches/.patch), so records from +//! older versions keep working with /agy:status, /agy:result, /agy:cancel. +//! +//! Fixes over 0.8.x: +//! - every read-modify-write of a record happens under a per-job lock file, +//! and the WORKER (not the parent) marks a job running, so a fast worker's +//! final status can no longer be overwritten with "running"; +//! - background workers lead their own process group and cancel stops the +//! whole group, so agy isn't orphaned; +//! - an agy killed by a signal is a failure, not exit code 0. + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use crate::json::{self, Map, Value}; +use crate::util::{self, Fail}; + +pub(crate) const STATE_DIR: &str = ".agy-plugin"; +pub(crate) const KINDS: &[&str] = &["rescue", "research", "review", "adversarial-review"]; +pub(crate) const STATUSES: &[&str] = &["pending", "running", "completed", "failed", "canceled"]; + +pub(crate) fn state_dir(root: &Path) -> PathBuf { + root.join(STATE_DIR) +} +pub(crate) fn record_path(root: &Path, id: &str) -> PathBuf { + state_dir(root).join("jobs").join(format!("{id}.json")) +} +pub(crate) fn log_path(root: &Path, id: &str) -> PathBuf { + state_dir(root).join("logs").join(format!("{id}.log")) +} +pub(crate) fn pid_path(root: &Path, id: &str) -> PathBuf { + state_dir(root).join("runtime").join(format!("{id}.pid")) +} +fn lock_path(root: &Path, id: &str) -> PathBuf { + state_dir(root).join("runtime").join(format!("{id}.lock")) +} +pub(crate) fn patch_path(root: &Path, id: &str) -> PathBuf { + state_dir(root).join("patches").join(format!("{id}.patch")) +} + +/// `agy-` + 8 lowercase hex digits, exactly what `generate_id` produces. +pub(crate) fn is_valid_id(s: &str) -> bool { + s.len() == 12 + && s.starts_with("agy-") + && s[4..] + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +pub(crate) fn generate_id() -> String { + format!("agy-{}", util::random_hex(4)) +} + +fn io_fail(what: &str, e: std::io::Error) -> Fail { + Fail::runtime(format!("error: {what}: {e}")) +} + +/// Write via a private temp file + rename, so a reader never sees a torn +/// record and a crash leaves the old one intact. Mode 0600: records hold +/// the full prompt. +pub(crate) fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { + let dir = path + .parent() + .ok_or_else(|| std::io::Error::other("path has no parent"))?; + std::fs::create_dir_all(dir)?; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = dir.join(format!( + ".{name}.tmp-{}-{}", + std::process::id(), + util::random_hex(4) + )); + let mut opts = OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let res = (|| { + let mut f = opts.open(&tmp)?; + f.write_all(data)?; + f.sync_all()?; + drop(f); + std::fs::rename(&tmp, path) + })(); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); + } + res +} + +fn write_record(root: &Path, id: &str, rec: &Value) -> Result<(), Fail> { + let text = format!("{}\n", json::to_string_pretty(rec)); + write_atomic(&record_path(root, id), text.as_bytes()) + .map_err(|e| io_fail("could not write the job record", e)) +} + +/// Ok(None) for a missing or empty file; Err for unreadable or invalid JSON. +fn read_record_file(path: &Path) -> Result, String> { + let text = match std::fs::read_to_string(path) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.to_string()), + }; + if text.trim().is_empty() { + return Ok(None); + } + let v = json::parse(&text).map_err(|e| e.to_string())?; + if v.as_object().is_none() { + return Err("job record is not a JSON object".into()); + } + Ok(Some(v)) +} + +/// Read a job; None for an unknown or malformed id (no disk access then). +pub(crate) fn read_job(root: &Path, id: &str) -> Result, Fail> { + if !is_valid_id(id) { + return Ok(None); + } + read_record_file(&record_path(root, id)) + .map_err(|e| Fail::runtime(format!("error: job {id} is unreadable: {e}"))) +} + +/// Run `f` while holding `runtime/.lock` (create-exclusive). A lock +/// older than 30 s is from a crashed process and is broken. +fn with_lock(root: &Path, id: &str, f: impl FnOnce() -> Result) -> Result { + let lp = lock_path(root, id); + if let Some(d) = lp.parent() { + std::fs::create_dir_all(d).map_err(|e| io_fail("could not create the job state dir", e))?; + } + let start = Instant::now(); + loop { + match OpenOptions::new().write(true).create_new(true).open(&lp) { + Ok(mut file) => { + let _ = write!(file, "{}", std::process::id()); + break; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let stale = std::fs::metadata(&lp) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > Duration::from_secs(30)); + if stale { + let _ = std::fs::remove_file(&lp); + continue; + } + if start.elapsed() > Duration::from_secs(10) { + return Err(Fail::runtime(format!( + "error: job {id} is locked by another process" + ))); + } + std::thread::sleep(Duration::from_millis(15)); + } + Err(e) => return Err(io_fail("could not lock the job record", e)), + } + } + let res = f(); + let _ = std::fs::remove_file(&lp); + res +} + +/// Read-modify-write a job record under its lock. `f` edits the object; +/// `lastUpdatedAt` is set automatically and statuses are validated. +pub(crate) fn update_job(root: &Path, id: &str, f: impl FnOnce(&mut Map)) -> Result { + with_lock(root, id, || { + let mut rec = read_job(root, id)? + .ok_or_else(|| Fail::runtime(format!("error: no such job '{id}'")))?; + let obj = rec + .as_object_mut() + .ok_or_else(|| Fail::runtime("error: job record is not an object"))?; + f(obj); + if let Some(s) = obj.get("status").and_then(Value::as_str) + && !STATUSES.contains(&s) + { + return Err(Fail::runtime(format!("error: invalid job status '{s}'"))); + } + obj.set("id", id); + obj.set("lastUpdatedAt", crate::time::iso_now()); + write_record(root, id, &rec)?; + Ok(rec) + }) +} + +pub(crate) struct NewJob { + pub(crate) kind: &'static str, + pub(crate) task: String, + pub(crate) model: Option, + pub(crate) args: Vec, + pub(crate) background: bool, + pub(crate) prompt: String, + pub(crate) agy_bin: String, + pub(crate) execution_root: Option, + pub(crate) stage_dir: Option, +} + +fn path_value(p: &Option) -> Value { + p.as_ref() + .map(|p| Value::from(p.display().to_string())) + .unwrap_or(Value::Null) +} + +/// Create a pending job record (key order as 0.8.x wrote it). +pub(crate) fn create_job(root: &Path, job: NewJob) -> Result { + if !KINDS.contains(&job.kind) { + return Err(Fail::runtime(format!( + "error: invalid job kind '{}'", + job.kind + ))); + } + check_state_dirs(root)?; + for sub in ["jobs", "logs", "runtime"] { + std::fs::create_dir_all(state_dir(root).join(sub)) + .map_err(|e| io_fail("could not create the job state dir", e))?; + } + check_state_dirs(root)?; + crate::git::ensure_exclude(root); + let mut id = generate_id(); + while record_path(root, &id).exists() { + id = generate_id(); + } + let log_rel = Path::new(STATE_DIR).join("logs").join(format!("{id}.log")); + let mut meta = Map::new(); + meta.set("prompt", job.prompt); + meta.set("agyBin", job.agy_bin); + meta.set("executionRoot", path_value(&job.execution_root)); + meta.set("stageDir", path_value(&job.stage_dir)); + let mut m = Map::new(); + m.set("id", id.clone()); + m.set("kind", job.kind); + m.set("task", job.task); + m.set("model", job.model); + m.set("workspaceRoot", root.display().to_string()); + m.set("createdAt", crate::time::iso_now()); + m.set("startedAt", Value::Null); + m.set("completedAt", Value::Null); + m.set("status", "pending"); + m.set("exitCode", Value::Null); + m.set("pid", Value::Null); + m.set("logFile", log_rel.display().to_string()); + m.set( + "args", + Value::Array(job.args.into_iter().map(Value::from).collect()), + ); + m.set("background", job.background); + m.set("meta", meta); + let rec = Value::Object(m); + write_record(root, &id, &rec)?; + crate::registry::register(&id, root, job.stage_dir.as_deref()); + Ok(rec) +} + +/// Refuse a `.agy-plugin` (or a subdirectory) that is a symlink: a repo can +/// commit one, and records, logs and patches would then be read from and +/// written to wherever it points. +pub(crate) fn check_state_dirs(root: &Path) -> Result<(), Fail> { + let base = state_dir(root); + for p in [ + base.clone(), + base.join("jobs"), + base.join("logs"), + base.join("runtime"), + base.join("patches"), + ] { + if let Ok(m) = std::fs::symlink_metadata(&p) + && m.file_type().is_symlink() + { + return Err(Fail::runtime(format!( + "error: {} is a symlink; refusing to use it for job state.", + p.display() + ))); + } + } + Ok(()) +} + +fn str_field<'a>(rec: &'a Value, key: &str) -> Option<&'a str> { + rec.get(key).and_then(Value::as_str) +} + +pub(crate) fn id_of(rec: &Value) -> &str { + str_field(rec, "id").unwrap_or("") +} + +pub(crate) fn status_of(rec: &Value) -> &str { + str_field(rec, "status").unwrap_or("") +} + +fn pid_of(rec: &Value) -> Option { + rec.get("pid") + .and_then(Value::as_u64) + .and_then(|p| u32::try_from(p).ok()) + .filter(|p| *p > 0) +} + +/// All jobs, newest first; corrupt records are skipped with a note. +pub(crate) fn list_jobs(root: &Path, kind: Option<&str>, limit: Option) -> Vec { + let Ok(entries) = std::fs::read_dir(state_dir(root).join("jobs")) else { + return Vec::new(); + }; + let mut out: Vec = Vec::new(); + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if !name.ends_with(".json") || name.starts_with('.') { + continue; + } + match read_record_file(&e.path()) { + Ok(Some(v)) => out.push(v), + Ok(None) => {} + Err(err) => eprintln!("agy-plugin: skipping corrupt job {name}: {err}"), + } + } + out.sort_by(|a, b| { + str_field(b, "createdAt") + .unwrap_or("") + .cmp(str_field(a, "createdAt").unwrap_or("")) + }); + if let Some(k) = kind { + out.retain(|r| str_field(r, "kind") == Some(k)); + } + if let Some(n) = limit { + out.truncate(n); + } + out +} + +/// Is the job's worker running? Proven by its registry lock when this user +/// started the job here; otherwise (records from 0.8.x) a best-effort pid +/// check, which is only ever used for DISPLAY, never to send a signal. +fn worker_alive(rec: &Value) -> bool { + let id = id_of(rec); + if crate::registry::read(id).is_some() { + // Our job: only a held lock counts (a bare pid may have been reused). + return crate::registry::worker_alive(id) == Some(true); + } + pid_of(rec).is_some_and(crate::sys::process_alive) +} + +/// A "running" record whose worker is gone is reported as failed (not +/// persisted; `wait_for_job` persists it). +pub(crate) fn liveness(rec: &Value) -> Value { + let mut r = rec.clone(); + if status_of(rec) == "running" + && !worker_alive(rec) + && let Some(o) = r.as_object_mut() + { + o.set("status", "failed"); + o.set("livenessDowngrade", true); + } + r +} + +pub(crate) enum Resolved { + Found(Value), + NotFound, + Ambiguous(Vec), + BadId, + NotCancelable(Value), +} + +/// Resolve "", "latest", a full id or a unique prefix (`agy-3a7b`). +pub(crate) fn resolve_job(root: &Path, input: &str) -> Result { + let raw = input.trim(); + if raw.is_empty() || raw == "latest" { + return Ok(list_jobs(root, None, Some(1)) + .first() + .map_or(Resolved::NotFound, |r| Resolved::Found(liveness(r)))); + } + if is_valid_id(raw) { + return Ok( + read_job(root, raw)?.map_or(Resolved::NotFound, |r| Resolved::Found(liveness(&r))) + ); + } + let hex = raw.strip_prefix("agy-").unwrap_or(""); + if hex.len() < 2 + || !hex + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Ok(Resolved::BadId); + } + let matches: Vec = list_jobs(root, None, None) + .into_iter() + .filter(|r| id_of(r).starts_with(raw)) + .collect(); + Ok(match matches.len() { + 0 => Resolved::NotFound, + 1 => Resolved::Found(liveness(&matches[0])), + _ => Resolved::Ambiguous(matches.iter().map(|r| id_of(r).to_string()).collect()), + }) +} + +pub(crate) fn resolve_cancelable(root: &Path, input: &str) -> Result { + Ok(match resolve_job(root, input)? { + Resolved::Found(r) if !matches!(status_of(&r), "running" | "pending") => { + Resolved::NotCancelable(r) + } + other => other, + }) +} + +// --------------------------------------------------------------------------- +// Running a job +// --------------------------------------------------------------------------- + +/// Where the worker's output goes: stdout (which IS the log for background +/// workers) and, in the foreground, also appended to the log file. +pub(crate) struct Sink { + tee: Option, +} + +impl Sink { + pub(crate) fn emit(&mut self, text: &str) { + let mut out = std::io::stdout().lock(); + let _ = out.write_all(text.as_bytes()); + let _ = out.flush(); + if let Some(f) = self.tee.as_mut() { + let _ = f.write_all(text.as_bytes()); + } + } +} + +fn open_log_append(path: &Path) -> std::io::Result { + if let Some(d) = path.parent() { + std::fs::create_dir_all(d)?; + } + let mut o = OpenOptions::new(); + o.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + o.mode(0o600); + } + o.open(path) +} + +/// What a job's agy run produced: Some(0) success, Some(n) failure, None +/// killed/unknown. +pub(crate) type RunnerResult = Option; + +/// Runs the agy part of a job. Injectable for tests. +pub(crate) type Runner<'a> = &'a dyn Fn(&Value, &mut Sink) -> RunnerResult; + +/// Run job `id` in this process. `tee` mirrors output into the job log +/// (foreground); background workers already write stdout to the log. +/// Returns the final status. +pub(crate) fn run_worker(root: &Path, id: &str, tee: bool, runner: Runner) -> Result { + let mut sink = Sink { + tee: if tee { + open_log_append(&log_path(root, id)).ok() + } else { + None + }, + }; + let me = std::process::id(); + let mut canceled_early = false; + let rec = update_job(root, id, |o| { + if o.get("status").and_then(Value::as_str) == Some("canceled") { + canceled_early = true; + return; + } + o.set("status", "running"); + o.set("pid", me); + if o.get("startedAt").is_none_or(Value::is_null) { + o.set("startedAt", crate::time::iso_now()); + } + })?; + if canceled_early { + sink.emit(&format!( + "[agy-job {id}] (job was canceled before it started)\n" + )); + return Ok("canceled".into()); + } + let _ = write_atomic(&pid_path(root, id), format!("{me}\n").as_bytes()); + // Proof of life for /agy:cancel: held until this function returns (the + // OS drops it if the process dies). Background workers (no tee) lead + // their own process group. + let _alive = crate::registry::hold(id); + crate::registry::update(id, |e| { + e.pid = Some(me); + e.group_leader = !tee; + }); + set_current_job(Some(id)); + sink.emit(&format!( + "[agy-job {id}] starting at {}\n", + crate::time::iso_now() + )); + sink.emit(&format!( + "[agy-job {id}] task: {}\n", + str_field(&rec, "task").unwrap_or("") + )); + if let Some(m) = str_field(&rec, "model").filter(|m| !m.is_empty()) { + sink.emit(&format!("[agy-job {id}] model: {m}\n")); + } + sink.emit(&format!("[agy-job {id}] ---\n")); + + let exit = runner(&rec, &mut sink); + set_current_job(None); + let final_status = if exit == Some(0) { + "completed" + } else { + "failed" + }; + + let mut was_canceled = false; + update_job(root, id, |o| { + if o.get("status").and_then(Value::as_str) == Some("canceled") { + was_canceled = true; + return; + } + o.set("status", final_status); + o.set("exitCode", exit.map(i64::from)); + o.set("completedAt", crate::time::iso_now()); + })?; + let _ = std::fs::remove_file(pid_path(root, id)); + drop(_alive); + crate::registry::remove(id); + if was_canceled { + sink.emit(&format!( + "[agy-job {id}] (job was canceled; leaving status=canceled)\n" + )); + return Ok("canceled".into()); + } + sink.emit(&format!("[agy-job {id}] ---\n")); + let code = exit.map_or_else(|| "null".to_string(), |c| c.to_string()); + sink.emit(&format!( + "[agy-job {id}] done: status={final_status} exitCode={code}\n" + )); + Ok(final_status.into()) +} + +static CURRENT_JOB: std::sync::Mutex> = std::sync::Mutex::new(None); + +fn set_current_job(id: Option<&str>) { + if let Ok(mut g) = CURRENT_JOB.lock() { + *g = id.map(str::to_string); + } +} + +/// Record the agy process the running job just started, so /agy:cancel can +/// stop it even when the worker isn't a process-group leader (foreground). +pub(crate) fn note_child(pid: u32) { + let id = CURRENT_JOB.lock().ok().and_then(|g| g.clone()); + if let Some(id) = id { + crate::registry::update(&id, |e| e.child_pid = Some(pid)); + } +} + +/// Start the job in a detached worker process (`agy-plugin _run-job `) +/// whose stdout/stderr append to the job log. +pub(crate) fn spawn_worker(root: &Path, id: &str) -> Result { + let log = open_log_append(&log_path(root, id)) + .map_err(|e| io_fail("could not open the job log", e))?; + let log2 = log + .try_clone() + .map_err(|e| io_fail("could not open the job log", e))?; + let exe = std::env::current_exe().map_err(|e| io_fail("could not locate agy-plugin", e))?; + let mut cmd = Command::new(exe); + cmd.arg("_run-job") + .arg(id) + .current_dir(root) + .env("AGY_JOB_WORKSPACE", root) + .stdin(Stdio::null()) + .stdout(Stdio::from(log)) + .stderr(Stdio::from(log2)); + crate::sys::detach(&mut cmd); + let child = cmd + .spawn() + .map_err(|e| io_fail("could not start the background worker", e))?; + let pid = child.id(); + let _ = write_atomic(&pid_path(root, id), format!("{pid}\n").as_bytes()); + crate::registry::update(id, |e| { + e.pid = Some(pid); + e.group_leader = true; + }); + // The worker records its own pid when it starts; record it here too so a + // cancel issued before that still finds the process. + let _ = update_job(root, id, |o| { + if o.get("pid").is_none_or(Value::is_null) { + o.set("pid", pid); + } + }); + Ok(pid) +} + +pub(crate) enum CancelResult { + Canceled(&'static str), + NotFound, + NotCancelable(Option), +} + +/// Cancel a pending or running job: stop its worker's process tree, then +/// mark it canceled. Idempotent for finished jobs. +pub(crate) fn cancel_job(root: &Path, id: &str, grace: Duration) -> Result { + // Check and mark in one locked step, so a job finishing right now can't + // be relabelled "canceled" after it completed. + let marked = with_lock(root, id, || { + let Some(mut rec) = read_job(root, id)? else { + return Ok(Err(CancelResult::NotFound)); + }; + let st = status_of(&rec).to_string(); + if st != "running" && st != "pending" { + return Ok(Err(CancelResult::NotCancelable(Some(st)))); + } + if let Some(o) = rec.as_object_mut() { + o.set("status", "canceled"); + o.set("completedAt", crate::time::iso_now()); + o.set("exitCode", Value::Null); + o.set("lastUpdatedAt", crate::time::iso_now()); + } + write_record(root, id, &rec)?; + Ok(Ok(())) + })?; + if let Err(r) = marked { + return Ok(r); + } + let _ = std::fs::remove_file(pid_path(root, id)); + // Signals and deletions use ONLY this user's registry, never the + // workspace record (a repo can commit a record naming any pid or dir). + let Some(entry) = crate::registry::read_for(id, root) else { + return Ok(CancelResult::Canceled("not-started-here")); + }; + let me = std::process::id(); + let reason = match crate::registry::worker_alive(id) { + Some(true) => { + if let Some(child) = entry.child_pid.filter(|p| *p != me) { + crate::sys::terminate_tree(child, grace); + } + if let Some(pid) = entry.pid.filter(|p| *p != me) { + crate::sys::terminate_tree(pid, grace); + } + "killed" + } + _ => "already-dead", + }; + // A killed worker never reaches its own cleanup. + if let Some(stage) = entry + .stage_dir + .as_deref() + .filter(|p| crate::registry::is_our_stage_dir(p)) + { + let _ = std::fs::remove_dir_all(stage); + } + crate::registry::remove(id); + Ok(CancelResult::Canceled(reason)) +} + +/// Block until the job finishes or `timeout` passes. A "running" record +/// whose worker died is persisted as failed. +pub(crate) fn wait_for_job( + root: &Path, + id: &str, + timeout: Duration, + poll: Duration, +) -> Result, Fail> { + let deadline = Instant::now() + timeout; + loop { + let Some(rec) = read_job(root, id)? else { + return Ok(None); + }; + let st = status_of(&rec); + if st != "running" && st != "pending" { + return Ok(Some(rec)); + } + if st == "running" && !worker_alive(&rec) { + std::thread::sleep(poll); + let Some(again) = read_job(root, id)? else { + return Ok(None); + }; + if matches!(status_of(&again), "running" | "pending") { + return update_job(root, id, |o| { + o.set("status", "failed"); + o.set("completedAt", crate::time::iso_now()); + if let Some(meta) = o.get_mut("meta").and_then(Value::as_object_mut) { + meta.set("livenessDowngradedBy", "waitForJob"); + } + }) + .map(Some); + } + return Ok(Some(again)); + } + if Instant::now() >= deadline { + return Ok(Some(rec)); + } + std::thread::sleep(poll); + } +} + +pub(crate) fn read_log(root: &Path, id: &str) -> Result { + match std::fs::read(log_path(root, id)) { + Ok(b) => Ok(String::from_utf8_lossy(&b).into_owned()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()), + Err(e) => Err(io_fail("could not read the job log", e)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::util::TempDir; + + fn new_job(kind: &'static str, background: bool) -> NewJob { + NewJob { + kind, + task: "do the thing".into(), + model: None, + args: vec![], + background, + prompt: "prompt — with \"quotes\"".into(), + agy_bin: "agy".into(), + execution_root: None, + stage_dir: None, + } + } + + #[test] + fn ids() { + let id = generate_id(); + assert!(is_valid_id(&id), "{id}"); + for bad in [ + "agy-DEADBEEF", + "agy-deadbee", + "agy-deadbeeff", + "../../etc/passwd", + "agy-deadbeef\n", + "", + "agy-../../x", + ] { + assert!(!is_valid_id(bad), "{bad:?}"); + } + } + + #[test] + fn create_read_update_round_trip_in_the_0_8_format() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let rec = create_job(d.path(), new_job("review", false)).unwrap(); + let id = id_of(&rec).to_string(); + let text = std::fs::read_to_string(record_path(d.path(), &id)).unwrap(); + let keys: Vec<&str> = rec.as_object().unwrap().iter().map(|(k, _)| k).collect(); + assert_eq!( + keys, + [ + "id", + "kind", + "task", + "model", + "workspaceRoot", + "createdAt", + "startedAt", + "completedAt", + "status", + "exitCode", + "pid", + "logFile", + "args", + "background", + "meta" + ] + ); + assert!(text.ends_with("}\n") && text.contains("\n \"meta\": {\n \"prompt\"")); + assert_eq!(status_of(&rec), "pending"); + let up = update_job(d.path(), &id, |o| o.set("status", "running")).unwrap(); + assert_eq!(status_of(&up), "running"); + assert!(up.get("lastUpdatedAt").is_some()); + assert!(update_job(d.path(), &id, |o| o.set("status", "bogus")).is_err()); + assert!(read_job(d.path(), "agy-00000000").unwrap().is_none()); + assert!(read_job(d.path(), "../../etc/passwd").unwrap().is_none()); + assert!(create_job(d.path(), new_job("nope", false)).is_err()); + } + + #[test] + fn reads_a_record_written_by_0_8_x() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + std::fs::create_dir_all(d.path().join(".agy-plugin/jobs")).unwrap(); + std::fs::write( + record_path(d.path(), "agy-2b067725"), + "{\n \"id\": \"agy-2b067725\",\n \"kind\": \"review\",\n \"task\": \"t\",\n \"model\": null,\n \"status\": \"completed\",\n \"exitCode\": 0,\n \"pid\": null,\n \"createdAt\": \"2026-05-31T15:02:38.473Z\",\n \"meta\": {}\n}\n", + ) + .unwrap(); + match resolve_job(d.path(), "agy-2b").unwrap() { + Resolved::Found(r) => assert_eq!(status_of(&r), "completed"), + _ => panic!("not found"), + } + } + + #[test] + fn list_sorts_filters_limits_and_skips_corrupt() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let a = create_job(d.path(), new_job("review", false)).unwrap(); + std::thread::sleep(Duration::from_millis(5)); + let b = create_job(d.path(), new_job("rescue", false)).unwrap(); + std::fs::write(d.path().join(".agy-plugin/jobs/agy-broken0.json"), "{oops").unwrap(); + let all = list_jobs(d.path(), None, None); + assert_eq!( + all.iter().map(id_of).collect::>(), + vec![id_of(&b), id_of(&a)] + ); + assert_eq!(list_jobs(d.path(), Some("review"), None).len(), 1); + assert_eq!(list_jobs(d.path(), None, Some(1)).len(), 1); + assert!(list_jobs(&d.path().join("nothing"), None, None).is_empty()); + } + + #[test] + fn resolution_rules() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + assert!(matches!( + resolve_job(d.path(), "").unwrap(), + Resolved::NotFound + )); + let r = create_job(d.path(), new_job("review", false)).unwrap(); + let id = id_of(&r).to_string(); + assert!(matches!( + resolve_job(d.path(), "latest").unwrap(), + Resolved::Found(_) + )); + assert!(matches!( + resolve_job(d.path(), &id).unwrap(), + Resolved::Found(_) + )); + assert!(matches!( + resolve_job(d.path(), &id[..6]).unwrap(), + Resolved::Found(_) + )); + for bad in ["agy-", "agy-a", "AGY-1234", "../x", "agy-ZZ"] { + assert!( + matches!(resolve_job(d.path(), bad).unwrap(), Resolved::BadId), + "{bad}" + ); + } + // Two jobs sharing a prefix -> ambiguous. + std::fs::write( + record_path(d.path(), "agy-aa000001"), + "{\"id\":\"agy-aa000001\",\"createdAt\":\"1\"}", + ) + .unwrap(); + std::fs::write( + record_path(d.path(), "agy-aa000002"), + "{\"id\":\"agy-aa000002\",\"createdAt\":\"2\"}", + ) + .unwrap(); + match resolve_job(d.path(), "agy-aa").unwrap() { + Resolved::Ambiguous(c) => assert_eq!(c.len(), 2), + _ => panic!("expected ambiguous"), + } + assert!( + matches!( + resolve_cancelable(d.path(), &id).unwrap(), + Resolved::Found(_) + ), + "pending is cancelable" + ); + } + + #[test] + fn worker_success_failure_and_signal() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + for (code, want) in [ + (Some(0), "completed"), + (Some(2), "failed"), + (None, "failed"), + ] { + let r = create_job(d.path(), new_job("review", false)).unwrap(); + let id = id_of(&r).to_string(); + let st = run_worker(d.path(), &id, true, &|_, s| { + s.emit("answer\n"); + code + }) + .unwrap(); + assert_eq!(st, want); + let rec = read_job(d.path(), &id).unwrap().unwrap(); + assert_eq!(status_of(&rec), want); + assert_eq!( + rec.get("pid").and_then(Value::as_u64), + Some(u64::from(std::process::id())) + ); + let log = read_log(d.path(), &id).unwrap(); + assert!( + log.contains("answer\n") && log.contains(&format!("done: status={want}")), + "{log}" + ); + assert!(!pid_path(d.path(), &id).exists()); + } + } + + #[test] + fn cancel_during_run_keeps_canceled_and_canceled_before_start_never_runs() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("review", false)).unwrap(); + let id = id_of(&r).to_string(); + let root = d.path().to_path_buf(); + let st = run_worker(d.path(), &id, false, &|rec, _| { + // Simulate /agy:cancel arriving mid-run from another process. + let jid = id_of(rec).to_string(); + update_job(&root, &jid, |o| o.set("status", "canceled")).unwrap(); + Some(0) + }) + .unwrap(); + assert_eq!(st, "canceled"); + assert_eq!( + status_of(&read_job(d.path(), &id).unwrap().unwrap()), + "canceled" + ); + + let r2 = create_job(d.path(), new_job("review", false)).unwrap(); + let id2 = id_of(&r2).to_string(); + assert!(matches!( + cancel_job(d.path(), &id2, Duration::from_millis(10)).unwrap(), + CancelResult::Canceled(_) + )); + let ran = std::cell::Cell::new(false); + assert_eq!( + run_worker(d.path(), &id2, false, &|_, _| { + ran.set(true); + Some(0) + }) + .unwrap(), + "canceled" + ); + assert!(!ran.get(), "a job canceled before start must not run"); + assert!(matches!( + cancel_job(d.path(), &id2, Duration::from_millis(10)).unwrap(), + CancelResult::NotCancelable(_) + )); + assert!(matches!( + cancel_job(d.path(), "agy-00000000", Duration::from_millis(10)).unwrap(), + CancelResult::NotFound + )); + } + + #[cfg(unix)] + fn spawn_detached_sleep() -> ( + u32, + std::thread::JoinHandle>, + ) { + let mut cmd = Command::new("sleep"); + cmd.arg("60"); + crate::sys::detach(&mut cmd); + let mut child = cmd.spawn().unwrap(); + let pid = child.id(); + (pid, std::thread::spawn(move || child.wait())) + } + + #[cfg(unix)] + #[test] + fn cancel_stops_a_worker_proven_alive_by_its_registry_lock() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("rescue", true)).unwrap(); + let id = id_of(&r).to_string(); + let (pid, reaper) = spawn_detached_sleep(); + update_job(d.path(), &id, |o| { + o.set("status", "running"); + o.set("pid", pid); + }) + .unwrap(); + crate::registry::update(&id, |e| { + e.pid = Some(pid); + e.group_leader = true; + }); + // The worker's proof of life (held by the worker process in real runs). + let lock = crate::registry::hold(&id).unwrap(); + assert!(matches!( + cancel_job(d.path(), &id, Duration::from_secs(3)).unwrap(), + CancelResult::Canceled("killed") + )); + drop(lock); + let _ = reaper.join(); + assert!(!crate::sys::process_alive(pid)); + assert_eq!( + status_of(&read_job(d.path(), &id).unwrap().unwrap()), + "canceled" + ); + assert!( + crate::registry::read(&id).is_none(), + "registry entry cleaned up" + ); + } + + /// A repository can commit `.agy-plugin/jobs/*.json`. A planted record + /// naming someone's pid and directory must not make cancel kill or + /// delete anything (independent review finding). + #[cfg(unix)] + #[test] + fn a_planted_record_cannot_make_cancel_kill_or_delete() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let victim = TempDir::new("agy-victim-").unwrap(); + std::fs::write(victim.path().join("precious.txt"), "keep me").unwrap(); + let (pid, reaper) = spawn_detached_sleep(); + std::fs::create_dir_all(d.path().join(".agy-plugin/jobs")).unwrap(); + std::fs::write( + record_path(d.path(), "agy-deadbeef"), + format!( + "{{\"id\":\"agy-deadbeef\",\"kind\":\"rescue\",\"status\":\"running\",\"pid\":{pid},\"createdAt\":\"9999\",\"meta\":{{\"stageDir\":\"{}\"}}}}", + victim.path().display() + ), + ) + .unwrap(); + assert!(matches!( + cancel_job(d.path(), "agy-deadbeef", Duration::from_millis(200)).unwrap(), + CancelResult::Canceled("not-started-here") + )); + assert!( + crate::sys::process_alive(pid), + "planted pid must not be signalled" + ); + assert_eq!( + std::fs::read_to_string(victim.path().join("precious.txt")).unwrap(), + "keep me" + ); + crate::sys::terminate_tree(pid, Duration::from_secs(2)); + let _ = reaper.join(); + } + + #[cfg(unix)] + #[test] + fn a_stale_registry_entry_never_signals_a_reused_pid() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("rescue", true)).unwrap(); + let id = id_of(&r).to_string(); + // An unrelated live process now owns the pid the dead worker had. + let (pid, reaper) = spawn_detached_sleep(); + update_job(d.path(), &id, |o| { + o.set("status", "running"); + o.set("pid", pid); + }) + .unwrap(); + crate::registry::update(&id, |e| { + e.pid = Some(pid); + e.group_leader = true; + }); + // Nobody holds the lock: the worker is dead. + let l = liveness(&read_job(d.path(), &id).unwrap().unwrap()); + assert_eq!(status_of(&l), "failed", "a dead worker is reported failed"); + assert!(matches!( + cancel_job(d.path(), &id, Duration::from_millis(200)).unwrap(), + CancelResult::Canceled("already-dead") + )); + assert!( + crate::sys::process_alive(pid), + "the reused pid must not be signalled" + ); + crate::sys::terminate_tree(pid, Duration::from_secs(2)); + let _ = reaper.join(); + + // wait_for_job persists the downgrade. + let r2 = create_job(d.path(), new_job("rescue", true)).unwrap(); + let id2 = id_of(&r2).to_string(); + update_job(d.path(), &id2, |o| o.set("status", "running")).unwrap(); + let _probe = crate::registry::hold(&id2); + drop(_probe); // lock file exists, nobody holds it + let w = wait_for_job( + d.path(), + &id2, + Duration::from_secs(2), + Duration::from_millis(10), + ) + .unwrap() + .unwrap(); + assert_eq!(status_of(&w), "failed"); + assert_eq!( + w.get("meta") + .and_then(|m| m.get("livenessDowngradedBy")) + .and_then(Value::as_str), + Some("waitForJob") + ); + } + + #[cfg(unix)] + #[test] + fn symlinked_state_dir_is_refused() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let elsewhere = TempDir::new("agy-elsewhere-").unwrap(); + std::os::unix::fs::symlink(elsewhere.path(), d.path().join(".agy-plugin")).unwrap(); + assert!(create_job(d.path(), new_job("review", false)).is_err()); + assert!( + std::fs::read_dir(elsewhere.path()) + .unwrap() + .next() + .is_none(), + "nothing written through the link" + ); + } + + #[test] + fn wait_returns_running_record_on_timeout_and_none_for_missing() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("review", true)).unwrap(); + let id = id_of(&r).to_string(); + let w = wait_for_job( + d.path(), + &id, + Duration::from_millis(50), + Duration::from_millis(10), + ) + .unwrap() + .unwrap(); + assert_eq!(status_of(&w), "pending"); + assert!( + wait_for_job( + d.path(), + "agy-00000000", + Duration::from_millis(10), + Duration::from_millis(5) + ) + .unwrap() + .is_none() + ); + } + + #[test] + fn concurrent_updates_are_not_lost() { + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("review", false)).unwrap(); + let id = id_of(&r).to_string(); + update_job(d.path(), &id, |o| o.set("counter", 0i64)).unwrap(); + let handles: Vec<_> = (0..8) + .map(|_| { + let root = d.path().to_path_buf(); + let id = id.clone(); + std::thread::spawn(move || { + for _ in 0..10 { + update_job(&root, &id, |o| { + let n = o.get("counter").and_then(Value::as_i64).unwrap_or(0); + o.set("counter", n + 1); + }) + .unwrap(); + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + let rec = read_job(d.path(), &id).unwrap().unwrap(); + assert_eq!(rec.get("counter").and_then(Value::as_i64), Some(80)); + } + + #[cfg(unix)] + #[test] + fn records_are_private() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("agy-jobs-test-").unwrap(); + let r = create_job(d.path(), new_job("review", false)).unwrap(); + let mode = std::fs::metadata(record_path(d.path(), id_of(&r))) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o600); + } +} diff --git a/src/json.rs b/src/json.rs new file mode 100644 index 0000000..02267e8 --- /dev/null +++ b/src/json.rs @@ -0,0 +1,1431 @@ +//! Minimal RFC 8259 JSON: a value tree, a strict parser and a serializer whose +//! output is byte-identical to JavaScript's `JSON.stringify`. +//! +//! Why byte-identical: job records under `.agy-plugin/jobs/` were written by +//! the old Node runtime with `JSON.stringify(record, null, 2)`. Old and new +//! binaries must be able to read and rewrite each other's files, and diffs of +//! those files should stay quiet across the migration. +//! +//! Why strict and depth-limited: the parser also reads agy's +//! `--output-format json` result, which is output of an external program and +//! therefore treated as hostile. Every failure is a `ParseError`, never a +//! panic, and nesting is capped so a `[[[[...` bomb cannot overflow the stack. + +use std::collections::HashMap; +use std::fmt; + +/// Maximum nesting of arrays/objects accepted by `parse`. Real job records +/// and agy results nest 2-3 levels; the cap only exists to bound recursion. +const MAX_DEPTH: usize = 128; + +/// Objects at or below this size look up duplicate keys by linear scan; above +/// it the parser builds a hash index so a hostile object with many keys costs +/// O(n) instead of O(n^2). +const LINEAR_SCAN_LIMIT: usize = 16; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Value { + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + Object(Map), +} + +/// Insertion-ordered object. Order matters because JS preserves insertion +/// order for string keys and the job files must serialize in the same order. +#[derive(Debug, Clone, PartialEq, Default)] +pub(crate) struct Map(Vec<(String, Value)>); + +impl Map { + pub(crate) fn new() -> Self { + Map(Vec::new()) + } + + pub(crate) fn get(&self, key: &str) -> Option<&Value> { + self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v) + } + + pub(crate) fn get_mut(&mut self, key: &str) -> Option<&mut Value> { + self.0.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v) + } + + /// Replaces an existing key in place (keeping its position, as assigning + /// to an existing property does in JS), otherwise appends. + pub(crate) fn set(&mut self, key: impl Into, value: impl Into) { + let key = key.into(); + let value = value.into(); + match self.get_mut(&key) { + Some(slot) => *slot = value, + None => self.0.push((key, value)), + } + } + + /// Removes a key, keeping the relative order of the remaining entries. + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn remove(&mut self, key: &str) -> Option { + let idx = self.0.iter().position(|(k, _)| k == key)?; + Some(self.0.remove(idx).1) + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.0.iter().map(|(k, v)| (k.as_str(), v)) + } + + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn len(&self) -> usize { + self.0.len() + } + + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } + + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn contains_key(&self, key: &str) -> bool { + self.get(key).is_some() + } +} + +impl Value { + pub(crate) fn as_str(&self) -> Option<&str> { + match self { + Value::String(s) => Some(s), + _ => None, + } + } + + pub(crate) fn as_f64(&self) -> Option { + match self { + Value::Number(n) => Some(*n), + _ => None, + } + } + + /// Only integral numbers that fit in i64 exactly; 1.5 or 1e19 give None + /// rather than a silently truncated/saturated value. + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn as_i64(&self) -> Option { + let n = self.as_f64()?; + // -2^63 is exactly representable; 2^63 is the first value out of range. + if n.is_finite() + && n.fract() == 0.0 + && (-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&n) + { + Some(n as i64) + } else { + None + } + } + + pub(crate) fn as_u64(&self) -> Option { + let n = self.as_f64()?; + if n.is_finite() && n.fract() == 0.0 && (0.0..18_446_744_073_709_551_616.0).contains(&n) { + Some(n as u64) + } else { + None + } + } + + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn as_bool(&self) -> Option { + match self { + Value::Bool(b) => Some(*b), + _ => None, + } + } + + pub(crate) fn as_array(&self) -> Option<&[Value]> { + match self { + Value::Array(a) => Some(a), + _ => None, + } + } + + #[cfg_attr(not(test), allow(dead_code))] // general JSON API; exercised by tests + pub(crate) fn as_array_mut(&mut self) -> Option<&mut Vec> { + match self { + Value::Array(a) => Some(a), + _ => None, + } + } + + pub(crate) fn as_object(&self) -> Option<&Map> { + match self { + Value::Object(m) => Some(m), + _ => None, + } + } + + pub(crate) fn as_object_mut(&mut self) -> Option<&mut Map> { + match self { + Value::Object(m) => Some(m), + _ => None, + } + } + + pub(crate) fn is_null(&self) -> bool { + matches!(self, Value::Null) + } + + /// Object member lookup; None for non-objects (like optional chaining). + pub(crate) fn get(&self, key: &str) -> Option<&Value> { + self.as_object()?.get(key) + } +} + +impl From<&str> for Value { + fn from(s: &str) -> Self { + Value::String(s.to_owned()) + } +} + +impl From for Value { + fn from(s: String) -> Self { + Value::String(s) + } +} + +impl From for Value { + fn from(b: bool) -> Self { + Value::Bool(b) + } +} + +// Integers beyond 2^53 lose precision, exactly as they would in JS. +impl From for Value { + fn from(n: i64) -> Self { + Value::Number(n as f64) + } +} + +impl From for Value { + fn from(n: u64) -> Self { + Value::Number(n as f64) + } +} + +impl From for Value { + fn from(n: i32) -> Self { + Value::Number(f64::from(n)) + } +} + +impl From for Value { + fn from(n: u32) -> Self { + Value::Number(f64::from(n)) + } +} + +impl From for Value { + fn from(n: usize) -> Self { + Value::Number(n as f64) + } +} + +impl From for Value { + fn from(n: f64) -> Self { + Value::Number(n) + } +} + +impl> From> for Value { + fn from(o: Option) -> Self { + o.map_or(Value::Null, Into::into) + } +} + +impl From> for Value { + fn from(a: Vec) -> Self { + Value::Array(a) + } +} + +impl From for Value { + fn from(m: Map) -> Self { + Value::Object(m) + } +} + +// --------------------------------------------------------------------------- +// Parser +// --------------------------------------------------------------------------- + +/// `offset` is a byte offset into the text given to `parse` (a leading BOM +/// counts as its 3 bytes), so it can be used to slice the original input. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ParseError { + pub(crate) offset: usize, + pub(crate) message: String, +} + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "invalid JSON at byte {}: {}", self.offset, self.message) + } +} + +impl std::error::Error for ParseError {} + +/// Parses one JSON document (RFC 8259, plus an optional leading UTF-8 BOM). +/// +/// Lossy on purpose in one place: a lone or mismatched UTF-16 surrogate in a +/// `\uXXXX` escape becomes U+FFFD, because a Rust `String` cannot hold it. +/// JS would keep the lone surrogate and `JSON.stringify` would re-escape it, +/// so such a string does not round-trip byte-for-byte; nothing we persist +/// contains lone surrogates. Numbers that overflow f64 (e.g. `1e400`) become +/// infinity, as in JS, and therefore serialize back as `null`. +pub(crate) fn parse(text: &str) -> Result { + // Windows editors (Notepad and friends) prefix saved files with a BOM. + let start = if text.starts_with('\u{FEFF}') { 3 } else { 0 }; + let mut p = Parser { + text, + bytes: text.as_bytes(), + pos: start, + }; + p.skip_ws(); + if p.pos >= p.bytes.len() { + return Err(p.err("empty input")); + } + let value = p.parse_value(0)?; + p.skip_ws(); + if p.pos < p.bytes.len() { + return Err(p.err("unexpected trailing characters after JSON value")); + } + Ok(value) +} + +struct Parser<'a> { + text: &'a str, + bytes: &'a [u8], + pos: usize, +} + +impl Parser<'_> { + fn err(&self, message: &str) -> ParseError { + self.err_at(self.pos, message) + } + + fn err_at(&self, offset: usize, message: &str) -> ParseError { + ParseError { + offset, + message: message.to_owned(), + } + } + + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + fn skip_ws(&mut self) { + // RFC 8259 whitespace only: no form feed, vertical tab, NBSP or BOM. + while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) { + self.pos += 1; + } + } + + fn expect_literal(&mut self, word: &str, value: Value) -> Result { + let end = self.pos.saturating_add(word.len()); + if self.bytes.get(self.pos..end) == Some(word.as_bytes()) { + self.pos = end; + Ok(value) + } else { + Err(self.err(&format!("invalid literal, expected '{word}'"))) + } + } + + fn parse_value(&mut self, depth: usize) -> Result { + match self.peek() { + None => Err(self.err("unexpected end of input, expected a value")), + Some(b'{') => self.parse_object(depth + 1), + Some(b'[') => self.parse_array(depth + 1), + Some(b'"') => self.parse_string().map(Value::String), + Some(b't') => self.expect_literal("true", Value::Bool(true)), + Some(b'f') => self.expect_literal("false", Value::Bool(false)), + Some(b'n') => self.expect_literal("null", Value::Null), + Some(b'-' | b'0'..=b'9') => self.parse_number(), + Some(_) => Err(self.err("unexpected character, expected a value")), + } + } + + fn check_depth(&self, depth: usize) -> Result<(), ParseError> { + if depth > MAX_DEPTH { + Err(self.err(&format!("nesting deeper than {MAX_DEPTH} levels"))) + } else { + Ok(()) + } + } + + fn parse_array(&mut self, depth: usize) -> Result { + self.check_depth(depth)?; + self.pos += 1; // '[' + let mut items = Vec::new(); + self.skip_ws(); + if self.peek() == Some(b']') { + self.pos += 1; + return Ok(Value::Array(items)); + } + loop { + self.skip_ws(); + items.push(self.parse_value(depth)?); + self.skip_ws(); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b']') => { + self.pos += 1; + return Ok(Value::Array(items)); + } + None => return Err(self.err("unterminated array")), + Some(_) => return Err(self.err("expected ',' or ']' in array")), + } + } + } + + fn parse_object(&mut self, depth: usize) -> Result { + self.check_depth(depth)?; + self.pos += 1; // '{' + let mut entries: Vec<(String, Value)> = Vec::new(); + let mut index: HashMap = HashMap::new(); + self.skip_ws(); + if self.peek() == Some(b'}') { + self.pos += 1; + return Ok(Value::Object(Map(entries))); + } + loop { + self.skip_ws(); + match self.peek() { + Some(b'"') => {} + None => return Err(self.err("unterminated object")), + Some(_) => return Err(self.err("expected string key in object")), + } + let key = self.parse_string()?; + self.skip_ws(); + match self.peek() { + Some(b':') => self.pos += 1, + None => return Err(self.err("unterminated object")), + Some(_) => return Err(self.err("expected ':' after object key")), + } + self.skip_ws(); + let value = self.parse_value(depth)?; + + // Duplicate keys: last value wins, first position is kept. That is + // what JSON.parse does (a repeated assignment to the same property). + let existing = if entries.len() <= LINEAR_SCAN_LIMIT { + entries.iter().position(|(k, _)| *k == key) + } else { + if index.is_empty() { + index = entries + .iter() + .enumerate() + .map(|(i, (k, _))| (k.clone(), i)) + .collect(); + } + index.get(&key).copied() + }; + match existing.and_then(|i| entries.get_mut(i)) { + Some(slot) => slot.1 = value, + None => { + if !index.is_empty() { + index.insert(key.clone(), entries.len()); + } + entries.push((key, value)); + } + } + + self.skip_ws(); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b'}') => { + self.pos += 1; + return Ok(Value::Object(Map(entries))); + } + None => return Err(self.err("unterminated object")), + Some(_) => return Err(self.err("expected ',' or '}' in object")), + } + } + } + + fn eat_digits(&mut self) -> usize { + let start = self.pos; + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + self.pos - start + } + + fn parse_number(&mut self) -> Result { + let start = self.pos; + if self.peek() == Some(b'-') { + self.pos += 1; + } + match self.peek() { + Some(b'0') => { + self.pos += 1; + if matches!(self.peek(), Some(b'0'..=b'9')) { + return Err(self.err("leading zeros are not allowed in numbers")); + } + } + Some(b'1'..=b'9') => { + self.eat_digits(); + } + _ => return Err(self.err("invalid number, expected a digit")), + } + if self.peek() == Some(b'.') { + self.pos += 1; + if self.eat_digits() == 0 { + return Err(self.err("invalid number, expected a digit after '.'")); + } + } + if matches!(self.peek(), Some(b'e' | b'E')) { + self.pos += 1; + if matches!(self.peek(), Some(b'+' | b'-')) { + self.pos += 1; + } + if self.eat_digits() == 0 { + return Err(self.err("invalid number, expected a digit in exponent")); + } + } + // The grammar above is a subset of what Rust's f64 parser accepts, and + // Rust's parser is correctly rounded, so 2^53-range integers are exact. + self.text + .get(start..self.pos) + .and_then(|s| s.parse::().ok()) + .map(Value::Number) + .ok_or_else(|| self.err_at(start, "invalid number")) + } + + fn hex4(&self, at: usize) -> Option { + let end = at.checked_add(4)?; + let digits = self.bytes.get(at..end)?; + let mut code = 0u32; + for &d in digits { + code = code * 16 + char::from(d).to_digit(16)?; + } + Some(code) + } + + fn parse_string(&mut self) -> Result { + let open = self.pos; + self.pos += 1; // '"' + let mut out = String::new(); + loop { + let run_start = self.pos; + while let Some(b) = self.peek() { + if b == b'"' || b == b'\\' || b < 0x20 { + break; + } + self.pos += 1; + } + // The run stops only at ASCII bytes or end of input, so both ends + // are char boundaries; `get` keeps this panic-free regardless. + match self.text.get(run_start..self.pos) { + Some(run) => out.push_str(run), + None => return Err(self.err_at(run_start, "invalid UTF-8 boundary in string")), + } + match self.peek() { + None => return Err(self.err_at(open, "unterminated string")), + Some(b'"') => { + self.pos += 1; + return Ok(out); + } + Some(b'\\') => self.parse_escape(&mut out)?, + Some(_) => return Err(self.err("unescaped control character in string")), + } + } + } + + /// Called with `pos` on the backslash. + fn parse_escape(&mut self, out: &mut String) -> Result<(), ParseError> { + let esc = self.bytes.get(self.pos + 1).copied(); + let simple = match esc { + Some(b'"') => Some('"'), + Some(b'\\') => Some('\\'), + Some(b'/') => Some('/'), + Some(b'b') => Some('\u{8}'), + Some(b'f') => Some('\u{c}'), + Some(b'n') => Some('\n'), + Some(b'r') => Some('\r'), + Some(b't') => Some('\t'), + Some(b'u') => None, + None => return Err(self.err("unterminated escape sequence")), + Some(_) => return Err(self.err("invalid escape sequence")), + }; + if let Some(c) = simple { + out.push(c); + self.pos += 2; + return Ok(()); + } + let Some(code) = self.hex4(self.pos + 2) else { + return Err(self.err("invalid \\u escape, expected 4 hex digits")); + }; + self.pos += 6; + let ch = match code { + 0xD800..=0xDBFF => { + // A high surrogate only means something when a low one follows + // as the very next escape. Otherwise it is lone: U+FFFD, and + // whatever follows is parsed on its own (and may still error). + let low = if self.bytes.get(self.pos..self.pos + 2) == Some(b"\\u") { + self.hex4(self.pos + 2) + .filter(|lo| (0xDC00..=0xDFFF).contains(lo)) + } else { + None + }; + match low { + Some(lo) => { + self.pos += 6; + char::from_u32(0x10000 + ((code - 0xD800) << 10) + (lo - 0xDC00)) + .unwrap_or('\u{FFFD}') + } + None => '\u{FFFD}', + } + } + 0xDC00..=0xDFFF => '\u{FFFD}', + _ => char::from_u32(code).unwrap_or('\u{FFFD}'), + }; + out.push(ch); + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Serializer +// --------------------------------------------------------------------------- + +/// Same bytes as `JSON.stringify(v)`. +pub(crate) fn to_string_compact(v: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, v, false, 0); + out +} + +/// Same bytes as `JSON.stringify(v, null, 2)`; no trailing newline (the old +/// code appended "\n" itself when writing files, and so must callers). +pub(crate) fn to_string_pretty(v: &Value) -> String { + let mut out = String::new(); + write_value(&mut out, v, true, 0); + out +} + +fn newline_indent(out: &mut String, level: usize) { + out.push('\n'); + for _ in 0..level { + out.push_str(" "); + } +} + +fn write_value(out: &mut String, v: &Value, pretty: bool, level: usize) { + match v { + Value::Null => out.push_str("null"), + Value::Bool(true) => out.push_str("true"), + Value::Bool(false) => out.push_str("false"), + Value::Number(n) => write_number(out, *n), + Value::String(s) => write_string(out, s), + Value::Array(items) => { + if items.is_empty() { + out.push_str("[]"); + return; + } + out.push('['); + for (i, item) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + if pretty { + newline_indent(out, level + 1); + } + write_value(out, item, pretty, level + 1); + } + if pretty { + newline_indent(out, level); + } + out.push(']'); + } + Value::Object(map) => { + if map.is_empty() { + out.push_str("{}"); + return; + } + out.push('{'); + for (i, (key, item)) in map.iter().enumerate() { + if i > 0 { + out.push(','); + } + if pretty { + newline_indent(out, level + 1); + } + write_string(out, key); + out.push(':'); + if pretty { + out.push(' '); + } + write_value(out, item, pretty, level + 1); + } + if pretty { + newline_indent(out, level); + } + out.push('}'); + } + } +} + +fn write_string(out: &mut String, s: &str) { + out.push('"'); + for ch in s.chars() { + match ch { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\u{8}' => out.push_str("\\b"), + '\u{c}' => out.push_str("\\f"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + // JS uses lowercase hex here. U+2028/U+2029 and DEL stay raw, as + // JSON.stringify leaves them. + c if u32::from(c) < 0x20 => { + out.push_str(&format!("\\u{:04x}", u32::from(c))); + } + c => out.push(c), + } + } + out.push('"'); +} + +/// Splits Rust's `{:e}` output ("1.2345e21") into ("12345", 21). +fn split_sci(sci: &str) -> (String, i64) { + let (mantissa, exp) = sci.split_once('e').unwrap_or((sci, "0")); + let digits = mantissa.chars().filter(|c| *c != '.').collect(); + (digits, exp.parse().unwrap_or(0)) +} + +/// Rust's shortest-digits algorithm and V8's agree except when the exact +/// binary value lies precisely halfway between the two shortest decimal +/// candidates (e.g. 801130354720945.25 -> "...945.2" or "...945.3"). Rust +/// rounds such ties up; V8 (bignum-dtoa) rounds them to the even digit. Found +/// by diffing 200k random doubles against node: ~0.04% differed, all ties. +/// So detect the exact tie from the full decimal expansion and pick the even +/// candidate, keeping it only if it still round-trips to `x`. +fn js_shortest_digits(x: f64) -> (String, i64) { + let (digits, exp) = split_sci(&format!("{x:e}")); + // Every finite f64 has an exact decimal expansion of at most 767 + // significant digits, so 1100 digits after the point is exact. + let (exact, exact_exp) = split_sci(&format!("{x:.1100e}")); + let k = digits.len(); + if exact_exp != exp { + return (digits, exp); + } + let (Some(lower), Some(tail)) = (exact.get(..k), exact.get(k..)) else { + return (digits, exp); + }; + let is_tie = tail.starts_with('5') && tail.bytes().skip(1).all(|b| b == b'0'); + if !is_tie { + return (digits, exp); + } + let lower_is_even = lower + .bytes() + .last() + .is_some_and(|b| b.wrapping_sub(b'0') % 2 == 0); + let even = if lower_is_even { + Some(lower.to_owned()) + } else { + increment_digits(lower) + }; + let Some(even) = even else { + return (digits, exp); + }; + if even == digits || even.is_empty() { + return (digits, exp); + } + let (first, rest) = even.split_at(1); + if format!("{first}.{rest}0e{exp}").parse::() == Ok(x) { + (even, exp) + } else { + (digits, exp) + } +} + +/// Decimal digit string + 1, or None when it would carry into a new digit +/// (that changes the exponent; the caller then keeps Rust's answer). +fn increment_digits(digits: &str) -> Option { + let mut bytes = digits.as_bytes().to_vec(); + for b in bytes.iter_mut().rev() { + if *b == b'9' { + *b = b'0'; + } else { + *b += 1; + return String::from_utf8(bytes).ok(); + } + } + None +} + +/// ECMAScript Number::toString(10), which JSON.stringify uses for finite +/// numbers: shortest round-trip digits (see `js_shortest_digits`) laid out by +/// the spec's fixed/exponential rules. +fn write_number(out: &mut String, x: f64) { + if !x.is_finite() { + // JSON has no NaN/Infinity; JSON.stringify writes null. + out.push_str("null"); + return; + } + if x == 0.0 { + // Covers -0, which JS prints as "0". + out.push('0'); + return; + } + let (digits, exp) = js_shortest_digits(x.abs()); + // Value = 0.DIGITS * 10^n, in the spec's terms: k digits, exponent n. + let k = digits.len() as i64; + let n = exp + 1; + + if x < 0.0 { + out.push('-'); + } + if k <= n && n <= 21 { + out.push_str(&digits); + for _ in 0..(n - k) { + out.push('0'); + } + } else if 0 < n && n <= 21 { + let (int_part, frac_part) = digits.split_at(n as usize); + out.push_str(int_part); + out.push('.'); + out.push_str(frac_part); + } else if -6 < n && n <= 0 { + out.push_str("0."); + for _ in 0..(-n) { + out.push('0'); + } + out.push_str(&digits); + } else { + let (first, rest) = digits.split_at(1.min(digits.len())); + out.push_str(first); + if !rest.is_empty() { + out.push('.'); + out.push_str(rest); + } + let e = n - 1; + out.push('e'); + out.push(if e >= 0 { '+' } else { '-' }); + out.push_str(&e.abs().to_string()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const JOB_RECORD: &str = r#"{ + "id": "agy-2b067725", + "kind": "review", + "task": "review: Be brief. List the bugs in calc.js.", + "model": null, + "workspaceRoot": "/private/var/folders/jg/x/T/tmp.SN7LQWIwMi/demo", + "createdAt": "2026-05-31T15:02:38.473Z", + "startedAt": "2026-05-31T15:02:38.485Z", + "completedAt": "2026-05-31T15:02:46.851Z", + "status": "completed", + "exitCode": 0, + "pid": null, + "logFile": ".agy-plugin/logs/agy-2b067725.log", + "args": [], + "background": false, + "meta": { + "prompt": "Review the following diff.\n— dash \"quoted\"", + "agyBin": "agy", + "executionRoot": null, + "stageDir": "/tmp/agy-review-BTZ7RN" + }, + "lastUpdatedAt": "2026-05-31T15:02:46.852Z" +}"#; + + const AGY_RESULT: &str = r#"{"conversation_id":"0795225f-aaaa","status":"SUCCESS","response":"OK\n","duration_seconds":3.000251,"num_turns":1,"usage":{"input_tokens":10137,"output_tokens":1},"denied_actions":[{"action":"write_file","display_name":"Edit"}]}"#; + + fn num(x: f64) -> String { + to_string_compact(&Value::Number(x)) + } + + fn s(text: &str) -> String { + match parse(text) { + Ok(Value::String(s)) => s, + other => panic!("expected string from {text:?}, got {other:?}"), + } + } + + #[test] + fn job_record_round_trips_byte_for_byte() { + let v = parse(JOB_RECORD).unwrap(); + assert_eq!(to_string_pretty(&v), JOB_RECORD); + // The file on disk has a trailing newline appended by the writer. + let with_nl = format!("{JOB_RECORD}\n"); + assert_eq!(parse(&with_nl).unwrap(), v); + + assert_eq!(v.get("id").and_then(Value::as_str), Some("agy-2b067725")); + assert!(v.get("model").unwrap().is_null()); + assert_eq!(v.get("exitCode").and_then(Value::as_i64), Some(0)); + assert_eq!(v.get("background").and_then(Value::as_bool), Some(false)); + assert_eq!( + v.get("args").and_then(Value::as_array).map(<[Value]>::len), + Some(0) + ); + let prompt = v + .get("meta") + .and_then(|m| m.get("prompt")) + .and_then(Value::as_str); + assert_eq!( + prompt, + Some("Review the following diff.\n\u{2014} dash \"quoted\"") + ); + let keys: Vec<&str> = v.as_object().unwrap().iter().map(|(k, _)| k).collect(); + assert_eq!(keys.first(), Some(&"id")); + assert_eq!(keys.last(), Some(&"lastUpdatedAt")); + assert_eq!(keys.len(), 16); + } + + #[test] + fn agy_result_parses_and_round_trips_compact() { + let v = parse(AGY_RESULT).unwrap(); + assert_eq!(v.get("status").and_then(Value::as_str), Some("SUCCESS")); + assert_eq!(v.get("response").and_then(Value::as_str), Some("OK\n")); + assert_eq!( + v.get("duration_seconds").and_then(Value::as_f64), + Some(3.000251) + ); + assert_eq!(v.get("duration_seconds").and_then(Value::as_i64), None); + let usage = v.get("usage").unwrap(); + assert_eq!( + usage.get("input_tokens").and_then(Value::as_u64), + Some(10137) + ); + let denied = v.get("denied_actions").and_then(Value::as_array).unwrap(); + assert_eq!( + denied[0].get("action").and_then(Value::as_str), + Some("write_file") + ); + assert_eq!(to_string_compact(&v), AGY_RESULT); + } + + #[test] + fn bom_is_skipped_only_at_start() { + assert_eq!( + parse("\u{FEFF}{\"a\":1}").unwrap().get("a"), + Some(&Value::Number(1.0)) + ); + assert_eq!(parse("\u{FEFF} [ ]\n").unwrap(), Value::Array(vec![])); + assert!(parse("\u{FEFF}").is_err()); + assert!(parse("\u{FEFF}\u{FEFF}1").is_err()); + assert!(parse(" \u{FEFF}1").is_err()); + assert!(parse("[\u{FEFF}1]").is_err()); + // Offsets are into the original text, BOM included. + assert_eq!(parse("\u{FEFF}x").unwrap_err().offset, 3); + } + + #[test] + fn surrogate_pairs_and_lone_surrogates() { + assert_eq!(s(r#""\ud83d\ude00""#), "\u{1F600}"); + assert_eq!(s(r#""\uD83D\uDE00""#), "\u{1F600}"); + assert_eq!(s("\"\u{1F600}\""), "\u{1F600}"); + assert_eq!(s(r#""\ud800x""#), "\u{FFFD}x"); + assert_eq!(s(r#""\udc00""#), "\u{FFFD}"); + assert_eq!(s(r#""\ud800""#), "\u{FFFD}"); + assert_eq!(s(r#""\ud800\ud83d\ude00""#), "\u{FFFD}\u{1F600}"); + assert_eq!(s(r#""\ude00\ud83d""#), "\u{FFFD}\u{FFFD}"); + assert_eq!(s(r#""\ud800\n""#), "\u{FFFD}\n"); + assert_eq!(s(r#""\ud800\u0041""#), "\u{FFFD}A"); + // A malformed escape after a high surrogate is still an error. + assert!(parse(r#""\ud800\u12""#).is_err()); + assert!(parse(r#""\ud800\uZZZZ""#).is_err()); + // Emoji serializes raw, like JS. + assert_eq!( + to_string_compact(&Value::from("\u{1F600}")), + "\"\u{1F600}\"" + ); + } + + #[test] + fn escapes_parse() { + assert_eq!(s(r#""\"\\\/\b\f\n\r\t""#), "\"\\/\u{8}\u{c}\n\r\t"); + assert_eq!(s(r#""\u0041\u00e9\u00E9\u0000""#), "A\u{e9}\u{e9}\u{0}"); + assert_eq!(s(r#""a\u2028b""#), "a\u{2028}b"); + assert_eq!(s("\"\u{7f}\""), "\u{7f}"); + for bad in [ + r#""\x""#, + r#""\U0041""#, + r#""\u004""#, + r#""\u00g0""#, + r#""\'""#, + "\"\\", + "\"\\u", + ] { + assert!(parse(bad).is_err(), "should reject {bad:?}"); + } + } + + #[test] + fn escapes_serialize_like_js() { + // Expected from node: JSON.stringify("x\u0001\u001f\u007f\u2028\u2029\b\f\n\r\t\"\\/é😀") + let input = "x\u{1}\u{1f}\u{7f}\u{2028}\u{2029}\u{8}\u{c}\n\r\t\"\\/\u{e9}\u{1F600}"; + let expected = + "\"x\\u0001\\u001f\u{7f}\u{2028}\u{2029}\\b\\f\\n\\r\\t\\\"\\\\/\u{e9}\u{1F600}\""; + assert_eq!(to_string_compact(&Value::from(input)), expected); + assert_eq!( + to_string_compact(&Value::from("\u{0}\u{b}\u{1b}")), + "\"\\u0000\\u000b\\u001b\"" + ); + assert_eq!(s(expected), input); + } + + #[test] + fn rejects_malformed_input() { + let cases = [ + "", + " ", + "\n\t\r ", + "01", + "-01", + "00", + "+1", + ".5", + "1.", + "1.e5", + "-", + "--1", + "1e", + "1e+", + "1E-", + "NaN", + "Infinity", + "-Infinity", + "nan", + "0x10", + "1_000", + "tru", + "true1", + "nul", + "nulll", + "False", + "[1,]", + "[,1]", + "[1 2]", + "[", + "]", + "{", + "}", + "{\"a\"}", + "{\"a\":}", + "{\"a\" 1}", + "{a:1}", + "{'a':1}", + "{\"a\":1,}", + "{,}", + "{\"a\":1 \"b\":2}", + "'x'", + "\"abc", + "\"a\nb\"", + "\"a\tb\"", + "\"\u{1}\"", + "\"\u{1f}\"", + "1 2", + "{} {}", + "[]x", + "null,", + "\u{b}1", + "\u{c}1", + "\u{a0}1", + "1\u{a0}", + "[1]\u{0}", + "/*c*/1", + "1//c", + "[\"a\",\"b\"", + "{\"a\":[}", + ]; + for c in cases { + assert!(parse(c).is_err(), "should reject {c:?}"); + } + } + + #[test] + fn error_offsets_and_messages() { + let e = parse("[1,]").unwrap_err(); + assert_eq!(e.offset, 3); + assert_eq!(parse("01").unwrap_err().offset, 1); + assert!(parse("01").unwrap_err().message.contains("leading zero")); + assert_eq!(parse("\"a\u{1}\"").unwrap_err().offset, 2); + assert_eq!(parse(" \"abc").unwrap_err().offset, 2); + assert_eq!(parse("1 2").unwrap_err().offset, 2); + assert!(parse("").unwrap_err().message.contains("empty")); + assert!(parse(" ").unwrap_err().message.contains("empty")); + let shown = parse("[1,]").unwrap_err().to_string(); + assert!(shown.contains("byte 3"), "{shown}"); + } + + #[test] + fn whitespace_accepted() { + let v = parse(" \t\r\n{ \"a\" \n:\t[ 1 , 2 ] \r} \n").unwrap(); + assert_eq!(to_string_compact(&v), r#"{"a":[1,2]}"#); + } + + #[test] + fn depth_limit() { + let ok = format!("{}{}", "[".repeat(MAX_DEPTH), "]".repeat(MAX_DEPTH)); + assert!(parse(&ok).is_ok()); + let too_deep = format!("{}{}", "[".repeat(MAX_DEPTH + 1), "]".repeat(MAX_DEPTH + 1)); + assert!(parse(&too_deep).unwrap_err().message.contains("nesting")); + + let obj_ok = format!("{}1{}", "{\"a\":".repeat(MAX_DEPTH), "}".repeat(MAX_DEPTH)); + assert!(parse(&obj_ok).is_ok()); + let obj_deep = format!( + "{}1{}", + "{\"a\":".repeat(MAX_DEPTH + 1), + "}".repeat(MAX_DEPTH + 1) + ); + assert!(parse(&obj_deep).is_err()); + + // A bomb far past the limit must error, not overflow the stack. + assert!(parse(&"[".repeat(1_000_000)).is_err()); + assert!(parse(&"{\"a\":[".repeat(200_000)).is_err()); + } + + #[test] + fn duplicate_keys_last_wins_first_position() { + let v = parse(r#"{"a":1,"b":2,"a":3}"#).unwrap(); + assert_eq!(to_string_compact(&v), r#"{"a":3,"b":2}"#); + + // Large object: exercises the hash-index path. + let mut text = String::from("{"); + for i in 0..40 { + text.push_str(&format!("\"k{i}\":{i},")); + } + text.push_str("\"k3\":\"x\",\"k39\":true,\"new\":null,\"k0\":[]}"); + let v = parse(&text).unwrap(); + let m = v.as_object().unwrap(); + assert_eq!(m.len(), 41); + let keys: Vec<&str> = m.iter().map(|(k, _)| k).collect(); + assert_eq!(keys[0], "k0"); + assert_eq!(keys[3], "k3"); + assert_eq!(keys[40], "new"); + assert_eq!(m.get("k0"), Some(&Value::Array(vec![]))); + assert_eq!(m.get("k3"), Some(&Value::from("x"))); + assert_eq!(m.get("k39"), Some(&Value::Bool(true))); + assert_eq!(m.get("k20"), Some(&Value::Number(20.0))); + } + + #[test] + fn pretty_matches_js() { + // node -e 'console.log(JSON.stringify({a:[1,{b:[]},{}],c:"x",d:null,e:true},null,2))' + let v = parse(r#"{"a":[1,{"b":[]},{}],"c":"x","d":null,"e":true}"#).unwrap(); + let expected = "{\n \"a\": [\n 1,\n {\n \"b\": []\n },\n {}\n ],\n \"c\": \"x\",\n \"d\": null,\n \"e\": true\n}"; + assert_eq!(to_string_pretty(&v), expected); + + // node: JSON.stringify([[],[[]],{"":{}}],null,2) + let v = parse(r#"[[],[[]],{"":{}}]"#).unwrap(); + let expected = "[\n [],\n [\n []\n ],\n {\n \"\": {}\n }\n]"; + assert_eq!(to_string_pretty(&v), expected); + + assert_eq!(to_string_pretty(&Value::Array(vec![])), "[]"); + assert_eq!(to_string_pretty(&Value::Object(Map::new())), "{}"); + assert_eq!(to_string_pretty(&Value::from("a\nb")), "\"a\\nb\""); + assert_eq!(to_string_pretty(&Value::Null), "null"); + } + + #[test] + fn compact_matches_js() { + let v = parse( + r#" { "a" : [ 1 , { "b" : [ ] } , { } ] , "c" : "x" , "d" : null , "e" : true } "#, + ) + .unwrap(); + assert_eq!( + to_string_compact(&v), + r#"{"a":[1,{"b":[]},{}],"c":"x","d":null,"e":true}"# + ); + assert_eq!(to_string_compact(&Value::Bool(false)), "false"); + } + + #[test] + fn numbers_serialize_like_js() { + // Expected strings produced by node's JSON.stringify. + let cases: &[(f64, &str)] = &[ + (0.0, "0"), + (-0.0, "0"), + (1e21, "1e+21"), + (1e20, "100000000000000000000"), + (123456789012345680000.0, "123456789012345680000"), + (9007199254740992.0, "9007199254740992"), + (9007199254740994.0, "9007199254740994"), + (0.1, "0.1"), + (1e-7, "1e-7"), + (1e-6, "0.000001"), + (0.000001234, "0.000001234"), + (-1.5e300, "-1.5e+300"), + (1.5, "1.5"), + (-1.0, "-1"), + (42.0, "42"), + (5e-324, "5e-324"), + (f64::MAX, "1.7976931348623157e+308"), + (123.456, "123.456"), + (1e100, "1e+100"), + (0.1 + 0.2, "0.30000000000000004"), + (-1e-7, "-1e-7"), + (1.2345e21, "1.2345e+21"), + (100.0, "100"), + (1e-10, "1e-10"), + (18446744073709551616.0, "18446744073709552000"), + (-9223372036854775808.0, "-9223372036854776000"), + (3.000251, "3.000251"), + (f64::NAN, "null"), + (f64::INFINITY, "null"), + (f64::NEG_INFINITY, "null"), + ]; + for &(x, want) in cases { + assert_eq!(num(x), want, "for {x:?}"); + } + } + + #[test] + fn number_ties_round_half_even_like_v8() { + // Exact binary values halfway between two shortest decimals. Rust's + // `{:e}` rounds these up; node prints the even digit. Expected + // strings come from node's JSON.stringify. + let cases: &[(u64, &str)] = &[ + (0x4306_c4fd_91b2_058a, "801130354720945.2"), + (0x4289_44ae_34f4_8d40, "3472846397073.6562"), + (0xc303_e1b7_152e_0932, "-699525126013222.2"), + (0x424e_5059_4f9a_5200, "260394098484.64062"), + ]; + for &(bits, want) in cases { + assert_eq!(num(f64::from_bits(bits)), want, "for bits {bits:x}"); + } + // Written as sums because the exact literal trips clippy's + // excessive_precision; at this magnitude ulp is 0.125, so both exact. + let base = 801_130_354_720_945.0_f64; + assert_eq!(num(base + 0.75), "801130354720945.8"); + assert_eq!(num(base + 0.25), "801130354720945.2"); + assert_eq!(num(0.5), "0.5"); + assert_eq!(num(2.5), "2.5"); + assert_eq!(num(1e23), "1e+23"); + assert_eq!(num(9.5e-7), "9.5e-7"); + assert_eq!(increment_digits("129"), Some("130".to_owned())); + assert_eq!(increment_digits("99"), None); + } + + #[test] + fn numbers_parse() { + let n = |t: &str| parse(t).unwrap().as_f64().unwrap(); + assert_eq!(n("0"), 0.0); + assert!(n("-0").is_sign_negative()); + assert_eq!(num(n("-0")), "0"); + assert_eq!(n("1E5"), 1e5); + assert_eq!(n("1e+2"), 100.0); + assert_eq!(n("1.5e-3"), 1.5e-3); + assert_eq!(n("-1.5e300"), -1.5e300); + assert_eq!(n("9007199254740992"), 9007199254740992.0); + assert_eq!(parse("9007199254740992").unwrap().as_i64(), Some(1 << 53)); + assert_eq!(num(n("9007199254740992")), "9007199254740992"); + // 2^53 + 1 rounds to even, as in JS. + assert_eq!(n("9007199254740993"), 9007199254740992.0); + assert_eq!(n("0.1"), 0.1); + assert!(n("1e400").is_infinite()); + assert_eq!(n("1e-400"), 0.0); + assert_eq!(n(&format!("1{}", "0".repeat(400))), f64::INFINITY); + } + + #[test] + fn integers_round_trip_up_to_2_pow_53() { + for i in [ + 0i64, + 1, + -1, + 255, + 1_000_000, + (1 << 31) - 1, + 1 << 40, + (1 << 53) - 1, + 1 << 53, + -(1 << 53), + ] { + let text = to_string_compact(&Value::from(i)); + assert_eq!(text, i.to_string()); + assert_eq!(parse(&text).unwrap().as_i64(), Some(i)); + } + } + + #[test] + fn value_accessors() { + assert_eq!(Value::Number(1.5).as_i64(), None); + assert_eq!(Value::Number(-1.0).as_i64(), Some(-1)); + assert_eq!(Value::Number(-1.0).as_u64(), None); + assert_eq!(Value::Number(-0.0).as_u64(), Some(0)); + assert_eq!(Value::Number(1e19).as_i64(), None); + assert_eq!( + Value::Number(1e19).as_u64(), + Some(10_000_000_000_000_000_000) + ); + assert_eq!(Value::Number(9223372036854775808.0).as_i64(), None); + assert_eq!( + Value::Number(-9223372036854775808.0).as_i64(), + Some(i64::MIN) + ); + assert_eq!(Value::Number(18446744073709551616.0).as_u64(), None); + assert_eq!(Value::Number(f64::NAN).as_i64(), None); + assert_eq!(Value::Number(f64::INFINITY).as_u64(), None); + assert_eq!(Value::from("1").as_i64(), None); + assert_eq!(Value::from("x").as_str(), Some("x")); + assert_eq!(Value::Null.as_str(), None); + assert_eq!(Value::Bool(true).as_bool(), Some(true)); + assert_eq!(Value::Null.as_bool(), None); + assert!(Value::Null.is_null()); + assert!(!Value::Bool(false).is_null()); + assert_eq!(Value::from("x").get("a"), None); + assert_eq!(Value::Array(vec![]).get("a"), None); + assert_eq!(Value::Null.as_array(), None); + assert_eq!(Value::Null.as_object(), None); + + let mut v = Value::Array(vec![Value::Null]); + v.as_array_mut().unwrap().push(Value::from(1)); + assert_eq!(to_string_compact(&v), "[null,1]"); + let mut o = Value::Object(Map::new()); + o.as_object_mut().unwrap().set("k", "v"); + assert_eq!(o.get("k").and_then(Value::as_str), Some("v")); + assert!(Value::Null.as_object_mut().is_none()); + } + + #[test] + fn from_impls() { + assert_eq!(Value::from("a"), Value::String("a".into())); + assert_eq!(Value::from(String::from("a")), Value::String("a".into())); + assert_eq!(Value::from(true), Value::Bool(true)); + assert_eq!(Value::from(-3i64), Value::Number(-3.0)); + assert_eq!(Value::from(3u64), Value::Number(3.0)); + assert_eq!(Value::from(-3i32), Value::Number(-3.0)); + assert_eq!(Value::from(3u32), Value::Number(3.0)); + assert_eq!(Value::from(3usize), Value::Number(3.0)); + assert_eq!(Value::from(2.5f64), Value::Number(2.5)); + assert_eq!(Value::from(None::<&str>), Value::Null); + assert_eq!(Value::from(Some("x")), Value::from("x")); + assert_eq!(Value::from(Some(7i64)), Value::Number(7.0)); + assert_eq!( + Value::from(vec![Value::Null]), + Value::Array(vec![Value::Null]) + ); + assert_eq!(Value::from(Map::new()), Value::Object(Map::new())); + } + + #[test] + fn map_api() { + let mut m = Map::new(); + assert!(m.is_empty()); + m.set("a", 1i64); + m.set("b", "two"); + m.set(String::from("c"), Value::Null); + m.set("a", true); // replaces in place + assert_eq!(m.len(), 3); + assert!(m.contains_key("b")); + assert!(!m.contains_key("z")); + assert_eq!( + to_string_compact(&Value::from(m.clone())), + r#"{"a":true,"b":"two","c":null}"# + ); + + if let Some(v) = m.get_mut("b") { + *v = Value::from(2i64); + } + assert_eq!(m.get("b"), Some(&Value::Number(2.0))); + assert!(m.get_mut("zz").is_none()); + + assert_eq!(m.remove("a"), Some(Value::Bool(true))); + assert_eq!(m.remove("a"), None); + m.set("a", 0i64); // re-added at the end + let keys: Vec<&str> = m.iter().map(|(k, _)| k).collect(); + assert_eq!(keys, ["b", "c", "a"]); + assert_eq!(Map::default(), Map::new()); + } + + /// xorshift64*: deterministic, std-only randomness for the fuzz test. + struct Rng(u64); + impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + } + + /// If a mutated document parses, it must also survive a serialize/parse + /// round trip unchanged (modulo NaN, which JSON cannot express). + fn check_no_panic_and_stable(text: &str) { + if let Ok(v) = parse(text) { + let compact = to_string_compact(&v); + let pretty = to_string_pretty(&v); + let back = parse(&compact).expect("serializer output must parse"); + assert_eq!(to_string_compact(&back), compact); + assert_eq!(parse(&pretty).map(|p| to_string_compact(&p)), Ok(compact)); + } + } + + #[test] + fn fuzz_truncations_and_mutations_never_panic() { + let seeds = [ + JOB_RECORD, + AGY_RESULT, + r#"{"s":"\ud83d\ude00\u0041\n\"\\","n":[-0,1e-7,1.5E+3,123456789012345678901234],"e":{},"a":[[[]]],"t":true,"f":false,"z":null}"#, + "\u{FEFF}[\"\u{e9}\u{1F600}\u{2028}\",{\"k\":\"\\ud800\"}]", + ]; + // Characters that are likely to produce interesting near-valid JSON. + let alphabet: Vec = + "{}[]\":,\\/ \n\t\r0123456789-+.eEtrufalsn\u{0}\u{1f}\u{e9}\u{FEFF}\u{1F600}" + .chars() + .collect(); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let mut runs = 0usize; + + for seed in seeds { + assert!(parse(seed).is_ok(), "seed must be valid: {seed}"); + let chars: Vec = seed.chars().collect(); + // Every prefix and every suffix. + for i in 0..=chars.len() { + let prefix: String = chars[..i].iter().collect(); + let suffix: String = chars[i..].iter().collect(); + check_no_panic_and_stable(&prefix); + check_no_panic_and_stable(&suffix); + runs += 2; + } + // Random point mutations: replace, insert, delete, duplicate a span. + for _ in 0..3000 { + let mut m = chars.clone(); + for _ in 0..1 + rng.below(4) { + let at = rng.below(m.len() + 1); + match rng.below(4) { + 0 if at < m.len() => m[at] = alphabet[rng.below(alphabet.len())], + 1 => m.insert(at, alphabet[rng.below(alphabet.len())]), + 2 if at < m.len() => { + m.remove(at); + } + _ => { + let end = (at + rng.below(16)).min(m.len()); + let span: Vec = m[at..end].to_vec(); + let to = rng.below(m.len() + 1); + m.splice(to..to, span); + } + } + } + let text: String = m.into_iter().collect(); + check_no_panic_and_stable(&text); + runs += 1; + } + } + // Pure random garbage from the alphabet. + for _ in 0..3000 { + let len = rng.below(64); + let text: String = (0..len) + .map(|_| alphabet[rng.below(alphabet.len())]) + .collect(); + check_no_panic_and_stable(&text); + runs += 1; + } + assert!(runs > 15_000); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..5cfc909 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,95 @@ +//! agy-plugin — Claude Code plugin runtime for Google's Antigravity CLI. +//! +//! One std-only binary behind the /agy:* slash commands. Read-only commands +//! (ask, review, adversarial-review, scrape, doc-to-md) run agy from a +//! throwaway workspace, pinned to its Default agent mode, so it can read but +//! not write; rescue and image are the only write-capable commands. + +mod agy; +mod capture; +mod cli; +mod commands; +mod fetch; +mod git; +mod guard; +mod jobs; +mod json; +mod models; +mod prompts; +mod registry; +mod render; +mod secrets; +mod sys; +mod time; +mod util; + +use std::path::PathBuf; + +/// Plugin <= 0.8.x switched models by patching agy's settings.json under a +/// lock, with a backup + sentinel. If such a run was killed mid-way, put the +/// user's settings back (once; harmless when nothing is left over). +fn restore_orphaned_settings() { + let Some(home) = util::home_dir() else { return }; + let dir: PathBuf = home.join(".gemini").join("antigravity-cli"); + let settings = dir.join("settings.json"); + let backup = dir.join("settings.json.agy-plugin.bak"); + let sentinel = dir.join(".agy-plugin.patched"); + let lock = dir.join(".agy-plugin.lock"); + if !sentinel.exists() { + let _ = std::fs::remove_file(&backup); + return; + } + let pid: Option = std::fs::read_to_string(&sentinel) + .ok() + .and_then(|s| s.lines().next().and_then(|l| l.trim().parse().ok())); + if pid.is_some_and(sys::process_alive) { + return; // an old-version run still owns it + } + if backup.exists() && std::fs::rename(&backup, &settings).is_ok() { + eprintln!( + "[agy-plugin] restored agy settings.json left patched by an interrupted older plugin run" + ); + } + let _ = std::fs::remove_file(&sentinel); + let _ = std::fs::remove_dir_all(&lock); +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let (cmd, rest) = match args.split_first() { + Some((c, r)) => (c.as_str(), r), + None => ("help", &[][..]), + }; + if cmd != "_run-job" { + restore_orphaned_settings(); + } + let result = match cmd { + "check" => commands::check(), + "ask" => commands::ask(rest), + "review" => commands::review(rest, false), + "adversarial-review" => commands::review(rest, true), + "scrape" => commands::scrape(rest), + "doc-to-md" => commands::doc_to_md(rest), + "image" => commands::image(rest), + "rescue" => commands::rescue(rest), + "status" => commands::status(rest), + "result" => commands::result(rest), + "cancel" => commands::cancel(rest), + "version" | "--version" => commands::version(), + "help" | "-h" | "--help" => commands::help(), + "_run-job" => commands::run_job(rest), + other => Err(util::Fail::usage(format!( + "error: unknown subcommand '{other}' (see `agy-plugin help`)" + ))), + }; + let code = match result { + Ok(c) => c, + Err(f) => { + if !f.message.is_empty() { + eprintln!("{}", f.message); + } + f.code + } + }; + std::process::exit(code); +} diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..796e5c8 --- /dev/null +++ b/src/models.rs @@ -0,0 +1,520 @@ +//! `--model` resolution. Aliases resolve at call time against `agy models` +//! to the NEWEST model in their family, and the result is passed to agy's own +//! `--model` flag for that one call (ported from upstream +//! simplybychris/antigravity-plugin-cc 0.5.0). 0.8.x instead patched the +//! "model" field of agy's settings.json under a lock: that flipped the model +//! of a TUI open in parallel and broke whenever Google renamed a model. + +use std::time::Duration; + +use crate::agy::{self, Agy}; +use crate::util::{self, Fail}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Model { + /// Stable id like `gemini-3.8-flash-high` (empty on builds that list + /// display names only). + pub(crate) id: String, + /// Display name like `Gemini 3.8 Flash (High)`. + pub(crate) name: String, +} + +impl Model { + /// The value for `agy --model`. + pub(crate) fn arg(&self) -> &str { + if self.id.is_empty() { + &self.name + } else { + &self.id + } + } +} + +#[derive(Clone, Copy, Debug)] +enum Family { + /// `gemini ()` + Gemini { + tier: &'static str, + level: &'static str, + }, + /// `claude ` with an optional ` (...)` suffix. + Claude { kind: &'static str }, + /// `gpt-oss 120b` with an optional ` (...)` suffix. + GptOss, +} + +struct AliasRow { + aliases: &'static [&'static str], + family: Family, + /// On a version tie, a name ending with this suffix wins. + prefer_suffix: Option<&'static str>, + description: &'static str, +} + +const ALIASES: &[AliasRow] = &[ + AliasRow { + aliases: &["flash-low"], + family: Family::Gemini { + tier: "flash", + level: "low", + }, + prefer_suffix: None, + description: "newest Gemini Flash (Low)", + }, + AliasRow { + aliases: &["flash-medium", "flash-med"], + family: Family::Gemini { + tier: "flash", + level: "medium", + }, + prefer_suffix: None, + description: "newest Gemini Flash (Medium)", + }, + AliasRow { + aliases: &["flash", "flash-high"], + family: Family::Gemini { + tier: "flash", + level: "high", + }, + prefer_suffix: None, + description: "newest Gemini Flash (High)", + }, + AliasRow { + aliases: &["pro-low"], + family: Family::Gemini { + tier: "pro", + level: "low", + }, + prefer_suffix: None, + description: "newest Gemini Pro (Low)", + }, + AliasRow { + aliases: &["pro", "pro-high"], + family: Family::Gemini { + tier: "pro", + level: "high", + }, + prefer_suffix: None, + description: "newest Gemini Pro (High)", + }, + AliasRow { + aliases: &["sonnet", "claude-sonnet"], + family: Family::Claude { kind: "sonnet" }, + prefer_suffix: Some("(thinking)"), + description: "newest Claude Sonnet", + }, + AliasRow { + aliases: &["opus", "claude-opus"], + family: Family::Claude { kind: "opus" }, + prefer_suffix: Some("(thinking)"), + description: "newest Claude Opus", + }, + AliasRow { + aliases: &["gpt-oss", "gpt-oss-120b"], + family: Family::GptOss, + prefer_suffix: Some("(medium)"), + description: "GPT-OSS 120B", + }, +]; + +fn is_version_word(w: &str) -> bool { + !w.is_empty() + && !w.starts_with('.') + && !w.ends_with('.') + && !w.contains("..") + && w.chars().all(|c| c.is_ascii_digit() || c == '.') +} + +/// ` (anything)` at the end, or nothing. +fn optional_paren_suffix(rest: &str) -> bool { + rest.is_empty() || (rest.starts_with(" (") && rest.ends_with(')')) +} + +impl Family { + fn matches(self, lower: &str) -> bool { + match self { + Family::Gemini { tier, level } => { + // exactly: "gemini ()" + let Some(rest) = lower.strip_prefix("gemini ") else { + return false; + }; + let Some((ver, rest)) = rest.split_once(' ') else { + return false; + }; + is_version_word_loose(ver) && rest == format!("{tier} ({level})") + } + Family::Claude { kind } => { + let Some(rest) = lower.strip_prefix("claude ") else { + return false; + }; + let Some(rest) = rest.strip_prefix(kind) else { + return false; + }; + let Some(rest) = rest.strip_prefix(' ') else { + return false; + }; + let ver_end = rest.find(' ').unwrap_or(rest.len()); + is_version_word_loose(&rest[..ver_end]) && optional_paren_suffix(&rest[ver_end..]) + } + Family::GptOss => lower + .strip_prefix("gpt-oss 120b") + .is_some_and(optional_paren_suffix), + } + } +} + +/// The alias patterns used `[0-9.]+`, which also accepts odd spellings like +/// `3.` — keep that leniency for matching (the version used for ORDERING is +/// the strict one from `family_version`). +fn is_version_word_loose(w: &str) -> bool { + !w.is_empty() && w.chars().all(|c| c.is_ascii_digit() || c == '.') +} + +/// The family version inside a lowercased display name: its first purely +/// numeric word ("gemini 3.8 flash (high)" -> "3.8"), or "". +fn family_version(lower: &str) -> &str { + lower.split(' ').find(|w| is_version_word(w)).unwrap_or("") +} + +/// Parse `agy models`: one "iddisplay name" row per model; skips blank +/// lines, the "Fetching available models..." banner and "Header:" lines. +pub(crate) fn parse_model_list(text: &str) -> Vec { + let mut out = Vec::new(); + for raw in text.split('\n') { + let line = raw.strip_suffix('\r').unwrap_or(raw); + if line.trim().is_empty() || line.trim_end().ends_with(':') || line.starts_with("Fetching ") + { + continue; + } + let (id, name) = match line.split_once('\t') { + Some((id, name)) => (id.trim(), name.trim()), + None => ("", line.trim()), + }; + if !name.is_empty() { + out.push(Model { + id: id.to_string(), + name: name.to_string(), + }); + } + } + out +} + +fn alias_row(input: &str) -> Option<&'static AliasRow> { + let lc = input.to_ascii_lowercase(); + ALIASES.iter().find(|r| r.aliases.contains(&lc.as_str())) +} + +fn newest_match<'a>(models: &'a [Model], row: &AliasRow) -> Option<&'a Model> { + let mut best: Option<(&Model, String, bool)> = None; + for m in models { + let lower = m.name.to_lowercase(); + if !row.family.matches(&lower) { + continue; + } + let version = family_version(&lower).to_string(); + let preferred = row.prefer_suffix.is_some_and(|s| lower.ends_with(s)); + let replace = match &best { + None => true, + Some((_, bv, bp)) => match agy::compare_versions(&version, bv) { + std::cmp::Ordering::Greater => true, + std::cmp::Ordering::Equal => preferred && !bp, + std::cmp::Ordering::Less => false, + }, + }; + if replace { + best = Some((m, version, preferred)); + } + } + best.map(|(m, _, _)| m) +} + +fn exact_match<'a>(models: &'a [Model], input: &str) -> Option<&'a Model> { + let want = input.to_lowercase(); + models + .iter() + .find(|m| m.id.to_lowercase() == want || m.name.to_lowercase() == want) +} + +/// Resolve against a model list (pure). Exact ids/names win over aliases. +pub(crate) fn resolve_from_list(models: &[Model], input: &str) -> Result { + if let Some(m) = exact_match(models, input) { + return Ok(m.arg().to_string()); + } + match alias_row(input) { + Some(row) => newest_match(models, row) + .map(|m| m.arg().to_string()) + .ok_or_else(|| { + format!( + "error: alias '{input}' has no matching model in `agy models` (expected: {})", + row.description + ) + }), + None => Err(format!( + "error: unknown model '{input}' (not an alias and not listed by `agy models`)" + )), + } +} + +/// Alias + model table for errors and `help`. +pub(crate) fn format_model_table(models: Option<&[Model]>) -> String { + let listed = models.filter(|m| !m.is_empty()); + let mut out = String::new(); + out.push_str(if listed.is_some() { + "Aliases (case-insensitive), resolved against `agy models`:\n" + } else { + "Aliases (case-insensitive). `agy models` could not be read, so they are shown unresolved:\n" + }); + for row in ALIASES { + let target = match listed { + None => row.description.to_string(), + Some(ms) => match newest_match(ms, row) { + Some(m) => m.name.clone(), + None => format!("(not available: {})", row.description), + }, + }; + out.push_str(&format!( + " {:<28} -> {}\n", + row.aliases.join(", "), + target + )); + } + if let Some(ms) = listed { + out.push_str( + "\nAvailable models (names and ids are accepted verbatim, case-insensitive):\n", + ); + for m in ms { + if m.id.is_empty() { + out.push_str(&format!(" {}\n", m.name)); + } else { + out.push_str(&format!(" {:<32} {}\n", m.name, m.id)); + } + } + } + out +} + +/// `agy models`, parsed; None if it can't be listed. +pub(crate) fn list_models(agy: &Agy) -> Option> { + let out = util::run_simple(agy.path(), &["models"], Duration::from_secs(60)).ok()?; + if !out.ok() { + return None; + } + Some(parse_model_list(&out.stdout_str())) +} + +/// Resolve a `--model` value for `agy --model` (requires agy >= 1.2.0, which +/// every command already enforces). Exit 64 for an unknown name, 1 when +/// `agy models` can't be read but an alias needs it. +pub(crate) fn resolve(agy: &Agy, input: &str) -> Result { + if input.trim().is_empty() { + return Err(empty_value_error(Some(agy))); + } + let models = list_models(agy).filter(|m| !m.is_empty()); + let Some(models) = models else { + if alias_row(input).is_some() { + return Err(Fail::runtime( + "error: could not list models with `agy models` (run it directly to see why).\n aliases need that list; pass the full model name instead.", + )); + } + eprintln!("[agy-plugin] note: could not list models; passing '{input}' to agy unchecked"); + return Ok(input.to_string()); + }; + resolve_from_list(&models, input).map_err(|e| { + Fail::usage(format!( + "{e}\n{}", + format_model_table(Some(&models)).trim_end() + )) + }) +} + +/// The error for `--model` given without a value (exit 64), with the table. +pub(crate) fn empty_value_error(agy: Option<&Agy>) -> Fail { + let models = agy.and_then(list_models); + Fail::usage(format!( + "error: --model requires a non-empty value (e.g. --model pro)\n{}", + format_model_table(models.as_deref()).trim_end() + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn listing() -> Vec { + parse_model_list( + "Fetching available models...\n\ + gemini-3.5-flash-high\tGemini 3.5 Flash (High)\n\ + gemini-3.8-flash-high\tGemini 3.8 Flash (High)\n\ + gemini-3.8-flash-low\tGemini 3.8 Flash (Low)\r\n\ + claude-sonnet-4-6\tClaude Sonnet 4.6\n\ + claude-sonnet-4-6-thinking\tClaude Sonnet 4.6 (Thinking)\n\ + claude-opus-4-6-thinking\tClaude Opus 4.6 (Thinking)\n\ + gpt-oss-120b-medium\tGPT-OSS 120B (Medium)\n\ + \n", + ) + } + + #[test] + fn parses_the_real_agy_1_5_16_listing() { + let m = listing(); + assert_eq!(m.len(), 7); + assert_eq!( + m[0], + Model { + id: "gemini-3.5-flash-high".into(), + name: "Gemini 3.5 Flash (High)".into() + } + ); + assert_eq!(m[2].name, "Gemini 3.8 Flash (Low)", "CRLF stripped"); + } + + #[test] + fn name_only_listing_and_headers() { + let m = parse_model_list("Models:\nGemini 3.8 Flash (High)\n \nFetching x\n"); + assert_eq!( + m, + vec![Model { + id: String::new(), + name: "Gemini 3.8 Flash (High)".into() + }] + ); + assert_eq!(m[0].arg(), "Gemini 3.8 Flash (High)"); + } + + #[test] + fn aliases_pick_the_newest_in_family() { + let m = listing(); + assert_eq!( + resolve_from_list(&m, "flash").unwrap(), + "gemini-3.8-flash-high" + ); + assert_eq!( + resolve_from_list(&m, "flash-high").unwrap(), + "gemini-3.8-flash-high" + ); + assert_eq!( + resolve_from_list(&m, "flash-low").unwrap(), + "gemini-3.8-flash-low" + ); + assert_eq!( + resolve_from_list(&m, "OPUS").unwrap(), + "claude-opus-4-6-thinking" + ); + assert_eq!( + resolve_from_list(&m, "gpt-oss").unwrap(), + "gpt-oss-120b-medium" + ); + } + + #[test] + fn version_tie_prefers_thinking() { + assert_eq!( + resolve_from_list(&listing(), "sonnet").unwrap(), + "claude-sonnet-4-6-thinking" + ); + } + + #[test] + fn newer_version_beats_preferred_suffix() { + let m = parse_model_list("a\tClaude Sonnet 4.6 (Thinking)\nb\tClaude Sonnet 4.10\n"); + assert_eq!( + resolve_from_list(&m, "sonnet").unwrap(), + "b", + "4.10 > 4.6 numerically" + ); + } + + #[test] + fn exact_names_and_ids_win_and_are_case_insensitive() { + let m = listing(); + assert_eq!( + resolve_from_list(&m, "claude opus 4.6 (thinking)").unwrap(), + "claude-opus-4-6-thinking" + ); + assert_eq!( + resolve_from_list(&m, "GPT-OSS-120B-MEDIUM").unwrap(), + "gpt-oss-120b-medium" + ); + // An id that is also alias-shaped resolves to itself, not the family. + let m2 = parse_model_list( + "flash\tSome Custom Model\ngemini-9-flash-high\tGemini 9 Flash (High)\n", + ); + assert_eq!(resolve_from_list(&m2, "flash").unwrap(), "flash"); + } + + #[test] + fn unknown_and_unavailable_family_errors() { + let m = listing(); + assert!( + resolve_from_list(&m, "nope") + .unwrap_err() + .contains("unknown model 'nope'") + ); + assert!( + resolve_from_list(&m, "pro") + .unwrap_err() + .contains("no matching model") + ); + } + + #[test] + fn family_matching_is_exact() { + let f = Family::Gemini { + tier: "flash", + level: "high", + }; + assert!(f.matches("gemini 3.8 flash (high)")); + assert!(!f.matches("gemini 3.8 flash (high) extra")); + assert!(!f.matches("gemini 3.8 flash lite (high)")); + assert!(!f.matches("gemini flash (high)")); + assert!(!f.matches("gemini 4 neon (high)")); + let c = Family::Claude { kind: "opus" }; + assert!(c.matches("claude opus 4.6")); + assert!(c.matches("claude opus 4.6 (thinking)")); + assert!(!c.matches("claude opus")); + assert!(!c.matches("claude opus 4.6 thinking")); + assert!(!c.matches("claude sonnet 4.6")); + assert!(Family::GptOss.matches("gpt-oss 120b")); + assert!(Family::GptOss.matches("gpt-oss 120b (medium)")); + assert!(!Family::GptOss.matches("gpt-oss 20b")); + } + + #[test] + fn table_shows_resolved_and_unavailable_aliases() { + let t = format_model_table(Some(&listing())); + assert!(t.starts_with("Aliases (case-insensitive), resolved against `agy models`:\n")); + // Byte-identical to the 0.8.x/0.9-wip bash wrapper's live output. + assert!(t.contains(" flash, flash-high -> Gemini 3.8 Flash (High)\n")); + assert!(t.contains( + " pro, pro-high -> (not available: newest Gemini Pro (High))\n" + )); + assert!(t.contains("-> (not available: newest Gemini Pro (High))")); + assert!(t.contains(" Gemini 3.8 Flash (Low) gemini-3.8-flash-low\n")); + let u = format_model_table(None); + assert!(u.contains("could not be read")); + assert!(u.contains("-> newest Claude Opus")); + } + + #[cfg(unix)] + #[test] + fn resolve_against_a_stub_agy() { + use std::os::unix::fs::PermissionsExt; + let d = util::TempDir::new("agy-models-test-").unwrap(); + let p = d.path().join("agy"); + std::fs::write(&p, "#!/bin/sh\n[ \"$1\" = models ] && printf 'Fetching available models...\\ngemini-3.8-flash-low\\tGemini 3.8 Flash (Low)\\n'\n").unwrap(); + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap(); + let a = Agy::at(p); + assert_eq!(resolve(&a, "flash-low").unwrap(), "gemini-3.8-flash-low"); + assert_eq!(resolve(&a, "nope").unwrap_err().code, 64); + assert_eq!(resolve(&a, " ").unwrap_err().code, 64); + // Unlistable models: alias fails (1), full name passes unchecked. + std::fs::write(d.path().join("agy"), "#!/bin/sh\nexit 1\n").unwrap(); + let a = Agy::at(d.path().join("agy")); + assert_eq!(resolve(&a, "flash").unwrap_err().code, 1); + assert_eq!( + resolve(&a, "Some Future Model").unwrap(), + "Some Future Model" + ); + } +} diff --git a/src/prompts.rs b/src/prompts.rs new file mode 100644 index 0000000..322a1ab --- /dev/null +++ b/src/prompts.rs @@ -0,0 +1,479 @@ +//! Prompt templates for /agy:review and /agy:adversarial-review +//! (port of lib/prompts.mjs, byte-identical output). +//! +//! Design A+: the diff and the full changed files live on disk in a staging +//! dir agy can read (passed via --add-dir); the prompt only POINTS at them. +//! That keeps the argv prompt tiny (no ENAMETOOLONG, no truncation) and gives +//! agy whole files for context, which kills "X not imported" / "missing +//! guard" false positives caused by seeing only a hunk. + +use crate::cli::js_trim; + +/// What is being reviewed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum Scope { + /// Uncommitted changes against HEAD. + WorkingTree, + /// HEAD against the merge-base with `base`. + Branch { + base: String, + merge_base: Option, + }, +} + +/// A changed file that was not staged for agy, and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Omitted { + pub path: String, + pub reason: String, +} + +const PREAMBLE_REVIEW: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity."; + +const PREAMBLE_ADVERSARIAL: &str = "Pressure-test the diff below. Your job is to challenge the implementation, NOT to validate it. Question the chosen approach, surface hidden assumptions, name failure modes the author didn't address, and propose at least one alternative design with concrete tradeoffs vs the chosen one. If the diff is sound, say so explicitly — but make the reader work for that conclusion."; + +const REVIEW_RULES: [&str; 5] = [ + "Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.", + "For each finding cite the file path and (ideally) the line number from the diff.", + "Prefer concrete code examples for suggested fixes over prose.", + "Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.", + "Do NOT propose unrelated refactors; review the diff as it stands.", +]; + +const ADVERSARIAL_RULES: [&str; 5] = [ + "Frame at least 3 questions the diff fails to answer.", + "Identify the assumption you think most likely to break, and why.", + "Propose one materially different design (not just 'rename this'); compare tradeoffs in 3-5 bullets.", + "Call out the failure modes that aren't covered by tests in the diff.", + "Conclude with a one-paragraph verdict: ship / change / rethink.", +]; + +fn join_rules(rules: &[&str]) -> String { + rules + .iter() + .enumerate() + .map(|(i, r)| format!("{}. {r}", i + 1)) + .collect::>() + .join("\n") +} + +/// Same reasons the JS regex `/too large|binary|symlink|outside/` matched: +/// files agy cannot see in full, so it must judge them from the diff alone. +fn is_big_reason(reason: &str) -> bool { + ["too large", "binary", "symlink", "outside"] + .iter() + .any(|k| reason.contains(k)) +} + +fn staged_materials_block(stage_dir: &str, staged: &[String], omitted: &[Omitted]) -> String { + // The prompt is read by agy on the same machine, so match the path + // style of stage_dir itself (Windows temp dirs use backslashes). + let sep = if stage_dir.contains('\\') { "\\" } else { "/" }; + let diff_path = format!("{stage_dir}{sep}diff.patch"); + let files_dir = format!("{stage_dir}{sep}files"); + let mut parts: Vec = vec![ + String::new(), + "## Material to review (read these files with your tools — they are on disk, not inline)" + .to_string(), + format!("- The unified diff (with expanded context) is at:\n {diff_path}"), + ]; + if !staged.is_empty() { + parts.push(format!( + "- The FULL current content of the changed files is under:\n {files_dir}{sep}" + )); + parts.push(" Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it — the definition is often outside the diff hunk.".to_string()); + parts.push(" Changed files staged for you:".to_string()); + parts.extend(staged.iter().map(|f| format!(" - {f}"))); + } + let big: Vec = omitted + .iter() + .filter(|o| is_big_reason(&o.reason)) + .map(|o| format!("{} [{}]", o.path, o.reason)) + .collect(); + if !big.is_empty() { + parts.push(format!( + " (Not staged: {} — judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)", + big.join(", ") + )); + } + parts.join("\n") +} + +fn assemble( + preamble: &str, + rules: &[&str], + scope_blurb: String, + focus_block: String, + stage_dir: &str, + staged: &[String], + omitted: &[Omitted], +) -> String { + [ + preamble.to_string(), + String::new(), + "Rules:".to_string(), + join_rules(rules), + String::new(), + scope_blurb, + focus_block, + staged_materials_block(stage_dir, staged, omitted), + String::new(), + ] + .join("\n") +} + +/// Prompt for `/agy:review`. `focus` empty means no focus block; a +/// whitespace-only focus still emits the (empty) block, as the JS did. +pub(crate) fn build_review_prompt( + scope: &Scope, + focus: &str, + stage_dir: &str, + staged: &[String], + omitted: &[Omitted], +) -> String { + let scope_blurb = match scope { + Scope::Branch { base, merge_base } => format!( + "Branch review: HEAD compared against merge-base of HEAD and `{base}` (resolved sha: {}).", + merge_base.as_deref().unwrap_or("?") + ), + Scope::WorkingTree => { + "Working-tree review: uncommitted changes against `HEAD`.".to_string() + } + }; + let focus_block = if focus.is_empty() { + String::new() + } else { + format!("\n\nUser focus / extra steer:\n{}", js_trim(focus)) + }; + assemble( + PREAMBLE_REVIEW, + &REVIEW_RULES, + scope_blurb, + focus_block, + stage_dir, + staged, + omitted, + ) +} + +/// Prompt for `/agy:adversarial-review`: same staged materials, different +/// stance and rules. +pub(crate) fn build_adversarial_prompt( + scope: &Scope, + focus: &str, + stage_dir: &str, + staged: &[String], + omitted: &[Omitted], +) -> String { + let scope_blurb = match scope { + Scope::Branch { base, .. } => { + format!("Branch under challenge: HEAD vs merge-base of HEAD and `{base}`.") + } + Scope::WorkingTree => "Working-tree changes under challenge.".to_string(), + }; + let focus_block = if focus.is_empty() { + String::new() + } else { + format!( + "\n\nWhere the user wants the most pressure:\n{}", + js_trim(focus) + ) + }; + assemble( + PREAMBLE_ADVERSARIAL, + &ADVERSARIAL_RULES, + scope_blurb, + focus_block, + stage_dir, + staged, + omitted, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Expected prompts below were generated by running the original + // lib/prompts.mjs under Node (scratchpad gen_prompts.mjs), so these + // tests pin byte-identity with the JS runtime. + const JS_REVIEW_WT: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.\n\nRules:\n1. Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.\n2. For each finding cite the file path and (ideally) the line number from the diff.\n3. Prefer concrete code examples for suggested fixes over prose.\n4. Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.\n5. Do NOT propose unrelated refactors; review the diff as it stands.\n\nWorking-tree review: uncommitted changes against `HEAD`.\n\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/agy-review-xyz/diff.patch\n- The FULL current content of the changed files is under:\n /tmp/agy-review-xyz/files/\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - foo.js\n"; + + const JS_REVIEW_BRANCH_OMITTED: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.\n\nRules:\n1. Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.\n2. For each finding cite the file path and (ideally) the line number from the diff.\n3. Prefer concrete code examples for suggested fixes over prose.\n4. Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.\n5. Do NOT propose unrelated refactors; review the diff as it stands.\n\nBranch review: HEAD compared against merge-base of HEAD and `main` (resolved sha: fff0000).\n\n\nUser focus / extra steer:\nerror handling\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/agy-review-xyz/diff.patch\n- The FULL current content of the changed files is under:\n /tmp/agy-review-xyz/files/\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - bar.ts\n - bar.test.ts\n (Not staged: huge.bin [binary], ln [symlink], big.json [too large (2 MB)], ../x [outside repo] \u{2014} judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)\n"; + + const JS_REVIEW_BRANCH_WS_FOCUS: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.\n\nRules:\n1. Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.\n2. For each finding cite the file path and (ideally) the line number from the diff.\n3. Prefer concrete code examples for suggested fixes over prose.\n4. Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.\n5. Do NOT propose unrelated refactors; review the diff as it stands.\n\nBranch review: HEAD compared against merge-base of HEAD and `origin/dev` (resolved sha: ?).\n\n\nUser focus / extra steer:\n\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/s/diff.patch\n"; + + const JS_REVIEW_WINDOWS: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.\n\nRules:\n1. Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.\n2. For each finding cite the file path and (ideally) the line number from the diff.\n3. Prefer concrete code examples for suggested fixes over prose.\n4. Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.\n5. Do NOT propose unrelated refactors; review the diff as it stands.\n\nWorking-tree review: uncommitted changes against `HEAD`.\n\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n C:\\Temp\\agy-review-xyz\\diff.patch\n- The FULL current content of the changed files is under:\n C:\\Temp\\agy-review-xyz\\files\\\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - foo.js\n - dir\\a.js\n (Not staged: img.png [binary] \u{2014} judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)\n"; + + const JS_ADV_WT: &str = "Pressure-test the diff below. Your job is to challenge the implementation, NOT to validate it. Question the chosen approach, surface hidden assumptions, name failure modes the author didn't address, and propose at least one alternative design with concrete tradeoffs vs the chosen one. If the diff is sound, say so explicitly \u{2014} but make the reader work for that conclusion.\n\nRules:\n1. Frame at least 3 questions the diff fails to answer.\n2. Identify the assumption you think most likely to break, and why.\n3. Propose one materially different design (not just 'rename this'); compare tradeoffs in 3-5 bullets.\n4. Call out the failure modes that aren't covered by tests in the diff.\n5. Conclude with a one-paragraph verdict: ship / change / rethink.\n\nWorking-tree changes under challenge.\n\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/agy-review-xyz/diff.patch\n"; + + const JS_ADV_BRANCH: &str = "Pressure-test the diff below. Your job is to challenge the implementation, NOT to validate it. Question the chosen approach, surface hidden assumptions, name failure modes the author didn't address, and propose at least one alternative design with concrete tradeoffs vs the chosen one. If the diff is sound, say so explicitly \u{2014} but make the reader work for that conclusion.\n\nRules:\n1. Frame at least 3 questions the diff fails to answer.\n2. Identify the assumption you think most likely to break, and why.\n3. Propose one materially different design (not just 'rename this'); compare tradeoffs in 3-5 bullets.\n4. Call out the failure modes that aren't covered by tests in the diff.\n5. Conclude with a one-paragraph verdict: ship / change / rethink.\n\nBranch under challenge: HEAD vs merge-base of HEAD and `main`.\n\n\nWhere the user wants the most pressure:\nthe retry/backoff design\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/agy-review-xyz/diff.patch\n- The FULL current content of the changed files is under:\n /tmp/agy-review-xyz/files/\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - bar.ts\n - bar.test.ts\n (Not staged: huge.bin [binary] \u{2014} judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)\n"; + + const JS_ADV_WINDOWS_TRIM: &str = "Pressure-test the diff below. Your job is to challenge the implementation, NOT to validate it. Question the chosen approach, surface hidden assumptions, name failure modes the author didn't address, and propose at least one alternative design with concrete tradeoffs vs the chosen one. If the diff is sound, say so explicitly \u{2014} but make the reader work for that conclusion.\n\nRules:\n1. Frame at least 3 questions the diff fails to answer.\n2. Identify the assumption you think most likely to break, and why.\n3. Propose one materially different design (not just 'rename this'); compare tradeoffs in 3-5 bullets.\n4. Call out the failure modes that aren't covered by tests in the diff.\n5. Conclude with a one-paragraph verdict: ship / change / rethink.\n\nWorking-tree changes under challenge.\n\n\nWhere the user wants the most pressure:\nx\u{85}\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n C:\\Temp\\s\\diff.patch\n- The FULL current content of the changed files is under:\n C:\\Temp\\s\\files\\\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - a\n"; + + const JS_REVIEW_UNICODE: &str = "Review the following diff. Be specific and actionable. Skip nits unless they materially affect correctness or safety. Group findings by severity.\n\nRules:\n1. Group findings under: ## Correctness, ## Security, ## Edge cases, ## Style. Omit empty sections.\n2. For each finding cite the file path and (ideally) the line number from the diff.\n3. Prefer concrete code examples for suggested fixes over prose.\n4. Be explicit about confidence: HIGH for clear bugs, MEDIUM for likely issues, LOW for guesses.\n5. Do NOT propose unrelated refactors; review the diff as it stands.\n\nBranch review: HEAD compared against merge-base of HEAD and `фича/ветка` (resolved sha: ?).\n\n\nUser focus / extra steer:\nмногострочный\nфокус 😀\n\n## Material to review (read these files with your tools \u{2014} they are on disk, not inline)\n- The unified diff (with expanded context) is at:\n /tmp/путь с пробелом/diff.patch\n- The FULL current content of the changed files is under:\n /tmp/путь с пробелом/files/\n Read the ones you need for context. Do NOT flag an issue (missing import, undefined name, missing guard) as a bug unless you've checked the full file and confirmed it \u{2014} the definition is often outside the diff hunk.\n Changed files staged for you:\n - файл.rs\n - 😀.md\n (Not staged: x [binarysymlink] \u{2014} judge those from the diff alone, and mark cross-context concerns as [UNVERIFIED].)\n"; + + const STAGE: &str = "/tmp/agy-review-xyz"; + + fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() + } + + fn om(path: &str, reason: &str) -> Omitted { + Omitted { + path: path.to_string(), + reason: reason.to_string(), + } + } + + fn branch(base: &str, mb: Option<&str>) -> Scope { + Scope::Branch { + base: base.to_string(), + merge_base: mb.map(str::to_string), + } + } + + // --- byte-identity with Node --- + + #[test] + fn js_review_working_tree() { + let p = build_review_prompt(&Scope::WorkingTree, "", STAGE, &s(&["foo.js"]), &[]); + assert_eq!(p, JS_REVIEW_WT); + } + + #[test] + fn js_review_branch_with_omitted() { + let omitted = [ + om("huge.bin", "binary"), + om("gone.txt", "deleted"), + om("ln", "symlink"), + om("big.json", "too large (2 MB)"), + om("../x", "outside repo"), + ]; + let p = build_review_prompt( + &branch("main", Some("fff0000")), + " error handling \n", + STAGE, + &s(&["bar.ts", "bar.test.ts"]), + &omitted, + ); + assert_eq!(p, JS_REVIEW_BRANCH_OMITTED); + } + + #[test] + fn js_review_branch_whitespace_focus_no_merge_base() { + let p = build_review_prompt(&branch("origin/dev", None), " ", "/tmp/s", &[], &[]); + assert_eq!(p, JS_REVIEW_BRANCH_WS_FOCUS); + } + + #[test] + fn js_review_windows_paths() { + let p = build_review_prompt( + &Scope::WorkingTree, + "", + "C:\\Temp\\agy-review-xyz", + &s(&["foo.js", "dir\\a.js"]), + &[om("img.png", "binary")], + ); + assert_eq!(p, JS_REVIEW_WINDOWS); + } + + #[test] + fn js_adversarial_working_tree() { + let p = build_adversarial_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]); + assert_eq!(p, JS_ADV_WT); + } + + #[test] + fn js_adversarial_branch() { + let p = build_adversarial_prompt( + &branch("main", Some("fff0000")), + "the retry/backoff design", + STAGE, + &s(&["bar.ts", "bar.test.ts"]), + &[om("huge.bin", "binary")], + ); + assert_eq!(p, JS_ADV_BRANCH); + } + + #[test] + fn js_adversarial_windows_and_js_trim() { + // U+FEFF is trimmed by JS but not by str::trim; U+0085 the reverse. + // The reason "Binary" does not match the case-sensitive JS regex. + let p = build_adversarial_prompt( + &Scope::WorkingTree, + "\u{feff} x\u{85} \u{3000}", + "C:\\Temp\\s", + &s(&["a"]), + &[om("q", "Binary")], + ); + assert_eq!(p, JS_ADV_WINDOWS_TRIM); + } + + #[test] + fn js_review_unicode() { + let p = build_review_prompt( + &branch("фича/ветка", None), + "многострочный\nфокус 😀", + "/tmp/путь с пробелом", + &s(&["файл.rs", "😀.md"]), + &[om("x", "binarysymlink")], + ); + assert_eq!(p, JS_REVIEW_UNICODE); + } + + // --- ported from tests/lib.prompts.test.mjs --- + + #[test] + fn includes_preamble_and_rules() { + let p = build_review_prompt(&Scope::WorkingTree, "", STAGE, &s(&["foo.js"]), &[]); + assert!(p.contains(&PREAMBLE_REVIEW[..30])); + for r in REVIEW_RULES { + assert!(p.contains(r), "{r}"); + } + } + + #[test] + fn scope_blurbs() { + let wt = build_review_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]); + assert!(wt.contains("Working-tree review")); + let b = build_review_prompt( + &branch("main", Some("fff0000")), + "", + STAGE, + &s(&["bar.ts", "bar.test.ts"]), + &[], + ); + assert!(b.contains("Branch review")); + assert!(b.contains("`main`")); + assert!(b.contains("fff0000")); + let nb = build_review_prompt(&branch("main", None), "", STAGE, &[], &[]); + assert!(nb.contains("(resolved sha: ?)")); + } + + #[test] + fn points_at_staged_materials() { + let p = build_review_prompt( + &branch("main", Some("fff0000")), + "", + STAGE, + &s(&["bar.ts", "bar.test.ts"]), + &[], + ); + assert!(p.contains("/tmp/agy-review-xyz/diff.patch")); + assert!(p.contains("/tmp/agy-review-xyz/files")); + assert!(p.contains("- bar.ts")); + assert!(p.contains("- bar.test.ts")); + assert!(!p.contains("```diff")); + } + + #[test] + fn no_staged_files_omits_file_section() { + let p = build_review_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]); + assert!(p.contains("diff.patch")); + assert!(!p.contains("Changed files staged for you")); + assert!(!p.contains("/files")); + } + + #[test] + fn omitted_files_marked_unverified() { + let p = build_review_prompt( + &branch("main", Some("fff0000")), + "", + STAGE, + &s(&["bar.ts"]), + &[om("huge.bin", "binary")], + ); + assert!(p.contains("huge.bin")); + assert!(p.contains("UNVERIFIED")); + } + + #[test] + fn omitted_with_other_reasons_not_listed() { + let p = build_review_prompt( + &Scope::WorkingTree, + "", + STAGE, + &[], + &[om("gone.txt", "deleted"), om("q", "BINARY")], + ); + assert!(!p.contains("Not staged")); + assert!(!p.contains("gone.txt")); + } + + #[test] + fn focus_block_only_when_non_empty() { + let p = build_review_prompt(&Scope::WorkingTree, "error handling", STAGE, &[], &[]); + assert!(p.contains("User focus / extra steer:\nerror handling")); + let p = build_review_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]); + assert!(!p.contains("User focus")); + } + + #[test] + fn adversarial_uses_own_preamble_and_rules() { + let p = build_adversarial_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]); + assert!(p.contains(&PREAMBLE_ADVERSARIAL[..30])); + assert!(!p.contains(&PREAMBLE_REVIEW[..30])); + for r in ADVERSARIAL_RULES { + assert!(p.contains(r), "{r}"); + } + assert!(!p.contains(REVIEW_RULES[0])); + } + + #[test] + fn adversarial_points_at_staged_and_frames_pressure() { + let p = build_adversarial_prompt( + &branch("main", Some("fff0000")), + "the retry/backoff design", + STAGE, + &s(&["bar.ts", "bar.test.ts"]), + &[], + ); + assert!(p.contains("/tmp/agy-review-xyz/diff.patch")); + assert!(p.to_lowercase().contains("pressure")); + assert!(p.contains("the retry/backoff design")); + assert!(p.contains("`main`")); + // Adversarial blurb never shows the merge-base sha. + assert!(!p.contains("fff0000")); + } + + #[test] + fn windows_separator() { + let p = build_review_prompt( + &Scope::WorkingTree, + "", + "C:\\Temp\\agy-review-xyz", + &s(&["foo.js"]), + &[], + ); + assert!(p.contains("C:\\Temp\\agy-review-xyz\\diff.patch")); + assert!(p.contains("C:\\Temp\\agy-review-xyz\\files\\")); + } + + #[test] + fn ends_with_single_newline() { + for p in [ + build_review_prompt(&Scope::WorkingTree, "", STAGE, &[], &[]), + build_adversarial_prompt(&Scope::WorkingTree, "x", STAGE, &s(&["a"]), &[]), + ] { + assert!(p.ends_with('\n') && !p.ends_with("\n\n")); + } + } + + #[test] + fn hostile_inputs_are_inert() { + // Format-string-looking and newline-laden inputs pass through verbatim. + let p = build_review_prompt( + &branch("{base}`\n## Security", Some("{}")), + "{0} {focus}", + "{stage_dir}", + &s(&["{f}", ""]), + &[om("{}", "too large {}")], + ); + assert!(p.contains("`{base}`\n## Security` (resolved sha: {})")); + assert!(p.contains("{0} {focus}")); + assert!(p.contains("{stage_dir}/diff.patch")); + assert!(p.contains(" - {f}\n - \n")); + assert!(p.contains("{} [too large {}]")); + } +} diff --git a/src/registry.rs b/src/registry.rs new file mode 100644 index 0000000..957b799 --- /dev/null +++ b/src/registry.rs @@ -0,0 +1,302 @@ +//! The per-user record of jobs this user started on this machine. +//! +//! Job records live in the workspace (`.agy-plugin/jobs/*.json`) and a +//! repository can COMMIT such files: a cloned repo could plant a record that +//! names any pid and any directory. So nothing that kills a process or +//! deletes a directory may trust the workspace record. This registry lives +//! outside every repo, in a private (0700) per-user directory, and only +//! this program writes it: +//! +//! - `.json`: the workspace, worker pid, agy child pid and stage dir; +//! - `.lock`: held with an exclusive OS file lock (`File::lock`) by the +//! worker while it runs. The OS releases it when the process dies, however +//! it dies, so "the lock is held" proves the worker is alive and is OURS — +//! a pid alone could have been reused by an unrelated process. + +use std::fs::{File, OpenOptions, TryLockError}; +use std::path::{Path, PathBuf}; + +use crate::json::{self, Map, Value}; +use crate::util; + +/// `$AGY_PLUGIN_STATE_DIR`, else the platform's per-user state dir. Unit +/// tests always use a private per-process temp dir, never the real one. +pub(crate) fn dir() -> Option { + #[cfg(test)] + { + return Some( + std::env::temp_dir() + .join(format!("agy-plugin-test-registry-{}", std::process::id())) + .join("jobs"), + ); + } + #[cfg_attr(test, allow(unreachable_code))] + if let Some(d) = util::env_nonempty("AGY_PLUGIN_STATE_DIR") { + return Some(PathBuf::from(d).join("jobs")); + } + #[cfg(windows)] + { + util::env_nonempty("LOCALAPPDATA").map(|l| PathBuf::from(l).join("agy-plugin").join("jobs")) + } + #[cfg(not(windows))] + { + let base = util::env_nonempty("XDG_STATE_HOME") + .map(PathBuf::from) + .or_else(|| util::home_dir().map(|h| h.join(".local").join("state")))?; + Some(base.join("agy-plugin").join("jobs")) + } +} + +fn ensure_dir() -> Option { + let d = dir()?; + let mut b = std::fs::DirBuilder::new(); + b.recursive(true); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + b.mode(0o700); + } + b.create(&d).ok()?; + // Refuse a registry dir that is a symlink or (on Unix) not private. + let meta = std::fs::symlink_metadata(&d).ok()?; + if meta.file_type().is_symlink() || !meta.is_dir() { + return None; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if meta.permissions().mode() & 0o077 != 0 { + let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)); + } + } + Some(d) +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct Entry { + pub(crate) workspace: PathBuf, + pub(crate) stage_dir: Option, + pub(crate) pid: Option, + /// The worker leads its own process group (background workers). + pub(crate) group_leader: bool, + /// The agy process the worker started, if any. + pub(crate) child_pid: Option, +} + +fn to_value(e: &Entry) -> Value { + let mut m = Map::new(); + m.set("workspace", e.workspace.display().to_string()); + m.set( + "stageDir", + e.stage_dir.as_ref().map(|p| p.display().to_string()), + ); + m.set("pid", e.pid); + m.set("groupLeader", e.group_leader); + m.set("childPid", e.child_pid); + Value::Object(m) +} + +fn pid_field(v: &Value, k: &str) -> Option { + v.get(k) + .and_then(Value::as_u64) + .and_then(|p| u32::try_from(p).ok()) + .filter(|p| *p > 1) +} + +fn from_value(v: &Value) -> Option { + Some(Entry { + workspace: PathBuf::from(v.get("workspace")?.as_str()?), + stage_dir: v.get("stageDir").and_then(Value::as_str).map(PathBuf::from), + pid: pid_field(v, "pid"), + group_leader: v + .get("groupLeader") + .and_then(Value::as_bool) + .unwrap_or(false), + child_pid: pid_field(v, "childPid"), + }) +} + +fn valid(id: &str) -> bool { + crate::jobs::is_valid_id(id) +} + +/// Record a new job (called when the job is created). +pub(crate) fn register(id: &str, workspace: &Path, stage_dir: Option<&Path>) { + let e = Entry { + workspace: util::canonical_or_self(workspace), + stage_dir: stage_dir.map(util::canonical_or_self), + ..Entry::default() + }; + write(id, &e); +} + +fn write(id: &str, e: &Entry) { + if !valid(id) { + return; + } + if let Some(d) = ensure_dir() { + let text = format!("{}\n", json::to_string_pretty(&to_value(e))); + let _ = crate::jobs::write_atomic(&d.join(format!("{id}.json")), text.as_bytes()); + } +} + +/// The entry for `id`, if THIS user's registry has one. +pub(crate) fn read(id: &str) -> Option { + if !valid(id) { + return None; + } + let text = std::fs::read_to_string(dir()?.join(format!("{id}.json"))).ok()?; + from_value(&json::parse(&text).ok()?) +} + +/// The entry for `id` only if it belongs to `workspace`. +pub(crate) fn read_for(id: &str, workspace: &Path) -> Option { + read(id).filter(|e| e.workspace == util::canonical_or_self(workspace)) +} + +pub(crate) fn update(id: &str, f: impl FnOnce(&mut Entry)) { + if let Some(mut e) = read(id) { + f(&mut e); + write(id, &e); + } +} + +pub(crate) fn remove(id: &str) { + if let Some(d) = dir().filter(|_| valid(id)) { + let _ = std::fs::remove_file(d.join(format!("{id}.json"))); + let _ = std::fs::remove_file(d.join(format!("{id}.lock"))); + } +} + +fn open_lock(id: &str) -> Option { + let d = ensure_dir()?; + let mut o = OpenOptions::new(); + o.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + o.mode(0o600); + } + o.open(d.join(format!("{id}.lock"))).ok() +} + +/// Take the job's liveness lock for the lifetime of the returned handle. +pub(crate) fn hold(id: &str) -> Option { + if !valid(id) { + return None; + } + let f = open_lock(id)?; + f.lock().ok()?; + Some(f) +} + +/// Some(true) if the job's worker holds its lock (alive and ours), +/// Some(false) if nobody holds it, None if there is no lock to probe. +pub(crate) fn worker_alive(id: &str) -> Option { + if !valid(id) { + return None; + } + let path = dir()?.join(format!("{id}.lock")); + let f = OpenOptions::new().read(true).write(true).open(path).ok()?; + match f.try_lock() { + Ok(()) => { + let _ = f.unlock(); + Some(false) + } + Err(TryLockError::WouldBlock) => Some(true), + Err(TryLockError::Error(_)) => None, + } +} + +/// Is `p` a review stage dir THIS program created (an `agy-review-*` +/// directory directly inside the OS temp dir, not a symlink)? Only such a +/// path may be deleted on cancel. +pub(crate) fn is_our_stage_dir(p: &Path) -> bool { + let tmp = util::canonical_or_self(&std::env::temp_dir()); + let Ok(meta) = std::fs::symlink_metadata(p) else { + return false; + }; + meta.is_dir() + && !meta.file_type().is_symlink() + && p.parent().map(util::canonical_or_self).as_deref() == Some(tmp.as_path()) + && p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with("agy-review-")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::util::TempDir; + + #[test] + fn register_read_and_workspace_binding() { + let ws = TempDir::new("agy-ws-").unwrap(); + register("agy-0000aaaa", ws.path(), None); + let e = read("agy-0000aaaa").unwrap(); + assert_eq!(e.workspace, util::canonical_or_self(ws.path())); + assert!(read_for("agy-0000aaaa", ws.path()).is_some()); + let other = TempDir::new("agy-ws-").unwrap(); + assert!( + read_for("agy-0000aaaa", other.path()).is_none(), + "bound to its workspace" + ); + update("agy-0000aaaa", |e| { + e.pid = Some(4242); + e.child_pid = Some(1); // pid 1 is never accepted + }); + let e = read("agy-0000aaaa").unwrap(); + assert_eq!(e.pid, Some(4242)); + assert_eq!(e.child_pid, None); + assert!(read("../../etc/passwd").is_none()); + remove("agy-0000aaaa"); + assert!(read("agy-0000aaaa").is_none()); + } + + #[test] + fn lock_proves_liveness() { + assert_eq!(worker_alive("agy-0000bbbb"), None, "no lock file yet"); + let held = hold("agy-0000bbbb").unwrap(); + assert_eq!(worker_alive("agy-0000bbbb"), Some(true)); + drop(held); + assert_eq!(worker_alive("agy-0000bbbb"), Some(false)); + } + + #[cfg(unix)] + #[test] + fn registry_dir_is_private() { + use std::os::unix::fs::PermissionsExt; + let ws = TempDir::new("agy-ws-").unwrap(); + register("agy-0000cccc", ws.path(), None); + let mode = std::fs::metadata(dir().unwrap()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o700); + } + + #[test] + fn only_our_stage_dirs_qualify_for_deletion() { + let ours = TempDir::new("agy-review-").unwrap(); + assert!(is_our_stage_dir(ours.path())); + let other = TempDir::new("agy-run-").unwrap(); + assert!(!is_our_stage_dir(other.path())); + let home = util::home_dir().unwrap_or_default(); + assert!(!is_our_stage_dir(&home)); + assert!(!is_our_stage_dir(Path::new("/"))); + let nested = ours.path().join("agy-review-x"); + std::fs::create_dir(&nested).unwrap(); + assert!( + !is_our_stage_dir(&nested), + "must sit directly in the temp dir" + ); + #[cfg(unix)] + { + let link = std::env::temp_dir().join(format!("agy-review-link{}", util::random_hex(4))); + std::os::unix::fs::symlink(&home, &link).unwrap(); + assert!(!is_our_stage_dir(&link), "a symlink is never ours"); + std::fs::remove_file(&link).unwrap(); + } + } +} diff --git a/src/render.rs b/src/render.rs new file mode 100644 index 0000000..2ec28e6 --- /dev/null +++ b/src/render.rs @@ -0,0 +1,600 @@ +//! Pure formatting for the companion's stdout (port of lib/render.mjs). +//! +//! Output is byte-identical to the Node runtime for every record either +//! runtime writes. Job records are untrusted JSON (a user or another tool can +//! edit `.agy-plugin/jobs/*.json`), so field access follows JS semantics — +//! `String(x)`, `x ?? d`, truthiness — instead of assuming types; that keeps +//! odd records rendering the way they used to, and never panics. + +use crate::json::{Value, to_string_compact}; +use crate::time::{iso_from_millis, parse_iso_millis}; + +const MS_PER_DAY: i64 = 86_400_000; +const JS_MAX_MS: i64 = 8_640_000_000_000_000; +const DASH: &str = "—"; + +/// How a cancel attempt ended (the JS `outcome` object, typed). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum CancelOutcome { + Canceled { reason: String }, + NotFound, + NotCancelable { status: Option }, +} + +pub(crate) fn status_badge(status: &str) -> String { + match status { + "pending" => "[pending]".to_string(), + "running" => "[running]".to_string(), + "completed" => "[done]".to_string(), + "failed" => "[failed]".to_string(), + "canceled" => "[cancel]".to_string(), + other => format!("[{other}]"), + } +} + +/// Timestamp column: `HH:MM:SS` when it falls on the same UTC day as +/// `now_ms`, else `YYYY-MM-DD HH:MM:SS`; `—` when absent/empty; the raw +/// text when unparseable. +pub(crate) fn short_time(iso: Option<&str>, now_ms: i64) -> String { + match iso { + None | Some("") => DASH.to_string(), + Some(s) => match parse_iso_millis(s) { + Some(ms) => short_time_ms(ms, now_ms), + None => s.to_string(), + }, + } +} + +fn short_time_ms(ms: i64, now_ms: i64) -> String { + let iso = iso_from_millis(ms); + // JS slices fixed positions of toISOString(); for extended years + // (`+010000-…`) that yields a shifted slice, reproduced as-is. The ISO + // string is ASCII, so byte slicing is char slicing. + if ms.div_euclid(MS_PER_DAY) == now_ms.div_euclid(MS_PER_DAY) { + iso.get(11..19).unwrap_or_default().to_string() + } else { + iso.get(0..19).unwrap_or_default().replacen('T', " ", 1) + } +} + +/// `shortTime(v)` for an arbitrary record field, mirroring `new Date(v)` +/// for the non-string values a hand-edited record may hold. +fn short_time_value(v: Option<&Value>, now_ms: i64) -> String { + match v { + None | Some(Value::Null) => DASH.to_string(), + Some(Value::String(s)) => short_time(Some(s), now_ms), + Some(Value::Bool(false)) => DASH.to_string(), + Some(Value::Bool(true)) => short_time_ms(1, now_ms), + Some(Value::Number(n)) => { + if *n == 0.0 || n.is_nan() { + DASH.to_string() + } else if n.is_finite() && n.trunc().abs() <= JS_MAX_MS as f64 { + // TimeClip truncates toward zero; the range check makes the + // cast exact. + short_time_ms(n.trunc() as i64, now_ms) + } else { + js_string(v) + } + } + // new Date(array|object) goes through ToPrimitive -> string. + Some(other) => { + let s = js_string(Some(other)); + match parse_iso_millis(&s) { + Some(ms) => short_time_ms(ms, now_ms), + None => s, + } + } + } +} + +/// Length in UTF-16 code units, which is what JS `.length` counts. +fn utf16_len(s: &str) -> usize { + s.chars().map(char::len_utf16).sum() +} + +/// Clip to `max` UTF-16 units, ending in `…` when clipped (JS parity). +/// +/// When JS's `slice` cuts an astral character in half it keeps a lone high +/// surrogate, which Node writes to stdout as U+FFFD; we emit U+FFFD in that +/// spot so the bytes on stdout match. +pub(crate) fn clip(s: &str, max: usize) -> String { + if utf16_len(s) <= max { + return s.to_string(); + } + let keep = max.saturating_sub(1); + let mut out = String::new(); + let mut units = 0; + for c in s.chars() { + let w = c.len_utf16(); + if units + w > keep { + if units < keep { + out.push('\u{FFFD}'); + } + break; + } + out.push(c); + units += w; + } + out.push('…'); + out +} + +/// `String.prototype.padEnd(n)` with spaces, counting UTF-16 units. +fn pad_end(s: &str, n: usize) -> String { + let mut out = s.to_string(); + for _ in utf16_len(s)..n { + out.push(' '); + } + out +} + +/// JS `String(v)`; `None` is `undefined`. +fn js_string(v: Option<&Value>) -> String { + match v { + None => "undefined".to_string(), + Some(Value::Null) => "null".to_string(), + Some(Value::Bool(b)) => b.to_string(), + Some(n @ Value::Number(_)) => to_string_compact(n), + Some(Value::String(s)) => s.clone(), + // Array.prototype.join: null/undefined elements become "". + Some(Value::Array(a)) => a + .iter() + .map(|e| { + if e.is_null() { + String::new() + } else { + js_string(Some(e)) + } + }) + .collect::>() + .join(","), + Some(Value::Object(_)) => "[object Object]".to_string(), + } +} + +/// JS `String(v ?? default)`. +fn or_default(v: Option<&Value>, default: &str) -> String { + match v { + None | Some(Value::Null) => default.to_string(), + some => js_string(some), + } +} + +fn truthy(v: Option<&Value>) -> bool { + match v { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(Value::Number(n)) => *n != 0.0 && !n.is_nan(), + Some(Value::String(s)) => !s.is_empty(), + Some(Value::Array(_) | Value::Object(_)) => true, + } +} + +fn badge_of(r: &Value) -> String { + status_badge(&js_string(r.get("status"))) +} + +/// Multi-job table for /agy:status. +pub(crate) fn render_status_list(records: &[Value], now_ms: i64) -> String { + if records.is_empty() { + return "No agy jobs recorded in this workspace yet.\n".to_string(); + } + let mut lines = vec!["ID STATUS KIND STARTED TASK".to_string()]; + for r in records { + let started = match r.get("startedAt") { + None | Some(Value::Null) => r.get("createdAt"), + some => some, + }; + lines.push( + [ + pad_end(&js_string(r.get("id")), 13), + pad_end(&badge_of(r), 9), + pad_end(&clip(&or_default(r.get("kind"), ""), 17), 18), + pad_end(&short_time_value(started, now_ms), 9), + clip(&or_default(r.get("task"), ""), 48), + ] + .join(" "), + ); + } + lines.join("\n") + "\n" +} + +/// Single-job detail block for /agy:status . +pub(crate) fn render_job_detail(record: Option<&Value>, now_ms: i64) -> String { + let Some(r) = record.filter(|r| truthy(Some(r))) else { + return "Job not found.\n".to_string(); + }; + let mut lines = vec![ + format!("Job: {}", js_string(r.get("id"))), + format!("Status: {}", badge_of(r)), + format!("Kind: {}", or_default(r.get("kind"), DASH)), + format!("Model: {}", or_default(r.get("model"), "(default)")), + format!( + "Task: {}", + clip(&or_default(r.get("task"), ""), 200) + ), + format!( + "Created: {}", + short_time_value(r.get("createdAt"), now_ms) + ), + format!( + "Started: {}", + short_time_value(r.get("startedAt"), now_ms) + ), + format!( + "Completed: {}", + short_time_value(r.get("completedAt"), now_ms) + ), + format!("Exit code: {}", or_default(r.get("exitCode"), DASH)), + format!("PID: {}", or_default(r.get("pid"), DASH)), + format!("Log file: {}", or_default(r.get("logFile"), DASH)), + format!("Workspace: {}", or_default(r.get("workspaceRoot"), DASH)), + ]; + if truthy(r.get("livenessDowngrade")) { + lines.push( + "Note: PID is dead but the record claimed running; treated as failed." + .to_string(), + ); + } + lines.join("\n") + "\n" +} + +/// /agy:result output: the detail block, then the captured log. +pub(crate) fn render_result(record: Option<&Value>, log: &str, now_ms: i64) -> String { + if !record.is_some_and(|r| truthy(Some(r))) { + return "No job to report on.\n".to_string(); + } + let head = render_job_detail(record, now_ms); + let body = if log.is_empty() { + "(log file is empty or missing)" + } else { + log + }; + let nl = if body.ends_with('\n') { "" } else { "\n" }; + format!("{head}\n--- output ---\n{body}{nl}") +} + +/// /agy:cancel report — one paragraph the user can paste into a ticket. +pub(crate) fn render_cancel_report(id: &str, outcome: &CancelOutcome) -> String { + match outcome { + CancelOutcome::Canceled { reason } => format!("Job {id}: canceled ({reason}).\n"), + CancelOutcome::NotFound => format!("Job {id}: not found in this workspace.\n"), + CancelOutcome::NotCancelable { status } => format!( + "Job {id}: already finished (status: {}); nothing to cancel.\n", + status.as_deref().unwrap_or("unknown") + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::json::parse; + + // Expected outputs below were generated by running the original + // lib/render.mjs under Node with `Date` pinned to NOW (scratchpad + // gen_render.mjs). Lone surrogates were passed through Node's UTF-8 + // encoder, i.e. they are the exact bytes Node writes to stdout. + const NOW: i64 = 1779993000000; + const JS_LIST_JSON: &str = r##"[{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-abcdef99","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"completed","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-27T23:59:59.999Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-pending1","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"pending","createdAt":"2026-05-28T00:00:00.000Z","startedAt":null,"completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-failed01","kind":"adversarial-review-extended","task":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","model":"opus","status":"failed","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-cancel01","kind":"rescue","task":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy😀😀","model":"opus","status":"canceled","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-cancel02","kind":"rescue","task":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy😀😀","model":"opus","status":"canceled","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-weird-status-and-long-id","kind":null,"task":null,"model":"opus","status":"weird","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-bare"},{"id":"agy-ts","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"not a date","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-ts2","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T20:00:00+02:00","startedAt":"","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-ts3","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"+010000-01-01T00:00:00.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-ts4","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":1780000000000,"completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"},{"id":"agy-ts5","kind":"ünïcödé-kind-name-long","task":"привет мир","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"1969-12-31T23:59:59.999Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}]"##; + const JS_LIST: &str = "ID STATUS KIND STARTED TASK\nagy-3a7b9c12 [running] rescue 15:00:01 investigate the flaky integration test\nagy-abcdef99 [done] rescue 2026-05-27 23:59:59 investigate the flaky integration test\nagy-pending1 [pending] rescue 00:00:00 investigate the flaky integration test\nagy-failed01 [failed] adversarial-revi\u{2026} 15:00:01 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\u{2026}\nagy-cancel01 [cancel] rescue 15:00:01 yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\u{fffd}\u{2026}\nagy-cancel02 [cancel] rescue 15:00:01 yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\u{2026}\nagy-weird-status-and-long-id [weird] 15:00:01 \nagy-bare [undefined] \u{2014} \nagy-ts [running] rescue not a date investigate the flaky integration test\nagy-ts2 [running] rescue \u{2014} investigate the flaky integration test\nagy-ts3 [running] rescue +010000-01-01 00:00 investigate the flaky integration test\nagy-ts4 [running] rescue 20:26:40 investigate the flaky integration test\nagy-ts5 [running] ünïcödé-kind-nam\u{2026} 1969-12-31 23:59:59 привет мир\n"; + const JS_DETAIL_SAMPLE_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}"##; + const JS_DETAIL_SAMPLE: &str = "Job: agy-3a7b9c12\nStatus: [running]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: \u{2014}\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n"; + const JS_DETAIL_MINIMAL_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":null,"status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":null,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}"##; + const JS_DETAIL_MINIMAL: &str = "Job: agy-3a7b9c12\nStatus: [running]\nKind: rescue\nModel: (default)\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: \u{2014}\nPID: \u{2014}\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n"; + const JS_DETAIL_DOWNGRADE_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"failed","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":"2026-05-28T15:10:00.000Z","exitCode":1,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo","livenessDowngrade":true}"##; + const JS_DETAIL_DOWNGRADE: &str = "Job: agy-3a7b9c12\nStatus: [failed]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: 15:10:00\nExit code: 1\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\nNote: PID is dead but the record claimed running; treated as failed.\n"; + const JS_DETAIL_EMPTY_MODEL_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":"2025-12-31T23:59:59.000Z","exitCode":0,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}"##; + const JS_DETAIL_EMPTY_MODEL: &str = "Job: agy-3a7b9c12\nStatus: [running]\nKind: rescue\nModel: \nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: 2025-12-31 23:59:59\nExit code: 0\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n"; + const JS_DETAIL_LONG_TASK_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz😀tail","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}"##; + const JS_DETAIL_LONG_TASK: &str = "Job: agy-3a7b9c12\nStatus: [running]\nKind: rescue\nModel: opus\nTask: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\u{2026}\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: \u{2014}\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n"; + const JS_DETAIL_ODD_TYPES_JSON: &str = r##"{"id":42,"status":true,"kind":7,"model":false,"task":["a",null,3],"exitCode":1.5,"pid":1e+21,"logFile":{},"workspaceRoot":[],"livenessDowngrade":"yes","createdAt":0,"startedAt":true,"completedAt":1780000000000.9}"##; + const JS_DETAIL_ODD_TYPES: &str = "Job: 42\nStatus: [true]\nKind: 7\nModel: false\nTask: a,,3\nCreated: \u{2014}\nStarted: 1970-01-01 00:00:00\nCompleted: 20:26:40\nExit code: 1.5\nPID: 1e+21\nLog file: [object Object]\nWorkspace: \nNote: PID is dead but the record claimed running; treated as failed.\n"; + const JS_DETAIL_EMPTY_OBJ_JSON: &str = r##"{}"##; + const JS_DETAIL_EMPTY_OBJ: &str = "Job: undefined\nStatus: [undefined]\nKind: \u{2014}\nModel: (default)\nTask: \nCreated: \u{2014}\nStarted: \u{2014}\nCompleted: \u{2014}\nExit code: \u{2014}\nPID: \u{2014}\nLog file: \u{2014}\nWorkspace: \u{2014}\n"; + const JS_DETAIL_FALSY_DOWNGRADE_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"running","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":null,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo","livenessDowngrade":0}"##; + const JS_DETAIL_FALSY_DOWNGRADE: &str = "Job: agy-3a7b9c12\nStatus: [running]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: \u{2014}\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n"; + const JS_RESULT_JSON: &str = r##"{"id":"agy-3a7b9c12","kind":"rescue","task":"investigate the flaky integration test","model":"opus","status":"completed","createdAt":"2026-05-28T15:00:00.000Z","startedAt":"2026-05-28T15:00:01.000Z","completedAt":null,"exitCode":0,"pid":12345,"logFile":".agy-plugin/logs/agy-3a7b9c12.log","workspaceRoot":"/repo"}"##; + const JS_RESULT_LOG: &str = "Job: agy-3a7b9c12\nStatus: [done]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: 0\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n\n--- output ---\nthe agy reply\n"; + const JS_RESULT_EMPTY: &str = "Job: agy-3a7b9c12\nStatus: [done]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: 0\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n\n--- output ---\n(log file is empty or missing)\n"; + const JS_RESULT_NO_NL: &str = "Job: agy-3a7b9c12\nStatus: [done]\nKind: rescue\nModel: opus\nTask: investigate the flaky integration test\nCreated: 15:00:00\nStarted: 15:00:01\nCompleted: \u{2014}\nExit code: 0\nPID: 12345\nLog file: .agy-plugin/logs/agy-3a7b9c12.log\nWorkspace: /repo\n\n--- output ---\nno trailing newline here\n"; + const JS_RESULT_NULL: &str = "No job to report on.\n"; + const JS_DETAIL_NULL: &str = "Job not found.\n"; + const JS_LIST_EMPTY: &str = "No agy jobs recorded in this workspace yet.\n"; + const JS_CANCEL_OK: &str = "Job agy-12345678: canceled (killed).\n"; + const JS_CANCEL_NF: &str = "Job agy-deadbeef: not found in this workspace.\n"; + const JS_CANCEL_NC: &str = + "Job agy-12345678: already finished (status: completed); nothing to cancel.\n"; + const JS_CANCEL_NC_UNKNOWN: &str = + "Job agy-12345678: already finished (status: unknown); nothing to cancel.\n"; + + fn v(json: &str) -> Value { + match parse(json) { + Ok(v) => v, + Err(e) => panic!("bad test JSON: {e}"), + } + } + + fn detail(json: &str) -> String { + render_job_detail(Some(&v(json)), NOW) + } + + // --- byte-identity with Node --- + + #[test] + fn js_status_list() { + let list = v(JS_LIST_JSON); + let records = list.as_array().unwrap_or_default(); + assert_eq!(records.len(), 13); + assert_eq!(render_status_list(records, NOW), JS_LIST); + assert_eq!(render_status_list(&[], NOW), JS_LIST_EMPTY); + } + + #[test] + fn js_job_details() { + assert_eq!(detail(JS_DETAIL_SAMPLE_JSON), JS_DETAIL_SAMPLE); + assert_eq!(detail(JS_DETAIL_MINIMAL_JSON), JS_DETAIL_MINIMAL); + assert_eq!(detail(JS_DETAIL_DOWNGRADE_JSON), JS_DETAIL_DOWNGRADE); + assert_eq!(detail(JS_DETAIL_EMPTY_MODEL_JSON), JS_DETAIL_EMPTY_MODEL); + assert_eq!(detail(JS_DETAIL_LONG_TASK_JSON), JS_DETAIL_LONG_TASK); + assert_eq!(detail(JS_DETAIL_ODD_TYPES_JSON), JS_DETAIL_ODD_TYPES); + assert_eq!(detail(JS_DETAIL_EMPTY_OBJ_JSON), JS_DETAIL_EMPTY_OBJ); + assert_eq!( + detail(JS_DETAIL_FALSY_DOWNGRADE_JSON), + JS_DETAIL_FALSY_DOWNGRADE + ); + assert_eq!(render_job_detail(None, NOW), JS_DETAIL_NULL); + } + + #[test] + fn js_results() { + let r = v(JS_RESULT_JSON); + assert_eq!( + render_result(Some(&r), "the agy reply\n", NOW), + JS_RESULT_LOG + ); + assert_eq!(render_result(Some(&r), "", NOW), JS_RESULT_EMPTY); + assert_eq!( + render_result(Some(&r), "no trailing newline here", NOW), + JS_RESULT_NO_NL + ); + assert_eq!(render_result(None, "anything", NOW), JS_RESULT_NULL); + } + + #[test] + fn js_cancel_reports() { + let ok = CancelOutcome::Canceled { + reason: "killed".to_string(), + }; + assert_eq!(render_cancel_report("agy-12345678", &ok), JS_CANCEL_OK); + assert_eq!( + render_cancel_report("agy-deadbeef", &CancelOutcome::NotFound), + JS_CANCEL_NF + ); + let nc = CancelOutcome::NotCancelable { + status: Some("completed".to_string()), + }; + assert_eq!(render_cancel_report("agy-12345678", &nc), JS_CANCEL_NC); + let nc = CancelOutcome::NotCancelable { status: None }; + assert_eq!( + render_cancel_report("agy-12345678", &nc), + JS_CANCEL_NC_UNKNOWN + ); + } + + // --- ported from tests/lib.render.test.mjs --- + + #[test] + fn list_empty_state() { + assert!( + render_status_list(&[], NOW) + .to_lowercase() + .contains("no agy jobs") + ); + } + + #[test] + fn list_header_plus_rows() { + let a = v(JS_DETAIL_SAMPLE_JSON); + let mut b = a.clone(); + if let Some(m) = b.as_object_mut() { + m.set("id", "agy-abcdef99"); + m.set("status", "completed"); + } + let out = render_status_list(&[a, b], NOW); + let lines: Vec<&str> = out.trim().split('\n').collect(); + assert_eq!(lines.len(), 3); + assert!(lines[0].starts_with("ID STATUS KIND")); + assert!(lines[1].contains("agy-3a7b9c12")); + assert!(lines[1].contains("[running]")); + assert!(lines[2].contains("agy-abcdef99")); + assert!(lines[2].contains("[done]")); + } + + #[test] + fn list_clips_long_task() { + let mut r = v(JS_DETAIL_SAMPLE_JSON); + if let Some(m) = r.as_object_mut() { + m.set("task", "x".repeat(200)); + } + let out = render_status_list(&[r], NOW); + assert!(out.contains('…')); + assert!(!out.contains(&"x".repeat(48))); + } + + #[test] + fn detail_headline_fields_and_nulls() { + let out = detail(JS_DETAIL_SAMPLE_JSON); + for s in [ + "agy-3a7b9c12", + "[running]", + "rescue", + "opus", + "investigate the flaky integration test", + "12345", + ".agy-plugin/logs/agy-3a7b9c12.log", + ] { + assert!(out.contains(s), "{s}"); + } + let out = detail(JS_DETAIL_MINIMAL_JSON); + assert!(out.contains("Model: (default)\n")); + assert!(out.contains("Completed: —\n")); + assert!(out.contains("Exit code: —\n")); + assert!(out.contains("PID: —\n")); + assert!(!out.contains("PID is dead")); + assert!(detail(JS_DETAIL_DOWNGRADE_JSON).contains("PID is dead")); + } + + #[test] + fn detail_not_found_for_falsy_records() { + for r in ["null", "false", "0", "\"\""] { + assert_eq!(detail(r), "Job not found.\n", "{r}"); + assert_eq!( + render_result(Some(&v(r)), "x", NOW), + "No job to report on.\n" + ); + } + } + + #[test] + fn result_layout() { + let r = v(JS_RESULT_JSON); + let out = render_result(Some(&r), "the agy reply\n", NOW); + assert!(out.contains("agy-3a7b9c12")); + assert!(out.contains("\n\n--- output ---\nthe agy reply\n")); + assert!(out.ends_with("reply\n") && !out.ends_with("\n\n")); + assert!(render_result(Some(&r), "", NOW).contains("(log file is empty")); + assert!(render_result(Some(&r), "x", NOW).ends_with("x\n")); + } + + #[test] + fn cancel_reports_text() { + let r = render_cancel_report( + "agy-12345678", + &CancelOutcome::Canceled { + reason: "killed".to_string(), + }, + ); + assert_eq!(r, "Job agy-12345678: canceled (killed).\n"); + assert!(render_cancel_report("x", &CancelOutcome::NotFound).contains("not found")); + } + + // --- helpers --- + + #[test] + fn badges() { + assert_eq!(status_badge("pending"), "[pending]"); + assert_eq!(status_badge("running"), "[running]"); + assert_eq!(status_badge("completed"), "[done]"); + assert_eq!(status_badge("failed"), "[failed]"); + assert_eq!(status_badge("canceled"), "[cancel]"); + assert_eq!(status_badge(""), "[]"); + assert_eq!(status_badge("Running"), "[Running]"); + // JS looked these up on a plain object and crashed or printed a + // function body; we just bracket them. + assert_eq!(status_badge("constructor"), "[constructor]"); + assert_eq!(status_badge("__proto__"), "[__proto__]"); + } + + #[test] + fn short_time_cases() { + assert_eq!(short_time(None, NOW), "—"); + assert_eq!(short_time(Some(""), NOW), "—"); + assert_eq!(short_time(Some("garbage"), NOW), "garbage"); + assert_eq!( + short_time(Some("2026-05-28T00:00:00.000Z"), NOW), + "00:00:00" + ); + assert_eq!( + short_time(Some("2026-05-28T23:59:59.999Z"), NOW), + "23:59:59" + ); + assert_eq!( + short_time(Some("2026-05-29T00:00:00.000Z"), NOW), + "2026-05-29 00:00:00" + ); + assert_eq!( + short_time(Some("2026-05-27T23:59:59.999Z"), NOW), + "2026-05-27 23:59:59" + ); + // Offsets are normalised to UTC before comparing days. + assert_eq!( + short_time(Some("2026-05-29T01:00:00+02:00"), NOW), + "23:00:00" + ); + // Pre-1970 `now` and record. + let pre = -86_400_000 + 5_000; + assert_eq!(short_time(Some("1969-12-31T12:00:00Z"), pre), "12:00:00"); + assert_eq!( + short_time(Some("1970-01-01T00:00:00Z"), pre), + "1970-01-01 00:00:00" + ); + // Extreme `now` must not overflow. + assert_eq!( + short_time(Some("2026-05-28T00:00:00Z"), i64::MIN), + "2026-05-28 00:00:00" + ); + } + + #[test] + fn clip_cases() { + assert_eq!(clip("abc", 3), "abc"); + assert_eq!(clip("abcd", 3), "ab…"); + assert_eq!(clip("", 0), ""); + assert_eq!(clip("a", 0), "…"); + assert_eq!(clip("ab", 1), "…"); + // UTF-16 counting: 😀 is two units. + assert_eq!(clip("😀", 2), "😀"); + assert_eq!(clip("😀a", 2), "\u{fffd}…"); + assert_eq!(clip("a😀b", 3), "a\u{fffd}…"); + assert_eq!(clip("a😀bc", 4), "a😀…"); + assert_eq!(clip("привет", 4), "при…"); + } + + #[test] + fn pad_end_counts_utf16() { + assert_eq!(pad_end("ab", 4), "ab "); + assert_eq!(pad_end("😀", 4), "😀 "); + assert_eq!(pad_end("toolong", 3), "toolong"); + } + + #[test] + fn js_string_conversions() { + assert_eq!(js_string(None), "undefined"); + assert_eq!(js_string(Some(&v("null"))), "null"); + assert_eq!( + js_string(Some(&v("[1,[2,null],\"x\",{}]"))), + "1,2,,x,[object Object]" + ); + assert_eq!(js_string(Some(&v("1e21"))), "1e+21"); + assert_eq!(js_string(Some(&v("-0"))), "0"); + assert_eq!(or_default(Some(&v("null")), "d"), "d"); + assert_eq!(or_default(Some(&v("\"\"")), "d"), ""); + assert!(!truthy(Some(&v("0")))); + assert!(truthy(Some(&v("[]")))); + assert!(truthy(Some(&v("\"0\"")))); + } + + #[test] + fn hostile_records_do_not_panic() { + let nasty = [ + "[]", + "[1,2]", + "\"str\"", + "1e308", + "{\"id\":null,\"status\":null,\"startedAt\":1e300,\"createdAt\":-1e300}", + "{\"startedAt\":-9e15,\"completedAt\":9e15,\"createdAt\":\"+275760-09-13T00:00:00.001Z\"}", + "{\"startedAt\":{\"a\":1},\"createdAt\":[\"2026-05-28T01:02:03Z\"]}", + "{\"task\":\"\\ud83d\",\"id\":\"\\u0000\\u001b[31m\"}", + ]; + for j in nasty { + let r = v(j); + let _ = render_job_detail(Some(&r), NOW); + let _ = render_result(Some(&r), "log", i64::MAX); + let _ = render_status_list(std::slice::from_ref(&r), i64::MIN); + } + // Array-valued timestamp goes through ToPrimitive like new Date([s]). + let r = v("{\"id\":\"a\",\"startedAt\":[\"2026-05-28T01:02:03Z\"]}"); + assert!(render_status_list(&[r], NOW).contains("01:02:03 ")); + } +} diff --git a/src/secrets.rs b/src/secrets.rs new file mode 100644 index 0000000..db48082 --- /dev/null +++ b/src/secrets.rs @@ -0,0 +1,677 @@ +//! Best-effort secret detection for material we are about to ship to Gemini +//! (review diffs, full contents of changed files). +//! +//! Not a replacement for gitleaks/trufflehog: a small, conservative pattern +//! set that keeps false positives low. The old Node/Bash code used +//! case-insensitive regexes; there is no regex crate here, so every pattern is +//! a hand-written matcher with exactly the semantics of the JS regex (`/i`, +//! unanchored search). Equivalence was checked against V8 with a fuzz corpus; +//! the unit tests keep a fixed representative subset. + +/// Labels in table order. `scan_text` reports hits in this order. +const LABELS: [&str; 10] = [ + "AWS access key", + "AWS STS token", + "GitHub personal access token", + "GitHub fine-grained PAT", + "Slack token", + "Anthropic API key", + "OpenAI project key", + "OpenAI legacy API key", + "PEM private key block", + "inline credential assignment", +]; + +/// Scan raw text. Returns the labels of every pattern that matches anywhere, +/// in table order, each at most once. +pub(crate) fn scan_text(text: &str) -> Vec<&'static str> { + labels(scan_mask(text)) +} + +/// Scan only the ADDED lines of a unified diff. +/// +/// A line starting with `+` is added content, except the `+++ ` file header, +/// recognised as a `+++ ` line directly after a `--- ` line. (The old code +/// dropped every `+++` line, which also hid added content starting with `++`.) +/// Inside a hunk whose `@@` header counts we can follow, a `+++ ` line is +/// content even after a `--- ` line (a removed `-- x` next to an added +/// `++ y`); we scan that reading too and report the union, so we never find +/// less than the plain header rule would. +#[cfg_attr(not(test), allow(dead_code))] // review scans the whole diff (scan_text); kept for its tests +pub(crate) fn scan_diff(diff: &str) -> Vec<&'static str> { + let mut by_rule: Vec<&str> = Vec::new(); + let mut by_hunk: Vec<&str> = Vec::new(); + let mut differs = false; + let mut prev: &str = ""; + // Lines still expected in the current hunk (old side, new side). + let mut old_left: u64 = 0; + let mut new_left: u64 = 0; + + for line in diff.split('\n') { + let mut in_hunk = false; + if old_left > 0 || new_left > 0 { + match line.as_bytes().first() { + // Some tools strip the single space of an empty context line. + None | Some(b' ') => { + in_hunk = true; + old_left = old_left.saturating_sub(1); + new_left = new_left.saturating_sub(1); + } + Some(b'-') => { + in_hunk = true; + old_left = old_left.saturating_sub(1); + } + Some(b'+') => { + in_hunk = true; + new_left = new_left.saturating_sub(1); + } + Some(b'\\') => in_hunk = true, // "\ No newline at end of file" + Some(_) => { + // Counts did not add up: stop trusting them. + old_left = 0; + new_left = 0; + } + } + } + if !in_hunk && let Some((o, n)) = parse_hunk_header(line) { + old_left = o; + new_left = n; + } + + if let Some(content) = line.strip_prefix('+') { + let is_header = line.starts_with("+++ ") && prev.starts_with("--- "); + if !is_header { + by_rule.push(content); + } + if !is_header || in_hunk { + by_hunk.push(content); + } + if is_header && in_hunk { + differs = true; + } + } + prev = line; + } + + let mut mask = if by_rule.is_empty() { + 0 + } else { + scan_mask(&by_rule.join("\n")) + }; + if differs { + mask |= scan_mask(&by_hunk.join("\n")); + } + labels(mask) +} + +/// `@@ -a[,b] +c[,d] @@...` -> (b, d); a missing count means 1. +fn parse_hunk_header(line: &str) -> Option<(u64, u64)> { + let rest = line.strip_prefix("@@ -")?; + let (old, rest) = rest.split_once(' ')?; + let rest = rest.strip_prefix('+')?; + let (new, rest) = rest.split_once(' ')?; + if !rest.starts_with("@@") { + return None; + } + let count = |r: &str| -> Option { + match r.split_once(',') { + Some((start, n)) => { + start.parse::().ok()?; + n.parse::().ok() + } + None => r.parse::().ok().map(|_| 1), + } + }; + Some((count(old)?, count(new)?)) +} + +fn labels(mask: u16) -> Vec<&'static str> { + LABELS + .iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .map(|(_, l)| *l) + .collect() +} + +fn scan_mask(text: &str) -> u16 { + if text.is_empty() { + return 0; + } + let t = text.as_bytes(); + let checks: [bool; 10] = [ + // AKIA[0-9A-Z]{16} (/i also lets the class match lowercase) + prefixed_run(t, &[b"a", b"k", b"i", b"a"], is_alnum, 16), + // ASIA[0-9A-Z]{16} + prefixed_run(t, &[b"a", b"s", b"i", b"a"], is_alnum, 16), + // gh[pousr]_[A-Za-z0-9]{36,} + prefixed_run(t, &[b"g", b"h", b"pousr", b"_"], is_alnum, 36), + // github_pat_[A-Za-z0-9_]{40,} + prefixed_run(t, &atoms(b"github_pat_"), is_alnum_us, 40), + // xox[baprs]-[A-Za-z0-9-]{10,} + prefixed_run(t, &[b"x", b"o", b"x", b"baprs", b"-"], is_alnum_dash, 10), + // sk-ant-[A-Za-z0-9_-]{20,} + prefixed_run(t, &atoms(b"sk-ant-"), is_alnum_us_dash, 20), + // sk-proj-[A-Za-z0-9_-]{20,} + prefixed_run(t, &atoms(b"sk-proj-"), is_alnum_us_dash, 20), + // sk-[A-Za-z0-9]{20,} + prefixed_run(t, &atoms(b"sk-"), is_alnum, 20), + pem_block(t), + inline_credential(text), + ]; + checks + .iter() + .enumerate() + .filter(|(_, hit)| **hit) + .fold(0u16, |m, (i, _)| m | (1 << i)) +} + +/// One single-byte atom per byte of a literal. +fn atoms(lit: &'static [u8]) -> Vec<&'static [u8]> { + lit.chunks(1).collect() +} + +/// `/i` on a pattern made only of ASCII: without the `u` flag JS canonicalises +/// with toUpperCase but refuses to map a non-ASCII char onto an ASCII one +/// (so U+017F long s is not `s`, U+212A Kelvin is not `k`). Plain ASCII +/// case folding is therefore exact. +fn in_set(b: u8, set: &[u8]) -> bool { + set.iter().any(|s| s.eq_ignore_ascii_case(&b)) +} + +fn is_alnum(b: u8) -> bool { + b.is_ascii_alphanumeric() +} +fn is_alnum_us(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} +fn is_alnum_dash(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'-' +} +fn is_alnum_us_dash(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b == b'-' +} +/// `[A-Za-z0-9_+/=\-]` +fn is_value(b: u8) -> bool { + b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'/' | b'=' | b'-') +} + +/// `{min,}` searched anywhere. For a `.test()` only the +/// existence of `min` class bytes after the prefix matters; the greedy tail +/// cannot change that. +fn prefixed_run(t: &[u8], atoms: &[&[u8]], class: fn(u8) -> bool, min: usize) -> bool { + let need = atoms.len() + min; + if t.len() < need { + return false; + } + (0..=t.len() - need).any(|i| { + atoms.iter().enumerate().all(|(k, a)| in_set(t[i + k], a)) + && t[i + atoms.len()..i + need].iter().all(|&b| class(b)) + }) +} + +fn ci_starts_with(t: &[u8], at: usize, lit: &[u8]) -> bool { + t.get(at..at + lit.len()) + .is_some_and(|s| s.eq_ignore_ascii_case(lit)) +} + +/// `-----BEGIN [A-Z ]*PRIVATE KEY-----` (/i). +/// +/// `[A-Z ]*` backtracks, but "PRIVATE KEY" is itself made of class chars and +/// the following `-` is not, so a match exists iff the maximal class run after +/// "BEGIN " ends with "PRIVATE KEY" and is followed by "-----". +fn pem_block(t: &[u8]) -> bool { + const HEAD: &[u8] = b"-----begin "; + const TAIL: &[u8] = b"private key"; + let mut i = 0; + while i + HEAD.len() <= t.len() { + if ci_starts_with(t, i, HEAD) { + let j = i + HEAD.len(); + let mut r = j; + while r < t.len() && (t[r].is_ascii_alphabetic() || t[r] == b' ') { + r += 1; + } + if r - j >= TAIL.len() + && ci_starts_with(t, r - TAIL.len(), TAIL) + && ci_starts_with(t, r, b"-----") + { + return true; + } + } + i += 1; + } + false +} + +/// JS `\s`: WhiteSpace + LineTerminator (ECMA-262). Not Rust's +/// `char::is_whitespace`, which also accepts U+0085 and rejects U+FEFF. +/// Matching JS keeps parity with the old scanner and also catches +/// `password\u{a0}=\u{a0}...` (wider than the ASCII-only set in the spec). +fn is_js_space(c: char) -> bool { + matches!( + c, + '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}' + ..='\u{200A}' + | '\u{2028}' + | '\u{2029}' + | '\u{202F}' + | '\u{205F}' + | '\u{3000}' + | '\u{FEFF}' + ) +} + +fn skip_js_space(text: &str, mut p: usize) -> usize { + while let Some(c) = text.get(p..).and_then(|s| s.chars().next()) { + if !is_js_space(c) { + break; + } + p += c.len_utf8(); + } + p +} + +/// `(api[_-]?key|secret|token|password|access[_-]?key)\s*[=:]\s*["']?[A-Za-z0-9_+/=\-]{16,}` (/i) +/// +/// Tried at every start and every alternative. After the keyword the match is +/// deterministic: `\s*` must eat the whole whitespace run (`[=:]`, quotes and +/// value chars are not whitespace), and dropping an optional quote would make +/// the value class face the quote, which it rejects. +fn inline_credential(text: &str) -> bool { + const KEYWORDS: [&[u8]; 9] = [ + b"apikey", + b"api_key", + b"api-key", + b"secret", + b"token", + b"password", + b"accesskey", + b"access_key", + b"access-key", + ]; + let t = text.as_bytes(); + for i in 0..t.len() { + if !matches!(t[i].to_ascii_lowercase(), b'a' | b's' | b't' | b'p') { + continue; + } + for kw in KEYWORDS { + if !ci_starts_with(t, i, kw) { + continue; + } + // Keyword is ASCII, so i + len is a char boundary. + let mut p = skip_js_space(text, i + kw.len()); + if !matches!(t.get(p), Some(b'=' | b':')) { + continue; + } + p = skip_js_space(text, p + 1); + if matches!(t.get(p), Some(b'"' | b'\'')) { + p += 1; + } + if t.get(p..p + 16) + .is_some_and(|v| v.iter().all(|&b| is_value(b))) + { + return true; + } + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + fn d(lines: &[&str]) -> String { + lines.join("\n") + } + + // ---- ported from tests/lib.secrets.test.mjs ------------------------- + + #[test] + fn clean_diff_returns_no_hits() { + assert!(scan_diff(&d(&["+const x = 1;", "-let y = 2;"])).is_empty()); + } + + #[test] + fn empty_input() { + assert!(scan_diff("").is_empty()); + assert!(scan_text("").is_empty()); + } + + #[test] + fn aws_key_in_added_line() { + assert!(scan_diff("+key = \"AKIAIOSFODNN7EXAMPLE\"").contains(&"AWS access key")); + } + + #[test] + fn github_pat_in_added_line() { + assert!( + scan_diff("+t = \"ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ\"") + .contains(&"GitHub personal access token") + ); + } + + #[test] + fn pem_in_added_line() { + assert!(scan_diff("+-----BEGIN RSA PRIVATE KEY-----").contains(&"PEM private key block")); + // bats variant: header line plus body line + assert!( + scan_diff(&d(&[ + "+-----BEGIN RSA PRIVATE KEY-----", + "+MIIEpAIBAAKCAQEAabc..." + ])) + .contains(&"PEM private key block") + ); + } + + #[test] + fn inline_credential_in_added_line() { + assert!( + scan_diff("+API_KEY = \"abcdef0123456789ABCDEF0123456789\"") + .contains(&"inline credential assignment") + ); + } + + #[test] + fn removed_lines_ignored() { + assert!(scan_diff("-AWS = \"AKIAIOSFODNN7EXAMPLE\"").is_empty()); + assert!(scan_diff("-AWS_KEY = \"AKIAIOSFODNN7EXAMPLE\"").is_empty()); + } + + #[test] + fn context_lines_ignored() { + assert!(scan_diff(" AWS = \"AKIAIOSFODNN7EXAMPLE\"").is_empty()); + } + + #[test] + fn file_header_ignored_even_if_it_looks_like_a_key() { + // Adapted: the header is only recognised after a `--- ` line, as git + // always emits it. + assert!( + scan_diff(&d(&[ + "--- a/AKIAIOSFODNN7EXAMPLE.txt", + "+++ b/AKIAIOSFODNN7EXAMPLE.txt", + "+hello" + ])) + .is_empty() + ); + assert!( + scan_diff(&d(&[ + "--- /dev/null", + "+++ b/secrets/AKIAIOSFODNN7EXAMPLE.txt", + "+hello" + ])) + .is_empty() + ); + } + + #[test] + fn benign_diff_with_headers() { + assert!( + scan_diff(&d(&[ + "--- a/foo.txt", + "+++ b/foo.txt", + "+hello world", + "+function add(a, b) { return a + b; }", + "-let x = 1;" + ])) + .is_empty() + ); + } + + #[test] + fn benign_code_reference_not_flagged() { + assert!(scan_diff("+const password = formData.password;").is_empty()); + } + + #[test] + fn case_insensitive() { + assert!(scan_diff("+x = \"akiaiosfodnn7example\"").contains(&"AWS access key")); + assert!( + scan_diff("+x = \"GHP_ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ\"") + .contains(&"GitHub personal access token") + ); + } + + #[test] + fn fine_grained_pat() { + let tok = format!("github_pat_{}", "A".repeat(82)); + assert!(scan_diff(&format!("+token = \"{tok}\"")).contains(&"GitHub fine-grained PAT")); + } + + #[test] + fn scan_text_needs_no_plus_prefix() { + assert!(scan_text("const k = \"AKIAIOSFODNN7EXAMPLE\";").contains(&"AWS access key")); + } + + #[test] + fn modern_api_keys() { + let ant = format!("sk-ant-api03-{}", "A".repeat(30)); + let proj = format!("sk-proj-{}", "B".repeat(30)); + let legacy = format!("sk-{}", "c".repeat(40)); + assert!(scan_text(&ant).contains(&"Anthropic API key")); + assert!(scan_diff(&format!("+key = \"{ant}\"")).contains(&"Anthropic API key")); + assert!(scan_diff(&format!("+k = \"{ant}\"")).contains(&"Anthropic API key")); + assert!(scan_text(&proj).contains(&"OpenAI project key")); + assert!(scan_text(&legacy).contains(&"OpenAI legacy API key")); + } + + #[test] + fn dashed_identifier_with_sk_not_flagged() { + assert!(scan_text("disk-management-system-controller-v2").is_empty()); + } + + // ---- new behaviour -------------------------------------------------- + + #[test] + fn added_content_starting_with_plus_plus_is_scanned() { + // Old code dropped every `+++` line, hiding added `++ secret` content. + assert!(scan_diff("+++ AKIAIOSFODNN7EXAMPLE").contains(&"AWS access key")); + assert!( + scan_diff(&d(&["+x", "+++ token = AKIAIOSFODNN7EXAMPLE"])).contains(&"AWS access key") + ); + assert!(scan_diff("+++AKIAIOSFODNN7EXAMPLE").contains(&"AWS access key")); + } + + #[test] + fn plus_plus_content_after_minus_minus_inside_hunk_is_scanned() { + // Removed `-- old` then added `++ AKIA...` look like ---/+++ headers, + // but the hunk counts say they are content. + let diff = d(&[ + "--- a/f.sql", + "+++ b/f.sql", + "@@ -1,1 +1,1 @@", + "--- old comment", + "+++ AKIAIOSFODNN7EXAMPLE", + ]); + assert_eq!(scan_diff(&diff), vec!["AWS access key"]); + } + + #[test] + fn second_file_header_after_hunk_is_still_a_header() { + let diff = d(&[ + "--- a/x", + "+++ b/x", + "@@ -1 +1 @@", + "-a", + "+b", + "--- a/AKIAIOSFODNN7EXAMPLE", + "+++ b/AKIAIOSFODNN7EXAMPLE", + "@@ -0,0 +1 @@", + "+fine", + ]); + assert!(scan_diff(&diff).is_empty()); + } + + #[test] + fn hunk_header_parsing() { + assert_eq!(parse_hunk_header("@@ -1,3 +1,4 @@ fn x"), Some((3, 4))); + assert_eq!(parse_hunk_header("@@ -1 +1 @@"), Some((1, 1))); + assert_eq!(parse_hunk_header("@@ -0,0 +1 @@"), Some((0, 1))); + assert_eq!(parse_hunk_header("@@ -a +1 @@"), None); + assert_eq!(parse_hunk_header("@@ -1 +1"), None); + assert_eq!(parse_hunk_header("@@ -99999999999999999999999 +1 @@"), None); + } + + #[test] + fn crlf_diff_lines() { + assert!(scan_diff("+k = AKIAIOSFODNN7EXAMPLE\r\n-x\r\n").contains(&"AWS access key")); + } + + #[test] + fn labels_in_table_order_each_once() { + let text = format!( + "{} AKIAIOSFODNN7EXAMPLE AKIAIOSFODNN7EXAMPLE password: {}", + "-----BEGIN PRIVATE KEY-----", + "x".repeat(16) + ); + assert_eq!( + scan_text(&text), + vec![ + "AWS access key", + "PEM private key block", + "inline credential assignment" + ] + ); + } + + #[test] + fn each_pattern_boundaries() { + // exact minimum lengths match, one less does not + assert!(scan_text(&format!("AKIA{}", "Z".repeat(16))).contains(&"AWS access key")); + assert!(scan_text(&format!("AKIA{}", "Z".repeat(15))).is_empty()); + assert!(scan_text(&format!("asia{}", "9".repeat(16))).contains(&"AWS STS token")); + for c in ["p", "o", "u", "s", "r"] { + let tok = format!("gh{c}_{}", "a".repeat(36)); + assert!(scan_text(&tok).contains(&"GitHub personal access token")); + } + assert!(scan_text(&format!("ghx_{}", "a".repeat(36))).is_empty()); + assert!(scan_text(&format!("ghp_{}", "a".repeat(35))).is_empty()); + assert!( + scan_text(&format!("github_pat_{}", "_".repeat(40))) + .contains(&"GitHub fine-grained PAT") + ); + assert!(scan_text(&format!("github_pat_{}", "a".repeat(39))).is_empty()); + for c in ["b", "a", "p", "r", "s"] { + assert!(scan_text(&format!("xox{c}-1234567890")).contains(&"Slack token")); + } + assert!(scan_text("xoxb-123456789").is_empty()); + assert!(scan_text("xoxq-1234567890").is_empty()); + assert!(scan_text(&format!("sk-ant-{}", "-".repeat(20))).contains(&"Anthropic API key")); + assert!(scan_text(&format!("sk-ant-{}", "_".repeat(19))).is_empty()); + assert!(scan_text(&format!("SK-PROJ-{}", "_".repeat(20))).contains(&"OpenAI project key")); + assert!(scan_text(&format!("sk-{}", "a".repeat(19))).is_empty()); + } + + #[test] + fn non_ascii_is_never_case_folded_onto_ascii() { + // U+212A KELVIN SIGN lowercases to `k` in Unicode, but JS /i (no u flag) + // does not fold non-ASCII onto ASCII, and neither do we. + assert!(scan_text("api\u{212A}ey = abcdefghijklmnop").is_empty()); + assert!(scan_text("\u{17F}ecret = abcdefghijklmnop").is_empty()); + assert!(scan_text("secret = abcdefghijklmnop").contains(&"inline credential assignment")); + } + + #[test] + fn pem_variants() { + for ok in [ + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN OPENSSH PRIVATE KEY-----", + "-----begin ec private key-----", + "-----BEGIN ENCRYPTED PRIVATE KEY-----", + "x-----BEGIN PRIVATE KEY PRIVATE KEY-----", + "------BEGIN RSA PRIVATE KEY------", + ] { + assert!(scan_text(ok).contains(&"PEM private key block"), "{ok}"); + } + for bad in [ + "-----BEGIN PUBLIC KEY-----", + "-----BEGIN RSA-PRIVATE KEY-----", + "-----BEGIN PRIVATE KEY----", + "-----BEGINPRIVATE KEY-----", + "-----BEGIN PRIVATE KEY-----", + "-----BEGIN RSA2 PRIVATE KEY-----", + "-----BEGIN \nPRIVATE KEY-----", + ] { + assert!(scan_text(bad).is_empty(), "{bad}"); + } + } + + #[test] + fn inline_credential_variants() { + let v = "abcdefghijklmnop"; + for ok in [ + format!("api_key={v}"), + format!("API-KEY: '{v}'"), + format!("apikey\t=\t\"{v}"), + format!("x.secret = {v}"), + format!("Token:{v}"), + format!("PASSWORD = {v}"), + format!("access_key = {v}"), + format!("accesskey={v}"), + format!("access-key={v}"), + format!("password\n=\n{v}"), + format!("password\u{a0}=\u{3000}{v}"), + format!("password\u{feff}={v}"), + format!("token = ==============={v}"), + format!("token = {}", "+/=-_".repeat(4)), + ] { + assert!( + scan_text(&ok).contains(&"inline credential assignment"), + "{ok:?}" + ); + } + for bad in [ + format!("api__key={v}"), + format!("password = {}", &v[..15]), + format!("password = \"\"{v}"), + format!("password == {v}"), + format!("password :: {v}"), + "password = formData.password".to_string(), + format!("password - {v}"), + // U+0085 is Rust whitespace but not JS \s + format!("password\u{85}={v}"), + format!("token = `{v}`"), + format!("secretsecret=:{v}"), + ] { + assert!(scan_text(&bad).is_empty(), "{bad:?}"); + } + } + + /// Representative subset of the V8 differential corpus (strings that + /// exercise backtracking and boundaries), with the masks JS produced. + #[test] + fn js_differential_fixed_subset() { + let cases: &[(&str, u16)] = &[ + ("tokentoken = 0123456789abcdef", 1 << 9), + ("token = '0123456789abcde'", 0), + ("token=\"\"0123456789abcdef", 0), + ("ApI-KeY:\r\n\u{b}\u{c}'0123456789abcdef", 1 << 9), + ("sk-ant-sk-proj-abcdefghijklmnopqrst", (1 << 5) | (1 << 6)), + ("sk-projabcdefghijklmnopqrst", 1 << 7), + ("sk-proj-abcdefghij-lmnopqrst", 1 << 6), + ("xoxs------------", 1 << 4), + ("xoxs-----------", 1 << 4), + ("AKIAASIA0000000000000000", 1 | (1 << 1)), + ("ghs_ghs_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1 << 2), + ("-----BEGIN -----BEGIN PRIVATE KEY-----", 1 << 8), + ("-----BEGIN private keyprivate key-----", 1 << 8), + ("password\u{2028}:\u{2029}abcdefghijklmnop", 1 << 9), + ("password\u{180e}:abcdefghijklmnop", 0), + ("password\u{1c}:abcdefghijklmnop", 0), + ]; + for (text, mask) in cases { + assert_eq!(scan_mask(text), *mask, "{text:?}"); + } + } + + #[test] + fn hostile_inputs_do_not_panic() { + let big = "password=".repeat(10_000) + &"\u{3000}".repeat(10_000); + let _ = scan_text(&big); + let _ = scan_text(&"-----BEGIN ".repeat(5_000)); + let _ = scan_text("é\u{feff}𝔸 token:\u{200a}é"); + let _ = scan_diff("@@ -1,18446744073709551615 +1,18446744073709551615 @@\n+++ x\n\n\\"); + let _ = scan_diff("\n\n+\n+++\n--- \n+++ "); + } +} diff --git a/src/sys.rs b/src/sys.rs new file mode 100644 index 0000000..b69d001 --- /dev/null +++ b/src/sys.rs @@ -0,0 +1,247 @@ +//! OS calls std does not wrap: is a pid alive, stop a process tree, and +//! detach a background worker. Declared with `extern` against the C library +//! (Unix) and kernel32 (Windows), both of which every Rust binary already +//! links — no crates. + +use std::process::Command; +use std::time::{Duration, Instant}; + +#[cfg(unix)] +mod imp { + use std::os::raw::c_int; + + unsafe extern "C" { + fn kill(pid: c_int, sig: c_int) -> c_int; + } + + // Same values on Linux and macOS. + pub(super) const SIGTERM: c_int = 15; + pub(super) const SIGKILL: c_int = 9; + const EPERM: i32 = 1; + + /// kill(2) on `pid` (negative = whole process group). Returns Ok on + /// success, Err(errno) otherwise. + pub(super) fn send(pid: i64, sig: c_int) -> Result<(), i32> { + let Ok(p) = c_int::try_from(pid) else { + return Err(0); + }; + // SAFETY: kill(2) takes plain integers and has no memory effects. + let rc = unsafe { kill(p, sig) }; + if rc == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(0)) + } + } + + pub(super) fn alive(pid: u32) -> bool { + match send(i64::from(pid), 0) { + Ok(()) => !is_zombie(pid), + // The process exists but belongs to someone else. + Err(e) => e == EPERM, + } + } + + /// kill(pid, 0) succeeds on a zombie (exited, not yet reaped). An + /// orphaned worker is reaped by whatever subreaper adopted it, which on + /// CI runners can take a while; it is gone for our purposes. Linux only + /// (/proc); elsewhere launchd/init reap promptly. + fn is_zombie(pid: u32) -> bool { + #[cfg(target_os = "linux")] + { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + // "pid (comm) S ..." — comm may contain spaces/parens, so + // take the state after the LAST ')'. + if let Some(rest) = stat.rsplit_once(')') { + return rest.1.trim_start().starts_with('Z'); + } + } + false + } + #[cfg(not(target_os = "linux"))] + { + let _ = pid; + false + } + } +} + +#[cfg(windows)] +mod imp { + use std::ffi::c_void; + + type Handle = *mut c_void; + const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; + const STILL_ACTIVE: u32 = 259; + const ERROR_ACCESS_DENIED: i32 = 5; + + #[link(name = "kernel32")] + unsafe extern "system" { + fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle; + fn GetExitCodeProcess(process: Handle, code: *mut u32) -> i32; + fn CloseHandle(handle: Handle) -> i32; + } + + pub(super) fn alive(pid: u32) -> bool { + // SAFETY: plain Win32 calls; the handle is closed on every path. + unsafe { + let h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); + if h.is_null() { + // Exists but we may not query it. + return std::io::Error::last_os_error().raw_os_error() == Some(ERROR_ACCESS_DENIED); + } + let mut code: u32 = 0; + let ok = GetExitCodeProcess(h, &mut code) != 0; + CloseHandle(h); + ok && code == STILL_ACTIVE + } + } +} + +/// True if a process with this pid exists (pid 0 and absurd values: false). +pub(crate) fn process_alive(pid: u32) -> bool { + if pid == 0 || pid > i32::MAX as u32 { + return false; + } + imp::alive(pid) +} + +/// Stop a background worker AND everything it started (agy, its tools). +/// Workers are started as process-group leaders (see `detach`), so on Unix +/// we signal the group: SIGTERM, wait up to `grace`, then SIGKILL. On +/// Windows `taskkill /T` walks the process tree. Returns true if the worker +/// is gone afterwards. +pub(crate) fn terminate_tree(pid: u32, grace: Duration) -> bool { + if !process_alive(pid) { + return true; + } + #[cfg(unix)] + { + let group = -i64::from(pid); + // Fall back to the pid alone if it is not a group leader (a record + // from an older plugin version). + if imp::send(group, imp::SIGTERM).is_err() { + let _ = imp::send(i64::from(pid), imp::SIGTERM); + } + if wait_gone(pid, grace) { + return true; + } + if imp::send(group, imp::SIGKILL).is_err() { + let _ = imp::send(i64::from(pid), imp::SIGKILL); + } + } + #[cfg(windows)] + { + let p = pid.to_string(); + let _ = crate::util::run_simple( + std::path::Path::new("taskkill"), + &["/PID", p.as_str(), "/T"], + Duration::from_secs(10), + ); + if wait_gone(pid, grace) { + return true; + } + let _ = crate::util::run_simple( + std::path::Path::new("taskkill"), + &["/PID", p.as_str(), "/T", "/F"], + Duration::from_secs(10), + ); + } + wait_gone(pid, Duration::from_millis(500)) +} + +fn wait_gone(pid: u32, within: Duration) -> bool { + let deadline = Instant::now() + within; + loop { + if !process_alive(pid) { + return true; + } + if Instant::now() >= deadline { + return false; + } + std::thread::sleep(Duration::from_millis(100)); + } +} + +/// Configure `cmd` to outlive its parent: its own process group on Unix (so +/// a Ctrl+C in the user's terminal doesn't reach it, and `terminate_tree` +/// can signal the whole group), a detached console-less process on Windows. +pub(crate) fn detach(cmd: &mut Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + cmd.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn self_is_alive_and_nonsense_pids_are_not() { + assert!(process_alive(std::process::id())); + assert!(!process_alive(0)); + assert!(!process_alive(u32::MAX)); + } + + #[cfg(unix)] + #[test] + fn terminate_tree_kills_a_detached_group_including_grandchildren() { + // sh (group leader) starts a grandchild sleep; both must die. + let dir = crate::util::TempDir::new("agy-sys-test-").unwrap(); + let pidfile = dir.path().join("grandchild.pid"); + let mut cmd = Command::new("sh"); + cmd.args([ + "-c", + &format!("sleep 60 & echo $! > '{}'; wait", pidfile.display()), + ]); + detach(&mut cmd); + let mut child = cmd.spawn().unwrap(); + let pid = child.id(); + // Reap concurrently: the killed shell is OUR child, and kill(pid, 0) + // reports an unreaped zombie as alive. (In production the canceller + // is a different process, so the worker is reaped by init.) + let reaper = std::thread::spawn(move || child.wait()); + let deadline = Instant::now() + Duration::from_secs(5); + let grandchild: u32 = loop { + if let Ok(s) = std::fs::read_to_string(&pidfile) + && let Ok(p) = s.trim().parse() + { + break p; + } + assert!(Instant::now() < deadline, "grandchild never started"); + std::thread::sleep(Duration::from_millis(20)); + }; + assert!(process_alive(grandchild)); + assert!(terminate_tree(pid, Duration::from_secs(3))); + let _ = reaper.join(); + assert!( + wait_gone(grandchild, Duration::from_secs(3)), + "grandchild orphaned" + ); + } + + #[test] + fn terminate_tree_on_dead_pid_is_true() { + let mut cmd = if cfg!(windows) { + let mut c = Command::new("cmd"); + c.args(["/C", "exit 0"]); + c + } else { + Command::new("true") + }; + let mut child = cmd.spawn().unwrap(); + let pid = child.id(); + child.wait().unwrap(); + assert!(terminate_tree(pid, Duration::from_millis(100))); + } +} diff --git a/src/time.rs b/src/time.rs new file mode 100644 index 0000000..0a5841c --- /dev/null +++ b/src/time.rs @@ -0,0 +1,403 @@ +//! UTC timestamps without a calendar crate. +//! +//! std has `SystemTime` but no calendar, and the job records written by the +//! old Node runtime store `Date.prototype.toISOString()` strings. Records +//! from both runtimes must stay interchangeable, so formatting matches JS +//! byte for byte (including the `+YYYYYY` / `-YYYYYY` extended years), and +//! parsing accepts what V8 accepts for the ISO forms we can meet in a record. +//! +//! The calendar maths is Howard Hinnant's days-from-civil / civil-from-days +//! (proleptic Gregorian, exact for the whole JS Date range). + +use std::time::{SystemTime, UNIX_EPOCH}; + +const MS_PER_DAY: i64 = 86_400_000; + +/// ECMAScript time values are limited to ±8.64e15 ms (±100,000,000 days); +/// `toISOString` throws outside it. We clamp instead of failing so a hostile +/// or corrupt value can never panic or print garbage. +const JS_MAX_MS: i64 = 8_640_000_000_000_000; + +/// Current time in unix milliseconds. A clock set before 1970 yields a +/// negative value rather than an error. +pub(crate) fn now_millis() -> i64 { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(d) => i64::try_from(d.as_millis()).unwrap_or(i64::MAX), + Err(e) => { + let back = e.duration(); + // Round toward -infinity like JS Date.now() would on such a clock. + let ms = i64::try_from(back.as_millis()).unwrap_or(i64::MAX); + let extra = i64::from(back.subsec_nanos() % 1_000_000 != 0); + -(ms.saturating_add(extra)) + } + } +} + +/// `new Date(ms).toISOString()`, e.g. `2026-05-31T15:02:38.473Z`. +/// Values outside the JS Date range are clamped to its ends. +pub(crate) fn iso_from_millis(ms: i64) -> String { + let ms = ms.clamp(-JS_MAX_MS, JS_MAX_MS); + let days = ms.div_euclid(MS_PER_DAY); + let rem = ms.rem_euclid(MS_PER_DAY); + let (y, m, d) = civil_from_days(days); + let hh = rem / 3_600_000; + let mm = rem / 60_000 % 60; + let ss = rem / 1000 % 60; + let frac = rem % 1000; + let year = if (0..=9999).contains(&y) { + format!("{y:04}") + } else if y > 9999 { + format!("+{y:06}") + } else { + format!("-{:06}", -y) + }; + format!("{year}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02}.{frac:03}Z") +} + +/// `new Date().toISOString()`. +pub(crate) fn iso_now() -> String { + iso_from_millis(now_millis()) +} + +/// Parse an ISO-8601 timestamp the way V8's `new Date(s)` does for the +/// date-time-string format, returning unix ms. +/// +/// Accepted: `YYYY`, `YYYY-MM`, `YYYY-MM-DD` (UTC), optionally followed by +/// `THH:MM[:SS[.fff…]]` and a mandatory `Z` / `±HH:MM` / `±HHMM` offset. +/// Years may be `±YYYYYY`. Like V8: day 1–31 is accepted for any month and +/// overflows (`02-30` is 2 March), `24:00:00` means next midnight, extra +/// fraction digits are truncated, `T`/`Z` are case-insensitive. +/// +/// Deliberately rejected (V8 would accept): a time with no offset, which V8 +/// reads as *local* time — that depends on the machine's zone and never +/// appears in records we write; and V8's legacy free-form formats. +pub(crate) fn parse_iso_millis(s: &str) -> Option { + let b = s.as_bytes(); + let mut p = Cursor { b, i: 0 }; + + let year = match p.peek() { + Some(c @ (b'+' | b'-')) => { + p.i += 1; + let v = p.digits(6)?; + if c == b'-' { + // "-000000" is explicitly invalid in ECMAScript. + if v == 0 { + return None; + } + -v + } else { + v + } + } + _ => p.digits(4)?, + }; + let mut month = 1; + let mut day = 1; + if p.eat(b'-') { + month = p.digits(2)?; + if p.eat(b'-') { + day = p.digits(2)?; + } + } + if !(1..=12).contains(&month) || !(1..=31).contains(&day) { + return None; + } + + let mut time_ms = 0i64; + let mut offset_ms = 0i64; + if matches!(p.peek(), Some(b'T' | b't')) { + p.i += 1; + let hh = p.digits(2)?; + if !p.eat(b':') { + return None; + } + let mi = p.digits(2)?; + let mut ss = 0; + let mut ms = 0; + if p.eat(b':') { + ss = p.digits(2)?; + if p.eat(b'.') { + let start = p.i; + let mut n = 0; + while let Some(c) = p.peek().filter(u8::is_ascii_digit) { + if n < 3 { + ms = ms * 10 + i64::from(c - b'0'); + } + n += 1; + p.i += 1; + } + if p.i == start { + return None; + } + for _ in n..3 { + ms *= 10; + } + } + } + let midnight_24 = hh == 24 && mi == 0 && ss == 0 && ms == 0; + if !(hh <= 23 || midnight_24) || mi > 59 || ss > 59 { + return None; + } + time_ms = ((hh * 60 + mi) * 60 + ss) * 1000 + ms; + + match p.peek() { + Some(b'Z' | b'z') => p.i += 1, + Some(c @ (b'+' | b'-')) => { + p.i += 1; + let oh = p.digits(2)?; + p.eat(b':'); + let om = p.digits(2)?; + if oh > 23 || om > 59 { + return None; + } + let off = (oh * 60 + om) * 60_000; + offset_ms = if c == b'+' { off } else { -off }; + } + // No offset: V8 would use local time. See doc comment. + _ => return None, + } + } + if p.i != b.len() { + return None; + } + + let days = days_from_civil(year, month, day); + let total = days + .checked_mul(MS_PER_DAY)? + .checked_add(time_ms)? + .checked_sub(offset_ms)?; + if total.abs() > JS_MAX_MS { + return None; + } + Some(total) +} + +/// Tiny byte cursor for `parse_iso_millis`. +struct Cursor<'a> { + b: &'a [u8], + i: usize, +} + +impl Cursor<'_> { + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + fn eat(&mut self, c: u8) -> bool { + if self.peek() == Some(c) { + self.i += 1; + true + } else { + false + } + } + + /// Exactly `n` ASCII digits (n <= 6, so no overflow). + fn digits(&mut self, n: usize) -> Option { + let mut v = 0i64; + for _ in 0..n { + let c = self.peek().filter(u8::is_ascii_digit)?; + v = v * 10 + i64::from(c - b'0'); + self.i += 1; + } + Some(v) + } +} + +/// Days since 1970-01-01 for a proleptic Gregorian date. `d` may exceed the +/// month length; the result simply runs on into the next month (V8 parity). +fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { + let y = if m <= 2 { y - 1 } else { y }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = if m > 2 { m - 3 } else { m + 9 }; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// Inverse of `days_from_civil`: (year, month 1-12, day 1-31). +fn civil_from_days(z: i64) -> (i64, i64, i64) { + let z = z + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + (y, m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Expected strings below were produced by `new Date(ms).toISOString()` + // in Node so the port is pinned to JS output. + const JS_CASES: &[(i64, &str)] = &[ + (0, "1970-01-01T00:00:00.000Z"), + (-1, "1969-12-31T23:59:59.999Z"), + (1, "1970-01-01T00:00:00.001Z"), + (-86_400_000, "1969-12-31T00:00:00.000Z"), + (-86_400_001, "1969-12-30T23:59:59.999Z"), + (951_782_400_000, "2000-02-29T00:00:00.000Z"), + (951_868_800_000, "2000-03-01T00:00:00.000Z"), + (946_684_799_999, "1999-12-31T23:59:59.999Z"), + (1_709_164_800_000, "2024-02-29T00:00:00.000Z"), + (1_709_251_199_999, "2024-02-29T23:59:59.999Z"), + (4_107_456_000_000, "2100-02-28T00:00:00.000Z"), + (4_107_542_400_000, "2100-03-01T00:00:00.000Z"), + (1_780_239_758_473, "2026-05-31T15:02:38.473Z"), + (-2_208_988_800_000, "1900-01-01T00:00:00.000Z"), + (-5_097_600_001, "1969-11-02T23:59:59.999Z"), + (-62_135_596_800_000, "0001-01-01T00:00:00.000Z"), + (-62_167_219_200_000, "0000-01-01T00:00:00.000Z"), + (-62_167_219_200_001, "-000001-12-31T23:59:59.999Z"), + (-62_198_755_200_000, "-000001-01-01T00:00:00.000Z"), + (253_402_300_799_999, "9999-12-31T23:59:59.999Z"), + (253_402_300_800_000, "+010000-01-01T00:00:00.000Z"), + (8_640_000_000_000_000, "+275760-09-13T00:00:00.000Z"), + (-8_640_000_000_000_000, "-271821-04-20T00:00:00.000Z"), + (2_147_483_647_000, "2038-01-19T03:14:07.000Z"), + (13_574_563_200_000, "2400-02-29T00:00:00.000Z"), + ]; + + #[test] + fn iso_from_millis_matches_js() { + for &(ms, want) in JS_CASES { + assert_eq!(iso_from_millis(ms), want, "ms={ms}"); + } + } + + #[test] + fn iso_from_millis_clamps_out_of_range() { + assert_eq!(iso_from_millis(i64::MAX), "+275760-09-13T00:00:00.000Z"); + assert_eq!(iso_from_millis(i64::MIN), "-271821-04-20T00:00:00.000Z"); + } + + #[test] + fn parse_round_trips_js_cases() { + for &(ms, s) in JS_CASES { + assert_eq!(parse_iso_millis(s), Some(ms), "{s}"); + } + } + + #[test] + fn round_trip_sweep() { + // Every ~13.7 days across ±1000 years, with odd ms offsets. + let mut ms = -31_556_952_000_000i64; + while ms < 31_556_952_000_000 { + let s = iso_from_millis(ms); + assert_eq!(parse_iso_millis(&s), Some(ms), "{s}"); + ms += 1_183_746_123; + } + } + + #[test] + fn civil_days_consistent() { + for z in -800_000..800_000i64 { + let (y, m, d) = civil_from_days(z); + assert_eq!(days_from_civil(y, m, d), z); + } + } + + #[test] + fn parse_variants_match_v8() { + // Expected values from `new Date(s).toISOString()` in Node. + let cases: &[(&str, &str)] = &[ + ("2026-05-28T15:00:00Z", "2026-05-28T15:00:00.000Z"), + ("2026-05-28T15:00:00+00:00", "2026-05-28T15:00:00.000Z"), + ("2026-05-28T15:00:00-00:00", "2026-05-28T15:00:00.000Z"), + ("2026-05-28T15:00:00+02:00", "2026-05-28T13:00:00.000Z"), + ("2026-05-28T15:00:00+0200", "2026-05-28T13:00:00.000Z"), + ("2026-05-28T15:00:00+23:59", "2026-05-27T15:01:00.000Z"), + ("2026-05-28T15:00:00.1239Z", "2026-05-28T15:00:00.123Z"), + ("2026-05-28T15:00:00.1Z", "2026-05-28T15:00:00.100Z"), + ("2026-05-28T24:00:00Z", "2026-05-29T00:00:00.000Z"), + ("2026-05-28T15:00Z", "2026-05-28T15:00:00.000Z"), + ("2026-05-28t15:00:00z", "2026-05-28T15:00:00.000Z"), + ("2026-05-28", "2026-05-28T00:00:00.000Z"), + ("2026-05", "2026-05-01T00:00:00.000Z"), + ("2026", "2026-01-01T00:00:00.000Z"), + ("2026-02-30T00:00:00Z", "2026-03-02T00:00:00.000Z"), + ("2026-02-29T00:00:00Z", "2026-03-01T00:00:00.000Z"), + ("2024-02-29T00:00:00Z", "2024-02-29T00:00:00.000Z"), + ("+010000-01-01T00:00:00Z", "+010000-01-01T00:00:00.000Z"), + ("-000001-01-01T00:00:00Z", "-000001-01-01T00:00:00.000Z"), + ("1969-12-31T23:59:59.999Z", "1969-12-31T23:59:59.999Z"), + ]; + for &(input, want) in cases { + let ms = parse_iso_millis(input); + assert_eq!(ms.map(iso_from_millis).as_deref(), Some(want), "{input}"); + } + } + + #[test] + fn parse_rejects_what_v8_rejects() { + for s in [ + "", + "garbage", + "2026-05-28T24:00:01Z", + "-000000-01-01T00:00:00Z", + "2026-05-28T15:00:60Z", + "2026-05-28T15:60:00Z", + "2026-13-01", + "2026-00-01", + "2026-05-00", + "2026-05-32", + " 2026-05-28T15:00:00Z", + "2026-05-28T15:00:00Z ", + "2026-05-28T15:00:00.Z", + "2026-05-28T15:00:00+24:00", + "2026-05-28T15:00:00+12:60", + "+275760-09-13T00:00:00.001Z", + "-271821-04-19T23:59:59.999Z", + "20260528", + "2026-05-28T", + "2026-05-28T15", + "2026-05-28T15:00:00+", + "2026-05-28", + ] { + assert_eq!(parse_iso_millis(s), None, "{s:?}"); + } + } + + #[test] + fn parse_rejects_local_time_forms() { + // V8 reads these as local time; we refuse rather than guess a zone. + assert_eq!(parse_iso_millis("2026-05-28T15:00:00"), None); + assert_eq!(parse_iso_millis("2026-05-28T15:00:00.000"), None); + // Legacy (non-ISO) date forms, also local time in V8. + assert_eq!(parse_iso_millis("2026-5-28"), None); + } + + #[test] + fn parse_range_edges() { + assert_eq!( + parse_iso_millis("+275760-09-13T00:00:00.000Z"), + Some(JS_MAX_MS) + ); + assert_eq!( + parse_iso_millis("-271821-04-20T00:00:00.000Z"), + Some(-JS_MAX_MS) + ); + // Max-width garbage must not overflow. + assert_eq!(parse_iso_millis("+999999-12-31T23:59:59.999Z"), None); + assert_eq!(parse_iso_millis("-999999-01-01T00:00:00.000Z"), None); + } + + #[test] + fn now_is_sane() { + let a = now_millis(); + // After 2020-01-01 and before 2200. + assert!(a > 1_577_836_800_000); + assert!(a < 7_258_118_400_000); + let s = iso_now(); + assert_eq!(s.len(), 24); + assert!(s.ends_with('Z')); + let parsed = parse_iso_millis(&s).unwrap_or(0); + assert!(parsed >= a); + } +} diff --git a/src/util.rs b/src/util.rs new file mode 100644 index 0000000..e05a4e2 --- /dev/null +++ b/src/util.rs @@ -0,0 +1,472 @@ +//! Small std-only helpers: temp dirs, randomness, PATH lookup, env, and +//! running a child process with captured output and a deadline. + +use std::collections::hash_map::RandomState; +use std::ffi::OsStr; +use std::hash::{BuildHasher, Hasher}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +/// 64 bits from the OS RNG. std's `RandomState` seeds every instance from the +/// operating system's random source, which is all we need for job ids and +/// temp-dir names (unpredictable, not cryptographic keys). +pub(crate) fn random_u64() -> u64 { + let mut h = RandomState::new().build_hasher(); + h.write_u64(0x9e37_79b9_7f4a_7c15); + h.finish() +} + +pub(crate) fn random_hex(bytes: usize) -> String { + let mut out = String::with_capacity(bytes * 2); + let mut left = bytes; + while left > 0 { + let chunk = random_u64().to_le_bytes(); + for b in chunk.iter().take(left.min(8)) { + out.push_str(&format!("{b:02x}")); + } + left = left.saturating_sub(8); + } + out +} + +/// Remove our own temp dirs (`*` directly in the OS temp dir, not +/// symlinks) older than `max_age` — left behind when a run was killed +/// before its cleanup (e.g. Claude's Bash tool timing out a foreground +/// review). They can hold full copies of reviewed source files. +pub(crate) fn sweep_stale_temp(prefixes: &[&str], max_age: Duration) { + let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) else { + return; + }; + for e in entries.flatten() { + let name = e.file_name(); + let Some(name) = name.to_str() else { continue }; + if !prefixes.iter().any(|p| name.starts_with(p)) { + continue; + } + let Ok(meta) = std::fs::symlink_metadata(e.path()) else { + continue; + }; + if !meta.is_dir() || meta.file_type().is_symlink() { + continue; + } + let old = meta + .modified() + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > max_age); + if old { + let _ = std::fs::remove_dir_all(e.path()); + } + } +} + +/// A directory under the OS temp dir that is removed when dropped (unless +/// `keep()` was called). Created with mode 0700 on Unix, so other local users +/// can't read staged diffs or plant files into agy's workspace. +pub(crate) struct TempDir { + path: PathBuf, + keep: bool, +} + +impl TempDir { + pub(crate) fn new(prefix: &str) -> std::io::Result { + let base = std::env::temp_dir(); + let mut last_err = None; + for _ in 0..16 { + let path = base.join(format!("{prefix}{}", random_hex(6))); + #[cfg_attr(not(unix), allow(unused_mut))] // mode() is Unix-only + let mut builder = std::fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + builder.mode(0o700); + } + match builder.create(&path) { + Ok(()) => { + // Hand out the canonical path. On macOS the temp dir is + // /var/folders/..., a symlink to /private/var/...: agy's + // cwd resolves to the /private form, and its --add-dir + // must name the same spelling or agy may judge its own + // workspace to be outside the workspace. + let path = canonical_or_self(&path); + return Ok(TempDir { path, keep: false }); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => last_err = Some(e), + Err(e) => return Err(e), + } + } + Err(last_err.unwrap_or_else(|| std::io::Error::other("could not create a temp dir"))) + } + + pub(crate) fn path(&self) -> &Path { + &self.path + } + + /// Hand ownership of the directory to someone else (e.g. a background + /// worker that deletes it when it finishes). + pub(crate) fn keep(mut self) -> PathBuf { + self.keep = true; + self.path.clone() + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + if !self.keep { + let _ = std::fs::remove_dir_all(&self.path); + } + } +} + +/// The value of an environment variable if it is set and non-empty. +pub(crate) fn env_nonempty(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.is_empty()) +} + +/// The user's home directory. HOME first on Unix (that's what the old shell +/// code honoured, and tests override it); USERPROFILE on Windows (Git Bash's +/// HOME is an MSYS path like /c/Users/x that native programs can't open). +pub(crate) fn home_dir() -> Option { + #[cfg(windows)] + let var = env_nonempty("USERPROFILE").or_else(|| env_nonempty("HOME")); + #[cfg(not(windows))] + let var = env_nonempty("HOME"); + var.map(PathBuf::from).or_else(std::env::home_dir) +} + +pub(crate) fn is_executable_file(p: &Path) -> bool { + match std::fs::metadata(p) { + Ok(m) if m.is_file() => { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + m.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + true + } + } + _ => false, + } +} + +/// Find `name` on PATH like a shell would (PATHEXT on Windows). +pub(crate) fn which(name: &str) -> Option { + which_in(name, &std::env::var_os("PATH")?) +} + +fn which_in(name: &str, path: &OsStr) -> Option { + // Windows: only real executable extensions (an extension-less file is + // never runnable there, e.g. a POSIX `agy` script left in ~/.local/bin). + #[cfg(windows)] + let exts: Vec = env_nonempty("PATHEXT") + .unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into()) + .split(';') + .filter(|s| !s.is_empty()) + .map(|s| s.to_ascii_lowercase()) + .collect(); + #[cfg(not(windows))] + let exts: Vec = vec![String::new()]; + for dir in std::env::split_paths(path) { + // Skip empty and relative entries (`.`, `bin`): they resolve against + // the current directory, i.e. whatever repo the user is in, so a + // repo could plant its own `agy`, `git` or `curl`. + if dir.as_os_str().is_empty() || !dir.is_absolute() { + continue; + } + for ext in &exts { + let candidate = dir.join(format!("{name}{ext}")); + if is_executable_file(&candidate) { + return Some(candidate); + } + } + } + None +} + +/// Output of a finished (or killed) child process. +pub(crate) struct Captured { + pub(crate) stdout: Vec, + pub(crate) stderr: Vec, + /// None when killed by a signal or by our deadline. + pub(crate) code: Option, + pub(crate) timed_out: bool, +} + +impl Captured { + pub(crate) fn stdout_str(&self) -> String { + String::from_utf8_lossy(&self.stdout).into_owned() + } + pub(crate) fn stderr_str(&self) -> String { + String::from_utf8_lossy(&self.stderr).into_owned() + } + pub(crate) fn ok(&self) -> bool { + self.code == Some(0) + } +} + +/// Run `cmd` with stdin closed (agy blocks forever on an open non-TTY stdin), +/// capturing stdout and stderr, and kill it after `timeout` if given. +/// Spawn failures are returned as Err. +pub(crate) fn run_captured( + cmd: &mut Command, + timeout: Option, +) -> std::io::Result { + run_captured_notify(cmd, timeout, &|_| {}) +} + +/// `run_captured`, telling `on_spawn` the child's pid as soon as it starts +/// (jobs record agy's pid so /agy:cancel can stop it). +pub(crate) fn run_captured_notify( + cmd: &mut Command, + timeout: Option, + on_spawn: &dyn Fn(u32), +) -> std::io::Result { + cmd.stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = cmd.spawn()?; + on_spawn(child.id()); + // Drain both pipes on threads: a child that fills one pipe while we wait + // on the other would deadlock. + let mut out_pipe = child.stdout.take(); + let mut err_pipe = child.stderr.take(); + let out_t = std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(p) = out_pipe.as_mut() { + let _ = p.read_to_end(&mut buf); + } + buf + }); + let err_t = std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(p) = err_pipe.as_mut() { + let _ = p.read_to_end(&mut buf); + } + buf + }); + let deadline = timeout.map(|t| Instant::now() + t); + let mut timed_out = false; + let status = loop { + if let Some(st) = child.try_wait()? { + break Some(st); + } + if let Some(d) = deadline + && Instant::now() >= d + { + timed_out = true; + let _ = child.kill(); + break child.wait().ok(); + } + std::thread::sleep(Duration::from_millis(20)); + }; + let stdout = out_t.join().unwrap_or_default(); + let stderr = err_t.join().unwrap_or_default(); + let code = if timed_out { + None + } else { + status.and_then(|s| s.code()) + }; + Ok(Captured { + stdout, + stderr, + code, + timed_out, + }) +} + +/// Convenience: run `program args...` with a deadline. +pub(crate) fn run_simple>( + program: &Path, + args: &[S], + timeout: Duration, +) -> std::io::Result { + let mut cmd = Command::new(program); + cmd.args(args); + run_captured(&mut cmd, Some(timeout)) +} + +/// Truncate to at most `max` bytes without splitting a UTF-8 character. +pub(crate) fn truncate_utf8(s: &str, max: usize) -> &str { + if s.len() <= max { + return s; + } + let mut end = max; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + &s[..end] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn random_hex_has_requested_length_and_varies() { + let a = random_hex(4); + let b = random_hex(4); + assert_eq!(a.len(), 8); + assert!( + a.chars() + .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()) + ); + assert_eq!(random_hex(11).len(), 22); + assert_ne!(a, b, "two draws from the OS RNG should differ"); + } + + #[test] + fn temp_dir_is_private_and_removed_on_drop() { + let p; + { + let t = TempDir::new("agy-test-").unwrap(); + p = t.path().to_path_buf(); + assert!(p.is_dir()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700); + } + std::fs::write(p.join("f"), "x").unwrap(); + } + assert!(!p.exists()); + } + + #[test] + fn temp_dir_keep_survives_drop() { + let t = TempDir::new("agy-test-").unwrap(); + let p = t.keep(); + assert!(p.is_dir()); + std::fs::remove_dir_all(&p).unwrap(); + } + + #[test] + fn truncate_utf8_respects_char_boundaries() { + assert_eq!(truncate_utf8("hello", 10), "hello"); + assert_eq!(truncate_utf8("hello", 3), "hel"); + // "é" is 2 bytes; cutting in its middle must back off. + assert_eq!(truncate_utf8("aé", 2), "a"); + assert_eq!(truncate_utf8("", 0), ""); + } + + #[cfg(unix)] + #[test] + fn run_captured_collects_both_streams_and_exit_code() { + let mut cmd = Command::new("sh"); + cmd.args(["-c", "echo out; echo err >&2; exit 3"]); + let c = run_captured(&mut cmd, Some(Duration::from_secs(10))).unwrap(); + assert_eq!(c.stdout_str(), "out\n"); + assert_eq!(c.stderr_str(), "err\n"); + assert_eq!(c.code, Some(3)); + assert!(!c.timed_out); + } + + #[cfg(unix)] + #[test] + fn run_captured_closes_stdin() { + // `cat` would block forever on an open stdin; closed stdin -> EOF. + let mut cmd = Command::new("cat"); + let c = run_captured(&mut cmd, Some(Duration::from_secs(10))).unwrap(); + assert!(c.ok()); + assert!(c.stdout.is_empty()); + } + + #[cfg(unix)] + #[test] + fn run_captured_kills_on_timeout() { + let mut cmd = Command::new("sleep"); + cmd.arg("30"); + let start = Instant::now(); + let c = run_captured(&mut cmd, Some(Duration::from_millis(200))).unwrap(); + assert!(c.timed_out); + assert_eq!(c.code, None); + assert!(start.elapsed() < Duration::from_secs(10)); + } + + #[test] + fn run_captured_reports_spawn_failure() { + let mut cmd = Command::new("/definitely/not/a/real/binary-xyz"); + assert!(run_captured(&mut cmd, Some(Duration::from_secs(1))).is_err()); + } + + #[cfg(unix)] + #[test] + fn which_ignores_relative_path_entries() { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("agy-which-test-").unwrap(); + let bin = d.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + let tool = bin.join("agy-which-probe"); + std::fs::write(&tool, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + // Absolute entry: found. + assert_eq!( + which_in("agy-which-probe", bin.as_os_str()), + Some(tool.clone()) + ); + // The same dir written relatively (as a repo could plant): ignored. + let rel = std::ffi::OsString::from("bin:.:"); + let cwd = std::env::current_dir().unwrap(); + assert!(cwd != d.path(), "test must not depend on cwd"); + assert_eq!(which_in("agy-which-probe", &rel), None); + } + + #[cfg(unix)] + #[test] + fn which_finds_sh_and_not_garbage() { + assert!(which("sh").is_some()); + assert!(which("definitely-not-a-command-xyz").is_none()); + } +} + +/// A command failure: the exit code the process should end with and the +/// message for stderr (already formatted, may span lines). +#[derive(Debug)] +pub(crate) struct Fail { + pub(crate) code: i32, + pub(crate) message: String, +} + +impl Fail { + pub(crate) fn new(code: i32, message: impl Into) -> Fail { + Fail { + code, + message: message.into(), + } + } + /// Bad usage (exit 64, like sysexits EX_USAGE). + pub(crate) fn usage(message: impl Into) -> Fail { + Fail::new(64, message) + } + /// Refused by a safety guard (exit 65, EX_DATAERR — kept from 0.8.x). + pub(crate) fn refused(message: impl Into) -> Fail { + Fail::new(65, message) + } + /// Environment / runtime failure (exit 1). + pub(crate) fn runtime(message: impl Into) -> Fail { + Fail::new(1, message) + } +} + +pub(crate) type CmdResult = Result; + +/// `std::fs::canonicalize` without Windows' verbatim `\\?\` prefix (agy, git +/// and many Windows tools reject verbatim paths); falls back to the input. +pub(crate) fn canonical_or_self(p: &Path) -> PathBuf { + match std::fs::canonicalize(p) { + Ok(c) => { + let s = c.to_string_lossy(); + if let Some(rest) = s.strip_prefix(r"\\?\") + && !rest.starts_with("UNC\\") + { + return PathBuf::from(rest); + } + c + } + Err(_) => p.to_path_buf(), + } +} diff --git a/tests/agy-companion.commands.test.mjs b/tests/agy-companion.commands.test.mjs deleted file mode 100644 index f6ed02b..0000000 --- a/tests/agy-companion.commands.test.mjs +++ /dev/null @@ -1,192 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { spawnSync, spawn } from "node:child_process"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import process from "node:process"; -import { fileURLToPath } from "node:url"; - -import { - createJob, - updateJob, - jobLogPath, -} from "../plugins/agy/scripts/lib/state.mjs"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const COMPANION = path.resolve( - __dirname, - "..", - "plugins", - "agy", - "scripts", - "agy-companion.mjs", -); - -let workspaceRoot; - -beforeEach(async () => { - workspaceRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-cmd-")); -}); -afterEach(async () => { - await fsp.rm(workspaceRoot, { recursive: true, force: true }); -}); - -function runCompanion(args, extraEnv = {}) { - return spawnSync(process.execPath, [COMPANION, ...args], { - encoding: "utf8", - timeout: 15000, - cwd: workspaceRoot, - env: { - ...process.env, - CLAUDE_PROJECT_DIR: workspaceRoot, - // Sandbox HOME / LOCALAPPDATA so the agy discovery doesn't find - // a real install on a developer's machine. - HOME: path.join(workspaceRoot, "fake-home"), - USERPROFILE: path.join(workspaceRoot, "fake-home"), - LOCALAPPDATA: path.join(workspaceRoot, "fake-home", "AppData", "Local"), - // Force PATH to a directory with no `agy`. - PATH: workspaceRoot, - AGY_BIN: "", - ...extraEnv, - }, - }); -} - -describe("rescue command (no agy installed)", () => { - it("rejects empty task with exit 64", () => { - const r = runCompanion(["rescue"]); - expect(r.status).toBe(64); - expect(r.stderr).toMatch(/task description is required/); - }); - - it("rejects --model with no value", () => { - const r = runCompanion(["rescue", "--model="]); - expect(r.status).toBe(64); - expect(r.stderr).toMatch(/non-empty/); - }); - - it("fails with exit 127 when agy binary is absent", () => { - const r = runCompanion(["rescue", "investigate", "the", "bug"]); - expect(r.status).toBe(127); - expect(r.stderr).toMatch(/cannot find the `agy` binary/); - }); -}); - -describe("status command", () => { - it("on an empty workspace prints the no-jobs message", () => { - const r = runCompanion(["status"]); - expect(r.status).toBe(0); - expect(r.stdout).toMatch(/no agy jobs/i); - }); - - it("with planted jobs prints a table", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "planted task" }); - await updateJob(workspaceRoot, j.id, { status: "completed", exitCode: 0 }); - const r = runCompanion(["status"]); - expect(r.status).toBe(0); - expect(r.stdout).toContain(j.id); - expect(r.stdout).toContain("[done]"); - expect(r.stdout).toContain("planted task"); - }); - - it("with a job id shows the detail block", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "detail check" }); - const r = runCompanion(["status", j.id]); - expect(r.status).toBe(0); - expect(r.stdout).toContain("Job:"); - expect(r.stdout).toContain(j.id); - }); - - it("with a missing id exits 2 and complains to stderr", () => { - const r = runCompanion(["status", "agy-deadbeef"]); - expect(r.status).toBe(2); - expect(r.stderr).toMatch(/not found/); - }); - - it("with an ambiguous prefix exits 2 and lists candidates", async () => { - const a = await createJob(workspaceRoot, { - kind: "rescue", task: "a", id: "agy-aaaa0001", - }); - const b = await createJob(workspaceRoot, { - kind: "rescue", task: "b", id: "agy-aaaa0002", - }); - const r = runCompanion(["status", "agy-aaaa"]); - expect(r.status).toBe(2); - expect(r.stderr).toMatch(/ambiguous/); - expect(r.stderr).toContain(a.id); - expect(r.stderr).toContain(b.id); - }); -}); - -describe("result command", () => { - it("with no id reads the latest job's log", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "log this" }); - await updateJob(workspaceRoot, j.id, { status: "completed" }); - await fsp.writeFile(jobLogPath(workspaceRoot, j.id), "captured output line\n"); - const r = runCompanion(["result"]); - expect(r.status).toBe(0); - expect(r.stdout).toContain("captured output line"); - expect(r.stdout).toContain(j.id); - }); - - it("reports gracefully when log file is missing", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "no log" }); - await updateJob(workspaceRoot, j.id, { status: "completed" }); - const r = runCompanion(["result", j.id]); - expect(r.status).toBe(0); - expect(r.stdout).toMatch(/log file is empty/); - }); -}); - -describe("cancel command", () => { - it("cancels a pending job (no PID) and marks canceled", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "pending" }); - const r = runCompanion(["cancel", j.id]); - expect(r.status).toBe(0); - expect(r.stdout).toMatch(/canceled/); - }); - - it("refuses to cancel a completed job", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "done" }); - await updateJob(workspaceRoot, j.id, { status: "completed", exitCode: 0 }); - const r = runCompanion(["cancel", j.id]); - expect(r.status).toBe(2); - expect(r.stderr).toMatch(/terminal status/); - }); - - it("kills a live PID and marks canceled", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "kill me" }); - // Spawn a sleep child we control. - const child = spawn( - process.execPath, - ["-e", "setTimeout(()=>{}, 30000)"], - { stdio: "ignore", detached: true }, - ); - child.unref(); - try { - await updateJob(workspaceRoot, j.id, { status: "running", pid: child.pid }); - const r = runCompanion(["cancel", j.id]); - expect(r.status).toBe(0); - expect(r.stdout).toMatch(/canceled/); - } finally { - try { process.kill(child.pid, "SIGKILL"); } catch {} - } - }); -}); - -describe("help & version still work", () => { - it("version prints JSON with the current version", () => { - const r = runCompanion(["version"]); - expect(r.status).toBe(0); - const obj = JSON.parse(r.stdout); - expect(typeof obj.version).toBe("string"); - }); - it("help lists rescue/status/result/cancel", () => { - const r = runCompanion(["help"]); - expect(r.status).toBe(0); - expect(r.stdout).toMatch(/rescue/); - expect(r.stdout).toMatch(/status/); - expect(r.stdout).toMatch(/result/); - expect(r.stdout).toMatch(/cancel/); - }); -}); diff --git a/tests/agy-companion.test.mjs b/tests/agy-companion.test.mjs deleted file mode 100644 index f0475aa..0000000 --- a/tests/agy-companion.test.mjs +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { spawnSync } from "node:child_process"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -import { HANDLERS, VERSION } from "../plugins/agy/scripts/agy-companion.mjs"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -const COMPANION = path.resolve(__dirname, "..", "plugins", "agy", "scripts", "agy-companion.mjs"); - -function runCompanion(args) { - return spawnSync(process.execPath, [COMPANION, ...args], { - encoding: "utf8", - timeout: 10000, - }); -} - -describe("agy-companion entry", () => { - it("exports a non-empty VERSION", () => { - expect(VERSION).toMatch(/^\d+\.\d+/); - }); - - it("HANDLERS includes version/help aliases", () => { - expect(typeof HANDLERS.version).toBe("function"); - expect(typeof HANDLERS.help).toBe("function"); - expect(typeof HANDLERS["--help"]).toBe("function"); - }); - - it("`version` subcommand prints JSON with current version", () => { - const r = runCompanion(["version"]); - expect(r.status).toBe(0); - expect(r.stdout.trim()).toContain('"version":'); - const obj = JSON.parse(r.stdout); - expect(obj.version).toBe(VERSION); - }); - - it("`help` exits 0 and prints usage", () => { - const r = runCompanion(["help"]); - expect(r.status).toBe(0); - expect(r.stdout).toContain("agy-companion"); - expect(r.stdout).toContain("Usage:"); - }); - - it("no subcommand exits 64 and prints to stderr", () => { - const r = runCompanion([]); - expect(r.status).toBe(64); - expect(r.stderr).toContain("Usage:"); - }); - - it("unknown subcommand exits 64", () => { - const r = runCompanion(["definitely-not-real"]); - expect(r.status).toBe(64); - expect(r.stderr).toContain("unknown subcommand"); - }); -}); diff --git a/tests/cli.rs b/tests/cli.rs new file mode 100644 index 0000000..7e1d292 --- /dev/null +++ b/tests/cli.rs @@ -0,0 +1,660 @@ +//! End-to-end tests: the real agy-plugin binary against examples/stub_agy, +//! with an isolated HOME. These pin the security contracts of every command. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +#[cfg(unix)] +use std::time::{Duration, Instant}; + +fn plugin_bin() -> PathBuf { + PathBuf::from(env!("CARGO_BIN_EXE_agy-plugin")) +} + +/// target//examples/stub_agy. Located from the plugin binary +/// (always in target//), not from the test executable: cargo 1.100 +/// moved test executables under target//build///. +fn stub_bin() -> PathBuf { + let plugin = plugin_bin(); + let profile_dir = plugin.parent().unwrap(); + let name = if cfg!(windows) { + "stub_agy.exe" + } else { + "stub_agy" + }; + let p = profile_dir.join("examples").join(name); + assert!( + p.is_file(), + "stub not built at {} (cargo test builds examples)", + p.display() + ); + p +} + +struct Env { + _dir: TempDir, + root: PathBuf, + home: PathBuf, + record: PathBuf, + prompt_out: PathBuf, +} + +struct TempDir(PathBuf); +impl TempDir { + fn new(tag: &str) -> TempDir { + let base = std::env::temp_dir().join(format!( + "agy-it-{tag}-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&base).unwrap(); + { + // Canonical (macOS /var -> /private/var), but without Windows' + // verbatim \\?\ prefix, which the plugin never produces. + let c = std::fs::canonicalize(&base).unwrap(); + let t = c.to_string_lossy(); + TempDir(PathBuf::from( + t.strip_prefix(r"\\?\").unwrap_or(&t).to_string(), + )) + } + } +} +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +impl Env { + fn new(tag: &str) -> Env { + let dir = TempDir::new(tag); + let root = dir.0.clone(); + let home = root.join("home"); + std::fs::create_dir_all(home.join(".gemini").join("antigravity-cli")).unwrap(); + Env { + record: root.join("record.txt"), + prompt_out: root.join("prompt.txt"), + root, + home, + _dir: dir, + } + } + + fn cmd(&self, cwd: &Path, args: &[&str]) -> Command { + let mut c = Command::new(plugin_bin()); + c.args(args) + .current_dir(cwd) + .env("HOME", &self.home) + .env("USERPROFILE", &self.home) + .env("AGY_PLUGIN_STATE_DIR", self.root.join("state")) + .env("AGY_BIN", stub_bin()) + .env("STUB_RECORD", &self.record) + .env("STUB_PROMPT_OUT", &self.prompt_out) + .env("STUB_MODELS", "gemini-3.8-flash-low\\tGemini 3.8 Flash (Low)\\nclaude-opus-4-6-thinking\\tClaude Opus 4.6 (Thinking)\\n") + .env("STUB_RESPONSE", "stub answer") + .env_remove("ANTIGRAVITY_API_KEY") + .env_remove("CLAUDE_PROJECT_DIR") + .env_remove("AGY_REVIEW_ALLOW_SECRETS") + .env("AGY_PLUGIN_TEST", "1"); + c + } + + fn run(&self, cwd: &Path, args: &[&str], envs: &[(&str, &str)]) -> Output { + let mut c = self.cmd(cwd, args); + for (k, v) in envs { + c.env(k, v); + } + c.output().unwrap() + } + + /// Recorded stub invocations: (cwd, argv, watched env). + fn calls(&self) -> Vec<(String, Vec, Vec)> { + std::fs::read_to_string(&self.record) + .unwrap_or_default() + .lines() + .map(|l| { + let mut parts = l.splitn(3, '\t'); + let cwd = parts.next().unwrap_or("").to_string(); + let argv = parts + .next() + .unwrap_or("") + .split('\x1f') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + let env = parts + .next() + .unwrap_or("") + .split('\x1f') + .filter(|s| !s.is_empty()) + .map(str::to_string) + .collect(); + (cwd, argv, env) + }) + .collect() + } + + /// The agy runs that actually executed a prompt. + fn print_calls(&self) -> Vec<(String, Vec, Vec)> { + self.calls() + .into_iter() + .filter(|(_, a, _)| a.iter().any(|x| x == "--print")) + .collect() + } +} + +fn stdout(o: &Output) -> String { + String::from_utf8_lossy(&o.stdout).into_owned() +} +fn stderr(o: &Output) -> String { + String::from_utf8_lossy(&o.stderr).into_owned() +} + +fn git(dir: &Path, args: &[&str]) { + let o = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); +} + +fn repo(env: &Env) -> PathBuf { + let r = env.root.join("repo"); + std::fs::create_dir_all(&r).unwrap(); + git(&r, &["init", "-q", "-b", "main"]); + git(&r, &["config", "user.email", "t@t.t"]); + git(&r, &["config", "user.name", "t"]); + git(&r, &["config", "commit.gpgsign", "false"]); + std::fs::write( + r.join("calc.js"), + "function add(a,b){return a+b}\nmodule.exports={add}\n", + ) + .unwrap(); + git(&r, &["add", "-A"]); + git(&r, &["commit", "-qm", "init"]); + r +} + +fn assert_readonly_contract(env: &Env, call: &(String, Vec, Vec), caller: &Path) { + let (cwd, argv, envs) = call; + let ws_idx = argv + .iter() + .position(|a| a == "--add-dir") + .expect("--add-dir"); + let ws = &argv[ws_idx + 1]; + let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| PathBuf::from(p)); + assert_eq!( + canon(cwd), + canon(ws), + "agy runs in its workspace (cwd == --add-dir)" + ); + assert_ne!( + Path::new(cwd), + caller, + "agy must not run in the caller's dir" + ); + assert!(argv.contains(&"--sandbox".to_string())); + assert!( + !argv + .iter() + .any(|a| a.contains("dangerously-skip-permissions")), + "{argv:?}" + ); + let p = argv.iter().position(|a| a == "--print").unwrap(); + assert!( + argv[p - 1].starts_with("--settings={\"agentMode\":\"\"") + && argv[p - 1].contains("command(*)") + && argv[p - 1].contains("write_file(*)"), + "the one-token mode pin must come last: {argv:?}" + ); + assert!( + argv.windows(2) + .any(|w| w[0] == "--output-format" && w[1] == "json") + ); + assert!(envs.is_empty(), "repo-location env leaked to agy: {envs:?}"); + let _ = env; +} + +#[test] +fn ask_runs_readonly_in_a_throwaway_dir_with_the_pin_last() { + let env = Env::new("ask"); + let caller = env.root.clone(); + let o = env.run( + &caller, + &["ask", "What is 6*7?"], + &[ + ("CLAUDE_PROJECT_DIR", caller.to_str().unwrap()), + ("GIT_DIR", "/x/.git"), + ("AGY_JOB_WORKSPACE", "/x"), + ], + ); + assert!(o.status.success(), "{}", stderr(&o)); + assert_eq!(stdout(&o), "stub answer\n"); + let calls = env.print_calls(); + assert_eq!(calls.len(), 1); + assert_readonly_contract(&env, &calls[0], &caller); + let prompt = std::fs::read_to_string(&env.prompt_out).unwrap(); + assert!(prompt.starts_with("What is 6*7?"), "{prompt}"); + assert!( + prompt.contains("read-only session"), + "agy is told which tools it has: {prompt}" + ); + assert!( + !Path::new(&calls[0].0).exists(), + "throwaway workspace removed afterwards" + ); +} + +#[test] +fn ask_model_alias_resolves_to_the_listed_id() { + let env = Env::new("model"); + let o = env.run(&env.root, &["ask", "--model", "FLASH-LOW", "hi"], &[]); + assert!(o.status.success(), "{}", stderr(&o)); + let argv = &env.print_calls()[0].1; + assert!( + argv.windows(2) + .any(|w| w[0] == "--model" && w[1] == "gemini-3.8-flash-low"), + "{argv:?}" + ); + let o = env.run(&env.root, &["ask", "--model", "pro", "hi"], &[]); + assert_eq!(o.status.code(), Some(64)); + assert!(stderr(&o).contains("no matching model")); + let o = env.run(&env.root, &["ask", "--model"], &[]); + assert_eq!(o.status.code(), Some(64)); +} + +#[test] +fn blocked_writes_are_reported_without_the_skip_permissions_hint() { + let env = Env::new("denied"); + let o = env.run( + &env.root, + &["ask", "overwrite /etc/hosts"], + &[ + ("STUB_RESPONSE", ""), + ("STUB_DENIED", "write_file"), + ( + "STUB_STDERR", + "jetski: re-run with --dangerously-skip-permissions to auto-approve all tools.", + ), + ], + ); + assert_eq!(o.status.code(), Some(1)); + let e = stderr(&o); + assert!(e.contains("read-only command blocks"), "{e}"); + assert!(!e.contains("dangerously"), "must not relay the hint: {e}"); +} + +#[test] +fn dangerous_passthrough_flags_are_refused_before_agy_runs() { + let env = Env::new("passthrough"); + for extra in [ + &["--mode", "auto"][..], + &["--dangerously-skip-permissions"], + &["--settings={}"], + &["--add-dir", "/"], + ] { + let mut args = vec!["ask", "hi"]; + args.extend_from_slice(extra); + let o = env.run(&env.root, &args, &[]); + assert_eq!(o.status.code(), Some(64), "{extra:?}"); + } + assert!(env.print_calls().is_empty()); + let o = env.run( + &env.root, + &["ask", "hi", "--print-timeout", "1m", "--effort", "low"], + &[], + ); + assert!(o.status.success(), "{}", stderr(&o)); +} + +#[test] +fn fails_closed_when_agy_defaults_to_auto_and_cannot_be_pinned() { + let env = Env::new("nopin"); + let o = env.run( + &env.root, + &["ask", "hi"], + &[ + ("STUB_VERSION", "1.5.9"), + ("STUB_HELP", "Usage of agy:\n --output-format x"), + ], + ); + assert_eq!(o.status.code(), Some(1)); + assert!(stderr(&o).contains("Refusing to run a read-only command")); + assert!(env.print_calls().is_empty(), "agy must not run"); +} + +#[test] +fn too_old_agy_and_missing_login_are_reported() { + let env = Env::new("old"); + let o = env.run(&env.root, &["ask", "hi"], &[("STUB_VERSION", "1.1.5")]); + assert_eq!(o.status.code(), Some(1)); + assert!(stderr(&o).contains("too old")); + std::fs::remove_dir_all(env.home.join(".gemini")).unwrap(); + let o = env.run(&env.root, &["ask", "hi"], &[]); + assert_eq!(o.status.code(), Some(1)); + assert!(stderr(&o).contains("not authenticated")); +} + +#[test] +fn scrape_guards_and_normalizes_urls() { + let env = Env::new("scrape"); + for bad in [ + "file:///etc/passwd", + "http://169.254.169.254/latest/meta-data/", + "http://2130706433/", + "http://1.2.3.4.127.0.0.1.nip.io/", + ] { + let o = env.run(&env.root, &["scrape", bad], &[]); + assert_eq!(o.status.code(), Some(65), "{bad}: {}", stderr(&o)); + } + assert!(env.print_calls().is_empty()); + let o = env.run(&env.root, &["scrape"], &[]); + assert_eq!(o.status.code(), Some(64)); + // A successful scrape downloads over the network; that path is covered + // by fetch.rs unit tests (local server) and scripts/e2e-live.sh. +} + +#[test] +fn doc_to_md_validates_and_stages_under_a_fixed_name() { + let env = Env::new("doc"); + std::fs::write(env.root.join(".env"), "SECRET=1").unwrap(); + let o = env.run(&env.root, &["doc-to-md", ".env"], &[]); + assert_eq!(o.status.code(), Some(65)); + std::fs::create_dir_all(env.home.join(".ssh")).unwrap(); + std::fs::write(env.home.join(".ssh").join("notes.md"), "k").unwrap(); + let o = env.run( + &env.root, + &[ + "doc-to-md", + env.home.join(".ssh/notes.md").to_str().unwrap(), + ], + &[], + ); + assert_eq!(o.status.code(), Some(65), "{}", stderr(&o)); + // An injection-shaped file name (Windows forbids '"' in names). + let evil = if cfg!(windows) { + "evil name ignore previous.md" + } else { + "evil \"name\" ignore previous.md" + }; + std::fs::write(env.root.join(evil), "# Title\n").unwrap(); + let o = env.run(&env.root, &["doc-to-md", evil], &[]); + assert!(o.status.success(), "{}", stderr(&o)); + let prompt = std::fs::read_to_string(&env.prompt_out).unwrap(); + assert!( + prompt.contains("\"document.md\"") && !prompt.contains("ignore previous"), + "{prompt}" + ); + assert_eq!(env.print_calls().len(), 1); +} + +#[test] +fn review_stages_materials_and_blocks_secrets_in_both_passes() { + let env = Env::new("review"); + let r = repo(&env); + // No diff yet. + let o = env.run(&r, &["review"], &[]); + assert_eq!(o.status.code(), Some(1)); + std::fs::write( + r.join("calc.js"), + "function add(a,b){return a-b}\nmodule.exports={add}\n", + ) + .unwrap(); + let o = env.run(&r, &["review", "focus on math"], &[]); + assert!(o.status.success(), "{}", stderr(&o)); + assert!(stdout(&o).contains("stub answer")); + let calls = env.print_calls(); + assert_readonly_contract(&env, &calls[0], &r); + let prompt = std::fs::read_to_string(&env.prompt_out).unwrap(); + assert!( + prompt.contains("diff.patch") + && prompt.contains("calc.js") + && prompt.contains("focus on math") + ); + assert!( + !Path::new(&calls[0].0).exists(), + "stage dir removed by the worker" + ); + assert!(r.join(".agy-plugin/jobs").is_dir()); + + // Pass 1: secret added in the diff. + std::fs::write(r.join("calc.js"), "const k = \"AKIAABCDEFGHIJKLMNOP\";\n").unwrap(); + let o = env.run(&r, &["review"], &[]); + assert_eq!(o.status.code(), Some(65), "{}", stderr(&o)); + // Removed lines are sent too: `git rm` of a secrets file must be refused. + git(&r, &["checkout", "-q", "--", "calc.js"]); + std::fs::write( + r.join(".env.example"), + "ANTHROPIC=sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123\n", + ) + .unwrap(); + git(&r, &["add", "-A"]); + git(&r, &["commit", "-qm", "env"]); + git(&r, &["rm", "-q", ".env.example"]); + let o = env.run(&r, &["review"], &[]); + assert_eq!( + o.status.code(), + Some(65), + "deleted secret file: {}", + stderr(&o) + ); + git(&r, &["reset", "-q", "--hard", "HEAD"]); + + // Pass 2: secret on an unchanged line far outside the diff's context + // window — only the full-file copy shipped to agy contains it. + let filler: String = (0..60).map(|i| format!("const f{i}=0;\n")).collect(); + std::fs::write( + r.join("cfg.js"), + format!("const KEY=\"AKIAABCDEFGHIJKLMNOP\";\n{filler}const a=1;\n"), + ) + .unwrap(); + git(&r, &["add", "-A"]); + git(&r, &["commit", "-qm", "cfg"]); + std::fs::write( + r.join("cfg.js"), + format!("const KEY=\"AKIAABCDEFGHIJKLMNOP\";\n{filler}const a=2;\n"), + ) + .unwrap(); + let before = env.print_calls().len(); + let o = env.run(&r, &["review"], &[]); + assert_eq!(o.status.code(), Some(65), "{}", stderr(&o)); + assert!(stderr(&o).contains("full content of a changed file")); + assert_eq!(env.print_calls().len(), before, "agy never ran on a secret"); + let o = env.run(&r, &["review"], &[("AGY_REVIEW_ALLOW_SECRETS", "1")]); + assert!(o.status.success(), "{}", stderr(&o)); +} + +#[test] +fn background_review_status_result_and_wait() { + let env = Env::new("bg"); + let r = repo(&env); + std::fs::write(r.join("calc.js"), "x\n").unwrap(); + let o = env.run(&r, &["adversarial-review", "--background", "--wait"], &[]); + assert!(o.status.success(), "{}{}", stdout(&o), stderr(&o)); + let out = stdout(&o); + assert!( + out.contains("stub answer") && out.contains("ended with status: completed"), + "{out}" + ); + let o = env.run(&r, &["status"], &[]); + assert!(stdout(&o).contains("[done]") && stdout(&o).contains("adversarial-review")); + let o = env.run(&r, &["result"], &[]); + assert!(stdout(&o).contains("--- output ---") && stdout(&o).contains("stub answer")); + let o = env.run(&r, &["status", "agy-zz"], &[]); + assert_eq!(o.status.code(), Some(64)); + let o = env.run(&r, &["status", "agy-00000000"], &[]); + assert_eq!(o.status.code(), Some(2)); +} + +#[test] +fn rescue_rails_dirty_tree_and_isolate() { + let env = Env::new("rescue"); + let r = repo(&env); + let o = env.run(&r, &["rescue"], &[]); + assert_eq!(o.status.code(), Some(64)); + std::fs::write(r.join("dirty.txt"), "x").unwrap(); + let o = env.run(&r, &["rescue", "fix", "it"], &[]); + assert_eq!(o.status.code(), Some(1)); + assert!(stderr(&o).contains("dirty working tree")); + assert!(env.print_calls().is_empty()); + std::fs::remove_file(r.join("dirty.txt")).unwrap(); + + // Unknown agy flag before the task no longer swallows the task. + let o = env.run(&r, &["rescue", "--sandbox", "fix", "the", "bug"], &[]); + assert!(o.status.success(), "{}", stderr(&o)); + let (cwd, argv, _) = env.print_calls().pop().unwrap(); + assert_eq!(Path::new(&cwd), r.as_path()); + assert!(argv.contains(&"--dangerously-skip-permissions".to_string())); + assert!(argv.contains(&"--sandbox".to_string())); + assert_eq!( + std::fs::read_to_string(&env.prompt_out).unwrap(), + "fix the bug" + ); + + // --isolate: the agy run happens in a throwaway worktree. + let o = env.run(&r, &["rescue", "--isolate", "touch", "nothing"], &[]); + assert!(o.status.success(), "{}", stderr(&o)); + let (cwd, _, _) = env.print_calls().pop().unwrap(); + assert_ne!(Path::new(&cwd), r.as_path()); + assert!(stdout(&o).contains("your working tree was NOT touched")); + assert!(!Path::new(&cwd).exists(), "worktree removed"); +} + +/// Running = exists and is not a zombie (Linux: /proc state; elsewhere +/// kill -0). +#[cfg(unix)] +fn running(pid: u32) -> bool { + if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) { + return !stat + .rsplit_once(')') + .is_some_and(|r| r.1.trim_start().starts_with('Z')); + } + if cfg!(target_os = "linux") { + return false; + } + Command::new("kill") + .args(["-0", &pid.to_string()]) + .status() + .is_ok_and(|s| s.success()) +} + +#[cfg(unix)] +#[test] +fn cancel_stops_a_background_job_and_its_agy() { + let env = Env::new("cancel"); + let r = repo(&env); + let stub_pid_file = env.root.join("stub.pid"); + let o = env.run( + &r, + &["rescue", "--background", "slow", "task"], + &[ + ("STUB_SLEEP_MS", "60000"), + ("STUB_PID_OUT", stub_pid_file.to_str().unwrap()), + ], + ); + assert!(o.status.success(), "{}", stderr(&o)); + let out = stdout(&o); + let id = out + .split_whitespace() + .find(|w| w.starts_with("agy-")) + .unwrap() + .to_string(); + // Wait for the worker to start agy. + let deadline = Instant::now() + Duration::from_secs(10); + while env.print_calls().is_empty() { + assert!(Instant::now() < deadline, "agy never started"); + std::thread::sleep(Duration::from_millis(50)); + } + let pid: u32 = std::fs::read_to_string(r.join(format!(".agy-plugin/runtime/{id}.pid"))) + .unwrap() + .trim() + .parse() + .unwrap(); + let o = env.run(&r, &["cancel", &id], &[]); + assert!(o.status.success(), "{}{}", stdout(&o), stderr(&o)); + assert!(stdout(&o).contains("canceled (killed)")); + let o = env.run(&r, &["status", &id], &[]); + assert!(stdout(&o).contains("[cancel]")); + // The worker AND the agy it started are gone (a zombie awaiting its + // reaper counts as gone). + let agy_pid: u32 = std::fs::read_to_string(env.root.join("stub.pid")) + .unwrap() + .trim() + .parse() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + while (running(pid) || running(agy_pid)) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + assert!(!running(pid), "worker still running"); + assert!(!running(agy_pid), "agy still running"); + let o = env.run(&r, &["cancel", &id], &[]); + assert_eq!(o.status.code(), Some(2)); +} + +#[test] +fn image_copies_only_from_agy_artifact_dirs() { + let env = Env::new("image"); + let brain = env.home.join(".gemini/antigravity-cli/brain/c1"); + std::fs::create_dir_all(&brain).unwrap(); + let img = brain.join("red.png"); + std::fs::write(&img, "PNG").unwrap(); + let out = env.root.join("out.png"); + let o = env.run( + &env.root, + &[ + "image", + "--output", + out.to_str().unwrap(), + "a", + "red", + "square", + ], + &[ + ("STUB_MARKER_FROM_PROMPT", "1"), + ("STUB_IMAGE", img.to_str().unwrap()), + ], + ); + assert!(o.status.success(), "{}", stderr(&o)); + assert_eq!(std::fs::read_to_string(&out).unwrap(), "PNG"); + let secret = env.root.join("secret.png"); + std::fs::write(&secret, "SECRET").unwrap(); + let o = env.run( + &env.root, + &["image", "x"], + &[ + ("STUB_MARKER_FROM_PROMPT", "1"), + ("STUB_IMAGE", secret.to_str().unwrap()), + ], + ); + assert_eq!(o.status.code(), Some(66), "{}", stderr(&o)); + let o = env.run(&env.root, &["image"], &[]); + assert_eq!(o.status.code(), Some(64)); +} + +#[test] +fn check_help_version_and_unknown() { + let env = Env::new("misc"); + let o = env.run(&env.root, &["check"], &[]); + let s = stdout(&o); + assert!( + s.contains("\"installed\":true") + && s.contains("\"version\":\"1.5.16\"") + && s.contains("\"supported\":true"), + "{s}" + ); + let o = env.run(&env.root, &["help"], &[]); + assert!(o.status.success() && stdout(&o).contains("Gemini 3.8 Flash (Low)")); + let o = env.run(&env.root, &["version"], &[]); + assert!(stdout(&o).starts_with("{\"version\":\"")); + let o = env.run(&env.root, &["nope"], &[]); + assert_eq!(o.status.code(), Some(64)); +} diff --git a/tests/helpers.bash b/tests/helpers.bash deleted file mode 100644 index 1b93bcd..0000000 --- a/tests/helpers.bash +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env bash -# Shared helpers for the bats suite. -# Sources agy-run.sh in "library mode" — the script has a sourcing -# guard (`if [ "${BASH_SOURCE[0]:-}" = "${0:-}" ]; then main "$@"; fi`) -# so functions become callable without triggering main(). - -REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -AGY_RUN="${REPO_ROOT}/plugins/agy/scripts/agy-run.sh" - -# Source the wrapper into the current shell. Bats runs each @test in a -# subshell, so this is per-test scoped. -# -# The wrapper sets `set -euo pipefail` at the top. We turn errexit off -# after sourcing because bats tests intentionally trigger non-zero exit -# codes via `run` and assertions — we don't want a stray failing -# assertion to abort the whole @test body. -load_agy_run() { - # shellcheck disable=SC1090 - source "$AGY_RUN" - set +e -} - -# Run a function from agy-run.sh and capture stdout + exit code into -# the standard bats globals ($status, $output). -run_agy_fn() { - load_agy_run - run "$@" -} diff --git a/tests/image_path_allowlist.bats b/tests/image_path_allowlist.bats deleted file mode 100644 index 7217a12..0000000 --- a/tests/image_path_allowlist.bats +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env bats -# Tests for _image_source_in_allowlist. The helper must accept paths -# inside agy's artifacts directories and reject everything else — -# including the canonicalized form of symlinks pointing outside. - -load helpers - -setup() { - load_agy_run - # Sandbox HOME so we don't pollute the user's real ~/.gemini. - # _image_source_in_allowlist reads $HOME inline, so this override - # takes effect immediately without re-sourcing the script. - TEST_HOME="$(mktemp -d 2>/dev/null || mktemp -d -t agy-bats)" - HOME="$TEST_HOME" - TEST_BRAIN="${HOME}/.gemini/antigravity-cli/brain" - mkdir -p "$TEST_BRAIN" - TEST_OK_FILE="${TEST_BRAIN}/ok.png" - touch "$TEST_OK_FILE" - TEST_BAD_FILE="${TMPDIR:-/tmp}/agy-bats-bad-$$.png" - touch "$TEST_BAD_FILE" -} - -teardown() { - rm -rf "$TEST_HOME" 2>/dev/null || true - rm -f "$TEST_BAD_FILE" 2>/dev/null || true -} - -@test "accepts a path inside ~/.gemini/antigravity-cli/brain/" { - load_agy_run - _image_source_in_allowlist "$TEST_OK_FILE" -} - -@test "rejects a path in /tmp" { - load_agy_run - run _image_source_in_allowlist "$TEST_BAD_FILE" - [ "$status" -ne 0 ] -} - -@test "rejects /etc/passwd" { - load_agy_run - run _image_source_in_allowlist "/etc/passwd" - [ "$status" -ne 0 ] -} - -@test "rejects empty input" { - load_agy_run - run _image_source_in_allowlist "" - [ "$status" -ne 0 ] -} - -@test "rejects a symlink whose target is outside the allowlist" { - load_agy_run - local symlink="${TEST_BRAIN}/agy-test-symlink.png" - ln -sf "$TEST_BAD_FILE" "$symlink" - run _image_source_in_allowlist "$symlink" - # _canonicalize_path resolves the symlink, so the check should reject. - # Fallback (no realpath / readlink -f / python3) would keep the literal - # path and accept it — we tolerate that on environments without any - # canonicalization tool, since CI has all three. - if command -v realpath >/dev/null 2>&1 || \ - command -v readlink >/dev/null 2>&1 || \ - command -v python3 >/dev/null 2>&1; then - [ "$status" -ne 0 ] - fi - rm -f "$symlink" -} diff --git a/tests/lib.agy.test.mjs b/tests/lib.agy.test.mjs deleted file mode 100644 index d67472a..0000000 --- a/tests/lib.agy.test.mjs +++ /dev/null @@ -1,102 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { findAgyBinary, getAuthStatus } from "../plugins/agy/scripts/lib/agy.mjs"; - -let tmpDir; -let fakeHome; - -beforeEach(async () => { - tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-bin-")); - fakeHome = path.join(tmpDir, "home"); - await fsp.mkdir(fakeHome, { recursive: true }); -}); -afterEach(async () => { - await fsp.rm(tmpDir, { recursive: true, force: true }); -}); - -describe("findAgyBinary", () => { - it("honors AGY_BIN when the file exists", async () => { - const fakeAgy = path.join(tmpDir, "fake-agy"); - await fsp.writeFile(fakeAgy, "#!/usr/bin/env true\n"); - await fsp.chmod(fakeAgy, 0o755); - const found = await findAgyBinary({ AGY_BIN: fakeAgy, PATH: "" }); - expect(found).toBe(fakeAgy); - }); - - it("ignores AGY_BIN when the file is missing", async () => { - const ghost = path.join(tmpDir, "ghost-agy"); - const found = await findAgyBinary({ - AGY_BIN: ghost, - PATH: tmpDir, - HOME: fakeHome, - LOCALAPPDATA: path.join(fakeHome, "AppData", "Local"), - }); - // The missing AGY_BIN must NOT be returned. It either falls through - // to null (no agy anywhere) or to a real `agy` on the machine's - // PATH — both are correct; the point is the ghost path is rejected. - // (Asserting strict null is non-hermetic: it fails on a dev box that - // actually has agy installed, which is exactly where we want tests - // to keep passing.) - expect(found).not.toBe(ghost); - }); - - it("finds a binary placed in ~/.local/bin/agy", async () => { - const localBin = path.join(fakeHome, ".local", "bin"); - await fsp.mkdir(localBin, { recursive: true }); - const candidate = path.join(localBin, "agy"); - await fsp.writeFile(candidate, ""); - const found = await findAgyBinary({ - AGY_BIN: "", - PATH: tmpDir, // no `agy` here - HOME: fakeHome, - LOCALAPPDATA: path.join(fakeHome, "AppData", "Local"), - }); - // findAgyBinary may find agy on the real PATH; only assert when - // the fallback path resolves. - if (found === candidate) { - expect(found).toBe(candidate); - } else { - // Test environment has real agy on PATH — assert it's not null. - expect(found).not.toBeNull(); - } - }); -}); - -describe("getAuthStatus", () => { - it("returns api-key when ANTIGRAVITY_API_KEY is set", async () => { - const s = await getAuthStatus({ - ANTIGRAVITY_API_KEY: "sk-abc", - HOME: fakeHome, - }); - expect(s).toBe("api-key"); - }); - - it("returns oauth when ~/.gemini/antigravity-cli exists", async () => { - const oauthDir = path.join(fakeHome, ".gemini", "antigravity-cli"); - await fsp.mkdir(oauthDir, { recursive: true }); - const s = await getAuthStatus({ HOME: fakeHome }); - expect(s).toBe("oauth"); - }); - - it("returns oauth when ~/.config/antigravity exists", async () => { - const cfgDir = path.join(fakeHome, ".config", "antigravity"); - await fsp.mkdir(cfgDir, { recursive: true }); - const s = await getAuthStatus({ HOME: fakeHome }); - expect(s).toBe("oauth"); - }); - - it("returns missing on a clean home", async () => { - const s = await getAuthStatus({ HOME: fakeHome }); - expect(s).toBe("missing"); - }); - - it("returns missing when no HOME and no API key", async () => { - const s = await getAuthStatus({ HOME: "" }); - // Empty HOME triggers the early "missing" branch; ensure we don't - // throw. - expect(["missing", "oauth"]).toContain(s); - }); -}); diff --git a/tests/lib.args.test.mjs b/tests/lib.args.test.mjs deleted file mode 100644 index a452c03..0000000 --- a/tests/lib.args.test.mjs +++ /dev/null @@ -1,112 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { parseArgs, joinPositional, splitArgString } from "../plugins/agy/scripts/lib/args.mjs"; - -const SCHEMA = { - boolean: ["background", "wait", "resume", "fresh"], - value: ["model", "base", "name", "output"], -}; - -describe("parseArgs", () => { - it("returns defaults for empty argv", () => { - const r = parseArgs([], SCHEMA); - expect(r.flags.background).toBe(false); - expect(r.values.model).toBeNull(); - expect(r.positional).toEqual([]); - expect(r.errors).toEqual([]); - }); - - it("parses a boolean flag", () => { - // argv arrives pre-tokenized by the shell; parseArgs does not - // re-split tokens that already contain spaces. - const r = parseArgs(["--background", "task", "text"], SCHEMA); - expect(r.flags.background).toBe(true); - expect(r.positional).toEqual(["task", "text"]); - }); - - it("parses --model X (space-separated)", () => { - const r = parseArgs(["--model", "opus", "fix", "the", "bug"], SCHEMA); - expect(r.values.model).toBe("opus"); - expect(r.positional).toEqual(["fix", "the", "bug"]); - }); - - it("parses --model=X (equals form)", () => { - const r = parseArgs(["--model=opus", "fix", "bug"], SCHEMA); - expect(r.values.model).toBe("opus"); - expect(r.positional).toEqual(["fix", "bug"]); - }); - - it("reports --model= with empty value", () => { - const r = parseArgs(["--model="], SCHEMA); - expect(r.values.model).toBeNull(); - expect(r.errors[0]).toContain("--model="); - }); - - it("reports --model with no value at end of argv", () => { - const r = parseArgs(["--model"], SCHEMA); - expect(r.errors[0]).toContain("--model"); - }); - - it("rejects a value on a boolean flag", () => { - const r = parseArgs(["--background=yes"], SCHEMA); - expect(r.errors[0]).toContain("--background"); - expect(r.flags.background).toBe(false); - }); - - it("forwards unknown flags to extra", () => { - const r = parseArgs(["--sandbox", "--print-timeout", "10m", "do", "the", "thing"], SCHEMA); - expect(r.extra).toEqual(["--sandbox", "--print-timeout", "10m"]); - expect(r.positional).toEqual(["do", "the", "thing"]); - }); - - it("`--` terminates flag parsing", () => { - const r = parseArgs(["--model", "opus", "--", "--this-is-not-a-flag", "task"], SCHEMA); - expect(r.values.model).toBe("opus"); - expect(r.positional).toEqual(["--this-is-not-a-flag", "task"]); - }); - - it("handles --base ref alongside positional", () => { - const r = parseArgs(["--base", "main", "focus", "on", "race", "conditions"], SCHEMA); - expect(r.values.base).toBe("main"); - expect(r.positional).toEqual(["focus", "on", "race", "conditions"]); - }); - - it("multiple boolean flags coexist", () => { - const r = parseArgs(["--background", "--wait", "--resume", "go"], SCHEMA); - expect(r.flags.background).toBe(true); - expect(r.flags.wait).toBe(true); - expect(r.flags.resume).toBe(true); - }); -}); - -describe("joinPositional", () => { - it("joins positional with single spaces", () => { - const r = parseArgs(["--background", "hello", "world"], SCHEMA); - expect(joinPositional(r)).toBe("hello world"); - }); - it("trims edge whitespace", () => { - const r = parseArgs([" hi "], SCHEMA); - expect(joinPositional(r)).toBe("hi"); - }); -}); - -describe("splitArgString", () => { - it("splits bare tokens", () => { - expect(splitArgString("a b c")).toEqual(["a", "b", "c"]); - }); - it("respects single-quoted groups", () => { - expect(splitArgString("a 'b c' d")).toEqual(["a", "b c", "d"]); - }); - it("respects double-quoted groups", () => { - expect(splitArgString('a "b c" d')).toEqual(["a", "b c", "d"]); - }); - it("handles backslash escapes in double quotes", () => { - expect(splitArgString('"a\\"b" c')).toEqual(['a"b', "c"]); - }); - it("handles literal backslash outside quotes", () => { - expect(splitArgString("a\\ b c")).toEqual(["a b", "c"]); - }); - it("returns [] for empty input", () => { - expect(splitArgString("")).toEqual([]); - expect(splitArgString(undefined)).toEqual([]); - }); -}); diff --git a/tests/lib.fs.test.mjs b/tests/lib.fs.test.mjs deleted file mode 100644 index eeffada..0000000 --- a/tests/lib.fs.test.mjs +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { - ensureDir, - writeAtomic, - readJson, - writeJson, - appendLogLine, - pathExists, - nowIso, -} from "../plugins/agy/scripts/lib/fs.mjs"; - -let tmpDir; - -beforeEach(async () => { - tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-fs-test-")); -}); - -afterEach(async () => { - await fsp.rm(tmpDir, { recursive: true, force: true }); -}); - -describe("ensureDir", () => { - it("creates nested directories", async () => { - const target = path.join(tmpDir, "a", "b", "c"); - await ensureDir(target); - const stat = await fsp.stat(target); - expect(stat.isDirectory()).toBe(true); - }); - it("is idempotent", async () => { - const target = path.join(tmpDir, "x"); - await ensureDir(target); - await ensureDir(target); - expect(await pathExists(target)).toBe(true); - }); -}); - -describe("writeAtomic + readJson", () => { - it("round-trips a JSON object", async () => { - const f = path.join(tmpDir, "state.json"); - await writeJson(f, { hello: "world", count: 7 }); - const back = await readJson(f); - expect(back).toEqual({ hello: "world", count: 7 }); - }); - - it("leaves no .tmp- artifact after successful write", async () => { - const f = path.join(tmpDir, "state.json"); - await writeJson(f, { a: 1 }); - const entries = await fsp.readdir(tmpDir); - expect(entries.filter((e) => e.includes(".tmp-"))).toEqual([]); - }); - - it("readJson returns fallback when file missing", async () => { - const r = await readJson(path.join(tmpDir, "absent.json"), { default: true }); - expect(r).toEqual({ default: true }); - }); - - it("readJson throws when file missing and no fallback", async () => { - await expect(readJson(path.join(tmpDir, "absent.json"))).rejects.toThrow(); - }); - - it("readJson throws on invalid JSON", async () => { - const f = path.join(tmpDir, "bad.json"); - await fsp.writeFile(f, "{not json"); - await expect(readJson(f, {})).rejects.toThrow(); - }); - - it("writeAtomic accepts a string body", async () => { - const f = path.join(tmpDir, "raw.txt"); - await writeAtomic(f, "hello\n"); - expect(await fsp.readFile(f, "utf8")).toBe("hello\n"); - }); -}); - -describe("appendLogLine", () => { - it("creates the file and adds a trailing newline", async () => { - const f = path.join(tmpDir, "logs", "x.log"); - await appendLogLine(f, "first"); - await appendLogLine(f, "second\n"); - expect(await fsp.readFile(f, "utf8")).toBe("first\nsecond\n"); - }); -}); - -describe("pathExists", () => { - it("returns true for existing files", async () => { - const f = path.join(tmpDir, "x"); - await fsp.writeFile(f, ""); - expect(await pathExists(f)).toBe(true); - }); - it("returns false for missing paths", async () => { - expect(await pathExists(path.join(tmpDir, "nope"))).toBe(false); - }); -}); - -describe("nowIso", () => { - it("returns parseable UTC ISO-8601 with ms", () => { - const s = nowIso(); - expect(s).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/); - expect(Number.isFinite(Date.parse(s))).toBe(true); - }); -}); diff --git a/tests/lib.git.test.mjs b/tests/lib.git.test.mjs deleted file mode 100644 index 5a281ea..0000000 --- a/tests/lib.git.test.mjs +++ /dev/null @@ -1,346 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { spawnSync } from "node:child_process"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - gitRoot, - currentBranch, - resolveRef, - mergeBase, - workingTreeDiff, - branchDiff, - gatherFileContext, - isGitRepo, - isWorkingTreeClean, - changeSummary, - addWorktree, - removeWorktree, - captureWorktreePatch, -} from "../plugins/agy/scripts/lib/git.mjs"; - -let repo; - -function git(cwd, args) { - const r = spawnSync("git", args, { cwd, encoding: "utf8" }); - if (r.status !== 0) { - throw new Error( - `git ${args.join(" ")} failed (exit ${r.status}):\n${r.stderr || r.stdout}`, - ); - } - return r.stdout; -} - -beforeEach(async () => { - repo = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-git-")); - // Initialize a non-interactive repo with a stable identity so commit - // shas are reproducible-ish. - git(repo, ["init", "-q", "-b", "main"]); - git(repo, ["config", "user.email", "test@example.com"]); - git(repo, ["config", "user.name", "Test"]); - git(repo, ["config", "commit.gpgsign", "false"]); - await fsp.writeFile(path.join(repo, "README.md"), "v1\n"); - git(repo, ["add", "README.md"]); - git(repo, ["commit", "-q", "-m", "initial"]); -}); -afterEach(async () => { - if (repo) await fsp.rm(repo, { recursive: true, force: true }); -}); - -describe("gitRoot", () => { - it("returns the toplevel for a path inside the repo", async () => { - const subdir = path.join(repo, "nested"); - await fsp.mkdir(subdir, { recursive: true }); - const found = await gitRoot(subdir); - // git returns forward slashes on Windows; fsp.realpath returns - // backslashes. Normalize via path.resolve before comparing. - expect(path.resolve(found)).toBe(path.resolve(await fsp.realpath(repo))); - }); - - it("returns null when called outside a git repo", async () => { - const outside = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-not-git-")); - try { - expect(await gitRoot(outside)).toBeNull(); - } finally { - await fsp.rm(outside, { recursive: true, force: true }); - } - }); -}); - -describe("currentBranch / resolveRef / mergeBase", () => { - it("currentBranch returns 'main' on a fresh repo", async () => { - expect(await currentBranch(repo)).toBe("main"); - }); - - it("resolveRef returns a 40-char sha for HEAD", async () => { - const sha = await resolveRef(repo, "HEAD"); - expect(sha).toMatch(/^[a-f0-9]{40}$/); - }); - - it("resolveRef returns null for a bogus ref", async () => { - expect(await resolveRef(repo, "does-not-exist")).toBeNull(); - }); - - it("mergeBase between HEAD and itself is HEAD", async () => { - const head = await resolveRef(repo, "HEAD"); - expect(await mergeBase(repo, "HEAD", "HEAD")).toBe(head); - }); -}); - -describe("workingTreeDiff", () => { - it("returns an empty diff for a clean tree", async () => { - const ctx = await workingTreeDiff(repo); - expect(ctx.scope).toBe("working-tree"); - expect(ctx.diff).toBe(""); - expect(ctx.files).toEqual([]); - }); - - it("captures uncommitted changes", async () => { - await fsp.writeFile(path.join(repo, "README.md"), "v1\nadded line\n"); - const ctx = await workingTreeDiff(repo); - expect(ctx.scope).toBe("working-tree"); - expect(ctx.diff).toContain("added line"); - expect(ctx.files).toContain("README.md"); - }); - - it("throws when called outside a git repo", async () => { - const outside = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-no-git-")); - try { - await expect(workingTreeDiff(outside)).rejects.toThrow(/not in a git repo/); - } finally { - await fsp.rm(outside, { recursive: true, force: true }); - } - }); -}); - -describe("branchDiff", () => { - it("captures the changes introduced by a feature branch", async () => { - git(repo, ["checkout", "-q", "-b", "feature"]); - await fsp.writeFile(path.join(repo, "feature.txt"), "new file\n"); - git(repo, ["add", "feature.txt"]); - git(repo, ["commit", "-q", "-m", "feat: add feature.txt"]); - const ctx = await branchDiff(repo, "main"); - expect(ctx.scope).toBe("branch"); - expect(ctx.base).toBe("main"); - expect(ctx.diff).toContain("feature.txt"); - expect(ctx.files).toContain("feature.txt"); - expect(ctx.mergeBase).toMatch(/^[a-f0-9]{40}$/); - }); - - it("throws on a base ref that doesn't resolve", async () => { - await expect(branchDiff(repo, "nope-branch")).rejects.toThrow(/cannot resolve/); - }); -}); - -describe("safety helpers (rescue guards + isolation)", () => { - it("isGitRepo true inside repo, false outside", async () => { - expect(await isGitRepo(repo)).toBe(true); - const outside = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-nogit-")); - try { - expect(await isGitRepo(outside)).toBe(false); - } finally { - await fsp.rm(outside, { recursive: true, force: true }); - } - }); - - it("isWorkingTreeClean: true on a fresh commit, false after an edit", async () => { - expect(await isWorkingTreeClean(repo)).toBe(true); - await fsp.writeFile(path.join(repo, "README.md"), "v1\ndirty\n"); - expect(await isWorkingTreeClean(repo)).toBe(false); - }); - - it("isWorkingTreeClean: false when there's an untracked file", async () => { - await fsp.writeFile(path.join(repo, "new.txt"), "hi\n"); - expect(await isWorkingTreeClean(repo)).toBe(false); - }); - - it("changeSummary reports edited + untracked files", async () => { - await fsp.writeFile(path.join(repo, "README.md"), "v1\nchanged\n"); - await fsp.writeFile(path.join(repo, "brand-new.txt"), "x\n"); - const s = await changeSummary(repo); - expect(s).toContain("README.md"); - expect(s).toMatch(/brand-new\.txt/); - }); - - it("changeSummary on a clean tree says no changes", async () => { - expect(await changeSummary(repo)).toMatch(/no changes/i); - }); - - it("worktree round-trip: add → edit isolated → capture patch → real tree untouched → remove", async () => { - const wtParent = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-wt-")); - const wtDir = path.join(wtParent, "wt"); - try { - const added = await addWorktree(repo, wtDir); - expect(added.ok).toBe(true); - - // Edit inside the worktree only. - await fsp.writeFile(path.join(wtDir, "README.md"), "v1\nfrom-worktree\n"); - await fsp.writeFile(path.join(wtDir, "added-in-wt.txt"), "new\n"); - - const { stat, patch } = await captureWorktreePatch(wtDir); - expect(stat).toContain("README.md"); - expect(patch).toContain("from-worktree"); - expect(patch).toContain("added-in-wt.txt"); - - // The REAL repo must be untouched by the worktree edits. - expect(await fsp.readFile(path.join(repo, "README.md"), "utf8")).toBe("v1\n"); - await expect(fsp.access(path.join(repo, "added-in-wt.txt"))).rejects.toThrow(); - } finally { - await removeWorktree(repo, wtDir); - await fsp.rm(wtParent, { recursive: true, force: true }); - } - }); -}); - -describe("gatherFileContext", () => { - it("includes small text files, skips large ones", async () => { - await fsp.writeFile(path.join(repo, "small.js"), "export const a = 1;\n"); - const big = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n"); - await fsp.writeFile(path.join(repo, "big.js"), big + "\n"); - const r = await gatherFileContext(repo, ["small.js", "big.js"], { maxLines: 10 }); - expect(r.included.map((f) => f.path)).toEqual(["small.js"]); - expect(r.included[0].content).toContain("export const a = 1;"); - expect(r.omitted.find((o) => o.path === "big.js").reason).toMatch(/too large/); - }); - - it("marks missing files as omitted", async () => { - const r = await gatherFileContext(repo, ["does-not-exist.js"]); - expect(r.included).toEqual([]); - expect(r.omitted[0].reason).toMatch(/missing/); - }); - - it("respects the total byte budget", async () => { - await fsp.writeFile(path.join(repo, "a.txt"), "x".repeat(100) + "\n"); - await fsp.writeFile(path.join(repo, "b.txt"), "y".repeat(100) + "\n"); - const r = await gatherFileContext(repo, ["a.txt", "b.txt"], { budgetBytes: 120 }); - expect(r.included.length).toBe(1); - // The second file no longer fits — it's rejected by the pre-read - // size check ("too large (N bytes)") or the post-read budget check. - const b = r.omitted.find((o) => o.path === "b.txt"); - expect(b).toBeTruthy(); - expect(b.reason).toMatch(/too large|budget/); - }); - - it("skips binary content (NUL byte)", async () => { - await fsp.writeFile(path.join(repo, "bin.dat"), Buffer.from([0x41, 0x00, 0x42])); - const r = await gatherFileContext(repo, ["bin.dat"]); - expect(r.included).toEqual([]); - expect(r.omitted[0].reason).toBe("binary"); - }); -}); - -describe("gatherFileContext — safety edges (symlink, pre-read size)", () => { - it("skips a symlinked path instead of following it", async () => { - const target = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-tgt-")); - const secret = path.join(target, "secret.txt"); - await fsp.writeFile(secret, "SENSITIVE\n"); - const link = path.join(repo, "link.txt"); - try { - await fsp.symlink(secret, link); - } catch { - return; // symlink not permitted (e.g. Windows w/o privilege) — skip - } - const r = await gatherFileContext(repo, ["link.txt"]); - expect(r.included).toEqual([]); - expect(r.omitted[0].reason).toMatch(/symlink/); - await fsp.rm(target, { recursive: true, force: true }); - }); - - it("rejects a too-large file via stat without reading it all", async () => { - const big = path.join(repo, "big.bin"); - await fsp.writeFile(big, "z".repeat(5000)); - const r = await gatherFileContext(repo, ["big.bin"], { budgetBytes: 1000 }); - expect(r.included).toEqual([]); - expect(r.omitted[0].reason).toMatch(/too large \(\d+ bytes\)/); - }); -}); - -describe("gatherFileContext — directory-symlink containment", () => { - it("skips a file reached through a symlinked directory pointing outside the repo", async () => { - const outside = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-out-")); - await fsp.writeFile(path.join(outside, "secret.txt"), "TOPSECRET\n"); - const linkdir = path.join(repo, "linkdir"); - try { - await fsp.symlink(outside, linkdir, "dir"); - } catch { - return; // no symlink privilege (Windows) — skip - } - const r = await gatherFileContext(repo, ["linkdir/secret.txt"]); - expect(r.included).toEqual([]); - expect(r.omitted[0].reason).toMatch(/outside the repo|symlink/); - await fsp.rm(outside, { recursive: true, force: true }); - }); -}); - -describe("stageReviewMaterials (Design A+)", () => { - it("writes diff.patch and full file content under files/", async () => { - const { stageReviewMaterials } = await import("../plugins/agy/scripts/lib/git.mjs"); - await fsp.writeFile(path.join(repo, "a.js"), "export const a = 1;\n"); - await fsp.mkdir(path.join(repo, "sub"), { recursive: true }); - await fsp.writeFile(path.join(repo, "sub", "b.js"), "export const b = 2;\n"); - const stage = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-stage-")); - try { - const r = await stageReviewMaterials(stage, repo, ["a.js", "sub/b.js"], "DIFFTEXT"); - expect(r.staged.sort()).toEqual(["a.js", "sub/b.js"]); - expect(await fsp.readFile(path.join(stage, "diff.patch"), "utf8")).toBe("DIFFTEXT"); - expect(await fsp.readFile(path.join(stage, "files", "a.js"), "utf8")).toContain("const a = 1"); - expect(await fsp.readFile(path.join(stage, "files", "sub", "b.js"), "utf8")).toContain("const b = 2"); - } finally { - await fsp.rm(stage, { recursive: true, force: true }); - } - }); - - it("skips symlinks, binaries, and missing files (omitted with reasons)", async () => { - const { stageReviewMaterials } = await import("../plugins/agy/scripts/lib/git.mjs"); - await fsp.writeFile(path.join(repo, "bin.dat"), Buffer.from([0x41, 0x00, 0x42])); - const stage = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-stage-")); - try { - const r = await stageReviewMaterials(stage, repo, ["bin.dat", "ghost.js"], "d"); - expect(r.staged).toEqual([]); - const reasons = Object.fromEntries(r.omitted.map((o) => [o.path, o.reason])); - expect(reasons["bin.dat"]).toBe("binary"); - expect(reasons["ghost.js"]).toMatch(/missing/); - } finally { - await fsp.rm(stage, { recursive: true, force: true }); - } - }); - - it("does not follow a symlinked file out of the repo", async () => { - const { stageReviewMaterials } = await import("../plugins/agy/scripts/lib/git.mjs"); - const outside = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-out-")); - await fsp.writeFile(path.join(outside, "secret.txt"), "SECRET\n"); - const link = path.join(repo, "link.txt"); - let madeLink = true; - try { await fsp.symlink(path.join(outside, "secret.txt"), link); } catch { madeLink = false; } - const stage = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-stage-")); - try { - if (madeLink) { - const r = await stageReviewMaterials(stage, repo, ["link.txt"], "d"); - expect(r.staged).toEqual([]); - await expect(fsp.access(path.join(stage, "files", "link.txt"))).rejects.toThrow(); - } - } finally { - await fsp.rm(stage, { recursive: true, force: true }); - await fsp.rm(outside, { recursive: true, force: true }); - } - }); -}); - -describe("stageReviewMaterials — dest path traversal guards", () => { - it("skips absolute and ..-escaping relpaths instead of writing/crashing", async () => { - const { stageReviewMaterials } = await import("../plugins/agy/scripts/lib/git.mjs"); - const stage = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-stage-")); - try { - const abs = process.platform === "win32" ? "C:/Windows/system32/x.txt" : "/etc/passwd"; - const r = await stageReviewMaterials(stage, repo, [abs, "../../escape.txt"], "d"); - expect(r.staged).toEqual([]); - const reasons = r.omitted.map((o) => o.reason).join("|"); - expect(reasons).toMatch(/absolute path|escapes stage/); - // nothing leaked outside the stage dir - await expect(fsp.access(path.join(stage, "..", "escape.txt"))).rejects.toThrow(); - } finally { - await fsp.rm(stage, { recursive: true, force: true }); - } - }); -}); diff --git a/tests/lib.inputguard.test.mjs b/tests/lib.inputguard.test.mjs deleted file mode 100644 index df405c7..0000000 --- a/tests/lib.inputguard.test.mjs +++ /dev/null @@ -1,227 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - isBlockedHost, - validateScrapeUrl, - isSensitivePath, - validateDocPath, - isUncPath, - stageFile, -} from "../plugins/agy/scripts/lib/inputguard.mjs"; - -describe("isBlockedHost (SSRF guard)", () => { - it("allows ordinary public hosts", () => { - for (const h of ["example.com", "sub.example.co.uk", "8.8.8.8", "1.1.1.1", "github.com"]) { - expect(isBlockedHost(h)).toBe(false); - } - }); - it("blocks localhost and *.localhost / *.local / *.internal", () => { - for (const h of ["localhost", "api.localhost", "foo.local", "svc.internal", "box.lan"]) { - expect(isBlockedHost(h)).toBe(true); - } - }); - it("blocks loopback / private / link-local IPv4", () => { - for (const h of [ - "127.0.0.1", "127.1.2.3", "0.0.0.0", "10.0.0.5", "192.168.1.10", - "172.16.0.1", "172.31.255.255", "169.254.169.254", "100.64.0.1", - ]) { - expect(isBlockedHost(h)).toBe(true); - } - }); - it("allows public IPv4 just outside the private ranges", () => { - for (const h of ["172.15.0.1", "172.32.0.1", "192.169.0.1", "11.0.0.1", "8.8.4.4"]) { - expect(isBlockedHost(h)).toBe(false); - } - }); - it("blocks IPv6 loopback / link-local / ULA and v4-mapped private", () => { - for (const h of ["::1", "[::1]", "fe80::1", "fc00::1", "fd12:3456::1", "::ffff:127.0.0.1"]) { - expect(isBlockedHost(h)).toBe(true); - } - }); - it("blocks IPv4-in-IPv6 hex/compat encodings (adversarial SSRF bypass)", () => { - // 7f00:1 == 127.0.0.1, 0a00:1 == 10.0.0.1 - for (const h of ["::ffff:7f00:1", "::7f00:1", "::127.0.0.1", "::ffff:0a00:1"]) { - expect(isBlockedHost(h)).toBe(true); - } - }); - it("allows a public v4-mapped IPv6 but blocks a private one", () => { - expect(isBlockedHost("::ffff:8.8.8.8")).toBe(false); - expect(isBlockedHost("::ffff:192.168.1.1")).toBe(true); - }); - it("blocks hostnames embedding a private IPv4 as leading labels (nip.io trick)", () => { - expect(isBlockedHost("127.0.0.1.nip.io")).toBe(true); - expect(isBlockedHost("10.0.0.1.sslip.io")).toBe(true); - expect(isBlockedHost("8.8.8.8.nip.io")).toBe(false); // public embedded → allowed - }); - it("blocks a private IPv4 embedded AFTER a leading garbage label (a prefix must not defeat the guard)", () => { - // Regression: the guard used to anchor the embedded-IPv4 match at the very - // first label, so a junk prefix slipped a loopback/private host past it — - // nip.io / sslip.io resolve `..nip.io` straight to . - expect(isBlockedHost("foo.127.0.0.1.nip.io")).toBe(true); - expect(isBlockedHost("a.b.10.0.0.1.sslip.io")).toBe(true); - expect(isBlockedHost("x.169.254.169.254.nip.io")).toBe(true); // cloud metadata - expect(isBlockedHost("foo.8.8.8.8.nip.io")).toBe(false); // public embedded → still allowed - // end-to-end through the URL validator (WHATWG URL keeps these un-normalized) - expect(validateScrapeUrl("http://foo.127.0.0.1.nip.io/x").ok).toBe(false); - expect(validateScrapeUrl("http://a.b.10.0.0.1.sslip.io/").ok).toBe(false); - }); - it("blocks integer / hex / octal encoded IPs", () => { - expect(isBlockedHost("2130706433")).toBe(true); // 127.0.0.1 - expect(isBlockedHost("0x7f000001")).toBe(true); - expect(isBlockedHost("0177.0.0.1")).toBe(true); // octal - }); - it("blocks empty/garbage host", () => { - expect(isBlockedHost("")).toBe(true); - }); -}); - -describe("validateScrapeUrl", () => { - it("accepts public http/https URLs (normalized)", () => { - expect(validateScrapeUrl("https://example.com/page?q=1")).toEqual({ - ok: true, - url: "https://example.com/page?q=1", - }); - expect(validateScrapeUrl("http://example.com").ok).toBe(true); - }); - it("rejects non-http(s) schemes", () => { - for (const u of [ - "file:///etc/passwd", - "ftp://example.com/x", - "data:text/html,

x

", - "javascript:alert(1)", - "gopher://example.com", - ]) { - expect(validateScrapeUrl(u).ok).toBe(false); - } - }); - it("rejects SSRF targets", () => { - for (const u of [ - "http://localhost:8080/admin", - "http://127.0.0.1/", - "https://169.254.169.254/latest/meta-data/", - "http://10.0.0.1/", - "http://[::1]:9000/", - "http://2130706433/", - ]) { - expect(validateScrapeUrl(u).ok).toBe(false); - } - }); - it("rejects empty / non-URL input", () => { - expect(validateScrapeUrl("").ok).toBe(false); - expect(validateScrapeUrl("not a url").ok).toBe(false); - expect(validateScrapeUrl(undefined).ok).toBe(false); - }); -}); - -describe("isSensitivePath", () => { - const home = path.join(path.sep, "home", "u"); - it("flags paths under credential dirs", () => { - expect(isSensitivePath(path.join(home, ".ssh", "id_rsa"), home)).toBe(true); - expect(isSensitivePath(path.join(home, ".gemini", "x.txt"), home)).toBe(true); - expect(isSensitivePath(path.join(home, ".aws", "credentials"), home)).toBe(true); - }); - it("does not flag ordinary project paths", () => { - expect(isSensitivePath(path.join(home, "projects", "doc.pdf"), home)).toBe(false); - }); -}); - -describe("validateDocPath", () => { - let dir; - beforeEach(async () => { - dir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-ig-")); - }); - afterEach(async () => { - await fsp.rm(dir, { recursive: true, force: true }); - }); - - it("accepts an allowed document type", async () => { - const f = path.join(dir, "notes.md"); - await fsp.writeFile(f, "# hi\n"); - const r = await validateDocPath("notes.md", { cwd: dir }); - expect(r.ok).toBe(true); - expect(r.ext).toBe(".md"); - }); - - it("rejects a non-document extension (fail closed)", async () => { - const f = path.join(dir, "secrets.env"); - await fsp.writeFile(f, "API_KEY=abc\n"); - const r = await validateDocPath("secrets.env", { cwd: dir }); - expect(r.ok).toBe(false); - expect(r.reason).toMatch(/not an allowed document type/); - }); - - it("rejects a missing file", async () => { - expect((await validateDocPath("nope.pdf", { cwd: dir })).ok).toBe(false); - }); - - it("rejects a directory", async () => { - await fsp.mkdir(path.join(dir, "sub.md")); - expect((await validateDocPath("sub.md", { cwd: dir })).ok).toBe(false); - }); - - it("rejects a file under a sensitive dir even with an allowed extension", async () => { - const fakeHome = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-home-")); - const ssh = path.join(fakeHome, ".ssh"); - await fsp.mkdir(ssh, { recursive: true }); - const f = path.join(ssh, "notes.md"); - await fsp.writeFile(f, "secret"); - const r = await validateDocPath(f, { cwd: dir, homedir: fakeHome }); - expect(r.ok).toBe(false); - expect(r.reason).toMatch(/sensitive/); - await fsp.rm(fakeHome, { recursive: true, force: true }); - }); -}); - -describe("isUncPath", () => { - it("flags UNC and device paths", () => { - expect(isUncPath("\\\\localhost\\c$\\Users\\u\\.ssh\\id_rsa")).toBe(true); - expect(isUncPath("\\\\?\\C:\\x")).toBe(true); - expect(isUncPath("//server/share/x")).toBe(true); - }); - it("does not flag ordinary paths", () => { - expect(isUncPath("C:\\Users\\u\\doc.pdf")).toBe(false); - expect(isUncPath("/home/u/doc.pdf")).toBe(false); - expect(isUncPath("doc.pdf")).toBe(false); - }); -}); - -describe("stageFile (TOCTOU-resistant staging)", () => { - let dir; - beforeEach(async () => { - dir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-stage-")); - }); - afterEach(async () => { - await fsp.rm(dir, { recursive: true, force: true }); - }); - - it("copies a regular file to the destination", async () => { - const src = path.join(dir, "src.md"); - await fsp.writeFile(src, "hello"); - const dest = path.join(dir, "document.md"); - const r = stageFile(src, dest); - expect(r.ok).toBe(true); - expect(await fsp.readFile(dest, "utf8")).toBe("hello"); - }); - - it("rejects a missing source and missing args", () => { - expect(stageFile(path.join(dir, "nope"), path.join(dir, "d")).ok).toBe(false); - expect(stageFile("", "").ok).toBe(false); - }); - - it("rejects a symlink source (the TOCTOU swap vector)", async () => { - const target = path.join(dir, "secret"); - await fsp.writeFile(target, "secret"); - const link = path.join(dir, "link.md"); - try { - await fsp.symlink(target, link); - } catch { - return; // symlink not permitted on this host (e.g. Windows w/o privilege) — skip - } - const r = stageFile(link, path.join(dir, "out.md")); - expect(r.ok).toBe(false); - expect(r.reason).toMatch(/symlink/); - }); -}); diff --git a/tests/lib.job-control.test.mjs b/tests/lib.job-control.test.mjs deleted file mode 100644 index db649eb..0000000 --- a/tests/lib.job-control.test.mjs +++ /dev/null @@ -1,152 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - createJob, - updateJob, -} from "../plugins/agy/scripts/lib/state.mjs"; -import { - liveness, - buildStatusSnapshot, - resolveJob, - resolveCancelable, -} from "../plugins/agy/scripts/lib/job-control.mjs"; - -let workspaceRoot; - -beforeEach(async () => { - workspaceRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-jc-")); -}); -afterEach(async () => { - await fsp.rm(workspaceRoot, { recursive: true, force: true }); -}); - -describe("liveness", () => { - it("downgrades running+dead-PID to failed", () => { - const dead = liveness({ status: "running", pid: 99999999 }); - expect(dead.status).toBe("failed"); - expect(dead.livenessDowngrade).toBe(true); - }); - - it("leaves running with a live PID alone (our own PID)", () => { - const alive = liveness({ status: "running", pid: process.pid }); - expect(alive.status).toBe("running"); - expect(alive.livenessDowngrade).toBeUndefined(); - }); - - it("leaves terminal statuses alone", () => { - for (const s of ["completed", "failed", "canceled", "pending"]) { - expect(liveness({ status: s, pid: 99999999 }).status).toBe(s); - } - }); - - it("handles null/undefined records gracefully", () => { - expect(liveness(null)).toBeNull(); - expect(liveness(undefined)).toBeUndefined(); - }); -}); - -describe("buildStatusSnapshot", () => { - it("returns recent jobs newest-first with liveness applied", async () => { - const a = await createJob(workspaceRoot, { kind: "rescue", task: "a" }); - await new Promise((r) => setTimeout(r, 3)); - const b = await createJob(workspaceRoot, { kind: "rescue", task: "b" }); - await updateJob(workspaceRoot, b.id, { status: "running", pid: 99999999 }); - - const snap = await buildStatusSnapshot(workspaceRoot, { limit: 5 }); - expect(snap[0].id).toBe(b.id); - expect(snap[0].status).toBe("failed"); // liveness downgrade - expect(snap[1].id).toBe(a.id); - expect(snap[1].status).toBe("pending"); - }); - - it("filters by kind", async () => { - await createJob(workspaceRoot, { kind: "rescue", task: "r1" }); - const rev = await createJob(workspaceRoot, { kind: "review", task: "rv" }); - const snap = await buildStatusSnapshot(workspaceRoot, { kind: "review" }); - expect(snap.map((r) => r.id)).toEqual([rev.id]); - }); -}); - -describe("resolveJob", () => { - it("empty input resolves to latest", async () => { - await createJob(workspaceRoot, { kind: "rescue", task: "old" }); - await new Promise((r) => setTimeout(r, 3)); - const newer = await createJob(workspaceRoot, { kind: "rescue", task: "new" }); - const r = await resolveJob(workspaceRoot, ""); - expect(r.record?.id).toBe(newer.id); - }); - - it("'latest' literal also resolves to latest", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - const r = await resolveJob(workspaceRoot, "latest"); - expect(r.record?.id).toBe(j.id); - }); - - it("returns not-found on empty workspace", async () => { - const r = await resolveJob(workspaceRoot, ""); - expect(r.record).toBeNull(); - expect(r.reason).toBe("not-found"); - }); - - it("full id returns exact match", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - const r = await resolveJob(workspaceRoot, j.id); - expect(r.record?.id).toBe(j.id); - }); - - it("returns not-found for valid id that doesn't exist", async () => { - const r = await resolveJob(workspaceRoot, "agy-deadbeef"); - expect(r.record).toBeNull(); - expect(r.reason).toBe("not-found"); - }); - - it("matches unique prefix", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - const prefix = j.id.slice(0, 6); // "agy-XX" - const r = await resolveJob(workspaceRoot, prefix); - expect(r.record?.id).toBe(j.id); - }); - - it("reports ambiguous prefix", async () => { - // Force two ids with the same prefix by writing them directly. - const j1 = await createJob(workspaceRoot, { kind: "rescue", task: "1", id: "agy-aaaa0001" }); - const j2 = await createJob(workspaceRoot, { kind: "rescue", task: "2", id: "agy-aaaa0002" }); - const r = await resolveJob(workspaceRoot, "agy-aaaa"); - expect(r.record).toBeNull(); - expect(r.reason).toBe("ambiguous"); - expect(r.candidates).toEqual(expect.arrayContaining([j1.id, j2.id])); - }); - - it("returns bad-id for unrecognized format", async () => { - const r = await resolveJob(workspaceRoot, "not-a-job"); - expect(r.record).toBeNull(); - expect(r.reason).toBe("bad-id"); - }); -}); - -describe("resolveCancelable", () => { - it("rejects completed jobs as not-cancelable", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "done" }); - await updateJob(workspaceRoot, j.id, { status: "completed" }); - const r = await resolveCancelable(workspaceRoot, j.id); - expect(r.record).toBeNull(); - expect(r.reason).toBe("not-cancelable"); - expect(r.existing?.id).toBe(j.id); - }); - - it("accepts running jobs", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "live" }); - await updateJob(workspaceRoot, j.id, { status: "running", pid: process.pid }); - const r = await resolveCancelable(workspaceRoot, j.id); - expect(r.record?.id).toBe(j.id); - }); - - it("accepts pending jobs", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "wait" }); - const r = await resolveCancelable(workspaceRoot, j.id); - expect(r.record?.id).toBe(j.id); - }); -}); diff --git a/tests/lib.process.test.mjs b/tests/lib.process.test.mjs deleted file mode 100644 index aebc9ed..0000000 --- a/tests/lib.process.test.mjs +++ /dev/null @@ -1,109 +0,0 @@ -import { describe, it, expect } from "vitest"; -import process from "node:process"; -import { - binaryAvailable, - runCaptured, - processAlive, - terminate, - spawnDetached, -} from "../plugins/agy/scripts/lib/process.mjs"; - -const isWindows = process.platform === "win32"; - -// Use `node -e ` everywhere so the tests are uniform across -// macOS, Linux, and Windows — sh vs cmd semantics keep biting us -// otherwise. -function nodeEval(code) { - return [process.execPath, ["-e", code]]; -} - -describe("binaryAvailable", () => { - it("finds a known binary on PATH", async () => { - // `node` is guaranteed since this test runs under node. - expect(await binaryAvailable("node")).toBe(true); - }); - - it("returns false for a definitely-missing binary", async () => { - expect(await binaryAvailable("definitely-not-a-real-binary-zzz-xxx")).toBe(false); - }); - - it("returns false for empty input", async () => { - expect(await binaryAvailable("")).toBe(false); - expect(await binaryAvailable(null)).toBe(false); - }); -}); - -describe("runCaptured", () => { - it("captures stdout", async () => { - const [cmd, args] = nodeEval("process.stdout.write('hello\\n')"); - const r = await runCaptured(cmd, args); - expect(r.exitCode).toBe(0); - expect(r.stdout).toBe("hello\n"); - }); - - it("captures stderr separately from stdout", async () => { - const [cmd, args] = nodeEval( - "process.stdout.write('out\\n'); process.stderr.write('err\\n')", - ); - const r = await runCaptured(cmd, args); - expect(r.stdout).toContain("out"); - expect(r.stderr).toContain("err"); - }); - - it("returns non-zero exit code without throwing", async () => { - const [cmd, args] = nodeEval("process.exit(7)"); - const r = await runCaptured(cmd, args); - expect(r.exitCode).toBe(7); - }); - - it("pipes stdin via `input`", async () => { - const [cmd, args] = nodeEval( - "process.stdin.on('data', c => process.stdout.write(c))", - ); - const r = await runCaptured(cmd, args, { input: "ping\npong\n" }); - expect(r.exitCode).toBe(0); - expect(r.stdout).toBe("ping\npong\n"); - }); - - it("honors timeoutMs (kills a long-running child)", async () => { - const start = Date.now(); - // 30-second sleep that we expect to be killed at 500ms. - const [cmd, args] = nodeEval("setTimeout(() => {}, 30000)"); - const r = await runCaptured(cmd, args, { timeoutMs: 500 }); - const elapsed = Date.now() - start; - expect(elapsed).toBeLessThan(4000); - expect(r.killed).toBe(true); - }, 8000); - - it("reports spawnError when the binary doesn't exist", async () => { - const r = await runCaptured("definitely-not-a-real-binary-zzz", []); - expect(r.spawnError).toBe(true); - expect(r.exitCode).toBeNull(); - }); -}); - -describe("processAlive / terminate / spawnDetached", () => { - it("processAlive is true for self, false for tiny invalid PIDs", () => { - expect(processAlive(process.pid)).toBe(true); - expect(processAlive(0)).toBe(false); - expect(processAlive(-1)).toBe(false); - }); - - it("spawnDetached returns a PID and the child is alive briefly", async () => { - if (isWindows) return; // detached semantics differ on Windows - const pid = spawnDetached(process.execPath, ["-e", "setTimeout(()=>{}, 5000)"], { - stdinIgnore: true, - }); - expect(typeof pid).toBe("number"); - expect(pid).toBeGreaterThan(0); - // Give the OS a moment to actually start the process. - await new Promise((r) => setTimeout(r, 200)); - expect(processAlive(pid)).toBe(true); - const gone = await terminate(pid, { graceMs: 1000 }); - expect(gone).toBe(true); - }); - - it("terminate returns true for an already-dead pid", async () => { - expect(await terminate(99999999)).toBe(true); - }); -}); diff --git a/tests/lib.prompts.test.mjs b/tests/lib.prompts.test.mjs deleted file mode 100644 index 6c50cf0..0000000 --- a/tests/lib.prompts.test.mjs +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { - buildReviewPrompt, - buildAdversarialPrompt, - PROMPT_INTERNALS, -} from "../plugins/agy/scripts/lib/prompts.mjs"; - -const WORKING_TREE = { - scope: "working-tree", - base: "HEAD", - head: "(uncommitted)", - diff: "--- a/foo.js\n+++ b/foo.js\n+const x = 1;\n", - files: ["foo.js"], - root: "/tmp/repo", -}; - -const BRANCH = { - scope: "branch", - base: "main", - baseSha: "abc1234", - head: "def5678", - mergeBase: "fff0000", - diff: "--- a/bar.ts\n+++ b/bar.ts\n+function add(a, b) { return a + b; }\n", - files: ["bar.ts", "bar.test.ts"], - root: "/tmp/repo", -}; - -const STAGE = "/tmp/agy-review-xyz"; -const STAGED = ["bar.ts", "bar.test.ts"]; - -describe("buildReviewPrompt (Design A+ staged)", () => { - it("includes the preamble and rules", () => { - const p = buildReviewPrompt({ diffContext: WORKING_TREE, stageDir: STAGE, staged: ["foo.js"] }); - expect(p).toContain(PROMPT_INTERNALS.PREAMBLE_REVIEW.slice(0, 30)); - for (const rule of PROMPT_INTERNALS.REVIEW_RULES) expect(p).toContain(rule); - }); - - it("renders the working-tree vs branch scope blurb", () => { - expect(buildReviewPrompt({ diffContext: WORKING_TREE, stageDir: STAGE, staged: [] })) - .toMatch(/Working-tree review/); - const b = buildReviewPrompt({ diffContext: BRANCH, stageDir: STAGE, staged: STAGED }); - expect(b).toMatch(/Branch review/); - expect(b).toContain("`main`"); - expect(b).toContain(BRANCH.mergeBase); - }); - - it("points at the staged diff and files instead of embedding them", () => { - const p = buildReviewPrompt({ diffContext: BRANCH, stageDir: STAGE, staged: STAGED }); - expect(p).toContain(`${STAGE}/diff.patch`); - expect(p).toContain(`${STAGE}/files`); - expect(p).toContain("- bar.ts"); - expect(p).toContain("- bar.test.ts"); - // The diff CONTENT must NOT be embedded (that was the ENAMETOOLONG source). - expect(p).not.toContain("function add(a, b)"); - expect(p).not.toContain("```diff"); - }); - - it("notes omitted files and tells agy to mark cross-context concerns UNVERIFIED", () => { - const p = buildReviewPrompt({ - diffContext: BRANCH, - stageDir: STAGE, - staged: ["bar.ts"], - omitted: [{ path: "huge.bin", reason: "binary" }], - }); - expect(p).toContain("huge.bin"); - expect(p).toMatch(/UNVERIFIED/); - }); - - it("focus block present only when focus is non-empty", () => { - expect(buildReviewPrompt({ diffContext: WORKING_TREE, stageDir: STAGE, staged: [], focus: "error handling" })) - .toContain("error handling"); - expect(buildReviewPrompt({ diffContext: WORKING_TREE, stageDir: STAGE, staged: [], focus: "" })) - .not.toContain("User focus"); - }); -}); - -describe("buildAdversarialPrompt (Design A+ staged)", () => { - it("uses the adversarial preamble + rules, not the review ones", () => { - const p = buildAdversarialPrompt({ diffContext: WORKING_TREE, stageDir: STAGE, staged: [] }); - expect(p).toContain(PROMPT_INTERNALS.PREAMBLE_ADVERSARIAL.slice(0, 30)); - expect(p).not.toContain(PROMPT_INTERNALS.PREAMBLE_REVIEW.slice(0, 30)); - for (const rule of PROMPT_INTERNALS.ADVERSARIAL_RULES) expect(p).toContain(rule); - expect(p).not.toContain(PROMPT_INTERNALS.REVIEW_RULES[0]); - }); - - it("also points at staged materials and frames focus as pressure", () => { - const p = buildAdversarialPrompt({ - diffContext: BRANCH, - stageDir: STAGE, - staged: STAGED, - focus: "the retry/backoff design", - }); - expect(p).toContain(`${STAGE}/diff.patch`); - expect(p).toMatch(/pressure/i); - expect(p).toContain("the retry/backoff design"); - }); - - it("uses Windows-style separators when stageDir is a Windows path", () => { - const p = buildReviewPrompt({ - diffContext: WORKING_TREE, - stageDir: "C:\\Temp\\agy-review-xyz", - staged: ["foo.js"], - }); - expect(p).toContain("C:\\Temp\\agy-review-xyz\\diff.patch"); - }); -}); diff --git a/tests/lib.render.test.mjs b/tests/lib.render.test.mjs deleted file mode 100644 index eb97789..0000000 --- a/tests/lib.render.test.mjs +++ /dev/null @@ -1,125 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { - renderStatusList, - renderJobDetail, - renderResult, - renderCancelReport, -} from "../plugins/agy/scripts/lib/render.mjs"; - -const SAMPLE = { - id: "agy-3a7b9c12", - kind: "rescue", - task: "investigate the flaky integration test", - model: "opus", - status: "running", - createdAt: "2026-05-28T15:00:00.000Z", - startedAt: "2026-05-28T15:00:01.000Z", - completedAt: null, - exitCode: null, - pid: 12345, - logFile: ".agy-plugin/logs/agy-3a7b9c12.log", - workspaceRoot: "/repo", -}; - -describe("renderStatusList", () => { - it("returns empty-state message for []", () => { - expect(renderStatusList([])).toMatch(/no agy jobs/i); - }); - - it("returns a header row plus one line per job", () => { - const out = renderStatusList([SAMPLE, { ...SAMPLE, id: "agy-abcdef99", status: "completed" }]); - const lines = out.trim().split("\n"); - expect(lines[0]).toMatch(/ID\s+STATUS\s+KIND/); - expect(lines).toHaveLength(3); - expect(lines[1]).toContain("agy-3a7b9c12"); - expect(lines[2]).toContain("agy-abcdef99"); - }); - - it("renders status badges", () => { - const out = renderStatusList([SAMPLE]); - expect(out).toContain("[running]"); - }); - - it("clips long task descriptions", () => { - const long = { ...SAMPLE, task: "x".repeat(200) }; - const out = renderStatusList([long]); - expect(out).toContain("…"); - }); -}); - -describe("renderJobDetail", () => { - it("returns 'not found' when record is null", () => { - expect(renderJobDetail(null)).toMatch(/not found/i); - }); - - it("shows all the headline fields", () => { - const out = renderJobDetail(SAMPLE); - expect(out).toContain("agy-3a7b9c12"); - expect(out).toContain("[running]"); - expect(out).toContain("rescue"); - expect(out).toContain("opus"); - expect(out).toContain("investigate the flaky integration test"); - expect(out).toContain("12345"); - expect(out).toContain(".agy-plugin/logs/agy-3a7b9c12.log"); - }); - - it("displays — for null fields", () => { - const minimal = { ...SAMPLE, model: null, pid: null, completedAt: null, exitCode: null }; - const out = renderJobDetail(minimal); - expect(out).toMatch(/Model:\s+\(default\)/); - expect(out).toMatch(/Completed:\s+—/); - expect(out).toMatch(/Exit code:\s+—/); - expect(out).toMatch(/PID:\s+—/); - }); - - it("surfaces liveness downgrade note", () => { - const out = renderJobDetail({ ...SAMPLE, livenessDowngrade: true }); - expect(out).toMatch(/PID is dead/i); - }); -}); - -describe("renderResult", () => { - it("returns short message when record is null", () => { - expect(renderResult(null, "anything")).toMatch(/No job/i); - }); - - it("includes detail header plus the log body", () => { - const out = renderResult({ ...SAMPLE, status: "completed", exitCode: 0 }, "the agy reply\n"); - expect(out).toContain("agy-3a7b9c12"); - expect(out).toContain("--- output ---"); - expect(out).toContain("the agy reply"); - }); - - it("handles empty log", () => { - const out = renderResult({ ...SAMPLE, status: "completed" }, ""); - expect(out).toContain("(log file is empty"); - }); - - it("ensures trailing newline", () => { - const out = renderResult({ ...SAMPLE, status: "completed" }, "no trailing newline here"); - expect(out.endsWith("\n")).toBe(true); - }); -}); - -describe("renderCancelReport", () => { - it("reports a successful cancel", () => { - const r = renderCancelReport("agy-12345678", { canceled: true, reason: "killed" }); - expect(r).toMatch(/canceled/); - expect(r).toContain("agy-12345678"); - }); - - it("reports not-found", () => { - const r = renderCancelReport("agy-deadbeef", { canceled: false, reason: "not-found" }); - expect(r).toMatch(/not found/i); - }); - - it("reports not-cancelable with status", () => { - const r = renderCancelReport("agy-12345678", { - canceled: false, - reason: "not-cancelable", - record: { status: "completed" }, - }); - expect(r).toMatch(/already finished/); - expect(r).toMatch(/completed/); - }); -}); diff --git a/tests/lib.secrets.test.mjs b/tests/lib.secrets.test.mjs deleted file mode 100644 index 5161a3f..0000000 --- a/tests/lib.secrets.test.mjs +++ /dev/null @@ -1,100 +0,0 @@ -import { describe, it, expect } from "vitest"; -import { scanDiffForSecrets, scanTextForSecrets } from "../plugins/agy/scripts/lib/secrets.mjs"; - -const d = (...lines) => lines.join("\n"); - -describe("scanDiffForSecrets", () => { - it("clean diff returns no hits", () => { - expect(scanDiffForSecrets(d("+const x = 1;", "-let y = 2;"))).toEqual([]); - }); - - it("empty / undefined input", () => { - expect(scanDiffForSecrets("")).toEqual([]); - expect(scanDiffForSecrets(undefined)).toEqual([]); - }); - - it("detects an AWS access key in an added line", () => { - expect(scanDiffForSecrets(d('+key = "AKIAIOSFODNN7EXAMPLE"'))).toContain("AWS access key"); - }); - - it("detects a GitHub PAT", () => { - expect( - scanDiffForSecrets(d('+t = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"')), - ).toContain("GitHub personal access token"); - }); - - it("detects a PEM private key block", () => { - expect(scanDiffForSecrets(d("+-----BEGIN RSA PRIVATE KEY-----"))).toContain( - "PEM private key block", - ); - }); - - it("detects an inline credential assignment", () => { - expect( - scanDiffForSecrets(d('+API_KEY = "abcdef0123456789ABCDEF0123456789"')), - ).toContain("inline credential assignment"); - }); - - it("ignores secrets on REMOVED lines", () => { - expect(scanDiffForSecrets(d('-AWS = "AKIAIOSFODNN7EXAMPLE"'))).toEqual([]); - }); - - it("ignores the +++ file header even if it looks like a key", () => { - expect(scanDiffForSecrets(d("+++ b/AKIAIOSFODNN7EXAMPLE.txt", "+hello"))).toEqual([]); - }); - - it("does not flag a benign code reference (value side has a dot)", () => { - expect(scanDiffForSecrets(d("+const password = formData.password;"))).toEqual([]); - }); -}); - -describe("scanDiffForSecrets — case-insensitivity (parity with grep -i)", () => { - it("catches a lowercased AWS-key form", () => { - expect(scanDiffForSecrets('+x = "akiaiosfodnn7example"')).toContain("AWS access key"); - }); - it("catches an uppercased GitHub PAT prefix", () => { - expect( - scanDiffForSecrets('+x = "GHP_ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJ"'), - ).toContain("GitHub personal access token"); - }); -}); - -describe("scanDiffForSecrets — fine-grained GitHub PAT", () => { - it("detects github_pat_ tokens", () => { - const tok = "github_pat_" + "A".repeat(82); - expect(scanDiffForSecrets(`+token = "${tok}"`)).toContain("GitHub fine-grained PAT"); - }); -}); - -describe("scanTextForSecrets (raw content — powers the GAP-2 full-file scan)", () => { - it("scans raw text with no `+` prefix required", () => { - expect(scanTextForSecrets('const k = "AKIAIOSFODNN7EXAMPLE";')).toContain("AWS access key"); - }); - it("empty / undefined → no hits", () => { - expect(scanTextForSecrets("")).toEqual([]); - expect(scanTextForSecrets(undefined)).toEqual([]); - }); -}); - -describe("modern API key formats (GAP-3)", () => { - const ant = "sk-ant-api03-" + "A".repeat(30); - const proj = "sk-proj-" + "B".repeat(30); - const legacy = "sk-" + "c".repeat(40); - - it("detects an Anthropic sk-ant- key (raw + diff)", () => { - expect(scanTextForSecrets(ant)).toContain("Anthropic API key"); - expect(scanDiffForSecrets(`+key = "${ant}"`)).toContain("Anthropic API key"); - }); - it("detects an OpenAI sk-proj- key", () => { - expect(scanTextForSecrets(proj)).toContain("OpenAI project key"); - }); - it("still detects a legacy sk- key", () => { - expect(scanTextForSecrets(legacy)).toContain("OpenAI legacy API key"); - }); - it("does not flag a dashed identifier that merely contains 'sk-'", () => { - // The legacy pattern needs 20 ALNUM after sk- (no dashes), and the - // modern patterns need the sk-ant-/sk-proj- prefix — so a kebab-case - // word like disk-management-... must not match. - expect(scanTextForSecrets("disk-management-system-controller-v2")).toEqual([]); - }); -}); diff --git a/tests/lib.state.test.mjs b/tests/lib.state.test.mjs deleted file mode 100644 index e44d4b1..0000000 --- a/tests/lib.state.test.mjs +++ /dev/null @@ -1,206 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - generateJobId, - isValidJobId, - ensureStateDirs, - ensureGitExclude, - createJob, - readJob, - updateJob, - listJobs, - deleteJob, - jobLogPath, - jobPidPath, - jobRecordPath, -} from "../plugins/agy/scripts/lib/state.mjs"; - -let workspaceRoot; - -beforeEach(async () => { - workspaceRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-state-")); -}); -afterEach(async () => { - await fsp.rm(workspaceRoot, { recursive: true, force: true }); -}); - -describe("ensureGitExclude", () => { - it("is a no-op (no throw) when the workspace is not a git repo", async () => { - await ensureGitExclude(workspaceRoot); - expect(await fsp.readdir(workspaceRoot)).not.toContain(".git"); - }); - - it("adds .agy-plugin/ to .git/info/exclude, idempotently", async () => { - await fsp.mkdir(path.join(workspaceRoot, ".git"), { recursive: true }); - await ensureGitExclude(workspaceRoot); - const exclude = path.join(workspaceRoot, ".git", "info", "exclude"); - const first = await fsp.readFile(exclude, "utf8"); - expect(first).toMatch(/^\.agy-plugin\/$/m); - await ensureGitExclude(workspaceRoot); - const second = await fsp.readFile(exclude, "utf8"); - expect((second.match(/^\.agy-plugin\/$/gm) || []).length).toBe(1); - }); -}); - -describe("generateJobId / isValidJobId", () => { - it("generates ids matching the expected shape", () => { - const id = generateJobId(); - expect(id).toMatch(/^agy-[a-f0-9]{8}$/); - expect(isValidJobId(id)).toBe(true); - }); - - it("rejects non-string and malformed ids", () => { - expect(isValidJobId(null)).toBe(false); - expect(isValidJobId(undefined)).toBe(false); - expect(isValidJobId(123)).toBe(false); - expect(isValidJobId("")).toBe(false); - expect(isValidJobId("nope")).toBe(false); - expect(isValidJobId("agy-")).toBe(false); - expect(isValidJobId("agy-XYZ12345")).toBe(false); - }); -}); - -describe("ensureStateDirs", () => { - it("creates jobs/, logs/, runtime/", async () => { - await ensureStateDirs(workspaceRoot); - const dirs = ["jobs", "logs", "runtime"].map((d) => - path.join(workspaceRoot, ".agy-plugin", d), - ); - for (const d of dirs) { - const s = await fsp.stat(d); - expect(s.isDirectory()).toBe(true); - } - }); -}); - -describe("createJob / readJob / updateJob", () => { - it("creates a record with sane defaults", async () => { - const rec = await createJob(workspaceRoot, { - kind: "rescue", - task: "investigate the bug", - model: "opus", - args: ["--sandbox"], - }); - expect(rec.id).toMatch(/^agy-/); - expect(rec.status).toBe("pending"); - expect(rec.kind).toBe("rescue"); - expect(rec.task).toBe("investigate the bug"); - expect(rec.model).toBe("opus"); - expect(rec.args).toEqual(["--sandbox"]); - expect(rec.exitCode).toBeNull(); - expect(rec.pid).toBeNull(); - expect(rec.workspaceRoot).toBe(workspaceRoot); - }); - - it("rejects invalid kind", async () => { - await expect( - createJob(workspaceRoot, { kind: "unknown-kind", task: "x" }), - ).rejects.toThrow(/invalid kind/); - }); - - it("readJob returns null for missing id", async () => { - expect(await readJob(workspaceRoot, "agy-deadbeef")).toBeNull(); - }); - - it("readJob returns null for invalid id (no I/O)", async () => { - expect(await readJob(workspaceRoot, "not-an-id")).toBeNull(); - }); - - it("updateJob merges fields and touches lastUpdatedAt", async () => { - const rec = await createJob(workspaceRoot, { kind: "rescue", task: "t" }); - const before = rec.createdAt; - await new Promise((r) => setTimeout(r, 5)); - const updated = await updateJob(workspaceRoot, rec.id, { - status: "running", - pid: 1234, - }); - expect(updated.status).toBe("running"); - expect(updated.pid).toBe(1234); - expect(updated.kind).toBe("rescue"); - expect(updated.createdAt).toBe(before); - expect(updated.lastUpdatedAt).not.toBe(before); - }); - - it("updateJob throws for missing job", async () => { - await expect( - updateJob(workspaceRoot, "agy-00000000", { status: "running" }), - ).rejects.toThrow(/no such job/); - }); - - it("updateJob rejects invalid status", async () => { - const rec = await createJob(workspaceRoot, { kind: "rescue", task: "t" }); - await expect( - updateJob(workspaceRoot, rec.id, { status: "weird" }), - ).rejects.toThrow(/invalid status/); - }); -}); - -describe("listJobs", () => { - it("returns [] for a fresh workspace", async () => { - expect(await listJobs(workspaceRoot)).toEqual([]); - }); - - it("returns newest first", async () => { - const a = await createJob(workspaceRoot, { kind: "rescue", task: "a" }); - await new Promise((r) => setTimeout(r, 5)); - const b = await createJob(workspaceRoot, { kind: "rescue", task: "b" }); - await new Promise((r) => setTimeout(r, 5)); - const c = await createJob(workspaceRoot, { kind: "research", task: "c" }); - const list = await listJobs(workspaceRoot); - expect(list.map((r) => r.id)).toEqual([c.id, b.id, a.id]); - }); - - it("filters by kind", async () => { - await createJob(workspaceRoot, { kind: "rescue", task: "1" }); - const rev = await createJob(workspaceRoot, { kind: "review", task: "2" }); - const list = await listJobs(workspaceRoot, { kind: "review" }); - expect(list.map((r) => r.id)).toEqual([rev.id]); - }); - - it("respects limit", async () => { - for (let i = 0; i < 5; i++) { - await createJob(workspaceRoot, { kind: "rescue", task: `t${i}` }); - await new Promise((r) => setTimeout(r, 2)); - } - const list = await listJobs(workspaceRoot, { limit: 2 }); - expect(list).toHaveLength(2); - }); - - it("skips corrupt records without throwing", async () => { - const rec = await createJob(workspaceRoot, { kind: "rescue", task: "good" }); - const badPath = path.join(workspaceRoot, ".agy-plugin", "jobs", "agy-broken.json"); - await fsp.writeFile(badPath, "{not json"); - // Should not throw, and should still surface the good record. - const list = await listJobs(workspaceRoot); - expect(list.map((r) => r.id)).toContain(rec.id); - expect(list.find((r) => r.id === "agy-broken")).toBeUndefined(); - }); -}); - -describe("deleteJob", () => { - it("removes record + log + pid; returns true; idempotent", async () => { - const rec = await createJob(workspaceRoot, { kind: "rescue", task: "kill me" }); - // Plant a fake log and pid file so we know they're cleaned. - await fsp.writeFile(jobLogPath(workspaceRoot, rec.id), "log\n"); - await fsp.writeFile(jobPidPath(workspaceRoot, rec.id), "12345\n"); - - expect(await deleteJob(workspaceRoot, rec.id)).toBe(true); - expect(await readJob(workspaceRoot, rec.id)).toBeNull(); - await expect(fsp.access(jobLogPath(workspaceRoot, rec.id))).rejects.toThrow(); - await expect(fsp.access(jobPidPath(workspaceRoot, rec.id))).rejects.toThrow(); - - // Second delete is a no-op. - expect(await deleteJob(workspaceRoot, rec.id)).toBe(false); - }); -}); - -describe("paths", () => { - it("are constructed under .agy-plugin/", () => { - const r = jobRecordPath(workspaceRoot, "agy-abc12345"); - expect(r).toContain(".agy-plugin"); - expect(r.endsWith(".json")).toBe(true); - }); -}); diff --git a/tests/lib.tracked-jobs.test.mjs b/tests/lib.tracked-jobs.test.mjs deleted file mode 100644 index 3ca335c..0000000 --- a/tests/lib.tracked-jobs.test.mjs +++ /dev/null @@ -1,194 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - createJob, - readJob, - updateJob, -} from "../plugins/agy/scripts/lib/state.mjs"; -import { - startTrackedJob, - runJobWorker, - cancelJob, - waitForJob, -} from "../plugins/agy/scripts/lib/tracked-jobs.mjs"; - -let workspaceRoot; - -beforeEach(async () => { - workspaceRoot = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-tj-")); -}); -afterEach(async () => { - await fsp.rm(workspaceRoot, { recursive: true, force: true }); -}); - -describe("startTrackedJob (foreground)", () => { - it("creates a pending record and does not spawn anything", async () => { - const rec = await startTrackedJob(workspaceRoot, { - kind: "rescue", - task: "investigate", - prompt: "investigate the bug", - background: false, - }); - expect(rec.status).toBe("pending"); - expect(rec.pid).toBeNull(); - expect(rec.background).toBe(false); - }); -}); - -describe("runJobWorker with injected runner", () => { - it("updates record to completed on exit 0", async () => { - const rec = await createJob(workspaceRoot, { - kind: "rescue", - task: "t", - meta: { prompt: "do thing" }, - }); - const status = await runJobWorker(workspaceRoot, rec.id, { - runner: async () => 0, - }); - expect(status).toBe("completed"); - const after = await readJob(workspaceRoot, rec.id); - expect(after.status).toBe("completed"); - expect(after.exitCode).toBe(0); - expect(after.completedAt).toBeTruthy(); - }); - - it("updates record to failed on non-zero exit", async () => { - const rec = await createJob(workspaceRoot, { - kind: "rescue", - task: "t", - meta: { prompt: "do thing" }, - }); - const status = await runJobWorker(workspaceRoot, rec.id, { - runner: async () => 7, - }); - expect(status).toBe("failed"); - const after = await readJob(workspaceRoot, rec.id); - expect(after.exitCode).toBe(7); - }); - - it("updates record to failed when runner throws", async () => { - const rec = await createJob(workspaceRoot, { - kind: "rescue", - task: "t", - meta: { prompt: "do thing" }, - }); - const status = await runJobWorker(workspaceRoot, rec.id, { - runner: async () => { throw new Error("boom"); }, - }); - expect(status).toBe("failed"); - }); - - it("throws on missing job id", async () => { - await expect( - runJobWorker(workspaceRoot, "agy-deadbeef", { runner: async () => 0 }), - ).rejects.toThrow(/no such job/); - }); -}); - -describe("cancelJob", () => { - it("returns not-found for missing job", async () => { - const r = await cancelJob(workspaceRoot, "agy-deadbeef"); - expect(r.canceled).toBe(false); - expect(r.reason).toBe("not-found"); - }); - - it("returns not-cancelable for a completed job", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "done" }); - await updateJob(workspaceRoot, j.id, { status: "completed" }); - const r = await cancelJob(workspaceRoot, j.id); - expect(r.canceled).toBe(false); - expect(r.reason).toBe("not-cancelable"); - }); - - it("marks pending job as canceled even with no PID", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - const r = await cancelJob(workspaceRoot, j.id); - expect(r.canceled).toBe(true); - const after = await readJob(workspaceRoot, j.id); - expect(after.status).toBe("canceled"); - }); - - it("kills a live child and marks canceled", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "live" }); - // Spawn a real long-running child we can kill. - const { spawn } = await import("node:child_process"); - const child = spawn(process.execPath, ["-e", "setTimeout(()=>{}, 30000)"], { - stdio: "ignore", - detached: true, - }); - child.unref(); - await updateJob(workspaceRoot, j.id, { status: "running", pid: child.pid }); - const r = await cancelJob(workspaceRoot, j.id, { graceMs: 1000 }); - expect(r.canceled).toBe(true); - const after = await readJob(workspaceRoot, j.id); - expect(after.status).toBe("canceled"); - }); -}); - -describe("waitForJob", () => { - it("returns the record once it reaches a terminal status", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - setTimeout(() => { - updateJob(workspaceRoot, j.id, { - status: "completed", - exitCode: 0, - completedAt: new Date().toISOString(), - }).catch(() => {}); - }, 200); - const final = await waitForJob(workspaceRoot, j.id, { - timeoutMs: 2000, - pollMs: 50, - }); - expect(final?.status).toBe("completed"); - }); - - it("returns null for missing job", async () => { - expect( - await waitForJob(workspaceRoot, "agy-deadbeef", { timeoutMs: 200, pollMs: 50 }), - ).toBeNull(); - }); - - it("returns the still-running record after timeout", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x" }); - await updateJob(workspaceRoot, j.id, { status: "running", pid: process.pid }); - const r = await waitForJob(workspaceRoot, j.id, { timeoutMs: 300, pollMs: 50 }); - expect(r?.status).toBe("running"); - }); -}); - -import { capPromptForArgv } from "../plugins/agy/scripts/lib/tracked-jobs.mjs"; - -describe("capPromptForArgv", () => { - it("passes a small prompt through unchanged (body + suffix)", () => { - expect(capPromptForArgv("hello", "\nSUFFIX")).toBe("hello\nSUFFIX"); - }); - - it("truncates an oversized body but keeps the suffix intact", () => { - const body = "X".repeat(50000); - const suffix = "\n---WRITE_FILE_INSTRUCTION---"; - const out = capPromptForArgv(body, suffix, 28000); - expect(Buffer.byteLength(out, "utf8")).toBeLessThanOrEqual(28000); - expect(out.endsWith(suffix)).toBe(true); - expect(out).toContain("truncated"); - }); -}); - -describe("runJobWorker — does not clobber a canceled status", () => { - it("keeps status=canceled when the job is canceled mid-run", async () => { - const j = await createJob(workspaceRoot, { kind: "rescue", task: "x", meta: { prompt: "p" } }); - await updateJob(workspaceRoot, j.id, { status: "running", pid: process.pid }); - const status = await runJobWorker(workspaceRoot, j.id, { - runner: async () => { - // Simulate /agy:cancel marking it canceled while agy runs. - await updateJob(workspaceRoot, j.id, { status: "canceled" }); - return 0; - }, - }); - expect(status).toBe("canceled"); - const after = await readJob(workspaceRoot, j.id); - expect(after.status).toBe("canceled"); - }); -}); diff --git a/tests/lib.transcript.test.mjs b/tests/lib.transcript.test.mjs deleted file mode 100644 index dd5d48f..0000000 --- a/tests/lib.transcript.test.mjs +++ /dev/null @@ -1,206 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { - agyStoreDir, - parseStoreDir, - parseConversationId, - extractAnswerFromTranscript, - transcriptPathFor, - conversationIdForWorkspace, - readTranscriptAnswer, - captureAnswer, -} from "../plugins/agy/scripts/lib/transcript.mjs"; - -const CID = "3e6627ad-6b64-48d3-a918-7eff8d87309b"; - -// A realistic transcript: user input, history, two tool-call/result pairs, -// then the final answer — matching what agy 1.0.3 writes for a review. -function transcriptFixture(answer = "FINAL ANSWER") { - return [ - { step_index: 0, source: "USER_EXPLICIT", type: "USER_INPUT", content: "review" }, - { step_index: 1, source: "SYSTEM", type: "CONVERSATION_HISTORY" }, - { step_index: 2, source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [{ name: "list_dir" }] }, - { step_index: 3, source: "MODEL", type: "LIST_DIRECTORY", content: "tool result noise — must be skipped" }, - { step_index: 5, source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [{ name: "view_file" }] }, - { step_index: 6, source: "MODEL", type: "VIEW_FILE", content: "file contents — must be skipped" }, - { step_index: 7, source: "MODEL", type: "PLANNER_RESPONSE", content: answer }, - ] - .map((o) => JSON.stringify(o)) - .join("\n"); -} - -describe("agyStoreDir", () => { - it("honors AGY_STORE_DIR above everything", () => { - expect(agyStoreDir({ AGY_STORE_DIR: "/custom/store", GEMINI_DIR: "/x" })).toBe("/custom/store"); - }); - it("derives from GEMINI_DIR when set", () => { - expect(agyStoreDir({ GEMINI_DIR: path.join("/home", "u", ".gemini") })).toBe( - path.join("/home", "u", ".gemini", "antigravity-cli"), - ); - }); - it("defaults to /.gemini/antigravity-cli", () => { - expect(agyStoreDir({}, "/home/u")).toBe(path.join("/home", "u", ".gemini", "antigravity-cli")); - }); -}); - -describe("parseConversationId", () => { - it("extracts the uuid from a real 'Created conversation' log line", () => { - const log = `I0531 03:59:20.696954 5280 server.go:755] Created conversation ${CID}\nmore`; - expect(parseConversationId(log)).toBe(CID); - }); - it("returns the LAST id when several are present", () => { - const other = "11111111-2222-3333-4444-555555555555"; - expect(parseConversationId(`Created conversation ${other}\nCreated conversation ${CID}`)).toBe(CID); - }); - it("returns null when no id is present", () => { - expect(parseConversationId("no conversation here")).toBeNull(); - expect(parseConversationId("")).toBeNull(); - expect(parseConversationId(null)).toBeNull(); - }); - it("does not match a non-uuid token", () => { - expect(parseConversationId("Created conversation not-a-uuid")).toBeNull(); - }); -}); - -describe("parseStoreDir", () => { - it("reads agy's reported data dir from the log (Windows path)", () => { - const log = "I0531 03:59:18 common.go:203] CLI app data directory: C:\\Users\\ennan\\.gemini\\antigravity-cli\r\n"; - expect(parseStoreDir(log)).toBe("C:\\Users\\ennan\\.gemini\\antigravity-cli"); - }); - it("reads a POSIX data dir (macOS / Linux / WSL)", () => { - expect(parseStoreDir("CLI app data directory: /home/u/.gemini/antigravity-cli\n")).toBe( - "/home/u/.gemini/antigravity-cli", - ); - }); - it("returns the last match and null when absent", () => { - expect(parseStoreDir("CLI app data directory: /a\nCLI app data directory: /b\n")).toBe("/b"); - expect(parseStoreDir("nothing here")).toBeNull(); - expect(parseStoreDir("")).toBeNull(); - }); -}); - -describe("extractAnswerFromTranscript", () => { - it("returns only the model's PLANNER_RESPONSE text, skipping tool calls + results", () => { - expect(extractAnswerFromTranscript(transcriptFixture("hello world"))).toBe("hello world"); - }); - it("joins multiple PLANNER_RESPONSE content blocks with a blank line", () => { - const jsonl = [ - { source: "MODEL", type: "PLANNER_RESPONSE", content: "part one" }, - { source: "MODEL", type: "VIEW_FILE", content: "noise" }, - { source: "MODEL", type: "PLANNER_RESPONSE", content: "part two" }, - ] - .map((o) => JSON.stringify(o)) - .join("\n"); - expect(extractAnswerFromTranscript(jsonl)).toBe("part one\n\npart two"); - }); - it("skips narration (a PLANNER_RESPONSE carrying a tool_call), keeping only the final answer", () => { - const jsonl = [ - { source: "MODEL", type: "PLANNER_RESPONSE", content: "I will read the file.", tool_calls: [{ name: "view_file" }] }, - { source: "MODEL", type: "VIEW_FILE", content: "file contents to skip" }, - { source: "MODEL", type: "PLANNER_RESPONSE", content: "# Final\n\nclean" }, - ] - .map((o) => JSON.stringify(o)) - .join("\n"); - expect(extractAnswerFromTranscript(jsonl)).toBe("# Final\n\nclean"); - }); - it("tolerates blank and malformed lines", () => { - const jsonl = `\n{ not json }\n${JSON.stringify({ source: "MODEL", type: "PLANNER_RESPONSE", content: "ok" })}\n\n`; - expect(extractAnswerFromTranscript(jsonl)).toBe("ok"); - }); - it("returns empty string when there is no model text", () => { - expect(extractAnswerFromTranscript("")).toBe(""); - expect( - extractAnswerFromTranscript(JSON.stringify({ source: "MODEL", type: "PLANNER_RESPONSE", tool_calls: [{ name: "x" }] })), - ).toBe(""); - }); -}); - -describe("transcriptPathFor", () => { - it("builds the brain//.system_generated/logs path", () => { - expect(transcriptPathFor("/store", CID)).toBe( - path.join("/store", "brain", CID, ".system_generated", "logs", "transcript.jsonl"), - ); - }); -}); - -describe("store-backed helpers", () => { - let store; - beforeEach(async () => { - store = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-store-")); - const logsDir = path.join(store, "brain", CID, ".system_generated", "logs"); - await fsp.mkdir(logsDir, { recursive: true }); - await fsp.writeFile(path.join(logsDir, "transcript.jsonl"), transcriptFixture("captured!")); - await fsp.mkdir(path.join(store, "cache"), { recursive: true }); - await fsp.writeFile( - path.join(store, "cache", "last_conversations.json"), - JSON.stringify({ "C:\\Users\\me\\proj": CID }), - ); - }); - afterEach(async () => { - await fsp.rm(store, { recursive: true, force: true }); - }); - - it("readTranscriptAnswer reads the model answer", async () => { - const { answer, transcriptPath } = await readTranscriptAnswer(store, CID, { retries: 0 }); - expect(answer).toBe("captured!"); - expect(transcriptPath).toContain(CID); - }); - - it("readTranscriptAnswer returns empty for an unknown conversation (no retry wait)", async () => { - const { answer } = await readTranscriptAnswer(store, "00000000-0000-0000-0000-000000000000", { - retries: 1, - delayMs: 1, - }); - expect(answer).toBe(""); - }); - - it("conversationIdForWorkspace matches case- and separator-insensitively", async () => { - expect(await conversationIdForWorkspace(store, "c:/users/me/proj")).toBe(CID); - expect(await conversationIdForWorkspace(store, "C:\\Users\\me\\proj\\")).toBe(CID); - expect(await conversationIdForWorkspace(store, "C:\\Users\\me\\other")).toBeNull(); - }); - - it("captureAnswer recovers the answer via the log-file conversation id", async () => { - const logFile = path.join(store, "run.log"); - await fsp.writeFile(logFile, `server.go:755] Created conversation ${CID}\n`); - const { answer, conversationId } = await captureAnswer({ logFile, env: { AGY_STORE_DIR: store } }); - expect(conversationId).toBe(CID); - expect(answer).toBe("captured!"); - }); - - it("captureAnswer falls back to the workspace map when the log has no id", async () => { - const logFile = path.join(store, "run.log"); - await fsp.writeFile(logFile, "no id in this log\n"); - const { answer, conversationId } = await captureAnswer({ - logFile, - cwd: "C:\\Users\\me\\proj", - env: { AGY_STORE_DIR: store }, - }); - expect(conversationId).toBe(CID); - expect(answer).toBe("captured!"); - }); - - it("captureAnswer returns empty (no throw) when nothing matches", async () => { - const { answer, conversationId } = await captureAnswer({ - logFile: path.join(store, "missing.log"), - env: { AGY_STORE_DIR: store }, - }); - expect(conversationId).toBeNull(); - expect(answer).toBe(""); - }); - - it("captureAnswer self-locates the store from the log's app-data-dir line (no env)", async () => { - const logFile = path.join(store, "run.log"); - await fsp.writeFile( - logFile, - `common.go:203] CLI app data directory: ${store}\nserver.go:755] Created conversation ${CID}\n`, - ); - const { answer, conversationId, storeDir } = await captureAnswer({ logFile, env: {} }); - expect(storeDir).toBe(store); - expect(conversationId).toBe(CID); - expect(answer).toBe("captured!"); - }); -}); diff --git a/tests/lib.workspace.test.mjs b/tests/lib.workspace.test.mjs deleted file mode 100644 index fdc44b0..0000000 --- a/tests/lib.workspace.test.mjs +++ /dev/null @@ -1,55 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from "vitest"; -import { promises as fsp } from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -import { resolveWorkspaceRoot } from "../plugins/agy/scripts/lib/workspace.mjs"; - -let tmpDir; - -beforeEach(async () => { - tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), "agy-ws-")); -}); -afterEach(async () => { - await fsp.rm(tmpDir, { recursive: true, force: true }); -}); - -describe("resolveWorkspaceRoot", () => { - it("uses CLAUDE_PROJECT_DIR when set and pointing at a real dir", async () => { - const r = await resolveWorkspaceRoot({ - cwd: os.homedir(), - env: { CLAUDE_PROJECT_DIR: tmpDir }, - }); - expect(path.resolve(r)).toBe(path.resolve(tmpDir)); - }); - - it("ignores CLAUDE_PROJECT_DIR if the directory doesn't exist", async () => { - const r = await resolveWorkspaceRoot({ - cwd: tmpDir, - env: { CLAUDE_PROJECT_DIR: path.join(tmpDir, "absent-xyz") }, - }); - // Falls back to git root (not present in tmpDir) → CWD. - expect(path.resolve(r)).toBe(path.resolve(tmpDir)); - }); - - it("walks up to find a .git/ root", async () => { - const repoRoot = path.join(tmpDir, "repo"); - const deep = path.join(repoRoot, "src", "deep", "deeper"); - await fsp.mkdir(deep, { recursive: true }); - await fsp.mkdir(path.join(repoRoot, ".git"), { recursive: true }); - - const r = await resolveWorkspaceRoot({ - cwd: deep, - env: { CLAUDE_PROJECT_DIR: "" }, - }); - expect(path.resolve(r)).toBe(path.resolve(repoRoot)); - }); - - it("falls back to CWD if no git root and no env hint", async () => { - const r = await resolveWorkspaceRoot({ - cwd: tmpDir, - env: { CLAUDE_PROJECT_DIR: "" }, - }); - expect(path.resolve(r)).toBe(path.resolve(tmpDir)); - }); -}); diff --git a/tests/read_only_cwd.bats b/tests/read_only_cwd.bats deleted file mode 100644 index 649ddfc..0000000 --- a/tests/read_only_cwd.bats +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env bats -# Regression guard for the read-only commands (/agy:ask, simple /agy:review). -# -# `agy --print` EXECUTES write tools even without --dangerously-skip-permissions -# (a non-TTY prompt is auto-proceeded), so "no auto-approve" alone does NOT -# make a command read-only. Read-only is enforced by running agy FROM a -# throwaway temp dir (not the user's repo) with the repo absent from -# --add-dir — so agy has no path to write into the repo. This test stubs -# `agy` to record its working directory and asserts it is NOT the caller's. - -load helpers - -@test "_agy_capture runs agy from a temp dir, not the caller's cwd (read-only guard)" { - load_agy_run - command -v node >/dev/null 2>&1 || skip "node required for the transcript capture path" - - local stub="$BATS_TEST_TMPDIR/agy-stub" - cat > "$stub" <<'STUB' -#!/usr/bin/env bash -pwd -P > "$AGY_TEST_CWD_OUT" -exit 0 -STUB - chmod +x "$stub" - - export AGY_TEST_CWD_OUT="$BATS_TEST_TMPDIR/agy_cwd.txt" - cd "$BATS_TEST_TMPDIR" - local caller - caller="$(pwd -P)" - - # transcript.mjs will find no conversation (stub wrote no log) and return - # non-zero — that's fine; we only care where agy ran. - _agy_capture "$stub" "" "5s" "hello there" >/dev/null 2>&1 || true - - [ -f "$AGY_TEST_CWD_OUT" ] - local agy_cwd - agy_cwd="$(cat "$AGY_TEST_CWD_OUT")" - # agy must NOT have inherited the caller's cwd — it runs in a throwaway temp. - [ "$agy_cwd" != "$caller" ] -} - -@test "_agy_capture_writefile (node-absent fallback) also runs agy from a temp dir" { - load_agy_run - - local stub="$BATS_TEST_TMPDIR/agy-stub2" - cat > "$stub" <<'STUB' -#!/usr/bin/env bash -pwd -P > "$AGY_TEST_CWD_OUT2" -exit 0 -STUB - chmod +x "$stub" - - export AGY_TEST_CWD_OUT2="$BATS_TEST_TMPDIR/agy_cwd2.txt" - cd "$BATS_TEST_TMPDIR" - local caller - caller="$(pwd -P)" - - _agy_capture_writefile "$stub" "" "5s" "hello there" >/dev/null 2>&1 || true - - [ -f "$AGY_TEST_CWD_OUT2" ] - local agy_cwd - agy_cwd="$(cat "$AGY_TEST_CWD_OUT2")" - [ "$agy_cwd" != "$caller" ] -} diff --git a/tests/resolve_model_alias.bats b/tests/resolve_model_alias.bats deleted file mode 100644 index ff9b1a8..0000000 --- a/tests/resolve_model_alias.bats +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env bats -# Tests for the model-alias resolver. Lifted aliases must map to their -# canonical TUI string; unknown / empty input must exit 64. - -load helpers - -@test "alias 'flash' maps to Gemini 3.5 Flash (High)" { - run_agy_fn resolve_model_alias "flash" - [ "$status" -eq 0 ] - [ "$output" = "Gemini 3.5 Flash (High)" ] -} - -@test "alias 'flash-low' maps to Gemini 3.5 Flash (Low)" { - run_agy_fn resolve_model_alias "flash-low" - [ "$status" -eq 0 ] - [ "$output" = "Gemini 3.5 Flash (Low)" ] -} - -@test "alias 'opus' maps to Claude Opus 4.6 (Thinking)" { - run_agy_fn resolve_model_alias "opus" - [ "$status" -eq 0 ] - [ "$output" = "Claude Opus 4.6 (Thinking)" ] -} - -@test "alias is case-insensitive" { - run_agy_fn resolve_model_alias "OPUS" - [ "$status" -eq 0 ] - [ "$output" = "Claude Opus 4.6 (Thinking)" ] -} - -@test "canonical TUI string passes through verbatim" { - run_agy_fn resolve_model_alias "Claude Opus 4.6 (Thinking)" - [ "$status" -eq 0 ] - [ "$output" = "Claude Opus 4.6 (Thinking)" ] -} - -@test "unknown alias exits 64" { - run_agy_fn resolve_model_alias "definitely-not-a-real-model" - [ "$status" -eq 64 ] -} - -@test "empty alias exits 64" { - run_agy_fn resolve_model_alias "" - [ "$status" -eq 64 ] -} diff --git a/tests/scan_diff_for_secrets.bats b/tests/scan_diff_for_secrets.bats deleted file mode 100644 index abc7530..0000000 --- a/tests/scan_diff_for_secrets.bats +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env bats -# Tests for _scan_diff_for_secrets. The helper must detect common -# secret patterns in added lines (^+) and stay silent on benign diffs. - -load helpers - -@test "empty diff: silent, exit 0" { - load_agy_run - run _scan_diff_for_secrets "" - [ "$status" -eq 0 ] - [ -z "$output" ] -} - -@test "benign diff: silent, exit 0" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '--- a/foo.txt' \ - '+++ b/foo.txt' \ - '+hello world' \ - '+function add(a, b) { return a + b; }' \ - '-let x = 1;')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 0 ] -} - -@test "AWS access key in added line: exit 1, label printed" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '+const key = "AKIAIOSFODNN7EXAMPLE";')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] - [[ "$output" == *"AWS access key"* ]] -} - -@test "PEM private key block in added line: exit 1" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '+-----BEGIN RSA PRIVATE KEY-----' \ - '+MIIEpAIBAAKCAQEAabc...')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] - [[ "$output" == *"PEM private key"* ]] -} - -@test "GitHub PAT in added line: exit 1" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '+token = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] - [[ "$output" == *"GitHub personal access token"* ]] -} - -@test "inline credential assignment with long base64-ish value: exit 1" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '+API_KEY = "abcdef0123456789ABCDEF0123456789"')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] -} - -@test "removed line containing a secret does NOT trigger" { - load_agy_run - # Removing a secret from the diff is the correct user action; do not - # warn on those lines. - local diff - diff="$(printf '%s\n' \ - '-AWS_KEY = "AKIAIOSFODNN7EXAMPLE"')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 0 ] -} - -@test "diff header lines (+++) do NOT trigger" { - load_agy_run - local diff - diff="$(printf '%s\n' \ - '+++ b/secrets/AKIAIOSFODNN7EXAMPLE.txt' \ - '+hello')" - run _scan_diff_for_secrets "$diff" - # The path in the +++ header looks like an AWS key, but the scanner - # filters those lines out. Expect a clean run. - [ "$status" -eq 0 ] -} - -@test "code reference like 'password = formData.password' does NOT trigger" { - load_agy_run - # The pattern requires the value side to be base64-safe chars only; - # the dot in `formData.password` should break the match. - local diff - diff="$(printf '%s\n' \ - '+const password = formData.password;')" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 0 ] -} - -@test "fine-grained github_pat_ in added line: exit 1 (GAP-1 — bash parity)" { - load_agy_run - local tok diff - tok="github_pat_$(printf 'A%.0s' {1..82})" - diff="$(printf '+token = "%s"\n' "$tok")" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] - [[ "$output" == *"GitHub fine-grained PAT"* ]] -} - -@test "Anthropic sk-ant- key in added line: exit 1 (GAP-3)" { - load_agy_run - local key diff - key="sk-ant-api03-$(printf 'A%.0s' {1..30})" - diff="$(printf '+k = "%s"\n' "$key")" - run _scan_diff_for_secrets "$diff" - [ "$status" -eq 1 ] - [[ "$output" == *"Anthropic API key"* ]] -} - -@test "_scan_text_for_secrets scans RAW content (GAP-2 full-file path)" { - load_agy_run - run _scan_text_for_secrets 'const k = "AKIAIOSFODNN7EXAMPLE";' - [ "$status" -eq 1 ] - [[ "$output" == *"AWS access key"* ]] -} - -@test "dashed identifier containing 'sk-' does NOT trigger (low false-positive)" { - load_agy_run - run _scan_text_for_secrets 'disk-management-system-controller-v2' - [ "$status" -eq 0 ] -} diff --git a/tests/scrape_doc_guard.bats b/tests/scrape_doc_guard.bats deleted file mode 100644 index 9300055..0000000 --- a/tests/scrape_doc_guard.bats +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bats -# /agy:scrape + /agy:doc-to-md input deny-lists. Validation runs BEFORE any -# agy invocation, so the refusal paths are testable without a live agy. - -load helpers - -@test "scrape refuses file:// (scheme guard), exit 65" { - load_agy_run - command -v node >/dev/null 2>&1 || skip "node required" - run cmd_scrape "file:///etc/passwd" - [ "$status" -eq 65 ] - [[ "$output" == *"refusing to scrape"* ]] -} - -@test "scrape refuses a cloud-metadata IP (SSRF), exit 65" { - load_agy_run - command -v node >/dev/null 2>&1 || skip "node required" - run cmd_scrape "http://169.254.169.254/latest/meta-data/" - [ "$status" -eq 65 ] -} - -@test "scrape with no URL is a usage error, exit 64" { - load_agy_run - run cmd_scrape - [ "$status" -eq 64 ] -} - -@test "doc-to-md refuses a non-document extension (.env), exit 65" { - load_agy_run - command -v node >/dev/null 2>&1 || skip "node required" - printf 'API_KEY=x\n' > "$BATS_TEST_TMPDIR/secrets.env" - run cmd_doc_to_md "$BATS_TEST_TMPDIR/secrets.env" - [ "$status" -eq 65 ] - [[ "$output" == *"refusing to convert"* ]] -} - -@test "doc-to-md refuses a missing file, exit 65" { - load_agy_run - command -v node >/dev/null 2>&1 || skip "node required" - run cmd_doc_to_md "$BATS_TEST_TMPDIR/nope.pdf" - [ "$status" -eq 65 ] -} - -@test "doc-to-md with no path is a usage error, exit 64" { - load_agy_run - run cmd_doc_to_md - [ "$status" -eq 64 ] -}