@niwa-labs/pstack 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +260 -2
- package/package.json +28 -4
- package/scripts/upstream-map.ts +90 -0
- package/src/author.ts +57 -0
- package/src/binding.ts +32 -0
- package/src/catalog.ts +86 -0
- package/src/composition.ts +66 -0
- package/src/index.ts +50 -0
- package/src/mapping/analyze.ts +223 -0
- package/src/mapping/assemble.ts +96 -0
- package/src/mapping/diff.ts +139 -0
- package/src/mapping/format.ts +67 -0
- package/src/mapping/git.ts +69 -0
- package/src/mapping/index.ts +18 -0
- package/src/mapping/maintain.ts +36 -0
- package/src/mapping/schema.ts +50 -0
- package/src/mapping/sources.ts +108 -0
- package/src/mapping/tool.ts +77 -0
- package/src/mapping/verify.ts +130 -0
- package/src/plugin.ts +136 -0
- package/src/policy.ts +115 -0
- package/src/ports.ts +184 -0
- package/src/pr-binding.ts +88 -0
- package/src/records.ts +61 -0
- package/src/roles.ts +49 -0
- package/src/trunk.ts +59 -0
- package/src/upstream-actions.ts +135 -0
- package/src/upstream-records.ts +71 -0
- package/src/upstream.ts +151 -0
- package/src/workflows/adapted.md +780 -0
- package/src/workflows/authoring-a-skill.ts +52 -0
- package/src/workflows/autonomous-run.ts +56 -0
- package/src/workflows/autopilot-full.ts +90 -0
- package/src/workflows/autopilot-stack.ts +125 -0
- package/src/workflows/babysit.ts +124 -0
- package/src/workflows/benny-reproduce.ts +122 -0
- package/src/workflows/benny-triage.ts +89 -0
- package/src/workflows/bug-fix.ts +54 -0
- package/src/workflows/entry.ts +130 -0
- package/src/workflows/eval.ts +63 -0
- package/src/workflows/feature.ts +54 -0
- package/src/workflows/hillclimb.ts +78 -0
- package/src/workflows/investigation.ts +41 -0
- package/src/workflows/lib/catalog.ts +45 -0
- package/src/workflows/lib/change.ts +70 -0
- package/src/workflows/lib/forensics.ts +37 -0
- package/src/workflows/lib/git.ts +30 -0
- package/src/workflows/lib/go.ts +58 -0
- package/src/workflows/lib/inputs.ts +34 -0
- package/src/workflows/lib/lane.ts +170 -0
- package/src/workflows/lib/measure.ts +34 -0
- package/src/workflows/lib/plan.ts +24 -0
- package/src/workflows/lib/script.ts +79 -0
- package/src/workflows/lib/ship.ts +110 -0
- package/src/workflows/lib/texts.ts +18 -0
- package/src/workflows/lib/trunk.ts +91 -0
- package/src/workflows/multi-phase-plan.ts +83 -0
- package/src/workflows/opening-a-pr.ts +62 -0
- package/src/workflows/pause-safely.ts +50 -0
- package/src/workflows/perf-issue.ts +87 -0
- package/src/workflows/prototype.ts +76 -0
- package/src/workflows/refactoring.ts +54 -0
- package/src/workflows/runtime-forensics.ts +26 -0
- package/src/workflows/scenarios.ts +380 -0
- package/src/workflows/session-pickup.ts +57 -0
- package/src/workflows/shipping.ts +63 -0
- package/src/workflows/suite.ts +129 -0
- package/src/workflows/texts/authoring-a-skill.json +5 -0
- package/src/workflows/texts/autonomous-run.json +5 -0
- package/src/workflows/texts/autopilot-full.json +5 -0
- package/src/workflows/texts/autopilot-stack.json +5 -0
- package/src/workflows/texts/babysit.json +5 -0
- package/src/workflows/texts/benny-reproduce.json +5 -0
- package/src/workflows/texts/benny-triage.json +5 -0
- package/src/workflows/texts/bug-fix.json +5 -0
- package/src/workflows/texts/bugbot-triage.json +5 -0
- package/src/workflows/texts/eval.json +5 -0
- package/src/workflows/texts/feature.json +5 -0
- package/src/workflows/texts/hillclimb.json +5 -0
- package/src/workflows/texts/investigation.json +5 -0
- package/src/workflows/texts/multi-phase-plan.json +5 -0
- package/src/workflows/texts/opening-a-pr.json +5 -0
- package/src/workflows/texts/pause-safely.json +5 -0
- package/src/workflows/texts/perf-issue.json +5 -0
- package/src/workflows/texts/prototype.json +5 -0
- package/src/workflows/texts/refactoring.json +5 -0
- package/src/workflows/texts/runtime-forensics.json +5 -0
- package/src/workflows/texts/session-pickup.json +5 -0
- package/src/workflows/texts/trace-forensics.json +5 -0
- package/src/workflows/texts/visual-parity.json +5 -0
- package/src/workflows/texts/worker.json +5 -0
- package/src/workflows/trace-forensics.ts +27 -0
- package/src/workflows/upstream-sync.ts +182 -0
- package/src/workflows/visual-parity.ts +52 -0
- package/src/workflows/worktree-cleanup.ts +57 -0
- package/test/author.test.ts +61 -0
- package/test/benny.test.ts +138 -0
- package/test/binding.test.ts +54 -0
- package/test/catalog-helpers.test.ts +49 -0
- package/test/closure.test.ts +45 -0
- package/test/composition.test.ts +23 -0
- package/test/eval.test.ts +23 -0
- package/test/lanes.test.ts +334 -0
- package/test/mapping-diff.test.ts +64 -0
- package/test/mapping-support.ts +110 -0
- package/test/mapping-texts.test.ts +106 -0
- package/test/mapping.test.ts +276 -0
- package/test/package-layout.ts +68 -0
- package/test/policy.test.ts +98 -0
- package/test/ports.test.ts +45 -0
- package/test/ports.ts +173 -0
- package/test/roles.test.ts +21 -0
- package/test/suite.test.ts +167 -0
- package/test/support.ts +541 -0
- package/test/texts.test.ts +174 -0
- package/test/tool.test.ts +48 -0
- package/test/trunk-helpers.test.ts +149 -0
- package/test/trunk.test.ts +24 -0
- package/test/upstream-sync.test.ts +246 -0
- package/test/upstream.test.ts +106 -0
- package/test/worktree-cleanup.test.ts +107 -0
- package/tsconfig.json +7 -0
- package/upstream/LICENSE +21 -0
- package/upstream/SOURCE.json +5 -0
- package/upstream/benny/FOR_AGENTS.md +89 -0
- package/upstream/benny/README.md +23 -0
- package/upstream/benny/skills/reproduce-and-fix-issues/SKILL.md +310 -0
- package/upstream/benny/skills/reproduce-and-fix-issues/references/control-adapter.md +169 -0
- package/upstream/benny/skills/reproduce-and-fix-issues/references/feature-map.example.md +205 -0
- package/upstream/benny/skills/reproduce-and-fix-issues/references/verify-existing-fix.md +93 -0
- package/upstream/benny/skills/setup-benny/SKILL.md +265 -0
- package/upstream/benny/skills/triage-issue-reports/SKILL.md +240 -0
- package/upstream/benny/skills/triage-issue-reports/references/routing.example.md +61 -0
- package/upstream/benny/templates/configuration.example.yaml +84 -0
- package/upstream/benny/templates/reproduce-automation-prompt.md +33 -0
- package/upstream/benny/templates/triage-automation-prompt.md +39 -0
- package/upstream/mapping.json +699 -0
- package/upstream/poteto-mode/SKILL.md +110 -0
- package/upstream/poteto-mode/playbooks/authoring-a-skill.md +12 -0
- package/upstream/poteto-mode/playbooks/autonomous-run.md +13 -0
- package/upstream/poteto-mode/playbooks/autopilot-full.md +25 -0
- package/upstream/poteto-mode/playbooks/autopilot-stack.md +8 -0
- package/upstream/poteto-mode/playbooks/babysit.md +10 -0
- package/upstream/poteto-mode/playbooks/bug-fix.md +15 -0
- package/upstream/poteto-mode/playbooks/eval.md +25 -0
- package/upstream/poteto-mode/playbooks/feature.md +21 -0
- package/upstream/poteto-mode/playbooks/hillclimb.md +21 -0
- package/upstream/poteto-mode/playbooks/investigation.md +14 -0
- package/upstream/poteto-mode/playbooks/multi-phase-plan.md +11 -0
- package/upstream/poteto-mode/playbooks/opening-a-pr.md +9 -0
- package/upstream/poteto-mode/playbooks/pause-safely.md +10 -0
- package/upstream/poteto-mode/playbooks/perf-issue.md +25 -0
- package/upstream/poteto-mode/playbooks/prototype.md +14 -0
- package/upstream/poteto-mode/playbooks/refactoring.md +16 -0
- package/upstream/poteto-mode/playbooks/runtime-forensics.md +11 -0
- package/upstream/poteto-mode/playbooks/session-pickup.md +11 -0
- package/upstream/poteto-mode/playbooks/shipping.md +12 -0
- package/upstream/poteto-mode/playbooks/trace-forensics.md +14 -0
- package/upstream/poteto-mode/playbooks/visual-parity.md +11 -0
- package/upstream/poteto-mode/playbooks/worktree-cleanup.md +12 -0
- package/upstream/poteto-mode/references/bugbot-triage.md +142 -0
- package/upstream/poteto-mode/worker.md +11 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The owner's go on plan nodes: asked once for a list of nodes of one revision of a plan, for one change, and
|
|
3
|
+
* attested once per node, bound by its digest to that revision, node and change. A new revision of the plan needs a
|
|
4
|
+
* new go: the old one covers nothing of it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { GO, goCovers, goDigest, goSubject } from "../../policy.ts";
|
|
8
|
+
import type { Listed, PlanRevision } from "../../policy.ts";
|
|
9
|
+
import { api } from "./script.ts";
|
|
10
|
+
|
|
11
|
+
/** A node of a plan, as the go names it. */
|
|
12
|
+
export interface PlanNode {
|
|
13
|
+
id: string;
|
|
14
|
+
text: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Ask the owner for a go on these nodes, and attest one per node when it is given. */
|
|
18
|
+
export async function askGo(key: string, opts: { plan: PlanRevision; nodes: readonly PlanNode[]; change: string }): Promise<boolean> {
|
|
19
|
+
const lines = opts.nodes.map((node) => `- ${node.id}: ${node.text}`);
|
|
20
|
+
const yes = await api().ask.confirm([`Go for revision ${String(opts.plan.rev)} of the plan ${opts.plan.of}, landing in ${opts.change}?`, "", ...lines].join("\n"), { label: `${key}-ask` });
|
|
21
|
+
if (!yes) return false;
|
|
22
|
+
for (const node of opts.nodes) {
|
|
23
|
+
await api().call(
|
|
24
|
+
"evidence.attest",
|
|
25
|
+
{ subject: goSubject(opts.plan, node.id), claim: { kind: "verdict", name: GO, outcome: "pass", sha: goDigest(opts.plan, node.id, opts.change) } },
|
|
26
|
+
{ label: `${key}-attest-${node.id}` },
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A plan as `plan.get` answers it. */
|
|
33
|
+
export interface PlanView {
|
|
34
|
+
of: string;
|
|
35
|
+
rev: number;
|
|
36
|
+
items: Array<{ id: string; text: string; state: string; note?: string }>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The plan's current revision. */
|
|
40
|
+
export async function currentPlan(key: string, of: string): Promise<PlanView> {
|
|
41
|
+
return (await api().call("plan.get", { of }, { label: key })) as PlanView;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether the go of each node covers the plan's current revision for this change: per node, covered or why not. */
|
|
45
|
+
export async function goFound(key: string, opts: { plan: PlanView; nodes: readonly string[]; change: string }): Promise<Array<{ name: string; covered: boolean; why?: string }>> {
|
|
46
|
+
const found: Array<{ name: string; covered: boolean; why?: string }> = [];
|
|
47
|
+
for (const node of opts.nodes) {
|
|
48
|
+
if (!opts.plan.items.some((item) => item.id === node)) {
|
|
49
|
+
found.push({ name: `go:${node}`, covered: false, why: "not-in-plan" });
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
const revision = { of: opts.plan.of, rev: opts.plan.rev };
|
|
53
|
+
const listed = (await api().call("evidence.list", { subject: goSubject(revision, node) }, { label: `${key}-${node}` })) as { items: Listed[] };
|
|
54
|
+
const covers = goCovers(listed.items, revision, node, opts.change);
|
|
55
|
+
found.push({ name: `go:${node}`, covered: covers.covered, ...(covers.why === undefined ? {} : { why: covers.why }) });
|
|
56
|
+
}
|
|
57
|
+
return found;
|
|
58
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The input every playbook takes, as a zod schema made with the script's own `z`: a schema is read before the
|
|
3
|
+
* script runs, by a process that has `z` and nothing else of the script runtime.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ScriptApi } from "@niwa-labs/script";
|
|
7
|
+
|
|
8
|
+
/** The zod of the script. */
|
|
9
|
+
export function zod(): ScriptApi["z"] {
|
|
10
|
+
const found = (globalThis as unknown as { z?: ScriptApi["z"] }).z;
|
|
11
|
+
if (found === undefined) throw new Error("pstack's scripts run inside a workflow script: z is not a global here");
|
|
12
|
+
return found;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A repository: where the forge serves it, and the real path of the local clone. */
|
|
16
|
+
export function repoSchema() {
|
|
17
|
+
const z = zod();
|
|
18
|
+
return z.strictObject({
|
|
19
|
+
host: z.string().min(1).describe("The host of the forge, gitlab.example.com"),
|
|
20
|
+
path: z.string().min(1).describe("The path of the project on the forge, acme/billing"),
|
|
21
|
+
local: z.string().min(1).describe("The real path of the local clone"),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** What a playbook is started with: the task, the repository, where niwa keeps its worktrees, and the trunk. */
|
|
26
|
+
export function playbookInput() {
|
|
27
|
+
const z = zod();
|
|
28
|
+
return z.strictObject({
|
|
29
|
+
task: z.string().min(1).max(4000),
|
|
30
|
+
repo: repoSchema(),
|
|
31
|
+
worktrees: z.string().min(1).describe("The real path of the folder niwa keeps its worktrees in, <home>/worktrees"),
|
|
32
|
+
base: z.string().min(1).default("main").describe("The trunk the changes land on"),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A lane: one change carried by one owner from its worktree to a verified pull request.
|
|
3
|
+
*
|
|
4
|
+
* The author works in a box tied to its checked worktree and publishes its branch. The lane opens the pull request
|
|
5
|
+
* only for the commit the author reported. The
|
|
6
|
+
* verifiers, sessions that did not write the code, re-run the gates and show the behaviour live, and attest each
|
|
7
|
+
* verdict under their own name; a verdict counts only when evidence says it covers the head and is not the author's.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { makeWorktree } from "@niwa-labs/flow-code";
|
|
11
|
+
import type { Worktree } from "@niwa-labs/flow-code";
|
|
12
|
+
import { untilPipeline } from "@niwa-labs/forge/flow";
|
|
13
|
+
|
|
14
|
+
import { VERDICTS } from "../../policy.ts";
|
|
15
|
+
import type { VerdictName } from "../../policy.ts";
|
|
16
|
+
import { gitOut } from "./git.ts";
|
|
17
|
+
import { zod } from "./inputs.ts";
|
|
18
|
+
import { api, authorOptions, forgeRepo, prSubject, seatOptions, stepTag } from "./script.ts";
|
|
19
|
+
import type { Repo, Roles, SessionAddress } from "./script.ts";
|
|
20
|
+
import { brief } from "./texts.ts";
|
|
21
|
+
import type { PlaybookText } from "./texts.ts";
|
|
22
|
+
|
|
23
|
+
/** A lane would not go on: what it refused, and why. */
|
|
24
|
+
export class LaneRefused extends Error {
|
|
25
|
+
override name = "LaneRefused";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What a lane built: the worktree, the author's address and the commit it made. */
|
|
29
|
+
export interface Built {
|
|
30
|
+
wt: Worktree;
|
|
31
|
+
author: SessionAddress;
|
|
32
|
+
sha: string;
|
|
33
|
+
summary: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** What the lanes of a playbook are given. */
|
|
37
|
+
export interface LaneOpts {
|
|
38
|
+
playbook: PlaybookText;
|
|
39
|
+
repo: Repo;
|
|
40
|
+
base: string;
|
|
41
|
+
worktrees: string;
|
|
42
|
+
roles: Roles;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const AUTHOR_CAN_DELEGATE = new Set(["bug-fix", "feature", "perf-issue", "refactoring"]);
|
|
46
|
+
|
|
47
|
+
/** Build a change: a worktree off `base`, an author boxed to it, and the commit the author made and published there. */
|
|
48
|
+
export async function build(key: string, opts: LaneOpts & { task: string; extra?: string[] }): Promise<Built> {
|
|
49
|
+
const z = zod();
|
|
50
|
+
const wt = await makeWorktree({ repo: opts.repo.local, base: opts.base, description: `${opts.playbook.title}: ${opts.task}`.slice(0, 120) });
|
|
51
|
+
const canDelegate = AUTHOR_CAN_DELEGATE.has(opts.playbook.name);
|
|
52
|
+
const author = await api().session({
|
|
53
|
+
...await authorOptions(`${key}-author`, wt.path, canDelegate),
|
|
54
|
+
label: `${key}-author`,
|
|
55
|
+
});
|
|
56
|
+
const done = await author.ask(
|
|
57
|
+
brief(stepTag(opts.playbook.name, "build"), opts.playbook, opts.task, [
|
|
58
|
+
`Work in ${wt.path}, on the branch ${wt.branch}. Commit the change there and publish the branch to the forge.`,
|
|
59
|
+
"Answer the commit you published and one paragraph on what changed.",
|
|
60
|
+
...(canDelegate ? [`If you use a helper, start it on ${author.address.harness}.`] : []),
|
|
61
|
+
...(opts.extra ?? []),
|
|
62
|
+
]),
|
|
63
|
+
{ schema: z.strictObject({ sha: z.string().regex(/^[0-9a-f]{40}([0-9a-f]{24})?$/), summary: z.string().min(1).max(4000) }), label: `${key}-build` },
|
|
64
|
+
);
|
|
65
|
+
await author.end();
|
|
66
|
+
const head = await gitOut(`${key}-head`, wt.path, ["rev-parse", "HEAD"]);
|
|
67
|
+
if (head !== done.sha) throw new LaneRefused(`the author answered ${done.sha}, but its worktree is at ${head}`);
|
|
68
|
+
return { wt, author: author.address, sha: head, summary: done.summary };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Open the pull request of a built change, only for the commit the author made. */
|
|
72
|
+
export async function openPr(key: string, opts: { repo: Repo; base: string; built: Built; title: string; description: string; draft?: boolean }): Promise<{ number: number; head: string; subject: string }> {
|
|
73
|
+
const out = (await api().call(
|
|
74
|
+
"forge.pr.ensure",
|
|
75
|
+
{
|
|
76
|
+
repo: forgeRepo(opts.repo),
|
|
77
|
+
branch: opts.built.wt.branch,
|
|
78
|
+
base: opts.base,
|
|
79
|
+
title: opts.title,
|
|
80
|
+
description: opts.description,
|
|
81
|
+
...(opts.draft === undefined ? {} : { draft: opts.draft }),
|
|
82
|
+
},
|
|
83
|
+
{ label: key },
|
|
84
|
+
)) as { pr: { number: number }; head: string };
|
|
85
|
+
if (out.head !== opts.built.sha) {
|
|
86
|
+
throw new LaneRefused(`the forge has ${out.head} at the head of ${opts.built.wt.branch}, not ${opts.built.sha} the author made: a push the lane did not make`);
|
|
87
|
+
}
|
|
88
|
+
const { id, path, branch, repo } = opts.built.wt;
|
|
89
|
+
await api().call("pstack.pr.bind", {
|
|
90
|
+
repo: forgeRepo(opts.repo), number: out.pr.number, head: out.head, author: opts.built.author, worktree: { id, path, branch, repo },
|
|
91
|
+
}, { label: `${key}-bind` });
|
|
92
|
+
return { number: out.pr.number, head: out.head, subject: prSubject(opts.repo, out.pr.number) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** What a verdict came to: covered at the head by a verifier that is not the author, or why not. */
|
|
96
|
+
export type VerdictFound = { name: VerdictName; covered: boolean; why?: string; outcome: "pass" | "fail"; evidence: string };
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Verify a head: for each verdict, a verifier session that did not write the code checks it in the worktree and
|
|
100
|
+
* attests what it found under its own name; the verdict counts when evidence says so, not the author's.
|
|
101
|
+
*/
|
|
102
|
+
export async function verify(
|
|
103
|
+
key: string,
|
|
104
|
+
opts: LaneOpts & { subject: string; sha: string; cwd: string; author: SessionAddress; task: string; names?: readonly VerdictName[] },
|
|
105
|
+
): Promise<VerdictFound[]> {
|
|
106
|
+
const z = zod();
|
|
107
|
+
const found: VerdictFound[] = [];
|
|
108
|
+
for (const name of opts.names ?? VERDICTS) {
|
|
109
|
+
const verifier = await api().session({
|
|
110
|
+
...seatOptions(opts.roles.verifier),
|
|
111
|
+
label: `${key}-${name}-start`,
|
|
112
|
+
cwd: opts.cwd,
|
|
113
|
+
visible: ["evidence.attest"],
|
|
114
|
+
});
|
|
115
|
+
const what =
|
|
116
|
+
name === "gates"
|
|
117
|
+
? "Run the repository's gates (type check, lint, tests) on this commit yourself."
|
|
118
|
+
: "Drive the real surface the change touches and show its load-bearing behaviour on this commit.";
|
|
119
|
+
const said = await verifier.ask(
|
|
120
|
+
brief(stepTag(opts.playbook.name, `verify-${name}`), opts.playbook, opts.task, [
|
|
121
|
+
`You did not write this change. Verify ${opts.subject} at ${opts.sha} in ${opts.cwd}. ${what}`,
|
|
122
|
+
`Then attest what you found with evidence.attest: subject "${opts.subject}", claim { kind: "verdict", name: "${name}", outcome: "pass" or "fail", sha: "${opts.sha}" }.`,
|
|
123
|
+
"Answer the outcome and the evidence it rests on.",
|
|
124
|
+
]),
|
|
125
|
+
{ schema: z.strictObject({ outcome: z.enum(["pass", "fail"]), evidence: z.string().min(1).max(4000) }), label: `${key}-${name}` },
|
|
126
|
+
);
|
|
127
|
+
await verifier.end();
|
|
128
|
+
const covers = (await api().call(
|
|
129
|
+
"evidence.covers",
|
|
130
|
+
{ requirement: { kind: "verdict", subject: opts.subject, name, sha: opts.sha, notBy: [opts.author] } },
|
|
131
|
+
{ label: `${key}-${name}-covers` },
|
|
132
|
+
)) as { covered: boolean; why?: string };
|
|
133
|
+
found.push({ name, covered: covers.covered, ...(covers.why === undefined ? {} : { why: covers.why }), outcome: said.outcome, evidence: said.evidence });
|
|
134
|
+
}
|
|
135
|
+
return found;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Wait for the pipeline of a pull request's head, and attest it when it is green. */
|
|
139
|
+
export async function headCi(key: string, opts: { repo: Repo; subject: string; sha: string; deadline?: string }): Promise<{ outcome: "green" | "red" | "timed-out"; pipeline?: number }> {
|
|
140
|
+
const ci = await untilPipeline(key, { repo: forgeRepo(opts.repo), sha: opts.sha, kind: "head", deadline: opts.deadline ?? "2h" });
|
|
141
|
+
if (ci.outcome === "green" && ci.pipeline !== undefined) {
|
|
142
|
+
await api().call("evidence.attest", { subject: opts.subject, claim: { kind: "ci", at: "head", sha: opts.sha, pipeline: ci.pipeline } }, { label: `${key}-attest` });
|
|
143
|
+
}
|
|
144
|
+
return ci;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A change carried to a verified pull request: built, opened, verified, and its head pipeline green. */
|
|
148
|
+
export interface Delivered {
|
|
149
|
+
built: Built;
|
|
150
|
+
pr: { number: number; head: string; subject: string };
|
|
151
|
+
verdicts: VerdictFound[];
|
|
152
|
+
ci: { outcome: "green" | "red" | "timed-out"; pipeline?: number };
|
|
153
|
+
verified: boolean;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Carry one change from a worktree to a verified pull request. */
|
|
157
|
+
export async function deliver(key: string, opts: LaneOpts & { task: string; title: string; extra?: string[]; draft?: boolean }): Promise<Delivered> {
|
|
158
|
+
const built = await build(`${key}-build`, opts);
|
|
159
|
+
const pr = await openPr(`${key}-pr`, {
|
|
160
|
+
repo: opts.repo,
|
|
161
|
+
base: opts.base,
|
|
162
|
+
built,
|
|
163
|
+
title: opts.title,
|
|
164
|
+
description: `## Why\n\n${opts.task}\n\n## What changed\n\n${built.summary}`,
|
|
165
|
+
...(opts.draft === undefined ? {} : { draft: opts.draft }),
|
|
166
|
+
});
|
|
167
|
+
const verdicts = await verify(`${key}-verify`, { ...opts, subject: pr.subject, sha: pr.head, cwd: built.wt.path, author: built.author });
|
|
168
|
+
const ci = await headCi(`${key}-ci`, { repo: opts.repo, subject: pr.subject, sha: pr.head });
|
|
169
|
+
return { built, pr, verdicts, ci, verified: verdicts.every((one) => one.covered) && ci.outcome === "green" };
|
|
170
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Commands a playbook runs in a worktree to decide something: a measurement whose last number is the metric, or a
|
|
3
|
+
* predicate whose exit says whether it holds. They run through `proc.run`, boxed to the worktree.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { api } from "./script.ts";
|
|
7
|
+
|
|
8
|
+
/** What a command answered: its exit and the end of its output. */
|
|
9
|
+
export interface Ran {
|
|
10
|
+
exit: number | null;
|
|
11
|
+
out: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Run a shell command in a worktree. */
|
|
15
|
+
export async function shell(key: string, cwd: string, command: string, timeout = 600_000): Promise<Ran> {
|
|
16
|
+
const ran = (await api().call("proc.run", { cmd: ["sh", "-c", command], cwd, timeout }, { label: key })) as { exit: number | null; tail: string };
|
|
17
|
+
return { exit: ran.exit, out: ran.tail };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The metric a measurement printed: the last number of its output, or null when it printed none or failed. */
|
|
21
|
+
export function metricOf(ran: Ran): number | null {
|
|
22
|
+
if (ran.exit !== 0) return null;
|
|
23
|
+
const numbers = ran.out.match(/-?\d+(?:\.\d+)?(?:e[-+]?\d+)?/gi);
|
|
24
|
+
const last = numbers?.at(-1);
|
|
25
|
+
return last === undefined ? null : Number(last);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Run a measurement in a worktree: its metric. */
|
|
29
|
+
export async function measure(key: string, cwd: string, command: string): Promise<number | null> {
|
|
30
|
+
return metricOf(await shell(key, cwd, command));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Whether `after` is better than `before` in the direction that counts. */
|
|
34
|
+
export const better = (after: number, before: number, direction: "lower" | "higher"): boolean => (direction === "lower" ? after < before : after > before);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The nodes of a plan as the playbooks that run one read them: each item, with the nodes it waits for, which the plan
|
|
3
|
+
* keeps in the item's note (`after a, b; files x`).
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { PlanView } from "./go.ts";
|
|
7
|
+
|
|
8
|
+
/** A node to run: its id, its text, its state in the plan, and the nodes it waits for. */
|
|
9
|
+
export interface RunNode {
|
|
10
|
+
id: string;
|
|
11
|
+
text: string;
|
|
12
|
+
state: string;
|
|
13
|
+
after: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The nodes of a plan that are still to be done, in the plan's order. */
|
|
17
|
+
export function openNodes(plan: PlanView): RunNode[] {
|
|
18
|
+
return plan.items
|
|
19
|
+
.filter((item) => item.state === "open" || item.state === "planned")
|
|
20
|
+
.map((item) => {
|
|
21
|
+
const after = /(?:^|;\s*)after ([^;]+)/.exec(item.note ?? "")?.[1];
|
|
22
|
+
return { id: item.id, text: item.text, state: item.state, after: after === undefined ? [] : after.split(",").map((one) => one.trim()).filter(Boolean) };
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The globals of the script a helper runs in, read when the helper is called: the helpers import nothing of the
|
|
3
|
+
* script runtime, only its types, so a stored copy of a script finds them as the script itself does.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { ScriptApi, ScriptSession, SessionOptions } from "@niwa-labs/script";
|
|
7
|
+
|
|
8
|
+
/** The globals of the script that calls a helper. */
|
|
9
|
+
export function api(): ScriptApi {
|
|
10
|
+
const globals = globalThis as unknown as Partial<ScriptApi>;
|
|
11
|
+
if (typeof globals.call !== "function" || typeof globals.ask !== "function" || typeof globals.session !== "function") {
|
|
12
|
+
throw new Error("pstack's helpers run inside a workflow script: call, ask and session must be available");
|
|
13
|
+
}
|
|
14
|
+
return globals as ScriptApi;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A repository as pstack's scripts are given it: where the forge serves it, and the local clone. */
|
|
18
|
+
export interface Repo {
|
|
19
|
+
/** The host of the forge: `gitlab.example.com`. */
|
|
20
|
+
host: string;
|
|
21
|
+
/** The path of the project on it: `acme/billing`. */
|
|
22
|
+
path: string;
|
|
23
|
+
/** The real path of the local clone. */
|
|
24
|
+
local: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The repository as forge's actions name it. */
|
|
28
|
+
export const forgeRepo = (repo: Repo): { host: string; path: string } => ({ host: repo.host, path: repo.path });
|
|
29
|
+
|
|
30
|
+
/** The subject of a pull request, as evidence names it: `gitlab.example.com/acme/billing/pr/7`. */
|
|
31
|
+
export const prSubject = (repo: Repo | { host: string; path: string }, number: number): string => `${repo.host}/${repo.path}/pr/${String(number)}`;
|
|
32
|
+
|
|
33
|
+
/** An address, as evidence binds a session that attests. */
|
|
34
|
+
export type SessionAddress = ScriptSession["address"];
|
|
35
|
+
|
|
36
|
+
/** A seat of a role, as the options of a workflow session. */
|
|
37
|
+
export interface Seat {
|
|
38
|
+
harness: string;
|
|
39
|
+
vendor?: string;
|
|
40
|
+
model?: string;
|
|
41
|
+
effort?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The roles, as `pstack.roles` answers them. */
|
|
45
|
+
export interface Roles {
|
|
46
|
+
lead: Seat;
|
|
47
|
+
author: Seat & { box: true };
|
|
48
|
+
reviewer: Seat;
|
|
49
|
+
verifier: Seat;
|
|
50
|
+
judge?: Seat;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The roles the owner gave pstack. */
|
|
54
|
+
export async function roles(): Promise<Roles> {
|
|
55
|
+
return (await api().call("pstack.roles", {}, { label: "roles" })) as Roles;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The launch options for a seat. */
|
|
59
|
+
export function seatOptions(seat: Seat): Pick<SessionOptions, "harness" | "model" | "effort"> {
|
|
60
|
+
return {
|
|
61
|
+
harness: seat.harness,
|
|
62
|
+
...(seat.model === undefined ? {} : { model: seat.model }),
|
|
63
|
+
...(seat.effort === undefined ? {} : { effort: seat.effort }),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Niwa tools for lending a bounded question to a child session of the current run. */
|
|
68
|
+
export const HELPER_ACTIONS = ["harness.list", "session.start", "session.ask", "session.end"];
|
|
69
|
+
|
|
70
|
+
/** The checked session settings for the author seat in a worktree. */
|
|
71
|
+
export async function authorOptions(key: string, place: string, helpers = false): Promise<SessionOptions> {
|
|
72
|
+
const settings = (await api().call("pstack.author.options", { place }, { label: `${key}-options` })) as SessionOptions & { harness: string };
|
|
73
|
+
if (!helpers) return settings;
|
|
74
|
+
const visible = HELPER_ACTIONS.map((action) => action === "session.start" ? `session.start@${settings.harness}` : action);
|
|
75
|
+
return { ...settings, visible };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The tag a prompt opens with: which step of which playbook it is, so a transcript shows where it came from. */
|
|
79
|
+
export const stepTag = (playbook: string, step: string): string => `[pstack:${playbook}:${step}]`;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Landing a pull request under pstack's merge policy: the owner's go on its plan nodes, verdicts not by its author,
|
|
3
|
+
* green CI on its head, and a green merge result of the pair the forge would merge now. The pipelines are read from
|
|
4
|
+
* the forge when it lands, and the evidence of them is attested from what it read. Trunk that conflicts with it
|
|
5
|
+
* stops it before anything is asked of the forge; any other move of trunk is what the merge result tests. Only then
|
|
6
|
+
* is it merged, at the head the policy was checked on, and read back.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { durationMs, land } from "@niwa-labs/forge/flow";
|
|
10
|
+
|
|
11
|
+
import { decide, mergeRequirements } from "../../policy.ts";
|
|
12
|
+
import type { Found } from "../../policy.ts";
|
|
13
|
+
import { currentPlan, goFound } from "./go.ts";
|
|
14
|
+
import { api, forgeRepo, prSubject } from "./script.ts";
|
|
15
|
+
import type { Repo, SessionAddress } from "./script.ts";
|
|
16
|
+
import { trunkAffects } from "./trunk.ts";
|
|
17
|
+
|
|
18
|
+
interface LandingRead {
|
|
19
|
+
state: string;
|
|
20
|
+
head: string;
|
|
21
|
+
base: string;
|
|
22
|
+
landing?: {
|
|
23
|
+
targetSha: string;
|
|
24
|
+
conditionalMerge: boolean;
|
|
25
|
+
pipelines: Array<{ pr?: number; pipeline: number; kind: string; state: string; sourceSha: string; targetSha?: string; mergeSha?: string }>;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** How a landing went. */
|
|
30
|
+
export type Shipped =
|
|
31
|
+
| { outcome: "merged"; pr: number; sha: string; trunk: string }
|
|
32
|
+
| { outcome: "refused"; pr: number; missing: Array<{ name: string; why: string }>; trunk?: string };
|
|
33
|
+
|
|
34
|
+
/** Land one pull request under the policy. */
|
|
35
|
+
export async function ship(
|
|
36
|
+
key: string,
|
|
37
|
+
opts: { repo: Repo; number: number; author?: SessionAddress | undefined; plan: string; nodes: readonly string[]; cwd: string; method?: "merge" | "squash" | "rebase"; deadline?: string },
|
|
38
|
+
): Promise<Shipped> {
|
|
39
|
+
const repo = forgeRepo(opts.repo);
|
|
40
|
+
const subject = prSubject(opts.repo, opts.number);
|
|
41
|
+
const read = (await api().call("forge.pr.read", { repo, number: opts.number }, { label: `${key}-read` })) as LandingRead;
|
|
42
|
+
if (read.state !== "open") return { outcome: "refused", pr: opts.number, missing: [{ name: "pr", why: `the pull request is ${read.state}` }] };
|
|
43
|
+
const head = read.head;
|
|
44
|
+
|
|
45
|
+
const { binding } = await api().call("pstack.pr.binding", { repo, number: opts.number, head }, { label: `${key}-binding` }) as { binding?: { author: SessionAddress } };
|
|
46
|
+
if (!binding || (opts.author && (opts.author.harness !== binding.author.harness || opts.author.id !== binding.author.id))) {
|
|
47
|
+
return { outcome: "refused", pr: opts.number, missing: [{ name: "author", why: binding ? "author differs from lane receipt" : "no unambiguous lane receipt for this head" }] };
|
|
48
|
+
}
|
|
49
|
+
const plan = await currentPlan(`${key}-plan`, opts.plan);
|
|
50
|
+
const goes = await goFound(`${key}-go`, { plan, nodes: opts.nodes, change: `${repo.host}/${repo.path}` });
|
|
51
|
+
|
|
52
|
+
const trunk = await trunkAffects(`${key}-trunk`, { pr: { repo, number: opts.number }, base: read.base, cwd: opts.cwd });
|
|
53
|
+
if (trunk.kind === "conflict") {
|
|
54
|
+
return { outcome: "refused", pr: opts.number, trunk: trunk.kind, missing: [...goes.filter((one) => !one.covered).map((one) => ({ name: one.name, why: one.why ?? "none" })), { name: "trunk", why: `conflict in ${trunk.files.join(", ")}` }] };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// CI is what the forge says in this run: the attestations are its receipts, and a claim another caller attested
|
|
58
|
+
// for this head does not stand in for a pipeline the forge reports red.
|
|
59
|
+
const deadline = opts.deadline ?? "2h";
|
|
60
|
+
const until = (await api().now({ label: `${key}-start` })) + durationMs(deadline);
|
|
61
|
+
let current: LandingRead;
|
|
62
|
+
for (let round = 0; ; round++) {
|
|
63
|
+
current = await api().call("forge.pr.read", { repo, number: opts.number, landing: true }, { label: `${key}-landing-${round}` }) as LandingRead;
|
|
64
|
+
if (current.state !== "open" || current.head !== head || current.base !== read.base || !current.landing) break;
|
|
65
|
+
const pending = current.landing.pipelines.some(one => !["success", "failed", "canceled", "skipped"].includes(one.state));
|
|
66
|
+
if (!pending) break;
|
|
67
|
+
const remaining = until - await api().now({ label: `${key}-now-${round}` });
|
|
68
|
+
if (remaining <= 0) break;
|
|
69
|
+
await api().sleep(Math.min(30_000, remaining), { label: `${key}-poll-${round}` });
|
|
70
|
+
}
|
|
71
|
+
if (current.state !== "open" || current.head !== head || current.base !== read.base || !current.landing) {
|
|
72
|
+
return { outcome: "refused", pr: opts.number, missing: [{ name: "pr", why: "pull request moved or current target is unknown" }] };
|
|
73
|
+
}
|
|
74
|
+
const { targetSha, pipelines, conditionalMerge } = current.landing;
|
|
75
|
+
const scoped = pipelines.filter(one => one.pr === opts.number && one.sourceSha === head);
|
|
76
|
+
const headCi = scoped.find(one => one.kind === "head");
|
|
77
|
+
const selected = scoped.find(one => one.kind === "merge-result");
|
|
78
|
+
const headGreen = headCi?.state === "success";
|
|
79
|
+
const mergeGreen = selected?.state === "success" && selected.targetSha === targetSha && selected.mergeSha !== undefined;
|
|
80
|
+
if (headGreen) {
|
|
81
|
+
await api().call("evidence.attest", { subject, claim: { kind: "ci", at: "head", sha: head, pipeline: headCi.pipeline } }, { label: `${key}-attest-head` });
|
|
82
|
+
}
|
|
83
|
+
if (mergeGreen) {
|
|
84
|
+
await api().call(
|
|
85
|
+
"evidence.attest",
|
|
86
|
+
{ subject, claim: { kind: "ci", at: "merge-result", sourceSha: head, targetSha: selected.targetSha, mergeSha: selected.mergeSha, pipeline: selected.pipeline, pipelineKind: selected.kind } },
|
|
87
|
+
{ label: `${key}-attest-merge-result` },
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const found: Found[] = [...goes];
|
|
92
|
+
if (!headGreen) found.push({ name: "head-ci", covered: false, why: headCi?.state ?? "none" });
|
|
93
|
+
if (!mergeGreen) found.push({ name: "merge-result", covered: false, why: selected?.targetSha !== targetSha ? "no pipeline for the current target" : selected.state });
|
|
94
|
+
const required = mergeRequirements({ subject, head, author: binding.author, target: { sha: targetSha, ...(selected === undefined ? {} : { pipeline: selected.pipeline }) } });
|
|
95
|
+
for (const one of required) {
|
|
96
|
+
if ((one.name === "head-ci" && !headGreen) || (one.name === "merge-result" && !mergeGreen)) continue;
|
|
97
|
+
const covers = (await api().call("evidence.covers", { requirement: one.requirement }, { label: `${key}-covers-${one.name}` })) as { covered: boolean; why?: string };
|
|
98
|
+
found.push({ name: one.name, covered: covers.covered, ...(covers.why === undefined ? {} : { why: covers.why }) });
|
|
99
|
+
}
|
|
100
|
+
const decision = decide(found);
|
|
101
|
+
if (!decision.land) return { outcome: "refused", pr: opts.number, trunk: trunk.kind, missing: decision.missing };
|
|
102
|
+
|
|
103
|
+
if (!conditionalMerge) return { outcome: "refused", pr: opts.number, trunk: trunk.kind, missing: [{ name: "land", why: "forge cannot condition a merge on the target commit" }] };
|
|
104
|
+
const landed = await land(`${key}-land`, { pr: { repo, number: opts.number }, expectHead: head, expectTarget: targetSha, method: opts.method ?? "merge" });
|
|
105
|
+
if (landed.outcome !== "merged") return { outcome: "refused", pr: opts.number, trunk: trunk.kind, missing: [{ name: "land", why: `${landed.outcome}: ${landed.why}` }] };
|
|
106
|
+
// Merged is what the forge says once it is read back, not what the merge call answered.
|
|
107
|
+
const after = (await api().call("forge.pr.read", { repo, number: opts.number }, { label: `${key}-read-back` })) as { state: string };
|
|
108
|
+
if (after.state !== "merged") return { outcome: "refused", pr: opts.number, trunk: trunk.kind, missing: [{ name: "land", why: `the pull request reads ${after.state} after the merge` }] };
|
|
109
|
+
return { outcome: "merged", pr: opts.number, sha: landed.sha, trunk: trunk.kind };
|
|
110
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The texts the scripts give their sessions: a playbook as upstream wrote it, with the worker rules that every
|
|
3
|
+
* session started for the operator works under.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import worker from "../texts/worker.json";
|
|
7
|
+
|
|
8
|
+
/** A playbook text, as the snapshot gives it. */
|
|
9
|
+
export interface PlaybookText {
|
|
10
|
+
name: string;
|
|
11
|
+
title: string;
|
|
12
|
+
text: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The brief of a session: its step, the worker rules, the playbook it works in, and the task. */
|
|
16
|
+
export function brief(tag: string, playbook: PlaybookText, task: string, extra: readonly string[] = []): string {
|
|
17
|
+
return [tag, "", worker.text.trim(), "", `You work in the ${playbook.title} playbook:`, "", playbook.text.trim(), "", ...extra, ...(extra.length > 0 ? [""] : []), `Task: ${task}`].join("\n");
|
|
18
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The script helpers that read what trunk did to a pull request, and carry a stack over a new lower head: git in a
|
|
3
|
+
* checkout of the repository, and the pull requests as the forge reads them.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { TrunkKind } from "../../trunk.ts";
|
|
7
|
+
import { stemsOf, trunkKind } from "../../trunk.ts";
|
|
8
|
+
import { gitOut, gitRun, linesOf } from "./git.ts";
|
|
9
|
+
import { api } from "./script.ts";
|
|
10
|
+
|
|
11
|
+
/** A pull request, as the helpers are given one. */
|
|
12
|
+
export interface PrRef {
|
|
13
|
+
repo: { host: string; path: string };
|
|
14
|
+
number: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A pull request as `forge.pr.read` answers it, as much as the helpers read. */
|
|
18
|
+
interface ReadPr {
|
|
19
|
+
state: "open" | "merged" | "closed";
|
|
20
|
+
branch: string;
|
|
21
|
+
base: string;
|
|
22
|
+
head: string;
|
|
23
|
+
mergeSha?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const readPr = async (key: string, pr: PrRef): Promise<ReadPr> =>
|
|
27
|
+
(await api().call("forge.pr.read", { repo: { host: pr.repo.host, path: pr.repo.path }, number: pr.number }, { label: key })) as ReadPr;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Whether trunk's changes since the pull request branched can affect it: its head as the forge has it, against `base`
|
|
31
|
+
* (a branch or a commit) in the checkout `cwd`, which must hold both. A conflict is found by merging the two trees
|
|
32
|
+
* without touching the checkout; a dependent is a file trunk changed that names a file of the patch.
|
|
33
|
+
*/
|
|
34
|
+
export async function trunkAffects(key: string, opts: { pr: PrRef; base: string; cwd: string }): Promise<{ kind: TrunkKind; files: string[] }> {
|
|
35
|
+
const { head } = await readPr(`${key}-pr`, opts.pr);
|
|
36
|
+
const fork = await gitOut(`${key}-fork`, opts.cwd, ["merge-base", opts.base, head]);
|
|
37
|
+
const patch = linesOf(await gitOut(`${key}-patch`, opts.cwd, ["diff", "--name-only", fork, head]));
|
|
38
|
+
const trunk = linesOf(await gitOut(`${key}-trunk`, opts.cwd, ["diff", "--name-only", fork, opts.base]));
|
|
39
|
+
const merged = await gitRun(`${key}-merge`, opts.cwd, ["merge-tree", "--write-tree", "--name-only", "--no-messages", opts.base, head]);
|
|
40
|
+
if (merged.exit !== 0 && merged.exit !== 1) throw new Error(`git merge-tree failed (${String(merged.exit)}): ${merged.out.trim().slice(-500)}`);
|
|
41
|
+
// The first line is the tree; a merge that conflicts lists the files after it.
|
|
42
|
+
const conflicts = merged.exit === 1 ? linesOf(merged.out).slice(1) : [];
|
|
43
|
+
const stems = stemsOf(patch);
|
|
44
|
+
const others = trunk.filter((file) => !patch.includes(file));
|
|
45
|
+
let dependents: string[] = [];
|
|
46
|
+
if (stems.length > 0 && others.length > 0) {
|
|
47
|
+
const grep = await gitRun(`${key}-grep`, opts.cwd, ["grep", "-l", "-F", ...stems.flatMap((stem) => ["-e", stem]), opts.base, "--", ...others]);
|
|
48
|
+
if (grep.exit !== 0 && grep.exit !== 1) throw new Error(`git grep failed (${String(grep.exit)}): ${grep.out.trim().slice(-500)}`);
|
|
49
|
+
dependents = linesOf(grep.out).map((line) => line.slice(line.indexOf(":") + 1));
|
|
50
|
+
}
|
|
51
|
+
return trunkKind({ patch, trunk, conflicts, dependents });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The patch-id of a range: what stays the same when a patch is carried onto another base unchanged. */
|
|
55
|
+
async function patchId(key: string, cwd: string, from: string, to: string): Promise<string> {
|
|
56
|
+
const hashed = (await api().call("proc.run", { cmd: ["sh", "-c", 'git diff --binary "$1" "$2" | git patch-id --stable', "patch-id", from, to], cwd, timeout: 60_000 }, { label: key })) as { exit: number; tail: string };
|
|
57
|
+
if (hashed.exit !== 0) throw new Error(`git patch-id failed: ${hashed.tail.trim().slice(-500)}`);
|
|
58
|
+
return hashed.tail.trim().split(/\s+/)[0] ?? "";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Carry the pull requests stacked on `lower` onto its new head: each upper one is rebased in the checkout `cwd` from
|
|
63
|
+
* `from`, the lower head it was built on, onto the lower head the forge has now (onto its target when it merged),
|
|
64
|
+
* and answers its new head and whether its patch is the one it was (same patch-id), which keeps its verdicts. The
|
|
65
|
+
* rebased commits are left in the checkout for their authors to publish; a rebase that conflicts is aborted and
|
|
66
|
+
* throws.
|
|
67
|
+
*/
|
|
68
|
+
export async function restack(key: string, opts: { lower: PrRef; from: string; upper: PrRef[]; cwd: string }): Promise<Array<{ pr: PrRef; head: string; patchKept: boolean }>> {
|
|
69
|
+
const lower = await readPr(`${key}-lower`, opts.lower);
|
|
70
|
+
const onto = lower.state === "merged" ? await gitOut(`${key}-onto`, opts.cwd, ["rev-parse", lower.base]) : lower.head;
|
|
71
|
+
const done: Array<{ pr: PrRef; head: string; patchKept: boolean }> = [];
|
|
72
|
+
let base = { from: opts.from, onto };
|
|
73
|
+
for (const [index, pr] of opts.upper.entries()) {
|
|
74
|
+
const step = `${key}-${String(index)}`;
|
|
75
|
+
const upper = await readPr(`${step}-pr`, pr);
|
|
76
|
+
// Detached: the branch itself stays checked out in its author's worktree.
|
|
77
|
+
await gitOut(`${step}-checkout`, opts.cwd, ["checkout", "-q", "--detach", upper.head]);
|
|
78
|
+
const rebased = await gitRun(`${step}-rebase`, opts.cwd, ["rebase", "-q", "--onto", base.onto, base.from]);
|
|
79
|
+
if (rebased.exit !== 0) {
|
|
80
|
+
await gitRun(`${step}-abort`, opts.cwd, ["rebase", "--abort"]);
|
|
81
|
+
throw new Error(`the pull request ${String(pr.number)} does not rebase onto ${base.onto}: ${rebased.out.trim().slice(-500)}`);
|
|
82
|
+
}
|
|
83
|
+
const head = await gitOut(`${step}-head`, opts.cwd, ["rev-parse", "HEAD"]);
|
|
84
|
+
const before = await patchId(`${step}-before`, opts.cwd, base.from, upper.head);
|
|
85
|
+
const after = await patchId(`${step}-after`, opts.cwd, base.onto, head);
|
|
86
|
+
done.push({ pr, head, patchKept: before === after });
|
|
87
|
+
// The next one up was built on this one's old head.
|
|
88
|
+
base = { from: upper.head, onto: head };
|
|
89
|
+
}
|
|
90
|
+
return done;
|
|
91
|
+
}
|