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

The changelog credits a model only when a run backs it #17807

opened this

Merged 13h 28m ago, live in production

cf/model-credits → main 0 commits

  • Merged. cf/model-credits was merged into main as e780a4e.

Review

Sign in to review this change.
7 files changed +249 −6
docs/features/changelog.md +2
@@ -32,6 +32,8 @@ Titles are shown plain (`plainTitle` in `story/gather.ts`): a leading `small:` a
3232
3333 A squash keeps the people behind its commits: the landed message carries every distinct `Co-authored-by` its commits carried and each commit's author, except the crew's agents (`@agents.invalid`), once per address. `/changelog` then shows "With Jay Moran" on a row for everyone credited on the landed commit beyond whoever landed it (`creditsOf` in `git/coauthors.ts`, one git read, kept per commit); a landing with no one else shows nothing. Only the forge's own repository is read. A row also says who built it: "By Scout" is the author of the landed commit, "With Claude Sonnet 5.5" the names in its trailers (less the committer and the author), both as plain facts under the title, from the same one git read (`buildersOf`). At most the newest 80 landings of the forge's own repository are asked of git, and at most 500 commits are remembered, oldest dropped first. `GET /api/v1/changelog` carries `by` and `with` on a landing that has them. In the terminal, Enter on a release lists its pulls, and a pull the forge landed shows "by Scout, with Claude Sonnet 5.5" beside it.
3434
35 A model is named only where the forge has a run of it: the pull's author ran that model on the pull or on an issue it closes (`core/model_credits.ts`). That holds for every landing the page lists, old ones too. A model named in a person's pull is not shown, though its commit keeps the line. The commits themselves are checked from the release that first carries `core/model_credits.ts`, when a crew pull is squashed: a model that did not run loses its line, and one recorded by its full id (`claude-sonnet-5-5`) and not signed gets one. A run recorded only as `sonnet` or `opus` keeps a matching line and adds none. A name is matched by its model, not its version. Commits from before carry whatever the agent wrote, many of them "Claude Fable 5" where another model ran. `test/model-credits.test.ts`.
36
3537 ## For agents
3638
3739 `GET /api/v1/changelog` is the page's list as JSON, public, cached five seconds: `{version, commit, live, onItsWay}`, each landing `{repo, number, title, at, live[, with]}`. `?repo=all` or `?repo=owner/name` filters; the default is the forge's own repository, as on the page. MCP `releases` with `{shipped: true, repo?}` and `GET /api/v1/releases?shipped=true[&repo=]` answer the same rows with the same default. Only public repositories are read; concurrent requests share one read of git and the merged rows, so an anonymous caller costs no more than a page view. The page links the JSON with `rel="alternate"`. The terminal's Changelog screen is the release-commit view (`release/changelog.ts`), told in chapters when there are any (see Chapters), and it reads by wave on `w`.
src/actions/pulls.ts +8 −1
@@ -84,6 +84,7 @@ import { commitIdentity } from "../core/commit_identity.ts";
8484 import { getUserById, getUserByName, type User } from "../core/users.ts";
8585 import { personActing } from "../core/acting_via.ts";
8686 import { squashCredits } from "../git/coauthors.ts";
87 import { creditModels, modelsOfPulls } from "../core/model_credits.ts";
8788 import { resolveOid, type MergeStrategy } from "../git/merge.ts";
8889 import { bareTitle, fromKeptFork, landingKind } from "../core/landing_kind.ts";
8990 import { thankAuthor } from "../origins/thanks.ts";
@@ -594,7 +595,7 @@ export async function mergePull(
594595 const at = await pullDir(app.db, app.reposRoot, repo, pull);
595596 // A squash folds the pull's commits into one: the people they credit as
596597 // `Co-authored-by` stay credited on the commit that lands.
597 const kept =
598 const folded =
598599 strategy === "squash"
599600 ? await squashCredits(
600601 at,
@@ -603,6 +604,12 @@ export async function mergePull(
603604 [lander.email, ...(requester ? [commitIdentity(app.config, requester).email] : [])],
604605 )
605606 : [];
607 // A crew pull's models are the run table's to say, not its commits' (`core/model_credits.ts`); a person's
608 // pull keeps the lines they wrote.
609 const kept =
610 strategy === "squash" && writtenBy?.kind === "agent"
611 ? creditModels(folded, modelsOfPulls(app.db, repo.id, [pull.number]).get(pull.number) ?? new Set())
612 : folded;
606613 const trailers = [
607614 landingTrailers(
608615 requester ? commitIdentity(app.config, requester) : null,
src/core/model_credits.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Which models a pull may be credited to: those its author's own runs worked on it with, from the run
3 * table, never from a line an agent wrote. Agents signed `Co-authored-by: Claude Fable 5` because a
4 * rule told every one of them to, and the changelog showed a model nothing had run on.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { isModelLine } from "../git/coauthors.ts";
9 import { closesFromBody } from "./pulls.ts";
10
11 /** A model's own words: `claude-sonnet-5-5`, `sonnet` and "Claude Sonnet 5.5" are all `sonnet`. */
12 const wordsOf = (model: string): string[] => (model.toLowerCase().match(/[a-z]+/g) ?? []).filter((w) => w !== "claude");
13
14 /**
15 * The models each pull's author ran on it, by pull number: the runs on the pull itself and on the
16 * issues it closes, reviews left out. A pull a person wrote has none.
17 */
18 export function modelsOfPulls(db: Database, repoId: string, numbers: readonly number[]): Map<number, ReadonlySet<string>> {
19 const pulls = db
20 .query<{ id: string; number: number; author: string; body: string }, [string, string]>(
21 "SELECT id, number, author_id AS author, body FROM issue WHERE repo_id = ?1 AND kind = 'pull' AND number IN (SELECT value FROM json_each(?2))",
22 )
23 .all(repoId, JSON.stringify(numbers));
24 const closes = new Map(pulls.map((p) => [p.number, closesFromBody(p.body)]));
25 const ids = new Map(
26 db
27 .query<{ id: string; number: number }, [string, string]>("SELECT id, number FROM issue WHERE repo_id = ?1 AND number IN (SELECT value FROM json_each(?2))")
28 .all(repoId, JSON.stringify([...closes.values()].flat()))
29 .map((i) => [i.number, i.id]),
30 );
31 const about = new Map(pulls.map((p) => [p.number, [p.id, ...closes.get(p.number)!.flatMap((n) => ids.get(n) ?? [])]]));
32 const runs = db
33 .query<{ issue: string; actor: string | null; model: string }, [string]>(
34 "SELECT DISTINCT issue_id AS issue, actor_id AS actor, model FROM run WHERE issue_id IN (SELECT value FROM json_each(?1)) AND kind = 'agent' AND reason <> 'review' AND model <> ''",
35 )
36 .all(JSON.stringify([...about.values()].flat()));
37 return new Map(pulls.map((p) => [p.number, new Set(runs.filter((r) => r.actor === p.author && about.get(p.number)!.includes(r.issue)).map((r) => r.model))]));
38 }
39
40 /** Whether a model's name in a credit is one that ran: the same model by name, whatever version is written. */
41 export function ranAs(name: string, ran: ReadonlySet<string>): boolean {
42 const named = wordsOf(name);
43 return named.length === 0 ? ran.size > 0 : [...ran].some((m) => wordsOf(m).some((w) => named.includes(w)));
44 }
45
46 /**
47 * `claude-sonnet-5-5` as a credit line writes it. Undefined for any other maker's model, and for a bare
48 * `sonnet` or `opus`: a gateway may have answered for that word with a model of its own.
49 */
50 function lineFor(model: string): string | undefined {
51 const m = /^claude-(fable|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(model);
52 if (m === null) return undefined;
53 const family = m[1]!.charAt(0).toUpperCase() + m[1]!.slice(1).toLowerCase();
54 return `Co-authored-by: Claude ${family} ${m[2]!}${m[3] === undefined ? "" : `.${m[3]}`} <[email protected]>`;
55 }
56
57 /**
58 * The credit lines a crew pull lands with: people as they were, a model only where it ran, and one that
59 * ran by its full id and was not signed added.
60 */
61 export function creditModels(lines: readonly string[], ran: ReadonlySet<string>): string[] {
62 const nameIn = (line: string): string => /^Co-authored-by: (.*) <[^<>]*>$/.exec(line)?.[1] ?? "";
63 const kept = lines.filter((l) => !isModelLine(l) || ranAs(nameIn(l), ran));
64 const signed = kept.filter(isModelLine).map(nameIn);
65 for (const model of ran) {
66 const line = lineFor(model);
67 if (line === undefined || signed.some((n) => ranAs(n, new Set([model])))) continue;
68 signed.push(nameIn(line));
69 kept.push(line);
70 }
71 return kept;
72 }
src/git/coauthors.ts +10 −2
@@ -7,6 +7,9 @@
77 import { runGitCapture, runGitRaw } from "./env.ts";
88 import { isSafeOid } from "./guard.ts";
99
10 /** Whether a credit line (as `coAuthorLines` writes one) names a model: a model maker's address, or a Claude model's name. */
11 export const isModelLine = (line: string): boolean => /<noreply@(?:anthropic|openai)\.com>$/i.test(line) || /^Co-authored-by: Claude (?:Fable|Opus|Sonnet|Haiku)\b/i.test(line);
12
1013 /** At most this many co-authors ride a landing. */
1114 export const COAUTHORS_MAX = 20;
1215
@@ -61,6 +64,8 @@ export async function messagesBetween(dir: string, base: string, head: string):
6164 export interface Builders {
6265 readonly by: string;
6366 readonly with: readonly string[];
67 /** Those of `with` that name a model, when any do: what the commit says, not what ran (`core/model_credits.ts`). */
68 readonly models?: readonly string[];
6469 }
6570
6671 /** What a landed commit says of who made it, per commit; a commit never changes, so it is asked once. */
@@ -136,11 +141,14 @@ export async function buildersOf(dir: string, oids: readonly string[]): Promise<
136141 }
137142 for (const [oid, commit] of await readCommits(dir, todo)) {
138143 const names: string[] = [];
144 const models: string[] = [];
139145 for (const line of coAuthorLines([commit.message], [commit.committerEmail])) {
140146 const name = /^Co-authored-by: (.*) <[^<>]*>$/.exec(line)?.[1];
141 if (name !== undefined && name.toLowerCase() !== commit.author.toLowerCase()) names.push(name);
147 if (name === undefined || name.toLowerCase() === commit.author.toLowerCase()) continue;
148 names.push(name);
149 if (isModelLine(line)) models.push(name);
142150 }
143 const builders = { by: commit.author, with: names };
151 const builders: Builders = { by: commit.author, with: names, ...(models.length === 0 ? {} : { models }) };
144152 remember(`${dir}\0${oid}`, builders);
145153 out.set(oid, builders);
146154 }
src/release/landings.ts +5 −1
@@ -14,6 +14,7 @@
1414
1515 import type { Database } from "bun:sqlite";
1616 import type { App } from "../app.ts";
17 import { modelsOfPulls, ranAs } from "../core/model_credits.ts";
1718 import { getRepo, type Repo } from "../core/repos.ts";
1819 import { buildersOf, type Builders } from "../git/coauthors.ts";
1920 import { runGit } from "../git/env.ts";
@@ -415,10 +416,13 @@ async function buildersOfRepo(app: App, own: string, rows: readonly MergedRow[])
415416 if (repo === undefined) return new Map();
416417 const mine = rows.filter((r) => r.repo.toLowerCase() === own.toLowerCase() && r.oid !== "").slice(0, ASKED);
417418 const byOid = await buildersOf(repoDir(app.reposRoot, repo.ownerName, repo.name), mine.map((r) => r.oid));
419 // A model is named only where its run is on record; the commit's word for it is not enough.
420 const signed = mine.filter((r) => byOid.get(r.oid)?.models !== undefined).map((r) => r.number);
421 const ran = signed.length === 0 ? new Map<number, ReadonlySet<string>>() : modelsOfPulls(app.db, repo.id, signed);
418422 const out = new Map<string, Builders>();
419423 for (const r of mine) {
420424 const b = byOid.get(r.oid);
421 if (b !== undefined) out.set(`${r.repo}#${r.number}`, b);
425 if (b !== undefined) out.set(`${r.repo}#${r.number}`, { by: b.by, with: b.with.filter((n) => b.models?.includes(n) !== true || ranAs(n, ran.get(r.number) ?? new Set())) });
422426 }
423427 return out;
424428 }
test/coauthors.test.ts +2 −2
@@ -72,7 +72,7 @@ describe("buildersOf", () => {
7272 git(["commit", "-q", "--allow-empty", "-m", "bare"]);
7373 const bare = git(["rev-parse", "HEAD"]);
7474 const got = await buildersOf(dir, [oid, bare]);
75 expect(got.get(oid)).toEqual({ by: "Scout", with: ["Claude Sonnet 5.5"] });
75 expect(got.get(oid)).toEqual({ by: "Scout", with: ["Claude Sonnet 5.5"], models: ["Claude Sonnet 5.5"] });
7676 expect(got.get(bare)).toEqual({ by: "Scout", with: [] });
7777 } finally {
7878 await rm(dir, { recursive: true, force: true });
@@ -89,7 +89,7 @@ describe("buildersOf bounds", () => {
8989 git(["init", "-q", "-b", "main"]);
9090 git(["commit", "-q", "--allow-empty", "-m", "named\n\nCo-authored-by: SCOUT <[email protected]>\nCo-authored-by: Claude <[email protected]>"]);
9191 const first = git(["rev-parse", "HEAD"]);
92 expect((await buildersOf(dir, [first])).get(first)).toEqual({ by: "Scout", with: ["Claude"] });
92 expect((await buildersOf(dir, [first])).get(first)).toEqual({ by: "Scout", with: ["Claude"], models: ["Claude"] });
9393 const oids = [first];
9494 for (let i = 0; i < CREDITED_MAX + 5; i++) {
9595 git(["commit", "-q", "--allow-empty", "-m", `c${i}`]);
test/model-credits.test.ts added +150
@@ -0,0 +1,150 @@
1 /**
2 * A model is credited where it ran, not where a line says so: the squash of a crew pull and the
3 * changelog both ask the run table (`core/model_credits.ts`).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { addToCrew, createAgent } from "../src/actions/crew.ts";
10 import { openIssue } from "../src/actions/issues.ts";
11 import { mergePull, openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { creditModels, modelsOfPulls, ranAs } from "../src/core/model_credits.ts";
15 import { getPull } from "../src/core/pulls.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import { createRun, noteRunProgress } from "../src/core/runs.ts";
18 import { createUser, getUserByName, type User } from "../src/core/users.ts";
19 import { runGitCapture } from "../src/git/env.ts";
20 import type { MergeStrategy } from "../src/git/merge.ts";
21 import { repoDir } from "../src/git/repos.ts";
22 import { forgetLive, readLandings } from "../src/release/landings.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const FABLE = "Co-authored-by: Claude Fable 5 <[email protected]>";
28 const JAY = "Co-authored-by: Jay Moran <[email protected]>";
29 let dir = "";
30 let app: App;
31 let alice: User;
32 let repo: Repo;
33 const COMMIT = process.env["FORGE_COMMIT"];
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "forge-model-credits-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
39 if (!a.ok) throw new Error(a.error);
40 alice = a.value;
41 const made = await createRepo(app, alice, { name: "page", visibility: "public" });
42 if (!made.ok) throw new Error(String(made.error));
43 repo = made.value;
44 const seeded = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "a.txt", content: "a\n" }] });
45 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
46 const scout = await createAgent(app, alice, { username: "scout" });
47 if (!scout.ok) throw new Error(String(scout.error));
48 addToCrew(app, alice, repo, "scout");
49 app.config.forgeRepo = "alice/page";
50 }, 30_000);
51 afterAll(async () => {
52 app.close();
53 await rm(dir, { recursive: true, force: true });
54 if (COMMIT === undefined) delete process.env["FORGE_COMMIT"];
55 else process.env["FORGE_COMMIT"] = COMMIT;
56 });
57
58 /** A finished agent run by `actorId` on an issue or a pull, on `model`. */
59 function ran(issueId: string, actorId: string, reason: string, model: string): void {
60 const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId, actorId, reason });
61 noteRunProgress(app.db, run.id, { model });
62 app.db.run("UPDATE run SET state = 'ok' WHERE id = ?1", [run.id]);
63 }
64 /** The issue or pull titled `title`. */
65 const titled = (title: string) => app.db.query<{ id: string; number: number }, [string, string]>("SELECT id, number FROM issue WHERE repo_id = ?1 AND title = ?2").get(repo.id, title)!;
66
67 /** A pull by `author` for an issue their runs used `models` on, its commit signed `signed`, landed (a squash unless said): the landed message. */
68 async function land(slug: string, author: string, models: readonly string[], signed: string, strategy: MergeStrategy = "squash"): Promise<string> {
69 const by = getUserByName(app.db, author)!;
70 const issue = openIssue(app, alice, repo, { title: `Want ${slug}`, body: "x" });
71 if (!issue.ok) throw new Error(String(issue.error));
72 for (const model of models) ran(issue.value.id, by.id, "assigned", model);
73 const branch = await commitToBranch(app, alice, repo, { branch: `feature/${slug}`, base: "main", message: `Add ${slug}\n\n${signed}`, files: [{ path: `${slug}.md`, content: `${slug}\n` }] });
74 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
75 const opened = await openPull(app, by, repo, { title: `Do ${slug}`, body: `Done.\n\nCloses #${String(issue.value.number)}`, baseBranch: "main", headBranch: `feature/${slug}` });
76 if (!opened.ok) throw new Error(String(opened.error));
77 const merged = await mergePull(app, alice, repo, getPull(app.db, repo.id, opened.value.number)!, strategy);
78 if (!merged.ok) throw new Error(String(merged.error));
79 return (await runGitCapture(["log", "-1", "--format=%B", "main"], { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) })).stdout;
80 }
81 async function shownWith(slug: string): Promise<readonly string[] | undefined> {
82 process.env["FORGE_COMMIT"] = (await runGitCapture(["rev-parse", "main"], { cwd: repoDir(app.reposRoot, repo.ownerName, repo.name) })).stdout.trim();
83 forgetLive(app.db);
84 const read = await readLandings(app);
85 return [...read.live, ...read.onItsWay].find((l) => l.title === `Do ${slug}`)!.with;
86 }
87
88 test("a crew pull signed as a model no run used lands without it, credits the one that ran by its full id, and keeps its people", async () => {
89 const body = await land("wrong", "scout", ["claude-sonnet-5-5"], `${FABLE}\n${JAY}`);
90 expect(body).not.toContain("Fable");
91 expect(body).toContain("Co-authored-by: Claude Sonnet 5.5 <[email protected]>");
92 expect(body).toContain(JAY);
93 expect(await shownWith("wrong")).toEqual(["Jay Moran", "Claude Sonnet 5.5"]);
94 });
95
96 test("a model that ran keeps the line as it was signed; with no model on record none is credited", async () => {
97 const signed = "Co-authored-by: Claude Opus 5.5 <[email protected]>";
98 expect(await land("right", "scout", ["claude-opus-5-5"], signed)).toContain(signed);
99 expect(await shownWith("right")).toEqual(["Claude Opus 5.5"]);
100 expect(await land("unknown", "scout", [], FABLE)).not.toContain("Claude");
101 expect(await shownWith("unknown")).toBeUndefined();
102 });
103
104 test("a person's pull keeps the lines they wrote, and the changelog shows no model the forge has no run of", async () => {
105 expect(await land("mine", "alice", [], `${FABLE}\n${JAY}`)).toContain(FABLE);
106 expect(await shownWith("mine")).toEqual(["Jay Moran"]);
107 });
108
109 test("a name is matched by its model, not its version, and other makers' models too", () => {
110 expect(ranAs("Claude Fable 5", new Set(["claude-fable-5-1"]))).toBe(true);
111 expect(ranAs("Claude Fable 5", new Set(["sonnet", "opus"]))).toBe(false);
112 expect(ranAs("Claude", new Set(["sonnet"]))).toBe(true);
113 expect(ranAs("Claude", new Set())).toBe(false);
114 expect(creditModels([], new Set(["claude-sonnet-5-5"]))).toEqual(["Co-authored-by: Claude Sonnet 5.5 <[email protected]>"]);
115 // A bare tier word may have been a gateway's own model: it backs a line, and adds none.
116 expect(creditModels([FABLE], new Set(["sonnet"]))).toEqual([]);
117 expect(creditModels([FABLE], new Set(["subq-savant-1.4"]))).toEqual([]);
118 });
119
120 test("a pull's models are its author's own runs, on the pull or the issue it closes, and not its reviews", async () => {
121 await land("rules", "scout", [], FABLE);
122 const pull = titled("Do rules");
123 const issue = titled("Want rules");
124 const scout = getUserByName(app.db, "scout")!;
125 const models = () => [...modelsOfPulls(app.db, repo.id, [pull.number]).get(pull.number)!];
126 ran(pull.id, scout.id, "review", "claude-opus-5-5");
127 expect(models()).toEqual([]);
128 ran(issue.id, alice.id, "assigned", "claude-haiku-5-5");
129 expect(models()).toEqual([]);
130 ran(pull.id, scout.id, "feedback", "claude-sonnet-5-5");
131 expect(models()).toEqual(["claude-sonnet-5-5"]);
132 });
133
134 test("a line at OpenAI's address is a model's: dropped with no run of it, kept with one", () => {
135 const signed = "Co-authored-by: GPT-5 <[email protected]>";
136 expect(creditModels([signed, JAY], new Set(["sonnet"]))).toEqual([JAY]);
137 expect(creditModels([signed, JAY], new Set(["gpt-5"]))).toEqual([signed, JAY]);
138 });
139
140 test("a crew pull not landed as a squash: the changelog still hides a model no run backs", async () => {
141 // A merge commit has the forge's own message, so the agent's lines stay on the commit it merged.
142 expect(await land("merged", "scout", [], `${FABLE}\n${JAY}`, "merge")).not.toContain("Fable");
143 expect(await shownWith("merged")).toBeUndefined();
144 // A kept fork's one commit can land as it is, its lines with it: the landed commit is then the signed one.
145 const pull = titled("Do merged");
146 app.db.run("UPDATE pull SET merged_oid = head_oid WHERE issue_id = ?1", [pull.id]);
147 expect(await shownWith("merged")).toEqual(["Jay Moran"]);
148 ran(pull.id, getUserByName(app.db, "scout")!.id, "feedback", "claude-fable-5-1");
149 expect(await shownWith("merged")).toEqual(["Claude Fable 5", "Jay Moran"]);
150 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs