Public: anyone can read this; the crew can change it.

A run never falls back to the forge's own model credential: no grant to the repository or its owner, no run #2085

Parked opened this
Closed without merging

scout/forge:scout/1144-a-run-never-falls-back-to-the-forge-s-ow → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +250 −9
README.md +5
@@ -563,6 +563,11 @@ Subscriptions, sealed, and grants each to a repository (Settings → Crew) or
563563 an organization (its page), down to one crew member: a work plan pays for
564564 the work repositories and nothing else. Two on one grant take turns, and
565565 one the provider rests hands its runs to the other until the reset.
566 Only a grant pays for a run: a repository neither it nor its owner has a grant
567 for does not run, spends nothing, and says "This repository has no model
568 account". The forge admin's repositories hold a grant of the forge's own
569 credential, written when they are created (and by a migration for those that
570 existed).
566571 **Sandbox.** An agent's shell is held to a policy — the network is the forge
567572 and the package registry, writes stay in the clone, the forge's data and the
568573 operator's credentials are unreadable — by bubblewrap and socat on Linux
scripts/gate.ts +1
@@ -91,6 +91,7 @@ export const GATE: readonly string[] = [
9191 "test/crew-continues.test.ts",
9292 "test/crew-declines.test.ts",
9393 "test/crew-network.test.ts",
94 "test/crew-no-grant.test.ts",
9495 "test/crew-pause.test.ts",
9596 "test/crew-review.test.ts",
9697 "test/crew-review-budget.test.ts",
src/actions/apps.ts +7 −1
@@ -43,6 +43,7 @@ import {
4343 } from "../core/app_env.ts";
4444 import { addCrew, getAgentByName } from "../core/agents.ts";
4545 import { listAllAgents } from "./crew.ts";
46 import { hasGrant, PLATFORM } from "../core/subscriptions.ts";
4647 import { plan, planIssueBody, planningAvailable } from "../crew/plan.ts";
4748 import type { Issue } from "../core/issues.ts";
4849 import { getPull } from "../core/pulls.ts";
@@ -337,7 +338,12 @@ export async function newApp(
337338 // the repository, the app and production above have already started.
338339 if (!agent && input.pickAgent && description !== "") {
339340 const binary = process.env["FORGE_CLAUDE"] ?? "claude";
340 if (planningAvailable(binary)) {
341 // The planner runs on the forge's own credential: only where a grant
342 // of it reaches the repository.
343 if (
344 planningAvailable(binary) &&
345 hasGrant(app.db, repo.value.id, repo.value.ownerId, { only: PLATFORM })
346 ) {
341347 const roster = listAllAgents(app, user.value);
342348 const agents = roster.ok ? roster.value : [];
343349 if (agents.length > 0) {
src/core/migrations/20261016150000-only-a-grant-pays.ts added +12
@@ -0,0 +1,12 @@
1 // Only a grant pays for a run (#1144). The runner used to fall back to the
2 // forge's own model credential (the row `platform`) when no grant reached a
3 // repository; it no longer does. So that nothing changes for the owner, each
4 // repository the forge admin owns today gets the explicit grant the fallback
5 // used to imply.
6 export default `
7 INSERT OR IGNORE INTO subscription_grant (scope_id, agent_id, subscription_id)
8 SELECT r.id, '', 'platform' FROM repo r JOIN user u ON u.id = r.owner_id
9 WHERE u.is_admin = 1
10 AND NOT EXISTS (SELECT 1 FROM subscription_grant g WHERE g.scope_id = r.id)
11 AND NOT EXISTS (SELECT 1 FROM subscription_grant g WHERE g.scope_id = r.owner_id);
12 `;
src/core/repos.ts +8
@@ -347,6 +347,14 @@ export async function createRepo(
347347 branch,
348348 ),
349349 );
350 // The forge admin's own repositories run on the forge's own model
351 // credential, by a grant written down here (the migration that ended the
352 // silent fallback did the same for those that already existed). Nobody
353 // else's repository is granted anything.
354 db.query(
355 `INSERT OR IGNORE INTO subscription_grant (scope_id, agent_id, subscription_id)
356 SELECT ?1, '', 'platform' FROM user WHERE id = ?2 AND is_admin = 1`,
357 ).run(repoId, input.ownerId);
350358 return ok(getRepoById(db, repoId)!);
351359 }
352360
src/core/subscriptions.ts +33 −4
@@ -541,8 +541,10 @@ function listGrantPlaceRows(
541541 // ---- the pick ----
542542
543543 export type Pick =
544 /** No grant reaches this run: the forge's own token, `PLATFORM`, from its environment. */
544 /** The forge's own token, `PLATFORM`, from its environment: only where a grant names it. */
545545 | { readonly kind: "env" }
546 /** No grant to the repository or its owner: the run does not start. */
547 | { readonly kind: "none" }
546548 | {
547549 readonly kind: "ready";
548550 readonly subscription: Subscription;
@@ -596,16 +598,20 @@ export function pickSubscription(
596598 s.resting_said, s.last_used_at, s.created_by, s.created_at, s.budget_usd,
597599 ${COMMITTED} AS spent_usd
598600 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
599 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '') AND s.id <> 'platform'
601 WHERE g.scope_id IN (?1, ?2) AND g.agent_id IN (?3, '')
600602 ORDER BY (g.scope_id = ?1) DESC, (g.agent_id = ?3) DESC,
601603 s.last_used_at IS NOT NULL, s.last_used_at, s.name COLLATE NOCASE`,
602604 )
603605 .all(scope.repoId, scope.ownerId, scope.agentId, reserve?.runId ?? "");
604606 const first = rows[0];
605 if (first === undefined) return { kind: "env" };
606 const grant = rows.filter(
607 // Only a grant pays for a run: with none, nothing does.
608 if (first === undefined) return { kind: "none" };
609 const nearest = rows.filter(
607610 (r) => r.scope_id === first.scope_id && r.agent_id === first.agent_id,
608611 );
612 const grant = nearest.filter((r) => r.id !== PLATFORM);
613 // A grant of the forge's own token, and of no sealed account beside it.
614 if (grant.length === 0) return { kind: "env" };
609615 // An account whose whole-life budget is spent is not offered again until
610616 // an admin raises it; looked at again within the hour, so a raise is felt.
611617 // Spent counts what other runs on it may still spend (their reservation)
@@ -696,6 +702,29 @@ export function grantedAccounts(
696702 return (own.length > 0 ? own : rows).map((r) => ({ id: r.id, name: r.name }));
697703 }
698704
705 /**
706 * Whether a grant reaches this repository — its own or its owner's, for
707 * anyone on the crew or for `agentId` — and so whether a run may start on
708 * it at all. With `only`, whether the grant is of that account.
709 */
710 export function hasGrant(
711 db: Database,
712 repoId: string,
713 ownerId: string,
714 options: { agentId?: string; only?: string } = {},
715 ): boolean {
716 return (
717 db
718 .query<{ n: number }, [string, string, string, string]>(
719 `SELECT 1 AS n FROM subscription_grant
720 WHERE scope_id IN (?1, ?2) AND agent_id IN (?3, '')
721 AND (?4 = '' OR subscription_id = ?4) LIMIT 1`,
722 )
723 .get(repoId, ownerId, options.agentId ?? "", options.only ?? "") !==
724 null
725 );
726 }
727
699728 /**
700729 * Whether the crew has any model credential to run on: a sealed account,
701730 * or a token or signed-in Claude config in the forge's own environment —
src/crew/runner.ts +25 −2
@@ -27,6 +27,7 @@ import {
2727 getIssue,
2828 getIssueById,
2929 labelsForIssues,
30 addComment as addIssueComment,
3031 listComments,
3132 type Issue,
3233 } from "../core/issues.ts";
@@ -99,6 +100,7 @@ import { pauseReason } from "./pacing.ts";
99100 import {
100101 credentialEnvOf,
101102 hostOfApiBase,
103 hasGrant,
102104 pickSubscription,
103105 PLATFORM,
104106 restSubscription,
@@ -597,6 +599,9 @@ export interface Pause {
597599 readonly summary?: string | undefined;
598600 }
599601
602 /** What a run says when no grant reaches its repository. */
603 export const NO_ACCOUNT = "This repository has no model account";
604
600605 async function work(
601606 app: App,
602607 run: Run,
@@ -622,6 +627,20 @@ async function work(
622627 summary: "agents do not work on mirrored repositories yet",
623628 };
624629 const reason = run.reason as RunReason;
630 // Only a grant pays for a run: before a fork is made or a token minted,
631 // a repository nothing reaches ends here, having spent nothing.
632 if (!hasGrant(app.db, repo.id, repo.ownerId, { agentId: agent.user.id })) {
633 write("no grant to this repository or its owner: nothing to run on");
634 // Said once on the issue, not at every retry.
635 const said = listComments(app.db, issue.id).at(-1);
636 if (said === undefined || said.body !== NO_ACCOUNT)
637 addIssueComment(app.db, {
638 issueId: issue.id,
639 authorId: agent.user.id,
640 body: NO_ACCOUNT,
641 });
642 return { state: "failed", summary: NO_ACCOUNT };
643 }
625644
626645 const pull =
627646 issue.kind === "pull" ? getPull(app.db, repo.id, issue.number) : undefined;
@@ -900,6 +919,10 @@ async function work(
900919 new Date(),
901920 { runId: run.id, usd: ownBudget },
902921 );
922 if (picked.kind === "none") {
923 write("no grant to this repository or its owner: nothing to run on");
924 return { state: "failed", summary: NO_ACCOUNT };
925 }
903926 if (picked.kind === "resting") {
904927 const names = picked.names.join(", ");
905928 write(
@@ -1766,8 +1789,8 @@ function redactResult<T extends { result: string }>(r: T): T {
17661789 /**
17671790 * The credential a run's environment carries: the picked account's token
17681791 * under the variable Claude Code reads it from (plus a gateway base URL when
1769 * the account has one), or — with nothing granted — whatever the forge
1770 * itself was started with.
1792 * the account has one), or — where a grant names the forge's own token —
1793 * whatever the forge itself was started with.
17711794 */
17721795 function credentialEnv(picked: Pick): Record<string, string> {
17731796 if (picked.kind === "ready") return credentialEnvOf(picked);
test/crew-no-grant.test.ts added +156
@@ -0,0 +1,156 @@
1 /**
2 * Only a grant pays for a run (#1144): a repository nothing reaches does not
3 * fall back to the forge's own model credential. The run ends without
4 * starting, says so on its page and its issue, and the ledger shows no spend.
5 * The forge admin's repositories keep the grant the fallback used to imply.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { assignIssue, openIssue } from "../src/actions/issues.ts";
14 import { createRepo } from "../src/actions/repos.ts";
15 import { listComments } from "../src/core/issues.ts";
16 import { getRun, createRun } from "../src/core/runs.ts";
17 import { getUsage, usageTotals } from "../src/core/usage.ts";
18 import { PLATFORM, pickSubscription, setGrants } from "../src/core/subscriptions.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { readRunLog } from "../src/runs/log.ts";
21 import { executeAgentRun, NO_ACCOUNT } from "../src/crew/runner.ts";
22 import type { Repo } from "../src/core/repos.ts";
23
24 describe("a run never falls back to the forge's own credential", () => {
25 let dataDir: string;
26 let app: App;
27 let admin: User;
28 let outsider: User;
29 let bot: User;
30
31 const options = () => ({
32 forgeUrl: "http://127.0.0.1:1",
33 localUrl: "http://127.0.0.1:1",
34 binary: join(dataDir, "no-such-claude-binary"),
35 concurrency: 1,
36 budgetUsd: 1,
37 runTimeoutMs: 20_000,
38 });
39
40 const assigned = async (owner: User, repo: Repo) => {
41 expect(addToCrew(app, owner, repo, "bot").ok).toBe(true);
42 const issue = openIssue(app, owner, repo, { title: "Plant", body: "" });
43 if (!issue.ok) throw new Error(String(issue.error));
44 expect(assignIssue(app, owner, repo, issue.value, bot).ok).toBe(true);
45 const run = createRun(app.db, {
46 repoId: repo.id,
47 kind: "agent",
48 issueId: issue.value.id,
49 actorId: bot.id,
50 reason: "assigned",
51 });
52 await executeAgentRun(app, run, options());
53 return { run: getRun(app.db, run.id)!, issue: issue.value };
54 };
55
56 beforeAll(async () => {
57 dataDir = await mkdtemp(join(tmpdir(), "forge-nogrant-"));
58 app = createApp({ dataDir, port: 0 });
59 const a = await createUser(app.db, {
60 trusted: true,
61 username: "alice",
62 email: "[email protected]",
63 password: "a-good-passphrase",
64 adminIfFirst: true,
65 });
66 const o = await createUser(app.db, {
67 trusted: true,
68 username: "olive",
69 email: "[email protected]",
70 password: "a-good-passphrase",
71 });
72 if (!a.ok || !o.ok) throw new Error("users");
73 admin = a.value;
74 outsider = o.value;
75 const made = await createAgent(app, admin, { username: "bot" });
76 if (!made.ok) throw new Error(String(made.error));
77 bot = made.value.user;
78 });
79
80 afterAll(async () => {
81 app.close();
82 await rm(dataDir, { recursive: true, force: true });
83 });
84
85 test("an outsider's repository: no run, no spend, said on the run and the issue", async () => {
86 const created = await createRepo(app, outsider, {
87 name: "yard",
88 visibility: "private",
89 });
90 if (!created.ok) throw new Error(String(created.error));
91 const { run, issue } = await assigned(outsider, created.value);
92 expect(run.state).toBe("failed");
93 expect(run.summary).toBe(NO_ACCOUNT);
94 expect(readRunLog(dataDir, run.id, 4096).lines.join("\n")).toContain(
95 "nothing to run on",
96 );
97 expect(
98 listComments(app.db, issue.id).filter((c) => c.body === NO_ACCOUNT),
99 ).toHaveLength(1);
100 expect(getUsage(app.db, run.id)?.costUsd ?? 0).toBe(0);
101 const spent = usageTotals(app.db, "repo", {
102 since: "1970-01-01T00:00:00Z",
103 repoId: created.value.id,
104 });
105 expect(spent.reduce((n, t) => n + t.costUsd, 0)).toBe(0);
106 expect(
107 pickSubscription(
108 app.db,
109 dataDir,
110 { repoId: created.value.id, ownerId: outsider.id, agentId: bot.id },
111 new Date(),
112 ),
113 ).toEqual({ kind: "none" });
114 });
115
116 test("the admin's repository holds an explicit grant and starts", async () => {
117 const created = await createRepo(app, admin, {
118 name: "garden",
119 visibility: "private",
120 });
121 if (!created.ok) throw new Error(String(created.error));
122 expect(
123 pickSubscription(
124 app.db,
125 dataDir,
126 { repoId: created.value.id, ownerId: admin.id, agentId: bot.id },
127 new Date(),
128 ),
129 ).toEqual({ kind: "env" });
130 const { run } = await assigned(admin, created.value);
131 // It got past the grant (this one then fails on the missing binary).
132 expect(run.summary).not.toBe(NO_ACCOUNT);
133 expect(readRunLog(dataDir, run.id, 4096).lines.join("\n")).not.toContain(
134 "nothing to run on",
135 );
136 });
137
138 test("the migration grants the forge's own credential to the admin's existing repositories only", async () => {
139 const mine = await createRepo(app, admin, { name: "old", visibility: "private" });
140 const theirs = await createRepo(app, outsider, { name: "other", visibility: "private" });
141 if (!mine.ok || !theirs.ok) throw new Error("repos");
142 app.db.query("DELETE FROM subscription_grant").run();
143 const sql = (await import("../src/core/schema.ts")).migrations.at(-1)!;
144 app.db.exec(sql);
145 const granted = app.db
146 .query<{ scope_id: string }, []>(
147 "SELECT scope_id FROM subscription_grant WHERE subscription_id = 'platform'",
148 )
149 .all()
150 .map((r) => r.scope_id);
151 expect(granted).toContain(mine.value.id);
152 expect(granted).not.toContain(theirs.value.id);
153 // An owner's own wider grant is respected, not doubled.
154 setGrants(app.db, outsider.id, "", [PLATFORM]);
155 });
156 });
test/subscriptions.test.ts +3 −2
@@ -153,9 +153,10 @@ describe("the pool", () => {
153153 const scope = { repoId: "repo-1", ownerId: "org-1", agentId: "bot-1" };
154154 const now = new Date("2026-09-28T12:00:00Z");
155155
156 // Nothing granted anywhere: the forge's own token.
156 // Nothing granted anywhere: no run. The forge's own token is used only
157 // where a grant names it.
157158 expect(pickSubscription(app.db, dataDir, scope, now)).toEqual({
158 kind: "env",
159 kind: "none",
159160 });
160161
161162 // The organization's grant reaches every repository under it.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs