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

A repository follows its upstream: new upstream commits land by themselves - clean merges through the gate, conflicts to the crew, then landed #3468

Closed opened this in answer to
Closed without merging

torque/forge:torque/3442-a-repository-follows-its-upstream-new-up → main 8 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +1990 −9
docs/ORIGINS.md +49
@@ -534,6 +534,55 @@ The clone runs as a job in the mirror's registry (`origins/jobs.ts`, kind
534534 app and the crew's first run — and then lands on the repository, which is
535535 the app's page, with what happened as the flash.
536536
537 ## Follow upstream — new upstream commits land by themselves
538
539 A migration forgets the URL for git, but keeps it as the repository's
540 upstream (`repo_upstream`, `core/upstream_follow.ts`): the source and its
541 default branch, its parent offered as the second choice when the host said
542 it is a fork. Following is on when the crew was put on it autonomous, and
543 off — filled in — otherwise. The settings page's **Follow upstream** card
544 turns it on or off and points it anywhere git may be handed (`migrateUrl`,
545 the same private-host rule as migrate); a private upstream uses the
546 person's connected origin on that host (`origins/credentials.ts`).
547
548 Every 30 minutes beside the autonomy tick, or on **Check upstream now**
549 (`actions/upstream_follow.ts`): `ls-remote`, and a fetch only when the tip
550 moved, into `refs/upstream/<branch>` — not a branch, so nothing of ours
551 moves. Then git decides:
552
553 - a fast-forward or a clean `git merge`: a pull
554 `Upstream: N commits from <upstream> (<base>..<tip>)` from
555 `upstream/<tip7>` (the tip, or the clean merge commit on top of ours),
556 opened as the person who turned following on. It lands through the
557 landing gate like any pull — as a **merge**, never a squash, whenever its
558 head carries upstream commits the base lacks (`carriesUpstream`), so
559 upstream's history stays an ancestor and the next check counts only what
560 is new.
561 - a conflict (an upstream deletion of a file we changed is one): an issue
562 with the same title and the files, assigned to a builder as a `converge`
563 run whose brief says merge the staged tip, keep upstream's fixes and our
564 work, explain each resolution. Its pull is reviewed and lands like any
565 crew pull.
566
567 One check runs at a time per repository, whichever door asked — the tick,
568 the page, the terminal or the API; a second is refused `busy` (409 in the
569 API) rather than racing the first to open a second proposal. One proposal
570 stands at a time; one closed unlanded is not opened again until upstream
571 moves, unless a person checks now. A finished check emits
572 `repo.upstream_checked`, so an open About card or page updates. Never a push to the
573 default branch, never a force-push. The About card says
574 "Following <upstream> · last checked HH:MM · N behind"; the tick line's
575 `upstream=` says how far behind and how many were proposed. In the
576 terminal, About (`I`) shows the same as a `following` row — on for every
577 reader, off for admins only, as on the page and in the API — and a writer's
578 `u` checks now. An admin's `f` turns it on or off (asking where, the first
579 time) and `F` points it elsewhere: the same `setFollowUpstream` and the same
580 refusals as the page and the API.
581 Why a check failed is the remote's stderr, redacted, and only writers read
582 it; a `git://` upstream is named, not linked. API:
583 `GET|PUT /api/v1/repos/:owner/:name/upstream`,
584 `POST /api/v1/repos/:owner/:name/upstream/check`.
585
537586 ## API
538587
539588 ```
src/actions/migrate.ts +24
@@ -67,6 +67,10 @@ import {
6767 } from "./repos.ts";
6868 import { tell, toldWords } from "./tell.ts";
6969 import { remoteGitEnv } from "../git/remote-env.ts";
70 import { setFollowUpstream } from "./upstream_follow.ts";
71 import { createLog } from "../kernel/log.ts";
72
73 const log = createLog("migrate");
7074
7175 /** The whole clone — the HEAD probe and the fetch — gets this long. */
7276 export const MIGRATE_TIMEOUT_MS = 120_000;
@@ -127,6 +131,8 @@ interface Resolved {
127131 readonly provider?: Provider;
128132 /** The person, as the source's commits may name them. */
129133 readonly who: Who;
134 /** The source's own parent on its host, when it is a fork: following's second choice. */
135 readonly parentUrl?: string;
130136 }
131137
132138 /** Why the work branch is the one it is: said in the job and the brief. */
@@ -424,6 +430,9 @@ export async function resolveSource(
424430 authEnv: () => provider.value.gitAuthEnv(url),
425431 provider: provider.value,
426432 who: { logins: [origin.login, user.username], emails: [user.email] },
433 ...(remote.value.parent === null
434 ? {}
435 : { parentUrl: `${origin.webUrl.replace(/\/+$/, "")}/${remote.value.parent}` }),
427436 });
428437 }
429438
@@ -533,6 +542,21 @@ async function runMigration(
533542 });
534543 }
535544
545 // The source becomes the upstream this repository follows (#3442): on
546 // when the crew runs it on its own, off — but filled in — otherwise.
547 const followed = await setFollowUpstream(app, user, current, {
548 url: source.url,
549 branch: cloned.value.head ?? work?.name ?? current.defaultBranch,
550 enabled: crew?.autonomous === true,
551 originId: source.originId,
552 ...(source.parentUrl === undefined ? {} : { parentUrl: source.parentUrl }),
553 });
554 if (!followed.ok)
555 log.warn("migrated repository does not follow its source", {
556 repo: `${current.ownerName}/${current.name}`,
557 why: followed.error,
558 });
559
536560 const where = `${current.ownerName}/${current.name}`;
537561 let detail = `migrated as ${where} — ${plural(branches.length, "branch", "branches")}, ${plural(refs.size - branches.length, "tag")}${conversations}`;
538562 if (work !== undefined)
src/actions/upstream_follow.ts added +618
@@ -0,0 +1,618 @@
1 /**
2 * A repository follows its upstream (#3442): an outside git URL and branch
3 * whose new commits land here by themselves, never by a push to the
4 * default branch.
5 *
6 * A check is cheap: one `ls-remote`, and a fetch only when the tip moved,
7 * into `refs/upstream/<branch>` — a ref that is not a branch, so nothing
8 * of ours is ever moved by it. Then git decides, deterministically:
9 *
10 * - the default branch fast-forwards to the upstream tip, or `git merge`
11 * is clean: a pull "Upstream: N commits from <upstream> (<range>)" from
12 * the branch `upstream/<tip>` (the tip itself, or the clean merge commit
13 * on top of the default branch), opened as the person who turned
14 * following on. It lands through the landing gate like any pull, as a
15 * merge, so upstream's history stays an ancestor of ours (`carriesUpstream`).
16 * - the merge conflicts — an upstream deletion of a file we changed is one:
17 * an issue with the same title, the files named, handed to a builder as a
18 * converge run (`crew/brief.ts`): merge the staged tip, keep upstream's
19 * fixes and our work, explain each resolution. Its pull is reviewed and
20 * lands like any crew pull.
21 *
22 * Never a force-push, never a rewrite of our history: one proposal stands
23 * at a time, and the next check after it closes proposes what is left.
24 */
25
26 import type { App } from "../app.ts";
27 import { listCrewRoles } from "../core/agents.ts";
28 import { commitIdentity } from "../core/commit_identity.ts";
29 import { getIssueById, setAssignee } from "../core/issues.ts";
30 import { getOriginFor, listOrigins } from "../core/origins.ts";
31 import { canAdmin, canWrite, getRepoById, type Repo } from "../core/repos.ts";
32 import { listRuns } from "../core/runs.ts";
33 import { storageStale } from "../core/storage.ts";
34 import {
35 getFollow,
36 listFollowing,
37 noteCheck,
38 putFollow,
39 type UpstreamFollow,
40 } from "../core/upstream_follow.ts";
41 import { getUserById, type User } from "../core/users.ts";
42 import { queueAgentRun } from "../crew/dispatch.ts";
43 import { pickBuilder } from "../crew/route.ts";
44 import { createBranch, isBranchName } from "../git/branches.ts";
45 import { runGit, runGitCapture } from "../git/env.ts";
46 import { isSafeOid } from "../git/guard.ts";
47 import { aheadCount, mergeBase, mergeable, resolveOid } from "../git/merge.ts";
48 import { remoteGitEnv } from "../git/remote-env.ts";
49 import { repoDir } from "../git/repos.ts";
50 import { createLog } from "../kernel/log.ts";
51 import { type Resolve, vetHost } from "../kernel/outbound.ts";
52 import { err, ok, type Result } from "../kernel/result.ts";
53 import { providerForOrigin } from "../origins/credential.ts";
54 import { redact, secretsIn } from "../origins/credentials.ts";
55 import { isTrustedHost } from "../origins/trusted-hosts.ts";
56 import { requireRepoAdmin, requireWriter, type AccessError } from "./access.ts";
57 import { openIssue } from "./issues.ts";
58 import { isPrivateHost, migrateUrl } from "./migrate.ts";
59 import { openPull } from "./pulls.ts";
60
61 const log = createLog("upstream-follow");
62
63 /** How often a following repository is checked on its own. */
64 export const FOLLOW_EVERY_MS = 30 * 60_000;
65 /** One check's whole budget: ls-remote and fetch together. */
66 const CHECK_TIMEOUT_MS = 120_000;
67 /** The transports an upstream may speak. */
68 const PROTOCOLS = "https:http:git";
69 /** Where the upstream tip is staged: not a branch, so a check moves nothing of ours. */
70 export const stagedRef = (branch: string): string => `refs/upstream/${branch}`;
71 /** The branch a clean proposal is opened from. */
72 const proposalBranch = (tip: string): string => `upstream/${tip.slice(0, 7)}`;
73 /** Every proposal's title begins so; the tick line and the page count them by it. */
74 export const UPSTREAM_TITLE = "Upstream: ";
75
76 /** `github.com/Trevato/SO-ARM100` for `https://github.com/Trevato/SO-ARM100.git`. */
77 export function upstreamLabel(url: string): string {
78 return url
79 .replace(/^[a-z]+:\/\//i, "")
80 .replace(/\/+$/, "")
81 .replace(/\.git$/, "");
82 }
83
84 export type FollowError =
85 | AccessError
86 | "invalid_url"
87 | "private_host"
88 | "invalid_branch"
89 | "archived"
90 /** A mirror's history is its origin's; it follows nothing else. */
91 | "mirrored";
92
93 /** What each refusal says, at every door. */
94 export const FOLLOW_REFUSALS: Record<FollowError | CheckError, string> = {
95 unauthorized: "Sign in to change where this repository follows.",
96 forbidden: "Only this repository's admins change where it follows.",
97 not_found: "That repository is not here.",
98 invalid_url: "That is not a git address the forge will fetch: use https://, http:// or git://, with no password in it.",
99 private_host: "That address is inside the network, not a public repository.",
100 invalid_branch: "That is not a branch name.",
101 archived: "This repository is archived; wake it first.",
102 mirrored: "A mirror follows its origin; it cannot follow another upstream.",
103 off: "Following an upstream is off for this repository.",
104 unreadable: "The upstream could not be read.",
105 no_branch: "The upstream has no such branch.",
106 diverged: "The staged upstream tip could not be fetched.",
107 git: "Git could not prepare the proposal.",
108 nobody: "The person who turned following on can no longer write here; turn it on again.",
109 busy: "A check of this upstream is already running; its answer is on the way.",
110 };
111
112 /** A pasted address the forge may fetch, refused inside the network unless allowed. */
113 export async function upstreamUrl(
114 app: App,
115 actor: User,
116 raw: string,
117 resolve?: Resolve,
118 ): Promise<Result<string, "invalid_url" | "private_host">> {
119 const url = migrateUrl(raw);
120 if (url === undefined) return err("invalid_url");
121 const host = new URL(url).hostname;
122 // The same rule migrate keeps (`resolveSource`): an admin, a forge run
123 // for one person, or a host the admin trusts may be inside the network.
124 if (actor.isAdmin || app.config.migrateFromPrivateHosts === true || isTrustedHost(host))
125 return ok(url);
126 if (isPrivateHost(host)) return err("private_host");
127 const vetted = await vetHost(host, resolve ? { resolve } : {});
128 if (!vetted.ok && vetted.error === "refused") return err("private_host");
129 return ok(url);
130 }
131
132 /** The actor's connected origin on the upstream's host: its credential opens a private one. */
133 function originOn(app: App, user: User, url: string): string {
134 const host = new URL(url).hostname.toLowerCase();
135 const origin = listOrigins(app.db, user.id).find((o) => {
136 try {
137 return new URL(o.webUrl).hostname.toLowerCase() === host;

High: this matches by hostname only, so an http:// upstream on a connected host picks up that origin, and gitAuthEnv(follow.url) then scopes the token to http://host/, which sends it in cleartext. Require new URL(url).origin === new URL(o.webUrl).origin.

138 } catch {
139 return false;
140 }
141 });
142 return origin?.id ?? "";
143 }
144
145 /**
146 * Turn following on or off, or point it elsewhere: the repository's admins
147 * only. Whoever saves it on is who the forge acts as.
148 */
149 export async function setFollowUpstream(
150 app: App,
151 actor: User | undefined,
152 repo: Repo,
153 input: {
154 readonly url: string;
155 readonly branch: string;
156 readonly enabled: boolean;
157 readonly parentUrl?: string;
158 /** The origin the source came through, when the caller knows it (migrate). */
159 readonly originId?: string;
160 },
161 resolve?: Resolve,
162 ): Promise<Result<UpstreamFollow, FollowError>> {
163 const admin = requireRepoAdmin(app, actor, repo);
164 if (!admin.ok) return admin;
165 if (repo.archivedAt !== null && input.enabled) return err("archived");
166 if (repo.origin !== null && input.enabled) return err("mirrored");
167 const branch = input.branch.trim();
168 if (!isBranchName(branch)) return err("invalid_branch");
169 const url = await upstreamUrl(app, admin.value, input.url, resolve);
170 if (!url.ok) return url;
171 const parent =
172 input.parentUrl === undefined || input.parentUrl === ""
173 ? undefined
174 : migrateUrl(input.parentUrl);
175 const follow = putFollow(app.db, {
176 repoId: repo.id,
177 url: url.value,
178 branch,
179 enabled: input.enabled,
180 byId: admin.value.id,
181 originId: input.originId ?? originOn(app, admin.value, url.value),
182 ...(parent === undefined ? {} : { parentUrl: parent }),
183 });
184 app.bus.append({
185 kind: "repo.upstream_follow",
186 repoId: repo.id,
187 actorId: admin.value.id,
188 payload: { url: follow.url, branch: follow.branch, enabled: follow.enabled },
189 });
190 return ok(follow);
191 }
192
193 export type CheckError =
194 | "off"
195 | "unreadable"
196 | "no_branch"
197 | "diverged"
198 | "git"
199 | "nobody"
200 /** Another check of this repository is in flight: one at a time, at every door. */
201 | "busy";
202
203 /** What one check found. */
204 export type Checked =
205 | { readonly kind: "up_to_date"; readonly tip: string }
206 /** A proposal is already open; it is the one to land first. */
207 | { readonly kind: "pending"; readonly behind: number; readonly id: string }
208 /** The last proposal of this same tip was closed unlanded: asked again only by a person. */
209 | { readonly kind: "declined"; readonly behind: number; readonly id: string }
210 | { readonly kind: "pull"; readonly behind: number; readonly number: number }
211 | {
212 readonly kind: "conflict";
213 readonly behind: number;
214 readonly number: number;
215 readonly files: readonly string[];
216 readonly builder: string | undefined;
217 };
218
outdated

No in-flight guard here: a manual check can overlap another manual check or the tick's check. Each reads pendingId === null, and each opens a pull (or an issue plus a converge run). Move the checking claim into checkUpstream so every door shares it, and refuse or join a second caller.

219 /** "Check upstream now": a writer may ask; the check acts as who turned it on. */
220 export async function checkUpstreamNow(
221 app: App,
222 actor: User | undefined,
223 repo: Repo,
224 ): Promise<Result<Checked, AccessError | CheckError>> {
225 const writer = requireWriter(app, actor, repo);
226 if (!writer.ok) return writer;
227 return checkUpstream(app, repo, true);
228 }
229
230 /** Repositories with a check in flight: one at a time each, whoever asked. */
231 const checking = new Set<string>();
232
233 /**
234 * One check, of one repository. Every outcome is noted on its row. The
235 * claim is taken before the first await, so two callers — a double click,
236 * the page and the terminal, a person and the tick — never both read "no
237 * proposal open" and both open one: the second is answered `busy`.
238 */
239 export async function checkUpstream(
240 app: App,
241 repo: Repo,
242 /** A person asked: a proposal they closed of this same tip is opened again. */
243 asked = false,
244 ): Promise<Result<Checked, CheckError>> {
245 if (checking.has(repo.id)) return err("busy");
246 checking.add(repo.id);
247 let checked: Result<Checked, CheckError> = err("git");
248 try {
249 checked = await checkOnce(app, repo, asked);
250 return checked;
251 } finally {
252 checking.delete(repo.id);
253 // An open About card or settings page redraws its "last checked" line;
254 // a following that is off was not checked, and says nothing.
255 if (checked.ok || checked.error !== "off")
256 app.bus.append({
257 kind: "repo.upstream_checked",
258 repoId: repo.id,
259 payload: { behind: getFollow(app.db, repo.id)?.behind ?? 0 },
260 });
261 }
262 }
263
264 async function checkOnce(app: App, repo: Repo, asked: boolean): Promise<Result<Checked, CheckError>> {
265 const follow = getFollow(app.db, repo.id);
266 if (follow === undefined || !follow.enabled || repo.archivedAt !== null || repo.origin !== null)
267 return err("off");
268 const at = new Date().toISOString();
269 const failed = (error: CheckError, why = ""): Result<Checked, CheckError> => {
270 noteCheck(app.db, repo.id, { at, error: why || FOLLOW_REFUSALS[error] });
271 return err(error);
272 };
273 const by = getUserById(app.db, follow.byId);
274 if (by === undefined || !canWrite(app.db, repo, by)) return failed("nobody");
275
276 // The credential, when the upstream is private: the connected origin's,
277 // scoped to this one git invocation (`origins/credentials.ts`).
278 let authEnv: Record<string, string> = {};
279 if (follow.originId !== "") {
280 const origin = getOriginFor(app.db, by.id, follow.originId);
281 const provider = origin === undefined ? undefined : providerForOrigin(app, origin);
282 if (provider?.ok) authEnv = await provider.value.gitAuthEnv(follow.url);

Check here too, not just when saving: only call gitAuthEnv when the follow URL's origin is exactly the connected origin's https origin. Rows saved by migrate pass originId directly and skip originOn.

283 }
284 // Checked again each time: a name that resolved outside the network may not now.
285 const vetted = await upstreamUrl(app, by, follow.url);
286 if (!vetted.ok) return failed("unreadable", FOLLOW_REFUSALS[vetted.error]);
287 const env = remoteGitEnv(authEnv, undefined, PROTOCOLS);

Medium: there's no pin, so git resolves the host again after upstreamUrl vetted it (DNS rebinding on a fetch that repeats every 30 min). Pin the vetted address the way origins/git-mirror.ts vettedEnv does: remoteGitEnv(authEnv, pinFor(follow.url, ip), PROTOCOLS).

288 const said = (stderr: string): string =>
289 redact(stderr.trim(), ...secretsIn(authEnv)).split("\n").find((l) => l.trim() !== "") ?? "";
290 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
291 const deadline = Date.now() + CHECK_TIMEOUT_MS;
292 const remaining = (): number => Math.max(1_000, deadline - Date.now());
293
294 const listed = await runGitCapture(
295 ["ls-remote", "--", follow.url, `refs/heads/${follow.branch}`],
296 { cwd: dir, env, timeoutMs: remaining() },
297 );
298 if (listed.code !== 0)
outdated

This 'one proposal at a time' read is stale under concurrency: follow was read before the first await, and pendingId is only written after openPull. Two checks both pass this point.

299 return failed("unreadable", `The upstream could not be read: ${said(listed.stderr) || "no reason given"}`);
300 const tip = listed.stdout.split("\t")[0]?.trim() ?? "";
301 if (!isSafeOid(tip)) return failed("no_branch");
302
303 // Fetch only when the tip moved: the staged ref is what the last fetch brought.
304 const ref = stagedRef(follow.branch);
305 if ((await resolveOid(dir, ref)) !== tip) {
306 const fetched = await runGitCapture(
307 [
308 "fetch",
309 "--no-tags",
310 "--no-write-fetch-head",
311 "--no-recurse-submodules",
312 "--quiet",
313 "--",
314 follow.url,
315 `+refs/heads/${follow.branch}:${ref}`,
316 ],
317 { cwd: dir, env, timeoutMs: remaining() },
318 );
319 if (fetched.code !== 0)
320 return failed("unreadable", `The upstream could not be fetched: ${said(fetched.stderr) || "no reason given"}`);
321 // What arrived counts against the owner's storage, as a migration's does.
322 storageStale(app, repo.ownerId);
323 }
324 const staged = await resolveOid(dir, ref);
325 if (staged === undefined) return failed("diverged");
326
327 const main = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
328 if (main === undefined) return failed("git", "The default branch has no commits yet.");
329 const behind = await aheadCount(dir, main, staged);
330 if (behind === 0) {
331 noteCheck(app.db, repo.id, { at, tip: staged, behind: 0, error: "", pendingId: null });
332 return ok({ kind: "up_to_date", tip: staged });
333 }
334 // One proposal at a time: while it is open, it is the one to land.
335 if (follow.pendingId !== null) {
336 const pending = getIssueById(app.db, follow.pendingId);
337 if (pending !== undefined && pending.state === "open") {
338 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
339 return ok({ kind: "pending", behind, id: pending.id });
340 }
341 // Closed without landing, and upstream has not moved since: someone
342 // said no to exactly this, and the clock does not ask again.
343 if (pending !== undefined && follow.tip === staged && !asked) {
344 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
345 return ok({ kind: "declined", behind, id: pending.id });
346 }
347 }
348
349 const base = (await mergeBase(dir, main, staged)) ?? "";
350 const title = `${UPSTREAM_TITLE}${behind} commit${behind === 1 ? "" : "s"} from ${upstreamLabel(follow.url)} (${base === "" ? "" : `${base.slice(0, 7)}..`}${staged.slice(0, 7)})`;
351 const log_ = await runGit(
352 ["log", "--no-merges", "--format=%h %s", "-n", "20", `${main}..${staged}`],
353 { cwd: dir },
354 );
355 const commits = log_.ok
356 ? log_.value.split("\n").filter((l) => l !== "").map((l) => `- ${l}`)
357 : [];
358 const more = behind > commits.length ? [`- … and ${behind - commits.length} more`] : [];
359 const where = `\`${follow.branch}\` of ${follow.url}`;
360
361 const reading = await mergeable(dir, main, staged);
362 if (reading.ok) {
363 // Deterministic: a fast-forward is the tip itself; a clean merge is one
364 // merge commit on top of ours, so the check tests exactly what lands.
365 const fastForward = base === main;
366 let head = staged;
367 if (!fastForward) {
368 const who = commitIdentity(app.config, by);
369 const made = await runGit(
370 [
371 "commit-tree",
372 reading.value.treeOid,
373 "-p",
374 main,
375 "-p",
376 staged,
377 "-m",
378 `Merge ${upstreamLabel(follow.url)} ${follow.branch} (${staged.slice(0, 7)})`,
379 ],
380 {
381 cwd: dir,
382 env: {
383 GIT_AUTHOR_NAME: who.name,
384 GIT_AUTHOR_EMAIL: who.email,
385 GIT_COMMITTER_NAME: who.name,
386 GIT_COMMITTER_EMAIL: who.email,
387 },
388 },
389 );
390 if (!made.ok) return failed("git");
391 head = made.value.trim();
392 }
393 const name = proposalBranch(staged);
394 const created = await createBranch(dir, name, head);
395 if (!created.ok && created.error !== "exists") return failed("git");
396 const opened = await openPull(app, by, repo, {
397 title,
398 body: [
399 `New commits on ${where}, taken ${fastForward ? "as a fast-forward" : "with a clean `git merge`"}: no conflicts, nothing decided.`,
400 "",
401 ...commits,
402 ...more,
403 "",
404 "It lands through the landing gate like any pull, as a merge, so upstream's history stays ours.",
405 ].join("\n"),
406 baseBranch: repo.defaultBranch,
407 headBranch: name,
408 });
409 if (!opened.ok) return failed("git", `The pull could not be opened: ${opened.error}`);
410 noteCheck(app.db, repo.id, {
411 at,
412 tip: staged,
413 behind,
414 error: "",
415 pendingId: opened.value.id,
416 opened: true,
417 });
418 log.info("upstream pull opened", {
419 repo: `${repo.ownerName}/${repo.name}`,
420 pull: opened.value.number,
421 behind,
422 });
423 return ok({ kind: "pull", behind, number: opened.value.number });
424 }
425 if (reading.error.kind !== "conflict") return failed("git");
426
427 // Both sides changed the same files: a decision, and the crew drafts it.
428 const files = reading.error.files;
429 const opened = openIssue(app, by, repo, {
430 title,
431 body: [
432 `New commits on ${where} do not merge cleanly with \`${repo.defaultBranch}\`: ${files.length === 1 ? "one file" : `${files.length} files`} changed on both sides.`,
433 "",
434 ...files.map((f) => `- \`${f}\``),
435 "",
436 `The upstream tip is staged here at \`${ref}\` (${staged.slice(0, 7)}). Merge it into a branch — a real merge, never a rebase or squash — keep upstream's fixes, keep this repository's work, and explain each resolution. Never take an upstream deletion of a file this repository changed without saying why. The pull lands like any crew pull.`,
437 "",
438 ...commits,
439 ...more,
440 ].join("\n"),
441 });
442 if (!opened.ok) return failed("git", `The issue could not be opened: ${opened.error}`);
443 let issue = opened.value;
444 const builders = listCrewRoles(app.db, repo.id)
445 .filter((c) => c.role === "builder")
446 .map((c) => c.agent);
447 const inFlight = new Map<string, number>();
448 for (const r of listRuns(app.db, repo.id, { kind: "agent", limit: 50 }))
449 if ((r.state === "running" || r.state === "queued") && r.actorId !== null)
450 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
451 const agent = pickBuilder(issue, builders, inFlight);
452 if (agent !== undefined) {
453 // Assigned without the assignment event, which starts an ordinary run:
454 // this one carries its own reason and brief (as `crew/converge.ts`).
455 issue = setAssignee(app.db, issue.id, agent.user.id) ?? issue;
456 queueAgentRun(app, repo, issue, agent, "converge", undefined, {
457 notBefore: at,
458 attempt: 0,
459 summary: `upstream moved: ${files.join(", ")}`,
460 });
461 }
462 noteCheck(app.db, repo.id, {
463 at,
464 tip: staged,
465 behind,
466 error: "",
467 pendingId: issue.id,
468 opened: true,
469 });
470 log.info("upstream conflict sent to the crew", {
471 repo: `${repo.ownerName}/${repo.name}`,
472 issue: issue.number,
473 files: files.length,
474 builder: agent?.user.username ?? "none",
475 });
476 return ok({
477 kind: "conflict",
478 behind,
479 number: issue.number,
480 files,
481 builder: agent?.user.username,
482 });
483 }
484
485 /** What the crew's brief says about a following repository's converge run. */
486 export function upstreamFollowing(
487 app: App,
488 repoId: string,
489 ): { parent: string; branch: string; ref: string; upstream: true } | undefined {
490 const follow = getFollow(app.db, repoId);
491 if (follow === undefined) return undefined;
492 return {
493 parent: upstreamLabel(follow.url),
494 branch: follow.branch,
495 ref: stagedRef(follow.branch),
496 upstream: true,
497 };
498 }
499
500 /**
501 * Whether a pull's head carries upstream commits the base lacks: such a
502 * pull lands as a merge, never a squash, so upstream's history becomes an
503 * ancestor of ours and the next check counts only what is new. Asked of
504 * git: the staged tip's merge base with the head is not already in the base.
505 */
506 export async function carriesUpstream(
507 app: App,
508 repo: Repo,
509 dir: string,
510 headOid: string,
511 baseOid: string,
512 ): Promise<boolean> {
513 const follow = getFollow(app.db, repo.id);
514 if (follow === undefined) return false;
515 const staged = await resolveOid(dir, stagedRef(follow.branch));
516 if (staged === undefined || !isSafeOid(headOid) || !isSafeOid(baseOid)) return false;
517 const shared = await mergeBase(dir, staged, headOid);
518 if (shared === undefined) return false;
519 const inBase = await runGit(["merge-base", "--is-ancestor", shared, baseOid], { cwd: dir });
520 return !inBase.ok;
521 }
522
523 /** A repository's following, as the API says it: no origin id, no actor id. */
524 export const followJson = (f: UpstreamFollow) => ({
525 url: f.url,
526 branch: f.branch,
527 enabled: f.enabled,
528 parentUrl: f.parentUrl === "" ? null : f.parentUrl,
529 checkedAt: f.checkedAt,
530 tip: f.tip === "" ? null : f.tip,
531 behind: f.behind,
532 error: f.error === "" ? null : f.error,
533 opened: f.opened,
534 });
535
536 /**
537 * Every following repository whose last check is older than
538 * `FOLLOW_EVERY_MS`, checked beside the tick, never in front of it: a
539 * slow upstream must not hold the crew up. Answers how many were started.
540 */
541 export function followTick(app: App, now = Date.now()): number {
542 let started = 0;
543 for (const follow of listFollowing(app.db)) {
544 if (checking.has(follow.repoId)) continue;
545 if (follow.checkedAt !== null && now - Date.parse(follow.checkedAt) < FOLLOW_EVERY_MS)
546 continue;
547 const repo = getRepoById(app.db, follow.repoId);
548 if (repo === undefined || repo.archivedAt !== null) continue;
549 started++;
550 // `checkUpstream` claims the repository before its first await.
551 void checkUpstream(app, repo).catch((error) =>
552 log.error("upstream check failed", {
553 repo: `${repo.ownerName}/${repo.name}`,
554 error: String(error),
555 }),
556 );
557 }
558 return started;
559 }
560
561 /** For the tick line: where a following repository stands, in a few words. */
562 export function followWords(app: App, repoId: string): string | undefined {
563 const follow = getFollow(app.db, repoId);
564 if (follow === undefined || !follow.enabled) return undefined;
565 const pending =
566 follow.pendingId === null ? undefined : getIssueById(app.db, follow.pendingId);
567 const open = pending !== undefined && pending.state === "open" ? `, #${pending.number} open` : "";
568 return `${follow.behind} behind, ${follow.opened} opened${open}`;
569 }
570
571 /**
572 * The following a viewer may read: an enabled one for anyone who reads the
573 * repository, an off one for its admins only — the rule the About line,
574 * the terminal's About card and `GET …/upstream` share.
575 */
576 export function followShown(
577 app: App,
578 repo: Repo,
579 viewer: User | undefined,
580 ): UpstreamFollow | undefined {
581 const follow = getFollow(app.db, repo.id);
582 if (follow === undefined) return undefined;
583 return follow.enabled || canAdmin(app.db, repo, viewer) ? follow : undefined;
584 }
585
586 /**
587 * Where a following repository stands, in words: "3 behind", "up to date",
588 * "off". Why a check failed is the remote's stderr, redacted, and only a
589 * writer is told it; anyone else reads "the last check did not finish".
590 */
591 export function standing(follow: UpstreamFollow, writer: boolean): string {
592 if (!follow.enabled) return "off";
593 if (follow.checkedAt === null) return "not checked yet";
594 if (follow.error !== "") return writer ? follow.error : "the last check did not finish";
595 return follow.behind === 0 ? "up to date" : `${follow.behind} behind`;
596 }
597
598 /** HH:MM in UTC, the instant a check last ran. */
599 export function clockWords(iso: string): string {
600 const at = new Date(iso);
601 return Number.isNaN(at.getTime()) ? "" : `${at.toISOString().slice(11, 16)} UTC`;
602 }
603
604 /** What a check found, in one sentence, for the page's flash and the terminal's toast. */
605 export function checkedWords(c: Checked): string {
606 switch (c.kind) {
607 case "up_to_date":
608 return "Up to date with the upstream.";
609 case "pending":
610 return `${c.behind} behind; the open proposal lands first.`;
611 case "declined":
612 return `${c.behind} behind; the last proposal was closed.`;
613 case "pull":
614 return `${c.behind === 1 ? "1 new upstream commit merges" : `${c.behind} new upstream commits merge`} cleanly: pull #${c.number} lands through the gate.`;
615 case "conflict":
616 return `${c.behind === 1 ? "1 new upstream commit conflicts" : `${c.behind} new upstream commits conflict`} in ${c.files.join(", ")}: issue #${c.number}${c.builder === undefined ? " waits for a builder" : ` is with @${c.builder}`}.`;
617 }
618 }
src/core/migrations/20261020200000-repo-upstream.ts added +21
@@ -0,0 +1,21 @@
1 // A repository follows an outside upstream (#3442): the git URL and branch
2 // it takes new commits from, whether it is on, who it acts as, the origin
3 // whose credential opens a private one, and what the last check read.
4 export default `
5 CREATE TABLE IF NOT EXISTS repo_upstream (
6 repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE,
7 url TEXT NOT NULL,
8 branch TEXT NOT NULL,
9 enabled INTEGER NOT NULL DEFAULT 0,
10 by_id TEXT NOT NULL,
11 origin_id TEXT NOT NULL DEFAULT '',
12 parent_url TEXT NOT NULL DEFAULT '',
13 checked_at TEXT,
14 tip TEXT NOT NULL DEFAULT '',
15 behind INTEGER NOT NULL DEFAULT 0,
16 error TEXT NOT NULL DEFAULT '',
17 pending_id TEXT,
18 opened INTEGER NOT NULL DEFAULT 0,
19 updated_at TEXT NOT NULL
20 );
21 `;
src/core/upstream_follow.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * A repository following an outside upstream (#3442): the git URL and
3 * branch new commits come from, whether it is on, who the forge acts as
4 * when it proposes them, and what the last check read. The commits
5 * themselves are git's (`refs/upstream/<branch>` in the repository); this
6 * row is the setting and the last reading, rebuilt by the next check.
7 *
8 * Pure data, no authz, no events (`actions/upstream_follow.ts`).
9 */
10
11 import type { Database } from "bun:sqlite";
12
13 export interface UpstreamFollow {
14 readonly repoId: string;
15 /** A git URL git may be handed (`migrateUrl`). */
16 readonly url: string;
17 readonly branch: string;
18 readonly enabled: boolean;
19 /** The person the forge acts as: who turned it on. */
20 readonly byId: string;
21 /** The connected origin whose credential opens a private upstream; "" for none. */
22 readonly originId: string;
23 /** The upstream's own parent, when its host said it is a fork: the second choice. */
24 readonly parentUrl: string;
25 readonly checkedAt: string | null;
26 /** The upstream tip the last check read; "" before the first. */
27 readonly tip: string;
28 /** Commits on the upstream branch the default branch does not hold. */
29 readonly behind: number;
30 /** Why the last check could not finish; "" when it did. */
31 readonly error: string;
32 /** The pull or issue carrying the last proposal, while it is open. */
33 readonly pendingId: string | null;
34 /** How many proposals the forge has opened for this repository. */
35 readonly opened: number;
36 }
37
38 interface Row {
39 repo_id: string;
40 url: string;
41 branch: string;
42 enabled: number;
43 by_id: string;
44 origin_id: string;
45 parent_url: string;
46 checked_at: string | null;
47 tip: string;
48 behind: number;
49 error: string;
50 pending_id: string | null;
51 opened: number;
52 }
53
54 const fromRow = (r: Row): UpstreamFollow => ({
55 repoId: r.repo_id,
56 url: r.url,
57 branch: r.branch,
58 enabled: r.enabled === 1,
59 byId: r.by_id,
60 originId: r.origin_id,
61 parentUrl: r.parent_url,
62 checkedAt: r.checked_at,
63 tip: r.tip,
64 behind: r.behind,
65 error: r.error,
66 pendingId: r.pending_id,
67 opened: r.opened,
68 });
69
70 export function getFollow(db: Database, repoId: string): UpstreamFollow | undefined {
71 const row = db
72 .query<Row, [string]>("SELECT * FROM repo_upstream WHERE repo_id = ?1")
73 .get(repoId);
74 return row ? fromRow(row) : undefined;
75 }
76
77 /** Every repository whose following is on. */
78 export function listFollowing(db: Database): UpstreamFollow[] {
79 return db
80 .query<Row, []>("SELECT * FROM repo_upstream WHERE enabled = 1 ORDER BY repo_id")
81 .all()
82 .map(fromRow);
83 }
84
85 /**
86 * Set where a repository follows and whether it does. A new URL or branch
87 * forgets the last reading — it was of another upstream.
88 */
89 export function putFollow(
90 db: Database,
91 input: {
92 readonly repoId: string;
93 readonly url: string;
94 readonly branch: string;
95 readonly enabled: boolean;
96 readonly byId: string;
97 readonly originId: string;
98 readonly parentUrl?: string;
99 },
100 ): UpstreamFollow {
101 const now = new Date().toISOString();
102 const was = getFollow(db, input.repoId);
103 const moved = was !== undefined && (was.url !== input.url || was.branch !== input.branch);
104 db.query(
105 `INSERT INTO repo_upstream (repo_id, url, branch, enabled, by_id, origin_id, parent_url, updated_at)
106 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
107 ON CONFLICT(repo_id) DO UPDATE SET url = ?2, branch = ?3, enabled = ?4,
108 by_id = ?5, origin_id = ?6, parent_url = CASE WHEN ?7 = '' THEN parent_url ELSE ?7 END,
109 updated_at = ?8`,
110 ).run(
111 input.repoId,
112 input.url,
113 input.branch,
114 input.enabled ? 1 : 0,
115 input.byId,
116 input.originId,
117 input.parentUrl ?? "",
118 now,
119 );
120 if (moved)
121 db.query(
122 "UPDATE repo_upstream SET checked_at = NULL, tip = '', behind = 0, error = '' WHERE repo_id = ?1",
123 ).run(input.repoId);
124 return getFollow(db, input.repoId)!;
125 }
126
127 /** What one check read. `pendingId` is left alone when absent. */
128 export function noteCheck(
129 db: Database,
130 repoId: string,
131 reading: {
132 readonly at: string;
133 readonly tip?: string;
134 readonly behind?: number;
135 readonly error: string;
136 readonly pendingId?: string | null;
137 /** A proposal was opened by this check. */
138 readonly opened?: boolean;
139 },
140 ): void {
141 db.query(
142 `UPDATE repo_upstream SET checked_at = ?2,
143 tip = COALESCE(?3, tip), behind = COALESCE(?4, behind), error = ?5,
144 pending_id = CASE WHEN ?6 = 1 THEN ?7 ELSE pending_id END,
145 opened = opened + ?8
146 WHERE repo_id = ?1`,
147 ).run(
148 repoId,
149 reading.at,
150 reading.tip ?? null,
151 reading.behind ?? null,
152 reading.error,
153 reading.pendingId === undefined ? 0 : 1,
154 reading.pendingId ?? null,
155 reading.opened === true ? 1 : 0,
156 );
157 }
src/crew/autonomy.ts +27 −1
@@ -30,6 +30,11 @@ import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
3030 import { repoDir } from "../git/repos.ts";
3131 import { CLOSED_NOTE } from "../core/done_on_main.ts";
3232 import { mergePull } from "../actions/pulls.ts";
33 import {
34 carriesUpstream,
35 followTick,
36 followWords,
37 } from "../actions/upstream_follow.ts";
3338 import {
3439 listCrewRoles,
3540 type Agent,
@@ -1167,6 +1172,7 @@ export async function autonomyTick(
11671172 // never a mystery: the numbers behind "idle" are on the line.
11681173 const status = autonomyStatus(app, current, now);
11691174 const approved = waitWords(lastWaits(current.id));
1175 const upstream = followWords(app, current.id);
11701176 const ready = readyNow(repoGraph(app.db, current.id, { sealed: true }));
11711177 const held = heldBy(
11721178 app,
@@ -1196,6 +1202,8 @@ export async function autonomyTick(
11961202 // The approved pulls the last green sweep saw, and why each waits (#3055).
11971203 ...(approved === undefined ? {} : { approved }),
11981204 spent: `${status.spentTodayUsd.toFixed(2)}/${status.ceilingUsd}`,
1205 // A repository following its upstream: how far behind, how many proposed (#3442).
1206 ...(upstream === undefined ? {} : { upstream }),
11991207 ...(status.paused === null ? {} : { paused: status.paused }),
12001208 });
12011209 } catch (error) {
@@ -1217,6 +1225,13 @@ export async function autonomyTick(
12171225 } catch (error) {
12181226 log.error("sentinel failed", { error: String(error) });
12191227 }
1228 // Every following repository is checked on its own clock (#3442), beside
1229 // the tick: a slow upstream holds nothing up.
1230 try {
1231 followTick(app, now.getTime());
1232 } catch (error) {
1233 log.error("upstream follow failed", { error: String(error) });
1234 }
12201235 // Review is not autonomy's alone: an agent's green pull is read by the
12211236 // crew's reviewer in every repository that has one.
12221237 try {
@@ -1915,7 +1930,18 @@ async function landGated(
19151930 by: "rule",
19161931 ms: 0,
19171932 });
1918 const merged = await mergePull(app, by, repo, pull, "squash", expect);
1933 // A pull carrying upstream's commits lands as a merge: squashed, their
1934 // history would never be ours and the next check would count it again.
1935 const strategy = (await carriesUpstream(

High: no test exercises this branch. The suite calls mergePull(..., "merge") directly, so reverting this to "squash" would still pass. Add a test where the gate itself lands the upstream pull, then assert that the staged tip is an ancestor of main and the next check is up_to_date.

1936 app,
1937 repo,
1938 await pullDir(app.db, app.reposRoot, repo, pull),
1939 pull.headOid,
1940 expect.baseOid,
1941 ))
1942 ? "merge"
1943 : "squash";
1944 const merged = await mergePull(app, by, repo, pull, strategy, expect);
19191945 if (!merged.ok) {
19201946 const why = mergeWhy(merged.error);
19211947 log.info("green but not landed", {
src/crew/brief.ts +26 −3
@@ -192,7 +192,14 @@ export interface TaskInput extends BriefInput {
192192 readonly resolution?: string | undefined;
193193 /** For `converge`: the parent this repository follows, and its branch. */
194194 readonly following?:
195 | { readonly parent: string; readonly branch: string }
195 | {
196 readonly parent: string;
197 readonly branch: string;
198 /** Where it is staged, when not `refs/following/<branch>`. */
199 readonly ref?: string;
200 /** An outside upstream this repository follows (#3442), not a forge parent. */
201 readonly upstream?: boolean;
202 }
196203 | undefined;
197204 /** For `review`: the pull's diff against its base, capped. */
198205 readonly reviewDiff?: string | undefined;
@@ -447,13 +454,29 @@ function taskBody(input: TaskInput): string {
447454 const parent = input.following?.parent ?? "its parent";
448455 const pbranch = input.following?.branch ?? "main";
449456 const direction = input.repo.autonomyDirection.trim();
457 const staged = input.following?.ref ?? `refs/following/${pbranch}`;
458 if (input.following?.upstream === true) {
459 out.push(
460 `This repository follows its upstream ${parent} (\`${pbranch}\`), and new upstream commits do not merge cleanly. Issue #${issue.number}: ${issue.title}`,
461 "",
462 ...told(),
463 "",
464 `The upstream tip is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
465 `1. \`git fetch origin ${staged} && git merge FETCH_HEAD\` — a real merge: never rebase, squash or cherry-pick, so upstream's history stays an ancestor of ours.`,
466 `2. Resolve each conflict${files.length > 0 ? ` (${files.join(", ")})` : ""}: keep upstream's fixes, and keep this repository's own work. Where they cannot both be kept, this repository's direction decides${direction === "" ? "" : `: ${direction}`}. Never take an upstream deletion of a file this repository changed unless you say why.`,
467 "3. Make sure the tests pass, then push. Never force-push.",
468 "",
469 `The forge opens the pull on your first push and lands it as a merge. Your report becomes its description: explain each resolution, file by file, and end it with \`Closes #${issue.number}\`.`,
470 );
471 return out.join("\n");
472 }
450473 out.push(
451474 `This repository follows ${parent}, and both have moved. Issue #${issue.number}: ${issue.title}`,
452475 "",
453476 ...told(),
454477 "",
455 `The parent's \`${pbranch}\` is staged here at \`refs/following/${pbranch}\`. On the branch \`${input.branch}\`:`,
456 `1. \`git fetch origin refs/following/${pbranch} && git merge FETCH_HEAD\``,
478 `The parent's \`${pbranch}\` is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
479 `1. \`git fetch origin ${staged} && git merge FETCH_HEAD\``,
457480 `2. Resolve each conflict${files.length > 0 ? ` (${files.join(", ")})` : ""} keeping what both sides meant. Where they cannot both be kept, this repository's direction decides${direction === "" ? "" : `: ${direction}`}. Never drop this repository's own work to make a merge easy.`,
458481 "3. Make sure the tests pass, then push.",
459482 "",
src/crew/runner.ts +7 −1
@@ -41,6 +41,7 @@ import {
4141 type Issue,
4242 } from "../core/issues.ts";
4343 import { refreshPullHead } from "../core/following.ts";
44 import { UPSTREAM_TITLE, upstreamFollowing } from "../actions/upstream_follow.ts";
4445 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
4546 import {
4647 canWrite,
@@ -976,13 +977,18 @@ async function work(
976977 conflictFiles:
977978 reason === "conflict" || reason === "converge"
978979 ? run.summary
979 .replace(/^(main|parent) moved: /, "")
980 .replace(/^(main|parent|upstream) moved: /, "")
980981 .split(", ")
981982 .filter((f) => f !== "")
982983 : undefined,
983984 following:
984985 reason === "converge"
985986 ? (() => {
987 // An outside upstream's new commits, staged here (#3442).
988 if (issue.title.startsWith(UPSTREAM_TITLE)) {
989 const upstream = upstreamFollowing(app, repo.id);
990 if (upstream !== undefined) return upstream;
991 }
986992 // Only a parent the agent may read is put in its brief.
987993 const parent = forkParentFor(app.db, repo, agent.user);
988994 return parent === undefined
src/http/api.ts +53
@@ -8,6 +8,13 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import {
12 checkUpstreamNow,
13 FOLLOW_REFUSALS,
14 followJson,
15 followShown,
16 setFollowUpstream,
17 } from "../actions/upstream_follow.ts";
1118 import { upstreamPayload } from "../spawn/upstream.ts";
1219 import { setRole } from "../actions/roles.ts";
1320 import { listPeople, NOT_A_MEMBER } from "../core/roles.ts";
@@ -2277,6 +2284,52 @@ export function apiRoutes(router: Router<Handler>): void {
22772284 : notFound();
22782285 });
22792286
2287 // Following an outside upstream (#3442): read, set, and check now.
2288 router.add("GET", "/api/v1/repos/:owner/:name/upstream", (ctx) => {
2289 const repo = loadRepo(ctx);
2290 if (!repo) return notFound();
2291 const follow = followShown(ctx.app, repo, ctx.auth.user);
2292 if (follow === undefined) return json({ following: null });
2293 // Why a check failed is the remote's own stderr: a writer's to read.
2294 const shown = followJson(follow);
2295 return json({
2296 following: canWrite(ctx.app.db, repo, ctx.auth.user) ? shown : { ...shown, error: null },
2297 });
2298 });
2299
2300 router.add("PUT", "/api/v1/repos/:owner/:name/upstream", async (ctx) => {
2301 const denied = requireScope(ctx, "admin");
2302 if (denied) return denied;
2303 const repo = loadRepo(ctx);
2304 if (!repo) return notFound();
2305 const input = await body(ctx.request);
2306 if (typeof input.enabled !== "boolean")
2307 return apiError("bad_enabled", 422, "enabled is true or false");
2308 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
2309 url: str(input.url),
2310 branch: str(input.branch),
2311 enabled: input.enabled,
2312 });
2313 if (!saved.ok)
2314 return saved.error === "unauthorized" || saved.error === "forbidden" || saved.error === "not_found"
2315 ? respondAccess(saved.error, 422)
2316 : apiError(saved.error, 422, FOLLOW_REFUSALS[saved.error]);
2317 return json({ following: followJson(saved.value) });
2318 });
2319
2320 router.add("POST", "/api/v1/repos/:owner/:name/upstream/check", async (ctx) => {
2321 const denied = requireScope(ctx, "rw");
2322 if (denied) return denied;
2323 const repo = loadRepo(ctx);
2324 if (!repo) return notFound();
2325 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
2326 if (!checked.ok)
2327 return checked.error === "unauthorized" || checked.error === "forbidden" || checked.error === "not_found"
2328 ? respondAccess(checked.error, 422)
2329 : apiError(checked.error, checked.error === "busy" ? 409 : 422, FOLLOW_REFUSALS[checked.error]);
2330 return json(checked.value);
2331 });
2332
22802333 router.add("PATCH", "/api/v1/repos/:owner/:name", async (ctx) => {
22812334 const denied = requireScope(ctx, "admin");
22822335 if (denied) return denied;
src/http/server.ts +6
@@ -5,6 +5,10 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import {
9 followUpstreamCheck,
10 followUpstreamUpdate,
11 } from "../web/pages/upstream-follow.ts";
812 import { refusedByDatabase, shownRefusal } from "./refusal.ts";
913 import { NOT_A_MEMBER } from "../core/roles.ts";
1014 import { signupOptions, signupPasskey } from "../web/pages/signup-passkey.ts";
@@ -1388,6 +1392,8 @@ export function buildRouter(): Router<Handler> {
13881392 );
13891393 router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage);
13901394 router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate);
1395 router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate);
1396 router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck);
13911397 router.add("GET", "/:owner/:name/settings/labels", labelsPage);
13921398 router.add("POST", "/:owner/:name/settings/labels", labelCreate);
13931399 router.add("POST", "/:owner/:name/settings/labels/:id", labelUpdate);
src/tui/screens/about.ts +124 −3
@@ -23,7 +23,18 @@ import { checkMemoryAt } from "../../apps/check-memory.ts";
2323 import { repoDir } from "../../git/repos.ts";
2424 import { listRefs } from "../../git/read.ts";
2525 import { updateRepoSettings } from "../../actions/repos.ts";
26 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
26 import { canAdmin, canWrite, getRepoById, type Repo } from "../../core/repos.ts";
27 import {
28 checkedWords,
29 checkUpstreamNow,
30 clockWords,
31 FOLLOW_REFUSALS,
32 followShown,
33 setFollowUpstream,
34 standing,
35 upstreamLabel,
36 } from "../../actions/upstream_follow.ts";
37 import { getFollow } from "../../core/upstream_follow.ts";
2738 import type { RepoFacts, RepoSource } from "../../view/source.ts";
2839 import type { Ctx, Screen } from "../app/app.ts";
2940 import { binding } from "../app/keys.ts";
@@ -31,7 +42,7 @@ import { style } from "../term/style.ts";
3142 import { truncate, wrap } from "../term/width.ts";
3243 import { badge, card } from "../ui/widgets.ts";
3344 import type { Session } from "../session.ts";
34 import { PIN_MARK, ago, drawFacts, plural } from "./common.ts";
45 import { PIN_MARK, ago, drawFacts, later, live, plural, promptScreen } from "./common.ts";
3546 import { forkOf, hostOf, liveOrigin, localRepo, sourceName } from "./where.ts";
3647
3748 /**
@@ -52,10 +63,17 @@ export function aboutScreen(
5263 let repo = localRepo(src);
5364 const may = (): boolean =>
5465 repo !== undefined && f.user !== undefined && canAdmin(f.db, repo, f.user);
66 // A writer may ask the upstream now, when following is on (#3442).
67 const mayCheck = (): boolean =>
68 repo !== undefined &&
69 f.user !== undefined &&
70 canWrite(f.db, repo, f.user) &&
71 followShown(f.app, repo, f.user)?.enabled === true;
5572 let cell: [string, string][] = [];
5673 const factRows = (): [string, string][] => [
5774 ...archivedRow(repo),
5875 ...aboutFacts(f, src, facts, ref),
76 ...followRow(f, repo),
5977 ...cell,
6078 ];
6179 let rows = factRows();
@@ -81,8 +99,58 @@ export function aboutScreen(
8199 });
82100 }
83101 const cloneUrl = rows.find(([label]) => label.startsWith("clone"))?.[1] ?? "";
84 return {
102 // An admin turns following on or off, or points it elsewhere (#3442):
103 // the page's `setFollowUpstream`, with the page's refusals.
104 const saveFollow = async (url: string, branch: string, enabled: boolean): Promise<void> => {
105 if (repo === undefined) return;
106 const saved = await setFollowUpstream(f.app, f.user, repo, { url, branch, enabled });
107 rows = factRows();
108 if (saved.ok)
109 ctx.toast(
110 saved.value.enabled
111 ? `following ${upstreamLabel(saved.value.url)} ${saved.value.branch}`
112 : "following the upstream is off",
113 "success",
114 );
outdated

The terminal can check but can't turn following on or off or change where it points, which the page's settings card can do. Add an admin-only binding that goes through setFollowUpstream, the way this screen already edits settings through updateRepoSettings.

115 else ctx.toast(FOLLOW_REFUSALS[saved.error], "danger");
116 ctx.invalidate();
117 };
118 const pointFollow = (enabled: boolean): void => {
119 const now = repo === undefined ? undefined : getFollow(f.db, repo.id);
120 ctx.push(
121 promptScreen(ctx, screen, {
122 title: "Follow an upstream",
123 label: "git address: https://, http:// or git://",
124 value: now?.url ?? "",
125 onSubmit: (url) =>
126 url === ""
127 ? "An address to follow."
128 : later(ctx, () =>
129 promptScreen(ctx, screen, {
130 title: "Follow an upstream",
131 label: "its branch",
132 value: now?.branch ?? "main",
133 onSubmit: (branch) => saveFollow(url, branch, enabled),
134 }),
135 ),
136 }),
137 );
138 };
139 const screen: Screen = {
85140 title: "About",
141 // A check finishing, or following changing, redraws the row in place.
142 async load(signal) {
143 if (repo === undefined) return;
144 live(
145 f,
146 signal,
147 { repoId: repo.id, kinds: ["repo.upstream_checked", "repo.upstream_follow"] },
148 () => {
149 rows = factRows();
150 ctx.invalidate();
151 },
152 );
153 },
86154 get keys() {
87155 return [
88156 binding(["y"], "copy the clone URL", { disabled: cloneUrl === "" }),
@@ -95,6 +163,18 @@ export function aboutScreen(
95163 ),
96164 ]
97165 : []),
166 ...(mayCheck() ? [binding(["u"], "check upstream now")] : []),
167 ...(may()
168 ? [
169 binding(
170 ["f"],
171 repo !== undefined && getFollow(f.db, repo.id)?.enabled === true
172 ? "stop following upstream"
173 : "follow upstream",
174 ),
175 binding(["F"], "point following elsewhere"),
176 ]
177 : []),
98178 binding(["esc"], "close"),
99179 ];
100180 },
@@ -200,6 +280,26 @@ export function aboutScreen(
200280 });
201281 return true;
202282 }
283 if (e.key === "u" && repo !== undefined && mayCheck()) {
284 ctx.toast("checking the upstream…");
285 void checkUpstreamNow(f.app, f.user, repo).then((checked) => {
286 rows = factRows();
287 if (checked.ok) ctx.toast(checkedWords(checked.value), "success");
288 else ctx.toast(FOLLOW_REFUSALS[checked.error], "danger");
289 ctx.invalidate();
290 });
291 return true;
292 }
293 if (e.key === "f" && repo !== undefined && may()) {
294 const now = getFollow(f.db, repo.id);
295 if (now === undefined) pointFollow(true);
296 else void saveFollow(now.url, now.branch, !now.enabled);
297 return true;
298 }
299 if (e.key === "F" && repo !== undefined && may()) {
300 pointFollow(getFollow(f.db, repo.id)?.enabled ?? true);
301 return true;
302 }
203303 if (e.key === "esc" || e.key === "q" || e.key === "I") {
204304 ctx.pop();
205305 return true;
@@ -207,6 +307,27 @@ export function aboutScreen(
207307 return true;
208308 },
209309 };
310 return screen;
311 }
312
313 /**
314 * What the repository follows, the About line's words (`followingLine`):
315 * shown when on, or to an admin when off.
316 */
317 function followRow(f: Session, repo: Repo | undefined): [string, string][] {
318 if (repo === undefined) return [];
319 const follow = followShown(f.app, repo, f.user);
320 if (follow === undefined) return [];
321 // Two rows: the card is at most 72 wide, and an address plus where it
322 // stands is more than one row of it holds.
323 const where = [
324 standing(follow, f.user !== undefined && canWrite(f.db, repo, f.user)),
325 ...(follow.checkedAt === null ? [] : [`last checked ${clockWords(follow.checkedAt)}`]),
326 ];
327 return [
328 ["following", `${upstreamLabel(follow.url)} ${follow.branch}`],
329 ...wrap(where.join(" · "), 50).map((line): [string, string] => ["", line]),
330 ];
210331 }
211332
212333 /** One line when an admin has put the repository away. */
src/web/live.ts +1
@@ -303,6 +303,7 @@ export const liveClientJs = /* js */ `
303303 'run.queued', 'run.started', 'run.finished', 'app.serving',
304304 'app.created', 'app.updated', 'app.deleted', 'app.stopped',
305305 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
306 'repo.upstream_checked',
306307 ];
307308 var extra = (cfg.getAttribute('data-repos') || '').split(' ').filter(Boolean);
308309 var watching = [repo].concat(extra).filter(function (r, i, all) {
src/web/pages/repo.ts +2
@@ -8,6 +8,7 @@
88 * path segment and can never smuggle a path of its own.
99 */
1010
11 import { followingLine } from "./upstream-follow.ts";
1112 import { NOT_A_MEMBER } from "../../core/roles.ts";
1213 import { storageLimitMessage } from "../../core/storage.ts";
1314 import { canRead, listForks, type Repo } from "../../core/repos.ts";
@@ -631,6 +632,7 @@ function aboutCard(
631632 </dd>`,
632633 )}
633634 </dl>
635 ${followingLine(ctx, repo)}
634636 ${whereItLives}
635637 ${when(
636638 repo.visibility === "public" && repo.origin === null,
src/web/pages/settings.ts +2 −1
@@ -109,6 +109,7 @@ import { proposalTokensSection } from "./proposal-tokens.ts";
109109 import { secretsSection } from "./secrets.ts";
110110 import { checkMemoryAt } from "../../apps/check-memory.ts";
111111 import { saveGrants } from "./subscriptions.ts";
112 import { followUpstreamCard } from "./upstream-follow.ts";
112113
113114 type Section =
114115 | "general"
@@ -363,7 +364,7 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
363364 repo,
364365 "general",
365366 "Settings",
366 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
367 html`${lead}<div class="mt">${body}</div><div class="mt">${followUpstreamCard(ctx, repo)}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
367368 ? html`<div class="mt">${proposals}</div>`
368369 : null}${secrets
369370 ? html`<div class="mt">${secrets}</div>`
src/web/pages/upstream-follow.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Following an upstream (#3442), on the page: the settings card that turns
3 * it on, points it and checks now; and the one line the repository's About
4 * card shows — "Following <upstream> · last checked HH:MM · N behind".
5 * Every mutation is a same-origin POST through `readForm`; the doors only
6 * word what `actions/upstream_follow.ts` answers.
7 */
8
9 import {
10 checkedWords,
11 checkUpstreamNow,
12 clockWords,
13 FOLLOW_REFUSALS,
14 followShown,
15 setFollowUpstream,
16 standing,
17 upstreamLabel,
18 } from "../../actions/upstream_follow.ts";
19 import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
20 import { getFollow } from "../../core/upstream_follow.ts";
21 import { getIssueById } from "../../core/issues.ts";
22 import type { Ctx } from "../../http/context.ts";
23 import { loadRepo, repoBase, repoNotFound } from "../chrome.ts";
24 import { field, readForm } from "../form.ts";
25 import { html, when, type Html } from "../html.ts";
26 import { icon } from "../icons.ts";
27 import { flashTo } from "../layout.ts";
28 import { btn, card, field as formField } from "../ui.ts";
29
30 /** HH:MM in UTC, with the instant for machines and the title for people. */
31 function clock(iso: string): Html {
32 const at = new Date(iso);
33 if (Number.isNaN(at.getTime())) return html``;
34 const exact = `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
35 return html`<time datetime="${at.toISOString()}" title="${exact}"
36 >${clockWords(iso)}</time
37 >`;
38 }
39
40 /**
41 * The About card's line: an enabled following for every reader, an off one
42 * for admins (`followShown`). Only a web address is a link; a `git://`
43 * upstream is named, not linked — no browser opens it.
44 */
45 export function followingLine(ctx: Ctx, repo: Repo): Html | null {

High: this line, the settings card and Check upstream now have no terminal equivalent. Add a row and a writer-gated check key to src/tui/screens/about.ts, using the same visibility rule (shown when on, or to an admin when off), with a test.

46 const follow = followShown(ctx.app, repo, ctx.auth.user);
47 if (follow === undefined) return null;
48 const writer = canWrite(ctx.app.db, repo, ctx.auth.user);
49 const pending =
50 follow.pendingId === null ? undefined : getIssueById(ctx.app.db, follow.pendingId);
51 const open = pending !== undefined && pending.state === "open" ? pending : undefined;
52 const label = upstreamLabel(follow.url);
53 return html`<p class="mt small muted" data-following-upstream>
54 ${icon("sync")} Following
55 ${/^https?:\/\//i.test(follow.url)
56 ? html`<a href="${follow.url}" rel="noreferrer noopener">${label}</a>`
57 : html`<span class="mono">${label}</span>`}
58 <span class="mono">${follow.branch}</span>
59 ${follow.checkedAt === null ? null : html`· last checked ${clock(follow.checkedAt)}`}
60 · ${standing(follow, writer)}${when(
61 open,
62 (i) =>
63 html` · <a href="${repoBase(repo)}/${i.kind === "pull" ? "pulls" : "issues"}/${i.number}"
64 >#${i.number}</a
65 >`,
66 )}
67 </p>`;
68 }
69
70 /** The settings card: on or off, the URL and branch, and "Check upstream now". */
71 export function followUpstreamCard(ctx: Ctx, repo: Repo): Html {
72 const follow = getFollow(ctx.app.db, repo.id);
73 const base = repoBase(repo);
74 const parent = follow?.parentUrl ?? "";
75 return card(
76 html`<form method="post" action="${base}/settings/upstream">
77 <p class="muted">
78 New commits on the upstream's branch land here by themselves: a
79 fast-forward or a clean <code>git merge</code> opens a pull that
80 lands through the landing gate; a conflict goes to the crew, whose
81 pull is reviewed and lands like any other. Never a push to
82 <span class="mono">${repo.defaultBranch}</span>, never a force-push.
83 Checked every 30 minutes.
84 </p>
85 ${formField({
86 label: "Upstream git URL",
87 name: "url",
88 value: follow?.url ?? "",
89 placeholder: "https://github.com/owner/name.git",
90 mono: true,
91 spellcheck: false,
92 hint:
93 parent === ""
94 ? "A public upstream needs no credential; a private one uses your connected origin on its host."
95 : `Its own upstream is ${upstreamLabel(parent)} — paste ${parent} to follow that instead.`,
96 })}
97 ${formField({
98 label: "Branch",
99 name: "branch",
100 value: follow?.branch ?? "main",
101 mono: true,
102 spellcheck: false,
103 })}
104 <div class="field">
105 <label class="check">
106 <input type="checkbox" name="enabled" ${follow?.enabled === true ? html`checked` : null} />
107 <span>Follow upstream</span>
108 </label>
109 </div>
110 ${when(
111 follow,
112 (f) => html`<p class="hint" data-following-standing>${standing(f, true)}${
113 f.checkedAt === null ? "" : html` · last checked ${clock(f.checkedAt)}`
114 } · ${f.opened} proposed so far</p>`,
115 )}
116 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
117 </form>
118 ${when(
119 follow?.enabled === true,
120 () => html`<form method="post" action="${base}/settings/upstream/check" class="mt">
121 ${btn("Check upstream now", { size: "sm", icon: "sync" })}
122 </form>`,
123 )}`,
124 { head: html`${icon("sync")}<h2 id="upstream">Follow upstream</h2>` },
125 );
126 }
127
128 // POST /:owner/:name/settings/upstream
129 export async function followUpstreamUpdate(ctx: Ctx): Promise<Response> {
130 const repo = loadRepo(ctx);
131 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
132 const form = await readForm(ctx, "admin");
133 if (form instanceof Response) return form;
134 const to = `${repoBase(repo)}/settings#upstream`;
135 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
136 url: field(form, "url"),
137 branch: field(form, "branch"),
138 enabled: form.get("enabled") !== null,
139 });
140 return flashTo(
141 ctx,
142 to,
143 saved.ok
144 ? {
145 message: saved.value.enabled
146 ? `Following ${upstreamLabel(saved.value.url)} ${saved.value.branch}. The first check runs within a minute.`
147 : "Following the upstream is off. Nothing is checked or proposed.",
148 }
149 : { tone: "danger", message: FOLLOW_REFUSALS[saved.error] },
150 );
151 }
152
153 // POST /:owner/:name/settings/upstream/check
154 export async function followUpstreamCheck(ctx: Ctx): Promise<Response> {
155 const repo = loadRepo(ctx);
156 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
157 const form = await readForm(ctx, "rw");
158 if (form instanceof Response) return form;
159 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
160 return flashTo(
161 ctx,
162 `${repoBase(repo)}/settings#upstream`,
163 checked.ok
164 ? { message: checkedWords(checked.value) }
165 : { tone: "danger", message: FOLLOW_REFUSALS[checked.error] },
166 );
167 }
test/migrate.test.ts +4
@@ -45,6 +45,7 @@ import { serve, type Servers } from "../src/http/server.ts";
4545 import { createToken } from "../src/core/tokens.ts";
4646 import { createSession } from "../src/core/sessions.ts";
4747 import { advance, createJob, settled } from "../src/origins/jobs.ts";
48 import { getFollow } from "../src/core/upstream_follow.ts";
4849 import { forgetProviders } from "../src/origins/providers/index.ts";
4950 import {
5051 newFakeOAuth,
@@ -463,6 +464,9 @@ describe("migrate", () => {
463464 ]);
464465 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
465466 expect(repo.autonomy).toBe(autonomous ? "autonomous" : "off");
467 // The source is the upstream it follows: on when autonomous (#3442).
468 const follow = getFollow(app.db, repo.id)!;
469 expect([follow.url, follow.branch, follow.enabled]).toEqual([fixtureUrl, "trunk", autonomous]);
466470
467471 const issues = listIssues(app.db, repo.id, {
468472 kind: "issue",
test/tui-upstream-follow.test.ts added +239
@@ -0,0 +1,239 @@
1 /**
2 * Following an upstream in the terminal (#3442): About shows what the
3 * repository follows, how far behind and when it last looked — on for
4 * everyone, off for its admins only — and a writer's `u` checks now. An
5 * admin's `f` turns it on or off and `F` points it elsewhere, through the
6 * page's refusals; a check finishing anywhere redraws the row.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { checkUpstream, setFollowUpstream } from "../src/actions/upstream_follow.ts";
15 import { createApp, type App as Forge } from "../src/app.ts";
16 import { listPulls } from "../src/core/pulls.ts";
17 import { getRepoById, type Repo } from "../src/core/repos.ts";
18 import { getFollow } from "../src/core/upstream_follow.ts";
19 import type { User } from "../src/core/users.ts";
20 import { runGit } from "../src/git/env.ts";
21 import { repoDir } from "../src/git/repos.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import type { TuiIdentity } from "../src/tui/session.ts";
25 import { headlessTerminal } from "../src/tui/term/terminal.ts";
26 import { seedAdmin } from "./helpers/admin.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { settleApp, settleUntil } from "./helpers/tui.ts";
29
30 quietLogs();
31
32 describe("following an upstream in the terminal", () => {
33 let dataDir: string;
34 let forge: Forge;
35 let servers: Servers;
36 let alice: User;
37 let up: Repo;
38 let beacon: Repo;
39 let upUrl: string;
40 const fresh = () => getRepoById(forge.db, beacon.id)!;
41 const commit = async (repo: Repo, path: string) => {
42 const done = await commitToBranch(forge, alice, repo, {
43 branch: "main",
44 message: path,
45 files: [{ path, content: `${path}\n` }],
46 });
47 if (!done.ok) throw new Error(JSON.stringify(done.error));
48 };
49 const asAlice = (): TuiIdentity => ({
50 sshUsername: "alice",
51 remoteAddress: "127.0.0.1",
52 fingerprint: "SHA256:test",
53 user: alice,
54 });
55 const asGuest: TuiIdentity = {
56 sshUsername: "git",
57 remoteAddress: "127.0.0.1",
58 fingerprint: "SHA256:unknown",
59 };
60
61 function boot(identity: TuiIdentity) {
62 const terminal = headlessTerminal(140, 40);
63 const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false });
64 app.start();
65 const press = async (...keys: string[]): Promise<void> => {
66 for (const key of keys)
67 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
68 await settleApp(app);
69 };
70 return { app, press, text: () => app.screen.toText() };
71 }
72
73 async function openAbout(h: ReturnType<typeof boot>): Promise<void> {
74 await settleApp(h.app);
75 await h.press("/");
76 for (const ch of "beacon") await h.press(ch);
77 await h.press("enter");
78 await h.press("enter");
79 await settleUntil(h.app, "alice/beacon");
80 await h.press("I");
81 await settleUntil(h.app, "clone (http)");
82 }
83
84 beforeAll(async () => {
85 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-upstream-"));
86 forge = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
87 servers = await serve(forge);
88 const a = await seedAdmin(forge, {
89 username: "alice",
90 email: "[email protected]",
91 password: "a-long-passphrase",
92 });
93 if (!a.ok) throw new Error("signup failed");
94 alice = a.value;
95 const u = await createRepo(forge, alice, { name: "up", visibility: "public" });
96 if (!u.ok) throw new Error("repo failed");
97 up = u.value;
98 await commit(up, "README.md");
99 upUrl = `http://127.0.0.1:${servers.port}/alice/up.git`;
100 const b = await createRepo(forge, alice, { name: "beacon", visibility: "public" });
101 if (!b.ok) throw new Error("repo failed");
102 beacon = b.value;
103 const fetched = await runGit(
104 ["fetch", "--quiet", repoDir(forge.reposRoot, "alice", "up"), "main:main"],
105 { cwd: repoDir(forge.reposRoot, "alice", "beacon") },
106 );
107 expect(fetched.ok).toBe(true);
108 });
109
110 afterAll(async () => {
111 servers.stop();
112 await rm(dataDir, { recursive: true, force: true });
113 });
114
115 test("off: an admin sees the row and no check key; a guest sees nothing", async () => {
116 const off = await setFollowUpstream(forge, alice, fresh(), { url: upUrl, branch: "main", enabled: false });
117 expect(off.ok).toBe(true);
118 const admin = boot(asAlice());
119 try {
120 await openAbout(admin);
121 expect(admin.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*\boff\b/);
122 expect(admin.text()).not.toContain("check upstream now");
123 } finally {
124 admin.app.stop();
125 }
126 const guest = boot(asGuest);
127 try {
128 await openAbout(guest);
129 expect(guest.text()).not.toMatch(/following +127/);
130 } finally {
131 guest.app.stop();
132 }
133 });
134
135 test("on: a writer's `u` checks now, proposes, and the row says how far behind and when", async () => {
136 const on = await setFollowUpstream(forge, alice, fresh(), { url: upUrl, branch: "main", enabled: true });
137 expect(on.ok).toBe(true);
138 await commit(up, "new.txt");
139 const h = boot(asAlice());
140 try {
141 await openAbout(h);
142 expect(h.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*not checked yet/);
143 expect(h.text()).toContain("check upstream now");
144 await h.press("u");
145 await settleUntil(h.app, "1 behind");
146 expect(h.text()).toMatch(/1 behind · last checked \d\d:\d\d UTC/);
147 expect(listPulls(forge.db, beacon.id, { state: "open" }).map((p) => p.title)).toEqual([
148 expect.stringMatching(/^Upstream: 1 commit from /),
149 ]);
150 } finally {
151 h.app.stop();
152 }
153 });
154
155 test("a guest sees the row of an enabled following, but not why a check failed, and `u` does nothing", async () => {
156 forge.db
157 .query("UPDATE repo_upstream SET error = 'fatal: secret-ish remote words' WHERE repo_id = ?1")
158 .run(beacon.id);
159 const checkedAt = getFollow(forge.db, beacon.id)!.checkedAt;
160 const h = boot(asGuest);
161 try {
162 await openAbout(h);
163 expect(h.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up main\s.*\n.*the last check did not finish/);
164 expect(h.text()).not.toContain("secret-ish");
165 expect(h.text()).not.toContain("check upstream now");
166 await h.press("u");
167 expect(getFollow(forge.db, beacon.id)!.checkedAt).toBe(checkedAt);
168 } finally {
169 h.app.stop();
170 }
171 });
172
173 test("a check finished elsewhere redraws the row in place", async () => {
174 await commit(up, "more.txt");
175 const h = boot(asAlice());
176 try {
177 await openAbout(h);
178 expect(h.text()).not.toContain("2 behind");
179 expect((await checkUpstream(forge, fresh())).ok).toBe(true);
180 await settleUntil(h.app, "2 behind");
181 expect(h.text()).toMatch(/2 behind · last checked \d\d:\d\d UTC/);
182 } finally {
183 h.app.stop();
184 }
185 });
186
187 test("an admin's `f` turns following off and on; `F` points it elsewhere, with the page's refusals", async () => {
188 const h = boot(asAlice());
189 try {
190 await openAbout(h);
191 expect(h.text()).toContain("stop following upstream");
192 await h.press("f");
193 await settleUntil(h.app, "following the upstream is off");
194 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(false);
195 await h.press("f");
196 await settleUntil(h.app, "following 127.0.0.1");
197 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(true);
198
199 // An address git must never be handed: refused, nothing changes.
200 const clear = Array.from({ length: upUrl.length + 5 }, () => "backspace");
201 await h.press("F");
202 await settleUntil(h.app, "git address");
203 await h.press(...clear, ..."file:///etc", "enter");
204 await settleUntil(h.app, "its branch");
205 await h.press("enter");
206 await settleUntil(h.app, "That is not a git address");
207 expect(getFollow(forge.db, beacon.id)!.url).toBe(upUrl);
208
209 // Elsewhere: the same address, another branch.
210 await h.press("F");
211 await settleUntil(h.app, "git address");
212 await h.press("enter");
213 await settleUntil(h.app, "its branch");
214 await h.press("backspace", "backspace", "backspace", "backspace", ..."dev", "enter");
215 await settleUntil(h.app, "following 127.0.0.1");
216 const now = getFollow(forge.db, beacon.id)!;
217 expect([now.url, now.branch, now.enabled]).toEqual([upUrl, "dev", true]);
218 } finally {
219 h.app.stop();
220 }
221 });
222
223 test("a guest is not offered `f` or `F`, and pressing them changes nothing", async () => {
224 const before = getFollow(forge.db, beacon.id)!;
225 const h = boot(asGuest);
226 try {
227 await openAbout(h);
228 expect(h.text()).not.toContain("following upstream");
229 expect(h.text()).not.toContain("point following elsewhere");
230 await h.press("f");
231 await h.press("F");
232 expect(h.text()).not.toContain("git address");
233 const after = getFollow(forge.db, beacon.id)!;
234 expect([after.enabled, after.url, after.branch]).toEqual([before.enabled, before.url, before.branch]);
235 } finally {
236 h.app.stop();
237 }
238 });
239 });
test/upstream_follow.test.ts added +463
@@ -0,0 +1,463 @@
1 /**
2 * A repository follows its upstream (#3442). The upstream is a public
3 * repository on this same forge, over HTTP on loopback (a private host, so
4 * the forge says that is fine). It gains two commits that merge cleanly:
5 * a pull opens and lands as a merge, and the next check is up to date. It
6 * gains a conflicting commit: an issue goes to the builder as a converge
7 * run, the crew's merge lands, up to date again. Turned off: nothing
8 * happens. And the doors: the About card's line, the settings card, the
9 * same-origin floor, the API.
10 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { addToCrew, createAgent } from "../src/actions/crew.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import {
20 carriesUpstream,
21 checkUpstream,
22 checkUpstreamNow,
23 followTick,
24 followWords,
25 setFollowUpstream,
26 stagedRef,
27 upstreamFollowing,
28 } from "../src/actions/upstream_follow.ts";
29 import { getIssueById } from "../src/core/issues.ts";
30 import { getPull, listPulls } from "../src/core/pulls.ts";
31 import { getRepoById, type Repo } from "../src/core/repos.ts";
32 import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
33 import { sweepGreen } from "../src/crew/autonomy.ts";
34 import { createSession } from "../src/core/sessions.ts";
35 import { createToken } from "../src/core/tokens.ts";
36 import { getFollow } from "../src/core/upstream_follow.ts";
37 import { createUser, type User } from "../src/core/users.ts";
38 import { taskPrompt, type TaskInput } from "../src/crew/brief.ts";
39 import { runGit } from "../src/git/env.ts";
40 import { aheadCount, resolveOid } from "../src/git/merge.ts";
41 import { repoDir } from "../src/git/repos.ts";
42 import { serve, type Servers } from "../src/http/server.ts";
43 import { promote } from "./helpers/members.ts";
44
45 let dataDir: string;
46 let app: App;
47 let servers: Servers;
48 let alice: User;
49 let bob: User;
50 let up: Repo;
51 let ours: Repo;
52 let upUrl: string;
53
54 const fresh = () => getRepoById(app.db, ours.id)!;
55 const ourDir = () => repoDir(app.reposRoot, "alice", "ours");
56 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
57 if (!r.ok) throw new Error(JSON.stringify(r.error));
58 return r.value;
59 };
60 const commit = async (repo: Repo, path: string, content: string, message = path) =>
61 must(
62 await commitToBranch(app, alice, repo, {
63 branch: "main",
64 message,
65 files: [{ path, content }],
66 }),
67 );
68 const behind = async () => {
69 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
70 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
71 return aheadCount(ourDir(), main, staged);
72 };
73 /**
74 * The landing gate lands it, as it would on its own: the repository runs
75 * autonomous, the head's check is green, the sweep picks the strategy.
76 * Upstream's tip is an ancestor of main afterwards — a squash would leave
77 * it out, and the next check would count the same commits again.
78 */
79 const landThroughGate = async (number: number) => {
80 app.db
81 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
82 .run(ours.id, alice.id);
83 const pull = getPull(app.db, ours.id, number)!;
84 const check = createRun(app.db, {
85 repoId: ours.id,
86 kind: "check",
87 issueId: pull.id,
88 env: `pull-${pull.number}`,
89 commitOid: pull.headOid,
90 reason: "pull",
91 });
92 claimRun(app.db, check.id);
93 finishRun(app.db, check.id, { state: "ok", summary: "check passed" });
94 expect(await sweepGreen(app, fresh())).toBe(1);
95 const landed = getPull(app.db, ours.id, number)!;
96 expect(landed.mergedOid).not.toBeNull();
97 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
98 expect(landed.mergedOid).toBe(main);
99 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
100 expect((await runGit(["merge-base", "--is-ancestor", staged, main], { cwd: ourDir() })).ok).toBe(true);
101 expect(await behind()).toBe(0);
102 };
103 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
104
105 beforeAll(async () => {
106 dataDir = await mkdtemp(join(tmpdir(), "forge-upstream-follow-"));
107 app = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
108 servers = await serve(app);
109 const person = async (username: string, adminIfFirst = false) =>
110 must(
111 await createUser(app.db, {
112 origin: "seed",
113 trusted: true,
114 username,
115 email: `${username}@forge.test`,
116 adminIfFirst,
117 }),
118 );
119 alice = await person("alice", true);
120 bob = await person("bob");
121 up = must(await createRepo(app, alice, { name: "up", visibility: "public" }));
122 await commit(up, "README.md", "upstream\n");
123 await commit(up, "a.txt", "one\ntwo\nthree\n");
124 upUrl = `http://127.0.0.1:${servers.port}/alice/up.git`;
125
126 // Ours starts as upstream's history, then does its own work.
127 ours = must(await createRepo(app, alice, { name: "ours", visibility: "private" }));
128 const upDir = repoDir(app.reposRoot, "alice", "up");
129 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: ourDir() })).ok).toBe(true);
130 await commit(fresh(), "ours.txt", "our own work\n");
131
132 must(await createAgent(app, alice, { username: "mason" }));
133 expect(addToCrew(app, alice, fresh(), "mason").ok).toBe(true);
134 });
135
136 afterAll(async () => {
137 servers.stop();
138 app.db.close();
139 await rm(dataDir, { recursive: true, force: true });
140 });
141
142 describe("the setting", () => {
143 test("an address git must never be handed, or a branch that is not one, is refused", async () => {
144 for (const url of ["file:///etc", "-uhoh", "ext::sh -c id", "https://u:[email protected]/x.git"]) {
145 const r = await setFollowUpstream(app, alice, fresh(), { url, branch: "main", enabled: true });
146 expect(r.ok ? "saved" : r.error).toBe("invalid_url");
147 }
148 const r = await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "-x", enabled: true });
149 expect(r.ok ? "saved" : r.error).toBe("invalid_branch");
150 expect(getFollow(app.db, ours.id)).toBeUndefined();
151 });
152
153 test("a host inside the network is refused unless the forge says it is fine", async () => {
154 const config = app.config as { migrateFromPrivateHosts?: boolean };
155 config.migrateFromPrivateHosts = false;
156 try {
157 // bob is no forge admin: the check is his, on his own repository.
158 promote(app.db, bob);
159 const bobs = must(await createRepo(app, bob, { name: "bobs", visibility: "private" }));
160 const r = await setFollowUpstream(app, bob, bobs, { url: upUrl, branch: "main", enabled: true });
161 expect(r.ok ? "saved" : r.error).toBe("private_host");
162 expect(getFollow(app.db, bobs.id)).toBeUndefined();
163 } finally {
164 config.migrateFromPrivateHosts = true;
165 }
166 });
167
168 test("only an admin turns it on", async () => {
169 const r = await setFollowUpstream(app, bob, fresh(), { url: upUrl, branch: "main", enabled: true });
170 expect(r.ok ? "saved" : r.error).toBe("not_found");
171 });
172 });
173
174 describe("following", () => {
175 test("off: nothing is checked and nothing is proposed", async () => {
176 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: false }));
177 await commit(up, "b.txt", "b\n");
178 const r = await checkUpstream(app, fresh());
179 expect(r.ok ? r.value.kind : r.error).toBe("off");
180 expect(followTick(app)).toBe(0);
181 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(0);
182 expect(await resolveOid(ourDir(), stagedRef("main"))).toBeUndefined();
183 });
184
185 test("two clean upstream commits open one pull, which lands as a merge; the next check is up to date", async () => {
186 await commit(up, "c.txt", "c\n");
187 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: true }));
188 const r = must(await checkUpstream(app, fresh()));
189 expect(r.kind).toBe("pull");
190 if (r.kind !== "pull") return;
191 expect(r.behind).toBe(2);
192 const pull = getPull(app.db, ours.id, r.number)!;
193 expect(pull.title).toMatch(
194 new RegExp(`^Upstream: 2 commits from 127\\.0\\.0\\.1:${servers.port}/alice/up \\([0-9a-f]{7}\\.\\.[0-9a-f]{7}\\)$`),
195 );
196 expect(pull.authorId).toBe(alice.id);
197 expect(pull.headBranch).toMatch(/^upstream\/[0-9a-f]{7}$/);
198 // Our own work stays: the head is a merge on top of main, not upstream alone.
199 const head = await runGit(["show", "--format=%P", "--no-patch", pull.headOid], { cwd: ourDir() });
200 expect(head.ok && head.value.trim().split(" ")).toHaveLength(2);
201 expect(followWords(app, ours.id)).toBe(`2 behind, 1 opened, #${pull.number} open`);
202
203 // While it is open, a second check opens nothing more.
204 const again = must(await checkUpstream(app, fresh()));
205 expect(again.kind).toBe("pending");
206 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(1);
207
208 // The gate's choice: it carries upstream, so it lands as a merge.
209 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
210 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
211 await landThroughGate(pull.number);
212 const done = must(await checkUpstream(app, fresh()));
213 expect(done.kind).toBe("up_to_date");
214 expect(getFollow(app.db, ours.id)!.behind).toBe(0);
215 // A pull with nothing of upstream's is squashed as ever.
216 const newMain = (await resolveOid(ourDir(), "refs/heads/main"))!;
217 expect(await carriesUpstream(app, fresh(), ourDir(), newMain, newMain)).toBe(false);
218 });
219
220 test("a conflicting upstream commit goes to the builder as a converge run; the crew's merge lands", async () => {
221 await commit(fresh(), "a.txt", "one\nours\nthree\n");
222 await commit(up, "a.txt", "one\ntheirs\nthree\n");
223 const r = must(await checkUpstream(app, fresh()));
224 expect(r.kind).toBe("conflict");
225 if (r.kind !== "conflict") return;
226 expect(r.files).toEqual(["a.txt"]);
227 expect(r.builder).toBe("mason");
228 const issue = getIssueById(app.db, getFollow(app.db, ours.id)!.pendingId!)!;
229 expect(issue.kind).toBe("issue");
230 expect(issue.title).toMatch(/^Upstream: 1 commit from /);
231 expect(issue.body).toContain("`a.txt`");
232 expect(issue.body).toContain("refs/upstream/main");
233 const runs = listRuns(app.db, ours.id, { kind: "agent" }).filter((x) => x.issueId === issue.id);
234 expect(runs.map((x) => [x.reason, x.summary])).toEqual([["converge", "upstream moved: a.txt"]]);
235
236 // The brief the builder reads: merge the staged tip, keep both, explain.
237 const following = upstreamFollowing(app, ours.id)!;
238 expect(following.ref).toBe("refs/upstream/main");
239 const brief = taskPrompt({
240 agent: { user: { username: "mason" } },
241 repo: fresh(),
242 issue,
243 branch: "mason/1",
244 forgeUrl: servers.url,
245 isApp: false,
246 resuming: false,
247 reason: "converge",
248 comments: [],
249 reviews: [],
250 reviewComments: [],
251 since: "1",
252 conflictFiles: ["a.txt"],
253 following,
254 } as unknown as TaskInput);
255 expect(brief).toContain("git fetch origin refs/upstream/main && git merge FETCH_HEAD");
256 expect(brief).toContain("keep upstream's fixes, and keep this repository's own work");
257 expect(brief).toContain("explain each resolution");
258
259 // A second check while the crew works opens nothing more.
260 expect(must(await checkUpstream(app, fresh())).kind).toBe("pending");
261
262 // The crew's resolution: a real merge of the staged tip, kept both.
263 const work = await mkdtemp(join(tmpdir(), "forge-upstream-work-"));
264 try {
265 const g = (args: string[]) =>
266 runGit(args, {
267 cwd: work,
268 env: {
269 GIT_AUTHOR_NAME: "mason",
270 GIT_AUTHOR_EMAIL: "[email protected]",
271 GIT_COMMITTER_NAME: "mason",
272 GIT_COMMITTER_EMAIL: "[email protected]",
273 },
274 });
275 expect((await g(["clone", "--quiet", ourDir(), "."])).ok).toBe(true);
276 expect((await g(["fetch", "--quiet", "origin", "refs/upstream/main"])).ok).toBe(true);
277 expect((await g(["merge", "--no-edit", "FETCH_HEAD"])).ok).toBe(false);
278 await Bun.write(join(work, "a.txt"), "one\nours\ntheirs\nthree\n");
279 expect((await g(["commit", "--quiet", "-am", "Merge upstream, both lines kept"])).ok).toBe(true);
280 // As the agent's push would, without a hook: the branch arrives.
281 expect(
282 (await runGit(["fetch", "--quiet", work, "HEAD:refs/heads/mason/resolve"], { cwd: ourDir() })).ok,
283 ).toBe(true);
284 } finally {
285 await rm(work, { recursive: true, force: true });
286 }
287 const pull = must(
288 await openPull(app, alice, fresh(), {
289 title: "Take upstream",
290 body: `Closes #${issue.number}`,
291 baseBranch: "main",
292 headBranch: "mason/resolve",
293 }),
294 );
295 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
296 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
297 await landThroughGate(pull.number);
298 expect(must(await checkUpstream(app, fresh())).kind).toBe("up_to_date");
299 });
300
301 test("a proposal closed unlanded is not opened again until upstream moves, unless a person asks", async () => {
302 await commit(up, "d.txt", "d\n");
303 const r = must(await checkUpstream(app, fresh()));
304 expect(r.kind).toBe("pull");
305 if (r.kind !== "pull") return;
306 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(getPull(app.db, ours.id, r.number)!.id);
307 expect(must(await checkUpstream(app, fresh())).kind).toBe("declined");
308 const asked = must(await checkUpstream(app, fresh(), true));
309 expect(asked.kind).toBe("pull");
310 });
311 });
312
313 describe("the doors", () => {
314 test("the About card says what it follows, how far behind, and when it last looked", async () => {
315 const page = await (await fetch(`${servers.url}/alice/ours`, { headers: { cookie: cookie(alice) } })).text();
316 expect(page).toContain("data-following-upstream");
317 expect(page).toMatch(/Following\s*<a href="http:\/\/127\.0\.0\.1:\d+\/alice\/up\.git"/);
318 expect(page).toMatch(/last checked\s*<time[^>]*>\d\d:\d\d UTC<\/time/);
319 expect(page).toContain("1 behind");
320 });
321
322 test("the settings card shows it; a cross-origin save is refused and changes nothing", async () => {
323 const settings = await (await fetch(`${servers.url}/alice/ours/settings`, { headers: { cookie: cookie(alice) } })).text();
324 expect(settings).toContain("Follow upstream");
325 expect(settings).toContain("Check upstream now");
326 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
327 method: "POST",
328 redirect: "manual",
329 headers: {
330 cookie: cookie(alice),
331 origin: "https://evil.example",
332 "content-type": "application/x-www-form-urlencoded",
333 },
334 body: new URLSearchParams({ url: upUrl, branch: "main" }),
335 });
336 expect(res.status).toBeGreaterThanOrEqual(400);
337 expect(getFollow(app.db, ours.id)!.enabled).toBe(true);
338 });
339
340 test("the settings form turns it off, same-origin", async () => {
341 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
342 method: "POST",
343 redirect: "manual",
344 headers: {
345 cookie: cookie(alice),
346 origin: servers.url,
347 "content-type": "application/x-www-form-urlencoded",
348 },
349 body: new URLSearchParams({ url: upUrl, branch: "main" }),
350 });
351 expect(res.status).toBe(303);
352 expect(getFollow(app.db, ours.id)!.enabled).toBe(false);
353 const r = await checkUpstream(app, fresh());
354 expect(r.ok ? r.value.kind : r.error).toBe("off");
355 });
356
357 test("the API reads it, an admin sets it, and a reader sees nothing of an off one", async () => {
358 const admin = createToken(app.db, alice.id, "t", "admin").token;
359 const put = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
360 method: "PUT",
361 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
362 body: JSON.stringify({ url: upUrl, branch: "main", enabled: true }),
363 });
364 expect(put.status).toBe(200);
365 const got = (await (
366 await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, { headers: { authorization: `Bearer ${admin}` } })
367 ).json()) as { following: { url: string; enabled: boolean; originId?: string } };
368 expect(got.following.url).toBe(upUrl);
369 expect(got.following.enabled).toBe(true);
370 expect("originId" in got.following).toBe(false);
371 const bad = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
372 method: "PUT",
373 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
374 body: JSON.stringify({ url: "file:///etc/passwd", branch: "main", enabled: true }),
375 });
376 expect(bad.status).toBe(422);
377 expect(((await bad.json()) as { error: string }).error).toBe("invalid_url");
378 const ro = createToken(app.db, alice.id, "r", "ro").token;
379 const refused = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
380 method: "POST",
381 headers: { authorization: `Bearer ${ro}` },
382 });
383 expect(refused.status).toBe(403);
384 });
385
386 test("a git:// upstream is named, not linked; why a check failed is a writer's to read", async () => {
387 const pub = must(await createRepo(app, alice, { name: "pub", visibility: "public" }));
388 await commit(pub, "README.md", "pub\n");
389 must(
390 await setFollowUpstream(app, alice, pub, {
391 url: `git://127.0.0.1:${servers.port}/alice/up.git`,
392 branch: "main",
393 enabled: true,
394 }),
395 );
396 app.db
397 .query("UPDATE repo_upstream SET checked_at = ?2, error = 'fatal: remote words' WHERE repo_id = ?1")
398 .run(pub.id, new Date().toISOString());
399 const page = await (await fetch(`${servers.url}/alice/pub`)).text();
400 expect(page).toContain("data-following-upstream");
401 expect(page).not.toContain('href="git://');
402 expect(page).toContain("the last check did not finish");
403 expect(page).not.toContain("remote words");
404 const anon = (await (await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`)).json()) as {
405 following: { error: string | null };
406 };
407 expect(anon.following.error).toBeNull();
408 const ro = createToken(app.db, alice.id, "ro2", "ro").token;
409 const own = (await (
410 await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`, { headers: { authorization: `Bearer ${ro}` } })
411 ).json()) as { following: { error: string | null } };
412 expect(own.following.error).toBe("fatal: remote words");
413 });
414 });
415
416 describe("one check at a time", () => {
417 test("two checks at once open exactly one pull: the second is refused busy, and only the first is heard", async () => {
418 const twice = must(await createRepo(app, alice, { name: "twice", visibility: "private" }));
419 const dir = repoDir(app.reposRoot, "alice", "twice");
420 const upDir = repoDir(app.reposRoot, "alice", "up");
421 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
422 const at = getRepoById(app.db, twice.id)!;
423 await commit(at, "twice.txt", "our own work\n");
424 must(await setFollowUpstream(app, alice, at, { url: upUrl, branch: "main", enabled: true }));
425 await commit(up, "e.txt", "e\n");
426 const heard: string[] = [];
427 const off = app.bus.subscribe((e) => {
428 if (e.repoId === twice.id) heard.push(e.kind);
429 });
430 try {
431 // A double click: both start before either has read "no proposal open".
432 const both = await Promise.all([
433 checkUpstreamNow(app, alice, at),
434 checkUpstreamNow(app, alice, at),
435 ]);
436 expect(both.map((r) => (r.ok ? r.value.kind : r.error)).sort()).toEqual(["busy", "pull"]);
437 expect(
438 listPulls(app.db, twice.id, { state: "open" }).filter((p) => p.title.startsWith("Upstream: ")),
439 ).toHaveLength(1);
440 expect(heard.filter((k) => k === "repo.upstream_checked")).toHaveLength(1);
441 // The claim is let go: the next check answers, and opens nothing more.
442 expect(must(await checkUpstreamNow(app, alice, at)).kind).toBe("pending");
443 expect(listPulls(app.db, twice.id, { state: "open" })).toHaveLength(1);
444 } finally {
445 off();
446 }
447 });
448
449 test("the API answers a check already running with 409 busy", async () => {
450 const at = getRepoById(app.db, ours.id)!;
451 const rw = createToken(app.db, alice.id, "rw-busy", "rw").token;
452 const post = () =>
453 fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
454 method: "POST",
455 headers: { authorization: `Bearer ${rw}` },
456 });
457 const running = checkUpstream(app, at);
458 const res = await post();
459 await running;
460 expect(res.status).toBe(409);
461 expect(((await res.json()) as { error: string }).error).toBe("busy");
462 });
463 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs