Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepfix/audit-sweep-2026-07-26gatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
ai-quota-metering.test.ts6.7 KB · 187 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/**
 * Regression guard: the AI spend cap must actually be able to trip.
 *
 * assertAiQuota is called at the top of the AI features (ai-review,
 * ai-review-trio, ai-ci-healer). It reads
 * userQuotas.aiTokensUsedThisMonth — and NOTHING ever incremented that
 * column. bumpUsage, the function whose entire job is to increment it, had
 * zero callers anywhere in the codebase. So the counter sat at 0 forever,
 * `allowed` was always true, and the monthly AI cap could never fire.
 *
 * Token counts were being recorded accurately the whole time, just into
 * ai_cost_events via recordAiCost, which the enforcement path does not read.
 * Metering and enforcement were wired to two different stores. Every piece
 * existed — bumpUsage, invalidateQuotaCache, checkAiQuotaCached,
 * assertAiQuota — and none of them were connected.
 *
 * The second half matters as much as the first: getUserQuota does NOT roll
 * the monthly cycle, and resetIfCycleExpired's only other caller is the
 * repo-creation gate. Making the counter live without also rolling it would
 * have permanently locked users out of AI once they hit the cap, released
 * only by the unrelated act of creating a repository. That would be a worse
 * bug than the one being fixed.
 *
 * The rule is asserted directly; the wiring is asserted from source, because
 * the defect was an absent call and no test of the rule alone would catch a
 * regression that simply stops calling it.
 */

import { describe, it, expect } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { quotaChargeForCall } from "../lib/ai-cost-tracker";

const USER = "11111111-1111-1111-1111-111111111111";

describe("quotaChargeForCall", () => {
  it("charges the owner for input plus output tokens", () => {
    expect(
      quotaChargeForCall({ ownerUserId: USER, inputTokens: 900, outputTokens: 100 })
    ).toEqual({ userId: USER, tokens: 1000 });
  });

  it("charges nobody when the call has no owner", () => {
    // Platform-internal work (cron sweeps, system tasks) has nobody to bill
    // and must not be charged to whichever user happens to be nearby.
    expect(
      quotaChargeForCall({ ownerUserId: null, inputTokens: 500, outputTokens: 500 })
    ).toBeNull();
    expect(
      quotaChargeForCall({ ownerUserId: "", inputTokens: 500, outputTokens: 500 })
    ).toBeNull();
    expect(
      quotaChargeForCall({ inputTokens: 500, outputTokens: 500 })
    ).toBeNull();
  });

  it("skips calls that consumed nothing", () => {
    expect(
      quotaChargeForCall({ ownerUserId: USER, inputTokens: 0, outputTokens: 0 })
    ).toBeNull();
  });

  it("never charges a negative or fractional amount", () => {
    // A bad usage payload must not be able to REFUND quota and hand a user
    // unlimited spend.
    expect(
      quotaChargeForCall({ ownerUserId: USER, inputTokens: -5000, outputTokens: 10 })
    ).toEqual({ userId: USER, tokens: 10 });
    expect(
      quotaChargeForCall({ ownerUserId: USER, inputTokens: -50, outputTokens: -50 })
    ).toBeNull();
    expect(
      quotaChargeForCall({ ownerUserId: USER, inputTokens: 1.9, outputTokens: 0.9 })
    ).toEqual({ userId: USER, tokens: 1 });
  });

  it("tolerates missing token fields", () => {
    expect(
      quotaChargeForCall({
        ownerUserId: USER,
        inputTokens: undefined as unknown as number,
        outputTokens: 7,
      })
    ).toEqual({ userId: USER, tokens: 7 });
  });
});

// --- the wiring must stay connected ----------------------------------------
//
// Strip ONLY line comments: a block-comment regex eats path-like text.

function source(...rel: string[]): string {
  const raw = readFileSync(join(import.meta.dir, "..", ...rel), "utf8");
  const stripped = raw
    .split("\n")
    .filter((l) => !l.trim().startsWith("//") && !l.trim().startsWith("*"))
    .join("\n");
  expect(stripped.length).toBeGreaterThan(0);
  return stripped;
}

/** Slice by anchor, never by character count. */
function slice(src: string, startAnchor: string, endAnchor: string): string {
  const start = src.indexOf(startAnchor);
  expect(start).toBeGreaterThan(-1);
  const end = src.indexOf(endAnchor, start + startAnchor.length);
  expect(end).toBeGreaterThan(start);
  const body = src.slice(start, end);
  expect(body.length).toBeGreaterThan(0);
  return body;
}

describe("recordAiCost meters the quota", () => {
  const src = source("lib", "ai-cost-tracker.ts");

  it("awaits the meter — referencing it is not calling it", () => {
    // Asserting the identifier merely APPEARS is too weak: `void
    // meterAiQuota;` satisfies that while metering nothing. Require the
    // awaited invocation.
    const body = slice(
      src,
      "export async function recordAiCost",
      "export async function summarize"
    );
    expect(body).toContain("await meterAiQuota(args)");
  });

  it("meters before the ledger insert, so a ledger failure cannot skip it", () => {
    const body = slice(
      src,
      "export async function recordAiCost",
      "export async function summarize"
    );
    expect(body.indexOf("await meterAiQuota(args)")).toBeLessThan(
      body.indexOf("insert(aiCostEvents)")
    );
  });

  it("bumps the column the enforcement path actually reads", () => {
    expect(src).toContain("bumpUsage");
    expect(src).toContain("aiTokensUsedThisMonth");
  });

  it("invalidates the cached verdict after bumping", () => {
    // Otherwise a burst of calls keeps reusing a stale allow until the cache
    // expires and sails past the cap.
    const meter = slice(src, "async function meterAiQuota", "export interface");
    expect(meter).toContain("invalidateQuotaCache");
    expect(meter.indexOf("bumpUsage")).toBeLessThan(
      meter.indexOf("invalidateQuotaCache")
    );
  });
});

describe("the quota gate rolls the monthly cycle", () => {
  const src = source("lib", "billing.ts");

  it("resets an expired cycle before reading usage", () => {
    const body = slice(
      src,
      "export async function checkAiQuotaCached",
      "export function invalidateQuotaCache"
    );
    expect(body).toContain("resetIfCycleExpired");
    expect(body.indexOf("resetIfCycleExpired")).toBeLessThan(
      body.indexOf("getUserQuota(userId)")
    );
  });

  it("still fails open on billing errors", () => {
    // Billing must never be a hard dependency of the primary path.
    const body = slice(
      src,
      "export async function checkAiQuotaCached",
      "export function invalidateQuotaCache"
    );
    expect(body).toContain("allowed: true");
  });
});

describe("AI entry points still assert the quota", () => {
  for (const file of ["ai-review.ts", "ai-review-trio.ts", "ai-ci-healer.ts"]) {
    it(`${file} calls assertAiQuota`, () => {
      expect(source("lib", file)).toContain("assertAiQuota(");
    });
  }
});