Code graph and memory for your coding agents, in one Rust program. For Claude Code, Codex, Cursor and any MCP client.
Rust agent-memoryai-agentsclaude-codecode-analysiscode-graphcode-intelligencecode-searchcodexcoding-agentscontext-engineeringcursordeveloper-toolsgraphragknowledge-graphlocal-firstmcpmcp-servermodel-context-protocolrusttree-sitter
Graphicle 0.1.9: packs, fix, review, pixel, see and Muse Code
VikramLex8799b9e6ba93
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9468deb..1c416cd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -208,6 +208,9 @@ jobs:- name: Adapted-file headersworking-directory: crates/graphicle-graphrun: python3 tools/mark_adapted_files.py --check+ # The review action's scripts, with stand-ins for curl, graphicle and gh.+ - name: Review action+ run: python3 packaging/github-action/test_action.py# The committed pages the release archives ship (CONTRIBUTING.md,# Dependencies): regenerated from the locks, they must not change.- name: Third-party licence pages are currentdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8008b5f..44f7997 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,423 @@Notable changes to Graphicle: the graph engine (`graphicle-graph`), the memorylibrary (`graphicle-memory`) and the `graphicle` program.+## 0.1.9 - 2026-10-28++Every crate is at 0.1.9, and `graphicle --version` prints+`graphicle 0.1.9 (core)`. The Python and TypeScript SDKs are at 0.1.9 too.++Most of what is new was written for Meta's Global AI Developer Hackathon.+[HACKATHON.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/HACKATHON.md)+says what was written before the event and what during it.++### How the new model features were tested++- The new commands that call a model (`ask --pack`, `plan`, `fix`,+ `review`, `pixel` and `see`) were tested only against stand-ins: local+ test servers that answer as the Meta Model API and OpenAI-compatible+ servers do, and `demo/mock_meta.py`. That covers the prompt cache+ requests, the exact counts of `POST /responses/input_tokens`, SAM 3.1 and+ computer use. None of them has called the live Meta Model API yet.+- The Muse Code plugin was tested with a stand-in for the `muse` program,+ not with Muse Code itself.+- The GitHub Action of `graphicle review` was tested with stand-ins for+ `curl`, `graphicle` and `gh`, not on GitHub's runners.+- The hosted demo in `demo/` was tested against `demo/mock_meta.py`. It is+ not deployed.++### After upgrading++- Run `graphicle sync` once in each project, as after 0.1.8. The saved+ graph and the query file are keyed to the program's build, so the first+ sync writes both again. Until then a question reads the code graph from+ the store, and on a project of 2,000 files or more the prompt hook gives+ only the files that define the code names a prompt gives.++### Whole-repository packs++- `graphicle pack [QUESTION]` gathers a project's code for one question into+ one block of text within a token budget (`--budget`, default 128,000, up+ to 2,000,000): a header, a manifest of what is in and the top files left+ out, an architecture summary, the ranked files (small ones whole, large+ ones as symbol excerpts with merged line ranges), callers and callees two+ steps along call edges, tests, docs and more of the repository. It reads+ `graphicle context`'s own ranking and the saved code graph. Formats:+ Markdown, XML, or JSON (`graphicle.pack.v1`, whose chunks' text joined in+ order is the pack). Without a question, an overview. See+ [docs/pack.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/pack.md).+- A pack's ranking is `context`'s, read deeper (3,000 fused passages), with+ two additions: the files of a small folder the question names (by a word,+ a path or module segment, or words joined by `_`) right after the top+ files, and the files that define what the top files use (Go identifiers+ through their imports, Python modules of the same folder). Up to 256,000+ tokens, the ranks past 15 go in as compact excerpts (their passages and+ the first lines of the symbols around them) instead of more of the+ repository by centrality, and no file takes more than a tenth of the+ budget. The manifest lists up to 100 top-ranked files left out.+- A pack's ranking reads an issue without its environment sections (a+ heading below the title that labels the system information, tested+ versions, a `<name> version`, the environment or the operating system, or+ an issue form's question for them) and its `<name> version: <value>`+ lines; a title or a heading that merely names a version stays.+- The first pack after an upgrade writes the project's query file for the+ new build once, and says so; later packs read it.+- The budget is never exceeded: tokens are counted exactly with+ `--tokenizer tokenizer.json` (any Hugging Face tokenizer; the released+ program includes the pure-Rust `tokenizers` library for it), else+ estimated from bytes per token by language, calibrated on Muse Spark+ Open's counts (7% above them in 22 packs of 128,000 tokens), with a+ margin. The same inputs give the same bytes.+- `graphicle pack --layout cache` splits a pack for a provider's prompt+ cache. Its repository part comes first and is the same bytes for every+ question about a commit at the same budget and settings: a header without+ the question, the architecture summary, a map of the folders (files,+ tokens and most connected symbols of each), the files with the most+ connections in the code graph (whole, or the first line of each symbol) and+ the top documentation. The question part follows (a manifest, focus, call+ paths and tests) and never repeats lines the repository part holds: it+ lists the ranked files already there as `in the prefix: path lines a-b`,+ and gives full excerpts to one ranked file per 8,000 tokens of its room+ (each up to two fifths of the room divided among them, or 2,000 tokens+ when that is more) and compact excerpts to the ranks after them.+ `--prefix-share F` (default 0.9) is the repository part's share of the+ budget at most; 1.0 makes a stable pack, where only the question after it+ changes. See+ [docs/pack.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/pack.md#layouts-and-the-prompt-cache).+- The pack JSON records the `layout`, `prefix_share` (cache layout only),+ `prefix_tokens`, `prefix_sha256` and a `part` (`prefix` or `suffix`) on+ every section; the prefix sections' text is the start of the pack's text.+- The MCP server publishes a `pack` tool (default 32,000 tokens, at most+ 200,000) after the tools of 0.1.0's server. Claude Code's essential set+ stays five tools; `graphicle connect claude-code --tools all` adds `pack`.++### Ranking for TypeScript, Java and C++++- The pack's ranking was tuned on TypeScript, Java and C++ repositories+ (angular, keycloak and godot) as well as on Go and Python ones+ (kubernetes and home-assistant):+ - it reads an issue without its environment sections, as above, whose+ words (graphics drivers, display servers, package versions) pulled+ unrelated files up;+ - files the question names by a code name (`TextEdit` names+ `text_edit.cpp` and `text_edit.h`, `FormControl` names+ `form_control.ts`, `UserModel` names `UserModel.java`), or by two or+ three of its words in the languages that name files after their classes+ (Java, TypeScript and JavaScript, C and C++), come right after the top+ five files: at most 4 files per name, 4 names and 8 files;+ - TypeScript and JavaScript imports lead to the files that define what the+ top files use: relative paths (an ES module's `./x.js` is `x.ts`), index+ files and `tsconfig` path aliases.+- Measured without a model, as the mean share of the files a fix changed+ that are inside the pack, whole or as excerpts or outlines of their+ symbols (standard layout, tokens counted with the Muse Spark Open+ tokenizer), over the 90 questions of three repositories held+ out from tuning (pytorch, vscode and elasticsearch, 30 each): 58.1%,+ 64.3%, 64.6%, 70.9% and 77.9% at budgets of 64K, 128K, 256K, 512K and 1M+ tokens, against 55.8%, 63.6%, 61.4%, 68.0% and 76.8% for the pack as it+ stood before the hackathon. pytorch gained 2.3 to 10.6 points; vscode+ lost 6.6 points at 64K, 0.9 at 256K and 3.3 at 512K. These numbers were+ measured before a later change to how a pack reads an issue's+ environment sections (the rule above). That change leaves the results of+ all 200 development questions unchanged; the held-out questions were not+ measured again. The method is that of+ [docs/benchmarks/whole-repo.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/benchmarks/whole-repo.md#context-recall-without-a-model),+ whose table is of the earlier pack.++### Answers, plans and fixes with Meta's models++- `graphicle config set model meta` writes a Muse Spark profile for the+ Meta Model API (`https://api.meta.ai/v1`, its Responses API, key in+ `MODEL_API_KEY`, model `muse-spark-1.3`, `reasoning_effort` medium, sent+ as `reasoning.effort`) and makes it the answer model;+ `meta:muse-wonder-1.0` chooses Muse Wonder. It refuses the `-contributor`+ models, which let Meta train on the data, and a `reasoning_effort` of+ `none`, which the Meta Model API refuses. `graphicle config set model+ compatible:MODEL --url URL` does the same for any OpenAI-compatible+ server, such as Muse Spark Open on vLLM or SGLang. The docs give Meta's+ list prices for Muse Spark 1.3 and Muse Wonder (26 October 2026) as+ configuration examples; prices stay out of the program.+- Model profiles take input limits up to 1,048,576 tokens and output limits+ up to 131,072, and an optional `price` (US dollars per million input,+ output and cached input tokens). `ask --pack` and `plan` show the tokens+ in and out from the provider's usage, and a cost only from that price.+- `graphicle ask --pack` answers in one model call from a pack that fills+ the model's input limit, streams the answer from chat models, checks every+ cited `path:line` against the working tree and lists the ones that do not+ hold. After each call it keeps the provider's prompt tokens over its own+ estimate per model profile, and sizes the next pack to fill the input+ limit by the provider's count. The `basic` and `reflect` workflows are+ unchanged.+- `graphicle plan "change request"` asks for a plan as JSON (steps, files to+ edit with line ranges, new files, tests, risks), checks it against the+ working tree and prints it as Markdown or JSON. It changes no files.+- `graphicle ask --pack`, `graphicle plan` and `graphicle fix` use the+ standard layout by default; `--layout cache` and `--prefix-share` choose+ the cache layout, which pays off when you ask several questions about+ the same commit. A cache-layout request sends the same instructions+ first, then the pack, then the question. Without `--budget`, the+ repository part is sized from the model's input limit, not the+ calibrated budget, so it stays the same bytes from one question to the+ next; when the provider counts more than the estimate, it steps down to+ 0.8, 0.64, ... of that size, the first whose share fits, and holds within+ each step. For the Meta Model API the request carries a+ `prompt_cache_key` built from the project, its commit and the pack's+ prefix hash (never from the question) and, on the Responses API, a+ 24-hour `prompt_cache_retention`; other profiles opt in with+ `"prompt_cache": true`.+- Every request is fitted to the input limit: its estimate, times the+ profile's calibration, must fit, and a request near the limit is counted+ exactly with `POST /responses/input_tokens` for the Meta Model API; the+ pack is made again smaller while it would not fit. A profile's `tokenizer`+ (a `tokenizer.json`, such as Muse Spark Open's) makes these packs count+ exactly without the API.+- `graphicle fix "issue"` (or `--issue-file`) makes a pack and a plan. The+ pack is in the standard layout by default, since one run asks about one+ issue and a shared repository part would only take room from the files+ the issue needs; `--layout cache` or `--prefix-share` keeps the cache+ layout. It asks for the edits as search-and-replace blocks and new files,+ checks each round's edits as a whole (paths, search texts, and new files+ against each other and the folders on disk) and applies them all or none,+ putting back every file of the round if a write fails, on a new branch in+ a new git worktree from HEAD, made once the plan has come back. It runs+ `--test CMD` (or the configuration's `fix.test`) there with a timeout+ (`--timeout`, 1 to 86,400 seconds), and sends a failure's output and the+ diff back for at most `--rounds` rounds (default 3), each request fitted to+ the input limit. It reports the branch, worktree, files changed, each+ round's result, tokens and cost, and the cited lines; `--commit` commits+ on the new branch. `--focus PATH[:LINE|:START-END]` (up to 50) puts+ passages first in the pack's ranking, whatever the issue's words rank:+ PATH alone is the whole file, PATH:LINE the 40 lines on each side. Edits+ outside the repository (absolute paths, `..`, any spelling of `.git`,+ symlinks leading out or into `.git`) are refused; git runs with hooks off+ and without variables that point it elsewhere or add configuration (your+ configuration files, and so your commit identity, are kept); the test+ command never comes from the model and runs without the model key+ variables of every profile, those stored in the workspace too, whose+ values are hidden in its output; on Linux, Graphicle makes itself not+ dumpable before the test starts, so the test cannot read Graphicle's+ environment through `/proc`. The test still runs as you and can read what+ you can: use a container or virtual machine for repositories you do not+ trust. Nothing is pushed. See+ [docs/fix.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/fix.md).+- The spend log: every model call of `ask --pack`, `plan`, `fix`, `review`,+ `pixel` and `see` adds one line to `usage.jsonl` in the data folder+ (tokens in, cached, out and reasoning, seconds, the cost at the profile's+ configured price, status; never the prompt or the answer). `graphicle+ usage` adds it up by day and model, with the cached share; `--since` and+ `--json`. After each answer, one line gives the tokens in (cached, with+ their share), out, and the cost.+- Cost caps in a profile, in US dollars at its configured price:+ `max_cost_per_call` refuses a call whose worst case (the whole input+ uncached, by the provider's count or the calibrated estimate plus 10%, and+ the output limit) costs more, and `max_cost_per_day` refuses a call whose+ worst case would take the day's cost of the profile past it. Calls not+ logged yet count at their worst case (held in `usage-pending.json`), so+ calls at the same time count against each other; calls without reported+ usage count at their worst case; a spend log that cannot be read refuses+ capped calls. Each refusal names the setting. A held worst case counts+ whatever its day (a call running past midnight UTC counts in the new+ day) and ends when its call is logged, its process ends, or after 40+ minutes. `graphicle usage` lists the calls not logged yet and the log+ lines it skipped; `--clear-pending` removes the held worst cases.++### Review a change: `graphicle review` and its GitHub Action++- `graphicle review` asks a long-context model (Muse Spark by default, with+ the `meta` profile) to review what a branch adds since its merge base with+ the base branch, as a pull request shows it. One model call gets a+ cache-layout pack whose ranking puts the changed hunks first, so it holds+ the changed code, the callers and callees of the changed symbols and+ their tests, then the architecture lines of the modules the change+ touches, the changed hunks and the diff. The model returns comments with+ a severity and `path:line` evidence. A comment is kept only on a changed+ line of the head with at least one citation that holds in the working+ tree; it is flagged when no citation holds, and dropped when it is on+ another file, outside the changed hunks, empty, a repeat or past+ `--max-comments` (20 by default). Formats: `markdown`, `json`, and+ `github`, the body of GitHub's create-a-review call, always a `COMMENT`+ that never approves or requests changes. It changes no files and posts+ nothing. See+ [docs/review.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/review.md).+- A composite GitHub Action in `packaging/github-action/` runs `graphicle+ review --format github` on a pull request and posts one review. It+ installs a Graphicle release pinned by version and SHA-256, runs on the+ `pull_request` event only (it skips pull requests from forks, which get no+ secrets, and refuses `pull_request_target`), gives the model key only to+ the review step and the GitHub token only to the posting step, and refuses+ a call whose worst case costs more than `max-cost-usd` (0.50 US dollars by+ default, at Muse Spark 1.3's list price of 26 October 2026). 0.1.9 is the+ first release it can install. See+ [the GitHub Action](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/review.md#the-github-action).++### From the screen to the code: `see`, `pixel` and the flow++- `graphicle pixel SCREENSHOT --at X,Y` finds the code that draws the+ element at a point of a screenshot. SAM 3.1 (`sam-3.1` on the Meta Model+ API) finds the element's box, a vision model (Muse Spark by default) reads+ its strings, and Graphicle searches the project for them as string+ literals (exact, then with mnemonics, ellipses and case set aside, then+ with placeholders), follows the keys of `package.nls.json` and of English+ JSON locale files to where they are used, adds the code graph's+ symbols named like the element, and ranks the candidates as `path:line`.+ `--text` gives the strings and makes no model call; `--explain` asks the+ model to rank the top candidates again from a small pack and explain+ them. SAM's calls are priced per image (`price.per_image`).+- `graphicle see` lets a model drive a web app in a browser you run, with+ computer use on the Meta Model API (Muse Wonder or Muse Spark 1.3), until+ the bug an issue describes shows (or, with `--look-for expected`, the+ expected behaviour). A driver command of yours runs the model's clicks and+ keys and returns screenshots; `demo/browser_driver.py` is one, headless+ Chromium that loads only the app's origin, blocks service workers and+ closes WebSockets to other origins. Each request replays the run so far,+ the model's encrypted reasoning included. It keeps every screenshot and a+ step log, and ends with a point on the last screenshot for `graphicle+ pixel`. A run takes at most 29 model calls (`--steps`, 25 by default). A+ pending safety check stops the run unless `--acknowledge-safety-checks`+ is given, and each acknowledgement is logged; the driver gets no model+ key; each call is checked against the profile's caps and the run's+ `--max-cost` (3 US dollars by default), and a profile without a price is+ refused. See+ [docs/flow.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/flow.md).+- `demo/flow/flow.py` takes one bug from the screen to a tested fix as one+ command: `see` reproduces it, `pixel` finds the code, `fix --focus`+ patches it on a new branch and runs the app's tests, and `see --look-for+ expected` checks the patched app. It writes a receipt with the steps,+ citations, diff, the end of the test log, the screenshots before and+ after, and each call's tokens and cost. One budget holds for the whole+ run (`--max-run-cost`, 3 US dollars by default). It has run end to end+ only against `demo/mock_meta.py`, on a small app of ours and on+ excalidraw issue 12053, not yet against Meta's live API.+- `demo/` also holds a small web app for trying Graphicle with Meta's models+ on kubernetes, pytorch and vscode: a question answered from a cache-aware+ pack, and a click on a VS Code screenshot answered by `graphicle pixel`.+ It runs the `graphicle` program with fixed arguments and never exposes+ Graphicle's own local server. See+ [demo/README.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/demo/README.md).++### Muse Code++- `graphicle setup` connects Muse Code: it finds it by its settings folder,+ `~/.config/muse`, or the `muse` program, and adds Graphicle's MCP server+ to the `mcp_servers` of `~/.config/muse/settings.json`, with+ `"mode": "optional"`. `graphicle disconnect muse` removes it. See+ [docs/muse-code.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/muse-code.md).+- A Muse Code plugin, as a preview: the MCP server, a skill and hooks in one+ package. With the `muse` program on your `PATH` (or in `~/.local/bin`),+ `graphicle connect muse --hooks` writes it into Graphicle's data folder,+ installs it with `muse plugins install --scope user` (or updates it) and+ removes the settings entry it replaces; approve it once with `muse+ plugins approve graphicle`. Setup does not install it: the plugin was+ tested against a stand-in `muse` program only, and stays opt-in until a+ check with Muse Code itself has passed. Run `graphicle disconnect muse`+ before you uninstall Graphicle or delete its data folder: it is not+ confirmed that Muse Code skips a plugin's server that fails to start.+- The plugin's hooks are built to add context without a tool call: at the+ start of a session, the project's map (the repository part of a+ cache-layout pack) and its reviewed memories; for a code question, the+ cited excerpts `graphicle context` finds (at most 8,400 characters);+ after a batch of tool calls that searched the files, one sentence on+ Graphicle's graph tools (at most five times a session). They keep the+ start of each request the same bytes through a session, so that the+ prompt cache can keep serving it; which hook events reach the model in+ Muse Code itself is not yet observed. The hooks never block Muse Code:+ each exits 0, and the session start waits at most 2.5 seconds for its+ context.+- Session memory with the plugin: the `Stop`, `PreCompact` and `SessionEnd`+ hooks hand Muse Code's session log to `graphicle sessions import`, so+ finished turns become sources of the project, and a decision one session+ records with `propose_memory` reaches the next session's start once a+ person approves it.+- `graphicle mcp --or-workspace`, the plugin's server, starts in any folder:+ it serves the project of that folder, else every project of the+ workspace.++### Fixes++- `graphicle setup` no longer stops when it cannot write a Git hook, as in+ Claude Code's sandbox, which does not let it write `.git/hooks`,+ `.mcp.json` or `.claude/settings.local.json` (reported by Thomas Thomsen,+ [#15](https://github.com/Graphicle-AI/graphicle/issues/15)). Before, it+ stopped with "Local I/O failed: Operation not permitted (os error 1)"+ without naming the file, and printed no summary, so the line to add to+ `.mcp.json` by hand was lost too. Now each hook it cannot write is listed+ with the reason, the summary gives the line to add to the hooks by hand,+ and setup goes on with its other steps. `AGENTS.md`, `CLAUDE.md` and the+ Graphify entries that setup removes are handled the same way, and an+ agent's settings file that cannot be backed up still gets the entry to+ paste into it. A hooks file that setup cannot write, Claude Code's+ `.claude/settings.local.json` or Codex's `~/.codex/hooks.json`, no longer+ fails the agent's connection. The agent stays connected, `.mcp.json` is+ listed with the files setup changed, and the hooks are listed as skipped+ with the file and the reason. The summary gives the `graphicle connect`+ command that adds them later from a normal terminal. Run by hand,+ `graphicle connect --hooks` still stops on such a file, and now names it.+ In a repository whose whole `.git` folder is read-only, as in Codex's+ default sandbox, setup also finishes: it leaves `.git/info/exclude` as it+ is, and the summary gives the lines to add to it to keep setup's backups+ and the settings file it created out of `git status`. When Codex's+ `config.toml` or Graphicle's data folder cannot be written, the error+ names it.+- An issue whose title names a version (a level-1 heading such as "...+ Version Check Preferences") lost every section under its title to the+ environment-section rule, so the question came out empty and `graphicle+ pack` refused it. A title or a heading that merely names a version now+ stays, and a question that still comes out empty is ranked as written.+ This was found before the release, in 18 of 633 issues of a public+ software engineering benchmark.+- Dependencies: zstd 0.14.3, zstd-safe 8.2.0 and zstd-sys 2.1.2, for+ RUSTSEC-2026-0391, -0398, -0403 and -0410. zstd 0.13.3 and zstd-safe 7.3.0+ stay: only jieba-rs 0.11.0 brings them in, through include-flate 0.3.4, to+ unpack its built-in dictionaries, a path that does not reach the affected+ functions, and each `deny.toml` says so for those three advisories.+- `graphicle config set model ollama` reads `OLLAMA_HOST` when its scheme+ is not lowercase (`HTTP://gpu.lan:11434`); it saved+ `http://127.0.0.1:11434` instead (#12, by @rudycelekli).+- `graphicle serve --port 80` accepts the `Host` header that browsers and+ curl send without the default port (`127.0.0.1` or `localhost`); it+ refused every such request as an unexpected host (#13, by @rudycelekli).+- A memory library test failed now and then on macOS when tests ran in+ parallel: two tests could make scratch folders of the same name, since+ macOS clocks tick in microseconds. A per-process counter keeps them apart.++### Docs++- New pages:+ [Packs](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/pack.md),+ [Fix](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/fix.md),+ [Review](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/review.md),+ [See it, find it, fix it, check it](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/flow.md),+ [Muse Code](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/muse-code.md),+ and+ [the whole-repository benchmark](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/docs/benchmarks/whole-repo.md):+ its questions, arms and scorer, fixed before any model run; the context+ recall of the pack without a model (a file counts when the pack holds any+ of its text); and the cost of a question with the+ prompt cache, computed at list prices and not billed. Its model runs have+ not been made yet.+- `docs/configuration.md` covers Muse Spark, prices, the spend log and the+ caps; `docs/agents.md` covers Muse Code, and Claude Code and Codex on+ Meta's models; `docs/mcp.md` covers the `pack` tool.+- The README gives "Agent memory, compared" near the top, a still of+ 0.1.8's `graphicle setup` as its hero, the 0.1.8 chart of time per+ question on kubernetes, and the new commands, and `docs/benchmarks.md`+ gives the early pre-release memory runs on GPT models.+- The benchmark kits are in the repository: `bench/whole-repo` (the+ whole-repository benchmark), `bench/pixel` (pixel to code) and+ `bench/muse-code` (Muse Code with and without the plugin, and the+ two-session memory demo).++### Packaging++- `server.json` at the repository's root is the MCP Registry entry of+ 0.1.8, the latest listed release (it named 0.1.7). A release's entry is+ committed after its listing, as+ [packaging/mcpb/README.md](https://github.com/Graphicle-AI/graphicle/blob/v0.1.9/packaging/mcpb/README.md#steps-at-release-time)+ describes.+- `packaging/muse-code-plugin/` holds the Muse Code plugin as `graphicle+ connect muse --hooks` writes it, and `packaging/github-action/` the+ GitHub Action of `graphicle review`, whose scripts CI tests with+ stand-ins.+## 0.1.8 - 2026-10-26Every crate is at 0.1.8, and `graphicle --version` printsdiff --git a/HACKATHON.md b/HACKATHON.mdnew file mode 100644index 0000000..6b80be1--- /dev/null+++ b/HACKATHON.md@@ -0,0 +1,29 @@+# Meta Global AI Developer Hackathon 2026++Graphicle is entered in the startup track of Meta's Global AI Developer Hackathon, 26 October to 4 November 2026. The event's rules ask entries built on an existing product to say clearly what is new. This page does that, and it is updated as work lands.++## Before the event++- **Graphicle 0.1.8**, released on 26 October 2026 before the kickoff, is the baseline.+- **Written on 26 October before the kickoff, and not released before the event:**+ - a first version of `graphicle pack`, which fills a token budget with the parts of a repository a question needs;+ - first versions of `graphicle ask --pack` and `graphicle plan`;+ - a Meta Model API profile for Muse Spark, and Muse Code in `graphicle setup`;+ - the harness and question sets of the whole-repository benchmark, and a first tuning round on its two development repositories (kubernetes and home-assistant).++## Built during the event++Everything below was started after the kickoff, at 26 October 2026, 16:00 UTC. Each item names the release it shipped in.++The commit ids are those of Graphicle's development repository, with the times they were committed (UTC); this public repository receives each release as one commit. The commands that call Meta's models were tested against stand-ins for the Meta Model API (the tests' local servers and [`demo/mock_meta.py`](demo/mock_meta.py)), not against the live API; the [0.1.9 notes](CHANGELOG.md#019---2026-10-28) say so feature by feature.++- **Cache-aware packs, the spend log and `graphicle fix`** (0.1.9). `graphicle pack --layout cache` puts first a repository part that is the same bytes for every question about a commit, so Meta's prompt cache can serve it. With `--layout cache`, `ask --pack`, `plan` and `fix` send a prompt cache key to the Meta Model API; they ask it for exact token counts near the input limit, log each call's tokens and cost (`graphicle usage`), and refuse a call past a profile's cost caps. `graphicle fix` makes a change for an issue on a new branch in a new worktree and runs your tests on it. Commits `3e0d7e8` (26 October, 17:08), `854c0cc` to `925f8c8` (5 commits, 26 October, 17:42 to 18:29), and two rounds of review fixes: `1e566f8` to `7ad616b` (2 commits, 26 October, 19:17) and `ad89536` to `4233438` (2 commits, 27 October, 01:20). `graphicle fix` packs in the standard layout by default, so the whole budget goes to the files the issue needs: `4578a5a` (27 October, 09:13).+- **The whole-repository benchmark** (its kit and page, 0.1.9). The grid of model runs, fixed before any model call; the runner, with the prompt cache and spending limits; the cost of a question with the prompt cache, computed at list prices and not billed; and the held-out baseline of the pack written before the event. Commits `c5ca2ca` to `0883169` (11 commits, 26 October, 16:58 to 27 October, 01:00). Three development repositories for TypeScript, Java and C++ (angular, keycloak and godot): `a1f83cf` (27 October, 02:39). The benchmark's model runs have not been made yet.+- **Pack ranking for TypeScript, Java and C++** (0.1.9). A second tuning round on the five development repositories, then one measurement on the three held-out repositories, whose numbers are in the 0.1.9 notes: `cbbf016` (27 October, 05:08). An issue whose title names a version is ranked as written instead of being refused as an empty question: `acf5f4e` (27 October, 07:20). Then the review's fix to how a pack reads an issue's environment sections: only a label below the title opens one, an issue form's question counts, and a `<name> version: <value>` line is left out; the results of all 200 development questions are unchanged, and the held-out questions were not measured again: `b8023f1` to `2955bba` (8 commits, 27 October, 08:56 to 11:34).+- **Pixel to code and the hosted demo** (0.1.9). `graphicle pixel` finds the code that draws an element of a screenshot: SAM 3.1 finds the element, a vision model (Muse Spark by default) reads it, and Graphicle looks up its strings in the code. [`demo/`](demo/README.md) is a small web app for trying Graphicle with Meta's models; it is not deployed. Commits `2dff779` to `8c352e8` (3 commits, 27 October, 01:51 to 02:18) and `2ec27e2` (27 October, 02:41).+- **`graphicle review` and its GitHub Action** (0.1.9). A review of a change from a cache-aware pack, each comment checked against the changed lines and its citations before it is shown, and a composite GitHub Action that posts one review on a pull request. Commits `92e89fc` to `04dbf74` (3 commits, 27 October, 02:21 to 02:26).+- **Graphicle inside Muse Code** (0.1.9). A native Muse Code plugin (the MCP server, a skill and hooks), session memory through Muse Code's session logs, a two-session memory demo, a harness that measures Muse Code with and without the plugin, and docs for Claude Code and Codex on Meta's models. Commits `586c339` to `99a1a1d` (6 commits, 27 October, 06:22 to 07:00). The review's fixes, `647941a` to `e580002` (6 commits, 27 October, 08:56 to 09:18): the plugin is a preview that you add with `graphicle connect muse --hooks`, since it has not yet run in Muse Code itself; its server is marked optional; the docs say to run `graphicle disconnect muse` before uninstalling; and the probe also records what Muse Code does when a plugin's server cannot start.+- **See it, find it, fix it, check it** (0.1.9). `graphicle see` drives a web app with computer use on the Meta Model API until a bug shows; `graphicle fix --focus` puts the places `graphicle pixel` finds first in the pack; `graphicle pixel` follows the keys of English JSON locale files; and [`demo/flow/flow.py`](demo/flow/flow.py) runs the whole path, from the bug on the screen to a tested fix, with a receipt. Commits `d3f3ec3` to `fd37c39` (6 commits, 27 October, 06:26 to 06:57), and the review's fixes, `dc48880` to `7e50e4f` (9 commits, 27 October, 07:55 to 08:59): the Meta key kept from the browser driver, the tests and the app's build, a browser that blocks service workers and closes WebSockets to other origins, one budget for a whole run, the model's reasoning replayed from step to step, screenshots counted by their size, and the docs saying the flow has run only against the stand-in.+- **Setup where it cannot write a file** (0.1.9). As in Claude Code's sandbox, which does not let it write `.git/hooks` or `.mcp.json`: a file setup cannot write is skipped with its reason, and the summary gives the lines to add by hand. Reported by Thomas Thomsen in [#15](https://github.com/Graphicle-AI/graphicle/issues/15). Commit `f29a86b` (27 October, 08:55). Then the rest of the issue: a hooks file setup cannot write (Claude Code's `.claude/settings.local.json`, Codex's `~/.codex/hooks.json`) is skipped with its reason while the agent stays connected, and a read-only `.git` keeps its exclude file while the summary gives the lines to add: `e1c0788` to `66643b6` (4 commits, 27 October, 11:52 to 11:59).+- **Also during the event** (0.1.9). The fix for four zstd advisories (`2f0ced3`, 27 October, 04:58); the README's section "Agent memory, compared" and its follow-ups (`7e1dd42`, `2b17d73`, `7c65015`, `7ac0c0b` and `b4ca138`, 27 October, 05:32 to 05:58), which describe memory comparisons run before the event; a test's formatting (`f20cb41`, 27 October, 06:54); and this page (`f7a67fd`, 26 October, 16:42).+- **The 0.1.9 release** itself: the version numbers, the 0.1.9 notes and this list, on top of the work above.diff --git a/README.md b/README.mdindex 2dbb06e..5a1de3a 100644--- a/README.md+++ b/README.md@@ -14,15 +14,6 @@<a href="https://discord.com/invite/rWuU7cWU4E"><img alt="Chat on Discord" src="https://img.shields.io/badge/chat-Discord-5865F2?style=flat-square&labelColor=1E2235&logo=discord&logoColor=white"></a></p>-<p align="center">- <a href="https://www.producthunt.com/products/graphicle?embed=true&utm_source=badge-featured&utm_medium=badge&utm_campaign=badge-graphicle">- <picture>- <source media="(prefers-color-scheme: dark)" srcset="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1294027&theme=dark">- <img alt="Graphicle on Product Hunt" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1294027&theme=light" width="250" height="54">- </picture>- </a>-</p>-<p align="center">Graphicle maps your repository into a code graph, remembers your project's docs, decisions and past agent sessions,and gives your coding agent cited excerpts from both: the exact files and lines. It runs on your machine: no API key needed, no account, <a href="#privacy-and-local-first">no telemetry</a>.<br>@@ -139,8 +130,11 @@ then run `graphicle setup --yes` in this repository and list every file it changtraces a path and exports an interactive HTML graph. After `graphicle graph extract . --code-only`, `graphicle graph affected "retry()"` lists what depends on a symbol.- **Project memory.** Docs (Markdown, PDF, Office, HTML), reviewed decisions and procedures, and past Claude Code and Codex sessions, searchable alongside the code.- **Cited context on a budget.** `graphicle context` and the MCP tools return excerpts with their sources, within a token budget, without calling a model.+- **Packs for long-context models.** `graphicle pack` fills a token budget, up to 2,000,000 tokens, with the code a question needs: architecture, focus code with line numbers, call paths, tests and a manifest. `graphicle ask --pack` and `graphicle plan` send one to a model such as Muse Spark ([packs](docs/pack.md)). In the cache layout the repository part of a pack is the same for every question about a commit, so a provider's prompt cache can bill follow-up questions at its cached price. `graphicle fix` makes a change for an issue on a new branch and runs your tests on it ([fix](docs/fix.md)).- **One MCP server.** `graphicle mcp` serves the code-graph tools, under Graphify's tool names such as `query_graph`, `get_neighbors` and `shortest_path`, next to the memory tools. With `--pull-requests` it also serves the pull-request tools `list_prs`, `get_pr_impact` and `triage_prs`, which use the GitHub CLI ([MCP](docs/mcp.md)).- **Memory tied to your code.** Reviewed memories are tied to the functions they are about: a memory goes stale when that code changes, and edits elsewhere in the file usually leave it current ([the exact rule](crates/graphicle/README.md#memory-anchored-to-code-symbols)). Mentions of code in your docs are linked to the definitions they name (`graphicle call graph.doc_links` lists them).+- **Reviews of a change.** `graphicle review` reviews what a branch adds with the code around it, the callers, callees and tests of what it changes, and keeps only comments on changed lines whose citations hold. A GitHub Action posts the review on pull requests ([review](docs/review.md)).+- **From the screen to the code.** `graphicle see` lets a model reproduce a bug in a web app with computer use on the Meta Model API, `graphicle pixel` finds the code that draws what it points at, and `graphicle fix` patches it and runs your tests ([see it, find it, fix it, check it](docs/flow.md)).- **Across repositories.** Recall can span the repositories of a workspace: `graphicle context --workspace`, or [the workspace MCP endpoint](docs/mcp.md#several-projects-in-one-connection).- **Always current.** Before each answer Graphicle syncs the few files you changed; Git hooks sync after each commit, merge and checkout.- **Sessions carry over.** Session capture keeps each finished turn, and once you have reviewed memories, each new session starts with them and the latest turns.@@ -157,6 +151,7 @@ then run `graphicle setup --yes` in this repository and list every file it chang| Cursor | `~/.cursor/mcp.json` | || VS Code | `.vscode/mcp.json` in the repository | || Claude Desktop | `claude_desktop_config.json` in Claude's settings folder | |+| Muse Code | `~/.config/muse/settings.json` ([Muse Code](docs/muse-code.md)) | hooks in the plugin, a preview: `graphicle connect muse --hooks` || Any other MCP client | a short JSON entry ([MCP](docs/mcp.md)) | |## How it works@@ -279,12 +274,12 @@ More answers: [FAQ](docs/faq.md) · [Troubleshooting](docs/troubleshooting.md)## Documentation-[Quick start](docs/quickstart.md) · [Agents](docs/agents.md) · [MCP](docs/mcp.md) · [Install](docs/install.md) · [Configuration](docs/configuration.md) ·-[Team server](docs/team.md) · [Moving from Graphify](docs/migrate-from-graphify.md) · [Benchmarks](docs/benchmarks.md) · [FAQ](docs/faq.md) · [Changelog](CHANGELOG.md)+[Quick start](docs/quickstart.md) · [Agents](docs/agents.md) · [Muse Code](docs/muse-code.md) · [MCP](docs/mcp.md) · [Packs](docs/pack.md) · [Fix](docs/fix.md) · [Flow](docs/flow.md) · [Review](docs/review.md) · [Install](docs/install.md) · [Configuration](docs/configuration.md) ·+[Team server](docs/team.md) · [Moving from Graphify](docs/migrate-from-graphify.md) · [Benchmarks](docs/benchmarks.md) · [FAQ](docs/faq.md) · [Changelog](CHANGELOG.md) · [Built at Meta's hackathon](HACKATHON.md)The code: [`crates/graphicle/`](crates/graphicle/README.md) (the program: command line, app, HTTP and MCP server), [`crates/graphicle-graph/`](crates/graphicle-graph/README.md) (the code-graph engine),[`crates/graphicle-memory/`](crates/graphicle-memory/README.md) (the memory library), SDKs for [Python](sdk/python/README.md) and [TypeScript](sdk/typescript/README.md),-and a team server recipe in [`deploy/`](deploy/README.md). Each crate builds on its own ([building from source](docs/install.md)).+a team server recipe in [`deploy/`](deploy/README.md), the benchmark kits in [`bench/`](bench/), and the hosted demo in [`demo/`](demo/README.md). Each crate builds on its own ([building from source](docs/install.md)).## Contributingdiff --git a/bench/.gitignore b/bench/.gitignoreindex 8283eab..8fc1183 100644--- a/bench/.gitignore+++ b/bench/.gitignore@@ -28,6 +28,8 @@!*.mjs!*.ts!*.css+# The whole-repository benchmark's question sets: issue URLs, gold files and text hashes, no issue text.+!/whole-repo/questions/*.jsonl# Run folders. Each run under results/ and competitors/ keeps its scripts,# README or methodology, inputs record, summaries, the results the documentsdiff --git a/bench/muse-code/caps.json b/bench/muse-code/caps.jsonnew file mode 100644index 0000000..c9e8f35--- /dev/null+++ b/bench/muse-code/caps.json@@ -0,0 +1,5 @@+{+ "unit": "US dollars, at the prices in ../whole-repo/prices.json",+ "note": "This kit's spending limit for Muse Code runs (muse_bench.py, memory_demo.py, hook_probe.py), summed over every line of its spend log. Each run also has its own cap ($1 by default) and each day its own ($10 by default).",+ "usd": {"meta": 15.0}+}diff --git a/bench/muse-code/hook_probe.py b/bench/muse-code/hook_probe.pynew file mode 100644index 0000000..c52bf5e--- /dev/null+++ b/bench/muse-code/hook_probe.py@@ -0,0 +1,231 @@+#!/usr/bin/env python3+"""Probes of Muse Code's plugins, in short headless sessions: which hook events add context to the model's+input, and what Muse Code does when a plugin's MCP server cannot start.++usage: hook_probe.py --out DIR --spend-log FILE [--muse muse] [--model muse-spark-1.3] [--key-file FILE]+ [--run-cap 0.25] [--server-cap 0.10]++1. Hook events. A probe plugin (OUT/probe-plugin) has one hook per candidate event: SessionStart,+ UserPromptSubmit, PreLLMCall, PostToolUse and PostToolBatch. Each prints `additionalContext` with its own+ marker, `PROBE-<event>-<nonce>`, in the shape Muse Code's hook output takes+ (`{"hookSpecificOutput":{"hookEventName":…,"additionalContext":…}}`), and appends its input to+ `${PLUGIN_DATA}/hook-inputs.jsonl`, so the payload of each event is on record too. In an isolated HOME the+ plugin is validated, installed and approved; one `muse exec --json` session runs a prompt that makes one+ shell call and asks the model to repeat every PROBE- line it can see. Three readings per event, in+ OUT/probe.json:+ - `fired`: the hook ran (its input was recorded);+ - `in_log`: its marker is in Muse Code's session log (session.jsonl), where the conversation is recorded;+ - `seen_by_model`: the model repeated the marker in its answer.+ The order of the markers in the log is recorded too, so a reader can tell whether context from a later+ event changes the start of the conversation. The plugin is removed afterwards.+2. A server that cannot start. Two more plugins, installed one at a time, each with one MCP server whose+ program exits at once with status 1: one sets `"mode": "optional"`, the other sets no mode. For each, one+ session asks for the word OK with one model step. OUT/probe.json's `failing_server` records, per plugin,+ the exit status, whether the session answered, and the end of its error output: whether Muse Code skips+ such a server or stops the session, and whether the field changes it.++Every session is capped and logged like muse_bench.py's runs, within this kit's spending limit: $0.25 for the+hook session and $0.10 for each server session by default.+"""+import argparse+import json+import os+import secrets+import subprocess+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import muse_bench # noqa: E402++EVENTS = ["SessionStart", "UserPromptSubmit", "PreLLMCall", "PostToolUse", "PostToolBatch"]+PROBE = r'''#!/usr/bin/env python3+import json, os, sys+event, nonce, record = sys.argv[1], sys.argv[2], sys.argv[3]+data = sys.stdin.read()+os.makedirs(os.path.dirname(record) or ".", exist_ok=True)+with open(record, "a") as f:+ f.write(json.dumps({"event": event, "input": data[:20000]}) + "\n")+print(json.dumps({"hookSpecificOutput": {"hookEventName": event,+ "additionalContext": f"PROBE-{event}-{nonce}"}}))+'''+FAILING_SERVER = "import sys\nsys.stderr.write('probe server: exits at once\\n')\nsys.exit(1)\n"+PROMPT = ("Run the shell command `ls` once. Then list, one per line and exactly as written, every line in your "+ "context that starts with PROBE-. If you see none, say NONE.")+SERVER_PROMPT = "Reply with the single word OK."+++def manifest(name, description, hooks=(), servers=()):+ return {"schemaVersion": 1, "name": name, "displayName": name, "version": "0.1.0",+ "description": description, "compat": {"source": "native", "manifestDir": ".muse-plugin"},+ "capabilities": {"skills": [], "commands": [], "hooks": list(hooks), "mcpServers": list(servers),+ "reminders": []}}+++def write_plugin(folder, manifest_value, files):+ os.makedirs(os.path.join(folder, ".muse-plugin"), exist_ok=True)+ for relative, text in files.items():+ path = os.path.join(folder, relative)+ os.makedirs(os.path.dirname(path), exist_ok=True)+ with open(path, "w") as f:+ f.write(text)+ with open(os.path.join(folder, ".muse-plugin", "plugin.json"), "w") as f:+ json.dump(manifest_value, f, indent=2)+++def muse(a, env, *args):+ done = subprocess.run([a.muse, *args], env=env, capture_output=True, text=True)+ return {"exit": done.returncode, "stdout": done.stdout[-4000:], "stderr": done.stderr[-2000:]}+++def install(a, env, folder, name, steps):+ """Validate, install and approve a plugin; the steps' outputs go in `steps`."""+ for step, args in [("validate", ["plugins", "validate", folder, "--json"]),+ ("install", ["plugins", "install", folder, "--scope", "user", "--json"]),+ ("approve", ["plugins", "approve", name, "--json"])]:+ steps[f"{name}:{step}"] = muse(a, env, *args)+ if steps[f"{name}:{step}"]["exit"] != 0:+ return False+ return True+++def session(a, env, work, name, prompt, max_steps, cap, price):+ """One capped `muse exec --json` session, logged to the spend log."""+ prompt_file = os.path.join(a.out, f"{name}.prompt.txt")+ with open(prompt_file, "w") as f:+ f.write(prompt)+ cmd = [a.muse, "exec", "--json", "--model", a.model, "--contributor-mode", "off", "--disable-approval",+ "--disable-request-user-input", "--trust-workspace", "--max-model-steps", str(max_steps),+ "--prompt-file", prompt_file]+ meter, reason, t0 = muse_bench.Meter(price), None, time.time()+ err_path = os.path.join(a.out, f"{name}.stderr.txt")+ with open(os.path.join(a.out, f"{name}.events.jsonl"), "w") as raw, open(err_path, "w") as err:+ proc = subprocess.Popen(cmd, cwd=work, env=env, stdout=subprocess.PIPE, stderr=err,+ stdin=subprocess.DEVNULL, start_new_session=True, text=True)+ timer = threading.Timer(600, lambda: muse_bench.stop(proc))+ timer.start()+ try:+ for line in proc.stdout:+ raw.write(line)+ try:+ meter.feed(json.loads(line))+ except ValueError:+ continue+ if reason is None and meter.spent() >= cap:+ reason = "run cap"+ muse_bench.stop(proc)+ code = proc.wait()+ finally:+ timer.cancel()+ tin, cached, tout, treason = meter.usage()+ cost = meter.cost_of(tin, cached, tout)+ muse_bench.append_log(a.spend_log, {+ "time": muse_bench.now_iso(), "provider": "meta", "kit": muse_bench.KIT, "client": "muse-code",+ "model": a.model, "arm": f"probe-{name}", "run": a.out, "status": "ok" if code == 0 and not reason else+ "stopped" if reason else "error", "input_tokens": tin, "cached_tokens": cached, "output_tokens": tout,+ "reasoning_tokens": treason, "model_calls": len(meter.calls), "seconds": round(time.time() - t0, 3),+ "cost_usd": round(cost, 6)})+ with open(err_path, encoding="utf-8", errors="replace") as f:+ stderr_tail = f.read()[-2000:]+ return {"exit_code": code, "stopped": reason, "model_calls": len(meter.calls), "cost_usd": round(cost, 6),+ "answer": "\n".join(meter.texts)[-4000:], "stderr_tail": stderr_tail}+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--out", required=True)+ ap.add_argument("--spend-log", required=True)+ ap.add_argument("--muse", default="muse")+ ap.add_argument("--model", default="muse-spark-1.3")+ ap.add_argument("--key-file", default=None)+ ap.add_argument("--run-cap", type=float, default=0.25, help="the hook session's cap")+ ap.add_argument("--server-cap", type=float, default=0.10, help="each server session's cap")+ ap.add_argument("--prices", default=os.path.join(muse_bench.BENCH, "prices.json"))+ a = ap.parse_args()+ a.out = os.path.abspath(a.out)+ os.makedirs(a.out, exist_ok=True)+ key = open(a.key_file).read().strip() if a.key_file else os.environ.get("MODEL_API_KEY")+ if not key:+ raise SystemExit("hook_probe: no key: pass --key-file (a 0600 file) or set MODEL_API_KEY")+ total = a.run_cap + 2 * a.server_cap+ if muse_bench.logged(a.spend_log, "meta", muse_bench.KIT, muse_bench.now_iso()[:10]) + total > 10.0:+ raise SystemExit("hook_probe: the day cap would be passed")+ price = json.load(open(a.prices))["models"][a.model]+ home = os.path.join(a.out, "home")+ work = os.path.join(a.out, "workspace")+ os.makedirs(work, exist_ok=True)+ with open(os.path.join(work, "README.md"), "w") as f:+ f.write("# Probe workspace\n")+ env = muse_bench.child_env(home, key)+ steps = {}+ result = {"model": a.model, "steps": steps}++ # 1. Hook events.+ nonce = secrets.token_hex(4)+ hooks, files = [], {}+ for event in EVENTS:+ script = f"hooks/{event.lower()}.py"+ files[script] = PROBE+ hooks.append({"id": event.lower(), "event": event,+ "command": ["python3", script, event, nonce, "${PLUGIN_DATA}/hook-inputs.jsonl"],+ "timeoutMs": 5000})+ plugin = os.path.join(a.out, "probe-plugin")+ write_plugin(plugin, manifest("hook-probe", "Adds a marker as context on each hook event.", hooks=hooks), files)+ result["nonce"] = nonce+ if install(a, env, plugin, "hook-probe", steps):+ hooks_run = session(a, env, work, "hooks", PROMPT, 6, a.run_cap, price)+ steps["hook-probe:remove"] = muse(a, env, "plugins", "remove", "hook-probe", "--json")+ # The hooks' record, wherever Muse Code put the plugin's data (or the workspace, unsubstituted).+ inputs = []+ for top in (home, work):+ for folder, _dirs, names in os.walk(top):+ if "hook-inputs.jsonl" in names:+ with open(os.path.join(folder, "hook-inputs.jsonl")) as f:+ inputs.extend(json.loads(line) for line in f if line.strip())+ fired = {item["event"] for item in inputs}+ with open(os.path.join(a.out, "hook-inputs.jsonl"), "w") as f:+ for item in inputs:+ f.write(json.dumps(item) + "\n")+ logs = []+ for folder, _dirs, names in os.walk(os.path.join(home, ".local/share/muse/sessions")):+ if "session.jsonl" in names and "subagent" not in folder:+ logs.append(os.path.join(folder, "session.jsonl"))+ log_text = "".join(open(p, encoding="utf-8", errors="replace").read() for p in sorted(logs))+ markers = {e: f"PROBE-{e}-{nonce}" for e in EVENTS}+ order = sorted((log_text.find(m), e) for e, m in markers.items() if m in log_text)+ result["hooks"] = dict(hooks_run, session_logs=logs, first_offset_in_log=[e for _, e in order])+ result["events"] = {e: {"fired": e in fired, "in_log": markers[e] in log_text,+ "seen_by_model": markers[e] in hooks_run["answer"]} for e in EVENTS}++ # 2. A server that cannot start, with and without "mode": "optional".+ result["failing_server"] = {}+ for mode in ("optional", None):+ label = mode or "default"+ name = f"server-probe-{label}"+ server = {"id": "failing", "transport": "stdio", "command": ["python3", "mcp/fail.py"]}+ if mode:+ server["mode"] = mode+ folder = os.path.join(a.out, name)+ write_plugin(folder, manifest(name, "One MCP server that cannot start.", servers=[server]),+ {"mcp/fail.py": FAILING_SERVER})+ if not install(a, env, folder, name, steps):+ result["failing_server"][label] = {"installed": False}+ continue+ run = session(a, env, work, name, SERVER_PROMPT, 1, a.server_cap, price)+ steps[f"{name}:remove"] = muse(a, env, "plugins", "remove", name, "--json")+ result["failing_server"][label] = dict(run, installed=True, answered=bool(run["answer"].strip()))++ with open(os.path.join(a.out, "probe.json"), "w") as f:+ json.dump(result, f, indent=2)+ for e, r in result.get("events", {}).items():+ print(f"{e:18} fired={r['fired']!s:5} in_log={r['in_log']!s:5} seen_by_model={r['seen_by_model']}")+ for label, r in result["failing_server"].items():+ print(f"failing server ({label}): installed={r.get('installed')} exit={r.get('exit_code')} "+ f"answered={r.get('answered')}")+ print(f"details in {a.out}/probe.json")+++if __name__ == "__main__":+ main()diff --git a/bench/muse-code/memory_demo.py b/bench/muse-code/memory_demo.pynew file mode 100644index 0000000..b962f4d--- /dev/null+++ b/bench/muse-code/memory_demo.py@@ -0,0 +1,185 @@+#!/usr/bin/env python3+"""Session memory in Muse Code, in two headless sessions on a public repository.++usage: memory_demo.py --repo DIR --data DIR --out DIR [--muse muse] [--graphicle graphicle]+ [--model muse-spark-1.3] [--key-file FILE] [--home DIR] [--approve] [--spend-log FILE]+ [--run-cap 1.0] [--day-cap 10.0] [--decision TEXT] [--question TEXT]++1. Setup: in the repository (Graphicle's data folder --data, Muse Code's HOME --home), `graphicle setup+ --clients none` syncs it and `graphicle connect muse --hooks --allow-learning` installs Graphicle's plugin;+ then `muse plugins approve graphicle`.+2. Session 1 makes a decision: the prompt states it and asks Muse Code to record it with Graphicle's+ propose_memory tool, quoting the code it rests on. The proposal is a draft.+3. Approval: you approve the draft in the app (`graphicle --data-dir DATA open`, Memories, Review draft) and+ press Enter; with --approve the script approves it through `graphicle call learning.review`.+4. Session 2 asks the question. It starts with the approved memory (the plugin's SessionStart hook) and should+ answer with the memory's id and the code's path:line.++Every session runs `muse exec --json` with Contributor mode off, within this kit's spending limit ($1 a run,+$10 a day, caps.json in all) and logged to its spend log, as muse_bench.py's runs are. OUT gets each session's events, the draft, and summary.json: the memory's+id, both answers, whether the second cites the memory, and each session's tokens and cost.+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import muse_bench # noqa: E402++DECISION = (+ "Team decision for this repository: a new configuration field of a scheduler plugin is validated in "+ "pkg/scheduler/apis/config/validation (validation_pluginargs.go), never with ad hoc checks inside the "+ "plugin. Read that validation code with graphicle's tools, then record this decision as a project memory "+ "with graphicle's propose_memory tool: kind decision, a short title, the decision in one or two sentences, "+ "and as evidence one line you quote verbatim from the validation code. Reply with the memory's title.")+QUESTION = (+ "By this project's decisions, where should I validate a new configuration field of a scheduler plugin? "+ "Answer in two sentences, and cite the project memory by its id and the code by path:line.")+++def graphicle(a, env, *args, stdin=None):+ out = subprocess.run([a.graphicle, "--data-dir", a.data, *args], cwd=a.repo, env=env, capture_output=True,+ text=True, input=stdin)+ if out.returncode != 0:+ raise SystemExit(f"graphicle {' '.join(args)} failed: {out.stderr.strip()[:500]}")+ return out.stdout+++def call(a, env, operation, arguments):+ with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:+ json.dump(arguments, f)+ try:+ return json.loads(graphicle(a, env, "call", operation, "--arguments", f.name))+ finally:+ os.unlink(f.name)+++def memories(a, env):+ reply = call(a, env, "memories", {"include_retired": False})+ items = reply.get("memories", reply) if isinstance(reply, dict) else reply+ return [m for m in items if isinstance(m, dict)]+++def session(a, env, name, prompt, price):+ """One capped `muse exec --json` session: its answer text, usage and cost."""+ day = muse_bench.now_iso()[:10]+ if muse_bench.logged(a.spend_log, "meta", muse_bench.KIT, day) + a.run_cap > a.day_cap:+ raise SystemExit("memory_demo: the day cap would be passed")+ total_cap = json.load(open(os.path.join(HERE, "caps.json")))["usd"]["meta"]+ if muse_bench.logged(a.spend_log, "meta") + a.run_cap > total_cap:+ raise SystemExit("memory_demo: the total cap (caps.json) would be passed")+ prompt_file = os.path.join(a.out, f"{name}.prompt.txt")+ with open(prompt_file, "w") as f:+ f.write(prompt)+ cmd = [a.muse, "exec", "--json", "--model", a.model, "--contributor-mode", "off", "--disable-approval",+ "--disable-request-user-input", "--trust-workspace", "--max-model-steps", "30",+ "--prompt-file", prompt_file]+ meter, reason, t0 = muse_bench.Meter(price), None, time.time()+ with open(os.path.join(a.out, f"{name}.events.jsonl"), "w") as raw, \+ open(os.path.join(a.out, f"{name}.stderr"), "w") as err:+ proc = subprocess.Popen(cmd, cwd=a.repo, env=env, stdout=subprocess.PIPE, stderr=err,+ stdin=subprocess.DEVNULL, start_new_session=True, text=True)+ timer = threading.Timer(1200, lambda: muse_bench.stop(proc))+ timer.start()+ try:+ for line in proc.stdout:+ raw.write(line)+ try:+ meter.feed(json.loads(line))+ except ValueError:+ continue+ if reason is None and meter.spent() >= a.run_cap - 0.25:+ reason = "run cap"+ muse_bench.stop(proc)+ code = proc.wait()+ finally:+ timer.cancel()+ tin, cached, tout, treason = meter.usage()+ cost = meter.cost_of(tin, cached, tout)+ muse_bench.append_log(a.spend_log, {+ "time": muse_bench.now_iso(), "provider": "meta", "kit": muse_bench.KIT, "client": "muse-code",+ "model": a.model, "arm": f"memory-demo-{name}", "run": os.path.abspath(a.out),+ "status": "ok" if code == 0 and not reason else "stopped" if reason else "error",+ "input_tokens": tin, "cached_tokens": cached, "output_tokens": tout, "reasoning_tokens": treason,+ "model_calls": len(meter.calls), "seconds": round(time.time() - t0, 3), "cost_usd": round(cost, 6)})+ return {"answer": "\n".join(meter.texts), "exit_code": code, "stopped": reason, "model_calls": len(meter.calls),+ "tokens_in": tin, "tokens_cached": cached, "tokens_out": tout, "cost_usd": round(cost, 6)}+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--repo", required=True)+ ap.add_argument("--data", required=True, help="Graphicle's data folder for the demo")+ ap.add_argument("--out", required=True)+ ap.add_argument("--muse", default="muse")+ ap.add_argument("--graphicle", default="graphicle")+ ap.add_argument("--model", default="muse-spark-1.3")+ ap.add_argument("--key-file", default=None)+ ap.add_argument("--home", default=None, help="Muse Code's HOME for the demo (default OUT/home)")+ ap.add_argument("--approve", action="store_true", help="approve the draft through graphicle call")+ ap.add_argument("--spend-log", required=True, help="this kit's spend log, as muse_bench.py's")+ ap.add_argument("--run-cap", type=float, default=1.0)+ ap.add_argument("--day-cap", type=float, default=10.0)+ ap.add_argument("--decision", default=DECISION)+ ap.add_argument("--question", default=QUESTION)+ ap.add_argument("--prices", default=os.path.join(muse_bench.BENCH, "prices.json"))+ a = ap.parse_args()+ a.repo, a.data, a.out = (os.path.abspath(p) for p in (a.repo, a.data, a.out))+ a.home = os.path.abspath(a.home or os.path.join(a.out, "home"))+ os.makedirs(a.out, exist_ok=True)+ os.makedirs(a.home, exist_ok=True)+ key = open(a.key_file).read().strip() if a.key_file else os.environ.get("MODEL_API_KEY")+ if not key:+ raise SystemExit("memory_demo: no key: pass --key-file (a 0600 file) or set MODEL_API_KEY")+ price = json.load(open(a.prices))["models"][a.model]+ env = muse_bench.child_env(a.home, key)++ graphicle(a, env, "setup", "--yes", "--clients", "none", "--no-instructions", "--no-hooks", "--json")+ graphicle(a, env, "connect", "muse", "--hooks", "--allow-learning", "--json")+ subprocess.run([a.muse, "plugins", "approve", "graphicle", "--json"], env=env, check=True,+ stdout=subprocess.DEVNULL)+ before = {m.get("id") for m in memories(a, env)}++ first = session(a, env, "session1", a.decision, price)+ print(f"Session 1 ({first['model_calls']} model calls, ${first['cost_usd']:.4f}):\n{first['answer']}\n")+ drafts = []+ for _ in range(60):+ drafts = [m for m in memories(a, env) if m.get("id") not in before and m.get("state") == "draft"]+ if drafts:+ break+ time.sleep(1)+ if not drafts:+ raise SystemExit("memory_demo: session 1 proposed no memory")+ draft = drafts[-1]+ with open(os.path.join(a.out, "draft.json"), "w") as f:+ json.dump(draft, f, indent=2)+ print(f"Draft memory {draft['id']}: {draft.get('title')}\n{draft.get('body', '')}\n")+ if a.approve:+ call(a, env, "learning.review", {"memory_id": draft["id"], "expected_revision": draft.get("revision", 1),+ "decision": "approve", "maintainer": "demo",+ "reason": "Checked the quoted validation code."})+ else:+ print(f"Approve it in the app: {a.graphicle} --data-dir {a.data} open (Memories, Review draft). "+ "Then press Enter.")+ sys.stdin.readline()+ approved = [m for m in memories(a, env) if m.get("id") == draft["id"]]+ if not approved or approved[0].get("state") != "reviewed":+ raise SystemExit(f"memory_demo: memory {draft['id']} is not approved")++ second = session(a, env, "session2", a.question, price)+ cited = draft["id"] in second["answer"]+ print(f"Session 2 ({second['model_calls']} model calls, ${second['cost_usd']:.4f}):\n{second['answer']}\n")+ print(f"Session 2 cites memory {draft['id']}: {'yes' if cited else 'no'}")+ with open(os.path.join(a.out, "summary.json"), "w") as f:+ json.dump({"memory_id": draft["id"], "title": draft.get("title"), "session1": first, "session2": second,+ "cites_memory": cited, "model": a.model}, f, indent=2)+++if __name__ == "__main__":+ main()diff --git a/bench/muse-code/muse_bench.py b/bench/muse-code/muse_bench.pynew file mode 100644index 0000000..1ccec70--- /dev/null+++ b/bench/muse-code/muse_bench.py@@ -0,0 +1,386 @@+#!/usr/bin/env python3+"""Muse Code headless, with and without Graphicle's plugin, on WholeRepoBench questions.++usage: muse_bench.py --arm plain|plugin --work WORK --texts DIR --out OUT [--questions DIR]+ [--repos kubernetes,home-assistant] [--first N] [--only ID,ID] [--muse PATH] [--graphicle PATH]+ [--model muse-spark-1.3] [--max-steps 25] [--run-cap 1.0] [--day-cap 10.0] [--margin 0.25]+ [--spend-log FILE] [--caps caps.json] [--prices prices.json] [--key-file FILE]+ [--state DIR] [--timeout 1200]++Each question runs `muse exec --json` once, in a clone of WORK/src/<repo> at the question's snapshot S. The+clone shares the bench checkout's objects (git clone --shared) and never changes it; it is reset and cleaned+before every question. Each question gets a fresh copy of its arm's HOME, so Muse Code's own memory and+session state never carry from one question to the next:+- plain: Muse Code alone, with nothing of Graphicle's;+- plugin: Graphicle's plugin installed (graphicle connect muse --hooks --allow-learning) and approved, without+ its three capture hooks (Stop, PreCompact, SessionEnd), so no question's session becomes a source for the next.+The prompt is the benchmark's own (run.py's PROMPT with no context: list the files to change, JSON only), the+same in both arms, with Contributor mode off.++Measures per question: the gold files named (score.py's hit@1/3/5, all-gold@5 and reciprocal rank, on the+answer's "files"), model calls, input, cached and output tokens from Muse Code's usage events, the cost at+prices.json's list prices, and the wall time.++Caps (this kit's spending limit: $1 a run and $10 a day by default, $15 in all in caps.json): a run starts only+when the day's logged total plus the run cap stays within the day cap, and the log's total plus the run cap+within the total cap.+While a run streams, its usage is added up and the run is stopped (SIGTERM to its process group, then SIGKILL)+once its cost reaches the run cap less --margin, the room left for a call in flight; --max-model-steps bounds+it as well. Every run appends one line to this kit's spend log (provider meta, kit muse-code), whatever its+outcome; the log is separate from the whole-repository benchmark's spend log. The key is read+from --key-file (or MODEL_API_KEY) and given to Muse Code as META_API_KEY; it is+never printed or written.+"""+import argparse+import datetime+import fcntl+import json+import os+import shutil+import signal+import subprocess+import sys+import threading+import time++HERE = os.path.dirname(os.path.abspath(__file__))+BENCH = os.path.join(HERE, "..", "whole-repo")+sys.path.insert(0, BENCH)+from run import PROMPT, parse_files # noqa: E402+from score import normalize_answer, score_answer # noqa: E402++KIT = "muse-code"+CAPTURE_HOOKS = ("stop", "pre-compact", "session-end")+++class CapReached(Exception):+ pass+++def now_iso():+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def logged(log_path, provider, kit=None, day=None):+ """The cost_usd total of the spend log's lines of `provider` (and `kit`, on UTC `day`)."""+ total = 0.0+ if not os.path.exists(log_path):+ return total+ with open(log_path) as f:+ for line in f:+ if not line.strip():+ continue+ r = json.loads(line)+ if r.get("provider") != provider:+ continue+ if kit is not None and r.get("kit") != kit:+ continue+ if day is not None and not str(r.get("time", "")).startswith(day):+ continue+ total += r.get("cost_usd") or 0.0+ return total+++def append_log(log_path, record):+ os.makedirs(os.path.dirname(log_path), exist_ok=True)+ with open(log_path, "a") as f:+ fcntl.flock(f, fcntl.LOCK_EX)+ f.write(json.dumps(record, sort_keys=True) + "\n")+ f.flush()+ fcntl.flock(f, fcntl.LOCK_UN)+++def tokens_of(obj):+ """(input, cached, output, reasoning) of a usage object, or None when it is not one."""+ if not isinstance(obj, dict):+ return None+ tin = obj.get("input_tokens", obj.get("prompt_tokens"))+ tout = obj.get("output_tokens", obj.get("completion_tokens"))+ if not isinstance(tin, int) or not isinstance(tout, int):+ return None+ cached = obj.get("cached_input_tokens", obj.get("cached_tokens"))+ if cached is None:+ details = obj.get("input_tokens_details") or obj.get("prompt_tokens_details") or {}+ cached = details.get("cached_tokens", 0) if isinstance(details, dict) else 0+ if not isinstance(cached, int) and isinstance(obj.get("non_cached_input_tokens"), int):+ cached = tin - obj["non_cached_input_tokens"]+ reasoning = obj.get("reasoning_tokens")+ if reasoning is None:+ details = obj.get("output_tokens_details") or {}+ reasoning = details.get("reasoning_tokens", 0) if isinstance(details, dict) else 0+ return tin, int(cached or 0), tout, int(reasoning or 0)+++def walk(value):+ stack = [value]+ while stack:+ v = stack.pop()+ if isinstance(v, dict):+ yield v+ stack.extend(v.values())+ elif isinstance(v, list):+ stack.extend(v)+++def event_name(event):+ if not isinstance(event, dict):+ return ""+ for key in ("type", "event", "kind", "method"):+ if isinstance(event.get(key), str):+ return event[key]+ return ""+++class Meter:+ """Usage and answer text from Muse Code's --json events, as they stream."""++ def __init__(self, price):+ self.price = price+ self.calls = [] # per-call usage tuples+ self.seen = set() # response ids already counted+ self.total = None # run.usage aggregate, when Muse Code printed one+ self.texts = [] # assistant texts, in order+ self.events = 0++ def cost_of(self, tin, cached, tout):+ p = self.price+ return ((tin - cached) * p["input"] + cached * p.get("cached_input", p["input"]) + tout * p["output"]) / 1e6++ def feed(self, event):+ self.events += 1+ name = event_name(event)+ if "run.usage" in name or (name.endswith("usage") and "run" in name):+ found = [t for t in (tokens_of(obj) for obj in walk(event)) if t]+ if found:+ # A total beside per-model rows is the sum of the others: use it alone.+ big = max(found, key=lambda t: t[0])+ rest = [t for t in found if t is not big]+ if rest and all(sum(t[i] for t in rest) == big[i] for i in range(4)):+ self.total = big+ else:+ self.total = tuple(sum(t[i] for t in found) for i in range(4))+ return+ for obj in walk(event):+ usage = obj.get("usage")+ t = tokens_of(usage) if isinstance(usage, dict) else None+ if t:+ rid = obj.get("response_id")+ if not (rid and rid in self.seen):+ if rid:+ self.seen.add(rid)+ self.calls.append(t)+ kind = obj.get("kind") or obj.get("type") or ""+ if isinstance(kind, str) and (kind in ("assistant_message_committed", "assistant_message",+ "agent_message", "final_message")+ or kind.endswith("message.completed")):+ text = obj.get("text") or obj.get("message") or obj.get("content")+ if isinstance(text, list):+ text = "\n".join(p.get("text", "") for p in text if isinstance(p, dict))+ if isinstance(text, str) and text.strip():+ self.texts.append(text)++ def usage(self):+ if self.total is not None and self.total[0] > 0:+ return self.total+ return tuple(sum(c[i] for c in self.calls) for i in range(4))++ def spent(self):+ tin, cached, tout, _ = self.usage()+ return self.cost_of(tin, cached, tout)+++def stop(proc):+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except ProcessLookupError:+ return+ try:+ proc.wait(timeout=20)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+++def git(*args, cwd=None):+ subprocess.run(["git", *args], cwd=cwd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+++def clone_at(src, dest, sha):+ """A clone of src that shares its objects, at sha, with every untracked file removed."""+ if not os.path.isdir(os.path.join(dest, ".git")):+ os.makedirs(os.path.dirname(dest), exist_ok=True)+ git("clone", "-q", "--shared", "--no-checkout", src, dest)+ git("checkout", "-q", "-f", "--detach", sha, cwd=dest)+ git("clean", "-q", "-fdx", cwd=dest)+++def child_env(home, key):+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": home, "LANG": "C.UTF-8",+ "XDG_CONFIG_HOME": os.path.join(home, ".config"), "XDG_DATA_HOME": os.path.join(home, ".local/share"),+ "XDG_CACHE_HOME": os.path.join(home, ".cache"), "TMPDIR": os.path.join(home, "tmp"),+ "NO_COLOR": "1"}+ os.makedirs(env["TMPDIR"], exist_ok=True)+ if key:+ env["META_API_KEY"] = key+ return env+++def prepare_plugin_home(a, home, clone, key):+ """The plugin arm's HOME: Graphicle synced and its plugin installed and approved, capture hooks removed."""+ env = child_env(home, key)+ data = os.path.join(a.state, "graphicle-data")+ subprocess.run([a.graphicle, "--data-dir", data, "setup", "--yes", "--clients", "none", "--no-instructions",+ "--no-hooks", "--json"], cwd=clone, env=env, check=True, stdout=subprocess.DEVNULL)+ subprocess.run([a.graphicle, "--data-dir", data, "connect", "muse", "--hooks", "--allow-learning", "--json"],+ cwd=clone, env=env, check=True, stdout=subprocess.DEVNULL)+ manifest_path = os.path.join(data, "muse-code-plugin", ".muse-plugin", "plugin.json")+ manifest = json.load(open(manifest_path))+ hooks = manifest["capabilities"]["hooks"]+ manifest["capabilities"]["hooks"] = [h for h in hooks if h["command"][-1] not in CAPTURE_HOOKS]+ with open(manifest_path, "w") as f:+ json.dump(manifest, f, indent=2)+ subprocess.run([a.muse, "plugins", "update", "graphicle", "--json"], env=env, check=True,+ stdout=subprocess.DEVNULL)+ subprocess.run([a.muse, "plugins", "approve", "graphicle", "--json"], env=env, check=True,+ stdout=subprocess.DEVNULL)+++def run_question(a, q, text, clone, template, key, price, out):+ qid = q["id"]+ home = os.path.join(a.state, "homes", f"{a.arm}-{qid}")+ if os.path.exists(home):+ shutil.rmtree(home)+ shutil.copytree(template, home, symlinks=True)+ prompt = PROMPT.format(context="", repo=q["repo"], sha=q["S"], issue=text)+ prompt_file = os.path.join(home, "prompt.txt")+ with open(prompt_file, "w") as f:+ f.write(prompt)+ cmd = [a.muse, "exec", "--json", "--model", a.model, "--contributor-mode", "off", "--disable-approval",+ "--disable-request-user-input", "--trust-workspace", "--max-model-steps", str(a.max_steps),+ "--prompt-file", prompt_file]+ meter = Meter(price)+ raw_path = os.path.join(out, "raw", f"{qid}.jsonl")+ reason, t0 = None, time.time()+ with open(raw_path, "w") as raw, open(os.path.join(out, "raw", f"{qid}.stderr"), "w") as err:+ proc = subprocess.Popen(cmd, cwd=clone, env=child_env(home, key), stdout=subprocess.PIPE, stderr=err,+ stdin=subprocess.DEVNULL, start_new_session=True, text=True)+ timer = threading.Timer(a.timeout, lambda: stop(proc))+ timer.start()+ try:+ for line in proc.stdout:+ raw.write(line)+ try:+ meter.feed(json.loads(line))+ except ValueError:+ continue+ if reason is None and meter.spent() >= a.run_cap - a.margin:+ reason = f"run cap: ${meter.spent():.4f} of ${a.run_cap:.2f} less ${a.margin:.2f}"+ stop(proc)+ code = proc.wait()+ finally:+ timer.cancel()+ seconds = time.time() - t0+ if reason is None and seconds >= a.timeout:+ reason = f"timeout {a.timeout}s"+ tin, cached, tout, treason = meter.usage()+ cost = meter.cost_of(tin, cached, tout)+ answer = "\n".join(meter.texts)+ files = parse_files(answer)+ tracked = subprocess.run(["git", "ls-files", "-z"], cwd=clone, capture_output=True, text=True).stdout+ file_set = {p for p in tracked.split("\0") if p}+ norm = normalize_answer(files, file_set) if files is not None else []+ row = {"id": qid, "repo": q["repo"], "arm": a.arm, "model": a.model, "gold": q["gold"], "files": norm,+ "answer_parsed": files is not None, "exit_code": code, "stopped": reason, "events": meter.events,+ "model_calls": len(meter.calls), "tokens_in": tin, "tokens_cached": cached, "tokens_out": tout,+ "tokens_reasoning": treason, "cost_usd": round(cost, 6), "wall_seconds": round(seconds, 1)}+ row.update(score_answer(norm, q["gold"]))+ append_log(a.spend_log, {"time": now_iso(), "provider": "meta", "kit": KIT, "client": "muse-code",+ "model": a.model, "arm": f"muse-{a.arm}", "run": os.path.abspath(out),+ "repo": q["repo"].split("/")[-1], "question": qid, "status": "ok" if code == 0 and+ not reason else "stopped" if reason else "error", "input_tokens": tin,+ "cached_tokens": cached, "output_tokens": tout, "reasoning_tokens": treason,+ "model_calls": len(meter.calls), "seconds": round(seconds, 3),+ "cost_usd": round(cost, 6)})+ return row+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--arm", choices=["plain", "plugin"], required=True)+ ap.add_argument("--work", required=True, help="the bench folder holding src/<repo> checkouts")+ ap.add_argument("--texts", required=True, help="the folder of texts-<repo>.jsonl")+ ap.add_argument("--out", required=True)+ ap.add_argument("--questions", default=os.path.join(BENCH, "questions"))+ ap.add_argument("--repos", default="kubernetes,home-assistant")+ ap.add_argument("--first", type=int, default=5, help="the first N questions of each repository's file")+ ap.add_argument("--only", default="", help="question ids instead of --first")+ ap.add_argument("--muse", default="muse")+ ap.add_argument("--graphicle", default="graphicle")+ ap.add_argument("--model", default="muse-spark-1.3")+ ap.add_argument("--max-steps", type=int, default=25)+ ap.add_argument("--run-cap", type=float, default=1.0)+ ap.add_argument("--day-cap", type=float, default=10.0)+ ap.add_argument("--margin", type=float, default=0.25)+ ap.add_argument("--spend-log", required=True, help="this kit's spend log (JSON lines)")+ ap.add_argument("--caps", default=os.path.join(HERE, "caps.json"), help="this kit's total cap")+ ap.add_argument("--prices", default=os.path.join(BENCH, "prices.json"))+ ap.add_argument("--key-file", default=None)+ ap.add_argument("--state", default=None, help="clones and HOMEs (default OUT/../state)")+ ap.add_argument("--timeout", type=int, default=1200)+ a = ap.parse_args()+ a.spend_log = os.path.abspath(a.spend_log)+ a.state = os.path.abspath(a.state or os.path.join(a.out, "..", "state"))+ price = json.load(open(a.prices))["models"][a.model]+ global_cap = json.load(open(a.caps))["usd"].get("meta")+ key = None+ if a.key_file:+ key = open(a.key_file).read().strip()+ else:+ key = os.environ.get("MODEL_API_KEY") or os.environ.get("META_API_KEY")+ if not key:+ sys.exit("muse_bench: no key: pass --key-file (a 0600 file) or set MODEL_API_KEY")+ os.makedirs(os.path.join(a.out, "raw"), exist_ok=True)+ os.makedirs(a.state, exist_ok=True)+ only = [x for x in a.only.split(",") if x]+ rows_path = os.path.join(a.out, "rows.jsonl")+ done = set()+ if os.path.exists(rows_path):+ done = {json.loads(l)["id"] for l in open(rows_path) if l.strip()}+ for name in [r for r in a.repos.split(",") if r]:+ qs = [json.loads(l) for l in open(os.path.join(a.questions, f"questions-{name}.jsonl")) if l.strip()]+ qs = [q for q in qs if q["id"] in only] if only else qs[:a.first]+ texts = {}+ for line in open(os.path.join(a.texts, f"texts-{name}.jsonl")):+ t = json.loads(line)+ texts[t["id"]] = t["text"]+ clone = os.path.join(a.state, "clones", f"{a.arm}-{name}")+ template = os.path.join(a.state, "homes", f"{a.arm}-template-{name}")+ for q in qs:+ if q["id"] in done:+ continue+ day = now_iso()[:10]+ today = logged(a.spend_log, "meta", KIT, day)+ if today + a.run_cap > a.day_cap:+ raise CapReached(f"day cap ${a.day_cap:.2f}: logged ${today:.4f} today")+ if global_cap is not None and logged(a.spend_log, "meta") + a.run_cap > global_cap:+ raise CapReached(f"total cap ${global_cap:.2f} (caps.json)")+ clone_at(os.path.join(a.work, "src", name), clone, q["S"])+ if not os.path.isdir(template):+ os.makedirs(template)+ if a.arm == "plugin":+ prepare_plugin_home(a, template, clone, key)+ row = run_question(a, q, texts[q["id"]], clone, template, key, price, a.out)+ with open(rows_path, "a") as f:+ f.write(json.dumps(row, sort_keys=True) + "\n")+ print(f"{q['id']} {a.arm}: hit5={row['hit5']} calls={row['model_calls']} in={row['tokens_in']} "+ f"cached={row['tokens_cached']} out={row['tokens_out']} ${row['cost_usd']:.4f}"+ f"{' STOPPED ' + row['stopped'] if row['stopped'] else ''}", flush=True)+++if __name__ == "__main__":+ try:+ main()+ except CapReached as e:+ sys.exit(f"muse_bench: stopped by a cap: {e}")diff --git a/bench/muse-code/test_hook_probe.py b/bench/muse-code/test_hook_probe.pynew file mode 100644index 0000000..853b53b--- /dev/null+++ b/bench/muse-code/test_hook_probe.py@@ -0,0 +1,109 @@+#!/usr/bin/env python3+"""Tests of hook_probe.py with a fake `muse` program: the hook readings (fired, in the session log, seen by+the model), the failing-server sessions with and without "mode": "optional", the plugins' removal, and the+spend log. No model is called.++usage: python3 -m unittest -v test_hook_probe+"""+import json+import os+import stat+import subprocess+import sys+import tempfile+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))++# The fake keeps the installed plugins in a state file beside it. `exec` with the hook probe installed runs+# its SessionStart hook (with ${PLUGIN_DATA} under HOME), writes a session log holding that hook's marker,+# and answers with the marker; with a failing server installed it answers OK when the server is optional+# and stops with status 1 otherwise, as a required server would.+FAKE_MUSE = r'''#!/usr/bin/env python3+import json, os, subprocess, sys+here = os.path.dirname(os.path.abspath(__file__))+state_path = os.path.join(here, "installed.json")+installed = json.load(open(state_path)) if os.path.exists(state_path) else {}+args = sys.argv[1:]+with open(os.path.join(here, "calls.log"), "a") as f:+ f.write(" ".join(args[:3]) + "\n")+def emit(event):+ print(json.dumps(event), flush=True)+if args[0] == "plugins":+ if args[1] == "install":+ manifest = json.load(open(os.path.join(args[2], ".muse-plugin", "plugin.json")))+ installed[manifest["name"]] = args[2]+ elif args[1] == "remove":+ installed.pop(args[2], None)+ json.dump(installed, open(state_path, "w"))+ print(json.dumps({"ok": True}))+ sys.exit(0)+home = os.environ["HOME"]+emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "model_completed",+ "response_id": "r1", "usage": {"input_tokens": 1000, "cached_tokens": 0, "output_tokens": 10}}}})+if "hook-probe" in installed:+ folder = installed["hook-probe"]+ manifest = json.load(open(os.path.join(folder, ".muse-plugin", "plugin.json")))+ hook = next(h for h in manifest["capabilities"]["hooks"] if h["event"] == "SessionStart")+ data = os.path.join(home, ".local/share/muse/plugin-data/hook-probe")+ argv = [part.replace("${PLUGIN_DATA}", data) for part in hook["command"]]+ out = subprocess.run(argv, cwd=folder, input=json.dumps({"hook_event_name": "SessionStart"}),+ capture_output=True, text=True, check=True).stdout+ marker = json.loads(out)["hookSpecificOutput"]["additionalContext"]+ log = os.path.join(home, ".local/share/muse/sessions/2026/10/27/s1/session.jsonl")+ os.makedirs(os.path.dirname(log), exist_ok=True)+ with open(log, "w") as f:+ f.write(json.dumps({"payload": {"event": {"kind": "hook_context", "text": marker}}}) + "\n")+ emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "assistant_message_committed",+ "text": marker}}})+ sys.exit(0)+failing = [n for n in installed if n.startswith("server-probe-")]+if failing:+ manifest = json.load(open(os.path.join(installed[failing[0]], ".muse-plugin", "plugin.json")))+ if manifest["capabilities"]["mcpServers"][0].get("mode") != "optional":+ sys.stderr.write("MCP server failing (required) did not start\n")+ sys.exit(1)+emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "assistant_message_committed",+ "text": "OK"}}})+'''+++class HookProbeTest(unittest.TestCase):+ def test_readings_failing_servers_and_log(self):+ with tempfile.TemporaryDirectory() as root:+ program = os.path.join(root, "bin", "muse")+ os.makedirs(os.path.dirname(program))+ with open(program, "w") as f:+ f.write(FAKE_MUSE)+ os.chmod(program, os.stat(program).st_mode | stat.S_IXUSR)+ key = os.path.join(root, "key")+ with open(key, "w") as f:+ f.write("test-key-not-real\n")+ out, log = os.path.join(root, "out"), os.path.join(root, "spend.jsonl")+ done = subprocess.run([sys.executable, os.path.join(HERE, "hook_probe.py"), "--out", out,+ "--spend-log", log, "--muse", program, "--key-file", key],+ capture_output=True, text=True, timeout=300)+ self.assertEqual(done.returncode, 0, done.stderr)+ with open(os.path.join(out, "probe.json")) as f:+ result = json.load(f)+ start = result["events"]["SessionStart"]+ self.assertEqual((start["fired"], start["in_log"], start["seen_by_model"]), (True, True, True))+ self.assertFalse(result["events"]["PreLLMCall"]["fired"])+ self.assertEqual(result["hooks"]["first_offset_in_log"], ["SessionStart"])+ optional, default = result["failing_server"]["optional"], result["failing_server"]["default"]+ self.assertEqual((optional["exit_code"], optional["answered"]), (0, True))+ self.assertEqual((default["exit_code"], default["answered"]), (1, False))+ self.assertIn("did not start", default["stderr_tail"])+ with open(os.path.join(root, "bin", "installed.json")) as f:+ self.assertEqual(json.load(f), {}, "every probe plugin is removed")+ with open(log) as f:+ lines = [json.loads(line) for line in f if line.strip()]+ self.assertEqual([l["arm"] for l in lines],+ ["probe-hooks", "probe-server-probe-optional", "probe-server-probe-default"])+ self.assertTrue(all(l["kit"] == "muse-code" for l in lines))+ with open(log) as f:+ self.assertNotIn("test-key", f.read())+++if __name__ == "__main__":+ unittest.main()diff --git a/bench/muse-code/test_muse_bench.py b/bench/muse-code/test_muse_bench.pynew file mode 100644index 0000000..9dc6ee0--- /dev/null+++ b/bench/muse-code/test_muse_bench.py@@ -0,0 +1,207 @@+#!/usr/bin/env python3+"""Tests of muse_bench.py with a fake `muse` (and `graphicle`) program: scoring, usage, the plugin arm's+HOME, the spend log, and the caps that stop a run. No model is called.++usage: python3 -m unittest -v test_muse_bench+"""+import json+import os+import stat+import subprocess+import sys+import tempfile+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import muse_bench # noqa: E402++# A fake muse: `plugins …` records its call; `exec --json …` prints the events of the mode in+# FAKE_MODE (a file beside the program), reading the prompt file it is given.+FAKE_MUSE = r'''#!/usr/bin/env python3+import json, os, sys, time+here = os.path.dirname(os.path.abspath(__file__))+with open(os.path.join(here, "calls.log"), "a") as f:+ f.write(json.dumps({"args": sys.argv[1:], "cwd": os.getcwd(), "home": os.environ.get("HOME"),+ "key": "META_API_KEY" in os.environ}) + "\n")+if sys.argv[1] == "plugins":+ print(json.dumps({"ok": True}))+ sys.exit(0)+mode = open(os.path.join(here, "FAKE_MODE")).read().strip()+prompt = open(sys.argv[sys.argv.index("--prompt-file") + 1]).read()+assert "List the source files" in prompt+def emit(event):+ print(json.dumps(event), flush=True)+if mode == "answer":+ emit({"type": "run.started", "run_id": "r1"})+ emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "model_completed",+ "response_id": "a", "usage": {"input_tokens": 20000, "cached_tokens": 0, "output_tokens": 300}}}})+ emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "model_completed",+ "response_id": "b", "usage": {"input_tokens": 30000, "cached_tokens": 19000, "output_tokens": 200}}}})+ emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "assistant_message_committed",+ "text": "{\"files\": [\"./pkg/a.go\", \"pkg/b.go:12\", \"missing.go\"]}"}}})+ emit({"type": "run.usage", "models": [{"model": "muse-spark-1.3", "input_tokens": 50000,+ "cached_input_tokens": 19000, "output_tokens": 500, "reasoning_tokens": 0}],+ "total": {"input_tokens": 50000, "cached_input_tokens": 19000, "output_tokens": 500,+ "reasoning_tokens": 0}})+elif mode == "spend":+ for i in range(1000):+ emit({"type": "agent.event", "payload": {"kind": "run", "event": {"kind": "model_completed",+ "response_id": f"c{i}", "usage": {"input_tokens": 200000, "cached_tokens": 0,+ "output_tokens": 1000}}}})+ time.sleep(0.05)+'''++# A fake graphicle: `connect` writes the plugin's manifest where `connect muse --hooks` would, with six+# hooks; `setup` (the sync) records only that it ran.+FAKE_GRAPHICLE = r'''#!/usr/bin/env python3+import json, os, sys+data = sys.argv[sys.argv.index("--data-dir") + 1]+if "connect" not in sys.argv:+ print("{}")+ sys.exit(0)+assert sys.argv[sys.argv.index("connect"):][:3] == ["connect", "muse", "--hooks"]+folder = os.path.join(data, "muse-code-plugin", ".muse-plugin")+os.makedirs(folder, exist_ok=True)+hooks = [{"id": h, "event": e, "command": ["graphicle", "hook", "muse", h], "timeoutMs": 1000}+ for h, e in [("session-start", "SessionStart"), ("prompt-context", "UserPromptSubmit"),+ ("tool-batch", "PostToolBatch"), ("stop", "Stop"), ("pre-compact", "PreCompact"),+ ("session-end", "SessionEnd")]]+json.dump({"name": "graphicle", "capabilities": {"hooks": hooks}}, open(os.path.join(folder, "plugin.json"), "w"))+print("{}")+'''+++def program(path, text):+ with open(path, "w") as f:+ f.write(text)+ os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)+++class MuseBenchTest(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ root = self.tmp.name+ self.work, self.bin = os.path.join(root, "work"), os.path.join(root, "bin")+ src = os.path.join(self.work, "src", "demo")+ os.makedirs(os.path.join(src, "pkg"))+ os.makedirs(self.bin)+ for name in ("a.go", "b.go"):+ with open(os.path.join(src, "pkg", name), "w") as f:+ f.write("package pkg\n")+ env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="[email protected]", GIT_COMMITTER_NAME="t",+ GIT_COMMITTER_EMAIL="[email protected]", GIT_CONFIG_NOSYSTEM="1")+ for args in (["init", "-q"], ["add", "."], ["commit", "-q", "-m", "s"]):+ subprocess.run(["git", *args], cwd=src, check=True, env=env)+ self.sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=src, capture_output=True, text=True,+ check=True).stdout.strip()+ self.questions = os.path.join(root, "questions")+ self.texts = os.path.join(root, "texts")+ os.makedirs(self.questions)+ os.makedirs(self.texts)+ with open(os.path.join(self.questions, "questions-demo.jsonl"), "w") as f:+ for n in (1, 2):+ f.write(json.dumps({"id": f"demo-{n}", "repo": "o/demo", "S": self.sha,+ "gold": ["pkg/b.go"]}) + "\n")+ with open(os.path.join(self.texts, "texts-demo.jsonl"), "w") as f:+ for n in (1, 2):+ f.write(json.dumps({"id": f"demo-{n}", "text": f"Issue {n}: b is wrong."}) + "\n")+ self.key = os.path.join(root, "key")+ with open(self.key, "w") as f:+ f.write("test-key-not-real\n")+ program(os.path.join(self.bin, "muse"), FAKE_MUSE)+ program(os.path.join(self.bin, "graphicle"), FAKE_GRAPHICLE)+ self.log = os.path.join(root, "spend", "spend-log.jsonl")++ def tearDown(self):+ self.tmp.cleanup()++ def mode(self, mode):+ with open(os.path.join(self.bin, "FAKE_MODE"), "w") as f:+ f.write(mode)++ def run_bench(self, arm, *extra):+ out = os.path.join(self.tmp.name, "out", arm)+ cmd = [sys.executable, os.path.join(HERE, "muse_bench.py"), "--arm", arm, "--work", self.work,+ "--texts", self.texts, "--out", out, "--questions", self.questions, "--repos", "demo",+ "--muse", os.path.join(self.bin, "muse"), "--graphicle", os.path.join(self.bin, "graphicle"),+ "--key-file", self.key, "--spend-log", self.log, *extra]+ done = subprocess.run(cmd, capture_output=True, text=True, timeout=300)+ rows_path = os.path.join(out, "rows.jsonl")+ rows = []+ if os.path.exists(rows_path):+ with open(rows_path) as f:+ rows = [json.loads(l) for l in f if l.strip()]+ return done, rows++ def calls(self):+ with open(os.path.join(self.bin, "calls.log")) as f:+ return [json.loads(l) for l in f]++ def test_scores_usage_and_log(self):+ self.mode("answer")+ done, rows = self.run_bench("plain")+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertEqual([r["id"] for r in rows], ["demo-1", "demo-2"])+ row = rows[0]+ self.assertEqual(row["files"], ["pkg/a.go", "pkg/b.go", "missing.go"])+ self.assertEqual((row["hit1"], row["hit3"], row["rr"]), (0, 1, 0.5))+ # The run.usage total wins over the per-call sum.+ self.assertEqual((row["tokens_in"], row["tokens_cached"], row["tokens_out"]), (50000, 19000, 500))+ self.assertEqual(row["model_calls"], 2)+ expected = ((50000 - 19000) * 1.25 + 19000 * 0.15 + 500 * 4.25) / 1e6+ self.assertAlmostEqual(row["cost_usd"], expected, places=6)+ with open(self.log) as f:+ text = f.read()+ lines = [json.loads(l) for l in text.splitlines() if l.strip()]+ self.assertEqual([l["kit"] for l in lines], ["muse-code", "muse-code"])+ self.assertEqual(lines[0]["provider"], "meta")+ self.assertNotIn("test-key", text)+ execs = [c for c in self.calls() if c["args"][0] == "exec"]+ self.assertTrue(all(c["key"] for c in execs))+ for flag in ("--json", "--disable-approval", "--trust-workspace"):+ self.assertIn(flag, execs[0]["args"])+ self.assertEqual(execs[0]["args"][execs[0]["args"].index("--contributor-mode") + 1], "off")+ # Each question gets a fresh HOME.+ self.assertNotEqual(execs[0]["home"], execs[1]["home"])+ # Resumed: questions in rows.jsonl are skipped.+ again, rows = self.run_bench("plain")+ self.assertEqual(len(rows), 2)++ def test_plugin_home_drops_capture_hooks(self):+ self.mode("answer")+ done, rows = self.run_bench("plugin", "--first", "1")+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertEqual(len(rows), 1)+ plugin_calls = [c["args"][:3] for c in self.calls() if c["args"][0] == "plugins"]+ self.assertEqual(plugin_calls, [["plugins", "update", "graphicle"], ["plugins", "approve", "graphicle"]])+ state = os.path.join(self.tmp.name, "out", "state")+ with open(os.path.join(state, "graphicle-data", "muse-code-plugin", ".muse-plugin", "plugin.json")) as f:+ manifest = json.load(f)+ self.assertEqual([h["id"] for h in manifest["capabilities"]["hooks"]],+ ["session-start", "prompt-context", "tool-batch"])++ def test_run_cap_stops_a_run(self):+ self.mode("spend")+ done, rows = self.run_bench("plain", "--first", "1", "--run-cap", "1.0", "--margin", "0.25")+ self.assertEqual(done.returncode, 0, done.stderr)+ row = rows[0]+ self.assertTrue(row["stopped"].startswith("run cap"), row)+ # Stopped at the first call past $0.75: each call costs $0.25425.+ self.assertLess(row["cost_usd"], 1.1)+ self.assertGreaterEqual(row["cost_usd"], 0.75)++ def test_day_cap_refuses_a_run(self):+ self.mode("answer")+ os.makedirs(os.path.dirname(self.log))+ with open(self.log, "w") as f:+ f.write(json.dumps({"time": muse_bench.now_iso(), "provider": "meta", "kit": "muse-code",+ "cost_usd": 9.5}) + "\n")+ done, rows = self.run_bench("plain")+ self.assertNotEqual(done.returncode, 0)+ self.assertIn("day cap", done.stderr)+ self.assertEqual(rows, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/bench/pixel/measure.py b/bench/pixel/measure.pynew file mode 100644index 0000000..d0bd8d5--- /dev/null+++ b/bench/pixel/measure.py@@ -0,0 +1,105 @@+#!/usr/bin/env python3+"""measure.py LABELS BINARY DATA_DIR PROJECT OUT [--e2e SCREENS_DIR CONFIG]: the pixel benchmark.++LABELS is a JSON file: {"labels": [{"id", "strings", "nearby", "gold": [{"path", "lines": [first, last]}]}]},+the true visible strings of each clicked element and the source lines that draw it, labelled by hand. For each+label, `graphicle pixel --text ... --json --top 5` runs on the project of DATA_DIR twice: with the element's own+strings (arm "text"), then with the labels near it too (arm "text+nearby"). A label's file rank is where the+first candidate in a gold file stands; its line rank, where the first candidate whose line is inside a gold range+stands. OUT gets every row and the hit rates at 1, 3 and 5.++With --e2e (live, needs the model key; about $0.0025 for SAM and a few tenths of a cent for Muse Spark per label)+the arm "e2e" runs `graphicle pixel SCREEN --at X,Y` instead: SAM finds the element, the model reads it, and the+lookup runs on what it read. CONFIG is the models file (with the SAM and reading profiles). The rows keep the+strings read, the box and the cost.+"""+import json+import os+import statistics+import subprocess+import sys+import time++ARMS = ("text", "text+nearby")+++def run(binary, data, project, label, arm, e2e=None):+ args = [binary, "--data-dir", data]+ if arm == "e2e":+ screens, config = e2e+ args += ["--config", config, "pixel", os.path.join(screens, label["screen"]), "--at",+ f'{label["x"]},{label["y"]}']+ else:+ args += ["pixel"]+ for text in label["strings"]:+ args += ["--text", text]+ args += ["--project", project, "--json", "--top", "5"]+ if arm == "text+nearby":+ for text in label.get("nearby", []):+ args += ["--nearby", text]+ env = dict(os.environ, GRAPHICLE_FRESHNESS="off", GRAPHICLE_NO_UPDATE_NOTIFIER="1")+ started = time.time()+ done = subprocess.run(args, capture_output=True, text=True, env=env, timeout=900)+ seconds = round(time.time() - started, 2)+ if done.returncode != 0:+ return {"error": done.stderr[-600:], "seconds": seconds}+ report = json.loads(done.stdout)+ candidates = report.get("candidates", [])+ gold = label["gold"]++ def rank(test):+ return next((i + 1 for i, c in enumerate(candidates) if test(c)), None)++ extra = {}+ if arm == "e2e":+ extra = {"read": report.get("read"), "box": report.get("box"), "cost_usd": report.get("cost_usd"),+ "notes": report.get("notes")}+ return {+ **extra,+ "file_rank": rank(lambda c: any(c["path"] == g["path"] for g in gold)),+ "line_rank": rank(lambda c: any(c["path"] == g["path"] and g["lines"][0] <= c["line"] <= g["lines"][1]+ for g in gold)),+ "top": [f'{c["path"]}:{c["line"]}' for c in candidates],+ "seconds": seconds,+ "lookup_seconds": report.get("lookup", {}).get("seconds"),+ "graph": report.get("lookup", {}).get("graph"),+ }+++def main(labels_path, binary, data, project, out, *rest):+ labels = json.load(open(labels_path))["labels"]+ e2e = (rest[1], rest[2]) if rest[:1] == ("--e2e",) else None+ arms = ("e2e",) if e2e else ARMS+ rows = []+ for label in labels:+ for arm in arms:+ if arm == "text+nearby" and not label.get("nearby"):+ continue+ row = {"id": label["id"], "arm": arm, **run(binary, data, project, label, arm, e2e)}+ rows.append(row)+ print(row["id"], arm, row.get("file_rank"), row.get("line_rank"), row.get("seconds"),+ row.get("error", "")[:200], flush=True)+ summary = {}+ for arm in arms:+ mine = [r for r in rows if r["arm"] == arm and "error" not in r]+ if not mine:+ continue+ n = len(mine)++ def share(key, k):+ return round(100.0 * sum(1 for r in mine if r[key] and r[key] <= k) / n, 1)++ summary[arm] = {+ "labels": n,+ "file_top1": share("file_rank", 1), "file_top3": share("file_rank", 3),+ "file_top5": share("file_rank", 5), "line_top1": share("line_rank", 1),+ "line_top5": share("line_rank", 5),+ "median_seconds": statistics.median(r["seconds"] for r in mine),+ "errors": sum(1 for r in rows if r["arm"] == arm and "error" in r),+ }+ json.dump({"summary": summary, "rows": rows}, open(out, "w"), indent=1)+ print(json.dumps(summary, indent=1))+++if __name__ == "__main__":+ main(*sys.argv[1:])diff --git a/bench/pixel/shots.py b/bench/pixel/shots.pynew file mode 100644index 0000000..b5598fa--- /dev/null+++ b/bench/pixel/shots.py@@ -0,0 +1,174 @@+#!/usr/bin/env python3+"""shots.py vscode OUT_DIR | shots.py app URL_FILE OUT_DIR: screenshots for the pixel benchmark.++`vscode` opens VS Code for the web at https://vscode.dev (Microsoft's hosted build, run in the browser; no+local server) with no folder. `app` opens Graphicle's own app at the address in URL_FILE (it carries the local+sign-in secret, so it is never printed or saved anywhere else). For each screen the script runs its steps+(commands through VS Code's command palette, or the app's routes), waits, saves OUT_DIR/<screen>.png+(1600x900 at scale 1, dark scheme) and records each target element's box, centre and visible text in+OUT_DIR/screens.json; a target not on the screen is recorded as missing. The source location that draws each+element is labelled by hand afterwards, from the repository at the benchmark's commit.++Needs Playwright (PyPI) and its Chromium headless shell (PLAYWRIGHT_BROWSERS_PATH).+"""+import json+import os+import sys+import time+from urllib.parse import urlparse++from playwright.sync_api import sync_playwright++W, H = 1600, 900+++def palette(page, command, enter=True):+ page.keyboard.press("F1")+ page.wait_for_selector(".quick-input-widget input", state="visible", timeout=15000)+ page.keyboard.type(command, delay=15)+ time.sleep(1.2)+ if enter:+ page.keyboard.press("Enter")+ time.sleep(2.5)+++def escape(page):+ page.keyboard.press("Escape")+ time.sleep(0.5)+++def text(page, value, scope=None):+ root = page.locator(scope).first if scope else page+ return root.get_by_text(value, exact=True)+++def steps(*actions):+ def run(page):+ for action in actions:+ action(page)+ return run+++# VS Code for the web, no folder open. Each screen: a name, its steps, and its targets (a label and a+# function returning a Playwright locator): elements with visible text a developer might ask about.+VSCODE = [+ ("v01-welcome", steps(lambda p: palette(p, "Help: Welcome")), [+ ("welcome: subtitle", lambda p: text(p, "Editing evolved")),+ ("welcome: new file", lambda p: text(p, "New File...")),+ ("welcome: open folder", lambda p: text(p, "Open Folder...", ".gettingStartedContainer")),+ ("welcome: walkthroughs heading", lambda p: text(p, "Walkthroughs")),+ ("welcome: learn the fundamentals", lambda p: text(p, "Learn the Fundamentals")),+ ("welcome: show on startup", lambda p: text(p, "Show welcome page on startup")),+ ("welcome: open a folder link", lambda p: text(p, "open a folder")),+ ]),+ ("v02-explorer", steps(escape, lambda p: palette(p, "View: Close All Editors"),+ lambda p: palette(p, "View: Show Explorer")), [+ ("explorer: no folder message", lambda p: text(p, "You have not yet opened a folder.")),+ ("explorer: open folder button", lambda p: p.locator(".part.sidebar").get_by_role("button", name="Open Folder")),+ ("explorer: open recent button", lambda p: p.locator(".part.sidebar").get_by_role("button", name="Open Recent")),+ ("explorer: no folder opened header", lambda p: text(p, "No Folder Opened", ".part.sidebar")),+ ("explorer: connect to tunnel button", lambda p: p.locator(".part.sidebar").get_by_role("button", name="Connect to Tunnel...")),+ ("watermark: show all commands", lambda p: text(p, "Show All Commands", ".part.editor")),+ ("watermark: find in files", lambda p: text(p, "Find in Files", ".part.editor")),+ ]),+ ("v03-untitled", steps(escape, lambda p: palette(p, "File: New Untitled Text File")), [+ ("status bar: cursor position", lambda p: p.locator("[id='status.editor.selection']").first),+ ("status bar: indentation", lambda p: p.locator("[id='status.editor.indentation']").first),+ ("status bar: language mode", lambda p: p.locator("[id='status.editor.mode']").first),+ ]),+ ("v04-debug", steps(escape, lambda p: palette(p, "View: Show Run and Debug")), [+ ("debug: disabled extensions text", lambda p: p.locator(".part.sidebar .welcome-view-content p").nth(0)),+ ("debug: not available text", lambda p: p.locator(".part.sidebar .welcome-view-content p").nth(1)),+ ]),+ ("v05-palette", steps(escape, lambda p: palette(p, "toggle word wrap", enter=False)), [+ ("palette: toggle word wrap", lambda p: p.locator(".quick-input-list .monaco-list-row .label-name").first),+ ]),+ ("v06-settings", steps(escape, lambda p: palette(p, "Preferences: Open Settings (UI)"), lambda p: time.sleep(2)), [+ ("settings: commonly used", lambda p: text(p, "Commonly Used", ".settings-toc-container")),+ ("settings: first description", lambda p: p.locator(".setting-item-description").first),+ ]),+ ("v07-keybindings", steps(escape, lambda p: p.keyboard.press("Control+K"), lambda p: p.keyboard.press("Control+S"),+ lambda p: time.sleep(3)), [+ ("keybindings: command column", lambda p: text(p, "Command", ".keybindings-editor")),+ ("keybindings: when column", lambda p: text(p, "When", ".keybindings-editor")),+ ]),+ ("v08-problems", steps(escape, lambda p: palette(p, "View: Focus Problems")), [+ ("problems: empty message", lambda p: text(p, "No problems have been detected in the workspace.")),+ ]),+ ("v09-extensions", steps(escape, lambda p: palette(p, "View: Show Extensions"), lambda p: time.sleep(4)), [+ ("extensions: installed header", lambda p: text(p, "Installed", ".part.sidebar")),+ ]),+]+++def box_of(locator):+ if locator.count() == 0:+ return None+ first = locator.first+ if not first.is_visible():+ return None+ b = first.bounding_box()+ if not b or b["width"] < 2 or b["height"] < 2:+ return None+ inner = first.inner_text(timeout=3000).strip()+ return {"x1": round(b["x"]), "y1": round(b["y"]), "x2": round(b["x"] + b["width"]),+ "y2": round(b["y"] + b["height"]), "x": round(b["x"] + b["width"] / 2),+ "y": round(b["y"] + b["height"] / 2), "text": inner[:400]}+++def record(page, screens_spec, out):+ screens = []+ for name, run, targets in screens_spec:+ entry = {"screen": f"{name}.png", "targets": []}+ try:+ run(page)+ except Exception as error: # a step that fails leaves the screen as it is+ entry["step_error"] = type(error).__name__+ time.sleep(1.5)+ page.screenshot(path=os.path.join(out, f"{name}.png"))+ for label, find in targets:+ try:+ found = box_of(find(page))+ except Exception as error:+ found = None+ entry.setdefault("errors", []).append(f"{label}: {type(error).__name__}")+ entry["targets"].append({"label": label, "box": found})+ screens.append(entry)+ print(name, sum(1 for t in entry["targets"] if t["box"]), "of", len(entry["targets"]), "targets",+ entry.get("step_error", ""), flush=True)+ return screens+++def main(argv):+ kind = argv[1]+ if kind == "vscode":+ url, out, spec = "https://vscode.dev/", argv[2], VSCODE+ else:+ url, out, spec = open(argv[2]).read().strip(), argv[3], APP+ os.makedirs(out, exist_ok=True)+ with sync_playwright() as pw:+ browser = pw.chromium.launch(headless=True)+ ctx = browser.new_context(viewport={"width": W, "height": H}, device_scale_factor=1,+ color_scheme="dark")+ page = ctx.new_page()+ page.goto(url, wait_until="domcontentloaded", timeout=120000)+ if kind == "vscode":+ page.wait_for_selector(".monaco-workbench", timeout=120000)+ time.sleep(10)+ version = page.evaluate("() => document.querySelector('meta[name=\"version\"]')?.content || null")+ else:+ time.sleep(4)+ version = None+ screens = record(page, spec, out)+ browser.close()+ origin = urlparse(url)+ with open(os.path.join(out, "screens.json"), "w") as f:+ json.dump({"target": kind, "host": origin.hostname if kind == "vscode" else "local",+ "version_meta": version, "viewport": [W, H], "screens": screens}, f, indent=1)+++# Graphicle's own app (`graphicle open`): filled in when the app's screens are recorded.+APP = []++if __name__ == "__main__":+ main(sys.argv)diff --git a/bench/whole-repo/README.md b/bench/whole-repo/README.mdnew file mode 100644index 0000000..1486528--- /dev/null+++ b/bench/whole-repo/README.md@@ -0,0 +1,96 @@+# Whole-repository change localization++A benchmark of finding the files a real fix changed, in eight public repositories that are each far larger+than a 1M-token context window. It compares Graphicle's `graphicle pack` with truncation of the repository,+with the same model searching the repository through tools (the search-only agent), and with no repository+context. The method, the questions and the scorer were fixed before any model result was seen. The report is+[docs/benchmarks/whole-repo.md](../../docs/benchmarks/whole-repo.md).++| Role | Repository |+|---|---|+| Development (used to tune `graphicle pack`) | kubernetes/kubernetes, home-assistant/core |+| Development, added 27 Oct 2026 for TypeScript, Java and C++ (before any tuning on them) | angular/angular, keycloak/keycloak, godotengine/godot |+| Held out (never used for tuning; run once per release candidate) | pytorch/pytorch, microsoft/vscode, elastic/elasticsearch |++The three newer development repositories were mined with the same method and filters, 40 questions each+(`repos.json`; the selection seed is `selection_seed` plus the repository's place in that list).++## The question sets++`questions/questions-<name>.jsonl` holds one question per line:++| Field | Meaning |+|---|---|+| `id` | `<name>-<pull request number>` |+| `repo`, `S` | the repository and the snapshot commit the question is asked at |+| `issue_url`, `pr_url`, `merged_at` | the issue, the pull request that fixed it and when it was merged |+| `gold` | the source files the fix changed that exist at S |+| `text_sha256` | the sha256 of the question text (UTF-8) |+| `names_gold_path` | the question text names a gold file by a path of at least two parts |++The issue texts are not in the repository. `fetch_texts.py` rebuilds them from GitHub (the issue's title and+body as first filed, from its edit history, with HTML comments and empty template headings removed) and+checks each against its hash. `questions/funnel.json` counts what each selection filter removed;+`mine.py` documents the filters.++## Files++| File | What it does |+|---|---|+| `repos.json`, `snapshots.json` | the repositories, the snapshot rule and each snapshot commit S |+| `paths.py` | the file classes: source, test, docs, changelog, generated, vendored |+| `fetch_prs.sh`, `fetch_issues.sh` | read-only GitHub queries for the candidate pull requests and their issues |+| `mine.py`, `issue_text.py` | the filters and the question text |+| `checkout.py` | each repository at S |+| `index.py` | `graphicle sync` of each checkout, with its time and size |+| `tokens.py` | the token counter shared by every budgeted arm, repository sizes, truncation |+| `pack_arm.py` | the pack arm's context (`graphicle pack`, in the standard or the cache layout) |+| `agent_tools.py` | the search-only agent's tools: grep, find, list_dir, read |+| `run.py` | runs one arm against an OpenAI-compatible API (Meta's Responses API or chat completions), with the cache key, a global spend log and hard spend caps |+| `mock_server.py` | a mock OpenAI-compatible server (chat completions and responses, with prompt caching per cache key) for testing without a model |+| `test_runner.py` | end-to-end tests of the runner, the caps, the spend log and the estimate on the mock |+| `score.py` | hit@k, all-gold@5, MRR, context recall, tokens, cost; McNemar tests and bootstrap intervals |+| `recall.py` | context recall without a model, for every question and budget |+| `estimate.py` | a planned grid's tokens and cost with and without the prompt cache, before any run; the registered grids |+| `report.py` | the report's data file and page; the chart is `docs/benchmarks/whole_repo_chart.py` |+| `prices.json` | the model prices used for cost, with their date and source |+| `caps.json` | the global spending limits per provider |++## Reproduce++Python 3.12 with `tokenizers` (for an exact tokenizer) and `matplotlib` (for the chart), git, and a Graphicle+binary; `graphicle pack --tokenizer` needs a build with the `local-inference` feature. WORK is a working folder+with room for the checkouts and indexes (about 40 GB). The exact counts use the model's own `tokenizer.json`,+which is not part of this repository.++```sh+python3 checkout.py WORK+python3 fetch_texts.py --questions questions --out WORK/texts+python3 index.py --binary graphicle --work WORK+python3 tokens.py sizes --work WORK --out WORK/sizes.json [--tokenizer tokenizer.json]+python3 estimate.py --questions questions --texts WORK/texts --registered+export MODEL_API_KEY=... # or --key-file FILE; BASETEN_API_KEY for --profile baseten+python3 run.py --arm pack --budget 128K --work WORK --questions questions --texts WORK/texts \+ --out WORK/runs/pack-128K --profile meta --spend-cap 20 --graphicle graphicle [--tokenizer tokenizer.json]+python3 run.py --arm trunc --budget 128K ... # and --arm agent, --arm noctx, --arm pack-cache+python3 score.py --runs WORK/runs/* --out WORK/score.json+python3 recall.py --work WORK --questions questions --texts WORK/texts --graphicle graphicle --out WORK/recall+python3 report.py --sizes WORK/sizes.json --index-dir WORK/index --score WORK/score.json \+ --recall WORK/recall/recall-summary.json --json ../../docs/benchmarks/whole-repo.json \+ --md ../../docs/benchmarks/whole-repo.md+```++`--profile meta` (the default) sends to `https://api.meta.ai/v1` with the Responses API and `muse-spark-1.3`;+`--profile baseten` sends to Baseten's chat completions with Muse Spark Open. Each call carries a cache key+(repository, snapshot, arm, budget and the hash of the shared prefix, never question text), sent as+`prompt_cache_key` with `prompt_cache_retention: "24h"` on Meta and as the `x-session-affinity` header on+Baseten. The questions of one repository run back to back, the first one alone, so the others can be served+from the cache.++Every call is appended to one spend log (`WORK/spend/spend-log.jsonl`: tokens, cached tokens, seconds, cost).+`run.py` refuses to start when the provider's logged total plus the run's estimate would pass the provider's+limit in `caps.json`, and stops before any call that could take its spending past `--spend-cap` (default $20)+or past what is left of that limit, counting what earlier runs into the same folder spent.++To test everything without a model, run `python3 test_runner.py` (it starts `mock_server.py` itself), or+start `mock_server.py` and use `--profile mock --base-url` pointing at it, with any key.diff --git a/bench/whole-repo/agent_tools.py b/bench/whole-repo/agent_tools.pynew file mode 100644index 0000000..7be2419--- /dev/null+++ b/bench/whole-repo/agent_tools.py@@ -0,0 +1,137 @@+"""The search-only agent's tools, over one checkout at S.++ grep(pattern, path_glob?) extended regular expression over the tracked text files; at most 100 lines+ find(name_glob) tracked paths whose path or file name matches the glob; at most 200+ list_dir(path) the folders (with a trailing /) and files directly in a folder+ read(path, start, end) lines start..end (1-based, inclusive), at most 400 per call, numbered++Every result is plain text. Long lines are cut at 300 characters. The tools record which files+were read, for the agent's context recall.+"""+import fnmatch+import os+import subprocess++MAX_GREP, MAX_FIND, MAX_LIST, MAX_READ, MAX_LINE = 100, 200, 1000, 400, 300++SCHEMAS = [+ ("grep", "Search the repository's files with an extended regular expression (git grep -E). "+ "Returns at most 100 matching lines as path:line:text.",+ {"type": "object", "properties": {+ "pattern": {"type": "string", "description": "Extended regular expression"},+ "path_glob": {"type": "string", "description": "Optional glob limiting the files, for example *.go or pkg/**"}},+ "required": ["pattern"]}),+ ("find", "Find files whose path or file name matches a glob, for example *scheduler*.go. At most 200 paths.",+ {"type": "object", "properties": {"name_glob": {"type": "string"}}, "required": ["name_glob"]}),+ ("list_dir", "List the folders and files directly inside a folder of the repository ('' is the root).",+ {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}),+ ("read", "Read lines start to end (1-based, inclusive) of a file, at most 400 lines per call.",+ {"type": "object", "properties": {"path": {"type": "string"}, "start": {"type": "integer"},+ "end": {"type": "integer"}}, "required": ["path", "start", "end"]}),+]+++def chat_tools():+ return [{"type": "function", "function": {"name": n, "description": d, "parameters": p}} for n, d, p in SCHEMAS]+++def responses_tools():+ return [{"type": "function", "name": n, "description": d, "parameters": p} for n, d, p in SCHEMAS]+++def cut(line):+ return line if len(line) <= MAX_LINE else line[:MAX_LINE] + " [cut]"+++class RepoTools:+ def __init__(self, src, files=None):+ self.src = src+ if files is None:+ out = subprocess.run(["git", "ls-files", "-z"], cwd=src, capture_output=True, text=True, check=True).stdout+ files = sorted(p for p in out.split("\0") if p)+ self.files = files+ self.file_set = set(self.files)+ self.read_paths = []++ def norm(self, path):+ p = (path or "").strip()+ while p.startswith("./"):+ p = p[2:]+ p = p.strip("/")+ return "" if p == "." else p++ def grep(self, pattern, path_glob=None):+ cmd = ["git", "grep", "-n", "-I", "-E", "--no-color", "-e", pattern]+ if path_glob:+ cmd += ["--", path_glob]+ try:+ r = subprocess.run(cmd, cwd=self.src, capture_output=True, text=True, errors="replace", timeout=120)+ except subprocess.TimeoutExpired:+ return "error: the search took too long; narrow the pattern or the path_glob"+ if r.returncode not in (0, 1):+ return "error: " + (r.stderr.strip().splitlines() or ["bad pattern"])[0][:300]+ lines = r.stdout.splitlines()+ if not lines:+ return "no matches"+ more = f"\n[{len(lines) - MAX_GREP} more matching lines not shown]" if len(lines) > MAX_GREP else ""+ return "\n".join(cut(l) for l in lines[:MAX_GREP]) + more++ def find(self, name_glob):+ g = name_glob or "*"+ hits = [p for p in self.files if fnmatch.fnmatchcase(p, g) or fnmatch.fnmatchcase(os.path.basename(p), g)]+ if not hits:+ return "no matching files"+ more = f"\n[{len(hits) - MAX_FIND} more paths not shown]" if len(hits) > MAX_FIND else ""+ return "\n".join(hits[:MAX_FIND]) + more++ def list_dir(self, path):+ d = self.norm(path)+ prefix = d + "/" if d else ""+ entries = set()+ for p in self.files:+ if p.startswith(prefix):+ rest = p[len(prefix):]+ entries.add(rest.split("/", 1)[0] + ("/" if "/" in rest else ""))+ if not entries:+ return f"error: no folder {d!r}"+ es = sorted(entries)+ more = f"\n[{len(es) - MAX_LIST} more entries not shown]" if len(es) > MAX_LIST else ""+ return "\n".join(es[:MAX_LIST]) + more++ def read(self, path, start, end):+ p = self.norm(path)+ if p not in self.file_set:+ return f"error: no file {p!r}"+ full = os.path.join(self.src, p)+ if os.path.islink(full) or not os.path.isfile(full):+ return f"error: {p!r} is not a regular file"+ try:+ start, end = max(1, int(start)), int(end)+ except (TypeError, ValueError):+ return "error: start and end must be integers"+ end = min(end, start + MAX_READ - 1)+ with open(full, "rb") as f:+ data = f.read()+ if b"\0" in data[:8192]:+ return f"error: {p!r} is a binary file"+ lines = data.decode("utf-8", errors="replace").splitlines()+ if p not in self.read_paths:+ self.read_paths.append(p)+ if start > len(lines):+ return f"[{p} has {len(lines)} lines]"+ body = "\n".join(f"{i}: {cut(lines[i - 1])}" for i in range(start, min(end, len(lines)) + 1))+ return f"[{p}, lines {start}-{min(end, len(lines))} of {len(lines)}]\n{body}"++ def call(self, name, args):+ try:+ if name == "grep":+ return self.grep(str(args.get("pattern", "")), args.get("path_glob") or None)+ if name == "find":+ return self.find(str(args.get("name_glob", "")))+ if name == "list_dir":+ return self.list_dir(str(args.get("path", "")))+ if name == "read":+ return self.read(str(args.get("path", "")), args.get("start", 1), args.get("end", MAX_READ))+ return f"error: unknown tool {name!r}"+ except Exception as e: # a tool error goes back to the model as text+ return f"error: {type(e).__name__}: {str(e)[:200]}"diff --git a/bench/whole-repo/caps.json b/bench/whole-repo/caps.jsonnew file mode 100644index 0000000..c95e1cc--- /dev/null+++ b/bench/whole-repo/caps.json@@ -0,0 +1,5 @@+{+ "unit": "US dollars, at the prices in prices.json",+ "note": "Global spend caps per provider for the benchmark's model answers, summed over every run in the global spend log. A run refuses to start when the logged total plus its own estimate would pass its provider's cap, and stops when a call's worst case would pass it.",+ "usd": {"meta": 45.0, "baseten": 100.0}+}diff --git a/bench/whole-repo/checkout.py b/bench/whole-repo/checkout.pynew file mode 100644index 0000000..8918055--- /dev/null+++ b/bench/whole-repo/checkout.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""Pin each repository at its snapshot commit S and check S out.++usage: checkout.py WORKDIR [NAME ...]++For each repository in repos.json (or only the NAMEs given):+1. a commit-only clone of the default branch (git --filter=tree:0) in WORKDIR/hist/NAME.git;+2. S: the commit recorded in snapshots.json, else the last commit on the default branch's+ first-parent line whose committer time is at or before repos.json's snapshot_cutoff;+3. a depth-1 fetch of S into WORKDIR/src/NAME, checked out detached.++Writes WORKDIR/snapshots/NAME.json. A resolved S that snapshots.json does not record yet is+printed, so it can be added there; a recorded S is checked against the history.+Every step is skipped when its result is already there, so the script can be run again.+"""+import datetime+import json+import os+import subprocess+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+++def git(*args, cwd=None, capture=True):+ r = subprocess.run(["git", *args], cwd=cwd, text=True,+ stdout=subprocess.PIPE if capture else None, stderr=subprocess.PIPE)+ if r.returncode != 0:+ raise SystemExit(f"git {' '.join(args)} failed: {r.stderr.strip()[:400]}")+ return (r.stdout or "").strip()+++def main():+ if len(sys.argv) < 2:+ raise SystemExit(__doc__)+ work = os.path.abspath(sys.argv[1])+ only = set(sys.argv[2:])+ cfg = json.load(open(os.path.join(HERE, "repos.json")))+ rec_path = os.path.join(HERE, "snapshots.json")+ recorded = json.load(open(rec_path)) if os.path.exists(rec_path) else {}+ os.makedirs(os.path.join(work, "snapshots"), exist_ok=True)+ os.makedirs(os.path.join(work, "hist"), exist_ok=True)+ os.makedirs(os.path.join(work, "src"), exist_ok=True)+ for r in cfg["repos"]:+ name, slug, branch = r["name"], r["slug"], r["branch"]+ if only and name not in only:+ continue+ url = f"https://github.com/{slug}.git"+ hist = os.path.join(work, "hist", name + ".git")+ if not os.path.exists(os.path.join(hist, "HEAD")):+ git("clone", "-q", "--bare", "--filter=tree:0", "--single-branch", "--branch", branch, url, hist)+ resolved = git("rev-list", "-1", "--first-parent", f"--before={cfg['snapshot_cutoff']}", branch, cwd=hist)+ s = recorded.get(name, {}).get("sha") or resolved+ if s != resolved:+ print(f"{name}: recorded S {s[:12]} differs from the resolved {resolved[:12]}; keeping the recorded one",+ flush=True)+ ct = int(git("show", "-s", "--format=%ct", s, cwd=hist))+ committed = datetime.datetime.fromtimestamp(ct, datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ src = os.path.join(work, "src", name)+ head = ""+ if os.path.exists(os.path.join(src, ".git")):+ try:+ head = git("rev-parse", "HEAD", cwd=src)+ except SystemExit:+ head = ""+ if head != s:+ os.makedirs(src, exist_ok=True)+ if not os.path.exists(os.path.join(src, ".git")):+ git("init", "-q", src)+ git("remote", "add", "origin", url, cwd=src)+ git("fetch", "-q", "--depth", "1", "origin", s, cwd=src)+ git("checkout", "-q", "--detach", "FETCH_HEAD", cwd=src)+ files = len(git("ls-files", "-z", cwd=src).split("\0")) - 1+ row = {"slug": slug, "branch": branch, "sha": s, "committed": committed, "tracked_files": files,+ "resolved": resolved}+ if name not in recorded:+ print(f"{name}: S {s} committed {committed} (not yet in snapshots.json)", flush=True)+ else:+ print(f"{name}: S {s[:12]} committed {committed}, {files} tracked files", flush=True)+ with open(os.path.join(work, "snapshots", name + ".json"), "w") as f:+ json.dump(row, f, indent=1, sort_keys=True)+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/estimate.py b/bench/whole-repo/estimate.pynew file mode 100644index 0000000..60e6c80--- /dev/null+++ b/bench/whole-repo/estimate.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""Tokens and cost of a planned grid, printed before any run.++usage: estimate.py --questions DIR [--texts DIR] [--grid GRID] [--model muse-spark-1.3] [--registered]+ [--prices prices.json] [--caps caps.json] [--out-tokens 4000] [--agent-turns 15]+ [--agent-turn-tokens 2500] [--agent-out-per-turn 800] [--agent-rows ROWS.jsonl ...]+ [--standard-prefix 0]++GRID is a comma-separated list of ARM[@BUDGET]:REPOS[:N]:+ ARM noctx, pack, pack-cache (prefix share 0.9), pack-cacheF (prefix share F, such as+ pack-cache0.95), pack-stable (prefix share 1.0), trunc or agent+ REPOS a '+'-joined list of names, or held-out, development or all+ N the first N questions of each repository, in file order (default: all of them)+The default grid is the registered grid G1 (REGISTERED). --registered prints every registered grid,+each priced with its own model, and adds them up in their order against their provider's global cap+(caps.json: Meta $45, Baseten $100).++Per call, a pack or truncation arm sends its whole budget (an upper bound) plus the prompt and the+issue; no context sends the prompt and the issue; every call returns --out-tokens (reasoning+included). The search-only agent: each turn sends everything so far, so a question of T turns sends+T x (prompt + issue) + turn_tokens x T(T+1)/2 tokens in and T x out_per_turn out; --agent-rows+replaces these assumptions with the means of measured agent rows (run.py's rows.jsonl).++Caching. The runner sends the questions of one (repository, arm, budget) group back to back, the+first one alone, under one prompt_cache_key, so every later question can read the group's shared+prefix from the cache:+ trunc the whole dump (the same text for every question)+ pack-stable the whole pack (only the question after it is new)+ pack-cache[F] F x B, the pack's question-independent prefix+ pack --standard-prefix tokens (the standard layout's question-independent head; 0 here)+ noctx nothing+ agent within one question, each turn's earlier turns+The "cached" columns bill the first question of a group at the input price and every later one at+the cached-input price on the shared prefix; "uncached" is the worst case, with no cache hit at all.+Whether a call is served from the cache is up to the API, so both are shown.+Issue tokens are UTF-8 bytes / 4 when --texts is given, else 1,000 per question.+"""+import argparse+import json+import math+import os+import re+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from run import BUDGETS, PROMPT # noqa: E402++# The pre-registered hosted grids (bench-results PREREG-2026-10-26.md), in their priority order.+REGISTERED = [+ ("G1", "Meta, grid C: the 128K arms on the 90 held-out questions", "muse-spark-1.3",+ "noctx:held-out,trunc@128K:held-out,pack@128K:held-out,agent:held-out"),+ ("G2", "Meta, the cache-aware pack at 1M on the first 10 held-out questions of each repository",+ "muse-spark-1.3", "pack-cache@1M:held-out:10"),+ ("G3", "Baseten, Muse Spark Open: the 1M answer arms on the held-out questions",+ "meta-models/muse-spark-open",+ "noctx:held-out,trunc@1M:held-out,pack-cache@1M:held-out,pack@1M:held-out:10"),+ ("G4", "Meta, a Muse Wonder subset, only if money is left", "muse-wonder-1.0", "pack-cache@128K:held-out:10"),+]+DEFAULT_GRID = REGISTERED[0][3]+ARM_RX = re.compile(r"pack-cache(?P<share>0?\.\d+|1(?:\.0+)?)?")+++def arm_parts(arm):+ """(kind, prefix share): ("pack", None) for the standard pack, ("pack", 0.9) for pack-cache, ..."""+ m = ARM_RX.fullmatch(arm)+ if m:+ return "pack", float(m.group("share")) if m.group("share") else 0.9+ if arm == "pack-stable":+ return "pack", 1.0+ if arm in ("pack", "trunc", "noctx", "agent"):+ return arm, None+ raise SystemExit(f"unknown arm {arm!r}")+++def shared_prefix(arm, budget_tokens, standard_prefix=0):+ """Tokens of the context that every question of a group sends unchanged."""+ kind, share = arm_parts(arm)+ if kind == "trunc":+ return budget_tokens+ if kind == "pack":+ return share * budget_tokens if share is not None else standard_prefix+ return 0+++def cost_of(price, tin, tcached, tout):+ return ((tin - tcached) * price["input"] + tcached * price.get("cached_input", price["input"])+ + tout * price["output"]) / 1e6+++def group_tokens(arm, budget, q, base, out_tokens, agent, standard_prefix=0):+ """(calls, tokens in, tokens cached when the cache works, tokens out) of one group of q questions.+ base is the prompt template plus the mean issue; agent holds turns, turn_tokens, out_per_turn and,+ when measured, tokens_in, tokens_cached and tokens_out per question."""+ if q <= 0:+ return 0, 0, 0, 0+ kind, _share = arm_parts(arm)+ if kind == "agent":+ if agent.get("measured"):+ m = agent["measured"]+ return q * m["turns"], q * m["tokens_in"], q * m["tokens_cached"], q * m["tokens_out"]+ t, tt = agent["turns"], agent["turn_tokens"]+ qin = t * base + tt * t * (t + 1) / 2+ return q * t, q * qin, q * (qin - base - tt * t), q * t * agent["out_per_turn"]+ if kind == "noctx":+ return q, q * base, 0, q * out_tokens+ b = BUDGETS[budget]+ return q, q * (b + base), (q - 1) * shared_prefix(arm, b, standard_prefix), q * out_tokens+++def load_questions(questions, texts, cfg):+ nq, qtok = {}, {}+ for r in cfg["repos"]:+ p = os.path.join(questions, f"questions-{r['name']}.jsonl")+ nq[r["name"]] = sum(1 for l in open(p) if l.strip()) if os.path.exists(p) else 0+ toks = []+ if texts and os.path.exists(os.path.join(texts, f"texts-{r['name']}.jsonl")):+ toks = [math.ceil(len(json.loads(l)["text"].encode()) / 4)+ for l in open(os.path.join(texts, f"texts-{r['name']}.jsonl"))]+ qtok[r["name"]] = (sum(toks) / len(toks)) if toks else 1000.0+ return nq, qtok+++def template_tokens():+ return math.ceil(len(PROMPT.encode()) / 4) + 30+++def repo_names(spec, roles):+ if spec in ("held-out", "development"):+ return [n for n, r in roles.items() if r == spec]+ if spec == "all":+ return list(roles)+ return spec.split("+")+++def grid_rows(grid, nq, qtok, roles, price, out_tokens, agent, standard_prefix=0):+ """One row per grid item: label, repos, calls, tokens in, cached, out, cost uncached, cost cached."""+ rows = []+ for item in grid.split(","):+ parts = item.split(":")+ arm_b, spec = parts[0], parts[1]+ limit = int(parts[2]) if len(parts) > 2 else 0+ arm, _, budget = arm_b.partition("@")+ names = repo_names(spec, roles)+ calls = tin = tcached = tout = 0.0+ for n in names:+ q = min(nq[n], limit) if limit else nq[n]+ c, i, ca, o = group_tokens(arm, budget, q, template_tokens() + qtok[n], out_tokens, agent,+ standard_prefix)+ calls, tin, tcached, tout = calls + c, tin + i, tcached + ca, tout + o+ rows.append({"item": arm_b + (f" (first {limit})" if limit else ""), "repos": "+".join(names),+ "calls": calls, "tokens_in": tin, "tokens_cached": tcached, "tokens_out": tout,+ "uncached": cost_of(price, tin, 0, tout), "cached": cost_of(price, tin, tcached, tout)})+ return rows+++def run_estimate(a_questions, a_texts, arm, budget, repos, limit, model, prices, out_tokens=4000, agent=None,+ standard_prefix=0):+ """The cost of one run.py run (cached and uncached), for its refusal to start past the global cap."""+ cfg = json.load(open(os.path.join(HERE, "repos.json")))+ nq, qtok = load_questions(a_questions, a_texts, cfg)+ names = repos or [r["name"] for r in cfg["repos"] if nq.get(r["name"])]+ agent = agent or {"turns": 15, "turn_tokens": 2500, "out_per_turn": 800}+ tot = {"uncached": 0.0, "cached": 0.0}+ for n in names:+ q = min(nq[n], limit) if limit else nq[n]+ c, i, ca, o = group_tokens(arm, budget, q, template_tokens() + qtok[n], out_tokens, agent, standard_prefix)+ tot["uncached"] += cost_of(prices["models"][model], i, 0, o)+ tot["cached"] += cost_of(prices["models"][model], i, ca, o)+ return tot+++def print_rows(rows):+ print(f"{'arm':22s} {'repos':28s} {'calls':>6s} {'tokens in':>13s} {'cached in':>13s} {'tokens out':>11s} "+ f"{'uncached':>9s} {'cached':>8s}")+ for r in rows:+ print(f"{r['item']:22s} {r['repos']:28s} {r['calls']:6.0f} {r['tokens_in']:13,.0f} {r['tokens_cached']:13,.0f} "+ f"{r['tokens_out']:11,.0f} {r['uncached']:9.2f} {r['cached']:8.2f}")+ tu, tc = sum(r["uncached"] for r in rows), sum(r["cached"] for r in rows)+ print(f"{'total':22s} {'':28s} {'':6s} {'':13s} {'':13s} {'':11s} {tu:9.2f} {tc:8.2f}")+ return tu, tc+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--questions", required=True)+ ap.add_argument("--texts")+ ap.add_argument("--grid", default=DEFAULT_GRID)+ ap.add_argument("--model", default="muse-spark-1.3")+ ap.add_argument("--registered", action="store_true", help="every registered grid against the global caps")+ ap.add_argument("--prices", default=os.path.join(HERE, "prices.json"))+ ap.add_argument("--caps", default=os.path.join(HERE, "caps.json"))+ ap.add_argument("--out-tokens", type=int, default=4000)+ ap.add_argument("--agent-turns", type=float, default=15)+ ap.add_argument("--agent-turn-tokens", type=float, default=2500)+ ap.add_argument("--agent-out-per-turn", type=float, default=800)+ ap.add_argument("--agent-rows", nargs="*")+ ap.add_argument("--standard-prefix", type=float, default=0,+ help="question-independent tokens at the head of a standard pack")+ a = ap.parse_args()+ cfg = json.load(open(os.path.join(HERE, "repos.json")))+ roles = {r["name"]: r["role"] for r in cfg["repos"]}+ prices = json.load(open(a.prices))+ caps = json.load(open(a.caps))["usd"]+ nq, qtok = load_questions(a.questions, a.texts, cfg)+ agent = {"turns": a.agent_turns, "turn_tokens": a.agent_turn_tokens, "out_per_turn": a.agent_out_per_turn}+ if a.agent_rows:+ rows = [json.loads(l) for p in a.agent_rows for l in open(p) if l.strip()]+ rows = [r for r in rows if not r.get("error")]+ if rows:+ agent["measured"] = {k: sum(r[k] for r in rows) / len(rows)+ for k in ("turns", "tokens_in", "tokens_cached", "tokens_out")}+ agent["measured"]["n"] = len(rows)+ print(f"prices: prices.json ({prices['date']}); questions: "+ + ", ".join(f"{k} {v} (issue ~{qtok[k]:,.0f} tokens)" for k, v in nq.items()))+ m = agent.get("measured")+ print(f"agent: measured means over {m['n']} rows: {m['turns']:.1f} turns, {m['tokens_in']:,.0f} in "+ f"({m['tokens_cached']:,.0f} cached), {m['tokens_out']:,.0f} out" if m else+ f"agent: assumed {a.agent_turns:g} turns, {a.agent_turn_tokens:,.0f} tokens added per turn, "+ f"{a.agent_out_per_turn:,.0f} out per turn")+ print(f"every call: {a.out_tokens:,} tokens out (reasoning included); budgets are upper bounds")+ grids = ([(g, d, model, grid) for g, d, model, grid in REGISTERED] if a.registered+ else [("grid", "", a.model, a.grid)])+ spent = {}+ for name, desc, model, grid in grids:+ p = prices["models"][model]+ prov = p.get("provider", "?")+ print(f"\n== {name}: {desc}" if desc else f"\n== {name}")+ print(f"model {model} ({prov}): ${p['input']}/M in, ${p.get('cached_input', p['input'])}/M cached in, "+ f"${p['output']}/M out")+ tu, tc = print_rows(grid_rows(grid, nq, qtok, roles, p, a.out_tokens, agent, a.standard_prefix))+ if prov in caps:+ before = spent.get(prov, (0.0, 0.0))+ spent[prov] = (before[0] + tu, before[1] + tc)+ cap = caps[prov]+ print(f"{prov} cap ${cap:.0f}: this grid ${tc:.2f} cached (${tu:.2f} uncached); with the grids before it "+ f"${spent[prov][1]:.2f} cached ({'fits' if spent[prov][1] <= cap else 'OVER'}), "+ f"${spent[prov][0]:.2f} uncached ({'fits' if spent[prov][0] <= cap else 'OVER'})")+ if a.registered:+ print("\nglobal caps (caps.json): " + ", ".join(f"{k} ${v:.0f}" for k, v in caps.items()))+ for prov, (tu, tc) in spent.items():+ print(f"{prov}: all registered grids ${tc:.2f} cached, ${tu:.2f} uncached, cap ${caps[prov]:.0f}")+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/fetch_issues.sh b/bench/whole-repo/fetch_issues.shnew file mode 100644index 0000000..36630bf--- /dev/null+++ b/bench/whole-repo/fetch_issues.sh@@ -0,0 +1,49 @@+#!/usr/bin/env bash+# Fetch the linked issues that mine.py asks for, with their edit history and title changes.+#+# bash fetch_issues.sh NEEDDIR OUTDIR+#+# NEEDDIR holds issues-needed-<name>.txt (one issue number per line, written by `mine.py check`).+# Writes OUTDIR/issues-<name>-<batch>.json, 20 issues per GraphQL call. Read-only calls through the+# GitHub CLI. The edit history gives the body as first filed (issue_text.py).+set -euo pipefail+NEED=${1:?usage: fetch_issues.sh NEEDDIR OUTDIR}+OUT=${2:?usage: fetch_issues.sh NEEDDIR OUTDIR}+mkdir -p "$OUT"+FIELDS='__typename+ ... on Issue {+ number url createdAt closedAt title body lastEditedAt+ userContentEdits(first: 100) { totalCount nodes { createdAt editedAt deletedAt diff } }+ timelineItems(itemTypes: [RENAMED_TITLE_EVENT], first: 50) {+ nodes { ... on RenamedTitleEvent { createdAt previousTitle currentTitle } }+ }+ }'+for pair in kubernetes:kubernetes/kubernetes home-assistant:home-assistant/core pytorch:pytorch/pytorch \+ vscode:microsoft/vscode elasticsearch:elastic/elasticsearch angular:angular/angular \+ keycloak:keycloak/keycloak godot:godotengine/godot; do+ name=${pair%%:*}; slug=${pair#*:}; owner=${slug%%/*}; repo=${slug#*/}+ list="$NEED/issues-needed-$name.txt"+ [ -s "$list" ] || continue+ batch=0; nums=()+ while read -r n || [ -n "$n" ]; do+ [ -n "$n" ] && nums+=("$n")+ if [ ${#nums[@]} -eq 20 ]; then+ batch=$((batch + 1)); f=$(printf '%s/issues-%s-%03d.json' "$OUT" "$name" "$batch")+ if [ ! -s "$f" ]; then+ q="query { repository(owner: \"$owner\", name: \"$repo\") {"+ for m in "${nums[@]}"; do q+=" i$m: issueOrPullRequest(number: $m) { $FIELDS }"; done+ gh api graphql -f query="$q } }" > "$f.part" && mv "$f.part" "$f"+ fi+ nums=()+ fi+ done < "$list"+ if [ ${#nums[@]} -gt 0 ]; then+ batch=$((batch + 1)); f=$(printf '%s/issues-%s-%03d.json' "$OUT" "$name" "$batch")+ if [ ! -s "$f" ]; then+ q="query { repository(owner: \"$owner\", name: \"$repo\") {"+ for m in "${nums[@]}"; do q+=" i$m: issueOrPullRequest(number: $m) { $FIELDS }"; done+ gh api graphql -f query="$q } }" > "$f.part" && mv "$f.part" "$f"+ fi+ fi+ echo "$name: $batch batches"+donediff --git a/bench/whole-repo/fetch_prs.sh b/bench/whole-repo/fetch_prs.shnew file mode 100644index 0000000..e3f7380--- /dev/null+++ b/bench/whole-repo/fetch_prs.sh@@ -0,0 +1,56 @@+#!/usr/bin/env bash+# Fetch the candidate pull requests of the benchmark's repositories from GitHub's GraphQL API.+#+# bash fetch_prs.sh OUTDIR [NAME ...]+#+# With NAMEs, only those repositories are fetched.+# Needs the GitHub CLI, logged in (read-only calls). Writes OUTDIR/prs-<name>[-<part>].json: the raw+# search pages, concatenated as gh prints them. mine.py reads them.+#+# Candidates: pull requests merged into the default branch from the snapshot cutoff to the end of+# the window (repos.json) that GitHub links to an issue they close. PyTorch lands most pull requests+# with its merge bot, which closes them with the label "Merged" instead of merging them, and its+# stacked pull requests do not target the default branch, so GitHub records no closing link for+# them: for PyTorch every landed pull request is fetched, with its body, and mine.py reads the+# closing keywords (Fixes, Closes, Resolves #N) itself.+set -euo pipefail+OUT=${1:?usage: fetch_prs.sh OUTDIR [NAME ...]}+shift+ONLY=" $* "+mkdir -p "$OUT"+WIN='2026-09-14T00:00:00Z..2026-10-25T23:59:59Z'+QUERY='query($q: String!, $endCursor: String) {+ search(query: $q, type: ISSUE, first: 25, after: $endCursor) {+ issueCount+ pageInfo { hasNextPage endCursor }+ nodes {+ ... on PullRequest {+ number url title createdAt mergedAt closedAt merged state+ baseRefName baseRefOid headRefOid+ mergeCommit { oid }+ labels(first: 30) { nodes { name } }+ changedFiles+ files(first: 100) { totalCount nodes { path changeType additions deletions } }+ body+ closingIssuesReferences(first: 10) { nodes { number repository { nameWithOwner } } }+ }+ }+ }+}'+fetch() { # name part search-query+ if [ "$ONLY" != " " ] && [[ "$ONLY" != *" $1 "* ]]; then return; fi+ local f="$OUT/prs-$1$2.json"+ if [ -s "$f" ]; then echo "$f exists"; return; fi+ gh api graphql --paginate -f query="$QUERY" -f q="$3" > "$f.part"+ mv "$f.part" "$f"+ echo "$f: $(wc -c < "$f") bytes"+}+fetch kubernetes "" "repo:kubernetes/kubernetes is:pr is:merged base:master merged:$WIN linked:issue"+fetch home-assistant "" "repo:home-assistant/core is:pr is:merged base:dev merged:$WIN linked:issue"+fetch vscode "" "repo:microsoft/vscode is:pr is:merged base:main merged:$WIN linked:issue"+fetch elasticsearch "" "repo:elastic/elasticsearch is:pr is:merged base:main merged:$WIN linked:issue"+fetch pytorch "-landed" "repo:pytorch/pytorch is:pr is:closed label:Merged closed:$WIN"+fetch pytorch "-merged" "repo:pytorch/pytorch is:pr is:merged base:main merged:$WIN"+fetch angular "" "repo:angular/angular is:pr is:merged base:main merged:$WIN linked:issue"+fetch keycloak "" "repo:keycloak/keycloak is:pr is:merged base:main merged:$WIN linked:issue"+fetch godot "" "repo:godotengine/godot is:pr is:merged base:master merged:$WIN linked:issue"diff --git a/bench/whole-repo/fetch_texts.py b/bench/whole-repo/fetch_texts.pynew file mode 100644index 0000000..e6bc956--- /dev/null+++ b/bench/whole-repo/fetch_texts.py@@ -0,0 +1,110 @@+#!/usr/bin/env python3+"""Rebuild the question texts from GitHub and check them against the published hashes.++usage: fetch_texts.py --questions DIR --out DIR [--raw DIR]++The question sets publish each issue's URL and the sha256 of the question text, not the text. This+script fetches each issue with its edit history and title changes (the GraphQL query of+fetch_issues.sh), rebuilds the text with issue_text.py and writes OUT/texts-<name>.jsonl. It prints+how many texts match their hash; a mismatch means the issue's history changed on GitHub (for+example a deleted revision).++Without --raw it calls GitHub's GraphQL API: through the GitHub CLI when `gh` is installed and+logged in, else with the token in GITHUB_TOKEN. With --raw it reads pages that fetch_issues.sh+saved instead.+"""+import argparse+import glob+import json+import os+import subprocess+import sys+import urllib.request++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from issue_text import question_text, sha256 # noqa: E402++FIELDS = """__typename+ ... on Issue {+ number url createdAt closedAt title body lastEditedAt+ userContentEdits(first: 100) { totalCount nodes { createdAt editedAt deletedAt diff } }+ timelineItems(itemTypes: [RENAMED_TITLE_EVENT], first: 50) {+ nodes { ... on RenamedTitleEvent { createdAt previousTitle currentTitle } }+ }+ }"""+++def graphql(query):+ try:+ r = subprocess.run(["gh", "api", "graphql", "-f", "query=" + query], capture_output=True, text=True)+ if r.returncode == 0:+ return json.loads(r.stdout)+ except FileNotFoundError:+ pass+ token = os.environ.get("GITHUB_TOKEN")+ if not token:+ raise SystemExit("needs the GitHub CLI (logged in) or GITHUB_TOKEN")+ req = urllib.request.Request("https://api.github.com/graphql", data=json.dumps({"query": query}).encode(),+ headers={"Authorization": "Bearer " + token, "Content-Type": "application/json"})+ with urllib.request.urlopen(req, timeout=120) as resp:+ return json.loads(resp.read())+++def read_raw(raw, name):+ from mine import read_pages+ out = {}+ for path in sorted(glob.glob(os.path.join(raw, f"issues-{name}-*.json"))):+ for page in read_pages(path):+ for _k, v in ((page.get("data") or {}).get("repository") or {}).items():+ if v and v.get("__typename") == "Issue":+ out[v["url"]] = v+ return out+++def fetch(slug, numbers):+ owner, repo = slug.split("/")+ out = {}+ for i in range(0, len(numbers), 20):+ part = numbers[i:i + 20]+ q = f'query {{ repository(owner: "{owner}", name: "{repo}") {{' + "".join(+ f" i{n}: issueOrPullRequest(number: {n}) {{ {FIELDS} }}" for n in part) + " } }"+ data = graphql(q)+ for _k, v in ((data.get("data") or {}).get("repository") or {}).items():+ if v and v.get("__typename") == "Issue":+ out[v["url"]] = v+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--questions", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--raw")+ a = ap.parse_args()+ os.makedirs(a.out, exist_ok=True)+ total = ok = 0+ for path in sorted(glob.glob(os.path.join(a.questions, "questions-*.jsonl"))):+ name = os.path.basename(path)[len("questions-"):-len(".jsonl")]+ qs = [json.loads(l) for l in open(path) if l.strip()]+ if a.raw:+ issues = read_raw(a.raw, name)+ else:+ issues = fetch(qs[0]["repo"], sorted({int(q["issue_url"].rsplit("/", 1)[1]) for q in qs}))+ good = 0+ with open(os.path.join(a.out, f"texts-{name}.jsonl"), "w") as f:+ for q in qs:+ iss = issues.get(q["issue_url"])+ text, notes = question_text(iss) if iss else ("", {"missing": True})+ match = bool(iss) and sha256(text) == q["text_sha256"]+ good += match+ f.write(json.dumps({"id": q["id"], "text": text, "notes": notes, "hash_ok": match}, sort_keys=True) + "\n")+ total += len(qs)+ ok += good+ print(f"{name}: {good}/{len(qs)} texts match their hash")+ print(f"all: {ok}/{total}")+ sys.exit(0 if ok == total else 1)+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/index.py b/bench/whole-repo/index.pynew file mode 100644index 0000000..a416a01--- /dev/null+++ b/bench/whole-repo/index.py@@ -0,0 +1,76 @@+#!/usr/bin/env python3+"""Build Graphicle's index of each checked-out repository and record its time and size.++usage: index.py --binary GRAPHICLE --work WORKDIR [NAME ...]++Runs `graphicle sync WORKDIR/src/NAME --data-dir WORKDIR/data/NAME --json` for each repository+(each in its own data folder, so the size is that repository's alone) and writes+WORKDIR/index/NAME.json: wall seconds, CPU seconds, peak memory of the sync process, the data+folder's size in bytes and the binary's version. A repository whose result file exists is skipped.+"""+import argparse+import json+import os+import resource+import subprocess+import time+++def du_bytes(path):+ total = 0+ for root, _dirs, files in os.walk(path):+ for f in files:+ try:+ total += os.lstat(os.path.join(root, f)).st_size+ except OSError:+ pass+ return total+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--binary", required=True)+ ap.add_argument("--work", required=True)+ ap.add_argument("names", nargs="*")+ a = ap.parse_args()+ work = os.path.abspath(a.work)+ names = a.names or sorted(os.listdir(os.path.join(work, "src")))+ os.makedirs(os.path.join(work, "index"), exist_ok=True)+ version = subprocess.run([a.binary, "--version"], text=True, capture_output=True).stdout.strip()+ for name in names:+ out = os.path.join(work, "index", name + ".json")+ if os.path.exists(out):+ print(f"{name}: indexed already", flush=True)+ continue+ src = os.path.join(work, "src", name)+ data = os.path.join(work, "data", name)+ os.makedirs(data, exist_ok=True)+ log = open(os.path.join(work, "index", name + ".log"), "w")+ before = resource.getrusage(resource.RUSAGE_CHILDREN)+ t0 = time.time()+ r = subprocess.run([a.binary, "sync", src, "--data-dir", data, "--json"],+ stdout=subprocess.PIPE, stderr=log, text=True)+ wall = time.time() - t0+ after = resource.getrusage(resource.RUSAGE_CHILDREN)+ log.close()+ try:+ summary = json.loads(r.stdout) if r.stdout.strip() else {}+ except json.JSONDecodeError:+ summary = {"unparsed_stdout_bytes": len(r.stdout)}+ row = {+ "name": name,+ "graphicle": version,+ "exit": r.returncode,+ "wall_seconds": round(wall, 1),+ "cpu_seconds": round((after.ru_utime - before.ru_utime) + (after.ru_stime - before.ru_stime), 1),+ "peak_rss_mib": round(after.ru_maxrss / 1024, 1),+ "data_bytes": du_bytes(data),+ "sync": summary,+ }+ with open(out if r.returncode == 0 else out + ".failed", "w") as f:+ json.dump(row, f, indent=1, sort_keys=True)+ print(f"{name}: exit {r.returncode}, {wall:.0f} s, {row['data_bytes'] / 2**20:.0f} MiB", flush=True)+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/issue_text.py b/bench/whole-repo/issue_text.pynew file mode 100644index 0000000..98efcf4--- /dev/null+++ b/bench/whole-repo/issue_text.py@@ -0,0 +1,100 @@+"""The question text of an issue: its title and body as first filed, lightly cleaned.++question_text(issue) takes the issue as GitHub's GraphQL API returns it (with userContentEdits and+RenamedTitleEvent timeline items, see fetch_issues.sh) and returns (text, notes):+- the title as filed: the previousTitle of the first rename, else the current title;+- the body as filed: the oldest revision in the edit history, else the current body;+- HTML comments removed, and template headings with nothing under them removed (a heading whose+ section holds only blank lines, GitHub's "_No response_" placeholder or other empty headings);+- everything else as written. The text is the title, a blank line, then the body.+"""+import hashlib+import re++COMMENT = re.compile(r"<!--.*?-->", re.S)+HEADING = re.compile(r"^ {0,3}(#{1,6})(\s+.*)?$")+FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")+FILLER = {"_no response_"}+++def strip_empty_headings(text):+ lines = text.split("\n")+ kind = [] # per line: ("h", level) heading, "c" content, "e" empty or filler+ fence = None+ for ln in lines:+ m = FENCE.match(ln)+ if fence is not None:+ kind.append("c")+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence):+ fence = None+ continue+ if m:+ fence = m.group(1)+ kind.append("c")+ continue+ h = HEADING.match(ln)+ if h and (h.group(2) or "").strip():+ kind.append(("h", len(h.group(1))))+ elif not ln.strip() or ln.strip().lower() in FILLER:+ kind.append("e")+ else:+ kind.append("c")+ drop = [False] * len(lines)+ for i, k in enumerate(kind):+ if not isinstance(k, tuple):+ continue+ level, j, has_content = k[1], i + 1, False+ while j < len(lines):+ kj = kind[j]+ if isinstance(kj, tuple) and kj[1] <= level:+ break+ if kj == "c":+ has_content = True+ break+ j += 1+ if not has_content:+ drop[i] = True+ j = i + 1+ while j < len(lines) and kind[j] == "e":+ drop[j] = True+ j += 1+ return "\n".join(ln for ln, d in zip(lines, drop) if not d)+++def clean_body(body):+ text = (body or "").replace("\r\n", "\n").replace("\r", "\n")+ text = COMMENT.sub("", text)+ text = strip_empty_headings(text)+ text = re.sub(r"\n{3,}", "\n\n", text)+ return text.strip()+++def original_title(issue):+ renames = [n for n in ((issue.get("timelineItems") or {}).get("nodes") or []) if n and "previousTitle" in n]+ if renames:+ renames.sort(key=lambda n: n["createdAt"])+ return renames[0]["previousTitle"], "first-title"+ return issue["title"], "current-title"+++def original_body(issue):+ edits = [e for e in ((issue.get("userContentEdits") or {}).get("nodes") or []) if e]+ if not edits:+ return issue.get("body") or "", "current-body"+ edits.sort(key=lambda e: e.get("editedAt") or e.get("createdAt"))+ first = edits[0]+ if first.get("deletedAt") or first.get("diff") is None:+ return issue.get("body") or "", "current-body (first revision deleted)"+ return first["diff"], "first-revision"+++def question_text(issue):+ title, tnote = original_title(issue)+ body, bnote = original_body(issue)+ body = clean_body(body)+ text = title.strip() + ("\n\n" + body if body else "")+ return text, {"title": tnote, "body": bnote}+++def sha256(text):+ return hashlib.sha256(text.encode("utf-8")).hexdigest()diff --git a/bench/whole-repo/mine.py b/bench/whole-repo/mine.pynew file mode 100644index 0000000..ce8afe4--- /dev/null+++ b/bench/whole-repo/mine.py@@ -0,0 +1,385 @@+#!/usr/bin/env python3+"""Build the change-localization question sets from merged pull requests.++usage:+ mine.py candidates --work WORKDIR --raw RAWDIR pull requests from fetch_prs.sh, first filters+ mine.py diffs --work WORKDIR [--jobs 4] each remaining pull request's diff from github.com+ mine.py check --work WORKDIR gold files from the diff; the diff must apply at S+ mine.py select --work WORKDIR --raw RAWDIR --out DIR issue texts (fetch_issues.sh), selection+Every command takes --repos a,b to work on those repositories only; the others' files are left as+they are (select keeps their rows in an existing funnel.json). The selection seed of a repository+depends on its place in repos.json, not on --repos.++WORKDIR holds the checkouts (checkout.py) and mine/, the intermediate files and the question texts,+which are not published. --out gets questions-<name>.jsonl and funnel.json.++The filters, in order (funnel.json counts what each one removed):+ window landed on the default branch after S and by repos.json's merged_until+ linked closes an issue of the same repository: GitHub's closing references, or a closing+ keyword in the body (close, closes, closed, fix, fixes, fixed, resolve, resolves,+ resolved, then #N or the issue's URL)+ files at most 100 changed files+ prefilter 1 to 5 changed source files by GitHub's file list (paths.py), before the diff is read+ diff the diff can be read+ gold 1 to 5 gold files: source files (paths.py) that exist at S and that the diff modifies,+ deletes or renames (new files are not gold)+ applies the diff restricted to the gold files applies to S (git apply --check)+ issue a linked issue is an issue (not a pull request) created before the pull request landed;+ the earliest such issue is the question+ duplicate the issue was not already the question of an earlier pull request+Then every pull request left is kept if there are at most `target` of them (repos.json); otherwise+`target` are drawn with random.Random(selection_seed + index of the repository). Kept questions are+listed oldest first.+"""+import argparse+import datetime+import glob+import json+import os+import random+import re+import subprocess+import sys+import tempfile+import time+import urllib.error+import urllib.request+from concurrent.futures import ThreadPoolExecutor++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from paths import classify # noqa: E402+from issue_text import question_text, sha256 # noqa: E402++CFG = json.load(open(os.path.join(HERE, "repos.json")))+SNAP = json.load(open(os.path.join(HERE, "snapshots.json")))+KEYWORD = r"(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)"+++def ts(s):+ return datetime.datetime.fromisoformat(s.replace("Z", "+00:00"))+++def read_pages(path):+ text, dec, pos, out = open(path).read(), json.JSONDecoder(), 0, []+ while True:+ while pos < len(text) and text[pos].isspace():+ pos += 1+ if pos >= len(text):+ return out+ obj, pos = dec.raw_decode(text, pos)+ out.append(obj)+++def mdir(work, *parts):+ d = os.path.join(work, "mine", *parts)+ os.makedirs(d, exist_ok=True)+ return d+++def tracked(work, name):+ out = subprocess.run(["git", "ls-files", "-z"], cwd=os.path.join(work, "src", name),+ capture_output=True, text=True, check=True).stdout+ return set(p for p in out.split("\0") if p)+++def linked_issues(repo, pr):+ owner_repo = repo["slug"]+ nums = []+ for n in (pr.get("closingIssuesReferences") or {}).get("nodes") or []:+ if n and n["repository"]["nameWithOwner"].lower() == owner_repo.lower():+ nums.append(n["number"])+ body = COMMENT_RX.sub("", pr.get("body") or "")+ rx = re.compile(r"\b" + KEYWORD + r":?\s+(?:(?:" + re.escape(owner_repo) + r")?#(\d+)|https://github\.com/"+ + re.escape(owner_repo) + r"/issues/(\d+))\b", re.I)+ for m in rx.finditer(body):+ nums.append(int(m.group(1) or m.group(2)))+ seen, out = set(), []+ for n in nums:+ if n not in seen and n != pr["number"]:+ seen.add(n)+ out.append(n)+ return out+++COMMENT_RX = re.compile(r"<!--.*?-->", re.S)+++def chosen(a):+ """The repositories of repos.json that --repos names (all of them without --repos), with their index."""+ return [(i, r) for i, r in enumerate(CFG["repos"]) if not a.repos or r["name"] in a.repos]+++def cmd_candidates(a):+ until = ts(CFG["merged_until"])+ for _ri, repo in chosen(a):+ name = repo["name"]+ s_time = ts(SNAP[name]["committed"])+ prs = {}+ for path in sorted(glob.glob(os.path.join(a.raw, f"prs-{name}*.json"))):+ for page in read_pages(path):+ for pr in page["data"]["search"]["nodes"]:+ if pr and "number" in pr:+ prs[pr["number"]] = pr+ rows = []+ for num in sorted(prs):+ pr = prs[num]+ labels = {l["name"] for l in (pr.get("labels") or {}).get("nodes") or []}+ landed = pr["mergedAt"] if pr.get("merged") else (pr["closedAt"] if "Merged" in labels else None)+ row = {"pr": num, "url": pr["url"], "landed_at": landed, "created_at": pr["createdAt"],+ "base": pr["baseRefName"], "issues": linked_issues(repo, pr), "drop": None}+ base_ok = pr["baseRefName"] == repo["branch"] or (name == "pytorch" and "Merged" in labels+ and re.match(r"^gh/[^/]+/\d+/base$", pr["baseRefName"]))+ files = pr.get("files") or {}+ nsrc = sum(1 for f in files.get("nodes") or []+ if f["changeType"] != "ADDED" and classify(name, f["path"]) == "source")+ if not landed or not base_ok or not (s_time < ts(landed) <= until):+ row["drop"] = "window"+ elif not row["issues"]:+ row["drop"] = "linked"+ elif (files.get("totalCount") or 0) > 100:+ row["drop"] = "files"+ elif not 1 <= nsrc <= 5:+ row["drop"] = "prefilter"+ rows.append(row)+ with open(os.path.join(mdir(a.work), f"candidates-{name}.json"), "w") as f:+ json.dump(rows, f, indent=0)+ left = sum(1 for r in rows if not r["drop"])+ print(f"{name}: {len(rows)} pull requests, {left} need their diff", flush=True)+++def fetch_diff(slug, num, dest):+ if os.path.exists(dest):+ return "cached"+ url = f"https://github.com/{slug}/pull/{num}.diff"+ for attempt in range(6):+ try:+ req = urllib.request.Request(url, headers={"User-Agent": "graphicle-bench-whole-repo"})+ with urllib.request.urlopen(req, timeout=60) as r:+ data = r.read()+ if data and not data.startswith(b"diff --git"):+ return "not-a-diff"+ with open(dest + ".part", "wb") as f:+ f.write(data)+ os.replace(dest + ".part", dest)+ return "ok"+ except urllib.error.HTTPError as e:+ if e.code in (429, 500, 502, 503, 504):+ time.sleep(20 * (attempt + 1))+ continue+ return f"http-{e.code}"+ except (urllib.error.URLError, TimeoutError, ConnectionError):+ time.sleep(10 * (attempt + 1))+ return "failed"+++def cmd_diffs(a):+ for _ri, repo in chosen(a):+ name = repo["name"]+ rows = json.load(open(os.path.join(mdir(a.work), f"candidates-{name}.json")))+ d = mdir(a.work, "diffs", name)+ todo = [r["pr"] for r in rows if not r["drop"]]+ with ThreadPoolExecutor(a.jobs) as ex:+ res = list(ex.map(lambda n: fetch_diff(repo["slug"], n, os.path.join(d, f"{n}.diff")), todo))+ counts = {}+ for x in res:+ counts[x] = counts.get(x, 0) + 1+ with open(os.path.join(d, "fetch-status.json"), "w") as f:+ json.dump(dict(zip(map(str, todo), res)), f)+ print(f"{name}: {counts}", flush=True)+++def unquote(p):+ if p.startswith('"') and p.endswith('"'):+ p = bytes(p[1:-1], "utf-8").decode("unicode_escape").encode("latin-1").decode("utf-8", "replace")+ return p+++def parse_diff(text):+ """Split a git diff into file sections: dicts with old, new, status and the section's text."""+ sections, cur = [], None+ for line in text.splitlines(keepends=True):+ if line.startswith("diff --git "):+ if cur:+ sections.append(cur)+ cur = {"lines": [line], "old": None, "new": None, "status": "modified"}+ hdr = line[len("diff --git "):].rstrip("\n")+ if hdr.startswith("a/") and " b/" in hdr:+ n = (len(hdr) - 5) // 2 # "a/X b/X": both halves name the same path+ if (len(hdr) - 5) % 2 == 0 and hdr[2 + n:5 + n] == " b/" and hdr[2:2 + n] == hdr[5 + n:]:+ cur["old"] = cur["new"] = hdr[2:2 + n]+ else:+ i = hdr.index(" b/")+ cur["old"], cur["new"] = hdr[2:i], hdr[i + 3:]+ continue+ if cur is None:+ continue+ cur["lines"].append(line)+ if line.startswith("new file mode"):+ cur["status"] = "added"+ elif line.startswith("deleted file mode"):+ cur["status"] = "deleted"+ elif line.startswith("rename from "):+ cur["status"], cur["old"] = "renamed", unquote(line[len("rename from "):].rstrip("\n"))+ elif line.startswith("rename to "):+ cur["new"] = unquote(line[len("rename to "):].rstrip("\n"))+ elif line.startswith("--- ") and not line.startswith("--- /dev/null"):+ p = unquote(line[4:].rstrip("\n").split("\t")[0])+ cur["old"] = p[2:] if p.startswith("a/") else p+ elif line.startswith("+++ ") and not line.startswith("+++ /dev/null"):+ p = unquote(line[4:].rstrip("\n").split("\t")[0])+ cur["new"] = p[2:] if p.startswith("b/") else p+ if cur:+ sections.append(cur)+ return sections+++def cmd_check(a):+ for _ri, repo in chosen(a):+ name = repo["name"]+ cpath = os.path.join(mdir(a.work), f"candidates-{name}.json")+ rows = json.load(open(cpath))+ at_s = tracked(a.work, name)+ src = os.path.join(a.work, "src", name)+ d = mdir(a.work, "diffs", name)+ need = []+ for r in rows:+ if r["drop"]:+ continue+ path = os.path.join(d, f"{r['pr']}.diff")+ if not os.path.exists(path):+ r["drop"] = "diff"+ continue+ secs = parse_diff(open(path, encoding="utf-8", errors="replace").read())+ if not secs:+ r["drop"] = "diff"+ continue+ gold = []+ for s in secs:+ old = s["old"]+ if s["status"] == "added" or not old or old not in at_s:+ continue+ if classify(name, old, at_s) == "source":+ gold.append(s)+ r["gold"] = sorted({s["old"] for s in gold})+ if not 1 <= len(r["gold"]) <= 5:+ r["drop"] = "gold"+ continue+ with tempfile.NamedTemporaryFile("w", suffix=".diff", delete=False) as f:+ for s in gold:+ f.write("".join(s["lines"]))+ patch = f.name+ p = subprocess.run(["git", "apply", "--check", patch], cwd=src, capture_output=True, text=True)+ os.unlink(patch)+ if p.returncode != 0:+ r["drop"] = "applies"+ r["apply_error"] = p.stderr.strip().splitlines()[0][:200] if p.stderr.strip() else ""+ continue+ need.extend(r["issues"])+ with open(cpath, "w") as f:+ json.dump(rows, f, indent=0)+ with open(os.path.join(mdir(a.work), f"issues-needed-{name}.txt"), "w") as f:+ f.write("".join(f"{n}\n" for n in sorted(set(need))))+ left = sum(1 for r in rows if not r["drop"])+ print(f"{name}: {left} pull requests pass the diff checks; {len(set(need))} issues to fetch", flush=True)+++def load_issues(raw, name):+ issues = {}+ for path in sorted(glob.glob(os.path.join(raw, f"issues-{name}-*.json"))):+ for page in read_pages(path):+ repo = (page.get("data") or {}).get("repository") or {}+ for k, v in repo.items():+ if v:+ issues[int(k[1:])] = v+ return issues+++def names_gold_path(text, gold):+ """True when the text names a gold file by a path of at least two components (dir/file)."""+ for g in gold:+ parts = g.split("/")+ for i in range(0, len(parts) - 1):+ if "/".join(parts[i:]) in text:+ return True+ return False+++def cmd_select(a):+ os.makedirs(a.out, exist_ok=True)+ fpath = os.path.join(a.out, "funnel.json")+ funnel = json.load(open(fpath)) if a.repos and os.path.exists(fpath) else {}+ for ri, repo in chosen(a):+ name = repo["name"]+ rows = json.load(open(os.path.join(mdir(a.work), f"candidates-{name}.json")))+ issues = load_issues(a.raw, name)+ used, pool, texts = set(), [], {}+ for r in sorted(rows, key=lambda r: (r["landed_at"] or "", r["pr"])):+ if r["drop"]:+ continue+ choices = []+ for n in r["issues"]:+ iss = issues.get(n)+ if not iss or iss.get("__typename") != "Issue" or ts(iss["createdAt"]) >= ts(r["landed_at"]):+ continue+ choices.append(iss)+ if not choices:+ r["drop"] = "issue"+ continue+ iss = min(choices, key=lambda i: (i["createdAt"], i["number"]))+ if iss["number"] in used:+ r["drop"] = "duplicate"+ continue+ used.add(iss["number"])+ text, notes = question_text(iss)+ q = {"id": f"{name}-{r['pr']}", "repo": repo["slug"], "S": SNAP[name]["sha"],+ "issue_url": iss["url"], "pr_url": r["url"], "merged_at": r["landed_at"],+ "gold": r["gold"], "text_sha256": sha256(text), "names_gold_path": names_gold_path(text, r["gold"])}+ pool.append(q)+ texts[q["id"]] = {"id": q["id"], "text": text, "notes": notes, "issue_created_at": iss["createdAt"]}+ target = repo["target"]+ if len(pool) > target:+ keep = random.Random(CFG["selection_seed"] + ri).sample(pool, target)+ keep.sort(key=lambda q: (q["merged_at"], q["id"]))+ else:+ keep = pool+ with open(os.path.join(a.out, f"questions-{name}.jsonl"), "w") as f:+ for q in keep:+ f.write(json.dumps(q, sort_keys=True) + "\n")+ with open(os.path.join(mdir(a.work), f"texts-{name}.jsonl"), "w") as f:+ for q in keep:+ f.write(json.dumps(texts[q["id"]], sort_keys=True) + "\n")+ counts = {"fetched": len(rows)}+ for k in ["window", "linked", "files", "prefilter", "diff", "gold", "applies", "issue", "duplicate"]:+ counts["dropped_" + k] = sum(1 for r in rows if r["drop"] == k)+ counts["passed"] = len(pool)+ counts["kept"] = len(keep)+ counts["sampled"] = len(pool) > target+ counts["names_gold_path"] = sum(1 for q in keep if q["names_gold_path"])+ funnel[name] = counts+ print(f"{name}: {json.dumps(counts)}", flush=True)+ with open(os.path.join(mdir(a.work), f"candidates-{name}.json"), "w") as f:+ json.dump(rows, f, indent=0)+ with open(fpath, "w") as f:+ json.dump(funnel, f, indent=1, sort_keys=True)+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("cmd", choices=["candidates", "diffs", "check", "select"])+ ap.add_argument("--work", required=True)+ ap.add_argument("--raw")+ ap.add_argument("--out")+ ap.add_argument("--jobs", type=int, default=4)+ ap.add_argument("--repos", help="comma-separated names from repos.json (default: all)")+ a = ap.parse_args()+ a.work = os.path.abspath(a.work)+ a.repos = set(a.repos.split(",")) if a.repos else set()+ unknown = a.repos - {r["name"] for r in CFG["repos"]}+ if unknown:+ raise SystemExit(f"unknown repositories: {sorted(unknown)}")+ {"candidates": cmd_candidates, "diffs": cmd_diffs, "check": cmd_check, "select": cmd_select}[a.cmd](a)+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/mock_server.py b/bench/whole-repo/mock_server.pynew file mode 100644index 0000000..0809e4f--- /dev/null+++ b/bench/whole-repo/mock_server.py@@ -0,0 +1,288 @@+#!/usr/bin/env python3+"""A mock OpenAI-compatible model server, for testing the runners without a model or a key.++usage: mock_server.py --host HOST --port PORT [--seed N] [--fail-every N] [--record FILE]++Serves POST /v1/chat/completions, POST /v1/responses and POST /v1/responses/input_tokens the way+Meta's Model API documents them (https://dev.meta.ai/docs/protocols/responses, /docs/tool-calling+and /docs/prompt-caching, read 2026-10-26):+- a Bearer key is required (any value);+- tool_choice other than "auto" and reasoning effort "none" return HTTP 400; so does a+ prompt_cache_retention other than "in_memory" or "24h", and max_output_tokens below 16;+- Responses: function tools are {"type": "function", "name", "description", "parameters"}; the+ output holds a reasoning item, then function_call items (call_id, name, arguments as a JSON+ string) or a message with output_text; previous_response_id continues a stored response, and a+ function_call_output must answer a call of that response;+- usage: input_tokens / output_tokens with output_tokens_details.reasoning_tokens and+ input_tokens_details.cached_tokens (Responses), prompt_tokens / completion_tokens with+ prompt_tokens_details.cached_tokens (chat).+Prompt caching is simulated per cache key (prompt_cache_key in the body, else the+x-session-affinity header): the cached tokens are the common prefix of the request's input with the+last input sent under the same key, counted only from 1,024 tokens up; a continued response also+counts the stored history as cached. Tokens are estimated as UTF-8 bytes / 4.+--record FILE appends one JSON line per request, without any prompt text: the path, model, cache+key, retention, session affinity, output cap, reasoning effort and the usage returned.++With tools, the mock explores: find, then grep, then two reads of paths it saw, then it answers.+Without tools it answers at once. The answer is {"files": [...]}: paths seen in the prompt or in tool+results, ranked by how often words of the issue appear near them. --fail-every N returns HTTP 500+on every Nth request, to test retries.+"""+import argparse+import json+import math+import os+import random+import re+import threading+import uuid+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++STATE = {"responses": {}, "count": 0, "keys": {}}+LOCK = threading.Lock()+PATH_RX = re.compile(r'<file path="([^"]+)"|^([\w./-]+\.[A-Za-z]{1,6})(?::\d+)?', re.M)+CACHE_MIN_TOKENS = 1024+++def est(text):+ return math.ceil(len(text.encode("utf-8")) / 4)+++def key_cached(key, text):+ """Tokens of `text` served from the cache under `key`: its common prefix with the key's last input."""+ if not key:+ return 0+ with LOCK:+ last = STATE["keys"].get(key)+ STATE["keys"][key] = text+ if not last:+ return 0+ n = len(os.path.commonprefix([last, text]))+ tokens = len(text[:n].encode("utf-8")) // 4+ return tokens if tokens >= CACHE_MIN_TOKENS else 0+++def flatten(content):+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(c.get("text", "") if isinstance(c, dict) else str(c) for c in content)+ return "" if content is None else str(content)+++def words_of(issue):+ return [w.lower() for w in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", issue)][:40]+++def answer_files(text, issue, rng):+ seen = []+ for m in PATH_RX.finditer(text):+ p = m.group(1) or m.group(2)+ if p and "/" in p and p not in seen:+ seen.append(p)+ words = words_of(issue)+ scored = []+ for i, p in enumerate(seen):+ score = sum(1 for w in words if w in p.lower()) + rng.random() * 0.5+ scored.append((-score, i, p))+ scored.sort()+ return [p for _, _, p in scored[:10]]+++def next_action(transcript, issue, n_tool_results, has_tools, rng):+ """('tool', name, args) or ('answer', text)."""+ words = words_of(issue) or ["main"]+ if has_tools and n_tool_results < 4:+ if n_tool_results == 0:+ return ("tool", "find", {"name_glob": f"*{words[0][:12]}*"})+ if n_tool_results == 1:+ return ("tool", "grep", {"pattern": words[min(1, len(words) - 1)], "path_glob": "*"})+ paths = answer_files(transcript, issue, rng)+ if paths:+ return ("tool", "read", {"path": paths[(n_tool_results - 2) % len(paths)], "start": 1, "end": 120})+ return ("tool", "list_dir", {"path": ""})+ files = answer_files(transcript, issue, rng)+ return ("answer", json.dumps({"files": files}))+++class Handler(BaseHTTPRequestHandler):+ server_version = "mock-openai/1"++ def log_message(self, *args):+ pass++ def send(self, code, obj):+ body = json.dumps(obj).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def api_error(self, code, msg, param=None):+ self.send(code, {"error": {"message": msg, "type": "invalid_request_error", "param": param}})++ def cache_key(self, req):+ return req.get("prompt_cache_key") or self.headers.get("x-session-affinity") or ""++ def record(self, req, usage, status=200):+ """One line per request in --record, without any prompt text."""+ if not self.server.record:+ return+ line = {"path": self.path, "status": status, "model": req.get("model"),+ "prompt_cache_key": req.get("prompt_cache_key"),+ "prompt_cache_retention": req.get("prompt_cache_retention"),+ "session_affinity": self.headers.get("x-session-affinity"),+ "max_output_tokens": req.get("max_output_tokens"), "max_tokens": req.get("max_tokens"),+ "reasoning_effort": (req.get("reasoning") or {}).get("effort") or req.get("reasoning_effort"),+ "store": req.get("store"), "previous_response_id": bool(req.get("previous_response_id")),+ "tools": len(req.get("tools") or []), "usage": usage}+ with LOCK:+ with open(self.server.record, "a") as f:+ f.write(json.dumps(line, sort_keys=True) + "\n")++ def do_POST(self):+ if not self.headers.get("Authorization", "").startswith("Bearer ") or len(self.headers["Authorization"]) < 9:+ return self.api_error(401, "missing bearer key")+ n = int(self.headers.get("Content-Length", "0"))+ try:+ req = json.loads(self.rfile.read(n))+ except json.JSONDecodeError:+ return self.api_error(400, "bad json")+ with LOCK:+ STATE["count"] += 1+ count = STATE["count"]+ if self.server.fail_every and count % self.server.fail_every == 0:+ return self.api_error(500, "mock failure")+ if req.get("tool_choice", "auto") != "auto":+ return self.api_error(400, "only tool_choice auto is supported", "tool_choice")+ rng = random.Random(self.server.seed + count)+ if self.path.rstrip("/").endswith("/chat/completions"):+ return self.api_chat(req, rng)+ if self.path.rstrip("/").endswith("/responses/input_tokens"):+ return self.api_input_tokens(req)+ if self.path.rstrip("/").endswith("/responses"):+ return self.api_responses(req, rng)+ return self.api_error(404, "unknown path")++ def api_input_tokens(self, req):+ items = req.get("input")+ items = [{"type": "message", "role": "user", "content": items}] if isinstance(items, str) else list(items or [])+ text = "\n".join(flatten(i.get("content")) if i.get("type", "message") == "message"+ else str(i.get("output", "")) for i in items)+ self.record(req, {"input_tokens": est(text)})+ self.send(200, {"object": "response.input_tokens", "input_tokens": est(text)})++ def api_chat(self, req, rng):+ if req.get("reasoning_effort") == "none":+ return self.api_error(400, "reasoning effort none is not supported", "reasoning_effort")+ msgs = req.get("messages") or []+ transcript = "\n".join(flatten(m.get("content")) for m in msgs)+ issue = next((flatten(m.get("content")) for m in msgs if m.get("role") == "user"), "")+ n_tool = sum(1 for m in msgs if m.get("role") == "tool")+ tool_names = [t["function"]["name"] for t in req.get("tools") or [] if t.get("type") == "function"]+ act = next_action(transcript, issue, n_tool, bool(tool_names), rng)+ reasoning = rng.randint(200, 1200)+ if act[0] == "tool" and act[1] in tool_names:+ msg = {"role": "assistant", "content": None, "tool_calls": [+ {"id": "call_" + uuid.uuid4().hex[:12], "type": "function",+ "function": {"name": act[1], "arguments": json.dumps(act[2])}}]}+ finish, out_text = "tool_calls", json.dumps(act[2])+ else:+ text = act[1] if act[0] == "answer" else next_action(transcript, issue, 99, False, rng)[1]+ msg, finish, out_text = {"role": "assistant", "content": text}, "stop", text+ prompt = est(transcript)+ cached = min(key_cached(self.cache_key(req), transcript), prompt)+ usage = {"prompt_tokens": prompt, "completion_tokens": est(out_text) + reasoning,+ "total_tokens": prompt + est(out_text) + reasoning,+ "prompt_tokens_details": {"cached_tokens": cached},+ "completion_tokens_details": {"reasoning_tokens": reasoning}}+ self.record(req, usage)+ self.send(200, {"id": "chatcmpl-" + uuid.uuid4().hex[:16], "object": "chat.completion",+ "model": req.get("model"), "choices": [{"index": 0, "message": msg, "finish_reason": finish}],+ "usage": usage})++ def api_responses(self, req, rng):+ effort = (req.get("reasoning") or {}).get("effort")+ if effort == "none":+ return self.api_error(400, "reasoning effort none is not supported", "reasoning.effort")+ if req.get("prompt_cache_retention") not in (None, "in_memory", "24h"):+ return self.api_error(400, "prompt_cache_retention must be in_memory or 24h", "prompt_cache_retention")+ if req.get("max_output_tokens") is not None and req["max_output_tokens"] < 16:+ return self.api_error(400, "max_output_tokens has a minimum of 16", "max_output_tokens")+ items = req.get("input")+ items = [{"type": "message", "role": "user", "content": items}] if isinstance(items, str) else list(items or [])+ prev = req.get("previous_response_id")+ history, pending = [], set()+ if prev:+ with LOCK:+ st = STATE["responses"].get(prev)+ if st is None:+ return self.api_error(400, "unknown previous_response_id", "previous_response_id")+ history = list(st["history"])+ pending = set(st["calls"])+ own_calls = {i.get("call_id") for i in items if i.get("type") == "function_call"}+ for i in items:+ if i.get("type") == "function_call_output":+ cid = i.get("call_id") or ""+ if not 1 <= len(cid) <= 64 or (cid not in pending and cid not in own_calls):+ return self.api_error(400, "function_call_output does not match a function_call", "call_id")+ history.extend(items)+ transcript = "\n".join(flatten(i.get("content")) if i.get("type", "message") == "message"+ else str(i.get("output", "")) for i in history)+ issue = next((flatten(i.get("content")) for i in history+ if i.get("type", "message") == "message" and i.get("role") == "user"), "")+ n_tool = sum(1 for i in history if i.get("type") == "function_call_output")+ tool_names = [t.get("name") for t in req.get("tools") or [] if t.get("type") == "function"]+ act = next_action(transcript, issue, n_tool, bool(tool_names), rng)+ rid = "resp_" + uuid.uuid4().hex[:20]+ reasoning = rng.randint(200, 1200)+ output = [{"type": "reasoning", "id": "rs_" + uuid.uuid4().hex[:12], "summary": []}]+ calls = []+ if act[0] == "tool" and act[1] in tool_names:+ cid = "call_" + uuid.uuid4().hex[:12]+ calls.append(cid)+ output.append({"type": "function_call", "id": "fc_" + uuid.uuid4().hex[:12], "call_id": cid,+ "name": act[1], "arguments": json.dumps(act[2]), "status": "completed"})+ out_text = json.dumps(act[2])+ else:+ text = act[1] if act[0] == "answer" else next_action(transcript, issue, 99, False, rng)[1]+ output.append({"type": "message", "id": "msg_" + uuid.uuid4().hex[:12], "role": "assistant",+ "status": "completed", "content": [{"type": "output_text", "text": text}]})+ out_text = text+ prompt = est(transcript)+ cached = est("\n".join(str(h) for h in history[:-len(items)])) if prev and items else 0+ cached = max(cached, key_cached(self.cache_key(req), transcript))+ with LOCK:+ STATE["responses"][rid] = {"history": history + output, "calls": calls}+ usage = {"input_tokens": prompt, "output_tokens": est(out_text) + reasoning,+ "total_tokens": prompt + est(out_text) + reasoning,+ "input_tokens_details": {"cached_tokens": min(cached, prompt)},+ "output_tokens_details": {"reasoning_tokens": reasoning}}+ self.record(req, usage)+ self.send(200, {"id": rid, "object": "response", "status": "completed", "model": req.get("model"),+ "output": output, "usage": usage})+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--host", required=True)+ ap.add_argument("--port", type=int, default=18080)+ ap.add_argument("--seed", type=int, default=7)+ ap.add_argument("--fail-every", type=int, default=0)+ ap.add_argument("--record", help="append one JSON line per request (no prompt text) to this file")+ a = ap.parse_args()+ srv = make_server(a.host, a.port, a.seed, a.fail_every, a.record)+ print(f"mock server on http://{a.host}:{srv.server_address[1]}/v1", flush=True)+ srv.serve_forever()+++def make_server(host, port=0, seed=7, fail_every=0, record=None):+ """A ready server (port 0 picks a free one); call serve_forever(), in a thread for tests."""+ srv = ThreadingHTTPServer((host, port), Handler)+ srv.seed, srv.fail_every, srv.record = seed, fail_every, record+ return srv+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/pack_arm.py b/bench/whole-repo/pack_arm.pynew file mode 100644index 0000000..2f48739--- /dev/null+++ b/bench/whole-repo/pack_arm.py@@ -0,0 +1,164 @@+"""The pack arm's context: `graphicle pack`, or `graphicle context` as a labelled stand-in.++pack_context(...) returns a dict: text, included (paths), tokens, seconds, source and, for the pack,+its layout fields (see layout_info):+- `graphicle pack QUESTION --project SRC --data-dir DATA --budget B --format xml [--tokenizer T]+ [--layout standard|cache] [--prefix-share F]` for the text, and the same with --format json for the+ included files, the tokens and the layout (the pack's output contract, graphicle.pack.v1);+- with standin=True, `graphicle context QUESTION --project SRC --data-dir DATA --max-tokens B+ --max-chars 4B --json`, with B capped at 16,000 tokens and 64,000 characters (the most `context`+ takes): its excerpts wrapped like pack chunks. This is for testing the plumbing only: `context`+ is built for short evidence packets, not for filling a large budget, so its numbers are never+ results of the pack.+A file is included when the context holds some of its text; names listed without text do not count.++pack_json(...) runs only the JSON form and also returns the call's wall seconds and peak memory,+the pack's top omitted files, the files its manifest names as left out (for recall.py) and the+layout fields.++The layout fields (additive to graphicle.pack.v1; builds without layouts have none of them):+"layout" (standard or cache), "prefix_share" (cache only), "prefix_tokens", "prefix_sha256" (hex of+the prefix text's bytes) and, per section, "part" (prefix or suffix). The prefix text is the+concatenation of the prefix sections' chunk text, a byte-prefix of the whole text (every chunk's+text in order). layout_info checks both.+"""+import hashlib+import json+import os+import re+import subprocess+import tempfile+import threading+import time++QUESTION_MAX_CHARS = 100000 # a command-line argument's limit; the model's prompt keeps the whole text+STANDIN_MAX_TOKENS = 16000+LEFT_OUT = re.compile(r"^- (.+?): ~\d+ tokens, rank (\d+)$")+# The arms that are `graphicle pack`, with their layout options.+PACK_ARMS = {"pack": (None, None), "pack-cache": ("cache", 0.9), "pack-stable": ("cache", 1.0)}+++def run_measured(cmd, timeout=1800):+ """(exit code, stdout, stderr, wall seconds, peak resident memory of the process in MiB)."""+ with tempfile.TemporaryFile() as out, tempfile.TemporaryFile() as err:+ t0 = time.time()+ p = subprocess.Popen(cmd, stdout=out, stderr=err)+ timer = threading.Timer(timeout, p.kill)+ timer.start()+ try:+ _pid, status, ru = os.wait4(p.pid, 0)+ finally:+ timer.cancel()+ p.returncode = os.waitstatus_to_exitcode(status)+ secs = time.time() - t0+ out.seek(0)+ err.seek(0)+ return p.returncode, out.read().decode("utf-8", "replace"), err.read().decode("utf-8", "replace"), \+ secs, ru.ru_maxrss / 1024+++def standin_packet_to_context(packet):+ """`graphicle context --json` (0.1.8): evidence items hold the text, sources (same id) the path and lines."""+ sources = {s.get("id"): s for s in packet.get("sources") or []}+ parts, paths = [], []+ for ex in packet.get("evidence") or []:+ s = sources.get(ex.get("id")) or {}+ p = s.get("path") or ex.get("title") or ""+ t = ex.get("text") or ""+ if not p or not t:+ continue+ lines = f"{s['line']}-{s['end_line']}" if s.get("line") and s.get("end_line") else ""+ parts.append(f'<file path="{p}" lines="{lines}">\n{t.rstrip()}\n</file>\n')+ if p not in paths:+ paths.append(p)+ return "".join(parts), paths, packet.get("tokens")+++def pack_command(graphicle, src, data, question, budget, tokenizer, fmt, layout=None, prefix_share=None):+ cmd = [graphicle, "pack", question[:QUESTION_MAX_CHARS], "--project", src, "--data-dir", data,+ "--budget", str(budget), "--format", fmt]+ if tokenizer:+ cmd += ["--tokenizer", tokenizer]+ if layout:+ cmd += ["--layout", layout]+ if prefix_share is not None:+ cmd += ["--prefix-share", f"{prefix_share:g}"]+ return cmd+++def layout_info(pj):+ """The layout fields of a graphicle.pack.v1 JSON, with checks of the prefix contract:+ prefix_ok (the prefix sections come first and their chunk text hashes to prefix_sha256),+ prefix_text_tokens (the prefix sections' tokens) and suffix_tokens."""+ secs = pj.get("sections") or []+ parts = [s.get("part") for s in secs]+ info = {"layout": pj.get("layout"), "prefix_share": pj.get("prefix_share"),+ "prefix_tokens": pj.get("prefix_tokens"), "prefix_sha256": pj.get("prefix_sha256"),+ "parts": {s.get("name"): s.get("part") for s in secs}}+ if not pj.get("prefix_sha256") or not any(parts):+ info["prefix_ok"] = None+ return info+ n_prefix = sum(1 for p in parts if p == "prefix")+ first = all(p == "prefix" for p in parts[:n_prefix]) and all(p == "suffix" for p in parts[n_prefix:])+ text = "".join(c.get("text") or "" for s in secs[:n_prefix] for c in s.get("chunks") or [])+ info["prefix_ok"] = bool(first and hashlib.sha256(text.encode("utf-8")).hexdigest() == pj["prefix_sha256"])+ info["prefix_text_tokens"] = sum(s.get("tokens") or 0 for s in secs[:n_prefix])+ info["suffix_tokens"] = (pj.get("tokens") or 0) - (pj.get("prefix_tokens") or 0)+ return info+++def pack_json(graphicle, src, data, question, budget, tokenizer=None, layout=None, prefix_share=None):+ """The JSON pack plus measurements: dict with included {path: rank}, omitted [(path, rank)],+ left_out_listed {path: rank} (the manifest's list), tokens, tokenizer, seconds, peak_mib, sections+ and the layout fields (layout_info)."""+ code, out, err, secs, peak = run_measured(+ pack_command(graphicle, src, data, question, budget, tokenizer, "json", layout, prefix_share))+ if code != 0:+ raise RuntimeError("graphicle pack: " + err.strip()[:300])+ pj = json.loads(out)+ listed = {}+ for sec in pj.get("sections") or []:+ if sec.get("name") != "manifest":+ continue+ for ch in sec.get("chunks") or []:+ for line in (ch.get("text") or "").splitlines():+ m = LEFT_OUT.match(line.strip())+ if m:+ listed[m.group(1)] = int(m.group(2))+ return {"included": {f["path"]: f.get("rank") for f in pj.get("included") or []},+ "omitted": [(f["path"], f.get("rank")) for f in pj.get("omitted") or []],+ "left_out_listed": listed, "tokens": pj.get("tokens"), "tokenizer": pj.get("tokenizer"),+ "seconds": round(secs, 3), "peak_mib": round(peak, 1), "pack_seconds": pj.get("seconds"),+ "sections": {s.get("name"): s.get("tokens") for s in pj.get("sections") or []},+ **layout_info(pj)}+++def pack_context(graphicle, src, data, question, budget, tokenizer=None, standin=False, want_text=True,+ layout=None, prefix_share=None):+ q = question[:QUESTION_MAX_CHARS]+ t0 = time.time()+ if standin:+ # graphicle context (0.1.8) takes at most 16,000 tokens and 64,000 characters, whatever the budget.+ cmd = [graphicle, "context", q, "--project", src, "--data-dir", data,+ "--max-tokens", str(min(budget, STANDIN_MAX_TOKENS)), "--max-chars", str(min(4 * budget, 64000)),+ "--more-files", "0", "--json"]+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=900)+ if r.returncode != 0:+ raise RuntimeError("graphicle context: " + r.stderr.strip()[:300])+ text, paths, ntok = standin_packet_to_context(json.loads(r.stdout))+ return {"text": text, "included": paths, "tokens": ntok, "seconds": time.time() - t0,+ "source": "graphicle context (stand-in, cl100k tokens)", "prefix_sha256": None}+ rj = subprocess.run(pack_command(graphicle, src, data, q, budget, tokenizer, "json", layout, prefix_share),+ capture_output=True, text=True, timeout=1800)+ if rj.returncode != 0:+ raise RuntimeError("graphicle pack: " + rj.stderr.strip()[:300])+ pj = json.loads(rj.stdout)+ text = None+ if want_text:+ rx = subprocess.run(pack_command(graphicle, src, data, q, budget, tokenizer, "xml", layout, prefix_share),+ capture_output=True, text=True, timeout=1800)+ if rx.returncode != 0:+ raise RuntimeError("graphicle pack: " + rx.stderr.strip()[:300])+ text = rx.stdout+ return {"text": text, "included": [f["path"] for f in pj.get("included") or []], "tokens": pj.get("tokens"),+ "seconds": time.time() - t0, "source": f"graphicle pack ({pj.get('tokenizer', '?')})", **layout_info(pj)}diff --git a/bench/whole-repo/paths.py b/bench/whole-repo/paths.pynew file mode 100644index 0000000..9a59035--- /dev/null+++ b/bench/whole-repo/paths.py@@ -0,0 +1,116 @@+"""File classes for the whole-repository benchmark.++classify(repo, path, all_paths=None) returns one of:+ vendored third-party code copied into the repository+ generated files written by tools (code generators, lock files, recorded metadata)+ changelog release notes and changelog entries+ docs documentation and project metadata+ test tests, test data, test frameworks and fixtures+ source everything else (code, build files, configuration)++The first matching class wins, in that order. Gold files are source files; truncation reads source+files first, then tests, then docs and changelogs, and leaves vendored and generated files out; the+repository sizes are reported with and without vendored and generated files.+"""+import os+import re++VENDOR_DIRS = {"vendor", "third_party", "third-party", "thirdparty", "node_modules", "bower_components"}+LOCK_FILES = {"go.sum", "go.work.sum", "package-lock.json", "yarn.lock", "npm-shrinkwrap.json", "Cargo.lock", "poetry.lock",+ "uv.lock", "pnpm-lock.yaml", "Gemfile.lock", "composer.lock", "Pipfile.lock"}+GENERATED_DIRS = {"generated", "generated-src", "generated-sources"}+GENERATED_NAME = re.compile(r"(^zz_generated|\.pb\.go$|_pb2\.pyi?$|\.pb\.(h|cc)$|\.generated\.|\.min\.(js|css)$|\.js\.map$)")+CHANGELOG_NAME = re.compile(r"^(CHANGELOG|CHANGES|HISTORY|RELEASE[-_]?NOTES)([-_.].*)?$", re.I)+CHANGELOG_DIRS = {"changelog", "changelogs", "CHANGELOG", "release-notes", "releasenotes"}+DOC_DIRS = {"docs", "doc", "documentation", "Documentation"}+DOC_EXT = {".md", ".rst", ".adoc", ".asciidoc", ".markdown"}+DOC_NAME = re.compile(r"^(LICENSE|LICENCE|NOTICE|AUTHORS|CONTRIBUTORS|CONTRIBUTING|SECURITY|CODE_OF_CONDUCT|OWNERS|OWNERS_ALIASES|SECURITY_CONTACTS|MAINTAINERS)([-_.].*)?$")+TEST_DIRS = {"test", "tests", "testing", "testdata", "__tests__", "__mocks__", "test-fixtures", "testFixtures",+ "fixtures", "internalClusterTest", "javaRestTest", "yamlRestTest", "integTest", "integrationTest",+ "qa", "e2e", "e2e_node"}+TEST_NAME = re.compile(r"(_test\.go$|^test_.*\.py$|_test\.py$|^conftest\.py$|\.(test|spec)\.[cm]?[jt]sx?$"+ r"|(Test|Tests|IT|TestCase)\.java$|_test\.(cc|cpp|c|h)$|^test_.*\.(cc|cpp)$)")++# Repository-specific rules: (class, regex on the path).+REPO_RULES = {+ "kubernetes": [+ ("generated", re.compile(r"^api/(openapi-spec|discovery|api-rules)/")),+ ("generated", re.compile(r"(^|/)pkg/generated/")),+ ("generated", re.compile(r"^staging/src/k8s\.io/client-go/(applyconfigurations|informers|listers|kubernetes)/")),+ ("generated", re.compile(r"^staging/src/k8s\.io/[^/]+/pkg/client/(clientset|informers|listers|applyconfiguration)")),+ ("generated", re.compile(r"(^|/)generated\.proto$|types_swagger_doc_generated\.go$")),+ ("vendored", re.compile(r"^LICENSES/vendor/")),+ ],+ "home-assistant": [+ ("generated", re.compile(r"^homeassistant/generated/")),+ ("generated", re.compile(r"^(requirements_all\.txt|requirements_test_all\.txt|homeassistant/package_constraints\.txt"+ r"|CODEOWNERS|mypy\.ini|script/hassfest/docker/Dockerfile)$")),+ ("generated", re.compile(r"^homeassistant/components/[^/]+/translations/")),+ ],+ "pytorch": [+ ("generated", re.compile(r"^torch/_inductor/autoheuristic/artifacts/")),+ # torch.testing's public helpers are source; its _internal package is the test framework.+ ("source", re.compile(r"^torch/testing/(?!_internal/)")),+ ("test", re.compile(r"^torch/testing/_internal/")),+ ],+ "vscode": [+ ("generated", re.compile(r"(^|/)(cgmanifest\.json|cglicenses\.json|ThirdPartyNotices\.txt)$")),+ ("generated", re.compile(r"^src/vs/monaco\.d\.ts$|^src/vs/editor/common/standalone/standaloneEnums\.ts$")),+ ("generated", re.compile(r"^extensions/[^/]+/syntaxes/.*\.tmLanguage\.json$")),+ ("vendored", re.compile(r"^src/vs/base/common/(marked|semver)/|^src/vs/base/browser/dompurify/")),+ ("test", re.compile(r"^extensions/(vscode-api-tests|vscode-colorize-tests|vscode-colorize-perf-tests|vscode-test-resolver)/")),+ ],+ "elasticsearch": [+ ("changelog", re.compile(r"^docs/changelog/")),+ ("generated", re.compile(r"^gradle/verification-metadata\.xml$")),+ ("generated", re.compile(r"^server/src/main/resources/transport/")),+ ("generated", re.compile(r"/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBase[A-Za-z]*\.(java|interp|tokens)$")),+ ("generated", re.compile(r"\.(interp|tokens)$")),+ ("test", re.compile(r"(^|/)rest-api-spec/src/main/resources/rest-api-spec/test/")),+ ("test", re.compile(r"(^|/)test/framework/")),+ ],+ "angular": [+ ("docs", re.compile(r"^adev/src/content/|^packages/examples/")),+ ("generated", re.compile(r"^goldens/")),+ ("test", re.compile(r"^integration/|^modules/(benchmarks|playground|ssr-benchmarks)/|^devtools/cypress/"+ r"|^vscode-ng-language-service/integration/")),+ ],+ "keycloak": [+ ("test", re.compile(r"^(testsuite|test-framework|misc/test-stability)/")),+ ],+ "godot": [+ ("docs", re.compile(r"(^|/)doc_classes/")),+ ("generated", re.compile(r"^editor/translations/")),+ ("test", re.compile(r"\.Tests/|/macrobenchmark/")),+ ],+}++ORDER = ["vendored", "generated", "changelog", "docs", "test", "source"]+++def classify(repo, path, all_paths=None):+ parts = path.split("/")+ dirs, name = parts[:-1], parts[-1]+ ext = os.path.splitext(name)[1].lower()+ for cls, rx in REPO_RULES.get(repo, []):+ if rx.search(path):+ return cls+ if VENDOR_DIRS.intersection(dirs):+ return "vendored"+ if name in LOCK_FILES or GENERATED_DIRS.intersection(dirs) or GENERATED_NAME.search(name):+ return "generated"+ if repo == "vscode" and parts[0] == "build" and ext == ".js" and all_paths is not None \+ and path[:-3] + ".ts" in all_paths:+ return "generated" # build scripts are committed as TypeScript and as their compiled JavaScript+ if CHANGELOG_NAME.match(name) or CHANGELOG_DIRS.intersection(dirs):+ return "changelog"+ if DOC_DIRS.intersection(dirs) or ext in DOC_EXT or DOC_NAME.match(name):+ return "docs"+ if TEST_DIRS.intersection(dirs) or TEST_NAME.search(name):+ return "test"+ return "source"+++def truncation_rank(cls):+ """Truncation reads source first, then tests, then docs and changelogs; None means left out."""+ return {"source": 0, "test": 1, "docs": 2, "changelog": 2}.get(cls)diff --git a/bench/whole-repo/prices.json b/bench/whole-repo/prices.jsonnew file mode 100644index 0000000..26ae393--- /dev/null+++ b/bench/whole-repo/prices.json@@ -0,0 +1,14 @@+{+ "unit": "US dollars per million tokens",+ "date": "2026-10-26",+ "source": "https://dev.meta.ai/docs/pricing-rate-limits (Standard mode; the page states no long-context surcharge) and https://www.baseten.co/pricing (Model APIs), both read 2026-10-26",+ "models": {+ "muse-spark-1.3": {"provider": "meta", "input": 1.25, "cached_input": 0.15, "output": 4.25},+ "muse-wonder-1.0": {"provider": "meta", "input": 4.0, "cached_input": 0.2, "output": 20.0},+ "muse-spark-1.2": {"provider": "meta", "input": 1.25, "cached_input": 0.15, "output": 4.25},+ "muse-spark-1.3-contributor": {"provider": "meta", "input": 0.10, "cached_input": 0.002, "output": 0.20, "note": "Contributor mode: Meta may use the prompts, context and responses to train future models; 150 requests and 3M tokens per minute (same page, read 2026-10-26)"},+ "meta-models/muse-spark-open": {"provider": "baseten", "input": 1.25, "cached_input": 0.15, "output": 4.25, "note": "Muse Spark Open on Baseten's Model APIs (https://www.baseten.co/pricing)"},+ "muse-spark-open": {"provider": "local", "input": 0.0, "cached_input": 0.0, "output": 0.0, "note": "our own GPUs: no per-token price"},+ "mock": {"provider": "mock", "input": 1.25, "cached_input": 0.15, "output": 4.25, "note": "the mock server, priced like muse-spark-1.3 to test the spend caps"}+ }+}diff --git a/bench/whole-repo/questions/funnel.json b/bench/whole-repo/questions/funnel.jsonnew file mode 100644index 0000000..3b9c76a--- /dev/null+++ b/bench/whole-repo/questions/funnel.json@@ -0,0 +1,130 @@+{+ "angular": {+ "dropped_applies": 4,+ "dropped_diff": 0,+ "dropped_duplicate": 3,+ "dropped_files": 0,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 0,+ "dropped_prefilter": 12,+ "dropped_window": 0,+ "fetched": 65,+ "kept": 40,+ "names_gold_path": 11,+ "passed": 46,+ "sampled": true+ },+ "elasticsearch": {+ "dropped_applies": 231,+ "dropped_diff": 0,+ "dropped_duplicate": 3,+ "dropped_files": 1,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 187,+ "dropped_prefilter": 71,+ "dropped_window": 0,+ "fetched": 579,+ "kept": 30,+ "names_gold_path": 2,+ "passed": 86,+ "sampled": true+ },+ "godot": {+ "dropped_applies": 32,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 2,+ "dropped_gold": 3,+ "dropped_issue": 0,+ "dropped_linked": 20,+ "dropped_prefilter": 28,+ "dropped_window": 0,+ "fetched": 237,+ "kept": 40,+ "names_gold_path": 7,+ "passed": 152,+ "sampled": true+ },+ "home-assistant": {+ "dropped_applies": 114,+ "dropped_diff": 0,+ "dropped_duplicate": 4,+ "dropped_files": 1,+ "dropped_gold": 8,+ "dropped_issue": 0,+ "dropped_linked": 15,+ "dropped_prefilter": 129,+ "dropped_window": 0,+ "fetched": 604,+ "kept": 40,+ "names_gold_path": 10,+ "passed": 333,+ "sampled": true+ },+ "keycloak": {+ "dropped_applies": 49,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 1,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 0,+ "dropped_prefilter": 139,+ "dropped_window": 0,+ "fetched": 455,+ "kept": 40,+ "names_gold_path": 12,+ "passed": 266,+ "sampled": true+ },+ "kubernetes": {+ "dropped_applies": 4,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 1,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 8,+ "dropped_prefilter": 26,+ "dropped_window": 0,+ "fetched": 89,+ "kept": 40,+ "names_gold_path": 23,+ "passed": 50,+ "sampled": true+ },+ "pytorch": {+ "dropped_applies": 17,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 0,+ "dropped_gold": 0,+ "dropped_issue": 1,+ "dropped_linked": 730,+ "dropped_prefilter": 24,+ "dropped_window": 0,+ "fetched": 860,+ "kept": 30,+ "names_gold_path": 9,+ "passed": 88,+ "sampled": true+ },+ "vscode": {+ "dropped_applies": 234,+ "dropped_diff": 0,+ "dropped_duplicate": 2,+ "dropped_files": 3,+ "dropped_gold": 37,+ "dropped_issue": 2,+ "dropped_linked": 71,+ "dropped_prefilter": 180,+ "dropped_window": 0,+ "fetched": 715,+ "kept": 30,+ "names_gold_path": 5,+ "passed": 186,+ "sampled": true+ }+}\ No newline at end of filediff --git a/bench/whole-repo/questions/questions-angular.jsonl b/bench/whole-repo/questions/questions-angular.jsonlnew file mode 100644index 0000000..1ab83d1--- /dev/null+++ b/bench/whole-repo/questions/questions-angular.jsonl@@ -0,0 +1,40 @@+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/defer/idle_scheduler.ts"], "id": "angular-70730", "issue_url": "https://github.com/angular/angular/issues/70728", "merged_at": "2026-09-17T17:14:12Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/70730", "repo": "angular/angular", "text_sha256": "9a5e39d48b2fabf2d974988c6f26e31cbd306ad4e3f3a295eea0bfd04407e426"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/metadata/directives.ts"], "id": "angular-70731", "issue_url": "https://github.com/angular/angular/issues/25797", "merged_at": "2026-09-17T17:16:12Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70731", "repo": "angular/angular", "text_sha256": "928588a04236312e270397daf4b96ff6149de41eb97000057ce29589f8264273"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/animation/interfaces.ts", "packages/core/src/animation/utils.ts"], "id": "angular-70793", "issue_url": "https://github.com/angular/angular/issues/70764", "merged_at": "2026-09-18T16:37:07Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70793", "repo": "angular/angular", "text_sha256": "113d3a98561700a2372035d4644c2c2aaefa2a08f8302f60e2156b488d1748d9"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/models.ts"], "id": "angular-70702", "issue_url": "https://github.com/angular/angular/issues/70698", "merged_at": "2026-09-21T17:08:03Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70702", "repo": "angular/angular", "text_sha256": "b0bac4ef040d4d9390cf503a5674aca73fec5fdf7c23bd3f473c55a9939293b6"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler/src/template/pipeline/src/phases/control_directives.ts"], "id": "angular-68290", "issue_url": "https://github.com/angular/angular/issues/68182", "merged_at": "2026-09-21T17:23:40Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/68290", "repo": "angular/angular", "text_sha256": "774631b9285284e9c9d12d2d04aa8f2541ab5f1c142d2f8f9150b2f4888fa8af"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["vscode-ng-language-service/server/src/embedded_support.ts"], "id": "angular-70857", "issue_url": "https://github.com/angular/angular/issues/65508", "merged_at": "2026-09-22T16:41:06Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70857", "repo": "angular/angular", "text_sha256": "b695fa2814a1d3b0580ef5321a4c9eaf2519af1e7dd419a93ea37f2e79f63334"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/platform-server/src/http.ts"], "id": "angular-70542", "issue_url": "https://github.com/angular/angular/issues/70540", "merged_at": "2026-09-22T21:01:43Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70542", "repo": "angular/angular", "text_sha256": "7d05006b46849087e5d216b6c08866fe06a715838ce8e7d2d862ab23f481e714"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["vscode-ng-language-service/client/src/client.ts"], "id": "angular-69657", "issue_url": "https://github.com/angular/angular/issues/69649", "merged_at": "2026-09-22T23:02:39Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/69657", "repo": "angular/angular", "text_sha256": "865bd2ab80c6fe2b18237d219ce9a629c178234b83da6ba317929b6e366218d7"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/url_tree.ts"], "id": "angular-70717", "issue_url": "https://github.com/angular/angular/issues/70716", "merged_at": "2026-09-23T15:51:06Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70717", "repo": "angular/angular", "text_sha256": "11ef6733bbc33f9f7d7451059b49106e946aeb4407bbb5b2dcb9335c464ec984"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/render3/hmr.ts"], "id": "angular-70674", "issue_url": "https://github.com/angular/angular/issues/70673", "merged_at": "2026-09-24T19:30:14Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70674", "repo": "angular/angular", "text_sha256": "4a0af3813e29c9f7acdb0dc07e95bf6cd5b256a5d602efadae41e9c99fb63ca2"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["vscode-ng-language-service/syntaxes/src/template-tag.ts", "vscode-ng-language-service/syntaxes/template-tag.json"], "id": "angular-70526", "issue_url": "https://github.com/angular/angular/issues/67679", "merged_at": "2026-09-25T23:00:57Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70526", "repo": "angular/angular", "text_sha256": "704f3c592394f4c395e033c8fe3fb75b6da755be56e8e43ba8edfbd3ca6e5cb6"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/directives/router_link.ts"], "id": "angular-70953", "issue_url": "https://github.com/angular/angular/issues/70908", "merged_at": "2026-09-25T23:56:12Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70953", "repo": "angular/angular", "text_sha256": "96c4206a92a3468ee4a52d52a323c805e50ab08bd6cbb4247c3d6cbd2b404a68"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["adev/src/app/editor/code-editor/code-editor.component.ts", "adev/src/app/editor/error-filename-handler.ts"], "id": "angular-70992", "issue_url": "https://github.com/angular/angular/issues/70990", "merged_at": "2026-09-28T19:00:24Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/70992", "repo": "angular/angular", "text_sha256": "c10e9392d0279033847a2d08e96f40b8e39c1d8854b8de2ffbd42017f31cdbab"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/recognize.ts", "packages/router/src/router_state.ts"], "id": "angular-70933", "issue_url": "https://github.com/angular/angular/issues/70932", "merged_at": "2026-09-28T19:09:23Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70933", "repo": "angular/angular", "text_sha256": "c5b9e4c9f32b2a9b52f58e1139fdae0ad20bb1123c6046b3d1176e31de3d31da"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/router_resource.ts"], "id": "angular-70975", "issue_url": "https://github.com/angular/angular/issues/70974", "merged_at": "2026-09-28T19:45:08Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/70975", "repo": "angular/angular", "text_sha256": "dbf83ff3ee6207c8e49f684b3462835445e17e452ded7a883e1edc2fed93ccbc"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/errors.ts", "packages/router/src/url_tree.ts"], "id": "angular-70257", "issue_url": "https://github.com/angular/angular/issues/69700", "merged_at": "2026-09-28T21:53:55Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70257", "repo": "angular/angular", "text_sha256": "ebe3aad43fecf156dd04162f5584c1de5b6e4f1cf1ff949341a17c3001046cd5"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/recognize.ts"], "id": "angular-70998", "issue_url": "https://github.com/angular/angular/issues/70997", "merged_at": "2026-09-28T22:59:56Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70998", "repo": "angular/angular", "text_sha256": "46fd3cefe93a406c7373e49ac4aa95f04ea973bdfb5b918687b00664e95a6c8c"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["adev/src/app/routing/navigation-entries/index.ts"], "id": "angular-71036", "issue_url": "https://github.com/angular/angular/issues/71035", "merged_at": "2026-09-29T19:25:42Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71036", "repo": "angular/angular", "text_sha256": "323d5e638f1c330af27b050c082408896d31bb66336df80e79e97a8c650e4e17"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts"], "id": "angular-70532", "issue_url": "https://github.com/angular/angular/issues/49335", "merged_at": "2026-09-29T22:04:40Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70532", "repo": "angular/angular", "text_sha256": "1c769943ce78244e4a2d6261047cccfc7900e49500d7ebc825b375bd136b39d8"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/platform-server/src/url.ts"], "id": "angular-71077", "issue_url": "https://github.com/angular/angular/issues/71076", "merged_at": "2026-09-30T14:19:33Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71077", "repo": "angular/angular", "text_sha256": "15f48cb77c845096a8578648a90626ab9c3eab5eadc2464e8684cbdf2167e93e"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/forms/signals/src/directive/form_field.ts", "packages/forms/signals/src/field/node.ts"], "id": "angular-71005", "issue_url": "https://github.com/angular/angular/issues/71004", "merged_at": "2026-10-01T18:32:31Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71005", "repo": "angular/angular", "text_sha256": "6c9ca4d9520905d9d15790143bdcdc6e22f082901f46f7f790a7806098d2795b"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/statemanager/navigation_state_manager.ts", "packages/router/src/statemanager/state_manager.ts"], "id": "angular-71130", "issue_url": "https://github.com/angular/angular/issues/71126", "merged_at": "2026-10-02T18:56:08Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71130", "repo": "angular/angular", "text_sha256": "614816d9807d8eb274f31b73ea485b3ea1313002ced6a578bcf39ab871ed80e4"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler/src/typecheck/ops/content_projection.ts"], "id": "angular-71173", "issue_url": "https://github.com/angular/angular/issues/71172", "merged_at": "2026-10-06T16:59:21Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71173", "repo": "angular/angular", "text_sha256": "3997c30940d162c4e42913cb5f3de8f85ecfc37d83a5c4ba9f512ef69c5f3f76"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/render3/after_render/manager.ts"], "id": "angular-70581", "issue_url": "https://github.com/angular/angular/issues/61715", "merged_at": "2026-10-06T22:01:44Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70581", "repo": "angular/angular", "text_sha256": "99acee7100fb9a9fd042decad00b22b7a5db1bce61e5f6c535bcc5f77307189a"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/errors.ts"], "id": "angular-71105", "issue_url": "https://github.com/angular/angular/issues/71092", "merged_at": "2026-10-07T13:56:20Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71105", "repo": "angular/angular", "text_sha256": "f95fb4e8e91dc77cb0152a0e303f7ef9741ec762bb3d38c36e122f84a923dc4b"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_control_flow_directive/index.ts", "packages/compiler-cli/src/ngtsc/typecheck/extended/checks/missing_structural_directive/index.ts"], "id": "angular-70944", "issue_url": "https://github.com/angular/angular/issues/70937", "merged_at": "2026-10-07T13:56:46Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70944", "repo": "angular/angular", "text_sha256": "739d4c609df1dc3092841cc99fee68f0be6d006016abdc660f12a3cdc0bdca52"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["adev/src/app/routing/navigation-entries/index.ts"], "id": "angular-71269", "issue_url": "https://github.com/angular/angular/issues/71238", "merged_at": "2026-10-12T22:14:09Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71269", "repo": "angular/angular", "text_sha256": "3cd12720e3485f946f1a1146d6798f057e537c0d8dcfec9ebe75daef570abfd7"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/defer/idle_scheduler.ts"], "id": "angular-70959", "issue_url": "https://github.com/angular/angular/issues/70941", "merged_at": "2026-10-12T23:05:12Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/70959", "repo": "angular/angular", "text_sha256": "74872d6aa2b5690648468d9f802910296b4a73d67f2377bcaf9ce4501c0d9456"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts"], "id": "angular-70985", "issue_url": "https://github.com/angular/angular/issues/70984", "merged_at": "2026-10-12T23:05:45Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70985", "repo": "angular/angular", "text_sha256": "24fa4557868c05a88375e8d81121d2c0d5aa0b9d3ccd2b64b5bfcd3f2193ec92"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler-cli/src/ngtsc/typecheck/src/context.ts", "packages/compiler-cli/src/ngtsc/typecheck/src/tcb_util.ts"], "id": "angular-71298", "issue_url": "https://github.com/angular/angular/issues/71291", "merged_at": "2026-10-12T23:09:26Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71298", "repo": "angular/angular", "text_sha256": "33d14d029f9dd7601baa8f5ea8c7c5b77df46ff2d8942f384e39acbfa64293d0"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler-cli/src/ngtsc/typecheck/src/oob.ts", "packages/compiler/src/typecheck/oob.ts", "packages/compiler/src/typecheck/ops/content_projection.ts"], "id": "angular-71289", "issue_url": "https://github.com/angular/angular/issues/71288", "merged_at": "2026-10-14T20:03:43Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71289", "repo": "angular/angular", "text_sha256": "a89197451751ea8564ebb3ef6d537acc4f7630537a7338436a6e428f30007a1e"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler/src/jit_compiler_facade.ts", "packages/compiler/src/util.ts"], "id": "angular-71118", "issue_url": "https://github.com/angular/angular/issues/71107", "merged_at": "2026-10-20T07:34:49Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71118", "repo": "angular/angular", "text_sha256": "fe3e8db63877c1ef6086f2876cbf4c2db3d169a104028179cb9afa21c171bd0e"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/render3/di.ts"], "id": "angular-71408", "issue_url": "https://github.com/angular/angular/issues/57390", "merged_at": "2026-10-20T07:43:56Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71408", "repo": "angular/angular", "text_sha256": "2085b0c37f26928f6d068d0b893689fdaed992ec8db4e45e5b7f9134747ddf23"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/core/src/hydration/i18n.ts"], "id": "angular-71426", "issue_url": "https://github.com/angular/angular/issues/71425", "merged_at": "2026-10-20T07:44:26Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71426", "repo": "angular/angular", "text_sha256": "4b38162175bc88c56a581ff7e0937b217965b18c82a0766c8118e6291dcb6900"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/compiler-cli/src/ngtsc/diagnostics/src/error_code.ts", "packages/compiler-cli/src/ngtsc/diagnostics/src/extended_template_diagnostic_name.ts", "packages/compiler-cli/src/ngtsc/typecheck/extended/BUILD.bazel", "packages/compiler-cli/src/ngtsc/typecheck/extended/index.ts"], "id": "angular-63705", "issue_url": "https://github.com/angular/angular/issues/61381", "merged_at": "2026-10-20T17:21:50Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/63705", "repo": "angular/angular", "text_sha256": "0388245376298b51824776fc98d5627c3ff9638e0ee680dae87b57108eb8a069"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/directives/router_link_active.ts"], "id": "angular-71349", "issue_url": "https://github.com/angular/angular/issues/71348", "merged_at": "2026-10-21T16:51:52Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71349", "repo": "angular/angular", "text_sha256": "41f55cc8677d0c284449a64bc4b57d0d6e6d4cd6eb33aa5909344bb761be568c"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/operators/check_guards.ts", "packages/router/src/operators/prioritized_guard_value.ts"], "id": "angular-71358", "issue_url": "https://github.com/angular/angular/issues/71357", "merged_at": "2026-10-21T17:03:47Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71358", "repo": "angular/angular", "text_sha256": "3f8ec97b00ef0672d30ebd0bd6abf98bfe86b961eb0bc6c9ba06b2b3e4af01f3"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/directives/router_link.ts"], "id": "angular-70963", "issue_url": "https://github.com/angular/angular/issues/71287", "merged_at": "2026-10-23T19:44:14Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/70963", "repo": "angular/angular", "text_sha256": "262116ff140ca15ce658eb43fdb760bb88164d918c7995882d2d519ffd36a1ce"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/router/src/statemanager/navigation_state_manager.ts"], "id": "angular-71552", "issue_url": "https://github.com/angular/angular/issues/71551", "merged_at": "2026-10-23T21:13:47Z", "names_gold_path": false, "pr_url": "https://github.com/angular/angular/pull/71552", "repo": "angular/angular", "text_sha256": "e25fdcff1ef05e691132e50ccb09bcb8bd8897ea89a1c80cd1a091b3646dcb00"}+{"S": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "gold": ["packages/upgrade/src/common/src/downgrade_component.ts", "packages/upgrade/src/common/src/downgrade_component_adapter.ts"], "id": "angular-71442", "issue_url": "https://github.com/angular/angular/issues/71441", "merged_at": "2026-10-25T14:38:21Z", "names_gold_path": true, "pr_url": "https://github.com/angular/angular/pull/71442", "repo": "angular/angular", "text_sha256": "940f1b72db5ece4fe3bf313b5c7be170b4826b3ca6f0fe54a86dc45a67ef80ad"}diff --git a/bench/whole-repo/questions/questions-elasticsearch.jsonl b/bench/whole-repo/questions/questions-elasticsearch.jsonlnew file mode 100644index 0000000..bbf822b--- /dev/null+++ b/bench/whole-repo/questions/questions-elasticsearch.jsonl@@ -0,0 +1,30 @@+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-159117", "issue_url": "https://github.com/elastic/elasticsearch/issues/159021", "merged_at": "2026-09-14T16:19:55Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159117", "repo": "elastic/elasticsearch", "text_sha256": "37a476f99fca22ba22cbb3b03f31f1c6c223f94604a6c26286a2c7bf5f522280"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/indices/IndicesRequestCache.java"], "id": "elasticsearch-157457", "issue_url": "https://github.com/elastic/elasticsearch/issues/157302", "merged_at": "2026-09-15T08:39:15Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/157457", "repo": "elastic/elasticsearch", "text_sha256": "b9360e246fb472d4096e28dd62e1db9636460ea3e3fe9958aa926cb05ee1426e"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-159102", "issue_url": "https://github.com/elastic/elasticsearch/issues/150440", "merged_at": "2026-09-15T13:13:16Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159102", "repo": "elastic/elasticsearch", "text_sha256": "b4b3e18dfed1852e6338d3fb403cd0e10deecf9a7e25e2f5accdc5e8fb18c4dd"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/MultiplexerTokenFilterFactory.java"], "id": "elasticsearch-158115", "issue_url": "https://github.com/elastic/elasticsearch/issues/158114", "merged_at": "2026-09-15T19:42:30Z", "names_gold_path": true, "pr_url": "https://github.com/elastic/elasticsearch/pull/158115", "repo": "elastic/elasticsearch", "text_sha256": "336e5669e8e3a578eeccf792b2f60a1d42ff32c1ec3e2186d862fc5744a4ffdb"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/gateway/AsyncShardFetch.java", "server/src/main/java/org/elasticsearch/gateway/GatewayAllocator.java"], "id": "elasticsearch-157766", "issue_url": "https://github.com/elastic/elasticsearch/issues/155449", "merged_at": "2026-09-16T15:26:01Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/157766", "repo": "elastic/elasticsearch", "text_sha256": "5663907b1983dc6d36037c8f60f202bc56d274e33699482e25312da9dbde11dc"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-159481", "issue_url": "https://github.com/elastic/elasticsearch/issues/158088", "merged_at": "2026-09-17T06:43:39Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159481", "repo": "elastic/elasticsearch", "text_sha256": "ff6eb2926c6767ee46704ef63448ab6f561d2bcc25224a52a26cd98fed442469"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-158825", "issue_url": "https://github.com/elastic/elasticsearch/issues/154988", "merged_at": "2026-09-18T08:13:04Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/158825", "repo": "elastic/elasticsearch", "text_sha256": "dda6ce2969f36671b144b9c5ad8d29b16d7e4acf1f4b25251a7496396669a534"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/index/mapper/DateFieldMapper.java"], "id": "elasticsearch-159718", "issue_url": "https://github.com/elastic/elasticsearch/issues/110726", "merged_at": "2026-09-22T08:03:46Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159718", "repo": "elastic/elasticsearch", "text_sha256": "de8556aadccde01bd3a3f17289ada68bbd7675499dbc348f4009b58ba9b17580"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/EsqlCapabilities.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/analysis/Analyzer.java"], "id": "elasticsearch-159610", "issue_url": "https://github.com/elastic/elasticsearch/issues/159602", "merged_at": "2026-09-22T11:53:06Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159610", "repo": "elastic/elasticsearch", "text_sha256": "eb5d62b9356ec54e872459aa061fa54b3de1801809d2e6852333f000dd701914"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/view/ViewService.java"], "id": "elasticsearch-160080", "issue_url": "https://github.com/elastic/elasticsearch/issues/147019", "merged_at": "2026-09-24T08:45:55Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160080", "repo": "elastic/elasticsearch", "text_sha256": "12b776501991c51928b3e05b29790c01d5f71bde57542d077f4521be3b2b8275"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/inference/build.gradle"], "id": "elasticsearch-160347", "issue_url": "https://github.com/elastic/elasticsearch/issues/145662", "merged_at": "2026-09-25T21:27:05Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160347", "repo": "elastic/elasticsearch", "text_sha256": "03ca1a40607b37bd48383c954148522a00a1dcf3398965798c0c7a166be09e36"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/NettyAllocator.java", "modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/TrashingByteBufAllocator.java"], "id": "elasticsearch-160288", "issue_url": "https://github.com/elastic/elasticsearch/issues/160186", "merged_at": "2026-09-26T17:42:47Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160288", "repo": "elastic/elasticsearch", "text_sha256": "18d2368e494625ed2439ec4f26a4276b903ff9bbfa93568b0acea6f2c8fe2054"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/Magnitude.java"], "id": "elasticsearch-160437", "issue_url": "https://github.com/elastic/elasticsearch/issues/160373", "merged_at": "2026-09-28T11:38:58Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160437", "repo": "elastic/elasticsearch", "text_sha256": "1e7e049236e35ba56bcd9270e45e37fdae88cc90bdfccdb2a4375f2d8e4b8375"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/action/search/SearchQueryThenFetchAsyncAction.java"], "id": "elasticsearch-159248", "issue_url": "https://github.com/elastic/elasticsearch/issues/158991", "merged_at": "2026-09-28T21:20:32Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159248", "repo": "elastic/elasticsearch", "text_sha256": "70a17aedc249486da0e7026105ff268053857e97811309a6544716f56e31da4b"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/queries/InferenceQueryUtils.java"], "id": "elasticsearch-160207", "issue_url": "https://github.com/elastic/elasticsearch/issues/160203", "merged_at": "2026-09-29T06:51:56Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160207", "repo": "elastic/elasticsearch", "text_sha256": "acc1dd38e116587e62f6f1b2d3716b32b29accf4504ccefa7054a4dee455794a"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/EsqlCapabilities.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/core/expression/function/Function.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/core/expression/predicate/BinaryPredicate.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/AggregateFunction.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/promql/function/PromqlFunctionDefinition.java"], "id": "elasticsearch-157650", "issue_url": "https://github.com/elastic/elasticsearch/issues/151972", "merged_at": "2026-09-29T13:00:11Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/157650", "repo": "elastic/elasticsearch", "text_sha256": "6f7df9ad83d54656d8a2a1b3ab8e590f22cd303109aa9248a37909c995e6b0bf"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/indices/breaker/HierarchyCircuitBreakerService.java"], "id": "elasticsearch-160450", "issue_url": "https://github.com/elastic/elasticsearch/issues/160449", "merged_at": "2026-10-02T12:27:32Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160450", "repo": "elastic/elasticsearch", "text_sha256": "ea055e06ec6ce5063cf699d285815e33e0c454dcdb7343af816c02d844b25d0b"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["libs/x-content/impl/src/main/java/org/elasticsearch/xcontent/provider/json/JsonXContentGenerator.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/PositionToXContent.java"], "id": "elasticsearch-160695", "issue_url": "https://github.com/elastic/elasticsearch/issues/160694", "merged_at": "2026-10-02T14:45:33Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/160695", "repo": "elastic/elasticsearch", "text_sha256": "d6f863f5386b55cd596c610eb3aba537960d2f7a58173070c4681749bb4ce70e"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogramMerger.java"], "id": "elasticsearch-161002", "issue_url": "https://github.com/elastic/elasticsearch/issues/160987", "merged_at": "2026-10-05T11:45:10Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161002", "repo": "elastic/elasticsearch", "text_sha256": "81c858f18bfc2d10c3f3c049bde7354a63e952de5294290cf1620ca78b050973"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/extras/plugins/microsoft-graph-authz/src/main/java/org/elasticsearch/xpack/security/authz/microsoft/MicrosoftGraphAuthzRealm.java"], "id": "elasticsearch-161254", "issue_url": "https://github.com/elastic/elasticsearch/issues/161197", "merged_at": "2026-10-08T09:10:55Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161254", "repo": "elastic/elasticsearch", "text_sha256": "06376e266c5163e347c9a3312d1ce0d82a76a05a6367cb198b34255e56d143b4"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToGeohash.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToGeohex.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToGeotile.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/type/EsqlDataTypeConverter.java"], "id": "elasticsearch-161242", "issue_url": "https://github.com/elastic/elasticsearch/issues/160230", "merged_at": "2026-10-08T14:55:37Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161242", "repo": "elastic/elasticsearch", "text_sha256": "a0e8d5a23ef7f10e62a6aea2533df39b39cd13d641ee12a4545f5911dd0d7f2a"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/search/aggregations/metrics/TopHitsAggregator.java"], "id": "elasticsearch-159231", "issue_url": "https://github.com/elastic/elasticsearch/issues/158722", "merged_at": "2026-10-09T13:42:41Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/159231", "repo": "elastic/elasticsearch", "text_sha256": "7a572e1eaef682310a9486c1b17456a2030b5ed92c107fc5071e0e4244a39ab6"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/DriverContext.java", "x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/Warnings.java"], "id": "elasticsearch-161338", "issue_url": "https://github.com/elastic/elasticsearch/issues/148398", "merged_at": "2026-10-12T07:38:59Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161338", "repo": "elastic/elasticsearch", "text_sha256": "415a825a97d17649b875e53e13616cea8125197cad4a61409cf4d6c862c46ff1"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/user/InternalUsers.java", "x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/Security.java"], "id": "elasticsearch-160754", "issue_url": "https://github.com/elastic/elasticsearch/issues/139158", "merged_at": "2026-10-12T17:08:16Z", "names_gold_path": true, "pr_url": "https://github.com/elastic/elasticsearch/pull/160754", "repo": "elastic/elasticsearch", "text_sha256": "6fd3b115c18f78eb05250a49315c6a6ad9d80d8742a5b3f91f62f28d170c0475"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-161980", "issue_url": "https://github.com/elastic/elasticsearch/issues/154059", "merged_at": "2026-10-15T08:35:38Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161980", "repo": "elastic/elasticsearch", "text_sha256": "0a04729d24b42dd43f8850aa055698bbde449cd521077fd8a6353d51404f370b"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/index/search/stats/FieldUsageStats.java", "server/src/main/java/org/elasticsearch/index/search/stats/ShardFieldUsageTracker.java", "server/src/main/java/org/elasticsearch/rest/action/admin/indices/RestFieldUsageStatsAction.java", "server/src/main/java/org/elasticsearch/search/internal/FieldUsageTrackingDirectoryReader.java"], "id": "elasticsearch-161426", "issue_url": "https://github.com/elastic/elasticsearch/issues/161287", "merged_at": "2026-10-16T10:23:06Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161426", "repo": "elastic/elasticsearch", "text_sha256": "63d1daf06a9b520adc5be5c6c602a74c9ba0a32b514711dc004eaa4db980ab07"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["muted-tests.yml"], "id": "elasticsearch-161973", "issue_url": "https://github.com/elastic/elasticsearch/issues/147853", "merged_at": "2026-10-16T10:42:51Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161973", "repo": "elastic/elasticsearch", "text_sha256": "a1a19c2301afe4c0e4e173fe5d8ae1f822f94a5045ccb21e10808346dadb529b"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/formatter/arrow/ArrowResponse.java", "x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/formatter/arrow/BlockArrowFormatter.java"], "id": "elasticsearch-162376", "issue_url": "https://github.com/elastic/elasticsearch/issues/153438", "merged_at": "2026-10-21T15:43:27Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/162376", "repo": "elastic/elasticsearch", "text_sha256": "f2cc2946660daeb5e1484d154bf64b17470b0d1d9f782636007e8bfdac86a262"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/job/TransportDeleteExpiredDataAction.java", "x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/retention/UnusedStatsRemover.java"], "id": "elasticsearch-163140", "issue_url": "https://github.com/elastic/elasticsearch/issues/147656", "merged_at": "2026-10-23T14:59:26Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/163140", "repo": "elastic/elasticsearch", "text_sha256": "f5f03d6faf6b14e65386c08eb0f3239d339844a298f7a3e2e3797b14f560ae41"}+{"S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "gold": ["server/src/main/java/org/elasticsearch/index/termvectors/TermVectorsService.java"], "id": "elasticsearch-161894", "issue_url": "https://github.com/elastic/elasticsearch/issues/161273", "merged_at": "2026-10-23T20:26:39Z", "names_gold_path": false, "pr_url": "https://github.com/elastic/elasticsearch/pull/161894", "repo": "elastic/elasticsearch", "text_sha256": "8338b6f852817f023671d672f21cc289987a288a4c0c8cd99631005dce6e74a1"}diff --git a/bench/whole-repo/questions/questions-godot.jsonl b/bench/whole-repo/questions/questions-godot.jsonlnew file mode 100644index 0000000..83afd6f--- /dev/null+++ b/bench/whole-repo/questions/questions-godot.jsonl@@ -0,0 +1,40 @@+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/rendering/renderer_rd/renderer_canvas_render_rd.cpp"], "id": "godot-122653", "issue_url": "https://github.com/godotengine/godot/issues/122648", "merged_at": "2026-09-16T16:22:29Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/122653", "repo": "godotengine/godot", "text_sha256": "a9ef287dfdfbc3877d6dc86e72419fe9dcfff0f8dc8855ba263b9ea9d06161ec"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/docks/filesystem_dock.cpp", "editor/docks/filesystem_dock.h"], "id": "godot-122709", "issue_url": "https://github.com/godotengine/godot/issues/122663", "merged_at": "2026-09-17T18:03:49Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/122709", "repo": "godotengine/godot", "text_sha256": "4faa8b4a27ddb030f7848e263e99f6d3b3466610ec9ba3d3b43c915c2bb5255c"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/debugger/editor_debugger_inspector.cpp"], "id": "godot-123156", "issue_url": "https://github.com/godotengine/godot/issues/123042", "merged_at": "2026-09-17T18:03:49Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123156", "repo": "godotengine/godot", "text_sha256": "f2ecb2d0aa5d99d6bedf064db8d685a75695ee413e5a7e639a1e32bc267fd9ea"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/export/android_sdk_manager.cpp", "editor/export/android_sdk_manager.h", "platform/android/export/export.cpp", "platform/android/export/export_plugin.cpp", "platform/android/export/export_plugin.h"], "id": "godot-123585", "issue_url": "https://github.com/godotengine/godot/issues/123492", "merged_at": "2026-09-18T15:48:03Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123585", "repo": "godotengine/godot", "text_sha256": "1ba3370e5abef6867b01976adc4a93670fb4d7ee2d610e92986197f7399d64fb"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp"], "id": "godot-123656", "issue_url": "https://github.com/godotengine/godot/issues/123626", "merged_at": "2026-09-21T15:07:11Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123656", "repo": "godotengine/godot", "text_sha256": "fc1495c13b12f98cf2546d1a30798e1167db0d890f7c85ec36f3b430f32b94df"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/script/script_editor_plugin.cpp", "modules/gdscript/gdscript.cpp", "modules/gdscript/gdscript.h"], "id": "godot-116368", "issue_url": "https://github.com/godotengine/godot/issues/66381", "merged_at": "2026-09-21T15:07:12Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/116368", "repo": "godotengine/godot", "text_sha256": "7592ec932c94d760c695b15e565f7a93deb978687afbd55f5dec22782bb7a188"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["platform/linuxbsd/wayland/wayland_thread.cpp"], "id": "godot-123580", "issue_url": "https://github.com/godotengine/godot/issues/123304", "merged_at": "2026-09-22T15:21:21Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/123580", "repo": "godotengine/godot", "text_sha256": "cf9d7fe3010f80d31270f707d660979a49aec6c817456216a69aa941f58e59ba"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/docks/scene_tree_dock.cpp"], "id": "godot-123637", "issue_url": "https://github.com/godotengine/godot/issues/123573", "merged_at": "2026-09-22T15:21:21Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123637", "repo": "godotengine/godot", "text_sha256": "cd8953a13f5f2d28687b11faad3e45ffbcc79b98bf52a1d2e33629f7fe7bfdd0"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/xr/xr_vrs.cpp"], "id": "godot-123795", "issue_url": "https://github.com/godotengine/godot/issues/121268", "merged_at": "2026-09-24T17:29:04Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/123795", "repo": "godotengine/godot", "text_sha256": "30a7423eff32df0c4cbcc807bdface5440cb4700eb15a813080b62871e4befd6"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["drivers/gles3/shaders/scene.glsl", "servers/rendering/renderer_rd/shaders/scene_forward_lights_inc.glsl"], "id": "godot-123733", "issue_url": "https://github.com/godotengine/godot/issues/121980", "merged_at": "2026-09-26T15:13:20Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123733", "repo": "godotengine/godot", "text_sha256": "5f6f15eee6b5bdf29bd8621770673780afe461de1847cdf8f0cb931865406b75"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/gui/control.cpp"], "id": "godot-116330", "issue_url": "https://github.com/godotengine/godot/issues/66651", "merged_at": "2026-09-27T16:30:19Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/116330", "repo": "godotengine/godot", "text_sha256": "3e2a89b7c4943e3f3372895378610ba1857511ad631d05bb88cc294cc24c907e"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/editor_log.cpp"], "id": "godot-121149", "issue_url": "https://github.com/godotengine/godot/issues/119357", "merged_at": "2026-09-27T16:30:19Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/121149", "repo": "godotengine/godot", "text_sha256": "9aaf9c835b064e2ff6b43af0ab9134623aa6f175acdc7e8636449db8435cd2d1"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/gui/code_editor.cpp", "modules/gdscript/gdscript_editor.cpp"], "id": "godot-123037", "issue_url": "https://github.com/godotengine/godot/issues/122821", "merged_at": "2026-09-28T18:37:39Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123037", "repo": "godotengine/godot", "text_sha256": "a45e576d2640d5a3dc30f8f8bbeb952699e2221226bf89f0357d8431dbca5f53"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/rendering/renderer_rd/shaders/forward_clustered/scene_forward_clustered.glsl"], "id": "godot-123882", "issue_url": "https://github.com/godotengine/godot/issues/123422", "merged_at": "2026-09-28T18:37:39Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123882", "repo": "godotengine/godot", "text_sha256": "6acd93e8cfe5ce227ee977ce150b24636728cb6e90a321899c76bca07fad5c6b"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/export/export_template_manager.cpp"], "id": "godot-124051", "issue_url": "https://github.com/godotengine/godot/issues/124050", "merged_at": "2026-10-01T15:58:29Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124051", "repo": "godotengine/godot", "text_sha256": "17a5f0b66cdac41ed0e4e9f46edfeb8c24c1803a25c42ac7e6b4a82e96e2a173"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/inspector/editor_properties.cpp"], "id": "godot-124081", "issue_url": "https://github.com/godotengine/godot/issues/124077", "merged_at": "2026-10-05T15:59:31Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124081", "repo": "godotengine/godot", "text_sha256": "31c82461e1506a0c73ebdfc39288a39c598bf71c570822e68fdd98fa06358f8c"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/docks/inspector_dock.cpp"], "id": "godot-124155", "issue_url": "https://github.com/godotengine/godot/issues/123896", "merged_at": "2026-10-05T15:59:31Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/124155", "repo": "godotengine/godot", "text_sha256": "02ad3cdcffb84bcc97216ffcde4d88a4817949ef9e9cb40f17388e85dbecaa14"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/gui/tree.cpp"], "id": "godot-116252", "issue_url": "https://github.com/godotengine/godot/issues/116233", "merged_at": "2026-10-05T15:59:32Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/116252", "repo": "godotengine/godot", "text_sha256": "eb5a70eddbf69e684a52f16fdb89a79ee2905cf01bf3c977b2db9245db77c2bf"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["platform/linuxbsd/x11/display_server_x11.cpp"], "id": "godot-124148", "issue_url": "https://github.com/godotengine/godot/issues/124146", "merged_at": "2026-10-06T00:19:22Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124148", "repo": "godotengine/godot", "text_sha256": "334b0415c1aecc4fd47b2f323860346658cb377be88165b7593683c2162046d8"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/editor_node.cpp", "editor/editor_node.h", "editor/script/script_editor_plugin.cpp"], "id": "godot-124140", "issue_url": "https://github.com/godotengine/godot/issues/123228", "merged_at": "2026-10-06T00:19:23Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124140", "repo": "godotengine/godot", "text_sha256": "bea1663c7537dde5eac6bfb12d1029c58496b679b182290bf3faebdd2dcd5fff"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/script/script_text_editor.cpp"], "id": "godot-124170", "issue_url": "https://github.com/godotengine/godot/issues/124154", "merged_at": "2026-10-06T17:11:06Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124170", "repo": "godotengine/godot", "text_sha256": "fb10dbac00e5ba656674d6afcacb3d60d411085be06f7db2be15cad664ba360a"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/inspector/editor_properties.cpp"], "id": "godot-124174", "issue_url": "https://github.com/godotengine/godot/issues/124161", "merged_at": "2026-10-06T17:11:06Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124174", "repo": "godotengine/godot", "text_sha256": "64326121b9a2ac0965d20226a25bfd9d115462188ab3bd01507b1b9498f913db"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/resources/material.cpp"], "id": "godot-124201", "issue_url": "https://github.com/godotengine/godot/issues/124195", "merged_at": "2026-10-07T14:25:40Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/124201", "repo": "godotengine/godot", "text_sha256": "25782da80816049f135a54a9271b98438b7fec11fa45324615e105c209afcc52"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/export/editor_export_platform_apple_embedded.cpp", "editor/export/editor_export_platform_apple_embedded.h", "platform/ios/export/export_plugin.cpp", "platform/ios/export/export_plugin.h"], "id": "godot-123801", "issue_url": "https://github.com/godotengine/godot/issues/123800", "merged_at": "2026-10-08T18:43:21Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/123801", "repo": "godotengine/godot", "text_sha256": "8c8dac36ac5b2d01fab16d2c6f3234d5be36da3a19a2d34a01272b7c5adfd096"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["modules/gdscript/gdscript_analyzer.cpp"], "id": "godot-124274", "issue_url": "https://github.com/godotengine/godot/issues/124254", "merged_at": "2026-10-08T18:43:21Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124274", "repo": "godotengine/godot", "text_sha256": "678dee002ad6e9b741907dc9c61e719711bb5fd0841a1ea9c5654a7ed136febd"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["drivers/gles3/rasterizer_scene_gles3.cpp"], "id": "godot-124310", "issue_url": "https://github.com/godotengine/godot/issues/119317", "merged_at": "2026-10-09T14:41:47Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124310", "repo": "godotengine/godot", "text_sha256": "61ce24162ee94206eaf01bb252ab2c97dacf41808b84f5d02c22fffbfd45d3d1"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/debugger/view_3d_controller.cpp"], "id": "godot-124175", "issue_url": "https://github.com/godotengine/godot/issues/122185", "merged_at": "2026-10-09T14:41:48Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124175", "repo": "godotengine/godot", "text_sha256": "81ec4f4f3295e40d782863fbaf0e9834ecda45a0cec68c8b71e6780664a49529"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/plugins/editor_plugin_settings.cpp", "editor/scene/scene_tree_editor.cpp"], "id": "godot-123764", "issue_url": "https://github.com/godotengine/godot/issues/123753", "merged_at": "2026-10-12T14:33:03Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123764", "repo": "godotengine/godot", "text_sha256": "19f34e00d5885ec610f63dfc3d9fb0e1ebd0882aa2c276f06ee71ac3eecad074"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/debugger/editor_debugger_inspector.cpp", "editor/debugger/editor_debugger_tree.cpp"], "id": "godot-124272", "issue_url": "https://github.com/godotengine/godot/issues/104717", "merged_at": "2026-10-14T19:52:02Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124272", "repo": "godotengine/godot", "text_sha256": "e488fd48f040645686970e40862b13e4c9975097ec1b652d26372ad7d701a389"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["platform/linuxbsd/wayland/display_server_wayland.cpp", "platform/linuxbsd/wayland/wayland_thread.cpp", "platform/linuxbsd/wayland/wayland_thread.h"], "id": "godot-122673", "issue_url": "https://github.com/godotengine/godot/issues/122638", "merged_at": "2026-10-14T19:52:03Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/122673", "repo": "godotengine/godot", "text_sha256": "caebc0f1d75aa3057228fef66bdd0761aed9288aed666a1b3002ed784ca0e2e8"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["drivers/gles3/rasterizer_scene_gles3.cpp"], "id": "godot-109404", "issue_url": "https://github.com/godotengine/godot/issues/99549", "merged_at": "2026-10-15T12:25:42Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/109404", "repo": "godotengine/godot", "text_sha256": "adb18afaf977373c1d3bfd49d7ea62492deea3d391a6b1bc8d07b0500a00926d"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/import/3d/resource_importer_obj.cpp", "editor/import/3d/resource_importer_scene.cpp"], "id": "godot-122494", "issue_url": "https://github.com/godotengine/godot/issues/117752", "merged_at": "2026-10-16T16:38:11Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/122494", "repo": "godotengine/godot", "text_sha256": "f5d240ad351309c351fa54a6597e5b0af71fdf299db400c866baae71c76646c3"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/gui/tree.cpp"], "id": "godot-123625", "issue_url": "https://github.com/godotengine/godot/issues/123609", "merged_at": "2026-10-16T16:38:12Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/123625", "repo": "godotengine/godot", "text_sha256": "1bfd0405007160983cbc333d057a53c29c2cb807a6710030a616901f34fcf7fb"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["platform/macos/godot_main_macos.mm"], "id": "godot-124624", "issue_url": "https://github.com/godotengine/godot/issues/124490", "merged_at": "2026-10-19T16:51:02Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/124624", "repo": "godotengine/godot", "text_sha256": "1d7c513c0abc57c284278d2f2bdbe2ee200d1ac1160a72c3afee94c559d6fd12"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["core/io/plist.cpp", "core/io/plist.h"], "id": "godot-124386", "issue_url": "https://github.com/godotengine/godot/issues/124317", "merged_at": "2026-10-19T20:57:31Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124386", "repo": "godotengine/godot", "text_sha256": "c4c881cde0f4b7c288d801862a0feb04e47d558402dc0935fb57b2c4128ef310"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["editor/editor_node.h", "editor/gui/window_wrapper.cpp"], "id": "godot-124565", "issue_url": "https://github.com/godotengine/godot/issues/79668", "merged_at": "2026-10-19T20:57:31Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124565", "repo": "godotengine/godot", "text_sha256": "3da8a11fb18ca9ea508987f214cf955fb7c5d19351cbdead70c3d9718959a83e"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/rendering/renderer_rd/forward_clustered/render_forward_clustered.cpp"], "id": "godot-124706", "issue_url": "https://github.com/godotengine/godot/issues/123910", "merged_at": "2026-10-20T21:22:56Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124706", "repo": "godotengine/godot", "text_sha256": "2853c348a7e1bf7d9c9393e976a6a0818f98afdf15b67eeb5cc17926a5d37ca5"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["scene/property_list_helper.cpp"], "id": "godot-124740", "issue_url": "https://github.com/godotengine/godot/issues/124712", "merged_at": "2026-10-21T17:28:23Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124740", "repo": "godotengine/godot", "text_sha256": "c50a09ffea531c01eb2eca6abffff4047e6f8dedd2fe79f9619e8bc1fb3f2e67"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["modules/openxr/openxr_api.cpp"], "id": "godot-124776", "issue_url": "https://github.com/godotengine/godot/issues/124496", "merged_at": "2026-10-22T18:18:28Z", "names_gold_path": true, "pr_url": "https://github.com/godotengine/godot/pull/124776", "repo": "godotengine/godot", "text_sha256": "46a762f4ef17e630411fa4753a5e2bb115163fad5408e1d41db4b05e766f6592"}+{"S": "2f698aa5fe31d0be68f205ec41aec9365081d364", "gold": ["servers/rendering/renderer_rd/renderer_scene_render_rd.cpp"], "id": "godot-124778", "issue_url": "https://github.com/godotengine/godot/issues/124769", "merged_at": "2026-10-22T18:18:28Z", "names_gold_path": false, "pr_url": "https://github.com/godotengine/godot/pull/124778", "repo": "godotengine/godot", "text_sha256": "0abe1f33351f9525a3fee602d7d4ab20c1ec701f750134203f3ad5d9ada2a8d5"}diff --git a/bench/whole-repo/questions/questions-home-assistant.jsonl b/bench/whole-repo/questions/questions-home-assistant.jsonlnew file mode 100644index 0000000..d9dbdd5--- /dev/null+++ b/bench/whole-repo/questions/questions-home-assistant.jsonl@@ -0,0 +1,40 @@+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/alexa_devices/manifest.json"], "id": "home-assistant-182204", "issue_url": "https://github.com/home-assistant/core/issues/174422", "merged_at": "2026-09-14T16:25:07Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182204", "repo": "home-assistant/core", "text_sha256": "23c3b325233d2e7675a1a3eef39d695e3b743116f0773c1c01ad58926b574465"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/pjlink/media_player.py"], "id": "home-assistant-182186", "issue_url": "https://github.com/home-assistant/core/issues/182027", "merged_at": "2026-09-15T15:48:54Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182186", "repo": "home-assistant/core", "text_sha256": "84ff5ed40760698f8e622dbfa1ff95222dcc15ff219bedb63104f2ffbe74612a"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/helpers/intent.py", "homeassistant/helpers/llm.py"], "id": "home-assistant-179527", "issue_url": "https://github.com/home-assistant/core/issues/145525", "merged_at": "2026-09-15T16:05:50Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/179527", "repo": "home-assistant/core", "text_sha256": "532d144ddcd0c7bd1e668b63ef6219268e3ac5bde5ecf777855a606f0fb6e553"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/imap/config_flow.py"], "id": "home-assistant-182377", "issue_url": "https://github.com/home-assistant/core/issues/182348", "merged_at": "2026-09-18T09:14:11Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182377", "repo": "home-assistant/core", "text_sha256": "3096b9ec63bf33b38faaf1b00cad4c93fc5ef5828d303628bb1b0e926757d347"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/filter/sensor.py"], "id": "home-assistant-182600", "issue_url": "https://github.com/home-assistant/core/issues/182489", "merged_at": "2026-09-18T18:18:33Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182600", "repo": "home-assistant/core", "text_sha256": "5e6cf31e32a642d374846d1f3837a3b852401376f87a5f521ba967f08699cb76"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/hive/__init__.py", "homeassistant/components/hive/binary_sensor.py", "homeassistant/components/hive/const.py"], "id": "home-assistant-182765", "issue_url": "https://github.com/home-assistant/core/issues/182753", "merged_at": "2026-09-20T13:50:23Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182765", "repo": "home-assistant/core", "text_sha256": "085a2894661b869a297245a4b29c3174b68985a5edc30c5cdf1878c119b89388"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/homematicip_cloud/hap.py"], "id": "home-assistant-182601", "issue_url": "https://github.com/home-assistant/core/issues/182484", "merged_at": "2026-09-21T11:30:42Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182601", "repo": "home-assistant/core", "text_sha256": "4b3c5e1d68080fa6d8479e6893380d9b036264fe2a927fee9429e09b9c22c2f6"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/broadlink/const.py", "homeassistant/components/broadlink/switch.py", "homeassistant/components/broadlink/updater.py"], "id": "home-assistant-183058", "issue_url": "https://github.com/home-assistant/core/issues/149679", "merged_at": "2026-09-24T18:11:06Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183058", "repo": "home-assistant/core", "text_sha256": "028f69b7557bb2b345e660a4ff494bf3876f63740ed11310a3b716fcf92e7344"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/auth/models.py", "homeassistant/components/auth/__init__.py", "homeassistant/components/auth/login_flow.py"], "id": "home-assistant-181957", "issue_url": "https://github.com/home-assistant/core/issues/181542", "merged_at": "2026-09-26T14:21:46Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/181957", "repo": "home-assistant/core", "text_sha256": "e09ea932a6beeee7a5a4e013dbcd8c059d51d5fd739a663e656a5fa055eb0b5a"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/samsung_exlink/manifest.json"], "id": "home-assistant-183347", "issue_url": "https://github.com/home-assistant/core/issues/183331", "merged_at": "2026-09-27T21:12:19Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183347", "repo": "home-assistant/core", "text_sha256": "9afa173defb633f260d4469e023ffeba54d92ce3703e99d62781ee0b7ab1ec23"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/myuplink/select.py"], "id": "home-assistant-182602", "issue_url": "https://github.com/home-assistant/core/issues/182530", "merged_at": "2026-09-29T15:59:35Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182602", "repo": "home-assistant/core", "text_sha256": "ed92bc5e126e96ebd1f76b6de6a9b5018a1320420ec911f475fa518741e78ad1"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/unifiprotect/event.py"], "id": "home-assistant-183372", "issue_url": "https://github.com/home-assistant/core/issues/183356", "merged_at": "2026-09-30T09:29:22Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183372", "repo": "home-assistant/core", "text_sha256": "36aee1854728cd0fc2c961b62bad726df294f07756868e554d860502bd133e30"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/mikrotik/coordinator.py"], "id": "home-assistant-183904", "issue_url": "https://github.com/home-assistant/core/issues/182935", "merged_at": "2026-10-01T18:50:51Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183904", "repo": "home-assistant/core", "text_sha256": "e894744019851b3e9f7da5702edc28d9a317c6ce06d54c0b81701458747f804c"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/__init__.py"], "id": "home-assistant-183909", "issue_url": "https://github.com/home-assistant/core/issues/183803", "merged_at": "2026-10-01T18:57:19Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183909", "repo": "home-assistant/core", "text_sha256": "0134bb42c824f0896027d9064fefb093601120a0d018583b52e77e70813c0f7e"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/philips_js/media_player.py"], "id": "home-assistant-183207", "issue_url": "https://github.com/home-assistant/core/issues/182011", "merged_at": "2026-10-02T09:44:53Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/183207", "repo": "home-assistant/core", "text_sha256": "43762dac86665e39f39204ebdef93ea48148d85c4493e98b87b1d8f804e8033e"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/melcloud_home/common.py", "homeassistant/components/melcloud_home/quality_scale.yaml", "homeassistant/components/melcloud_home/strings.json"], "id": "home-assistant-184029", "issue_url": "https://github.com/home-assistant/core/issues/184016", "merged_at": "2026-10-02T18:10:43Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184029", "repo": "home-assistant/core", "text_sha256": "c59308d3f7e157cac6642c1572e8cad223525210c3455fe476256d95bb3b2935"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/ambient_network/config_flow.py", "homeassistant/components/ambient_network/strings.json"], "id": "home-assistant-184143", "issue_url": "https://github.com/home-assistant/core/issues/179169", "merged_at": "2026-10-03T17:58:10Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184143", "repo": "home-assistant/core", "text_sha256": "c9b4974cc51022ff8755e39d6a558d8f877345d83deaf7ebce6d69944b410a21"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/acaia/button.py", "homeassistant/components/acaia/quality_scale.yaml"], "id": "home-assistant-184024", "issue_url": "https://github.com/home-assistant/core/issues/184008", "merged_at": "2026-10-05T09:09:19Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184024", "repo": "home-assistant/core", "text_sha256": "959889d7986c1d0c3979ea0e0e587ecdae70d8e3b841bedcfb2df5262df13e7d"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/ovhcloud_ai_endpoints/config_flow.py"], "id": "home-assistant-184249", "issue_url": "https://github.com/home-assistant/core/issues/184114", "merged_at": "2026-10-05T11:07:29Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184249", "repo": "home-assistant/core", "text_sha256": "ea4c73a4da221998cfef754e794e27f5aaf06907a5c52cf62531c9e4050c9d8a"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/proxmoxve/sensor.py"], "id": "home-assistant-184374", "issue_url": "https://github.com/home-assistant/core/issues/184174", "merged_at": "2026-10-06T06:32:14Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184374", "repo": "home-assistant/core", "text_sha256": "4009d73a79bd5d9e1608d5aea01d0a2e079f212cb2e74088cfee2bf61c499e5d"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/plaato/__init__.py", "homeassistant/components/plaato/config_flow.py", "homeassistant/components/plaato/const.py", "homeassistant/components/plaato/coordinator.py", "homeassistant/components/plaato/strings.json"], "id": "home-assistant-184376", "issue_url": "https://github.com/home-assistant/core/issues/168843", "merged_at": "2026-10-06T06:34:54Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/184376", "repo": "home-assistant/core", "text_sha256": "e6967fffb725ae96920a672d23359c5baa1b4da20c162e527d12f1adcf1bcb1c"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/risco/config_flow.py", "homeassistant/components/risco/const.py", "homeassistant/components/risco/coordinator.py", "homeassistant/components/risco/strings.json"], "id": "home-assistant-184386", "issue_url": "https://github.com/home-assistant/core/issues/168844", "merged_at": "2026-10-06T07:41:39Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/184386", "repo": "home-assistant/core", "text_sha256": "042f667c709d36562e664b8d382dd84ac4eddc9ecf3e9fc0370bce0e5837d283"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/telegram_bot/bot.py"], "id": "home-assistant-184566", "issue_url": "https://github.com/home-assistant/core/issues/178525", "merged_at": "2026-10-07T02:23:09Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/184566", "repo": "home-assistant/core", "text_sha256": "059d79be074c6e90567e006cf789ca86b2548e88f5efdf1ec6e4993cae5ed34d"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/jellyfin/coordinator.py"], "id": "home-assistant-184518", "issue_url": "https://github.com/home-assistant/core/issues/184052", "merged_at": "2026-10-07T02:30:53Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/184518", "repo": "home-assistant/core", "text_sha256": "4e3a76ab3e45ddfdbaf29144361bdac84b8b80309e635019e900b09609efc7b4"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/traccar/__init__.py"], "id": "home-assistant-184562", "issue_url": "https://github.com/home-assistant/core/issues/178993", "merged_at": "2026-10-07T04:31:30Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/184562", "repo": "home-assistant/core", "text_sha256": "ee1145f9862b6800c1ade131bfdff9876372145e47ad2aca85a950627a29750e"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/helpers/collection.py"], "id": "home-assistant-184631", "issue_url": "https://github.com/home-assistant/core/issues/169602", "merged_at": "2026-10-07T09:50:49Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/184631", "repo": "home-assistant/core", "text_sha256": "70f4e57f233a2a552897832c9402baf3fa9629e1611cdda2d43e83fcd0252593"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/luci/__init__.py", "homeassistant/components/luci/const.py", "homeassistant/components/luci/strings.json"], "id": "home-assistant-178426", "issue_url": "https://github.com/home-assistant/core/issues/178352", "merged_at": "2026-10-08T13:06:17Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/178426", "repo": "home-assistant/core", "text_sha256": "a1e47a3d68fdd3d49d9df43c570d7a2367d2555d46dfeadd3ccee4e8ca07b73e"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/lg_infrared/climate.py"], "id": "home-assistant-185231", "issue_url": "https://github.com/home-assistant/core/issues/185150", "merged_at": "2026-10-09T10:23:57Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/185231", "repo": "home-assistant/core", "text_sha256": "76b78f3ccddf8defed27eba3c126584713230748c9b0ec6e07cc53af8455b247"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/indevolt/manifest.json", "homeassistant/components/indevolt/number.py"], "id": "home-assistant-185181", "issue_url": "https://github.com/home-assistant/core/issues/185099", "merged_at": "2026-10-09T10:52:30Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/185181", "repo": "home-assistant/core", "text_sha256": "5b781baf2d0710c923dad49198e5a2ce3b38a483e60d25d623ab5ea1b6b6e0a3"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/deconz/light.py"], "id": "home-assistant-185117", "issue_url": "https://github.com/home-assistant/core/issues/185116", "merged_at": "2026-10-09T15:08:31Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/185117", "repo": "home-assistant/core", "text_sha256": "7e06116cb48f9de37f875e1865bbab1b38c831cfd3edad2655b87e139813f231"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/google_assistant/__init__.py", "homeassistant/components/google_assistant/button.py", "homeassistant/components/google_assistant/const.py", "homeassistant/components/google_assistant/diagnostics.py"], "id": "home-assistant-185610", "issue_url": "https://github.com/home-assistant/core/issues/168771", "merged_at": "2026-10-10T12:06:14Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/185610", "repo": "home-assistant/core", "text_sha256": "69a938c582aed79ca145a55560fad973c5f33b0e9a71b443474e43c88ef70ece"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/nanoleaf/manifest.json"], "id": "home-assistant-185777", "issue_url": "https://github.com/home-assistant/core/issues/184440", "merged_at": "2026-10-12T12:42:45Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/185777", "repo": "home-assistant/core", "text_sha256": "447a13684ee40d8679b8f755f040a5acdce6e446e10902abf4d62c2bdfdd2d86"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/intellifire/manifest.json"], "id": "home-assistant-186143", "issue_url": "https://github.com/home-assistant/core/issues/185563", "merged_at": "2026-10-13T17:56:12Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/186143", "repo": "home-assistant/core", "text_sha256": "594d12dd32c02f08b979220ad35213a1e5706f2940e61405fa6f5a2f8d31cf90"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/weatherflow_cloud/manifest.json"], "id": "home-assistant-186142", "issue_url": "https://github.com/home-assistant/core/issues/174833", "merged_at": "2026-10-13T17:58:40Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/186142", "repo": "home-assistant/core", "text_sha256": "6ff62d03b8c58c2dba2bb6b60ce1511132a0a925f337aeef8e70a1901a3703cb"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/shelly/manifest.json"], "id": "home-assistant-186921", "issue_url": "https://github.com/home-assistant/core/issues/186840", "merged_at": "2026-10-17T08:06:58Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/186921", "repo": "home-assistant/core", "text_sha256": "4fe55b80b84b635cf31f6d31acb1c127d3b81546ca860aaaeb48463c43341877"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/tesla_fleet/update.py"], "id": "home-assistant-186733", "issue_url": "https://github.com/home-assistant/core/issues/186140", "merged_at": "2026-10-18T10:17:04Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/186733", "repo": "home-assistant/core", "text_sha256": "72c8ea4c0cbe81cb0db874f839588f07166db6d086d8a561a085dd0f9b47dede"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/modbus/entity.py"], "id": "home-assistant-182862", "issue_url": "https://github.com/home-assistant/core/issues/157526", "merged_at": "2026-10-18T19:08:18Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/182862", "repo": "home-assistant/core", "text_sha256": "d899268e79fd8a7af7e998ebbe96e86317e1cce5ac6bdd7f1b09071dc8227c96"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/helpers/config_validation.py"], "id": "home-assistant-187661", "issue_url": "https://github.com/home-assistant/core/issues/151247", "merged_at": "2026-10-21T02:48:10Z", "names_gold_path": true, "pr_url": "https://github.com/home-assistant/core/pull/187661", "repo": "home-assistant/core", "text_sha256": "245f9165dba4228826b7431218e5b34a05d066c397197154dfac24da3d119198"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/ntfy/manifest.json"], "id": "home-assistant-188249", "issue_url": "https://github.com/home-assistant/core/issues/181464", "merged_at": "2026-10-23T18:37:53Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/188249", "repo": "home-assistant/core", "text_sha256": "3bad92943e8efa71041d48524f810677c314a63ea35a76057d3f5123a9aa7857"}+{"S": "09e3474f91be03d4ac5a70a698474986fc759bcf", "gold": ["homeassistant/components/shelly/coordinator.py"], "id": "home-assistant-188575", "issue_url": "https://github.com/home-assistant/core/issues/160317", "merged_at": "2026-10-25T18:18:49Z", "names_gold_path": false, "pr_url": "https://github.com/home-assistant/core/pull/188575", "repo": "home-assistant/core", "text_sha256": "a3aa5e154c9e7cfe20f4dc4aa2437cd49adcc161e9041cec30285728eb74f9bb"}diff --git a/bench/whole-repo/questions/questions-keycloak.jsonl b/bench/whole-repo/questions/questions-keycloak.jsonlnew file mode 100644index 0000000..2263e41--- /dev/null+++ b/bench/whole-repo/questions/questions-keycloak.jsonl@@ -0,0 +1,40 @@+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["model/jpa/src/main/java/org/keycloak/authentication/jpa/JpaAuthenticationSessionProvider.java", "model/jpa/src/main/java/org/keycloak/authentication/jpa/RootAuthenticationSessionAdapter.java", "model/jpa/src/main/java/org/keycloak/loginfailures/jpa/JpaUserLoginFailureProvider.java"], "id": "keycloak-52615", "issue_url": "https://github.com/keycloak/keycloak/issues/52610", "merged_at": "2026-09-14T07:00:18Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52615", "repo": "keycloak/keycloak", "text_sha256": "56ffac59dc7146bd45275da07a1d3a35721b3616237e6eb2fc4739a84664c598"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oid4vc/resources/admin/UserVerifiableCredentialResource.java"], "id": "keycloak-52740", "issue_url": "https://github.com/keycloak/keycloak/issues/52105", "merged_at": "2026-09-14T14:48:42Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52740", "repo": "keycloak/keycloak", "text_sha256": "48114fd3690b9da60328be61a111009187ded8b0e93106aa9d922e9fa24bd3fa"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCAuthorizationDetailsProcessor.java"], "id": "keycloak-52734", "issue_url": "https://github.com/keycloak/keycloak/issues/52670", "merged_at": "2026-09-16T08:51:39Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52734", "repo": "keycloak/keycloak", "text_sha256": "48eb20468bf0ae7c88ff6fb082162736212f51bf73d64dcdacc8d048b8556a81"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oidc/grants/device/DeviceGrantType.java"], "id": "keycloak-52791", "issue_url": "https://github.com/keycloak/keycloak/issues/52783", "merged_at": "2026-09-17T07:44:56Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52791", "repo": "keycloak/keycloak", "text_sha256": "c8dedc6cf224509c75993fcc63a1e29d46448c45222497711e8890f9ff5539fb"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["common/src/main/java/org/keycloak/common/Profile.java"], "id": "keycloak-52728", "issue_url": "https://github.com/keycloak/keycloak/issues/50871", "merged_at": "2026-09-17T14:50:49Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52728", "repo": "keycloak/keycloak", "text_sha256": "ad95e7ff4b687211090fc9285cafaf5c98420c9d6140d1daf62defffd5b435a0"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java"], "id": "keycloak-52920", "issue_url": "https://github.com/keycloak/keycloak/issues/52919", "merged_at": "2026-09-18T08:13:10Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52920", "repo": "keycloak/keycloak", "text_sha256": "ed0d4bbba3091d9c37df870159a204b299b96cf41561e13ee768a7a84090c896"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java"], "id": "keycloak-52205", "issue_url": "https://github.com/keycloak/keycloak/issues/52013", "merged_at": "2026-09-21T07:06:56Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/52205", "repo": "keycloak/keycloak", "text_sha256": "059616de1db238f0dc067d9bb67ae50b144c790cf5511b5deeaba5089fac213e"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/theme/ClassLoaderTheme.java", "services/src/main/java/org/keycloak/theme/ClasspathThemeResourceProviderFactory.java", "services/src/main/java/org/keycloak/theme/ResourceLoader.java"], "id": "keycloak-50266", "issue_url": "https://github.com/keycloak/keycloak/issues/50265", "merged_at": "2026-09-22T18:08:28Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/50266", "repo": "keycloak/keycloak", "text_sha256": "0e6230597295595e476007b17d239173d132eeaab38fa3cd649387042a73b3d1"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/libs/ui-shared/src/context/KeycloakContext.tsx"], "id": "keycloak-52462", "issue_url": "https://github.com/keycloak/keycloak/issues/52157", "merged_at": "2026-09-22T20:28:35Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52462", "repo": "keycloak/keycloak", "text_sha256": "df1defc83972bc6c97d28915e5c587e25e4aa398180a91b5ca8bf97e2253f2ad"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["pom.xml"], "id": "keycloak-53182", "issue_url": "https://github.com/keycloak/keycloak/issues/52972", "merged_at": "2026-09-25T11:06:45Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53182", "repo": "keycloak/keycloak", "text_sha256": "be0f71f2a927dd011d5fc91a6fe92d1fb4e512de3c992f90fbae8593d4c15d86"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["common/src/main/java/org/keycloak/common/util/PathMatcher.java"], "id": "keycloak-52843", "issue_url": "https://github.com/keycloak/keycloak/issues/52836", "merged_at": "2026-09-28T12:18:24Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52843", "repo": "keycloak/keycloak", "text_sha256": "3d08c3ca760a8da5506eaf33e5356e40993b7e037c68776a2259efa5ecde5aa3"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["themes/src/main/resources/theme/base/email/html/workflow-notification.ftl", "themes/src/main/resources/theme/base/email/messages/messages_en.properties", "themes/src/main/resources/theme/base/email/text/workflow-notification.ftl"], "id": "keycloak-52290", "issue_url": "https://github.com/keycloak/keycloak/issues/52287", "merged_at": "2026-09-28T14:50:41Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/52290", "repo": "keycloak/keycloak", "text_sha256": "558a9ae844d0265958e95979f0ca66073659264aab29c80131f604482d9ae9ee"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/DefaultCredentialOfferProvider.java"], "id": "keycloak-53272", "issue_url": "https://github.com/keycloak/keycloak/issues/52665", "merged_at": "2026-09-29T08:38:46Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53272", "repo": "keycloak/keycloak", "text_sha256": "d7b04d407d094f8da652842b498f48afc1d586a78dffdf69c242ac1ec044bea4"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["rest/admin-v2/services/src/main/java/org/keycloak/models/utils/StripSecretsUtilsV2.java"], "id": "keycloak-53209", "issue_url": "https://github.com/keycloak/keycloak/issues/53117", "merged_at": "2026-09-29T15:42:04Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53209", "repo": "keycloak/keycloak", "text_sha256": "5f47815baef2e76e0cbd6eabbee6d62baab1f2e3383180b5a4c83feed4165e72"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/apps/admin-ui/src/realm-settings/RealmSettingsTabs.tsx"], "id": "keycloak-53227", "issue_url": "https://github.com/keycloak/keycloak/issues/51498", "merged_at": "2026-09-29T15:47:09Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53227", "repo": "keycloak/keycloak", "text_sha256": "1a4fd087e52d9d318aada7be1919dca2b1ff4fc98ebbe45db6054d6fce0ea3b9"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["ssf/transmitter/src/main/java/org/keycloak/ssf/transmitter/support/SsfUtil.java"], "id": "keycloak-53214", "issue_url": "https://github.com/keycloak/keycloak/issues/53107", "merged_at": "2026-09-29T16:39:17Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53214", "repo": "keycloak/keycloak", "text_sha256": "92cba4a183b0a280253ad612d4a04518f212355b0300541d2b935ad5b7343195"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/organization/admin/resource/OrganizationIdentityProvidersResource.java", "services/src/main/java/org/keycloak/organization/utils/Organizations.java", "services/src/main/java/org/keycloak/services/resources/admin/IdentityProviderResource.java", "services/src/main/java/org/keycloak/services/resources/admin/IdentityProvidersResource.java"], "id": "keycloak-53318", "issue_url": "https://github.com/keycloak/keycloak/issues/53307", "merged_at": "2026-09-30T10:52:40Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53318", "repo": "keycloak/keycloak", "text_sha256": "c25d4839f0119df24fb017d06f8ceffee17d694e914cc49ce071d8b013a9f773"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/broker/saml/SAMLEndpoint.java"], "id": "keycloak-53281", "issue_url": "https://github.com/keycloak/keycloak/issues/53242", "merged_at": "2026-09-30T13:47:42Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53281", "repo": "keycloak/keycloak", "text_sha256": "ac58ae61b0b936f6b0a3815d85e86b75499bfa27f1bbbba3f3a1f2f3329daeed"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/resources/admin/RoleContainerResource.java"], "id": "keycloak-52381", "issue_url": "https://github.com/keycloak/keycloak/issues/52378", "merged_at": "2026-09-30T13:52:43Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/52381", "repo": "keycloak/keycloak", "text_sha256": "167b7b29b7257928a6b5dfb9b6c0f925925bf99ea552e5dd1d4850055a51050f"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/apps/account-ui/src/applications/Applications.tsx", "js/apps/account-ui/src/verifiable-credentials/IssuedCredentialsModal.tsx"], "id": "keycloak-53044", "issue_url": "https://github.com/keycloak/keycloak/issues/52677", "merged_at": "2026-10-01T13:32:26Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53044", "repo": "keycloak/keycloak", "text_sha256": "19e08a15020f950902d835bd25ccebb985c1c3fd61c6bd4993c799270492c649"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/apps/admin-ui/maven-resources/theme/keycloak.v2/admin/messages/messages_en.properties"], "id": "keycloak-53408", "issue_url": "https://github.com/keycloak/keycloak/issues/53373", "merged_at": "2026-10-01T14:33:22Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53408", "repo": "keycloak/keycloak", "text_sha256": "13a96c486df3d8cbf1d472a0531687cbe73d70b49a8cb9a85d72315865ded9a2"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/apps/admin-ui/src/permissions-configuration/resource-types/RoleSelect.tsx"], "id": "keycloak-53376", "issue_url": "https://github.com/keycloak/keycloak/issues/53370", "merged_at": "2026-10-01T14:34:55Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53376", "repo": "keycloak/keycloak", "text_sha256": "2956f9c5e425b956f10343b6dd39a1a76835c43a94b4d8f4ec65ed8a468d6cb0"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/authorization/admin/PolicyEvaluationService.java"], "id": "keycloak-53412", "issue_url": "https://github.com/keycloak/keycloak/issues/53072", "merged_at": "2026-10-01T18:05:45Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53412", "repo": "keycloak/keycloak", "text_sha256": "c9656c9c54ecce4b934f43baa8c8393ac82c3d921d55b116b707129b338175aa"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/authorization/authorization/AuthorizationTokenService.java"], "id": "keycloak-53469", "issue_url": "https://github.com/keycloak/keycloak/issues/53073", "merged_at": "2026-10-02T15:44:55Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53469", "repo": "keycloak/keycloak", "text_sha256": "bf4e0d3e67a98897644fc01d08be9a921e3e1ab09183d9a2e6e69a5624d33d86"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["common/src/main/java/org/keycloak/common/util/UriUtils.java", "services/src/main/java/org/keycloak/protocol/oidc/endpoints/LoginStatusIframeEndpoint.java", "services/src/main/java/org/keycloak/protocol/oidc/utils/RedirectUtils.java", "services/src/main/java/org/keycloak/protocol/oidc/utils/WebOriginsUtils.java", "services/src/main/java/org/keycloak/services/cors/DefaultCors.java"], "id": "keycloak-52845", "issue_url": "https://github.com/keycloak/keycloak/issues/52119", "merged_at": "2026-10-06T06:07:00Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52845", "repo": "keycloak/keycloak", "text_sha256": "f6c44e339fa6bc915b6f0d826329afb0c8115844eb572448cf3a011920175247"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["js/apps/admin-ui/src/sessions/SessionsTable.tsx"], "id": "keycloak-53543", "issue_url": "https://github.com/keycloak/keycloak/issues/52927", "merged_at": "2026-10-06T07:59:43Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53543", "repo": "keycloak/keycloak", "text_sha256": "95e29757bf8b3ae057dbeb1e7d2b0165f4ca37c3c9a2c31ec448426a26a4c819"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["server-spi-private/src/main/java/org/keycloak/authentication/ConfigurableAuthenticatorFactory.java", "server-spi-private/src/main/java/org/keycloak/models/utils/StripSecretsUtils.java"], "id": "keycloak-53361", "issue_url": "https://github.com/keycloak/keycloak/issues/52792", "merged_at": "2026-10-07T11:19:17Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53361", "repo": "keycloak/keycloak", "text_sha256": "473d520bc1116fe1f8d0ffb3322d2390b13c0d5bfeab83e7485912497f282475"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["model/storage-private/src/main/java/org/keycloak/storage/UserStorageManager.java", "server-spi-private/src/main/java/org/keycloak/authorization/fgap/AdminPermissionsSchema.java", "server-spi-private/src/main/java/org/keycloak/authorization/fgap/evaluation/partial/PartialEvaluator.java"], "id": "keycloak-53715", "issue_url": "https://github.com/keycloak/keycloak/issues/53693", "merged_at": "2026-10-08T14:29:45Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53715", "repo": "keycloak/keycloak", "text_sha256": "9d0f706a2c762f83ab77eaea544d9d53b9422521fc585fbb5f588224fcc7376e"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/social/twitter/TwitterIdentityProvider.java"], "id": "keycloak-51750", "issue_url": "https://github.com/keycloak/keycloak/issues/51377", "merged_at": "2026-10-08T19:14:53Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/51750", "repo": "keycloak/keycloak", "text_sha256": "49a77692efa181ed1fccd6863ece9b0bedcac6dc35571614adbaa7f19d12cd9d"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["saml-core/src/main/java/org/keycloak/saml/processing/core/util/JAXPValidationUtil.java"], "id": "keycloak-53766", "issue_url": "https://github.com/keycloak/keycloak/issues/53760", "merged_at": "2026-10-09T13:49:09Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/53766", "repo": "keycloak/keycloak", "text_sha256": "30f2b5aa63a260efef86e498395aaac71db8daaf8ddd56d91baf065147840bc9"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/DefaultLazyLoader.java", "model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedUser.java"], "id": "keycloak-51322", "issue_url": "https://github.com/keycloak/keycloak/issues/51321", "merged_at": "2026-10-09T18:28:17Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/51322", "repo": "keycloak/keycloak", "text_sha256": "bb670c3f3836db23677cd58e044945e487a8115ef434ec03ec00127beb550065"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/resources/IdentityBrokerService.java"], "id": "keycloak-53635", "issue_url": "https://github.com/keycloak/keycloak/issues/53634", "merged_at": "2026-10-13T11:51:44Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53635", "repo": "keycloak/keycloak", "text_sha256": "bef8280a7ffa4ca31a6fd3b9d0962ff6e45c3dc136b407afc03fa3ca14be4eb9"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/clientregistration/oidc/DescriptionConverter.java"], "id": "keycloak-53754", "issue_url": "https://github.com/keycloak/keycloak/issues/53749", "merged_at": "2026-10-13T12:52:54Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53754", "repo": "keycloak/keycloak", "text_sha256": "45a77e10b73252d984f61305461f0ed81ceb7f410c90ddebebcf408ee2a4f680"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java"], "id": "keycloak-53913", "issue_url": "https://github.com/keycloak/keycloak/issues/50917", "merged_at": "2026-10-14T10:48:47Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53913", "repo": "keycloak/keycloak", "text_sha256": "997b4684f21b12b34b49de70a9c6d18703edb44a47e196a4869db23e31f653ed"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["server-spi-private/src/main/java/org/keycloak/models/utils/StripSecretsUtils.java"], "id": "keycloak-54039", "issue_url": "https://github.com/keycloak/keycloak/issues/52730", "merged_at": "2026-10-15T20:02:59Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/54039", "repo": "keycloak/keycloak", "text_sha256": "79c1556bd71f22eafb7bb4657efe05e7f89b9e19d201a850dc4be73bdc0e9493"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["adapters/saml/core/src/main/java/org/keycloak/adapters/saml/profile/AbstractSamlAuthenticationHandler.java", "saml-core/src/main/java/org/keycloak/saml/validators/SubjectConfirmationDataValidator.java", "services/src/main/java/org/keycloak/broker/saml/SAMLEndpoint.java"], "id": "keycloak-54038", "issue_url": "https://github.com/keycloak/keycloak/issues/53475", "merged_at": "2026-10-16T18:24:40Z", "names_gold_path": true, "pr_url": "https://github.com/keycloak/keycloak/pull/54038", "repo": "keycloak/keycloak", "text_sha256": "790dfaacf2953eac36f8a8732592fb679c8b580bd3c4cb55e7df4fdb83511908"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["model/storage/src/main/java/org/keycloak/storage/UserStorageProviderSpi.java"], "id": "keycloak-53993", "issue_url": "https://github.com/keycloak/keycloak/issues/53989", "merged_at": "2026-10-19T11:45:32Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53993", "repo": "keycloak/keycloak", "text_sha256": "c59bda07c6be7ad2c9ec642e388351310729d6db535157b80f374c7251da303e"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/DatabasePropertyMappers.java"], "id": "keycloak-52828", "issue_url": "https://github.com/keycloak/keycloak/issues/52825", "merged_at": "2026-10-19T18:20:15Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/52828", "repo": "keycloak/keycloak", "text_sha256": "d9796f5446b2dfd111f4cf578470cdf13744f234dba6a5acbf2b5c2cecb8758f"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/resources/admin/ClientAttributeCertificateResource.java"], "id": "keycloak-54006", "issue_url": "https://github.com/keycloak/keycloak/issues/49240", "merged_at": "2026-10-20T12:00:58Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/54006", "repo": "keycloak/keycloak", "text_sha256": "ba5708ad8bf0cff481763d3ea9d8d52ebae844ab40fc8caeea085c85af150a11"}+{"S": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "gold": ["services/src/main/java/org/keycloak/services/resources/admin/ClientScopeEvaluateScopeMappingsResource.java"], "id": "keycloak-53721", "issue_url": "https://github.com/keycloak/keycloak/issues/53555", "merged_at": "2026-10-23T18:54:27Z", "names_gold_path": false, "pr_url": "https://github.com/keycloak/keycloak/pull/53721", "repo": "keycloak/keycloak", "text_sha256": "30aa0988784b31c1a6673115325eceef956a060078cec746e55cd56257b06a21"}diff --git a/bench/whole-repo/questions/questions-kubernetes.jsonl b/bench/whole-repo/questions/questions-kubernetes.jsonlnew file mode 100644index 0000000..c3547d4--- /dev/null+++ b/bench/whole-repo/questions/questions-kubernetes.jsonl@@ -0,0 +1,40 @@+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/volume/attachdetach/cache/actual_state_of_world.go"], "id": "kubernetes-141385", "issue_url": "https://github.com/kubernetes/kubernetes/issues/117042", "merged_at": "2026-09-14T03:07:16Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141385", "repo": "kubernetes/kubernetes", "text_sha256": "30f9c045feabea0085b97d37ea809d3009483353a7543d300df84f9453296499"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/scheduler/backend/queue/scheduling_queue.go"], "id": "kubernetes-139450", "issue_url": "https://github.com/kubernetes/kubernetes/issues/139186", "merged_at": "2026-09-14T14:43:19Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/139450", "repo": "kubernetes/kubernetes", "text_sha256": "f55283998c01ec91a2c340f384f71e14e08238c95460e11838b41fc36b7110b6"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/cm/cpumanager/policy_static.go"], "id": "kubernetes-141041", "issue_url": "https://github.com/kubernetes/kubernetes/issues/140989", "merged_at": "2026-09-14T15:47:18Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141041", "repo": "kubernetes/kubernetes", "text_sha256": "c009e91ed7989219fcf0d1fd068f9b1754720de8f7d6626f42f8286fd2b7cb85"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/volume/persistentvolume/metrics/metrics.go"], "id": "kubernetes-141536", "issue_url": "https://github.com/kubernetes/kubernetes/issues/136310", "merged_at": "2026-09-16T21:53:23Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141536", "repo": "kubernetes/kubernetes", "text_sha256": "1cd11753642af83976a03f1eb8cfaafbb570a2224dae89e4151edb8b30db2fd3"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/scheduler/extender.go", "pkg/scheduler/framework/preemption/preemption.go", "staging/src/k8s.io/kube-scheduler/extender/v1/types.go", "staging/src/k8s.io/kube-scheduler/framework/extender.go"], "id": "kubernetes-135486", "issue_url": "https://github.com/kubernetes/kubernetes/issues/139270", "merged_at": "2026-09-17T14:07:23Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/135486", "repo": "kubernetes/kubernetes", "text_sha256": "756c259d8880340f9d2b442ad312108d3ac52a3372e640951479e11173de3d1f"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/prober/prober_manager.go", "pkg/kubelet/prober/worker.go"], "id": "kubernetes-141487", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141473", "merged_at": "2026-09-18T22:45:57Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141487", "repo": "kubernetes/kubernetes", "text_sha256": "db4be4c9e47503768058fe043ca56e6ed1e79db8ef5db6093cdb7057f5322393"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/util/sliceutils/sliceutils.go"], "id": "kubernetes-141211", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141210", "merged_at": "2026-09-18T23:42:14Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141211", "repo": "kubernetes/kubernetes", "text_sha256": "b77ebc41f3986d9fa623b73b6e5b1c53757d470f37959596690d9ae72f1b0c68"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/kubectl/pkg/describe/describe.go"], "id": "kubernetes-142214", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142209", "merged_at": "2026-09-21T14:51:00Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142214", "repo": "kubernetes/kubernetes", "text_sha256": "3f8e80283fbbb847d6eb56ac2e03eac8bfe93e40a4e0f6f7f82ce7879307ec02"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/client-go/tools/cache/mutation_cache.go"], "id": "kubernetes-141736", "issue_url": "https://github.com/kubernetes/kubernetes/issues/140041", "merged_at": "2026-09-21T16:44:08Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141736", "repo": "kubernetes/kubernetes", "text_sha256": "aae1a9432e8702572a268dff4320f6288d7fa9e5ddc63cf8007234578f303b72"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/kubectl/pkg/describe/describe.go"], "id": "kubernetes-142215", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142210", "merged_at": "2026-09-21T16:44:16Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142215", "repo": "kubernetes/kubernetes", "text_sha256": "defa6d71f754052046b425e718b22fcbb3cdb67fe95b130f1c2cde42691c4694"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/features/kube_features.go"], "id": "kubernetes-142018", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141987", "merged_at": "2026-09-21T17:58:21Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142018", "repo": "kubernetes/kubernetes", "text_sha256": "86480a2ac7bcb9664b07b36337cd0e0bcdec54d89e7d5aa4e6cc84373abeecfb"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/kubelet.go"], "id": "kubernetes-140220", "issue_url": "https://github.com/kubernetes/kubernetes/issues/140132", "merged_at": "2026-09-21T18:50:18Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/140220", "repo": "kubernetes/kubernetes", "text_sha256": "dc7b502eb35aaababb6286ba867928b52d897f73e4d81f8ed18697199ef657a4"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/cm/cpumanager/cpu_assignment.go"], "id": "kubernetes-141238", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141237", "merged_at": "2026-09-22T18:14:16Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141238", "repo": "kubernetes/kubernetes", "text_sha256": "f369e73c128246f413f0e317929abbd6e83a8ed40b58d5576a136c6bbee6442a"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/registry/core/pod/storage/eviction.go", "pkg/registry/core/pod/storage/storage.go"], "id": "kubernetes-142197", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142195", "merged_at": "2026-09-22T19:04:23Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142197", "repo": "kubernetes/kubernetes", "text_sha256": "56adb2c54fbe6019feb0d5d28ba7557ac2c255d93931bf450518cc8c346800c3"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/dynamic-resource-allocation/kubeletplugin/draplugin.go"], "id": "kubernetes-142003", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142002", "merged_at": "2026-09-23T08:42:12Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142003", "repo": "kubernetes/kubernetes", "text_sha256": "7388c9de43bf2c9844901f49e362f4d23c737dd78c47872341a7db0cfe08a26a"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/job/job_controller.go"], "id": "kubernetes-142247", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142142", "merged_at": "2026-09-24T09:00:22Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142247", "repo": "kubernetes/kubernetes", "text_sha256": "2ae283be6ef96e91afc82617a3b5af74171bc097304f1fe75c7c3c7d725f1e68"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go", "staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_proto.go", "staging/src/k8s.io/component-base/logs/api/v1/options.go"], "id": "kubernetes-142277", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141404", "merged_at": "2026-09-25T18:38:31Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142277", "repo": "kubernetes/kubernetes", "text_sha256": "663ba4dae83a9e984328e0b51e542d49143b7c824fa2e1bc8e73b78e435ad9c8"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/proxy/util/nodeport_addresses.go"], "id": "kubernetes-142138", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142129", "merged_at": "2026-09-28T01:32:30Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142138", "repo": "kubernetes/kubernetes", "text_sha256": "e84d213aae9eadf05cd0d779e559c057fb8a0a7744e78a1e396a3d086f04a90c"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/features/kube_features.go", "staging/src/k8s.io/cloud-provider/cloud.go", "staging/src/k8s.io/cloud-provider/controllers/node/node_controller.go", "staging/src/k8s.io/controller-manager/pkg/features/kube_features.go"], "id": "kubernetes-141616", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141631", "merged_at": "2026-09-29T02:56:18Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141616", "repo": "kubernetes/kubernetes", "text_sha256": "d082ae94b4c04cbb67ffe24cd0dc8adf93a721fdb28112aba0de52c67b324132"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/resourceclaim/controller.go"], "id": "kubernetes-141276", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141274", "merged_at": "2026-09-29T10:46:12Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141276", "repo": "kubernetes/kubernetes", "text_sha256": "af4b31adb33c412502698f92f4ace015689566dfefc2da0c48c8fdea42b7fd68"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apiserver/pkg/admission/conversion.go"], "id": "kubernetes-142493", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142302", "merged_at": "2026-09-29T18:16:32Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142493", "repo": "kubernetes/kubernetes", "text_sha256": "3d73ae12c5b4d076fb0041bdae580f2f213ffe1bfd8a4231dea36c4214aba6e3"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/cm/devicemanager/manager.go", "pkg/kubelet/cm/dra/manager.go"], "id": "kubernetes-142340", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142293", "merged_at": "2026-09-30T21:28:24Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142340", "repo": "kubernetes/kubernetes", "text_sha256": "e709de2cf9b2b55d4fd4b853b3a144f55f737380eb372339d63041a96ec80576"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/tainteviction/taint_eviction.go"], "id": "kubernetes-141742", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142617", "merged_at": "2026-10-02T17:55:32Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/141742", "repo": "kubernetes/kubernetes", "text_sha256": "58c807c60556234a51f5b4bd1ff247e6cd6907addc5131af11e400261fec9586"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/network/dns/dns.go"], "id": "kubernetes-140880", "issue_url": "https://github.com/kubernetes/kubernetes/issues/140844", "merged_at": "2026-10-04T11:42:23Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/140880", "repo": "kubernetes/kubernetes", "text_sha256": "42d6a168a861d26ff3b8833e2e6267bebc03060560d6f887853f315756ba8604"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apiserver/pkg/cel/environment/base.go", "staging/src/k8s.io/apiserver/pkg/cel/library/cidr.go", "staging/src/k8s.io/apiserver/pkg/cel/library/cost.go"], "id": "kubernetes-139569", "issue_url": "https://github.com/kubernetes/kubernetes/issues/134224", "merged_at": "2026-10-05T01:00:32Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/139569", "repo": "kubernetes/kubernetes", "text_sha256": "00bacf0f81cc387fb333fb4bcfc9c3eadc6456e55585768374b562360cbb507a"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apiserver/pkg/server/deprecated_insecure_serving.go", "staging/src/k8s.io/apiserver/pkg/server/secure_serving.go"], "id": "kubernetes-142607", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142606", "merged_at": "2026-10-07T00:04:45Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142607", "repo": "kubernetes/kubernetes", "text_sha256": "89cbbd27d1c4838051b0a420d1e1b12f81cf24f691dbe74775a5c991502c9a79"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/registry/core/service/ipallocator/cidrallocator.go", "pkg/registry/core/service/ipallocator/ipallocator.go"], "id": "kubernetes-142758", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142757", "merged_at": "2026-10-08T17:10:00Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142758", "repo": "kubernetes/kubernetes", "text_sha256": "69c5b0e35dec00d534c3b7ed3b67119021c0350356f24ed3b34f0caf15611b34"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["hack/golangci-hints.yaml", "hack/golangci.yaml", "hack/kube-api-linter/exceptions.yaml", "staging/src/k8s.io/api/autoscaling/v1/types.go", "staging/src/k8s.io/api/autoscaling/v2/types.go"], "id": "kubernetes-137038", "issue_url": "https://github.com/kubernetes/kubernetes/issues/136862", "merged_at": "2026-10-08T18:30:04Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/137038", "repo": "kubernetes/kubernetes", "text_sha256": "ebe2cb568b867ddb229e9a01c3334f9a73c2cf3042de3498e00b4e9216a522bf"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/api/scheduling/v1alpha3/types.go", "staging/src/k8s.io/api/scheduling/v1beta1/types.go"], "id": "kubernetes-142846", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142845", "merged_at": "2026-10-13T21:44:54Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142846", "repo": "kubernetes/kubernetes", "text_sha256": "380347eb8270478e1ded8799e5f8c77285bd121e7223e1a23381023dcb74a3cb"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/kubelet_pods.go", "pkg/kubelet/util/env/env_util.go"], "id": "kubernetes-142665", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142662", "merged_at": "2026-10-14T21:28:17Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142665", "repo": "kubernetes/kubernetes", "text_sha256": "01f48934896f7c8a10c2408037b38d8ae6ebd427f40e12819918cc355e829e53"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/kubectl/pkg/describe/describe.go"], "id": "kubernetes-142213", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142208", "merged_at": "2026-10-15T02:24:08Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142213", "repo": "kubernetes/kubernetes", "text_sha256": "ffcd5a6db093ba6fb65160cbdeaa7da3b5b6bd2e00b39b9ab9a527bbc1731ae4"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/proxy/apis/config/validation/validation.go"], "id": "kubernetes-142583", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142580", "merged_at": "2026-10-16T12:44:20Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142583", "repo": "kubernetes/kubernetes", "text_sha256": "e081f317190ba4ca4d908119ab32516f75215147d8bbc6aceb018dba7eb992a0"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["hack/update-conformance-yaml.sh", "hack/verify-conformance-yaml.sh"], "id": "kubernetes-142561", "issue_url": "https://github.com/kubernetes/kubernetes/issues/132954", "merged_at": "2026-10-20T12:41:12Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142561", "repo": "kubernetes/kubernetes", "text_sha256": "f45ec2c19ad118b73031e08245014ecd205eedbe71dc95c8a657dd652ef5a785"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/cm/memorymanager/policy_static.go"], "id": "kubernetes-140816", "issue_url": "https://github.com/kubernetes/kubernetes/issues/140814", "merged_at": "2026-10-20T13:33:10Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/140816", "repo": "kubernetes/kubernetes", "text_sha256": "f8be6aebe0e01ab495dd37af3756af2a5e073ff6f10725db6786ada51efa00af"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/helpers.go"], "id": "kubernetes-142216", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142211", "merged_at": "2026-10-20T19:20:00Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142216", "repo": "kubernetes/kubernetes", "text_sha256": "4b118f64594ca971071a4ef882b3b240b29082591e45e8883b01a7eb5d194dcc"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["staging/src/k8s.io/apimachinery/pkg/util/managedfields/gvkparser.go"], "id": "kubernetes-142048", "issue_url": "https://github.com/kubernetes/kubernetes/issues/126849", "merged_at": "2026-10-21T20:21:45Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142048", "repo": "kubernetes/kubernetes", "text_sha256": "ea537e45701a414f50dfd1d6eaf76d54b8d051ea4461f7a0bb9ea84b23b08dec"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/proxy/nftables/proxier.go"], "id": "kubernetes-142184", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142183", "merged_at": "2026-10-21T23:51:39Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142184", "repo": "kubernetes/kubernetes", "text_sha256": "3d692e3673453d6fa0bbaa56264df045ee95c1db01ece36dc947edbdeb9c9814"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/controller/job/job_scheduling_manager.go"], "id": "kubernetes-142856", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142844", "merged_at": "2026-10-22T11:11:33Z", "names_gold_path": true, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142856", "repo": "kubernetes/kubernetes", "text_sha256": "9a7aafef66e1566dae91e78379895e8e4a96def47aa0c0db38cd9465e7c0a4d5"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/scheduler/eventhandlers.go"], "id": "kubernetes-142950", "issue_url": "https://github.com/kubernetes/kubernetes/issues/142930", "merged_at": "2026-10-22T15:09:50Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142950", "repo": "kubernetes/kubernetes", "text_sha256": "0d7d5d42e51701f976337f8ddb2770be5ae69695a28e3cd33dbc4011e8e82636"}+{"S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "gold": ["pkg/kubelet/kubelet.go", "pkg/kubelet/kubelet_pods.go"], "id": "kubernetes-142761", "issue_url": "https://github.com/kubernetes/kubernetes/issues/141483", "merged_at": "2026-10-22T20:47:48Z", "names_gold_path": false, "pr_url": "https://github.com/kubernetes/kubernetes/pull/142761", "repo": "kubernetes/kubernetes", "text_sha256": "d91a9230812150c1954fa2e3b01db6c0c20494a40240ed2494632a42895ccb24"}diff --git a/bench/whole-repo/questions/questions-pytorch.jsonl b/bench/whole-repo/questions/questions-pytorch.jsonlnew file mode 100644index 0000000..9af7a53--- /dev/null+++ b/bench/whole-repo/questions/questions-pytorch.jsonl@@ -0,0 +1,30 @@+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_functorch/_aot_autograd/autograd_cache.py"], "id": "pytorch-190080", "issue_url": "https://github.com/pytorch/pytorch/issues/189293", "merged_at": "2026-09-16T12:50:03Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/190080", "repo": "pytorch/pytorch", "text_sha256": "fbf37f026a736c458ec0bbef975b7a8d5e7235b99e04f1821de6935ae589cb48"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["aten/src/ATen/native/mps/OperationUtils.h", "aten/src/ATen/native/mps/OperationUtils.mm", "aten/src/ATen/native/mps/operations/Shape.mm"], "id": "pytorch-189965", "issue_url": "https://github.com/pytorch/pytorch/issues/189960", "merged_at": "2026-09-18T06:16:14Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/189965", "repo": "pytorch/pytorch", "text_sha256": "d00d6029ea82a4aa90679e33cf4eb2c856b3b11c75476105144f4dfd94f7f147"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/distributed/elastic/rendezvous/etcd_server.py"], "id": "pytorch-191451", "issue_url": "https://github.com/pytorch/pytorch/issues/191395", "merged_at": "2026-09-18T20:54:21Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/191451", "repo": "pytorch/pytorch", "text_sha256": "c54cbced7625b8a8d248ef5620c939f818a1fa83f946a00cd62dd030c0a90467"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/distributed/device_mesh.py"], "id": "pytorch-189655", "issue_url": "https://github.com/pytorch/pytorch/issues/173815", "merged_at": "2026-09-22T11:32:16Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/189655", "repo": "pytorch/pytorch", "text_sha256": "5e21a61257ce73c70e57a3711aaafc62e23434b23bd63ae25f1ce8f451876380"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_library/infer_schema.py"], "id": "pytorch-187012", "issue_url": "https://github.com/pytorch/pytorch/issues/160094", "merged_at": "2026-09-23T10:37:24Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/187012", "repo": "pytorch/pytorch", "text_sha256": "0b647a66fb1aadb809eff885e2de5d0e444e0cfa3278c75659eeab8fa29ebdbb"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_dynamo/trace_rules.py"], "id": "pytorch-186168", "issue_url": "https://github.com/pytorch/pytorch/issues/139603", "merged_at": "2026-09-23T13:30:22Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/186168", "repo": "pytorch/pytorch", "text_sha256": "009c4f6b592b2c220254f77f67791b99229475f42a89633a3471b6c98e8c0e02"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/export/passes/__init__.py"], "id": "pytorch-185105", "issue_url": "https://github.com/pytorch/pytorch/issues/163323", "merged_at": "2026-09-25T09:34:46Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/185105", "repo": "pytorch/pytorch", "text_sha256": "e5e5c96f7feb4fea82a3bd3f38f09fb6a1d8d538003555e387f76e045921a946"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_dynamo/exc.py", "torch/_dynamo/graph_break_registry.json", "torch/_dynamo/variables/builtin.py"], "id": "pytorch-196124", "issue_url": "https://github.com/pytorch/pytorch/issues/195969", "merged_at": "2026-09-25T13:57:04Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/196124", "repo": "pytorch/pytorch", "text_sha256": "3758ff14e9093ef714643b53b67dabd2fe8a12b4df97b7b28ebf91fc87d1b3db"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_inductor/kernel/flex/flex_decoding.py"], "id": "pytorch-198543", "issue_url": "https://github.com/pytorch/pytorch/issues/198513", "merged_at": "2026-09-26T03:55:34Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/198543", "repo": "pytorch/pytorch", "text_sha256": "b8900bb128c686166e9f38550a53fef56347b75cc8ac94cc62a417f173350458"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/optim/optimizer.py"], "id": "pytorch-198710", "issue_url": "https://github.com/pytorch/pytorch/issues/198693", "merged_at": "2026-09-28T22:29:27Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/198710", "repo": "pytorch/pytorch", "text_sha256": "081f4066cff4735c041a2b847992e84f2ac024f0b707c65622859477b5d3a221"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["aten/src/ATen/native/mps/kernels/LinearAlgebra.metal"], "id": "pytorch-199063", "issue_url": "https://github.com/pytorch/pytorch/issues/19611", "merged_at": "2026-09-30T05:36:21Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/199063", "repo": "pytorch/pytorch", "text_sha256": "dff05c9d4c7211eda682550bfcbd995507d4f5a30613ad2c682761fbdbb78a17"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/fx/experimental/symbolic_shapes.py"], "id": "pytorch-184628", "issue_url": "https://github.com/pytorch/pytorch/issues/182217", "merged_at": "2026-10-01T01:23:30Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/184628", "repo": "pytorch/pytorch", "text_sha256": "22c81453213a54ab088bd7954e781f95913a02b1e1ddaa076cadb077c254c3e8"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/nn/modules/rnn.py"], "id": "pytorch-173888", "issue_url": "https://github.com/pytorch/pytorch/issues/165621", "merged_at": "2026-10-02T16:21:59Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/173888", "repo": "pytorch/pytorch", "text_sha256": "0d86cbd164dc9ff7e24bab29527d7be3784387bd5ece3e6fb83f7dfc6bf963e9"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_dynamo/eval_frame.py"], "id": "pytorch-191977", "issue_url": "https://github.com/pytorch/pytorch/issues/192071", "merged_at": "2026-10-02T20:47:43Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/191977", "repo": "pytorch/pytorch", "text_sha256": "54e1b740df154dc9ecae3faa5d30503b1cb63d9259ee6041a7a71f96e41fc76c"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/distributed/checkpoint/__init__.py", "torch/distributed/checkpoint/_fsspec_filesystem.py", "torch/distributed/checkpoint/_storage_utils.py"], "id": "pytorch-188698", "issue_url": "https://github.com/pytorch/pytorch/issues/188772", "merged_at": "2026-10-05T09:18:50Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/188698", "repo": "pytorch/pytorch", "text_sha256": "5dde00b1967cfb66a99b2affeb79300657d4c9233f589141d8b38beade6a1f6e"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_functorch/aot_autograd.py", "torch/_subclasses/fake_impls.py", "torch/export/exported_program.py"], "id": "pytorch-184052", "issue_url": "https://github.com/pytorch/pytorch/issues/160388", "merged_at": "2026-10-05T17:02:46Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/184052", "repo": "pytorch/pytorch", "text_sha256": "edcd81ea9425cfbdb5881bddaa2b1aaf0a9bd8175355d28ca89a410d929c4327"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["aten/src/ATen/native/cuda/Embedding.cu"], "id": "pytorch-199569", "issue_url": "https://github.com/pytorch/pytorch/issues/196164", "merged_at": "2026-10-05T18:26:45Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/199569", "repo": "pytorch/pytorch", "text_sha256": "badcccfa0b9498d1d5b65979c0365e2e8931bfe7f14104a748f06761895b35b7"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_functorch/_aot_autograd/schemas.py", "torch/export/exported_program.py"], "id": "pytorch-186470", "issue_url": "https://github.com/pytorch/pytorch/issues/122860", "merged_at": "2026-10-05T20:32:02Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/186470", "repo": "pytorch/pytorch", "text_sha256": "cccc85f958f45521cf6aa5cd86d89c801a8dacff211fff7da5a6991ba5d9e9df"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_inductor/graph.py"], "id": "pytorch-198104", "issue_url": "https://github.com/pytorch/pytorch/issues/198101", "merged_at": "2026-10-06T04:18:27Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/198104", "repo": "pytorch/pytorch", "text_sha256": "512e06c29d090337c0dd2ab07fbaeeebeacaebae9d4b9b48ccfc7f94bb38c456"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_inductor/kernel/flex/flex_attention.py"], "id": "pytorch-185916", "issue_url": "https://github.com/pytorch/pytorch/issues/146896", "merged_at": "2026-10-08T16:28:54Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/185916", "repo": "pytorch/pytorch", "text_sha256": "032eb1890389d08aec3def03713e40494f6b9bcd51accb2082f1153c54c6cd4d"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_inductor/lowering.py"], "id": "pytorch-195817", "issue_url": "https://github.com/pytorch/pytorch/issues/189522", "merged_at": "2026-10-09T06:09:16Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/195817", "repo": "pytorch/pytorch", "text_sha256": "857f42157afafee7389a8e3260c0226ad3e272f5ab3996c4de15e4899827d587"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/csrc/distributed/c10d/symm_mem/NCCLSymmetricMemory.cu"], "id": "pytorch-185227", "issue_url": "https://github.com/pytorch/pytorch/issues/185216", "merged_at": "2026-10-09T10:51:58Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/185227", "repo": "pytorch/pytorch", "text_sha256": "c47315b27d553e44343989c3857f6edcb73299ff675feb77c384b6fbad026f84"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["aten/src/ATen/TensorIndexing.h"], "id": "pytorch-200412", "issue_url": "https://github.com/pytorch/pytorch/issues/200396", "merged_at": "2026-10-11T12:59:08Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/200412", "repo": "pytorch/pytorch", "text_sha256": "b443c12599bb686cbf9e4b85a01c8973744d9b6af0150cb97cb97d8999ceb6c9"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/nn/functional.py"], "id": "pytorch-191653", "issue_url": "https://github.com/pytorch/pytorch/issues/191652", "merged_at": "2026-10-12T13:57:35Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/191653", "repo": "pytorch/pytorch", "text_sha256": "86c858e43aa68ebcf9b6ea58730cf002d6393b689b652ef489590b88ab072268"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["aten/src/ATen/native/Loss.cpp"], "id": "pytorch-199823", "issue_url": "https://github.com/pytorch/pytorch/issues/198951", "merged_at": "2026-10-12T20:08:30Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/199823", "repo": "pytorch/pytorch", "text_sha256": "2a49ad0cb03e20403522bcbb2ed5b71d7060daacdb5b6d0af1710063913b4b00"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/csrc/distributed/c10d/symm_mem/CUDASymmetricMemory.cu"], "id": "pytorch-200021", "issue_url": "https://github.com/pytorch/pytorch/issues/199896", "merged_at": "2026-10-13T20:28:25Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/200021", "repo": "pytorch/pytorch", "text_sha256": "70c0170be8d95224da587861b61c069b1827c45b12540f8e3d3b35c1a0477ba6"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/profiler/_chrome_trace_export.py", "torch/profiler/_cuspy/observers/profiler.py", "torch/profiler/_cuspy/trace.py", "torch/profiler/profiler.py"], "id": "pytorch-200614", "issue_url": "https://github.com/pytorch/pytorch/issues/200605", "merged_at": "2026-10-15T18:19:43Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/200614", "repo": "pytorch/pytorch", "text_sha256": "70558240c225a17fff36fb3f31453cce818aaf6c5bad5029d67cf6c8d01fca2a"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_inductor/codegen/mps.py"], "id": "pytorch-201460", "issue_url": "https://github.com/pytorch/pytorch/issues/201455", "merged_at": "2026-10-21T06:51:24Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/201460", "repo": "pytorch/pytorch", "text_sha256": "7ab15d3adb96ae377ee130b24984f8ccb94e54d05e3c459ea306061d6120509f"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["cmake/public/LoadHIP.cmake"], "id": "pytorch-201482", "issue_url": "https://github.com/pytorch/pytorch/issues/184397", "merged_at": "2026-10-22T07:16:12Z", "names_gold_path": true, "pr_url": "https://github.com/pytorch/pytorch/pull/201482", "repo": "pytorch/pytorch", "text_sha256": "2697b576d9f17d7186eb5d372d9c7ca95dd4fa55bc13e4adfebcdfe46898afbc"}+{"S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "gold": ["torch/_dynamo/variables/torch.py"], "id": "pytorch-199433", "issue_url": "https://github.com/pytorch/pytorch/issues/198486", "merged_at": "2026-10-24T01:32:41Z", "names_gold_path": false, "pr_url": "https://github.com/pytorch/pytorch/pull/199433", "repo": "pytorch/pytorch", "text_sha256": "fab8fea3c65da4ca92e83ee0dfc4f2186fc1f7c12c87dcbbaac493a853eac06f"}diff --git a/bench/whole-repo/questions/questions-vscode.jsonl b/bench/whole-repo/questions/questions-vscode.jsonlnew file mode 100644index 0000000..1424334--- /dev/null+++ b/bench/whole-repo/questions/questions-vscode.jsonl@@ -0,0 +1,30 @@+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/chat/common/plugins/agentPluginServiceImpl.ts"], "id": "vscode-326916", "issue_url": "https://github.com/microsoft/vscode/issues/301167", "merged_at": "2026-09-17T18:53:37Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/326916", "repo": "microsoft/vscode", "text_sha256": "ce76464cd1672e432a84b7193b37d8172f4aeebd77817d5f76932bc0a5e60b91"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationServiceImpl.ts"], "id": "vscode-336419", "issue_url": "https://github.com/microsoft/vscode/issues/336418", "merged_at": "2026-09-17T19:11:36Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/336419", "repo": "microsoft/vscode", "text_sha256": "1fa2490076ddf74cff57a8fd34302ff852b06de6dd39a95e3525fb53d14ddf14"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts"], "id": "vscode-336606", "issue_url": "https://github.com/microsoft/vscode/issues/336163", "merged_at": "2026-09-17T20:12:33Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/336606", "repo": "microsoft/vscode", "text_sha256": "fc14890ad6e661b2465794d564789c3e9c887624dfd69b0e1ee80201d27ade22"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/files/browser/fileActions.ts"], "id": "vscode-336662", "issue_url": "https://github.com/microsoft/vscode/issues/206471", "merged_at": "2026-09-18T02:22:06Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/336662", "repo": "microsoft/vscode", "text_sha256": "ebc8b50289cbb7f4f5ff95c7d179c4468da5135cc430ca56bd86b626a5fb54b9"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["package.json"], "id": "vscode-336747", "issue_url": "https://github.com/microsoft/vscode/issues/336369", "merged_at": "2026-09-18T12:46:49Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/336747", "repo": "microsoft/vscode", "text_sha256": "80ec316424afc3b1e4cd892ebb2384d2d119a11cd9633c6eca6ebef8b567ef58"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["extensions/theme-solarized-light/themes/solarized-light-color-theme.json"], "id": "vscode-337025", "issue_url": "https://github.com/microsoft/vscode/issues/326126", "merged_at": "2026-09-21T13:31:33Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337025", "repo": "microsoft/vscode", "text_sha256": "630da0adc3fee4a08294adc153673efe51724ea5ee7577dad5aa69090cccc864"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/sessions/contrib/chat/browser/media/chatInput.css"], "id": "vscode-337109", "issue_url": "https://github.com/microsoft/vscode/issues/337042", "merged_at": "2026-09-21T18:50:29Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337109", "repo": "microsoft/vscode", "text_sha256": "c1ab13c01c8c58cdb512e2e14d039669bee0985ab52a6c34ddcaae088825a8b6"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/editor/browser/controller/editContext/native/nativeEditContext.ts"], "id": "vscode-310901", "issue_url": "https://github.com/microsoft/vscode/issues/262473", "merged_at": "2026-09-22T08:31:25Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/310901", "repo": "microsoft/vscode", "text_sha256": "2943267379c2d81445b8ef2761c08645820c38b83103a3d080bfbd782bfb4c17"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": [".eslint-plugin-local/code-amd-node-module.ts"], "id": "vscode-334811", "issue_url": "https://github.com/microsoft/vscode/issues/334810", "merged_at": "2026-09-22T10:42:35Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/334811", "repo": "microsoft/vscode", "text_sha256": "2d84ebb600a1f15f6dd8c3b0bae7c4b0634cc06fd8e9a5871cc15e7cdd0ca377"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/files/browser/files.contribution.ts", "src/vs/workbench/services/textfile/common/encoding.ts"], "id": "vscode-337268", "issue_url": "https://github.com/microsoft/vscode/issues/336685", "merged_at": "2026-09-22T14:57:10Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337268", "repo": "microsoft/vscode", "text_sha256": "0fce7030f74a9a4a8b03099020aa4d6be6f74a743ff282205bb828b5ac131328"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/webview/common/webviewManagerService.ts", "src/vs/platform/webview/electron-main/webviewMainService.ts", "src/vs/workbench/contrib/webview/electron-browser/webviewElement.ts"], "id": "vscode-337403", "issue_url": "https://github.com/microsoft/vscode/issues/233044", "merged_at": "2026-09-23T04:57:28Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337403", "repo": "microsoft/vscode", "text_sha256": "591e6c7f62d9d10f9ff440eff07ccfe9b393850febfff6af7e1f8df7ac8f9be3"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/chat/browser/widget/chatContentParts/chatConfirmationWidget.ts"], "id": "vscode-337414", "issue_url": "https://github.com/microsoft/vscode/issues/337412", "merged_at": "2026-09-23T06:03:53Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337414", "repo": "microsoft/vscode", "text_sha256": "656f3c7bde1824b8c73a67bc71d79705c8a640603b0977c66842417eb3e389c5"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/sessions/contrib/sessions/browser/media/sessionsList.css"], "id": "vscode-334191", "issue_url": "https://github.com/microsoft/vscode/issues/332997", "merged_at": "2026-09-23T12:58:42Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/334191", "repo": "microsoft/vscode", "text_sha256": "4886a522a2cd4f9d52a017992dccc7094fa55cd07e8e4aa91bb66c739f403194"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["extensions/copilot/src/extension/intents/node/searchIntent.ts"], "id": "vscode-337561", "issue_url": "https://github.com/microsoft/vscode/issues/316997", "merged_at": "2026-09-24T00:10:31Z", "names_gold_path": true, "pr_url": "https://github.com/microsoft/vscode/pull/337561", "repo": "microsoft/vscode", "text_sha256": "5175dda891b8704261c75757e83611f674ae131fea4bf8cce38126b4520327ed"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/api/common/extHostTypeConverters.ts", "src/vs/workbench/contrib/chat/browser/tools/languageModelToolsService.ts", "src/vs/workbench/contrib/chat/common/tools/builtinTools/runSubagentTool.ts", "src/vs/workbench/contrib/chat/common/tools/languageModelToolsService.ts"], "id": "vscode-337611", "issue_url": "https://github.com/microsoft/vscode/issues/335257", "merged_at": "2026-09-24T09:21:34Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337611", "repo": "microsoft/vscode", "text_sha256": "eada0906d443fdc316b7da768abe63c1d5142052ee3373833829de8a5b53b121"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/api/common/extHostTypeConverters.ts"], "id": "vscode-337740", "issue_url": "https://github.com/microsoft/vscode/issues/325990", "merged_at": "2026-09-25T16:11:18Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/337740", "repo": "microsoft/vscode", "text_sha256": "9f36d1310f7ef58387cab6e6a553607b7fd747de5bad113e5dd0f5fb4887185c"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/editor/common/cursor/cursor.ts"], "id": "vscode-338349", "issue_url": "https://github.com/microsoft/vscode/issues/205598", "merged_at": "2026-09-28T12:16:18Z", "names_gold_path": true, "pr_url": "https://github.com/microsoft/vscode/pull/338349", "repo": "microsoft/vscode", "text_sha256": "f8863059d981934ba2b53132a88fbacd4689a31bf8f27f8ef8bb66b08240ea5e"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/sessions/contrib/layout/browser/singlePane/singlePaneDockedTabsCoordinator.ts"], "id": "vscode-338491", "issue_url": "https://github.com/microsoft/vscode/issues/338346", "merged_at": "2026-09-28T19:11:02Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/338491", "repo": "microsoft/vscode", "text_sha256": "a3c4e15c7746029249ab12872cc30a86adbd3ee370a1df6a55bf21735d2167b2"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/files/node/watcher/parcel/parcelWatcher.ts"], "id": "vscode-339081", "issue_url": "https://github.com/microsoft/vscode/issues/339080", "merged_at": "2026-10-01T16:50:51Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/339081", "repo": "microsoft/vscode", "text_sha256": "30723aebde6c7a58866f5c2dbac41dd19ddd54484b9301f2d6eb2e7e8f2073b0"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/agentHost/node/copilot/copilotGitHubTelemetryForwarder.ts"], "id": "vscode-339601", "issue_url": "https://github.com/microsoft/vscode/issues/335623", "merged_at": "2026-10-04T22:29:25Z", "names_gold_path": true, "pr_url": "https://github.com/microsoft/vscode/pull/339601", "repo": "microsoft/vscode", "text_sha256": "4adf0c2be14510d9b74342db3d9e73ce0ca0819228727502e228d3783f2d2351"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/agentHost/common/agentService.ts", "src/vs/platform/agentHost/node/protocolServerHandler.ts"], "id": "vscode-339627", "issue_url": "https://github.com/microsoft/vscode/issues/334196", "merged_at": "2026-10-04T23:46:13Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/339627", "repo": "microsoft/vscode", "text_sha256": "25d61d21da4fd61e9b75fec9003680da6ab07d5edbcc30b744421b29a9ee5cb2"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/agentHost/common/agentService.ts"], "id": "vscode-339903", "issue_url": "https://github.com/microsoft/vscode/issues/339874", "merged_at": "2026-10-05T22:56:54Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/339903", "repo": "microsoft/vscode", "text_sha256": "96bbefc2c7fcf52ae3741a6f6b39c092921cd69cbea36ac30f18e17a9cb88085"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/platform/mcp/common/mcpWorkspaceConfiguration.ts"], "id": "vscode-340034", "issue_url": "https://github.com/microsoft/vscode/issues/339955", "merged_at": "2026-10-08T22:03:41Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/340034", "repo": "microsoft/vscode", "text_sha256": "f34a5b23c09153a45e98dddef03d38e9a027972a1615dc818ba7c2ea556239c8"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["extensions/copilot/src/extension/byok/vscode-node/openRouterProvider.ts"], "id": "vscode-340814", "issue_url": "https://github.com/microsoft/vscode/issues/340809", "merged_at": "2026-10-12T18:29:15Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/340814", "repo": "microsoft/vscode", "text_sha256": "507e5c592ccf310129b891895d5d69dc6b930fa66fb9827b30dbdf286d8f8105"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["extensions/copilot/src/platform/authentication/common/authentication.ts", "extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchChunkSearch.ts", "extensions/copilot/src/platform/workspaceChunkSearch/node/codeSearch/codeSearchRepo.ts"], "id": "vscode-339875", "issue_url": "https://github.com/microsoft/vscode/issues/320570", "merged_at": "2026-10-13T22:05:50Z", "names_gold_path": true, "pr_url": "https://github.com/microsoft/vscode/pull/339875", "repo": "microsoft/vscode", "text_sha256": "c6c4ba8757d3cd88888516b908d603539fdc2b66b09e5a40d842796f632a05f3"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/sessions/contrib/sessions/browser/media/sessionsList.css"], "id": "vscode-342391", "issue_url": "https://github.com/microsoft/vscode/issues/338189", "merged_at": "2026-10-18T13:32:27Z", "names_gold_path": true, "pr_url": "https://github.com/microsoft/vscode/pull/342391", "repo": "microsoft/vscode", "text_sha256": "b1a7293cded11a7ff288addd228a8b450548136d654376f0497a31001e1cccf6"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/editor/browser/controller/editContext/clipboardUtils.ts"], "id": "vscode-342695", "issue_url": "https://github.com/microsoft/vscode/issues/170708", "merged_at": "2026-10-19T23:27:28Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/342695", "repo": "microsoft/vscode", "text_sha256": "5b8229c8559d64d3847dc6d8663f8578676027f9a9c4622d1e556603c6ecef65"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/debug/browser/debugConfigurationManager.ts"], "id": "vscode-343111", "issue_url": "https://github.com/microsoft/vscode/issues/129425", "merged_at": "2026-10-21T03:50:48Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/343111", "repo": "microsoft/vscode", "text_sha256": "4ed1156b0b76842bbed26b80a80427c9d2b7884d3c0986174301896e27d262d5"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsControl.ts", "src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsViewer.ts", "src/vs/workbench/contrib/chat/browser/agentSessions/media/agentsessionsviewer.css"], "id": "vscode-343380", "issue_url": "https://github.com/microsoft/vscode/issues/343341", "merged_at": "2026-10-21T23:58:18Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/343380", "repo": "microsoft/vscode", "text_sha256": "2e0ca4295a7dbd3bc08a5280ec2e805e5b8b054338990ec47fa96981f5603f39"}+{"S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "gold": ["build/lib/tsgo.ts"], "id": "vscode-343569", "issue_url": "https://github.com/microsoft/vscode/issues/343567", "merged_at": "2026-10-22T19:18:51Z", "names_gold_path": false, "pr_url": "https://github.com/microsoft/vscode/pull/343569", "repo": "microsoft/vscode", "text_sha256": "ab672e22aad8e4209d936ed25bb52e4a448eb2cf82ab0eb877f72b81f191ea64"}diff --git a/bench/whole-repo/recall.py b/bench/whole-repo/recall.pynew file mode 100644index 0000000..484362f--- /dev/null+++ b/bench/whole-repo/recall.py@@ -0,0 +1,265 @@+#!/usr/bin/env python3+"""Context recall without a model: are the gold files inside the pack and inside truncation?++usage: recall.py --work WORKDIR --questions DIR --texts DIR --graphicle BIN --out DIR+ [--budgets 64K,128K,256K,512K,1M] [--repos a,b] [--standin] [--tokenizer FILE] [--jobs 4]+ [--layouts standard,cache0.9,cache0.95,stable]++For every question and budget: the pack's included files and truncation's (tokens.py truncation_order+over the manifest, the same files build_truncation takes), and for each: recall (the share of the gold+files inside), any (some gold file inside) and all (every gold file inside). Pass the same --tokenizer+that tokens.py sizes counted the manifests with, so both arms fill the same budget.++For the pack, every gold file gets a status at every budget:+ inside the pack holds some of its text+ manifest-only left out, but named in the pack's manifest as a top-ranked file left out+ ranked-cut ranked by the retrieval (its rank is seen in any of the question's packs) but left+ out, and not named in the manifest+ unranked never among the ranked files of any of the question's packs (the ranking does not+ depend on the budget; at the largest budgets nearly every ranked file fits)+and each call's wall seconds and peak memory (resident set of the pack process) are recorded.+--standin uses `graphicle context` in place of `graphicle pack` and labels every row so: those rows+test the plumbing and are not results.++--layouts runs the pack once per layout, each as its own arm: standard (`--layout standard`, arm+pack), cacheF (`--layout cache --prefix-share F`, arm pack-cache for F = 0.9, else pack-cacheF) and+stable (`--layout cache --prefix-share 1.0`, arm pack-stable). Each pack row then also records the+pack's layout fields: its prefix and suffix tokens, prefix_sha256 and whether the prefix comes first+and matches its hash (prefix_ok), and the question's own tokens; the summary gives their means, the+number of distinct prefix hashes per repository, budget and layout (1 when every question shares one+prefix) and how many rows passed the prefix check. Without --layouts the pack runs once, with no+--layout option, as builds before the cache layout need.++Writes OUT/recall-rows.jsonl (per question, budget and arm) and OUT/recall-summary.json (means per+repository, budget and arm, with and without the questions whose text names a gold file path).+"""+import argparse+import json+import os+import re+import statistics+import sys+from concurrent.futures import ThreadPoolExecutor++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from pack_arm import pack_context, pack_json # noqa: E402+from run import BUDGETS, PROMPT # noqa: E402+from tokens import Counter, load_manifest, truncation_order # noqa: E402++STATUSES = ["inside", "manifest-only", "ranked-cut", "unranked"]+++def layout_spec(spec):+ """(arm label, --layout, --prefix-share) for one --layouts item."""+ if spec == "standard":+ return "pack", "standard", None+ if spec == "stable":+ return "pack-stable", "cache", 1.0+ m = re.fullmatch(r"cache(0?\.\d+|1(?:\.0+)?)", spec)+ if not m:+ raise SystemExit(f"unknown layout {spec!r}: use standard, cacheF (such as cache0.9) or stable")+ share = float(m.group(1))+ return ("pack-cache" if abs(share - 0.9) < 1e-9 else f"pack-cache{share:g}"), "cache", share+++def truncation_sets(work, name, budgets):+ rows, counter = load_manifest(work, name)+ order = truncation_order(name, rows)+ out = {}+ for b in budgets:+ used, inc = 0, set()+ for _r, p, c, w in order:+ if used + c + w <= BUDGETS[b]:+ inc.add(p)+ used += c + w+ out[b] = (inc, used)+ return out, counter+++def measure(gold, included):+ inside = [g for g in gold if g in included]+ return {"recall": len(inside) / len(gold), "any": int(bool(inside)), "all": int(len(inside) == len(gold))}+++def pack_rows(a, work, name, qs, texts, budgets, arm="pack", layout=None, share=None, qtokens=None):+ """The real pack: every question at every budget, then each gold file's status."""+ def one(job):+ q, b = job+ try:+ return job, pack_json(a.graphicle, os.path.join(work, "src", name), os.path.join(work, "data", name),+ texts[q["id"]], BUDGETS[b], a.tokenizer, layout, share)+ except Exception as e:+ return job, {"error": f"{type(e).__name__}: {str(e)[:200]}"}++ jobs = [(q, b) for q in qs for b in budgets]+ with ThreadPoolExecutor(a.jobs) as ex:+ got = {(q["id"], b): s for (q, b), s in ex.map(one, jobs)}+ rows = []+ for q in qs:+ rank = {}+ for b in budgets:+ s = got[(q["id"], b)]+ if s.get("error"):+ continue+ rank.update({p: r for p, r in s["included"].items() if r})+ rank.update({p: r for p, r in s["omitted"] if r})+ rank.update(s["left_out_listed"])+ for b in budgets:+ s = got[(q["id"], b)]+ row = {"id": q["id"], "repo": name, "budget": b, "names_gold_path": q["names_gold_path"], "arm": arm,+ "source": "graphicle pack"}+ if s.get("error"):+ rows.append(dict(row, error=s["error"]))+ continue+ status = {}+ for g in q["gold"]:+ if g in s["included"]:+ status[g] = "inside"+ elif g in s["left_out_listed"]:+ status[g] = "manifest-only"+ elif g in rank:+ status[g] = "ranked-cut"+ else:+ status[g] = "unranked"+ row.update(measure(q["gold"], set(s["included"])))+ row.update({"status": status, "gold_rank": {g: rank.get(g) for g in q["gold"]},+ "gold_inside_by_rank": {g: s["included"].get(g) for g in q["gold"] if g in s["included"]},+ "tokens": s["tokens"], "tokenizer": s["tokenizer"], "files": len(s["included"]),+ "seconds": s["seconds"], "peak_mib": s["peak_mib"], "sections": s["sections"],+ "ranked_files_seen": len(rank)})+ if layout:+ row.update({k: s.get(k) for k in ("layout", "prefix_share", "prefix_tokens", "prefix_sha256",+ "prefix_ok", "suffix_tokens", "parts")})+ row["question_tokens"] = (qtokens or {}).get(q["id"])+ rows.append(row)+ return rows+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--work", required=True)+ ap.add_argument("--questions", required=True)+ ap.add_argument("--texts", required=True)+ ap.add_argument("--graphicle", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--budgets", default="64K,128K,256K,512K,1M")+ ap.add_argument("--repos", default="kubernetes,home-assistant")+ ap.add_argument("--standin", action="store_true")+ ap.add_argument("--tokenizer")+ ap.add_argument("--jobs", type=int, default=4)+ ap.add_argument("--layouts", help="pack layouts, each its own arm: standard, cacheF (such as cache0.9), stable")+ a = ap.parse_args()+ work = os.path.abspath(a.work)+ budgets = a.budgets.split(",")+ os.makedirs(a.out, exist_ok=True)+ pack_label = "pack-standin" if a.standin else "pack"+ layouts = [layout_spec(x) for x in a.layouts.split(",")] if a.layouts else None+ if layouts and a.standin:+ raise SystemExit("--layouts needs the real pack, not --standin")+ qcounter = Counter(a.tokenizer) if layouts else None+ rows = []+ for name in a.repos.split(","):+ qs = [json.loads(l) for l in open(os.path.join(a.questions, f"questions-{name}.jsonl")) if l.strip()]+ texts = {json.loads(l)["id"]: json.loads(l)["text"] for l in open(os.path.join(a.texts, f"texts-{name}.jsonl"))}+ tsets, counter = truncation_sets(work, name, budgets)+ for q in qs:+ for b in budgets:+ inc, used = tsets[b]+ rows.append({"id": q["id"], "repo": name, "budget": b, "names_gold_path": q["names_gold_path"],+ "arm": "truncation", "source": f"truncation ({counter})", "tokens": used,+ "files": len(inc), **measure(q["gold"], inc)})+ if a.standin:+ def one(job):+ q, b = job+ row = {"id": q["id"], "repo": name, "budget": b, "names_gold_path": q["names_gold_path"],+ "arm": pack_label}+ try:+ p = pack_context(a.graphicle, os.path.join(work, "src", name), os.path.join(work, "data", name),+ texts[q["id"]], BUDGETS[b], None, True, want_text=False)+ return dict(row, source=p["source"], tokens=p["tokens"], files=len(p["included"]),+ seconds=round(p["seconds"], 2), **measure(q["gold"], set(p["included"])))+ except Exception as e:+ return dict(row, error=f"{type(e).__name__}: {str(e)[:200]}")+ with ThreadPoolExecutor(a.jobs) as ex:+ rows.extend(ex.map(one, [(q, b) for q in qs for b in budgets]))+ elif layouts:+ # The prompt's part after the context: the template and the issue (never inside the pack).+ qtokens = {q["id"]: qcounter.count(PROMPT.format(context="", repo=q["repo"], sha=q["S"],+ issue=texts[q["id"]])) for q in qs}+ for arm, layout, share in layouts:+ rows.extend(pack_rows(a, work, name, qs, texts, budgets, arm, layout, share, qtokens))+ print(f"{name} {arm}: done", flush=True)+ else:+ rows.extend(pack_rows(a, work, name, qs, texts, budgets))+ print(f"{name}: {len(qs) * len(budgets)} question-budget pairs", flush=True)+ with open(os.path.join(a.out, "recall-rows.jsonl"), "w") as f:+ for r in rows:+ f.write(json.dumps(r, sort_keys=True) + "\n")+ summary = {}+ for r in rows:+ if r.get("error"):+ continue+ for scope in ("all", "without_named"):+ if scope == "without_named" and r["names_gold_path"]:+ continue+ k = (r["repo"], r["budget"], r["arm"], scope)+ s = summary.setdefault(k, {"repo": r["repo"], "budget": r["budget"], "arm": r["arm"], "scope": scope,+ "n": 0, "recall": 0.0, "any": 0, "all": 0, "tokens": 0, "source": r["source"],+ "gold_status": {}, "seconds": [], "peak_mib": []})+ s["n"] += 1+ s["recall"] += r["recall"]+ s["any"] += r["any"]+ s["all"] += r["all"]+ s["tokens"] += r.get("tokens") or 0+ for st in (r.get("status") or {}).values():+ s["gold_status"][st] = s["gold_status"].get(st, 0) + 1+ if r.get("seconds") is not None:+ s["seconds"].append(r["seconds"])+ if r.get("peak_mib") is not None:+ s["peak_mib"].append(r["peak_mib"])+ if r.get("layout"):+ lay = s.setdefault("layout_rows", {"layout": r["layout"], "prefix_share": r.get("prefix_share"),+ "prefix_tokens": [], "suffix_tokens": [], "question_tokens": [],+ "prefix_shas": set(), "prefix_ok": 0})+ lay["prefix_tokens"].append(r.get("prefix_tokens") or 0)+ lay["suffix_tokens"].append(r.get("suffix_tokens") or 0)+ lay["question_tokens"].append(r.get("question_tokens") or 0)+ lay["prefix_shas"].add(r.get("prefix_sha256"))+ lay["prefix_ok"] += 1 if r.get("prefix_ok") else 0+ for s in summary.values():+ n = s["n"]+ s["recall"], s["any"], s["all"], s["tokens"] = s["recall"] / n, s["any"] / n, s["all"] / n, s["tokens"] / n+ for k in ("seconds", "peak_mib"):+ xs = sorted(s.pop(k))+ s[k] = ({"median": statistics.median(xs), "p90": xs[int(0.9 * (len(xs) - 1))], "max": xs[-1]}+ if xs else None)+ lay = s.pop("layout_rows", None)+ if lay:+ s.update({"layout": lay["layout"], "prefix_share": lay["prefix_share"],+ "prefix_tokens": statistics.mean(lay["prefix_tokens"]),+ "prefix_tokens_min": min(lay["prefix_tokens"]),+ "suffix_tokens": statistics.mean(lay["suffix_tokens"]),+ "question_tokens": statistics.mean(lay["question_tokens"]),+ "prefix_shas": len(lay["prefix_shas"]), "prefix_ok": lay["prefix_ok"]})+ errors = sum(1 for r in rows if r.get("error"))+ ordered = sorted(summary.values(), key=lambda s: (s["repo"], BUDGETS[s["budget"]], s["arm"], s["scope"]))+ with open(os.path.join(a.out, "recall-summary.json"), "w") as f:+ json.dump({"pack_source": pack_label, "tokenizer": a.tokenizer and os.path.basename(a.tokenizer),+ "layouts": a.layouts, "errors": errors, "rows": ordered}, f, indent=1)+ for s in ordered:+ if s["scope"] == "all":+ extra = ""+ if s["arm"].startswith("pack") and s["seconds"]:+ extra = (f" status={s['gold_status']} sec={s['seconds']['median']:.1f}/{s['seconds']['max']:.1f}"+ f" mib={s['peak_mib']['median']:.0f}/{s['peak_mib']['max']:.0f}")+ if s.get("layout"):+ extra += (f" prefix={s['prefix_tokens']:,.0f} suffix={s['suffix_tokens']:,.0f}"+ f" prefix_shas={s['prefix_shas']} prefix_ok={s['prefix_ok']}/{s['n']}")+ print(f"{s['repo']:15s} {s['budget']:>5s} {s['arm']:13s} n={s['n']:3d} recall={s['recall']:.3f} "+ f"any={s['any']:.3f} all={s['all']:.3f} tokens={s['tokens']:,.0f}{extra}")+ print(f"errors: {errors}")+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/redact.py b/bench/whole-repo/redact.pynew file mode 100644index 0000000..b8f4ab5--- /dev/null+++ b/bench/whole-repo/redact.py@@ -0,0 +1,71 @@+#!/usr/bin/env python3+"""Strip email addresses and GitHub @handles from issue texts before they are sent to a model.++usage: redact.py --texts DIR [--repos a,b] (prints counts only, never the texts)++redact(text) returns (new text, emails replaced, handles replaced):+- every email address becomes [email];+- every @handle outside code becomes @user. A handle is @ and 1 to 39 letters, digits or hyphens,+ not preceded by a letter, digit, underscore, dot, @, slash, backtick or hyphen, and not followed by a+ letter, digit, underscore, dot, opening parenthesis, slash or hyphen. So a mention such as "cc @someone"+ is replaced, while decorators and annotations such as @torch.compile and @dataclass(...), package+ scopes such as @types/node, and anything inside a fenced code block (```...```) or an inline code span+ (`...`) are left as they are.+The pack is built from the redacted text too, so nothing that is sent holds the original handles.+"""+import argparse+import json+import os+import re++EMAIL_RX = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}")+HANDLE_RX = re.compile(r"(?<![A-Za-z0-9_.@/`-])@[A-Za-z0-9][A-Za-z0-9-]{0,38}(?![A-Za-z0-9_.(/-])")+CODE_RX = re.compile(r"```.*?(?:```|\Z)|`[^`\n]*`", re.S)+++def redact(text):+ text, emails = EMAIL_RX.subn("[email]", text or "")+ out, handles, last = [], 0, 0+ for m in CODE_RX.finditer(text):+ part, n = HANDLE_RX.subn("@user", text[last:m.start()])+ out.append(part)+ out.append(m.group(0))+ handles += n+ last = m.end()+ part, n = HANDLE_RX.subn("@user", text[last:])+ out.append(part)+ return "".join(out), emails, handles + n+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--texts", required=True)+ ap.add_argument("--repos", default="")+ ap.add_argument("--words", type=int, default=0,+ help="also print the N most frequent replaced @words that occur in 3 or more texts "+ "(technical terms such as @timestamp, never a single person's handle)")+ a = ap.parse_args()+ names = [r for r in a.repos.split(",") if r] or sorted(+ p[len("texts-"):-len(".jsonl")] for p in os.listdir(a.texts) if p.startswith("texts-"))+ for name in names:+ changed = emails = handles = n = 0+ seen = {}+ with open(os.path.join(a.texts, f"texts-{name}.jsonl")) as f:+ for line in f:+ t = json.loads(line)["text"]+ new, e, h = redact(t)+ n += 1+ changed += new != t+ emails += e+ handles += h+ if a.words:+ outside = CODE_RX.sub(" ", EMAIL_RX.sub(" ", t))+ for w in set(m.group(0) for m in HANDLE_RX.finditer(outside)):+ seen[w] = seen.get(w, 0) + 1+ common = sorted(((c, w) for w, c in seen.items() if c >= 3), reverse=True)[:a.words]+ print(f"{name}: {n} texts, {changed} changed, {emails} emails, {handles} handles"+ + (f"; in 3+ texts: {', '.join(f'{w} ({c})' for c, w in common)}" if common else ""))+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/report.py b/bench/whole-repo/report.pynew file mode 100644index 0000000..0128186--- /dev/null+++ b/bench/whole-repo/report.py@@ -0,0 +1,610 @@+#!/usr/bin/env python3+"""The whole-repository benchmark's data file and report page.++usage: report.py --sizes SIZES.json [--sizes-estimate SIZES.json] [--counter-label TEXT] --index-dir DIR+ [--score SCORE.json] [--recall LABEL=RECALL.json ...] [--texts DIR] [--layouts LAYOUTS.json]+ --json OUT.json --md OUT.md [--test]++Reads the repository sizes (tokens.py sizes), the index records (index.py), the question funnel+(questions/funnel.json), the scores of the model runs (score.py), the context recall without a+model (recall.py), the registered hosted grids (estimate.py REGISTERED, priced with estimate.py's+defaults; --texts gives the issue sizes) and, for the cost section, the pack layouts' prefix and+suffix tokens (recall.py --layouts on the development repositories; without it, nominal shares), and+writes:+ OUT.json every number the page and its charts show (docs/benchmarks/whole-repo.json)+ OUT.md the page (docs/benchmarks/whole-repo.md): method, repositories, questions, results+Sections whose inputs are missing say so. Rows from `graphicle context` (the stand-in for testing the+plumbing) and runs on the mock server are refused unless --test is given, and a --test page says on+its first line that its numbers are test data.+"""+import argparse+import datetime+import json+import os+import sys++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from run import BUDGETS, PROMPT # noqa: E402+import estimate # noqa: E402++ARM_ORDER = ["pack@128K", "pack-cache@128K", "pack@512K", "pack@1M", "pack-cache@1M", "trunc@128K", "trunc@512K",+ "trunc@1M", "agent", "noctx"]+ARM_NAMES = {"pack": "Graphicle pack", "pack-cache": "Graphicle pack, cache layout",+ "pack-stable": "Graphicle pack, stable layout", "trunc": "Truncation", "agent": "Search-only agent",+ "noctx": "No context"}+MODEL_NAMES = {"muse-spark-1.3": "Muse Spark 1.3", "muse-wonder-1.0": "Muse Wonder",+ "meta-models/muse-spark-open": "Muse Spark Open", "muse-spark-1.2": "Muse Spark 1.2"}+PROVIDER_NAMES = {"meta": "Meta Model API, Responses API", "baseten": "Baseten Model APIs, chat completions"}+GRID_ARM_TEXT = {"noctx": "no context", "trunc": "truncation", "pack": "pack", "pack-cache": "cache-layout pack",+ "pack-stable": "stable pack", "agent": "search-only agent"}+++def arm_name(label):+ fam, _, b = label.partition("@")+ fam = fam.replace("-standin", "")+ return ARM_NAMES.get(fam, fam) + (f", {b}" if b else "")+++COUNTER_LABEL = {}+++def counter_text(name):+ if name in COUNTER_LABEL:+ return COUNTER_LABEL[name]+ if name.startswith("estimate:"):+ return "estimated as UTF-8 bytes / 4"+ return "counted with " + name.split(":", 1)[-1]+++def pct(x):+ return "n/a" if x is None else f"{100 * x:.1f}%"+++def ci(c, scale=100, unit="%"):+ return "" if not c else f" [{scale * c[0]:.1f}, {scale * c[1]:.1f}]" if unit == "%" else f" [{c[0]:.3f}, {c[1]:.3f}]"+++def mtok(n):+ return f"{n / 1e6:.1f}M"+++def build(a):+ cfg = json.load(open(os.path.join(HERE, "repos.json")))+ snaps = json.load(open(os.path.join(HERE, "snapshots.json")))+ funnel = json.load(open(os.path.join(HERE, "questions", "funnel.json")))+ sizes = json.load(open(a.sizes))+ estimate = json.load(open(a.sizes_estimate)) if a.sizes_estimate else None+ if a.counter_label:+ COUNTER_LABEL[sizes["counter"]] = a.counter_label+ data = {"generated": datetime.date.today().isoformat(), "test_data": bool(a.test),+ "counter": sizes["counter"], "counter_label": counter_text(sizes["counter"]),+ "estimate_counter": estimate and estimate["counter"], "snapshot_cutoff": cfg["snapshot_cutoff"],+ "merged_until": cfg["merged_until"], "selection_seed": cfg["selection_seed"],+ "prices": json.load(open(os.path.join(HERE, "prices.json"))), "repos": [], "runs": {}, "paired": [],+ "recall": None}+ for r in cfg["repos"]:+ n = r["name"]+ s = sizes["repos"][n]+ idx_path = os.path.join(a.index_dir, n + ".json")+ idx = json.load(open(idx_path)) if os.path.exists(idx_path) else {}+ files = sum(v["files"] for v in s["by_class"].values())+ data["repos"].append({+ "name": n, "slug": r["slug"], "role": r["role"], "S": snaps[n]["sha"], "S_date": snaps[n]["committed"],+ "tokens_all": s["tokens_all"], "tokens_without_vendored_generated": s["tokens_without_vendored_generated"],+ "tokens_nontest_source": s["tokens_nontest_source"], "text_files": files,+ "index_seconds": idx.get("wall_seconds"), "index_bytes": idx.get("data_bytes"),+ "index_peak_rss_mib": idx.get("peak_rss_mib"), "graphicle": idx.get("graphicle"),+ "funnel": funnel[n]})+ if estimate:+ e = estimate["repos"][n]+ data["repos"][-1]["estimate"] = {k: e[k] for k in ("tokens_all", "tokens_without_vendored_generated",+ "tokens_nontest_source")}+ if a.score:+ sc = json.load(open(a.score))+ for label, run in sc["runs"].items():+ m = run["meta"]+ if (m.get("model") == "mock" or "stand-in" in (m.get("context_source") or "")) and not a.test:+ raise SystemExit(f"{label}: mock or stand-in run; pass --test to build a test page")+ data["runs"][label] = run+ data["paired"] = sc["paired"]+ data["by_role"] = by_role(data)+ data["recall"] = []+ for spec in a.recall or []:+ label, sep, path = spec.rpartition("=")+ path = path if sep else spec+ with open(path) as f:+ rc = json.load(f)+ if rc["pack_source"] != "pack" and not a.test:+ raise SystemExit("the recall file comes from the stand-in; pass --test to build a test page")+ data["recall"].append(dict(rc, label=label if sep else rc["pack_source"]))+ data["registered"] = registered_grids(a, cfg, data["prices"])+ data["cost"] = cost_section(a, cfg, data["prices"])+ return data+++def registered_grids(a, cfg, prices):+ """The pre-registered hosted grids (estimate.REGISTERED), each with its estimated cost at the+ estimate's default assumptions."""+ roles = {r["name"]: r["role"] for r in cfg["repos"]}+ nq, qtok = estimate.load_questions(os.path.join(HERE, "questions"), a.texts, cfg)+ caps = json.load(open(os.path.join(HERE, "caps.json")))["usd"]+ agent = {"turns": 15, "turn_tokens": 2500, "out_per_turn": 800}+ out = []+ for name, desc, model, grid in estimate.REGISTERED:+ p = prices["models"][model]+ rows = estimate.grid_rows(grid, nq, qtok, roles, p, 4000, agent)+ items = []+ for item in grid.split(","):+ parts = item.split(":")+ arm, _, budget = parts[0].partition("@")+ first = int(parts[2]) if len(parts) > 2 else None+ names = estimate.repo_names(parts[1], roles)+ items.append({"arm": arm, "budget": budget or None, "repos": names, "first": first,+ "questions": sum(min(nq[n], first) if first else nq[n] for n in names)})+ out.append({"grid": name, "description": desc, "model": model, "provider": p.get("provider"),+ "cap_usd": caps.get(p.get("provider")), "items": items,+ "estimate_cached_usd": round(sum(r["cached"] for r in rows), 2),+ "estimate_uncached_usd": round(sum(r["uncached"] for r in rows), 2)})+ return out+++COST_MODELS = ["muse-spark-1.3", "muse-wonder-1.0"]+COST_CONTEXTS = [("pack", "Graphicle pack, standard layout", None),+ ("pack-cache0.5", "Graphicle pack, cache layout, 50% prefix", 0.5),+ ("pack-cache0.7", "Graphicle pack, cache layout, 70% prefix", 0.7),+ ("pack-cache", "Graphicle pack, cache layout, 90% prefix", 0.9),+ ("pack-cache0.95", "Graphicle pack, cache layout, 95% prefix", 0.95),+ ("pack-stable", "Graphicle pack, stable layout", 1.0), ("truncation", "Truncation", 1.0)]+COST_BUDGETS = ["128K", "256K", "512K", "1M"]+SESSION = 20+COST_LABEL = "computed at list prices, not billed"+++def cost_section(a, cfg, prices):+ """Input cost per question with and without the prompt cache, computed at list prices from token counts.++ Per context and budget: P shared-prefix tokens (the same for every question about the repository),+ S question-specific context tokens and Q tokens of the template and the question after the context.+ The first question pays the input price on P + S + Q; each follow-up pays the cached-input price on P+ and the input price on S + Q; a session of SESSION questions pays one first question and SESSION - 1+ follow-ups. With --layouts (recall.py --layouts, on the development repositories), P, S and Q are the+ measured means; otherwise the nominal shares of the budget (the standard pack counted with no shared+ prefix)."""+ lay, lay_label = None, None+ if a.layouts:+ lay_label, sep, path = a.layouts.rpartition("=")+ with open(path if sep else a.layouts) as f:+ lay = json.load(f)+ lay_label = lay_label if sep else None+ dev = [r["name"] for r in cfg["repos"] if r["role"] == "development"]+ nq, qtok = estimate.load_questions(os.path.join(HERE, "questions"), a.texts, cfg)+ q_nominal = estimate.template_tokens() + sum(qtok[n] * nq[n] for n in dev) / max(1, sum(nq[n] for n in dev))++ def pooled(budget, arm):+ rows = [s for s in (lay or {}).get("rows", []) if s["scope"] == "all" and s["budget"] == budget+ and s["arm"] == arm and s["repo"] in dev]+ n = sum(s["n"] for s in rows)+ if not n:+ return None+ mean = lambda k: sum((s.get(k) or 0) * s["n"] for s in rows) / n+ if arm == "truncation":+ qs = pooled(budget, "pack")+ return {"n": n, "prefix": mean("tokens"), "suffix": 0.0, "question": qs["question"] if qs else q_nominal,+ "recall": mean("recall")}+ return {"n": n, "prefix": mean("prefix_tokens"), "suffix": mean("suffix_tokens"),+ "question": mean("question_tokens"), "recall": mean("recall"),+ "prefix_shas": max(s.get("prefix_shas") or 0 for s in rows) if arm != "pack" else None}++ out_rows = []+ for budget in COST_BUDGETS:+ B = BUDGETS[budget]+ for arm, name, share in COST_CONTEXTS:+ m = pooled(budget, arm) if lay else None+ if lay and m is None:+ continue+ if m is None:+ prefix = share * B if share is not None else 0.0+ m = {"n": None, "prefix": prefix, "suffix": B - prefix, "question": q_nominal}+ row = {"budget": budget, "arm": arm, "context": name, "questions": m["n"],+ "prefix_tokens": round(m["prefix"]), "suffix_tokens": round(m["suffix"]),+ "question_tokens": round(m["question"]), "recall": m.get("recall"),+ "prefix_hashes_per_repository": m.get("prefix_shas"), "models": {}}+ for model in COST_MODELS:+ p = prices["models"][model]+ first = (m["prefix"] + m["suffix"] + m["question"]) * p["input"] / 1e6+ follow = (m["prefix"] * p["cached_input"] + (m["suffix"] + m["question"]) * p["input"]) / 1e6+ row["models"][model] = {"first_usd": first, "follow_up_usd": follow,+ "session_mean_usd": (first + (SESSION - 1) * follow) / SESSION,+ "follow_up_vs_first": follow / first if first else None}+ out_rows.append(row)+ present = [n for n in dev if any(s["repo"] == n for s in (lay or {}).get("rows", []))]+ return {"label": COST_LABEL, "basis": "measured" if lay else "nominal", "pack_build": lay_label, "session": SESSION,+ "models": {m: {k: prices["models"][m][k] for k in ("input", "cached_input", "output")} for m in COST_MODELS},+ "prices_date": prices["date"], "repos": present if lay else None, "tokenizer": lay and lay.get("tokenizer"),+ "question_tokens_nominal": round(q_nominal), "rows": out_rows}+++def by_role(d):+ """Each run's means pooled over the repositories of one role (weighted by questions)."""+ out = {}+ for role in ("held-out", "development"):+ repos = [r["name"] for r in d["repos"] if r["role"] == role]+ out[role] = {}+ for label, run in d["runs"].items():+ sel = [run["rows"][n]["all"] for n in repos if n in run["rows"]]+ n = sum(s["n"] for s in sel)+ if not n:+ continue+ row = {"n": n, "repos": [x for x in repos if x in run["rows"]], "arm": run["meta"]["arm"],+ "budget": run["meta"]["budget"], "model": run["meta"]["model"]}+ for k in ("hit1", "hit3", "hit5", "allgold5", "rr", "context_recall", "tokens_in", "tokens_out",+ "cost_usd", "wall_seconds", "turns"):+ vals = [(s[k], s["n"]) for s in sel if s.get(k) is not None]+ row[k] = sum(v * w for v, w in vals) / sum(w for _, w in vals) if vals else None+ out[role][label] = row+ return out+++def recall_section(d, w):+ """Context recall without a model: one table per recall run (its label names the pack build)."""+ w("## Context recall without a model\n")+ runs = d.get("recall") or []+ if not runs:+ w("Not run yet: for every question and budget, whether the pack and truncation contain the gold files.\n")+ return+ w("For every question and budget, with no model involved: the share of the question's gold files that are "+ "inside the context, for the pack and for truncation filled to the same budget, with tokens "+ f"{counter_text(d['counter'])}. The pack holds small files whole and large ones as excerpts and as outlines "+ "of their symbols, and a gold file counts as inside when any of its text is in the pack; truncation holds "+ "whole files only. \"Some inside\" is the share of questions with at least one gold file inside. "+ "Each table is one run, named by the pack build it used.\n")+ order = [r["name"] for r in d["repos"]]+ roles = {r["name"]: r["role"] for r in d["repos"]}+ for rc in runs:+ rows = [s for s in rc["rows"] if s["scope"] == "all" and s["arm"] in ("pack", "truncation")]+ get = {(s["repo"], s["budget"], s["arm"]): s for s in rows}+ repos = sorted({s["repo"] for s in rows}, key=order.index)+ budgets = sorted({s["budget"] for s in rows}, key=BUDGETS.get)+ w(f"### {rc['label']}\n")+ w("| Repository | Role | Budget | Questions | Pack: gold files inside | Truncation: gold files inside | "+ "Pack: some inside | Truncation: some inside |")+ w("|---|---|---|---|---|---|---|---|")+ for role in ("held-out", "development"):+ names = [n for n in repos if roles.get(n) == role]+ groups = [(n, [n]) for n in names] + ([(f"all {role}", names)] if len(names) > 1 else [])+ for label, members in groups:+ for b in budgets:+ cell = {}+ for arm in ("pack", "truncation"):+ sel = [get[(n, b, arm)] for n in members if (n, b, arm) in get]+ k = sum(s["n"] for s in sel)+ cell[arm] = {m: (sum(s[m] * s["n"] for s in sel) / k if k else None) for m in ("recall", "any")}+ cell[arm]["n"] = k+ name = f"**{label}**" if len(members) > 1 else label+ w(f"| {name} | {role} | {b} | {cell['pack']['n'] or cell['truncation']['n']} | "+ f"{pct(cell['pack']['recall'])} | {pct(cell['truncation']['recall'])} | {pct(cell['pack']['any'])} | "+ f"{pct(cell['truncation']['any'])} |")+ w("")+++def usd(v):+ return f"${v:.3f}" if v < 1 else f"${v:.2f}"+++def cost_page_section(d, w):+ """The cost per question with and without the prompt cache, by context, budget and model."""+ c = d.get("cost")+ if not c:+ return+ names = {m: MODEL_NAMES.get(m, m) for m in c["models"]}+ w("## Cost per question with the prompt cache\n")+ w(f"**All numbers in this section are {c['label']}.** Runs with the model will replace them with billed costs.\n")+ prices = "; ".join(f"{names[m]} ${p['input']:.2f} per million input tokens, ${p['cached_input']:.2f} cached"+ for m, p in c["models"].items())+ w("Meta's API serves the longest prefix a prompt shares with an earlier prompt from its cache, and bills it at "+ f"the cached-input price ({prices}; prices of {c['prices_date']}). A context whose first part is the same for "+ "every question about a repository pays the full input price once; every follow-up question pays the cached "+ "price on that part and the full price only on the rest. Truncation's dump is the same for every question, so "+ "it is cached the same way. These are input costs; output is billed on top "+ + ", ".join(f"(${p['output']:.2f} per million on {names[m]})" for m, p in c["models"].items()) + ".\n")+ if c["basis"] == "measured":+ build = f" ({c['pack_build']})" if c.get("pack_build") else ""+ w(f"The shared prefix and the question-specific tokens are the means over the questions of the development "+ f"repositories ({', '.join(c['repos'])}) for each context and budget{build}, counted with the Muse Spark Open "+ f"tokenizer. A first question pays for both, plus the question and the prompt template after the context.\n")+ else:+ w(f"No pack in the cache layout has been measured yet, so each context's shared prefix is its nominal share of "+ f"the budget (50% to 95% for the cache layout, all of it for the stable layout and for truncation); the "+ f"standard pack is counted with no shared prefix. The question and the prompt template add about "+ f"{c['question_tokens_nominal']:,} tokens.\n")+ w('<p align="center">\n <picture>\n'+ ' <source media="(prefers-color-scheme: dark)" srcset="../assets/whole-repo-cost-dark.svg">\n'+ f' <img src="../assets/whole-repo-cost-light.svg" alt="{cost_alt(c)}">\n </picture>\n</p>\n')+ head = " | ".join(f"{names[m]}: first question | {names[m]}: each follow-up | {names[m]}: mean over "+ f"{c['session']}" for m in c["models"])+ measured = c["basis"] == "measured"+ rec = " Gold files inside (development) |" if measured else ""+ w(f"| Budget | Context | Shared prefix (tokens) | Question-specific (tokens) |{rec} {head} |")+ w("|---|---|---|---|" + ("---|" if measured else "") + "---|" * (3 * len(c["models"])))+ for r in c["rows"]:+ if r["budget"] not in ("128K", "1M"):+ continue+ cells = " | ".join(f"{usd(x['first_usd'])} | {usd(x['follow_up_usd'])} | {usd(x['session_mean_usd'])}"+ for x in r["models"].values())+ rc = f" {pct(r['recall'])} |" if measured else ""+ w(f"| {r['budget']} | {r['context']} | {r['prefix_tokens']:,} | {r['suffix_tokens'] + r['question_tokens']:,} "+ f"|{rc} {cells} |")+ if measured:+ same = all((r.get("prefix_hashes_per_repository") or 1) == 1 for r in c["rows"] if r["arm"] != "truncation")+ w(f"\nEvery question about one repository at one budget got {'the same' if same else 'NOT always the same'} "+ f"prefix bytes in the cache and stable layouts (one sha256 per repository, budget and layout"+ f"{'' if same else '; see the data file'}). Gold files inside: the share of each question's gold files with "+ f"any of their text in the context (in a pack, whole or as excerpts or outlines), the same measure as in "+ f"the context recall section.")+ w(f"\nThe 256K and 512K rows are in the data file [whole-repo.json](whole-repo.json). Whether a follow-up is served "+ f"from the cache is up to the API: the 24-hour retention is a hint, and a prompt that leaves the cache pays the "+ f"first-question price again.\n")+++def cost_alt(c):+ """The cost chart's alt text: every bar's value."""+ names = {m: MODEL_NAMES.get(m, m) for m in c["models"]}+ parts = []+ for r in c["rows"]:+ if r["budget"] != "1M":+ continue+ parts.append(r["context"] + ": " + ", ".join(+ f"{names[m]} {usd(x['first_usd'])} without the cache, {usd(x['follow_up_usd'])} with it"+ for m, x in r["models"].items()))+ return (f"Input cost per follow-up question at a 1M-token budget, without and with the prompt cache, "+ f"{c['label']}. " + "; ".join(parts) + ".")+++def registered_section(d, w):+ """The model runs as registered before any of them ran: grids, order, settings, tests, limits."""+ regs = d.get("registered") or []+ if not regs:+ return+ w("## Model runs, fixed before they ran\n")+ w("These runs, their order, their settings, the tests and the spending limits were fixed on 26 Oct 2026, before "+ "any model call. A grid runs only when the one before it has finished and only if it fits the money left; "+ "this page says which ones ran.\n")+ w("| Grid | Model | API | Arms, in run order | Questions | Estimated cost with caching (without) |")+ w("|---|---|---|---|---|---|")+ for g in regs:+ arms, qs = [], set()+ for it in g["items"]:+ t = GRID_ARM_TEXT.get(it["arm"], it["arm"]) + (f" at {it['budget']}" if it["budget"] else "")+ if it["first"]:+ t += f" (the first {it['first']} questions of each repository)"+ arms.append(t)+ qs.add(it["questions"])+ cap = f" of ${g['cap_usd']:.0f}" if g.get("cap_usd") else ""+ w(f"| {g['grid']} | {MODEL_NAMES.get(g['model'], g['model'])} (`{g['model']}`) | "+ f"{PROVIDER_NAMES.get(g['provider'], g['provider'])} | {', '.join(arms)} | "+ f"{max(qs)} held-out | ${g['estimate_cached_usd']:.2f} (${g['estimate_uncached_usd']:.2f}){cap} |")+ w("")+ w("The estimates fill every budget, count 4,000 output tokens per call and assume the search-only agent takes "+ "15 turns that add 2,500 tokens each (`estimate.py --registered`). The 1M arms on Muse Spark 1.3 (G2) and "+ "the Muse Wonder subset (G4) run only if the Meta limit still allows them after G1.\n")+ w("- **Caching:** Meta's API caches the longest identical prefix of a prompt and bills it at the cached-input "+ "price. Every call sends `prompt_cache_key`, one key per repository, snapshot, arm, budget and prefix hash, "+ "and `prompt_cache_retention: \"24h\"`; on Baseten the same key goes in the `x-session-affinity` header. "+ "Truncation, whose dump is the same for every question, gets the same treatment as the pack, so the cost "+ "comparison does not favour the pack.")+ w("- **Order:** the questions of one repository, arm and budget run back to back in the question file's order, "+ "the first one alone, so the later ones can be served from the cache. The search-only agent takes the three "+ "repositories in turn, one question each, so a run stopped by its spending limit still covers them evenly.")+ w("- **Settings:** reasoning effort medium; at most 8,192 output tokens per call (per turn for the agent); "+ "one answer per question; the API's default sampling.")+ w("- **Primary comparisons:** hit@5, pooled over the three held-out repositories, by McNemar's exact test: the "+ "pack against truncation at 128K and the pack against the search-only agent at 128K (Muse Spark 1.3), and the "+ "cache-layout pack against truncation at 1M (Muse Spark Open). Every other comparison is secondary. A question "+ "whose call still fails after retries is left out of the means and counted; the hit rates with such questions "+ "counted as misses are shown too.")+ w("- **Cost:** per question as billed, from the input, cached and output tokens the API reports, and at list "+ "prices without any cache.")+ w("- **Spending limits:** the runner logs every call (tokens, cached tokens, seconds, cost) and refuses to start "+ "a run when the logged total plus the run's own estimate would pass $45 on Meta's API or $100 on Baseten; "+ "within a run, no call is sent whose worst case (the whole prompt uncached plus the output limit) would pass "+ "the run's own limit or the total one.")+ w("- **Held-out repositories:** tuning happens only on kubernetes and home-assistant. Every run on pytorch, "+ "vscode or elasticsearch, with or without a model, is logged with its time and pack version before its result "+ "is read, and no held-out result changes the pack. The context recall runs once per release candidate; each "+ "hosted grid runs once, with one pack version, and a run stopped by an error or a spending limit is resumed, "+ "never repeated. The first held-out run is the context recall of the pack as it was built before 26 Oct 2026.\n")+++def page(d):+ L = []+ w = L.append+ if d["test_data"]:+ w("> **TEST DATA.** This page was built from the mock server and the stand-in, to test the report "+ "generator. None of its result numbers measure a model or `graphicle pack`.\n")+ w("# Whole-repository change localization past 1M tokens\n")+ lo = min(r["tokens_all"] for r in d["repos"]) / 1e6+ hi = max(r["tokens_all"] for r in d["repos"]) / 1e6+ nq = sum(r["funnel"]["kept"] for r in d["repos"])+ w("Can a model find the files a real fix changed, in a repository far larger than its context window? "+ f"This benchmark asks it for five public repositories of {lo:.0f} to {hi:.0f} million tokens each, with {nq} questions taken "+ "from real issues and the files their fixes changed. It compares Graphicle's `graphicle pack` with plain "+ "truncation of the repository, with the same model searching the repository through tools, and with no "+ "repository context at all. The method was fixed before any result was seen, and the results are published "+ "as they came out.\n")+ w("## Results\n")+ if not d["runs"]:+ w("Not run yet. The questions, arms, prompts and scorer are fixed and committed; the model runs come next.\n")+ else:+ order = sorted(d["runs"], key=lambda l: ARM_ORDER.index(l) if l in ARM_ORDER else 99)+ for role in ("held-out", "development"):+ repos = [r["name"] for r in d["repos"] if r["role"] == role]+ labels = [l for l in order if l in d["by_role"].get(role, {})]+ if not labels:+ continue+ w(f"### {role.capitalize()} repositories ({', '.join(repos)})\n")+ w("| Arm | Questions | hit@1 | hit@3 | hit@5 [95% CI] | hit@5 without named paths | All gold in top 5 | "+ "MRR | Context recall | Tokens in per question | Tokens out per question | Cost per question | "+ "Seconds per question | Turns |")+ w("|---|---|---|---|---|---|---|---|---|---|---|---|---|---|")+ for label in labels:+ r = d["by_role"][role][label]+ run = d["runs"][label]["rows"]+ c = run["pooled"]["all"].get("hit5_ci") if set(r["repos"]) == set(k for k in run if k != "pooled") else None+ wn = [run[n]["without_named"] for n in r["repos"]]+ nn = sum(x["n"] for x in wn)+ h5n = sum((x["hit5"] or 0) * x["n"] for x in wn) / nn if nn else None+ f3 = lambda v: "n/a" if v is None else f"{v:.3f}"+ f0 = lambda v: "n/a" if v is None else f"{v:,.0f}"+ f1 = lambda v: "n/a" if v is None else f"{v:.1f}"+ w(f"| {arm_name(label)} | {r['n']} | {pct(r['hit1'])} | {pct(r['hit3'])} | {pct(r['hit5'])}{ci(c)} | "+ f"{pct(h5n)} ({nn}) | {pct(r['allgold5'])} | {f3(r['rr'])} | {pct(r['context_recall'])} | "+ f"{f0(r['tokens_in'])} | {f0(r['tokens_out'])} | "+ f"{'n/a' if r['cost_usd'] is None else '$%.3f' % r['cost_usd']} | {f1(r['wall_seconds'])} | "+ f"{f1(r['turns'])} |")+ w("")+ w("| Repository | Arm | Questions | hit@1 | hit@5 [95% CI] | MRR | Context recall | Cost per question |")+ w("|---|---|---|---|---|---|---|---|")+ for n in repos:+ for label in labels:+ rr = d["runs"][label]["rows"].get(n)+ if not rr:+ continue+ x = rr["all"]+ w(f"| {n} | {arm_name(label)} | {x['n']} | {pct(x['hit1'])} | {pct(x['hit5'])}{ci(x.get('hit5_ci'))} | "+ f"{'n/a' if x['rr'] is None else '%.3f' % x['rr']} | {pct(x['context_recall'])} | "+ f"{'n/a' if x['cost_usd'] is None else '$%.3f' % x['cost_usd']} |")+ w("")+ w("Questions with an API error are left out of the means and counted in the data file; the data file "+ "[whole-repo.json](whole-repo.json) also holds the intervals of every mean.\n")+ if d["paired"]:+ w("### Paired comparisons on hit@5 (McNemar's exact test, pooled over all repositories run)\n")+ w("| A | B | Questions | Only A hits | Only B hits | p |")+ w("|---|---|---|---|---|---|")+ for p in d["paired"]:+ if p["scope"] == "pooled":+ w(f"| {arm_name(p['a'])} | {arm_name(p['b'])} | {p['n']} | {p['a_only']} | {p['b_only']} | "+ f"{p['mcnemar_p']:.3g} |")+ w("")+ recall_section(d, w)+ cost_page_section(d, w)+ w("## Repositories\n")+ w(f"Each repository is pinned at S, the last commit on its default branch's first-parent line at or before "+ f"{d['snapshot_cutoff'].replace('T00:00:00Z', ' 00:00 UTC')}. Meta's model documentation states no knowledge "+ f"cutoff for Muse Spark, so the date was not moved. Sizes count the tracked text files at S, in tokens "+ f"{counter_text(d['counter'])}" + ("; in brackets, the estimate of UTF-8 bytes / 4" if d.get("estimate_counter")+ else "") + "; "+ f"vendored and generated files are listed in `bench/whole-repo/paths.py`.\n")+ w("| Repository | Role | S | S date (UTC) | Tokens, all | Without vendored and generated | Non-test source | "+ "Text files | Index time | Index size |")+ w("|---|---|---|---|---|---|---|---|---|---|")+ for r in d["repos"]:+ it = f"{r['index_seconds']:.0f} s" if r["index_seconds"] else "n/a"+ isz = f"{r['index_bytes'] / 2**30:.1f} GiB" if r["index_bytes"] else "n/a"+ e = r.get("estimate") or {}+ tk = lambda k: mtok(r[k]) + (f" ({mtok(e[k])})" if k in e else "")+ w(f"| {r['slug']} | {r['role']} | `{r['S'][:12]}` | {r['S_date'][:16].replace('T', ' ')} | {tk('tokens_all')} | "+ f"{tk('tokens_without_vendored_generated')} | {tk('tokens_nontest_source')} | {r['text_files']:,} | "+ f"{it} | {isz} |")+ g = next((r["graphicle"] for r in d["repos"] if r.get("graphicle")), "")+ w(f"\nIndex time is the wall time of `graphicle sync` ({g}) on 48 cores of a shared machine at low priority, "+ f"two repositories at a time; index size is its data folder.\n")+ w("## Questions\n")+ w(f"Each question is a real issue, fixed by a pull request merged into the default branch after S and by "+ f"{d['merged_until'][:10]}. The question is the issue's title and body as first filed (from GitHub's edit "+ f"history), with HTML comments and empty template headings removed. The gold answer is the source files the "+ f"pull request changed that exist at S: no tests, docs, changelogs, generated or vendored files. Only pull "+ f"requests with 1 to 5 gold files are kept, and only when their change to the gold files applies cleanly to S, "+ f"so the bug is present in the snapshot. When more questions pass than the target, the target number is drawn "+ f"with the fixed seed {d['selection_seed']}. The question sets publish the issue and pull request links, the "+ f"gold files and the sha256 of each question text; `fetch_texts.py` rebuilds the texts and checks them.\n")+ w("| Repository | Pull requests found | No readable linked issue | Over 100 files | Not 1 to 5 source files "+ "| Diff not readable | Not 1 to 5 gold files | Does not apply at S | Issue not usable | Issue already used | "+ "Passed | Kept | Text names a gold path |")+ w("|---|---|---|---|---|---|---|---|---|---|---|---|---|")+ for r in d["repos"]:+ f = r["funnel"]+ w(f"| {r['slug']} | {f['fetched']} | {f['dropped_linked']} | {f['dropped_files']} | {f['dropped_prefilter']} | "+ f"{f['dropped_diff']} | {f['dropped_gold']} | {f['dropped_applies']} | {f['dropped_issue']} | "+ f"{f['dropped_duplicate']} | {f['passed']} | {f['kept']} | {f['names_gold_path']} |")+ w("\nThe search found the merged pull requests GitHub links to an issue. For PyTorch, whose merge bot closes pull "+ "requests instead of merging them, every landed pull request was read and its closing keywords parsed, so most "+ "PyTorch pull requests drop out at the linked-issue step. Questions whose text names a gold file path (a "+ "path of at least two parts, such as a stack trace line) are flagged; the results are shown with and without "+ "them.\n")+ w("## Arms\n")+ w("Every arm sends one prompt: the context, then the question, in this template:\n")+ w("```text\n" + PROMPT.format(context="<context>\n\n", repo="<org>/<name>", sha="<S>", issue="<issue text>")+ + "\n```\n")+ w("- **Graphicle pack at B tokens:** `graphicle pack \"<issue>\" --project <repository> --budget B --format xml`.")+ w("- **Graphicle pack, cache layout:** the same with `--layout cache --prefix-share 0.9`: the first 90% of the "+ "budget is a prefix that does not depend on the question, byte for byte the same for every question about the "+ "repository at S, and the rest is chosen for the question. A model API's prompt cache can then serve the prefix "+ "of every question after the first at its cached-input price. With `--prefix-share 1.0` (the stable layout) "+ "the whole pack is the same for every question.")+ w("- **Truncation at B tokens:** the repository's files in a fixed order up to B: source files, then tests, then "+ "docs, each group by path, vendored and generated files left out, each file wrapped with its path like the "+ "pack's chunks; a file that would pass the budget is skipped.")+ w("- **Search-only agent:** the same model with four tools over the checkout at S: `grep` (at most 100 lines), "+ "`find` (at most 200 paths), `list_dir` and `read` (at most 400 lines per call), for at most 30 turns, then "+ "the same answer. Every token of every turn is counted.")+ w("- **No context:** the question alone, the control for memorisation.\n")+ w(f"Budgets B: {', '.join(f'{k} = {v:,}' for k, v in BUDGETS.items())} tokens (1M leaves 32,768 tokens of the "+ f"1,048,576-token window for the question and the answer). Pack and truncation are measured in the same "+ f"tokenizer ({counter_text(d['counter'])}).\n")+ w("## Metrics\n")+ w("- **hit@k:** a gold file is among the first k files of the answer (k = 1, 3, 5). **All gold in top 5:** every "+ "gold file is among the first 5. **MRR:** the mean of 1/rank of the first gold file (0 when none of the 10 is).")+ w("- **Context recall:** the share of gold files whose text is inside the context; for the agent, the share it read.")+ w("- **Tokens and cost:** from the API's usage fields; cost from the price table in `prices.json` "+ f"({d['prices']['date']}, {d['prices']['source'].split(' ')[0]}).")+ w("- **Tests:** McNemar's exact test on hit@5 between arms on the same questions; 95% bootstrap intervals "+ "(questions resampled) on the means.\n")+ registered_section(d, w)+ w("## Limitations\n")+ w(f"- Five repositories and {nq} questions: differences of a few points are within the noise; the intervals say how much.")+ w("- File-level localization only, scored by exact path; a fix can be correct in other files than the ones the "+ "pull request changed.")+ w("- The gold files come from what the fix changed, which is not always where the bug was reported.")+ w("- Issues filed before S can be in a model's training data; the no-context arm measures how much that helps.")+ w("- Pull requests whose changes do not apply at S were dropped, which favours fixes to code that did not move "+ "in the weeks after S.\n")+ w("## Reproduce\n")+ w("The scripts and question sets are in [`bench/whole-repo/`](../../bench/whole-repo/). In order: "+ "`checkout.py` (the snapshots), `fetch_texts.py` (the question texts, checked against their hashes), "+ "`index.py`, `tokens.py sizes`, `run.py` once per arm (with `--spend-cap`), `score.py`, `recall.py` (with "+ "`--layouts` for the cost section) and `report.py`; the charts come from `whole_repo_chart.py` and "+ "`whole_repo_cost_chart.py` in this folder. `estimate.py` prints a grid's tokens and cost before it runs.\n")+ text = "\n".join(L)+ for bad in ("—", "–"):+ if bad in text:+ raise SystemExit("the page holds a dash it must not")+ return text+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--sizes", required=True)+ ap.add_argument("--sizes-estimate", help="sizes counted by the estimate, shown in brackets")+ ap.add_argument("--counter-label", help="plain words for the tokenizer, for the page")+ ap.add_argument("--index-dir", required=True)+ ap.add_argument("--score")+ ap.add_argument("--recall", action="append",+ help="LABEL=RECALL.json (recall.py's summary; LABEL names the pack build), once per run")+ ap.add_argument("--texts", help="the question texts (fetch_texts.py), for the issue tokens in the estimates")+ ap.add_argument("--layouts", help="[LABEL=]recall.py --layouts summary (development repositories) for the cost "+ "section; LABEL names the pack build")+ ap.add_argument("--json", required=True)+ ap.add_argument("--md", required=True)+ ap.add_argument("--test", action="store_true")+ a = ap.parse_args()+ d = build(a)+ with open(a.json, "w") as f:+ json.dump(d, f, indent=1, sort_keys=True)+ with open(a.md, "w") as f:+ f.write(page(d))+ print(f"wrote {a.json} and {a.md}")+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/repos.json b/bench/whole-repo/repos.jsonnew file mode 100644index 0000000..a83b6e5--- /dev/null+++ b/bench/whole-repo/repos.json@@ -0,0 +1,16 @@+{+ "snapshot_cutoff": "2026-09-14T00:00:00Z",+ "merged_until": "2026-10-25T23:59:59Z",+ "snapshot_rule": "S is the last commit on the default branch's first-parent line whose committer time is at or before snapshot_cutoff. Meta's model documentation (https://dev.meta.ai/docs/models, read 2026-10-26) states no knowledge cutoff for muse-spark-1.2, so the cutoff date applies unchanged.",+ "selection_seed": 20261026,+ "repos": [+ {"name": "kubernetes", "slug": "kubernetes/kubernetes", "branch": "master", "role": "development", "target": 40},+ {"name": "home-assistant", "slug": "home-assistant/core", "branch": "dev", "role": "development", "target": 40},+ {"name": "pytorch", "slug": "pytorch/pytorch", "branch": "main", "role": "held-out", "target": 30},+ {"name": "vscode", "slug": "microsoft/vscode", "branch": "main", "role": "held-out", "target": 30},+ {"name": "elasticsearch", "slug": "elastic/elasticsearch", "branch": "main", "role": "held-out", "target": 30},+ {"name": "angular", "slug": "angular/angular", "branch": "main", "role": "development", "target": 40},+ {"name": "keycloak", "slug": "keycloak/keycloak", "branch": "main", "role": "development", "target": 40},+ {"name": "godot", "slug": "godotengine/godot", "branch": "master", "role": "development", "target": 40}+ ]+}diff --git a/bench/whole-repo/run.py b/bench/whole-repo/run.pynew file mode 100644index 0000000..b397db4--- /dev/null+++ b/bench/whole-repo/run.py@@ -0,0 +1,675 @@+#!/usr/bin/env python3+"""Run one arm of the whole-repository benchmark against an OpenAI-compatible model API.++usage:+ run.py --arm noctx|pack|pack-cache|pack-stable|trunc|agent [--budget 128K] --work WORKDIR+ --questions DIR --texts DIR --out DIR [--profile meta|baseten|mock] [--base-url URL]+ [--model MODEL] [--api responses|chat] [--key-file FILE] [--spend-cap 20|auto]+ [--prices prices.json] [--caps caps.json] [--spend-log FILE] [--repos a,b] [--limit N]+ [--jobs 1] [--order grouped|interleaved] [--reasoning-effort medium]+ [--max-output-tokens 8192] [--tokenizer FILE] [--graphicle BIN] [--prefix-share F]+ [--pack-standin] [--max-turns 30] [--label NAME]++Profiles (--base-url, --model and --api override them):+ meta https://api.meta.ai/v1, the Responses API, muse-spark-1.3; key from MODEL_API_KEY+ baseten https://inference.baseten.co/v1, chat completions, meta-models/muse-spark-open (Muse Spark+ Open); key from BASETEN_API_KEY+ mock mock_server.py at --base-url, the Responses API, model "mock"; key from MODEL_API_KEY++Arms (one prompt template for all, see PROMPT: the context first, the question last):+ noctx the issue alone: the memorisation and contamination control+ pack `graphicle pack "<issue>" --project P --budget B --format xml` (and --format json for+ the included files and the layout fields); --pack-standin uses `graphicle context+ --max-tokens B` instead, a stand-in for testing the plumbing, never a result+ pack-cache the same with --layout cache --prefix-share F (--prefix-share, default 0.9): a prefix+ that is the same for every question about the repository, then a question-specific+ suffix+ pack-stable --layout cache --prefix-share 1.0: the whole pack is the same for every question+ trunc the repository's files in a fixed order up to B (tokens.py build_truncation)+ agent the same model with grep, find, list_dir and read (agent_tools.py), at most --max-turns+ turns, then the same final answer (sooner when its context passes --agent-max-context);+ with --api responses the turns are chained with previous_response_id, so the model keeps+ its reasoning between turns++Caching. Every call carries a cache key made of the repository, its snapshot, the arm, the budget+and the first 12 hex digits of the sha256 of the arm's shared prefix (the pack's prefix_sha256; the+whole truncation dump; the fixed instructions for noctx and the agent); no question text is in it.+The meta and mock profiles send it as prompt_cache_key, plus prompt_cache_retention "24h" on the+Responses API; the baseten and mock profiles send its sha256 as the x-session-affinity header. With+--order grouped (the default, except for the agent) the questions of one repository run back to back+in the question file's order, the first one alone, so the others can read its prefix from the cache;+with --order interleaved (the agent's default) the repositories take turns, one question each, so a+run stopped by a cap covers them evenly. Truncation is cached exactly like the pack. The parameter and+usage names were checked on 2026-10-26 against https://dev.meta.ai/docs/protocols/responses,+https://dev.meta.ai/docs/prompt-caching, https://docs.baseten.co/inference/model-apis/pricing-and-limits.md+and https://docs.baseten.co/inference/model-apis/reasoning.md (Muse Spark Open reasons at xhigh unless+reasoning_effort says otherwise).++The key comes from the profile's environment variable or --key-file (a file holding only the key). It+is sent as a Bearer header and never printed or written. --redact strips email addresses and @handles+from each issue text before the context is built or anything is sent (redact.py); off by default.++Spending. Every call appends one line to the global spend log (--spend-log, default+WORKDIR/spend/spend-log.jsonl): time, provider, model, arm, repository, question, input, cached,+output and reasoning tokens, seconds and cost_usd at prices.json. A run refuses to start when its+provider's logged total plus the run's own estimate (estimate.py with caching, for the questions it+still has to do) would pass the provider's global cap in caps.json (Meta $45, Baseten $100), or when+another run of the same provider holds the log's lock. Before each call the run reserves the call's+largest possible cost (the prompt's tokens uncached at the input price plus --max-output-tokens at the+output price); if that would pass --spend-cap (default $20) or what is left of the global cap, the run+stops. --spend-cap auto sets the run's cap to 1.5 times its cached estimate in whole dollars, at most+what the global cap leaves (the registered rule). What a run has spent is kept in OUT/spend.json, so+a resumed run counts it.++Writes OUT/run.json (the settings, without the key), OUT/rows.jsonl (one row per question: answer,+scores, tokens, cost, time, turns) and OUT/raw/ (each question's responses and contexts' file lists,+not for publishing). Questions already in rows.jsonl are skipped, so a run can be resumed. A question+whose call fails is tried once more at the end of the run, and only a second failure stays in its row.+"""+import argparse+import datetime+import fcntl+import hashlib+import json+import math+import os+import re+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from concurrent.futures import ThreadPoolExecutor++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import agent_tools # noqa: E402+from pack_arm import PACK_ARMS, pack_context # noqa: E402+from score import normalize_answer, score_answer # noqa: E402+from redact import redact # noqa: E402+from tokens import Counter, build_truncation # noqa: E402++PROMPT_VERSION = "whole-repo-v1"+PROMPT = ("{context}Repository {repo} at commit {sha}. Issue: {issue}\n\n"+ "List the source files that must change to resolve this issue, most likely first, at most 10. "+ "Answer with JSON only, in the form {{\"files\": [\"path/to/file\", ...]}}, with paths relative "+ "to the repository root.")+AGENT_CONTEXT = ("You can explore the repository at that commit with the tools grep, find, list_dir and read, "+ "in at most {turns} turns. Then give the answer.\n\n")+LAST_TURN = "The turn limit is reached. Answer now, with the JSON only."+BUDGETS = {"64K": 65536, "128K": 131072, "256K": 262144, "512K": 524288, "1M": 1015808}+CACHE_RETENTION = "24h"+PROFILES = {+ "meta": {"base_url": "https://api.meta.ai/v1", "api": "responses", "model": "muse-spark-1.3",+ "key_env": "MODEL_API_KEY", "cache_key": True, "affinity": False},+ "baseten": {"base_url": "https://inference.baseten.co/v1", "api": "chat", "model": "meta-models/muse-spark-open",+ "key_env": "BASETEN_API_KEY", "cache_key": False, "affinity": True},+ "mock": {"base_url": None, "api": "responses", "model": "mock", "key_env": "MODEL_API_KEY",+ "cache_key": True, "affinity": True},+}+++class CapReached(Exception):+ pass+++def now_iso():+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def sha12(text):+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]+++def logged_total(log_path, provider):+ """The cost_usd total of one provider's lines in the global spend log."""+ if not os.path.exists(log_path):+ return 0.0+ total = 0.0+ with open(log_path) as f:+ for line in f:+ if line.strip():+ r = json.loads(line)+ if r.get("provider") == provider:+ total += r.get("cost_usd") or 0.0+ return total+++class Spend:+ """What this run has spent (OUT/spend.json, for resuming) and the provider's global log and cap."""++ def __init__(self, path, cap, price, log_path, provider, global_cap):+ self.path, self.cap, self.price, self.lock = path, cap, price, threading.Lock()+ self.spent = json.load(open(path))["spent_usd"] if os.path.exists(path) else 0.0+ self.reserved = 0.0+ self.log_path, self.provider, self.global_cap = log_path, provider, global_cap+ self.logged = logged_total(log_path, provider) # every run of the provider, this one's past calls included++ def cost(self, tin, tcached, tout):+ p = self.price+ return ((tin - tcached) * p["input"] + tcached * p.get("cached_input", p["input"]) + tout * p["output"]) / 1e6++ def reserve(self, prompt_tokens, max_out):+ worst = self.cost(prompt_tokens, 0, max_out)+ with self.lock:+ if self.spent + self.reserved + worst > self.cap:+ raise CapReached(f"run spend cap ${self.cap:.2f}: spent ${self.spent:.4f}, the next call could cost "+ f"${worst:.4f}")+ if self.global_cap is not None and self.logged + self.reserved + worst > self.global_cap:+ raise CapReached(f"global {self.provider} cap ${self.global_cap:.2f} (caps.json): logged "+ f"${self.logged:.4f}, the next call could cost ${worst:.4f}")+ self.reserved += worst+ return worst++ def settle(self, worst, actual, record):+ with self.lock:+ self.reserved -= worst+ self.spent += actual+ self.logged += actual+ with open(self.path + ".part", "w") as f:+ json.dump({"spent_usd": self.spent, "cap_usd": self.cap}, f)+ os.replace(self.path + ".part", self.path)+ with open(self.log_path, "a") as f:+ fcntl.flock(f, fcntl.LOCK_EX)+ f.write(json.dumps(record, sort_keys=True) + "\n")+ f.flush()+ fcntl.flock(f, fcntl.LOCK_UN)+++class Client:+ def __init__(self, base_url, key, api):+ self.base, self.key, self.api = base_url.rstrip("/"), key, api++ def post(self, path, body, headers=None, timeout=900):+ data = json.dumps(body).encode()+ delay = 5+ for attempt in range(6):+ req = urllib.request.Request(self.base + path, data=data, method="POST", headers={+ "Content-Type": "application/json", "Authorization": "Bearer " + self.key, **(headers or {})})+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return json.loads(r.read())+ except urllib.error.HTTPError as e:+ msg = e.read()[:500].decode("utf-8", "replace")+ if e.code in (429, 500, 502, 503, 504) and attempt < 5:+ time.sleep(delay)+ delay *= 3+ continue+ raise RuntimeError(f"HTTP {e.code}: {msg}")+ except (urllib.error.URLError, TimeoutError, ConnectionError) as e:+ if attempt < 5:+ time.sleep(delay)+ delay *= 3+ continue+ raise RuntimeError(f"connection: {e}")+++def usage_of(resp, api):+ u = resp.get("usage") or {}+ if api == "responses":+ return (u.get("input_tokens", 0), (u.get("input_tokens_details") or {}).get("cached_tokens", 0) or 0,+ u.get("output_tokens", 0), (u.get("output_tokens_details") or {}).get("reasoning_tokens", 0) or 0)+ return (u.get("prompt_tokens", 0), (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0) or 0,+ u.get("completion_tokens", 0), (u.get("completion_tokens_details") or {}).get("reasoning_tokens", 0) or 0)+++def text_of(resp, api):+ if api == "responses":+ parts = []+ for o in resp.get("output") or []:+ if o.get("type") == "message":+ parts.extend(c.get("text", "") for c in o.get("content") or [] if c.get("type") == "output_text")+ return "".join(parts)+ ch = (resp.get("choices") or [{}])[0].get("message") or {}+ return ch.get("content") or ""+++def user_message(text):+ return {"type": "message", "role": "user", "content": [{"type": "input_text", "text": text}]}+++def parse_files(text):+ """The last JSON object in the text that has a "files" list."""+ dec, found = json.JSONDecoder(), None+ for m in re.finditer(r"\{", text or ""):+ try:+ obj, _ = dec.raw_decode(text, m.start())+ except json.JSONDecodeError:+ continue+ if isinstance(obj, dict) and isinstance(obj.get("files"), list):+ found = obj["files"]+ return found+++def arm_label(arm, budget, prefix_share, standin=False):+ core = arm+ if arm == "pack-cache" and abs(prefix_share - PACK_ARMS["pack-cache"][1]) > 1e-9:+ core = f"pack-cache{prefix_share:g}"+ return core + ("@" + budget if budget else "") + ("-standin" if standin else "")+++def estimate_arm(arm, prefix_share):+ """The arm's name in estimate.py's grids."""+ if arm == "pack-cache" and abs(prefix_share - PACK_ARMS["pack-cache"][1]) > 1e-9:+ return f"pack-cache{prefix_share:g}"+ return arm+++class Runner:+ def __init__(self, a, key, prices, provider, global_cap):+ self.a = a+ self.client = Client(a.base_url, key, a.api)+ self.prof = PROFILES[a.profile]+ self.provider = provider+ self.spend = Spend(os.path.join(a.out, "spend.json"), a.spend_cap, prices["models"][a.model], a.spend_log,+ provider, global_cap)+ self.counter = Counter(a.tokenizer)+ self.trunc_cache, self.files_cache, self.lock = {}, {}, threading.Lock()+ self.stop = threading.Event()++ def cache_fields(self, key):+ """(body fields, headers) that carry the cache key."""+ body, headers = {}, {}+ if self.prof["cache_key"]:+ body["prompt_cache_key"] = key+ if self.a.api == "responses":+ body["prompt_cache_retention"] = CACHE_RETENTION+ if self.prof["affinity"]:+ headers["x-session-affinity"] = hashlib.sha256(key.encode()).hexdigest()[:32]+ return body, headers++ def call(self, body, prompt_tokens, headers, info):+ a = self.a+ worst = self.spend.reserve(prompt_tokens, a.max_output_tokens)+ t0 = time.time()+ rec = {"time": now_iso(), "provider": self.provider, "model": a.model, "api": a.api, "arm": a.label,+ "budget": a.budget, "run": os.path.abspath(a.out), "cache_key": info.get("cache_key"),+ "repo": info["repo"], "question": info["question"], "turn": info.get("turn", 1)}+ try:+ resp = self.client.post("/responses" if a.api == "responses" else "/chat/completions", body, headers)+ except Exception as e:+ self.spend.settle(worst, 0.0, dict(rec, status="error", error=str(e)[:200], input_tokens=0,+ cached_tokens=0, output_tokens=0, reasoning_tokens=0,+ seconds=round(time.time() - t0, 3), cost_usd=0.0))+ raise+ tin, tcached, tout, treason = usage_of(resp, a.api)+ cost = self.spend.cost(tin, tcached, tout)+ secs = time.time() - t0+ self.spend.settle(worst, cost, dict(rec, status="ok", input_tokens=tin, cached_tokens=tcached,+ output_tokens=tout, reasoning_tokens=treason, seconds=round(secs, 3),+ cost_usd=cost))+ return resp, {"in": tin, "cached": tcached, "out": tout, "reasoning": treason, "cost": cost, "seconds": secs}++ def single(self, prompt, key, info):+ a = self.a+ fields, headers = self.cache_fields(key)+ if a.api == "responses":+ body = {"model": a.model, "input": [user_message(prompt)], "store": False,+ "reasoning": {"effort": a.reasoning_effort}, "max_output_tokens": a.max_output_tokens, **fields}+ else:+ body = {"model": a.model, "messages": [{"role": "user", "content": prompt}],+ "max_tokens": a.max_output_tokens, **fields}+ if a.reasoning_effort:+ body["reasoning_effort"] = a.reasoning_effort+ resp, u = self.call(body, self.counter.count(prompt), headers, info)+ return text_of(resp, a.api), [u], [resp], 1, 0++ def agent(self, prompt, tools, key, info):+ a = self.a+ usages, raws, ncalls = [], [], 0+ fields, headers = self.cache_fields(key)+ last_in = self.counter.count(prompt)+ if a.api == "responses":+ items, prev = [user_message(prompt)], None+ final_next = False+ for turn in range(1, a.max_turns + 2):+ body = {"model": a.model, "input": items, "store": True, "reasoning": {"effort": a.reasoning_effort},+ "max_output_tokens": a.max_output_tokens, **fields}+ if not final_next:+ body["tools"] = agent_tools.responses_tools()+ if prev:+ body["previous_response_id"] = prev+ resp, u = self.call(body, last_in + sum(self.counter.count(str(i.get("output", i.get("content", ""))))+ for i in items), headers, dict(info, turn=turn))+ usages.append(u)+ raws.append(resp)+ last_in = u["in"] + u["out"]+ calls = [o for o in resp.get("output") or [] if o.get("type") == "function_call"]+ if not calls or final_next:+ return text_of(resp, a.api), usages, raws, turn, ncalls+ items = []+ for c in calls:+ ncalls += 1+ try:+ args = json.loads(c.get("arguments") or "{}")+ except json.JSONDecodeError:+ args = {}+ items.append({"type": "function_call_output", "call_id": c["call_id"],+ "output": tools.call(c.get("name"), args)})+ if turn == a.max_turns or last_in > a.agent_max_context:+ items.append(user_message(LAST_TURN))+ final_next = True+ prev = resp["id"]+ else:+ msgs, final_next = [{"role": "user", "content": prompt}], False+ for turn in range(1, a.max_turns + 2):+ body = {"model": a.model, "messages": msgs, "max_tokens": a.max_output_tokens, **fields}+ if a.reasoning_effort:+ body["reasoning_effort"] = a.reasoning_effort+ if not final_next:+ body["tools"] = agent_tools.chat_tools()+ resp, u = self.call(body, self.counter.count(json.dumps(msgs)), headers, dict(info, turn=turn))+ usages.append(u)+ raws.append(resp)+ msg = (resp.get("choices") or [{}])[0].get("message") or {}+ calls = msg.get("tool_calls") or []+ msgs.append({k: v for k, v in msg.items() if k in ("role", "content", "tool_calls")})+ if not calls or final_next:+ return msg.get("content") or "", usages, raws, turn, ncalls+ for c in calls:+ ncalls += 1+ try:+ args = json.loads(c["function"].get("arguments") or "{}")+ except json.JSONDecodeError:+ args = {}+ msgs.append({"role": "tool", "tool_call_id": c["id"],+ "content": tools.call(c["function"].get("name"), args)})+ if turn == a.max_turns or u["in"] + u["out"] > a.agent_max_context:+ msgs.append({"role": "user", "content": LAST_TURN})+ final_next = True+ return "", usages, raws, a.max_turns + 1, ncalls++ def context(self, name, q, text):+ """(context text, included paths or None, context tokens, shared-prefix sha256 or None, pack info)."""+ a = self.a+ if a.arm == "noctx":+ return "", None, 0, hashlib.sha256(PROMPT.encode()).hexdigest(), {}+ if a.arm == "agent":+ ctx = AGENT_CONTEXT.format(turns=a.max_turns)+ return ctx, None, 0, hashlib.sha256(ctx.encode()).hexdigest(), {}+ if a.arm == "trunc":+ with self.lock:+ if name not in self.trunc_cache:+ t, inc, ntok = build_truncation(a.work, name, a.budget_tokens, self.counter)+ self.trunc_cache[name] = (t, inc, ntok, hashlib.sha256(t.encode("utf-8")).hexdigest())+ ctx, included, ntok, sha = self.trunc_cache[name]+ return ctx + "\n\n", included, ntok, sha, {}+ layout, share = PACK_ARMS[a.arm]+ if a.arm == "pack-cache":+ share = a.prefix_share+ p = pack_context(a.graphicle, os.path.join(a.work, "src", name), os.path.join(a.work, "data", name), text,+ a.budget_tokens, a.tokenizer, a.pack_standin, layout=layout, prefix_share=share)+ info = {k: p.get(k) for k in ("layout", "prefix_share", "prefix_tokens", "prefix_sha256", "prefix_ok",+ "suffix_tokens")}+ if layout and p.get("prefix_ok") is False:+ raise RuntimeError("the pack's prefix does not match its prefix_sha256 or does not come first")+ return p["text"] + "\n\n", p["included"], p["tokens"], p.get("prefix_sha256"), info++ def tools_for(self, name):+ """Fresh tools for one question (their read list is the agent's context), sharing the file list."""+ src = os.path.join(self.a.work, "src", name)+ with self.lock:+ if name not in self.files_cache:+ self.files_cache[name] = agent_tools.RepoTools(src).files+ return agent_tools.RepoTools(src, self.files_cache[name])++ def one(self, q, text):+ a = self.a+ name = q["id"].rsplit("-", 1)[0]+ row = {"id": q["id"], "repo": name, "arm": a.arm, "label": a.label, "budget": a.budget,+ "budget_tokens": a.budget_tokens, "model": a.model, "api": a.api, "profile": a.profile,+ "gold": q["gold"], "names_gold_path": q["names_gold_path"], "error": None}+ if a.redact:+ # Emails and @handles out of the issue text before anything is built or sent (redact.py).+ text, n_emails, n_handles = redact(text)+ row["redacted"] = {"emails": n_emails, "handles": n_handles}+ t0 = time.time()+ try:+ ctx, included, ntok, prefix_sha, pinfo = self.context(name, q, text)+ key = f"wrb:{name}@{q['S'][:12]}:{a.label}:{(prefix_sha or 'none')[:12]}"+ row.update({"cache_key": key, **pinfo})+ prompt = PROMPT.format(context=ctx, repo=q["repo"], sha=q["S"], issue=text)+ tools = self.tools_for(name)+ info = {"repo": name, "question": q["id"], "cache_key": key}+ if a.arm == "agent":+ answer, usages, raws, turns, ncalls = self.agent(prompt, tools, key, info)+ included = tools.read_paths+ else:+ answer, usages, raws, turns, ncalls = self.single(prompt, key, info)+ files = parse_files(answer)+ norm = normalize_answer(files, tools.file_set) if files is not None else []+ row.update(score_answer(norm, q["gold"]))+ row.update({"files": norm, "answer_parsed": files is not None, "context_tokens": ntok,+ "context_files": len(included) if included is not None else None,+ "context_recall": (sum(1 for g in q["gold"] if g in set(included)) / len(q["gold"])+ if included is not None else None),+ "tokens_in": sum(u["in"] for u in usages), "tokens_cached": sum(u["cached"] for u in usages),+ "tokens_out": sum(u["out"] for u in usages),+ "tokens_reasoning": sum(u["reasoning"] for u in usages),+ "cached_per_call": [u["cached"] for u in usages],+ "cost_usd": sum(u["cost"] for u in usages), "turns": turns, "tool_calls": ncalls,+ "prompt_tokens_counted": self.counter.count(prompt) if a.arm != "agent" else None})+ with open(os.path.join(a.out, "raw", q["id"] + ".json"), "w") as f:+ json.dump({"responses": raws, "included": included, "answer": answer}, f)+ except CapReached:+ self.stop.set()+ raise+ except Exception as e:+ row["error"] = f"{type(e).__name__}: {str(e)[:300]}"+ row["wall_seconds"] = round(time.time() - t0, 2)+ return row+++def bench_commit():+ """The commit of this code: BENCH_COMMIT beside run.py (written when the folder is exported), else git."""+ path = os.path.join(HERE, "BENCH_COMMIT")+ if os.path.exists(path):+ with open(path) as f:+ return f.read().strip()+ r = subprocess.run(["git", "rev-parse", "HEAD"], cwd=HERE, capture_output=True, text=True)+ return r.stdout.strip() or None+++def interleave(groups):+ """Round robin over the groups: the first question of each, then the second of each, ..."""+ out, i = [], 0+ while any(i < len(items) for _n, items in groups):+ out.extend(items[i] for _n, items in groups if i < len(items))+ i += 1+ return out+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--arm", required=True, choices=["noctx", "pack", "pack-cache", "pack-stable", "trunc", "agent"])+ ap.add_argument("--budget", default=None, choices=list(BUDGETS))+ ap.add_argument("--work", required=True)+ ap.add_argument("--questions", required=True)+ ap.add_argument("--texts", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--profile", default="meta", choices=list(PROFILES))+ ap.add_argument("--base-url")+ ap.add_argument("--model")+ ap.add_argument("--api", choices=["responses", "chat"])+ ap.add_argument("--key-file")+ ap.add_argument("--spend-cap", default="20",+ help="dollars (default 20), or auto: 1.5 x the run's cached estimate in whole dollars, at most "+ "what the global cap leaves")+ ap.add_argument("--prices", default=os.path.join(HERE, "prices.json"))+ ap.add_argument("--caps", default=os.path.join(HERE, "caps.json"))+ ap.add_argument("--spend-log", help="the global spend log (default WORKDIR/spend/spend-log.jsonl)")+ ap.add_argument("--repos", default="")+ ap.add_argument("--limit", type=int, default=0)+ ap.add_argument("--jobs", type=int, default=1)+ ap.add_argument("--order", choices=["grouped", "interleaved"])+ ap.add_argument("--reasoning-effort", default="medium")+ ap.add_argument("--max-output-tokens", type=int, default=8192)+ ap.add_argument("--max-turns", type=int, default=30)+ ap.add_argument("--agent-max-context", type=int, default=900000,+ help="the agent answers at once when a turn's context passes this many tokens")+ ap.add_argument("--tokenizer")+ ap.add_argument("--graphicle", default="graphicle")+ ap.add_argument("--prefix-share", type=float, default=PACK_ARMS["pack-cache"][1],+ help="the cache layout's prefix share for --arm pack-cache")+ ap.add_argument("--pack-standin", action="store_true")+ ap.add_argument("--label")+ ap.add_argument("--redact", action="store_true",+ help="strip email addresses and @handles from the issue text first (redact.py)")+ a = ap.parse_args()+ if a.arm in ("pack", "pack-cache", "pack-stable", "trunc") and not a.budget:+ raise SystemExit("--budget is needed for the pack and truncation arms")+ if a.pack_standin and a.arm != "pack":+ raise SystemExit("--pack-standin goes with --arm pack only")+ prof = PROFILES[a.profile]+ a.base_url = a.base_url or prof["base_url"]+ a.model = a.model or prof["model"]+ a.api = a.api or prof["api"]+ a.order = a.order or ("interleaved" if a.arm == "agent" else "grouped")+ if not a.base_url:+ raise SystemExit(f"--base-url is needed with --profile {a.profile}")+ a.budget_tokens = BUDGETS[a.budget] if a.budget else None+ a.work = os.path.abspath(a.work)+ a.spend_log = os.path.abspath(a.spend_log or os.path.join(a.work, "spend", "spend-log.jsonl"))+ a.label = a.label or arm_label(a.arm, a.budget, a.prefix_share, a.pack_standin)+ prices = json.load(open(a.prices))+ if a.model not in prices["models"]:+ raise SystemExit(f"no price for {a.model} in {a.prices}")+ provider = prices["models"][a.model].get("provider", a.profile)+ caps = json.load(open(a.caps))["usd"] if os.path.exists(a.caps) else {}+ global_cap = caps.get(provider)+ key = os.environ.get(prof["key_env"], "")+ if a.key_file:+ key = open(a.key_file).read().strip()+ if not key:+ raise SystemExit(f"no key: set {prof['key_env']} or pass --key-file")+ os.makedirs(os.path.join(a.out, "raw"), exist_ok=True)+ os.makedirs(os.path.dirname(a.spend_log), exist_ok=True)++ # One run per provider at a time, so the global cap is checked against everything in flight.+ lock = open(a.spend_log + f".{provider}.lock", "w")+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError:+ print(f"REFUSED: another run for {provider} holds {lock.name}", file=sys.stderr)+ sys.exit(3)++ repos = [r for r in a.repos.split(",") if r]+ groups = []+ for path in sorted(os.listdir(a.questions)):+ if not (path.startswith("questions-") and path.endswith(".jsonl")):+ continue+ name = path[len("questions-"):-len(".jsonl")]+ if repos and name not in repos:+ continue+ texts = {}+ for line in open(os.path.join(a.texts, f"texts-{name}.jsonl")):+ t = json.loads(line)+ texts[t["id"]] = t["text"]+ qs = [json.loads(l) for l in open(os.path.join(a.questions, path)) if l.strip()]+ if a.limit:+ qs = qs[:a.limit]+ groups.append((name, [(q, texts[q["id"]]) for q in qs]))+ rows_path = os.path.join(a.out, "rows.jsonl")+ done = set()+ if os.path.exists(rows_path):+ done = {json.loads(l)["id"] for l in open(rows_path) if l.strip()}+ total_q = sum(len(items) for _n, items in groups)+ groups = [(n, [(q, t) for q, t in items if q["id"] not in done]) for n, items in groups]+ left = sum(len(items) for _n, items in groups)++ # The run's own estimate (estimate.py, with caching) for the questions it still has to do.+ import estimate+ est = estimate.run_estimate(a.questions, a.texts, estimate_arm(a.arm, a.prefix_share), a.budget,+ [n for n, _ in groups], a.limit, a.model, prices)+ frac = left / total_q if total_q else 0.0+ est_left = {k: v * frac for k, v in est.items()}+ logged = logged_total(a.spend_log, provider)+ print(f"{a.label}: {left} of {total_q} questions to do; estimate ${est_left['cached']:.2f} with caching "+ f"(${est_left['uncached']:.2f} without); {provider} log total ${logged:.2f}"+ + (f", global cap ${global_cap:.2f}" if global_cap is not None else ", no global cap"), flush=True)+ if global_cap is not None and logged + est_left["cached"] > global_cap:+ print(f"REFUSED: the {provider} log total ${logged:.2f} plus this run's estimate ${est_left['cached']:.2f} "+ f"would pass the global cap ${global_cap:.2f} ({a.caps})", file=sys.stderr)+ sys.exit(3)+ if str(a.spend_cap).lower() == "auto":+ # 1.5 x the cached estimate of what is left, in whole dollars, never past what the global cap leaves.+ spent_before = 0.0+ if os.path.exists(os.path.join(a.out, "spend.json")):+ with open(os.path.join(a.out, "spend.json")) as f:+ spent_before = json.load(f)["spent_usd"]+ allow = float(math.ceil(1.5 * est_left["cached"]))+ if global_cap is not None:+ allow = min(allow, global_cap - logged)+ a.spend_cap = spent_before + max(allow, 0.0)+ print(f"{a.label}: spend cap auto = ${a.spend_cap:.2f}", flush=True)+ else:+ a.spend_cap = float(a.spend_cap)++ runner = Runner(a, key, prices, provider, global_cap)+ graphicle_version = ""+ if a.arm.startswith("pack"):+ graphicle_version = subprocess.run([a.graphicle, "--version"], capture_output=True, text=True).stdout.strip()+ meta = {"label": a.label, "arm": a.arm, "budget": a.budget, "budget_tokens": a.budget_tokens, "model": a.model,+ "api": a.api, "profile": a.profile, "provider": provider, "base_url": a.base_url,+ "reasoning_effort": a.reasoning_effort, "max_output_tokens": a.max_output_tokens,+ "max_turns": a.max_turns if a.arm == "agent" else None, "order": a.order, "jobs": a.jobs,+ "prefix_share": a.prefix_share if a.arm == "pack-cache" else PACK_ARMS.get(a.arm, (None, None))[1],+ "cache_key": "prompt_cache_key" if PROFILES[a.profile]["cache_key"] else None,+ "cache_retention": CACHE_RETENTION if PROFILES[a.profile]["cache_key"] and a.api == "responses" else None,+ "session_affinity": PROFILES[a.profile]["affinity"],+ "counter": runner.counter.name, "prompt_version": PROMPT_VERSION, "graphicle": graphicle_version,+ "context_source": ("graphicle context (stand-in, not a result)" if a.pack_standin else+ "graphicle pack" if a.arm.startswith("pack") else a.arm),+ "spend_cap_usd": a.spend_cap, "global_cap_usd": global_cap, "spend_log": a.spend_log,+ "estimate_usd": est_left, "bench_commit": bench_commit(), "redact": a.redact, "started": now_iso()}+ wlock = threading.Lock()+ stopped = None+ retry = []++ def write(row):+ with wlock:+ with open(rows_path, "a") as f:+ f.write(json.dumps(row, sort_keys=True) + "\n")++ def work(item, last_try=False):+ nonlocal stopped+ if runner.stop.is_set():+ return+ q, t = item+ try:+ row = runner.one(q, t)+ except CapReached as e:+ stopped = str(e)+ return+ if row["error"] and not last_try:+ with wlock:+ retry.append(item)+ return+ write(row)++ if a.order == "grouped":+ for _name, items in groups:+ if runner.stop.is_set() or not items:+ continue+ work(items[0]) # alone, so the others can read its prefix from the cache+ with ThreadPoolExecutor(max(1, a.jobs)) as ex:+ list(ex.map(work, items[1:]))+ else:+ with ThreadPoolExecutor(max(1, a.jobs)) as ex:+ list(ex.map(work, interleave(groups)))+ for item in list(retry):+ work(item, last_try=True)+ meta["finished"] = now_iso()+ meta["spend_usd"] = runner.spend.spent+ meta["stopped"] = stopped+ meta["retried"] = len(retry)+ with open(os.path.join(a.out, "run.json"), "w") as f:+ json.dump(meta, f, indent=1, sort_keys=True)+ n = sum(1 for _ in open(rows_path)) if os.path.exists(rows_path) else 0+ print(f"{a.label}: {n} rows, spent ${runner.spend.spent:.4f}; {provider} log total ${runner.spend.logged:.4f}"+ + (f"; STOPPED: {stopped}" if stopped else ""))+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/score.py b/bench/whole-repo/score.pynew file mode 100644index 0000000..f85e67a--- /dev/null+++ b/bench/whole-repo/score.py@@ -0,0 +1,155 @@+#!/usr/bin/env python3+"""Scores for the whole-repository benchmark.++usage: score.py --runs DIR [DIR ...] --out FILE [--boot 2000] [--seed 1]++Each DIR is a run folder written by run.py (rows.jsonl and run.json). Writes a JSON summary with, per+run (arm and budget) and per repository plus pooled:+ n, hit@1, hit@3, hit@5 (a gold file among the first k answers), all-gold@5, MRR (reciprocal rank+ of the first gold file in the answer, 0 when none of the 10 is gold), context recall (pack and+ truncation: the share of gold files inside the context; the agent: the share of gold files it read),+ tokens in (cached and not), tokens out (reasoning included), cost, wall seconds and turns, with 95%+ bootstrap intervals (percentile, resampling questions) on the means;+ the same rows without the questions whose text names a gold file path;+ and paired comparisons between runs on the same questions: McNemar's exact test on hit@5.+"""+import argparse+import json+import math+import os+import random++METRICS = ["hit1", "hit3", "hit5", "allgold5", "rr", "context_recall", "tokens_in", "tokens_cached",+ "tokens_out", "tokens_reasoning", "cost_usd", "wall_seconds", "turns"]+++def normalize_answer(files, file_set=None, limit=10):+ """Clean the model's paths: strip spaces, ./, a/ b/ prefixes, :line suffixes; resolve a leading+ folder that is not part of the repository when the rest is a file of it. Dedupe, keep order."""+ out = []+ for f in files or []:+ if not isinstance(f, str):+ continue+ p = f.strip().strip("`'\"")+ p = p.split("#L")[0]+ while p.startswith("./"):+ p = p[2:]+ if p[:2] in ("a/", "b/") and file_set is not None and p not in file_set and p[2:] in file_set:+ p = p[2:]+ p = p.lstrip("/")+ head, sep, tail = p.rpartition(":")+ if sep and tail.replace("-", "").isdigit():+ p = head+ if file_set is not None and p not in file_set and "/" in p and p.split("/", 1)[1] in file_set:+ p = p.split("/", 1)[1]+ if p and p not in out:+ out.append(p)+ return out[:limit]+++def score_answer(files, gold):+ g = set(gold)+ first = next((i + 1 for i, f in enumerate(files) if f in g), None)+ return {+ "hit1": int(first is not None and first <= 1),+ "hit3": int(first is not None and first <= 3),+ "hit5": int(first is not None and first <= 5),+ "allgold5": int(g.issubset(set(files[:5]))),+ "rr": 1.0 / first if first else 0.0,+ }+++def mean(xs):+ return sum(xs) / len(xs) if xs else None+++def boot_ci(xs, rng, n):+ if not xs:+ return None+ ms = sorted(mean([xs[rng.randrange(len(xs))] for _ in xs]) for _ in range(n))+ return [ms[int(0.025 * n)], ms[min(n - 1, int(0.975 * n))]]+++def mcnemar_exact(b, c):+ """Two-sided exact McNemar p-value from the discordant counts b and c."""+ n = b + c+ if n == 0:+ return 1.0+ k = min(b, c)+ p = sum(math.comb(n, i) for i in range(0, k + 1)) / 2 ** n+ return min(1.0, 2 * p)+++def summarize(rows, rng, nboot):+ out = {"n": len(rows)}+ for m in METRICS:+ xs = [r[m] for r in rows if r.get(m) is not None]+ out[m] = mean(xs)+ if m in ("hit1", "hit3", "hit5", "allgold5", "rr", "context_recall", "cost_usd", "tokens_in", "tokens_out"):+ out[m + "_ci"] = boot_ci(xs, rng, nboot)+ out["errors"] = sum(1 for r in rows if r.get("error"))+ out["cost_usd_total"] = sum(r.get("cost_usd") or 0 for r in rows)+ return out+++def load_run(d):+ meta = json.load(open(os.path.join(d, "run.json")))+ rows = [json.loads(l) for l in open(os.path.join(d, "rows.jsonl")) if l.strip()]+ return meta, rows+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--runs", nargs="+", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--boot", type=int, default=2000)+ ap.add_argument("--seed", type=int, default=1)+ a = ap.parse_args()+ runs = []+ seen = set()+ for d in a.runs:+ meta, rows = load_run(d)+ label = meta["label"]+ if label in seen: # two runs of one arm (another api or model): name the second by its folder+ label = f"{label} [{os.path.basename(os.path.normpath(d))}]"+ seen.add(label)+ runs.append((label, meta, rows))+ result = {"runs": {}, "paired": []}+ for label, meta, rows in runs:+ rng = random.Random(a.seed)+ per = {}+ for repo in sorted({r["repo"] for r in rows}):+ rr = [r for r in rows if r["repo"] == repo]+ per[repo] = {"all": summarize(rr, rng, a.boot),+ "without_named": summarize([r for r in rr if not r.get("names_gold_path")], rng, a.boot)}+ per["pooled"] = {"all": summarize(rows, rng, a.boot),+ "without_named": summarize([r for r in rows if not r.get("names_gold_path")], rng, a.boot)}+ result["runs"][label] = {"meta": {k: meta.get(k) for k in+ ("arm", "budget", "budget_tokens", "model", "api", "counter", "context_source",+ "graphicle", "started", "finished", "spend_usd")}, "rows": per}+ for i in range(len(runs)):+ for j in range(i + 1, len(runs)):+ la, _, ra = runs[i]+ lb, _, rb = runs[j]+ ia = {r["id"]: r for r in ra if not r.get("error")}+ ib = {r["id"]: r for r in rb if not r.get("error")}+ common = sorted(set(ia) & set(ib))+ if not common:+ continue+ for scope in ["pooled"] + sorted({ia[k]["repo"] for k in common}):+ ks = [k for k in common if scope == "pooled" or ia[k]["repo"] == scope]+ b = sum(1 for k in ks if ia[k]["hit5"] and not ib[k]["hit5"])+ c = sum(1 for k in ks if ib[k]["hit5"] and not ia[k]["hit5"])+ result["paired"].append({"a": la, "b": lb, "scope": scope, "n": len(ks), "a_only": b, "b_only": c,+ "hit5_a": mean([ia[k]["hit5"] for k in ks]),+ "hit5_b": mean([ib[k]["hit5"] for k in ks]),+ "mcnemar_p": mcnemar_exact(b, c)})+ with open(a.out, "w") as f:+ json.dump(result, f, indent=1, sort_keys=True)+ for label in result["runs"]:+ p = result["runs"][label]["rows"]["pooled"]["all"]+ print(f"{label}: n={p['n']} hit@5={p['hit5']} MRR={p['rr']} cost=${p['cost_usd_total']:.2f} errors={p['errors']}")+++if __name__ == "__main__":+ main()diff --git a/bench/whole-repo/snapshots.json b/bench/whole-repo/snapshots.jsonnew file mode 100644index 0000000..0bee09e--- /dev/null+++ b/bench/whole-repo/snapshots.json@@ -0,0 +1,10 @@+{+ "angular": {"sha": "c60c41e29aa175ca25b0e91a40f5ab115b46139f", "committed": "2026-09-13T21:20:24Z"},+ "elasticsearch": {"sha": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0", "committed": "2026-09-13T20:09:26Z"},+ "godot": {"sha": "2f698aa5fe31d0be68f205ec41aec9365081d364", "committed": "2026-09-13T08:18:55Z"},+ "home-assistant": {"sha": "09e3474f91be03d4ac5a70a698474986fc759bcf", "committed": "2026-09-13T20:00:07Z"},+ "keycloak": {"sha": "06f4cad3925fd2cd95dc81d55b58b6d0282a7806", "committed": "2026-09-11T12:33:12Z"},+ "kubernetes": {"sha": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7", "committed": "2026-09-12T20:05:12Z"},+ "pytorch": {"sha": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7", "committed": "2026-09-13T22:40:38Z"},+ "vscode": {"sha": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b", "committed": "2026-09-13T21:23:17Z"}+}diff --git a/bench/whole-repo/test_runner.py b/bench/whole-repo/test_runner.pynew file mode 100644index 0000000..da98a93--- /dev/null+++ b/bench/whole-repo/test_runner.py@@ -0,0 +1,470 @@+#!/usr/bin/env python3+"""Tests of the runner, the global spend log, the caps and the estimate, end to end on the mock.++usage: python test_runner.py [-v]+ MOCK_HOST=ADDR the address the mock listens on (default: the first of `hostname -I`, else+ 127.0.0.1; some machines refuse TCP to 127.0.0.1)+ BENCH_WORK=DIR optional: a benchmark work folder with kubernetes checked out and indexed, to+ BENCH_GRAPHICLE=BIN also run the pack arms (and the cache layouts when BIN has them) on 2 questions+ BENCH_TOKENIZER=FILE++Builds a tiny work folder (two git repositories named like benchmark repositories, their manifests,+question and text files), serves mock_server.py in a thread and runs run.py as a subprocess. No model,+no key and no spend: the mock is priced like Muse Spark 1.3 only to exercise the caps.+"""+import fcntl+import json+import os+import shutil+import subprocess+import sys+import tempfile+import threading+import unittest++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import estimate # noqa: E402+import mock_server # noqa: E402+from run import BUDGETS, Spend, CapReached, logged_total # noqa: E402+from tokens import Counter, build_manifest # noqa: E402++++def read_json(path):+ with open(path) as f:+ return json.load(f)+++def read_jsonl(path):+ if not os.path.exists(path):+ return []+ with open(path) as f:+ return [json.loads(line) for line in f if line.strip()]+++PRICES = read_json(os.path.join(HERE, "prices.json"))+MOCK_PRICE = PRICES["models"]["mock"]++# A stand-in for `graphicle pack` that keeps the cache layout's JSON contract (graphicle.pack.v1 plus+# layout, prefix_share, prefix_tokens, prefix_sha256 and each section's part), for testing the+# runner's and recall.py's layout paths without a Graphicle build. Never used for results.+FAKE_PACK = r'''+import hashlib, json, os, subprocess, sys+args = sys.argv[1:]+if args[:1] == ["--version"]:+ print("graphicle (test stand-in)")+ sys.exit(0)+if args[:2] == ["pack", "--help"]:+ print("usage: graphicle pack [QUESTION] --layout standard|cache --prefix-share F")+ sys.exit(0)+q, opt = args[1], {args[i]: args[i + 1] for i in range(2, len(args) - 1, 2)}+src, budget, fmt = opt["--project"], int(opt["--budget"]), opt["--format"]+layout, share = opt.get("--layout", "standard"), float(opt.get("--prefix-share", "0.9"))+files = subprocess.run(["git", "ls-files"], cwd=src, capture_output=True, text=True).stdout.split()+++def chunk(path, text):+ return {"path": path, "start_line": 1, "end_line": text.count("\n"), "whole": True,+ "tokens": len(text.encode()) // 4, "why": "test", "text": text}+++def body(p):+ return '<file path="%s">\n' % p + open(os.path.join(src, p)).read() + "</file>\n"+++header = chunk("", "# Code pack\n\nRepository map:\n" + "".join("- %s\n" % p for p in files) * 8)+words = [w.lower() for w in q.split() if len(w) > 3]+focus = [p for p in files if any(w in p.lower() for w in words)] or files[:1]+if layout == "cache":+ prefix, used = [header], header["tokens"]+ for p in files: # question-independent: files by path while the prefix share lasts+ c = chunk(p, body(p))+ if used + c["tokens"] > int(budget * share):+ break+ prefix.append(c)+ used += c["tokens"]+ held = {c["path"] for c in prefix}+ suffix = [chunk(p, body(p)) for p in focus if p not in held] + [chunk("", "Focus: %s\n" % ", ".join(focus))]+ sections = [{"name": "map", "part": "prefix", "chunks": prefix}, {"name": "focus", "part": "suffix", "chunks": suffix}]+else:+ rest = [p for p in files if p not in focus]+ sections = [{"name": "header", "part": "prefix", "chunks": [header]},+ {"name": "focus", "part": "suffix", "chunks": [chunk(p, body(p)) for p in focus + rest]}]+total = 0+for s in sections:+ keep = []+ for c in s["chunks"]:+ if total + c["tokens"] <= budget:+ keep.append(c)+ total += c["tokens"]+ s["chunks"], s["tokens"] = keep, sum(c["tokens"] for c in keep)+pre = [s for s in sections if s["part"] == "prefix"]+prefix_text = "".join(c["text"] for s in pre for c in s["chunks"])+paths = [c["path"] for s in sections for c in s["chunks"] if c["path"]]+pj = {"format": "graphicle.pack.v1", "project": os.path.basename(src), "commit": "test", "question": q,+ "budget": budget, "tokens": total, "tokenizer": "estimate", "order": "relevant-last", "layout": layout,+ "prefix_tokens": sum(s["tokens"] for s in pre), "prefix_sha256": hashlib.sha256(prefix_text.encode()).hexdigest(),+ "sections": sections, "included": [{"path": p, "tokens": 0, "rank": i + 1} for i, p in enumerate(paths)],+ "omitted": [], "seconds": 0.0}+if layout == "cache":+ pj["prefix_share"] = share+if fmt == "json":+ print(json.dumps(pj))+else:+ sys.stdout.write("".join('<section name="%s">\n' % s["name"] + "".join(c["text"] for c in s["chunks"])+ + "</section>\n" for s in sections))+'''+++def mock_host():+ if os.environ.get("MOCK_HOST"):+ return os.environ["MOCK_HOST"]+ try:+ out = subprocess.run(["hostname", "-I"], capture_output=True, text=True, timeout=10).stdout.split()+ if out:+ return out[0]+ except (OSError, subprocess.SubprocessError):+ pass+ return "127.0.0.1"+++def git(cwd, *args):+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True,+ env=dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@t", GIT_COMMITTER_NAME="t",+ GIT_COMMITTER_EMAIL="t@t"))+++def make_repo(src, files):+ os.makedirs(src)+ for path, text in files.items():+ os.makedirs(os.path.join(src, os.path.dirname(path)), exist_ok=True)+ with open(os.path.join(src, path), "w") as f:+ f.write(text)+ git(src, "init", "-q")+ git(src, "add", "-A")+ git(src, "commit", "-q", "-m", "fixture")+ return subprocess.run(["git", "rev-parse", "HEAD"], cwd=src, capture_output=True, text=True).stdout.strip()+++def body(word, n):+ return "".join(f"func {word}Handler{i}(ctx Context) error {{ return check{word}(ctx, {i}) }}\n" for i in range(n))+++class RunnerTest(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tmp = tempfile.mkdtemp(prefix="wrb-test-")+ cls.work = os.path.join(cls.tmp, "work")+ cls.qdir = os.path.join(cls.tmp, "questions")+ cls.tdir = os.path.join(cls.tmp, "texts")+ os.makedirs(cls.qdir)+ os.makedirs(cls.tdir)+ layout = {+ "kubernetes": {f"pkg/{w}/{w}.go": body(w, 40) for w in+ ("scheduler", "kubelet", "proxy", "volume", "eviction", "storage", "features", "apiserver")},+ "pytorch": {f"torch/{w}.py": body(w, 40).replace("func ", "def ") for w in+ ("autograd", "cache", "dynamo", "inductor", "sparse")},+ }+ issues = {+ "kubernetes": [("scheduler", "The scheduler handler panics when ctx is nil"),+ ("kubelet", "kubelet handler returns the wrong error"),+ ("eviction", "eviction handler skips pods"),+ ("features", "feature gate features handler is ignored")],+ "pytorch": [("autograd", "autograd handler leaks memory"), ("cache", "cache handler is stale"),+ ("sparse", "sparse handler crashes")],+ }+ counter = Counter(None)+ for name, files in layout.items():+ sha = make_repo(os.path.join(cls.work, "src", name), files)+ build_manifest(cls.work, name, counter)+ slug = {"kubernetes": "kubernetes/kubernetes", "pytorch": "pytorch/pytorch"}[name]+ ext = ".go" if name == "kubernetes" else ".py"+ with open(os.path.join(cls.qdir, f"questions-{name}.jsonl"), "w") as qf, \+ open(os.path.join(cls.tdir, f"texts-{name}.jsonl"), "w") as tf:+ for i, (word, text) in enumerate(issues[name], 1):+ gold = f"pkg/{word}/{word}{ext}" if name == "kubernetes" else f"torch/{word}{ext}"+ qf.write(json.dumps({"id": f"{name}-{i}", "repo": slug, "S": sha, "gold": [gold],+ "names_gold_path": False}) + "\n")+ tf.write(json.dumps({"id": f"{name}-{i}", "text": text}) + "\n")+ cls.record = os.path.join(cls.tmp, "mock-requests.jsonl")+ cls.host = mock_host()+ cls.srv = mock_server.make_server(cls.host, 0, record=cls.record)+ threading.Thread(target=cls.srv.serve_forever, daemon=True).start()+ cls.url = f"http://{cls.host}:{cls.srv.server_address[1]}/v1"+ cls.fake = os.path.join(cls.tmp, "fake-graphicle")+ with open(cls.fake, "w") as f:+ f.write(f"#!{sys.executable}\n" + FAKE_PACK)+ os.chmod(cls.fake, 0o755)+ cls.log = os.path.join(cls.tmp, "spend", "spend-log.jsonl")+ cls.caps = os.path.join(cls.tmp, "caps.json")+ with open(cls.caps, "w") as f:+ json.dump({"usd": {"mock": 5.0}}, f)+ cls.runs = []++ @classmethod+ def tearDownClass(cls):+ cls.srv.shutdown()+ cls.srv.server_close()+ if not os.environ.get("KEEP_TEST_DIR"):+ shutil.rmtree(cls.tmp, ignore_errors=True)++ def run_py(self, out, *args, caps=None, ok=True):+ cmd = [sys.executable, os.path.join(HERE, "run.py"), "--work", self.work, "--questions", self.qdir,+ "--texts", self.tdir, "--out", os.path.join(self.tmp, out), "--base-url", self.url,+ "--model", "mock", "--caps", caps or self.caps, "--spend-log", self.log, *args]+ if "--profile" not in args:+ cmd += ["--profile", "mock"]+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=600, env=dict(os.environ, MODEL_API_KEY="mock-key",+ BASETEN_API_KEY="mock-key"))+ if ok:+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ self.runs.append(os.path.join(self.tmp, out))+ return r++ def rows(self, out):+ return read_jsonl(os.path.join(self.tmp, out, "rows.jsonl"))++ def requests(self):+ return read_jsonl(self.record)++ def log_lines(self, out=None):+ lines = read_jsonl(self.log)+ return [x for x in lines if out is None or x["run"] == os.path.join(self.tmp, out)]++ def test_1_truncation_is_cached_after_the_first_question(self):+ before = len(self.requests())+ self.run_py("trunc", "--arm", "trunc", "--budget", "64K", "--repos", "kubernetes", "--jobs", "2")+ rows = {r["id"]: r for r in self.rows("trunc")}+ self.assertEqual(len(rows), 4)+ self.assertFalse(any(r["error"] for r in rows.values()))+ self.assertEqual(rows["kubernetes-1"]["cached_per_call"], [0], "the first question runs alone and pays in full")+ for qid in ("kubernetes-2", "kubernetes-3", "kubernetes-4"):+ self.assertGreaterEqual(rows[qid]["tokens_cached"], 1024, qid)+ reqs = self.requests()[before:]+ keys = {r["prompt_cache_key"] for r in reqs}+ self.assertEqual(len(keys), 1, "one cache key for the group")+ key = keys.pop()+ self.assertTrue(key.startswith("wrb:kubernetes@") and ":trunc@64K:" in key, key)+ self.assertNotIn("handler", key, "no question text in the key")+ self.assertEqual({r["prompt_cache_retention"] for r in reqs}, {"24h"})+ self.assertEqual({r["max_output_tokens"] for r in reqs}, {8192})+ self.assertEqual({r["reasoning_effort"] for r in reqs}, {"medium"})+ self.assertEqual({r["store"] for r in reqs}, {False})++ def test_2_agent_takes_the_repositories_in_turn(self):+ self.run_py("agent", "--arm", "agent", "--repos", "kubernetes,pytorch", "--max-turns", "4", "--jobs", "1")+ rows = self.rows("agent")+ self.assertEqual(len(rows), 7)+ self.assertFalse(any(r["error"] for r in rows))+ first_turns = [x["question"] for x in self.log_lines("agent") if x["turn"] == 1]+ self.assertEqual(first_turns[:4], ["kubernetes-1", "pytorch-1", "kubernetes-2", "pytorch-2"])+ self.assertTrue(all(r["turns"] > 1 for r in rows))+ self.assertTrue(any(c > 0 for r in rows for c in r["cached_per_call"][1:]), "chained turns read the cache")++ def test_3_baseten_profile_sends_session_affinity_not_the_key(self):+ before = len(self.requests())+ self.run_py("baseten-trunc", "--profile", "baseten", "--arm", "trunc", "--budget", "64K",+ "--repos", "pytorch", "--jobs", "1")+ reqs = self.requests()[before:]+ self.assertEqual(len(reqs), 3)+ self.assertTrue(all(r["path"].endswith("/chat/completions") for r in reqs))+ self.assertEqual({r["prompt_cache_key"] for r in reqs}, {None})+ aff = {r["session_affinity"] for r in reqs}+ self.assertEqual(len(aff), 1)+ self.assertRegex(aff.pop(), r"^[0-9a-f]{32}$")+ self.assertEqual({r["max_tokens"] for r in reqs}, {8192})+ self.assertEqual({r["reasoning_effort"] for r in reqs}, {"medium"})+ rows = {r["id"]: r for r in self.rows("baseten-trunc")}+ self.assertEqual(rows["pytorch-1"]["tokens_cached"], 0)+ self.assertGreaterEqual(rows["pytorch-2"]["tokens_cached"], 1024)++ def test_4_global_cap_refuses_to_start(self):+ tight = os.path.join(self.tmp, "caps-tight.json")+ with open(tight, "w") as f:+ json.dump({"usd": {"mock": logged_total(self.log, "mock") + 0.01}}, f)+ before = len(self.requests())+ r = self.run_py("refused", "--arm", "trunc", "--budget", "128K", "--repos", "kubernetes", caps=tight, ok=False)+ self.assertEqual(r.returncode, 3)+ self.assertIn("REFUSED", r.stderr)+ self.assertEqual(len(self.requests()), before, "no call was sent")++ def test_5_run_cap_stops_the_run(self):+ r = self.run_py("capped", "--arm", "trunc", "--budget", "64K", "--repos", "kubernetes", "--jobs", "1",+ "--spend-cap", "0.05", "--label", "trunc-capped")+ self.assertIn("STOPPED", r.stdout)+ rows = self.rows("capped")+ self.assertEqual(len(rows), 1)+ spent = read_json(os.path.join(self.tmp, "capped", "spend.json"))["spent_usd"]+ self.assertLessEqual(spent, 0.05)+ meta = read_json(os.path.join(self.tmp, "capped", "run.json"))+ self.assertIn("run spend cap", meta["stopped"])++ def test_5b_auto_cap_is_one_and_a_half_estimates_within_the_global_cap(self):+ self.run_py("auto-cap", "--arm", "trunc", "--budget", "64K", "--repos", "kubernetes", "--spend-cap", "auto",+ "--label", "trunc-auto")+ meta = read_json(os.path.join(self.tmp, "auto-cap", "run.json"))+ est = meta["estimate_usd"]["cached"]+ self.assertEqual(meta["spend_cap_usd"], float(-(-1.5 * est // 1))) # ceil, in whole dollars+ tight = os.path.join(self.tmp, "caps-auto.json")+ left = 0.5+ with open(tight, "w") as f:+ json.dump({"usd": {"mock": logged_total(self.log, "mock") + left}}, f)+ self.run_py("auto-cap-tight", "--arm", "trunc", "--budget", "64K", "--repos", "pytorch", "--spend-cap", "auto",+ "--label", "trunc-auto-tight", caps=tight)+ meta = read_json(os.path.join(self.tmp, "auto-cap-tight", "run.json"))+ self.assertAlmostEqual(meta["spend_cap_usd"], left, places=6)++ def test_6_global_cap_stops_a_call_mid_run(self):+ log = os.path.join(self.tmp, "unit-log.jsonl")+ with open(log, "w") as f:+ f.write(json.dumps({"provider": "mock", "cost_usd": 0.95}) + "\n")+ s = Spend(os.path.join(self.tmp, "unit-spend.json"), 10.0, MOCK_PRICE, log, "mock", 1.0)+ w = s.reserve(10000, 1000) # $0.0168 worst case fits under the $0.05 left+ s.settle(w, 0.01, {"provider": "mock", "cost_usd": 0.01})+ with self.assertRaises(CapReached) as cm:+ s.reserve(100000, 8192) # $0.16 worst case does not+ self.assertIn("global mock cap", str(cm.exception))+ self.assertAlmostEqual(logged_total(log, "mock"), 0.96)++ def test_7_a_failing_call_is_tried_again_once_then_kept_as_an_error(self):+ self.run_py("errors", "--arm", "noctx", "--repos", "pytorch", "--reasoning-effort", "none")+ rows = self.rows("errors")+ self.assertEqual(len(rows), 3)+ self.assertTrue(all("HTTP 400" in r["error"] for r in rows))+ lines = self.log_lines("errors")+ self.assertEqual(len(lines), 6, "each question: the call and its one retry")+ self.assertEqual({x["status"] for x in lines}, {"error"})+ self.assertEqual(sum(x["cost_usd"] for x in lines), 0.0)++ def test_8_a_second_run_of_the_provider_is_refused(self):+ with open(self.log + ".mock.lock", "w") as held:+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)+ r = self.run_py("locked", "--arm", "noctx", "--repos", "pytorch", ok=False)+ self.assertEqual(r.returncode, 3)+ self.assertIn("another run", r.stderr)++ def test_9_the_global_log_adds_up(self):+ lines = self.log_lines()+ self.assertTrue(lines)+ for x in lines:+ want = ((x["input_tokens"] - x["cached_tokens"]) * MOCK_PRICE["input"]+ + x["cached_tokens"] * MOCK_PRICE["cached_input"] + x["output_tokens"] * MOCK_PRICE["output"]) / 1e6+ self.assertAlmostEqual(x["cost_usd"], want, places=12)+ for k in ("time", "model", "arm", "repo", "input_tokens", "cached_tokens", "output_tokens",+ "reasoning_tokens", "seconds", "cost_usd", "provider"):+ self.assertIn(k, x)+ for d in self.runs:+ rows = read_jsonl(os.path.join(d, "rows.jsonl"))+ spent = read_json(os.path.join(d, "spend.json"))["spent_usd"]+ logged = sum(x["cost_usd"] for x in lines if x["run"] == d)+ self.assertAlmostEqual(spent, logged, places=9, msg=d)+ if not os.path.basename(d).startswith("capped"):+ self.assertAlmostEqual(sum(r.get("cost_usd") or 0 for r in rows), logged, places=9, msg=d)+ self.assertAlmostEqual(logged_total(self.log, "mock"), sum(x["cost_usd"] for x in lines), places=9)++ def test_c1_cache_layout_arm_reads_its_prefix_from_the_cache(self):+ before = len(self.requests())+ self.run_py("pack-cache", "--arm", "pack-cache", "--budget", "64K", "--repos", "kubernetes", "--jobs", "2",+ "--graphicle", self.fake)+ rows = {r["id"]: r for r in self.rows("pack-cache")}+ self.assertEqual(len(rows), 4)+ self.assertFalse(any(r["error"] for r in rows.values()))+ self.assertTrue(all(r["prefix_ok"] and r["layout"] == "cache" and r["prefix_share"] == 0.9+ for r in rows.values()))+ self.assertEqual(len({r["prefix_sha256"] for r in rows.values()}), 1)+ self.assertEqual(rows["kubernetes-1"]["tokens_cached"], 0)+ for qid in ("kubernetes-2", "kubernetes-3", "kubernetes-4"):+ self.assertGreaterEqual(rows[qid]["tokens_cached"], 1024, qid)+ keys = {r["prompt_cache_key"] for r in self.requests()[before:]}+ self.assertEqual(len(keys), 1)+ self.assertIn(":pack-cache@64K:" + rows["kubernetes-1"]["prefix_sha256"][:12], keys.pop())++ def test_c2_recall_layout_grid(self):+ out = os.path.join(self.tmp, "recall-layouts")+ r = subprocess.run([sys.executable, os.path.join(HERE, "recall.py"), "--work", self.work, "--questions",+ self.qdir, "--texts", self.tdir, "--graphicle", self.fake, "--out", out,+ "--repos", "kubernetes,pytorch", "--budgets", "64K,128K",+ "--layouts", "standard,cache0.9,cache0.95,stable", "--jobs", "2"],+ capture_output=True, text=True, timeout=600)+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ summary = read_json(os.path.join(out, "recall-summary.json"))+ self.assertEqual(summary["errors"], 0)+ rows = [s for s in summary["rows"] if s["scope"] == "all" and s["arm"] != "truncation"]+ self.assertEqual({s["arm"] for s in rows}, {"pack", "pack-cache", "pack-cache0.95", "pack-stable"})+ self.assertEqual(len(rows), 4 * 2 * 2)+ for s in rows:+ self.assertEqual(s["prefix_ok"], s["n"], s)+ self.assertGreater(s["question_tokens"], 0)+ if s["arm"] != "pack":+ self.assertEqual(s["prefix_shas"], 1, f"one prefix per repository, budget and layout: {s}")+ self.assertGreater(s["prefix_tokens"], 1024)+ stable = [x for x in read_jsonl(os.path.join(out, "recall-rows.jsonl")) if x["arm"] == "pack-stable"]+ self.assertTrue(stable and all(x["prefix_share"] == 1.0 for x in stable))++ def test_redact_strips_emails_and_mentions_but_not_code(self):+ from redact import redact+ text = ("cc @alice and @bob-x: see [email protected]. @torch.compile and @types/node stay, "+ "`@property` stays\n```\n@Override\n@someone\n```\n@carol")+ new, emails, handles = redact(text)+ self.assertEqual((emails, handles), (1, 3))+ self.assertNotIn("alice", new)+ self.assertNotIn("bob-x", new)+ self.assertNotIn("carol", new)+ self.assertNotIn("example.com", new)+ for kept in ("@torch.compile", "@types/node", "`@property`", "@Override", "@someone"):+ self.assertIn(kept, new)+ self.run_py("redacted", "--arm", "noctx", "--repos", "pytorch", "--redact")+ rows = self.rows("redacted")+ self.assertTrue(rows and all(r["redacted"] == {"emails": 0, "handles": 0} for r in rows))+ self.assertTrue(read_json(os.path.join(self.tmp, "redacted", "run.json"))["redact"])++ def test_estimate_caches_the_shared_prefix(self):+ agent = {"turns": 15, "turn_tokens": 2500, "out_per_turn": 800}+ b = BUDGETS["64K"]+ self.assertEqual(estimate.group_tokens("trunc", "64K", 4, 1000, 4000, agent)[2], 3 * b)+ self.assertAlmostEqual(estimate.group_tokens("pack-cache", "64K", 4, 1000, 4000, agent)[2], 3 * 0.9 * b)+ self.assertAlmostEqual(estimate.group_tokens("pack-cache0.95", "64K", 4, 1000, 4000, agent)[2], 3 * 0.95 * b)+ self.assertEqual(estimate.group_tokens("pack-stable", "64K", 4, 1000, 4000, agent)[2], 3 * b)+ self.assertEqual(estimate.group_tokens("pack", "64K", 4, 1000, 4000, agent)[2], 0)+ self.assertEqual(estimate.group_tokens("noctx", None, 4, 1000, 4000, agent)[2], 0)+ calls, tin, cached, tout = estimate.group_tokens("trunc", "64K", 4, 1000, 4000, agent)+ p = PRICES["models"]["muse-spark-1.3"]+ first = estimate.cost_of(p, b + 1000, 0, 4000)+ later = estimate.cost_of(p, b + 1000, b, 4000)+ self.assertAlmostEqual(estimate.cost_of(p, tin, cached, tout), first + 3 * later)+ self.assertLess(later, first)++ def test_pack_arms_on_a_real_index(self):+ work, binary = os.environ.get("BENCH_WORK"), os.environ.get("BENCH_GRAPHICLE")+ if not (work and binary):+ self.skipTest("BENCH_WORK and BENCH_GRAPHICLE not set")+ tok = os.environ.get("BENCH_TOKENIZER")+ has_layout = "--layout" in subprocess.run([binary, "pack", "--help"], capture_output=True, text=True).stdout+ arms = ["pack"] + (["pack-cache", "pack-stable"] if has_layout else [])+ qdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "questions")+ for arm in arms:+ out = os.path.join(self.tmp, f"real-{arm}")+ cmd = [sys.executable, os.path.join(HERE, "run.py"), "--arm", arm, "--budget", "64K", "--work", work,+ "--questions", qdir, "--texts", os.path.join(work, "mine"), "--out", out, "--profile", "mock",+ "--base-url", self.url, "--model", "mock", "--caps", self.caps, "--spend-log", self.log,+ "--repos", "kubernetes", "--limit", "2", "--graphicle", binary] + (["--tokenizer", tok] if tok else [])+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=1800,+ env=dict(os.environ, MODEL_API_KEY="mock-key"))+ self.assertEqual(r.returncode, 0, r.stderr[-2000:])+ self.runs.append(out)+ rows = read_jsonl(os.path.join(out, "rows.jsonl"))+ self.assertEqual(len(rows), 2)+ for row in rows:+ self.assertIsNone(row["error"], row["error"])+ self.assertLessEqual(row["context_tokens"], BUDGETS["64K"])+ self.assertIn(f":{arm}@64K:", row["cache_key"])+ if arm != "pack":+ self.assertTrue(row["prefix_ok"], "the prefix comes first and matches its sha256")+ if arm != "pack":+ self.assertEqual(len({r["prefix_sha256"] for r in rows}), 1, "one prefix for both questions")+ self.assertGreaterEqual(rows[1]["tokens_cached"], 1024)+++if __name__ == "__main__":+ unittest.main()diff --git a/bench/whole-repo/tokens.py b/bench/whole-repo/tokens.pynew file mode 100644index 0000000..55ef7d4--- /dev/null+++ b/bench/whole-repo/tokens.py@@ -0,0 +1,229 @@+#!/usr/bin/env python3+"""Token counts for the whole-repository benchmark: one counter for every arm with a budget.++usage:+ tokens.py sizes --work WORKDIR [--tokenizer FILE] [--out FILE] [NAME ...]+ counts every tracked file of each checkout at S by class (paths.py) and writes+ WORKDIR/manifest/NAME.tsv (path, class, bytes, tokens of the text, tokens of truncation's+ wrapper tags; binary files get tokens -1)+ and a summary of the sizes to --out+ tokens.py count [--tokenizer FILE] < TEXT+ tokens.py check-pack [--tokenizer FILE] PACK.json ...+ compares the token counts in `graphicle pack --format json` output with this counter (exit 1 when+ they differ by more than 2%): truncation and the pack must measure their budgets alike++The counter: with --tokenizer (a tokenizer.json in the Hugging Face format, read with the+`tokenizers` package), exact tokens. Without it, the estimate: ceil(UTF-8 bytes / 4). Every result+records which one was used (counter_name). The pack arm gets the same tokenizer.json through+`graphicle pack --tokenizer`, so its budget and truncation's are measured in the same units.+"""+import argparse+import json+import math+import os+import subprocess+import sys+from concurrent.futures import ThreadPoolExecutor++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+from paths import classify # noqa: E402+++class Counter:+ def __init__(self, tokenizer=None):+ self.tok = None+ if tokenizer:+ from tokenizers import Tokenizer+ self.tok = Tokenizer.from_file(tokenizer)+ self.name = "exact:" + os.path.basename(os.path.dirname(os.path.abspath(tokenizer))) + "/" + os.path.basename(tokenizer)+ else:+ self.name = "estimate:utf8-bytes/4"++ def count(self, text):+ if self.tok is None:+ return math.ceil(len(text.encode("utf-8")) / 4)+ return len(self.tok.encode(text, add_special_tokens=False).ids)++ def count_many(self, texts):+ if self.tok is None:+ return [self.count(t) for t in texts]+ return [len(e.ids) for e in self.tok.encode_batch(texts, add_special_tokens=False)]+++def tracked_files(src):+ out = subprocess.run(["git", "ls-files", "-z"], cwd=src, capture_output=True, text=True, check=True).stdout+ return sorted(p for p in out.split("\0") if p)+++def read_text(path):+ """The file's text, or None for a binary file, a symlink or anything that is not a regular file."""+ if os.path.islink(path) or not os.path.isfile(path):+ return None+ with open(path, "rb") as f:+ data = f.read()+ if b"\0" in data[:8192]:+ return None+ return data.decode("utf-8", errors="replace")+++def line_count(text):+ return text.count("\n") + (0 if text.endswith("\n") or not text else 1)+++def wrap_parts(path, text):+ """How truncation wraps a file, as the pack wraps its chunks: (opening tag, body, closing tag)."""+ body = text if text.endswith("\n") or not text else text + "\n"+ return f'<file path="{path}" lines="1-{line_count(text)}">\n', body, "</file>\n"+++def wrap(path, text):+ return "".join(wrap_parts(path, text))+++def build_manifest(work, name, counter):+ src = os.path.join(work, "src", name)+ paths = tracked_files(src)+ allp = set(paths)+ rows, batch = [], []++ def flush():+ if not batch:+ return+ counts = counter.count_many([t for (_, _, t) in batch])+ tags = counter.count_many([wrap_parts(p, t)[0] + wrap_parts(p, t)[2] for (p, _, t) in batch])+ for (p, cls, t), c, w in zip(batch, counts, tags):+ rows.append((p, cls, len(t.encode("utf-8")), c, w))+ batch.clear()++ for p in paths:+ cls = classify(name, p, allp)+ t = read_text(os.path.join(src, p))+ if t is None:+ full = os.path.join(src, p)+ size = os.path.getsize(full) if os.path.isfile(full) and not os.path.islink(full) else 0+ rows.append((p, cls, size, -1, 0))+ continue+ batch.append((p, cls, t))+ if len(batch) >= 2000:+ flush()+ flush()+ rows.sort()+ d = os.path.join(work, "manifest")+ os.makedirs(d, exist_ok=True)+ with open(os.path.join(d, name + ".tsv"), "w") as f:+ f.write(f"# counter\t{counter.name}\n")+ for p, cls, b, c, w in rows:+ f.write(f"{p}\t{cls}\t{b}\t{c}\t{w}\n")+ return rows+++def load_manifest(work, name):+ rows, counter = [], None+ with open(os.path.join(work, "manifest", name + ".tsv")) as f:+ for line in f:+ if line.startswith("# counter\t"):+ counter = line.rstrip("\n").split("\t")[1]+ continue+ p, cls, b, c, w = line.rstrip("\n").split("\t")+ rows.append((p, cls, int(b), int(c), int(w)))+ return rows, counter+++def truncation_order(name, rows):+ """Truncation's fixed order: source files, then tests, then docs and changelogs, each by path;+ vendored, generated and binary files left out."""+ from paths import truncation_rank+ keyed = [(truncation_rank(cls), p, c, w) for p, cls, _b, c, w in rows+ if c >= 0 and truncation_rank(cls) is not None]+ keyed.sort(key=lambda k: (k[0], k[1]))+ return keyed+++def build_truncation(work, name, budget, counter, verify=True):+ """The truncation context of at most `budget` tokens: whole files in truncation_order, each+ wrapped like a pack chunk; a file that would pass the budget is skipped and the next one tried.+ Returns (text, included paths, tokens)."""+ rows, mcounter = load_manifest(work, name)+ if mcounter != counter.name:+ raise SystemExit(f"{name}: the manifest was counted with {mcounter}, not {counter.name}; run tokens.py sizes again")+ src = os.path.join(work, "src", name)+ used, parts, included = 0, [], []+ for _rank, p, c, w in truncation_order(name, rows):+ if used + c + w > budget:+ continue+ t = read_text(os.path.join(src, p))+ if t is None:+ continue+ parts.append(wrap(p, t))+ included.append(p)+ used += c + w+ text = "".join(parts)+ total = counter.count(text) if verify else used+ while total > budget and parts: # joins can tokenize differently from the parts; trim from the end+ parts.pop()+ included.pop()+ text = "".join(parts)+ total = counter.count(text)+ return text, included, total+++def summarize(rows):+ by = {}+ for _p, cls, b, c, _w in rows:+ d = by.setdefault(cls, {"files": 0, "bytes": 0, "tokens": 0, "binary_files": 0})+ if c < 0:+ d["binary_files"] += 1+ continue+ d["files"] += 1+ d["bytes"] += b+ d["tokens"] += c+ tot = lambda classes: sum(by.get(k, {}).get("tokens", 0) for k in classes)+ return {+ "by_class": by,+ "tokens_all": tot(["source", "test", "docs", "changelog", "vendored", "generated"]),+ "tokens_without_vendored_generated": tot(["source", "test", "docs", "changelog"]),+ "tokens_nontest_source": tot(["source"]),+ }+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("cmd", choices=["sizes", "count", "check-pack"])+ ap.add_argument("--work")+ ap.add_argument("--tokenizer")+ ap.add_argument("--out")+ ap.add_argument("names", nargs="*")+ a = ap.parse_intermixed_args()+ counter = Counter(a.tokenizer)+ if a.cmd == "count":+ print(counter.count(sys.stdin.read()))+ return+ if a.cmd == "check-pack":+ # Pack JSON files (graphicle.pack.v1) as arguments: do the pack's token counts agree with this counter?+ ours = theirs = 0+ for path in a.names:+ pj = json.load(open(path))+ for sec in pj.get("sections") or []:+ for ch in sec.get("chunks") or []:+ ours += counter.count(ch.get("text") or "")+ theirs += ch.get("tokens") or 0+ print(f"{os.path.basename(path)}: pack tokenizer {pj.get('tokenizer')}, pack total {pj.get('tokens')}")+ ratio = ours / theirs if theirs else float("nan")+ print(f"chunk tokens: pack {theirs:,}, {counter.name} {ours:,}, ratio {ratio:.4f}")+ sys.exit(0 if theirs and abs(ratio - 1) <= 0.02 else 1)+ work = os.path.abspath(a.work)+ names = a.names or sorted(os.listdir(os.path.join(work, "src")))+ with ThreadPoolExecutor(min(5, len(names))) as ex:+ res = dict(zip(names, ex.map(lambda n: summarize(build_manifest(work, n, counter)), names)))+ out = {"counter": counter.name, "repos": res}+ if a.out:+ with open(a.out, "w") as f:+ json.dump(out, f, indent=1, sort_keys=True)+ for n, s in res.items():+ print(f"{n}: all {s['tokens_all']:,} without vendored/generated {s['tokens_without_vendored_generated']:,}"+ f" non-test source {s['tokens_nontest_source']:,} ({counter.name})", flush=True)+++if __name__ == "__main__":+ main()diff --git a/crates/graphicle-graph/Cargo.lock b/crates/graphicle-graph/Cargo.lockindex 658a862..5ccc7f4 100644--- a/crates/graphicle-graph/Cargo.lock+++ b/crates/graphicle-graph/Cargo.lock@@ -1471,7 +1471,7 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"[[package]]name = "graphicle"-version = "0.1.8"+version = "0.1.9"dependencies = ["aws-config","aws-sdk-bedrockruntime",@@ -1571,7 +1571,7 @@ dependencies = [[[package]]name = "graphicle-graph"-version = "0.1.8"+version = "0.1.9"dependencies = ["graphicle","libmimalloc-sys",diff --git a/crates/graphicle-graph/Cargo.toml b/crates/graphicle-graph/Cargo.tomlindex 0e4d191..491dd76 100644--- a/crates/graphicle-graph/Cargo.toml+++ b/crates/graphicle-graph/Cargo.toml@@ -1,6 +1,6 @@[package]name = "graphicle"-version = "0.1.8"+version = "0.1.9"edition = "2024"rust-version = "1.94.1"publish = falsediff --git a/crates/graphicle-graph/cli/Cargo.toml b/crates/graphicle-graph/cli/Cargo.tomlindex bb7656d..9dbe80c 100644--- a/crates/graphicle-graph/cli/Cargo.toml+++ b/crates/graphicle-graph/cli/Cargo.toml@@ -1,6 +1,6 @@[package]name = "graphicle-graph"-version = "0.1.8"+version = "0.1.9"edition = "2024"rust-version = "1.94.1"publish = falsediff --git a/crates/graphicle-memory/Cargo.lock b/crates/graphicle-memory/Cargo.lockindex 1492975..dbc1156 100644--- a/crates/graphicle-memory/Cargo.lock+++ b/crates/graphicle-memory/Cargo.lock@@ -1453,7 +1453,7 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"[[package]]name = "graphicle"-version = "0.1.8"+version = "0.1.9"dependencies = ["aws-config","aws-sdk-bedrockruntime",@@ -1551,7 +1551,7 @@ dependencies = [[[package]]name = "graphicle-memory"-version = "0.1.8"+version = "0.1.9"dependencies = ["chrono","graphicle",diff --git a/crates/graphicle-memory/Cargo.toml b/crates/graphicle-memory/Cargo.tomlindex 20425c8..5a6918c 100644--- a/crates/graphicle-memory/Cargo.toml+++ b/crates/graphicle-memory/Cargo.toml@@ -1,6 +1,6 @@[package]name = "graphicle-memory"-version = "0.1.8"+version = "0.1.9"edition = "2024"rust-version = "1.94.1"publish = falsediff --git a/crates/graphicle-memory/src/retrieval.rs b/crates/graphicle-memory/src/retrieval.rsindex d7a7a00..67085a6 100644--- a/crates/graphicle-memory/src/retrieval.rs+++ b/crates/graphicle-memory/src/retrieval.rs@@ -16,6 +16,9 @@ pub const MAX_RANK_LIMIT: usize = 60;/// Most candidates [`rank`] keeps after fusion and the relationship lift,/// best first, ties by identity: selection reads no others.pub const MAX_FUSED: usize = 400;+/// Most candidates a call may ask [`rank`] to keep instead (`fused_cap`):+/// a long ranking for a caller that fills a large context window.+pub const MAX_FUSED_CAP: usize = 4000;/// Counting and listing questions need every instance, not the best one.fn aggregate_question(lowercase: &str) -> bool {@@ -824,13 +827,19 @@ pub fn rank(request: &Value) -> Result<Value> {}let mut remaining: Vec<_> = scores.into_iter().collect();remaining.sort_by(|a, b| b.1.total_cmp(&a.1).then(a.0.cmp(&b.0)));- remaining.truncate(MAX_FUSED);+ let fused_cap = request+ .get("fused_cap")+ .and_then(Value::as_u64)+ .map_or(MAX_FUSED, |cap| {+ (cap as usize).clamp(MAX_FUSED, MAX_FUSED_CAP)+ });+ remaining.truncate(fused_cap);// Diagnostics: the fused order before selection (for recall harnesses).let debug_fused = request.get("debug_fused").and_then(Value::as_u64).unwrap_or(0)- .min(MAX_FUSED as u64) as usize;+ .min(fused_cap as u64) as usize;let fused: Vec<String> = remaining.iter().filter(|(id, _)| rows[ids[id]]["kind"] != "memory")diff --git a/crates/graphicle/Cargo.lock b/crates/graphicle/Cargo.lockindex a6831c4..646b37d 100644--- a/crates/graphicle/Cargo.lock+++ b/crates/graphicle/Cargo.lock@@ -1327,7 +1327,7 @@ dependencies = [[[package]]name = "graphicle"-version = "0.1.8"+version = "0.1.9"dependencies = ["base64 0.22.1","calamine",@@ -1421,7 +1421,7 @@ dependencies = [[[package]]name = "graphicle-memory"-version = "0.1.8"+version = "0.1.9"dependencies = ["chrono","graphicle",@@ -1439,7 +1439,7 @@ dependencies = [[[package]]name = "graphicle-runtime"-version = "0.1.8"+version = "0.1.9"dependencies = ["aes-gcm","axum",diff --git a/crates/graphicle/Cargo.toml b/crates/graphicle/Cargo.tomlindex 8ba0721..e1d501f 100644--- a/crates/graphicle/Cargo.toml+++ b/crates/graphicle/Cargo.toml@@ -1,6 +1,6 @@[package]name = "graphicle-runtime"-version = "0.1.8"+version = "0.1.9"edition = "2024"rust-version = "1.94.1"publish = false@@ -20,7 +20,7 @@ test = false# This crate builds the Core edition. Another edition depends on it and adds# its features through the extension registry (src/extension.rs).[features]-local-inference = ["dep:ort", "dep:tokenizers"]+local-inference = ["dep:ort"][dependencies]graphicle-memory = { path = "../graphicle-memory" }@@ -47,7 +47,9 @@ rand = "0.8"sha2 = "0.10"sha1 = "0.10"ort = { version = "=2.0.0-rc.10", optional = true, default-features = false, features = ["std", "load-dynamic"] }-tokenizers = { version = "=0.22.2", optional = true, default-features = false, features = ["fancy-regex"] }+# Exact token counts for `graphicle pack --tokenizer`, in every build: pure Rust+# (fancy-regex; no onig, no esaxx C++).+tokenizers = { version = "=0.22.2", default-features = false, features = ["fancy-regex"] }quick-xml = "0.41"zip = { version = "8", default-features = false, features = ["deflate"] }calamine = "0.36"diff --git a/crates/graphicle/README.md b/crates/graphicle/README.mdindex b3cf228..5820f4b 100644--- a/crates/graphicle/README.md+++ b/crates/graphicle/README.md@@ -55,7 +55,7 @@ operations through the extension registry (`src/extension.rs`).provider permission mode ("is not part of Graphicle Core"), while it still enforcesthe provider permissions an existing store holds.- `build.info` reports the edition and its capabilities, and- `graphicle --version` prints it (`graphicle 0.1.8 (core)`).+ `graphicle --version` prints it (`graphicle 0.1.9 (core)`).- A store keeps every table when either edition opens it, and Core keeps theother edition's guarantees on a store it has used (`src/store_compat.rs`).diff --git a/crates/graphicle/src/agent_detect.rs b/crates/graphicle/src/agent_detect.rsindex 51f6990..7b0ecef 100644--- a/crates/graphicle/src/agent_detect.rs+++ b/crates/graphicle/src/agent_detect.rs@@ -96,6 +96,12 @@ impl Environment {self.at_home(".cursor/mcp.json")}+ /// Muse Code's user settings file, which holds its MCP servers+ /// (`mcp_servers`).+ pub fn muse_config(&self) -> Option<PathBuf> {+ self.at_home(".config/muse/settings.json")+ }+/// Claude Desktop's folder (where `connect claude` writes).pub fn claude_desktop_dir(&self) -> Option<PathBuf> {#[cfg(target_os = "macos")]@@ -159,12 +165,13 @@ fn executable(path: &Path) -> bool {}/// The clients `graphicle connect` supports, in the order setup lists them.-pub const CLIENTS: [(&str, &str); 5] = [+pub const CLIENTS: [(&str, &str); 6] = [("claude-code", "Claude Code"),("codex", "Codex"),("cursor", "Cursor"),("vscode", "VS Code"),("claude", "Claude Desktop"),+ ("muse", "Muse Code"),];/// The display name of a client id.@@ -189,6 +196,7 @@ pub fn parse(word: &str) -> Option<&'static str> {"cursor" => "cursor","vscode" | "code" | "visualstudiocode" | "copilot" => "vscode","claude" | "claudedesktop" | "desktop" => "claude",+ "muse" | "musecode" => "muse",_ => return None,};Some(id)@@ -217,6 +225,7 @@ pub fn detect(env: &Environment) -> Vec<Found> {"vscode" => folder(env.vscode_dir()).or_else(|| folder(env.at_home(".vscode"))).or_else(|| env.program("code")),+ "muse" => folder(env.at_home(".config/muse")).or_else(|| env.program("muse")),_ => folder(env.claude_desktop_dir()),};if let Some(evidence) = evidence {diff --git a/crates/graphicle/src/agent_files.rs b/crates/graphicle/src/agent_files.rsindex cb3a3c8..e8be2a0 100644--- a/crates/graphicle/src/agent_files.rs+++ b/crates/graphicle/src/agent_files.rs@@ -163,10 +163,56 @@ pub fn exclude_created(data: &Path, file: &Path) -> Result<()> {exclude_in_block(data, &file, &pattern)}+/// Why a write failed when the file system refused it (a read-only folder,+/// Claude Code's or Codex's sandbox): `not writable: <the OS error>`; `None`+/// for any other error.+pub fn write_failure(error: &Error) -> Option<String> {+ error+ .message+ .strip_prefix("Local I/O failed: ")+ .map(|os| format!("not writable: {os}"))+}++/// `error`, from a write of `path`, naming the file when the file system+/// refused the write: `<path>: not writable: <the OS error>`.+pub fn naming(path: &Path, error: Error) -> Error {+ match write_failure(&error) {+ Some(reason) => Error::bad(format!("{}: {reason}", path.display())),+ None => error,+ }+}++/// A line Graphicle could not add to a repository's exclude file.+#[derive(Clone, Debug, PartialEq)]+pub struct Unexcluded {+ /// The exclude file.+ pub file: PathBuf,+ /// The line it lacks: `*.graphicle-bak`, or a created file's path.+ pub pattern: String,+ /// Why: `not writable: <the OS error>`.+ pub reason: String,+}++thread_local! {+ /// The lines this thread could not add to exclude files, until+ /// [`take_unexcluded`] takes them.+ static UNEXCLUDED: std::cell::RefCell<Vec<Unexcluded>> =+ const { std::cell::RefCell::new(Vec::new()) };+}++/// The lines this thread could not add to an exclude file since the last+/// call, each once: setup's summary gives them to add by hand.+pub fn take_unexcluded() -> Vec<Unexcluded> {+ UNEXCLUDED.with(|list| std::mem::take(&mut *list.borrow_mut()))+}+/// Add `pattern` to the marked block of the exclude file of the working tree/// that holds `file` (the block is created, after a backup of the file, when/// it is missing; nothing is added when the file has the pattern outside the-/// block), and record the change in `data`.+/// block), and record the change in `data`. An exclude file that cannot be+/// written (a read-only `.git`, as in Codex's sandbox) is left as it is:+/// the line only keeps a file out of `git status`, so the change it goes+/// with is still made, and [`take_unexcluded`] has the line.fn exclude_in_block(data: &Path, file: &Path, pattern: &str) -> Result<()> {let Some(folder) = file.parent() else {return Ok(());@@ -180,23 +226,44 @@ fn exclude_in_block(data: &Path, file: &Path, pattern: &str) -> Result<()> {let existed = exclude.exists();let text = std::fs::read_to_string(&exclude).unwrap_or_default();let mut lines: Vec<&str> = text.split('\n').collect();- match exclude_block(&lines) {+ let written = match exclude_block(&lines) {Some((start, end)) => {- if !lines[start..end].iter().any(|line| line.trim() == pattern) {+ if lines[start..end].iter().any(|line| line.trim() == pattern) {+ Ok(())+ } else {lines.insert(end - 1, pattern);- write(&exclude, lines.join("\n").as_bytes(), 0o644)?;+ write(&exclude, lines.join("\n").as_bytes(), 0o644)}}None if lines.iter().any(|line| line.trim() == pattern) => return Ok(()),None => {- backup_once(&exclude)?;let mut updated = text.clone();if !updated.is_empty() && !updated.ends_with('\n') {updated.push('\n');}updated.push_str(&format!("{EXCLUDE_START}\n{pattern}\n{EXCLUDE_END}\n"));- write(&exclude, updated.as_bytes(), 0o644)?;+ backup_once(&exclude).and_then(|_| write(&exclude, updated.as_bytes(), 0o644))}+ };+ if let Err(error) = written {+ let Some(reason) = write_failure(&error) else {+ return Err(error);+ };+ let line = Unexcluded {+ file: exclude,+ pattern: pattern.to_string(),+ reason,+ };+ UNEXCLUDED.with(|list| {+ let mut list = list.borrow_mut();+ if !list+ .iter()+ .any(|known| known.file == line.file && known.pattern == line.pattern)+ {+ list.push(line);+ }+ });+ return Ok(());}record(data,@@ -361,7 +428,9 @@ pub struct Change {/// - `removed-mcp`, `removed-codex`: a Graphify entry a switch removed,/// put back on disconnect (`replaced` holds it);/// - `exclude`: the `*.graphicle-bak` block of a repository's- /// `.git/info/exclude` (`folder` is the working tree).+ /// `.git/info/exclude` (`folder` is the working tree);+ /// - `muse-plugin`: Graphicle's Muse Code plugin (`path` is its manifest+ /// in the data folder), installed for every project.pub kind: String,/// The agent client, for entries and capture hooks.#[serde(default, skip_serializing_if = "Option::is_none")]diff --git a/crates/graphicle/src/agent_setup.rs b/crates/graphicle/src/agent_setup.rsindex f816dbb..172e7fa 100644--- a/crates/graphicle/src/agent_setup.rs+++ b/crates/graphicle/src/agent_setup.rs@@ -66,6 +66,11 @@ pub struct Policy {/// when `--guards` is not asked for, so a second run leaves what the/// first one would have.pub drop_guards: bool,+ /// Setup: a hooks file the file system refuses to write (Claude Code's+ /// sandbox, a read-only folder) does not fail the connection. The+ /// reply's hooks are `skipped`, with the reason and the `connect`+ /// command that adds them later.+ pub skip_unwritable_hooks: bool,}/// The connection `setup` and `connect` without a client make for `client`@@ -88,7 +93,7 @@ pub fn default_connection<'a>(project: None,name: None,replace: false,- hooks: capture && has_hooks(client),+ hooks: capture && setup_hooks(client),work_state: false,graph: true,allow_learning: false,@@ -147,13 +152,26 @@ fn entry_tools(entry: &Value) -> ToolSet {.unwrap_or(ToolSet::All)}-/// Whether `client` takes session-capture hooks.+/// Whether `client` takes session-capture hooks: Muse Code's come in+/// Graphicle's plugin ([`crate::muse_code`]).pub fn has_hooks(client: &str) -> bool {+ matches!(client, "claude-code" | "codex" | "muse")+}++/// Whether setup gives `client` its capture hooks. Muse Code's plugin is+/// opt-in (`connect muse --hooks`) until it has passed a live check with+/// Muse Code: setup keeps Muse Code's settings entry as before.+pub fn setup_hooks(client: &str) -> bool {matches!(client, "claude-code" | "codex")}/// Clients whose MCP file belongs to one folder (Claude Code's `.mcp.json`,/// VS Code's `.vscode/mcp.json`); the others hold one file per user.+/// The object of Muse Code's settings that holds its MCP servers.+pub const MUSE_GROUP: &str = "mcp_servers";+/// The `schema_version` Muse Code's settings file must set.+pub const MUSE_SCHEMA_VERSION: u64 = 1;+fn project_scope(client: &str) -> bool {matches!(client, "claude-code" | "vscode")}@@ -276,14 +294,14 @@ pub fn connect(store: &Store, options: &Connect<'_>) -> Result<Value> {/// when an existing entry of that name was replaced.pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Result<Value> {let client = options.client;- if !["claude", "claude-code", "cursor", "vscode", "codex"].contains(&client) {+ if !["claude", "claude-code", "cursor", "vscode", "codex", "muse"].contains(&client) {return Err(Error::bad(- "Choose claude, claude-code, cursor, vscode or codex",+ "Choose claude, claude-code, cursor, vscode, codex or muse",));}- if options.hooks && !["claude-code", "codex"].contains(&client) {+ if options.hooks && !has_hooks(client) {return Err(Error::bad(- "Session-capture hooks are available for claude-code and codex",+ "Session-capture hooks are available for claude-code, codex and muse",));}let session = local::session(store, false)?;@@ -299,12 +317,37 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Reslet program = stable_program()?;let directory = store.directory.canonical()?;let mut arguments: Vec<String> = Vec::new();- if local::default_data_dir().canonical().ok().as_deref() != Some(directory.as_path()) {+ let custom_store =+ local::default_data_dir().canonical().ok().as_deref() != Some(directory.as_path());+ if custom_store {arguments.extend(["--data-dir".into(),directory.to_string_lossy().into_owned(),]);}+ // The `connect` command, run by hand in this folder, that adds the hooks+ // (`guards`: with Claude Code's guard hooks) when setup could not write+ // their file; none for a plan that only removed hooks.+ let hooks_command = |guards: bool| -> Option<String> {+ if !options.hooks && !guards {+ return None;+ }+ let mut words = vec!["graphicle".to_string()];+ if custom_store {+ words.extend(["--data-dir".into(), quote(&directory.to_string_lossy())]);+ }+ words.extend(["connect".into(), client.to_string()]);+ if options.hooks {+ words.push("--hooks".into());+ }+ if guards {+ words.push("--guards".into());+ }+ if let Some(tools) = options.tools {+ words.extend(["--tools".into(), tools.name().into()]);+ }+ Some(words.join(" "))+ };arguments.push("mcp".into());// A project-scope entry in this folder's own file follows the folder// when the folder decided: the project of the folder the client starts@@ -475,7 +518,8 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Resresult["unchanged"] = json!(true);} else {if let Some(config) = &config {- agent_files::backup_in(&directory, config)?;+ agent_files::backup_in(&directory, config)+ .map_err(|error| agent_files::naming(config, error))?;}match crate::platform::command("codex").args(["mcp", "add", &entry, "--"])@@ -498,7 +542,8 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Reslet Some(config) = &config else {return Err(Error::bad("Home directory unavailable"));};- write_codex_table(config, &text, &entry, &command_text, &arguments)?;+ write_codex_table(config, &text, &entry, &command_text, &arguments)+ .map_err(|error| agent_files::naming(config, error))?;}Err(_) => {return Err(Error::bad(@@ -527,14 +572,81 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Resresult["configuration"] = json!(config);}if let Some(plan) = hook_plan {- result["hooks"] =- write_hooks(plan, &directory, &folder, &project.id)?["capture"].take();+ let file = plan.destination.clone();+ result["hooks"] = match write_hooks(plan, &directory, &folder, &project.id)? {+ Ok(mut written) => written["capture"].take(),+ Err(reason) if policy.skip_unwritable_hooks => {+ hooks_skipped(&file, reason, hooks_command(false))+ }+ Err(reason) => return Err(unwritten(&file, &reason)),+ };}if options.guards {result["graph"] = json!({"guard_hooks":"not available for codex: its hooks cannot add context before a tool call"});}return Ok(result);}+ // Muse Code with hooks: Graphicle's plugin carries the server, the skill+ // and the hooks. Without the `muse` program, or when Muse Code refuses+ // the plugin, the server's entry goes into its settings as before and+ // the reply says why.+ let mut plugin_skipped = None;+ if client == "muse" && options.hooks && options.config_path.is_none() {+ // The server's flags, as `connect` chose them (`--name` names a+ // settings entry: the plugin's id is always `graphicle`).+ let mut server: Vec<&str> = Vec::new();+ if tools != ToolSet::All {+ server.extend(["--tools", tools.name()]);+ }+ if learning {+ server.push("--allow-learning");+ }+ if options.work_state {+ server.push("--work-state");+ }+ match connect_muse_plugin(&directory, &program, &folder, &project.id, &server) {+ Ok(mut plugin) => {+ let next = format!(+ "Approve the plugin once with muse plugins approve {}, then start a new Muse Code session",+ crate::muse_code::PLUGIN_ID+ );+ let mut result = json!({"connected":true,"client":client,+ "configuration":plugin["package"].take(),"entry":crate::muse_code::PLUGIN_ID,+ "project":chosen,"access":access(learning),"tools":tools.name(),+ "plugin":plugin["state"].clone(),+ "hooks":{"configuration":plugin["manifest"].take(),"installed":plugin["hooks"].take(),"next":next},+ "next":next});+ if plugin["state"] == "updated" {+ result["updated"] = json!(true);+ }+ if let Some(removed) = plugin.get_mut("replaced").map(Value::take) {+ result["replaced"] = removed;+ }+ return Ok(result);+ }+ Err(error) => plugin_skipped = Some(error.message),+ }+ }+ // Muse Code with Graphicle's plugin installed: the plugin's server+ // serves the project, so no settings entry is added beside it; the+ // plugin's paths are kept current (after an upgrade moved the program).+ if client == "muse"+ && !options.hooks+ && options.config_path.is_none()+ && let Some(mut plugin) = refresh_muse_plugin(&directory, &program)?+ {+ let learned = plugin["learning"] == true;+ let mut result = json!({"connected":true,"client":client,+ "configuration":plugin["package"].take(),"entry":crate::muse_code::PLUGIN_ID,+ "project":chosen,"access":access(learned),"tools":plugin["tools"].take(),+ "plugin":plugin["state"].clone(),+ "next":"Graphicle's Muse Code plugin serves this project; graphicle disconnect muse removes it"});+ match plugin["state"].as_str() {+ Some("current") => result["unchanged"] = json!(true),+ _ => result["updated"] = json!(true),+ }+ return Ok(result);+ }let user =crate::platform::home_dir().ok_or_else(|| Error::bad("Home directory unavailable"))?;let destination = if let Some(path) = options.config_path {@@ -560,6 +672,7 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Res}}"cursor" => user.join(".cursor/mcp.json"),+ "muse" => user.join(".config/muse/settings.json"),"vscode" => options.cwd.join(".vscode/mcp.json"),_ => options.cwd.join(".mcp.json"),}@@ -567,10 +680,10 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Res// The reply names the file as given; the record, absolutely.let recorded = std::path::absolute(&destination)?;let existed = destination.exists();- let group = if client == "vscode" {- "servers"- } else {- "mcpServers"+ let group = match client {+ "vscode" => "servers",+ "muse" => MUSE_GROUP,+ _ => "mcpServers",};let mut server = json!({"command":command,"args":arguments});let mut learned = json!({"command":command,"args":learned_arguments});@@ -578,6 +691,14 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Resserver["type"] = json!("stdio");learned["type"] = json!("stdio");}+ // Muse Code's servers name their transport; `optional` lets a session+ // start, with a warning, while Graphicle is not installed.+ if client == "muse" {+ for entry in [&mut server, &mut learned] {+ entry["transport"] = json!("stdio");+ entry["mode"] = json!("optional");+ }+ }// The entry to paste by hand when the file cannot be edited.let by_hand = |name: &str| -> String {format!(@@ -665,7 +786,8 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Res&& !guards&& read_config(&hook_file(client, options.cwd)?, "hook").is_ok_and(|(document, _)| holds_guard_hooks(&document, client, &directory));- let hook_plan = if options.hooks || guards || drop_guards {+ // Muse Code's hooks come only in its plugin (above).+ let hook_plan = if (options.hooks && client != "muse") || guards || drop_guards {let mut plan = plan_hooks(client,&program,@@ -691,16 +813,25 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Res} else {// Only Graphicle's entry changes in the file's text: its other// entries, formatting, comments and final newline stay.- let edited = original+ let mut edited = original.as_deref().and_then(|text| crate::json_edit::set(text, group, &entry, &server));document[group][&entry] = server.clone();- if let Some(parent) = destination.parent() {- std::fs::create_dir_all(parent)?;+ // Muse Code refuses a settings file without its schema version.+ if client == "muse" && document.get("schema_version").is_none() {+ document["schema_version"] = json!(MUSE_SCHEMA_VERSION);+ edited = None;}- agent_files::backup_in(&directory, &destination)?;- agent_files::write_json(&destination, original.as_deref(), edited, &document)- .map_err(|error| Error::bad(format!("{}; {}", error.message, by_hand(&entry))))?;+ // A file that cannot be written (in Claude Code's sandbox, or a+ // read-only folder) gets the entry to paste, whichever write failed.+ let written = (|| -> Result<()> {+ if let Some(parent) = destination.parent() {+ std::fs::create_dir_all(parent)?;+ }+ agent_files::backup_in(&directory, &destination)?;+ agent_files::write_json(&destination, original.as_deref(), edited, &document)+ })();+ written.map_err(|error| Error::bad(format!("{}; {}", error.message, by_hand(&entry))))?;if replacing {result["updated"] = json!(true);}@@ -724,13 +855,29 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> Res"An entry named graphicle from an earlier connect is still there; remove it if it serves the same project");}+ if let Some(reason) = plugin_skipped {+ result["plugin"] = json!({"state":"skipped","reason":reason,+ "next":"Install Muse Code's muse program, then run graphicle connect muse --hooks"});+ } else if client == "muse" {+ result["plugin"] = json!({"state":"off",+ "reason":"preview, opt-in: graphicle connect muse --hooks --allow-learning installs Graphicle's plugin (hooks, skill, server)"});+ }if let Some(plan) = hook_plan {- let mut written = write_hooks(plan, &directory, &folder, &project.id)?;+ let file = plan.destination.clone();+ let (capture, guard) = match write_hooks(plan, &directory, &folder, &project.id)? {+ Ok(mut written) => (written["capture"].take(), written["guard"].take()),+ // Setup: the entry stays written; the hooks say why they are not.+ Err(reason) if policy.skip_unwritable_hooks => {+ let skipped = hooks_skipped(&file, reason, hooks_command(guards));+ (skipped.clone(), skipped)+ }+ Err(reason) => return Err(unwritten(&file, &reason)),+ };if options.hooks {- result["hooks"] = written["capture"].take();+ result["hooks"] = capture;}if guards || drop_guards {- result["graph"] = json!({"guard_hooks":written["guard"].take()});+ result["graph"] = json!({"guard_hooks":guard});}} else if options.guards {result["graph"] = json!({"guard_hooks":format!("not available for {client}: only Claude Code's hooks can add context before a tool call")});@@ -738,6 +885,147 @@ pub fn connect_with(store: &Store, options: &Connect<'_>, policy: Policy) -> ResOk(result)}+/// Graphicle's Muse Code plugin of the data folder `directory`, when+/// `connect muse --hooks` installed it: its package rewritten with+/// `program`'s path and its server flags as they were, and Muse Code's copy+/// refreshed (`muse plugins update`) when that changed it. `None` when the+/// plugin is not installed.+fn refresh_muse_plugin(directory: &Path, program: &Path) -> Result<Option<Value>> {+ use crate::muse_code;+ let package = directory.join(muse_code::PLUGIN_FOLDER);+ let path = package.join(".muse-plugin/plugin.json");+ let Some(old) = std::fs::read_to_string(&path)+ .ok()+ .and_then(|text| serde_json::from_str::<Value>(&text).ok())+ else {+ return Ok(None);+ };+ let command: Vec<&str> = old["capabilities"]["mcpServers"][0]["command"]+ .as_array()+ .map(|argv| argv.iter().filter_map(Value::as_str).collect())+ .unwrap_or_default();+ let flags: Vec<&str> = command+ .iter()+ .position(|arg| *arg == "--or-workspace")+ .map(|at| command[at + 1..].to_vec())+ .unwrap_or_else(|| muse_code::PACKAGED_SERVER_FLAGS.to_vec());+ let tokens = old["capabilities"]["hooks"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|hook| hook["command"].as_array())+ .find_map(|argv| {+ let at = argv.iter().position(|arg| arg == "--pack-tokens")?;+ argv.get(at + 1)?.as_str()?.parse::<u64>().ok()+ })+ .unwrap_or(muse_code::SESSION_PACK_TOKENS);+ let manifest = muse_code::manifest(&program.to_string_lossy(), Some(directory), tokens, &flags);+ let tools = flags+ .iter()+ .position(|arg| *arg == "--tools")+ .and_then(|at| flags.get(at + 1))+ .copied()+ .unwrap_or("all");+ let mut reply = json!({"package":package,"tools":tools,+ "learning":flags.contains(&"--allow-learning")});+ if !muse_code::write_package(&package, &manifest)? {+ reply["state"] = json!("current");+ return Ok(Some(reply));+ }+ reply["state"] = match muse_code::program() {+ Some(muse) => match muse_code::update(&muse) {+ Ok(_) => json!("updated"),+ Err(error) => json!(format!("written; {}", error.message)),+ },+ None => json!("written; run muse plugins update graphicle"),+ };+ Ok(Some(reply))+}++/// Install Graphicle's Muse Code plugin for the data folder `directory`+/// ([`crate::muse_code`]): write the package into the data folder with+/// `program`'s path, back up Muse Code's plugin records, then+/// `muse plugins install`. Muse Code's settings entries of this data folder+/// for `project` (from an earlier `connect muse`) are removed, since the+/// plugin's server replaces them; the settings file is backed up first.+/// The session map of `project` starts building in the background.+fn connect_muse_plugin(+ directory: &Path,+ program: &Path,+ folder: &Path,+ project: &str,+ server: &[&str],+) -> Result<Value> {+ use crate::muse_code;+ let muse = muse_code::program()+ .ok_or_else(|| Error::bad("Muse Code's muse program was not found on PATH"))?;+ let package = directory.join(muse_code::PLUGIN_FOLDER);+ let manifest = muse_code::manifest(+ &program.to_string_lossy(),+ Some(directory),+ muse_code::SESSION_PACK_TOKENS,+ server,+ );+ let existed = package.join(".muse-plugin/plugin.json").is_file();+ muse_code::write_package(&package, &manifest)?;+ let env = crate::agent_detect::Environment::current();+ // Muse Code's own record of plugins changes: backed up first.+ if let Some(config) = env.muse_config().as_deref().and_then(Path::parent) {+ for record in ["plugins/installed.json", "plugins/marketplaces.json"] {+ let path = config.join(record);+ if path.is_file() && !path.is_symlink() {+ agent_files::backup_in(directory, &path)?;+ }+ }+ }+ let installed = muse_code::install(&muse, &package)?;+ agent_files::record(+ directory,+ agent_files::Change {+ path: std::path::absolute(package.join(".muse-plugin/plugin.json"))?,+ kind: "muse-plugin".into(),+ client: Some("muse".into()),+ entry: Some(muse_code::PLUGIN_ID.into()),+ created: !existed,+ ..Default::default()+ },+ )?;+ let mut reply = json!({"package":package,"state":installed["state"],+ "manifest":package.join(".muse-plugin/plugin.json"),+ "hooks":muse_code::HOOKS.iter().map(|hook| hook.event).collect::<Vec<_>>()});+ // The settings entries the plugin's server replaces.+ if let Some(settings) = env.muse_config().filter(|path| path.is_file()) {+ let (mut document, original) = read_config(&settings, "Muse Code")?;+ let names = graphicle_entries(&document, MUSE_GROUP, Some(project), directory);+ if !names.is_empty() {+ let mut edited = original.clone();+ for name in &names {+ remove_entry(&mut document, MUSE_GROUP, name, directory, Some(project));+ edited = edited+ .as_deref()+ .and_then(|text| crate::json_edit::remove(text, MUSE_GROUP, name));+ }+ agent_files::backup_in(directory, &settings)?;+ agent_files::write_json(&settings, original.as_deref(), edited, &document)?;+ reply["replaced"] = json!({"file":settings,"entries":names});+ }+ }+ // The first session's map: built now, in the background.+ if let Ok(executable) = std::env::current_exe() {+ let mut command = std::process::Command::new(executable);+ command+ .arg("--data-dir")+ .arg(directory)+ .args(["hook", "muse", "pack", "--project", project])+ .current_dir(folder)+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null());+ let _ = crate::platform::spawn_detached(&mut command);+ }+ Ok(reply)+}+/// Write Graphicle's table for `entry` into Codex's `config.toml` (`text`/// is its content), in place of an earlier one of that name.fn write_codex_table(@@ -1180,7 +1468,7 @@ pub fn refresh_hooks(store: &Store, client: &str, cwd: &Path) -> Result<Value> {specs.push(CLAUDE_CODE_PROMPT_CONTEXT);}let plan = plan_hooks(client, &stable_program()?, &directory, true, cwd, &specs)?;- let mut written = write_hooks(plan, &directory, &cwd.canonical()?, &project.id)?;+ let mut written = write_hooks_or_fail(plan, &directory, &cwd.canonical()?, &project.id)?;let mut reply = written["capture"].take();if guards {reply["guard"] = written["guard"].take();@@ -1214,26 +1502,70 @@ pub fn connect_prompt_context(store: &Store, cwd: &Path) -> Result<Value> {cwd,&[CLAUDE_CODE_PROMPT_CONTEXT],)?;- let mut written = write_hooks(plan, &directory, &cwd.canonical()?, &project.id)?;+ let mut written = write_hooks_or_fail(plan, &directory, &cwd.canonical()?, &project.id)?;Ok(written["prompt_context"].take())}+/// The error of a hooks file the file system refused to write: the file,+/// then why (`not writable: <the OS error>`).+fn unwritten(file: &Path, reason: &str) -> Error {+ Error::bad(format!("{}: {reason}", file.display()))+}++/// Hooks setup could not write ([`Policy::skip_unwritable_hooks`]): the+/// file, why, and the `connect` command that adds them later.+fn hooks_skipped(file: &Path, reason: String, command: Option<String>) -> Value {+ let mut skipped = json!({"configuration":file,"state":"skipped","reason":reason});+ if let Some(command) = command {+ skipped["by_hand"] = json!(format!(+ "To add them later, run this in this folder from a normal terminal: {command}"+ ));+ }+ skipped+}++/// [`write_hooks`] where a file that cannot be written is an error that+/// names it.+fn write_hooks_or_fail(+ plan: HookPlan,+ directory: &Path,+ folder: &Path,+ project: &str,+) -> Result<Value> {+ let file = plan.destination.clone();+ write_hooks(plan, directory, folder, project)?.map_err(|reason| unwritten(&file, &reason))+}+/// Write a hook plan (backing the file up first) and record it in the data/// folder `directory`; `folder` is the folder `connect` ran in, for-/// `project`.-fn write_hooks(plan: HookPlan, directory: &Path, folder: &Path, project: &str) -> Result<Value> {+/// `project`. `Err` inside is why the file system refused to write the+/// file (`not writable: <the OS error>`); nothing is recorded then.+fn write_hooks(+ plan: HookPlan,+ directory: &Path,+ folder: &Path,+ project: &str,+) -> Result<std::result::Result<Value, String>> {let existed = plan.destination.exists();if plan.outcomes.iter().any(|(_, installed)| *installed) || !plan.removed.is_empty() {- if let Some(parent) = plan.destination.parent() {- std::fs::create_dir_all(parent)?;+ let written = (|| -> Result<()> {+ if let Some(parent) = plan.destination.parent() {+ std::fs::create_dir_all(parent)?;+ }+ agent_files::backup_in(directory, &plan.destination)?;+ agent_files::write_json(+ &plan.destination,+ plan.original.as_deref(),+ None,+ &plan.document,+ )+ })();+ if let Err(error) = written {+ return match agent_files::write_failure(&error) {+ Some(reason) => Ok(Err(reason)),+ None => Err(error),+ };}- agent_files::backup_in(directory, &plan.destination)?;- agent_files::write_json(- &plan.destination,- plan.original.as_deref(),- None,- &plan.document,- )?;// A personal settings file Graphicle created stays out of Git.if !existed && plan.client == "claude-code" {agent_files::exclude_created(directory, &plan.destination)?;@@ -1272,7 +1604,7 @@ fn write_hooks(plan: HookPlan, directory: &Path, folder: &Path, project: &str) -"Keep .claude/settings.local.json out of version control; restart Claude Code"};// A capture hook is named by its event, a guard hook by its argument.- Ok(json!({+ Ok(Ok(json!({"capture": {"configuration":plan.destination,"installed":listed(false, true),"unchanged":listed(false, false),"capture":"completed turns after each answer; reviewed memory at session start; private spans dropped, credentials redacted","next":next},@@ -1283,7 +1615,7 @@ fn write_hooks(plan: HookPlan, directory: &Path, folder: &Path, project: &str) -"prompt_context": {"configuration":plan.destination,"installed":prompt(true),"unchanged":prompt(false),"context":"before each prompt that is a code question, the packet of graphicle context (at most 8,400 characters); nothing for other prompts, short ones, or when it fails or takes over 10 seconds","next":next},- }))+ })))}/// The arguments of the capture hooks `connect --hooks` installs.@@ -1527,7 +1859,7 @@ const NUDGE_CAP: u64 = 5;/// `GRAPHICLE_HOOK_NUDGE_CAP`, read as the graph engine's guard reads it:/// unset is [`NUDGE_CAP`]; 0, or anything but a number, lifts the cap.-fn nudge_cap() -> u64 {+pub(crate) fn nudge_cap() -> u64 {match std::env::var("GRAPHICLE_HOOK_NUDGE_CAP") {Err(std::env::VarError::NotPresent) => NUDGE_CAP,Ok(value) => value.trim().parse().unwrap_or(0),@@ -1543,7 +1875,7 @@ fn nudge_cap() -> u64 {/// `hook-nudges` folder; markers older than a day are removed when a new one/// starts. A payload without a session id, or a marker that cannot be/// written, is not budgeted.-fn nudge_allowed(directory: &Path, payload: &Value, cap: u64) -> bool {+pub(crate) fn nudge_allowed(directory: &Path, payload: &Value, cap: u64) -> bool {use sha2::Digest;let session = payload["session_id"].as_str().unwrap_or("");// A marker file name: `[^A-Za-z0-9_-]` becomes `_`, at most 64 characters.@@ -1606,7 +1938,7 @@ fn nudge_allowed(directory: &Path, payload: &Value, cap: u64) -> bool {/// Whether a shell command runs a text search (`grep`, `rg`, `find`, `fd`,/// `ack`, `ag`, `git grep`), behind wrappers such as `sudo` or `xargs`, in/// any of its pipeline or list segments; quoted text is not a command.-fn runs_a_search(command: &str) -> bool {+pub(crate) fn runs_a_search(command: &str) -> bool {const WRAPPERS: [&str; 12] = ["sudo", "command", "exec", "nohup", "time", "nice", "ionice", "env", "xargs", "timeout","stdbuf", "doas",diff --git a/crates/graphicle/src/api.rs b/crates/graphicle/src/api.rsindex 9e46810..90df46f 100644--- a/crates/graphicle/src/api.rs+++ b/crates/graphicle/src/api.rs@@ -1217,6 +1217,7 @@ pub const CORE_OPERATIONS: &[&str] = &["oauth.status","observer.context","observer.status",+ "pack","project.delete","project.list","projection.retry",@@ -1323,6 +1324,15 @@ pub(crate) fn dispatch(}},"note" => store.note(workspace, capability, args),+ // A tokenizer is a local file: the command line names one, a call+ // over HTTP or MCP counts by estimate.+ "pack" => {+ let mut args = args.clone();+ if let Some(fields) = args.as_object_mut() {+ fields.remove("tokenizer");+ }+ store.project_pack(workspace, capability, &args)+ }"memory.search" => store.memory_search(workspace, capability, args),"learning.refresh.prepare" => store.refresh_context(workspace, capability, args),"learning.review" => store.review_memory(workspace, capability, args),@@ -1783,6 +1793,23 @@ pub fn core_mcp_tools(learning: bool, work_state: bool) -> Vec<McpTool> {), "work_state.read", false));}tools.extend(crate::graph_tools::tools(false));+ // After the tools of 0.1.0's one server, which keep their order.+ tools.push(+ McpTool::new(+ tool(+ "pack",+ PACK_DESCRIPTION,+ json!({"question":{"type":"string","description":"the question or change request; leave it out for a whole-repository overview"},+ "budget":{"type":"integer","default":crate::code_pack::MCP_DEFAULT_BUDGET,"minimum":crate::code_pack::MIN_BUDGET,"maximum":crate::code_pack::MCP_MAX_BUDGET,"description":"the pack's size in tokens, a hard limit"},+ "repo":{"type":"string","description":REPO_DESCRIPTION}}),+ &[],+ false,+ ),+ "pack",+ true,+ )+ .workspace_only(),+ );tools}/// `identifier_route` when a call to `recall_project` leaves it out: on in@@ -1860,6 +1887,8 @@ pub fn switch_refusal(field: &str, value: &Value) -> Option<String> {pub const RECALL_SCOPE: &str = "scope";/// The `repo` argument of `recall_project` and `read_project_source`, which/// workspace connections publish.+/// The `pack` tool's description: when an agent should call it.+const PACK_DESCRIPTION: &str = "Pack the project's code for a question into one block of text within a token budget (budget, default 32000): an architecture summary, the most relevant code (small files whole, large ones as excerpts with line numbers), callers and callees, tests, docs and a manifest of what is in and what was left out. Call it once before a repository-wide question or a change that spans files, instead of many searches and reads; cite code from it as path:line.";const REPO_DESCRIPTION: &str = "The project to read, by id or key (list_projects lists the ids). Without it, recall_project searches every project of the workspace you can read, and read_project_source needs it.";/// What one MCP connection has been given, for `recall_project`'s opt-in/// `skip_shown` (Mastra's navigable recall, a86dc4240): the source spans of@@ -2451,6 +2480,9 @@ fn mcp_in(if name == "recall_project" && !structured {crate::query::cap_recall(&mut args);}+ if name == "pack" && args.get("budget").is_none_or(Value::is_null) {+ args["budget"] = json!(crate::code_pack::MCP_DEFAULT_BUDGET);+ }// 0.1.0's order: test files where the ranking puts them, and// 0.1.0's excerpts: no dates or age marks (`source_age`).if name == "recall_project" && !lean {@@ -2616,12 +2648,14 @@ fn mcp_in(} else {Vec::new()};- // The essentials' text, else the full reply.+ // The essentials' text, else the full reply; a pack's+ // markdown in every set.let reply = match (!structured).then(|| crate::query::lean_reply(name, graph_tool, &packet)).flatten(){Some(lean) => lean,+ None if name == "pack" => crate::code_pack::mcp_reply(packet),None => tool_reply(graph_tool, packet),};if let Err(error) = admission.serve(&app.worker.store, served_text(&reply), shares)diff --git a/crates/graphicle/src/capture.rs b/crates/graphicle/src/capture.rsindex 4e65fdc..f1fc0d8 100644--- a/crates/graphicle/src/capture.rs+++ b/crates/graphicle/src/capture.rs@@ -1,5 +1,5 @@-//! Agent-session capture: completed turns of Claude Code and Codex-//! transcripts become documents of a per-project "agent sessions" JSONL+//! Agent-session capture: completed turns of Claude Code, Codex and Muse+//! Code transcripts become documents of a per-project "agent sessions" JSONL//! connector through the ordinary delta import — originals that can be//! searched, cited and forgotten like any other source, never summaries.//!@@ -51,6 +51,7 @@ pub const START_CONTEXT_CHARS: usize = 8000;pub enum Client {ClaudeCode,Codex,+ Muse,}impl Client {@@ -58,19 +59,22 @@ impl Client {match value {"claude-code" | "claude_code" | "claude" => Ok(Self::ClaudeCode),"codex" => Ok(Self::Codex),- _ => Err(Error::bad("Choose the claude-code or codex client")),+ "muse" | "muse-code" => Ok(Self::Muse),+ _ => Err(Error::bad("Choose the claude-code, codex or muse client")),}}pub fn as_str(self) -> &'static str {match self {Self::ClaudeCode => "claude-code",Self::Codex => "codex",+ Self::Muse => "muse",}}fn label(self) -> &'static str {match self {Self::ClaudeCode => "Claude Code",Self::Codex => "Codex",+ Self::Muse => "Muse Code",}}}@@ -672,10 +676,200 @@ pub fn parse_codex(text: &str) -> Result<Session> {Ok(session)}+/// A Muse Code record's time (`recorded_at`, microseconds since 1970) as+/// RFC 3339.+fn muse_stamp(record: &Value) -> Option<String> {+ let micros = record["recorded_at"].as_i64()?;+ chrono::DateTime::from_timestamp_micros(micros)+ .map(|time| time.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))+}++/// The record kinds that carry Muse Code tool outputs.+const MUSE_TOOL_RESULTS: [&str; 4] = [+ "tool_result",+ "tool_result_batch_committed",+ "tool_results_committed",+ "tool_result_committed",+];++/// Parse a Muse Code session log+/// (`~/.local/share/muse/sessions/YYYY/MM/DD/<session>/session.jsonl`).+/// Every line is an envelope whose `stream` names the session+/// (`{"kind":"session","id":…}`) and whose `payload` holds the record; a+/// run's records carry their event in `payload.event` (`payload.kind` is+/// `run`), the shape Muse Code's own session-evidence projection reads, and+/// a run stream's records (an export's) carry it as the payload itself:+/// * a run's `started` event holds the person's prompt and starts a turn;+/// * `assistant_message_committed` holds an answer's text;+/// * `assistant_tool_calls_committed` holds `tool_calls` (`name`, `args`,+/// `call_id`) and the `tool_result…` events their outputs;+/// * `terminal` ends the run, which completes the turn;+/// * `runtime.session.metadata` names the session's `workspace_root`.+///+/// Sub-agents keep their own logs (`subagent/<id>/session.jsonl`), which+/// are not turns of the person's session ([`transcripts`] skips them), and+/// reasoning is never stored.+pub fn parse_muse(text: &str) -> Result<Session> {+ let mut session = Session::default();+ let mut drafts: Vec<Draft> = Vec::new();+ let mut names: BTreeMap<String, String> = BTreeMap::new();+ for line in text.lines() {+ let Ok(record) = serde_json::from_str::<Value>(line) else {+ continue;+ };+ if session.session_id.is_empty()+ && record["stream"]["kind"] == "session"+ && let Some(id) = record["stream"]["id"].as_str()+ {+ session.session_id = id.to_string();+ }+ let payload = &record["payload"];+ let payload_type = record["payload_type"].as_str().unwrap_or("");+ if payload_type == "runtime.session.metadata" {+ if let Some(root) = payload["workspace_root"]+ .as_str()+ .or(payload["record"]["workspace_root"].as_str())+ {+ session.cwd = Some(root.to_string());+ }+ if session.session_id.is_empty()+ && let Some(id) = payload["session_id"].as_str()+ {+ session.session_id = id.to_string();+ }+ continue;+ }+ // A session log's run record nests its event; a run stream's+ // record is the event.+ let nested = payload["event"].is_object();+ let event = if nested { &payload["event"] } else { payload };+ let kind = event["kind"].as_str().unwrap_or("");+ match kind {+ "context_projection_checkpoint" => {+ if session.cwd.is_none()+ && let Some(root) = event["session_metadata"]["workspace_root"].as_str()+ {+ session.cwd = Some(root.to_string());+ }+ }+ "started" => {+ let run = if nested {+ payload["kind"] == "run"+ } else {+ payload_type == "agent.run"+ };+ let Some(prompt) = event["prompt"].as_str().filter(|_| run) else {+ continue;+ };+ if prompt.trim().is_empty() || protocol_payload(prompt) {+ continue;+ }+ let mut draft = Draft {+ started_at: muse_stamp(&record),+ ..Draft::default()+ };+ let cleaned = clean(prompt, &mut draft.applied);+ if cleaned.trim().is_empty() {+ continue;+ }+ draft.prompt = cleaned.trim().to_string();+ draft.parts.push(format!("user: {}", cleaned.trim()));+ drafts.push(draft);+ }+ "assistant_message_committed" => {+ let Some(draft) = drafts.last_mut() else {+ continue;+ };+ let text = block_text(&event["text"]);+ if text.trim().is_empty() {+ continue;+ }+ let cleaned = clean(&text, &mut draft.applied);+ draft.parts.push(format!("assistant: {}", cleaned.trim()));+ draft.answered = true;+ }+ "assistant_tool_calls_committed" => {+ let Some(draft) = drafts.last_mut() else {+ continue;+ };+ for call in event["tool_calls"].as_array().into_iter().flatten() {+ let name = call["name"].as_str().unwrap_or("tool").to_string();+ let input = call+ .get("args")+ .or(call.get("arguments"))+ .or(call.get("input"))+ .cloned()+ .unwrap_or(Value::Null);+ let parsed = input+ .as_str()+ .and_then(|t| serde_json::from_str::<Value>(t).ok())+ .unwrap_or_else(|| input.clone());+ paths_of(&parsed, &mut draft.files);+ let shown = tool_text("input", &compact(&input), &mut draft.applied);+ draft.parts.push(format!("tool {name}: {shown}"));+ if !draft.tools.contains(&name) {+ draft.tools.push(name.clone());+ }+ if let Some(id) = call["call_id"].as_str().or(call["id"].as_str()) {+ names.insert(id.to_string(), name);+ draft.open_calls.insert(id.to_string());+ }+ draft.answered = true;+ }+ }+ kind if MUSE_TOOL_RESULTS.contains(&kind) => {+ let Some(draft) = drafts.last_mut() else {+ continue;+ };+ let results: Vec<&Value> = match event["results"].as_array() {+ Some(results) => results.iter().collect(),+ None => vec![event],+ };+ for result in results {+ let id = result["tool_call_id"]+ .as_str()+ .or(result["call_id"].as_str())+ .unwrap_or("")+ .to_string();+ draft.open_calls.remove(&id);+ let name = names.get(&id).cloned().unwrap_or_else(|| "tool".into());+ if let Some(code) = result["exit_code"]+ .as_i64()+ .or(result["metadata"]["exit_code"].as_i64())+ {+ draft.exit_codes.push(code);+ }+ let raw = ["text", "output", "result", "content"]+ .iter()+ .map(|key| &result[*key])+ .find(|value| !value.is_null())+ .unwrap_or(&Value::Null);+ let body = tool_text("output", &block_text(raw), &mut draft.applied);+ draft.parts.push(format!("tool {name} output: {body}"));+ }+ }+ "terminal" => {+ // The run ended: its turn is complete, answered or not.+ if let Some(draft) = drafts.last_mut() {+ draft.answered = true;+ draft.open_calls.clear();+ }+ }+ _ => {}+ }+ }+ if !valid_session_id(&session.session_id) {+ return Err(Error::bad("Session log names no valid session id"));+ }+ close(drafts, &mut session);+ Ok(session)+}+pub fn parse(client: Client, text: &str) -> Result<Session> {match client {Client::ClaudeCode => parse_claude_code(text),Client::Codex => parse_codex(text),+ Client::Muse => parse_muse(text),}}@@ -1153,11 +1347,22 @@ pub fn project_for_cwd(.map(|found| found.id))}-/// Transcript files under `root` (`*.jsonl`), newest first, at most `limit`.+/// Folders under a client's transcript root that hold no session of a+/// person's: Muse Code's sub-agent logs (`<session>/subagent/…`).+pub fn skipped_folders(client: Client) -> &'static [&'static str] {+ match client {+ Client::Muse => &["subagent"],+ Client::ClaudeCode | Client::Codex => &[],+ }+}++/// Transcript files under `root` (`*.jsonl`), newest first, at most `limit`;+/// folders named in `skip` are not entered.pub fn transcripts(root: &std::path::Path,since: Option<std::time::SystemTime>,limit: usize,+ skip: &[&str],) -> Vec<std::path::PathBuf> {let mut found: Vec<(std::time::SystemTime, std::path::PathBuf)> = Vec::new();let mut stack = vec![root.to_path_buf()];@@ -1171,7 +1376,13 @@ pub fn transcripts(continue;};if meta.is_dir() && !meta.file_type().is_symlink() {- stack.push(path);+ if !path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| skip.contains(&name))+ {+ stack.push(path);+ }} else if meta.is_file()&& path.extension().is_some_and(|e| e == "jsonl")&& meta.len() <= crate::limits::current().transcript_bytes as u64@@ -1198,6 +1409,13 @@ pub fn default_root(client: Client) -> Option<std::path::PathBuf> {Client::Codex => std::env::var_os("CODEX_HOME").map(|d| std::path::PathBuf::from(d).join("sessions")).or_else(|| home.map(|h| h.join(".codex/sessions"))),+ // Muse Code keeps its data under the XDG data folder on every+ // platform.+ Client::Muse => std::env::var_os("XDG_DATA_HOME")+ .map(std::path::PathBuf::from)+ .filter(|d| d.is_absolute())+ .or_else(|| home.map(|h| h.join(".local/share")))+ .map(|d| d.join("muse/sessions")),}}@@ -1229,6 +1447,145 @@ mod tests {assert_eq!(applied.elided, 1);}+ /// A Muse Code session log as its own session-evidence projection+ /// reads it: run records nest their event; a metadata record names the+ /// workspace.+ pub(crate) fn muse_log(session: &str, workspace: &str, finished: bool) -> String {+ let record = |sequence: u64, payload_type: &str, payload: Value| {+ json!({"schema_version":1,"id":format!("r{sequence}"),+ "stream":{"kind":"session","id":session},"sequence":sequence,+ "recorded_at":1_793_000_000_000_000_u64 + sequence,"record_type":"event",+ "durability":"durable","payload_type":payload_type,"payload":payload})+ .to_string()+ };+ let run = |event: Value| json!({"kind":"run","run_id":"run-1","event":event});+ let mut lines = vec![+ record(+ 1,+ "runtime.session.metadata",+ json!({"workspace_root":workspace}),+ ),+ record(+ 2,+ "agent.run",+ run(json!({"kind":"started",+ "prompt":"Why does the cache key include the tokenizer? <system-reminder>noise</system-reminder>"})),+ ),+ record(+ 3,+ "agent.run",+ run(json!({"kind":"reasoning_committed","text":"secret thoughts"})),+ ),+ record(+ 4,+ "agent.run",+ run(+ json!({"kind":"assistant_tool_calls_committed","tool_calls":[+ {"name":"mcp__graphicle__pack","args":"{\"question\":\"cache key\",\"path\":\"src/pack.rs\"}","call_id":"c1"}]}),+ ),+ ),+ record(+ 5,+ "agent.run",+ run(+ json!({"kind":"tool_result","call_id":"c1","text":"src/pack.rs:10 key = sha(tokenizer)"}),+ ),+ ),+ record(+ 6,+ "agent.run",+ run(json!({"kind":"assistant_message_committed",+ "text":"Because the tokenizer changes the token count (src/pack.rs:10)."})),+ ),+ record(+ 7,+ "agent.run",+ run(json!({"kind":"terminal","terminal":"completed"})),+ ),+ record(+ 8,+ "agent.run",+ run(json!({"kind":"started","prompt":"Now rename it"})),+ ),+ record(+ 9,+ "agent.run",+ run(+ json!({"kind":"assistant_tool_calls_committed","tool_calls":[+ {"name":"exec_command","args":{"cmd":"sed -i s/a/b/ src/pack.rs"},"call_id":"c2"}]}),+ ),+ ),+ ];+ if finished {+ lines.push(record(+ 10,+ "agent.run",+ run(json!({"kind":"tool_results_committed",+ "results":[{"tool_call_id":"c2","output":"","exit_code":0}]})),+ ));+ lines.push(record(+ 11,+ "agent.run",+ run(json!({"kind":"assistant_message_committed","text":"Renamed."})),+ ));+ lines.push(record(+ 12,+ "agent.run",+ run(json!({"kind":"terminal","terminal":"completed"})),+ ));+ }+ lines.join("\n") + "\n"+ }++ #[test]+ fn parses_a_muse_code_session_log() {+ let session = parse_muse(&muse_log("6a1f-77", "/w/repo", false)).unwrap();+ assert_eq!(session.session_id, "6a1f-77");+ assert_eq!(session.cwd.as_deref(), Some("/w/repo"));+ // The second run has an open tool call: only the first is complete.+ assert_eq!((session.seen, session.turns.len()), (2, 1));+ let turn = &session.turns[0];+ assert_eq!(turn.prompt, "Why does the cache key include the tokenizer?");+ assert!(+ turn.text.contains("tool mcp__graphicle__pack: "),+ "{}",+ turn.text+ );+ assert!(+ turn.text+ .contains("tool mcp__graphicle__pack output: src/pack.rs:10")+ );+ assert!(turn.text.contains("assistant: Because the tokenizer"));+ assert!(!turn.text.contains("noise") && !turn.text.contains("secret thoughts"));+ assert_eq!(turn.applied.private_spans, 1);+ assert!(turn.files.contains("src/pack.rs"));+ assert_eq!(+ turn.started_at.as_deref(),+ Some("2026-10-26T07:33:20.000002Z")+ );+ let finished = parse_muse(&muse_log("6a1f-77", "/w/repo", true)).unwrap();+ assert_eq!(finished.turns.len(), 2);+ assert_eq!(finished.turns[1].exit_codes, vec![0]);+ assert_eq!(finished.turns[1].tools, vec!["exec_command".to_string()]);+ assert!(parse_muse("{}\n").is_err());+ // A run stream's records (an export's) carry the event as the payload.+ let flat = [+ json!({"stream":{"kind":"session","id":"s-2"},"payload_type":"agent.run",+ "payload":{"kind":"started","prompt":"What prints the total?"}}),+ json!({"stream":{"kind":"session","id":"s-2"},"payload_type":"agent.run",+ "payload":{"kind":"assistant_message_committed","text":"tariff.py prints it."}}),+ json!({"stream":{"kind":"session","id":"s-2"},"payload_type":"agent.run",+ "payload":{"kind":"terminal","terminal":"completed"}}),+ ]+ .iter()+ .map(Value::to_string)+ .collect::<Vec<_>>()+ .join("\n");+ let flat = parse_muse(&flat).unwrap();+ assert_eq!(flat.turns.len(), 1);+ assert_eq!(flat.turns[0].prompt, "What prints the total?");+ }+#[test]fn only_a_lone_task_notification_is_a_protocol_notice() {let notice = "<task-notification>\n<task-id>b7</task-id>\n<status>completed</status>\n</task-notification>";diff --git a/crates/graphicle/src/cli.rs b/crates/graphicle/src/cli.rsindex 35dfe21..44cd362 100644--- a/crates/graphicle/src/cli.rs+++ b/crates/graphicle/src/cli.rs@@ -130,9 +130,11 @@ enum Command {#[arg(long)]replace: bool,/// Also install session-capture hooks (claude-code: this folder's- /// .claude/settings.local.json; codex: the user's hooks.json). They- /// import completed turns after each answer and add reviewed memory- /// at session start; they never block the client.+ /// .claude/settings.local.json; codex: the user's hooks.json; muse:+ /// Graphicle's Muse Code plugin, a preview, with the server, a skill+ /// and the hooks, through `muse plugins install`; setup leaves it to+ /// this flag). They import completed turns after each answer and add+ /// reviewed memory at session start; they never block the client.#[arg(long)]hooks: bool,/// Also give the client the work-state tools (`work_state_write`,@@ -363,6 +365,59 @@ enum Command {#[arg(long, hide = true)]graph_only: bool,},+ /// Pack the project's code for a question into one prompt, to a token+ /// budget: architecture, focus code, call paths, tests, docs and more of+ /// the repository, with a manifest. Without a question, an overview.+ Pack {+ /// The question; `-` reads it from standard input (at most 1 MiB).+ question: Option<String>,+ /// The project: an id, a key or a synced folder (default: this+ /// folder's project, else the last synced one).+ #[arg(long)]+ project: Option<String>,+ /// The pack's budget in tokens, a hard limit [default: 128000].+ #[arg(long, value_name = "TOKENS", value_parser = clap::value_parser!(u64).range(512..=2_000_000))]+ budget: Option<u64>,+ /// markdown (the default), xml, or json (the pack's chunks, with+ /// their markdown text, and the manifest).+ #[arg(long, default_value = "markdown", value_parser = ["markdown", "xml", "json"])]+ format: String,+ /// Count tokens exactly with this Hugging Face tokenizer.json; without+ /// it, an estimate with a margin.+ #[arg(long, value_name = "PATH")]+ tokenizer: Option<PathBuf>,+ /// Estimate tokens as UTF-8 bytes divided by this number, for all+ /// text alike and without a margin (to match another tool's sizing),+ /// instead of the per-language estimate.+ #[arg(long, value_name = "N", conflicts_with = "tokenizer")]+ bytes_per_token: Option<f64>,+ /// relevant-last puts the most relevant code at the end, next to the+ /// question; relevant-first puts it first.+ #[arg(long, default_value = "relevant-last", value_parser = ["relevant-last", "relevant-first"])]+ order: String,+ /// Which chunks start each line with its number.+ #[arg(long, default_value = "focus", value_parser = ["focus", "all", "none"])]+ line_numbers: String,+ /// The sections, comma-separated: arch, map, focus, paths, tests,+ /// docs, breadth, manifest [default: all; map is the cache layout's].+ #[arg(long, value_name = "LIST")]+ sections: Option<String>,+ /// standard: one pack for the question. cache: a repository part+ /// that is the same for every question at this commit, budget and+ /// settings (a provider's prompt cache bills it at the cached price+ /// on follow-up questions), then a question part [default: standard;+ /// cache with --prefix-share].+ #[arg(long, value_parser = ["standard", "cache"])]+ layout: Option<String>,+ /// With the cache layout: the share of the budget the repository part+ /// takes at most, from 0.1 to 1; 1.0 is a stable pack, where only the+ /// question after it changes [default: 0.9].+ #[arg(long, value_name = "F")]+ prefix_share: Option<f64>,+ /// Write the pack to this file instead of standard output.+ #[arg(long, value_name = "FILE")]+ out: Option<PathBuf>,+ },/// Answer from the project's original sources with the configured model.////// By default a `basic` job: one model call reads the retrieved excerpts@@ -384,11 +439,164 @@ enum Command {/// Most model calls the job may make.#[arg(long, default_value_t = 4)]max_calls: usize,+ /// Answer in one model call from a pack of the project's code+ /// (`graphicle pack`) that fills the model's input limit, for a model+ /// with a long context window; each cited path:line is checked+ /// against the working tree.+ #[arg(long, conflicts_with_all = ["retain", "workflow"])]+ pack: bool,+ /// With --pack: the pack's budget in tokens [default: the model's+ /// input limit less room for the question].+ #[arg(long, value_name = "TOKENS", requires = "pack")]+ budget: Option<usize>,+ /// With --pack: the configured model profile to ask [default: the+ /// answer model].+ #[arg(long, value_name = "NAME", requires = "pack")]+ model: Option<String>,+ /// With --pack: the pack's layout, standard or cache (a repository+ /// part that a provider's prompt cache can bill at the cached price+ /// on follow-up questions, then a question part) [default: standard;+ /// cache with --prefix-share].+ #[arg(long, value_parser = ["standard", "cache"], requires = "pack")]+ layout: Option<String>,+ /// With --pack and the cache layout: the share of the budget the+ /// repository part takes at most, from 0.1 to 1 [default: 0.9].+ #[arg(long, value_name = "F", requires = "pack")]+ prefix_share: Option<f64>,/// Print the job as JSON (the default when the output is not a/// terminal).#[arg(long)]json: bool,},+ /// Plan a change from a pack of the project's code: steps, files to edit+ /// with line ranges, new files, tests and risks, checked against the+ /// working tree. Nothing is changed.+ Plan {+ /// The change request; `-` reads it from standard input.+ request: String,+ /// The project: an id, a key or a synced folder (default: this+ /// folder's project, else the last synced one).+ #[arg(long)]+ project: Option<String>,+ /// The pack's budget in tokens [default: the model's input limit less+ /// room for the request].+ #[arg(long, value_name = "TOKENS")]+ budget: Option<usize>,+ /// The configured model profile to ask [default: the answer model].+ #[arg(long, value_name = "NAME")]+ model: Option<String>,+ /// The pack's layout, standard or cache [default: standard; cache+ /// with --prefix-share].+ #[arg(long, value_parser = ["standard", "cache"])]+ layout: Option<String>,+ /// With the cache layout: the share of the budget the repository part+ /// takes at most, from 0.1 to 1 [default: 0.9].+ #[arg(long, value_name = "F")]+ prefix_share: Option<f64>,+ /// Print the plan as JSON (the default when the output is not a+ /// terminal).+ #[arg(long)]+ json: bool,+ },+ /// Review a change: what the head adds since its merge base with the+ /// base, from a cache-aware pack whose change part holds the changed+ /// code, its callers and callees and its tests. Comments must sit on+ /// changed lines and cite evidence that holds in the working tree;+ /// --format github prints a review for GitHub. Nothing is posted.+ Review(crate::review::Args),+ /// The spend log of `ask --pack`, `plan` and `fix`: calls, tokens, the+ /// cached share and the cost at the configured price, by day and model.+ /// The log is `usage.jsonl` in the data folder, one line per model call,+ /// without prompts or answers.+ Usage {+ /// Only calls since this day (2026-10-26, UTC) or time+ /// (2026-10-26T12:00:00Z).+ #[arg(long, value_name = "WHEN")]+ since: Option<String>,+ /// Print the report as JSON.+ #[arg(long)]+ json: bool,+ /// Remove the reservations of calls not logged yet (each ends by+ /// itself when its call is logged, its process ends, or 40 minutes+ /// pass), for example after a crash; then print the report.+ #[arg(long)]+ clear_pending: bool,+ },+ /// Fix an issue on a new branch: a cache-aware pack focused on the issue,+ /// a plan, then edits as search-and-replace blocks, applied in a new git+ /// worktree from HEAD and tested with your test command; a failure goes+ /// back to the model, for at most --rounds rounds. Your working tree and+ /// branch are never touched, and nothing is pushed.+ Fix {+ /// The issue's text; `-` reads it from standard input.+ #[arg(conflicts_with = "issue_file")]+ issue: Option<String>,+ /// Read the issue's text from this file (at most 1 MiB).+ #[arg(long, value_name = "FILE")]+ issue_file: Option<PathBuf>,+ /// The test command, run with `sh -c` in the new worktree; never a+ /// command the model suggests [default: the configuration's fix.test,+ /// else none, and the change is untested].+ #[arg(long, value_name = "CMD")]+ test: Option<String>,+ /// Rounds of edits and tests at most.+ #[arg(long, default_value_t = 3, value_parser = clap::value_parser!(u64).range(1..=10))]+ rounds: u64,+ /// The pack's budget in tokens [default: the model's input limit less+ /// room for the issue].+ #[arg(long, value_name = "TOKENS")]+ budget: Option<usize>,+ /// The new branch [default: graphicle/fix-<words of the issue>].+ #[arg(long, value_name = "NAME")]+ branch: Option<String>,+ /// Commit the changes on the new branch (else they stay in its+ /// worktree).+ #[arg(long)]+ commit: bool,+ /// Seconds the test command may run, 1 to 86400 [default: the+ /// configuration's fix.timeout_seconds, else 600].+ #[arg(long, value_name = "SECONDS", value_parser = clap::value_parser!(u64).range(1..=86_400))]+ timeout: Option<u64>,+ /// The project: an id, a key or a synced folder (default: this+ /// folder's project, else the last synced one).+ #[arg(long)]+ project: Option<String>,+ /// The configured model profile to ask [default: the answer model].+ #[arg(long, value_name = "NAME")]+ model: Option<String>,+ /// The pack's layout, standard or cache [default: standard; cache+ /// with --prefix-share].+ #[arg(long, value_parser = ["standard", "cache"])]+ layout: Option<String>,+ /// With the cache layout: the share of the budget the repository part+ /// takes at most, from 0.1 to 1 [default: 0.9].+ #[arg(long, value_name = "F")]+ prefix_share: Option<f64>,+ /// A passage the pack takes first, whatever the issue's words rank:+ /// PATH, PATH:LINE (the lines around it) or PATH:START-END, as the+ /// project shows the path (`graphicle pixel`'s candidates, for one).+ /// In the cache layout it leads the question part, which takes what+ /// the repository part leaves of --budget. Repeatable, at most 50.+ #[arg(long, value_name = "PATH[:LINES]")]+ focus: Vec<String>,+ /// Print the report as JSON (the default when the output is not a+ /// terminal).+ #[arg(long)]+ json: bool,+ },+ /// Point at a pixel of a screenshot and get the code that draws it:+ /// SAM 3.1 finds the element under the point, the model reads its+ /// strings, and Graphicle finds them in the project's code (string+ /// literals, localization calls, then the code graph), ranked as+ /// path:line. With --text, only the lookup runs: no model call.+ Pixel(crate::pixel::Args),+ /// Drive a web app with a model's computer use (Muse Wonder or Muse+ /// Spark 1.3 on the Meta Model API): the model sees screenshots and+ /// sends clicks and keys, which your driver runs in a browser, until the+ /// issue's bug shows (or, with --look-for expected, the expected+ /// behaviour). Saves each screenshot and a step log; every call goes in+ /// the spend log, under the profile's caps and --max-cost.+ See(crate::computer::Args),/// Build, update and query code graphs with the graph engine/// (`graphicle graph --help` lists its commands).///@@ -447,6 +655,12 @@ enum Command {/// and the other tools need `repo` (`list_projects` lists them).#[arg(long)]workspace: bool,+ /// With --project, serve the workspace as --workspace does when the+ /// project is not found, instead of failing: for a client that+ /// starts one server in every folder, such as Muse Code's plugin+ /// (`--project . --or-workspace`).+ #[arg(long, conflicts_with_all = ["workspace", "pull_requests"])]+ or_workspace: bool,#[arg(long)]allow_learning: bool,/// Publish `work_state_write` and `work_state_read`: the agent's own@@ -497,7 +711,7 @@ enum Command {#[arg(long)]json: bool,},- /// Capture Claude Code or Codex sessions as project sources: completed+ /// Capture Claude Code, Codex or Muse Code sessions as project sources: completed/// turns with `<private>` spans dropped, credentials redacted and large/// tool output replaced by its size and digest. No model is called.Sessions {@@ -507,7 +721,17 @@ enum Command {/// Lifecycle-hook entry point (installed by `connect <client> --hooks`):/// reads the hook's JSON on stdin, never blocks the client, always exits 0.#[command(hide = true)]- Hook { client: String, event: String },+ Hook {+ client: String,+ event: String,+ /// Muse Code's session start: tokens of the repository map it adds+ /// (0 leaves it out; at most 100,000).+ #[arg(long)]+ pack_tokens: Option<u64>,+ /// The project of an internal step (`hook muse pack`).+ #[arg(long)]+ project: Option<String>,+ },/// Call a project operation with arguments from a JSON file.Call {operation: String,@@ -603,7 +827,7 @@ enum SessionsAction {/// goes to the synced project containing its working directory, and/// transcripts from other folders are skipped.Import {- /// claude-code or codex.+ /// claude-code, codex or muse (Muse Code).#[arg(long)]client: String,/// A transcript (.jsonl) or a folder of them.@@ -773,6 +997,46 @@ fn unread_environment(read: &[&str], set: impl Fn(&str) -> bool) -> Option<&'sta.copied().find(|name| set(name) && !read.contains(name))}+/// `-`: the text on standard input (at most 1 MiB); else the text itself.+fn read_dash(text: String) -> Result<String> {+ if text != "-" {+ return Ok(text);+ }+ use std::io::Read;+ let mut read = String::new();+ std::io::stdin()+ .take(1024 * 1024)+ .read_to_string(&mut read)?;+ Ok(read)+}++/// The session, project and working tree of a long-context command (`ask+/// --pack`, `plan`), with the folder brought up to date first.+fn long_context_target(+ store: &crate::store::Store,+ config: &crate::model::Config,+ project: Option<String>,+) -> Result<(local::Session, String, Option<PathBuf>)> {+ let session = local::session(store, false)?;+ let resolved = local::resolve(store, &session, project.as_deref())?;+ let project = resolved.id.clone();+ let fresh = crate::fresh::ensure(+ store,+ &session,+ &project,+ crate::fresh::Options::ask(config),+ );+ fresh.tell();+ let folder = match resolved.folder.clone() {+ Some(folder) => Some(folder),+ None => {+ store.authorized_read(&session.workspace, &session.capability, "read", |db, _| {+ crate::folders::current_folder(db, &project)+ })?+ }+ };+ Ok((session, project, folder))+}/// Whether the new-release notice ([`crate::update_notice`]) may follow/// `command` (`None`: `graphicle` alone): a command people run at a terminal/// that prints its readable view. Never the servers (`mcp`, `serve`, `open`),@@ -793,12 +1057,17 @@ fn notice_allowed(command: Option<&Command>) -> bool {| Command::Doctor { json, .. }| Command::Context { json, .. }| Command::Ask { json, .. }+ | Command::Plan { json, .. }+ | Command::Fix { json, .. }| Command::WorkState { json, .. }| Command::Config {action: Some(ConfigAction::Set { json, .. }),},) => *json,+ Some(Command::Review(args)) => args.machine(),Some(Command::Sync { json, quiet, .. }) => *json || *quiet,+ Some(Command::Pixel(args)) => args.json,+ Some(Command::See(args)) => args.json,_ => return false,};crate::terminal::human(json)@@ -903,13 +1172,47 @@ wherereturn print(&result);}let directory = cli.data_dir.unwrap_or_else(local::data_dir);- if let Command::Hook { client, event } = &command {- hook(&directory, client, event);+ if let Command::Hook {+ client,+ event,+ pack_tokens,+ project,+ } = &command+ {+ hook(&directory, client, event, *pack_tokens, project.as_deref());return Ok(());}if let Command::Restore { path } = command {return print(&local::restore(&path, &directory)?);}+ if let Command::Usage {+ since,+ json,+ clear_pending,+ } = &command+ {+ let log = crate::spend::log_path(&directory);+ let cleared = if *clear_pending {+ Some(crate::spend::clear_pending(&directory)?)+ } else {+ None+ };+ let mut report = crate::spend::report(&crate::spend::read(&directory)?, since.as_deref())?;+ report["pending"] = json!(crate::spend::pending(&directory, chrono::Utc::now())?);+ if let Some(cleared) = cleared {+ report["cleared_pending"] = json!(cleared);+ }+ if crate::terminal::human(*json) {+ if let Some(cleared) = cleared {+ println!("Removed {cleared} reservation(s) of calls not logged yet.");+ }+ print!("{}", crate::spend::report_text(&report, &log));+ } else {+ report["log"] = json!(log);+ println!("{}", serde_json::to_string_pretty(&report)?);+ }+ return Ok(());+ }if let Command::Uninstall { purge, yes, json } = command {return crate::disconnect::uninstall(&directory, purge, yes, json);}@@ -966,7 +1269,10 @@ where}_ => {}}- let store = Store::open(directory)?;+ // A data folder the file system refuses (a sandbox that keeps the home+ // folder read-only) is named.+ let store =+ Store::open(&directory).map_err(|error| crate::agent_files::naming(&directory, error))?;if let Some(note) = crate::terminal::note_data_version(&store.directory)&& std::io::stderr().is_terminal(){@@ -1348,6 +1654,7 @@ whereCommand::Mcp {project,workspace,+ or_workspace,allow_learning,work_state,tools,@@ -1361,8 +1668,23 @@ wherelet project = if workspace {None} else {- Some(local::project(&store, &session, project.as_deref())?)+ match local::project(&store, &session, project.as_deref()) {+ Ok(found) => Some(found),+ // A folder outside every synced project: the workspace.+ Err(error) if or_workspace => {+ eprintln!(+ "graphicle mcp: {}; serving the workspace's projects",+ error.message.trim_end_matches('.')+ );+ None+ }+ Err(error) => return Err(error),+ }};+ // The flags of a project connection that a workspace has no+ // project for.+ let workspace = project.is_none();+ let work_state = work_state && !workspace;let cwd = std::env::current_dir()?;// The pull-request tools run gh in this process's folder, so it// must be the project's own; a workspace@@ -1702,6 +2024,247 @@ where);Ok(())}+ Command::Pack {+ question,+ project,+ budget,+ format,+ tokenizer,+ bytes_per_token,+ order,+ line_numbers,+ sections,+ layout,+ prefix_share,+ out,+ } => {+ let question = match question.as_deref() {+ Some("-") => {+ use std::io::Read;+ let mut read = String::new();+ std::io::stdin()+ .take(1024 * 1024)+ .read_to_string(&mut read)?;+ read+ }+ Some(question) => question.to_string(),+ None => String::new(),+ };+ let session = local::session(&store, false)?;+ let resolved = local::resolve(&store, &session, project.as_deref())?;+ let project = resolved.id;+ let fresh = crate::fresh::ensure(+ &store,+ &session,+ &project,+ crate::fresh::Options::answer(&config),+ );+ fresh.tell();+ let mut args = json!({"repository_id":project,"question":question,+ "budget":budget.unwrap_or(crate::code_pack::DEFAULT_BUDGET as u64),+ "order":order,"line_numbers":line_numbers,+ "style":if format == "xml" {"xml"} else {"markdown"}});+ if let Some(sections) = sections {+ args["sections"] = json!(sections);+ }+ if let Some(tokenizer) = &tokenizer {+ args["tokenizer"] = json!(tokenizer.to_string_lossy());+ }+ if let Some(rate) = bytes_per_token {+ args["bytes_per_token"] = json!(rate);+ }+ if let Some(layout) = &layout {+ args["layout"] = json!(layout);+ }+ if let Some(share) = prefix_share {+ args["prefix_share"] = json!(share);+ }+ let pack = store.project_pack(&session.workspace, &session.capability, &args)?;+ let text = if format == "json" {+ format!("{pack}\n")+ } else {+ crate::code_pack::text(&pack)+ };+ match &out {+ Some(path) => {+ std::fs::write(path, &text)+ .map_err(|e| Error::bad(format!("Cannot write {}: {e}", path.display())))?;+ eprintln!(+ "graphicle: packed {} tokens of {} files into {} ({} s)",+ pack["tokens"],+ pack["included"].as_array().map_or(0, Vec::len),+ path.display(),+ pack["seconds"]+ );+ }+ None => {+ use std::io::Write;+ let mut stdout = std::io::stdout().lock();+ stdout.write_all(text.as_bytes())?;+ stdout.flush()?;+ }+ }+ Ok(())+ }+ Command::Ask {+ question,+ project,+ workflow,+ retain,+ max_calls,+ pack: true,+ budget,+ model,+ layout,+ prefix_share,+ json,+ } => {+ let _ = (workflow, retain, max_calls);+ let question = read_dash(question)?;+ let (session, project, folder) = long_context_target(&store, &config, project)?;+ let run = crate::long_context::Run {+ store: &store,+ session: &session,+ config: &config,+ project,+ folder,+ model,+ budget,+ layout,+ prefix_share,+ json,+ };+ crate::long_context::ask(run, &question).await+ }+ Command::Fix {+ issue,+ issue_file,+ test,+ rounds,+ budget,+ branch,+ commit,+ timeout,+ project,+ model,+ layout,+ prefix_share,+ focus,+ json,+ } => {+ if focus.len() > crate::fix::MAX_FOCUS {+ return Err(Error::bad(format!(+ "--focus takes at most {} passages",+ crate::fix::MAX_FOCUS+ )));+ }+ let focus = focus+ .iter()+ .map(|spec| crate::fix::parse_focus(spec).map_err(Error::bad))+ .collect::<Result<Vec<_>>>()?;+ let issue = match (issue, issue_file) {+ (Some(text), None) => read_dash(text)?,+ (None, Some(path)) => {+ use std::io::Read;+ let mut text = String::new();+ std::fs::File::open(&path)+ .map_err(|e| Error::bad(format!("Cannot read {}: {e}", path.display())))?+ .take(1024 * 1024)+ .read_to_string(&mut text)?;+ text+ }+ _ => return Err(Error::bad("Give the issue's text, or --issue-file FILE")),+ };+ let (session, project, folder) = long_context_target(&store, &config, project)?;+ let settings = config.fix.clone().unwrap_or_default();+ let run = crate::long_context::Run {+ store: &store,+ session: &session,+ config: &config,+ project,+ folder,+ model,+ budget,+ layout,+ prefix_share,+ json,+ };+ crate::fix::fix(+ run,+ crate::fix::Options {+ issue,+ test: test.or(settings.test),+ rounds: rounds as usize,+ branch,+ commit,+ timeout: std::time::Duration::from_secs(+ timeout.or(settings.timeout_seconds).unwrap_or(600),+ ),+ focus,+ },+ )+ .await+ }+ Command::Pixel(args) => {+ let (session, project, folder) =+ long_context_target(&store, &config, args.project.clone())?;+ let run = crate::long_context::Run {+ store: &store,+ session: &session,+ config: &config,+ project,+ folder,+ model: args.model.clone(),+ budget: Some(args.budget),+ layout: Some("cache".into()),+ prefix_share: None,+ json: args.json,+ };+ crate::pixel::pixel(run, args).await+ }+ Command::See(args) => crate::computer::see(&store, &config, args).await,+ Command::Plan {+ request,+ project,+ budget,+ model,+ layout,+ prefix_share,+ json,+ } => {+ let request = read_dash(request)?;+ let (session, project, folder) = long_context_target(&store, &config, project)?;+ let run = crate::long_context::Run {+ store: &store,+ session: &session,+ config: &config,+ project,+ folder,+ model,+ budget,+ layout,+ prefix_share,+ json,+ };+ crate::long_context::plan(run, &request).await+ }+ Command::Review(args) => {+ let (session, project, folder) =+ long_context_target(&store, &config, args.project.clone())?;+ let run = crate::long_context::Run {+ store: &store,+ session: &session,+ config: &config,+ project,+ folder,+ model: args.model.clone(),+ budget: args.budget,+ layout: args.layout.clone().or_else(|| Some("cache".into())),+ prefix_share: args.prefix_share,+ json: args.machine(),+ };+ crate::review::review(run, args).await+ }Command::Ask {question,project,@@ -1709,6 +2272,7 @@ whereretain,max_calls,json,+ ..} => {// `basic` with its default contract (grounded-v2) answers unless// the caller opts into `reflect`, the workflow that checks@@ -1868,6 +2432,7 @@ whereCommand::ConfigExample| Command::Help { .. }| Command::Config { .. }+ | Command::Usage { .. }| Command::Doctor { .. } => unreachable!(),}}@@ -2019,7 +2584,12 @@ fn import_sessions(let files = if root.is_file() {vec![root]} else if root.is_dir() {- capture::transcripts(&root, since, limit.clamp(1, 100_000))+ capture::transcripts(+ &root,+ since,+ limit.clamp(1, 100_000),+ capture::skipped_folders(client),+ )} else {return Err(Error::bad("Transcript path not found"));};@@ -2066,11 +2636,18 @@ fn import_sessions(/// Client lifecycle hook. It never blocks or fails the client: the session/// start context has 2.5 seconds, imports run in a detached process, every/// error is dropped and the exit code is 0.-fn hook(directory: &std::path::Path, client: &str, event: &str) {+fn hook(+ directory: &std::path::Path,+ client: &str,+ event: &str,+ pack_tokens: Option<u64>,+ project: Option<&str>,+) {use std::io::Read;let Ok(client) = crate::capture::Client::parse(client) else {return;};+ let muse = client == crate::capture::Client::Muse;// A data folder that is gone stays gone: `graphicle setup` makes a new// one (doctor reports the hooks that point at it).if !directory.join("reviews.sqlite3").is_file() {@@ -2091,11 +2668,24 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {.filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();+ // Muse Code's session map: at most SESSION_PACK_MAX tokens.+ let pack_tokens = pack_tokens+ .unwrap_or(crate::muse_code::SESSION_PACK_TOKENS)+ .min(crate::muse_code::SESSION_PACK_MAX);match event.as_str() {+ // The detached build of a Muse Code session's map+ // (`crate::muse_code::session_pack`).+ "pack" if muse => {+ if let (Some(project), Ok(store)) = (project, Store::open(directory)) {+ let _ = crate::muse_code::build_pack(&store, project, pack_tokens);+ }+ }"sessionstart" => {- // A resumed Claude Code conversation still holds the context its- // own start added (claude-mem #4423).- if client == crate::capture::Client::ClaudeCode && payload["source"] == "resume" {+ // A resumed Claude Code or Muse Code conversation still holds+ // the context its own start added (claude-mem #4423).+ if (client == crate::capture::Client::ClaudeCode || muse)+ && payload["source"] == "resume"+ {return;}let Some(cwd) = payload["cwd"]@@ -2116,7 +2706,7 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {// A plain thread: returning from main does not wait for it.std::thread::spawn(move || {let context = (|| -> Result<Option<(String, Store, crate::metering::Call)>> {- let store = Store::open(directory)?;+ let store = Store::open(directory.clone())?;let session = local::session(&store, false)?;let Some(project) = crate::capture::project_for_cwd(&store, &session, &cwd)?else {@@ -2126,7 +2716,7 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {// Graphicle (crate::agent_instructions::SESSION_ROUTING),// so every session in a project gets it; an empty one// would print nothing.- let context = store.session_start_context(+ let mut context = store.session_start_context(&session.workspace,&session.capability,&project,@@ -2134,6 +2724,15 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {if context.is_empty() {return Ok(None);}+ // Muse Code's session starts with the repository's map+ // first: the same bytes for every session at a commit,+ // so the prompt cache serves it across sessions too.+ if muse+ && let Some(map) =+ crate::muse_code::session_pack(&directory, &project, pack_tokens)+ {+ context = format!("{}\n\n{context}", map.trim_end());+ }let credential =crate::metering::principal(&store, &session.workspace, &session.capability).map(|principal| principal.credential)@@ -2162,7 +2761,13 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {}}"stop" | "sessionend" | "precompact" => {- let Some(transcript) = payload["transcript_path"].as_str().map(PathBuf::from) else {+ // Muse Code names its session log by the session's id.+ let transcript = if muse {+ crate::muse_code::session_log(&payload)+ } else {+ payload["transcript_path"].as_str().map(PathBuf::from)+ };+ let Some(transcript) = transcript else {return;};if transcript.extension().is_none_or(|e| e != "jsonl") || !transcript.is_file() {@@ -2184,8 +2789,16 @@ fn hook(directory: &std::path::Path, client: &str, event: &str) {// timeout does not stop the import.let _ = crate::platform::spawn_detached(&mut command);}- // The prompt hook of `setup --prompt-context` (crate::prompt_hook).+ // The prompt hook of `setup --prompt-context` (crate::prompt_hook),+ // and of Muse Code's plugin."promptcontext" => crate::prompt_hook::run(directory, &payload),+ // Muse Code's plugin, after a batch of tool calls.+ "toolbatch" if muse => {+ use std::io::Write;+ if let Some(output) = crate::muse_code::tool_batch_output(directory, &payload) {+ let _ = writeln!(std::io::stdout(), "{output}");+ }+ }// The guard hooks of `connect --graph`."guardsearch" | "guardread" => {use std::io::Write;diff --git a/crates/graphicle/src/code_pack.rs b/crates/graphicle/src/code_pack.rsnew file mode 100644index 0000000..9ec6afc--- /dev/null+++ b/crates/graphicle/src/code_pack.rs@@ -0,0 +1,6819 @@+//! `graphicle pack`: a project's code for one question, filled to a token+//! budget and laid out for a long-context model.+//!+//! The ranking is `context`'s own: the fused order of the passage index, the+//! identifier arm and the code-graph arm, read whole+//! ([`crate::query::PACK_RANKING`]) instead of as the packet's top excerpts.+//! The saved query file ([`crate::query_file`]) gives the symbol start lines+//! that cut large files into excerpts, the call edges of the call paths and+//! the tests, and the degrees that order the breadth fill. File text comes+//! from the project's synced snapshot, the text the ranking and the code graph+//! read, so every line range in a pack is a range of that text.+//!+//! Sections, filled in this order, each within its share of the budget:+//! architecture (question-independent, cached per code-graph episode), focus+//! (the ranked files: small ones whole, large ones as symbol excerpts with+//! overlapping ranges merged), call paths (callers and callees of the focus+//! symbols, two steps along call edges), tests (from the graph's edges, else+//! by path and name), docs (ranked documentation passages and the nearest+//! README), breadth (the next ranked files, files in the focus folders, then+//! the rest by centrality). A header and a manifest frame them.+//!+//! The cache layout ([`Layout::Cache`]) splits a pack for a provider's+//! prompt cache, which matches the longest identical start of a prompt. Its+//! repository part comes first and depends on nothing but the project, its+//! commit and the settings: a header without the question, the architecture,+//! a map of the folders, the files with the most connections in the code+//! graph (whole, or the first line of each symbol) and the top docs, within+//! the prefix share of the budget. The question part follows: a manifest,+//! focus, call paths and tests, sized like a pack of the room left, which+//! never repeats lines the repository part holds and lists the ranked files+//! it holds instead. The question itself goes after the pack.+//!+//! The budget is a hard limit. Tokens are counted exactly with a Hugging Face+//! `tokenizer.json` (the `tokenizers` crate, pure Rust), else estimated from bytes+//! per token by language ([`estimate`]), with a margin. The text of a pack is+//! the concatenation of its chunks' text, in order, and the same inputs give+//! the same bytes.++use crate::store::{Store, repo, rows, s};+use crate::{Error, Result};+use serde_json::{Value, json};+use std::cell::RefCell;+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};+use std::path::Path;+use std::rc::Rc;+use std::sync::{Arc, LazyLock, Mutex, PoisonError};++/// The JSON format's name.+pub const FORMAT: &str = "graphicle.pack.v1";+/// `--budget` when a call gives none.+pub const DEFAULT_BUDGET: usize = 128_000;+/// The largest budget.+pub const MAX_BUDGET: usize = 2_000_000;+/// The smallest budget: room for the header and a little code.+pub const MIN_BUDGET: usize = 512;+/// The MCP tool's default and largest budgets.+pub const MCP_DEFAULT_BUDGET: usize = 32_000;+pub const MCP_MAX_BUDGET: usize = 200_000;++/// The token estimator's constants, in one place: a calibration against a+/// model's tokenizer changes them here and nowhere else.+pub mod estimate {+ /// Bytes per token by file extension: the Muse Spark Open tokenizer's+ /// own bytes per token over 1.03, measured on kubernetes and+ /// home-assistant (up to 400 files per extension and repository), so+ /// that an estimate runs about 3% above an exact count. Extensions those+ /// repositories hardly hold keep a lower rate (about 1.10 times the+ /// first, conservative one), which runs further above it.+ pub const BYTES_PER_TOKEN: &[(&str, f64)] = &[+ ("c", 3.4),+ ("cc", 3.4),+ ("cpp", 3.4),+ ("cs", 3.7),+ ("css", 3.3),+ ("go", 3.63),+ ("h", 3.5),+ ("hpp", 3.4),+ ("html", 3.3),+ ("java", 3.85),+ ("js", 3.5),+ ("json", 4.1),+ ("jsx", 3.4),+ ("kt", 3.6),+ ("md", 3.8),+ ("php", 3.5),+ ("proto", 4.05),+ ("py", 4.34),+ ("rb", 3.6),+ ("rs", 3.5),+ ("rst", 3.8),+ ("scala", 3.6),+ ("sh", 3.59),+ ("swift", 3.6),+ ("toml", 3.39),+ ("ts", 3.5),+ ("tsx", 3.4),+ ("txt", 2.9),+ ("xml", 3.2),+ ("yaml", 3.64),+ ("yml", 3.64),+ ];+ /// Any other file.+ pub const DEFAULT_BYTES_PER_TOKEN: f64 = 3.0;+ /// The pack's own text: headings, the manifest, the architecture and+ /// the call paths (3.61 bytes per token in Muse Spark Open's count of+ /// 22 kubernetes packs, over 1.03).+ pub const PACK_TEXT_BYTES_PER_TOKEN: f64 = 3.5;+ /// The share of the budget held back when counting by estimate.+ pub const MARGIN: f64 = 0.03;+ /// The share held back with an exact tokenizer (chunks are counted one+ /// by one while filling, the whole pack once at the end).+ pub const EXACT_MARGIN: f64 = 0.002;++ /// Bytes per token for a file with this extension.+ pub fn rate(extension: &str) -> f64 {+ BYTES_PER_TOKEN+ .binary_search_by(|(name, _)| name.cmp(&extension))+ .map_or(DEFAULT_BYTES_PER_TOKEN, |i| BYTES_PER_TOKEN[i].1)+ }++ /// The tokens of a line-number prefix (the number and a tab), in tenths:+ /// 1.6 up to four digits (Muse Spark Open adds 1.3 to 1.8 tokens a line,+ /// 1.5 on average), one more past them. A chunk's prefixes count the sum,+ /// rounded up ([`prefix_tokens`]).+ pub fn prefix_tenths(line: usize) -> usize {+ if line < 10_000 { 16 } else { 26 }+ }++ /// The tokens of the line-number prefixes of lines `from..=to`.+ pub fn prefix_tokens(from: usize, to: usize) -> usize {+ (from..=to).map(prefix_tenths).sum::<usize>().div_ceil(10)+ }++ /// The estimate for `bytes` of text at `rate` bytes per token.+ pub fn tokens(bytes: usize, rate: f64) -> usize {+ (bytes as f64 / rate).ceil() as usize+ }+}++/// How tokens are counted.+pub enum Counter {+ /// Bytes per token by language ([`estimate`]).+ Estimate,+ /// UTF-8 bytes divided by one rate for all text, with no margin+ /// (`--bytes-per-token`): the rule another tool sizes its own text by,+ /// so that both are matched.+ Uniform(f64),+ /// A Hugging Face tokenizer.+ Exact {+ name: String,+ tokenizer: Box<tokenizers::Tokenizer>,+ },+}++impl Counter {+ /// The estimator, one rate of bytes per token, or the tokenizer at+ /// `path`.+ pub fn open(path: Option<&str>, bytes_per_token: Option<f64>) -> Result<Self> {+ let Some(path) = path else {+ return Ok(match bytes_per_token {+ Some(rate) => Self::Uniform(rate),+ None => Self::Estimate,+ });+ };+ if bytes_per_token.is_some() {+ return Err(Error::bad(+ "Choose --tokenizer or --bytes-per-token, not both",+ ));+ }+ let tokenizer = tokenizers::Tokenizer::from_file(path)+ .map_err(|error| Error::bad(format!("Cannot read the tokenizer {path}: {error}")))?;+ Ok(Self::Exact {+ name: tokenizer_name(path),+ tokenizer: Box::new(tokenizer),+ })+ }++ /// `estimate`, or the tokenizer's name.+ pub fn name(&self) -> String {+ match self {+ Self::Estimate | Self::Uniform(_) => "estimate".into(),+ Self::Exact { name, .. } => name.clone(),+ }+ }++ pub fn exact(&self) -> bool {+ !matches!(self, Self::Estimate | Self::Uniform(_))+ }++ /// The tokens of `text`, whose `prefix_bytes` of line-number prefixes+ /// cost `prefix_tokens`, the rest `rate` bytes per token.+ fn count(&self, text: &str, rate: f64, prefix_bytes: usize, prefix_tokens: usize) -> usize {+ match self {+ Self::Estimate => {+ estimate::tokens(text.len().saturating_sub(prefix_bytes), rate) + prefix_tokens+ }+ Self::Uniform(uniform) => {+ let _ = (rate, prefix_bytes, prefix_tokens);+ estimate::tokens(text.len(), *uniform)+ }+ Self::Exact { tokenizer, .. } => {+ let _ = (rate, prefix_bytes, prefix_tokens);+ exact_count(tokenizer, text)+ }+ }+ }++ /// The tokens of the whole pack's text: the sum of its chunks by+ /// estimate, one count of the text with a tokenizer.+ fn total(&self, text: &str, sum: usize) -> usize {+ match self {+ Self::Estimate | Self::Uniform(_) => {+ let _ = text;+ sum+ }+ Self::Exact { tokenizer, .. } => {+ let _ = sum;+ exact_count(tokenizer, text)+ }+ }+ }++ fn margin(&self) -> f64 {+ match self {+ Self::Estimate => estimate::MARGIN,+ Self::Uniform(_) => 0.0,+ Self::Exact { .. } => estimate::EXACT_MARGIN,+ }+ }++ /// How the header says tokens were counted.+ fn counted(&self) -> String {+ match self {+ Self::Estimate => "estimated from bytes per token by language, with a margin".into(),+ Self::Uniform(rate) => format!("estimated as UTF-8 bytes / {rate}, without a margin"),+ Self::Exact { name, .. } => format!("counted exactly with the tokenizer {name}"),+ }+ }+}++fn exact_count(tokenizer: &tokenizers::Tokenizer, text: &str) -> usize {+ tokenizer+ .encode_fast(text, false)+ .map(|encoding| encoding.len())+ // A text the tokenizer refuses: the estimate, doubled.+ .unwrap_or_else(|_| 2 * estimate::tokens(text.len(), estimate::DEFAULT_BYTES_PER_TOKEN))+}++/// A tokenizer's name: its folder's for a `tokenizer.json`, else its file's.+pub fn tokenizer_name(path: &str) -> String {+ let path = Path::new(path);+ let file = path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default();+ match path.parent().and_then(Path::file_name) {+ Some(folder) if file == "tokenizer.json" => folder.to_string_lossy().into_owned(),+ _ => file,+ }+}++/// A pack's sections, by their JSON names.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub enum Section {+ Header,+ Manifest,+ Architecture,+ /// The cache layout's map of the folders.+ Map,+ Focus,+ Paths,+ Tests,+ Docs,+ Breadth,+}++impl Section {+ pub const CHOOSABLE: [Section; 8] = [+ Section::Manifest,+ Section::Architecture,+ Section::Map,+ Section::Focus,+ Section::Paths,+ Section::Tests,+ Section::Docs,+ Section::Breadth,+ ];++ const ALL: [Section; 9] = [+ Section::Header,+ Section::Manifest,+ Section::Architecture,+ Section::Map,+ Section::Focus,+ Section::Paths,+ Section::Tests,+ Section::Docs,+ Section::Breadth,+ ];++ pub fn name(self) -> &'static str {+ match self {+ Self::Header => "header",+ Self::Manifest => "manifest",+ Self::Architecture => "architecture",+ Self::Map => "map",+ Self::Focus => "focus",+ Self::Paths => "paths",+ Self::Tests => "tests",+ Self::Docs => "docs",+ Self::Breadth => "breadth",+ }+ }++ fn title(self) -> &'static str {+ match self {+ Self::Header => "Code pack",+ Self::Manifest => "Manifest",+ Self::Architecture => "Architecture summary",+ Self::Map => "Repository map",+ Self::Focus => "Focus code",+ Self::Paths => "Call paths",+ Self::Tests => "Tests",+ Self::Docs => "Documentation",+ Self::Breadth => "Breadth",+ }+ }++ /// A `--sections` name: a section's JSON name, or `arch`.+ pub fn parse(name: &str) -> Option<Self> {+ Some(match name {+ "arch" | "architecture" => Self::Architecture,+ "map" => Self::Map,+ "manifest" => Self::Manifest,+ "focus" => Self::Focus,+ "paths" => Self::Paths,+ "tests" => Self::Tests,+ "docs" => Self::Docs,+ "breadth" => Self::Breadth,+ _ => return None,+ })+ }+}++/// Where the most relevant code goes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Order {+ /// Header, manifest, architecture, breadth (least relevant first), docs,+ /// tests, call paths, focus (most relevant last).+ RelevantLast,+ /// Header, manifest, architecture, focus (most relevant first), call+ /// paths, tests, docs, breadth.+ RelevantFirst,+}++impl Order {+ pub fn name(self) -> &'static str {+ match self {+ Self::RelevantLast => "relevant-last",+ Self::RelevantFirst => "relevant-first",+ }+ }++ fn sections(self) -> [Section; 8] {+ use Section::*;+ match self {+ Self::RelevantLast => [+ Header,+ Manifest,+ Architecture,+ Breadth,+ Docs,+ Tests,+ Paths,+ Focus,+ ],+ Self::RelevantFirst => [+ Header,+ Manifest,+ Architecture,+ Focus,+ Paths,+ Tests,+ Docs,+ Breadth,+ ],+ }+ }+}++/// How a pack's text is split for a provider's prompt cache, which matches+/// the longest identical start of a prompt.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Layout {+ /// One question-specific pack: its header names the question, so no+ /// part of it is the same for another question.+ Standard,+ /// A repository part first (header, architecture, map, breadth by+ /// centrality, top docs), the same bytes for every question at a+ /// commit, budget and settings; then a question part (manifest, focus,+ /// call paths, tests) that does not repeat what the first part holds.+ Cache,+}++impl Layout {+ pub fn name(self) -> &'static str {+ match self {+ Self::Standard => "standard",+ Self::Cache => "cache",+ }+ }+}++/// The share of the budget the cache layout's repository part takes at+/// most, when a call gives none.+pub const DEFAULT_PREFIX_SHARE: f64 = 0.9;+/// The smallest prefix share.+pub const MIN_PREFIX_SHARE: f64 = 0.1;++/// Which chunks carry line numbers.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Numbers {+ Focus,+ All,+ None,+}++/// The text a pack is written in.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Style {+ Markdown,+ Xml,+}++/// What a pack is asked for.+#[derive(Clone, Debug)]+pub struct Options {+ pub question: String,+ pub budget: usize,+ pub order: Order,+ pub numbers: Numbers,+ pub sections: BTreeSet<Section>,+ pub style: Style,+ pub tokenizer: Option<String>,+ /// One rate of UTF-8 bytes per token for all text, instead of the+ /// per-language estimate.+ pub bytes_per_token: Option<f64>,+ pub layout: Layout,+ /// The cache layout's repository part: this share of the budget at+ /// most (1.0: a stable pack, only the question after it changes).+ pub prefix_share: f64,+ /// The fixed budget the cache layout's repository part is sized from,+ /// when the budget itself moves between calls (a calibrated budget): the+ /// part then stays the same bytes ([`prefix_basis`]).+ pub prefix_budget: Option<usize>,+}++impl Options {+ /// From a call's arguments: `question`, `budget`, `order`,+ /// `line_numbers`, `sections` (a list or a comma-separated string),+ /// `style` (`markdown` or `xml`), `tokenizer` (a path), `layout`+ /// (`standard` or `cache`) and `prefix_share` (which alone chooses the+ /// cache layout).+ pub fn parse(args: &Value) -> Result<Self> {+ let question = args+ .get("question")+ .and_then(Value::as_str)+ .unwrap_or("")+ .trim()+ .to_string();+ if question.len() > 1024 * 1024 {+ return Err(Error::bad("The question is longer than 1 MiB"));+ }+ let budget = match args.get("budget") {+ None | Some(Value::Null) => DEFAULT_BUDGET,+ Some(value) => value+ .as_u64()+ .map(|n| n as usize)+ .ok_or_else(|| Error::bad("budget must be a number of tokens"))?,+ };+ if !(MIN_BUDGET..=MAX_BUDGET).contains(&budget) {+ return Err(Error::bad(format!(+ "budget must be from {MIN_BUDGET} to {MAX_BUDGET} tokens"+ )));+ }+ let pick = |key: &str, default: &str| -> String {+ args.get(key)+ .and_then(Value::as_str)+ .unwrap_or(default)+ .to_string()+ };+ let order = match pick("order", "relevant-last").as_str() {+ "relevant-last" => Order::RelevantLast,+ "relevant-first" => Order::RelevantFirst,+ _ => return Err(Error::bad("order must be relevant-last or relevant-first")),+ };+ let numbers = match pick("line_numbers", "focus").as_str() {+ "focus" => Numbers::Focus,+ "all" => Numbers::All,+ "none" => Numbers::None,+ _ => return Err(Error::bad("line_numbers must be focus, all or none")),+ };+ let style = match pick("style", "markdown").as_str() {+ "markdown" => Style::Markdown,+ "xml" => Style::Xml,+ _ => return Err(Error::bad("style must be markdown or xml")),+ };+ let names: Vec<String> = match args.get("sections") {+ None | Some(Value::Null) => Vec::new(),+ Some(Value::String(list)) => list+ .split(',')+ .map(|n| n.trim().to_string())+ .filter(|n| !n.is_empty())+ .collect(),+ Some(Value::Array(list)) => list+ .iter()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect(),+ Some(_) => return Err(Error::bad("sections must be a list of section names")),+ };+ let sections = if names.is_empty() {+ Section::CHOOSABLE.into_iter().collect()+ } else {+ let mut chosen = BTreeSet::new();+ for name in &names {+ chosen.insert(Section::parse(name).ok_or_else(|| {+ Error::bad(format!(+ "Unknown section {name}: choose from arch, map, focus, paths, tests, docs, breadth, manifest"+ ))+ })?);+ }+ chosen+ };+ let tokenizer = args+ .get("tokenizer")+ .and_then(Value::as_str)+ .filter(|t| !t.is_empty())+ .map(str::to_string);+ let bytes_per_token = match args.get("bytes_per_token") {+ None | Some(Value::Null) => None,+ Some(value) => Some(+ value+ .as_f64()+ .filter(|rate| (1.0..=16.0).contains(rate))+ .ok_or_else(|| Error::bad("bytes_per_token must be a number from 1 to 16"))?,+ ),+ };+ let prefix_share = match args.get("prefix_share") {+ None | Some(Value::Null) => None,+ Some(value) => Some(+ value+ .as_f64()+ .filter(|share| (MIN_PREFIX_SHARE..=1.0).contains(share))+ .ok_or_else(|| {+ Error::bad(format!(+ "prefix_share must be a number from {MIN_PREFIX_SHARE} to 1"+ ))+ })?,+ ),+ };+ let prefix_budget = match args.get("prefix_budget") {+ None | Some(Value::Null) => None,+ Some(value) => Some(+ value+ .as_u64()+ .map(|n| n as usize)+ .filter(|n| (MIN_BUDGET..=MAX_BUDGET).contains(n))+ .ok_or_else(|| {+ Error::bad(format!(+ "prefix_budget must be from {MIN_BUDGET} to {MAX_BUDGET} tokens"+ ))+ })?,+ ),+ };+ let layout = match args.get("layout").and_then(Value::as_str) {+ None if prefix_share.is_some() => Layout::Cache,+ None | Some("standard") => {+ if prefix_share.is_some() {+ return Err(Error::bad(+ "prefix_share sizes the cache layout's repository part: choose layout cache, or leave prefix_share out",+ ));+ }+ Layout::Standard+ }+ Some("cache") => Layout::Cache,+ Some(_) => return Err(Error::bad("layout must be standard or cache")),+ };+ Ok(Self {+ question,+ budget,+ order,+ numbers,+ sections,+ style,+ tokenizer,+ bytes_per_token,+ layout,+ prefix_share: prefix_share.unwrap_or(DEFAULT_PREFIX_SHARE),+ prefix_budget,+ })+ }++ fn on(&self, section: Section) -> bool {+ section == Section::Header || self.sections.contains(§ion)+ }+}++/// A code symbol of the graph.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Symbol {+ pub node: usize,+ pub name: String,+ pub path: String,+ pub line: usize,+ pub degree: usize,+}++/// One edge of a node: the node at its other end, its relation, and whether+/// it points at the node.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Edge {+ pub other: usize,+ pub relation: String,+ pub incoming: bool,+}++type EdgesFn<'a> = Box<dyn Fn(usize) -> Vec<Edge> + 'a>;+/// How a corpus reads a file's text by its path.+pub type FetchFn<'a> = Box<dyn FnMut(&str) -> Option<String> + 'a>;+type NodesFn<'a> = Box<dyn Fn(usize) -> Vec<usize> + 'a>;+type StartsFn<'a> = Box<dyn Fn(&str) -> Vec<usize> + 'a>;++/// What a pack reads of a code graph: its symbols, each node's edges, the+/// nodes each node points at (any relation), and each file's node start+/// lines (a node's range runs to the next start).+pub struct GraphView<'a> {+ symbols: Vec<Symbol>,+ by_path: HashMap<String, (usize, usize)>,+ by_node: HashMap<usize, usize>,+ edges: EdgesFn<'a>,+ dependencies: NodesFn<'a>,+ starts: StartsFn<'a>,+ memo: RefCell<HashMap<usize, Rc<Vec<Edge>>>>,+}++/// Edges read of one node at most (a hub's thousands are cut).+const MAX_EDGES_READ: usize = 2_000;++impl<'a> GraphView<'a> {+ pub fn new(+ mut symbols: Vec<Symbol>,+ edges: EdgesFn<'a>,+ dependencies: NodesFn<'a>,+ starts: StartsFn<'a>,+ ) -> Self {+ symbols.sort_by(|a, b| {+ (a.path.as_str(), a.line, a.name.as_str(), a.node).cmp(&(+ b.path.as_str(),+ b.line,+ b.name.as_str(),+ b.node,+ ))+ });+ let mut by_path: HashMap<String, (usize, usize)> = HashMap::new();+ let mut by_node = HashMap::new();+ for (i, symbol) in symbols.iter().enumerate() {+ by_path+ .entry(symbol.path.clone())+ .and_modify(|range| range.1 = i + 1)+ .or_insert((i, i + 1));+ by_node.entry(symbol.node).or_insert(i);+ }+ Self {+ symbols,+ by_path,+ by_node,+ edges,+ dependencies,+ starts,+ memo: RefCell::new(HashMap::new()),+ }+ }++ /// The graph of a saved query file.+ pub fn of_query_file(file: Arc<crate::query_file::QueryFile>) -> Option<GraphView<'static>> {+ use graphicle::serve_search::ScoreSource;+ let mut symbols = Vec::with_capacity(file.symbol_count());+ for position in 0..file.symbol_count() {+ let (node, name, path, line) = file.symbol(position).ok()?;+ let Some(line) = line else {+ continue;+ };+ symbols.push(Symbol {+ node,+ name: name.to_string(),+ path: path.to_string(),+ line,+ degree: file.degree(node),+ });+ }+ let edges_file = file.clone();+ let edges: EdgesFn<'static> = Box::new(move |node| {+ let Ok(adjacency) = edges_file.adjacency(node) else {+ return Vec::new();+ };+ let mut found = Vec::new();+ for id in adjacency.all().into_iter().take(MAX_EDGES_READ) {+ let Ok(edge) = edges_file.edge(id) else {+ continue;+ };+ let relation = edge+ .relation+ .as_ref()+ .and_then(Value::as_str)+ .unwrap_or("")+ .to_string();+ if edge.target == node && edge.source != node {+ found.push(Edge {+ other: edge.source,+ relation,+ incoming: true,+ });+ } else if edge.source == node && edge.target != node {+ found.push(Edge {+ other: edge.target,+ relation,+ incoming: false,+ });+ }+ }+ found+ });+ let deps_file = file.clone();+ let dependencies: NodesFn<'static> = Box::new(move |node| {+ let Ok(adjacency) = deps_file.adjacency(node) else {+ return Vec::new();+ };+ adjacency+ .neighbours()+ .into_iter()+ .filter(|&v| v != node && !adjacency.out_to(v).is_empty())+ .collect()+ });+ let starts: StartsFn<'static> =+ Box::new(move |path: &str| file.starts(path).ok().flatten().unwrap_or_default());+ Some(GraphView::new(symbols, edges, dependencies, starts))+ }++ /// The symbols of `path`, by start line.+ pub fn symbols(&self, path: &str) -> &[Symbol] {+ self.by_path+ .get(path)+ .map_or(&[], |&(from, to)| &self.symbols[from..to])+ }++ pub fn symbol_of(&self, node: usize) -> Option<&Symbol> {+ self.by_node.get(&node).map(|&i| &self.symbols[i])+ }++ fn edges(&self, node: usize) -> Rc<Vec<Edge>> {+ if let Some(hit) = self.memo.borrow().get(&node) {+ return hit.clone();+ }+ let mut found = (self.edges)(node);+ found.sort_by(|a, b| {+ (a.other, a.incoming, a.relation.as_str()).cmp(&(+ b.other,+ b.incoming,+ b.relation.as_str(),+ ))+ });+ found.dedup();+ let found = Rc::new(found);+ self.memo.borrow_mut().insert(node, found.clone());+ found+ }++ /// The node start lines of `path`, else its symbols' lines.+ fn starts(&self, path: &str) -> Vec<usize> {+ let mut starts = (self.starts)(path);+ if starts.is_empty() {+ starts = self.symbols(path).iter().map(|s| s.line).collect();+ }+ starts.sort_unstable();+ starts.dedup();+ starts+ }+}++/// What a pack is built from.+pub struct Corpus<'a> {+ pub project: String,+ pub commit: Option<String>,+ /// Every file of the project with its size in bytes.+ pub files: BTreeMap<String, usize>,+ /// The ranking's passages, best first: (path, first line, last line).+ pub ranking: Vec<(String, usize, usize)>,+ pub graph: Option<GraphView<'a>>,+ /// The question-independent architecture, when cached.+ pub modules: Option<Arc<Modules>>,+ fetch: FetchFn<'a>,+ cache: HashMap<String, Option<Arc<str>>>,+}++impl<'a> Corpus<'a> {+ pub fn new(+ project: String,+ commit: Option<String>,+ files: BTreeMap<String, usize>,+ ranking: Vec<(String, usize, usize)>,+ graph: Option<GraphView<'a>>,+ fetch: FetchFn<'a>,+ ) -> Self {+ Self {+ project,+ commit,+ files,+ ranking,+ graph,+ modules: None,+ fetch,+ cache: HashMap::new(),+ }+ }++ fn text(&mut self, path: &str) -> Option<Arc<str>> {+ if let Some(hit) = self.cache.get(path) {+ return hit.clone();+ }+ let read: Option<Arc<str>> = (self.fetch)(path).map(Arc::from);+ self.cache.insert(path.to_string(), read.clone());+ read+ }+}++fn extension(path: &str) -> &str {+ let name = path.rsplit('/').next().unwrap_or(path);+ match name.rsplit_once('.') {+ Some((stem, ext)) if !stem.is_empty() => ext,+ _ => "",+ }+}++fn rate_of(path: &str) -> f64 {+ estimate::rate(&extension(path).to_ascii_lowercase())+}++fn language(path: &str) -> &'static str {+ match extension(path).to_ascii_lowercase().as_str() {+ "go" => "go",+ "py" => "python",+ "rs" => "rust",+ "ts" => "typescript",+ "tsx" => "tsx",+ "js" | "mjs" | "cjs" => "javascript",+ "jsx" => "jsx",+ "java" => "java",+ "kt" => "kotlin",+ "c" | "h" => "c",+ "cc" | "cpp" | "cxx" | "hpp" | "hh" => "cpp",+ "cs" => "csharp",+ "rb" => "ruby",+ "php" => "php",+ "swift" => "swift",+ "scala" => "scala",+ "sh" | "bash" => "bash",+ "md" => "markdown",+ "json" => "json",+ "yaml" | "yml" => "yaml",+ "toml" => "toml",+ "proto" => "protobuf",+ "sql" => "sql",+ "html" => "html",+ "css" => "css",+ _ => "",+ }+}++const CODE_EXTENSIONS: &[&str] = &[+ "c", "cc", "cpp", "cs", "cxx", "go", "h", "hh", "hpp", "java", "js", "jsx", "kt", "m", "mm",+ "php", "proto", "py", "rb", "rs", "scala", "sh", "swift", "ts", "tsx",+];++fn is_code(path: &str) -> bool {+ CODE_EXTENSIONS.contains(&extension(path).to_ascii_lowercase().as_str())+}++/// Generated code, which the centrality fill leaves out (a ranked generated+/// file still goes in).+fn generated(path: &str) -> bool {+ let name = path.rsplit('/').next().unwrap_or(path);+ name.contains("generated")+ || name.ends_with(".pb.go")+ || name.ends_with("_pb2.py")+ || name.ends_with(".min.js")+ || path.contains("/testdata/")+ || path.starts_with("testdata/")+}++fn class(path: &str) -> crate::code_question::PathClass {+ crate::code_question::path_class(path)+}++fn est_file(path: &str, bytes: usize) -> usize {+ estimate::tokens(bytes, rate_of(path))+}++/// A symbol's name as a pack shows it: the code graph's qualified name+/// without its file (`pkg/x.go.Type.Method` is `Type.Method`), at most its+/// last two dotted segments; empty for a file's own node.+fn short(name: &str) -> &str {+ let tail = name.rsplit('/').next().unwrap_or(name);+ let mut parts = tail.splitn(3, '.');+ let tail = match (parts.next(), parts.next(), parts.next()) {+ (Some(stem), Some(ext), rest) if !stem.is_empty() && is_code(&format!("x.{ext}")) => {+ rest.unwrap_or("")+ }+ _ => tail,+ };+ let mut dots = tail.rmatch_indices('.');+ match (dots.next(), dots.next()) {+ (Some(_), Some((i, _))) => &tail[i + 1..],+ _ => tail,+ }+}++fn attr(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ for c in text.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' => out.push_str("""),+ '\n' | '\r' => out.push(' '),+ c => out.push(c),+ }+ }+ out+}++/// A fence longer than any run of backticks in `body`.+fn fence(body: &str) -> String {+ let mut longest = 0;+ let mut run = 0;+ for c in body.chars() {+ if c == '`' {+ run += 1;+ longest = longest.max(run);+ } else {+ run = 0;+ }+ }+ "`".repeat((longest + 1).max(3))+}++/// Line ranges (first, last; from 1) merged where they overlap or are at+/// most [`MERGE_GAP`] lines apart.+pub fn merge(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {+ ranges.retain(|&(a, b)| a >= 1 && a <= b);+ ranges.sort_unstable();+ let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());+ for (a, b) in ranges {+ match merged.last_mut() {+ Some(last) if a <= last.1 + 1 + MERGE_GAP => last.1 = last.1.max(b),+ _ => merged.push((a, b)),+ }+ }+ merged+}++/// Lines between two ranges that merging closes.+pub const MERGE_GAP: usize = 2;++/// `ranges` less the lines `covered` holds (both merged).+fn uncovered(ranges: &[(usize, usize)], covered: &[(usize, usize)]) -> Vec<(usize, usize)> {+ let mut out = Vec::new();+ for &(a, b) in ranges {+ let mut start = a;+ for &(c, d) in covered {+ if d < start || c > b {+ continue;+ }+ if c > start {+ out.push((start, c - 1));+ }+ start = start.max(d + 1);+ if start > b {+ break;+ }+ }+ if start <= b {+ out.push((start, b));+ }+ }+ out+}++/// One piece of a pack's text.+#[derive(Clone, Debug)]+struct Chunk {+ path: Option<String>,+ start: usize,+ end: usize,+ whole: bool,+ why: String,+ text: String,+ tokens: usize,+ /// The order its file went in (relevance), for the section's layout.+ order: usize,+}++impl Chunk {+ fn json(&self) -> Value {+ let lines = |n: usize| {+ if self.path.is_some() {+ json!(n)+ } else {+ Value::Null+ }+ };+ json!({"path":self.path,"start_line":lines(self.start),"end_line":lines(self.end),+ "whole":self.whole,"tokens":self.tokens,"why":self.why,"text":self.text})+ }+}++/// A file's text rendered as a chunk.+struct FilePiece<'t> {+ path: &'t str,+ lines: &'t [&'t str],+ start: usize,+ end: usize,+ whole: bool,+ numbered: bool,+}++fn render_file(+ style: Style,+ piece: &FilePiece<'_>,+ why: &str,+ counter: &Counter,+) -> (String, usize) {+ let mut body = String::new();+ let mut prefix_bytes = 0;+ let mut prefix_tenths = 0;+ for (i, line) in piece.lines[piece.start - 1..piece.end].iter().enumerate() {+ if piece.numbered {+ let n = piece.start + i;+ let prefix = format!("{n}\t");+ prefix_bytes += prefix.len();+ prefix_tenths += estimate::prefix_tenths(n);+ body.push_str(&prefix);+ }+ body.push_str(line);+ body.push('\n');+ }+ let range = format!("{}-{}", piece.start, piece.end);+ let text = match style {+ Style::Markdown => {+ let fence = fence(&body);+ format!(+ "### {} lines {range}{}\nwhy: {why}\n{fence}{}\n{body}{fence}\n\n",+ piece.path,+ if piece.whole { " (whole file)" } else { "" },+ language(piece.path)+ )+ }+ Style::Xml => format!(+ "<file path=\"{}\" lines=\"{range}\" why=\"{}\">\n{body}</file>\n",+ attr(piece.path),+ attr(why)+ ),+ };+ let tokens = counter.count(+ &text,+ rate_of(piece.path),+ prefix_bytes,+ prefix_tenths.div_ceil(10),+ );+ (text, tokens)+}++fn section_open(style: Style, section: Section) -> String {+ match style {+ Style::Markdown if section == Section::Header => String::new(),+ Style::Markdown => format!("## {}\n\n", section.title()),+ Style::Xml => format!("<section name=\"{}\">\n", section.name()),+ }+}++fn section_close(style: Style) -> String {+ match style {+ Style::Markdown => String::new(),+ Style::Xml => "</section>\n".into(),+ }+}++/// An included file.+#[derive(Clone, Debug)]+struct Included {+ tokens: usize,+ rank: Option<usize>,+ section: Section,+ /// The manifest line's cost charged when it went in.+ charged: usize,+}++/// The filling state: chunks by section, what each file holds, the tokens+/// used against the limit.+struct Fill<'o> {+ options: &'o Options,+ counter: &'o Counter,+ limit: usize,+ used: usize,+ sections: BTreeMap<Section, Vec<Chunk>>,+ spent: BTreeMap<Section, usize>,+ files: BTreeMap<String, Included>,+ covered: HashMap<String, Vec<(usize, usize)>>,+ next_order: usize,+ /// The cost of each section's opening and closing chunks.+ frame: BTreeMap<Section, usize>,+ /// Whether each new file is charged its manifest line.+ manifest: bool,+}++impl<'o> Fill<'o> {+ fn new(+ options: &'o Options,+ counter: &'o Counter,+ limit: usize,+ frame: BTreeMap<Section, usize>,+ manifest: bool,+ ) -> Self {+ Self {+ options,+ counter,+ limit,+ used: 0,+ sections: BTreeMap::new(),+ spent: BTreeMap::new(),+ files: BTreeMap::new(),+ covered: HashMap::new(),+ next_order: 0,+ frame,+ manifest,+ }+ }++ fn numbered(&self, section: Section) -> bool {+ match self.options.numbers {+ Numbers::All => true,+ Numbers::Focus => section == Section::Focus,+ Numbers::None => false,+ }+ }++ fn manifest_cost(&self, path: &str, rank: Option<usize>, section: Section) -> usize {+ if !self.manifest {+ return 0;+ }+ let line = manifest_line(path, 9_999_999, rank, section);+ self.counter+ .count(&line, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0)+ }++ fn room(&self, section: Section, cap: usize) -> usize {+ let frame = if self.sections.contains_key(§ion) {+ 0+ } else {+ self.frame[§ion]+ };+ let by_cap = cap.saturating_sub(self.spent.get(§ion).copied().unwrap_or(0) + frame);+ let by_limit = self.limit.saturating_sub(self.used + frame);+ by_cap.min(by_limit)+ }++ /// Add `chunk` to `section` if it fits the section's cap and the limit.+ fn add(&mut self, section: Section, cap: usize, mut chunk: Chunk, rank: Option<usize>) -> bool {+ let manifest = match &chunk.path {+ Some(path) if !self.files.contains_key(path) => self.manifest_cost(path, rank, section),+ _ => 0,+ };+ if chunk.tokens + manifest > self.room(section, cap) {+ return false;+ }+ if !self.sections.contains_key(§ion) {+ self.used += self.frame[§ion];+ *self.spent.entry(section).or_default() += self.frame[§ion];+ }+ self.used += chunk.tokens + manifest;+ *self.spent.entry(section).or_default() += chunk.tokens;+ if let Some(path) = &chunk.path {+ let entry = self.files.entry(path.clone()).or_insert(Included {+ tokens: 0,+ rank,+ section,+ charged: manifest,+ });+ entry.tokens += chunk.tokens;+ let covered = self.covered.entry(path.clone()).or_default();+ covered.push((chunk.start, chunk.end));+ *covered = merge_exact(std::mem::take(covered));+ }+ if chunk.order == usize::MAX {+ chunk.order = self.next_order;+ }+ self.next_order += 1;+ self.sections.entry(section).or_default().push(chunk);+ true+ }++ /// Remove the last chunk of `section` (the budget check at the end).+ fn pop(&mut self, section: Section) -> bool {+ let Some(list) = self.sections.get_mut(§ion) else {+ return false;+ };+ let Some(chunk) = list.pop() else {+ return false;+ };+ let empty = list.is_empty();+ self.used -= chunk.tokens;+ if let Some(path) = &chunk.path {+ let mut gone = false;+ if let Some(entry) = self.files.get_mut(path) {+ entry.tokens -= chunk.tokens;+ if entry.tokens == 0 {+ self.used -= entry.charged;+ gone = true;+ }+ }+ if gone {+ self.files.remove(path);+ self.covered.remove(path);+ }+ }+ if empty {+ self.sections.remove(§ion);+ self.used -= self.frame[§ion];+ }+ true+ }++ fn covered(&self, path: &str) -> &[(usize, usize)] {+ self.covered.get(path).map_or(&[], Vec::as_slice)+ }++ /// The chunks of a file's `ranges` (uncovered parts only), each with+ /// `why`; false when the first does not fit.+ #[allow(clippy::too_many_arguments)]+ fn add_ranges(+ &mut self,+ section: Section,+ cap: usize,+ path: &str,+ lines: &[&str],+ ranges: &[(usize, usize)],+ why: &dyn Fn(usize, usize) -> String,+ rank: Option<usize>,+ order: usize,+ ) -> usize {+ let total = lines.len();+ let ranges: Vec<(usize, usize)> = ranges+ .iter()+ .map(|&(a, b)| (a.max(1), b.min(total)))+ .filter(|&(a, b)| a <= b)+ .collect();+ let ranges = uncovered(&merge(ranges), self.covered(path));+ let mut added = 0;+ for (a, b) in ranges {+ let whole = a == 1 && b == total && self.covered(path).is_empty();+ let piece = FilePiece {+ path,+ lines,+ start: a,+ end: b,+ whole,+ numbered: self.numbered(section),+ };+ let reason = why(a, b);+ let (text, tokens) = render_file(self.options.style, &piece, &reason, self.counter);+ let chunk = Chunk {+ path: Some(path.to_string()),+ start: a,+ end: b,+ whole,+ why: reason,+ text,+ tokens,+ order,+ };+ if self.add(section, cap, chunk, rank) {+ added += 1;+ }+ }+ added+ }+}++/// Ranges merged only where they overlap or touch (what a file holds).+fn merge_exact(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {+ ranges.sort_unstable();+ let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());+ for (a, b) in ranges {+ match merged.last_mut() {+ Some(last) if a <= last.1 + 1 => last.1 = last.1.max(b),+ _ => merged.push((a, b)),+ }+ }+ merged+}++fn manifest_line(path: &str, tokens: usize, rank: Option<usize>, section: Section) -> String {+ match rank {+ Some(rank) => format!(+ "- {path}: {tokens} tokens, {}, rank {rank}\n",+ section.name()+ ),+ None => format!("- {path}: {tokens} tokens, {}\n", section.name()),+ }+}++/// A ranked file: its rank (from 1), its passages, best first, and why it+/// was put in the ranking when the retrieval did not rank it.+#[derive(Clone, Debug)]+struct Ranked {+ path: String,+ rank: usize,+ passages: Vec<(usize, usize)>,+ added: Option<&'static str>,+}++/// Folder names too general to route a question to.+const GENERAL_FOLDERS: &[&str] = &[+ "api",+ "app",+ "apps",+ "build",+ "cmd",+ "common",+ "components",+ "config",+ "core",+ "doc",+ "docs",+ "example",+ "examples",+ "hack",+ "helpers",+ "internal",+ "lib",+ "libs",+ "pkg",+ "plugin",+ "plugins",+ "script",+ "scripts",+ "server",+ "src",+ "staging",+ "test",+ "tests",+ "testdata",+ "third_party",+ "tools",+ "util",+ "utils",+ "vendor",+ "web",+];+/// Folder segments whose folders are never routed to: tests and vendored code.+const UNROUTED_SEGMENTS: &[&str] = &[+ "test",+ "tests",+ "testdata",+ "e2e",+ "fixtures",+ "vendor",+ "third_party",+ "node_modules",+];+/// A folder the question names is routed to when it holds at most this+/// many files.+const ROUTE_MAX_FILES: usize = 80;+/// Top-ranked files that stay ahead of the named folders' files.+const ROUTE_AFTER: usize = 5;+/// Ranked files that stay ahead of the definition files.+const DEFINITIONS_AFTER: usize = 15;+/// Top files whose imports lead to definitions, and the definition files+/// added at most.+const DEFINITION_SOURCES: usize = 8;+const DEFINITION_FILES: usize = 12;++/// The folders a question names: a folder whose last name is one, two or+/// three consecutive words of the question joined by `_` or `-` ("Alexa+/// Devices" names `alexa_devices`; the segments of a path, a URL or a+/// dotted module name are words too), that holds at most+/// [`ROUTE_MAX_FILES`] files, is not a test or vendored folder, and shares+/// its name with at most one other such folder. The longest name wins where+/// names overlap. In the order the question names them, at most three.+fn named_folders(question: &str, files: &BTreeMap<String, usize>) -> Vec<String> {+ let mut counts: HashMap<&str, usize> = HashMap::new();+ for path in files.keys() {+ let mut end = path.len();+ while let Some(i) = path[..end].rfind('/') {+ *counts.entry(&path[..i]).or_default() += 1;+ end = i;+ }+ }+ let mut by_leaf: HashMap<&str, Vec<&str>> = HashMap::new();+ for (&folder, &count) in &counts {+ let routable =+ count <= ROUTE_MAX_FILES && !folder.split('/').any(|s| UNROUTED_SEGMENTS.contains(&s));+ if routable {+ let leaf = folder.rsplit('/').next().unwrap_or(folder);+ by_leaf.entry(leaf).or_default().push(folder);+ }+ }+ let lower = question.to_lowercase();+ let words: Vec<&str> = lower+ .split(|c: char| !c.is_ascii_alphanumeric())+ .filter(|t| !t.is_empty())+ .collect();+ let mut used = vec![false; words.len()];+ let mut out: Vec<String> = Vec::new();+ 'words: for i in 0..words.len() {+ for n in (1..=3).rev() {+ if i + n > words.len() || used[i..i + n].iter().any(|u| *u) {+ continue;+ }+ for separator in ["_", "-"] {+ if n == 1 && separator == "-" {+ continue;+ }+ let name = words[i..i + n].join(separator);+ if name.len() < 3 || GENERAL_FOLDERS.contains(&name.as_str()) {+ continue;+ }+ let Some(folders) = by_leaf.get(name.as_str()) else {+ continue;+ };+ if folders.len() > 2 {+ continue;+ }+ let mut folders = folders.clone();+ folders.sort_unstable();+ for folder in folders {+ if !out.iter().any(|f| f == folder) {+ out.push(folder.to_string());+ }+ }+ used[i..i + n].iter_mut().for_each(|u| *u = true);+ if out.len() >= 3 {+ break 'words;+ }+ continue 'words;+ }+ }+ }+ out.truncate(3);+ out+}++static GO_IMPORT: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r#"^\s*(?:import\s+)?(?:([A-Za-z_][A-Za-z0-9_]*)\s+)?"([^"]+)"\s*$"#).unwrap()+});+static GO_SELECTOR: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"\b([a-z][A-Za-z0-9_]*)\.([A-Z][A-Za-z0-9_]{2,})\b").unwrap()+});+static PY_FROM: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"(?m)^\s*from\s+(\.*)([A-Za-z0-9_.]*)\s+import\s").unwrap()+});++/// A Go file's imports: package name (its alias, else the path's last+/// segment) to import path.+fn go_imports(text: &str) -> BTreeMap<String, String> {+ let mut out = BTreeMap::new();+ let mut block = false;+ for line in text.lines().take(400) {+ let trimmed = line.trim();+ if trimmed.starts_with("import (") {+ block = true;+ continue;+ }+ if block && trimmed.starts_with(')') {+ block = false;+ continue;+ }+ if !(block || trimmed.starts_with("import ")) {+ continue;+ }+ if let Some(found) = GO_IMPORT.captures(trimmed) {+ let path = found[2].to_string();+ let name = match found.get(1) {+ Some(alias) => alias.as_str().to_string(),+ None => path.rsplit('/').next().unwrap_or(&path).to_string(),+ };+ out.insert(name, path);+ }+ }+ out+}++/// The project folder an import path names: the longest tail of it (two+/// segments at least) that is a folder of the project, as is or under+/// `staging/src/`.+fn import_folder(path: &str, folders: &BTreeSet<String>) -> Option<String> {+ let staged = format!("staging/src/{path}");+ if folders.contains(&staged) {+ return Some(staged);+ }+ let segments: Vec<&str> = path.split('/').collect();+ (0..segments.len().saturating_sub(1))+ .map(|i| segments[i..].join("/"))+ .find(|tail| folders.contains(tail))+}++/// Whether `text` defines `name` (Go): a declaration line that starts with+/// it (in a const, var or type block), or `func`, `type`, `var` or `const`+/// before it.+fn go_defines(text: &str, name: &str) -> bool {+ text.lines().any(|line| {+ let trimmed = line.trim_start();+ let after = |prefix: &str| -> bool {+ trimmed.strip_prefix(prefix).is_some_and(|rest| {+ let rest = rest.trim_start();+ let rest = if prefix == "func " && rest.starts_with('(') {+ rest.split_once(')').map_or("", |(_, r)| r.trim_start())+ } else {+ rest+ };+ rest.strip_prefix(name)+ .is_some_and(|tail| tail.starts_with([' ', '\t', '=', '(', '[']))+ })+ };+ after("") && line.starts_with(['\t', ' '])+ || after("func ")+ || after("type ")+ || after("var ")+ || after("const ")+ })+}++/// TypeScript and JavaScript files.+const TS_EXTENSIONS: &[&str] = &["ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "cts"];+/// C, C++ and Objective-C files.+const C_EXTENSIONS: &[&str] = &[+ "c", "cc", "cpp", "cxx", "h", "hh", "hpp", "hxx", "inl", "ipp", "m", "mm",+];+/// tsconfig files read for path aliases at most.+const MAX_TSCONFIGS: usize = 40;++static TS_FROM: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r#"(?m)^[ \t]*(?:import|export)\b([^;'"`]*?)\bfrom[ \t]*['"]([^'"\n]+)['"]"#)+ .unwrap()+});+static TS_BARE: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(+ r#"(?m)^[ \t]*import[ \t]*['"]([^'"\n]+)['"]|\b(?:require|import)[ \t]*\([ \t]*['"]([^'"\n]+)['"][ \t]*\)"#,+ )+ .unwrap()+});+static TS_PATHS: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r#""paths"\s*:\s*\{([^{}]*)\}"#).unwrap());+static TS_PATH_ENTRY: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r#""([^"]+)"\s*:\s*\[([^\]]*)\]"#).unwrap());+static TS_BASE_URL: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r#""baseUrl"\s*:\s*"([^"]*)""#).unwrap());+static QUOTED: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r#""([^"]*)""#).unwrap());+static IDENTIFIER: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r"[A-Za-z_][A-Za-z0-9_]*").unwrap());++/// `folder/relative` with `.` and `..` resolved; `None` when it climbs out+/// of the project.+fn joined(folder: &str, relative: &str) -> Option<String> {+ let mut out: Vec<&str> = Vec::new();+ for part in folder.split('/').chain(relative.split('/')) {+ match part {+ "" | "." => {}+ ".." => {+ out.pop()?;+ }+ part => out.push(part),+ }+ }+ Some(out.join("/"))+}++/// The project file a module path names, as TypeScript resolves it: the+/// path itself, with a TypeScript or JavaScript extension, or its folder's+/// index file (`./x.js` in an ES module names `x.ts`).+fn ts_file(base: &str, files: &BTreeMap<String, usize>) -> Option<String> {+ let base = ["js", "mjs", "cjs", "jsx"]+ .iter()+ .find_map(|e| base.strip_suffix(&format!(".{e}")))+ .unwrap_or(base);+ if base.is_empty() {+ return None;+ }+ let mut candidates = vec![base.to_string()];+ for e in ["ts", "tsx", "d.ts", "js", "jsx", "mts", "mjs", "cts", "cjs"] {+ candidates.push(format!("{base}.{e}"));+ }+ for e in ["ts", "tsx", "js", "jsx"] {+ candidates.push(format!("{base}/index.{e}"));+ }+ candidates.into_iter().find(|c| {+ files.contains_key(c) && TS_EXTENSIONS.contains(&extension(c).to_ascii_lowercase().as_str())+ })+}++/// A tsconfig `paths` entry: `@scope/*` to `packages/*`, from the project+/// root.+#[derive(Clone, Debug, PartialEq, Eq)]+struct TsAlias {+ pattern: String,+ targets: Vec<String>,+}++/// The `paths` aliases of a tsconfig file at `path` (comments allowed),+/// with their targets resolved from its `baseUrl` (else its folder) to+/// project paths. Targets outside the project or in `node_modules` are+/// left out.+fn ts_aliases_of(path: &str, text: &str) -> Vec<TsAlias> {+ let folder = path.rsplit_once('/').map_or("", |(f, _)| f);+ let base = TS_BASE_URL+ .captures(text)+ .and_then(|c| joined(folder, &c[1]))+ .unwrap_or_else(|| folder.to_string());+ let Some(block) = TS_PATHS.captures(text) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for entry in TS_PATH_ENTRY.captures_iter(&block[1]) {+ let targets: Vec<String> = QUOTED+ .captures_iter(&entry[2])+ .filter_map(|t| joined(&base, &t[1]))+ .filter(|t| !t.is_empty() && !t.split('/').any(|s| s == "node_modules"))+ .collect();+ if !targets.is_empty() {+ out.push(TsAlias {+ pattern: entry[1].to_string(),+ targets,+ });+ }+ }+ out+}++/// The project's tsconfig path aliases: those of its `tsconfig*.json`+/// files at most three folders deep, outside tests and vendored code.+fn ts_aliases(corpus: &mut Corpus<'_>) -> Vec<TsAlias> {+ let configs: Vec<String> = corpus+ .files+ .keys()+ .filter(|p| {+ let name = p.rsplit('/').next().unwrap_or(p);+ name.starts_with("tsconfig")+ && name.ends_with(".json")+ && p.matches('/').count() <= 3+ && !is_test(p)+ && class(p) != crate::code_question::PathClass::Vendored+ })+ .take(MAX_TSCONFIGS)+ .cloned()+ .collect();+ let mut out: Vec<TsAlias> = Vec::new();+ for config in configs {+ if let Some(text) = corpus.text(&config) {+ for alias in ts_aliases_of(&config, &text) {+ if !out.contains(&alias) {+ out.push(alias);+ }+ }+ }+ }+ out+}++/// The project file a TypeScript or JavaScript import names: a relative+/// path from `here`, or a tsconfig alias. Package imports outside the+/// project resolve to nothing.+fn ts_resolve(+ spec: &str,+ here: &str,+ files: &BTreeMap<String, usize>,+ aliases: &[TsAlias],+) -> Option<String> {+ if spec.starts_with('.') {+ return ts_file(&joined(here, spec)?, files);+ }+ for alias in aliases {+ let star = match alias.pattern.split_once('*') {+ Some((prefix, suffix)) => {+ let Some(middle) = spec+ .strip_prefix(prefix)+ .and_then(|rest| rest.strip_suffix(suffix))+ else {+ continue;+ };+ Some(middle)+ }+ None if alias.pattern == spec => None,+ None => continue,+ };+ for target in &alias.targets {+ let base = match star {+ Some(middle) => target.replacen('*', middle, 1),+ None => target.clone(),+ };+ if let Some(file) = ts_file(&base, files) {+ return Some(file);+ }+ }+ }+ None+}++/// The modules a TypeScript or JavaScript file imports or re-exports, each+/// with the number of names it takes from it (at least one).+fn ts_imports(text: &str) -> Vec<(String, usize)> {+ let mut out: Vec<(String, usize)> = Vec::new();+ for found in TS_FROM.captures_iter(text) {+ let clause = &found[1];+ let names = match clause.split_once('{') {+ Some((head, rest)) => {+ let inner = rest.split('}').next().unwrap_or("");+ let listed = inner+ .split(',')+ .filter(|n| {+ n.split_whitespace()+ .any(|w| w != "type" && IDENTIFIER.is_match(w))+ })+ .count();+ // `import D, {...}` takes D too; `import type {...}` does not.+ let default = head+ .split(|c: char| c == ',' || c.is_whitespace())+ .any(|w| w != "type" && IDENTIFIER.is_match(w));+ listed + usize::from(default)+ }+ None => 1,+ };+ out.push((found[2].to_string(), names.max(1)));+ }+ for found in TS_BARE.captures_iter(text) {+ if let Some(spec) = found.get(1).or(found.get(2)) {+ out.push((spec.as_str().to_string(), 1));+ }+ }+ out+}++/// Whether a module is a barrel (`index.ts`, `public_api.ts`) that passes+/// other modules' names on.+fn ts_barrel(path: &str) -> bool {+ let name = path.rsplit('/').next().unwrap_or(path);+ let stem = name.split('.').next().unwrap_or(name);+ matches!(stem, "index" | "public_api" | "public-api")+}++/// The files that define what the top ranked files use: for Go, the+/// identifiers they take from imported project packages (`features.X`+/// leads to the file of `pkg/features` that declares `X`); for Python, the+/// project modules they import from their own folder; for TypeScript and+/// JavaScript, the modules they import by a relative path or a tsconfig+/// alias, weighed by the names they take. Most used first.+fn definitions(corpus: &mut Corpus<'_>, top: &[Ranked]) -> Vec<String> {+ let mut folders: BTreeSet<String> = BTreeSet::new();+ for path in corpus.files.keys() {+ if let Some((folder, _)) = path.rsplit_once('/') {+ folders.insert(folder.to_string());+ }+ }+ let skip = |path: &str| {+ is_test(path) || generated(path) || class(path) == crate::code_question::PathClass::Vendored+ };+ let mut score: BTreeMap<String, (usize, usize)> = BTreeMap::new();+ let mut order = 0usize;+ let mut credit = |file: String, weight: usize, score: &mut BTreeMap<String, (usize, usize)>| {+ let entry = score.entry(file).or_insert((0, order));+ entry.0 += weight;+ order += 1;+ };+ // Read when a TypeScript or JavaScript source needs them.+ let mut aliases: Option<Vec<TsAlias>> = None;+ let in_top = |file: &str| top.iter().any(|r| r.path == file);+ for source in top+ .iter()+ .filter(|r| !skip(&r.path))+ .take(DEFINITION_SOURCES)+ {+ let Some(text) = corpus.text(&source.path) else {+ continue;+ };+ let here = source+ .path+ .rsplit_once('/')+ .map_or("", |(f, _)| f)+ .to_string();+ match extension(&source.path) {+ "go" => {+ let imports = go_imports(&text);+ let mut used: BTreeSet<(String, String)> = BTreeSet::new();+ for found in GO_SELECTOR.captures_iter(&text) {+ if imports.contains_key(&found[1]) {+ used.insert((found[1].to_string(), found[2].to_string()));+ }+ }+ for (package, name) in used.into_iter().take(200) {+ let Some(folder) = import_folder(&imports[&package], &folders) else {+ continue;+ };+ if folder == here {+ continue;+ }+ let candidates: Vec<String> = corpus+ .files+ .keys()+ .filter(|p| {+ p.rsplit_once('/').is_some_and(|(f, _)| f == folder)+ && p.ends_with(".go")+ && !skip(p)+ })+ .cloned()+ .collect();+ for candidate in candidates {+ if corpus+ .text(&candidate)+ .is_some_and(|t| go_defines(&t, &name))+ {+ credit(candidate, 1, &mut score);+ break;+ }+ }+ }+ }+ "py" => {+ for found in PY_FROM.captures_iter(&text) {+ let module = found[2].replace('.', "/");+ let base = if found[1].is_empty() {+ // Absolute: only modules of the importing file's own folder tree.+ module.clone()+ } else {+ let mut base = here.clone();+ for _ in 1..found[1].len() {+ base = base+ .rsplit_once('/')+ .map_or(String::new(), |(f, _)| f.to_string());+ }+ if module.is_empty() {+ base+ } else if base.is_empty() {+ module.clone()+ } else {+ format!("{base}/{module}")+ }+ };+ for file in [format!("{base}.py"), format!("{base}/__init__.py")] {+ let near = file.starts_with(&format!("{here}/"))+ || here.starts_with(base.as_str());+ if near+ && corpus.files.contains_key(&file)+ && !skip(&file)+ && file != source.path+ {+ credit(file, 1, &mut score);+ break;+ }+ }+ }+ }+ ext if TS_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()) => {+ if aliases.is_none() {+ aliases = Some(ts_aliases(corpus));+ }+ let aliases = aliases.as_deref().unwrap_or_default();+ for (spec, names) in ts_imports(&text) {+ let Some(file) = ts_resolve(&spec, &here, &corpus.files, aliases) else {+ continue;+ };+ // A package's barrel only passes its modules' names on.+ if !spec.starts_with('.') && ts_barrel(&file) {+ continue;+ }+ if file != source.path && !skip(&file) && !in_top(&file) {+ credit(file, names, &mut score);+ }+ }+ }+ _ => {}+ }+ }+ let mut files: Vec<(String, (usize, usize))> = score.into_iter().collect();+ files.sort_by(|a, b| b.1.0.cmp(&a.1.0).then(a.1.1.cmp(&b.1.1)));+ files+ .into_iter()+ .map(|(f, _)| f)+ .take(DEFINITION_FILES)+ .collect()+}++/// A name or file stem without case and separators: `MeshInstance3D`,+/// `mesh_instance_3d` and `mesh-instance-3d` are all `meshinstance3d`.+fn folded(name: &str) -> String {+ name.chars()+ .filter(char::is_ascii_alphanumeric)+ .map(|c| c.to_ascii_lowercase())+ .collect()+}++/// Whether a name reads as one of code's compound names: camelCase or+/// PascalCase with a capital after a lowercase letter or a digit+/// (`TextEdit`, `MeshInstance3D`, `formControl`), or words joined by `_`.+fn compound(name: &str) -> bool {+ let bytes = name.as_bytes();+ let inner_capital = bytes+ .windows(2)+ .any(|w| (w[0].is_ascii_lowercase() || w[0].is_ascii_digit()) && w[1].is_ascii_uppercase());+ let joined = name+ .trim_matches('_')+ .split('_')+ .filter(|p| !p.is_empty())+ .count()+ > 1;+ inner_capital || joined+}++/// Files a question names by a code name at most, per name.+const NAMED_FILES_PER_NAME: usize = 4;+/// Code names of a question routed to files at most.+const NAMED_FILE_NAMES: usize = 4;+/// Files routed by name at most.+const NAMED_FILES_MAX: usize = 8;+/// Words of a question read for names of two or three words.+const NAMED_WORDS: usize = 600;++static WORD: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(r"[A-Za-z0-9]+").unwrap());++/// The files a question names by a code name: a compound name of the+/// question (a part of `Class::method` or `a.b.C` too), or two or three+/// consecutive words of it, whose folded form is a code file's folded stem+/// (`TextEdit` and "the text edit" name `text_edit.cpp` and `text_edit.h`,+/// `FormControl` names `form_control.ts`, `UserModel` names+/// `UserModel.java`, `FooComponent` names `foo.component.ts`, "FileSystem+/// dock" names `filesystem_dock.cpp`), when at most+/// [`NAMED_FILES_PER_NAME`] code files outside tests carry that stem. In+/// the order the question names them, for at most [`NAMED_FILE_NAMES`]+/// names and [`NAMED_FILES_MAX`] files.+fn named_files(question: &str, files: &BTreeMap<String, usize>) -> Vec<String> {+ // (where the question names it, folded name)+ let mut keys: Vec<(usize, String)> = Vec::new();+ for name in crate::identifier_arm::named(question).names {+ let at = question.find(name.as_str()).unwrap_or(usize::MAX);+ for part in name.split(['.', ':', '#', '-', '>']) {+ let key = folded(part);+ if compound(part) && key.len() >= 6 {+ keys.push((at, key));+ }+ }+ }+ keys.sort_by_key(|(at, _)| *at);+ // Code names first, then runs of two or three words.+ let compound_keys = keys.len();+ let words: Vec<(usize, String)> = WORD+ .find_iter(question)+ .take(NAMED_WORDS)+ .map(|m| (m.start(), m.as_str().to_ascii_lowercase()))+ .collect();+ let mut runs: Vec<(usize, String)> = Vec::new();+ for n in 2..=3 {+ for run in words.windows(n) {+ let key: String = run.iter().map(|(_, w)| w.as_str()).collect();+ if key.len() >= 6 {+ runs.push((run[0].0, key));+ }+ }+ }+ runs.sort_by_key(|(at, _)| *at);+ keys.extend(runs);+ let mut wanted: Vec<(String, bool)> = Vec::new();+ let mut known: HashSet<String> = HashSet::new();+ for (i, (_, key)) in keys.into_iter().enumerate() {+ if known.insert(key.clone()) {+ wanted.push((key, i < compound_keys));+ }+ }+ if wanted.is_empty() {+ return Vec::new();+ }+ let mut by_stem: HashMap<String, Vec<&String>> = HashMap::new();+ for path in files.keys() {+ let name = path.rsplit('/').next().unwrap_or(path);+ let Some((stem, _)) = name.rsplit_once('.') else {+ continue;+ };+ let key = folded(stem);+ if known.contains(&key) {+ by_stem.entry(key).or_default().push(path);+ }+ }+ let mut out: Vec<String> = Vec::new();+ let mut names = 0;+ for (key, code_name) in &wanted {+ if out.len() >= NAMED_FILES_MAX {+ break;+ }+ let Some(paths) = by_stem.get(key) else {+ continue;+ };+ // Words name a file only in the languages that name files after+ // their classes.+ let class_files = |p: &str| {+ let ext = extension(p).to_ascii_lowercase();+ ext == "java"+ || TS_EXTENSIONS.contains(&ext.as_str())+ || C_EXTENSIONS.contains(&ext.as_str())+ };+ let code: Vec<&&String> = paths+ .iter()+ .filter(|p| {+ (is_code(p) || TS_EXTENSIONS.contains(&extension(p).to_ascii_lowercase().as_str()))+ && (*code_name || class_files(p))+ && !is_test(p)+ && !generated(p)+ && class(p) != crate::code_question::PathClass::Vendored+ })+ .collect();+ if code.is_empty() || code.len() > NAMED_FILES_PER_NAME {+ continue;+ }+ for path in code {+ if !out.contains(*path) {+ out.push((*path).clone());+ }+ }+ names += 1;+ if names >= NAMED_FILE_NAMES {+ break;+ }+ }+ out.truncate(NAMED_FILES_MAX);+ out+}++/// The ranking a pack fills by: the retrieval's, with the files the+/// question names by a code name and the files of the folders it names+/// right after its top files, and the files that define what the top files+/// use after the first [`DEFINITIONS_AFTER`]. Ranks follow the new order.+fn augment(corpus: &mut Corpus<'_>, question: &str, ranked: Vec<Ranked>) -> Vec<Ranked> {+ let folders = named_folders(question, &corpus.files);+ let mut routed: Vec<Ranked> = Vec::new();+ for path in named_files(question, &corpus.files) {+ let passages = ranked+ .iter()+ .find(|r| r.path == path)+ .map(|r| r.passages.clone())+ .unwrap_or_default();+ routed.push(Ranked {+ path,+ rank: 0,+ passages,+ added: Some("named in the question"),+ });+ }+ for folder in &folders {+ let prefix = format!("{folder}/");+ let mut files: Vec<(&String, usize)> = corpus+ .files+ .iter()+ .filter(|(p, _)| p.starts_with(&prefix) && !is_test(p) && !generated(p))+ .map(|(p, b)| (p, *b))+ .collect();+ // Files the retrieval ranked first, by rank; then the rest, smallest first.+ let rank_of: HashMap<&str, usize> =+ ranked.iter().map(|r| (r.path.as_str(), r.rank)).collect();+ files.sort_by(|a, b| {+ let ra = rank_of.get(a.0.as_str()).copied().unwrap_or(usize::MAX);+ let rb = rank_of.get(b.0.as_str()).copied().unwrap_or(usize::MAX);+ ra.cmp(&rb).then(a.1.cmp(&b.1)).then(a.0.cmp(b.0))+ });+ for (path, _) in files {+ let passages = ranked+ .iter()+ .find(|r| &r.path == path)+ .map(|r| r.passages.clone())+ .unwrap_or_default();+ routed.push(Ranked {+ path: path.clone(),+ rank: 0,+ passages,+ added: Some("in a folder the question names"),+ });+ }+ }+ let mut order: Vec<Ranked> = Vec::new();+ let mut seen: BTreeSet<String> = BTreeSet::new();+ let mut push = |r: Ranked, order: &mut Vec<Ranked>| {+ if seen.insert(r.path.clone()) {+ order.push(r);+ }+ };+ let mut rest = ranked.into_iter();+ for r in rest.by_ref().take(ROUTE_AFTER) {+ push(r, &mut order);+ }+ for r in routed {+ push(r, &mut order);+ }+ let mut tail: Vec<Ranked> = rest.collect();+ // Definitions come after the first ranks, computed from the top files.+ let head_len = DEFINITIONS_AFTER.saturating_sub(order.len());+ let more: Vec<Ranked> = tail.drain(..head_len.min(tail.len())).collect();+ for r in more {+ push(r, &mut order);+ }+ let top: Vec<Ranked> = order.iter().take(DEFINITION_SOURCES * 2).cloned().collect();+ for file in definitions(corpus, &top) {+ push(+ Ranked {+ path: file,+ rank: 0,+ passages: Vec::new(),+ added: Some("defines what the top files use"),+ },+ &mut order,+ );+ }+ for r in tail {+ push(r, &mut order);+ }+ for (i, r) in order.iter_mut().enumerate() {+ r.rank = i + 1;+ }+ order+}++fn ranked_files(corpus: &Corpus<'_>) -> Vec<Ranked> {+ let mut order: Vec<Ranked> = Vec::new();+ let mut at: HashMap<&str, usize> = HashMap::new();+ for (path, a, b) in &corpus.ranking {+ if !corpus.files.contains_key(path) {+ continue;+ }+ let i = *at.entry(path.as_str()).or_insert_with(|| {+ order.push(Ranked {+ path: path.clone(),+ rank: order.len() + 1,+ passages: Vec::new(),+ added: None,+ });+ order.len() - 1+ });+ order[i].passages.push(((*a).max(1), (*b).max(*a).max(1)));+ }+ order+}++/// The question-independent view of a project: its folders as modules,+/// and the dependencies between them.+#[derive(Clone, Debug, Default)]+pub struct Modules {+ pub files: usize,+ pub tokens: usize,+ pub modules: Vec<Module>,+ /// (from, to, relations), most first.+ pub edges: Vec<(String, String, usize)>,+}++#[derive(Clone, Debug, Default)]+pub struct Module {+ pub path: String,+ pub files: usize,+ pub tokens: usize,+ pub language: String,+ pub purpose: String,+ pub key: Vec<String>,+ pub entries: Vec<String>,+}++/// Folders a summary splits the project into at most.+const MAX_MODULES: usize = 48;++fn folder_of(path: &str, depth: usize) -> String {+ let parts: Vec<&str> = path.split('/').collect();+ if parts.len() <= depth {+ // A file directly in the folder of depth - 1.+ return parts[..parts.len() - 1].join("/");+ }+ parts[..depth].join("/")+}++/// The modules of `files`: top-level folders, the largest split into their+/// subfolders while there are fewer than [`MAX_MODULES`].+fn partition(files: &BTreeMap<String, usize>) -> BTreeMap<String, Vec<String>> {+ // module prefix → (depth, files)+ let mut modules: BTreeMap<String, (usize, Vec<String>)> = BTreeMap::new();+ for path in files.keys() {+ let folder = folder_of(path, 1);+ modules+ .entry(folder)+ .or_insert((1, Vec::new()))+ .1+ .push(path.clone());+ }+ let tokens = |list: &[String]| -> usize { list.iter().map(|p| est_file(p, files[p])).sum() };+ let total: usize = files.iter().map(|(p, b)| est_file(p, *b)).sum();+ let mut sealed: BTreeSet<String> = BTreeSet::new();+ loop {+ if modules.len() >= MAX_MODULES {+ break;+ }+ let largest = modules+ .iter()+ .filter(|(prefix, _)| !sealed.contains(*prefix))+ .map(|(prefix, (_, list))| (tokens(list), prefix.clone()))+ .max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));+ let Some((size, prefix)) = largest else {+ break;+ };+ if size * 16 < total {+ break;+ }+ let (depth, list) = modules[&prefix].clone();+ let vendored = list+ .first()+ .is_some_and(|p| class(p) == crate::code_question::PathClass::Vendored);+ let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();+ for path in &list {+ children+ .entry(folder_of(path, depth + 1))+ .or_default()+ .push(path.clone());+ }+ if vendored || children.len() < 2 || modules.len() - 1 + children.len() > MAX_MODULES {+ sealed.insert(prefix);+ continue;+ }+ modules.remove(&prefix);+ for (child, list) in children {+ if child == prefix {+ // The files directly in the folder stay one module, sealed.+ sealed.insert(child.clone());+ }+ modules.insert(child, (depth + 1, list));+ }+ }+ modules.into_iter().map(|(k, (_, v))| (k, v)).collect()+}++/// The first line of prose in a README or a package comment.+fn purpose_of(text: &str) -> Option<String> {+ for line in text.lines().take(60) {+ let line = line.trim();+ let line = line+ .strip_prefix("//")+ .or_else(|| line.strip_prefix('#').filter(|_| false))+ .unwrap_or(line)+ .trim();+ if line.is_empty()+ || line.starts_with('#')+ || line.starts_with('[')+ || line.starts_with('!')+ || line.starts_with('<')+ || line.starts_with("```")+ || line.starts_with("+build")+ || line.starts_with("go:build")+ || line.starts_with("Copyright")+ || line.starts_with("SPDX")+ || line.starts_with('=')+ || line.starts_with('-')+ || line.starts_with("package ")+ || line.starts_with("/*")+ || line.starts_with('*')+ {+ continue;+ }+ let mut purpose: String = line.chars().take(140).collect();+ if purpose.len() < line.len() {+ purpose.push_str("...");+ }+ return Some(purpose);+ }+ None+}++const ENTRY_NAMES: &[&str] = &[+ "main.go",+ "main.py",+ "__main__.py",+ "main.rs",+ "lib.rs",+ "index.ts",+ "index.js",+ "app.py",+ "manage.py",+ "Main.java",+ "main.c",+ "main.cc",+ "main.cpp",+];++fn modules_of(corpus: &mut Corpus<'_>) -> Modules {+ let parts = partition(&corpus.files);+ let mut module_of: HashMap<&str, usize> = HashMap::new();+ let names: Vec<String> = parts.keys().cloned().collect();+ for (i, list) in parts.values().enumerate() {+ for path in list {+ module_of.insert(path.as_str(), i);+ }+ }+ let mut modules = Vec::new();+ let mut keys: Vec<Vec<(usize, usize)>> = vec![Vec::new(); parts.len()];+ if let Some(graph) = &corpus.graph {+ for symbol in &graph.symbols {+ if let Some(&m) = module_of.get(symbol.path.as_str()) {+ keys[m].push((symbol.degree, graph.by_node[&symbol.node]));+ }+ }+ }+ let mut edges: BTreeMap<(usize, usize), usize> = BTreeMap::new();+ let mut readmes = Vec::new();+ for (i, (prefix, list)) in parts.iter().enumerate() {+ let tokens: usize = list.iter().map(|p| est_file(p, corpus.files[p])).sum();+ let mut languages: BTreeMap<&'static str, usize> = BTreeMap::new();+ for path in list {+ let language = language(path);+ if !language.is_empty() && language != "markdown" {+ *languages.entry(language).or_default() += corpus.files[path];+ }+ }+ let language = languages+ .iter()+ .max_by(|a, b| a.1.cmp(b.1).then(b.0.cmp(a.0)))+ .map(|(l, _)| l.to_string())+ .unwrap_or_default();+ let mut key = std::mem::take(&mut keys[i]);+ key.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));+ let mut seen = BTreeSet::new();+ let mut key_names = Vec::new();+ let mut key_nodes = Vec::new();+ if let Some(graph) = &corpus.graph {+ for &(_, index) in &key {+ let symbol = &graph.symbols[index];+ if !short(&symbol.name).is_empty() && seen.insert(short(&symbol.name).to_string()) {+ key_names.push(short(&symbol.name).to_string());+ key_nodes.push(symbol.node);+ }+ if key_names.len() == 5 {+ break;+ }+ }+ for &node in key_nodes.iter().take(3) {+ for target in (graph.dependencies)(node).into_iter().take(MAX_EDGES_READ) {+ let Some(other) = graph.symbol_of(target) else {+ continue;+ };+ if let Some(&m) = module_of.get(other.path.as_str())+ && m != i+ {+ *edges.entry((i, m)).or_default() += 1;+ }+ }+ }+ }+ let entries: Vec<String> = list+ .iter()+ .filter(|p| {+ let name = p.rsplit('/').next().unwrap_or(p);+ ENTRY_NAMES.contains(&name)+ })+ .take(3)+ .cloned()+ .collect();+ let readme = ["README.md", "README", "README.rst", "doc.go"]+ .iter()+ .map(|name| {+ if prefix.is_empty() {+ name.to_string()+ } else {+ format!("{prefix}/{name}")+ }+ })+ .find(|p| corpus.files.contains_key(p));+ readmes.push(readme);+ modules.push(Module {+ path: if prefix.is_empty() {+ ".".into()+ } else {+ prefix.clone()+ },+ files: list.len(),+ tokens,+ language,+ purpose: String::new(),+ key: key_names,+ entries,+ });+ }+ for (module, readme) in modules.iter_mut().zip(readmes) {+ if let Some(path) = readme+ && let Some(text) = corpus.text(&path)+ {+ module.purpose = purpose_of(&text).unwrap_or_default();+ }+ }+ let mut edges: Vec<(String, String, usize)> = edges+ .into_iter()+ .map(|((a, b), n)| (names_or_dot(&names[a]), names_or_dot(&names[b]), n))+ .collect();+ edges.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)).then(a.1.cmp(&b.1)));+ Modules {+ files: corpus.files.len(),+ tokens: corpus.files.iter().map(|(p, b)| est_file(p, *b)).sum(),+ modules,+ edges,+ }+}++fn names_or_dot(name: &str) -> String {+ if name.is_empty() {+ ".".into()+ } else {+ name.into()+ }+}++/// The architecture section's text, within `room` tokens.+fn architecture_text(modules: &Modules, room: usize, counter: &Counter) -> String {+ let mut text = format!(+ "{} files, about {} tokens (estimated), in {} folders. Each line: folder, files, tokens, main language, purpose, key symbols by connections in the code graph, entry points.\n\n",+ modules.files,+ modules.tokens,+ modules.modules.len()+ );+ let cost = |t: &str| counter.count(t, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ if cost(&text) > room {+ return String::new();+ }+ let mut ordered: Vec<&Module> = modules.modules.iter().collect();+ ordered.sort_by(|a, b| b.tokens.cmp(&a.tokens).then(a.path.cmp(&b.path)));+ for module in ordered {+ let mut line = format!(+ "- {}/: {} files, ~{} tokens",+ module.path, module.files, module.tokens+ );+ if !module.language.is_empty() {+ line.push_str(&format!(", {}", module.language));+ }+ if !module.purpose.is_empty() {+ line.push_str(&format!(". {}", module.purpose));+ }+ if !module.key.is_empty() {+ line.push_str(&format!(" Key: {}.", module.key.join(", ")));+ }+ if !module.entries.is_empty() {+ line.push_str(&format!(" Entry: {}.", module.entries.join(", ")));+ }+ line.push('\n');+ let next = format!("{text}{line}");+ if cost(&next) > room {+ return text;+ }+ text = next;+ }+ if !modules.edges.is_empty() {+ let head = "\nDependencies between folders (edges from the key symbols, most first):\n";+ let next = format!("{text}{head}");+ if cost(&next) > room {+ return text;+ }+ text = next;+ for (from, to, n) in modules.edges.iter().take(60) {+ let next = format!("{text}- {from}/ -> {to}/ ({n})\n");+ if cost(&next) > room {+ return text;+ }+ text = next;+ }+ }+ text+}++/// The architecture cache: one entry per project and code-graph episode.+static ARCHITECTURE: Mutex<Option<(String, Arc<Modules>)>> = Mutex::new(None);++fn cached_modules(key: &str) -> Option<Arc<Modules>> {+ let held = ARCHITECTURE.lock().unwrap_or_else(PoisonError::into_inner);+ held.as_ref()+ .filter(|(k, _)| k == key)+ .map(|(_, m)| m.clone())+}++fn cache_modules(key: String, modules: Arc<Modules>) {+ *ARCHITECTURE.lock().unwrap_or_else(PoisonError::into_inner) = Some((key, modules));+}++/// A symbol's range in a file of `total` lines whose node starts are+/// `starts`: from its line to the line before the next start.+fn span(line: usize, starts: &[usize], total: usize) -> (usize, usize) {+ let next = starts+ .iter()+ .find(|&&s| s > line)+ .map_or(total, |&s| s.saturating_sub(1));+ (line, next.max(line).min(total.max(line)))+}++/// Lines of one excerpt at most; a longer symbol is cut around its passage,+/// with its first line kept.+const MAX_EXCERPT: usize = 300;+/// Lines kept on each side of a passage in a cut symbol.+const CONTEXT: usize = 40;+/// Budgets up to this spend breadth's share on compact excerpts of the+/// ranks past [`FULL_RANKS`], as far down the ranking as the budget goes.+const SMALL_BUDGET: usize = 256_000;+const FULL_RANKS: usize = 15;+/// The cache layout's question part gives full excerpts to one ranked file+/// per this many tokens of its room ([`Sizing::question_part`]).+const QUESTION_FULL_TOKENS: usize = 8_000;+/// A compactly excerpted file goes in whole at most this size.+const COMPACT_WHOLE: usize = 1_500;+/// Lines around a passage in a compact excerpt.+const COMPACT_CONTEXT: usize = 3;+/// Top-ranked files left out that the manifest lists at most.+const MANIFEST_OMITTED: usize = 100;++/// A file's excerpt ranges for its passages, best passage first, within+/// `cap` tokens (estimated from the lines' bytes at `rate`): each passage+/// widened to its symbols ([`excerpt_ranges`]), or with `compact` only a few+/// lines around it and the first line of each symbol it overlaps. The+/// first passage always goes in, cut to the cap.+fn capped_ranges(+ passages: &[(usize, usize)],+ symbols: &[Symbol],+ starts: &[usize],+ lines: &[&str],+ rate: f64,+ cap: usize,+ compact: bool,+) -> Vec<(usize, usize)> {+ let total = lines.len();+ let cost = |ranges: &[(usize, usize)]| -> usize {+ ranges+ .iter()+ .map(|&(a, b)| {+ let bytes: usize = lines[a - 1..b].iter().map(|l| l.len() + 1).sum();+ estimate::tokens(bytes, rate) + (b - a + 1)+ })+ .sum()+ };+ let mut kept: Vec<(usize, usize)> = Vec::new();+ for &(a, b) in passages {+ let (a, b) = (a.clamp(1, total.max(1)), b.clamp(1, total.max(1)));+ if total == 0 {+ break;+ }+ let pieces = if compact {+ let mut pieces = vec![(+ a.saturating_sub(COMPACT_CONTEXT).max(1),+ (b + COMPACT_CONTEXT).min(total),+ )];+ for symbol in symbols {+ let (s, e) = span(symbol.line, starts, total);+ if s <= b && e >= a && s <= total {+ pieces.push((s, s));+ }+ }+ pieces+ } else {+ excerpt_ranges(&[(a, b)], symbols, starts, total)+ };+ let mut next = kept.clone();+ next.extend(pieces);+ let next = merge(next);+ if cost(&next) <= cap {+ kept = next;+ } else if kept.is_empty() {+ // The first passage alone, cut to the cap.+ let mut end = a;+ while end < b && cost(&[(a, end + 1)]) <= cap {+ end += 1;+ }+ kept = vec![(a, end)];+ }+ }+ kept+}++/// The excerpt ranges of a large file for its passages: each passage widened+/// to the symbols it overlaps.+fn excerpt_ranges(+ passages: &[(usize, usize)],+ symbols: &[Symbol],+ starts: &[usize],+ total: usize,+) -> Vec<(usize, usize)> {+ let mut ranges = Vec::new();+ for &(a, b) in passages {+ let (a, b) = (a.min(total.max(1)), b.min(total.max(1)));+ let mut from = a;+ let mut to = b;+ let mut first = None;+ for symbol in symbols {+ let (s, e) = span(symbol.line, starts, total);+ if s <= b && e >= a {+ from = from.min(s);+ to = to.max(e);+ first.get_or_insert(s);+ }+ }+ if to - from + 1 > MAX_EXCERPT {+ let cut = (a.saturating_sub(CONTEXT).max(from), (b + CONTEXT).min(to));+ if let Some(s) = first+ && s < cut.0+ {+ ranges.push((s, s));+ }+ ranges.push(cut);+ } else {+ ranges.push((from, to));+ }+ }+ merge(ranges)+}++/// The names of the symbols that start in `a..=b`, most connected first.+fn names_in(symbols: &[Symbol], a: usize, b: usize) -> Vec<String> {+ let mut inside: Vec<&Symbol> = symbols+ .iter()+ .filter(|s| s.line >= a && s.line <= b)+ .collect();+ inside.sort_by(|x, y| y.degree.cmp(&x.degree).then(x.line.cmp(&y.line)));+ let mut names = Vec::new();+ for symbol in inside {+ let name = short(&symbol.name).to_string();+ if !name.is_empty() && !names.contains(&name) {+ names.push(name);+ }+ if names.len() == 3 {+ break;+ }+ }+ names+}++fn defines(names: &[String]) -> String {+ if names.is_empty() {+ String::new()+ } else {+ format!(", defines {}", names.join(", "))+ }+}++/// Test file names that go with `path`, by language convention.+fn test_names(path: &str) -> Vec<String> {+ let (folder, name) = match path.rsplit_once('/') {+ Some((folder, name)) => (format!("{folder}/"), name),+ None => (String::new(), path),+ };+ let Some((stem, ext)) = name.rsplit_once('.') else {+ return Vec::new();+ };+ match ext {+ "go" => vec![format!("{folder}{stem}_test.go")],+ "py" => vec![+ format!("{folder}test_{stem}.py"),+ format!("{folder}{stem}_test.py"),+ format!("{folder}tests/test_{stem}.py"),+ ],+ "ts" | "tsx" | "js" | "jsx" => vec![+ format!("{folder}{stem}.test.{ext}"),+ format!("{folder}{stem}.spec.{ext}"),+ format!("{folder}__tests__/{stem}.test.{ext}"),+ ],+ "rs" => vec![format!("{folder}tests.rs"), format!("tests/{stem}.rs")],+ "java" => vec![format!(+ "{}{stem}Test.java",+ folder.replace("/main/", "/test/")+ )],+ _ => Vec::new(),+ }+}++fn is_test(path: &str) -> bool {+ class(path) == crate::code_question::PathClass::Test+}++/// Relations a test's reference to a symbol travels.+const REFERENCES: &[&str] = &[+ "calls",+ "references",+ "uses",+ "inherits",+ "implements",+ "extends",+];++/// Build the pack of `corpus` for `options`, as the JSON format without+/// `seconds`.+pub fn build(corpus: &mut Corpus<'_>, options: &Options, counter: &Counter) -> Result<Value> {+ match options.layout {+ Layout::Standard => build_standard(corpus, options, counter),+ Layout::Cache => build_cache(corpus, options, counter),+ }+}++/// The cost of each section's opening and closing chunks, counted as the+/// two chunks they are.+fn frames(style: Style, counter: &Counter) -> BTreeMap<Section, usize> {+ let cost = |text: &str| {+ if text.is_empty() {+ 0+ } else {+ counter.count(text, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0)+ }+ };+ Section::ALL+ .into_iter()+ .map(|section| {+ (+ section,+ cost(§ion_open(style, section)) + cost(§ion_close(style)),+ )+ })+ .collect()+}++/// What the question's sections are sized by: the budget they share.+struct Sizing {+ budget: usize,+ /// At small budgets the ranks past [`FULL_RANKS`] get compact excerpts+ /// (their passages and the first lines of the symbols around them), and+ /// breadth fills by rank only.+ small: bool,+ /// The most one focus file takes.+ per_file: usize,+ /// A focus file goes in whole up to this size.+ whole_limit: usize,+ /// The ranks that get full excerpts at small budgets; the ranks past+ /// them get compact ones.+ full_ranks: usize,+}++impl Sizing {+ fn new(budget: usize, overview: bool) -> Self {+ let small = budget <= SMALL_BUDGET && !overview;+ Self {+ budget,+ small,+ per_file: (budget / if small { 10 } else { 8 }).max(2_000),+ whole_limit: (budget / 16).clamp(1_500, 16_000),+ full_ranks: FULL_RANKS,+ }+ }++ /// The cache layout's question part, sized by its `room`: full excerpts+ /// for one ranked file per [`QUESTION_FULL_TOKENS`] of the room (3 to+ /// [`FULL_RANKS`]), together at most two fifths of it, and compact ones+ /// past them, so that a small question part still reaches far down the+ /// ranking.+ fn question_part(room: usize) -> Self {+ let mut sizing = Self::new(room, false);+ sizing.full_ranks = (room / QUESTION_FULL_TOKENS).clamp(3, FULL_RANKS);+ sizing.per_file = (room * 2 / 5 / sizing.full_ranks).max(2_000);+ sizing+ }++ fn share(&self, part: f64) -> usize {+ ((self.budget as f64) * part) as usize+ }+}++/// The ranked files for the question: none without one.+fn question_ranking(corpus: &mut Corpus<'_>, options: &Options) -> Vec<Ranked> {+ if options.question.is_empty() {+ Vec::new()+ } else {+ let base = ranked_files(corpus);+ augment(corpus, &ranking_question(&options.question), base)+ }+}++static HEADING: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r"^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$").unwrap());+/// A heading's parenthesized note, as in "Container runtime (CRI) and+/// version (if applicable)".+static HEADING_NOTE: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r"\([^()]*\)").unwrap());+/// A short heading that labels the environment, read in lower case without+/// its notes and punctuation: the system information, the environment, a+/// `<name> version` or the tested versions, the cloud provider, install+/// tools, the container runtime, related plugins, the operating system,+/// hardware or the type of installation, or several of them ("Container+/// runtime and version").+static ENVIRONMENT_LABEL: LazyLock<regex::Regex> = LazyLock::new(|| {+ let label = concat!(+ r"(?:system (?:information|info|details)",+ r"|(?:[\w+/-]+ )?environment(?: (?:information|info|details))?",+ r"|(?:[\w+/-]+ ){0,3}versions?",+ r"|versions? (?:affected|used|tested|info|information|details)",+ r"|cloud provider|install tools|container runtime|related plugins",+ r"|operating system|os|hardware|type of installation)"+ );+ regex::Regex::new(&format!(r"^{label}(?:(?: and | & |, ?| ?/ ?){label})*$")).unwrap()+});+/// An issue form's question for the environment, as a heading in lower+/// case: "What version of Home Assistant Core has the issue?", "Please+/// provide the environment you discovered this bug in". It must also name+/// an `ENVIRONMENT_WORD`.+static ENVIRONMENT_QUESTION: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"^(?:what|which)\b.*\?$|\bplease (?:provide|specify|share|list|include)\b")+ .unwrap()+});+/// A word that names the environment, for `ENVIRONMENT_QUESTION`.+static ENVIRONMENT_WORD: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(+ r"\b(?:versions?|environment|operating system|os|type of installation|installation type)\b",+ )+ .unwrap()+});+/// Words that make a short heading or a version line a sentence, not a+/// label: "Broken in the new version", "In the new version: it fails".+const SENTENCE_WORDS: [&str; 14] = [+ "in", "on", "at", "to", "from", "after", "since", "with", "for", "by", "before", "when", "is",+ "not",+];++/// Whether a markdown heading opens an environment section: a short label+/// (five words or fewer without its parenthesized notes) such as "System+/// information", "Tested versions", "Godot version", "OS" or "Container+/// runtime (CRI) and version (if applicable)", or an issue form's question+/// for the environment. A heading that merely names a version ("Upgrade to+/// version 2 breaks login") does not, and a level-1 heading never does: it+/// is the issue's title.+fn environment_heading(level: usize, heading: &str) -> bool {+ if level < 2 {+ return false;+ }+ let heading = heading.to_lowercase();+ let label: String = HEADING_NOTE+ .replace_all(&heading, " ")+ .chars()+ .map(|c| {+ if c.is_alphanumeric() || "+/-&,".contains(c) {+ c+ } else {+ ' '+ }+ })+ .collect();+ let label = label.split_whitespace().collect::<Vec<_>>().join(" ");+ let label = label.trim_matches(|c: char| " ,-&/".contains(c));+ let words = || label.split(' ').filter(|word| !word.is_empty());+ if words().count() <= 5+ && ENVIRONMENT_LABEL.is_match(label)+ && !words().any(|word| SENTENCE_WORDS.contains(&word))+ {+ return true;+ }+ let asked = heading.replace(['*', '`'], "");+ let asked = asked.trim();+ ENVIRONMENT_QUESTION.is_match(asked) && ENVIRONMENT_WORD.is_match(asked)+}++/// A `<label> version: <value>` line: at most three words of a label at the+/// start of the line, the word version or versions (or "version affected",+/// ...) and a colon, with a list marker and emphasis around the label+/// allowed. Group 1 is the label's words.+static VERSION_LINE: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(concat!(+ r"(?i)^[ \t]*(?:[-*+][ \t]+)?(?:\*\*|__|\*|_)?((?:[A-Za-z0-9./+_-]+[ \t]+){0,3})",+ r"versions?(?:[ \t]+(?:affected|used|tested|info|information|details))?",+ r"[ \t]*(?:\*\*|__|\*|_)?[ \t]*:"+ ))+ .unwrap()+});++/// Whether a line is a `<label> version: <value>` line ("- VS Code Version:+/// 1.95", "**Godot version:** 4.2"), not prose ("Version check fails: ...",+/// "In the new version: ...") or code (`def version(self):`).+fn version_line(line: &str) -> bool {+ VERSION_LINE.captures(line).is_some_and(|line| {+ !line[1]+ .split_whitespace()+ .any(|word| SENTENCE_WORDS.contains(&word.to_lowercase().as_str()))+ })+}++/// The question as the ranking reads it: an issue without its environment+/// sections (a heading below the title that labels the system information,+/// the tested versions or a `<name> version`, the environment, the cloud+/// provider, install tools, the container runtime, related plugins, the+/// operating system, hardware or the type of installation, see+/// `environment_heading`, down to the next heading of its level) and+/// without its `<name> version:` lines. They say where the reporter ran the+/// program, not what the code does, and their words (graphics drivers,+/// display servers, package versions) pull unrelated files up. A level-1+/// heading (the title, or a `# comment` line of a code block) never opens+/// an environment section. A question without environment sections or+/// version lines is returned as it is.+fn ranking_question(question: &str) -> std::borrow::Cow<'_, str> {+ let mut kept: Vec<&str> = Vec::new();+ let mut skipping: Option<usize> = None;+ let mut changed = false;+ for line in question.split('\n') {+ // A line read without its `\r` (Windows line ends), kept as it is.+ let read = line.strip_suffix('\r').unwrap_or(line);+ if let Some(heading) = HEADING.captures(read) {+ let level = heading[1].len();+ if skipping.is_some_and(|at| level <= at) {+ skipping = None;+ }+ if skipping.is_none() && environment_heading(level, &heading[2]) {+ skipping = Some(level);+ changed = true;+ continue;+ }+ }+ if skipping.is_some() || version_line(read) {+ changed = true;+ continue;+ }+ kept.push(line);+ }+ if changed {+ let kept = kept.join("\n");+ if kept.trim().is_empty() {+ // Every line was in an environment section or a version line:+ // rank on the question as written.+ return std::borrow::Cow::Borrowed(question);+ }+ std::borrow::Cow::Owned(kept)+ } else {+ std::borrow::Cow::Borrowed(question)+ }+}++/// The top ranked code files (the tests and READMEs that go with them).+fn top_code_of(ranked: &[Ranked]) -> Vec<Ranked> {+ ranked+ .iter()+ .filter(|r| class(&r.path) != crate::code_question::PathClass::Doc)+ .take(10)+ .cloned()+ .collect()+}++/// The focus symbols: those the top ranked code files' passages overlap+/// (the call paths and tests start from them, whatever the focus section+/// holds).+fn focus_symbols_of(corpus: &mut Corpus<'_>, ranked: &[Ranked]) -> Vec<usize> {+ let mut focus_symbols: Vec<usize> = Vec::new();+ if corpus.graph.is_some() {+ for file in ranked+ .iter()+ .filter(|r| class(&r.path) != crate::code_question::PathClass::Doc)+ {+ if focus_symbols.len() >= MAX_FOCUS_SYMBOLS {+ break;+ }+ let Some(text) = corpus.text(&file.path) else {+ continue;+ };+ let total = text.lines().count();+ let Some(graph) = corpus.graph.as_ref() else {+ break;+ };+ let starts = graph.starts(&file.path);+ for symbol in graph.symbols(&file.path) {+ let (s, e) = span(symbol.line, &starts, total);+ if file.passages.iter().any(|&(a, b)| s <= b && e >= a)+ && !short(&symbol.name).is_empty()+ && !focus_symbols.contains(&symbol.node)+ && focus_symbols.len() < MAX_FOCUS_SYMBOLS+ {+ focus_symbols.push(symbol.node);+ }+ }+ }+ }+ focus_symbols+}++/// The architecture section within `cap`.+fn add_architecture(fill: &mut Fill<'_>, corpus: &mut Corpus<'_>, cap: usize) {+ let counter = fill.counter;+ let room = fill.room(Section::Architecture, cap);+ let modules = match corpus.modules.clone() {+ Some(modules) => modules,+ None => {+ let built = Arc::new(modules_of(corpus));+ corpus.modules = Some(built.clone());+ built+ }+ };+ let body = architecture_text(&modules, room, counter);+ if !body.is_empty() {+ let tokens = counter.count(&body, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ fill.add(+ Section::Architecture,+ cap,+ Chunk {+ path: None,+ start: 0,+ end: 0,+ whole: false,+ why: "architecture".into(),+ text: body,+ tokens,+ order: usize::MAX,+ },+ None,+ );+ }+}++/// The sum of the connections of each file's symbols in the code graph.+fn centrality_of(corpus: &Corpus<'_>) -> HashMap<String, usize> {+ match &corpus.graph {+ Some(graph) => {+ let mut sums: HashMap<String, usize> = HashMap::new();+ for (path, &(from, to)) in &graph.by_path {+ sums.insert(+ path.clone(),+ graph.symbols[from..to].iter().map(|s| s.degree).sum(),+ );+ }+ sums+ }+ None => HashMap::new(),+ }+}++fn build_standard(corpus: &mut Corpus<'_>, options: &Options, counter: &Counter) -> Result<Value> {+ let budget = options.budget;+ let limit = budget - ((budget as f64) * counter.margin()).ceil() as usize;+ let mut fill = Fill::new(+ options,+ counter,+ limit,+ frames(options.style, counter),+ options.on(Section::Manifest),+ );+ let overview = options.question.is_empty();+ let ranked = question_ranking(corpus, options);+ let rank_of: HashMap<String, usize> = ranked.iter().map(|r| (r.path.clone(), r.rank)).collect();+ // The header's room, from its text at the largest numbers.+ let header_reserve = counter.count(+ &header_text(corpus, options, counter, budget, &rank_of),+ estimate::PACK_TEXT_BYTES_PER_TOKEN,+ 0,+ 0,+ ) + fill.frame[&Section::Header]+ + 8;+ fill.used += header_reserve;+ // The manifest's frame, title line and left-out list.+ let omitted_reserve = if options.on(Section::Manifest) {+ let lines = (budget / 600).clamp(3, MANIFEST_OMITTED);+ fill.frame[&Section::Manifest] + 40 + lines * 24+ } else {+ 0+ };+ fill.used += omitted_reserve;+ if fill.used > limit {+ return Err(Error::bad(format!(+ "The budget of {budget} tokens leaves no room after the header"+ )));+ }+ let sizing = Sizing::new(budget, overview);+ let share = |part: f64| sizing.share(part);++ // Architecture.+ if options.on(Section::Architecture) {+ add_architecture(&mut fill, corpus, share(if overview { 0.20 } else { 0.04 }));+ }++ let top_code = top_code_of(&ranked);+ let focus_symbols = focus_symbols_of(corpus, &ranked);++ // Focus.+ if options.on(Section::Focus) && !ranked.is_empty() {+ let reserved: usize = [+ (Section::Paths, 0.10),+ (Section::Tests, 0.10),+ (Section::Docs, 0.05),+ ]+ .iter()+ .filter(|(s, _)| options.on(*s))+ .map(|(_, p)| share(*p))+ .sum();+ let left = limit.saturating_sub(fill.used);+ let cap = left.saturating_sub(reserved).max(share(0.5).min(left));+ fill_focus(&mut fill, corpus, &ranked, cap, &sizing, None);+ }++ // Call paths.+ if options.on(Section::Paths) && !focus_symbols.is_empty() && corpus.graph.is_some() {+ fill_paths(&mut fill, corpus, &focus_symbols, &rank_of, share(0.10));+ }++ // Tests.+ if options.on(Section::Tests) && !ranked.is_empty() {+ fill_tests(+ &mut fill,+ corpus,+ &focus_symbols,+ &top_code,+ &rank_of,+ share(0.10),+ sizing.whole_limit,+ );+ }++ // Docs.+ if options.on(Section::Docs) && !ranked.is_empty() {+ let cap = share(0.05);+ for file in &ranked {+ if class(&file.path) != crate::code_question::PathClass::Doc {+ continue;+ }+ if fill.room(Section::Docs, cap) < 64 {+ break;+ }+ let Some(text) = corpus.text(&file.path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ let ranges: Vec<(usize, usize)> = file+ .passages+ .iter()+ .map(|&(a, b)| (a, b.min(a + 119)))+ .collect();+ let rank = file.rank;+ let why = move |_: usize, _: usize| format!("docs: rank {rank}");+ fill.add_ranges(+ Section::Docs,+ cap,+ &file.path,+ &lines,+ &ranges,+ &why,+ Some(rank),+ usize::MAX,+ );+ }+ // The nearest README of the top ranked code files.+ let tops: Vec<String> = top_code.iter().take(3).map(|r| r.path.clone()).collect();+ let mut seen = BTreeSet::new();+ for top in tops {+ let mut folder = top.rsplit_once('/').map(|(f, _)| f.to_string());+ while let Some(current) = folder {+ let candidate = format!("{current}/README.md");+ if corpus.files.contains_key(&candidate) {+ if seen.insert(candidate.clone())+ && fill.room(Section::Docs, cap) >= 64+ && let Some(text) = corpus.text(&candidate)+ {+ let lines: Vec<&str> = text.lines().collect();+ let why = format!("docs: README of {current}/");+ let why = move |_: usize, _: usize| why.clone();+ let end = lines.len().min(80);+ let rank = rank_of.get(&candidate).copied();+ fill.add_ranges(+ Section::Docs,+ cap,+ &candidate,+ &lines,+ &[(1, end)],+ &why,+ rank,+ usize::MAX,+ );+ }+ break;+ }+ folder = current.rsplit_once('/').map(|(f, _)| f.to_string());+ }+ }+ }++ // Breadth.+ if options.on(Section::Breadth) {+ let small = sizing.small;+ let centrality = centrality_of(corpus);+ let mut candidates: Vec<(String, String)> = Vec::new(); // (path, why)+ let mut queued: BTreeSet<String> = BTreeSet::new();+ for file in &ranked {+ if queued.insert(file.path.clone()) {+ candidates.push((file.path.clone(), format!("breadth: rank {}", file.rank)));+ }+ }+ // Small budgets fill by rank only; larger ones then take the top+ // files' folders and the rest of the project by centrality.+ let mut folders: Vec<String> = Vec::new();+ for file in ranked.iter().take(if small { 0 } else { 10 }) {+ let folder = file+ .path+ .rsplit_once('/')+ .map_or("", |(f, _)| f)+ .to_string();+ if !folders.contains(&folder) {+ folders.push(folder);+ }+ }+ let by_centrality = |paths: &mut Vec<&String>| {+ paths.sort_by(|a, b| {+ let ca = centrality.get(a.as_str()).copied().unwrap_or(0);+ let cb = centrality.get(b.as_str()).copied().unwrap_or(0);+ cb.cmp(&ca).then(a.cmp(b))+ });+ };+ for folder in &folders {+ let mut near: Vec<&String> = corpus+ .files+ .keys()+ .filter(|p| p.rsplit_once('/').map_or("", |(f, _)| f) == folder.as_str())+ .filter(|p| is_code(p) && !is_test(p) && !generated(p))+ .collect();+ by_centrality(&mut near);+ for path in near {+ if queued.insert(path.clone()) {+ let shown = if folder.is_empty() {+ "."+ } else {+ folder.as_str()+ };+ candidates.push((+ path.clone(),+ format!("breadth: same folder as the focus ({shown}/)"),+ ));+ }+ }+ }+ let mut rest: Vec<&String> = corpus+ .files+ .keys()+ .filter(|p| {+ !small+ && is_code(p)+ && !generated(p)+ && matches!(class(p), crate::code_question::PathClass::Source)+ })+ .collect();+ by_centrality(&mut rest);+ for path in rest {+ if queued.insert(path.clone()) {+ let c = centrality.get(path.as_str()).copied().unwrap_or(0);+ candidates.push((path.clone(), format!("breadth: centrality {c}")));+ }+ }+ fill_breadth(+ &mut fill,+ corpus,+ candidates,+ &rank_of,+ sizing.whole_limit * 2,+ );+ }++ finish(+ corpus,+ options,+ counter,+ fill,+ &ranked,+ &rank_of,+ header_reserve,+ )+}++/// The focus section within `cap`: the ranked code files, small ones whole,+/// large ones as excerpts of their passages' symbols. A file that+/// `in_prefix` holds whole (the cache layout's repository part, by path+/// with its line count) is not repeated: the section's first chunk refers+/// to it.+fn fill_focus(+ fill: &mut Fill<'_>,+ corpus: &mut Corpus<'_>,+ ranked: &[Ranked],+ cap: usize,+ sizing: &Sizing,+ in_prefix: Option<&BTreeMap<String, usize>>,+) {+ let (small, per_file, whole_limit) = (sizing.small, sizing.per_file, sizing.whole_limit);+ let full_ranks = sizing.full_ranks;+ let mut references = References::default();+ let mut misses = 0;+ for file in ranked {+ if class(&file.path) == crate::code_question::PathClass::Doc {+ continue;+ }+ if fill.room(Section::Focus, cap) < 64 || misses >= 40 {+ break;+ }+ if let Some(&lines) = in_prefix.and_then(|held| held.get(&file.path)) {+ references.note(fill, cap, &file.path, lines, file.rank);+ continue;+ }+ let Some(text) = corpus.text(&file.path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ if lines.is_empty() || minified(text.len(), lines.len()) {+ continue;+ }+ let total = lines.len();+ let symbols: Vec<Symbol> = corpus+ .graph+ .as_ref()+ .map(|g| g.symbols(&file.path).to_vec())+ .unwrap_or_default();+ let starts = corpus+ .graph+ .as_ref()+ .map(|g| g.starts(&file.path))+ .unwrap_or_default();+ let rank = file.rank;+ let path = file.path.clone();+ let est = est_file(&file.path, text.len());+ let compact = small && rank > full_ranks;+ let note = file.added.map_or(String::new(), |why| format!(" ({why})"));+ let whole_cap = if compact { COMPACT_WHOLE } else { whole_limit };+ let mut added = 0;+ if est <= whole_cap.min(per_file) {+ let names = names_in(&symbols, 1, total);+ let note = note.clone();+ let why =+ move |_: usize, _: usize| format!("focus: rank {rank}{note}{}", defines(&names));+ added = fill.add_ranges(+ Section::Focus,+ cap,+ &path,+ &lines,+ &[(1, total)],+ &why,+ Some(rank),+ usize::MAX,+ );+ }+ if added == 0 {+ // A file the ranking added has no passages: its head.+ let passages = if file.passages.is_empty() {+ vec![(1, total.min(60))]+ } else {+ file.passages.clone()+ };+ let ranges = capped_ranges(+ &passages,+ &symbols,+ &starts,+ &lines,+ rate_of(&path),+ per_file,+ compact,+ );+ let symbols_ref = &symbols;+ let why = move |a: usize, b: usize| {+ format!(+ "focus: rank {rank}{note}{}",+ defines(&names_in(symbols_ref, a, b))+ )+ };+ added = fill.add_ranges(+ Section::Focus,+ cap,+ &path,+ &lines,+ &ranges,+ &why,+ Some(rank),+ usize::MAX,+ );+ if added == 0 {+ // The bare passages, when their symbols do not fit.+ added = fill.add_ranges(+ Section::Focus,+ cap,+ &path,+ &lines,+ &passages,+ &why,+ Some(rank),+ usize::MAX,+ );+ }+ }+ if added == 0 {+ misses += 1;+ } else {+ misses = 0;+ }+ }+ references.finish(fill, cap);+}++/// References at most, in the focus section, to ranked files the+/// repository part holds whole.+const MAX_REFERENCES: usize = 60;+const REFERENCES_HEAD: &str =+ "Ranked files the repository part already holds whole (not repeated here):\n";++/// The focus section's references to the repository part, charged against+/// the budget as they are noted and added as one chunk at the end.+#[derive(Default)]+struct References {+ lines: Vec<String>,+ charged: usize,+}++impl References {+ fn note(&mut self, fill: &mut Fill<'_>, cap: usize, path: &str, lines: usize, rank: usize) {+ if self.lines.len() >= MAX_REFERENCES {+ return;+ }+ let line = format!("- in the prefix: {path} lines 1-{lines} (rank {rank})\n");+ let count = |text: &str| {+ fill.counter+ .count(text, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0)+ };+ let mut cost = count(&line);+ if self.lines.is_empty() {+ // The head line and the blank line after the list.+ cost += count(REFERENCES_HEAD) + 1;+ }+ if cost > fill.room(Section::Focus, cap) {+ return;+ }+ fill.used += cost;+ *fill.spent.entry(Section::Focus).or_default() += cost;+ self.charged += cost;+ self.lines.push(line);+ }++ fn finish(self, fill: &mut Fill<'_>, cap: usize) {+ if self.lines.is_empty() {+ return;+ }+ fill.used -= self.charged;+ *fill.spent.entry(Section::Focus).or_default() -= self.charged;+ let text = format!("{REFERENCES_HEAD}{}\n", self.lines.concat());+ let tokens = fill+ .counter+ .count(&text, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ fill.add(+ Section::Focus,+ cap,+ Chunk {+ path: None,+ start: 0,+ end: 0,+ whole: false,+ why: "in the prefix".into(),+ text,+ tokens,+ order: 0,+ },+ None,+ );+ }+}++/// The call paths section within `cap`: the lines, then the bodies of the+/// key hops not already in the pack.+fn fill_paths(+ fill: &mut Fill<'_>,+ corpus: &mut Corpus<'_>,+ focus_symbols: &[usize],+ rank_of: &HashMap<String, usize>,+ cap: usize,+) {+ let counter = fill.counter;+ let (lines, hops) = call_paths(corpus.graph.as_ref().unwrap(), focus_symbols, rank_of);+ if lines.is_empty() {+ return;+ }+ let mut body = String::from(+ "Callers and callees of the focus symbols along call edges, two steps at most: a (path:line) -> b (path:line).\n\n",+ );+ let cost = |t: &str| counter.count(t, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ let room = fill.room(Section::Paths, cap);+ let mut kept = 0;+ for line in &lines {+ let next = format!("{body}{line}\n");+ if cost(&next) > room / 2 {+ break;+ }+ body = next;+ kept += 1;+ }+ if kept == 0 {+ return;+ }+ body.push('\n');+ let tokens = cost(&body);+ fill.add(+ Section::Paths,+ cap,+ Chunk {+ path: None,+ start: 0,+ end: 0,+ whole: false,+ why: "call paths".into(),+ text: body,+ tokens,+ order: 0,+ },+ None,+ );+ // The bodies of the key hops not already in the pack.+ for (node, why) in hops {+ if fill.room(Section::Paths, cap) < 64 {+ break;+ }+ let Some(symbol) = corpus.graph.as_ref().unwrap().symbol_of(node).cloned() else {+ continue;+ };+ let Some(text) = corpus.text(&symbol.path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ let starts = corpus.graph.as_ref().unwrap().starts(&symbol.path);+ let (a, b) = span(symbol.line, &starts, lines.len());+ let (a, b) = (a, b.min(a + MAX_EXCERPT - 1));+ let rank = rank_of.get(&symbol.path).copied();+ let why = move |_: usize, _: usize| why.clone();+ fill.add_ranges(+ Section::Paths,+ cap,+ &symbol.path,+ &lines,+ &[(a, b)],+ &why,+ rank,+ usize::MAX,+ );+ }+}++/// The tests section within `cap`: tests that reach the focus symbols in+/// the code graph, then the test files named after the top code files.+#[allow(clippy::too_many_arguments)]+fn fill_tests(+ fill: &mut Fill<'_>,+ corpus: &mut Corpus<'_>,+ focus_symbols: &[usize],+ top_code: &[Ranked],+ rank_of: &HashMap<String, usize>,+ cap: usize,+ whole_limit: usize,+) {+ let mut tests: Vec<(usize, Vec<String>)> = Vec::new(); // (node, focus names)+ if let Some(graph) = &corpus.graph {+ let mut by_test: BTreeMap<usize, Vec<String>> = BTreeMap::new();+ for &focus in focus_symbols {+ let Some(target) = graph.symbol_of(focus) else {+ continue;+ };+ for edge in graph.edges(focus).iter() {+ if !edge.incoming || !REFERENCES.contains(&edge.relation.as_str()) {+ continue;+ }+ if let Some(test) = graph.symbol_of(edge.other)+ && is_test(&test.path)+ {+ let names = by_test.entry(edge.other).or_default();+ let name = short(&target.name).to_string();+ if !names.contains(&name) {+ names.push(name);+ }+ }+ }+ }+ tests = by_test.into_iter().collect();+ tests.sort_by(|a, b| {+ let (sa, sb) = (graph.symbol_of(a.0).unwrap(), graph.symbol_of(b.0).unwrap());+ b.1.len()+ .cmp(&a.1.len())+ .then((sa.path.as_str(), sa.line).cmp(&(sb.path.as_str(), sb.line)))+ });+ }+ for (node, names) in tests {+ if fill.room(Section::Tests, cap) < 64 {+ break;+ }+ let Some(symbol) = corpus.graph.as_ref().unwrap().symbol_of(node).cloned() else {+ continue;+ };+ let Some(text) = corpus.text(&symbol.path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ let starts = corpus.graph.as_ref().unwrap().starts(&symbol.path);+ let (a, b) = span(symbol.line, &starts, lines.len());+ let (a, b) = (a, b.min(a + MAX_EXCERPT - 1));+ let rank = rank_of.get(&symbol.path).copied();+ let why = format!("test of {}", names.join(", "));+ let why = move |_: usize, _: usize| why.clone();+ fill.add_ranges(+ Section::Tests,+ cap,+ &symbol.path,+ &lines,+ &[(a, b)],+ &why,+ rank,+ usize::MAX,+ );+ }+ // By name: the test files that go with the top ranked code files.+ for file in top_code {+ if fill.room(Section::Tests, cap) < 64 {+ break;+ }+ for candidate in test_names(&file.path) {+ if !corpus.files.contains_key(&candidate) || !fill.covered(&candidate).is_empty() {+ continue;+ }+ let Some(text) = corpus.text(&candidate) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ if lines.is_empty() {+ continue;+ }+ let est = est_file(&candidate, text.len());+ let names: Vec<String> = corpus+ .graph+ .as_ref()+ .map(|g| {+ g.symbols(&file.path)+ .iter()+ .map(|s| s.name.rsplit('.').next().unwrap_or(&s.name).to_string())+ .collect()+ })+ .unwrap_or_default();+ let ranges: Vec<(usize, usize)> = if est <= whole_limit / 2 {+ vec![(1, lines.len())]+ } else if let Some(graph) = &corpus.graph {+ let starts = graph.starts(&candidate);+ graph+ .symbols(&candidate)+ .iter()+ .filter(|t| {+ names+ .iter()+ .any(|n| n.len() > 2 && t.name.contains(n.as_str()))+ })+ .map(|t| {+ let (a, b) = span(t.line, &starts, lines.len());+ (a, b.min(a + MAX_EXCERPT - 1))+ })+ .collect()+ } else {+ Vec::new()+ };+ if ranges.is_empty() {+ continue;+ }+ let why = format!("test of {} (by file name)", file.path);+ let why = move |_: usize, _: usize| why.clone();+ let rank = rank_of.get(&candidate).copied();+ fill.add_ranges(+ Section::Tests,+ cap,+ &candidate,+ &lines,+ &ranges,+ &why,+ rank,+ usize::MAX,+ );+ }+ }+}++/// Breadth: `candidates` (path, why) in order, each whole when it is at+/// most `breadth_whole` tokens and fits, else an outline (the first line of+/// each symbol), until the budget is spent.+fn fill_breadth(+ fill: &mut Fill<'_>,+ corpus: &mut Corpus<'_>,+ candidates: Vec<(String, String)>,+ rank_of: &HashMap<String, usize>,+ breadth_whole: usize,+) {+ let cap = fill.limit;+ let mut misses = 0;+ for (path, why) in candidates {+ let room = fill.room(Section::Breadth, cap);+ if room < 48 || misses >= 400 {+ break;+ }+ if !fill.covered(&path).is_empty() {+ continue;+ }+ let bytes = corpus.files[&path];+ let est = est_file(&path, bytes);+ let outline_only = est > breadth_whole || est > room;+ if outline_only+ && corpus+ .graph+ .as_ref()+ .is_none_or(|g| g.symbols(&path).is_empty())+ {+ misses += 1;+ continue;+ }+ let Some(text) = corpus.text(&path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ if lines.is_empty() || minified(text.len(), lines.len()) {+ continue;+ }+ let rank = rank_of.get(&path).copied();+ let added = if outline_only {+ let graph = corpus.graph.as_ref().unwrap();+ let ranges: Vec<(usize, usize)> = graph+ .symbols(&path)+ .iter()+ .map(|s| (s.line, s.line))+ .collect();+ let reason = format!("{why} (outline: the first line of each symbol)");+ let ranges = merge_exact(ranges);+ let piece_ranges: Vec<(usize, usize)> = ranges+ .into_iter()+ .map(|(a, b)| (a.min(lines.len()), b.min(lines.len())))+ .filter(|&(a, b)| a >= 1 && a <= b)+ .collect();+ outline(fill, &path, &lines, &piece_ranges, &reason, rank)+ } else {+ let reason = why.clone();+ let f = move |_: usize, _: usize| reason.clone();+ fill.add_ranges(+ Section::Breadth,+ cap,+ &path,+ &lines,+ &[(1, lines.len())],+ &f,+ rank,+ usize::MAX,+ ) > 0+ };+ if added {+ misses = 0;+ } else {+ misses += 1;+ }+ }+}++/// The cache layout's repository part: its sections with their chunks+/// (opening and closing ones included), its text and tokens, and what it+/// holds.+struct Prefix {+ sections: Vec<(Section, Vec<Chunk>)>,+ text: String,+ tokens: usize,+ /// The sum of its chunks' tokens.+ sum: usize,+ files: BTreeMap<String, Included>,+ /// The files it holds whole, with their line counts.+ whole: BTreeMap<String, usize>,+ /// The lines it holds by file, outlines left out: the question part+ /// does not repeat them.+ held: HashMap<String, Vec<(usize, usize)>>,+}++/// The repository part's sections, in their order.+const PREFIX_SECTIONS: [Section; 5] = [+ Section::Header,+ Section::Architecture,+ Section::Map,+ Section::Breadth,+ Section::Docs,+];+/// Lines of each top document the repository part takes at most.+const TOP_DOC_LINES: usize = 200;++/// The share as a person reads it: 0.9 is 90, 0.925 is 92.5.+fn percent(share: f64) -> String {+ format!("{}", (share * 1000.0).round() / 10.0)+}++/// The cache layout: the repository part, the same bytes for every+/// question at this commit, budget and settings, then the question part.+fn build_cache(corpus: &mut Corpus<'_>, options: &Options, counter: &Counter) -> Result<Value> {+ let budget = options.budget;+ let frame = frames(options.style, counter);+ let prefix = repository_part(corpus, options, counter, &frame)?;+ let ranked = question_ranking(corpus, options);+ let rank_of: HashMap<String, usize> = ranked.iter().map(|r| (r.path.clone(), r.rank)).collect();+ let limit = budget - ((budget as f64) * counter.margin()).ceil() as usize;+ // The question part takes what the repository part leaves.+ let room = budget.saturating_sub(prefix.tokens);+ let question_part = options.prefix_share < 1.0 && !options.question.is_empty();+ let mut fill = Fill::new(+ options,+ counter,+ limit.saturating_sub(prefix.tokens),+ frame,+ question_part && options.on(Section::Manifest),+ );+ fill.covered = prefix.held.clone();+ if question_part {+ if fill.manifest {+ let lines = (room / 600).clamp(3, MANIFEST_OMITTED);+ fill.used += fill.frame[&Section::Manifest] + 60 + lines * 24;+ }+ let sizing = Sizing::question_part(room);+ let top_code = top_code_of(&ranked);+ let focus_symbols = focus_symbols_of(corpus, &ranked);+ if options.on(Section::Focus) && !ranked.is_empty() {+ let reserved: usize = [(Section::Paths, 0.10), (Section::Tests, 0.10)]+ .iter()+ .filter(|(s, _)| options.on(*s))+ .map(|(_, p)| sizing.share(*p))+ .sum();+ let left = fill.limit.saturating_sub(fill.used);+ let cap = left+ .saturating_sub(reserved)+ .max(sizing.share(0.5).min(left));+ fill_focus(+ &mut fill,+ corpus,+ &ranked,+ cap,+ &sizing,+ Some(&prefix.whole),+ );+ }+ if options.on(Section::Paths) && !focus_symbols.is_empty() && corpus.graph.is_some() {+ fill_paths(+ &mut fill,+ corpus,+ &focus_symbols,+ &rank_of,+ sizing.share(0.10),+ );+ }+ if options.on(Section::Tests) && !ranked.is_empty() {+ fill_tests(+ &mut fill,+ corpus,+ &focus_symbols,+ &top_code,+ &rank_of,+ sizing.share(0.10),+ sizing.whole_limit,+ );+ }+ }+ finish_cache(+ corpus, options, counter, fill, &prefix, &ranked, &rank_of, room,+ )+}++/// Each step down from a fixed `prefix_budget` whose share does not fit+/// the budget keeps this much of the last ([`prefix_basis`]).+const BASIS_STEP: f64 = 0.8;++/// The budget the cache layout's repository part is sized from. A call+/// whose budget moves with calibration names a fixed `prefix_budget`: the+/// part is sized from it when its share fits in the budget, else from the+/// first of its steps down by [`BASIS_STEP`] (0.8, 0.64, ... of it) whose+/// share fits. The basis then moves only when the budget crosses a step, so+/// the repository part stays the same bytes from call to call. Without a+/// `prefix_budget`, or below [`MIN_BUDGET`], the budget itself.+fn prefix_basis(options: &Options) -> usize {+ let Some(mut basis) = options.prefix_budget else {+ return options.budget;+ };+ let fits = |basis: usize| ((basis as f64) * options.prefix_share) as usize <= options.budget;+ while !fits(basis) {+ basis = ((basis as f64) * BASIS_STEP) as usize;+ if basis < MIN_BUDGET {+ return options.budget;+ }+ }+ basis+}++/// The repository part: header, architecture, the folder map, the top+/// documentation, then breadth by centrality, within the prefix share of+/// the budget it is sized from ([`prefix_basis`]); nothing in it depends on+/// the question.+fn repository_part(+ corpus: &mut Corpus<'_>,+ options: &Options,+ counter: &Counter,+ frame: &BTreeMap<Section, usize>,+) -> Result<Prefix> {+ let budget = prefix_basis(options);+ let size = ((budget as f64) * options.prefix_share).floor() as usize;+ let limit = size.saturating_sub(((size as f64) * counter.margin()).ceil() as usize);+ let mut fill = Fill::new(options, counter, limit, frame.clone(), false);+ let header = text_chunk(+ "header",+ cache_header_text(corpus, options, counter),+ counter,+ );+ fill.used += header.tokens + fill.frame[&Section::Header];+ if fill.used > limit {+ return Err(Error::bad(format!(+ "The budget of {budget} tokens at a prefix share of {} leaves no room after the header",+ options.prefix_share+ )));+ }+ let share = |part: f64| ((budget as f64) * part) as usize;+ if options.on(Section::Architecture) {+ add_architecture(&mut fill, corpus, share(0.04));+ }+ if options.on(Section::Map) {+ let cap = share(0.03);+ let room = fill.room(Section::Map, cap);+ let body = map_text(corpus, room, counter);+ if !body.is_empty() {+ let tokens = counter.count(&body, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ fill.add(+ Section::Map,+ cap,+ Chunk {+ path: None,+ start: 0,+ end: 0,+ whole: false,+ why: "map".into(),+ text: body,+ tokens,+ order: usize::MAX,+ },+ None,+ );+ }+ }+ if options.on(Section::Docs) {+ let cap = share(0.03);+ for (path, why) in top_docs(corpus) {+ if fill.room(Section::Docs, cap) < 64 {+ break;+ }+ let Some(text) = corpus.text(&path) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ if lines.is_empty() {+ continue;+ }+ let end = lines.len().min(TOP_DOC_LINES);+ let why = move |_: usize, _: usize| why.to_string();+ fill.add_ranges(+ Section::Docs,+ cap,+ &path,+ &lines,+ &[(1, end)],+ &why,+ None,+ usize::MAX,+ );+ }+ }+ if options.on(Section::Breadth) {+ let centrality = centrality_of(corpus);+ let mut rest: Vec<&String> = corpus+ .files+ .keys()+ .filter(|p| {+ is_code(p)+ && !generated(p)+ && matches!(class(p), crate::code_question::PathClass::Source)+ })+ .collect();+ rest.sort_by(|a, b| {+ let ca = centrality.get(a.as_str()).copied().unwrap_or(0);+ let cb = centrality.get(b.as_str()).copied().unwrap_or(0);+ cb.cmp(&ca).then(a.cmp(b))+ });+ let candidates: Vec<(String, String)> = rest+ .into_iter()+ .map(|path| {+ let c = centrality.get(path.as_str()).copied().unwrap_or(0);+ (path.clone(), format!("breadth: centrality {c}"))+ })+ .collect();+ let whole_limit = (budget / 16).clamp(1_500, 16_000);+ fill_breadth(+ &mut fill,+ corpus,+ candidates,+ &HashMap::new(),+ whole_limit * 2,+ );+ }+ loop {+ let mut sections: Vec<(Section, Vec<Chunk>)> = Vec::new();+ for section in PREFIX_SECTIONS {+ let mut chunks: Vec<Chunk> = match section {+ Section::Header => vec![header.clone()],+ _ => match fill.sections.get(§ion) {+ Some(chunks) => layout(chunks, options.order),+ None => continue,+ },+ };+ let open = section_open(options.style, section);+ if !open.is_empty() {+ chunks.insert(0, text_chunk("section", open, counter));+ }+ let close = section_close(options.style);+ if !close.is_empty() {+ chunks.push(text_chunk("section", close, counter));+ }+ sections.push((section, chunks));+ }+ let text: String = sections+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.text.as_str()))+ .collect();+ let sum: usize = sections+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.tokens))+ .sum();+ let tokens = counter.total(&text, sum);+ if tokens > size {+ let drop_order = [+ Section::Breadth,+ Section::Docs,+ Section::Map,+ Section::Architecture,+ ];+ if drop_order.iter().any(|&s| fill.pop(s)) {+ continue;+ }+ return Err(Error::bad(format!(+ "The budget of {budget} tokens at a prefix share of {} leaves no room after the header",+ options.prefix_share+ )));+ }+ let mut whole = BTreeMap::new();+ let mut held: HashMap<String, Vec<(usize, usize)>> = HashMap::new();+ for (section, chunks) in §ions {+ for chunk in chunks {+ let Some(path) = &chunk.path else {+ continue;+ };+ if chunk.whole {+ whole.insert(path.clone(), chunk.end);+ }+ if chunk.whole || *section == Section::Docs {+ held.entry(path.clone())+ .or_default()+ .push((chunk.start, chunk.end));+ }+ }+ }+ for ranges in held.values_mut() {+ *ranges = merge_exact(std::mem::take(ranges));+ }+ return Ok(Prefix {+ sections,+ text,+ tokens,+ sum,+ files: fill.files,+ whole,+ held,+ });+ }+}++/// The repository part's header: no question, time or count that changes+/// with the question.+fn cache_header_text(corpus: &Corpus<'_>, options: &Options, counter: &Counter) -> String {+ let counted = counter.counted();+ let part = if options.prefix_share >= 1.0 {+ "This pack is one repository part, the same text for every question about this commit with these settings; only the question after it changes.".to_string()+ } else {+ format!(+ "This pack starts with a repository part, the same text for every question about this commit with these settings (at most {}% of the budget), then a question part chosen for the question after the pack.",+ percent(options.prefix_share)+ )+ };+ let order = match options.order {+ Order::RelevantLast => {+ "relevant-last: in the question part, the most relevant code at the end"+ }+ Order::RelevantFirst => {+ "relevant-first: in the question part, the most relevant code first"+ }+ };+ let numbers = match options.numbers {+ Numbers::Focus => "Focus code lines start with their line number and a tab. ",+ Numbers::All => "Code lines start with their line number and a tab. ",+ Numbers::None => "",+ };+ let body = format!(+ "Repository: {} at commit {}\nTokens: {counted}.\n{part}\nThe repository part holds the architecture summary, a map of the folders, the files with the most connections in the code graph (whole, or the first line of each symbol) and the top documentation.\nOrder: {order}.\n{numbers}Each file chunk names its path, line range and why it is here. Cite code as path:line.\n",+ corpus.project,+ corpus.commit.as_deref().unwrap_or("unknown")+ );+ match options.style {+ Style::Markdown => format!("# Code pack: {}\n\n{body}\n", corpus.project),+ Style::Xml => body,+ }+}++/// The repository's README and its architecture or design documents,+/// shallowest first, each with why it is here.+fn top_docs(corpus: &Corpus<'_>) -> Vec<(String, &'static str)> {+ let mut docs: Vec<(String, &'static str)> = Vec::new();+ if let Some(readme) = [+ "README.md",+ "README.rst",+ "README.txt",+ "README",+ "readme.md",+ ]+ .iter()+ .find(|name| corpus.files.contains_key(**name))+ {+ docs.push((readme.to_string(), "docs: the repository's README"));+ }+ let mut others: Vec<&String> = corpus+ .files+ .keys()+ .filter(|path| {+ let name = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();+ let text = [".md", ".rst", ".adoc", ".txt"]+ .iter()+ .any(|ext| name.ends_with(ext));+ text && path.matches('/').count() <= 2+ && class(path) != crate::code_question::PathClass::Vendored+ && (name.contains("architecture")+ || name.starts_with("design")+ || name.starts_with("overview"))+ })+ .collect();+ others.sort_by(|a, b| (a.matches('/').count(), *a).cmp(&(b.matches('/').count(), *b)));+ for path in others.into_iter().take(4) {+ docs.push((path.clone(), "docs: architecture"));+ }+ docs+}++/// The repository map within `room`: every folder that holds files (other+/// than vendored ones), with its files, their estimated tokens and its most+/// connected symbols, in path order; when they do not all fit, the most+/// connected and largest folders.+fn map_text(corpus: &Corpus<'_>, room: usize, counter: &Counter) -> String {+ #[derive(Default)]+ struct Folder {+ files: usize,+ tokens: usize,+ degree: usize,+ /// (degree, symbol index) of its symbols.+ symbols: Vec<(usize, usize)>,+ }+ let folder_of = |path: &str| -> String {+ path.rsplit_once('/')+ .map_or(String::new(), |(f, _)| f.to_string())+ };+ let mut folders: BTreeMap<String, Folder> = BTreeMap::new();+ let mut vendored = (0usize, 0usize, 0usize); // folders, files, tokens+ let mut vendored_folders: BTreeSet<String> = BTreeSet::new();+ for (path, &bytes) in &corpus.files {+ let folder = folder_of(path);+ if class(path) == crate::code_question::PathClass::Vendored {+ vendored.1 += 1;+ vendored.2 += est_file(path, bytes);+ vendored_folders.insert(folder);+ continue;+ }+ let entry = folders.entry(folder).or_default();+ entry.files += 1;+ entry.tokens += est_file(path, bytes);+ }+ vendored.0 = vendored_folders.len();+ if let Some(graph) = &corpus.graph {+ for (i, symbol) in graph.symbols.iter().enumerate() {+ if short(&symbol.name).is_empty() {+ continue;+ }+ if let Some(entry) = folders.get_mut(&folder_of(&symbol.path)) {+ entry.degree += symbol.degree;+ entry.symbols.push((symbol.degree, i));+ }+ }+ }+ let line_of = |folder: &str, entry: &Folder| -> String {+ let shown = if folder.is_empty() { "." } else { folder };+ let files = if entry.files == 1 { "file" } else { "files" };+ let mut line = format!(+ "- {shown}/: {} {files}, ~{} tokens",+ entry.files, entry.tokens+ );+ if let Some(graph) = &corpus.graph {+ let mut best = entry.symbols.clone();+ best.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));+ let mut names: Vec<&str> = Vec::new();+ for (_, i) in best {+ let name = short(&graph.symbols[i].name);+ if !names.contains(&name) {+ names.push(name);+ }+ if names.len() == 3 {+ break;+ }+ }+ if !names.is_empty() {+ line.push_str(&format!(". Key: {}", names.join(", ")));+ }+ }+ line.push_str(".\n");+ line+ };+ let cost = |text: &str| counter.count(text, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ let lines: Vec<(&String, String)> = folders+ .iter()+ .map(|(folder, entry)| (folder, line_of(folder, entry)))+ .collect();+ let tail = if vendored.1 > 0 {+ format!(+ "Vendored code, not listed: {} folders, {} files, ~{} tokens.\n",+ vendored.0, vendored.1, vendored.2+ )+ } else {+ String::new()+ };+ let head = |shown: usize| -> String {+ if shown == lines.len() {+ format!(+ "{} folders that hold files, in path order. Each line: the folder, the files directly in it, their tokens (estimated) and its most connected symbols in the code graph.\n\n",+ lines.len()+ )+ } else {+ format!(+ "{shown} of the {} folders that hold files (the most connected and largest), in path order. Each line: the folder, the files directly in it, their tokens (estimated) and its most connected symbols in the code graph.\n\n",+ lines.len()+ )+ }+ };+ // The folders by weight: connections, then tokens, then path.+ let mut by_weight: Vec<usize> = (0..lines.len()).collect();+ by_weight.sort_by(|&a, &b| {+ let (fa, fb) = (&folders[lines[a].0], &folders[lines[b].0]);+ (fb.degree, fb.tokens)+ .cmp(&(fa.degree, fa.tokens))+ .then(lines[a].0.cmp(lines[b].0))+ });+ let fixed = cost(&head(lines.len())) + cost(&tail) + 1;+ let mut chosen: Vec<usize> = Vec::new();+ let mut spent = fixed;+ for &i in &by_weight {+ let c = cost(&lines[i].1);+ if spent + c > room {+ break;+ }+ spent += c;+ chosen.push(i);+ }+ loop {+ if chosen.is_empty() {+ return String::new();+ }+ let mut shown = chosen.clone();+ shown.sort_unstable();+ let mut text = head(shown.len());+ for &i in &shown {+ text.push_str(&lines[i].1);+ }+ text.push_str(&tail);+ text.push('\n');+ if cost(&text) <= room {+ return text;+ }+ // An exact count over the whole text: drop the lightest tenth.+ let keep = chosen.len() - chosen.len().div_ceil(10);+ chosen.truncate(keep);+ }+}++/// The cache layout's manifest: the question part's files, how many the+/// repository part holds, and the top ranked files left out of both.+fn cache_manifest(+ corpus: &Corpus<'_>,+ fill: &Fill<'_>,+ prefix: &Prefix,+ ranked: &[Ranked],+ room: usize,+) -> String {+ let mut included: Vec<(&String, &Included)> = fill.files.iter().collect();+ included.sort_by(|a, b| {+ (a.1.rank.unwrap_or(usize::MAX), a.0).cmp(&(b.1.rank.unwrap_or(usize::MAX), b.0))+ });+ let mut text = format!(+ "The question part starts here: {} files (tokens each, the section of their first chunk, and their rank in the retrieval where ranked). The repository part above holds {} files.\n",+ included.len(),+ prefix.files.len()+ );+ for (path, entry) in &included {+ text.push_str(&manifest_line(+ path,+ entry.tokens,+ entry.rank,+ entry.section,+ ));+ }+ let lines = (room / 600).clamp(3, MANIFEST_OMITTED);+ let omitted: Vec<String> = ranked+ .iter()+ .filter(|f| !fill.files.contains_key(&f.path) && !prefix.files.contains_key(&f.path))+ .take(lines)+ .map(|f| {+ format!(+ "- {}: ~{} tokens, rank {}\n",+ f.path,+ est_file(&f.path, corpus.files[&f.path]),+ f.rank+ )+ })+ .collect();+ if !omitted.is_empty() {+ text.push_str("Top ranked files left out (estimated tokens, rank):\n");+ for line in omitted {+ text.push_str(&line);+ }+ }+ text.push('\n');+ text+}++/// The cache layout's question part assembled after the repository part,+/// within the budget, and the pack's JSON.+#[allow(clippy::too_many_arguments)]+fn finish_cache(+ corpus: &Corpus<'_>,+ options: &Options,+ counter: &Counter,+ mut fill: Fill<'_>,+ prefix: &Prefix,+ ranked: &[Ranked],+ rank_of: &HashMap<String, usize>,+ room: usize,+) -> Result<Value> {+ let style = options.style;+ let order = match options.order {+ Order::RelevantLast => [+ Section::Manifest,+ Section::Tests,+ Section::Paths,+ Section::Focus,+ ],+ Order::RelevantFirst => [+ Section::Manifest,+ Section::Focus,+ Section::Paths,+ Section::Tests,+ ],+ };+ let mut with_manifest = fill.manifest;+ loop {+ let manifest = with_manifest.then(|| cache_manifest(corpus, &fill, prefix, ranked, room));+ let mut suffix: Vec<(Section, Vec<Chunk>)> = Vec::new();+ for section in order {+ let mut chunks: Vec<Chunk> = match section {+ Section::Manifest => match &manifest {+ Some(text) => vec![text_chunk("manifest", text.clone(), counter)],+ None => continue,+ },+ _ => match fill.sections.get(§ion) {+ Some(chunks) => layout(chunks, options.order),+ None => continue,+ },+ };+ let open = section_open(style, section);+ if !open.is_empty() {+ chunks.insert(0, text_chunk("section", open, counter));+ }+ let close = section_close(style);+ if !close.is_empty() {+ chunks.push(text_chunk("section", close, counter));+ }+ suffix.push((section, chunks));+ }+ let suffix_text: String = suffix+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.text.as_str()))+ .collect();+ let suffix_sum: usize = suffix+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.tokens))+ .sum();+ let total = if suffix.is_empty() {+ prefix.tokens+ } else {+ counter.total(+ &format!("{}{suffix_text}", prefix.text),+ prefix.sum + suffix_sum,+ )+ };+ if total > options.budget {+ if [Section::Tests, Section::Paths, Section::Focus]+ .iter()+ .any(|&s| fill.pop(s))+ {+ continue;+ }+ if with_manifest {+ with_manifest = false;+ continue;+ }+ return Err(Error::bad(format!(+ "The budget of {} tokens leaves no room after the repository part",+ options.budget+ )));+ }+ let mut tokens_of: BTreeMap<&String, usize> = BTreeMap::new();+ for (path, entry) in prefix.files.iter().chain(fill.files.iter()) {+ *tokens_of.entry(path).or_default() += entry.tokens;+ }+ let mut included: Vec<(&String, usize, Option<usize>)> = tokens_of+ .into_iter()+ .map(|(path, tokens)| (path, tokens, rank_of.get(path.as_str()).copied()))+ .collect();+ included.sort_by(|a, b| {+ (a.2.unwrap_or(usize::MAX), a.0).cmp(&(b.2.unwrap_or(usize::MAX), b.0))+ });+ let omitted: Vec<Value> = ranked+ .iter()+ .filter(|r| !prefix.files.contains_key(&r.path) && !fill.files.contains_key(&r.path))+ .take(50)+ .map(|r| json!({"path":r.path,"rank":r.rank,"tokens":est_file(&r.path, corpus.files[&r.path])}))+ .collect();+ let sections: Vec<Value> = prefix+ .sections+ .iter()+ .map(|s| (s, "prefix"))+ .chain(suffix.iter().map(|s| (s, "suffix")))+ .map(|((section, chunks), part)| {+ json!({+ "name": section.name(),+ "part": part,+ "tokens": chunks.iter().map(|c| c.tokens).sum::<usize>(),+ "chunks": chunks.iter().map(Chunk::json).collect::<Vec<_>>(),+ })+ })+ .collect();+ return Ok(json!({+ "format": FORMAT,+ "project": corpus.project,+ "commit": corpus.commit,+ "question": options.question,+ "budget": options.budget,+ "tokens": total,+ "tokenizer": counter.name(),+ "order": options.order.name(),+ "layout": Layout::Cache.name(),+ "prefix_share": options.prefix_share,+ "prefix_tokens": prefix.tokens,+ "prefix_sha256": sha256_hex(&prefix.text),+ "sections": sections,+ "included": included.iter().map(|(path, tokens, rank)| json!({"path":path,"tokens":tokens,"rank":rank})).collect::<Vec<_>>(),+ "omitted": omitted,+ }));+ }+}++/// The SHA-256 of `text`'s bytes, in hex.+pub fn sha256_hex(text: &str) -> String {+ use sha2::Digest;+ sha2::Sha256::digest(text.as_bytes())+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect()+}++/// Focus symbols the call paths and tests start from at most.+const MAX_FOCUS_SYMBOLS: usize = 16;++/// A minified or data file: lines of 300 bytes or more on average.+fn minified(bytes: usize, lines: usize) -> bool {+ lines > 0 && bytes / lines >= 300+}++/// An outline: one chunk of a file's symbol lines (not numbered unless all+/// chunks are), as one piece with gaps marked.+fn outline(+ fill: &mut Fill<'_>,+ path: &str,+ lines: &[&str],+ ranges: &[(usize, usize)],+ why: &str,+ rank: Option<usize>,+) -> bool {+ if ranges.is_empty() {+ return false;+ }+ let mut body = String::new();+ let mut prefix_bytes = 0;+ let mut prefix_tenths = 0;+ for &(a, b) in ranges {+ for n in a..=b {+ // Outlines always carry line numbers: their lines are apart.+ let prefix = format!("{n}\t");+ prefix_bytes += prefix.len();+ prefix_tenths += estimate::prefix_tenths(n);+ body.push_str(&prefix);+ body.push_str(lines[n - 1]);+ body.push('\n');+ }+ }+ let (start, end) = (ranges[0].0, ranges[ranges.len() - 1].1);+ let range = format!("{start}-{end}");+ let text = match fill.options.style {+ Style::Markdown => {+ let fence = fence(&body);+ format!(+ "### {path} lines {range} (outline)\nwhy: {why}\n{fence}{}\n{body}{fence}\n\n",+ language(path)+ )+ }+ Style::Xml => format!(+ "<file path=\"{}\" lines=\"{range}\" why=\"{}\">\n{body}</file>\n",+ attr(path),+ attr(why)+ ),+ };+ let tokens = fill.counter.count(+ &text,+ rate_of(path),+ prefix_bytes,+ prefix_tenths.div_ceil(10),+ );+ let chunk = Chunk {+ path: Some(path.to_string()),+ start,+ end,+ whole: false,+ why: why.to_string(),+ text,+ tokens,+ order: usize::MAX,+ };+ fill.add(Section::Breadth, fill.limit, chunk, rank)+}++/// The call paths of `focus` (lines) and the hops whose bodies matter+/// (node, why), most connected first.+fn call_paths(+ graph: &GraphView<'_>,+ focus: &[usize],+ rank_of: &HashMap<String, usize>,+) -> (Vec<String>, Vec<(usize, String)>) {+ let show = |node: usize| -> Option<String> {+ let s = graph.symbol_of(node)?;+ Some(format!("{} ({}:{})", short(&s.name), s.path, s.line))+ };+ let order = |nodes: &mut Vec<usize>| {+ nodes.sort_by(|&a, &b| {+ let key = |n: usize| {+ let s = graph.symbol_of(n);+ (+ s.and_then(|s| rank_of.get(&s.path).copied())+ .unwrap_or(usize::MAX),+ s.map_or("", |s| s.path.as_str()).to_string(),+ s.map_or(0, |s| s.line),+ )+ };+ key(a).cmp(&key(b))+ });+ nodes.dedup();+ };+ let neighbours = |node: usize, callers: bool| -> Vec<usize> {+ let mut found: Vec<usize> = graph+ .edges(node)+ .iter()+ .filter(|e| e.relation == "calls" && e.incoming == callers)+ .map(|e| e.other)+ // Tests have their own section; generated code is left out.+ .filter(|&n| {+ graph.symbol_of(n).is_some_and(|s| {+ !is_test(&s.path) && !generated(&s.path) && !short(&s.name).is_empty()+ })+ })+ .collect();+ order(&mut found);+ found+ };+ let mut lines: Vec<String> = Vec::new();+ let mut seen_lines: BTreeSet<String> = BTreeSet::new();+ let mut hops: Vec<(usize, String)> = Vec::new();+ let mut hop_count: HashMap<usize, usize> = HashMap::new();+ let mut push = |line: String, lines: &mut Vec<String>| {+ if seen_lines.insert(line.clone()) {+ lines.push(line);+ }+ };+ for &f in focus {+ let Some(fs) = show(f) else {+ continue;+ };+ let fname = short(&graph.symbol_of(f).unwrap().name).to_string();+ for c1 in neighbours(f, true).into_iter().take(5) {+ let Some(c1s) = show(c1) else { continue };+ let hub = graph.symbol_of(c1).is_some_and(|s| s.degree > 500);+ let c2s = if hub {+ Vec::new()+ } else {+ neighbours(c1, true)+ };+ if c2s.is_empty() {+ push(format!("- {c1s} -> {fs}"), &mut lines);+ }+ for c2 in c2s.into_iter().take(2) {+ if let Some(c2s) = show(c2) {+ push(format!("- {c2s} -> {c1s} -> {fs}"), &mut lines);+ }+ }+ if !focus.contains(&c1) {+ *hop_count.entry(c1).or_default() += 1;+ if !hops.iter().any(|(n, _)| *n == c1) {+ hops.push((c1, format!("caller of {fname}")));+ }+ }+ }+ for d1 in neighbours(f, false).into_iter().take(5) {+ let Some(d1s) = show(d1) else { continue };+ let hub = graph.symbol_of(d1).is_some_and(|s| s.degree > 500);+ let d2s = if hub {+ Vec::new()+ } else {+ neighbours(d1, false)+ };+ if d2s.is_empty() {+ push(format!("- {fs} -> {d1s}"), &mut lines);+ }+ for d2 in d2s.into_iter().take(2) {+ if let Some(d2s) = show(d2) {+ push(format!("- {fs} -> {d1s} -> {d2s}"), &mut lines);+ }+ }+ if !focus.contains(&d1) {+ *hop_count.entry(d1).or_default() += 1;+ if !hops.iter().any(|(n, _)| *n == d1) {+ hops.push((d1, format!("callee of {fname}")));+ }+ }+ }+ }+ // Most connected first; ties keep the order they were found in.+ let position: HashMap<usize, usize> =+ hops.iter().enumerate().map(|(i, (n, _))| (*n, i)).collect();+ hops.sort_by(|a, b| {+ hop_count[&b.0]+ .cmp(&hop_count[&a.0])+ .then(position[&a.0].cmp(&position[&b.0]))+ });+ (lines, hops)+}++fn header_text(+ corpus: &Corpus<'_>,+ options: &Options,+ counter: &Counter,+ tokens: usize,+ rank_of: &HashMap<String, usize>,+) -> String {+ let question = if options.question.is_empty() {+ "none (a whole-repository overview)".to_string()+ } else {+ let mut q: String = options.question.chars().take(300).collect();+ if q.len() < options.question.len() {+ q.push_str("...");+ }+ q.replace('\n', " ")+ };+ let counted = counter.counted();+ let chosen = if options.question.is_empty() {+ "no question: folders from the code graph and files by centrality".to_string()+ } else if rank_of.is_empty() {+ "the retrieval ranking found no files for the question; the rest by folder and centrality"+ .to_string()+ } else {+ "Graphicle's retrieval ranking for the question (passage index, identifier arm, code-graph arm); call paths and tests from the code graph; the rest by rank, folder and centrality".to_string()+ };+ let order = match options.order {+ Order::RelevantLast => {+ "relevant-last: least relevant first, the most relevant code at the end"+ }+ Order::RelevantFirst => "relevant-first: the most relevant code first",+ };+ let numbers = match options.numbers {+ Numbers::Focus => "Focus code lines start with their line number and a tab. ",+ Numbers::All => "Code lines start with their line number and a tab. ",+ Numbers::None => "",+ };+ let body = format!(+ "Repository: {} at commit {}\nQuestion: {question}\nBudget: {} tokens; this pack: {tokens} tokens, {counted}.\nChosen by: {chosen}.\nOrder: {order}.\n{numbers}Each file chunk names its path, line range and why it is here. Cite code as path:line.\n",+ corpus.project,+ corpus.commit.as_deref().unwrap_or("unknown"),+ options.budget+ );+ match options.style {+ Style::Markdown => format!("# Code pack: {}\n\n{body}\n", corpus.project),+ Style::Xml => body,+ }+}++fn finish(+ corpus: &Corpus<'_>,+ options: &Options,+ counter: &Counter,+ mut fill: Fill<'_>,+ ranked: &[Ranked],+ rank_of: &HashMap<String, usize>,+ header_reserve: usize,+) -> Result<Value> {+ let style = options.style;+ let drop_order = [+ Section::Breadth,+ Section::Docs,+ Section::Tests,+ Section::Paths,+ Section::Architecture,+ Section::Focus,+ ];+ loop {+ // The manifest from what is in.+ let manifest = if options.on(Section::Manifest) {+ let mut included: Vec<(&String, &Included)> = fill.files.iter().collect();+ included.sort_by(|a, b| {+ (a.1.rank.unwrap_or(usize::MAX), a.0).cmp(&(b.1.rank.unwrap_or(usize::MAX), b.0))+ });+ let mut text = format!(+ "{} files in this pack (tokens each, the section of their first chunk, and their rank in the retrieval where ranked):\n",+ included.len()+ );+ for (path, entry) in &included {+ text.push_str(&manifest_line(+ path,+ entry.tokens,+ entry.rank,+ entry.section,+ ));+ }+ let lines = (options.budget / 600).clamp(3, MANIFEST_OMITTED);+ let mut omitted: Vec<String> = Vec::new();+ for file in ranked {+ if omitted.len() == lines {+ break;+ }+ if !fill.files.contains_key(&file.path) {+ omitted.push(format!(+ "- {}: ~{} tokens, rank {}\n",+ file.path,+ est_file(&file.path, corpus.files[&file.path]),+ file.rank+ ));+ }+ }+ if !omitted.is_empty() {+ text.push_str("Top ranked files left out (estimated tokens, rank):\n");+ for line in omitted {+ text.push_str(&line);+ }+ }+ text.push('\n');+ Some(text)+ } else {+ None+ };+ let manifest_tokens = manifest.as_ref().map_or(0, |t| {+ counter.count(t, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0)+ });+ // Tokens without the header and manifest.+ let body_tokens: usize = fill+ .sections+ .iter()+ .map(|(section, chunks)| {+ fill.frame[section] + chunks.iter().map(|c| c.tokens).sum::<usize>()+ })+ .sum();+ let manifest_total = manifest+ .as_ref()+ .map_or(0, |_| fill.frame[&Section::Manifest] + manifest_tokens);+ // The header at its final numbers (its own tokens included).+ let mut header_tokens = header_reserve;+ let mut header = String::new();+ for _ in 0..3 {+ let total = body_tokens + manifest_total + header_tokens;+ header = header_text(corpus, options, counter, total, rank_of);+ let counted = counter.count(&header, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0)+ + fill.frame[&Section::Header];+ if counted == header_tokens {+ break;+ }+ header_tokens = counted;+ }+ // Assemble in order.+ let mut sections_out: Vec<(Section, Vec<Chunk>)> = Vec::new();+ for section in options.order.sections() {+ let mut chunks: Vec<Chunk> = match section {+ Section::Header => vec![text_chunk("header", header.clone(), counter)],+ Section::Manifest => match &manifest {+ Some(text) => vec![text_chunk("manifest", text.clone(), counter)],+ None => continue,+ },+ _ => match fill.sections.get(§ion) {+ Some(chunks) => layout(chunks, options.order),+ None => continue,+ },+ };+ let open = section_open(style, section);+ if !open.is_empty() {+ chunks.insert(0, text_chunk("section", open, counter));+ }+ let close = section_close(style);+ if !close.is_empty() {+ chunks.push(text_chunk("section", close, counter));+ }+ sections_out.push((section, chunks));+ }+ let text: String = sections_out+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.text.as_str()))+ .collect();+ let sum: usize = sections_out+ .iter()+ .flat_map(|(_, chunks)| chunks.iter().map(|c| c.tokens))+ .sum();+ let total = counter.total(&text, sum);+ if total > options.budget {+ if drop_order.iter().any(|&s| fill.pop(s)) {+ continue;+ }+ return Err(Error::bad(format!(+ "The budget of {} tokens leaves no room after the header",+ options.budget+ )));+ }+ let mut included: Vec<(&String, &Included)> = fill.files.iter().collect();+ included.sort_by(|a, b| {+ (a.1.rank.unwrap_or(usize::MAX), a.0).cmp(&(b.1.rank.unwrap_or(usize::MAX), b.0))+ });+ let omitted: Vec<Value> = ranked+ .iter()+ .filter(|r| !fill.files.contains_key(&r.path))+ .take(50)+ .map(|r| json!({"path":r.path,"rank":r.rank,"tokens":est_file(&r.path, corpus.files[&r.path])}))+ .collect();+ // The standard layout's prefix is its leading sections that do not+ // depend on the question. The header names the question, so a pack+ // for a question has none; an overview is all prefix.+ let overview = options.question.is_empty();+ let part = if overview { "prefix" } else { "suffix" };+ return Ok(json!({+ "format": FORMAT,+ "project": corpus.project,+ "commit": corpus.commit,+ "question": options.question,+ "budget": options.budget,+ "tokens": total,+ "tokenizer": counter.name(),+ "order": options.order.name(),+ "layout": Layout::Standard.name(),+ "prefix_tokens": if overview { total } else { 0 },+ "prefix_sha256": sha256_hex(if overview { text.as_str() } else { "" }),+ "sections": sections_out.iter().map(|(section, chunks)| json!({+ "name": section.name(),+ "part": part,+ "tokens": chunks.iter().map(|c| c.tokens).sum::<usize>(),+ "chunks": chunks.iter().map(Chunk::json).collect::<Vec<_>>(),+ })).collect::<Vec<_>>(),+ "included": included.iter().map(|(path, entry)| json!({"path":path,"tokens":entry.tokens,"rank":entry.rank})).collect::<Vec<_>>(),+ "omitted": omitted,+ }));+ }+}++fn text_chunk(why: &str, text: String, counter: &Counter) -> Chunk {+ let tokens = counter.count(&text, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0);+ Chunk {+ path: None,+ start: 0,+ end: 0,+ whole: false,+ why: why.into(),+ text,+ tokens,+ order: 0,+ }+}++/// A section's chunks in output order: by the order their files went in+/// (most relevant first, or last under relevant-last), each file's chunks+/// by line; text chunks first.+fn layout(chunks: &[Chunk], order: Order) -> Vec<Chunk> {+ // A file's place is its first chunk's.+ let mut first: HashMap<&str, usize> = HashMap::new();+ for chunk in chunks {+ if let Some(path) = &chunk.path {+ let entry = first.entry(path.as_str()).or_insert(chunk.order);+ *entry = (*entry).min(chunk.order);+ }+ }+ let mut out: Vec<Chunk> = chunks.to_vec();+ out.sort_by(|a, b| {+ let place = |c: &Chunk| -> (usize, usize, usize) {+ match &c.path {+ None => (0, c.order, 0),+ Some(path) => {+ let p = first[path.as_str()];+ let p = match order {+ Order::RelevantFirst => p,+ Order::RelevantLast => usize::MAX - p,+ };+ (1, p, c.start)+ }+ }+ };+ place(a).cmp(&place(b))+ });+ out+}++/// The text of a pack in the JSON format: its chunks' text in order.+pub fn text(pack: &Value) -> String {+ let mut out = String::new();+ for section in pack["sections"].as_array().into_iter().flatten() {+ for chunk in section["chunks"].as_array().into_iter().flatten() {+ out.push_str(chunk["text"].as_str().unwrap_or(""));+ }+ }+ out+}++/// The summary fields of a pack: the JSON format without its sections.+pub fn summary(pack: &Value) -> Value {+ let mut summary = pack.clone();+ if let Some(fields) = summary.as_object_mut() {+ fields.remove("sections");+ }+ summary+}++/// A git checkout's HEAD commit, read from its files.+pub fn git_head(folder: &Path) -> Option<String> {+ let mut git = folder.join(".git");+ if git.is_file() {+ let text = std::fs::read_to_string(&git).ok()?;+ let dir = text.trim().strip_prefix("gitdir:")?.trim().to_string();+ git = folder.join(dir);+ }+ let head = std::fs::read_to_string(git.join("HEAD")).ok()?;+ let head = head.trim();+ let sha = match head.strip_prefix("ref:") {+ None => head.to_string(),+ Some(name) => {+ let name = name.trim();+ let common = std::fs::read_to_string(git.join("commondir"))+ .ok()+ .map(|c| git.join(c.trim()))+ .unwrap_or_else(|| git.clone());+ match std::fs::read_to_string(git.join(name))+ .or_else(|_| std::fs::read_to_string(common.join(name)))+ {+ Ok(sha) => sha.trim().to_string(),+ Err(_) => {+ let packed = std::fs::read_to_string(common.join("packed-refs")).ok()?;+ packed+ .lines()+ .filter_map(|line| line.split_once(' '))+ .find(|(_, r)| *r == name)+ .map(|(sha, _)| sha.to_string())?+ }+ }+ }+ };+ let hex = sha.chars().all(|c| c.is_ascii_hexdigit());+ (hex && (sha.len() == 40 || sha.len() == 64)).then_some(sha)+}++impl Store {+ /// The pack of a project for `args` (`repository_id`, `question`,+ /// `budget`, `order`, `line_numbers`, `sections`, `style`, `tokenizer`,+ /// and `focus`, passages ranked ahead of the question's: [`pinned`]),+ /// in the JSON format.+ pub fn project_pack(&self, workspace: &str, token: &str, args: &Value) -> Result<Value> {+ let started = std::time::Instant::now();+ let options = Options::parse(args)?;+ let pinned = pinned(args)?;+ let counter = Counter::open(options.tokenizer.as_deref(), options.bytes_per_token)?;+ self.refresh_query_file(workspace, token, crate::string(args, "repository_id", 100)?)?;+ let mut pack = self.authorized_read(workspace, token, "read", |db, p| {+ let id = crate::string(args, "repository_id", 100)?;+ let repository = repo(db, p, id)?;+ let ranked = if options.question.is_empty() {+ Vec::new()+ } else {+ rank(db, p, &repository, &options.question)?+ };+ let ranking: Vec<(String, usize, usize)> =+ pinned.iter().cloned().chain(ranked).collect();+ let mut files = BTreeMap::new();+ for row in rows(+ db,+ "SELECT h.path,o.bytes FROM repo_heads h JOIN repo_objects o ON o.repository_id=h.repository_id AND o.sha256=h.sha256 WHERE h.repository_id=? ORDER BY h.path",+ [id],+ )? {+ files.insert(s(&row, "path").to_string(), row["bytes"].as_u64().unwrap_or(0) as usize);+ }+ let episode = crate::graph_projection::current_episode(db, id)?;+ let graph = crate::query_file::open(db, id, &episode).and_then(GraphView::of_query_file);+ let commit = crate::folders::current_folder(db, id)?.and_then(|folder| git_head(&folder));+ let mut statement = db.prepare(+ "SELECT o.content FROM repo_heads h JOIN repo_objects o ON o.repository_id=h.repository_id AND o.sha256=h.sha256 WHERE h.repository_id=?1 AND h.path=?2",+ )?;+ let fetch = move |path: &str| {+ statement+ .query_row(rusqlite::params![id, path], |row| row.get::<_, String>(0))+ .ok()+ };+ let name = s(&repository, "name").to_string();+ let key = format!("{id}:{episode}");+ let mut corpus = Corpus::new(name, commit, files, ranking, graph, Box::new(fetch));+ corpus.modules = cached_modules(&key);+ let pack = build(&mut corpus, &options, &counter)?;+ if let Some(modules) = corpus.modules.take() {+ cache_modules(key, modules);+ }+ Ok(pack)+ })?;+ pack["seconds"] = json!((started.elapsed().as_secs_f64() * 1000.0).round() / 1000.0);+ Ok(pack)+ }+}++impl Store {+ /// Write the project's query file once when this build has none+ /// ([`crate::query_graph::query_file_state`]: missing, or written by+ /// another build), so that this and later packs read it instead of the+ /// whole saved graph. Says so on standard error.+ fn refresh_query_file(&self, workspace: &str, token: &str, id: &str) -> Result<()> {+ let state = self.authorized_read(workspace, token, "read", |db, p| {+ let repository = repo(db, p, id)?;+ let episode = crate::graph_projection::current_episode(db, s(&repository, "id"))?;+ Ok(crate::query_graph::query_file_state(+ db,+ s(&repository, "id"),+ &episode,+ ))+ })?;+ if state["state"] != "missing" {+ return Ok(());+ }+ let saved = self.authorized_read(workspace, token, "read", |db, p| {+ let repository = repo(db, p, id)?;+ crate::query_graph::ensure(db, s(&repository, "id"), true)+ })?;+ if saved["status"] == "written" && saved["query_file"] == "written" {+ eprintln!(+ "graphicle: wrote the project's query file for this build ({} s); later packs read it",+ saved["seconds"]+ );+ }+ Ok(())+ }+}++/// The ranking's passages for `question`: `context`'s fused order.+fn rank(+ db: &rusqlite::Connection,+ p: &crate::store::Principal,+ repository: &Value,+ question: &str,+) -> Result<Vec<(String, usize, usize)>> {+ let question = ranking_question(question);+ let question = crate::code_question::shorten(&question)+ .map(|(q, _)| q)+ .unwrap_or_else(|| question.to_string());+ let mut args = json!({"repository_id":s(repository,"id"),"question":question,"max_tokens":1000,"max_chars":4000,"more_files":0});+ args[crate::query::PACK_RANKING] = json!(true);+ let (_, packet) = crate::query::project_packet(db, p, repository, &args, None, None)?;+ Ok(packet[crate::query::PACK_RANKING]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|row| {+ Some((+ row[0].as_str()?.to_string(),+ row[1].as_u64().unwrap_or(1) as usize,+ row[2].as_u64().or(row[1].as_u64()).unwrap_or(1) as usize,+ ))+ })+ .collect())+}++/// Passages a pack takes as its first ranked ones whatever the question+/// (`review` pins the changed hunks there, so that the focus is the changed+/// code, its call paths the changed symbols' callers and callees, and its+/// tests theirs): `focus` in a call's arguments, a list of objects with+/// `path`, `start_line` and `end_line`, at most [`MAX_PINNED`]. A path the+/// project does not hold is left out, as a ranked one is.+pub fn pinned(args: &Value) -> Result<Vec<(String, usize, usize)>> {+ let list = match args.get("focus") {+ None | Some(Value::Null) => return Ok(Vec::new()),+ Some(Value::Array(list)) if list.len() <= MAX_PINNED => list,+ Some(Value::Array(_)) => {+ return Err(Error::bad(format!(+ "focus holds at most {MAX_PINNED} passages"+ )));+ }+ Some(_) => return Err(Error::bad("focus must be a list of passages")),+ };+ let mut passages = Vec::with_capacity(list.len());+ for passage in list {+ let path = passage["path"]+ .as_str()+ .filter(|path| !path.is_empty() && path.len() <= 4096)+ .ok_or_else(|| Error::bad("each focus passage needs a path"))?;+ let line = |key: &str| {+ passage[key]+ .as_u64()+ .filter(|&n| n >= 1)+ .map(|n| n as usize)+ .ok_or_else(|| Error::bad(format!("each focus passage needs a {key} from 1")))+ };+ let (start, end) = (line("start_line")?, line("end_line")?);+ passages.push((path.to_string(), start.min(end), start.max(end)));+ }+ Ok(passages)+}++/// The most passages `focus` pins.+pub const MAX_PINNED: usize = 4_000;++/// The MCP tool's reply: the pack's markdown, and its summary as structured+/// content.+pub fn mcp_reply(pack: Value) -> Value {+ json!({"content":[{"type":"text","text":text(&pack)}],"structuredContent":summary(&pack),"isError":false})+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A project of `n` Go files in a few folders, each with symbols every+ /// 20 lines, calls between neighbours, and a test file for the first.+ type Project = (BTreeMap<String, String>, Vec<Symbol>, Vec<(usize, usize)>);++ fn project(n: usize) -> Project {+ let mut files = BTreeMap::new();+ let mut symbols = Vec::new();+ let mut calls = Vec::new();+ let mut node = 0;+ for i in 0..n {+ let folder = ["pkg/a", "pkg/b", "cmd/tool", "internal/c"][i % 4];+ let path = format!("{folder}/file{i}.go");+ let functions = 2 + (i % 7) * 6;+ let mut text = String::from("package x\n\n");+ for f in 0..functions {+ let line = text.lines().count() + 1;+ text.push_str(&format!("// F{i}x{f} does a thing.\nfunc F{i}x{f}() {{\n"));+ for k in 0..16 {+ text.push_str(&format!("\tvalue := compute{k}(\"word{i} widget{f}\")\n"));+ }+ text.push_str("}\n");+ symbols.push(Symbol {+ node,+ name: format!("x.F{i}x{f}"),+ path: path.clone(),+ line: line + 1,+ degree: (n - i) + f,+ });+ if node > 0 {+ calls.push((node - 1, node));+ }+ node += 1;+ }+ files.insert(path, text);+ }+ let test = "pkg/a/file0_test.go".to_string();+ let mut text = String::from("package x\n\n");+ text.push_str("func TestF0x0(t *testing.T) {\n\tF0x0()\n}\n");+ symbols.push(Symbol {+ node,+ name: "x.TestF0x0".into(),+ path: test.clone(),+ line: 3,+ degree: 1,+ });+ calls.push((node, 0));+ files.insert(test, text);+ files.insert(+ "pkg/a/README.md".into(),+ "# Package a\n\nPackage a computes widgets.\n".into(),+ );+ (files, symbols, calls)+ }++ fn corpus<'a>(+ files: &'a BTreeMap<String, String>,+ symbols: &[Symbol],+ calls: &'a [(usize, usize)],+ ranking: Vec<(String, usize, usize)>,+ ) -> Corpus<'a> {+ let sizes = files.iter().map(|(p, t)| (p.clone(), t.len())).collect();+ let edges: EdgesFn<'a> = Box::new(move |node| {+ let mut out = Vec::new();+ for &(a, b) in calls {+ if a == node {+ out.push(Edge {+ other: b,+ relation: "calls".into(),+ incoming: false,+ });+ }+ if b == node {+ out.push(Edge {+ other: a,+ relation: "calls".into(),+ incoming: true,+ });+ }+ }+ out+ });+ let deps: NodesFn<'a> = Box::new(move |node| {+ calls+ .iter()+ .filter(|(a, _)| *a == node)+ .map(|(_, b)| *b)+ .collect()+ });+ let starts: StartsFn<'a> = Box::new(|_: &str| Vec::new());+ let graph = GraphView::new(symbols.to_vec(), edges, deps, starts);+ Corpus::new(+ "demo".into(),+ Some("0123456789abcdef0123456789abcdef01234567".into()),+ sizes,+ ranking,+ Some(graph),+ Box::new(move |path: &str| files.get(path).cloned()),+ )+ }++ fn ranking() -> Vec<(String, usize, usize)> {+ vec![+ ("pkg/a/file4.go".into(), 30, 40),+ ("pkg/b/file1.go".into(), 3, 10),+ ("pkg/a/file4.go".into(), 200, 215),+ ("pkg/a/README.md".into(), 1, 3),+ ("cmd/tool/file2.go".into(), 5, 12),+ ("pkg/a/file0.go".into(), 3, 8),+ ]+ .into_iter()+ .chain([5, 9, 13, 17, 21, 25, 29, 33].map(|i| (format!("pkg/b/file{i}.go"), 3, 10)))+ .collect()+ }++ fn pack(question: &str, budget: usize, extra: Value) -> Value {+ let (files, symbols, calls) = project(40);+ let mut args = json!({"question":question,"budget":budget});+ for (k, v) in extra.as_object().unwrap() {+ args[k] = v.clone();+ }+ let options = Options::parse(&args).unwrap();+ let counter = Counter::open(options.tokenizer.as_deref(), options.bytes_per_token).unwrap();+ let mut corpus = corpus(&files, &symbols, &calls, ranking());+ build(&mut corpus, &options, &counter).unwrap()+ }++ fn recount(pack: &Value) -> usize {+ pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .flat_map(|s| s["chunks"].as_array().unwrap())+ .map(|c| c["tokens"].as_u64().unwrap() as usize)+ .sum()+ }++ #[test]+ fn the_budget_is_never_exceeded() {+ for budget in [MIN_BUDGET, 900, 2_000, 8_000, 30_000, 200_000, MAX_BUDGET] {+ for question in ["", "how does F4x3 compute widgets"] {+ let pack = pack(question, budget, json!({}));+ let tokens = pack["tokens"].as_u64().unwrap() as usize;+ assert!(tokens <= budget, "{tokens} > {budget}");+ assert_eq!(tokens, recount(&pack));+ // Every section's tokens are its chunks'.+ for section in pack["sections"].as_array().unwrap() {+ let sum: u64 = section["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .map(|c| c["tokens"].as_u64().unwrap())+ .sum();+ assert_eq!(section["tokens"].as_u64().unwrap(), sum);+ }+ }+ }+ }++ /// `focus` passages go ahead of the question's ranking: the pinned file+ /// is rank 1 and the call paths are its symbols' callers and callees,+ /// whatever the question asks about.+ #[test]+ fn pinned_passages_lead_the_focus_and_its_call_paths() {+ assert!(pinned(&json!({})).unwrap().is_empty());+ let one = pinned(+ &json!({"focus":[{"path":"cmd/tool/file38.go","start_line":100,"end_line":99}]}),+ )+ .unwrap();+ assert_eq!(one, [("cmd/tool/file38.go".to_string(), 99, 100)]);+ for bad in [+ json!({"focus":"cmd/tool/file38.go"}),+ json!({"focus":[{"start_line":1,"end_line":2}]}),+ json!({"focus":[{"path":"a.go","start_line":0,"end_line":2}]}),+ json!({"focus":vec![json!({"path":"a.go","start_line":1,"end_line":1}); MAX_PINNED + 1]}),+ ] {+ assert!(pinned(&bad).is_err(), "{bad}");+ }+ let (files, symbols, calls) = project(40);+ let ranked: Vec<(String, usize, usize)> = one.into_iter().chain(ranking()).collect();+ let options =+ Options::parse(&json!({"question":"how does F4x3 compute widgets","budget":20_000}))+ .unwrap();+ let counter = Counter::open(None, None).unwrap();+ let mut corpus = corpus(&files, &symbols, &calls, ranked);+ let pack = build(&mut corpus, &options, &counter).unwrap();+ let first = pack["included"]+ .as_array()+ .unwrap()+ .iter()+ .find(|f| f["rank"] == 1)+ .unwrap();+ assert_eq!(first["path"], "cmd/tool/file38.go");+ let paths: String = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|s| s["name"] == "paths")+ .flat_map(|s| s["chunks"].as_array().unwrap())+ .map(|c| c["text"].as_str().unwrap())+ .collect();+ assert!(+ paths.contains("F38x4") && paths.contains("F38x6"),+ "{paths}"+ );+ }++ #[test]+ fn a_large_budget_takes_the_whole_project() {+ let pack = pack("how does F4x3 compute widgets", MAX_BUDGET, json!({}));+ let (files, _, _) = project(40);+ let included: BTreeSet<&str> = pack["included"]+ .as_array()+ .unwrap()+ .iter()+ .map(|f| f["path"].as_str().unwrap())+ .collect();+ for path in files+ .keys()+ .filter(|p| p.ends_with(".go") && !p.ends_with("_test.go"))+ {+ assert!(included.contains(path.as_str()), "{path} left out");+ }+ }++ #[test]+ fn the_same_inputs_give_the_same_bytes() {+ for format in ["markdown", "xml"] {+ let a = pack(+ "how does F4x3 compute widgets",+ 20_000,+ json!({"style":format}),+ );+ let b = pack(+ "how does F4x3 compute widgets",+ 20_000,+ json!({"style":format}),+ );+ assert_eq!(a.to_string(), b.to_string());+ assert_eq!(text(&a), text(&b));+ }+ }++ #[test]+ fn small_files_go_in_whole_and_large_ones_as_excerpts() {+ let pack = pack("how does F4x3 compute widgets", 30_000, json!({}));+ let focus = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .find(|s| s["name"] == "focus")+ .unwrap();+ let chunks: Vec<&Value> = focus["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|c| !c["path"].is_null())+ .collect();+ // file1.go (8 functions) is small: whole; file4.go (26) is cut.+ let whole = chunks+ .iter()+ .find(|c| c["path"] == "pkg/b/file1.go")+ .unwrap();+ assert_eq!(whole["whole"], true);+ assert_eq!(whole["start_line"], 1);+ let large: Vec<&&Value> = chunks+ .iter()+ .filter(|c| c["path"] == "pkg/a/file4.go")+ .collect();+ assert!(!large.is_empty());+ for chunk in &large {+ assert_eq!(chunk["whole"], false);+ let (a, b) = (+ chunk["start_line"].as_u64().unwrap(),+ chunk["end_line"].as_u64().unwrap(),+ );+ assert!(b - a < 60, "an excerpt of {a}-{b}");+ }+ // The excerpts hold the passages' symbols, numbered.+ let first = large[0]["text"].as_str().unwrap();+ assert!(first.contains("\tfunc F4x"), "{first}");+ let why = large[0]["why"].as_str().unwrap();+ assert!(why.starts_with("focus: rank 1, defines x.F4x"), "{why}");+ }++ #[test]+ fn overlapping_ranges_merge() {+ assert_eq!(+ merge(vec![(10, 20), (15, 30), (40, 50), (52, 60)]),+ vec![(10, 30), (40, 60)]+ );+ assert_eq!(merge(vec![(5, 5), (1, 3)]), vec![(1, 5)]);+ assert_eq!(merge(vec![(1, 3), (8, 9)]), vec![(1, 3), (8, 9)]);+ assert_eq!(+ uncovered(&[(1, 100)], &[(10, 20), (50, 60)]),+ vec![(1, 9), (21, 49), (61, 100)]+ );+ assert_eq!(+ uncovered(&[(10, 20)], &[(1, 30)]),+ Vec::<(usize, usize)>::new()+ );+ // Two passages in one symbol: one excerpt.+ let symbols: Vec<Symbol> = [1, 20, 40]+ .iter()+ .enumerate()+ .map(|(i, &line)| Symbol {+ node: i,+ name: format!("f{i}"),+ path: "a.go".into(),+ line,+ degree: 1,+ })+ .collect();+ let starts = vec![1, 20, 40];+ assert_eq!(+ excerpt_ranges(&[(22, 24), (30, 33)], &symbols, &starts, 60),+ vec![(20, 39)]+ );+ assert_eq!(+ excerpt_ranges(&[(22, 24), (45, 46)], &symbols, &starts, 60),+ vec![(20, 60)]+ );+ }++ #[test]+ fn the_manifest_lists_what_is_in_and_the_top_left_out() {+ let pack = pack("how does F4x3 compute widgets", 2_500, json!({}));+ let manifest = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .find(|s| s["name"] == "manifest")+ .unwrap();+ let text: String = manifest["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .map(|c| c["text"].as_str().unwrap())+ .collect();+ for file in pack["included"].as_array().unwrap() {+ assert!(text.contains(&format!(+ "- {}: {} tokens",+ file["path"].as_str().unwrap(),+ file["tokens"]+ )));+ }+ assert!(!pack["omitted"].as_array().unwrap().is_empty());+ let first = &pack["omitted"][0];+ assert!(text.contains(&format!("- {}: ~", first["path"].as_str().unwrap())));+ }++ #[test]+ fn each_section_turns_on_and_off() {+ let all = pack("how does F4x3 compute widgets", 300_000, json!({}));+ let names: Vec<&str> = all["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["name"].as_str().unwrap())+ .collect();+ assert_eq!(+ names,+ [+ "header",+ "manifest",+ "architecture",+ "breadth",+ "docs",+ "tests",+ "paths",+ "focus"+ ]+ );+ for section in Section::CHOOSABLE {+ let others: Vec<&str> = Section::CHOOSABLE+ .iter()+ .filter(|s| **s != section)+ .map(|s| s.name())+ .collect();+ let without = pack(+ "how does F4x3 compute widgets",+ 300_000,+ json!({"sections":others.join(",")}),+ );+ assert!(+ without["sections"]+ .as_array()+ .unwrap()+ .iter()+ .all(|s| s["name"] != section.name()),+ "{} still in",+ section.name()+ );+ let only = pack(+ "how does F4x3 compute widgets",+ 300_000,+ json!({"sections":section.name()}),+ );+ let names: Vec<&str> = only["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["name"].as_str().unwrap())+ .collect();+ if section == Section::Map {+ // The map is the cache layout's (tested there).+ assert_eq!(names, ["header"]);+ } else {+ assert_eq!(names, ["header", section.name()]);+ }+ }+ let first = pack(+ "how does F4x3 compute widgets",+ 300_000,+ json!({"order":"relevant-first"}),+ );+ let names: Vec<&str> = first["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["name"].as_str().unwrap())+ .collect();+ assert_eq!(+ names,+ [+ "header",+ "manifest",+ "architecture",+ "focus",+ "paths",+ "tests",+ "docs",+ "breadth"+ ]+ );+ }++ #[test]+ fn no_question_gives_an_overview() {+ let pack = pack("", 20_000, json!({}));+ let names: Vec<&str> = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["name"].as_str().unwrap())+ .collect();+ assert_eq!(names, ["header", "manifest", "architecture", "breadth"]);+ assert!(text(&pack).contains("none (a whole-repository overview)"));+ assert!(+ pack["included"]+ .as_array()+ .unwrap()+ .iter()+ .all(|f| f["rank"].is_null())+ );+ }++ #[test]+ fn a_tiny_budget_still_fits() {+ let pack = pack("how does F4x3 compute widgets", MIN_BUDGET, json!({}));+ assert!(pack["tokens"].as_u64().unwrap() as usize <= MIN_BUDGET);+ assert_eq!(pack["sections"][0]["name"], "header");+ let refused = Options::parse(&json!({"budget":MIN_BUDGET - 1}));+ assert!(refused.is_err());+ let refused = Options::parse(&json!({"budget":MAX_BUDGET + 1}));+ assert!(refused.is_err());+ }++ #[test]+ fn the_json_contract_holds_and_the_text_is_its_chunks() {+ for style in ["markdown", "xml"] {+ let pack = pack(+ "how does F4x3 compute widgets",+ 40_000,+ json!({"style":style}),+ );+ let fields: BTreeSet<&str> = pack+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect();+ assert_eq!(+ fields,+ BTreeSet::from([+ "format",+ "project",+ "commit",+ "question",+ "budget",+ "tokens",+ "tokenizer",+ "order",+ "layout",+ "prefix_tokens",+ "prefix_sha256",+ "sections",+ "included",+ "omitted"+ ])+ );+ assert_eq!(pack["format"], FORMAT);+ assert_eq!(pack["tokenizer"], "estimate");+ assert_eq!(pack["order"], "relevant-last");+ assert_eq!(pack["layout"], "standard");+ for section in pack["sections"].as_array().unwrap() {+ assert_eq!(section["part"], "suffix");+ for chunk in section["chunks"].as_array().unwrap() {+ let keys: BTreeSet<&str> = chunk+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect();+ assert_eq!(+ keys,+ BTreeSet::from([+ "path",+ "start_line",+ "end_line",+ "whole",+ "tokens",+ "why",+ "text"+ ])+ );+ if let Some(path) = chunk["path"].as_str() {+ let marker = if style == "xml" {+ format!(+ "<file path=\"{path}\" lines=\"{}-{}\"",+ chunk["start_line"], chunk["end_line"]+ )+ } else {+ format!(+ "### {path} lines {}-{}",+ chunk["start_line"], chunk["end_line"]+ )+ };+ assert!(chunk["text"].as_str().unwrap().starts_with(&marker));+ }+ }+ }+ for file in pack["included"].as_array().unwrap() {+ let path = file["path"].as_str().unwrap();+ let in_chunks = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .flat_map(|s| s["chunks"].as_array().unwrap())+ .any(|c| c["path"] == path);+ assert!(in_chunks, "{path}");+ }+ let text = text(&pack);+ if style == "xml" {+ assert!(text.starts_with("<section name=\"header\">\n"));+ assert!(text.ends_with("</section>\n"));+ } else {+ assert!(text.starts_with("# Code pack: demo\n"));+ }+ // The focus code comes last under relevant-last, the top file last.+ let last_file = pack["sections"].as_array().unwrap().last().unwrap()["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .rev()+ .find(|c| !c["path"].is_null())+ .unwrap()+ .clone();+ assert_eq!(last_file["path"], "pkg/a/file4.go");+ }+ }++ #[test]+ fn call_paths_and_tests_come_from_the_graph() {+ let pack = pack("how does F0x0 compute widgets", 60_000, json!({}));+ let all = text(&pack);+ assert!(all.contains("## Call paths"));+ assert!(all.contains(" -> "));+ let tests = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .find(|s| s["name"] == "tests")+ .unwrap();+ assert!(+ tests["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .any(|c| c["path"] == "pkg/a/file0_test.go")+ );+ }++ #[test]+ fn git_heads_read_refs_and_detached_heads() {+ let dir = std::env::temp_dir().join(format!("graphicle-pack-git-{}", std::process::id()));+ let git = dir.join(".git");+ std::fs::create_dir_all(git.join("refs/heads")).unwrap();+ std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();+ let sha = "0123456789abcdef0123456789abcdef01234567";+ std::fs::write(git.join("refs/heads/main"), format!("{sha}\n")).unwrap();+ assert_eq!(git_head(&dir).as_deref(), Some(sha));+ std::fs::remove_file(git.join("refs/heads/main")).unwrap();+ std::fs::write(+ git.join("packed-refs"),+ format!("# pack-refs\n{sha} refs/heads/main\n"),+ )+ .unwrap();+ assert_eq!(git_head(&dir).as_deref(), Some(sha));+ std::fs::write(git.join("HEAD"), format!("{sha}\n")).unwrap();+ assert_eq!(git_head(&dir).as_deref(), Some(sha));+ std::fs::remove_dir_all(&dir).unwrap();+ assert_eq!(git_head(&dir), None);+ }++ /// With a tokenizer, every chunk and the whole pack are counted exactly,+ /// and the pack stays inside the budget.+ #[test]+ fn an_exact_tokenizer_counts_and_keeps_the_budget() {+ let dir = std::env::temp_dir().join(format!("graphicle-pack-tok-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("tokenizer.json");+ // Every word and every punctuation run is one token.+ std::fs::write(+ &path,+ r#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[],"normalizer":null,+ "pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,+ "model":{"type":"WordLevel","vocab":{"[UNK]":0},"unk_token":"[UNK]"}}"#,+ )+ .unwrap();+ let counter = Counter::open(Some(path.to_str().unwrap()), None).unwrap();+ assert!(counter.exact());+ assert_eq!(counter.name(), dir.file_name().unwrap().to_string_lossy());+ let (files, symbols, calls) = project(40);+ for budget in [MIN_BUDGET, 5_000, 60_000] {+ let options = options_for("how does F4x3 compute widgets", budget);+ let mut corpus = corpus(&files, &symbols, &calls, ranking());+ let pack = build(&mut corpus, &options, &counter).unwrap();+ let tokens = pack["tokens"].as_u64().unwrap() as usize;+ assert!(tokens <= budget, "{tokens} > {budget}");+ let Counter::Exact { tokenizer, .. } = &counter else {+ unreachable!()+ };+ assert_eq!(tokens, exact_count(tokenizer, &text(&pack)));+ assert_eq!(pack["tokenizer"], counter.name());+ }+ std::fs::remove_dir_all(&dir).unwrap();+ }++ fn options_for(question: &str, budget: usize) -> Options {+ Options::parse(&json!({"question":question,"budget":budget})).unwrap()+ }++ /// `bytes_per_token`: every chunk is its UTF-8 bytes over the rate, with+ /// no margin, and the whole text over the rate stays inside the budget.+ #[test]+ fn one_rate_of_bytes_per_token_counts_every_byte_alike() {+ for budget in [MIN_BUDGET, 6_000, 90_000] {+ let pack = pack(+ "how does F4x3 compute widgets",+ budget,+ json!({"bytes_per_token":4}),+ );+ for section in pack["sections"].as_array().unwrap() {+ for chunk in section["chunks"].as_array().unwrap() {+ let bytes = chunk["text"].as_str().unwrap().len();+ assert_eq!(+ chunk["tokens"].as_u64().unwrap() as usize,+ bytes.div_ceil(4)+ );+ }+ }+ let tokens = pack["tokens"].as_u64().unwrap() as usize;+ assert!(tokens <= budget && text(&pack).len().div_ceil(4) <= budget);+ assert_eq!(pack["tokenizer"], "estimate");+ assert!(text(&pack).contains("estimated as UTF-8 bytes / 4, without a margin"));+ }+ assert!(Options::parse(&json!({"bytes_per_token":0.5})).is_err());+ assert!(Counter::open(Some("t.json"), Some(4.0)).is_err());+ }++ #[test]+ fn a_question_routes_to_the_folders_it_names() {+ let files: BTreeMap<String, usize> = [+ "homeassistant/components/alexa_devices/__init__.py",+ "homeassistant/components/alexa_devices/manifest.json",+ "homeassistant/components/light/__init__.py",+ "homeassistant/components/alexa/__init__.py",+ "homeassistant/helpers/entity.py",+ "tests/components/alexa_devices/test_init.py",+ "pkg/controller/job/job_controller.go",+ "pkg/registry/batch/job/strategy.go",+ "test/e2e/apps/job/job.go",+ "a/x/one.go",+ "b/x/two.go",+ "c/x/three.go",+ ]+ .iter()+ .map(|p| (p.to_string(), 100))+ .collect();+ let named = named_folders(+ "Integration causing the issue: Alexa Devices. See https://www.home-assistant.io/integrations/alexa_devices/ and the helpers.",+ &files,+ );+ assert_eq!(named, ["homeassistant/components/alexa_devices"]);+ // Two folders of one name are both routed; three or more, none.+ let named = named_folders("the job counts twice; x marks", &files);+ assert_eq!(named, ["pkg/controller/job", "pkg/registry/batch/job"]);+ assert!(named_folders("general words: helpers, tests, pkg", &files).is_empty());+ // The longest name wins: "Alexa Devices" is alexa_devices, not alexa.+ let named = named_folders("Alexa Devices stops at login", &files);+ assert_eq!(named, ["homeassistant/components/alexa_devices"]);+ }++ #[test]+ fn go_imports_lead_to_the_file_that_defines_a_name() {+ let text = "package job\n\nimport (\n\t\"fmt\"\n\tutilfeature \"k8s.io/apiserver/pkg/util/feature\"\n\t\"k8s.io/kubernetes/pkg/features\"\n)\n\nfunc f() { if utilfeature.Enabled(features.JobPodReplacementPolicy) {} }\n";+ let imports = go_imports(text);+ assert_eq!(imports["features"], "k8s.io/kubernetes/pkg/features");+ assert_eq!(imports["utilfeature"], "k8s.io/apiserver/pkg/util/feature");+ let folders: BTreeSet<String> = [+ "pkg/features",+ "staging/src/k8s.io/apiserver/pkg/util/feature",+ ]+ .iter()+ .map(|s| s.to_string())+ .collect();+ assert_eq!(+ import_folder("k8s.io/kubernetes/pkg/features", &folders).as_deref(),+ Some("pkg/features")+ );+ assert_eq!(+ import_folder("k8s.io/apiserver/pkg/util/feature", &folders).as_deref(),+ Some("staging/src/k8s.io/apiserver/pkg/util/feature")+ );+ assert_eq!(import_folder("fmt", &folders), None);+ let defining = "package features\n\nconst (\n\t// a gate\n\tJobPodReplacementPolicy featuregate.Feature = \"JobPodReplacementPolicy\"\n)\n\nfunc (g *Gate) Enabled(f Feature) bool { return true }\n";+ assert!(go_defines(defining, "JobPodReplacementPolicy"));+ assert!(go_defines(defining, "Enabled"));+ assert!(!go_defines(defining, "Feature"));+ assert!(!go_defines(+ "x := JobPodReplacementPolicy\n",+ "JobPodReplacementPolicy"+ ));+ }++ fn file_map(paths: &[&str]) -> BTreeMap<String, usize> {+ paths.iter().map(|p| (p.to_string(), 100)).collect()+ }++ #[test]+ fn typescript_imports_resolve_relative_paths_and_tsconfig_aliases() {+ let files = file_map(&[+ "packages/core/index.ts",+ "packages/core/src/render3/instructions/shared.ts",+ "packages/core/src/render3/interfaces/view.ts",+ "packages/core/src/util/assert.ts",+ "packages/forms/src/model/form_control.ts",+ "src/vs/base/common/event.ts",+ "src/vs/base/common/lifecycle.ts",+ "src/vs/editor/common/model.ts",+ "packages/tsconfig.json",+ ]);+ let tsconfig = "{\n \"compilerOptions\": {\n // resolve from the root\n \"baseUrl\": \"..\",\n \"paths\": {\n \"rxjs/*\": [\"./node_modules/rxjs/*\"],\n \"@angular/*\": [\"./packages/*\"]\n }\n }\n}\n";+ let aliases = ts_aliases_of("packages/tsconfig.json", tsconfig);+ assert_eq!(+ aliases,+ [TsAlias {+ pattern: "@angular/*".into(),+ targets: vec!["packages/*".into()],+ }]+ );+ let text = "import {assertDefined, assertEqual} from '../../util/assert';\nimport {\n LView,\n type TView,\n} from '../interfaces/view';\nimport {Injector} from '@angular/core';\nimport {FormControl} from '@angular/forms/src/model/form_control';\nimport {of} from 'rxjs';\nexport * from './missing';\n";+ let imports = ts_imports(text);+ assert_eq!(+ imports,+ [+ ("../../util/assert".to_string(), 2),+ ("../interfaces/view".to_string(), 2),+ ("@angular/core".to_string(), 1),+ ("@angular/forms/src/model/form_control".to_string(), 1),+ ("rxjs".to_string(), 1),+ ("./missing".to_string(), 1),+ ]+ );+ let here = "packages/core/src/render3/instructions";+ let resolved: Vec<Option<String>> = imports+ .iter()+ .map(|(spec, _)| ts_resolve(spec, here, &files, &aliases))+ .collect();+ assert_eq!(+ resolved,+ [+ Some("packages/core/src/util/assert.ts".to_string()),+ Some("packages/core/src/render3/interfaces/view.ts".to_string()),+ Some("packages/core/index.ts".to_string()),+ Some("packages/forms/src/model/form_control.ts".to_string()),+ None,+ None,+ ]+ );+ assert_eq!(+ ts_imports("import type {A, B} from './a';\nimport D, {e} from './d';\n"),+ [("./a".to_string(), 2), ("./d".to_string(), 2)]+ );+ assert!(ts_barrel("packages/core/index.ts"));+ assert!(!ts_barrel("packages/core/src/util/assert.ts"));+ // An ES module names the compiled file: `./event.js` is `event.ts`.+ let text = "import { Emitter } from '../../base/common/event.js';\nimport { Disposable } from '../../base/common/lifecycle.js';\nconst x = require('./model');\n";+ let resolved: Vec<Option<String>> = ts_imports(text)+ .iter()+ .map(|(spec, _)| ts_resolve(spec, "src/vs/editor/common", &files, &[]))+ .collect();+ assert_eq!(+ resolved,+ [+ Some("src/vs/base/common/event.ts".to_string()),+ Some("src/vs/base/common/lifecycle.ts".to_string()),+ Some("src/vs/editor/common/model.ts".to_string()),+ ]+ );+ assert_eq!(joined("a/b", "../../../c"), None);+ }++ #[test]+ fn a_question_names_files_by_their_code_names_and_words() {+ let files = file_map(&[+ "scene/gui/text_edit.cpp",+ "scene/gui/text_edit.h",+ "tests/scene/test_text_edit.h",+ "editor/plugins/text_editor.cpp",+ "packages/forms/src/model/form_control.ts",+ "packages/core/src/foo.component.ts",+ "services/src/main/java/org/keycloak/models/UserModel.java",+ "a/node.cpp",+ "homeassistant/helpers/update_coordinator.py",+ "pkg/controller/job/job_controller.go",+ ]);+ let named = named_files(+ "TextEdit crashes when a FormControl holds a `UserModel`; FooComponent::render too. Node is fine.",+ &files,+ );+ assert_eq!(+ named,+ [+ "scene/gui/text_edit.cpp",+ "scene/gui/text_edit.h",+ "packages/forms/src/model/form_control.ts",+ "services/src/main/java/org/keycloak/models/UserModel.java",+ "packages/core/src/foo.component.ts",+ ]+ );+ assert!(named_files("the node crashes", &files).is_empty());+ // Two or three words of the question name a file of a language that+ // names its files after their classes.+ assert_eq!(+ named_files("Typing in the text edit freezes the editor", &files),+ ["scene/gui/text_edit.cpp", "scene/gui/text_edit.h"]+ );+ // Words do not name a Python or Go module; a code name does.+ assert!(+ named_files(+ "the update coordinator and the job controller stall",+ &files+ )+ .is_empty()+ );+ assert_eq!(+ named_files("JobController stalls", &files),+ ["pkg/controller/job/job_controller.go"]+ );+ assert!(compound("MeshInstance3D") && compound("text_edit") && !compound("Node"));+ assert_eq!(folded("mesh_instance_3d"), folded("MeshInstance3D"));+ }++ #[test]+ fn the_ranking_reads_an_issue_without_its_environment_sections() {+ let issue = "### Tested versions\n\n4.7.2 stable\n\n### System information\n\nGodot v4.8 - Wayland - Vulkan (Forward+)\n\n### Issue description\n\nThe FileSystem dock freezes.\n\n#### Kubernetes version\n\nkubectl version output\n\n### Steps to reproduce\n\n- VS Code Version: 1.95\n- Click twice\n";+ let read = ranking_question(issue);+ for gone in ["4.7.2", "Wayland", "kubectl", "VS Code Version"] {+ assert!(!read.contains(gone), "{gone}");+ }+ for kept in [+ "### Issue description",+ "The FileSystem dock freezes.",+ "### Steps to reproduce",+ "- Click twice",+ ] {+ assert!(read.contains(kept), "{kept}");+ }+ assert!(matches!(+ ranking_question("how does F4x3 compute widgets"),+ std::borrow::Cow::Borrowed(_)+ ));+ assert_eq!(+ ranking_question("### Godot version\r\n4.0\r\n### Issue description\r\nCrash\r\n"),+ "### Issue description\r\nCrash\r\n"+ );+ }++ #[test]+ fn an_issue_whose_title_names_a_version_ranks_as_written() {+ let issue = "# Flipt Configuration Lacks a Metadata Section for Version Check Preferences\n\n## Description\n\nThe config has no metadata section.\n\n## Expected\n\nA `meta.check_for_updates` key.\n";+ assert!(matches!(+ ranking_question(issue),+ std::borrow::Cow::Borrowed(read) if read == issue+ ));+ }++ #[test]+ fn a_comment_in_a_code_block_is_not_an_environment_section() {+ // A `# comment` line that names a version reads as a level-1 heading,+ // which never opens an environment section: the issue's sections+ // after the block stay in the question.+ let issue = "Saving fails.\n\n```python\n# works on version 2.3, fails on 2.4\nsave()\n```\n\n### Traceback\n\nKeyError: 'name'\n\n### Expected\n\nThe file is saved.\n";+ assert!(matches!(+ ranking_question(issue),+ std::borrow::Cow::Borrowed(read) if read == issue+ ));+ }++ #[test]+ fn a_heading_that_merely_names_a_version_is_not_an_environment_section() {+ // A real title after a one-line preamble, a level-1 heading and short+ // headings that are sentences keep the issue's body.+ for issue in [+ "Reported by a customer.\n\n## Upgrade to version 2 breaks login\n\nThe login form rejects every password.\n\n### Steps\n\nLog in.\n",+ "Seen on Linux.\n# Crash in version 4.2\n\nThe editor closes.\n",+ "Seen on Linux.\n## Environment variables are not expanded\n\n`$HOME` stays literal.\n",+ "Seen on Linux.\n### Broken in new version\n\nThe dock is empty.\n",+ ] {+ assert!(+ matches!(+ ranking_question(issue),+ std::borrow::Cow::Borrowed(read) if read == issue+ ),+ "{issue}"+ );+ }+ // Short labels and an issue form's questions for the environment+ // still open environment sections.+ let issue = "### The problem\n\nThe light stays off.\n\n### What version of Home Assistant Core has the issue?\n\ncore-2026.9.4\n\n### Container runtime (CRI) and version (if applicable)\n\ncontainerd 2.1\n\n### OS\n\nLinux\n\n### Anything else?\n\nNo.\n";+ assert_eq!(+ ranking_question(issue),+ "### The problem\n\nThe light stays off.\n\n### Anything else?\n\nNo.\n"+ );+ }++ #[test]+ fn only_a_label_line_is_a_version_line() {+ for line in [+ "Version check fails: the updater crashes offline.",+ "def version(self):",+ "Upgrading to version 2: the login breaks.",+ "In the new version: the dock is empty.",+ ] {+ let issue = format!("The dock is empty.\n{line}\n");+ assert_eq!(ranking_question(&issue), issue, "{line}");+ }+ for line in [+ "- VS Code Version: 1.95",+ "**Godot version:** 4.2.1",+ "* Kubernetes version: v1.37.0",+ "Versions affected: 2.1",+ ] {+ assert_eq!(+ ranking_question(&format!("The dock is empty.\n{line}\n")),+ "The dock is empty.\n",+ "{line}"+ );+ }+ }++ #[test]+ fn excerpts_keep_to_a_cap_best_passage_first() {+ let lines: Vec<String> = (1..=400)+ .map(|i| format!("line number {i} of a long file"))+ .collect();+ let lines: Vec<&str> = lines.iter().map(String::as_str).collect();+ let symbols: Vec<Symbol> = [1, 100, 200, 300]+ .iter()+ .enumerate()+ .map(|(i, &line)| Symbol {+ node: i,+ name: format!("f{i}"),+ path: "a.go".into(),+ line,+ degree: 1,+ })+ .collect();+ let starts = vec![1, 100, 200, 300];+ let full = capped_ranges(+ &[(150, 152), (250, 252)],+ &symbols,+ &starts,+ &lines,+ 3.0,+ 100_000,+ false,+ );+ assert_eq!(full, vec![(100, 299)]);+ let capped = capped_ranges(+ &[(150, 152), (250, 252)],+ &symbols,+ &starts,+ &lines,+ 3.0,+ 1_200,+ false,+ );+ assert_eq!(capped, vec![(100, 199)]);+ let compact = capped_ranges(+ &[(150, 152), (250, 252)],+ &symbols,+ &starts,+ &lines,+ 3.0,+ 100_000,+ true,+ );+ assert_eq!(+ compact,+ vec![(100, 100), (147, 155), (200, 200), (247, 255)]+ );+ let tiny = capped_ranges(&[(150, 190)], &symbols, &starts, &lines, 3.0, 40, false);+ assert_eq!(tiny.len(), 1);+ assert!(tiny[0].0 == 150 && tiny[0].1 < 190);+ }++ #[test]+ fn a_named_folder_joins_the_ranking_after_the_top_files() {+ let pack = pack(+ "why does the tool command fail to compute widgets",+ 300_000,+ json!({}),+ );+ let routed: Vec<&Value> = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .flat_map(|s| s["chunks"].as_array().unwrap())+ .filter(|c| {+ c["why"]+ .as_str()+ .unwrap_or("")+ .contains("in a folder the question names")+ })+ .collect();+ assert!(!routed.is_empty());+ assert!(+ routed+ .iter()+ .all(|c| c["path"].as_str().unwrap().starts_with("cmd/tool/"))+ );+ // Ranks follow the new order: the top five, then the folder.+ let ranks: Vec<u64> = routed+ .iter()+ .filter_map(|c| {+ let path = c["path"].as_str().unwrap();+ pack["included"]+ .as_array()+ .unwrap()+ .iter()+ .find(|f| f["path"] == path)?["rank"]+ .as_u64()+ })+ .collect();+ assert!(ranks.iter().all(|&r| r > ROUTE_AFTER as u64), "{ranks:?}");+ }++ #[test]+ fn symbols_show_without_their_file() {+ assert_eq!(+ short("staging/src/k8s.io/api/apps/v1/types.go.StatefulSet"),+ "StatefulSet"+ );+ assert_eq!(short("pkg/x.go.Cache.Get"), "Cache.Get");+ assert_eq!(short("pkg/x.go.Cache.Get.inner"), "Get.inner");+ assert_eq!(short("listers/apps/v1/statefulset.go"), "");+ assert_eq!(short("kubelet.Kubelet.syncPod"), "Kubelet.syncPod");+ assert_eq!(short("getOrdinal"), "getOrdinal");+ assert_eq!(short("x.F4x1"), "x.F4x1");+ }++ #[test]+ fn the_estimator_rates_are_sorted_and_conservative() {+ let names: Vec<&str> = estimate::BYTES_PER_TOKEN.iter().map(|(n, _)| *n).collect();+ let mut sorted = names.clone();+ sorted.sort_unstable();+ assert_eq!(names, sorted);+ assert_eq!(estimate::rate("go"), 3.63);+ assert_eq!(estimate::rate("unknown"), estimate::DEFAULT_BYTES_PER_TOKEN);+ assert_eq!(estimate::prefix_tokens(7, 7), 2);+ assert_eq!(estimate::prefix_tokens(1, 10), 16);+ assert_eq!(estimate::prefix_tokens(9_999, 10_000), 5);+ assert_eq!(+ tokenizer_name("/m/Muse-Spark-Open/tokenizer.json"),+ "Muse-Spark-Open"+ );+ assert_eq!(tokenizer_name("/m/custom.json"), "custom.json");+ }+ /// The pack JSON without the fields the layouts added.+ fn without_layout_fields(pack: &Value) -> Value {+ let mut out = serde_json::Map::new();+ for (key, value) in pack.as_object().unwrap() {+ if ["layout", "prefix_share", "prefix_tokens", "prefix_sha256"].contains(&key.as_str())+ {+ continue;+ }+ if key == "sections" {+ let sections = value+ .as_array()+ .unwrap()+ .iter()+ .map(|section| {+ let mut kept = serde_json::Map::new();+ for (k, v) in section.as_object().unwrap() {+ if k != "part" {+ kept.insert(k.clone(), v.clone());+ }+ }+ Value::Object(kept)+ })+ .collect();+ out.insert(key.clone(), Value::Array(sections));+ } else {+ out.insert(key.clone(), value.clone());+ }+ }+ Value::Object(out)+ }++ /// The standard layout gives the bytes and JSON it gave before the+ /// layouts (hashes taken at 50ebde1), plus the new fields.+ #[test]+ fn the_standard_layout_is_unchanged_but_for_the_new_fields() {+ let goldens: [(&str, usize, Value, &str, &str); 6] = [+ (+ "how does F4x3 compute widgets",+ 20_000,+ json!({}),+ "a3fe4f1b8a832d51ebdbd3c82a6f5688bc4abdc9120931ff2f6bdb50decbd6de",+ "ec0fcd4c739a584a137d16819673adc52b8213c7e7a392702e9a345cbcee6bd7",+ ),+ (+ "how does F4x3 compute widgets",+ 40_000,+ json!({"style":"xml"}),+ "100f9cbb8c03e9b5d8a817f9fa988b828c9eb7baa2324d274b8a1ae234790e20",+ "94f0b3b5dc3555149fe54a620b609f0be0f28c2dde5df27c2b68c4cd5d2f0466",+ ),+ (+ "",+ 20_000,+ json!({}),+ "a7c0f0cd8f5bf5df83cbf487f553bbf545631dd558990c92adb01d65862ce70f",+ "602698368d8c9ea4dc3eb19938f7ce13c0cceaf922af9c92cfd718df65805cc8",+ ),+ (+ "how does F0x0 compute widgets",+ 300_000,+ json!({"order":"relevant-first"}),+ "f21d87fad3a784701b24c523434126fbd40ff1658efe6be56c62dd5068c9f632",+ "3b1abe7ac364f823d0aea60fad5d8e2c0c32718fbfe976df19b5cd018fceea8e",+ ),+ (+ "how does F4x3 compute widgets",+ MIN_BUDGET,+ json!({}),+ "f73aaf24790512eafddbb91558fcd15db347b63e50c5ef590417b6dd5971bf3e",+ "42ba6be2990fef1ccd8cd9dcd1b8e4e6cbc4c82fff621351ca465fd539af2f7a",+ ),+ (+ "how does F4x3 compute widgets",+ 8_000,+ json!({"line_numbers":"all","sections":"focus,tests,manifest"}),+ "10246944f0adcfd023961ba3f8ac1d6c4a344e16a170b73d827e8e1a75efa0a0",+ "4bec267dbd2d7136f65bea6a76722470c3d5f16f0e51fd4167fc40fcbd592d81",+ ),+ ];+ for (question, budget, extra, text_sha, json_sha) in goldens {+ let pack = pack(question, budget, extra.clone());+ assert_eq!(+ sha256_hex(&text(&pack)),+ text_sha,+ "{question:?} {budget} {extra}"+ );+ assert_eq!(+ sha256_hex(&without_layout_fields(&pack).to_string()),+ json_sha,+ "{question:?} {budget} {extra}"+ );+ assert_eq!(pack["layout"], "standard");+ assert!(pack.get("prefix_share").is_none());+ // The header names the question: a pack for one has no prefix.+ if question.is_empty() {+ assert_eq!(pack["prefix_tokens"], pack["tokens"]);+ assert_eq!(pack["prefix_sha256"], sha256_hex(&text(&pack)));+ } else {+ assert_eq!(pack["prefix_tokens"], 0);+ assert_eq!(pack["prefix_sha256"], sha256_hex(""));+ }+ }+ }++ /// Another question's ranking: other files, other passages.+ fn other_ranking() -> Vec<(String, usize, usize)> {+ vec![+ ("internal/c/file3.go".into(), 20, 30),+ ("cmd/tool/file6.go".into(), 5, 12),+ ("pkg/b/file13.go".into(), 40, 60),+ ("internal/c/file7.go".into(), 3, 9),+ ("pkg/a/file0.go".into(), 60, 70),+ ]+ }++ /// The demo project with a root README and an architecture document.+ fn documented(n: usize) -> Project {+ let (mut files, symbols, calls) = project(n);+ files.insert(+ "README.md".into(),+ "# Demo\n\nDemo computes widgets for tools.\n".into(),+ );+ files.insert(+ "docs/ARCHITECTURE.md".into(),+ "# Architecture\n\nThe tool calls pkg/a, which calls pkg/b.\n".into(),+ );+ (files, symbols, calls)+ }++ fn cache_pack(+ question: &str,+ ranking: Vec<(String, usize, usize)>,+ budget: usize,+ extra: Value,+ ) -> Value {+ let (files, symbols, calls) = documented(40);+ let mut args = json!({"question":question,"budget":budget,"layout":"cache"});+ for (k, v) in extra.as_object().unwrap() {+ args[k] = v.clone();+ }+ let options = Options::parse(&args).unwrap();+ let counter = Counter::open(options.tokenizer.as_deref(), options.bytes_per_token).unwrap();+ let mut corpus = corpus(&files, &symbols, &calls, ranking);+ build(&mut corpus, &options, &counter).unwrap()+ }++ /// The text of a pack's prefix sections, in order.+ fn prefix_text(pack: &Value) -> String {+ pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|s| s["part"] == "prefix")+ .flat_map(|s| s["chunks"].as_array().unwrap())+ .map(|c| c["text"].as_str().unwrap())+ .collect()+ }++ fn section_names(pack: &Value) -> Vec<String> {+ pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["name"].as_str().unwrap().to_string())+ .collect()+ }++ #[test]+ fn two_questions_share_the_repository_part_byte_for_byte() {+ for style in ["markdown", "xml"] {+ for share in [0.5, 0.9, 0.95, 1.0] {+ for budget in [8_000, 60_000] {+ let extra = json!({"style":style,"prefix_share":share});+ let a = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ budget,+ extra.clone(),+ );+ let b = cache_pack(+ "where do tools read file3",+ other_ranking(),+ budget,+ extra.clone(),+ );+ let (pa, pb) = (prefix_text(&a), prefix_text(&b));+ assert!(!pa.is_empty());+ assert_eq!(pa, pb, "{style} {share} {budget}");+ assert_eq!(a["prefix_sha256"], b["prefix_sha256"]);+ assert_eq!(a["prefix_sha256"], sha256_hex(&pa));+ assert_eq!(a["prefix_tokens"], b["prefix_tokens"]);+ assert_eq!(a["layout"], "cache");+ assert_eq!(a["prefix_share"], share);+ // Neither question is in the repository part.+ assert!(!pa.contains("F4x3 compute") && !pa.contains("read file3"));+ if share < 1.0 {+ assert_ne!(text(&a), text(&b), "{style} {share} {budget}");+ } else {+ assert_eq!(text(&a), text(&b));+ }+ }+ }+ }+ }++ #[test]+ fn the_prefix_is_a_byte_prefix_of_the_text_and_leads_it() {+ for share in [0.5, 0.9, 1.0] {+ let pack = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 30_000,+ json!({"prefix_share":share}),+ );+ let all = text(&pack);+ let prefix = prefix_text(&pack);+ assert!(all.starts_with(&prefix));+ assert_eq!(pack["prefix_sha256"], sha256_hex(&all[..prefix.len()]));+ // Every prefix section comes before every suffix section.+ let parts: Vec<&str> = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .map(|s| s["part"].as_str().unwrap())+ .collect();+ let first_suffix = parts.iter().position(|p| *p == "suffix");+ if let Some(i) = first_suffix {+ assert!(parts[i..].iter().all(|p| *p == "suffix"), "{parts:?}");+ }+ let names = section_names(&pack);+ assert_eq!(&names[..4], ["header", "architecture", "map", "breadth"]);+ if share < 1.0 {+ assert!(names.contains(&"manifest".to_string()));+ assert!(names.contains(&"focus".to_string()));+ assert_eq!(names.last().unwrap(), "focus");+ }+ }+ }++ #[test]+ fn the_cache_layout_keeps_the_budget_and_its_split() {+ for budget in [MIN_BUDGET, 900, 2_000, 8_000, 30_000, 200_000, MAX_BUDGET] {+ for share in [0.5, 0.9, 0.95, 1.0] {+ for question in ["", "how does F4x3 compute widgets"] {+ let pack =+ cache_pack(question, ranking(), budget, json!({"prefix_share":share}));+ let tokens = pack["tokens"].as_u64().unwrap() as usize;+ let prefix = pack["prefix_tokens"].as_u64().unwrap() as usize;+ assert!(tokens <= budget, "{tokens} > {budget}");+ assert!(+ prefix <= ((budget as f64) * share) as usize,+ "{prefix} over {share} of {budget}"+ );+ assert!(prefix <= tokens);+ assert_eq!(tokens, recount(&pack));+ let in_prefix: u64 = pack["sections"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|s| s["part"] == "prefix")+ .map(|s| s["tokens"].as_u64().unwrap())+ .sum();+ assert_eq!(in_prefix as usize, prefix);+ for section in pack["sections"].as_array().unwrap() {+ let sum: u64 = section["chunks"]+ .as_array()+ .unwrap()+ .iter()+ .map(|c| c["tokens"].as_u64().unwrap())+ .sum();+ assert_eq!(section["tokens"].as_u64().unwrap(), sum);+ }+ }+ }+ }+ }++ #[test]+ fn a_stable_pack_is_only_the_repository_part() {+ let a = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 30_000,+ json!({"prefix_share":1.0}),+ );+ let b = cache_pack("", Vec::new(), 30_000, json!({"prefix_share":1.0}));+ assert_eq!(text(&a), text(&b));+ assert_eq!(a["prefix_tokens"], a["tokens"]);+ assert!(+ a["sections"]+ .as_array()+ .unwrap()+ .iter()+ .all(|s| s["part"] == "prefix")+ );+ let names = section_names(&a);+ assert_eq!(names, ["header", "architecture", "map", "breadth", "docs"]);+ let all = text(&a);+ assert!(all.contains("only the question after it changes"));+ assert!(all.contains("### README.md lines 1-3 (whole file)"));+ assert!(all.contains("docs/ARCHITECTURE.md"));+ // The prefix share alone chooses the cache layout.+ let options = Options::parse(&json!({"prefix_share":1.0})).unwrap();+ assert_eq!(options.layout, Layout::Cache);+ }++ #[test]+ fn the_question_part_refers_to_the_repository_part_instead_of_repeating_it() {+ // internal/c/file3.go is among the most connected files (whole in the+ // repository part) and ranked first for this question.+ let pack = cache_pack(+ "where do tools read file3",+ other_ranking(),+ 30_000,+ json!({"prefix_share":0.5}),+ );+ let sections = pack["sections"].as_array().unwrap();+ let mut whole_in_prefix: BTreeMap<String, (u64, u64)> = BTreeMap::new();+ for section in sections.iter().filter(|s| s["part"] == "prefix") {+ for chunk in section["chunks"].as_array().unwrap() {+ if chunk["whole"] == true {+ whole_in_prefix.insert(+ chunk["path"].as_str().unwrap().to_string(),+ (+ chunk["start_line"].as_u64().unwrap(),+ chunk["end_line"].as_u64().unwrap(),+ ),+ );+ }+ }+ }+ assert!(+ whole_in_prefix.contains_key("internal/c/file3.go"),+ "{whole_in_prefix:?}"+ );+ assert!(!whole_in_prefix.contains_key("cmd/tool/file6.go"));+ let mut suffix_text = String::new();+ for section in sections.iter().filter(|s| s["part"] == "suffix") {+ for chunk in section["chunks"].as_array().unwrap() {+ suffix_text.push_str(chunk["text"].as_str().unwrap());+ if let Some(path) = chunk["path"].as_str() {+ assert!(+ !whole_in_prefix.contains_key(path),+ "{path} repeated in the question part"+ );+ }+ }+ }+ let (_, end) = whole_in_prefix["internal/c/file3.go"];+ assert!(+ suffix_text.contains(&format!(+ "- in the prefix: internal/c/file3.go lines 1-{end} (rank 1)"+ )),+ "{suffix_text}"+ );+ // The second file, not whole in the repository part, is in focus.+ assert!(suffix_text.contains("### cmd/tool/file6.go lines "));+ // `included` covers both parts, with the question's ranks.+ let included: BTreeMap<&str, &Value> = pack["included"]+ .as_array()+ .unwrap()+ .iter()+ .map(|f| (f["path"].as_str().unwrap(), &f["rank"]))+ .collect();+ assert_eq!(included["internal/c/file3.go"], &json!(1));+ assert_eq!(included["cmd/tool/file6.go"], &json!(2));+ }++ #[test]+ fn the_map_lists_the_folders_and_turns_off() {+ let pack = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 30_000,+ json!({}),+ );+ let all = text(&pack);+ assert!(all.contains("## Repository map\n"));+ assert!(all.contains("- pkg/a/: 12 files, ~"), "{}", &all[..2000]);+ assert!(all.contains("- ./: 1 file, ~"));+ assert!(all.contains(". Key: x.F4x25, x.F4x24, x.F12x31.\n"));+ let without = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 30_000,+ json!({"sections":"arch,focus,paths,tests,docs,breadth,manifest"}),+ );+ assert!(!section_names(&without).contains(&"map".to_string()));+ // A small room keeps the most connected folders, in path order.+ let (files, symbols, calls) = documented(40);+ let corpus = corpus(&files, &symbols, &calls, ranking());+ let full = map_text(&corpus, 100_000, &Counter::Estimate);+ let small = map_text(&corpus, 90, &Counter::Estimate);+ assert!(full.starts_with("6 folders that hold files"), "{full}");+ assert!(small.starts_with("1 of the 6 folders"), "{small}");+ assert!(small.contains("- cmd/tool/:"), "{small}");+ assert!(Counter::Estimate.count(&small, estimate::PACK_TEXT_BYTES_PER_TOKEN, 0, 0) <= 90);+ }++ #[test]+ fn options_choose_the_layout_and_check_the_share() {+ let standard = Options::parse(&json!({})).unwrap();+ assert_eq!(standard.layout, Layout::Standard);+ let cache = Options::parse(&json!({"layout":"cache"})).unwrap();+ assert_eq!(cache.layout, Layout::Cache);+ assert_eq!(cache.prefix_share, DEFAULT_PREFIX_SHARE);+ let stable = Options::parse(&json!({"prefix_share":1})).unwrap();+ assert_eq!((stable.layout, stable.prefix_share), (Layout::Cache, 1.0));+ for bad in [+ json!({"layout":"standard","prefix_share":0.9}),+ json!({"prefix_share":0.05}),+ json!({"prefix_share":1.5}),+ json!({"prefix_share":"most"}),+ json!({"layout":"cached"}),+ ] {+ assert!(Options::parse(&bad).is_err(), "{bad}");+ }+ }++ /// With a tokenizer, the cache layout's parts are counted exactly and+ /// stay inside the budget and the split.+ #[test]+ fn an_exact_tokenizer_counts_the_cache_layout() {+ let dir = std::env::temp_dir().join(format!("graphicle-pack-tokc-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("tokenizer.json");+ std::fs::write(+ &path,+ r#"{"version":"1.0","truncation":null,"padding":null,"added_tokens":[],"normalizer":null,+ "pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,+ "model":{"type":"WordLevel","vocab":{"[UNK]":0},"unk_token":"[UNK]"}}"#,+ )+ .unwrap();+ let tokenizer = path.to_str().unwrap().to_string();+ for budget in [MIN_BUDGET, 5_000, 60_000] {+ for share in [0.9, 1.0] {+ let pack = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ budget,+ json!({"prefix_share":share,"tokenizer":tokenizer}),+ );+ let counter = Counter::open(Some(&tokenizer), None).unwrap();+ let Counter::Exact {+ tokenizer: exact, ..+ } = &counter+ else {+ unreachable!()+ };+ let tokens = pack["tokens"].as_u64().unwrap() as usize;+ assert!(tokens <= budget, "{tokens} > {budget}");+ assert_eq!(tokens, exact_count(exact, &text(&pack)));+ let prefix = pack["prefix_tokens"].as_u64().unwrap() as usize;+ assert_eq!(prefix, exact_count(exact, &prefix_text(&pack)));+ assert!(prefix <= ((budget as f64) * share) as usize);+ }+ }+ std::fs::remove_dir_all(&dir).unwrap();+ }+ #[test]+ fn a_small_question_part_gives_full_excerpts_to_fewer_ranks() {+ let ranks = |room: usize| Sizing::question_part(room).full_ranks;+ assert_eq!(+ [+ ranks(10_000),+ ranks(25_000),+ ranks(49_000),+ ranks(92_000),+ ranks(300_000)+ ],+ [3, 3, 6, 11, 15]+ );+ assert_eq!(Sizing::new(25_000, false).full_ranks, FULL_RANKS);+ // The full excerpts take at most two fifths of the room together.+ for room in [25_000, 49_000, 92_000, 139_000, 500_000] {+ let sizing = Sizing::question_part(room);+ assert!(+ sizing.full_ranks * sizing.per_file <= room * 2 / 5,+ "{room}"+ );+ }+ }+ /// A calibrated budget moves from call to call; a fixed `prefix_budget`+ /// keeps the repository part the same bytes, and the header names no+ /// budget.+ #[test]+ fn a_fixed_prefix_budget_keeps_the_repository_part_when_the_budget_moves() {+ let a = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 56_000,+ json!({"prefix_budget":56_000}),+ );+ let b = cache_pack(+ "where do tools read file3",+ other_ranking(),+ 60_794,+ json!({"prefix_budget":56_000}),+ );+ assert_eq!(a["prefix_sha256"], b["prefix_sha256"]);+ assert_ne!(a["budget"], b["budget"]);+ assert!(!prefix_text(&a).contains("Budget:"));+ // Without it, the budget sizes the part.+ let c = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 60_794,+ json!({}),+ );+ assert_ne!(a["prefix_sha256"], c["prefix_sha256"]);+ // A fixed budget whose share does not fit steps down by 0.8 until it+ // does: 56,000, 44,800, 35,840, then 28,672 at the share 0.9.+ let d = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 30_000,+ json!({"prefix_budget":56_000}),+ );+ let e = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 28_672,+ json!({}),+ );+ assert_eq!(d["prefix_sha256"], e["prefix_sha256"]);+ assert!(d["tokens"].as_u64().unwrap() <= 30_000);+ assert!(Options::parse(&json!({"prefix_budget":100})).is_err());+ }+ /// When the provider counts more than the estimate, the calibrated+ /// budget falls below the fixed one's share: the repository part is then+ /// sized from a fixed step down, the same while the budget moves within+ /// the step.+ #[test]+ fn a_budget_below_the_fixed_share_steps_down_and_holds() {+ let nominal = json!({"prefix_budget":56_000});+ for (share, budgets) in [(0.9, [46_000, 49_500]), (1.0, [45_500, 48_000])] {+ let mut extra = nominal.clone();+ extra["prefix_share"] = json!(share);+ let packs: Vec<Value> = budgets+ .iter()+ .map(|&budget| {+ cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ budget,+ extra.clone(),+ )+ })+ .collect();+ assert_eq!(+ packs[0]["prefix_sha256"], packs[1]["prefix_sha256"],+ "{share}"+ );+ for (pack, budget) in packs.iter().zip(budgets) {+ assert!(pack["tokens"].as_u64().unwrap() <= budget as u64);+ assert!(pack["prefix_tokens"].as_u64().unwrap() <= (44_800.0 * share) as u64);+ }+ // The step's own budget gives the same part.+ let stepped = cache_pack(+ "how does F4x3 compute widgets",+ ranking(),+ 44_800,+ json!({"prefix_share":share}),+ );+ assert_eq!(+ stepped["prefix_sha256"], packs[0]["prefix_sha256"],+ "{share}"+ );+ }+ }+}diff --git a/crates/graphicle/src/computer.rs b/crates/graphicle/src/computer.rsnew file mode 100644index 0000000..d1fdb10--- /dev/null+++ b/crates/graphicle/src/computer.rs@@ -0,0 +1,1244 @@+//! Computer use (`graphicle see`): a model drives a browser that Graphicle+//! runs, through the computer tool of the Meta Model API's Responses API,+//! until the screen a task describes shows, or it cannot get there.+//!+//! The loop follows <https://dev.meta.ai/docs/computer-use.md>:+//! 1. The first request holds the task and a screenshot, with the tool+//! `{"type":"computer"}`.+//! 2. A reply's `computer_call` carries a batch of actions (`click`,+//! `double_click`, `drag`, `keypress`, `move`, `scroll`, `type`,+//! `screenshot`, `wait`) in the latest screenshot's pixels.+//! 3. The driver runs them in order, stops at the first that fails, and+//! takes one screenshot of the viewport ([`Screen`]).+//! 4. The screenshot goes back as a `computer_call_output`, with the safety+//! checks acknowledged for that call.+//! 5. A reply without a `computer_call` ends the run: its message is the+//! model's answer, a JSON object that says what the last screen shows.+//!+//! **State is replayed** (`store: false`): each request holds the first+//! message and every call and output so far, each call exactly as the model+//! returned it, so a `meta_safety_replay_receipt` goes back unchanged. The+//! requests ask for `include: ["reasoning.encrypted_content"]`, and the+//! reasoning items that come back with it go back, unchanged, before their+//! call, so the model keeps its reasoning from step to step.+//! Replay holds at most 29 pairs and `truncation` is not sent, so a run takes+//! at most [`MAX_STEPS`] model calls ([`DEFAULT_STEPS`] unless asked).+//!+//! **Safety:** a pending safety check stops the run, unless the person+//! passed `--acknowledge-safety-checks` (meant for their own sandboxed app+//! only); then each acknowledgement goes in the step log and on standard+//! error. The driver gets no model key. Graphicle's driver+//! (`demo/browser_driver.py`) loads only the app's origin.+//!+//! **Money:** every call goes in the spend log as `see`, one line per step,+//! under the profile's caps (`max_cost_per_call`, `max_cost_per_day`), with+//! each step's worst case (its input, none of it cached, and the step's+//! output limit) checked against the run's `--max-cost` too. A run needs a+//! priced profile, so that the caps can work.+//!+//! The pieces are public for other callers: [`body`], [`parse`],+//! [`verdict`], the [`Screen`] trait and the [`Driver`] process.+use crate::model::{self, Profile};+use crate::{Error, Result};+use serde_json::{Value, json};+use std::io::{BufRead, BufReader, Read, Write};+use std::path::{Path, PathBuf};+use std::process::{Child, ChildStdin, Command, Stdio};+use std::sync::mpsc;+use std::time::{Duration, Instant};++/// Model calls a run takes at most: stateless replay holds 29 call and+/// output pairs.+pub const MAX_STEPS: u64 = 29;+/// Model calls a run takes unless asked for another number.+pub const DEFAULT_STEPS: u64 = 25;+/// Output tokens a step may use unless asked for another number.+pub const DEFAULT_OUTPUT_TOKENS: u64 = 8_192;+/// Input tokens counted in a step's worst case for a screenshot of+/// [`IMAGE_AREA`] pixels (Meta documents about 1,300-1,500 for a 1280-pixel+/// image); a larger one counts in proportion to its area, a smaller one as+/// this much.+pub const IMAGE_TOKENS: u64 = 1_600;+/// The pixel area [`IMAGE_TOKENS`] stands for: 1280 by 800.+pub const IMAGE_AREA: u64 = 1_280 * 800;+/// Base64 characters of a data URL read at most to find its image's size+/// (a JPEG's size can sit after its other headers).+const HEADER_CHARS: usize = 87_384;+/// The largest screenshot the API takes, decoded.+pub const MAX_IMAGE_BYTES: usize = 25 << 20;+/// How long one model call may take.+const CALL_TIMEOUT: Duration = Duration::from_secs(300);+/// The longest line read from a driver (a base64 screenshot and its fields).+const MAX_REPLY_BYTES: u64 = 48 << 20;+/// Characters of the model's last answer kept in the report.+const ANSWER_CHARS: usize = 4_000;+/// The largest task file read.+const MAX_TASK_BYTES: u64 = 1 << 20;++/// The instructions of every step.+pub const INSTRUCTIONS: &str = "You test a web application in a browser for a developer, with the computer tool. The task gives an issue and what to look for. Each turn, look at the latest screenshot and act on it; coordinates are in that screenshot's pixels from its top left corner. Stay inside the application: do not open other sites, sign in, buy, download, upload or send anything. When the screen shows what the task asks you to look for, or you cannot get there, stop acting and reply with one JSON object and nothing else: {\"shown\": \"bug\" or \"expected\" or \"neither\", \"point\": {\"x\": X, \"y\": Y} or null, \"summary\": \"...\"}. shown says what the last screenshot shows: the issue's bug, the expected behaviour, or neither; point is a point on the element of the last screenshot that shows it; summary says in one or two sentences what you did and what the screen shows.";++/// What a run looks for.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LookFor {+ /// Reproduce the issue until its bug shows.+ Bug,+ /// Check that the expected behaviour shows now (after a fix).+ Expected,+}++impl LookFor {+ pub fn parse(text: &str) -> Result<Self> {+ match text {+ "bug" => Ok(Self::Bug),+ "expected" => Ok(Self::Expected),+ _ => Err(Error::bad("--look-for takes bug or expected")),+ }+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Self::Bug => "bug",+ Self::Expected => "expected",+ }+ }+}++/// The first message's text: what to look for, then the task.+pub fn task_text(look_for: LookFor, task: &str) -> String {+ let goal = match look_for {+ LookFor::Bug => {+ "Reproduce this issue: follow its steps in the application until its bug shows on the screen, then answer."+ }+ LookFor::Expected => {+ "The code was changed to fix this issue. Follow its steps in the application and check whether the screen now shows the expected behaviour instead of the bug, then answer."+ }+ };+ format!("{goal}\n\n{}", task.trim())+}++/// The computer tool, as Meta documents it.+pub fn tool() -> Value {+ json!({"type":"computer"})+}++/// The first input item: the task and the first screenshot.+pub fn first_message(text: &str, image_url: &str) -> Value {+ json!({"role":"user","content":[{"type":"input_text","text":text},+ {"type":"input_image","image_url":image_url}]})+}++/// The output of `call_id`: its screenshot and the safety checks+/// acknowledged for it.+pub fn call_output(call_id: &str, acknowledged: &[Value], image_url: &str) -> Value {+ json!({"type":"computer_call_output","call_id":call_id,+ "acknowledged_safety_checks":acknowledged,+ "output":{"type":"computer_screenshot","image_url":image_url}})+}++/// One step's request: the instructions, the replayed input, the computer+/// tool, no stored state, and the step's output limit. A profile with the+/// prompt cache on sends a cache key, as `ask --pack` does; its reasoning+/// effort goes in too.+pub fn body(+ profile: &Profile,+ instructions: &str,+ input: &[Value],+ output_tokens: usize,+ cache_key: Option<&str>,+) -> Value {+ let mut body = json!({"model":profile.model,"instructions":instructions,"input":input,+ "tools":[tool()],"store":false,"include":["reasoning.encrypted_content"],+ "max_output_tokens":output_tokens});+ if let Some(effort) = &profile.reasoning_effort {+ body["reasoning"] = json!({"effort":effort});+ }+ if let Some(key) = cache_key.filter(|_| model::prompt_cache_on(profile)) {+ body["prompt_cache_key"] = json!(key);+ body["prompt_cache_retention"] = json!(model::PROMPT_CACHE_RETENTION);+ }+ body+}++/// What one reply holds.+#[derive(Clone, Debug, Default)]+pub struct Turn {+ /// `completed`, `incomplete` or another status (`completed` when none).+ pub status: String,+ /// Why it is incomplete (`max_output_tokens`).+ pub incomplete: Option<String>,+ /// The error of a reply whose status is `failed` or `cancelled`.+ pub error: Option<String>,+ /// Its `computer_call` items, exactly as returned.+ pub calls: Vec<Value>,+ /// Its reasoning items that carry `encrypted_content`, exactly as+ /// returned, to replay before its calls (one without it cannot be+ /// replayed when nothing is stored).+ pub reasoning: Vec<Value>,+ /// The text of its messages.+ pub text: String,+ pub completion: model::Completion,+}++/// A reply of the Responses API with the computer tool.+pub fn parse(value: &Value, elapsed_ms: u64, fallback_model: &str) -> Turn {+ let mut turn = Turn {+ status: value["status"].as_str().unwrap_or("completed").to_string(),+ incomplete: value["incomplete_details"]["reason"]+ .as_str()+ .map(str::to_string),+ error: value["error"]["message"]+ .as_str()+ .or(value["error"].as_str())+ .map(str::to_string),+ ..Turn::default()+ };+ for item in value["output"].as_array().into_iter().flatten() {+ match item["type"].as_str() {+ Some("computer_call") => turn.calls.push(item.clone()),+ Some("reasoning") if item["encrypted_content"].is_string() => {+ turn.reasoning.push(item.clone())+ }+ Some("message") => {+ for part in item["content"].as_array().into_iter().flatten() {+ if part["type"] == "output_text"+ && let Some(text) = part["text"].as_str()+ {+ turn.text.push_str(text);+ }+ }+ }+ _ => {}+ }+ }+ let usage = &value["usage"];+ turn.completion = model::Completion {+ text: turn.text.clone(),+ input_tokens: usage["input_tokens"].as_u64(),+ output_tokens: usage["output_tokens"].as_u64(),+ cached_tokens: usage["input_tokens_details"]["cached_tokens"].as_u64(),+ reasoning_tokens: usage["output_tokens_details"]["reasoning_tokens"].as_u64(),+ elapsed_ms,+ model: value["model"]+ .as_str()+ .unwrap_or(fallback_model)+ .to_string(),+ };+ turn+}++/// A call's actions: its `actions`, or one `action`.+pub fn actions_of(call: &Value) -> Vec<Value> {+ match (&call["actions"], &call["action"]) {+ (Value::Array(actions), _) => actions.clone(),+ (_, action @ Value::Object(_)) => vec![action.clone()],+ _ => Vec::new(),+ }+}++/// A call's pending safety checks.+pub fn safety_checks(call: &Value) -> Vec<Value> {+ call["pending_safety_checks"]+ .as_array()+ .cloned()+ .unwrap_or_default()+}++/// One action in a few words, for the step log's readers.+pub fn describe(action: &Value) -> String {+ let at = |a: &Value| match (a["x"].as_f64(), a["y"].as_f64()) {+ (Some(x), Some(y)) => format!(" ({x}, {y})"),+ _ => String::new(),+ };+ let kind = action["type"].as_str().unwrap_or("?");+ match kind {+ "click" => {+ let button = action["button"].as_str().unwrap_or("left");+ if button == "left" {+ format!("click{}", at(action))+ } else {+ format!("{button} click{}", at(action))+ }+ }+ "double_click" | "move" => format!("{}{}", kind.replace('_', " "), at(action)),+ "scroll" => format!(+ "scroll{} by ({}, {})",+ at(action),+ action["scroll_x"].as_f64().unwrap_or(0.0),+ action["scroll_y"].as_f64().unwrap_or(0.0)+ ),+ "type" => {+ let text: String = action["text"]+ .as_str()+ .unwrap_or("")+ .chars()+ .take(60)+ .collect();+ format!("type {text:?}")+ }+ "keypress" => {+ let keys: Vec<&str> = action["keys"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect();+ format!("keys {}", keys.join("+"))+ }+ "drag" => format!(+ "drag through {} points",+ action["path"].as_array().map_or(0, Vec::len)+ ),+ other => other.to_string(),+ }+}++/// The model's answer at the end of a run.+#[derive(Clone, Debug, PartialEq)]+pub struct Verdict {+ /// `bug`, `expected` or `neither`.+ pub shown: String,+ /// A point on the element that shows it, inside the last screenshot.+ pub point: Option<(u32, u32)>,+ pub summary: String,+}++/// The answer in the model's last text, checked against the last+/// screenshot's size: none when it is not the JSON object asked for.+pub fn verdict(text: &str, width: u32, height: u32) -> Option<Verdict> {+ let value = crate::long_context::json_in(text).ok()?;+ let shown = value["shown"].as_str()?.trim().to_ascii_lowercase();+ if !matches!(shown.as_str(), "bug" | "expected" | "neither") {+ return None;+ }+ let point = match (value["point"]["x"].as_f64(), value["point"]["y"].as_f64()) {+ (Some(x), Some(y))+ if x >= 0.0 && y >= 0.0 && x < f64::from(width) && y < f64::from(height) =>+ {+ Some((x as u32, y as u32))+ }+ _ => None,+ };+ let summary = value["summary"].as_str().unwrap_or("").trim().to_string();+ Some(Verdict {+ shown,+ point,+ summary,+ })+}++// ---------------------------------------------------------------- screen++/// The browser (or desktop) a run drives: it answers one request at a time+/// with one reply, in the driver protocol of `demo/browser_driver.py`:+/// `{"op":"screenshot"}` and `{"op":"act","actions":[...]}` get+/// `{"ok":true,"done":N,"error":...,"url":...,"blocked":N,"png":"<base64>"}`.+pub trait Screen {+ fn ask(&mut self, request: &Value) -> Result<Value>;+}++/// A screenshot from a driver's reply.+#[derive(Clone, Debug)]+pub struct Shot {+ pub bytes: Vec<u8>,+ pub image: crate::pixel::ImageInfo,+ /// The reply without its image: `done`, `error`, `url`, `blocked`.+ pub reply: Value,+}++impl Shot {+ pub fn data_url(&self) -> String {+ crate::pixel::data_url(&self.image, &self.bytes)+ }+}++/// The screenshot in a driver's reply, checked: a PNG or JPEG of at most+/// [`MAX_IMAGE_BYTES`].+pub fn shot_of(mut reply: Value) -> Result<Shot> {+ use base64::Engine as _;+ if reply["ok"] != true {+ return Err(Error::bad(format!(+ "The driver refused the request: {}",+ reply["error"].as_str().unwrap_or("no reason given")+ )));+ }+ let encoded = reply+ .get("png")+ .or_else(|| reply.get("image"))+ .and_then(Value::as_str)+ .ok_or_else(|| Error::bad("The driver's reply holds no screenshot"))?;+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(encoded.trim())+ .map_err(|_| Error::bad("The driver's screenshot is not base64"))?;+ if bytes.len() > MAX_IMAGE_BYTES {+ return Err(Error::bad("The driver's screenshot is over 25 MiB"));+ }+ let image = crate::pixel::image_info(&bytes)+ .filter(|i| matches!(i.mime, "image/png" | "image/jpeg"))+ .ok_or_else(|| Error::bad("The driver's screenshot is not a PNG or JPEG"))?;+ if let Some(fields) = reply.as_object_mut() {+ fields.remove("png");+ fields.remove("image");+ fields.remove("ok");+ }+ Ok(Shot {+ bytes,+ image,+ reply,+ })+}++/// A driver process: a command run with `sh -c` (`cmd /C` on Windows),+/// one JSON request per line on its standard input and one reply per line+/// on its standard output; its standard error goes to a log file. It gets+/// no model key. Dropping it asks it to close, then stops it.+pub struct Driver {+ child: Child,+ stdin: Option<ChildStdin>,+ replies: mpsc::Receiver<std::io::Result<String>>,+ timeout: Duration,+}++impl Driver {+ pub fn start(+ command: &str,+ log: &Path,+ timeout: Duration,+ scrub: &crate::fix::Scrub,+ ) -> Result<Self> {+ #[cfg(unix)]+ let mut process = {+ let mut c = Command::new("sh");+ c.arg("-c").arg(command);+ c+ };+ #[cfg(not(unix))]+ let mut process = {+ let mut c = Command::new("cmd");+ c.arg("/C").arg(command);+ c+ };+ let errors = std::fs::File::create(log)?;+ process+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::from(errors));+ for name in &scrub.remove {+ process.env_remove(name);+ }+ let mut child = process+ .spawn()+ .map_err(|e| Error::bad(format!("Cannot start the driver: {e}")))?;+ let stdin = child.stdin.take();+ let stdout = child+ .stdout+ .take()+ .ok_or_else(|| Error::bad("The driver has no standard output"))?;+ let (send, replies) = mpsc::channel();+ std::thread::spawn(move || {+ let mut reader = BufReader::new(stdout);+ loop {+ let mut line = String::new();+ match (&mut reader).take(MAX_REPLY_BYTES).read_line(&mut line) {+ Ok(0) => break,+ Ok(_) => {+ if send.send(Ok(line)).is_err() {+ break;+ }+ }+ Err(error) => {+ let _ = send.send(Err(error));+ break;+ }+ }+ }+ });+ Ok(Self {+ child,+ stdin,+ replies,+ timeout,+ })+ }+}++impl Screen for Driver {+ fn ask(&mut self, request: &Value) -> Result<Value> {+ let stdin = self+ .stdin+ .as_mut()+ .ok_or_else(|| Error::bad("The driver is closed"))?;+ writeln!(stdin, "{request}")+ .and_then(|()| stdin.flush())+ .map_err(|e| Error::bad(format!("The driver stopped reading: {e}")))?;+ match self.replies.recv_timeout(self.timeout) {+ Ok(Ok(line)) => serde_json::from_str(line.trim())+ .map_err(|_| Error::bad("The driver's reply is not one JSON object on a line")),+ Ok(Err(error)) => Err(Error::bad(format!("Cannot read the driver: {error}"))),+ Err(mpsc::RecvTimeoutError::Timeout) => Err(Error::bad(format!(+ "The driver did not answer within {} s",+ self.timeout.as_secs()+ ))),+ Err(mpsc::RecvTimeoutError::Disconnected) => {+ Err(Error::bad("The driver ended; its log says why"))+ }+ }+ }+}++impl Drop for Driver {+ fn drop(&mut self) {+ if let Some(mut stdin) = self.stdin.take() {+ let _ = writeln!(stdin, "{}", json!({"op":"close"}));+ }+ let until = Instant::now() + Duration::from_secs(10);+ while Instant::now() < until {+ if matches!(self.child.try_wait(), Ok(Some(_))) {+ return;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++// ---------------------------------------------------------------- the run++/// `graphicle see`'s arguments.+#[derive(clap::Args, Clone, Debug)]+pub struct Args {+ /// The task: the issue, with its steps and what goes wrong; `-` reads it+ /// from standard input.+ #[arg(required_unless_present = "task_file", conflicts_with = "task_file")]+ pub task: Option<String>,+ /// Read the task from this file (at most 1 MiB).+ #[arg(long, value_name = "FILE")]+ pub task_file: Option<PathBuf>,+ /// The driver: a command, run with `sh -c`, that speaks the driver+ /// protocol on its standard input and output, such as+ /// `python3 demo/browser_driver.py --url http://HOST:PORT/`.+ #[arg(long, value_name = "CMD")]+ pub driver: String,+ /// What the run looks for: the issue's bug, or the expected behaviour+ /// (after a fix).+ #[arg(long, value_parser = ["bug", "expected"], default_value = "bug")]+ pub look_for: String,+ /// Model calls at most, 1 to 29 (stateless replay holds 29 pairs).+ #[arg(long, default_value_t = DEFAULT_STEPS, value_parser = clap::value_parser!(u64).range(1..=MAX_STEPS))]+ pub steps: u64,+ /// The run's cap in US dollars at the profile's price: a step whose+ /// worst case would bring the run over it is not sent.+ #[arg(long, value_name = "USD", default_value_t = 3.0)]+ pub max_cost: f64,+ /// Output tokens a step may use at most.+ #[arg(long, value_name = "TOKENS", default_value_t = DEFAULT_OUTPUT_TOKENS, value_parser = clap::value_parser!(u64).range(256..=131_072))]+ pub output_tokens: u64,+ /// Acknowledge the model's pending safety checks, each one logged,+ /// instead of stopping the run. Only on your own sandboxed app.+ #[arg(long)]+ pub acknowledge_safety_checks: bool,+ /// The folder for the screenshots, the step log and the driver's log+ /// [default: graphicle-see-<time> in this folder].+ #[arg(long, value_name = "DIR")]+ pub out: Option<PathBuf>,+ /// Seconds the driver may take for one request.+ #[arg(long, value_name = "SECONDS", default_value_t = 120, value_parser = clap::value_parser!(u64).range(1..=3_600))]+ pub driver_timeout: u64,+ /// The configured model profile: Muse Wonder (recommended) or Muse+ /// Spark 1.3 on the Meta Model API [default: the answer model].+ #[arg(long, value_name = "NAME")]+ pub model: Option<String>,+ /// Print the report as JSON (the default when the output is not a+ /// terminal).+ #[arg(long)]+ pub json: bool,+}++/// The task's text from the arguments.+fn task_of(args: &Args) -> Result<String> {+ let text = match (&args.task, &args.task_file) {+ (Some(text), None) if text == "-" => {+ let mut text = String::new();+ std::io::stdin()+ .take(MAX_TASK_BYTES)+ .read_to_string(&mut text)?;+ text+ }+ (Some(text), None) => text.clone(),+ (None, Some(path)) => {+ let mut text = String::new();+ std::fs::File::open(path)+ .map_err(|e| Error::bad(format!("Cannot read {}: {e}", path.display())))?+ .take(MAX_TASK_BYTES)+ .read_to_string(&mut text)?;+ text+ }+ _ => return Err(Error::bad("Give the task, or --task-file FILE")),+ };+ if text.trim().is_empty() {+ return Err(Error::bad("The task is empty"));+ }+ Ok(text)+}++/// A step's input tokens at most: the text at three bytes a token, and+/// [`image_tokens`] for each screenshot.+/// The input tokens a step's worst case counts for an image data URL: its+/// area over [`IMAGE_AREA`] times [`IMAGE_TOKENS`], at least+/// [`IMAGE_TOKENS`]; an image whose size cannot be read counts as one of+/// 2560 by 1600 pixels.+pub fn image_tokens(url: &str) -> u64 {+ use base64::Engine as _;+ let payload = url.split_once(',').map_or("", |(_, data)| data);+ let size = [64, HEADER_CHARS].iter().find_map(|&chars| {+ let head = &payload[..payload.len().min(chars) / 4 * 4];+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(head)+ .ok()?;+ crate::pixel::image_info(&bytes).map(|i| u64::from(i.width) * u64::from(i.height))+ });+ let area = size.unwrap_or(4 * IMAGE_AREA);+ (IMAGE_TOKENS * area).div_ceil(IMAGE_AREA).max(IMAGE_TOKENS)+}++pub fn input_estimate(instructions: &str, input: &[Value]) -> u64 {+ fn walk(value: &Value, images: &mut u64, bytes: &mut u64) {+ match value {+ Value::String(text) if text.starts_with("data:image/") => *images += image_tokens(text),+ Value::String(text) => *bytes += text.len() as u64,+ Value::Array(items) => items.iter().for_each(|v| walk(v, images, bytes)),+ Value::Object(fields) => {+ for (key, v) in fields {+ *bytes += key.len() as u64 + 4;+ walk(v, images, bytes);+ }+ }+ other => *bytes += other.to_string().len() as u64,+ }+ }+ let mut images = 0u64;+ let mut bytes = instructions.len() as u64;+ input.iter().for_each(|v| walk(v, &mut images, &mut bytes));+ bytes.div_ceil(3) + images+}++/// What a run looked for, found and spent.+struct Run<'a> {+ store: &'a crate::store::Store,+ name: String,+ /// The profile with the step's output limit, for the caps.+ profile: Profile,+ out: PathBuf,+ max_cost: f64,+ spent: f64,+ calls: usize,+ human: bool,+ cache_key: Option<String>,+}++impl Run<'_> {+ fn save(&self, file: &str, bytes: &[u8]) -> Result<()> {+ std::fs::write(self.out.join(file), bytes)?;+ Ok(())+ }++ /// One model call under the caps: the reply (or why there is none) and+ /// its log entry; `Err` when a cap refuses it.+ async fn call(&mut self, step: u64, input: &[Value]) -> Result<(Result<Turn>, Value)> {+ let estimate = input_estimate(INSTRUCTIONS, input);+ let price = self.profile.price.clone().ok_or_else(|| {+ Error::bad("graphicle see needs the profile's price to keep the run under --max-cost")+ })?;+ let worst = price.cost(estimate, 0, self.profile.output_limit as u64);+ if self.spent + worst > self.max_cost {+ return Err(Error::bad(format!(+ "Refused before sending step {step}: the run has cost {} and this step could add up to {} ({} input tokens, none cached, and {} output tokens at most), over --max-cost {}",+ crate::spend::usd(self.spent),+ crate::spend::usd(worst),+ crate::terminal::count(estimate),+ crate::terminal::count(self.profile.output_limit as u64),+ crate::spend::usd(self.max_cost)+ )));+ }+ let held = crate::spend::reserve(+ &self.store.directory,+ &self.name,+ &self.profile,+ estimate,+ chrono::Utc::now(),+ )?;+ let request = body(+ &self.profile,+ INSTRUCTIONS,+ input,+ self.profile.output_limit,+ self.cache_key.as_deref(),+ );+ let start = Instant::now();+ let reply = model::post_json(&self.profile, "responses", &request, CALL_TIMEOUT).await;+ let elapsed = start.elapsed().as_millis() as u64;+ let turn = reply.map(|value| parse(&value, elapsed, &self.profile.model));+ let completion = match &turn {+ Ok(turn) => Ok(turn.completion.clone()),+ Err(error) => Err(Error::bad(error.message.clone())),+ };+ let call = crate::spend::Call {+ command: "see",+ profile: &self.name,+ settings: &self.profile,+ project: None,+ commit: None,+ prompt_cache_key: self.cache_key.as_deref(),+ };+ let mut entry = crate::spend::entry(&call, &completion, chrono::Utc::now());+ entry["step"] = json!(step);+ if let Err(error) = crate::spend::settle(&self.store.directory, &held, &mut entry) {+ eprintln!("graphicle: could not write the spend log: {error}");+ }+ self.calls += 1;+ self.spent += entry["cost_usd"]+ .as_f64()+ .or(entry["worst_cost_usd"].as_f64())+ .unwrap_or(0.0);+ Ok((turn, entry))+ }+}++/// The report as a person reads it.+fn report_text(report: &Value) -> String {+ let mut out = format!(+ "Result: {} after {} model calls ({} at the configured price; cap {}).\n",+ report["result"].as_str().unwrap_or("?"),+ report["calls"],+ crate::spend::usd(report["cost_usd"].as_f64().unwrap_or(0.0)),+ crate::spend::usd(report["max_cost_usd"].as_f64().unwrap_or(0.0))+ );+ if let Some(summary) = report["summary"].as_str().filter(|s| !s.is_empty()) {+ out.push_str(&format!("The model: {summary}\n"));+ }+ if let (Some(x), Some(y)) = (report["point"]["x"].as_u64(), report["point"]["y"].as_u64()) {+ out.push_str(&format!(+ "It points at ({x}, {y}) on {}: `graphicle pixel {} --at {x},{y}` finds the code that draws it.\n",+ report["last_screenshot"].as_str().unwrap_or(""),+ report["last_screenshot_path"].as_str().unwrap_or("")+ ));+ }+ for step in report["steps"].as_array().into_iter().flatten() {+ let actions: Vec<String> = step["actions"]+ .as_array()+ .into_iter()+ .flatten()+ .map(describe)+ .collect();+ out.push_str(&format!(+ " {:>2}. {}{}\n",+ step["step"],+ if actions.is_empty() {+ "answer".to_string()+ } else {+ actions.join(", ")+ },+ step["driver"]["error"]+ .as_str()+ .map(|e| format!(" (stopped: {e})"))+ .unwrap_or_default()+ ));+ }+ for ack in report["acknowledged"].as_array().into_iter().flatten() {+ out.push_str(&format!(+ "Acknowledged safety check at step {}: {} ({})\n",+ ack["step"],+ ack["check"]["message"].as_str().unwrap_or(""),+ ack["check"]["code"].as_str().unwrap_or("")+ ));+ }+ out.push_str(&format!(+ "Screenshots and the step log: {}\n",+ report["out"].as_str().unwrap_or("")+ ));+ out+}++/// `graphicle see`: run the loop and report.+pub async fn see(store: &crate::store::Store, config: &model::Config, args: Args) -> Result<()> {+ let look_for = LookFor::parse(&args.look_for)?;+ let task = task_of(&args)?;+ if !(args.max_cost.is_finite() && args.max_cost > 0.0) {+ return Err(Error::bad(+ "--max-cost must be a positive number of US dollars",+ ));+ }+ let configuration = match crate::local::session(store, false) {+ Ok(session) => crate::settings::configuration(store, &session.workspace, config)?,+ Err(_) => config.clone(),+ };+ let (name, profile) = configuration+ .profile(args.model.as_deref())+ .map_err(|_| {+ Error::bad(match &args.model {+ Some(name) => {+ format!("No model profile named {name}: graphicle config show lists them")+ }+ None => "No answer model: choose Muse Wonder with `graphicle config set model meta:muse-wonder-1.0`".into(),+ })+ })?;+ let (name, mut profile) = (name.to_string(), profile.clone());+ if !matches!(profile.protocol.as_str(), "responses" | "azure_responses") {+ return Err(Error::bad(+ "Computer use needs a Responses API profile: Muse Wonder or Muse Spark 1.3 on the Meta Model API",+ ));+ }+ if profile.price.is_none() {+ return Err(Error::bad(format!(+ "graphicle see needs the profile's price to keep the run under --max-cost: set models.{name}.price"+ )));+ }+ profile.output_limit = (args.output_tokens as usize).min(profile.output_limit.max(256));+ let human = crate::terminal::human(args.json);+ let started = chrono::Utc::now();+ let out = args.out.clone().unwrap_or_else(|| {+ PathBuf::from(format!(+ "graphicle-see-{}",+ started.format("%Y%m%dT%H%M%SZ")+ ))+ });+ std::fs::create_dir_all(&out)+ .map_err(|e| Error::bad(format!("Cannot make {}: {e}", out.display())))?;+ let out = out.canonicalize().unwrap_or(out);+ let scrub = crate::fix::Scrub::of(&configuration);+ let mut screen = Driver::start(+ &args.driver,+ &out.join("driver.log"),+ Duration::from_secs(args.driver_timeout),+ &scrub,+ )?;+ let cache_key = format!(+ "graphicle-see:{}-{}",+ started.format("%Y%m%dT%H%M%S"),+ std::process::id()+ );+ let mut run = Run {+ store,+ name,+ profile,+ out: out.clone(),+ max_cost: args.max_cost,+ spent: 0.0,+ calls: 0,+ human,+ cache_key: Some(cache_key),+ };+ let report = drive(+ &mut run,+ &mut screen,+ look_for,+ &task,+ args.steps,+ args.acknowledge_safety_checks,+ )+ .await?;+ drop(screen);+ std::fs::write(+ out.join("see.json"),+ serde_json::to_string_pretty(&report)? + "\n",+ )?;+ if human {+ print!("{}", crate::fix::printable(&report_text(&report)));+ } else {+ println!("{}", serde_json::to_string_pretty(&report)?);+ }+ let wanted = match look_for {+ LookFor::Bug => "reproduced",+ LookFor::Expected => "expected shown",+ };+ match report["result"].as_str() {+ Some(result) if result == wanted => Ok(()),+ other => Err(Error::bad(format!(+ "see ended with the result {:?}; the screenshots and step log are in {}",+ other.unwrap_or("unknown"),+ out.display()+ ))),+ }+}++/// The loop itself, on any [`Screen`]: the report.+async fn drive(+ run: &mut Run<'_>,+ screen: &mut dyn Screen,+ look_for: LookFor,+ task: &str,+ steps: u64,+ acknowledge: bool,+) -> Result<Value> {+ let mut log = std::fs::File::create(run.out.join("steps.jsonl"))?;+ let first = shot_of(screen.ask(&json!({"op":"screenshot"}))?)?;+ run.save("step-00.png", &first.bytes)?;+ let size = (first.image.width, first.image.height);+ let mut input = vec![first_message(&task_text(look_for, task), &first.data_url())];+ let mut last = ("step-00.png".to_string(), first.image);+ let mut records: Vec<Value> = Vec::new();+ let mut acknowledged_all: Vec<Value> = Vec::new();+ let mut usage: Vec<Value> = Vec::new();+ let mut result = "step cap reached".to_string();+ let mut stopped: Option<String> = None;+ let mut answer: Option<(String, Option<Verdict>)> = None;+ 'steps: for step in 1..=steps {+ let (turn, entry) = match run.call(step, &input).await {+ Ok(called) => called,+ Err(refused) => {+ result = "refused by a cap".into();+ stopped = Some(refused.message);+ break;+ }+ };+ usage.push(entry.clone());+ let turn = match turn {+ Ok(turn) => turn,+ Err(error) => {+ result = "provider error".into();+ stopped = Some(error.message);+ break;+ }+ };+ if matches!(turn.status.as_str(), "failed" | "cancelled") {+ result = "provider error".into();+ stopped = Some(format!(+ "The reply's status is {}: {}",+ turn.status,+ turn.error.as_deref().unwrap_or("no reason given")+ ));+ break;+ }+ if turn.status == "incomplete" {+ result = "incomplete".into();+ stopped = Some(format!(+ "The reply stopped early ({}): raise --output-tokens",+ turn.incomplete.as_deref().unwrap_or("no reason given")+ ));+ break;+ }+ if turn.calls.is_empty() {+ let verdict = verdict(&turn.text, last.1.width, last.1.height);+ result = match (verdict.as_ref().map(|v| v.shown.as_str()), look_for) {+ (Some("bug"), LookFor::Bug) => "reproduced",+ (Some("expected"), LookFor::Expected) => "expected shown",+ (Some("bug"), LookFor::Expected) => "bug still shown",+ (Some(_), _) => "not shown",+ (None, _) => "unclear answer",+ }+ .to_string();+ let record = json!({"step":step,"actions":[],"answer":true,"usage":entry});+ writeln!(log, "{record}")?;+ records.push(record);+ answer = Some((turn.text.clone(), verdict));+ break;+ }+ for (index, call) in turn.calls.iter().enumerate() {+ let call_id = call["call_id"].as_str().unwrap_or("").to_string();+ if call_id.is_empty() {+ result = "provider error".into();+ stopped = Some("A computer call came without a call_id".into());+ break 'steps;+ }+ let actions = actions_of(call);+ let checks = safety_checks(call);+ if !checks.is_empty() && !acknowledge {+ result = "stopped at a safety check".into();+ stopped = Some(format!(+ "The model asked to acknowledge {} safety check(s) ({}); rerun with --acknowledge-safety-checks only on your own sandboxed app",+ checks.len(),+ checks+ .iter()+ .map(|c| c["code"].as_str().unwrap_or("?").to_string())+ .collect::<Vec<_>>()+ .join(", ")+ ));+ let record = json!({"step":step,"call_id":call_id,"actions":actions,+ "safety_checks":checks,"acknowledged":[],"usage":entry});+ writeln!(log, "{record}")?;+ records.push(record);+ break 'steps;+ }+ for check in &checks {+ eprintln!(+ "graphicle: step {step}: acknowledged the safety check {} ({}) as --acknowledge-safety-checks asks",+ check["code"].as_str().unwrap_or("?"),+ crate::fix::printable(check["message"].as_str().unwrap_or(""))+ );+ acknowledged_all.push(json!({"step":step,"call_id":call_id,"check":check}));+ }+ let shot = match screen+ .ask(&json!({"op":"act","actions":actions}))+ .and_then(shot_of)+ {+ Ok(shot) => shot,+ Err(error) => {+ result = "driver error".into();+ stopped = Some(error.message);+ let record = json!({"step":step,"call_id":call_id,"actions":actions,+ "safety_checks":checks,"usage":entry,"driver":{"error":stopped}});+ writeln!(log, "{record}")?;+ records.push(record);+ break 'steps;+ }+ };+ if (shot.image.width, shot.image.height) != size {+ eprintln!(+ "graphicle: step {step}: the screenshot's size changed from {}x{} to {}x{}",+ size.0, size.1, shot.image.width, shot.image.height+ );+ }+ let file = format!("step-{step:02}.png");+ run.save(&file, &shot.bytes)?;+ if run.human {+ eprintln!(+ "graphicle: step {step}: {} ({})",+ actions.iter().map(describe).collect::<Vec<_>>().join(", "),+ crate::spend::line(&entry)+ );+ }+ let record = json!({"step":step,"call_id":call_id,"actions":actions,+ "safety_checks":checks,"acknowledged":if checks.is_empty() {json!([])} else {json!(checks)},+ "driver":shot.reply,"screenshot":file,"usage":entry});+ writeln!(log, "{record}")?;+ records.push(record);+ if index == 0 {+ input.extend(turn.reasoning.iter().cloned());+ }+ input.push(call.clone());+ input.push(call_output(&call_id, &checks, &shot.data_url()));+ last = (file, shot.image);+ }+ }+ if result == "step cap reached" && stopped.is_none() {+ stopped = Some(format!(+ "The model was still acting after {steps} calls (--steps)"+ ));+ }+ let (text, verdict) = answer.unwrap_or_default();+ let point = verdict+ .as_ref()+ .and_then(|v| v.point)+ .map(|(x, y)| json!({"x":x,"y":y}));+ let cost: f64 = usage.iter().filter_map(|u| u["cost_usd"].as_f64()).sum();+ let tokens = |field: &str| -> u64 { usage.iter().filter_map(|u| u[field].as_u64()).sum() };+ Ok(json!({+ "result": result,+ "look_for": look_for.as_str(),+ "shown": verdict.as_ref().map(|v| v.shown.clone()),+ "point": point,+ "summary": verdict.as_ref().map(|v| v.summary.clone()).unwrap_or_default(),+ "answer": text.chars().take(ANSWER_CHARS).collect::<String>(),+ "stopped": stopped,+ "task": task,+ "model": run.profile.model,+ "profile": run.name,+ "calls": run.calls,+ "cost_usd": cost,+ "max_cost_usd": run.max_cost,+ "input_tokens": tokens("input_tokens"),+ "cached_tokens": tokens("cached_tokens"),+ "output_tokens": tokens("output_tokens"),+ "first_screenshot": "step-00.png",+ "last_screenshot": last.0,+ "last_screenshot_path": run.out.join(&last.0),+ "screen": {"width": size.0, "height": size.1},+ "acknowledged": acknowledged_all,+ "steps": records,+ "out": run.out,+ }))+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A 1x1 PNG.+ const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++ fn profile() -> Profile {+ serde_json::from_value(+ json!({"protocol":"responses","base_url":"https://api.meta.ai/v1",+ "model":"muse-wonder-1.0","key_env":"MODEL_API_KEY",+ "price":{"input":4.0,"cached_input":0.2,"output":20.0}}),+ )+ .unwrap()+ }++ #[test]+ fn the_request_is_the_documented_shape_and_replays_calls_unchanged() {+ let call = json!({"type":"computer_call","id":"cc_1","call_id":"call_1",+ "actions":[{"type":"click","button":"left","x":4,"y":5}],+ "pending_safety_checks":[],"status":"completed","meta_safety_replay_receipt":"r1"});+ let input = vec![+ first_message("Reproduce it.", "data:image/png;base64,AAA"),+ call.clone(),+ call_output("call_1", &[], "data:image/png;base64,BBB"),+ ];+ let body = body(+ &profile(),+ INSTRUCTIONS,+ &input,+ 8192,+ Some("graphicle-see:x"),+ );+ assert_eq!(body["model"], "muse-wonder-1.0");+ assert_eq!(body["tools"], json!([{"type":"computer"}]));+ assert_eq!(body["store"], false);+ assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));+ assert_eq!(body["max_output_tokens"], 8192);+ assert!(body.get("truncation").is_none());+ assert!(body.get("previous_response_id").is_none());+ assert_eq!(+ body["input"][1], call,+ "a call goes back exactly as returned"+ );+ assert_eq!(+ body["input"][2],+ json!({"type":"computer_call_output","call_id":"call_1",+ "acknowledged_safety_checks":[],+ "output":{"type":"computer_screenshot","image_url":"data:image/png;base64,BBB"}})+ );+ assert_eq!(+ body["input"][0]["content"][1],+ json!({"type":"input_image","image_url":"data:image/png;base64,AAA"})+ );+ // The Meta Model API takes the prompt cache key; another provider's+ // profile does not send it.+ assert_eq!(body["prompt_cache_key"], "graphicle-see:x");+ let mut other = profile();+ other.base_url = "https://example.com/v1".into();+ let plain = super::body(&other, INSTRUCTIONS, &input, 8192, Some("k"));+ assert!(plain.get("prompt_cache_key").is_none());+ }++ #[test]+ fn replies_give_calls_messages_status_and_usage() {+ let reply = json!({"model":"muse-wonder-1.0","status":"completed","output":[+ {"type":"reasoning","id":"rs_1"},+ {"type":"computer_call","id":"cc_1","call_id":"call_1",+ "actions":[{"type":"type","text":"hello"},{"type":"keypress","keys":["CTRL","A"]}],+ "pending_safety_checks":[{"id":"csc_1","code":"malicious_instructions","message":"Careful."}]}],+ "usage":{"input_tokens":3000,"output_tokens":90,+ "input_tokens_details":{"cached_tokens":1500},+ "output_tokens_details":{"reasoning_tokens":40}}});+ let turn = parse(&reply, 12, "x");+ assert_eq!(turn.calls.len(), 1);+ // A reasoning item without encrypted content cannot be replayed.+ assert!(turn.reasoning.is_empty());+ let encrypted = json!({"output":[{"type":"reasoning","id":"rs_2",+ "summary":[{"type":"summary_text","text":"The menu."}],"encrypted_content":"abc"},+ {"type":"computer_call","call_id":"c","actions":[]}]});+ assert_eq!(+ parse(&encrypted, 1, "x").reasoning,+ vec![encrypted["output"][0].clone()]+ );+ assert_eq!(actions_of(&turn.calls[0]).len(), 2);+ assert_eq!(+ safety_checks(&turn.calls[0])[0]["code"],+ "malicious_instructions"+ );+ assert_eq!(turn.completion.input_tokens, Some(3000));+ assert_eq!(turn.completion.cached_tokens, Some(1500));+ assert_eq!(turn.completion.reasoning_tokens, Some(40));+ assert_eq!(turn.completion.model, "muse-wonder-1.0");+ let done = json!({"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},+ "output":[{"type":"message","content":[{"type":"output_text","text":"{\"shown\":"}]}]});+ let turn = parse(&done, 1, "muse-spark-1.3");+ assert!(turn.calls.is_empty());+ assert_eq!(turn.status, "incomplete");+ assert_eq!(turn.incomplete.as_deref(), Some("max_output_tokens"));+ assert_eq!(turn.completion.model, "muse-spark-1.3");+ let failed = parse(+ &json!({"status":"failed","error":{"message":"overloaded"},"output":[]}),+ 1,+ "x",+ );+ assert_eq!(+ (failed.status.as_str(), failed.error.as_deref()),+ ("failed", Some("overloaded"))+ );+ // One `action` instead of a batch.+ let single = json!({"type":"computer_call","call_id":"c","action":{"type":"wait"}});+ assert_eq!(actions_of(&single), vec![json!({"type":"wait"})]);+ }++ #[test]+ fn the_answer_is_checked_against_the_last_screenshot() {+ let v = verdict(+ "Done.\n```json\n{\"shown\":\"Bug\",\"point\":{\"x\":12,\"y\":30},\"summary\":\"The menu stays open.\"}\n```",+ 100,+ 50,+ )+ .unwrap();+ assert_eq!(v.shown, "bug");+ assert_eq!(v.point, Some((12, 30)));+ assert_eq!(v.summary, "The menu stays open.");+ let outside = verdict(+ "{\"shown\":\"expected\",\"point\":{\"x\":120,\"y\":3}}",+ 100,+ 50,+ )+ .unwrap();+ assert_eq!(outside.point, None);+ assert!(verdict("{\"shown\":\"maybe\"}", 100, 50).is_none());+ assert!(verdict("no JSON here", 100, 50).is_none());+ }++ #[test]+ fn shots_are_checked_and_estimates_count_images() {+ use base64::Engine as _;+ let shot =+ shot_of(json!({"ok":true,"done":1,"error":null,"url":"http://a/","png":PNG})).unwrap();+ assert_eq!((shot.image.width, shot.image.height), (1, 1));+ assert!(shot.data_url().starts_with("data:image/png;base64,iVBOR"));+ assert!(shot.reply.get("png").is_none());+ assert_eq!(shot.reply["url"], "http://a/");+ assert!(shot_of(json!({"ok":false,"error":"no page"})).is_err());+ assert!(shot_of(json!({"ok":true,"png":"bm90IGFuIGltYWdl"})).is_err());+ let png = format!("data:image/png;base64,{PNG}");+ let input = vec![first_message("abc", &png), call_output("c", &[], &png)];+ // Sizes come from the image's header: a 1x1 PNG counts the floor, a+ // 2560x1600 one four times it, an unreadable one as 2560x1600.+ assert_eq!(+ image_tokens(&format!("data:image/png;base64,{PNG}")),+ IMAGE_TOKENS+ );+ let mut big = base64::engine::general_purpose::STANDARD+ .decode(PNG)+ .unwrap();+ big[16..20].copy_from_slice(&2560u32.to_be_bytes());+ big[20..24].copy_from_slice(&1600u32.to_be_bytes());+ let big = base64::engine::general_purpose::STANDARD.encode(&big);+ assert_eq!(+ image_tokens(&format!("data:image/png;base64,{big}")),+ 4 * IMAGE_TOKENS+ );+ assert_eq!(image_tokens("data:image/png;base64,AAAA"), 4 * IMAGE_TOKENS);+ let estimate = input_estimate("", &input);+ assert!((2 * IMAGE_TOKENS..2 * IMAGE_TOKENS + 200).contains(&estimate));+ }++ #[test]+ fn actions_read_as_words() {+ assert_eq!(+ describe(&json!({"type":"click","button":"left","x":4,"y":5})),+ "click (4, 5)"+ );+ assert_eq!(+ describe(&json!({"type":"click","button":"right","x":4,"y":5})),+ "right click (4, 5)"+ );+ assert_eq!(+ describe(&json!({"type":"keypress","keys":["CTRL","A"]})),+ "keys CTRL+A"+ );+ assert_eq!(describe(&json!({"type":"type","text":"hi"})), "type \"hi\"");+ assert_eq!(+ describe(&json!({"type":"scroll","x":1,"y":2,"scroll_x":0,"scroll_y":300})),+ "scroll (1, 2) by (0, 300)"+ );+ assert_eq!(describe(&json!({"type":"wait"})), "wait");+ }+}diff --git a/crates/graphicle/src/disconnect.rs b/crates/graphicle/src/disconnect.rsindex f6cf6fa..2fa5ffa 100644--- a/crates/graphicle/src/disconnect.rs+++ b/crates/graphicle/src/disconnect.rs@@ -51,7 +51,7 @@ pub fn disconnect_report(let client = match options.client.as_deref() {Some(word) => Some(agent_detect::parse(word).ok_or_else(|| {Error::bad(format!(- "Unknown client {word}: choose claude-code, codex, cursor, vscode or claude (Claude Desktop)"+ "Unknown client {word}: choose claude-code, codex, cursor, vscode, claude (Claude Desktop) or muse (Muse Code)"))})?),None => None,@@ -78,6 +78,7 @@ pub fn disconnect_report(|change: &Change| client.is_none_or(|client| change.client.as_deref() == Some(client));let mine = |change: &Change| {options.all+ || (change.kind == "muse-plugin" && client == Some("muse"))|| change.folder.as_deref() == Some(folder.as_path())|| (project.is_some() && change.project == project)// The backups line of the repository this folder is in.@@ -91,6 +92,9 @@ pub fn disconnect_report(.iter().filter(|change| wanted(change) && mine(change)).filter(|change| change.kind != "hooks" || change.folder.is_some() || options.all)+ // Muse Code's plugin serves every project: it goes with+ // `disconnect muse` and `disconnect --all`.+ .filter(|change| change.kind != "muse-plugin" || options.all || client == Some("muse")).filter(|change| change.kind != "exclude" || client.is_none()).map(|change| Target {change: change.clone(),@@ -296,9 +300,10 @@ fn scan_user() -> Vec<Change> {let mut found = Vec::new();let wanted = |name: &str| client.is_none_or(|client| client == name);- for (name, file) in [- ("cursor", env.cursor_config()),- ("claude", env.claude_desktop_config()),+ for (name, file, group) in [+ ("cursor", env.cursor_config(), "mcpServers"),+ ("claude", env.claude_desktop_config(), "mcpServers"),+ ("muse", env.muse_config(), agent_setup::MUSE_GROUP),] {let (true, Some(file)) = (wanted(name), file) else {continue;@@ -306,14 +311,14 @@ fn scan_user(let Some(document) = agent_detect::json_file(&file) else {continue;};- for entry in agent_setup::graphicle_entries(&document, "mcpServers", project, data) {+ for entry in agent_setup::graphicle_entries(&document, group, project, data) {found.push(Change {path: file.clone(),kind: "mcp".into(),client: Some(name.into()),project: project.map(str::to_string),entry: Some(entry),- group: Some("mcpServers".into()),+ group: Some(group.into()),..Change::default()});}@@ -358,9 +363,10 @@ fn scan_user(fn other_stores(env: &Environment, client: Option<&str>, data: &Path) -> Vec<Value> {let wanted = |name: &str| client.is_none_or(|client| client == name);let mut others = Vec::new();- for (name, file) in [- ("cursor", env.cursor_config()),- ("claude", env.claude_desktop_config()),+ for (name, file, group) in [+ ("cursor", env.cursor_config(), "mcpServers"),+ ("claude", env.claude_desktop_config(), "mcpServers"),+ ("muse", env.muse_config(), agent_setup::MUSE_GROUP),] {let (true, Some(file)) = (wanted(name), file) else {continue;@@ -368,7 +374,7 @@ fn other_stores(env: &Environment, client: Option<&str>, data: &Path) -> Vec<Vallet Some(document) = agent_detect::json_file(&file) else {continue;};- for (entry, store) in agent_setup::other_stores(&document, "mcpServers", data) {+ for (entry, store) in agent_setup::other_stores(&document, group, data) {others.push(json!({"file":file,"entry":entry,"data_dir":store}));}}@@ -404,6 +410,10 @@ fn undo_file(path: &Path, targets: &[Target], all: bool, data: &Path) -> Result<}let created = targets.iter().any(|target| target.change.created);let kind = targets[0].change.kind.as_str();+ // Muse Code's plugin: removed from Muse Code, then its package.+ if kind == "muse-plugin" {+ return crate::muse_code::undo(path, data).map(Some);+ }let mut removed = Vec::new();let (bytes, same, empty): (Vec<u8>, SameAsBackup, bool) = match kind {"mcp" | "hooks" | "removed-mcp" => {@@ -676,7 +686,7 @@ fn pruned(value: &Value) -> Value {}/// Phrases joined for a sentence: `a`, `a and b`, `a, b and c`.-fn listed(items: &[&str]) -> String {+pub(crate) fn listed(items: &[&str]) -> String {match items {[] => String::new(),[one] => (*one).to_string(),diff --git a/crates/graphicle/src/fix.rs b/crates/graphicle/src/fix.rsnew file mode 100644index 0000000..7842dc4--- /dev/null+++ b/crates/graphicle/src/fix.rs@@ -0,0 +1,1989 @@+//! `graphicle fix`: a change for an issue, made and tested on a new branch.+//!+//! One cache-aware pack focused on the issue ([`crate::code_pack`]) and a+//! plan (the `plan` command's validated JSON), then at most `--rounds` rounds+//! of edits. Each round the model returns search-and-replace blocks per file,+//! whole new files and a short explanation as structured output. They are+//! checked as a whole and applied, all or none, in a new git worktree on a new+//! branch from HEAD (never the person's working tree or branch), made once+//! the plan has come back, and the test command runs there with a timeout. A+//! failure's output tail and the diff so far go back to the model as the next+//! round, whose start (the instructions, the pack, the issue and the plan) the+//! provider's prompt cache can still hold. Every round's request is fitted to+//! the model's input limit.+//!+//! The test command comes from `--test` or the configuration's `fix.test`,+//! never from the model: its test suggestions are shown, not run. It runs+//! model-edited code with the person's privileges, without the variables+//! that hold model keys. Edits may only touch files inside the repository:+//! absolute paths, `..`, any spelling of `.git` and symlinks that lead+//! outside or into `.git` are refused. Every git command runs with hooks+//! turned off and without the variables that would point git at another+//! repository. Nothing is fetched or pushed.++use crate::long_context::{self, Request, Run, Tree};+use crate::{Error, Result, model};+use serde_json::{Value, json};+use std::collections::{BTreeMap, BTreeSet};+use std::path::{Component, Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++/// What `fix` tells the model in every round: the same words each time, so+/// that the provider's prompt cache matches them and the pack after them.+pub const FIX_INSTRUCTIONS: &str = "You fix an issue in a code repository from a pack of its code. The pack starts with a header. It holds an architecture summary, a manifest of the files it holds, and the files themselves, each headed by its path, line range and why it is included; a pack in the cache layout has a repository part first and a question part after it. Code lines that start with a number and a tab carry their line number, which is not part of the file. After the pack come the issue and a plan, and after a round whose tests failed, the end of the test output and the diff so far. Return one JSON object that matches the schema: the edits, each a file's path, a search text copied exactly from the file as it is now (without the line numbers the pack adds, and long enough to occur once in the file) and its replacement; new files with their whole content; a short explanation that cites the code as path:line; and the tests you would run or add. Change only what the issue needs, keep the code's style, and use paths exactly as the pack shows them.";++/// The edits' JSON schema.+pub fn edits_schema() -> Value {+ json!({"type":"object","properties":{+ "explanation":{"type":"string"},+ "edits":{"type":"array","items":{"type":"object","properties":{+ "path":{"type":"string"},"search":{"type":"string"},"replace":{"type":"string"}}}},+ "new_files":{"type":"array","items":{"type":"object","properties":{+ "path":{"type":"string"},"content":{"type":"string"}}}},+ "tests":{"type":"array","items":{"type":"string"}}}})+}++/// Edits and new files one round may make at most.+const MAX_EDITS: usize = 100;+const MAX_NEW_FILES: usize = 20;+/// The largest file an edit or a new file may write.+const MAX_FILE_BYTES: usize = 4 << 20;+/// The end of a test's output that is kept and sent back.+const OUTPUT_TAIL: usize = 6_000;+/// The end of each output stream held while a test runs.+const OUTPUT_KEEP: usize = 64 << 10;+/// How long a test's output is still read after the command ends.+const OUTPUT_GRACE: Duration = Duration::from_secs(2);+/// The diff so far that a follow-up sends at most.+const DIFF_CAP: usize = 24_000;+/// Tokens a pack without `--budget` leaves free, beyond the room `ask+/// --pack` keeps, for what the rounds add after it: the plan, the test+/// output's end and the diff so far. Each round is still fitted to the+/// input limit.+const ROUND_ROOM: usize = 12_000;+/// The variable that marks a test run's processes (to find the ones that+/// left its process group).+const TEST_MARKER: &str = "GRAPHICLE_FIX_TEST_RUN";+/// The variables model keys are usually read from, besides the ones the+/// configuration names.+const KEY_VARIABLES: &[&str] = &[+ "MODEL_API_KEY",+ // Muse Code reads the Meta Model API key from it.+ "META_API_KEY",+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "AZURE_OPENAI_API_KEY",+];++/// What `fix` is asked for.+pub struct Options {+ pub issue: String,+ /// The test command, run with `sh -c` in the worktree.+ pub test: Option<String>,+ pub rounds: usize,+ pub branch: Option<String>,+ pub commit: bool,+ pub timeout: Duration,+ /// Passages the pack takes first, whatever the issue's words rank+ /// (`--focus`: the places `graphicle pixel` located, for one): path,+ /// first and last line.+ pub focus: Vec<(String, usize, usize)>,+}++/// The most `--focus` passages.+pub const MAX_FOCUS: usize = 50;+/// Lines on each side of a `--focus PATH:LINE`.+const FOCUS_AROUND: usize = 40;+/// The last line of a `--focus PATH` (the whole file; the pack stops at its+/// end).+const WHOLE_FILE: usize = 1_000_000;++/// A `--focus` passage: `PATH`, `PATH:LINE` (the lines around it) or+/// `PATH:START-END`, with the path as the project shows it.+pub fn parse_focus(spec: &str) -> std::result::Result<(String, usize, usize), String> {+ let spec = spec.trim();+ let number = |text: &str| text.parse::<usize>().ok().filter(|&n| n >= 1);+ let (path, start, end) = match spec.rsplit_once(':') {+ Some((path, lines))+ if !lines.is_empty() && lines.bytes().all(|b| b.is_ascii_digit() || b == b'-') =>+ {+ match lines.split_once('-') {+ Some((a, b)) => match (number(a), number(b)) {+ (Some(a), Some(b)) => (path, a.min(b), a.max(b)),+ _ => return Err(format!("--focus {spec}: lines are START-END from 1")),+ },+ None => match number(lines) {+ Some(line) => (+ path,+ line.saturating_sub(FOCUS_AROUND).max(1),+ line + FOCUS_AROUND,+ ),+ None => return Err(format!("--focus {spec}: a line counts from 1")),+ },+ }+ }+ _ => (spec, 1, WHOLE_FILE),+ };+ if path.is_empty() || path.len() > 4096 {+ return Err(format!("--focus {spec}: give a path of the project"));+ }+ Ok((path.to_string(), start, end))+}++/// The pack's `focus` argument for `passages`; null when there are none.+fn focus_json(passages: &[(String, usize, usize)]) -> Value {+ if passages.is_empty() {+ return Value::Null;+ }+ json!(+ passages+ .iter()+ .map(|(path, start, end)| json!({"path":path,"start_line":start,"end_line":end}))+ .collect::<Vec<_>>()+ )+}++/// Whether one part of a path names `.git` on some file system: in any+/// case, with the trailing dots or spaces Windows drops, or as a Windows+/// short name such as `GIT~1`.+fn is_git_name(part: &str) -> bool {+ let folded = part.trim_end_matches(['.', ' ']).to_ascii_lowercase();+ if folded == ".git" {+ return true;+ }+ folded+ .strip_prefix("git~")+ .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))+}++/// The parts of `path` as the model wrote it, empty and `.` parts dropped,+/// or why it is refused.+fn path_parts(path: &str) -> std::result::Result<Vec<&str>, String> {+ if path.is_empty() || path.len() > 4096 {+ return Err("an empty or overlong path".into());+ }+ if path.contains(['\\', '\0', ':']) {+ return Err("a path with a backslash, colon or NUL".into());+ }+ if path.starts_with('/') {+ return Err("an absolute path".into());+ }+ let mut parts = Vec::new();+ for part in path.split('/') {+ match part {+ "" | "." => {}+ ".." => return Err("a path that leaves the repository (..)".into()),+ part if is_git_name(part) => return Err("a path inside .git".into()),+ part => parts.push(part),+ }+ }+ if parts.is_empty() {+ return Err("an empty path".into());+ }+ Ok(parts)+}++/// The file `path` (as the model wrote it) names inside `root`, or why it is+/// refused: an empty, absolute or Windows path, `..`, any spelling of+/// `.git`, or a symlink (on the way or at the end) that leads outside `root`+/// or into a `.git`.+pub fn safe_path(root: &Path, path: &str) -> std::result::Result<PathBuf, String> {+ let parts = path_parts(path)?;+ let real_root = root+ .canonicalize()+ .map_err(|e| format!("the worktree cannot be read ({e})"))?;+ let full = parts+ .iter()+ .fold(root.to_path_buf(), |p, part| p.join(part));+ // The deepest part of the path that exists, the file itself included,+ // must resolve inside the repository and outside its .git.+ let mut probe = full.clone();+ loop {+ if probe.symlink_metadata().is_ok() {+ let real = probe+ .canonicalize()+ .map_err(|_| "a symlink that leads nowhere".to_string())?;+ let Ok(inside) = real.strip_prefix(&real_root) else {+ return Err("a symlink that leads outside the repository".into());+ };+ if inside.components().any(|c| match c {+ Component::Normal(part) => is_git_name(&part.to_string_lossy()),+ _ => false,+ }) {+ return Err("a path inside .git".into());+ }+ break;+ }+ if !probe.pop() {+ break;+ }+ }+ Ok(full)+}++/// The text with a line-number prefix (`123<tab>`) taken off each line, when+/// every line has one: the pack's numbering copied into a search text.+fn unnumbered(text: &str) -> Option<String> {+ let mut out = String::with_capacity(text.len());+ let mut any = false;+ for line in text.split_inclusive('\n') {+ let digits = line.bytes().take_while(u8::is_ascii_digit).count();+ if digits == 0 || line.as_bytes().get(digits) != Some(&b'\t') {+ return None;+ }+ out.push_str(&line[digits + 1..]);+ any = true;+ }+ any.then_some(out)+}++/// Whether the file system under `root` ignores case: the root under its+/// own name with the case of its letters swapped is found too.+fn case_insensitive(root: &Path) -> bool {+ let Some(name) = root.file_name().and_then(|n| n.to_str()) else {+ return cfg!(any(windows, target_os = "macos"));+ };+ let swapped: String = name+ .chars()+ .map(|c| {+ if c.is_ascii_lowercase() {+ c.to_ascii_uppercase()+ } else {+ c.to_ascii_lowercase()+ }+ })+ .collect();+ if swapped == name {+ return cfg!(any(windows, target_os = "macos"));+ }+ root.with_file_name(swapped).exists()+}++/// The key a file is staged under: an existing file's identity on disk, so+/// that every spelling of it is one file; else its path as normalised,+/// case-folded where the file system ignores case.+fn file_key(full: &Path, normalised: &str, fold: bool) -> String {+ #[cfg(unix)]+ if let Ok(meta) = std::fs::metadata(full) {+ use std::os::unix::fs::MetadataExt;+ return format!("file:{}:{}", meta.dev(), meta.ino());+ }+ #[cfg(not(unix))]+ let _ = full;+ if fold {+ format!("path:{}", normalised.to_lowercase())+ } else {+ format!("path:{normalised}")+ }+}++/// The files a round wrote: changed and created, as paths in the project.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Applied {+ pub changed: Vec<String>,+ pub created: Vec<String>,+}++/// One file of a round, checked and ready to write.+struct Staged {+ /// The path as normalised.+ path: String,+ full: PathBuf,+ text: String,+ /// Its bytes before the round, for an edit.+ before: Option<Vec<u8>>,+}++/// Apply a round's `reply` (edits and new files) under `root`, all or none:+/// every path is checked, every search text found exactly once, and the new+/// files checked against each other and the folders on disk, before anything+/// is written; a write that fails puts back every file the round touched.+/// Else the problems, one per refused item.+pub fn apply(root: &Path, reply: &Value) -> std::result::Result<Applied, Vec<String>> {+ let edits = reply["edits"].as_array().cloned().unwrap_or_default();+ let new_files = reply["new_files"].as_array().cloned().unwrap_or_default();+ if edits.len() > MAX_EDITS || new_files.len() > MAX_NEW_FILES {+ return Err(vec![format!(+ "too many changes in one round (at most {MAX_EDITS} edits and {MAX_NEW_FILES} new files)"+ )]);+ }+ let fold = case_insensitive(root);+ let mut problems = Vec::new();+ // key -> the file, staged+ let mut staged: BTreeMap<String, Staged> = BTreeMap::new();+ for edit in &edits {+ let spelled = edit["path"].as_str().unwrap_or("");+ let search = edit["search"].as_str().unwrap_or("");+ let replace = edit["replace"].as_str().unwrap_or("");+ let full = match safe_path(root, spelled) {+ Ok(full) => full,+ Err(why) => {+ problems.push(format!("{spelled}: refused, {why}"));+ continue;+ }+ };+ let path = path_parts(spelled).unwrap_or_default().join("/");+ let key = file_key(&full, &path, fold);+ let current = match staged.get(&key) {+ Some(file) if file.before.is_none() => {+ problems.push(format!(+ "{path}: a new file of this round (write it whole in new_files)"+ ));+ continue;+ }+ Some(file) => file.text.clone(),+ None if full.is_file() => match std::fs::read(&full) {+ Ok(bytes) => match String::from_utf8(bytes) {+ Ok(text) => text,+ Err(_) => {+ problems.push(format!("{path}: not a text file"));+ continue;+ }+ },+ Err(_) => {+ problems.push(format!("{path}: cannot be read"));+ continue;+ }+ },+ None => {+ problems.push(format!(+ "{path}: no such file (a new file goes in new_files)"+ ));+ continue;+ }+ };+ if search.is_empty() {+ problems.push(format!("{path}: an empty search text"));+ continue;+ }+ let (search, replace) = match current.matches(search).count() {+ 0 => match (unnumbered(search), unnumbered(replace)) {+ (Some(s), r) if current.matches(&s).count() == 1 => {+ (s, r.unwrap_or_else(|| replace.to_string()))+ }+ _ => {+ problems.push(format!(+ "{path}: the search text is not in the file as it is now"+ ));+ continue;+ }+ },+ 1 => (search.to_string(), replace.to_string()),+ n => {+ problems.push(format!(+ "{path}: the search text occurs {n} times; give a longer one"+ ));+ continue;+ }+ };+ let text = current.replacen(&search, &replace, 1);+ if text.len() > MAX_FILE_BYTES {+ problems.push(format!("{path}: the edited file is too large"));+ continue;+ }+ match staged.get_mut(&key) {+ Some(file) => file.text = text,+ None => {+ let before = Some(current.into_bytes());+ staged.insert(+ key,+ Staged {+ path,+ full,+ text,+ before,+ },+ );+ }+ }+ }+ // New files: the paths, then the folders they need, checked as a whole.+ let mut new_paths: BTreeSet<String> = BTreeSet::new();+ let fold_path = |p: &str| {+ if fold {+ p.to_lowercase()+ } else {+ p.to_string()+ }+ };+ for file in &new_files {+ let spelled = file["path"].as_str().unwrap_or("");+ let content = file["content"].as_str().unwrap_or("");+ let full = match safe_path(root, spelled) {+ Ok(full) => full,+ Err(why) => {+ problems.push(format!("{spelled}: refused, {why}"));+ continue;+ }+ };+ let path = path_parts(spelled).unwrap_or_default().join("/");+ let key = file_key(&full, &path, fold);+ if full.symlink_metadata().is_ok() || staged.contains_key(&key) {+ problems.push(format!("{path}: exists already (edit it instead)"));+ continue;+ }+ if content.len() > MAX_FILE_BYTES {+ problems.push(format!("{path}: the new file is too large"));+ continue;+ }+ new_paths.insert(fold_path(&path));+ staged.insert(+ key,+ Staged {+ path,+ full,+ text: content.to_string(),+ before: None,+ },+ );+ }+ for file in staged.values().filter(|f| f.before.is_none()) {+ let parts: Vec<&str> = file.path.split('/').collect();+ for depth in 1..parts.len() {+ let folder = parts[..depth].join("/");+ if new_paths.contains(&fold_path(&folder)) {+ problems.push(format!(+ "{}: its folder {folder} is a new file of this round",+ file.path+ ));+ break;+ }+ let on_disk = root.join(&folder);+ if on_disk.symlink_metadata().is_ok() && !on_disk.is_dir() {+ problems.push(format!(+ "{}: its folder {folder} is a file in the repository",+ file.path+ ));+ break;+ }+ }+ }+ if !problems.is_empty() {+ return Err(problems);+ }+ write_all(staged.into_values().collect())+}++/// Write a round's files; on a failed write, put back every file written so+/// far and remove the files and folders the round made.+fn write_all(files: Vec<Staged>) -> std::result::Result<Applied, Vec<String>> {+ let mut written: Vec<&Staged> = Vec::new();+ let mut folders: Vec<PathBuf> = Vec::new();+ let mut failure = None;+ for file in &files {+ if file.before.is_none()+ && let Some(parent) = file.full.parent()+ {+ let mut missing = Vec::new();+ let mut probe = parent.to_path_buf();+ while probe.symlink_metadata().is_err() {+ missing.push(probe.clone());+ if !probe.pop() {+ break;+ }+ }+ for folder in missing.into_iter().rev() {+ match std::fs::create_dir(&folder) {+ Ok(()) => folders.push(folder),+ Err(error) => {+ failure =+ Some(format!("{}: cannot create its folder ({error})", file.path));+ break;+ }+ }+ }+ if failure.is_some() {+ break;+ }+ }+ let result = if file.before.is_some() {+ std::fs::write(&file.full, &file.text)+ } else {+ std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&file.full)+ .and_then(|mut handle| {+ use std::io::Write;+ handle.write_all(file.text.as_bytes())+ })+ };+ match result {+ Ok(()) => written.push(file),+ Err(error) => {+ written.push(file);+ failure = Some(format!("{}: cannot write it ({error})", file.path));+ break;+ }+ }+ }+ if let Some(failure) = failure {+ for file in written.iter().rev() {+ match &file.before {+ Some(before) => {+ let _ = std::fs::write(&file.full, before);+ }+ None => {+ let _ = std::fs::remove_file(&file.full);+ }+ }+ }+ for folder in folders.iter().rev() {+ let _ = std::fs::remove_dir(folder);+ }+ return Err(vec![format!(+ "{failure}; the files of this round were put back"+ )]);+ }+ let mut applied = Applied::default();+ for file in &files {+ if file.before.is_some() {+ applied.changed.push(file.path.clone());+ } else {+ applied.created.push(file.path.clone());+ }+ }+ Ok(applied)+}++/// What the test command's environment leaves out and its output hides:+/// the variables model keys are read from, and their values.+#[derive(Clone, Debug, Default)]+pub struct Scrub {+ pub remove: Vec<String>,+ pub secrets: Vec<String>,+}++impl Scrub {+ /// The model keys of `config`: the variables its profiles read their+ /// keys from and the providers' usual ones, and the values set here.+ /// `fix` passes the merged configuration, with the profiles stored in+ /// the workspace.+ pub fn of(config: &model::Config) -> Self {+ let mut names: BTreeSet<String> = KEY_VARIABLES.iter().map(|n| n.to_string()).collect();+ for profile in config.models.values() {+ if let Some(name) = &profile.key_env+ && !name.is_empty()+ && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')+ {+ names.insert(name.clone());+ }+ }+ let secrets = names+ .iter()+ .filter_map(|name| std::env::var(name).ok())+ .filter(|value| value.len() >= 8)+ .collect();+ Self {+ remove: names.into_iter().collect(),+ secrets,+ }+ }++ fn redact(&self, text: &str) -> String {+ let mut text = text.to_string();+ for secret in &self.secrets {+ text = text.replace(secret.as_str(), "[redacted]");+ }+ text+ }+}++/// A test run's result.+#[derive(Clone, Debug)]+pub struct TestRun {+ pub passed: bool,+ pub code: Option<i32>,+ pub seconds: f64,+ pub timed_out: bool,+ /// The end of its output (standard output, then standard error).+ pub tail: String,+}++/// The last `cap` bytes of `text`, cut at a character boundary.+fn tail(text: &str, cap: usize) -> String {+ if text.len() <= cap {+ return text.to_string();+ }+ let mut start = text.len() - cap;+ while !text.is_char_boundary(start) {+ start += 1;+ }+ format!("...\n{}", &text[start..])+}++/// The end of an output stream, at most [`OUTPUT_KEEP`] bytes of it.+#[derive(Default)]+struct Kept {+ bytes: Vec<u8>,+ cut: bool,+}++impl Kept {+ fn push(&mut self, chunk: &[u8]) {+ self.bytes.extend_from_slice(chunk);+ if self.bytes.len() > 2 * OUTPUT_KEEP {+ let drop = self.bytes.len() - OUTPUT_KEEP;+ self.bytes.drain(..drop);+ self.cut = true;+ }+ }++ fn text(&self) -> String {+ let start = self.bytes.len().saturating_sub(OUTPUT_KEEP);+ let text = String::from_utf8_lossy(&self.bytes[start..]).into_owned();+ if self.cut || start > 0 {+ format!("...\n{text}")+ } else {+ text+ }+ }+}++/// Read `stream` into `kept` until it closes; say so on `done`.+fn keep(+ mut stream: impl std::io::Read + Send + 'static,+ kept: Arc<Mutex<Kept>>,+ done: std::sync::mpsc::Sender<()>,+) {+ std::thread::spawn(move || {+ let mut buffer = [0u8; 8192];+ while let Ok(n) = stream.read(&mut buffer) {+ if n == 0 {+ break;+ }+ kept.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .push(&buffer[..n]);+ }+ let _ = done.send(());+ });+}++/// Stop what a test run left: its process group (the command itself when it+/// is still `running`), and on Linux any process of the run that left the+/// group (found by the run's marker in its environment). On Windows, a+/// command still running is stopped with its process tree.+fn stop_run(pid: u32, marker: &str, running: bool) {+ #[cfg(unix)]+ // SAFETY: a signal to the process group this run started (its leader's+ // id); with the leader gone, the group's other members.+ unsafe {+ libc::kill(-(pid as libc::pid_t), libc::SIGKILL);+ }+ #[cfg(windows)]+ if running {+ let _ = Command::new("taskkill")+ .args(["/F", "/T", "/PID", &pid.to_string()])+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ }+ #[cfg(not(windows))]+ let _ = running;+ #[cfg(target_os = "linux")]+ {+ let needle = format!("{TEST_MARKER}={marker}");+ let me = std::process::id();+ if let Ok(entries) = std::fs::read_dir("/proc") {+ for entry in entries.flatten() {+ let Some(other) = entry+ .file_name()+ .to_str()+ .and_then(|n| n.parse::<libc::pid_t>().ok())+ else {+ continue;+ };+ if other as u32 == me {+ continue;+ }+ let Ok(environ) = std::fs::read(entry.path().join("environ")) else {+ continue;+ };+ if environ+ .split(|b| *b == 0)+ .any(|var| var == needle.as_bytes())+ {+ // SAFETY: a signal to a process that carries this run's+ // marker, so one the test command started.+ unsafe {+ libc::kill(other, libc::SIGKILL);+ }+ }+ }+ }+ }+ #[cfg(not(target_os = "linux"))]+ let _ = marker;+}++/// Run `command` with `sh -c` (`cmd /C` on Windows) in `dir`, without the+/// variables `scrub` names. The run ends when the command itself ends (or+/// after `timeout`); then whatever it left running in its process group is+/// stopped, and on Linux so are the processes that left the group. Output is+/// kept to its end, read for [`OUTPUT_GRACE`] more at most, and the values+/// `scrub` holds are hidden in it.+pub fn run_test(dir: &Path, command: &str, timeout: Duration, scrub: &Scrub) -> TestRun {+ #[cfg(unix)]+ let mut child = {+ use std::os::unix::process::CommandExt;+ let mut c = Command::new("sh");+ c.arg("-c").arg(command).process_group(0);+ c+ };+ #[cfg(not(unix))]+ let mut child = {+ let mut c = Command::new("cmd");+ c.arg("/C").arg(command);+ c+ };+ let marker = format!(+ "{}-{}",+ std::process::id(),+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map_or(0, |d| d.as_nanos())+ );+ child+ .current_dir(dir)+ .env(TEST_MARKER, &marker)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ for name in &scrub.remove {+ child.env_remove(name);+ }+ // On Linux, the test cannot read this process's environment or memory+ // (which may hold a model key) through /proc/<pid>: a process that is not+ // dumpable has those files owned by root. Its children are dumpable again+ // once they exec, so the sweep in `stop_run` still reads theirs. This is+ // defence in depth, not isolation: the test runs as the user.+ #[cfg(target_os = "linux")]+ // SAFETY: PR_SET_DUMPABLE changes only this process's dumpable flag.+ unsafe {+ let off: libc::c_ulong = 0;+ libc::prctl(libc::PR_SET_DUMPABLE, off, off, off, off);+ }+ let start = Instant::now();+ let mut spawned = match child.spawn() {+ Ok(spawned) => spawned,+ Err(error) => {+ return TestRun {+ passed: false,+ code: None,+ seconds: 0.0,+ timed_out: false,+ tail: format!("The test command did not start: {error}"),+ };+ }+ };+ let pid = spawned.id();+ let (done, finished) = std::sync::mpsc::channel();+ let out = Arc::new(Mutex::new(Kept::default()));+ let err = Arc::new(Mutex::new(Kept::default()));+ let mut streams = 0;+ if let Some(stdout) = spawned.stdout.take() {+ keep(stdout, out.clone(), done.clone());+ streams += 1;+ }+ if let Some(stderr) = spawned.stderr.take() {+ keep(stderr, err.clone(), done.clone());+ streams += 1;+ }+ drop(done);+ let (status, timed_out) = loop {+ match spawned.try_wait() {+ Ok(Some(status)) => break (Some(status), false),+ Ok(None) if start.elapsed() >= timeout => break (None, true),+ Ok(None) => std::thread::sleep(Duration::from_millis(20)),+ Err(_) => break (None, false),+ }+ };+ stop_run(pid, &marker, timed_out);+ let status = match status {+ Some(status) => Some(status),+ None => {+ let _ = spawned.kill();+ spawned.wait().ok()+ }+ };+ let seconds = (start.elapsed().as_secs_f64() * 10.0).round() / 10.0;+ // The output read so far, and what comes within the grace period; a+ // stream still held open by a process that escaped is left behind.+ let deadline = Instant::now() + OUTPUT_GRACE;+ for _ in 0..streams {+ let left = deadline.saturating_duration_since(Instant::now());+ if finished.recv_timeout(left).is_err() {+ break;+ }+ }+ let text = format!(+ "{}{}",+ out.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .text(),+ err.lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .text()+ );+ TestRun {+ passed: status.is_some_and(|s| s.success()) && !timed_out,+ code: status.and_then(|s| s.code()),+ seconds,+ timed_out,+ tail: tail(&scrub.redact(&text), OUTPUT_TAIL),+ }+}++/// Text from a model or a test, safe to print to a terminal: escape+/// sequences and control characters other than newlines and tabs removed.+pub fn printable(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ let mut chars = text.chars().peekable();+ while let Some(c) = chars.next() {+ match c {+ '\u{1b}' => match chars.peek() {+ // CSI: parameters, then one final byte from @ to ~.+ Some('[') => {+ chars.next();+ for c in chars.by_ref() {+ if ('\u{40}'..='\u{7e}').contains(&c) {+ break;+ }+ }+ }+ // OSC, DCS and the like: to BEL or ESC \.+ Some(']' | 'P' | '^' | '_' | 'X') => {+ chars.next();+ while let Some(c) = chars.next() {+ if c == '\u{7}' {+ break;+ }+ if c == '\u{1b}' {+ if chars.peek() == Some(&'\\') {+ chars.next();+ }+ break;+ }+ }+ }+ _ => {+ chars.next();+ }+ },+ '\n' | '\t' => out.push(c),+ c if c.is_control() => {}+ c => out.push(c),+ }+ }+ out+}++/// git, as `fix` runs it: with hooks turned off (an empty hooks folder),+/// without the variables that would point it at another repository or add+/// configuration, and with its error's end in the error.+pub(crate) struct Git {+ hooks: PathBuf,+}++/// Variables that point git at another repository, index or object store,+/// or add configuration on top of the files. The variables that choose the+/// user's own configuration files (`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`,+/// `GIT_CONFIG_NOSYSTEM`) are kept: they hold the commit identity, and the+/// command line's `-c core.hooksPath` wins over them.+fn redirects_git(name: &str) -> bool {+ matches!(+ name,+ "GIT_DIR"+ | "GIT_WORK_TREE"+ | "GIT_INDEX_FILE"+ | "GIT_OBJECT_DIRECTORY"+ | "GIT_ALTERNATE_OBJECT_DIRECTORIES"+ | "GIT_COMMON_DIR"+ | "GIT_NAMESPACE"+ | "GIT_PREFIX"+ | "GIT_CEILING_DIRECTORIES"+ | "GIT_DISCOVERY_ACROSS_FILESYSTEM"+ | "GIT_CONFIG"+ | "GIT_CONFIG_PARAMETERS"+ | "GIT_CONFIG_COUNT"+ | "GIT_EXTERNAL_DIFF"+ | "GIT_DIFF_OPTS"+ ) || name.starts_with("GIT_CONFIG_KEY_")+ || name.starts_with("GIT_CONFIG_VALUE_")+}++impl Git {+ /// Hooks off through an empty folder in the data folder.+ pub(crate) fn new(data: &Path) -> Result<Self> {+ let hooks = data.join("fix").join("no-hooks");+ std::fs::create_dir_all(&hooks)?;+ Ok(Self { hooks })+ }++ /// `git -C dir ARGS`: its standard output, or its error's last lines.+ pub(crate) fn run(&self, dir: &Path, args: &[&str]) -> Result<String> {+ let mut command = Command::new("git");+ command+ .arg("-c")+ .arg(format!("core.hooksPath={}", self.hooks.display()))+ .arg("-C")+ .arg(dir)+ .args(args)+ .stdin(Stdio::null());+ for (name, _) in std::env::vars_os() {+ if let Some(name) = name.to_str()+ && redirects_git(name)+ {+ command.env_remove(name);+ }+ }+ let output = command+ .output()+ .map_err(|e| Error::bad(format!("git did not run: {e}")))?;+ if !output.status.success() {+ return Err(Error::bad(format!(+ "git {} failed: {}",+ args.first().unwrap_or(&""),+ tail(String::from_utf8_lossy(&output.stderr).trim(), 400)+ )));+ }+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())+ }+}++/// A branch-name word list from the issue: lower case, letters and digits+/// joined by hyphens, at most 40 characters.+pub fn slug(issue: &str) -> String {+ let mut out = String::new();+ for word in issue+ .split(|c: char| !c.is_ascii_alphanumeric())+ .filter(|w| !w.is_empty())+ {+ let word = word.to_ascii_lowercase();+ if !out.is_empty() && out.len() + 1 + word.len() > 40 {+ break;+ }+ if !out.is_empty() {+ out.push('-');+ }+ out.push_str(&word[..word.len().min(40)]);+ }+ if out.is_empty() { "issue".into() } else { out }+}++/// The repository of the project's folder: its top folder, the project's+/// folder inside it, and HEAD.+struct Repository {+ top: PathBuf,+ prefix: String,+ base: String,+}++impl Repository {+ fn of(git: &Git, folder: &Path) -> Result<Self> {+ let top = PathBuf::from(git.run(folder, &["rev-parse", "--show-toplevel"])?.trim());+ let prefix = git+ .run(folder, &["rev-parse", "--show-prefix"])?+ .trim()+ .to_string();+ let base = git+ .run(folder, &["rev-parse", "HEAD"])+ .map_err(|_| {+ Error::bad("fix needs a commit to start from: the repository has no HEAD")+ })?+ .trim()+ .to_string();+ Ok(Self { top, prefix, base })+ }+}++/// The new worktree: its branch, its folder, the folder of the project in it+/// (the project may be a subfolder of its repository) and the base commit.+struct Worktree {+ branch: String,+ root: PathBuf,+ project: PathBuf,+ base: String,+}++/// Make the branch and its worktree from HEAD, under the data folder.+fn new_worktree(+ git: &Git,+ repository: &Repository,+ data: &Path,+ wanted: Option<&str>,+ issue: &str,+) -> Result<Worktree> {+ let top = &repository.top;+ let exists = |name: &str| {+ git.run(+ top,+ &[+ "rev-parse",+ "--verify",+ "--quiet",+ &format!("refs/heads/{name}"),+ ],+ )+ .is_ok()+ };+ let branch = match wanted {+ Some(name) => {+ if name.starts_with('-')+ || git+ .run(top, &["check-ref-format", "--branch", name])+ .is_err()+ {+ return Err(Error::bad(format!("{name} is not a branch name git takes")));+ }+ if exists(name) {+ return Err(Error::bad(format!(+ "The branch {name} exists already: fix makes a new one"+ )));+ }+ name.to_string()+ }+ None => {+ let stem = format!("graphicle/fix-{}", slug(issue));+ (1..100)+ .map(|n| {+ if n == 1 {+ stem.clone()+ } else {+ format!("{stem}-{n}")+ }+ })+ .find(|name| !exists(name))+ .ok_or_else(|| Error::bad("No free branch name for this issue"))?+ }+ };+ let name = top+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| "repository".into());+ let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");+ let root = data+ .join("fix")+ .join(format!("{}-{}-{stamp}", slug(&name), slug(issue)));+ std::fs::create_dir_all(data.join("fix"))?;+ let path = root.to_string_lossy().into_owned();+ git.run(+ top,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ &branch,+ &path,+ &repository.base,+ ],+ )?;+ let project = root.join(&repository.prefix);+ Ok(Worktree {+ branch,+ root,+ project,+ base: repository.base.clone(),+ })+}++/// The diff of the worktree against its base, new files included; textual+/// diff drivers and external diff programs are not run.+fn diff(git: &Git, worktree: &Worktree) -> Result<(String, Vec<String>)> {+ git.run(&worktree.root, &["add", "-A", "-N"])?;+ let text = git.run(+ &worktree.root,+ &[+ "diff",+ "--no-color",+ "--no-ext-diff",+ "--no-textconv",+ &worktree.base,+ ],+ )?;+ let names = git+ .run(+ &worktree.root,+ &["diff", "--name-only", "--no-ext-diff", &worktree.base],+ )?+ .lines()+ .map(str::to_string)+ .collect();+ Ok((text, names))+}++/// One round as the report shows it.+fn round_json(+ round: usize,+ reply: Option<&Value>,+ applied: &std::result::Result<Applied, Vec<String>>,+ test: Option<&TestRun>,+ usage: &Value,+) -> Value {+ let (applied_json, refused) = match applied {+ Ok(applied) => (+ json!({"changed":applied.changed,"created":applied.created}),+ Value::Null,+ ),+ Err(problems) => (Value::Null, json!(problems)),+ };+ let result = match (applied, test) {+ (Err(_), _) => "not applied",+ (Ok(_), None) => "untested",+ (Ok(_), Some(t)) if t.passed => "passed",+ (Ok(_), Some(t)) if t.timed_out => "timed out",+ (Ok(_), Some(_)) => "failed",+ };+ json!({"round":round,"result":result,"applied":applied_json,"refused":refused,+ "explanation":reply.and_then(|r| r["explanation"].as_str()),+ "test":test.map(|t| json!({"passed":t.passed,"exit_code":t.code,"seconds":t.seconds,+ "timed_out":t.timed_out,"output_tail":t.tail})),+ "usage":usage})+}++/// The one-line usage of a spend log entry.+fn entry_line(entry: &Value) -> String {+ crate::spend::line(entry)+}++/// `graphicle fix`.+pub async fn fix(run: Run<'_>, options: Options) -> Result<()> {+ let (name, profile) = long_context::profile(&run)?;+ let human = crate::terminal::human(run.json);+ let folder = run.folder.clone().ok_or_else(|| {+ Error::bad("fix works on a project's own folder, a git working tree: sync one first")+ })?;+ let issue = options.issue.trim().to_string();+ if issue.is_empty() {+ return Err(Error::bad("Give the issue's text, or --issue-file FILE"));+ }+ let git = Git::new(&run.store.directory)?;+ let repository = Repository::of(&git, &folder)?;+ let dirty = git+ .run(&folder, &["status", "--porcelain", "--untracked-files=no"])+ .map(|s| !s.trim().is_empty())+ .unwrap_or(false);+ let ratio = long_context::calibration(run.store, &name, &profile);+ let room = |budget: usize| {+ if run.budget.is_none() {+ budget+ .saturating_sub(ROUND_ROOM)+ .max(crate::code_pack::MIN_BUDGET)+ } else {+ budget+ }+ };+ let budget = room(long_context::budget_with(&profile, run.budget, ratio)?);+ let nominal = room(long_context::budget_for(&profile, run.budget)?);+ // The plan: the `plan` command's call and checks, on a cache-aware pack.+ let plan_schema = long_context::plan_schema();+ let plan_user = |pack: &Value| {+ format!(+ "{}\nChange request: {issue}\n",+ crate::code_pack::text(pack)+ )+ };+ let plan_request = Request {+ question: &issue,+ rest: &issue,+ instructions: long_context::PLAN_INSTRUCTIONS,+ user_of: &plan_user,+ schema: Some(&plan_schema),+ };+ // The pack of the issue, with the --focus passages first: the same+ // arguments as every long-context pack (`long_context::pack_args`), and+ // `focus` only when there are passages.+ let focus = focus_json(&options.focus);+ let repack = |budget: usize| -> Result<Value> {+ let mut args = long_context::pack_args(&run, &profile, &issue, budget, Some(nominal));+ if !focus.is_null() {+ args["focus"] = focus.clone();+ }+ run.store+ .project_pack(&run.session.workspace, &run.session.capability, &args)+ };+ let (mut pack, mut budget, counted) = long_context::fit_with(+ &profile,+ &plan_request,+ repack(budget)?,+ budget,+ ratio,+ human,+ &repack,+ )+ .await?;+ if human {+ long_context::tell_packed(&pack, &name, &profile);+ }+ let (result, plan_entry) = long_context::send(+ &run,+ "fix",+ &name,+ &profile,+ &pack,+ &plan_request,+ counted,+ ratio,+ &mut |_| {},+ )+ .await?;+ let mut plan = long_context::json_in(&result?.text)?;+ if !plan.is_object() {+ return Err(Error::bad("The model's plan is not a JSON object"));+ }+ let mut tree = Tree::new(Some(folder.clone()));+ let plan_problems = long_context::check_plan(&mut plan, &mut tree);+ if human {+ eprintln!(+ "graphicle: planned ({}); {}",+ entry_line(&plan_entry),+ printable(plan["summary"].as_str().unwrap_or("no summary"))+ );+ }+ // The branch and its worktree, now that there is a plan.+ let worktree = new_worktree(+ &git,+ &repository,+ &run.store.directory,+ options.branch.as_deref(),+ &issue,+ )?;+ if human {+ eprintln!(+ "graphicle: made the branch {} at {} from HEAD {}{}",+ worktree.branch,+ worktree.root.display(),+ &worktree.base[..12.min(worktree.base.len())],+ if dirty {+ " (your uncommitted changes are not in it)"+ } else {+ ""+ }+ );+ }+ let named = |error: Error| {+ Error::bad(format!(+ "{}; the branch {} and its worktree {} remain",+ error.message,+ worktree.branch,+ worktree.root.display()+ ))+ };+ // The rounds: the same instructions, pack, issue and plan each time,+ // then what the last round left, each request fitted to the input limit.+ let schema = edits_schema();+ let plan_json = serde_json::to_string(&plan)?;+ let scrub = Scrub::of(&crate::settings::configuration(+ run.store,+ &run.session.workspace,+ run.config,+ )?);+ let mut follow_up = String::new();+ let mut rounds: Vec<Value> = Vec::new();+ let mut suggested: Vec<String> = Vec::new();+ let mut explanations = String::new();+ let mut outcome = "not applied";+ let mut stopped: Option<String> = None;+ for round in 1..=options.rounds {+ let rest = format!(+ "Issue: {issue}\nPlan: {plan_json}\n{follow_up}Round {round}: return the edits.\n"+ );+ let user_of = |pack: &Value| format!("{}\n{rest}", crate::code_pack::text(pack));+ let round_request = Request {+ question: &issue,+ rest: &rest,+ instructions: FIX_INSTRUCTIONS,+ user_of: &user_of,+ schema: Some(&schema),+ };+ let fitted = long_context::fit_with(+ &profile,+ &round_request,+ pack.clone(),+ budget,+ ratio,+ human,+ &repack,+ )+ .await;+ let counted = match fitted {+ Ok((fitted, fitted_budget, counted)) => {+ pack = fitted;+ budget = fitted_budget;+ counted+ }+ Err(error) => {+ rounds.push(json!({"round":round,"result":"does not fit","error":error.message}));+ outcome = "does not fit";+ stopped = Some(error.message);+ break;+ }+ };+ let sent = long_context::send(+ &run,+ "fix",+ &name,+ &profile,+ &pack,+ &round_request,+ counted,+ ratio,+ &mut |_| {},+ )+ .await;+ let (result, entry) = match sent {+ Ok(sent) => sent,+ Err(error) => {+ rounds.push(+ json!({"round":round,"result":"refused by a cap","refused":[error.message]}),+ );+ outcome = "refused by a cap";+ stopped = Some(error.message);+ break;+ }+ };+ let done = match result {+ Ok(done) => done,+ Err(error) => {+ rounds.push(json!({"round":round,"result":"provider error","error":error.message,"usage":entry}));+ outcome = "provider error";+ stopped = Some(error.message);+ break;+ }+ };+ let reply = match long_context::json_in(&done.text) {+ Ok(reply) if reply.is_object() => reply,+ Ok(_) | Err(_) => {+ let applied: std::result::Result<Applied, Vec<String>> =+ Err(vec!["the model's reply is not the edits' JSON".to_string()]);+ rounds.push(round_json(round, None, &applied, None, &entry));+ follow_up = format!(+ "Round {round} failed: the reply was not one JSON object that matches the schema.\n"+ );+ continue;+ }+ };+ for test in reply["tests"].as_array().into_iter().flatten() {+ if let Some(test) = test.as_str()+ && !suggested.iter().any(|s| s == test)+ {+ suggested.push(test.to_string());+ }+ }+ if let Some(text) = reply["explanation"].as_str() {+ explanations.push_str(text);+ explanations.push('\n');+ }+ let applied = apply(&worktree.project, &reply);+ let test = match (&applied, &options.test) {+ (Ok(_), Some(command)) => Some(run_test(+ &worktree.project,+ command,+ options.timeout,+ &scrub,+ )),+ _ => None,+ };+ rounds.push(round_json(+ round,+ Some(&reply),+ &applied,+ test.as_ref(),+ &entry,+ ));+ if human {+ eprintln!(+ "graphicle: round {round}: {} ({})",+ rounds.last().unwrap()["result"].as_str().unwrap_or(""),+ entry_line(&entry)+ );+ }+ match (&applied, &test) {+ (Err(problems), _) => {+ outcome = if outcome == "failed" {+ "failed"+ } else {+ "not applied"+ };+ follow_up = format!(+ "Round {round}: no edit was applied, because:\n{}\n",+ problems.join("\n")+ );+ }+ (Ok(_), None) => {+ outcome = "untested";+ break;+ }+ (Ok(_), Some(t)) if t.passed => {+ outcome = "passed";+ break;+ }+ (Ok(_), Some(t)) => {+ outcome = "failed";+ let (diff_text, _) = diff(&git, &worktree).map_err(named)?;+ follow_up = format!(+ "Round {round}: the edits were applied, and the test command {} ({}). The end of its output:\n```\n{}\n```\nThe diff so far:\n```diff\n{}\n```\n",+ if t.timed_out { "timed out" } else { "failed" },+ t.code+ .map_or("no exit code".to_string(), |c| format!("exit code {c}")),+ t.tail,+ tail(&diff_text, DIFF_CAP)+ );+ }+ }+ }+ let (_, files) = diff(&git, &worktree).map_err(named)?;+ let mut committed = None;+ if options.commit && !files.is_empty() {+ let title: String = issue+ .lines()+ .next()+ .unwrap_or("Fix")+ .chars()+ .take(72)+ .collect();+ let tests = match (outcome, &options.test) {+ ("passed", Some(command)) => format!("Tests pass: {command}"),+ (_, Some(command)) => format!("Tests do not pass yet: {command}"),+ (_, None) => "Not tested.".to_string(),+ };+ // Hooks stay off: the worktree's own hooks may be files the model+ // edited.+ git.run(&worktree.root, &["add", "-A"]).map_err(named)?;+ git.run(+ &worktree.root,+ &["commit", "-q", "--no-verify", "-m", &title, "-m", &tests],+ )+ .map_err(named)?;+ committed = Some(+ git.run(&worktree.root, &["rev-parse", "HEAD"])+ .map_err(named)?+ .trim()+ .to_string(),+ );+ }+ // Citations of the plan and the explanations, checked against the tree.+ let mut cited: Vec<Value> = Vec::new();+ let mut text = explanations.clone();+ for edit in plan["edits"].as_array().into_iter().flatten() {+ text.push_str(&format!(+ "{}:{}-{}\n",+ edit["path"].as_str().unwrap_or(""),+ edit["start_line"],+ edit["end_line"]+ ));+ }+ for c in long_context::citations(&text) {+ let problem = tree.problem(&c.path, c.line, c.end);+ cited.push(json!({"path":c.path,"line":c.line,"end_line":c.end,"valid":problem.is_none(),"problem":problem}));+ }+ let cost: f64 = std::iter::once(&plan_entry)+ .chain(rounds.iter().map(|r| &r["usage"]))+ .filter_map(|u| u["cost_usd"].as_f64())+ .sum();+ let mut report = json!({"branch":worktree.branch,"worktree":worktree.root,"base":worktree.base,+ "result":outcome,"tested":options.test.is_some(),"test_command":options.test,+ "plan":plan,"plan_problems":plan_problems,"plan_usage":plan_entry,"rounds":rounds,+ "files_changed":files,"citations":cited,"suggested_tests":suggested,+ "committed":committed,"cost_usd":cost,"model":profile.model,"profile":name,+ "prompt_cache_key":model::prompt_cache_on(&profile).then(|| long_context::cache_key(&pack)),+ "pack":crate::code_pack::summary(&pack)});+ if !focus.is_null() {+ report["focus"] = focus.clone();+ }+ if !human {+ println!("{}", serde_json::to_string_pretty(&report)?);+ } else {+ print!("{}", printable(&report_text(&report)));+ }+ match outcome {+ "passed" | "untested" => Ok(()),+ other => Err(Error::bad(format!(+ "fix ended with the result {other:?}{}; the changes are in {}",+ stopped.map_or(String::new(), |why| format!(" ({})", printable(&why))),+ worktree.root.display()+ ))),+ }+}++/// The report as a person reads it.+fn report_text(report: &Value) -> String {+ let mut out = format!(+ "Branch {} in {} (from {}).\n",+ report["branch"].as_str().unwrap_or(""),+ report["worktree"].as_str().unwrap_or(""),+ report["base"]+ .as_str()+ .unwrap_or("")+ .get(..12)+ .unwrap_or("")+ );+ if let Some(summary) = report["plan"]["summary"].as_str() {+ out.push_str(&format!("Plan: {summary}\n"));+ }+ out.push_str(&format!(+ "Plan call: {}\n",+ entry_line(&report["plan_usage"])+ ));+ for round in report["rounds"].as_array().into_iter().flatten() {+ let mut line = format!(+ "Round {}: {}",+ round["round"],+ round["result"].as_str().unwrap_or("")+ );+ if let Some(test) = round["test"].as_object() {+ line.push_str(&format!(+ " ({} s{})",+ test["seconds"],+ test["exit_code"]+ .as_i64()+ .map_or(String::new(), |c| format!(", exit code {c}"))+ ));+ }+ if let Some(error) = round["error"].as_str() {+ line.push_str(&format!("\n {error}"));+ }+ if let Some(refused) = round["refused"].as_array() {+ for problem in refused {+ line.push_str(&format!("\n refused: {}", problem.as_str().unwrap_or("")));+ }+ }+ if round["usage"].is_object() {+ line.push_str(&format!("\n {}", entry_line(&round["usage"])));+ }+ out.push_str(&line);+ out.push('\n');+ }+ let files: Vec<&str> = report["files_changed"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect();+ out.push_str(&format!(+ "Files changed: {}\n",+ if files.is_empty() {+ "none".to_string()+ } else {+ files.join(", ")+ }+ ));+ let cited: Vec<String> = report["citations"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|c| {+ let place = if c["line"] == c["end_line"] {+ format!("{}:{}", c["path"].as_str().unwrap_or(""), c["line"])+ } else {+ format!(+ "{}:{}-{}",+ c["path"].as_str().unwrap_or(""),+ c["line"],+ c["end_line"]+ )+ };+ if c["valid"] == true {+ place+ } else {+ format!("{place} (does not hold)")+ }+ })+ .collect();+ if !cited.is_empty() {+ out.push_str(&format!("Cited: {}\n", cited.join(", ")));+ }+ let suggested: Vec<&str> = report["suggested_tests"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .collect();+ if !suggested.is_empty() {+ out.push_str(&format!(+ "Tests the model suggests (not run): {}\n",+ suggested.join("; ")+ ));+ }+ if report["tested"] != true {+ out.push_str(+ "Untested: give a test command with --test, or set fix.test in the configuration.\n",+ );+ }+ out.push_str(&format!(+ "Cost: {} at the configured price.\n",+ crate::spend::usd(report["cost_usd"].as_f64().unwrap_or(0.0))+ ));+ match report["committed"].as_str() {+ Some(sha) => out.push_str(&format!(+ "Committed {} on {}. Nothing was pushed.\n",+ &sha[..12.min(sha.len())],+ report["branch"].as_str().unwrap_or("")+ )),+ None => out.push_str(&format!(+ "The changes are in the worktree, not committed: `git -C {} diff`, or run fix with --commit.\n",+ report["worktree"].as_str().unwrap_or("")+ )),+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn focus_names_a_file_a_line_or_a_range() {+ assert_eq!(+ parse_focus("src/a.ts"),+ Ok(("src/a.ts".into(), 1, WHOLE_FILE))+ );+ assert_eq!(+ parse_focus("src/a.ts:100"),+ Ok(("src/a.ts".into(), 60, 140))+ );+ assert_eq!(parse_focus("src/a.ts:3"), Ok(("src/a.ts".into(), 1, 43)));+ assert_eq!(+ parse_focus(" src/a.ts:20-10 "),+ Ok(("src/a.ts".into(), 10, 20))+ );+ assert!(parse_focus("src/a.ts:0").is_err());+ assert!(parse_focus("src/a.ts:5-").is_err());+ assert!(parse_focus(":5").is_err());+ // A colon that is not a line range is part of the path.+ assert_eq!(+ parse_focus("src/a:b.ts"),+ Ok(("src/a:b.ts".into(), 1, WHOLE_FILE))+ );+ assert_eq!(focus_json(&[]), Value::Null);+ }++ #[test]+ fn paths_that_leave_the_repository_or_reach_git_are_refused() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path().join("repo");+ std::fs::create_dir_all(root.join("src")).unwrap();+ std::fs::create_dir_all(root.join(".git")).unwrap();+ std::fs::write(root.join("src/a.go"), "package a\n").unwrap();+ assert!(safe_path(&root, "src/a.go").is_ok());+ assert!(safe_path(&root, "./src/new/b.go").is_ok());+ assert!(safe_path(&root, "src//a.go").is_ok());+ for bad in [+ "",+ ".",+ "/etc/passwd",+ "../outside.txt",+ "src/../../outside.txt",+ ".git/config",+ ".GIT/config",+ ".Git/hooks/pre-commit",+ ".git./config",+ ".git /config",+ "GIT~1/config",+ "src/.git/hooks/pre-commit",+ "C:\\x",+ "src\\a.go",+ "a:b",+ ] {+ assert!(safe_path(&root, bad).is_err(), "{bad}");+ }+ #[cfg(unix)]+ {+ std::os::unix::fs::symlink(dir.path(), root.join("out")).unwrap();+ std::os::unix::fs::symlink(root.join("src/a.go"), root.join("inside")).unwrap();+ std::os::unix::fs::symlink(root.join(".git"), root.join("g")).unwrap();+ assert!(safe_path(&root, "out/x.txt").is_err());+ assert!(safe_path(&root, "inside").is_ok());+ assert!(safe_path(&root, "g/config").is_err());+ assert!(safe_path(&root, "g").is_err());+ }+ }++ #[test]+ fn edits_apply_all_or_none() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(root.join("a.go"), "func A() int {\n\treturn 41\n}\n").unwrap();+ let ok = json!({"edits":[{"path":"a.go","search":"\treturn 41\n","replace":"\treturn 42\n"}],+ "new_files":[{"path":"b/b.go","content":"package b\n"}]});+ assert_eq!(+ apply(root, &ok).unwrap(),+ Applied {+ changed: vec!["a.go".into()],+ created: vec!["b/b.go".into()]+ }+ );+ assert!(+ std::fs::read_to_string(root.join("a.go"))+ .unwrap()+ .contains("return 42")+ );+ // One bad item: nothing is written.+ let mixed = json!({"edits":[{"path":"a.go","search":"return 42","replace":"return 43"},+ {"path":"../x.go","search":"a","replace":"b"}]});+ let problems = apply(root, &mixed).unwrap_err();+ assert!(problems[0].starts_with("../x.go: refused"), "{problems:?}");+ assert!(+ std::fs::read_to_string(root.join("a.go"))+ .unwrap()+ .contains("return 42")+ );+ // The pack's line numbers copied into a search text still match.+ let numbered = json!({"edits":[{"path":"a.go","search":"2\t\treturn 42\n","replace":"2\t\treturn 43\n"}]});+ apply(root, &numbered).unwrap();+ assert!(+ std::fs::read_to_string(root.join("a.go"))+ .unwrap()+ .contains("\treturn 43\n")+ );+ // Missing and repeated search texts, and new files that exist.+ for (bad, why) in [+ (+ json!({"edits":[{"path":"a.go","search":"return 99","replace":"x"}]}),+ "not in the file",+ ),+ (+ json!({"edits":[{"path":"a.go","search":"\n","replace":"x"}]}),+ "occurs",+ ),+ (+ json!({"new_files":[{"path":"a.go","content":"x"}]}),+ "exists already",+ ),+ (+ json!({"edits":[{"path":"c.go","search":"a","replace":"b"}]}),+ "no such file",+ ),+ ] {+ let problems = apply(root, &bad).unwrap_err();+ assert!(problems[0].contains(why), "{problems:?}");+ }+ }++ /// New files `a` and `a/b`, or a new file under an existing file: the+ /// round is refused before anything is written.+ #[test]+ fn new_files_that_need_each_other_as_folders_are_refused_whole() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(root.join("keep.txt"), "x\n").unwrap();+ let reply = json!({"edits":[],"new_files":[+ {"path":"a","content":"first\n"},{"path":"a/b","content":"second\n"}]});+ let problems = apply(root, &reply).unwrap_err();+ assert!(+ problems[0].contains("its folder a is a new file of this round"),+ "{problems:?}"+ );+ assert!(!root.join("a").exists());+ let reply = json!({"new_files":[{"path":"keep.txt/inner","content":"x"}]});+ let problems = apply(root, &reply).unwrap_err();+ assert!(+ problems[0].contains("is a file in the repository"),+ "{problems:?}"+ );+ }++ /// A write that fails puts back what the round wrote before it.+ #[cfg(unix)]+ #[test]+ fn a_failed_write_puts_the_round_back() {+ use std::os::unix::fs::PermissionsExt;+ // Root writes anyway: the check needs an ordinary user.+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path();+ std::fs::write(root.join("a.txt"), "one\n").unwrap();+ std::fs::write(root.join("b.txt"), "two\n").unwrap();+ std::fs::set_permissions(root.join("b.txt"), std::fs::Permissions::from_mode(0o444))+ .unwrap();+ let reply = json!({"edits":[+ {"path":"a.txt","search":"one","replace":"ONE"},+ {"path":"b.txt","search":"two","replace":"TWO"}],+ "new_files":[{"path":"new/c.txt","content":"three\n"}]});+ let problems = apply(root, &reply).unwrap_err();+ assert!(problems[0].contains("were put back"), "{problems:?}");+ assert_eq!(+ std::fs::read_to_string(root.join("a.txt")).unwrap(),+ "one\n"+ );+ assert_eq!(+ std::fs::read_to_string(root.join("b.txt")).unwrap(),+ "two\n"+ );+ assert!(!root.join("new").exists());+ }++ /// Two spellings of one file are one file: both edits are made.+ #[test]+ fn spellings_of_one_path_are_one_file() {+ let dir = tempfile::tempdir().unwrap();+ let root = dir.path().join("work");+ std::fs::create_dir_all(root.join("src")).unwrap();+ std::fs::write(root.join("src/lib.rs"), "one\ntwo\nthree\n").unwrap();+ let reply = json!({"edits":[+ {"path":"src/lib.rs","search":"one","replace":"ONE"},+ {"path":"src//lib.rs","search":"two","replace":"TWO"},+ {"path":"./src/./lib.rs","search":"three","replace":"THREE"}],"new_files":[]});+ let applied = apply(&root, &reply).unwrap();+ assert_eq!(applied.changed, vec!["src/lib.rs".to_string()]);+ assert_eq!(+ std::fs::read_to_string(root.join("src/lib.rs")).unwrap(),+ "ONE\nTWO\nTHREE\n"+ );+ // Where the file system ignores case, another case is the same file.+ if case_insensitive(&root) {+ let reply = json!({"edits":[+ {"path":"src/lib.rs","search":"ONE","replace":"one"},+ {"path":"SRC/LIB.rs","search":"TWO","replace":"two"}]});+ apply(&root, &reply).unwrap();+ assert_eq!(+ std::fs::read_to_string(root.join("src/lib.rs")).unwrap(),+ "one\ntwo\nTHREE\n"+ );+ }+ }++ #[test]+ fn tests_run_with_a_timeout_and_keep_the_end_of_their_output() {+ let dir = tempfile::tempdir().unwrap();+ let none = Scrub::default();+ let passed = run_test(dir.path(), "echo fine", Duration::from_secs(30), &none);+ assert!(passed.passed && passed.code == Some(0) && passed.tail.contains("fine"));+ let failed = run_test(+ dir.path(),+ "echo broken >&2; exit 3",+ Duration::from_secs(30),+ &none,+ );+ assert!(!failed.passed && failed.code == Some(3) && failed.tail.contains("broken"));+ #[cfg(unix)]+ {+ let slow = run_test(dir.path(), "sleep 30", Duration::from_millis(300), &none);+ assert!(slow.timed_out && !slow.passed && slow.seconds < 20.0);+ // A background child holding the output does not make the run+ // time out: it ends with the command.+ let started = Instant::now();+ let background = run_test(+ dir.path(),+ "sleep 20 & echo started",+ Duration::from_secs(10),+ &none,+ );+ assert!(background.passed && !background.timed_out, "{background:?}");+ assert!(background.tail.contains("started"));+ assert!(started.elapsed() < Duration::from_secs(8));+ // Output past what is kept: the end stays, the memory bounded.+ let loud = run_test(+ dir.path(),+ "i=0; while [ $i -lt 4000 ]; do echo line $i of a long run of output; i=$((i+1)); done",+ Duration::from_secs(60),+ &none,+ );+ assert!(loud.tail.contains("line 3999"));+ assert!(loud.tail.len() <= OUTPUT_TAIL + 8);+ }+ #[cfg(target_os = "linux")]+ {+ // A child that leaves the process group: the output read is kept.+ let started = Instant::now();+ let escaped = run_test(+ dir.path(),+ "setsid sleep 25 & echo started",+ Duration::from_secs(10),+ &none,+ );+ assert!(+ escaped.passed && escaped.tail.contains("started"),+ "{escaped:?}"+ );+ assert!(started.elapsed() < Duration::from_secs(8));+ }+ assert_eq!(+ slug("Fix: the StatefulSet ordinal 01 bug!"),+ "fix-the-statefulset-ordinal-01-bug"+ );+ assert_eq!(slug("***"), "issue");+ assert_eq!(tail("abcdef", 3), "...\ndef");+ }++ /// The test command runs without the model key variables, and their+ /// values are hidden in its output.+ #[cfg(unix)]+ #[test]+ fn the_test_command_gets_no_model_keys() {+ let dir = tempfile::tempdir().unwrap();+ let scrub = Scrub {+ remove: vec!["HOME".into()],+ secrets: vec!["s3cr3t-value-0123456789".into()],+ };+ let run = run_test(+ dir.path(),+ "echo \"home=[$HOME]\"; echo leaked s3cr3t-value-0123456789",+ Duration::from_secs(30),+ &scrub,+ );+ assert!(run.tail.contains("home=[]"), "{}", run.tail);+ assert!(run.tail.contains("leaked [redacted]"), "{}", run.tail);+ assert!(!run.tail.contains("s3cr3t"));+ let config: model::Config = serde_json::from_value(json!({"models":{"m":{+ "protocol":"responses","base_url":"https://api.meta.ai/v1","model":"m",+ "key_env":"MY_FIX_KEY","input_limit":4000,"output_limit":1000}}}))+ .unwrap();+ let scrub = Scrub::of(&config);+ assert!(scrub.remove.contains(&"MY_FIX_KEY".to_string()));+ assert!(scrub.remove.contains(&"MODEL_API_KEY".to_string()));+ }++ #[test]+ fn model_text_is_printed_without_terminal_controls() {+ let text =+ "Plan\u{1b}]0;owned\u{7}: fix\u{1b}[2J\u{1b}[31m it\u{1b}[0m\u{7}\r\n\tdone\u{9b}";+ assert_eq!(printable(text), "Plan: fix it\n\tdone");+ let shown = printable(&report_text(+ &json!({"plan":{"summary":"x\u{1b}[2Jy"},"rounds":[],+ "suggested_tests":["make \u{1b}]0;t\u{7}test"]}),+ ));+ assert!(!shown.contains('\u{1b}'));+ assert!(+ shown.contains("Plan: xy") && shown.contains("make test"),+ "{shown}"+ );+ assert_eq!(printable("plain text\n"), "plain text\n");+ }++ #[test]+ fn git_runs_without_redirecting_variables() {+ for name in [+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_INDEX_FILE",+ "GIT_OBJECT_DIRECTORY",+ "GIT_CONFIG_PARAMETERS",+ "GIT_CONFIG_COUNT",+ "GIT_CONFIG_KEY_0",+ "GIT_CONFIG_VALUE_0",+ ] {+ assert!(redirects_git(name), "{name}");+ }+ // The user's configuration files, which hold the commit identity.+ for name in [+ "GIT_CONFIG_GLOBAL",+ "GIT_CONFIG_SYSTEM",+ "GIT_CONFIG_NOSYSTEM",+ "GIT_AUTHOR_NAME",+ "GIT_COMMITTER_EMAIL",+ "GIT_SSH_COMMAND",+ "PATH",+ ] {+ assert!(!redirects_git(name), "{name}");+ }+ }+}diff --git a/crates/graphicle/src/indexed_query.rs b/crates/graphicle/src/indexed_query.rsindex 18e8ac6..7e12762 100644--- a/crates/graphicle/src/indexed_query.rs+++ b/crates/graphicle/src/indexed_query.rs@@ -29,6 +29,9 @@ pub const MAX_MISSING: usize = 2_000;pub const MAX_MISSING_BYTES: usize = 64 << 20;/// The lexical and speaker arms' list lengths in `rank`.const RANKED: usize = 200;+/// Keys the lexical arm keeps for `graphicle pack`'s long ranking+/// ([`crate::query::PACK_RANKING`]).+const PACK_RANKED: usize = 2000;/// Why a call takes the full path instead of the index, or `None`: the/// index serves `context`'s defaults.@@ -125,6 +128,7 @@ fn bm25(extra: &[Option<std::sync::Arc<cache::Features>>],bonus: Option<(&[bool], &[bool])>,identity: &dyn Fn(Key) -> String,+ kept: usize,) -> Result<Order> {// Rows: every index passage with a length (all of them for the words,// those with turns for a speaker side), and the extra rows with@@ -209,10 +213,10 @@ fn bm25(}}let scored = positive.len() as u64;- // The first RANKED by score, ties by identity: everything above the- // RANKED-th score, and every tie at it.- if positive.len() > RANKED {- let cut = RANKED - 1;+ // The first `kept` by score, ties by identity: everything above the+ // `kept`-th score, and every tie at it.+ if positive.len() > kept {+ let cut = kept - 1;positive.select_nth_unstable_by(cut, |a, b| b.0.total_cmp(&a.0));let threshold = positive[cut].0;positive.retain(|(score, _)| *score >= threshold);@@ -222,7 +226,7 @@ fn bm25(.map(|(score, key)| (score, identity(key), key)).collect();named.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));- named.truncate(RANKED);+ named.truncate(kept);Ok(Order {ranked: named.into_iter()@@ -555,6 +559,11 @@ pub fn packet(&features,Some((&file_bonus, &extra_bonus)),&identity,+ if args[query::PACK_RANKING] == true {+ PACK_RANKED+ } else {+ RANKED+ },)})?;let side = speaker_keep(args, query);@@ -580,7 +589,9 @@ pub fn packet(Some((side,crate::phase::phase("context_speaker", || {- bm25(db, &index, &terms, prefix, length, &spoken, None, &identity)+ bm25(+ db, &index, &terms, prefix, length, &spoken, None, &identity, RANKED,+ )})?,))}diff --git a/crates/graphicle/src/lib.rs b/crates/graphicle/src/lib.rsindex 9501ee1..b43a82b 100644--- a/crates/graphicle/src/lib.rs+++ b/crates/graphicle/src/lib.rs@@ -11,8 +11,10 @@ pub mod capture;pub mod claims;pub mod cli;pub mod code_graph_arm;+pub mod code_pack;pub mod code_question;pub mod codex_config;+pub mod computer;pub mod connectors;pub mod core_capabilities;pub mod deletion;@@ -23,6 +25,7 @@ pub mod documents;pub mod embedding_cache;pub mod evidence;pub mod extension;+pub mod fix;pub mod folders;pub mod fresh;pub mod git_hooks;@@ -42,11 +45,13 @@ pub mod json_edit;pub mod limits;pub mod local;pub mod local_inference;+pub mod long_context;pub mod maintenance;pub mod memory;pub mod memory_evidence;pub mod metering;pub mod model;+pub mod muse_code;pub mod notes_first;pub mod oauth;pub mod observer;@@ -56,6 +61,7 @@ pub mod packs;pub mod passage_index;pub mod permissions;pub mod phase;+pub mod pixel;pub mod platform;pub mod product;pub mod projection;@@ -66,10 +72,12 @@ pub mod query_file;pub mod query_graph;pub mod releases;pub mod retention;+pub mod review;pub mod search;pub mod settings;pub mod setup;pub mod source_age;+pub mod spend;pub mod store;pub mod store_compat;pub mod structured_memory;diff --git a/crates/graphicle/src/long_context.rs b/crates/graphicle/src/long_context.rsnew file mode 100644index 0000000..d8af51b--- /dev/null+++ b/crates/graphicle/src/long_context.rs@@ -0,0 +1,1079 @@+//! `graphicle ask --pack` and `graphicle plan`: one model call over a pack+//! of the project's code ([`crate::code_pack`]) for a model with a long+//! context window (Muse Spark through the Meta Model API, or any+//! OpenAI-compatible server such as Muse Spark Open on vLLM or SGLang), then+//! every cited `path:line` checked against the working tree.+//!+//! The pack fills the profile's input limit less [`RESERVE`] (or `--budget`);+//! the question follows it. Tokens in and out are the provider's usage+//! counts; a cost is shown only from the profile's configured price.++use crate::local::Session;+use crate::store::Store;+use crate::{Error, Result, model};+use serde_json::{Value, json};+use std::collections::HashMap;+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::LazyLock;++/// What `ask --pack` tells the model: the same words for every question+/// (no date, no question), so that a provider's prompt cache can match them+/// and the pack's repository part after them.+pub const ASK_INSTRUCTIONS: &str = "You answer questions about a code repository from a pack of its code. The pack starts with a header. It holds an architecture summary, a manifest of the files it holds, and the files themselves, each headed by its path, line range and why it is included; a pack in the cache layout has a repository part first and a question part after it. Code lines that start with a number and a tab carry their line number. Answer from the pack only. Cite each claim about the code as path:line or path:start-end, with the path exactly as the pack shows it. Say plainly what the pack does not show and which files you would need to see; do not guess at code you cannot see.";++/// What `plan` tells the model (the same words for every request).+pub const PLAN_INSTRUCTIONS: &str = "You plan a change to a code repository from a pack of its code. The pack starts with a header. It holds an architecture summary, a manifest of the files it holds, and the files themselves, each headed by its path, line range and why it is included; a pack in the cache layout has a repository part first and a question part after it. Code lines that start with a number and a tab carry their line number. Return the plan as one JSON object that matches the schema: a short summary; the steps in order; the files to edit, each with the line range to change (line numbers from the pack) and the reason; the new files with their purpose; the tests to add, update or run; and the risks. Edit only files the pack shows, with line ranges inside them, and list files that do not exist yet as new files. Use paths exactly as the pack shows them.";++/// Tokens kept out of a pack that fills a profile's input limit: the+/// instructions, the question and the estimate's slack.+pub const RESERVE: usize = 4_000;++/// The plan's JSON schema.+pub fn plan_schema() -> Value {+ json!({"type":"object","properties":{+ "summary":{"type":"string"},+ "steps":{"type":"array","items":{"type":"string"}},+ "edits":{"type":"array","items":{"type":"object","properties":{+ "path":{"type":"string"},"start_line":{"type":"integer"},"end_line":{"type":"integer"},+ "reason":{"type":"string"}}}},+ "new_files":{"type":"array","items":{"type":"object","properties":{+ "path":{"type":"string"},"purpose":{"type":"string"}}}},+ "tests":{"type":"array","items":{"type":"object","properties":{+ "action":{"type":"string","enum":["add","update","run"]},"path":{"type":"string"},+ "what":{"type":"string"}}}},+ "risks":{"type":"array","items":{"type":"string"}}}})+}++/// What a long-context command runs on.+pub struct Run<'a> {+ pub store: &'a Store,+ pub session: &'a Session,+ pub config: &'a model::Config,+ pub project: String,+ /// The working tree the citations are checked against.+ pub folder: Option<PathBuf>,+ /// A configured profile's name (default: the answer model).+ pub model: Option<String>,+ pub budget: Option<usize>,+ /// The pack's layout (`standard` or `cache`) and the cache layout's+ /// prefix share; unset, [`default_layout`].+ pub layout: Option<String>,+ pub prefix_share: Option<f64>,+ pub json: bool,+}++/// The layout of a long-context call's pack when the call names none.+pub fn default_layout(profile: &model::Profile) -> &'static str {+ let _ = profile;+ "standard"+}++/// A pack's prompt cache key: `graphicle:<project>@<commit12>:<prefix12>`,+/// from the project's name, its commit and the pack's prefix, with nothing+/// the question says.+pub fn cache_key(pack: &Value) -> String {+ let project: String = pack["project"]+ .as_str()+ .unwrap_or("project")+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {+ c+ } else {+ '-'+ }+ })+ .take(24)+ .collect();+ let commit: String = pack["commit"]+ .as_str()+ .unwrap_or("nocommit")+ .chars()+ .take(12)+ .collect();+ let prefix: String = pack["prefix_sha256"]+ .as_str()+ .unwrap_or("")+ .chars()+ .take(12)+ .collect();+ format!("graphicle:{project}@{commit}:{prefix}")+}++/// The configured profile `name` (else the answer model).+pub(crate) fn profile(run: &Run<'_>) -> Result<(String, model::Profile)> {+ let configuration =+ crate::settings::configuration(run.store, &run.session.workspace, run.config)?;+ let (name, profile) = configuration.profile(run.model.as_deref()).map_err(|_| {+ Error::bad(match &run.model {+ Some(name) => format!("No model profile named {name}: graphicle config show lists them"),+ None => "No answer model: choose one with `graphicle config set model meta` (Muse Spark) or `graphicle config set model meta:muse-wonder-1.0` (Muse Wonder), or another provider".into(),+ })+ })?;+ if profile.protocol == "local_onnx" {+ return Err(Error::bad(+ "A local ONNX profile embeds or reranks; choose a chat model",+ ));+ }+ Ok((name.to_string(), profile.clone()))+}++/// The pack's budget: `asked`, else the profile's input limit less+/// [`RESERVE`]; never more than the profile takes.+pub fn budget_for(profile: &model::Profile, asked: Option<usize>) -> Result<usize> {+ budget_with(profile, asked, None)+}++/// [`budget_for`] with a profile's calibration: when the provider counted+/// `ratio` of Graphicle's estimate on earlier calls, a pack without+/// `--budget` is sized so that the provider's count fills the room less+/// [`CALIBRATION_MARGIN`].+pub fn budget_with(+ profile: &model::Profile,+ asked: Option<usize>,+ ratio: Option<f64>,+) -> Result<usize> {+ let room = profile.input_limit.saturating_sub(RESERVE);+ let calibrated = ratio+ .filter(|r| r.is_finite() && *r > 0.0)+ .map(|r| ((room as f64) * (1.0 - CALIBRATION_MARGIN) / r) as usize);+ if asked.is_none()+ && let Some(budget) = calibrated+ {+ return Ok(budget.clamp(crate::code_pack::MIN_BUDGET, crate::code_pack::MAX_BUDGET));+ }+ let budget = asked.unwrap_or(room).min(crate::code_pack::MAX_BUDGET);+ if budget > room {+ return Err(Error::bad(format!(+ "--budget {budget} does not fit the model's input limit of {} tokens with room for the question ({} tokens at most)",+ profile.input_limit, room+ )));+ }+ if budget < crate::code_pack::MIN_BUDGET {+ return Err(Error::bad(format!(+ "The model's input limit ({} tokens) leaves no room for a pack: raise it with `graphicle config set models.NAME.input_limit ...`",+ profile.input_limit+ )));+ }+ Ok(budget)+}++/// The share of the room a calibrated pack leaves free.+pub const CALIBRATION_MARGIN: f64 = 0.03;+/// The file in the data folder that keeps each profile's calibration.+const CALIBRATION_FILE: &str = "pack-calibration.json";++/// A profile's calibration: the provider's prompt tokens over Graphicle's+/// estimate of the same prompt, from earlier `ask --pack` and `plan` calls+/// of the same model.+pub fn calibration(store: &Store, name: &str, profile: &model::Profile) -> Option<f64> {+ let text = std::fs::read_to_string(store.directory.join(CALIBRATION_FILE)).ok()?;+ let all: Value = serde_json::from_str(&text).ok()?;+ let entry = &all[name];+ (entry["model"] == profile.model.as_str())+ .then(|| entry["ratio"].as_f64())+ .flatten()+ .filter(|r| (0.3..=2.0).contains(r))+}++/// Record a call's ratio of the provider's prompt tokens to the estimate,+/// averaged with the earlier one.+pub fn record_calibration(+ store: &Store,+ name: &str,+ profile: &model::Profile,+ prompt_tokens: u64,+ estimated: usize,+) {+ if estimated == 0 || prompt_tokens == 0 {+ return;+ }+ let ratio = (prompt_tokens as f64 / estimated as f64).clamp(0.3, 2.0);+ let path = store.directory.join(CALIBRATION_FILE);+ let mut all: Value = std::fs::read_to_string(&path)+ .ok()+ .and_then(|t| serde_json::from_str(&t).ok())+ .filter(Value::is_object)+ .unwrap_or_else(|| json!({}));+ let ratio = match calibration(store, name, profile) {+ Some(earlier) => (earlier + ratio) / 2.0,+ None => ratio,+ };+ let calls = all[name]["calls"].as_u64().unwrap_or(0) + 1;+ all[name] =+ json!({"model":profile.model,"ratio":(ratio * 10_000.0).round() / 10_000.0,"calls":calls});+ let _ = std::fs::write(&path, format!("{all:#}\n"));+}++/// Graphicle's estimate of a request: the pack's tokens, and the+/// instructions and the rest of the request (the question, or what `fix`+/// adds after the pack) at the estimator's default rate.+pub(crate) fn request_estimate(pack: &Value, instructions: &str, rest: &str) -> u64 {+ pack["tokens"].as_u64().unwrap_or(0)+ + crate::code_pack::estimate::tokens(+ instructions.len() + rest.len() + 32,+ crate::code_pack::estimate::PACK_TEXT_BYTES_PER_TOKEN,+ ) as u64+}++/// [`request_estimate`] for a pack sized by the estimator (the requests whose+/// provider counts calibrate the profile).+fn prompt_estimate(pack: &Value, instructions: &str, question: &str) -> Option<usize> {+ (pack["tokenizer"] == "estimate")+ .then(|| request_estimate(pack, instructions, question) as usize)+}++/// A `path:line` or `path:start-end` an answer cites.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Citation {+ pub path: String,+ pub line: usize,+ pub end: usize,+}++static CITATION: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"([A-Za-z0-9_][A-Za-z0-9_.\-/]*\.[A-Za-z0-9]+):(\d+)(?:-(\d+))?").unwrap()+});++/// The citations in `text`, each once, in order.+pub fn citations(text: &str) -> Vec<Citation> {+ let mut found: Vec<Citation> = Vec::new();+ for capture in CITATION.captures_iter(text) {+ let path = capture[1].trim_start_matches("./").to_string();+ let Ok(line) = capture[2].parse::<usize>() else {+ continue;+ };+ let end = capture+ .get(3)+ .and_then(|m| m.as_str().parse::<usize>().ok())+ .unwrap_or(line);+ let citation = Citation { path, line, end };+ if !found.contains(&citation) {+ found.push(citation);+ }+ }+ found+}++/// Line counts of the working tree's files, read once each.+pub struct Tree {+ folder: Option<PathBuf>,+ lines: HashMap<String, Option<usize>>,+}++impl Tree {+ pub fn new(folder: Option<PathBuf>) -> Self {+ Self {+ folder,+ lines: HashMap::new(),+ }+ }++ /// The number of lines of `path`, if it is a file of the tree.+ pub fn lines(&mut self, path: &str) -> Option<usize> {+ if let Some(hit) = self.lines.get(path) {+ return *hit;+ }+ let count = self.folder.as_ref().and_then(|folder| {+ let relative = Path::new(path);+ if relative.is_absolute() || path.split('/').any(|part| part == "..") {+ return None;+ }+ let text = std::fs::read(folder.join(relative)).ok()?;+ Some(String::from_utf8_lossy(&text).lines().count())+ });+ self.lines.insert(path.to_string(), count);+ count+ }++ pub fn exists(&mut self, path: &str) -> bool {+ self.lines(path).is_some()+ }++ /// Why `citation` does not hold in the tree, if it does not.+ pub fn problem(&mut self, path: &str, line: usize, end: usize) -> Option<String> {+ if self.folder.is_none() {+ return Some("no working tree to check against".into());+ }+ let Some(lines) = self.lines(path) else {+ return Some("no such file in the working tree".into());+ };+ if line == 0 || end < line {+ return Some(format!("{line}-{end} is not a line range"));+ }+ if end > lines {+ return Some(format!("past the end of the file ({lines} lines)"));+ }+ None+ }+}++pub(crate) fn usage_json(done: &model::Completion, price: Option<&model::Price>) -> Value {+ let cost = match (price, done.input_tokens, done.output_tokens) {+ (Some(price), Some(input), Some(output)) => {+ Some(price.cost(input, done.cached_tokens.unwrap_or(0), output))+ }+ _ => None,+ };+ json!({"input_tokens":done.input_tokens,"output_tokens":done.output_tokens,+ "cached_tokens":done.cached_tokens,"reasoning_tokens":done.reasoning_tokens,+ "seconds":done.elapsed_ms as f64 / 1000.0,"cost_usd":cost})+}++/// Append a call to the spend log ([`crate::spend`]), releasing its+/// reservation, and return its entry; a log that cannot be written is+/// reported, and the answer still printed.+#[allow(clippy::too_many_arguments)]+pub(crate) fn log_call(+ run: &Run<'_>,+ command: &str,+ name: &str,+ profile: &model::Profile,+ pack: &Value,+ key: &str,+ result: &Result<model::Completion>,+ held: &crate::spend::Reservation,+) -> Value {+ let call = crate::spend::Call {+ command,+ profile: name,+ settings: profile,+ project: pack["project"].as_str(),+ commit: pack["commit"].as_str(),+ prompt_cache_key: model::prompt_cache_on(profile).then_some(key),+ };+ let mut entry = crate::spend::entry(&call, result, chrono::Utc::now());+ if let Err(error) = crate::spend::settle(&run.store.directory, held, &mut entry) {+ eprintln!("graphicle: could not write the spend log: {error}");+ }+ entry+}++/// One long-context request: the question its pack is made for, the text+/// that goes after the pack (the question, or what `fix` adds), the+/// instructions, how the request's text is made from a pack, and the+/// schema of a structured reply.+pub(crate) struct Request<'a> {+ pub question: &'a str,+ pub rest: &'a str,+ pub instructions: &'a str,+ pub user_of: &'a (dyn Fn(&Value) -> String + Sync),+ pub schema: Option<&'a Value>,+}++/// Send `request` with `pack`: the caps reserve its worst case first+/// ([`crate::spend::reserve`]: the provider's count, else the estimate+/// with the calibration `ratio` and a margin), the spend log records it, and+/// the profile's calibration takes the provider's count of an estimated+/// pack. The call's result, and its log entry; an error only when a cap+/// refuses the call.+#[allow(clippy::too_many_arguments)]+pub(crate) async fn send(+ run: &Run<'_>,+ command: &str,+ name: &str,+ profile: &model::Profile,+ pack: &Value,+ request: &Request<'_>,+ counted: Option<u64>,+ ratio: Option<f64>,+ on_text: &mut (dyn FnMut(&str) + Send),+) -> Result<(Result<model::Completion>, Value)> {+ let key = cache_key(pack);+ let estimate = request_estimate(pack, request.instructions, request.rest);+ let held = crate::spend::reserve(+ &run.store.directory,+ name,+ profile,+ crate::spend::worst_input(estimate, counted, ratio),+ chrono::Utc::now(),+ )?;+ let user = (request.user_of)(pack);+ let result = model::complete(+ profile,+ request.instructions,+ &user,+ request.schema,+ profile.output_limit,+ Some(&key),+ on_text,+ )+ .await;+ let entry = log_call(run, command, name, profile, pack, &key, &result, &held);+ if let Ok(done) = &result+ && let Some(prompt) = done.input_tokens+ && let Some(estimated) = prompt_estimate(pack, request.instructions, request.rest)+ {+ record_calibration(run.store, name, profile, prompt, estimated);+ }+ Ok((result, entry))+}++/// The pack of `question` at `budget`; for the cache layout, its repository+/// part sized from `nominal` when given ([`crate::code_pack::Options`]'s+/// `prefix_budget`).+fn pack_for(+ run: &Run<'_>,+ profile: &model::Profile,+ question: &str,+ budget: usize,+ nominal: Option<usize>,+) -> Result<Value> {+ let args = pack_args(run, profile, question, budget, nominal);+ run.store+ .project_pack(&run.session.workspace, &run.session.capability, &args)+}++/// [`pack_for`]'s arguments to [`crate::store::Store::project_pack`], for a+/// caller that adds its own (`review`'s pinned focus).+pub(crate) fn pack_args(+ run: &Run<'_>,+ profile: &model::Profile,+ question: &str,+ budget: usize,+ nominal: Option<usize>,+) -> Value {+ let layout = match (&run.layout, run.prefix_share) {+ (Some(layout), _) => layout.as_str(),+ (None, Some(_)) => "cache",+ (None, None) => default_layout(profile),+ };+ let mut args = json!({"repository_id":run.project,"question":question,"budget":budget,+ "layout":layout});+ if let Some(share) = run.prefix_share {+ args["prefix_share"] = json!(share);+ }+ if let Some(nominal) = nominal {+ args["prefix_budget"] = json!(nominal);+ }+ if let Some(tokenizer) = &profile.tokenizer {+ args["tokenizer"] = json!(tokenizer);+ }+ args+}++/// A request is counted by the provider ([`model::count_tokens_on`]) when+/// its estimate comes to this share of the input limit.+const COUNT_FROM: f64 = 0.8;+/// Packs made again at most while a request does not fit.+const REFITS: usize = 3;++/// The pack for `request` at `budget`, fitted to the input limit ([`fit`]).+#[allow(clippy::too_many_arguments)]+pub(crate) async fn fitted_pack(+ run: &Run<'_>,+ profile: &model::Profile,+ request: &Request<'_>,+ budget: usize,+ nominal: Option<usize>,+ ratio: Option<f64>,+ human: bool,+) -> Result<(Value, usize, Option<u64>)> {+ let pack = pack_for(run, profile, request.question, budget, nominal)?;+ fit(run, profile, request, pack, budget, nominal, ratio, human).await+}++/// `pack` (made at `budget`) fitted to the input limit with `request`: the+/// request's estimate times the profile's calibration `ratio` must fit, and+/// where the profile counts ([`model::count_tokens_on`]) a request near the+/// limit is counted with the provider. While it would not fit, the pack is+/// made again smaller by what is over. The pack, the budget it was made at,+/// and the provider's count when there is one (else the estimate stands, as+/// it does when counting fails).+#[allow(clippy::too_many_arguments)]+pub(crate) async fn fit(+ run: &Run<'_>,+ profile: &model::Profile,+ request: &Request<'_>,+ pack: Value,+ budget: usize,+ nominal: Option<usize>,+ ratio: Option<f64>,+ human: bool,+) -> Result<(Value, usize, Option<u64>)> {+ let repack = |budget: usize| pack_for(run, profile, request.question, budget, nominal);+ fit_with(profile, request, pack, budget, ratio, human, &repack).await+}++/// [`fit`], packing again with `repack` (a pack at the budget it is given).+pub(crate) async fn fit_with(+ profile: &model::Profile,+ request: &Request<'_>,+ mut pack: Value,+ mut budget: usize,+ ratio: Option<f64>,+ human: bool,+ repack: &(dyn Fn(usize) -> Result<Value> + Sync),+) -> Result<(Value, usize, Option<u64>)> {+ let limit = profile.input_limit;+ let counts = model::count_tokens_on(profile);+ let ratio = ratio.filter(|r| r.is_finite() && *r > 0.0).unwrap_or(1.0);+ for refit in 0..=REFITS {+ let estimate = request_estimate(&pack, request.instructions, request.rest) as f64;+ let predicted = (estimate * ratio).ceil() as usize;+ let (over, by) = if counts && (refit > 0 || predicted as f64 >= COUNT_FROM * limit as f64) {+ match model::count_input_tokens(+ profile,+ request.instructions,+ &(request.user_of)(&pack),+ request.schema,+ )+ .await+ {+ Ok(counted) if counted as usize <= limit => {+ return Ok((pack, budget, Some(counted)));+ }+ Ok(counted) => (counted as usize, "the provider counted"),+ Err(error) => {+ if human {+ eprintln!(+ "graphicle: the provider did not count the request ({error}); sizing it by the estimate"+ );+ }+ if predicted <= limit {+ return Ok((pack, budget, None));+ }+ (predicted, "the estimate comes to")+ }+ }+ } else if predicted <= limit {+ return Ok((pack, budget, None));+ } else {+ (predicted, "the estimate comes to")+ };+ // The pack's part of the request, shrunk by what is over and a margin,+ // in the estimate's tokens.+ let observed = over as f64 / estimate.max(1.0);+ let excess = ((over - limit) as f64 + CALIBRATION_MARGIN * limit as f64) / observed;+ let smaller = (pack["tokens"].as_f64().unwrap_or(0.0) - excess).floor();+ let smaller = if smaller > 0.0 { smaller as usize } else { 0 };+ if refit == REFITS || smaller < crate::code_pack::MIN_BUDGET || smaller >= budget {+ return Err(Error::bad(format!(+ "For this request {by} {over} tokens, over the model's input limit of {limit}, and a smaller pack leaves no room: ask with a smaller --budget or a shorter text"+ )));+ }+ if human {+ eprintln!(+ "graphicle: for this request {by} {} tokens, over the input limit of {}; packing again at {} tokens",+ crate::terminal::count(over as u64),+ crate::terminal::count(limit as u64),+ crate::terminal::count(smaller as u64)+ );+ }+ budget = smaller;+ pack = repack(budget)?;+ }+ Ok((pack, budget, None))+}++pub(crate) fn tell_packed(pack: &Value, name: &str, profile: &model::Profile) {+ let layout = if pack["layout"] == "cache" {+ format!(+ ", {} in the repository part",+ crate::terminal::count(pack["prefix_tokens"].as_u64().unwrap_or(0))+ )+ } else {+ String::new()+ };+ eprintln!(+ "graphicle: packed {} tokens of {} files ({}{layout}) in {} s; asking {name} ({})...",+ crate::terminal::count(pack["tokens"].as_u64().unwrap_or(0)),+ pack["included"].as_array().map_or(0, Vec::len),+ pack["tokenizer"].as_str().unwrap_or("estimate"),+ pack["seconds"],+ profile.model+ );+}++/// `graphicle ask --pack`.+pub async fn ask(run: Run<'_>, question: &str) -> Result<()> {+ let (name, profile) = profile(&run)?;+ let ratio = calibration(run.store, &name, &profile);+ let budget = budget_with(&profile, run.budget, ratio)?;+ // The repository part of a cache-layout pack is sized from the budget+ // before calibration, so that it stays the same bytes from call to call.+ let nominal = budget_for(&profile, run.budget)?;+ let human = crate::terminal::human(run.json);+ // The stable instructions, then the pack (its repository part first),+ // then the question.+ let user_of =+ |pack: &Value| format!("{}\nQuestion: {question}\n", crate::code_pack::text(pack));+ let request = Request {+ question,+ rest: question,+ instructions: ASK_INSTRUCTIONS,+ user_of: &user_of,+ schema: None,+ };+ let (pack, _, counted) = fitted_pack(+ &run,+ &profile,+ &request,+ budget,+ Some(nominal),+ ratio,+ human,+ )+ .await?;+ if human {+ tell_packed(&pack, &name, &profile);+ }+ let key = cache_key(&pack);+ let mut stdout = std::io::stdout();+ let mut show = |delta: &str| {+ if human {+ let _ = stdout.write_all(delta.as_bytes());+ let _ = stdout.flush();+ }+ };+ let (result, _) = send(+ &run,+ "ask --pack",+ &name,+ &profile,+ &pack,+ &request,+ counted,+ ratio,+ &mut show,+ )+ .await?;+ let done = result?;+ let mut tree = Tree::new(run.folder.clone());+ let checked: Vec<Value> = citations(&done.text)+ .into_iter()+ .map(|c| {+ let problem = tree.problem(&c.path, c.line, c.end);+ json!({"path":c.path,"line":c.line,"end_line":c.end,"valid":problem.is_none(),"problem":problem})+ })+ .collect();+ let usage = usage_json(&done, profile.price.as_ref());+ if !human {+ let output = json!({"answer":done.text,"model":done.model,"profile":name,+ "citations":checked,"invalid_citations":checked.iter().filter(|c| c["valid"] != true).count(),+ "usage":usage,"prompt_cache_key":model::prompt_cache_on(&profile).then_some(&key),+ "input_tokens_counted":counted,"pack":crate::code_pack::summary(&pack)});+ println!("{}", serde_json::to_string_pretty(&output)?);+ return Ok(());+ }+ let mut tail = String::from("\n\n");+ let valid: Vec<&Value> = checked.iter().filter(|c| c["valid"] == true).collect();+ let invalid: Vec<&Value> = checked.iter().filter(|c| c["valid"] != true).collect();+ let cite = |c: &Value| {+ if c["line"] == c["end_line"] {+ format!("{}:{}", c["path"].as_str().unwrap_or(""), c["line"])+ } else {+ format!(+ "{}:{}-{}",+ c["path"].as_str().unwrap_or(""),+ c["line"],+ c["end_line"]+ )+ }+ };+ if !valid.is_empty() {+ tail.push_str("Sources (checked against the working tree):\n");+ for c in &valid {+ tail.push_str(&format!(" {}\n", cite(c)));+ }+ }+ if !invalid.is_empty() {+ tail.push_str("Citations that do not hold in the working tree:\n");+ for c in &invalid {+ tail.push_str(&format!(+ " {}: {}\n",+ cite(c),+ c["problem"].as_str().unwrap_or("")+ ));+ }+ }+ if checked.is_empty() {+ tail.push_str("The answer cites no path:line.\n");+ }+ tail.push_str(&crate::spend::line(&usage));+ tail.push('\n');+ print!("{tail}");+ Ok(())+}++/// The JSON object in a model's text: the text itself, or the part between+/// its first `{` and last `}` (fences and prose around it are dropped).+pub(crate) fn json_in(text: &str) -> Result<Value> {+ if let Ok(value) = serde_json::from_str::<Value>(text.trim()) {+ return Ok(value);+ }+ let (Some(start), Some(end)) = (text.find('{'), text.rfind('}')) else {+ return Err(Error::bad("The model's plan is not JSON"));+ };+ serde_json::from_str(&text[start..=end]).map_err(|_| Error::bad("The model's plan is not JSON"))+}++/// The plan with each file checked against the working tree: edits must be+/// existing files with ranges inside them, new files must not exist yet,+/// tests to update or run must exist.+pub fn check_plan(plan: &mut Value, tree: &mut Tree) -> usize {+ let mut problems = 0;+ if let Some(edits) = plan["edits"].as_array_mut() {+ for edit in edits {+ let path = edit["path"].as_str().unwrap_or("").to_string();+ let start = edit["start_line"].as_u64().unwrap_or(0) as usize;+ let end = edit["end_line"].as_u64().unwrap_or(0) as usize;+ let problem = tree.problem(&path, start, end);+ problems += usize::from(problem.is_some());+ edit["valid"] = json!(problem.is_none());+ edit["problem"] = json!(problem);+ }+ }+ if let Some(files) = plan["new_files"].as_array_mut() {+ for file in files {+ let path = file["path"].as_str().unwrap_or("").to_string();+ let exists = tree.exists(&path);+ problems += usize::from(exists);+ file["valid"] = json!(!exists);+ file["problem"] = json!(exists.then_some("the file exists already"));+ }+ }+ if let Some(tests) = plan["tests"].as_array_mut() {+ for test in tests {+ let path = test["path"].as_str().unwrap_or("").to_string();+ let needs = test["action"] != "add";+ let missing = needs && !path.is_empty() && !tree.exists(&path);+ problems += usize::from(missing);+ test["valid"] = json!(!missing);+ test["problem"] = json!(missing.then_some("no such file in the working tree"));+ }+ }+ problems+}++/// The plan as Markdown.+pub fn plan_markdown(request: &str, plan: &Value) -> String {+ let mark = |item: &Value| match item["problem"].as_str() {+ Some(problem) => format!(" (check: {problem})"),+ None => String::new(),+ };+ let mut out = format!("# Plan: {}\n\n", request.lines().next().unwrap_or(request));+ if let Some(summary) = plan["summary"].as_str().filter(|s| !s.is_empty()) {+ out.push_str(&format!("{summary}\n\n"));+ }+ let list = |key: &str| plan[key].as_array().cloned().unwrap_or_default();+ let steps = list("steps");+ if !steps.is_empty() {+ out.push_str("## Steps\n\n");+ for (i, step) in steps.iter().enumerate() {+ out.push_str(&format!("{}. {}\n", i + 1, step.as_str().unwrap_or("")));+ }+ out.push('\n');+ }+ let edits = list("edits");+ if !edits.is_empty() {+ out.push_str("## Files to edit\n\n");+ for edit in &edits {+ out.push_str(&format!(+ "- {}:{}-{}: {}{}\n",+ edit["path"].as_str().unwrap_or(""),+ edit["start_line"],+ edit["end_line"],+ edit["reason"].as_str().unwrap_or(""),+ mark(edit)+ ));+ }+ out.push('\n');+ }+ let new_files = list("new_files");+ if !new_files.is_empty() {+ out.push_str("## New files\n\n");+ for file in &new_files {+ out.push_str(&format!(+ "- {}: {}{}\n",+ file["path"].as_str().unwrap_or(""),+ file["purpose"].as_str().unwrap_or(""),+ mark(file)+ ));+ }+ out.push('\n');+ }+ let tests = list("tests");+ if !tests.is_empty() {+ out.push_str("## Tests\n\n");+ for test in &tests {+ out.push_str(&format!(+ "- {} {}: {}{}\n",+ test["action"].as_str().unwrap_or("run"),+ test["path"].as_str().unwrap_or(""),+ test["what"].as_str().unwrap_or(""),+ mark(test)+ ));+ }+ out.push('\n');+ }+ let risks = list("risks");+ if !risks.is_empty() {+ out.push_str("## Risks\n\n");+ for risk in &risks {+ out.push_str(&format!("- {}\n", risk.as_str().unwrap_or("")));+ }+ out.push('\n');+ }+ out+}++/// `graphicle plan`.+pub async fn plan(run: Run<'_>, request: &str) -> Result<()> {+ let (name, profile) = profile(&run)?;+ let ratio = calibration(run.store, &name, &profile);+ let budget = budget_with(&profile, run.budget, ratio)?;+ let nominal = budget_for(&profile, run.budget)?;+ let human = crate::terminal::human(run.json);+ let schema = plan_schema();+ let user_of = |pack: &Value| {+ format!(+ "{}\nChange request: {request}\n",+ crate::code_pack::text(pack)+ )+ };+ let call = Request {+ question: request,+ rest: request,+ instructions: PLAN_INSTRUCTIONS,+ user_of: &user_of,+ schema: Some(&schema),+ };+ let (pack, _, counted) =+ fitted_pack(&run, &profile, &call, budget, Some(nominal), ratio, human).await?;+ if human {+ tell_packed(&pack, &name, &profile);+ }+ let key = cache_key(&pack);+ let (result, _) = send(+ &run,+ "plan",+ &name,+ &profile,+ &pack,+ &call,+ counted,+ ratio,+ &mut |_| {},+ )+ .await?;+ let done = result?;+ let mut plan = json_in(&done.text)?;+ if !plan.is_object() {+ return Err(Error::bad("The model's plan is not a JSON object"));+ }+ let mut tree = Tree::new(run.folder.clone());+ let problems = check_plan(&mut plan, &mut tree);+ let usage = usage_json(&done, profile.price.as_ref());+ if !human {+ let output = json!({"request":request,"plan":plan,"problems":problems,"model":done.model,+ "profile":name,"usage":usage,"prompt_cache_key":model::prompt_cache_on(&profile).then_some(&key),+ "input_tokens_counted":counted,"pack":crate::code_pack::summary(&pack)});+ println!("{}", serde_json::to_string_pretty(&output)?);+ return Ok(());+ }+ let mut text = plan_markdown(request, &plan);+ if problems > 0 {+ text.push_str(&format!(+ "{problems} item(s) of the plan do not hold in the working tree (marked check).\n"+ ));+ }+ text.push_str(&crate::spend::line(&usage));+ text.push('\n');+ print!("{text}");+ Ok(())+}++/// Lines per file of a pack's citations, for tests.+#[cfg(test)]+fn by_path(cites: &[Citation]) -> std::collections::BTreeMap<String, Vec<usize>> {+ let mut out: std::collections::BTreeMap<String, Vec<usize>> = Default::default();+ for c in cites {+ out.entry(c.path.clone()).or_default().push(c.line);+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn citations_are_found_once_each_in_order() {+ let text = "The check is in `pkg/a/x.go:42` and pkg/a/x.go:50-60; see also ./cmd/main.go:7, \+ pkg/a/x.go:42 again, and version 1.2:3 is not a file. README.md:1";+ let found = citations(text);+ assert_eq!(+ found,+ vec![+ Citation {+ path: "pkg/a/x.go".into(),+ line: 42,+ end: 42+ },+ Citation {+ path: "pkg/a/x.go".into(),+ line: 50,+ end: 60+ },+ Citation {+ path: "cmd/main.go".into(),+ line: 7,+ end: 7+ },+ Citation {+ path: "1.2".into(),+ line: 3,+ end: 3+ },+ Citation {+ path: "README.md".into(),+ line: 1,+ end: 1+ },+ ]+ );+ assert_eq!(by_path(&found)["pkg/a/x.go"], vec![42, 50]);+ }++ fn tree() -> (PathBuf, Tree) {+ let dir = std::env::temp_dir().join(format!(+ "graphicle-lc-{}-{}",+ std::process::id(),+ rand_suffix()+ ));+ std::fs::create_dir_all(dir.join("pkg")).unwrap();+ std::fs::write(dir.join("pkg/x.go"), "package x\n\nfunc A() {}\n").unwrap();+ (dir.clone(), Tree::new(Some(dir)))+ }++ fn rand_suffix() -> u128 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ }++ #[test]+ fn citations_are_checked_against_the_tree() {+ let (dir, mut tree) = tree();+ assert_eq!(tree.problem("pkg/x.go", 3, 3), None);+ assert_eq!(tree.problem("pkg/x.go", 1, 3), None);+ assert!(tree.problem("pkg/x.go", 4, 4).unwrap().contains("3 lines"));+ assert!(+ tree.problem("pkg/y.go", 1, 1)+ .unwrap()+ .contains("no such file")+ );+ assert!(tree.problem("../etc/passwd", 1, 1).is_some());+ assert!(tree.problem("pkg/x.go", 3, 2).is_some());+ assert!(Tree::new(None).problem("pkg/x.go", 1, 1).is_some());+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn a_plan_is_checked_and_rendered() {+ let (dir, mut tree) = tree();+ let mut plan = json!({"summary":"Add B.","steps":["Write B","Test B"],+ "edits":[{"path":"pkg/x.go","start_line":3,"end_line":3,"reason":"call B"},+ {"path":"pkg/x.go","start_line":2,"end_line":9,"reason":"too far"},+ {"path":"pkg/z.go","start_line":1,"end_line":1,"reason":"missing"}],+ "new_files":[{"path":"pkg/b.go","purpose":"B"},{"path":"pkg/x.go","purpose":"exists"}],+ "tests":[{"action":"add","path":"pkg/b_test.go","what":"B works"},+ {"action":"run","path":"pkg/x_test.go","what":"nothing there"}],+ "risks":["B is slow"]});+ assert_eq!(check_plan(&mut plan, &mut tree), 4);+ assert_eq!(plan["edits"][0]["valid"], true);+ assert_eq!(plan["edits"][1]["valid"], false);+ assert_eq!(plan["new_files"][0]["valid"], true);+ assert_eq!(plan["new_files"][1]["valid"], false);+ assert_eq!(plan["tests"][0]["valid"], true);+ assert_eq!(plan["tests"][1]["valid"], false);+ let text = plan_markdown("Add B", &plan);+ assert!(text.starts_with("# Plan: Add B\n\nAdd B.\n\n## Steps\n\n1. Write B\n2. Test B\n"));+ assert!(text.contains("- pkg/x.go:3-3: call B\n"));+ assert!(+ text.contains("- pkg/x.go:2-9: too far (check: past the end of the file (3 lines))\n")+ );+ assert!(text.contains("## Risks\n\n- B is slow\n"));+ std::fs::remove_dir_all(dir).unwrap();+ }++ #[test]+ fn plans_are_read_from_fenced_or_bare_json() {+ assert_eq!(json_in("{\"a\":1}").unwrap()["a"], 1);+ assert_eq!(json_in("Here:\n```json\n{\"a\":2}\n```\n").unwrap()["a"], 2);+ assert!(json_in("no plan").is_err());+ }++ #[test]+ fn the_budget_fits_the_profile() {+ let profile: model::Profile = serde_json::from_value(json!({"protocol":"chat",+ "base_url":"https://api.meta.ai/v1","model":"muse-spark-1.3","key_env":"MODEL_API_KEY",+ "input_limit":1_016_576,"output_limit":32_000}))+ .unwrap();+ assert_eq!(budget_for(&profile, None).unwrap(), 1_016_576 - RESERVE);+ assert_eq!(budget_for(&profile, Some(128_000)).unwrap(), 128_000);+ assert!(budget_for(&profile, Some(1_100_000)).is_err());+ let small: model::Profile = serde_json::from_value(json!({"protocol":"chat",+ "base_url":"https://api.meta.ai/v1","model":"m","input_limit":4_000}))+ .unwrap();+ assert!(budget_for(&small, None).is_err());+ }++ #[test]+ fn a_calibrated_profile_fills_its_room() {+ let profile: model::Profile = serde_json::from_value(json!({"protocol":"chat",+ "base_url":"https://api.meta.ai/v1","model":"muse-spark-1.3","input_limit":104_000}))+ .unwrap();+ let room = 100_000.0;+ // The provider counted 0.8 of the estimate: a larger pack by estimate.+ let budget = budget_with(&profile, None, Some(0.8)).unwrap();+ assert_eq!(budget, (room * (1.0 - CALIBRATION_MARGIN) / 0.8) as usize);+ // --budget wins over the calibration.+ assert_eq!(+ budget_with(&profile, Some(50_000), Some(0.8)).unwrap(),+ 50_000+ );+ assert_eq!(budget_with(&profile, None, None).unwrap(), 100_000);+ let pack = json!({"tokenizer":"estimate","tokens":1000});+ assert!(prompt_estimate(&pack, "abc", "def").unwrap() > 1000);+ assert!(prompt_estimate(&json!({"tokenizer":"x","tokens":1}), "a", "b").is_none());+ }++ #[test]+ fn costs_come_from_the_configured_price() {+ let price = model::Price {+ input: 1.25,+ output: 4.25,+ cached_input: Some(0.15),+ per_image: None,+ };+ let cost = price.cost(1_000_000, 200_000, 10_000);+ assert!((cost - (0.8 * 1.25 + 0.2 * 0.15 + 0.01 * 4.25)).abs() < 1e-9);+ let done = model::Completion {+ input_tokens: Some(1000),+ output_tokens: Some(100),+ ..Default::default()+ };+ assert!(usage_json(&done, None)["cost_usd"].is_null());+ assert!(+ usage_json(&done, Some(&price))["cost_usd"]+ .as_f64()+ .unwrap()+ > 0.0+ );+ let line = crate::spend::line(&usage_json(&done, Some(&price)));+ assert!(line.starts_with("1,000 tokens in, 100 out; $"), "{line}");+ }+ #[test]+ fn the_cache_key_names_the_project_commit_and_prefix_only() {+ let pack = json!({"project":"my repo/\u{fc}","commit":"0123456789abcdef",+ "prefix_sha256":"e3b0c44298fc1c149afbf4c8996fb924","question":"a secret question"});+ let key = cache_key(&pack);+ assert_eq!(key, "graphicle:my-repo--@0123456789ab:e3b0c44298fc");+ assert!(!key.contains("secret"));+ assert_eq!(cache_key(&json!({"project":"p"})), "graphicle:p@nocommit:");+ }+}diff --git a/crates/graphicle/src/model.rs b/crates/graphicle/src/model.rsindex b1cd2a0..6ba5f93 100644--- a/crates/graphicle/src/model.rs+++ b/crates/graphicle/src/model.rs@@ -29,7 +29,138 @@ pub struct Profile {/// owns (messages, budgets, output format, sampling temperature) are rejected.#[serde(default, skip_serializing_if = "Option::is_none")]pub extra_body: Option<serde_json::Map<String, Value>>,+ /// What the provider charges, from the configuration (never built in):+ /// `ask --pack` and `plan` show a call's cost with it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub price: Option<Price>,+ /// The reasoning effort each call asks for (`reasoning.effort` on the+ /// Responses API, `reasoning_effort` on Chat Completions): `minimal`,+ /// `low`, `medium`, `high`, `xhigh` or `max`, or `none` where the+ /// provider takes it (the Meta Model API refuses it).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reasoning_effort: Option<String>,+ /// Whether `ask --pack` and `plan` send a prompt cache key (on the+ /// Responses API with a 24-hour retention): on by default for the Meta+ /// Model API, off for other providers.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub prompt_cache: Option<bool>,+ /// Whether `ask --pack` and `plan` count a request that comes near the+ /// input limit with the provider's `responses/input_tokens` endpoint+ /// before sending it, and pack again smaller if it would not fit: on by+ /// default for the Meta Model API's Responses profiles.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub count_tokens: Option<bool>,+ /// A Hugging Face `tokenizer.json` of the profile's model (Muse Spark+ /// Open's, for one): `ask --pack` and `plan` count their packs with it+ /// exactly instead of estimating.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub tokenizer: Option<String>,+ /// Refuse a long-context call whose worst case (its input, none of it+ /// cached, and the output limit) would cost more than this, in US dollars+ /// at the configured price.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_cost_per_call: Option<f64>,+ /// Refuse long-context calls once the day's logged cost of this profile+ /// (UTC) reaches this, in US dollars at the configured price.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub max_cost_per_day: Option<f64>,+}+/// Prices in US dollars per million tokens: input, output and, when the+/// provider discounts them, cached input tokens.+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]+#[serde(deny_unknown_fields)]+pub struct Price {+ pub input: f64,+ pub output: f64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub cached_input: Option<f64>,+ /// US dollars per image, for a model that bills images rather than+ /// tokens (SAM 3.1's segmentation, which `graphicle pixel` calls).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub per_image: Option<f64>,+}+impl Price {+ /// The cost in US dollars of `input` tokens (of which `cached` were+ /// cached) and `output` tokens.+ pub fn cost(&self, input: u64, cached: u64, output: u64) -> f64 {+ let cached = cached.min(input);+ let cached_rate = self.cached_input.unwrap_or(self.input);+ ((input - cached) as f64 * self.input+ + cached as f64 * cached_rate+ + output as f64 * self.output)+ / 1_000_000.0+ }+}+/// The reasoning efforts a profile may ask for.+pub const REASONING_EFFORTS: [&str; 7] =+ ["none", "minimal", "low", "medium", "high", "xhigh", "max"];+/// The Meta Model API's host.+pub const META_API_HOST: &str = "api.meta.ai";+/// The prompt cache retention long-context calls ask for on the Responses+/// API.+pub const PROMPT_CACHE_RETENTION: &str = "24h";++/// Whether a profile calls the Meta Model API.+pub fn meta_api(p: &Profile) -> bool {+ url::Url::parse(&p.base_url).is_ok_and(|url| {+ url.host_str()+ .is_some_and(|host| host.eq_ignore_ascii_case(META_API_HOST))+ })+}++/// Whether a profile's long-context calls send a prompt cache key.+pub fn prompt_cache_on(p: &Profile) -> bool {+ p.prompt_cache.unwrap_or_else(|| meta_api(p))}++/// Whether a profile's long-context calls count their requests with the+/// provider before sending them (Responses profiles only).+pub fn count_tokens_on(p: &Profile) -> bool {+ matches!(p.protocol.as_str(), "responses" | "azure_responses")+ && p.count_tokens.unwrap_or_else(|| meta_api(p))+}++/// How long a token count may take.+const COUNT_TIMEOUT: Duration = Duration::from_secs(300);++/// The provider's exact count of the input tokens of [`complete`]'s request+/// for the same arguments (`POST responses/input_tokens`, which generates+/// nothing). Only the request's model, instructions, input, output format+/// and reasoning are sent.+pub async fn count_input_tokens(+ p: &Profile,+ system: &str,+ user: &str,+ schema: Option<&Value>,+) -> Result<u64> {+ if !matches!(p.protocol.as_str(), "responses" | "azure_responses") {+ return Err(Error::bad("Only a Responses API profile counts tokens"));+ }+ let (_, body) = completion_body(p, system, user, schema, p.output_limit, None)?;+ let mut request = serde_json::Map::new();+ for field in ["model", "instructions", "input", "text", "reasoning"] {+ if let Some(value) = body.get(field) {+ request.insert(field.into(), value.clone());+ }+ }+ let credential = environment_credential(p)?;+ let client = client_with_timeout(COUNT_TIMEOUT)?;+ let response = authenticated(&client, p, "responses/input_tokens", credential.as_deref())?+ .json(&Value::Object(request))+ .send()+ .await+ .map_err(|error| Error::bad(request_failure("The token count request failed", &error)))?;+ let value = provider_json(response, credential.as_deref()).await?;+ value["input_tokens"]+ .as_u64()+ .ok_or_else(|| Error::bad("The provider's token count has no input_tokens"))+}++/// The largest input limit a profile may set: a context window of+/// 1,048,576 tokens (Muse Spark's).+pub const MAX_INPUT_LIMIT: usize = 1_048_576;+/// The largest output limit: reasoning models count their reasoning in it.+pub const MAX_OUTPUT_LIMIT: usize = 131_072;/// Chat request fields that carry the runtime's prompt, budget and output contract.const OWNED_CHAT_FIELDS: [&str; 13] = ["model",@@ -96,6 +227,22 @@ pub struct Config {/// Claude Code's prompt-context hook's settings ([`PromptContextSettings`]).#[serde(default, skip_serializing_if = "Option::is_none")]pub prompt_context: Option<PromptContextSettings>,+ /// `graphicle fix`'s settings ([`FixSettings`]).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fix: Option<FixSettings>,+}++/// `graphicle fix`'s settings (`fix.*` in the configuration file).+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct FixSettings {+ /// The test command `fix` runs in its worktree (with `sh -c`) when+ /// `--test` gives none.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub test: Option<String>,+ /// The seconds the test command may run [default: 600].+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub timeout_seconds: Option<u64>,}/// The prompt-context hook's settings (`prompt_context.*` in the@@ -141,6 +288,7 @@ impl Default for Config {update_notifier: None,sync: None,prompt_context: None,+ fix: None,}}}@@ -201,6 +349,19 @@ impl Config {crate::prompt_hook::MAX_SECONDS)));}+ if let Some(fix) = &self.fix+ && (fix+ .test+ .as_ref()+ .is_some_and(|t| t.trim().is_empty() || t.len() > 4096)+ || fix+ .timeout_seconds+ .is_some_and(|s| !(1..=86_400).contains(&s)))+ {+ return Err(Error::bad(+ "fix.test must be a command of at most 4096 characters, and fix.timeout_seconds 1 to 86400",+ ));+ }for (name, p) in &self.models {if name.is_empty()|| name.len() > 100@@ -217,8 +378,19 @@ impl Config {"local_onnx",].contains(&p.protocol.as_str())- || !(512..=128000).contains(&p.input_limit)- || !(64..=16000).contains(&p.output_limit)+ || !(512..=MAX_INPUT_LIMIT).contains(&p.input_limit)+ || !(64..=MAX_OUTPUT_LIMIT).contains(&p.output_limit)+ || p.price.as_ref().is_some_and(|price| {+ [+ Some(price.input),+ Some(price.output),+ price.cached_input,+ price.per_image,+ ]+ .into_iter()+ .flatten()+ .any(|rate| !rate.is_finite() || !(0.0..=10_000.0).contains(&rate))+ })|| p.temperature.is_some_and(|t| !t.is_finite() || !(0.0..=2.0).contains(&t)){@@ -236,6 +408,47 @@ impl Config {"Invalid extra_body: chat profiles only, at most 16 fields and 4 KiB, no runtime-owned fields",));}+ for (setting, cap) in [+ ("max_cost_per_call", p.max_cost_per_call),+ ("max_cost_per_day", p.max_cost_per_day),+ ] {+ let Some(cap) = cap else {+ continue;+ };+ if !cap.is_finite() || cap <= 0.0 || cap > 1_000_000.0 {+ return Err(Error::bad(format!(+ "models.{name}.{setting} must be a number of US dollars above 0"+ )));+ }+ if p.price.is_none() {+ return Err(Error::bad(format!(+ "models.{name}.{setting} is counted at the profile's price: set models.{name}.price too"+ )));+ }+ }+ if p.tokenizer+ .as_ref()+ .is_some_and(|path| path.is_empty() || path.len() > 4096)+ {+ return Err(Error::bad("tokenizer must be the path of a tokenizer.json"));+ }+ if let Some(effort) = &p.reasoning_effort {+ if effort == "none" && meta_api(p) {+ return Err(Error::bad(+ "The Meta Model API refuses reasoning_effort none: choose minimal, low, medium, high, xhigh or max",+ ));+ }+ if !REASONING_EFFORTS.contains(&effort.as_str())+ || !matches!(+ p.protocol.as_str(),+ "responses" | "azure_responses" | "chat" | "azure_chat"+ )+ {+ return Err(Error::bad(+ "reasoning_effort is none, minimal, low, medium, high, xhigh or max, on responses and chat profiles",+ ));+ }+ }if p.protocol == "local_onnx" {crate::local_inference::validate(p)?;} else {@@ -752,6 +965,391 @@ pub async fn generate_with_credential(reply(p, &value, estimated, start)}+/// How long a long-context call may take: a prompt of a million tokens is+/// read before the first answer token.+pub const LONG_TIMEOUT: Duration = Duration::from_secs(1800);++/// One long-context completion's result: the text and the provider's usage+/// counts (`None` where it reported none).+#[derive(Clone, Debug, Default)]+pub struct Completion {+ pub text: String,+ pub input_tokens: Option<u64>,+ pub output_tokens: Option<u64>,+ pub cached_tokens: Option<u64>,+ pub reasoning_tokens: Option<u64>,+ pub elapsed_ms: u64,+ pub model: String,+}++/// The request of [`complete`]: the endpoint and body, in the profile's+/// protocol. `user` goes in as it is (a pack and a question, not JSON); with+/// `schema`, the reply is a structured result where the profile has+/// structured output, else the schema is in the instructions; chat profiles+/// stream, with the usage in the last event. A profile with the prompt+/// cache on ([`prompt_cache_on`]) sends `prompt_cache_key`, and on the+/// Responses API a [`PROMPT_CACHE_RETENTION`] retention.+pub fn completion_body(+ p: &Profile,+ system: &str,+ user: &str,+ schema: Option<&Value>,+ output_limit: usize,+ prompt_cache_key: Option<&str>,+) -> Result<(String, Value)> {+ let plain = json!({"type":"object","properties":{"answer":{"type":"string"}}});+ let (suffix, mut body) = request_body(+ p,+ system,+ &json!(""),+ schema.unwrap_or(&plain),+ output_limit,+ )?;+ match p.protocol.as_str() {+ "responses" | "azure_responses" => body["input"] = json!(user),+ "chat" | "azure_chat" | "ollama" => body["messages"][1]["content"] = json!(user),+ "anthropic" => body["messages"][0]["content"] = json!(user),+ "gemini" => body["contents"][0]["parts"][0]["text"] = json!(user),+ _ => return Err(Error::bad("Unsupported inference protocol")),+ }+ if schema.is_none() {+ let fields = body.as_object_mut().expect("request bodies are objects");+ match p.protocol.as_str() {+ "responses" | "azure_responses" => {+ fields.remove("text");+ fields.insert("instructions".into(), json!(system));+ }+ "chat" | "azure_chat" => {+ fields.remove("response_format");+ body["messages"][0]["content"] = json!(system);+ }+ "ollama" => {+ fields.remove("format");+ body["messages"][0]["content"] = json!(system);+ }+ "anthropic" => {+ fields.remove("tools");+ fields.remove("tool_choice");+ fields.insert("system".into(), json!(system));+ }+ _ => {+ if let Some(config) = body["generationConfig"].as_object_mut() {+ config.remove("responseMimeType");+ config.remove("responseJsonSchema");+ }+ body["systemInstruction"]["parts"][0]["text"] = json!(system);+ }+ }+ }+ if matches!(p.protocol.as_str(), "chat" | "azure_chat") {+ body["stream"] = json!(true);+ body["stream_options"] = json!({"include_usage":true});+ }+ if let Some(key) = prompt_cache_key.filter(|_| prompt_cache_on(p)) {+ match p.protocol.as_str() {+ "responses" | "azure_responses" => {+ body["prompt_cache_key"] = json!(key);+ body["prompt_cache_retention"] = json!(PROMPT_CACHE_RETENTION);+ }+ "chat" | "azure_chat" => body["prompt_cache_key"] = json!(key),+ _ => {}+ }+ }+ Ok((suffix, body))+}++/// One long-context completion (`ask --pack`, `plan`) with the profile's+/// credential from its environment variable. A chat profile's reply streams:+/// `on_text` gets the answer as it arrives, and a gateway's limit on waiting+/// for a whole reply does not cut a long request.+pub async fn complete(+ p: &Profile,+ system: &str,+ user: &str,+ schema: Option<&Value>,+ output_limit: usize,+ prompt_cache_key: Option<&str>,+ on_text: &mut (dyn FnMut(&str) + Send),+) -> Result<Completion> {+ complete_with(+ p,+ system,+ user,+ None,+ schema,+ output_limit,+ prompt_cache_key,+ on_text,+ )+ .await+}++/// [`complete`] with the Responses API's `input` given whole: messages whose+/// content holds parts, such as an `input_image` with a base64 data URL+/// (`graphicle pixel`). Only a Responses API profile takes it.+pub async fn complete_input(+ p: &Profile,+ system: &str,+ input: &Value,+ schema: Option<&Value>,+ output_limit: usize,+ on_text: &mut (dyn FnMut(&str) + Send),+) -> Result<Completion> {+ if !matches!(p.protocol.as_str(), "responses" | "azure_responses") {+ return Err(Error::bad(+ "Images go to a Responses API profile, such as the Meta Model API's (graphicle config set model meta)",+ ));+ }+ complete_with(+ p,+ system,+ "",+ Some(input),+ schema,+ output_limit,+ None,+ on_text,+ )+ .await+}++/// POST `body` as it is to the profile's endpoint `suffix` with its+/// credential, and the reply's JSON (a refusal keeps the provider's reason,+/// without the credential). For a call that is not a completion, such as+/// SAM 3.1's segmentation on the Responses API (`graphicle pixel`).+pub async fn post_json(+ p: &Profile,+ suffix: &str,+ body: &Value,+ timeout: Duration,+) -> Result<Value> {+ let credential = environment_credential(p)?;+ let client = client_with_timeout(timeout)?;+ let response = authenticated(&client, p, suffix, credential.as_deref())?+ .json(body)+ .send()+ .await+ .map_err(|error| {+ Error::bad(request_failure(+ "Provider request failed before a response",+ &error,+ ))+ })?;+ provider_json(response, credential.as_deref()).await+}++#[allow(clippy::too_many_arguments)]+async fn complete_with(+ p: &Profile,+ system: &str,+ user: &str,+ input: Option<&Value>,+ schema: Option<&Value>,+ output_limit: usize,+ prompt_cache_key: Option<&str>,+ on_text: &mut (dyn FnMut(&str) + Send),+) -> Result<Completion> {+ if output_limit < 64 || output_limit > p.output_limit {+ return Err(Error::bad(+ "Inference request exceeds the configured model budget",+ ));+ }+ let credential = environment_credential(p)?;+ let client = client_with_timeout(LONG_TIMEOUT)?;+ let (suffix, mut body) =+ completion_body(p, system, user, schema, output_limit, prompt_cache_key)?;+ if let Some(input) = input {+ body["input"] = input.clone();+ }+ let start = Instant::now();+ let send = |body: &Value| {+ let request = authenticated(&client, p, &suffix, credential.as_deref());+ let body = body.clone();+ async move {+ request?.json(&body).send().await.map_err(|error| {+ let what = if error.is_timeout() {+ "Provider request timed out; usage may be unknown"+ } else if error.is_connect() {+ "Could not establish the provider connection"+ } else {+ "Provider request failed before a response; usage may be unknown"+ };+ Error::bad(request_failure(what, &error))+ })+ }+ };+ let mut response = send(&body).await?;+ // A server that refuses `stream_options` (not every OpenAI-compatible+ // server takes it): once more without it.+ if body["stream"] == true && response.status() == reqwest::StatusCode::BAD_REQUEST {+ let mut plain = body.clone();+ if let Some(fields) = plain.as_object_mut() {+ fields.remove("stream_options");+ }+ response = send(&plain).await?;+ }+ if body["stream"] == true && response.status().is_success() {+ return stream_reply(p, response, start, on_text).await;+ }+ let value = provider_json(response, credential.as_deref()).await?;+ let mut effective = p.clone();+ effective.structured_output = schema.is_some() && p.structured_output;+ let estimated = (system.len() + user.len()) / 4;+ let reply = reply(&effective, &value, estimated, start)?;+ on_text(&reply.text);+ let usage = &value["usage"];+ Ok(Completion {+ text: reply.text,+ input_tokens: reply.usage_reported.then_some(reply.input_tokens as u64),+ output_tokens: reply.usage_reported.then_some(reply.output_tokens as u64),+ cached_tokens: usage["input_tokens_details"]["cached_tokens"]+ .as_u64()+ .or(usage["prompt_tokens_details"]["cached_tokens"].as_u64())+ .or(usage["cache_read_input_tokens"].as_u64()),+ reasoning_tokens: usage["output_tokens_details"]["reasoning_tokens"]+ .as_u64()+ .or(usage["completion_tokens_details"]["reasoning_tokens"].as_u64()),+ elapsed_ms: reply.elapsed_ms,+ model: reply.model,+ })+}++/// Bytes of a streamed reply read at most.+const STREAM_BYTES: usize = 16 << 20;++/// A chat completion's server-sent events as one [`Completion`]: the content+/// deltas in order, the finish reason, and the usage of the last event. A+/// server that answers without streaming is read as one reply.+async fn stream_reply(+ p: &Profile,+ mut response: reqwest::Response,+ start: Instant,+ on_text: &mut (dyn FnMut(&str) + Send),+) -> Result<Completion> {+ let mut pending: Vec<u8> = Vec::new();+ let mut whole: Vec<u8> = Vec::new();+ let mut done = Completion {+ model: p.model.clone(),+ ..Completion::default()+ };+ let mut finish: Option<String> = None;+ let mut refusal = String::new();+ let mut events = 0usize;+ let mut handle = |line: &[u8],+ done: &mut Completion,+ finish: &mut Option<String>,+ refusal: &mut String,+ events: &mut usize| {+ let line = String::from_utf8_lossy(line);+ let Some(data) = line.trim_end_matches('\r').strip_prefix("data:") else {+ return;+ };+ let data = data.trim();+ if data.is_empty() || data == "[DONE]" {+ return;+ }+ let Ok(event) = serde_json::from_str::<Value>(data) else {+ return;+ };+ *events += 1;+ if let Some(model) = event["model"].as_str() {+ done.model = model.to_string();+ }+ let choice = &event["choices"][0];+ if let Some(delta) = choice["delta"]["content"].as_str()+ && !delta.is_empty()+ {+ done.text.push_str(delta);+ on_text(delta);+ }+ if let Some(text) = choice["delta"]["refusal"].as_str() {+ refusal.push_str(text);+ }+ if let Some(reason) = choice["finish_reason"].as_str() {+ *finish = Some(reason.to_string());+ }+ let usage = &event["usage"];+ if usage.is_object() {+ done.input_tokens = usage["prompt_tokens"].as_u64();+ done.output_tokens = usage["completion_tokens"].as_u64();+ done.cached_tokens = usage["prompt_tokens_details"]["cached_tokens"].as_u64();+ done.reasoning_tokens = usage["completion_tokens_details"]["reasoning_tokens"].as_u64();+ }+ };+ loop {+ let chunk = match response.chunk().await {+ Ok(Some(chunk)) => chunk,+ Ok(None) => break,+ Err(error) => {+ return Err(Error::bad(request_failure(+ "The provider's streamed reply broke off; usage may be unknown",+ &error,+ )));+ }+ };+ if whole.len() < STREAM_BYTES {+ whole.extend_from_slice(&chunk);+ }+ pending.extend_from_slice(&chunk);+ while let Some(end) = pending.iter().position(|&b| b == b'\n') {+ let line: Vec<u8> = pending.drain(..=end).collect();+ handle(+ &line[..line.len() - 1],+ &mut done,+ &mut finish,+ &mut refusal,+ &mut events,+ );+ }+ if whole.len() >= STREAM_BYTES && events == 0 {+ return Err(Error::bad("The provider's reply is too large"));+ }+ }+ if !pending.is_empty() {+ let line = std::mem::take(&mut pending);+ handle(&line, &mut done, &mut finish, &mut refusal, &mut events);+ }+ if events == 0 {+ // Not a stream: one JSON reply.+ let value: Value = serde_json::from_slice(&whole)+ .map_err(|_| Error::bad("The provider's reply was neither a stream nor JSON"))?;+ let reply = reply(p, &value, 0, start)?;+ on_text(&reply.text);+ let usage = &value["usage"];+ return Ok(Completion {+ text: reply.text,+ input_tokens: usage["prompt_tokens"].as_u64(),+ output_tokens: usage["completion_tokens"].as_u64(),+ cached_tokens: usage["prompt_tokens_details"]["cached_tokens"].as_u64(),+ reasoning_tokens: usage["completion_tokens_details"]["reasoning_tokens"].as_u64(),+ elapsed_ms: start.elapsed().as_millis() as u64,+ model: reply.model,+ });+ }+ done.elapsed_ms = start.elapsed().as_millis() as u64;+ if !refusal.is_empty() {+ return Err(Error::bad("Model declined the inference request"));+ }+ match finish.as_deref() {+ Some("stop") => {}+ Some("length") => {+ return Err(Error::bad(+ "Model did not complete the answer (max_output_tokens): raise the profile's output_limit",+ ));+ }+ Some(other) => return Err(Error::bad(format!("Model answer ended early ({other})"))),+ None => {+ return Err(Error::bad(+ "The provider's streamed reply ended without finishing",+ ));+ }+ }+ if done.text.trim().is_empty() {+ return Err(Error::bad("Model returned no answer"));+ }+ Ok(done)+}+/// What the Anthropic transport's structured mode adds to the instructions:/// the tool is offered with `tool_choice: auto`, because current Claude/// models (Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.1) refuse a@@ -893,6 +1491,15 @@ pub fn request_body(}}}+ // The profile's reasoning effort, in each API's own field (over one an+ // extra_body sets).+ if let Some(effort) = &p.reasoning_effort {+ match p.protocol.as_str() {+ "responses" | "azure_responses" => body["reasoning"] = json!({"effort":effort}),+ "chat" | "azure_chat" => body["reasoning_effort"] = json!(effort),+ _ => {}+ }+ }Ok((suffix, body))}@@ -1635,4 +2242,67 @@ mod tests {);}}+ /// A long-context call to the Meta Model API asks for the profile's+ /// reasoning effort and, on the Responses API, sends the prompt cache key+ /// with a 24-hour retention; chat servers get the key only when the+ /// profile opts in.+ #[test]+ fn long_context_calls_carry_the_cache_key_and_the_reasoning_effort() {+ let meta: Profile = serde_json::from_value(json!({"protocol":"responses",+ "base_url":"https://api.meta.ai/v1","model":"muse-spark-1.3","key_env":"MODEL_API_KEY",+ "input_limit":1_016_576,"output_limit":32_000,"reasoning_effort":"low"}))+ .unwrap();+ assert!(super::meta_api(&meta) && super::prompt_cache_on(&meta));+ let (path, body) = super::completion_body(+ &meta,+ "Stable rules",+ "pack\nQuestion: q\n",+ None,+ 1_000,+ Some("graphicle:demo@0123456789ab:e3b0c44298fc"),+ )+ .unwrap();+ assert_eq!(path, "responses");+ assert_eq!(body["instructions"], "Stable rules");+ assert_eq!(body["input"], "pack\nQuestion: q\n");+ assert_eq!(body["max_output_tokens"], 1_000);+ assert_eq!(body["reasoning"]["effort"], "low");+ assert_eq!(+ body["prompt_cache_key"],+ "graphicle:demo@0123456789ab:e3b0c44298fc"+ );+ assert_eq!(body["prompt_cache_retention"], "24h");+ // The same profile on Chat Completions: the key, no retention.+ let mut chat = meta.clone();+ chat.protocol = "chat".into();+ let (_, body) =+ super::completion_body(&chat, "Stable rules", "u", None, 1_000, Some("k")).unwrap();+ assert_eq!(body["reasoning_effort"], "low");+ assert_eq!(body["prompt_cache_key"], "k");+ assert!(body.get("prompt_cache_retention").is_none());+ // A vLLM server: no key unless the profile opts in.+ let mut vllm = profile("chat", true);+ let (_, body) =+ super::completion_body(&vllm, "Stable rules", "u", None, 500, Some("k")).unwrap();+ assert!(body.get("prompt_cache_key").is_none());+ assert!(body.get("reasoning_effort").is_none());+ vllm.prompt_cache = Some(true);+ let (_, body) =+ super::completion_body(&vllm, "Stable rules", "u", None, 500, Some("k")).unwrap();+ assert_eq!(body["prompt_cache_key"], "k");+ // The Meta Model API refuses reasoning effort none; other values are+ // checked.+ for (effort, valid) in [("none", false), ("max", true), ("fast", false)] {+ let mut p = meta.clone();+ p.reasoning_effort = Some(effort.into());+ let config: Config =+ serde_json::from_value(json!({"default_model":"m","models":{"m":p}})).unwrap();+ assert_eq!(config.validate().is_ok(), valid, "{effort}");+ }+ let mut local = profile("chat", true);+ local.reasoning_effort = Some("none".into());+ let config: Config =+ serde_json::from_value(json!({"default_model":"m","models":{"m":local}})).unwrap();+ assert!(config.validate().is_ok());+ }}diff --git a/crates/graphicle/src/muse_code.rs b/crates/graphicle/src/muse_code.rsnew file mode 100644index 0000000..3c0f5a4--- /dev/null+++ b/crates/graphicle/src/muse_code.rs@@ -0,0 +1,750 @@+//! Muse Code, Meta's coding agent: Graphicle as a native Muse plugin.+//!+//! `graphicle connect muse --hooks` writes the plugin into the data folder+//! ([`PLUGIN_FOLDER`]) and installs it with `muse plugins install <folder>+//! --scope user`. It is opt-in (a preview) until it has passed a live check+//! with Muse Code: `graphicle setup` keeps Muse Code's settings entry, and+//! keeps an installed plugin's paths current instead of adding an entry+//! beside it. Muse Code reviews a plugin's hooks and MCP servers: the+//! person approves them once with `muse plugins approve graphicle`. The+//! package is a native Muse plugin (`.muse-plugin/plugin.json`, the contract+//! of Muse Code's own `create-plugin` skill) with three capability families:+//! * the MCP server: `graphicle mcp --project . --or-workspace` with the+//! flags `connect` chose, the project of the folder Muse Code starts it+//! in, else every project of the workspace, so it starts in any folder;+//! it sets `"mode": "optional"` as the settings entry does; Muse Code+//! accepts the field in a plugin's server (no diagnostics on validate,+//! install or inspect) but does not show it, so whether it skips a plugin+//! server that cannot start is not confirmed (`hook_probe.py` checks);+//! * the `graphicle` skill ([`SKILL`]): when to call which tool;+//! * hooks ([`HOOKS`]) that run `graphicle hook muse <event>`: the session+//! start adds the project's repository map and its reviewed memory, a+//! prompt adds the evidence for a code question, a batch of searches adds+//! a pointer to the graph tools, and the end of a turn captures the+//! session log as a source.+//!+//! The context goes in at the session's start and after each prompt, never+//! before every model call, so the start of the conversation (system+//! prompt, tools, then Graphicle's map and memory) is the same bytes for the+//! whole session and the API's prompt cache keeps serving it. The map is+//! the repository part of a cache-layout pack ([`crate::code_pack`],+//! `--prefix-share 1.0`): the same bytes for every session at a commit.+//! It is built in the background and kept in the data folder+//! ([`session_pack`]), so a session start never waits for a pack.+use crate::{Error, Result};+use serde_json::{Value, json};+use std::path::{Path, PathBuf};++/// The plugin's id in Muse Code.+pub const PLUGIN_ID: &str = "graphicle";+/// The folder in the data folder that holds the generated plugin.+pub const PLUGIN_FOLDER: &str = "muse-code-plugin";+/// The folder in the data folder that holds the session packs.+pub const PACK_FOLDER: &str = "muse-code-packs";+/// The `graphicle` skill the plugin carries. The plugin in+/// `packaging/muse-code-plugin` holds the same text.+pub const SKILL: &str = include_str!("muse_code_skill.md");+/// Tokens of the repository map a session starts with, unless the hook's+/// `--pack-tokens` says otherwise (0 leaves it out).+pub const SESSION_PACK_TOKENS: u64 = 8_000;+/// Most tokens `--pack-tokens` may give.+pub const SESSION_PACK_MAX: u64 = 100_000;+/// A session pack younger than this is used without a rebuild.+const PACK_FRESH: std::time::Duration = std::time::Duration::from_secs(600);++/// One hook of the plugin: its id, Muse Code's event, the argument of+/// `graphicle hook muse` and Muse Code's timeout in milliseconds.+#[derive(Clone, Copy, Debug)]+pub struct Hook {+ pub id: &'static str,+ pub event: &'static str,+ pub argument: &'static str,+ pub timeout_ms: u64,+}++/// The plugin's hooks. Session start waits at most 2.5 s for its context+/// (the timeout leaves room for the system's first-launch check of an+/// updated program); the prompt hook gives up by itself after its budget+/// ([`crate::prompt_hook::budget`]); capture hands the import to a detached+/// process.+pub const HOOKS: [Hook; 6] = [+ Hook {+ id: "session-start",+ event: "SessionStart",+ argument: "session-start",+ timeout_ms: 10_000,+ },+ Hook {+ id: "prompt-context",+ event: "UserPromptSubmit",+ argument: "prompt-context",+ timeout_ms: crate::prompt_hook::HOOK_TIMEOUT * 1000,+ },+ Hook {+ id: "tool-batch",+ event: "PostToolBatch",+ argument: "tool-batch",+ timeout_ms: 5_000,+ },+ Hook {+ id: "stop",+ event: "Stop",+ argument: "stop",+ timeout_ms: 10_000,+ },+ Hook {+ id: "pre-compact",+ event: "PreCompact",+ argument: "pre-compact",+ timeout_ms: 10_000,+ },+ Hook {+ id: "session-end",+ event: "SessionEnd",+ argument: "session-end",+ timeout_ms: 10_000,+ },+];++/// The server flags of the package in `packaging/`: the whole server, with+/// the memory proposals a person reviews (`connect muse --hooks+/// --allow-learning`).+pub const PACKAGED_SERVER_FLAGS: [&str; 1] = ["--allow-learning"];++/// The plugin's manifest. `program` and `data` are the program and data+/// folder its commands run with: the absolute paths `connect muse --hooks`+/// writes, or `graphicle` and `None` for the package in `packaging/`, which+/// runs the `graphicle` on `PATH` with its default data folder.+/// `pack_tokens` sizes the session start's repository map; `server` holds+/// the server's flags after `mcp --project . --or-workspace` (`--tools`,+/// `--allow-learning`, `--work-state`, as `connect` chose them). The server+/// sets `"mode": "optional"`, as the settings entry does, so that Muse Code+/// can skip it when it cannot start (Graphicle uninstalled, its data folder+/// gone). Muse Code accepts the field for a plugin's server but does not show+/// it, so that is not confirmed: `graphicle disconnect muse` removes the+/// plugin before an uninstall.+pub fn manifest(program: &str, data: Option<&Path>, pack_tokens: u64, server: &[&str]) -> Value {+ let prefix = |rest: &[&str]| -> Vec<String> {+ let mut argv = vec![program.to_string()];+ if let Some(data) = data {+ argv.push("--data-dir".into());+ argv.push(data.to_string_lossy().into_owned());+ }+ argv.extend(rest.iter().map(|arg| arg.to_string()));+ argv+ };+ let mut server_args = vec!["mcp", "--project", ".", "--or-workspace"];+ server_args.extend_from_slice(server);+ let hooks: Vec<Value> = HOOKS+ .iter()+ .map(|hook| {+ let mut argv = prefix(&["hook", "muse", hook.argument]);+ if hook.argument == "session-start" && pack_tokens != SESSION_PACK_TOKENS {+ argv.extend(["--pack-tokens".into(), pack_tokens.to_string()]);+ }+ json!({"id":hook.id,"event":hook.event,"command":argv,"timeoutMs":hook.timeout_ms})+ })+ .collect();+ json!({+ "schemaVersion": 1,+ "name": PLUGIN_ID,+ "displayName": "Graphicle",+ "version": env!("CARGO_PKG_VERSION"),+ "description": "Graphicle's code graph, whole-repository packs and reviewed project memory for Muse Code, with the context added at session start and per prompt.",+ "compat": {"source": "native", "manifestDir": ".muse-plugin"},+ "capabilities": {+ "skills": [{"id": PLUGIN_ID, "path": "skills/graphicle/SKILL.md", "enabledDefault": true}],+ "commands": [],+ "hooks": hooks,+ "mcpServers": [{+ "id": PLUGIN_ID,+ "transport": "stdio",+ "command": prefix(&server_args),+ "mode": "optional",+ }],+ "reminders": [],+ },+ })+}++/// Write the plugin package into `folder`: the manifest and the skill.+/// Files of the package that are already the same bytes are left alone.+pub fn write_package(folder: &Path, manifest: &Value) -> Result<bool> {+ let files = [+ (+ folder.join(".muse-plugin/plugin.json"),+ format!("{}\n", serde_json::to_string_pretty(manifest)?),+ ),+ (folder.join("skills/graphicle/SKILL.md"), SKILL.to_string()),+ ];+ let mut changed = false;+ for (path, text) in files {+ if std::fs::read_to_string(&path).is_ok_and(|old| old == text) {+ continue;+ }+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)?;+ }+ std::fs::write(&path, text)?;+ changed = true;+ }+ Ok(changed)+}++/// The `muse` program: on `PATH`, else where Muse Code's installer puts it+/// (`~/.local/bin/muse`).+pub fn program() -> Option<PathBuf> {+ let env = crate::agent_detect::Environment::current();+ env.program("muse").or_else(|| {+ crate::platform::home_dir()+ .map(|home| home.join(".local/bin/muse"))+ .filter(|path| path.is_file())+ })+}++/// Run `muse plugins <args> --json`; the reply is its exit status, and its+/// JSON (or its text) from standard output and error.+fn plugins(muse: &Path, args: &[&str]) -> Result<(bool, Value)> {+ let output = std::process::Command::new(muse)+ .arg("plugins")+ .args(args)+ .arg("--json")+ .stdin(std::process::Stdio::null())+ .output()+ .map_err(|error| Error::bad(format!("Cannot run {}: {error}", muse.display())))?;+ let text = String::from_utf8_lossy(&output.stdout);+ let reply = serde_json::from_str::<Value>(text.trim()).unwrap_or_else(|_| {+ let mut both = text.trim().to_string();+ let error = String::from_utf8_lossy(&output.stderr);+ if !error.trim().is_empty() {+ both.push_str(if both.is_empty() { "" } else { "\n" });+ both.push_str(error.trim());+ }+ let cut: String = both.chars().take(2000).collect();+ Value::String(cut)+ });+ Ok((output.status.success(), reply))+}++/// Install the package in `folder` for the user, or refresh an earlier+/// install from it (`muse plugins update`). Muse Code keeps its own record+/// of installed plugins; `muse plugins remove graphicle` undoes this.+pub fn install(muse: &Path, folder: &Path) -> Result<Value> {+ let path = folder.to_string_lossy().into_owned();+ let (installed, reply) = plugins(muse, &["install", &path, "--scope", "user"])?;+ if installed {+ return Ok(json!({"state":"installed","muse":reply}));+ }+ // Installed before: refresh it from the folder.+ let (updated, again) = plugins(muse, &["update", PLUGIN_ID])?;+ if updated {+ return Ok(json!({"state":"updated","muse":again}));+ }+ Err(Error::bad(format!(+ "muse plugins install {path} --scope user failed: {}",+ match &reply {+ Value::String(text) => text.clone(),+ other => other.to_string(),+ }+ )))+}++/// Refresh the installed plugin from its folder (`muse plugins update+/// graphicle`), after its package changed.+pub fn update(muse: &Path) -> Result<Value> {+ let (updated, reply) = plugins(muse, &["update", PLUGIN_ID])?;+ if updated {+ return Ok(reply);+ }+ Err(Error::bad(format!(+ "muse plugins update {PLUGIN_ID} failed: {}",+ match &reply {+ Value::String(text) => text.clone(),+ other => other.to_string(),+ }+ )))+}++/// Remove the plugin from Muse Code (`muse plugins remove graphicle`).+pub fn remove(muse: &Path) -> Result<Value> {+ let (removed, reply) = plugins(muse, &["remove", PLUGIN_ID])?;+ Ok(json!({"removed":removed,"muse":reply}))+}++/// Undo the plugin for `graphicle disconnect`: `muse plugins remove+/// graphicle`, then the package Graphicle wrote in the data folder `data`+/// (whose manifest is `manifest`). Without the `muse` program, Muse Code's+/// record stays and the outcome says how to remove it.+pub fn undo(manifest: &Path, data: &Path) -> Result<Value> {+ let package = manifest+ .parent()+ .and_then(Path::parent)+ .ok_or_else(|| Error::bad("Not a plugin manifest"))?;+ let ours = |path: &Path| {+ use crate::platform::CanonicalExt;+ let expected = data.join(PLUGIN_FOLDER);+ path.canonical()+ .ok()+ .is_some_and(|found| Some(found) == expected.as_path().canonical().ok())+ };+ if !ours(package) {+ return Err(Error::bad(format!(+ "{} is not Graphicle's Muse Code plugin; remove it with muse plugins remove {PLUGIN_ID}",+ package.display()+ )));+ }+ let mut removed = Vec::new();+ let mut outcome = json!({"file":manifest,"state":"deleted"});+ match program() {+ Some(muse) => {+ let reply = remove(&muse)?;+ if reply["removed"] == true {+ removed.push(format!("removed the {PLUGIN_ID} plugin from Muse Code"));+ } else {+ outcome["next"] = json!(format!(+ "Muse Code did not remove the plugin; run muse plugins remove {PLUGIN_ID}"+ ));+ }+ outcome["muse"] = reply["muse"].clone();+ }+ None => {+ outcome["next"] = json!(format!(+ "The muse program was not found: run muse plugins remove {PLUGIN_ID}"+ ));+ }+ }+ std::fs::remove_dir_all(package)?;+ removed.push("deleted the plugin package".to_string());+ outcome["removed"] = json!(removed);+ Ok(outcome)+}++/// Muse Code's session root: `$XDG_DATA_HOME/muse/sessions`, else+/// `~/.local/share/muse/sessions`.+pub fn sessions_root() -> Option<PathBuf> {+ crate::capture::default_root(crate::capture::Client::Muse)+}++/// The session log a hook's payload belongs to: its `transcript_path`, else+/// `MUSE_CURRENT_SESSION_LOG`, else the log of its session id (the+/// payload's `session_id`, else `MUSE_SESSION_ID`) under the session root:+/// `YYYY/MM/DD/<session>/session.jsonl`, sub-agents' logs left out.+pub fn session_log(payload: &Value) -> Option<PathBuf> {+ let given = payload["transcript_path"]+ .as_str()+ .map(PathBuf::from)+ .or_else(|| std::env::var_os("MUSE_CURRENT_SESSION_LOG").map(PathBuf::from));+ if let Some(path) = given.filter(|path| path.is_file()) {+ return Some(path);+ }+ let session = payload["session_id"]+ .as_str()+ .map(str::to_string)+ .or_else(|| std::env::var("MUSE_SESSION_ID").ok())?;+ if session.is_empty()+ || session.len() > 100+ || !session+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')+ {+ return None;+ }+ find_session_log(&sessions_root()?, &session)+}++/// `<root>/YYYY/MM/DD/<session>/session.jsonl`, newest day first.+pub fn find_session_log(root: &Path, session: &str) -> Option<PathBuf> {+ let sorted = |folder: &Path| -> Vec<PathBuf> {+ let mut found: Vec<PathBuf> = std::fs::read_dir(folder)+ .into_iter()+ .flatten()+ .flatten()+ .map(|entry| entry.path())+ .filter(|path| path.is_dir())+ .collect();+ found.sort();+ found.reverse();+ found+ };+ for year in sorted(root) {+ for month in sorted(&year) {+ for day in sorted(&month) {+ let log = day.join(session).join("session.jsonl");+ if log.is_file() {+ return Some(log);+ }+ }+ }+ }+ None+}++/// Where the session pack of `project` at `tokens` is kept.+fn pack_path(directory: &Path, project: &str, tokens: u64) -> PathBuf {+ let safe: String = project+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })+ .take(80)+ .collect();+ directory+ .join(PACK_FOLDER)+ .join(format!("{safe}-{tokens}.md"))+}++/// The repository map a session of `project` starts with: the kept session+/// pack, when there is one. A missing pack, or one older than ten minutes,+/// is rebuilt by a detached `graphicle hook muse pack` ([`build_pack`]), so+/// the next session has it; this one is never held up.+pub fn session_pack(directory: &Path, project: &str, tokens: u64) -> Option<String> {+ if tokens == 0 {+ return None;+ }+ let path = pack_path(directory, project, tokens);+ let kept = std::fs::metadata(&path).ok();+ let fresh = kept+ .as_ref()+ .and_then(|meta| meta.modified().ok())+ .and_then(|time| time.elapsed().ok())+ .is_some_and(|age| age < PACK_FRESH);+ if !fresh && let Ok(executable) = std::env::current_exe() {+ let mut command = std::process::Command::new(executable);+ command+ .arg("--data-dir")+ .arg(directory)+ .args(["hook", "muse", "pack", "--project", project])+ .args(["--pack-tokens", &tokens.to_string()])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null());+ let _ = crate::platform::spawn_detached(&mut command);+ }+ kept.and_then(|_| std::fs::read_to_string(&path).ok())+ .filter(|text| !text.trim().is_empty())+}++/// Build and keep the session pack of `project` at `tokens`: the repository+/// part of a cache-layout pack with prefix share 1.0 (the same bytes for+/// every question at a commit), written whole and renamed into place. One+/// build at a time per pack: a second one finds the lock and leaves.+pub fn build_pack(store: &crate::store::Store, project: &str, tokens: u64) -> Result<PathBuf> {+ let session = crate::local::session(store, false)?;+ let path = pack_path(&store.directory, project, tokens);+ let folder = path+ .parent()+ .ok_or_else(|| Error::bad("No pack folder"))?+ .to_path_buf();+ std::fs::create_dir_all(&folder)?;+ let lock = path.with_extension("lock");+ // A lock left by a build that died is taken over after ten minutes.+ if std::fs::metadata(&lock)+ .and_then(|meta| meta.modified())+ .is_ok_and(|time| time.elapsed().unwrap_or_default() > PACK_FRESH)+ {+ let _ = std::fs::remove_file(&lock);+ }+ let Ok(_held) = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&lock)+ else {+ return Ok(path);+ };+ let built = (|| -> Result<()> {+ let pack = store.project_pack(+ &session.workspace,+ &session.capability,+ &json!({"repository_id":project,"question":"","budget":tokens,+ "layout":"cache","prefix_share":1.0,"style":"markdown"}),+ )?;+ let text = crate::code_pack::text(&pack);+ let mut file = tempfile::NamedTempFile::new_in(&folder)?;+ std::io::Write::write_all(&mut file, text.as_bytes())?;+ file.persist(&path).map_err(|error| error.error)?;+ Ok(())+ })();+ let _ = std::fs::remove_file(&lock);+ built.map(|()| path)+}++/// The tool calls a PostToolBatch payload names: each object with a tool+/// name (`tool_name` or `name`) and its input (`tool_input`, `input`,+/// `args` or `arguments`), at any depth.+fn batch_calls(payload: &Value) -> Vec<(String, Value)> {+ let mut found = Vec::new();+ let mut stack = vec![payload];+ while let Some(value) = stack.pop() {+ match value {+ Value::Object(map) => {+ let name = map+ .get("tool_name")+ .or(map.get("name"))+ .and_then(Value::as_str);+ let input = ["tool_input", "input", "args", "arguments"]+ .iter()+ .find_map(|key| map.get(*key));+ if let (Some(name), Some(input)) = (name, input) {+ let input = input+ .as_str()+ .and_then(|text| serde_json::from_str::<Value>(text).ok())+ .unwrap_or_else(|| input.clone());+ found.push((name.to_string(), input));+ }+ stack.extend(map.values());+ }+ Value::Array(items) => stack.extend(items),+ _ => {}+ }+ if found.len() > 256 {+ break;+ }+ }+ found+}++/// How many calls of a batch searched the repository's text: a search tool+/// (`grep`, `search`, `glob`, `find`) or a shell command that runs one.+pub fn searches(payload: &Value) -> usize {+ batch_calls(payload)+ .iter()+ .filter(|(name, input)| {+ let short = name+ .rsplit(['.', '/'])+ .next()+ .unwrap_or(name)+ .rsplit("__")+ .next()+ .unwrap_or(name)+ .to_ascii_lowercase();+ if short.contains("graphicle") || name.contains("graphicle") {+ return false;+ }+ let shell = ["bash", "shell", "exec_command", "run_shell", "terminal"]+ .iter()+ .any(|tool| short == *tool);+ if shell {+ let command = input["command"]+ .as_str()+ .or(input["cmd"].as_str())+ .map(str::to_string)+ .or_else(|| {+ input["command"].as_array().map(|parts| {+ parts+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(" ")+ })+ })+ .unwrap_or_default();+ return crate::agent_setup::runs_a_search(&command);+ }+ ["grep", "search", "glob", "find"]+ .iter()+ .any(|word| short.contains(word))+ })+ .count()+}++/// The note a batch of searches gets: where Graphicle's tools answer in+/// one call.+pub const SEARCH_NOTE: &str = "Graphicle: this folder is a Graphicle project with a code graph. For a question about how the repository works, one call of graphicle's pack tool returns the relevant code with path:line citations within a token budget; query_graph, get_node and get_neighbors give definitions, callers and callees. Searching the files is fine for an exact string.";++/// The PostToolBatch hook's output for `payload`, if any: [`SEARCH_NOTE`]+/// after a batch with a search, within the nudge budget of the session+/// ([`crate::agent_setup::nudge_allowed`]).+pub fn tool_batch_output(directory: &Path, payload: &Value) -> Option<Value> {+ if searches(payload) == 0 {+ return None;+ }+ if !crate::agent_setup::nudge_allowed(directory, payload, crate::agent_setup::nudge_cap()) {+ return None;+ }+ Some(+ json!({"hookSpecificOutput":{"hookEventName":"PostToolBatch","additionalContext":SEARCH_NOTE}}),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn manifest_is_a_native_plugin_with_three_families() {+ let manifest = manifest(+ "graphicle",+ None,+ SESSION_PACK_TOKENS,+ &PACKAGED_SERVER_FLAGS,+ );+ assert_eq!(manifest["compat"]["manifestDir"], ".muse-plugin");+ assert_eq!(manifest["name"], PLUGIN_ID);+ let capabilities = &manifest["capabilities"];+ assert_eq!(+ capabilities["mcpServers"][0]["command"],+ json!([+ "graphicle",+ "mcp",+ "--project",+ ".",+ "--or-workspace",+ "--allow-learning"+ ])+ );+ // Optional, as the settings entry is (accepted by Muse Code's+ // validator; whether it skips a failing plugin server is unconfirmed).+ assert_eq!(capabilities["mcpServers"][0]["mode"], "optional");+ let hooks = capabilities["hooks"].as_array().unwrap();+ let events: Vec<&str> = hooks.iter().map(|h| h["event"].as_str().unwrap()).collect();+ assert_eq!(+ events,+ [+ "SessionStart",+ "UserPromptSubmit",+ "PostToolBatch",+ "Stop",+ "PreCompact",+ "SessionEnd"+ ]+ );+ assert_eq!(+ hooks[0]["command"],+ json!(["graphicle", "hook", "muse", "session-start"])+ );+ // Ids follow Muse's portable grammar; argv only, no shell strings.+ for hook in hooks {+ let id = hook["id"].as_str().unwrap();+ assert!(+ id.chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "-._".contains(c))+ );+ assert!(hook["command"].is_array());+ }+ assert_eq!(+ capabilities["skills"][0]["path"],+ "skills/graphicle/SKILL.md"+ );+ let with_data = manifest_with_data();+ assert_eq!(+ with_data["capabilities"]["mcpServers"][0]["command"],+ json!([+ "/opt/g/graphicle",+ "--data-dir",+ "/d",+ "mcp",+ "--project",+ ".",+ "--or-workspace",+ "--tools",+ "essentials"+ ])+ );+ assert_eq!(+ with_data["capabilities"]["hooks"][0]["command"],+ json!([+ "/opt/g/graphicle",+ "--data-dir",+ "/d",+ "hook",+ "muse",+ "session-start",+ "--pack-tokens",+ "0"+ ])+ );+ }++ fn manifest_with_data() -> Value {+ manifest(+ "/opt/g/graphicle",+ Some(Path::new("/d")),+ 0,+ &["--tools", "essentials"],+ )+ }++ #[test]+ fn skill_has_frontmatter_and_names_the_tools() {+ assert!(SKILL.starts_with("---\nname: graphicle\ndescription: "));+ for tool in ["pack", "query_graph", "recall_project", "propose_memory"] {+ assert!(SKILL.contains(tool), "{tool}");+ }+ }++ #[test]+ fn packaging_copy_matches_the_skill_and_manifest() {+ // The package in packaging/ (private tree, then public export).+ let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));+ for root in [+ crate_dir.join("../graphicle/public-root/packaging/muse-code-plugin"),+ crate_dir.join("../..").join("packaging/muse-code-plugin"),+ ] {+ if !root.is_dir() {+ continue;+ }+ let skill = std::fs::read_to_string(root.join("skills/graphicle/SKILL.md")).unwrap();+ assert_eq!(skill, SKILL);+ let text = std::fs::read_to_string(root.join(".muse-plugin/plugin.json")).unwrap();+ let mut packaged: Value = serde_json::from_str(&text).unwrap();+ let mut ours = manifest(+ "graphicle",+ None,+ SESSION_PACK_TOKENS,+ &PACKAGED_SERVER_FLAGS,+ );+ // The packaged copy names the release it ships in; a written+ // one names the version of the program that wrote it.+ assert!(packaged["version"].is_string());+ packaged.as_object_mut().unwrap().remove("version");+ ours.as_object_mut().unwrap().remove("version");+ assert_eq!(packaged, ours);+ return;+ }+ }++ #[test]+ fn searches_counts_search_tools_and_shell_searches() {+ let payload = json!({"hook_event_name":"PostToolBatch","session_id":"s",+ "tool_calls":[+ {"tool_name":"grep","tool_input":{"pattern":"Foo"}},+ {"name":"exec_command","args":"{\"cmd\":\"rg -n Foo src\"}"},+ {"name":"shell","input":{"command":["bash","-lc","ls src"]}},+ {"name":"read_file","args":{"path":"a.rs"}},+ {"name":"mcp__graphicle__query_graph","args":{"query":"Foo"}}]});+ assert_eq!(searches(&payload), 2);+ assert_eq!(searches(&json!({"tool_calls":[]})), 0);+ }++ #[test]+ fn finds_a_session_log_by_id_and_skips_others() {+ let root = tempfile::tempdir().unwrap();+ let day = root.path().join("2026/10/27/abc-1");+ std::fs::create_dir_all(day.join("subagent/x")).unwrap();+ std::fs::write(day.join("session.jsonl"), "{}\n").unwrap();+ std::fs::write(day.join("subagent/x/session.jsonl"), "{}\n").unwrap();+ assert_eq!(+ find_session_log(root.path(), "abc-1"),+ Some(day.join("session.jsonl"))+ );+ assert_eq!(find_session_log(root.path(), "x"), None);+ let given = json!({"transcript_path": day.join("session.jsonl")});+ assert_eq!(session_log(&given), Some(day.join("session.jsonl")));+ assert_eq!(session_log(&json!({"session_id":"../etc"})), None);+ }++ #[test]+ fn writes_the_package_once() {+ let folder = tempfile::tempdir().unwrap();+ let manifest = manifest_with_data();+ assert!(write_package(folder.path(), &manifest).unwrap());+ assert!(!write_package(folder.path(), &manifest).unwrap());+ let written: Value = serde_json::from_str(+ &std::fs::read_to_string(folder.path().join(".muse-plugin/plugin.json")).unwrap(),+ )+ .unwrap();+ assert_eq!(written, manifest);+ assert_eq!(+ std::fs::read_to_string(folder.path().join("skills/graphicle/SKILL.md")).unwrap(),+ SKILL+ );+ }+}diff --git a/crates/graphicle/src/muse_code_skill.md b/crates/graphicle/src/muse_code_skill.mdnew file mode 100644index 0000000..449a205--- /dev/null+++ b/crates/graphicle/src/muse_code_skill.md@@ -0,0 +1,43 @@+---+name: graphicle+description: Use Graphicle's MCP tools for questions about how this repository works, for changes that span several files, and to recall or record the project's decisions. Graphicle answers with path:line citations from the code graph, whole-repository packs and reviewed project memory.+metadata:+ display-name: Graphicle+---++# Graphicle++Graphicle indexes this repository into a code graph and keeps the project's+reviewed memory. Its context already arrived at the start of the session (a+map of the repository and the reviewed memories) and after code questions+(cited excerpts). Use its tools when that is not enough.++## Which tool++- **A question about how something works, across files:** call `pack` with+ the question and a budget (default 32000 tokens, at most 200000). It+ returns the most relevant code with line numbers, callers and callees,+ tests and docs, and a manifest of what it left out. Answer from it and+ cite `path:line`.+- **Where a symbol is defined, who calls it, what it calls:** `query_graph`+ with the name, then `get_node` and `get_neighbors`. `shortest_path`+ connects two symbols.+- **A past decision, a reason, a convention, or anything said in an earlier+ session:** `recall_project`, then `read_project_source` to quote the source+ it cites. `project_memory` lists the reviewed memories.+- **An exact string you already know:** search the files as usual; Graphicle+ is not needed.++## Recording a decision++When the person makes a decision worth keeping (a design choice, a+convention, a reason not to do something), call `propose_memory` with a+short title, the decision in a sentence or two, and the files or turns it+rests on. A proposal is a draft: a person approves it in Graphicle before+any session sees it. The next session starts with the approved memories.++## Citations++Cite every claim from Graphicle as `path:line` (code) or by the memory or+source id it gave. If a tool says the folder is not a Graphicle project,+tell the person to run `graphicle setup` there.diff --git a/crates/graphicle/src/pixel.rs b/crates/graphicle/src/pixel.rsnew file mode 100644index 0000000..eed7ea2--- /dev/null+++ b/crates/graphicle/src/pixel.rs@@ -0,0 +1,2610 @@+//! `graphicle pixel`: point at a pixel of a screenshot and get the code that+//! draws it.+//!+//! 1. **The element.** SAM 3.1 (`sam-3.1` on the Meta Model API's Responses+//! API) segments the object under the point. The prompt is a frame+//! marker, an object id and a point in the image's pixels,+//! `<0f>1<|point;x=X;y=Y;w=W;h=H|>`, with the screenshot as a base64 data+//! URL; the reply's records, such as+//! `<0f>1<|box;x1=..;y1=..;x2=..;y2=..;w=..;h=..;c=..|><|mask;..|>`, give+//! the element's box ([`parse_segments`]). Masks are not decoded.+//! 2. **What it says.** A vision model (Muse Spark by default) reads the+//! element in the whole screenshot, with the point and the box in the+//! prompt: its exact strings, its type, its icon, the labels near it and+//! names the code may use for it ([`read_schema`]).+//! 3. **The code.** The project's files are searched for the strings as+//! string literals ([`Lookup`]): exact, then with mnemonics (`&&`),+//! ellipses and case set aside, then with placeholders (`{0}`, `%s`); a+//! literal in a localization call counts more, and tests, translations,+//! docs and generated files less. A key of `package.nls.json` is followed+//! to `%key%` in the `package.json` beside it, and the dotted key of an+//! English JSON locale file (`menu.reset` in `locales/en.json`) to the+//! string literals that name it in the code (`t("menu.reset")`). The code graph adds the+//! symbols named like the element, the symbol around each hit and its+//! callers. Candidates are ranked as `path:line` with the lines around.+//! 4. **Optional:** `--explain` asks the model to rank the top candidates+//! again from a small cache-aware pack and to explain them, citing+//! `path:line`.+//!+//! With `--text` the element's strings are given, and the lookup alone runs:+//! no model call. Every model call goes in the spend log (`graphicle usage`)+//! under the command `pixel`; SAM bills images, so its profile's+//! `price.per_image` prices its calls.++use crate::long_context::{self, Run};+use crate::model;+use crate::{Error, Result};+use base64::Engine as _;+use serde::Serialize;+use serde_json::{Value, json};+use std::collections::{BTreeMap, HashSet};+use std::io::Read as _;+use std::path::{Path, PathBuf};+use std::sync::LazyLock;+use std::time::{Duration, Instant};++/// The largest screenshot sent, in bytes (the Meta Model API takes 50 MB+/// inline).+pub const MAX_IMAGE_BYTES: u64 = 20 << 20;+/// The model of a segmentation profile made from the reading profile.+pub const SAM_MODEL: &str = "sam-3.1";+/// How long a segmentation may take.+const SAM_TIMEOUT: Duration = Duration::from_secs(120);+/// The reading call's output limit at most (Muse Spark reasons, and its+/// reasoning counts in the output).+const READ_OUTPUT_LIMIT: usize = 16_000;+/// Half the width and the height of the box around the point when nothing+/// segments it.+const FALLBACK_HALF: (u32, u32) = (160, 40);+/// The pack's budget of `--explain` unless given.+pub const EXPLAIN_BUDGET: usize = 32_000;+/// The input tokens of one image in a worst case (Muse Spark counts about+/// 1,300 to 1,500 for a 1280-pixel image).+const IMAGE_TOKENS: u64 = 1_600;+/// Files larger than this are not searched (bundles, data).+const MAX_SCAN_BYTES: usize = 4 << 20;+/// Places of one text in one file read at most.+const MAX_OFFSETS: usize = 200;+/// Texts of each kind searched at most.+const MAX_NEEDLES: usize = 12;++/// `graphicle pixel`'s arguments.+#[derive(clap::Args, Clone, Debug)]+pub struct Args {+ /// The screenshot: PNG, JPEG, GIF or WebP, at most 20 MiB.+ #[arg(required_unless_present = "text")]+ pub screenshot: Option<PathBuf>,+ /// The point, in the screenshot's pixels from its top left corner.+ #[arg(long, value_name = "X,Y", required_unless_present = "text")]+ pub at: Option<String>,+ /// What you point at, in a few words, for the model that reads the+ /// screenshot.+ #[arg(long, value_name = "TEXT")]+ pub phrase: Option<String>,+ /// The element's box in the screenshot's pixels, instead of SAM's.+ #[arg(long = "box", value_name = "X1,Y1,X2,Y2")]+ pub bbox: Option<String>,+ /// The element's visible text, when you know it: then no model reads+ /// the screenshot, and only the lookup runs (no model call). Repeat it+ /// for each text.+ #[arg(long, value_name = "TEXT")]+ pub text: Vec<String>,+ /// A label near the element (a view's title, a heading), weighed less.+ /// Repeatable.+ #[arg(long, value_name = "TEXT")]+ pub nearby: Vec<String>,+ /// A name the code may use for the element (a command id, a component).+ /// Repeatable.+ #[arg(long, value_name = "NAME")]+ pub name: Vec<String>,+ /// Candidates shown.+ #[arg(long, default_value_t = 5, value_parser = clap::value_parser!(u64).range(1..=20))]+ pub top: u64,+ /// Ask the model to rank the top candidates again from a small+ /// cache-aware pack and to explain them, citing path:line.+ #[arg(long)]+ pub explain: bool,+ /// The pack's budget in tokens for --explain.+ #[arg(long, value_name = "TOKENS", default_value_t = EXPLAIN_BUDGET)]+ pub budget: usize,+ /// The project: an id, a key or a synced folder (default: this folder's+ /// project, else the last synced one).+ #[arg(long)]+ pub project: Option<String>,+ /// The configured model profile that reads the screenshot and explains+ /// [default: the answer model].+ #[arg(long, value_name = "NAME")]+ pub model: Option<String>,+ /// The configured segmentation profile [default: a profile whose model+ /// is sam-*, else SAM 3.1 at the reading profile's Meta Model API].+ #[arg(long, value_name = "NAME")]+ pub sam: Option<String>,+ /// Print the report as JSON (the default when the output is not a+ /// terminal).+ #[arg(long)]+ pub json: bool,+}++// ---------------------------------------------------------------- images++/// What a screenshot's header says: its media type and size in pixels.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ImageInfo {+ pub mime: &'static str,+ pub width: u32,+ pub height: u32,+}++/// The type and size of a PNG, JPEG, GIF or WebP image, from its header+/// (no image library: nothing is decoded).+pub fn image_info(b: &[u8]) -> Option<ImageInfo> {+ let be16 = |i: usize| -> Option<u32> {+ Some(u32::from(u16::from_be_bytes([*b.get(i)?, *b.get(i + 1)?])))+ };+ let le16 = |i: usize| -> Option<u32> {+ Some(u32::from(u16::from_le_bytes([*b.get(i)?, *b.get(i + 1)?])))+ };+ let be32 =+ |i: usize| -> Option<u32> { Some(u32::from_be_bytes(b.get(i..i + 4)?.try_into().ok()?)) };+ let le24 = |i: usize| -> Option<u32> {+ Some(+ u32::from(*b.get(i)?)+ | (u32::from(*b.get(i + 1)?) << 8)+ | (u32::from(*b.get(i + 2)?) << 16),+ )+ };+ let (mime, width, height) =+ if b.starts_with(b"\x89PNG\r\n\x1a\n") && b.get(12..16) == Some(b"IHDR") {+ ("image/png", be32(16)?, be32(20)?)+ } else if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") {+ ("image/gif", le16(6)?, le16(8)?)+ } else if b.starts_with(&[0xFF, 0xD8]) {+ let mut i = 2;+ loop {+ while b.get(i) == Some(&0xFF) && b.get(i + 1) == Some(&0xFF) {+ i += 1;+ }+ if *b.get(i)? != 0xFF {+ return None;+ }+ let marker = *b.get(i + 1)?;+ if (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC) {+ break ("image/jpeg", be16(i + 7)?, be16(i + 5)?);+ }+ if marker == 0x01 || (0xD0..=0xD9).contains(&marker) {+ i += 2;+ continue;+ }+ i += 2 + be16(i + 2)? as usize;+ }+ } else if b.starts_with(b"RIFF") && b.get(8..12) == Some(b"WEBP") {+ match b.get(12..16)? {+ b"VP8 " => ("image/webp", le16(26)? & 0x3FFF, le16(28)? & 0x3FFF),+ b"VP8L" => {+ let bits = u32::from_le_bytes(b.get(21..25)?.try_into().ok()?);+ (+ "image/webp",+ (bits & 0x3FFF) + 1,+ ((bits >> 14) & 0x3FFF) + 1,+ )+ }+ b"VP8X" => ("image/webp", le24(24)? + 1, le24(27)? + 1),+ _ => return None,+ }+ } else {+ return None;+ };+ (width > 0 && height > 0).then_some(ImageInfo {+ mime,+ width,+ height,+ })+}++/// The image as a base64 data URL, as the Responses API's `input_image`+/// takes it.+pub fn data_url(image: &ImageInfo, bytes: &[u8]) -> String {+ format!(+ "data:{};base64,{}",+ image.mime,+ base64::engine::general_purpose::STANDARD.encode(bytes)+ )+}++fn read_image(path: &Path) -> Result<Vec<u8>> {+ let file = std::fs::File::open(path)+ .map_err(|e| Error::bad(format!("Cannot read {}: {e}", path.display())))?;+ let mut bytes = Vec::new();+ file.take(MAX_IMAGE_BYTES + 1).read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_IMAGE_BYTES {+ return Err(Error::bad("The screenshot is over 20 MiB"));+ }+ Ok(bytes)+}++fn numbers(text: &str, count: usize, what: &str) -> Result<Vec<u32>> {+ let values: Vec<u32> = text+ .split(',')+ .map(|part| part.trim().parse::<f64>())+ .collect::<std::result::Result<Vec<f64>, _>>()+ .ok()+ .filter(|v| v.len() == count && v.iter().all(|n| n.is_finite() && *n >= 0.0))+ .ok_or_else(|| Error::bad(format!("{what} takes {count} numbers separated by commas")))?+ .into_iter()+ .map(|n| n.round() as u32)+ .collect();+ Ok(values)+}++/// `X,Y` inside the image.+pub fn parse_point(text: &str, image: &ImageInfo) -> Result<(u32, u32)> {+ let v = numbers(text, 2, "--at")?;+ if v[0] >= image.width || v[1] >= image.height {+ return Err(Error::bad(format!(+ "The point {},{} is outside the {}x{} screenshot",+ v[0], v[1], image.width, image.height+ )));+ }+ Ok((v[0], v[1]))+}++// ---------------------------------------------------------------- the box++/// The element's box in the screenshot's pixels, and where it came from.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct Bounds {+ pub x1: u32,+ pub y1: u32,+ pub x2: u32,+ pub y2: u32,+ /// `sam` (with the model's name in `model`), `given` (--box) or+ /// `around the point` (nothing segmented it).+ pub from: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub model: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub confidence: Option<f64>,+ /// The mask SAM returned (not decoded): rows, columns and encoding.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub mask: Option<Value>,+}++impl Bounds {+ fn around(point: (u32, u32), image: &ImageInfo) -> Self {+ Bounds {+ x1: point.0.saturating_sub(FALLBACK_HALF.0),+ y1: point.1.saturating_sub(FALLBACK_HALF.1),+ x2: (point.0 + FALLBACK_HALF.0).min(image.width - 1),+ y2: (point.1 + FALLBACK_HALF.1).min(image.height - 1),+ from: "around the point".into(),+ model: None,+ confidence: None,+ mask: None,+ }+ }+}++/// `--box X1,Y1,X2,Y2`, ordered and inside the image.+pub fn parse_bounds(text: &str, image: &ImageInfo) -> Result<Bounds> {+ let v = numbers(text, 4, "--box")?;+ let (x1, x2) = (v[0].min(v[2]), v[0].max(v[2]).min(image.width - 1));+ let (y1, y2) = (v[1].min(v[3]), v[1].max(v[3]).min(image.height - 1));+ if x1 >= image.width || y1 >= image.height {+ return Err(Error::bad("The box is outside the screenshot"));+ }+ Ok(Bounds {+ x1,+ y1,+ x2,+ y2,+ from: "given".into(),+ model: None,+ confidence: None,+ mask: None,+ })+}++/// SAM 3.1's prompt for one point: the frame marker, object 1, and the point+/// with the image's size, in its pixels.+pub fn sam_prompt(point: (u32, u32), image: &ImageInfo) -> String {+ format!(+ "<0f>1<|point;x={};y={};w={};h={}|>",+ point.0, point.1, image.width, image.height+ )+}++/// The segmentation request: one user message with the prompt and the+/// image; confidences on, one-bit masks (the smaller encoding; a point+/// prompt gets one-bit masks anyway). Not streamed: the reply holds every+/// record at once.+pub fn sam_body(model: &str, prompt: &str, data_url: &str) -> Value {+ json!({"model":model,"input":[{"role":"user","content":[+ {"type":"input_text","text":prompt},+ {"type":"input_image","image_url":data_url}]}],+ "metadata":{"include_confidence":"true","mask_encoding":"one_bit"}})+}++/// One object of SAM's reply.+#[derive(Clone, Debug, PartialEq)]+pub struct Segment {+ pub frame: u64,+ pub object: u64,+ pub x1: f64,+ pub y1: f64,+ pub x2: f64,+ pub y2: f64,+ /// The image size the box is given in, when the record says.+ pub width: Option<f64>,+ pub height: Option<f64>,+ pub confidence: Option<f64>,+ /// The mask's rows, columns and encoding (`~` lossless, `!` one bit),+ /// when there is one; not decoded.+ pub mask: Option<(u64, u64, char)>,+}++/// Where a mask's group ends in `rest` (the text after its `<|`): at the+/// first `|>` that a comma, a line end, a space or the end follows. The+/// base85 payload may hold `|` or `>`, never one of those after `|>`.+fn group_end(rest: &str) -> usize {+ let bytes = rest.as_bytes();+ let mut from = 0;+ while let Some(k) = rest[from..].find("|>") {+ let at = from + k;+ if matches!(bytes.get(at + 2), None | Some(b',' | b'\n' | b'\r' | b' ')) {+ return at;+ }+ from = at + 1;+ }+ rest.len()+}++fn fields(body: &str, names: &[&str]) -> BTreeMap<String, String> {+ let mut found = BTreeMap::new();+ for (position, field) in body.split(';').enumerate() {+ let field = field.trim();+ match field.split_once('=') {+ Some((key, value)) => {+ found.insert(key.trim().to_string(), value.trim().to_string());+ }+ None => {+ if let Some(name) = names.get(position) {+ found.insert((*name).to_string(), field.to_string());+ }+ }+ }+ }+ found+}++/// The objects of SAM's reply text: each record is a frame marker (`<0f>`,+/// once per line), an object id and its groups, `<|box;x1=..;y1=..;x2=..;+/// y2=..;w=..;h=..[;c=..]|>` then `<|mask;x=..;y=..[;c=..];data=H,W,~..|>`;+/// records are separated by commas. Positional box fields (no `key=`) are+/// read in that order too. No records (nothing matched) is no objects.+pub fn parse_segments(text: &str) -> Vec<Segment> {+ let mut found: Vec<Segment> = Vec::new();+ let bytes = text.as_bytes();+ let mut frame = 0u64;+ let mut object: Option<u64> = None;+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i..].starts_with(b"<|") {+ let rest = &text[i + 2..];+ let kind_end = rest.find([';', '|']).unwrap_or(rest.len());+ let kind = rest[..kind_end].trim();+ let end = if kind == "mask" {+ group_end(rest)+ } else {+ match rest.find("|>") {+ Some(end) => end,+ None => break,+ }+ };+ let body = rest[kind_end..end].trim_start_matches(';');+ match (kind, object) {+ ("box", Some(id)) => {+ let f = fields(body, &["x1", "y1", "x2", "y2", "w", "h", "c"]);+ let number = |key: &str| f.get(key).and_then(|v| v.parse::<f64>().ok());+ if let (Some(x1), Some(y1), Some(x2), Some(y2)) =+ (number("x1"), number("y1"), number("x2"), number("y2"))+ {+ found.push(Segment {+ frame,+ object: id,+ x1,+ y1,+ x2,+ y2,+ width: number("w"),+ height: number("h"),+ confidence: number("c"),+ mask: None,+ });+ }+ }+ ("mask", Some(id)) => {+ if let Some(data) = body.split_once("data=").map(|(_, d)| d) {+ let mut parts = data.splitn(3, ',');+ let rows = parts.next().and_then(|v| v.trim().parse::<u64>().ok());+ let cols = parts.next().and_then(|v| v.trim().parse::<u64>().ok());+ let encoding = parts.next().and_then(|v| v.chars().next());+ if let (Some(rows), Some(cols), Some(encoding)) = (rows, cols, encoding)+ && let Some(last) = found.last_mut()+ && last.object == id+ && last.frame == frame+ {+ last.mask = Some((rows, cols, encoding));+ }+ }+ }+ _ => {}+ }+ i += 2 + end + 2;+ continue;+ }+ if bytes[i] == b'<' {+ if let Some(close) = text[i + 1..].find("f>") {+ let digits = &text[i + 1..i + 1 + close];+ if !digits.is_empty() && digits.bytes().all(|c| c.is_ascii_digit()) {+ frame = digits.parse().unwrap_or(frame);+ object = None;+ i += close + 3;+ continue;+ }+ }+ i += 1;+ continue;+ }+ if bytes[i].is_ascii_digit() {+ let start = i;+ while i < bytes.len() && bytes[i].is_ascii_digit() {+ i += 1;+ }+ object = text[start..i].parse().ok();+ continue;+ }+ if bytes[i] == b',' {+ object = None;+ }+ i += 1;+ }+ found+}++/// The segment for the point: object 1's (else any), one that holds the+/// point first, then the most confident, then the smallest; its box in the+/// image's pixels (scaled when the record gives another size).+pub fn choose(segments: &[Segment], point: (u32, u32), image: &ImageInfo) -> Option<Bounds> {+ let ours: Vec<&Segment> = segments.iter().filter(|s| s.object == 1).collect();+ let pool: Vec<&Segment> = if ours.is_empty() {+ segments.iter().collect()+ } else {+ ours+ };+ let scaled = |s: &Segment| {+ let sx = s+ .width+ .filter(|w| *w > 0.0)+ .map_or(1.0, |w| f64::from(image.width) / w);+ let sy = s+ .height+ .filter(|h| *h > 0.0)+ .map_or(1.0, |h| f64::from(image.height) / h);+ (s.x1 * sx, s.y1 * sy, s.x2 * sx, s.y2 * sy)+ };+ let (px, py) = (f64::from(point.0), f64::from(point.1));+ let best = pool.into_iter().max_by(|a, b| {+ let key = |s: &Segment| {+ let (x1, y1, x2, y2) = scaled(s);+ let holds =+ x1.min(x2) <= px && px <= x1.max(x2) && y1.min(y2) <= py && py <= y1.max(y2);+ let area = (x2 - x1).abs() * (y2 - y1).abs();+ (holds, s.confidence.unwrap_or(0.0), -area)+ };+ let (ha, ca, aa) = key(a);+ let (hb, cb, ab) = key(b);+ ha.cmp(&hb).then(ca.total_cmp(&cb)).then(aa.total_cmp(&ab))+ })?;+ let (x1, y1, x2, y2) = scaled(best);+ let clamp_x = |v: f64| (v.round().max(0.0) as u32).min(image.width - 1);+ let clamp_y = |v: f64| (v.round().max(0.0) as u32).min(image.height - 1);+ Some(Bounds {+ x1: clamp_x(x1.min(x2)),+ y1: clamp_y(y1.min(y2)),+ x2: clamp_x(x1.max(x2)),+ y2: clamp_y(y1.max(y2)),+ from: "sam".into(),+ model: None,+ confidence: best.confidence,+ mask: best.mask.map(|(rows, cols, encoding)| {+ json!({"rows":rows,"columns":cols,+ "encoding":if encoding == '!' { "one_bit" } else { "lossless" }})+ }),+ })+}++/// The text of a Responses API reply: its `output_text` parts in order.+fn output_text(value: &Value) -> String {+ let mut text = String::new();+ for item in value["output"].as_array().into_iter().flatten() {+ for part in item["content"].as_array().into_iter().flatten() {+ if part["type"] == "output_text"+ && let Some(t) = part["text"].as_str()+ {+ text.push_str(t);+ }+ }+ }+ text+}++// ---------------------------------------------------------------- reading++/// The instructions of the call that reads the element.+pub const READ_INSTRUCTIONS: &str = "You read one element of an application's screenshot for a developer who wants the source code that draws it. The person clicked at a point, and the element around it is inside a box; coordinates are in the image's pixels from its top left corner. Return one JSON object that matches the schema: strings, the exact texts the element shows, character for character as they appear (keep case, punctuation, ellipses and symbols; one entry per separate text; none when it shows no text); element_type, what it is (button, menu item, tab, link, input, label, heading, title, icon, list item, tree item, status bar item, notification, tooltip, checkbox, dropdown or other); icon, a short description of any icon in the element (empty when there is none); nearby_labels, up to five exact texts near the element that name its group (a view or panel title, a heading, a section, a column); names, up to five identifiers the source code may use for it (a component, class, command id, setting key or icon name), as guesses. Never invent text the screenshot does not show.";++/// The reading's schema.+pub fn read_schema() -> Value {+ json!({"type":"object","additionalProperties":false,+ "required":["strings","element_type","icon","nearby_labels","names"],+ "properties":{+ "strings":{"type":"array","items":{"type":"string"}},+ "element_type":{"type":"string"},+ "icon":{"type":"string"},+ "nearby_labels":{"type":"array","items":{"type":"string"}},+ "names":{"type":"array","items":{"type":"string"}}}})+}++/// The reading request's text: the image's size, the point, the box and the+/// person's words.+pub fn read_prompt(+ point: (u32, u32),+ bounds: &Bounds,+ image: &ImageInfo,+ phrase: Option<&str>,+) -> String {+ let mut text = format!(+ "The screenshot is {}x{} pixels. The person clicked at x={}, y={}. The element is inside the box from ({}, {}) to ({}, {}).",+ image.width, image.height, point.0, point.1, bounds.x1, bounds.y1, bounds.x2, bounds.y2+ );+ if let Some(phrase) = phrase.map(str::trim).filter(|p| !p.is_empty()) {+ text.push_str(&format!(" They describe it as: {phrase}."));+ }+ text.push_str(" Read that element.");+ text+}++/// The Responses API input of the reading call: the text, then the image.+pub fn read_input(prompt: &str, data_url: &str) -> Value {+ json!([{"role":"user","content":[+ {"type":"input_text","text":prompt},+ {"type":"input_image","image_url":data_url}]}])+}++/// What the model read.+#[derive(Clone, Debug, Default, PartialEq, Serialize)]+pub struct Reading {+ pub strings: Vec<String>,+ pub element_type: String,+ pub icon: String,+ pub nearby_labels: Vec<String>,+ pub names: Vec<String>,+}++/// The model's reading, checked: texts trimmed, empty ones dropped, at most+/// ten strings and five of the rest, none over 300 characters.+pub fn parse_reading(value: &Value) -> Result<Reading> {+ if !value.is_object() {+ return Err(Error::bad("The model's reading is not a JSON object"));+ }+ let list = |key: &str, most: usize| -> Vec<String> {+ value[key]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty() && s.chars().count() <= 300)+ .take(most)+ .map(String::from)+ .collect()+ };+ let one = |key: &str| -> String {+ value[key]+ .as_str()+ .unwrap_or("")+ .trim()+ .chars()+ .take(200)+ .collect()+ };+ Ok(Reading {+ strings: list("strings", 10),+ element_type: one("element_type"),+ icon: one("icon"),+ nearby_labels: list("nearby_labels", 5),+ names: list("names", 5),+ })+}++// ---------------------------------------------------------------- lookup++/// What the lookup searches for: the element's strings, the labels near it+/// (weighed less) and names the code may use for it.+#[derive(Clone, Debug, Default, PartialEq, Serialize)]+pub struct Query {+ pub strings: Vec<String>,+ pub nearby: Vec<String>,+ pub names: Vec<String>,+}++impl Query {+ pub fn is_empty(&self) -> bool {+ self.strings.is_empty() && self.nearby.is_empty() && self.names.is_empty()+ }+}++/// What a searched text is for.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Role {+ /// The element's own text.+ Text,+ /// A label near the element.+ Nearby,+ /// A name the code may use for it.+ Name,+}++impl Role {+ fn weight(self) -> f64 {+ match self {+ Role::Text => 1.0,+ Role::Nearby => 0.35,+ Role::Name => 0.4,+ }+ }+}++/// `&&` mnemonics out, "…" as "...", runs of white space as one space.+pub fn normalize(text: &str) -> String {+ text.replace("&&", "")+ .replace('…', "...")+ .split_whitespace()+ .collect::<Vec<_>>()+ .join(" ")+}++/// A file's text as the search reads it: lower case, `&&` out and "…" as+/// "...", with its lines kept.+fn fold_text(text: &str) -> String {+ text.replace("&&", "").replace('…', "...").to_lowercase()+}++struct Needle {+ role: Role,+ text: String,+ norm: String,+ fold: String,+ /// What a folded file is searched for: the folded text, and its forms+ /// with quotes escaped.+ variants: Vec<String>,+ /// The folded text's longest word of three letters or more, which finds+ /// the strings with placeholders.+ word: Option<String>,+}++impl Needle {+ fn new(role: Role, text: &str) -> Option<Self> {+ let norm = normalize(text);+ let fold = norm.to_lowercase();+ if fold.chars().count() < 2 {+ return None;+ }+ let mut variants = vec![fold.clone()];+ for (quote, escaped) in [('\'', "\\'"), ('"', "\\\"")] {+ if fold.contains(quote) {+ variants.push(fold.replace(quote, escaped));+ }+ }+ let word = fold+ .split(|c: char| !c.is_alphabetic())+ .filter(|w| w.chars().count() >= 3)+ .max_by_key(|w| w.len())+ .map(String::from);+ Some(Needle {+ role,+ text: text.trim().to_string(),+ norm,+ fold,+ variants,+ word,+ })+ }+}++/// The string literals of a line, decoded: `".."`, `'..'` and `` `..` ``;+/// an apostrophe inside a word (don't) opens none, and a `//` comment ends+/// the line.+pub fn literals(line: &str) -> Vec<String> {+ let mut found = Vec::new();+ let mut chars = line.chars().peekable();+ let mut previous: Option<char> = None;+ while let Some(c) = chars.next() {+ if c == '/' && chars.peek() == Some(&'/') {+ break;+ }+ let opens = matches!(c, '"' | '\'' | '`')+ && !(c == '\'' && previous.is_some_and(char::is_alphanumeric));+ if opens {+ let mut text = String::new();+ let mut closed = false;+ while let Some(d) = chars.next() {+ if d == '\\' {+ match chars.next() {+ Some('n') => text.push('\n'),+ Some('t') => text.push('\t'),+ Some(e) => text.push(e),+ None => {}+ }+ continue;+ }+ if d == c {+ closed = true;+ break;+ }+ text.push(d);+ }+ if closed {+ found.push(text);+ }+ }+ previous = Some(c);+ }+ found+}++static PLACEHOLDER: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"\{\d+\}|\{[A-Za-z_][A-Za-z0-9_]*\}|%(\d+\$)?[sdifuxo@]|\$\{[^}]*\}")+ .expect("the placeholder pattern compiles")+});++static LOCALIZATION: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"(?i)\b(localize2?|l10n\.t|i18n\.t|\$t|t|_|tr|gettext|ngettext|formatmessage|nslocalizedstring|getstring|translate)\s*\(")+ .expect("the localization pattern compiles")+});++/// How much of `text` (folded) a literal with placeholders (`{0}`,+/// `{name}`, `%s`, `%1$s`, `${..}`) covers when it reads as that text: its+/// fixed parts in order, the first at the start and the last at the end.+pub fn placeholder_cover(literal_fold: &str, text_fold: &str) -> Option<f64> {+ let parts: Vec<&str> = PLACEHOLDER.split(literal_fold).collect();+ if parts.len() < 2 {+ return None;+ }+ let fixed: usize = parts.iter().map(|p| p.len()).sum();+ if fixed < 3 || text_fold.is_empty() {+ return None;+ }+ let last = parts.len() - 1;+ let mut at = 0;+ for (i, part) in parts.iter().enumerate() {+ if i == 0 {+ if !text_fold.starts_with(part) {+ return None;+ }+ at = part.len();+ } else if i == last {+ if text_fold.len() < at + part.len() || !text_fold.ends_with(part) {+ return None;+ }+ } else {+ let found = text_fold.get(at..)?.find(part)?;+ at += found + part.len();+ }+ }+ Some(fixed as f64 / text_fold.len() as f64)+}++/// How much a path counts: tests, translations, docs, styles and generated+/// or locked files count less.+pub fn path_factor(path: &str) -> f64 {+ let p = path.to_ascii_lowercase();+ let name = p.rsplit('/').next().unwrap_or(&p);+ let dirs: Vec<&str> = p.split('/').collect();+ let dirs = &dirs[..dirs.len().saturating_sub(1)];+ if matches!(+ name,+ "package-lock.json"+ | "yarn.lock"+ | "pnpm-lock.yaml"+ | "cargo.lock"+ | "go.sum"+ | "poetry.lock"+ ) || name.ends_with(".map")+ || name.contains(".min.")+ {+ return 0.05;+ }+ if dirs.iter().any(|d| {+ matches!(+ *d,+ "test"+ | "tests"+ | "__tests__"+ | "testdata"+ | "fixtures"+ | "__mocks__"+ | "spec"+ | "e2e"+ | "testing"+ )+ }) || name.contains(".test.")+ || name.contains(".spec.")+ || name.contains("_test.")+ || name.starts_with("test_")+ {+ return 0.25;+ }+ if dirs+ .iter()+ .any(|d| matches!(*d, "i18n" | "locales" | "locale" | "l10n" | "translations"))+ || translation_name(name)+ {+ return 0.3;+ }+ if name.ends_with(".md")+ || name.ends_with(".txt")+ || name.ends_with(".rst")+ || dirs.iter().any(|d| matches!(*d, "docs" | "doc"))+ || name.starts_with("changelog")+ {+ return 0.4;+ }+ if [".css", ".scss", ".less", ".svg"]+ .iter()+ .any(|e| name.ends_with(e))+ || dirs+ .iter()+ .any(|d| matches!(*d, "dist" | "out" | "build" | "generated"))+ {+ return 0.3;+ }+ 1.0+}++/// `package.nls.de.json`, `strings.zh-cn.json`: a language before the+/// extension, other than English.+fn translation_name(name: &str) -> bool {+ let parts: Vec<&str> = name.split('.').collect();+ if parts.len() < 3 {+ return false;+ }+ let language = parts[parts.len() - 2];+ let base = language.split(['-', '_']).next().unwrap_or("");+ base.len() == 2+ && base.chars().all(|c| c.is_ascii_lowercase())+ && base != "en"+ && language.len() <= 7+}++/// An English JSON locale file, whose dotted keys the code names+/// (`locales/en.json`, `i18n/en-US.json`, `lang/messages.json`), not a+/// translation and not VS Code's `package.nls.json` (followed apart).+pub fn locale_json(path: &str) -> bool {+ let p = path.to_ascii_lowercase();+ let name = p.rsplit('/').next().unwrap_or(&p);+ if !name.ends_with(".json") || name.ends_with(".nls.json") || translation_name(name) {+ return false;+ }+ // `de-DE.json`, `pt_BR.json`, `fr.json`: a language other than English.+ let stem = name.trim_end_matches(".json");+ let language = stem.split(['-', '_']).next().unwrap_or("");+ if (2..=3).contains(&language.len())+ && language.bytes().all(|b| b.is_ascii_lowercase())+ && stem.len() <= 10+ && language != "en"+ {+ return false;+ }+ let folder = p.split('/').rev().skip(1).any(|d| {+ matches!(+ d,+ "locales" | "locale" | "i18n" | "l10n" | "lang" | "langs" | "translations" | "messages"+ )+ });+ folder+ || matches!(+ name,+ "en.json"+ | "en-us.json"+ | "en_us.json"+ | "en-gb.json"+ | "messages.json"+ | "strings.json"+ )+}++/// The dotted path of the key that `line` (from 1) of a JSON text defines:+/// `menu.reset` for `"reset": "Reset the canvas"` inside `"menu": {`. None+/// when the line defines no key.+pub fn json_key_at(text: &str, line: usize) -> Option<String> {+ let bytes = text.as_bytes();+ let mut stack: Vec<Option<String>> = Vec::new();+ let mut pending: Option<String> = None;+ let mut row = 1;+ let mut i = 0;+ while i < bytes.len() && row <= line {+ match bytes[i] {+ b'\n' => row += 1,+ b'"' => {+ let start = i + 1;+ let mut j = start;+ while j < bytes.len() && bytes[j] != b'"' {+ j += if bytes[j] == b'\\' { 2 } else { 1 };+ }+ let end = j.min(bytes.len());+ let string = serde_json::from_str::<String>(&format!("\"{}\"", &text[start..end]))+ .unwrap_or_else(|_| text[start..end].to_string());+ i = j;+ let mut k = j + 1;+ while k < bytes.len() && matches!(bytes[k], b' ' | b'\t' | b'\r') {+ k += 1;+ }+ if bytes.get(k) == Some(&b':') {+ if row == line {+ let mut parts: Vec<String> = stack.iter().flatten().cloned().collect();+ parts.push(string);+ return Some(parts.join("."));+ }+ pending = Some(string);+ }+ }+ b'{' | b'[' => stack.push(pending.take()),+ b'}' | b']' => {+ stack.pop();+ pending = None;+ }+ b',' => pending = None,+ _ => {}+ }+ i += 1;+ }+ None+}++/// A hit in an English JSON locale file, to follow to the code: the+/// needle, the dotted key, and the hit's grade without the locale file's+/// path factor.+#[derive(Clone, Debug, PartialEq)]+pub struct LocaleKey {+ index: usize,+ key: String,+ grade: f64,+}++/// Locale keys followed at most.+const MAX_KEYS: usize = 24;++/// Markup, where a page's text stands outside string literals.+fn is_markup(path: &str) -> bool {+ let p = path.to_ascii_lowercase();+ [+ ".html", ".htm", ".jsx", ".tsx", ".vue", ".svelte", ".xml", ".xaml", ".erb", ".hbs",+ ".ejs", ".astro",+ ]+ .iter()+ .any(|e| p.ends_with(e))+}++fn newline_offsets(text: &str) -> Vec<usize> {+ text.bytes()+ .enumerate()+ .filter(|&(_, b)| b == b'\n')+ .map(|(i, _)| i)+ .collect()+}++/// A line of code with its number.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct SnippetLine {+ pub line: usize,+ pub text: String,+}++fn snippet(lines: &[&str], index: usize) -> Vec<SnippetLine> {+ let from = index.saturating_sub(2);+ let to = (index + 2).min(lines.len().saturating_sub(1));+ (from..=to)+ .filter_map(|i| {+ lines.get(i).map(|text| SnippetLine {+ line: i + 1,+ text: text.chars().take(200).collect(),+ })+ })+ .collect()+}++#[derive(Clone, Debug)]+struct Hit {+ line: usize,+ grade: f64,+ how: &'static str,+ snippet: Vec<SnippetLine>,+ /// The key of a localization file's line (`"key": "Text"`).+ key: Option<String>,+}++/// Whether `needle` stands in `haystack` as a whole: an end of it that is a+/// letter or digit has no letter or digit beside it.+fn contains_word(haystack: &str, needle: &str) -> bool {+ if needle.is_empty() {+ return false;+ }+ let first = needle.chars().next().is_some_and(char::is_alphanumeric);+ let last = needle+ .chars()+ .next_back()+ .is_some_and(char::is_alphanumeric);+ let mut from = 0;+ while let Some(k) = haystack[from..].find(needle) {+ let at = from + k;+ let before = haystack[..at].chars().next_back();+ let after = haystack[at + needle.len()..].chars().next();+ if (!first || !before.is_some_and(char::is_alphanumeric))+ && (!last || !after.is_some_and(char::is_alphanumeric))+ {+ return true;+ }+ from = at + needle.chars().next().map_or(1, char::len_utf8);+ }+ false+}++fn better(best: &mut Option<(f64, &'static str)>, grade: f64, how: &'static str) {+ if best.is_none_or(|(g, _)| grade > g) {+ *best = Some((grade, how));+ }+}++/// How well `line` holds the needle, before the path and context count.+fn grade_line(line: &str, needle: &Needle, markup: bool) -> Option<(f64, &'static str)> {+ let mut best = None;+ for literal in literals(line) {+ if literal.trim() == needle.text {+ better(&mut best, 1.0, "exact string");+ continue;+ }+ let norm = normalize(&literal);+ if norm == needle.norm {+ better(+ &mut best,+ 0.95,+ "same string apart from mnemonics, ellipses or spaces",+ );+ continue;+ }+ let fold = norm.to_lowercase();+ if fold.is_empty() {+ continue;+ }+ if fold == needle.fold {+ better(&mut best, 0.85, "same string in another case");+ } else if contains_word(&fold, &needle.fold) {+ let share = needle.fold.len() as f64 / fold.len() as f64;+ better(&mut best, 0.6 * share.sqrt(), "inside a longer string");+ } else if fold.chars().count() >= 4+ && fold.len() * 2 >= needle.fold.len()+ && contains_word(&needle.fold, &fold)+ {+ let share = fold.len() as f64 / needle.fold.len() as f64;+ better(&mut best, 0.55 * share, "part of the text");+ } else if let Some(cover) = placeholder_cover(&fold, &needle.fold) {+ better(&mut best, 0.75 * cover, "a string with placeholders");+ }+ }+ if best.is_none() {+ let folded = fold_text(line);+ if needle.variants.iter().any(|v| contains_word(&folded, v)) {+ better(&mut best, if markup { 0.8 } else { 0.35 }, "in the text");+ }+ }+ best+}++/// A localization call on the line or the two before it.+fn localized(lines: &[&str], index: usize) -> bool {+ (index.saturating_sub(2)..=index)+ .any(|i| lines.get(i).is_some_and(|l| LOCALIZATION.is_match(l)))+}++/// One place the lookup found.+#[derive(Clone, Debug, Serialize)]+pub struct Candidate {+ pub path: String,+ pub line: usize,+ pub score: f64,+ /// What was found in the file: each text, how it matched and where.+ pub matched: Vec<Matched>,+ /// The lines around `line`.+ pub snippet: Vec<SnippetLine>,+ /// The symbol around `line` in the code graph.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub symbol: Option<Place>,+ /// Who calls or uses that symbol, from the code graph.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub callers: Vec<Place>,+}++/// A text found in a candidate's file.+#[derive(Clone, Debug, Serialize)]+pub struct Matched {+ pub text: String,+ pub role: Role,+ pub how: &'static str,+ pub line: usize,+ pub grade: f64,+}++/// A symbol of the code graph.+#[derive(Clone, Debug, PartialEq, Serialize)]+pub struct Place {+ pub name: String,+ pub path: String,+ pub line: usize,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub relation: Option<String>,+}++fn round3(v: f64) -> f64 {+ (v * 1000.0).round() / 1000.0+}++/// The search of a project's files for one query: [`Lookup::scan`] each+/// file, [`Lookup::follow_keys`] and [`Lookup::symbols`] once, then+/// [`Lookup::ranked`].+pub struct Lookup {+ needles: Vec<Needle>,+ files: BTreeMap<String, Vec<Option<Hit>>>,+ pub scanned: usize,+}++impl Lookup {+ pub fn new(query: &Query) -> Self {+ let mut needles: Vec<Needle> = Vec::new();+ let mut seen = HashSet::new();+ for (role, texts) in [+ (Role::Text, &query.strings),+ (Role::Nearby, &query.nearby),+ (Role::Name, &query.names),+ ] {+ for text in texts.iter().take(MAX_NEEDLES) {+ if let Some(needle) = Needle::new(role, text)+ && seen.insert(needle.fold.clone())+ {+ needles.push(needle);+ }+ }+ }+ Lookup {+ needles,+ files: BTreeMap::new(),+ scanned: 0,+ }+ }++ pub fn is_empty(&self) -> bool {+ self.needles.is_empty()+ }++ fn keep(&mut self, path: &str, index: usize, hit: Hit) {+ let count = self.needles.len();+ let best = self+ .files+ .entry(path.to_string())+ .or_insert_with(|| vec![None; count]);+ if best[index].as_ref().is_none_or(|b| hit.grade > b.grade) {+ best[index] = Some(hit);+ }+ }++ /// Search one file of the project.+ pub fn scan(&mut self, path: &str, text: &str) {+ self.scanned += 1;+ if text.len() > MAX_SCAN_BYTES || self.needles.is_empty() {+ return;+ }+ let factor = path_factor(path);+ let markup = is_markup(path);+ let nls = path.ends_with(".nls.json");+ let folded = fold_text(text);+ let mut lines: Option<Vec<&str>> = None;+ let mut newlines: Option<Vec<usize>> = None;+ let mut found_hits: Vec<(usize, Hit)> = Vec::new();+ for (index, needle) in self.needles.iter().enumerate() {+ let mut rows: Vec<usize> = Vec::new();+ for variant in &needle.variants {+ let mut from = 0;+ while rows.len() < MAX_OFFSETS+ && let Some(k) = folded[from..].find(variant.as_str())+ {+ let at = from + k;+ let ends = newlines.get_or_insert_with(|| newline_offsets(&folded));+ rows.push(ends.partition_point(|&n| n < at));+ from = at + variant.len().max(1);+ }+ }+ // Strings with placeholders: lines with the needle's longest+ // word and a placeholder.+ if needle.role != Role::Name+ && let Some(word) = &needle.word+ {+ let mut from = 0;+ let mut seen = 0;+ while seen < MAX_OFFSETS+ && let Some(k) = folded[from..].find(word.as_str())+ {+ let at = from + k;+ from = at + word.len();+ seen += 1;+ let ends = newlines.get_or_insert_with(|| newline_offsets(&folded));+ let row = ends.partition_point(|&n| n < at);+ let start = if row == 0 { 0 } else { ends[row - 1] + 1 };+ let end = ends.get(row).copied().unwrap_or(folded.len());+ if PLACEHOLDER.is_match(&folded[start..end]) {+ rows.push(row);+ }+ }+ }+ if rows.is_empty() {+ continue;+ }+ rows.sort_unstable();+ rows.dedup();+ let lines = lines.get_or_insert_with(|| text.lines().collect());+ let mut best: Option<Hit> = None;+ for row in rows {+ let Some(line) = lines.get(row) else {+ continue;+ };+ let Some((grade, how)) = grade_line(line, needle, markup) else {+ continue;+ };+ let grade = grade * factor * if localized(lines, row) { 1.15 } else { 1.0 };+ if best.as_ref().is_none_or(|b| grade > b.grade) {+ let key = if nls && line.contains(':') {+ literals(line).into_iter().next()+ } else {+ None+ };+ best = Some(Hit {+ line: row + 1,+ grade,+ how,+ snippet: snippet(lines, row),+ key,+ });+ }+ }+ if let Some(hit) = best {+ found_hits.push((index, hit));+ }+ }+ for (index, hit) in found_hits {+ self.keep(path, index, hit);+ }+ }++ /// Localization keys followed to the manifests that use them: a hit on+ /// `"key": "Text"` in `package.nls.json` is also a hit on `"%key%"` in+ /// the `package.json` beside it (the contribution that shows the text).+ pub fn follow_keys(&mut self, mut fetch: impl FnMut(&str) -> Option<String>) {+ let mut added: Vec<(String, usize, Hit)> = Vec::new();+ for (path, best) in &self.files {+ let Some(folder) = path.strip_suffix("package.nls.json") else {+ continue;+ };+ let manifest = format!("{folder}package.json");+ let mut text: Option<Option<String>> = None;+ for (index, hit) in best.iter().enumerate() {+ let Some(hit) = hit else { continue };+ let Some(key) = &hit.key else { continue };+ let Some(text) = text.get_or_insert_with(|| fetch(&manifest)) else {+ continue;+ };+ let lines: Vec<&str> = text.lines().collect();+ let pattern = format!("\"%{key}%\"");+ if let Some(row) = lines.iter().position(|l| l.contains(&pattern)) {+ added.push((+ manifest.clone(),+ index,+ Hit {+ line: row + 1,+ grade: hit.grade * 1.01,+ how: "uses the localization key of this text",+ snippet: snippet(&lines, row),+ key: None,+ },+ ));+ }+ }+ }+ for (path, index, hit) in added {+ self.keep(&path, index, hit);+ }+ }++ /// The dotted keys of the hits in English JSON locale files+ /// ([`locale_json`]), for [`Lookup::key_uses`]: a key needs a dot, since+ /// a bare word names too much.+ pub fn locale_keys(&self, mut fetch: impl FnMut(&str) -> Option<String>) -> Vec<LocaleKey> {+ let mut keys: Vec<LocaleKey> = Vec::new();+ for (path, best) in &self.files {+ if !locale_json(path) || best.iter().all(Option::is_none) {+ continue;+ }+ let Some(text) = fetch(path) else { continue };+ let factor = path_factor(path).max(0.05);+ for (index, hit) in best.iter().enumerate() {+ let Some(hit) = hit else { continue };+ let Some(key) = json_key_at(&text, hit.line).filter(|k| k.contains('.')) else {+ continue;+ };+ let grade = hit.grade / factor;+ match keys.iter_mut().find(|k| k.key == key && k.index == index) {+ Some(known) => known.grade = known.grade.max(grade),+ None => keys.push(LocaleKey { index, key, grade }),+ }+ }+ }+ keys.sort_by(|a, b| b.grade.total_cmp(&a.grade));+ keys.truncate(MAX_KEYS);+ keys+ }++ /// Where a file's code names a locale key: a string literal equal to the+ /// dotted key (`t("menu.reset")`) is a hit on the key's text, a little+ /// above the locale file's line once the paths count.+ pub fn key_uses(&mut self, path: &str, text: &str, keys: &[LocaleKey]) {+ if keys.is_empty() || path.to_ascii_lowercase().ends_with(".json") {+ return;+ }+ let wanted: Vec<&LocaleKey> = keys.iter().filter(|k| text.contains(&k.key)).collect();+ if wanted.is_empty() {+ return;+ }+ let factor = path_factor(path);+ let lines: Vec<&str> = text.lines().collect();+ let mut added: Vec<(usize, Hit)> = Vec::new();+ for (row, line) in lines.iter().enumerate() {+ let named: Vec<&LocaleKey> = wanted+ .iter()+ .copied()+ .filter(|k| line.contains(&k.key))+ .collect();+ if named.is_empty() {+ continue;+ }+ let found = literals(line);+ for key in named {+ if found.contains(&key.key) {+ added.push((+ key.index,+ Hit {+ line: row + 1,+ grade: key.grade * factor * 1.01,+ how: "uses the localization key of this text",+ snippet: snippet(&lines, row),+ key: None,+ },+ ));+ }+ }+ }+ for (index, hit) in added {+ self.keep(path, index, hit);+ }+ }++ /// Names that are identifiers, found as symbols of the code graph+ /// (`symbols`: name, path and line of each).+ pub fn symbols<'s>(+ &mut self,+ symbols: impl Iterator<Item = (&'s str, &'s str, usize)>,+ mut fetch: impl FnMut(&str) -> Option<String>,+ ) {+ let wanted: Vec<(usize, String)> = self+ .needles+ .iter()+ .enumerate()+ .filter(|(_, n)| {+ n.role == Role::Name+ && n.text+ .chars()+ .all(|c| c.is_alphanumeric() || c == '_' || c == '$')+ })+ .map(|(i, n)| (i, n.text.clone()))+ .collect();+ if wanted.is_empty() {+ return;+ }+ let mut found: Vec<(usize, String, usize)> = Vec::new();+ for (name, path, line) in symbols {+ let bare = name.trim_start_matches('.').trim_end_matches("()");+ for (index, text) in &wanted {+ if bare == text && found.len() < 50 {+ found.push((*index, path.to_string(), line));+ }+ }+ }+ for (index, path, line) in found {+ let lines_text = fetch(&path).unwrap_or_default();+ let lines: Vec<&str> = lines_text.lines().collect();+ let hit = Hit {+ line,+ grade: 0.9 * path_factor(&path),+ how: "a symbol of the code graph with this name",+ snippet: snippet(&lines, line.saturating_sub(1)),+ key: None,+ };+ self.keep(&path, index, hit);+ }+ }++ /// The files found, best first: each file's score adds up the best grade+ /// of each text times its weight (the element's own text 1, a label+ /// near it 0.35, a name 0.4); its line is the best place of the+ /// element's own text, else of the rest.+ pub fn ranked(&self) -> Vec<Candidate> {+ let mut out = Vec::new();+ for (path, best) in &self.files {+ let mut score = 0.0;+ let mut matched = Vec::new();+ let mut lead: Option<(f64, &Hit)> = None;+ for (index, hit) in best.iter().enumerate() {+ let Some(hit) = hit else { continue };+ let needle = &self.needles[index];+ let weighted = needle.role.weight() * hit.grade;+ score += weighted;+ matched.push(Matched {+ text: needle.text.clone(),+ role: needle.role,+ how: hit.how,+ line: hit.line,+ grade: round3(hit.grade),+ });+ let rank = weighted + if needle.role == Role::Text { 10.0 } else { 0.0 };+ if lead.is_none_or(|(r, _)| rank > r) {+ lead = Some((rank, hit));+ }+ }+ let Some((_, lead)) = lead else { continue };+ out.push(Candidate {+ path: path.clone(),+ line: lead.line,+ score: round3(score),+ matched,+ snippet: lead.snippet.clone(),+ symbol: None,+ callers: Vec::new(),+ });+ }+ out.sort_by(|a, b| {+ b.score+ .total_cmp(&a.score)+ .then_with(|| a.path.cmp(&b.path))+ });+ out+ }+}++/// The symbol around each of the top candidates' lines and up to three of+/// its callers or users, from the project's code graph.+fn enrich(candidates: &mut [Candidate], file: &std::sync::Arc<crate::query_file::QueryFile>) {+ let Some(graph) = crate::code_pack::GraphView::of_query_file(file.clone()) else {+ return;+ };+ for candidate in candidates.iter_mut() {+ let Some(symbol) = graph+ .symbols(&candidate.path)+ .iter()+ .rfind(|s| s.line <= candidate.line)+ else {+ continue;+ };+ candidate.symbol = Some(Place {+ name: symbol.name.clone(),+ path: symbol.path.clone(),+ line: symbol.line,+ relation: None,+ });+ let Ok(adjacency) = file.adjacency(symbol.node) else {+ continue;+ };+ let mut callers = Vec::new();+ for id in adjacency.all().into_iter().take(2_000) {+ let Ok(edge) = file.edge(id) else { continue };+ let relation = edge.relation.as_ref().and_then(Value::as_str).unwrap_or("");+ if edge.target != symbol.node+ || edge.source == symbol.node+ || !matches!(relation, "calls" | "references" | "uses" | "instantiates")+ {+ continue;+ }+ if let Some(user) = graph.symbol_of(edge.source) {+ let place = Place {+ name: user.name.clone(),+ path: user.path.clone(),+ line: user.line,+ relation: Some(relation.to_string()),+ };+ if !callers.contains(&place) {+ callers.push(place);+ }+ }+ if callers.len() >= 3 {+ break;+ }+ }+ candidate.callers = callers;+ }+}++/// What the search of a project found.+pub struct Found {+ pub candidates: Vec<Candidate>,+ pub files: usize,+ pub graph: bool,+ pub paths: HashSet<String>,+ pub seconds: f64,+}++/// Search the project's current files (as last synced) for `query`, with+/// its code graph when it has one; the `top` candidates.+pub fn search(run: &Run<'_>, query: &Query, top: usize) -> Result<Found> {+ let started = Instant::now();+ let (workspace, token) = (&run.session.workspace, &run.session.capability);+ let id = run.project.as_str();+ // The project's query file, written once for this build when missing+ // (as `pack` does), so that the graph can be read.+ let state = run+ .store+ .authorized_read(workspace, token, "read", |db, p| {+ crate::store::repo(db, p, id)?;+ let episode = crate::graph_projection::current_episode(db, id)?;+ Ok(crate::query_graph::query_file_state(db, id, &episode))+ })?;+ if state["state"] == "missing" {+ let _ = run+ .store+ .authorized_read(workspace, token, "read", |db, p| {+ crate::store::repo(db, p, id)?;+ crate::query_graph::ensure(db, id, true)+ });+ }+ let mut lookup = Lookup::new(query);+ run.store.authorized_read(workspace, token, "read", |db, p| {+ crate::store::repo(db, p, id)?;+ let mut paths = HashSet::new();+ let mut statement = db.prepare(+ "SELECT h.path,o.content FROM repo_heads h JOIN repo_objects o ON o.repository_id=h.repository_id AND o.sha256=h.sha256 WHERE h.repository_id=?1",+ )?;+ let mut rows = statement.query([id])?;+ while let Some(row) = rows.next()? {+ let path: String = row.get(0)?;+ if let Ok(text) = row.get::<_, String>(1) {+ lookup.scan(&path, &text);+ }+ paths.insert(path);+ }+ let mut one = db.prepare(+ "SELECT o.content FROM repo_heads h JOIN repo_objects o ON o.repository_id=h.repository_id AND o.sha256=h.sha256 WHERE h.repository_id=?1 AND h.path=?2",+ )?;+ let mut fetch = |path: &str| {+ one.query_row(rusqlite::params![id, path], |row| row.get::<_, String>(0))+ .ok()+ };+ lookup.follow_keys(&mut fetch);+ let keys = lookup.locale_keys(&mut fetch);+ if !keys.is_empty() {+ let mut again = db.prepare(+ "SELECT h.path,o.content FROM repo_heads h JOIN repo_objects o ON o.repository_id=h.repository_id AND o.sha256=h.sha256 WHERE h.repository_id=?1",+ )?;+ let mut rows = again.query([id])?;+ while let Some(row) = rows.next()? {+ let path: String = row.get(0)?;+ if let Ok(text) = row.get::<_, String>(1) {+ lookup.key_uses(&path, &text, &keys);+ }+ }+ }+ let episode = crate::graph_projection::current_episode(db, id)?;+ let graph = crate::query_file::open(db, id, &episode);+ if let Some(file) = &graph {+ let symbols = (0..file.symbol_count()).filter_map(|position| {+ let (_, name, path, line) = file.symbol(position).ok()?;+ Some((name, path, line?))+ });+ lookup.symbols(symbols, &mut fetch);+ }+ let mut candidates = lookup.ranked();+ candidates.truncate(top);+ if let Some(file) = &graph {+ enrich(&mut candidates, file);+ }+ Ok(Found {+ candidates,+ files: lookup.scanned,+ graph: graph.is_some(),+ paths,+ seconds: round3(started.elapsed().as_secs_f64()),+ })+ })+}++// ---------------------------------------------------------------- calls++/// Log one call of `pixel` in the spend log; an image-billed profile's+/// `price.per_image` adds `images` times its price to the cost.+#[allow(clippy::too_many_arguments)]+fn log(+ run: &Run<'_>,+ name: &str,+ profile: &model::Profile,+ meta: &Value,+ result: &Result<model::Completion>,+ held: &crate::spend::Reservation,+ images: u64,+ step: &str,+) -> Value {+ let call = crate::spend::Call {+ command: "pixel",+ profile: name,+ settings: profile,+ project: meta["project"].as_str(),+ commit: meta["commit"].as_str(),+ prompt_cache_key: None,+ };+ let mut entry = crate::spend::entry(&call, result, chrono::Utc::now());+ if result.is_ok()+ && images > 0+ && let Some(per_image) = profile.price.as_ref().and_then(|p| p.per_image)+ {+ let tokens = entry["cost_usd"].as_f64().unwrap_or(0.0);+ entry["cost_usd"] = json!(tokens + per_image * images as f64);+ }+ if let Err(error) = crate::spend::settle(&run.store.directory, held, &mut entry) {+ eprintln!("graphicle: could not write the spend log: {error}");+ }+ entry["step"] = json!(step);+ entry+}++/// The segmentation profile: `asked`, else a configured profile whose model+/// is `sam-*`, else SAM 3.1 at the reading profile's address when that is+/// the Meta Model API (no price: its cost is logged as unknown), else none.+fn sam_profile(+ run: &Run<'_>,+ reader: &model::Profile,+ asked: Option<&str>,+) -> Result<Option<(String, model::Profile)>> {+ let configuration =+ crate::settings::configuration(run.store, &run.session.workspace, run.config)?;+ if let Some(name) = asked {+ let (name, profile) = configuration.profile(Some(name)).map_err(|_| {+ Error::bad(format!(+ "No model profile named {name}: graphicle config show lists them"+ ))+ })?;+ return Ok(Some((name.to_string(), profile.clone())));+ }+ if let Some((name, profile)) = configuration+ .models+ .iter()+ .find(|(_, p)| p.model.starts_with("sam-") && p.protocol == "responses")+ {+ return Ok(Some((name.clone(), profile.clone())));+ }+ if model::meta_api(reader) {+ let mut profile = reader.clone();+ profile.model = SAM_MODEL.into();+ profile.price = None;+ profile.reasoning_effort = None;+ profile.prompt_cache = None;+ profile.max_cost_per_call = None;+ profile.max_cost_per_day = None;+ return Ok(Some((SAM_MODEL.to_string(), profile)));+ }+ Ok(None)+}++/// Segment the point with SAM: its box (none when nothing matched), the+/// call's log entry, and why there is no box when the call failed. A cap+/// that refuses the call is an error.+#[allow(clippy::too_many_arguments)]+async fn segment(+ run: &Run<'_>,+ name: &str,+ profile: &model::Profile,+ point: (u32, u32),+ image: &ImageInfo,+ data_url: &str,+ meta: &Value,+) -> Result<(Option<Bounds>, Value, Option<String>)> {+ let held = crate::spend::reserve(&run.store.directory, name, profile, 0, chrono::Utc::now())?;+ let body = sam_body(&profile.model, &sam_prompt(point, image), data_url);+ let start = Instant::now();+ let result = match model::post_json(profile, "responses", &body, SAM_TIMEOUT).await {+ Ok(value) if matches!(value["status"].as_str(), None | Some("completed")) => {+ Ok(model::Completion {+ text: output_text(&value),+ input_tokens: value["usage"]["input_tokens"].as_u64(),+ output_tokens: value["usage"]["output_tokens"].as_u64(),+ cached_tokens: None,+ reasoning_tokens: None,+ elapsed_ms: start.elapsed().as_millis() as u64,+ model: value["model"]+ .as_str()+ .unwrap_or(&profile.model)+ .to_string(),+ })+ }+ Ok(value) => Err(Error::bad(format!(+ "The segmentation did not complete ({})",+ value["status"].as_str().unwrap_or("unknown status")+ ))),+ Err(error) => Err(error),+ };+ let entry = log(run, name, profile, meta, &result, &held, 1, "segment");+ match result {+ Ok(done) => {+ let segments = parse_segments(&done.text);+ let bounds = choose(&segments, point, image).map(|mut b| {+ b.model = Some(done.model.clone());+ b+ });+ Ok((bounds, entry, None))+ }+ Err(error) => Ok((None, entry, Some(error.to_string()))),+ }+}++/// Read the element with the vision model: what it says, and the call's+/// log entry.+#[allow(clippy::too_many_arguments)]+async fn read_element(+ run: &Run<'_>,+ name: &str,+ profile: &model::Profile,+ prompt: &str,+ data_url: &str,+ meta: &Value,+) -> Result<(Reading, Value)> {+ let schema = read_schema();+ let estimate = ((READ_INSTRUCTIONS.len() + prompt.len() + schema.to_string().len()) / 3) as u64+ + IMAGE_TOKENS;+ let held = crate::spend::reserve(+ &run.store.directory,+ name,+ profile,+ crate::spend::worst_input(estimate, None, None),+ chrono::Utc::now(),+ )?;+ let output_limit = READ_OUTPUT_LIMIT.min(profile.output_limit);+ let result = model::complete_input(+ profile,+ READ_INSTRUCTIONS,+ &read_input(prompt, data_url),+ Some(&schema),+ output_limit,+ &mut |_| {},+ )+ .await;+ let entry = log(run, name, profile, meta, &result, &held, 0, "read");+ let done = result?;+ let value = long_context::json_in(&done.text)+ .map_err(|_| Error::bad("The model's reading is not JSON"))?;+ Ok((parse_reading(&value)?, entry))+}++/// The instructions of `--explain`.+pub const EXPLAIN_INSTRUCTIONS: &str = "You find the source code that draws an element of an application's screenshot, from a pack of the repository's code and candidate places that a search for the element's strings found. The pack starts with a header. It holds an architecture summary, a manifest of the files it holds, and the files themselves, each headed by its path, line range and why it is included; a pack in the cache layout has a repository part first and a question part after it. Code lines that start with a number and a tab carry their line number. Return one JSON object that matches the schema: ranking, the candidates (and any better place the pack shows) best first, each with its path exactly as shown, its line, and why in one sentence; explanation, a few sentences on which code draws the element and how it gets on screen (where it is registered, called or rendered), citing path:line. Use only what the pack and the candidates show, and say so when they do not settle it.";++fn explain_schema() -> Value {+ json!({"type":"object","additionalProperties":false,"required":["ranking","explanation"],+ "properties":{+ "ranking":{"type":"array","items":{"type":"object","additionalProperties":false,+ "required":["path","line","reason"],+ "properties":{"path":{"type":"string"},"line":{"type":"integer"},+ "reason":{"type":"string"}}}},+ "explanation":{"type":"string"}}})+}++/// The question of `--explain`: the element, and the candidates with their+/// lines.+fn explain_question(query: &Query, element: Option<&Reading>, candidates: &[Candidate]) -> String {+ let quoted = |texts: &[String]| {+ texts+ .iter()+ .map(|t| format!("\"{t}\""))+ .collect::<Vec<_>>()+ .join(", ")+ };+ let mut text = String::from("Which code draws the element of the screenshot");+ if !query.strings.is_empty() {+ text.push_str(&format!(" that shows {}", quoted(&query.strings)));+ }+ if let Some(element) = element.filter(|e| !e.element_type.is_empty()) {+ text.push_str(&format!(" (a {})", element.element_type));+ }+ if !query.nearby.is_empty() {+ text.push_str(&format!(", near {}", quoted(&query.nearby)));+ }+ text.push_str("? The candidates Graphicle's search found, best first:\n");+ for (i, c) in candidates.iter().enumerate() {+ text.push_str(&format!("{}. {}:{}\n", i + 1, c.path, c.line));+ for line in &c.snippet {+ text.push_str(&format!("{}\t{}\n", line.line, line.text));+ }+ }+ text+}++/// Ask the model to rank the candidates again from a small cache-aware+/// pack and explain them: its answer (`ranking` with paths the project+/// has, `explanation`), and the call's log entry.+async fn explain(+ run: &Run<'_>,+ query: &Query,+ element: Option<&Reading>,+ found: &Found,+ budget: usize,+) -> Result<(Value, Value)> {+ let (name, profile) = long_context::profile(run)?;+ let ratio = long_context::calibration(run.store, &name, &profile);+ let question = explain_question(query, element, &found.candidates);+ let user_of = |pack: &Value| format!("{}\n{}\n", crate::code_pack::text(pack), question);+ let schema = explain_schema();+ let request = long_context::Request {+ question: &question,+ rest: &question,+ instructions: EXPLAIN_INSTRUCTIONS,+ user_of: &user_of,+ schema: Some(&schema),+ };+ let budget = budget.min(long_context::budget_for(&profile, None)?);+ let (pack, _, counted) = long_context::fitted_pack(+ run,+ &profile,+ &request,+ budget,+ Some(budget),+ ratio,+ crate::terminal::human(run.json),+ )+ .await?;+ let (result, mut entry) = long_context::send(+ run,+ "pixel",+ &name,+ &profile,+ &pack,+ &request,+ counted,+ ratio,+ &mut |_| {},+ )+ .await?;+ entry["step"] = json!("explain");+ let done = result?;+ let mut value = long_context::json_in(&done.text)+ .map_err(|_| Error::bad("The model's explanation is not JSON"))?;+ if let Some(ranking) = value["ranking"].as_array_mut() {+ ranking.retain(|r| {+ r["path"].as_str().is_some_and(|p| found.paths.contains(p))+ && r["line"].as_u64().is_some_and(|l| l >= 1)+ });+ }+ let answer = json!({"ranking":value["ranking"],"explanation":value["explanation"],+ "pack":crate::code_pack::summary(&pack)});+ Ok((answer, entry))+}++// ---------------------------------------------------------------- command++fn clean(texts: &[String]) -> Vec<String> {+ texts+ .iter()+ .map(|t| t.trim().to_string())+ .filter(|t| !t.is_empty())+ .collect()+}++/// `graphicle pixel`.+pub async fn pixel(run: Run<'_>, args: Args) -> Result<()> {+ let started = Instant::now();+ let human = crate::terminal::human(run.json);+ let commit = run.folder.as_deref().and_then(crate::code_pack::git_head);+ let meta = json!({"project":run.project,"commit":commit});+ let mut report = json!({"project":run.project,"commit":commit});+ let mut calls: Vec<Value> = Vec::new();+ let mut notes: Vec<String> = Vec::new();+ let mut query = Query {+ strings: clean(&args.text),+ nearby: clean(&args.nearby),+ names: clean(&args.name),+ };+ let mut reading: Option<Reading> = None;+ if query.strings.is_empty() {+ let path = args.screenshot.as_ref().ok_or_else(|| {+ Error::bad("Give a screenshot and --at X,Y, or the element's text with --text")+ })?;+ let bytes = read_image(path)?;+ let image = image_info(&bytes)+ .ok_or_else(|| Error::bad("The screenshot is not a PNG, JPEG, GIF or WebP image"))?;+ let at = args+ .at+ .as_deref()+ .ok_or_else(|| Error::bad("Give the point with --at X,Y"))?;+ let point = parse_point(at, &image)?;+ let url = data_url(&image, &bytes);+ report["screenshot"] = json!({"path":path,"type":image.mime,"width":image.width,+ "height":image.height});+ report["point"] = json!({"x":point.0,"y":point.1});+ let (reader_name, reader) = long_context::profile(&run)?;+ let bounds = match &args.bbox {+ Some(text) => parse_bounds(text, &image)?,+ None => match sam_profile(&run, &reader, args.sam.as_deref())? {+ Some((sam_name, sam)) => {+ if human {+ eprintln!("graphicle: segmenting the point with {} ...", sam.model);+ }+ let (bounds, entry, failure) =+ segment(&run, &sam_name, &sam, point, &image, &url, &meta).await?;+ calls.push(entry);+ match (bounds, failure) {+ (Some(bounds), _) => bounds,+ (None, Some(failure)) => {+ notes.push(format!("The segmentation failed ({failure}); the box is the area around the point."));+ Bounds::around(point, &image)+ }+ (None, None) => {+ notes.push("SAM found no object at the point; the box is the area around the point.".into());+ Bounds::around(point, &image)+ }+ }+ }+ None => {+ notes.push("No segmentation profile (SAM 3.1 is on the Meta Model API); the box is the area around the point.".into());+ Bounds::around(point, &image)+ }+ },+ };+ report["box"] = json!(bounds);+ if human {+ eprintln!("graphicle: reading the element with {} ...", reader.model);+ }+ let prompt = read_prompt(point, &bounds, &image, args.phrase.as_deref());+ let (read, entry) = read_element(&run, &reader_name, &reader, &prompt, &url, &meta).await?;+ calls.push(entry);+ query.strings = read.strings.clone();+ for label in &read.nearby_labels {+ if !query.nearby.contains(label) {+ query.nearby.push(label.clone());+ }+ }+ for name in &read.names {+ if !query.names.contains(name) {+ query.names.push(name.clone());+ }+ }+ report["read"] = json!(read);+ reading = Some(read);+ }+ report["query"] = json!(query);+ let top = args.top as usize;+ let found = if query.is_empty() {+ notes.push(+ "The element shows no text and the model gave no names: there is nothing to look for."+ .into(),+ );+ None+ } else {+ Some(search(&run, &query, top)?)+ };+ if let Some(found) = &found {+ report["candidates"] = json!(found.candidates);+ report["lookup"] = json!({"files":found.files,"graph":found.graph,"seconds":found.seconds});+ if found.candidates.is_empty() {+ notes.push("No file of the project holds these strings.".into());+ }+ if args.explain && !found.candidates.is_empty() {+ if human {+ eprintln!("graphicle: asking the model to explain the candidates ...");+ }+ let (answer, entry) =+ explain(&run, &query, reading.as_ref(), found, args.budget).await?;+ calls.push(entry);+ report["explain"] = answer;+ }+ } else {+ report["candidates"] = json!([]);+ }+ let costs: Vec<Option<f64>> = calls.iter().map(|c| c["cost_usd"].as_f64()).collect();+ report["calls"] = json!(calls);+ report["cost_usd"] = if costs.iter().all(Option::is_some) {+ json!((costs.iter().flatten().sum::<f64>() * 1e6).round() / 1e6)+ } else {+ Value::Null+ };+ report["notes"] = json!(notes);+ report["seconds"] = json!(round3(started.elapsed().as_secs_f64()));+ if human {+ print!("{}", markdown(&report));+ } else {+ println!("{report}");+ }+ Ok(())+}++/// The report as Markdown.+pub fn markdown(report: &Value) -> String {+ let mut out = String::new();+ if let Some(shot) = report["screenshot"].as_object() {+ out.push_str(&format!(+ "## Pixel {},{} of {} ({}x{})\n\n",+ report["point"]["x"],+ report["point"]["y"],+ shot.get("path").and_then(Value::as_str).unwrap_or(""),+ shot.get("width").unwrap_or(&Value::Null),+ shot.get("height").unwrap_or(&Value::Null)+ ));+ } else {+ out.push_str("## Lookup\n\n");+ }+ let b = &report["box"];+ if b.is_object() {+ out.push_str(&format!(+ "Box: {},{} to {},{} ({}{})\n",+ b["x1"],+ b["y1"],+ b["x2"],+ b["y2"],+ b["model"]+ .as_str()+ .unwrap_or(b["from"].as_str().unwrap_or("")),+ b["confidence"]+ .as_f64()+ .map(|c| format!(", confidence {c:.2}"))+ .unwrap_or_default()+ ));+ }+ let r = &report["read"];+ if r.is_object() {+ let list = |v: &Value| {+ v.as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(|s| format!("\"{s}\""))+ .collect::<Vec<_>>()+ .join(", ")+ };+ out.push_str(&format!(+ "Read: {} {}{}{}\n",+ r["element_type"].as_str().unwrap_or("element"),+ list(&r["strings"]),+ if r["icon"].as_str().is_some_and(|i| !i.is_empty()) {+ format!("; icon: {}", r["icon"].as_str().unwrap_or(""))+ } else {+ String::new()+ },+ if r["nearby_labels"].as_array().is_some_and(|a| !a.is_empty()) {+ format!("; near {}", list(&r["nearby_labels"]))+ } else {+ String::new()+ }+ ));+ }+ out.push_str("\n### Where the code draws it\n\n");+ for (i, c) in report["candidates"]+ .as_array()+ .into_iter()+ .flatten()+ .enumerate()+ {+ out.push_str(&format!(+ "{}. {}:{} (score {})\n",+ i + 1,+ c["path"].as_str().unwrap_or(""),+ c["line"],+ c["score"]+ ));+ for m in c["matched"].as_array().into_iter().flatten().take(4) {+ out.push_str(&format!(+ " - \"{}\": {} (line {})\n",+ m["text"].as_str().unwrap_or(""),+ m["how"].as_str().unwrap_or(""),+ m["line"]+ ));+ }+ out.push_str(" ```\n");+ for line in c["snippet"].as_array().into_iter().flatten() {+ out.push_str(&format!(+ " {:>5} {}\n",+ line["line"],+ line["text"].as_str().unwrap_or("")+ ));+ }+ out.push_str(" ```\n");+ if let Some(symbol) = c["symbol"].as_object() {+ out.push_str(&format!(+ " In {} (line {})",+ symbol.get("name").and_then(Value::as_str).unwrap_or(""),+ symbol.get("line").unwrap_or(&Value::Null)+ ));+ let callers: Vec<String> = c["callers"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|p| {+ format!(+ "{} ({}:{})",+ p["name"].as_str().unwrap_or(""),+ p["path"].as_str().unwrap_or(""),+ p["line"]+ )+ })+ .collect();+ if !callers.is_empty() {+ out.push_str(&format!("; used by {}", callers.join(", ")));+ }+ out.push('\n');+ }+ }+ if let Some(explanation) = report["explain"]["explanation"].as_str() {+ out.push_str(&format!(+ "\n### The model's reading of the candidates\n\n{explanation}\n"+ ));+ }+ for note in report["notes"].as_array().into_iter().flatten() {+ out.push_str(&format!("\nNote: {}\n", note.as_str().unwrap_or("")));+ }+ let calls: Vec<String> = report["calls"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|c| {+ let mut text = format!(+ "{} ({})",+ c["model"].as_str().unwrap_or(""),+ c["step"].as_str().unwrap_or("")+ );+ if let (Some(input), Some(output)) =+ (c["input_tokens"].as_u64(), c["output_tokens"].as_u64())+ {+ text.push_str(&format!(" {input} in, {output} out"));+ if let Some(cached) = c["cached_tokens"].as_u64().filter(|n| *n > 0) {+ text.push_str(&format!(" ({cached} cached)"));+ }+ }+ match c["cost_usd"].as_f64() {+ Some(cost) => text.push_str(&format!(", {}", crate::spend::usd(cost))),+ None => text.push_str(", cost unknown"),+ }+ if let Some(seconds) = c["seconds"].as_f64() {+ text.push_str(&format!(", {seconds:.1} s"));+ }+ text+ })+ .collect();+ out.push('\n');+ if calls.is_empty() {+ out.push_str("No model call (the lookup is free).");+ } else {+ out.push_str(&format!("Calls: {}", calls.join("; ")));+ if let Some(total) = report["cost_usd"].as_f64() {+ out.push_str(&format!(". Total {}", crate::spend::usd(total)));+ }+ }+ out.push_str(&format!(" Time {} s.\n", report["seconds"]));+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn png(width: u32, height: u32) -> Vec<u8> {+ let mut b = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();+ b.extend_from_slice(&width.to_be_bytes());+ b.extend_from_slice(&height.to_be_bytes());+ b.extend_from_slice(&[8, 6, 0, 0, 0]);+ b+ }++ #[test]+ fn image_headers_give_type_and_size() {+ assert_eq!(+ image_info(&png(1600, 900)),+ Some(ImageInfo {+ mime: "image/png",+ width: 1600,+ height: 900+ })+ );+ let mut gif = b"GIF89a".to_vec();+ gif.extend_from_slice(&[0x40, 0x01, 0xF0, 0x00]);+ assert_eq!(+ image_info(&gif).map(|i| (i.width, i.height)),+ Some((320, 240))+ );+ // JPEG: SOI, an APP0 segment, then SOF0 with height 600 and width 800.+ let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00];+ jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08, 0x02, 0x58, 0x03, 0x20]);+ assert_eq!(+ image_info(&jpeg),+ Some(ImageInfo {+ mime: "image/jpeg",+ width: 800,+ height: 600+ })+ );+ let mut webp = b"RIFF\0\0\0\0WEBPVP8X\x0a\0\0\0\0\0\0\0".to_vec();+ webp.extend_from_slice(&[0x7F, 0x07, 0x00, 0x37, 0x04, 0x00]);+ assert_eq!(+ image_info(&webp).map(|i| (i.width, i.height)),+ Some((1920, 1080))+ );+ assert_eq!(image_info(b"not an image"), None);+ assert_eq!(image_info(&png(0, 10)), None);+ }++ #[test]+ fn the_sam_prompt_is_a_point_in_source_pixels() {+ let image = ImageInfo {+ mime: "image/png",+ width: 1200,+ height: 800,+ };+ assert_eq!(+ sam_prompt((700, 300), &image),+ "<0f>1<|point;x=700;y=300;w=1200;h=800|>"+ );+ let body = sam_body(+ "sam-3.1",+ "<0f>1<|point;x=1;y=2;w=3;h=4|>",+ "data:image/png;base64,AA==",+ );+ assert_eq!(body["model"], "sam-3.1");+ assert_eq!(body["input"][0]["content"][1]["type"], "input_image");+ assert_eq!(body["metadata"]["include_confidence"], "true");+ assert!(body.get("stream").is_none());+ }++ #[test]+ fn sam_records_parse_into_boxes() {+ // The documented example (one object, a lossless mask).+ let text = "<0f>0<|box;x1=181;y1=365;x2=556;y2=486;w=1516;h=1600|><|mask;x=0;y=0;data=122,376,~9jqo^BlbD-BleB1|>";+ let found = parse_segments(text);+ assert_eq!(found.len(), 1);+ assert_eq!((found[0].frame, found[0].object), (0, 0));+ assert_eq!((found[0].x1, found[0].y2), (181.0, 486.0));+ assert_eq!(found[0].width, Some(1516.0));+ assert_eq!(found[0].mask, Some((122, 376, '~')));+ // Two objects with confidences, one-bit masks whose payloads hold+ // `|>`, `;` and `<`, separated by commas.+ let text = "<0f>1<|box;x1=10;y1=20;x2=110;y2=60;w=1200;h=800;c=0.91|><|mask;x=10;y=20;c=0.9;data=40,100,!a|>b;c<|d|>,2<|box;x1=0;y1=0;x2=1199;y2=799;w=1200;h=800;c=0.4|><|mask;x=0;y=0;data=800,1200,!zz|>\n";+ let found = parse_segments(text);+ assert_eq!(found.len(), 2);+ assert_eq!(found[0].object, 1);+ assert_eq!(found[0].confidence, Some(0.91));+ assert_eq!(found[0].mask, Some((40, 100, '!')));+ assert_eq!(found[1].object, 2);+ assert_eq!(found[1].x2, 1199.0);+ // Positional fields, and no match at all.+ let found = parse_segments("<0f>1<|box;5;6;50;60;100;100|>");+ assert_eq!(+ (found[0].x1, found[0].y1, found[0].x2, found[0].y2),+ (5.0, 6.0, 50.0, 60.0)+ );+ assert!(parse_segments("").is_empty());+ assert!(parse_segments("<0f>").is_empty());+ }++ #[test]+ fn the_box_holds_the_point_and_is_scaled_to_the_image() {+ let image = ImageInfo {+ mime: "image/png",+ width: 1200,+ height: 800,+ };+ let found = parse_segments(+ "<0f>1<|box;x1=0;y1=0;x2=600;y2=400;w=600;h=400;c=0.99|>,1<|box;x1=100;y1=100;x2=200;y2=140;w=1200;h=800;c=0.5|>",+ );+ // The first holds the point once scaled (x2 = 1200 px), and is more confident.+ let chosen = choose(&found, (150, 120), &image).unwrap();+ assert_eq!(+ (chosen.x1, chosen.y1, chosen.x2, chosen.y2),+ (0, 0, 1199, 799)+ );+ // Only the second holds this point.+ let found = parse_segments(+ "<0f>1<|box;x1=0;y1=0;x2=50;y2=50;c=0.99|>,1<|box;x1=100;y1=100;x2=200;y2=140;c=0.5|>",+ );+ let chosen = choose(&found, (150, 120), &image).unwrap();+ assert_eq!(+ (chosen.x1, chosen.x2, chosen.confidence),+ (100, 200, Some(0.5))+ );+ assert!(choose(&[], (1, 1), &image).is_none());+ let around = Bounds::around((10, 795), &image);+ assert_eq!(+ (around.x1, around.y1, around.x2, around.y2),+ (0, 755, 170, 799)+ );+ }++ #[test]+ fn the_reading_is_checked() {+ let value = json!({"strings":[" Open Folder ", "", "x".repeat(400)],"element_type":"button",+ "icon":"","nearby_labels":["Explorer"],"names":["workbench.action.files.openFolder"]});+ let read = parse_reading(&value).unwrap();+ assert_eq!(read.strings, vec!["Open Folder"]);+ assert_eq!(read.nearby_labels, vec!["Explorer"]);+ assert!(parse_reading(&json!("text")).is_err());+ let prompt = read_prompt(+ (5, 6),+ &Bounds::around(+ (5, 6),+ &ImageInfo {+ mime: "image/png",+ width: 100,+ height: 50,+ },+ ),+ &ImageInfo {+ mime: "image/png",+ width: 100,+ height: 50,+ },+ Some("the save button"),+ );+ assert!(prompt.contains("x=5, y=6") && prompt.contains("from (0, 0) to (99, 46)"));+ assert!(prompt.contains("the save button"));+ assert_eq!(+ read_input("p", "data:x")[0]["content"][1]["image_url"],+ "data:x"+ );+ }++ #[test]+ fn literals_are_read_with_escapes_and_without_apostrophes() {+ assert_eq!(+ literals(r#"title: localize('openFolder', "Open &&Folder..."), // don't"#),+ vec!["openFolder", "Open &&Folder..."]+ );+ assert_eq!(literals(r#"const a = 'Don\'t Save';"#), vec!["Don't Save"]);+ assert_eq!(literals("<p>Don't save</p>"), Vec::<String>::new());+ assert_eq!(+ literals("`Ln ${line}, Col ${col}`"),+ vec!["Ln ${line}, Col ${col}"]+ );+ assert!(contains_word("press ok to go", "ok"));+ assert!(!contains_word("token", "ok"));+ assert!(contains_word("open folder...", "folder..."));+ }++ #[test]+ fn placeholders_cover_the_fixed_parts() {+ assert!(placeholder_cover("ln {0}, col {1}", "ln 12, col 5").is_some());+ assert!(placeholder_cover("ln {0}, col {1}", "col 5").is_none());+ assert!(placeholder_cover("%s selected", "3 selected").is_some());+ assert!(placeholder_cover("no placeholder", "no placeholder").is_none());+ assert!(placeholder_cover("{0}", "anything").is_none());+ }++ #[test]+ fn paths_count_less_for_tests_translations_and_docs() {+ assert_eq!(+ path_factor("src/vs/workbench/browser/parts/editor/editor.ts"),+ 1.0+ );+ assert_eq!(+ path_factor("src/vs/editor/test/browser/editor.test.ts"),+ 0.25+ );+ assert_eq!(path_factor("extensions/git/package.nls.de.json"), 0.3);+ assert_eq!(path_factor("extensions/git/package.nls.json"), 1.0);+ assert_eq!(path_factor("docs/guide.md"), 0.4);+ assert_eq!(path_factor("package-lock.json"), 0.05);+ }++ fn lookup(files: &[(&str, &str)], query: &Query) -> Vec<Candidate> {+ let mut lookup = Lookup::new(query);+ for (path, text) in files {+ lookup.scan(path, text);+ }+ let texts: BTreeMap<String, String> = files+ .iter()+ .map(|(p, t)| (p.to_string(), t.to_string()))+ .collect();+ lookup.follow_keys(|path| texts.get(path).cloned());+ let keys = lookup.locale_keys(|path| texts.get(path).cloned());+ for (path, text) in files {+ lookup.key_uses(path, text, &keys);+ }+ lookup.ranked()+ }++ #[test]+ fn json_keys_are_dotted_paths() {+ let text = "{\n \"app\": { \"title\": \"Sketch\" },\n \"menu\": {\n \"open\": \"Open\",\n \"reset\": \"Reset the \\\"canvas\\\"\",\n \"list\": [\"a\", {\"deep\": \"x\"}]\n }\n}\n";+ assert_eq!(json_key_at(text, 2).as_deref(), Some("app"));+ assert_eq!(json_key_at(text, 4).as_deref(), Some("menu.open"));+ assert_eq!(json_key_at(text, 5).as_deref(), Some("menu.reset"));+ assert_eq!(json_key_at(text, 6).as_deref(), Some("menu.list"));+ assert_eq!(json_key_at(text, 7), None);+ assert!(locale_json("packages/excalidraw/locales/en.json"));+ assert!(locale_json("src/i18n/en-US.json"));+ assert!(!locale_json("packages/excalidraw/locales/de-DE.json"));+ assert!(!locale_json("extensions/git/package.nls.json"));+ assert!(!locale_json("src/config/settings.json"));+ }++ #[test]+ fn a_locale_key_leads_to_the_code_that_draws_its_text() {+ let files = [+ (+ "locales/en.json",+ "{\n \"menu\": {\n \"open\": \"Open\",\n \"reset\": \"Reset the canvas\"\n }\n}\n",+ ),+ (+ "locales/de-DE.json",+ "{\n \"menu\": {\n \"reset\": \"Zeichenfläche zurücksetzen\"\n }\n}\n",+ ),+ (+ "src/app.js",+ "function renderMenu(root) {\n root.replaceChildren(\n menuItem(\"open\", t(\"menu.open\")),\n menuItem(\"reset\", t(\"menu.reset\")),\n );\n}\n",+ ),+ (+ "src/notes.js",+ "// The menu.reset item clears the canvas.\nexport const reset = \"reset\";\n",+ ),+ ];+ let query = Query {+ strings: vec!["Reset the canvas".into()],+ nearby: vec![],+ names: vec![],+ };+ let found = lookup(&files, &query);+ assert_eq!(found[0].path, "src/app.js");+ assert_eq!(found[0].line, 4);+ assert_eq!(found[1].path, "locales/en.json");+ assert!(found.iter().all(|c| c.path != "src/notes.js"));+ }++ #[test]+ fn the_lookup_ranks_the_string_that_draws_the_element_first() {+ let files = [+ (+ "src/views/explorer.ts",+ "import { localize } from 'nls';\n\nexport class Explorer {\n\ttitle = localize('explorer', \"Explorer\");\n\topen = localize('openFolder', \"Open &&Folder...\");\n}\n",+ ),+ (+ "src/views/welcome.ts",+ "// Opens a folder from the welcome page\nconst label = 'Open the folder picker';\n",+ ),+ (+ "src/test/explorer.test.ts",+ "assert.equal(button.label, 'Open Folder...');\n",+ ),+ ("README.md", "Click Open Folder... to start.\n"),+ (+ "src/status.ts",+ "const text = localize('position', \"Ln {0}, Col {1}\", line, column);\n",+ ),+ ];+ let query = Query {+ strings: vec!["Open Folder...".into()],+ nearby: vec!["EXPLORER".into()],+ names: vec![],+ };+ let found = lookup(&files, &query);+ assert_eq!(found[0].path, "src/views/explorer.ts");+ assert_eq!(found[0].line, 5);+ assert_eq!(+ found[0].snippet.iter().map(|l| l.line).collect::<Vec<_>>(),+ vec![3, 4, 5, 6]+ );+ assert!(+ found+ .iter()+ .position(|c| c.path == "src/test/explorer.test.ts")+ .unwrap()+ > 0+ );+ assert!(found.iter().all(|c| c.path != "src/views/welcome.ts"));+ // Placeholders: the status bar's "Ln 12, Col 5".+ let found = lookup(+ &files,+ &Query {+ strings: vec!["Ln 12, Col 5".into()],+ ..Query::default()+ },+ );+ assert_eq!(+ (found[0].path.as_str(), found[0].line),+ ("src/status.ts", 1)+ );+ assert_eq!(found[0].matched[0].how, "a string with placeholders");+ }++ #[test]+ fn a_localization_key_leads_to_the_manifest_that_uses_it() {+ let files = [+ (+ "extensions/git/package.nls.json",+ "{\n\t\"command.init\": \"Initialize Repository\",\n\t\"command.close\": \"Close Repository\"\n}\n",+ ),+ (+ "extensions/git/package.json",+ "{\n\t\"contributes\": {\n\t\t\"commands\": [\n\t\t\t{ \"command\": \"git.init\", \"title\": \"%command.init%\" }\n\t\t]\n\t}\n}\n",+ ),+ (+ "extensions/git/package.nls.de.json",+ "{\n\t\"command.init\": \"Initialize Repository\"\n}\n",+ ),+ ];+ let query = Query {+ strings: vec!["Initialize Repository".into()],+ ..Query::default()+ };+ let found = lookup(&files, &query);+ assert_eq!(+ (found[0].path.as_str(), found[0].line),+ ("extensions/git/package.json", 4)+ );+ assert_eq!(found[1].path, "extensions/git/package.nls.json");+ assert_eq!(found[2].path, "extensions/git/package.nls.de.json");+ }++ #[test]+ fn names_find_symbols_of_the_graph() {+ let query = Query {+ names: vec!["OpenFolderAction".into()],+ ..Query::default()+ };+ let mut lookup = Lookup::new(&query);+ lookup.scan("src/a.ts", "export class Other {}\n");+ lookup.symbols(+ [+ ("OpenFolderAction", "src/actions.ts", 3),+ (".run()", "src/actions.ts", 5),+ ]+ .into_iter(),+ |_| Some("a\nb\nexport class OpenFolderAction {\n}\n".into()),+ );+ let found = lookup.ranked();+ assert_eq!(+ (found[0].path.as_str(), found[0].line),+ ("src/actions.ts", 3)+ );+ }++ #[test]+ fn the_markdown_report_lists_candidates_and_costs() {+ let report = json!({"point":{"x":1,"y":2},"screenshot":{"path":"s.png","width":10,"height":10},+ "box":{"x1":0,"y1":0,"x2":9,"y2":9,"from":"sam","model":"sam-3.1","confidence":0.9},+ "read":{"strings":["Open Folder"],"element_type":"button","icon":"","nearby_labels":[],"names":[]},+ "candidates":[{"path":"a.ts","line":5,"score":1.1,"matched":[{"text":"Open Folder","how":"exact string","line":5}],+ "snippet":[{"line":5,"text":"x"}]}],+ "calls":[{"model":"sam-3.1","step":"segment","cost_usd":0.0025,"seconds":1.0},+ {"model":"muse-spark-1.3","step":"read","input_tokens":1500,"output_tokens":200,"cost_usd":0.0027,"seconds":3.0}],+ "cost_usd":0.0052,"notes":[],"seconds":4.2});+ let text = markdown(&report);+ assert!(text.contains("1. a.ts:5 (score 1.1)"));+ assert!(text.contains("Box: 0,0 to 9,9 (sam-3.1, confidence 0.90)"));+ assert!(text.contains("muse-spark-1.3 (read) 1500 in, 200 out"));+ }+}diff --git a/crates/graphicle/src/query.rs b/crates/graphicle/src/query.rsindex 1cb6be9..4c5e7d3 100644--- a/crates/graphicle/src/query.rs+++ b/crates/graphicle/src/query.rs@@ -71,6 +71,13 @@ pub const MORE_FILES_DEFAULT: usize = 10;/// after its excerpts.pub const MORE_FILES_FUSED: usize = 200;+/// The internal `context` argument with which `graphicle pack` asks for the+/// whole fused order of project-file passages (crate::pack); the packet then+/// carries it under the same name.+pub const PACK_RANKING: &str = "pack_ranking";+/// Passages of the fused order `graphicle pack` reads.+pub const PACK_FUSED: usize = 3000;+/// Retrieval options that are on unless a call turns them off. An absent or/// `null` option takes its value here and is listed in the packet's/// `retrieval_defaults`; `false` turns it off. Porter-stemmed BM25 (Lucene's@@ -1395,6 +1402,13 @@ fn context_impl(} else {fused_depth};+ // `graphicle pack` reads a long fused order (crate::code_pack).+ let fused_depth = if args[PACK_RANKING] == true {+ rank_request["fused_cap"] = json!(PACK_FUSED);+ PACK_FUSED+ } else {+ fused_depth+ };if fused_depth > 0 {rank_request["debug_fused"] = json!(fused_depth);}@@ -1890,6 +1904,26 @@ fn context_impl(}let mut packet = crate::phase::phase("assemble_pack", || native("pack", pack_request))?;packet["question"] = json!(question);+ // The fused order's project-file passages, as `graphicle pack` ranks+ // them: [path, first line, last line] each, best first.+ if args[PACK_RANKING] == true {+ let order: Vec<Value> = ranked["fused"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|id| by_id.get(id.as_str()?))+ .filter(|row| s(&row["source"], "id").starts_with("file:"))+ .filter(|row| !s(&row["source"], "path").is_empty())+ .map(|row| {+ json!([+ s(&row["source"], "path"),+ row["source"]["line"],+ row["source"]["end_line"]+ ])+ })+ .collect();+ packet[PACK_RANKING] = json!(order);+ }if let Some(listed) = packet.as_object_mut().and_then(|p| p.remove("next_files")) {packet["more_files"] = listed;}diff --git a/crates/graphicle/src/query_file.rs b/crates/graphicle/src/query_file.rsindex eded6a1..52926c9 100644--- a/crates/graphicle/src/query_file.rs+++ b/crates/graphicle/src/query_file.rs@@ -1384,6 +1384,12 @@ impl QueryFile {Ok(None)}+ /// The number of code symbols ([`QueryFile::symbol`] takes positions+ /// below it).+ pub fn symbol_count(&self) -> usize {+ self.symbols+ }+/// Code symbol `position`: (node index, dotted name, file, start line).pub fn symbol(&self, position: usize) -> Result<(usize, &str, &str, Option<usize>), Corrupt> {if position >= self.symbols {diff --git a/crates/graphicle/src/review.rs b/crates/graphicle/src/review.rsnew file mode 100644index 0000000..381779a--- /dev/null+++ b/crates/graphicle/src/review.rs@@ -0,0 +1,1326 @@+//! `graphicle review`: review comments on a change, from a cache-aware pack.+//!+//! The change is what `--head` adds since its merge base with `--base`, as a+//! pull request shows it, read with git in the project's folder (`fix`'s git:+//! hooks off, no variables that point it elsewhere). One model call:+//! - the instructions, then a pack ([`crate::code_pack`]) whose repository+//! part comes first in the cache layout, and whose question part has the+//! changed hunks pinned at the top of its ranking+//! ([`crate::code_pack::pinned`]): its focus is the changed code, its call+//! paths are the changed symbols' callers and callees along the code+//! graph's call edges, and its tests are the tests that touch them;+//! - then the change's own text: the lines of the pack's architecture for the+//! modules the change touches, the changed hunks, and the diff.+//!+//! The model returns structured comments: path, line, severity, body and the+//! `path:line` evidence each relies on. A comment is kept only on a line of+//! the head inside one of the diff's changed hunks, the lines a pull request+//! review can comment on; the others are dropped, with the reason. Its+//! evidence is checked against the working tree, and a comment none of whose+//! evidence holds is flagged: shown, never posted. Output is markdown for a+//! terminal, the report as JSON, or the body of GitHub's "create a review"+//! call (`--format github`), always a plain `COMMENT` review.+//!+//! The pack reads the project's synced files, so `--head` must be the commit+//! checked out in the project's folder. The call goes through the spend log+//! and its caps ([`crate::spend`]) like `ask --pack`. Nothing is fetched,+//! pushed or posted: the GitHub Action posts the review.++use crate::fix::Git;+use crate::long_context::{self, Request, Run, Tree};+use crate::{Error, Result, model};+use serde_json::{Value, json};+use std::collections::{BTreeSet, HashMap, HashSet};+use std::path::Path;+use std::sync::LazyLock;++pub const REVIEW_INSTRUCTIONS: &str = "You review a change to a code repository from a pack of its code and the change's diff. The pack starts with a header. It holds an architecture summary, a manifest of the files it holds, and the files themselves, each headed by its path, line range and why it is included. Its repository part comes first; its change part holds the changed code, the callers and callees of the changed symbols, and the tests that touch them. Code lines that start with a number and a tab carry their line number, which is not part of the file, and the pack shows the code as the change leaves it. After the pack come the architecture of the modules the change touches, the changed hunks with their line ranges, and the diff. Return one JSON object that matches the schema: a short summary of the change and of what you found, and the comments. Comment only on what a careful reviewer would raise: bugs, callers or contracts the change breaks, missing or wrong tests for changed behaviour, security and data-loss risks, and clear performance traps. Skip style and naming unless they hide a bug, and do not praise. Each comment gives a path exactly as the diff shows it and one line inside a changed hunk, numbered as in the code after the change; a severity: blocker, major, minor or nit; a body that says what is wrong and what to do about it; and its evidence: the path:line or path:start-end citations of the code the comment relies on, from the pack or the diff. Leave out any comment you cannot support with evidence, and return no comments when the change has no problems.";++/// Severities, most severe first.+pub const SEVERITIES: [&str; 4] = ["blocker", "major", "minor", "nit"];++/// The comments' JSON schema.+pub fn review_schema() -> Value {+ json!({"type":"object","properties":{+ "summary":{"type":"string"},+ "comments":{"type":"array","items":{"type":"object","properties":{+ "path":{"type":"string"},"line":{"type":"integer"},+ "severity":{"type":"string","enum":SEVERITIES},+ "body":{"type":"string"},+ "evidence":{"type":"array","items":{"type":"string"}}}}}}})+}++/// The diff's bytes a request holds at most; past them it is cut, and the+/// list of changed hunks still names every file.+const DIFF_CAP: usize = 400_000;+/// Room for the change's own text the repository part's size leaves, so that+/// it stays the same bytes for changes of up to about this many tokens.+const REVIEW_ROOM: usize = 24_000;+/// Room for the affected modules' lines of the architecture.+const MODULES_ROOM: usize = 4_000;+/// The affected modules' lines at most.+const MODULE_LINES: usize = 60;+/// A comment's body, in characters, at most.+const BODY_CAP: usize = 4_000;+/// Evidence entries read per comment at most.+const EVIDENCE_CAP: usize = 12;+/// The question the pack is ranked for, in bytes at most.+const QUESTION_CAP: usize = 2_000;+/// The summary, in characters, at most.+const SUMMARY_CAP: usize = 8_000;++/// `graphicle review`'s arguments.+#[derive(clap::Args, Clone, Debug)]+pub struct Args {+ /// The base to review against: a commit, branch or tag. The review covers+ /// what the head adds since their merge base, as a pull request shows it+ /// [default: origin/HEAD, else origin/main, origin/master, main or+ /// master].+ #[arg(long, value_name = "REF")]+ pub base: Option<String>,+ /// The head: the commit checked out in the project's folder, synced+ /// after checkout [default: HEAD].+ #[arg(long, value_name = "REF")]+ pub head: Option<String>,+ /// markdown, json (the report) or github (the body of GitHub's+ /// create-a-review call, for the Action) [default: markdown at a+ /// terminal, else json].+ #[arg(long, value_parser = ["markdown", "json", "github"])]+ pub format: Option<String>,+ /// Comments to keep at most, the most severe first.+ #[arg(long, value_name = "N", default_value_t = 20, value_parser = clap::value_parser!(u64).range(0..=100))]+ pub max_comments: u64,+ /// The project: an id, a key or a synced folder (default: this folder's+ /// project, else the last synced one).+ #[arg(long)]+ pub project: Option<String>,+ /// The pack's budget in tokens [default: the model's input limit less+ /// room for the diff].+ #[arg(long, value_name = "TOKENS")]+ pub budget: Option<usize>,+ /// The configured model profile to ask [default: the answer model].+ #[arg(long, value_name = "NAME")]+ pub model: Option<String>,+ /// The pack's layout, standard or cache [default: cache].+ #[arg(long, value_parser = ["standard", "cache"])]+ pub layout: Option<String>,+ /// With the cache layout: the share of the budget the repository part+ /// takes at most, from 0.1 to 1 [default: 0.9].+ #[arg(long, value_name = "F")]+ pub prefix_share: Option<f64>,+}++impl Args {+ /// Whether the output is for a program: json or github.+ pub fn machine(&self) -> bool {+ matches!(self.format.as_deref(), Some("json" | "github"))+ }+}++/// The output's format.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Format {+ Markdown,+ Json,+ Github,+}++impl Format {+ /// `--format`, else markdown at a terminal and JSON otherwise.+ pub fn of(asked: Option<&str>) -> Self {+ match asked {+ Some("markdown") => Self::Markdown,+ Some("json") => Self::Json,+ Some("github") => Self::Github,+ _ if crate::terminal::human(false) => Self::Markdown,+ _ => Self::Json,+ }+ }+}++/// One hunk of a diff: its ranges in the base and the head, and git's+/// function context after its `@@`.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Hunk {+ pub old_start: usize,+ pub old_lines: usize,+ pub new_start: usize,+ pub new_lines: usize,+ pub context: String,+}++impl Hunk {+ /// The head's lines the hunk shows (added and unchanged), if any.+ pub fn head_range(&self) -> Option<(usize, usize)> {+ (self.new_lines > 0 && self.new_start > 0)+ .then(|| (self.new_start, self.new_start + self.new_lines - 1))+ }+}++/// One file of a diff.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct FileDiff {+ /// Its path in the head; none for a deleted file.+ pub path: Option<String>,+ /// Its path in the base; none for an added file.+ pub old_path: Option<String>,+ pub binary: bool,+ pub hunks: Vec<Hunk>,+ pub added: usize,+ pub removed: usize,+}++impl FileDiff {+ pub fn status(&self) -> &'static str {+ match (&self.path, &self.old_path) {+ (Some(_), None) => "added",+ (None, _) => "deleted",+ (Some(new), Some(old)) if new != old => "renamed",+ _ => "modified",+ }+ }++ /// The path a reader knows it by.+ pub fn name(&self) -> &str {+ self.path+ .as_deref()+ .or(self.old_path.as_deref())+ .unwrap_or("")+ }++ /// Whether the head's `line` is inside one of the hunks.+ pub fn in_hunks(&self, line: usize) -> bool {+ self.hunks+ .iter()+ .filter_map(Hunk::head_range)+ .any(|(a, b)| a <= line && line <= b)+ }+}++static HUNK: LazyLock<regex::Regex> = LazyLock::new(|| {+ regex::Regex::new(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$").unwrap()+});++/// Git's C-style quoting undone (`"a\tb\303\251"`); none when it is not+/// quoting.+fn unquote(text: &str) -> Option<String> {+ let inner = text.strip_prefix('"')?.strip_suffix('"')?;+ let mut bytes = Vec::with_capacity(inner.len());+ let mut it = inner.bytes().peekable();+ while let Some(b) = it.next() {+ if b != b'\\' {+ bytes.push(b);+ continue;+ }+ match it.next()? {+ b'n' => bytes.push(b'\n'),+ b't' => bytes.push(b'\t'),+ b'r' => bytes.push(b'\r'),+ b'a' => bytes.push(7),+ b'b' => bytes.push(8),+ b'f' => bytes.push(12),+ b'v' => bytes.push(11),+ b'\\' => bytes.push(b'\\'),+ b'"' => bytes.push(b'"'),+ first @ b'0'..=b'7' => {+ let mut value = u32::from(first - b'0');+ for _ in 0..2 {+ match it.peek() {+ Some(&digit @ b'0'..=b'7') => {+ value = value * 8 + u32::from(digit - b'0');+ it.next();+ }+ _ => break,+ }+ }+ bytes.push((value & 0xff) as u8);+ }+ _ => return None,+ }+ }+ Some(String::from_utf8_lossy(&bytes).into_owned())+}++/// A path as a diff's header prints it: quoted or not.+fn plain(text: &str) -> String {+ let text = text.strip_suffix('\t').unwrap_or(text);+ unquote(text).unwrap_or_else(|| text.to_string())+}++/// The path of a `---` or `+++` line after its `a/` or `b/`; none for+/// `/dev/null`.+fn side_path(text: &str, side: &str) -> Option<String> {+ let text = plain(text);+ if text == "/dev/null" {+ return None;+ }+ Some(text.strip_prefix(side).unwrap_or(&text).to_string())+}++/// The two paths of a `diff --git a/X b/Y` line, for the files without+/// `---` and `+++` lines (binary files, mode changes).+fn header_paths(rest: &str) -> Option<(String, String)> {+ if let Some(quoted) = rest.strip_prefix('"') {+ let close = quoted.find("\" ")?;+ let old = unquote(&rest[..close + 2])?;+ let new = plain("ed[close + 2..]);+ return Some((+ old.strip_prefix("a/")?.to_string(),+ new.strip_prefix("b/")?.to_string(),+ ));+ }+ // `a/P b/P`, the same path twice, is the usual case; split in the middle.+ let n = rest.len();+ if n >= 5 && (n - 5).is_multiple_of(2) {+ let p = (n - 5) / 2;+ if rest.is_char_boundary(2 + p)+ && rest.is_char_boundary(5 + p)+ && rest.starts_with("a/")+ && &rest[2 + p..5 + p] == " b/"+ && rest[2..2 + p] == rest[5 + p..]+ {+ return Some((rest[2..2 + p].to_string(), rest[5 + p..].to_string()));+ }+ }+ let (old, new) = rest.split_once(" b/")?;+ Some((old.strip_prefix("a/")?.to_string(), plain(new)))+}++/// The files of a unified diff as `git diff` prints it, with the `a/` and+/// `b/` prefixes.+pub fn parse_diff(text: &str) -> Vec<FileDiff> {+ let mut files: Vec<FileDiff> = Vec::new();+ // The base's and the head's lines the current hunk has still to show.+ let (mut old_left, mut new_left) = (0usize, 0usize);+ for line in text.split('\n') {+ if old_left > 0 || new_left > 0 {+ let file = files.last_mut();+ match line.as_bytes().first() {+ Some(b'+') => {+ new_left = new_left.saturating_sub(1);+ if let Some(file) = file {+ file.added += 1;+ }+ continue;+ }+ Some(b'-') => {+ old_left = old_left.saturating_sub(1);+ if let Some(file) = file {+ file.removed += 1;+ }+ continue;+ }+ // An unchanged line; `diff.suppressBlankEmpty` prints an empty+ // one without its space.+ Some(b' ') | None => {+ old_left = old_left.saturating_sub(1);+ new_left = new_left.saturating_sub(1);+ continue;+ }+ Some(b'\\') => continue,+ // A hunk that ends early: read the line as a header.+ _ => (old_left, new_left) = (0, 0),+ }+ }+ if let Some(rest) = line.strip_prefix("diff --git ") {+ let mut file = FileDiff::default();+ if let Some((old, new)) = header_paths(rest) {+ file.old_path = Some(old);+ file.path = Some(new);+ }+ files.push(file);+ continue;+ }+ let Some(file) = files.last_mut() else {+ continue;+ };+ if let Some(rest) = line.strip_prefix("--- ") {+ file.old_path = side_path(rest, "a/");+ } else if let Some(rest) = line.strip_prefix("+++ ") {+ file.path = side_path(rest, "b/");+ } else if line.starts_with("new file mode ") {+ file.old_path = None;+ } else if line.starts_with("deleted file mode ") {+ file.path = None;+ } else if let Some(rest) = line.strip_prefix("rename from ") {+ file.old_path = Some(plain(rest));+ } else if let Some(rest) = line.strip_prefix("rename to ") {+ file.path = Some(plain(rest));+ } else if line.starts_with("Binary files ") || line == "GIT binary patch" {+ file.binary = true;+ } else if let Some(c) = HUNK.captures(line) {+ let n = |i: usize, default: usize| {+ c.get(i)+ .and_then(|m| m.as_str().parse().ok())+ .unwrap_or(default)+ };+ let hunk = Hunk {+ old_start: n(1, 0),+ old_lines: n(2, 1),+ new_start: n(3, 0),+ new_lines: n(4, 1),+ context: c.get(5).map_or("", |m| m.as_str()).trim().to_string(),+ };+ (old_left, new_left) = (hunk.old_lines, hunk.new_lines);+ file.hunks.push(hunk);+ }+ }+ files+}++/// The first `cap` bytes of `text` at a character boundary.+fn clip(text: &str, cap: usize) -> &str {+ if text.len() <= cap {+ return text;+ }+ let mut end = cap;+ while !text.is_char_boundary(end) {+ end -= 1;+ }+ &text[..end]+}++fn short(sha: &str) -> &str {+ &sha[..12.min(sha.len())]+}++/// A severity of [`SEVERITIES`] for what the model wrote.+fn severity_of(text: Option<&str>) -> &'static str {+ match text.unwrap_or("").trim().to_ascii_lowercase().as_str() {+ "blocker" | "critical" => "blocker",+ "major" | "high" | "error" => "major",+ "nit" | "info" | "style" | "suggestion" | "trivial" => "nit",+ _ => "minor",+ }+}++fn severity_rank(severity: &str) -> usize {+ SEVERITIES+ .iter()+ .position(|s| *s == severity)+ .unwrap_or(SEVERITIES.len())+}++/// What became of the model's comments.+#[derive(Debug, Default)]+pub struct Checked {+ /// On a changed line, with evidence that holds: shown and posted.+ pub kept: Vec<Value>,+ /// On a changed line, but none of its evidence holds: shown, not posted.+ pub flagged: Vec<Value>,+ /// Elsewhere, empty, a repeat, or over the cap, with the reason.+ pub dropped: Vec<Value>,+}++/// The comments of the model's `reply` checked against the change's `files`+/// and the working `tree`: at most `max` kept, the most severe first.+pub fn check(reply: &Value, files: &[FileDiff], tree: &mut Tree, max: usize) -> Checked {+ let by_path: HashMap<&str, &FileDiff> = files+ .iter()+ .filter_map(|f| Some((f.path.as_deref()?, f)))+ .collect();+ let mut checked = Checked::default();+ let mut seen: HashSet<(String, usize, String)> = HashSet::new();+ let mut held: Vec<Value> = Vec::new();+ for comment in reply["comments"].as_array().into_iter().flatten() {+ let written = comment["path"].as_str().unwrap_or("").trim();+ let mut path = written.trim_start_matches("./").to_string();+ if !by_path.contains_key(path.as_str())+ && let Some(stripped) = path.strip_prefix("b/").or(path.strip_prefix("a/"))+ && by_path.contains_key(stripped)+ {+ path = stripped.to_string();+ }+ let line = comment["line"]+ .as_u64()+ .or_else(|| comment["line"].as_str().and_then(|s| s.trim().parse().ok()))+ .unwrap_or(0) as usize;+ let severity = severity_of(comment["severity"].as_str());+ let body = clip(comment["body"].as_str().unwrap_or("").trim(), BODY_CAP).to_string();+ let mut out = json!({"path":path,"line":line,"severity":severity,"body":body});+ let problem = if body.is_empty() {+ Some("the comment is empty".to_string())+ } else if line == 0 {+ Some("the comment names no line".to_string())+ } else {+ match by_path.get(path.as_str()) {+ None => Some(format!(+ "{} is not a file the change adds or modifies",+ clip(written, 200)+ )),+ Some(file) if !file.in_hunks(line) => Some(format!(+ "line {line} is outside the changed hunks of {path}"+ )),+ Some(_) => None,+ }+ };+ if let Some(problem) = problem {+ out["reason"] = json!(problem);+ checked.dropped.push(out);+ continue;+ }+ if !seen.insert((path.clone(), line, body.clone())) {+ out["reason"] = json!("a repeat of an earlier comment");+ checked.dropped.push(out);+ continue;+ }+ let mut evidence: Vec<Value> = Vec::new();+ for item in comment["evidence"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .take(EVIDENCE_CAP)+ {+ let cites = long_context::citations(item);+ if cites.is_empty() {+ evidence.push(json!({"cite":clip(item.trim(), 200),"valid":false,+ "problem":"not a path:line citation"}));+ }+ for c in cites {+ let cite = if c.end == c.line {+ format!("{}:{}", c.path, c.line)+ } else {+ format!("{}:{}-{}", c.path, c.line, c.end)+ };+ let problem = tree.problem(&c.path, c.line, c.end);+ evidence.push(json!({"cite":cite,"valid":problem.is_none(),"problem":problem}));+ }+ }+ let holds = evidence.iter().any(|e| e["valid"] == true);+ out["evidence"] = json!(evidence);+ if holds {+ held.push(out);+ } else {+ out["reason"] = json!("none of its evidence holds in the working tree");+ checked.flagged.push(out);+ }+ }+ held.sort_by(|a, b| {+ let key = |c: &Value| {+ (+ severity_rank(c["severity"].as_str().unwrap_or("")),+ c["path"].as_str().unwrap_or("").to_string(),+ c["line"].as_u64().unwrap_or(0),+ )+ };+ key(a).cmp(&key(b))+ });+ for mut comment in held {+ if checked.kept.len() < max {+ checked.kept.push(comment);+ } else {+ comment["reason"] = json!("over --max-comments");+ checked.dropped.push(comment);+ }+ }+ checked+}++/// The lines of the pack's architecture for the modules that hold the+/// changed `paths`, and the dependencies between folders that involve them.+pub fn affected_modules(pack: &Value, paths: &[&str]) -> Vec<String> {+ let architecture: String = pack["sections"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|s| s["name"] == "architecture")+ .flat_map(|s| s["chunks"].as_array().into_iter().flatten())+ .filter_map(|c| c["text"].as_str())+ .collect();+ let holds = |module: &str, path: &str| {+ if module.is_empty() {+ !path.contains('/')+ } else {+ path.starts_with(module) && path[module.len()..].starts_with('/')+ }+ };+ let mut modules: BTreeSet<&str> = BTreeSet::new();+ let mut lines: Vec<String> = Vec::new();+ for line in architecture.lines() {+ if let Some(rest) = line.strip_prefix("- ")+ && let Some((module, _)) = rest.split_once("/: ")+ && paths.iter().any(|path| holds(module, path))+ {+ modules.insert(module);+ lines.push(line.to_string());+ }+ }+ for line in architecture.lines() {+ if let Some(rest) = line.strip_prefix("- ")+ && let Some((from, tail)) = rest.split_once("/ -> ")+ && let Some((to, _)) = tail.split_once("/ (")+ && (modules.contains(from) || modules.contains(to))+ {+ lines.push(line.to_string());+ }+ }+ lines.truncate(MODULE_LINES);+ lines+}++/// The question the pack's ranking reads: the changed files and the+/// function context of their hunks.+fn ranking_question(files: &[FileDiff]) -> String {+ let mut question = String::from("Review a change to ");+ for (i, file) in files.iter().filter(|f| f.path.is_some()).enumerate() {+ if i > 0 {+ question.push_str(", ");+ }+ question.push_str(file.name());+ let contexts: BTreeSet<&str> = file+ .hunks+ .iter()+ .map(|h| h.context.as_str())+ .filter(|c| !c.is_empty())+ .collect();+ if !contexts.is_empty() {+ let shown: Vec<&str> = contexts.into_iter().take(3).collect();+ question.push_str(&format!(" ({})", shown.join("; ")));+ }+ if question.len() > QUESTION_CAP {+ break;+ }+ }+ clip(&question, QUESTION_CAP).to_string()+}++/// The changed hunks, one line per file, for the request and the report.+fn hunk_lines(files: &[FileDiff]) -> String {+ let mut out = String::new();+ for file in files {+ let ranges: Vec<String> = file+ .hunks+ .iter()+ .filter_map(|h| {+ let (a, b) = h.head_range()?;+ Some(if h.context.is_empty() {+ format!("{a}-{b}")+ } else {+ format!("{a}-{b} ({})", clip(&h.context, 120))+ })+ })+ .collect();+ let status = match (file.status(), &file.old_path) {+ ("renamed", Some(old)) => format!("renamed from {old}"),+ (status, _) => status.to_string(),+ };+ let binary = if file.binary { ", binary" } else { "" };+ out.push_str(&format!(+ "- {} ({status}{binary}, +{} -{}): {}\n",+ file.name(),+ file.added,+ file.removed,+ if ranges.is_empty() {+ "no lines to comment on".to_string()+ } else {+ ranges.join(", ")+ }+ ));+ }+ out+}++/// The changed hunks the pack pins at the top of its ranking.+fn focus_of(files: &[FileDiff]) -> Value {+ let passages: Vec<Value> = files+ .iter()+ .filter_map(|f| Some((f.path.as_deref()?, f)))+ .flat_map(|(path, f)| {+ f.hunks.iter().filter_map(move |h| {+ let (a, b) = h.head_range()?;+ Some(json!({"path":path,"start_line":a,"end_line":b}))+ })+ })+ .take(crate::code_pack::MAX_PINNED)+ .collect();+ json!(passages)+}++/// What the pack's change part holds: the changed symbols its focus names,+/// the call-path lines, the callers' and callees' excerpts and the tests.+fn context_of(pack: &Value, changed: &[&str]) -> Value {+ let mut symbols: BTreeSet<String> = BTreeSet::new();+ let mut call_lines = 0;+ let mut neighbours: Vec<Value> = Vec::new();+ let mut tests: BTreeSet<String> = BTreeSet::new();+ for section in pack["sections"].as_array().into_iter().flatten() {+ for chunk in section["chunks"].as_array().into_iter().flatten() {+ let why = chunk["why"].as_str().unwrap_or("");+ let path = chunk["path"].as_str();+ match section["name"].as_str().unwrap_or("") {+ "focus" if path.is_some_and(|p| changed.contains(&p)) => {+ if let Some((_, names)) = why.split_once("defines ") {+ symbols.extend(names.split(", ").map(|n| n.trim().to_string()));+ }+ }+ "paths" => match path {+ None => {+ call_lines += chunk["text"]+ .as_str()+ .unwrap_or("")+ .lines()+ .filter(|l| l.contains(" -> "))+ .count();+ }+ Some(path) => {+ neighbours.push(json!({"path":path,"start_line":chunk["start_line"],+ "end_line":chunk["end_line"],"why":why}));+ }+ },+ "tests" => {+ if let Some(path) = path {+ tests.insert(path.to_string());+ }+ }+ _ => {}+ }+ }+ }+ json!({"changed_symbols":symbols,"call_path_lines":call_lines,+ "callers_and_callees":neighbours,"tests":tests})+}++/// `ref`'s commit in `folder`.+fn commit_of(git: &Git, folder: &Path, reference: &str) -> Result<String> {+ if reference.is_empty() || reference.starts_with('-') {+ return Err(Error::bad(format!("{reference:?} is not a git reference")));+ }+ let spec = format!("{reference}^{{commit}}");+ git.run(folder, &["rev-parse", "--verify", "--quiet", &spec])+ .map(|sha| sha.trim().to_string())+ .map_err(|_| Error::bad(format!("No commit {reference} in {}", folder.display())))+}++/// `--base` when it is left out: the remote's default branch, else a local+/// main or master.+fn default_base(git: &Git, folder: &Path) -> Result<(String, String)> {+ for candidate in [+ "origin/HEAD",+ "origin/main",+ "origin/master",+ "main",+ "master",+ ] {+ if let Ok(sha) = commit_of(git, folder, candidate) {+ return Ok((candidate.to_string(), sha));+ }+ }+ Err(Error::bad(+ "Name the base to review against with --base REF (no origin/HEAD, main or master here)",+ ))+}++/// GitHub turns `@name` into a mention that notifies; the model's text never+/// mentions anyone (a word joiner after each `@` that starts a name).+fn quiet_mentions(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ let mut chars = text.chars().peekable();+ while let Some(c) = chars.next() {+ out.push(c);+ if c == '@' && chars.peek().is_some_and(|n| n.is_ascii_alphanumeric()) {+ out.push('\u{2060}');+ }+ }+ out+}++fn cite_list(comment: &Value, valid: bool) -> Vec<String> {+ comment["evidence"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|e| (e["valid"] == true) == valid)+ .filter_map(|e| e["cite"].as_str())+ .map(str::to_string)+ .collect()+}++/// A kept comment as GitHub shows it.+fn github_comment_body(comment: &Value) -> String {+ let cites: Vec<String> = cite_list(comment, true)+ .into_iter()+ .map(|c| format!("`{c}`"))+ .collect();+ quiet_mentions(&format!(+ "**{}**: {}\n\nEvidence: {}",+ comment["severity"].as_str().unwrap_or("minor"),+ comment["body"].as_str().unwrap_or(""),+ cites.join(", ")+ ))+}++/// The body of GitHub's create-a-review call: a `COMMENT` review at the+/// head, its comments at `prefix` (the project's folder in its repository)+/// plus their paths.+pub fn github_review(report: &Value, prefix: &str) -> Value {+ let comments: Vec<Value> = report["comments"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|c| {+ json!({"path":format!("{prefix}{}", c["path"].as_str().unwrap_or("")),+ "line":c["line"],"side":"RIGHT","body":github_comment_body(c)})+ })+ .collect();+ let count = |key: &str| report[key].as_array().map_or(0, Vec::len);+ let mut body = format!(+ "**Graphicle review** of `{}..{}`",+ short(report["merge_base"].as_str().unwrap_or("")),+ short(report["head"].as_str().unwrap_or(""))+ );+ if let Some(model) = report["model"].as_str() {+ body.push_str(&format!(" with {model}"));+ }+ body.push_str(&format!(+ ".\n\n{}",+ report["summary"].as_str().unwrap_or("")+ ));+ if report["result"] == "reviewed" {+ body.push_str(&format!(+ "\n\n{} inline comment(s); {} withheld because none of their evidence holds; {} dropped (outside the changed lines, repeated, or over the cap).",+ comments.len(),+ count("flagged"),+ count("dropped")+ ));+ }+ if let Some(line) = report["usage_line"].as_str() {+ body.push_str(&format!("\n\nUsage: {line}"));+ }+ json!({"commit_id":report["head"],"event":"COMMENT",+ "body":clip(&quiet_mentions(&body), 60_000),"comments":comments})+}++/// The report for a terminal.+pub fn markdown(report: &Value) -> String {+ let mut out = format!(+ "# Review of {}..{}\n\n",+ short(report["merge_base"].as_str().unwrap_or("")),+ short(report["head"].as_str().unwrap_or(""))+ );+ if let Some(files) = report["files"].as_array() {+ out.push_str(&format!("{} file(s) changed.\n\n", files.len()));+ }+ if let Some(summary) = report["summary"].as_str().filter(|s| !s.is_empty()) {+ out.push_str(summary);+ out.push_str("\n\n");+ }+ let show = |out: &mut String, title: &str, list: &Value, why: bool| {+ let Some(list) = list.as_array().filter(|l| !l.is_empty()) else {+ return;+ };+ out.push_str(&format!("## {title} ({})\n\n", list.len()));+ for c in list {+ out.push_str(&format!(+ "- **{}** `{}:{}`: {}\n",+ c["severity"].as_str().unwrap_or("minor"),+ c["path"].as_str().unwrap_or(""),+ c["line"],+ c["body"].as_str().unwrap_or("").replace('\n', "\n ")+ ));+ let valid = cite_list(c, true);+ if !valid.is_empty() {+ out.push_str(&format!(" Evidence: {}\n", valid.join(", ")));+ }+ let invalid = cite_list(c, false);+ if !invalid.is_empty() {+ out.push_str(&format!(+ " Evidence that does not hold: {}\n",+ invalid.join(", ")+ ));+ }+ if why && let Some(reason) = c["reason"].as_str() {+ out.push_str(&format!(" ({reason})\n"));+ }+ }+ out.push('\n');+ };+ show(&mut out, "Comments", &report["comments"], false);+ show(+ &mut out,+ "Flagged: no evidence that holds, not posted",+ &report["flagged"],+ false,+ );+ show(&mut out, "Dropped", &report["dropped"], true);+ if report["comments"].as_array().is_some_and(Vec::is_empty) && report["result"] == "reviewed" {+ out.push_str("No comments to post.\n\n");+ }+ if let Some(line) = report["usage_line"].as_str() {+ out.push_str(line);+ out.push('\n');+ }+ out+}++fn files_json(files: &[FileDiff]) -> Value {+ json!(+ files+ .iter()+ .map(|f| json!({"path":f.path,"old_path":f.old_path,"status":f.status(),+ "binary":f.binary,"added":f.added,"removed":f.removed,+ "hunks":f.hunks.iter().filter_map(Hunk::head_range).map(|(a, b)| json!([a, b])).collect::<Vec<_>>()}))+ .collect::<Vec<_>>()+ )+}++fn output(report: &Value, format: Format, prefix: &str) -> Result<()> {+ match format {+ Format::Json => println!("{}", serde_json::to_string_pretty(report)?),+ Format::Github => println!(+ "{}",+ serde_json::to_string_pretty(&github_review(report, prefix))?+ ),+ Format::Markdown => print!("{}", markdown(report)),+ }+ Ok(())+}++/// `graphicle review`.+pub async fn review(run: Run<'_>, args: Args) -> Result<()> {+ let format = Format::of(args.format.as_deref());+ let human = format == Format::Markdown && crate::terminal::human(run.json);+ let (name, profile) = long_context::profile(&run)?;+ let folder = run.folder.clone().ok_or_else(|| {+ Error::bad("review reads a project's own folder, a git working tree: sync one first")+ })?;+ let git = Git::new(&run.store.directory)?;+ let head_ref = args.head.as_deref().unwrap_or("HEAD");+ let head = commit_of(&git, &folder, head_ref)?;+ let checked_out = commit_of(&git, &folder, "HEAD")?;+ if head != checked_out {+ return Err(Error::bad(format!(+ "review reads the project's synced files, which are the folder's HEAD ({}): check out {head_ref} there and sync it, then review",+ short(&checked_out)+ )));+ }+ let (base_ref, base) = match &args.base {+ Some(reference) => (reference.clone(), commit_of(&git, &folder, reference)?),+ None => default_base(&git, &folder)?,+ };+ let merge_base = git+ .run(&folder, &["merge-base", &base, &head])+ .map_err(|_| {+ Error::bad(format!(+ "{base_ref} and {head_ref} have no merge base here: fetch the base's history (in a GitHub workflow, actions/checkout with fetch-depth: 0)"+ ))+ })?+ .trim()+ .to_string();+ let prefix = git+ .run(&folder, &["rev-parse", "--show-prefix"])?+ .trim()+ .to_string();+ let diff = git.run(+ &folder,+ &[+ "-c",+ "core.quotePath=false",+ "diff",+ "--no-color",+ "--no-ext-diff",+ "--no-textconv",+ "--relative",+ "--find-renames",+ "--unified=3",+ "--src-prefix=a/",+ "--dst-prefix=b/",+ &merge_base,+ &head,+ "--",+ ],+ )?;+ let files = parse_diff(&diff);+ if human+ && git+ .run(&folder, &["status", "--porcelain", "--untracked-files=no"])+ .is_ok_and(|s| !s.trim().is_empty())+ {+ eprintln!(+ "graphicle: the folder has uncommitted changes; the diff reads commits, the pack the synced files"+ );+ }+ let mut report = json!({"result":"reviewed","base":base_ref,"base_commit":base,+ "merge_base":merge_base,"head":head,"files":files_json(&files),"summary":"",+ "comments":[],"flagged":[],"dropped":[]});+ if files.is_empty() {+ report["result"] = json!("no changes");+ report["summary"] = json!(format!(+ "No changes between {} and {}.",+ short(&merge_base),+ short(&head)+ ));+ return output(&report, format, &prefix);+ }+ // No head line to comment on (deleted, renamed or binary files only): no call.+ let focus = focus_of(&files);+ if focus.as_array().is_none_or(Vec::is_empty) {+ report["result"] = json!("nothing to review");+ report["summary"] = json!(+ "The change adds or modifies no lines a review can comment on: it deletes, renames or changes binary files only."+ );+ return output(&report, format, &prefix);+ }+ // The change's own text, after the pack: the affected modules (from the+ // pack's architecture), the changed hunks and the diff.+ let cut = diff.len() > DIFF_CAP;+ let shown = clip(&diff, DIFF_CAP);+ let rest = format!(+ "Changed hunks of {}..{} (path, status, lines added and removed, then the head's line ranges a comment may name):\n{}\n<diff>\n{shown}{}</diff>\n{}Review the change.\n",+ short(&merge_base),+ short(&head),+ hunk_lines(&files),+ if shown.ends_with('\n') { "" } else { "\n" },+ if cut {+ format!(+ "The diff is cut at {DIFF_CAP} of its {} bytes; the hunks above list every file.\n",+ diff.len()+ )+ } else {+ String::new()+ }+ );+ let changed: Vec<&str> = files.iter().filter_map(|f| f.path.as_deref()).collect();+ let user_of = |pack: &Value| {+ let modules = affected_modules(pack, &changed);+ let modules = if modules.is_empty() {+ String::new()+ } else {+ format!(+ "Architecture of the modules the change touches:\n{}\n\n",+ modules.join("\n")+ )+ };+ format!("{}\n{modules}{rest}", crate::code_pack::text(pack))+ };+ let question = ranking_question(&files);+ let schema = review_schema();+ let request = Request {+ question: &question,+ rest: &rest,+ instructions: REVIEW_INSTRUCTIONS,+ user_of: &user_of,+ schema: Some(&schema),+ };+ let ratio = long_context::calibration(run.store, &name, &profile);+ let rest_tokens = crate::code_pack::estimate::tokens(+ rest.len(),+ crate::code_pack::estimate::PACK_TEXT_BYTES_PER_TOKEN,+ ) + MODULES_ROOM;+ let room = |budget: usize, less: usize| {+ if run.budget.is_none() {+ budget+ .saturating_sub(less)+ .max(crate::code_pack::MIN_BUDGET)+ } else {+ budget+ }+ };+ let budget = room(+ long_context::budget_with(&profile, run.budget, ratio)?,+ rest_tokens,+ );+ let nominal = room(long_context::budget_for(&profile, run.budget)?, REVIEW_ROOM);+ let repack = |budget: usize| {+ let mut args = long_context::pack_args(&run, &profile, &question, budget, Some(nominal));+ args["focus"] = focus.clone();+ run.store+ .project_pack(&run.session.workspace, &run.session.capability, &args)+ };+ let pack = repack(budget)?;+ let (pack, _, counted) =+ long_context::fit_with(&profile, &request, pack, budget, ratio, human, &repack).await?;+ if human {+ long_context::tell_packed(&pack, &name, &profile);+ }+ let (result, _) = long_context::send(+ &run,+ "review",+ &name,+ &profile,+ &pack,+ &request,+ counted,+ ratio,+ &mut |_| {},+ )+ .await?;+ let done = result?;+ let reply = long_context::json_in(&done.text)?;+ if !reply.is_object() {+ return Err(Error::bad("The model's review is not a JSON object"));+ }+ let mut tree = Tree::new(Some(folder.clone()));+ let checked = check(&reply, &files, &mut tree, args.max_comments as usize);+ let usage = long_context::usage_json(&done, profile.price.as_ref());+ report["summary"] = json!(clip(+ reply["summary"].as_str().unwrap_or("").trim(),+ SUMMARY_CAP+ ));+ report["comments"] = json!(checked.kept);+ report["flagged"] = json!(checked.flagged);+ report["dropped"] = json!(checked.dropped);+ report["model"] = json!(done.model);+ report["profile"] = json!(name);+ report["usage_line"] = json!(crate::spend::line(&usage));+ report["usage"] = usage;+ report["prompt_cache_key"] =+ json!(model::prompt_cache_on(&profile).then(|| long_context::cache_key(&pack)));+ report["input_tokens_counted"] = json!(counted);+ report["diff_cut"] = json!(cut);+ report["context"] = context_of(&pack, &changed);+ report["pack"] = crate::code_pack::summary(&pack);+ output(&report, format, &prefix)+}++#[cfg(test)]+mod tests {+ use super::*;++ const DIFF: &str = "diff --git a/src/answer.go b/src/answer.go+index 1111111..2222222 100644+--- a/src/answer.go++++ b/src/answer.go+@@ -3,4 +3,5 @@ package answer+ // Answer is the answer.+ func Answer() int {+-\treturn 41++\tvalue := 42++\treturn value+ }+@@ -20,2 +21,3 @@ func Other() int {+ \ta := 1++-- not a header+ \treturn a+diff --git a/docs/new.md b/docs/new.md+new file mode 100644+index 0000000..3333333+--- /dev/null++++ b/docs/new.md+@@ -0,0 +1,2 @@++# New++--- a list item, not a header+diff --git a/old.txt b/old.txt+deleted file mode 100644+index 4444444..0000000+--- a/old.txt++++ /dev/null+@@ -1 +0,0 @@+--- gone+\\ No newline at end of file+diff --git a/a b.rs b/c d.rs+similarity index 90%+rename from a b.rs+rename to c d.rs+index 5555555..6666666 100644+--- a/a b.rs\t++++ b/c d.rs\t+@@ -1 +1 @@+-fn a() {}++fn c() {}+diff --git a/logo.png b/logo.png+index 7777777..8888888 100644+Binary files a/logo.png and b/logo.png differ+diff --git \"a/caf\\303\\251.txt\" \"b/caf\\303\\251.txt\"+index 9999999..aaaaaaa 100644+--- \"a/caf\\303\\251.txt\"++++ \"b/caf\\303\\251.txt\"+@@ -1 +1,2 @@+ one++two+";++ #[test]+ fn a_diff_parses_into_files_hunks_and_counts() {+ let files = parse_diff(DIFF);+ let names: Vec<&str> = files.iter().map(FileDiff::name).collect();+ assert_eq!(+ names,+ [+ "src/answer.go",+ "docs/new.md",+ "old.txt",+ "c d.rs",+ "logo.png",+ "café.txt"+ ]+ );+ let statuses: Vec<&str> = files.iter().map(FileDiff::status).collect();+ assert_eq!(+ statuses,+ [+ "modified", "added", "deleted", "renamed", "modified", "modified"+ ]+ );+ let answer = &files[0];+ assert_eq!(answer.hunks.len(), 2);+ assert_eq!(answer.hunks[0].head_range(), Some((3, 7)));+ assert_eq!(answer.hunks[0].context, "package answer");+ assert_eq!(answer.hunks[1].head_range(), Some((21, 23)));+ // "-- not a header" and "--- a list item" are content, not headers.+ assert_eq!((answer.added, answer.removed), (3, 1));+ assert_eq!((files[1].added, files[1].removed), (2, 0));+ assert_eq!(files[1].old_path, None);+ assert_eq!(files[2].path, None);+ // A removed line "-- gone" prints as "--- gone": content, not a header.+ assert_eq!((files[2].added, files[2].removed), (0, 1));+ assert_eq!(files[2].hunks[0].head_range(), None);+ assert_eq!(files[3].old_path.as_deref(), Some("a b.rs"));+ assert!(files[4].binary && files[4].hunks.is_empty());+ assert!(answer.in_hunks(3) && answer.in_hunks(7) && answer.in_hunks(22));+ assert!(!answer.in_hunks(2) && !answer.in_hunks(8) && !answer.in_hunks(24));+ }++ #[test]+ fn quoting_and_headers_without_paths_lines() {+ assert_eq!(unquote("\"a\\tb\\\\c\\\"\"").as_deref(), Some("a\tb\\c\""));+ assert_eq!(unquote("plain"), None);+ assert_eq!(+ header_paths("a/x y.rs b/x y.rs"),+ Some(("x y.rs".into(), "x y.rs".into()))+ );+ assert_eq!(+ header_paths("\"a/\\303\\251\" \"b/\\303\\251\""),+ Some(("é".into(), "é".into()))+ );+ }++ fn tree_with(files: &[(&str, usize)]) -> (tempfile::TempDir, Tree) {+ let dir = tempfile::TempDir::new().unwrap();+ for (path, lines) in files {+ let full = dir.path().join(path);+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();+ std::fs::write(&full, "x\n".repeat(*lines)).unwrap();+ }+ let tree = Tree::new(Some(dir.path().to_path_buf()));+ (dir, tree)+ }++ #[test]+ fn comments_are_kept_flagged_or_dropped() {+ let files = parse_diff(DIFF);+ let (_dir, mut tree) = tree_with(&[("src/answer.go", 30), ("src/use.go", 10)]);+ let reply = json!({"summary":"s","comments":[+ {"path":"src/answer.go","line":5,"severity":"minor","body":"Name the constant.",+ "evidence":["src/answer.go:4-6"]},+ {"path":"b/src/answer.go","line":6,"severity":"BLOCKER","body":"Callers expect 41.",+ "evidence":["src/use.go:3", "nowhere.go:1"]},+ {"path":"src/answer.go","line":5,"severity":"minor","body":"Name the constant.",+ "evidence":["src/answer.go:4"]},+ {"path":"src/answer.go","line":12,"severity":"major","body":"Outside.","evidence":["src/answer.go:12"]},+ {"path":"old.txt","line":1,"severity":"major","body":"Deleted.","evidence":["src/answer.go:1"]},+ {"path":"src/answer.go","line":22,"severity":"nit","body":"Unsupported.",+ "evidence":["src/answer.go:99","see the docs"]},+ {"path":"src/answer.go","line":4,"severity":"major","body":"","evidence":[]}+ ]});+ let checked = check(&reply, &files, &mut tree, 20);+ let kept: Vec<(&str, u64, &str)> = checked+ .kept+ .iter()+ .map(|c| {+ (+ c["path"].as_str().unwrap(),+ c["line"].as_u64().unwrap(),+ c["severity"].as_str().unwrap(),+ )+ })+ .collect();+ // The blocker first; `b/` taken off its path; one invalid citation+ // beside a valid one keeps it.+ assert_eq!(+ kept,+ [+ ("src/answer.go", 6, "blocker"),+ ("src/answer.go", 5, "minor")+ ]+ );+ assert_eq!(checked.kept[0]["evidence"][1]["valid"], false);+ assert_eq!(checked.flagged.len(), 1);+ assert_eq!(checked.flagged[0]["line"], 22);+ let reasons: Vec<&str> = checked+ .dropped+ .iter()+ .map(|c| c["reason"].as_str().unwrap())+ .collect();+ assert_eq!(reasons.len(), 4, "{reasons:?}");+ assert!(reasons.contains(&"a repeat of an earlier comment"));+ assert!(reasons.contains(&"line 12 is outside the changed hunks of src/answer.go"));+ assert!(reasons.contains(&"old.txt is not a file the change adds or modifies"));+ assert!(reasons.contains(&"the comment is empty"));+ // The cap keeps the most severe.+ let capped = check(&reply, &files, &mut tree, 1);+ assert_eq!(capped.kept.len(), 1);+ assert_eq!(capped.kept[0]["severity"], "blocker");+ assert!(+ capped+ .dropped+ .iter()+ .any(|c| c["reason"] == "over --max-comments")+ );+ }++ #[test]+ fn the_github_review_comments_on_the_head_and_mentions_no_one() {+ let report = json!({"result":"reviewed","merge_base":"0123456789abcdef","head":"fedcba9876543210ffff",+ "model":"muse-spark-1.3","summary":"Looks risky, cc @octocat.",+ "comments":[{"path":"src/answer.go","line":6,"severity":"major","body":"Ask @admin first.",+ "evidence":[{"cite":"src/use.go:3","valid":true},{"cite":"x.go:1","valid":false}]}],+ "flagged":[{"path":"src/answer.go","line":22}],"dropped":[],+ "usage_line":"1,000 tokens in, 10 out; 1.0 s."});+ let review = github_review(&report, "services/api/");+ assert_eq!(review["event"], "COMMENT");+ assert_eq!(review["commit_id"], "fedcba9876543210ffff");+ let comment = &review["comments"][0];+ assert_eq!(comment["path"], "services/api/src/answer.go");+ assert_eq!(comment["line"], 6);+ assert_eq!(comment["side"], "RIGHT");+ let body = comment["body"].as_str().unwrap();+ assert!(+ body.starts_with("**major**: Ask @\u{2060}admin first."),+ "{body}"+ );+ assert!(body.contains("`src/use.go:3`") && !body.contains("x.go:1"));+ let summary = review["body"].as_str().unwrap();+ assert!(summary.contains("@\u{2060}octocat") && !summary.contains("@octocat"));+ assert!(summary.contains("1 inline comment(s); 1 withheld"));+ }++ #[test]+ fn affected_modules_come_from_the_architecture() {+ let pack = json!({"sections":[{"name":"architecture","part":"prefix","chunks":[{"text":+ "3 files.\n\n- src/: 2 files, ~100 tokens, Go. The answer.\n- docs/: 1 files, ~10 tokens\n- /: 1 files, ~5 tokens\n\nDependencies between folders (edges from the key symbols, most first):\n- src/ -> lib/ (4)\n- docs/ -> lib/ (1)\n"}]}]});+ let lines = affected_modules(&pack, &["src/answer.go", "README.md"]);+ assert_eq!(+ lines,+ [+ "- src/: 2 files, ~100 tokens, Go. The answer.",+ "- /: 1 files, ~5 tokens",+ "- src/ -> lib/ (4)"+ ]+ );+ }++ #[test]+ fn the_ranking_question_names_the_changed_files() {+ let question = ranking_question(&parse_diff(DIFF));+ assert!(+ question.starts_with(+ "Review a change to src/answer.go (func Other() int {; package answer)"+ ),+ "{question}"+ );+ assert!(!question.contains("old.txt"));+ let focus = focus_of(&parse_diff(DIFF));+ assert_eq!(+ focus[0],+ json!({"path":"src/answer.go","start_line":3,"end_line":7})+ );+ assert!(+ focus+ .as_array()+ .unwrap()+ .iter()+ .all(|p| p["path"] != "old.txt")+ );+ }+}diff --git a/crates/graphicle/src/setup.rs b/crates/graphicle/src/setup.rsindex 67c6d31..d5ffa29 100644--- a/crates/graphicle/src/setup.rs+++ b/crates/graphicle/src/setup.rs@@ -207,6 +207,8 @@ pub fn setup_report() -> Result<Value> {let started = std::time::Instant::now();let data = data_folder(store)?;+ // The exclude lines a read-only `.git` refuses are this run's alone.+ agent_files::take_unexcluded();// 1. The project: the folder decides it, and its code graph is// built in the foreground.@@ -286,6 +288,7 @@ pub fn setup_report(agent_setup::Policy {refresh_ours: true,drop_guards: true,+ skip_unwritable_hooks: true,},) {Ok(result) => client_report(client, &result),@@ -355,6 +358,29 @@ pub fn setup_report((switch, &connected),options,)?;+ // The lines a read-only `.git` (Codex's sandbox) kept out of an exclude+ // file: the files they cover show in `git status` until they are added.+ let mut unexcluded: Vec<(PathBuf, String, Vec<String>)> = Vec::new();+ for line in agent_files::take_unexcluded() {+ match unexcluded+ .iter_mut()+ .find(|(file, _, _)| *file == line.file)+ {+ Some((_, _, patterns)) => patterns.push(line.pattern),+ None => unexcluded.push((line.file, line.reason, vec![line.pattern])),+ }+ }+ let git_exclude: Vec<Value> = unexcluded+ .into_iter()+ .map(|(file, reason, patterns)| {+ let named: Vec<&str> = patterns.iter().map(String::as_str).collect();+ let by_hand = format!(+ "To keep setup's files out of Git, add {} to it, one per line",+ crate::disconnect::listed(&named)+ );+ json!({"file":file,"state":"skipped","reason":reason,"lines":patterns,"by_hand":by_hand})+ })+ .collect();// 7. The answer model.let model = model_step(store, &session, config, options, ui);@@ -473,6 +499,9 @@ pub fn setup_report(if !prompt_context.is_null() {report["prompt_context"] = prompt_context;}+ if !git_exclude.is_empty() {+ report["git_exclude"] = json!(git_exclude);+ }Ok(report)}@@ -570,16 +599,34 @@ fn client_report(client: &str, result: &Value) -> Value {let mut report = json!({"client":client,"name":agent_detect::name(client),"state":state,"file":result["configuration"],"entry":result["entry"],"project":result["project"]["id"],"tools":result["tools"]});+ // Hooks whose file could not be written: why, and how to add them later.+ let skipped = |hooks: &Value| {+ let mut skipped =+ json!({"file":hooks["configuration"],"state":"skipped","reason":hooks["reason"]});+ if let Some(by_hand) = hooks.get("by_hand") {+ skipped["by_hand"] = by_hand.clone();+ }+ skipped+ };if let Some(hooks) = result.get("hooks") {let installed = hooks["installed"].as_array().map_or(0, Vec::len);- report["capture"] = json!({"file":hooks["configuration"],"installed":hooks["installed"],- "state":if installed > 0 { "added" } else { "already set" },"next":hooks["next"]});+ report["capture"] = if hooks["state"] == "skipped" {+ skipped(hooks)+ } else {+ json!({"file":hooks["configuration"],"installed":hooks["installed"],+ "state":if installed > 0 { "added" } else { "already set" },"next":hooks["next"]})+ };}// Claude Code's guard hooks (`--guards`), or those of an earlier setup// that this run removed.- if let Some(guard) = result["graph"]["guard_hooks"].as_object() {- report["guard"] = json!({"file":guard.get("configuration"),"installed":guard.get("installed"),- "state":guard_state(guard)});+ let guard_hooks = &result["graph"]["guard_hooks"];+ if let Some(guard) = guard_hooks.as_object() {+ report["guard"] = if guard_hooks["state"] == "skipped" {+ skipped(guard_hooks)+ } else {+ json!({"file":guard.get("configuration"),"installed":guard.get("installed"),+ "state":guard_state(guard)})+ };}if let Some(access) = result.get("access") {report["access"] = access.clone();@@ -587,6 +634,10 @@ fn client_report(client: &str, result: &Value) -> Value {if let Some(note) = result.get("note") {report["note"] = note.clone();}+ // Muse Code: its plugin, or why its settings entry was written instead.+ if let Some(plugin) = result.get("plugin") {+ report["plugin"] = plugin.clone();+ }report}@@ -612,18 +663,29 @@ fn capture_report(clients: &[Value], chosen: &[&str], skipped: bool) -> Value {.iter().filter(|client| client.get("capture").is_some()).map(|client| {- json!({"client":client["client"],"name":client["name"],"file":client["capture"]["file"],- "state":client["capture"]["state"]})+ let capture = &client["capture"];+ let mut hooked = json!({"client":client["client"],"name":client["name"],+ "file":capture["file"],"state":capture["state"]});+ for key in ["reason", "by_hand"] {+ if let Some(value) = capture.get(key) {+ hooked[key] = value.clone();+ }+ }+ hooked}).collect();if hooked.is_empty() {- let reason = if chosen.iter().any(|client| agent_setup::has_hooks(client)) {+ let reason = if chosen.iter().any(|client| agent_setup::setup_hooks(client)) {"the connection failed"} else {"neither Claude Code nor Codex was connected"};return json!({"state":"skipped","reason":reason});}+ // Every hooks file refused (Claude Code's sandbox): each client says why.+ if hooked.iter().all(|client| client["state"] == "skipped") {+ return json!({"state":"skipped","reason":"no hooks file could be written","clients":hooked});+ }json!({"state":"on","clients":hooked,"what":"After each answer, the session's finished turns are stored as sources of this project (private spans dropped, credentials redacted); at session start the agent gets your reviewed memory. graphicle setup --no-capture skips this."})}@@ -775,9 +837,12 @@ fn write_instructions(agent_instructions::section()};let upserted = agent_instructions::upsert_section(&text, switch, §ion);- if let Some(new) = upserted.text {- agent_files::backup_in(data, &target)?;- agent_files::write(&target, native(new, crlf).as_bytes(), 0o644)?;+ if let Some(new) = upserted.text+ && let Err(reason) = backup_and_write(data, &target, |path| {+ agent_files::write(path, native(new, crlf).as_bytes(), 0o644)+ })+ {+ return Ok(json!({"file":target,"state":"skipped","reason":reason}));}agent_files::record(data,@@ -801,8 +866,31 @@ fn write_instructions(Ok(report)}+/// Back up `path` and write it with `write`. A file setup cannot write (in+/// Claude Code's sandbox, or a read-only folder) is skipped, not fatal: the+/// error is the reason, which names the OS error.+fn backup_and_write(+ data: &Path,+ path: &Path,+ write: impl FnOnce(&Path) -> Result<()>,+) -> std::result::Result<(), String> {+ agent_files::backup_in(data, path)+ .and_then(|_| write(path))+ .map_err(|error| agent_files::write_failure(&error).unwrap_or(error.message))+}++/// The line to add by hand to each of `hooks`, in the hooks folder.+fn hooks_by_hand(data: &Path, folder: &Path, hooks: &[&str]) -> String {+ format!(+ "Add this line to {} in that folder: {}",+ crate::disconnect::listed(hooks),+ git_hooks::manual_line(folder, data_argument(data))+ )+}+/// Step 5: the freshness block in the repository's post-commit,-/// post-merge and post-checkout hooks.+/// post-merge and post-checkout hooks. A hook that cannot be written is+/// skipped with its reason, and the step gives the line to add by hand.fn git_hooks_step(data: &Path,folder: &Path,@@ -813,8 +901,7 @@ fn git_hooks_step(Ok(dir) => dir.clone(),Err(reason) => {return Ok(json!({"state":"skipped","reason":reason,- "by_hand":format!("Add this line to post-commit, post-merge and post-checkout in that folder: {}",- git_hooks::manual_line(folder, data_argument(data)))}));+ "by_hand":hooks_by_hand(data, folder, &git_hooks::HOOKS)}));}};let block = git_hooks::block(@@ -824,6 +911,7 @@ fn git_hooks_step(data_argument(data),)?;let mut hooks = Vec::new();+ let mut unwritten = Vec::new();for name in git_hooks::HOOKS {let path = hooks_dir.join(name);if path.is_symlink() {@@ -850,8 +938,13 @@ fn git_hooks_step(};let mut entry = match git_hooks::upsert(text.as_deref(), &block, folder) {git_hooks::Upserted::Changed(new, state) => {- agent_files::backup_in(data, &path)?;- agent_files::write(&path, native(new, crlf).as_bytes(), 0o755)?;+ if let Err(reason) = backup_and_write(data, &path, |path| {+ agent_files::write(path, native(new, crlf).as_bytes(), 0o755)+ }) {+ hooks.push(json!({"hook":name,"file":path,"state":"skipped","reason":reason}));+ unwritten.push(name);+ continue;+ }json!({"hook":name,"file":path,"state":state})}git_hooks::Upserted::Unchanged => {@@ -885,12 +978,21 @@ fn git_hooks_step(let changed = hooks.iter().any(|hook| matches!(hook["state"].as_str(), Some("added" | "updated")));- let all_set = hooks.iter().all(|hook| hook["state"] == "already set");- Ok(- json!({"state":if changed { "added" } else if all_set { "already set" } else { "partly set" },- "directory":hooks_dir,"hooks":hooks,- "what":"After commits, merges and checkouts, Graphicle syncs this folder in the background"}),- )+ let state = if changed {+ "added"+ } else if hooks.iter().all(|hook| hook["state"] == "already set") {+ "already set"+ } else if hooks.iter().all(|hook| hook["state"] == "skipped") {+ "skipped"+ } else {+ "partly set"+ };+ let mut report = json!({"state":state,"directory":hooks_dir,"hooks":hooks,+ "what":"After commits, merges and checkouts, Graphicle syncs this folder in the background"});+ if !unwritten.is_empty() {+ report["by_hand"] = json!(hooks_by_hand(data, folder, &unwritten));+ }+ Ok(report)}#[cfg(unix)]@@ -1043,13 +1145,19 @@ fn graphify_step("state":"skipped","reason":"Graphicle's connection failed, so Graphify's entry stays"}));continue;}- let state = match &entry.group {+ let removed = match &entry.group {Some(group) => remove_json_entry(data, owner, entry, group)?,None => remove_codex_entry(data, owner, entry)?,};- changed.push(- json!({"file":entry.file,"entry":entry.name,"client":entry.client,"state":state}),- );+ let mut item = json!({"file":entry.file,"entry":entry.name,"client":entry.client});+ match removed {+ Ok(state) => item["state"] = json!(state),+ Err(reason) => {+ item["state"] = json!("skipped");+ item["reason"] = json!(format!("{reason}, so Graphify's entry stays"));+ }+ }+ changed.push(item);}if options.no_instructions && !graphify.sections.is_empty() {report["note"] =@@ -1059,21 +1167,22 @@ fn graphify_step(Ok(report)}-/// Remove Graphify's entry from a JSON client file, recording it.+/// Remove Graphify's entry from a JSON client file, recording it; `Err`+/// inside is why the file could not be written.fn remove_json_entry(data: &Path,(folder, project): (&Path, &str),entry: &agent_detect::GraphifyEntry,group: &str,-) -> Result<&'static str> {+) -> Result<std::result::Result<&'static str, String>> {let Some(mut document) = agent_detect::json_file(&entry.file) else {- return Ok("skipped");+ return Ok(Ok("skipped"));};let Some(value) = document[group].as_object_mut().and_then(|servers| servers.shift_remove(&entry.name))else {- return Ok("skipped");+ return Ok(Ok("skipped"));};// A group it was alone in goes with it.if document[group]@@ -1088,8 +1197,11 @@ fn remove_json_entry(let edited = original.as_deref().and_then(|text| crate::json_edit::remove(text, group, &entry.name));- agent_files::backup_in(data, &entry.file)?;- agent_files::write_json(&entry.file, original.as_deref(), edited, &document)?;+ if let Err(reason) = backup_and_write(data, &entry.file, |path| {+ agent_files::write_json(path, original.as_deref(), edited, &document)+ }) {+ return Ok(Err(reason));+ }agent_files::record(data,Change {@@ -1104,24 +1216,28 @@ fn remove_json_entry(..Change::default()},)?;- Ok("removed")+ Ok(Ok("removed"))}-/// Remove Graphify's table from Codex's `config.toml`, recording it.+/// Remove Graphify's table from Codex's `config.toml`, recording it; `Err`+/// inside is why the file could not be written.fn remove_codex_entry(data: &Path,(folder, project): (&Path, &str),entry: &agent_detect::GraphifyEntry,-) -> Result<&'static str> {+) -> Result<std::result::Result<&'static str, String>> {let Ok(raw) = std::fs::read_to_string(&entry.file) else {- return Ok("skipped");+ return Ok(Ok("skipped"));};let (text, crlf) = unix(&raw);let Some((new, removed, at)) = codex_config::remove(&text, &entry.name) else {- return Ok("skipped");+ return Ok(Ok("skipped"));};- agent_files::backup_in(data, &entry.file)?;- agent_files::write(&entry.file, native(new, crlf).as_bytes(), 0o600)?;+ if let Err(reason) = backup_and_write(data, &entry.file, |path| {+ agent_files::write(path, native(new, crlf).as_bytes(), 0o600)+ }) {+ return Ok(Err(reason));+ }agent_files::record(data,Change {@@ -1135,7 +1251,7 @@ fn remove_codex_entry(..Change::default()},)?;- Ok("removed")+ Ok(Ok("removed"))}/// The summary's freshness (ux-fresh): the project's folder against its@@ -1328,6 +1444,18 @@ pub fn render_setup(report: &Value) -> String {" {label:<13} {:<15} {detail}",client["name"].as_str().unwrap_or_default()));+ // Muse Code: Graphicle's plugin, or why its settings got the entry.+ match client["plugin"].as_str() {+ Some(_) => line(format!(+ " {:<15} the graphicle plugin (server, skill, hooks): approve it once with muse plugins approve graphicle",+ ""+ )),+ None => {+ if let Some(reason) = client["plugin"]["reason"].as_str() {+ line(format!(" {:<15} no plugin: {reason}", ""));+ }+ }+ }}// Each entry runs the one MCP server; Claude Code's, its five// essential tools unless --tools says otherwise.@@ -1351,37 +1479,49 @@ pub fn render_setup(report: &Value) -> String {));}}- let capture = &report["capture"];- match capture["state"].as_str() {- Some("on") => {- for (index, client) in capture["clients"]- .as_array()- .into_iter()- .flatten()- .enumerate()- {- let label = if index == 0 { "Capture" } else { "" };- line(format!(- " {label:<13} {:<15} {}: {}",- client["name"].as_str().unwrap_or_default(),- client["state"].as_str().unwrap_or_default(),- show(&client["file"])- ));- }- line(" Finished turns become project sources; reviewed memory reaches the agent at session start (--no-capture skips this)".into());- if capture["clients"]- .as_array()- .into_iter()- .flatten()- .any(|client| client["client"] == "codex" && client["state"] == "added")- {- line(" Codex asks you to review and trust the new hooks before they run".into());- }+ // A client's hooks: their state and file, and why a file that could not+ // be written was skipped.+ let hooks_detail = |hooks: &Value| -> String {+ let detail = format!(+ "{}: {}",+ hooks["state"].as_str().unwrap_or_default(),+ show(&hooks["file"])+ );+ match hooks["reason"].as_str() {+ Some(reason) => format!("{detail}: {reason}"),+ None => detail,}- _ => line(format!(+ };+ let capture = &report["capture"];+ let hooked = capture["clients"].as_array().cloned().unwrap_or_default();+ if hooked.is_empty() {+ line(format!(" Capture off: {}",capture["reason"].as_str().unwrap_or_default()- )),+ ));+ }+ for (index, client) in hooked.iter().enumerate() {+ let label = if index == 0 { "Capture" } else { "" };+ line(format!(+ " {label:<13} {:<15} {}",+ client["name"].as_str().unwrap_or_default(),+ hooks_detail(client)+ ));+ if let Some(by_hand) = client["by_hand"].as_str() {+ line(format!(" {by_hand}"));+ }+ }+ if capture["state"] == "on" {+ line(" Finished turns become project sources; reviewed memory reaches the agent at session start (--no-capture skips this)".into());+ if hooked+ .iter()+ .any(|client| client["client"] == "codex" && client["state"] == "added")+ {+ line(+ " Codex asks you to review and trust the new hooks before they run"+ .into(),+ );+ }}// Claude Code's guard hooks.let guarded: Vec<&Value> = clients@@ -1391,16 +1531,23 @@ pub fn render_setup(report: &Value) -> String {for (index, client) in guarded.iter().enumerate() {let label = if index == 0 { "Graph guard" } else { "" };line(format!(- " {label:<13} {:<15} {}: {}",+ " {label:<13} {:<15} {}",client["name"].as_str().unwrap_or_default(),- client["guard"]["state"].as_str().unwrap_or_default(),- show(&client["guard"]["file"])+ hooks_detail(&client["guard"])));+ // The capture hooks' file and command are the same: given once.+ if let Some(by_hand) = client["guard"]["by_hand"].as_str()+ && client["capture"]["by_hand"].as_str() != Some(by_hand)+ {+ line(format!(" {by_hand}"));+ }}- if guarded- .iter()- .any(|client| client["guard"]["state"] != "removed")- {+ if guarded.iter().any(|client| {+ !matches!(+ client["guard"]["state"].as_str(),+ Some("removed" | "skipped")+ )+ }) {line(" Before a search or a source read here, Claude Code is pointed to the graph tools".into());}if guarded@@ -1470,20 +1617,32 @@ pub fn render_setup(report: &Value) -> String {show(&git["directory"])));for hook in hooks {- if let Some(text) = hook["reason"].as_str().or(hook["note"].as_str()) {- line(format!(" {text}"));+ if let Some(reason) = hook["reason"].as_str() {+ line(format!(" {}: {reason}", show(&hook["file"])));+ } else if let Some(note) = hook["note"].as_str() {+ line(format!(" {note}"));}}}- None => {- line(format!(- " Git hooks skipped: {}",- git["reason"].as_str().unwrap_or_default()- ));- if let Some(by_hand) = git["by_hand"].as_str() {- line(format!(" {by_hand}"));- }- }+ None => line(format!(+ " Git hooks skipped: {}",+ git["reason"].as_str().unwrap_or_default()+ )),+ }+ if let Some(by_hand) = git["by_hand"].as_str() {+ line(format!(" {by_hand}"));+ }+ // An exclude file a read-only `.git` kept as it was.+ for exclude in report["git_exclude"].as_array().into_iter().flatten() {+ line(format!(+ " Git exclude skipped: {}: {}",+ show(&exclude["file"]),+ exclude["reason"].as_str().unwrap_or_default()+ ));+ line(format!(+ " {}",+ exclude["by_hand"].as_str().unwrap_or_default()+ ));}let graphify = &report["graphify"];if !graphify.is_null() {@@ -1495,6 +1654,11 @@ pub fn render_setup(report: &Value) -> String {line(format!(" {next}"));}}+ for item in graphify["changed"].as_array().into_iter().flatten() {+ if let Some(reason) = item["reason"].as_str() {+ line(format!(" {}: {reason}", show(&item["file"])));+ }+ }for command in graphify["by_hand"].as_array().into_iter().flatten() {line(format!(" Claude Code's own graphify server is in ~/.claude.json, which setup does not edit: run {}",@@ -1572,7 +1736,25 @@ pub fn render_setup(report: &Value) -> String {.as_array().cloned().unwrap_or_default();- if files.is_empty() {+ // Not "already set" when a client failed or a file could not be written.+ let not_writable = |list: &Value| {+ list.as_array().into_iter().flatten().any(|item| {+ item["reason"]+ .as_str()+ .is_some_and(|reason| reason.starts_with("not writable"))+ })+ };+ let undone = clients.iter().any(|client| {+ client["state"] == "failed"+ || client["capture"]["state"] == "skipped"+ || client["guard"]["state"] == "skipped"+ }) || git["by_hand"].is_string()+ || report["git_exclude"].is_array()+ || not_writable(&report["instructions"])+ || not_writable(&report["graphify"]["changed"]);+ if files.is_empty() && undone {+ line("Nothing changed outside the data folder.".into());+ } else if files.is_empty() {line("Nothing changed outside the data folder: everything was already set.".into());} else {line("Files changed outside the data folder (a file that existed is backed up once as <file>.graphicle-bak; graphicle disconnect undoes them):".into());@@ -1652,6 +1834,7 @@ pub fn connect_found(store: &Store, options: &ConnectFound) -> Result<()> {agent_setup::Policy {refresh_ours: true,drop_guards: true,+ ..Default::default()},) {Ok(result) => connected.push(result),diff --git a/crates/graphicle/src/spend.rs b/crates/graphicle/src/spend.rsnew file mode 100644index 0000000..50bc38c--- /dev/null+++ b/crates/graphicle/src/spend.rs@@ -0,0 +1,1002 @@+//! The spend log and caps of long-context model calls (`ask --pack`, `plan`,+//! `fix`).+//!+//! Every call appends one JSON line to `usage.jsonl` in Graphicle's data+//! folder: when, which command, profile, provider and model, the project and+//! commit, the prompt cache key, the provider's input, cached, output and+//! reasoning tokens, the seconds, the cost at the profile's configured price+//! (null without one), the call's worst case at that price, and the status.+//! Never the prompt or the answer. `graphicle usage` adds it up by day and+//! model.+//!+//! A profile's `max_cost_per_call` and `max_cost_per_day` (US dollars at its+//! configured price) refuse a call before it is sent. Under the log's lock, a+//! call checks its worst case against both caps and, with a day cap,+//! reserves that worst case in `usage-pending.json` until it is logged, so+//! calls made at the same time count against each other. A logged call counts+//! at its cost, or at its worst case when the provider reported no usage. A+//! reservation counts whatever its day while its process runs, until+//! [`RESERVATION_LIFETIME`] after it was made; one whose process is gone, or+//! older than that, is dropped. `graphicle usage` shows the reservations and+//! `--clear-pending` removes them. A log that cannot be read refuses capped+//! calls; a line that is not a JSON object is skipped, and `graphicle usage`+//! lists it.++use crate::model::{Completion, Profile};+use crate::{Error, Result};+use chrono::{DateTime, NaiveDate, SecondsFormat, Utc};+use serde_json::{Value, json};+use std::collections::BTreeMap;+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Duration;++/// The log's file in the data folder.+pub const LOG_FILE: &str = "usage.jsonl";+/// The lock every reader that decides and every writer holds.+const LOCK_FILE: &str = "usage.lock";+/// The worst cases of capped calls not yet logged.+const PENDING_FILE: &str = "usage-pending.json";+/// A worst case adds a tenth to an estimated input.+const WORST_MARGIN_PARTS: u64 = 10;++/// The log of the data folder `directory`.+pub fn log_path(directory: &Path) -> PathBuf {+ directory.join(LOG_FILE)+}++/// One model call, as the log records it.+pub struct Call<'a> {+ pub command: &'a str,+ /// The profile's name in the configuration.+ pub profile: &'a str,+ pub settings: &'a Profile,+ pub project: Option<&'a str>,+ pub commit: Option<&'a str>,+ pub prompt_cache_key: Option<&'a str>,+}++/// The provider a profile calls: its address's host (and port).+fn provider(p: &Profile) -> String {+ url::Url::parse(&p.base_url)+ .ok()+ .and_then(|url| {+ url.host_str().map(|host| match url.port() {+ Some(port) => format!("{host}:{port}"),+ None => host.to_string(),+ })+ })+ .unwrap_or_else(|| p.protocol.clone())+}++/// The log line of `call` with its result: the provider's usage of a+/// finished call, or what a failed one reported. [`settle`] adds the call's+/// worst case.+pub fn entry(call: &Call<'_>, result: &Result<Completion>, now: DateTime<Utc>) -> Value {+ let (status, model, input, cached, output, reasoning, seconds) = match result {+ Ok(done) => (+ "ok".to_string(),+ done.model.clone(),+ done.input_tokens,+ done.cached_tokens,+ done.output_tokens,+ done.reasoning_tokens,+ Some(done.elapsed_ms as f64 / 1000.0),+ ),+ Err(error) => match &error.provider_failure {+ Some(failure) => (+ failure.reason.clone(),+ failure.model.clone(),+ failure.input_tokens,+ None,+ failure.output_tokens,+ None,+ Some(failure.elapsed_ms as f64 / 1000.0),+ ),+ None => ("error".into(), String::new(), None, None, None, None, None),+ },+ };+ let model = if model.is_empty() {+ call.settings.model.clone()+ } else {+ model+ };+ let cost = match (&call.settings.price, input, output) {+ (Some(price), Some(input), Some(output)) => {+ Some(price.cost(input, cached.unwrap_or(0), output))+ }+ _ => None,+ };+ json!({+ "time": now.to_rfc3339_opts(SecondsFormat::Secs, true),+ "command": call.command,+ "profile": call.profile,+ "provider": provider(call.settings),+ "model": model,+ "project": call.project,+ "commit": call.commit,+ "prompt_cache_key": call.prompt_cache_key,+ "input_tokens": input,+ "cached_tokens": cached,+ "output_tokens": output,+ "reasoning_tokens": reasoning,+ "seconds": seconds.map(|s| (s * 1000.0).round() / 1000.0),+ "cost_usd": cost,+ "worst_cost_usd": Value::Null,+ "status": status,+ })+}++/// The log's lock, held until the returned file is dropped.+fn lock(directory: &Path) -> Result<std::fs::File> {+ std::fs::create_dir_all(directory)?;+ let file = std::fs::OpenOptions::new()+ .create(true)+ .truncate(false)+ .read(true)+ .write(true)+ .open(directory.join(LOCK_FILE))+ .map_err(|e| Error::bad(format!("Cannot open the spend log's lock: {e}")))?;+ file.lock()+ .map_err(|e| Error::bad(format!("Cannot lock the spend log: {e}")))?;+ Ok(file)+}++/// Append `entry` to the log of `directory`, the lock held.+fn append_locked(directory: &Path, entry: &Value) -> Result<()> {+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(log_path(directory))?;+ let mut line = serde_json::to_string(entry)?;+ line.push('\n');+ file.write_all(line.as_bytes())?;+ Ok(())+}++/// Append `entry` to the log of `directory`.+pub fn append(directory: &Path, entry: &Value) -> Result<()> {+ let _lock = lock(directory)?;+ append_locked(directory, entry)+}++/// The log as read: its entries in order, and the numbers (from 1) of the+/// lines that are not JSON objects, which are skipped.+#[derive(Debug, Default)]+pub struct Log {+ pub entries: Vec<Value>,+ pub skipped: Vec<usize>,+}++/// The log of `directory`: empty when there is none yet, an error when it+/// cannot be read.+pub fn read(directory: &Path) -> Result<Log> {+ let path = log_path(directory);+ let bytes = match std::fs::read(&path) {+ Ok(bytes) => bytes,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Log::default()),+ Err(error) => {+ return Err(Error::bad(format!(+ "Cannot read the spend log {}: {error}",+ path.display()+ )));+ }+ };+ let mut log = Log::default();+ for (i, line) in String::from_utf8_lossy(&bytes).lines().enumerate() {+ if line.trim().is_empty() {+ continue;+ }+ match serde_json::from_str::<Value>(line) {+ Ok(value) if value.is_object() => log.entries.push(value),+ _ => log.skipped.push(i + 1),+ }+ }+ Ok(log)+}++/// How long a reservation counts at most: the longest a model call may take,+/// and a margin.+pub const RESERVATION_LIFETIME: Duration =+ Duration::from_secs(crate::model::LONG_TIMEOUT.as_secs() + 600);++/// Whether the process `pid` still runs (where that can be told; elsewhere,+/// only the lifetime ends a reservation).+fn running(pid: u64) -> bool {+ pid == u64::from(std::process::id()) || exists(pid)+}++#[cfg(unix)]+fn exists(pid: u64) -> bool {+ let Ok(pid) = libc::pid_t::try_from(pid) else {+ return false;+ };+ // SAFETY: signal 0 sends nothing; it only checks that the process exists.+ let sent = unsafe { libc::kill(pid, 0) } == 0;+ sent || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)+}++#[cfg(not(unix))]+fn exists(_: u64) -> bool {+ true+}++/// Whether a reservation still counts at `now`: made less than+/// [`RESERVATION_LIFETIME`] ago, by a process that still runs.+fn live(reservation: &Value, now: DateTime<Utc>) -> bool {+ let made = reservation["time"]+ .as_str()+ .and_then(|t| DateTime::parse_from_rfc3339(t).ok())+ .map(|t| t.with_timezone(&Utc));+ let fresh = match made {+ Some(made) => match now.signed_duration_since(made).to_std() {+ Ok(age) => age < RESERVATION_LIFETIME,+ // Made later than now (a clock set back): it still counts.+ Err(_) => true,+ },+ None => false,+ };+ fresh && reservation["pid"].as_u64().is_some_and(running)+}++/// The reservations not yet settled, by id.+fn read_pending(directory: &Path) -> Result<BTreeMap<String, Value>> {+ let path = directory.join(PENDING_FILE);+ match std::fs::read(&path) {+ Ok(bytes) => serde_json::from_slice(&bytes).map_err(|_| {+ Error::bad(format!(+ "The spend log's reservations ({}) cannot be read; remove the file when no call is running",+ path.display()+ ))+ }),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeMap::new()),+ Err(error) => Err(Error::bad(format!(+ "Cannot read the spend log's reservations {}: {error}",+ path.display()+ ))),+ }+}++/// Replace the reservations, through a temporary file.+fn write_pending(directory: &Path, pending: &BTreeMap<String, Value>) -> Result<()> {+ let path = directory.join(PENDING_FILE);+ let temporary = directory.join(format!("{PENDING_FILE}.{}", std::process::id()));+ std::fs::write(&temporary, serde_json::to_vec(pending)?)?;+ std::fs::rename(&temporary, &path)?;+ Ok(())+}++/// The UTC day of an entry's time, `YYYY-MM-DD`.+fn day_of(entry: &Value) -> Option<String> {+ let time = DateTime::parse_from_rfc3339(entry["time"].as_str()?).ok()?;+ Some(time.with_timezone(&Utc).format("%Y-%m-%d").to_string())+}++/// What a logged call counts against a day cap: its cost, or its worst case+/// when the provider reported no usage.+fn charged(entry: &Value) -> f64 {+ entry["cost_usd"]+ .as_f64()+ .or_else(|| entry["worst_cost_usd"].as_f64())+ .unwrap_or(0.0)+}++/// US dollars as a person reads them: cents, or four decimals below a cent.+pub fn usd(amount: f64) -> String {+ if amount >= 0.01 || amount == 0.0 {+ format!("${amount:.2}")+ } else {+ format!("${amount:.4}")+ }+}++/// A count with thousands separators.+fn count(n: u64) -> String {+ crate::terminal::count(n)+}++/// The input tokens a call's worst case counts: the provider's exact count,+/// else the estimate, times the profile's calibration ratio when the+/// provider counts more than the estimate, plus a tenth.+pub fn worst_input(estimate: u64, counted: Option<u64>, ratio: Option<f64>) -> u64 {+ match counted {+ Some(counted) => counted,+ None => {+ let ratio = ratio.filter(|r| r.is_finite() && *r > 1.0);+ let scaled = match ratio {+ Some(ratio) => ((estimate as f64) * ratio).ceil() as u64,+ None => estimate,+ };+ scaled + scaled.div_ceil(WORST_MARGIN_PARTS)+ }+ }+}++/// A call's hold on the caps: its worst case at the configured price, and+/// the reservation that counts it against the day cap until it is logged.+#[derive(Debug)]+pub struct Reservation {+ id: Option<String>,+ pub worst: Option<f64>,+}++static RESERVATIONS: AtomicU64 = AtomicU64::new(0);++/// Check a call of profile `name` against its caps before it is sent, and+/// reserve its worst case (`input` tokens, none cached, and the output limit)+/// against the day cap. Refused when the worst case is over+/// `max_cost_per_call`, or when the day's logged and reserved cost of the+/// profile (UTC) and this worst case together pass `max_cost_per_day`.+pub fn reserve(+ directory: &Path,+ name: &str,+ p: &Profile,+ input: u64,+ now: DateTime<Utc>,+) -> Result<Reservation> {+ let Some(price) = &p.price else {+ return Ok(Reservation {+ id: None,+ worst: None,+ });+ };+ let output = p.output_limit as u64;+ let worst = price.cost(input, 0, output);+ if let Some(cap) = p.max_cost_per_call+ && worst > cap+ {+ return Err(Error::bad(format!(+ "Refused before sending: this call could cost up to {} at the configured price ({} input tokens, none cached, and {} output tokens at most), over max_cost_per_call of {} (the setting models.{name}.max_cost_per_call)",+ usd(worst),+ count(input),+ count(output),+ usd(cap)+ )));+ }+ let Some(cap) = p.max_cost_per_day else {+ return Ok(Reservation {+ id: None,+ worst: Some(worst),+ });+ };+ let _lock = lock(directory)?;+ let today = now.format("%Y-%m-%d").to_string();+ let log = read(directory)?;+ // Reservations of calls cut off or long gone are dropped; the others+ // count, whatever their day.+ let mut pending = read_pending(directory)?;+ pending.retain(|_, r| live(r, now));+ let logged: f64 = log+ .entries+ .iter()+ .filter(|e| e["profile"] == name && day_of(e).as_deref() == Some(today.as_str()))+ .map(charged)+ .sum();+ let reserved: f64 = pending+ .values()+ .filter(|r| r["profile"] == name)+ .filter_map(|r| r["worst_cost_usd"].as_f64())+ .sum();+ if logged + reserved + worst > cap {+ return Err(Error::bad(format!(+ "Refused before sending: the calls of {name} today (UTC) come to {} at the configured price{}, and this call could add up to {}, over max_cost_per_day of {} (the setting models.{name}.max_cost_per_day)",+ usd(logged + reserved),+ if reserved > 0.0 {+ format!(" ({} of it for calls not logged yet)", usd(reserved))+ } else {+ String::new()+ },+ usd(worst),+ usd(cap)+ )));+ }+ let id = format!(+ "{}-{}-{}",+ std::process::id(),+ now.timestamp_nanos_opt().unwrap_or(0),+ RESERVATIONS.fetch_add(1, Ordering::Relaxed)+ );+ pending.insert(+ id.clone(),+ json!({"profile":name,"day":today,"worst_cost_usd":worst,"pid":std::process::id(),+ "time":now.to_rfc3339_opts(SecondsFormat::Secs, true)}),+ );+ write_pending(directory, &pending)?;+ Ok(Reservation {+ id: Some(id),+ worst: Some(worst),+ })+}++/// Log a call: its entry, with its worst case, goes into the log, and its+/// reservation is released, under one hold of the lock.+pub fn settle(directory: &Path, reservation: &Reservation, entry: &mut Value) -> Result<()> {+ entry["worst_cost_usd"] = json!(reservation.worst);+ let _lock = lock(directory)?;+ append_locked(directory, entry)?;+ if let Some(id) = &reservation.id {+ let mut pending = read_pending(directory)?;+ if pending.remove(id).is_some() {+ write_pending(directory, &pending)?;+ }+ }+ Ok(())+}++/// The reservations that still count at `now`, oldest first. The file is+/// replaced whole, so it is read without the lock (and nothing is created).+pub fn pending(directory: &Path, now: DateTime<Utc>) -> Result<Vec<Value>> {+ let mut held: Vec<Value> = read_pending(directory)?+ .into_values()+ .filter(|r| live(r, now))+ .collect();+ held.sort_by(|a, b| a["time"].as_str().cmp(&b["time"].as_str()));+ Ok(held)+}++/// Remove every reservation, even from a file that cannot be read, and say+/// how many could be read.+pub fn clear_pending(directory: &Path) -> Result<usize> {+ let path = directory.join(PENDING_FILE);+ if !path.exists() {+ return Ok(0);+ }+ let _lock = lock(directory)?;+ let removed = read_pending(directory).map_or(0, |pending| pending.len());+ match std::fs::remove_file(&path) {+ Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(Error::bad(format!(+ "Cannot remove the spend log's reservations {}: {error}",+ path.display()+ ))),+ _ => Ok(removed),+ }+}++/// The calls since `since` (a day `YYYY-MM-DD` or an RFC 3339 time), added+/// up by day and model, and in all, with the log lines that were skipped.+pub fn report(log: &Log, since: Option<&str>) -> Result<Value> {+ let since: Option<DateTime<Utc>> = match since {+ None => None,+ Some(text) => Some(+ DateTime::parse_from_rfc3339(text)+ .map(|t| t.with_timezone(&Utc))+ .or_else(|_| {+ NaiveDate::parse_from_str(text, "%Y-%m-%d")+ .map(|d| d.and_hms_opt(0, 0, 0).unwrap().and_utc())+ })+ .map_err(|_| {+ Error::bad("--since takes a day (2026-10-26) or a time (2026-10-26T12:00:00Z)")+ })?,+ ),+ };+ #[derive(Default)]+ struct Sum {+ calls: u64,+ input: u64,+ cached: u64,+ output: u64,+ reasoning: u64,+ cost: f64,+ unpriced: u64,+ failed: u64,+ }+ impl Sum {+ fn add(&mut self, e: &Value) {+ self.calls += 1;+ self.input += e["input_tokens"].as_u64().unwrap_or(0);+ self.cached += e["cached_tokens"].as_u64().unwrap_or(0);+ self.output += e["output_tokens"].as_u64().unwrap_or(0);+ self.reasoning += e["reasoning_tokens"].as_u64().unwrap_or(0);+ match e["cost_usd"].as_f64() {+ Some(cost) => self.cost += cost,+ None => self.unpriced += 1,+ }+ if e["status"] != "ok" {+ self.failed += 1;+ }+ }+ fn json(&self) -> Value {+ let share = if self.input == 0 {+ 0.0+ } else {+ (self.cached as f64 / self.input as f64 * 1000.0).round() / 1000.0+ };+ json!({"calls":self.calls,"input_tokens":self.input,"cached_tokens":self.cached,+ "cached_share":share,"output_tokens":self.output,"reasoning_tokens":self.reasoning,+ "cost_usd":(self.cost * 1_000_000.0).round() / 1_000_000.0,+ "unpriced_calls":self.unpriced,"failed_calls":self.failed})+ }+ }+ let mut by_day: BTreeMap<(String, String), Sum> = BTreeMap::new();+ let mut total = Sum::default();+ for e in &log.entries {+ let Some(time) = e["time"]+ .as_str()+ .and_then(|t| DateTime::parse_from_rfc3339(t).ok())+ else {+ continue;+ };+ if since.is_some_and(|since| time.with_timezone(&Utc) < since) {+ continue;+ }+ let day = time.with_timezone(&Utc).format("%Y-%m-%d").to_string();+ let model = e["model"].as_str().unwrap_or("").to_string();+ by_day.entry((day, model)).or_default().add(e);+ total.add(e);+ }+ let days: Vec<Value> = by_day+ .iter()+ .map(|((day, model), sum)| {+ let mut row = sum.json();+ row["day"] = json!(day);+ row["model"] = json!(model);+ row+ })+ .collect();+ Ok(json!({"days":days,"total":total.json(),"skipped_lines":log.skipped}))+}++/// The report's lines about calls not logged yet (its `pending`).+fn pending_text(report: &Value) -> String {+ let pending = report["pending"].as_array().cloned().unwrap_or_default();+ if pending.is_empty() {+ return String::new();+ }+ let worst: f64 = pending+ .iter()+ .filter_map(|r| r["worst_cost_usd"].as_f64())+ .sum();+ let mut text = format!(+ "Calls not logged yet: {}, held against the day caps at up to {} in all:\n",+ pending.len(),+ usd(worst)+ );+ for r in &pending {+ text.push_str(&format!(+ " {} since {} (process {}), up to {}\n",+ r["profile"].as_str().unwrap_or(""),+ r["time"].as_str().unwrap_or(""),+ r["pid"],+ usd(r["worst_cost_usd"].as_f64().unwrap_or(0.0))+ ));+ }+ text.push_str(&format!(+ "A reservation ends when its call is logged, its process ends, or {} minutes pass; graphicle usage --clear-pending removes them now.\n",+ RESERVATION_LIFETIME.as_secs() / 60+ ));+ text+}++/// The report as a table.+pub fn report_text(report: &Value, log: &Path) -> String {+ let skipped: Vec<String> = report["skipped_lines"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|n| n.to_string())+ .collect();+ let skipped = if skipped.is_empty() {+ String::new()+ } else {+ format!(+ "Skipped {} that {} not a JSON object: line {}.\n",+ if skipped.len() == 1 {+ "1 line".to_string()+ } else {+ format!("{} lines", skipped.len())+ },+ if skipped.len() == 1 { "is" } else { "are" },+ skipped.join(", ")+ )+ };+ let skipped = format!("{skipped}{}", pending_text(report));+ let rows = report["days"].as_array().cloned().unwrap_or_default();+ if rows.is_empty() {+ return format!(+ "No model calls in {} for that time. `ask --pack`, `plan` and `fix` log one line per call.\n{skipped}",+ log.display()+ );+ }+ let cached = |row: &Value| {+ format!(+ "{} ({:.0}%)",+ count(row["cached_tokens"].as_u64().unwrap_or(0)),+ row["cached_share"].as_f64().unwrap_or(0.0) * 100.0+ )+ };+ let cost = |row: &Value| {+ let mut text = usd(row["cost_usd"].as_f64().unwrap_or(0.0));+ let unpriced = row["unpriced_calls"].as_u64().unwrap_or(0);+ if unpriced > 0 {+ text.push_str(&format!(" (+{unpriced} without a cost)"));+ }+ text+ };+ let mut table: Vec<[String; 7]> = vec![[+ "day".into(),+ "model".into(),+ "calls".into(),+ "tokens in".into(),+ "cached".into(),+ "out".into(),+ "cost".into(),+ ]];+ for row in &rows {+ table.push([+ row["day"].as_str().unwrap_or("").into(),+ row["model"].as_str().unwrap_or("").into(),+ count(row["calls"].as_u64().unwrap_or(0)),+ count(row["input_tokens"].as_u64().unwrap_or(0)),+ cached(row),+ count(row["output_tokens"].as_u64().unwrap_or(0)),+ cost(row),+ ]);+ }+ let total = &report["total"];+ table.push([+ "total".into(),+ String::new(),+ count(total["calls"].as_u64().unwrap_or(0)),+ count(total["input_tokens"].as_u64().unwrap_or(0)),+ cached(total),+ count(total["output_tokens"].as_u64().unwrap_or(0)),+ cost(total),+ ]);+ let mut widths = [0usize; 7];+ for row in &table {+ for (i, cell) in row.iter().enumerate() {+ widths[i] = widths[i].max(cell.chars().count());+ }+ }+ let mut out = String::new();+ for row in &table {+ let mut line = String::new();+ for (i, cell) in row.iter().enumerate() {+ let pad = widths[i] - cell.chars().count();+ if i < 2 {+ line.push_str(cell);+ line.push_str(&" ".repeat(pad));+ } else {+ line.push_str(&" ".repeat(pad));+ line.push_str(cell);+ }+ line.push_str(" ");+ }+ out.push_str(line.trim_end());+ out.push('\n');+ }+ out.push_str(&format!(+ "Costs are at each profile's configured price when the call was made. Log: {}\n{skipped}",+ log.display()+ ));+ out+}++/// The line after an answer: tokens in (cached, share), out, and the cost+/// at the configured price.+pub fn line(usage: &Value) -> String {+ let n = |key: &str| usage[key].as_u64();+ let mut line = match n("input_tokens") {+ Some(input) => format!("{} tokens in", count(input)),+ None => "tokens in unreported".to_string(),+ };+ if let (Some(input), Some(cached)) = (n("input_tokens"), n("cached_tokens"))+ && cached > 0+ {+ let share = if input == 0 {+ 0.0+ } else {+ cached as f64 * 100.0 / input as f64+ };+ line.push_str(&format!(" ({} cached, {share:.0}%)", count(cached)));+ }+ match n("output_tokens") {+ Some(output) => line.push_str(&format!(", {} out", count(output))),+ None => line.push_str(", out unreported"),+ }+ if let Some(reasoning) = n("reasoning_tokens").filter(|&r| r > 0) {+ line.push_str(&format!(" ({} reasoning)", count(reasoning)));+ }+ if let Some(cost) = usage["cost_usd"].as_f64() {+ line.push_str(&format!("; {} at the configured price", usd(cost)));+ }+ line.push_str(&format!(+ "; {:.1} s.",+ usage["seconds"].as_f64().unwrap_or(0.0)+ ));+ line+}++#[cfg(test)]+mod tests {+ use super::*;++ fn profile(price: Value, caps: Value) -> Profile {+ let mut value = json!({"protocol":"responses","base_url":"https://api.meta.ai/v1",+ "model":"muse-spark-1.3","input_limit":1_016_576,"output_limit":32_000});+ if !price.is_null() {+ value["price"] = price;+ }+ for (k, v) in caps.as_object().unwrap() {+ value[k] = v.clone();+ }+ serde_json::from_value(value).unwrap()+ }++ fn price() -> Value {+ json!({"input":1.25,"output":4.25,"cached_input":0.15})+ }++ fn done(input: u64, cached: u64, output: u64) -> Result<Completion> {+ Ok(Completion {+ text: "an answer that is never logged".into(),+ input_tokens: Some(input),+ output_tokens: Some(output),+ cached_tokens: Some(cached),+ reasoning_tokens: Some(output / 2),+ elapsed_ms: 1_500,+ model: "muse-spark-1.3".into(),+ })+ }++ fn at(time: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(time)+ .unwrap()+ .with_timezone(&Utc)+ }++ fn call<'a>(p: &'a Profile) -> Call<'a> {+ Call {+ command: "ask --pack",+ profile: "meta",+ settings: p,+ project: Some("demo"),+ commit: Some("0123456789abcdef"),+ prompt_cache_key: Some("graphicle:demo@0123456789ab:e3b0c44298fc"),+ }+ }++ #[test]+ fn a_call_logs_its_tokens_cost_and_worst_case_but_no_text() {+ let dir = tempfile::tempdir().unwrap();+ let p = profile(price(), json!({}));+ let held = reserve(+ dir.path(),+ "meta",+ &p,+ 1_000_000,+ at("2026-10-26T17:00:00Z"),+ )+ .unwrap();+ let mut logged = entry(+ &call(&p),+ &done(1_000_000, 900_000, 2_000),+ at("2026-10-26T17:00:00Z"),+ );+ settle(dir.path(), &held, &mut logged).unwrap();+ let log = read(dir.path()).unwrap();+ assert_eq!(log.entries.len(), 1);+ let e = &log.entries[0];+ assert_eq!(e["time"], "2026-10-26T17:00:00Z");+ assert_eq!(e["provider"], "api.meta.ai");+ assert_eq!(e["cached_tokens"], 900_000);+ assert_eq!(e["status"], "ok");+ // 100,000 at $1.25, 900,000 at $0.15 and 2,000 at $4.25 a million.+ assert_eq!(e["cost_usd"], 0.2685);+ // The worst case: 1,000,000 uncached and 32,000 out.+ assert_eq!(e["worst_cost_usd"], 1.386);+ let text = std::fs::read_to_string(log_path(dir.path())).unwrap();+ assert!(!text.contains("never logged"));+ // Without a price, the cost is null.+ let free = profile(Value::Null, json!({}));+ assert!(+ entry(&call(&free), &done(10, 0, 5), at("2026-10-26T17:00:00Z"))["cost_usd"].is_null()+ );+ }++ #[test]+ fn the_per_call_cap_names_its_setting() {+ let dir = tempfile::tempdir().unwrap();+ let p = profile(price(), json!({"max_cost_per_call":1.0}));+ let refused = reserve(+ dir.path(),+ "meta",+ &p,+ 1_000_000,+ at("2026-10-26T10:00:00Z"),+ )+ .unwrap_err()+ .to_string();+ assert!(+ refused.contains("models.meta.max_cost_per_call"),+ "{refused}"+ );+ assert!(refused.contains("$1.39"), "{refused}");+ assert!(reserve(dir.path(), "meta", &p, 500_000, at("2026-10-26T10:00:00Z")).is_ok());+ }++ #[test]+ fn the_day_cap_counts_this_call_unknown_usage_and_calls_in_flight() {+ let dir = tempfile::tempdir().unwrap();+ // Each call's worst case: 100,000 x $1.25 + 32,000 x $4.25 a million,+ // $0.261.+ let p = profile(price(), json!({"max_cost_per_day":1.0}));+ let now = at("2026-10-26T09:00:00Z");+ // A call in flight counts at its worst case before it is logged.+ let first = reserve(dir.path(), "meta", &p, 100_000, now).unwrap();+ let second = reserve(dir.path(), "meta", &p, 100_000, now).unwrap();+ let third = reserve(dir.path(), "meta", &p, 100_000, now).unwrap();+ // The fourth would pass $1 with the three in flight ($0.783 + $0.261).+ let refused = reserve(dir.path(), "meta", &p, 100_000, now)+ .unwrap_err()+ .to_string();+ assert!(+ refused.contains("models.meta.max_cost_per_day"),+ "{refused}"+ );+ assert!(refused.contains("calls not logged yet"), "{refused}");+ // Settled: one at its cost, one with unknown usage at its worst case.+ let mut cheap = entry(&call(&p), &done(100_000, 90_000, 100), now);+ settle(dir.path(), &first, &mut cheap).unwrap();+ let unknown: Result<Completion> = Err(Error::bad("no usage"));+ let mut lost = entry(&call(&p), &unknown, now);+ settle(dir.path(), &second, &mut lost).unwrap();+ let log = read(dir.path()).unwrap();+ assert!(log.entries[1]["cost_usd"].is_null());+ assert_eq!(charged(&log.entries[1]), 0.261);+ // $0.027 + $0.261 logged, $0.261 still reserved: room for one more.+ let fourth = reserve(dir.path(), "meta", &p, 100_000, now).unwrap();+ assert!(reserve(dir.path(), "meta", &p, 100_000, now).is_err());+ // Another profile and another day do not count.+ assert!(reserve(dir.path(), "wonder", &p, 100_000, now).is_ok());+ assert!(reserve(dir.path(), "meta", &p, 100_000, at("2026-10-27T00:00:00Z")).is_ok());+ drop((third, fourth));+ }++ #[test]+ fn calls_at_the_same_time_cannot_pass_the_day_cap_together() {+ let dir = tempfile::tempdir().unwrap();+ let p = profile(price(), json!({"max_cost_per_day":1.0}));+ let now = at("2026-10-26T09:00:00Z");+ let granted: usize = std::thread::scope(|scope| {+ let threads: Vec<_> = (0..12)+ .map(|_| scope.spawn(|| reserve(dir.path(), "meta", &p, 100_000, now).is_ok()))+ .collect();+ threads+ .into_iter()+ .map(|t| usize::from(t.join().unwrap()))+ .sum()+ });+ // $0.261 each: three fit under $1.+ assert_eq!(granted, 3);+ }++ #[test]+ fn a_log_that_cannot_be_read_refuses_and_bad_lines_are_listed() {+ let dir = tempfile::tempdir().unwrap();+ let p = profile(price(), json!({"max_cost_per_day":5.0}));+ let now = at("2026-10-26T09:00:00Z");+ // One torn line among good ones: skipped, and listed.+ let good = entry(&call(&p), &done(1_000, 0, 10), now);+ std::fs::write(+ log_path(dir.path()),+ format!("{good}\n{{\"time\":\"2026-10-26T09:\n{good}\n"),+ )+ .unwrap();+ let log = read(dir.path()).unwrap();+ assert_eq!((log.entries.len(), log.skipped.clone()), (2, vec![2]));+ assert!(reserve(dir.path(), "meta", &p, 1_000, now).is_ok());+ let report = report(&log, None).unwrap();+ assert_eq!(report["skipped_lines"], json!([2]));+ let text = report_text(&report, Path::new("/data/usage.jsonl"));+ assert!(+ text.contains("Skipped 1 line that is not a JSON object: line 2."),+ "{text}"+ );+ // A log that cannot be read: capped calls are refused.+ let unreadable = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(log_path(unreadable.path())).unwrap();+ let refused = reserve(unreadable.path(), "meta", &p, 1_000, now)+ .unwrap_err()+ .to_string();+ assert!(refused.contains("Cannot read the spend log"), "{refused}");+ }++ #[test]+ fn the_worst_case_input_takes_the_calibration_and_a_margin() {+ assert_eq!(worst_input(100_000, Some(90_000), Some(2.0)), 90_000);+ assert_eq!(worst_input(100_000, None, None), 110_000);+ assert_eq!(worst_input(100_000, None, Some(0.9)), 110_000);+ assert_eq!(worst_input(100_000, None, Some(1.5)), 165_000);+ }++ #[test]+ fn the_report_adds_up_by_day_and_model() {+ let entries = vec![+ json!({"time":"2026-10-26T09:00:00Z","model":"muse-spark-1.3","input_tokens":1000,"cached_tokens":0,"output_tokens":10,"cost_usd":0.5,"status":"ok"}),+ json!({"time":"2026-10-26T10:00:00Z","model":"muse-spark-1.3","input_tokens":1000,"cached_tokens":900,"output_tokens":10,"cost_usd":0.25,"status":"ok"}),+ json!({"time":"2026-10-26T11:00:00Z","model":"muse-wonder-1.0","input_tokens":2000,"cached_tokens":1000,"output_tokens":20,"cost_usd":null,"status":"ok"}),+ json!({"time":"2026-10-27T01:00:00Z","model":"muse-spark-1.3","input_tokens":500,"output_tokens":5,"cost_usd":0.1,"status":"max_output_tokens"}),+ json!({"not":"an entry"}),+ ];+ let log = Log {+ entries,+ skipped: Vec::new(),+ };+ let all = report(&log, None).unwrap();+ assert_eq!(all["days"].as_array().unwrap().len(), 3);+ let first = &all["days"][0];+ assert_eq!(+ (first["day"].as_str(), first["model"].as_str()),+ (Some("2026-10-26"), Some("muse-spark-1.3"))+ );+ assert_eq!(first["calls"], 2);+ assert_eq!(first["cached_share"], 0.45);+ assert_eq!(first["cost_usd"], 0.75);+ assert_eq!(all["total"]["calls"], 4);+ assert_eq!(all["total"]["cost_usd"], 0.85);+ assert_eq!(all["total"]["unpriced_calls"], 1);+ assert_eq!(all["total"]["failed_calls"], 1);+ let since = report(&log, Some("2026-10-27")).unwrap();+ assert_eq!(since["total"]["calls"], 1);+ let since = report(&log, Some("2026-10-26T10:30:00Z")).unwrap();+ assert_eq!(since["total"]["calls"], 2);+ assert!(report(&log, Some("yesterday")).is_err());+ let text = report_text(&all, Path::new("/data/usage.jsonl"));+ assert!(text.contains("muse-wonder-1.0"), "{text}");+ assert!(text.contains("$0.85 (+1 without a cost)"), "{text}");+ }++ #[test]+ fn the_answer_line_shows_the_cached_share_and_cost() {+ let usage = json!({"input_tokens":1_012_345,"cached_tokens":936_000,"output_tokens":2_345,+ "reasoning_tokens":0,"seconds":41.3,"cost_usd":0.25});+ assert_eq!(+ line(&usage),+ "1,012,345 tokens in (936,000 cached, 92%), 2,345 out; $0.25 at the configured price; 41.3 s."+ );+ assert_eq!(usd(0.0042), "$0.0042");+ }+ /// Reservations of calls cut off or long gone are dropped; running ones+ /// count whatever their day; `pending` shows them and `clear_pending`+ /// removes them.+ #[cfg(unix)]+ #[test]+ fn stale_reservations_end_and_running_ones_count_past_midnight() {+ let dir = tempfile::tempdir().unwrap();+ let p = profile(price(), json!({"max_cost_per_day":1.0}));+ let now = at("2026-10-27T00:05:00Z");+ let mut ended = std::process::Command::new("true").spawn().unwrap();+ let ended_pid = ended.id();+ ended.wait().unwrap();+ let me = std::process::id();+ let stored = json!({+ "gone":{"profile":"meta","day":"2026-10-27","worst_cost_usd":0.5,"pid":ended_pid,+ "time":"2026-10-27T00:00:00Z"},+ "old":{"profile":"meta","day":"2026-10-26","worst_cost_usd":0.5,"pid":me,+ "time":"2026-10-26T22:00:00Z"},+ "running":{"profile":"meta","day":"2026-10-26","worst_cost_usd":0.6,"pid":me,+ "time":"2026-10-26T23:59:00Z"}});+ std::fs::write(dir.path().join(PENDING_FILE), stored.to_string()).unwrap();+ // The call reserved before midnight still counts ($0.6 + $0.261);+ // the ended and the old ones do not.+ let held = reserve(dir.path(), "meta", &p, 100_000, now).unwrap();+ let refused = reserve(dir.path(), "meta", &p, 100_000, now)+ .unwrap_err()+ .to_string();+ assert!(refused.contains("calls not logged yet"), "{refused}");+ let shown = pending(dir.path(), now).unwrap();+ assert_eq!(shown.len(), 2, "{shown:?}");+ assert!(shown.iter().all(|r| r["pid"] == me));+ let mut report = report(&Log::default(), None).unwrap();+ report["pending"] = json!(shown);+ let text = report_text(&report, Path::new("/data/usage.jsonl"));+ assert!(text.contains("Calls not logged yet: 2"), "{text}");+ assert!(text.contains("--clear-pending"), "{text}");+ drop(held);+ assert_eq!(clear_pending(dir.path()).unwrap(), 2);+ assert!(pending(dir.path(), now).unwrap().is_empty());+ assert!(reserve(dir.path(), "meta", &p, 100_000, now).is_ok());+ }+}diff --git a/crates/graphicle/src/terminal.rs b/crates/graphicle/src/terminal.rsindex e73eee6..89786b4 100644--- a/crates/graphicle/src/terminal.rs+++ b/crates/graphicle/src/terminal.rs@@ -1833,7 +1833,7 @@ pub fn repair_entry(store: &Store, check: &EntryCheck) -> Result<Value> {},crate::agent_setup::Policy {refresh_ours: true,- drop_guards: false,+ ..Default::default()},);}@@ -1862,7 +1862,7 @@ pub fn repair_entry(store: &Store, check: &EntryCheck) -> Result<Value> {},crate::agent_setup::Policy {refresh_ours: true,- drop_guards: false,+ ..Default::default()},);}@@ -2228,8 +2228,18 @@ pub const ANTHROPIC_MODEL: &str = "claude-opus-5-5";pub const OPENAI_MODEL: &str = "gpt-5-mini";/// The Ollama model `config set model ollama` chooses when none is pulled.pub const OLLAMA_MODEL: &str = "qwen3:4b";+/// The Muse Spark model `config set model meta` chooses (Meta Model API).+/// Never a `-contributor` model: that tier lets Meta train on the data.+pub const META_MODEL: &str = "muse-spark-1.3";+/// The Meta Model API's OpenAI-compatible address.+pub const META_BASE_URL: &str = "https://api.meta.ai/v1";+/// Muse Spark's context window holds the input and the output together.+pub const META_WINDOW: usize = 1_048_576;+/// The output limit of the `meta` profile: Muse Spark always reasons, and+/// its reasoning counts in the output.+pub const META_OUTPUT_LIMIT: usize = 32_000;/// The providers `config set model` knows.-pub const PROVIDERS: &[&str] = &["anthropic", "openai", "ollama"];+pub const PROVIDERS: &[&str] = &["anthropic", "openai", "ollama", "meta", "compatible"];/// An answer model `setup` can offer: what is configured in this/// environment, best first.@@ -2514,9 +2524,40 @@ pub fn model_profile_at(}profile}+ // Muse Spark or Muse Wonder through the Meta Model API: the Responses+ // API (where a prompt cache retention of 24 hours can be asked for),+ // the key in MODEL_API_KEY, reasoning effort medium ("none" is+ // refused).+ "meta" => {+ if model.is_some_and(|m| m.ends_with("-contributor")) {+ return Err(Error::bad(+ "A -contributor model lets Meta train on what you send; set it in the configuration file yourself if you mean to",+ ));+ }+ json!({"protocol":"responses","base_url":url.unwrap_or(META_BASE_URL),+ "model":model.unwrap_or(META_MODEL),"key_env":key_env.unwrap_or("MODEL_API_KEY"),+ "input_limit":META_WINDOW - META_OUTPUT_LIMIT,"output_limit":META_OUTPUT_LIMIT,+ "reasoning_effort":"medium"})+ }+ // Any OpenAI-compatible chat server: Muse Spark Open on vLLM or+ // SGLang, or a hosted endpoint.+ "compatible" => {+ let url = url.ok_or_else(|| {+ Error::bad("compatible needs --url, the server's OpenAI-compatible address (for example http://127.0.0.1:8000/v1)")+ })?;+ let model = model.ok_or_else(|| {+ Error::bad("compatible needs the served model's name: compatible:MODEL")+ })?;+ let mut profile = json!({"protocol":"chat","base_url":url,"model":model,+ "input_limit":128000,"output_limit":16000});+ if let Some(key) = key_env {+ profile["key_env"] = json!(key);+ }+ profile+ }_ => {return Err(Error::bad(format!(- "Unknown model provider {provider:?}: choose anthropic, openai or ollama, optionally with a model (anthropic:MODEL, ollama:llama3.2)"+ "Unknown model provider {provider:?}: choose anthropic, openai, ollama, meta or compatible, optionally with a model (anthropic:MODEL, ollama:llama3.2)")));}})@@ -2649,7 +2690,7 @@ pub fn set_answer_model(.map_or((spec, None), |(provider, model)| (provider, Some(model)));if !PROVIDERS.contains(&provider) {return Err(Error::bad(format!(- "Unknown model provider {provider:?}: choose anthropic, openai or ollama, optionally with a model (ollama:llama3.2), or none"+ "Unknown model provider {provider:?}: choose anthropic, openai, ollama, meta or compatible, optionally with a model (ollama:llama3.2), or none")));}let profile = model_profile(provider, model.or(named), key_env, url)?;@@ -2926,7 +2967,7 @@ pub fn config_show_text(value: &Value, style: Style) -> String {);}out.push_str(- "\nChange the answer model: graphicle config set model anthropic|openai|ollama[:MODEL]\n",+ "\nChange the answer model: graphicle config set model anthropic|openai|ollama|meta[:MODEL]\n",);out.push_str("Change a setting: graphicle config set KEY VALUE (graphicle config example lists them)");out@@ -2947,8 +2988,10 @@ pub enum ConfigAction {/// such as `models.anthropic.model`.Get { key: String },/// Change one setting. `model VALUE` sets the answer model: anthropic,- /// openai or ollama, optionally with a model (`ollama:llama3.2`), or- /// none. Other keys are dotted paths in the file; VALUE is JSON or text.+ /// openai, ollama, meta (Muse Spark; meta:muse-wonder-1.0 for Muse+ /// Wonder) or compatible (with --url),+ /// optionally with a model (`ollama:llama3.2`), or none. Other keys are+ /// dotted paths in the file; VALUE is JSON or text.Set {key: String,value: String,@@ -3578,7 +3621,7 @@ pub fn job_failure(job: &Value, model: Option<&ModelState>) -> String {format!("The evidence for this question does not fit the model's input limit ({} tokens). Raise it with `graphicle config set models.{profile}.input_limit {}`, or ask a narrower question.",count(limit as u64),- (limit * 2).min(128_000)+ (limit * 2).min(crate::model::MAX_INPUT_LIMIT))} else if error.contains("max_output_tokens") {let (limit, profile) = model.map_or((2048, "NAME".to_string()), |m| {@@ -5718,8 +5761,40 @@ args = ["-y", "thing"]assert_eq!(ollama["protocol"], "ollama");assert!(ollama.get("key_env").is_none());assert!(model_profile("gemini", None, None, None).is_err());+ // Muse Spark through the Meta Model API, never a -contributor model.+ let meta = model_profile("meta", None, None, None).unwrap();+ assert_eq!(meta["protocol"], "responses");+ assert_eq!(meta["base_url"], "https://api.meta.ai/v1");+ assert_eq!(meta["model"], META_MODEL);+ assert_eq!(meta["key_env"], "MODEL_API_KEY");+ assert_eq!(meta["input_limit"], META_WINDOW - META_OUTPUT_LIMIT);+ assert_eq!(meta["reasoning_effort"], "medium");+ assert!(meta.get("extra_body").is_none());+ assert!(meta.get("price").is_none());+ assert!(model_profile("meta", Some("muse-spark-1.2-contributor"), None, None).is_err());+ assert!(model_profile("meta", Some("muse-spark-1.3-contributor"), None, None).is_err());+ assert_eq!(+ model_profile("meta", Some("muse-spark-1.2"), None, None).unwrap()["model"],+ "muse-spark-1.2"+ );+ assert_eq!(+ model_profile("meta", Some("muse-wonder-1.0"), None, None).unwrap()["model"],+ "muse-wonder-1.0"+ );+ // Any OpenAI-compatible server, by its address and model.+ assert!(model_profile("compatible", Some("m"), None, None).is_err());+ assert!(model_profile("compatible", None, None, Some("http://127.0.0.1:8000/v1")).is_err());+ let compatible = model_profile(+ "compatible",+ Some("muse-spark-open"),+ None,+ Some("http://127.0.0.1:8000/v1"),+ )+ .unwrap();+ assert_eq!(compatible["protocol"], "chat");+ assert!(compatible.get("key_env").is_none());// Each profile is valid as Graphicle reads it.- for profile in [anthropic, openai, ollama] {+ for profile in [anthropic, openai, ollama, meta, compatible] {let config: model::Config =serde_json::from_value(json!({"default_model":"m","models":{"m":profile}})).unwrap();diff --git a/crates/graphicle/tests/it/easy_setup.rs b/crates/graphicle/tests/it/easy_setup.rsindex ec0ce01..c31c24f 100644--- a/crates/graphicle/tests/it/easy_setup.rs+++ b/crates/graphicle/tests/it/easy_setup.rs@@ -96,6 +96,29 @@ impl Machine {output(command)}+ /// [`Machine::run`] in `cwd` with `input` on standard input.+ fn run_with_input(&self, cwd: &Path, args: &[&str], input: &str) -> Output {+ use std::io::Write;+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ self.environment(&mut command);+ command+ .current_dir(cwd)+ .arg("--data-dir")+ .arg(&self.data)+ .args(args)+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped());+ let mut child = command.spawn().unwrap();+ child+ .stdin+ .take()+ .unwrap()+ .write_all(input.as_bytes())+ .unwrap();+ child.wait_with_output().unwrap()+ }+/// [`Machine::run`] in the repository, which must succeed; its JSON.fn graphicle(&self, args: &[&str]) -> Value {self.graphicle_in(&self.repo, args)@@ -1044,6 +1067,409 @@ fn connect_without_a_client_connects_what_is_installed() {assert!(!file.exists() && m.home.join(".cursor").is_dir());}+/// Muse Code: `connect muse` adds the project's entry to the `mcp_servers`+/// of `~/.config/muse/settings.json` with its transport, keeps the file's+/// other keys and adds the `schema_version` a file without one lacks; a+/// second connect changes nothing; `disconnect muse` removes only the entry.+#[test]+fn muse_code_gets_an_entry_in_its_settings() {+ let m = Machine::new();+ let settings = m.home.join(".config/muse/settings.json");+ write(+ &settings,+ "{\n \"tui\": {\"terminal_background\": \"dark\"},\n \"mcp_servers\": {\"other\": {\"transport\": \"stdio\", \"command\": \"other-server\", \"args\": []}}\n}\n",+ );+ m.graphicle(&["sync", "."]);+ let reply = m.graphicle(&["connect", "muse"]);+ assert_eq!(reply["entry"], "graphicle-app", "{reply:#}");+ let document = read_json(&settings);+ let entry = &document["mcp_servers"]["graphicle-app"];+ assert_eq!(entry["transport"], "stdio", "{document:#}");+ assert_eq!(entry["mode"], "optional");+ // The whole server, as for the other agents with one settings file.+ let args = entry["args"].as_array().unwrap();+ assert!(+ args.iter().any(|a| a == "mcp") && !args.iter().any(|a| a == "--tools"),+ "{entry}"+ );+ assert_eq!(document["schema_version"], 1);+ assert_eq!(document["tui"]["terminal_background"], "dark");+ assert_eq!(document["mcp_servers"]["other"]["command"], "other-server");+ let again = m.graphicle(&["connect", "muse"]);+ assert_eq!(again["unchanged"], true, "{again:#}");+ let undone = m.graphicle(&["disconnect", "muse"]);+ let after = read_json(&settings);+ assert!(+ after["mcp_servers"].get("graphicle-app").is_none(),+ "{undone:#}"+ );+ assert_eq!(after["mcp_servers"]["other"]["command"], "other-server");+ assert_eq!(after["tui"]["terminal_background"], "dark");+}++/// A fake `muse` program in the machine's `bin`: it records each call's+/// arguments, one line per call, in `bin/muse.calls`, and answers+/// `plugins … --json` with `{"ok":true}`.+#[cfg(unix)]+fn fake_muse(m: &Machine) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let program = m.bin.join("muse");+ write(+ &program,+ &format!(+ "#!/bin/sh\necho \"$*\" >> '{}'\necho '{{\"ok\":true}}'\n",+ m.bin.join("muse.calls").display()+ ),+ );+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();+ m.bin.join("muse.calls")+}++/// Muse Code with hooks: `connect muse --hooks` writes Graphicle's plugin+/// into the data folder (the optional server with the flags connect chose,+/// the skill and six hooks, with this program's path and data folder),+/// backs up and installs it with `muse plugins install`, and removes the+/// settings entry an earlier `connect muse` wrote; a later `connect muse`+/// (or setup) adds no entry beside it; the session start adds the kept map+/// before the memory; `disconnect muse` runs `muse plugins remove+/// graphicle` and deletes the package. Without the `muse` program the+/// settings entry is written as before, with the reason.+#[cfg(unix)]+#[test]+fn muse_code_gets_the_plugin_with_hooks() {+ let m = Machine::new();+ let settings = m.home.join(".config/muse/settings.json");+ write(&settings, "{\"schema_version\": 1, \"mcp_servers\": {}}\n");+ m.graphicle(&["sync", "."]);+ // No muse program: the entry, and why there is no plugin.+ let fallback = m.graphicle(&["connect", "muse", "--hooks"]);+ assert_eq!(fallback["plugin"]["state"], "skipped", "{fallback:#}");+ assert!(read_json(&settings)["mcp_servers"]["graphicle-app"].is_object());+ let calls = fake_muse(&m);+ let reply = m.graphicle(&["connect", "muse", "--hooks", "--allow-learning"]);+ assert_eq!(reply["plugin"], "installed", "{reply:#}");+ let project = reply["project"]["id"].as_str().unwrap().to_string();+ let package = m.data.join("muse-code-plugin");+ assert_eq!(+ std::fs::read_to_string(&calls).unwrap().trim(),+ format!("plugins install {} --scope user --json", package.display())+ );+ let manifest = read_json(&package.join(".muse-plugin/plugin.json"));+ assert_eq!(manifest["name"], "graphicle");+ let server = manifest["capabilities"]["mcpServers"][0]["command"]+ .as_array()+ .unwrap()+ .clone();+ assert_eq!(server[1], "--data-dir");+ assert_eq!(server[2], m.data.to_string_lossy().as_ref());+ assert!(server.ends_with(&[json!("--or-workspace"), json!("--allow-learning")]));+ assert_eq!(+ manifest["capabilities"]["mcpServers"][0]["mode"],+ "optional"+ );+ assert_eq!(+ manifest["capabilities"]["hooks"].as_array().unwrap().len(),+ 6+ );+ assert!(package.join("skills/graphicle/SKILL.md").is_file());+ // The plugin's server replaces the settings entry, backed up first.+ let after = read_json(&settings);+ assert!(+ after["mcp_servers"].get("graphicle-app").is_none(),+ "{after:#}"+ );+ assert!(+ m.home+ .join(".config/muse/settings.json.graphicle-bak")+ .is_file()+ );+ // With the plugin installed, connect without --hooks keeps it and adds+ // no settings entry beside it.+ let again = m.graphicle(&["connect", "muse"]);+ assert_eq!(again["plugin"], "current", "{again:#}");+ assert_eq!(again["unchanged"], true);+ assert!(+ read_json(&settings)["mcp_servers"]+ .get("graphicle-app")+ .is_none()+ );+ assert_eq!(std::fs::read_to_string(&calls).unwrap().lines().count(), 1);++ // The session start: the kept map first, then the memory section.+ let built = m.run(+ &m.repo,+ &[+ "hook",+ "muse",+ "pack",+ "--project",+ &project,+ "--pack-tokens",+ "8000",+ ],+ );+ assert!(built.status.success());+ // Built here, or by the build connect started (which holds the lock).+ let map = m.data.join(format!("muse-code-packs/{project}-8000.md"));+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);+ while !map.is_file() && std::time::Instant::now() < deadline {+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ let map_text = std::fs::read_to_string(&map).unwrap();+ assert!(map_text.contains("src/billing.py"), "{map_text}");+ let mut start = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ m.environment(&mut start);+ start+ .current_dir(&m.repo)+ .arg("--data-dir")+ .arg(&m.data)+ .args(["hook", "muse", "session-start"])+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped());+ let mut child = start.spawn().unwrap();+ {+ use std::io::Write;+ let payload = json!({"hook_event_name":"SessionStart","session_id":"s-1","source":"startup","cwd":m.repo});+ child+ .stdin+ .take()+ .unwrap()+ .write_all(payload.to_string().as_bytes())+ .unwrap();+ }+ let started = child.wait_with_output().unwrap();+ let output: Value = serde_json::from_slice(&started.stdout).unwrap();+ let context = output["hookSpecificOutput"]["additionalContext"]+ .as_str()+ .unwrap();+ assert_eq!(+ output["hookSpecificOutput"]["hookEventName"],+ "SessionStart"+ );+ assert!(context.starts_with(map_text.trim_end()), "{context}");+ assert!(+ context.contains("Graphicle: use its MCP tools"),+ "{context}"+ );++ let undone = m.graphicle(&["disconnect", "muse"]);+ assert!(!package.exists(), "{undone:#}");+ assert!(+ std::fs::read_to_string(&calls)+ .unwrap()+ .lines()+ .any(|line| line == "plugins remove graphicle --json"),+ "{undone:#}"+ );+}++/// Setup leaves Graphicle's Muse Code plugin to `connect muse --hooks`+/// (a preview): with the `muse` program found it writes the settings entry+/// as before, installs nothing, and says how to add the plugin.+#[cfg(unix)]+#[test]+fn setup_keeps_the_muse_code_plugin_opt_in() {+ let m = Machine::new();+ let settings = m.home.join(".config/muse/settings.json");+ write(&settings, "{\"schema_version\": 1, \"mcp_servers\": {}}\n");+ let calls = fake_muse(&m);+ let report = m.graphicle(&[+ "setup",+ "--yes",+ "--clients",+ "muse",+ "--no-instructions",+ "--no-hooks",+ "--json",+ ]);+ let muse = &report["clients"][0];+ assert_eq!(muse["client"], "muse", "{report:#}");+ assert_eq!(muse["plugin"]["state"], "off", "{report:#}");+ assert!(read_json(&settings)["mcp_servers"]["graphicle-app"].is_object());+ assert!(!calls.exists(), "setup ran muse");+ assert!(!m.data.join("muse-code-plugin").exists());+}++/// Muse Code's session logs become sources: `sessions import --client+/// muse` reads Muse Code's session root (`$XDG_DATA_HOME/muse/sessions`),+/// skips sub-agents' logs, and imports each finished turn into the project+/// of the log's workspace.+#[test]+fn muse_code_sessions_are_captured() {+ let m = Machine::new();+ m.graphicle(&["sync", "."]);+ let record = |sequence: u64, payload_type: &str, payload: Value| {+ json!({"stream":{"kind":"session","id":"9f1c-2"},"sequence":sequence,+ "recorded_at":1_793_000_000_000_000_u64 + sequence,"record_type":"event",+ "payload_type":payload_type,"payload":payload})+ .to_string()+ };+ let run = |event: Value| json!({"kind":"run","run_id":"r1","event":event});+ let log = [+ record(+ 1,+ "runtime.session.metadata",+ json!({"workspace_root":m.repo}),+ ),+ record(+ 2,+ "agent.run",+ run(json!({"kind":"started","prompt":"Decision: invoices settle monthly, never weekly."})),+ ),+ record(+ 3,+ "agent.run",+ run(json!({"kind":"assistant_message_committed","text":"Noted: monthly settlement (src/billing.py:4)."})),+ ),+ record(+ 4,+ "agent.run",+ run(json!({"kind":"terminal","terminal":"completed"})),+ ),+ ]+ .join("\n");+ let day = m.home.join(".local/share/muse/sessions/2026/10/27/9f1c-2");+ write(&day.join("session.jsonl"), &format!("{log}\n"));+ write(&day.join("subagent/a1/session.jsonl"), &format!("{log}\n"));+ let reply = m.graphicle(&["sessions", "import", "--client", "muse"]);+ assert_eq!(reply["transcripts"], 1, "{reply:#}");+ assert_eq!(reply["turns_imported"], 1, "{reply:#}");+ let again = m.graphicle(&["sessions", "import", "--client", "muse"]);+ assert_eq!(again["turns_imported"], 0, "{again:#}");+}++/// The plugin's server starts in any folder: `mcp --project .+/// --or-workspace` outside every synced project serves the workspace,+/// where `--project .` alone fails.+#[test]+fn mcp_or_workspace_starts_outside_projects() {+ let m = Machine::new();+ m.graphicle(&["sync", "."]);+ let outside = m.root.join("elsewhere");+ std::fs::create_dir_all(&outside).unwrap();+ let serve = |args: &[&str]| {+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ m.environment(&mut command);+ command+ .current_dir(&outside)+ .arg("--data-dir")+ .arg(&m.data)+ .args(args)+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped());+ let mut child = command.spawn().unwrap();+ {+ use std::io::Write;+ let mut input = child.stdin.take().unwrap();+ input+ .write_all(+ b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{}}\n",+ )+ .unwrap();+ }+ child.wait_with_output().unwrap()+ };+ let strict = serve(&["mcp", "--project", "."]);+ assert!(!strict.status.success());+ let served = serve(&[+ "mcp",+ "--project",+ ".",+ "--or-workspace",+ "--allow-learning",+ ]);+ assert!(+ served.status.success(),+ "{}",+ String::from_utf8_lossy(&served.stderr)+ );+ let reply: Value = serde_json::from_str(+ String::from_utf8_lossy(&served.stdout)+ .lines()+ .next()+ .unwrap(),+ )+ .unwrap();+ assert!(reply["result"]["serverInfo"].is_object(), "{reply}");+ assert!(String::from_utf8_lossy(&served.stderr).contains("serving the workspace"));+}++/// The Graphicle side of the two-session memory demo (memory_demo.py), with+/// the agent's calls made by hand: the plugin's server takes a decision as a+/// draft memory with a quote from the code; it is not in a session's start+/// until a person approves it (`learning.review`, as the app does); then+/// Muse Code's session start names it by title and id.+#[test]+fn muse_code_session_starts_with_an_approved_memory() {+ let m = Machine::new();+ m.graphicle(&["sync", "."]);+ let proposal = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"propose_memory",+ "arguments":{"kind":"decision","title":"Invoices settle with their tax",+ "body":"settle_invoice adds the tax before rounding to cents; keep it that way.",+ "evidence":[{"source_id":"file:src/billing.py","quote":" return cents(total + tax)"}],+ "idempotency_key":"demo-1"}}});+ let input = format!(+ "{}\n{proposal}\n",+ json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{}})+ );+ let served = m.run_with_input(+ &m.repo,+ &[+ "mcp",+ "--project",+ ".",+ "--or-workspace",+ "--allow-learning",+ ],+ &input,+ );+ let replies: Vec<Value> = String::from_utf8_lossy(&served.stdout)+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect();+ let saved = &replies[1]["result"];+ assert_eq!(saved["isError"], false, "{saved}");+ let memory = saved["structuredContent"]["memory_id"]+ .as_str()+ .unwrap()+ .to_string();+ let start = |m: &Machine| -> String {+ let payload = json!({"hook_event_name":"SessionStart","session_id":"s-2","source":"startup","cwd":m.repo});+ let output = m.run_with_input(+ &m.repo,+ &["hook", "muse", "session-start", "--pack-tokens", "0"],+ &payload.to_string(),+ );+ let reply: Value = serde_json::from_slice(&output.stdout).unwrap();+ reply["hookSpecificOutput"]["additionalContext"]+ .as_str()+ .unwrap()+ .to_string()+ };+ assert!(!start(&m).contains(&memory), "a draft is never served");+ let arguments = m.root.join("review.json");+ write(+ &arguments,+ &json!({"memory_id":memory,"expected_revision":1,"decision":"approve","maintainer":"demo",+ "reason":"Checked the quoted line."})+ .to_string(),+ );+ m.graphicle(&[+ "call",+ "learning.review",+ "--arguments",+ arguments.to_str().unwrap(),+ ]);+ let context = start(&m);+ assert!(+ context.contains(&format!(+ "- Invoices settle with their tax (memory {memory})"+ )),+ "{context}"+ );+}+/// Setup outside a Git repository and without a terminal: the project is/// synced, no client is connected without --yes or --clients, no Git hook/// is written, AGENTS.md is not created, and nothing outside the data@@ -1129,6 +1555,391 @@ fn git_hooks_run_in_the_background_and_respect_core_hooks_path() {assert!(!husky.join(".githooks/post-commit").exists());}+/// A folder made read-only (0555) while the guard lives, as Claude Code's+/// sandbox leaves `.git/hooks` and `.mcp.json`; `None` when it stays+/// writable (a test run as root), so there is nothing to check.+#[cfg(unix)]+struct ReadOnly(PathBuf);++#[cfg(unix)]+impl ReadOnly {+ fn new(folder: &Path) -> Option<Self> {+ set_mode(folder, 0o555);+ let guard = Self(folder.to_path_buf());+ let probe = folder.join(".probe");+ if std::fs::write(&probe, "").is_ok() {+ let _ = std::fs::remove_file(&probe);+ eprintln!("{} stays writable: nothing to check", folder.display());+ return None;+ }+ Some(guard)+ }+}++#[cfg(unix)]+impl Drop for ReadOnly {+ fn drop(&mut self) {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));+ }+}++/// The three hooks' entries: each skipped, with its file and a reason that+/// names the OS error; the step's line to add by hand, which the summary+/// prints after one line per hook.+#[cfg(unix)]+fn assert_hooks_skipped(m: &Machine, report: &Value) {+ let git = &report["git_hooks"];+ assert_eq!(git["state"], "skipped", "{report:#}");+ let hooks = m.repo.join(".git/hooks");+ let text = graphicle_runtime::setup::render_setup(report);+ let names = ["post-commit", "post-merge", "post-checkout"];+ let entries = git["hooks"].as_array().unwrap();+ assert_eq!(entries.len(), names.len(), "{report:#}");+ for (hook, name) in entries.iter().zip(names) {+ assert_eq!(hook["hook"], name, "{report:#}");+ assert_eq!(hook["file"], json!(hooks.join(name)), "{report:#}");+ assert_eq!(hook["state"], "skipped", "{report:#}");+ let reason = hook["reason"].as_str().unwrap();+ assert!(+ reason.starts_with("not writable: ") && reason.contains("(os error "),+ "{reason}"+ );+ assert!(+ text.contains(&format!(".git/hooks/{name}: {reason}\n")),+ "{text}"+ );+ assert!(!hooks.join(name).exists());+ }+ let by_hand = git["by_hand"].as_str().unwrap();+ assert!(+ by_hand.starts_with(+ "Add this line to post-commit, post-merge and post-checkout in that folder: "+ ) && by_hand.contains(&format!("sync '{}' --quiet", m.repo.display())),+ "{by_hand}"+ );+ assert!(+ text.contains(&format!(" {by_hand}\n")),+ "{text}"+ );+ assert!(text.contains("\nTry:\n"), "the whole summary: {text}");+}++/// Git hooks setup cannot write (Claude Code's sandbox; here a read-only+/// `.git/hooks`) do not stop it: each hook is named with its reason, the+/// summary gives the line to add by hand, and setup finishes.+#[cfg(unix)]+#[test]+fn setup_finishes_when_it_cannot_write_the_git_hooks() {+ let m = Machine::new();+ let Some(_hooks) = ReadOnly::new(&m.repo.join(".git/hooks")) else {+ return;+ };+ let report = m.graphicle(&["setup", "--yes", "--clients", "none"]);+ assert_hooks_skipped(&m, &report);+ // The steps after the hooks ran.+ assert!(report["model"].is_object(), "{report:#}");+ assert_eq!(+ report["files_changed"],+ json!([m.repo.join("AGENTS.md")]),+ "{report:#}"+ );+}++/// With `.mcp.json` not writable too (here in a read-only project folder),+/// the summary has Claude Code's entry to paste into `.mcp.json`, AGENTS.md+/// skipped with its reason and the hooks' line; setup then fails, naming+/// Claude Code, and has changed no file.+#[cfg(unix)]+#[test]+fn setup_prints_each_line_to_add_by_hand_when_mcp_json_is_read_only_too() {+ let m = Machine::new();+ std::fs::create_dir_all(m.home.join(".claude")).unwrap();+ let mcp = m.repo.join(".mcp.json");+ let servers = json!({"mcpServers":{"other":other()}}).to_string();+ write(&mcp, &servers);+ set_mode(&mcp, 0o444);+ let Some(_hooks) = ReadOnly::new(&m.repo.join(".git/hooks")) else {+ return;+ };+ let Some(_folder) = ReadOnly::new(&m.repo) else {+ return;+ };+ let output = m.run(&m.repo, &["setup", "--yes"]);+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("graphicle: Not connected: Claude Code: "),+ "{stderr}"+ );+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(+ states(&report, "clients", "client"),+ [("claude-code".to_string(), "failed".to_string())],+ "{report:#}"+ );+ let error = report["clients"][0]["error"].as_str().unwrap();+ assert!(+ error.contains(&format!(+ "add this to the \"mcpServers\" object of {} yourself (docs/mcp.md#other-clients): \"graphicle\": {{",+ mcp.display()+ )),+ "the entry to paste: {error}"+ );+ let agents = &report["instructions"][0];+ assert_eq!(+ agents["file"],+ json!(m.repo.join("AGENTS.md")),+ "{report:#}"+ );+ assert_eq!(agents["state"], "skipped", "{report:#}");+ let reason = agents["reason"].as_str().unwrap();+ assert!(reason.starts_with("not writable: "), "{reason}");+ assert_hooks_skipped(&m, &report);+ let text = graphicle_runtime::setup::render_setup(&report);+ assert!(text.contains(&format!("failed: {error}\n")), "{text}");+ assert!(+ text.contains(&format!("AGENTS.md skipped: {reason}\n")),+ "{text}"+ );+ assert!(+ text.contains("\nNothing changed outside the data folder.\n"),+ "not everything was already set: {text}"+ );+ assert_eq!(report["files_changed"], json!([]), "{report:#}");+ assert_eq!(std::fs::read_to_string(&mcp).unwrap(), servers);+ assert!(!m.repo.join("AGENTS.md").exists());+ assert!(!m.repo.join(".mcp.json.graphicle-bak").exists());+}++/// A reason setup gives for a file the file system refused: it names the+/// OS error.+#[cfg(unix)]+fn assert_not_writable(reason: &str) {+ assert!(+ reason.starts_with("not writable: ") && reason.contains("(os error "),+ "{reason}"+ );+}++/// Claude Code's hooks file that setup cannot write (its sandbox; here a+/// read-only `.claude` folder) does not fail the connection: `.mcp.json`+/// stays written and listed, the hooks are skipped with the file and the+/// reason, the summary gives the `connect` command that adds them later,+/// and setup exits 0. That command fails while the file stays read-only,+/// naming it, and adds the hooks once it is writable.+#[cfg(unix)]+#[test]+fn setup_keeps_claude_code_connected_when_its_hooks_file_is_read_only() {+ let m = Machine::new();+ std::fs::create_dir_all(m.home.join(".claude")).unwrap();+ let claude = m.repo.join(".claude");+ std::fs::create_dir_all(&claude).unwrap();+ let settings = claude.join("settings.local.json");+ let Some(read_only) = ReadOnly::new(&claude) else {+ return;+ };+ let output = m.run(&m.repo, &["setup", "--yes"]);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "{stderr}");+ assert!(!stderr.contains("Local I/O failed"), "{stderr}");+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(+ states(&report, "clients", "client"),+ [("claude-code".to_string(), "added".to_string())],+ "{report:#}"+ );+ let capture = &report["clients"][0]["capture"];+ assert_eq!(capture["state"], "skipped", "{report:#}");+ assert_eq!(capture["file"], json!(settings), "{report:#}");+ assert_eq!(report["capture"]["state"], "skipped", "{report:#}");+ let reason = capture["reason"].as_str().unwrap();+ assert_not_writable(reason);+ let by_hand = capture["by_hand"].as_str().unwrap();+ assert!(+ by_hand.ends_with(&format!(+ ": graphicle --data-dir '{}' connect claude-code --hooks",+ m.data.display()+ )),+ "{by_hand}"+ );+ let mcp = m.repo.join(".mcp.json");+ assert!(read_json(&mcp)["mcpServers"]["graphicle"].is_object());+ let files = report["files_changed"].as_array().unwrap();+ assert!(files.contains(&json!(mcp)), "{report:#}");+ assert!(!files.contains(&json!(settings)), "{report:#}");+ assert!(!settings.exists());+ let text = graphicle_runtime::setup::render_setup(&report);+ assert!(+ text.contains(&format!(+ " {:<13} {:<15} skipped: .claude/settings.local.json: {reason}\n {by_hand}\n",+ "Capture", "Claude Code"+ )),+ "{text}"+ );+ assert!(text.contains("\n .mcp.json\n"), "{text}");+ assert!(!text.contains("Finished turns become"), "{text}");+ // `connect --hooks` by hand still fails on the file, and names it.+ let refused = m.run(&m.repo, &["connect", "claude-code", "--hooks"]);+ assert!(!refused.status.success());+ let error = String::from_utf8_lossy(&refused.stderr);+ assert!(+ error.contains(&format!("{}: not writable: ", settings.display()))+ && error.contains("(os error ")+ && !error.contains("Local I/O failed"),+ "{error}"+ );+ // Writable again, the summary's command adds the hooks beside the entry+ // setup wrote, which stays as it is.+ drop(read_only);+ let entry = std::fs::read(&mcp).unwrap();+ let connected = m.graphicle(&["connect", "claude-code", "--hooks", "--json"]);+ assert_eq!(connected["unchanged"], true, "{connected:#}");+ assert!(+ connected["hooks"]["installed"]+ .as_array()+ .is_some_and(|installed| !installed.is_empty()),+ "{connected:#}"+ );+ assert!(read_json(&settings)["hooks"]["Stop"].is_array());+ assert_eq!(std::fs::read(&mcp).unwrap(), entry);+}++/// Codex's hooks file goes the same way: with `~/.codex` read-only once its+/// entry is there, setup keeps Codex connected, skips the hooks with the+/// file and the reason, gives `connect codex --hooks`, and exits 0.+#[cfg(unix)]+#[test]+fn setup_keeps_codex_connected_when_its_hooks_file_is_read_only() {+ let m = Machine::new();+ let codex = m.home.join(".codex");+ std::fs::create_dir_all(&codex).unwrap();+ m.graphicle(&["setup", "--yes", "--clients", "codex"]);+ // Its hooks taken out by hand, then its folder read-only.+ let hooks = codex.join("hooks.json");+ write(&hooks, "{\"hooks\":{}}\n");+ let Some(_codex) = ReadOnly::new(&codex) else {+ return;+ };+ let output = m.run(&m.repo, &["setup", "--yes", "--clients", "codex"]);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "{stderr}");+ assert!(!stderr.contains("Local I/O failed"), "{stderr}");+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(+ states(&report, "clients", "client"),+ [("codex".to_string(), "already set".to_string())],+ "{report:#}"+ );+ let capture = &report["clients"][0]["capture"];+ assert_eq!(capture["state"], "skipped", "{report:#}");+ assert_eq!(capture["file"], json!(hooks), "{report:#}");+ let reason = capture["reason"].as_str().unwrap();+ assert_not_writable(reason);+ let by_hand = capture["by_hand"].as_str().unwrap();+ assert!(+ by_hand.ends_with(&format!(+ ": graphicle --data-dir '{}' connect codex --hooks",+ m.data.display()+ )),+ "{by_hand}"+ );+ assert_eq!(std::fs::read_to_string(&hooks).unwrap(), "{\"hooks\":{}}\n");+ let text = graphicle_runtime::setup::render_setup(&report);+ assert!(+ text.contains(&format!("skipped: {}: {reason}\n", hooks.display())),+ "{text}"+ );+ assert!(+ text.contains("\nNothing changed outside the data folder.\n"),+ "not everything was already set: {text}"+ );+}++/// Codex's default sandbox keeps the whole `.git` folder read-only, not+/// only its hooks. Setup still connects the agent and prints its summary:+/// the Git hooks are skipped as above, and so is the exclude file, whose+/// lines the summary gives to add by hand; every other file is written.+#[cfg(unix)]+#[test]+fn setup_finishes_when_the_whole_git_folder_is_read_only() {+ let m = Machine::new();+ std::fs::create_dir_all(m.home.join(".claude")).unwrap();+ // The project's own MCP file: its backup needs a line in the exclude+ // file, and so does the settings file setup creates.+ let mcp = m.repo.join(".mcp.json");+ write(&mcp, &json!({"mcpServers":{"other":other()}}).to_string());+ let git = m.repo.join(".git");+ let exclude = git.join("info/exclude");+ let before = std::fs::read(&exclude).unwrap();+ let Some(_hooks) = ReadOnly::new(&git.join("hooks")) else {+ return;+ };+ let Some(_info) = ReadOnly::new(&git.join("info")) else {+ return;+ };+ let Some(_git) = ReadOnly::new(&git) else {+ return;+ };+ let output = m.run(&m.repo, &["setup", "--yes"]);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "{stderr}");+ assert!(!stderr.contains("Local I/O failed"), "{stderr}");+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(+ states(&report, "clients", "client"),+ [("claude-code".to_string(), "added".to_string())],+ "{report:#}"+ );+ assert_eq!(report["capture"]["state"], "on", "{report:#}");+ assert_hooks_skipped(&m, &report);+ let skipped = &report["git_exclude"][0];+ assert_eq!(skipped["file"], json!(exclude), "{report:#}");+ let reason = skipped["reason"].as_str().unwrap();+ assert_not_writable(reason);+ assert_eq!(+ skipped["lines"],+ json!(["*.graphicle-bak", "/.claude/settings.local.json"]),+ "{report:#}"+ );+ assert_eq!(std::fs::read(&exclude).unwrap(), before);+ let settings = m.repo.join(".claude/settings.local.json");+ assert_eq!(+ report["files_changed"],+ json!([mcp, settings]),+ "{report:#}"+ );+ assert!(read_json(&mcp)["mcpServers"]["graphicle"].is_object());+ assert!(m.repo.join(".mcp.json.graphicle-bak").exists());+ let text = graphicle_runtime::setup::render_setup(&report);+ assert!(+ text.contains(&format!(+ " Git exclude skipped: .git/info/exclude: {reason}\n To keep setup's files out of Git, add *.graphicle-bak and /.claude/settings.local.json to it, one per line\n"+ )),+ "{text}"+ );+}++/// A data folder the file system refuses (a sandbox that keeps the home+/// folder read-only) stops setup before it starts, naming the folder.+#[cfg(unix)]+#[test]+fn setup_names_a_data_folder_it_cannot_create() {+ let m = Machine::new();+ let Some(_root) = ReadOnly::new(&m.root) else {+ return;+ };+ let output = m.run(&m.repo, &["setup", "--yes"]);+ assert!(!output.status.success());+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains(&format!("{}: not writable: ", m.data.display()))+ && stderr.contains("(os error ")+ && !stderr.contains("Local I/O failed"),+ "{stderr}"+ );+}+/// `uninstall --purge` disconnects everywhere, says how to remove the/// program and deletes the data folder; without a terminal it needs --yes.#[test]diff --git a/crates/graphicle/tests/it/fix_command.rs b/crates/graphicle/tests/it/fix_command.rsnew file mode 100644index 0000000..84be543--- /dev/null+++ b/crates/graphicle/tests/it/fix_command.rs@@ -0,0 +1,1098 @@+//! `graphicle fix` against a scripted mock of the Responses API: round 1's+//! edit still fails the test, round 2's passes, and the follow-up's start is+//! cached; an edit that leaves the repository is refused; with no test+//! command the change is made and reported untested; hooks never run, not+//! even ones the model edited; git ignores variables that point it+//! elsewhere; the test command gets no model key; nothing is made before+//! the plan; each round fits the window; a provider's error is reported as+//! one. The person's working tree and branch never change.+use axum::{+ Json, Router,+ extract::State,+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::post,+};+use serde_json::{Value, json};+use std::{+ collections::HashMap,+ path::{Path, PathBuf},+ process::{Command, Output, Stdio},+ sync::{Arc, Mutex},+};+use tempfile::TempDir;++#[derive(Clone, Default)]+struct Mock {+ requests: Arc<Mutex<Vec<Value>>>,+ last: Arc<Mutex<HashMap<String, String>>>,+ /// The edits' replies, in order.+ script: Arc<Mutex<Vec<Value>>>,+ /// Refuse every request for edits, as a provider refuses.+ refuse_edits: Arc<Mutex<bool>>,+ /// Bytes of padding in the plan's summary.+ plan_padding: Arc<Mutex<usize>>,+ /// The context window (bytes over four), and the requests refused for it.+ window: Arc<Mutex<Option<u64>>>,+ over_window: Arc<Mutex<u64>>,+}++async fn responses(State(mock): State<Mock>, Json(request): Json<Value>) -> Response {+ let instructions = request["instructions"].as_str().unwrap_or("");+ let prompt = format!("{instructions}{}", request["input"].as_str().unwrap_or(""));+ let input = prompt.len() as u64 / 4;+ if let Some(window) = *mock.window.lock().unwrap()+ && input > window+ {+ *mock.over_window.lock().unwrap() += 1;+ return (+ StatusCode::BAD_REQUEST,+ Json(json!({"error":{"message":"input exceeds the context window"}})),+ )+ .into_response();+ }+ if instructions.starts_with("You fix") && *mock.refuse_edits.lock().unwrap() {+ mock.requests.lock().unwrap().push(request.clone());+ return (+ StatusCode::BAD_REQUEST,+ Json(json!({"error":{"message":"the request was refused by the fixture"}})),+ )+ .into_response();+ }+ let mut cached = 0;+ if let Some(key) = request["prompt_cache_key"].as_str() {+ let mut last = mock.last.lock().unwrap();+ if let Some(previous) = last.get(key) {+ let common = previous+ .bytes()+ .zip(prompt.bytes())+ .take_while(|(a, b)| a == b)+ .count() as u64+ / 4;+ if common >= 1024 {+ cached = common;+ }+ }+ last.insert(key.to_string(), prompt.clone());+ }+ mock.requests.lock().unwrap().push(request.clone());+ let text = if instructions.starts_with("You fix") {+ let mut script = mock.script.lock().unwrap();+ if script.is_empty() {+ json!({"explanation":"Nothing to change.","edits":[],"new_files":[],"tests":[]})+ } else {+ script.remove(0)+ }+ } else {+ let padding = "x".repeat(*mock.plan_padding.lock().unwrap());+ json!({"summary":format!("Return 42 from Answer.{padding}"),"steps":["Change the return value"],+ "edits":[{"path":"src/answer.go","start_line":4,"end_line":6,"reason":"the value"}],+ "new_files":[],"tests":[{"action":"run","path":"check.sh","what":"the check"}],"risks":[]})+ };+ Json(json!({"status":"completed","model":"muse-wonder-1.0",+ "usage":{"input_tokens":input,"input_tokens_details":{"cached_tokens":cached},+ "output_tokens":60,"output_tokens_details":{"reasoning_tokens":30}},+ "output":[{"type":"message","content":[{"type":"output_text","text":text.to_string()}]}]}))+ .into_response()+}++async fn serve(mock: Mock) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = Router::new()+ .route("/v1/responses", post(responses))+ .with_state(mock);+ let server = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ (format!("http://{address}/v1"), server)+}++fn identity(command: &mut Command) -> &mut Command {+ command+ .env("GIT_AUTHOR_NAME", "Fixture")+ .env("GIT_AUTHOR_EMAIL", "[email protected]")+ .env("GIT_COMMITTER_NAME", "Fixture")+ .env("GIT_COMMITTER_EMAIL", "[email protected]")+}++fn graphicle_env(dir: &Path, args: &[String], env: &[(String, String)]) -> Output {+ graphicle_as(dir, args, env, true)+}++/// [`graphicle_env`]; without `with_identity`, git takes the commit identity+/// from its configuration files (the identity variables and EMAIL removed).+fn graphicle_as(+ dir: &Path,+ args: &[String],+ env: &[(String, String)],+ with_identity: bool,+) -> Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ command.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));+ crate::child_env::home(&mut command, dir)+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--config")+ .arg(dir.join("models.json"))+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ if with_identity {+ identity(&mut command);+ } else {+ for name in [+ "GIT_AUTHOR_NAME",+ "GIT_AUTHOR_EMAIL",+ "GIT_COMMITTER_NAME",+ "GIT_COMMITTER_EMAIL",+ "EMAIL",+ ] {+ command.env_remove(name);+ }+ }+ crate::fork_guard::spawn(&mut command)+ .unwrap()+ .wait_with_output()+ .unwrap()+}++async fn run(root: &Path, args: &[&str]) -> Output {+ run_env(root, args, &[]).await+}++async fn run_env(root: &Path, args: &[&str], env: &[(&str, &str)]) -> Output {+ let root = root.to_path_buf();+ let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();+ let env: Vec<(String, String)> = env+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect();+ tokio::task::spawn_blocking(move || graphicle_env(&root, &args, &env))+ .await+ .unwrap()+}++/// The JSON a command printed, whatever its exit status.+fn printed(output: &Output) -> Value {+ serde_json::from_slice(&output.stdout).unwrap_or_else(|_| {+ panic!(+ "no JSON: {}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ })+}++fn git(dir: &Path, args: &[&str]) -> String {+ let mut command = Command::new("git");+ command.arg("-C").arg(dir).args(args);+ identity(&mut command);+ let output = command.output().unwrap();+ assert!(+ output.status.success(),+ "git {args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).trim().to_string()+}++/// A git repository whose check fails: Answer returns 41, the check wants 42.+fn repository(root: &Path) -> PathBuf {+ let project = root.join("project");+ std::fs::create_dir_all(project.join("src")).unwrap();+ std::fs::write(+ project.join("src/answer.go"),+ "package answer\n\n// Answer is the answer.\nfunc Answer() int {\n\treturn 41\n}\n",+ )+ .unwrap();+ for i in 0..12 {+ let mut text = format!("package answer\n\n// Helper{i} helps the answer.\n");+ for f in 0..6 {+ text.push_str(&format!(+ "func Helper{i}x{f}() int {{\n\tvalue := Answer() + {f}\n\treturn value * {i}\n}}\n\n"+ ));+ }+ std::fs::write(project.join(format!("src/helper{i}.go")), text).unwrap();+ }+ std::fs::write(+ project.join("check.sh"),+ "grep -q 'return 42' src/answer.go\n",+ )+ .unwrap();+ std::fs::write(+ project.join("README.md"),+ "# Answer\n\nAnswer returns the answer.\n",+ )+ .unwrap();+ git(&project, &["init", "-q"]);+ git(&project, &["add", "-A"]);+ git(&project, &["commit", "-q", "-m", "The answer"]);+ project+}++fn models(root: &Path, base: &str) {+ models_with(root, base, json!({}));+}++fn models_with(root: &Path, base: &str, extra: Value) {+ let mut wonder = json!({"protocol":"responses","base_url":base,+ "model":"muse-wonder-1.0","input_limit":60_000,"output_limit":4_000,"prompt_cache":true,+ "reasoning_effort":"medium","price":{"input":4.0,"output":20.0,"cached_input":0.2}});+ for (k, v) in extra.as_object().unwrap() {+ wonder[k] = v.clone();+ }+ std::fs::write(+ root.join("models.json"),+ json!({"default_model":"wonder","models":{"wonder":wonder}}).to_string(),+ )+ .unwrap();+}++/// The repository with its hooks in the tree (`core.hooksPath .githooks`, as+/// husky-style setups have them): pre-commit, post-commit and post-checkout,+/// each leaving a marker when it runs.+#[cfg(unix)]+fn hooked_repository(root: &Path) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let project = root.join("project");+ std::fs::create_dir_all(project.join(".githooks")).unwrap();+ for hook in ["pre-commit", "post-commit", "post-checkout"] {+ let path = project.join(".githooks").join(hook);+ let marker = root.join(format!("{hook}-ran"));+ std::fs::write(+ &path,+ format!("#!/bin/sh\ntouch '{}'\nexit 0\n", marker.display()),+ )+ .unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let project = repository(root);+ git(&project, &["config", "core.hooksPath", ".githooks"]);+ // The fixture's own commit ran pre-commit and post-commit: start clean.+ for hook in ["pre-commit", "post-commit", "post-checkout"] {+ let _ = std::fs::remove_file(root.join(format!("{hook}-ran")));+ }+ project+}++fn edit(path: &str, search: &str, replace: &str) -> Value {+ json!({"explanation":format!("Answer returns the value at {path}:5."),+ "edits":[{"path":path,"search":search,"replace":replace}],"new_files":[],+ "tests":["go test ./..."]})+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_failing_round_is_fed_back_and_the_next_one_passes() {+ let mock = Mock::default();+ mock.script.lock().unwrap().extend([+ edit("src/answer.go", "\treturn 41\n", "\treturn 40\n"),+ edit("src/answer.go", "\treturn 40\n", "\treturn 42\n"),+ ]);+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ let branch = git(&project, &["rev-parse", "--abbrev-ref", "HEAD"]);+ let synced = run(root, &["sync", project.to_str().unwrap()]).await;+ assert!(synced.status.success());+ let fixed = run(+ root,+ &[+ "fix",+ "The answer should be 42, not 41",+ "--test",+ "sh check.sh",+ "--rounds",+ "3",+ "--json",+ ],+ )+ .await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert_eq!(report["result"], "passed");+ assert_eq!(+ report["branch"],+ "graphicle/fix-the-answer-should-be-42-not-41"+ );+ let rounds = report["rounds"].as_array().unwrap();+ assert_eq!(rounds.len(), 2, "{report}");+ assert_eq!(rounds[0]["result"], "failed");+ assert_eq!(rounds[0]["test"]["exit_code"], 1);+ assert_eq!(rounds[1]["result"], "passed");+ assert_eq!(report["files_changed"], json!(["src/answer.go"]));+ assert_eq!(report["suggested_tests"], json!(["go test ./..."]));+ assert!(report["committed"].is_null());+ let cited = report["citations"].as_array().unwrap();+ assert!(+ cited+ .iter()+ .any(|c| c["path"] == "src/answer.go" && c["valid"] == true)+ );+ // The change is in the new worktree; the person's tree and branch are as+ // they were.+ let worktree = PathBuf::from(report["worktree"].as_str().unwrap());+ assert!(worktree.starts_with(root.join("data")));+ assert!(+ std::fs::read_to_string(worktree.join("src/answer.go"))+ .unwrap()+ .contains("return 42")+ );+ assert!(+ std::fs::read_to_string(project.join("src/answer.go"))+ .unwrap()+ .contains("return 41")+ );+ assert_eq!(+ git(&project, &["rev-parse", "--abbrev-ref", "HEAD"]),+ branch+ );+ assert_eq!(+ git(&project, &["status", "--porcelain", "--untracked-files=no"]),+ ""+ );+ // Round 2 got round 1's failure and diff, after the same start, which the+ // cache held.+ let requests = mock.requests.lock().unwrap();+ assert_eq!(requests.len(), 3, "a plan and two rounds");+ let (one, two) = (+ requests[1]["input"].as_str().unwrap(),+ requests[2]["input"].as_str().unwrap(),+ );+ assert!(+ two.contains("the test command failed (exit code 1)"),+ "{}",+ &two[two.len() - 600..]+ );+ assert!(two.contains("-\treturn 41") && two.contains("+\treturn 40"));+ let start = one.find("Round 1: return the edits.").unwrap();+ assert_eq!(&two[..start], &one[..start]);+ assert_eq!(+ requests[1]["prompt_cache_key"],+ requests[2]["prompt_cache_key"]+ );+ drop(requests);+ assert!(rounds[1]["usage"]["cached_tokens"].as_u64().unwrap() >= 1024);+ let log: Vec<Value> = std::fs::read_to_string(root.join("data/usage.jsonl"))+ .unwrap()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();+ assert_eq!(log.len(), 3);+ assert!(log.iter().all(|e| e["command"] == "fix"));+ assert_eq!(log[2]["cached_tokens"], rounds[1]["usage"]["cached_tokens"]);+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn an_edit_that_leaves_the_repository_is_refused() {+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(json!({"explanation":"Escape.",+ "edits":[{"path":"src/answer.go","search":"\treturn 41\n","replace":"\treturn 42\n"},+ {"path":"../outside.txt","search":"a","replace":"b"}],+ "new_files":[{"path":".git/hooks/pre-commit","content":"#!/bin/sh\n"},+ {"path":"/tmp/graphicle-fix-escape","content":"x"}],"tests":[]}));+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(+ root,+ &[+ "fix",+ "Make it 42",+ "--test",+ "sh check.sh",+ "--rounds",+ "1",+ "--json",+ ],+ )+ .await;+ assert!(!fixed.status.success());+ let report = printed(&fixed);+ assert_eq!(report["result"], "not applied");+ let refused: Vec<&str> = report["rounds"][0]["refused"]+ .as_array()+ .unwrap()+ .iter()+ .map(|p| p.as_str().unwrap())+ .collect();+ assert!(+ refused+ .iter()+ .any(|p| p.starts_with("../outside.txt: refused")),+ "{refused:?}"+ );+ assert!(+ refused+ .iter()+ .any(|p| p.starts_with(".git/hooks/pre-commit: refused"))+ );+ assert!(+ refused+ .iter()+ .any(|p| p.starts_with("/tmp/graphicle-fix-escape: refused"))+ );+ // All or none: the good edit was not applied either, and nothing was+ // written outside.+ let worktree = PathBuf::from(report["worktree"].as_str().unwrap());+ assert!(+ std::fs::read_to_string(worktree.join("src/answer.go"))+ .unwrap()+ .contains("return 41")+ );+ assert!(!worktree.parent().unwrap().join("outside.txt").exists());+ assert!(!Path::new("/tmp/graphicle-fix-escape").exists());+ assert_eq!(report["files_changed"], json!([]));+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn without_a_test_command_the_change_is_made_and_reported_untested() {+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(+ root,+ &[+ "fix",+ "Make it 42",+ "--rounds",+ "2",+ "--commit",+ "--branch",+ "answer-42",+ "--json",+ ],+ )+ .await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert_eq!(report["result"], "untested");+ assert_eq!(report["tested"], false);+ assert_eq!(report["rounds"].as_array().unwrap().len(), 1);+ assert_eq!(report["branch"], "answer-42");+ let worktree = PathBuf::from(report["worktree"].as_str().unwrap());+ let sha = report["committed"].as_str().unwrap();+ assert_eq!(git(&worktree, &["rev-parse", "HEAD"]), sha);+ assert_eq!(git(&worktree, &["log", "-1", "--format=%s"]), "Make it 42");+ assert_eq!(git(&project, &["rev-parse", "answer-42"]), sha);+ assert!(+ std::fs::read_to_string(project.join("src/answer.go"))+ .unwrap()+ .contains("return 41")+ );+ server.abort();+}++/// `--focus` puts the passages it names in the pack whatever the issue's+/// words rank: a file they never rank is not in a small pack without it, and+/// is with it; the report says which passages; a bad range is refused. (The+/// standard layout: in the cache layout the passages lead the question part,+/// which a budget this small leaves no room.)+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn focus_puts_the_located_passages_in_the_pack() {+ let mock = Mock::default();+ for _ in 0..2 {+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ }+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ std::fs::write(+ project.join("src/zebra.go"),+ "package answer\n\n// Zebra paints stripes.\nfunc Zebra() string {\n\treturn \"stripes\"\n}\n",+ )+ .unwrap();+ git(&project, &["add", "-A"]);+ git(&project, &["commit", "-q", "-m", "Stripes"]);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let plain = run(+ root,+ &[+ "fix",+ "Make it 42",+ "--budget",+ "600",+ "--layout",+ "standard",+ "--branch",+ "plain",+ "--json",+ ],+ )+ .await;+ assert!(plain.status.success(), "{}", printed(&plain));+ assert!(printed(&plain).get("focus").is_none());+ let focused = run(+ root,+ &[+ "fix",+ "Make it 42",+ "--budget",+ "600",+ "--layout",+ "standard",+ "--branch",+ "focused",+ "--focus",+ "src/zebra.go:4",+ "--json",+ ],+ )+ .await;+ let report = printed(&focused);+ assert!(focused.status.success(), "{report}");+ assert_eq!(+ report["focus"],+ json!([{"path":"src/zebra.go","start_line":1,"end_line":44}])+ );+ let requests = mock.requests.lock().unwrap().clone();+ let plan = |i: usize| requests[i]["input"].as_str().unwrap().to_string();+ assert!(!plan(0).contains("Zebra paints stripes"));+ let focused_plan = requests+ .iter()+ .skip(1)+ .find(|r| {+ !r["instructions"]+ .as_str()+ .unwrap_or("")+ .starts_with("You fix")+ })+ .unwrap();+ assert!(+ focused_plan["input"]+ .as_str()+ .unwrap()+ .contains("Zebra paints stripes")+ );+ let refused = run(+ root,+ &["fix", "Make it 42", "--focus", "src/answer.go:0", "--json"],+ )+ .await;+ assert!(!refused.status.success());+ assert!(String::from_utf8_lossy(&refused.stderr).contains("--focus"));+ server.abort();+}++/// `--commit` runs no hook: not the person's own (post-checkout, as the+/// worktree is made), and not the ones the model edited in the round.+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn hooks_never_run_even_ones_the_model_edited() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ let edited = |hook: &str| {+ json!({"path":format!(".githooks/{hook}"),"search":"exit 0\n",+ "replace":format!("touch '{}'\nexit 0\n", root.join(format!("{hook}-model-ran")).display())})+ };+ mock.script+ .lock()+ .unwrap()+ .push(json!({"explanation":"See src/answer.go:5.",+ "edits":[{"path":"src/answer.go","search":"\treturn 41\n","replace":"\treturn 42\n"},+ edited("pre-commit"), edited("post-commit")],+ "new_files":[],"tests":[]}));+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = hooked_repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(root, &["fix", "Make it 42", "--commit", "--json"]).await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert!(report["committed"].is_string(), "{report}");+ for marker in [+ "pre-commit-ran",+ "post-commit-ran",+ "post-checkout-ran",+ "pre-commit-model-ran",+ "post-commit-model-ran",+ ] {+ assert!(!root.join(marker).exists(), "{marker}");+ }+ server.abort();+}++/// Variables that would point git at another repository are not passed on.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn git_ignores_variables_that_point_it_elsewhere() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let elsewhere = root.join("elsewhere");+ let elsewhere = elsewhere.to_str().unwrap();+ let fixed = run_env(+ root,+ &["fix", "Make it 42", "--test", "sh check.sh", "--json"],+ &[+ ("GIT_DIR", elsewhere),+ ("GIT_WORK_TREE", elsewhere),+ ("GIT_INDEX_FILE", elsewhere),+ ],+ )+ .await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert_eq!(report["result"], "passed");+ let branch = report["branch"].as_str().unwrap();+ assert_eq!(+ git(&project, &["branch", "--list", branch]).trim_start_matches(['*', '+', ' ']),+ branch+ );+ server.abort();+}++/// META_API_KEY, which Muse Code reads the Meta key from, is one of the+/// variables a test command never gets, and its value is not in the report.+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_test_command_gets_no_meta_key() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let secret = "meta-fixture-0123456789abcdef";+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run_env(+ root,+ &[+ "fix",+ "Make it 42",+ "--test",+ "echo \"meta=[$META_API_KEY]\"; sh check.sh",+ "--rounds",+ "1",+ "--json",+ ],+ &[("META_API_KEY", secret)],+ )+ .await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ let tail = report["rounds"][0]["test"]["output_tail"].as_str().unwrap();+ assert!(tail.contains("meta=[]"), "{tail}");+ assert!(!report.to_string().contains(secret));+ server.abort();+}++/// The test command runs without the variable the model key is read from,+/// and the key's value never reaches the model or the report.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_test_command_gets_no_model_key() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let secret = "sk-fixture-0123456789abcdef";+ let mock = Mock::default();+ mock.script.lock().unwrap().extend([+ edit("src/answer.go", "\treturn 41\n", "\treturn 40\n"),+ edit("src/answer.go", "\treturn 40\n", "\treturn 39\n"),+ ]);+ let (base, server) = serve(mock.clone()).await;+ models_with(root, &base, json!({"key_env":"FIX_TEST_MODEL_KEY"}));+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ // A test that reads the key some other way: from a file outside the+ // repository, and on Linux from graphicle's own environment+ // (/proc/$PPID/environ), printed shifted (a to b) so that the output's+ // redaction would not hide it.+ let stash = root.join("stash.txt");+ std::fs::write(&stash, secret).unwrap();+ let probe = if cfg!(target_os = "linux") {+ "if tr 'a-z' 'b-za' < /proc/$PPID/environ; then echo environ=read; else echo environ=refused; fi; "+ } else {+ ""+ };+ let test = format!(+ "echo \"key=[$FIX_TEST_MODEL_KEY]\"; echo leaked $(cat '{}'); {probe}exit 1",+ stash.display()+ );+ let shifted: String = secret+ .chars()+ .map(|c| match c {+ 'a'..='y' => char::from(c as u8 + 1),+ 'z' => 'a',+ c => c,+ })+ .collect();+ let fixed = run_env(+ root,+ &[+ "fix",+ "Make it 42",+ "--test",+ &test,+ "--rounds",+ "2",+ "--json",+ ],+ &[("FIX_TEST_MODEL_KEY", secret)],+ )+ .await;+ let report = printed(&fixed);+ assert_eq!(report["result"], "failed", "{report}");+ let tail = report["rounds"][0]["test"]["output_tail"].as_str().unwrap();+ assert!(+ tail.contains("key=[]") && tail.contains("leaked [redacted]"),+ "{tail}"+ );+ if cfg!(target_os = "linux") {+ assert!(tail.contains("environ=refused"), "{tail}");+ }+ let stdout = String::from_utf8_lossy(&fixed.stdout);+ assert!(!stdout.contains(secret) && !stdout.contains(&shifted));+ let requests = mock.requests.lock().unwrap();+ assert!(+ requests+ .iter()+ .all(|r| !r.to_string().contains(secret) && !r.to_string().contains(&shifted))+ );+ drop(requests);+ server.abort();+}++/// A profile stored in the workspace (not in the configuration file) has its+/// key variable removed from the test command's environment too.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_key_of_a_profile_stored_in_the_workspace_is_removed_too() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let secret = "sk-stored-fedcba9876543210";+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 40\n"));+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ {+ let store = graphicle_runtime::store::Store::open(root.join("data")).unwrap();+ let session = graphicle_runtime::local::session(&store, false).unwrap();+ let profile = json!({"protocol":"responses","base_url":"https://api.example.com/v1",+ "model":"stored-1","key_env":"FIX_STORED_MODEL_KEY","input_limit":60_000,+ "output_limit":4_000});+ store+ .connect()+ .unwrap()+ .execute(+ "INSERT INTO am_model_profiles VALUES(?,?,?,0,0)",+ rusqlite::params![session.workspace, "stored", profile.to_string()],+ )+ .unwrap();+ }+ let fixed = run_env(+ root,+ &[+ "fix",+ "Make it 42",+ "--test",+ "echo \"stored=[$FIX_STORED_MODEL_KEY]\"; exit 1",+ "--rounds",+ "1",+ "--json",+ ],+ &[("FIX_STORED_MODEL_KEY", secret)],+ )+ .await;+ let report = printed(&fixed);+ assert_eq!(report["result"], "failed", "{report}");+ let tail = report["rounds"][0]["test"]["output_tail"].as_str().unwrap();+ assert!(tail.contains("stored=[]"), "{tail}");+ assert!(!String::from_utf8_lossy(&fixed.stdout).contains(secret));+ let requests = mock.requests.lock().unwrap();+ assert!(requests.iter().all(|r| !r.to_string().contains(secret)));+ drop(requests);+ server.abort();+}++/// The user's own configuration files stay: GIT_CONFIG_GLOBAL, with the+/// commit identity, and GIT_CONFIG_NOSYSTEM (the system file named here+/// cannot be read). The command line's core.hooksPath still wins over the+/// hooks folder they name.+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn git_keeps_the_users_configuration_files_but_not_their_hooks() {+ use std::os::unix::fs::PermissionsExt;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let hooks = root.join("global-hooks");+ std::fs::create_dir_all(&hooks).unwrap();+ let names = ["pre-commit", "commit-msg", "post-commit", "post-checkout"];+ for hook in names {+ let path = hooks.join(hook);+ let marker = root.join(format!("{hook}-ran"));+ std::fs::write(+ &path,+ format!("#!/bin/sh\ntouch '{}'\nexit 0\n", marker.display()),+ )+ .unwrap();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ let global = root.join("global.gitconfig");+ std::fs::write(+ &global,+ format!(+ "[user]\n\tname = Global Fixture\n\temail = [email protected]\n[core]\n\thooksPath = {}\n",+ hooks.display()+ ),+ )+ .unwrap();+ let system = root.join("system.gitconfig");+ std::fs::write(&system, "[user\n").unwrap();+ let args: Vec<String> = [+ "fix",+ "Make it 42",+ "--test",+ "sh check.sh",+ "--commit",+ "--json",+ ]+ .iter()+ .map(|a| a.to_string())+ .collect();+ let env: Vec<(String, String)> = [+ ("GIT_CONFIG_GLOBAL", global.display().to_string()),+ ("GIT_CONFIG_SYSTEM", system.display().to_string()),+ ("GIT_CONFIG_NOSYSTEM", "1".to_string()),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v))+ .collect();+ let home = root.to_path_buf();+ let fixed = tokio::task::spawn_blocking(move || graphicle_as(&home, &args, &env, false))+ .await+ .unwrap();+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert_eq!(report["result"], "passed", "{report}");+ let commit = report["committed"].as_str().unwrap();+ assert_eq!(+ git(+ &project,+ &["log", "-1", "--format=%an <%ae>|%cn <%ce>", commit]+ ),+ "Global Fixture <[email protected]>|Global Fixture <[email protected]>"+ );+ for hook in names {+ assert!(!root.join(format!("{hook}-ran")).exists(), "{hook}");+ }+ server.abort();+}++/// A cap that refuses the plan leaves no branch and no worktree behind.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn nothing_is_made_before_the_plan() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ models_with(root, &base, json!({"max_cost_per_call":0.0001}));+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(root, &["fix", "Make it 42", "--test", "sh check.sh"]).await;+ assert!(!fixed.status.success());+ assert!(String::from_utf8_lossy(&fixed.stderr).contains("models.wonder.max_cost_per_call"));+ assert!(mock.requests.lock().unwrap().is_empty());+ assert_eq!(git(&project, &["branch", "--list", "graphicle/*"]), "");+ let made: Vec<String> = std::fs::read_dir(root.join("data/fix"))+ .map(|entries| {+ entries+ .flatten()+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .filter(|name| name != "no-hooks")+ .collect()+ })+ .unwrap_or_default();+ assert!(made.is_empty(), "{made:?}");+ server.abort();+}++/// What a round adds (here a long plan) cannot take its request over the+/// window: the pack part is made smaller first.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn each_round_is_fitted_to_the_window() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ *mock.plan_padding.lock().unwrap() = 90_000;+ *mock.window.lock().unwrap() = Some(30_000);+ mock.script+ .lock()+ .unwrap()+ .push(edit("src/answer.go", "\treturn 41\n", "\treturn 42\n"));+ let (base, server) = serve(mock.clone()).await;+ models_with(root, &base, json!({"input_limit":30_000}));+ let project = repository(root);+ for i in 0..60 {+ std::fs::write(+ project.join(format!("src/more{i}.go")),+ format!("package answer\n\n// More{i} adds to the answer.\nfunc More{i}() int {{\n{}\treturn {i}\n}}\n", "\t_ = Answer()\n".repeat(60)),+ )+ .unwrap();+ }+ git(&project, &["add", "-A"]);+ git(&project, &["commit", "-q", "-m", "More"]);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(root, &["fix", "Make it 42", "--json"]).await;+ let report = printed(&fixed);+ assert!(fixed.status.success(), "{report}");+ assert_eq!(report["result"], "untested");+ assert_eq!(*mock.over_window.lock().unwrap(), 0);+ let requests = mock.requests.lock().unwrap();+ let length = |r: &Value| r["input"].as_str().unwrap().len();+ // The round's request carries the long plan, yet its pack part shrank.+ let (plan, round) = (length(&requests[0]), length(&requests[1]));+ assert!(round < plan + 90_000, "plan {plan}, round {round}");+ drop(requests);+ server.abort();+}++/// A provider's refusal of a round is reported as the provider's error.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_provider_error_in_a_round_is_reported_as_one() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let mock = Mock::default();+ *mock.refuse_edits.lock().unwrap() = true;+ let (base, server) = serve(mock.clone()).await;+ models(root, &base);+ let project = repository(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ let fixed = run(+ root,+ &["fix", "Make it 42", "--test", "sh check.sh", "--json"],+ )+ .await;+ assert!(!fixed.status.success());+ let report = printed(&fixed);+ assert_eq!(report["result"], "provider error", "{report}");+ let error = report["rounds"][0]["error"].as_str().unwrap();+ assert!(error.contains("refused by the fixture"), "{error}");+ assert!(String::from_utf8_lossy(&fixed.stderr).contains("refused by the fixture"));+ assert_eq!(report["rounds"].as_array().unwrap().len(), 1);+ server.abort();+}++/// --timeout takes 1 to 86400 seconds, as the configuration does.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_timeout_is_checked() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ for bad in ["0", "86401"] {+ let refused = run(root, &["fix", "Make it 42", "--timeout", bad]).await;+ assert!(!refused.status.success());+ assert!(+ String::from_utf8_lossy(&refused.stderr).contains("--timeout"),+ "{}",+ String::from_utf8_lossy(&refused.stderr)+ );+ }+}diff --git a/crates/graphicle/tests/it/long_context_cache.rs b/crates/graphicle/tests/it/long_context_cache.rsnew file mode 100644index 0000000..14022ca--- /dev/null+++ b/crates/graphicle/tests/it/long_context_cache.rs@@ -0,0 +1,584 @@+//! `ask --pack` and `plan` against a mock of the Meta Model API's Responses+//! endpoints that behaves like its prompt cache: the cache key, retention,+//! reasoning effort and output cap are sent; a follow-up question on the same+//! repository reports cached tokens and the spend log records them; each cap+//! refuses before anything is sent; `graphicle usage` adds the log up; and the+//! provider's exact count shrinks a pack that would not fit.+use axum::{Json, Router, extract::State, routing::post};+use serde_json::{Value, json};+use std::{+ collections::HashMap,+ path::{Path, PathBuf},+ process::{Command, Output, Stdio},+ sync::{Arc, Mutex},+};+use tempfile::TempDir;++/// What the mock saw, and the last prompt of each cache key.+#[derive(Clone, Default)]+struct Mock {+ requests: Arc<Mutex<Vec<Value>>>,+ counts: Arc<Mutex<Vec<Value>>>,+ last: Arc<Mutex<HashMap<String, String>>>,+ /// Bytes per token of the `input_tokens` endpoint's count (0: four).+ count_rate: Arc<Mutex<f64>>,+ /// Bytes per token of the input usage a response reports (0: four).+ usage_rate: Arc<Mutex<f64>>,+}++/// The prompt as the provider sees it: the instructions, then the input.+fn prompt_of(request: &Value) -> String {+ format!(+ "{}{}",+ request["instructions"].as_str().unwrap_or(""),+ request["input"].as_str().unwrap_or("")+ )+}++/// A completed response whose usage looks real: input tokens are the+/// prompt's bytes over the usage rate (four unless set); cached tokens are+/// the start the prompt shares with the last one of its cache key, counted+/// from 1,024 tokens up.+async fn responses(State(mock): State<Mock>, Json(request): Json<Value>) -> Json<Value> {+ let prompt = prompt_of(&request);+ let rate = match *mock.usage_rate.lock().unwrap() {+ r if r > 0.0 => r,+ _ => 4.0,+ };+ let input = (prompt.len() as f64 / rate) as u64;+ let mut cached = 0;+ if let Some(key) = request["prompt_cache_key"].as_str() {+ let mut last = mock.last.lock().unwrap();+ if let Some(previous) = last.get(key) {+ let common = previous+ .bytes()+ .zip(prompt.bytes())+ .take_while(|(a, b)| a == b)+ .count() as u64+ / 4;+ if common >= 1024 {+ cached = common;+ }+ }+ last.insert(key.to_string(), prompt.clone());+ }+ mock.requests.lock().unwrap().push(request.clone());+ let text = if request["text"]["format"]["type"] == "json_schema" {+ json!({"summary":"Start the canary first.","steps":["Edit the canary"],+ "edits":[{"path":"pkg/release/file0.go","start_line":1,"end_line":2,"reason":"the start"}],+ "new_files":[],"tests":[],"risks":[]})+ .to_string()+ } else {+ "The canary starts in pkg/release/file0.go:3.".to_string()+ };+ Json(json!({"status":"completed","model":request["model"],+ "usage":{"input_tokens":input,"input_tokens_details":{"cached_tokens":cached},+ "output_tokens":40,"output_tokens_details":{"reasoning_tokens":25},"total_tokens":input + 40},+ "output":[{"type":"message","content":[{"type":"output_text","text":text}]}]}))+}++/// `POST /v1/responses/input_tokens`: the prompt's bytes over the count rate.+async fn input_tokens(State(mock): State<Mock>, Json(request): Json<Value>) -> Json<Value> {+ let rate = match *mock.count_rate.lock().unwrap() {+ r if r > 0.0 => r,+ _ => 4.0,+ };+ mock.counts.lock().unwrap().push(request.clone());+ let tokens = (prompt_of(&request).len() as f64 / rate).ceil() as u64;+ Json(json!({"object":"response.input_tokens","input_tokens":tokens}))+}++async fn serve(mock: Mock) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = Router::new()+ .route("/v1/responses", post(responses))+ .route("/v1/responses/input_tokens", post(input_tokens))+ .with_state(mock);+ let server = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ (format!("http://{address}/v1"), server)+}++fn graphicle(dir: &Path, args: &[String]) -> Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ crate::child_env::home(&mut command, dir)+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--config")+ .arg(dir.join("models.json"))+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ crate::fork_guard::spawn(&mut command)+ .unwrap()+ .wait_with_output()+ .unwrap()+}++/// The program blocks; the provider keeps serving on the other workers.+async fn run(root: &Path, args: &[&str]) -> Output {+ let root = root.to_path_buf();+ let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();+ tokio::task::spawn_blocking(move || graphicle(&root, &args))+ .await+ .unwrap()+}++fn json_of(output: &Output) -> Value {+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ serde_json::from_slice(&output.stdout).unwrap()+}++/// A Go project of `n` files in four packages, with a README.+fn project(root: &Path, n: usize) -> PathBuf {+ let project = root.join("project");+ for i in 0..n {+ let folder = ["pkg/release", "pkg/canary", "cmd/ship", "internal/check"][i % 4];+ std::fs::create_dir_all(project.join(folder)).unwrap();+ let mut text = String::from("package x\n\n");+ for f in 0..6 {+ text.push_str(&format!(+ "// Step{i}x{f} runs step {f} of release stage {i}.\nfunc Step{i}x{f}() {{\n"+ ));+ for k in 0..8 {+ text.push_str(&format!(+ "\tvalue{k} := check(\"stage {i} canary {f} gate {k}\")\n"+ ));+ }+ if f > 0 {+ text.push_str(&format!("\tStep{i}x{}()\n", f - 1));+ }+ text.push_str("}\n\n");+ }+ std::fs::write(project.join(format!("{folder}/file{i}.go")), text).unwrap();+ }+ std::fs::write(+ project.join("README.md"),+ "# Ship\n\nShip releases behind a canary and a signed checklist.\n",+ )+ .unwrap();+ project+}++fn models(root: &Path, base: &str, extra: Value) {+ let mut meta = json!({"protocol":"responses","base_url":base,"model":"muse-spark-1.3",+ "input_limit":60_000,"output_limit":2_048,"prompt_cache":true,"reasoning_effort":"low",+ "price":{"input":1.25,"output":4.25,"cached_input":0.15}});+ for (k, v) in extra.as_object().unwrap() {+ meta[k] = v.clone();+ }+ std::fs::write(+ root.join("models.json"),+ json!({"default_model":"meta","models":{"meta":meta}}).to_string(),+ )+ .unwrap();+}++fn log_of(root: &Path) -> Vec<Value> {+ std::fs::read_to_string(root.join("data/usage.jsonl"))+ .unwrap_or_default()+ .lines()+ .map(|line| serde_json::from_str(line).unwrap())+ .collect()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn follow_up_questions_hit_the_cache_and_the_spend_log_records_them() {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base, json!({}));+ let project = project(root, 24);+ json_of(&run(root, &["sync", project.to_str().unwrap()]).await);++ let ask = |question: &'static str| {+ let root = root.to_path_buf();+ async move {+ json_of(+ &run(+ &root,+ &[+ "ask", "--pack", "--layout", "cache", "--budget", "20000", "--json",+ question,+ ],+ )+ .await,+ )+ }+ };+ let first = ask("How does the canary start?").await;+ let second = ask("Where is the signed checklist checked?").await;+ let key = first["prompt_cache_key"].as_str().unwrap().to_string();+ assert!(key.starts_with("graphicle:project@"), "{key}");+ assert_eq!(second["prompt_cache_key"], key.as_str());+ assert!(!key.contains("canary") && !key.contains("checklist"));+ assert_eq!(first["pack"]["layout"], "cache");+ assert_eq!(+ first["pack"]["prefix_sha256"],+ second["pack"]["prefix_sha256"]+ );+ assert!(key.ends_with(&first["pack"]["prefix_sha256"].as_str().unwrap()[..12]));+ // The first question warms the cache; the follow-up reads the shared+ // instructions and repository part from it.+ assert_eq!(first["usage"]["cached_tokens"], 0);+ let cached = second["usage"]["cached_tokens"].as_u64().unwrap();+ let prefix = first["pack"]["prefix_tokens"].as_u64().unwrap();+ assert!(cached >= 1024, "{second}");+ assert!(+ cached * 10 >= prefix * 8,+ "{cached} of a {prefix}-token prefix"+ );+ {+ let requests = mock.requests.lock().unwrap();+ assert_eq!(requests.len(), 2);+ for request in requests.iter() {+ assert_eq!(request["prompt_cache_key"], key.as_str());+ assert_eq!(request["prompt_cache_retention"], "24h");+ assert_eq!(request["reasoning"]["effort"], "low");+ assert_eq!(request["max_output_tokens"], 2_048);+ assert_eq!(request["instructions"], requests[0]["instructions"]);+ // The question comes after the pack.+ assert!(request["input"].as_str().unwrap().trim_end().ends_with('?'));+ }+ }+ // The spend log: one line per call, the cached tokens and the cost at+ // the configured price, never the prompt or the answer.+ let log = log_of(root);+ assert_eq!(log.len(), 2, "{log:?}");+ assert_eq!(log[1]["cached_tokens"], cached);+ assert_eq!(log[1]["command"], "ask --pack");+ assert_eq!(log[1]["profile"], "meta");+ assert_eq!(log[1]["model"], "muse-spark-1.3");+ assert_eq!(log[1]["prompt_cache_key"], key.as_str());+ assert_eq!(log[1]["status"], "ok");+ let raw = std::fs::read_to_string(root.join("data/usage.jsonl")).unwrap();+ assert!(!raw.contains("canary") && !raw.contains("Ship releases"));+ let input = log[1]["input_tokens"].as_u64().unwrap() as f64;+ let expected =+ ((input - cached as f64) * 1.25 + cached as f64 * 0.15 + 40.0 * 4.25) / 1_000_000.0;+ assert!((log[1]["cost_usd"].as_f64().unwrap() - expected).abs() < 1e-6);+ assert_eq!(second["usage"]["cost_usd"], log[1]["cost_usd"]);++ // A plan on the same repository: its own call, logged too.+ let planned = json_of(+ &run(+ root,+ &[+ "plan",+ "--layout",+ "cache",+ "--budget",+ "20000",+ "--json",+ "Start the canary before the checklist",+ ],+ )+ .await,+ );+ assert_eq!(planned["prompt_cache_key"], key.as_str());+ assert_eq!(log_of(root).len(), 3);++ // The report adds the log up.+ let report = json_of(&run(root, &["usage", "--json"]).await);+ let log = log_of(root);+ let sum = |field: &str| log.iter().map(|e| e[field].as_u64().unwrap()).sum::<u64>();+ assert_eq!(report["total"]["calls"], 3);+ assert_eq!(report["total"]["input_tokens"], sum("input_tokens"));+ assert_eq!(report["total"]["cached_tokens"], sum("cached_tokens"));+ assert_eq!(report["total"]["output_tokens"], sum("output_tokens"));+ let cost: f64 = log.iter().map(|e| e["cost_usd"].as_f64().unwrap()).sum();+ assert!((report["total"]["cost_usd"].as_f64().unwrap() - cost).abs() < 1e-6);+ assert_eq!(report["days"][0]["model"], "muse-spark-1.3");+ let today = json_of(&run(root, &["usage", "--json", "--since", "2999-01-01"]).await);+ assert_eq!(today["total"]["calls"], 0);+ let text = run(root, &["usage"]).await;+ assert!(text.status.success());+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn each_cap_refuses_before_anything_is_sent() {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let project = project(root, 8);+ models(root, &base, json!({}));+ json_of(&run(root, &["sync", project.to_str().unwrap()]).await);+ let ask = [+ "ask",+ "--pack",+ "--budget",+ "8000",+ "--json",+ "How does the canary start?",+ ];++ // A call whose worst case is over max_cost_per_call.+ models(root, &base, json!({"max_cost_per_call":0.001}));+ let refused = run(root, &ask).await;+ assert!(!refused.status.success());+ let message = String::from_utf8_lossy(&refused.stderr);+ assert!(message.contains("max_cost_per_call"), "{message}");+ assert!(+ message.contains("models.meta.max_cost_per_call"),+ "{message}"+ );+ assert!(mock.requests.lock().unwrap().is_empty());+ assert!(log_of(root).is_empty());++ // A day cap with room: the call goes out, and the log holds its cost+ // and its worst case.+ models(root, &base, json!({"max_cost_per_day":10.0}));+ json_of(&run(root, &ask).await);+ let logged = &log_of(root)[0];+ let (cost, worst) = (+ logged["cost_usd"].as_f64().unwrap(),+ logged["worst_cost_usd"].as_f64().unwrap(),+ );+ assert!(cost > 0.0 && worst > cost, "{logged}");+ // Today's spend with this call's worst case would pass the day cap: the+ // call is refused, though the logged total alone is under the cap.+ models(root, &base, json!({"max_cost_per_day":cost + worst / 2.0}));+ let refused = run(root, &ask).await;+ assert!(!refused.status.success());+ let message = String::from_utf8_lossy(&refused.stderr);+ assert!(+ message.contains("models.meta.max_cost_per_day"),+ "{message}"+ );+ assert_eq!(mock.requests.lock().unwrap().len(), 1);+ // A spend log that cannot be read refuses capped calls.+ std::fs::rename(root.join("data/usage.jsonl"), root.join("data/usage.saved")).unwrap();+ std::fs::create_dir(root.join("data/usage.jsonl")).unwrap();+ models(root, &base, json!({"max_cost_per_day":10.0}));+ let refused = run(root, &ask).await;+ assert!(!refused.status.success());+ assert!(String::from_utf8_lossy(&refused.stderr).contains("Cannot read the spend log"));+ assert_eq!(mock.requests.lock().unwrap().len(), 1);+ std::fs::remove_dir(root.join("data/usage.jsonl")).unwrap();+ std::fs::rename(root.join("data/usage.saved"), root.join("data/usage.jsonl")).unwrap();++ // A cap needs the price it is counted at.+ models(root, &base, json!({"max_cost_per_day":1.0,"price":null}));+ let invalid = run(root, &ask).await;+ assert!(!invalid.status.success());+ assert!(String::from_utf8_lossy(&invalid.stderr).contains("models.meta.price"));+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_providers_exact_count_shrinks_a_pack_that_would_not_fit() {+ let mock = Mock::default();+ // The provider counts twice the tokens of the estimate's bytes.+ *mock.count_rate.lock().unwrap() = 1.75;+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ let project = project(root, 160);+ models(+ root,+ &base,+ json!({"input_limit":40_000,"count_tokens":true}),+ );+ json_of(&run(root, &["sync", project.to_str().unwrap()]).await);+ // The cache layout fills its repository part whatever the question.+ let asked = json_of(+ &run(+ root,+ &[+ "ask",+ "--pack",+ "--layout",+ "cache",+ "--json",+ "How does the canary start?",+ ],+ )+ .await,+ );+ let counted = asked["input_tokens_counted"].as_u64().unwrap_or_else(|| {+ panic!(+ "not counted: {} counts, pack {}",+ mock.counts.lock().unwrap().len(),+ asked["pack"]+ )+ });+ assert!(counted <= 40_000, "{asked}");+ let budget = 40_000 - 4_000;+ assert!(+ asked["pack"]["budget"].as_u64().unwrap() < budget,+ "{asked}"+ );+ {+ let counts = mock.counts.lock().unwrap();+ assert!(counts.len() >= 2, "{}", counts.len());+ assert_eq!(counts[0]["model"], "muse-spark-1.3");+ assert!(counts[0].get("max_output_tokens").is_none());+ }+ // The call sent is the one counted last.+ let requests = mock.requests.lock().unwrap();+ assert_eq!(requests.len(), 1);+ let sent = (prompt_of(&requests[0]).len() as f64 / 1.75).ceil() as u64;+ assert_eq!(sent, counted);+ drop(requests);+ server.abort();+}++/// Without --budget, the budget moves with the calibration after each call;+/// the cache layout's repository part, sized from the budget before+/// calibration, stays the same bytes, and so does the cache key.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_repository_part_holds_while_the_calibration_moves_the_budget() {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base, json!({}));+ let project = project(root, 160);+ json_of(&run(root, &["sync", project.to_str().unwrap()]).await);+ let mut seen = Vec::new();+ for question in [+ "How does the canary start?",+ "Where is the signed checklist checked?",+ "Which stage runs the gate checks?",+ ] {+ let asked = json_of(+ &run(+ root,+ &["ask", "--pack", "--layout", "cache", "--json", question],+ )+ .await,+ );+ seen.push((+ asked["pack"]["budget"].as_u64().unwrap(),+ asked["pack"]["prefix_sha256"].as_str().unwrap().to_string(),+ asked["prompt_cache_key"].as_str().unwrap().to_string(),+ ));+ }+ let calibration = std::fs::read_to_string(root.join("data/pack-calibration.json")).unwrap();+ assert!(calibration.contains("\"calls\": 3"), "{calibration}");+ // The budget moved with the calibration...+ assert_ne!(seen[0].0, seen[1].0, "{seen:?}");+ // ...and the repository part and the cache key did not.+ assert!(+ seen.windows(2)+ .all(|w| w[0].1 == w[1].1 && w[0].2 == w[1].2),+ "{seen:?}"+ );+ server.abort();+}++/// A provider that counts more than Graphicle's estimate (a calibration+/// above 1) puts the calibrated budget below the repository part's share of+/// the fixed budget. The part then steps down to the first size that fits+/// (0.8 of it here) and holds there while the calibration moves within the+/// step, from the first calibrated call on.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_repository_part_holds_when_the_provider_counts_more() {+ // (the prefix share, the usage rates of the four calls, and the 0.8+ // step's bounds on the calibration: 0.97 / share, 0.97 / (0.8 * share));+ // the rates give a calibration near 1.1 and near 1.19.+ for (share, rates, within) in [+ ("1.0", [3.25, 3.4, 3.1, 3.3], (0.97, 1.21)),+ ("0.9", [3.0, 3.15, 2.9, 3.05], (1.08, 1.34)),+ ] {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base, json!({}));+ let project = project(root, 160);+ json_of(&run(root, &["sync", project.to_str().unwrap()]).await);+ let mut seen = Vec::new();+ for (rate, question) in rates.into_iter().zip([+ "How does the canary start?",+ "Where is the signed checklist checked?",+ "Which stage runs the gate checks?",+ "What does the rollback stage undo?",+ ]) {+ *mock.usage_rate.lock().unwrap() = rate;+ let asked = json_of(+ &run(+ root,+ &[+ "ask",+ "--pack",+ "--layout",+ "cache",+ "--prefix-share",+ share,+ "--json",+ question,+ ],+ )+ .await,+ );+ let calibration: Value = serde_json::from_str(+ &std::fs::read_to_string(root.join("data/pack-calibration.json")).unwrap(),+ )+ .unwrap();+ seen.push((+ asked["pack"]["budget"].as_u64().unwrap(),+ asked["pack"]["prefix_sha256"].as_str().unwrap().to_string(),+ calibration["meta"]["ratio"].as_f64().unwrap(),+ ));+ }+ // The calibration is above 1 and moves, and so does the budget...+ assert!(+ seen.iter().all(|s| s.2 > within.0 && s.2 < within.1),+ "{share}: {seen:?}"+ );+ assert!(+ seen[1].0 != seen[2].0 && seen[2].0 != seen[3].0,+ "{share}: {seen:?}"+ );+ // ...while the repository part holds from the first calibrated call.+ assert!(+ seen[1..].windows(2).all(|w| w[0].1 == w[1].1),+ "{share}: {seen:?}"+ );+ server.abort();+ }+}++/// `graphicle usage` lists the calls not logged yet that still count (not+/// one whose process ended, nor one older than the longest call), and+/// `--clear-pending` removes them all.+#[cfg(unix)]+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn usage_lists_and_clears_the_calls_not_logged_yet() {+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, "http://127.0.0.1:9/v1", json!({}));+ std::fs::create_dir_all(root.join("data")).unwrap();+ let mut ended = std::process::Command::new("true").spawn().unwrap();+ let ended_pid = ended.id();+ ended.wait().unwrap();+ let me = std::process::id();+ let at = |minutes: i64| {+ (chrono::Utc::now() - chrono::Duration::minutes(minutes))+ .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)+ };+ let held = json!({+ "running":{"profile":"meta","day":"2026-10-26","worst_cost_usd":0.5,"pid":me,"time":at(5)},+ "ended":{"profile":"meta","day":"2026-10-27","worst_cost_usd":0.5,"pid":ended_pid,"time":at(1)},+ "old":{"profile":"meta","day":"2026-10-26","worst_cost_usd":0.5,"pid":me,"time":at(120)}});+ std::fs::write(root.join("data/usage-pending.json"), held.to_string()).unwrap();+ let report = json_of(&run(root, &["usage", "--json"]).await);+ let pending = report["pending"].as_array().unwrap();+ assert_eq!(pending.len(), 1, "{report}");+ assert_eq!(pending[0]["pid"], me);+ let cleared = json_of(&run(root, &["usage", "--clear-pending", "--json"]).await);+ assert_eq!(cleared["cleared_pending"], 3, "{cleared}");+ assert_eq!(cleared["pending"], json!([]), "{cleared}");+ assert!(!root.join("data/usage-pending.json").exists());+}diff --git a/crates/graphicle/tests/it/main.rs b/crates/graphicle/tests/it/main.rsindex 1f9bbb8..8104f88 100644--- a/crates/graphicle/tests/it/main.rs+++ b/crates/graphicle/tests/it/main.rs@@ -41,6 +41,7 @@ mod embedding_workflow;mod evidence_windows;mod expansion;mod fault_isolation;+mod fix_command;mod forgetting;mod freshness;mod graph_always;@@ -53,6 +54,7 @@ mod invalidation;mod jobs_bounds;mod lean_replies;mod local_inference;+mod long_context_cache;mod memory_handoffs;mod memory_symbols;mod observer;@@ -60,6 +62,7 @@ mod offboard;mod one_server;mod passage_index;mod permissions_refresh;+mod pixel;mod product_workspace;mod project_identity;mod provider_http_hosts;@@ -72,8 +75,10 @@ mod release_0_4;mod rerank_depth;mod retention;mod retrieval_defaults;+mod review_command;mod revocation;mod scale_bounds;+mod see;mod selective_integration;mod service_gaps;mod store_compat;diff --git a/crates/graphicle/tests/it/one_server.rs b/crates/graphicle/tests/it/one_server.rsindex 093a876..f3a5dd1 100644--- a/crates/graphicle/tests/it/one_server.rs+++ b/crates/graphicle/tests/it/one_server.rs@@ -288,15 +288,16 @@ fn every_flag_combination_lists_each_tool_once() {// `graph_stats` is the engine's (Graphify's), once.assert_eq!(listed.iter().filter(|n| *n == "graph_stats").count(), 1);// A project connection's core tools: `list_projects` is a workspace- // connection's, the other 22 as the one server lists them.+ // connection's, the other 23 as the one server lists them, `pack` last.let core: Vec<String> = api::core_mcp_tools(false, false).into_iter().filter_map(McpTool::confined).map(|tool| tool.name().to_string()).collect();- assert_eq!(core.len(), 22, "{core:?}");- assert_eq!(core[15..], graph_tools::NAVIGATION.map(String::from));- assert_eq!(listed[..22], core[..], "the core tools lead the list");+ assert_eq!(core.len(), 23, "{core:?}");+ assert_eq!(core[15..22], graph_tools::NAVIGATION.map(String::from));+ assert_eq!(core[22], "pack");+ assert_eq!(listed[..23], core[..], "the core tools lead the list");assert!(!listed.contains(&"list_projects".to_string()));let pull = api::mcp_tools_for(false,diff --git a/crates/graphicle/tests/it/pixel.rs b/crates/graphicle/tests/it/pixel.rsnew file mode 100644index 0000000..9c3d57c--- /dev/null+++ b/crates/graphicle/tests/it/pixel.rs@@ -0,0 +1,396 @@+//! `graphicle pixel` against a mock of the Responses API: SAM 3.1 segments+//! the point (the documented point prompt and record format), the reading+//! model returns the element's strings, and the lookup finds the string+//! literal that draws it in a synced fixture repository. The spend log+//! records both calls under `pixel`, SAM's at its per-image price. With+//! --text the lookup runs alone, with no model call; a point SAM cannot+//! segment gets the area around it; --explain asks for a ranking from a+//! small pack and keeps only paths the project has.+use axum::{Json, Router, extract::State, routing::post};+use serde_json::{Value, json};+use std::{+ path::{Path, PathBuf},+ process::{Command, Output, Stdio},+ sync::{Arc, Mutex},+};+use tempfile::TempDir;++#[derive(Clone, Default)]+struct Mock {+ requests: Arc<Mutex<Vec<Value>>>,+ /// SAM finds no object at the point.+ sam_empty: Arc<Mutex<bool>>,+}++const RECORDS: &str = "<0f>1<|box;x1=10;y1=5;x2=90;y2=25;w=200;h=100;c=0.97|><|mask;x=10;y=5;c=0.97;data=20,80,!0a|b>c|>";++async fn responses(State(mock): State<Mock>, Json(request): Json<Value>) -> Json<Value> {+ mock.requests.lock().unwrap().push(request.clone());+ let model = request["model"].as_str().unwrap_or("").to_string();+ if model == "sam-3.1" {+ let text = if *mock.sam_empty.lock().unwrap() {+ ""+ } else {+ RECORDS+ };+ return Json(+ json!({"id":"resp_sam","object":"response","status":"completed",+ "model":"sam-3.1","output":[{"type":"message","role":"assistant",+ "content":[{"type":"output_text","text":text}]}]}),+ );+ }+ let instructions = request["instructions"].as_str().unwrap_or("");+ let text = if instructions.starts_with("You read one element") {+ json!({"strings":["Open Folder..."],"element_type":"button","icon":"",+ "nearby_labels":["Explorer"],"names":["workbench.action.files.openFolder"]})+ } else {+ json!({"ranking":[{"path":"src/ui/welcome.ts","line":4,"reason":"The button's label."},+ {"path":"no/such/file.ts","line":1,"reason":"Not in the project."}],+ "explanation":"src/ui/welcome.ts:4 gives the Open Folder button its label."})+ };+ Json(+ json!({"id":"resp_read","object":"response","status":"completed","model":model,+ "output":[{"type":"message","role":"assistant",+ "content":[{"type":"output_text","text":text.to_string()}]}],+ "usage":{"input_tokens":1500,"output_tokens":120,+ "input_tokens_details":{"cached_tokens":0},+ "output_tokens_details":{"reasoning_tokens":40}}}),+ )+}++async fn serve(mock: Mock) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = Router::new()+ .route("/v1/responses", post(responses))+ .with_state(mock);+ let server = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ (format!("http://{address}/v1"), server)+}++fn graphicle(dir: &Path, args: &[String]) -> Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ crate::child_env::home(&mut command, dir)+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--config")+ .arg(dir.join("models.json"))+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ crate::fork_guard::spawn(&mut command)+ .unwrap()+ .wait_with_output()+ .unwrap()+}++async fn run(root: &Path, args: &[&str]) -> Output {+ let root = root.to_path_buf();+ let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();+ tokio::task::spawn_blocking(move || graphicle(&root, &args))+ .await+ .unwrap()+}++fn printed(output: &Output) -> Value {+ serde_json::from_slice(&output.stdout).unwrap_or_else(|_| {+ panic!(+ "no JSON: {}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ })+}++fn models(root: &Path, base: &str) {+ let spark = json!({"protocol":"responses","base_url":base,"model":"muse-spark-1.3",+ "input_limit":60_000,"output_limit":4_000,"reasoning_effort":"medium",+ "price":{"input":1.25,"output":4.25,"cached_input":0.15}});+ let sam = json!({"protocol":"responses","base_url":base,"model":"sam-3.1",+ "price":{"input":0.0,"output":0.0,"per_image":0.0025}});+ std::fs::write(+ root.join("models.json"),+ json!({"default_model":"spark","models":{"spark":spark,"sam":sam}}).to_string(),+ )+ .unwrap();+}++fn repository(root: &Path) -> PathBuf {+ let project = root.join("project");+ for folder in ["src/ui", "src/test"] {+ std::fs::create_dir_all(project.join(folder)).unwrap();+ }+ let files = [+ (+ "src/ui/welcome.ts",+ "import { localize } from '../nls';\n\nexport const actions = [\n\t{ id: 'workbench.action.files.openFolder', label: localize('openFolder', \"Open &&Folder...\") },\n\t{ id: 'workbench.action.files.newFile', label: localize('newFile', \"New File...\") },\n];\n\nexport function renderWelcome(container: HTMLElement) {\n\tfor (const action of actions) {\n\t\tcontainer.append(button(action.label));\n\t}\n}\n",+ ),+ (+ "src/ui/explorer.ts",+ "import { localize } from '../nls';\nexport const EXPLORER_TITLE = localize('explorer', \"Explorer\");\nexport function emptyMessage() {\n\treturn localize('noFolder', \"You have not yet opened a folder.\");\n}\n",+ ),+ (+ "src/test/welcome.test.ts",+ "import * as assert from 'assert';\nassert.strictEqual(label, 'Open Folder...');\n",+ ),+ ("README.md", "# Fixture\n\nUse Open Folder... to start.\n"),+ ];+ for (path, text) in files {+ std::fs::write(project.join(path), text).unwrap();+ }+ project+}++/// A PNG's signature and header (200 x 100): all `pixel` reads of it.+fn screenshot(root: &Path) -> PathBuf {+ let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();+ bytes.extend_from_slice(&200u32.to_be_bytes());+ bytes.extend_from_slice(&100u32.to_be_bytes());+ bytes.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]);+ let path = root.join("shot.png");+ std::fs::write(&path, bytes).unwrap();+ path+}++fn pixel_log(root: &Path) -> Vec<Value> {+ std::fs::read_to_string(root.join("data").join("usage.jsonl"))+ .unwrap_or_default()+ .lines()+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())+ .filter(|e| e["command"] == "pixel")+ .collect()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_point_is_segmented_read_and_found_in_the_code() {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ let shot = screenshot(root);+ let synced = run(root, &["sync", project.to_str().unwrap()]).await;+ assert!(+ synced.status.success(),+ "{}",+ String::from_utf8_lossy(&synced.stderr)+ );++ let out = run(+ root,+ &["pixel", shot.to_str().unwrap(), "--at", "50,15", "--json"],+ )+ .await;+ assert!(+ out.status.success(),+ "{}",+ String::from_utf8_lossy(&out.stderr)+ );+ let report = printed(&out);+ // SAM's box, its confidence and its (undecoded) one-bit mask.+ let b = &report["box"];+ assert_eq!(+ (+ b["x1"].as_u64(),+ b["y1"].as_u64(),+ b["x2"].as_u64(),+ b["y2"].as_u64()+ ),+ (Some(10), Some(5), Some(90), Some(25)),+ "{report}"+ );+ assert_eq!(b["from"], "sam");+ assert_eq!(b["model"], "sam-3.1");+ assert_eq!(b["confidence"], 0.97);+ assert_eq!(+ b["mask"],+ json!({"rows":20,"columns":80,"encoding":"one_bit"})+ );+ assert_eq!(report["read"]["strings"], json!(["Open Folder..."]));+ assert_eq!(report["screenshot"]["width"], 200);+ // The string that draws the button: the localized label, not the test+ // or the README.+ let first = &report["candidates"][0];+ assert_eq!(first["path"], "src/ui/welcome.ts", "{report}");+ assert_eq!(first["line"], 4);+ let paths: Vec<&str> = report["candidates"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|c| c["path"].as_str())+ .collect();+ let test = paths+ .iter()+ .position(|p| *p == "src/test/welcome.test.ts")+ .unwrap();+ assert!(test > 0);+ eprintln!("graph read: {}", report["lookup"]["graph"]);++ // The requests: SAM's point prompt in source pixels with the image as a+ // data URL; the reading call with the point, the box and the image.+ let requests = mock.requests.lock().unwrap().clone();+ assert_eq!(requests.len(), 2);+ let sam = &requests[0];+ assert_eq!(sam["model"], "sam-3.1");+ let content = &sam["input"][0]["content"];+ assert_eq!(content[0]["text"], "<0f>1<|point;x=50;y=15;w=200;h=100|>");+ assert!(+ content[1]["image_url"]+ .as_str()+ .unwrap()+ .starts_with("data:image/png;base64,iVBORw0KGgo")+ );+ assert_eq!(sam["metadata"]["include_confidence"], "true");+ let read = &requests[1];+ assert_eq!(read["model"], "muse-spark-1.3");+ assert!(+ read["instructions"]+ .as_str()+ .unwrap()+ .starts_with("You read one element")+ );+ let text = read["input"][0]["content"][0]["text"].as_str().unwrap();+ assert!(+ text.contains("x=50, y=15") && text.contains("from (10, 5) to (90, 25)"),+ "{text}"+ );+ assert_eq!(read["input"][0]["content"][1]["type"], "input_image");+ assert!(read.get("prompt_cache_key").is_none());++ // The spend log: SAM at its per-image price, the reading at its tokens.+ let log = pixel_log(root);+ assert_eq!(log.len(), 2, "{log:?}");+ assert_eq!(+ (log[0]["profile"].as_str(), log[0]["model"].as_str()),+ (Some("sam"), Some("sam-3.1"))+ );+ assert!((log[0]["cost_usd"].as_f64().unwrap() - 0.0025).abs() < 1e-12);+ let read_cost = (1500.0 * 1.25 + 120.0 * 4.25) / 1_000_000.0;+ assert!((log[1]["cost_usd"].as_f64().unwrap() - read_cost).abs() < 1e-12);+ assert_eq!(log[1]["input_tokens"], 1500);+ assert!((report["cost_usd"].as_f64().unwrap() - (0.0025 + read_cost)).abs() < 1e-9);+ assert_eq!(report["calls"][0]["step"], "segment");+ assert_eq!(report["calls"][1]["step"], "read");++ // Nothing segmented at the point: the area around it, and a note.+ *mock.sam_empty.lock().unwrap() = true;+ let out = run(+ root,+ &["pixel", shot.to_str().unwrap(), "--at", "50,15", "--json"],+ )+ .await;+ let report = printed(&out);+ assert_eq!(report["box"]["from"], "around the point");+ assert_eq!(+ (report["box"]["x1"].as_u64(), report["box"]["x2"].as_u64()),+ (Some(0), Some(199))+ );+ assert!(report["notes"][0].as_str().unwrap().contains("no object"));+ assert_eq!(report["candidates"][0]["path"], "src/ui/welcome.ts");++ // The text given: the lookup alone, no model call, nothing logged.+ let before = mock.requests.lock().unwrap().len();+ let out = run(+ root,+ &[+ "pixel",+ "--text",+ "You have not yet opened a folder.",+ "--json",+ ],+ )+ .await;+ let report = printed(&out);+ assert_eq!(+ report["candidates"][0]["path"], "src/ui/explorer.ts",+ "{report}"+ );+ assert_eq!(report["candidates"][0]["line"], 4);+ assert_eq!(report["calls"], json!([]));+ assert_eq!(mock.requests.lock().unwrap().len(), before);+ assert_eq!(pixel_log(root).len(), 4);++ // --explain: one call with a small pack; a path the project lacks is+ // dropped from the model's ranking.+ let out = run(+ root,+ &[+ "pixel",+ "--text",+ "Open Folder...",+ "--explain",+ "--budget",+ "4000",+ "--json",+ ],+ )+ .await;+ assert!(+ out.status.success(),+ "{}",+ String::from_utf8_lossy(&out.stderr)+ );+ let report = printed(&out);+ assert_eq!(+ report["explain"]["ranking"].as_array().unwrap().len(),+ 1,+ "{report}"+ );+ assert_eq!(report["explain"]["ranking"][0]["path"], "src/ui/welcome.ts");+ assert!(+ report["explain"]["explanation"]+ .as_str()+ .unwrap()+ .contains("welcome.ts:4")+ );+ assert_eq!(report["calls"][0]["step"], "explain");+ let last = mock.requests.lock().unwrap().last().cloned().unwrap();+ assert!(+ last["input"]+ .as_str()+ .unwrap()+ .contains("1. src/ui/welcome.ts:4")+ );+ assert_eq!(pixel_log(root).len(), 5);+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn bad_input_is_refused_before_any_call() {+ let mock = Mock::default();+ let (base, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &base);+ let project = repository(root);+ let shot = screenshot(root);+ assert!(+ run(root, &["sync", project.to_str().unwrap()])+ .await+ .status+ .success()+ );+ // Outside the image, not an image, and no point.+ let out = run(+ root,+ &["pixel", shot.to_str().unwrap(), "--at", "500,15", "--json"],+ )+ .await;+ assert!(!out.status.success());+ assert!(String::from_utf8_lossy(&out.stderr).contains("outside"));+ let readme = project.join("README.md");+ let out = run(+ root,+ &["pixel", readme.to_str().unwrap(), "--at", "1,1", "--json"],+ )+ .await;+ assert!(!out.status.success());+ let out = run(root, &["pixel", shot.to_str().unwrap(), "--json"]).await;+ assert!(!out.status.success());+ assert!(mock.requests.lock().unwrap().is_empty());+ server.abort();+}diff --git a/crates/graphicle/tests/it/review_command.rs b/crates/graphicle/tests/it/review_command.rsnew file mode 100644index 0000000..c2f8fdb--- /dev/null+++ b/crates/graphicle/tests/it/review_command.rs@@ -0,0 +1,371 @@+//! `graphicle review` against a mock of the Responses API, on a fixture+//! repository with a two-commit change: the request holds the instructions,+//! a cache-layout pack whose top-ranked file is the changed one, the changed+//! hunks and the diff; a comment on a file the change does not touch is+//! dropped and one whose evidence does not hold is flagged; `--format+//! github` prints a COMMENT review at the head, with paths from the+//! repository's root for a project in a subfolder; a head that is not+//! checked out is refused, and a base equal to the head or a change that+//! only deletes makes no call.+use axum::{Json, Router, extract::State, response::IntoResponse, routing::post};+use serde_json::{Value, json};+use std::{+ path::{Path, PathBuf},+ process::{Command, Output, Stdio},+ sync::{Arc, Mutex},+};+use tempfile::TempDir;++#[derive(Clone, Default)]+struct Mock {+ requests: Arc<Mutex<Vec<Value>>>,+ reply: Arc<Mutex<Value>>,+}++async fn responses(State(mock): State<Mock>, Json(request): Json<Value>) -> impl IntoResponse {+ let prompt = format!(+ "{}{}",+ request["instructions"].as_str().unwrap_or(""),+ request["input"].as_str().unwrap_or("")+ );+ mock.requests.lock().unwrap().push(request.clone());+ let text = mock.reply.lock().unwrap().to_string();+ Json(json!({"status":"completed","model":"muse-spark-1.3",+ "usage":{"input_tokens":prompt.len() / 4,"input_tokens_details":{"cached_tokens":0},+ "output_tokens":80,"output_tokens_details":{"reasoning_tokens":20}},+ "output":[{"type":"message","content":[{"type":"output_text","text":text}]}]}))+}++async fn serve(mock: Mock) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = Router::new()+ .route("/v1/responses", post(responses))+ .with_state(mock);+ let server = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ (format!("http://{address}/v1"), server)+}++fn identity(command: &mut Command) -> &mut Command {+ command+ .env("GIT_AUTHOR_NAME", "Fixture")+ .env("GIT_AUTHOR_EMAIL", "[email protected]")+ .env("GIT_COMMITTER_NAME", "Fixture")+ .env("GIT_COMMITTER_EMAIL", "[email protected]")+}++fn graphicle(dir: &Path, cwd: &Path, args: &[String]) -> Output {+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ crate::child_env::home(&mut command, dir)+ .current_dir(cwd)+ .arg("--data-dir")+ .arg(dir.join("data"))+ .arg("--config")+ .arg(dir.join("models.json"))+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ identity(&mut command);+ crate::fork_guard::spawn(&mut command)+ .unwrap()+ .wait_with_output()+ .unwrap()+}++async fn run(root: &Path, cwd: &Path, args: &[&str]) -> Output {+ let (root, cwd) = (root.to_path_buf(), cwd.to_path_buf());+ let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();+ tokio::task::spawn_blocking(move || graphicle(&root, &cwd, &args))+ .await+ .unwrap()+}++/// The JSON a command printed, whatever its exit status.+fn printed(output: &Output) -> Value {+ serde_json::from_slice(&output.stdout).unwrap_or_else(|_| {+ panic!(+ "no JSON: {}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ })+}++fn git(dir: &Path, args: &[&str]) -> String {+ let mut command = Command::new("git");+ command.arg("-C").arg(dir).args(args);+ identity(&mut command);+ let output = command.output().unwrap();+ assert!(+ output.status.success(),+ "git {args:?}: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).trim().to_string()+}++/// A repository whose project is `folder` inside it (the root when empty):+/// a base commit where Answer returns 41, its caller and its test, plus+/// helpers; then a head commit where it returns 42. The base and head shas.+fn repository(root: &Path, folder: &str) -> (PathBuf, String, String) {+ let top = root.join("repo");+ let project = if folder.is_empty() {+ top.clone()+ } else {+ top.join(folder)+ };+ std::fs::create_dir_all(project.join("src")).unwrap();+ let write = |path: &str, text: &str| std::fs::write(project.join(path), text).unwrap();+ write(+ "src/answer.go",+ "package answer\n\n// Answer is the answer.\nfunc Answer() int {\n\treturn 41\n}\n",+ );+ write(+ "src/use.go",+ "package answer\n\n// Double doubles the answer.\nfunc Double() int {\n\treturn Answer() * 2\n}\n",+ );+ write(+ "src/answer_test.go",+ "package answer\n\nimport \"testing\"\n\nfunc TestAnswer(t *testing.T) {\n\tif Answer() != 41 {\n\t\tt.Fatal(\"wrong\")\n\t}\n}\n",+ );+ for i in 0..12 {+ let mut text = format!("package answer\n\n// Helper{i} helps.\n");+ for f in 0..6 {+ text.push_str(&format!(+ "func Helper{i}x{f}() int {{\n\tvalue := Double() + {f}\n\treturn value * {i}\n}}\n\n"+ ));+ }+ write(&format!("src/helper{i}.go"), &text);+ }+ write("README.md", "# Answer\n\nAnswer returns the answer.\n");+ git(&top, &["init", "-q"]);+ git(&top, &["add", "-A"]);+ git(&top, &["commit", "-q", "-m", "The answer"]);+ let base = git(&top, &["rev-parse", "HEAD"]);+ write(+ "src/answer.go",+ "package answer\n\n// Answer is the answer.\nfunc Answer() int {\n\treturn 42\n}\n",+ );+ git(&top, &["commit", "-q", "-a", "-m", "Make it 42"]);+ let head = git(&top, &["rev-parse", "HEAD"]);+ (project, base, head)+}++fn models(root: &Path, base: &str) {+ let spark = json!({"protocol":"responses","base_url":base,+ "model":"muse-spark-1.3","input_limit":60_000,"output_limit":4_000,"prompt_cache":true,+ "price":{"input":1.25,"output":4.25,"cached_input":0.15}});+ std::fs::write(+ root.join("models.json"),+ json!({"default_model":"spark","models":{"spark":spark}}).to_string(),+ )+ .unwrap();+}++fn reply() -> Value {+ json!({"summary":"Answer now returns 42.","comments":[+ {"path":"src/answer.go","line":5,"severity":"major",+ "body":"TestAnswer still expects 41, so it fails now; update it with the change.",+ "evidence":["src/answer_test.go:6","src/answer.go:5"]},+ {"path":"src/use.go","line":5,"severity":"minor","body":"Double changes too.",+ "evidence":["src/use.go:5"]},+ {"path":"src/answer.go","line":4,"severity":"nit","body":"Say why 42.",+ "evidence":["src/missing.go:3"]}]})+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_change_is_reviewed_and_its_comments_checked() {+ let mock = Mock::default();+ *mock.reply.lock().unwrap() = reply();+ let (url, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &url);+ let (project, base, head) = repository(root, "");+ let synced = run(root, &project, &["sync", project.to_str().unwrap()]).await;+ assert!(+ synced.status.success(),+ "{}",+ String::from_utf8_lossy(&synced.stderr)+ );+ let reviewed = run(+ root,+ &project,+ &[+ "review", "--base", &base, "--format", "json", "--budget", "6000",+ ],+ )+ .await;+ let report = printed(&reviewed);+ assert!(reviewed.status.success(), "{report}");+ assert_eq!(report["result"], "reviewed");+ assert_eq!(report["head"], head.as_str());+ assert_eq!(report["merge_base"], base.as_str());+ assert_eq!(report["files"][0]["path"], "src/answer.go");+ assert_eq!(report["files"][0]["hunks"], json!([[2, 6]]));+ // Kept: on a changed line, with evidence that holds.+ let comments = report["comments"].as_array().unwrap();+ assert_eq!(comments.len(), 1, "{report}");+ assert_eq!(comments[0]["path"], "src/answer.go");+ assert_eq!(comments[0]["line"], 5);+ assert_eq!(comments[0]["severity"], "major");+ assert_eq!(comments[0]["evidence"][0]["valid"], true);+ // Flagged: its only citation names no file of the tree.+ assert_eq!(report["flagged"].as_array().unwrap().len(), 1);+ assert_eq!(report["flagged"][0]["line"], 4);+ // Dropped: a file the change does not touch.+ let dropped = report["dropped"].as_array().unwrap();+ assert_eq!(dropped.len(), 1);+ assert!(+ dropped[0]["reason"]+ .as_str()+ .unwrap()+ .contains("src/use.go is not a file the change adds or modifies")+ );+ // The pack: the cache layout, the changed file ranked first.+ assert_eq!(report["pack"]["layout"], "cache");+ let first = report["pack"]["included"]+ .as_array()+ .unwrap()+ .iter()+ .find(|f| f["rank"] == 1)+ .unwrap();+ assert_eq!(first["path"], "src/answer.go");+ // The request: the instructions, the schema, the pack, then the hunks+ // and the diff after it.+ let requests = mock.requests.lock().unwrap();+ assert_eq!(requests.len(), 1);+ let request = &requests[0];+ assert!(+ request["instructions"]+ .as_str()+ .unwrap()+ .starts_with("You review a change")+ );+ assert_eq!(request["text"]["format"]["type"], "json_schema");+ assert!(+ request["prompt_cache_key"]+ .as_str()+ .unwrap()+ .starts_with("graphicle:")+ );+ let input = request["input"].as_str().unwrap();+ let hunks = input.find("Changed hunks of").unwrap();+ assert!(+ input[..hunks].starts_with("# Code pack"),+ "{}",+ &input[..200]+ );+ assert!(input[hunks..].contains("- src/answer.go (modified, +1 -1): 2-6"));+ assert!(input[hunks..].contains("-\treturn 41\n+\treturn 42\n"));+ assert!(input.ends_with("Review the change.\n"));+ drop(requests);+ let log = std::fs::read_to_string(root.join("data/usage.jsonl")).unwrap();+ let entries: Vec<Value> = log+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0]["command"], "review");+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_github_format_is_a_comment_review_from_the_repository_root() {+ let mock = Mock::default();+ *mock.reply.lock().unwrap() = reply();+ let (url, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &url);+ let (project, base, head) = repository(root, "services/answer");+ let synced = run(root, &project, &["sync", project.to_str().unwrap()]).await;+ assert!(+ synced.status.success(),+ "{}",+ String::from_utf8_lossy(&synced.stderr)+ );+ let reviewed = run(+ root,+ &project,+ &[+ "review", "--base", &base, "--head", &head, "--format", "github",+ ],+ )+ .await;+ let review = printed(&reviewed);+ assert!(reviewed.status.success(), "{review}");+ assert_eq!(review["event"], "COMMENT");+ assert_eq!(review["commit_id"], head.as_str());+ let comments = review["comments"].as_array().unwrap();+ assert_eq!(comments.len(), 1, "{review}");+ assert_eq!(comments[0]["path"], "services/answer/src/answer.go");+ assert_eq!(comments[0]["line"], 5);+ assert_eq!(comments[0]["side"], "RIGHT");+ let body = comments[0]["body"].as_str().unwrap();+ assert!(+ body.starts_with("**major**: TestAnswer still expects 41"),+ "{body}"+ );+ assert!(body.contains("`src/answer_test.go:6`"));+ let summary = review["body"].as_str().unwrap();+ assert!(summary.contains("Answer now returns 42."));+ assert!(summary.contains("1 inline comment(s); 1 withheld"));+ server.abort();+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_head_not_checked_out_and_an_empty_change_make_no_call() {+ let mock = Mock::default();+ *mock.reply.lock().unwrap() = reply();+ let (url, server) = serve(mock.clone()).await;+ let dir = TempDir::new().unwrap();+ let root = dir.path();+ models(root, &url);+ let (project, base, head) = repository(root, "");+ let synced = run(root, &project, &["sync", project.to_str().unwrap()]).await;+ assert!(+ synced.status.success(),+ "{}",+ String::from_utf8_lossy(&synced.stderr)+ );+ let elsewhere = run(+ root,+ &project,+ &[+ "review", "--base", &base, "--head", &base, "--format", "json",+ ],+ )+ .await;+ assert!(!elsewhere.status.success());+ let message = String::from_utf8_lossy(&elsewhere.stderr).to_string()+ + &String::from_utf8_lossy(&elsewhere.stdout);+ assert!(message.contains("check out"), "{message}");+ let empty = run(+ root,+ &project,+ &["review", "--base", &head, "--format", "json"],+ )+ .await;+ let report = printed(&empty);+ assert!(empty.status.success(), "{report}");+ assert_eq!(report["result"], "no changes");+ // A change that only deletes a file leaves no line to comment on.+ git(&project, &["rm", "-q", "README.md"]);+ git(&project, &["commit", "-q", "-m", "Drop the readme"]);+ let deleted = run(+ root,+ &project,+ &["review", "--base", &head, "--format", "json"],+ )+ .await;+ let report = printed(&deleted);+ assert!(deleted.status.success(), "{report}");+ assert_eq!(report["result"], "nothing to review");+ assert_eq!(report["files"][0]["status"], "deleted");+ assert!(mock.requests.lock().unwrap().is_empty());+ server.abort();+}diff --git a/crates/graphicle/tests/it/see.rs b/crates/graphicle/tests/it/see.rsnew file mode 100644index 0000000..22ecd47--- /dev/null+++ b/crates/graphicle/tests/it/see.rs@@ -0,0 +1,386 @@+//! `graphicle see` against a scripted mock of the Responses API's computer+//! tool and a fake driver (a shell script that logs each request and answers+//! with a 1x1 PNG): the request has the documented shape (the computer tool,+//! no stored state, encrypted reasoning asked for, each step's reasoning and+//! call replayed exactly as returned, each output with its call's id and a+//! screenshot); a run ends with the model's answer and+//! saves its screenshots and step log; every call goes in the spend log as+//! `see`; a pending safety check stops the run unless acknowledged, and an+//! acknowledged one goes back on the next request; the run's cap and the+//! step cap stop a run before the call that would pass them; a profile+//! without a price is refused.+use axum::{Json, Router, extract::State, http::StatusCode, routing::post};+use serde_json::{Value, json};+use std::{+ path::{Path, PathBuf},+ process::{Command, Output, Stdio},+ sync::{Arc, Mutex},+};+use tempfile::TempDir;++const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";++#[derive(Clone, Default)]+struct Mock {+ requests: Arc<Mutex<Vec<Value>>>,+ /// The output items of each step's reply, in order; the last repeats.+ script: Arc<Mutex<Vec<Value>>>,+ /// What the mock found wrong in a request.+ problems: Arc<Mutex<Vec<String>>>,+}++async fn responses(+ State(mock): State<Mock>,+ Json(request): Json<Value>,+) -> (StatusCode, Json<Value>) {+ mock.requests.lock().unwrap().push(request.clone());+ let input = request["input"].as_array().cloned().unwrap_or_default();+ let step = input+ .iter()+ .filter(|i| i["type"] == "computer_call_output")+ .count();+ let script = mock.script.lock().unwrap().clone();+ let mut problems = Vec::new();+ if request["tools"] != json!([{"type":"computer"}])+ || request["store"] != false+ || request["include"] != json!(["reasoning.encrypted_content"])+ {+ problems.push("not the computer tool without stored state".to_string());+ }+ // Each step's reasoning and call come back as the mock returned them, in+ // that order, and each output answers its call with a screenshot and its+ // acknowledged checks.+ for (index, group) in input[1..].chunks(3).enumerate() {+ let returned = &script[index.min(script.len() - 1)];+ if group[0] != reasoning(index) {+ problems.push(format!(+ "the reasoning of step {index} was not replayed unchanged"+ ));+ }+ if group.get(1) != Some(returned) {+ problems.push(format!("call {index} was not replayed unchanged"));+ }+ let output = group.get(2).cloned().unwrap_or(Value::Null);+ if output["call_id"] != returned["call_id"]+ || !output["output"]["image_url"]+ .as_str()+ .unwrap_or("")+ .starts_with("data:image/png;base64,")+ {+ problems.push(format!("output {index} does not answer its call"));+ }+ let pending = returned["pending_safety_checks"]+ .as_array()+ .cloned()+ .unwrap_or_default();+ if output["acknowledged_safety_checks"] != json!(pending) {+ return (+ StatusCode::BAD_REQUEST,+ Json(json!({"error":{"message":"pending safety checks were not acknowledged"}})),+ );+ }+ }+ mock.problems.lock().unwrap().extend(problems);+ let item = script[step.min(script.len() - 1)].clone();+ let output = if item["type"] == "computer_call" {+ json!([reasoning(step), item])+ } else {+ json!([item])+ };+ (+ StatusCode::OK,+ Json(+ json!({"id":format!("resp_{step}"),"object":"response","status":"completed",+ "model":"muse-wonder-1.0","output":output,+ "usage":{"input_tokens":2000 + 1600 * step,"output_tokens":100,+ "input_tokens_details":{"cached_tokens":1600 * step},+ "output_tokens_details":{"reasoning_tokens":20}}}),+ ),+ )+}++async fn serve(mock: Mock) -> (String, tokio::task::JoinHandle<()>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = Router::new()+ .route("/v1/responses", post(responses))+ .with_state(mock);+ let server = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ (format!("http://{address}/v1"), server)+}++fn call(id: usize, actions: Value, checks: Value) -> Value {+ json!({"type":"computer_call","id":format!("cc_{id}"),"call_id":format!("call_{id}"),+ "actions":actions,"pending_safety_checks":checks,"status":"completed",+ "meta_safety_replay_receipt":format!("receipt-{id}")})+}++/// The reasoning item the mock returns before step `step`'s call.+fn reasoning(step: usize) -> Value {+ json!({"type":"reasoning","id":format!("rs_{step}"),+ "summary":[{"type":"summary_text","text":"The menu is open; click the canvas."}],+ "encrypted_content":format!("encrypted-{step}")})+}++fn answer(shown: &str) -> Value {+ let text = json!({"shown":shown,"point":{"x":0,"y":0},"summary":"The menu stays open."});+ json!({"type":"message","role":"assistant",+ "content":[{"type":"output_text","text":text.to_string()}]})+}++fn setup(base: &str, price: bool) -> TempDir {+ let root = TempDir::new().unwrap();+ let mut wonder = json!({"protocol":"responses","base_url":base,"model":"muse-wonder-1.0",+ "input_limit":1_000_000,"output_limit":16_000});+ if price {+ wonder["price"] = json!({"input":4.0,"cached_input":0.2,"output":20.0});+ }+ std::fs::write(+ root.path().join("models.json"),+ json!({"default_model":"wonder","models":{"wonder":wonder}}).to_string(),+ )+ .unwrap();+ std::fs::write(+ root.path().join("driver.sh"),+ format!(+ "printf 'meta=[%s]\\n' \"$META_API_KEY\" > \"$1.env\"\nwhile IFS= read -r line; do\n printf '%s\\n' \"$line\" >> \"$1\"\n case \"$line\" in *'\"op\":\"close\"'*) exit 0;; esac\n printf '{{\"ok\":true,\"done\":1,\"error\":null,\"url\":\"http://app.test/\",\"blocked\":0,\"png\":\"%s\"}}\\n' '{PNG}'\ndone\n"+ ),+ )+ .unwrap();+ root+}++fn see(root: &Path, extra: &[&str]) -> Output {+ let driver = format!(+ "sh '{}' '{}'",+ root.join("driver.sh").display(),+ root.join("driver-requests.jsonl").display()+ );+ let mut command = Command::new(env!("CARGO_BIN_EXE_graphicle"));+ crate::child_env::home(&mut command, root)+ .arg("--data-dir")+ .arg(root.join("data"))+ .arg("--config")+ .arg(root.join("models.json"))+ .args([+ "see",+ "Open the main menu, then click the canvas: the menu should close.",+ "--driver",+ &driver,+ "--out",+ ])+ .arg(root.join("out"))+ .arg("--json")+ .args(extra)+ .env("META_API_KEY", "meta-fixture-0123456789abcdef")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ crate::fork_guard::spawn(&mut command)+ .unwrap()+ .wait_with_output()+ .unwrap()+}++async fn run(root: &Path, extra: &[&str]) -> Output {+ let root: PathBuf = root.to_path_buf();+ let extra: Vec<String> = extra.iter().map(|a| a.to_string()).collect();+ tokio::task::spawn_blocking(move || {+ let extra: Vec<&str> = extra.iter().map(String::as_str).collect();+ see(&root, &extra)+ })+ .await+ .unwrap()+}++fn report(output: &Output) -> Value {+ serde_json::from_slice(&output.stdout).unwrap_or_else(|_| {+ panic!(+ "no JSON: {}\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ })+}++fn spend_log(root: &Path) -> Vec<Value> {+ std::fs::read_to_string(root.join("data/usage.jsonl"))+ .unwrap_or_default()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect()+}++fn driver_requests(root: &Path) -> Vec<Value> {+ std::fs::read_to_string(root.join("driver-requests.jsonl"))+ .unwrap_or_default()+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect()+}++#[cfg(unix)]+#[tokio::test]+async fn a_run_reproduces_the_bug_replays_each_call_and_logs_each_step() {+ let mock = Mock::default();+ *mock.script.lock().unwrap() = vec![+ call(+ 1,+ json!([{"type":"click","button":"left","x":20,"y":20}]),+ json!([]),+ ),+ call(+ 2,+ json!([{"type":"click","button":"left","x":600,"y":400},{"type":"wait"}]),+ json!([]),+ ),+ answer("bug"),+ ];+ let (base, server) = serve(mock.clone()).await;+ let root = setup(&base, true);+ let output = run(root.path(), &[]).await;+ let report = report(&output);+ assert!(output.status.success(), "{report}");+ assert_eq!(report["result"], "reproduced");+ assert_eq!(report["shown"], "bug");+ assert_eq!(report["point"], json!({"x":0,"y":0}));+ assert_eq!(report["calls"], 3);+ assert_eq!(report["steps"].as_array().unwrap().len(), 3);+ assert_eq!(report["last_screenshot"], "step-02.png");+ assert!(+ mock.problems.lock().unwrap().is_empty(),+ "{:?}",+ mock.problems+ );+ let requests = mock.requests.lock().unwrap().clone();+ assert_eq!(requests.len(), 3);+ // The first message, then reasoning, call and output for each step.+ assert_eq!(requests[2]["input"].as_array().unwrap().len(), 7);+ assert_eq!(requests[2]["input"][4], reasoning(1));+ assert_eq!(+ requests[2]["input"][5]["meta_safety_replay_receipt"],+ "receipt-2"+ );+ // The driver ran each batch, then was asked to close.+ let asked = driver_requests(root.path());+ assert_eq!(asked[0], json!({"op":"screenshot"}));+ assert_eq!(asked[1]["actions"][0]["x"], 20);+ assert_eq!(asked[2]["actions"][1]["type"], "wait");+ assert_eq!(asked.last().unwrap(), &json!({"op":"close"}));+ // The driver never gets a model key, META_API_KEY among them.+ let env = std::fs::read_to_string(root.path().join("driver-requests.jsonl.env")).unwrap();+ assert_eq!(env.trim(), "meta=[]");+ let out = root.path().join("out");+ for file in [+ "step-00.png",+ "step-01.png",+ "step-02.png",+ "steps.jsonl",+ "see.json",+ "driver.log",+ ] {+ assert!(out.join(file).exists(), "{file}");+ }+ let log = spend_log(root.path());+ assert_eq!(log.len(), 3);+ for (index, entry) in log.iter().enumerate() {+ assert_eq!(entry["command"], "see");+ assert_eq!(entry["step"], index as u64 + 1);+ assert_eq!(entry["model"], "muse-wonder-1.0");+ assert!(entry["cost_usd"].as_f64().unwrap() > 0.0);+ }+ assert_eq!(log[2]["cached_tokens"], 3200);+ // Step 3: 5,200 input tokens of which 3,200 cached, and 100 output.+ let expected = (2000.0 * 4.0 + 3200.0 * 0.2 + 100.0 * 20.0) / 1e6;+ assert!((log[2]["cost_usd"].as_f64().unwrap() - expected).abs() < 1e-9);+ server.abort();+}++#[cfg(unix)]+#[tokio::test]+async fn a_safety_check_stops_the_run_unless_acknowledged_and_then_goes_back() {+ let check = json!([{"id":"csc_1","code":"malicious_instructions","message":"Potentially unsafe action detected."}]);+ let mock = Mock::default();+ *mock.script.lock().unwrap() = vec![+ call(1, json!([{"type":"type","text":"hello"}]), check.clone()),+ answer("bug"),+ ];+ let (base, server) = serve(mock.clone()).await;+ let root = setup(&base, true);+ let output = run(root.path(), &[]).await;+ assert!(!output.status.success());+ let stopped = report(&output);+ assert_eq!(stopped["result"], "stopped at a safety check");+ assert_eq!(+ driver_requests(root.path()).len(),+ 2,+ "a screenshot, then close: no action ran"+ );++ let root = setup(&base, true);+ mock.requests.lock().unwrap().clear();+ let output = run(root.path(), &["--acknowledge-safety-checks"]).await;+ let done = report(&output);+ assert!(output.status.success(), "{done}");+ assert_eq!(+ done["acknowledged"][0]["check"]["code"],+ "malicious_instructions"+ );+ let requests = mock.requests.lock().unwrap().clone();+ assert_eq!(requests[1]["input"][3]["acknowledged_safety_checks"], check);+ assert!(String::from_utf8_lossy(&output.stderr).contains("acknowledged the safety check"));+ server.abort();+}++#[cfg(unix)]+#[tokio::test]+async fn the_caps_and_a_missing_price_stop_a_run_before_its_call() {+ let mock = Mock::default();+ *mock.script.lock().unwrap() = vec![call(+ 1,+ json!([{"type":"click","button":"left","x":1,"y":1}]),+ json!([]),+ )];+ let (base, server) = serve(mock.clone()).await;+ // The run's cap is under one step's worst case: nothing is sent.+ let root = setup(&base, true);+ let output = run(root.path(), &["--max-cost", "0.0001"]).await;+ assert!(!output.status.success());+ assert_eq!(report(&output)["result"], "refused by a cap");+ assert!(mock.requests.lock().unwrap().is_empty());+ // The model keeps acting: two steps, then the step cap.+ let root = setup(&base, true);+ let output = run(root.path(), &["--steps", "2"]).await;+ assert!(!output.status.success());+ let capped = report(&output);+ assert_eq!(capped["result"], "step cap reached");+ assert_eq!(capped["calls"], 2);+ assert_eq!(spend_log(root.path()).len(), 2);+ // No price: refused before the driver starts.+ let root = setup(&base, false);+ let output = run(root.path(), &[]).await;+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("price"));+ assert!(driver_requests(root.path()).is_empty());+ server.abort();+}++#[cfg(unix)]+#[tokio::test]+async fn a_check_run_passes_on_the_expected_screen_and_fails_on_the_bug() {+ let mock = Mock::default();+ *mock.script.lock().unwrap() = vec![answer("expected")];+ let (base, server) = serve(mock.clone()).await;+ let root = setup(&base, true);+ let output = run(root.path(), &["--look-for", "expected"]).await;+ assert!(output.status.success());+ assert_eq!(report(&output)["result"], "expected shown");+ *mock.script.lock().unwrap() = vec![answer("bug")];+ let root = setup(&base, true);+ let output = run(root.path(), &["--look-for", "expected"]).await;+ assert!(!output.status.success());+ assert_eq!(report(&output)["result"], "bug still shown");+ server.abort();+}diff --git a/crates/graphicle/tests/it/workspace_scope.rs b/crates/graphicle/tests/it/workspace_scope.rsindex 912d8cd..bffdc4a 100644--- a/crates/graphicle/tests/it/workspace_scope.rs+++ b/crates/graphicle/tests/it/workspace_scope.rs@@ -1333,7 +1333,12 @@ fn a_workspace_connection_serves_the_graph_tools_of_the_project_repo_names() {assert_eq!(rest, memory);assert_eq!(memory,- ["recall_project", "read_project_source", "list_projects"],+ [+ "recall_project",+ "read_project_source",+ "list_projects",+ "pack"+ ],"{all:?}");assert!(diff --git a/demo/Dockerfile b/demo/Dockerfilenew file mode 100644index 0000000..71e5acd--- /dev/null+++ b/demo/Dockerfile@@ -0,0 +1,33 @@+# Graphicle's hosted demo: a thin, read-only web server (server.py) that runs the graphicle binary.+#+# Build from the repository's root:+# docker build -f demo/Dockerfile -t graphicle-demo .+# Run (see README.md for the data folder and the configuration files):+# docker run -p 8080:8080 -e MODEL_API_KEY \+# -v /srv/graphicle/data:/data/graphicle -v /srv/graphicle/src:/src:ro \+# -v /srv/graphicle/demo.json:/app/demo.json:ro -v /srv/graphicle/models.json:/etc/graphicle/models.json:ro \+# -v /srv/graphicle/curated.json:/app/curated.json:ro graphicle-demo++FROM rust:1.94.1-bookworm AS build+WORKDIR /src+# The program and the two crates it depends on (path dependencies); nothing else of the repository.+COPY crates/graphicle /src/crates/graphicle+COPY crates/graphicle-graph /src/crates/graphicle-graph+COPY crates/graphicle-memory /src/crates/graphicle-memory+RUN cd crates/graphicle && cargo build --release --locked --bin graphicle++FROM debian:bookworm-slim+RUN apt-get update \+ && apt-get install -y --no-install-recommends python3 ca-certificates git \+ && rm -rf /var/lib/apt/lists/*+RUN useradd --create-home --uid 10001 demo \+ && mkdir -p /var/lib/graphicle-demo /data/graphicle \+ && chown demo /var/lib/graphicle-demo /data/graphicle+COPY --from=build /src/crates/graphicle/target/release/graphicle /usr/local/bin/graphicle+COPY demo/server.py /app/server.py+COPY demo/static /app/static+USER demo+ENV DEMO_CONFIG=/app/demo.json PYTHONUNBUFFERED=1+EXPOSE 8080+HEALTHCHECK --interval=30s --timeout=5s CMD python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz')"+CMD ["python3", "/app/server.py"]diff --git a/demo/README.md b/demo/README.mdnew file mode 100644index 0000000..a84358c--- /dev/null+++ b/demo/README.md@@ -0,0 +1,66 @@+# Graphicle's hosted demo++A small web app for trying Graphicle with Meta's models on large repositories:++- **Ask:** a question about kubernetes, pytorch or vscode gets a cache-aware pack of the repository and an answer+ from Muse Spark, with each cited `path:line` linked to GitHub at the indexed commit, the pack's make-up, and the+ tokens, cached share, cost and time of the call.+- **Point at a pixel:** drop a screenshot of VS Code and click an element; `graphicle pixel` finds the element+ (SAM 3.1), reads it (Muse Spark) and finds the code that draws it.++`server.py` is a thin server (Python 3 standard library only) that runs the `graphicle` binary for each request+(`graphicle ask --pack` and `graphicle pixel`, fixed arguments, no shell). It never exposes Graphicle's own+local server, which has write APIs.++## Safety and cost++- **Read only:** the server runs `ask --pack` and `pixel` only, with freshness checks off (no sync).+- **Rate limit:** per client address, `per_minute` and `per_day` requests (in memory). Behind a proxy, set+ `trust_proxy` so that `X-Forwarded-For` names the client.+- **At most `max_concurrent` requests at once:** packs took a median of 0.7 to 1.0 GB of memory in the+ whole-repository benchmark's runs.+- **Daily cap:** before each live call, the day's spend (UTC) from `graphicle usage` over the data folders must be+ under `daily_cap_usd`. The profiles' own `max_cost_per_call` and `max_cost_per_day` in the models file stay the+ hard stop inside the binary.+- **Stored answers:** at the cap, or with no key, the curated questions (`curated.json`) show their recorded+ answers and cost; other questions get a pause message.+- **Nothing a visitor sends is kept:** a question goes to the binary only; a screenshot is a temporary file,+ deleted after the call; the request log has the time, path, status and duration, with no address, question+ or answer. The spend log (`usage.jsonl` in the data folder) has its own fields only: when, which command and+ model, the project, tokens, cost and status.++## Set up a host++1. **The data folder.** Check out each repository at its commit and sync it into one data folder, so that the+ binary's day cap covers every call:+ `graphicle --data-dir /srv/graphicle/data sync /srv/graphicle/src/kubernetes` (and pytorch, vscode). The+ checkouts must stay at the same paths: citations are checked against them.+2. **The models file** (`models.example.json`): Muse Spark 1.3 and SAM 3.1 profiles with their prices and caps.+ The key is the environment variable `MODEL_API_KEY`; it is never written to a file.+3. **The demo file** (`demo.example.json`): the repositories (`project` is the synced folder's path),+ the binary, the models file, the caps and limits.+4. **The stored answers:** with the key set, `python3 record.py demo.json curated.questions.json curated.json`+ asks each curated question once (live, logged in the spend log) and saves the answers with their cost.+5. **Run:** `DEMO_CONFIG=demo.json MODEL_API_KEY=... python3 server.py`, or build the image with the+ `Dockerfile` (from the repository's root) and run it as its header shows. Put TLS in front (a proxy or the+ host's load balancer).++## Tests++`python3 -m unittest test_demo` runs the unit tests. With `GRAPHICLE_BIN` naming a binary, the end-to-end test+syncs a fixture repository and runs the server against `mock_meta.py`, a stand-in for the Meta Model API (no key,+no model): ask, pixel, the rate limit, the cap with a stored answer, and a request log without the question.++## The flow: see it, find it, fix it, check it++`flow/flow.py` runs one bug from the screen to a tested fix, with a receipt+([docs/flow.md](../docs/flow.md)): `graphicle see` is built for Muse Wonder's computer use to reproduce the bug in+a browser we run (`browser_driver.py`, headless Chromium locked to the app's origin), `graphicle pixel` finds the+code that draws what it points at, `graphicle fix` patches it on a new branch and runs the app's tests, and+`graphicle see --look-for expected` checks the patched app. So far the flow is built and tested against+`mock_meta.py` only; it has not yet run against Meta's live API. `flow/targets/` holds the apps: `fixture.json` (a small app of our own+with a planted bug, for runs against `mock_meta.py`) and `excalidraw-12053.json`.++`mock_meta.py` also stands in for computer use (scripted actions, refusing requests that break the replay Meta's+computer-use page describes) and for `fix`'s plans and edits, from the files named by `MOCK_COMPUTER_SCRIPT` and+`MOCK_FIX_SCRIPT`.diff --git a/demo/browser_driver.py b/demo/browser_driver.pynew file mode 100644index 0000000..f646fda--- /dev/null+++ b/demo/browser_driver.py@@ -0,0 +1,226 @@+#!/usr/bin/env python3+"""browser_driver.py --url URL [options]: the browser that `graphicle see` drives with a model's computer use.++Graphicle starts this program and speaks to it in JSON, one object per line: a request on its standard input,+one reply on its standard output. Requests:+- {"op":"screenshot"}: the viewport as a PNG;+- {"op":"act","actions":[...]}: computer-use actions as the Meta Model API's `computer_call` gives them+ (click, double_click, drag, keypress, move, scroll, type, screenshot, wait), run in order and stopped at the+ first that fails, then the viewport as a PNG;+- {"op":"find","selector":"CSS"}: the box of the first element the selector matches (for scripted runs and+ tests; never sent on a model's behalf);+- {"op":"close"}.+A reply is {"ok":true,"done":N,"error":null|"...","url":"...","blocked":N,"width":W,"height":H,"png":"<base64>"};+a request it cannot read gets {"ok":false,"error":"..."}.++Safety: the browser runs headless with a fresh profile and loads only the --url's origin and the --allow ones;+every other request is aborted, and a WebSocket to any other origin is closed, each counted in "blocked". Service+workers are blocked, so no request bypasses that check. Pop-ups are closed and downloads refused. Points outside+the viewport are refused.++Needs Playwright for Python and its Chromium headless shell (PLAYWRIGHT_BROWSERS_PATH).+"""+import argparse+import base64+import json+import sys+import time+from urllib.parse import urlsplit++KEYS = {+ "ctrl": "Control", "control": "Control", "cmd": "Meta", "command": "Meta", "meta": "Meta", "super": "Meta",+ "win": "Meta", "alt": "Alt", "option": "Alt", "shift": "Shift", "enter": "Enter", "return": "Enter",+ "esc": "Escape", "escape": "Escape", "tab": "Tab", "space": "Space", "backspace": "Backspace",+ "delete": "Delete", "del": "Delete", "insert": "Insert", "home": "Home", "end": "End", "pageup": "PageUp",+ "pagedown": "PageDown", "up": "ArrowUp", "down": "ArrowDown", "left": "ArrowLeft", "right": "ArrowRight",+ "arrowup": "ArrowUp", "arrowdown": "ArrowDown", "arrowleft": "ArrowLeft", "arrowright": "ArrowRight",+ "capslock": "CapsLock",+}+BUTTONS = {"left": "left", "right": "right", "wheel": "middle", "middle": "middle"}+++def origin(url):+ parts = urlsplit(url)+ return f"{parts.scheme}://{parts.netloc}".lower()+++def socket_origin(url):+ """A WebSocket's origin as its page's scheme would name it: ws -> http, wss -> https."""+ parts = urlsplit(url)+ scheme = {"ws": "http", "wss": "https"}.get(parts.scheme, parts.scheme)+ return f"{scheme}://{parts.netloc}".lower()+++def key_name(key):+ text = str(key)+ folded = text.strip().lower().replace("_", "")+ if folded in KEYS:+ return KEYS[folded]+ if len(folded) >= 2 and folded[0] == "f" and folded[1:].isdigit():+ return folded.upper()+ return text if len(text) == 1 else text[:1].upper() + text[1:]+++class Driver:+ def __init__(self, page, width, height, settle):+ self.page, self.width, self.height, self.settle = page, width, height, settle+ self.blocked = 0++ def point(self, action, x="x", y="y"):+ px, py = action.get(x), action.get(y)+ if not isinstance(px, (int, float)) or not isinstance(py, (int, float)):+ raise ValueError(f"{action.get('type')} needs numbers {x} and {y}")+ if not (0 <= px < self.width and 0 <= py < self.height):+ raise ValueError(f"({px}, {py}) is outside the {self.width}x{self.height} screen")+ return float(px), float(py)++ def run(self, action):+ page, kind = self.page, action.get("type")+ if kind == "click":+ button = action.get("button", "left")+ if button == "back":+ page.go_back()+ elif button == "forward":+ page.go_forward()+ elif button in BUTTONS:+ page.mouse.click(*self.point(action), button=BUTTONS[button])+ else:+ raise ValueError(f"unknown button {button!r}")+ elif kind == "double_click":+ page.mouse.dblclick(*self.point(action))+ elif kind == "drag":+ path = action.get("path") or []+ if len(path) < 2:+ raise ValueError("drag needs a path of at least two points")+ points = [self.point(p) for p in path]+ page.mouse.move(*points[0])+ page.mouse.down()+ for p in points[1:]:+ page.mouse.move(*p, steps=5)+ page.mouse.up()+ elif kind == "keypress":+ keys = action.get("keys") or []+ if not keys:+ raise ValueError("keypress needs keys")+ page.keyboard.press("+".join(key_name(k) for k in keys))+ elif kind == "move":+ page.mouse.move(*self.point(action))+ elif kind == "scroll":+ page.mouse.move(*self.point(action))+ page.mouse.wheel(float(action.get("scroll_x") or 0), float(action.get("scroll_y") or 0))+ elif kind == "type":+ page.keyboard.type(str(action.get("text", "")), delay=10)+ elif kind == "wait":+ time.sleep(1.0)+ elif kind == "screenshot":+ pass+ else:+ raise ValueError(f"unknown action {kind!r}")++ def reply(self, done=0, error=None):+ time.sleep(self.settle)+ png = self.page.screenshot(type="png")+ return {"ok": True, "done": done, "error": error, "url": self.page.url, "blocked": self.blocked,+ "width": self.width, "height": self.height, "png": base64.b64encode(png).decode()}++ def handle(self, request):+ op = request.get("op")+ if op == "screenshot":+ return self.reply()+ if op == "act":+ actions = request.get("actions")+ if not isinstance(actions, list):+ return {"ok": False, "error": "act needs a list of actions"}+ done, error = 0, None+ for action in actions:+ try:+ if not isinstance(action, dict):+ raise ValueError("an action is not an object")+ self.run(action)+ done += 1+ except Exception as e: # stop the batch at the first failure, as the docs ask+ error = f"action {done + 1} ({action.get('type') if isinstance(action, dict) else '?'}): {e}"+ break+ return self.reply(done, error)+ if op == "find":+ box = self.page.locator(str(request.get("selector", ""))).first.bounding_box(timeout=5000)+ return {"ok": True, "box": box, "url": self.page.url}+ return {"ok": False, "error": f"unknown op {op!r}"}+++def main():+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--url", required=True)+ parser.add_argument("--width", type=int, default=1280)+ parser.add_argument("--height", type=int, default=800)+ parser.add_argument("--allow", action="append", default=[], help="another origin the page may load")+ parser.add_argument("--settle", type=float, default=0.6, help="seconds to wait before each screenshot")+ parser.add_argument("--dark", action="store_true", help="prefer the dark colour scheme")+ args = parser.parse_args()+ allowed = {origin(args.url)} | {origin(a) for a in args.allow}++ from playwright.sync_api import sync_playwright++ out = sys.stdout+ with sync_playwright() as pw:+ browser = pw.chromium.launch(headless=True)+ # No service workers: a request one answers would not pass through the route below.+ context = browser.new_context(viewport={"width": args.width, "height": args.height}, device_scale_factor=1,+ accept_downloads=False, color_scheme="dark" if args.dark else "light",+ service_workers="block")+ driver = None++ def guard(route):+ url = route.request.url+ if url.startswith(("data:", "blob:", "about:")) or origin(url) in allowed:+ route.continue_()+ else:+ if driver is not None:+ driver.blocked += 1+ route.abort()++ def socket_guard(socket):+ if socket_origin(socket.url) in allowed:+ socket.connect_to_server()+ else:+ if driver is not None:+ driver.blocked += 1+ socket.close()++ context.route("**/*", guard)+ context.route_web_socket("**/*", socket_guard)+ page = context.new_page()+ context.on("page", lambda p: p.close() if p is not page else None)+ driver = Driver(page, args.width, args.height, args.settle)+ page.goto(args.url, wait_until="load", timeout=60000)+ # Apps often wire their UI after load (fetching texts, then adding listeners): wait for the network to go+ # quiet and the page to settle before the first request, so the first click finds a ready page.+ try:+ page.wait_for_load_state("networkidle", timeout=15000)+ except Exception:+ pass+ time.sleep(args.settle)+ for line in sys.stdin:+ line = line.strip()+ if not line:+ continue+ try:+ request = json.loads(line)+ if not isinstance(request, dict):+ raise ValueError("a request is one JSON object")+ except ValueError as e:+ reply = {"ok": False, "error": f"unreadable request: {e}"}+ else:+ if request.get("op") == "close":+ break+ try:+ reply = driver.handle(request)+ except Exception as e:+ reply = {"ok": False, "error": str(e)}+ out.write(json.dumps(reply) + "\n")+ out.flush()+ browser.close()+++if __name__ == "__main__":+ main()diff --git a/demo/curated.questions.json b/demo/curated.questions.jsonnew file mode 100644index 0000000..a58cb34--- /dev/null+++ b/demo/curated.questions.json@@ -0,0 +1,11 @@+[+ {"repo": "kubernetes", "question": "How does the scheduler pick a node for a pod, from the queue to the binding?"},+ {"repo": "kubernetes", "question": "Where does the job controller count the pods it creates, and which metric records it?"},+ {"repo": "kubernetes", "question": "How does the kubelet decide to evict pods when a node runs low on memory?"},+ {"repo": "pytorch", "question": "How does autograd find and run the backward function of a tensor's operation?"},+ {"repo": "pytorch", "question": "Where does torch.compile handle a graph break, and what happens to the code after it?"},+ {"repo": "pytorch", "question": "How does the CUDA caching allocator reuse freed blocks?"},+ {"repo": "vscode", "question": "How does the Welcome page decide which walkthroughs to show?"},+ {"repo": "vscode", "question": "Where is the status bar's Ln and Col item updated when the cursor moves?"},+ {"repo": "vscode", "question": "How does the Explorer show its message when no folder is open?"}+]diff --git a/demo/demo.example.json b/demo/demo.example.jsonnew file mode 100644index 0000000..dd3eea5--- /dev/null+++ b/demo/demo.example.json@@ -0,0 +1,25 @@+{+ "listen": "0.0.0.0",+ "port": 8080,+ "binary": "/usr/local/bin/graphicle",+ "models": "/etc/graphicle/models.json",+ "key_env": "MODEL_API_KEY",+ "daily_cap_usd": 10,+ "max_concurrent": 2,+ "per_minute": 3,+ "per_day": 30,+ "trust_proxy": false,+ "timeout_seconds": 300,+ "ask_profile": "spark",+ "ask_budget": 400000,+ "curated": "/app/curated.json",+ "state_dir": "/var/lib/graphicle-demo",+ "repos": [+ {"id": "kubernetes", "github": "kubernetes/kubernetes", "commit": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7",+ "data_dir": "/data/graphicle", "project": "/src/kubernetes"},+ {"id": "pytorch", "github": "pytorch/pytorch", "commit": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7",+ "data_dir": "/data/graphicle", "project": "/src/pytorch"},+ {"id": "vscode", "github": "microsoft/vscode", "commit": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b",+ "data_dir": "/data/graphicle", "project": "/src/vscode", "pixel": true}+ ]+}diff --git a/demo/flow/fixture/README.md b/demo/flow/fixture/README.mdnew file mode 100644index 0000000..d398a39--- /dev/null+++ b/demo/flow/fixture/README.md@@ -0,0 +1,5 @@+# Sketch (the flow's fixture app)++A small web app with one planted bug, for running Graphicle's flow (`demo/flow/flow.py`) against the mock of the+Meta Model API: the main menu does not close when you press outside it. It has no dependencies; serve the folder+with any static server and run its tests with `node --test test/*.test.js`.diff --git a/demo/flow/fixture/index.html b/demo/flow/fixture/index.htmlnew file mode 100644index 0000000..97cf665--- /dev/null+++ b/demo/flow/fixture/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>Sketch</title>+<link rel="stylesheet" href="src/style.css">+</head>+<body>+<main id="canvas" class="canvas" aria-label="Canvas"></main>+<header class="toolbar">+ <button id="menu-trigger" class="menu-trigger" type="button" aria-haspopup="menu" aria-expanded="false">☰</button>+ <span id="title" class="title"></span>+</header>+<div id="menu" class="dropdown-menu" role="menu" hidden></div>+<script type="module" src="src/app.js"></script>+</body>+</html>diff --git a/demo/flow/fixture/locales/en.json b/demo/flow/fixture/locales/en.jsonnew file mode 100644index 0000000..c8dcb46--- /dev/null+++ b/demo/flow/fixture/locales/en.json@@ -0,0 +1,11 @@+{+ "app": {+ "title": "Sketch"+ },+ "menu": {+ "open": "Open",+ "saveTo": "Save to...",+ "exportImage": "Export image...",+ "reset": "Reset the canvas"+ }+}diff --git a/demo/flow/fixture/package.json b/demo/flow/fixture/package.jsonnew file mode 100644index 0000000..47b5adc--- /dev/null+++ b/demo/flow/fixture/package.json@@ -0,0 +1,9 @@+{+ "name": "sketch-fixture",+ "private": true,+ "type": "module",+ "description": "A small app with a planted bug, for Graphicle's flow on the mock: the main menu does not close on a press outside it.",+ "scripts": {+ "test": "node --test test/*.test.js"+ }+}diff --git a/demo/flow/fixture/src/app.js b/demo/flow/fixture/src/app.jsnew file mode 100644index 0000000..29bfbdc--- /dev/null+++ b/demo/flow/fixture/src/app.js@@ -0,0 +1,40 @@+import { loadStrings, t } from "./i18n.js";+import { createMenu } from "./menu.js";++function menuItem(id, label) {+ const button = document.createElement("button");+ button.type = "button";+ button.className = "menu-item";+ button.dataset.item = id;+ button.setAttribute("role", "menuitem");+ button.textContent = label;+ return button;+}++function renderMenu(root) {+ root.replaceChildren(+ menuItem("open", t("menu.open")),+ menuItem("save", t("menu.saveTo")),+ menuItem("export", t("menu.exportImage")),+ menuItem("reset", t("menu.reset")),+ );+}++async function main() {+ await loadStrings("locales/en.json");+ document.getElementById("title").textContent = t("app.title");+ const root = document.getElementById("menu");+ renderMenu(root);+ createMenu({+ root,+ trigger: document.getElementById("menu-trigger"),+ doc: document,+ onSelect: (id) => {+ if (id === "reset") {+ document.getElementById("canvas").replaceChildren();+ }+ },+ });+}++main();diff --git a/demo/flow/fixture/src/i18n.js b/demo/flow/fixture/src/i18n.jsnew file mode 100644index 0000000..73de67f--- /dev/null+++ b/demo/flow/fixture/src/i18n.js@@ -0,0 +1,17 @@+// The app's texts, by dotted key ("menu.reset"), from a locale file.+let strings = {};++export async function loadStrings(url) {+ strings = await (await fetch(url)).json();+}++export function setStrings(value) {+ strings = value;+}++export function t(key) {+ const found = key+ .split(".")+ .reduce((node, part) => (node && typeof node === "object" ? node[part] : undefined), strings);+ return typeof found === "string" ? found : key;+}diff --git a/demo/flow/fixture/src/menu.js b/demo/flow/fixture/src/menu.jsnew file mode 100644index 0000000..04b46c2--- /dev/null+++ b/demo/flow/fixture/src/menu.js@@ -0,0 +1,35 @@+// A dropdown menu: its trigger opens and closes it; Escape, a choice, or a+// press anywhere outside it closes it.+export function createMenu({ root, trigger, doc, onSelect = () => {} }) {+ let open = false;+ const show = () => {+ open = true;+ root.hidden = false;+ trigger.setAttribute("aria-expanded", "true");+ };+ const hide = () => {+ open = false;+ root.hidden = true;+ trigger.setAttribute("aria-expanded", "false");+ };+ trigger.addEventListener("click", () => (open ? hide() : show()));+ // A press outside the menu (and its trigger) closes it.+ root.addEventListener("pointerdown", (event) => {+ if (open && !root.contains(event.target) && !trigger.contains(event.target)) {+ hide();+ }+ });+ doc.addEventListener("keydown", (event) => {+ if (event.key === "Escape") {+ hide();+ }+ });+ root.addEventListener("click", (event) => {+ const item = event.target.closest?.("[data-item]");+ if (item) {+ hide();+ onSelect(item.dataset.item);+ }+ });+ return { show, hide, isOpen: () => open };+}diff --git a/demo/flow/fixture/src/style.css b/demo/flow/fixture/src/style.cssnew file mode 100644index 0000000..00c01b9--- /dev/null+++ b/demo/flow/fixture/src/style.css@@ -0,0 +1,21 @@+body { margin: 0; font: 16px/1.4 system-ui, sans-serif; color: #1b1b1f; }+.canvas {+ position: fixed; inset: 0; background-color: #fbfbfd;+ background-image: radial-gradient(#d4d4dc 1px, transparent 1px); background-size: 24px 24px;+}+.toolbar { position: fixed; top: 16px; left: 16px; display: flex; align-items: center; gap: 12px; }+.menu-trigger {+ width: 40px; height: 40px; border: 1px solid #c9c9d3; border-radius: 8px; background: #fff;+ font-size: 20px; cursor: pointer;+}+.title { font-weight: 600; }+.dropdown-menu {+ position: fixed; top: 64px; left: 16px; width: 220px; padding: 6px; background: #fff;+ border: 1px solid #c9c9d3; border-radius: 10px; box-shadow: 0 8px 24px rgb(0 0 0 / 12%);+}+.dropdown-menu[hidden] { display: none; }+.menu-item {+ display: block; width: 100%; height: 36px; padding: 0 10px; border: 0; border-radius: 6px;+ background: none; text-align: left; font: inherit; cursor: pointer;+}+.menu-item:hover { background: #eef0ff; }diff --git a/demo/flow/fixture/test/menu.test.js b/demo/flow/fixture/test/menu.test.jsnew file mode 100644index 0000000..1122cce--- /dev/null+++ b/demo/flow/fixture/test/menu.test.js@@ -0,0 +1,69 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { createMenu } from "../src/menu.js";++// Just enough of the DOM: nodes that hold children and dispatch events.+class FakeNode extends EventTarget {+ constructor(children = []) {+ super();+ this.children = children;+ this.hidden = true;+ this.attributes = {};+ }+ contains(node) {+ return node === this || this.children.some((child) => child.contains(node));+ }+ setAttribute(name, value) {+ this.attributes[name] = value;+ }+}++function setup() {+ const item = new FakeNode();+ const root = new FakeNode([item]);+ const trigger = new FakeNode();+ const canvas = new FakeNode();+ const doc = new FakeNode([root, trigger, canvas]);+ const menu = createMenu({ root, trigger, doc });+ return { menu, root, trigger, canvas, doc, item };+}++// A pointerdown on `target`, as it reaches the document after bubbling up.+function pressAt(doc, target) {+ const event = new Event("pointerdown");+ Object.defineProperty(event, "target", { value: target });+ doc.dispatchEvent(event);+}++test("the trigger opens and closes the menu", () => {+ const { menu, root, trigger } = setup();+ trigger.dispatchEvent(new Event("click"));+ assert.equal(menu.isOpen(), true);+ assert.equal(root.hidden, false);+ trigger.dispatchEvent(new Event("click"));+ assert.equal(menu.isOpen(), false);+ assert.equal(root.hidden, true);+});++test("a press inside the menu keeps it open", () => {+ const { menu, doc, item } = setup();+ menu.show();+ pressAt(doc, item);+ assert.equal(menu.isOpen(), true);+});++test("a press outside the menu closes it", () => {+ const { menu, doc, canvas } = setup();+ menu.show();+ pressAt(doc, canvas);+ assert.equal(menu.isOpen(), false);+});++test("Escape closes the menu", () => {+ const { menu, doc } = setup();+ menu.show();+ const event = new Event("keydown");+ event.key = "Escape";+ doc.dispatchEvent(event);+ assert.equal(menu.isOpen(), false);+});diff --git a/demo/flow/flow.py b/demo/flow/flow.pynew file mode 100644index 0000000..ad9cd1e--- /dev/null+++ b/demo/flow/flow.py@@ -0,0 +1,746 @@+#!/usr/bin/env python3+"""flow.py TARGET.json --out DIR (--mock | --models FILE --key-file FILE): see it, find it, fix it, check it.++One run of Graphicle's flow on a web app, ending in a receipt:+1. **Set up.** Check out the app (the target's "checkout"), sync it into Graphicle, build it ("build") and serve+ it ("serve") on this machine's address.+2. **See it.** `graphicle see` lets the model drive the app in headless Chromium (../browser_driver.py) until the+ issue's bug is on screen; it keeps every screenshot, the step log and the point the model names.+3. **Find it.** `graphicle pixel` on the last screenshot at that point: SAM 3.1 finds the element, Muse Spark+ reads it, and Graphicle's lookup and code graph rank file:line candidates.+4. **Fix it.** `graphicle fix` with the issue, the candidates as --focus, and the target's test command ("test",+ never a model's), on a new branch in a new worktree, committed there.+5. **Check it.** The patched worktree is built and served, and `graphicle see --look-for expected` repeats the+ steps and says whether the screen now shows the expected behaviour.+6. **The receipt.** DIR/receipt.json and DIR/receipt.md: the steps, citations and diff, the end of the test log,+ the before and after screenshots, and each model call's model, tokens, cached tokens and cost, read from+ Graphicle's usage ledger.++A scripted screen check (the target's "oracle": fixed clicks, then whether a CSS selector is on screen) runs+before and after too, with no model, so a run against the mock still shows what the screen really did.++**Mock** (--mock): mock_meta.py stands in for the Meta Model API (no key, no model, no cost); its computer-use,+reading and fix replies come from the target's "mock" section. **Live** (--models FILE --key-file FILE): FILE+names the profiles (--see-model and --fix-model for Muse Wonder, --read-model for Muse Spark, --sam-model for SAM+3.1), each with its price; the key file (mode 0600) goes to Graphicle's processes as MODEL_API_KEY, never to the+app, the driver or the receipt. Every call goes through the usage ledger under this run's own copies of the+profiles, whose caps hold the run to --max-run-cost (the binary checks them before each call); the run does+not start when the day's flow runs and this one could pass --max-day-cost.++Needs: the graphicle binary (--graphicle), git, Python 3 with Playwright and its Chromium headless shell+(PLAYWRIGHT_BROWSERS_PATH), and what the target's commands need.+"""+import argparse+import base64+import datetime+import http.client+import json+import os+import shlex+import shutil+import signal+import socket+import subprocess+import sys+import time+from pathlib import Path+from urllib.parse import urlsplit++DEMO = Path(__file__).resolve().parent.parent+FLOW = Path(__file__).resolve().parent+DRIVER = DEMO / "browser_driver.py"+MOCK = DEMO / "mock_meta.py"+IDENTITY = {"GIT_AUTHOR_NAME": "Graphicle flow", "GIT_AUTHOR_EMAIL": "[email protected]",+ "GIT_COMMITTER_NAME": "Graphicle flow", "GIT_COMMITTER_EMAIL": "[email protected]"}+# Meta's Standard prices (dev.meta.ai/docs/pricing-rate-limits), for the mock's profiles.+MOCK_PROFILES = {+ "wonder": {"model": "muse-wonder-1.0", "input_limit": 1048576, "output_limit": 16384,+ "price": {"input": 4.0, "cached_input": 0.2, "output": 20.0}},+ "spark": {"model": "muse-spark-1.3", "input_limit": 1048576, "output_limit": 16384,+ "price": {"input": 1.25, "cached_input": 0.15, "output": 4.25}},+ "sam": {"model": "sam-3.1", "price": {"input": 0.0, "output": 0.0, "per_image": 0.0025}},+}+TAIL = 4000+# The variables model keys are read from (as graphicle's fix and see remove them): never in the app's build, serve+# and test commands, the driver or the mock. The key file's key goes to graphicle's processes alone.+KEY_VARIABLES = ("MODEL_API_KEY", "META_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY",+ "GOOGLE_API_KEY", "AZURE_OPENAI_API_KEY")+# When see and fix use different profiles, see's share of the Muse budget (its two runs, before and after);+# fix gets the rest.+SEE_SHARE = 0.35+# The app's own git hooks (husky's, once its packages are installed) never run in the flow's commits.+GIT_NO_HOOKS = ["git", "-c", "core.hooksPath=/dev/null"]+++def http_status(url, method="GET", body=None, timeout=5):+ """The status of one plain-HTTP request. http.client builds no TLS context, unlike urllib's opener, which some+ hosts' OpenSSL refuses to build in an empty environment (env -i), even for an http:// address."""+ parts = urlsplit(url)+ connection = http.client.HTTPConnection(parts.hostname, parts.port or 80, timeout=timeout)+ try:+ headers = {"Content-Type": "application/json"} if body is not None else {}+ connection.request(method, parts.path or "/", body=body, headers=headers)+ return connection.getresponse().status+ finally:+ connection.close()+++def now():+ return datetime.datetime.now(datetime.timezone.utc)+++def host_address():+ """This machine's first address (some hosts refuse TCP to loopback), else loopback."""+ try:+ out = subprocess.run(["hostname", "-I"], capture_output=True, text=True, timeout=10).stdout.split()+ if out:+ return out[0]+ except (OSError, subprocess.SubprocessError):+ pass+ return "127.0.0.1"+++def free_port(host, start):+ for port in range(start, start + 200):+ with socket.socket() as s:+ try:+ s.bind((host, port))+ return port+ except OSError:+ continue+ raise SystemExit(f"flow: no free port from {start}")+++class Flow:+ def __init__(self, args, target):+ self.args, self.target = args, target+ self.out = Path(args.out).resolve()+ self.out.mkdir(parents=True, exist_ok=True)+ self.data = Path(args.data_dir).resolve() if args.data_dir else self.out / "data"+ self.started = now()+ self.run_id = self.started.strftime("%Y%m%dT%H%M%SZ")+ self.host = args.host or host_address()+ self.processes = []+ self.events = []+ self.env = {k: v for k, v in os.environ.items() if k not in KEY_VARIABLES}+ self.key = None+ self.models_file = self.out / "models.json"+ self.profiles = {}+ self.marks = []++ # ------------------------------------------------------------ plumbing++ def note(self, step, **fields):+ event = {"step": step, "time": now().isoformat(timespec="seconds"), **fields}+ self.events.append(event)+ print(f"flow: {step}: " + ", ".join(f"{k}={v}" for k, v in fields.items() if k != "detail"),+ file=sys.stderr, flush=True)++ def shell(self, step, command, cwd, timeout=1800, env=None):+ """Run one of the target's commands (never a model's) and record its exit code and output's end."""+ started = time.time()+ done = subprocess.run(command, shell=True, cwd=cwd, env=env or self.env, capture_output=True, text=True,+ timeout=timeout)+ log = self.out / "logs" / f"{step}.log"+ log.parent.mkdir(exist_ok=True)+ log.write_text(done.stdout + done.stderr)+ self.note(step, command=command, exit=done.returncode, seconds=round(time.time() - started, 1))+ if done.returncode != 0:+ raise SystemExit(f"flow: {step} failed ({command}); see {log}")+ return done++ def graphicle(self, step, *args, check=True):+ command = [self.args.graphicle, "--data-dir", str(self.data), "--config", str(self.models_file), *args]+ # fix --commit commits as the flow, as the flow's own commits do (an empty environment has no identity).+ env = {**self.env, **IDENTITY}+ if self.key:+ env["MODEL_API_KEY"] = self.key+ if self.args.mock:+ env["GRAPHICLE_PROVIDER_HTTP_HOSTS"] = self.host+ started = time.time()+ done = subprocess.run(command, env=env, capture_output=True, text=True, timeout=3600)+ (self.out / "logs").mkdir(exist_ok=True)+ (self.out / "logs" / f"{step}.stderr").write_text(done.stderr)+ report = None+ try:+ report = json.loads(done.stdout) if done.stdout.strip() else None+ except ValueError:+ pass+ if report is not None:+ (self.out / f"{step}.json").write_text(json.dumps(report, indent=1) + "\n")+ self.note(step, command="graphicle " + " ".join(shlex.quote(a) for a in args[:1]), exit=done.returncode,+ seconds=round(time.time() - started, 1))+ if check and done.returncode != 0 and report is None:+ raise SystemExit(f"flow: graphicle {args[0]} failed: {done.stderr.strip()[-600:]}")+ return report, done.returncode++ def start(self, step, command, cwd, env=None):+ log = open(self.out / "logs" / f"{step}.log", "w")+ process = subprocess.Popen(command, shell=True, cwd=cwd, env=env or self.env, stdout=log,+ stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True)+ self.processes.append(process)+ self.note(step, command=command, pid=process.pid)+ return process++ def stop(self, process):+ if process.poll() is None:+ try:+ os.killpg(process.pid, signal.SIGTERM)+ process.wait(timeout=20)+ except (OSError, subprocess.TimeoutExpired):+ os.killpg(process.pid, signal.SIGKILL)+ if process in self.processes:+ self.processes.remove(process)++ def wait_http(self, url, timeout=120):+ until = time.time() + timeout+ while time.time() < until:+ try:+ if http_status(url) < 500:+ return+ except OSError:+ pass+ time.sleep(0.5)+ raise SystemExit(f"flow: {url} did not answer within {timeout} s")++ # ------------------------------------------------------------ models and money++ def ledger(self):+ path = self.data / "usage.jsonl"+ rows = []+ if path.exists():+ for line in path.read_text().splitlines():+ try:+ row = json.loads(line)+ except ValueError:+ continue+ if isinstance(row, dict):+ rows.append(row)+ return rows++ def prepare_models(self):+ """This run's own copies of the profiles, with caps that hold the run to --max-run-cost."""+ a = self.args+ if a.mock:+ base = f"http://{self.host}:{self.mock_port}/v1"+ source = {name: {"protocol": "responses", "base_url": base, **p} for name, p in MOCK_PROFILES.items()}+ names = {"see": "wonder", "fix": "wonder", "read": "spark", "sam": "sam"}+ else:+ source = json.loads(Path(a.models).read_text()).get("models", {})+ names = {"see": a.see_model, "fix": a.fix_model, "read": a.read_model, "sam": a.sam_model}+ shares = {"read": 0.2, "sam": 0.1}+ heavy = round(a.max_run_cost - sum(shares[r] for r in shares), 4)+ if heavy <= 0:+ raise SystemExit("flow: --max-run-cost leaves nothing for Muse Wonder")+ # Caps are per profile: one profile for see and fix shares the whole budget; two split it, so that the+ # run's caps never add up to more than --max-run-cost.+ if names["see"] == names["fix"]:+ shares.update(see=heavy, fix=heavy)+ else:+ see_cap = round(heavy * SEE_SHARE, 4)+ shares.update(see=see_cap, fix=round(heavy - see_cap, 4))+ profiles, caps = {}, {}+ for role, name in names.items():+ if name not in source:+ raise SystemExit(f"flow: no profile {name!r} in the models file")+ run_name = f"flow-{name}-{self.run_id}"+ if run_name not in profiles:+ profile = dict(source[name])+ if not profile.get("price"):+ raise SystemExit(f"flow: the profile {name!r} has no price, so its caps cannot work")+ cap = shares[role]+ if "output_limit" in profile or profile.get("model", "").startswith("muse-"):+ # A call's worst case counts its whole output limit, so keep it to what a step needs.+ profile["output_limit"] = min(int(profile.get("output_limit") or a.max_output), a.max_output)+ profile["max_cost_per_day"] = cap+ profile["max_cost_per_call"] = min(profile.get("max_cost_per_call") or cap, cap)+ if not a.mock and profile.get("key_env") is None:+ profile["key_env"] = "MODEL_API_KEY"+ profiles[run_name], caps[run_name] = profile, cap+ self.profiles[role] = run_name+ self.models_file.write_text(json.dumps({"default_model": self.profiles["fix"], "models": profiles},+ indent=1) + "\n")+ # And whatever variables the profiles read their keys from.+ for profile in source.values():+ self.env.pop(str(profile.get("key_env") or ""), None)+ self.caps = caps++ def check_day_budget(self):+ today = self.started.strftime("%Y-%m-%d")+ spent = sum((r.get("cost_usd") or r.get("worst_cost_usd") or 0.0) for r in self.ledger()+ if str(r.get("profile", "")).startswith("flow-") and str(r.get("time", "")).startswith(today))+ if spent + self.args.max_run_cost > self.args.max_day_cost:+ raise SystemExit(f"flow: today's flow runs cost ${spent:.2f}; another run could bring the day over "+ f"--max-day-cost ${self.args.max_day_cost:.2f}")+ return spent++ def run_cost(self):+ return sum((r.get("cost_usd") or 0.0) for r in self.mine())++ # ------------------------------------------------------------ the app++ def checkout(self):+ spec = self.target["checkout"]+ repo = self.out / "repo"+ if repo.exists():+ shutil.rmtree(repo)+ env = {**self.env, **IDENTITY}+ if "fixture" in spec:+ shutil.copytree(FLOW / spec["fixture"], repo)+ for command in (["git", "init", "-q"], ["git", "add", "-A"],+ [*GIT_NO_HOOKS, "commit", "-q", "--no-verify", "-m", "The app before the fix"]):+ subprocess.run(command, cwd=repo, env=env, check=True, capture_output=True)+ else:+ source = spec.get("mirror") or spec["url"]+ subprocess.run(["git", "clone", "-q", "--no-checkout", "--filter=blob:none", source, str(repo)],+ env=env, check=True, capture_output=True)+ subprocess.run(["git", "checkout", "-q", "-B", "flow/base", spec["commit"]], cwd=repo, env=env,+ check=True, capture_output=True)+ extra = spec.get("add_from")+ if extra:+ subprocess.run(["git", "checkout", extra["commit"], "--", *extra["paths"]], cwd=repo, env=env,+ check=True, capture_output=True)+ subprocess.run([*GIT_NO_HOOKS, "commit", "-q", "--no-verify", "-m", extra["message"]], cwd=repo,+ env=env, check=True, capture_output=True)+ head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=repo, capture_output=True, text=True).stdout.strip()+ self.note("checkout", repo=str(repo), head=head[:12])+ return repo, head++ def command(self, name, **values):+ """The target's command `name` with its placeholders ({flow}, {host}, {port}, {dir}) filled."""+ text = self.target.get(name, "true")+ for key, value in {"flow": shlex.quote(str(FLOW)), "host": self.host, **values}.items():+ text = text.replace("{" + key + "}", str(value))+ return text++ def serve(self, step, folder, port):+ command = self.command("serve", port=port, dir=shlex.quote(str(folder)))+ process = self.start(step, command, cwd=folder)+ url = f"http://{self.host}:{port}{self.target.get('path', '/')}"+ self.wait_http(url)+ return process, url++ def driver_command(self, url):+ width, height = self.target.get("viewport", [1280, 800])+ command = [sys.executable, str(DRIVER), "--url", url, "--width", str(width), "--height", str(height)]+ command += [x for origin in self.target.get("allow", []) for x in ("--allow", origin)]+ return " ".join(shlex.quote(c) for c in command)++ def oracle(self, step, url):+ """The target's scripted screen check, with no model: is the bug's selector on screen after its clicks?+ A check that cannot run is recorded with its error; the flow goes on."""+ spec = self.target.get("oracle")+ if not spec:+ return None+ try:+ return self.screen_check(step, url, spec)+ except SystemExit as error:+ self.note(step, error=str(error))+ return {"error": str(error), "selector": spec.get("bug_selector")}++ def screen_check(self, step, url, spec):+ errors = open(self.out / "logs" / f"{step}-driver.log", "w")+ driver = subprocess.Popen(shlex.split(self.driver_command(url)), stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=errors, text=True, env=self.env)++ def ask(request):+ driver.stdin.write(json.dumps(request) + "\n")+ driver.stdin.flush()+ line = driver.stdout.readline()+ if not line:+ try:+ code = driver.wait(timeout=10)+ except subprocess.TimeoutExpired:+ code = None+ raise SystemExit(f"flow: the screen check's driver ended (exit {code}); see logs/{step}-driver.log")+ return json.loads(line)++ try:+ reply = {}+ for actions in spec["steps"]:+ actions = [dict(a) for a in actions]+ for action in actions:+ # A click by selector: the centre of the element's box.+ selector = action.pop("selector", None)+ if selector:+ box = ask({"op": "find", "selector": selector}).get("box")+ if not box:+ raise SystemExit(f"flow: the screen check found no {selector}")+ action["x"] = int(box["x"] + box["width"] / 2)+ action["y"] = int(box["y"] + box["height"] / 2)+ reply = ask({"op": "act", "actions": actions})+ if not reply.get("ok") or reply.get("error"):+ raise SystemExit(f"flow: the screen check could not act: {reply.get('error')}")+ shot = self.out / f"{step}.png"+ shot.write_bytes(base64.b64decode(reply["png"]))+ found = ask({"op": "find", "selector": spec["bug_selector"]})+ driver.stdin.write(json.dumps({"op": "close"}) + "\n")+ driver.stdin.flush()+ finally:+ try:+ driver.wait(timeout=30)+ except subprocess.TimeoutExpired:+ driver.kill()+ shown = bool(found.get("ok") and found.get("box"))+ self.note(step, bug_shown=shown)+ return {"bug_shown": shown, "selector": spec["bug_selector"], "screenshot": shot.name}++ # ------------------------------------------------------------ the steps++ def see(self, step, url, look_for, task):+ task_file = self.out / f"{step}-task.md"+ task_file.write_text(task)+ remaining = max(0.01, self.caps[self.profiles["see"]] - self.run_cost())+ args = ["see", "--task-file", str(task_file), "--driver", self.driver_command(url), "--look-for", look_for,+ "--out", str(self.out / step), "--steps", str(self.args.steps), "--max-cost", f"{remaining:.4f}",+ "--model", self.profiles["see"], "--json"]+ if self.target.get("sandboxed"):+ args.append("--acknowledge-safety-checks")+ report, code = self.graphicle(step, *args, check=False)+ if report is None:+ raise SystemExit(f"flow: graphicle see gave no report (exit {code})")+ return report++ def run(self):+ a, t = self.args, self.target+ self.mock_port = free_port(self.host, a.port + 2) if a.mock else None+ if a.mock:+ env = dict(self.env)+ mock = t.get("mock", {})+ for name, key in (("computer", "MOCK_COMPUTER_SCRIPT"), ("fix", "MOCK_FIX_SCRIPT")):+ if name in mock:+ path = self.out / f"mock-{name}.json"+ path.write_text(json.dumps(mock[name], indent=1))+ env[key] = str(path)+ env["MOCK_STRINGS"] = mock.get("strings", "")+ env["MOCK_NEARBY"] = mock.get("nearby", "")+ (self.out / "logs").mkdir(exist_ok=True)+ self.start("mock", f"{shlex.quote(sys.executable)} {shlex.quote(str(MOCK))} {self.host} {self.mock_port}",+ cwd=self.out, env=env)+ self.wait_http_post(f"http://{self.host}:{self.mock_port}/v1/responses/input_tokens")+ else:+ key = Path(a.key_file)+ if key.stat().st_mode & 0o077:+ raise SystemExit("flow: the key file must be readable by its owner only (chmod 600)")+ self.key = key.read_text().strip()+ self.prepare_models()+ day_before = self.check_day_budget()+ (self.out / "logs").mkdir(exist_ok=True)++ # 1. Set up.+ repo, head = self.checkout()+ self.graphicle("sync", "sync", str(repo), "--json")+ self.shell("build-before", self.command("build", dir=shlex.quote(str(repo))), cwd=repo)+ server, url = self.serve("serve-before", repo, free_port(self.host, a.port))+ oracle_before = self.oracle("screen-check-before", url)++ # 2. See it.+ self.mark("see")+ see = self.see("see", url, "bug", t["issue"])+ self.stop(server)+ receipt = {"mode": "mock" if a.mock else "live", "target": {k: t.get(k) for k in ("name", "about", "issue")},+ "repository": {"path": str(repo), "head": head, "checkout": t["checkout"]},+ "started": self.started.isoformat(timespec="seconds"), "run_id": self.run_id,+ "profiles": self.profiles, "caps_usd": self.caps, "day_spent_before_usd": round(day_before, 6),+ "screen_checks": {"before": oracle_before}, "steps": {}}+ receipt["steps"]["see"] = self.see_step(see, "before.png")+ if see.get("result") != "reproduced" or not see.get("point"):+ return self.finish(receipt, f"stopped: see ended with {see.get('result')!r} and no point")++ # 3. Find it.+ shot = Path(see["out"]) / see["last_screenshot"]+ point = f"{see['point']['x']},{see['point']['y']}"+ self.mark("find")+ pixel, code = self.graphicle("find", "pixel", str(shot), "--at", point, "--project", str(repo), "--model",+ self.profiles["read"], "--sam", self.profiles["sam"], "--top", "5", "--json",+ check=False)+ candidates = (pixel or {}).get("candidates") or []+ receipt["steps"]["find"] = {"point": see["point"], "box": (pixel or {}).get("box"),+ "read": (pixel or {}).get("read"), "exit": code,+ "candidates": [{"path": c["path"], "line": c["line"], "score": c.get("score"),+ "symbol": (c.get("symbol") or {}).get("name"),+ "snippet": c.get("snippet")} for c in candidates]}+ if not candidates:+ return self.finish(receipt, "stopped: pixel found no candidate")++ # 4. Fix it.+ located = "\n".join(f"- {c['path']}:{c['line']}" + (f" ({c['symbol']['name']})" if c.get("symbol") else "")+ for c in candidates[:3])+ strings = ", ".join(f'"{s}"' for s in ((pixel.get("read") or {}).get("strings") or []))+ issue = (t["issue"].rstrip() + "\n\nWhere it shows: the model reproduced the bug on screen, and the element "+ f"it pointed at{(' (' + strings + ')') if strings else ''} is drawn here (graphicle pixel):\n"+ + located + "\n")+ (self.out / "fix-issue.md").write_text(issue)+ focus = [x for c in candidates[:3] for x in ("--focus", f"{c['path']}:{c['line']}")]+ self.mark("fix")+ test = self.command("test")+ fix, code = self.graphicle("fix", "fix", "--issue-file", str(self.out / "fix-issue.md"), "--test", test,+ "--rounds", str(a.rounds), "--budget", str(a.fix_budget), "--layout",+ a.fix_layout, "--branch",+ f"flow/{self.run_id}", "--commit", "--project", str(repo), "--model",+ self.profiles["fix"], "--json", *focus, check=False)+ if fix is None:+ return self.finish(receipt, f"stopped: fix gave no report (exit {code})")+ worktree = Path(fix["worktree"])+ diff = subprocess.run(["git", "diff", fix["base"], "HEAD"], cwd=worktree, capture_output=True,+ text=True).stdout+ (self.out / "fix.diff").write_text(diff)+ rounds = fix.get("rounds") or []+ tail = next((r["test"]["output_tail"] for r in reversed(rounds) if r.get("test")), None)+ receipt["steps"]["fix"] = {+ "result": fix.get("result"), "branch": fix.get("branch"), "commit": fix.get("committed"),+ "worktree": str(worktree), "files_changed": fix.get("files_changed"),+ "plan": (fix.get("plan") or {}).get("summary"), "focus": fix.get("focus"),+ "rounds": [{"round": r.get("round"), "result": r.get("result"),+ "test": {k: (r.get("test") or {}).get(k) for k in ("passed", "exit_code", "seconds")}+ if r.get("test") else None} for r in rounds],+ "citations": fix.get("citations"), "test_command": test,+ "test_tail": (tail or "")[-TAIL:], "diff": diff}+ packed = {f.get("path") for f in ((fix.get("pack") or {}).get("included") or [])}+ receipt["steps"]["fix"]["pack"] = {"layout": a.fix_layout, "budget": a.fix_budget,+ "tokens": (fix.get("pack") or {}).get("tokens"), "files": len(packed)}+ key = t.get("answer_key")+ if key:+ changed = set(fix.get("files_changed") or [])+ receipt["answer_key"] = {**key, "touched_the_same_files": bool(changed & set(key.get("files", []))),+ "files_in_the_pack": sorted(set(key.get("files", [])) & packed)}+ if fix.get("result") != "passed":+ return self.finish(receipt, f"stopped: fix ended with {fix.get('result')!r}")++ # 5. Check it.+ self.mark("between")+ self.shell("build-after", self.command("build", dir=shlex.quote(str(worktree))), cwd=worktree)+ server, url = self.serve("serve-after", worktree, free_port(self.host, a.port + 1))+ receipt["screen_checks"]["after"] = self.oracle("screen-check-after", url)+ steps = "\n".join(f"{i}. " + ", ".join(describe(x) for x in s.get("actions", []))+ for i, s in enumerate(see.get("steps", []), 1) if s.get("actions"))+ self.mark("check")+ check = self.see("check", url, "expected", t["issue"].rstrip()+ + ("\n\nThe steps that showed the bug before the change:\n" + steps if steps else ""))+ self.stop(server)+ receipt["steps"]["check"] = self.see_step(check, "after.png")+ result = "fixed and checked" if check.get("result") == "expected shown" else \+ f"fixed; the check ended with {check.get('result')!r}"+ return self.finish(receipt, result)++ def wait_http_post(self, url, timeout=60):+ until = time.time() + timeout+ while time.time() < until:+ try:+ if http_status(url, "POST", b"{}") == 200:+ return+ except OSError:+ pass+ time.sleep(0.3)+ raise SystemExit(f"flow: the mock at {url} did not start")++ def see_step(self, report, copy_as):+ last = Path(report.get("out", "")) / (report.get("last_screenshot") or "")+ if last.is_file():+ shutil.copyfile(last, self.out / copy_as)+ return {"result": report.get("result"), "shown": report.get("shown"), "point": report.get("point"),+ "summary": report.get("summary"), "stopped": report.get("stopped"), "calls": report.get("calls"),+ "screenshot": copy_as if last.is_file() else None, "folder": report.get("out"),+ "acknowledged": report.get("acknowledged"),+ "actions": [{"step": s.get("step"), "actions": [describe(x) for x in s.get("actions", [])],+ "error": (s.get("driver") or {}).get("error")} for s in report.get("steps", [])]}++ def mine(self):+ """This run's rows of the usage ledger, in order."""+ names = set(self.profiles.values())+ return [r for r in self.ledger() if r.get("profile") in names]++ def mark(self, step):+ """Where `step`'s calls start in this run's rows of the ledger."""+ self.marks.append((step, len(self.mine())))++ def finish(self, receipt, result):+ rows = self.mine()+ bounds = self.marks + [(None, len(rows))]+ for (step, start), (_, end) in zip(bounds, bounds[1:]):+ if step in receipt["steps"]:+ receipt["steps"][step]["usage"] = totals(rows[start:end])+ receipt["ledger"] = [{k: r.get(k) for k in ("time", "command", "step", "profile", "model", "input_tokens",+ "cached_tokens", "output_tokens", "reasoning_tokens",+ "cost_usd", "worst_cost_usd", "status")} for r in rows]+ receipt["total"] = totals(rows)+ receipt["max_run_cost_usd"] = self.args.max_run_cost+ receipt["result"] = result+ receipt["finished"] = now().isoformat(timespec="seconds")+ receipt["events"] = self.events+ (self.out / "receipt.json").write_text(json.dumps(receipt, indent=1) + "\n")+ (self.out / "receipt.md").write_text(markdown(receipt))+ self.note("receipt", result=result, cost=f"${receipt['total']['cost_usd']:.4f}",+ file=str(self.out / "receipt.md"))+ return receipt++ def close(self):+ for process in list(self.processes):+ self.stop(process)+++def describe(action):+ kind = action.get("type", "?")+ at = f" ({action.get('x')}, {action.get('y')})" if "x" in action and "y" in action else ""+ if kind == "type":+ return f"type {action.get('text', '')[:60]!r}"+ if kind == "keypress":+ return "keys " + "+".join(map(str, action.get("keys", [])))+ if kind == "click" and action.get("button", "left") != "left":+ return f"{action['button']} click{at}"+ return f"{kind.replace('_', ' ')}{at}"+++def totals(rows):+ def add(field):+ return sum((r.get(field) or 0) for r in rows)+ models = sorted({r.get("model") for r in rows if r.get("model")})+ return {"calls": len(rows), "models": models, "input_tokens": add("input_tokens"),+ "cached_tokens": add("cached_tokens"), "output_tokens": add("output_tokens"),+ "cost_usd": round(sum((r.get("cost_usd") or 0.0) for r in rows), 6)}+++def where(checkout):+ if "fixture" in checkout:+ return f"the fixture app (demo/flow/{checkout['fixture']}), as a new git repository"+ extra = " with the fix's regression test added" if checkout.get("add_from") else ""+ return f"{checkout.get('url')} at {str(checkout.get('commit'))[:12]}{extra}; the run's checkout"+++def money(value):+ return f"${value:.4f}" if value < 1 else f"${value:.2f}"+++def markdown(r):+ mock = r["mode"] == "mock"+ lines = [f"# Flow receipt: {r['target'].get('name')}", ""]+ if mock:+ lines += ["**Mock run.** `mock_meta.py` stood in for the Meta Model API: no model saw these screenshots. "+ "Its actions, answers, readings and edits are scripted in the target file, and its token counts "+ "are made up (a quarter of the bytes sent, 1,500 per image); the costs are those counts at Meta's "+ "Standard prices. The scripted screen checks (no model) show what the screen really did.", ""]+ lines += [f"- **Result:** {r['result']}", f"- **Run:** {r['run_id']} ({r['started']} to {r['finished']})",+ f"- **Repository:** {where(r['repository']['checkout'])} at {r['repository']['head'][:12]}",+ f"- **Cost:** {money(r['total']['cost_usd'])} in {r['total']['calls']} model calls "+ f"(cap {money(r['max_run_cost_usd'])} a run)", "", "## The issue", "", "```text",+ (r["target"].get("issue") or "").strip(), "```", ""]+ see = r["steps"].get("see")+ if see:+ lines += ["## 1. See it", "", f"{see.get('summary') or ''} Result: **{see.get('result')}**"+ + (f", pointing at ({see['point']['x']}, {see['point']['y']})." if see.get("point") else "."), ""]+ for s in see.get("actions", []):+ lines.append(f"{s['step']}. " + (", ".join(s["actions"]) or "answer")+ + (f" (stopped: {s['error']})" if s.get("error") else ""))+ for ack in see.get("acknowledged") or []:+ check = ack.get("check", {})+ lines.append(f"\nAcknowledged safety check at step {ack.get('step')}: {check.get('code')}: "+ f"{check.get('message')} (this run's own sandboxed app).")+ if see.get("screenshot"):+ lines += ["", f""]+ lines.append("")+ find = r["steps"].get("find")+ if find:+ read = find.get("read") or {}+ lines += ["## 2. Find it", "", f"`graphicle pixel` at ({find['point']['x']}, {find['point']['y']}): "+ f"SAM 3.1's box {find.get('box') and [find['box'].get(k) for k in ('x1', 'y1', 'x2', 'y2')]}, "+ f"read as {', '.join(repr(s) for s in read.get('strings') or []) or 'no text'}.", "",+ "| # | Place | Symbol |", "|---|---|---|"]+ for i, c in enumerate(find["candidates"], 1):+ lines.append(f"| {i} | `{c['path']}:{c['line']}` | {c.get('symbol') or ''} |")+ lines.append("")+ fix = r["steps"].get("fix")+ if fix:+ pack = fix.get("pack") or {}+ lines += ["## 3. Fix it", "", f"Plan: {fix.get('plan') or ''}", "",+ f"Pack: {pack.get('layout', '?')} layout, {pack.get('tokens') or 0:,} tokens in {pack.get('files', 0)} "+ f"files (budget {pack.get('budget') or 0:,}), with pixel's places first (--focus).", "",+ f"Branch `{fix.get('branch')}`, commit {str(fix.get('commit'))[:12]}, result **{fix.get('result')}** "+ f"with `{fix.get('test_command')}`.", ""]+ for rd in fix.get("rounds", []):+ test = rd.get("test") or {}+ lines.append(f"- Round {rd['round']}: {rd['result']}"+ + (f" (exit {test.get('exit_code')}, {test.get('seconds')} s)" if test else ""))+ cited = [c for c in fix.get("citations") or [] if c.get("valid")]+ if cited:+ lines += ["", "Citations: " + ", ".join(f"`{c['path']}:{c['line']}`" for c in cited)]+ lines += ["", "```diff", (fix.get("diff") or "").rstrip(), "```", "", "The end of the test log:", "",+ "```text", (fix.get("test_tail") or "").rstrip()[-1500:], "```", ""]+ key = r.get("answer_key")+ if key:+ packed = key.get("files_in_the_pack")+ lines += [f"Answer key: {key.get('about', '')} The fix touched the same files: "+ f"**{'yes' if key.get('touched_the_same_files') else 'no'}**"+ + (f"; the fix's pack held {len(packed)} of its {len(key.get('files', []))} file(s)"+ if packed is not None else "") + ".", ""]+ check = r["steps"].get("check")+ if check:+ lines += ["## 4. Check it", "", f"{check.get('summary') or ''} Result: **{check.get('result')}**.", ""]+ if check.get("screenshot"):+ lines += [f"", ""]+ checks = r.get("screen_checks") or {}+ if any(checks.values()):+ lines += ["## Scripted screen checks (no model)", ""]+ for when, c in checks.items():+ if c and c.get("error"):+ lines.append(f"- {when}: could not run ({c['error']})")+ elif c:+ lines.append(f"- {when}: `{c['selector']}` {'on screen (the bug)' if c['bug_shown'] else 'not on screen'}"+ f" ([screenshot]({c['screenshot']}))")+ lines.append("")+ lines += ["## Model calls (from the usage ledger)", "",+ "| Step | Calls | Models | Input | Cached | Output | Cost |", "|---|---|---|---|---|---|---|"]+ for name in ("see", "find", "fix", "check"):+ u = (r["steps"].get(name) or {}).get("usage")+ if u:+ lines.append(f"| {name} | {u['calls']} | {', '.join(u['models'])} | {u['input_tokens']:,} | "+ f"{u['cached_tokens']:,} | {u['output_tokens']:,} | {money(u['cost_usd'])} |")+ t = r["total"]+ lines += [f"| **total** | {t['calls']} | | {t['input_tokens']:,} | {t['cached_tokens']:,} | "+ f"{t['output_tokens']:,} | {money(t['cost_usd'])} |", ""]+ return "\n".join(lines)+++def main():+ parser = argparse.ArgumentParser(description="See it, find it, fix it, check it: one flow run and its receipt.")+ parser.add_argument("target", help="the target file (targets/*.json)")+ parser.add_argument("--out", required=True, help="the run's folder: receipt, screenshots, logs")+ parser.add_argument("--graphicle", default="graphicle", help="the graphicle binary")+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument("--mock", action="store_true", help="run against mock_meta.py (no key, no model, no cost)")+ mode.add_argument("--models", help="live: the models file with the profiles named below")+ parser.add_argument("--key-file", help="live: the Meta Model API key, in a file of mode 0600")+ parser.add_argument("--see-model", default="wonder")+ parser.add_argument("--fix-model", default="wonder")+ parser.add_argument("--read-model", default="spark")+ parser.add_argument("--sam-model", default="sam")+ parser.add_argument("--data-dir", help="Graphicle's data folder [default: OUT/data]")+ parser.add_argument("--host", help="the address the app and the mock listen on [default: this machine's]")+ parser.add_argument("--port", type=int, default=3101, help="the first port tried for the app")+ parser.add_argument("--steps", type=int, default=25, help="computer-use steps at most, each run (1-29)")+ parser.add_argument("--rounds", type=int, default=2, help="fix rounds at most")+ parser.add_argument("--fix-budget", type=int, default=200000, help="the fix pack's budget in tokens")+ parser.add_argument("--fix-layout", choices=["standard", "cache"], default="standard",+ help="the fix pack's layout: standard fills the budget by relevance to the issue; within one "+ "fix run the plan and the rounds have different instructions, so the cache layout's "+ "shared repository part pays off only across runs")+ parser.add_argument("--max-run-cost", type=float, default=3.0, help="US dollars a run may cost at most")+ parser.add_argument("--max-day-cost", type=float, default=10.0, help="US dollars the day's flow runs may cost")+ parser.add_argument("--max-output", type=int, default=16384,+ help="the output limit of this run's Muse profiles (a call's worst case counts all of it)")+ args = parser.parse_args()+ if args.models and not args.key_file:+ parser.error("a live run needs --key-file")+ if not 1 <= args.steps <= 29:+ parser.error("--steps runs from 1 to 29")+ target = json.loads(Path(args.target).read_text())+ flow = Flow(args, target)+ try:+ receipt = flow.run()+ finally:+ flow.close()+ print(json.dumps({"result": receipt["result"], "receipt": str(flow.out / "receipt.md"),+ "cost_usd": receipt["total"]["cost_usd"]}))+++if __name__ == "__main__":+ main()diff --git a/demo/flow/targets/excalidraw-12053.json b/demo/flow/targets/excalidraw-12053.jsonnew file mode 100644index 0000000..7f72501--- /dev/null+++ b/demo/flow/targets/excalidraw-12053.json@@ -0,0 +1,206 @@+{+ "name": "excalidraw #12053: the main menu stays open after a click on the canvas",+ "about": "excalidraw (MIT, github.com/excalidraw/excalidraw) at f1a79b73, the commit before the fix of #12053, with that fix's regression test added. The issue text is written from the fix's description (a regression from #11974); the upstream fix 2b1c2a9f is the answer key. Building, serving and testing run excalidraw's own toolchain (excalidraw-build.sh, excalidraw-test.sh): run them only on a host allowed to run third-party code.",+ "checkout": {+ "url": "https://github.com/excalidraw/excalidraw.git",+ "commit": "f1a79b73df5b9883f940417861a4f5fb879a3f02",+ "add_from": {+ "commit": "2b1c2a9fbf62417168cdae041d00f38cc403f0a5",+ "paths": [+ "packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx"+ ],+ "message": "Add the regression test of excalidraw #12053 (from 2b1c2a9f), which fails before the fix"+ }+ },+ "issue": "Clicking the canvas no longer closes the main menu.\n\nSteps to reproduce:\n1. Open the editor.\n2. Click the main menu button (the three lines at the top left).\n3. Click anywhere on the empty canvas.\n\nExpected: the menu closes, as it used to.\nActual: the menu stays open. The \"More tools\" dropdown in the toolbar does the same.",+ "build": "bash {flow}/targets/excalidraw-build.sh",+ "serve": "python3 -m http.server {port} --bind {host} --directory excalidraw-app/build",+ "test": "bash {flow}/targets/excalidraw-test.sh",+ "viewport": [+ 1280,+ 800+ ],+ "sandboxed": true,+ "oracle": {+ "steps": [+ [+ {+ "type": "click",+ "button": "left",+ "selector": "[data-testid='main-menu-trigger']"+ }+ ],+ [+ {+ "type": "click",+ "button": "left",+ "x": 1000,+ "y": 420+ }+ ]+ ],+ "bug_selector": "[data-testid='dropdown-menu']"+ },+ "answer_key": {+ "about": "The upstream fix 2b1c2a9f (#12053) changed DropdownMenuContent.tsx: the outside-click listeners attach once the menu's content is mounted.",+ "files": [+ "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx"+ ]+ },+ "mock": {+ "about": "For --mock runs: the computer-use clicks were measured on the built app at 1280x800, and the scripted edit is the upstream fix 2b1c2a9f's change to DropdownMenuContent.tsx, so a mock receipt shows the pipeline, not a model's fix.",+ "strings": "Reset the canvas",+ "nearby": "Export image...|Save to...|Command palette",+ "computer": {+ "runs": [+ {+ "match": "Reproduce this issue",+ "steps": [+ {+ "actions": [+ {+ "type": "click",+ "button": "left",+ "x": 34,+ "y": 34+ }+ ]+ },+ {+ "actions": [+ {+ "type": "click",+ "button": "left",+ "x": 1000,+ "y": 420+ }+ ],+ "safety": [+ {+ "id": "csc_mock_1",+ "code": "mock_check",+ "message": "A scripted check from the mock, to show the acknowledgement path."+ }+ ]+ },+ {+ "answer": {+ "shown": "bug",+ "point": {+ "x": 118,+ "y": 315+ },+ "summary": "I opened the main menu and clicked the empty canvas; the menu is still open."+ }+ }+ ]+ },+ {+ "match": "The code was changed",+ "steps": [+ {+ "actions": [+ {+ "type": "click",+ "button": "left",+ "x": 34,+ "y": 34+ }+ ]+ },+ {+ "actions": [+ {+ "type": "click",+ "button": "left",+ "x": 1000,+ "y": 420+ }+ ]+ },+ {+ "answer": {+ "shown": "expected",+ "point": null,+ "summary": "I opened the main menu and clicked the empty canvas; the menu closed."+ }+ }+ ]+ }+ ]+ },+ "fix": {+ "plan": {+ "summary": "Attach the dropdown's outside-click and Escape listeners once Radix has mounted the menu content: track the content node with a callback ref, so the listeners resolve its owner document.",+ "steps": [+ "Track the mounted content node with useCallbackRefState",+ "Build the menu ref from that node",+ "Bind the Escape listener to the node's owner document once it exists"+ ],+ "edits": [+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "start_line": 1,+ "end_line": 95,+ "reason": "The outside-click effect runs before Radix mounts the content"+ }+ ],+ "new_files": [],+ "tests": [+ {+ "action": "run",+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenu.test.tsx",+ "what": "the menus close on outside pointer and touch events"+ }+ ],+ "risks": []+ },+ "rounds": [+ {+ "explanation": "MenuContent passes a plain ref to DropdownMenuPrimitive.Content, but Radix mounts the content after the outside-click effect has run, so useOutsideClick never finds its owner document. Tracking the node with a callback ref rebinds the listeners when it mounts.",+ "edits": [+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": "import React, { useCallback, useEffect, useRef } from \"react\";",+ "replace": "import React, { useCallback, useEffect, useMemo } from \"react\";"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": "import { useOutsideClick } from \"../../hooks/useOutsideClick\";",+ "replace": "import { useCallbackRefState } from \"../../hooks/useCallbackRefState\";\nimport { useOutsideClick } from \"../../hooks/useOutsideClick\";"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": " const menuRef = useRef<HTMLDivElement>(null);",+ "replace": " const [menuNode, setMenuNode] = useCallbackRefState<HTMLDivElement>();\n // Radix mounts the content lazily. Rebind outside-click listeners when the\n // node becomes available so they attach to its owner document.\n const menuRef = useMemo(() => ({ current: menuNode }), [menuNode]);"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": " [callbacksRef],\n ),\n );",+ "replace": " [callbacksRef, menuRef],\n ),\n );"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": " if (!open) {\n return;\n }\n const onKeyDown",+ "replace": " if (!open || !menuNode) {\n return;\n }\n const onKeyDown"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": " document.addEventListener(EVENT.KEYDOWN, onKeyDown, option);\n return () => {\n document.removeEventListener(EVENT.KEYDOWN, onKeyDown, option);\n };\n }, [callbacksRef, open]);",+ "replace": " const ownerDocument = menuNode.ownerDocument;\n ownerDocument.addEventListener(EVENT.KEYDOWN, onKeyDown, option);\n return () => {\n ownerDocument.removeEventListener(EVENT.KEYDOWN, onKeyDown, option);\n };\n }, [callbacksRef, open, menuNode]);"+ },+ {+ "path": "packages/excalidraw/components/dropdownMenu/DropdownMenuContent.tsx",+ "search": " ref={menuRef}",+ "replace": " ref={setMenuNode}"+ }+ ],+ "new_files": [],+ "tests": [+ "yarn vitest run packages/excalidraw/components/dropdownMenu"+ ]+ }+ ]+ }+ }+}diff --git a/demo/flow/targets/excalidraw-build.sh b/demo/flow/targets/excalidraw-build.shnew file mode 100755index 0000000..1943185--- /dev/null+++ b/demo/flow/targets/excalidraw-build.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Build excalidraw's web app in the current folder (a checkout of github.com/excalidraw/excalidraw) for the+# flow: yarn 1 with the lockfile as it is, then the app's production build into excalidraw-app/build.+# This runs third-party code (the yarn packages and their build tools): run it only on a host allowed to.+# Needs Node.js 20 or later and yarn 1 on PATH; YARN_CACHE_FOLDER keeps the packages between checkouts.+set -euo pipefail+export CI=1 BROWSER=none+yarn install --frozen-lockfile --network-timeout 600000+(cd excalidraw-app && yarn build:app:docker)diff --git a/demo/flow/targets/excalidraw-test.sh b/demo/flow/targets/excalidraw-test.shnew file mode 100755index 0000000..81ba168--- /dev/null+++ b/demo/flow/targets/excalidraw-test.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# The flow's test command for excalidraw: install the packages when the checkout has none (a new worktree),+# then run the dropdown menu's tests with vitest. Third-party code: only on a host allowed to run it.+set -euo pipefail+export CI=1+[ -d node_modules ] || yarn install --frozen-lockfile --prefer-offline --network-timeout 600000 > /dev/null+yarn vitest run packages/excalidraw/components/dropdownMenudiff --git a/demo/flow/targets/fixture.json b/demo/flow/targets/fixture.jsonnew file mode 100644index 0000000..6a00260--- /dev/null+++ b/demo/flow/targets/fixture.json@@ -0,0 +1,65 @@+{+ "name": "fixture: the main menu stays open after a click outside it",+ "about": "The flow's own fixture app (demo/flow/fixture): a planted bug of the same kind as excalidraw #12053, for runs against the mock. No third-party code.",+ "checkout": {"fixture": "fixture"},+ "issue": "The main menu does not close when I click outside it.\n\nSteps to reproduce:\n1. Open the app.\n2. Click the menu button (the three lines at the top left).\n3. Click anywhere on the empty canvas.\n\nExpected: the menu closes.\nActual: the menu stays open until you press its button again.",+ "build": "true",+ "serve": "python3 -m http.server {port} --bind {host}",+ "test": "node --test test/*.test.js",+ "viewport": [1280, 800],+ "sandboxed": true,+ "oracle": {+ "steps": [+ [{"type": "click", "button": "left", "x": 36, "y": 36}],+ [{"type": "click", "button": "left", "x": 640, "y": 450}]+ ],+ "bug_selector": "#menu:not([hidden])"+ },+ "answer_key": {+ "about": "The planted bug: src/menu.js listens for presses outside the menu on the menu itself, so they never arrive.",+ "files": ["src/menu.js"]+ },+ "mock": {+ "strings": "Reset the canvas",+ "nearby": "Open|Save to...|Export image...",+ "computer": {+ "runs": [+ {+ "match": "Reproduce this issue",+ "steps": [+ {"actions": [{"type": "click", "button": "left", "x": 36, "y": 36}]},+ {"actions": [{"type": "click", "button": "left", "x": 640, "y": 450}],+ "safety": [{"id": "csc_mock_1", "code": "mock_check", "message": "A scripted check from the mock, to show the acknowledgement path."}]},+ {"answer": {"shown": "bug", "point": {"x": 90, "y": 196}, "summary": "I opened the main menu and clicked the empty canvas; the menu is still open."}}+ ]+ },+ {+ "match": "The code was changed",+ "steps": [+ {"actions": [{"type": "click", "button": "left", "x": 36, "y": 36}]},+ {"actions": [{"type": "click", "button": "left", "x": 640, "y": 450}]},+ {"answer": {"shown": "expected", "point": null, "summary": "I opened the main menu and clicked the empty canvas; the menu closed."}}+ ]+ }+ ]+ },+ "fix": {+ "plan": {+ "summary": "Close the menu on a press anywhere outside it: the outside-press listener is attached to the menu itself, so presses outside never reach it.",+ "steps": ["Attach the pointerdown listener to the document instead of the menu root"],+ "edits": [{"path": "src/menu.js", "start_line": 16, "end_line": 21, "reason": "The outside-press listener is on the menu, not the document"}],+ "new_files": [],+ "tests": [{"action": "run", "path": "test/menu.test.js", "what": "a press outside the menu closes it"}],+ "risks": []+ },+ "rounds": [+ {+ "explanation": "src/menu.js:17 attaches the outside-press listener to the menu root, so a press on the canvas never reaches it; listening on the document lets src/menu.js:18 see presses outside the menu and close it.",+ "edits": [{"path": "src/menu.js", "search": " root.addEventListener(\"pointerdown\", (event) => {", "replace": " doc.addEventListener(\"pointerdown\", (event) => {"}],+ "new_files": [],+ "tests": ["node --test test/*.test.js"]+ }+ ]+ }+ }+}diff --git a/demo/flow/test_flow.py b/demo/flow/test_flow.pynew file mode 100644index 0000000..0eb49ad--- /dev/null+++ b/demo/flow/test_flow.py@@ -0,0 +1,224 @@+#!/usr/bin/env python3+"""Tests of mock_meta.py's computer use and fix replies, and of the flow script's receipt: python3 -m unittest+test_flow (from this folder). They need nothing else: no binary, browser or model."""+import argparse+import json+import os+import sys+import tempfile+import unittest+from pathlib import Path++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+sys.path.insert(0, os.path.dirname(HERE))+import browser_driver # noqa: E402+import flow # noqa: E402+import mock_meta # noqa: E402++PNG = "data:image/png;base64,iVBORw0KGgo="+++def scripted(variable, value):+ handle = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False)+ json.dump(value, handle)+ handle.close()+ os.environ[variable] = handle.name+ return handle.name+++class MockComputerUse(unittest.TestCase):+ def setUp(self):+ self.path = scripted("MOCK_COMPUTER_SCRIPT", {"runs": [{"match": "Reproduce", "steps": [+ {"actions": [{"type": "click", "button": "left", "x": 1, "y": 2}],+ "safety": [{"id": "csc_1", "code": "mock_check", "message": "Scripted."}]},+ {"answer": {"shown": "bug", "point": {"x": 1, "y": 2}, "summary": "Shown."}}]}]})++ def tearDown(self):+ os.unlink(self.path)+ os.environ.pop("MOCK_COMPUTER_SCRIPT")++ def request(self, *items):+ first = {"role": "user", "content": [{"type": "input_text", "text": "Reproduce this issue: ..."},+ {"type": "input_image", "image_url": PNG}]}+ return {"model": "muse-wonder-1.0", "tools": [{"type": "computer"}], "store": False,+ "input": [first, *items]}++ def answer(self, call, acknowledged=None, url=PNG):+ return {"type": "computer_call_output", "call_id": call["call_id"],+ "acknowledged_safety_checks": call["pending_safety_checks"] if acknowledged is None else acknowledged,+ "output": {"type": "computer_screenshot", "image_url": url}}++ def test_a_run_gives_its_call_then_its_answer_with_the_prefix_cached(self):+ _, output, usage = mock_meta.reply(self.request(), 100)+ call = output[0]+ self.assertEqual(call["type"], "computer_call")+ self.assertEqual(call["pending_safety_checks"][0]["id"], "csc_1")+ self.assertIn("meta_safety_replay_receipt", call)+ self.assertEqual(usage["input_tokens_details"]["cached_tokens"], 0)+ _, output, usage = mock_meta.reply(self.request(call, self.answer(call)), 100)+ self.assertEqual(output[0]["type"], "message")+ self.assertEqual(json.loads(output[0]["content"][0]["text"])["shown"], "bug")+ self.assertGreater(usage["input_tokens_details"]["cached_tokens"], 0)+ self.assertGreater(usage["input_tokens"], usage["input_tokens_details"]["cached_tokens"])++ def test_encrypted_reasoning_comes_before_each_call_and_must_be_replayed(self):+ request = self.request()+ request["include"] = ["reasoning.encrypted_content"]+ _, output, _ = mock_meta.reply(request, 100)+ thought, call = output+ self.assertEqual((thought["type"], call["type"]), ("reasoning", "computer_call"))+ self.assertIn("encrypted_content", thought)+ replay = self.request(thought, call, self.answer(call))+ replay["include"] = request["include"]+ self.assertEqual(mock_meta.reply(replay, 100)[1][0]["type"], "message")+ without = self.request(call, self.answer(call))+ without["include"] = request["include"]+ with self.assertRaises(mock_meta.Refused):+ mock_meta.reply(without, 100)++ def test_requests_that_break_the_replay_are_refused(self):+ _, output, _ = mock_meta.reply(self.request(), 100)+ call = output[0]+ for items in ((call, self.answer(call, acknowledged=[])),+ (dict(call, actions=[]), self.answer(call)),+ (dict(call, meta_safety_replay_receipt="changed"), self.answer(call)),+ (call, self.answer(call, url="https://example.com/a.png"))):+ with self.assertRaises(mock_meta.Refused):+ mock_meta.reply(self.request(*items), 100)+ other = self.request()+ other["input"][0]["content"][0]["text"] = "Something else"+ with self.assertRaises(mock_meta.Refused):+ mock_meta.reply(other, 100)+++class MockFix(unittest.TestCase):+ def test_the_plan_and_each_round_come_from_the_script(self):+ path = scripted("MOCK_FIX_SCRIPT", {"plan": {"summary": "Plan."},+ "rounds": [{"explanation": "One."}, {"explanation": "Two."}]})+ try:+ plan = {"model": "muse-wonder-1.0", "instructions": "You plan a change to a code repository.",+ "input": "pack", "text": {"format": {}}}+ self.assertEqual(json.loads(mock_meta.reply(plan, 10)[1][0]["content"][0]["text"])["summary"], "Plan.")+ edits = dict(plan, instructions="You fix an issue in a code repository.")+ for prompt, expected in (("Round 1: return the edits.\n", "One."),+ ("Round 1 failed\nRound 2: return the edits.\n", "Two."),+ ("Round 3: return the edits.\n", "Two.")):+ text = mock_meta.reply(dict(edits, input=prompt), 10)[1][0]["content"][0]["text"]+ self.assertEqual(json.loads(text)["explanation"], expected)+ finally:+ os.unlink(path)+ os.environ.pop("MOCK_FIX_SCRIPT")++ def test_other_replies_are_unchanged(self):+ ask = {"model": "muse-spark-1.3", "input": "### src/a.ts lines 1-9\ncode"}+ _, output, usage = mock_meta.reply(ask, 400)+ self.assertIn("`src/a.ts:1`", output[0]["content"][0]["text"])+ self.assertEqual(usage["input_tokens"], 100)+++class RunProfiles(unittest.TestCase):+ def flow_for(self, folder, models):+ path = Path(folder) / "models.json"+ path.write_text(json.dumps({"models": models}))+ args = argparse.Namespace(out=os.path.join(folder, "out"), data_dir=None, host="127.0.0.1", mock=False,+ models=str(path), see_model="wonder", fix_model="wonder", read_model="spark",+ sam_model="sam", max_run_cost=3.0, max_output=16384)+ return flow.Flow(args, {})++ def test_the_run_gets_its_own_profiles_with_caps_that_add_up_to_the_run_cap(self):+ price = {"input": 4.0, "cached_input": 0.2, "output": 20.0}+ models = {"wonder": {"protocol": "responses", "base_url": "https://api.meta.ai/v1",+ "model": "muse-wonder-1.0", "output_limit": 131072, "price": price},+ "spark": {"protocol": "responses", "base_url": "https://api.meta.ai/v1",+ "model": "muse-spark-1.3", "price": price, "max_cost_per_call": 0.05},+ "sam": {"protocol": "responses", "base_url": "https://api.meta.ai/v1", "model": "sam-3.1",+ "price": {"input": 0, "output": 0, "per_image": 0.0025}}}+ with tempfile.TemporaryDirectory() as folder:+ run = self.flow_for(folder, models)+ run.prepare_models()+ written = json.loads(run.models_file.read_text())["models"]+ self.assertEqual(run.profiles["see"], run.profiles["fix"])+ self.assertTrue(all(name.startswith("flow-") and name.endswith(run.run_id) for name in written))+ wonder, spark, sam = (written[run.profiles[r]] for r in ("fix", "read", "sam"))+ self.assertEqual(wonder["output_limit"], 16384)+ self.assertEqual(wonder["key_env"], "MODEL_API_KEY")+ self.assertAlmostEqual(wonder["max_cost_per_day"] + spark["max_cost_per_day"] + sam["max_cost_per_day"], 3.0)+ self.assertEqual(spark["max_cost_per_call"], 0.05)+ self.assertNotIn("output_limit", sam)++ def test_different_see_and_fix_profiles_split_the_budget(self):+ price = {"input": 4.0, "cached_input": 0.2, "output": 20.0}+ models = {name: {"protocol": "responses", "base_url": "https://api.meta.ai/v1", "model": model,+ "price": price}+ for name, model in (("wonder", "muse-wonder-1.0"), ("spark", "muse-spark-1.3"),+ ("sam", "sam-3.1"))}+ with tempfile.TemporaryDirectory() as folder:+ run = self.flow_for(folder, models)+ run.args.see_model = "spark"+ run.prepare_models()+ caps = run.caps+ self.assertNotEqual(run.profiles["see"], run.profiles["fix"])+ self.assertEqual(run.profiles["see"], run.profiles["read"])+ self.assertLessEqual(sum(caps.values()), 3.0 + 1e-9)+ self.assertAlmostEqual(caps[run.profiles["fix"]], 2.7 * (1 - flow.SEE_SHARE), places=3)++ def test_an_unpriced_profile_is_refused(self):+ models = {name: {"protocol": "responses", "base_url": "https://api.meta.ai/v1", "model": name}+ for name in ("wonder", "spark", "sam")}+ with tempfile.TemporaryDirectory() as folder:+ run = self.flow_for(folder, models)+ with self.assertRaises(SystemExit):+ run.prepare_models()+++class Driver(unittest.TestCase):+ def test_a_socket_is_judged_by_its_pages_origin(self):+ self.assertEqual(browser_driver.socket_origin("ws://App.test:3101/socket"), "http://app.test:3101")+ self.assertEqual(browser_driver.socket_origin("wss://collab.example.com/x"), "https://collab.example.com")+ self.assertEqual(browser_driver.origin("http://App.test:3101/a?b"), "http://app.test:3101")+++class Receipt(unittest.TestCase):+ def test_actions_read_as_words(self):+ self.assertEqual(flow.describe({"type": "click", "button": "left", "x": 4, "y": 5}), "click (4, 5)")+ self.assertEqual(flow.describe({"type": "keypress", "keys": ["CTRL", "A"]}), "keys CTRL+A")+ self.assertEqual(flow.describe({"type": "double_click", "x": 1, "y": 2}), "double click (1, 2)")++ def test_the_receipt_adds_up_the_ledger_and_says_when_it_is_a_mock(self):+ rows = [{"model": "muse-wonder-1.0", "input_tokens": 1000, "cached_tokens": 600, "output_tokens": 50,+ "cost_usd": 0.003},+ {"model": "sam-3.1", "input_tokens": None, "cached_tokens": None, "output_tokens": None,+ "cost_usd": 0.0025}]+ total = flow.totals(rows)+ self.assertEqual((total["calls"], total["input_tokens"], total["cached_tokens"]), (2, 1000, 600))+ self.assertAlmostEqual(total["cost_usd"], 0.0055)+ self.assertEqual(total["models"], ["muse-wonder-1.0", "sam-3.1"])+ receipt = {"mode": "mock", "target": {"name": "fixture", "issue": "The menu stays open."},+ "result": "fixed and checked", "run_id": "r", "started": "s", "finished": "f",+ "repository": {"checkout": {"fixture": "fixture"}, "head": "0123456789abcdef"},+ "total": total, "max_run_cost_usd": 3.0, "screen_checks": {},+ "steps": {"see": {"summary": "Shown.", "result": "reproduced", "point": {"x": 1, "y": 2},+ "actions": [{"step": 1, "actions": ["click (1, 2)"], "error": None}],+ "acknowledged": [{"step": 1, "check": {"code": "c", "message": "m"}}],+ "screenshot": "before.png", "usage": total}}}+ text = flow.markdown(receipt)+ self.assertIn("**Mock run.**", text)+ self.assertIn("", text)+ self.assertIn("Acknowledged safety check at step 1", text)+ self.assertIn("| see | 2 |", text)+ receipt["mode"] = "live"+ self.assertNotIn("Mock run", flow.markdown(receipt))+ receipt["steps"]["fix"] = {"plan": "Listen on the document.", "branch": "flow/r", "commit": "abc",+ "result": "passed", "test_command": "node --test", "rounds": [],+ "pack": {"layout": "standard", "tokens": 1234, "files": 5, "budget": 200000},+ "diff": "", "test_tail": ""}+ receipt["answer_key"] = {"about": "The planted bug.", "files": ["src/menu.js"],+ "touched_the_same_files": True, "files_in_the_pack": ["src/menu.js"]}+ text = flow.markdown(receipt)+ self.assertIn("Pack: standard layout, 1,234 tokens in 5 files (budget 200,000)", text)+ self.assertIn("the fix's pack held 1 of its 1 file(s)", text)+++if __name__ == "__main__":+ unittest.main()diff --git a/demo/mock_meta.py b/demo/mock_meta.pynew file mode 100644index 0000000..d49910f--- /dev/null+++ b/demo/mock_meta.py@@ -0,0 +1,213 @@+#!/usr/bin/env python3+"""mock_meta.py HOST PORT: a stand-in for the Meta Model API's Responses endpoint, for the demo's tests and the flow.++POST /v1/responses answers as the real models' formats do, with made-up content and no model:+- `sam-*`: one segmentation record, a 160x28 box around the prompt's point;+- the reading call of `graphicle pixel` (instructions "You read one element"): the strings in MOCK_STRINGS+ (separated by `|`, default "Open Folder...") and the labels in MOCK_NEARBY (default none);+- computer use (the tool {"type":"computer"}, `graphicle see`): the scripted run of MOCK_COMPUTER_SCRIPT whose+ "match" text the task holds (see below), with its replay checked;+- `fix`'s plan ("You plan a change") and edits ("You fix an issue"): MOCK_FIX_SCRIPT's "plan" and "rounds" (round N+ gets the Nth, the last repeats); without the file, a plan of the pack's first file and no edits;+- another structured call (`text.format`): a ranking of the first file the pack shows, and an explanation;+- anything else (`ask --pack`): a short answer that cites the first file the pack shows.+Usage counts are a quarter of the bytes sent (text bytes and 1,500 tokens an image for computer use, with the+replayed prefix as cached). Nothing is logged.++MOCK_COMPUTER_SCRIPT is a JSON file: {"runs": [{"match": TEXT, "steps": [STEP, ...]}, ...]}. A STEP is+{"actions": [...], "safety": [{"id","code","message"}, ...]} (a computer_call), or {"answer": {...}} (the final+message, as JSON). The step of a request is the number of computer_call_output items it holds. When the request+asks for include ["reasoning.encrypted_content"], each call comes after a reasoning item with encrypted content.+The mock refuses a request with HTTP 400 when it breaks the replay that Meta's computer-use page describes: a+reasoning item or call not sent back as returned, an output that does not answer its call with a PNG or JPEG data+URL, or a pending safety check not acknowledged.+"""+import json+import os+import re+import sys+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++IMAGE_TOKENS = 1500+++class Refused(Exception):+ pass+++def text_of(value):+ if isinstance(value, str):+ return value+ parts = []+ for message in value or []:+ for part in message.get("content", []) if isinstance(message, dict) else []:+ if isinstance(part, dict) and part.get("type") == "input_text":+ parts.append(part.get("text", ""))+ return "\n".join(parts)+++def load(variable):+ path = os.environ.get(variable)+ if not path:+ return None+ with open(path) as f:+ return json.load(f)+++def tokens(value):+ """Text bytes over four, and IMAGE_TOKENS for each image data URL."""+ if isinstance(value, str):+ return IMAGE_TOKENS if value.startswith("data:image/") else len(value) // 4+ if isinstance(value, list):+ return sum(tokens(v) for v in value)+ if isinstance(value, dict):+ return sum(len(k) // 4 + tokens(v) for k, v in value.items())+ return 1+++def computer_call(step, spec):+ return {"type": "computer_call", "id": f"cc_mock_{step}", "call_id": f"call_mock_{step}",+ "actions": spec.get("actions", []), "pending_safety_checks": spec.get("safety", []),+ "status": "completed", "meta_safety_replay_receipt": f"mock-receipt-{step}"}+++def reasoning(step):+ return {"type": "reasoning", "id": f"rs_mock_{step}",+ "summary": [{"type": "summary_text", "text": "A scripted step of the mock."}],+ "encrypted_content": f"mock-encrypted-{step}"}+++def computer(request):+ """One step of a scripted computer-use run: the output items and their usage."""+ script = load("MOCK_COMPUTER_SCRIPT") or {"runs": []}+ items = request.get("input") or []+ task = text_of(items[:1])+ run = next((r for r in script.get("runs", []) if r.get("match", "") in task), None)+ if run is None:+ raise Refused("the mock has no scripted run for this task")+ steps = run["steps"]+ replayed = items[1:]+ # With encrypted reasoning asked for, each step comes back as its reasoning item, its call and its output.+ thinking = "reasoning.encrypted_content" in (request.get("include") or [])+ width = 3 if thinking else 2+ for index in range(0, len(replayed), width):+ step = index // width+ group = replayed[index:index + width]+ if thinking:+ if group[0] != reasoning(step):+ raise Refused(f"the reasoning of step {step} was not replayed unchanged")+ group = group[1:]+ expected = computer_call(step, steps[min(step, len(steps) - 1)])+ if not group or group[0] != expected:+ raise Refused(f"the computer_call of step {step} was not replayed unchanged")+ output = group[1] if len(group) > 1 else {}+ url = (output.get("output") or {}).get("image_url") or ""+ if output.get("type") != "computer_call_output" or output.get("call_id") != expected["call_id"] \+ or not re.match(r"data:image/(png|jpeg);base64,", url):+ raise Refused(f"the output of step {step} does not answer its call with a screenshot")+ if output.get("acknowledged_safety_checks") != expected["pending_safety_checks"]:+ raise Refused(f"the pending safety checks of step {step} were not acknowledged")+ step = len(replayed) // width+ spec = steps[min(step, len(steps) - 1)]+ if "answer" in spec:+ text = json.dumps(spec["answer"])+ output = [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}]+ output_tokens = 40 + len(text) // 4+ else:+ call = computer_call(step, spec)+ output = [reasoning(step), call] if thinking else [call]+ output_tokens = 40 + 15 * len(call["actions"])+ instructions = tokens(request.get("instructions") or "")+ total = instructions + tokens(items)+ cached = 0 if step == 0 else min(total, instructions + tokens(items[:-1]))+ return output, {"input_tokens": total, "output_tokens": output_tokens,+ "input_tokens_details": {"cached_tokens": cached},+ "output_tokens_details": {"reasoning_tokens": 0}}+++def fix_reply(instructions, prompt, first):+ script = load("MOCK_FIX_SCRIPT") or {}+ if instructions.startswith("You plan a change"):+ if "plan" in script:+ return json.dumps(script["plan"])+ edits = [{"path": first.group(1), "start_line": int(first.group(2)), "end_line": int(first.group(2)),+ "reason": "The mock picks the first file."}] if first else []+ return json.dumps({"summary": "A mock plan.", "steps": ["Change the first file"], "edits": edits,+ "new_files": [], "tests": [], "risks": []})+ rounds = script.get("rounds") or [{"explanation": "The mock has no edits.", "edits": [], "new_files": [],+ "tests": []}]+ found = re.findall(r"Round (\d+): return the edits\.", prompt)+ number = int(found[-1]) if found else 1+ return json.dumps(rounds[min(number, len(rounds)) - 1])+++def reply(request, length):+ """The output items, model and usage of a reply to a request of `length` bytes."""+ model = request.get("model", "")+ if any(isinstance(t, dict) and t.get("type") == "computer" for t in request.get("tools") or []):+ output, usage = computer(request)+ return model, output, usage+ prompt = text_of(request.get("input"))+ instructions = request.get("instructions") or ""+ first = re.search(r"^### (\S+) lines (\d+)-(\d+)", prompt, re.M)+ cite = f"{first.group(1)}:{first.group(2)}" if first else None+ if model.startswith("sam-"):+ m = re.search(r"point;x=(\d+);y=(\d+);w=(\d+);h=(\d+)", prompt)+ text = ""+ if m:+ x, y, w, h = map(int, m.groups())+ x1, y1, x2, y2 = max(0, x - 80), max(0, y - 14), min(w - 1, x + 80), min(h - 1, y + 14)+ text = f"<0f>1<|box;x1={x1};y1={y1};x2={x2};y2={y2};w={w};h={h};c=0.9|>"+ elif instructions.startswith("You read one element"):+ strings = os.environ.get("MOCK_STRINGS", "Open Folder...").split("|")+ nearby = [t for t in os.environ.get("MOCK_NEARBY", "").split("|") if t]+ text = json.dumps({"strings": strings, "element_type": "button", "icon": "",+ "nearby_labels": nearby, "names": []})+ elif instructions.startswith(("You plan a change", "You fix an issue")):+ text = fix_reply(instructions, prompt, first)+ elif request.get("text", {}).get("format"):+ ranking = [{"path": first.group(1), "line": int(first.group(2)), "reason": "The mock picks the first file."}] if first else []+ text = json.dumps({"ranking": ranking, "explanation": f"A mock explanation citing {cite}."})+ else:+ text = "This answer comes from a mock model, not Muse Spark."+ if cite:+ text += f" The pack's first file is `{cite}`."+ item = {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}+ usage = None+ if not model.startswith("sam-"):+ usage = {"input_tokens": length // 4, "output_tokens": max(1, len(text) // 4),+ "input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}+ return model, [item], usage+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def send(self, status, body):+ data = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def do_POST(self):+ length = int(self.headers.get("Content-Length") or 0)+ raw = self.rfile.read(length) or b"{}"+ if self.path.rstrip("/").endswith("/responses/input_tokens"):+ self.send(200, {"input_tokens": length // 4})+ return+ try:+ model, output, usage = reply(json.loads(raw), length)+ except Refused as e:+ self.send(400, {"error": {"message": str(e), "type": "invalid_request_error"}})+ return+ body = {"id": "resp_mock", "object": "response", "status": "completed", "model": model, "output": output}+ if usage:+ body["usage"] = usage+ self.send(200, body)+++if __name__ == "__main__":+ ThreadingHTTPServer((sys.argv[1], int(sys.argv[2])), Handler).serve_forever()diff --git a/demo/models.example.json b/demo/models.example.jsonnew file mode 100644index 0000000..937982d--- /dev/null+++ b/demo/models.example.json@@ -0,0 +1,25 @@+{+ "default_model": "spark",+ "models": {+ "spark": {+ "protocol": "responses",+ "base_url": "https://api.meta.ai/v1",+ "model": "muse-spark-1.3",+ "key_env": "MODEL_API_KEY",+ "input_limit": 1016576,+ "output_limit": 32000,+ "reasoning_effort": "medium",+ "price": {"input": 1.25, "output": 4.25, "cached_input": 0.15},+ "max_cost_per_call": 1.5,+ "max_cost_per_day": 10+ },+ "sam": {+ "protocol": "responses",+ "base_url": "https://api.meta.ai/v1",+ "model": "sam-3.1",+ "key_env": "MODEL_API_KEY",+ "price": {"input": 0, "output": 0, "per_image": 0.0025},+ "max_cost_per_day": 2+ }+ }+}diff --git a/demo/record.py b/demo/record.pynew file mode 100644index 0000000..ecb019c--- /dev/null+++ b/demo/record.py@@ -0,0 +1,44 @@+#!/usr/bin/env python3+"""record.py DEMO_CONFIG QUESTIONS OUT: record the curated questions' answers for the demo.++Runs each question of QUESTIONS (curated.questions.json) through the same `graphicle ask --pack` call as the+server, live, and writes OUT (curated.json): the answer, its checked citations with links, the pack's+make-up, the tokens, the cached share, the cost and the time, and when it was recorded. The server shows these+answers when the day's budget is used up or no key is set. Each call goes in the spend log like any other.+With --mock (tests only) the entries are marked "mock", and the page says so next to each.+"""+import json+import sys+from datetime import datetime, timezone++import server+++def main(argv):+ mock = "--mock" in argv+ config_path, questions_path, out = [a for a in argv[1:] if a != "--mock"]+ demo = server.Demo(server.load_config(config_path))+ recorded = []+ for item in json.load(open(questions_path)):+ repo = demo.repos.get(item["repo"])+ if not repo:+ print("skipped, unknown repository:", item["repo"], flush=True)+ continue+ try:+ answer = demo.ask(repo, item["question"])+ except server.CallFailed as failure:+ print("failed:", item["repo"], item["question"][:60], "-", str(failure)[:200], flush=True)+ continue+ answer.update(repo=item["repo"], question=item["question"], mode="mock" if mock else "live",+ recorded_at=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%MZ"))+ recorded.append(answer)+ usage = answer.get("usage") or {}+ print(item["repo"], "|", item["question"][:60], "|", usage.get("input_tokens"), "in,",+ usage.get("cost_usd"), "USD", flush=True)+ with open(out, "w") as f:+ json.dump(recorded, f, indent=1)+ print(len(recorded), "answers recorded in", out)+++if __name__ == "__main__":+ main(sys.argv)diff --git a/demo/server.py b/demo/server.pynew file mode 100644index 0000000..5b4782b--- /dev/null+++ b/demo/server.py@@ -0,0 +1,415 @@+#!/usr/bin/env python3+"""Graphicle's hosted demo: ask a large repository a question, or point at a pixel of a screenshot.++A thin, read-only web server that runs the `graphicle` binary for each request, `graphicle ask --pack` and+`graphicle pixel`, with fixed arguments and never a shell. Graphicle's own local server (`graphicle serve`,+`graphicle open`) is never exposed: it has write APIs.++Safety and cost:+- a rate limit per client address, kept in memory;+- at most `max_concurrent` model requests at once;+- a daily dollar cap: the spend log's total for the day (UTC) from `graphicle usage`, over every data folder;+ the profiles' own `max_cost_per_day` in the models file stays the hard stop;+- at the cap, or with no model key, the curated questions' stored answers are shown, with their recorded cost;+- nothing a visitor sends is logged or kept: a question goes to the binary only, a screenshot is a temporary+ file deleted after the call, and the request log has no addresses, questions or answers. The spend log keeps+ only its own fields: when, which command and model, the project, tokens, cost and status.++Configuration: the JSON file in DEMO_CONFIG (see demo.example.json). The model key comes from the environment+variable the models file names (MODEL_API_KEY for the Meta Model API), never from the configuration.+"""+import base64+import json+import os+import re+import subprocess+import sys+import tempfile+import threading+import time+from collections import deque+from datetime import datetime, timezone+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlparse++HERE = os.path.dirname(os.path.abspath(__file__))+MAX_BODY = 12 << 20+MAX_IMAGE = 8 << 20+MAX_QUESTION = 600+STATIC_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png"}+KNOWN_PATHS = {"/", "/healthz", "/api/config", "/api/ask", "/api/pixel", "/app.js", "/style.css"}+SECURITY_HEADERS = {+ "Content-Security-Policy": "default-src 'self'; img-src 'self' data: blob:; style-src 'self'; "+ "script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'",+ "X-Content-Type-Options": "nosniff",+ "Referrer-Policy": "no-referrer",+ "X-Frame-Options": "DENY",+ "Cache-Control": "no-store",+}+++def load_config(path):+ with open(path) as f:+ return load_config_dict(json.load(f))+++def load_config_dict(config):+ config = dict(config)+ config.setdefault("listen", "0.0.0.0")+ config.setdefault("port", 8080)+ config.setdefault("binary", "graphicle")+ config.setdefault("daily_cap_usd", 10.0)+ config.setdefault("max_concurrent", 2)+ config.setdefault("per_minute", 3)+ config.setdefault("per_day", 30)+ config.setdefault("trust_proxy", False)+ config.setdefault("timeout_seconds", 300)+ config.setdefault("key_env", "MODEL_API_KEY")+ config.setdefault("state_dir", tempfile.mkdtemp(prefix="graphicle-demo-"))+ for repo in config["repos"]:+ for field in ("id", "github", "commit", "data_dir", "project"):+ if not repo.get(field):+ raise SystemExit(f"repos[].{field} is required")+ return config+++class Limiter:+ """At most `per_minute` and `per_day` requests for each key (a client address)."""++ def __init__(self, per_minute, per_day):+ self.per_minute, self.per_day = per_minute, per_day+ self.seen = {}+ self.lock = threading.Lock()++ def allow(self, key, now=None):+ now = time.time() if now is None else now+ with self.lock:+ times = self.seen.setdefault(key, deque())+ while times and now - times[0] > 86400:+ times.popleft()+ last_minute = sum(1 for t in times if now - t < 60)+ if last_minute >= self.per_minute:+ return False, 60+ if len(times) >= self.per_day:+ return False, int(86400 - (now - times[0])) + 1+ times.append(now)+ if len(self.seen) > 100_000: # forget the oldest keys first+ for stale in [k for k, v in self.seen.items() if not v or now - v[-1] > 86400]:+ del self.seen[stale]+ return True, 0+++def github_link(repo, path, line=None, end=None):+ url = f"https://github.com/{repo['github']}/blob/{repo['commit']}/{path}"+ if line:+ url += f"#L{line}" + (f"-L{end}" if end and end != line else "")+ return url+++def image_type(data):+ if data.startswith(b"\x89PNG\r\n\x1a\n"):+ return ".png"+ if data.startswith(b"\xff\xd8"):+ return ".jpg"+ if data.startswith(b"RIFF") and data[8:12] == b"WEBP":+ return ".webp"+ if data.startswith(b"GIF87a") or data.startswith(b"GIF89a"):+ return ".gif"+ return None+++def normalized(question):+ return re.sub(r"\s+", " ", question.strip().lower())+++class Demo:+ def __init__(self, config):+ self.config = config+ self.repos = {r["id"]: r for r in config["repos"]}+ self.limiter = Limiter(config["per_minute"], config["per_day"])+ self.running = threading.BoundedSemaphore(config["max_concurrent"])+ self.spend_cache = (0.0, None)+ self.spend_lock = threading.Lock()+ curated = config.get("curated")+ self.curated = []+ if curated and os.path.exists(curated):+ with open(curated) as f:+ self.curated = json.load(f)+ self.last_failure = None+ self.paused_until = 0.0+ self.home = os.path.join(config["state_dir"], "home")+ self.scratch = os.path.join(config["state_dir"], "scratch")+ os.makedirs(self.home, mode=0o700, exist_ok=True)+ os.makedirs(self.scratch, mode=0o700, exist_ok=True)++ # ---- the binary+ def env(self):+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": self.home, "LANG": "C.UTF-8",+ "GRAPHICLE_FRESHNESS": "off", "GRAPHICLE_NO_UPDATE_NOTIFIER": "1",+ "GRAPHICLE_NO_BROWSER": "1"}+ for name in [self.config["key_env"]] + self.config.get("pass_env", []):+ if os.environ.get(name):+ env[name] = os.environ[name]+ return env++ def graphicle(self, repo, args, timeout=None):+ argv = [self.config["binary"], "--data-dir", repo["data_dir"]]+ if self.config.get("models"):+ argv += ["--config", self.config["models"]]+ done = subprocess.run(argv + args, capture_output=True, text=True, env=self.env(),+ timeout=timeout or self.config["timeout_seconds"], stdin=subprocess.DEVNULL)+ if done.returncode != 0:+ last = [line for line in done.stderr.strip().splitlines() if line.strip()][-1:] or ["failed"]+ self.last_failure = last[0][:500] # for the operator's tests; never logged or sent+ raise CallFailed(last[0])+ return json.loads(done.stdout)++ def live(self):+ return (bool(self.config.get("live", True)) and bool(os.environ.get(self.config["key_env"]))+ and time.time() >= self.paused_until)++ def spent_today(self):+ """The day's spend (UTC) in US dollars over every data folder, from the spend logs."""+ with self.spend_lock:+ amount, when = self.spend_cache+ if when and time.time() - when < 15:+ return amount+ day = datetime.now(timezone.utc).strftime("%Y-%m-%d")+ total = 0.0+ for data_dir in sorted({r["data_dir"] for r in self.repos.values()}):+ try:+ report = self.graphicle({"data_dir": data_dir}, ["usage", "--since", day, "--json"], 60)+ total += float(report.get("total", {}).get("cost_usd") or 0.0)+ except (CallFailed, subprocess.TimeoutExpired, ValueError):+ total = float("inf") # an unreadable log stops live calls+ self.spend_cache = (total, time.time())+ return total++ def budget_left(self):+ return self.spent_today() < float(self.config["daily_cap_usd"])++ # ---- answers+ def stored(self, repo_id, question):+ for entry in self.curated:+ if entry.get("repo") == repo_id and normalized(entry.get("question", "")) == normalized(question):+ return dict(entry, stored=True)+ return None++ def ask(self, repo, question):+ args = ["ask", "--pack", "--project", repo["project"], "--layout", "cache", "--json"]+ if self.config.get("ask_profile"):+ args += ["--model", self.config["ask_profile"]]+ if self.config.get("ask_budget"):+ args += ["--budget", str(int(self.config["ask_budget"]))]+ report = self.graphicle(repo, args + ["--", question])+ citations = [dict(c, url=github_link(repo, c["path"], c.get("line"), c.get("end_line")))+ for c in report.get("citations", []) if c.get("valid")]+ usage = report.get("usage") or {}+ input_tokens = usage.get("input_tokens") or 0+ return {"answer": report.get("answer", ""), "citations": citations,+ "invalid_citations": report.get("invalid_citations", 0),+ "model": report.get("model"), "usage": usage,+ "cached_share": round((usage.get("cached_tokens") or 0) / input_tokens, 3) if input_tokens else None,+ "pack": pack_makeup(report.get("pack") or {})}++ def pixel(self, repo, image, x, y):+ suffix = image_type(image)+ handle, path = tempfile.mkstemp(suffix=suffix, dir=self.scratch)+ try:+ with os.fdopen(handle, "wb") as f:+ f.write(image)+ report = self.graphicle(repo, ["pixel", path, "--at", f"{x},{y}", "--project", repo["project"],+ "--json"])+ finally:+ os.unlink(path)+ report.pop("screenshot", None) # it names the temporary file+ for c in report.get("candidates", []):+ c["url"] = github_link(repo, c["path"], c.get("line"))+ for caller in c.get("callers", []):+ caller["url"] = github_link(repo, caller["path"], caller.get("line"))+ return report+++def pack_makeup(pack):+ """What the pack held, in a visitor's words: its layout, files and tokens, the repository part that is the+ same for every question (and so cached) and the question part, the budget and the time to pack."""+ rows = {}+ if pack.get("layout"):+ rows["layout"] = pack["layout"]+ if isinstance(pack.get("included"), list):+ rows["files in the pack"] = len(pack["included"])+ tokens, prefix = pack.get("tokens"), pack.get("prefix_tokens")+ if isinstance(tokens, int):+ rows["tokens in the pack"] = tokens+ if isinstance(prefix, int) and prefix > 0:+ rows["repository part (the same for every question)"] = prefix+ if isinstance(tokens, int):+ rows["question part"] = tokens - prefix+ if isinstance(pack.get("budget"), int):+ rows["budget"] = pack["budget"]+ if isinstance(pack.get("seconds"), (int, float)):+ rows["packed in"] = f"{pack['seconds']:.1f} s"+ return rows+++class CallFailed(Exception):+ pass+++CREDIT_WORDS = ("insufficient", "quota", "credit", "billing", "payment", "402")+++def out_of_credits(message):+ """A provider's refusal that says the account cannot pay for more calls."""+ lower = message.lower()+ return any(word in lower for word in CREDIT_WORDS)+++def public_error(message):+ """A binary's error as a visitor may read it: the cap's refusal in plain words, else a generic line."""+ if "Refused before sending" in message or "max_cost_per_day" in message:+ return "The demo's budget for today is used up."+ if "max_cost_per_call" in message:+ return "This request would cost more than the demo allows for one call."+ return "The request failed. Please try again later."+++def make_handler(demo):+ class Handler(BaseHTTPRequestHandler):+ server_version = "graphicle-demo"+ sys_version = ""++ def log_message(self, *args): # no addresses, no paths with user text+ pass++ def log(self, status, started):+ path = urlparse(self.path).path+ shown = path if path in KNOWN_PATHS else "(other)" # a typed path is visitor text+ print(f"{datetime.now(timezone.utc).strftime('%H:%M:%SZ')} {self.command} {shown} {status} "+ f"{time.time() - started:.1f}s", flush=True)++ def client(self):+ if demo.config["trust_proxy"] and self.headers.get("X-Forwarded-For"):+ return self.headers["X-Forwarded-For"].split(",")[0].strip()+ return self.client_address[0]++ def send(self, status, body, content_type="application/json; charset=utf-8", extra=None):+ data = body if isinstance(body, bytes) else json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(data)))+ for k, v in {**SECURITY_HEADERS, **(extra or {})}.items():+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self):+ started = time.time()+ path = urlparse(self.path).path+ status = 200+ if path == "/healthz":+ self.send(200, {"ok": True})+ elif path == "/api/config":+ self.send(200, {+ "repos": [{"id": r["id"], "github": r["github"], "commit": r["commit"],+ "pixel": bool(r.get("pixel"))} for r in demo.repos.values()],+ "live": demo.live(), "daily_cap_usd": demo.config["daily_cap_usd"],+ "spent_today_usd": round(min(demo.spent_today(), 1e9), 4),+ "curated": [{"repo": c["repo"], "question": c["question"], "mode": c.get("mode")}+ for c in demo.curated]})+ else:+ name = "index.html" if path == "/" else path.lstrip("/")+ full = os.path.normpath(os.path.join(HERE, "static", name))+ if not full.startswith(os.path.join(HERE, "static") + os.sep) or not os.path.isfile(full):+ status = 404+ self.send(404, {"error": "not found"})+ else:+ with open(full, "rb") as f:+ self.send(200, f.read(), STATIC_TYPES.get(os.path.splitext(full)[1], "text/plain"))+ self.log(status, started)++ def do_POST(self):+ started = time.time()+ status, body = self.post()+ self.send(status, body, extra={"Retry-After": str(body.get("retry_after"))}+ if body.get("retry_after") else None)+ self.log(status, started)++ def post(self):+ path = urlparse(self.path).path+ if path not in ("/api/ask", "/api/pixel"):+ return 404, {"error": "not found"}+ length = int(self.headers.get("Content-Length") or 0)+ if length <= 0 or length > MAX_BODY:+ return 413, {"error": "The request is too large."}+ try:+ request = json.loads(self.rfile.read(length))+ except ValueError:+ return 400, {"error": "The request is not JSON."}+ repo = demo.repos.get(request.get("repo"))+ if not repo:+ return 400, {"error": "Unknown repository."}+ if path == "/api/ask":+ question = str(request.get("question") or "").strip()+ if not 3 <= len(question) <= MAX_QUESTION:+ return 400, {"error": f"Ask a question of 3 to {MAX_QUESTION} characters."}+ stored = demo.stored(repo["id"], question)+ if not demo.live() or not demo.budget_left():+ if stored:+ return 200, stored+ return 503, {"error": "Live answers are paused (no budget left today). The curated "+ "questions below have recorded answers.", "paused": True}+ else:+ if not repo.get("pixel"):+ return 400, {"error": "Pixel to code is set up for the vscode repository only."}+ try:+ x, y = int(request.get("x")), int(request.get("y"))+ data = str(request.get("image") or "")+ image = base64.b64decode(data.split(",", 1)[-1], validate=True)+ except (TypeError, ValueError):+ return 400, {"error": "Send a PNG, JPEG, GIF or WebP screenshot and the point."}+ if not image_type(image) or len(image) > MAX_IMAGE or x < 0 or y < 0:+ return 400, {"error": "Send a PNG, JPEG, GIF or WebP screenshot of at most 8 MB."}+ if not demo.live() or not demo.budget_left():+ return 503, {"error": "Live calls are paused (no budget left today).", "paused": True}+ allowed, retry = demo.limiter.allow(self.client())+ if not allowed:+ return 429, {"error": "Too many requests from your address; try again later.",+ "retry_after": retry}+ if not demo.running.acquire(timeout=30):+ return 503, {"error": "The demo is busy; try again in a minute.", "retry_after": 60}+ try:+ if path == "/api/ask":+ return 200, demo.ask(repo, question)+ return 200, demo.pixel(repo, image, x, y)+ except CallFailed as failure:+ if out_of_credits(str(failure)):+ demo.paused_until = time.time() + 600 # stored answers only for ten minutes+ if path == "/api/ask":+ stored = demo.stored(repo["id"], question)+ if stored:+ return 200, stored+ return 502, {"error": public_error(str(failure)), "paused": not demo.live()}+ except subprocess.TimeoutExpired:+ return 504, {"error": "The request took too long."}+ finally:+ demo.running.release()+ with demo.spend_lock:+ demo.spend_cache = (0.0, None)++ return Handler+++def main():+ config = load_config(os.environ.get("DEMO_CONFIG", os.path.join(HERE, "demo.json")))+ demo = Demo(config)+ server = ThreadingHTTPServer((config["listen"], int(config["port"])), make_handler(demo))+ server.daemon_threads = True+ print(f"graphicle demo on {config['listen']}:{config['port']}, live={demo.live()}, "+ f"{len(demo.repos)} repositories, {len(demo.curated)} curated answers", flush=True)+ server.serve_forever()+++if __name__ == "__main__":+ sys.exit(main())diff --git a/demo/static/app.js b/demo/static/app.jsnew file mode 100644index 0000000..d8115d8--- /dev/null+++ b/demo/static/app.js@@ -0,0 +1,261 @@+// Graphicle's hosted demo: the page. Text from the server is shown as text, never as HTML.+"use strict";++const $ = (id) => document.getElementById(id);+let config = { repos: [], curated: [] };+let image = null; // { dataUrl, width, height }++function el(tag, text, attrs) {+ const node = document.createElement(tag);+ if (text != null) node.textContent = text;+ for (const [k, v] of Object.entries(attrs || {})) node.setAttribute(k, v);+ return node;+}++function usd(v) {+ if (v == null) return "unknown";+ return v >= 0.01 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;+}++function count(n) {+ return n == null ? "?" : Number(n).toLocaleString("en-US");+}++function repo() {+ return config.repos.find((r) => r.id === $("repo").value) || config.repos[0];+}++async function post(path, body) {+ const response = await fetch(path, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ let data = {};+ try { data = await response.json(); } catch (_) { /* not JSON */ }+ if (!response.ok) throw Object.assign(new Error(data.error || `HTTP ${response.status}`), { data });+ return data;+}++// The answer as paragraphs; `code` spans; cited path:line shown as links when the server checked them.+function renderAnswer(text, citations) {+ const box = $("answer");+ box.replaceChildren();+ const links = new Map(citations.map((c) => [`${c.path}:${c.line}`, c.url]));+ for (const para of text.split(/\n{2,}/)) {+ const p = el("p");+ for (const part of para.split(/(`[^`]+`)/)) {+ if (part.startsWith("`") && part.endsWith("`") && part.length > 2) {+ const inner = part.slice(1, -1);+ const key = inner.replace(/-\d+$/, "");+ if (links.has(key)) {+ const a = el("a", inner, { href: links.get(key), target: "_blank", rel: "noopener" });+ p.append(a);+ } else {+ p.append(el("code", inner));+ }+ } else {+ p.append(document.createTextNode(part));+ }+ }+ box.append(p);+ }+}++function showAsk(data) {+ $("ask-result").hidden = false;+ renderAnswer(data.answer || "", data.citations || []);+ const list = $("citations");+ list.replaceChildren();+ for (const c of data.citations || []) {+ const li = el("li");+ const label = c.end_line && c.end_line !== c.line ? `${c.path}:${c.line}-${c.end_line}` : `${c.path}:${c.line}`;+ li.append(el("a", label, { href: c.url, target: "_blank", rel: "noopener" }));+ list.append(li);+ }+ if (!list.children.length) list.append(el("li", "The answer cites no line."));+ const pack = $("pack");+ pack.replaceChildren();+ for (const [k, v] of Object.entries(data.pack || {})) {+ pack.append(el("dt", k), el("dd", typeof v === "number" ? count(v) : String(v)));+ }+ const u = data.usage || {};+ let line = `${count(u.input_tokens)} input tokens`;+ if (data.cached_share != null) line += ` (${Math.round(data.cached_share * 100)}% cached)`;+ line += `, ${count(u.output_tokens)} output, ${usd(u.cost_usd)}, ${u.seconds != null ? u.seconds.toFixed(1) : "?"} s`;+ if (data.stored) line += `. Recorded ${data.recorded_at || ""}${data.mode === "mock" ? " with a mock model" : ""}: not a live call.`;+ $("ask-cost").textContent = line;+}++async function ask(question) {+ $("question").value = question;+ $("ask-button").disabled = true;+ $("ask-status").textContent = "Packing the repository and asking the model...";+ $("ask-status").classList.remove("error");+ try {+ const data = await post("/api/ask", { repo: repo().id, question });+ showAsk(data);+ $("ask-status").textContent = "";+ } catch (error) {+ $("ask-status").textContent = error.message;+ $("ask-status").classList.add("error");+ } finally {+ $("ask-button").disabled = false;+ refreshBudget();+ }+}++function showCurated() {+ const box = $("curated");+ box.replaceChildren();+ for (const c of config.curated.filter((c) => c.repo === repo().id)) {+ const b = el("button", c.question, { type: "button" });+ b.addEventListener("click", () => ask(c.question));+ box.append(b);+ }+}++function placeOverlay(node, x1, y1, x2, y2) {+ const shot = $("shot");+ const sx = shot.clientWidth / image.width;+ const sy = shot.clientHeight / image.height;+ node.style.left = `${x1 * sx}px`;+ node.style.top = `${y1 * sy}px`;+ if (x2 != null) {+ node.style.width = `${Math.max(2, (x2 - x1) * sx)}px`;+ node.style.height = `${Math.max(2, (y2 - y1) * sy)}px`;+ }+ node.hidden = false;+}++function showPixel(data) {+ $("pixel-result").hidden = false;+ const b = data.box;+ if (b) placeOverlay($("box"), b.x1, b.y1, b.x2, b.y2);+ const r = data.read || {};+ const strings = (r.strings || []).map((s) => `"${s}"`).join(", ") || "no text";+ $("read").textContent = `Read: ${r.element_type || "element"} ${strings}` ++ ((r.nearby_labels || []).length ? `, near ${(r.nearby_labels || []).map((s) => `"${s}"`).join(", ")}` : "");+ const list = $("candidates");+ list.replaceChildren();+ for (const c of data.candidates || []) {+ const li = el("li");+ li.append(el("a", `${c.path}:${c.line}`, { href: c.url, target: "_blank", rel: "noopener" }));+ const how = (c.matched || []).slice(0, 2).map((m) => `"${m.text}": ${m.how}`).join("; ");+ if (how) li.append(el("div", how, { class: "dim" }));+ const pre = el("pre");+ pre.textContent = (c.snippet || []).map((s) => `${String(s.line).padStart(5)} ${s.text}`).join("\n");+ li.append(pre);+ if (c.symbol) {+ const callers = (c.callers || []).map((p) => `${p.name} (${p.path}:${p.line})`).join(", ");+ li.append(el("div", `In ${c.symbol.name}${callers ? `; used by ${callers}` : ""}`, { class: "dim" }));+ }+ list.append(li);+ }+ if (!list.children.length) list.append(el("li", "No file of the repository holds these strings."));+ const calls = (data.calls || []).map((c) => {+ let t = `${c.model} (${c.step})`;+ if (c.input_tokens != null) t += ` ${count(c.input_tokens)} in, ${count(c.output_tokens)} out`;+ return `${t}, ${usd(c.cost_usd)}`;+ });+ $("pixel-cost").textContent = calls.length+ ? `${calls.join("; ")}. Total ${usd(data.cost_usd)} in ${data.seconds} s.`+ : `No model call. ${data.seconds} s.`;+}++async function pointAt(event) {+ if (!image) return;+ const shot = $("shot");+ const rect = shot.getBoundingClientRect();+ const x = Math.round(((event.clientX - rect.left) / rect.width) * image.width);+ const y = Math.round(((event.clientY - rect.top) / rect.height) * image.height);+ placeOverlay($("dot"), x, y);+ $("box").hidden = true;+ $("pixel-status").textContent = "Finding the element, reading it and searching the code...";+ $("pixel-status").classList.remove("error");+ try {+ const target = config.repos.find((r) => r.pixel) || repo();+ const data = await post("/api/pixel", { repo: target.id, image: image.dataUrl, x, y });+ showPixel(data);+ $("pixel-status").textContent = "";+ } catch (error) {+ $("pixel-status").textContent = error.message;+ $("pixel-status").classList.add("error");+ } finally {+ refreshBudget();+ }+}++function loadFile(file) {+ if (!file || file.size > 8 * 1024 * 1024) {+ $("pixel-status").textContent = "Choose a PNG, JPEG, WebP or GIF of at most 8 MB.";+ return;+ }+ const reader = new FileReader();+ reader.onload = () => {+ const probe = new Image();+ probe.onload = () => {+ image = { dataUrl: reader.result, width: probe.naturalWidth, height: probe.naturalHeight };+ $("shot").src = reader.result;+ $("stage").hidden = false;+ $("box").hidden = true;+ $("dot").hidden = true;+ $("pixel-status").textContent = "Click an element of the screenshot.";+ };+ probe.src = reader.result;+ };+ reader.readAsDataURL(file);+}++function select(tab) {+ for (const name of ["ask", "pixel"]) {+ $(`tab-${name}`).setAttribute("aria-selected", String(name === tab));+ $(name).hidden = name !== tab;+ }+ const pixelRepo = config.repos.find((r) => r.pixel);+ if (tab === "pixel" && pixelRepo) $("repo").value = pixelRepo.id;+ showRepo();+}++function showRepo() {+ const r = repo();+ if (!r) return;+ $("commit").textContent = `at ${r.commit.slice(0, 10)}`;+ showCurated();+}++async function refreshBudget() {+ try {+ const fresh = await (await fetch("/api/config")).json();+ $("budget").textContent = fresh.live+ ? `Today's budget: ${usd(fresh.spent_today_usd)} of ${usd(fresh.daily_cap_usd)} used.`+ : "Live calls are off: recorded answers only.";+ } catch (_) { /* keep the last line */ }+}++async function start() {+ config = await (await fetch("/api/config")).json();+ for (const r of config.repos) $("repo").append(el("option", r.id, { value: r.id }));+ $("repo").addEventListener("change", showRepo);+ $("tab-ask").addEventListener("click", () => select("ask"));+ $("tab-pixel").addEventListener("click", () => select("pixel"));+ $("ask-form").addEventListener("submit", (e) => {+ e.preventDefault();+ const q = $("question").value.trim();+ if (q.length >= 3) ask(q);+ });+ $("file").addEventListener("change", (e) => loadFile(e.target.files[0]));+ const drop = $("drop");+ drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });+ drop.addEventListener("dragleave", () => drop.classList.remove("over"));+ drop.addEventListener("drop", (e) => {+ e.preventDefault();+ drop.classList.remove("over");+ loadFile(e.dataTransfer.files[0]);+ });+ $("shot").addEventListener("click", pointAt);+ showRepo();+ refreshBudget();+}++start();diff --git a/demo/static/index.html b/demo/static/index.htmlnew file mode 100644index 0000000..6fa15bc--- /dev/null+++ b/demo/static/index.html@@ -0,0 +1,70 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Graphicle demo</title>+<link rel="stylesheet" href="/style.css">+</head>+<body>+<header>+ <h1>Graphicle <span class="dim">on Muse Spark</span></h1>+ <p class="lede">Ask a repository far larger than a 1M-token window, or point at a pixel of a screenshot and get the code that draws it.</p>+</header>+<main>+ <div class="bar">+ <label>Repository+ <select id="repo"></select>+ </label>+ <span id="commit" class="dim"></span>+ <nav role="tablist">+ <button role="tab" id="tab-ask" aria-selected="true">Ask</button>+ <button role="tab" id="tab-pixel" aria-selected="false">Point at a pixel</button>+ </nav>+ </div>++ <section id="ask" class="panel">+ <form id="ask-form">+ <textarea id="question" rows="3" maxlength="600" placeholder="How does the scheduler pick a node for a pod?"></textarea>+ <div class="row">+ <button type="submit" id="ask-button">Ask</button>+ <span id="ask-status" class="dim" aria-live="polite"></span>+ </div>+ </form>+ <div id="curated" class="chips" aria-label="Questions with recorded answers"></div>+ <div id="ask-result" class="result" hidden>+ <div id="answer" class="answer"></div>+ <h3>Sources</h3>+ <ul id="citations" class="links"></ul>+ <h3>The pack</h3>+ <dl id="pack" class="facts"></dl>+ <h3>Cost</h3>+ <p id="ask-cost" class="facts-line"></p>+ </div>+ </section>++ <section id="pixel" class="panel" hidden>+ <p class="dim">Pixel to code runs on the vscode repository: drop a screenshot of VS Code, then click an element.</p>+ <label id="drop" class="drop" tabindex="0">+ <input id="file" type="file" accept="image/png,image/jpeg,image/webp,image/gif">+ <span>Drop a screenshot here, or choose a file (PNG, JPEG, WebP or GIF, at most 8 MB)</span>+ </label>+ <div id="stage" class="stage" hidden>+ <img id="shot" alt="Your screenshot: click an element">+ <div id="box" class="box" hidden></div>+ <div id="dot" class="dot" hidden></div>+ </div>+ <p id="pixel-status" class="dim" aria-live="polite"></p>+ <div id="pixel-result" class="result" hidden>+ <p id="read" class="read"></p>+ <ol id="candidates" class="candidates"></ol>+ <p id="pixel-cost" class="facts-line"></p>+ </div>+ </section>+</main>+<footer>+ <p>A read-only demo. Questions and screenshots are not stored: the spend log keeps the time, model, tokens and cost of each call. <span id="budget"></span></p>+</footer>+<script src="/app.js"></script>+</body>+</html>diff --git a/demo/static/style.css b/demo/static/style.cssnew file mode 100644index 0000000..925b5a4--- /dev/null+++ b/demo/static/style.css@@ -0,0 +1,55 @@+:root {+ --bg: #fbfaf8; --fg: #1d1c1a; --dim: #6b6862; --line: #e3e0da; --card: #ffffff;+ --accent: #2f5fd0; --accent-fg: #ffffff; --mark: rgba(47, 95, 208, 0.18); --code: #f2f0ec; --bad: #a3362a;+}+@media (prefers-color-scheme: dark) {+ :root:not([data-theme="light"]) {+ --bg: #161615; --fg: #ecebe8; --dim: #a19e98; --line: #33322f; --card: #1e1e1c;+ --accent: #7ea2f3; --accent-fg: #10131a; --mark: rgba(126, 162, 243, 0.22); --code: #262624; --bad: #f08a7c;+ }+}+* { box-sizing: border-box; }+body { margin: 0; background: var(--bg); color: var(--fg); font: 16px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif; }+header, main, footer { max-width: 980px; margin: 0 auto; padding: 0 16px; }+header { padding-top: 32px; }+h1 { font-size: 28px; margin: 0 0 6px; letter-spacing: -0.01em; }+h3 { font-size: 15px; margin: 22px 0 8px; text-transform: none; color: var(--dim); font-weight: 600; }+.dim { color: var(--dim); }+.lede { margin: 0 0 20px; color: var(--dim); max-width: 60ch; }+.bar { display: flex; flex-wrap: wrap; gap: 12px 16px; align-items: center; padding: 12px 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }+.bar label { display: flex; gap: 8px; align-items: center; font-weight: 600; }+select, textarea, button { font: inherit; color: inherit; }+select { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: 4px 8px; }+nav { margin-left: auto; display: flex; gap: 4px; }+nav button { background: none; border: 1px solid transparent; border-radius: 6px; padding: 6px 12px; cursor: pointer; color: var(--dim); }+nav button[aria-selected="true"] { border-color: var(--line); background: var(--card); color: var(--fg); }+.panel { padding: 20px 0 8px; }+textarea { width: 100%; background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; resize: vertical; }+.row { display: flex; gap: 12px; align-items: center; margin-top: 10px; }+button[type="submit"] { background: var(--accent); color: var(--accent-fg); border: 0; border-radius: 8px; padding: 8px 18px; font-weight: 600; cursor: pointer; }+button:disabled { opacity: 0.5; cursor: progress; }+.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 0; }+.chips button { background: var(--card); border: 1px solid var(--line); border-radius: 999px; padding: 4px 12px; font-size: 14px; cursor: pointer; text-align: left; }+.result { margin-top: 20px; padding: 18px 20px; background: var(--card); border: 1px solid var(--line); border-radius: 10px; }+.answer p { margin: 0 0 10px; }+.answer code, .candidates code { background: var(--code); border-radius: 4px; padding: 1px 4px; font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }+.links { margin: 0; padding-left: 18px; font: 14px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }+a { color: var(--accent); }+.facts { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0; font-size: 14px; }+.facts dt { color: var(--dim); }+.facts dd { margin: 0; font-variant-numeric: tabular-nums; }+.facts-line { font-size: 14px; font-variant-numeric: tabular-nums; margin: 0; }+.drop { display: block; border: 1.5px dashed var(--line); border-radius: 10px; padding: 28px 16px; text-align: center; cursor: pointer; color: var(--dim); }+.drop.over { border-color: var(--accent); color: var(--fg); }+.drop input { display: block; margin: 0 auto 8px; }+.stage { position: relative; margin-top: 16px; display: inline-block; max-width: 100%; }+.stage img { display: block; max-width: 100%; height: auto; cursor: crosshair; border: 1px solid var(--line); border-radius: 6px; }+.box { position: absolute; border: 2px solid var(--accent); background: var(--mark); border-radius: 3px; pointer-events: none; }+.dot { position: absolute; width: 10px; height: 10px; margin: -5px 0 0 -5px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 2px var(--card); pointer-events: none; }+.read { margin: 0 0 12px; }+.candidates { margin: 0; padding-left: 22px; }+.candidates li { margin-bottom: 14px; }+.candidates pre { margin: 6px 0 0; padding: 8px 10px; background: var(--code); border-radius: 6px; overflow-x: auto; font: 12.5px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }+.error { color: var(--bad); }+footer { padding: 28px 16px 40px; color: var(--dim); font-size: 14px; }+@media (max-width: 640px) { nav { margin-left: 0; } h1 { font-size: 24px; } }diff --git a/demo/test_demo.py b/demo/test_demo.pynew file mode 100644index 0000000..5fb27c4--- /dev/null+++ b/demo/test_demo.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""The demo server's tests: python3 -m unittest test_demo (from this folder).++The unit tests need nothing else. The end-to-end test runs when GRAPHICLE_BIN names a graphicle binary: it+syncs a fixture repository, starts mock_meta.py (a stand-in for the Meta Model API, no key and no model) and+the demo server, and checks /api/ask, /api/pixel, the rate limit, the daily cap with the curated answers, and+that the request log holds no question.+"""+import base64+import contextlib+import io+import json+import os+import socket+import subprocess+import sys+import tempfile+import threading+import time+import unittest+import urllib.error+import urllib.request++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, HERE)+import server # noqa: E402+++def png(width, height):+ return b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR" + width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes(9)+++class Units(unittest.TestCase):+ def test_the_limit_counts_per_minute_and_per_day(self):+ limiter = server.Limiter(per_minute=2, per_day=3)+ self.assertTrue(limiter.allow("a", now=0)[0])+ self.assertTrue(limiter.allow("a", now=1)[0])+ self.assertEqual(limiter.allow("a", now=2), (False, 60))+ self.assertTrue(limiter.allow("b", now=2)[0])+ self.assertTrue(limiter.allow("a", now=70)[0])+ allowed, retry = limiter.allow("a", now=200)+ self.assertFalse(allowed)+ self.assertGreater(retry, 86000)+ self.assertTrue(limiter.allow("a", now=86401)[0])++ def test_links_point_at_the_commit(self):+ repo = {"github": "microsoft/vscode", "commit": "3e8601c5"}+ self.assertEqual(server.github_link(repo, "src/a.ts", 4, 9),+ "https://github.com/microsoft/vscode/blob/3e8601c5/src/a.ts#L4-L9")+ self.assertEqual(server.github_link(repo, "src/a.ts", 4, 4),+ "https://github.com/microsoft/vscode/blob/3e8601c5/src/a.ts#L4")++ def test_images_are_checked_by_their_bytes(self):+ self.assertEqual(server.image_type(png(2, 2)), ".png")+ self.assertEqual(server.image_type(b"\xff\xd8\xff\xe0"), ".jpg")+ self.assertIsNone(server.image_type(b"<svg"))++ def test_a_refusal_for_credits_is_recognized(self):+ self.assertTrue(server.out_of_credits("Provider refused (HTTP 402): insufficient credits"))+ self.assertFalse(server.out_of_credits("Provider refused (HTTP 400): input exceeds the context window"))++ def test_errors_never_pass_the_binary_text_through(self):+ self.assertEqual(server.public_error("Refused before sending: ... max_cost_per_day of $10.00"),+ "The demo's budget for today is used up.")+ self.assertEqual(server.public_error("Cannot read /var/lib/secret/path: denied"),+ "The request failed. Please try again later.")+++def free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def call(port, path, body=None):+ request = urllib.request.Request(f"http://127.0.0.1:{port}{path}",+ data=json.dumps(body).encode() if body is not None else None,+ headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(request, timeout=300) as response:+ return response.status, json.loads(response.read())+ except urllib.error.HTTPError as error:+ return error.code, json.loads(error.read())++[email protected](os.environ.get("GRAPHICLE_BIN"), "GRAPHICLE_BIN names no graphicle binary")+class EndToEnd(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tmp = tempfile.TemporaryDirectory()+ root = cls.tmp.name+ binary = os.environ["GRAPHICLE_BIN"]+ project = os.path.join(root, "src", "app")+ os.makedirs(os.path.join(project, "src"))+ with open(os.path.join(project, "src", "welcome.ts"), "w") as f:+ f.write("import { localize } from './nls';\n\nexport const label = localize('openFolder', "+ "\"Open &&Folder...\");\nexport function render() {\n\treturn button(label);\n}\n")+ with open(os.path.join(project, "README.md"), "w") as f:+ f.write("# App\n\nThe welcome page has an Open Folder... button.\n")+ for args in (["init", "-q"], ["add", "."], ["-c", "user.name=t", "-c", "[email protected]",+ "commit", "-q", "-m", "fixture"]):+ subprocess.run(["git", "-C", project] + args, check=True)+ cls.mock_port = free_port()+ cls.mock = subprocess.Popen([sys.executable, os.path.join(HERE, "mock_meta.py"), "127.0.0.1",+ str(cls.mock_port)])+ base = f"http://127.0.0.1:{cls.mock_port}/v1"+ models = os.path.join(root, "models.json")+ with open(models, "w") as f:+ json.dump({"default_model": "spark", "models": {+ "spark": {"protocol": "responses", "base_url": base, "model": "muse-spark-1.3",+ "key_env": "MODEL_API_KEY", "input_limit": 60000, "output_limit": 4000,+ "price": {"input": 1.25, "output": 4.25, "cached_input": 0.15}},+ "sam": {"protocol": "responses", "base_url": base, "model": "sam-3.1", "key_env": "MODEL_API_KEY",+ "price": {"input": 0, "output": 0, "per_image": 0.0025}}}}, f)+ data = os.path.join(root, "data")+ env = dict(os.environ, HOME=os.path.join(root, "home"))+ subprocess.run([binary, "--data-dir", data, "--config", models, "sync", project, "--json"], check=True,+ env=env, capture_output=True)+ curated = os.path.join(root, "curated.json")+ with open(curated, "w") as f:+ json.dump([{"repo": "app", "question": "Where is the welcome label?", "answer": "A stored answer.",+ "citations": [], "usage": {"cost_usd": 0.01}, "mode": "mock",+ "recorded_at": "2026-10-27"}], f)+ cls.config = {"listen": "127.0.0.1", "port": free_port(), "binary": binary, "models": models,+ "daily_cap_usd": 5, "per_minute": 3, "per_day": 10, "curated": curated,+ "state_dir": os.path.join(root, "state"), "pass_env": ["LD_PRELOAD", "LOOPSHIM_IP"],+ "repos": [{"id": "app", "github": "example/app", "commit": "abc123", "data_dir": data,+ "project": project, "pixel": True}]}+ os.environ["MODEL_API_KEY"] = "mock-key"+ cls.log = io.StringIO()+ cls.demo = server.Demo(server.load_config_dict(cls.config))+ cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", cls.config["port"]), server.make_handler(cls.demo))+ cls.thread = threading.Thread(target=cls.serve, daemon=True)+ cls.thread.start()+ for _ in range(50):+ try:+ socket.create_connection(("127.0.0.1", cls.mock_port), timeout=1).close()+ break+ except OSError:+ time.sleep(0.1)+ else:+ raise RuntimeError("the mock server did not start")++ @classmethod+ def serve(cls):+ with contextlib.redirect_stdout(cls.log):+ cls.httpd.serve_forever()++ @classmethod+ def tearDownClass(cls):+ cls.httpd.shutdown()+ cls.mock.terminate()+ cls.mock.wait()+ cls.tmp.cleanup()++ def test_ask_pixel_limits_and_the_cap(self):+ port = self.config["port"]+ question = "Which function renders the welcome label xyzzy?"+ status, body = call(port, "/api/ask", {"repo": "app", "question": question})+ self.assertEqual(status, 200, (body, self.demo.last_failure))+ self.assertIn("mock model", body["answer"])+ self.assertTrue(body["citations"], body)+ self.assertTrue(body["citations"][0]["url"].startswith("https://github.com/example/app/blob/abc123/"))+ self.assertGreater(body["usage"]["input_tokens"], 0)+ self.assertEqual(body["pack"]["layout"], "cache")+ self.assertGreater(body["pack"]["files in the pack"], 0)++ shot = base64.b64encode(png(400, 200)).decode()+ status, body = call(port, "/api/pixel", {"repo": "app", "image": f"data:image/png;base64,{shot}",+ "x": 100, "y": 50})+ self.assertEqual(status, 200, (body, self.demo.last_failure))+ self.assertEqual(body["box"]["x1"], 20)+ self.assertEqual(body["candidates"][0]["path"], "src/welcome.ts")+ self.assertEqual(body["candidates"][0]["url"], "https://github.com/example/app/blob/abc123/src/welcome.ts#L3")+ self.assertNotIn("screenshot", body)+ self.assertEqual(os.listdir(self.demo.scratch), [])++ # Three a minute: the next is refused.+ status, body = call(port, "/api/ask", {"repo": "app", "question": question})+ self.assertEqual(status, 200)+ status, body = call(port, "/api/ask", {"repo": "app", "question": question})+ self.assertEqual(status, 429)++ # At the cap: the curated question's stored answer, and a pause for the rest.+ self.demo.config["daily_cap_usd"] = 0+ self.demo.limiter = server.Limiter(10, 10)+ status, body = call(port, "/api/ask", {"repo": "app", "question": "where is the welcome label?"})+ self.assertEqual((status, body["answer"], body["stored"]), (200, "A stored answer.", True))+ status, body = call(port, "/api/ask", {"repo": "app", "question": question})+ self.assertEqual((status, body.get("paused")), (503, True))++ # record.py stores the curated answers with their cost (here from the mock, marked so).+ config_path = os.path.join(self.tmp.name, "demo.json")+ questions = os.path.join(self.tmp.name, "questions.json")+ stored = os.path.join(self.tmp.name, "recorded.json")+ with open(config_path, "w") as f:+ json.dump(dict(self.config, daily_cap_usd=5), f)+ with open(questions, "w") as f:+ json.dump([{"repo": "app", "question": "Where is the welcome label drawn?"},+ {"repo": "nope", "question": "Skipped?"}], f)+ done = subprocess.run([sys.executable, os.path.join(HERE, "record.py"), config_path, questions, stored,+ "--mock"], capture_output=True, text=True, cwd=HERE)+ self.assertEqual(done.returncode, 0, done.stderr)+ recorded = json.load(open(stored))+ self.assertEqual([(r["repo"], r["mode"]) for r in recorded], [("app", "mock")])+ self.assertGreater(recorded[0]["usage"]["cost_usd"], 0)++ # The spend log has the calls and their cost; the request log has no question.+ status, config = call(port, "/api/config")+ self.assertGreater(config["spent_today_usd"], 0)+ self.assertNotIn("xyzzy", self.log.getvalue())+ self.assertIn("POST /api/ask 200", self.log.getvalue())+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/agents.md b/docs/agents.mdindex 5e9d4f9..77155ca 100644--- a/docs/agents.md+++ b/docs/agents.md@@ -22,8 +22,8 @@ graphicle disconnect --all # the same for every projectgraphicle uninstall # disconnect everywhere, then show how to remove the program```-The agent names are `claude-code`, `codex`, `cursor`, `vscode` and `claude`-(Claude Desktop). `setup --clients` also takes the numbers setup shows on a+The agent names are `claude-code`, `codex`, `cursor`, `vscode`, `claude`+(Claude Desktop) and `muse` (Muse Code). `setup --clients` also takes the numbers setup shows on aterminal. Restart or reload an agent after you connect or disconnectit. `graphicle status` lists the connected agents and whether each entry stillworks.@@ -140,7 +140,7 @@ for example `graphicle-my-app`. When another project already has that namefor example `graphicle-api-1a2b3c4d`, and each keeps its own. Agents with a settings file per folder (ClaudeCode and VS Code) get one entry named `graphicle` that finds the project fromthe folder they start in. Agents with one settings file for your user account-(Codex, Cursor and Claude Desktop) get one entry per project.+(Codex, Cursor, Claude Desktop and Muse Code) get one entry per project.## Claude Code@@ -213,6 +213,98 @@ the folder they start in. Agents with one settings file for your user accountown entry.- Undo: `graphicle disconnect claude`, or delete the entry by hand.+## Muse Code++| What | Where | Written by |+|---|---|---|+| MCP server `graphicle-<project>` | `~/.config/muse/settings.json`, in its `mcp_servers` object | setup, `connect muse` |+| Graphicle's plugin (preview): MCP server, skill `graphicle`, six hooks | Graphicle's data folder, `muse-code-plugin/`, installed with `muse plugins install` | `connect muse --hooks` |++- Setup finds Muse Code by its settings folder, `~/.config/muse`, or the+ `muse` program, and writes the settings entry: a stdio server+ (`"transport": "stdio"`) with `"mode": "optional"`, so a Muse Code session+ still starts, with a warning, when Graphicle is not installed. Graphicle+ changes only its own entry; the file's other settings stay. Muse Code+ requires `"schema_version": 1` in the file, and Graphicle adds it when the+ file has none.+- Graphicle's plugin is a preview, tested against a stand-in `muse` program+ and not yet with Meta's live API, so setup does not install it.+ `graphicle connect muse --hooks --allow-learning` installs it; approve it+ once with `muse plugins approve graphicle`. Its server replaces the+ project's settings entry. Its hooks are built to add the project's map and+ reviewed memory at session start and cited excerpts after a code question,+ and capture each session as a source (below). They never block Muse Code.+- Muse Code reads a project's `AGENTS.md` (else `CLAUDE.md`) once you trust+ the workspace, so the Graphicle section setup writes there for Codex or+ Claude Code reaches Muse Code too.+- Undo: `graphicle disconnect muse` removes the settings entry and the+ plugin (`muse plugins remove graphicle`).+- [Graphicle with Muse Code](muse-code.md) has the details: what each hook+ adds, how the context keeps the prompt cache, and session memory.++## Claude Code and Codex on Meta's models++Meta documents running Claude Code and Codex on its models+(https://dev.meta.ai/docs/coding-agents.md). Graphicle connects to them the+same way whatever model they use: `graphicle setup` adds its MCP server and+capture hooks as above. Pointing them at Meta changes where they send their+requests and who bills them, so Graphicle does not write that part for you:+it would change every session of the agent, not only Graphicle's.++**Claude Code**, through the Messages API, for one shell:++```sh+export ANTHROPIC_BASE_URL=https://api.meta.ai+export ANTHROPIC_AUTH_TOKEN="$MODEL_API_KEY"+export ANTHROPIC_MODEL=muse-wonder-1.0+export ANTHROPIC_DEFAULT_OPUS_MODEL=muse-wonder-1.0+export ANTHROPIC_DEFAULT_SONNET_MODEL=muse-spark-1.3+export ANTHROPIC_DEFAULT_HAIKU_MODEL=muse-spark-1.3+export CLAUDE_CODE_SUBAGENT_MODEL=muse-spark-1.3+export ENABLE_TOOL_SEARCH=true+claude+```++- The base URL has no `/v1`: Claude Code adds `/v1/messages`.+- `ANTHROPIC_AUTH_TOKEN`, not `ANTHROPIC_API_KEY`, which sends another+ header.+- Name every model: a background task, Plan Mode or a sub-agent otherwise+ asks for a model the Meta Model API does not serve.+- `ENABLE_TOOL_SEARCH=true` keeps tool search, which Claude Code turns off+ for other hosts, so Graphicle's tools load when the agent needs them.++**Codex**, through the Responses API: add a provider and a profile to+`~/.codex/config.toml`, and your default provider stays as it is.++```toml+[model_providers.meta]+name = "Meta Model API"+base_url = "https://api.meta.ai/v1"+env_key = "MODEL_API_KEY"+wire_api = "responses"++[profiles.meta]+model = "muse-wonder-1.0"+model_provider = "meta"+model_reasoning_effort = "high"+model_reasoning_summary = "auto"+```++```sh+export MODEL_API_KEY=...+codex --profile meta -c model_context_window=1048576 -c model_auto_compact_token_limit=900000+```++- Codex sends `MODEL_API_KEY` as a bearer token; the key never goes in the+ file.+- Meta's page sets these keys at the top level instead, which makes Meta+ Codex's default, and asks you to `/logout` from OpenAI first. A+ `CODEX_HOME` of its own keeps such a setup apart from your usual one.++**Billing.** Both bill the Meta Model API key by usage. Their cost displays+show $0 for a provider without prices; the Model API's usage page has the+real figures.+## Other MCP clientsAny client that starts an MCP server over stdio, such as Windsurf, can use@@ -266,9 +358,11 @@ the new code.## Session capture-Session capture saves your Claude Code and Codex conversations in the project,-so that you and your agents can search what was said and decided before.-Setup turns it on; `--no-capture` leaves it off.+Session capture saves your Claude Code, Codex and Muse Code conversations in+the project, so that you and your agents can search what was said and+decided before. Setup turns it on; `--no-capture` leaves it off. Muse Code's+capture comes with Graphicle's plugin, a preview you add with `graphicle+connect muse --hooks` ([Muse Code](muse-code.md#session-memory)).- After each answer, a background process stores the session's completedturns. The hooks never make the agent wait.diff --git a/docs/assets/whole-repo-cost-dark.png b/docs/assets/whole-repo-cost-dark.pngnew file mode 100644index 0000000..449fd0bBinary files /dev/null and b/docs/assets/whole-repo-cost-dark.png differdiff --git a/docs/assets/whole-repo-cost-dark.svg b/docs/assets/whole-repo-cost-dark.svgnew file mode 100644index 0000000..abd16d5--- /dev/null+++ b/docs/assets/whole-repo-cost-dark.svg@@ -0,0 +1,5354 @@+<?xml version="1.0" encoding="utf-8" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">+<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="1600" height="900" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" version="1.1">+ <title>Input cost per follow-up question with a 1M-token context, without and with the prompt cache, computed at list prices, not billed.</title>+ <desc>Pack, standard layout: Muse Spark 1.3 $1.27 without the cache, $1.27 with it, Muse Wonder $4.06 without the cache, $4.06 with it; Pack, cache layout, 50%: Muse Spark 1.3 $1.17 without the cache, $0.610 with it, Muse Wonder $3.74 without the cache, $1.81 with it; Pack, cache layout, 70%: Muse Spark 1.3 $1.21 without the cache, $0.433 with it, Muse Wonder $3.88 without the cache, $1.19 with it; Pack, cache layout, 90%: Muse Spark 1.3 $1.26 without the cache, $0.252 with it, Muse Wonder $4.02 without the cache, $0.551 with it; Pack, cache layout, 95%: Muse Spark 1.3 $1.26 without the cache, $0.204 with it, Muse Wonder $4.04 without the cache, $0.383 with it; Pack, stable layout: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.06 without the cache, $0.206 with it; Truncation: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.07 without the cache, $0.206 with it.</desc>+ <metadata>+ <rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+ <cc:Work>+ <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>+ <dc:format>image/svg+xml</dc:format>+ <dc:creator>+ <cc:Agent>+ <dc:title>Matplotlib v3.11.2, https://matplotlib.org/</dc:title>+ </cc:Agent>+ </dc:creator>+ </cc:Work>+ </rdf:RDF>+ </metadata>+ <defs>+ <style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>+ </defs>+ <g id="figure_1">+ <g id="patch_1">+ <path d="M 0 900+L 1600 900+L 1600 0+L 0 0+z+" style="fill: #0d1117"/>+ </g>+ <g id="axes_1">+ <g id="patch_2">+ <path d="M 48 789+L 1552 789+L 1552 790+L 48 790+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a2f3b"/>+ </g>+ <g id="patch_3">+ <path d="M 48 197+L 66 197+L 66 215+L 48 215+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_4">+ <path d="M 290.59375 197+L 308.59375 197+L 308.59375 215+L 290.59375 215+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_5">+ <path d="M 308.46875 316+L 466.136904 316+Q 470.136904 316 470.136904 320+L 470.136904 335.928571+Q 470.136904 339.928571 466.136904 339.928571+L 308.46875 339.928571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_6">+ <path d="M 308.46875 341.928571+L 466.136904 341.928571+Q 470.136904 341.928571 470.136904 345.928571+L 470.136904 361.857143+Q 470.136904 365.857143 466.136904 365.857143+L 308.46875 365.857143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_7">+ <path d="M 308.46875 381.857143+L 453.461289 381.857143+Q 457.461289 381.857143 457.461289 385.857143+L 457.461289 401.785714+Q 457.461289 405.785714 453.461289 405.785714+L 308.46875 405.785714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_8">+ <path d="M 308.46875 407.785714+L 382.332132 407.785714+Q 386.332132 407.785714 386.332132 411.785714+L 386.332132 427.714286+Q 386.332132 431.714286 382.332132 431.714286+L 308.46875 431.714286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_9">+ <path d="M 308.46875 447.714286+L 459.349926 447.714286+Q 463.349926 447.714286 463.349926 451.714286+L 463.349926 467.642857+Q 463.349926 471.642857 459.349926 471.642857+L 308.46875 471.642857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_10">+ <path d="M 308.46875 473.642857+L 359.766411 473.642857+Q 363.766411 473.642857 363.766411 477.642857+L 363.766411 493.571429+Q 363.766411 497.571429 359.766411 497.571429+L 308.46875 497.571429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_11">+ <path d="M 308.46875 513.571429+L 464.639568 513.571429+Q 468.639568 513.571429 468.639568 517.571429+L 468.639568 533.5+Q 468.639568 537.5 464.639568 537.5+L 308.46875 537.5+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_12">+ <path d="M 308.46875 539.5+L 336.60338 539.5+Q 340.60338 539.5 340.60338 543.5+L 340.60338 559.428571+Q 340.60338 563.428571 336.60338 563.428571+L 308.46875 563.428571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_13">+ <path d="M 308.46875 579.428571+L 465.65276 579.428571+Q 469.65276 579.428571 469.65276 583.428571+L 469.65276 599.357143+Q 469.65276 603.357143 465.65276 603.357143+L 308.46875 603.357143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_14">+ <path d="M 308.46875 605.357143+L 330.50214 605.357143+Q 334.50214 605.357143 334.50214 609.357143+L 334.50214 625.285714+Q 334.50214 629.285714 330.50214 629.285714+L 308.46875 629.285714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_15">+ <path d="M 308.46875 645.285714+L 466.258087 645.285714+Q 470.258087 645.285714 470.258087 649.285714+L 470.258087 665.214286+Q 470.258087 669.214286 466.258087 669.214286+L 308.46875 669.214286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_16">+ <path d="M 308.46875 671.214286+L 323.993036 671.214286+Q 327.993036 671.214286 327.993036 675.214286+L 327.993036 691.142857+Q 327.993036 695.142857 323.993036 695.142857+L 308.46875 695.142857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_17">+ <path d="M 308.46875 711.142857+L 466.583008 711.142857+Q 470.583008 711.142857 470.583008 715.142857+L 470.583008 731.071429+Q 470.583008 735.071429 466.583008 735.071429+L 308.46875 735.071429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_18">+ <path d="M 308.46875 737.071429+L 324.032027 737.071429+Q 328.032027 737.071429 328.032027 741.071429+L 328.032027 757+Q 328.032027 761 324.032027 761+L 308.46875 761+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_19">+ <path d="M 950.234375 316+L 1463.572467 316+Q 1467.572467 316 1467.572467 320+L 1467.572467 335.928571+Q 1467.572467 339.928571 1463.572467 339.928571+L 950.234375 339.928571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_20">+ <path d="M 950.234375 341.928571+L 1463.572467 341.928571+Q 1467.572467 341.928571 1467.572467 345.928571+L 1467.572467 361.857143+Q 1467.572467 365.857143 1463.572467 365.857143+L 950.234375 365.857143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_21">+ <path d="M 950.234375 381.857143+L 1423.010501 381.857143+Q 1427.010501 381.857143 1427.010501 385.857143+L 1427.010501 401.785714+Q 1427.010501 405.785714 1423.010501 405.785714+L 950.234375 405.785714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_22">+ <path d="M 950.234375 407.785714+L 1177.291593 407.785714+Q 1181.291593 407.785714 1181.291593 411.785714+L 1181.291593 427.714286+Q 1181.291593 431.714286 1177.291593 431.714286+L 950.234375 431.714286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_23">+ <path d="M 950.234375 447.714286+L 1441.854138 447.714286+Q 1445.854138 447.714286 1445.854138 451.714286+L 1445.854138 467.642857+Q 1445.854138 471.642857 1441.854138 471.642857+L 950.234375 471.642857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_24">+ <path d="M 950.234375 473.642857+L 1097.838358 473.642857+Q 1101.838358 473.642857 1101.838358 477.642857+L 1101.838358 493.571429+Q 1101.838358 497.571429 1097.838358 497.571429+L 950.234375 497.571429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_25">+ <path d="M 950.234375 513.571429+L 1458.780994 513.571429+Q 1462.780994 513.571429 1462.780994 517.571429+L 1462.780994 533.5+Q 1462.780994 537.5 1458.780994 537.5+L 950.234375 537.5+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_26">+ <path d="M 950.234375 539.5+L 1016.474161 539.5+Q 1020.474161 539.5 1020.474161 543.5+L 1020.474161 559.428571+Q 1020.474161 563.428571 1016.474161 563.428571+L 950.234375 563.428571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_27">+ <path d="M 950.234375 579.428571+L 1462.023208 579.428571+Q 1466.023208 579.428571 1466.023208 583.428571+L 1466.023208 599.357143+Q 1466.023208 603.357143 1462.023208 603.357143+L 950.234375 603.357143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_28">+ <path d="M 950.234375 605.357143+L 995.139249 605.357143+Q 999.139249 605.357143 999.139249 609.357143+L 999.139249 625.285714+Q 999.139249 629.285714 995.139249 629.285714+L 950.234375 629.285714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_29">+ <path d="M 950.234375 645.285714+L 1463.960254 645.285714+Q 1467.960254 645.285714 1467.960254 649.285714+L 1467.960254 665.214286+Q 1467.960254 669.214286 1463.960254 669.214286+L 950.234375 669.214286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_30">+ <path d="M 950.234375 671.214286+L 972.499168 671.214286+Q 976.499168 671.214286 976.499168 675.214286+L 976.499168 691.142857+Q 976.499168 695.142857 972.499168 695.142857+L 950.234375 695.142857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_31">+ <path d="M 950.234375 711.142857+L 1465 711.142857+Q 1469 711.142857 1469 715.142857+L 1469 731.071429+Q 1469 735.071429 1465 735.071429+L 950.234375 735.071429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #3987e5"/>+ </g>+ <g id="patch_32">+ <path d="M 950.234375 737.071429+L 972.551156 737.071429+Q 976.551156 737.071429 976.551156 741.071429+L 976.551156 757+Q 976.551156 761 972.551156 761+L 950.234375 761+z+" clip-path="url(#p1c9bf33d97)" style="fill: #d95926"/>+ </g>+ <g id="patch_33">+ <path d="M 307.71875 308+L 309.21875 308+L 309.21875 769+L 307.71875 769+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a2f3b"/>+ </g>+ <g id="patch_34">+ <path d="M 949.484375 308+L 950.984375 308+L 950.984375 769+L 949.484375 769+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a2f3b"/>+ </g>+ <g id="text_1">+ <!-- Graphicle -->+ <g style="fill: #f4f6fa" transform="translate(48 60) scale(0.28 -0.28)">+ <defs>+ <path id="Inter-Bold-8d" d="M 2484 -63+Q 1831 -63 1337 226+Q 844 516 569 1050+Q 294 1584 294 2322+Q 294 3075 580 3612+Q 866 4150 1358 4434+Q 1850 4719 2463 4719+Q 2988 4719 3413 4519+Q 3838 4319 4109 3967+Q 4381 3616 4447 3156+L 3478 3156+Q 3378 3491 3122 3681+Q 2866 3872 2478 3872+Q 1941 3872 1602 3472+Q 1263 3072 1263 2331+Q 1263 1591 1597 1187+Q 1931 784 2491 784+Q 2988 784 3272 1046+Q 3556 1309 3569 1756+L 2556 1756+L 2556 2481+L 4494 2481+L 4494 1900+Q 4494 1288 4234 848+Q 3975 409 3522 173+Q 3069 -63 2484 -63+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-354" d="M 400 0+L 400 3494+L 1306 3494+L 1306 2884+L 1344 2884+Q 1441 3206 1667 3373+Q 1894 3541 2188 3541+Q 2347 3541 2491 3509+L 2491 2672+Q 2428 2691 2308 2705+Q 2188 2719 2084 2719+Q 1759 2719 1548 2516+Q 1338 2313 1338 1988+L 1338 0+L 400 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-1fb" d="M 1375 -69+Q 875 -69 544 195+Q 213 459 213 978+Q 213 1369 400 1591+Q 588 1813 888 1916+Q 1188 2019 1531 2050+Q 1981 2094 2179 2142+Q 2378 2191 2378 2363+L 2378 2378+Q 2378 2600 2236 2722+Q 2094 2844 1831 2844+Q 1559 2844 1393 2726+Q 1228 2609 1172 2441+L 313 2584+Q 447 3038 848 3288+Q 1250 3538 1834 3538+Q 2209 3538 2548 3419+Q 2888 3300 3102 3039+Q 3316 2778 3316 2353+L 3316 0+L 2428 0+L 2428 484+L 2397 484+Q 2269 241 2016 86+Q 1763 -69 1375 -69+z+M 1641 591+Q 1969 591 2176 781+Q 2384 972 2384 1250+L 2384 1628+Q 2328 1588 2201 1558+Q 2075 1528 1934 1504+Q 1794 1481 1691 1469+Q 1431 1431 1272 1322+Q 1113 1213 1113 1003+Q 1113 800 1261 695+Q 1409 591 1641 591+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-34b" d="M 400 -1306+L 400 3494+L 1322 3494+L 1322 2906+L 1366 2906+Q 1428 3044 1548 3191+Q 1669 3338 1867 3438+Q 2066 3538 2363 3538+Q 2750 3538 3072 3338+Q 3394 3138 3586 2738+Q 3778 2338 3778 1741+Q 3778 1159 3590 757+Q 3403 356 3081 148+Q 2759 -59 2356 -59+Q 2072 -59 1875 37+Q 1678 134 1554 276+Q 1431 419 1366 559+L 1338 559+L 1338 -1306+L 400 -1306+z+M 2069 694+Q 2434 694 2626 987+Q 2819 1281 2819 1744+Q 2819 2203 2628 2495+Q 2438 2788 2069 2788+Q 1706 2788 1511 2503+Q 1316 2219 1316 1744+Q 1316 1269 1512 981+Q 1709 694 2069 694+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-29e" d="M 1338 2022+L 1338 0+L 400 0+L 400 4656+L 1319 4656+L 1319 2825+Q 1472 3166 1734 3352+Q 1997 3538 2384 3538+Q 2928 3538 3258 3188+Q 3588 2838 3588 2222+L 3588 0+L 2647 0+L 2647 2059+Q 2647 2384 2480 2568+Q 2313 2753 2016 2753+Q 1716 2753 1527 2561+Q 1338 2369 1338 2022+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-2b1" d="M 400 0+L 400 3494+L 1338 3494+L 1338 0+L 400 0+z+M 869 3950+Q 656 3950 506 4090+Q 356 4231 356 4431+Q 356 4631 506 4772+Q 656 4913 869 4913+Q 1081 4913 1232 4772+Q 1384 4631 1384 4431+Q 1384 4231 1232 4090+Q 1081 3950 869 3950+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-24a" d="M 1963 -69+Q 1434 -69 1051 157+Q 669 384 461 789+Q 253 1194 253 1731+Q 253 2272 461 2678+Q 669 3084 1051 3311+Q 1434 3538 1963 3538+Q 2584 3538 3000 3227+Q 3416 2916 3516 2375+L 2644 2213+Q 2584 2484 2414 2642+Q 2244 2800 1972 2800+Q 1597 2800 1403 2504+Q 1209 2209 1209 1734+Q 1209 1266 1403 967+Q 1597 669 1972 669+Q 2244 669 2419 833+Q 2594 997 2650 1278+L 3522 1119+Q 3422 566 3006 248+Q 2591 -69 1963 -69+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-2e0" d="M 1338 4656+L 1338 0+L 400 0+L 400 4656+L 1338 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-266" d="M 1978 -69+Q 1444 -69 1056 150+Q 669 369 461 772+Q 253 1175 253 1728+Q 253 2269 461 2675+Q 669 3081 1045 3309+Q 1422 3538 1931 3538+Q 2388 3538 2759 3344+Q 3131 3150 3351 2756+Q 3572 2363 3572 1766+L 3572 1503+L 1181 1503+Q 1197 1075 1419 856+Q 1641 638 1994 638+Q 2241 638 2417 742+Q 2594 847 2669 1050+L 3519 891+Q 3391 456 2989 193+Q 2588 -69 1978 -69+z+M 1188 2091+L 2669 2091+Q 2634 2431 2450 2631+Q 2266 2831 1941 2831+Q 1603 2831 1409 2623+Q 1216 2416 1188 2091+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Bold-8d"/>+ <use xlink:href="#Inter-Bold-354" transform="translate(75.046875 0)"/>+ <use xlink:href="#Inter-Bold-1fb" transform="translate(114.40625 0)"/>+ <use xlink:href="#Inter-Bold-34b" transform="translate(172.46875 0)"/>+ <use xlink:href="#Inter-Bold-29e" transform="translate(235.5 0)"/>+ <use xlink:href="#Inter-Bold-2b1" transform="translate(297.75 0)"/>+ <use xlink:href="#Inter-Bold-24a" transform="translate(324.84375 0)"/>+ <use xlink:href="#Inter-Bold-2e0" transform="translate(383.6875 0)"/>+ <use xlink:href="#Inter-Bold-266" transform="translate(410.78125 0)"/>+ </g>+ </g>+ <g id="text_2">+ <!-- whole-repository benchmark -->+ <g style="fill: #8a93a6" transform="translate(195.734375 60) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-3d8" d="M 1278 0+L 219 3494+L 816 3494+L 1241 1969+Q 1316 1697 1403 1358+Q 1491 1019 1575 603+Q 1659 1003 1742 1340+Q 1825 1678 1906 1969+L 2325 3494+L 2925 3494+L 3338 1969+Q 3413 1688 3495 1352+Q 3578 1016 3659 613+Q 3747 1013 3833 1348+Q 3919 1684 3997 1969+L 4422 3494+L 5019 3494+L 3959 0+L 3400 0+L 2947 1581+Q 2859 1881 2779 2200+Q 2700 2519 2619 2853+Q 2541 2519 2458 2197+Q 2375 1875 2291 1581+L 1838 0+L 1278 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-29e" d="M 1056 2094+L 1056 0+L 494 0+L 494 4656+L 1056 4656+L 1056 2888+Q 1228 3238 1495 3388+Q 1763 3538 2106 3538+Q 2638 3538 2964 3209+Q 3291 2881 3291 2219+L 3291 0+L 2725 0+L 2725 2172+Q 2725 2575 2514 2803+Q 2303 3031 1938 3031+Q 1559 3031 1307 2786+Q 1056 2541 1056 2094+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-316" d="M 1916 -75+Q 1441 -75 1083 150+Q 725 375 525 781+Q 325 1188 325 1725+Q 325 2272 525 2680+Q 725 3088 1083 3313+Q 1441 3538 1916 3538+Q 2394 3538 2753 3313+Q 3113 3088 3313 2680+Q 3513 2272 3513 1725+Q 3513 1188 3313 781+Q 3113 375 2753 150+Q 2394 -75 1916 -75+z+M 1916 428+Q 2269 428 2497 609+Q 2725 791 2834 1086+Q 2944 1381 2944 1725+Q 2944 2072 2834 2370+Q 2725 2669 2497 2851+Q 2269 3034 1916 3034+Q 1566 3034 1341 2851+Q 1116 2669 1006 2372+Q 897 2075 897 1725+Q 897 1381 1006 1086+Q 1116 791 1341 609+Q 1566 428 1916 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2e0" d="M 1056 4656+L 1056 0+L 494 0+L 494 4656+L 1056 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-266" d="M 1963 -75+Q 1456 -75 1089 150+Q 722 375 523 778+Q 325 1181 325 1719+Q 325 2256 519 2665+Q 713 3075 1067 3306+Q 1422 3538 1897 3538+Q 2175 3538 2445 3445+Q 2716 3353 2936 3148+Q 3156 2944 3287 2609+Q 3419 2275 3419 1791+L 3419 1556+L 894 1556+Q 916 1009 1208 717+Q 1500 425 1966 425+Q 2275 425 2498 561+Q 2722 697 2819 963+L 3363 813+Q 3241 416 2870 170+Q 2500 -75 1963 -75+z+M 897 2031+L 2847 2031+Q 2806 2478 2567 2758+Q 2328 3038 1897 3038+Q 1597 3038 1380 2897+Q 1163 2756 1038 2528+Q 913 2300 897 2031+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5b3" d="M 2494 2247+L 2494 1728+L 450 1728+L 450 2247+L 2494 2247+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-354" d="M 494 0+L 494 3494+L 1038 3494+L 1038 2956+L 1075 2956+Q 1172 3222 1420 3383+Q 1669 3544 1981 3544+Q 2044 3544 2130 3541+Q 2216 3538 2266 3534+L 2266 2969+Q 2241 2975 2141 2987+Q 2041 3000 1928 3000+Q 1550 3000 1303 2770+Q 1056 2541 1056 2188+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-34b" d="M 494 -1306+L 494 3494+L 1038 3494+L 1038 2934+L 1100 2934+Q 1159 3028 1265 3170+Q 1372 3313 1572 3425+Q 1772 3538 2113 3538+Q 2550 3538 2883 3319+Q 3216 3100 3405 2695+Q 3594 2291 3594 1738+Q 3594 1181 3406 775+Q 3219 369 2886 147+Q 2553 -75 2116 -75+Q 1784 -75 1581 39+Q 1378 153 1268 298+Q 1159 444 1100 541+L 1056 541+L 1056 -1306+L 494 -1306+z+M 2031 428+Q 2359 428 2579 604+Q 2800 781 2911 1079+Q 3022 1378 3022 1744+Q 3022 2106 2912 2398+Q 2803 2691 2583 2862+Q 2363 3034 2031 3034+Q 1550 3034 1300 2678+Q 1050 2322 1050 1744+Q 1050 1159 1303 793+Q 1556 428 2031 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-367" d="M 1681 -75+Q 1144 -75 787 159+Q 431 394 338 847+L 872 975+Q 947 688 1155 553+Q 1363 419 1675 419+Q 2041 419 2258 575+Q 2475 731 2475 947+Q 2475 1306 1963 1428+L 1381 1566+Q 444 1788 444 2519+Q 444 2819 612 3048+Q 781 3278 1073 3408+Q 1366 3538 1738 3538+Q 2278 3538 2576 3302+Q 2875 3066 2994 2697+L 2484 2566+Q 2413 2753 2245 2906+Q 2078 3059 1741 3059+Q 1428 3059 1220 2915+Q 1013 2772 1013 2553+Q 1013 2359 1153 2242+Q 1294 2125 1600 2053+L 2128 1928+Q 2603 1816 2831 1580+Q 3059 1344 3059 984+Q 3059 678 2886 439+Q 2713 200 2402 62+Q 2091 -75 1681 -75+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2b1" d="M 494 0+L 494 3494+L 1056 3494+L 1056 0+L 494 0+z+M 778 4066+Q 619 4066 503 4175+Q 387 4284 387 4438+Q 387 4594 503 4701+Q 619 4809 778 4809+Q 940 4809 1056 4701+Q 1172 4594 1172 4438+Q 1172 4284 1056 4175+Q 940 4066 778 4066+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-379" d="M 1869 3494+L 1869 3013+L 1150 3013+L 1150 906+Q 1150 672 1245 564+Q 1341 456 1563 456+Q 1616 456 1698 468+Q 1781 481 1850 494+L 1966 19+Q 1878 -13 1767 -28+Q 1656 -44 1547 -44+Q 1094 -44 841 195+Q 588 434 588 863+L 588 3013+L 63 3013+L 63 3494+L 588 3494+L 588 4325+L 1150 4325+L 1150 3494+L 1869 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3e6" d="M 438 -1266+L 581 -778+L 641 -794+Q 900 -863 1087 -773+Q 1275 -684 1403 -309+L 1503 -19+L 169 3494+L 784 3494+L 1528 1422+Q 1609 1194 1673 969+Q 1738 744 1797 525+Q 1856 744 1920 969+Q 1984 1194 2066 1422+L 2816 3494+L 3428 3494+L 1894 -522+Q 1734 -938 1478 -1134+Q 1222 -1331 850 -1331+Q 700 -1331 590 -1309+Q 481 -1288 438 -1266+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-6f1" transform="scale(0.015625)"/>+ <path id="Inter-Regular-242" d="M 2116 -75+Q 1784 -75 1581 39+Q 1378 153 1268 298+Q 1159 444 1100 541+L 1038 541+L 1038 0+L 494 0+L 494 4656+L 1056 4656+L 1056 2934+L 1100 2934+Q 1159 3028 1265 3170+Q 1372 3313 1572 3425+Q 1772 3538 2113 3538+Q 2550 3538 2883 3319+Q 3216 3100 3405 2695+Q 3594 2291 3594 1738+Q 3594 1181 3406 775+Q 3219 369 2886 147+Q 2553 -75 2116 -75+z+M 2031 428+Q 2359 428 2579 604+Q 2800 781 2911 1079+Q 3022 1378 3022 1744+Q 3022 2106 2912 2398+Q 2803 2691 2583 2862+Q 2363 3034 2031 3034+Q 1550 3034 1300 2678+Q 1050 2322 1050 1744+Q 1050 1159 1303 793+Q 1556 428 2031 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-305" d="M 1056 2094+L 1056 0+L 494 0+L 494 3494+L 1034 3494+L 1038 2847+Q 1206 3219 1479 3378+Q 1753 3538 2106 3538+Q 2638 3538 2963 3209+Q 3288 2881 3288 2219+L 3288 0+L 2725 0+L 2725 2172+Q 2725 2575 2514 2803+Q 2303 3031 1938 3031+Q 1559 3031 1307 2786+Q 1056 2541 1056 2094+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-24a" d="M 1916 -75+Q 1441 -75 1083 150+Q 725 375 525 781+Q 325 1188 325 1725+Q 325 2272 525 2680+Q 725 3088 1083 3313+Q 1441 3538 1916 3538+Q 2422 3538 2805 3283+Q 3188 3028 3331 2572+L 2791 2419+Q 2713 2688 2486 2861+Q 2259 3034 1916 3034+Q 1566 3034 1341 2851+Q 1116 2669 1006 2372+Q 897 2075 897 1725+Q 897 1381 1006 1086+Q 1116 791 1341 609+Q 1566 428 1916 428+Q 2269 428 2498 608+Q 2728 788 2806 1072+L 3344 919+Q 3203 453 2815 189+Q 2428 -75 1916 -75+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2fe" d="M 494 0+L 494 3494+L 1041 3494+L 1044 2853+Q 1172 3206 1442 3381+Q 1713 3556 2022 3556+Q 2366 3556 2592 3361+Q 2819 3166 2913 2844+Q 3038 3175 3336 3365+Q 3634 3556 4013 3556+Q 4316 3556 4566 3425+Q 4816 3294 4964 3028+Q 5113 2763 5113 2356+L 5113 0+L 4550 0+L 4550 2341+Q 4550 2719 4337 2881+Q 4125 3044 3844 3044+Q 3491 3044 3287 2828+Q 3084 2613 3084 2281+L 3084 0+L 2522 0+L 2522 2397+Q 2522 2688 2328 2866+Q 2134 3044 1838 3044+Q 1531 3044 1293 2831+Q 1056 2619 1056 2200+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-1fb" d="M 1472 -81+Q 1141 -81 870 44+Q 600 169 440 409+Q 281 650 281 994+Q 281 1294 400 1481+Q 519 1669 717 1776+Q 916 1884 1156 1937+Q 1397 1991 1641 2022+Q 1953 2063 2150 2084+Q 2347 2106 2442 2159+Q 2538 2213 2538 2341+L 2538 2359+Q 2538 2684 2353 2864+Q 2169 3044 1806 3044+Q 1428 3044 1215 2880+Q 1003 2716 922 2531+L 381 2709+Q 516 3028 744 3208+Q 972 3388 1247 3463+Q 1522 3538 1791 3538+Q 1966 3538 2189 3495+Q 2413 3453 2620 3328+Q 2828 3203 2964 2958+Q 3100 2713 3100 2303+L 3100 0+L 2547 0+L 2547 475+L 2509 475+Q 2450 353 2319 223+Q 2188 94 1978 6+Q 1769 -81 1472 -81+z+M 1569 416+Q 1881 416 2097 537+Q 2313 659 2425 854+Q 2538 1050 2538 1263+L 2538 1747+Q 2503 1706 2387 1673+Q 2272 1641 2123 1616+Q 1975 1591 1836 1573+Q 1697 1556 1616 1547+Q 1413 1522 1236 1461+Q 1059 1400 953 1283+Q 847 1166 847 966+Q 847 694 1051 555+Q 1256 416 1569 416+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2d7" d="M 494 0+L 494 4656+L 1056 4656+L 1056 1953+L 1125 1953+L 2619 3494+L 3316 3494+L 1853 1994+L 3425 0+L 2703 0+L 1425 1634+L 1056 1288+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-3d8"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(81.84375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(140.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(200.9375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(225.15625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(283.453125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(329.453125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(365.4375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(423.734375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(484.96875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(544.9375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(597.71875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(621.9375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(653.6875 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(713.65625 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(752.859375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(809.0625 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(837.1875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(898.421875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(956.71875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1015.796875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1072.921875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(1132.046875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1219.640625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(1275.796875 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1315 0)"/>+ </g>+ </g>+ <g id="text_3">+ <!-- What a follow-up question costs with the prompt cache -->+ <g style="fill: #f4f6fa" transform="translate(48 112) scale(0.34 -0.34)">+ <defs>+ <path id="InterDisplay-SemiBold-1cb" d="M 1297 0+L 41 4656+L 913 4656+L 1528 2147+Q 1600 1841 1664 1536+Q 1728 1231 1788 925+Q 1850 1231 1919 1536+Q 1988 1841 2063 2147+L 2703 4656+L 3575 4656+L 4209 2147+Q 4284 1844 4353 1542+Q 4422 1241 4484 941+Q 4603 1531 4747 2147+L 5363 4656+L 6238 4656+L 4978 0+L 4044 0+L 3331 2694+Q 3281 2884 3234 3095+Q 3188 3306 3138 3538+Q 3088 3306 3041 3095+Q 2994 2884 2944 2694+L 2234 0+L 1297 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-29e" d="M 1138 1866+L 1138 0+L 350 0+L 350 4656+L 1138 4656+L 1138 2816+Q 1481 3366 2138 3366+Q 2656 3366 2986 3031+Q 3316 2697 3316 2063+L 3316 0+L 2525 0+L 2525 1938+Q 2525 2300 2350 2487+Q 2175 2675 1859 2675+Q 1550 2675 1344 2481+Q 1138 2288 1138 1866+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-1fb" d="M 1356 -53+Q 863 -53 539 195+Q 216 444 216 938+Q 216 1313 398 1517+Q 581 1722 876 1815+Q 1172 1909 1513 1944+Q 1972 1997 2153 2037+Q 2334 2078 2334 2247+L 2334 2272+Q 2334 2484 2173 2618+Q 2013 2753 1731 2753+Q 1444 2753 1264 2618+Q 1084 2484 1069 2275+L 309 2275+Q 338 2766 719 3066+Q 1100 3366 1747 3366+Q 2391 3366 2753 3066+Q 3116 2766 3116 2250+L 3116 0+L 2341 0+L 2341 466+L 2328 466+Q 2209 247 1984 97+Q 1759 -53 1356 -53+z+M 1550 531+Q 1938 531 2138 732+Q 2338 934 2338 1222+L 2338 1578+Q 2266 1531 2059 1492+Q 1853 1453 1609 1416+Q 1356 1378 1170 1273+Q 984 1169 984 944+Q 984 750 1137 640+Q 1291 531 1550 531+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-379" d="M 2091 3300+L 2091 2666+L 1419 2666+L 1419 947+Q 1419 769 1491 701+Q 1563 634 1753 634+L 2091 634+L 2091 0+L 1616 0+Q 1113 0 870 203+Q 628 406 628 831+L 628 2666+L 53 2666+L 53 3300+L 628 3300+L 628 4200+L 1419 4200+L 1419 3300+L 2091 3300+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-6f1" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-287" d="M 2109 3300+L 2109 2666+L 1438 2666+L 1438 0+L 647 0+L 647 2666+L 53 2666+L 53 3300+L 647 3300+L 647 3781+Q 647 4206 905 4431+Q 1163 4656 1650 4656+L 2109 4656+L 2109 4022+L 1806 4022+Q 1603 4022 1520 3937+Q 1438 3853 1438 3650+L 1438 3300+L 2109 3300+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-316" d="M 1825 -75+Q 1338 -75 972 142+Q 606 359 401 746+Q 197 1134 197 1647+Q 197 2159 401 2548+Q 606 2938 972 3156+Q 1338 3375 1825 3375+Q 2309 3375 2676 3156+Q 3044 2938 3248 2548+Q 3453 2159 3453 1647+Q 3453 1134 3248 746+Q 3044 359 2676 142+Q 2309 -75 1825 -75+z+M 1825 584+Q 2203 584 2428 868+Q 2653 1153 2653 1647+Q 2653 2141 2428 2428+Q 2203 2716 1825 2716+Q 1444 2716 1219 2430+Q 994 2144 994 1647+Q 994 1153 1219 868+Q 1444 584 1825 584+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2e0" d="M 1138 4656+L 1138 0+L 350 0+L 350 4656+L 1138 4656+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-3d8" d="M 1075 0+L 56 3300+L 884 3300+L 1225 2047+Q 1303 1753 1375 1440+Q 1447 1128 1522 822+Q 1597 1128 1675 1440+Q 1753 1753 1834 2047+L 2184 3300+L 2913 3300+L 3259 2047+Q 3338 1753 3414 1443+Q 3491 1134 3569 828+Q 3641 1134 3712 1443+Q 3784 1753 3863 2047+L 4203 3300+L 5041 3300+L 4019 0+L 3200 0+L 2800 1375+Q 2734 1603 2671 1843+Q 2609 2084 2547 2325+Q 2488 2084 2425 1843+Q 2363 1603 2294 1375+L 1888 0+L 1075 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-5b3" d="M 2450 2188+L 2450 1525+L 363 1525+L 363 2188+L 2450 2188+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-393" d="M 1525 -66+Q 1006 -66 678 268+Q 350 603 350 1238+L 350 3300+L 1138 3300+L 1138 1363+Q 1138 1000 1313 812+Q 1488 625 1803 625+Q 2116 625 2320 819+Q 2525 1013 2525 1434+L 2525 3300+L 3316 3300+L 3316 0+L 2541 0+L 2541 506+Q 2194 -66 1525 -66+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-34b" d="M 350 -1306+L 350 3300+L 1125 3300+L 1125 2841+L 1134 2841+Q 1291 3103 1553 3234+Q 1816 3366 2134 3366+Q 2559 3366 2879 3148+Q 3200 2931 3379 2545+Q 3559 2159 3559 1653+Q 3559 1138 3382 752+Q 3206 366 2884 150+Q 2563 -66 2131 -66+Q 1806 -66 1554 75+Q 1303 216 1147 497+L 1138 497+L 1138 -1306+L 350 -1306+z+M 1947 594+Q 2313 594 2538 867+Q 2763 1141 2763 1653+Q 2763 2163 2538 2438+Q 2313 2713 1947 2713+Q 1559 2713 1326 2423+Q 1094 2134 1094 1653+Q 1094 1172 1326 883+Q 1559 594 1947 594+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-351" d="M 3406 -1306+L 2619 -1306+L 2619 497+L 2609 497+Q 2453 216 2200 75+Q 1947 -66 1625 -66+Q 1194 -66 872 150+Q 550 366 373 752+Q 197 1138 197 1653+Q 197 2159 375 2545+Q 553 2931 875 3148+Q 1197 3366 1619 3366+Q 1941 3366 2203 3234+Q 2466 3103 2619 2841+L 2631 2841+L 2631 3300+L 3406 3300+L 3406 -1306+z+M 1809 594+Q 2197 594 2430 883+Q 2663 1172 2663 1653+Q 2663 2134 2430 2423+Q 2197 2713 1809 2713+Q 1444 2713 1219 2438+Q 994 2163 994 1653+Q 994 1141 1219 867+Q 1444 594 1809 594+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-266" d="M 1806 -75+Q 1313 -75 950 147+Q 588 369 392 758+Q 197 1147 197 1647+Q 197 2150 398 2539+Q 600 2928 956 3151+Q 1313 3375 1775 3375+Q 2250 3375 2606 3156+Q 2963 2938 3159 2552+Q 3356 2166 3356 1659+L 3356 1444+L 969 1444+Q 984 1041 1206 794+Q 1428 547 1825 547+Q 2122 547 2315 676+Q 2509 806 2578 1019+L 3316 1019+Q 3253 697 3042 450+Q 2831 203 2512 64+Q 2194 -75 1806 -75+z+M 975 1988+L 2600 1988+Q 2563 2341 2345 2545+Q 2128 2750 1788 2750+Q 1444 2750 1230 2545+Q 1016 2341 975 1988+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-367" d="M 1644 -78+Q 1041 -78 636 205+Q 231 488 194 1019+L 972 1019+Q 997 778 1165 645+Q 1334 513 1631 513+Q 1916 513 2080 625+Q 2244 738 2244 913+Q 2244 1063 2122 1153+Q 2000 1244 1794 1288+L 1231 1403+Q 269 1603 269 2356+Q 269 2813 631 3092+Q 994 3372 1597 3372+Q 2197 3372 2573 3076+Q 2950 2781 2963 2272+L 2222 2272+Q 2216 2494 2050 2637+Q 1884 2781 1616 2781+Q 1356 2781 1206 2665+Q 1056 2550 1056 2381+Q 1056 2234 1172 2142+Q 1288 2050 1494 2003+L 2088 1881+Q 2578 1778 2811 1556+Q 3044 1334 3044 972+Q 3044 650 2864 414+Q 2684 178 2368 50+Q 2053 -78 1644 -78+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2b1" d="M 350 0+L 350 3300+L 1138 3300+L 1138 0+L 350 0+z+M 743 3791+Q 540 3791 406 3920+Q 272 4050 272 4241+Q 272 4431 406 4559+Q 540 4688 743 4688+Q 943 4688 1077 4559+Q 1212 4431 1212 4241+Q 1212 4050 1077 3920+Q 943 3791 743 3791+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-305" d="M 1138 1866+L 1138 0+L 350 0+L 350 3300+L 1125 3300+L 1125 2794+Q 1469 3366 2138 3366+Q 2656 3366 2986 3031+Q 3316 2697 3316 2063+L 3316 0+L 2525 0+L 2525 1938+Q 2525 2300 2350 2487+Q 2175 2675 1859 2675+Q 1550 2675 1344 2481+Q 1138 2288 1138 1866+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-24a" d="M 1809 -75+Q 1328 -75 964 144+Q 600 363 398 750+Q 197 1138 197 1647+Q 197 2156 398 2545+Q 600 2934 964 3154+Q 1328 3375 1809 3375+Q 2225 3375 2550 3214+Q 2875 3053 3073 2770+Q 3272 2488 3306 2119+L 2534 2119+Q 2491 2384 2308 2551+Q 2125 2719 1819 2719+Q 1431 2719 1212 2428+Q 994 2138 994 1647+Q 994 1159 1212 870+Q 1431 581 1819 581+Q 2128 581 2300 745+Q 2472 909 2528 1184+L 3306 1184+Q 3278 822 3079 537+Q 2881 253 2554 89+Q 2228 -75 1809 -75+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-354" d="M 350 0+L 350 3300+L 1109 3300+L 1109 2753+L 1119 2753+Q 1209 3034 1404 3182+Q 1600 3331 1919 3331+Q 2000 3331 2064 3326+Q 2128 3322 2175 3319+L 2175 2619+Q 2131 2625 2025 2634+Q 1919 2644 1803 2644+Q 1522 2644 1330 2450+Q 1138 2256 1138 1869+L 1138 0+L 350 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2fe" d="M 350 0+L 350 3300+L 1113 3300+L 1113 2728+Q 1263 3047 1528 3206+Q 1794 3366 2106 3366+Q 2441 3366 2697 3195+Q 2953 3025 3056 2741+Q 3188 3025 3466 3195+Q 3744 3366 4106 3366+Q 4575 3366 4894 3062+Q 5213 2759 5213 2178+L 5213 0+L 4422 0+L 4422 2066+Q 4422 2394 4242 2545+Q 4063 2697 3809 2697+Q 3509 2697 3336 2509+Q 3163 2322 3163 2025+L 3163 0+L 2397 0+L 2397 2103+Q 2397 2372 2228 2534+Q 2059 2697 1797 2697+Q 1531 2697 1334 2511+Q 1138 2325 1138 1969+L 1138 0+L 350 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#InterDisplay-SemiBold-1cb"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(98.09375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(155.375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(209.484375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(244.453125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(267.0625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(321.171875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-287" transform="translate(343.78125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(377.71875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2e0" transform="translate(434.703125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2e0" transform="translate(457.953125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(481.203125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-3d8" transform="translate(536.671875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-5b3" transform="translate(616.3125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-393" transform="translate(660.265625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(717.546875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(776.234375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-351" transform="translate(798.84375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-393" transform="translate(857.53125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(914.8125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(970.140625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1021.609375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2b1" transform="translate(1056.578125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1079.828125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-305" transform="translate(1136.8125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1194.09375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(1216.703125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1271.140625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(1328.125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1379.59375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(1413.734375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1464.21875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-3d8" transform="translate(1486.828125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2b1" transform="translate(1566.46875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1590.5 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(1625.46875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1682.75 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1705.359375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(1740.328125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(1797.609375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1852.9375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(1875.546875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-354" transform="translate(1934.234375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1969.1875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2fe" transform="translate(2026.171875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(2113.03125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(2171.71875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(2206.6875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(2229.296875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(2284.421875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(2338.53125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(2392.96875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(2450.25 0)"/>+ </g>+ </g>+ <g id="text_4">+ <!-- Input cost of a follow-up question with a 1M-token context; prefix and question-specific tokens measured on the development repositories. Computed at the -->+ <g style="fill: #8a93a6" transform="translate(48 146) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-c5" d="M 1156 4656+L 1156 0+L 563 0+L 563 4656+L 1156 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-393" d="M 1678 -44+Q 1150 -44 822 284+Q 494 613 494 1275+L 494 3494+L 1056 3494+L 1056 1322+Q 1056 919 1268 691+Q 1481 463 1847 463+Q 2222 463 2473 708+Q 2725 953 2725 1400+L 2725 3494+L 3291 3494+L 3291 0+L 2747 0+L 2747 653+Q 2575 272 2298 114+Q 2022 -44 1678 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-287" d="M 2119 3494+L 2119 3013+L 1313 3013+L 1313 0+L 750 0+L 750 3013+L 63 3013+L 63 3494+L 750 3494+L 750 3959+Q 750 4263 892 4466+Q 1034 4669 1262 4772+Q 1491 4875 1744 4875+Q 1944 4875 2075 4842+Q 2206 4809 2269 4781+L 2113 4300+Q 2069 4316 1998 4334+Q 1928 4353 1809 4353+Q 1550 4353 1431 4220+Q 1313 4088 1313 3834+L 1313 3494+L 2119 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-351" d="M 3425 -1306+L 2863 -1306+L 2863 541+L 2819 541+Q 2763 444 2652 298+Q 2541 153 2339 39+Q 2138 -75 1803 -75+Q 1369 -75 1034 147+Q 700 369 512 775+Q 325 1181 325 1738+Q 325 2291 514 2695+Q 703 3100 1037 3319+Q 1372 3538 1806 3538+Q 2147 3538 2347 3425+Q 2547 3313 2655 3170+Q 2763 3028 2819 2934+L 2881 2934+L 2881 3494+L 3425 3494+L 3425 -1306+z+M 1888 428+Q 2363 428 2616 793+Q 2869 1159 2869 1744+Q 2869 2322 2620 2678+Q 2372 3034 1888 3034+Q 1556 3034 1336 2862+Q 1116 2691 1006 2398+Q 897 2106 897 1744+Q 897 1378 1008 1079+Q 1119 781 1341 604+Q 1563 428 1888 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-53e" d="M 2041 4656+L 2041 0+L 1456 0+L 1456 4106+L 1425 4106+L 300 3272+L 300 3909+L 1313 4656+L 2041 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-124" d="M 563 0+L 563 4656+L 1406 4656+L 2553 1719+Q 2619 1550 2716 1247+Q 2813 944 2897 659+Q 2978 934 3075 1239+Q 3172 1544 3241 1719+L 4372 4656+L 5219 4656+L 5219 0+L 4634 0+L 4634 2659+Q 4634 2916 4640 3287+Q 4647 3659 4656 4022+Q 4528 3622 4398 3244+Q 4269 2866 4188 2659+L 3147 0+L 2631 0+L 1575 2659+Q 1497 2856 1370 3229+Q 1244 3603 1106 4013+Q 1113 3681 1120 3304+Q 1128 2928 1128 2659+L 1128 0+L 563 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3e1" d="M 203 0+L 1431 1794+L 275 3494+L 931 3494+L 1366 2816+Q 1484 2628 1579 2461+Q 1675 2294 1766 2134+Q 1850 2294 1937 2461+Q 2025 2628 2147 2816+L 2591 3494+L 3234 3494+L 2066 1763+L 3291 0+L 2638 0+L 2125 784+Q 2009 963 1918 1123+Q 1828 1284 1741 1431+Q 1659 1284 1575 1123+Q 1491 963 1372 784+L 853 0+L 203 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5e4" d="M 400 -1122+L 675 650+L 1319 650+L 831 -1122+L 400 -1122+z+M 1010 2487+Q 835 2487 711 2610+Q 588 2734 588 2909+Q 588 3084 711 3207+Q 835 3331 1010 3331+Q 1185 3331 1308 3207+Q 1432 3084 1432 2909+Q 1432 2734 1308 2610+Q 1185 2487 1010 2487+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-255" d="M 1803 -75+Q 1369 -75 1034 147+Q 700 369 512 775+Q 325 1181 325 1738+Q 325 2291 514 2695+Q 703 3100 1037 3319+Q 1372 3538 1806 3538+Q 2147 3538 2347 3425+Q 2547 3313 2655 3170+Q 2763 3028 2819 2934+L 2863 2934+L 2863 4656+L 3425 4656+L 3425 0+L 2881 0+L 2881 541+L 2819 541+Q 2763 444 2652 298+Q 2541 153 2339 39+Q 2138 -75 1803 -75+z+M 1888 428+Q 2363 428 2616 793+Q 2869 1159 2869 1744+Q 2869 2322 2620 2678+Q 2372 3034 1888 3034+Q 1556 3034 1336 2862+Q 1116 2691 1006 2398+Q 897 2106 897 1744+Q 897 1378 1008 1079+Q 1119 781 1341 604+Q 1563 428 1888 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3d4" d="M 1503 0+L 169 3494+L 784 3494+L 1528 1422+Q 1609 1194 1675 967+Q 1741 741 1800 522+Q 1859 741 1923 967+Q 1988 1194 2069 1422+L 2813 3494+L 3428 3494+L 2094 0+L 1503 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5de" d="M 922 -41+Q 747 -41 623 82+Q 500 206 500 381+Q 500 556 623 679+Q 747 803 922 803+Q 1097 803 1220 679+Q 1344 556 1344 381+Q 1344 206 1220 82+Q 1097 -41 922 -41+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-49" d="M 2447 -63+Q 1850 -63 1383 226+Q 916 516 648 1052+Q 381 1588 381 2325+Q 381 3066 648 3602+Q 916 4138 1383 4428+Q 1850 4719 2447 4719+Q 2919 4719 3314 4536+Q 3709 4353 3976 4012+Q 4244 3672 4325 3191+L 3731 3191+Q 3666 3509 3477 3728+Q 3288 3947 3019 4058+Q 2750 4169 2447 4169+Q 2028 4169 1690 3956+Q 1353 3744 1156 3333+Q 959 2922 959 2325+Q 959 1731 1157 1320+Q 1356 909 1693 698+Q 2031 488 2447 488+Q 2753 488 3020 600+Q 3288 713 3477 931+Q 3666 1150 3731 1466+L 4325 1466+Q 4244 994 3980 650+Q 3716 306 3320 121+Q 2925 -63 2447 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-c5"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(26.859375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(85.9375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(147.171875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(206.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(239.015625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(267.140625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(324.265625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(384.234375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(437.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(469.734375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(497.859375 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(557.828125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(594.84375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(622.96875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(679.125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(707.25 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(741.34375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(801.3125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(825.53125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(849.75 0)"/>+ <use xlink:href="#Inter-Regular-3d8" transform="translate(907.90625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(989.75 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1035.75 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(1094.875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1156.109375 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(1184.234375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1245.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1304.59375 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1362.890625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1415.671875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1448.390625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1472.609375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1532.578125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1591.65625 0)"/>+ <use xlink:href="#Inter-Regular-3d8" transform="translate(1619.78125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1701.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1725.84375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1758.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1817.6875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1845.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1901.96875 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(1930.09375 0)"/>+ <use xlink:href="#Inter-Regular-124" transform="translate(1970.765625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(2061.09375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2107.09375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2138.84375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(2198.8125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2251.453125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2309.75 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2368.828125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(2396.953125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2454.078125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2514.046875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2573.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2604.875 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(2660.921875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2717.46875 0)"/>+ <use xlink:href="#Inter-Regular-5e4" transform="translate(2750.1875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2780.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2808.484375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2869.71875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2905.703125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(2964 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3001.015625 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(3025.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3079.828125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3107.953125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3164.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(3223.1875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3284.421875 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(3312.546875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3373.78125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3432.90625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3491.203125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3543.984375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3576.703125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3600.921875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3660.890625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(3719.96875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3765.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(3818.75 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3879.984375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(3938.28125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3995.40625 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(4019.625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4056.640625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4080.859375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4137.984375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4166.109375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4197.859375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(4257.828125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4310.46875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(4368.765625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4427.84375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4480.625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4508.75 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4596.34375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4655.625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4711.78125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(4764.5625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4823.6875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4859.671875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(4917.96875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4979.203125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5007.328125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(5067.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5126.375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5154.5 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5187.21875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5246.34375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5304.640625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5332.765625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5394 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(5450.34375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5504.59375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5562.890625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5587.109375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(5647.078125 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(5708.3125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5795.90625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(5854.203125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5913.28125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5946 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(5974.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6010.109375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6068.40625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6129.640625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(6189.609375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6242.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6266.609375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6298.359375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6358.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6396.953125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6421.171875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(6479.46875 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(6532.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6561.0625 0)"/>+ <use xlink:href="#Inter-Regular-49" transform="translate(6589.1875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6662.234375 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(6722.203125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6809.796875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(6871.03125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6930.15625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6961.90625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(7020.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7081.4375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(7109.5625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7165.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7198.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7226.5625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(7259.28125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(7318.40625 0)"/>+ </g>+ </g>+ <g id="text_5">+ <!-- list prices of 2026-10-26, not billed. Output is billed on top. -->+ <g style="fill: #8a93a6" transform="translate(48 172) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-53f" d="M 481 0+L 481 428+L 2028 2106+Q 2288 2388 2459 2600+Q 2631 2813 2718 3005+Q 2806 3197 2806 3413+Q 2806 3778 2554 3990+Q 2303 4203 1931 4203+Q 1534 4203 1298 3965+Q 1063 3728 1063 3334+L 494 3334+Q 494 3747 684 4059+Q 875 4372 1203 4545+Q 1531 4719 1947 4719+Q 2363 4719 2683 4545+Q 3003 4372 3186 4078+Q 3369 3784 3369 3419+Q 3369 3166 3278 2927+Q 3188 2688 2959 2384+Q 2731 2081 2319 1644+L 1300 559+L 1300 522+L 3447 522+L 3447 0+L 481 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-53d" d="M 2019 -63+Q 1241 -63 811 562+Q 381 1188 381 2325+Q 381 3456 814 4087+Q 1247 4719 2019 4719+Q 2794 4719 3225 4087+Q 3656 3456 3656 2325+Q 3656 1188 3228 562+Q 2800 -63 2019 -63+z+M 2019 456+Q 2531 456 2807 948+Q 3084 1441 3084 2325+Q 3084 3216 2807 3709+Q 2531 4203 2019 4203+Q 1509 4203 1231 3708+Q 953 3213 953 2325+Q 953 1441 1231 948+Q 1509 456 2019 456+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-545" d="M 2019 -63+Q 1728 -63 1437 43+Q 1147 150 908 400+Q 669 650 525 1078+Q 381 1506 381 2150+Q 381 3378 840 4048+Q 1300 4719 2091 4719+Q 2481 4719 2790 4562+Q 3100 4406 3297 4128+Q 3494 3850 3550 3484+L 2969 3484+Q 2891 3788 2672 3991+Q 2453 4194 2091 4194+Q 1553 4194 1248 3730+Q 944 3266 944 2425+L 981 2425+Q 1169 2716 1467 2880+Q 1766 3044 2128 3044+Q 2528 3044 2859 2847+Q 3191 2650 3389 2301+Q 3588 1953 3588 1503+Q 3588 1069 3394 714+Q 3200 359 2847 148+Q 2494 -63 2019 -63+z+M 2019 459+Q 2300 459 2525 600+Q 2750 741 2881 977+Q 3013 1213 3013 1503+Q 3013 1788 2886 2020+Q 2759 2253 2537 2390+Q 2316 2528 2034 2528+Q 1753 2528 1525 2384+Q 1297 2241 1162 2005+Q 1028 1769 1028 1497+Q 1028 1222 1156 986+Q 1284 750 1509 604+Q 1734 459 2019 459+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5bf" d="M 2494 2581+L 2494 2062+L 450 2062+L 450 2581+L 2494 2581+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5dd" d="M 400 -1122+L 675 650+L 1319 650+L 831 -1122+L 400 -1122+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-141" d="M 2450 -63+Q 1853 -63 1386 226+Q 919 516 650 1052+Q 381 1588 381 2325+Q 381 3066 650 3602+Q 919 4138 1386 4428+Q 1853 4719 2450 4719+Q 3047 4719 3512 4428+Q 3978 4138 4245 3602+Q 4513 3066 4513 2325+Q 4513 1588 4245 1052+Q 3978 516 3512 226+Q 3047 -63 2450 -63+z+M 2450 488+Q 2866 488 3202 698+Q 3538 909 3736 1320+Q 3934 1731 3934 2325+Q 3934 2925 3736 3336+Q 3538 3747 3202 3958+Q 2866 4169 2450 4169+Q 2031 4169 1693 3956+Q 1356 3744 1157 3333+Q 959 2922 959 2325+Q 959 1731 1157 1322+Q 1356 913 1693 700+Q 2031 488 2450 488+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-2e0"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(24.21875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(48.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(101.21875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(133.9375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(162.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(223.296875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(261.921875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(286.140625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(343.265625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(401.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(454.34375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(482.46875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(542.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(579.453125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(607.578125 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(668.5625 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(731.65625 0)"/>+ <use xlink:href="#Inter-Regular-545" transform="translate(792.640625 0)"/>+ <use xlink:href="#Inter-Regular-5bf" transform="translate(854.65625 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(900.65625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(941.328125 0)"/>+ <use xlink:href="#Inter-Regular-5bf" transform="translate(1004.421875 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(1047.046875 0)"/>+ <use xlink:href="#Inter-Regular-545" transform="translate(1108.03125 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1166.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1195.484375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1223.609375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1282.6875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1342.65625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1375.375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(1403.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1464.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1488.953125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1513.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1537.390625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1595.6875 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1656.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1685.734375 0)"/>+ <use xlink:href="#Inter-Regular-141" transform="translate(1713.859375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1790.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1849.453125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(1882.171875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1943.40625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2002.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2035.25 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(2063.375 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2087.59375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2140.375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(2168.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(2229.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2253.953125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2278.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2302.390625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(2360.6875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2421.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2450.046875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2510.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2569.09375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2597.21875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2628.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2688.9375 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(2750.171875 0)"/>+ </g>+ </g>+ <g id="text_6">+ <!-- Without the cache -->+ <g style="fill: #c9ced8" transform="translate(76 212) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-1cb" d="M 1422 0+L 159 4656+L 909 4656+L 1581 1988+Q 1656 1681 1722 1348+Q 1788 1016 1847 678+Q 1913 1016 1980 1348+Q 2047 1681 2128 1988+L 2819 4656+L 3600 4656+L 4284 1988+Q 4363 1684 4431 1356+Q 4500 1028 4566 697+Q 4625 1028 4692 1356+Q 4759 1684 4831 1988+L 5503 4656+L 6259 4656+L 4991 0+L 4169 0+L 3428 2759+Q 3366 2994 3311 3259+Q 3256 3525 3206 3828+Q 3156 3541 3104 3280+Q 3053 3019 2984 2759+L 2247 0+L 1422 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2b1" d="M 463 0+L 463 3494+L 1150 3494+L 1150 0+L 463 0+z+M 809 4028+Q 631 4028 504 4147+Q 378 4266 378 4434+Q 378 4606 504 4725+Q 631 4844 809 4844+Q 987 4844 1115 4725+Q 1243 4606 1243 4434+Q 1243 4266 1115 4147+Q 987 4028 809 4028+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-379" d="M 1956 3494+L 1956 2934+L 1259 2934+L 1259 944+Q 1259 734 1348 636+Q 1438 538 1641 538+Q 1697 538 1783 550+Q 1869 563 1931 575+L 2053 25+Q 1944 -13 1817 -30+Q 1691 -47 1572 -47+Q 1097 -47 834 198+Q 572 444 572 888+L 572 2934+L 63 2934+L 63 3494+L 572 3494+L 572 4325+L 1259 4325+L 1259 3494+L 1956 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-29e" d="M 1150 2069+L 1150 0+L 463 0+L 463 4656+L 1144 4656+L 1144 2866+Q 1309 3213 1575 3375+Q 1841 3538 2200 3538+Q 2734 3538 3062 3202+Q 3391 2866 3391 2219+L 3391 0+L 2700 0+L 2700 2134+Q 2700 2513 2503 2725+Q 2306 2938 1963 2938+Q 1613 2938 1381 2711+Q 1150 2484 1150 2069+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-316" d="M 1931 -72+Q 1441 -72 1073 153+Q 706 378 503 783+Q 300 1188 300 1728+Q 300 2272 503 2680+Q 706 3088 1073 3313+Q 1441 3538 1931 3538+Q 2425 3538 2792 3313+Q 3159 3088 3362 2680+Q 3566 2272 3566 1728+Q 3566 1188 3362 783+Q 3159 378 2792 153+Q 2425 -72 1931 -72+z+M 1931 509+Q 2250 509 2458 676+Q 2666 844 2767 1120+Q 2869 1397 2869 1728+Q 2869 2063 2767 2342+Q 2666 2622 2458 2789+Q 2250 2956 1931 2956+Q 1616 2956 1409 2789+Q 1203 2622 1101 2342+Q 1000 2063 1000 1728+Q 1000 1397 1101 1120+Q 1203 844 1409 676+Q 1616 509 1931 509+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-393" d="M 1653 -44+Q 1119 -44 791 292+Q 463 628 463 1275+L 463 3494+L 1150 3494+L 1150 1359+Q 1150 981 1348 768+Q 1547 556 1888 556+Q 2238 556 2469 782+Q 2700 1009 2700 1425+L 2700 3494+L 3391 3494+L 3391 0+L 2731 0+L 2728 678+Q 2563 297 2289 126+Q 2016 -44 1653 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-6f1" transform="scale(0.015625)"/>+ <path id="Inter-Medium-266" d="M 1969 -72+Q 1453 -72 1078 150+Q 703 372 501 775+Q 300 1178 300 1722+Q 300 2259 498 2668+Q 697 3078 1059 3308+Q 1422 3538 1909 3538+Q 2306 3538 2664 3361+Q 3022 3184 3245 2798+Q 3469 2413 3469 1781+L 3469 1538+L 991 1538+Q 1009 1031 1278 764+Q 1547 497 1975 497+Q 2263 497 2470 622+Q 2678 747 2769 991+L 3416 838+Q 3291 428 2909 178+Q 2528 -72 1969 -72+z+M 994 2050+L 2788 2050+Q 2750 2463 2529 2716+Q 2309 2969 1913 2969+Q 1500 2969 1261 2698+Q 1022 2428 994 2050+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-24a" d="M 1931 -72+Q 1438 -72 1072 153+Q 706 378 503 783+Q 300 1188 300 1728+Q 300 2272 503 2680+Q 706 3088 1072 3313+Q 1438 3538 1931 3538+Q 2475 3538 2870 3264+Q 3266 2991 3394 2506+L 2741 2350+Q 2669 2622 2461 2789+Q 2253 2956 1934 2956+Q 1619 2956 1411 2790+Q 1203 2625 1101 2345+Q 1000 2066 1000 1728+Q 1000 1394 1101 1117+Q 1203 841 1411 675+Q 1619 509 1934 509+Q 2259 509 2471 682+Q 2684 856 2753 1141+L 3403 984+Q 3275 491 2878 209+Q 2481 -72 1931 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-1fb" d="M 1441 -78+Q 1106 -78 839 45+Q 572 169 415 406+Q 259 644 259 988+Q 259 1284 375 1476+Q 491 1669 684 1780+Q 878 1891 1117 1947+Q 1356 2003 1603 2031+Q 2066 2084 2275 2123+Q 2484 2163 2484 2347+L 2484 2366+Q 2484 2656 2314 2817+Q 2144 2978 1816 2978+Q 1472 2978 1275 2828+Q 1078 2678 1006 2500+L 359 2669+Q 478 2981 700 3172+Q 922 3363 1208 3450+Q 1494 3538 1806 3538+Q 2016 3538 2253 3488+Q 2491 3438 2700 3308+Q 2909 3178 3040 2937+Q 3172 2697 3172 2319+L 3172 0+L 2506 0+L 2506 478+L 2472 478+Q 2369 272 2117 97+Q 1866 -78 1441 -78+z+M 1594 475+Q 1872 475 2072 586+Q 2272 697 2380 875+Q 2488 1053 2488 1259+L 2488 1706+Q 2438 1656 2273 1620+Q 2109 1584 1928 1559+Q 1747 1534 1641 1522+Q 1350 1481 1142 1364+Q 934 1247 934 978+Q 934 728 1120 601+Q 1306 475 1594 475+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-1cb"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(100.296875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(125.5 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(159.625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(219.78125 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(280.1875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(340.34375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(374.375 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(401.03125 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(435.15625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(495.3125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(554.046875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(580.703125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(639.40625 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(696.1875 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(753.90625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(814.0625 0)"/>+ </g>+ </g>+ <g id="text_7">+ <!-- With the cache -->+ <g style="fill: #c9ced8" transform="translate(318.59375 212) scale(0.2 -0.2)">+ <use xlink:href="#Inter-Medium-1cb"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(100.296875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(125.5 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(159.625 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(219.78125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(246.4375 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(280.5625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(340.71875 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(399.453125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(426.109375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(484.8125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(541.59375 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(599.3125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(659.46875 0)"/>+ </g>+ </g>+ <g id="text_8">+ <!-- Shared prefix: the part of the context that is the same for every question about a repository at one commit, billed at the cached-input price after the first question. Truncation's -->+ <g style="fill: #8a93a6" transform="translate(48 821) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-18d" d="M 2053 -81+Q 1297 -81 850 276+Q 403 634 363 1219+L 972 1219+Q 997 956 1150 786+Q 1303 616 1542 533+Q 1781 450 2053 450+Q 2369 450 2620 553+Q 2872 656 3019 843+Q 3166 1031 3166 1278+Q 3166 1503 3039 1643+Q 2913 1784 2703 1875+Q 2494 1966 2244 2034+L 1681 2194+Q 1119 2353 806 2650+Q 494 2947 494 3409+Q 494 3803 706 4098+Q 919 4394 1281 4556+Q 1644 4719 2094 4719+Q 2553 4719 2906 4556+Q 3259 4394 3464 4114+Q 3669 3834 3681 3481+L 3100 3481+Q 3059 3822 2775 4008+Q 2491 4194 2075 4194+Q 1622 4194 1347 3980+Q 1072 3766 1072 3438+Q 1072 3194 1223 3045+Q 1375 2897 1583 2814+Q 1791 2731 1959 2684+L 2425 2556+Q 2613 2506 2839 2418+Q 3066 2331 3272 2186+Q 3478 2041 3611 1817+Q 3744 1594 3744 1269+Q 3744 888 3545 581+Q 3347 275 2969 97+Q 2591 -81 2053 -81+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5e1" d="M 922 -41+Q 747 -41 623 82+Q 500 206 500 381+Q 500 556 623 679+Q 747 803 922 803+Q 1097 803 1220 679+Q 1344 556 1344 381+Q 1344 206 1220 82+Q 1097 -41 922 -41+z+M 922 2487+Q 747 2487 623 2610+Q 500 2734 500 2909+Q 500 3084 623 3207+Q 747 3331 922 3331+Q 1097 3331 1220 3207+Q 1344 3084 1344 2909+Q 1344 2734 1220 2610+Q 1097 2487 922 2487+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-19b" d="M 306 4131+L 306 4656+L 3825 4656+L 3825 4131+L 2366 4131+L 2366 0+L 1772 0+L 1772 4131+L 306 4131+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5cc" d="M 725 2884+L 656 4656+L 1263 4656+L 1194 2884+L 725 2884+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-18d"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(123.28125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(179.4375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(215.421875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(273.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(334.953125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(363.078125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(424.3125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(460.296875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(518.59375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(555.609375 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(579.828125 0)"/>+ <use xlink:href="#Inter-Regular-5e1" transform="translate(634.421875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(663.234375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(691.359375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(724.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(783.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(841.5 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(869.625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(931.84375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(988 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1027.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1059.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1088.046875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(1148.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1185.03125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1213.15625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1245.875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1305 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1363.296875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1391.421875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1448.546875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1508.515625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1567.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1599.34375 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(1655.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1711.9375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1744.65625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1772.78125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1805.5 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1864.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1920.78125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1953.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1981.625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2005.84375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2058.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2086.75 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2119.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2178.59375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2236.890625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2265.015625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2317.796875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(2373.953125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2461.546875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2519.84375 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(2547.96875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2582.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2642.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2679.671875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2707.796875 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(2764.140625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2818.390625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2876.6875 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(2915.890625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2972.09375 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(3000.21875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3061.453125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3120.578125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3178.875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3231.65625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3264.375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3288.59375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3348.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3407.640625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3435.765625 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(3491.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3553.15625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3613.125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3672.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3704.96875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3733.09375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3789.25 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3817.375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3853.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(3911.65625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3972.890625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4032.859375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4085.640625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4109.859375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4141.609375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4201.578125 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(4240.78125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4296.984375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4325.109375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4381.265625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4413.984375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4442.109375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(4502.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4561.15625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4619.453125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4647.578125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4704.703125 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4764.671875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4852.265625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4939.859375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4964.078125 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(4996.796875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5025.609375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(5053.734375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(5114.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5139.1875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5163.40625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5187.625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5245.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5307.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(5335.28125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5391.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5424.15625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5452.28125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5485 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5544.125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5602.421875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(5630.546875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(5688.65625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(5744.8125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5801.9375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5861.0625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5919.359375 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(5980.59375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6026.59375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(6050.8125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6109.890625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(6171.125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6230.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6262.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6291.09375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6352.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6390.953125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(6415.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6472.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6530.59375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(6558.71875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(6614.875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6648.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6680.21875 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6738.515625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6776.15625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6804.28125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(6837 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6896.125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6954.421875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(6982.546875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(7019.5625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(7043.78125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(7081.421875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7134.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7166.921875 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(7195.046875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(7256.28125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(7315.40625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(7373.703125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7426.484375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(7459.203125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(7483.421875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(7543.390625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(7602.46875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7631.28125 0)"/>+ <use xlink:href="#Inter-Regular-19b" transform="translate(7659.40625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(7718.296875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(7755.9375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(7815.0625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(7874.140625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(7932.25 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7988.40625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(8021.125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(8045.34375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(8105.3125 0)"/>+ <use xlink:href="#Inter-Regular-5cc" transform="translate(8164.390625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(8194.375 0)"/>+ </g>+ </g>+ <g id="text_9">+ <!-- dump is all shared prefix, so it is cached like the stable pack. Whether a call is served from the cache is up to the API. -->+ <g style="fill: #8a93a6" transform="translate(48 846) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-1cb" d="M 1431 0+L 163 4656+L 769 4656+L 1506 1800+Q 1581 1500 1650 1190+Q 1719 881 1781 553+Q 1844 881 1912 1190+Q 1981 1500 2063 1800+L 2816 4656+L 3491 4656+L 4238 1800+Q 4394 1216 4522 572+Q 4581 894 4651 1198+Q 4722 1503 4797 1800+L 5531 4656+L 6144 4656+L 4869 0+L 4178 0+L 3378 2950+Q 3319 3172 3261 3425+Q 3203 3678 3150 3984+Q 3097 3700 3044 3451+Q 2991 3203 2922 2950+L 2125 0+L 1431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2" d="M 163 0+L 1853 4656+L 2541 4656+L 4253 0+L 3628 0+L 3163 1300+L 1244 1300+L 794 0+L 163 0+z+M 1425 1819+L 2978 1819+L 2641 2763+Q 2556 2997 2450 3336+Q 2344 3675 2194 4181+Q 2047 3666 1937 3322+Q 1828 2978 1753 2763+L 1425 1819+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-177" d="M 563 0+L 563 4656+L 2156 4656+Q 2700 4656 3051 4457+Q 3403 4259 3573 3925+Q 3744 3591 3744 3175+Q 3744 2759 3573 2421+Q 3403 2084 3053 1884+Q 2703 1684 2159 1684+L 1156 1684+L 1156 0+L 563 0+z+M 1156 2206+L 2131 2206+Q 2684 2206 2918 2482+Q 3153 2759 3153 3175+Q 3153 3588 2918 3861+Q 2684 4134 2125 4134+L 1156 4134+L 1156 2206+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-255"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(61.234375 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(120.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(207.953125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(269.1875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(297.3125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(321.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(374.3125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(402.4375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(458.59375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(482.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(507.03125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(535.15625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(587.9375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(647.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(703.21875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(739.203125 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(797.5 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(858.734375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(886.859375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(948.09375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(984.078125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(1042.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1079.390625 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(1103.609375 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1158.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1187.015625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1215.140625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1267.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1327.890625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1356.015625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1380.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1412.953125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1441.078125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1465.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1518.078125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1546.203125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1604.3125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1660.46875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1717.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1776.71875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1835.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1896.25 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1924.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1948.59375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1972.8125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2025.453125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2083.75 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2111.875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2144.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2203.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2262.015625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2290.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2342.921875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2376.125 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(2432.28125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2493.515625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2517.734375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2576.03125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2604.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2666.375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(2722.53125 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(2779.65625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(2834.546875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2863.359375 0)"/>+ <use xlink:href="#Inter-Regular-1cb" transform="translate(2891.484375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2990.015625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3049.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3107.4375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(3140.15625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3199.28125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3257.578125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3295.21875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3323.34375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3379.5 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(3407.625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3465.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(3521.890625 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(3546.109375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3570.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3598.453125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3622.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3675.453125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3703.578125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3756.359375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3814.65625 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(3853.859375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3908.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(3966.40625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4027.640625 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(4055.765625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4092.78125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4128.765625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4188.734375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4276.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4304.453125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(4337.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4396.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4454.59375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4482.71875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4540.828125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4596.984375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(4654.109375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4713.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4771.53125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4799.65625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4823.875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4876.65625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(4904.78125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(4963.90625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5025.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5053.265625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5085.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5144.984375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5173.109375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5205.828125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5264.953125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5323.25 0)"/>+ <use xlink:href="#Inter-Regular-2" transform="translate(5351.375 0)"/>+ <use xlink:href="#Inter-Regular-177" transform="translate(5420.375 0)"/>+ <use xlink:href="#Inter-Regular-c5" transform="translate(5484.25 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(5511.109375 0)"/>+ </g>+ </g>+ <g id="text_10">+ <!-- Method and data: -->+ <g style="fill: #8a93a6" transform="translate(48 871) scale(0.18 -0.18)">+ <use xlink:href="#Inter-Regular-124"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(90.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(148.625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(181.34375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(240.46875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(300.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(361.671875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(389.796875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(445.953125 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(505.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(566.265625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(594.390625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(655.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(711.78125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(744.984375 0)"/>+ <use xlink:href="#Inter-Regular-5e1" transform="translate(801.140625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(829.953125 0)"/>+ </g>+ </g>+ <g id="text_11">+ <!-- github.com/graphicle-ai/graphicle/blob/main/docs/benchmarks/whole-repo.md -->+ <g style="fill: #8a93a6" transform="translate(202.46875 871) scale(0.17 -0.17)">+ <defs>+ <path id="JetBrainsMono-Regular-f5" d="M 1030 -1152+L 1030 -627+L 2022 -627+Q 2323 -627 2496 -457+Q 2669 -288 2669 0+L 2669 320+L 2682 896+L 2662 896+Q 2611 582 2361 412+Q 2112 243 1734 243+Q 1190 243 876 588+Q 563 934 563 1536+L 563 2278+Q 563 2880 876 3232+Q 1190 3584 1734 3584+Q 2112 3584 2361 3405+Q 2611 3226 2662 2912+L 2675 2912+L 2675 3520+L 3245 3520+L 3245 0+Q 3245 -531 2915 -841+Q 2586 -1152 2016 -1152+L 1030 -1152+z+M 1907 723+Q 2266 723 2470 947+Q 2675 1171 2675 1568+L 2675 2240+Q 2675 2637 2470 2861+Q 2266 3085 1907 3085+Q 1542 3085 1340 2873+Q 1139 2662 1139 2304+L 1139 1504+Q 1139 1146 1340 934+Q 1542 723 1907 723+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-ff" d="M 544 0+L 544 525+L 1792 525+L 1792 2995+L 672 2995+L 672 3520+L 2368 3520+L 2368 525+L 3552 525+L 3552 0+L 544 0+z+M 2016 4154+Q 1805 4154 1683 4262+Q 1562 4371 1562 4557+Q 1562 4749 1683 4861+Q 1805 4973 2016 4973+Q 2227 4973 2348 4861+Q 2470 4749 2470 4557+Q 2470 4371 2348 4262+Q 2227 4154 2016 4154+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-14c" d="M 2272 0+Q 1837 0 1574 253+Q 1312 506 1312 928+L 1312 2995+L 301 2995+L 301 3520+L 1312 3520+L 1312 4512+L 1888 4512+L 1888 3520+L 3328 3520+L 3328 2995+L 1888 2995+L 1888 928+Q 1888 749 1993 637+Q 2099 525 2272 525+L 3296 525+L 3296 0+L 2272 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-fc" d="M 589 0+L 589 4672+L 1165 4672+L 1165 2848+L 1171 2848+Q 1216 3200 1459 3392+Q 1702 3584 2106 3584+Q 2637 3584 2950 3257+Q 3264 2931 3264 2368+L 3264 0+L 2688 0+L 2688 2272+Q 2688 2669 2486 2883+Q 2285 3098 1939 3098+Q 1581 3098 1373 2874+Q 1165 2650 1165 2240+L 1165 0+L 589 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-151" d="M 1914 -64+Q 1306 -64 941 297+Q 576 659 576 1280+L 576 3520+L 1152 3520+L 1152 1280+Q 1152 896 1357 669+Q 1562 442 1914 442+Q 2272 442 2480 669+Q 2688 896 2688 1280+L 2688 3520+L 3264 3520+L 3264 1280+Q 3264 659 2893 297+Q 2522 -64 1914 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-d6" d="M 2125 -64+Q 1728 -64 1472 131+Q 1216 326 1171 672+L 1165 672+L 1165 0+L 589 0+L 589 4672+L 1165 4672+L 1165 3648+L 1152 2848+L 1158 2848+Q 1210 3187 1469 3385+Q 1728 3584 2125 3584+Q 2656 3584 2969 3232+Q 3283 2880 3283 2272+L 3283 1242+Q 3283 640 2969 288+Q 2656 -64 2125 -64+z+M 1933 435+Q 2298 435 2502 627+Q 2707 819 2707 1248+L 2707 2272+Q 2707 2707 2502 2896+Q 2298 3085 1933 3085+Q 1581 3085 1373 2861+Q 1165 2637 1165 2240+L 1165 1280+Q 1165 883 1373 659+Q 1581 435 1933 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-329" d="M 1920 -64+Q 1683 -64 1539 77+Q 1395 218 1395 442+Q 1395 678 1539 825+Q 1683 973 1920 973+Q 2157 973 2301 825+Q 2445 678 2445 442+Q 2445 218 2301 77+Q 2157 -64 1920 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-d7" d="M 1971 -64+Q 1331 -64 947 294+Q 563 653 563 1280+L 563 2240+Q 563 2867 947 3225+Q 1331 3584 1971 3584+Q 2579 3584 2953 3257+Q 3328 2931 3347 2368+L 2771 2368+Q 2752 2707 2541 2889+Q 2330 3072 1971 3072+Q 1594 3072 1366 2857+Q 1139 2643 1139 2246+L 1139 1280+Q 1139 883 1366 665+Q 1594 448 1971 448+Q 2330 448 2541 633+Q 2752 819 2771 1152+L 3347 1152+Q 3328 589 2953 262+Q 2579 -64 1971 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-122" d="M 1920 -51+Q 1286 -51 912 320+Q 538 691 538 1357+L 538 2163+Q 538 2835 909 3203+Q 1280 3571 1920 3571+Q 2560 3571 2931 3203+Q 3302 2835 3302 2163+L 3302 1357+Q 3302 691 2928 320+Q 2554 -51 1920 -51+z+M 1920 461+Q 2298 461 2512 672+Q 2726 883 2726 1293+L 2726 2227+Q 2726 2637 2512 2848+Q 2298 3059 1920 3059+Q 1549 3059 1331 2848+Q 1114 2637 1114 2227+L 1114 1293+Q 1114 883 1331 672+Q 1549 461 1920 461+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-11a" d="M 384 0+L 384 3520+L 883 3520+L 883 3053+L 896 3053+Q 928 3290 1085 3437+Q 1242 3584 1485 3584+Q 1715 3584 1875 3449+Q 2035 3315 2106 3085+L 2112 3085+Q 2157 3315 2313 3449+Q 2470 3584 2714 3584+Q 3053 3584 3254 3331+Q 3456 3078 3456 2675+L 3456 0+L 2918 0+L 2918 2682+Q 2918 2893 2816 3017+Q 2714 3142 2534 3142+Q 2362 3142 2259 3020+Q 2157 2899 2157 2688+L 2157 0+L 1683 0+L 1683 2682+Q 1683 2893 1580 3017+Q 1478 3142 1306 3142+Q 1126 3142 1024 3020+Q 922 2899 922 2688+L 922 0+L 384 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-33d" d="M 480 -704+L 2752 5312+L 3360 5312+L 1088 -704+L 480 -704+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-140" d="M 717 0+L 717 3520+L 1293 3520+L 1293 2848+L 1306 2848+Q 1350 3187 1593 3385+Q 1837 3584 2246 3584+Q 2797 3584 3094 3254+Q 3392 2925 3392 2317+L 3392 2016+L 2816 2016+L 2816 2317+Q 2816 3085 2067 3085+Q 1690 3085 1491 2867+Q 1293 2650 1293 2240+L 1293 0+L 717 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-bd" d="M 1613 -64+Q 1069 -64 749 240+Q 429 544 429 1037+Q 429 1363 576 1606+Q 723 1850 985 1987+Q 1248 2125 1587 2125+L 2675 2125+L 2675 2400+Q 2675 3085 1926 3085+Q 1594 3085 1389 2963+Q 1184 2842 1171 2624+L 595 2624+Q 627 3040 982 3312+Q 1338 3584 1926 3584+Q 2566 3584 2908 3277+Q 3251 2970 3251 2419+L 3251 0+L 2682 0+L 2682 640+L 2669 640+Q 2618 314 2342 125+Q 2067 -64 1613 -64+z+M 1754 422+Q 2176 422 2425 627+Q 2675 832 2675 1184+L 2675 1677+L 1651 1677+Q 1370 1677 1194 1507+Q 1018 1338 1018 1056+Q 1018 762 1213 592+Q 1408 422 1754 422+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-13d" d="M 589 -1152+L 589 3520+L 1165 3520+L 1165 2848+L 1171 2848+Q 1216 3194 1472 3389+Q 1728 3584 2125 3584+Q 2656 3584 2969 3235+Q 3283 2886 3283 2278+L 3283 1248+Q 3283 640 2969 288+Q 2656 -64 2125 -64+Q 1728 -64 1472 134+Q 1216 333 1171 672+L 1152 672+L 1165 -128+L 1165 -1152+L 589 -1152+z+M 1933 435+Q 2298 435 2502 627+Q 2707 819 2707 1248+L 2707 2272+Q 2707 2707 2502 2896+Q 2298 3085 1933 3085+Q 1581 3085 1373 2861+Q 1165 2637 1165 2240+L 1165 1280+Q 1165 883 1373 659+Q 1581 435 1933 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-113" d="M 2432 0+Q 1965 0 1686 272+Q 1408 544 1408 992+L 1408 4147+L 192 4147+L 192 4672+L 1984 4672+L 1984 992+Q 1984 774 2105 649+Q 2227 525 2432 525+L 3520 525+L 3520 0+L 2432 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-e1" d="M 1920 -64+Q 1299 -64 918 310+Q 538 685 538 1344+L 538 2176+Q 538 2835 918 3209+Q 1299 3584 1920 3584+Q 2336 3584 2646 3417+Q 2957 3251 3129 2950+Q 3302 2650 3302 2240+L 3302 1613+L 1101 1613+L 1101 1280+Q 1101 890 1325 662+Q 1549 435 1920 435+Q 2240 435 2448 560+Q 2656 685 2701 896+L 3277 896+Q 3219 454 2848 195+Q 2477 -64 1920 -64+z+M 1101 2061+L 2739 2061+L 2739 2240+Q 2739 2656 2524 2883+Q 2310 3110 1920 3110+Q 1530 3110 1315 2883+Q 1101 2656 1101 2240+L 1101 2061+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-357" d="M 896 1856+L 896 2368+L 2944 2368+L 2944 1856+L 896 1856+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-11b" d="M 589 0+L 589 3520+L 1165 3520+L 1165 2848+L 1171 2848+Q 1216 3200 1459 3392+Q 1702 3584 2106 3584+Q 2637 3584 2950 3257+Q 3264 2931 3264 2368+L 3264 0+L 2688 0+L 2688 2266+Q 2688 2669 2486 2883+Q 2285 3098 1939 3098+Q 1581 3098 1373 2874+Q 1165 2650 1165 2240+L 1165 0+L 589 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-dd" d="M 1715 -64+Q 1190 -64 873 288+Q 557 640 557 1242+L 557 2272+Q 557 2880 870 3232+Q 1184 3584 1715 3584+Q 2112 3584 2371 3385+Q 2630 3187 2682 2848+L 2688 2848+L 2675 3648+L 2675 4672+L 3251 4672+L 3251 0+L 2675 0+L 2675 672+L 2669 672+Q 2624 326 2368 131+Q 2112 -64 1715 -64+z+M 1907 435+Q 2266 435 2470 659+Q 2675 883 2675 1280+L 2675 2240+Q 2675 2637 2470 2861+Q 2266 3085 1907 3085+Q 1542 3085 1337 2896+Q 1133 2707 1133 2272+L 1133 1248+Q 1133 819 1337 627+Q 1542 435 1907 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-144" d="M 1779 -51+Q 1190 -51 867 214+Q 544 480 544 966+L 1120 966+Q 1120 723 1293 585+Q 1466 448 1779 448+L 2061 448+Q 2381 448 2557 589+Q 2733 730 2733 986+Q 2733 1440 2317 1498+L 1344 1638+Q 986 1690 787 1936+Q 589 2182 589 2586+Q 589 3046 905 3308+Q 1222 3571 1779 3571+L 2061 3571+Q 2573 3571 2896 3318+Q 3219 3066 3245 2656+L 2662 2656+Q 2650 2842 2486 2963+Q 2323 3085 2061 3085+L 1779 3085+Q 1485 3085 1318 2950+Q 1152 2816 1152 2586+Q 1152 2214 1491 2163+L 2400 2035+Q 3296 1907 3296 986+Q 3296 493 2973 221+Q 2650 -51 2061 -51+L 1779 -51+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-110" d="M 621 0+L 621 4672+L 1197 4672+L 1197 2067+L 1869 2067+L 2854 3520+L 3514 3520+L 2381 1843+L 3578 0+L 2906 0+L 1882 1568+L 1197 1568+L 1197 0+L 621 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-16a" d="M 774 0+L 198 3520+L 698 3520+L 1056 1037+Q 1075 896 1094 726+Q 1114 557 1120 448+Q 1133 557 1149 726+Q 1165 896 1190 1037+L 1632 3520+L 2208 3520+L 2650 1037+Q 2675 896 2697 726+Q 2720 557 2726 448+Q 2739 557 2758 726+Q 2778 896 2797 1037+L 3168 3520+L 3642 3520+L 3040 0+L 2406 0+L 2003 2432+Q 1978 2611 1955 2812+Q 1933 3014 1920 3123+Q 1914 3014 1888 2812+Q 1862 2611 1830 2432+L 1408 0+L 774 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#JetBrainsMono-Regular-f5"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(60 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-14c" transform="translate(120 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(180 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-151" transform="translate(240 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(300 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-329" transform="translate(360 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(420 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(480 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(540 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(600 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-f5" transform="translate(660 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(720 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(780 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(840 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(900 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(960 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(1020 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(1080 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(1140 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-357" transform="translate(1200 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(1260 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(1320 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(1380 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-f5" transform="translate(1440 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(1500 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(1560 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(1620 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(1680 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(1740 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(1800 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(1860 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(1920 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(1980 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2040 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(2100 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(2160 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2220 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2280 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(2340 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(2400 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(2460 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11b" transform="translate(2520 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2580 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-dd" transform="translate(2640 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(2700 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(2760 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-144" transform="translate(2820 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2880 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2940 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(3000 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11b" transform="translate(3060 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(3120 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(3180 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(3240 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(3300 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(3360 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-110" transform="translate(3420 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-144" transform="translate(3480 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(3540 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-16a" transform="translate(3600 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(3660 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(3720 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(3780 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(3840 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-357" transform="translate(3900 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(3960 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(4020 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(4080 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(4140 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-329" transform="translate(4200 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(4260 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-dd" transform="translate(4320 0)"/>+ </g>+ </g>+ <g id="text_12">+ <!-- Pack, standard layout -->+ <g style="fill: #c9ced8" transform="translate(48 348.198571) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-177" d="M 516 0+L 516 4656+L 2184 4656+Q 2722 4656 3081 4457+Q 3441 4259 3619 3917+Q 3797 3575 3797 3144+Q 3797 2713 3617 2370+Q 3438 2028 3078 1829+Q 2719 1631 2178 1631+L 1228 1631+L 1228 0+L 516 0+z+M 1228 2234+L 2109 2234+Q 2622 2234 2848 2492+Q 3075 2750 3075 3144+Q 3075 3538 2848 3792+Q 2622 4047 2103 4047+L 1228 4047+L 1228 2234+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2d7" d="M 463 0+L 463 4656+L 1150 4656+L 1150 2019+L 1213 2019+L 2591 3494+L 3416 3494+L 2009 1988+L 3513 0+L 2663 0+L 1484 1566+L 1150 1231+L 1150 0+L 463 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-5dd" d="M 390 -1160+L 665 668+L 1406 668+L 890 -1160+L 390 -1160+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-367" d="M 1716 -72+Q 1147 -72 773 173+Q 400 419 306 884+L 953 1019+Q 1094 484 1722 484+Q 2056 484 2251 623+Q 2447 763 2447 956+Q 2447 1288 1956 1397+L 1369 1531+Q 406 1747 406 2497+Q 406 2809 579 3043+Q 753 3278 1058 3408+Q 1363 3538 1759 3538+Q 2325 3538 2647 3295+Q 2969 3053 3081 2666+L 2466 2531+Q 2400 2716 2237 2855+Q 2075 2994 1766 2994+Q 1481 2994 1290 2866+Q 1100 2738 1100 2541+Q 1100 2366 1226 2258+Q 1353 2150 1641 2084+L 2203 1959+Q 3156 1744 3156 1016+Q 3156 697 2973 451+Q 2791 206 2466 67+Q 2141 -72 1716 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-305" d="M 1150 2069+L 1150 0+L 463 0+L 463 3494+L 1119 3494+L 1122 2822+Q 1284 3191 1557 3364+Q 1831 3538 2200 3538+Q 2734 3538 3061 3202+Q 3388 2866 3388 2219+L 3388 0+L 2700 0+L 2700 2134+Q 2700 2513 2503 2725+Q 2306 2938 1963 2938+Q 1613 2938 1381 2711+Q 1150 2484 1150 2069+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-255" d="M 1763 -69+Q 1338 -69 1008 147+Q 678 363 489 769+Q 300 1175 300 1738+Q 300 2306 490 2709+Q 681 3113 1011 3325+Q 1341 3538 1763 3538+Q 2088 3538 2288 3430+Q 2488 3322 2598 3176+Q 2709 3031 2769 2925+L 2806 2925+L 2806 4656+L 3494 4656+L 3494 0+L 2825 0+L 2825 547+L 2769 547+Q 2706 434 2592 290+Q 2478 147 2278 39+Q 2078 -69 1763 -69+z+M 1913 516+Q 2350 516 2584 856+Q 2819 1197 2819 1744+Q 2819 2288 2587 2620+Q 2356 2953 1913 2953+Q 1609 2953 1407 2793+Q 1206 2634 1104 2361+Q 1003 2088 1003 1744+Q 1003 1397 1106 1119+Q 1209 841 1412 678+Q 1616 516 1913 516+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-354" d="M 463 0+L 463 3494+L 1128 3494+L 1128 2931+L 1166 2931+Q 1259 3216 1501 3380+Q 1744 3544 2050 3544+Q 2116 3544 2202 3537+Q 2288 3531 2341 3525+L 2341 2869+Q 2303 2878 2197 2892+Q 2091 2906 1981 2906+Q 1622 2906 1386 2686+Q 1150 2466 1150 2122+L 1150 0+L 463 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2e0" d="M 1150 4656+L 1150 0+L 463 0+L 463 4656+L 1150 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-3e6" d="M 416 -1256+L 584 -697+L 663 -716+Q 928 -788 1114 -698+Q 1300 -609 1397 -272+L 1472 -16+L 144 3494+L 888 3494+L 1578 1509+Q 1656 1278 1715 1053+Q 1775 828 1831 603+Q 1891 828 1953 1054+Q 2016 1281 2097 1509+L 2800 3494+L 3538 3494+L 2019 -484+Q 1859 -903 1589 -1117+Q 1319 -1331 897 -1331+Q 734 -1331 607 -1307+Q 481 -1284 416 -1256+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-367" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(343.9375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(378.453125 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(435.234375 0)"/>+ <use xlink:href="#Inter-Medium-255" transform="translate(495.390625 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(557.203125 0)"/>+ <use xlink:href="#Inter-Medium-354" transform="translate(613.984375 0)"/>+ <use xlink:href="#Inter-Medium-255" transform="translate(650.75 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(712.5625 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(739.21875 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(764.421875 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(819.640625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(875.25 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(935.65625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(995.8125 0)"/>+ </g>+ </g>+ <g id="text_13">+ <!-- Pack, cache layout, 50% -->+ <g style="fill: #c9ced8" transform="translate(48 414.055714) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-543" d="M 1897 -63+Q 1463 -63 1122 103+Q 781 269 579 559+Q 378 850 363 1219+L 1056 1219+Q 1081 919 1322 728+Q 1563 538 1897 538+Q 2294 538 2551 806+Q 2809 1075 2809 1494+Q 2809 1775 2687 1997+Q 2566 2219 2353 2345+Q 2141 2472 1866 2472+Q 1653 2472 1440 2398+Q 1228 2325 1100 2209+L 444 2303+L 703 4656+L 3275 4656+L 3275 4047+L 1300 4047+L 1153 2747+L 1178 2747+Q 1316 2884 1542 2970+Q 1769 3056 2031 3056+Q 2456 3056 2789 2856+Q 3122 2656 3314 2306+Q 3506 1956 3506 1506+Q 3506 1053 3300 698+Q 3094 344 2730 140+Q 2366 -63 1897 -63+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-53d" d="M 2066 -63+Q 1253 -63 803 562+Q 353 1188 353 2325+Q 353 3456 804 4087+Q 1256 4719 2066 4719+Q 2875 4719 3326 4087+Q 3778 3456 3778 2325+Q 3778 1191 3329 564+Q 2881 -63 2066 -63+z+M 2066 547+Q 2550 547 2811 1012+Q 3072 1478 3072 2325+Q 3072 3175 2811 3644+Q 2550 4113 2066 4113+Q 1581 4113 1318 3642+Q 1056 3172 1056 2325+Q 1056 1478 1318 1012+Q 1581 547 2066 547+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-6d0" d="M 1622 2544+Q 1313 2544 1102 2676+Q 891 2809 781 3031+Q 672 3253 672 3516+L 672 3759+Q 672 4025 783 4245+Q 894 4466 1106 4598+Q 1319 4731 1622 4731+Q 1931 4731 2142 4598+Q 2353 4466 2459 4244+Q 2566 4022 2566 3759+L 2566 3516+Q 2566 3250 2458 3029+Q 2350 2809 2139 2676+Q 1928 2544 1622 2544+z+M 4738 -88+Q 4428 -88 4217 45+Q 4006 178 3898 400+Q 3791 622 3791 884+L 3791 1128+Q 3791 1394 3902 1614+Q 4013 1834 4223 1967+Q 4434 2100 4738 2100+Q 5050 2100 5259 1967+Q 5469 1834 5576 1612+Q 5684 1391 5684 1128+L 5684 884+Q 5684 622 5575 400+Q 5466 178 5255 45+Q 5044 -88 4738 -88+z+M 1278 0+L 4478 4656+L 5047 4656+L 1847 0+L 1278 0+z+M 4738 375+Q 4966 375 5056 533+Q 5147 691 5147 884+L 5147 1128+Q 5147 1322 5059 1481+Q 4972 1641 4738 1641+Q 4513 1641 4419 1481+Q 4325 1322 4325 1128+L 4325 884+Q 4325 691 4417 533+Q 4509 375 4738 375+z+M 1622 3006+Q 1850 3006 1940 3162+Q 2031 3319 2031 3516+L 2031 3759+Q 2031 3953 1943 4112+Q 1856 4272 1622 4272+Q 1397 4272 1303 4112+Q 1209 3953 1209 3759+L 1209 3516+Q 1209 3319 1300 3162+Q 1391 3006 1622 3006+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-543" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1015.703125 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1080.25 0)"/>+ </g>+ </g>+ <g id="text_14">+ <!-- Pack, cache layout, 70% -->+ <g style="fill: #c9ced8" transform="translate(48 479.912857) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-546" d="M 600 0+L 2625 4009+L 2625 4047+L 281 4047+L 281 4656+L 3372 4656+L 3372 4022+L 1347 0+L 600 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-546" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1010.96875 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1075.515625 0)"/>+ </g>+ </g>+ <g id="text_15">+ <!-- Pack, cache layout, 90% -->+ <g style="fill: #c9ced8" transform="translate(48 545.77) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-548" d="M 1919 -66+Q 1503 -66 1178 100+Q 853 266 648 556+Q 444 847 394 1222+L 1100 1222+Q 1166 931 1373 745+Q 1581 559 1919 559+Q 2428 559 2712 1003+Q 2997 1447 2997 2241+L 2963 2241+Q 2784 1950 2481 1779+Q 2178 1609 1809 1609+Q 1403 1609 1072 1806+Q 741 2003 547 2348+Q 353 2694 353 3138+Q 353 3584 556 3945+Q 759 4306 1126 4517+Q 1494 4728 1984 4722+Q 2294 4716 2594 4606+Q 2894 4497 3141 4242+Q 3388 3988 3534 3559+Q 3681 3131 3681 2488+Q 3681 1678 3465 1108+Q 3250 538 2854 236+Q 2459 -66 1919 -66+z+M 1963 2188+Q 2228 2188 2442 2323+Q 2656 2459 2782 2679+Q 2909 2900 2909 3159+Q 2909 3413 2787 3631+Q 2666 3850 2456 3984+Q 2247 4119 1978 4119+Q 1716 4119 1505 3989+Q 1294 3859 1172 3639+Q 1050 3419 1050 3150+Q 1050 2878 1167 2661+Q 1284 2444 1492 2316+Q 1700 2188 1963 2188+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-548" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1018.390625 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1082.9375 0)"/>+ </g>+ </g>+ <g id="text_16">+ <!-- Pack, cache layout, 95% -->+ <g style="fill: #c9ced8" transform="translate(48 611.627143) scale(0.2 -0.2)">+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-548" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-543" transform="translate(1018.390625 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1078.6875 0)"/>+ </g>+ </g>+ <g id="text_17">+ <!-- Pack, stable layout -->+ <g style="fill: #c9ced8" transform="translate(48 677.484286) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-242" d="M 2197 -69+Q 1878 -69 1678 39+Q 1478 147 1364 290+Q 1250 434 1188 547+L 1131 547+L 1131 0+L 463 0+L 463 4656+L 1150 4656+L 1150 2925+L 1188 2925+Q 1247 3031 1358 3176+Q 1469 3322 1669 3430+Q 1869 3538 2197 3538+Q 2616 3538 2945 3325+Q 3275 3113 3465 2709+Q 3656 2306 3656 1738+Q 3656 1175 3468 769+Q 3281 363 2951 147+Q 2622 -69 2197 -69+z+M 2044 516+Q 2344 516 2545 678+Q 2747 841 2850 1119+Q 2953 1397 2953 1744+Q 2953 2088 2851 2361+Q 2750 2634 2548 2793+Q 2347 2953 2044 2953+Q 1600 2953 1369 2620+Q 1138 2288 1138 1744+Q 1138 1197 1372 856+Q 1606 516 2044 516+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-367" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(343.9375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(378.453125 0)"/>+ <use xlink:href="#Inter-Medium-242" transform="translate(435.234375 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(497.046875 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(522.25 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(580.984375 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(607.640625 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(632.84375 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(688.0625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(743.671875 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(804.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(864.234375 0)"/>+ </g>+ </g>+ <g id="text_18">+ <!-- Truncation -->+ <g style="fill: #c9ced8" transform="translate(48 743.341429) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-19b" d="M 281 4044+L 281 4656+L 3897 4656+L 3897 4044+L 2450 4044+L 2450 0+L 1734 0+L 1734 4044+L 281 4044+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-19b"/>+ <use xlink:href="#Inter-Medium-354" transform="translate(59.625 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(98.296875 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(158.453125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(218.609375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(277.3125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(334.09375 0)"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(368.125 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(393.328125 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(453.734375 0)"/>+ </g>+ </g>+ <g id="text_19">+ <!-- Muse Spark 1.3 -->+ <g style="fill: #f4f6fa" transform="translate(308.46875 260) scale(0.26 -0.26)">+ <defs>+ <path id="Inter-SemiBold-124" d="M 469 0+L 469 4656+L 1725 4656+L 2609 2253+Q 2656 2116 2717 1895+Q 2778 1675 2840 1423+Q 2903 1172 2956 941+Q 3009 1169 3071 1420+Q 3134 1672 3195 1892+Q 3256 2113 3300 2253+L 4175 4656+L 5434 4656+L 5434 0+L 4603 0+L 4603 2350+Q 4603 2525 4608 2783+Q 4613 3041 4620 3331+Q 4628 3622 4631 3900+Q 4553 3600 4465 3303+Q 4378 3006 4300 2756+Q 4222 2506 4166 2350+L 3306 0+L 2597 0+L 1725 2350+Q 1669 2500 1592 2744+Q 1516 2988 1430 3281+Q 1344 3575 1256 3875+Q 1263 3613 1270 3327+Q 1278 3041 1283 2784+Q 1288 2528 1288 2350+L 1288 0+L 469 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-393" d="M 1628 -44+Q 1088 -44 759 300+Q 431 644 431 1272+L 431 3494+L 1244 3494+L 1244 1397+Q 1244 1047 1426 847+Q 1609 647 1928 647+Q 2253 647 2462 856+Q 2672 1066 2672 1447+L 2672 3494+L 3488 3494+L 3488 0+L 2716 0+L 2709 700+Q 2397 -44 1628 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-367" d="M 1753 -72+Q 1150 -72 758 186+Q 366 444 275 919+L 1034 1063+Q 1172 550 1769 550+Q 2069 550 2245 670+Q 2422 791 2422 969+Q 2422 1266 1950 1369+L 1353 1497+Q 372 1709 372 2475+Q 372 2800 550 3037+Q 728 3275 1045 3406+Q 1363 3538 1781 3538+Q 2375 3538 2720 3291+Q 3066 3044 3172 2638+L 2447 2494+Q 2384 2675 2228 2803+Q 2072 2931 1791 2931+Q 1534 2931 1359 2817+Q 1184 2703 1184 2525+Q 1184 2372 1298 2273+Q 1413 2175 1681 2116+L 2275 1991+Q 3253 1781 3253 1047+Q 3253 716 3062 464+Q 2872 213 2533 70+Q 2194 -72 1753 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-266" d="M 1975 -72+Q 1447 -72 1067 150+Q 688 372 483 775+Q 278 1178 278 1725+Q 278 2263 479 2670+Q 681 3078 1051 3308+Q 1422 3538 1922 3538+Q 2347 3538 2711 3352+Q 3075 3166 3297 2777+Q 3519 2388 3519 1775+L 3519 1519+L 1088 1519+Q 1103 1053 1348 809+Q 1594 566 1984 566+Q 2253 566 2445 681+Q 2638 797 2719 1019+L 3466 866+Q 3341 444 2948 186+Q 2556 -72 1975 -72+z+M 1091 2072+L 2728 2072+Q 2691 2447 2489 2673+Q 2288 2900 1925 2900+Q 1553 2900 1336 2661+Q 1119 2422 1091 2072+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-6f1" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-18d" d="M 2103 -72+Q 1291 -72 808 303+Q 325 678 297 1369+L 1119 1369+Q 1147 1000 1425 820+Q 1703 641 2097 641+Q 2509 641 2770 827+Q 3031 1013 3031 1313+Q 3031 1584 2800 1723+Q 2569 1863 2191 1959+L 1663 2097+Q 1078 2247 751 2550+Q 425 2853 425 3347+Q 425 3759 647 4067+Q 869 4375 1253 4547+Q 1638 4719 2125 4719+Q 2622 4719 2995 4547+Q 3369 4375 3581 4072+Q 3794 3769 3803 3381+L 2994 3381+Q 2963 3678 2727 3843+Q 2491 4009 2113 4009+Q 1719 4009 1494 3836+Q 1269 3663 1269 3397+Q 1269 3200 1389 3076+Q 1509 2953 1692 2878+Q 1875 2803 2063 2756+L 2497 2644+Q 2841 2559 3155 2401+Q 3469 2244 3667 1978+Q 3866 1713 3866 1306+Q 3866 897 3656 586+Q 3447 275 3053 101+Q 2659 -72 2103 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-34b" d="M 431 -1306+L 431 3494+L 1225 3494+L 1225 2916+L 1278 2916+Q 1338 3038 1453 3183+Q 1569 3328 1769 3433+Q 1969 3538 2278 3538+Q 2681 3538 3007 3331+Q 3334 3125 3526 2723+Q 3719 2322 3719 1741+Q 3719 1166 3530 762+Q 3341 359 3016 148+Q 2691 -63 2275 -63+Q 1975 -63 1776 39+Q 1578 141 1459 284+Q 1341 428 1278 553+L 1244 553+L 1244 -1306+L 431 -1306+z+M 2056 606+Q 2463 606 2673 929+Q 2884 1253 2884 1744+Q 2884 2231 2676 2550+Q 2469 2869 2056 2869+Q 1653 2869 1440 2561+Q 1228 2253 1228 1744+Q 1228 1234 1443 920+Q 1659 606 2056 606+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-1fb" d="M 1406 -72+Q 1075 -72 809 48+Q 544 169 391 403+Q 238 638 238 981+Q 238 1375 430 1592+Q 622 1809 926 1907+Q 1231 2006 1569 2041+Q 2025 2091 2228 2133+Q 2431 2175 2431 2356+L 2431 2372+Q 2431 2628 2275 2770+Q 2119 2913 1822 2913+Q 1516 2913 1334 2778+Q 1153 2644 1091 2472+L 338 2625+Q 491 3088 892 3313+Q 1294 3538 1819 3538+Q 2066 3538 2317 3480+Q 2569 3422 2778 3286+Q 2988 3150 3116 2917+Q 3244 2684 3244 2334+L 3244 0+L 2466 0+L 2466 481+L 2434 481+Q 2319 256 2066 92+Q 1813 -72 1406 -72+z+M 1616 531+Q 1991 531 2214 747+Q 2438 963 2438 1253+L 2438 1666+Q 2381 1622 2237 1589+Q 2094 1556 1933 1532+Q 1772 1509 1666 1494+Q 1391 1456 1208 1343+Q 1025 1231 1025 991+Q 1025 766 1190 648+Q 1356 531 1616 531+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-354" d="M 431 0+L 431 3494+L 1219 3494+L 1219 2909+L 1256 2909+Q 1350 3213 1584 3377+Q 1819 3541 2119 3541+Q 2275 3541 2416 3519+L 2416 2772+Q 2366 2784 2253 2798+Q 2141 2813 2031 2813+Q 1691 2813 1467 2602+Q 1244 2391 1244 2056+L 1244 0+L 431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-2d7" d="M 431 0+L 431 4656+L 1244 4656+L 1244 2084+L 1303 2084+L 2563 3494+L 3516 3494+L 2163 1984+L 3597 0+L 2622 0+L 1544 1497+L 1244 1175+L 1244 0+L 431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-53e" d="M 2241 4656+L 2241 0+L 1413 0+L 1413 3913+L 1381 3913+L 294 3131+L 294 3925+L 1316 4656+L 2241 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-5de" d="M 1019 -53+Q 809 -53 664 90+Q 519 234 519 447+Q 519 656 664 800+Q 809 944 1019 944+Q 1231 944 1376 800+Q 1522 656 1522 447+Q 1522 234 1376 90+Q 1231 -53 1019 -53+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-541" d="M 2034 -63+Q 1544 -63 1164 104+Q 784 272 565 572+Q 347 872 334 1263+L 1175 1263+Q 1194 975 1437 806+Q 1681 638 2034 638+Q 2409 638 2650 831+Q 2891 1025 2891 1334+Q 2891 1653 2642 1854+Q 2394 2056 1950 2056+L 1538 2056+L 1538 2700+L 1950 2700+Q 2313 2700 2541 2887+Q 2769 3075 2769 3381+Q 2769 3678 2570 3858+Q 2372 4038 2044 4038+Q 1722 4038 1483 3869+Q 1244 3700 1234 3403+L 431 3403+Q 438 3791 655 4087+Q 872 4384 1236 4551+Q 1600 4719 2050 4719+Q 2516 4719 2859 4544+Q 3203 4369 3392 4076+Q 3581 3784 3581 3431+Q 3581 3038 3350 2772+Q 3119 2506 2741 2422+L 2741 2384+Q 3228 2316 3489 2022+Q 3750 1728 3750 1291+Q 3750 900 3528 594+Q 3306 288 2918 112+Q 2531 -63 2034 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-124"/>+ <use xlink:href="#Inter-SemiBold-393" transform="translate(92.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-367" transform="translate(153.46875 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(208.40625 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(267.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-18d" transform="translate(292.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-34b" transform="translate(357.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-1fb" transform="translate(421.171875 0)"/>+ <use xlink:href="#Inter-SemiBold-354" transform="translate(478.59375 0)"/>+ <use xlink:href="#Inter-SemiBold-2d7" transform="translate(519.859375 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(576.796875 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(602 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(644.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(673.734375 0)"/>+ </g>+ </g>+ <g id="text_20">+ <!-- $1.25 per million input tokens, $0.15 cached -->+ <g style="fill: #8a93a6" transform="translate(308.46875 286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-51d" d="M 1866 -681+L 1866 -75+Q 1191 -28 795 320+Q 400 669 363 1219+L 972 1219+Q 1003 869 1259 683+Q 1516 497 1866 459+L 1866 2141+L 1681 2194+Q 1119 2353 806 2650+Q 494 2947 494 3409+Q 494 3769 673 4047+Q 853 4325 1162 4495+Q 1472 4666 1866 4706+L 1866 5338+L 2241 5338+L 2241 4716+Q 2659 4688 2979 4520+Q 3300 4353 3484 4083+Q 3669 3813 3681 3481+L 3100 3481+Q 3066 3788 2830 3969+Q 2594 4150 2241 4184+L 2241 2606+L 2425 2556+Q 2613 2506 2839 2418+Q 3066 2331 3272 2186+Q 3478 2041 3611 1817+Q 3744 1594 3744 1269+Q 3744 909 3567 617+Q 3391 325 3055 140+Q 2719 -44 2241 -75+L 2241 -681+L 1866 -681+z+M 2241 459+Q 2644 503 2905 723+Q 3166 944 3166 1278+Q 3166 1503 3039 1643+Q 2913 1784 2703 1875+Q 2494 1966 2244 2034+L 2241 2034+L 2241 459+z+M 1866 2713+L 1866 4181+Q 1503 4131 1287 3928+Q 1072 3725 1072 3438+Q 1072 3216 1200 3073+Q 1328 2931 1512 2845+Q 1697 2759 1866 2713+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-543" d="M 1863 -63+Q 1453 -63 1128 98+Q 803 259 609 539+Q 416 819 400 1175+L 975 1175+Q 1003 863 1258 661+Q 1513 459 1863 459+Q 2144 459 2364 590+Q 2584 722 2709 953+Q 2834 1184 2834 1478+Q 2834 1778 2703 2015+Q 2572 2253 2345 2389+Q 2119 2525 1825 2525+Q 1609 2525 1387 2456+Q 1166 2388 1028 2281+L 472 2350+L 747 4656+L 3197 4656+L 3197 4134+L 1247 4134+L 1088 2775+L 1113 2775+Q 1256 2894 1475 2970+Q 1694 3047 1934 3047+Q 2363 3047 2697 2845+Q 3031 2644 3223 2291+Q 3416 1938 3416 1488+Q 3416 1041 3214 691+Q 3013 341 2663 139+Q 2313 -63 1863 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-51d"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(104.828125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(133.640625 0)"/>+ <use xlink:href="#Inter-Regular-543" transform="translate(194.625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(253.953125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(282.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(343.3125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(401.609375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(439.25 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(467.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(554.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(579.1875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(603.40625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(627.625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(651.84375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(711.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(770.890625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(799.015625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(823.234375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(882.3125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(943.546875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1002.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1035.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1063.515625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1095.265625 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1155.234375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1207.875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1266.171875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1325.25 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1378.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1406.84375 0)"/>+ <use xlink:href="#Inter-Regular-51d" transform="translate(1434.96875 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1499.125 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1559.6875 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(1579.859375 0)"/>+ <use xlink:href="#Inter-Regular-543" transform="translate(1620.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1679.859375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1707.984375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1766.09375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1822.25 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1879.375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1938.5 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1996.796875 0)"/>+ </g>+ </g>+ <g id="text_21">+ <!-- $1.27 -->+ <g style="fill: #f4f6fa" transform="translate(480.136904 334.507286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-51d" d="M 1913 -644+L 1913 -66+Q 1184 -22 753 348+Q 322 719 297 1369+L 1119 1369+Q 1144 1044 1366 866+Q 1588 688 1913 650+L 1913 2031+L 1663 2097+Q 1078 2247 751 2550+Q 425 2853 425 3347+Q 425 3728 617 4022+Q 809 4316 1145 4494+Q 1481 4672 1913 4709+L 1913 5300+L 2288 5300+L 2288 4713+Q 2741 4684 3077 4506+Q 3413 4328 3603 4037+Q 3794 3747 3803 3381+L 2994 3381+Q 2966 3644 2778 3803+Q 2591 3963 2288 4000+L 2288 2697+L 2497 2644+Q 2841 2559 3155 2401+Q 3469 2244 3667 1978+Q 3866 1713 3866 1306+Q 3866 728 3452 353+Q 3038 -22 2288 -66+L 2288 -644+L 1913 -644+z+M 2288 653+Q 2622 694 2826 872+Q 3031 1050 3031 1313+Q 3031 1569 2828 1705+Q 2625 1841 2288 1931+L 2288 653+z+M 1913 2794+L 1913 3997+Q 1609 3953 1439 3790+Q 1269 3628 1269 3397+Q 1269 3141 1467 3005+Q 1666 2869 1913 2794+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-53f" d="M 419 0+L 419 600+L 2034 2191+Q 2375 2538 2553 2784+Q 2731 3031 2731 3328+Q 2731 3656 2511 3847+Q 2291 4038 1959 4038+Q 1609 4038 1400 3830+Q 1191 3622 1191 3263+L 394 3263+Q 394 3703 595 4031+Q 797 4359 1153 4539+Q 1509 4719 1969 4719+Q 2434 4719 2787 4544+Q 3141 4369 3337 4064+Q 3534 3759 3534 3369+Q 3534 3113 3436 2863+Q 3338 2613 3088 2303+Q 2838 1994 2384 1556+L 1575 731+L 1575 697+L 3603 697+L 3603 0+L 419 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-546" d="M 578 0+L 2559 3925+L 2559 3956+L 259 3956+L 259 4656+L 3428 4656+L 3428 3938+L 1447 0+L 578 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_22">+ <!-- $1.27 -->+ <g style="fill: #f4f6fa" transform="translate(480.136904 360.435857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_23">+ <!-- $1.17 -->+ <g style="fill: #f4f6fa" transform="translate(467.461289 400.364429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(130.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(172.609375 0)"/>+ </g>+ </g>+ <g id="text_24">+ <!-- $0.610 -->+ <g style="fill: #f4f6fa" transform="translate(396.332132 426.293) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-53d" d="M 2113 -63+Q 1263 -63 792 564+Q 322 1191 322 2325+Q 322 3456 794 4087+Q 1266 4719 2113 4719+Q 2956 4719 3428 4087+Q 3900 3456 3900 2325+Q 3900 1191 3429 564+Q 2959 -63 2113 -63+z+M 2113 638+Q 2569 638 2814 1078+Q 3059 1519 3059 2325+Q 3059 3134 2814 3578+Q 2569 4022 2113 4022+Q 1656 4022 1409 3576+Q 1163 3131 1163 2325+Q 1163 1519 1408 1078+Q 1653 638 2113 638+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-545" d="M 2097 -63+Q 1763 -63 1447 51+Q 1131 166 876 425+Q 622 684 472 1118+Q 322 1553 322 2194+Q 322 2991 545 3555+Q 769 4119 1178 4419+Q 1588 4719 2147 4719+Q 2581 4719 2918 4547+Q 3256 4375 3467 4078+Q 3678 3781 3728 3403+L 2909 3403+Q 2844 3669 2647 3833+Q 2450 3997 2147 3997+Q 1659 3997 1396 3575+Q 1134 3153 1134 2413+L 1169 2413+Q 1338 2716 1645 2886+Q 1953 3056 2328 3056+Q 2738 3056 3064 2861+Q 3391 2666 3581 2322+Q 3772 1978 3772 1538+Q 3772 1078 3562 717+Q 3353 356 2976 146+Q 2600 -63 2097 -63+z+M 2094 616+Q 2341 616 2537 736+Q 2734 856 2848 1061+Q 2963 1266 2963 1522+Q 2963 1772 2852 1975+Q 2741 2178 2545 2297+Q 2350 2416 2103 2416+Q 1856 2416 1657 2292+Q 1459 2169 1343 1964+Q 1228 1759 1228 1519+Q 1228 1272 1340 1067+Q 1453 863 1648 739+Q 1844 616 2094 616+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(157.34375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(221.3125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(263.59375 0)"/>+ </g>+ </g>+ <g id="text_25">+ <!-- $1.21 -->+ <g style="fill: #f4f6fa" transform="translate(473.349926 466.221571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_26">+ <!-- $0.433 -->+ <g style="fill: #f4f6fa" transform="translate(373.766411 492.150143) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-542" d="M 334 866+L 334 1531+L 2313 4656+L 3350 4656+L 3350 1553+L 3950 1553+L 3950 866+L 3350 866+L 3350 0+L 2550 0+L 2550 866+L 334 866+z+M 2566 1553+L 2566 3706+L 2528 3706+L 1188 1591+L 1188 1553+L 2566 1553+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(226.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(290.359375 0)"/>+ </g>+ </g>+ <g id="text_27">+ <!-- $1.26 -->+ <g style="fill: #f4f6fa" transform="translate(478.639568 532.078714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_28">+ <!-- $0.252 -->+ <g style="fill: #f4f6fa" transform="translate(350.60338 558.007286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-543" d="M 1931 -63+Q 1475 -63 1117 109+Q 759 281 550 579+Q 341 878 328 1263+L 1141 1263+Q 1156 975 1384 795+Q 1613 616 1931 616+Q 2303 616 2545 866+Q 2788 1116 2788 1509+Q 2788 1906 2539 2164+Q 2291 2422 1906 2422+Q 1694 2422 1492 2342+Q 1291 2263 1172 2134+L 416 2256+L 659 4656+L 3353 4656+L 3353 3956+L 1350 3956+L 1219 2719+L 1244 2719+Q 1375 2872 1611 2970+Q 1847 3069 2128 3069+Q 2550 3069 2883 2870+Q 3216 2672 3406 2323+Q 3597 1975 3597 1528+Q 3597 1066 3384 706+Q 3172 347 2797 142+Q 2422 -63 1931 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(283.671875 0)"/>+ </g>+ </g>+ <g id="text_29">+ <!-- $1.26 -->+ <g style="fill: #f4f6fa" transform="translate(479.65276 597.935857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_30">+ <!-- $0.204 -->+ <g style="fill: #f4f6fa" transform="translate(344.50214 623.864429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(288.40625 0)"/>+ </g>+ </g>+ <g id="text_31">+ <!-- $1.27 -->+ <g style="fill: #f4f6fa" transform="translate(480.258087 663.793) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_32">+ <!-- $0.153 -->+ <g style="fill: #f4f6fa" transform="translate(337.993036 689.721571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(151.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(193.515625 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(254.75 0)"/>+ </g>+ </g>+ <g id="text_33">+ <!-- $1.27 -->+ <g style="fill: #f4f6fa" transform="translate(480.583008 729.650143) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_34">+ <!-- $0.153 -->+ <g style="fill: #f4f6fa" transform="translate(338.032027 755.578714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(151.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(193.515625 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(254.75 0)"/>+ </g>+ </g>+ <g id="text_35">+ <!-- Muse Wonder -->+ <g style="fill: #f4f6fa" transform="translate(950.234375 260) scale(0.26 -0.26)">+ <defs>+ <path id="Inter-SemiBold-1cb" d="M 1413 0+L 156 4656+L 1053 4656+L 1659 2178+Q 1731 1863 1793 1511+Q 1856 1159 1916 813+Q 1978 1159 2045 1511+Q 2113 1863 2191 2178+L 2822 4656+L 3706 4656+L 4334 2178+Q 4413 1866 4480 1519+Q 4547 1172 4609 828+Q 4669 1172 4733 1519+Q 4797 1866 4869 2178+L 5472 4656+L 6372 4656+L 5113 0+L 4156 0+L 3478 2572+Q 3416 2816 3362 3091+Q 3309 3366 3259 3666+Q 3213 3375 3164 3103+Q 3116 2831 3047 2572+L 2369 0+L 1413 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-316" d="M 1947 -72+Q 1438 -72 1063 154+Q 688 381 483 786+Q 278 1191 278 1728+Q 278 2272 483 2680+Q 688 3088 1063 3313+Q 1438 3538 1947 3538+Q 2456 3538 2831 3313+Q 3206 3088 3412 2680+Q 3619 2272 3619 1728+Q 3619 1191 3412 786+Q 3206 381 2831 154+Q 2456 -72 1947 -72+z+M 1947 588+Q 2231 588 2418 741+Q 2606 894 2700 1153+Q 2794 1413 2794 1731+Q 2794 2053 2700 2312+Q 2606 2572 2418 2725+Q 2231 2878 1947 2878+Q 1666 2878 1478 2725+Q 1291 2572 1198 2312+Q 1106 2053 1106 1731+Q 1106 1413 1198 1153+Q 1291 894 1478 741+Q 1666 588 1947 588+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-305" d="M 1244 2047+L 1244 0+L 431 0+L 431 3494+L 1200 3494+L 1209 2797+Q 1522 3538 2291 3538+Q 2831 3538 3157 3194+Q 3484 2850 3484 2222+L 3484 0+L 2672 0+L 2672 2097+Q 2672 2447 2490 2647+Q 2309 2847 1991 2847+Q 1666 2847 1455 2637+Q 1244 2428 1244 2047+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-255" d="M 1719 -63+Q 1306 -63 979 148+Q 653 359 465 762+Q 278 1166 278 1741+Q 278 2322 468 2723+Q 659 3125 986 3331+Q 1313 3538 1716 3538+Q 2028 3538 2226 3433+Q 2425 3328 2540 3183+Q 2656 3038 2719 2916+L 2753 2916+L 2753 4656+L 3566 4656+L 3566 0+L 2769 0+L 2769 553+L 2719 553+Q 2653 428 2534 284+Q 2416 141 2217 39+Q 2019 -63 1719 -63+z+M 1941 606+Q 2338 606 2553 920+Q 2769 1234 2769 1744+Q 2769 2253 2555 2561+Q 2341 2869 1941 2869+Q 1528 2869 1318 2550+Q 1109 2231 1109 1744+Q 1109 1253 1320 929+Q 1531 606 1941 606+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-124"/>+ <use xlink:href="#Inter-SemiBold-393" transform="translate(92.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-367" transform="translate(153.46875 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(208.40625 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(267.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-1cb" transform="translate(292.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-316" transform="translate(389.703125 0)"/>+ <use xlink:href="#Inter-SemiBold-305" transform="translate(450.59375 0)"/>+ <use xlink:href="#Inter-SemiBold-255" transform="translate(511.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(574.1875 0)"/>+ <use xlink:href="#Inter-SemiBold-354" transform="translate(633.3125 0)"/>+ </g>+ </g>+ <g id="text_36">+ <!-- $4.00 per million input tokens, $0.20 cached -->+ <g style="fill: #8a93a6" transform="translate(950.234375 286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-542" d="M 375 947+L 375 1431+L 2413 4656+L 3134 4656+L 3134 1469+L 3766 1469+L 3766 947+L 3134 947+L 3134 0+L 2566 0+L 2566 947+L 375 947+z+M 2569 1469+L 2569 3913+L 2531 3913+L 1009 1506+L 1009 1469+L 2569 1469+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-51d"/>+ <use xlink:href="#Inter-Regular-542" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(125.375 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(151.65625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(214.75 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(277.84375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(305.96875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(367.203125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(425.5 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(463.140625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(491.265625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(578.859375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(603.078125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(627.296875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(651.515625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(675.734375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(735.703125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(794.78125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(822.90625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(847.125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(906.203125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(967.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1026.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1059.28125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1087.40625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1119.15625 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1179.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1231.765625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1290.0625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1349.140625 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1401.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1430.734375 0)"/>+ <use xlink:href="#Inter-Regular-51d" transform="translate(1458.859375 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1523.015625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1583.578125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(1612.390625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1673.375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1736.46875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1764.59375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1822.703125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1878.859375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1935.984375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1995.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(2053.40625 0)"/>+ </g>+ </g>+ <g id="text_37">+ <!-- $4.06 -->+ <g style="fill: #f4f6fa" transform="translate(1477.572467 334.507286) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_38">+ <!-- $4.06 -->+ <g style="fill: #f4f6fa" transform="translate(1477.572467 360.435857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_39">+ <!-- $3.74 -->+ <g style="fill: #f4f6fa" transform="translate(1437.010501 400.364429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(126.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(156.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(208.09375 0)"/>+ </g>+ </g>+ <g id="text_40">+ <!-- $1.81 -->+ <g style="fill: #f4f6fa" transform="translate(1191.291593 426.293) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-547" d="M 2047 -63+Q 1541 -63 1152 106+Q 763 275 542 572+Q 322 869 322 1247+Q 322 1538 450 1784+Q 578 2031 798 2197+Q 1019 2363 1294 2409+L 1294 2438+Q 934 2519 712 2806+Q 491 3094 491 3472+Q 491 3831 692 4112+Q 894 4394 1245 4556+Q 1597 4719 2047 4719+Q 2494 4719 2845 4556+Q 3197 4394 3400 4112+Q 3603 3831 3603 3472+Q 3603 3094 3379 2806+Q 3156 2519 2803 2438+L 2803 2409+Q 3072 2363 3292 2197+Q 3513 2031 3644 1784+Q 3775 1538 3775 1247+Q 3775 869 3553 572+Q 3331 275 2940 106+Q 2550 -63 2047 -63+z+M 2047 581+Q 2441 581 2677 781+Q 2913 981 2913 1306+Q 2913 1641 2666 1856+Q 2419 2072 2047 2072+Q 1669 2072 1423 1856+Q 1178 1641 1178 1306+Q 1178 981 1414 781+Q 1650 581 2047 581+z+M 2047 2703+Q 2369 2703 2578 2893+Q 2788 3084 2788 3391+Q 2788 3694 2581 3878+Q 2375 4063 2047 4063+Q 1716 4063 1511 3878+Q 1306 3694 1306 3391+Q 1306 3088 1514 2895+Q 1722 2703 2047 2703+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(136.578125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(200.59375 0)"/>+ </g>+ </g>+ <g id="text_41">+ <!-- $3.88 -->+ <g style="fill: #f4f6fa" transform="translate(1455.854138 466.221571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(126.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(155.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(219.796875 0)"/>+ </g>+ </g>+ <g id="text_42">+ <!-- $1.19 -->+ <g style="fill: #f4f6fa" transform="translate(1111.838358 492.150143) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-548" d="M 1953 -66+Q 1516 -66 1175 106+Q 834 278 625 578+Q 416 878 366 1259+L 1191 1259+Q 1253 991 1450 823+Q 1647 656 1953 656+Q 2438 656 2700 1079+Q 2963 1503 2963 2247+L 2931 2247+Q 2763 1950 2455 1776+Q 2147 1603 1769 1603+Q 1359 1603 1032 1798+Q 706 1994 514 2337+Q 322 2681 322 3119+Q 322 3578 533 3943+Q 744 4309 1123 4518+Q 1503 4728 2006 4722+Q 2334 4719 2650 4605+Q 2966 4491 3219 4231+Q 3472 3972 3622 3539+Q 3772 3106 3772 2466+Q 3772 1666 3548 1100+Q 3325 534 2917 234+Q 2509 -66 1953 -66+z+M 1991 2244+Q 2241 2244 2439 2367+Q 2638 2491 2755 2697+Q 2872 2903 2872 3147+Q 2872 3384 2759 3589+Q 2647 3794 2450 3917+Q 2253 4041 2003 4041+Q 1756 4041 1559 3920+Q 1363 3800 1248 3595+Q 1134 3391 1134 3138+Q 1134 2884 1245 2682+Q 1356 2481 1550 2362+Q 1744 2244 1991 2244+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(130.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-548" transform="translate(172.609375 0)"/>+ </g>+ </g>+ <g id="text_43">+ <!-- $4.02 -->+ <g style="fill: #f4f6fa" transform="translate(1472.780994 532.078714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_44">+ <!-- $0.551 -->+ <g style="fill: #f4f6fa" transform="translate(1030.474161 558.007286) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(159.203125 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(220.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(281.671875 0)"/>+ </g>+ </g>+ <g id="text_45">+ <!-- $4.04 -->+ <g style="fill: #f4f6fa" transform="translate(1476.023208 597.935857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_46">+ <!-- $0.383 -->+ <g style="fill: #f4f6fa" transform="translate(1009.139249 623.864429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(157.6875 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(221.3125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(285.328125 0)"/>+ </g>+ </g>+ <g id="text_47">+ <!-- $4.06 -->+ <g style="fill: #f4f6fa" transform="translate(1477.960254 663.793) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_48">+ <!-- $0.206 -->+ <g style="fill: #f4f6fa" transform="translate(986.499168 689.721571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(288.40625 0)"/>+ </g>+ </g>+ <g id="text_49">+ <!-- $4.07 -->+ <g style="fill: #f4f6fa" transform="translate(1479 729.650143) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(221.40625 0)"/>+ </g>+ </g>+ <g id="text_50">+ <!-- $0.206 -->+ <g style="fill: #f4f6fa" transform="translate(986.551156 755.578714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(288.40625 0)"/>+ </g>+ </g>+ </g>+ </g>+ <defs>+ <clipPath id="p1c9bf33d97">+ <rect x="0" y="0" width="1600" height="900"/>+ </clipPath>+ </defs>+</svg>diff --git a/docs/assets/whole-repo-cost-light.png b/docs/assets/whole-repo-cost-light.pngnew file mode 100644index 0000000..96ff158Binary files /dev/null and b/docs/assets/whole-repo-cost-light.png differdiff --git a/docs/assets/whole-repo-cost-light.svg b/docs/assets/whole-repo-cost-light.svgnew file mode 100644index 0000000..e868d68--- /dev/null+++ b/docs/assets/whole-repo-cost-light.svg@@ -0,0 +1,5354 @@+<?xml version="1.0" encoding="utf-8" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"+ "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">+<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="1600" height="900" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" version="1.1">+ <title>Input cost per follow-up question with a 1M-token context, without and with the prompt cache, computed at list prices, not billed.</title>+ <desc>Pack, standard layout: Muse Spark 1.3 $1.27 without the cache, $1.27 with it, Muse Wonder $4.06 without the cache, $4.06 with it; Pack, cache layout, 50%: Muse Spark 1.3 $1.17 without the cache, $0.610 with it, Muse Wonder $3.74 without the cache, $1.81 with it; Pack, cache layout, 70%: Muse Spark 1.3 $1.21 without the cache, $0.433 with it, Muse Wonder $3.88 without the cache, $1.19 with it; Pack, cache layout, 90%: Muse Spark 1.3 $1.26 without the cache, $0.252 with it, Muse Wonder $4.02 without the cache, $0.551 with it; Pack, cache layout, 95%: Muse Spark 1.3 $1.26 without the cache, $0.204 with it, Muse Wonder $4.04 without the cache, $0.383 with it; Pack, stable layout: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.06 without the cache, $0.206 with it; Truncation: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.07 without the cache, $0.206 with it.</desc>+ <metadata>+ <rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">+ <cc:Work>+ <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>+ <dc:format>image/svg+xml</dc:format>+ <dc:creator>+ <cc:Agent>+ <dc:title>Matplotlib v3.11.2, https://matplotlib.org/</dc:title>+ </cc:Agent>+ </dc:creator>+ </cc:Work>+ </rdf:RDF>+ </metadata>+ <defs>+ <style type="text/css">*{stroke-linejoin: round; stroke-linecap: butt}</style>+ </defs>+ <g id="figure_1">+ <g id="patch_1">+ <path d="M 0 900+L 1600 900+L 1600 0+L 0 0+z+" style="fill: #ffffff"/>+ </g>+ <g id="axes_1">+ <g id="patch_2">+ <path d="M 48 789+L 1552 789+L 1552 790+L 48 790+z+" clip-path="url(#p1c9bf33d97)" style="fill: #e3e6ec"/>+ </g>+ <g id="patch_3">+ <path d="M 48 197+L 66 197+L 66 215+L 48 215+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_4">+ <path d="M 290.59375 197+L 308.59375 197+L 308.59375 215+L 290.59375 215+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_5">+ <path d="M 308.46875 316+L 466.136904 316+Q 470.136904 316 470.136904 320+L 470.136904 335.928571+Q 470.136904 339.928571 466.136904 339.928571+L 308.46875 339.928571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_6">+ <path d="M 308.46875 341.928571+L 466.136904 341.928571+Q 470.136904 341.928571 470.136904 345.928571+L 470.136904 361.857143+Q 470.136904 365.857143 466.136904 365.857143+L 308.46875 365.857143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_7">+ <path d="M 308.46875 381.857143+L 453.461289 381.857143+Q 457.461289 381.857143 457.461289 385.857143+L 457.461289 401.785714+Q 457.461289 405.785714 453.461289 405.785714+L 308.46875 405.785714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_8">+ <path d="M 308.46875 407.785714+L 382.332132 407.785714+Q 386.332132 407.785714 386.332132 411.785714+L 386.332132 427.714286+Q 386.332132 431.714286 382.332132 431.714286+L 308.46875 431.714286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_9">+ <path d="M 308.46875 447.714286+L 459.349926 447.714286+Q 463.349926 447.714286 463.349926 451.714286+L 463.349926 467.642857+Q 463.349926 471.642857 459.349926 471.642857+L 308.46875 471.642857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_10">+ <path d="M 308.46875 473.642857+L 359.766411 473.642857+Q 363.766411 473.642857 363.766411 477.642857+L 363.766411 493.571429+Q 363.766411 497.571429 359.766411 497.571429+L 308.46875 497.571429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_11">+ <path d="M 308.46875 513.571429+L 464.639568 513.571429+Q 468.639568 513.571429 468.639568 517.571429+L 468.639568 533.5+Q 468.639568 537.5 464.639568 537.5+L 308.46875 537.5+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_12">+ <path d="M 308.46875 539.5+L 336.60338 539.5+Q 340.60338 539.5 340.60338 543.5+L 340.60338 559.428571+Q 340.60338 563.428571 336.60338 563.428571+L 308.46875 563.428571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_13">+ <path d="M 308.46875 579.428571+L 465.65276 579.428571+Q 469.65276 579.428571 469.65276 583.428571+L 469.65276 599.357143+Q 469.65276 603.357143 465.65276 603.357143+L 308.46875 603.357143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_14">+ <path d="M 308.46875 605.357143+L 330.50214 605.357143+Q 334.50214 605.357143 334.50214 609.357143+L 334.50214 625.285714+Q 334.50214 629.285714 330.50214 629.285714+L 308.46875 629.285714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_15">+ <path d="M 308.46875 645.285714+L 466.258087 645.285714+Q 470.258087 645.285714 470.258087 649.285714+L 470.258087 665.214286+Q 470.258087 669.214286 466.258087 669.214286+L 308.46875 669.214286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_16">+ <path d="M 308.46875 671.214286+L 323.993036 671.214286+Q 327.993036 671.214286 327.993036 675.214286+L 327.993036 691.142857+Q 327.993036 695.142857 323.993036 695.142857+L 308.46875 695.142857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_17">+ <path d="M 308.46875 711.142857+L 466.583008 711.142857+Q 470.583008 711.142857 470.583008 715.142857+L 470.583008 731.071429+Q 470.583008 735.071429 466.583008 735.071429+L 308.46875 735.071429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_18">+ <path d="M 308.46875 737.071429+L 324.032027 737.071429+Q 328.032027 737.071429 328.032027 741.071429+L 328.032027 757+Q 328.032027 761 324.032027 761+L 308.46875 761+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_19">+ <path d="M 950.234375 316+L 1463.572467 316+Q 1467.572467 316 1467.572467 320+L 1467.572467 335.928571+Q 1467.572467 339.928571 1463.572467 339.928571+L 950.234375 339.928571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_20">+ <path d="M 950.234375 341.928571+L 1463.572467 341.928571+Q 1467.572467 341.928571 1467.572467 345.928571+L 1467.572467 361.857143+Q 1467.572467 365.857143 1463.572467 365.857143+L 950.234375 365.857143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_21">+ <path d="M 950.234375 381.857143+L 1423.010501 381.857143+Q 1427.010501 381.857143 1427.010501 385.857143+L 1427.010501 401.785714+Q 1427.010501 405.785714 1423.010501 405.785714+L 950.234375 405.785714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_22">+ <path d="M 950.234375 407.785714+L 1177.291593 407.785714+Q 1181.291593 407.785714 1181.291593 411.785714+L 1181.291593 427.714286+Q 1181.291593 431.714286 1177.291593 431.714286+L 950.234375 431.714286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_23">+ <path d="M 950.234375 447.714286+L 1441.854138 447.714286+Q 1445.854138 447.714286 1445.854138 451.714286+L 1445.854138 467.642857+Q 1445.854138 471.642857 1441.854138 471.642857+L 950.234375 471.642857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_24">+ <path d="M 950.234375 473.642857+L 1097.838358 473.642857+Q 1101.838358 473.642857 1101.838358 477.642857+L 1101.838358 493.571429+Q 1101.838358 497.571429 1097.838358 497.571429+L 950.234375 497.571429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_25">+ <path d="M 950.234375 513.571429+L 1458.780994 513.571429+Q 1462.780994 513.571429 1462.780994 517.571429+L 1462.780994 533.5+Q 1462.780994 537.5 1458.780994 537.5+L 950.234375 537.5+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_26">+ <path d="M 950.234375 539.5+L 1016.474161 539.5+Q 1020.474161 539.5 1020.474161 543.5+L 1020.474161 559.428571+Q 1020.474161 563.428571 1016.474161 563.428571+L 950.234375 563.428571+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_27">+ <path d="M 950.234375 579.428571+L 1462.023208 579.428571+Q 1466.023208 579.428571 1466.023208 583.428571+L 1466.023208 599.357143+Q 1466.023208 603.357143 1462.023208 603.357143+L 950.234375 603.357143+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_28">+ <path d="M 950.234375 605.357143+L 995.139249 605.357143+Q 999.139249 605.357143 999.139249 609.357143+L 999.139249 625.285714+Q 999.139249 629.285714 995.139249 629.285714+L 950.234375 629.285714+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_29">+ <path d="M 950.234375 645.285714+L 1463.960254 645.285714+Q 1467.960254 645.285714 1467.960254 649.285714+L 1467.960254 665.214286+Q 1467.960254 669.214286 1463.960254 669.214286+L 950.234375 669.214286+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_30">+ <path d="M 950.234375 671.214286+L 972.499168 671.214286+Q 976.499168 671.214286 976.499168 675.214286+L 976.499168 691.142857+Q 976.499168 695.142857 972.499168 695.142857+L 950.234375 695.142857+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_31">+ <path d="M 950.234375 711.142857+L 1465 711.142857+Q 1469 711.142857 1469 715.142857+L 1469 731.071429+Q 1469 735.071429 1465 735.071429+L 950.234375 735.071429+z+" clip-path="url(#p1c9bf33d97)" style="fill: #2a78d6"/>+ </g>+ <g id="patch_32">+ <path d="M 950.234375 737.071429+L 972.551156 737.071429+Q 976.551156 737.071429 976.551156 741.071429+L 976.551156 757+Q 976.551156 761 972.551156 761+L 950.234375 761+z+" clip-path="url(#p1c9bf33d97)" style="fill: #eb6834"/>+ </g>+ <g id="patch_33">+ <path d="M 307.71875 308+L 309.21875 308+L 309.21875 769+L 307.71875 769+z+" clip-path="url(#p1c9bf33d97)" style="fill: #e3e6ec"/>+ </g>+ <g id="patch_34">+ <path d="M 949.484375 308+L 950.984375 308+L 950.984375 769+L 949.484375 769+z+" clip-path="url(#p1c9bf33d97)" style="fill: #e3e6ec"/>+ </g>+ <g id="text_1">+ <!-- Graphicle -->+ <g style="fill: #0a0b0f" transform="translate(48 60) scale(0.28 -0.28)">+ <defs>+ <path id="Inter-Bold-8d" d="M 2484 -63+Q 1831 -63 1337 226+Q 844 516 569 1050+Q 294 1584 294 2322+Q 294 3075 580 3612+Q 866 4150 1358 4434+Q 1850 4719 2463 4719+Q 2988 4719 3413 4519+Q 3838 4319 4109 3967+Q 4381 3616 4447 3156+L 3478 3156+Q 3378 3491 3122 3681+Q 2866 3872 2478 3872+Q 1941 3872 1602 3472+Q 1263 3072 1263 2331+Q 1263 1591 1597 1187+Q 1931 784 2491 784+Q 2988 784 3272 1046+Q 3556 1309 3569 1756+L 2556 1756+L 2556 2481+L 4494 2481+L 4494 1900+Q 4494 1288 4234 848+Q 3975 409 3522 173+Q 3069 -63 2484 -63+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-354" d="M 400 0+L 400 3494+L 1306 3494+L 1306 2884+L 1344 2884+Q 1441 3206 1667 3373+Q 1894 3541 2188 3541+Q 2347 3541 2491 3509+L 2491 2672+Q 2428 2691 2308 2705+Q 2188 2719 2084 2719+Q 1759 2719 1548 2516+Q 1338 2313 1338 1988+L 1338 0+L 400 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-1fb" d="M 1375 -69+Q 875 -69 544 195+Q 213 459 213 978+Q 213 1369 400 1591+Q 588 1813 888 1916+Q 1188 2019 1531 2050+Q 1981 2094 2179 2142+Q 2378 2191 2378 2363+L 2378 2378+Q 2378 2600 2236 2722+Q 2094 2844 1831 2844+Q 1559 2844 1393 2726+Q 1228 2609 1172 2441+L 313 2584+Q 447 3038 848 3288+Q 1250 3538 1834 3538+Q 2209 3538 2548 3419+Q 2888 3300 3102 3039+Q 3316 2778 3316 2353+L 3316 0+L 2428 0+L 2428 484+L 2397 484+Q 2269 241 2016 86+Q 1763 -69 1375 -69+z+M 1641 591+Q 1969 591 2176 781+Q 2384 972 2384 1250+L 2384 1628+Q 2328 1588 2201 1558+Q 2075 1528 1934 1504+Q 1794 1481 1691 1469+Q 1431 1431 1272 1322+Q 1113 1213 1113 1003+Q 1113 800 1261 695+Q 1409 591 1641 591+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-34b" d="M 400 -1306+L 400 3494+L 1322 3494+L 1322 2906+L 1366 2906+Q 1428 3044 1548 3191+Q 1669 3338 1867 3438+Q 2066 3538 2363 3538+Q 2750 3538 3072 3338+Q 3394 3138 3586 2738+Q 3778 2338 3778 1741+Q 3778 1159 3590 757+Q 3403 356 3081 148+Q 2759 -59 2356 -59+Q 2072 -59 1875 37+Q 1678 134 1554 276+Q 1431 419 1366 559+L 1338 559+L 1338 -1306+L 400 -1306+z+M 2069 694+Q 2434 694 2626 987+Q 2819 1281 2819 1744+Q 2819 2203 2628 2495+Q 2438 2788 2069 2788+Q 1706 2788 1511 2503+Q 1316 2219 1316 1744+Q 1316 1269 1512 981+Q 1709 694 2069 694+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-29e" d="M 1338 2022+L 1338 0+L 400 0+L 400 4656+L 1319 4656+L 1319 2825+Q 1472 3166 1734 3352+Q 1997 3538 2384 3538+Q 2928 3538 3258 3188+Q 3588 2838 3588 2222+L 3588 0+L 2647 0+L 2647 2059+Q 2647 2384 2480 2568+Q 2313 2753 2016 2753+Q 1716 2753 1527 2561+Q 1338 2369 1338 2022+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-2b1" d="M 400 0+L 400 3494+L 1338 3494+L 1338 0+L 400 0+z+M 869 3950+Q 656 3950 506 4090+Q 356 4231 356 4431+Q 356 4631 506 4772+Q 656 4913 869 4913+Q 1081 4913 1232 4772+Q 1384 4631 1384 4431+Q 1384 4231 1232 4090+Q 1081 3950 869 3950+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-24a" d="M 1963 -69+Q 1434 -69 1051 157+Q 669 384 461 789+Q 253 1194 253 1731+Q 253 2272 461 2678+Q 669 3084 1051 3311+Q 1434 3538 1963 3538+Q 2584 3538 3000 3227+Q 3416 2916 3516 2375+L 2644 2213+Q 2584 2484 2414 2642+Q 2244 2800 1972 2800+Q 1597 2800 1403 2504+Q 1209 2209 1209 1734+Q 1209 1266 1403 967+Q 1597 669 1972 669+Q 2244 669 2419 833+Q 2594 997 2650 1278+L 3522 1119+Q 3422 566 3006 248+Q 2591 -69 1963 -69+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-2e0" d="M 1338 4656+L 1338 0+L 400 0+L 400 4656+L 1338 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Bold-266" d="M 1978 -69+Q 1444 -69 1056 150+Q 669 369 461 772+Q 253 1175 253 1728+Q 253 2269 461 2675+Q 669 3081 1045 3309+Q 1422 3538 1931 3538+Q 2388 3538 2759 3344+Q 3131 3150 3351 2756+Q 3572 2363 3572 1766+L 3572 1503+L 1181 1503+Q 1197 1075 1419 856+Q 1641 638 1994 638+Q 2241 638 2417 742+Q 2594 847 2669 1050+L 3519 891+Q 3391 456 2989 193+Q 2588 -69 1978 -69+z+M 1188 2091+L 2669 2091+Q 2634 2431 2450 2631+Q 2266 2831 1941 2831+Q 1603 2831 1409 2623+Q 1216 2416 1188 2091+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Bold-8d"/>+ <use xlink:href="#Inter-Bold-354" transform="translate(75.046875 0)"/>+ <use xlink:href="#Inter-Bold-1fb" transform="translate(114.40625 0)"/>+ <use xlink:href="#Inter-Bold-34b" transform="translate(172.46875 0)"/>+ <use xlink:href="#Inter-Bold-29e" transform="translate(235.5 0)"/>+ <use xlink:href="#Inter-Bold-2b1" transform="translate(297.75 0)"/>+ <use xlink:href="#Inter-Bold-24a" transform="translate(324.84375 0)"/>+ <use xlink:href="#Inter-Bold-2e0" transform="translate(383.6875 0)"/>+ <use xlink:href="#Inter-Bold-266" transform="translate(410.78125 0)"/>+ </g>+ </g>+ <g id="text_2">+ <!-- whole-repository benchmark -->+ <g style="fill: #5b6474" transform="translate(195.734375 60) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-3d8" d="M 1278 0+L 219 3494+L 816 3494+L 1241 1969+Q 1316 1697 1403 1358+Q 1491 1019 1575 603+Q 1659 1003 1742 1340+Q 1825 1678 1906 1969+L 2325 3494+L 2925 3494+L 3338 1969+Q 3413 1688 3495 1352+Q 3578 1016 3659 613+Q 3747 1013 3833 1348+Q 3919 1684 3997 1969+L 4422 3494+L 5019 3494+L 3959 0+L 3400 0+L 2947 1581+Q 2859 1881 2779 2200+Q 2700 2519 2619 2853+Q 2541 2519 2458 2197+Q 2375 1875 2291 1581+L 1838 0+L 1278 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-29e" d="M 1056 2094+L 1056 0+L 494 0+L 494 4656+L 1056 4656+L 1056 2888+Q 1228 3238 1495 3388+Q 1763 3538 2106 3538+Q 2638 3538 2964 3209+Q 3291 2881 3291 2219+L 3291 0+L 2725 0+L 2725 2172+Q 2725 2575 2514 2803+Q 2303 3031 1938 3031+Q 1559 3031 1307 2786+Q 1056 2541 1056 2094+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-316" d="M 1916 -75+Q 1441 -75 1083 150+Q 725 375 525 781+Q 325 1188 325 1725+Q 325 2272 525 2680+Q 725 3088 1083 3313+Q 1441 3538 1916 3538+Q 2394 3538 2753 3313+Q 3113 3088 3313 2680+Q 3513 2272 3513 1725+Q 3513 1188 3313 781+Q 3113 375 2753 150+Q 2394 -75 1916 -75+z+M 1916 428+Q 2269 428 2497 609+Q 2725 791 2834 1086+Q 2944 1381 2944 1725+Q 2944 2072 2834 2370+Q 2725 2669 2497 2851+Q 2269 3034 1916 3034+Q 1566 3034 1341 2851+Q 1116 2669 1006 2372+Q 897 2075 897 1725+Q 897 1381 1006 1086+Q 1116 791 1341 609+Q 1566 428 1916 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2e0" d="M 1056 4656+L 1056 0+L 494 0+L 494 4656+L 1056 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-266" d="M 1963 -75+Q 1456 -75 1089 150+Q 722 375 523 778+Q 325 1181 325 1719+Q 325 2256 519 2665+Q 713 3075 1067 3306+Q 1422 3538 1897 3538+Q 2175 3538 2445 3445+Q 2716 3353 2936 3148+Q 3156 2944 3287 2609+Q 3419 2275 3419 1791+L 3419 1556+L 894 1556+Q 916 1009 1208 717+Q 1500 425 1966 425+Q 2275 425 2498 561+Q 2722 697 2819 963+L 3363 813+Q 3241 416 2870 170+Q 2500 -75 1963 -75+z+M 897 2031+L 2847 2031+Q 2806 2478 2567 2758+Q 2328 3038 1897 3038+Q 1597 3038 1380 2897+Q 1163 2756 1038 2528+Q 913 2300 897 2031+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5b3" d="M 2494 2247+L 2494 1728+L 450 1728+L 450 2247+L 2494 2247+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-354" d="M 494 0+L 494 3494+L 1038 3494+L 1038 2956+L 1075 2956+Q 1172 3222 1420 3383+Q 1669 3544 1981 3544+Q 2044 3544 2130 3541+Q 2216 3538 2266 3534+L 2266 2969+Q 2241 2975 2141 2987+Q 2041 3000 1928 3000+Q 1550 3000 1303 2770+Q 1056 2541 1056 2188+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-34b" d="M 494 -1306+L 494 3494+L 1038 3494+L 1038 2934+L 1100 2934+Q 1159 3028 1265 3170+Q 1372 3313 1572 3425+Q 1772 3538 2113 3538+Q 2550 3538 2883 3319+Q 3216 3100 3405 2695+Q 3594 2291 3594 1738+Q 3594 1181 3406 775+Q 3219 369 2886 147+Q 2553 -75 2116 -75+Q 1784 -75 1581 39+Q 1378 153 1268 298+Q 1159 444 1100 541+L 1056 541+L 1056 -1306+L 494 -1306+z+M 2031 428+Q 2359 428 2579 604+Q 2800 781 2911 1079+Q 3022 1378 3022 1744+Q 3022 2106 2912 2398+Q 2803 2691 2583 2862+Q 2363 3034 2031 3034+Q 1550 3034 1300 2678+Q 1050 2322 1050 1744+Q 1050 1159 1303 793+Q 1556 428 2031 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-367" d="M 1681 -75+Q 1144 -75 787 159+Q 431 394 338 847+L 872 975+Q 947 688 1155 553+Q 1363 419 1675 419+Q 2041 419 2258 575+Q 2475 731 2475 947+Q 2475 1306 1963 1428+L 1381 1566+Q 444 1788 444 2519+Q 444 2819 612 3048+Q 781 3278 1073 3408+Q 1366 3538 1738 3538+Q 2278 3538 2576 3302+Q 2875 3066 2994 2697+L 2484 2566+Q 2413 2753 2245 2906+Q 2078 3059 1741 3059+Q 1428 3059 1220 2915+Q 1013 2772 1013 2553+Q 1013 2359 1153 2242+Q 1294 2125 1600 2053+L 2128 1928+Q 2603 1816 2831 1580+Q 3059 1344 3059 984+Q 3059 678 2886 439+Q 2713 200 2402 62+Q 2091 -75 1681 -75+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2b1" d="M 494 0+L 494 3494+L 1056 3494+L 1056 0+L 494 0+z+M 778 4066+Q 619 4066 503 4175+Q 387 4284 387 4438+Q 387 4594 503 4701+Q 619 4809 778 4809+Q 940 4809 1056 4701+Q 1172 4594 1172 4438+Q 1172 4284 1056 4175+Q 940 4066 778 4066+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-379" d="M 1869 3494+L 1869 3013+L 1150 3013+L 1150 906+Q 1150 672 1245 564+Q 1341 456 1563 456+Q 1616 456 1698 468+Q 1781 481 1850 494+L 1966 19+Q 1878 -13 1767 -28+Q 1656 -44 1547 -44+Q 1094 -44 841 195+Q 588 434 588 863+L 588 3013+L 63 3013+L 63 3494+L 588 3494+L 588 4325+L 1150 4325+L 1150 3494+L 1869 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3e6" d="M 438 -1266+L 581 -778+L 641 -794+Q 900 -863 1087 -773+Q 1275 -684 1403 -309+L 1503 -19+L 169 3494+L 784 3494+L 1528 1422+Q 1609 1194 1673 969+Q 1738 744 1797 525+Q 1856 744 1920 969+Q 1984 1194 2066 1422+L 2816 3494+L 3428 3494+L 1894 -522+Q 1734 -938 1478 -1134+Q 1222 -1331 850 -1331+Q 700 -1331 590 -1309+Q 481 -1288 438 -1266+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-6f1" transform="scale(0.015625)"/>+ <path id="Inter-Regular-242" d="M 2116 -75+Q 1784 -75 1581 39+Q 1378 153 1268 298+Q 1159 444 1100 541+L 1038 541+L 1038 0+L 494 0+L 494 4656+L 1056 4656+L 1056 2934+L 1100 2934+Q 1159 3028 1265 3170+Q 1372 3313 1572 3425+Q 1772 3538 2113 3538+Q 2550 3538 2883 3319+Q 3216 3100 3405 2695+Q 3594 2291 3594 1738+Q 3594 1181 3406 775+Q 3219 369 2886 147+Q 2553 -75 2116 -75+z+M 2031 428+Q 2359 428 2579 604+Q 2800 781 2911 1079+Q 3022 1378 3022 1744+Q 3022 2106 2912 2398+Q 2803 2691 2583 2862+Q 2363 3034 2031 3034+Q 1550 3034 1300 2678+Q 1050 2322 1050 1744+Q 1050 1159 1303 793+Q 1556 428 2031 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-305" d="M 1056 2094+L 1056 0+L 494 0+L 494 3494+L 1034 3494+L 1038 2847+Q 1206 3219 1479 3378+Q 1753 3538 2106 3538+Q 2638 3538 2963 3209+Q 3288 2881 3288 2219+L 3288 0+L 2725 0+L 2725 2172+Q 2725 2575 2514 2803+Q 2303 3031 1938 3031+Q 1559 3031 1307 2786+Q 1056 2541 1056 2094+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-24a" d="M 1916 -75+Q 1441 -75 1083 150+Q 725 375 525 781+Q 325 1188 325 1725+Q 325 2272 525 2680+Q 725 3088 1083 3313+Q 1441 3538 1916 3538+Q 2422 3538 2805 3283+Q 3188 3028 3331 2572+L 2791 2419+Q 2713 2688 2486 2861+Q 2259 3034 1916 3034+Q 1566 3034 1341 2851+Q 1116 2669 1006 2372+Q 897 2075 897 1725+Q 897 1381 1006 1086+Q 1116 791 1341 609+Q 1566 428 1916 428+Q 2269 428 2498 608+Q 2728 788 2806 1072+L 3344 919+Q 3203 453 2815 189+Q 2428 -75 1916 -75+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2fe" d="M 494 0+L 494 3494+L 1041 3494+L 1044 2853+Q 1172 3206 1442 3381+Q 1713 3556 2022 3556+Q 2366 3556 2592 3361+Q 2819 3166 2913 2844+Q 3038 3175 3336 3365+Q 3634 3556 4013 3556+Q 4316 3556 4566 3425+Q 4816 3294 4964 3028+Q 5113 2763 5113 2356+L 5113 0+L 4550 0+L 4550 2341+Q 4550 2719 4337 2881+Q 4125 3044 3844 3044+Q 3491 3044 3287 2828+Q 3084 2613 3084 2281+L 3084 0+L 2522 0+L 2522 2397+Q 2522 2688 2328 2866+Q 2134 3044 1838 3044+Q 1531 3044 1293 2831+Q 1056 2619 1056 2200+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-1fb" d="M 1472 -81+Q 1141 -81 870 44+Q 600 169 440 409+Q 281 650 281 994+Q 281 1294 400 1481+Q 519 1669 717 1776+Q 916 1884 1156 1937+Q 1397 1991 1641 2022+Q 1953 2063 2150 2084+Q 2347 2106 2442 2159+Q 2538 2213 2538 2341+L 2538 2359+Q 2538 2684 2353 2864+Q 2169 3044 1806 3044+Q 1428 3044 1215 2880+Q 1003 2716 922 2531+L 381 2709+Q 516 3028 744 3208+Q 972 3388 1247 3463+Q 1522 3538 1791 3538+Q 1966 3538 2189 3495+Q 2413 3453 2620 3328+Q 2828 3203 2964 2958+Q 3100 2713 3100 2303+L 3100 0+L 2547 0+L 2547 475+L 2509 475+Q 2450 353 2319 223+Q 2188 94 1978 6+Q 1769 -81 1472 -81+z+M 1569 416+Q 1881 416 2097 537+Q 2313 659 2425 854+Q 2538 1050 2538 1263+L 2538 1747+Q 2503 1706 2387 1673+Q 2272 1641 2123 1616+Q 1975 1591 1836 1573+Q 1697 1556 1616 1547+Q 1413 1522 1236 1461+Q 1059 1400 953 1283+Q 847 1166 847 966+Q 847 694 1051 555+Q 1256 416 1569 416+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2d7" d="M 494 0+L 494 4656+L 1056 4656+L 1056 1953+L 1125 1953+L 2619 3494+L 3316 3494+L 1853 1994+L 3425 0+L 2703 0+L 1425 1634+L 1056 1288+L 1056 0+L 494 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-3d8"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(81.84375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(140.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(200.9375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(225.15625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(283.453125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(329.453125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(365.4375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(423.734375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(484.96875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(544.9375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(597.71875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(621.9375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(653.6875 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(713.65625 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(752.859375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(809.0625 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(837.1875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(898.421875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(956.71875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1015.796875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1072.921875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(1132.046875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1219.640625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(1275.796875 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1315 0)"/>+ </g>+ </g>+ <g id="text_3">+ <!-- What a follow-up question costs with the prompt cache -->+ <g style="fill: #0a0b0f" transform="translate(48 112) scale(0.34 -0.34)">+ <defs>+ <path id="InterDisplay-SemiBold-1cb" d="M 1297 0+L 41 4656+L 913 4656+L 1528 2147+Q 1600 1841 1664 1536+Q 1728 1231 1788 925+Q 1850 1231 1919 1536+Q 1988 1841 2063 2147+L 2703 4656+L 3575 4656+L 4209 2147+Q 4284 1844 4353 1542+Q 4422 1241 4484 941+Q 4603 1531 4747 2147+L 5363 4656+L 6238 4656+L 4978 0+L 4044 0+L 3331 2694+Q 3281 2884 3234 3095+Q 3188 3306 3138 3538+Q 3088 3306 3041 3095+Q 2994 2884 2944 2694+L 2234 0+L 1297 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-29e" d="M 1138 1866+L 1138 0+L 350 0+L 350 4656+L 1138 4656+L 1138 2816+Q 1481 3366 2138 3366+Q 2656 3366 2986 3031+Q 3316 2697 3316 2063+L 3316 0+L 2525 0+L 2525 1938+Q 2525 2300 2350 2487+Q 2175 2675 1859 2675+Q 1550 2675 1344 2481+Q 1138 2288 1138 1866+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-1fb" d="M 1356 -53+Q 863 -53 539 195+Q 216 444 216 938+Q 216 1313 398 1517+Q 581 1722 876 1815+Q 1172 1909 1513 1944+Q 1972 1997 2153 2037+Q 2334 2078 2334 2247+L 2334 2272+Q 2334 2484 2173 2618+Q 2013 2753 1731 2753+Q 1444 2753 1264 2618+Q 1084 2484 1069 2275+L 309 2275+Q 338 2766 719 3066+Q 1100 3366 1747 3366+Q 2391 3366 2753 3066+Q 3116 2766 3116 2250+L 3116 0+L 2341 0+L 2341 466+L 2328 466+Q 2209 247 1984 97+Q 1759 -53 1356 -53+z+M 1550 531+Q 1938 531 2138 732+Q 2338 934 2338 1222+L 2338 1578+Q 2266 1531 2059 1492+Q 1853 1453 1609 1416+Q 1356 1378 1170 1273+Q 984 1169 984 944+Q 984 750 1137 640+Q 1291 531 1550 531+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-379" d="M 2091 3300+L 2091 2666+L 1419 2666+L 1419 947+Q 1419 769 1491 701+Q 1563 634 1753 634+L 2091 634+L 2091 0+L 1616 0+Q 1113 0 870 203+Q 628 406 628 831+L 628 2666+L 53 2666+L 53 3300+L 628 3300+L 628 4200+L 1419 4200+L 1419 3300+L 2091 3300+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-6f1" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-287" d="M 2109 3300+L 2109 2666+L 1438 2666+L 1438 0+L 647 0+L 647 2666+L 53 2666+L 53 3300+L 647 3300+L 647 3781+Q 647 4206 905 4431+Q 1163 4656 1650 4656+L 2109 4656+L 2109 4022+L 1806 4022+Q 1603 4022 1520 3937+Q 1438 3853 1438 3650+L 1438 3300+L 2109 3300+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-316" d="M 1825 -75+Q 1338 -75 972 142+Q 606 359 401 746+Q 197 1134 197 1647+Q 197 2159 401 2548+Q 606 2938 972 3156+Q 1338 3375 1825 3375+Q 2309 3375 2676 3156+Q 3044 2938 3248 2548+Q 3453 2159 3453 1647+Q 3453 1134 3248 746+Q 3044 359 2676 142+Q 2309 -75 1825 -75+z+M 1825 584+Q 2203 584 2428 868+Q 2653 1153 2653 1647+Q 2653 2141 2428 2428+Q 2203 2716 1825 2716+Q 1444 2716 1219 2430+Q 994 2144 994 1647+Q 994 1153 1219 868+Q 1444 584 1825 584+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2e0" d="M 1138 4656+L 1138 0+L 350 0+L 350 4656+L 1138 4656+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-3d8" d="M 1075 0+L 56 3300+L 884 3300+L 1225 2047+Q 1303 1753 1375 1440+Q 1447 1128 1522 822+Q 1597 1128 1675 1440+Q 1753 1753 1834 2047+L 2184 3300+L 2913 3300+L 3259 2047+Q 3338 1753 3414 1443+Q 3491 1134 3569 828+Q 3641 1134 3712 1443+Q 3784 1753 3863 2047+L 4203 3300+L 5041 3300+L 4019 0+L 3200 0+L 2800 1375+Q 2734 1603 2671 1843+Q 2609 2084 2547 2325+Q 2488 2084 2425 1843+Q 2363 1603 2294 1375+L 1888 0+L 1075 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-5b3" d="M 2450 2188+L 2450 1525+L 363 1525+L 363 2188+L 2450 2188+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-393" d="M 1525 -66+Q 1006 -66 678 268+Q 350 603 350 1238+L 350 3300+L 1138 3300+L 1138 1363+Q 1138 1000 1313 812+Q 1488 625 1803 625+Q 2116 625 2320 819+Q 2525 1013 2525 1434+L 2525 3300+L 3316 3300+L 3316 0+L 2541 0+L 2541 506+Q 2194 -66 1525 -66+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-34b" d="M 350 -1306+L 350 3300+L 1125 3300+L 1125 2841+L 1134 2841+Q 1291 3103 1553 3234+Q 1816 3366 2134 3366+Q 2559 3366 2879 3148+Q 3200 2931 3379 2545+Q 3559 2159 3559 1653+Q 3559 1138 3382 752+Q 3206 366 2884 150+Q 2563 -66 2131 -66+Q 1806 -66 1554 75+Q 1303 216 1147 497+L 1138 497+L 1138 -1306+L 350 -1306+z+M 1947 594+Q 2313 594 2538 867+Q 2763 1141 2763 1653+Q 2763 2163 2538 2438+Q 2313 2713 1947 2713+Q 1559 2713 1326 2423+Q 1094 2134 1094 1653+Q 1094 1172 1326 883+Q 1559 594 1947 594+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-351" d="M 3406 -1306+L 2619 -1306+L 2619 497+L 2609 497+Q 2453 216 2200 75+Q 1947 -66 1625 -66+Q 1194 -66 872 150+Q 550 366 373 752+Q 197 1138 197 1653+Q 197 2159 375 2545+Q 553 2931 875 3148+Q 1197 3366 1619 3366+Q 1941 3366 2203 3234+Q 2466 3103 2619 2841+L 2631 2841+L 2631 3300+L 3406 3300+L 3406 -1306+z+M 1809 594+Q 2197 594 2430 883+Q 2663 1172 2663 1653+Q 2663 2134 2430 2423+Q 2197 2713 1809 2713+Q 1444 2713 1219 2438+Q 994 2163 994 1653+Q 994 1141 1219 867+Q 1444 594 1809 594+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-266" d="M 1806 -75+Q 1313 -75 950 147+Q 588 369 392 758+Q 197 1147 197 1647+Q 197 2150 398 2539+Q 600 2928 956 3151+Q 1313 3375 1775 3375+Q 2250 3375 2606 3156+Q 2963 2938 3159 2552+Q 3356 2166 3356 1659+L 3356 1444+L 969 1444+Q 984 1041 1206 794+Q 1428 547 1825 547+Q 2122 547 2315 676+Q 2509 806 2578 1019+L 3316 1019+Q 3253 697 3042 450+Q 2831 203 2512 64+Q 2194 -75 1806 -75+z+M 975 1988+L 2600 1988+Q 2563 2341 2345 2545+Q 2128 2750 1788 2750+Q 1444 2750 1230 2545+Q 1016 2341 975 1988+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-367" d="M 1644 -78+Q 1041 -78 636 205+Q 231 488 194 1019+L 972 1019+Q 997 778 1165 645+Q 1334 513 1631 513+Q 1916 513 2080 625+Q 2244 738 2244 913+Q 2244 1063 2122 1153+Q 2000 1244 1794 1288+L 1231 1403+Q 269 1603 269 2356+Q 269 2813 631 3092+Q 994 3372 1597 3372+Q 2197 3372 2573 3076+Q 2950 2781 2963 2272+L 2222 2272+Q 2216 2494 2050 2637+Q 1884 2781 1616 2781+Q 1356 2781 1206 2665+Q 1056 2550 1056 2381+Q 1056 2234 1172 2142+Q 1288 2050 1494 2003+L 2088 1881+Q 2578 1778 2811 1556+Q 3044 1334 3044 972+Q 3044 650 2864 414+Q 2684 178 2368 50+Q 2053 -78 1644 -78+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2b1" d="M 350 0+L 350 3300+L 1138 3300+L 1138 0+L 350 0+z+M 743 3791+Q 540 3791 406 3920+Q 272 4050 272 4241+Q 272 4431 406 4559+Q 540 4688 743 4688+Q 943 4688 1077 4559+Q 1212 4431 1212 4241+Q 1212 4050 1077 3920+Q 943 3791 743 3791+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-305" d="M 1138 1866+L 1138 0+L 350 0+L 350 3300+L 1125 3300+L 1125 2794+Q 1469 3366 2138 3366+Q 2656 3366 2986 3031+Q 3316 2697 3316 2063+L 3316 0+L 2525 0+L 2525 1938+Q 2525 2300 2350 2487+Q 2175 2675 1859 2675+Q 1550 2675 1344 2481+Q 1138 2288 1138 1866+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-24a" d="M 1809 -75+Q 1328 -75 964 144+Q 600 363 398 750+Q 197 1138 197 1647+Q 197 2156 398 2545+Q 600 2934 964 3154+Q 1328 3375 1809 3375+Q 2225 3375 2550 3214+Q 2875 3053 3073 2770+Q 3272 2488 3306 2119+L 2534 2119+Q 2491 2384 2308 2551+Q 2125 2719 1819 2719+Q 1431 2719 1212 2428+Q 994 2138 994 1647+Q 994 1159 1212 870+Q 1431 581 1819 581+Q 2128 581 2300 745+Q 2472 909 2528 1184+L 3306 1184+Q 3278 822 3079 537+Q 2881 253 2554 89+Q 2228 -75 1809 -75+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-354" d="M 350 0+L 350 3300+L 1109 3300+L 1109 2753+L 1119 2753+Q 1209 3034 1404 3182+Q 1600 3331 1919 3331+Q 2000 3331 2064 3326+Q 2128 3322 2175 3319+L 2175 2619+Q 2131 2625 2025 2634+Q 1919 2644 1803 2644+Q 1522 2644 1330 2450+Q 1138 2256 1138 1869+L 1138 0+L 350 0+z+" transform="scale(0.015625)"/>+ <path id="InterDisplay-SemiBold-2fe" d="M 350 0+L 350 3300+L 1113 3300+L 1113 2728+Q 1263 3047 1528 3206+Q 1794 3366 2106 3366+Q 2441 3366 2697 3195+Q 2953 3025 3056 2741+Q 3188 3025 3466 3195+Q 3744 3366 4106 3366+Q 4575 3366 4894 3062+Q 5213 2759 5213 2178+L 5213 0+L 4422 0+L 4422 2066+Q 4422 2394 4242 2545+Q 4063 2697 3809 2697+Q 3509 2697 3336 2509+Q 3163 2322 3163 2025+L 3163 0+L 2397 0+L 2397 2103+Q 2397 2372 2228 2534+Q 2059 2697 1797 2697+Q 1531 2697 1334 2511+Q 1138 2325 1138 1969+L 1138 0+L 350 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#InterDisplay-SemiBold-1cb"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(98.09375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(155.375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(209.484375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(244.453125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(267.0625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(321.171875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-287" transform="translate(343.78125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(377.71875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2e0" transform="translate(434.703125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2e0" transform="translate(457.953125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(481.203125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-3d8" transform="translate(536.671875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-5b3" transform="translate(616.3125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-393" transform="translate(660.265625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(717.546875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(776.234375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-351" transform="translate(798.84375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-393" transform="translate(857.53125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(914.8125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(970.140625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1021.609375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2b1" transform="translate(1056.578125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1079.828125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-305" transform="translate(1136.8125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1194.09375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(1216.703125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1271.140625 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(1328.125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1379.59375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-367" transform="translate(1413.734375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1464.21875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-3d8" transform="translate(1486.828125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2b1" transform="translate(1566.46875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1590.5 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(1625.46875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1682.75 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(1705.359375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(1740.328125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(1797.609375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(1852.9375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(1875.546875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-354" transform="translate(1934.234375 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-316" transform="translate(1969.1875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-2fe" transform="translate(2026.171875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-34b" transform="translate(2113.03125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-379" transform="translate(2171.71875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-6f1" transform="translate(2206.6875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(2229.296875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-1fb" transform="translate(2284.421875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-24a" transform="translate(2338.53125 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-29e" transform="translate(2392.96875 0)"/>+ <use xlink:href="#InterDisplay-SemiBold-266" transform="translate(2450.25 0)"/>+ </g>+ </g>+ <g id="text_4">+ <!-- Input cost of a follow-up question with a 1M-token context; prefix and question-specific tokens measured on the development repositories. Computed at the -->+ <g style="fill: #5b6474" transform="translate(48 146) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-c5" d="M 1156 4656+L 1156 0+L 563 0+L 563 4656+L 1156 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-393" d="M 1678 -44+Q 1150 -44 822 284+Q 494 613 494 1275+L 494 3494+L 1056 3494+L 1056 1322+Q 1056 919 1268 691+Q 1481 463 1847 463+Q 2222 463 2473 708+Q 2725 953 2725 1400+L 2725 3494+L 3291 3494+L 3291 0+L 2747 0+L 2747 653+Q 2575 272 2298 114+Q 2022 -44 1678 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-287" d="M 2119 3494+L 2119 3013+L 1313 3013+L 1313 0+L 750 0+L 750 3013+L 63 3013+L 63 3494+L 750 3494+L 750 3959+Q 750 4263 892 4466+Q 1034 4669 1262 4772+Q 1491 4875 1744 4875+Q 1944 4875 2075 4842+Q 2206 4809 2269 4781+L 2113 4300+Q 2069 4316 1998 4334+Q 1928 4353 1809 4353+Q 1550 4353 1431 4220+Q 1313 4088 1313 3834+L 1313 3494+L 2119 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-351" d="M 3425 -1306+L 2863 -1306+L 2863 541+L 2819 541+Q 2763 444 2652 298+Q 2541 153 2339 39+Q 2138 -75 1803 -75+Q 1369 -75 1034 147+Q 700 369 512 775+Q 325 1181 325 1738+Q 325 2291 514 2695+Q 703 3100 1037 3319+Q 1372 3538 1806 3538+Q 2147 3538 2347 3425+Q 2547 3313 2655 3170+Q 2763 3028 2819 2934+L 2881 2934+L 2881 3494+L 3425 3494+L 3425 -1306+z+M 1888 428+Q 2363 428 2616 793+Q 2869 1159 2869 1744+Q 2869 2322 2620 2678+Q 2372 3034 1888 3034+Q 1556 3034 1336 2862+Q 1116 2691 1006 2398+Q 897 2106 897 1744+Q 897 1378 1008 1079+Q 1119 781 1341 604+Q 1563 428 1888 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-53e" d="M 2041 4656+L 2041 0+L 1456 0+L 1456 4106+L 1425 4106+L 300 3272+L 300 3909+L 1313 4656+L 2041 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-124" d="M 563 0+L 563 4656+L 1406 4656+L 2553 1719+Q 2619 1550 2716 1247+Q 2813 944 2897 659+Q 2978 934 3075 1239+Q 3172 1544 3241 1719+L 4372 4656+L 5219 4656+L 5219 0+L 4634 0+L 4634 2659+Q 4634 2916 4640 3287+Q 4647 3659 4656 4022+Q 4528 3622 4398 3244+Q 4269 2866 4188 2659+L 3147 0+L 2631 0+L 1575 2659+Q 1497 2856 1370 3229+Q 1244 3603 1106 4013+Q 1113 3681 1120 3304+Q 1128 2928 1128 2659+L 1128 0+L 563 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3e1" d="M 203 0+L 1431 1794+L 275 3494+L 931 3494+L 1366 2816+Q 1484 2628 1579 2461+Q 1675 2294 1766 2134+Q 1850 2294 1937 2461+Q 2025 2628 2147 2816+L 2591 3494+L 3234 3494+L 2066 1763+L 3291 0+L 2638 0+L 2125 784+Q 2009 963 1918 1123+Q 1828 1284 1741 1431+Q 1659 1284 1575 1123+Q 1491 963 1372 784+L 853 0+L 203 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5e4" d="M 400 -1122+L 675 650+L 1319 650+L 831 -1122+L 400 -1122+z+M 1010 2487+Q 835 2487 711 2610+Q 588 2734 588 2909+Q 588 3084 711 3207+Q 835 3331 1010 3331+Q 1185 3331 1308 3207+Q 1432 3084 1432 2909+Q 1432 2734 1308 2610+Q 1185 2487 1010 2487+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-255" d="M 1803 -75+Q 1369 -75 1034 147+Q 700 369 512 775+Q 325 1181 325 1738+Q 325 2291 514 2695+Q 703 3100 1037 3319+Q 1372 3538 1806 3538+Q 2147 3538 2347 3425+Q 2547 3313 2655 3170+Q 2763 3028 2819 2934+L 2863 2934+L 2863 4656+L 3425 4656+L 3425 0+L 2881 0+L 2881 541+L 2819 541+Q 2763 444 2652 298+Q 2541 153 2339 39+Q 2138 -75 1803 -75+z+M 1888 428+Q 2363 428 2616 793+Q 2869 1159 2869 1744+Q 2869 2322 2620 2678+Q 2372 3034 1888 3034+Q 1556 3034 1336 2862+Q 1116 2691 1006 2398+Q 897 2106 897 1744+Q 897 1378 1008 1079+Q 1119 781 1341 604+Q 1563 428 1888 428+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-3d4" d="M 1503 0+L 169 3494+L 784 3494+L 1528 1422+Q 1609 1194 1675 967+Q 1741 741 1800 522+Q 1859 741 1923 967+Q 1988 1194 2069 1422+L 2813 3494+L 3428 3494+L 2094 0+L 1503 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5de" d="M 922 -41+Q 747 -41 623 82+Q 500 206 500 381+Q 500 556 623 679+Q 747 803 922 803+Q 1097 803 1220 679+Q 1344 556 1344 381+Q 1344 206 1220 82+Q 1097 -41 922 -41+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-49" d="M 2447 -63+Q 1850 -63 1383 226+Q 916 516 648 1052+Q 381 1588 381 2325+Q 381 3066 648 3602+Q 916 4138 1383 4428+Q 1850 4719 2447 4719+Q 2919 4719 3314 4536+Q 3709 4353 3976 4012+Q 4244 3672 4325 3191+L 3731 3191+Q 3666 3509 3477 3728+Q 3288 3947 3019 4058+Q 2750 4169 2447 4169+Q 2028 4169 1690 3956+Q 1353 3744 1156 3333+Q 959 2922 959 2325+Q 959 1731 1157 1320+Q 1356 909 1693 698+Q 2031 488 2447 488+Q 2753 488 3020 600+Q 3288 713 3477 931+Q 3666 1150 3731 1466+L 4325 1466+Q 4244 994 3980 650+Q 3716 306 3320 121+Q 2925 -63 2447 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-c5"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(26.859375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(85.9375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(147.171875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(206.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(239.015625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(267.140625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(324.265625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(384.234375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(437.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(469.734375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(497.859375 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(557.828125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(594.84375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(622.96875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(679.125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(707.25 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(741.34375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(801.3125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(825.53125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(849.75 0)"/>+ <use xlink:href="#Inter-Regular-3d8" transform="translate(907.90625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(989.75 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1035.75 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(1094.875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1156.109375 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(1184.234375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1245.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1304.59375 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1362.890625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1415.671875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1448.390625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1472.609375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1532.578125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1591.65625 0)"/>+ <use xlink:href="#Inter-Regular-3d8" transform="translate(1619.78125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1701.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1725.84375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1758.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1817.6875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1845.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1901.96875 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(1930.09375 0)"/>+ <use xlink:href="#Inter-Regular-124" transform="translate(1970.765625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(2061.09375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2107.09375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2138.84375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(2198.8125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2251.453125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2309.75 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2368.828125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(2396.953125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2454.078125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2514.046875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2573.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2604.875 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(2660.921875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2717.46875 0)"/>+ <use xlink:href="#Inter-Regular-5e4" transform="translate(2750.1875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2780.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2808.484375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2869.71875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2905.703125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(2964 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3001.015625 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(3025.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3079.828125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3107.953125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3164.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(3223.1875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3284.421875 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(3312.546875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3373.78125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3432.90625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3491.203125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3543.984375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3576.703125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3600.921875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3660.890625 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(3719.96875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3765.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(3818.75 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3879.984375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(3938.28125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3995.40625 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(4019.625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4056.640625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4080.859375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4137.984375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4166.109375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4197.859375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(4257.828125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4310.46875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(4368.765625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4427.84375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4480.625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4508.75 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4596.34375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4655.625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4711.78125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(4764.5625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4823.6875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4859.671875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(4917.96875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4979.203125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5007.328125 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(5067.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5126.375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5154.5 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5187.21875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5246.34375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5304.640625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5332.765625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5394 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(5450.34375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5504.59375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5562.890625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5587.109375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(5647.078125 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(5708.3125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5795.90625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(5854.203125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5913.28125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5946 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(5974.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6010.109375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6068.40625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6129.640625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(6189.609375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6242.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6266.609375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6298.359375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6358.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6396.953125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6421.171875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(6479.46875 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(6532.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6561.0625 0)"/>+ <use xlink:href="#Inter-Regular-49" transform="translate(6589.1875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(6662.234375 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(6722.203125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6809.796875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(6871.03125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6930.15625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6961.90625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(7020.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7081.4375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(7109.5625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7165.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7198.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7226.5625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(7259.28125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(7318.40625 0)"/>+ </g>+ </g>+ <g id="text_5">+ <!-- list prices of 2026-10-26, not billed. Output is billed on top. -->+ <g style="fill: #5b6474" transform="translate(48 172) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Regular-53f" d="M 481 0+L 481 428+L 2028 2106+Q 2288 2388 2459 2600+Q 2631 2813 2718 3005+Q 2806 3197 2806 3413+Q 2806 3778 2554 3990+Q 2303 4203 1931 4203+Q 1534 4203 1298 3965+Q 1063 3728 1063 3334+L 494 3334+Q 494 3747 684 4059+Q 875 4372 1203 4545+Q 1531 4719 1947 4719+Q 2363 4719 2683 4545+Q 3003 4372 3186 4078+Q 3369 3784 3369 3419+Q 3369 3166 3278 2927+Q 3188 2688 2959 2384+Q 2731 2081 2319 1644+L 1300 559+L 1300 522+L 3447 522+L 3447 0+L 481 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-53d" d="M 2019 -63+Q 1241 -63 811 562+Q 381 1188 381 2325+Q 381 3456 814 4087+Q 1247 4719 2019 4719+Q 2794 4719 3225 4087+Q 3656 3456 3656 2325+Q 3656 1188 3228 562+Q 2800 -63 2019 -63+z+M 2019 456+Q 2531 456 2807 948+Q 3084 1441 3084 2325+Q 3084 3216 2807 3709+Q 2531 4203 2019 4203+Q 1509 4203 1231 3708+Q 953 3213 953 2325+Q 953 1441 1231 948+Q 1509 456 2019 456+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-545" d="M 2019 -63+Q 1728 -63 1437 43+Q 1147 150 908 400+Q 669 650 525 1078+Q 381 1506 381 2150+Q 381 3378 840 4048+Q 1300 4719 2091 4719+Q 2481 4719 2790 4562+Q 3100 4406 3297 4128+Q 3494 3850 3550 3484+L 2969 3484+Q 2891 3788 2672 3991+Q 2453 4194 2091 4194+Q 1553 4194 1248 3730+Q 944 3266 944 2425+L 981 2425+Q 1169 2716 1467 2880+Q 1766 3044 2128 3044+Q 2528 3044 2859 2847+Q 3191 2650 3389 2301+Q 3588 1953 3588 1503+Q 3588 1069 3394 714+Q 3200 359 2847 148+Q 2494 -63 2019 -63+z+M 2019 459+Q 2300 459 2525 600+Q 2750 741 2881 977+Q 3013 1213 3013 1503+Q 3013 1788 2886 2020+Q 2759 2253 2537 2390+Q 2316 2528 2034 2528+Q 1753 2528 1525 2384+Q 1297 2241 1162 2005+Q 1028 1769 1028 1497+Q 1028 1222 1156 986+Q 1284 750 1509 604+Q 1734 459 2019 459+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5bf" d="M 2494 2581+L 2494 2062+L 450 2062+L 450 2581+L 2494 2581+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5dd" d="M 400 -1122+L 675 650+L 1319 650+L 831 -1122+L 400 -1122+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-141" d="M 2450 -63+Q 1853 -63 1386 226+Q 919 516 650 1052+Q 381 1588 381 2325+Q 381 3066 650 3602+Q 919 4138 1386 4428+Q 1853 4719 2450 4719+Q 3047 4719 3512 4428+Q 3978 4138 4245 3602+Q 4513 3066 4513 2325+Q 4513 1588 4245 1052+Q 3978 516 3512 226+Q 3047 -63 2450 -63+z+M 2450 488+Q 2866 488 3202 698+Q 3538 909 3736 1320+Q 3934 1731 3934 2325+Q 3934 2925 3736 3336+Q 3538 3747 3202 3958+Q 2866 4169 2450 4169+Q 2031 4169 1693 3956+Q 1356 3744 1157 3333+Q 959 2922 959 2325+Q 959 1731 1157 1322+Q 1356 913 1693 700+Q 2031 488 2450 488+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-2e0"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(24.21875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(48.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(101.21875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(133.9375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(162.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(223.296875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(261.921875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(286.140625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(343.265625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(401.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(454.34375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(482.46875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(542.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(579.453125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(607.578125 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(668.5625 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(731.65625 0)"/>+ <use xlink:href="#Inter-Regular-545" transform="translate(792.640625 0)"/>+ <use xlink:href="#Inter-Regular-5bf" transform="translate(854.65625 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(900.65625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(941.328125 0)"/>+ <use xlink:href="#Inter-Regular-5bf" transform="translate(1004.421875 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(1047.046875 0)"/>+ <use xlink:href="#Inter-Regular-545" transform="translate(1108.03125 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1166.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1195.484375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1223.609375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1282.6875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1342.65625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1375.375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(1403.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1464.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1488.953125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1513.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1537.390625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1595.6875 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1656.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1685.734375 0)"/>+ <use xlink:href="#Inter-Regular-141" transform="translate(1713.859375 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1790.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1849.453125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(1882.171875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(1943.40625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2002.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2035.25 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(2063.375 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2087.59375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2140.375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(2168.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(2229.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2253.953125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2278.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2302.390625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(2360.6875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2421.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2450.046875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(2510.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2569.09375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2597.21875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2628.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2688.9375 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(2750.171875 0)"/>+ </g>+ </g>+ <g id="text_6">+ <!-- Without the cache -->+ <g style="fill: #2e3440" transform="translate(76 212) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-1cb" d="M 1422 0+L 159 4656+L 909 4656+L 1581 1988+Q 1656 1681 1722 1348+Q 1788 1016 1847 678+Q 1913 1016 1980 1348+Q 2047 1681 2128 1988+L 2819 4656+L 3600 4656+L 4284 1988+Q 4363 1684 4431 1356+Q 4500 1028 4566 697+Q 4625 1028 4692 1356+Q 4759 1684 4831 1988+L 5503 4656+L 6259 4656+L 4991 0+L 4169 0+L 3428 2759+Q 3366 2994 3311 3259+Q 3256 3525 3206 3828+Q 3156 3541 3104 3280+Q 3053 3019 2984 2759+L 2247 0+L 1422 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2b1" d="M 463 0+L 463 3494+L 1150 3494+L 1150 0+L 463 0+z+M 809 4028+Q 631 4028 504 4147+Q 378 4266 378 4434+Q 378 4606 504 4725+Q 631 4844 809 4844+Q 987 4844 1115 4725+Q 1243 4606 1243 4434+Q 1243 4266 1115 4147+Q 987 4028 809 4028+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-379" d="M 1956 3494+L 1956 2934+L 1259 2934+L 1259 944+Q 1259 734 1348 636+Q 1438 538 1641 538+Q 1697 538 1783 550+Q 1869 563 1931 575+L 2053 25+Q 1944 -13 1817 -30+Q 1691 -47 1572 -47+Q 1097 -47 834 198+Q 572 444 572 888+L 572 2934+L 63 2934+L 63 3494+L 572 3494+L 572 4325+L 1259 4325+L 1259 3494+L 1956 3494+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-29e" d="M 1150 2069+L 1150 0+L 463 0+L 463 4656+L 1144 4656+L 1144 2866+Q 1309 3213 1575 3375+Q 1841 3538 2200 3538+Q 2734 3538 3062 3202+Q 3391 2866 3391 2219+L 3391 0+L 2700 0+L 2700 2134+Q 2700 2513 2503 2725+Q 2306 2938 1963 2938+Q 1613 2938 1381 2711+Q 1150 2484 1150 2069+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-316" d="M 1931 -72+Q 1441 -72 1073 153+Q 706 378 503 783+Q 300 1188 300 1728+Q 300 2272 503 2680+Q 706 3088 1073 3313+Q 1441 3538 1931 3538+Q 2425 3538 2792 3313+Q 3159 3088 3362 2680+Q 3566 2272 3566 1728+Q 3566 1188 3362 783+Q 3159 378 2792 153+Q 2425 -72 1931 -72+z+M 1931 509+Q 2250 509 2458 676+Q 2666 844 2767 1120+Q 2869 1397 2869 1728+Q 2869 2063 2767 2342+Q 2666 2622 2458 2789+Q 2250 2956 1931 2956+Q 1616 2956 1409 2789+Q 1203 2622 1101 2342+Q 1000 2063 1000 1728+Q 1000 1397 1101 1120+Q 1203 844 1409 676+Q 1616 509 1931 509+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-393" d="M 1653 -44+Q 1119 -44 791 292+Q 463 628 463 1275+L 463 3494+L 1150 3494+L 1150 1359+Q 1150 981 1348 768+Q 1547 556 1888 556+Q 2238 556 2469 782+Q 2700 1009 2700 1425+L 2700 3494+L 3391 3494+L 3391 0+L 2731 0+L 2728 678+Q 2563 297 2289 126+Q 2016 -44 1653 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-6f1" transform="scale(0.015625)"/>+ <path id="Inter-Medium-266" d="M 1969 -72+Q 1453 -72 1078 150+Q 703 372 501 775+Q 300 1178 300 1722+Q 300 2259 498 2668+Q 697 3078 1059 3308+Q 1422 3538 1909 3538+Q 2306 3538 2664 3361+Q 3022 3184 3245 2798+Q 3469 2413 3469 1781+L 3469 1538+L 991 1538+Q 1009 1031 1278 764+Q 1547 497 1975 497+Q 2263 497 2470 622+Q 2678 747 2769 991+L 3416 838+Q 3291 428 2909 178+Q 2528 -72 1969 -72+z+M 994 2050+L 2788 2050+Q 2750 2463 2529 2716+Q 2309 2969 1913 2969+Q 1500 2969 1261 2698+Q 1022 2428 994 2050+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-24a" d="M 1931 -72+Q 1438 -72 1072 153+Q 706 378 503 783+Q 300 1188 300 1728+Q 300 2272 503 2680+Q 706 3088 1072 3313+Q 1438 3538 1931 3538+Q 2475 3538 2870 3264+Q 3266 2991 3394 2506+L 2741 2350+Q 2669 2622 2461 2789+Q 2253 2956 1934 2956+Q 1619 2956 1411 2790+Q 1203 2625 1101 2345+Q 1000 2066 1000 1728+Q 1000 1394 1101 1117+Q 1203 841 1411 675+Q 1619 509 1934 509+Q 2259 509 2471 682+Q 2684 856 2753 1141+L 3403 984+Q 3275 491 2878 209+Q 2481 -72 1931 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-1fb" d="M 1441 -78+Q 1106 -78 839 45+Q 572 169 415 406+Q 259 644 259 988+Q 259 1284 375 1476+Q 491 1669 684 1780+Q 878 1891 1117 1947+Q 1356 2003 1603 2031+Q 2066 2084 2275 2123+Q 2484 2163 2484 2347+L 2484 2366+Q 2484 2656 2314 2817+Q 2144 2978 1816 2978+Q 1472 2978 1275 2828+Q 1078 2678 1006 2500+L 359 2669+Q 478 2981 700 3172+Q 922 3363 1208 3450+Q 1494 3538 1806 3538+Q 2016 3538 2253 3488+Q 2491 3438 2700 3308+Q 2909 3178 3040 2937+Q 3172 2697 3172 2319+L 3172 0+L 2506 0+L 2506 478+L 2472 478+Q 2369 272 2117 97+Q 1866 -78 1441 -78+z+M 1594 475+Q 1872 475 2072 586+Q 2272 697 2380 875+Q 2488 1053 2488 1259+L 2488 1706+Q 2438 1656 2273 1620+Q 2109 1584 1928 1559+Q 1747 1534 1641 1522+Q 1350 1481 1142 1364+Q 934 1247 934 978+Q 934 728 1120 601+Q 1306 475 1594 475+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-1cb"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(100.296875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(125.5 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(159.625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(219.78125 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(280.1875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(340.34375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(374.375 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(401.03125 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(435.15625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(495.3125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(554.046875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(580.703125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(639.40625 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(696.1875 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(753.90625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(814.0625 0)"/>+ </g>+ </g>+ <g id="text_7">+ <!-- With the cache -->+ <g style="fill: #2e3440" transform="translate(318.59375 212) scale(0.2 -0.2)">+ <use xlink:href="#Inter-Medium-1cb"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(100.296875 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(125.5 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(159.625 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(219.78125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(246.4375 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(280.5625 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(340.71875 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(399.453125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(426.109375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(484.8125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(541.59375 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(599.3125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(659.46875 0)"/>+ </g>+ </g>+ <g id="text_8">+ <!-- Shared prefix: the part of the context that is the same for every question about a repository at one commit, billed at the cached-input price after the first question. Truncation's -->+ <g style="fill: #5b6474" transform="translate(48 821) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-18d" d="M 2053 -81+Q 1297 -81 850 276+Q 403 634 363 1219+L 972 1219+Q 997 956 1150 786+Q 1303 616 1542 533+Q 1781 450 2053 450+Q 2369 450 2620 553+Q 2872 656 3019 843+Q 3166 1031 3166 1278+Q 3166 1503 3039 1643+Q 2913 1784 2703 1875+Q 2494 1966 2244 2034+L 1681 2194+Q 1119 2353 806 2650+Q 494 2947 494 3409+Q 494 3803 706 4098+Q 919 4394 1281 4556+Q 1644 4719 2094 4719+Q 2553 4719 2906 4556+Q 3259 4394 3464 4114+Q 3669 3834 3681 3481+L 3100 3481+Q 3059 3822 2775 4008+Q 2491 4194 2075 4194+Q 1622 4194 1347 3980+Q 1072 3766 1072 3438+Q 1072 3194 1223 3045+Q 1375 2897 1583 2814+Q 1791 2731 1959 2684+L 2425 2556+Q 2613 2506 2839 2418+Q 3066 2331 3272 2186+Q 3478 2041 3611 1817+Q 3744 1594 3744 1269+Q 3744 888 3545 581+Q 3347 275 2969 97+Q 2591 -81 2053 -81+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5e1" d="M 922 -41+Q 747 -41 623 82+Q 500 206 500 381+Q 500 556 623 679+Q 747 803 922 803+Q 1097 803 1220 679+Q 1344 556 1344 381+Q 1344 206 1220 82+Q 1097 -41 922 -41+z+M 922 2487+Q 747 2487 623 2610+Q 500 2734 500 2909+Q 500 3084 623 3207+Q 747 3331 922 3331+Q 1097 3331 1220 3207+Q 1344 3084 1344 2909+Q 1344 2734 1220 2610+Q 1097 2487 922 2487+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-19b" d="M 306 4131+L 306 4656+L 3825 4656+L 3825 4131+L 2366 4131+L 2366 0+L 1772 0+L 1772 4131+L 306 4131+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-5cc" d="M 725 2884+L 656 4656+L 1263 4656+L 1194 2884+L 725 2884+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-18d"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(123.28125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(179.4375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(215.421875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(273.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(334.953125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(363.078125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(424.3125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(460.296875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(518.59375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(555.609375 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(579.828125 0)"/>+ <use xlink:href="#Inter-Regular-5e1" transform="translate(634.421875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(663.234375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(691.359375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(724.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(783.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(841.5 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(869.625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(931.84375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(988 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1027.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1059.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1088.046875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(1148.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1185.03125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1213.15625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1245.875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1305 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1363.296875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1391.421875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1448.546875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1508.515625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1567.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1599.34375 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(1655.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1711.9375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1744.65625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1772.78125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1805.5 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1864.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1920.78125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1953.5 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1981.625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2005.84375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2058.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2086.75 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2119.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2178.59375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2236.890625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2265.015625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2317.796875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(2373.953125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2461.546875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2519.84375 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(2547.96875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(2582.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2642.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2679.671875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2707.796875 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(2764.140625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2818.390625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(2876.6875 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(2915.890625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2972.09375 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(3000.21875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3061.453125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3120.578125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3178.875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3231.65625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3264.375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3288.59375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(3348.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3407.640625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3435.765625 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(3491.921875 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3553.15625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(3613.125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3672.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3704.96875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3733.09375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3789.25 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3817.375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3853.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(3911.65625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(3972.890625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4032.859375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4085.640625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4109.859375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4141.609375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4201.578125 0)"/>+ <use xlink:href="#Inter-Regular-3e6" transform="translate(4240.78125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4296.984375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4325.109375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4381.265625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4413.984375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4442.109375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(4502.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4561.15625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4619.453125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4647.578125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4704.703125 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4764.671875 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4852.265625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4939.859375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4964.078125 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(4996.796875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5025.609375 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(5053.734375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(5114.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5139.1875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(5163.40625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5187.625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5245.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5307.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(5335.28125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5391.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5424.15625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5452.28125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5485 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5544.125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5602.421875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(5630.546875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(5688.65625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(5744.8125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5801.9375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5861.0625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(5919.359375 0)"/>+ <use xlink:href="#Inter-Regular-5b3" transform="translate(5980.59375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6026.59375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(6050.8125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6109.890625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(6171.125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6230.25 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6262.96875 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(6291.09375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6352.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(6390.953125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(6415.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6472.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6530.59375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(6558.71875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(6614.875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6648.46875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6680.21875 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(6738.515625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6776.15625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(6804.28125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(6837 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(6896.125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(6954.421875 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(6982.546875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(7019.5625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(7043.78125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(7081.421875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7134.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7166.921875 0)"/>+ <use xlink:href="#Inter-Regular-351" transform="translate(7195.046875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(7256.28125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(7315.40625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(7373.703125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7426.484375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(7459.203125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(7483.421875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(7543.390625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(7602.46875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(7631.28125 0)"/>+ <use xlink:href="#Inter-Regular-19b" transform="translate(7659.40625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(7718.296875 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(7755.9375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(7815.0625 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(7874.140625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(7932.25 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(7988.40625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(8021.125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(8045.34375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(8105.3125 0)"/>+ <use xlink:href="#Inter-Regular-5cc" transform="translate(8164.390625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(8194.375 0)"/>+ </g>+ </g>+ <g id="text_9">+ <!-- dump is all shared prefix, so it is cached like the stable pack. Whether a call is served from the cache is up to the API. -->+ <g style="fill: #5b6474" transform="translate(48 846) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-1cb" d="M 1431 0+L 163 4656+L 769 4656+L 1506 1800+Q 1581 1500 1650 1190+Q 1719 881 1781 553+Q 1844 881 1912 1190+Q 1981 1500 2063 1800+L 2816 4656+L 3491 4656+L 4238 1800+Q 4394 1216 4522 572+Q 4581 894 4651 1198+Q 4722 1503 4797 1800+L 5531 4656+L 6144 4656+L 4869 0+L 4178 0+L 3378 2950+Q 3319 3172 3261 3425+Q 3203 3678 3150 3984+Q 3097 3700 3044 3451+Q 2991 3203 2922 2950+L 2125 0+L 1431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-2" d="M 163 0+L 1853 4656+L 2541 4656+L 4253 0+L 3628 0+L 3163 1300+L 1244 1300+L 794 0+L 163 0+z+M 1425 1819+L 2978 1819+L 2641 2763+Q 2556 2997 2450 3336+Q 2344 3675 2194 4181+Q 2047 3666 1937 3322+Q 1828 2978 1753 2763+L 1425 1819+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-177" d="M 563 0+L 563 4656+L 2156 4656+Q 2700 4656 3051 4457+Q 3403 4259 3573 3925+Q 3744 3591 3744 3175+Q 3744 2759 3573 2421+Q 3403 2084 3053 1884+Q 2703 1684 2159 1684+L 1156 1684+L 1156 0+L 563 0+z+M 1156 2206+L 2131 2206+Q 2684 2206 2918 2482+Q 3153 2759 3153 3175+Q 3153 3588 2918 3861+Q 2684 4134 2125 4134+L 1156 4134+L 1156 2206+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-255"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(61.234375 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(120.359375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(207.953125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(269.1875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(297.3125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(321.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(374.3125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(402.4375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(458.59375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(482.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(507.03125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(535.15625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(587.9375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(647.0625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(703.21875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(739.203125 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(797.5 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(858.734375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(886.859375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(948.09375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(984.078125 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(1042.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1079.390625 0)"/>+ <use xlink:href="#Inter-Regular-3e1" transform="translate(1103.609375 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1158.203125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1187.015625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1215.140625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1267.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1327.890625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1356.015625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1380.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1412.953125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1441.078125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1465.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1518.078125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1546.203125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1604.3125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1660.46875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1717.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1776.71875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1835.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1896.25 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(1924.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(1948.59375 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1972.8125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2025.453125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2083.75 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2111.875 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2144.59375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2203.71875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2262.015625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(2290.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(2342.921875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2376.125 0)"/>+ <use xlink:href="#Inter-Regular-242" transform="translate(2432.28125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(2493.515625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(2517.734375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2576.03125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(2604.15625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(2666.375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(2722.53125 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(2779.65625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(2834.546875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(2863.359375 0)"/>+ <use xlink:href="#Inter-Regular-1cb" transform="translate(2891.484375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(2990.015625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3049.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(3107.4375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(3140.15625 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3199.28125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3257.578125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3295.21875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3323.34375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3379.5 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(3407.625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(3465.734375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(3521.890625 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(3546.109375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3570.328125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(3598.453125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3622.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(3675.453125 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(3703.578125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3756.359375 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(3814.65625 0)"/>+ <use xlink:href="#Inter-Regular-3d4" transform="translate(3853.859375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(3908.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(3966.40625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4027.640625 0)"/>+ <use xlink:href="#Inter-Regular-287" transform="translate(4055.765625 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(4092.78125 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(4128.765625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(4188.734375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4276.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(4304.453125 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(4337.171875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4396.296875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4454.59375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4482.71875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(4540.828125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(4596.984375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(4654.109375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(4713.234375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4771.53125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(4799.65625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(4823.875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(4876.65625 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(4904.78125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(4963.90625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5025.140625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5053.265625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(5085.015625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5144.984375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(5173.109375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(5205.828125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(5264.953125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(5323.25 0)"/>+ <use xlink:href="#Inter-Regular-2" transform="translate(5351.375 0)"/>+ <use xlink:href="#Inter-Regular-177" transform="translate(5420.375 0)"/>+ <use xlink:href="#Inter-Regular-c5" transform="translate(5484.25 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(5511.109375 0)"/>+ </g>+ </g>+ <g id="text_10">+ <!-- Method and data: -->+ <g style="fill: #5b6474" transform="translate(48 871) scale(0.18 -0.18)">+ <use xlink:href="#Inter-Regular-124"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(90.328125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(148.625 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(181.34375 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(240.46875 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(300.4375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(361.671875 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(389.796875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(445.953125 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(505.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(566.265625 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(594.390625 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(655.625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(711.78125 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(744.984375 0)"/>+ <use xlink:href="#Inter-Regular-5e1" transform="translate(801.140625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(829.953125 0)"/>+ </g>+ </g>+ <g id="text_11">+ <!-- github.com/graphicle-ai/graphicle/blob/main/docs/benchmarks/whole-repo.md -->+ <g style="fill: #5b6474" transform="translate(202.46875 871) scale(0.17 -0.17)">+ <defs>+ <path id="JetBrainsMono-Regular-f5" d="M 1030 -1152+L 1030 -627+L 2022 -627+Q 2323 -627 2496 -457+Q 2669 -288 2669 0+L 2669 320+L 2682 896+L 2662 896+Q 2611 582 2361 412+Q 2112 243 1734 243+Q 1190 243 876 588+Q 563 934 563 1536+L 563 2278+Q 563 2880 876 3232+Q 1190 3584 1734 3584+Q 2112 3584 2361 3405+Q 2611 3226 2662 2912+L 2675 2912+L 2675 3520+L 3245 3520+L 3245 0+Q 3245 -531 2915 -841+Q 2586 -1152 2016 -1152+L 1030 -1152+z+M 1907 723+Q 2266 723 2470 947+Q 2675 1171 2675 1568+L 2675 2240+Q 2675 2637 2470 2861+Q 2266 3085 1907 3085+Q 1542 3085 1340 2873+Q 1139 2662 1139 2304+L 1139 1504+Q 1139 1146 1340 934+Q 1542 723 1907 723+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-ff" d="M 544 0+L 544 525+L 1792 525+L 1792 2995+L 672 2995+L 672 3520+L 2368 3520+L 2368 525+L 3552 525+L 3552 0+L 544 0+z+M 2016 4154+Q 1805 4154 1683 4262+Q 1562 4371 1562 4557+Q 1562 4749 1683 4861+Q 1805 4973 2016 4973+Q 2227 4973 2348 4861+Q 2470 4749 2470 4557+Q 2470 4371 2348 4262+Q 2227 4154 2016 4154+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-14c" d="M 2272 0+Q 1837 0 1574 253+Q 1312 506 1312 928+L 1312 2995+L 301 2995+L 301 3520+L 1312 3520+L 1312 4512+L 1888 4512+L 1888 3520+L 3328 3520+L 3328 2995+L 1888 2995+L 1888 928+Q 1888 749 1993 637+Q 2099 525 2272 525+L 3296 525+L 3296 0+L 2272 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-fc" d="M 589 0+L 589 4672+L 1165 4672+L 1165 2848+L 1171 2848+Q 1216 3200 1459 3392+Q 1702 3584 2106 3584+Q 2637 3584 2950 3257+Q 3264 2931 3264 2368+L 3264 0+L 2688 0+L 2688 2272+Q 2688 2669 2486 2883+Q 2285 3098 1939 3098+Q 1581 3098 1373 2874+Q 1165 2650 1165 2240+L 1165 0+L 589 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-151" d="M 1914 -64+Q 1306 -64 941 297+Q 576 659 576 1280+L 576 3520+L 1152 3520+L 1152 1280+Q 1152 896 1357 669+Q 1562 442 1914 442+Q 2272 442 2480 669+Q 2688 896 2688 1280+L 2688 3520+L 3264 3520+L 3264 1280+Q 3264 659 2893 297+Q 2522 -64 1914 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-d6" d="M 2125 -64+Q 1728 -64 1472 131+Q 1216 326 1171 672+L 1165 672+L 1165 0+L 589 0+L 589 4672+L 1165 4672+L 1165 3648+L 1152 2848+L 1158 2848+Q 1210 3187 1469 3385+Q 1728 3584 2125 3584+Q 2656 3584 2969 3232+Q 3283 2880 3283 2272+L 3283 1242+Q 3283 640 2969 288+Q 2656 -64 2125 -64+z+M 1933 435+Q 2298 435 2502 627+Q 2707 819 2707 1248+L 2707 2272+Q 2707 2707 2502 2896+Q 2298 3085 1933 3085+Q 1581 3085 1373 2861+Q 1165 2637 1165 2240+L 1165 1280+Q 1165 883 1373 659+Q 1581 435 1933 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-329" d="M 1920 -64+Q 1683 -64 1539 77+Q 1395 218 1395 442+Q 1395 678 1539 825+Q 1683 973 1920 973+Q 2157 973 2301 825+Q 2445 678 2445 442+Q 2445 218 2301 77+Q 2157 -64 1920 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-d7" d="M 1971 -64+Q 1331 -64 947 294+Q 563 653 563 1280+L 563 2240+Q 563 2867 947 3225+Q 1331 3584 1971 3584+Q 2579 3584 2953 3257+Q 3328 2931 3347 2368+L 2771 2368+Q 2752 2707 2541 2889+Q 2330 3072 1971 3072+Q 1594 3072 1366 2857+Q 1139 2643 1139 2246+L 1139 1280+Q 1139 883 1366 665+Q 1594 448 1971 448+Q 2330 448 2541 633+Q 2752 819 2771 1152+L 3347 1152+Q 3328 589 2953 262+Q 2579 -64 1971 -64+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-122" d="M 1920 -51+Q 1286 -51 912 320+Q 538 691 538 1357+L 538 2163+Q 538 2835 909 3203+Q 1280 3571 1920 3571+Q 2560 3571 2931 3203+Q 3302 2835 3302 2163+L 3302 1357+Q 3302 691 2928 320+Q 2554 -51 1920 -51+z+M 1920 461+Q 2298 461 2512 672+Q 2726 883 2726 1293+L 2726 2227+Q 2726 2637 2512 2848+Q 2298 3059 1920 3059+Q 1549 3059 1331 2848+Q 1114 2637 1114 2227+L 1114 1293+Q 1114 883 1331 672+Q 1549 461 1920 461+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-11a" d="M 384 0+L 384 3520+L 883 3520+L 883 3053+L 896 3053+Q 928 3290 1085 3437+Q 1242 3584 1485 3584+Q 1715 3584 1875 3449+Q 2035 3315 2106 3085+L 2112 3085+Q 2157 3315 2313 3449+Q 2470 3584 2714 3584+Q 3053 3584 3254 3331+Q 3456 3078 3456 2675+L 3456 0+L 2918 0+L 2918 2682+Q 2918 2893 2816 3017+Q 2714 3142 2534 3142+Q 2362 3142 2259 3020+Q 2157 2899 2157 2688+L 2157 0+L 1683 0+L 1683 2682+Q 1683 2893 1580 3017+Q 1478 3142 1306 3142+Q 1126 3142 1024 3020+Q 922 2899 922 2688+L 922 0+L 384 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-33d" d="M 480 -704+L 2752 5312+L 3360 5312+L 1088 -704+L 480 -704+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-140" d="M 717 0+L 717 3520+L 1293 3520+L 1293 2848+L 1306 2848+Q 1350 3187 1593 3385+Q 1837 3584 2246 3584+Q 2797 3584 3094 3254+Q 3392 2925 3392 2317+L 3392 2016+L 2816 2016+L 2816 2317+Q 2816 3085 2067 3085+Q 1690 3085 1491 2867+Q 1293 2650 1293 2240+L 1293 0+L 717 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-bd" d="M 1613 -64+Q 1069 -64 749 240+Q 429 544 429 1037+Q 429 1363 576 1606+Q 723 1850 985 1987+Q 1248 2125 1587 2125+L 2675 2125+L 2675 2400+Q 2675 3085 1926 3085+Q 1594 3085 1389 2963+Q 1184 2842 1171 2624+L 595 2624+Q 627 3040 982 3312+Q 1338 3584 1926 3584+Q 2566 3584 2908 3277+Q 3251 2970 3251 2419+L 3251 0+L 2682 0+L 2682 640+L 2669 640+Q 2618 314 2342 125+Q 2067 -64 1613 -64+z+M 1754 422+Q 2176 422 2425 627+Q 2675 832 2675 1184+L 2675 1677+L 1651 1677+Q 1370 1677 1194 1507+Q 1018 1338 1018 1056+Q 1018 762 1213 592+Q 1408 422 1754 422+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-13d" d="M 589 -1152+L 589 3520+L 1165 3520+L 1165 2848+L 1171 2848+Q 1216 3194 1472 3389+Q 1728 3584 2125 3584+Q 2656 3584 2969 3235+Q 3283 2886 3283 2278+L 3283 1248+Q 3283 640 2969 288+Q 2656 -64 2125 -64+Q 1728 -64 1472 134+Q 1216 333 1171 672+L 1152 672+L 1165 -128+L 1165 -1152+L 589 -1152+z+M 1933 435+Q 2298 435 2502 627+Q 2707 819 2707 1248+L 2707 2272+Q 2707 2707 2502 2896+Q 2298 3085 1933 3085+Q 1581 3085 1373 2861+Q 1165 2637 1165 2240+L 1165 1280+Q 1165 883 1373 659+Q 1581 435 1933 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-113" d="M 2432 0+Q 1965 0 1686 272+Q 1408 544 1408 992+L 1408 4147+L 192 4147+L 192 4672+L 1984 4672+L 1984 992+Q 1984 774 2105 649+Q 2227 525 2432 525+L 3520 525+L 3520 0+L 2432 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-e1" d="M 1920 -64+Q 1299 -64 918 310+Q 538 685 538 1344+L 538 2176+Q 538 2835 918 3209+Q 1299 3584 1920 3584+Q 2336 3584 2646 3417+Q 2957 3251 3129 2950+Q 3302 2650 3302 2240+L 3302 1613+L 1101 1613+L 1101 1280+Q 1101 890 1325 662+Q 1549 435 1920 435+Q 2240 435 2448 560+Q 2656 685 2701 896+L 3277 896+Q 3219 454 2848 195+Q 2477 -64 1920 -64+z+M 1101 2061+L 2739 2061+L 2739 2240+Q 2739 2656 2524 2883+Q 2310 3110 1920 3110+Q 1530 3110 1315 2883+Q 1101 2656 1101 2240+L 1101 2061+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-357" d="M 896 1856+L 896 2368+L 2944 2368+L 2944 1856+L 896 1856+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-11b" d="M 589 0+L 589 3520+L 1165 3520+L 1165 2848+L 1171 2848+Q 1216 3200 1459 3392+Q 1702 3584 2106 3584+Q 2637 3584 2950 3257+Q 3264 2931 3264 2368+L 3264 0+L 2688 0+L 2688 2266+Q 2688 2669 2486 2883+Q 2285 3098 1939 3098+Q 1581 3098 1373 2874+Q 1165 2650 1165 2240+L 1165 0+L 589 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-dd" d="M 1715 -64+Q 1190 -64 873 288+Q 557 640 557 1242+L 557 2272+Q 557 2880 870 3232+Q 1184 3584 1715 3584+Q 2112 3584 2371 3385+Q 2630 3187 2682 2848+L 2688 2848+L 2675 3648+L 2675 4672+L 3251 4672+L 3251 0+L 2675 0+L 2675 672+L 2669 672+Q 2624 326 2368 131+Q 2112 -64 1715 -64+z+M 1907 435+Q 2266 435 2470 659+Q 2675 883 2675 1280+L 2675 2240+Q 2675 2637 2470 2861+Q 2266 3085 1907 3085+Q 1542 3085 1337 2896+Q 1133 2707 1133 2272+L 1133 1248+Q 1133 819 1337 627+Q 1542 435 1907 435+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-144" d="M 1779 -51+Q 1190 -51 867 214+Q 544 480 544 966+L 1120 966+Q 1120 723 1293 585+Q 1466 448 1779 448+L 2061 448+Q 2381 448 2557 589+Q 2733 730 2733 986+Q 2733 1440 2317 1498+L 1344 1638+Q 986 1690 787 1936+Q 589 2182 589 2586+Q 589 3046 905 3308+Q 1222 3571 1779 3571+L 2061 3571+Q 2573 3571 2896 3318+Q 3219 3066 3245 2656+L 2662 2656+Q 2650 2842 2486 2963+Q 2323 3085 2061 3085+L 1779 3085+Q 1485 3085 1318 2950+Q 1152 2816 1152 2586+Q 1152 2214 1491 2163+L 2400 2035+Q 3296 1907 3296 986+Q 3296 493 2973 221+Q 2650 -51 2061 -51+L 1779 -51+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-110" d="M 621 0+L 621 4672+L 1197 4672+L 1197 2067+L 1869 2067+L 2854 3520+L 3514 3520+L 2381 1843+L 3578 0+L 2906 0+L 1882 1568+L 1197 1568+L 1197 0+L 621 0+z+" transform="scale(0.015625)"/>+ <path id="JetBrainsMono-Regular-16a" d="M 774 0+L 198 3520+L 698 3520+L 1056 1037+Q 1075 896 1094 726+Q 1114 557 1120 448+Q 1133 557 1149 726+Q 1165 896 1190 1037+L 1632 3520+L 2208 3520+L 2650 1037+Q 2675 896 2697 726+Q 2720 557 2726 448+Q 2739 557 2758 726+Q 2778 896 2797 1037+L 3168 3520+L 3642 3520+L 3040 0+L 2406 0+L 2003 2432+Q 1978 2611 1955 2812+Q 1933 3014 1920 3123+Q 1914 3014 1888 2812+Q 1862 2611 1830 2432+L 1408 0+L 774 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#JetBrainsMono-Regular-f5"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(60 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-14c" transform="translate(120 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(180 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-151" transform="translate(240 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(300 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-329" transform="translate(360 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(420 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(480 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(540 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(600 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-f5" transform="translate(660 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(720 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(780 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(840 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(900 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(960 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(1020 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(1080 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(1140 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-357" transform="translate(1200 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(1260 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(1320 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(1380 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-f5" transform="translate(1440 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(1500 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(1560 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(1620 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(1680 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(1740 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(1800 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(1860 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(1920 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(1980 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2040 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(2100 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(2160 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2220 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2280 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(2340 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(2400 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-ff" transform="translate(2460 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11b" transform="translate(2520 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2580 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-dd" transform="translate(2640 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(2700 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(2760 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-144" transform="translate(2820 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(2880 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d6" transform="translate(2940 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(3000 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11b" transform="translate(3060 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-d7" transform="translate(3120 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(3180 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(3240 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-bd" transform="translate(3300 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(3360 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-110" transform="translate(3420 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-144" transform="translate(3480 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-33d" transform="translate(3540 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-16a" transform="translate(3600 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-fc" transform="translate(3660 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(3720 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-113" transform="translate(3780 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(3840 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-357" transform="translate(3900 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-140" transform="translate(3960 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-e1" transform="translate(4020 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-13d" transform="translate(4080 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-122" transform="translate(4140 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-329" transform="translate(4200 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-11a" transform="translate(4260 0)"/>+ <use xlink:href="#JetBrainsMono-Regular-dd" transform="translate(4320 0)"/>+ </g>+ </g>+ <g id="text_12">+ <!-- Pack, standard layout -->+ <g style="fill: #2e3440" transform="translate(48 348.198571) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-177" d="M 516 0+L 516 4656+L 2184 4656+Q 2722 4656 3081 4457+Q 3441 4259 3619 3917+Q 3797 3575 3797 3144+Q 3797 2713 3617 2370+Q 3438 2028 3078 1829+Q 2719 1631 2178 1631+L 1228 1631+L 1228 0+L 516 0+z+M 1228 2234+L 2109 2234+Q 2622 2234 2848 2492+Q 3075 2750 3075 3144+Q 3075 3538 2848 3792+Q 2622 4047 2103 4047+L 1228 4047+L 1228 2234+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2d7" d="M 463 0+L 463 4656+L 1150 4656+L 1150 2019+L 1213 2019+L 2591 3494+L 3416 3494+L 2009 1988+L 3513 0+L 2663 0+L 1484 1566+L 1150 1231+L 1150 0+L 463 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-5dd" d="M 390 -1160+L 665 668+L 1406 668+L 890 -1160+L 390 -1160+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-367" d="M 1716 -72+Q 1147 -72 773 173+Q 400 419 306 884+L 953 1019+Q 1094 484 1722 484+Q 2056 484 2251 623+Q 2447 763 2447 956+Q 2447 1288 1956 1397+L 1369 1531+Q 406 1747 406 2497+Q 406 2809 579 3043+Q 753 3278 1058 3408+Q 1363 3538 1759 3538+Q 2325 3538 2647 3295+Q 2969 3053 3081 2666+L 2466 2531+Q 2400 2716 2237 2855+Q 2075 2994 1766 2994+Q 1481 2994 1290 2866+Q 1100 2738 1100 2541+Q 1100 2366 1226 2258+Q 1353 2150 1641 2084+L 2203 1959+Q 3156 1744 3156 1016+Q 3156 697 2973 451+Q 2791 206 2466 67+Q 2141 -72 1716 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-305" d="M 1150 2069+L 1150 0+L 463 0+L 463 3494+L 1119 3494+L 1122 2822+Q 1284 3191 1557 3364+Q 1831 3538 2200 3538+Q 2734 3538 3061 3202+Q 3388 2866 3388 2219+L 3388 0+L 2700 0+L 2700 2134+Q 2700 2513 2503 2725+Q 2306 2938 1963 2938+Q 1613 2938 1381 2711+Q 1150 2484 1150 2069+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-255" d="M 1763 -69+Q 1338 -69 1008 147+Q 678 363 489 769+Q 300 1175 300 1738+Q 300 2306 490 2709+Q 681 3113 1011 3325+Q 1341 3538 1763 3538+Q 2088 3538 2288 3430+Q 2488 3322 2598 3176+Q 2709 3031 2769 2925+L 2806 2925+L 2806 4656+L 3494 4656+L 3494 0+L 2825 0+L 2825 547+L 2769 547+Q 2706 434 2592 290+Q 2478 147 2278 39+Q 2078 -69 1763 -69+z+M 1913 516+Q 2350 516 2584 856+Q 2819 1197 2819 1744+Q 2819 2288 2587 2620+Q 2356 2953 1913 2953+Q 1609 2953 1407 2793+Q 1206 2634 1104 2361+Q 1003 2088 1003 1744+Q 1003 1397 1106 1119+Q 1209 841 1412 678+Q 1616 516 1913 516+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-354" d="M 463 0+L 463 3494+L 1128 3494+L 1128 2931+L 1166 2931+Q 1259 3216 1501 3380+Q 1744 3544 2050 3544+Q 2116 3544 2202 3537+Q 2288 3531 2341 3525+L 2341 2869+Q 2303 2878 2197 2892+Q 2091 2906 1981 2906+Q 1622 2906 1386 2686+Q 1150 2466 1150 2122+L 1150 0+L 463 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-2e0" d="M 1150 4656+L 1150 0+L 463 0+L 463 4656+L 1150 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-3e6" d="M 416 -1256+L 584 -697+L 663 -716+Q 928 -788 1114 -698+Q 1300 -609 1397 -272+L 1472 -16+L 144 3494+L 888 3494+L 1578 1509+Q 1656 1278 1715 1053+Q 1775 828 1831 603+Q 1891 828 1953 1054+Q 2016 1281 2097 1509+L 2800 3494+L 3538 3494+L 2019 -484+Q 1859 -903 1589 -1117+Q 1319 -1331 897 -1331+Q 734 -1331 607 -1307+Q 481 -1284 416 -1256+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-367" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(343.9375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(378.453125 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(435.234375 0)"/>+ <use xlink:href="#Inter-Medium-255" transform="translate(495.390625 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(557.203125 0)"/>+ <use xlink:href="#Inter-Medium-354" transform="translate(613.984375 0)"/>+ <use xlink:href="#Inter-Medium-255" transform="translate(650.75 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(712.5625 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(739.21875 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(764.421875 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(819.640625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(875.25 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(935.65625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(995.8125 0)"/>+ </g>+ </g>+ <g id="text_13">+ <!-- Pack, cache layout, 50% -->+ <g style="fill: #2e3440" transform="translate(48 414.055714) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-543" d="M 1897 -63+Q 1463 -63 1122 103+Q 781 269 579 559+Q 378 850 363 1219+L 1056 1219+Q 1081 919 1322 728+Q 1563 538 1897 538+Q 2294 538 2551 806+Q 2809 1075 2809 1494+Q 2809 1775 2687 1997+Q 2566 2219 2353 2345+Q 2141 2472 1866 2472+Q 1653 2472 1440 2398+Q 1228 2325 1100 2209+L 444 2303+L 703 4656+L 3275 4656+L 3275 4047+L 1300 4047+L 1153 2747+L 1178 2747+Q 1316 2884 1542 2970+Q 1769 3056 2031 3056+Q 2456 3056 2789 2856+Q 3122 2656 3314 2306+Q 3506 1956 3506 1506+Q 3506 1053 3300 698+Q 3094 344 2730 140+Q 2366 -63 1897 -63+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-53d" d="M 2066 -63+Q 1253 -63 803 562+Q 353 1188 353 2325+Q 353 3456 804 4087+Q 1256 4719 2066 4719+Q 2875 4719 3326 4087+Q 3778 3456 3778 2325+Q 3778 1191 3329 564+Q 2881 -63 2066 -63+z+M 2066 547+Q 2550 547 2811 1012+Q 3072 1478 3072 2325+Q 3072 3175 2811 3644+Q 2550 4113 2066 4113+Q 1581 4113 1318 3642+Q 1056 3172 1056 2325+Q 1056 1478 1318 1012+Q 1581 547 2066 547+z+" transform="scale(0.015625)"/>+ <path id="Inter-Medium-6d0" d="M 1622 2544+Q 1313 2544 1102 2676+Q 891 2809 781 3031+Q 672 3253 672 3516+L 672 3759+Q 672 4025 783 4245+Q 894 4466 1106 4598+Q 1319 4731 1622 4731+Q 1931 4731 2142 4598+Q 2353 4466 2459 4244+Q 2566 4022 2566 3759+L 2566 3516+Q 2566 3250 2458 3029+Q 2350 2809 2139 2676+Q 1928 2544 1622 2544+z+M 4738 -88+Q 4428 -88 4217 45+Q 4006 178 3898 400+Q 3791 622 3791 884+L 3791 1128+Q 3791 1394 3902 1614+Q 4013 1834 4223 1967+Q 4434 2100 4738 2100+Q 5050 2100 5259 1967+Q 5469 1834 5576 1612+Q 5684 1391 5684 1128+L 5684 884+Q 5684 622 5575 400+Q 5466 178 5255 45+Q 5044 -88 4738 -88+z+M 1278 0+L 4478 4656+L 5047 4656+L 1847 0+L 1278 0+z+M 4738 375+Q 4966 375 5056 533+Q 5147 691 5147 884+L 5147 1128+Q 5147 1322 5059 1481+Q 4972 1641 4738 1641+Q 4513 1641 4419 1481+Q 4325 1322 4325 1128+L 4325 884+Q 4325 691 4417 533+Q 4509 375 4738 375+z+M 1622 3006+Q 1850 3006 1940 3162+Q 2031 3319 2031 3516+L 2031 3759+Q 2031 3953 1943 4112+Q 1856 4272 1622 4272+Q 1397 4272 1303 4112+Q 1209 3953 1209 3759+L 1209 3516+Q 1209 3319 1300 3162+Q 1391 3006 1622 3006+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-543" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1015.703125 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1080.25 0)"/>+ </g>+ </g>+ <g id="text_14">+ <!-- Pack, cache layout, 70% -->+ <g style="fill: #2e3440" transform="translate(48 479.912857) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-546" d="M 600 0+L 2625 4009+L 2625 4047+L 281 4047+L 281 4656+L 3372 4656+L 3372 4022+L 1347 0+L 600 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-546" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1010.96875 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1075.515625 0)"/>+ </g>+ </g>+ <g id="text_15">+ <!-- Pack, cache layout, 90% -->+ <g style="fill: #2e3440" transform="translate(48 545.77) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-548" d="M 1919 -66+Q 1503 -66 1178 100+Q 853 266 648 556+Q 444 847 394 1222+L 1100 1222+Q 1166 931 1373 745+Q 1581 559 1919 559+Q 2428 559 2712 1003+Q 2997 1447 2997 2241+L 2963 2241+Q 2784 1950 2481 1779+Q 2178 1609 1809 1609+Q 1403 1609 1072 1806+Q 741 2003 547 2348+Q 353 2694 353 3138+Q 353 3584 556 3945+Q 759 4306 1126 4517+Q 1494 4728 1984 4722+Q 2294 4716 2594 4606+Q 2894 4497 3141 4242+Q 3388 3988 3534 3559+Q 3681 3131 3681 2488+Q 3681 1678 3465 1108+Q 3250 538 2854 236+Q 2459 -66 1919 -66+z+M 1963 2188+Q 2228 2188 2442 2323+Q 2656 2459 2782 2679+Q 2909 2900 2909 3159+Q 2909 3413 2787 3631+Q 2666 3850 2456 3984+Q 2247 4119 1978 4119+Q 1716 4119 1505 3989+Q 1294 3859 1172 3639+Q 1050 3419 1050 3150+Q 1050 2878 1167 2661+Q 1284 2444 1492 2316+Q 1700 2188 1963 2188+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-548" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-53d" transform="translate(1018.390625 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1082.9375 0)"/>+ </g>+ </g>+ <g id="text_16">+ <!-- Pack, cache layout, 95% -->+ <g style="fill: #2e3440" transform="translate(48 611.627143) scale(0.2 -0.2)">+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(348.78125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(405.5625 0)"/>+ <use xlink:href="#Inter-Medium-29e" transform="translate(463.28125 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(523.4375 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(582.171875 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(608.828125 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(634.03125 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(689.25 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(744.859375 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(805.265625 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(865.421875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(899.453125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(928.75 0)"/>+ <use xlink:href="#Inter-Medium-548" transform="translate(955.40625 0)"/>+ <use xlink:href="#Inter-Medium-543" transform="translate(1018.390625 0)"/>+ <use xlink:href="#Inter-Medium-6d0" transform="translate(1078.6875 0)"/>+ </g>+ </g>+ <g id="text_17">+ <!-- Pack, stable layout -->+ <g style="fill: #2e3440" transform="translate(48 677.484286) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-242" d="M 2197 -69+Q 1878 -69 1678 39+Q 1478 147 1364 290+Q 1250 434 1188 547+L 1131 547+L 1131 0+L 463 0+L 463 4656+L 1150 4656+L 1150 2925+L 1188 2925+Q 1247 3031 1358 3176+Q 1469 3322 1669 3430+Q 1869 3538 2197 3538+Q 2616 3538 2945 3325+Q 3275 3113 3465 2709+Q 3656 2306 3656 1738+Q 3656 1175 3468 769+Q 3281 363 2951 147+Q 2622 -69 2197 -69+z+M 2044 516+Q 2344 516 2545 678+Q 2747 841 2850 1119+Q 2953 1397 2953 1744+Q 2953 2088 2851 2361+Q 2750 2634 2548 2793+Q 2347 2953 2044 2953+Q 1600 2953 1369 2620+Q 1138 2288 1138 1744+Q 1138 1197 1372 856+Q 1606 516 2044 516+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-177"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(63.71875 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(120.5 0)"/>+ <use xlink:href="#Inter-Medium-2d7" transform="translate(178.21875 0)"/>+ <use xlink:href="#Inter-Medium-5dd" transform="translate(234.125 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(263.421875 0)"/>+ <use xlink:href="#Inter-Medium-367" transform="translate(290.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(343.9375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(378.453125 0)"/>+ <use xlink:href="#Inter-Medium-242" transform="translate(435.234375 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(497.046875 0)"/>+ <use xlink:href="#Inter-Medium-266" transform="translate(522.25 0)"/>+ <use xlink:href="#Inter-Medium-6f1" transform="translate(580.984375 0)"/>+ <use xlink:href="#Inter-Medium-2e0" transform="translate(607.640625 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(632.84375 0)"/>+ <use xlink:href="#Inter-Medium-3e6" transform="translate(688.0625 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(743.671875 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(804.078125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(864.234375 0)"/>+ </g>+ </g>+ <g id="text_18">+ <!-- Truncation -->+ <g style="fill: #2e3440" transform="translate(48 743.341429) scale(0.2 -0.2)">+ <defs>+ <path id="Inter-Medium-19b" d="M 281 4044+L 281 4656+L 3897 4656+L 3897 4044+L 2450 4044+L 2450 0+L 1734 0+L 1734 4044+L 281 4044+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Medium-19b"/>+ <use xlink:href="#Inter-Medium-354" transform="translate(59.625 0)"/>+ <use xlink:href="#Inter-Medium-393" transform="translate(98.296875 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(158.453125 0)"/>+ <use xlink:href="#Inter-Medium-24a" transform="translate(218.609375 0)"/>+ <use xlink:href="#Inter-Medium-1fb" transform="translate(277.3125 0)"/>+ <use xlink:href="#Inter-Medium-379" transform="translate(334.09375 0)"/>+ <use xlink:href="#Inter-Medium-2b1" transform="translate(368.125 0)"/>+ <use xlink:href="#Inter-Medium-316" transform="translate(393.328125 0)"/>+ <use xlink:href="#Inter-Medium-305" transform="translate(453.734375 0)"/>+ </g>+ </g>+ <g id="text_19">+ <!-- Muse Spark 1.3 -->+ <g style="fill: #0a0b0f" transform="translate(308.46875 260) scale(0.26 -0.26)">+ <defs>+ <path id="Inter-SemiBold-124" d="M 469 0+L 469 4656+L 1725 4656+L 2609 2253+Q 2656 2116 2717 1895+Q 2778 1675 2840 1423+Q 2903 1172 2956 941+Q 3009 1169 3071 1420+Q 3134 1672 3195 1892+Q 3256 2113 3300 2253+L 4175 4656+L 5434 4656+L 5434 0+L 4603 0+L 4603 2350+Q 4603 2525 4608 2783+Q 4613 3041 4620 3331+Q 4628 3622 4631 3900+Q 4553 3600 4465 3303+Q 4378 3006 4300 2756+Q 4222 2506 4166 2350+L 3306 0+L 2597 0+L 1725 2350+Q 1669 2500 1592 2744+Q 1516 2988 1430 3281+Q 1344 3575 1256 3875+Q 1263 3613 1270 3327+Q 1278 3041 1283 2784+Q 1288 2528 1288 2350+L 1288 0+L 469 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-393" d="M 1628 -44+Q 1088 -44 759 300+Q 431 644 431 1272+L 431 3494+L 1244 3494+L 1244 1397+Q 1244 1047 1426 847+Q 1609 647 1928 647+Q 2253 647 2462 856+Q 2672 1066 2672 1447+L 2672 3494+L 3488 3494+L 3488 0+L 2716 0+L 2709 700+Q 2397 -44 1628 -44+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-367" d="M 1753 -72+Q 1150 -72 758 186+Q 366 444 275 919+L 1034 1063+Q 1172 550 1769 550+Q 2069 550 2245 670+Q 2422 791 2422 969+Q 2422 1266 1950 1369+L 1353 1497+Q 372 1709 372 2475+Q 372 2800 550 3037+Q 728 3275 1045 3406+Q 1363 3538 1781 3538+Q 2375 3538 2720 3291+Q 3066 3044 3172 2638+L 2447 2494+Q 2384 2675 2228 2803+Q 2072 2931 1791 2931+Q 1534 2931 1359 2817+Q 1184 2703 1184 2525+Q 1184 2372 1298 2273+Q 1413 2175 1681 2116+L 2275 1991+Q 3253 1781 3253 1047+Q 3253 716 3062 464+Q 2872 213 2533 70+Q 2194 -72 1753 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-266" d="M 1975 -72+Q 1447 -72 1067 150+Q 688 372 483 775+Q 278 1178 278 1725+Q 278 2263 479 2670+Q 681 3078 1051 3308+Q 1422 3538 1922 3538+Q 2347 3538 2711 3352+Q 3075 3166 3297 2777+Q 3519 2388 3519 1775+L 3519 1519+L 1088 1519+Q 1103 1053 1348 809+Q 1594 566 1984 566+Q 2253 566 2445 681+Q 2638 797 2719 1019+L 3466 866+Q 3341 444 2948 186+Q 2556 -72 1975 -72+z+M 1091 2072+L 2728 2072+Q 2691 2447 2489 2673+Q 2288 2900 1925 2900+Q 1553 2900 1336 2661+Q 1119 2422 1091 2072+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-6f1" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-18d" d="M 2103 -72+Q 1291 -72 808 303+Q 325 678 297 1369+L 1119 1369+Q 1147 1000 1425 820+Q 1703 641 2097 641+Q 2509 641 2770 827+Q 3031 1013 3031 1313+Q 3031 1584 2800 1723+Q 2569 1863 2191 1959+L 1663 2097+Q 1078 2247 751 2550+Q 425 2853 425 3347+Q 425 3759 647 4067+Q 869 4375 1253 4547+Q 1638 4719 2125 4719+Q 2622 4719 2995 4547+Q 3369 4375 3581 4072+Q 3794 3769 3803 3381+L 2994 3381+Q 2963 3678 2727 3843+Q 2491 4009 2113 4009+Q 1719 4009 1494 3836+Q 1269 3663 1269 3397+Q 1269 3200 1389 3076+Q 1509 2953 1692 2878+Q 1875 2803 2063 2756+L 2497 2644+Q 2841 2559 3155 2401+Q 3469 2244 3667 1978+Q 3866 1713 3866 1306+Q 3866 897 3656 586+Q 3447 275 3053 101+Q 2659 -72 2103 -72+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-34b" d="M 431 -1306+L 431 3494+L 1225 3494+L 1225 2916+L 1278 2916+Q 1338 3038 1453 3183+Q 1569 3328 1769 3433+Q 1969 3538 2278 3538+Q 2681 3538 3007 3331+Q 3334 3125 3526 2723+Q 3719 2322 3719 1741+Q 3719 1166 3530 762+Q 3341 359 3016 148+Q 2691 -63 2275 -63+Q 1975 -63 1776 39+Q 1578 141 1459 284+Q 1341 428 1278 553+L 1244 553+L 1244 -1306+L 431 -1306+z+M 2056 606+Q 2463 606 2673 929+Q 2884 1253 2884 1744+Q 2884 2231 2676 2550+Q 2469 2869 2056 2869+Q 1653 2869 1440 2561+Q 1228 2253 1228 1744+Q 1228 1234 1443 920+Q 1659 606 2056 606+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-1fb" d="M 1406 -72+Q 1075 -72 809 48+Q 544 169 391 403+Q 238 638 238 981+Q 238 1375 430 1592+Q 622 1809 926 1907+Q 1231 2006 1569 2041+Q 2025 2091 2228 2133+Q 2431 2175 2431 2356+L 2431 2372+Q 2431 2628 2275 2770+Q 2119 2913 1822 2913+Q 1516 2913 1334 2778+Q 1153 2644 1091 2472+L 338 2625+Q 491 3088 892 3313+Q 1294 3538 1819 3538+Q 2066 3538 2317 3480+Q 2569 3422 2778 3286+Q 2988 3150 3116 2917+Q 3244 2684 3244 2334+L 3244 0+L 2466 0+L 2466 481+L 2434 481+Q 2319 256 2066 92+Q 1813 -72 1406 -72+z+M 1616 531+Q 1991 531 2214 747+Q 2438 963 2438 1253+L 2438 1666+Q 2381 1622 2237 1589+Q 2094 1556 1933 1532+Q 1772 1509 1666 1494+Q 1391 1456 1208 1343+Q 1025 1231 1025 991+Q 1025 766 1190 648+Q 1356 531 1616 531+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-354" d="M 431 0+L 431 3494+L 1219 3494+L 1219 2909+L 1256 2909+Q 1350 3213 1584 3377+Q 1819 3541 2119 3541+Q 2275 3541 2416 3519+L 2416 2772+Q 2366 2784 2253 2798+Q 2141 2813 2031 2813+Q 1691 2813 1467 2602+Q 1244 2391 1244 2056+L 1244 0+L 431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-2d7" d="M 431 0+L 431 4656+L 1244 4656+L 1244 2084+L 1303 2084+L 2563 3494+L 3516 3494+L 2163 1984+L 3597 0+L 2622 0+L 1544 1497+L 1244 1175+L 1244 0+L 431 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-53e" d="M 2241 4656+L 2241 0+L 1413 0+L 1413 3913+L 1381 3913+L 294 3131+L 294 3925+L 1316 4656+L 2241 4656+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-5de" d="M 1019 -53+Q 809 -53 664 90+Q 519 234 519 447+Q 519 656 664 800+Q 809 944 1019 944+Q 1231 944 1376 800+Q 1522 656 1522 447+Q 1522 234 1376 90+Q 1231 -53 1019 -53+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-541" d="M 2034 -63+Q 1544 -63 1164 104+Q 784 272 565 572+Q 347 872 334 1263+L 1175 1263+Q 1194 975 1437 806+Q 1681 638 2034 638+Q 2409 638 2650 831+Q 2891 1025 2891 1334+Q 2891 1653 2642 1854+Q 2394 2056 1950 2056+L 1538 2056+L 1538 2700+L 1950 2700+Q 2313 2700 2541 2887+Q 2769 3075 2769 3381+Q 2769 3678 2570 3858+Q 2372 4038 2044 4038+Q 1722 4038 1483 3869+Q 1244 3700 1234 3403+L 431 3403+Q 438 3791 655 4087+Q 872 4384 1236 4551+Q 1600 4719 2050 4719+Q 2516 4719 2859 4544+Q 3203 4369 3392 4076+Q 3581 3784 3581 3431+Q 3581 3038 3350 2772+Q 3119 2506 2741 2422+L 2741 2384+Q 3228 2316 3489 2022+Q 3750 1728 3750 1291+Q 3750 900 3528 594+Q 3306 288 2918 112+Q 2531 -63 2034 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-124"/>+ <use xlink:href="#Inter-SemiBold-393" transform="translate(92.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-367" transform="translate(153.46875 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(208.40625 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(267.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-18d" transform="translate(292.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-34b" transform="translate(357.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-1fb" transform="translate(421.171875 0)"/>+ <use xlink:href="#Inter-SemiBold-354" transform="translate(478.59375 0)"/>+ <use xlink:href="#Inter-SemiBold-2d7" transform="translate(519.859375 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(576.796875 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(602 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(644.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(673.734375 0)"/>+ </g>+ </g>+ <g id="text_20">+ <!-- $1.25 per million input tokens, $0.15 cached -->+ <g style="fill: #5b6474" transform="translate(308.46875 286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-51d" d="M 1866 -681+L 1866 -75+Q 1191 -28 795 320+Q 400 669 363 1219+L 972 1219+Q 1003 869 1259 683+Q 1516 497 1866 459+L 1866 2141+L 1681 2194+Q 1119 2353 806 2650+Q 494 2947 494 3409+Q 494 3769 673 4047+Q 853 4325 1162 4495+Q 1472 4666 1866 4706+L 1866 5338+L 2241 5338+L 2241 4716+Q 2659 4688 2979 4520+Q 3300 4353 3484 4083+Q 3669 3813 3681 3481+L 3100 3481+Q 3066 3788 2830 3969+Q 2594 4150 2241 4184+L 2241 2606+L 2425 2556+Q 2613 2506 2839 2418+Q 3066 2331 3272 2186+Q 3478 2041 3611 1817+Q 3744 1594 3744 1269+Q 3744 909 3567 617+Q 3391 325 3055 140+Q 2719 -44 2241 -75+L 2241 -681+L 1866 -681+z+M 2241 459+Q 2644 503 2905 723+Q 3166 944 3166 1278+Q 3166 1503 3039 1643+Q 2913 1784 2703 1875+Q 2494 1966 2244 2034+L 2241 2034+L 2241 459+z+M 1866 2713+L 1866 4181+Q 1503 4131 1287 3928+Q 1072 3725 1072 3438+Q 1072 3216 1200 3073+Q 1328 2931 1512 2845+Q 1697 2759 1866 2713+z+" transform="scale(0.015625)"/>+ <path id="Inter-Regular-543" d="M 1863 -63+Q 1453 -63 1128 98+Q 803 259 609 539+Q 416 819 400 1175+L 975 1175+Q 1003 863 1258 661+Q 1513 459 1863 459+Q 2144 459 2364 590+Q 2584 722 2709 953+Q 2834 1184 2834 1478+Q 2834 1778 2703 2015+Q 2572 2253 2345 2389+Q 2119 2525 1825 2525+Q 1609 2525 1387 2456+Q 1166 2388 1028 2281+L 472 2350+L 747 4656+L 3197 4656+L 3197 4134+L 1247 4134+L 1088 2775+L 1113 2775+Q 1256 2894 1475 2970+Q 1694 3047 1934 3047+Q 2363 3047 2697 2845+Q 3031 2644 3223 2291+Q 3416 1938 3416 1488+Q 3416 1041 3214 691+Q 3013 341 2663 139+Q 2313 -63 1863 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-51d"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(104.828125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(133.640625 0)"/>+ <use xlink:href="#Inter-Regular-543" transform="translate(194.625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(253.953125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(282.078125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(343.3125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(401.609375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(439.25 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(467.375 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(554.96875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(579.1875 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(603.40625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(627.625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(651.84375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(711.8125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(770.890625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(799.015625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(823.234375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(882.3125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(943.546875 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1002.671875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1035.390625 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1063.515625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1095.265625 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1155.234375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1207.875 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1266.171875 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1325.25 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1378.03125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1406.84375 0)"/>+ <use xlink:href="#Inter-Regular-51d" transform="translate(1434.96875 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1499.125 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1559.6875 0)"/>+ <use xlink:href="#Inter-Regular-53e" transform="translate(1579.859375 0)"/>+ <use xlink:href="#Inter-Regular-543" transform="translate(1620.53125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1679.859375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1707.984375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1766.09375 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1822.25 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1879.375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1938.5 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(1996.796875 0)"/>+ </g>+ </g>+ <g id="text_21">+ <!-- $1.27 -->+ <g style="fill: #0a0b0f" transform="translate(480.136904 334.507286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-51d" d="M 1913 -644+L 1913 -66+Q 1184 -22 753 348+Q 322 719 297 1369+L 1119 1369+Q 1144 1044 1366 866+Q 1588 688 1913 650+L 1913 2031+L 1663 2097+Q 1078 2247 751 2550+Q 425 2853 425 3347+Q 425 3728 617 4022+Q 809 4316 1145 4494+Q 1481 4672 1913 4709+L 1913 5300+L 2288 5300+L 2288 4713+Q 2741 4684 3077 4506+Q 3413 4328 3603 4037+Q 3794 3747 3803 3381+L 2994 3381+Q 2966 3644 2778 3803+Q 2591 3963 2288 4000+L 2288 2697+L 2497 2644+Q 2841 2559 3155 2401+Q 3469 2244 3667 1978+Q 3866 1713 3866 1306+Q 3866 728 3452 353+Q 3038 -22 2288 -66+L 2288 -644+L 1913 -644+z+M 2288 653+Q 2622 694 2826 872+Q 3031 1050 3031 1313+Q 3031 1569 2828 1705+Q 2625 1841 2288 1931+L 2288 653+z+M 1913 2794+L 1913 3997+Q 1609 3953 1439 3790+Q 1269 3628 1269 3397+Q 1269 3141 1467 3005+Q 1666 2869 1913 2794+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-53f" d="M 419 0+L 419 600+L 2034 2191+Q 2375 2538 2553 2784+Q 2731 3031 2731 3328+Q 2731 3656 2511 3847+Q 2291 4038 1959 4038+Q 1609 4038 1400 3830+Q 1191 3622 1191 3263+L 394 3263+Q 394 3703 595 4031+Q 797 4359 1153 4539+Q 1509 4719 1969 4719+Q 2434 4719 2787 4544+Q 3141 4369 3337 4064+Q 3534 3759 3534 3369+Q 3534 3113 3436 2863+Q 3338 2613 3088 2303+Q 2838 1994 2384 1556+L 1575 731+L 1575 697+L 3603 697+L 3603 0+L 419 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-546" d="M 578 0+L 2559 3925+L 2559 3956+L 259 3956+L 259 4656+L 3428 4656+L 3428 3938+L 1447 0+L 578 0+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_22">+ <!-- $1.27 -->+ <g style="fill: #0a0b0f" transform="translate(480.136904 360.435857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_23">+ <!-- $1.17 -->+ <g style="fill: #0a0b0f" transform="translate(467.461289 400.364429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(130.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(172.609375 0)"/>+ </g>+ </g>+ <g id="text_24">+ <!-- $0.610 -->+ <g style="fill: #0a0b0f" transform="translate(396.332132 426.293) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-53d" d="M 2113 -63+Q 1263 -63 792 564+Q 322 1191 322 2325+Q 322 3456 794 4087+Q 1266 4719 2113 4719+Q 2956 4719 3428 4087+Q 3900 3456 3900 2325+Q 3900 1191 3429 564+Q 2959 -63 2113 -63+z+M 2113 638+Q 2569 638 2814 1078+Q 3059 1519 3059 2325+Q 3059 3134 2814 3578+Q 2569 4022 2113 4022+Q 1656 4022 1409 3576+Q 1163 3131 1163 2325+Q 1163 1519 1408 1078+Q 1653 638 2113 638+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-545" d="M 2097 -63+Q 1763 -63 1447 51+Q 1131 166 876 425+Q 622 684 472 1118+Q 322 1553 322 2194+Q 322 2991 545 3555+Q 769 4119 1178 4419+Q 1588 4719 2147 4719+Q 2581 4719 2918 4547+Q 3256 4375 3467 4078+Q 3678 3781 3728 3403+L 2909 3403+Q 2844 3669 2647 3833+Q 2450 3997 2147 3997+Q 1659 3997 1396 3575+Q 1134 3153 1134 2413+L 1169 2413+Q 1338 2716 1645 2886+Q 1953 3056 2328 3056+Q 2738 3056 3064 2861+Q 3391 2666 3581 2322+Q 3772 1978 3772 1538+Q 3772 1078 3562 717+Q 3353 356 2976 146+Q 2600 -63 2097 -63+z+M 2094 616+Q 2341 616 2537 736+Q 2734 856 2848 1061+Q 2963 1266 2963 1522+Q 2963 1772 2852 1975+Q 2741 2178 2545 2297+Q 2350 2416 2103 2416+Q 1856 2416 1657 2292+Q 1459 2169 1343 1964+Q 1228 1759 1228 1519+Q 1228 1272 1340 1067+Q 1453 863 1648 739+Q 1844 616 2094 616+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(157.34375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(221.3125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(263.59375 0)"/>+ </g>+ </g>+ <g id="text_25">+ <!-- $1.21 -->+ <g style="fill: #0a0b0f" transform="translate(473.349926 466.221571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_26">+ <!-- $0.433 -->+ <g style="fill: #0a0b0f" transform="translate(373.766411 492.150143) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-542" d="M 334 866+L 334 1531+L 2313 4656+L 3350 4656+L 3350 1553+L 3950 1553+L 3950 866+L 3350 866+L 3350 0+L 2550 0+L 2550 866+L 334 866+z+M 2566 1553+L 2566 3706+L 2528 3706+L 1188 1591+L 1188 1553+L 2566 1553+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(226.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(290.359375 0)"/>+ </g>+ </g>+ <g id="text_27">+ <!-- $1.26 -->+ <g style="fill: #0a0b0f" transform="translate(478.639568 532.078714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_28">+ <!-- $0.252 -->+ <g style="fill: #0a0b0f" transform="translate(350.60338 558.007286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-543" d="M 1931 -63+Q 1475 -63 1117 109+Q 759 281 550 579+Q 341 878 328 1263+L 1141 1263+Q 1156 975 1384 795+Q 1613 616 1931 616+Q 2303 616 2545 866+Q 2788 1116 2788 1509+Q 2788 1906 2539 2164+Q 2291 2422 1906 2422+Q 1694 2422 1492 2342+Q 1291 2263 1172 2134+L 416 2256+L 659 4656+L 3353 4656+L 3353 3956+L 1350 3956+L 1219 2719+L 1244 2719+Q 1375 2872 1611 2970+Q 1847 3069 2128 3069+Q 2550 3069 2883 2870+Q 3216 2672 3406 2323+Q 3597 1975 3597 1528+Q 3597 1066 3384 706+Q 3172 347 2797 142+Q 2422 -63 1931 -63+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(283.671875 0)"/>+ </g>+ </g>+ <g id="text_29">+ <!-- $1.26 -->+ <g style="fill: #0a0b0f" transform="translate(479.65276 597.935857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_30">+ <!-- $0.204 -->+ <g style="fill: #0a0b0f" transform="translate(344.50214 623.864429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(288.40625 0)"/>+ </g>+ </g>+ <g id="text_31">+ <!-- $1.27 -->+ <g style="fill: #0a0b0f" transform="translate(480.258087 663.793) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_32">+ <!-- $0.153 -->+ <g style="fill: #0a0b0f" transform="translate(337.993036 689.721571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(151.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(193.515625 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(254.75 0)"/>+ </g>+ </g>+ <g id="text_33">+ <!-- $1.27 -->+ <g style="fill: #0a0b0f" transform="translate(480.583008 729.650143) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(139.21875 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(201.53125 0)"/>+ </g>+ </g>+ <g id="text_34">+ <!-- $0.153 -->+ <g style="fill: #0a0b0f" transform="translate(338.032027 755.578714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(151.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(193.515625 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(254.75 0)"/>+ </g>+ </g>+ <g id="text_35">+ <!-- Muse Wonder -->+ <g style="fill: #0a0b0f" transform="translate(950.234375 260) scale(0.26 -0.26)">+ <defs>+ <path id="Inter-SemiBold-1cb" d="M 1413 0+L 156 4656+L 1053 4656+L 1659 2178+Q 1731 1863 1793 1511+Q 1856 1159 1916 813+Q 1978 1159 2045 1511+Q 2113 1863 2191 2178+L 2822 4656+L 3706 4656+L 4334 2178+Q 4413 1866 4480 1519+Q 4547 1172 4609 828+Q 4669 1172 4733 1519+Q 4797 1866 4869 2178+L 5472 4656+L 6372 4656+L 5113 0+L 4156 0+L 3478 2572+Q 3416 2816 3362 3091+Q 3309 3366 3259 3666+Q 3213 3375 3164 3103+Q 3116 2831 3047 2572+L 2369 0+L 1413 0+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-316" d="M 1947 -72+Q 1438 -72 1063 154+Q 688 381 483 786+Q 278 1191 278 1728+Q 278 2272 483 2680+Q 688 3088 1063 3313+Q 1438 3538 1947 3538+Q 2456 3538 2831 3313+Q 3206 3088 3412 2680+Q 3619 2272 3619 1728+Q 3619 1191 3412 786+Q 3206 381 2831 154+Q 2456 -72 1947 -72+z+M 1947 588+Q 2231 588 2418 741+Q 2606 894 2700 1153+Q 2794 1413 2794 1731+Q 2794 2053 2700 2312+Q 2606 2572 2418 2725+Q 2231 2878 1947 2878+Q 1666 2878 1478 2725+Q 1291 2572 1198 2312+Q 1106 2053 1106 1731+Q 1106 1413 1198 1153+Q 1291 894 1478 741+Q 1666 588 1947 588+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-305" d="M 1244 2047+L 1244 0+L 431 0+L 431 3494+L 1200 3494+L 1209 2797+Q 1522 3538 2291 3538+Q 2831 3538 3157 3194+Q 3484 2850 3484 2222+L 3484 0+L 2672 0+L 2672 2097+Q 2672 2447 2490 2647+Q 2309 2847 1991 2847+Q 1666 2847 1455 2637+Q 1244 2428 1244 2047+z+" transform="scale(0.015625)"/>+ <path id="Inter-SemiBold-255" d="M 1719 -63+Q 1306 -63 979 148+Q 653 359 465 762+Q 278 1166 278 1741+Q 278 2322 468 2723+Q 659 3125 986 3331+Q 1313 3538 1716 3538+Q 2028 3538 2226 3433+Q 2425 3328 2540 3183+Q 2656 3038 2719 2916+L 2753 2916+L 2753 4656+L 3566 4656+L 3566 0+L 2769 0+L 2769 553+L 2719 553+Q 2653 428 2534 284+Q 2416 141 2217 39+Q 2019 -63 1719 -63+z+M 1941 606+Q 2338 606 2553 920+Q 2769 1234 2769 1744+Q 2769 2253 2555 2561+Q 2341 2869 1941 2869+Q 1528 2869 1318 2550+Q 1109 2231 1109 1744+Q 1109 1253 1320 929+Q 1531 606 1941 606+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-124"/>+ <use xlink:href="#Inter-SemiBold-393" transform="translate(92.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-367" transform="translate(153.46875 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(208.40625 0)"/>+ <use xlink:href="#Inter-SemiBold-6f1" transform="translate(267.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-1cb" transform="translate(292.734375 0)"/>+ <use xlink:href="#Inter-SemiBold-316" transform="translate(389.703125 0)"/>+ <use xlink:href="#Inter-SemiBold-305" transform="translate(450.59375 0)"/>+ <use xlink:href="#Inter-SemiBold-255" transform="translate(511.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-266" transform="translate(574.1875 0)"/>+ <use xlink:href="#Inter-SemiBold-354" transform="translate(633.3125 0)"/>+ </g>+ </g>+ <g id="text_36">+ <!-- $4.00 per million input tokens, $0.20 cached -->+ <g style="fill: #5b6474" transform="translate(950.234375 286) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-Regular-542" d="M 375 947+L 375 1431+L 2413 4656+L 3134 4656+L 3134 1469+L 3766 1469+L 3766 947+L 3134 947+L 3134 0+L 2566 0+L 2566 947+L 375 947+z+M 2569 1469+L 2569 3913+L 2531 3913+L 1009 1506+L 1009 1469+L 2569 1469+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-Regular-51d"/>+ <use xlink:href="#Inter-Regular-542" transform="translate(64.15625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(125.375 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(151.65625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(214.75 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(277.84375 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(305.96875 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(367.203125 0)"/>+ <use xlink:href="#Inter-Regular-354" transform="translate(425.5 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(463.140625 0)"/>+ <use xlink:href="#Inter-Regular-2fe" transform="translate(491.265625 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(578.859375 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(603.078125 0)"/>+ <use xlink:href="#Inter-Regular-2e0" transform="translate(627.296875 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(651.515625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(675.734375 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(735.703125 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(794.78125 0)"/>+ <use xlink:href="#Inter-Regular-2b1" transform="translate(822.90625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(847.125 0)"/>+ <use xlink:href="#Inter-Regular-34b" transform="translate(906.203125 0)"/>+ <use xlink:href="#Inter-Regular-393" transform="translate(967.4375 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1026.5625 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1059.28125 0)"/>+ <use xlink:href="#Inter-Regular-379" transform="translate(1087.40625 0)"/>+ <use xlink:href="#Inter-Regular-316" transform="translate(1119.15625 0)"/>+ <use xlink:href="#Inter-Regular-2d7" transform="translate(1179.125 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1231.765625 0)"/>+ <use xlink:href="#Inter-Regular-305" transform="translate(1290.0625 0)"/>+ <use xlink:href="#Inter-Regular-367" transform="translate(1349.140625 0)"/>+ <use xlink:href="#Inter-Regular-5dd" transform="translate(1401.921875 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1430.734375 0)"/>+ <use xlink:href="#Inter-Regular-51d" transform="translate(1458.859375 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1523.015625 0)"/>+ <use xlink:href="#Inter-Regular-5de" transform="translate(1583.578125 0)"/>+ <use xlink:href="#Inter-Regular-53f" transform="translate(1612.390625 0)"/>+ <use xlink:href="#Inter-Regular-53d" transform="translate(1673.375 0)"/>+ <use xlink:href="#Inter-Regular-6f1" transform="translate(1736.46875 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1764.59375 0)"/>+ <use xlink:href="#Inter-Regular-1fb" transform="translate(1822.703125 0)"/>+ <use xlink:href="#Inter-Regular-24a" transform="translate(1878.859375 0)"/>+ <use xlink:href="#Inter-Regular-29e" transform="translate(1935.984375 0)"/>+ <use xlink:href="#Inter-Regular-266" transform="translate(1995.109375 0)"/>+ <use xlink:href="#Inter-Regular-255" transform="translate(2053.40625 0)"/>+ </g>+ </g>+ <g id="text_37">+ <!-- $4.06 -->+ <g style="fill: #0a0b0f" transform="translate(1477.572467 334.507286) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_38">+ <!-- $4.06 -->+ <g style="fill: #0a0b0f" transform="translate(1477.572467 360.435857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_39">+ <!-- $3.74 -->+ <g style="fill: #0a0b0f" transform="translate(1437.010501 400.364429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(126.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(156.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(208.09375 0)"/>+ </g>+ </g>+ <g id="text_40">+ <!-- $1.81 -->+ <g style="fill: #0a0b0f" transform="translate(1191.291593 426.293) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-547" d="M 2047 -63+Q 1541 -63 1152 106+Q 763 275 542 572+Q 322 869 322 1247+Q 322 1538 450 1784+Q 578 2031 798 2197+Q 1019 2363 1294 2409+L 1294 2438+Q 934 2519 712 2806+Q 491 3094 491 3472+Q 491 3831 692 4112+Q 894 4394 1245 4556+Q 1597 4719 2047 4719+Q 2494 4719 2845 4556+Q 3197 4394 3400 4112+Q 3603 3831 3603 3472+Q 3603 3094 3379 2806+Q 3156 2519 2803 2438+L 2803 2409+Q 3072 2363 3292 2197+Q 3513 2031 3644 1784+Q 3775 1538 3775 1247+Q 3775 869 3553 572+Q 3331 275 2940 106+Q 2550 -63 2047 -63+z+M 2047 581+Q 2441 581 2677 781+Q 2913 981 2913 1306+Q 2913 1641 2666 1856+Q 2419 2072 2047 2072+Q 1669 2072 1423 1856+Q 1178 1641 1178 1306+Q 1178 981 1414 781+Q 1650 581 2047 581+z+M 2047 2703+Q 2369 2703 2578 2893+Q 2788 3084 2788 3391+Q 2788 3694 2581 3878+Q 2375 4063 2047 4063+Q 1716 4063 1511 3878+Q 1306 3694 1306 3391+Q 1306 3088 1514 2895+Q 1722 2703 2047 2703+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(136.578125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(200.59375 0)"/>+ </g>+ </g>+ <g id="text_41">+ <!-- $3.88 -->+ <g style="fill: #0a0b0f" transform="translate(1455.854138 466.221571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(126.53125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(155.78125 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(219.796875 0)"/>+ </g>+ </g>+ <g id="text_42">+ <!-- $1.19 -->+ <g style="fill: #0a0b0f" transform="translate(1111.838358 492.150143) scale(0.18 -0.18)">+ <defs>+ <path id="Inter-SemiBold-548" d="M 1953 -66+Q 1516 -66 1175 106+Q 834 278 625 578+Q 416 878 366 1259+L 1191 1259+Q 1253 991 1450 823+Q 1647 656 1953 656+Q 2438 656 2700 1079+Q 2963 1503 2963 2247+L 2931 2247+Q 2763 1950 2455 1776+Q 2147 1603 1769 1603+Q 1359 1603 1032 1798+Q 706 1994 514 2337+Q 322 2681 322 3119+Q 322 3578 533 3943+Q 744 4309 1123 4518+Q 1503 4728 2006 4722+Q 2334 4719 2650 4605+Q 2966 4491 3219 4231+Q 3472 3972 3622 3539+Q 3772 3106 3772 2466+Q 3772 1666 3548 1100+Q 3325 534 2917 234+Q 2509 -66 1953 -66+z+M 1991 2244+Q 2241 2244 2439 2367+Q 2638 2491 2755 2697+Q 2872 2903 2872 3147+Q 2872 3384 2759 3589+Q 2647 3794 2450 3917+Q 2253 4041 2003 4041+Q 1756 4041 1559 3920+Q 1363 3800 1248 3595+Q 1134 3391 1134 3138+Q 1134 2884 1245 2682+Q 1356 2481 1550 2362+Q 1744 2244 1991 2244+z+" transform="scale(0.015625)"/>+ </defs>+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(107.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(130.328125 0)"/>+ <use xlink:href="#Inter-SemiBold-548" transform="translate(172.609375 0)"/>+ </g>+ </g>+ <g id="text_43">+ <!-- $4.02 -->+ <g style="fill: #0a0b0f" transform="translate(1472.780994 532.078714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_44">+ <!-- $0.551 -->+ <g style="fill: #0a0b0f" transform="translate(1030.474161 558.007286) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(159.203125 0)"/>+ <use xlink:href="#Inter-SemiBold-543" transform="translate(220.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-53e" transform="translate(281.671875 0)"/>+ </g>+ </g>+ <g id="text_45">+ <!-- $4.04 -->+ <g style="fill: #0a0b0f" transform="translate(1476.023208 597.935857) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_46">+ <!-- $0.383 -->+ <g style="fill: #0a0b0f" transform="translate(1009.139249 623.864429) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(157.6875 0)"/>+ <use xlink:href="#Inter-SemiBold-547" transform="translate(221.3125 0)"/>+ <use xlink:href="#Inter-SemiBold-541" transform="translate(285.328125 0)"/>+ </g>+ </g>+ <g id="text_47">+ <!-- $4.06 -->+ <g style="fill: #0a0b0f" transform="translate(1477.960254 663.793) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(223.359375 0)"/>+ </g>+ </g>+ <g id="text_48">+ <!-- $0.206 -->+ <g style="fill: #0a0b0f" transform="translate(986.499168 689.721571) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(288.40625 0)"/>+ </g>+ </g>+ <g id="text_49">+ <!-- $4.07 -->+ <g style="fill: #0a0b0f" transform="translate(1479 729.650143) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-542" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.28125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(157.390625 0)"/>+ <use xlink:href="#Inter-SemiBold-546" transform="translate(221.40625 0)"/>+ </g>+ </g>+ <g id="text_50">+ <!-- $0.206 -->+ <g style="fill: #0a0b0f" transform="translate(986.551156 755.578714) scale(0.18 -0.18)">+ <use xlink:href="#Inter-SemiBold-51d"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(65.046875 0)"/>+ <use xlink:href="#Inter-SemiBold-5de" transform="translate(128.234375 0)"/>+ <use xlink:href="#Inter-SemiBold-53f" transform="translate(160.125 0)"/>+ <use xlink:href="#Inter-SemiBold-53d" transform="translate(222.4375 0)"/>+ <use xlink:href="#Inter-SemiBold-545" transform="translate(288.40625 0)"/>+ </g>+ </g>+ </g>+ </g>+ <defs>+ <clipPath id="p1c9bf33d97">+ <rect x="0" y="0" width="1600" height="900"/>+ </clipPath>+ </defs>+</svg>diff --git a/docs/benchmarks.md b/docs/benchmarks.mdindex c3aa872..710714b 100644--- a/docs/benchmarks.md+++ b/docs/benchmarks.md@@ -16,6 +16,7 @@ endorsement is implied.| Retrieval: finding the files a fix changes | Graphicle 0.1.8, offline, 25 October 2026, on 100 SWE-bench Verified issues never used for tuning; Graphicle 0.1.3 and the 0.1.2 release, 21 October 2026, on those and 80 issues used for tuning | On the held-out issues, a file the fix changed was among the first 5 files of 0.1.8's context packet for 75, against 61 for BM25 (SWE-bench style; McNemar exact p = 0.013) and 54 for grep on the issue's names; for the first file and the first 10 files the differences from BM25 are not significant. 0.1.3 had the same counts, apart from 82 in the first 10 files against 0.1.8's 81. Ranking only: no agent test of this ranking has been run yet ([retrieval benchmark](benchmarks/retrieval.md)) || Retrieval: time per question, our run | Graphicle 0.1.8 against 0.1.7 on our Linux server, 25 October 2026 | kubernetes, the 22 questions of issue #8, each call a new process: `graphicle context` took a median of 1.34 s with 0.1.8 against 2.99 s with 0.1.7 on 16 cores, and 1.38 s against 3.89 s on 4; the peak memory of a call was 0.6 GB against 3.5 GB, with the same packet for every question. [Details](#our-own-run-on-kubernetes-017-and-018) || Retrieval: time per question, measured independently | Run and published by @selimaytac, who reported issue #8, on Graphicle 0.1.3 and 0.1.5, 23 October 2026 | kubernetes, 22 questions, an Apple M3 Pro, no answer model: `graphicle context` took a median of 153.5 s per question on 0.1.3 and 9.5 s on 0.1.5, and the prompt hook returned a packet for 18 of 22. [Details](#independent-measurements) |+| Whole-repository packs: the files a fix changes, in repositories past 1M tokens | Questions, arms and scorer fixed; the model runs are not made yet. Context recall without a model, on 3 held-out and 2 development repositories, with the pack built before Meta's hackathon (2a46edb) | Held out (pytorch, vscode and elasticsearch, 90 questions): a mean 55.8% of the files a fix changed had text inside a 64K-token pack (whole, or as excerpts or outlines of their symbols) and 76.8% inside 1M tokens, against 1.1% and 2.2% for the repository cut to the same budget, which holds whole files only. [The benchmark's page](benchmarks/whole-repo.md) || Agent memory: comparison with seven memory systems | Done, on development sets, with a proxy evaluator | Every system's scores and the 21 registered comparisons are [below](#agent-memory-comparison-with-seven-memory-systems). None of them is a headline claim || Agent memory: retrieval defaults | Chosen | Model-free retrieval runs on development data, plus held-out checks; their records are not published yet, so no numbers are given |diff --git a/docs/benchmarks/whole-repo.json b/docs/benchmarks/whole-repo.jsonnew file mode 100644index 0000000..6ee26af--- /dev/null+++ b/docs/benchmarks/whole-repo.json@@ -0,0 +1,3264 @@+{+ "cost": {+ "basis": "measured",+ "label": "computed at list prices, not billed",+ "models": {+ "muse-spark-1.3": {+ "cached_input": 0.15,+ "input": 1.25,+ "output": 4.25+ },+ "muse-wonder-1.0": {+ "cached_input": 0.2,+ "input": 4.0,+ "output": 20.0+ }+ },+ "pack_build": "pack 06818eb",+ "prices_date": "2026-10-26",+ "question_tokens_nominal": 811,+ "repos": [+ "kubernetes",+ "home-assistant"+ ],+ "rows": [+ {+ "arm": "pack",+ "budget": "128K",+ "context": "Graphicle pack, standard layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.164061625,+ "follow_up_usd": 0.164061625,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 0.164061625+ },+ "muse-wonder-1.0": {+ "first_usd": 0.5249971999999999,+ "follow_up_usd": 0.5249971999999999,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 0.5249971999999999+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 0,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9127083333333335,+ "suffix_tokens": 130469+ },+ {+ "arm": "pack-cache0.5",+ "budget": "128K",+ "context": "Graphicle pack, cache layout, 50% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.158323375,+ "follow_up_usd": 0.086409775,+ "follow_up_vs_first": 0.5457802740751326,+ "session_mean_usd": 0.09000545499999998+ },+ "muse-wonder-1.0": {+ "first_usd": 0.5066347999999999,+ "follow_up_usd": 0.258206,+ "follow_up_vs_first": 0.5096491595129273,+ "session_mean_usd": 0.27062744+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 65376,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8960416666666667,+ "suffix_tokens": 60502+ },+ {+ "arm": "pack-cache0.7",+ "budget": "128K",+ "context": "Graphicle pack, cache layout, 70% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.161768140625,+ "follow_up_usd": 0.061049390625,+ "follow_up_vs_first": 0.37738821988762655,+ "session_mean_usd": 0.066085328125+ },+ "muse-wonder-1.0": {+ "first_usd": 0.51765805,+ "follow_up_usd": 0.16972055,+ "follow_up_vs_first": 0.32786228283323327,+ "session_mean_usd": 0.187117425+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 91562,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8679166666666667,+ "suffix_tokens": 37071+ },+ {+ "arm": "pack-cache",+ "budget": "128K",+ "context": "Graphicle pack, cache layout, 90% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.1637119375,+ "follow_up_usd": 0.03425733749999999,+ "follow_up_vs_first": 0.20925375402145,+ "session_mean_usd": 0.040730067499999995+ },+ "muse-wonder-1.0": {+ "first_usd": 0.5238782,+ "follow_up_usd": 0.0766714,+ "follow_up_vs_first": 0.14635348445497448,+ "session_mean_usd": 0.09903174000000001+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 117686,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8054166666666667,+ "suffix_tokens": 12503+ },+ {+ "arm": "pack-cache0.95",+ "budget": "128K",+ "context": "Graphicle pack, cache layout, 95% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.1640763125,+ "follow_up_usd": 0.0274095625,+ "follow_up_vs_first": 0.16705374518945265,+ "session_mean_usd": 0.0342429+ },+ "muse-wonder-1.0": {+ "first_usd": 0.5250442,+ "follow_up_usd": 0.052922699999999996,+ "follow_up_vs_first": 0.10079665673861363,+ "session_mean_usd": 0.076528775+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 124242,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.6570833333333335,+ "suffix_tokens": 6238+ },+ {+ "arm": "pack-stable",+ "budget": "128K",+ "context": "Graphicle pack, stable layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.1644659375,+ "follow_up_usd": 0.020594737499999998,+ "follow_up_vs_first": 0.12522190195158192,+ "session_mean_usd": 0.027788297499999996+ },+ "muse-wonder-1.0": {+ "first_usd": 0.526291,+ "follow_up_usd": 0.029281400000000003,+ "follow_up_vs_first": 0.05563728051591231,+ "session_mean_usd": 0.05413188+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 130792,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.06666666666666668,+ "suffix_tokens": 0+ },+ {+ "arm": "truncation",+ "budget": "128K",+ "context": "Truncation",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.1648084375,+ "follow_up_usd": 0.020635837499999997,+ "follow_up_vs_first": 0.12521104995003668,+ "session_mean_usd": 0.027844467499999997+ },+ "muse-wonder-1.0": {+ "first_usd": 0.527387,+ "follow_up_usd": 0.0293362,+ "follow_up_vs_first": 0.05562556528697142,+ "session_mean_usd": 0.054238739999999994+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 131066,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.016666666666666666,+ "suffix_tokens": 0+ },+ {+ "arm": "pack",+ "budget": "256K",+ "context": "Graphicle pack, standard layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.327585671875,+ "follow_up_usd": 0.327585671875,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 0.327585671875+ },+ "muse-wonder-1.0": {+ "first_usd": 1.0482741500000001,+ "follow_up_usd": 1.0482741500000001,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 1.0482741500000001+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 0,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9168750000000001,+ "suffix_tokens": 261288+ },+ {+ "arm": "pack-cache0.5",+ "budget": "256K",+ "context": "Graphicle pack, cache layout, 50% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.31070678125,+ "follow_up_usd": 0.16686143125,+ "follow_up_vs_first": 0.5370382666857226,+ "session_mean_usd": 0.17405369874999999+ },+ "muse-wonder-1.0": {+ "first_usd": 0.9942616999999999,+ "follow_up_usd": 0.49734140000000004,+ "follow_up_vs_first": 0.5002117651720871,+ "session_mean_usd": 0.522187415+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 130768,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9152083333333334,+ "suffix_tokens": 117016+ },+ {+ "arm": "pack-cache0.7",+ "budget": "256K",+ "context": "Graphicle pack, cache layout, 70% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.319785421875,+ "follow_up_usd": 0.118375421875,+ "follow_up_vs_first": 0.3701714142593762,+ "session_mean_usd": 0.12844592187499998+ },+ "muse-wonder-1.0": {+ "first_usd": 1.02331335,+ "follow_up_usd": 0.32753335,+ "follow_up_vs_first": 0.32007141312091747,+ "session_mean_usd": 0.36232235+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 183100,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9127083333333335,+ "suffix_tokens": 71948+ },+ {+ "arm": "pack-cache",+ "budget": "256K",+ "context": "Graphicle pack, cache layout, 90% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.326381359375,+ "follow_up_usd": 0.06739240937499999,+ "follow_up_vs_first": 0.20648363467831699,+ "session_mean_usd": 0.08034185687499999+ },+ "muse-wonder-1.0": {+ "first_usd": 1.04442035,+ "follow_up_usd": 0.14973125,+ "follow_up_vs_first": 0.1433630147095468,+ "session_mean_usd": 0.194465705+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 235444,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8647916666666667,+ "suffix_tokens": 24880+ },+ {+ "arm": "pack-cache0.95",+ "budget": "256K",+ "context": "Graphicle pack, cache layout, 95% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.327203359375,+ "follow_up_usd": 0.053840709375,+ "follow_up_vs_first": 0.16454815585586466,+ "session_mean_usd": 0.06750884187499999+ },+ "muse-wonder-1.0": {+ "first_usd": 1.04705075,+ "follow_up_usd": 0.10270705000000001,+ "follow_up_vs_first": 0.0980917591625812,+ "session_mean_usd": 0.14992423500000002+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 248512,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8147916666666667,+ "suffix_tokens": 12470+ },+ {+ "arm": "pack-stable",+ "budget": "256K",+ "context": "Graphicle pack, stable layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.3279734375,+ "follow_up_usd": 0.0402156375,+ "follow_up_vs_first": 0.12261858096358794,+ "session_mean_usd": 0.054603527500000006+ },+ "muse-wonder-1.0": {+ "first_usd": 1.049515,+ "follow_up_usd": 0.05544260000000001,+ "follow_up_vs_first": 0.05282687717660063,+ "session_mean_usd": 0.10514622+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 261598,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.07916666666666668,+ "suffix_tokens": 0+ },+ {+ "arm": "truncation",+ "budget": "256K",+ "context": "Truncation",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.3286453125,+ "follow_up_usd": 0.0402962625,+ "follow_up_vs_first": 0.12261322759624024,+ "session_mean_usd": 0.054713714999999996+ },+ "muse-wonder-1.0": {+ "first_usd": 1.051665,+ "follow_up_usd": 0.055550100000000005,+ "follow_up_vs_first": 0.0528210979732139,+ "session_mean_usd": 0.10535584500000002+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 262136,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.029166666666666664,+ "suffix_tokens": 0+ },+ {+ "arm": "pack",+ "budget": "512K",+ "context": "Graphicle pack, standard layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.654500875,+ "follow_up_usd": 0.654500875,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 0.654500875+ },+ "muse-wonder-1.0": {+ "first_usd": 2.0944028,+ "follow_up_usd": 2.0944028,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 2.0944028+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 0,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9589583333333334,+ "suffix_tokens": 522820+ },+ {+ "arm": "pack-cache0.5",+ "budget": "512K",+ "context": "Graphicle pack, cache layout, 50% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.610364203125,+ "follow_up_usd": 0.322606953125,+ "follow_up_vs_first": 0.5285482855535869,+ "session_mean_usd": 0.336994815625+ },+ "muse-wonder-1.0": {+ "first_usd": 1.95316545,+ "follow_up_usd": 0.95909495,+ "follow_up_vs_first": 0.4910464446317131,+ "session_mean_usd": 1.008798475+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 261598,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9127083333333335,+ "suffix_tokens": 225913+ },+ {+ "arm": "pack-cache0.7",+ "budget": "512K",+ "context": "Graphicle pack, cache layout, 70% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.63255221875,+ "follow_up_usd": 0.22969921875,+ "follow_up_vs_first": 0.3631308403342787,+ "session_mean_usd": 0.24984186875+ },+ "muse-wonder-1.0": {+ "first_usd": 2.0241671,+ "follow_up_usd": 0.6324931,+ "follow_up_vs_first": 0.31247079354268725,+ "session_mean_usd": 0.7020768000000001+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 366230,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9318750000000001,+ "suffix_tokens": 139031+ },+ {+ "arm": "pack-cache",+ "budget": "512K",+ "context": "Graphicle pack, cache layout, 90% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.65037228125,+ "follow_up_usd": 0.13237293125,+ "follow_up_vs_first": 0.20353409126782337,+ "session_mean_usd": 0.15827289875+ },+ "muse-wonder-1.0": {+ "first_usd": 2.0811913,+ "follow_up_usd": 0.291739,+ "follow_up_vs_first": 0.1401788485277639,+ "session_mean_usd": 0.38121161500000006+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 470908,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9002083333333335,+ "suffix_tokens": 48609+ },+ {+ "arm": "pack-cache0.95",+ "budget": "512K",+ "context": "Graphicle pack, cache layout, 95% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.6533516875,+ "follow_up_usd": 0.10657963749999999,+ "follow_up_vs_first": 0.16312751545468382,+ "session_mean_usd": 0.13391824+ },+ "muse-wonder-1.0": {+ "first_usd": 2.0907253999999997,+ "follow_up_usd": 0.2018765,+ "follow_up_vs_first": 0.09655811327494276,+ "session_mean_usd": 0.296318945+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 497066,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.8595833333333335,+ "suffix_tokens": 24835+ },+ {+ "arm": "pack-stable",+ "budget": "512K",+ "context": "Graphicle pack, stable layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.6550084375,+ "follow_up_usd": 0.07945983749999999,+ "follow_up_vs_first": 0.12131116631608274,+ "session_mean_usd": 0.10823726749999998+ },+ "muse-wonder-1.0": {+ "first_usd": 2.096027,+ "follow_up_usd": 0.10776820000000001,+ "follow_up_vs_first": 0.05141546363668026,+ "session_mean_usd": 0.20718114+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 523226,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.09166666666666667,+ "suffix_tokens": 0+ },+ {+ "arm": "truncation",+ "budget": "512K",+ "context": "Truncation",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 0.6563328125,+ "follow_up_usd": 0.0796187625,+ "follow_up_vs_first": 0.12130852059144917,+ "session_mean_usd": 0.108454465+ },+ "muse-wonder-1.0": {+ "first_usd": 2.100265,+ "follow_up_usd": 0.10798010000000001,+ "follow_up_vs_first": 0.0514126074566781,+ "session_mean_usd": 0.207594345+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 524286,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.041666666666666664,+ "suffix_tokens": 0+ },+ {+ "arm": "pack",+ "budget": "1M",+ "context": "Graphicle pack, standard layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.267228546875,+ "follow_up_usd": 1.267228546875,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 1.267228546875+ },+ "muse-wonder-1.0": {+ "first_usd": 4.05513135,+ "follow_up_usd": 4.05513135,+ "follow_up_vs_first": 1.0,+ "session_mean_usd": 4.05513135+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 0,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9620833333333334,+ "suffix_tokens": 1013002+ },+ {+ "arm": "pack-cache0.5",+ "budget": "1M",+ "context": "Graphicle pack, cache layout, 50% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.1678713125,+ "follow_up_usd": 0.6103286125,+ "follow_up_vs_first": 0.5225991990448863,+ "session_mean_usd": 0.6382057475+ },+ "muse-wonder-1.0": {+ "first_usd": 3.7371882000000003,+ "follow_up_usd": 1.8111316,+ "follow_up_vs_first": 0.48462413533254756,+ "session_mean_usd": 1.90743443+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 506857,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9589583333333334,+ "suffix_tokens": 426659+ },+ {+ "arm": "pack-cache0.7",+ "budget": "1M",+ "context": "Graphicle pack, cache layout, 70% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.214029125,+ "follow_up_usd": 0.43344822499999996,+ "follow_up_vs_first": 0.3570328059468919,+ "session_mean_usd": 0.47247727+ },+ "muse-wonder-1.0": {+ "first_usd": 3.8848932,+ "follow_up_usd": 1.188341,+ "follow_up_vs_first": 0.30588768823812196,+ "session_mean_usd": 1.3231686100000002+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 709619,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.929375,+ "suffix_tokens": 260824+ },+ {+ "arm": "pack-cache",+ "budget": "1M",+ "context": "Graphicle pack, cache layout, 90% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.25549175,+ "follow_up_usd": 0.25188585,+ "follow_up_vs_first": 0.20062724426504597,+ "session_mean_usd": 0.30206614500000006+ },+ "muse-wonder-1.0": {+ "first_usd": 4.0175736,+ "follow_up_usd": 0.5505714,+ "follow_up_vs_first": 0.13704077505885642,+ "session_mean_usd": 0.72392151+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 912369,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9443750000000002,+ "suffix_tokens": 91244+ },+ {+ "arm": "pack-cache0.95",+ "budget": "1M",+ "context": "Graphicle pack, cache layout, 95% prefix",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.263433609375,+ "follow_up_usd": 0.20406155937499998,+ "follow_up_vs_first": 0.16151348029750917,+ "session_mean_usd": 0.257030161875+ },+ "muse-wonder-1.0": {+ "first_usd": 4.042987549999999,+ "follow_up_usd": 0.38333865,+ "follow_up_vs_first": 0.09481568895753836,+ "session_mean_usd": 0.5663210949999999+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 963066,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.9214583333333334,+ "suffix_tokens": 46901+ },+ {+ "arm": "pack-stable",+ "budget": "1M",+ "context": "Graphicle pack, stable layout",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.2681784375,+ "follow_up_usd": 0.15304023749999998,+ "follow_up_vs_first": 0.12067721148270981,+ "session_mean_usd": 0.20879714749999997+ },+ "muse-wonder-1.0": {+ "first_usd": 4.058171,+ "follow_up_usd": 0.20587540000000001,+ "follow_up_vs_first": 0.05073108057792538,+ "session_mean_usd": 0.39849018+ }+ },+ "prefix_hashes_per_repository": 1,+ "prefix_tokens": 1013762,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.18208333333333335,+ "suffix_tokens": 0+ },+ {+ "arm": "truncation",+ "budget": "1M",+ "context": "Truncation",+ "models": {+ "muse-spark-1.3": {+ "first_usd": 1.2707253125,+ "follow_up_usd": 0.15334586249999999,+ "follow_up_vs_first": 0.12067585416891582,+ "session_mean_usd": 0.209214835+ },+ "muse-wonder-1.0": {+ "first_usd": 4.066321,+ "follow_up_usd": 0.20628290000000002,+ "follow_up_vs_first": 0.050729615295988684,+ "session_mean_usd": 0.399284805+ }+ },+ "prefix_hashes_per_repository": null,+ "prefix_tokens": 1015800,+ "question_tokens": 781,+ "questions": 80,+ "recall": 0.06999999999999999,+ "suffix_tokens": 0+ }+ ],+ "session": 20,+ "tokenizer": "tokenizer.json"+ },+ "counter": "exact:muse-tokenizer/tokenizer.json",+ "counter_label": "counted with the Muse Spark Open tokenizer (Hugging Face revision 4239e4db)",+ "estimate_counter": "estimate:utf8-bytes/4",+ "generated": "2026-10-27",+ "merged_until": "2026-10-25T23:59:59Z",+ "paired": [],+ "prices": {+ "date": "2026-10-26",+ "models": {+ "meta-models/muse-spark-open": {+ "cached_input": 0.15,+ "input": 1.25,+ "note": "Muse Spark Open on Baseten's Model APIs (https://www.baseten.co/pricing)",+ "output": 4.25,+ "provider": "baseten"+ },+ "mock": {+ "cached_input": 0.15,+ "input": 1.25,+ "note": "the mock server, priced like muse-spark-1.3 to test the spend caps",+ "output": 4.25,+ "provider": "mock"+ },+ "muse-spark-1.2": {+ "cached_input": 0.15,+ "input": 1.25,+ "output": 4.25,+ "provider": "meta"+ },+ "muse-spark-1.3": {+ "cached_input": 0.15,+ "input": 1.25,+ "output": 4.25,+ "provider": "meta"+ },+ "muse-spark-1.3-contributor": {+ "cached_input": 0.002,+ "input": 0.1,+ "note": "Contributor mode: Meta may use the prompts, context and responses to train future models; 150 requests and 3M tokens per minute (same page, read 2026-10-26)",+ "output": 0.2,+ "provider": "meta"+ },+ "muse-spark-open": {+ "cached_input": 0.0,+ "input": 0.0,+ "note": "our own GPUs: no per-token price",+ "output": 0.0,+ "provider": "local"+ },+ "muse-wonder-1.0": {+ "cached_input": 0.2,+ "input": 4.0,+ "output": 20.0,+ "provider": "meta"+ }+ },+ "source": "https://dev.meta.ai/docs/pricing-rate-limits (Standard mode; the page states no long-context surcharge) and https://www.baseten.co/pricing (Model APIs), both read 2026-10-26",+ "unit": "US dollars per million tokens"+ },+ "recall": [+ {+ "errors": 0,+ "label": "pack 2a46edb, built before the event: held-out repositories",+ "pack_source": "pack",+ "rows": [+ {+ "all": 0.3333333333333333,+ "any": 0.5666666666666667,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 19,+ "manifest-only": 8,+ "ranked-cut": 8,+ "unranked": 13+ },+ "n": 30,+ "peak_mib": {+ "max": 1656.6,+ "median": 1090.9,+ "p90": 1396.2+ },+ "recall": 0.43833333333333335,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": {+ "max": 53.606,+ "median": 12.553,+ "p90": 19.944+ },+ "source": "graphicle pack",+ "tokens": 65211.0+ },+ {+ "all": 0.32142857142857145,+ "any": 0.5357142857142857,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 17,+ "manifest-only": 8,+ "ranked-cut": 7,+ "unranked": 13+ },+ "n": 28,+ "peak_mib": {+ "max": 1656.6,+ "median": 1110.15,+ "p90": 1396.2+ },+ "recall": 0.4160714285714286,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": {+ "max": 53.606,+ "median": 12.553,+ "p90": 19.944+ },+ "source": "graphicle pack",+ "tokens": 65191.5+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65521.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 28,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65521.0+ },+ {+ "all": 0.43333333333333335,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 25,+ "manifest-only": 4,+ "ranked-cut": 6,+ "unranked": 13+ },+ "n": 30,+ "peak_mib": {+ "max": 1664.3,+ "median": 1086.35,+ "p90": 1386.5+ },+ "recall": 0.5466666666666666,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": {+ "max": 53.743,+ "median": 12.6645,+ "p90": 19.873+ },+ "source": "graphicle pack",+ "tokens": 130832.46666666666+ },+ {+ "all": 0.42857142857142855,+ "any": 0.6428571428571429,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 23,+ "manifest-only": 3,+ "ranked-cut": 6,+ "unranked": 13+ },+ "n": 28,+ "peak_mib": {+ "max": 1664.3,+ "median": 1096.6,+ "p90": 1386.5+ },+ "recall": 0.5321428571428571,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": {+ "max": 53.743,+ "median": 12.6645,+ "p90": 19.873+ },+ "source": "graphicle pack",+ "tokens": 130834.10714285714+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131069.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 28,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131069.0+ },+ {+ "all": 0.43333333333333335,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 25,+ "manifest-only": 4,+ "ranked-cut": 6,+ "unranked": 13+ },+ "n": 30,+ "peak_mib": {+ "max": 1656.7,+ "median": 1093.65,+ "p90": 1384.3+ },+ "recall": 0.5466666666666666,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": {+ "max": 54.341,+ "median": 13.3205,+ "p90": 21.168+ },+ "source": "graphicle pack",+ "tokens": 261907.26666666666+ },+ {+ "all": 0.42857142857142855,+ "any": 0.6428571428571429,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 23,+ "manifest-only": 3,+ "ranked-cut": 6,+ "unranked": 13+ },+ "n": 28,+ "peak_mib": {+ "max": 1656.7,+ "median": 1096.55,+ "p90": 1384.3+ },+ "recall": 0.5321428571428571,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": {+ "max": 54.341,+ "median": 13.3205,+ "p90": 21.168+ },+ "source": "graphicle pack",+ "tokens": 261897.7142857143+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262140.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 28,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262140.0+ },+ {+ "all": 0.5,+ "any": 0.7,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 29,+ "manifest-only": 5,+ "ranked-cut": 1,+ "unranked": 13+ },+ "n": 30,+ "peak_mib": {+ "max": 1656.0,+ "median": 1083.65,+ "p90": 1393.4+ },+ "recall": 0.6116666666666667,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": {+ "max": 55.01,+ "median": 13.594000000000001,+ "p90": 21.277+ },+ "source": "graphicle pack",+ "tokens": 523735.1+ },+ {+ "all": 0.4642857142857143,+ "any": 0.6785714285714286,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 26,+ "manifest-only": 5,+ "ranked-cut": 1,+ "unranked": 13+ },+ "n": 28,+ "peak_mib": {+ "max": 1656.0,+ "median": 1095.9,+ "p90": 1393.4+ },+ "recall": 0.5839285714285715,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": {+ "max": 55.01,+ "median": 13.594000000000001,+ "p90": 21.277+ },+ "source": "graphicle pack",+ "tokens": 523741.4285714286+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524285.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 28,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524285.0+ },+ {+ "all": 0.6666666666666666,+ "any": 0.8333333333333334,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 34,+ "manifest-only": 1,+ "unranked": 13+ },+ "n": 30,+ "peak_mib": {+ "max": 1656.3,+ "median": 1184.0,+ "p90": 1385.2+ },+ "recall": 0.7616666666666667,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": {+ "max": 58.048,+ "median": 14.907,+ "p90": 22.819+ },+ "source": "graphicle pack",+ "tokens": 1013897.9333333333+ },+ {+ "all": 0.6428571428571429,+ "any": 0.8214285714285714,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 31,+ "manifest-only": 1,+ "unranked": 13+ },+ "n": 28,+ "peak_mib": {+ "max": 1656.3,+ "median": 1185.0,+ "p90": 1385.2+ },+ "recall": 0.7446428571428572,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": {+ "max": 58.048,+ "median": 14.907,+ "p90": 22.819+ },+ "source": "graphicle pack",+ "tokens": 1013994.1428571428+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015796.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 28,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "elasticsearch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015796.0+ },+ {+ "all": 0.5666666666666667,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 24,+ "manifest-only": 7,+ "ranked-cut": 6,+ "unranked": 5+ },+ "n": 30,+ "peak_mib": {+ "max": 977.4,+ "median": 829.85,+ "p90": 930.5+ },+ "recall": 0.6027777777777777,+ "repo": "pytorch",+ "scope": "all",+ "seconds": {+ "max": 31.364,+ "median": 10.551,+ "p90": 22.48+ },+ "source": "graphicle pack",+ "tokens": 65129.96666666667+ },+ {+ "all": 0.47619047619047616,+ "any": 0.5238095238095238,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 13,+ "manifest-only": 5,+ "ranked-cut": 5,+ "unranked": 5+ },+ "n": 21,+ "peak_mib": {+ "max": 977.4,+ "median": 854.6,+ "p90": 931.9+ },+ "recall": 0.4880952380952381,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": {+ "max": 31.364,+ "median": 8.304,+ "p90": 22.723+ },+ "source": "graphicle pack",+ "tokens": 65123.23809523809+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65526.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 21,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65526.0+ },+ {+ "all": 0.6666666666666666,+ "any": 0.7666666666666667,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 29,+ "manifest-only": 3,+ "ranked-cut": 5,+ "unranked": 5+ },+ "n": 30,+ "peak_mib": {+ "max": 991.1,+ "median": 842.7,+ "p90": 937.5+ },+ "recall": 0.7194444444444444,+ "repo": "pytorch",+ "scope": "all",+ "seconds": {+ "max": 31.608,+ "median": 10.552,+ "p90": 22.583+ },+ "source": "graphicle pack",+ "tokens": 130504.66666666667+ },+ {+ "all": 0.6190476190476191,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 18,+ "manifest-only": 1,+ "ranked-cut": 4,+ "unranked": 5+ },+ "n": 21,+ "peak_mib": {+ "max": 991.1,+ "median": 856.9,+ "p90": 958.9+ },+ "recall": 0.6547619047619048,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": {+ "max": 31.608,+ "median": 8.222,+ "p90": 22.673+ },+ "source": "graphicle pack",+ "tokens": 130490.42857142857+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131067.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 21,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131067.0+ },+ {+ "all": 0.6,+ "any": 0.7,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 27,+ "manifest-only": 7,+ "ranked-cut": 3,+ "unranked": 5+ },+ "n": 30,+ "peak_mib": {+ "max": 986.3,+ "median": 837.95,+ "p90": 935.0+ },+ "recall": 0.6527777777777778,+ "repo": "pytorch",+ "scope": "all",+ "seconds": {+ "max": 33.387,+ "median": 10.9205,+ "p90": 23.711+ },+ "source": "graphicle pack",+ "tokens": 261273.93333333332+ },+ {+ "all": 0.5238095238095238,+ "any": 0.5714285714285714,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 16,+ "manifest-only": 5,+ "ranked-cut": 2,+ "unranked": 5+ },+ "n": 21,+ "peak_mib": {+ "max": 986.3,+ "median": 856.7,+ "p90": 950.1+ },+ "recall": 0.5595238095238095,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": {+ "max": 33.387,+ "median": 9.856,+ "p90": 24.013+ },+ "source": "graphicle pack",+ "tokens": 261256.04761904763+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262141.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 21,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262141.0+ },+ {+ "all": 0.6666666666666666,+ "any": 0.7666666666666667,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 29,+ "manifest-only": 6,+ "ranked-cut": 2,+ "unranked": 5+ },+ "n": 30,+ "peak_mib": {+ "max": 981.6,+ "median": 827.3,+ "p90": 932.2+ },+ "recall": 0.7194444444444444,+ "repo": "pytorch",+ "scope": "all",+ "seconds": {+ "max": 33.986,+ "median": 11.504999999999999,+ "p90": 23.789+ },+ "source": "graphicle pack",+ "tokens": 522814.8+ },+ {+ "all": 0.6190476190476191,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 18,+ "manifest-only": 4,+ "ranked-cut": 1,+ "unranked": 5+ },+ "n": 21,+ "peak_mib": {+ "max": 981.6,+ "median": 856.7,+ "p90": 954.1+ },+ "recall": 0.6547619047619048,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": {+ "max": 33.986,+ "median": 10.204,+ "p90": 24.8+ },+ "source": "graphicle pack",+ "tokens": 522844.3333333333+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524283.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 21,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524283.0+ },+ {+ "all": 0.7666666666666667,+ "any": 0.8333333333333334,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 34,+ "manifest-only": 3,+ "unranked": 5+ },+ "n": 30,+ "peak_mib": {+ "max": 1057.3,+ "median": 935.9000000000001,+ "p90": 971.7+ },+ "recall": 0.8,+ "repo": "pytorch",+ "scope": "all",+ "seconds": {+ "max": 33.84,+ "median": 12.947,+ "p90": 25.129+ },+ "source": "graphicle pack",+ "tokens": 1012924.2333333333+ },+ {+ "all": 0.7142857142857143,+ "any": 0.7619047619047619,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 21,+ "manifest-only": 2,+ "unranked": 5+ },+ "n": 21,+ "peak_mib": {+ "max": 979.5,+ "median": 934.0,+ "p90": 971.7+ },+ "recall": 0.7301587301587302,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": {+ "max": 33.84,+ "median": 10.601,+ "p90": 25.153+ },+ "source": "graphicle pack",+ "tokens": 1012978.0952380953+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015805.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 21,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "pytorch",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015805.0+ },+ {+ "all": 0.6333333333333333,+ "any": 0.6333333333333333,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 25,+ "manifest-only": 4,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 30,+ "peak_mib": {+ "max": 1001.6,+ "median": 685.25,+ "p90": 913.1+ },+ "recall": 0.6333333333333333,+ "repo": "vscode",+ "scope": "all",+ "seconds": {+ "max": 25.022,+ "median": 5.229,+ "p90": 10.422+ },+ "source": "graphicle pack",+ "tokens": 65272.666666666664+ },+ {+ "all": 0.56,+ "any": 0.56,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 18,+ "manifest-only": 4,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 25,+ "peak_mib": {+ "max": 941.3,+ "median": 681.1,+ "p90": 839.1+ },+ "recall": 0.56,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": {+ "max": 14.206,+ "median": 5.073,+ "p90": 8.789+ },+ "source": "graphicle pack",+ "tokens": 65264.44+ },+ {+ "all": 0.03333333333333333,+ "any": 0.03333333333333333,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.03333333333333333,+ "repo": "vscode",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65533.0+ },+ {+ "all": 0.04,+ "any": 0.04,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 25,+ "peak_mib": null,+ "recall": 0.04,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65533.0+ },+ {+ "all": 0.6333333333333333,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 26,+ "manifest-only": 3,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 30,+ "peak_mib": {+ "max": 987.6,+ "median": 689.9000000000001,+ "p90": 902.9+ },+ "recall": 0.6416666666666667,+ "repo": "vscode",+ "scope": "all",+ "seconds": {+ "max": 25.137,+ "median": 5.390000000000001,+ "p90": 10.693+ },+ "source": "graphicle pack",+ "tokens": 130658.93333333333+ },+ {+ "all": 0.56,+ "any": 0.6,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 19,+ "manifest-only": 3,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 25,+ "peak_mib": {+ "max": 945.3,+ "median": 685.0,+ "p90": 809.8+ },+ "recall": 0.57,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": {+ "max": 14.061,+ "median": 4.978,+ "p90": 9.0+ },+ "source": "graphicle pack",+ "tokens": 130665.76+ },+ {+ "all": 0.03333333333333333,+ "any": 0.03333333333333333,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.03333333333333333,+ "repo": "vscode",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131071.0+ },+ {+ "all": 0.04,+ "any": 0.04,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 25,+ "peak_mib": null,+ "recall": 0.04,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131071.0+ },+ {+ "all": 0.6333333333333333,+ "any": 0.6666666666666666,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 26,+ "manifest-only": 3,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 30,+ "peak_mib": {+ "max": 1007.1,+ "median": 694.9000000000001,+ "p90": 923.6+ },+ "recall": 0.6416666666666667,+ "repo": "vscode",+ "scope": "all",+ "seconds": {+ "max": 25.949,+ "median": 6.6065000000000005,+ "p90": 11.207+ },+ "source": "graphicle pack",+ "tokens": 261499.2+ },+ {+ "all": 0.56,+ "any": 0.6,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 19,+ "manifest-only": 3,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 25,+ "peak_mib": {+ "max": 943.2,+ "median": 685.4,+ "p90": 836.6+ },+ "recall": 0.57,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": {+ "max": 15.164,+ "median": 6.178,+ "p90": 9.516+ },+ "source": "graphicle pack",+ "tokens": 261507.76+ },+ {+ "all": 0.03333333333333333,+ "any": 0.03333333333333333,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.03333333333333333,+ "repo": "vscode",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262127.0+ },+ {+ "all": 0.04,+ "any": 0.04,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 25,+ "peak_mib": null,+ "recall": 0.04,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262127.0+ },+ {+ "all": 0.7,+ "any": 0.7333333333333333,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 28,+ "manifest-only": 1,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 30,+ "peak_mib": {+ "max": 1004.3,+ "median": 735.2,+ "p90": 916.9+ },+ "recall": 0.7083333333333334,+ "repo": "vscode",+ "scope": "all",+ "seconds": {+ "max": 26.807,+ "median": 7.05,+ "p90": 12.327+ },+ "source": "graphicle pack",+ "tokens": 523154.86666666664+ },+ {+ "all": 0.64,+ "any": 0.68,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 21,+ "manifest-only": 1,+ "ranked-cut": 2,+ "unranked": 10+ },+ "n": 25,+ "peak_mib": {+ "max": 949.2,+ "median": 722.9,+ "p90": 824.2+ },+ "recall": 0.65,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": {+ "max": 15.336,+ "median": 6.804,+ "p90": 10.066+ },+ "source": "graphicle pack",+ "tokens": 523160.84+ },+ {+ "all": 0.03333333333333333,+ "any": 0.03333333333333333,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.03333333333333333,+ "repo": "vscode",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524288.0+ },+ {+ "all": 0.04,+ "any": 0.04,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 25,+ "peak_mib": null,+ "recall": 0.04,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524288.0+ },+ {+ "all": 0.7333333333333333,+ "any": 0.7666666666666667,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 29,+ "manifest-only": 2,+ "unranked": 10+ },+ "n": 30,+ "peak_mib": {+ "max": 1041.1,+ "median": 971.35,+ "p90": 1023.3+ },+ "recall": 0.7416666666666667,+ "repo": "vscode",+ "scope": "all",+ "seconds": {+ "max": 27.793,+ "median": 7.646,+ "p90": 13.884+ },+ "source": "graphicle pack",+ "tokens": 1013852.4666666667+ },+ {+ "all": 0.68,+ "any": 0.72,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 22,+ "manifest-only": 2,+ "unranked": 10+ },+ "n": 25,+ "peak_mib": {+ "max": 1041.1,+ "median": 970.1,+ "p90": 1019.2+ },+ "recall": 0.69,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": {+ "max": 16.29,+ "median": 7.433,+ "p90": 11.423+ },+ "source": "graphicle pack",+ "tokens": 1013844.48+ },+ {+ "all": 0.06666666666666667,+ "any": 0.06666666666666667,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.06666666666666667,+ "repo": "vscode",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015797.0+ },+ {+ "all": 0.08,+ "any": 0.08,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 25,+ "peak_mib": null,+ "recall": 0.08,+ "repo": "vscode",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015797.0+ }+ ],+ "tokenizer": "tokenizer.json"+ },+ {+ "errors": 0,+ "label": "pack 2a46edb, built before the event: development repositories (used for tuning)",+ "pack_source": "pack",+ "rows": [+ {+ "all": 0.925,+ "any": 0.95,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 61,+ "manifest-only": 1,+ "ranked-cut": 2+ },+ "n": 40,+ "peak_mib": {+ "max": 1105.0,+ "median": 667.7,+ "p90": 883.0+ },+ "recall": 0.9416666666666668,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": {+ "max": 13.558,+ "median": 5.914,+ "p90": 9.998+ },+ "source": "graphicle pack",+ "tokens": 64823.5+ },+ {+ "all": 0.9,+ "any": 0.9333333333333333,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 46,+ "manifest-only": 1,+ "ranked-cut": 2+ },+ "n": 30,+ "peak_mib": {+ "max": 1105.0,+ "median": 666.85,+ "p90": 861.0+ },+ "recall": 0.9222222222222223,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": {+ "max": 13.558,+ "median": 5.9785,+ "p90": 9.998+ },+ "source": "graphicle pack",+ "tokens": 64821.26666666667+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65534.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65534.0+ },+ {+ "all": 0.925,+ "any": 0.95,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 61,+ "manifest-only": 2,+ "ranked-cut": 1+ },+ "n": 40,+ "peak_mib": {+ "max": 1082.0,+ "median": 683.4000000000001,+ "p90": 880.3+ },+ "recall": 0.9416666666666668,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": {+ "max": 13.688,+ "median": 6.132,+ "p90": 9.976+ },+ "source": "graphicle pack",+ "tokens": 130188.125+ },+ {+ "all": 0.9,+ "any": 0.9333333333333333,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 46,+ "manifest-only": 2,+ "ranked-cut": 1+ },+ "n": 30,+ "peak_mib": {+ "max": 1082.0,+ "median": 678.45,+ "p90": 859.8+ },+ "recall": 0.9222222222222223,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": {+ "max": 13.688,+ "median": 6.276999999999999,+ "p90": 9.976+ },+ "source": "graphicle pack",+ "tokens": 130183.8+ },+ {+ "all": 0.025,+ "any": 0.05,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.03333333333333333,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131072.0+ },+ {+ "all": 0.03333333333333333,+ "any": 0.06666666666666667,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.04444444444444444,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131072.0+ },+ {+ "all": 0.925,+ "any": 0.95,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 61,+ "manifest-only": 2,+ "ranked-cut": 1+ },+ "n": 40,+ "peak_mib": {+ "max": 1100.7,+ "median": 665.2,+ "p90": 894.3+ },+ "recall": 0.9416666666666668,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": {+ "max": 14.47,+ "median": 6.697,+ "p90": 10.858+ },+ "source": "graphicle pack",+ "tokens": 260994.7+ },+ {+ "all": 0.9,+ "any": 0.9333333333333333,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 46,+ "manifest-only": 2,+ "ranked-cut": 1+ },+ "n": 30,+ "peak_mib": {+ "max": 1100.7,+ "median": 665.2,+ "p90": 864.8+ },+ "recall": 0.9222222222222223,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": {+ "max": 14.47,+ "median": 6.745,+ "p90": 10.858+ },+ "source": "graphicle pack",+ "tokens": 260989.5+ },+ {+ "all": 0.05,+ "any": 0.075,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.05833333333333333,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262127.0+ },+ {+ "all": 0.03333333333333333,+ "any": 0.06666666666666667,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.04444444444444444,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262127.0+ },+ {+ "all": 1.0,+ "any": 1.0,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 64+ },+ "n": 40,+ "peak_mib": {+ "max": 1101.8,+ "median": 667.75,+ "p90": 884.3+ },+ "recall": 1.0,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": {+ "max": 15.371,+ "median": 7.083,+ "p90": 11.418+ },+ "source": "graphicle pack",+ "tokens": 522503.025+ },+ {+ "all": 1.0,+ "any": 1.0,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 49+ },+ "n": 30,+ "peak_mib": {+ "max": 1101.8,+ "median": 667.75,+ "p90": 865.4+ },+ "recall": 1.0,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": {+ "max": 15.371,+ "median": 7.1965,+ "p90": 11.418+ },+ "source": "graphicle pack",+ "tokens": 522506.5333333333+ },+ {+ "all": 0.075,+ "any": 0.1,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.08333333333333333,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524284.0+ },+ {+ "all": 0.06666666666666667,+ "any": 0.1,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.07777777777777777,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524284.0+ },+ {+ "all": 1.0,+ "any": 1.0,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 64+ },+ "n": 40,+ "peak_mib": {+ "max": 1112.7,+ "median": 903.35,+ "p90": 953.6+ },+ "recall": 1.0,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": {+ "max": 16.929,+ "median": 8.2985,+ "p90": 12.043+ },+ "source": "graphicle pack",+ "tokens": 1012449.55+ },+ {+ "all": 1.0,+ "any": 1.0,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 49+ },+ "n": 30,+ "peak_mib": {+ "max": 1112.7,+ "median": 903.2,+ "p90": 948.2+ },+ "recall": 1.0,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": {+ "max": 16.929,+ "median": 8.5445,+ "p90": 12.043+ },+ "source": "graphicle pack",+ "tokens": 1012470.2333333333+ },+ {+ "all": 0.125,+ "any": 0.125,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.125,+ "repo": "home-assistant",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015808.0+ },+ {+ "all": 0.1,+ "any": 0.1,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 30,+ "peak_mib": null,+ "recall": 0.1,+ "repo": "home-assistant",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015808.0+ },+ {+ "all": 0.775,+ "any": 0.9,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 47,+ "manifest-only": 6,+ "ranked-cut": 2,+ "unranked": 8+ },+ "n": 40,+ "peak_mib": {+ "max": 1861.7,+ "median": 926.35,+ "p90": 1198.8+ },+ "recall": 0.8504166666666666,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": {+ "max": 18.036,+ "median": 9.032,+ "p90": 14.201+ },+ "source": "graphicle pack",+ "tokens": 65322.175+ },+ {+ "all": 0.6470588235294118,+ "any": 0.8823529411764706,+ "arm": "pack",+ "budget": "64K",+ "gold_status": {+ "inside": 20,+ "manifest-only": 2,+ "ranked-cut": 2,+ "unranked": 6+ },+ "n": 17,+ "peak_mib": {+ "max": 1284.8,+ "median": 847.5,+ "p90": 1071.9+ },+ "recall": 0.7852941176470588,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": {+ "max": 15.219,+ "median": 6.842,+ "p90": 10.388+ },+ "source": "graphicle pack",+ "tokens": 65325.64705882353+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65536.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "64K",+ "gold_status": {},+ "n": 17,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 65536.0+ },+ {+ "all": 0.825,+ "any": 0.925,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 50,+ "manifest-only": 5,+ "unranked": 8+ },+ "n": 40,+ "peak_mib": {+ "max": 1865.1,+ "median": 931.5,+ "p90": 1198.6+ },+ "recall": 0.88375,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": {+ "max": 18.467,+ "median": 9.008,+ "p90": 14.378+ },+ "source": "graphicle pack",+ "tokens": 130748.975+ },+ {+ "all": 0.7058823529411765,+ "any": 0.8823529411764706,+ "arm": "pack",+ "budget": "128K",+ "gold_status": {+ "inside": 21,+ "manifest-only": 3,+ "unranked": 6+ },+ "n": 17,+ "peak_mib": {+ "max": 1286.8,+ "median": 865.1,+ "p90": 1056.4+ },+ "recall": 0.8147058823529412,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": {+ "max": 15.162,+ "median": 6.936,+ "p90": 10.562+ },+ "source": "graphicle pack",+ "tokens": 130758.41176470589+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131060.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "128K",+ "gold_status": {},+ "n": 17,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 131060.0+ },+ {+ "all": 0.825,+ "any": 0.95,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 51,+ "manifest-only": 4,+ "unranked": 8+ },+ "n": 40,+ "peak_mib": {+ "max": 1863.9,+ "median": 925.5,+ "p90": 1199.1+ },+ "recall": 0.8920833333333335,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": {+ "max": 18.872,+ "median": 9.625499999999999,+ "p90": 14.761+ },+ "source": "graphicle pack",+ "tokens": 261580.875+ },+ {+ "all": 0.7058823529411765,+ "any": 0.8823529411764706,+ "arm": "pack",+ "budget": "256K",+ "gold_status": {+ "inside": 21,+ "manifest-only": 3,+ "unranked": 6+ },+ "n": 17,+ "peak_mib": {+ "max": 1286.8,+ "median": 857.1,+ "p90": 1071.3+ },+ "recall": 0.8147058823529412,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": {+ "max": 16.191,+ "median": 7.331,+ "p90": 11.125+ },+ "source": "graphicle pack",+ "tokens": 261611.23529411765+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262144.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "256K",+ "gold_status": {},+ "n": 17,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 262144.0+ },+ {+ "all": 0.825,+ "any": 0.975,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 54,+ "manifest-only": 1,+ "unranked": 8+ },+ "n": 40,+ "peak_mib": {+ "max": 1861.0,+ "median": 929.45,+ "p90": 1199.7+ },+ "recall": 0.9179166666666667,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": {+ "max": 19.234,+ "median": 10.211500000000001,+ "p90": 15.305+ },+ "source": "graphicle pack",+ "tokens": 523136.875+ },+ {+ "all": 0.7058823529411765,+ "any": 0.9411764705882353,+ "arm": "pack",+ "budget": "512K",+ "gold_status": {+ "inside": 23,+ "manifest-only": 1,+ "unranked": 6+ },+ "n": 17,+ "peak_mib": {+ "max": 1287.6,+ "median": 855.7,+ "p90": 1060.8+ },+ "recall": 0.8558823529411765,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": {+ "max": 16.064,+ "median": 8.59,+ "p90": 11.526+ },+ "source": "graphicle pack",+ "tokens": 523124.29411764705+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524287.0+ },+ {+ "all": 0.0,+ "any": 0.0,+ "arm": "truncation",+ "budget": "512K",+ "gold_status": {},+ "n": 17,+ "peak_mib": null,+ "recall": 0.0,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 524287.0+ },+ {+ "all": 0.825,+ "any": 0.975,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 55,+ "unranked": 8+ },+ "n": 40,+ "peak_mib": {+ "max": 1862.6,+ "median": 958.25,+ "p90": 1199.1+ },+ "recall": 0.9241666666666667,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": {+ "max": 20.412,+ "median": 11.2385,+ "p90": 16.218+ },+ "source": "graphicle pack",+ "tokens": 1013554.625+ },+ {+ "all": 0.7058823529411765,+ "any": 0.9411764705882353,+ "arm": "pack",+ "budget": "1M",+ "gold_status": {+ "inside": 24,+ "unranked": 6+ },+ "n": 17,+ "peak_mib": {+ "max": 1289.0,+ "median": 946.3,+ "p90": 1069.3+ },+ "recall": 0.8705882352941177,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": {+ "max": 17.271,+ "median": 9.66,+ "p90": 12.399+ },+ "source": "graphicle pack",+ "tokens": 1013551.2941176471+ },+ {+ "all": 0.0,+ "any": 0.025,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 40,+ "peak_mib": null,+ "recall": 0.015,+ "repo": "kubernetes",+ "scope": "all",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015791.0+ },+ {+ "all": 0.0,+ "any": 0.058823529411764705,+ "arm": "truncation",+ "budget": "1M",+ "gold_status": {},+ "n": 17,+ "peak_mib": null,+ "recall": 0.03529411764705882,+ "repo": "kubernetes",+ "scope": "without_named",+ "seconds": null,+ "source": "truncation (exact:muse-tokenizer/tokenizer.json)",+ "tokens": 1015791.0+ }+ ],+ "tokenizer": "tokenizer.json"+ }+ ],+ "registered": [+ {+ "cap_usd": 45.0,+ "description": "Meta, grid C: the 128K arms on the 90 held-out questions",+ "estimate_cached_usd": 34.48,+ "estimate_uncached_usd": 74.28,+ "grid": "G1",+ "items": [+ {+ "arm": "noctx",+ "budget": null,+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "trunc",+ "budget": "128K",+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "pack",+ "budget": "128K",+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "agent",+ "budget": null,+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ }+ ],+ "model": "muse-spark-1.3",+ "provider": "meta"+ },+ {+ "cap_usd": 45.0,+ "description": "Meta, the cache-aware pack at 1M on the first 10 held-out questions of each repository",+ "estimate_cached_usd": 11.48,+ "estimate_uncached_usd": 38.64,+ "grid": "G2",+ "items": [+ {+ "arm": "pack-cache",+ "budget": "1M",+ "first": 10,+ "questions": 30,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ }+ ],+ "model": "muse-spark-1.3",+ "provider": "meta"+ },+ {+ "cap_usd": 100.0,+ "description": "Baseten, Muse Spark Open: the 1M answer arms on the held-out questions",+ "estimate_cached_usd": 87.39,+ "estimate_uncached_usd": 272.09,+ "grid": "G3",+ "items": [+ {+ "arm": "noctx",+ "budget": null,+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "trunc",+ "budget": "1M",+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "pack-cache",+ "budget": "1M",+ "first": null,+ "questions": 90,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ },+ {+ "arm": "pack",+ "budget": "1M",+ "first": 10,+ "questions": 30,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ }+ ],+ "model": "meta-models/muse-spark-open",+ "provider": "baseten"+ },+ {+ "cap_usd": 45.0,+ "description": "Meta, a Muse Wonder subset, only if money is left",+ "estimate_cached_usd": 6.14,+ "estimate_uncached_usd": 18.24,+ "grid": "G4",+ "items": [+ {+ "arm": "pack-cache",+ "budget": "128K",+ "first": 10,+ "questions": 30,+ "repos": [+ "pytorch",+ "vscode",+ "elasticsearch"+ ]+ }+ ],+ "model": "muse-wonder-1.0",+ "provider": "meta"+ }+ ],+ "repos": [+ {+ "S": "d5cbb79be9160faa3a7d7323e3294c3781c16ae7",+ "S_date": "2026-09-12T20:05:12Z",+ "estimate": {+ "tokens_all": 68353600,+ "tokens_nontest_source": 12186977,+ "tokens_without_vendored_generated": 39695631+ },+ "funnel": {+ "dropped_applies": 4,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 1,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 8,+ "dropped_prefilter": 26,+ "dropped_window": 0,+ "fetched": 89,+ "kept": 40,+ "names_gold_path": 23,+ "passed": 50,+ "sampled": true+ },+ "graphicle": "graphicle 0.1.8 (core)",+ "index_bytes": 6322956744,+ "index_peak_rss_mib": 7418.1,+ "index_seconds": 267.5,+ "name": "kubernetes",+ "role": "development",+ "slug": "kubernetes/kubernetes",+ "text_files": 30388,+ "tokens_all": 74354864,+ "tokens_nontest_source": 12015140,+ "tokens_without_vendored_generated": 41397282+ },+ {+ "S": "09e3474f91be03d4ac5a70a698474986fc759bcf",+ "S_date": "2026-09-13T20:00:07Z",+ "estimate": {+ "tokens_all": 47984327,+ "tokens_nontest_source": 15278132,+ "tokens_without_vendored_generated": 47753016+ },+ "funnel": {+ "dropped_applies": 114,+ "dropped_diff": 0,+ "dropped_duplicate": 4,+ "dropped_files": 1,+ "dropped_gold": 8,+ "dropped_issue": 0,+ "dropped_linked": 15,+ "dropped_prefilter": 129,+ "dropped_window": 0,+ "fetched": 604,+ "kept": 40,+ "names_gold_path": 10,+ "passed": 333,+ "sampled": true+ },+ "graphicle": "graphicle 0.1.8 (core)",+ "index_bytes": 4684810429,+ "index_peak_rss_mib": 5606.0,+ "index_seconds": 188.0,+ "name": "home-assistant",+ "role": "development",+ "slug": "home-assistant/core",+ "text_files": 27850,+ "tokens_all": 47157282,+ "tokens_nontest_source": 13476414,+ "tokens_without_vendored_generated": 46898763+ },+ {+ "S": "b8bd7cf750ea02a2390d8a5440261e2c6ed5ddc7",+ "S_date": "2026-09-13T22:40:38Z",+ "estimate": {+ "tokens_all": 48127454,+ "tokens_nontest_source": 27080172,+ "tokens_without_vendored_generated": 44783726+ },+ "funnel": {+ "dropped_applies": 17,+ "dropped_diff": 0,+ "dropped_duplicate": 0,+ "dropped_files": 0,+ "dropped_gold": 0,+ "dropped_issue": 1,+ "dropped_linked": 730,+ "dropped_prefilter": 24,+ "dropped_window": 0,+ "fetched": 860,+ "kept": 30,+ "names_gold_path": 9,+ "passed": 88,+ "sampled": true+ },+ "graphicle": "graphicle 0.1.8 (core)",+ "index_bytes": 4810039124,+ "index_peak_rss_mib": 6252.0,+ "index_seconds": 254.6,+ "name": "pytorch",+ "role": "held-out",+ "slug": "pytorch/pytorch",+ "text_files": 21685,+ "tokens_all": 49758766,+ "tokens_nontest_source": 28658617,+ "tokens_without_vendored_generated": 46308068+ },+ {+ "S": "3e8601c5f63f5b2358e0fbbfb825fbbfd72cbe2b",+ "S_date": "2026-09-13T21:23:17Z",+ "estimate": {+ "tokens_all": 59812977,+ "tokens_nontest_source": 29362605,+ "tokens_without_vendored_generated": 56733266+ },+ "funnel": {+ "dropped_applies": 234,+ "dropped_diff": 0,+ "dropped_duplicate": 2,+ "dropped_files": 3,+ "dropped_gold": 37,+ "dropped_issue": 2,+ "dropped_linked": 71,+ "dropped_prefilter": 180,+ "dropped_window": 0,+ "fetched": 715,+ "kept": 30,+ "names_gold_path": 5,+ "passed": 186,+ "sampled": true+ },+ "graphicle": "graphicle 0.1.8 (core)",+ "index_bytes": 5390816806,+ "index_peak_rss_mib": 7509.7,+ "index_seconds": 278.1,+ "name": "vscode",+ "role": "held-out",+ "slug": "microsoft/vscode",+ "text_files": 18541,+ "tokens_all": 63201298,+ "tokens_nontest_source": 30570400,+ "tokens_without_vendored_generated": 59092253+ },+ {+ "S": "d8a9ab59389dee57cc9e50f41f217ec49fda12f0",+ "S_date": "2026-09-13T20:09:26Z",+ "estimate": {+ "tokens_all": 103027588,+ "tokens_nontest_source": 36124961,+ "tokens_without_vendored_generated": 98942914+ },+ "funnel": {+ "dropped_applies": 231,+ "dropped_diff": 0,+ "dropped_duplicate": 3,+ "dropped_files": 1,+ "dropped_gold": 0,+ "dropped_issue": 0,+ "dropped_linked": 187,+ "dropped_prefilter": 71,+ "dropped_window": 0,+ "fetched": 579,+ "kept": 30,+ "names_gold_path": 2,+ "passed": 86,+ "sampled": true+ },+ "graphicle": "graphicle 0.1.8 (core)",+ "index_bytes": 15120342910,+ "index_peak_rss_mib": 15764.2,+ "index_seconds": 598.9,+ "name": "elasticsearch",+ "role": "held-out",+ "slug": "elastic/elasticsearch",+ "text_files": 47679,+ "tokens_all": 103579228,+ "tokens_nontest_source": 30714542,+ "tokens_without_vendored_generated": 99583601+ }+ ],+ "runs": {},+ "selection_seed": 20261026,+ "snapshot_cutoff": "2026-09-14T00:00:00Z",+ "test_data": false+}\ No newline at end of filediff --git a/docs/benchmarks/whole-repo.md b/docs/benchmarks/whole-repo.mdnew file mode 100644index 0000000..678ab03--- /dev/null+++ b/docs/benchmarks/whole-repo.md@@ -0,0 +1,180 @@+# Whole-repository change localization past 1M tokens++Can a model find the files a real fix changed, in a repository far larger than its context window? This benchmark asks it for five public repositories of 47 to 104 million tokens each, with 170 questions taken from real issues and the files their fixes changed. It compares Graphicle's `graphicle pack` with plain truncation of the repository, with the same model searching the repository through tools, and with no repository context at all. The method was fixed before any result was seen, and the results are published as they came out.++## Results++Not run yet. The questions, arms, prompts and scorer are fixed and committed; the model runs come next.++## Context recall without a model++For every question and budget, with no model involved: the share of the question's gold files that are inside the context, for the pack and for truncation filled to the same budget, with tokens counted with the Muse Spark Open tokenizer (Hugging Face revision 4239e4db). The pack holds small files whole and large ones as excerpts and as outlines of their symbols, and a gold file counts as inside when any of its text is in the pack; truncation holds whole files only. "Some inside" is the share of questions with at least one gold file inside. Each table is one run, named by the pack build it used.++### pack 2a46edb, built before the event: held-out repositories++| Repository | Role | Budget | Questions | Pack: gold files inside | Truncation: gold files inside | Pack: some inside | Truncation: some inside |+|---|---|---|---|---|---|---|---|+| pytorch | held-out | 64K | 30 | 60.3% | 0.0% | 66.7% | 0.0% |+| pytorch | held-out | 128K | 30 | 71.9% | 0.0% | 76.7% | 0.0% |+| pytorch | held-out | 256K | 30 | 65.3% | 0.0% | 70.0% | 0.0% |+| pytorch | held-out | 512K | 30 | 71.9% | 0.0% | 76.7% | 0.0% |+| pytorch | held-out | 1M | 30 | 80.0% | 0.0% | 83.3% | 0.0% |+| vscode | held-out | 64K | 30 | 63.3% | 3.3% | 63.3% | 3.3% |+| vscode | held-out | 128K | 30 | 64.2% | 3.3% | 66.7% | 3.3% |+| vscode | held-out | 256K | 30 | 64.2% | 3.3% | 66.7% | 3.3% |+| vscode | held-out | 512K | 30 | 70.8% | 3.3% | 73.3% | 3.3% |+| vscode | held-out | 1M | 30 | 74.2% | 6.7% | 76.7% | 6.7% |+| elasticsearch | held-out | 64K | 30 | 43.8% | 0.0% | 56.7% | 0.0% |+| elasticsearch | held-out | 128K | 30 | 54.7% | 0.0% | 66.7% | 0.0% |+| elasticsearch | held-out | 256K | 30 | 54.7% | 0.0% | 66.7% | 0.0% |+| elasticsearch | held-out | 512K | 30 | 61.2% | 0.0% | 70.0% | 0.0% |+| elasticsearch | held-out | 1M | 30 | 76.2% | 0.0% | 83.3% | 0.0% |+| **all held-out** | held-out | 64K | 90 | 55.8% | 1.1% | 62.2% | 1.1% |+| **all held-out** | held-out | 128K | 90 | 63.6% | 1.1% | 70.0% | 1.1% |+| **all held-out** | held-out | 256K | 90 | 61.4% | 1.1% | 67.8% | 1.1% |+| **all held-out** | held-out | 512K | 90 | 68.0% | 1.1% | 73.3% | 1.1% |+| **all held-out** | held-out | 1M | 90 | 76.8% | 2.2% | 81.1% | 2.2% |++### pack 2a46edb, built before the event: development repositories (used for tuning)++| Repository | Role | Budget | Questions | Pack: gold files inside | Truncation: gold files inside | Pack: some inside | Truncation: some inside |+|---|---|---|---|---|---|---|---|+| kubernetes | development | 64K | 40 | 85.0% | 0.0% | 90.0% | 0.0% |+| kubernetes | development | 128K | 40 | 88.4% | 0.0% | 92.5% | 0.0% |+| kubernetes | development | 256K | 40 | 89.2% | 0.0% | 95.0% | 0.0% |+| kubernetes | development | 512K | 40 | 91.8% | 0.0% | 97.5% | 0.0% |+| kubernetes | development | 1M | 40 | 92.4% | 1.5% | 97.5% | 2.5% |+| home-assistant | development | 64K | 40 | 94.2% | 0.0% | 95.0% | 0.0% |+| home-assistant | development | 128K | 40 | 94.2% | 3.3% | 95.0% | 5.0% |+| home-assistant | development | 256K | 40 | 94.2% | 5.8% | 95.0% | 7.5% |+| home-assistant | development | 512K | 40 | 100.0% | 8.3% | 100.0% | 10.0% |+| home-assistant | development | 1M | 40 | 100.0% | 12.5% | 100.0% | 12.5% |+| **all development** | development | 64K | 80 | 89.6% | 0.0% | 92.5% | 0.0% |+| **all development** | development | 128K | 80 | 91.3% | 1.7% | 93.8% | 2.5% |+| **all development** | development | 256K | 80 | 91.7% | 2.9% | 95.0% | 3.8% |+| **all development** | development | 512K | 80 | 95.9% | 4.2% | 98.8% | 5.0% |+| **all development** | development | 1M | 80 | 96.2% | 7.0% | 98.8% | 7.5% |++## Cost per question with the prompt cache++**All numbers in this section are computed at list prices, not billed.** Runs with the model will replace them with billed costs.++Meta's API serves the longest prefix a prompt shares with an earlier prompt from its cache, and bills it at the cached-input price (Muse Spark 1.3 $1.25 per million input tokens, $0.15 cached; Muse Wonder $4.00 per million input tokens, $0.20 cached; prices of 2026-10-26). A context whose first part is the same for every question about a repository pays the full input price once; every follow-up question pays the cached price on that part and the full price only on the rest. Truncation's dump is the same for every question, so it is cached the same way. These are input costs; output is billed on top ($4.25 per million on Muse Spark 1.3), ($20.00 per million on Muse Wonder).++The shared prefix and the question-specific tokens are the means over the questions of the development repositories (kubernetes, home-assistant) for each context and budget (pack 06818eb), counted with the Muse Spark Open tokenizer. A first question pays for both, plus the question and the prompt template after the context.++<p align="center">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="../assets/whole-repo-cost-dark.svg">+ <img src="../assets/whole-repo-cost-light.svg" alt="Input cost per follow-up question at a 1M-token budget, without and with the prompt cache, computed at list prices, not billed. Graphicle pack, standard layout: Muse Spark 1.3 $1.27 without the cache, $1.27 with it, Muse Wonder $4.06 without the cache, $4.06 with it; Graphicle pack, cache layout, 50% prefix: Muse Spark 1.3 $1.17 without the cache, $0.610 with it, Muse Wonder $3.74 without the cache, $1.81 with it; Graphicle pack, cache layout, 70% prefix: Muse Spark 1.3 $1.21 without the cache, $0.433 with it, Muse Wonder $3.88 without the cache, $1.19 with it; Graphicle pack, cache layout, 90% prefix: Muse Spark 1.3 $1.26 without the cache, $0.252 with it, Muse Wonder $4.02 without the cache, $0.551 with it; Graphicle pack, cache layout, 95% prefix: Muse Spark 1.3 $1.26 without the cache, $0.204 with it, Muse Wonder $4.04 without the cache, $0.383 with it; Graphicle pack, stable layout: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.06 without the cache, $0.206 with it; Truncation: Muse Spark 1.3 $1.27 without the cache, $0.153 with it, Muse Wonder $4.07 without the cache, $0.206 with it.">+ </picture>+</p>++| Budget | Context | Shared prefix (tokens) | Question-specific (tokens) | Gold files inside (development) | Muse Spark 1.3: first question | Muse Spark 1.3: each follow-up | Muse Spark 1.3: mean over 20 | Muse Wonder: first question | Muse Wonder: each follow-up | Muse Wonder: mean over 20 |+|---|---|---|---|---|---|---|---|---|---|---|+| 128K | Graphicle pack, standard layout | 0 | 131,250 | 91.3% | $0.164 | $0.164 | $0.164 | $0.525 | $0.525 | $0.525 |+| 128K | Graphicle pack, cache layout, 50% prefix | 65,376 | 61,283 | 89.6% | $0.158 | $0.086 | $0.090 | $0.507 | $0.258 | $0.271 |+| 128K | Graphicle pack, cache layout, 70% prefix | 91,562 | 37,852 | 86.8% | $0.162 | $0.061 | $0.066 | $0.518 | $0.170 | $0.187 |+| 128K | Graphicle pack, cache layout, 90% prefix | 117,686 | 13,284 | 80.5% | $0.164 | $0.034 | $0.041 | $0.524 | $0.077 | $0.099 |+| 128K | Graphicle pack, cache layout, 95% prefix | 124,242 | 7,019 | 65.7% | $0.164 | $0.027 | $0.034 | $0.525 | $0.053 | $0.077 |+| 128K | Graphicle pack, stable layout | 130,792 | 781 | 6.7% | $0.164 | $0.021 | $0.028 | $0.526 | $0.029 | $0.054 |+| 128K | Truncation | 131,066 | 781 | 1.7% | $0.165 | $0.021 | $0.028 | $0.527 | $0.029 | $0.054 |+| 1M | Graphicle pack, standard layout | 0 | 1,013,783 | 96.2% | $1.27 | $1.27 | $1.27 | $4.06 | $4.06 | $4.06 |+| 1M | Graphicle pack, cache layout, 50% prefix | 506,857 | 427,440 | 95.9% | $1.17 | $0.610 | $0.638 | $3.74 | $1.81 | $1.91 |+| 1M | Graphicle pack, cache layout, 70% prefix | 709,619 | 261,605 | 92.9% | $1.21 | $0.433 | $0.472 | $3.88 | $1.19 | $1.32 |+| 1M | Graphicle pack, cache layout, 90% prefix | 912,369 | 92,025 | 94.4% | $1.26 | $0.252 | $0.302 | $4.02 | $0.551 | $0.724 |+| 1M | Graphicle pack, cache layout, 95% prefix | 963,066 | 47,682 | 92.1% | $1.26 | $0.204 | $0.257 | $4.04 | $0.383 | $0.566 |+| 1M | Graphicle pack, stable layout | 1,013,762 | 781 | 18.2% | $1.27 | $0.153 | $0.209 | $4.06 | $0.206 | $0.398 |+| 1M | Truncation | 1,015,800 | 781 | 7.0% | $1.27 | $0.153 | $0.209 | $4.07 | $0.206 | $0.399 |++Every question about one repository at one budget got the same prefix bytes in the cache and stable layouts (one sha256 per repository, budget and layout). Gold files inside: the share of each question's gold files with any of their text in the context (in a pack, whole or as excerpts or outlines), the same measure as in the context recall section.++The 256K and 512K rows are in the data file [whole-repo.json](whole-repo.json). Whether a follow-up is served from the cache is up to the API: the 24-hour retention is a hint, and a prompt that leaves the cache pays the first-question price again.++## Repositories++Each repository is pinned at S, the last commit on its default branch's first-parent line at or before 2026-09-14 00:00 UTC. Meta's model documentation states no knowledge cutoff for Muse Spark, so the date was not moved. Sizes count the tracked text files at S, in tokens counted with the Muse Spark Open tokenizer (Hugging Face revision 4239e4db); in brackets, the estimate of UTF-8 bytes / 4; vendored and generated files are listed in `bench/whole-repo/paths.py`.++| Repository | Role | S | S date (UTC) | Tokens, all | Without vendored and generated | Non-test source | Text files | Index time | Index size |+|---|---|---|---|---|---|---|---|---|---|+| kubernetes/kubernetes | development | `d5cbb79be916` | 2026-09-12 20:05 | 74.4M (68.4M) | 41.4M (39.7M) | 12.0M (12.2M) | 30,388 | 268 s | 5.9 GiB |+| home-assistant/core | development | `09e3474f91be` | 2026-09-13 20:00 | 47.2M (48.0M) | 46.9M (47.8M) | 13.5M (15.3M) | 27,850 | 188 s | 4.4 GiB |+| pytorch/pytorch | held-out | `b8bd7cf750ea` | 2026-09-13 22:40 | 49.8M (48.1M) | 46.3M (44.8M) | 28.7M (27.1M) | 21,685 | 255 s | 4.5 GiB |+| microsoft/vscode | held-out | `3e8601c5f63f` | 2026-09-13 21:23 | 63.2M (59.8M) | 59.1M (56.7M) | 30.6M (29.4M) | 18,541 | 278 s | 5.0 GiB |+| elastic/elasticsearch | held-out | `d8a9ab59389d` | 2026-09-13 20:09 | 103.6M (103.0M) | 99.6M (98.9M) | 30.7M (36.1M) | 47,679 | 599 s | 14.1 GiB |++Index time is the wall time of `graphicle sync` (graphicle 0.1.8 (core)) on 48 cores of a shared machine at low priority, two repositories at a time; index size is its data folder.++## Questions++Each question is a real issue, fixed by a pull request merged into the default branch after S and by 2026-10-25. The question is the issue's title and body as first filed (from GitHub's edit history), with HTML comments and empty template headings removed. The gold answer is the source files the pull request changed that exist at S: no tests, docs, changelogs, generated or vendored files. Only pull requests with 1 to 5 gold files are kept, and only when their change to the gold files applies cleanly to S, so the bug is present in the snapshot. When more questions pass than the target, the target number is drawn with the fixed seed 20261026. The question sets publish the issue and pull request links, the gold files and the sha256 of each question text; `fetch_texts.py` rebuilds the texts and checks them.++| Repository | Pull requests found | No readable linked issue | Over 100 files | Not 1 to 5 source files | Diff not readable | Not 1 to 5 gold files | Does not apply at S | Issue not usable | Issue already used | Passed | Kept | Text names a gold path |+|---|---|---|---|---|---|---|---|---|---|---|---|---|+| kubernetes/kubernetes | 89 | 8 | 1 | 26 | 0 | 0 | 4 | 0 | 0 | 50 | 40 | 23 |+| home-assistant/core | 604 | 15 | 1 | 129 | 0 | 8 | 114 | 0 | 4 | 333 | 40 | 10 |+| pytorch/pytorch | 860 | 730 | 0 | 24 | 0 | 0 | 17 | 1 | 0 | 88 | 30 | 9 |+| microsoft/vscode | 715 | 71 | 3 | 180 | 0 | 37 | 234 | 2 | 2 | 186 | 30 | 5 |+| elastic/elasticsearch | 579 | 187 | 1 | 71 | 0 | 0 | 231 | 0 | 3 | 86 | 30 | 2 |++The search found the merged pull requests GitHub links to an issue. For PyTorch, whose merge bot closes pull requests instead of merging them, every landed pull request was read and its closing keywords parsed, so most PyTorch pull requests drop out at the linked-issue step. Questions whose text names a gold file path (a path of at least two parts, such as a stack trace line) are flagged; the results are shown with and without them.++## Arms++Every arm sends one prompt: the context, then the question, in this template:++```text+<context>++Repository <org>/<name> at commit <S>. Issue: <issue text>++List the source files that must change to resolve this issue, most likely first, at most 10. Answer with JSON only, in the form {"files": ["path/to/file", ...]}, with paths relative to the repository root.+```++- **Graphicle pack at B tokens:** `graphicle pack "<issue>" --project <repository> --budget B --format xml`.+- **Graphicle pack, cache layout:** the same with `--layout cache --prefix-share 0.9`: the first 90% of the budget is a prefix that does not depend on the question, byte for byte the same for every question about the repository at S, and the rest is chosen for the question. A model API's prompt cache can then serve the prefix of every question after the first at its cached-input price. With `--prefix-share 1.0` (the stable layout) the whole pack is the same for every question.+- **Truncation at B tokens:** the repository's files in a fixed order up to B: source files, then tests, then docs, each group by path, vendored and generated files left out, each file wrapped with its path like the pack's chunks; a file that would pass the budget is skipped.+- **Search-only agent:** the same model with four tools over the checkout at S: `grep` (at most 100 lines), `find` (at most 200 paths), `list_dir` and `read` (at most 400 lines per call), for at most 30 turns, then the same answer. Every token of every turn is counted.+- **No context:** the question alone, the control for memorisation.++Budgets B: 64K = 65,536, 128K = 131,072, 256K = 262,144, 512K = 524,288, 1M = 1,015,808 tokens (1M leaves 32,768 tokens of the 1,048,576-token window for the question and the answer). Pack and truncation are measured in the same tokenizer (counted with the Muse Spark Open tokenizer (Hugging Face revision 4239e4db)).++## Metrics++- **hit@k:** a gold file is among the first k files of the answer (k = 1, 3, 5). **All gold in top 5:** every gold file is among the first 5. **MRR:** the mean of 1/rank of the first gold file (0 when none of the 10 is).+- **Context recall:** the share of gold files whose text is inside the context; for the agent, the share it read.+- **Tokens and cost:** from the API's usage fields; cost from the price table in `prices.json` (2026-10-26, https://dev.meta.ai/docs/pricing-rate-limits).+- **Tests:** McNemar's exact test on hit@5 between arms on the same questions; 95% bootstrap intervals (questions resampled) on the means.++## Model runs, fixed before they ran++These runs, their order, their settings, the tests and the spending limits were fixed on 26 Oct 2026, before any model call. A grid runs only when the one before it has finished and only if it fits the money left; this page says which ones ran.++| Grid | Model | API | Arms, in run order | Questions | Estimated cost with caching (without) |+|---|---|---|---|---|---|+| G1 | Muse Spark 1.3 (`muse-spark-1.3`) | Meta Model API, Responses API | no context, truncation at 128K, pack at 128K, search-only agent | 90 held-out | $34.48 ($74.28) of $45 |+| G2 | Muse Spark 1.3 (`muse-spark-1.3`) | Meta Model API, Responses API | cache-layout pack at 1M (the first 10 questions of each repository) | 30 held-out | $11.48 ($38.64) of $45 |+| G3 | Muse Spark Open (`meta-models/muse-spark-open`) | Baseten Model APIs, chat completions | no context, truncation at 1M, cache-layout pack at 1M, pack at 1M (the first 10 questions of each repository) | 90 held-out | $87.39 ($272.09) of $100 |+| G4 | Muse Wonder (`muse-wonder-1.0`) | Meta Model API, Responses API | cache-layout pack at 128K (the first 10 questions of each repository) | 30 held-out | $6.14 ($18.24) of $45 |++The estimates fill every budget, count 4,000 output tokens per call and assume the search-only agent takes 15 turns that add 2,500 tokens each (`estimate.py --registered`). The 1M arms on Muse Spark 1.3 (G2) and the Muse Wonder subset (G4) run only if the Meta limit still allows them after G1.++- **Caching:** Meta's API caches the longest identical prefix of a prompt and bills it at the cached-input price. Every call sends `prompt_cache_key`, one key per repository, snapshot, arm, budget and prefix hash, and `prompt_cache_retention: "24h"`; on Baseten the same key goes in the `x-session-affinity` header. Truncation, whose dump is the same for every question, gets the same treatment as the pack, so the cost comparison does not favour the pack.+- **Order:** the questions of one repository, arm and budget run back to back in the question file's order, the first one alone, so the later ones can be served from the cache. The search-only agent takes the three repositories in turn, one question each, so a run stopped by its spending limit still covers them evenly.+- **Settings:** reasoning effort medium; at most 8,192 output tokens per call (per turn for the agent); one answer per question; the API's default sampling.+- **Primary comparisons:** hit@5, pooled over the three held-out repositories, by McNemar's exact test: the pack against truncation at 128K and the pack against the search-only agent at 128K (Muse Spark 1.3), and the cache-layout pack against truncation at 1M (Muse Spark Open). Every other comparison is secondary. A question whose call still fails after retries is left out of the means and counted; the hit rates with such questions counted as misses are shown too.+- **Cost:** per question as billed, from the input, cached and output tokens the API reports, and at list prices without any cache.+- **Spending limits:** the runner logs every call (tokens, cached tokens, seconds, cost) and refuses to start a run when the logged total plus the run's own estimate would pass $45 on Meta's API or $100 on Baseten; within a run, no call is sent whose worst case (the whole prompt uncached plus the output limit) would pass the run's own limit or the total one.+- **Held-out repositories:** tuning happens only on kubernetes and home-assistant. Every run on pytorch, vscode or elasticsearch, with or without a model, is logged with its time and pack version before its result is read, and no held-out result changes the pack. The context recall runs once per release candidate; each hosted grid runs once, with one pack version, and a run stopped by an error or a spending limit is resumed, never repeated. The first held-out run is the context recall of the pack as it was built before 26 Oct 2026.++## Limitations++- Five repositories and 170 questions: differences of a few points are within the noise; the intervals say how much.+- File-level localization only, scored by exact path; a fix can be correct in other files than the ones the pull request changed.+- The gold files come from what the fix changed, which is not always where the bug was reported.+- Issues filed before S can be in a model's training data; the no-context arm measures how much that helps.+- Pull requests whose changes do not apply at S were dropped, which favours fixes to code that did not move in the weeks after S.++## Reproduce++The scripts and question sets are in [`bench/whole-repo/`](../../bench/whole-repo/). In order: `checkout.py` (the snapshots), `fetch_texts.py` (the question texts, checked against their hashes), `index.py`, `tokens.py sizes`, `run.py` once per arm (with `--spend-cap`), `score.py`, `recall.py` (with `--layouts` for the cost section) and `report.py`; the charts come from `whole_repo_chart.py` and `whole_repo_cost_chart.py` in this folder. `estimate.py` prints a grid's tokens and cost before it runs.diff --git a/docs/benchmarks/whole_repo_chart.py b/docs/benchmarks/whole_repo_chart.pynew file mode 100644index 0000000..ea0ec68--- /dev/null+++ b/docs/benchmarks/whole_repo_chart.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+"""The whole-repository benchmark's chart, from its data file.++ python3 whole_repo_chart.py --data docs/benchmarks/whole-repo.json --out docs/assets --fonts FONT_DIR++writes whole-repo-light.svg, whole-repo-dark.svg and their PNGs (twice the SVG's size) to --out. The+data file is written by bench/whole-repo/report.py. The chart shows, for each arm run on the held-out+repositories (pooled, each repository's questions weighted equally per question): hit@5 (a file the fix+changed among the first five files of the answer), the cost per question and the input tokens per+question. A data file built from test data (the mock server or the stand-in) gets a TEST DATA title.++Colours: one per arm family (pack, search-only agent, truncation, no context), from a palette checked+for colour-blind separation and contrast in both themes; every bar is also labelled with its arm and+value, so no colour has to be told apart.++Needs matplotlib 3.11 and the Inter 4.1 and JetBrains Mono 2.304 TTF files in FONT_DIR (rsms/inter and+JetBrains/JetBrainsMono releases); without them it uses DejaVu Sans and says so. The SVGs carry their+text as outlines, so they show the same everywhere.+"""+import argparse+import html+import json+import os+import re+import sys++THEMES = {+ "light": {"surface": "#FFFFFF", "ink": "#0A0B0F", "ink2": "#2E3440", "muted": "#5B6474", "hair": "#E3E6EC",+ "family": {"pack": "#3F5EFB", "agent": "#eb6834", "trunc": "#1baf7a", "noctx": "#eda100"}},+ "dark": {"surface": "#0D1117", "ink": "#F4F6FA", "ink2": "#C9CED8", "muted": "#8A93A6", "hair": "#2A2F3B",+ "family": {"pack": "#5B7CFF", "agent": "#d95926", "trunc": "#199e70", "noctx": "#c98500"}},+}+FAMILY_ORDER = ["pack", "agent", "trunc", "noctx"]+FAMILY_NAMES = {"pack": "Graphicle pack", "agent": "Search-only agent", "trunc": "Truncation", "noctx": "No context"}+FONT_FILES = {"regular": "Inter-Regular.ttf", "medium": "Inter-Medium.ttf", "semibold": "Inter-SemiBold.ttf",+ "bold": "Inter-Bold.ttf", "display": "InterDisplay-SemiBold.ttf", "mono": "JetBrainsMono-Regular.ttf"}+FALLBACK = {"regular": "normal", "medium": "medium", "semibold": "semibold", "bold": "bold", "display": "semibold",+ "mono": "normal"}+FORBIDDEN = [(re.compile("[—–]"), "dash"), (re.compile(r"/tmp|/Users|/private", re.I), "local path")]+DPI = 72+CAP = 0.727+W, H, M, GAP = 1600, 900, 48, 40+URL = "github.com/graphicle-ai/graphicle/blob/main/docs/benchmarks/whole-repo.md"+++def arm_rows(data, role="held-out"):+ rows = data.get("by_role", {}).get(role, {})+ out = []+ for label, r in rows.items():+ fam = r["arm"]+ name = FAMILY_NAMES[fam] + (f", {r['budget']}" if r.get("budget") else "")+ out.append({"label": label, "family": fam, "name": name, "budget": r.get("budget") or "", **r})+ budget_key = lambda b: {"64K": 1, "128K": 2, "256K": 3, "512K": 4, "1M": 5}.get(b, 0)+ out.sort(key=lambda r: (FAMILY_ORDER.index(r["family"]), budget_key(r["budget"])))+ return out+++def alt_text(data, rows):+ model = rows[0]["model"] if rows else "the model"+ short = f"Whole-repository change localization, held-out repositories: hit@5, cost and input tokens per question by arm ({model})."+ parts = [f"{r['name']}: hit@5 {100 * r['hit5']:.1f}%, ${r['cost_usd']:.3f} and {r['tokens_in']:,.0f} input tokens per question"+ for r in rows if r.get("hit5") is not None]+ return short, ("TEST DATA. " if data.get("test_data") else "") + "; ".join(parts) + "."+++def draw(data, theme, fonts_dir, base):+ import matplotlib+ matplotlib.use("Agg")+ matplotlib.rcParams["text.hinting"] = "no_hinting"+ matplotlib.rcParams["svg.hashsalt"] = "graphicle-whole-repo"+ matplotlib.rcParams["svg.fonttype"] = "path"+ import matplotlib.pyplot as plt+ from matplotlib.font_manager import FontProperties+ from matplotlib.patches import FancyBboxPatch, PathPatch, Rectangle+ from matplotlib.path import Path++ C = THEMES[theme]+ rows = [r for r in arm_rows(data) if r.get("hit5") is not None]+ if not rows:+ raise SystemExit("no held-out results in the data file")+ missing = [f for f in FONT_FILES.values() if not os.path.exists(os.path.join(fonts_dir or "", f))]+ cache = {}++ def fp(kind, size):+ if (kind, size) not in cache:+ path = os.path.join(fonts_dir or "", FONT_FILES[kind])+ cache[(kind, size)] = (FontProperties(fname=path, size=size) if os.path.exists(path) else+ FontProperties(family="DejaVu Sans Mono" if kind == "mono" else "DejaVu Sans",+ weight=FALLBACK[kind], size=size))+ return cache[(kind, size)]++ fig = plt.figure(figsize=(W / DPI, H / DPI), dpi=DPI)+ fig.patch.set_facecolor(C["surface"])+ ax = fig.add_axes([0, 0, 1, 1])+ ax.set_xlim(0, W)+ ax.set_ylim(H, 0)+ ax.axis("off")+ rend = fig.canvas.get_renderer()+ texts = []++ def width(s, kind, size):+ return rend.get_text_width_height_descent(s, fp(kind, size), ismath=False)[0]++ def text(x, y, s, kind, size, color, ha="left"):+ texts.append((ax.text(x, y, s, fontproperties=fp(kind, size), color=color, ha=ha, va="baseline", zorder=6), s))++ def box(x, y, w, h, color, r=0, z=1):+ p = (FancyBboxPatch((x, y), w, h, boxstyle=f"round,pad=0,rounding_size={r}", fc=color, ec="none", zorder=z)+ if r else Rectangle((x, y), w, h, fc=color, ec="none", zorder=z))+ ax.add_patch(p)++ def hbar(x_base, y, length, h, color, r=4):+ """A bar from the baseline to the right, with a rounded data end and a square baseline end."""+ r = max(0.0, min(r, h / 2, length))+ xe = x_base + length+ verts = [(x_base, y), (xe - r, y), (xe, y), (xe, y + r), (xe, y + h - r), (xe, y + h), (xe - r, y + h),+ (x_base, y + h), (x_base, y)]+ codes = [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3,+ Path.LINETO, Path.CLOSEPOLY]+ ax.add_patch(PathPatch(Path(verts, codes), fc=color, ec="none", zorder=3))++ def wrap(s, kind, size, max_w):+ lines, cur = [], ""+ for word in s.split():+ trial = f"{cur} {word}".strip()+ if cur and width(trial, kind, size) > max_w:+ lines.append(cur)+ cur = word+ else:+ cur = trial+ return lines + ([cur] if cur else [])++ held = [r for r in data["repos"] if r["role"] == "held-out"]+ model = rows[0]["model"]+ n = max(r["n"] for r in rows)+ yb = 60+ text(M, yb, "Graphicle", "bold", 28, C["ink"])+ text(M + width("Graphicle", "bold", 28) + 16, yb, "whole-repository benchmark", "regular", 20, C["muted"])+ yb += 52+ title = ("TEST DATA: " if data.get("test_data") else "") + "Finding the files a fix changed, past 1M tokens"+ text(M, yb, title, "display", 34, C["ink"])+ yb += 34+ sub = (f"{model} on {len(held)} held-out repositories ({', '.join(r['slug'] for r in held)}), "+ f"up to {n} questions per arm. Each repository is far larger than the model's window.")+ for line in wrap(sub, "regular", 20, W - 2 * M):+ text(M, yb, line, "regular", 20, C["muted"])+ yb += 26+ top = yb + 16++ foot = [f"hit@5: a file the fix changed is among the first five files of the answer. Cost from the API's usage "+ f"fields at the listed prices of {data['prices']['date']}. Intervals and per-repository rows on the page."]+ flines = []+ for para in foot:+ flines += wrap(para, "regular", 18, W - 2 * M)+ footer_top = H - 22 - 25 * (len(flines) + 1)+ y = footer_top+ for line in flines:+ text(M, y + 18, line, "regular", 18, C["muted"])+ y += 25+ label = "Method and data: "+ text(M, y + 18, label, "regular", 18, C["muted"])+ text(M + width(label, "regular", 18), y + 18, URL, "mono", 17, C["muted"])+ box(M, footer_top - 14, W - 2 * M, 1, C["hair"], z=1)+ bottom = footer_top - 34++ gutter = max(width(r["name"], "medium", 20) for r in rows) + 24+ panels = [("hit5", "hit@5", "Share of questions", lambda v: f"{100 * v:.1f}%", 1.0),+ ("cost_usd", "Cost", "Dollars per question", lambda v: f"${v:.3f}", None),+ ("tokens_in", "Input tokens", "Per question", lambda v: f"{v / 1000:,.0f}K", None)]+ PW = (W - 2 * M - gutter - GAP * 2) / 3+ head_h = 30 + 26 + 18+ row_h = min(64, (bottom - top - head_h) / len(rows))+ bh = min(28, row_h * 0.55)+ y0 = top + head_h+ for i, r in enumerate(rows):+ cy = y0 + row_h * (i + 0.5)+ text(M, cy + CAP * 20 / 2, r["name"], "medium", 20, C["ink2"])+ for j, (key, ptitle, psub, fmt, vmax) in enumerate(panels):+ x0 = M + gutter + j * (PW + GAP)+ text(x0, top + 26, ptitle, "semibold", 26, C["ink"])+ text(x0, top + 26 + 26, psub, "regular", 18, C["muted"])+ vals = [r.get(key) or 0 for r in rows]+ vm = vmax or (max(vals) * 1.0 if max(vals) > 0 else 1.0)+ label_w = max(width(fmt(v), "semibold", 20) for v in vals) + 12+ span = PW - label_w+ box(x0 - 0.75, y0, 1.5, row_h * len(rows), C["hair"], z=3.5)+ for i, (r, v) in enumerate(zip(rows, vals)):+ cy = y0 + row_h * (i + 0.5)+ length = span * (v / vm) if vm else 0+ hbar(x0, cy - bh / 2, max(length, 1.5), bh, C["family"][r["family"]])+ text(x0 + length + 10, cy + CAP * 20 / 2, fmt(v), "semibold", 20, C["ink"], ha="left")++ problems = [f"fonts missing, DejaVu Sans used: {', '.join(missing)}"] if missing else []+ fig.canvas.draw()+ boxes = []+ for a, s in texts:+ bb = a.get_window_extent(renderer=rend)+ x0, x1, y0_, y1 = bb.x0, bb.x1, H - bb.y1, H - bb.y0+ if x0 < 8 or y0_ < 8 or x1 > W - 8 or y1 > H - 8:+ problems.append(f"outside the canvas: {s!r}")+ for rx, why in FORBIDDEN:+ if rx.search(s):+ problems.append(f"{why}: {s!r}")+ boxes.append((x0, y0_, x1, y1, s))+ for i in range(len(boxes)):+ for k in range(i + 1, len(boxes)):+ a, b = boxes[i], boxes[k]+ if a[0] < b[2] - 1 and b[0] < a[2] - 1 and a[1] < b[3] - 1 and b[1] < a[3] - 1:+ problems.append(f"overlap: {a[4]!r} / {b[4]!r}")+ alt_short, alt_long = alt_text(data, rows)+ fig.savefig(base + ".png", dpi=DPI * 2, facecolor=C["surface"], metadata={"Title": alt_short, "Description": alt_long})+ fig.savefig(base + ".svg", dpi=DPI, facecolor=C["surface"], metadata={"Date": None})+ plt.close(fig)+ svg = open(base + ".svg", encoding="utf-8").read()+ svg = re.sub(r'width="[\d.]+pt" height="[\d.]+pt"', f'width="{W}" height="{H}"', svg, count=1)+ i = svg.find(">", svg.find("<svg")) + 1+ svg = svg[:i] + "\n <title>" + html.escape(alt_short) + "</title>\n <desc>" + html.escape(alt_long) + "</desc>" + svg[i:]+ with open(base + ".svg", "w", encoding="utf-8") as f:+ f.write(svg)+ return problems, alt_short, alt_long+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--data", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--fonts")+ a = ap.parse_args()+ data = json.load(open(a.data))+ os.makedirs(a.out, exist_ok=True)+ bad = False+ for theme in ("light", "dark"):+ base = os.path.join(a.out, f"whole-repo-{theme}")+ problems, alt_short, _ = draw(data, theme, a.fonts, base)+ for p in problems:+ print(f"{theme}: {p}", file=sys.stderr)+ bad = bad or not p.startswith("fonts missing")+ print(f"{base}.svg and .png")+ print(f"alt: {alt_short}")+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ main()diff --git a/docs/benchmarks/whole_repo_cost_chart.py b/docs/benchmarks/whole_repo_cost_chart.pynew file mode 100644index 0000000..5cc55a6--- /dev/null+++ b/docs/benchmarks/whole_repo_cost_chart.py@@ -0,0 +1,257 @@+#!/usr/bin/env python3+"""The whole-repository benchmark's cost chart, from its data file.++ python3 whole_repo_cost_chart.py --data docs/benchmarks/whole-repo.json --out docs/assets --fonts FONT_DIR++writes whole-repo-cost-light.svg, whole-repo-cost-dark.svg and their PNGs (twice the SVG's size) to --out.+The data file is written by bench/whole-repo/report.py; its "cost" section holds the input cost of a+question with each context at each budget, without and with the prompt cache, computed at list prices+from token counts (not billed). The chart shows the 1M-token budget: for each context, what a follow-up+question costs without the cache (every input token at the input price) and with it (the shared prefix+at the cached-input price), one panel per model on one shared dollar scale.++Colours: the two series (without the cache, with the cache) take the first two slots of a categorical+palette checked for colour-blind separation and contrast in both themes; every bar is also labelled+with its value and the legend names both, so no colour has to be told apart. Style, fonts and canvas+match whole_repo_chart.py, whose constants this script imports.+"""+import argparse+import html+import json+import os+import re+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from whole_repo_chart import CAP, DPI, FALLBACK, FONT_FILES, FORBIDDEN, GAP, H, M, THEMES, URL, W # noqa: E402++SERIES = {"light": {"uncached": "#2a78d6", "cached": "#eb6834"},+ "dark": {"uncached": "#3987e5", "cached": "#d95926"}}+SERIES_NAMES = {"uncached": "Without the cache", "cached": "With the cache"}+MODEL_NAMES = {"muse-spark-1.3": "Muse Spark 1.3", "muse-wonder-1.0": "Muse Wonder"}+SHORT = {"pack": "Pack, standard layout", "pack-cache0.5": "Pack, cache layout, 50%",+ "pack-cache0.7": "Pack, cache layout, 70%", "pack-cache": "Pack, cache layout, 90%",+ "pack-cache0.95": "Pack, cache layout, 95%", "pack-stable": "Pack, stable layout", "truncation": "Truncation"}+BUDGET = "1M"+++def usd(v):+ return f"${v:.3f}" if v < 1 else f"${v:.2f}"+++def chart_rows(cost):+ """The rows of the 1M budget (of the largest budget in the data when it has no 1M rows)."""+ order = ["64K", "128K", "256K", "512K", "1M"]+ have = [r["budget"] for r in cost["rows"]]+ budget = BUDGET if BUDGET in have else max(have, key=order.index, default=BUDGET)+ return [r for r in cost["rows"] if r["budget"] == budget]+++def alt_text(data, rows):+ c = data["cost"]+ budget = rows[0]["budget"] if rows else BUDGET+ short = (f"Input cost per follow-up question with a {budget}-token context, without and with the prompt cache, "+ f"{c['label']}.")+ parts = []+ for r in rows:+ parts.append(SHORT.get(r["arm"], r["context"]) + ": " + ", ".join(+ f"{MODEL_NAMES.get(m, m)} {usd(x['first_usd'])} without the cache, {usd(x['follow_up_usd'])} with it"+ for m, x in r["models"].items()))+ return short, ("TEST DATA. " if data.get("test_data") else "") + "; ".join(parts) + "."+++def draw(data, theme, fonts_dir, base):+ import matplotlib+ matplotlib.use("Agg")+ matplotlib.rcParams["text.hinting"] = "no_hinting"+ matplotlib.rcParams["svg.hashsalt"] = "graphicle-whole-repo-cost"+ matplotlib.rcParams["svg.fonttype"] = "path"+ import matplotlib.pyplot as plt+ from matplotlib.font_manager import FontProperties+ from matplotlib.patches import PathPatch, Rectangle+ from matplotlib.path import Path++ C = THEMES[theme]+ S = SERIES[theme]+ cost = data.get("cost")+ if not cost:+ raise SystemExit("no cost section in the data file")+ rows = chart_rows(cost)+ models = list(cost["models"])+ if not rows:+ raise SystemExit("no rows in the cost section")+ missing = [f for f in FONT_FILES.values() if not os.path.exists(os.path.join(fonts_dir or "", f))]+ cache = {}++ def fp(kind, size):+ if (kind, size) not in cache:+ path = os.path.join(fonts_dir or "", FONT_FILES[kind])+ cache[(kind, size)] = (FontProperties(fname=path, size=size) if os.path.exists(path) else+ FontProperties(family="DejaVu Sans Mono" if kind == "mono" else "DejaVu Sans",+ weight=FALLBACK[kind], size=size))+ return cache[(kind, size)]++ fig = plt.figure(figsize=(W / DPI, H / DPI), dpi=DPI)+ fig.patch.set_facecolor(C["surface"])+ ax = fig.add_axes([0, 0, 1, 1])+ ax.set_xlim(0, W)+ ax.set_ylim(H, 0)+ ax.axis("off")+ rend = fig.canvas.get_renderer()+ texts = []++ def width(s, kind, size):+ return rend.get_text_width_height_descent(s, fp(kind, size), ismath=False)[0]++ def text(x, y, s, kind, size, color, ha="left"):+ # parse_math off: two dollar signs in one label must not turn into math text.+ texts.append((ax.text(x, y, s, fontproperties=fp(kind, size), color=color, ha=ha, va="baseline", zorder=6,+ parse_math=False), s))++ def box(x, y, w, h, color, z=1):+ ax.add_patch(Rectangle((x, y), w, h, fc=color, ec="none", zorder=z))++ def hbar(x_base, y, length, h, color, r=4):+ """A bar from the baseline to the right, with a rounded data end and a square baseline end."""+ r = max(0.0, min(r, h / 2, length))+ xe = x_base + length+ verts = [(x_base, y), (xe - r, y), (xe, y), (xe, y + r), (xe, y + h - r), (xe, y + h), (xe - r, y + h),+ (x_base, y + h), (x_base, y)]+ codes = [Path.MOVETO, Path.LINETO, Path.CURVE3, Path.CURVE3, Path.LINETO, Path.CURVE3, Path.CURVE3,+ Path.LINETO, Path.CLOSEPOLY]+ ax.add_patch(PathPatch(Path(verts, codes), fc=color, ec="none", zorder=3))++ def wrap(s, kind, size, max_w):+ lines, cur = [], ""+ for word in s.split():+ trial = f"{cur} {word}".strip()+ if cur and width(trial, kind, size) > max_w:+ lines.append(cur)+ cur = word+ else:+ cur = trial+ return lines + ([cur] if cur else [])++ yb = 60+ text(M, yb, "Graphicle", "bold", 28, C["ink"])+ text(M + width("Graphicle", "bold", 28) + 16, yb, "whole-repository benchmark", "regular", 20, C["muted"])+ yb += 52+ title = ("TEST DATA: " if data.get("test_data") else "") + "What a follow-up question costs with the prompt cache"+ text(M, yb, title, "display", 34, C["ink"])+ yb += 34+ basis = ("prefix and question-specific tokens measured on the development repositories"+ if cost["basis"] == "measured" else "each layout's nominal share of the budget as the shared prefix")+ sub = (f"Input cost of a follow-up question with a {rows[0]['budget']}-token context; {basis}. Computed at the list prices "+ f"of {cost['prices_date']}, not billed. Output is billed on top.")+ for line in wrap(sub, "regular", 20, W - 2 * M):+ text(M, yb, line, "regular", 20, C["muted"])+ yb += 26+ yb += 14+ x = M+ for key in ("uncached", "cached"):+ box(x, yb - 15, 18, 18, S[key], z=3)+ text(x + 28, yb, SERIES_NAMES[key], "medium", 20, C["ink2"])+ x += 28 + width(SERIES_NAMES[key], "medium", 20) + 40+ top = yb + 22++ foot = ["Shared prefix: the part of the context that is the same for every question about a repository at one "+ "commit, billed at the cached-input price after the first question. Truncation's dump is all shared "+ "prefix, so it is cached like the stable pack. Whether a call is served from the cache is up to the API."]+ flines = []+ for para in foot:+ flines += wrap(para, "regular", 18, W - 2 * M)+ footer_top = H - 22 - 25 * (len(flines) + 1)+ y = footer_top+ for line in flines:+ text(M, y + 18, line, "regular", 18, C["muted"])+ y += 25+ label = "Method and data: "+ text(M, y + 18, label, "regular", 18, C["muted"])+ text(M + width(label, "regular", 18), y + 18, URL, "mono", 17, C["muted"])+ box(M, footer_top - 14, W - 2 * M, 1, C["hair"], z=1)+ bottom = footer_top - 34++ names = [SHORT.get(r["arm"], r["context"]) for r in rows]+ gutter = max(width(n, "medium", 20) for n in names) + 24+ PW = (W - 2 * M - gutter - GAP * (len(models) - 1)) / len(models)+ head_h = 30 + 26 + 18+ row_h = min(96, (bottom - top - head_h) / len(rows))+ bh = min(24, (row_h - 18) / 2)+ y0 = top + head_h+ vmax = max(r["models"][m]["first_usd"] for r in rows for m in models)+ fmt_w = max(width(usd(v), "semibold", 20) for r in rows for m in models+ for v in (r["models"][m]["first_usd"], r["models"][m]["follow_up_usd"])) + 12+ for i, n in enumerate(names):+ cy = y0 + row_h * (i + 0.5)+ text(M, cy + CAP * 20 / 2, n, "medium", 20, C["ink2"])+ for j, m in enumerate(models):+ x0 = M + gutter + j * (PW + GAP)+ p = cost["models"][m]+ text(x0, top + 26, MODEL_NAMES.get(m, m), "semibold", 26, C["ink"])+ text(x0, top + 26 + 26, f"${p['input']:.2f} per million input tokens, ${p['cached_input']:.2f} cached",+ "regular", 18, C["muted"])+ span = PW - fmt_w+ box(x0 - 0.75, y0, 1.5, row_h * len(rows), C["hair"], z=3.5)+ for i, r in enumerate(rows):+ cy = y0 + row_h * (i + 0.5)+ for k, (key, field) in enumerate((("uncached", "first_usd"), ("cached", "follow_up_usd"))):+ v = r["models"][m][field]+ yb_ = cy - bh - 1 + k * (bh + 2) # a 2px surface gap between the pair+ length = span * v / vmax if vmax else 0+ hbar(x0, yb_, max(length, 1.5), bh, S[key])+ text(x0 + length + 10, yb_ + bh / 2 + CAP * 18 / 2, usd(v), "semibold", 18, C["ink"])++ problems = [f"fonts missing, DejaVu Sans used: {', '.join(missing)}"] if missing else []+ fig.canvas.draw()+ boxes = []+ for a, s in texts:+ bb = a.get_window_extent(renderer=rend)+ x0, x1, y0_, y1 = bb.x0, bb.x1, H - bb.y1, H - bb.y0+ if x0 < 8 or y0_ < 8 or x1 > W - 8 or y1 > H - 8:+ problems.append(f"outside the canvas: {s!r}")+ for rx, why in FORBIDDEN:+ if rx.search(s):+ problems.append(f"{why}: {s!r}")+ boxes.append((x0, y0_, x1, y1, s))+ for i in range(len(boxes)):+ for k in range(i + 1, len(boxes)):+ a, b = boxes[i], boxes[k]+ if a[0] < b[2] - 1 and b[0] < a[2] - 1 and a[1] < b[3] - 1 and b[1] < a[3] - 1:+ problems.append(f"overlap: {a[4]!r} / {b[4]!r}")+ alt_short, alt_long = alt_text(data, rows)+ fig.savefig(base + ".png", dpi=DPI * 2, facecolor=C["surface"], metadata={"Title": alt_short, "Description": alt_long})+ fig.savefig(base + ".svg", dpi=DPI, facecolor=C["surface"], metadata={"Date": None})+ plt.close(fig)+ with open(base + ".svg", encoding="utf-8") as f:+ svg = f.read()+ svg = re.sub(r'width="[\d.]+pt" height="[\d.]+pt"', f'width="{W}" height="{H}"', svg, count=1)+ i = svg.find(">", svg.find("<svg")) + 1+ svg = svg[:i] + "\n <title>" + html.escape(alt_short) + "</title>\n <desc>" + html.escape(alt_long) + "</desc>" + svg[i:]+ with open(base + ".svg", "w", encoding="utf-8") as f:+ f.write(svg)+ return problems, alt_short, alt_long+++def main():+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--data", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--fonts")+ a = ap.parse_args()+ with open(a.data) as f:+ data = json.load(f)+ os.makedirs(a.out, exist_ok=True)+ bad = False+ for theme in ("light", "dark"):+ base = os.path.join(a.out, f"whole-repo-cost-{theme}")+ problems, alt_short, _ = draw(data, theme, a.fonts, base)+ for p in problems:+ print(f"{theme}: {p}", file=sys.stderr)+ bad = bad or not p.startswith("fonts missing")+ print(f"{base}.svg and .png")+ print(f"alt: {alt_short}")+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ main()diff --git a/docs/configuration.md b/docs/configuration.mdindex 1758895..7ba066a 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -113,10 +113,11 @@ You can add a model in any of three ways:| `base_url` | HTTPS, or HTTP on loopback. A plain-HTTP host on your network must be listed in `GRAPHICLE_PROVIDER_HTTP_HOSTS` (exact host names or addresses, separated by commas). Such a profile cannot have a `key_env` || `model` | The provider's model name || `key_env` | The name of the environment variable that holds the API key. The key itself never goes in the file |-| `input_limit`, `output_limit` | Token limits: 512 to 128,000 (default 16,000) and 64 to 16,000 (default 2,048) |+| `input_limit`, `output_limit` | Token limits: 512 to 1,048,576 (default 16,000) and 64 to 131,072 (default 2,048). A reasoning model counts its reasoning in the output || `temperature` | Optional, from 0 to 2 || `structured_output` | `true` by default. Set it to `false` for servers without schema-constrained output; replies are still validated. With `anthropic`, `true` offers the result as a tool the model is asked to call (Claude Opus 5.5, Claude Sonnet 5.5 and Claude Fable 5.1 refuse a forced tool call); `graphicle config set model anthropic` writes `false`, which asks for the JSON in the prompt |-| `extra_body` | `chat` and `azure_chat` only: up to 16 extra request fields, such as `chat_template_kwargs` |+| `extra_body` | `chat` and `azure_chat` only: up to 16 extra request fields, such as `chat_template_kwargs` or `reasoning_effort` |+| `price` | Optional: what the provider charges, in US dollars per million tokens: `{"input": N, "output": N, "cached_input": N}` (`cached_input` optional). `ask --pack` and `plan` show a call's cost from it; Graphicle has no prices built in |An OpenAI-compatible server, such as vLLM, llama.cpp or LM Studio, takes a`chat` profile. Two commands write one; the second makes it the answer model:@@ -130,6 +131,161 @@ Add `"key_env":"VARIABLE"` when the server needs a key. A server that speaksOpenAI's Responses API, such as vLLM, also works with `graphicle config setmodel openai --url URL --model NAME`, which sends the key in `OPENAI_API_KEY`.+### Muse Spark++Muse Spark and Muse Wonder, Meta's models with a context window of+1,048,576 tokens, are served by the Meta Model API. One command writes the+profile and makes it the answer model; the key stays in `MODEL_API_KEY`:++```sh+export MODEL_API_KEY=... # your Meta Model API key+graphicle config set model meta # Muse Spark 1.3+graphicle config set model meta:muse-wonder-1.0 # Muse Wonder+graphicle config set model meta:muse-spark-1.2 # another Muse Spark model+```++The profile it writes, as `models.meta` in `models.json`:++```json+{+ "protocol": "responses",+ "base_url": "https://api.meta.ai/v1",+ "model": "muse-spark-1.3",+ "key_env": "MODEL_API_KEY",+ "input_limit": 1016576,+ "output_limit": 32000,+ "reasoning_effort": "medium"+}+```++- The profile speaks the Responses API, the one where a 24-hour prompt cache+ retention can be asked for. Profiles written by earlier versions speak+ Chat Completions and keep working.+- The context window holds the input and the output together, so the input+ limit is 1,048,576 less the output limit.+- Muse Spark and Muse Wonder always reason, and the reasoning counts in the+ output. `reasoning_effort` takes `minimal`, `low`, `medium`, `high`,+ `xhigh` or `max`; the API refuses `none`, and so does Graphicle for this+ API. Graphicle sends it as `reasoning.effort` on the Responses API and as+ `reasoning_effort` on Chat Completions.+- `muse-spark-1.3` is the model Meta recommends for new work;+ `muse-spark-1.2` and `muse-spark-1.1` cost the same and stay available.+ `muse-wonder-1.0` is Meta's model for complex software engineering, the+ one to try first for `graphicle fix`.+- The `-contributor` models cost less because Meta may train on what you+ send. `config set model meta` refuses them; to choose one, write the model+ name in the configuration file yourself.+- `graphicle ask --pack`, `graphicle plan` and `graphicle fix` fill the input+ limit with a pack of the project's code ([packs](pack.md)).++**The prompt cache.** The Meta Model API caches the longest repeated start of+a prompt by itself and bills those input tokens at the cached price. For+calls to it, `ask --pack`, `plan` and `fix` send the same instructions first,+then the pack, then the question, and add:++- `prompt_cache_key`: `graphicle:<project>@<commit>:<prefix>`, from the+ project's name, the first 12 characters of its commit and of the pack's+ prefix hash, and nothing the question says;+- `prompt_cache_retention: "24h"` (Responses API only).++With the cache layout of a pack (`--layout cache`), the repository part of+the pack is the same for every question at a commit, so most of a follow-up+question's input can be billed at the cached price. The cache is the+provider's: Meta's documentation calls the retention a hint, not a+guarantee, and the usage line shows how many input tokens were cached.+Other providers get the key only when their profile sets `"prompt_cache":+true`; `"prompt_cache": false` turns it off for the Meta Model API.++**Exact counts.** Before a request whose estimate comes to 80% of the input+limit or more is sent, Graphicle counts it with the API's+`POST /responses/input_tokens`, which generates nothing, and packs again+smaller while it would not fit. Without a key, or if the count fails, the+estimate stands. `"count_tokens": false` turns this off; `"count_tokens":+true` turns it on for another Responses API server. For Muse Spark Open on+your own server, set `"tokenizer"` to its `tokenizer.json`: packs for+`ask --pack`, `plan` and `fix` are then counted with it exactly.++### Prices, the spend log and caps++Prices stay in your configuration, never in the program. A profile's `price`+is in US dollars per million tokens. Meta's list prices for Standard mode on+26 October 2026 (the Meta Model API's pricing page,+https://dev.meta.ai/docs/pricing-rate-limits):++| Model | Input | Cached input | Output |+|---|---|---|---|+| `muse-spark-1.3` (and 1.2, 1.1) | $1.25 | $0.15 | $4.25 |+| `muse-wonder-1.0` | $4.00 | $0.20 | $20.00 |++```sh+graphicle config set models.meta.price '{"input":1.25,"output":4.25,"cached_input":0.15}'+graphicle config set models.meta.price '{"input":4,"output":20,"cached_input":0.2}' # for muse-wonder-1.0+```++Check the pricing page before you rely on these: prices change.++**The spend log.** Every model call of `ask --pack`, `plan` and `fix` adds+one line to `usage.jsonl` in Graphicle's data folder: the time, command,+profile, provider, model, project, commit, prompt cache key, the input,+cached, output and reasoning tokens from the provider's usage, the seconds,+the cost at the profile's price (`null` without one) and the status. It never+holds the prompt or the answer. After each answer, one line sums it up, for+example:++```text+1,012,345 tokens in (936,000 cached, 92%), 2,345 out; $0.25 at the configured price; 41.3 s.+```++`graphicle usage` adds the log up by day and model: calls, tokens, the cached+share and the cost, and lists the calls not logged yet (below) with their+profile, start time, process and worst case. `--since 2026-10-26` (or a time+such as `2026-10-26T12:00:00Z`) starts later, `--json` prints it for+programs (the calls not logged yet as `pending`), and `--clear-pending`+removes the reservations of calls not logged yet, for example after a crash.++**Caps.** Two optional profile settings, in US dollars at the profile's+price, refuse a call before it is sent:++- `max_cost_per_call`: a call whose worst case costs more. The worst case is+ the whole input at the uncached price plus the output limit at the output+ price. The input is the provider's exact count where there is one, else+ Graphicle's estimate times the profile's calibration (when the provider+ counts more than the estimate) plus 10%.+- `max_cost_per_day`: a call whose worst case, added to the day's cost of+ the profile so far (UTC days), would pass it. The day's cost counts every+ logged call at its cost, or at its worst case when the provider reported+ no usage, and every call not logged yet at its worst case: from before it+ is sent until it is logged, a call's worst case is held in+ `usage-pending.json`, so calls made at the same time count against each+ other. A held worst case counts whatever its day, so a call started before+ midnight (UTC) and still running counts against the new day. It stops+ counting when the call is logged, when its process is no longer running+ (where that can be told: Linux and macOS), or 40 minutes after it was+ made (the longest a model call may take, 30 minutes, and a margin);+ `graphicle usage --clear-pending` removes them all at once.++```sh+graphicle config set models.meta.max_cost_per_call 2+graphicle config set models.meta.max_cost_per_day 10+```++A cap needs the profile's `price`. A refusal names the cap and its setting,+for example `models.meta.max_cost_per_call`. If the spend log cannot be+read, calls of a profile with a day cap are refused; a line of it that is not+a JSON object is skipped, and `graphicle usage` lists the lines it skipped.++The same kind of profile works for Muse Spark Open, or any model, on your+own vLLM or SGLang server, and for hosted OpenAI-compatible endpoints:++```sh+graphicle config set model compatible:MODEL --url http://127.0.0.1:8000/v1+graphicle config set models.compatible.input_limit 1000000+```++Add `--key-env VARIABLE` when the endpoint needs a key, and set+`input_limit` to the context length the server runs with, less the output+limit.+Graphicle sends `ollama` requests with thinking turned off (`think: false`),so a thinking model such as `qwen3:4b` writes its answer within`output_limit` instead of spending it on reasoning. When a provider refuses adiff --git a/docs/fix.md b/docs/fix.mdnew file mode 100644index 0000000..300b84d--- /dev/null+++ b/docs/fix.md@@ -0,0 +1,149 @@+# `graphicle fix`: a tested change on a new branch++`graphicle fix` takes an issue, plans a change from a pack of the+repository's code, asks the model for the edits, applies them on a new branch+in a new git worktree, and runs your tests there. When the tests fail, the+end of their output and the diff so far go back to the model, for at most+`--rounds` rounds. Your working tree and your current branch never change,+and nothing is pushed.++```sh+graphicle fix "The Job controller counts a failed pod create as both failed and succeeded" --test "go test ./pkg/controller/job/..."+graphicle fix --issue-file issue.md --test "pytest -q tests/test_cache.py" --rounds 2 --commit+graphicle fix - --test "cargo test -p store" < issue.txt+```++## What it does++1. **Pack and plan.** It makes a pack focused on the issue, in the standard+ layout by default ([packs](pack.md#layouts-and-the-prompt-cache)): one+ run asks about one issue, so the cache layout's shared repository part+ would only take room from the files the issue needs. It then asks for a+ plan, the same validated JSON `graphicle plan` prints: steps,+ files to edit with line ranges, new files, tests and risks, each checked+ against the working tree.+2. **Branch.** Once the plan has come back, it makes the branch+ `graphicle/fix-<words of the issue>` (or `--branch NAME`) from HEAD, in a+ new worktree under Graphicle's data folder (`fix/` there). Uncommitted+ changes in your working tree are not in it; it says so when there are+ some. A cap that refuses the plan, or a provider error, leaves no branch+ behind.+3. **Edits.** It asks for the edits as structured output: for each change, a+ file's path, a search text copied from the file as it is now and its+ replacement; whole new files; a short explanation that cites+ `path:line`; and the tests the model would run or add.+4. **Apply.** The edits apply all or none. Before anything is written,+ every path is checked, every search text must occur exactly once in the+ file as it is, and the new files are checked against each other and the+ folders on disk (a new file `a` and another at `a/b` are refused+ together). Spellings of one path (`src//lib.rs`, `./src/lib.rs`, another+ case where the file system ignores case) are one file. If a write fails,+ every file the round wrote is put back. A search text that carries the+ pack's line numbers still matches.+5. **Test.** Your test command runs in the worktree with `sh -c`, with a+ timeout (`--timeout`, 1 to 86,400 seconds, default 600). The run ends+ when the command ends: whatever it left running in its process group is+ stopped then, and on Linux so is any process it started that left the+ group. At the timeout the command is stopped with its process group (its+ process tree on Windows). The last 6,000 bytes of its output are kept.+ On Linux that sweep also stops daemons the test started for later builds+ to share, such as an `sccache` server or a Gradle daemon; the next build+ starts them again.+6. **Again.** If the tests fail, or no edit could be applied, the next round+ sends the same instructions, pack, issue and plan, then the end of the+ test output and the diff so far. Each round's request is fitted to the+ model's input limit first: the pack is made smaller when the plan, the+ output and the diff would not fit with it. With the Meta Model API, the+ round's start can still be in the provider's prompt cache, so most of a+ follow-up round's input can be billed at the cached price. A provider+ error stops the rounds and is reported as the provider's error.+7. **Report.** The branch and worktree, the plan, each round's result, test+ time and exit code, the files changed, the cited lines checked against+ your working tree, the tests the model suggested (shown, never run), and+ each call's tokens and cost from the [spend log](configuration.md#prices-the-spend-log-and-caps).+ With `--commit`, the change is committed on the new branch; otherwise it+ stays in the worktree for you to read (`git -C <worktree> diff`).++The command ends with status 0 when the tests pass, or when the change was+made without a test command; else with an error that names the worktree.++## Safety++- **Your tests, not the model's.** The test command comes from `--test` or+ the configuration's `fix.test`, never from the model's reply. The model's+ test suggestions are printed, not run. Without a test command the change+ is made and reported as untested.+- **The test command runs model-edited code with your privileges.** It runs+ in the worktree, on the files the model edited, as you, with your+ environment less the variables model keys are read from (the profiles'+ `key_env` and the usual ones such as `MODEL_API_KEY` and+ `OPENAI_API_KEY`); their values are hidden in the output that goes back to+ the model and into the report. On Linux, Graphicle also marks itself not+ dumpable before the test starts, so the test cannot read Graphicle's own+ environment or memory through `/proc`. This is defence in depth, not+ isolation: model-edited code can read whatever you can read, such as your+ files, your keychain, and the environment of your other processes (the+ shell that started Graphicle among them; on macOS and Windows, Graphicle's+ own too), and it can reach the network. For a repository you do not+ trust, run `fix` in a container or a virtual machine that holds no+ secrets but the model key. Read the plan and the diff before you give it+ a test command.+- **Inside the repository only.** Edits and new files may only touch files+ inside the repository: absolute paths, paths with `..`, `.git` in any+ spelling (any case, with trailing dots or spaces, or a Windows short name+ such as `GIT~1`), and symlinks that lead outside or into `.git` are+ refused, and then nothing of that round is written.+- **No hooks.** Every git command `fix` runs, `worktree add` and `commit`+ among them, runs with hooks turned off (an empty hooks folder, and+ `--no-verify` on the commit), so neither your hooks nor hooks the model+ edited run. git also runs without the variables that would point it at+ another repository, index or object store, or add configuration+ (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`,+ `GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT` with its keys and values, and+ the like). The variables that choose your own configuration files+ (`GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_NOSYSTEM`) are kept,+ so the commit has your identity; a hooks folder they name is still turned+ off. Filters your git configuration defines still apply to the files the+ edits touch.+- **No network but the model.** `fix` fetches and pushes nothing. What the+ test command reaches is up to it.+- **Spend.** Every call goes to the spend log, and the profile's+ `max_cost_per_call` and `max_cost_per_day` caps apply to each one.++## Options++| Option | Default | Meaning |+|---|---|---|+| `ISSUE` | none | The issue's text; `-` reads it from standard input |+| `--issue-file FILE` | none | Read the issue's text from a file (at most 1 MiB) |+| `--test CMD` | `fix.test` | The test command, run with `sh -c` in the worktree |+| `--rounds N` | 3 | Rounds of edits and tests at most, 1 to 10 |+| `--budget TOKENS` | the input limit less 16,000 | The pack's budget; the room after it holds the issue, the plan, and a failed round's test output and diff |+| `--branch NAME` | `graphicle/fix-<words>` | The new branch; it must not exist |+| `--commit` | off | Commit the change on the new branch |+| `--timeout SECONDS` | `fix.timeout_seconds`, else 600 | How long the test command may run, 1 to 86,400 |+| `--layout`, `--prefix-share` | `standard`; with `--prefix-share`, `cache` (share 0.9 if `--layout cache` alone) | The pack's layout ([packs](pack.md#layouts-and-the-prompt-cache)) |+| `--focus PATH[:LINES]` | none | A passage the pack takes first, whatever the issue's words rank: `PATH`, `PATH:LINE` (40 lines each side) or `PATH:START-END`; repeatable, at most 50 |+| `--model NAME` | the answer model | Another configured profile |+| `--project P` | this folder's project | A project id, key or synced folder |+| `--json` | off | Print the report as JSON |++`--focus` is for places you already know, such as the candidates+[`graphicle pixel`](flow.md) finds for an element on screen. In the standard+layout the passages lead the pack. In the cache layout they lead the question+part, which gets what the repository part leaves of the budget (a tenth by+default), so a very small `--budget` leaves them no room. The JSON report+lists them under `focus`.++The configuration can hold the test command and its timeout:++```sh+graphicle config set fix '{"test":"go test ./...","timeout_seconds":900}'+```++## Which model++Any configured model with structured output works. Muse Wonder+(`graphicle config set model meta:muse-wonder-1.0`) is Meta's model for+complex, multi-file software engineering and the one to try first; Muse+Spark 1.3 costs less per token ([configuration](configuration.md#muse-spark)).diff --git a/docs/flow.md b/docs/flow.mdnew file mode 100644index 0000000..40d758e--- /dev/null+++ b/docs/flow.md@@ -0,0 +1,134 @@+# See it, find it, fix it, check it++**Status:** built and tested against `demo/mock_meta.py`, a stand-in for the Meta Model API, on our own fixture app+and on excalidraw (#12053). It has not yet run against Meta's live API: the model calls below are what the commands+send, and no live model has answered them yet.++From a bug on the screen to a tested fix, with a receipt:++1. **See it.** `graphicle see` is built to let a model drive a web app in a browser you run, with+ [computer use](https://dev.meta.ai/docs/computer-use.md) on the Meta Model API, until the bug an issue+ describes is on the screen. It keeps every screenshot, a step log, and the point on the last screenshot where+ the model says the bug shows.+2. **Find it.** [`graphicle pixel`](../demo/README.md) on that screenshot and point: SAM 3.1 finds the element,+ Muse Spark reads its text, and Graphicle finds the code that draws it, as `path:line`.+3. **Fix it.** [`graphicle fix`](fix.md) with the issue and those places as `--focus`: a plan, edits on a new+ branch in a new worktree, and your test command. The flow packs for `fix` in the standard layout+ (`--fix-layout`), so the whole budget goes to what the issue and those places need; a single `fix` run sends+ its plan and its rounds with different instructions, so a cache layout's shared repository part would pay off+ only across runs.+4. **Check it.** The patched app is built and served again, and `graphicle see --look-for expected` repeats the+ steps and says whether the screen now shows the expected behaviour.+5. **The receipt.** `receipt.json` and `receipt.md`: the steps, citations and diff, the end of the test log, the+ before and after screenshots, and each model call's model, tokens, cached tokens and cost from the usage log.++`demo/flow/flow.py` runs all five as one command. Each step is also a command of its own.++## `graphicle see`++```sh+graphicle see --task-file issue.md \+ --driver "python3 demo/browser_driver.py --url http://10.0.0.5:3101/" \+ --model wonder --out runs/see --acknowledge-safety-checks+graphicle see --task-file issue.md --look-for expected --driver "..." --model wonder --out runs/check+```++The model sees a screenshot, answers with a batch of actions (click, double click, drag, keys, move, scroll,+type, wait), your driver runs them and takes the next screenshot, and so on until the model stops acting. Its+last answer is a JSON object: what the last screenshot shows (`bug`, `expected` or `neither`), a point on the+element that shows it, and a sentence on what it did. `--look-for bug` (the default) succeeds when the bug shows,+`--look-for expected` when the expected behaviour shows; the exit status says which. The point feeds+`graphicle pixel SCREENSHOT --at X,Y`.++**Models.** Computer use is a tool of the Responses API: Muse Wonder (`muse-wonder-1.0`, recommended) or Muse+Spark 1.3, on a profile with a price (see Money).++**State.** Each request replays the whole run so far with `store: false`: every `computer_call` exactly as the+model returned it (so its `meta_safety_replay_receipt` goes back unchanged), after the reasoning items that came+with it (asked for with `include: ["reasoning.encrypted_content"]`, so the model keeps its reasoning from step to+step), and every screenshot after it. Meta+documents that this replay holds 29 call and output pairs and that `truncation: "auto"` is refused unless enabled+for the account, so `see` never sends `truncation` and takes at most 29 steps (`--steps`, 25 by default).++**Safety.**+- A `pending_safety_checks` entry stops the run, unless you pass `--acknowledge-safety-checks`. Pass it only for+ your own sandboxed app. Then each acknowledgement goes back on the next request, on standard error, and in the+ step log and report.+- The driver gets no model key: the variables model keys are read from are removed from its environment.+- `demo/browser_driver.py` runs headless Chromium with a fresh profile and loads only the app's origin (and any+ `--allow` origins): every other request is aborted, and a WebSocket to any other origin is closed, each counted.+ Service workers are blocked, so no request bypasses that check (a progressive web app registers one). Pop-ups+ are closed, downloads refused, and points outside the screen refused.++**Money.** Every model call goes in the spend log (`graphicle usage`) as `see`, one line per step. Before each+call, its worst case (its input with none of it cached, each screenshot counted by its pixel area at 1,600+tokens per 1280 by 800, and the step's output limit) is checked against the+profile's `max_cost_per_call` and `max_cost_per_day`, and against the run's `--max-cost` (US dollars, 3 by+default) with what the run has cost so far. A profile without a price is refused, since no cap could work.++| Option | Default | Meaning |+|---|---|---|+| `TASK` or `--task-file FILE` | none | The issue: its steps and what goes wrong; `-` reads standard input |+| `--driver CMD` | none | The driver command, run with `sh -c` (below) |+| `--look-for bug\|expected` | `bug` | Reproduce the bug, or check the expected behaviour after a fix |+| `--steps N` | 25 | Model calls at most, 1 to 29 |+| `--max-cost USD` | 3 | The run's cap at the profile's price |+| `--output-tokens N` | 8,192 | Output tokens a step may use (a reply cut short ends the run as `incomplete`) |+| `--acknowledge-safety-checks` | off | Acknowledge pending safety checks, each logged, instead of stopping |+| `--out DIR` | `graphicle-see-<time>` | Screenshots (`step-NN.png`), `steps.jsonl`, `see.json` and `driver.log` |+| `--driver-timeout SECONDS` | 120 | How long the driver may take for one request |+| `--model NAME` | the answer model | The configured profile |+| `--json` | off | Print the report as JSON |++### The driver protocol++A driver is any program that answers one JSON object per line on its standard output for each JSON object per+line on its standard input:++- `{"op":"screenshot"}`: the screen now;+- `{"op":"act","actions":[...]}`: the model's actions as the API gives them, run in order and stopped at the first+ that fails, then the screen;+- `{"op":"close"}`: exit.++A reply is `{"ok":true,"done":N,"error":null,"url":"...","png":"<base64 PNG or JPEG>"}`, or `{"ok":false,+"error":"..."}`. Keep the screen's size the same for a whole run. `demo/browser_driver.py` is the driver for web+apps (Playwright for Python and its Chromium headless shell); a desktop or VM driver can speak the same protocol.++## The flow script++```sh+python3 demo/flow/flow.py demo/flow/targets/fixture.json --out runs/fixture --mock+python3 demo/flow/flow.py TARGET.json --out runs/live --models models.json --key-file ~/.meta-key \+ --data-dir runs/data+```++A target file names the app and the issue:++| Field | Meaning |+|---|---|+| `checkout` | `{"fixture": FOLDER}` (a folder beside the script, made a git repository), or `{"url": ..., "commit": ..., "add_from": {"commit": ..., "paths": [...], "message": ...}}` |+| `issue` | The issue's text, as a person wrote it |+| `build`, `serve`, `test` | Shell commands run in the checkout (and in the fix's worktree): build the app, serve it on `{host}:{port}`, test it |+| `viewport`, `allow` | The screen's size and other origins the page may load |+| `sandboxed` | The app is your own sandbox: `see` acknowledges safety checks, each logged |+| `oracle` | A scripted screen check with no model: fixed clicks, then whether a CSS selector is on screen (the bug) |+| `answer_key` | The files a known fix touched, to compare with |+| `mock` | For `--mock`: the computer-use runs, the strings the reading returns, and the fix's plan and edits |++**Mock.** `--mock` starts `demo/mock_meta.py` in place of the Meta Model API: no key, no model, no cost. It+answers computer use with the target's scripted actions, and refuses a request that breaks the replay Meta's+computer-use page describes: a reasoning item or call not sent back as it was returned, an output that does not+answer its call with a screenshot, or a pending safety check not acknowledged. A mock receipt says so at the top:+its token counts are made up and its costs are those counts at Meta's prices. The scripted screen checks show+what the screen really did.++**Live.** `--models FILE` names profiles for Muse Wonder (`--see-model`, `--fix-model`), Muse Spark+(`--read-model`) and SAM 3.1 (`--sam-model`), each with its price. The key file must be readable by its owner+only; its key goes to Graphicle's processes alone. The script copies the profiles under names of their own for the+run, with caps that hold the run to `--max-run-cost` (3 US dollars by default; the binary checks them before each+call) and output limits of `--max-output` tokens (16,384 by default, since a call's worst case counts all of it),+and does not start when the day's flow runs in the data folder and this one could pass `--max-day-cost`+(10 by default). These caps stop the calls themselves, before they are sent.++The fixture target (`demo/flow/fixture`) is a small app of our own with one planted bug (its main menu stays open+after a click outside it), for runs against the mock with no third-party code.diff --git a/docs/install.md b/docs/install.mdindex 5a91192..173b4b7 100644--- a/docs/install.md+++ b/docs/install.md@@ -12,11 +12,16 @@ After you install, set up a repository with`cd your-repo && graphicle setup`. The [quick start](quickstart.md) shows eachstep.+Claude Code's sandbox does not let setup write `.git/hooks`, `.mcp.json` or+`.claude/settings.local.json`, and Codex's sandbox keeps `.git` read-only.+There, setup prints the lines to add by hand and the command that adds the+agent's hooks later. Or run `graphicle setup` in a normal terminal.+## Homebrew```shbrew install graphicle-ai/tap/graphicle-graphicle --version # graphicle 0.1.8 (core)+graphicle --version # graphicle 0.1.9 (core)````brew upgrade graphicle` installs a new release. Afterwards, read@@ -154,7 +159,7 @@ folder with both programs, `LICENSE`, `NOTICE`, `NOTICE.md`, `README.md`,| Windows, x86-64 (preview) | `x86_64-pc-windows-msvc`, a `.zip` |```sh-version=0.1.8+version=0.1.9target=aarch64-apple-darwinbase=https://github.com/graphicle-ai/graphicle/releases/download/v$versioncurl -fLO "$base/graphicle-$version-$target.tar.gz"@@ -248,7 +253,7 @@ in them.## Check the installation```sh-graphicle --version # graphicle 0.1.8 (core)+graphicle --version # graphicle 0.1.9 (core)graphicle graph --help # the code-graph engine's commandsgraphicle doctor # checks the programs, the data folder and your agents```diff --git a/docs/mcp.md b/docs/mcp.mdindex 67759ec..6bc7bd3 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -316,6 +316,7 @@ are the ones `graphicle sync` or `graph_link` last recorded.|---|---|| `recall_project` | Finds original source evidence and current reviewed memory for a question, within a token budget; an identifier, or a question that only asks where one is defined or used, gets its definitions and references from the code graph || `read_project_source` | Reads a source by ID or path, continuing exactly where an excerpt stopped |+| `pack` | Packs the project's code for a question into one block of text within a token budget (`budget`, default 32,000, at most 200,000): architecture, focus code, call paths, tests, docs and a manifest ([packs](pack.md)) || `list_projects` | Lists the workspace's projects you can read, with the ids `repo` takes (workspace connections only) || `workspace_map` | Maps the projects you can read: their counts of files, documents, code symbols, memories and links, and the imports between them (workspace connections only) || `repository_status` | Shows source coverage, revisions and memory state |diff --git a/docs/muse-code.md b/docs/muse-code.mdnew file mode 100644index 0000000..261c2fd--- /dev/null+++ b/docs/muse-code.md@@ -0,0 +1,229 @@+# Graphicle with Muse Code++Muse Code is Meta's coding agent. `graphicle setup` connects it to+Graphicle's MCP server, which gives it the project's code graph,+whole-repository packs and the project's reviewed memory.++Graphicle's Muse Code plugin, a preview you add with one command, puts the+server, a skill and hooks in one package. The hooks are built to add+Graphicle's context without a tool call, at the start of each session and+after each code question, and to keep each session as a source of the+project, so that the next session can recall what this one decided.++**Status of the plugin.** It is built and tested against a stand-in `muse`+program that follows Muse Code's plugin contract. It has not yet run with+Muse Code on Meta's live API, so which hook events reach the model, and how+the context sits in each request, are as designed, not yet observed.+`bench/muse-code/hook_probe.py` checks the hook events in one short+session. Until that check has passed, setup does not install the plugin for+you.++## Connect++```sh+cd my-project+graphicle setup # syncs the project and connects the agents it finds, Muse Code among them+```++Setup finds Muse Code by its settings folder, `~/.config/muse`, or the+`muse` program, and adds Graphicle's server to Muse Code's settings+([below](#the-mcp-server-alone)).++### Add the plugin (preview)++```sh+graphicle connect muse --hooks --allow-learning+muse plugins approve graphicle # once: Muse Code reviews a plugin's hooks and servers+```++With the `muse` program on your `PATH` (or in `~/.local/bin`, where Muse+Code's installer puts it), `connect muse --hooks`:++1. writes the plugin into Graphicle's data folder (`muse-code-plugin/`),+ with the paths of your `graphicle` program and data folder;+2. backs up Muse Code's plugin records (`<file>.graphicle-bak`, once);+3. runs `muse plugins install <that folder> --scope user`, or+ `muse plugins update graphicle` when it was installed before;+4. removes the settings entry setup wrote for this project (the file backed+ up first), since the plugin's server replaces it;+5. starts building the project's session map in the background.++Muse Code runs the plugin's hooks and server only after you approve them:+until you run `muse plugins approve graphicle` (or approve it in+`/plugins`), Muse Code has no Graphicle server. Then start a new session.+`/mcp` lists the server and its tools; `muse plugins inspect graphicle`+shows the plugin.++- `--allow-learning` lets the agent propose memories, which a person+ reviews; without it the server publishes no proposal tools. `--tools` and+ `--work-state` reach the plugin's server as they reach a settings entry.+ `--name` does not apply: the plugin's id is always `graphicle`.+- Once the plugin is installed, setup and `graphicle connect muse` keep its+ paths current (after an upgrade) and add no settings entry beside it.+- Without the `muse` program, `connect muse --hooks` writes the settings+ entry instead, and says why.++To remove it, `graphicle disconnect muse` runs `muse plugins remove+graphicle` and deletes the package from the data folder. The plugin serves+every project, so a `graphicle disconnect` without a client, in one project,+leaves it; `graphicle disconnect --all` removes it too.++**Before you uninstall Graphicle or delete its data folder, run `graphicle+disconnect muse`.** The plugin's server sets `"mode": "optional"`, as the+settings entry does, and Muse Code accepts the field for a plugin's server,+but it does not show it, and it is not confirmed that Muse Code skips a+plugin's server that fails to start. If it does not, a plugin left behind+would stop every Muse Code session, in every folder, until you run `muse+plugins remove graphicle`. `bench/muse-code/hook_probe.py` records what Muse+Code does when a plugin's server cannot start, with and without the field.++## What the plugin holds++| Part | What it does |+|---|---|+| MCP server | `graphicle mcp --project . --or-workspace` with the flags you gave `connect`: the project of the folder Muse Code starts it in, else every project of the workspace, so it starts in any folder. The code graph's tools, cited search, `pack`, and with `--allow-learning` memory proposals that a person reviews. It sets `"mode": "optional"`, as the settings entry does; whether Muse Code then skips it when it cannot start is not confirmed ([above](#add-the-plugin-preview)). |+| Skill `graphicle` | When to call which tool: `pack` for a question across files, `query_graph` and `get_neighbors` for definitions, callers and callees, `recall_project` for past decisions, `propose_memory` to record one. |+| `SessionStart` hook | Adds the project's map (below) and its reviewed memories. |+| `UserPromptSubmit` hook | For a code question, adds the cited excerpts `graphicle context` finds, at most 8,400 characters, within the hook's time budget (10 seconds unless `prompt_context.seconds` says otherwise). |+| `PostToolBatch` hook | After a batch of tool calls that searched the files, adds one sentence on Graphicle's graph tools, at most five times a session. |+| `Stop`, `PreCompact`, `SessionEnd` hooks | Hand the session log to a detached `graphicle sessions import`: finished turns become sources of the project. |++The hooks never block Muse Code: each exits 0, the session start waits at+most 2.5 seconds for its context, and imports run in their own process.++The package itself, to install by hand, is in+[`packaging/muse-code-plugin/`](../packaging/muse-code-plugin/README.md).++### Context that keeps the prompt cache++The Meta Model API bills the longest start of a request it has seen recently+at its cached price ($0.15 instead of $1.25 per million input tokens on Muse+Spark 1.3, list prices on 26 October 2026). The plugin is designed to add its+context so that the start of every request in a session stays the same+bytes. This is the design; it has not yet been observed in Muse Code's+requests to the live API:++- **At session start:** the project's map comes first. It is the repository+ part of a cache-layout pack with `--prefix-share 1.0`+ ([packs](pack.md#layouts-and-the-prompt-cache)), 8,000 tokens by default:+ the architecture summary, a map of the folders, the most connected files+ and the top documentation. It is the same bytes for every session at a+ commit, so sessions can share it too. The reviewed memories follow it.+- **After a prompt:** the question's excerpts follow the prompt they answer,+ so the conversation before them stays as it was.+- **Never before every model call:** context added on `PreLLMCall` would+ change what each request starts with.++The map is kept in the data folder (`muse-code-packs/`) and rebuilt in the+background when it is older than ten minutes, so a session start never+waits for a pack; the first session after `connect muse --hooks` may start+without it.+`--pack-tokens N` after `hook muse session-start` in the plugin's manifest+sizes it (0 leaves it out, at most 100,000).++## Session memory++The plugin's hooks capture Muse Code sessions the way Claude Code and Codex+sessions are captured ([agents](agents.md#session-capture)):++- **Where Muse Code keeps them:** each session writes one log,+ `~/.local/share/muse/sessions/YYYY/MM/DD/<session id>/session.jsonl`+ (under `$XDG_DATA_HOME` when it is set). Sub-agents write their own logs+ under `subagent/`, which are not captured.+- **What becomes a source:** each finished turn: the person's prompt, the+ answer, the tool calls and their outputs. `<private>` spans and injected+ `<system-reminder>` blocks are dropped, credentials redacted, and tool text+ over 16 KiB replaced by its size and digest. Reasoning is never stored.+- **Import by hand:** `graphicle sessions import --client muse` reads every+ log under the session root; `--path` names one log or a folder of them.+- **Memories:** when the agent calls `propose_memory`, the proposal waits+ for review in the app (`graphicle open`). A memory you approve is in the+ next session's start, by title and id, and `recall_project` finds it with+ its sources.++Muse Code also keeps its own memory (`MEMORY.md` files). Graphicle's+memories are separate: approved by a person, cited to their sources, and+shared by every agent connected to the project.++`bench/muse-code/memory_demo.py` is a two-session example on a public+repository: the first session records a decision, you approve it, and the+second is asked about it and should cite the memory and the code. Its+Graphicle side (a draft is never in a session start, an approved memory is)+is tested; the example itself has not yet run with Muse Code on Meta's live+API.++## Contributor mode++Muse Code turns Contributor mode on by default for subscribers, which lets+Meta train on the content of your requests. With the plugin, those requests+hold your repository's code and memory: turn Contributor mode off in+`/settings` for private code, or run with `--contributor-mode off`.++## The MCP server alone++Without the plugin, `graphicle connect muse` adds one entry per project to+the `mcp_servers` object of `~/.config/muse/settings.json`:++```json+{+ "schema_version": 1,+ "mcp_servers": {+ "graphicle-my-project": {+ "transport": "stdio",+ "command": "/path/to/graphicle",+ "args": ["mcp", "--project", "<project id>"],+ "mode": "optional"+ }+ }+}+```++- Graphicle changes only its own entry; the file's other settings and+ servers stay. Muse Code requires `"schema_version": 1`, and Graphicle adds+ it when the file has none.+- `"mode": "optional"` lets a Muse Code session start, with a warning, when+ Graphicle is not installed.+- `graphicle disconnect muse` removes the entry.++## Use `pack` from Muse Code++The server gives Muse Code the code graph's tools (`query_graph`,+`get_node`, `get_neighbors` and more), cited search (`recall_project`,+`read_project_source`) and `pack`. The `pack` tool returns the project's code+for a question within a token budget (default 32,000 tokens, at most+200,000): an architecture summary, the most relevant code with line+numbers, callers and callees, tests, docs and a manifest of what is in and+what was left out ([packs](pack.md)).++```text+Call graphicle's pack tool for "how does the job controller count pod creations",+with a budget of 100000, then answer from it with path:line citations.+```++Muse Code's models, Muse Spark and Muse Wonder, have context windows of+1,048,576 tokens, so a large pack fits. For a pack larger than the tool's+200,000 tokens, use the command line: `graphicle pack "question" --budget+1000000 --out pack.md`, or `graphicle ask --pack` with the `meta` profile+([configuration](configuration.md#muse-spark)).++## Headless runs++`muse exec` runs one task without the interface, with the plugin's hooks+and server. Muse Code takes the Model API key from `META_API_KEY` before a+stored key or a browser sign-in, and API-key runs are billed by usage to+that key's account:++```sh+META_API_KEY=... muse exec --json --contributor-mode off "How does the scheduler pick a node?"+```++`--json` prints events as JSON lines, with a `run.usage` line before the run+ends. `bench/muse-code/` measures Muse Code with and without the plugin this+way.++## Claude Code and Codex on Meta's models++Meta documents running Claude Code and Codex on its models+(https://dev.meta.ai/docs/coding-agents.md). `graphicle setup` connects+Graphicle to them as to any other agent; only where they send their+requests changes. See [agents](agents.md#claude-code-and-codex-on-metas-models).diff --git a/docs/pack.md b/docs/pack.mdnew file mode 100644index 0000000..ffe3571--- /dev/null+++ b/docs/pack.md@@ -0,0 +1,344 @@+# Packs: one prompt of a repository's code++`graphicle pack` gathers a project's code for one question into a single+block of text that fits a token budget, laid out for a model with a long+context window. `graphicle ask --pack` sends such a pack with the question+to a model in one call, and `graphicle plan` asks for a structured plan of a+change. All three read the project Graphicle already synced: no new index.++```sh+graphicle pack "Where does the scheduler count matching pods for spread constraints?" > pack.md+graphicle pack "How are LimitRange checks done?" --budget 512000 --format xml --out pack.xml+graphicle pack --budget 32000 # no question: an overview of the repository+graphicle ask --pack "Why does the Job controller count a failed pod create twice?"+graphicle plan "Add a metric for evicted pods to the taint manager"+```++## What a pack holds++A pack is built from Graphicle's own retrieval: the ranking `graphicle+context` uses (the passage index, the identifier arm and the code-graph arm),+read as a long ranked list of files instead of a few excerpts.++The ranking reads the question without an issue's environment sections (a+heading below the title that labels the system information, tested versions,+a `<name> version`, the environment, the operating system and the like, or an+issue form's question for them) and its `<name> version: <value>` lines: they+say where the reporter ran the program, not what the code does. A title or a+heading that merely names a version ("Upgrade to version 2 breaks login")+stays in the question. Right after+the top five files come the files the question names:+- by a code name: `TextEdit` names `text_edit.cpp` and `text_edit.h`,+ `FormControl` names `form_control.ts`, `UserModel` names `UserModel.java`;+- by two or three of its words, in the languages that name files after their+ classes (Java, TypeScript and JavaScript, C and C++): "the FileSystem dock"+ names `filesystem_dock.cpp`;+- by a folder name ("Alexa Devices" names `alexa_devices/`).++After the first 15 ranks come the files that define what the top files use:+the Go identifiers they take from imported packages, the Python modules they+import from their own folder, and the TypeScript and JavaScript modules they+import by a relative path or a tsconfig `paths` alias.++The saved code graph gives the line ranges of symbols, the call edges and the+tests. The sections, each with its share of the budget:++| Section | What it holds | Share |+|---|---|---|+| Header | The repository, commit, budget, tokens used, how the files were chosen and how tokens were counted | |+| Manifest | Every file in the pack with its tokens, section and rank, then the top-ranked files left out | |+| Architecture | One line per folder: files, tokens, main language, purpose (from a README or package comment), key symbols by connections in the code graph, entry points; then the dependencies between folders | about 4% (20% without a question) |+| Focus | The ranked files: small ones whole, large ones as excerpts of the symbols around the ranked passages, with overlapping ranges merged | 50% or more |+| Call paths | Callers and callees of the focus symbols, two steps along call edges, as `a (path:line) -> b (path:line)`, then the bodies of the key ones | up to 10% |+| Tests | Tests that call or reference the focus symbols, from the code graph, else the test files that go with the top files by name | up to 10% |+| Docs | Ranked documentation passages and the nearest README of the top files | up to 5% |+| Breadth | The next ranked files, then files in the same folders as the top files, then the rest of the repository by connections in the code graph; a file too large to go in whole goes in as an outline (the first line of each symbol) | the rest |++Without a question, a pack is an overview: the architecture, then files by+connections in the code graph.++Every file chunk names its path, its line range and why it is in the pack.+In Markdown:++````text+### pkg/store/cache.go lines 40-95+why: focus: rank 1, defines Cache.Get, Cache.evict+```go+40 func (c *Cache) Get(key string) (Item, bool) {+...+```+````++and in XML:++```xml+<file path="pkg/store/cache.go" lines="40-95" why="focus: rank 1, defines Cache.Get, Cache.evict">+...+</file>+```++## Options++| Option | Default | Meaning |+|---|---|---|+| `QUESTION` | none | The question or change request; `-` reads it from standard input |+| `--project P` | this folder's project | A project id, key or synced folder |+| `--budget TOKENS` | 128000 | The pack's size, a hard limit, from 512 to 2,000,000 tokens |+| `--format` | `markdown` | `markdown`, `xml`, or `json` (below) |+| `--tokenizer PATH` | none | Count tokens exactly with a Hugging Face `tokenizer.json`, for example the tokenizer of the model you will send the pack to |+| `--bytes-per-token N` | none | Estimate tokens as UTF-8 bytes divided by N for all text alike, without a margin, to match another tool that sizes text that way |+| `--order` | `relevant-last` | `relevant-last`: header, manifest, architecture, breadth, docs, tests, call paths, then focus, so the most relevant code is next to the question that follows the pack. `relevant-first` puts focus first |+| `--line-numbers` | `focus` | Which chunks start each line with its number and a tab: `focus`, `all` or `none` |+| `--sections LIST` | all | Comma-separated: `arch`, `map`, `focus`, `paths`, `tests`, `docs`, `breadth`, `manifest` (`map` is the cache layout's) |+| `--layout` | `standard` | `standard`, or `cache`: a repository part that is the same for every question at a commit, then a question part ([below](#layouts-and-the-prompt-cache)) |+| `--prefix-share F` | 0.9 | With the cache layout, the share of the budget the repository part takes at most, from 0.1 to 1; 1.0 makes a stable pack. Alone, it chooses the cache layout |+| `--out FILE` | standard output | Write the pack to a file |++**Tokens.** With `--tokenizer`, every chunk and the whole pack are counted+with that tokenizer, and the budget is never exceeded. Without it, each+chunk is estimated as its UTF-8 bytes, less its line-number prefixes,+divided by the bytes per token of its file's language, plus 1.6 tokens per+line-number prefix (2.6 past line 9,999); 3% of the budget is held back.+The rates are the Muse Spark Open tokenizer's bytes per token on two large+repositories (kubernetes and home-assistant) over 1.03: for example 3.63+bytes per token for Go, 4.34 for Python, 3.8 for Markdown and 4.1 for JSON;+languages those repositories hardly hold keep lower rates. In 22 packs of+128,000 tokens from those repositories, the estimate ran 7% above that+tokenizer's count (2.5% to 11% per pack). Other tokenizers count+differently: pass `--tokenizer` for an exact count. `--bytes-per-token N`+counts every chunk as its UTF-8 bytes divided by N instead, without a+margin. The header says which way the pack was counted.++**The same inputs give the same pack.** The text is byte for byte the same+for the same project state, question and options.++**Speed.** A pack reads the ranking and the query file that `graphicle+sync` keeps, and file text from the store. On a shallow clone of kubernetes+(30,315 files) on 48 cores of a Linux server, building a pack for each of the+22 questions of GitHub issue #8 took a median of 1.8 seconds at 128,000,+512,000 and 1,000,000 tokens alike, with at most 1.0 GB of memory; the whole+command, which first checks the folder for changed files, took a median of+4.8 seconds. The query file belongs to one build of Graphicle: after an+upgrade, the first pack writes it once and says so (24 seconds on that+kubernetes clone, 16 on home-assistant), and later packs read it.++## Layouts and the prompt cache++A provider with a prompt cache bills the longest start of a prompt it has+seen recently at its cached price. The Meta Model API caches by itself: on+Muse Spark 1.3, cached input costs $0.15 instead of $1.25 per million+tokens; on Muse Wonder, $0.20 instead of $4 (list prices on 26 October+2026). A standard pack names the question in its header, so packs for two+questions share almost nothing. `--layout cache` lays a pack out so that+they share almost all of it:++- **The repository part** comes first and depends only on the project's+ files and the settings (budget, prefix share, tokenizer, format, order,+ line numbers and sections): a header without the question, the+ architecture summary, a map of the folders (the files directly in each,+ their tokens and its most connected symbols), the files with the most+ connections in the code graph (whole, or the first line of each symbol when+ large) and the top documentation (the README and architecture documents).+ It takes at most the prefix share of the budget (`--prefix-share`, 0.9 by+ default).+- **The question part** follows: a manifest, focus, call paths and tests for+ the question, in the room left. It never repeats lines the repository part+ holds; ranked files held whole there are listed as `in the prefix: path+ lines a-b`. It gives full excerpts to one ranked file per 8,000 tokens of+ its room (3 to 15 files, each up to two fifths of the room divided among+ them, or 2,000 tokens when that is more) and compact excerpts to the ranks+ after them.+- The question itself is not in the pack: it goes after it, as `ask --pack`,+ `plan` and `fix` send it.++`--prefix-share 1.0` makes a stable pack: the repository part alone, the same+for every question, so only the question after it changes. Two packs with the+same `prefix_sha256` share their repository part byte for byte. The header+names no budget. `ask --pack`, `plan` and `fix` without `--budget` size the+repository part from the fixed budget the model's input limit gives (the+input limit less 4,000 tokens), not from the budget the calibration sets+(below). What holds, exactly:++- While the calibration (the provider's count over Graphicle's estimate) is+ at most 0.97 divided by the prefix share (0.97 at `--prefix-share 1.0`,+ 1.08 at 0.9), the repository part is sized from the fixed budget and stays+ the same bytes whatever the calibration.+- Above that, the calibrated budget cannot hold the share of the fixed+ budget, and the repository part is sized from 0.8 of the fixed budget, or+ 0.64, 0.512 and so on: the largest of these steps whose share fits. It+ stays the same bytes while the calibration stays within that step (for+ the 0.8 step, at most 0.97 divided by 0.8 times the prefix share: 1.21 at+ `--prefix-share 1.0`, 1.35 at 0.9), and changes when the calibration+ crosses into another step.+- The first call of a model profile has no calibration yet and uses the+ fixed budget, so when the provider counts more than the estimate, the+ second call's repository part differs from the first's; from there on+ the steps above hold.++```sh+graphicle pack "Where does the scheduler count matching pods for spread constraints?" --layout cache --budget 1000000+graphicle ask --pack --layout cache "Why does the Job controller count a failed pod create twice?"+graphicle pack --prefix-share 1.0 --budget 1000000 --out stable.md+```++**Measured on kubernetes** (commit ca8a2a9e4, a shallow clone of 30,315+files; the 22 questions of GitHub issue #8, each with its answer's key file;+counted with Muse Spark Open's tokenizer; no model calls). "Key file in the+pack" counts the questions whose key file has any of its text in the pack:+whole, or as excerpts or outlines of its symbols. The cost of a+follow-up question is the repository part at the cached price plus the+question part at the input price, computed at list prices, not billed;+output, the instructions and the question are extra.++| Budget | Layout | Key file in the pack | Repository part (tokens) | Question part (tokens) | Follow-up, Muse Spark 1.3 | Follow-up, Muse Wonder |+|---|---|---|---|---|---|---|+| 256K | standard | 21 of 22 | 0 | 255,354 | $0.32 | $1.02 |+| 256K | cache 0.5 | 22 of 22 | 127,713 | 117,794 | $0.17 | $0.50 |+| 256K | cache 0.7 | 19 of 22 | 178,838 | 72,157 | $0.12 | $0.32 |+| 256K | cache 0.9 | 17 of 22 | 229,933 | 24,730 | $0.07 | $0.14 |+| 256K | cache 0.95 | 17 of 22 | 242,709 | 12,402 | $0.05 | $0.10 |+| 256K | stable (1.0) | 2 of 22 | 255,481 | 0 | $0.04 | $0.05 |+| 512K | standard | 22 of 22 | 0 | 510,860 | $0.64 | $2.04 |+| 512K | cache 0.5 | 21 of 22 | 255,464 | 227,507 | $0.32 | $0.96 |+| 512K | cache 0.7 | 22 of 22 | 357,662 | 139,480 | $0.23 | $0.63 |+| 512K | cache 0.9 | 18 of 22 | 459,860 | 49,097 | $0.13 | $0.29 |+| 512K | cache 0.95 | 17 of 22 | 485,384 | 24,840 | $0.10 | $0.20 |+| 512K | stable (1.0) | 2 of 22 | 510,963 | 0 | $0.08 | $0.10 |+| 1M | standard | 22 of 22 | 0 | 997,914 | $1.25 | $3.99 |+| 1M | cache 0.5 | 22 of 22 | 498,998 | 428,002 | $0.61 | $1.81 |+| 1M | cache 0.7 | 21 of 22 | 698,573 | 263,859 | $0.43 | $1.20 |+| 1M | cache 0.9 | 21 of 22 | 898,171 | 92,094 | $0.25 | $0.55 |+| 1M | cache 0.95 | 18 of 22 | 948,084 | 47,769 | $0.20 | $0.38 |+| 1M | stable (1.0) | 4 of 22 | 997,976 | 0 | $0.15 | $0.20 |++Token counts are the means over the 22 questions.++The repository part was the same bytes for all 22 questions in every row.+Counting with the tokenizer, building a pack took a median of 3.9 seconds at+256K, 4.6 at 512K and 6.1 at 1M on 48 cores of a Linux server, with at most+1.2 GB of memory (the first packs after a new build also write the+project's query file once, which took 34 seconds and 4.6 GB here).++The trade-off is the question part's size. At the default share it holds a+tenth of the budget, so a cache-layout pack covers fewer of the question's+ranked files than a standard pack of the same budget: at 0.9 the key file+was in the pack for 17, 18 and 21 of the 22 questions at 256K, 512K and 1M,+against 21, 22 and 22 for standard packs. A larger question part closes most+of that gap at a higher cost per follow-up (0.5: 22, 21 and 22). A stable+pack holds no question part at all. `ask --pack` and `plan` keep the+standard layout by default; choose the cache layout and its share when you+will ask several questions about the same commit.++## The JSON format++`--format json` prints one object. Its chunks carry the Markdown text, and+the pack's text is the chunks' `text` joined in order:++```json+{"format":"graphicle.pack.v1","project":"my-app","commit":"<git HEAD or null>","question":"...",+ "budget":128000,"tokens":N,"tokenizer":"estimate","order":"relevant-last",+ "layout":"cache","prefix_share":0.9,"prefix_tokens":N,"prefix_sha256":"<hex>",+ "sections":[{"name":"focus","part":"suffix","tokens":N,+ "chunks":[{"path":"pkg/x.go","start_line":10,"end_line":80,"whole":false,"tokens":N,+ "why":"focus: rank 3, defines Foo","text":"..."}]}],+ "included":[{"path":"pkg/x.go","tokens":N,"rank":3}],+ "omitted":[{"path":"pkg/y.go","rank":51,"tokens":N}],+ "seconds":N}+```++- `included` lists every file with at least one chunk; `rank` is its place+ in the retrieval's ranking, or `null` for files the breadth or+ architecture sections chose.+- `omitted` lists the top-ranked files left out, with estimated tokens.+- Chunks that are not file text (headings, the manifest, the architecture,+ the call paths) have `path`, `start_line` and `end_line` set to `null`.+- `layout` is `standard` or `cache`; `prefix_share` is there for the cache+ layout only. Every section has a `part`, `prefix` or `suffix`: the prefix+ sections come first, and their chunks' text joined in order (the prefix) is+ the start of the pack's text, byte for byte. `prefix_tokens` counts it, and+ `prefix_sha256` is the SHA-256 of its UTF-8 bytes. A standard pack for a+ question has no prefix (its header names the question): `prefix_tokens` is+ 0 and the hash is that of the empty text. An overview is all prefix.++## From an agent: the `pack` tool++The MCP server publishes a `pack` tool in the whole server, which `graphicle+setup` gives Muse Code, Codex, Cursor and Claude Desktop, and in its memory+half (`--tools memory`). Claude Code's entry runs the five essential tools;+`graphicle connect claude-code --tools all` gives it `pack` too. It takes+`question` and `budget` (default 32,000 tokens, at most 200,000) and returns+the pack's Markdown, with the summary fields as structured content. Its+description tells an agent to call it once before a repository-wide question+or a change that spans files, instead of many searches and reads.++## `graphicle ask --pack`++```sh+graphicle ask --pack "Where is the loopback decision for NodePort services made?"+graphicle ask --pack --budget 256000 --model meta "..."+```++- The pack fills the model's input limit, less 4,000 tokens for the+ instructions and the question, or `--budget`. After each call Graphicle+ keeps, per model profile, the ratio of the provider's prompt tokens to its+ own estimate (`pack-calibration.json` in the data folder), and sizes the+ next pack without `--budget` so that the provider's count fills the input+ limit less 3%.+- One model call: the instructions ask for an answer from the pack only,+ with every claim cited as `path:line`, and for a plain statement of what+ the pack does not show.+- The answer streams to the terminal from chat models. Then every cited+ `path:line` is checked against the working tree (the file exists and the+ lines are inside it), and the citations that do not hold are listed.+- The last line gives the tokens in and out from the provider's usage+ counts, and a cost when the profile has a `price` (see+ [configuration](configuration.md#muse-spark)).+- `--model NAME` picks another configured profile; `--json` prints the+ answer, the checked citations, the usage, the prompt cache key and the+ pack's summary as JSON.+- `--layout cache` (and `--prefix-share F`) sends a cache-layout pack. The+ request starts with the same instructions for every question, then the+ pack, then the question; with the Meta Model API it carries a prompt cache+ key and a 24-hour retention, and a request near the input limit is first+ counted with the provider ([configuration](configuration.md#muse-spark)).+- Each call is added to the spend log, and the profile's cost caps apply+ ([configuration](configuration.md#prices-the-spend-log-and-caps)).+- The `basic` and `reflect` workflows are unchanged without `--pack`.++## `graphicle plan`++```sh+graphicle plan "Count evictions per taint in the taint manager and expose them as a metric"+graphicle plan - --json < request.txt+```++`plan` makes a pack focused on the change request and asks the model for a+plan as JSON (schema-constrained where the profile has structured output):++- a summary and the steps in order;+- the files to edit, each with a line range and the reason;+- new files, with their purpose;+- tests to add, update or run;+- risks.++Graphicle then checks the plan against the working tree: files to edit must+exist and their ranges must be inside them, new files must not exist yet,+and tests to update or run must exist. Items that do not hold are marked+`check`. The plan prints as Markdown, or as JSON with `--json`. `plan`+changes no files. Like `ask --pack`, it takes `--layout` and+`--prefix-share`, sends the prompt cache key to the Meta Model API, and adds+its call to the spend log. To make the change itself and test it on a new+branch, see [`graphicle fix`](fix.md).++## Which model++`ask --pack` and `plan` work with any configured chat model; a pack is only+as large as the model's input limit allows. For a whole-repository pack,+use a model with a long context window:++- Muse Spark or Muse Wonder through the Meta Model API: `graphicle config+ set model meta` or `graphicle config set model meta:muse-wonder-1.0`+ ([configuration](configuration.md#muse-spark));+- Muse Spark Open, or any model, on your own vLLM or SGLang server:+ `graphicle config set model compatible:MODEL --url http://HOST:8000/v1`,+ then raise `input_limit` to the server's context length.diff --git a/docs/quickstart.md b/docs/quickstart.mdindex 917aa48..492595e 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -170,6 +170,14 @@ the model, and prints the command that fixes each problem.## Next steps- [Agents](agents.md): what each agent gets, and how to disconnect it+- [Muse Code](muse-code.md): connecting Muse Code, and the plugin preview with hooks+ and session memory+- [Packs](pack.md): one prompt of a repository's code for a long-context model, with+ `graphicle ask --pack` and `graphicle plan`+- [Fix](fix.md): a tested change for an issue, on a new branch+- [Review](review.md): a review of a change, and the GitHub Action that posts it+- [See it, find it, fix it, check it](flow.md): from a bug on the screen to the code+ that draws it and a tested fix- [Moving from Graphify](migrate-from-graphify.md)- [A shared server for your team](team.md)- [MCP](mcp.md): every tool, and other MCP clientsdiff --git a/docs/review.md b/docs/review.mdnew file mode 100644index 0000000..faa6330--- /dev/null+++ b/docs/review.md@@ -0,0 +1,219 @@+# `graphicle review`: review a change with the repository's context++`graphicle review` asks a long-context model, Muse Spark by default with the+`meta` profile, to review a change: what a branch adds since its merge base+with the base branch, as a pull request shows it. Along with the diff, the+model gets what a reviewer would look up: the changed code, the+callers and callees of the changed symbols, the tests that touch them, and+the architecture of the modules the change touches. It returns comments on+changed lines, each with the `path:line` evidence it relies on, and Graphicle+checks every comment before you see it.++```sh+graphicle review # what HEAD adds since the default branch+graphicle review --base main --max-comments 5+graphicle review --base origin/main --format json > review.json+graphicle review --base "$BASE_SHA" --format github > review.json # for GitHub's review API+```++It needs a synced project (`graphicle sync .`, after you check out the head)+and a model profile, for example `graphicle config set model meta` with your+key in `MODEL_API_KEY` ([configuration](configuration.md#muse-spark)). It+changes no files and posts nothing. To post reviews on pull requests, use+[the GitHub Action](#the-github-action).++## Options++| Option | Default | Meaning |+|---|---|---|+| `--base REF` | `origin/HEAD`, else `origin/main`, `origin/master`, `main` or `master` | The branch, tag or commit to review against. The review covers what the head adds since their merge base. |+| `--head REF` | `HEAD` | The head. It must be the commit checked out in the project's folder, because the pack reads the synced files. |+| `--format` | `markdown` at a terminal, else `json` | `markdown`, `json` (the report) or `github` (the body of GitHub's create-a-review call). |+| `--max-comments N` | 20 | Comments to keep at most, from 0 to 100, the most severe first. |+| `--budget TOKENS` | the model's input limit less room for the diff | The pack's size. |+| `--model NAME` | the answer model | A configured model profile. |+| `--layout`, `--prefix-share` | `cache`, 0.9 | The pack's layout ([packs](pack.md#layouts-and-the-prompt-cache)). |+| `--project` | this folder's project | An id, a key or a synced folder. |++## What the model reads++One request, in this order:++1. **The instructions**, the same for every review.+2. **The repository part of the pack**: the architecture summary, a map of+ the folders and the most connected files. It is the same bytes for every+ review of the same commit at the same budget, so a second review of the+ same head (a re-run) can read it from the provider's prompt cache.+3. **The change part of the pack.** The changed hunks are pinned at the top+ of the pack's ranking, so its focus is the changed code (small files+ whole, large ones as the symbols the hunks touch), its call paths are the+ callers and callees of the changed symbols along the code graph's call+ edges (two steps at most), and its tests are the tests that reach them.+ The question's own ranking fills the rest.+4. **The change's text**: the architecture lines of the modules the change+ touches and the dependencies between them, the changed hunks with the+ line ranges a comment may name, and the diff. A diff over 400,000 bytes is+ cut; the list of hunks still names every file.++The diff comes from `git diff` between the merge base and the head, run with+hooks off, without external diff or text conversion drivers, and without the+variables that would point git at another repository. In a project that is a+subfolder of its repository, only the subfolder's changes are reviewed.++## What comes back, and what is checked++The model returns a summary and comments as structured output. Each comment+has a path, a line, a severity (`blocker`, `major`, `minor` or `nit`), a body+and its evidence: `path:line` or `path:start-end` citations. Graphicle sorts+each comment into one of three lists:++- **Comments**: on a line of the head inside one of the diff's changed hunks,+ with at least one citation that holds in the working tree (the file exists+ and has those lines). These are shown and, in the GitHub format, posted.+- **Flagged**: on a changed line, but no citation holds. Shown with the+ reason, never posted.+- **Dropped**: on a file the change does not add or modify, outside the+ changed hunks, empty, a repeat, or past `--max-comments`. Listed with the+ reason.++Citations that do not hold are marked on each comment. A review is advice+from a model: Graphicle checks where a comment points and what it cites, not+whether it is right.++## Output++- **markdown**: the summary, the three lists, and the call's usage line+ (tokens in, cached, out, and the cost at the configured price).+- **json**: `result` (`reviewed`; `no changes`, or `nothing to review` when+ the change only deletes, renames or changes binary files, both without a+ model call), `base`, `merge_base`,+ `head`, `files` (path, status, lines added and removed, hunk ranges),+ `summary`, `comments`, `flagged`, `dropped`, `model`, `usage`,+ `prompt_cache_key`, `context` (the changed symbols, the call-path lines, the+ callers' and callees' excerpts, the tests) and `pack` (the pack's summary).+- **github**: `{"commit_id", "event": "COMMENT", "body", "comments"}`, ready+ for `POST /repos/{owner}/{repo}/pulls/{number}/reviews`. Paths start at+ the repository's root, comments are on the head's side of the diff, and+ `@` before a name gets a word joiner, so the model's text never mentions+ anyone. The event is always `COMMENT`: the review never approves or+ requests changes.++Each review is one model call. It goes through the spend log and its caps+like `ask --pack` ([configuration](configuration.md)): `graphicle usage`+lists it, and `max_cost_per_call` refuses it before it is sent when its worst+case costs more.++## The GitHub Action++A composite action in this repository,+[`packaging/github-action/`](../packaging/github-action/action.yml), runs+`graphicle review --format github` on a pull request and posts one review.++```yaml+name: Graphicle review+on:+ pull_request:+ types: [opened, synchronize, reopened, ready_for_review]++permissions:+ contents: read+ pull-requests: write++concurrency:+ group: graphicle-review-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ review:+ if: github.event.pull_request.draft == false+ runs-on: ubuntu-24.04+ timeout-minutes: 30+ steps:+ - uses: graphicle-ai/graphicle/packaging/github-action@FULL_COMMIT_SHA # vX.Y.Z+ with:+ graphicle-version: X.Y.Z+ graphicle-sha256: SHA256_OF_THE_LINUX_X86_64_ARCHIVE+ model-api-key: ${{ secrets.MODEL_API_KEY }}+ max-cost-usd: "0.50"+```++Replace `X.Y.Z` with a release that has `graphicle review`, `FULL_COMMIT_SHA`+with that release tag's commit, and the SHA-256 with the line for+`graphicle-X.Y.Z-x86_64-unknown-linux-gnu.tar.gz` in the release's+`SHA256SUMS`. Add your Meta Model API key as the repository secret+`MODEL_API_KEY`.++The action:++1. checks the event: it runs on `pull_request` only, and skips with a message+ for a pull request from a fork or a run without a key;+2. checks out the pull request's head with its full history, without keeping+ the token in `.git`;+3. downloads the pinned release and checks its SHA-256 before unpacking it;+4. restores the index from the cache (`actions/cache`, keyed on the base+ commit), then syncs it to the head;+5. writes a `meta` profile with the price and the cost cap, and runs+ `graphicle review --format github`;+6. posts one review with the job's token. If GitHub refuses an inline+ comment (a line outside its view of the diff), the comments go into the+ review's body instead.++| Input | Default | Meaning |+|---|---|---|+| `graphicle-version` | required | The release to install. |+| `graphicle-sha256` | required | The SHA-256 of that release's archive for the runner. |+| `model-api-key` | empty: skip | The key; pass `secrets.MODEL_API_KEY`. |+| `model` | `muse-spark-1.3` | Or `muse-wonder-1.0` (set its `price` too). |+| `price` | `{"input":1.25,"output":4.25,"cached_input":0.15}` | US dollars per million tokens: Muse Spark 1.3's list price on 26 October 2026. |+| `max-cost-usd` | `0.50` | The most one review may cost at that price, worst case. |+| `budget` | `200000` | The pack's budget in tokens. |+| `max-comments` | `10` | Inline comments at most. |+| `post-without-comments` | `true` | Post the summary when there are no inline comments. |+| `github-token` | the job's token | The token that posts the review. |++The cap counts the worst case: the whole input at the uncached price plus+the output limit (16,000 tokens in the action) at the output price, with a+tenth added to an estimated input. At the defaults the pack and the output+come to about $0.34 (220,000 × $1.25 + 16,000 × $4.25 per million), plus the+diff's tokens at the input price: under the $0.50 cap. A larger `budget` needs a larger `max-cost-usd`, or the+call is refused before it is sent.++## Security++The action takes strict defaults and refuses the risky choices:++- **The `pull_request` event only.** On `pull_request`, GitHub gives a pull+ request from a fork no secrets and a read-only token, and the action skips+ it with a message: review it locally with `graphicle review`. The action+ refuses `pull_request_target`, which runs with the repository's secrets+ and a write token; never combine that event with a checkout of the pull+ request's code.+- **Least privilege.** The workflow grants `contents: read` and+ `pull-requests: write`, nothing else. The checkout keeps no credentials in+ `.git`. Only the review step sees the model key, and only the posting step+ sees the GitHub token: Graphicle never gets the token.+- **Pinned code.** The actions the action uses are pinned by full commit SHA,+ the workflow pins the action itself the same way, and the Graphicle release+ is pinned by version and SHA-256. Nothing runs from a moving tag.+- **One key, one place.** The model key comes only from the `MODEL_API_KEY`+ secret through the `model-api-key` input. Graphicle reads it from the+ environment and never writes it to the index, the cache or the log.+- **A cost cap per run.** One model call per run, refused before it is sent+ when its worst case passes `max-cost-usd`; `graphicle usage` prints the+ run's spend log at the end of the job. For a ceiling across runs, set a+ spend limit on the key itself.+- **Little network.** The release download from GitHub, the model API, and+ the GitHub API that posts the review. `graphicle sync` reads the checkout+ locally, and the new-release check is off on CI.+- **The model's text is untrusted.** A pull request's code and text reach+ the model, so a pull request can try to steer what the review says. The+ output can only become one `COMMENT` review on the pull request: comments+ sit on changed lines only, never approve or request changes, and mention+ no one. Treat the review as advice.+- **The cache.** GitHub scopes caches by branch: a pull request's run can+ read the base branch's caches and its own, and other branches cannot read+ what it saves. The index holds the repository's own code.+- **Where the code goes.** The pull request's code goes to the Meta Model+ API in Standard mode, which Meta does not use for training.+ `graphicle config set model` refuses the `-contributor` models, which Meta+ may train on.diff --git a/licenses/graphicle-graph/licenses/THIRD_PARTY_LICENSES.html b/licenses/graphicle-graph/licenses/THIRD_PARTY_LICENSES.htmlindex 3dbb986..d8ada8b 100644--- a/licenses/graphicle-graph/licenses/THIRD_PARTY_LICENSES.html+++ b/licenses/graphicle-graph/licenses/THIRD_PARTY_LICENSES.html@@ -10799,7 +10799,7 @@ Notes<h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p><ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-safe 7.3.0</a></li>-<li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>+<li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li></ul><pre>BSD 3-Clause License@@ -10832,7 +10832,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p>-<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>+<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li></ul><pre>BSD License@@ -10987,7 +10987,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p>-<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>+<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li></ul><pre>The auto-generated bindings are under the 3-clause BSD license:diff --git a/licenses/graphicle/THIRD_PARTY_LICENSES.html b/licenses/graphicle/THIRD_PARTY_LICENSES.htmlindex b2da30f..45aab9f 100644--- a/licenses/graphicle/THIRD_PARTY_LICENSES.html+++ b/licenses/graphicle/THIRD_PARTY_LICENSES.html@@ -10856,9 +10856,9 @@ Notes<h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p><ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-safe 7.3.0</a></li>-<li><a href="https://github.com/gyscos/zstd-rs">zstd-safe 8.0.0</a></li>-<li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>-<li><a href="https://github.com/gyscos/zstd-rs">zstd 0.14.0</a></li>+<li><a href="https://github.com/gyscos/zstd-rs">zstd-safe 8.2.0</a></li>+<li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li>+<li><a href="https://github.com/gyscos/zstd-rs">zstd 0.14.3</a></li></ul><pre>BSD 3-Clause License@@ -10891,7 +10891,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p>-<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>+<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li></ul><pre>BSD License@@ -11045,7 +11045,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</pre><h3 id="BSD-3-Clause">BSD 3-Clause "New" or "Revised" License</h3><p>Used by:</p>-<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.0+zstd.1.5.7</a></li>+<ul><li><a href="https://github.com/gyscos/zstd-rs">zstd-sys 2.1.2+zstd.1.5.7</a></li></ul><pre>The auto-generated bindings are under the 3-clause BSD license:diff --git a/packaging/github-action/action.yml b/packaging/github-action/action.ymlnew file mode 100644index 0000000..ba709fa--- /dev/null+++ b/packaging/github-action/action.yml@@ -0,0 +1,130 @@+# Graphicle review: one pull-request review from Muse Spark, with the+# repository's context from Graphicle (docs/review.md).+#+# Security (docs/review.md#security):+# - runs on the pull_request event only; refuses pull_request_target, and skips+# pull requests from forks, which get no secrets;+# - checks out the pull request's head without keeping the token in .git;+# - the model key comes from the input the workflow fills from the+# MODEL_API_KEY secret, and only the review step sees it; only the posting+# step sees the GitHub token;+# - the actions it uses are pinned by full commit SHA, and the Graphicle+# release by version and SHA-256;+# - one model call per run, refused before it is sent when its worst case+# costs more than max-cost-usd at the configured price;+# - network: the release download, the model API and the GitHub API that+# posts the review.+name: Graphicle review+description: Review a pull request with Muse Spark, with the changed code's callers, callees, tests and architecture from Graphicle, and post one review.+author: Graphicle+branding:+ icon: eye+ color: blue++inputs:+ graphicle-version:+ description: The Graphicle release to install, for example 0.1.9. Pin one; there is no "latest".+ required: true+ graphicle-sha256:+ description: The SHA-256 of that release's archive for the runner (graphicle-VERSION-TARGET.tar.gz in the release's SHA256SUMS).+ required: true+ model-api-key:+ description: The Meta Model API key. Pass secrets.MODEL_API_KEY; without it the review is skipped.+ required: false+ default: ""+ model:+ description: The Meta model, muse-spark-1.3 or muse-wonder-1.0.+ required: false+ default: muse-spark-1.3+ price:+ description: The model's price in US dollars per million tokens, as JSON; the cost cap needs it. The default is muse-spark-1.3's list price on 26 Oct 2026.+ required: false+ default: '{"input":1.25,"output":4.25,"cached_input":0.15}'+ max-cost-usd:+ description: The most one review may cost, in US dollars at that price. The call is refused before it is sent when its worst case (the whole input uncached plus the output limit) costs more.+ required: false+ default: "0.50"+ budget:+ description: The pack's budget in tokens.+ required: false+ default: "200000"+ max-comments:+ description: Inline comments at most, the most severe first.+ required: false+ default: "10"+ post-without-comments:+ description: Post the review's summary when it has no inline comments ("true" or "false").+ required: false+ default: "true"+ github-token:+ description: The token that posts the review; it needs pull-requests write.+ required: false+ default: ${{ github.token }}++outputs:+ comments:+ description: The number of inline comments posted.+ value: ${{ steps.review.outputs.comments }}++runs:+ using: composite+ steps:+ - name: Check the event+ id: gate+ shell: bash+ env:+ EVENT: ${{ github.event_name }}+ HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}+ BASE_REPO: ${{ github.repository }}+ HAS_KEY: ${{ inputs.model-api-key != '' }}+ run: bash "$GITHUB_ACTION_PATH/gate.sh"++ - name: Check out the pull request's head+ if: steps.gate.outputs.run == 'true'+ uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0+ with:+ ref: ${{ github.event.pull_request.head.sha }}+ fetch-depth: 0+ persist-credentials: false++ - name: Install Graphicle ${{ inputs.graphicle-version }}+ if: steps.gate.outputs.run == 'true'+ shell: bash+ env:+ VERSION: ${{ inputs.graphicle-version }}+ SHA256: ${{ inputs.graphicle-sha256 }}+ run: bash "$GITHUB_ACTION_PATH/install.sh"++ - name: Restore the index+ if: steps.gate.outputs.run == 'true'+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ runner.temp }}/graphicle-data+ key: graphicle-index-${{ runner.os }}-${{ inputs.graphicle-version }}-${{ github.event.pull_request.base.sha }}+ restore-keys: |+ graphicle-index-${{ runner.os }}-${{ inputs.graphicle-version }}-++ - name: Review+ id: review+ if: steps.gate.outputs.run == 'true'+ shell: bash+ env:+ MODEL_API_KEY: ${{ inputs.model-api-key }}+ MODEL: ${{ inputs.model }}+ PRICE: ${{ inputs.price }}+ MAX_COST: ${{ inputs.max-cost-usd }}+ BUDGET: ${{ inputs.budget }}+ MAX_COMMENTS: ${{ inputs.max-comments }}+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: bash "$GITHUB_ACTION_PATH/review.sh"++ - name: Post the review+ if: steps.gate.outputs.run == 'true'+ shell: bash+ env:+ GH_TOKEN: ${{ inputs.github-token }}+ REPOSITORY: ${{ github.repository }}+ PULL: ${{ github.event.pull_request.number }}+ POST_EMPTY: ${{ inputs.post-without-comments }}+ run: bash "$GITHUB_ACTION_PATH/post.sh"diff --git a/packaging/github-action/gate.sh b/packaging/github-action/gate.shnew file mode 100755index 0000000..e8cdcac--- /dev/null+++ b/packaging/github-action/gate.sh@@ -0,0 +1,31 @@+#!/usr/bin/env bash+# Whether this run reviews: on the pull_request event only, and not for a+# pull request from a fork (it gets no secrets) or without a model key.+# Writes run=true or run=false to the step's outputs.+set -euo pipefail++skip() {+ echo "graphicle review: skipped: $1"+ echo "run=false" >> "$GITHUB_OUTPUT"+ exit 0+}++case "$EVENT" in+ pull_request) ;;+ pull_request_target)+ echo "::error::graphicle review refuses pull_request_target: that event runs with the repository's secrets and a write token, and this action reads the pull request's code. Use the pull_request event."+ exit 1+ ;;+ *)+ echo "::error::graphicle review runs on the pull_request event, not ${EVENT}."+ exit 1+ ;;+esac++if [ "$HEAD_REPO" != "$BASE_REPO" ]; then+ skip "the pull request comes from a fork (${HEAD_REPO:-deleted}), and GitHub gives fork pull requests no secrets. Review it locally with graphicle review."+fi+if [ "$HAS_KEY" != true ]; then+ skip "no model key. Add the MODEL_API_KEY secret and pass it as model-api-key."+fi+echo "run=true" >> "$GITHUB_OUTPUT"diff --git a/packaging/github-action/install.sh b/packaging/github-action/install.shnew file mode 100755index 0000000..21ba36c--- /dev/null+++ b/packaging/github-action/install.sh@@ -0,0 +1,48 @@+#!/usr/bin/env bash+# Install the pinned Graphicle release for this runner: download its archive+# from the GitHub release, check it against the pinned SHA-256 before+# unpacking anything, and put its folder on PATH.+set -euo pipefail++if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then+ echo "::error::graphicle-version must be a release version such as 0.1.9, not '${VERSION}'."+ exit 1+fi+if ! [[ "$SHA256" =~ ^[0-9a-f]{64}$ ]]; then+ echo "::error::graphicle-sha256 must be the archive's SHA-256: 64 lowercase hex digits."+ exit 1+fi++case "$(uname -s)-$(uname -m)" in+ Linux-x86_64) target=x86_64-unknown-linux-gnu ;;+ Linux-aarch64 | Linux-arm64) target=aarch64-unknown-linux-gnu ;;+ Darwin-arm64) target=aarch64-apple-darwin ;;+ Darwin-x86_64) target=x86_64-apple-darwin ;;+ *)+ echo "::error::No Graphicle release for $(uname -s) $(uname -m)."+ exit 1+ ;;+esac++name="graphicle-${VERSION}-${target}"+dir="${RUNNER_TEMP}/graphicle-bin"+archive="${dir}/${name}.tar.gz"+mkdir -p "$dir"+curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 --retry 3 \+ --output "$archive" \+ "https://github.com/graphicle-ai/graphicle/releases/download/v${VERSION}/${name}.tar.gz"++if command -v sha256sum > /dev/null; then+ actual=$(sha256sum "$archive" | cut -d' ' -f1)+else+ actual=$(shasum -a 256 "$archive" | cut -d' ' -f1)+fi+if [ "$actual" != "$SHA256" ]; then+ echo "::error::${name}.tar.gz has SHA-256 ${actual}, not the pinned ${SHA256}. Nothing was installed."+ rm -f "$archive"+ exit 1+fi++tar -xzf "$archive" -C "$dir"+echo "${dir}/${name}" >> "$GITHUB_PATH"+"${dir}/${name}/graphicle" --versiondiff --git a/packaging/github-action/post.sh b/packaging/github-action/post.shnew file mode 100755index 0000000..a75e017--- /dev/null+++ b/packaging/github-action/post.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# Post the review as one pull-request review, always a plain COMMENT: it never+# approves or requests changes. GitHub refuses the whole review when one of+# its comments sits on a line outside the pull request's diff; the comments+# then go into the review's body instead, still as one review.+set -euo pipefail++review="${RUNNER_TEMP}/graphicle-review.json"+if ! [ -s "$review" ]; then+ echo "graphicle review: no review to post."+ exit 0+fi+count=$(jq '.comments | length' "$review")+if [ "$count" = 0 ] && [ "$POST_EMPTY" != true ]; then+ echo "graphicle review: no inline comments, so nothing was posted."+ exit 0+fi++payload="${RUNNER_TEMP}/graphicle-review-post.json"+jq '.event = "COMMENT"' "$review" > "$payload"+endpoint="repos/${REPOSITORY}/pulls/${PULL}/reviews"+if ! gh api --method POST "$endpoint" --input "$payload" > /dev/null; then+ echo "::warning::GitHub refused the inline comments; posting them in the review's body instead."+ jq '{commit_id, event: "COMMENT", comments: [],+ body: (.body + "\n\n" + ([.comments[] | "- `\(.path):\(.line)`: \(.body | gsub("\n+"; " "))"] | join("\n")))}' \+ "$review" > "$payload"+ gh api --method POST "$endpoint" --input "$payload" > /dev/null+fi+jq -r '.body' "$review" >> "$GITHUB_STEP_SUMMARY"+echo "graphicle review: posted one review with ${count} inline comment(s)."diff --git a/packaging/github-action/review.sh b/packaging/github-action/review.shnew file mode 100755index 0000000..f6665d8--- /dev/null+++ b/packaging/github-action/review.sh@@ -0,0 +1,39 @@+#!/usr/bin/env bash+# Configure the Meta profile with its price and cost cap, bring the index up+# to the pull request's head, and write the review for GitHub. The model key+# reaches Graphicle through MODEL_API_KEY in this step's environment only.+set -euo pipefail++case "$MODEL" in+ muse-spark-1.3 | muse-wonder-1.0) ;;+ *)+ echo "::error::model must be muse-spark-1.3 or muse-wonder-1.0, not '${MODEL}'."+ exit 1+ ;;+esac+if ! [[ "$MAX_COST" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then+ echo "::error::max-cost-usd must be a number of US dollars, such as 0.50."+ exit 1+fi+if ! [[ "$BUDGET" =~ ^[0-9]+$ ]] || ! [[ "$MAX_COMMENTS" =~ ^[0-9]+$ ]]; then+ echo "::error::budget and max-comments must be whole numbers."+ exit 1+fi++export GRAPHICLE_NO_UPDATE_NOTIFIER=1+data="${RUNNER_TEMP}/graphicle-data"+config="${RUNNER_TEMP}/graphicle-models.json"+review="${RUNNER_TEMP}/graphicle-review.json"+graphicle_() { graphicle --data-dir "$data" --config "$config" "$@"; }++graphicle_ config set model "meta:${MODEL}" > /dev/null+graphicle_ config set models.meta.price "$PRICE" > /dev/null+graphicle_ config set models.meta.output_limit 16000 > /dev/null+graphicle_ config set models.meta.max_cost_per_call "$MAX_COST" > /dev/null++graphicle_ sync . --quiet+graphicle_ review --base "$BASE_SHA" --head "$HEAD_SHA" --format github \+ --budget "$BUDGET" --max-comments "$MAX_COMMENTS" > "$review"++echo "comments=$(jq '.comments | length' "$review")" >> "$GITHUB_OUTPUT"+graphicle_ usage || truediff --git a/packaging/github-action/test_action.py b/packaging/github-action/test_action.pynew file mode 100755index 0000000..2e22e46--- /dev/null+++ b/packaging/github-action/test_action.py@@ -0,0 +1,227 @@+#!/usr/bin/env python3+"""Tests of the review action's scripts, with stand-ins for curl, graphicle+and gh on PATH, so they run offline with bash and jq:+python3 packaging/github-action/test_action.py++They check the event gate (forks and runs without a key skip,+pull_request_target and other events fail), the pinned install (a wrong+SHA-256 installs nothing), the review step's configuration and command, and+the posting (one COMMENT review, the body fallback, nothing without+comments when asked)."""+import hashlib+import io+import json+import os+import subprocess+import tarfile+import tempfile+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent+VERSION = '0.1.9'+TARGET = {'Linux-x86_64': 'x86_64-unknown-linux-gnu', 'Linux-aarch64': 'aarch64-unknown-linux-gnu',+ 'Darwin-arm64': 'aarch64-apple-darwin', 'Darwin-x86_64': 'x86_64-apple-darwin'}[+ f'{os.uname().sysname}-{os.uname().machine}']+++class Runner:+ """A temporary runner: RUNNER_TEMP, the output files and a bin folder of stand-ins."""++ def __init__(self, root):+ self.root = Path(root)+ self.temp = self.root / 'runner-temp'+ self.bin = self.root / 'bin'+ self.temp.mkdir()+ self.bin.mkdir()+ self.output = self.root / 'output'+ self.path_file = self.root / 'path'+ self.summary = self.root / 'summary'+ self.calls = self.root / 'calls'+ for f in (self.output, self.path_file, self.summary, self.calls):+ f.write_text('')++ def tool(self, name, body):+ script = self.bin / name+ script.write_text('#!/usr/bin/env bash\n' + body)+ script.chmod(0o755)++ def run(self, script, **env):+ full = {'PATH': f'{self.bin}:/usr/bin:/bin:/usr/local/bin', 'HOME': str(self.root),+ 'RUNNER_TEMP': str(self.temp), 'GITHUB_OUTPUT': str(self.output),+ 'GITHUB_PATH': str(self.path_file), 'GITHUB_STEP_SUMMARY': str(self.summary),+ 'CALLS': str(self.calls), **env}+ return subprocess.run(['bash', str(HERE / script)], env=full, cwd=self.root,+ capture_output=True, text=True)++ def outputs(self):+ return dict(line.split('=', 1) for line in self.output.read_text().splitlines() if '=' in line)+++class Gate(unittest.TestCase):+ def gate(self, **env):+ with tempfile.TemporaryDirectory() as root:+ runner = Runner(root)+ done = runner.run('gate.sh', **{'EVENT': 'pull_request', 'HEAD_REPO': 'org/repo',+ 'BASE_REPO': 'org/repo', 'HAS_KEY': 'true', **env})+ return done, runner.outputs()++ def test_a_pull_request_with_a_key_runs(self):+ done, outputs = self.gate()+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertEqual(outputs, {'run': 'true'})++ def test_a_fork_and_a_missing_key_skip(self):+ for env, words in (({'HEAD_REPO': 'someone/repo'}, 'fork'), ({'HEAD_REPO': ''}, 'fork'),+ ({'HAS_KEY': 'false'}, 'no model key')):+ done, outputs = self.gate(**env)+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertEqual(outputs, {'run': 'false'})+ self.assertIn(words, done.stdout)++ def test_pull_request_target_and_other_events_fail(self):+ for event in ('pull_request_target', 'push', 'issue_comment'):+ done, outputs = self.gate(EVENT=event)+ self.assertEqual(done.returncode, 1)+ self.assertEqual(outputs, {})+ self.assertIn('::error::', done.stdout)+++def archive_bytes():+ """A release archive whose graphicle prints its version."""+ buffer = io.BytesIO()+ with tarfile.open(fileobj=buffer, mode='w:gz') as tar:+ data = f'#!/usr/bin/env bash\necho "graphicle {VERSION}"\n'.encode()+ info = tarfile.TarInfo(f'graphicle-{VERSION}-{TARGET}/graphicle')+ info.size, info.mode = len(data), 0o755+ tar.addfile(info, io.BytesIO(data))+ return buffer.getvalue()+++class Install(unittest.TestCase):+ def install(self, sha256=None, version=VERSION):+ root = tempfile.TemporaryDirectory()+ self.addCleanup(root.cleanup)+ runner = Runner(root.name)+ archive = self.root_archive = Path(root.name) / 'release.tar.gz'+ archive.write_bytes(archive_bytes())+ # curl copies the release archive to --output and records the URL.+ runner.tool('curl', f'''out=""; url=""+while [ $# -gt 0 ]; do case "$1" in --output) out=$2; shift 2;; --proto|--retry) shift 2;; -*) shift;; *) url=$1; shift;; esac; done+echo "$url" >> "$CALLS"; cp "{archive}" "$out"+''')+ sha = sha256 or hashlib.sha256(archive.read_bytes()).hexdigest()+ done = runner.run('install.sh', VERSION=version, SHA256=sha)+ return runner, done++ def test_the_pinned_archive_is_checked_and_put_on_path(self):+ runner, done = self.install()+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ self.assertEqual(runner.calls.read_text().strip(),+ f'https://github.com/graphicle-ai/graphicle/releases/download/v{VERSION}/'+ f'graphicle-{VERSION}-{TARGET}.tar.gz')+ folder = runner.path_file.read_text().strip()+ self.assertTrue((Path(folder) / 'graphicle').exists())+ self.assertIn(f'graphicle {VERSION}', done.stdout)++ def test_a_wrong_sha256_installs_nothing(self):+ runner, done = self.install(sha256='0' * 64)+ self.assertEqual(done.returncode, 1)+ self.assertIn('not the pinned', done.stdout)+ self.assertEqual(runner.path_file.read_text(), '')+ self.assertEqual(list((runner.temp / 'graphicle-bin').iterdir()), [])++ def test_a_version_or_sha256_that_is_not_one_is_refused(self):+ for version, sha in (('latest', None), ('0.1.9; rm -rf /', None), (VERSION, 'abc')):+ runner, done = self.install(sha256=sha, version=version)+ self.assertEqual(done.returncode, 1)+ self.assertEqual(runner.calls.read_text(), '')+++PAYLOAD = {'commit_id': 'f' * 40, 'event': 'COMMENT', 'body': 'Graphicle review.',+ 'comments': [{'path': 'src/a.go', 'line': 5, 'side': 'RIGHT', 'body': '**major**: x\n\nEvidence: `src/a.go:5`'}]}+++class Review(unittest.TestCase):+ def review(self, **env):+ root = tempfile.TemporaryDirectory()+ self.addCleanup(root.cleanup)+ runner = Runner(root.name)+ # graphicle records its arguments and the key it sees; review prints the payload.+ runner.tool('graphicle', f'''echo "key=${{MODEL_API_KEY:-none}} $*" >> "$CALLS"+for a in "$@"; do if [ "$a" = review ]; then echo '{json.dumps(PAYLOAD)}'; fi; done+''')+ full = {'MODEL_API_KEY': 'k', 'MODEL': 'muse-spark-1.3', 'PRICE': '{"input":1.25,"output":4.25,"cached_input":0.15}',+ 'MAX_COST': '0.50', 'BUDGET': '200000', 'MAX_COMMENTS': '10', 'BASE_SHA': 'a' * 40, 'HEAD_SHA': 'b' * 40, **env}+ return runner, runner.run('review.sh', **full)++ def test_the_profile_is_capped_and_the_review_written(self):+ runner, done = self.review()+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ calls = runner.calls.read_text().splitlines()+ data, config = runner.temp / 'graphicle-data', runner.temp / 'graphicle-models.json'+ prefix = f'key=k --data-dir {data} --config {config} '+ self.assertEqual([c[len(prefix):] for c in calls], [+ 'config set model meta:muse-spark-1.3',+ 'config set models.meta.price {"input":1.25,"output":4.25,"cached_input":0.15}',+ 'config set models.meta.output_limit 16000',+ 'config set models.meta.max_cost_per_call 0.50',+ 'sync . --quiet',+ f'review --base {"a" * 40} --head {"b" * 40} --format github --budget 200000 --max-comments 10',+ 'usage'])+ self.assertEqual(json.loads((runner.temp / 'graphicle-review.json').read_text()), PAYLOAD)+ self.assertEqual(runner.outputs(), {'comments': '1'})++ def test_bad_inputs_are_refused_before_anything_runs(self):+ for env in ({'MODEL': 'muse-spark-1.3-contributor'}, {'MAX_COST': '1e9'},+ {'MAX_COST': '$(id)'}, {'BUDGET': '200k'}, {'MAX_COMMENTS': '-1'}):+ runner, done = self.review(**env)+ self.assertEqual(done.returncode, 1, env)+ self.assertIn('::error::', done.stdout)+ self.assertEqual(runner.calls.read_text(), '')+++class Post(unittest.TestCase):+ def post(self, payload, fail_first=False, post_empty='true'):+ root = tempfile.TemporaryDirectory()+ self.addCleanup(root.cleanup)+ runner = Runner(root.name)+ (runner.temp / 'graphicle-review.json').write_text(json.dumps(payload))+ # gh records each call and the payload it would send; it can refuse the first.+ runner.tool('gh', f'''n=$(grep -c . "$CALLS" || true)+input=""; prev=""; for a in "$@"; do [ "$prev" = --input ] && input=$a; prev=$a; done+echo "token=$GH_TOKEN $* $(jq -c . "$input")" >> "$CALLS"+if [ "{'yes' if fail_first else 'no'}" = yes ] && [ "$n" = 0 ]; then exit 1; fi+''')+ done = runner.run('post.sh', GH_TOKEN='t', REPOSITORY='org/repo', PULL='7', POST_EMPTY=post_empty)+ calls = runner.calls.read_text().splitlines()+ sent = [json.loads(c[c.index('{'):]) for c in calls]+ return runner, done, calls, sent++ def test_one_comment_review_is_posted(self):+ runner, done, calls, sent = self.post(dict(PAYLOAD, event='APPROVE'))+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ self.assertEqual(len(calls), 1)+ self.assertTrue(calls[0].startswith('token=t api --method POST repos/org/repo/pulls/7/reviews --input '))+ self.assertEqual(sent[0]['event'], 'COMMENT')+ self.assertEqual(sent[0]['comments'], PAYLOAD['comments'])+ self.assertIn('Graphicle review.', runner.summary.read_text())++ def test_refused_inline_comments_go_into_the_body(self):+ runner, done, calls, sent = self.post(PAYLOAD, fail_first=True)+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ self.assertEqual(len(calls), 2)+ self.assertEqual(sent[1]['comments'], [])+ self.assertEqual(sent[1]['event'], 'COMMENT')+ self.assertIn('- `src/a.go:5`: **major**: x Evidence: `src/a.go:5`', sent[1]['body'])++ def test_no_comments_posts_nothing_when_asked(self):+ runner, done, calls, _ = self.post(dict(PAYLOAD, comments=[]), post_empty='false')+ self.assertEqual(done.returncode, 0, done.stdout + done.stderr)+ self.assertEqual(calls, [])+ runner, done, calls, sent = self.post(dict(PAYLOAD, comments=[]))+ self.assertEqual(len(calls), 1)+++if __name__ == '__main__':+ unittest.main()diff --git a/packaging/muse-code-plugin/.muse-plugin/plugin.json b/packaging/muse-code-plugin/.muse-plugin/plugin.jsonnew file mode 100644index 0000000..674c4ae--- /dev/null+++ b/packaging/muse-code-plugin/.muse-plugin/plugin.json@@ -0,0 +1,105 @@+{+ "schemaVersion": 1,+ "name": "graphicle",+ "displayName": "Graphicle",+ "version": "0.1.9",+ "description": "Graphicle's code graph, whole-repository packs and reviewed project memory for Muse Code, with the context added at session start and per prompt.",+ "compat": {+ "source": "native",+ "manifestDir": ".muse-plugin"+ },+ "capabilities": {+ "skills": [+ {+ "id": "graphicle",+ "path": "skills/graphicle/SKILL.md",+ "enabledDefault": true+ }+ ],+ "commands": [],+ "hooks": [+ {+ "id": "session-start",+ "event": "SessionStart",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "session-start"+ ],+ "timeoutMs": 10000+ },+ {+ "id": "prompt-context",+ "event": "UserPromptSubmit",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "prompt-context"+ ],+ "timeoutMs": 30000+ },+ {+ "id": "tool-batch",+ "event": "PostToolBatch",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "tool-batch"+ ],+ "timeoutMs": 5000+ },+ {+ "id": "stop",+ "event": "Stop",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "stop"+ ],+ "timeoutMs": 10000+ },+ {+ "id": "pre-compact",+ "event": "PreCompact",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "pre-compact"+ ],+ "timeoutMs": 10000+ },+ {+ "id": "session-end",+ "event": "SessionEnd",+ "command": [+ "graphicle",+ "hook",+ "muse",+ "session-end"+ ],+ "timeoutMs": 10000+ }+ ],+ "mcpServers": [+ {+ "id": "graphicle",+ "transport": "stdio",+ "command": [+ "graphicle",+ "mcp",+ "--project",+ ".",+ "--or-workspace",+ "--allow-learning"+ ],+ "mode": "optional"+ }+ ],+ "reminders": []+ }+}diff --git a/packaging/muse-code-plugin/README.md b/packaging/muse-code-plugin/README.mdnew file mode 100644index 0000000..5576968--- /dev/null+++ b/packaging/muse-code-plugin/README.md@@ -0,0 +1,38 @@+# Graphicle plugin for Muse Code++A native Muse Code plugin (`.muse-plugin/plugin.json`) with:++- **the MCP server:** `graphicle mcp --project . --or-workspace --allow-learning`,+ the project of the folder Muse Code starts it in, else every project of+ the workspace;+- **the `graphicle` skill:** when to call which tool;+- **hooks,** built so that the session start adds the repository's map and+ its reviewed memory, a code question adds cited excerpts, a batch of+ searches adds a pointer to the graph tools, and the end of each turn+ stores the session as a source of the project.++`graphicle connect muse --hooks --allow-learning` writes and installs this+plugin for you, with the paths of your Graphicle program and data folder.+To install this copy by hand instead, with `graphicle` on your `PATH`, from+a clone of the Graphicle repository (this folder is+`packaging/muse-code-plugin` in it):++```sh+graphicle setup --clients none # in your project: sync it+muse plugins validate /path/to/graphicle/packaging/muse-code-plugin+muse plugins install /path/to/graphicle/packaging/muse-code-plugin --scope user+muse plugins approve graphicle+```++The plugin is a preview: it is tested against a stand-in `muse` program and+has not yet run with Muse Code on Meta's live API.++**Before you uninstall Graphicle or delete its data folder, remove the+plugin** (`graphicle disconnect muse`, or `muse plugins remove graphicle`).+The plugin's server sets `"mode": "optional"`, and Muse Code accepts that+field, but it is not confirmed that Muse Code skips a plugin's server that+fails to start; it may stop every Muse Code session instead.++Remove it with `muse plugins remove graphicle`, or `graphicle disconnect muse`+when `connect muse --hooks` installed it. See+[docs/muse-code.md](../../docs/muse-code.md).diff --git a/packaging/muse-code-plugin/skills/graphicle/SKILL.md b/packaging/muse-code-plugin/skills/graphicle/SKILL.mdnew file mode 100644index 0000000..449a205--- /dev/null+++ b/packaging/muse-code-plugin/skills/graphicle/SKILL.md@@ -0,0 +1,43 @@+---+name: graphicle+description: Use Graphicle's MCP tools for questions about how this repository works, for changes that span several files, and to recall or record the project's decisions. Graphicle answers with path:line citations from the code graph, whole-repository packs and reviewed project memory.+metadata:+ display-name: Graphicle+---++# Graphicle++Graphicle indexes this repository into a code graph and keeps the project's+reviewed memory. Its context already arrived at the start of the session (a+map of the repository and the reviewed memories) and after code questions+(cited excerpts). Use its tools when that is not enough.++## Which tool++- **A question about how something works, across files:** call `pack` with+ the question and a budget (default 32000 tokens, at most 200000). It+ returns the most relevant code with line numbers, callers and callees,+ tests and docs, and a manifest of what it left out. Answer from it and+ cite `path:line`.+- **Where a symbol is defined, who calls it, what it calls:** `query_graph`+ with the name, then `get_node` and `get_neighbors`. `shortest_path`+ connects two symbols.+- **A past decision, a reason, a convention, or anything said in an earlier+ session:** `recall_project`, then `read_project_source` to quote the source+ it cites. `project_memory` lists the reviewed memories.+- **An exact string you already know:** search the files as usual; Graphicle+ is not needed.++## Recording a decision++When the person makes a decision worth keeping (a design choice, a+convention, a reason not to do something), call `propose_memory` with a+short title, the decision in a sentence or two, and the files or turns it+rests on. A proposal is a draft: a person approves it in Graphicle before+any session sees it. The next session starts with the approved memories.++## Citations++Cite every claim from Graphicle as `path:line` (code) or by the memory or+source id it gave. If a tool says the folder is not a Graphicle project,+tell the person to run `graphicle setup` there.diff --git a/sdk/python/graphicle_sdk/__init__.py b/sdk/python/graphicle_sdk/__init__.pyindex 5b5efc1..a0bf4e1 100644--- a/sdk/python/graphicle_sdk/__init__.py+++ b/sdk/python/graphicle_sdk/__init__.py@@ -73,4 +73,4 @@ __all__ = ["resolve_tool_call","tool_schemas",]-__version__ = "0.1.8"+__version__ = "0.1.9"diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex bd4c5bc..d9ab6b2 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"[project]# The PyPI name "graphicle" belongs to an unrelated project; the import package is graphicle_sdk.name = "graphicle-sdk"-version = "0.1.8"+version = "0.1.9"description = "Python SDK for Graphicle, a local-first memory service that keeps original sources"readme = "README.md"license = "Apache-2.0"diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 71fe323..ce56310 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -1,6 +1,6 @@{"name": "@graphicle/sdk",- "version": "0.1.8",+ "version": "0.1.9","description": "Graphicle project evidence, memory, graph and workflow client","private": true,"type": "module",diff --git a/server.json b/server.jsonindex a556db3..f36ae3c 100644--- a/server.json+++ b/server.json@@ -3,11 +3,11 @@"name": "io.github.Graphicle-AI/graphicle","title": "Graphicle","description": "Code graph and project memory for coding agents, cited to exact files and lines, on your machine.",- "version": "0.1.7",- "websiteUrl": "https://github.com/Graphicle-AI/graphicle/blob/v0.1.7/docs/mcp.md",+ "version": "0.1.8",+ "websiteUrl": "https://github.com/Graphicle-AI/graphicle/blob/v0.1.8/docs/mcp.md","icons": [{- "src": "https://raw.githubusercontent.com/Graphicle-AI/graphicle/74b7137fb34c6a3ef6d36c4929dedb3d5f1f6cb4/packaging/mcpb/icon.png",+ "src": "https://raw.githubusercontent.com/Graphicle-AI/graphicle/4e24671c97cdd702770f3983cee9816876c304f6/packaging/mcpb/icon.png","mimeType": "image/png","sizes": ["512x512"@@ -22,45 +22,45 @@"packages": [{"registryType": "mcpb",- "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.7/graphicle-0.1.7-aarch64-apple-darwin.mcpb",- "version": "0.1.7",- "fileSha256": "968487828cd4900e65d1e4edd707e4e4c158f278dfb61f5f38e7e6b4048713fe",+ "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.8/graphicle-0.1.8-aarch64-apple-darwin.mcpb",+ "version": "0.1.8",+ "fileSha256": "644053a0977d4a60b5fae9ad182637f6937038223d47c2e4fddd1875f9425a0f","transport": {"type": "stdio"}},{"registryType": "mcpb",- "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.7/graphicle-0.1.7-x86_64-apple-darwin.mcpb",- "version": "0.1.7",- "fileSha256": "6f5f1132981ede7896bdb55feb945ac8ba874412a4a98e8b7ca4e924a824b1fb",+ "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.8/graphicle-0.1.8-x86_64-apple-darwin.mcpb",+ "version": "0.1.8",+ "fileSha256": "9cc09ecc0dba89d5590720353fd4dc67bd92a84a08401768954326b8732b6f42","transport": {"type": "stdio"}},{"registryType": "mcpb",- "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.7/graphicle-0.1.7-x86_64-pc-windows-msvc.mcpb",- "version": "0.1.7",- "fileSha256": "7011727e14bd52df9a994c32e69cfc4e65395bdb531dde7fc19a697bec3c717f",+ "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.8/graphicle-0.1.8-x86_64-pc-windows-msvc.mcpb",+ "version": "0.1.8",+ "fileSha256": "2538c881396985fdf80f84ce647a8280e7d7c402273822033aaba1f5dc15e264","transport": {"type": "stdio"}},{"registryType": "mcpb",- "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.7/graphicle-0.1.7-x86_64-unknown-linux-gnu.mcpb",- "version": "0.1.7",- "fileSha256": "6f583c9904a2d523a40f591a989909d9bfdf2228f8c2da1f1517f3526fa7d414",+ "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.8/graphicle-0.1.8-x86_64-unknown-linux-gnu.mcpb",+ "version": "0.1.8",+ "fileSha256": "91d4b905ab891c70b9bf5fb4658ac8f8efaaa5357e6014ccefe9c4075c8a418b","transport": {"type": "stdio"}},{"registryType": "mcpb",- "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.7/graphicle-0.1.7-aarch64-unknown-linux-gnu.mcpb",- "version": "0.1.7",- "fileSha256": "951c5865cf0f92bbd597a24553cad5e850ea591316da00fc82714088e0cf1c2d",+ "identifier": "https://github.com/Graphicle-AI/graphicle/releases/download/v0.1.8/graphicle-0.1.8-aarch64-unknown-linux-gnu.mcpb",+ "version": "0.1.8",+ "fileSha256": "02261bfaa4a8118318081d58de055e9455c65ab16d0c0cb9875cb5b77c520ed9","transport": {"type": "stdio"}