Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
39b99c0
fix(ads): every proof and meter reset needs a card request behind it
arul28 Nov 30, 2026
647a8fa
fix(ads): the owner's report counts a proof only with its own row
arul28 Nov 30, 2026
47a2ed0
test(ads): proofs, retries and the Free Models meter need a card requ…
arul28 Nov 30, 2026
cf3a931
docs(ads): the ads invariants, and the README's rules as the server k…
arul28 Nov 30, 2026
cd60de8
fix(ads): a message's proof is covered by a recent card request or op…
arul28 Nov 30, 2026
80906b1
test(ads): covered messages, window-opening rooms, meter resets and o…
arul28 Nov 30, 2026
455d994
docs(ads): the cover and window-opening rules, the meter's resets, an…
arul28 Nov 30, 2026
4246df1
fix(ads): a message counts when its own computer had a card request, …
arul28 Nov 30, 2026
4e54c55
test(ads): a simulated day per strategy stays under its bounds, and a…
arul28 Nov 30, 2026
ce4c3c8
docs(ads): a card request backs its own computer, a fixed few windows…
arul28 Nov 30, 2026
66c81c6
fix(ads): a kept answer backs only from its own request, the refused …
arul28 Nov 30, 2026
b79faee
test(ads): kept-answer replays, takeovers the limits refused, one met…
arul28 Nov 30, 2026
84c1ab4
docs(ads): kept answers, one meter start over a turn, brand-new chats…
arul28 Nov 30, 2026
f1cb6fb
fix(ads): a message's rows all fit under the day's proofs or none go,…
arul28 Nov 30, 2026
68fa735
test(ads): a create the minute tick adopts keeps its first message's …
arul28 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .agents/skills/quality/references/ade-review-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,30 @@ perf budget in `AGENTS.md` still decides what needs a measurement.

---

## 15. Ads invariants

**Class:** A proof, a Free Models meter reset or a partner request that an app
can raise with no server-side bound behind it. Read **Ads invariants** in
`docs/features/ade-cloud/README.md` first.

**Check:** For each change to `gravity.ts`, `gravityAd.ts`, `adPrice.ts`,
`adProof.ts`, `sponsoredConsent.ts`, `sponsoredTurns.ts`,
`sponsoredSmall.ts`, `sponsoredReport.ts` or `freeModelsMeter.ts`
(`apps/account-directory/src/cloud/`), name in the review:

- The card request behind each new or changed proof or meter reset (the
turn's request, its kept answer, or the day's limit refusing it; for a
message, the proof that covers it or the room it opens a window in).
- The per-account daily bound on the server that stops each new count, and
that it is checked in the same write that counts.
- That a count moves only when its own row was written, so a repeat or a race
never counts twice, and that a refused proof syncs the price.

A proof or reset with no request behind it, or a count with no daily bound,
is High.

---

## Output

Same per-finding shape as `correctness-security-review.md`: Severity / Location
Expand Down
14 changes: 14 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,20 @@ phone.
`daex secrets exec --env CLOUD_OWNER_TOKEN`. It is instant and never
touches Stripe. Guide: `docs/features/ade-cloud/account-test-tool.md`.

## Ads invariants

Read **Ads invariants** in `docs/features/ade-cloud/README.md` before you
touch `gravity.ts`, `gravityAd.ts`, `adPrice.ts`, `adProof.ts`,
`sponsoredConsent.ts`, `sponsoredTurns.ts`, `sponsoredSmall.ts`,
`sponsoredReport.ts` or `freeModelsMeter.ts` (all in
`apps/account-directory/src/cloud/`). In short: every proof and every Free
Models meter reset needs a card request behind it (a message only a few
times ahead of the last reply's proof, unless one just covered it), every
count an app can raise has a per-account daily bound on the server, and
every compare-then-write is one statement. In `/quality`, name the partner
request and the server-side daily bound behind each new proof or meter
reset.

## Every provider, both surfaces

Claude Code does not load this file, so `CLAUDE.md` has a copy of this
Expand Down
17 changes: 17 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,23 @@ phone.
`daex secrets exec --env CLOUD_OWNER_TOKEN`. It is instant and never
touches Stripe. Guide: `docs/features/ade-cloud/account-test-tool.md`.

## Ads invariants

Claude Code does not load `AGENTS.md`, so this is a copy of its **Ads
invariants** section. Keep the two the same.

Read **Ads invariants** in `docs/features/ade-cloud/README.md` before you
touch `gravity.ts`, `gravityAd.ts`, `adPrice.ts`, `adProof.ts`,
`sponsoredConsent.ts`, `sponsoredTurns.ts`, `sponsoredSmall.ts`,
`sponsoredReport.ts` or `freeModelsMeter.ts` (all in
`apps/account-directory/src/cloud/`). In short: every proof and every Free
Models meter reset needs a card request behind it (a message only a few
times ahead of the last reply's proof, unless one just covered it), every
count an app can raise has a per-account daily bound on the server, and
every compare-then-write is one statement. In `/quality`, name the partner
request and the server-side daily bound behind each new proof or meter
reset.

## Main checkout

Claude Code does not load `AGENTS.md`, so this is a copy of its **Main
Expand Down
284 changes: 244 additions & 40 deletions apps/account-directory/src/cloud/adPrice.ts

Large diffs are not rendered by default.

61 changes: 28 additions & 33 deletions apps/account-directory/src/cloud/adProof.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
import type { CloudWaitUntil } from "./analytics";
import { UNSAVED_CHAT_WINDOW_MS, adContextFor, adsOnHere, cloudNetworkOf, computerRatesMilli, countAdProof, noteCloudNetworkProof, noteUnverified, repeatOfCountedMessage } from "./adPrice";
import { UNSAVED_CHAT_WINDOW_MS, adContextFor, adsOnHere, cloudNetworkOf, computerRatesMilli, countAdProof, firstMessageRoomSql, messageTurnIds, noteCloudNetworkProof, noteUnverified, repeatOfCountedMessage } from "./adPrice";
import type { CloudAdProofAnswer } from "./contract";
import { blockedReason, freeModelAdGate, honorGpc, ownCloudComputer, ownLivePhone, type GravityEnv } from "./gravity";
import { ROW_ID, UNREADABLE_REQUEST_MESSAGE, badRequest, fail, json, knowsPricingV3, readJson, shortString } from "./http";
import { utcDay, type CloudSize, type V3Rate } from "./plans";
import type { CloudSize, V3Rate } from "./plans";
import { readCloudSettings } from "./settings";
import { readConsent, requestNetwork, sponsoredRequester } from "./sponsoredConsent";
import { adTerms, pricingV3Mode, pricingV3Reaches } from "./sponsoredSwitch";
import { loadAccount, reportCloudFailure, type AccountRow, type ComputerRow } from "./store";

// Pricing v3's proof from a person's message (`adPrice.ts` has the price):
// `POST /cloud/sponsored/sent`, and a message that wakes a computer at 0
// credits (`routes.ts`). A proof is the app's word: the server never sees a
// cloud chat's messages. What bounds it: one proof per (account, chat,
// message); only the account's own computer or live phone; nothing from the
// network of the account's own cloud computers; and a chat no computer saved
// yet holds the price with ads only briefly, a few times a day.
export { UNSAVED_CHAT_PROOFS_A_DAY } from "./adPrice";

/** How many proofs for chats with no saved copy one computer takes a UTC day (a phone: one session's 120 minutes). */
export const UNSAVED_CHAT_PROOFS_A_DAY = { computer: 6, phone: 12 } as const;
// Pricing v3's proof from a person's message (`adPrice.ts` has the price):
// `POST /cloud/sponsored/sent`, a message that wakes a computer at 0
// credits (`routes.ts`), and a new computer's first message. A proof is the
// app's word: the server never sees a cloud chat's messages. What bounds it:
// one proof per (account, chat, message); only the account's own computer or
// live phone; nothing from the network of the account's own cloud computers;
// a chat no computer saved yet holds the price with ads only briefly, a few
// times a day; and a card request behind it (`countAdProof`): a message soon
// after a counted proof there is covered, and one that opens a window counts
// only a few times ahead of the account's last reply proof, which is a card
// request. All under `PROOFS_A_DAY`.

const notFound = () => fail("not_found", "That DAEX Cloud route doesn't exist.", 404);

Expand Down Expand Up @@ -49,14 +52,6 @@ async function chatPlace(env: GravityEnv, userId: string, chatId: string, instan
return copies.here && !copies.child ? "here" : "elsewhere";
}

/** Proofs for unsaved chats one computer or phone took today (`turn_id` `new:<message>`). */
async function unsavedProofsToday(env: GravityEnv, userId: string, column: "instance_id" | "phone_id", id: string, now: number): Promise<number> {
const dayStart = Date.parse(`${utcDay(now)}T00:00:00Z`);
const row = await env.DB.prepare(`select count(*) as n from cloud_ad_proofs where user_id = ? and ${column} = ? and turn_id like 'new:%' and at >= ?`)
.bind(userId, id, dayStart).first<{ n: number }>();
return row?.n ?? 0;
}

/**
* One person's message as a proof for the computer its chat runs on and the
* live phone it holds. Ads must hold here (`adsOnHere`: a yes with the notice
Expand Down Expand Up @@ -101,17 +96,13 @@ async function proveSent(
const saved = instanceId ? place === "here" : (await chatPlace(env, userId, input.chatId, null)) === "here";
// A repeat (a second device, or a retry of a request cut short): its window set back if the cut lost it.
if (await repeatOfCountedMessage(env, account, input.messageId, freeModel, now)) return refused("repeat");
if (saved) return countAdProof(env, account, { chatId: input.chatId, turnId: `msg:${input.messageId}`, kind: "sent", freeModel, ...targets }, now);
// Each target has its own day's cap: a chat on a computer that holds the phone still counts for the phone once the computer's are used.
const capped = {
instanceId: instanceId && (await unsavedProofsToday(env, userId, "instance_id", instanceId, now)) < UNSAVED_CHAT_PROOFS_A_DAY.computer ? instanceId : null,
phoneId: phoneId && (await unsavedProofsToday(env, userId, "phone_id", phoneId, now)) < UNSAVED_CHAT_PROOFS_A_DAY.phone ? phoneId : null,
};
if (!capped.instanceId && !capped.phoneId) return refused("not_cloud");
// Kept as a proof whose window ends in a few minutes (never past the whole window's).
if (saved) return countAdProof(env, account, { chatId: input.chatId, turnId: `msg:${input.messageId}`, kind: "sent", freeModel, messageId: input.messageId, message: { unsaved: false }, ...targets }, now);
// A chat no computer saved yet: a proof whose window ends in a few minutes (never past the whole window's),
// a few a day on each target (`UNSAVED_CHAT_PROOFS_A_DAY`), a chat on a computer that holds the phone
// still counting for the phone once the computer's are used.
const windowMs = adTerms(await readCloudSettings(env)).windowMinutes * 60_000;
const targetAt = Math.min(now, now - windowMs + UNSAVED_CHAT_WINDOW_MS);
return countAdProof(env, account, { chatId: input.chatId, turnId: `new:${input.messageId}`, kind: "sent", freeModel, targetAt, ...capped }, now);
return countAdProof(env, account, { chatId: input.chatId, turnId: `new:${input.messageId}`, kind: "sent", freeModel, targetAt, messageId: input.messageId, message: { unsaved: true }, ...targets }, now);
}

/**
Expand All @@ -133,12 +124,12 @@ export async function handleSent(request: Request, env: GravityEnv, userId: stri

/**
* One message counts once, whatever chat id it came under: a chat saved after
* it came (`new:` then `msg:`), or a new lane's first message, counted at its
* it came (`new:` then `msg:`), covered or not (`cov:`), or a new lane's first message, counted at its
* launch under the launch id, then sent again by the app under its chat's.
*/
async function messageCounted(env: GravityEnv, userId: string, messageId: string): Promise<boolean> {
const hit = await env.DB.prepare("select 1 as hit from cloud_ad_proofs where user_id = ? and turn_id in (?, ?) limit 1")
.bind(userId, `msg:${messageId}`, `new:${messageId}`).first<{ hit: number }>();
const hit = await env.DB.prepare("select 1 as hit from cloud_ad_proofs where user_id = ? and turn_id in (?, ?, ?) limit 1")
.bind(userId, ...messageTurnIds(messageId)).first<{ hit: number }>();
return hit != null;
}

Expand All @@ -150,8 +141,10 @@ export type FirstMessageProof = { request: Request; chatId: string; messageId: s
* person's first message: a launch's, or an app's create with `adProof`) will
* count for it: it runs at the ad rate from its first minute. Null when it won't (Pricing v3 or ads not
* reaching the account, ads off, no ads here, the network of the account's own
* computers, a message already counted), so the create checks hours at the
* full rate as before. Never fails the create.
* computers, a message already counted, no room for another window-opening
* message or the day's proofs used, `firstMessageRoomSql`), so the create checks
* hours at the full rate as before. The reservation checks that room again in
* its own write. Never fails the create.
*/
export async function firstMessageRate(env: GravityEnv, account: AccountRow, size: CloudSize, proof: FirstMessageProof, now: number, waitUntil?: CloudWaitUntil): Promise<V3Rate | null> {
try {
Expand All @@ -164,6 +157,8 @@ export async function firstMessageRate(env: GravityEnv, account: AccountRow, siz
const consent = await honorGpc(env, account, await readConsent(env, account.user_id), who, now);
if (!adsOnHere(env, consent, account, who, knowsPricingV3(proof.request), now)) return null;
if (await messageCounted(env, account.user_id, proof.messageId)) return null;
const room = firstMessageRoomSql(account.user_id, now);
if (!(await env.DB.prepare(`select (${room.sql}) as ok`).bind(...room.binds).first<{ ok: number }>())?.ok) return null;
const asn = requestNetwork(proof.request);
const network = await cloudNetworkOf(env, account.user_id, asn, now);
if (network === "own") {
Expand Down
13 changes: 7 additions & 6 deletions apps/account-directory/src/cloud/freeModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const DEFAULT_INFERENCE_BASE = "https://inference.trygravity.ai/v1";
const MAX_REQUEST_BYTES = 8 * 1024 * 1024;
/** Gravity's output limit per call. */
const MAX_OUTPUT_TOKENS = 65_536;
/** Calls one account may make a UTC day: under Gravity's 3,000 for one person. */
/** Calls one account may make a UTC day: under the partner's limit for one person. */
const ACCOUNT_DAILY_REQUESTS = 2_900;
/** A person "has the chat open" when a device of theirs said so this recently. */
const VIEWER_FRESH_MS = 10 * 60_000;
Expand Down Expand Up @@ -347,10 +347,11 @@ async function handleChat(request: Request, env: GravityEnv, userId: string, now
void keep(markThrottle(env, userId, throttle, now).then((first) => (first ? countStatement(env, utcDay(now), ALL, `fm_${throttle}`).run() : null)));
if (throttle === "paused") {
// The refused reply still asks for its ad, and that request is what lifts the pause: the chat must
// read as one these models serve (`freeModelAdGate`), a new chat's first reply included.
// read as one these models serve today (`freeModelAdGate`), a new chat's first reply included, and
// an old one whose last call was more than a day ago too.
await env.DB.prepare(`
insert into cloud_free_model_chats (user_id, chat_id, first_at, last_at, requests) values (?, ?, ?, ?, 0)
on conflict (user_id, chat_id) do nothing
on conflict (user_id, chat_id) do update set last_at = max(last_at, excluded.last_at)
`).bind(userId, chatId, now, now).run();
return refuse("free_models_no_cards");
}
Expand Down Expand Up @@ -445,8 +446,8 @@ function untilNextMinute(refusal: Response, now: number): Response {
return new Response(refusal.body, { status: 429, headers });
}

/** A chat's id, never a launch's stand-in record (`launch:<id>`). */
const isChatId = (chatId: string): boolean => ROW_ID.test(chatId) && !chatId.startsWith(LAUNCH_VIEWER_PREFIX);
/** A chat's id, never a launch's stand-in record (`launch:<id>`, in any case: SQLite's `like` ignores it). */
const isChatId = (chatId: string): boolean => ROW_ID.test(chatId) && !chatId.toLowerCase().startsWith(LAUNCH_VIEWER_PREFIX);

/** The stand-in record a person's ADE Cloud launch leaves until its chat reports itself. */
const LAUNCH_VIEWER_PREFIX = "launch:";
Expand Down Expand Up @@ -494,7 +495,7 @@ export async function noteFreeModelLaunch(env: GravityEnv, userId: string, reque
*/
async function claimLaunchViewer(env: GravityEnv, userId: string, chatId: string, now: number): Promise<boolean> {
const launch = await env.DB.prepare(`
select chat_id from cloud_free_model_viewers where user_id = ? and chat_id like 'launch:%' and seen_at >= ? order by seen_at desc limit 1
select chat_id from cloud_free_model_viewers where user_id = ? and chat_id glob 'launch:*' and seen_at >= ? order by seen_at desc limit 1
`).bind(userId, now - LAUNCH_CLAIM_MS).first<{ chat_id: string }>();
if (!launch) return false;
// From the claim on, the usual windows run: the chat's own reports keep it watched.
Expand Down
13 changes: 10 additions & 3 deletions apps/account-directory/src/cloud/freeModelsMeter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@ import type { CloudDb } from "./store";
// never per chat: a script can make up a new chat id for every call.
//
// The card event is a card request (`gravity.ts` `handleAd`) in a chat these
// models served, once per turn, whatever Gravity answers (a card, a test
// card, or none to show). A current app asks when the turn's message is sent,
// models served, with the turn's text, really made for the person: it went
// to Gravity (whatever Gravity answers, or if Gravity fails: the partner's
// failure is never the person's), or the day's limit alone refused it (the
// account's, or the ceiling on every account's). An ask with no text, one
// the rules refuse (the yes, the switch, a chat these models didn't serve),
// or a second request after an answered no card starts nothing; a turn the
// day's limit refused keeps that answer, so its repeats start nothing again.
// A request that failed may be asked again (each try a request under the
// day's limit). A current app asks when the turn's message is sent,
// so the meter starts over at the turn's start; an older one asks at the
// reply's end. ADE's apps ask only while the chat's card place is on screen
// in a window in front, so a person using them in the app resets the meter
Expand Down Expand Up @@ -75,7 +82,7 @@ export function meterTokensStatement(env: CloudDb, userId: string, inputTokens:
.bind(inputTokens, now, userId);
}

/** A card was asked for in a chat these models served: the meter starts over. */
/** A card request was made in a chat these models served (see above): the meter starts over. */
export async function resetFreeModelMeter(env: CloudDb, userId: string, now: number): Promise<void> {
await env.DB.prepare(`
update cloud_free_model_meters set calls = 0, input_tokens = 0, since_at = ?, slowed_at = null, paused_at = null, updated_at = ?
Expand Down
Loading
Loading