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

An owner sets a fork's follow mode from the fork's own page: follow automatically or propose only, one confirmed action with a receipt #13511

Merged opened this

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

Merged

scout/forge:scout/13443-an-owner-sets-a-fork-s-follow-mode-from → main 3 commits fork 3 threads · 3 unresolved

  • Merged. scout/13443-an-owner-sets-a-fork-s-follow-mode-from was merged into main as 575823e.

Review

Sign in to review this change.
5 files changed +135 −12
docs/features/follow-mode.md +2
@@ -18,6 +18,8 @@ The fork's repository page and its forks page (`/:owner/:name/forks`) carry the
1818 - **MCP:** `follow_mode` with `repo` and `mode` (`take-updates`, `tell-me` or `dont-follow`) switches it for an admin and answers in the same words as the page. Anyone else is refused. `following` returns the current `mode`, and `fork_tree` names each node's `follow`.
1919 - **Terminal:** on a fork's screen the row shows the same line; `m` steps to the next mode and the toast says the same sentence.
2020
21 While an update check of the fork is running (`isChecking` in `src/actions/upstream_follow.ts`, one claim per repository and source), the change is refused with `An update from upstream is running here; change how this fork follows when it has finished.` (409, `updating`) on every door: web form, MCP, API and terminal. It is tested after the admin check, so anyone else gets the same refusal as ever and learns nothing of a check.
22
2123 A spawned forge's chain (its code repository following its parent forge) takes only `tell-me` or `take-updates`. To follow nothing, it severs.
2224
2325 ## What honours it
src/actions/follow.ts +5 −2
@@ -18,7 +18,7 @@ import { FOLLOWS_NOTHING, followModeWords, followStandingLine } from "./follow_w
1818 import { FORK_FOLLOW_MODES, forkFollowMode, lastTookAt, isForkFollowMode, setForkFollowMode, type ForkFollowMode } from "../core/fork_follow.ts";
1919 import { requireUser } from "./access.ts";
2020 import { getFollow, setFollowTaking } from "../core/upstream_follow.ts";
21 import { severUpstream } from "./upstream_follow.ts";
21 import { isChecking, severUpstream } from "./upstream_follow.ts";
2222 import { takeFromParent, type Taken } from "../spawn/take.ts";
2323 import { takeUpdates, type ForkSync, type TakeUpdatesError } from "./forks.ts";
2424 import { convergeFollowed } from "./upstream_sync.ts";
@@ -148,7 +148,7 @@ export async function followStanding(app: App, repo: Repo, viewer: User | undefi
148148 );
149149 }
150150
151 export type FollowModeError = SeverError | "invalid_mode" | "severed";
151 export type FollowModeError = SeverError | "invalid_mode" | "severed" | "updating";
152152
153153 /** The one answer every door gives a refused mode change, with the status an HTTP door sends. */
154154 export const FOLLOW_MODE_REFUSALS: Record<FollowModeError, { status: number; message: string }> = {
@@ -157,6 +157,7 @@ export const FOLLOW_MODE_REFUSALS: Record<FollowModeError, { status: number; mes
157157 not_following: { status: 404, message: FAMILY_WORDS.not_following },
158158 invalid_mode: { status: 422, message: `mode is one of: ${FORK_FOLLOW_MODES.join(", ")}; a spawned forge takes ${FOLLOW_MODES.join(" or ")} and severs instead of not following` },
159159 severed: { status: 409, message: "this forge is severed and follows nothing; there is no mode to change" },
160 updating: { status: 409, message: "An update from upstream is running here; change how this fork follows when it has finished." },
160161 };
161162
162163 /**
@@ -179,6 +180,8 @@ export async function setFollowMode(
179180 const upstream = !carries && repo.forkParentId === null ? getFollow(app.db, repo.id) : undefined;
180181 if (!carries && repo.forkParentId === null && upstream === undefined) return err("not_following");
181182 if (!canAdmin(app.db, repo, who.value) || !canWrite(app.db, repo, who.value)) return err("forbidden");
183 // After the admin check, so anyone else gets the same 403 and learns nothing of a check.
184 if (isChecking(repo.id)) return err("updating");
182185 if (!isForkFollowMode(mode)) return err("invalid_mode");
183186 if (upstream !== undefined) {
184187 if (upstream.severedAt !== null) return err("severed");
src/actions/upstream_follow.ts +26 −9
@@ -156,16 +156,34 @@ export function mayCarryCredential(upstreamUrl: string, webUrl: string): boolean
156156 }
157157 }
158158
159 /** Repositories with a check in flight: one at a time each, whoever asked. */
160 const checking = new Set<string>();
159 /**
160 * Checks in flight, per repository: its upstream's (`""`) and each followed source's by id. One at
161 * a time each.
162 */
163 const checking = new Map<string, Set<string>>();
164
165 /** Take the claim on one check; `undefined` when it is already running, else the release. */
166 export function claimCheck(repoId: string, sourceId = ""): (() => void) | undefined {
outdated

Prefix match on ${repoId}: over an untyped string Set is fragile and scans the whole set per call. Track checks per repo id explicitly.

167 const held = checking.get(repoId) ?? new Set<string>();
168 if (held.has(sourceId)) return undefined;
169 held.add(sourceId);
170 checking.set(repoId, held);
171 return () => {
172 held.delete(sourceId);
173 if (held.size === 0 && checking.get(repoId) === held) checking.delete(repoId);
174 };
175 }
176
177 /** Whether any update check of this repository is running now. */
178 export const isChecking = (repoId: string): boolean => checking.has(repoId);
161179
162180 /**
163181 * One check, of one repository. The claim is taken before the first await,
164182 * so a double click and the clock never both run: the second is `busy`.
165183 */
166184 export async function checkUpstream(app: App, repo: Repo): Promise<Result<Checked, CheckError>> {
167 if (checking.has(repo.id)) return err("busy");
168 checking.add(repo.id);
185 const release = claimCheck(repo.id);
186 if (release === undefined) return err("busy");
169187 try {
170188 const result = await checkOnce(app, repo);
171189 // So an open settings page or About card updates; no address in it.
@@ -173,7 +191,7 @@ export async function checkUpstream(app: App, repo: Repo): Promise<Result<Checke
173191 app.bus.append({ kind: "repo.upstream_checked", repoId: repo.id, payload: {} });
174192 return result;
175193 } finally {
176 checking.delete(repo.id);
194 release();
177195 }
178196 }
179197
@@ -473,9 +491,8 @@ async function checkOnce(app: App, repo: Repo): Promise<Result<Checked, CheckErr
473491 * upstream's.
474492 */
475493 export async function checkSource(app: App, repo: Repo, source: FollowSource): Promise<Result<Checked, CheckError>> {
476 const key = `${repo.id}:${source.id}`;
477 if (checking.has(key)) return err("busy");
478 checking.add(key);
494 const release = claimCheck(repo.id, source.id);
495 if (release === undefined) return err("busy");
479496 try {
480497 if (!source.enabled || repo.archivedAt !== null || repo.origin !== null) return err("off");
481498 const result = await checkTarget(app, repo, {
@@ -489,7 +506,7 @@ export async function checkSource(app: App, repo: Repo, source: FollowSource): P
489506 app.bus.append({ kind: "repo.upstream_checked", repoId: repo.id, payload: {} });
490507 return result;
491508 } finally {
492 checking.delete(key);
509 release();
493510 }
494511 }
495512
src/http/mcp/tools/follow_mode.ts +1 −1
@@ -5,7 +5,7 @@ import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"
55
66 export const tool: Tool = {
77 name: "follow_mode",
8 doc: "`{ repo, mode }`: choose how a fork follows its parent: `take-updates`, `tell-me` or `dont-follow` (a spawned forge: the first two; it severs instead); the admin only; answers `{ says, mode, line }`; refused `unauthorized`, `forbidden`, `not_following`, `invalid_mode` or `severed`",
8 doc: "`{ repo, mode }`: choose how a fork follows its parent: `take-updates`, `tell-me` or `dont-follow` (a spawned forge: the first two; it severs instead); the admin only; answers `{ says, mode, line }`; refused `unauthorized`, `forbidden`, `not_following`, `invalid_mode`, `severed` or `updating` (an update is running)",
99 description:
1010 "How a fork follows its parent: take updates, tell me, or don't follow.",
1111 inputSchema: {
test/follow-mode-updating.test.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * A follow-mode change while an update check is running is refused in a plain sentence (#13443),
3 * on the action, the web form and the MCP tool; a non-admin gets the same 403 and learns nothing.
4 * The check is held by its claim, so nothing here touches the network.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { FOLLOW_MODE_REFUSALS, setFollowMode } from "../src/actions/follow.ts";
13 import { claimCheck, isChecking, setFollowUpstream } from "../src/actions/upstream_follow.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { getRepo, type Repo } from "../src/core/repos.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19
20 let dir = "";
21 let app: App;
22 let servers: Servers;
23 let owner: User;
24 let repo: Repo;
25 let cookie = "";
26 let token = "";
27 let strangerCookie = "";
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-follow-busy-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 servers = await serve(app);
33 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 const other = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
35 if (!made.ok || !other.ok) throw new Error("user");
36 owner = made.value;
37 cookie = `forge_session=${createSession(app.db, owner.id).token}`;
38 strangerCookie = `forge_session=${createSession(app.db, other.value.id).token}`;
outdated

checkUpstream fetches https://example.com for real: network dependent, up to 60s, racy against whether the claim is still held. Stub the fetch with a controllable promise so the test is deterministic and fast.

39 token = createToken(app.db, owner.id, "t", "rw").token;
40 const r = await createRepo(app, owner, { name: "square", visibility: "public" });
41 if (!r.ok) throw new Error("repo");
42 await commitToBranch(app, owner, r.value, { message: "Start", files: [{ path: "README.md", content: "# s\n" }] });
43 repo = getRepo(app.db, "alice", "square")!;
44 const set = setFollowUpstream(app, owner, repo, { url: "https://example.com/up/stream.git", branch: "main", enabled: true });
45 if (!set.ok) throw new Error("follow");
46 });
47 afterAll(async () => {
48 await servers.stop();
49 app.close();
50 await rm(dir, { recursive: true, force: true });
51 });
52
53 const form = (who: string) =>
54 fetch(`${servers.url}/alice/square/following/mode`, {
55 method: "POST",
56 headers: { cookie: who, origin: servers.url, accept: "application/json" },
57 body: new URLSearchParams({ mode: "take-updates" }),
58 redirect: "manual",
59 });
60 const mcp = async () => {
61 const res = await fetch(`${servers.url}/mcp`, {
62 method: "POST",
63 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
64 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "follow_mode", arguments: { repo: "alice/square", mode: "take-updates" } } }),
65 });
66 return ((await res.json()) as any).result.content[0].text as string;
67 };
68
69 test("the claim is per repository: a source's check counts, and its release clears it", () => {
70 const upstream = claimCheck(repo.id)!;
71 expect(claimCheck(repo.id)).toBeUndefined();
72 const source = claimCheck(repo.id, "s1")!;
73 upstream();
74 expect(isChecking(repo.id)).toBe(true);
75 source();
76 expect(isChecking(repo.id)).toBe(false);
77 expect(isChecking("other")).toBe(false);
78 });
79
80 test("while an update is running the mode does not change; after it, it does", async () => {
81 const release = claimCheck(repo.id)!;
82 expect(await setFollowMode(app, owner, repo, "take-updates")).toEqual({ ok: false, error: "updating" });
83 expect(FOLLOW_MODE_REFUSALS.updating.message).toContain("update from upstream is running");
84 release();
85 expect((await setFollowMode(app, owner, repo, "take-updates")).ok).toBe(true);
86 });
87
88 test("the web form and the MCP tool say the sentence; a non-admin is 403 and learns nothing", async () => {
89 const release = claimCheck(repo.id)!;
90 try {
91 expect(await (await form(cookie)).text()).toContain(FOLLOW_MODE_REFUSALS.updating.message);
92 const said = await mcp();
93 expect(said).toContain(FOLLOW_MODE_REFUSALS.updating.message);
94 const stranger = await form(strangerCookie);
95 expect(await stranger.text()).not.toContain("update from upstream");
96 const busy = await setFollowMode(app, undefined, repo, "tell-me");
97 expect(busy).toEqual({ ok: false, error: "unauthorized" });
98 } finally {
99 release();
100 }
101 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs