@moo.md/hum 0.0.0 → 0.2.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.
Files changed (110) hide show
  1. package/package.json +2 -2
  2. package/schema/hum.schema.json +2 -2
  3. package/scripts/eval.ts +88 -50
  4. package/src/adapter-api.ts +46 -14
  5. package/src/adapters/admit.ts +2 -2
  6. package/src/adapters/argument.ts +1 -1
  7. package/src/adapters/claim.ts +18 -15
  8. package/src/adapters/claude-bg.ts +72 -32
  9. package/src/adapters/claude-p.ts +26 -25
  10. package/src/adapters/contract.ts +22 -10
  11. package/src/adapters/each-call.ts +9 -0
  12. package/src/adapters/fake.ts +6 -6
  13. package/src/adapters/git.ts +12 -19
  14. package/src/adapters/github-client.ts +102 -0
  15. package/src/adapters/github.ts +50 -136
  16. package/src/adapters/guard.ts +20 -9
  17. package/src/adapters/history.ts +12 -15
  18. package/src/adapters/item-file.ts +1 -1
  19. package/src/adapters/markdown.ts +49 -42
  20. package/src/adapters/marked.ts +15 -13
  21. package/src/adapters/model-call.ts +4 -4
  22. package/src/adapters/once.ts +5 -5
  23. package/src/adapters/owner-commit.ts +13 -11
  24. package/src/adapters/pull-requests.ts +11 -13
  25. package/src/adapters/registry.ts +7 -7
  26. package/src/adapters/roundup.ts +31 -37
  27. package/src/adapters/serial.ts +4 -5
  28. package/src/adapters/transcript.ts +13 -8
  29. package/src/cli/main.ts +1 -0
  30. package/src/cli/ops.ts +32 -14
  31. package/src/cli/service.ts +14 -8
  32. package/src/cli/setup.ts +8 -3
  33. package/src/cli/shared-watch.ts +3 -3
  34. package/src/config/checks.ts +14 -18
  35. package/src/config/machine.ts +5 -7
  36. package/src/config/refusal.ts +7 -0
  37. package/src/config/schema.ts +9 -9
  38. package/src/config/settings.ts +17 -2
  39. package/src/config/state-map.ts +5 -3
  40. package/src/decide/alignment.ts +4 -4
  41. package/src/decide/answer.ts +24 -22
  42. package/src/decide/kind.ts +1 -6
  43. package/src/decide/labels.ts +9 -9
  44. package/src/decide/merge.ts +6 -7
  45. package/src/decide/prose.ts +4 -4
  46. package/src/decide/question.ts +23 -20
  47. package/src/decide/review.ts +4 -2
  48. package/src/decide/risk.ts +25 -19
  49. package/src/decide/taste.ts +3 -3
  50. package/src/exec.ts +10 -4
  51. package/src/index.ts +14 -13
  52. package/src/loop/check-item.ts +3 -3
  53. package/src/loop/ci.ts +1 -1
  54. package/src/loop/github.ts +2 -2
  55. package/src/loop/groups.ts +13 -6
  56. package/src/loop/memory.ts +40 -28
  57. package/src/loop/notes.ts +5 -5
  58. package/src/loop/pair.ts +1 -1
  59. package/src/loop/pass.ts +18 -12
  60. package/src/loop/proof.ts +9 -7
  61. package/src/loop/prove-item.ts +3 -3
  62. package/src/loop/records.ts +12 -13
  63. package/src/loop/signals.ts +6 -6
  64. package/src/measure/inputs.ts +1 -1
  65. package/src/measure/measure.ts +4 -4
  66. package/src/measure/rate.ts +2 -0
  67. package/src/service/ci-tick.ts +2 -2
  68. package/src/service/supervise.ts +3 -2
  69. package/src/service/token.ts +3 -3
  70. package/src/service/wake.ts +2 -2
  71. package/src/service/workflows.ts +2 -2
  72. package/src/setup/propose.ts +4 -4
  73. package/src/setup/prove.ts +20 -14
  74. package/src/setup/scan.ts +31 -24
  75. package/src/setup/shipped.ts +8 -2
  76. package/src/setup/tables.ts +4 -3
  77. package/src/setup/waits.ts +9 -11
  78. package/src/setup/write.ts +17 -10
  79. package/src/slots/pool.ts +32 -24
  80. package/src/state/events.ts +1 -1
  81. package/src/state/faults.ts +13 -5
  82. package/src/state/format.ts +2 -2
  83. package/src/state/items.ts +20 -15
  84. package/src/state/open.ts +2 -2
  85. package/src/state/ops.ts +16 -10
  86. package/src/state/records.ts +5 -5
  87. package/src/state/runs.ts +33 -26
  88. package/src/state/saved.ts +44 -32
  89. package/src/status/file.ts +20 -1
  90. package/src/status/format.ts +47 -57
  91. package/src/status/sections.ts +2 -2
  92. package/src/worker/alignment-report.ts +4 -5
  93. package/src/worker/answers.ts +26 -24
  94. package/src/worker/base-check.ts +4 -5
  95. package/src/worker/checks.ts +25 -11
  96. package/src/worker/kind.ts +23 -19
  97. package/src/worker/land.ts +115 -126
  98. package/src/worker/merged.ts +9 -7
  99. package/src/worker/open.ts +15 -13
  100. package/src/worker/prose-run.ts +3 -3
  101. package/src/worker/questions.ts +15 -12
  102. package/src/worker/scheduler.ts +4 -4
  103. package/src/worker/signature.ts +3 -3
  104. package/src/worker/tally.ts +0 -2
  105. package/src/worker/taste.ts +6 -15
  106. package/src/worker/thin-path.ts +150 -123
  107. package/src/worker/thread.ts +25 -0
  108. package/src/worker/worker.ts +125 -73
  109. package/surface.json +633 -2198
  110. package/src/slots/scan.ts +0 -26
@@ -4,13 +4,13 @@ import { join } from "node:path";
4
4
  import slugify from "@sindresorhus/slugify";
5
5
  import PQueue from "p-queue";
6
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";
7
+ import { type Adapter, ADAPTER_API_VERSION, type AdapterContext, type Claim, type Failed, type Item, ITEM_ID_LENGTH, ItemId, type ItemRef, PermanentError, type ThreadEntry, type Watch } from "../adapter-api.ts";
8
8
  import type { MergeMethod } from "../config/schema.ts";
9
9
  import { parseArgument } from "./argument.ts";
10
10
  import { claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
11
- import { type GitIdentity, gitIn, push, PushRefused, readOrAbsent } from "./git.ts";
11
+ import { type GitIdentity, gitIn, push, readOrAbsent } from "./git.ts";
12
12
  import { appendEntry, type ItemFile, newItemFile, parseItemFile, READY_STATE } from "./item-file.ts";
13
- import { answerMarker, followUpKey, questionText } from "./marked.ts";
13
+ import { answerMarker, followUpBody, followUpKey, questionText } from "./marked.ts";
14
14
  import { type CommitLanded, landOwnerCommit } from "./owner-commit.ts";
15
15
  import type { PullRequests } from "./pull-requests.ts";
16
16
 
@@ -18,6 +18,9 @@ const ITEM_EXTENSION = ".md";
18
18
  const BASE_REF = "refs/hum/base";
19
19
  const CLAIMS_REF = "refs/hum/claims";
20
20
  const NO_BASE_TOKEN = "none";
21
+
22
+ /** The remote the adapter fetches from and pushes to. */
23
+ const REMOTE = "origin";
21
24
  const WRITE_RACE_BACKOFF_MS = 50;
22
25
  const FOLLOW_UP_SLUG_LENGTH = 40;
23
26
 
@@ -30,7 +33,6 @@ export type MarkdownOptions = {
30
33
  readonly itemsDir: string;
31
34
  /** The author and committer of the commits the adapter makes. */
32
35
  readonly identity: GitIdentity;
33
- readonly remote?: string;
34
36
  /** Retries of a write that another writer's push beat. */
35
37
  readonly writeRaceRetries: number;
36
38
  /** Item files read at once; each read is a git process. */
@@ -62,7 +64,7 @@ type View = {
62
64
  };
63
65
 
64
66
  /** 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">;
67
+ type Landed = Extract<CommitLanded["via"], "push" | "pull-request">;
66
68
 
67
69
  /** Another writer moved the base branch between this write's read and its push. */
68
70
  class LostRace extends Error {
@@ -79,7 +81,7 @@ const followUpId = (from: string, title: string): string =>
79
81
  * Every write is a commit built from git plumbing and pushed with hooks off, so the clone's working tree
80
82
  * and branches stay untouched. A claim is the first push of its claim branch; a renewal is a fast-forward on top.
81
83
  */
82
- export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRaceRetries, itemReadsAtOnce, pulls, mergeMethod, ownerBranchPrefix, timeoutMs, remote = "origin", base = "main" }: MarkdownOptions, { report, now }: AdapterContext) => {
84
+ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRaceRetries, itemReadsAtOnce, pulls, mergeMethod, ownerBranchPrefix, timeoutMs, base = "main" }: MarkdownOptions, { report, now }: AdapterContext) => {
83
85
  const git = gitIn(repo, { identity, timeoutMs });
84
86
  const pathOf = (id: string): string => `${itemsDir}/${id}${ITEM_EXTENSION}`;
85
87
  const baseBranch = `refs/heads/${base}`;
@@ -90,7 +92,7 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
90
92
  const refetch = (): Promise<View> => {
91
93
  spent++;
92
94
 
93
- const fetched = git.raw(["fetch", "--prune", "--no-tags", "--quiet", remote, `+${baseBranch}:${BASE_REF}`, `+refs/heads/${claimPrefix}*:${CLAIMS_REF}/*`]).then((): View => ({ sources: new Map() }));
95
+ const fetched = git.raw(["fetch", "--prune", "--no-tags", "--quiet", REMOTE, `+${baseBranch}:${BASE_REF}`, `+refs/heads/${claimPrefix}*:${CLAIMS_REF}/*`]).then((): View => ({ sources: new Map() }));
94
96
 
95
97
  view = fetched;
96
98
  fetched.catch(() => {
@@ -106,23 +108,23 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
106
108
  const pushCounted = async (args: readonly string[]) => {
107
109
  spent++;
108
110
 
109
- const outcome = await push(git, [remote, ...args]).catch((cause: unknown) => {
111
+ const outcome = await push(git, [REMOTE, ...args]).catch((cause: unknown) => {
110
112
  view = undefined;
111
113
 
112
114
  throw cause;
113
115
  });
114
116
 
115
- if (outcome === "conflict") view = undefined;
117
+ if (outcome.kind !== "pushed") view = undefined;
116
118
 
117
119
  return outcome;
118
120
  };
119
121
 
120
122
  const standingFromLine = (line: string): [string, StandingClaim][] => {
121
123
  const [ref = "", sha = "", subject = ""] = line.split("\t");
122
- const item = ref.slice(`${CLAIMS_REF}/`.length);
123
- const claim = claimOfCommit(item, subject);
124
+ const item = ItemId.safeParse(ref.slice(`${CLAIMS_REF}/`.length));
125
+ const claim = item.success ? claimOfCommit(item.data, subject) : undefined;
124
126
 
125
- return claim ? [[item, { claim, sha }]] : [];
127
+ return claim ? [[claim.item, { claim, sha }]] : [];
126
128
  };
127
129
 
128
130
  const readClaims = async (): Promise<ReadonlyMap<string, StandingClaim>> =>
@@ -187,14 +189,16 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
187
189
  const isReady = (file: ItemFile | undefined, standing: StandingClaim | undefined): file is ItemFile => file?.state === READY_STATE && !isLive(standing?.claim, now());
188
190
 
189
191
  const readyRef = async (name: string, claims: ReadonlyMap<string, StandingClaim>): Promise<ItemRef[]> => {
190
- const id = name.slice(0, -ITEM_EXTENSION.length);
192
+ const raw = name.slice(0, -ITEM_EXTENSION.length);
193
+ const parsed = ItemId.safeParse(raw);
191
194
 
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.` });
195
+ if (!parsed.success) {
196
+ report({ code: "item-malformed", item: raw, cause: `${itemsDir}/${name} has a name that is no item id`, fix: `Rename ${itemsDir}/${name} to letters, digits, dot, dash or underscore.` });
194
197
 
195
198
  return [];
196
199
  }
197
200
 
201
+ const id = parsed.data;
198
202
  const file = await loadItem(id);
199
203
 
200
204
  return isReady(file, claims.get(id)) ? [{ id, title: file.title }] : [];
@@ -219,27 +223,21 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
219
223
  }
220
224
  };
221
225
 
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
- });
226
+ /** No retry gets past a remote that said no, so the call fails now, in the remote's words. */
227
+ const refused = (ref: string, said: string): Failed => ({ failed: "now", why: `${said}; let this account push to ${ref}` });
229
228
 
230
- throw error;
231
- };
229
+ const pushToBase = async (sha: string): Promise<Landed | Failed> => {
230
+ const outcome = await pushCounted([`${sha}:${baseBranch}`]);
232
231
 
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)));
232
+ if (outcome.kind === "refused") return refused(base, outcome.said);
235
233
 
236
- if (outcome === "conflict") throw new LostRace(`another writer moved ${base} first`);
234
+ if (outcome.kind === "conflict") throw new LostRace(`another writer moved ${base} first`);
237
235
 
238
236
  return "push";
239
237
  };
240
238
 
241
239
  /** 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> => {
240
+ const landOwned = async (sha: string, message: string, label: string): Promise<Landed | Failed> => {
243
241
  const landed = await landOwnerCommit({
244
242
  sha,
245
243
  base,
@@ -250,35 +248,40 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
250
248
  mergeMethod,
251
249
  pulls,
252
250
  push: pushCounted,
253
- }).catch((cause: unknown) => (cause instanceof PushRefused ? reportRefusal(cause) : Promise.reject(cause)));
251
+ });
252
+
253
+ if (landed.via === "refused") return refused(base, landed.said);
254
254
 
255
255
  if (landed.via === "conflict") throw new LostRace(`another writer moved ${base} first`);
256
256
 
257
257
  return landed.via;
258
258
  };
259
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 () => {
260
+ /** Changes one file on the remote base branch, reading it afresh after every lost race; a write the remote refused answers why. */
261
+ const write = async (message: string, change: () => Promise<FileChange | undefined>, ownedBy?: string): Promise<Failed | undefined> => {
262
+ const attempt = async (): Promise<Failed | undefined> => {
263
263
  await current();
264
264
 
265
265
  const next = await change();
266
266
 
267
- if (!next) return;
267
+ if (!next) return undefined;
268
268
 
269
269
  const sha = await commitOn((await git.raw(["rev-parse", BASE_REF])).trim(), message, next);
270
270
  const landed = ownedBy === undefined ? await pushToBase(sha) : await landOwned(sha, message, ownedBy);
271
271
 
272
272
  if (landed === "push") await mirrorBase(sha, next);
273
- else view = undefined;
273
+ else if (landed === "pull-request") view = undefined;
274
+ else return landed;
275
+
276
+ return undefined;
274
277
  };
275
278
 
276
- await pRetry(attempt, { retries: writeRaceRetries, minTimeout: WRITE_RACE_BACKOFF_MS, randomize: true, shouldRetry: ({ error }) => error instanceof LostRace }).catch((cause: unknown) => {
279
+ return pRetry(attempt, { retries: writeRaceRetries, minTimeout: WRITE_RACE_BACKOFF_MS, randomize: true, shouldRetry: ({ error }) => error instanceof LostRace }).catch((cause: unknown) => {
277
280
  throw cause instanceof LostRace ? new PermanentError(`gave up after ${writeRaceRetries + 1} lost races pushing to ${base}`) : cause;
278
281
  });
279
282
  };
280
283
 
281
- const appendTo = (id: string, entry: Omit<ThreadEntry, "text" | "at">, text: string): Promise<void> =>
284
+ const appendTo = (id: string, entry: Omit<ThreadEntry, "text" | "at">, text: string): Promise<Failed | undefined> =>
282
285
  write(
283
286
  `hum: ${entry.kind} on ${id}`,
284
287
  async () => {
@@ -291,7 +294,7 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
291
294
  entry.kind === "answer" ? id : undefined,
292
295
  );
293
296
 
294
- const take = claimer<StandingClaim>(
297
+ const take = claimer<StandingClaim, Failed>(
295
298
  {
296
299
  standing: async (id) => (await claimsNow()).get(id),
297
300
  isReady: async (id) => (await loadItem(id))?.state === READY_STATE,
@@ -299,7 +302,11 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
299
302
  const parent = over?.sha ?? (await git.raw(["rev-parse", BASE_REF])).trim();
300
303
  const sha = await commitOn(parent, claimCommitMessage(claim));
301
304
 
302
- if ((await pushCounted([`${sha}:refs/heads/${claimPrefix}${claim.item}`])) === "conflict") return false;
305
+ const pushed = await pushCounted([`${sha}:refs/heads/${claimPrefix}${claim.item}`]);
306
+
307
+ if (pushed.kind === "refused") return refused(`${claimPrefix}${claim.item}`, pushed.said);
308
+
309
+ if (pushed.kind === "conflict") return false;
303
310
 
304
311
  await mirrorClaim(claim, sha);
305
312
 
@@ -323,7 +330,7 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
323
330
  };
324
331
 
325
332
  const adapter = {
326
- apiVersion: 1,
333
+ apiVersion: ADAPTER_API_VERSION,
327
334
  /** Fetches and pushes so far. */
328
335
  spent: () => spent,
329
336
  workSource: {
@@ -341,9 +348,9 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
341
348
  fileFollowUp: async (from, { title, body }) => {
342
349
  const id = parseArgument(ItemId, followUpId(parseArgument(ItemId, from), title));
343
350
 
344
- await write(`hum: file ${id}`, async () => ((await itemSource(id)) === undefined ? { path: pathOf(id), content: newItemFile(title, `${body.trim()}\n\nFiled from ${from}.`) } : undefined));
351
+ const failed = await write(`hum: file ${id}`, async () => ((await itemSource(id)) === undefined ? { path: pathOf(id), content: newItemFile(title, followUpBody(body, from)) } : undefined));
345
352
 
346
- return { id, title };
353
+ return failed ?? { id, title };
347
354
  },
348
355
  },
349
356
  questions: {
@@ -354,7 +361,7 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
354
361
  answer: (id, { text, option }) => appendTo(id, answerMarker(option), text),
355
362
  /** The token is the remote base branch's tip; reading one ref spends no rate limit. */
356
363
  watch: async (since?: string): Promise<Watch> => {
357
- const [token = NO_BASE_TOKEN] = (await git.raw(["ls-remote", remote, baseBranch])).split(/\s/).filter(Boolean);
364
+ const [token = NO_BASE_TOKEN] = (await git.raw(["ls-remote", REMOTE, baseBranch])).split(/\s/).filter(Boolean);
358
365
 
359
366
  return { token, changed: token !== since };
360
367
  },
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { z } from "zod";
3
- import { PermanentError, type Question, THREAD_KINDS, type ThreadEntry } from "../adapter-api.ts";
3
+ import { ItemId, type Question, THREAD_KINDS, type ThreadEntry } from "../adapter-api.ts";
4
4
 
5
5
  const OPEN = "<!-- hum ";
6
6
  const CLOSE = " -->";
@@ -12,7 +12,7 @@ export const Marker = z.looseObject({
12
12
  kind: z.enum(THREAD_KINDS),
13
13
  option: z.string().min(1).optional(),
14
14
  options: z.array(z.string()).optional(),
15
- followUp: z.strictObject({ key: z.string(), item: z.string().min(1) }).optional(),
15
+ followUp: z.object({ key: z.string(), item: z.string().min(1) }).optional(),
16
16
  });
17
17
 
18
18
  export type Marker = z.infer<typeof Marker>;
@@ -69,8 +69,16 @@ export const commentText = (text: string): string => text.trim() || EMPTY_COMMEN
69
69
  /** The same follow-up title from the same item always has the same key, so filing it twice files it once. */
70
70
  export const followUpKey = (title: string): string => createHash("sha256").update(title).digest("hex").slice(0, FOLLOW_UP_KEY_LENGTH);
71
71
 
72
+ const filedFrom = (from: string): string => `Filed from ${from}.`;
73
+
72
74
  /** A follow-up's body, which names the item it came from. */
73
- export const followUpBody = (body: string, from: string): string => `${body.trim()}\n\nFiled from ${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));
74
82
 
75
83
  /** The note left on the item a follow-up came from; its marker carries the key that finds the follow-up again. */
76
84
  export const followUpNote = (title: string, item: string) => ({
@@ -86,20 +94,14 @@ export const markerOf = (body: string): Marker | undefined => {
86
94
  };
87
95
 
88
96
  /** The item a follow-up with this title was filed as, read from the notes on the item it came from. */
89
- export const filedFollowUp = (bodies: readonly string[], title: string): string | undefined =>
90
- bodies.map(markerOf).find((marker) => marker?.followUp?.key === followUpKey(title))?.followUp?.item;
97
+ export const filedFollowUp = (bodies: readonly string[], title: string): ItemId | undefined =>
98
+ ItemId.safeParse(bodies.map(markerOf).find((marker) => marker?.followUp?.key === followUpKey(title))?.followUp?.item).data;
91
99
 
92
100
  /** A comment hum writes on a provider's thread. */
93
101
  export const marked = (marker: Marker, text: string): string => `${markerLine(Marker, marker)}\n\n${text.trim()}`;
94
102
 
95
- /** 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. */
96
- export const markedLine = (marker: Marker, text: string, limit: number): string => {
97
- const line = `${markerLine(Marker, marker)} ${text.replaceAll(/\s+/g, " ").trim()}`;
98
-
99
- if (line.length > limit) throw new PermanentError(`this provider's comments hold ${limit} characters; this one needs ${line.length}`);
100
-
101
- return line;
102
- };
103
+ /** The same comment on one line, for a provider whose comments hold one line. */
104
+ export const markedLine = (marker: Marker, text: string): string => `${markerLine(Marker, marker)} ${text.replaceAll(/\s+/g, " ").trim()}`;
103
105
 
104
106
  /** The first lines of `text` on one line, cut so the line with its optional marker and the closing `note` fits `limit`. */
105
107
  export const cutLine = (marker: Marker | undefined, text: string, note: string, limit: number): string => {
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
  import type { Boundary, HumConfig } from "../config/schema.ts";
4
4
  import { isTrusted, jsonSchemaOf } from "../decide/prose.ts";
5
5
  import { SECOND_MS } from "../time.ts";
6
- import { type RunOutcome, type Runner, succeeded } from "./claude-p.ts";
6
+ import { type RunOutcome, type Runner, hasSucceeded } from "./claude-p.ts";
7
7
 
8
8
  /** One question to the cheap model: the boundary it is measured at, the prompt, and the typed answer. */
9
9
  export type Question<T> = { readonly boundary: Boundary; readonly prompt: string; readonly answer: z.ZodType<T>;
@@ -20,12 +20,12 @@ export type Judgment<T> =
20
20
 
21
21
  export type ModelCall = <T>(question: Question<T>) => Promise<Judgment<T>>;
22
22
 
23
- const NOT_ANSWERED: Readonly<Record<Exclude<RunOutcome, { kind: "finished" }>["kind"], string>> = {
23
+ const NOT_ANSWERED = {
24
24
  limited: "a usage limit refused the call",
25
25
  held: "the runner is held",
26
26
  "over-cap": "the call passed its token cap",
27
27
  stopped: "the call timed out",
28
- };
28
+ } as const satisfies Record<Exclude<RunOutcome, { kind: "finished" }>["kind"], string>;
29
29
 
30
30
  const abstained = (why: string) => ({ kind: "abstained", why }) as const;
31
31
 
@@ -56,7 +56,7 @@ export const modelCallOver =
56
56
 
57
57
  if (outcome.kind !== "finished") return abstained(NOT_ANSWERED[outcome.kind]);
58
58
 
59
- if (!succeeded(outcome)) return abstained(`the call ended as ${outcome.subtype}`);
59
+ if (!hasSucceeded(outcome)) return abstained(`the call ended as ${outcome.subtype}`);
60
60
 
61
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
62
 
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { Adapter, ThreadEntry } from "../adapter-api.ts";
2
+ import type { Integrations, ItemId, ThreadEntry } from "../adapter-api.ts";
3
3
  import type { OpKeys } from "../state/ops.ts";
4
4
 
5
5
  /** The run and attempt a write belongs to; with the item and the write itself they form its op key. */
@@ -13,20 +13,20 @@ type Entry = { readonly kind: ThreadEntry["kind"]; readonly text: string; readon
13
13
  const opName = ({ kind, text, option }: Entry): string => `${kind}:${createHash("sha256").update(`${option ?? ""}\u0000${text}`).digest("hex").slice(0, OP_HASH_LENGTH)}`;
14
14
 
15
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 =>
16
+ const hasEntry = (thread: readonly ThreadEntry[], { kind, text, option }: Entry): boolean =>
17
17
  thread.some((found) => found.kind === kind && found.option === option && (found.text === text || found.text.startsWith(`${text}\n`)));
18
18
 
19
19
  /**
20
20
  * `comment`, `ask`, `decide` and `answer` are never retried by the guard, so each runs under an op key. A key a
21
21
  * crash left started is settled by reading the item's thread: when the entry is there, the write is skipped.
22
22
  */
23
- export const onceCalls = (adapter: Adapter, ops: OpKeys, scope: CallScope): Adapter => {
23
+ export const onceCalls = (adapter: Integrations, ops: OpKeys, scope: CallScope): Integrations => {
24
24
  const { workSource, questions, answers } = adapter;
25
25
 
26
- const once = async (itemId: string, entry: Entry, write: () => Promise<void>): Promise<void> => {
26
+ const once = async (itemId: ItemId, entry: Entry, write: () => Promise<void>): Promise<void> => {
27
27
  await ops.once(
28
28
  { itemId, ...scope, op: opName(entry) },
29
- { holds: async () => (workSource ? holdsEntry((await workSource.read(itemId)).thread, entry) : false), run: write },
29
+ { holds: async () => (workSource ? hasEntry((await workSource.read(itemId)).thread, entry) : false), run: write },
30
30
  );
31
31
  };
32
32
 
@@ -1,5 +1,5 @@
1
1
  import type { MergeMethod } from "../config/schema.ts";
2
- import { type PushOutcome, PushRefused } from "./git.ts";
2
+ import type { PushOutcome } from "./git.ts";
3
3
  import { methodFor, type Pull, type PullRequests } from "./pull-requests.ts";
4
4
 
5
5
  export type OwnerCommit = {
@@ -22,13 +22,17 @@ export type CommitLanded =
22
22
  | { readonly via: "push" }
23
23
  | { readonly via: "pull-request"; readonly pull: Pull; readonly merged: boolean }
24
24
  /** Another writer moved the base first; the caller builds the commit again. */
25
- | { readonly via: "conflict" };
25
+ | { readonly via: "conflict" }
26
+ /** The remote refused the push, in `said`, and the repo is not on GitHub, so no pull request can land it. */
27
+ | { readonly via: "refused"; readonly said: string };
26
28
 
27
29
  const throughPullRequest = async (commit: OwnerCommit, pulls: PullRequests): Promise<CommitLanded> => {
28
30
  const branch = `${commit.branchPrefix}${commit.label}-${commit.sha.slice(0, 12)}`;
29
31
  const rules = await pulls.rules(commit.base);
30
32
 
31
- await commit.push([`${commit.sha}:refs/heads/${branch}`]);
33
+ const pushed = await commit.push([`${commit.sha}:refs/heads/${branch}`]);
34
+
35
+ if (pushed.kind === "refused") return { via: "refused", said: pushed.said };
32
36
 
33
37
  const pull = (await pulls.find(branch)) ?? (await pulls.open({ head: branch, base: commit.base, title: commit.title, body: commit.body }));
34
38
  const armed = pull.state === "MERGED" ? "merged" : await pulls.autoMerge(pull, true, methodFor(commit.mergeMethod, rules.mergeMethods));
@@ -46,15 +50,13 @@ export const landOwnerCommit = async (commit: OwnerCommit): Promise<CommitLanded
46
50
 
47
51
  if (pulls && (await pulls.rules(commit.base)).requiresPullRequest) return throughPullRequest(commit, pulls);
48
52
 
49
- try {
50
- const outcome = await commit.push([`${commit.sha}:refs/heads/${commit.base}`]);
53
+ const outcome = await commit.push([`${commit.sha}:refs/heads/${commit.base}`]);
54
+
55
+ if (outcome.kind !== "refused") return { via: outcome.kind === "pushed" ? "push" : "conflict" };
51
56
 
52
- return outcome === "pushed" ? { via: "push" } : { via: "conflict" };
53
- } catch (error) {
54
- if (!(error instanceof PushRefused) || !pulls) throw error;
57
+ if (!pulls) return { via: "refused", said: outcome.said };
55
58
 
56
- await pulls.rules(commit.base, true);
59
+ await pulls.rules(commit.base, true);
57
60
 
58
- return throughPullRequest(commit, pulls);
59
- }
61
+ return throughPullRequest(commit, pulls);
60
62
  };
@@ -3,13 +3,8 @@ import pMemoize from "p-memoize";
3
3
  import { z } from "zod";
4
4
  import type { Json } from "../config/json.ts";
5
5
  import { MERGE_METHODS, type MergeMethod } from "../config/schema.ts";
6
- import {
7
- type GitHubClient,
8
- gitHubClient,
9
- MERGE_METHOD,
10
- ownerToken,
11
- raise,
12
- } from "./github.ts";
6
+ import type { Env } from "../exec.ts";
7
+ import { type GitHubClient, MERGE_METHOD, ownerGitHub, raise } from "./github-client.ts";
13
8
 
14
9
  /** What the target branch's rules ask of a change that lands on it. */
15
10
  export type BranchRules = {
@@ -46,6 +41,8 @@ export type PullRequests = {
46
41
  on: boolean,
47
42
  method: MergeMethod,
48
43
  ) => Promise<"armed" | "merged" | "off">;
44
+ /** Merges the pull request now. */
45
+ readonly merge: (pull: Pull, method: MergeMethod) => Promise<void>;
49
46
  readonly update: (pull: Pull) => Promise<void>;
50
47
  /** One comment on the pull request. */
51
48
  readonly comment: (pull: Pull, body: string) => Promise<void>;
@@ -142,13 +139,10 @@ export const methodFor = (
142
139
  /** Pull requests and branch rules of a GitHub repo, on the owner's own login unless a client is given. `timeoutMs` bounds the `gh auth token` that reads that login. */
143
140
  export const gitHubPullRequests = (
144
141
  repo: string,
145
- { timeoutMs, client }: { readonly timeoutMs: number; readonly client?: GitHubClient },
142
+ options: { readonly timeoutMs: number } & ({ readonly client: () => Promise<GitHubClient> } | { readonly env: Env }),
146
143
  ): PullRequests => {
147
144
  const [owner = "", name = ""] = repo.split("/");
148
-
149
- const connect = pMemoize(
150
- async () => client ?? gitHubClient({ token: await ownerToken(timeoutMs) }),
151
- );
145
+ const connect = "client" in options ? options.client : () => ownerGitHub(options.timeoutMs, options.env);
152
146
 
153
147
  const rulesCache = new Map<string, BranchRules>();
154
148
 
@@ -188,6 +182,9 @@ export const gitHubPullRequests = (
188
182
  { cache: rulesCache },
189
183
  );
190
184
 
185
+ const merge = async (pull: Pull, method: MergeMethod): Promise<void> =>
186
+ void (await graphql(Acknowledged, MERGE_NOW, { pull: pull.id, mergeMethod: MERGE_METHOD[method] }));
187
+
191
188
  const find = async (head: string): Promise<Pull | undefined> => {
192
189
  const node = (await graphql(PullsReply, PULLS, { head })).repository
193
190
  .pullRequests.nodes[0];
@@ -241,10 +238,11 @@ export const gitHubPullRequests = (
241
238
 
242
239
  if (armed) return "armed";
243
240
 
244
- await graphql(Acknowledged, MERGE_NOW, { pull: pull.id, mergeMethod });
241
+ await merge(pull, method);
245
242
 
246
243
  return "merged";
247
244
  },
245
+ merge,
248
246
  update: async (pull) =>
249
247
  void (await graphql(Acknowledged, UPDATE_BRANCH, { pull: pull.id })),
250
248
  comment: async (pull, body) =>
@@ -2,10 +2,10 @@ import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { z } from "zod";
5
- import { ADAPTER_API_VERSION, type Adapter, type AdapterContext, type AdapterFactory, PermanentError } from "../adapter-api.ts";
5
+ import { ADAPTER_API_VERSION, type Adapter, type AdapterContext, type AdapterFactory, type Integrations, PermanentError } from "../adapter-api.ts";
6
6
  import { readSettings } from "../config/settings.ts";
7
7
  import { HumConfig } from "../config/schema.ts";
8
- import { commandTimeoutMs } from "../exec.ts";
8
+ import { commandTimeoutMs, type Env } from "../exec.ts";
9
9
  import type { Faults } from "../state/faults.ts";
10
10
  import type { Card } from "../status/format.ts";
11
11
  import { githubAdapter, repoFromRemote } from "./github.ts";
@@ -61,10 +61,10 @@ const defaultBase = async (repo: string, timeoutMs: number): Promise<string> =>
61
61
  };
62
62
 
63
63
  /** The pull requests of the repo's `origin` when it is on GitHub. */
64
- const originPulls = async (repo: string, timeoutMs: number): Promise<PullRequests | undefined> => {
64
+ const originPulls = async (repo: string, timeoutMs: number, env: Env): Promise<PullRequests | undefined> => {
65
65
  const found = repoFromRemote(await gitIn(repo, { timeoutMs }).raw(["remote", "get-url", "origin"]).catch(whenGitFailed("")));
66
66
 
67
- return found === undefined ? undefined : gitHubPullRequests(found, { timeoutMs });
67
+ return found === undefined ? undefined : gitHubPullRequests(found, { timeoutMs, env });
68
68
  };
69
69
 
70
70
  const githubRepo = async (repo: string, timeoutMs: number): Promise<string> => {
@@ -80,7 +80,7 @@ const BUILT_IN = {
80
80
  [MARKDOWN]: async ({ path, settings, context }) => {
81
81
  const timeoutMs = commandTimeoutMs(settings);
82
82
 
83
- return markdownAdapter({ repo: path, base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, itemsDir: settings.itemsDir, identity: settings.commitIdentity, writeRaceRetries: settings.writeRaceRetries, itemReadsAtOnce: settings.itemReadsAtOnce, pulls: await originPulls(path, timeoutMs), mergeMethod: settings.mergeMethod, ownerBranchPrefix: settings.ownerBranchPrefix, timeoutMs }, context);
83
+ return markdownAdapter({ repo: path, base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, itemsDir: settings.itemsDir, identity: settings.commitIdentity, writeRaceRetries: settings.writeRaceRetries, itemReadsAtOnce: settings.itemReadsAtOnce, pulls: await originPulls(path, timeoutMs, context.env), mergeMethod: settings.mergeMethod, ownerBranchPrefix: settings.ownerBranchPrefix, timeoutMs }, context);
84
84
  },
85
85
  github: async ({ path, settings, context }) => {
86
86
  const timeoutMs = commandTimeoutMs(settings);
@@ -125,7 +125,7 @@ export const refuseOtherVersion = (name: string, adapter: Adapter, faults: Fault
125
125
  export const resolveAdapters = async (
126
126
  repo: string,
127
127
  { faults, guard, context }: { faults: Faults; guard: Pick<GuardOptions, "lastReady">; context: AdapterContext },
128
- ): Promise<Partial<Record<Slot, Adapter>>> => {
128
+ ): Promise<Partial<Record<Slot, Integrations>>> => {
129
129
  const settings = readSettings(repo, AdapterSettings);
130
130
 
131
131
  const slots = SLOTS.flatMap((slot) => {
@@ -136,7 +136,7 @@ export const resolveAdapters = async (
136
136
 
137
137
  const source: Repo = { path: repo, settings, context };
138
138
 
139
- const build = async (name: string): Promise<Adapter> => {
139
+ const build = async (name: string): Promise<Integrations> => {
140
140
  const adapter = await (isBuiltIn(name) ? BUILT_IN[name](source) : ownerAdapter(name, source));
141
141
 
142
142
  if (refuseOtherVersion(name, adapter, faults)) throw new PermanentError(`adapter "${name}" implements another adapter API version`);