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

Following an upstream's update shows the commits it brings before the owner takes it #13157

Merged opened this

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

Merged

scout/forge:scout/13144-following-an-upstream-s-update-shows-the → main 11 commits fork 3 threads · 3 unresolved

  • Merged. scout/13144-following-an-upstream-s-update-shows-the was merged into main as b89a90a.

Review

Sign in to review this change.
15 files changed +473 −41
docs/MCP.md +1 −1
@@ -226,7 +226,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
226226 | `sync` | — | Sync a mirror now; `originId` reconnects it | 197 |
227227 | `system` | `csp`, `routes`, `footing`, `offsite`, `size`, `maintenance`, `growth` | The forge machine now: CPU, memory, disk, network | 361 |
228228 | `take_back` | — | Open the pull that undoes a shipped pull | 219 |
229 | `take_updates` | — | Take the parent forge's updates into a fork | 176 |
229 | `take_updates` | — | Take the parent forge's updates into a fork | 268 |
230230 | `teams` | — | Crew teams for person admins: charter, dial (0–100) and member agents | 338 |
231231 | `telemetry_grant` | — | Grant an agent telemetry:read, or `on: false` takes it back | 226 |
232232 | `telemetry_history` | — | Machine CPU, memory, load over `hours` (1–72, default 6) | 239 |
docs/features/README.md +1
@@ -386,6 +386,7 @@ Read with the guide page [Backups and moving](../guide-backups-moving.md).
386386 - [Connecting an origin read-only](origin-read-only.md)
387387 - [Forge-to-forge compatibility, measured](forge-origin-compat.md)
388388 - [How a fork follows its upstream](follow-mode.md)
389 - [Read an update before you take it](following-incoming.md)
389390 - [Moving a forge out of this forge's process into its own sandbox](sandbox-move.md)
390391 - [Moving a platform app to the forge (gretchy-stretchy, #11687)](platform-app-move.md)
391392 - [Moving a repository to another owner](repo-transfer.md)
docs/features/following-incoming.md added +20
@@ -0,0 +1,20 @@
1 # Read an update before you take it
2
3 A fork that is behind its parent lists the commits an update would bring, newest first, with who wrote each and how long ago. You read them, then take.
4
5 ## Where
6
7 - **Page:** the following card on a fork's home lists up to 50 commits above **Take updates**; a longer list ends with "and N more".
8 - **Terminal:** the Forks screen (`t` on a fork behind its parent) shows the first eight commits in its confirm, and counts the rest.
9 - **API:** `POST /api/v1/repos/:owner/:name/following/take?tip=<commit id>`.
10 - **MCP:** `take_updates` with `{ "repo": "owner/name", "tip": "<commit id>" }`.
11
12 ## The tip you saw is the tip taken
13
14 The page and the terminal hand back the parent tip the list led to. If the parent has moved since, nothing is taken and the next look shows the new list. The API answers `409` with `upstream_moved` and the new tip; MCP answers the same error name. A malformed `tip` is `422` (`invalid_tip`). Without `tip`, a take applies whatever the parent is now, as before.
15
16 A fast-forward applies that same id: the fetch that stages the parent's tip is checked against it before the fork's branch moves.
17
18 ## Not covered
19
20 A repository that follows an address instead of a parent here lists nothing, and its take is not tied to a tip.
scripts/gate.ts +1
@@ -50,6 +50,7 @@ export const EXCLUDED: readonly Exclusion[] = [];
5050 * short: an entry is a debt with an owner, not a home.
5151 */
5252 export const SLOW: readonly Exclusion[] = [
53 { file: "test/following-incoming.test.ts", reason: "makes 52 real commits to pass the 50-line cap of the incoming list; 2.4 s under full-suite load, 0.5 s alone", issue: 13144 },
5354 { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 },
5455 // From the breach list closing this pull's check log at e2a5c15 (#12088):
5556 // every test over the 2 s budget, its file named once with its slowest time.
src/actions/follow.ts +12 −5
@@ -43,8 +43,9 @@ export async function takeOrTell(
4343 app: App,
4444 actor: User | undefined,
4545 fork: Repo,
46 expect?: string,
4647 ): Promise<TakeOrTell> {
47 const took = await takeUpdates(app, actor, fork);
48 const took = await takeUpdates(app, actor, fork, expect);
4849 if (took.ok || typeof took.error === "string" || took.error.kind !== "conflict") return took;
4950 const parent = forkParentFor(app.db, fork, actor);
5051 const converge = parent === undefined ? await convergeFollowed(app, fork, actor) : await convergeFork(app, fork, parent, actor);
@@ -67,7 +68,8 @@ export async function severForge(
6768 const who = requireUser(actor);
6869 if (!who.ok) return err("unauthorized");
6970 if ((await chainOfRepo(app, repo)) === undefined) {
70 // Not the forge's own code: an app that follows the repository it came from, or any upstream an admin set.
71 // Not the forge's own code: an app that follows the repository it came from, or any upstream an
72 // admin set.
7173 const upstream = getFollow(app.db, repo.id);
7274 if (upstream === undefined) return err("not_following");
7375 if (!canAdmin(app.db, repo, who.value) || !canWrite(app.db, repo, who.value)) return err("forbidden");
@@ -120,7 +122,10 @@ export function takeForgeWords(r: TakeForgeResult): { tone?: "danger"; message:
120122 return { message: "Already up to date." };
121123 }
122124
123 /** How a repository follows its parent now: the forge chain's record when it carries one, else the fork's own choice. */
125 /**
126 * How a repository follows its parent now: the forge chain's record when it carries one, else the
127 * fork's own choice.
128 */
124129 export async function followModeOf(app: App, repo: Repo): Promise<ForkFollowMode> {
125130 const link = await forgeLinkOf(app);
126131 if (link !== undefined && link.repo === `${repo.ownerName}/${repo.name}`) return link.mode;
@@ -169,7 +174,8 @@ export async function setFollowMode(
169174 const who = requireUser(actor);
170175 if (!who.ok) return err("unauthorized");
171176 const carries = (await chainOfRepo(app, repo)) !== undefined;
172 // A repository that is no fork but follows an upstream (an app a spawn sent down) takes the same choice.
177 // A repository that is no fork but follows an upstream (an app a spawn sent down) takes the same
178 // choice.
173179 const upstream = !carries && repo.forkParentId === null ? getFollow(app.db, repo.id) : undefined;
174180 if (!carries && repo.forkParentId === null && upstream === undefined) return err("not_following");
175181 if (!canAdmin(app.db, repo, who.value) || !canWrite(app.db, repo, who.value)) return err("forbidden");
@@ -297,8 +303,9 @@ export function takeWords(
297303 const words = "converge" in e ? convergeWords(e.converge, parentName) : { message: "" };
298304 return { tone: "danger", message: `${files}. ${words.message}` };
299305 }
306 if (e.kind === "upstream_moved") return { tone: "danger", message: `${parentName} has moved since you looked; nothing was taken.` };
300307 return {
301308 tone: "danger",
302 message: e.kind === "moved" ? "Something moved while this was read; try again." : `Git could not take the updates: ${e.message}`,
309 message: e.kind === "git" ? `Git could not take the updates: ${e.message}` : "Something moved while this was read; try again.",
303310 };
304311 }
src/actions/follow_incoming.ts added +47
@@ -0,0 +1,47 @@
1 /**

Both doors: no src/tui/ screen and no docs/features/ how-to for this feature.

2 * What taking a parent's update would bring, read before it is taken: the
3 * commits the parent's tip has that the fork's does not, newest first,
4 * bounded. One `git log` through the git module's own read, over two object
5 * ids git itself resolved, so no text a person typed reaches git.
6 */
7
8 import type { ForkRelation } from "../core/following.ts";
9 import type { Repo } from "../core/repos.ts";
10 import { commitLog } from "../git/read.ts";
11 import { isSafeOid } from "../git/guard.ts";
12 import { repoDir } from "../git/repos.ts";
13
14 /** How many commits the page lists; the rest are counted. */
15 export const INCOMING_CAP = 50;
16
17 export interface IncomingCommit {
18 readonly oid: string;
19 readonly subject: string;
20 readonly author: string;
21 /** ISO author date. */
22 readonly date: string;
23 }
24
25 export interface Incoming {
26 /** The parent tip these commits lead to: the one a take must be handed back. */
27 readonly tip: string;
28 readonly commits: readonly IncomingCommit[];
29 /** Commits beyond the cap, counted and not listed. */
30 readonly more: number;
31 }
32
33 /** The commits an update would bring; undefined when there are none or git cannot say. */
34 export async function incomingOf(
35 reposRoot: string,
36 fork: Repo,
37 relation: ForkRelation,
38 ): Promise<Incoming | undefined> {
39 if (relation.behind === 0 || relation.parent.detached !== null) return undefined;
40 if (!isSafeOid(relation.forkTip) || !isSafeOid(relation.parentTip)) return undefined;
41 // The parent's objects reach the fork through its alternates (`forkRelation`).
42 const dir = repoDir(reposRoot, fork.ownerName, fork.name);
43 const log = await commitLog(dir, `${relation.forkTip}..${relation.parentTip}`, { limit: INCOMING_CAP });
44 if (!log.ok) return undefined;
45 const commits = log.value.map((c) => ({ oid: c.oid, subject: c.subject, author: c.author, date: c.date }));
46 return { tip: relation.parentTip, commits, more: Math.max(0, relation.behind - commits.length) };
47 }
src/actions/forks.ts +3 −1
@@ -63,6 +63,8 @@ export async function takeUpdates(
6363 app: App,
6464 actor: User | undefined,
6565 fork: Repo,
66 /** The parent tip the owner was shown; refused when the parent has moved since. */
67 expect?: string,
6668 ): Promise<Result<ForkSync & { merged: boolean }, TakeUpdatesError>> {
6769 const writer = requireWriter(app, actor, fork);
6870 if (!writer.ok) return writer;
@@ -73,7 +75,7 @@ export async function takeUpdates(
7375 return take(app, fork, parent, {
7476 id: who.id,
7577 ...commitIdentity(app.config, who),
76 });
78 }, expect);
7779 }
7880
7981 export interface ForkDrift {
src/core/following.ts +35 −5
@@ -57,7 +57,10 @@ export interface Following {
5757 readonly db: Database;
5858 readonly reposRoot: string;
5959 readonly bus: EventBus;
60 /** Who a merge the forge makes for a fork's owner is written as; absent, a fork never merges by itself. */
60 /**
61 * Who a merge the forge makes for a fork's owner is written as; absent, a fork never merges by
62 * itself.
63 */
6164 readonly authorOf?: (userId: string) => (MergeIdentity & { readonly id: string }) | undefined;
6265 }
6366
@@ -189,7 +192,10 @@ export interface ForkRelation {
189192 readonly conflicts: readonly string[];
190193 readonly forkTip: string;
191194 readonly parentTip: string;
192 /** The one action that reconciles the two, and the words for it: the sync contract's (`describeLink`). */
195 /**
196 * The one action that reconciles the two, and the words for it: the sync contract's
197 * (`describeLink`).
198 */
193199 readonly action: Reconcile;
194200 readonly words: string;
195201 }
@@ -351,8 +357,19 @@ async function compare(
351357 export type TakeError =
352358 | { kind: "conflict"; files: readonly string[] }
353359 | { kind: "moved" }
360 /** The parent's tip is not the one the owner was shown; nothing was taken. */
361 | { kind: "upstream_moved"; tip: string; message: string }
354362 | { kind: "git"; message: string };
355363
364 /** What a refused take says; the tip it names is in `tip`. */
365 const MOVED = "the parent has moved since you looked; nothing was taken";
366
367 /** The parent's tip as it is now, for the refusal that says the owner's was stale. */
368 async function movedTip(forge: Following, parent: Repo): Promise<{ ok: false; error: TakeError }> {
369 const now = await resolveOid(repoDir(forge.reposRoot, parent.ownerName, parent.name), `refs/heads/${parent.defaultBranch}`);
370 return { ok: false, error: { kind: "upstream_moved", tip: now ?? "", message: MOVED } };
371 }
372
356373 /**
357374 * Take the parent's updates into the fork's default branch: a fast-forward
358375 * when the fork has nothing of its own, a merge commit when it has and git
@@ -365,9 +382,13 @@ export async function takeUpdates(
365382 fork: Repo,
366383 parent: Repo,
367384 author: MergeIdentity & { readonly id: string },
385 /** The parent tip the owner was shown; a take of any other tip is refused. */
386 expect?: string,
368387 ): Promise<Result<ForkSync & { merged: boolean }, TakeError>> {
369388 const relation = await forkRelation(forge, fork, parent);
370389 if (relation === undefined) return err({ kind: "git", message: "no parent" });
390 if (expect !== undefined && relation.parentTip !== expect)
391 return err({ kind: "upstream_moved", tip: relation.parentTip, message: MOVED });
371392 if (relation.state === "synced" || relation.state === "ahead")
372393 return ok({
373394 updated: false,
@@ -376,8 +397,9 @@ export async function takeUpdates(
376397 to: relation.forkTip,
377398 });
378399 if (relation.state === "behind") {
379 const moved = await fastForwardFork(forge, fork, parent, author.id);
400 const moved = await fastForwardFork(forge, fork, parent, author.id, expect);
380401 if (moved.ok) return ok({ ...moved.value, merged: false });
402 if (moved.error === "upstream_moved") return await movedTip(forge, parent);
381403 // Diverged between the read and the move: fall through to the merge.
382404 }
383405 const again = await forkRelation(forge, fork, parent);
@@ -394,6 +416,7 @@ export async function takeUpdates(
394416 `refs/heads/${parent.defaultBranch}`,
395417 );
396418 if (tip === undefined) return err({ kind: "git", message: "fetch failed" });
419 if (expect !== undefined && tip !== expect) return err({ kind: "upstream_moved", tip, message: MOVED });
397420 const ref = `refs/heads/${fork.defaultBranch}`;
398421 const landed = await merge(forkDir, {
399422 baseBranch: fork.defaultBranch,
@@ -561,7 +584,9 @@ export async function fastForwardFork(
561584 fork: Repo,
562585 parent: Repo,
563586 actorId: string | undefined,
564 ): Promise<Result<ForkSync, "diverged">> {
587 /** The parent tip the caller was shown: the fetch that lands any other moves nothing. */
588 expect?: string,
589 ): Promise<Result<ForkSync, "diverged" | "upstream_moved">> {
565590 const parentDir = repoDir(forge.reposRoot, parent.ownerName, parent.name);
566591 const forkDir = repoDir(forge.reposRoot, fork.ownerName, fork.name);
567592 const ref = `refs/heads/${fork.defaultBranch}`;
@@ -578,7 +603,9 @@ export async function fastForwardFork(
578603 parentDir,
579604 `refs/heads/${parent.defaultBranch}`,
580605 `refs/following/${parent.defaultBranch}`,
606 expect,
581607 );
608 if (!synced.ok && synced.error === "upstream-moved") return err("upstream_moved");
582609 if (!synced.ok) return ok({ updated: false, from: from ?? "", to });
583610 if (!synced.value.moved)
584611 return synced.value.judgement.state === "synced"
@@ -608,7 +635,10 @@ export interface LineageNode {
608635 readonly repo: Repo;
609636 /** Against this node's parent; absent on the root, and past the budget. */
610637 readonly relation: ForkRelation | undefined;
611 /** How it follows its parent, as stored (a fork that never chose has the default); absent on the root. */
638 /**
639 * How it follows its parent, as stored (a fork that never chose has the default); absent on the
640 * root.
641 */
612642 readonly mode?: ForkFollowMode;
613643 readonly children: readonly LineageNode[];
614644 }
src/http/api.ts +28 −16
@@ -211,7 +211,7 @@ import { diffCommit } from "../git/diff.ts";
211211 import { runGit } from "../git/env.ts";
212212 import { appLimitWords, appsOwnedBy } from "../actions/app_limit.ts";
213213 import { getQuota, quotaOf } from "../settings/quotas.ts";
214 import { isSafeRef, isSafeTreePath } from "../git/guard.ts";
214 import { isSafeOid, isSafeRef, isSafeTreePath } from "../git/guard.ts";
215215 import { compareBranches, listBranchRows } from "../git/branches.ts";
216216 import {
217217 NO_NAME_ERROR,
@@ -433,7 +433,11 @@ import { ANSWER_WORDS, ORDER_WORDS, VISIBILITY_WORDS } from "../core/arg_words.t
433433
434434 /** Take the parent's updates for `repo` and answer as the API does, for every route that asks. */
435435 export async function respondTake(ctx: Ctx, repo: Repo): Promise<Response> {
436 const took = await takeOrTell(ctx.app, ctx.auth.user, repo);
436 // An optional `tip` (a full object id) is the parent tip the caller was shown; any other is
437 // refused.
438 const tip = ctx.url.searchParams.get("tip") ?? undefined;
439 if (tip !== undefined && !isSafeOid(tip)) return apiError("invalid_tip", 422, "tip is a full commit id");
440 const took = await takeOrTell(ctx.app, ctx.auth.user, repo, tip);
437441 if (!took.ok) {
438442 const e = took.error;
439443 if (typeof e === "string")
@@ -454,9 +458,11 @@ export async function respondTake(ctx: Ctx, repo: Repo): Promise<Response> {
454458 return apiError(
455459 e.kind,
456460 409,
457 e.kind === "moved"
458 ? "something moved while this was read; try again"
459 : e.message,
461 e.kind === "git"
462 ? e.message
463 : e.kind === "upstream_moved"
464 ? `the parent has moved to ${e.tip}; nothing was taken`
465 : "something moved while this was read; try again",
460466 );
461467 }
462468 return json(took.value);
@@ -810,7 +816,9 @@ function editFailure(error: { kind: string } & Record<string, unknown>) {
810816 const ANCHOR_FORMAT =
811817 'An anchor is {"path": a file in the pull\'s diff, "line": its line number, "side": "new" (the head\'s numbering, for added or kept lines) or "old" (the base\'s, for removed lines)}; the line must be inside one of the diff\'s hunks: in `@@ -a,b +c,d @@` the hunk\'s first line is c on the new side and a on the old. GET …/pulls/N returns the diff.';
812818
813 /** A review's line comments as the API was sent them; undefined when they are not a list of objects. */
819 /**
820 * A review's line comments as the API was sent them; undefined when they are not a list of objects.
821 */
814822 function reviewLines(raw: unknown): ReviewInput[] | undefined {
815823 if (raw === undefined || raw === null) return [];
816824 // The cap is `submitReview`'s to refuse, by name (`too_many_lines`).
@@ -1969,7 +1977,8 @@ export function apiRoutes(router: Router<Handler>): void {
19691977 const from = at + 1;
19701978 const items = all.slice(from, from + limit);
19711979 const more = from + limit < all.length;
1972 // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so does the page.
1980 // The tag is of the exact bytes sent: a pushed, moved or deleted tag changes them, and so
1981 // does the page.
19731982 const text = JSON.stringify({ items, next_cursor: more ? items[items.length - 1]!.name : null });
19741983 const etag = weakEtag(text);
19751984 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
@@ -2419,8 +2428,8 @@ export function apiRoutes(router: Router<Handler>): void {
24192428 },
24202429 );
24212430 // One action on a whole limb (#733): defer, resume, or close as not
2422 // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a dry run by default with a
2423 // read credential, an admin token to apply, the receipt in
2431 // doing, or raise or lower it among its siblings (#1064). A fleet operation in every respect — a
2432 // dry run by default with a read credential, an admin token to apply, the receipt in
24242433 // /api/v1/fleet/ops/:id and its undo at …/undo.
24252434 router.add(
24262435 "POST",
@@ -2500,7 +2509,8 @@ export function apiRoutes(router: Router<Handler>): void {
25002509 const since = parseSince(ctx.url.searchParams.get("since"));
25012510 if (since === undefined) return apiError("invalid_since", 422, "since is day, week or month");
25022511 const scope = sealedScope(ctx.app.db, repo, ctx.auth.user);
2503 // Built by the map's worker, so the thread serves everything else meanwhile; a snapshot of this write clock answers at once.
2512 // Built by the map's worker, so the thread serves everything else meanwhile; a snapshot of this
2513 // write clock answers at once.
25042514 const got = await snapshotMap(ctx.app, { repoId: repo.id, scope, now: new Date() });
25052515 if (got === undefined) return notFound();
25062516 // The growth line is read here, not in the snapshot: it moves with the clock, not with writes.
@@ -2539,7 +2549,8 @@ export function apiRoutes(router: Router<Handler>): void {
25392549 });
25402550 });
25412551 // What people asked of the crew in the repositories the caller can write —
2542 // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts, the /asked page).
2552 // by default what has nothing merged yet, oldest first — and what became of each (core/asked.ts,
2553 // the /asked page).
25432554 router.add("GET", "/api/v1/asked", (ctx) => {
25442555 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
25452556 const denied = requireScope(ctx, "ro");
@@ -2658,8 +2669,8 @@ export function apiRoutes(router: Router<Handler>): void {
26582669 ...(states[i] ?? {}),
26592670 }));
26602671 });
2661 // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a 304;
2662 // the page, state, limit, cursor and fields are in the body or the query that chose it.
2672 // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a
2673 // 304; the page, state, limit, cursor and fields are in the body or the query that chose it.
26632674 return timePhase(ctx.request, "render", () => {
26642675 const text = JSON.stringify(paged(items, query.limit, (p) => p.number));
26652676 const etag = weakEtag(text);
@@ -2851,7 +2862,8 @@ export function apiRoutes(router: Router<Handler>): void {
28512862 ...(diff === undefined ? {} : { diff }),
28522863 hold: hold === undefined ? null : holdJson(hold),
28532864 });
2854 // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or merge is never hidden behind a 304.
2865 // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or
2866 // merge is never hidden behind a 304.
28552867 const etag = weakEtag(text);
28562868 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
28572869 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
@@ -3712,8 +3724,8 @@ export function apiRoutes(router: Router<Handler>): void {
37123724 return kept ? json(await beatAnswer(ctx.app, raw)) : apiError("not_found", 404, "no such door");
37133725 });
37143726
3715 // A child asking its parent to broker an origin sign-in (`spawn/origin_broker.ts`): signed with the
3716 // heartbeat key; every refusal is the same 404, so nothing says who is a child.
3727 // A child asking its parent to broker an origin sign-in (`spawn/origin_broker.ts`): signed with
3728 // the heartbeat key; every refusal is the same 404, so nothing says who is a child.
37173729 router.add("POST", "/api/v1/broker/origins", async (ctx) => {
37183730 const bytes = await readBounded(ctx.request, CALL_BODY_MAX);
37193731 if (bytes === "too_large") return apiError("not_found", 404, "no such door");
src/http/mcp/tools/take_updates.ts +10 −4
@@ -1,17 +1,21 @@
11 import { FAMILY_WORDS } from "../../../actions/family_words.ts";
22 import { convergeWords, takeForgeCode, takeForgeWords, takeOrTell } from "../../../actions/follow.ts";
3 import { isSafeOid } from "../../../git/guard.ts";
34 import { chainOfRepo } from "../../../spawn/chain.ts";
45 import { forkParentFor } from "../../../core/repos.ts";
56 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
67
78 export const tool: Tool = {
89 name: "take_updates",
9 doc: "`{ repo }`: a fork takes its parent's updates when git can do it alone; a conflict is refused. On a spawned forge's code repository it opens the one `forge/take-updates` pull and never moves the default branch",
10 doc: "`{ repo, tip? }`: a fork takes its parent's updates when git can do it alone; a conflict is refused; with `tip`, refused when the parent has moved past it. On a spawned forge's code repository it opens the one `forge/take-updates` pull and never moves the default branch",
1011 description:
1112 "Take the parent forge's updates into a fork.",
1213 inputSchema: {
1314 type: "object",
14 properties: { repo: REPO_ARG },
15 properties: {
16 repo: REPO_ARG,
17 tip: { type: "string", description: "The parent tip you were shown; refused if it moved." },
18 },
1519 required: ["repo"],
1620 },
1721 writes: true,
@@ -26,7 +30,9 @@ export const tool: Tool = {
2630 ? bad("not_following", FAMILY_WORDS.not_following)
2731 : bad(across.error, "only this repository's admin can take the parent forge's code");
2832 }
29 const took = await takeOrTell(ctx.app, user, repo);
33 const tip = typeof args.tip === "string" ? args.tip : undefined;
34 if (tip !== undefined && !isSafeOid(tip)) return bad("invalid_tip", "tip is a full commit id");
35 const took = await takeOrTell(ctx.app, user, repo, tip);
3036 if (took.ok)
3137 return good({
3238 says: !took.value.updated
@@ -53,7 +59,7 @@ export const tool: Tool = {
5359 )
5460 : bad(
5561 e.kind,
56 e.kind === "moved" ? "something moved; try again" : e.message,
62 e.kind === "git" ? e.message : e.kind === "upstream_moved" ? `the parent has moved to ${e.tip}; nothing was taken` : "something moved; try again",
5763 );
5864 },
5965 };
src/tui/screens/forks.ts +17 −2
@@ -23,6 +23,7 @@ import {
2323 } from "../../actions/forks.ts";
2424 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";
26 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
2627 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
2728 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
2829 import type { Pull } from "../../core/pulls.ts";
@@ -141,12 +142,25 @@ export function takeOffer(
141142 return `Both sides changed ${relation.conflicts.join(", ")}: the crew is told on a converge issue.`;
142143 }
143144
145 /** The commits a take would bring, one line each, as the confirm shows them (at most eight). */
146 export function incomingLines(incoming: Incoming | undefined): string[] {
147 if (incoming === undefined) return [];
148 const shown = incoming.commits.slice(0, 8);
149 const rest = incoming.commits.length - shown.length + incoming.more;
150 return [
151 ...shown.map((c) => `${c.oid.slice(0, 7)} ${c.subject}`),
152 ...(rest > 0 ? [`and ${rest} more`] : []),
153 ];
154 }
155
144156 export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
145157 let ranked: ForkRanking | undefined;
146158 let tree: ForkNode[] = [];
147159 let following: ForkRow[] = [];
148160 let relation: ForkRelation | undefined;
149161 let offer: string | undefined;
162 /** The commits an update would bring and the tip they lead to: what a take is handed back. */
163 let incoming: Incoming | undefined;
150164 /** What the repository follows by address, when it has no parent here. */
151165 let followed: ReturnType<typeof followedAs> | undefined;
152166 let open: Pull | undefined;
@@ -201,6 +215,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
201215 tree = forkTree(f.db, repo.id, f.user);
202216 relation = await relationOf(f.app, f.user, repo);
203217 open = relation === undefined ? undefined : openProposal(f.app, repo, relation.parent);
218 incoming = relation === undefined ? undefined : await incomingOf(f.app.reposRoot, repo, relation);
204219 const address = relation === undefined ? followedOf(f.app, repo) : undefined;
205220 followed = address === undefined ? undefined : followedAs(address);
206221 offer =
@@ -224,13 +239,13 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
224239 ctx.push(
225240 confirmScreen(ctx, self, {
226241 title: "Take updates",
227 body: [offer],
242 body: [offer, ...incomingLines(incoming)],
228243 actions: [{ label: "Take updates" }, { label: "Cancel", variant: "ghost" }],
229244 yesNo: true,
230245 onChoose: (choice) => {
231246 if (choice !== 0) return;
232247 runAsync(ctx, async () => {
233 const took = await takeOrTell(f.app, f.user, repo);
248 const took = await takeOrTell(f.app, f.user, repo, incoming?.tip);
234249 const words = takeWords(took, repo, parent);
235250 await read();
236251 // The converge issue just opened or found is the line Enter opens.
src/web/pages/following.ts +38 −5
@@ -42,13 +42,14 @@ import type { ForkFollowMode } from "../../core/fork_follow.ts";
4242 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
4343 import { convergeWords, followModeOf, takeOrTell, takeWords } from "../../actions/follow.ts";
4444 import { FOLLOW_WORD, FOLLOWS_NOTHING, HIDDEN_FORK_WORD, proposeRefusalWords } from "../../actions/follow_words.ts";
45 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
4546 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
4647 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
4748 import { proposesViaFork } from "../../origins/fork-route.ts";
4849 import { field, readForm } from "../form.ts";
4950 import { html, when, type Html } from "../html.ts";
5051 import { flashOrJson } from "../layout.ts";
51 import { badge, btn, icon, row, type Tone } from "../ui.ts";
52 import { badge, btn, icon, row, timeAgo, type Tone } from "../ui.ts";
5253 import { disconnectedOn } from "./frozen.ts";
5354
5455 /**
@@ -63,7 +64,8 @@ export function lineageCard(lineage: Lineage, hereId: string, viewerId?: string)
6364 const here = n.repo.id === hereId;
6465 const trail = [
6566 here ? badge("you are here", { variant: "outline" }) : null,
66 // The viewer's own forks say "you" in words. aria-current stays on the one row being looked at.
67 // The viewer's own forks say "you" in words. aria-current stays on the one row being looked
68 // at.
6769 !here && viewerId !== undefined && n.repo.ownerId === viewerId ? badge("you", { variant: "outline" }) : null,
6870 depth === 0 && lineage.hiddenParent ? html`<span class="muted small">${HIDDEN_FORK_WORD}</span>` : null,
6971 n.mode === undefined ? null : html`<span class="muted small">${FOLLOW_WORD[n.mode]}</span>`,
@@ -102,6 +104,8 @@ export interface Following {
102104 readonly releases: { url: string; view: ParentReleases } | undefined;
103105 /** How this repository follows its parent (`followModeOf`). */
104106 readonly mode: ForkFollowMode;
107 /** What an update would bring, newest first and capped; absent when level. */
108 readonly incoming: Incoming | undefined;
105109 }
106110
107111 /** Everything the card needs, for a repo that follows something. */
@@ -129,7 +133,13 @@ export async function followingOf(
129133 loopback: ctx.app.config.parentLoopback === true,
130134 }),
131135 };
132 return { relation, converge, releases, mode: await followModeOf(ctx.app, repo) };
136 return {
137 relation,
138 converge,
139 releases,
140 mode: await followModeOf(ctx.app, repo),
141 incoming: await incomingOf(ctx.app.reposRoot, repo, relation),
142 };
133143 }
134144
135145 /** The parent, when the viewer may read it and an admin has archived it. */
@@ -226,6 +236,21 @@ export function relationSentence(relation: ForkRelation): string {
226236 }
227237 }
228238
239 /** The commits an update would bring: subject, author, age; the rest of a long list counted. */
240 function incomingList(incoming: Incoming): Html {
241 return html`<ul class="list" data-incoming aria-label="Commits an update would bring">
242 ${incoming.commits.map((c) =>
243 row({
244 title: c.subject === "" ? c.oid.slice(0, 7) : c.subject,
245 meta: html`<span class="mono">${c.oid.slice(0, 7)}</span> · ${c.author} · ${timeAgo(c.date)}`,
246 }),
247 )}
248 ${incoming.more > 0
249 ? html`<li class="muted small" data-incoming-more>and ${incoming.more} more</li>`
250 : null}
251 </ul>`;
252 }
253
229254 /**
230255 * The card on a fork's home. `studio` swaps nothing but the words for the
231256 * crew's part; the mechanics are one and the same.
@@ -234,7 +259,10 @@ export function followingCard(
234259 ctx: Ctx,
235260 repo: Repo,
236261 following: Following,
237 /** `bare` drops the card's margin; `family: false` drops the link to the forks page, for the forks page itself. */
262 /**
263 * `bare` drops the card's margin; `family: false` drops the link to the forks page, for the forks
264 * page itself.
265 */
238266 o: { bare?: boolean; family?: boolean } = {},
239267 ): Html {
240268 const { relation, converge } = following;
@@ -257,6 +285,7 @@ export function followingCard(
257285 actions.push(
258286 html`<form method="post" action="${base}/following">
259287 <input type="hidden" name="do" value="take" />
288 <input type="hidden" name="tip" value="${following.incoming?.tip ?? relation.parentTip}" />
260289 ${btn("Take updates", {
261290 size: "sm",
262291 type: "submit",
@@ -405,6 +434,7 @@ export function followingCard(
405434 >
406435 <div class="bar"><h2>${head}</h2></div>
407436 <div class="stack">${prose}</div>
437 ${following.incoming === undefined ? null : incomingList(following.incoming)}
408438 ${when(
409439 rows.length > 0,
410440 () => html`<ul class="list">
@@ -479,6 +509,9 @@ export async function followingSubmit(ctx: Ctx): Promise<Response> {
479509 );
480510 }
481511
482 const took = await takeOrTell(ctx.app, ctx.auth.user, repo);
512 // The tip the page showed: a take applies that one, or nothing.
513 const shown = field(form, "tip");
514 const expect = /^[0-9a-f]{40,64}$/.test(shown) ? shown : undefined;
515 const took = await takeOrTell(ctx.app, ctx.auth.user, repo, expect);
483516 return flashOrJson(ctx, base, takeWords(took, repo, parent));
484517 }
test/following-incoming.test.ts added +128
@@ -0,0 +1,128 @@
1 /**
2 * An update is an offer the owner reads first (#13144): the commits it
3 * brings are listed above Take, capped with the rest counted, and Take
4 * applies the tip that was shown or nothing.
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 { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser, getUserByName } from "../src/core/users.ts";
15 import { resolveOid } from "../src/git/merge.ts";
16 import { repoDir } from "../src/git/repos.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { promote } from "./helpers/members.ts";
19
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let cookie = "";
24
25 const commit = async (who: string, path: string, message: string) => {
26 const user = getUserByName(app.db, who)!;
27 const r = getRepo(app.db, who, "lib")!;
28 const done = await commitToBranch(app, user, r, { message, files: [{ path, content: `${message}\n` }] });
29 if (!done.ok) throw new Error(JSON.stringify(done.error));
30 };
31 const page = async () => (await fetch(`${servers.url}/bob/lib`, { headers: { cookie } })).text();
32 const waitFor = async (want: string) => {
33 let p = "";
34 for (let i = 0; i < 125 && !p.includes(want); i++) {
35 p = await page();
36 if (!p.includes(want)) await Bun.sleep(40); // real-timer: polls a live server until the page shows the commit
37 }
38 if (!p.includes(want)) throw new Error(`never came: ${want}`);
39 return p;
40 };
41 const tipOf = (p: string) => p.match(/name="tip" value="([0-9a-f]+)"/)![1]!;
42 const take = (tip?: string) =>
43 fetch(`${servers.url}/bob/lib/following`, {
44 method: "POST",
45 headers: { cookie, origin: servers.url },
46 body: new URLSearchParams({ do: "take", ...(tip === undefined ? {} : { tip }) }),
47 redirect: "manual",
48 });
49 const forkTip = () => resolveOid(repoDir(app.reposRoot, "bob", "lib"), "refs/heads/main");
50
51 beforeAll(async () => {
52 dataDir = await mkdtemp(join(tmpdir(), "forge-following-incoming-"));
53 app = createApp({ dataDir, port: 0 });
54 servers = await serve(app);
55 const alice = await createUser(app.db, {
56 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
57 password: "a-good-passphrase", adminIfFirst: true,
58 });
59 if (!alice.ok) throw new Error(alice.error);
60 const lib = await createRepo(app, alice.value, { name: "lib", visibility: "public" });
61 if (!lib.ok) throw new Error(String(lib.error));
62 await commit("alice", "README.md", "Start");
63 const bob = await createUser(app.db, {
64 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
65 });
66 if (!bob.ok) throw new Error(bob.error);
67 promote(app.db, bob.value);
68 const forked = await forkRepo(app, bob.value, lib.value);
69 if (!forked.ok) throw new Error(String(forked.error));
70 cookie = `forge_session=${createSession(app.db, bob.value.id).token}`;
71 await commit("bob", "mine.txt", "Bob's own work");
72 }, 60_000);
73
74 afterAll(async () => {
75 servers.stop();
76 app.close();
77 await rm(dataDir, { recursive: true, force: true });
78 });
79
80 test("the page lists the commits an update brings, above Take", async () => {
81 await commit("alice", "a.txt", "Add <b>a</b>");
82 await commit("alice", "b.txt", "Add b");
83 const p = await waitFor("data-incoming");
84 const list = p.match(/<ul class="list" data-incoming[\s\S]*?<\/ul>/)![0];
85 expect(list).toContain("Add b");
86 expect(list).toContain("Add &lt;b&gt;a&lt;/b&gt;");
87 expect(list).not.toContain("<b>a</b>");
88 expect(list).toContain("alice");
89 expect(list).toMatch(/ago|just now/);
90 expect(list).not.toContain("Bob&#39;s own work");
91 expect(list).not.toContain("data-incoming-more");
92 expect(p.indexOf("data-incoming")).toBeLessThan(p.indexOf('value="take"'));
93 }, 30_000);
94
95 test("Take applies the previewed tip; when upstream moved it refuses and shows the new list", async () => {
96 const shown = tipOf(await waitFor("data-incoming"));
97 const before = await forkTip();
98 await commit("alice", "c.txt", "Added after the look");
99 const stale = await take(shown);
100 expect(stale.status).toBe(303);
101 expect(await forkTip()).toBe(before);
102 // The refusal rides the redirect's flash cookie; the page it lands on shows the new list.
103 const flash = (stale.headers.get("set-cookie") ?? "").split(";")[0]!;
104 const landed = await fetch(`${servers.url}${stale.headers.get("location")}`, { headers: { cookie: `${cookie}; ${flash}` } });
105 expect(await landed.text()).toContain("has moved since you looked");
106 const p = await waitFor("Added after the look");
107 expect(tipOf(p)).not.toBe(shown);
108 }, 30_000);
109
110 test("Take with the new tip takes exactly it", async () => {
111 const p = await waitFor("Added after the look");
112 const shown = tipOf(p);
113 const taken = await take(shown);
114 expect(taken.status).toBe(303);
115 const upstream = await resolveOid(repoDir(app.reposRoot, "alice", "lib"), "refs/heads/main");
116 expect(upstream).toBe(shown);
117 const after = await page();
118 expect(after).not.toContain("data-incoming");
119 }, 30_000);
120
121 test("a long list is capped at fifty and the rest counted", async () => {
122 await commit("bob", "own2.txt", "Bob again");
123 for (let i = 0; i < 52; i++) await commit("alice", `n${i}.txt`, `Change ${i}`);
124 const p = await waitFor("data-incoming-more");
125 const list = p.match(/<ul class="list" data-incoming[\s\S]*?<\/ul>/)![0];
126 expect(list.match(/Change \d+/g)!.length).toBe(50);
127 expect(list).toContain("and 2 more");
128 }, 120_000);
test/take-expect.test.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * A take applies the parent tip the owner was shown, or nothing, at every
3 * door (#13144): the API and MCP accept a `tip`, the terminal hands back the
4 * one it listed, and a fast-forward applies the previewed id rather than one
5 * fetched a moment later.
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 { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { fastForwardFork } from "../src/core/following.ts";
14 import { setForkFollowMode } from "../src/core/fork_follow.ts";
15 import { getRepo } from "../src/core/repos.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, getUserByName } from "../src/core/users.ts";
18 import { resolveOid } from "../src/git/merge.ts";
19 import { repoDir } from "../src/git/repos.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { incomingLines } from "../src/tui/screens/forks.ts";
22 import { mcpTool } from "./helpers/mcp.ts";
23 import { promote } from "./helpers/members.ts";
24
25 let dataDir: string;
26 let app: App;
27 let servers: Servers;
28 let token = "";
29
30 const commit = async (who: string, repo: string, path: string, message: string) => {
31 const user = getUserByName(app.db, who)!;
32 const done = await commitToBranch(app, user, getRepo(app.db, who, repo)!, {
33 message,
34 files: [{ path, content: `${message}\n` }],
35 });
36 if (!done.ok) throw new Error(JSON.stringify(done.error));
37 };
38 const tipOf = (owner: string, name: string) => resolveOid(repoDir(app.reposRoot, owner, name), "refs/heads/main");
39 const STALE = "1".repeat(40);
40
41 beforeAll(async () => {
42 dataDir = await mkdtemp(join(tmpdir(), "forge-take-expect-"));
43 app = createApp({ dataDir, port: 0 });
44 servers = await serve(app);
45 const alice = await createUser(app.db, {
46 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
47 password: "a-good-passphrase", adminIfFirst: true,
48 });
49 if (!alice.ok) throw new Error(alice.error);
50 const bob = await createUser(app.db, {
51 origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase",
52 });
53 if (!bob.ok) throw new Error(bob.error);
54 promote(app.db, bob.value);
55 token = createToken(app.db, bob.value.id, "t", "admin").token;
56 for (const name of ["lib", "ff"]) {
57 const r = await createRepo(app, alice.value, { name, visibility: "public" });
58 if (!r.ok) throw new Error(String(r.error));
59 await commit("alice", name, "README.md", "Start");
60 const forked = await forkRepo(app, bob.value, r.value);
61 if (!forked.ok) throw new Error(String(forked.error));
62 await commit("alice", name, "next.txt", "Next");
63 }
64 }, 60_000);
65
66 afterAll(async () => {
67 servers.stop();
68 app.close();
69 await rm(dataDir, { recursive: true, force: true });
70 });
71
72 const post = (repo: string, tip?: string) =>
73 fetch(`${servers.url}/api/v1/repos/bob/${repo}/following/take${tip === undefined ? "" : `?tip=${tip}`}`, {
74 method: "POST",
75 headers: { authorization: `Bearer ${token}` },
76 });
77
78 test("the API refuses a tip that is not the parent's, and a malformed one, and takes nothing", async () => {
79 const before = await tipOf("bob", "lib");
80 const stale = await post("lib", STALE);
81 expect(stale.status).toBe(409);
82 expect(((await stale.json()) as { error: string }).error).toBe("upstream_moved");
83 expect((await post("lib", "main")).status).toBe(422);
84 expect(await tipOf("bob", "lib")).toBe(before);
85 });
86
87 test("MCP take_updates refuses a stale tip and takes nothing", async () => {
88 const before = await tipOf("bob", "lib");
89 const r = await mcpTool(servers.url, token, "take_updates", { repo: "bob/lib", tip: STALE });
90 expect(r.error).toContain("nothing was taken");
91 expect((await mcpTool(servers.url, token, "take_updates", { repo: "bob/lib", tip: "nope" })).error).toContain("full commit id");
92 expect(await tipOf("bob", "lib")).toBe(before);
93 });
94
95 test("the API takes the tip it is given when that is the parent's", async () => {
96 const shown = (await tipOf("alice", "lib"))!;
97 const took = await post("lib", shown);
98 expect(took.status).toBe(200);
99 expect(await tipOf("bob", "lib")).toBe(shown);
100 });
101
102 test("a fast-forward applies the previewed id: a parent that moved after it is not taken", async () => {
103 const shown = (await tipOf("alice", "ff"))!;
104 const fork = getRepo(app.db, "bob", "ff")!;
105 // The forge's own follow would move the fork by itself; this fork chose not to.
106 setForkFollowMode(app.db, fork.id, "dont-follow");
107 await commit("alice", "ff", "later.txt", "Later");
108 const parent = getRepo(app.db, "alice", "ff")!;
109 const before = await tipOf("bob", "ff");
110 const moved = await fastForwardFork(app, fork, parent, undefined, shown);
111 expect(moved).toEqual({ ok: false, error: "upstream_moved" });
112 expect(await tipOf("bob", "ff")).toBe(before);
113 const now = (await tipOf("alice", "ff"))!;
114 const landed = await fastForwardFork(app, fork, parent, undefined, now);
115 expect(landed.ok).toBe(true);
116 expect(await tipOf("bob", "ff")).toBe(now);
117 });
118
119 test("the terminal's confirm lists the commits, eight at most, and counts the rest", () => {
120 const c = (i: number) => ({ oid: `${i}`.padStart(40, "a"), subject: `Change ${i}`, author: "alice", date: "2026-01-01T00:00:00Z" });
121 expect(incomingLines(undefined)).toEqual([]);
122 const lines = incomingLines({ tip: "t", commits: Array.from({ length: 10 }, (_, i) => c(i)), more: 5 });
123 expect(lines.length).toBe(9);
124 expect(lines[0]).toContain("Change 0");
125 expect(lines[8]).toBe("and 7 more");
126 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs