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

A fork's page says what its last follow of upstream did, in one line #14534

Merged opened this

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

Merged

scout/forge:scout/14517-a-fork-s-page-says-what-its-last-follow → main 9 commits fork 2 threads · 2 unresolved

  • Merged. scout/14517-a-fork-s-page-says-what-its-last-follow was merged into main as 42827cf.

Review

Sign in to review this change.
12 files changed +288 −13
docs/features/fork-last-follow.md added +25
@@ -0,0 +1,25 @@
1 ---
2 topic: Backups and moving
3 row: What a fork's last follow did
4 ---
5 # What a fork's last follow did
6
7 A fork's standing sentence (the one under its header, #14462) says what its last follow of the upstream did, once, in the same sentence that says how far behind it is:
8
9 - **Code came in:** `Last took 3 hours ago.` This reads the push the take recorded, so it holds for every way a fork takes: the Take button, the API, the MCP `take_updates` tool, the terminal, and a fork that follows automatically.
10 - **Nothing new:** `Checked 5 minutes ago: nothing new.`
11 - **A conflict:** `A take 2 hours ago hit a conflict the crew holds as pull #12.` When no crew member holds it: `... a conflict that no one holds yet.`
12 - **Never followed, or not recorded:** nothing is said. A fork never reads "has not followed" it has in fact followed.
13
14 A newer take of code replaces an older check or conflict clause.
15
16 ## Where
17
18 - **Fork's page:** the live standing line under the header; a take updates it without a reload.
19 - **Fork trees:** each fork's row on the repository page says `last took …`; the terminal's fork tree line and `fork_tree` nodes (`tookAt`) carry it too.
20 - **MCP:** `following` returns `lastFollow`, the clause on a take that took nothing, else `null`; `line` has the last took.
21 - **Terminal:** the forks screen reads the same sentence.
22
23 ## How it is stored
24
25 A take that took nothing (nothing new, or a conflict) stores one `fork.followed` event (`{outcome, on}`) from `takeOrTell`. Taking code is already a `push` event marked `followed`. Nothing runs git to read it: the page makes one indexed query.
src/actions/follow.ts +34 −2
@@ -14,8 +14,9 @@ import type { User } from "../core/users.ts";
1414 import { err, ok, type Result } from "../kernel/result.ts";
1515 import { chainOfRepo, forgeLinkOf, FOLLOW_MODES, isFollowMode, setChainMode, severChain } from "../spawn/chain.ts";
1616 import { FAMILY_WORDS } from "./family_words.ts";
17 import { FOLLOWS_NOTHING, FOLLOW_LINE, agoWords, driftWords, followModeWords, followStandingLine } from "./follow_words.ts";
17 import { FOLLOWS_NOTHING, FOLLOW_LINE, agoWords, driftWords, followModeWords, followStandingLine, lastFollowClause } from "./follow_words.ts";
1818 import { FORK_FOLLOW_MODES, forkFollowMode, lastTookAt, isForkFollowMode, setForkFollowMode, type ForkFollowMode } from "../core/fork_follow.ts";
19 import { lastFollow } from "../core/last_follow.ts";
1920 import { requireUser } from "./access.ts";
2021 import { getFollow, setFollowTaking } from "../core/upstream_follow.ts";
2122 import { isChecking, severUpstream } from "./upstream_follow.ts";
@@ -45,6 +46,12 @@ export async function takeOrTell(
4546 fork: Repo,
4647 expect?: string,
4748 ): Promise<TakeOrTell> {
49 const result = await takeAndTell(app, actor, fork, expect);
50 recordFollow(app, actor, fork, result);
51 return result;
52 }
53
54 async function takeAndTell(app: App, actor: User | undefined, fork: Repo, expect?: string): Promise<TakeOrTell> {
4855 const took = await takeUpdates(app, actor, fork, expect);
4956 if (took.ok || typeof took.error === "string" || took.error.kind !== "conflict") return took;
5057 const parent = forkParentFor(app.db, fork, actor);
@@ -53,6 +60,24 @@ export async function takeOrTell(
5360 return err({ kind: "conflict", files: took.error.files, converge });
5461 }
5562
63 /**
64 * Store one `fork.followed` event for a take that reached the parent and took no code: what it
65 * found, once. A take of code is a push marked `followed` already, on every path that takes.
66 */
67 function recordFollow(app: App, actor: User | undefined, fork: Repo, result: TakeOrTell): void {
68 let payload: Record<string, unknown>;
69 if (result.ok) {
70 if (result.value.updated) return;
71 payload = { outcome: "nothing_new" };
72 } else if (typeof result.error !== "string" && result.error.kind === "conflict" && "converge" in result.error) {
73 const c = result.error.converge;
74 const on =
75 c.kind === "proposed" ? { kind: "pull", number: c.pull.number } : "issue" in c ? { kind: "issue", number: c.issue.number } : null;
76 payload = { outcome: "conflict", on };
77 } else return;
78 app.bus.append({ kind: "fork.followed", repoId: fork.id, actorId: actor?.id, payload });
79 }
80
5681 export type SeverError = "unauthorized" | "forbidden" | "not_following";
5782
5883 /**
@@ -156,6 +181,11 @@ export async function followStanding(app: App, repo: Repo, viewer: User | undefi
156181 );
157182 }
158183
184 /** The clause on a take that found nothing new or a conflict, or "" (see `lastFollowClause`). */
185 export function lastFollowSaid(app: App, repo: Repo): string {
186 return repo.forkParentId === null ? "" : lastFollowClause(lastFollow(app.db, repo.id), lastTookAt(app.db, repo.id));
187 }
188
159189 /**
160190 * The one sentence on how far a fork is from its parent and what following will do (#14462); the
161191 * drift is the cached reading (`driftOfForks`), never a new walk. Undefined for a repository that
@@ -175,7 +205,9 @@ export async function followWords(app: App, repo: Repo, viewer: User | undefined
175205 drift.behind,
176206 );
177207 const took = lastTookAt(app.db, repo.id);
178 return took === null ? sentence : `${sentence} Last took ${agoWords(took)}.`;
208 const said = took === null ? sentence : `${sentence} Last took ${agoWords(took)}.`;
209 const clause = lastFollowClause(lastFollow(app.db, repo.id), took);
210 return clause === "" ? said : `${said} ${clause}`;
179211 }
180212
181213 export type FollowModeError = SeverError | "invalid_mode" | "severed" | "updating";
src/actions/follow_words.ts +17
@@ -209,3 +209,20 @@ export function treeFollowPhrase(follow: "take-updates" | "offers" | "dont-follo
209209 if (follow === "autonomous") return "";
210210 return FOLLOW_PHRASE[follow === "offers" ? "tell-me" : follow];
211211 }
212
213 /**
214 * The clause a fork's standing sentence adds when its newest follow took no code: nothing new, or a
215 * conflict and who holds it. Empty when a later take of code already says the last word, or when
216 * none was recorded: unknown is not said.
217 */
218 export function lastFollowClause(
219 last: { outcome: "nothing_new" | "conflict"; at: string; on: { kind: "pull" | "issue"; number: number } | null } | null,
220 tookAt: string | null,
221 now: number = Date.now(),
222 ): string {
223 if (last === null || (tookAt !== null && Date.parse(tookAt) >= Date.parse(last.at))) return "";
224 if (last.outcome === "nothing_new") return `Checked ${agoWords(last.at, now)}: nothing new.`;
225 return last.on === null
226 ? `A take ${agoWords(last.at, now)} hit a conflict that no one holds yet.`
227 : `A take ${agoWords(last.at, now)} hit a conflict the crew holds as ${last.on.kind} #${last.on.number}.`;
228 }
src/actions/fork_tree.ts +5 −1
@@ -15,7 +15,7 @@
1515 import type { Database } from "bun:sqlite";
1616 import { FOLLOW_WORD } from "./follow_words.ts";
1717 import { keptBehind, type Following } from "../core/following.ts";
18 import { FORK_DEFAULT_MODE, forkFollowModes } from "../core/fork_follow.ts";
18 import { FORK_DEFAULT_MODE, forkFollowModes, lastTookAts } from "../core/fork_follow.ts";
1919 import { canRead, forkParentFor, visibleForksByParent, type Repo } from "../core/repos.ts";
2020 import type { User } from "../core/users.ts";
2121
@@ -46,6 +46,8 @@ export interface TreeNode {
4646 * tips.
4747 */
4848 readonly behind: number | null;
49 /** When it last took code from its parent (ISO); absent when it never has. */
50 readonly tookAt?: string;
4951 /** Set on a root that is a fork of something the caller may not read: a hidden fork, not a gap.
5052 * The parent is not named. */
5153 readonly hiddenParent?: true;
@@ -116,6 +118,7 @@ export function forkTree(
116118 // A root that still has a parent here is a fork of one the caller cannot read.
117119 const hidden = root.forkParentId !== null && !keep.has(root.forkParentId);
118120 const modes = forkFollowModes(db, rows.slice(hidden ? 0 : 1).map((r) => r.repo.id));
121 const took = lastTookAts(db, rows.slice(hidden ? 0 : 1).map((r) => r.repo.id));
119122 const nodes: TreeNode[] = rows.map((r) => {
120123 const hides = hidden && r.parent === null;
121124 // A root whose link the owner cut reads "severed", not nothing.
@@ -129,6 +132,7 @@ export function forkTree(
129132 follow: mode === undefined ? "autonomous" : treeFollow(modes.get(r.repo.id)),
130133 word: mode === undefined ? "" : FOLLOW_WORD[mode],
131134 behind: r.parent === null ? null : (keptBehind(forge, r.repo, r.parent) ?? null),
135 ...(took.has(r.repo.id) && !(r.parent === null && !hides) ? { tookAt: took.get(r.repo.id)! } : {}),
132136 ...(hides ? { hiddenParent: true as const } : {}),
133137 };
134138 });
src/core/event_audience.ts +2
@@ -78,6 +78,8 @@ const READER_KINDS: ReadonlySet<string> = new Set([
7878 "forge.spawn.live",
7979 "forge.spawn.failed",
8080 "fork.diverged",
81 // A fork's follow of upstream took or met a conflict: counts and a pull number, as its page says.
82 "fork.followed",
8183 "push",
8284 "account.parent_linked",
8385 "account.parent_unlinked",
src/core/fork_follow.ts +11
@@ -38,6 +38,17 @@ export function forkFollowModes(db: Database, repoIds: readonly string[]): Map<s
3838 return new Map(rows.map((r) => [r.repo_id, r.mode]));
3939 }
4040
41 /** `lastTookAt` for many repositories in one statement; a repository that never took is absent. */
42 export function lastTookAts(db: Database, repoIds: readonly string[]): Map<string, string> {
43 if (repoIds.length === 0) return new Map();
44 const rows = db
45 .query<{ id: string; at: string | null }, [string]>(
46 `SELECT j.value AS id, (SELECT created_at FROM event WHERE repo_id = j.value AND kind = 'push' AND json_extract(payload, '$.followed') IS NOT NULL ORDER BY seq DESC LIMIT 1) AS at FROM json_each(?1) j`,
47 )
48 .all(JSON.stringify(repoIds));
49 return new Map(rows.flatMap((r) => (r.at === null ? [] : [[r.id, r.at] as [string, string]])));
50 }
51
4152 /**
4253 * When this repository last took code from what it follows (ISO), or null: the newest push recorded as
4354 * followed (a fast-forward, a merge, or a forge's take of its upstream). Walks `event_repo_kind_seq`
src/core/last_follow.ts added +49
@@ -0,0 +1,49 @@
1 /**
2 * What a fork's last follow of its upstream did: one `fork.followed` event per take that took no
3 * code (nothing new, or a conflict), read back as the newest; a take that took code is already a
4 * push marked `followed`. Nothing is run to read it: one indexed query on the repository's own
5 * events.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 /** What a take that took nothing recorded; a take that took code is a `followed` push already. */
11 export type FollowOutcome = "nothing_new" | "conflict";
12
13 export interface LastFollow {
14 readonly outcome: FollowOutcome;
15 /** When it happened (ISO). */
16 readonly at: string;
17 /** The pull or issue the crew holds a conflict on, when there is one: `{kind, number}`. */
18 readonly on: { readonly kind: "pull" | "issue"; readonly number: number } | null;
19 }
20
21 export const FOLLOWED_EVENT = "fork.followed";
22
23 const isOutcome = (v: unknown): v is FollowOutcome => v === "nothing_new" || v === "conflict";
24
25 /** The newest follow recorded for this repository, or null when it never followed. */
26 export function lastFollow(db: Database, repoId: string): LastFollow | null {
27 const row = db
28 .query<{ at: string; payload: string }, [string, string]>(
29 "SELECT created_at AS at, payload FROM event WHERE repo_id = ?1 AND kind = ?2 ORDER BY seq DESC LIMIT 1",
30 )
31 .get(repoId, FOLLOWED_EVENT);
32 if (row === null) return null;
33 let p: Record<string, unknown>;
34 try {
35 p = JSON.parse(row.payload) as Record<string, unknown>;
36 } catch {
37 return null;
38 }
39 if (!isOutcome(p["outcome"])) return null;
40 const on = p["on"] as { kind?: unknown; number?: unknown } | null | undefined;
41 return {
42 outcome: p["outcome"],
43 at: row.at,
44 on:
45 on && (on.kind === "pull" || on.kind === "issue") && Number.isInteger(on.number)
46 ? { kind: on.kind, number: on.number as number }
47 : null,
48 };
49 }
src/core/standing_events.ts +1 −1
@@ -3,4 +3,4 @@
33 * terminal's forks screen. `repo.synced` is a mirror's sync that ended in failure or recovered
44 * from one.
55 */
6 export const STANDING_EVENTS: readonly string[] = ["push", "repo.synced", "repo.following", "repo.upstream_checked"];
6 export const STANDING_EVENTS: readonly string[] = ["push", "repo.synced", "repo.following", "repo.upstream_checked", "fork.followed"];
src/http/mcp/tools/following.ts +3 −2
@@ -1,6 +1,6 @@
11 import { upstreamPayload } from "../../../spawn/upstream.ts";
22 import { relationOf } from "../../../actions/forks.ts";
3 import { followModeOf, followStanding } from "../../../actions/follow.ts";
3 import { followModeOf, followStanding, lastFollowSaid } from "../../../actions/follow.ts";
44 import { chainOfRepo } from "../../../spawn/chain.ts";
55 import { convergeState } from "../../../crew/converge.ts";
66 import { parentForgeFor } from "../../../core/parent_releases.ts";
@@ -9,7 +9,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"
99 export const tool: Tool = {
1010 name: "following",
1111 doc:
12 "`{ repo }`: for a fork `{ parent, mode, line, state, behind, ahead, clean, conflicts, action, words, parentForge, converge, chain, severedAt, upstream }`, where it stands against what it follows (`line` the one plain line the page says, choice and last took; `mode` take-updates, tell-me or dont-follow, set by `follow_mode`; `state` in step, behind, ahead or diverged; `behind`/`ahead` commits; `clean` whether a merge would apply; `conflicts` the files that clash; `action` the one thing that reconciles it (none, fast-forward, offer, merge, keep-both) and `words` it said plainly; `converge` what the crew is doing about a conflict, else `null`; `parentForge`, `chain`, `severedAt` and `upstream` the forge-to-forge link, `null` when there is none); for a repository that is no fork but a spawned forge, only `{ chain, severedAt, upstream }`; refused `not_a_fork` when it follows nothing, `not_found` for a repository the caller may not see",
12 "`{ repo }`: for a fork `{ parent, mode, line, state, behind, ahead, clean, conflicts, action, words, parentForge, converge, chain, severedAt, upstream }`, where it stands against what it follows (`line` the one plain line the page says, choice and last took; `lastFollow` the clause on a take that took nothing (nothing new, or a conflict and who holds it), else `null`; `mode` take-updates, tell-me or dont-follow, set by `follow_mode`; `state` in step, behind, ahead or diverged; `behind`/`ahead` commits; `clean` whether a merge would apply; `conflicts` the files that clash; `action` the one thing that reconciles it (none, fast-forward, offer, merge, keep-both) and `words` it said plainly; `converge` what the crew is doing about a conflict, else `null`; `parentForge`, `chain`, `severedAt` and `upstream` the forge-to-forge link, `null` when there is none); for a repository that is no fork but a spawned forge, only `{ chain, severedAt, upstream }`; refused `not_a_fork` when it follows nothing, `not_found` for a repository the caller may not see",
1313 description:
1414 "Where a fork stands against what it follows: in step, behind, ahead, diverged.",
1515 inputSchema: {
@@ -38,6 +38,7 @@ export const tool: Tool = {
3838 parent: `${relation.parent.ownerName}/${relation.parent.name}`,
3939 mode: await followModeOf(ctx.app, repo),
4040 line: await followStanding(ctx.app, repo, user),
41 lastFollow: lastFollowSaid(ctx.app, repo) || null,
4142 state: relation.state,
4243 behind: relation.behind,
4344 ahead: relation.ahead,
src/tui/screens/fork_tree.ts +3 −2
@@ -4,7 +4,7 @@
44 * the tool does: a repo the session's person may not read has no tree.
55 */
66
7 import { HIDDEN_FORK_WORD, treeFollowPhrase } from "../../actions/follow_words.ts";
7 import { HIDDEN_FORK_WORD, agoWords, treeFollowPhrase } from "../../actions/follow_words.ts";
88 import { forkTree, type ForkTree } from "../../actions/fork_tree.ts";
99 import { followLine } from "../../actions/follow.ts";
1010 import type { Repo } from "../../core/repos.ts";
@@ -24,7 +24,8 @@ export function treeLines(tree: ForkTree | undefined, asked: string, width = 80,
2424 const lines = tree.nodes.map((n) => {
2525 const phrase = n.word === "" ? "" : treeFollowPhrase(n.follow);
2626 const behind = n.behind === null ? "" : ` · ${n.behind} behind`;
27 const follow = (phrase === "" ? "" : ` ${phrase}${behind}`) + (n.hiddenParent === true ? ` ${HIDDEN_FORK_WORD}` : "");
27 const took = n.tookAt === undefined ? "" : ` · last took ${agoWords(n.tookAt)}`;
28 const follow = (phrase === "" ? "" : ` ${phrase}${behind}${took}`) + (n.hiddenParent === true ? ` ${HIDDEN_FORK_WORD}` : "");
2829 const you = n.repo !== asked && viewer !== undefined && n.repo.startsWith(`${viewer}/`) ? " (you)" : "";
2930 return truncate(`${" ".repeat(n.depth)}${n.repo === asked ? "* " : ""}${n.repo}${you}${follow}`, width);
3031 });
src/web/pages/repo.ts +11 −5
@@ -45,8 +45,8 @@ import {
4545 takeUpdates,
4646 type ForkDrift,
4747 } from "../../actions/forks.ts";
48 import { FORK_DEFAULT_MODE, forkFollowModes, type ForkFollowMode } from "../../core/fork_follow.ts";
49 import { FOLLOW_PHRASE, isSevered } from "../../actions/follow_words.ts";
48 import { FORK_DEFAULT_MODE, forkFollowModes, lastTookAts, type ForkFollowMode } from "../../core/fork_follow.ts";
49 import { FOLLOW_PHRASE, agoWords, isSevered } from "../../actions/follow_words.ts";
5050 import { keptBehind, lineageOf, MINE_ANCHOR, ownsInTree } from "../../core/following.ts";
5151 import {
5252 archivedLine,
@@ -184,7 +184,9 @@ export async function forksPage(ctx: Ctx): Promise<Response> {
184184 notePhase(ctx.request, "forks", performance.now() - t);
185185 t = performance.now();
186186 const tree = forkTree(ctx.app.db, repo.id, ctx.auth.user);
187 const forkModes = forkFollowModes(ctx.app.db, [...tree, ...tree.flatMap((n) => n.forks)].map((n) => n.repo.id));
187 const forkIds = [...tree, ...tree.flatMap((n) => n.forks)].map((n) => n.repo.id);
188 const forkModes = forkFollowModes(ctx.app.db, forkIds);
189 const forkTook = lastTookAts(ctx.app.db, forkIds);
188190 notePhase(ctx.request, "fork-tree", performance.now() - t);
189191 t = performance.now();
190192 // The whole family, from the oldest ancestor this viewer may see: who
@@ -217,7 +219,7 @@ export async function forksPage(ctx: Ctx): Promise<Response> {
217219 note: "A fork is a copy under another name that can propose changes back here, and follows this one until it has work of its own.",
218220 bind: BIND.rest,
219221 })
220 : html`${forkRanking(ranked, new Map(tree.map((n) => [n.repo.id, n])), BIND.rest, forkModes, (fork, parent) => keptBehind(ctx.app, fork, parent))}
222 : html`${forkRanking(ranked, new Map(tree.map((n) => [n.repo.id, n])), BIND.rest, forkModes, (fork, parent) => keptBehind(ctx.app, fork, parent), forkTook)}
221223 <h3 class="mt">The family, by who follows whom</h3>
222224 ${lineageCard(lineage, repo.id, ctx.auth.user?.id)}`}`;
223225 const res = page({
@@ -243,7 +245,10 @@ function forkRanking(
243245 modes: ReadonlyMap<string, ForkFollowMode> = new Map(),
244246 /** Commits a nested fork lacks from its parent, as last counted; never asks git. */
245247 behindOf: (fork: Repo, parent: Repo) => number | undefined = () => undefined,
248 /** When each fork last took from its parent (ISO), from the pushes already recorded. */
249 tookAt: ReadonlyMap<string, string> = new Map(),
246250 ): Html {
251 const took = (id: string): string => (tookAt.has(id) ? `last took ${agoWords(tookAt.get(id)!)}` : "");
247252 const modeOf = (id: string): ForkFollowMode => modes.get(id) ?? FORK_DEFAULT_MODE;
248253 const below = (n: ForkNode, parent: Repo): Html => {
249254 const behind = behindOf(n.repo, parent);
@@ -253,7 +258,7 @@ function forkRanking(
253258 title: html`<a href="/${n.repo.ownerName}/${n.repo.name}"
254259 >${n.repo.ownerName}/${n.repo.name}</a
255260 >`,
256 meta: html`<span>${FOLLOW_PHRASE[modeOf(n.repo.id)]}</span>${behind === undefined ? "" : html` · ${behind} behind`}${n.deeper === 0
261 meta: html`<span>${FOLLOW_PHRASE[modeOf(n.repo.id)]}</span>${behind === undefined ? "" : html` · ${behind} behind`}${took(n.repo.id) === "" ? "" : html` · ${took(n.repo.id)}`}${n.deeper === 0
257262 ? html``
258263 : html` · <a href="/${n.repo.ownerName}/${n.repo.name}/forks"
259264 >and ${n.deeper} more fork${n.deeper === 1 ? "" : "s"} below</a
@@ -270,6 +275,7 @@ function forkRanking(
270275 >`,
271276 meta: html`<span>${FOLLOW_PHRASE[modeOf(f.fork.id)]}</span>${[
272277 ranked.archived ? "" : driftWords(f.drift),
278 took(f.fork.id),
273279 f.pushedAt === null ? "" : html`pushed ${time(f.pushedAt)}`,
274280 ]
275281 .filter((p) => String(p) !== "")
test/fork-last-follow.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * A fork's one standing sentence says what its last follow did, once: "Last took …" when code came
3 * in (a push marked followed, on every take path), and a clause when the newest take found nothing
4 * new or a conflict. A fork that never followed says nothing of it (unknown is not said). Read from
5 * stored rows, on the page, the MCP `following` tool, the terminal and the tree.
6 */
7 import { afterAll, beforeAll, 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 { followWords, lastFollowSaid, takeOrTell } from "../src/actions/follow.ts";
12 import { lastFollowClause, agoWords } from "../src/actions/follow_words.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { forkTree } from "../src/actions/fork_tree.ts";
15 import { treeLines } from "../src/tui/screens/fork_tree.ts";
16 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { lastFollow } from "../src/core/last_follow.ts";
19 import { getRepoById, type Repo } from "../src/core/repos.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { promote } from "./helpers/members.ts";
23
24 let dataDir = "";
25 let app: App;
26 let servers: Servers;
27 let alice: User;
28 let bob: User;
29 let parent: Repo;
30
31 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
32 if (!r.ok) throw new Error(JSON.stringify(r.error));
33 return r.value;
34 };
35 const fresh = (r: Repo): Repo => getRepoById(app.db, r.id)!;
36 const commit = async (who: User, repo: Repo, path: string, content: string) =>
37 must(await commitToBranch(app, who, repo, { message: `${who.username}: ${path}`, files: [{ path, content }] }));
38 /** The standing sentence as the live fragment draws it, tags and link dropped. */
39 const standing = async (fork: Repo): Promise<string> =>
40 (await (await fetch(`${servers.url}/${fork.ownerName}/${fork.name}/standing-line`)).text()).replace(/<[^>]*>/g, "").trim();
41
42 beforeAll(async () => {
43 dataDir = await mkdtemp(join(tmpdir(), "forge-last-follow-"));
44 app = createApp({ dataDir, port: 0 });
45 servers = await serve(app);
46 const both = await Promise.all(
47 ["alice", "bob"].map(async (username, i) => {
48 const made = must(
49 await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.dev`, password: "a-good-passphrase", adminIfFirst: i === 0 }),
50 );
51 promote(app.db, made);
52 return made;
53 }),
54 );
55 alice = both[0]!;
56 bob = both[1]!;
57 parent = must(await createRepo(app, alice, { name: "game", visibility: "public" }));
58 await commit(alice, parent, "README.md", "# game\n");
59 }, 30_000);
60
61 afterAll(async () => {
62 servers.stop();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66
67 test("the words: each outcome says once, a later take of code or no record says nothing", () => {
68 const now = Date.parse("2026-01-01T03:00:00Z");
69 const at = "2026-01-01T00:00:00Z";
70 expect(lastFollowClause(null, null, now)).toBe("");
71 expect(lastFollowClause({ outcome: "nothing_new", at, on: null }, null, now)).toBe("Checked 3 hours ago: nothing new.");
72 expect(lastFollowClause({ outcome: "conflict", at, on: { kind: "issue", number: 7 } }, null, now)).toBe(
73 "A take 3 hours ago hit a conflict the crew holds as issue #7.",
74 );
75 expect(lastFollowClause({ outcome: "conflict", at, on: null }, null, now)).toBe("A take 3 hours ago hit a conflict that no one holds yet.");
76 // Code taken after the check is the newer word, and "Last took" says it.
77 expect(lastFollowClause({ outcome: "nothing_new", at, on: null }, "2026-01-01T01:00:00Z", now)).toBe("");
78 expect(lastFollowClause({ outcome: "conflict", at, on: null }, "2025-12-31T00:00:00Z", now)).not.toBe("");
79 });
80
81 test("a fork that never followed says nothing false; each take that took nothing is said once", async () => {
82 const fork = must(await forkRepo(app, bob, fresh(parent), "game-bob"));
83 expect(lastFollow(app.db, fork.id)).toBeNull();
84 expect(lastFollowSaid(app, fresh(fork))).toBe("");
85 expect(await standing(fork)).not.toMatch(/follow(ed)? upstream|Checked|conflict/);
86
87 must(await takeOrTell(app, bob, fresh(fork)));
88 expect(lastFollowSaid(app, fresh(fork))).toBe("Checked just now: nothing new.");
89 expect(await standing(fork)).toContain("Checked just now: nothing new.");
90
91 // Code taken is the push marked followed: "Last took", and the older check is not repeated.
92 await commit(bob, fork, "mine.txt", "mine\n");
93 await commit(alice, parent, "a.txt", "a\n");
94 must(await takeOrTell(app, bob, fresh(fork)));
95 const took = await followWords(app, fresh(fork), bob);
96 expect(took).toMatch(/Last took .* ago\.|Last took just now\./);
97 expect(took).not.toMatch(/Checked/);
98
99 // A conflict with no crew member to hold it says so, and names nobody.
100 await commit(bob, fork, "README.md", "# bob\n");
101 await commit(alice, parent, "README.md", "# alice\n");
102 const none = await takeOrTell(app, bob, fresh(fork));
103 expect(none.ok).toBe(false);
104 expect(lastFollowSaid(app, fresh(fork))).toMatch(/hit a conflict (that no one holds yet|the crew holds as (issue|pull) #\d+)\.$/);
105
106 // With a crew member the conflict is held, and the line says where.
107 must(await createAgent(app, alice, { username: "bot", brief: "Be brief." }));
108 expect(addToCrew(app, bob, fresh(fork), "bot").ok).toBe(true);
109 const conflict = await takeOrTell(app, bob, fresh(fork));
110 expect(conflict.ok).toBe(false);
111 expect(lastFollowSaid(app, fresh(fork))).toMatch(/the crew holds as (issue|pull) #\d+\.$/);
112 expect(await standing(fork)).toMatch(/the crew holds as (issue|pull) #\d+\.$/);
113 }, 30_000);
114
115 test("the tree says when each fork last took, on the web page and in the terminal", async () => {
116 const fork = must(await forkRepo(app, alice, fresh(parent), "game-alice"));
117 expect(forkTree(app.db, fresh(parent), alice, app)!.nodes.find((n) => n.repo === "alice/game-alice")!.tookAt).toBeUndefined();
118 await commit(alice, parent, "t.txt", "t\n");
119 must(await takeOrTell(app, alice, fresh(fork)));
120 const node = forkTree(app.db, fresh(parent), alice, app)!.nodes.find((n) => n.repo === "alice/game-alice")!;
121 expect(node.tookAt).toBeDefined();
122 const said = `last took ${agoWords(node.tookAt!)}`;
123 expect(treeLines(forkTree(app.db, fresh(parent), alice, app), "alice/game", 120).join("\n")).toContain(said);
124 const page = await (await fetch(`${servers.url}/alice/game/forks`)).text().catch(() => "");
125 const root = await (await fetch(`${servers.url}/alice/game`)).text();
126 expect(root + page).toContain(said);
127 }, 30_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs