Public: anyone can read this; the crew can change it.
Severing a fork from its upstream is previewed, receipted and undoable for seven days #15786
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15745-severing-a-fork-from-its-upstream-is-pre → main 0 commits fork 6 threads · 6 unresolved
docs/features/fork-sever.md +4
| @@ -8,7 +8,11 @@ A fork's admin can stop following its parent: Settings › Danger zone › **Sev | ||
| 8 | 8 | |
| 9 | 9 | - The confirm names the parent (`ann/yard`) and says what stops: updates from it and offers to it. A parent the viewer may not read is shown as "its parent". |
| 10 | 10 | - Only an admin, from this origin, can post it; anyone else is refused and nothing changes. |
| 11 | - The confirm, the Danger zone and the MCP say the same preview (`severPreview`): what stops flowing down (updates) and up (offers, with how many are open), and who is affected. | |
| 11 | 12 | - The fork's code and history stay. The history records `repo.detached`. |
| 13 | - **Undo** (on the fork's home, beside the receipt "Severed <when>; undo until <when>") restores following for seven days: it names the parent again and borrows its objects, so what the parent did meanwhile arrives as an ordinary update. Offers sent before the sever are listed at the parent again; none could be made during the gap. The history records `repo.reattached`. | |
| 12 | 14 | - The fork's home then reads "On its own since <date>." in the following card's place, with **Follow upstream again** (Settings › Follow upstream) for an admin. |
| 13 | 15 | |
| 14 | 16 | In the terminal it is the repository's About screen (`src/tui/screens/about.ts`): an admin presses `x` on a fork, reads the plan in the confirm and picks Detach. Both doors run `detachFromParent`, so the gate and the `repo.detached` event are the same. |
| 17 | ||
| 18 | On the MCP it is the `fork` tool: `{ repo, action: "sever" }` plans; add `confirm: true` to do it; `undo: true` follows again. |
src/actions/detach.ts +4 −2
| @@ -129,9 +129,11 @@ function failureLine(stderr: string): string { | ||
| 129 | 129 | } |
| 130 | 130 | |
| 131 | 131 | /** The plan in one sentence, for the terminal's confirm and the MCP. */ |
| 132 | export function detachPlanWords(plan: DetachPlan): string { | |
| 132 | export function detachPlanWords(plan: DetachPlan, says?: string): string { | |
| 133 | 133 | const parent = plan.parent ?? "its parent"; |
| 134 | return `${plan.borrows ? `Copies every object it borrows from ${parent} into its own store, drops the link, then forgets` : `Borrows nothing from ${parent}; forgets`} the parent. ${DETACH_STAYS} ${DETACH_STOPS} ${DETACH_AGAIN}`; | |
| 134 | const head = `${plan.borrows ? `Copies every object it borrows from ${parent} into its own store, drops the link, then forgets` : `Borrows nothing from ${parent}; forgets`} the parent.`; | |
| 135 | // `says` is the fuller preview (`severPreview`): what stops, who is affected, the undo. | |
| 136 | return says === undefined ? `${head} ${DETACH_STAYS} ${DETACH_STOPS} ${DETACH_AGAIN}` : `${head} ${says}`; | |
| 135 | 137 | } |
| 136 | 138 | |
| 137 | 139 | /** Where a detach stands, in words; null when none is under way or failed. */ |
src/actions/detach_words.ts +19 −3
| @@ -12,8 +12,24 @@ export const DETACH_STOPS = "Updates from the parent and offers to it stop."; | ||
| 12 | 12 | export const DETACH_RECEIPT = "severed a fork from its upstream: code and history kept, updates and offers stopped"; |
| 13 | 13 | /** A fork's line in a chain when its link was cut: the chain stops there. */ |
| 14 | 14 | export const SEVERED_LINE = "Severed from its upstream."; |
| 15 | /** How long a severing can be undone. */ | |
| 16 | export const UNDO_DAYS = 7; | |
| 17 | /** The history row's verb for the undo. */ | |
| 18 | export const UNDO_RECEIPT = "undid a severing: the fork follows its upstream again"; | |
| 15 | 19 | /** |
| 16 | * No undo, and the way back: any repository's admin follows an address from Settings, under Follow | |
| 17 | * upstream. | |
| 20 | * The way back, for every door: Undo restores following within seven days; after that Settings › | |
| 21 | * Follow upstream can follow an address. | |
| 18 | 22 | */ |
| 19 | export const DETACH_AGAIN = "There is no undo, but Settings › Follow upstream can follow its address again."; | |
| 23 | export const DETACH_AGAIN = `Undo restores following for ${UNDO_DAYS} days; after that, Settings › Follow upstream can follow its address.`; | |
| 24 | /** What an undo keeps and does, said after it. */ | |
| 25 | 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."; | |
| 26 | /** What an undo asks before it follows again (the terminal's confirm). */ | |
| 27 | 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 | /** Why an undo is refused, by reason. */ | |
| 29 | export const UNDO_REFUSALS = { | |
| 30 | unauthorized: "sign in to undo a severing", | |
| 31 | forbidden: "only this repository's admin undoes a severing", | |
| 32 | nothing_to_undo: `there is no severing to undo: none was made, it was undone, or it is more than ${UNDO_DAYS} days old`, | |
| 33 | parent_gone: "the parent is gone or is not readable by you, so there is nothing to follow again", | |
| 34 | running: "the sever is still copying objects; try again when it has finished", | |
| 35 | } as const; |
src/actions/sever_undo.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | /** | |
| 2 | * Severing a fork, previewed and undoable for seven days (#15745): the preview says what stops | |
| 3 | * flowing down (updates) and up (offers) and who is affected, in the words every door shares; the | |
| 4 | * undo names the parent again. The fork kept every object it borrowed (the repack), so naming the | |
| 5 | * parent is all it takes: whatever the parent did meanwhile is an ordinary update after. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { canAdmin, canRead, forkParentFor, getRepoById, restoreForkParent, visibleForks, type Repo } from "../core/repos.ts"; | |
| 11 | import type { User } from "../core/users.ts"; | |
| 12 | import { relinkFork, repoDir, unlinkFork } from "../git/repos.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | import { detachJob } from "./detach.ts"; | |
| 15 | import { DETACH_AGAIN, DETACH_STAYS, DETACH_STOPS, UNDO_DAYS, type UNDO_REFUSALS } from "./detach_words.ts"; | |
| 16 | ||
| 17 | const DAY_MS = 24 * 60 * 60 * 1000; | |
| 18 | ||
| 19 | /** What severing a fork stops, in numbers and names; plain data. */ | |
| 20 | export interface SeverPreview { | |
| 21 | /** owner/name of the parent, or "its parent" when the viewer may not read it. */ | |
| 22 | readonly parent: string; | |
| 23 | /** Open pulls this fork has offered its parent, which stop being listed there. */ | |
| 24 | readonly offersOpen: number; | |
| 25 | /** Forks of this fork: they follow it and are untouched. */ | |
| 26 | readonly forks: number; | |
| 27 | /** Each fact once, for the page's rows: Stops down, Stops up, Affected, Undo. */ | |
| 28 | readonly rows: readonly (readonly [label: string, text: string])[]; | |
| 29 | /** The same rows as one text, for the terminal and the MCP. */ | |
| 30 | readonly says: string; | |
| 31 | } | |
| 32 | ||
| 33 | export function severPreview(db: Database, repo: Repo, viewer: User | undefined): SeverPreview { | |
| 34 | const row = forkParentFor(db, repo, viewer); | |
| 35 | const parent = row === undefined ? "its parent" : `${row.ownerName}/${row.name}`; | |
| 36 | const offersOpen = | |
| 37 | row === undefined | |
| 38 | ? 0 | |
| 39 | : (db | |
| 40 | .query<{ n: number }, [string, string]>( | |
| 41 | `SELECT count(*) AS n FROM pull JOIN issue ON issue.id = pull.issue_id | |
| 42 | WHERE issue.repo_id = ?1 AND pull.head_repo_id = ?2 AND issue.state = 'open' AND pull.merged_at IS NULL`, | |
| 43 | ) | |
| 44 | .get(row.id, repo.id)?.n ?? 0); | |
| 45 | const forks = visibleForks(db, repo.id, viewer).length; | |
| 46 | const owners = row === undefined ? "its parent's owners" : row.ownerName; | |
| 47 | const open = offersOpen === 1 ? "1 open offer stops" : `${offersOpen} open offers stop`; | |
| 48 | const rows: [string, string][] = [ | |
| 49 | ["Stops down", `updates from ${parent} no longer reach ${repo.ownerName}/${repo.name}.`], | |
| 50 | ["Stops up", `offers to ${parent} can no longer be made${offersOpen === 0 ? "" : `; ${open} being listed there`}.`], | |
| 51 | [ | |
| 52 | "Affected", | |
| 53 | `${repo.ownerName} and the crew (updates), ${owners} (offers)${forks === 0 ? "" : `; ${forks} fork${forks === 1 ? "" : "s"} of this one keep following it, now as a line of its own`}.`, | |
| 54 | ], | |
| 55 | ["Undo", DETACH_AGAIN], | |
| 56 | ]; | |
| 57 | const says = `${DETACH_STAYS} ${DETACH_STOPS} ${rows.map(([k, v]) => `${k}: ${v}`).join(" ")}`; | |
| 58 | return { parent, offersOpen, forks, rows, says }; | |
| 59 | } | |
| 60 | ||
| 61 | export interface UndoableSever { | |
| 62 | readonly parentId: string; | |
| 63 | readonly at: string; | |
| 64 | readonly until: string; | |
| 65 | } | |
| 66 | ||
| 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 { | |
| 69 | if (repo.forkParentId !== null) return undefined; | |
| 70 | const last = app.db | |
| 71 | .query<{ kind: string; payload: string; created_at: string }, [string]>( | |
| 72 | `SELECT kind, payload, created_at FROM event | |
| 73 | WHERE repo_id = ?1 AND kind IN ('repo.detached', 'repo.reattached') ORDER BY seq DESC LIMIT 1`, | |
| 74 | ) | |
| 75 | .get(repo.id); | |
| 76 | 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() }; | |
| 81 | } | |
| 82 | ||
| 83 | export type UndoError = keyof typeof UNDO_REFUSALS; | |
| 84 | ||
| 85 | /** Follow the parent again: an admin of the fork only; the history records it. */ | |
| 86 | export async function undoSever(app: App, actor: User | undefined, repo: Repo): Promise<Result<UndoableSever, UndoError>> { | |
| 87 | if (actor === undefined) return err("unauthorized"); | |
| 88 | // The sever is never an agent's (`detachFromParent`): neither is its undo. | |
outdated
relinkFork rewrites the alternates file before the event and column are written; if restoreForkParent or the append fails the fork is half-restored. Order it so a failure leaves the sever intact, and test parent_gone. |
||
| 89 | if (actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("forbidden"); | |
| 90 | 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); | |
| 94 | if (parent === undefined || !canRead(app.db, parent, actor)) return err("parent_gone"); | |
| 95 | // The fork owns its objects but not what the parent made since: borrow them again, so the next | |
| 96 | // take reads them. A failure anywhere after that leaves the sever as it was. | |
| 97 | const forkDir = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 98 | const linked = await relinkFork(forkDir, repoDir(app.reposRoot, parent.ownerName, parent.name)); | |
| 99 | if (!linked.ok) return err("parent_gone"); | |
| 100 | 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 } }); | |
| 103 | } catch (e) { | |
| 104 | await unlinkFork(forkDir); | |
| 105 | throw e; | |
| 106 | } | |
| 107 | return ok(undo); | |
| 108 | } |
src/core/event_audience.ts +1
| @@ -175,6 +175,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([ | ||
| 175 | 175 | "repo.forked", |
| 176 | 176 | "repo.links_probed", |
| 177 | 177 | "repo.detached", |
| 178 | "repo.reattached", | |
| 178 | 179 | "repo.deleted", |
| 179 | 180 | // Who moved a repository from where to where (#569): its readers knew both paths. |
| 180 | 181 | "repo.transferred", |
src/core/repos.ts +9
| @@ -767,6 +767,15 @@ export function clearForkParent(db: Database, repoId: string): void { | ||
| 767 | 767 | forgetListings(db); |
| 768 | 768 | } |
| 769 | 769 | |
| 770 | /** | |
| 771 | * Name a parent again for a fork that was severed from it and still owns every object (the undo of | |
| 772 | * `clearForkParent`, `actions/sever_undo.ts`): the link returns and the severing's mark goes. | |
| 773 | */ | |
| 774 | export function restoreForkParent(db: Database, repoId: string, parentId: string): void { | |
| 775 | db.query("UPDATE repo SET fork_parent_id = ?2, origin_detached_at = NULL WHERE id = ?1").run(repoId, parentId); | |
| 776 | forgetListings(db); | |
| 777 | } | |
| 778 | ||
| 770 | 779 | /** The forks of this repository the viewer may see — the list, and its count. */ |
| 771 | 780 | export function visibleForks( |
| 772 | 781 | db: Database, |
src/design/activity.ts +2 −1
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | 12 | import { VIA_WORDS } from "../core/acting_via.ts"; |
| 13 | import { DETACH_RECEIPT } from "../actions/detach_words.ts"; | |
| 13 | import { DETACH_RECEIPT, UNDO_RECEIPT } from "../actions/detach_words.ts"; | |
| 14 | 14 | import { rankedWords, type Place } from "../actions/next.ts"; |
| 15 | 15 | import type { ForgeEvent } from "../core/events.ts"; |
| 16 | 16 | |
| @@ -205,6 +205,7 @@ const WORDS: Record<string, string> = { | ||
| 205 | 205 | "repo.created": "created a repository", |
| 206 | 206 | "repo.forked": "forked a repository", |
| 207 | 207 | "repo.detached": DETACH_RECEIPT, |
| 208 | "repo.reattached": UNDO_RECEIPT, | |
| 208 | 209 | "repo.settings_updated": "changed repository settings", |
| 209 | 210 | "repo.upstream_follow": "changed which upstream the repository follows", |
| 210 | 211 | "repo.source_added": "followed another source", |
src/git/repos.ts +20 −1
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { dirname, isAbsolute, join, resolve } from "node:path"; |
| 8 | import { rm, stat } from "node:fs/promises"; | |
| 8 | import { mkdir, rm, stat, writeFile } from "node:fs/promises"; | |
| 9 | 9 | import { defect } from "../kernel/error.ts"; |
| 10 | 10 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 11 | 11 | import { runGit, type GitFailure } from "./env.ts"; |
| @@ -178,6 +178,25 @@ export async function detachFork( | ||
| 178 | 178 | return ok(); |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | /** | |
| 182 | * Borrow the parent's objects again (what `detachFork` cut): the fork keeps every object it | |
| 183 | * owns, and the alternates line lets a take read the parent's new ones. | |
| 184 | */ | |
| 185 | export async function relinkFork(forkDir: string, parentDir: string): Promise<Result<void, GitFailure>> { | |
| 186 | const info = join(forkDir, "objects", "info"); | |
| 187 | await mkdir(info, { recursive: true }); | |
| 188 | await writeFile(join(info, "alternates"), `${resolve(parentDir, "objects")}\n`); | |
| 189 | const kept = await keepLentObjects(forkDir); // reads the link just written | |
| 190 | if (kept.ok) return ok(); | |
| 191 | await unlinkFork(forkDir); // a failure leaves the fork exactly as the sever left it | |
| 192 | return kept; | |
| 193 | } | |
| 194 | ||
| 195 | /** Cut the link `relinkFork` made, when what followed it failed. */ | |
| 196 | export async function unlinkFork(forkDir: string): Promise<void> { | |
| 197 | await rm(join(forkDir, "objects", "info", "alternates"), { force: true }); | |
| 198 | } | |
| 199 | ||
| 181 | 200 | /** Does this bare repo borrow objects from a parent via alternates? */ |
| 182 | 201 | export async function hasAlternates(dir: string): Promise<boolean> { |
| 183 | 202 | return await Bun.file(join(dir, "objects", "info", "alternates")).exists(); |
src/http/mcp/tools/detach.ts +14 −3
| @@ -1,16 +1,20 @@ | ||
| 1 | 1 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 2 | 2 | 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 | 5 | import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts"; |
| 4 | 6 | |
| 5 | 7 | export const tool: Tool = { |
| 6 | 8 | name: "detach", |
| 7 | doc: "`{ repo, dryRun? }`: detach a fork from its parent — repack so it owns its objects, drop the alternates link, forget the parent; planned first (`dryRun` is true unless `false`); the repack runs on its own, so call again to read its `phase` (`repacking`, `failed`) until the fork has no `parent`; only the repository's admin with an admin token, never an agent", | |
| 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", | |
| 8 | 10 | description: "Detach a fork from its parent. Plans first; admin token.", |
| 9 | 11 | inputSchema: { |
| 10 | 12 | type: "object", |
| 11 | 13 | properties: { |
| 12 | 14 | repo: REPO_ARG, |
| 13 | 15 | dryRun: { type: "boolean" }, |
| 16 | confirm: { type: "boolean" }, | |
| 17 | undo: { type: "boolean" }, | |
| 14 | 18 | }, |
| 15 | 19 | required: ["repo"], |
| 16 | 20 | }, |
| @@ -19,7 +23,14 @@ export const tool: Tool = { | ||
| 19 | 23 | async run(ctx, user, args) { |
| 20 | 24 | const repo = repoArg(ctx, user, args); |
| 21 | 25 | if (isAnswer(repo)) return repo; |
| 22 | const dryRun = args["dryRun"] !== false; | |
| 26 | // Doing it takes the explicit `confirm: true` (`dryRun: false` still does, as it always has). | |
| 27 | const dryRun = !(args["confirm"] === true || args["dryRun"] === false); | |
| 28 | if (args["undo"] === true) { | |
Undo takes this path before the agent refusal the doc promises ("never an agent"). Apply the same agent gate, and add a test with an agent token and a read-only token. |
||
| 29 | if (user.kind === "agent") return bad("forbidden", "only an admin of this repository undoes it, never an agent"); | |
| 30 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "undoing a sever needs an admin token"); | |
| 31 | const undone = await undoSever(ctx.app, user, repo); | |
| 32 | return undone.ok ? good({ says: UNDO_DONE }) : bad("forbidden", UNDO_REFUSALS[undone.error]); | |
| 33 | } | |
| 23 | 34 | if (!dryRun && !scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 24 | 35 | return bad("forbidden", "detaching needs an admin token"); |
| 25 | 36 | const job = detachJob(repo.id); |
| @@ -38,7 +49,7 @@ export const tool: Tool = { | ||
| 38 | 49 | ...planned.value, |
| 39 | 50 | ...(phase === null ? {} : { last: phase }), |
| 40 | 51 | says: dryRun |
| 41 | ? `This is the plan; nothing changed. ${detachPlanWords(planned.value)} Send dryRun: false to detach.` | |
| 52 | ? `This is the plan; nothing changed. ${detachPlanWords(planned.value, severPreview(ctx.app.db, repo, user).says)} Send confirm: true to sever.` | |
| 42 | 53 | : "Detaching: the repack runs on its own. Call again to see it finish.", |
| 43 | 54 | }); |
| 44 | 55 | }, |
src/http/mcp/tools/fork.ts +4 −2
| @@ -17,7 +17,7 @@ import { good, bad, type Tool, str, REPO_ARG, repoArg, isAnswer } from "../share | ||
| 17 | 17 | /** The MCP door to `POST /api/v1/repos/:owner/:name/forks`: the same action, the same refusals. */ |
| 18 | 18 | export const tool: Tool = { |
| 19 | 19 | name: "fork", |
| 20 | doc: "`{ repo, name? }`: fork a repository you can read into your account,. For a guest this is Help build this: a public fork that runs nothing, to change with `write_file` or git and send back with `open_pull`. `{ repo, action: \"offer\", commit }` sends a full commit id of your fork to its parent as a pull and returns its receipt `{ receipt, state: sent|seen|taken|declined|withdrawn, says, reason, upstream, url }`; `{ action: \"receipt\", receipt }` reads it again, `{ action: \"withdraw\", receipt }` takes a pending offer back (not once taken). Page: `/offers/<receipt>`. `{ repo, action: \"sever\", dryRun? }` severs your fork from its upstream: dryRun (default) says what stops and stays; `dryRun: false` with an admin token does it", | |
| 20 | doc: "`{ repo, name? }`: fork a repository you can read into your account,. For a guest this is Help build this: a public fork that runs nothing, to change with `write_file` or git and send back with `open_pull`. `{ repo, action: \"offer\", commit }` sends a full commit id of your fork to its parent as a pull and returns its receipt `{ receipt, state: sent|seen|taken|declined|withdrawn, says, reason, upstream, url }`; `{ action: \"receipt\", receipt }` reads it again, `{ action: \"withdraw\", receipt }` takes a pending offer back (not once taken). Page: `/offers/<receipt>`. `{ repo, action: \"sever\", confirm?, dryRun? }` severs your fork from its upstream: without `confirm: true` it says what stops and who is affected; with it and an admin token it does it; `undo: true` follows again within 7 days", | |
| 21 | 21 | description: "Fork a repository into your account; `action` offer sends a fork's commit upstream, receipt reads it.", |
| 22 | 22 | inputSchema: { |
| 23 | 23 | type: "object", |
| @@ -27,11 +27,13 @@ export const tool: Tool = { | ||
| 27 | 27 | action: { type: "string", enum: ["offer", "receipt", "withdraw", "sever"] }, |
| 28 | 28 | commit: { type: "string", maxLength: 40 }, |
| 29 | 29 | dryRun: { type: "boolean" }, |
| 30 | confirm: { type: "boolean" }, | |
| 31 | undo: { type: "boolean" }, | |
| 30 | 32 | receipt: { type: "string", maxLength: 32 }, |
| 31 | 33 | }, |
| 32 | 34 | }, |
| 33 | 35 | writes: true, |
| 34 | readsWhen: (args) => args["action"] === "sever" && args["dryRun"] !== false, | |
| 36 | readsWhen: (args) => args["action"] === "sever" && args["dryRun"] !== false && args["confirm"] !== true && args["undo"] !== true, | |
| 35 | 37 | async run(ctx, user, args) { |
| 36 | 38 | if (args["action"] === "sever") return detachTool.run(ctx, user, args); |
| 37 | 39 | if (args["action"] === "receipt") { |
src/http/server.ts +2 −1
| @@ -481,7 +481,7 @@ import { | ||
| 481 | 481 | mirrorStop, |
| 482 | 482 | } from "../web/pages/settings.ts"; |
| 483 | 483 | import { dangerPage, repoDelete } from "../web/pages/danger.ts"; |
| 484 | import { detachSubmit } from "../web/pages/detach.ts"; | |
| 484 | import { detachSubmit, undoSeverSubmit } from "../web/pages/detach.ts"; | |
| 485 | 485 | import { |
| 486 | 486 | hooksPage, |
| 487 | 487 | webhookCreate, |
| @@ -1895,6 +1895,7 @@ export function buildRouter(): Router<Handler> { | ||
| 1895 | 1895 | router.add("GET", "/:owner/:name/settings/danger", dangerPage); |
| 1896 | 1896 | router.add("POST", "/:owner/:name/settings/delete", repoDelete); |
| 1897 | 1897 | router.add("POST", "/:owner/:name/settings/detach", detachSubmit); |
| 1898 | router.add("POST", "/:owner/:name/settings/detach/undo", undoSeverSubmit); | |
| 1898 | 1899 | router.add( |
| 1899 | 1900 | "POST", |
| 1900 | 1901 | "/:owner/:name/settings/origin/reconnect", |
src/tui/screens/about.ts +26 −1
| @@ -33,6 +33,8 @@ import { | ||
| 33 | 33 | detachPhaseWords, |
| 34 | 34 | detachPlanWords, |
| 35 | 35 | } 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 | 38 | import { upstreamOffer, type UpstreamOffer } from "../../actions/offer_upstream.ts"; |
| 37 | 39 | import { listRefs } from "../../git/read.ts"; |
| 38 | 40 | import { directionNote } from "../../crew/direct.ts"; |
| @@ -125,6 +127,8 @@ export function aboutScreen( | ||
| 125 | 127 | // Danger zone card's gate (#7452). |
| 126 | 128 | const mayDetach = (): boolean => |
| 127 | 129 | mayPerson() && repo !== undefined && repo.forkParentId !== null; |
| 130 | // A severing is undone within seven days (`undoableSever`): an admin's, like the sever. | |
| 131 | const mayUndoSever = (): boolean => mayPerson() && repo !== undefined && undoableSever(f.app, repo) !== undefined; | |
| 128 | 132 | // The team card's button: the first agent not yet on the crew, in the first empty seat. |
| 129 | 133 | const emptySeat = () => |
| 130 | 134 | repo === undefined ? undefined : seatsOf(f.db, repo, crewOffInPreview()).seats.find((x) => x.by.length === 0); |
| @@ -262,6 +266,7 @@ export function aboutScreen( | ||
| 262 | 266 | ...(mayDetach() && detachJob(repo!.id)?.phase !== "repacking" |
| 263 | 267 | ? [binding(["x"], "sever from upstream")] |
| 264 | 268 | : []), |
| 269 | ...(mayUndoSever() ? [binding(["U"], "undo the sever (follow upstream again)")] : []), | |
| 265 | 270 | ...(offered === null |
| 266 | 271 | ? [] |
| 267 | 272 | : [ |
| @@ -438,7 +443,7 @@ export function aboutScreen( | ||
| 438 | 443 | ctx.push( |
| 439 | 444 | confirmScreen(ctx, screen, { |
| 440 | 445 | title: "Sever from upstream", |
| 441 | body: [detachPlanWords(plan.value)], | |
| 446 | body: [detachPlanWords(plan.value, severPreview(f.db, at, f.user).says)], | |
| 442 | 447 | actions: [{ label: "Detach" }, { label: "Cancel" }], |
| 443 | 448 | onChoose: (i) => { |
| 444 | 449 | if (i !== 0) return; |
| @@ -467,6 +472,26 @@ export function aboutScreen( | ||
| 467 | 472 | }); |
| 468 | 473 | return true; |
| 469 | 474 | } |
| 475 | if (e.key === "U" && repo !== undefined && mayUndoSever()) { | |
| 476 | const at = repo; | |
| 477 | ctx.push( | |
| 478 | confirmScreen(ctx, screen, { | |
| 479 | title: "Undo the sever", | |
| 480 | body: [UNDO_ASKS], | |
| 481 | actions: [{ label: "Undo" }, { label: "Cancel" }], | |
| 482 | onChoose: (i) => { | |
| 483 | if (i !== 0) return; | |
| 484 | void undoSever(f.app, f.user, at).then((done) => { | |
| 485 | repo = getRepoById(f.db, at.id) ?? at; | |
| 486 | rows = factRows(); | |
| 487 | ctx.toast(done.ok ? "following its upstream again" : UNDO_REFUSALS[done.error], done.ok ? "success" : "danger"); | |
| 488 | ctx.invalidate(); | |
| 489 | }); | |
| 490 | }, | |
| 491 | }), | |
| 492 | ); | |
| 493 | return true; | |
| 494 | } | |
| 470 | 495 | if (e.key === "l" && repo !== undefined && mayPerson()) { |
| 471 | 496 | const landing = repo.landing === "merge" ? "linear" : "merge"; |
| 472 | 497 | void updateRepoSettings(f.app, f.user, repo, { landing }).then((done) => { |
src/web/pages/detach.ts +21 −4
| @@ -8,7 +8,8 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import { detachFromParent, detachJob, type DetachJob } from "../../actions/detach.ts"; |
| 11 | import { DETACH_AGAIN, DETACH_STAYS, DETACH_STOPS } from "../../actions/detach_words.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"; | |
| 12 | 13 | import { forkParentFor, type Repo } from "../../core/repos.ts"; |
| 13 | 14 | import type { User } from "../../core/users.ts"; |
| 14 | 15 | import type { Ctx } from "../../http/context.ts"; |
| @@ -27,6 +28,8 @@ export interface DetachView { | ||
| 27 | 28 | /** Where the confirmed detach posts. */ |
| 28 | 29 | readonly action: string; |
| 29 | 30 | readonly job: DetachJob | undefined; |
| 31 | /** What stops, and who is affected, a row each (`severPreview`). */ | |
| 32 | readonly rows: SeverPreview["rows"]; | |
| 30 | 33 | } |
| 31 | 34 | |
| 32 | 35 | /** The section, for a fork; null on a repository that follows nothing. */ |
| @@ -43,11 +46,12 @@ export function detachSection( | ||
| 43 | 46 | name: parent === undefined ? "its parent" : `${parent.ownerName}/${parent.name}`, |
| 44 | 47 | action: `${repoBase(repo)}/settings/detach`, |
| 45 | 48 | job: detachJob(repo.id), |
| 49 | rows: severPreview(db, repo, viewer).rows, | |
| 46 | 50 | }); |
| 47 | 51 | } |
| 48 | 52 | |
| 49 | 53 | /** The plan and its button, the repack running since when, or the last failure over the plan. */ |
| 50 | export function detachBlock({ name, action, job }: DetachView): Html { | |
| 54 | export function detachBlock({ name, action, job, rows }: DetachView): Html { | |
| 51 | 55 | const body = |
| 52 | 56 | job?.phase === "repacking" |
| 53 | 57 | ? html`<p data-detach-progress> |
| @@ -66,9 +70,11 @@ export function detachBlock({ name, action, job }: DetachView): Html { | ||
| 66 | 70 | : null} |
| 67 | 71 | <p> |
| 68 | 72 | Copies what this fork borrows from <strong>${name}</strong> into its |
| 69 | own store and forgets the parent. ${DETACH_STAYS} ${DETACH_STOPS} | |
| 70 | It is recorded in this repository's history. ${DETACH_AGAIN} | |
| 73 | own store and forgets the parent. ${DETACH_STAYS} | |
| 71 | 74 | </p> |
outdated
Principle 7: a fact paragraph where |
||
| 75 | <dl class="status-rows" data-sever-preview> | |
| 76 | ${rows.map(([label, text]) => html`<div class="status-row"><dt>${label}</dt><dd>${text}</dd></div>`)} | |
| 77 | </dl> | |
| 72 | 78 | <div class="form-actions"> |
| 73 | 79 | ${confirmAction({ action, verb: "Sever from upstream" })} |
| 74 | 80 | </div>`; |
| @@ -78,6 +84,17 @@ export function detachBlock({ name, action, job }: DetachView): Html { | ||
| 78 | 84 | </section>`; |
| 79 | 85 | } |
| 80 | 86 | |
| 87 | /** POST /:owner/:name/settings/detach/undo — follow the parent again, within seven days. */ | |
| 88 | export async function undoSeverSubmit(ctx: Ctx): Promise<Response> { | |
| 89 | const gate = await adminForm(ctx); | |
| 90 | if (gate instanceof Response) return gate; | |
| 91 | 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]}.` }); | |
| 96 | } | |
| 97 | ||
| 81 | 98 | /** POST /:owner/:name/settings/detach — start the detach; the section shows it. */ |
| 82 | 99 | export async function detachSubmit(ctx: Ctx): Promise<Response> { |
| 83 | 100 | const gate = await adminForm(ctx); |
src/web/pages/following.ts +9 −3
| @@ -40,6 +40,7 @@ import { running } from "../../kernel/version.ts"; | ||
| 40 | 40 | import { FOLLOW_CHOICES, FOLLOW_SWITCH_LABELS, followModeWords } from "../../actions/follow_words.ts"; |
| 41 | 41 | import type { ForkFollowMode } from "../../core/fork_follow.ts"; |
| 42 | 42 | import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts"; |
| 43 | import { undoableSever } from "../../actions/sever_undo.ts"; | |
| 43 | 44 | import { convergeWords, followModeOf, lastModeChange, takeOrTell, takeWords } from "../../actions/follow.ts"; |
| 44 | 45 | import { FOLLOW_WORD, FOLLOWS_NOTHING, HIDDEN_FORK_WORD, proposeRefusalWords } from "../../actions/follow_words.ts"; |
| 45 | 46 | import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts"; |
| @@ -186,10 +187,15 @@ export function archivedParentLine(ctx: Ctx, repo: Repo): Html | null { | ||
| 186 | 187 | */ |
| 187 | 188 | export function onItsOwnLine(ctx: Ctx, repo: Repo): Html | null { |
| 188 | 189 | if (repo.forkParentId !== null || repo.severedAt === null) return null; |
| 190 | const admin = canAdmin(ctx.app.db, repo, ctx.auth.user); | |
| 191 | const undo = admin ? undoableSever(ctx.app, repo) : undefined; | |
| 189 | 192 | return html`<p class="mt small muted" data-on-its-own> |
| 190 | ${icon("fork")} On its own since ${repo.severedAt.slice(0, 10)}.${canAdmin(ctx.app.db, repo, ctx.auth.user) | |
| 191 | ? html` <a href="${repoBase(repo)}/settings#upstream">Follow upstream again</a>` | |
| 192 | : null} | |
| 193 | ${icon("fork")} On its own since ${repo.severedAt.slice(0, 10)}.${undo !== undefined | |
| 194 | ? html` <span data-sever-receipt>Undo until ${time(undo.until)}.</span> | |
| 195 | <form method="post" action="${repoBase(repo)}/settings/detach/undo" class="inline">${btn("Undo", { variant: "outline", size: "sm" })}</form>` | |
outdated
Principle 1: 'On its own since' and 'Severed ...; undo until ...' say the same thing twice. Merge into one line with the Undo button. |
||
| 196 | : admin | |
| 197 | ? html` <a href="${repoBase(repo)}/settings#upstream">Follow upstream again</a>` | |
| 198 | : null} | |
| 193 | 199 | </p>`; |
| 194 | 200 | } |
| 195 | 201 |
src/web/pages/search.ts +2 −2
| @@ -13,7 +13,7 @@ | ||
| 13 | 13 | import { ARCHIVE_DETAIL, RESTORE_DETAIL, archiveTitle, restoreTitle } from "../../core/archive-words.ts"; |
| 14 | 14 | import { cappedQuery, echoed, queryTooLong, QUERY_TRIMMED_NOTE } from "../../core/query_limit.ts"; |
| 15 | 15 | import { returnTo, withReturn } from "../return_to.ts"; |
| 16 | import { DETACH_AGAIN, DETACH_STAYS, DETACH_STOPS } from "../../actions/detach_words.ts"; | |
| 16 | import { severPreview } from "../../actions/sever_undo.ts"; | |
| 17 | 17 | import { DISCONNECT_DETAIL } from "../../actions/origin_words.ts"; |
| 18 | 18 | import { strangerCodeSearch } from "../../http/strangers.ts"; |
| 19 | 19 | import { search } from "../../actions/search.ts"; |
| @@ -667,7 +667,7 @@ const DESTRUCTIVE: { | ||
| 667 | 667 | return { |
| 668 | 668 | verb: "Sever from upstream", |
| 669 | 669 | title: `Detach ${m[1]}/${m[2]} from ${name}?`, |
| 670 | detail: `Every object it borrows is copied into its own store and the link is dropped. ${DETACH_STAYS} ${DETACH_STOPS} It is recorded in this repository's history. ${DETACH_AGAIN}`, | |
| 670 | detail: `Every object it borrows is copied into its own store and the link is dropped. ${fork === undefined ? "" : severPreview(ctx.app.db, fork, ctx.auth.user).says} It is recorded in this repository's history.`, | |
| 671 | 671 | phrase: "", |
| 672 | 672 | }; |
| 673 | 673 | }, |
test/confirm-detach.test.ts +3 −3
| @@ -75,7 +75,7 @@ test("the fork's danger zone sends Sever from upstream through the confirm page" | ||
| 75 | 75 | expect(confirm.status).toBe(200); |
| 76 | 76 | const body = await confirm.text(); |
| 77 | 77 | expect(body).toContain("Detach forker/down from upstreamer/up?"); |
| 78 | expect(body).toContain("There is no undo, but Settings › Follow upstream can follow its address again."); | |
| 78 | expect(body).toContain("Undo restores following for 7 days"); | |
| 79 | 79 | expect(body).toContain(`action="${to}"`); |
| 80 | 80 | }); |
| 81 | 81 | |
| @@ -100,10 +100,10 @@ test("the confirm and the Danger zone say what stays and what stops; the history | ||
| 100 | 100 | const to = `${base}/settings/detach`; |
| 101 | 101 | const danger = await (await fetch(`${servers.url}${base}/settings/danger`, { headers: { cookie } })).text(); |
| 102 | 102 | expect(danger).toContain("The code and its history stay"); |
| 103 | expect(danger).toContain("Updates from the parent and offers to it stop."); | |
| 103 | expect(danger).toContain("Stops down"); | |
| 104 | 104 | const body = await (await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent(to)}`, { headers: { cookie } })).text(); |
| 105 | 105 | expect(body).toContain("The code and its history stay"); |
| 106 | expect(body).toContain("Updates from the parent and offers to it stop."); | |
| 106 | expect(body).toContain("Stops down"); | |
| 107 | 107 | expect(body).toContain("recorded in this repository"); |
| 108 | 108 | |
| 109 | 109 | const post = await fetch(`${servers.url}${to}`, { |
test/danger-language.test.ts +3 −3
| @@ -86,7 +86,7 @@ test("the detach shows its plan with its parent named", async () => { | ||
| 86 | 86 | const m = main(await (await danger(forker)).text()); |
| 87 | 87 | const detach = m.slice(m.indexOf('id="detach"'), m.indexOf('id="delete"')); |
| 88 | 88 | expect(detach).toContain("<strong>upstreamer/up</strong>"); |
| 89 | expect(detach).toContain("There is no undo, but Settings › Follow upstream"); | |
| 89 | expect(detach).toContain("Undo restores following for 7 days"); | |
| 90 | 90 | expect(detach).toContain(`href="/-/confirm?to=${encodeURIComponent(`${base()}/settings/detach`)}"`); |
| 91 | 91 | }); |
| 92 | 92 | |
| @@ -94,14 +94,14 @@ test("the detach shows its running state since when, and its failure over the pl | ||
| 94 | 94 | const startedAt = new Date(Date.now() - 5 * 60_000).toISOString(); |
| 95 | 95 | const done = Promise.resolve(); |
| 96 | 96 | const action = `${base()}/settings/detach`; |
| 97 | const running = String(detachBlock({ name: "upstreamer/up", action, job: { phase: "repacking", startedAt, message: "", done } })); | |
| 97 | const running = String(detachBlock({ name: "upstreamer/up", action, rows: [], job: { phase: "repacking", startedAt, message: "", done } })); | |
| 98 | 98 | expect(running).toContain('<section class="settings-block" id="detach">'); |
| 99 | 99 | expect(running).toContain("data-detach-progress"); |
| 100 | 100 | expect(running).toMatch(/started <time [^>]*>5m ago<\/time\s*>/); |
| 101 | 101 | expect(running).not.toContain("/-/confirm"); |
| 102 | 102 | |
| 103 | 103 | const failed = String( |
| 104 | detachBlock({ name: "upstreamer/up", action, job: { phase: "failed", startedAt, message: "repack died", done } }), | |
| 104 | detachBlock({ name: "upstreamer/up", action, rows: [], job: { phase: "failed", startedAt, message: "repack died", done } }), | |
| 105 | 105 | ); |
| 106 | 106 | expect(failed).toContain("data-detach-failed"); |
| 107 | 107 | expect(failed).toContain("The last detach stopped: repack died."); |
test/fork-sever-page.test.ts +5 −3
| @@ -66,8 +66,8 @@ test("the confirm names the parent and what stops; a stranger and a cross-origin | ||
| 66 | 66 | const to = `${base}/settings/detach`; |
| 67 | 67 | const confirm = await (await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent(to)}`, { headers: { cookie } })).text(); |
| 68 | 68 | expect(confirm).toContain("Detach forker/down from upstreamer/up?"); |
| 69 | expect(confirm).toContain("Updates from the parent and offers to it stop."); | |
| 70 | expect(confirm.split("offers to it stop").length - 1).toBe(1); | |
| 69 | expect(confirm).toContain("Stops down"); | |
| 70 | expect(confirm.split("Stops down").length - 1).toBe(1); | |
| 71 | 71 | |
| 72 | 72 | const form = (origin: string, c: string) => ({ |
| 73 | 73 | method: "POST", |
| @@ -102,7 +102,9 @@ test("the confirm names the parent and what stops; a stranger and a cross-origin | ||
| 102 | 102 | expect(after).toContain("data-on-its-own"); |
| 103 | 103 | expect(after).toContain("On its own since"); |
| 104 | 104 | expect(after).toMatch(/On its own since \d{4}-\d{2}-\d{2}\./); |
| 105 | expect(after).toContain(`${base}/settings#upstream`); | |
| 105 | // Inside the seven days the one way back is Undo; the settings link returns after them. | |
| 106 | expect(after).toContain(`action="${base}/settings/detach/undo"`); | |
| 107 | expect(after).not.toContain(`${base}/settings#upstream`); | |
| 106 | 108 | const strangerView = await (await fetch(`${servers.url}${base}`, { headers: { cookie: strangerCookie } })).text(); |
| 107 | 109 | expect(strangerView).toContain("data-on-its-own"); |
| 108 | 110 | expect(strangerView).not.toContain("Follow upstream again"); |
test/sever-fork.test.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
Missing tests: parent_gone, running, open-offer count, non-admin/cross-origin undo post, TUI U, MCP undo without admin scope or as an agent, offers listed again after undo. |
||
| 2 | * #15745: severing a fork says what stops and who is affected first, leaves a receipt with an Undo | |
| 3 | * on the fork's page for seven days, follows cleanly after the upstream moved, and has the same | |
| 4 | * words and an explicit confirm on the MCP. | |
| 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 { createAgent } from "../src/actions/crew.ts"; | |
| 12 | import { openPull } from "../src/actions/pulls.ts"; | |
| 13 | import { hasAlternates, repoDir } from "../src/git/repos.ts"; | |
| 14 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 15 | import { detachFromParent, detachJob } from "../src/actions/detach.ts"; | |
| 16 | import { severPreview, undoSever, undoableSever } from "../src/actions/sever_undo.ts"; | |
| 17 | import { UNDO_DONE } from "../src/actions/detach_words.ts"; | |
| 18 | import { eventVerb } from "../src/design/activity.ts"; | |
| 19 | import { listEvents } from "../src/core/events.ts"; | |
| 20 | import { forkRepo as coreFork, getRepo, type Repo } from "../src/core/repos.ts"; | |
| 21 | import { setMember } from "../src/core/roles.ts"; | |
| 22 | import { createToken } from "../src/core/tokens.ts"; | |
| 23 | import { createUser, type User } from "../src/core/users.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 26 | import { quietLogs } from "./helpers/globals.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | ||
| 30 | let dataDir = ""; | |
| 31 | let app: App; | |
| 32 | let alice: User; | |
| 33 | let parent: Repo; | |
| 34 | let servers: Servers; | |
| 35 | const cells = process.env["FORGE_CELLS"]; | |
| 36 | ||
| 37 | const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => { | |
| 38 | if (!r.ok) throw new Error(JSON.stringify(r.error)); | |
| 39 | return r.value; | |
| 40 | }; | |
| 41 | /** One person per fork: the forge lets each fork a parent once. */ | |
| 42 | const owners = new Map<string, User>(); | |
| 43 | const forkAs = async (name: string): Promise<Repo> => | |
| 44 | ok(await coreFork(app.db, app.reposRoot, parent, owners.get(name)!.id, name)); | |
| 45 | const commit = async (repo: Repo, who: User, path: string) => | |
| 46 | ok(await commitToBranch(app, who, repo, { message: path, files: [{ path, content: `${path}\n` }] })); | |
| 47 | const sever = async (name: string): Promise<Repo> => { | |
| 48 | const fork = getRepo(app.db, name, name)!; | |
| 49 | ok(await detachFromParent(app, owners.get(name)!, fork, false)); | |
| 50 | await detachJob(fork.id)?.done; | |
| 51 | return getRepo(app.db, name, name)!; | |
| 52 | }; | |
| 53 | ||
| 54 | beforeAll(async () => { | |
| 55 | process.env["FORGE_CELLS"] = "off"; | |
| 56 | dataDir = await mkdtemp(join(tmpdir(), "forge-sever-fork-")); | |
| 57 | app = createApp({ dataDir, port: 0 }); | |
| 58 | servers = await serve(app); | |
| 59 | alice = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true })); | |
| 60 | for (const name of ["pre", "back", "late", "page", "mcpf", "offr", "gone", "busy", "gate"]) | |
| 61 | owners.set(name, ok(await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase" }))); | |
| 62 | for (const u of owners.values()) setMember(app.db, u.id, true, alice.id, new Date()); // members fork as their own | |
| 63 | parent = ok(await createRepo(app, alice, { name: "root", visibility: "public" })); | |
| 64 | await commit(parent, alice, "a.txt"); | |
| 65 | }); | |
| 66 | ||
| 67 | afterAll(async () => { | |
| 68 | servers.stop(); | |
| 69 | app.close(); | |
| 70 | if (cells === undefined) delete process.env["FORGE_CELLS"]; | |
| 71 | else process.env["FORGE_CELLS"] = cells; | |
| 72 | await rm(dataDir, { recursive: true, force: true }); | |
| 73 | }); | |
| 74 | ||
| 75 | test("the preview is four rows, each fact once, and counts the open offers", async () => { | |
| 76 | const fork = await forkAs("pre"); | |
| 77 | const none = severPreview(app.db, fork, owners.get("pre")!); | |
| 78 | expect(none.rows.map(([k]) => k)).toEqual(["Stops down", "Stops up", "Affected", "Undo"]); | |
| 79 | expect(none.rows[0]![1]).toBe("updates from alice/root no longer reach pre/pre."); | |
| 80 | expect(none.rows[1]![1]).toBe("offers to alice/root can no longer be made."); | |
| 81 | expect(none.rows[3]![1]).toContain("Undo restores following for 7 days"); | |
| 82 | expect(none.says.split("Stops down").length).toBe(2); // said once | |
| 83 | expect(none.says).not.toContain("open offer"); | |
| 84 | // Nothing changed by asking. | |
| 85 | expect(getRepo(app.db, "pre", "pre")!.forkParentId).not.toBeNull(); | |
| 86 | ||
| 87 | const mine = await forkAs("offr"); | |
| 88 | ok(await commitToBranch(app, owners.get("offr")!, mine, { branch: "feat", message: "f", files: [{ path: "f.txt", content: "f\n" }] })); | |
| 89 | ok(await openPull(app, owners.get("offr")!, parent, { title: "Offer", baseBranch: "main", headBranch: "feat", headRepo: mine })); | |
| 90 | const one = severPreview(app.db, mine, owners.get("offr")!); | |
| 91 | expect(one.offersOpen).toBe(1); | |
| 92 | expect(one.rows[1]![1]).toContain("1 open offer stops being listed there"); | |
| 93 | const { forkOffers } = await import("../src/core/fork_offers.ts"); | |
| 94 | expect(forkOffers(app.db, parent, alice)).toHaveLength(1); | |
| 95 | ||
| 96 | // Severed: the offer stops being listed at the parent; undone: it is listed again. | |
| 97 | const severed = await sever("offr"); | |
| 98 | expect(forkOffers(app.db, parent, alice)).toHaveLength(0); | |
| 99 | ok(await undoSever(app, owners.get("offr")!, severed)); | |
| 100 | expect(forkOffers(app.db, parent, alice)).toHaveLength(1); | |
| 101 | }, 30_000); | |
| 102 | ||
| 103 | test("an undo refuses while the repack runs, and when the parent can no longer be read, leaving the sever whole", async () => { | |
| 104 | const busy = await forkAs("busy"); | |
| 105 | ok(await detachFromParent(app, owners.get("busy")!, busy, false)); | |
| 106 | expect(await undoSever(app, owners.get("busy")!, busy)).toEqual({ ok: false, error: "running" }); | |
| 107 | await detachJob(busy.id)?.done; | |
| 108 | ||
| 109 | // The parent turned private since: the fork's admin cannot follow what they cannot read. | |
| 110 | const lone = ok(await createRepo(app, alice, { name: "lone", visibility: "public" })); | |
| 111 | await commit(lone, alice, "l.txt"); | |
| 112 | const f = ok(await coreFork(app.db, app.reposRoot, lone, owners.get("gone")!.id, "gonefork")); | |
| 113 | ok(await detachFromParent(app, owners.get("gone")!, f, false)); | |
| 114 | await detachJob(f.id)?.done; | |
| 115 | const severed = getRepo(app.db, "gone", "gonefork")!; | |
| 116 | app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(lone.id); | |
| 117 | expect(await undoSever(app, owners.get("gone")!, severed)).toEqual({ ok: false, error: "parent_gone" }); | |
| 118 | expect(getRepo(app.db, "gone", "gonefork")!.forkParentId).toBeNull(); | |
| 119 | ||
| 120 | // The parent readable but its store gone: the link is written and cut again, the sever stays. | |
| 121 | app.db.query("UPDATE repo SET visibility = 'public' WHERE id = ?1").run(lone.id); | |
| 122 | await rm(repoDir(app.reposRoot, lone.ownerName, lone.name), { recursive: true, force: true }); | |
| 123 | expect(await undoSever(app, owners.get("gone")!, severed)).toEqual({ ok: false, error: "parent_gone" }); | |
| 124 | expect(getRepo(app.db, "gone", "gonefork")!.forkParentId).toBeNull(); | |
| 125 | expect(await hasAlternates(repoDir(app.reposRoot, severed.ownerName, severed.name))).toBe(false); | |
| 126 | expect(listEvents(app.db, { repoId: f.id, kind: "repo.reattached", limit: 5 })).toHaveLength(0); | |
| 127 | }, 30_000); | |
| 128 | ||
| 129 | test("an undo restores following; what the parent did meanwhile arrives as an update", async () => { | |
| 130 | const fork = await forkAs("back"); | |
| 131 | const severed = await sever("back"); | |
| 132 | expect(severed.forkParentId).toBeNull(); | |
| 133 | expect(undoableSever(app, severed)).toBeDefined(); | |
| 134 | await commit(parent, alice, "moved.txt"); | |
| 135 | ||
| 136 | expect(await undoSever(app, undefined, severed)).toEqual({ ok: false, error: "unauthorized" }); | |
| 137 | const stranger = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" })); | |
| 138 | expect(await undoSever(app, stranger, severed)).toEqual({ ok: false, error: "forbidden" }); | |
| 139 | ||
| 140 | ok(await undoSever(app, owners.get("back")!, severed)); | |
| 141 | const again = getRepo(app.db, "back", "back")!; | |
| 142 | expect(again.forkParentId).toBe(parent.id); | |
| 143 | expect(again.severedAt).toBeNull(); | |
| 144 | const receipt = listEvents(app.db, { repoId: fork.id, kind: "repo.reattached", limit: 5 }); | |
| 145 | expect(receipt).toHaveLength(1); | |
| 146 | expect(eventVerb(receipt[0]!)).toContain("undid a severing"); | |
| 147 | // Spent: a second undo has nothing to undo. | |
| 148 | expect(await undoSever(app, owners.get("back")!, again)).toEqual({ ok: false, error: "nothing_to_undo" }); | |
| 149 | const { takeUpdates } = await import("../src/actions/forks.ts"); | |
| 150 | const took = await takeUpdates(app, owners.get("back")!, again); | |
| 151 | expect(took.ok && took.value.updated).toBe(true); | |
| 152 | }, 30_000); | |
| 153 | ||
| 154 | test("the undo is gone after seven days", async () => { | |
| 155 | await forkAs("late"); | |
| 156 | const severed = await sever("late"); | |
| 157 | expect(undoableSever(app, severed, Date.now() + 6 * 86_400_000)).toBeDefined(); | |
| 158 | expect(undoableSever(app, severed, Date.now() + 8 * 86_400_000)).toBeUndefined(); | |
| 159 | }); | |
| 160 | ||
| 161 | test("the fork's page carries the receipt and an Undo that posts to the undo route", async () => { | |
| 162 | await forkAs("page"); | |
| 163 | await sever("page"); | |
| 164 | const signin = await fetch(`${servers.url}/signin`, { | |
| 165 | method: "POST", | |
| 166 | headers: { origin: servers.url }, | |
| 167 | body: new URLSearchParams({ username: "page", password: "a-good-passphrase" }), | |
| 168 | redirect: "manual", | |
| 169 | }); | |
| 170 | const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 171 | const html = await (await fetch(`${servers.url}/page/page`, { headers: { cookie } })).text(); | |
| 172 | expect(html).toContain("data-sever-receipt"); | |
| 173 | expect(html).toContain('action="/page/page/settings/detach/undo"'); | |
| 174 | const post = await fetch(`${servers.url}/page/page/settings/detach/undo`, { method: "POST", headers: { cookie, origin: servers.url }, redirect: "manual" }); | |
| 175 | expect(post.status).toBe(303); | |
| 176 | expect(getRepo(app.db, "page", "page")!.forkParentId).toBe(parent.id); | |
| 177 | const gone = await (await fetch(`${servers.url}/page/page`, { headers: { cookie } })).text(); | |
| 178 | expect(gone).not.toContain("data-sever-receipt"); | |
| 179 | }); | |
| 180 | ||
| 181 | test("the MCP plans in the same words, severs only with confirm: true, and undoes", async () => { | |
| 182 | await forkAs("mcpf"); | |
| 183 | const token = createToken(app.db, owners.get("mcpf")!.id, "admin", "admin").token; | |
| 184 | const call = async (args: Record<string, unknown>): Promise<string> => { | |
| 185 | const said = await mcpTool(servers.url, token, "fork", args); | |
| 186 | return said.value?.says ?? said.error ?? ""; | |
| 187 | }; | |
| 188 | const fork = getRepo(app.db, "mcpf", "mcpf")!; | |
| 189 | const plan = await call({ repo: "mcpf/mcpf", action: "sever" }); | |
| 190 | expect(plan).toContain(severPreview(app.db, fork, owners.get("mcpf")!).says); | |
| 191 | expect(plan).toContain("confirm: true"); | |
| 192 | expect(getRepo(app.db, "mcpf", "mcpf")!.forkParentId).not.toBeNull(); | |
| 193 | ||
| 194 | await call({ repo: "mcpf/mcpf", action: "sever", confirm: true }); | |
| 195 | await detachJob(fork.id)?.done; | |
| 196 | expect(getRepo(app.db, "mcpf", "mcpf")!.forkParentId).toBeNull(); | |
| 197 | ||
| 198 | expect(await call({ repo: "mcpf/mcpf", action: "sever", undo: true })).toContain(UNDO_DONE.slice(0, 40)); | |
| 199 | expect(getRepo(app.db, "mcpf", "mcpf")!.forkParentId).toBe(parent.id); | |
| 200 | }, 30_000); | |
| 201 | ||
| 202 | test("the undo is an admin's and never an agent's, on the MCP and on the page", async () => { | |
| 203 | const fork = await forkAs("gate"); | |
| 204 | const gate = owners.get("gate")!; | |
| 205 | const severed = await sever("gate"); | |
| 206 | const bot = ok(await createAgent(app, alice, { username: "undobot" })); | |
| 207 | const call = async (token: string) => (await mcpTool(servers.url, token, "detach", { repo: "gate/gate", undo: true })).error ?? ""; | |
| 208 | const agentToken = createToken(app.db, bot.user.id, "agent", "admin").token; | |
| 209 | expect(await call(agentToken)).toContain("never an agent"); | |
| 210 | expect(await call(createToken(app.db, gate.id, "ro", "ro").token)).toContain("needs an admin token"); | |
| 211 | expect(getRepo(app.db, "gate", "gate")!.forkParentId).toBeNull(); | |
| 212 | expect(undoableSever(app, severed)).toBeDefined(); | |
| 213 | expect(await undoSever(app, bot.user, severed)).toEqual({ ok: false, error: "forbidden" }); | |
| 214 | ||
| 215 | // The page: a non-admin's post and a cross-origin post change nothing. | |
| 216 | const stranger = owners.get("pre")!; | |
| 217 | const login = async (name: string) => { | |
| 218 | const res = await fetch(`${servers.url}/signin`, { | |
| 219 | method: "POST", | |
| 220 | headers: { origin: servers.url }, | |
| 221 | body: new URLSearchParams({ username: name, password: "a-good-passphrase" }), | |
| 222 | redirect: "manual", | |
| 223 | }); | |
| 224 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 225 | }; | |
| 226 | const url = `${servers.url}/gate/gate/settings/detach/undo`; | |
| 227 | const other = await fetch(url, { method: "POST", headers: { cookie: await login(stranger.username), origin: servers.url }, redirect: "manual" }); | |
| 228 | expect(other.status).toBe(404); // the admin form answers as if the page were not there | |
| 229 | expect(getRepo(app.db, "gate", "gate")!.forkParentId).toBeNull(); | |
| 230 | const cookie = await login("gate"); | |
| 231 | const cross = await fetch(url, { method: "POST", headers: { cookie, origin: "https://evil.example" }, redirect: "manual" }); | |
| 232 | expect(cross.status).toBeGreaterThanOrEqual(400); | |
| 233 | expect(getRepo(app.db, "gate", "gate")!.forkParentId).toBeNull(); | |
| 234 | const done = await fetch(url, { method: "POST", headers: { cookie, origin: servers.url }, redirect: "manual" }); | |
| 235 | expect(done.status).toBe(303); | |
| 236 | expect(getRepo(app.db, "gate", "gate")!.forkParentId).toBe(parent.id); | |
| 237 | void fork; | |
| 238 | }, 30_000); |
test/tui-about-detach.test.ts +22
| @@ -155,3 +155,25 @@ test("the phase row is the admin's: a reader's About has none while a detach run | ||
| 155 | 155 | expect(guest).not.toMatch(/detach +(repacking|stopped)/); |
| 156 | 156 | }, 30_000); |
| 157 | 157 | |
| 158 | ||
| 159 | const tap = (s: Screen, key: string) => s.key!({ key } as unknown as Parameters<NonNullable<Screen["key"]>>[0]); | |
| 160 | ||
| 161 | test("U undoes a severing like x severs it: after a confirm, never at once, and for an admin only", async () => { | |
| 162 | // The first test's fork is severed by now and inside its seven days. | |
| 163 | expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull(); | |
| 164 | for (const who of [reader, bot]) expect(card(who).offered("U")).toBe(false); | |
| 165 | const c = card(forker); | |
| 166 | expect(c.offered("U")).toBe(true); | |
| 167 | ||
| 168 | c.press("U"); | |
| 169 | expect(c.pushed).toHaveLength(1); | |
| 170 | expect(c.pushed[0]!.title).toBe("Undo the sever"); | |
| 171 | expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull(); // asked, not done | |
| 172 | tap(c.pushed[0]!, "esc"); | |
| 173 | expect(getRepoById(app.db, fork.id)!.forkParentId).toBeNull(); | |
| 174 | ||
| 175 | c.press("U"); | |
| 176 | tap(c.pushed[1]!, "enter"); | |
| 177 | await until("the undo to land", () => getRepoById(app.db, fork.id)!.forkParentId === parent.id); | |
| 178 | expect(card(forker).offered("U")).toBe(false); | |
| 179 | }); |
Principles 1 and 8: this sentence restates DETACH_STOPS three times over and runs to a wall of text. Split into one short line per fact (down, up, who, undo) and render as dl rows.