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

Following an upstream is safe: exact-origin credentials, https only and pinned, one check at a time, and an upstream branch nobody else can plant #3626

Parked opened this
Closed without merging

scout/forge:scout/3622-following-an-upstream-is-safe-exact-orig → main 22 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +2302 −12
docs/ORIGINS.md +53
@@ -534,6 +534,59 @@ 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 refused at save: its transport resolves the name
583 itself, past the vetted-address pin. The settings card's "Check upstream now"
584 is the admin's; any writer checks from the API (`POST …/upstream/check`) or the
585 terminal's `u`. What can be saved can be checked: save and check apply the
586 same private-host rule. API:
587 `GET|PUT /api/v1/repos/:owner/:name/upstream`,
588 `POST /api/v1/repos/:owner/:name/upstream/check`.
589
537590 ## API
538591
539592 ```
src/actions/migrate.ts +24
@@ -68,6 +68,10 @@ import {
6868 } from "./repos.ts";
6969 import { tell, toldWords } from "./tell.ts";
7070 import { pinFor, remoteGitEnv, type Pin } from "../git/remote-env.ts";
71 import { setFollowUpstream } from "./upstream_follow.ts";
72 import { createLog } from "../kernel/log.ts";
73
74 const log = createLog("migrate");
7175
7276 /** The whole clone — the HEAD probe and the fetch — gets this long. */
7377 export const MIGRATE_TIMEOUT_MS = 120_000;
@@ -141,6 +145,8 @@ interface Resolved {
141145 readonly provider?: Provider;
142146 /** The person, as the source's commits may name them. */
143147 readonly who: Who;
148 /** The source's own parent on its host, when it is a fork: following's second choice. */
149 readonly parentUrl?: string;
144150 }
145151
146152 /** Why the work branch is the one it is: said in the job and the brief. */
@@ -442,6 +448,9 @@ export async function resolveSource(
442448 authEnv: () => provider.value.gitAuthEnv(url),
443449 provider: provider.value,
444450 who: { logins: [origin.login, user.username], emails: [user.email] },
451 ...(remote.value.parent === null
452 ? {}
453 : { parentUrl: `${origin.webUrl.replace(/\/+$/, "")}/${remote.value.parent}` }),
445454 });
446455 }
447456
@@ -560,6 +569,21 @@ async function runMigration(
560569 });
561570 }
562571
572 // The source becomes the upstream this repository follows (#3442): on
573 // when the crew runs it on its own, off — but filled in — otherwise.
574 const followed = await setFollowUpstream(app, user, current, {
575 url: source.url,
576 branch: cloned.value.head ?? work?.name ?? current.defaultBranch,
577 enabled: crew?.autonomous === true,
578 originId: source.originId,
579 ...(source.parentUrl === undefined ? {} : { parentUrl: source.parentUrl }),
580 });
581 if (!followed.ok)
582 log.warn("migrated repository does not follow its source", {
583 repo: `${current.ownerName}/${current.name}`,
584 why: followed.error,
585 });
586
563587 const where = `${current.ownerName}/${current.name}`;
564588 let detail = `migrated as ${where} — ${plural(branches.length, "branch", "branches")}, ${plural(refs.size - branches.length, "tag")}${conversations}`;
565589 if (work !== undefined)
src/actions/upstream_follow.ts added +686
@@ -0,0 +1,686 @@
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 { repoDir } from "../git/repos.ts";
49 import { createLog } from "../kernel/log.ts";
50 import { type Resolve, vetHost } from "../kernel/outbound.ts";
51 import { err, ok, type Result } from "../kernel/result.ts";
52 import { providerForOrigin } from "../origins/credential.ts";
53 import { redact, secretsIn } from "../origins/credentials.ts";
54 import { REMOTE_PROTOCOLS } from "../git/remote-env.ts";
55 import { vettedEnv } from "../origins/git-mirror.ts";
56 import { isTrustedHost } from "../origins/trusted-hosts.ts";
57 import { requireRepoAdmin, requireWriter, type AccessError } from "./access.ts";
58 import { openIssue } from "./issues.ts";
59 import { isPrivateHost, migrateUrl } from "./migrate.ts";
60 import { openPull } from "./pulls.ts";
61
62 const log = createLog("upstream-follow");
63
64 /** How often a following repository is checked on its own. */
65 export const FOLLOW_EVERY_MS = 30 * 60_000;
66 /** One check's whole budget: ls-remote and fetch together. */
67 const CHECK_TIMEOUT_MS = 120_000;
68 /** Where the upstream tip is staged: not a branch, so a check moves nothing of ours. */
69 export const stagedRef = (branch: string): string => `refs/upstream/${branch}`;
70 /** The branch a clean proposal is opened from. */
71 const proposalBranch = (tip: string): string => `upstream/${tip.slice(0, 7)}`;
72 /** Every proposal's title begins so; the tick line and the page count them by it. */
73 export const UPSTREAM_TITLE = "Upstream: ";
74
75 /**
76 * What a proposal calls its upstream. Proposals are read by everyone who can
77 * read the repository, so a followed-with-credentials upstream stays unnamed.
78 */
79 export function proposalLabel(follow: { url: string; originId: string }): string {
80 return follow.originId === "" ? upstreamLabel(follow.url) : "a private upstream";
81 }
82
83 /** `github.com/Trevato/SO-ARM100` for `https://github.com/Trevato/SO-ARM100.git`. */
84 export function upstreamLabel(url: string): string {
85 return url
86 .replace(/^[a-z]+:\/\//i, "")
87 .replace(/\/+$/, "")
88 .replace(/\.git$/, "");
89 }
90
91 export type FollowError =
92 | AccessError
93 | "invalid_url"
94 | "private_host"
95 | "invalid_branch"
96 | "archived"
97 /** A mirror's history is its origin's; it follows nothing else. */
98 | "mirrored";
99
100 /** What each refusal says, at every door. */
101 export const FOLLOW_REFUSALS: Record<FollowError | CheckError, string> = {
102 unauthorized: "Sign in to change where this repository follows.",
103 forbidden: "Only this repository's admins change where it follows.",
104 not_found: "That repository is not here.",
105 invalid_url: "That is not a git address the forge will fetch: use https:// or http://, with no password in it.",
106 private_host: "That address is inside the network, not a public repository.",
107 invalid_branch: "That is not a branch name.",
108 archived: "This repository is archived; wake it first.",
109 mirrored: "A mirror follows its origin; it cannot follow another upstream.",
110 off: "Following an upstream is off for this repository.",
111 unreadable: "The upstream could not be read.",
112 no_branch: "The upstream has no such branch.",
113 diverged: "The staged upstream tip could not be fetched.",
114 git: "Git could not prepare the proposal.",
115 nobody: "The person who turned following on can no longer write here; turn it on again.",
116 busy: "Already checking this upstream; its answer is on the way.",
117 };
118
119 /**
120 * The same rule migrate keeps (`resolveSource`): an admin, a forge run for
121 * one person, or a host the admin trusts may be inside the network. Save and
122 * check both ask it, so what can be saved can be checked.
123 */
124 function mayBePrivate(app: App, actor: User, host: string): boolean {
125 return actor.isAdmin || app.config.migrateFromPrivateHosts === true || isTrustedHost(host);
126 }
127
128 /** A pasted address the forge may fetch, refused inside the network unless allowed. */
129 export async function upstreamUrl(
130 app: App,
131 actor: User,
132 raw: string,
133 resolve?: Resolve,
134 ): Promise<Result<string, "invalid_url" | "private_host">> {
135 const url = migrateUrl(raw);
136 // git:// is refused: its transport resolves the name itself, past the pin.
137 if (url === undefined || new URL(url).protocol === "git:") return err("invalid_url");
138 const host = new URL(url).hostname;
139 if (mayBePrivate(app, actor, host)) return ok(url);
140 if (isPrivateHost(host)) return err("private_host");
141 const vetted = await vetHost(host, resolve ? { resolve } : {});
142 if (!vetted.ok && vetted.error === "refused") return err("private_host");
143 return ok(url);
144 }
145
146 /**
147 * Whether an origin's token may travel to this upstream: only to the exact
148 * https origin (scheme, host and port) the person connected. An `http://`
149 * upstream on the same host is fetched anonymously.
150 */
151 export function mayCarryCredential(upstreamUrl: string, webUrl: string): boolean {
152 try {
153 const up = new URL(upstreamUrl);
154 return up.protocol === "https:" && up.origin === new URL(webUrl).origin;
155 } catch {
156 return false;
157 }
158 }
159
160 /** The actor's connected origin at the upstream's https origin: its credential opens a private one. */
161 function originOn(app: App, user: User, url: string): string {
162 return listOrigins(app.db, user.id).find((o) => mayCarryCredential(url, o.webUrl))?.id ?? "";
163 }
164
165 /** The origin to remember: one whose token may go to this url, else none. */
166 function savedOrigin(app: App, user: User, url: string, given: string | undefined): string {
167 if (given === undefined) return originOn(app, user, url);
168 const origin = given === "" ? undefined : getOriginFor(app.db, user.id, given);
169 return origin !== undefined && mayCarryCredential(url, origin.webUrl) ? given : "";
170 }
171
172 /**
173 * Turn following on or off, or point it elsewhere: the repository's admins
174 * only. Whoever saves it on is who the forge acts as.
175 */
176 export async function setFollowUpstream(
177 app: App,
178 actor: User | undefined,
179 repo: Repo,
180 input: {
181 readonly url: string;
182 readonly branch: string;
183 readonly enabled: boolean;
184 readonly parentUrl?: string;
185 /** The origin the source came through, when the caller knows it (migrate). */
186 readonly originId?: string;
187 },
188 resolve?: Resolve,
189 ): Promise<Result<UpstreamFollow, FollowError>> {
190 const admin = requireRepoAdmin(app, actor, repo);
191 if (!admin.ok) return admin;
192 if (repo.archivedAt !== null && input.enabled) return err("archived");
193 if (repo.origin !== null && input.enabled) return err("mirrored");
194 const branch = input.branch.trim();
195 if (!isBranchName(branch)) return err("invalid_branch");
196 // Turning it off is never refused: an unchanged address is not vetted again.
197 const current = getFollow(app.db, repo.id);
198 const unchanged =
199 !input.enabled && current !== undefined && current.url === input.url.trim() && current.branch === branch;
200 const url = unchanged ? ok(current.url) : await upstreamUrl(app, admin.value, input.url, resolve);
201 if (!url.ok) return url;
202 const parent =
203 input.parentUrl === undefined || input.parentUrl === ""
204 ? undefined
205 : migrateUrl(input.parentUrl);
206 const follow = putFollow(app.db, {
207 repoId: repo.id,
208 url: url.value,
209 branch,
210 enabled: input.enabled,
211 byId: admin.value.id,
212 originId: savedOrigin(app, admin.value, url.value, input.originId),
213 ...(parent === undefined ? {} : { parentUrl: parent }),
214 });
215 app.bus.append({
216 kind: "repo.upstream_follow",
217 repoId: repo.id,
218 actorId: admin.value.id,
219 payload: { url: follow.url, branch: follow.branch, enabled: follow.enabled },
220 });
221 return ok(follow);
222 }
223
224 export type CheckError =
225 | "off"
226 | "unreadable"
227 | "no_branch"
228 | "diverged"
229 | "git"
230 | "nobody"
231 /** Another check of this repository is in flight: one at a time, at every door. */
232 | "busy";
233
234 /** What one check found. */
235 export type Checked =
236 | { readonly kind: "up_to_date"; readonly tip: string }
237 /** A proposal is already open; it is the one to land first. */
238 | { readonly kind: "pending"; readonly behind: number; readonly id: string }
239 /** The last proposal of this same tip was closed unlanded: asked again only by a person. */
240 | { readonly kind: "declined"; readonly behind: number; readonly id: string }
241 | { readonly kind: "pull"; readonly behind: number; readonly number: number }
242 | {
243 readonly kind: "conflict";
244 readonly behind: number;
245 readonly number: number;
246 readonly files: readonly string[];
247 readonly builder: string | undefined;
248 };
249
250 /** "Check upstream now": a writer may ask; the check acts as who turned it on. */
251 export async function checkUpstreamNow(
252 app: App,
253 actor: User | undefined,
254 repo: Repo,
255 ): Promise<Result<Checked, AccessError | CheckError>> {
256 const writer = requireWriter(app, actor, repo);
257 if (!writer.ok) return writer;
258 return checkUpstream(app, repo, true);
259 }
260
261 /** Repositories with a check in flight: one at a time each, whoever asked. */
262 const checking = new Set<string>();
263
264 /**
265 * One check, of one repository. Every outcome is noted on its row. The
266 * claim is taken before the first await, so two callers — a double click,
267 * the page and the terminal, a person and the tick — never both read "no
268 * proposal open" and both open one: the second is answered `busy`.
269 */
270 export async function checkUpstream(
271 app: App,
272 repo: Repo,
273 /** A person asked: a proposal they closed of this same tip is opened again. */
274 asked = false,
275 ): Promise<Result<Checked, CheckError>> {
276 if (checking.has(repo.id)) return err("busy");
277 checking.add(repo.id);
278 let checked: Result<Checked, CheckError> = err("git");
279 try {
280 checked = await checkOnce(app, repo, asked);
281 return checked;
282 } finally {
283 checking.delete(repo.id);
284 // An open About card or settings page redraws its "last checked" line;
285 // a following that is off was not checked, and says nothing.
286 if (checked.ok || checked.error !== "off")
287 app.bus.append({
288 kind: "repo.upstream_checked",
289 repoId: repo.id,
290 payload: { behind: getFollow(app.db, repo.id)?.behind ?? 0 },
291 });
292 }
293 }
294
295 async function checkOnce(app: App, repo: Repo, asked: boolean): Promise<Result<Checked, CheckError>> {
296 const follow = getFollow(app.db, repo.id);
297 if (follow === undefined || !follow.enabled || repo.archivedAt !== null || repo.origin !== null)
298 return err("off");
299 const at = new Date().toISOString();
300 const failed = (error: CheckError, why = ""): Result<Checked, CheckError> => {
301 noteCheck(app.db, repo.id, { at, error: why || FOLLOW_REFUSALS[error] });
302 return err(error);
303 };
304 const by = getUserById(app.db, follow.byId);
305 if (by === undefined || !canWrite(app.db, repo, by)) return failed("nobody");
306
307 // The credential, when the upstream is private: the connected origin's,
308 // scoped to this one git invocation (`origins/credentials.ts`).
309 let authEnv: Record<string, string> = {};
310 if (follow.originId !== "") {
311 const origin = getOriginFor(app.db, by.id, follow.originId);
312 const provider = origin === undefined ? undefined : providerForOrigin(app, origin);
313 // Again at each check, rows written by migrate included.
314 if (origin !== undefined && provider?.ok && mayCarryCredential(follow.url, origin.webUrl))
315 authEnv = await provider.value.gitAuthEnv(follow.url);
316 }
317 // Checked again each time: a name that resolved outside the network may not now.
318 const vetted = await upstreamUrl(app, by, follow.url);
319 if (!vetted.ok) return failed("unreadable", FOLLOW_REFUSALS[vetted.error]);
320 // Pinned to the address the vet resolved, so a second DNS answer cannot redirect the fetch.
321 const pinned = await vettedEnv(
322 follow.url,
323 authEnv,
324 REMOTE_PROTOCOLS,
325 mayBePrivate(app, by, new URL(follow.url).hostname),
326 );
327 if (!pinned.ok) return failed("unreadable", pinned.error.message);
328 const env = pinned.value;
329 const said = (stderr: string): string =>
330 redact(stderr.trim(), ...secretsIn(authEnv)).split("\n").find((l) => l.trim() !== "") ?? "";
331 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
332 const deadline = Date.now() + CHECK_TIMEOUT_MS;
333 const remaining = (): number => Math.max(1_000, deadline - Date.now());
334
335 const listed = await runGitCapture(
336 ["ls-remote", "--", follow.url, `refs/heads/${follow.branch}`],
337 { cwd: dir, env, timeoutMs: remaining() },
338 );
339 if (listed.code !== 0)
340 return failed("unreadable", `The upstream could not be read: ${said(listed.stderr) || "no reason given"}`);
341 const tip = listed.stdout.split("\t")[0]?.trim() ?? "";
342 if (!isSafeOid(tip)) return failed("no_branch");
343
344 // Fetch only when the tip moved: the staged ref is what the last fetch brought.
345 const ref = stagedRef(follow.branch);
346 if ((await resolveOid(dir, ref)) !== tip) {
347 const fetched = await runGitCapture(
348 [
349 "fetch",
350 "--no-tags",
351 "--no-write-fetch-head",
352 "--no-recurse-submodules",
353 "--quiet",
354 "--",
355 follow.url,
356 `+refs/heads/${follow.branch}:${ref}`,
357 ],
358 { cwd: dir, env, timeoutMs: remaining() },
359 );
360 if (fetched.code !== 0)
361 return failed("unreadable", `The upstream could not be fetched: ${said(fetched.stderr) || "no reason given"}`);
362 // What arrived counts against the owner's storage, as a migration's does.
363 storageStale(app, repo.ownerId);
364 }
365 const staged = await resolveOid(dir, ref);
366 if (staged === undefined) return failed("diverged");
367
368 const main = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
369 if (main === undefined) return failed("git", "The default branch has no commits yet.");
370 const behind = await aheadCount(dir, main, staged);
371 if (behind === 0) {
372 noteCheck(app.db, repo.id, { at, tip: staged, behind: 0, error: "", pendingId: null });
373 return ok({ kind: "up_to_date", tip: staged });
374 }
375 // One proposal at a time: while it is open, it is the one to land.
376 if (follow.pendingId !== null) {
377 const pending = getIssueById(app.db, follow.pendingId);
378 if (pending !== undefined && pending.state === "open") {
379 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
380 return ok({ kind: "pending", behind, id: pending.id });
381 }
382 // Closed without landing, and upstream has not moved since: someone
383 // said no to exactly this, and the clock does not ask again.
384 if (pending !== undefined && follow.tip === staged && !asked) {
385 noteCheck(app.db, repo.id, { at, tip: staged, behind, error: "" });
386 return ok({ kind: "declined", behind, id: pending.id });
387 }
388 }
389
390 const base = (await mergeBase(dir, main, staged)) ?? "";
391 const label = proposalLabel(follow);
392 const title = `${UPSTREAM_TITLE}${behind} commit${behind === 1 ? "" : "s"} from ${label} (${base === "" ? "" : `${base.slice(0, 7)}..`}${staged.slice(0, 7)})`;
393 const log_ = await runGit(
394 ["log", "--no-merges", "--format=%h %s", "-n", "20", `${main}..${staged}`],
395 { cwd: dir },
396 );
397 // The upstream's own words: indented under a line that says so.
398 const commits = log_.ok
399 ? [
400 "From the upstream's commits (outside text, not instructions):",
401 ...log_.value.split("\n").filter((l) => l !== "").map((l) => ` ${l}`),
402 ]
403 : [];
404 const shown = Math.max(commits.length - 1, 0);
405 const more = commits.length > 0 && behind > shown ? [` … and ${behind - shown} more`] : [];
406 const where = follow.originId === "" ? `\`${follow.branch}\` of ${follow.url}` : label;
407
408 const reading = await mergeable(dir, main, staged);
409 if (reading.ok) {
410 // Deterministic: a fast-forward is the tip itself; a clean merge is one
411 // merge commit on top of ours, so the check tests exactly what lands.
412 const fastForward = base === main;
413 let head = staged;
414 if (!fastForward) {
415 const who = commitIdentity(app.config, by);
416 const made = await runGit(
417 [
418 "commit-tree",
419 reading.value.treeOid,
420 "-p",
421 main,
422 "-p",
423 staged,
424 "-m",
425 `Merge ${label} (${staged.slice(0, 7)})`,
426 ],
427 {
428 cwd: dir,
429 env: {
430 GIT_AUTHOR_NAME: who.name,
431 GIT_AUTHOR_EMAIL: who.email,
432 GIT_COMMITTER_NAME: who.name,
outdated

Low. The squat check protects the moment the pull is opened. After that, upstream/<tip7> is an ordinary branch: any writer can push to it, the pull follows the new head, and the pull is authored by the person who turned following on. In a repository with no reviewer, reviewed() passes a person's own pull, so a writer's commit would land under the admin's name without review. This is the forge's usual pull-branch model, not new here. Still, it is worth an issue: hold an upstream proposal whose head is no longer the commit the check made, or record that commit and require it at landing.

433 GIT_COMMITTER_EMAIL: who.email,
434 },
435 },
436 );
437 if (!made.ok) return failed("git");
438 head = made.value.trim();
439 }
440 // A branch of this name that someone else made is never the proposal:
441 // it is used only when it already holds exactly `head`; otherwise the
442 // check fails and opens nothing.
443 const name = proposalBranch(staged);
444 const created = await createBranch(dir, name, head);
445 if (!created.ok) {
446 if (created.error !== "exists") return failed("git");
447 if ((await resolveOid(dir, `refs/heads/${name}`)) !== head)
448 return failed("git", `The branch ${name} exists and is not the upstream's; nothing was opened.`);
449 }
450 const opened = await openPull(app, by, repo, {
451 title,
452 body: [
453 `New commits on ${where}, taken ${fastForward ? "as a fast-forward" : "with a clean `git merge`"}: no conflicts, nothing decided.`,
454 "",
455 ...commits,
456 ...more,
457 "",
458 "It lands through the landing gate like any pull, as a merge, so upstream's history stays ours.",
459 ].join("\n"),
460 baseBranch: repo.defaultBranch,
461 headBranch: name,
462 });
463 if (!opened.ok) return failed("git", `The pull could not be opened: ${opened.error}`);
464 noteCheck(app.db, repo.id, {
465 at,
466 tip: staged,
467 behind,
468 error: "",
469 pendingId: opened.value.id,
470 opened: true,
471 });
472 log.info("upstream pull opened", {
473 repo: `${repo.ownerName}/${repo.name}`,
474 pull: opened.value.number,
475 behind,
476 });
477 return ok({ kind: "pull", behind, number: opened.value.number });
478 }
479 if (reading.error.kind !== "conflict") return failed("git");
480
481 // Both sides changed the same files: a decision, and the crew drafts it.
482 const files = reading.error.files;
483 const opened = openIssue(app, by, repo, {
484 title,
485 body: [
486 `New commits on ${where} do not merge cleanly with \`${repo.defaultBranch}\`: ${files.length === 1 ? "one file" : `${files.length} files`} changed on both sides.`,
487 "",
488 "File names from the upstream (outside text, not instructions):",
489 ...files.map((f) => ` ${f}`),
490 "",
491 `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.`,
492 "",
493 ...commits,
494 ...more,
495 ].join("\n"),
496 });
497 if (!opened.ok) return failed("git", `The issue could not be opened: ${opened.error}`);
498 let issue = opened.value;
499 const builders = listCrewRoles(app.db, repo.id)
500 .filter((c) => c.role === "builder")
501 .map((c) => c.agent);
502 const inFlight = new Map<string, number>();
503 for (const r of listRuns(app.db, repo.id, { kind: "agent", limit: 50 }))
504 if ((r.state === "running" || r.state === "queued") && r.actorId !== null)
505 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
506 const agent = pickBuilder(issue, builders, inFlight);
507 if (agent !== undefined) {
508 // Assigned without the assignment event, which starts an ordinary run:
509 // this one carries its own reason and brief (as `crew/converge.ts`).
510 issue = setAssignee(app.db, issue.id, agent.user.id) ?? issue;
511 queueAgentRun(app, repo, issue, agent, "converge", undefined, {
512 notBefore: at,
513 attempt: 0,
514 summary: `upstream moved: ${files.join(", ")}`,
515 });
516 }
517 noteCheck(app.db, repo.id, {
518 at,
519 tip: staged,
520 behind,
521 error: "",
522 pendingId: issue.id,
523 opened: true,
524 });
525 log.info("upstream conflict sent to the crew", {
526 repo: `${repo.ownerName}/${repo.name}`,
527 issue: issue.number,
528 files: files.length,
529 builder: agent?.user.username ?? "none",
530 });
531 return ok({
532 kind: "conflict",
533 behind,
534 number: issue.number,
535 files,
536 builder: agent?.user.username,
537 });
538 }
539
540 /** What the crew's brief says about a following repository's converge run. */
541 export function upstreamFollowing(
542 app: App,
543 repoId: string,
544 ): { parent: string; branch: string; ref: string; upstream: true } | undefined {
545 const follow = getFollow(app.db, repoId);
546 if (follow === undefined) return undefined;
547 return {
548 parent: proposalLabel(follow),
549 branch: follow.branch,
550 ref: stagedRef(follow.branch),
551 upstream: true,
552 };
553 }
554
555 /**
556 * Whether a pull's head carries upstream commits the base lacks: such a
557 * pull lands as a merge, never a squash, so upstream's history becomes an
558 * ancestor of ours and the next check counts only what is new. Asked of
559 * git: the staged tip's merge base with the head is not already in the base.
560 */
561 export async function carriesUpstream(
562 app: App,
563 repo: Repo,
564 dir: string,
565 headOid: string,
566 baseOid: string,
567 ): Promise<boolean> {
568 const follow = getFollow(app.db, repo.id);
569 if (follow === undefined) return false;
570 const staged = await resolveOid(dir, stagedRef(follow.branch));
571 if (staged === undefined || !isSafeOid(headOid) || !isSafeOid(baseOid)) return false;
572 const shared = await mergeBase(dir, staged, headOid);
573 if (shared === undefined) return false;
574 const inBase = await runGit(["merge-base", "--is-ancestor", shared, baseOid], { cwd: dir });
575 return !inBase.ok;
576 }
577
578 /** A repository's following, as the API says it: no origin id, no actor id. */
579 export const followJson = (f: UpstreamFollow) => ({
580 url: f.url === "" ? null : f.url,
581 branch: f.branch === "" ? null : f.branch,
582 enabled: f.enabled,
583 parentUrl: f.parentUrl === "" ? null : f.parentUrl,
584 checkedAt: f.checkedAt,
585 tip: f.tip === "" ? null : f.tip,
586 behind: f.behind,
587 error: f.error === "" ? null : f.error,
588 opened: f.opened,
589 });
590
591 /**
592 * Every following repository whose last check is older than
593 * `FOLLOW_EVERY_MS`, checked beside the tick, never in front of it: a
594 * slow upstream must not hold the crew up. Answers how many were started.
595 */
596 export function followTick(app: App, now = Date.now()): number {
597 let started = 0;
598 for (const follow of listFollowing(app.db)) {
599 if (checking.has(follow.repoId)) continue;
600 if (follow.checkedAt !== null && now - Date.parse(follow.checkedAt) < FOLLOW_EVERY_MS)
601 continue;
602 const repo = getRepoById(app.db, follow.repoId);
603 if (repo === undefined || repo.archivedAt !== null) continue;
604 started++;
605 // `checkUpstream` claims the repository before its first await.
606 void checkUpstream(app, repo).catch((error) =>
607 log.error("upstream check failed", {
608 repo: `${repo.ownerName}/${repo.name}`,
609 error: String(error),
610 }),
611 );
612 }
613 return started;
614 }
615
616 /** For the tick line: where a following repository stands, in a few words. */
617 export function followWords(app: App, repoId: string): string | undefined {
618 const follow = getFollow(app.db, repoId);
619 if (follow === undefined || !follow.enabled) return undefined;
620 const pending =
621 follow.pendingId === null ? undefined : getIssueById(app.db, follow.pendingId);
622 const open = pending !== undefined && pending.state === "open" ? `, #${pending.number} open` : "";
623 return `${follow.behind} behind, ${follow.opened} opened${open}`;
624 }
625
626 /**
627 * The following a viewer may read: an enabled one for anyone who reads the
628 * repository, an off one for its admins only; a private upstream's address
629 * (fetched with an admin's origin) is the admins' too — the rule the About line,
630 * the terminal's About card and `GET …/upstream` share.
631 */
632 export function followShown(
633 app: App,
634 repo: Repo,
635 viewer: User | undefined,
636 ): UpstreamFollow | undefined {
637 const follow = getFollow(app.db, repo.id);
638 if (follow === undefined) return undefined;
639 const admin = canAdmin(app.db, repo, viewer);
640 if (!follow.enabled && !admin) return undefined;
641 if (admin || follow.originId === "") return follow;
642 // Fetched with an admin's credential, so the upstream is private: readers
643 // get the standing, not the address, branch, parent or tip.
644 return {
645 ...follow,
646 url: "",
647 branch: "",
648 parentUrl: "",
649 tip: "",
650 error: follow.error === "" ? "" : "the last check did not finish",
651 };
652 }
653
654 /**
655 * Where a following repository stands, in words: "3 behind", "up to date",
656 * "off". Why a check failed is the remote's stderr, redacted, and only a
657 * writer is told it; anyone else reads "the last check did not finish".
658 */
659 export function standing(follow: UpstreamFollow, writer: boolean): string {
660 if (!follow.enabled) return "off";
661 if (follow.checkedAt === null) return "not checked yet";
662 if (follow.error !== "") return writer ? follow.error : "the last check did not finish";
663 return follow.behind === 0 ? "up to date" : `${follow.behind} behind`;
664 }
665
666 /** HH:MM in UTC, the instant a check last ran. */
667 export function clockWords(iso: string): string {
668 const at = new Date(iso);
669 return Number.isNaN(at.getTime()) ? "" : `${at.toISOString().slice(11, 16)} UTC`;
670 }
671
672 /** What a check found, in one sentence, for the page's flash and the terminal's toast. */
673 export function checkedWords(c: Checked): string {
674 switch (c.kind) {
675 case "up_to_date":
676 return "Up to date with the upstream.";
677 case "pending":
678 return `${c.behind} behind; the open proposal lands first.`;
679 case "declined":
680 return `${c.behind} behind; the last proposal was closed.`;
681 case "pull":
682 return `${c.behind === 1 ? "1 new upstream commit merges" : `${c.behind} new upstream commits merge`} cleanly: pull #${c.number} lands through the gate.`;
683 case "conflict":
684 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}`}.`;
685 }
686 }
src/core/event_audience.ts +5
@@ -36,6 +36,8 @@ const READER_KINDS: ReadonlySet<string> = new Set([
3636 "issue.closed",
3737 "issue.commented",
3838 "usage.delta",
39 // Only a count of commits behind: the About line shows it to every reader.
40 "repo.upstream_checked",
3941 "issue.raised",
4042 "issue.blocked",
4143 "pull.pushed",
@@ -160,6 +162,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
160162 // Which of a person's connected accounts a mirror syncs through is too.
161163 kind.startsWith("origin.") ||
162164 kind === "repo.settings_updated" ||
165 // Where a repository follows is its admins' to read (`followShown`),
166 // off or on: the address is often a private repository's.
167 kind === "repo.upstream_follow" ||
163168 kind === "repo.crew_outsiders"
164169 )
165170 return "admins";
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
@@ -28,6 +28,11 @@ import { mergeable, resolveOid, treeOf } from "../git/merge.ts";
2828 import { repoDir } from "../git/repos.ts";
2929 import { CLOSED_NOTE } from "../core/done_on_main.ts";
3030 import { mergePull } from "../actions/pulls.ts";
31 import {
32 carriesUpstream,
33 followTick,
34 followWords,
35 } from "../actions/upstream_follow.ts";
3136 import {
3237 listCrewRoles,
3338 type Agent,
@@ -1169,6 +1174,7 @@ export async function autonomyTick(
11691174 // never a mystery: the numbers behind "idle" are on the line.
11701175 const status = autonomyStatus(app, current, now);
11711176 const approved = waitWords(lastWaits(current.id));
1177 const upstream = followWords(app, current.id);
11721178 const ready = readyNow(repoGraph(app.db, current.id, { sealed: true }));
11731179 const held = heldBy(
11741180 app,
@@ -1203,6 +1209,8 @@ export async function autonomyTick(
12031209 // What the merge queue is doing now, not what the sweep admitted (#3430).
12041210 queue: queueWords(current.id),
12051211 spent: `${status.spentTodayUsd.toFixed(2)}/${status.ceilingUsd}`,
1212 // A repository following its upstream: how far behind, how many proposed (#3442).
1213 ...(upstream === undefined ? {} : { upstream }),
12061214 ...(status.paused === null ? {} : { paused: status.paused }),
12071215 // Starts after the first, and how many followed a crash (#3708).
12081216 restarts: boots.restarts,
@@ -1227,6 +1235,13 @@ export async function autonomyTick(
12271235 } catch (error) {
12281236 log.error("sentinel failed", { error: String(error) });
12291237 }
1238 // Every following repository is checked on its own clock (#3442), beside
1239 // the tick: a slow upstream holds nothing up.
1240 try {
1241 followTick(app, now.getTime());
1242 } catch (error) {
1243 log.error("upstream follow failed", { error: String(error) });
1244 }
12301245 // Review is not autonomy's alone: an agent's green pull is read by the
12311246 // crew's reviewer in every repository that has one.
12321247 try {
@@ -1912,7 +1927,18 @@ async function landGated(
19121927 by: "rule",
19131928 ms: 0,
19141929 });
1915 const merged = await mergePull(app, by, repo, pull, "squash", expect);
1930 // A pull carrying upstream's commits lands as a merge: squashed, their
1931 // history would never be ours and the next check would count it again.
1932 const strategy = (await carriesUpstream(
1933 app,
1934 repo,
1935 await pullDir(app.db, app.reposRoot, repo, pull),
1936 pull.headOid,
1937 expect.baseOid,
1938 ))
1939 ? "merge"
1940 : "squash";
1941 const merged = await mergePull(app, by, repo, pull, strategy, expect);
19161942 if (!merged.ok) {
19171943 const why = mergeWhy(merged.error);
19181944 log.info("green but not landed", {
src/crew/brief.ts +26 −3
@@ -196,7 +196,14 @@ export interface TaskInput extends BriefInput {
196196 readonly resolution?: string | undefined;
197197 /** For `converge`: the parent this repository follows, and its branch. */
198198 readonly following?:
199 | { readonly parent: string; readonly branch: string }
199 | {
200 readonly parent: string;
201 readonly branch: string;
202 /** Where it is staged, when not `refs/following/<branch>`. */
203 readonly ref?: string;
204 /** An outside upstream this repository follows (#3442), not a forge parent. */
205 readonly upstream?: boolean;
206 }
200207 | undefined;
201208 /** For `review`: the pull's diff against its base, capped. */
202209 readonly reviewDiff?: string | undefined;
@@ -451,13 +458,29 @@ function taskBody(input: TaskInput): string {
451458 const parent = input.following?.parent ?? "its parent";
452459 const pbranch = input.following?.branch ?? "main";
453460 const direction = input.repo.autonomyDirection.trim();
461 const staged = input.following?.ref ?? `refs/following/${pbranch}`;
462 if (input.following?.upstream === true) {
463 out.push(
464 `This repository follows its upstream ${parent} (\`${pbranch}\`), and new upstream commits do not merge cleanly. Issue #${issue.number}: ${issue.title}`,
465 "",
466 ...told(),
467 "",
468 `The upstream tip is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
469 `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.`,
470 `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.`,
471 "3. Make sure the tests pass, then push. Never force-push.",
472 "",
473 `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}\`.`,
474 );
475 return out.join("\n");
476 }
454477 out.push(
455478 `This repository follows ${parent}, and both have moved. Issue #${issue.number}: ${issue.title}`,
456479 "",
457480 ...told(),
458481 "",
459 `The parent's \`${pbranch}\` is staged here at \`refs/following/${pbranch}\`. On the branch \`${input.branch}\`:`,
460 `1. \`git fetch origin refs/following/${pbranch} && git merge FETCH_HEAD\``,
482 `The parent's \`${pbranch}\` is staged here at \`${staged}\`. On the branch \`${input.branch}\`:`,
483 `1. \`git fetch origin ${staged} && git merge FETCH_HEAD\``,
461484 `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.`,
462485 "3. Make sure the tests pass, then push.",
463486 "",
src/crew/runner.ts +7 −1
@@ -42,6 +42,7 @@ import {
4242 type Issue,
4343 } from "../core/issues.ts";
4444 import { refreshPullHead } from "../core/following.ts";
45 import { UPSTREAM_TITLE, upstreamFollowing } from "../actions/upstream_follow.ts";
4546 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
4647 import {
4748 canWrite,
@@ -990,13 +991,18 @@ async function work(
990991 conflictFiles:
991992 reason === "conflict" || reason === "converge"
992993 ? run.summary
993 .replace(/^(main|parent) moved: /, "")
994 .replace(/^(main|parent|upstream) moved: /, "")
994995 .split(", ")
995996 .filter((f) => f !== "")
996997 : undefined,
997998 following:
998999 reason === "converge"
9991000 ? (() => {
1001 // An outside upstream's new commits, staged here (#3442).
1002 if (issue.title.startsWith(UPSTREAM_TITLE)) {
1003 const upstream = upstreamFollowing(app, repo.id);
1004 if (upstream !== undefined) return upstream;
1005 }
10001006 // Only a parent the agent may read is put in its brief.
10011007 const parent = forkParentFor(app.db, repo, agent.user);
10021008 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 { goldenPath } from "../apps/golden_path.ts";
1219 import { upstreamPayload } from "../spawn/upstream.ts";
1320 import { setRole } from "../actions/roles.ts";
@@ -2319,6 +2326,52 @@ export function apiRoutes(router: Router<Handler>): void {
23192326 : notFound();
23202327 });
23212328
2329 // Following an outside upstream (#3442): read, set, and check now.
2330 router.add("GET", "/api/v1/repos/:owner/:name/upstream", (ctx) => {
2331 const repo = loadRepo(ctx);
2332 if (!repo) return notFound();
2333 const follow = followShown(ctx.app, repo, ctx.auth.user);
2334 if (follow === undefined) return json({ following: null });
2335 // Why a check failed is the remote's own stderr: a writer's to read.
2336 const shown = followJson(follow);
2337 return json({
2338 following: canWrite(ctx.app.db, repo, ctx.auth.user) ? shown : { ...shown, error: null },
2339 });
2340 });
2341
2342 router.add("PUT", "/api/v1/repos/:owner/:name/upstream", async (ctx) => {
2343 const denied = requireScope(ctx, "admin");
2344 if (denied) return denied;
2345 const repo = loadRepo(ctx);
2346 if (!repo) return notFound();
2347 const input = await body(ctx.request);
2348 if (typeof input.enabled !== "boolean")
2349 return apiError("bad_enabled", 422, "enabled is true or false");
2350 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
2351 url: str(input.url),
2352 branch: str(input.branch),
2353 enabled: input.enabled,
2354 });
2355 if (!saved.ok)
2356 return saved.error === "unauthorized" || saved.error === "forbidden" || saved.error === "not_found"
2357 ? respondAccess(saved.error, 422)
2358 : apiError(saved.error, 422, FOLLOW_REFUSALS[saved.error]);
2359 return json({ following: followJson(saved.value) });
2360 });
2361
2362 router.add("POST", "/api/v1/repos/:owner/:name/upstream/check", async (ctx) => {
2363 const denied = requireScope(ctx, "rw");
2364 if (denied) return denied;
2365 const repo = loadRepo(ctx);
2366 if (!repo) return notFound();
2367 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
2368 if (!checked.ok)
2369 return checked.error === "unauthorized" || checked.error === "forbidden" || checked.error === "not_found"
2370 ? respondAccess(checked.error, 422)
2371 : apiError(checked.error, checked.error === "busy" ? 409 : 422, FOLLOW_REFUSALS[checked.error]);
2372 return json(checked.value);
2373 });
2374
23222375 router.add("PATCH", "/api/v1/repos/:owner/:name", async (ctx) => {
23232376 const denied = requireScope(ctx, "admin");
23242377 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";
@@ -1402,6 +1406,8 @@ export function buildRouter(): Router<Handler> {
14021406 );
14031407 router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage);
14041408 router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate);
1409 router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate);
1410 router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck);
14051411 router.add("GET", "/:owner/:name/settings/labels", labelsPage);
14061412 router.add("POST", "/:owner/:name/settings/labels", labelCreate);
14071413 router.add("POST", "/:owner/:name/settings/labels/:id", labelUpdate);
src/origins/git-mirror.ts +9 −3
@@ -57,17 +57,23 @@ export const MIRROR_UNRESOLVED = "the remote's host could not be resolved";
5757 * Vet the clone URL's host and return git's environment pinned to the
5858 * address that passed — or the one sentence that ends the sync.
5959 */
60 async function vettedEnv(
60 export async function vettedEnv(
6161 url: string,
6262 authEnv: Record<string, string>,
63 protocols?: string,
64 /** The host may resolve inside the network: the caller's own rule let it. */
65 allowPrivate = false,
6366 ): Promise<Result<Record<string, string>, GitMirrorError>> {
6467 const host = new URL(url).hostname;
65 const vetted = await vetHost(host, { ...outbound, trusted: trustedHosts() });
68 const vetted = await vetHost(host, {
69 ...outbound,
70 trusted: allowPrivate ? [...trustedHosts(), host] : trustedHosts(),
71 });
6672 if (!vetted.ok)
6773 return err({
6874 message: vetted.error === "refused" ? MIRROR_REFUSED : MIRROR_UNRESOLVED,
6975 });
70 return ok(remoteGitEnv(authEnv, pinFor(url, vetted.value[0]!)));
76 return ok(remoteGitEnv(authEnv, pinFor(url, vetted.value[0]!), protocols));
7177 }
7278
7379 export interface RefSnapshot {
src/tui/screens/about.ts +127 −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 { connectionsScreen, egressScreen } from "./egress.ts";
3647 import { forkOf, hostOf, liveOrigin, localRepo, sourceName } from "./where.ts";
3748
@@ -53,10 +64,17 @@ export function aboutScreen(
5364 let repo = localRepo(src);
5465 const may = (): boolean =>
5566 repo !== undefined && f.user !== undefined && canAdmin(f.db, repo, f.user);
67 // A writer may ask the upstream now, when following is on (#3442).
68 const mayCheck = (): boolean =>
69 repo !== undefined &&
70 f.user !== undefined &&
71 canWrite(f.db, repo, f.user) &&
72 followShown(f.app, repo, f.user)?.enabled === true;
5673 let cell: [string, string][] = [];
5774 const factRows = (): [string, string][] => [
5875 ...archivedRow(repo),
5976 ...aboutFacts(f, src, facts, ref),
77 ...followRow(f, repo),
6078 ...cell,
6179 ];
6280 let rows = factRows();
@@ -82,8 +100,58 @@ export function aboutScreen(
82100 });
83101 }
84102 const cloneUrl = rows.find(([label]) => label.startsWith("clone"))?.[1] ?? "";
85 return {
103 // An admin turns following on or off, or points it elsewhere (#3442):
104 // the page's `setFollowUpstream`, with the page's refusals.
105 const saveFollow = async (url: string, branch: string, enabled: boolean): Promise<void> => {
106 if (repo === undefined) return;
107 const saved = await setFollowUpstream(f.app, f.user, repo, { url, branch, enabled });
108 rows = factRows();
109 if (saved.ok)
110 ctx.toast(
111 saved.value.enabled
112 ? `following ${upstreamLabel(saved.value.url)} ${saved.value.branch}`
113 : "following the upstream is off",
114 "success",
115 );
116 else ctx.toast(FOLLOW_REFUSALS[saved.error], "danger");
117 ctx.invalidate();
118 };
119 const pointFollow = (enabled: boolean): void => {
120 const now = repo === undefined ? undefined : getFollow(f.db, repo.id);
121 ctx.push(
122 promptScreen(ctx, screen, {
123 title: "Follow an upstream",
124 label: "git address: https:// or http://",
125 value: now?.url ?? "",
126 onSubmit: (url) =>
127 url === ""
128 ? "An address to follow."
129 : later(ctx, () =>
130 promptScreen(ctx, screen, {
131 title: "Follow an upstream",
132 label: "its branch",
133 value: now?.branch ?? "main",
134 onSubmit: (branch) => saveFollow(url, branch, enabled),
135 }),
136 ),
137 }),
138 );
139 };
140 const screen: Screen = {
86141 title: "About",
142 // A check finishing, or following changing, redraws the row in place.
143 async load(signal) {
144 if (repo === undefined) return;
145 live(
146 f,
147 signal,
148 { repoId: repo.id, kinds: ["repo.upstream_checked", "repo.upstream_follow"] },
149 () => {
150 rows = factRows();
151 ctx.invalidate();
152 },
153 );
154 },
87155 get keys() {
88156 return [
89157 binding(["y"], "copy the clone URL", { disabled: cloneUrl === "" }),
@@ -96,6 +164,18 @@ export function aboutScreen(
96164 ),
97165 ]
98166 : []),
167 ...(mayCheck() ? [binding(["u"], "check upstream now")] : []),
168 ...(may()
169 ? [
170 binding(
171 ["f"],
172 repo !== undefined && getFollow(f.db, repo.id)?.enabled === true
173 ? "stop following upstream"
174 : "follow upstream",
175 ),
176 binding(["F"], "point following elsewhere"),
177 ]
178 : []),
99179 // A site admin also reaches the repository's private egress grants.
100180 ...(f.user?.isAdmin === true && repo !== undefined
101181 ? [binding(["e"], "egress"), binding(["c"], "connections")]
@@ -205,6 +285,26 @@ export function aboutScreen(
205285 });
206286 return true;
207287 }
288 if (e.key === "u" && repo !== undefined && mayCheck()) {
289 ctx.toast("checking the upstream…");
290 void checkUpstreamNow(f.app, f.user, repo).then((checked) => {
291 rows = factRows();
292 if (checked.ok) ctx.toast(checkedWords(checked.value), "success");
293 else ctx.toast(FOLLOW_REFUSALS[checked.error], "danger");
294 ctx.invalidate();
295 });
296 return true;
297 }
298 if (e.key === "f" && repo !== undefined && may()) {
299 const now = getFollow(f.db, repo.id);
300 if (now === undefined) pointFollow(true);
301 else void saveFollow(now.url, now.branch, !now.enabled);
302 return true;
303 }
304 if (e.key === "F" && repo !== undefined && may()) {
305 pointFollow(getFollow(f.db, repo.id)?.enabled ?? true);
306 return true;
307 }
208308 if (e.key === "e" && repo !== undefined && f.user?.isAdmin === true) {
209309 ctx.push(egressScreen(f, ctx, repo));
210310 return true;
@@ -220,6 +320,30 @@ export function aboutScreen(
220320 return true;
221321 },
222322 };
323 return screen;
324 }
325
326 /**
327 * What the repository follows, the About line's words (`followingLine`):
328 * shown when on, or to an admin when off.
329 */
330 function followRow(f: Session, repo: Repo | undefined): [string, string][] {
331 if (repo === undefined) return [];
332 const follow = followShown(f.app, repo, f.user);
333 if (follow === undefined) return [];
334 // Two rows: the card is at most 72 wide, and an address plus where it
335 // stands is more than one row of it holds.
336 const where = [
337 standing(follow, f.user !== undefined && canWrite(f.db, repo, f.user)),
338 ...(follow.checkedAt === null ? [] : [`last checked ${clockWords(follow.checkedAt)}`]),
339 ];
340 return [
341 [
342 "following",
343 follow.url === "" ? "a private upstream" : `${upstreamLabel(follow.url)} ${follow.branch}`,
344 ],
345 ...wrap(where.join(" · "), 50).map((line): [string, string] => ["", line]),
346 ];
223347 }
224348
225349 /** 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
@@ -118,6 +118,7 @@ import { proposalTokensSection } from "./proposal-tokens.ts";
118118 import { secretsSection } from "./secrets.ts";
119119 import { checkMemoryAt } from "../../apps/check-memory.ts";
120120 import { saveGrants } from "./subscriptions.ts";
121 import { followUpstreamCard } from "./upstream-follow.ts";
121122
122123 type Section =
123124 | "general"
@@ -388,7 +389,7 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
388389 repo,
389390 "general",
390391 "Settings",
391 html`${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
392 html`${lead}${mirror ? html`<div class="mt">${mirror}</div>` : null}<div class="mt">${body}</div><div class="mt">${followUpstreamCard(ctx, repo)}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
392393 ? html`<div class="mt">${proposals}</div>`
393394 : null}${secrets
394395 ? html`<div class="mt">${secrets}</div>`
src/web/pages/upstream-follow.ts added +164
@@ -0,0 +1,164 @@
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`).
43 */
44 export function followingLine(ctx: Ctx, repo: Repo): Html | null {
45 const follow = followShown(ctx.app, repo, ctx.auth.user);
46 if (follow === undefined) return null;
47 const writer = canWrite(ctx.app.db, repo, ctx.auth.user);
48 const pending =
49 follow.pendingId === null ? undefined : getIssueById(ctx.app.db, follow.pendingId);
50 const open = pending !== undefined && pending.state === "open" ? pending : undefined;
51 const label = upstreamLabel(follow.url);
52 return html`<p class="mt small muted" data-following-upstream>
53 ${icon("sync")} Following
54 ${
55 follow.url === ""
56 ? html`a private upstream`
57 : html`<a href="${follow.url}" rel="noreferrer noopener">${label}</a>
58 <span class="mono">${follow.branch}</span>`
59 }
60 ${follow.checkedAt === null ? null : html`· last checked ${clock(follow.checkedAt)}`}
61 · ${standing(follow, writer)}${when(
62 open,
63 (i) =>
64 html` · <a href="${repoBase(repo)}/${i.kind === "pull" ? "pulls" : "issues"}/${i.number}"
65 >#${i.number}</a
66 >`,
67 )}
68 </p>`;
69 }
70
71 /** The settings card: on or off, the URL and branch, and "Check upstream now". */
72 export function followUpstreamCard(ctx: Ctx, repo: Repo): Html {
73 const follow = getFollow(ctx.app.db, repo.id);
74 const base = repoBase(repo);
75 const parent = follow?.parentUrl ?? "";
76 return card(
77 html`<form method="post" action="${base}/settings/upstream">
78 <p class="muted">
79 New upstream commits arrive as a pull or, on a conflict, an issue for the crew; never a push to
80 <span class="mono">${repo.defaultBranch}</span>.
81 </p>
82 ${formField({
83 label: "Upstream git URL",
84 name: "url",
85 value: follow?.url ?? "",
86 placeholder: "https://github.com/owner/name.git",
87 mono: true,
88 spellcheck: false,
89 hint:
90 parent === ""
91 ? "A public upstream needs no credential; a private one uses your connected origin on its host."
92 : `Its own upstream is ${upstreamLabel(parent)} — paste ${parent} to follow that instead.`,
93 })}
94 ${formField({
95 label: "Branch",
96 name: "branch",
97 value: follow?.branch ?? "main",
98 mono: true,
99 spellcheck: false,
100 })}
101 <div class="field">
102 <label class="check">
103 <input type="checkbox" name="enabled" ${follow?.enabled === true ? html`checked` : null} />
104 <span>Follow upstream</span>
105 </label>
106 </div>
107 ${when(
108 follow,
109 (f) => html`<p class="hint" data-following-standing>${standing(f, true)}${
110 f.checkedAt === null ? "" : html` · last checked ${clock(f.checkedAt)}`
111 } · ${f.opened} proposed so far</p>`,
112 )}
113 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
114 </form>
115 ${when(
116 follow?.enabled === true,
117 () => html`<form method="post" action="${base}/settings/upstream/check" class="mt">
118 ${btn("Check upstream now", { size: "sm", icon: "sync" })}
119 </form>`,
120 )}`,
121 { head: html`${icon("sync")}<h2 id="upstream">Follow upstream</h2>` },
122 );
123 }
124
125 // POST /:owner/:name/settings/upstream
126 export async function followUpstreamUpdate(ctx: Ctx): Promise<Response> {
127 const repo = loadRepo(ctx);
128 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
129 const form = await readForm(ctx, "admin");
130 if (form instanceof Response) return form;
131 const to = `${repoBase(repo)}/settings#upstream`;
132 const saved = await setFollowUpstream(ctx.app, ctx.auth.user, repo, {
133 url: field(form, "url"),
134 branch: field(form, "branch"),
135 enabled: form.get("enabled") !== null,
136 });
137 return flashTo(
138 ctx,
139 to,
140 saved.ok
141 ? {
142 message: saved.value.enabled
143 ? `Following ${upstreamLabel(saved.value.url)} ${saved.value.branch}. The first check runs within a minute.`
144 : "Following the upstream is off. Nothing is checked or proposed.",
145 }
146 : { tone: "danger", message: FOLLOW_REFUSALS[saved.error] },
147 );
148 }
149
150 // POST /:owner/:name/settings/upstream/check
151 export async function followUpstreamCheck(ctx: Ctx): Promise<Response> {
152 const repo = loadRepo(ctx);
153 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
154 const form = await readForm(ctx, "rw");
155 if (form instanceof Response) return form;
156 const checked = await checkUpstreamNow(ctx.app, ctx.auth.user, repo);
157 return flashTo(
158 ctx,
159 `${repoBase(repo)}/settings#upstream`,
160 checked.ok
161 ? { message: checkedWords(checked.value) }
162 : { tone: "danger", message: FOLLOW_REFUSALS[checked.error] },
163 );
164 }
test/migrate.test.ts +4
@@ -48,6 +48,7 @@ import { serve, type Servers } from "../src/http/server.ts";
4848 import { createToken } from "../src/core/tokens.ts";
4949 import { createSession } from "../src/core/sessions.ts";
5050 import { advance, createJob, settled } from "../src/origins/jobs.ts";
51 import { getFollow } from "../src/core/upstream_follow.ts";
5152 import { forgetProviders } from "../src/origins/providers/index.ts";
5253 import {
5354 newFakeOAuth,
@@ -468,6 +469,9 @@ describe("migrate", () => {
468469 ]);
469470 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
470471 expect(repo.autonomy).toBe(autonomous ? "autonomous" : "off");
472 // The source is the upstream it follows: on when autonomous (#3442).
473 const follow = getFollow(app.db, repo.id)!;
474 expect([follow.url, follow.branch, follow.enabled]).toEqual([fixtureUrl, "trunk", autonomous]);
471475
472476 const issues = listIssues(app.db, repo.id, {
473477 kind: "issue",
test/tui-upstream-follow.test.ts added +262
@@ -0,0 +1,262 @@
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 private upstream's address is the admins': a guest's About row has the standing without it", async () => {
174 const was = getFollow(forge.db, beacon.id)!.originId;
175 forge.db.query("UPDATE repo_upstream SET origin_id = 'an-origin' WHERE repo_id = ?1").run(beacon.id);
176 const guest = boot(asGuest);
177 try {
178 await openAbout(guest);
179 expect(guest.text()).toContain("a private upstream");
180 expect(guest.text()).not.toContain("127.0.0.1");
181 expect(guest.text()).not.toContain("alice/up");
182 } finally {
183 guest.app.stop();
184 forge.db.query("UPDATE repo_upstream SET origin_id = ?2 WHERE repo_id = ?1").run(beacon.id, was);
185 }
186 const admin = boot(asAlice());
187 try {
188 await settleApp(admin.app);
189 await openAbout(admin);
190 expect(admin.text()).toMatch(/following +127\.0\.0\.1:\d+\/alice\/up/);
191 } finally {
192 admin.app.stop();
193 }
194 });
195
196 test("a check finished elsewhere redraws the row in place", async () => {
197 await commit(up, "more.txt");
198 const h = boot(asAlice());
199 try {
200 await openAbout(h);
201 expect(h.text()).not.toContain("2 behind");
202 expect((await checkUpstream(forge, fresh())).ok).toBe(true);
203 await settleUntil(h.app, "2 behind");
204 expect(h.text()).toMatch(/2 behind · last checked \d\d:\d\d UTC/);
205 } finally {
206 h.app.stop();
207 }
208 });
209
210 test("an admin's `f` turns following off and on; `F` points it elsewhere, with the page's refusals", async () => {
211 const h = boot(asAlice());
212 try {
213 await openAbout(h);
214 expect(h.text()).toContain("stop following upstream");
215 await h.press("f");
216 await settleUntil(h.app, "following the upstream is off");
217 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(false);
218 await h.press("f");
219 await settleUntil(h.app, "following 127.0.0.1");
220 expect(getFollow(forge.db, beacon.id)!.enabled).toBe(true);
221
222 // An address git must never be handed: refused, nothing changes.
223 const clear = Array.from({ length: upUrl.length + 5 }, () => "backspace");
224 await h.press("F");
225 await settleUntil(h.app, "git address");
226 await h.press(...clear, ..."file:///etc", "enter");
227 await settleUntil(h.app, "its branch");
228 await h.press("enter");
229 await settleUntil(h.app, "That is not a git address");
230 expect(getFollow(forge.db, beacon.id)!.url).toBe(upUrl);
231
232 // Elsewhere: the same address, another branch.
233 await h.press("F");
234 await settleUntil(h.app, "git address");
235 await h.press("enter");
236 await settleUntil(h.app, "its branch");
237 await h.press("backspace", "backspace", "backspace", "backspace", ..."dev", "enter");
238 await settleUntil(h.app, "following 127.0.0.1");
239 const now = getFollow(forge.db, beacon.id)!;
240 expect([now.url, now.branch, now.enabled]).toEqual([upUrl, "dev", true]);
241 } finally {
242 h.app.stop();
243 }
244 });
245
246 test("a guest is not offered `f` or `F`, and pressing them changes nothing", async () => {
247 const before = getFollow(forge.db, beacon.id)!;
248 const h = boot(asGuest);
249 try {
250 await openAbout(h);
251 expect(h.text()).not.toContain("following upstream");
252 expect(h.text()).not.toContain("point following elsewhere");
253 await h.press("f");
254 await h.press("F");
255 expect(h.text()).not.toContain("git address");
256 const after = getFollow(forge.db, beacon.id)!;
257 expect([after.enabled, after.url, after.branch]).toEqual([before.enabled, before.url, before.branch]);
258 } finally {
259 h.app.stop();
260 }
261 });
262 });
test/upstream_follow.test.ts added +666
@@ -0,0 +1,666 @@
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 { audienceFilter } from "../src/core/event_audience.ts";
37 import { createOrigin } from "../src/core/origins.ts";
38 import { getFollow, putFollow } from "../src/core/upstream_follow.ts";
39 import { provideMirrorOutboundForTest, vettedEnv } from "../src/origins/git-mirror.ts";
40 import { createUser, type User } from "../src/core/users.ts";
41 import { taskPrompt, type TaskInput } from "../src/crew/brief.ts";
42 import { runGit } from "../src/git/env.ts";
43 import { aheadCount, resolveOid } from "../src/git/merge.ts";
44 import { repoDir } from "../src/git/repos.ts";
45 import { serve, type Servers } from "../src/http/server.ts";
46 import { promote } from "./helpers/members.ts";
47
48 let dataDir: string;
49 let app: App;
50 let servers: Servers;
51 let alice: User;
52 let bob: User;
53 let up: Repo;
54 let ours: Repo;
55 let upUrl: string;
56
57 const fresh = () => getRepoById(app.db, ours.id)!;
58 const ourDir = () => repoDir(app.reposRoot, "alice", "ours");
59 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
60 if (!r.ok) throw new Error(JSON.stringify(r.error));
61 return r.value;
62 };
63 const commit = async (repo: Repo, path: string, content: string, message = path) =>
64 must(
65 await commitToBranch(app, alice, repo, {
66 branch: "main",
67 message,
68 files: [{ path, content }],
69 }),
70 );
71 const behind = async () => {
72 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
73 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
74 return aheadCount(ourDir(), main, staged);
75 };
76 /**
77 * The landing gate lands it, as it would on its own: the repository runs
78 * autonomous, the head's check is green, the sweep picks the strategy.
79 * Upstream's tip is an ancestor of main afterwards — a squash would leave
80 * it out, and the next check would count the same commits again.
81 */
82 const landThroughGate = async (number: number) => {
83 app.db
84 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
85 .run(ours.id, alice.id);
86 const pull = getPull(app.db, ours.id, number)!;
87 const check = createRun(app.db, {
88 repoId: ours.id,
89 kind: "check",
90 issueId: pull.id,
91 env: `pull-${pull.number}`,
92 commitOid: pull.headOid,
93 reason: "pull",
94 });
95 claimRun(app.db, check.id);
96 finishRun(app.db, check.id, { state: "ok", summary: "check passed" });
97 expect(await sweepGreen(app, fresh())).toBe(1);
98 const landed = getPull(app.db, ours.id, number)!;
99 expect(landed.mergedOid).not.toBeNull();
100 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
101 expect(landed.mergedOid).toBe(main);
102 const staged = (await resolveOid(ourDir(), stagedRef("main")))!;
103 expect((await runGit(["merge-base", "--is-ancestor", staged, main], { cwd: ourDir() })).ok).toBe(true);
104 expect(await behind()).toBe(0);
105 };
106 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
107
108 beforeAll(async () => {
109 dataDir = await mkdtemp(join(tmpdir(), "forge-upstream-follow-"));
110 app = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
111 servers = await serve(app);
112 const person = async (username: string, adminIfFirst = false) =>
113 must(
114 await createUser(app.db, {
115 origin: "seed",
116 trusted: true,
117 username,
118 email: `${username}@forge.test`,
119 adminIfFirst,
120 }),
121 );
122 alice = await person("alice", true);
123 bob = await person("bob");
124 up = must(await createRepo(app, alice, { name: "up", visibility: "public" }));
125 await commit(up, "README.md", "upstream\n");
126 await commit(up, "a.txt", "one\ntwo\nthree\n");
127 upUrl = `http://127.0.0.1:${servers.port}/alice/up.git`;
128
129 // Ours starts as upstream's history, then does its own work.
130 ours = must(await createRepo(app, alice, { name: "ours", visibility: "private" }));
131 const upDir = repoDir(app.reposRoot, "alice", "up");
132 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: ourDir() })).ok).toBe(true);
133 await commit(fresh(), "ours.txt", "our own work\n");
134
135 must(await createAgent(app, alice, { username: "mason" }));
136 expect(addToCrew(app, alice, fresh(), "mason").ok).toBe(true);
137 });
138
139 afterAll(async () => {
140 servers.stop();
141 app.db.close();
142 await rm(dataDir, { recursive: true, force: true });
143 });
144
145 describe("the setting", () => {
146 test("an address git must never be handed, or a branch that is not one, is refused", async () => {
147 for (const url of ["file:///etc", "-uhoh", "ext::sh -c id", "https://u:[email protected]/x.git"]) {
148 const r = await setFollowUpstream(app, alice, fresh(), { url, branch: "main", enabled: true });
149 expect(r.ok ? "saved" : r.error).toBe("invalid_url");
150 }
151 const r = await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "-x", enabled: true });
152 expect(r.ok ? "saved" : r.error).toBe("invalid_branch");
153 expect(getFollow(app.db, ours.id)).toBeUndefined();
154 });
155
156 test("a host inside the network is refused unless the forge says it is fine", async () => {
157 const config = app.config as { migrateFromPrivateHosts?: boolean };
158 config.migrateFromPrivateHosts = false;
159 try {
160 // bob is no forge admin: the check is his, on his own repository.
161 promote(app.db, bob);
162 const bobs = must(await createRepo(app, bob, { name: "bobs", visibility: "private" }));
163 const r = await setFollowUpstream(app, bob, bobs, { url: upUrl, branch: "main", enabled: true });
164 expect(r.ok ? "saved" : r.error).toBe("private_host");
165 expect(getFollow(app.db, bobs.id)).toBeUndefined();
166 } finally {
167 config.migrateFromPrivateHosts = true;
168 }
169 });
170
171 test("turning it off is never refused, even when the host now resolves inside the network", async () => {
172 const config = app.config as { migrateFromPrivateHosts?: boolean };
173 promote(app.db, bob);
174 const mine = must(await createRepo(app, bob, { name: "offable", visibility: "private" }));
175 must(await setFollowUpstream(app, bob, mine, { url: upUrl, branch: "main", enabled: true }));
176 config.migrateFromPrivateHosts = false;
177 try {
178 const on = await setFollowUpstream(app, bob, mine, { url: upUrl, branch: "main", enabled: true });
179 expect(on.ok ? "saved" : on.error).toBe("private_host");
180 const off = await setFollowUpstream(app, bob, mine, { url: upUrl, branch: "main", enabled: false });
181 expect(off.ok ? "saved" : off.error).toBe("saved");
182 expect(getFollow(app.db, mine.id)?.enabled).toBe(false);
183 } finally {
184 config.migrateFromPrivateHosts = true;
185 }
186 });
187
188 test("only an admin turns it on", async () => {
189 const r = await setFollowUpstream(app, bob, fresh(), { url: upUrl, branch: "main", enabled: true });
190 expect(r.ok ? "saved" : r.error).toBe("not_found");
191 });
192 });
193
194 describe("following", () => {
195 test("off: nothing is checked and nothing is proposed", async () => {
196 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: false }));
197 await commit(up, "b.txt", "b\n");
198 const r = await checkUpstream(app, fresh());
199 expect(r.ok ? r.value.kind : r.error).toBe("off");
200 expect(followTick(app)).toBe(0);
201 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(0);
202 expect(await resolveOid(ourDir(), stagedRef("main"))).toBeUndefined();
203 });
204
205 test("two clean upstream commits open one pull, which lands as a merge; the next check is up to date", async () => {
206 await commit(up, "c.txt", "c\n");
207 must(await setFollowUpstream(app, alice, fresh(), { url: upUrl, branch: "main", enabled: true }));
208 const r = must(await checkUpstream(app, fresh()));
209 expect(r.kind).toBe("pull");
210 if (r.kind !== "pull") return;
211 expect(r.behind).toBe(2);
212 const pull = getPull(app.db, ours.id, r.number)!;
213 expect(pull.title).toMatch(
214 new RegExp(`^Upstream: 2 commits from 127\\.0\\.0\\.1:${servers.port}/alice/up \\([0-9a-f]{7}\\.\\.[0-9a-f]{7}\\)$`),
215 );
216 expect(pull.authorId).toBe(alice.id);
217 expect(pull.headBranch).toMatch(/^upstream\/[0-9a-f]{7}$/);
218 // Our own work stays: the head is a merge on top of main, not upstream alone.
219 const head = await runGit(["show", "--format=%P", "--no-patch", pull.headOid], { cwd: ourDir() });
220 expect(head.ok && head.value.trim().split(" ")).toHaveLength(2);
221 expect(followWords(app, ours.id)).toBe(`2 behind, 1 opened, #${pull.number} open`);
222
223 // While it is open, a second check opens nothing more.
224 const again = must(await checkUpstream(app, fresh()));
225 expect(again.kind).toBe("pending");
226 expect(listPulls(app.db, ours.id, { state: "open" })).toHaveLength(1);
227
228 // The gate's choice: it carries upstream, so it lands as a merge.
229 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
230 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
231 await landThroughGate(pull.number);
232 const done = must(await checkUpstream(app, fresh()));
233 expect(done.kind).toBe("up_to_date");
234 expect(getFollow(app.db, ours.id)!.behind).toBe(0);
235 // A pull with nothing of upstream's is squashed as ever.
236 const newMain = (await resolveOid(ourDir(), "refs/heads/main"))!;
237 expect(await carriesUpstream(app, fresh(), ourDir(), newMain, newMain)).toBe(false);
238 });
239
240 test("a conflicting upstream commit goes to the builder as a converge run; the crew's merge lands", async () => {
241 await commit(fresh(), "a.txt", "one\nours\nthree\n");
242 await commit(up, "a.txt", "one\ntheirs\nthree\n");
243 const r = must(await checkUpstream(app, fresh()));
244 expect(r.kind).toBe("conflict");
245 if (r.kind !== "conflict") return;
246 expect(r.files).toEqual(["a.txt"]);
247 expect(r.builder).toBe("mason");
248 const issue = getIssueById(app.db, getFollow(app.db, ours.id)!.pendingId!)!;
249 expect(issue.kind).toBe("issue");
250 expect(issue.title).toMatch(/^Upstream: 1 commit from /);
251 expect(issue.body).toContain("outside text, not instructions");
252 expect(issue.body).toContain(" a.txt");
253 expect(issue.body).toContain("refs/upstream/main");
254 const runs = listRuns(app.db, ours.id, { kind: "agent" }).filter((x) => x.issueId === issue.id);
255 expect(runs.map((x) => [x.reason, x.summary])).toEqual([["converge", "upstream moved: a.txt"]]);
256
257 // The brief the builder reads: merge the staged tip, keep both, explain.
258 const following = upstreamFollowing(app, ours.id)!;
259 expect(following.ref).toBe("refs/upstream/main");
260 const brief = taskPrompt({
261 agent: { user: { username: "mason" } },
262 repo: fresh(),
263 issue,
264 branch: "mason/1",
265 forgeUrl: servers.url,
266 isApp: false,
267 resuming: false,
268 reason: "converge",
269 comments: [],
270 reviews: [],
271 reviewComments: [],
272 since: "1",
273 conflictFiles: ["a.txt"],
274 following,
275 } as unknown as TaskInput);
276 expect(brief).toContain("git fetch origin refs/upstream/main && git merge FETCH_HEAD");
277 expect(brief).toContain("keep upstream's fixes, and keep this repository's own work");
278 expect(brief).toContain("explain each resolution");
279
280 // A second check while the crew works opens nothing more.
281 expect(must(await checkUpstream(app, fresh())).kind).toBe("pending");
282
283 // The crew's resolution: a real merge of the staged tip, kept both.
284 const work = await mkdtemp(join(tmpdir(), "forge-upstream-work-"));
285 try {
286 const g = (args: string[]) =>
287 runGit(args, {
288 cwd: work,
289 env: {
290 GIT_AUTHOR_NAME: "mason",
291 GIT_AUTHOR_EMAIL: "[email protected]",
292 GIT_COMMITTER_NAME: "mason",
293 GIT_COMMITTER_EMAIL: "[email protected]",
294 },
295 });
296 expect((await g(["clone", "--quiet", ourDir(), "."])).ok).toBe(true);
297 expect((await g(["fetch", "--quiet", "origin", "refs/upstream/main"])).ok).toBe(true);
298 expect((await g(["merge", "--no-edit", "FETCH_HEAD"])).ok).toBe(false);
299 await Bun.write(join(work, "a.txt"), "one\nours\ntheirs\nthree\n");
300 expect((await g(["commit", "--quiet", "-am", "Merge upstream, both lines kept"])).ok).toBe(true);
301 // As the agent's push would, without a hook: the branch arrives.
302 expect(
303 (await runGit(["fetch", "--quiet", work, "HEAD:refs/heads/mason/resolve"], { cwd: ourDir() })).ok,
304 ).toBe(true);
305 } finally {
306 await rm(work, { recursive: true, force: true });
307 }
308 const pull = must(
309 await openPull(app, alice, fresh(), {
310 title: "Take upstream",
311 body: `Closes #${issue.number}`,
312 baseBranch: "main",
313 headBranch: "mason/resolve",
314 }),
315 );
316 const main = (await resolveOid(ourDir(), "refs/heads/main"))!;
317 expect(await carriesUpstream(app, fresh(), ourDir(), pull.headOid, main)).toBe(true);
318 await landThroughGate(pull.number);
319 expect(must(await checkUpstream(app, fresh())).kind).toBe("up_to_date");
320 });
321
322 test("a proposal closed unlanded is not opened again until upstream moves, unless a person asks", async () => {
323 await commit(up, "d.txt", "d\n");
324 const r = must(await checkUpstream(app, fresh()));
325 expect(r.kind).toBe("pull");
326 if (r.kind !== "pull") return;
327 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(getPull(app.db, ours.id, r.number)!.id);
328 expect(must(await checkUpstream(app, fresh())).kind).toBe("declined");
329 const asked = must(await checkUpstream(app, fresh(), true));
330 expect(asked.kind).toBe("pull");
331 });
332 });
333
334 describe("the doors", () => {
335 test("the About card says what it follows, how far behind, and when it last looked", async () => {
336 const page = await (await fetch(`${servers.url}/alice/ours`, { headers: { cookie: cookie(alice) } })).text();
337 expect(page).toContain("data-following-upstream");
338 expect(page).toMatch(/Following\s*<a href="http:\/\/127\.0\.0\.1:\d+\/alice\/up\.git"/);
339 expect(page).toMatch(/last checked\s*<time[^>]*>\d\d:\d\d UTC<\/time/);
340 expect(page).toContain("1 behind");
341 });
342
343 test("the settings card shows it; a cross-origin save is refused and changes nothing", async () => {
344 const settings = await (await fetch(`${servers.url}/alice/ours/settings`, { headers: { cookie: cookie(alice) } })).text();
345 expect(settings).toContain("Follow upstream");
346 expect(settings).toContain("Check upstream now");
347 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
348 method: "POST",
349 redirect: "manual",
350 headers: {
351 cookie: cookie(alice),
352 origin: "https://evil.example",
353 "content-type": "application/x-www-form-urlencoded",
354 },
355 body: new URLSearchParams({ url: upUrl, branch: "main" }),
356 });
357 expect(res.status).toBeGreaterThanOrEqual(400);
358 expect(getFollow(app.db, ours.id)!.enabled).toBe(true);
359 });
360
361 test("the settings form turns it off, same-origin", async () => {
362 const res = await fetch(`${servers.url}/alice/ours/settings/upstream`, {
363 method: "POST",
364 redirect: "manual",
365 headers: {
366 cookie: cookie(alice),
367 origin: servers.url,
368 "content-type": "application/x-www-form-urlencoded",
369 },
370 body: new URLSearchParams({ url: upUrl, branch: "main" }),
371 });
372 expect(res.status).toBe(303);
373 expect(getFollow(app.db, ours.id)!.enabled).toBe(false);
374 const r = await checkUpstream(app, fresh());
375 expect(r.ok ? r.value.kind : r.error).toBe("off");
376 });
377
378 test("the API reads it, an admin sets it, and a reader sees nothing of an off one", async () => {
379 const admin = createToken(app.db, alice.id, "t", "admin").token;
380 const put = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
381 method: "PUT",
382 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
383 body: JSON.stringify({ url: upUrl, branch: "main", enabled: true }),
384 });
385 expect(put.status).toBe(200);
386 const got = (await (
387 await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, { headers: { authorization: `Bearer ${admin}` } })
388 ).json()) as { following: { url: string; enabled: boolean; originId?: string } };
389 expect(got.following.url).toBe(upUrl);
390 expect(got.following.enabled).toBe(true);
391 expect("originId" in got.following).toBe(false);
392 const bad = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream`, {
393 method: "PUT",
394 headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" },
395 body: JSON.stringify({ url: "file:///etc/passwd", branch: "main", enabled: true }),
396 });
397 expect(bad.status).toBe(422);
398 expect(((await bad.json()) as { error: string }).error).toBe("invalid_url");
399 const ro = createToken(app.db, alice.id, "r", "ro").token;
400 const refused = await fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
outdated

Nit. This test's name still says the upstream is "named, not linked, when it is not a web address". That path was removed with the dead git:// branch, and the body now tests only that check errors are for writers. Rename it, e.g. "why a check failed is a writer's to read".

401 method: "POST",
402 headers: { authorization: `Bearer ${ro}` },
403 });
404 expect(refused.status).toBe(403);
405 });
406
407 test("a git:// upstream cannot be saved, by an admin or anyone: its transport escapes the pin", async () => {
408 for (const who of [alice, bob]) {
409 const r = await setFollowUpstream(app, who, who === alice ? fresh() : must(await createRepo(app, bob, { name: `g${who.id.slice(-4)}`, visibility: "private" })), {
410 url: "git://rebind.example:6379/x.git",
411 branch: "main",
412 enabled: true,
413 });
414 expect(r.ok ? "saved" : r.error).toBe("invalid_url");
415 }
416 });
417
418 test("an upstream is named, not linked, when it is not a web address; why a check failed is a writer's to read", async () => {
419 const pub = must(await createRepo(app, alice, { name: "pub", visibility: "public" }));
420 await commit(pub, "README.md", "pub\n");
421 must(
422 await setFollowUpstream(app, alice, pub, {
423 url: upUrl,
424 branch: "main",
425 enabled: true,
426 }),
427 );
428 app.db
429 .query("UPDATE repo_upstream SET checked_at = ?2, error = 'fatal: remote words' WHERE repo_id = ?1")
430 .run(pub.id, new Date().toISOString());
431 const page = await (await fetch(`${servers.url}/alice/pub`)).text();
432 expect(page).toContain("data-following-upstream");
433 expect(page).toContain("the last check did not finish");
434 expect(page).not.toContain("remote words");
435 const anon = (await (await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`)).json()) as {
436 following: { error: string | null };
437 };
438 expect(anon.following.error).toBeNull();
439 const ro = createToken(app.db, alice.id, "ro2", "ro").token;
440 const own = (await (
441 await fetch(`${servers.url}/api/v1/repos/alice/pub/upstream`, { headers: { authorization: `Bearer ${ro}` } })
442 ).json()) as { following: { error: string | null } };
443 expect(own.following.error).toBe("fatal: remote words");
444 });
445 });
446
447 describe("one check at a time", () => {
448 test("two checks at once open exactly one pull: the second is refused busy, and only the first is heard", async () => {
449 const twice = must(await createRepo(app, alice, { name: "twice", visibility: "private" }));
450 const dir = repoDir(app.reposRoot, "alice", "twice");
451 const upDir = repoDir(app.reposRoot, "alice", "up");
452 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
453 const at = getRepoById(app.db, twice.id)!;
454 await commit(at, "twice.txt", "our own work\n");
455 must(await setFollowUpstream(app, alice, at, { url: upUrl, branch: "main", enabled: true }));
456 await commit(up, "e.txt", "e\n");
457 const heard: string[] = [];
458 const off = app.bus.subscribe((e) => {
459 if (e.repoId === twice.id) heard.push(e.kind);
460 });
461 try {
462 // A double click: both start before either has read "no proposal open".
463 const both = await Promise.all([
464 checkUpstreamNow(app, alice, at),
465 checkUpstreamNow(app, alice, at),
466 ]);
467 expect(both.map((r) => (r.ok ? r.value.kind : r.error)).sort()).toEqual(["busy", "pull"]);
468 expect(
469 listPulls(app.db, twice.id, { state: "open" }).filter((p) => p.title.startsWith("Upstream: ")),
470 ).toHaveLength(1);
471 expect(heard.filter((k) => k === "repo.upstream_checked")).toHaveLength(1);
472 // The claim is let go: the next check answers, and opens nothing more.
473 expect(must(await checkUpstreamNow(app, alice, at)).kind).toBe("pending");
474 expect(listPulls(app.db, twice.id, { state: "open" })).toHaveLength(1);
475 } finally {
476 off();
477 }
478 });
479
480 test("the API answers a check already running with 409 busy", async () => {
481 const at = getRepoById(app.db, ours.id)!;
482 const rw = createToken(app.db, alice.id, "rw-busy", "rw").token;
483 const post = () =>
484 fetch(`${servers.url}/api/v1/repos/alice/ours/upstream/check`, {
485 method: "POST",
486 headers: { authorization: `Bearer ${rw}` },
487 });
488 const running = checkUpstream(app, at);
489 const res = await post();
490 await running;
491 expect(res.status).toBe(409);
492 expect(((await res.json()) as { error: string }).error).toBe("busy");
493 });
494 });
495
496 describe("a credential goes only to its exact https origin", () => {
497 const connect = (webUrl: string, login: string) =>
498 must(
499 createOrigin(app.db, app.config.dataDir, {
500 userId: alice.id,
501 kind: "forgejo",
502 apiUrl: `${webUrl}/api/v1`,
503 webUrl,
504 login,
505 token: "s3cret-token",
506 }),
507 );
508
509 test("the setting remembers an origin only for the same https scheme, host and port", async () => {
510 const o = connect("https://git.example.test", "cred-a");
511 const save = async (url: string) => {
512 must(await setFollowUpstream(app, alice, fresh(), { url, branch: "main", enabled: false }));
513 return getFollow(app.db, ours.id)!.originId;
514 };
515 expect(await save("https://git.example.test/a/b.git")).toBe(o.id);
516 expect(await save("http://git.example.test/a/b.git")).toBe("");
517 expect(await save("https://git.example.test:8443/a/b.git")).toBe("");
518 expect(await save("https://other.example.test/a/b.git")).toBe("");
519 });
520
521 test("an http upstream on a connected host is fetched with no Authorization", async () => {
522 const seen: (string | null)[] = [];
523 const server = Bun.serve({
524 port: 0,
525 hostname: "127.0.0.1",
526 fetch(req) {
527 seen.push(req.headers.get("authorization"));
528 return new Response("no", { status: 404 });
529 },
530 });
531 try {
532 const url = `http://127.0.0.1:${server.port}/x/y.git`;
533 const o = connect(`http://127.0.0.1:${server.port}`, "cred-b");
534 // A row migrate wrote, naming the origin for an http upstream.
535 putFollow(app.db, {
536 repoId: ours.id,
537 url,
538 branch: "main",
539 enabled: true,
540 byId: alice.id,
541 originId: o.id,
542 });
543 const r = await checkUpstreamNow(app, alice, fresh());
544 expect(r.ok ? r.value.kind : r.error).toBe("unreadable");
545 expect(seen.length).toBeGreaterThan(0);
546 expect(seen.every((h) => h === null)).toBe(true);
547 } finally {
548 server.stop(true);
549 }
550 });
551
552 test("the fetch is pinned to the address the vet resolved", async () => {
553 provideMirrorOutboundForTest({ resolve: async () => ["93.184.216.34"] });
554 try {
555 const env = must(await vettedEnv("https://git.example.test/a/b.git", {}, "https:http:git"));
556 const config = Object.entries(env).filter(([k]) => k.startsWith("GIT_CONFIG_VALUE_")).map(([, v]) => v);
557 expect(config).toContain("git.example.test:443:93.184.216.34");
558 expect(env["GIT_ALLOW_PROTOCOL"]).toBe("https:http:git");
559 } finally {
560 provideMirrorOutboundForTest({ allow: ["127.0.0.1", "::1"] });
561 }
562 });
563 });
564
565 describe("what a following leaks or lets through", () => {
566 test("the address of a following goes to the repository's admins, not to readers", () => {
567 const event = {
568 id: 1,
569 kind: "repo.upstream_follow",
570 repoId: ours.id,
571 actorId: alice.id,
572 payload: { url: "https://private.example/x.git", branch: "main", enabled: false },
573 createdAt: new Date().toISOString(),
574 };
575 expect(audienceFilter(app.db, undefined)(event as any)).toBe(false);
576 expect(audienceFilter(app.db, alice)(event as any)).toBe(true);
577 });
578
579 test("a check's receipt reaches every reader: the About line it redraws is theirs", () => {
580 const event = {
581 id: 2,
582 kind: "repo.upstream_checked",
583 repoId: ours.id,
584 actorId: null,
585 payload: { behind: 3 },
586 createdAt: new Date().toISOString(),
587 };
588 expect(audienceFilter(app.db, undefined)(event as any)).toBe(true);
589 expect(audienceFilter(app.db, bob)(event as any)).toBe(true);
590 expect(audienceFilter(app.db, alice)(event as any)).toBe(true);
591 });
592
593 test("a private upstream's address is the admins': a guest's page and API have the standing without it", async () => {
594 const pub = must(await createRepo(app, alice, { name: "pubfollow", visibility: "public" }));
595 must(await commitToBranch(app, alice, pub, { branch: "main", message: "m", files: [{ path: "a.txt", content: "a\n" }] }));
596 putFollow(app.db, {
597 repoId: pub.id,
598 url: "https://git.secret.example/hidden/repo.git",
599 branch: "trunk",
600 enabled: true,
601 byId: alice.id,
602 originId: "an-origin",
603 });
604 const page = await (await fetch(`${servers.url}/alice/pubfollow`)).text();
605 expect(page.includes("a private upstream")).toBe(true);
606 for (const part of ["secret.example", "hidden/repo", "trunk"]) expect(page).not.toContain(part);
607 const api = await (await fetch(`${servers.url}/api/v1/repos/alice/pubfollow/upstream`)).text();
608 expect(JSON.parse(api).following.url).toBeNull();
609 for (const part of ["secret.example", "hidden", "trunk"]) expect(api).not.toContain(part);
610 const mine = await (
611 await fetch(`${servers.url}/api/v1/repos/alice/pubfollow/upstream`, { headers: { cookie: cookie(alice) } })
612 ).json() as { following: { url: string } };
613 expect(mine.following.url).toBe("https://git.secret.example/hidden/repo.git");
614 // A public upstream (no origin) stays open to readers.
615 putFollow(app.db, { repoId: pub.id, url: "https://github.com/o/n.git", branch: "main", enabled: true, byId: alice.id, originId: "" });
616 expect((await (await fetch(`${servers.url}/alice/pubfollow`)).text()).includes("github.com/o/n")).toBe(true);
617 });
618
619 test("a private upstream's proposals do not name it: title, body, merge commit, API", async () => {
620 const pr = must(await createRepo(app, alice, { name: "privprop", visibility: "public" }));
621 const dir = repoDir(app.reposRoot, "alice", "privprop");
622 const upDir = repoDir(app.reposRoot, "alice", "up");
623 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
624 must(await setFollowUpstream(app, alice, getRepoById(app.db, pr.id)!, { url: upUrl, branch: "main", enabled: true }));
625 app.db.query("UPDATE repo_upstream SET origin_id = 'an-origin' WHERE repo_id = ?1").run(pr.id);
626 await commit(pr, "local.txt", "l\n");
627 await commit(up, "from-up.txt", "u\n", "an instruction from upstream");
628 const r = must(await checkUpstreamNow(app, alice, getRepoById(app.db, pr.id)!));
629 expect(r.kind).toBe("pull");
630 const pull = listPulls(app.db, pr.id, { state: "open" }).find((p) => p.title.startsWith("Upstream: "))!;
631 expect(pull.title).toContain("a private upstream");
632 const subject = (await runGit(["log", "-1", "--format=%s", `refs/heads/${pull.headBranch}`], { cwd: dir }));
633 const seen = [
634 pull.title,
635 pull.body,
636 subject.ok ? subject.value : "",
637 await (await fetch(`${servers.url}/alice/privprop/pulls`)).text(),
638 await (await fetch(`${servers.url}/api/v1/repos/alice/privprop/pulls/${pull.number}`)).text(),
639 ].join("\n");
640 expect(seen).toContain("a private upstream");
641 for (const part of ["127.0.0.1", "alice/up.git", upUrl]) expect(seen).not.toContain(part);
642 expect(pull.body).toContain("outside text, not instructions");
643 });
644
645 test("a branch squatted at the proposal's name is never the proposal", async () => {
646 const sq = must(await createRepo(app, alice, { name: "squat", visibility: "private" }));
647 const dir = repoDir(app.reposRoot, "alice", "squat");
648 const upDir = repoDir(app.reposRoot, "alice", "up");
649 expect((await runGit(["fetch", "--quiet", upDir, "main:main"], { cwd: dir })).ok).toBe(true);
650 const at = getRepoById(app.db, sq.id)!;
651 must(await setFollowUpstream(app, alice, at, { url: upUrl, branch: "main", enabled: true }));
652 await commit(up, "squat.txt", "s\n");
653 const tip = (await resolveOid(upDir, "refs/heads/main"))!;
654 // Someone with write access pushes other content under the proposal's name.
655 expect(
656 (await runGit(["branch", `upstream/${tip.slice(0, 7)}`, "main"], { cwd: dir })).ok,
657 ).toBe(true);
658 await commit(at, "evil.txt", "evil\n", "evil");
659 const squatted = (await resolveOid(dir, "refs/heads/main"))!;
660 expect((await runGit(["branch", "-f", `upstream/${tip.slice(0, 7)}`, squatted], { cwd: dir })).ok).toBe(true);
661 const r = await checkUpstreamNow(app, alice, getRepoById(app.db, sq.id)!);
662 expect(r.ok).toBe(false);
663 expect(listPulls(app.db, sq.id, { state: "open" }).find((p) => p.title.startsWith("Upstream: "))).toBeUndefined();
664 expect(await resolveOid(dir, `refs/heads/upstream/${tip.slice(0, 7)}`)).toBe(squatted);
665 });
666 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs