From f4592483f0499dd126a956c3d51e6bc2b7678e64 Mon Sep 17 00:00:00 2001 From: garrytan Date: Mon, 26 Oct 2026 01:52:56 +0000 Subject: [PATCH] fix(context-bill): --exact sends only files the bill prices Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 4 ++-- lib/context-bill.ts | 34 ++++++++++++++++++++++++++++------ test/context-bill.test.ts | 27 +++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6e256d36..c7e0a4f3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,10 +5,10 @@ **`gstack-context-bill` now bills a real install.** On `~/.claude/skills` it reported "2 skills, ~134 tok" always-on, because setup installs each skill as a real directory whose `SKILL.md` and `sections/` are symlinks into the gstack checkout, and the walker only counted regular files. The tool built to answer the token-cost complaint gave a falsely tiny answer on the layout users actually have. On a fresh install it now reports 58 skills, ~6.8K tokens always-on, and 3.6 MB on disk (it was 37 KB across 2 skills). Billing the checkout itself is unchanged (66 skills, ~7.2K tokens). ### Fixed -- **`lib/context-bill.ts`**: `findSkillDirs`, `walkMd` and the foreign-file check follow symlinked files and directories. Every path the bill reports, and every file `--exact` keys on, stays the lexical path under the root you passed. A link to a directory that contains the tree being billed or the skill being walked (`..`, `/`, `$HOME`) is never followed, so a link cannot climb out of the root into its parent or your home directory, even from a symlinked skill that lives elsewhere. The markdown walk expands each real directory once and counts each real file once per skill, under the first path reached in sorted order, which is how a skill loads it: loops end, links that fan out into each other cannot multiply the walk, and a tree with more than 200,000 entries is refused with an error instead of being cut short. `--exact` sends each real file once and prices every link to it with that one measurement, and its notice says how many of the files it sends sit outside the tree behind symlinks (on an install, the checkout's skill files). A link named `*.md` counts only when its target is a `.md` file, so `--exact` never sends a non-markdown file through a markdown-named link. `walkMd` skips a child repo checkout (the `gstack/` link beside the installed skills), as `findSkillDirs` already did, so `--exact` does not send the whole checkout. `--exact` on a path that does not exist now stops with `No such tree` before any request (it used to send its one-character envelope probe first). +- **`lib/context-bill.ts`**: `findSkillDirs`, `walkMd` and the foreign-file check follow symlinked files and directories. Every path the bill reports, and every file `--exact` keys on, stays the lexical path under the root you passed. A link to a directory that contains the tree being billed or the skill being walked (`..`, `/`, `$HOME`) is never followed, so a link cannot climb out of the root into its parent or your home directory, even from a symlinked skill that lives elsewhere. The markdown walk expands each real directory once and counts each real file once per skill, under the first path reached in sorted order, which is how a skill loads it: loops end, links that fan out into each other cannot multiply the walk, and a tree with more than 200,000 entries is refused with an error instead of being cut short. `--exact` sends only files the bill prices, each real file once, and prices every link to it with that one measurement, and its notice says how many of the files it sends sit outside the tree behind symlinks (on an install, the checkout's skill files). A link named `*.md` counts only when its target is a `.md` file, so `--exact` never sends a non-markdown file through a markdown-named link. `walkMd` skips a child repo checkout (the `gstack/` link beside the installed skills), as `findSkillDirs` already did, so `--exact` does not send the whole checkout. `--exact` on a path that does not exist now stops with `No such tree` before any request (it used to send its one-character envelope probe first). ### Tests -- `test/context-bill.test.ts`: an installed-layout fixture (a checkout outside the skills root, real skill directories with symlinked `SKILL.md` and `sections/`, and a `gstack/` link to the checkout) bills both skills with the target's exact frontmatter, `SKILL.md` and section bytes, and keeps every walked path under the root. Negative controls: a dangling `SKILL.md` link and a `SKILL.md` link to a directory are not skills. A second fixture holds a self link, a parent link that reaches a skill outside the root, a loop back into the skill and a link up to the temp root; only the one real skill and its own files are billed. Further cases cover a loop to a directory below the walk root, a root whose name starts with `..`, a symlinked `agents.md` (with a dangling link and a directory of a foreign-file name as controls), `--exact` on the installed layout (every billed file measured; nothing behind `gstack/` or a `.md`-named link to a non-markdown file is sent), a 12-level fan-out of links that reaches one file by 2^12 paths (walked once, where a walker that expands every link would return all 4,096), two skills linking one checkout file and directory (each real file sent once, both skills priced from it), a symlinked skill outside the root with a link up to the root's parent, the `--exact` notice's outside-the-tree count, a skill whose `SKILL.md` is first walked under another name (its frontmatter still measured), a container skill whose nested skill links to the container's own files (both skills still bill them), and `--exact` on a missing tree (named, with no request sent). The installed-layout and escape fixtures fail on main (the first finds no skills, the second bills the outside skill), the missing-tree case fails on main (one request sent), and each later case failed on the commit before its fix. +- `test/context-bill.test.ts`: an installed-layout fixture (a checkout outside the skills root, real skill directories with symlinked `SKILL.md` and `sections/`, and a `gstack/` link to the checkout) bills both skills with the target's exact frontmatter, `SKILL.md` and section bytes, and keeps every walked path under the root. Negative controls: a dangling `SKILL.md` link and a `SKILL.md` link to a directory are not skills. A second fixture holds a self link, a parent link that reaches a skill outside the root, a loop back into the skill and a link up to the temp root; only the one real skill and its own files are billed. Further cases cover a loop to a directory below the walk root, a root whose name starts with `..`, a symlinked `agents.md` (with a dangling link and a directory of a foreign-file name as controls), `--exact` on the installed layout (every billed file measured; nothing behind `gstack/` or a `.md`-named link to a non-markdown file is sent), a 12-level fan-out of links that reaches one file by 2^12 paths (walked once, where a walker that expands every link would return all 4,096), two skills linking one checkout file and directory (each real file sent once, both skills priced from it), a symlinked skill outside the root with a link up to the root's parent, the `--exact` notice's outside-the-tree count, a skill whose `SKILL.md` is first walked under another name (its frontmatter still measured), a container skill whose nested skill links to the container's own files (both skills still bill them), `--exact` on a missing tree (named, with no request sent), and a symlinked skill with a link up to its real parent (the files there are not billed, so not sent). The installed-layout and escape fixtures fail on main (the first finds no skills, the second bills the outside skill), the missing-tree case fails on main (one request sent), and each later case failed on the commit before its fix. ### Gate integrity - No threshold, budget, timeout, trial count, case kind or assertion changed. The bill of this repo's own tree, which the context-budget ratchet reads, is byte-for-byte unchanged. diff --git a/lib/context-bill.ts b/lib/context-bill.ts index c25216779..a3dc7c76c 100644 --- a/lib/context-bill.ts +++ b/lib/context-bill.ts @@ -783,6 +783,31 @@ async function countTokens(text: string, { model, apiKey, fetchImpl }: CountToke return json.input_tokens; } +/** + * The files --exact sends: the .md files the root walk reaches that the bill + * actually prices, each real file once. The root walk alone would also reach + * files a skill's own walk refuses (a symlinked skill's link up to its real + * parent), and those must not leave the machine when nothing bills them. + * + * The root is resolved before keying. buildBill resolves its root, so a + * relative root here would produce keys that never match and every lookup + * would fall back to the estimate. + */ +export function exactSendFiles(root: string): string[] { + const resolved = path.resolve(root); + const fmSuffix = frontmatterKey(""); + const priced = new Set(); + buildBill(resolved, { + tokensOf: (key) => { + try { + priced.add(fs.realpathSync(key.endsWith(fmSuffix) ? key.slice(0, -fmSuffix.length) : key)); + } catch {} + return 0; + }, + }); + return walkMd(resolved).filter((file) => priced.has(fs.realpathSync(file))); +} + export interface ExactMeasurement { tokenSource: string; tokensOf: TokensOf; @@ -823,14 +848,11 @@ export async function measureExactTokens( const opts: CountTokensOptions = { model, apiKey, fetchImpl }; const texts = new Map(); - // The walk returns each real file once, so each is sent once. The bill keys + // The send set holds each real file once, so each is sent once. The bill keys // the same file by every lexical path it is billed under; lexicalOf maps a // real file back to the one key that was measured. const lexicalOf = new Map(); - // Resolve before keying. buildBill resolves its root, so a relative root here - // would produce keys that never match and every lookup would fall back to the - // estimate -- exact mode silently degrading to the thing it replaces. - for (const file of walkMd(path.resolve(root))) { + for (const file of exactSendFiles(root)) { const text = fs.readFileSync(file, "utf8"); texts.set(file, text); lexicalOf.set(fs.realpathSync(file), file); @@ -1039,7 +1061,7 @@ export async function contextBillMain(argv: string[], options: MainOptions = {}) }> => { if (!flags.exact) return {}; if (!fs.existsSync(tree)) throw new Error(`No such tree: ${path.resolve(tree)}`); - const walked = walkMd(tree); + const walked = exactSendFiles(tree); const treeReal = fs.realpathSync(tree); const outside = walked.filter((f) => !encloses(treeReal, fs.realpathSync(f))).length; stderr.write( diff --git a/test/context-bill.test.ts b/test/context-bill.test.ts index 13486797a..82071b46a 100644 --- a/test/context-bill.test.ts +++ b/test/context-bill.test.ts @@ -899,6 +899,33 @@ describe("--exact (opt-in measurement; offline here via an injected fetch)", () fs.rmSync(tmp, { recursive: true, force: true }); }); + it("sends nothing the bill does not price, even what the root walk reaches", async () => { + if (process.platform === "win32") return; + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-send-set-")); + const skills = path.join(tmp, "skills"); + const ext = path.join(tmp, "ext"); + fs.mkdirSync(skills); + fs.mkdirSync(path.join(ext, "cc"), { recursive: true }); + fs.mkdirSync(path.join(ext, "private")); + fs.writeFileSync(path.join(ext, "cc", "SKILL.md"), "---\nname: cc\ndescription: d\n---\n# cc\n"); + fs.writeFileSync(path.join(ext, "private", "notes.md"), "PRIVATE-NOTES"); + fs.symlinkSync(ext, path.join(ext, "cc", "up")); + fs.symlinkSync(path.join(ext, "cc"), path.join(skills, "cc")); + const calls: { body: string }[] = []; + const stderr = capture(); + const code = await contextBillMain([skills, "--exact", "--json"], { + stdout: capture().stream, + stderr: stderr.stream, + apiKey: "sk-test", + fetchImpl: fakeFetch(calls), + egressHome, + }); + expect(code).toBe(0); + expect(calls.some((c) => c.body.includes("PRIVATE-NOTES"))).toBe(false); + expect(stderr.text()).toContain("sending the content of 1 .md file(s)"); + fs.rmSync(tmp, { recursive: true, force: true }); + }); + it("names a missing tree, without a raw ENOENT or any request", async () => { const out = capture(); const calls: { body: string }[] = [];