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

In tell-me, the owner takes the parent's new code with one press on the chain page, the API or MCP #2645

Parked opened this
Closed without merging

scout/forge:scout/2642-in-tell-me-the-owner-takes-the-parent-s → main 2 commits fork 1 thread · 1 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +364 −9
README.md +7
@@ -194,6 +194,13 @@ record in `parent.json` is rewritten atomically and a `forge.follow_mode` event
194194 is appended. A non-admin is refused (403), a value outside the two modes is
195195 422, and a severed forge is 409; each leaves `parent.json` untouched.
196196
197 In either mode the admin can take the parent's last fetched code once: "Take the
198 N new commits" on the chain page (shown when behind), `POST
199 /api/v1/forge/following/take`, the MCP `take_updates_now` tool, or `t` on the chain screen in the terminal (offered when behind). A clean take
200 merges; a conflict changes nothing on main and opens (or finds) the one converge
201 issue; the result is kept in `upstream.json` as `taken`. A non-admin is refused
202 (403), a severed forge is 409, a take that did not apply (a lost race) is 409 `not_taken`, and nothing behind answers 200, "already up to date".
203
197204 The page and `GET …/following/proposals` show each proposal as open, merged or
198205 closed, read from the parent (the token may read back only pulls it opened) and
199206 cached for a minute (only a signed-in viewer makes the parent get asked); a merged or closed one is final. A parent that does not
src/actions/follow.ts +49 −1
@@ -12,7 +12,9 @@ import { convergeFork, type Converge } from "../crew/converge.ts";
1212 import { ARCHIVED_WHY, canAdmin, canWrite, forkParentFor, type Repo } from "../core/repos.ts";
1313 import type { User } from "../core/users.ts";
1414 import { err, ok, type Result } from "../kernel/result.ts";
15 import { chainOfRepo, FOLLOW_MODES, isFollowMode, setChainMode, severChain, type FollowMode } from "../spawn/chain.ts";
15 import { takeFromParent, type Taken } from "../spawn/take.ts";
16 import { recordTaken } from "../spawn/upstream.ts";
17 import { chainOfRepo, forgeLinkOf, FOLLOW_MODES, isFollowMode, setChainMode, severChain, type FollowMode } from "../spawn/chain.ts";
1618 import { requireUser } from "./access.ts";
1719 import { takeUpdates, type ForkSync, type TakeUpdatesError } from "./forks.ts";
1820
@@ -62,6 +64,52 @@ export async function severForge(
6264 return ok(cut.value);
6365 }
6466
67 export type TakeNowError = SeverError | "severed" | "not_taken";
68
69 /** The one answer every door gives a refused take, with the status an HTTP door sends. */
70 export const TAKE_REFUSALS: Record<TakeNowError, { status: number; message: string }> = {
71 unauthorized: { status: 401, message: "sign in to take your parent's new code" },
72 forbidden: { status: 403, message: "only this forge's owner can take the parent's new code" },
73 not_following: { status: 404, message: "this repository follows nothing across forges" },
74 severed: { status: 409, message: "this forge is severed and follows nothing; there is nothing to take" },
75 not_taken: { status: 409, message: "the take did not apply; try again" },
76 };
77
78 /** What a press on "take" came to: nothing behind, or what the take did. */
79 export type TakeNow = { readonly kind: "current" } | Taken;
80
81 /**
82 * Take the parent's last fetched code once, whatever the follow mode: the
83 * repository's admin only. A clean take merges; a conflict changes nothing
84 * and opens (or finds) the converge issue. The result is kept as `taken`.
85 */
86 export async function takeNow(
87 app: App,
88 actor: User | undefined,
89 repo: Repo,
90 ): Promise<Result<TakeNow, TakeNowError>> {
91 const who = requireUser(actor);
92 if (!who.ok) return err("unauthorized");
93 const link = await forgeLinkOf(app);
94 if (link === undefined || link.repo !== `${repo.ownerName}/${repo.name}`) return err("not_following");
95 if (!canAdmin(app.db, repo, who.value) || !canWrite(app.db, repo, who.value)) return err("forbidden");
96 if (link.severedAt !== undefined) return err("severed");
97 const taken = await takeFromParent(app, link);
98 const state = await recordTaken(app, taken);
outdated

takeFromParent also returns undefined when update-ref loses a race with a push, or when mergeable/merge fail for any reason other than a conflict. Here every one of those becomes {kind:"current"}, which says "Already up to date" while recordTaken recounts behind as still > 0. Report up to date only when behind really is 0 (for example, check recordTaken's recount). Otherwise return a refusal such as not_taken (409, "the take did not apply; try again"), so no door claims a success that did not happen.

99 if (taken !== undefined) return ok(taken);
100 // Nothing taken: up to date only when nothing is behind; a lost race or failed merge is not.
101 if ((state?.behind ?? 0) > 0) return err("not_taken");
102 return ok({ kind: "current" });
103 }
104
105 /** The answer in one sentence, the same for the page, the API and MCP. */
106 export function takeWords(t: TakeNow): string {
107 if (t.kind === "current") return "Already up to date: your parent has nothing you lack.";
108 if (t.kind === "took")
109 return `Took ${t.commits} new commit${t.commits === 1 ? "" : "s"} from your parent${t.merged ? " in a merge" : ""}.`;
110 return `Your parent's new code conflicts in ${t.files.join(", ")}; nothing was changed${t.issue === null ? "" : `, see issue #${t.issue}`}.`;
111 }
112
65113 export type FollowModeError = SeverError | "invalid_mode" | "severed";
66114
67115 /** The one answer every door gives a refused mode change, with the status an HTTP door sends. */
src/http/api.ts +17 −1
@@ -63,7 +63,7 @@ import { receiveBeat, SIGNATURE_HEADER } from "../spawn/heartbeat.ts";
6363 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
6464 import { listSecrets, putSecret, removeSecret } from "../actions/secrets.ts";
6565 import { forgeProposals, proposeToParentForge, proposeUpstream } from "../actions/upstream.ts";
66 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeOrTell } from "../actions/follow.ts";
66 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeNow, takeOrTell, takeWords, TAKE_REFUSALS } from "../actions/follow.ts";
6767 import { relationOf } from "../actions/forks.ts";
6868 import { chainOfRepo, forgeLinkOf } from "../spawn/chain.ts";
6969 import { noteRead, telemetryReader, type Reader } from "../actions/telemetry.ts";
@@ -2372,6 +2372,22 @@ export function apiRoutes(router: Router<Handler>): void {
23722372 return apiError(set.error, r.status, r.message);
23732373 });
23742374
2375 // Take the parent's last fetched code once, whatever the mode: the admin only.
2376 router.add("POST", "/api/v1/forge/following/take", async (ctx) => {
2377 const denied = requireScope(ctx, "rw");
2378 if (denied) return denied;
2379 const link = await forgeLinkOf(ctx.app);
2380 const [owner, name] = (link?.repo ?? "/").split("/") as [string, string];
2381 const repo = link === undefined ? undefined : getRepo(ctx.app.db, owner, name);
2382 if (repo === undefined) return apiError("not_following", 404, TAKE_REFUSALS.not_following.message);
2383 const took = await takeNow(ctx.app, ctx.auth.user, repo);
2384 if (!took.ok) {
2385 const r = TAKE_REFUSALS[took.error];
2386 return apiError(took.error, r.status, r.message);
2387 }
2388 return json({ says: takeWords(took.value), taken: took.value });
2389 });
2390
23752391 router.add(
23762392 "POST",
23772393 "/api/v1/repos/:owner/:name/following/propose",
src/http/mcp.ts +19 −1
@@ -33,7 +33,7 @@ import { changeSignup, readSignup } from "../actions/signup.ts";
3333 import { SIGNUP_MODES } from "../settings/signup.ts";
3434 import { QUOTA_KEYS } from "../settings/quotas.ts";
3535 import { LIMIT_KEYS } from "../settings/limits.ts";
36 import { convergeWords, FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeOrTell } from "../actions/follow.ts";
36 import { convergeWords, FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeNow, takeOrTell, takeWords, TAKE_REFUSALS } from "../actions/follow.ts";
3737 import { relationOf } from "../actions/forks.ts";
3838 import { chainOfRepo, FOLLOW_MODES, forgeLinkOf } from "../spawn/chain.ts";
3939 import { watchMilestone } from "../actions/watches.ts";
@@ -1596,6 +1596,24 @@ const TOOLS: readonly Tool[] = [
15961596 );
15971597 },
15981598 },
1599 {
1600 name: "take_updates_now",
1601 description:
1602 "Take the parent forge's last fetched code once, whatever the follow mode (its `forge` repository's admin only). A clean take merges; a conflict changes nothing and opens (or finds) the converge issue. Refused on a severed forge. The same words as the button on the following page.",
1603 inputSchema: {
1604 type: "object",
1605 properties: { repo: REPO_ARG },
1606 required: ["repo"],
1607 },
1608 writes: true,
1609 async run(ctx, user, args) {
1610 const repo = repoArg(ctx, user, args);
1611 if (isAnswer(repo)) return repo;
1612 const took = await takeNow(ctx.app, user, repo);
1613 if (took.ok) return good({ says: takeWords(took.value), taken: took.value });
1614 return bad(took.error, TAKE_REFUSALS[took.error].message);
1615 },
1616 },
15991617 {
16001618 name: "follow_mode",
16011619 description:
src/http/server.ts +2 −1
@@ -128,7 +128,7 @@ import {
128128 signinPasskey,
129129 } from "../web/pages/passkeys.ts";
130130 import { confirmPage, searchPage } from "../web/pages/search.ts";
131 import { chainPage, checkSubmit, modeSubmit, proposeParentSubmit, severSubmit } from "../web/pages/chain.ts";
131 import { chainPage, checkSubmit, modeSubmit, takeSubmit, proposeParentSubmit, severSubmit } from "../web/pages/chain.ts";
132132 import { followingSubmit } from "../web/pages/following.ts";
133133 import { reconnectSubmit } from "../web/pages/frozen.ts";
134134 import { activityAtom } from "../web/feeds.ts";
@@ -1273,6 +1273,7 @@ export function buildRouter(): Router<Handler> {
12731273 router.add("GET", "/:owner/:name/following", chainPage);
12741274 router.add("POST", "/:owner/:name/following/sever", severSubmit);
12751275 router.add("POST", "/:owner/:name/following/mode", modeSubmit);
1276 router.add("POST", "/:owner/:name/following/take", takeSubmit);
12761277 router.add("POST", "/:owner/:name/following/propose", proposeParentSubmit);
12771278 router.add("POST", "/:owner/:name/following/check", checkSubmit);
12781279 // A mirror pulls on demand; a pin says "keep this on my machine". Both are
src/spawn/upstream.ts +26
@@ -87,6 +87,32 @@ async function keep(app: App, s: UpstreamState): Promise<void> {
8787 }
8888 }
8989
90 /**
91 * Write what a press on "take" did into the last check: `taken`, and how far
92 * behind the fork is now. Undefined `taken` records only the recount.
93 */
94 export async function recordTaken(app: App, taken: Taken | undefined): Promise<UpstreamState | undefined> {
95 const link = await forgeLinkOf(app);
96 if (link === undefined) return undefined;
97 const [o, n] = link.repo.split("/") as [string, string];
98 const left = await runGit(["rev-list", "--count", "HEAD..refs/upstream/HEAD"], { cwd: repoDir(app.reposRoot, o, n) });
99 const count = left.ok ? Number(left.value.trim()) : NaN;
100 const before = await upstreamState(app);
101 const state: UpstreamState = {
102 behind: Number.isSafeInteger(count) ? count : (before?.behind ?? null),
103 parentTip: before?.parentTip ?? "",
104 checkedAt: before?.checkedAt ?? Date.now(),
105 error: before?.error ?? "",
106 toldTip: before?.toldTip ?? "",
107 ...(taken === undefined ? {} : { taken }),
108 };
109 await keep(app, state);
110 const repo = getRepo(app.db, o, n);
111 if (repo !== undefined)
112 app.bus.append({ kind: "forge.upstream", repoId: repo.id, payload: { repo: link.repo, behind: state.behind, error: state.error } });
113 return state;
114 }
115
90116 /** The parent's code repository as a git remote, when this forge follows and has not severed. */
91117 export async function upstreamRemote(app: App): Promise<string | undefined> {
92118 const link = await forgeLinkOf(app);
src/tui/screens/chain.ts +10 −3
@@ -2,11 +2,11 @@
22 * The chain of forges this forge's code descends from, in a card. The gate is
33 * the page's: only someone who can read `<org>/forge` sees it, and only that
44 * repository's owner is offered Sever, which asks for the same typed word,
5 * and `m`, which flips the follow mode.
5 * `m`, which flips the follow mode, and `t`, which takes the parent's new code.
66 */
77
88 import type { App as Forge } from "../../app.ts";
9 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge } from "../../actions/follow.ts";
9 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeNow, takeWords, TAKE_REFUSALS } from "../../actions/follow.ts";
1010 import { forgeProposalLine, forgeProposals, proposeToParentForge } from "../../actions/upstream.ts";
1111 import { checkUpstream, upstreamState, upstreamWords } from "../../spawn/upstream.ts";
1212 import { parentCredential } from "../../spawn/parent_credential.ts";
@@ -50,13 +50,14 @@ export async function chainScreen(app: Forge, user: User | undefined, ctx: Ctx):
5050 : []),
5151 ];
5252 let rows = await linesOf();
53 const behind = (await upstreamState(app))?.behind ?? 0;
5354 if (!owner && !writer) return familyScreen(ctx, rows, "Chain");
5455 const self: Screen = {
5556 title: "Chain",
5657 keys: [
5758 ...(writer ? [binding(["c"], "check now")] : []),
5859 ...(writer && proposing ? [binding(["p"], "propose")] : []),
59 ...(owner ? [binding(["m"], "follow mode"), binding(["s"], "sever")] : []),
60 ...(owner ? [binding(["m"], "follow mode"), ...(behind > 0 ? [binding(["t"], "take now")] : []), binding(["s"], "sever")] : []),
6061 binding(["esc"], "close"),
6162 ],
6263 render(area, s) {
@@ -101,6 +102,12 @@ export async function chainScreen(app: Forge, user: User | undefined, ctx: Ctx):
101102 rows = await linesOf();
102103 ctx.toast(`Now following in ${set.value} mode.`, "success");
103104 });
105 else if (e.key === "t" && owner)
106 void takeNow(app, user, repo).then(async (took) => {
107 if (!took.ok) return ctx.toast(TAKE_REFUSALS[took.error].message, "danger");
108 rows = await linesOf();
109 ctx.toast(takeWords(took.value), took.value.kind === "conflict" ? "danger" : "success");
110 });
104111 else if (e.key === "s" && owner)
105112 ctx.push(
106113 promptScreen(ctx, self, {
src/web/pages/chain.ts +23 −2
@@ -5,7 +5,7 @@
55 * sever. A severed forge says so with the date and nothing is deleted.
66 */
77
8 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge } from "../../actions/follow.ts";
8 import { FOLLOW_MODE_REFUSALS, setFollowMode, severForge, takeNow, takeWords, TAKE_REFUSALS } from "../../actions/follow.ts";
99 import { forgeProposals, proposeToParentForge, type ForgeProposal } from "../../actions/upstream.ts";
1010 import { canAdmin, canWrite } from "../../core/repos.ts";
1111 import type { Ctx } from "../../http/context.ts";
@@ -44,7 +44,7 @@ function modeCard(base: string, current: FollowMode | null): Html {
4444 );
4545 }
4646
47 const MODE_WORDS = { "tell-me": "tell me", "take-updates": "take updates (recorded; nothing applies them yet)" } as const;
47 const MODE_WORDS = { "tell-me": "tell me", "take-updates": "take updates every hour" } as const;
4848
4949 function lineRow(l: ChainLine, upstream?: string): Html {
5050 const where = l.host === "" ? "" : ` on ${l.host}`;
@@ -141,6 +141,13 @@ export async function chainPage(ctx: Ctx): Promise<Response> {
141141 <div class="form-actions">${btn("Check the parent now", { type: "submit" })}</div>
142142 </form>`
143143 : null}
144 ${owner && view.severedAt === null && (state?.behind ?? 0) > 0
145 ? html`<form method="post" action="${base}/following/take" class="mt">
146 <div class="form-actions">
147 ${btn(`Take the ${state!.behind} new commit${state!.behind === 1 ? "" : "s"}`, { type: "submit", icon: "merge" })}
148 </div>
149 </form>`
150 : null}
144151 ${owner && view.severedAt === null ? modeCard(base, view.lines[view.lines.length - 1]?.mode ?? null) : null}
145152 ${proposing ? proposalCard(base, proposals, writer) : null}
146153 ${view.severedAt !== null
@@ -204,6 +211,20 @@ export async function checkSubmit(ctx: Ctx): Promise<Response> {
204211 return flashOrJson(ctx, to, state.error === "" ? { message: upstreamWords(state) } : { tone: "danger", message: upstreamWords(state) });
205212 }
206213
214 /** POST /:owner/:name/following/take: take the parent's fetched code once; the owner only. */
215 export async function takeSubmit(ctx: Ctx): Promise<Response> {
216 const repo = loadRepo(ctx);
217 if (!repo) return notFoundPage(ctx);
218 if (!ctx.auth.user) return signInFirst(ctx);
219 const form = await readForm(ctx, "rw");
220 if (form instanceof Response) return form;
221 const to = `${repoBase(repo)}/following`;
222 const took = await takeNow(ctx.app, ctx.auth.user, repo);
223 if (!took.ok) return flashOrJson(ctx, to, { tone: "danger", message: TAKE_REFUSALS[took.error].message });
224 const message = takeWords(took.value);
225 return flashOrJson(ctx, to, took.value.kind === "conflict" ? { tone: "danger", message } : { message });
226 }
227
207228 /** POST /:owner/:name/following/mode {mode}; the owner only. */
208229 export async function modeSubmit(ctx: Ctx): Promise<Response> {
209230 const repo = loadRepo(ctx);
test/follow-take-now.test.ts added +210
@@ -0,0 +1,210 @@
1 /**
2 * The owner takes the parent's new code with one press (#2642): the same
3 * action behind the chain page, the API and MCP, over two local bare
4 * repositories and a forge in `tell-me`.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { listIssues } from "../src/core/issues.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { runGit } from "../src/git/env.ts";
19 import { repoDir } from "../src/git/repos.ts";
20 import { chainScreen } from "../src/tui/screens/chain.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { severChain } from "../src/spawn/chain.ts";
23 import { checkUpstream, upstreamState } from "../src/spawn/upstream.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25
26 quietLogs();
27
28 const git = async (cwd: string, ...args: string[]) => {
29 const r = await runGit(["-c", "user.name=t", "-c", "[email protected]", ...args], { cwd });
30 if (!r.ok) throw new Error(r.error.stderr);
31 return r.value.trim();
32 };
33
34 describe("taking the parent's code with one press", () => {
35 let dir = "";
36 let app: App;
37 let servers: Servers;
38 let kid: User;
39 let repo: Repo;
40 let child = "";
41 let parent = "";
42 let work = "";
43 let ownerTok = "";
44 let readerTok = "";
45 let readerCookie = "";
46 let cookie = "";
47 let id = 1;
48
49 const mine = async (path: string, content: string) => {
50 const r = await commitToBranch(app, kid, repo, { message: `kid: ${path}`, files: [{ path, content }] });
51 if (!r.ok) throw new Error(JSON.stringify(r.error));
52 };
53 const theirs = async (path: string, content: string) => {
54 await Bun.write(join(work, path), content);
55 await git(work, "add", ".");
56 await git(work, "commit", "-m", `parent: ${path}`);
57 await git(work, "push", "-q", parent, "HEAD:refs/heads/main");
58 await checkUpstream(app, { remote: parent });
59 };
60 const main = () => git(child, "rev-parse", "refs/heads/main");
61 const api = (tok: string) =>
62 fetch(`${servers.url}/api/v1/forge/following/take`, { method: "POST", headers: { authorization: `Bearer ${tok}` } });
63 const tool = async (tok: string) => {
64 const res = await fetch(`${servers.url}/mcp`, {
65 method: "POST",
66 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` },
67 body: JSON.stringify({ jsonrpc: "2.0", id: id++, method: "tools/call", params: { name: "take_updates_now", arguments: { repo: "kid/forge" } } }),
68 });
69 const j = (await res.json()) as any;
70 return { error: j.result.isError === true, text: String(j.result.content[0].text) };
71 };
72 const press = (ck: string) =>
73 fetch(`${servers.url}/kid/forge/following/take`, {
74 method: "POST",
75 headers: { cookie: ck, origin: servers.url },
76 redirect: "manual",
77 });
78 const page = async () =>
79 (await (await fetch(`${servers.url}/kid/forge/following`, { headers: { cookie } })).text()).replace(/\s+/g, " ");
80 const converge = () => listIssues(app.db, repo.id, { sealed: true }).filter((i) => i.title === "Take updates from root/forge");
81
82 beforeAll(async () => {
83 dir = await mkdtemp(join(tmpdir(), "forge-take-now-"));
84 app = createApp({ dataDir: join(dir, "data"), port: 0 });
85 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "kid", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
86 if (!u.ok) throw new Error(u.error);
87 kid = u.value;
88 const r = await createUser(app.db, { origin: "seed", trusted: true, username: "reader", email: "[email protected]" });
89 if (!r.ok) throw new Error("reader");
90 const made = await createRepo(app, kid, { name: "forge", visibility: "public" });
91 if (!made.ok) throw new Error(String(made.error));
92 repo = made.value;
93 child = repoDir(app.reposRoot, "kid", "forge");
94 await mine("a.txt", "base\n");
95 parent = join(dir, "parent.git");
96 work = join(dir, "work");
97 await git(dir, "clone", "-q", "--bare", child, parent);
98 await git(dir, "clone", "-q", parent, work);
99 await Bun.write(
100 join(app.config.dataDir, "parent.json"),
101 JSON.stringify({
102 upstream: "https://parent.test",
103 forgeCode: { repo: "kid/forge", upstream: "root/forge", mode: "tell-me", tip: "a".repeat(40), chain: [] },
104 }),
105 );
106 servers = await serve(app);
107 ownerTok = createToken(app.db, kid.id, "t", "rw").token;
108 readerTok = createToken(app.db, r.value.id, "t", "rw").token;
109 readerCookie = `forge_session=${createSession(app.db, r.value.id).token}`;
110 cookie = `forge_session=${createSession(app.db, kid.id).token}`;
111 }, 30_000);
112 afterAll(async () => {
113 servers.stop();
114 app.close();
115 await rm(dir, { recursive: true, force: true });
116 });
117
118 test("nothing behind answers 200, already up to date, and changes nothing", async () => {
119 await checkUpstream(app, { remote: parent });
120 const before = await main();
121 const res = await api(ownerTok);
122 expect(res.status).toBe(200);
123 expect(((await res.json()) as any).says).toContain("Already up to date");
124 expect(await main()).toBe(before);
125 expect(await page()).not.toContain("/following/take");
126 });
127
128 test("a take that does not apply is refused, not called up to date", async () => {
129 await theirs("pf.txt", "f\n");
130 const before = await main();
131 const lock = join(child, "refs/heads/main.lock");
132 await Bun.write(lock, "");
133 const res = await api(ownerTok);
134 expect(res.status).toBe(409);
135 expect(((await res.json()) as any).error).toBe("not_taken");
136 expect((await tool(ownerTok)).error).toBe(true);
137 expect(await main()).toBe(before);
138 await rm(lock);
139 expect((await api(ownerTok)).status).toBe(200);
140 expect(await main()).not.toBe(before);
141 });
142
143 test("a non-admin is refused by every door and nothing moves", async () => {
144 await mine("m0.txt", "0\n");
145 await theirs("p0.txt", "0\n");
146 const before = await main();
147 expect((await api(readerTok)).status).toBe(403);
148 expect((await tool(readerTok)).error).toBe(true);
149 const res = await press(readerCookie);
150 expect(res.status).toBe(303);
151 expect(await main()).toBe(before);
152 expect((await upstreamState(app))?.behind).toBe(1);
153 });
154
155 test("tell-me shows the button; a press merges and the page says so", async () => {
156 const html = await page();
157 expect(html).toContain('action="/kid/forge/following/take"');
158 expect(html).toContain("Take the 1 new commit");
159 expect(html).not.toContain("<script>");
160 const cross = await fetch(`${servers.url}/kid/forge/following/take`, { method: "POST", headers: { cookie, origin: "https://evil.test" } });
161 expect(cross.status).toBe(403);
162 const before = await main();
163 expect((await press(cookie)).status).toBe(303);
164 expect(await main()).not.toBe(before);
165 expect(await git(child, "show", "refs/heads/main:p0.txt")).toBe("0");
166 const s = await upstreamState(app);
167 expect(s?.taken).toMatchObject({ kind: "took", commits: 1, merged: true });
168 expect(s?.behind).toBe(0);
169 expect(await page()).not.toContain("Take the 1 new commit");
170 });
171
172 test("a conflict leaves main alone and opens one issue, through API and MCP", async () => {
173 await mine("a.txt", "kid's\n");
174 await theirs("a.txt", "parent's\n");
175 const before = await main();
176 const res = await api(ownerTok);
177 expect(res.status).toBe(200);
178 const body = (await res.json()) as any;
179 expect(body.taken).toMatchObject({ kind: "conflict", files: ["a.txt"] });
180 const viaTool = await tool(ownerTok);
181 expect(viaTool.error).toBe(false);
182 expect(viaTool.text).toContain(body.says);
183 expect(await main()).toBe(before);
184 expect(converge()).toHaveLength(1);
185 expect((await upstreamState(app))?.taken).toMatchObject({ kind: "conflict", issue: converge()[0]!.number });
186 });
187
188 test("the terminal chain screen offers t to the owner and words the answer the same", async () => {
189 const toasts: [string, string | undefined][] = [];
190 const ctx = { toast: (m: string, t?: string) => toasts.push([m, t]), pop() {}, push() {}, theme: {} } as any;
191 const screen = await chainScreen(app, kid, ctx);
192 expect(JSON.stringify(screen.keys)).toContain("take now");
193 const before = await main();
194 screen.key({ key: "t" } as any);
195 await Bun.sleep(300);
196 expect(toasts.at(-1)![0]).toContain("conflicts in a.txt");
197 expect(toasts.at(-1)![1]).toBe("danger");
198 expect(await main()).toBe(before);
199 expect(converge()).toHaveLength(1);
200 });
201
202 test("a severed forge is refused with 409", async () => {
203 const cut = await severChain(app);
204 expect(cut.ok).toBe(true);
205 const before = await main();
206 expect((await api(ownerTok)).status).toBe(409);
207 expect((await tool(ownerTok)).error).toBe(true);
208 expect(await main()).toBe(before);
209 });
210 });
test/mcp.test.ts +1
@@ -199,6 +199,7 @@ describe("the forge over MCP", () => {
199199 "claim_link",
200200 "take_updates",
201201 "sever",
202 "take_updates_now",
202203 "follow_mode",
203204 "propose_to_parent_forge",
204205 "forge_proposals",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs