@moo.md/hum 0.0.0-stage → 0.1.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/defaults/hum.json +321 -0
- package/defaults/kinds/check.json +183 -0
- package/defaults/kinds/docs.json +151 -0
- package/defaults/kinds/feature.json +202 -0
- package/defaults/kinds/fix.json +183 -0
- package/defaults/kinds/hotfix.json +164 -0
- package/defaults/roles/build.md +3 -0
- package/defaults/roles/fix.md +1 -0
- package/defaults/roles/plan.md +3 -0
- package/defaults/roles/review.md +3 -0
- package/evals/alignment/RESULTS.md +8 -0
- package/evals/alignment/cases.jsonl +128 -0
- package/evals/alignment/sample.jsonl +20 -0
- package/evals/kind/RESULTS.md +5 -0
- package/evals/kind/cases.jsonl +24 -0
- package/evals/plan-outcome/RESULTS.md +4 -0
- package/evals/plan-outcome/cases.jsonl +12 -0
- package/evals/repeat-pair/RESULTS.md +4 -0
- package/evals/repeat-pair/cases.jsonl +51 -0
- package/evals/reply-option/RESULTS.md +3 -0
- package/evals/reply-option/cases.jsonl +45 -0
- package/evals/review-verdict/RESULTS.md +4 -0
- package/evals/review-verdict/cases.jsonl +12 -0
- package/package.json +88 -4
- package/schema/hum.schema.json +1355 -0
- package/scripts/eval.ts +244 -0
- package/src/adapter-api.ts +134 -0
- package/src/adapters/admit.ts +111 -0
- package/src/adapters/argument.ts +11 -0
- package/src/adapters/claim.ts +93 -0
- package/src/adapters/claude-bg.ts +392 -0
- package/src/adapters/claude-p.ts +599 -0
- package/src/adapters/contract.ts +231 -0
- package/src/adapters/fake.ts +157 -0
- package/src/adapters/git.ts +156 -0
- package/src/adapters/github.ts +479 -0
- package/src/adapters/guard.ts +152 -0
- package/src/adapters/history.ts +215 -0
- package/src/adapters/item-file.ts +102 -0
- package/src/adapters/limit.ts +67 -0
- package/src/adapters/markdown.ts +365 -0
- package/src/adapters/marked.ts +127 -0
- package/src/adapters/model-call.ts +75 -0
- package/src/adapters/once.ts +45 -0
- package/src/adapters/owner-commit.ts +60 -0
- package/src/adapters/pull-requests.ts +253 -0
- package/src/adapters/registry.ts +156 -0
- package/src/adapters/roundup.ts +293 -0
- package/src/adapters/serial.ts +22 -0
- package/src/adapters/transcript.ts +99 -0
- package/src/cli/commands.ts +46 -0
- package/src/cli/main.ts +8 -0
- package/src/cli/ops.ts +224 -0
- package/src/cli/service.ts +156 -0
- package/src/cli/setup.ts +141 -0
- package/src/cli/shared-watch.ts +127 -0
- package/src/config/change.ts +54 -0
- package/src/config/checks.ts +217 -0
- package/src/config/git-ref-name.d.ts +3 -0
- package/src/config/hash.ts +6 -0
- package/src/config/json.ts +6 -0
- package/src/config/load.ts +88 -0
- package/src/config/machine.ts +20 -0
- package/src/config/migrate.ts +61 -0
- package/src/config/refusal.ts +58 -0
- package/src/config/schema.ts +465 -0
- package/src/config/settings.ts +6 -0
- package/src/config/state-map.ts +76 -0
- package/src/decide/alignment.ts +79 -0
- package/src/decide/answer.ts +131 -0
- package/src/decide/kind.ts +39 -0
- package/src/decide/labels.ts +137 -0
- package/src/decide/merge.ts +102 -0
- package/src/decide/prose.ts +109 -0
- package/src/decide/question.ts +159 -0
- package/src/decide/review.ts +10 -0
- package/src/decide/risk.ts +216 -0
- package/src/decide/taste.ts +37 -0
- package/src/exec.ts +85 -0
- package/src/index.ts +200 -0
- package/src/loop/breaks.ts +8 -0
- package/src/loop/check-item.ts +76 -0
- package/src/loop/ci.ts +8 -0
- package/src/loop/github.ts +81 -0
- package/src/loop/groups.ts +108 -0
- package/src/loop/memory.ts +70 -0
- package/src/loop/notes.ts +76 -0
- package/src/loop/pair.ts +39 -0
- package/src/loop/pass.ts +99 -0
- package/src/loop/proof.ts +85 -0
- package/src/loop/prove-item.ts +33 -0
- package/src/loop/records.ts +75 -0
- package/src/loop/signals.ts +130 -0
- package/src/measure/inputs.ts +28 -0
- package/src/measure/measure.ts +68 -0
- package/src/service/cards.ts +24 -0
- package/src/service/ci-tick.ts +28 -0
- package/src/service/launchd.ts +16 -0
- package/src/service/supervise.ts +145 -0
- package/src/service/systemd.ts +44 -0
- package/src/service/token.ts +21 -0
- package/src/service/unit.ts +29 -0
- package/src/service/wake.ts +30 -0
- package/src/service/workflows.ts +97 -0
- package/src/setup/propose.ts +120 -0
- package/src/setup/prove.ts +216 -0
- package/src/setup/scan.ts +186 -0
- package/src/setup/scratch.ts +81 -0
- package/src/setup/shipped.ts +15 -0
- package/src/setup/tables.ts +101 -0
- package/src/setup/waits.ts +58 -0
- package/src/setup/write.ts +161 -0
- package/src/slots/env.ts +42 -0
- package/src/slots/pool.ts +329 -0
- package/src/slots/scan.ts +26 -0
- package/src/slots/worktree.ts +17 -0
- package/src/state/events.ts +52 -0
- package/src/state/faults.ts +73 -0
- package/src/state/format.ts +50 -0
- package/src/state/fs.ts +100 -0
- package/src/state/items.ts +195 -0
- package/src/state/open.ts +80 -0
- package/src/state/ops.ts +76 -0
- package/src/state/records.ts +35 -0
- package/src/state/runs.ts +99 -0
- package/src/state/saved.ts +119 -0
- package/src/status/file.ts +49 -0
- package/src/status/format.ts +132 -0
- package/src/status/sections.ts +14 -0
- package/src/status/version.ts +2 -0
- package/src/time.ts +7 -0
- package/src/worker/alignment-report.ts +18 -0
- package/src/worker/answers.ts +153 -0
- package/src/worker/base-check.ts +45 -0
- package/src/worker/checks.ts +40 -0
- package/src/worker/kind.ts +68 -0
- package/src/worker/land.ts +509 -0
- package/src/worker/lifecycle.ts +97 -0
- package/src/worker/merged.ts +29 -0
- package/src/worker/open.ts +100 -0
- package/src/worker/prose-run.ts +56 -0
- package/src/worker/questions.ts +89 -0
- package/src/worker/scheduler.ts +135 -0
- package/src/worker/signature.ts +41 -0
- package/src/worker/tally.ts +25 -0
- package/src/worker/taste.ts +38 -0
- package/src/worker/thin-path.ts +886 -0
- package/src/worker/worker.ts +750 -0
- package/surface.json +8787 -0
- package/README.md +0 -3
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import slugify from "@sindresorhus/slugify";
|
|
5
|
+
import PQueue from "p-queue";
|
|
6
|
+
import pRetry from "p-retry";
|
|
7
|
+
import { type Adapter, type AdapterContext, type Claim, type Item, ITEM_ID_LENGTH, ItemId, type ItemRef, PermanentError, type ThreadEntry, type Watch } from "../adapter-api.ts";
|
|
8
|
+
import type { MergeMethod } from "../config/schema.ts";
|
|
9
|
+
import { parseArgument } from "./argument.ts";
|
|
10
|
+
import { claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
|
|
11
|
+
import { type GitIdentity, gitIn, push, PushRefused, readOrAbsent } from "./git.ts";
|
|
12
|
+
import { appendEntry, type ItemFile, newItemFile, parseItemFile, READY_STATE } from "./item-file.ts";
|
|
13
|
+
import { answerMarker, followUpKey, questionText } from "./marked.ts";
|
|
14
|
+
import { type CommitLanded, landOwnerCommit } from "./owner-commit.ts";
|
|
15
|
+
import type { PullRequests } from "./pull-requests.ts";
|
|
16
|
+
|
|
17
|
+
const ITEM_EXTENSION = ".md";
|
|
18
|
+
const BASE_REF = "refs/hum/base";
|
|
19
|
+
const CLAIMS_REF = "refs/hum/claims";
|
|
20
|
+
const NO_BASE_TOKEN = "none";
|
|
21
|
+
const WRITE_RACE_BACKOFF_MS = 50;
|
|
22
|
+
const FOLLOW_UP_SLUG_LENGTH = 40;
|
|
23
|
+
|
|
24
|
+
export type MarkdownOptions = {
|
|
25
|
+
/** A clone of the work repo. The adapter never touches its working tree or its branches. */
|
|
26
|
+
readonly repo: string;
|
|
27
|
+
/** A claim is the first push of the branch this prefix and the item id make. */
|
|
28
|
+
readonly claimPrefix: string;
|
|
29
|
+
/** The folder of the repo that holds the item files. */
|
|
30
|
+
readonly itemsDir: string;
|
|
31
|
+
/** The author and committer of the commits the adapter makes. */
|
|
32
|
+
readonly identity: GitIdentity;
|
|
33
|
+
readonly remote?: string;
|
|
34
|
+
/** Retries of a write that another writer's push beat. */
|
|
35
|
+
readonly writeRaceRetries: number;
|
|
36
|
+
/** Item files read at once; each read is a git process. */
|
|
37
|
+
readonly itemReadsAtOnce: number;
|
|
38
|
+
/** The branch whose items folder holds the items; every write is pushed to it. */
|
|
39
|
+
readonly base?: string;
|
|
40
|
+
/** Pull requests of the repo on GitHub. An owner's answer goes through one when the base requires it. */
|
|
41
|
+
readonly pulls?: PullRequests;
|
|
42
|
+
readonly mergeMethod: MergeMethod;
|
|
43
|
+
/** The branch prefix of a pull request that lands an owner's answer. */
|
|
44
|
+
readonly ownerBranchPrefix: string;
|
|
45
|
+
/** The owner's `commandTimeoutSeconds` in milliseconds: the limit of every git call the adapter makes. */
|
|
46
|
+
readonly timeoutMs: number;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
type StandingClaim = { readonly claim: Claim; readonly sha: string };
|
|
50
|
+
|
|
51
|
+
type FileChange = { readonly path: string; readonly content: string };
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The remote as the last fetch saw it, with this adapter's own pushes since laid over it. Every read until the next
|
|
55
|
+
* fetch shares it: `listReady` fetches, and so does a read after a push that did not land as written.
|
|
56
|
+
*/
|
|
57
|
+
type View = {
|
|
58
|
+
/** The standing claims, read from the fetched refs at most once. */
|
|
59
|
+
claims?: Promise<ReadonlyMap<string, StandingClaim>>;
|
|
60
|
+
/** Each item file's source by path, read at most once. */
|
|
61
|
+
readonly sources: Map<string, Promise<string | undefined>>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/** How a write reached the base: a push of its own commit, or a pull request that merges it as a commit of GitHub's. */
|
|
65
|
+
type Landed = Exclude<CommitLanded["via"], "conflict">;
|
|
66
|
+
|
|
67
|
+
/** Another writer moved the base branch between this write's read and its push. */
|
|
68
|
+
class LostRace extends Error {
|
|
69
|
+
override name = "LostRace";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const isItemFileName = (name: string): boolean => name.endsWith(ITEM_EXTENSION);
|
|
73
|
+
|
|
74
|
+
const followUpId = (from: string, title: string): string =>
|
|
75
|
+
[from, slugify(title).slice(0, FOLLOW_UP_SLUG_LENGTH) || "follow-up", followUpKey(title)].join("-").slice(0, ITEM_ID_LENGTH);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The default work source: markdown files in the items folder on the base branch of a git remote.
|
|
79
|
+
* Every write is a commit built from git plumbing and pushed with hooks off, so the clone's working tree
|
|
80
|
+
* and branches stay untouched. A claim is the first push of its claim branch; a renewal is a fast-forward on top.
|
|
81
|
+
*/
|
|
82
|
+
export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRaceRetries, itemReadsAtOnce, pulls, mergeMethod, ownerBranchPrefix, timeoutMs, remote = "origin", base = "main" }: MarkdownOptions, { report, now }: AdapterContext) => {
|
|
83
|
+
const git = gitIn(repo, { identity, timeoutMs });
|
|
84
|
+
const pathOf = (id: string): string => `${itemsDir}/${id}${ITEM_EXTENSION}`;
|
|
85
|
+
const baseBranch = `refs/heads/${base}`;
|
|
86
|
+
let spent = 0;
|
|
87
|
+
/** One fetch serves every read that waits on it; a failed one leaves none. */
|
|
88
|
+
let view: Promise<View> | undefined;
|
|
89
|
+
|
|
90
|
+
const refetch = (): Promise<View> => {
|
|
91
|
+
spent++;
|
|
92
|
+
|
|
93
|
+
const fetched = git.raw(["fetch", "--prune", "--no-tags", "--quiet", remote, `+${baseBranch}:${BASE_REF}`, `+refs/heads/${claimPrefix}*:${CLAIMS_REF}/*`]).then((): View => ({ sources: new Map() }));
|
|
94
|
+
|
|
95
|
+
view = fetched;
|
|
96
|
+
fetched.catch(() => {
|
|
97
|
+
if (view === fetched) view = undefined;
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
return fetched;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const current = (): Promise<View> => view ?? refetch();
|
|
104
|
+
|
|
105
|
+
/** A push that did not land leaves the remote unknown, so the next read fetches. */
|
|
106
|
+
const pushCounted = async (args: readonly string[]) => {
|
|
107
|
+
spent++;
|
|
108
|
+
|
|
109
|
+
const outcome = await push(git, [remote, ...args]).catch((cause: unknown) => {
|
|
110
|
+
view = undefined;
|
|
111
|
+
|
|
112
|
+
throw cause;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
if (outcome === "conflict") view = undefined;
|
|
116
|
+
|
|
117
|
+
return outcome;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const standingFromLine = (line: string): [string, StandingClaim][] => {
|
|
121
|
+
const [ref = "", sha = "", subject = ""] = line.split("\t");
|
|
122
|
+
const item = ref.slice(`${CLAIMS_REF}/`.length);
|
|
123
|
+
const claim = claimOfCommit(item, subject);
|
|
124
|
+
|
|
125
|
+
return claim ? [[item, { claim, sha }]] : [];
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const readClaims = async (): Promise<ReadonlyMap<string, StandingClaim>> =>
|
|
129
|
+
new Map((await git.raw(["for-each-ref", "--format=%(refname)%09%(objectname)%09%(contents:subject)", CLAIMS_REF])).split("\n").filter(Boolean).flatMap(standingFromLine));
|
|
130
|
+
|
|
131
|
+
const claimsNow = async (): Promise<ReadonlyMap<string, StandingClaim>> => {
|
|
132
|
+
const seen = await current();
|
|
133
|
+
|
|
134
|
+
return (seen.claims ??= readClaims());
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const sourceIn = (seen: View, path: string): Promise<string | undefined> => {
|
|
138
|
+
const source = seen.sources.get(path) ?? readOrAbsent(git, ["show", `${BASE_REF}:${path}`]);
|
|
139
|
+
|
|
140
|
+
seen.sources.set(path, source);
|
|
141
|
+
|
|
142
|
+
return source;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
/** An item file the view lacks is looked for once more after a fetch: a view holds only what was there when it was fetched. */
|
|
146
|
+
const itemSource = async (id: string): Promise<string | undefined> => (await sourceIn(await current(), pathOf(id))) ?? sourceIn(await refetch(), pathOf(id));
|
|
147
|
+
|
|
148
|
+
/** The local copy of the base takes a commit this adapter pushed to it, so reads after the write see it without a fetch. */
|
|
149
|
+
const mirrorBase = async (sha: string, { path, content }: FileChange): Promise<void> => {
|
|
150
|
+
await git.raw(["update-ref", BASE_REF, sha]);
|
|
151
|
+
(await current()).sources.set(path, Promise.resolve(content));
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/** The local copy of a claim takes the claim this adapter pushed. */
|
|
155
|
+
const mirrorClaim = async (claim: Claim, sha: string): Promise<void> => {
|
|
156
|
+
await git.raw(["update-ref", `${CLAIMS_REF}/${claim.item}`, sha]);
|
|
157
|
+
|
|
158
|
+
const seen = await current();
|
|
159
|
+
|
|
160
|
+
if (seen.claims) seen.claims = seen.claims.then((claims) => new Map(claims).set(claim.item, { claim, sha }));
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const itemFileNames = async (): Promise<string[]> => ((await readOrAbsent(git, ["ls-tree", "--name-only", `${BASE_REF}:${itemsDir}`])) ?? "").split("\n").filter(isItemFileName);
|
|
164
|
+
|
|
165
|
+
/** One bad file raises one card and is skipped; the other items go on. */
|
|
166
|
+
const parseOrReport = (id: string, source: string): ItemFile | undefined => {
|
|
167
|
+
try {
|
|
168
|
+
return parseItemFile(source);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
report({
|
|
171
|
+
code: "item-malformed",
|
|
172
|
+
item: id,
|
|
173
|
+
cause: `${pathOf(id)} does not parse: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`,
|
|
174
|
+
fix: `Fix the front matter or thread markers in ${pathOf(id)}.`,
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const loadItem = async (id: string): Promise<ItemFile | undefined> => {
|
|
182
|
+
const source = await itemSource(id);
|
|
183
|
+
|
|
184
|
+
return source === undefined ? undefined : parseOrReport(id, source);
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const isReady = (file: ItemFile | undefined, standing: StandingClaim | undefined): file is ItemFile => file?.state === READY_STATE && !isLive(standing?.claim, now());
|
|
188
|
+
|
|
189
|
+
const readyRef = async (name: string, claims: ReadonlyMap<string, StandingClaim>): Promise<ItemRef[]> => {
|
|
190
|
+
const id = name.slice(0, -ITEM_EXTENSION.length);
|
|
191
|
+
|
|
192
|
+
if (!ItemId.safeParse(id).success) {
|
|
193
|
+
report({ code: "item-malformed", item: id, cause: `${itemsDir}/${name} has a name that is no item id`, fix: `Rename ${itemsDir}/${name} to letters, digits, dot, dash or underscore.` });
|
|
194
|
+
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const file = await loadItem(id);
|
|
199
|
+
|
|
200
|
+
return isReady(file, claims.get(id)) ? [{ id, title: file.title }] : [];
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/** A commit on `parent` with the base branch's tree, and `change` applied through a scratch index when given. */
|
|
204
|
+
const commitOn = async (parent: string, message: string, change?: FileChange): Promise<string> => {
|
|
205
|
+
const scratch = mkdtempSync(join(tmpdir(), "hum-index-"));
|
|
206
|
+
const indexed = gitIn(repo, { identity, timeoutMs, env: { GIT_INDEX_FILE: join(scratch, "index") } });
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
if (change) {
|
|
210
|
+
await indexed.raw(["read-tree", BASE_REF]);
|
|
211
|
+
await indexed.raw(["update-index", "--add", "--cacheinfo", `100644,${(await indexed.raw(["hash-object", "-w", "--stdin"], change.content)).trim()},${change.path}`]);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const tree = change ? (await indexed.raw(["write-tree"])).trim() : `${BASE_REF}^{tree}`;
|
|
215
|
+
|
|
216
|
+
return (await indexed.raw(["-c", "commit.gpgsign=false", "commit-tree", tree, "-p", parent, "-m", message])).trim();
|
|
217
|
+
} finally {
|
|
218
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const reportRefusal = (error: PushRefused): never => {
|
|
223
|
+
report({
|
|
224
|
+
code: "push-refused",
|
|
225
|
+
item: base,
|
|
226
|
+
cause: `The remote refused the push to ${base}: ${error.message.slice(0, 300)}`,
|
|
227
|
+
fix: `Let this account push to ${base}, or point hum at a branch it may write.`,
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
throw error;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const pushToBase = async (sha: string): Promise<Landed> => {
|
|
234
|
+
const outcome = await pushCounted([`${sha}:${baseBranch}`]).catch((cause: unknown) => (cause instanceof PushRefused ? reportRefusal(cause) : Promise.reject(cause)));
|
|
235
|
+
|
|
236
|
+
if (outcome === "conflict") throw new LostRace(`another writer moved ${base} first`);
|
|
237
|
+
|
|
238
|
+
return "push";
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
/** An owner's commit lands the way the base asks: a pull request that merges itself where one is required, a push elsewhere. */
|
|
242
|
+
const landOwned = async (sha: string, message: string, label: string): Promise<Landed> => {
|
|
243
|
+
const landed = await landOwnerCommit({
|
|
244
|
+
sha,
|
|
245
|
+
base,
|
|
246
|
+
label,
|
|
247
|
+
title: message,
|
|
248
|
+
body: `The owner answered on item ${label}.`,
|
|
249
|
+
branchPrefix: ownerBranchPrefix,
|
|
250
|
+
mergeMethod,
|
|
251
|
+
pulls,
|
|
252
|
+
push: pushCounted,
|
|
253
|
+
}).catch((cause: unknown) => (cause instanceof PushRefused ? reportRefusal(cause) : Promise.reject(cause)));
|
|
254
|
+
|
|
255
|
+
if (landed.via === "conflict") throw new LostRace(`another writer moved ${base} first`);
|
|
256
|
+
|
|
257
|
+
return landed.via;
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/** Changes one file on the remote base branch, reading it afresh after every lost race. */
|
|
261
|
+
const write = async (message: string, change: () => Promise<FileChange | undefined>, ownedBy?: string): Promise<void> => {
|
|
262
|
+
const attempt = async () => {
|
|
263
|
+
await current();
|
|
264
|
+
|
|
265
|
+
const next = await change();
|
|
266
|
+
|
|
267
|
+
if (!next) return;
|
|
268
|
+
|
|
269
|
+
const sha = await commitOn((await git.raw(["rev-parse", BASE_REF])).trim(), message, next);
|
|
270
|
+
const landed = ownedBy === undefined ? await pushToBase(sha) : await landOwned(sha, message, ownedBy);
|
|
271
|
+
|
|
272
|
+
if (landed === "push") await mirrorBase(sha, next);
|
|
273
|
+
else view = undefined;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
await pRetry(attempt, { retries: writeRaceRetries, minTimeout: WRITE_RACE_BACKOFF_MS, randomize: true, shouldRetry: ({ error }) => error instanceof LostRace }).catch((cause: unknown) => {
|
|
277
|
+
throw cause instanceof LostRace ? new PermanentError(`gave up after ${writeRaceRetries + 1} lost races pushing to ${base}`) : cause;
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const appendTo = (id: string, entry: Omit<ThreadEntry, "text" | "at">, text: string): Promise<void> =>
|
|
282
|
+
write(
|
|
283
|
+
`hum: ${entry.kind} on ${id}`,
|
|
284
|
+
async () => {
|
|
285
|
+
const source = await itemSource(id);
|
|
286
|
+
|
|
287
|
+
if (source === undefined) throw new PermanentError(`no item "${id}" under ${itemsDir}/`);
|
|
288
|
+
|
|
289
|
+
return { path: pathOf(id), content: appendEntry(source, { ...entry, at: now() }, text) };
|
|
290
|
+
},
|
|
291
|
+
entry.kind === "answer" ? id : undefined,
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
const take = claimer<StandingClaim>(
|
|
295
|
+
{
|
|
296
|
+
standing: async (id) => (await claimsNow()).get(id),
|
|
297
|
+
isReady: async (id) => (await loadItem(id))?.state === READY_STATE,
|
|
298
|
+
write: async (claim, over) => {
|
|
299
|
+
const parent = over?.sha ?? (await git.raw(["rev-parse", BASE_REF])).trim();
|
|
300
|
+
const sha = await commitOn(parent, claimCommitMessage(claim));
|
|
301
|
+
|
|
302
|
+
if ((await pushCounted([`${sha}:refs/heads/${claimPrefix}${claim.item}`])) === "conflict") return false;
|
|
303
|
+
|
|
304
|
+
await mirrorClaim(claim, sha);
|
|
305
|
+
|
|
306
|
+
return true;
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
now,
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
const read = async (id: string): Promise<Item> => {
|
|
313
|
+
const item = parseArgument(ItemId, id);
|
|
314
|
+
const [source, claims] = await Promise.all([itemSource(item), claimsNow()]);
|
|
315
|
+
|
|
316
|
+
if (source === undefined) throw new PermanentError(`no item "${item}" under ${itemsDir}/`);
|
|
317
|
+
|
|
318
|
+
const file = parseOrReport(item, source);
|
|
319
|
+
|
|
320
|
+
if (!file) throw new PermanentError(`item "${item}" is malformed; see its fault card`);
|
|
321
|
+
|
|
322
|
+
return { id: item, title: file.title, body: file.body, ready: isReady(file, claims.get(item)), thread: file.thread, labels: file.kind === undefined ? [] : [file.kind] };
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const adapter = {
|
|
326
|
+
apiVersion: 1,
|
|
327
|
+
/** Fetches and pushes so far. */
|
|
328
|
+
spent: () => spent,
|
|
329
|
+
workSource: {
|
|
330
|
+
listReady: async () => {
|
|
331
|
+
await refetch();
|
|
332
|
+
|
|
333
|
+
const [claims, names] = await Promise.all([claimsNow(), itemFileNames()]);
|
|
334
|
+
|
|
335
|
+
return (await new PQueue({ concurrency: itemReadsAtOnce }).addAll(names.map((name) => () => readyRef(name, claims)))).flat();
|
|
336
|
+
},
|
|
337
|
+
read,
|
|
338
|
+
claim: (id, holder, ttlMs) => take("claim", parseArgument(ItemId, id), holder, ttlMs),
|
|
339
|
+
renew: (id, holder, ttlMs) => take("renew", parseArgument(ItemId, id), holder, ttlMs),
|
|
340
|
+
comment: (id, text) => appendTo(id, { kind: "comment" }, text),
|
|
341
|
+
fileFollowUp: async (from, { title, body }) => {
|
|
342
|
+
const id = parseArgument(ItemId, followUpId(parseArgument(ItemId, from), title));
|
|
343
|
+
|
|
344
|
+
await write(`hum: file ${id}`, async () => ((await itemSource(id)) === undefined ? { path: pathOf(id), content: newItemFile(title, `${body.trim()}\n\nFiled from ${from}.`) } : undefined));
|
|
345
|
+
|
|
346
|
+
return { id, title };
|
|
347
|
+
},
|
|
348
|
+
},
|
|
349
|
+
questions: {
|
|
350
|
+
ask: (id, question) => appendTo(id, { kind: "question" }, questionText(question)),
|
|
351
|
+
decide: (id, text) => appendTo(id, { kind: "decision" }, text),
|
|
352
|
+
},
|
|
353
|
+
answers: {
|
|
354
|
+
answer: (id, { text, option }) => appendTo(id, answerMarker(option), text),
|
|
355
|
+
/** The token is the remote base branch's tip; reading one ref spends no rate limit. */
|
|
356
|
+
watch: async (since?: string): Promise<Watch> => {
|
|
357
|
+
const [token = NO_BASE_TOKEN] = (await git.raw(["ls-remote", remote, baseBranch])).split(/\s/).filter(Boolean);
|
|
358
|
+
|
|
359
|
+
return { token, changed: token !== since };
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
} satisfies Adapter & { readonly spent: () => number };
|
|
363
|
+
|
|
364
|
+
return adapter;
|
|
365
|
+
};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { PermanentError, type Question, THREAD_KINDS, type ThreadEntry } from "../adapter-api.ts";
|
|
4
|
+
|
|
5
|
+
const OPEN = "<!-- hum ";
|
|
6
|
+
const CLOSE = " -->";
|
|
7
|
+
const EMPTY_COMMENT = "(empty)";
|
|
8
|
+
const FOLLOW_UP_KEY_LENGTH = 12;
|
|
9
|
+
|
|
10
|
+
/** The hidden first line of a comment hum writes: its kind, the option an answer carries, the options a question offers. */
|
|
11
|
+
export const Marker = z.looseObject({
|
|
12
|
+
kind: z.enum(THREAD_KINDS),
|
|
13
|
+
option: z.string().min(1).optional(),
|
|
14
|
+
options: z.array(z.string()).optional(),
|
|
15
|
+
followUp: z.strictObject({ key: z.string(), item: z.string().min(1) }).optional(),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export type Marker = z.infer<typeof Marker>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* One hidden line that carries `value`: an HTML comment opened by `open`. The value is checked against the schema
|
|
22
|
+
* its reader parses it with, and `>` is written as `>`, so a value can never close the comment that holds it.
|
|
23
|
+
*/
|
|
24
|
+
export const markerLine = <T>(schema: z.ZodType<T>, value: T, open: string = OPEN): string =>
|
|
25
|
+
`${open}${JSON.stringify(schema.parse(value)).replaceAll(">", "\\u003e")}${CLOSE}`;
|
|
26
|
+
|
|
27
|
+
/** Whether `line` is one whole hidden line opened by `open`. */
|
|
28
|
+
export const isMarkerLine = (line: string, open: string = OPEN): boolean => line.startsWith(open) && line.endsWith(CLOSE);
|
|
29
|
+
|
|
30
|
+
/** The JSON of a text's leading hidden line and the text after it; undefined when the text opens with no such line. */
|
|
31
|
+
export const splitMarker = (body: string, open: string = OPEN): { readonly json: string; readonly text: string } | undefined => {
|
|
32
|
+
const source = body.replaceAll("\r\n", "\n");
|
|
33
|
+
const end = source.indexOf(CLOSE);
|
|
34
|
+
|
|
35
|
+
return source.startsWith(open) && end >= 0 ? { json: source.slice(open.length, end), text: source.slice(end + CLOSE.length).trim() } : undefined;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** JSON a person may have written by hand: anything that does not parse, or does not fit `schema`, reads as no value at all. */
|
|
39
|
+
export const parseLooseJson = <T>(schema: z.ZodType<T>, json: string): T | undefined => {
|
|
40
|
+
try {
|
|
41
|
+
return schema.safeParse(JSON.parse(json)).data;
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export const questionMarker = (options?: readonly string[]): Marker => (options?.length ? { kind: "question", options: [...options] } : { kind: "question" });
|
|
48
|
+
|
|
49
|
+
export const answerMarker = (option?: string): Marker => (option === undefined ? { kind: "answer" } : { kind: "answer", option });
|
|
50
|
+
|
|
51
|
+
const FOLD_OPEN = "<details><summary>For Agents</summary>";
|
|
52
|
+
const FOLD_CLOSE = "</details>";
|
|
53
|
+
|
|
54
|
+
/** A question as a thread shows it: the options it offers follow on their own line, and its detail folds below. */
|
|
55
|
+
export const questionText = ({ text, options, detail }: Question): string =>
|
|
56
|
+
[text, options?.length ? `Options: ${options.join(", ")}` : undefined, detail?.trim() ? `${FOLD_OPEN}\n\n${detail.trim()}\n\n${FOLD_CLOSE}` : undefined].filter(Boolean).join("\n\n");
|
|
57
|
+
|
|
58
|
+
const OPTIONS_LINE = /^Options: (.+)$/m;
|
|
59
|
+
|
|
60
|
+
/** The options a question's thread text offers, from its options line. */
|
|
61
|
+
export const optionsIn = (text: string): string[] => (OPTIONS_LINE.exec(text)?.[1] ?? "").split(", ").filter(Boolean);
|
|
62
|
+
|
|
63
|
+
/** The part of a thread entry's text the owner reads: what comes before the options line and the fold. */
|
|
64
|
+
export const visibleText = (text: string): string => text.split(/\n\n(?:Options: |<details>)/)[0] ?? text;
|
|
65
|
+
|
|
66
|
+
/** A comment's text; a provider that refuses an empty comment gets a placeholder. */
|
|
67
|
+
export const commentText = (text: string): string => text.trim() || EMPTY_COMMENT;
|
|
68
|
+
|
|
69
|
+
/** The same follow-up title from the same item always has the same key, so filing it twice files it once. */
|
|
70
|
+
export const followUpKey = (title: string): string => createHash("sha256").update(title).digest("hex").slice(0, FOLLOW_UP_KEY_LENGTH);
|
|
71
|
+
|
|
72
|
+
const filedFrom = (from: string): string => `Filed from ${from}.`;
|
|
73
|
+
|
|
74
|
+
/** A follow-up's body, which names the item it came from. */
|
|
75
|
+
export const followUpBody = (body: string, from: string): string => `${body.trim()}\n\n${filedFrom(from)}`;
|
|
76
|
+
|
|
77
|
+
/** Whether an item is the follow-up with this title filed from `from`, read from the item itself: it finds a follow-up whose note on `from` was never written. */
|
|
78
|
+
export const isFollowUpOf =
|
|
79
|
+
(from: string, title: string) =>
|
|
80
|
+
(found: { readonly title: string; readonly body: string }): boolean =>
|
|
81
|
+
found.title === title && found.body.trimEnd().endsWith(filedFrom(from));
|
|
82
|
+
|
|
83
|
+
/** The note left on the item a follow-up came from; its marker carries the key that finds the follow-up again. */
|
|
84
|
+
export const followUpNote = (title: string, item: string) => ({
|
|
85
|
+
marker: { kind: "comment", followUp: { key: followUpKey(title), item } } satisfies Marker,
|
|
86
|
+
text: `Filed follow-up #${item}: ${title}`,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
/** The marker on a comment's first line, or undefined for a person's comment. */
|
|
90
|
+
export const markerOf = (body: string): Marker | undefined => {
|
|
91
|
+
const split = splitMarker(body);
|
|
92
|
+
|
|
93
|
+
return split && parseLooseJson(Marker, split.json);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** The item a follow-up with this title was filed as, read from the notes on the item it came from. */
|
|
97
|
+
export const filedFollowUp = (bodies: readonly string[], title: string): string | undefined =>
|
|
98
|
+
bodies.map(markerOf).find((marker) => marker?.followUp?.key === followUpKey(title))?.followUp?.item;
|
|
99
|
+
|
|
100
|
+
/** A comment hum writes on a provider's thread. */
|
|
101
|
+
export const marked = (marker: Marker, text: string): string => `${markerLine(Marker, marker)}\n\n${text.trim()}`;
|
|
102
|
+
|
|
103
|
+
/** The same comment on one line, for a provider whose comments hold one line of at most `limit` characters; text that does not fit is refused, never cut. */
|
|
104
|
+
export const markedLine = (marker: Marker, text: string, limit: number): string => {
|
|
105
|
+
const line = `${markerLine(Marker, marker)} ${text.replaceAll(/\s+/g, " ").trim()}`;
|
|
106
|
+
|
|
107
|
+
if (line.length > limit) throw new PermanentError(`this provider's comments hold ${limit} characters; this one needs ${line.length}`);
|
|
108
|
+
|
|
109
|
+
return line;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** The first lines of `text` on one line, cut so the line with its optional marker and the closing `note` fits `limit`. */
|
|
113
|
+
export const cutLine = (marker: Marker | undefined, text: string, note: string, limit: number): string => {
|
|
114
|
+
const prefix = marker ? `${markerLine(Marker, marker)} ` : "";
|
|
115
|
+
const room = limit - prefix.length - note.length;
|
|
116
|
+
const head = visibleText(text).replaceAll(/\s+/g, " ").trim();
|
|
117
|
+
|
|
118
|
+
return `${prefix}${head.length > room ? `${head.slice(0, room - 1)}…` : head}${note}`;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** A comment as a thread entry. One without hum's marker, or with nothing after it, is a person's and reads as a comment. */
|
|
122
|
+
export const parseComment = (body: string, at: number): ThreadEntry => {
|
|
123
|
+
const marker = markerOf(body);
|
|
124
|
+
const text = splitMarker(body)?.text ?? "";
|
|
125
|
+
|
|
126
|
+
return marker && text !== "" ? { kind: marker.kind, text, at, option: marker.option, author: "hum" } : { kind: "comment", text: commentText(body.replaceAll("\r\n", "\n")), at, author: "person" };
|
|
127
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { tmpdir } from "node:os";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import type { Boundary, HumConfig } from "../config/schema.ts";
|
|
4
|
+
import { isTrusted, jsonSchemaOf } from "../decide/prose.ts";
|
|
5
|
+
import { SECOND_MS } from "../time.ts";
|
|
6
|
+
import { type RunOutcome, type Runner, succeeded } from "./claude-p.ts";
|
|
7
|
+
|
|
8
|
+
/** One question to the cheap model: the boundary it is measured at, the prompt, and the typed answer. */
|
|
9
|
+
export type Question<T> = { readonly boundary: Boundary; readonly prompt: string; readonly answer: z.ZodType<T>;
|
|
10
|
+
/** The item the call is for: the tokens it spends join that item's total. */
|
|
11
|
+
readonly item?: string;
|
|
12
|
+
/** The pick feeds a report that decides nothing, so it needs no measured rate; the caller says what the rate is. */
|
|
13
|
+
readonly reportOnly?: true;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** An answer counts only as a pick; anything else is an abstention, which marks the item unclear and never raises a level. */
|
|
17
|
+
export type Judgment<T> =
|
|
18
|
+
| { readonly kind: "picked"; readonly value: T; readonly models: readonly string[] }
|
|
19
|
+
| { readonly kind: "abstained"; readonly why: string };
|
|
20
|
+
|
|
21
|
+
export type ModelCall = <T>(question: Question<T>) => Promise<Judgment<T>>;
|
|
22
|
+
|
|
23
|
+
const NOT_ANSWERED: Readonly<Record<Exclude<RunOutcome, { kind: "finished" }>["kind"], string>> = {
|
|
24
|
+
limited: "a usage limit refused the call",
|
|
25
|
+
held: "the runner is held",
|
|
26
|
+
"over-cap": "the call passed its token cap",
|
|
27
|
+
stopped: "the call timed out",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const abstained = (why: string) => ({ kind: "abstained", why }) as const;
|
|
31
|
+
|
|
32
|
+
export type ModelCallOptions = {
|
|
33
|
+
readonly model: string;
|
|
34
|
+
readonly timeoutMs: number;
|
|
35
|
+
/** Whether picks from these model ids count at this boundary. */
|
|
36
|
+
readonly trusts: (boundary: Boundary, models: readonly string[]) => boolean;
|
|
37
|
+
/** Told the tokens every call spends, whatever it answers, with the item it was for. */
|
|
38
|
+
readonly onSpent?: (item: string, tokens: number) => void;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** The cheap model call through `claude -p`, as hope's judge calls it, with a typed answer by JSON schema. */
|
|
42
|
+
export const modelCallOver =
|
|
43
|
+
(runner: Runner, { model, timeoutMs, trusts, onSpent }: ModelCallOptions): ModelCall =>
|
|
44
|
+
async ({ boundary, prompt, answer, item, reportOnly }) => {
|
|
45
|
+
const outcome = await runner.run({
|
|
46
|
+
prompt,
|
|
47
|
+
cwd: tmpdir(),
|
|
48
|
+
model,
|
|
49
|
+
effort: "low",
|
|
50
|
+
schema: jsonSchemaOf(answer),
|
|
51
|
+
call: "judgment",
|
|
52
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
if (item !== undefined && (outcome.kind === "finished" || outcome.kind === "over-cap")) onSpent?.(item, outcome.tokens);
|
|
56
|
+
|
|
57
|
+
if (outcome.kind !== "finished") return abstained(NOT_ANSWERED[outcome.kind]);
|
|
58
|
+
|
|
59
|
+
if (!succeeded(outcome)) return abstained(`the call ended as ${outcome.subtype}`);
|
|
60
|
+
|
|
61
|
+
if (reportOnly !== true && !trusts(boundary, outcome.models)) return abstained(`${outcome.models.join(", ") || "no model"} has no measured rate at ${boundary} that meets the bar`);
|
|
62
|
+
|
|
63
|
+
const parsed = answer.safeParse(outcome.structured);
|
|
64
|
+
|
|
65
|
+
return parsed.success ? { kind: "picked", value: parsed.data, models: outcome.models } : abstained("the answer does not match its schema");
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** The model call a config sets up: its decision model, its timeout, and its record of measured model ids. */
|
|
69
|
+
export const configuredModelCall = (runner: Runner, config: Pick<HumConfig, "decisionModel" | "modelCallTimeoutSeconds" | "measuredModels" | "minJudgeRate">, onSpent?: ModelCallOptions["onSpent"]): ModelCall =>
|
|
70
|
+
modelCallOver(runner, {
|
|
71
|
+
model: config.decisionModel,
|
|
72
|
+
timeoutMs: config.modelCallTimeoutSeconds * SECOND_MS,
|
|
73
|
+
trusts: (boundary, models) => isTrusted(models, boundary, config),
|
|
74
|
+
onSpent,
|
|
75
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { Adapter, ThreadEntry } from "../adapter-api.ts";
|
|
3
|
+
import type { OpKeys } from "../state/ops.ts";
|
|
4
|
+
|
|
5
|
+
/** The run and attempt a write belongs to; with the item and the write itself they form its op key. */
|
|
6
|
+
export type CallScope = { readonly run: string; readonly attempt: number };
|
|
7
|
+
|
|
8
|
+
const OP_HASH_LENGTH = 16;
|
|
9
|
+
|
|
10
|
+
type Entry = { readonly kind: ThreadEntry["kind"]; readonly text: string; readonly option?: string };
|
|
11
|
+
|
|
12
|
+
/** The same entry in the same scope is the same op, so writing it twice writes it once. */
|
|
13
|
+
const opName = ({ kind, text, option }: Entry): string => `${kind}:${createHash("sha256").update(`${option ?? ""}\u0000${text}`).digest("hex").slice(0, OP_HASH_LENGTH)}`;
|
|
14
|
+
|
|
15
|
+
/** Whether `thread` already holds `entry`; a provider may append its own lines after the text. */
|
|
16
|
+
const holdsEntry = (thread: readonly ThreadEntry[], { kind, text, option }: Entry): boolean =>
|
|
17
|
+
thread.some((found) => found.kind === kind && found.option === option && (found.text === text || found.text.startsWith(`${text}\n`)));
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `comment`, `ask`, `decide` and `answer` are never retried by the guard, so each runs under an op key. A key a
|
|
21
|
+
* crash left started is settled by reading the item's thread: when the entry is there, the write is skipped.
|
|
22
|
+
*/
|
|
23
|
+
export const onceCalls = (adapter: Adapter, ops: OpKeys, scope: CallScope): Adapter => {
|
|
24
|
+
const { workSource, questions, answers } = adapter;
|
|
25
|
+
|
|
26
|
+
const once = async (itemId: string, entry: Entry, write: () => Promise<void>): Promise<void> => {
|
|
27
|
+
await ops.once(
|
|
28
|
+
{ itemId, ...scope, op: opName(entry) },
|
|
29
|
+
{ holds: async () => (workSource ? holdsEntry((await workSource.read(itemId)).thread, entry) : false), run: write },
|
|
30
|
+
);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
...adapter,
|
|
35
|
+
workSource: workSource && { ...workSource, comment: (id, text) => once(id, { kind: "comment", text }, () => workSource.comment(id, text)) },
|
|
36
|
+
questions: questions && {
|
|
37
|
+
ask: (id, question) => once(id, { kind: "question", text: question.text }, () => questions.ask(id, question)),
|
|
38
|
+
decide: (id, text) => once(id, { kind: "decision", text }, () => questions.decide(id, text)),
|
|
39
|
+
},
|
|
40
|
+
answers: answers && {
|
|
41
|
+
...answers,
|
|
42
|
+
answer: (id, answer) => once(id, { kind: "answer", text: answer.text, option: answer.option }, () => answers.answer(id, answer)),
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { MergeMethod } from "../config/schema.ts";
|
|
2
|
+
import { type PushOutcome, PushRefused } from "./git.ts";
|
|
3
|
+
import { methodFor, type Pull, type PullRequests } from "./pull-requests.ts";
|
|
4
|
+
|
|
5
|
+
export type OwnerCommit = {
|
|
6
|
+
/** The commit to land, already built on the newest base. */
|
|
7
|
+
readonly sha: string;
|
|
8
|
+
readonly base: string;
|
|
9
|
+
/** Names the commit's branch with its sha: what the commit is about, such as an item id. */
|
|
10
|
+
readonly label: string;
|
|
11
|
+
readonly title: string;
|
|
12
|
+
readonly body: string;
|
|
13
|
+
readonly branchPrefix: string;
|
|
14
|
+
readonly mergeMethod: MergeMethod;
|
|
15
|
+
/** Absent off GitHub, where a push is the only way to land. */
|
|
16
|
+
readonly pulls?: PullRequests;
|
|
17
|
+
/** Pushes refspecs to the remote. */
|
|
18
|
+
readonly push: (refspecs: readonly string[]) => Promise<PushOutcome>;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type CommitLanded =
|
|
22
|
+
| { readonly via: "push" }
|
|
23
|
+
| { readonly via: "pull-request"; readonly pull: Pull; readonly merged: boolean }
|
|
24
|
+
/** Another writer moved the base first; the caller builds the commit again. */
|
|
25
|
+
| { readonly via: "conflict" };
|
|
26
|
+
|
|
27
|
+
const throughPullRequest = async (commit: OwnerCommit, pulls: PullRequests): Promise<CommitLanded> => {
|
|
28
|
+
const branch = `${commit.branchPrefix}${commit.label}-${commit.sha.slice(0, 12)}`;
|
|
29
|
+
const rules = await pulls.rules(commit.base);
|
|
30
|
+
|
|
31
|
+
await commit.push([`${commit.sha}:refs/heads/${branch}`]);
|
|
32
|
+
|
|
33
|
+
const pull = (await pulls.find(branch)) ?? (await pulls.open({ head: branch, base: commit.base, title: commit.title, body: commit.body }));
|
|
34
|
+
const armed = pull.state === "MERGED" ? "merged" : await pulls.autoMerge(pull, true, methodFor(commit.mergeMethod, rules.mergeMethods));
|
|
35
|
+
|
|
36
|
+
return { via: "pull-request", pull, merged: armed === "merged" || pull.state === "MERGED" };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Lands a commit the owner wrote. A base that requires a pull request gets one, on a branch of its own that
|
|
41
|
+
* merges itself once the required checks pass; any other base takes a push. A push the remote refuses goes
|
|
42
|
+
* through a pull request when the repo is on GitHub.
|
|
43
|
+
*/
|
|
44
|
+
export const landOwnerCommit = async (commit: OwnerCommit): Promise<CommitLanded> => {
|
|
45
|
+
const { pulls } = commit;
|
|
46
|
+
|
|
47
|
+
if (pulls && (await pulls.rules(commit.base)).requiresPullRequest) return throughPullRequest(commit, pulls);
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const outcome = await commit.push([`${commit.sha}:refs/heads/${commit.base}`]);
|
|
51
|
+
|
|
52
|
+
return outcome === "pushed" ? { via: "push" } : { via: "conflict" };
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (!(error instanceof PushRefused) || !pulls) throw error;
|
|
55
|
+
|
|
56
|
+
await pulls.rules(commit.base, true);
|
|
57
|
+
|
|
58
|
+
return throughPullRequest(commit, pulls);
|
|
59
|
+
}
|
|
60
|
+
};
|