mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-12 11:40:51 +01:00
fix(context-bill): --exact refuses every missing tree before sending, and the notice counts what is sent
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
f4592483f0
commit
21f9c1c245
3 files changed
+40
-12
No files matched your search
+2
-2
@@ -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 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).
|
||||
- **`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, including `--diff` with one missing tree (it used to send its one-character envelope probe first, and `--diff` sent the whole first tree), and its notice counts the same list of files it then sends. `--help` now says `--exact` sends the `.md` files the bill prices, including files reached through symlinks.
|
||||
|
||||
### 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), `--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.
|
||||
- `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 and `--diff --exact` with a missing second 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.
|
||||
|
||||
+14
-9
@@ -831,7 +831,9 @@ export interface ExactMeasurement {
|
||||
*/
|
||||
export async function measureExactTokens(
|
||||
root: string,
|
||||
{ model, apiKey, fetchImpl = fetch, onProgress, egressHome }: {
|
||||
{ files, model, apiKey, fetchImpl = fetch, onProgress, egressHome }: {
|
||||
/** The send set from exactSendFiles(root), when the caller already computed it. */
|
||||
files?: string[];
|
||||
model: string;
|
||||
apiKey: string;
|
||||
fetchImpl?: FetchLike;
|
||||
@@ -852,7 +854,7 @@ export async function measureExactTokens(
|
||||
// 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<string, string>();
|
||||
for (const file of exactSendFiles(root)) {
|
||||
for (const file of files ?? exactSendFiles(root)) {
|
||||
const text = fs.readFileSync(file, "utf8");
|
||||
texts.set(file, text);
|
||||
lexicalOf.set(fs.realpathSync(file), file);
|
||||
@@ -1004,7 +1006,8 @@ const USAGE =
|
||||
"\n" +
|
||||
" --exact measure tokens with Anthropic's count_tokens instead of\n" +
|
||||
" estimating. Off by default: it sends the content of every\n" +
|
||||
" .md file in the tree to api.anthropic.com. Needs\n" +
|
||||
" .md file the bill prices (including files reached\n" +
|
||||
" through symlinks) to api.anthropic.com. Needs\n" +
|
||||
" ANTHROPIC_API_KEY; passing --exact is the consent. An\n" +
|
||||
" egress receipt is written before the send (see\n" +
|
||||
" gstack-egress); if it cannot be written, the run falls\n" +
|
||||
@@ -1053,15 +1056,14 @@ export async function contextBillMain(argv: string[], options: MainOptions = {})
|
||||
|
||||
// Exact mode is the only path that leaves the machine. Announce what is sent
|
||||
// before sending it, and degrade to the estimate rather than failing the run.
|
||||
const exactFor = async (tree: string): Promise<{
|
||||
const sendSet = (tree: string) => (flags.exact ? exactSendFiles(tree) : []);
|
||||
const exactFor = async (tree: string, walked: string[]): Promise<{
|
||||
tokensOf?: TokensOf;
|
||||
tokenSource?: string;
|
||||
calibration?: Calibration;
|
||||
onDone?: () => void;
|
||||
}> => {
|
||||
if (!flags.exact) return {};
|
||||
if (!fs.existsSync(tree)) throw new Error(`No such tree: ${path.resolve(tree)}`);
|
||||
const walked = exactSendFiles(tree);
|
||||
const treeReal = fs.realpathSync(tree);
|
||||
const outside = walked.filter((f) => !encloses(treeReal, fs.realpathSync(f))).length;
|
||||
stderr.write(
|
||||
@@ -1071,6 +1073,7 @@ export async function contextBillMain(argv: string[], options: MainOptions = {})
|
||||
);
|
||||
try {
|
||||
const measured = await measureExactTokens(tree, {
|
||||
files: walked,
|
||||
model: flags.exactModel,
|
||||
apiKey: options.apiKey ?? process.env.ANTHROPIC_API_KEY ?? "",
|
||||
fetchImpl: options.fetchImpl,
|
||||
@@ -1104,8 +1107,10 @@ export async function contextBillMain(argv: string[], options: MainOptions = {})
|
||||
}
|
||||
const treeA = path.resolve(cwd, positional[0]);
|
||||
const treeB = path.resolve(cwd, positional[1]);
|
||||
const optsA = await exactFor(treeA);
|
||||
const optsB = await exactFor(treeB);
|
||||
const filesA = sendSet(treeA);
|
||||
const filesB = sendSet(treeB);
|
||||
const optsA = await exactFor(treeA, filesA);
|
||||
const optsB = await exactFor(treeB, filesB);
|
||||
const diff = diffBills(buildBill(treeA, optsA), buildBill(treeB, optsB));
|
||||
optsA.onDone?.();
|
||||
optsB.onDone?.();
|
||||
@@ -1120,7 +1125,7 @@ export async function contextBillMain(argv: string[], options: MainOptions = {})
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
const exactOpts = await exactFor(tree);
|
||||
const exactOpts = await exactFor(tree, sendSet(tree));
|
||||
const bill = buildBill(tree, exactOpts);
|
||||
exactOpts.onDone?.();
|
||||
if (bill.skills.length === 0) {
|
||||
|
||||
@@ -921,27 +921,50 @@ describe("--exact (opt-in measurement; offline here via an injected fetch)", ()
|
||||
egressHome,
|
||||
});
|
||||
expect(code).toBe(0);
|
||||
expect(stderr.text()).not.toContain("--exact unavailable");
|
||||
expect(calls.some((c) => c.body.includes("# cc"))).toBe(true);
|
||||
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 parent = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-missing-"));
|
||||
const out = capture();
|
||||
const calls: { body: string }[] = [];
|
||||
const code = await contextBillMain([path.join(os.tmpdir(), "context-bill-no-such-tree"), "--exact"], {
|
||||
const code = await contextBillMain([path.join(parent, "absent"), "--exact"], {
|
||||
stdout: out.stream,
|
||||
stderr: out.stream,
|
||||
apiKey: "sk-test",
|
||||
fetchImpl: fakeFetch(calls),
|
||||
egressHome,
|
||||
});
|
||||
fs.rmSync(parent, { recursive: true, force: true });
|
||||
expect(code).toBe(1);
|
||||
expect(out.text()).toContain("No such tree:");
|
||||
expect(out.text()).not.toContain("ENOENT");
|
||||
expect(calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("--diff with a missing second tree sends nothing from the first", async () => {
|
||||
const parent = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-diff-missing-"));
|
||||
fs.mkdirSync(path.join(parent, "a", "qa"), { recursive: true });
|
||||
fs.writeFileSync(path.join(parent, "a", "qa", "SKILL.md"), "---\nname: qa\ndescription: d\n---\n# qa\n");
|
||||
const out = capture();
|
||||
const calls: { body: string }[] = [];
|
||||
const code = await contextBillMain(["--diff", path.join(parent, "a"), path.join(parent, "absent"), "--exact"], {
|
||||
stdout: out.stream,
|
||||
stderr: out.stream,
|
||||
apiKey: "sk-test",
|
||||
fetchImpl: fakeFetch(calls),
|
||||
egressHome,
|
||||
});
|
||||
fs.rmSync(parent, { recursive: true, force: true });
|
||||
expect(code).toBe(1);
|
||||
expect(out.text()).toContain("No such tree:");
|
||||
expect(calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("measures a skill's frontmatter even when its file was first walked under another name", async () => {
|
||||
if (process.platform === "win32") return;
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "context-bill-fm-alias-"));
|
||||
|
||||
Reference in new issue
Block a user