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

A fork severed more than seven days ago rejoins its former upstream in one tap, with the follow mode it had #16089

Merged opened this

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

Merged

torque/forge:torque/16064-a-fork-severed-more-than-seven-days-ago → main 0 commits fork

  • Merged. torque/16064-a-fork-severed-more-than-seven-days-ago was merged into main as 1b1befb.

Review

Sign in to review this change.
13 files changed +507 −32
docs/features/fork-rejoin.md added +14
@@ -0,0 +1,14 @@
1 ---
2 topic: Ship and undo
3 row: A severed fork rejoins its former parent
4 ---
5 # A severed fork rejoins its former parent (#16064)
6
7 Undo lasts seven days. After that, an admin of the fork can still follow the former parent again, at any age, as long as that parent exists and they can read it. The fork comes back with the follow mode it had when it was severed (the sever records it); a sever from before that was recorded rejoins with the default mode ("tell me") and says so. Undo restores the recorded mode too, and leaves the mode as it is when none was recorded.
8
9 - Web: on a fork that is on its own, the line "On its own since …" shows "Rejoin owner/name" once the Undo window has closed (inside it, only Undo shows). It goes through `/-/confirm`, then a POST to `/:owner/:name/settings/detach/rejoin`; it works without JavaScript. The parent is named only when you can read it; otherwise "Follow upstream again" in Settings is what shows.
10 - Terminal: on the fork's About screen, `U` asks, then rejoins (inside the Undo window `U` is the Undo).
11 - MCP: `detach` with `{ repo, rejoin: true, confirm: true }`; without `confirm: true` it only says what it would do. It needs an admin token and is never an agent's.
12 - Refusals are the Undo's: not an admin, an agent, a repack running, the parent gone or unreadable.
13 - The parent, the mode and the `repo.reattached` event are set in one guarded step: if it throws, the git link is undone and the error surfaces, so the fork is not left half-rejoined.
14 - Code: `rejoinParent` in `src/actions/sever_undo.ts`; tests in `test/fork-rejoin.test.ts` and `test/fork-rejoin-doors.test.ts`.
src/actions/detach.ts +2 −1
@@ -10,6 +10,7 @@
1010 */
1111
1212 import type { App } from "../app.ts";
13 import { forkFollowMode } from "../core/fork_follow.ts";
1314 import { clearForkParent, forkParentFor, type Repo } from "../core/repos.ts";
1415 import type { User } from "../core/users.ts";
1516 import { detachFork, hasAlternates, repoDir } from "../git/repos.ts";
@@ -118,7 +119,7 @@ async function run(
118119 kind: "repo.detached",
119120 repoId: repo.id,
120121 actorId,
121 payload: { parentId },
122 payload: { parentId, mode: forkFollowMode(app.db, repo.id) },
122123 });
123124 }
124125
src/actions/detach_words.ts +7 −1
@@ -20,16 +20,22 @@ export const UNDO_RECEIPT = "undid a severing: the fork follows its upstream aga
2020 * The way back, for every door: Undo restores following within seven days; after that Settings ›
2121 * Follow upstream can follow an address.
2222 */
23 export const DETACH_AGAIN = `Undo restores following for ${UNDO_DAYS} days; after that, Settings › Follow upstream can follow its address.`;
23 export const DETACH_AGAIN = `Undo restores following for ${UNDO_DAYS} days; after that, Rejoin follows the parent again with the mode it had, for as long as the parent exists and you can read it.`;
2424 /** What an undo keeps and does, said after it. */
2525 export const UNDO_DONE = "Following is restored: updates from the parent flow down and offers can go up again. Whatever the parent changed meanwhile arrives as an update; offers made before the sever are listed again.";
2626 /** What an undo asks before it follows again (the terminal's confirm). */
2727 export const UNDO_ASKS = "Follow the parent again: updates flow down and offers can go up. Offers made before the sever are listed again.";
28 /** What a rejoin asks before it follows again (the confirm page and the terminal). */
29 export const REJOIN_ASKS = "Follow the former parent again: updates flow down and offers can go up. Offers made before the sever are listed again.";
30 /** What a rejoin did, and the mode it came back with. */
31 export const rejoinDone = (mode: string, known: boolean): string =>
32 `${UNDO_DONE} Follow mode: ${mode}${known ? ", as it was when it was severed" : " (the default: the sever did not record the mode it had)"}.`;
2833 /** Why an undo is refused, by reason. */
2934 export const UNDO_REFUSALS = {
3035 unauthorized: "sign in to undo a severing",
3136 forbidden: "only this repository's admin undoes a severing",
3237 nothing_to_undo: `there is no severing to undo: none was made, it was undone, or it is more than ${UNDO_DAYS} days old`,
3338 parent_gone: "the parent is gone or is not readable by you, so there is nothing to follow again",
39 not_severed: "there is no severing to rejoin: this repository was never severed from a parent, or it follows one again",
3440 running: "the sever is still copying objects; try again when it has finished",
3541 } as const;
src/actions/sever_undo.ts +81 −13
@@ -7,6 +7,7 @@
77
88 import type { Database } from "bun:sqlite";
99 import type { App } from "../app.ts";
10 import { FORK_DEFAULT_MODE, forkFollowMode, isForkFollowMode, setForkFollowMode, type ForkFollowMode } from "../core/fork_follow.ts";
1011 import { canAdmin, canRead, forkParentFor, getRepoById, restoreForkParent, visibleForks, type Repo } from "../core/repos.ts";
1112 import type { User } from "../core/users.ts";
1213 import { relinkFork, repoDir, unlinkFork } from "../git/repos.ts";
@@ -64,8 +65,18 @@ export interface UndoableSever {
6465 readonly until: string;
6566 }
6667
67 /** The standing severing of this fork that may still be undone, or undefined. */
68 export function undoableSever(app: App, repo: Repo, now: number = Date.now()): UndoableSever | undefined {
68 /**
69 * A standing severing of any age: the parent it left, when, and the follow mode it had (null: not
70 * recorded).
71 */
72 export interface Severed {
73 readonly parentId: string;
74 readonly at: string;
75 readonly mode: ForkFollowMode | null;
76 }
77
78 /** The standing severing of this fork, however old, or undefined. */
79 export function severedFrom(app: App, repo: Repo): Severed | undefined {
6980 if (repo.forkParentId !== null) return undefined;
7081 const last = app.db
7182 .query<{ kind: string; payload: string; created_at: string }, [string]>(
@@ -74,35 +85,92 @@ export function undoableSever(app: App, repo: Repo, now: number = Date.now()): U
7485 )
7586 .get(repo.id);
7687 if (last === null || last.kind !== "repo.detached") return undefined;
77 const parentId = (JSON.parse(last.payload) as { parentId?: unknown }).parentId;
78 const at = Date.parse(last.created_at);
79 if (typeof parentId !== "string" || !(now - at < UNDO_DAYS * DAY_MS)) return undefined;
80 return { parentId, at: last.created_at, until: new Date(at + UNDO_DAYS * DAY_MS).toISOString() };
88 const p = JSON.parse(last.payload) as { parentId?: unknown; mode?: unknown };
89 if (typeof p.parentId !== "string") return undefined;
90 return { parentId: p.parentId, at: last.created_at, mode: isForkFollowMode(p.mode) ? p.mode : null };
91 }
92
93 /** The severing `s`, if it is still within the undo window. */
94 function withinUndo(s: Severed | undefined, now: number): UndoableSever | undefined {
95 const at = s === undefined ? NaN : Date.parse(s.at);
96 if (s === undefined || !(now - at < UNDO_DAYS * DAY_MS)) return undefined;
97 return { parentId: s.parentId, at: s.at, until: new Date(at + UNDO_DAYS * DAY_MS).toISOString() };
98 }
99
100 /** The standing severing of this fork that may still be undone, or undefined. */
101 export function undoableSever(app: App, repo: Repo, now: number = Date.now()): UndoableSever | undefined {
102 return withinUndo(severedFrom(app, repo), now);
103 }
104
105 /** The former parent, only while it exists and `viewer` may read it. */
106 export function rejoinableParent(app: App, repo: Repo, viewer: User | undefined): Repo | undefined {
107 const s = severedFrom(app, repo);
108 const parent = s === undefined ? undefined : getRepoById(app.db, s.parentId);
109 return parent !== undefined && canRead(app.db, parent, viewer) ? parent : undefined;
81110 }
82111
83112 export type UndoError = keyof typeof UNDO_REFUSALS;
84113
85 /** Follow the parent again: an admin of the fork only; the history records it. */
114 /**
115 * Follow the parent again within seven days: an admin of the fork only; the history records it. The
116 * follow mode the sever recorded comes back too, as with a rejoin; one it did not record is left
117 * as it is.
118 */
86119 export async function undoSever(app: App, actor: User | undefined, repo: Repo): Promise<Result<UndoableSever, UndoError>> {
120 const s = severedFrom(app, repo);
121 const undo = withinUndo(s, Date.now());
122 const done = await relink(app, actor, repo, undo === undefined ? undefined : s, "nothing_to_undo", false);
123 if (!done.ok) return done;
124 return undo === undefined ? err("nothing_to_undo") : ok(undo);
125 }
126
127 /**
128 * What a rejoin restored: the parent and the mode, and whether the sever had recorded that mode.
129 */
130 export interface Rejoined {
131 readonly parent: Repo;
132 readonly mode: ForkFollowMode;
133 readonly modeKnown: boolean;
134 }
135
136 /**
137 * Follow the former parent again at any age, with the mode the fork had; the same refusals as the
138 * undo.
139 */
140 export async function rejoinParent(app: App, actor: User | undefined, repo: Repo): Promise<Result<Rejoined, UndoError>> {
141 const done = await relink(app, actor, repo, severedFrom(app, repo), "not_severed", true);
142 if (!done.ok) return done;
143 return ok({ parent: done.value.parent, mode: done.value.mode, modeKnown: done.value.modeKnown });
144 }
145
146 async function relink(
147 app: App,
148 actor: User | undefined,
149 repo: Repo,
150 s: Severed | undefined,
151 none: "nothing_to_undo" | "not_severed",
152 defaultMode: boolean,
153 ): Promise<Result<Rejoined, UndoError>> {
87154 if (actor === undefined) return err("unauthorized");
88155 // The sever is never an agent's (`detachFromParent`): neither is its undo.
89156 if (actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("forbidden");
90157 if (detachJob(repo.id)?.phase === "repacking") return err("running");
91 const undo = undoableSever(app, repo);
92 if (undo === undefined) return err("nothing_to_undo");
93 const parent = getRepoById(app.db, undo.parentId);
158 if (s === undefined) return err(none);
159 const parent = getRepoById(app.db, s.parentId);
94160 if (parent === undefined || !canRead(app.db, parent, actor)) return err("parent_gone");
95161 // The fork owns its objects but not what the parent made since: borrow them again, so the next
96162 // take reads them. A failure anywhere after that leaves the sever as it was.
97163 const forkDir = repoDir(app.reposRoot, repo.ownerName, repo.name);
98164 const linked = await relinkFork(forkDir, repoDir(app.reposRoot, parent.ownerName, parent.name));
99165 if (!linked.ok) return err("parent_gone");
166 const mode = s.mode ?? (defaultMode ? FORK_DEFAULT_MODE : forkFollowMode(app.db, repo.id));
100167 try {
101 restoreForkParent(app.db, repo.id, undo.parentId);
102 app.bus.append({ kind: "repo.reattached", repoId: repo.id, actorId: actor.id, payload: { parentId: undo.parentId } });
168 restoreForkParent(app.db, repo.id, s.parentId);
169 if (s.mode !== null || defaultMode) setForkFollowMode(app.db, repo.id, mode);
170 app.bus.append({ kind: "repo.reattached", repoId: repo.id, actorId: actor.id, payload: { parentId: s.parentId } });
103171 } catch (e) {
104172 await unlinkFork(forkDir);
105173 throw e;
106174 }
107 return ok(undo);
175 return ok({ parent, mode, modeKnown: s.mode !== null });
108176 }
src/http/mcp/tools/detach.ts +11 −3
@@ -1,12 +1,12 @@
11 import { scopeAllows } from "../../../core/tokens.ts";
22 import { detachFromParent, detachJob, detachPlanWords } from "../../../actions/detach.ts";
3 import { severPreview, undoSever } from "../../../actions/sever_undo.ts";
4 import { UNDO_DONE, UNDO_REFUSALS } from "../../../actions/detach_words.ts";
3 import { rejoinParent, severPreview, undoSever } from "../../../actions/sever_undo.ts";
4 import { REJOIN_ASKS, UNDO_DONE, rejoinDone, UNDO_REFUSALS } from "../../../actions/detach_words.ts";
55 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
66
77 export const tool: Tool = {
88 name: "detach",
9 doc: "`{ repo, confirm?, dryRun?, undo? }`: sever a fork from its parent — repack so it owns its objects, drop the link; without `confirm: true` (or with `dryRun: true`) it only says what stops and who is affected; the repack runs on its own, so call again to read its `phase` (`repacking`, `failed`) until the fork has no `parent`; `undo: true` follows the parent again within 7 days; only the repository's admin with an admin token, never an agent",
9 doc: "`{ repo, confirm?, dryRun?, undo?, rejoin? }`: sever a fork from its parent — repack so it owns its objects, drop the link; without `confirm: true` (or with `dryRun: true`) it says what stops and who is hit; the repack runs on its own; call again to read its `phase` until the fork has no `parent`; `rejoin: true, confirm: true` follows the former parent again at any age; `undo: true` does so within 7 days; only the repository's admin with an admin token, never an agent",
1010 description: "Detach a fork from its parent. Plans first; admin token.",
1111 inputSchema: {
1212 type: "object",
@@ -15,6 +15,7 @@ export const tool: Tool = {
1515 dryRun: { type: "boolean" },
1616 confirm: { type: "boolean" },
1717 undo: { type: "boolean" },
18 rejoin: { type: "boolean" },
1819 },
1920 required: ["repo"],
2021 },
@@ -25,6 +26,13 @@ export const tool: Tool = {
2526 if (isAnswer(repo)) return repo;
2627 // Doing it takes the explicit `confirm: true` (`dryRun: false` still does, as it always has).
2728 const dryRun = !(args["confirm"] === true || args["dryRun"] === false);
29 if (args["rejoin"] === true) {
30 if (user.kind === "agent") return bad("forbidden", "only an admin of this repository rejoins, never an agent");
31 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "rejoining needs an admin token");
32 if (dryRun) return good({ dryRun: true, says: `${REJOIN_ASKS} Call again with confirm: true to do it.` });
33 const done = await rejoinParent(ctx.app, user, repo);
34 return done.ok ? good({ says: rejoinDone(done.value.mode, done.value.modeKnown) }) : bad("forbidden", UNDO_REFUSALS[done.error]);
35 }
2836 if (args["undo"] === true) {
2937 if (user.kind === "agent") return bad("forbidden", "only an admin of this repository undoes it, never an agent");
3038 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "undoing a sever needs an admin token");
src/http/server.ts +2 −1
@@ -491,7 +491,7 @@ import {
491491 mirrorStop,
492492 } from "../web/pages/settings.ts";
493493 import { dangerPage, repoDelete } from "../web/pages/danger.ts";
494 import { detachSubmit, undoSeverSubmit } from "../web/pages/detach.ts";
494 import { detachSubmit, rejoinSubmit, undoSeverSubmit } from "../web/pages/detach.ts";
495495 import {
496496 hooksPage,
497497 webhookCreate,
@@ -1920,6 +1920,7 @@ export function buildRouter(): Router<Handler> {
19201920 router.add("POST", "/:owner/:name/settings/delete", repoDelete);
19211921 router.add("POST", "/:owner/:name/settings/detach", detachSubmit);
19221922 router.add("POST", "/:owner/:name/settings/detach/undo", undoSeverSubmit);
1923 router.add("POST", "/:owner/:name/settings/detach/rejoin", rejoinSubmit);
19231924 router.add(
19241925 "POST",
19251926 "/:owner/:name/settings/origin/reconnect",
src/tui/screens/about.ts +25 −2
@@ -33,8 +33,8 @@ import {
3333 detachPhaseWords,
3434 detachPlanWords,
3535 } from "../../actions/detach.ts";
36 import { UNDO_ASKS, UNDO_REFUSALS } from "../../actions/detach_words.ts";
37 import { severPreview, undoSever, undoableSever } from "../../actions/sever_undo.ts";
36 import { REJOIN_ASKS, UNDO_ASKS, rejoinDone, UNDO_REFUSALS } from "../../actions/detach_words.ts";
37 import { rejoinableParent, rejoinParent, severPreview, undoSever, undoableSever } from "../../actions/sever_undo.ts";
3838 import { upstreamOffer, type UpstreamOffer } from "../../actions/offer_upstream.ts";
3939 import { listRefs } from "../../git/read.ts";
4040 import { directionNote } from "../../crew/direct.ts";
@@ -139,6 +139,8 @@ export function aboutScreen(
139139 mayPerson() && repo !== undefined && repo.forkParentId !== null;
140140 // A severing is undone within seven days (`undoableSever`): an admin's, like the sever.
141141 const mayUndoSever = (): boolean => mayPerson() && repo !== undefined && undoableSever(f.app, repo) !== undefined;
142 // Rejoin: the same person's, for as long as the former parent exists and is readable.
143 const mayRejoin = (): boolean => mayPerson() && repo !== undefined && rejoinableParent(f.app, repo, f.user) !== undefined;
142144 // The team card's button: the first agent not yet on the crew, in the first empty seat.
143145 const emptySeat = () =>
144146 repo === undefined ? undefined : seatsOf(f.db, repo, crewOffInPreview()).seats.find((x) => x.by.length === 0);
@@ -280,6 +282,7 @@ export function aboutScreen(
280282 ...(mayDetach() && detachJob(repo!.id)?.phase !== "repacking"
281283 ? [binding(["x"], "sever from upstream")]
282284 : []),
285 ...(mayRejoin() && !mayUndoSever() ? [binding(["U"], "rejoin the former parent")] : []),
283286 ...(mayUndoSever() ? [binding(["U"], "undo the sever (follow upstream again)")] : []),
284287 ...(offered === null
285288 ? []
@@ -486,6 +489,26 @@ export function aboutScreen(
486489 });
487490 return true;
488491 }
492 if (e.key === "U" && repo !== undefined && !mayUndoSever() && mayRejoin()) {
493 const at = repo;
494 ctx.push(
495 confirmScreen(ctx, screen, {
496 title: "Rejoin the former parent",
497 body: [REJOIN_ASKS],
498 actions: [{ label: "Rejoin" }, { label: "Cancel" }],
499 onChoose: (i) => {
500 if (i !== 0) return;
501 void rejoinParent(f.app, f.user, at).then((done) => {
502 repo = getRepoById(f.db, at.id) ?? at;
503 rows = factRows();
504 ctx.toast(done.ok ? rejoinDone(done.value.mode, done.value.modeKnown) : UNDO_REFUSALS[done.error], done.ok ? "success" : "danger");
505 ctx.invalidate();
506 });
507 },
508 }),
509 );
510 return true;
511 }
489512 if (e.key === "U" && repo !== undefined && mayUndoSever()) {
490513 const at = repo;
491514 ctx.push(
src/web/pages/detach.ts +25 −7
@@ -8,8 +8,8 @@
88 */
99
1010 import { detachFromParent, detachJob, type DetachJob } from "../../actions/detach.ts";
11 import { DETACH_STAYS, UNDO_DONE, UNDO_REFUSALS } from "../../actions/detach_words.ts";
12 import { severPreview, undoSever, type SeverPreview } from "../../actions/sever_undo.ts";
11 import { DETACH_STAYS, UNDO_DONE, rejoinDone, UNDO_REFUSALS } from "../../actions/detach_words.ts";
12 import { severPreview, rejoinParent, undoSever, type SeverPreview, type UndoError } from "../../actions/sever_undo.ts";
1313 import { forkParentFor, type Repo } from "../../core/repos.ts";
1414 import type { User } from "../../core/users.ts";
1515 import type { Ctx } from "../../http/context.ts";
@@ -20,6 +20,7 @@ import { flashTo } from "../layout.ts";
2020 import { confirmAction, time } from "../ui.ts";
2121 import type { Database } from "bun:sqlite";
2222 import { adminForm } from "../admin_form.ts";
23 import type { Result } from "../../kernel/result.ts";
2324
2425 /** What the detach section shows: plain data, read by `detachSection`. */
2526 export interface DetachView {
@@ -85,14 +86,31 @@ export function detachBlock({ name, action, job, rows }: DetachView): Html {
8586 }
8687
8788 /** POST /:owner/:name/settings/detach/undo — follow the parent again, within seven days. */
88 export async function undoSeverSubmit(ctx: Ctx): Promise<Response> {
89 export const undoSeverSubmit = (ctx: Ctx): Promise<Response> => relinkSubmit(ctx, undoSever, () => UNDO_DONE);
90
91 /**
92 * POST /:owner/:name/settings/detach/rejoin — follow the former parent again, at any age, with the
93 * mode it had.
94 */
95 export const rejoinSubmit = (ctx: Ctx): Promise<Response> =>
96 relinkSubmit(ctx, rejoinParent, (r) => rejoinDone(r.mode, r.modeKnown));
97
98 /**
99 * The admin form shared by undo and rejoin: do it, then flash what happened on the repository's
100 * page.
101 */
102 async function relinkSubmit<T>(
103 ctx: Ctx,
104 act: (app: Ctx["app"], actor: Ctx["auth"]["user"], repo: Repo) => Promise<Result<T, UndoError>>,
105 said: (done: T) => string,
106 ): Promise<Response> {
89107 const gate = await adminForm(ctx);
90108 if (gate instanceof Response) return gate;
91109 const home = repoBase(gate.repo);
92 const undone = await undoSever(ctx.app, ctx.auth.user, gate.repo);
93 return undone.ok
94 ? flashTo(ctx, home, { message: UNDO_DONE })
95 : flashTo(ctx, home, { tone: "danger", message: `Nothing changed: ${UNDO_REFUSALS[undone.error]}.` });
110 const done = await act(ctx.app, ctx.auth.user, gate.repo);
111 return done.ok
112 ? flashTo(ctx, home, { message: said(done.value) })
113 : flashTo(ctx, home, { tone: "danger", message: `Nothing changed: ${UNDO_REFUSALS[done.error]}.` });
96114 }
97115
98116 /** POST /:owner/:name/settings/detach — start the detach; the section shows it. */
src/web/pages/following.ts +5 −2
@@ -40,7 +40,7 @@ import { running } from "../../kernel/version.ts";
4040 import { FOLLOW_CHOICES, FOLLOW_SWITCH_LABELS, followModeWords } from "../../actions/follow_words.ts";
4141 import type { ForkFollowMode } from "../../core/fork_follow.ts";
4242 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
43 import { undoableSever } from "../../actions/sever_undo.ts";
43 import { rejoinableParent, undoableSever } from "../../actions/sever_undo.ts";
4444 import { convergeWords, followModeOf, lastModeChange, takeOrTell, takeWords } from "../../actions/follow.ts";
4545 import { FOLLOW_WORD, FOLLOWS_NOTHING, HIDDEN_FORK_WORD, proposeRefusalWords } from "../../actions/follow_words.ts";
4646 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
@@ -189,11 +189,14 @@ export function onItsOwnLine(ctx: Ctx, repo: Repo): Html | null {
189189 if (repo.forkParentId !== null || repo.severedAt === null) return null;
190190 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
191191 const undo = admin ? undoableSever(ctx.app, repo) : undefined;
192 const former = admin && undo === undefined && ctx.auth.user?.kind !== "agent" ? rejoinableParent(ctx.app, repo, ctx.auth.user) : undefined;
192193 return html`<p class="mt small muted" data-on-its-own>
193194 ${icon("fork")} On its own since ${repo.severedAt.slice(0, 10)}.${undo !== undefined
194195 ? html` <span data-sever-receipt>Undo until ${time(undo.until)}.</span>
195196 <form method="post" action="${repoBase(repo)}/settings/detach/undo" class="inline">${btn("Undo", { variant: "outline", size: "sm" })}</form>`
196 : admin
197 : null}${former !== undefined
198 ? html` <span data-rejoin>${btn(`Rejoin ${former.ownerName}/${former.name}`, { href: `/-/confirm?to=${encodeURIComponent(`${repoBase(repo)}/settings/detach/rejoin`)}`, variant: "outline", size: "sm" })}</span>`
199 : admin && undo === undefined
197200 ? html` <a href="${repoBase(repo)}/settings#upstream">Follow upstream again</a>`
198201 : null}
199202 </p>`;
src/web/pages/search.ts +11 −1
@@ -13,7 +13,8 @@
1313 import { ARCHIVE_DETAIL, RESTORE_DETAIL, archiveTitle, restoreTitle } from "../../core/archive-words.ts";
1414 import { cappedQuery, echoed, queryTooLong, QUERY_TRIMMED_NOTE } from "../../core/query_limit.ts";
1515 import { returnTo, withReturn } from "../return_to.ts";
16 import { severPreview } from "../../actions/sever_undo.ts";
16 import { REJOIN_ASKS } from "../../actions/detach_words.ts";
17 import { rejoinableParent, severPreview } from "../../actions/sever_undo.ts";
1718 import { DISCONNECT_DETAIL } from "../../actions/origin_words.ts";
1819 import { strangerCodeSearch } from "../../http/strangers.ts";
1920 import { search } from "../../actions/search.ts";
@@ -671,6 +672,15 @@ const DESTRUCTIVE: {
671672 };
672673 },
673674 },
675 {
676 pattern: /^\/([^/]+)\/([^/]+)\/settings\/detach\/rejoin$/,
677 describe: (m, ctx) => {
678 const fork = getRepo(ctx.app.db, m[1] ?? "", m[2] ?? "");
679 const former = fork === undefined ? undefined : rejoinableParent(ctx.app, fork, ctx.auth.user);
680 const name = former === undefined ? "its former parent" : `${former.ownerName}/${former.name}`;
681 return { verb: `Rejoin ${name}`, title: `Rejoin ${name}?`, detail: `${REJOIN_ASKS} It follows with the mode it had when it was severed, or the default if that was not recorded.`, phrase: "" };
682 },
683 },
674684 {
675685 pattern: /^\/([^/]+)\/([^/]+)\/branches\/([^/]+)\/delete$/,
676686 describe: (m) => ({
test/fork-detach.test.ts +1 −1
@@ -243,6 +243,6 @@ describe("detach from parent", () => {
243243 const events = listEvents(app.db, { repoId: fork.id, kind: "repo.detached", limit: 5 });
244244 expect(events).toHaveLength(1);
245245 expect(JSON.stringify(events[0]!.payload)).not.toContain(name);
246 expect(events[0]!.payload).toEqual({ parentId: secret.id });
246 expect(events[0]!.payload).toEqual({ parentId: secret.id, mode: "tell-me" });
247247 }, 30_000);
248248 });
test/fork-rejoin-doors.test.ts added +201
@@ -0,0 +1,201 @@
1 /**
2 * #16064: the doors of Rejoin: the page's button, /-/confirm, the POST, the MCP tool and the
3 * terminal's U, over a fork severed ten days ago.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { commitToBranch } from "../src/actions/repos.ts";
11 import { detachFromParent, detachJob } from "../src/actions/detach.ts";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { setForkFollowMode } from "../src/core/fork_follow.ts";
14 import { createRepo, forkRepo, getRepo, getRepoById, type Repo } from "../src/core/repos.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import type { Ctx, Screen } from "../src/tui/app/app.ts";
19 import { aboutScreen } from "../src/tui/screens/about.ts";
20 import type { Session } from "../src/tui/session.ts";
21 import { theme } from "../src/tui/ui/theme.ts";
22 import type { KeyEvent } from "../src/tui/term/input.ts";
23 const pressed = (key: string): KeyEvent => ({ type: "key", key, ctrl: false, alt: false, shift: false });
24 import { localSource } from "../src/view/local.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26
27 quietLogs();
28
29 let dataDir = "";
30 let app: App;
31 let servers: Servers;
32 let alice: User;
33 let bob: User;
34 let carol: User;
35 let bot: User;
36 const cells = process.env["FORGE_CELLS"];
37 const cookies = new Map<string, string>();
38 let n = 0;
39
40 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
41 if (!r.ok) throw new Error(JSON.stringify(r.error));
42 return r.value;
43 };
44 const signin = async (username: string): Promise<void> => {
45 const res = await fetch(`${servers.url}/signin`, {
46 method: "POST",
47 headers: { origin: servers.url },
48 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
49 redirect: "manual",
50 });
51 cookies.set(username, (res.headers.get("set-cookie") ?? "").split(";")[0]!);
52 };
53
54 beforeAll(async () => {
55 process.env["FORGE_CELLS"] = "off";
56 dataDir = await mkdtemp(join(tmpdir(), "forge-rejoin-doors-"));
57 app = createApp({ dataDir, port: 0 });
58 servers = await serve(app);
59 const make = async (username: string, adminIfFirst = false) =>
60 ok(await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst }));
61 alice = await make("alice", true);
62 bob = await make("bob");
63 carol = await make("carol");
64 bot = ok(await createAgent(app, alice, { username: "bot" })).user;
65 await signin("alice");
66 await signin("bob");
67 await signin("carol");
68 }, 30_000);
69
70 afterAll(async () => {
71 servers.stop();
72 app.close();
73 if (cells === undefined) delete process.env["FORGE_CELLS"];
74 else process.env["FORGE_CELLS"] = cells;
75 await rm(dataDir, { recursive: true, force: true });
76 });
77
78 /** A fork of alice's, severed `days` ago in "dont-follow", of a public parent of `owner`'s. */
79 async function severed(days: number, owner: User = alice, forker: User = alice): Promise<{ fork: Repo; parent: Repo; base: string }> {
80 const id = `r${++n}`;
81 const parent = ok(await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: `up-${id}`, visibility: "public" }));
82 ok(await commitToBranch(app, owner, parent, { message: "a", files: [{ path: "a.txt", content: "a\n" }] }));
83 const fork = ok(await forkRepo(app.db, app.reposRoot, parent, forker.id, id));
84 setForkFollowMode(app.db, fork.id, "dont-follow");
85 ok(await detachFromParent(app, forker, getRepo(app.db, forker.username, id)!, false));
86 await detachJob(fork.id)?.done;
87 const at = new Date(Date.now() - days * 86_400_000).toISOString();
88 app.db.query("UPDATE event SET created_at = ?2 WHERE repo_id = ?1 AND kind = 'repo.detached'").run(fork.id, at);
89 return { fork: getRepo(app.db, forker.username, id)!, parent, base: `/${forker.username}/${id}` };
90 }
91 const page = async (path: string, who = "alice"): Promise<string> =>
92 (await fetch(`${servers.url}${path}`, { headers: { cookie: cookies.get(who)! } })).text();
93 const post = (path: string, who = "alice", origin: string = servers.url) =>
94 fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie: cookies.get(who)!, origin }, redirect: "manual" });
95 const flash = (r: Response): string => decodeURIComponent(r.headers.get("set-cookie") ?? "").replace(/\+/g, " ");
96
97 test("the page offers Rejoin after seven days, not inside them, not to a non-admin or for an unreadable parent", async () => {
98 const old = await severed(10);
99 const html = await page(old.base);
100 expect(html).toContain("data-rejoin");
101 expect(html).toContain(`Rejoin alice/${old.parent.name}`);
102 expect(html).toContain(`/-/confirm?to=${encodeURIComponent(`${old.base}/settings/detach/rejoin`)}`);
103 expect(await page(old.base, "bob")).not.toContain("data-rejoin");
104
105 const fresh = await severed(1);
106 const inside = await page(fresh.base);
107 expect(inside).toContain(`${fresh.base}/settings/detach/undo`);
108 expect(inside).not.toContain("data-rejoin");
109
110 const hidden = await severed(10, bob, carol);
111 app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(hidden.parent.id);
112 const seen = await page(hidden.base, "carol");
113 expect(seen).not.toContain("data-rejoin");
114 expect(seen).not.toContain(hidden.parent.name);
115 });
116
117 test("/-/confirm describes the rejoin and posts to it", async () => {
118 const { base, parent } = await severed(10);
119 const to = `${base}/settings/detach/rejoin`;
120 const res = await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent(to)}`, { headers: { cookie: cookies.get("alice")! } });
121 expect(res.status).toBe(200);
122 const body = await res.text();
123 expect(body).toContain(`Rejoin alice/${parent.name}?`);
124 expect(body).toContain("Follow the former parent again");
125 expect(body).toContain(`action="${to}"`);
126 });
127
128 test("the POST is same-origin and admin only; success and refusal flash", async () => {
129 const { fork, parent, base } = await severed(10);
130 const to = `${base}/settings/detach/rejoin`;
131 expect((await post(to, "alice", "https://evil.example")).status).toBe(403);
132 expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull();
133 const stranger = await post(to, "bob");
134 expect(stranger.status).not.toBe(303);
135 expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull();
136
137 const done = await post(to);
138 expect(done.status).toBe(303);
139 expect(flash(done)).toContain("Follow mode: dont-follow, as it was when it was severed");
140 expect(getRepoById(app.db, fork.id)!.forkParentId).toBe(parent.id);
141
142 const again = await post(to);
143 expect(again.status).toBe(303);
144 expect(flash(again)).toContain("Nothing changed:");
145 });
146
147 const mcp = async (token: string, args: Record<string, unknown>) => {
148 const res = await fetch(`${servers.url}/mcp`, {
149 method: "POST",
150 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
151 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "detach", arguments: args } }),
152 });
153 const body = (await res.json()) as any;
154 return { error: body.result.isError === true, text: body.result.content[0].text as string };
155 };
156
157 test("MCP detach rejoin: an agent and a non-admin token are refused, an admin needs confirm", async () => {
158 const { fork, parent, base } = await severed(10);
159 const args = { repo: base.slice(1), rejoin: true };
160 const agentTok = createToken(app.db, bot.id, "t", "admin").token;
161 const roTok = createToken(app.db, alice.id, "t", "rw").token;
162 const admin = createToken(app.db, alice.id, "t", "admin").token;
163 const a = await mcp(agentTok, { ...args, confirm: true });
164 expect(a.error).toBe(true);
165 const r = await mcp(roTok, { ...args, confirm: true });
166 expect(r.error).toBe(true);
167 expect(r.text).toContain("admin token");
168 expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull();
169
170 const dry = await mcp(admin, args);
171 expect(dry.error).toBe(false);
172 expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull();
173 const done = await mcp(admin, { ...args, confirm: true });
174 expect(done.error).toBe(false);
175 expect(done.text).toContain("dont-follow");
176 expect(getRepoById(app.db, fork.id)!.forkParentId).toBe(parent.id);
177 });
178
179 function card(user: User, target: Repo) {
180 const pushed: Screen[] = [];
181 let toasted!: (message: string) => void;
182 const toast = new Promise<string>((r) => (toasted = r));
183 const ctx = { theme: theme("dark"), invalidate() {}, toast: (m: string) => toasted(m), push: (s: Screen) => pushed.push(s), pop() {}, copy() {} } as unknown as Ctx;
184 const f = { app, db: app.db, user } as unknown as Session;
185 const screen = aboutScreen(f, ctx, { render() {} } as unknown as Screen, localSource(app, getRepoById(app.db, target.id)!, user), undefined, "main");
186 return { pushed, toast, offered: () => screen.keys.some((b) => b.keys.includes("U")), press: () => screen.key!(pressed("U")) };
187 }
188
189 test("terminal U rejoins an old sever after a confirm, for an admin only", async () => {
190 const { fork, parent } = await severed(10);
191 expect(card(bob, fork).offered()).toBe(false);
192 expect(card(bot, fork).offered()).toBe(false);
193 const c = card(alice, fork);
194 expect(c.offered()).toBe(true);
195 c.press();
196 expect(c.pushed[0]!.title).toBe("Rejoin the former parent");
197 expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull(); // asked, not done
198 c.pushed[0]!.key!(pressed("enter"));
199 expect(await c.toast).toContain("Follow mode: dont-follow");
200 expect(getRepoById(app.db, fork.id)!.forkParentId).toBe(parent.id);
201 });
test/fork-rejoin.test.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * #16064: a fork severed more than seven days ago rejoins its former parent in one action, with the
3 * follow mode it had; the same refusals as Undo.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
11 import { detachFromParent, detachJob } from "../src/actions/detach.ts";
12 import { rejoinParent, undoSever, undoableSever } from "../src/actions/sever_undo.ts";
13 import { forkFollowMode, setForkFollowMode } from "../src/core/fork_follow.ts";
14 import { getRepo, type Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dataDir = "";
21 let app: App;
22 let alice: User;
23 let bob: User;
24 let parent: Repo;
25 const parents = new Map<string, Repo>();
26 const cells = process.env["FORGE_CELLS"];
27
28 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
29 if (!r.ok) throw new Error(JSON.stringify(r.error));
30 return r.value;
31 };
32
33 beforeAll(async () => {
34 process.env["FORGE_CELLS"] = "off";
35 dataDir = await mkdtemp(join(tmpdir(), "forge-fork-rejoin-"));
36 app = createApp({ dataDir, port: 0 });
37 alice = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }));
38 bob = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
39 parent = ok(await createRepo(app, alice, { name: "root", visibility: "public" }));
40 ok(await commitToBranch(app, alice, parent, { message: "a", files: [{ path: "a.txt", content: "a\n" }] }));
41 });
42
43 afterAll(async () => {
44 app.close();
45 if (cells === undefined) delete process.env["FORGE_CELLS"];
46 else process.env["FORGE_CELLS"] = cells;
47 await rm(dataDir, { recursive: true, force: true });
48 });
49
50 async function severed(name: string, mode?: "tell-me" | "dont-follow" | "take-updates"): Promise<Repo> {
51 // One parent each: a user forks a repository once.
52 const root = ok(await createRepo(app, alice, { name: `root-${name}`, visibility: "public" }));
53 ok(await commitToBranch(app, alice, root, { message: "a", files: [{ path: "a.txt", content: "a\n" }] }));
54 parents.set(name, root);
55 const fork = ok(await forkRepo(app, alice, root, name));
56 if (mode !== undefined) setForkFollowMode(app.db, fork.id, mode);
57 ok(await detachFromParent(app, alice, getRepo(app.db, "alice", name)!, false));
58 await detachJob(fork.id)?.done;
59 return getRepo(app.db, "alice", name)!;
60 }
61 const age = (repoId: string, days: number): void => {
62 const at = new Date(Date.now() - days * 86_400_000).toISOString();
63 app.db.query("UPDATE event SET created_at = ?2 WHERE repo_id = ?1 AND kind = 'repo.detached'").run(repoId, at);
64 };
65
66 test("the sever records the mode; after seven days Undo is gone and rejoin restores parent and mode", async () => {
67 const fork = await severed("old", "dont-follow");
68 const payload = app.db.query<{ payload: string }, [string]>("SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'repo.detached'").get(fork.id)!;
69 expect(JSON.parse(payload.payload).mode).toBe("dont-follow");
70 age(fork.id, 10);
71 setForkFollowMode(app.db, fork.id, "tell-me"); // drifted since: the recorded mode wins
72 expect(undoableSever(app, fork)).toBeUndefined();
73 expect((await undoSever(app, alice, fork)).ok).toBe(false);
74 const done = ok(await rejoinParent(app, alice, fork));
75 expect(done).toMatchObject({ mode: "dont-follow", modeKnown: true });
76 expect(done.parent.id).toBe(parents.get("old")!.id);
77 expect(getRepo(app.db, "alice", "old")!.forkParentId).toBe(parents.get("old")!.id);
78 expect(forkFollowMode(app.db, fork.id)).toBe("dont-follow");
79 // Joined again: nothing left to rejoin.
80 const again = await rejoinParent(app, alice, getRepo(app.db, "alice", "old")!);
81 expect(again.ok ? "" : again.error).toBe("not_severed");
82 });
83
84 test("a fork severed before the mode was recorded rejoins with the default and says so", async () => {
85 const fork = await severed("legacy");
86 app.db.query("UPDATE event SET payload = ?2 WHERE repo_id = ?1 AND kind = 'repo.detached'").run(fork.id, JSON.stringify({ parentId: parents.get("legacy")!.id }));
87 age(fork.id, 30);
88 const done = ok(await rejoinParent(app, alice, fork));
89 expect(done.modeKnown).toBe(false);
90 expect(done.mode).toBe("tell-me");
91 });
92
93 test("a stranger and an agent are refused; a gone parent says so", async () => {
94 const fork = await severed("guarded");
95 age(fork.id, 10);
96 const stranger = await rejoinParent(app, bob, fork);
97 expect(stranger.ok ? "" : stranger.error).toBe("forbidden");
98 const anon = await rejoinParent(app, undefined, fork);
99 expect(anon.ok ? "" : anon.error).toBe("unauthorized");
100 const agent = { ...alice, kind: "agent" } as User;
101 const refused = await rejoinParent(app, agent, fork);
102 expect(refused.ok ? "" : refused.error).toBe("forbidden");
103 expect(getRepo(app.db, "alice", "guarded")!.forkParentId).toBeNull();
104
105 app.db.query("UPDATE event SET payload = ?2 WHERE repo_id = ?1 AND kind = 'repo.detached'").run(fork.id, JSON.stringify({ parentId: "gone" }));
106 const gone = await rejoinParent(app, alice, fork);
107 expect(gone.ok ? "" : gone.error).toBe("parent_gone");
108 expect(getRepo(app.db, "alice", "guarded")!.forkParentId).toBeNull();
109 });
110
111 test("undo restores the recorded mode like rejoin, and leaves it alone when none was recorded", async () => {
112 const fork = await severed("undone", "dont-follow");
113 setForkFollowMode(app.db, fork.id, "take-updates");
114 ok(await undoSever(app, alice, fork));
115 expect(forkFollowMode(app.db, fork.id)).toBe("dont-follow");
116
117 const legacy = await severed("undone-legacy");
118 app.db.query("UPDATE event SET payload = ?2 WHERE repo_id = ?1 AND kind = 'repo.detached'").run(legacy.id, JSON.stringify({ parentId: parents.get("undone-legacy")!.id }));
119 setForkFollowMode(app.db, legacy.id, "take-updates");
120 ok(await undoSever(app, alice, legacy));
121 expect(forkFollowMode(app.db, legacy.id)).toBe("take-updates");
122 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs