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

A fork's header says in one word how it follows its parent (follow, propose, apart) and how far behind it is #12724

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/12683-a-fork-s-header-says-in-one-word-how-it → main 7 commits fork 7 threads · 7 unresolved

  • Merged. scout/12683-a-fork-s-header-says-in-one-word-how-it was merged into main as b389418.

Review

Sign in to review this change.
8 files changed +257 −12
docs/features/fork-tree.md +12
@@ -12,6 +12,18 @@ about is marked `*`, each generation is indented, and each fork says in one word
1212 `src/actions/follow_words.ts`, the same word the fork's family tree on the web says).
1313 A repository you may not read answers "not found", as everywhere else.
1414
15 ## A fork's header
16
17 Under the title of a fork the line "forked from alice/lib" ends in the same one word, `follows`, `proposes` or
18 `severed`, linked to the setting that changes it (`/owner/name/forks#following`), then how far behind it is:
19 "forked from alice/lib · proposes · 2 behind". It is on every tab of the repository, not only the code tab, and a
20 repository with no parent (or one whose parent you may not read) has no word. The count is the one the fork's
21 relation last read at these two tips (the code page, the Following card, the terminal and the MCP all read it);
22 when either branch has moved since, the header says no number rather than an old one, and never runs git to
23 find out. The code page still says the plain standing ("Sends offers to alice/lib · last took 2 hours ago")
24 where no behind line speaks. In the terminal the Forks screen's first line reads
25 `proposes · Sends offers to alice/lib · 1 behind`.
26
1527 ## MCP
1628
1729 ```json
src/core/following.ts +17 −1
@@ -39,7 +39,7 @@ import {
3939 } from "../git/merge.ts";
4040 import { runGit } from "../git/env.ts";
4141 import { describeLink, syncLink, type Reconcile } from "../git/sync_link.ts";
42 import { readTipOrAbsent } from "../git/tip.ts";
42 import { readTipOrAbsent, readTipSync } from "../git/tip.ts";
4343 import { readTips } from "../git/tips.ts";
4444 import { repoDir } from "../git/repos.ts";
4545 import { combine } from "../git/combined.ts";
@@ -247,6 +247,22 @@ export async function forkRelation(
247247 return at(...standing);
248248 }
249249
250 /**
251 * How far behind its parent the fork is, from what `forkRelation` last counted, without
252 * awaiting: the two tips from the ref files, then the cache keyed on them. Undefined when
253 * either side moved since the count or nothing has counted it yet, so a header that renders
254 * on every tab says no number rather than a stale one (#12683). Never asks git.
255 */
256 export function keptBehind(forge: Pick<Following, "reposRoot">, fork: Repo, parent: Repo): number | undefined {
257 const parentDir = repoDir(forge.reposRoot, parent.ownerName, parent.name);
258 const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name);
259 const parentTip = readTipSync(parentDir, `refs/heads/${parent.defaultBranch}`);
260 const forkTip = readTipSync(forkDir, `refs/heads/${fork.defaultBranch}`);
261 if (parentTip === undefined || forkTip === undefined) return undefined;
262 if (parentTip === forkTip) return 0;
263 return relationCache.get(`${forkDir}\0${parentDir}\0${forkTip}\0${parentTip}`)?.[1];
264 }
265
250266 /** Tips already asked for in one read, so a parent is read once for all its forks. */
251267 export type TipReads = Map<string, Promise<string | undefined>>;
252268
src/git/tip.ts +30
@@ -4,6 +4,7 @@
44 * ref, a missing file, a surprise) is `undefined`, and the caller asks git.
55 */
66
7 import { readFileSync, statSync } from "node:fs";
78 import { readFile, stat } from "node:fs/promises";
89 import { join } from "node:path";
910 import { isSafeOid, isSafeRef } from "./guard.ts";
@@ -47,6 +48,10 @@ async function packedHeads(dir: string): Promise<ReadonlyMap<string, string | un
4748 if (kept?.key === key) return kept.heads;
4849 const packed = await text(path);
4950 if (packed === undefined) return undefined;
51 return keepPacked(path, key, packed);
52 }
53
54 function keepPacked(path: string, key: string, packed: string): ReadonlyMap<string, string | undefined> {
5055 const heads = new Map<string, string | undefined>();
5156 for (const line of packed.split("\n")) {
5257 const [oid, name] = line.split(" ");
@@ -58,6 +63,31 @@ async function packedHeads(dir: string): Promise<ReadonlyMap<string, string | un
5863 return heads;
5964 }
6065
66 /**
67 * `readTip` for a synchronous render that only checks a remembered tip (a fork header's
68 * behind count, #12683): the loose ref file, else packed-refs through the same parse cache.
69 * Undefined for anything it cannot say, and the caller then says nothing; it never asks git.
70 */
71 export function readTipSync(dir: string, ref: string): string | undefined {
72 if (!isSafeRef(ref) || !ref.startsWith("refs/heads/")) return undefined;
73 try {
74 const loose = readFileSync(join(dir, ref), "utf8").trim();
75 return isSafeOid(loose) ? loose : undefined;
76 } catch {
77 // not loose: it may be packed
78 }
79 const path = join(dir, "packed-refs");
80 try {
81 const s = statSync(path);
82 const key = `${s.ino}.${s.mtimeMs}.${s.size}`;
83 const kept = packedOf.get(path);
84 const heads = kept?.key === key ? kept.heads : keepPacked(path, key, readFileSync(path, "utf8"));
85 return heads.get(ref);
86 } catch {
87 return undefined;
88 }
89 }
90
6191 export async function readTip(
6292 dir: string,
6393 ref: string,
src/tui/screens/forks.ts +7 −3
@@ -21,10 +21,9 @@ import {
2121 type ForkRanking,
2222 type ForkRelation,
2323 } from "../../actions/forks.ts";

Second import from follow_words.ts: merge with the existing import on the line below (clean).

24 import { followModeWords } from "../../actions/follow_words.ts";
24 import { FOLLOW_WORD, FOLLOWS_NOTHING, followModeWords, proposeRefusalWords } from "../../actions/follow_words.ts";
2525 import { FOLLOW_MODE_REFUSALS, convergeWords, followModeOf, followStanding, followModeSaid, setFollowMode, takeOrTell, takeWords } from "../../actions/follow.ts";
2626 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
27 import { FOLLOWS_NOTHING, proposeRefusalWords } from "../../actions/follow_words.ts";
2827 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
2928 import type { Pull } from "../../core/pulls.ts";
3029 import { convergeState, type Converge } from "../../crew/converge.ts";
@@ -306,7 +305,12 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
306305 style(c.mutedFg, c.bg),
307306 head!.x + head!.w,
308307 );
309 if (standing !== undefined) s.text(line!.x, line!.y, truncate(standing, line!.w), style(c.mutedFg, c.bg), line!.x + line!.w);
308 if (standing !== undefined) {
309 // The same word the web header says, then how far behind when the relation was read.
310 const word = mode === undefined ? "" : `${FOLLOW_WORD[mode]} · `;
311 const behind = relation === undefined ? "" : ` · ${relation.behind} behind`;
312 s.text(line!.x, line!.y, truncate(`${word}${standing}${behind}`, line!.w), style(c.mutedFg, c.bg), line!.x + line!.w);
313 }
310314 if (list.length === 0) {
311315 emptyState(s, body!, c, {
312316 title: ranked === undefined ? "Reading…" : "No forks yet",
src/web/chrome.ts +20 −4
@@ -20,9 +20,12 @@ import {
2020 import { nearRepos as nearTo } from "../core/near_repos.ts";
2121 import { type Repo } from "../core/repos.ts";
2222 import { parentUrl, shownTrail, sourceLabel } from "../core/provenance.ts";
23 import type { Database } from "bun:sqlite";
23 import type { App } from "../app.ts";
2424 import type { Ctx } from "../http/context.ts";
2525 import { apiError, prefersJson } from "../http/respond.ts";
26 import { FOLLOW_WORD } from "../actions/follow_words.ts";
27 import { forkFollowMode } from "../core/fork_follow.ts";
28 import { keptBehind } from "../core/following.ts";
2629 import { html, raw, when, type Html } from "./html.ts";
2730 import { icon } from "./icons.ts";
2831 import { page, redirect } from "./layout.ts";
@@ -312,7 +315,7 @@ export function scopeHeader(
312315 !options.compact && facts.description !== "",
313316 () => html`<p class="muted small">${facts.description}</p>`,
314317 )}
315 ${repo === undefined ? null : lineageLine(ctx.app.db, repo, parent)}
318 ${repo === undefined ? null : lineageLine(ctx.app, repo, parent)}
316319 ${when(
317320 scope.upstream !== undefined && upstreamHref(scope) === undefined,
318321 // The where strip carries "fork of octo/widgets" and links it, which
@@ -339,10 +342,11 @@ export function scopeHeader(
339342 * noreferrer`). A migrated trail whose owner turned it off is not drawn.
340343 */
341344 export function lineageLine(
342 db: Database,
345 app: Pick<App, "db" | "reposRoot">,
343346 repo: Repo,
344347 parent: Repo | undefined,
345348 ): Html | null {
349 const db = app.db;
346350 const shown = shownTrail(db, repo, parent);
347351 if (parent === undefined && shown === undefined) return null;
348352 const out = (href: string, text: string): Html =>
@@ -353,7 +357,7 @@ export function lineageLine(
353357 html`forked from
354358 <a href="/${parent.ownerName}/${parent.name}"
355359 >${parent.ownerName}/${parent.name}</a
356 >`,
360 > · ${followWord(app, repo, parent)}`,
357361 );
358362 if (shown !== undefined) {
outdated

The word depends on an optional base, so any caller that omits it silently shows no word on a fork. Derive the link from repo (repoBase) and drop the optional parameter. Also the header lacks "N behind" (issue box 1).

359363 segments.push(
@@ -368,6 +372,18 @@ export function lineageLine(
368372 </p>`;
369373 }
370374
375 /**
376 * How a fork follows its parent, in one word that links to the setting, then how far behind it
377 * is when the relation cache counted it at these tips (#12683). One indexed read and two ref
378 * files; no git. Only ever drawn beside a parent, so a repository that is no fork pays nothing.
379 */
380 function followWord(app: Pick<App, "db" | "reposRoot">, repo: Repo, parent: Repo): Html {
381 const behind = keptBehind(app, repo, parent);
382 return html`<a href="${repoBase(repo)}/forks#following" data-follow-word
383 >${FOLLOW_WORD[forkFollowMode(app.db, repo.id)]}</a

Non-blocking: when the count is unknown the header says only the word, so "unknown" and "not counted yet" look alike. Fine for now; a short hint would help a reader on a phone.

384 >${behind === undefined ? null : html` · <span data-follow-behind>${behind} behind</span>`}`;
385 }
386
371387 /**
372388 * Who can see this repository, in the one sentence `audienceOf` gives, on a
373389 * line under the title. The Private badge in the title says the code's
test/fork-follow-word.test.ts added +142
@@ -0,0 +1,142 @@
1 /** A fork's header says in one word how it follows its parent (#12683); a non-fork says nothing. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { setForkFollowMode } from "../src/core/fork_follow.ts";
9 import { forkRelation } from "../src/core/following.ts";
10 import { getRepo } from "../src/core/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { createForgeApp } from "../src/tui/forge.ts";
14 import { forksScreen } from "../src/tui/screens/forks.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { lineageLine } from "../src/web/chrome.ts";
17 import { getUserByName } from "../src/core/users.ts";
18 import { settleApp } from "./helpers/tui.ts";
19 import { promote } from "./helpers/members.ts";
20 import { expectWork, gitSpawns } from "./helpers/work.ts";
21
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-fword-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 const alice = await createUser(app.db, {
31 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
32 password: "a-good-passphrase", adminIfFirst: true,
33 });
34 const bob = await createUser(app.db, {
35 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
36 });
37 if (!alice.ok || !bob.ok) throw new Error("users");
38 promote(app.db, alice.value);
39 promote(app.db, bob.value);
40 const lib = await createRepo(app, alice.value, { name: "lib", visibility: "public" });
41 if (!lib.ok) throw new Error(String(lib.error));
42 const first = await commitToBranch(app, alice.value, lib.value, { message: "Start", files: [{ path: "README.md", content: "# lib\n" }] });
43 if (!first.ok) throw new Error(JSON.stringify(first.error));
44 const forked = await forkRepo(app, bob.value, lib.value);
45 if (!forked.ok) throw new Error(String(forked.error));
46 // The fork's own commit first: a fork with work of its own is diverged, so a parent that moves
47 // is behind, never fast-forwarded.
48 const own = await commitToBranch(app, bob.value, forked.value, { message: "Mine", files: [{ path: "mine.txt", content: "m\n" }] });
49 if (!own.ok) throw new Error(JSON.stringify(own.error));
50 const more = await commitToBranch(app, alice.value, lib.value, { message: "Two", files: [{ path: "two.txt", content: "2\n" }] });
51 if (!more.ok) throw new Error(JSON.stringify(more.error));
52 }, 60_000);
53
54 afterAll(async () => {
55 servers.stop();
56 app.close();
57 await rm(dataDir, { recursive: true, force: true });
58 });
59
60 const wordOf = async (path: string): Promise<{ href: string; word: string } | null> => {
61 const page = await (await fetch(`${servers.url}${path}`)).text();
62 const m = page.match(/<a href="([^"]*)" data-follow-word\s*>([^<]*)</);
63 return m === null ? null : { href: m[1]!, word: m[2]! };
64 };
65
outdated

Add a timing/guard test for box 3 and a TUI/doc check for the second door.

66 test("each mode is one word linking to the setting, on the code tab and on the others", async () => {
67 const fork = getRepo(app.db, "bob", "lib")!;
68 const want: [Parameters<typeof setForkFollowMode>[2], string][] = [
69 ["tell-me", "proposes"],
70 ["take-updates", "follows"],
71 ["dont-follow", "severed"],
72 ];
73 for (const [mode, word] of want) {
74 setForkFollowMode(app.db, fork.id, mode);
75 for (const path of ["/bob/lib", "/bob/lib/issues", "/bob/lib/pulls"]) {
76 const got = await wordOf(path);
77 expect(got?.word, path).toBe(word);
78 expect(got?.href).toBe("/bob/lib/forks#following");
79 }
80 }
81 });
82
83 test("a repository that is no fork shows no word, and the fork says it once", async () => {
84 expect(await wordOf("/alice/lib")).toBeNull();
85 const page = await (await fetch(`${servers.url}/bob/lib`)).text();
86 expect(page.match(/data-follow-word/g)?.length).toBe(1);
87 });
88
89 test("a fork whose tips have not moved costs a few statements and no git; a root, no follow read", async () => {
90 const fork = getRepo(app.db, "bob", "lib")!;
91 const parent = getRepo(app.db, "alice", "lib")!;
92 const asked: string[] = [];
93 const spy = new Proxy(app.db, {
94 get: (t, k) =>
95 k === "query" || k === "prepare"
96 ? (sql: string) => (asked.push(sql), (t as any)[k](sql))
97 : (t as any)[k]?.bind?.(t) ?? (t as any)[k],
98 });
99 const db = { db: spy, reposRoot: app.reposRoot };
100 lineageLine(db, fork, parent);
101 asked.length = 0;
102 expect(await gitSpawns(() => void lineageLine(db, fork, parent))).toBe(0);
103 expectWork(asked.length, { max: 3 });
104 asked.length = 0;
105 expect(lineageLine(db, parent, undefined)).toBeNull();
106 expect(asked.filter((q) => q.includes("fork_follow"))).toEqual([]);
107 });
108
109 test("the terminal's forks screen says the same word and how far behind", async () => {
110 const bob = getUserByName(app.db, "bob")!;
111 setForkFollowMode(app.db, getRepo(app.db, "bob", "lib")!.id, "tell-me");
112 const terminal = headlessTerminal(120, 30);
113 const { app: tui, session } = createForgeApp(
114 app,
115 { sshUsername: "bob", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: bob },
116 { terminal, exitHooks: false },
117 );
118 tui.start();
119 tui.ctx.push(forksScreen(session, tui.ctx, getRepo(app.db, "bob", "lib")!));
120 await settleApp(tui);
121 const frame = tui.screen.toText();
122 tui.stop?.();
123 expect(frame).toContain("proposes · Sends offers to alice/lib · 1 behind");
124 });
125
126 const behindOf = async (path: string): Promise<string | null> =>
127 (await (await fetch(`${servers.url}${path}`)).text()).match(/data-follow-behind>([^<]*)</)?.[1] ?? null;
outdated

Asserting a heading exists in a markdown file tests nothing about behaviour; remove it.

128
129 test("the header says how far behind once counted at these tips, and nothing once a tip moves", async () => {
130 const fork = getRepo(app.db, "bob", "lib")!;
131 const parent = getRepo(app.db, "alice", "lib")!;
132 await forkRelation(app, fork, parent);
133 for (const path of ["/bob/lib/issues", "/bob/lib/pulls"]) expect(await behindOf(path), path).toBe("1 behind");
134 expect(await behindOf("/alice/lib/issues")).toBeNull();
135 const alice = getUserByName(app.db, "alice")!;
136 const three = await commitToBranch(app, alice, parent, { message: "Three", files: [{ path: "three.txt", content: "3\n" }] });
137 if (!three.ok) throw new Error(JSON.stringify(three.error));
138 // The parent moved: the old count is not said as if it were current.
139 expect(await behindOf("/bob/lib/issues")).toBeNull();
140 await forkRelation(app, fork, parent);
141 expect(await behindOf("/bob/lib/issues")).toBe("2 behind");
142 });
test/provenance.test.ts +4 −4
@@ -174,8 +174,8 @@ describe("the record and the line", () => {
174174 parents: ["TheRobotStudio/SO-ARM100"],
175175 });
176176 const fork = { ...source, id: "not-recorded", ownerName: "someone" };
177 const line = lineageLine(app.db, fork, source)!.text.replace(/\s+/g, " ");
178 expect(line).toMatch(/forked from <a href="\/trevato\/arm" ?>trevato\/arm<\/a ?> · migrated/);
177 const line = lineageLine(app, fork, source)!.text.replace(/\s+/g, " ");
178 expect(line).toMatch(/forked from <a href="\/trevato\/arm" ?>trevato\/arm<\/a ?> · <a href="\/someone\/arm\/forks#following" data-follow-word ?>proposes<\/a ?> · migrated/);
179179 expect(line).toContain(
180180 'migrated from <a href="https://github.com/Trevato/SO-ARM100" rel="noopener noreferrer">github.com/Trevato/SO-ARM100</a>',
181181 );
@@ -183,7 +183,7 @@ describe("the record and the line", () => {
183183 'fork of <a href="https://github.com/TheRobotStudio/SO-ARM100" rel="noopener noreferrer">TheRobotStudio/SO-ARM100</a>',
184184 );
185185 // A repository with neither a parent nor a record draws nothing.
186 expect(lineageLine(app.db, fork, undefined)).toBeNull();
186 expect(lineageLine(app, fork, undefined)).toBeNull();
187187 });
188188
189189 test("hidden is hidden everywhere it is drawn; the record stays", () => {
@@ -207,7 +207,7 @@ describe("the record and the line", () => {
207207 const trail = listEvents(app.db, { repoId: source.id, kind: "repo.settings_updated", limit: 1 })[0]!;
208208 expect(trail.actorId).toBe(owner.id);
209209 expect(trail.payload["changed"]).toEqual({ provenance: { from: true, to: false } });
210 expect(lineageLine(app.db, source, undefined)).toBeNull();
210 expect(lineageLine(app, source, undefined)).toBeNull();
211211 expect(getProvenance(app.db, source.id)?.parents).toEqual([
212212 "TheRobotStudio/SO-ARM100",
213213 ]);
test/tip-sync.test.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * `readTipSync` says what `readTip` says from the ref files, and nothing where they cannot
3 * (#12683).
4 */
5 import { expect, test } from "bun:test";
6 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { readTip, readTipSync } from "../src/git/tip.ts";
10
11 test("loose wins over packed, packed answers alone, a missing or unsafe ref is undefined", async () => {
12 const dir = await mkdtemp(join(tmpdir(), "forge-tipsync-"));
13 const a = "a".repeat(40);
14 const b = "b".repeat(40);
15 await mkdir(join(dir, "refs/heads"), { recursive: true });
16 await writeFile(join(dir, "packed-refs"), `# pack-refs with: peeled\n${b} refs/heads/main\n${b} refs/heads/old\n`);
17 await writeFile(join(dir, "refs/heads/main"), `${a}\n`);
18 for (const ref of ["refs/heads/main", "refs/heads/old", "refs/heads/none"])
19 expect(readTipSync(dir, ref), ref).toBe(await readTip(dir, ref));
20 expect(readTipSync(dir, "refs/heads/main")).toBe(a);
21 expect(readTipSync(dir, "refs/heads/old")).toBe(b);
22 expect(readTipSync(dir, "refs/heads/none")).toBeUndefined();
23 expect(readTipSync(dir, "refs/heads/../../etc")).toBeUndefined();
24 await rm(dir, { recursive: true, force: true });
25 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs