@moo.md/hum 0.1.0 → 0.3.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 (112) hide show
  1. package/defaults/hum.json +9 -2
  2. package/package.json +2 -2
  3. package/schema/hum.schema.json +208 -7
  4. package/scripts/eval.ts +88 -50
  5. package/src/adapter-api.ts +46 -14
  6. package/src/adapters/admit.ts +2 -2
  7. package/src/adapters/argument.ts +1 -1
  8. package/src/adapters/claim.ts +18 -15
  9. package/src/adapters/claude-bg.ts +50 -27
  10. package/src/adapters/claude-p.ts +18 -23
  11. package/src/adapters/contract.ts +22 -10
  12. package/src/adapters/each-call.ts +9 -0
  13. package/src/adapters/fake.ts +6 -6
  14. package/src/adapters/git.ts +10 -18
  15. package/src/adapters/github-client.ts +102 -0
  16. package/src/adapters/github.ts +61 -146
  17. package/src/adapters/guard.ts +20 -9
  18. package/src/adapters/history.ts +12 -15
  19. package/src/adapters/item-file.ts +1 -1
  20. package/src/adapters/markdown.ts +49 -42
  21. package/src/adapters/marked.ts +6 -12
  22. package/src/adapters/model-call.ts +4 -4
  23. package/src/adapters/once.ts +5 -5
  24. package/src/adapters/owner-commit.ts +13 -11
  25. package/src/adapters/pull-requests.ts +11 -13
  26. package/src/adapters/registry.ts +9 -8
  27. package/src/adapters/roundup.ts +27 -35
  28. package/src/adapters/serial.ts +4 -5
  29. package/src/adapters/transcript.ts +13 -8
  30. package/src/cli/main.ts +1 -0
  31. package/src/cli/ops.ts +32 -14
  32. package/src/cli/service.ts +14 -8
  33. package/src/cli/setup.ts +22 -7
  34. package/src/cli/shared-watch.ts +3 -3
  35. package/src/config/checks.ts +27 -18
  36. package/src/config/machine.ts +5 -7
  37. package/src/config/migrate.ts +5 -2
  38. package/src/config/refusal.ts +15 -2
  39. package/src/config/schema.ts +74 -12
  40. package/src/config/settings.ts +17 -2
  41. package/src/config/state-map.ts +5 -3
  42. package/src/config/wake-job.ts +74 -0
  43. package/src/decide/alignment.ts +4 -4
  44. package/src/decide/answer.ts +24 -22
  45. package/src/decide/kind.ts +1 -6
  46. package/src/decide/labels.ts +9 -9
  47. package/src/decide/merge.ts +6 -7
  48. package/src/decide/prose.ts +4 -4
  49. package/src/decide/question.ts +23 -20
  50. package/src/decide/review.ts +4 -2
  51. package/src/decide/risk.ts +25 -19
  52. package/src/decide/taste.ts +3 -3
  53. package/src/exec.ts +4 -3
  54. package/src/index.ts +14 -13
  55. package/src/loop/check-item.ts +3 -3
  56. package/src/loop/ci.ts +1 -1
  57. package/src/loop/github.ts +2 -2
  58. package/src/loop/groups.ts +13 -6
  59. package/src/loop/memory.ts +40 -28
  60. package/src/loop/notes.ts +5 -5
  61. package/src/loop/pair.ts +1 -1
  62. package/src/loop/pass.ts +18 -12
  63. package/src/loop/proof.ts +9 -7
  64. package/src/loop/prove-item.ts +1 -1
  65. package/src/loop/records.ts +12 -13
  66. package/src/loop/signals.ts +6 -6
  67. package/src/measure/inputs.ts +1 -1
  68. package/src/measure/measure.ts +4 -4
  69. package/src/measure/rate.ts +2 -0
  70. package/src/service/ci-tick.ts +2 -2
  71. package/src/service/supervise.ts +3 -2
  72. package/src/service/token.ts +3 -3
  73. package/src/service/wake.ts +2 -2
  74. package/src/service/workflows.ts +165 -48
  75. package/src/setup/propose.ts +78 -7
  76. package/src/setup/prove.ts +18 -12
  77. package/src/setup/scan.ts +91 -28
  78. package/src/setup/shipped.ts +8 -2
  79. package/src/setup/tables.ts +22 -3
  80. package/src/setup/waits.ts +9 -11
  81. package/src/setup/write.ts +67 -27
  82. package/src/slots/pool.ts +32 -24
  83. package/src/state/events.ts +1 -1
  84. package/src/state/faults.ts +13 -5
  85. package/src/state/format.ts +2 -2
  86. package/src/state/items.ts +9 -10
  87. package/src/state/open.ts +2 -2
  88. package/src/state/ops.ts +16 -10
  89. package/src/state/records.ts +5 -5
  90. package/src/state/runs.ts +33 -26
  91. package/src/state/saved.ts +44 -32
  92. package/src/status/file.ts +20 -1
  93. package/src/status/format.ts +47 -57
  94. package/src/status/sections.ts +2 -2
  95. package/src/worker/alignment-report.ts +4 -5
  96. package/src/worker/answers.ts +26 -24
  97. package/src/worker/base-check.ts +2 -2
  98. package/src/worker/kind.ts +23 -19
  99. package/src/worker/land.ts +114 -126
  100. package/src/worker/merged.ts +9 -7
  101. package/src/worker/open.ts +14 -12
  102. package/src/worker/prose-run.ts +3 -3
  103. package/src/worker/questions.ts +15 -12
  104. package/src/worker/scheduler.ts +4 -4
  105. package/src/worker/signature.ts +3 -3
  106. package/src/worker/tally.ts +0 -2
  107. package/src/worker/taste.ts +6 -15
  108. package/src/worker/thin-path.ts +148 -121
  109. package/src/worker/thread.ts +25 -0
  110. package/src/worker/worker.ts +77 -47
  111. package/surface.json +1091 -2251
  112. package/src/slots/scan.ts +0 -26
@@ -6,6 +6,7 @@ import { PLAIN_QUESTIONS } from "../decide/question.ts";
6
6
  import type { State } from "../state/open.ts";
7
7
  import type { ItemKind } from "../state/saved.ts";
8
8
  import { queueQuestion, releaseQuestions } from "./questions.ts";
9
+ import { pickedAnswer } from "./thread.ts";
9
10
 
10
11
  export type KindContext = {
11
12
  readonly state: State;
@@ -17,7 +18,7 @@ export type KindContext = {
17
18
  };
18
19
 
19
20
  /** Why the model call gave no kind it may use. */
20
- const noKind = async (o: KindContext, item: Item, kinds: readonly string[]): Promise<{ kind: string } | { why: string }> => {
21
+ const noKind = async (o: Pick<KindContext, "config" | "judge">, item: Item, kinds: readonly string[]): Promise<{ kind: string } | { why: string }> => {
21
22
  const judged = await o.judge({ ...kindQuestion(item, { kinds, kindMeanings: o.config.hum.kindMeanings }), item: item.id });
22
23
 
23
24
  if (judged.kind === "abstained") return { why: judged.why };
@@ -25,41 +26,44 @@ const noKind = async (o: KindContext, item: Item, kinds: readonly string[]): Pro
25
26
  return judged.value.kind === UNSURE ? { why: "the model call could not tell" } : { kind: judged.value.kind };
26
27
  };
27
28
 
29
+ /** The kinds an item may be: every kind but `except`, for an item whose change showed it is not that kind. */
30
+ const kindsBut = (o: Pick<KindContext, "config">, except: string | undefined): string[] => o.config.hum.kinds.filter((kind) => kind !== except);
31
+
28
32
  /**
29
- * An item's kind, decided once and saved: the name its source gives it, else the model call's pick from the kinds,
30
- * else the fallback kind. A fallback is an abstention: the item is unclear, and one question asks the owner for its kind.
31
- * `except` leaves one kind out, for an item whose change showed it is not that kind.
33
+ * An item's kind: the name its source gives it, else the model call's pick from the kinds, else the fallback kind.
34
+ * A fallback is an abstention: the item is unclear.
32
35
  */
33
- export const decideKind = async (o: KindContext, item: Item, except?: string): Promise<ItemKind> => {
34
- const kinds = o.config.hum.kinds.filter((kind) => kind !== except);
36
+ export const pickKind = async (o: Pick<KindContext, "config" | "judge">, item: Item, except?: string): Promise<ItemKind> => {
37
+ const kinds = kindsBut(o, except);
35
38
  const declared = declaredKind(item, kinds, o.config.hum.kindLabels);
36
- const picked = declared === undefined ? await noKind(o, item, kinds) : undefined;
37
39
 
38
- const decided: ItemKind =
39
- declared !== undefined
40
- ? { item: item.id, kind: declared, from: "source" }
41
- : picked && "kind" in picked
42
- ? { item: item.id, kind: picked.kind, from: "model" }
43
- : { item: item.id, kind: o.config.hum.fallbackKind, from: "fallback", why: picked?.why ?? "no kind named" };
40
+ if (declared !== undefined) return { item: item.id, kind: declared, from: "source" };
41
+
42
+ const picked = await noKind(o, item, kinds);
43
+
44
+ return "kind" in picked ? { item: item.id, kind: picked.kind, from: "model" } : { item: item.id, kind: o.config.hum.fallbackKind, from: "fallback", why: picked.why };
45
+ };
44
46
 
45
- o.state.itemKinds.put(item.id, decided);
47
+ /** Saves the item's kind and, for a fallback, asks the owner once for it; returns the kind's name. */
48
+ export const keepKind = async (o: KindContext, item: Item, kind: ItemKind, except?: string): Promise<string> => {
49
+ o.state.itemKinds.put(item.id, kind);
46
50
 
47
- if (decided.from === "fallback") {
48
- queueQuestion(o, item, { text: PLAIN_QUESTIONS.kind, options: kinds, detail: `It runs as ${decided.kind} for now.` }, "kind");
51
+ if (kind.from === "fallback") {
52
+ queueQuestion(o, item, { text: PLAIN_QUESTIONS.kind, options: kindsBut(o, except), detail: `It runs as ${kind.kind} for now.` }, "kind");
49
53
  await releaseQuestions(o);
50
54
  }
51
55
 
52
- return decided;
56
+ return kind.kind;
53
57
  };
54
58
 
55
59
  /** The kind the owner named in answer to the kind question, for an item still on its fallback kind. */
56
60
  export const kindAnswered = (known: ItemKind, item: Item, kinds: readonly string[]): ItemKind | undefined => {
57
- const answer = known.from === "fallback" ? item.thread.findLast((entry) => entry.kind === "answer" && entry.option !== undefined && kinds.includes(entry.option)) : undefined;
61
+ const answer = known.from === "fallback" ? pickedAnswer(item.thread, kinds) : undefined;
58
62
 
59
63
  return answer?.option === undefined ? undefined : { item: item.id, kind: answer.option, from: "source" };
60
64
  };
61
65
 
62
- /** Drops what an item's run on its earlier kind left: its snapshot, its landing, its plan and its verdict. Its branch stays. */
66
+ /** Drops what an item's run on its earlier kind left: its snapshot, its landing, its plan and its verdict. Its next run restarts its branch at the base. */
63
67
  export const forgetProgress = (state: State, id: string): void => {
64
68
  state.items.remove(id);
65
69
  state.landings.remove(id);
@@ -1,7 +1,6 @@
1
1
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
- import pRetry from "p-retry";
5
4
  import { z } from "zod";
6
5
  import {
7
6
  type Item,
@@ -14,26 +13,27 @@ import {
14
13
  isAncestor,
15
14
  PATCH,
16
15
  push,
17
- PushRefused,
16
+ type PushOutcome,
18
17
  } from "../adapters/git.ts";
19
- import { type CommitLanded, landOwnerCommit } from "../adapters/owner-commit.ts";
18
+ import { landOwnerCommit } from "../adapters/owner-commit.ts";
20
19
  import { commandTimeoutMs } from "../exec.ts";
21
20
  import { changeOf, historiesOf, readHistory } from "../adapters/history.ts";
22
21
  import { markDone } from "../adapters/item-file.ts";
23
22
  import {
24
23
  type BranchRules,
25
24
  methodFor,
25
+ type Pull,
26
26
  type PullRequests,
27
27
  } from "../adapters/pull-requests.ts";
28
28
  import type { ModelCall } from "../adapters/model-call.ts";
29
29
  import type { Config } from "../config/load.ts";
30
30
  import type { Boundary } from "../config/schema.ts";
31
- import { alignedPlacement, alignmentQuestion, gatesAlignment } from "../decide/alignment.ts";
31
+ import { alignedPlacement, alignmentQuestion, doesGateAlignment } from "../decide/alignment.ts";
32
32
  import {
33
33
  isCleared,
34
34
  type Landing,
35
35
  landingOf,
36
- needsReviewRun,
36
+ doesNeedReviewRun,
37
37
  OWNER_APPROVAL,
38
38
  type Route,
39
39
  routeOf,
@@ -54,6 +54,7 @@ import { checksTimeoutMs, runChecks } from "./checks.ts";
54
54
  import { recordMerged } from "./merged.ts";
55
55
  import { blockedPaths, brokenCommits } from "../loop/breaks.ts";
56
56
  import { queueQuestion, releaseQuestions } from "./questions.ts";
57
+ import { pickedAnswer } from "./thread.ts";
57
58
  import { reportAlignment } from "./alignment-report.ts";
58
59
  import { reportTaste } from "./taste.ts";
59
60
  import type { ThinResult } from "./thin-path.ts";
@@ -67,6 +68,9 @@ const NO_RULES: BranchRules = {
67
68
  mergeMethods: undefined,
68
69
  };
69
70
 
71
+ /** A change's pull request as it stands at one head of the run branch, which a report on it is made once for. */
72
+ export type PullAtHead = { readonly pulls: PullRequests; readonly pull: Pull; readonly head: string };
73
+
70
74
  /** Everything landing a finished change reads and writes. The clone has the run branch checked out and the base fetched. */
71
75
  export type LandContext = {
72
76
  readonly state: State;
@@ -97,17 +101,22 @@ export type LandContext = {
97
101
  export type ReviewOutcome = { readonly verdict: Verdict } | { readonly halted: ThinResult };
98
102
 
99
103
  /** The review verdict that lets a change merge. */
100
- export const REVIEW_APPROVAL = "approve";
104
+ const REVIEW_APPROVAL = "approve";
105
+
106
+ /** Why the change cannot merge on the newest base: it conflicts there, or its checks fail there. */
107
+ type Stale = { readonly kind: "stale"; readonly why: string };
108
+
109
+ /** A push that did not land: the remote refused it in `said`, or another writer moved the ref first. */
110
+ type Unpushed = Exclude<PushOutcome, { kind: "pushed" }>;
101
111
 
102
- /** The change cannot merge on the newest base: it conflicts, or its checks fail there. */
103
- class StaleMerge extends Error {
104
- override name = "StaleMerge";
105
- }
112
+ /** A push that did not land, as the pass's result: the remote's refusal ends the item stuck in its words; a push another writer beat waits for the next pass. */
113
+ export const unpushed = (id: string, ref: string, outcome: Unpushed): ThinResult =>
114
+ outcome.kind === "refused" ? { outcome: "stuck", item: id, detail: outcome.said } : { outcome: "held", item: id, why: `another push moved ${ref} first` };
106
115
 
107
- /** Another writer moved the base between the fetch and the push. */
108
- class BaseMoved extends Error {
109
- override name = "BaseMoved";
110
- }
116
+ /** How a push to the base ended: the base holds the change, it cannot merge on the newest base, or the push did not land. */
117
+ type BaseLanding = { readonly kind: "landed" } | Stale | Unpushed;
118
+
119
+ const LANDED: BaseLanding = { kind: "landed" };
111
120
 
112
121
  /** The glob a new path rule takes for a path no rule places: its folder, or the file itself at the top. */
113
122
  export const ruleGlobFor = (path: string): string =>
@@ -160,26 +169,8 @@ export const changeOn = async ({
160
169
  }: Pick<LandContext, "git" | "base" | "config">): Promise<Change> =>
161
170
  changeOf(await git.raw(["diff", ...PATCH, `origin/${base}...HEAD`]), config.hum);
162
171
 
163
- const isOwnerApproval =
164
- (since: number) =>
165
- (entry: Item["thread"][number]): boolean =>
166
- entry.kind === "answer" &&
167
- entry.option === OWNER_APPROVAL &&
168
- entry.at >= since;
169
-
170
172
  /** The level the owner picked for unclear paths, answered since the change was saved. */
171
- const answeredLevel = (
172
- item: Item,
173
- since: number,
174
- levels: readonly string[],
175
- ): string | undefined =>
176
- item.thread.findLast(
177
- (entry) =>
178
- entry.kind === "answer" &&
179
- entry.at >= since &&
180
- entry.option !== undefined &&
181
- levels.includes(entry.option),
182
- )?.option;
173
+ const answeredLevel = (item: Item, since: number, levels: readonly string[]): string | undefined => pickedAnswer(item.thread, levels, since)?.option;
183
174
 
184
175
  const askUnclear = async (ctx: LandContext, unclear: readonly string[]): Promise<void> => {
185
176
  const globs = [...new Set(unclear.map(ruleGlobFor))];
@@ -190,12 +181,12 @@ const askUnclear = async (ctx: LandContext, unclear: readonly string[]): Promise
190
181
 
191
182
  const RawPaths = z.looseObject({ paths: z.array(z.unknown()).default([]) });
192
183
 
193
- /** Commits the owner's answer as path rules in the base's `hum.json`, with hooks off, and saves them for the view's undo. */
184
+ /** Commits the owner's answer as path rules in the base's `hum.json`, with hooks off, and saves them for the view's undo. Returns why the rules did not land, or nothing once they did. */
194
185
  const learnRules = async (
195
186
  ctx: LandContext,
196
187
  unclear: readonly string[],
197
188
  level: string,
198
- ): Promise<CommitLanded> => {
189
+ ): Promise<Unpushed | undefined> => {
199
190
  const { state, config, id, base, remote, now } = ctx;
200
191
  const globs = [...new Set(unclear.map(ruleGlobFor))];
201
192
  const scratch = mkdtempSync(join(tmpdir(), "hum-rule-"));
@@ -245,22 +236,21 @@ const learnRules = async (
245
236
  push: (refspecs) => push(git, ["origin", ...refspecs]),
246
237
  });
247
238
 
248
- if (landed.via === "conflict")
249
- throw new Error(
250
- `another push moved ${base} before the path rule for ${id} landed`,
251
- );
239
+ if (landed.via === "refused") return { kind: "refused", said: landed.said };
240
+
241
+ if (landed.via === "conflict") return { kind: "conflict" };
252
242
 
253
243
  for (const glob of globs)
254
244
  state.learned.put(glob, { glob, level, item: id, commit, pull: landed.via === "pull-request" ? landed.pull.url : undefined, at: now() });
255
245
 
256
- return landed;
246
+ return undefined;
257
247
  } finally {
258
248
  rmSync(scratch, { recursive: true, force: true });
259
249
  }
260
250
  };
261
251
 
262
252
  /** Marks the item done on the run branch, pushes the branch and saves what its diff showed, so a retry lands it without a run. `ownerApproved` records that the owner approved this change in its review state. */
263
- export const prepareLanding = async (ctx: LandContext, ownerApproved = false): Promise<void> => {
253
+ export const prepareLanding = async (ctx: LandContext, { ownerApproved = false }: { readonly ownerApproved?: boolean } = {}): Promise<PushOutcome> => {
264
254
  const { git, clone, dir, id, branch, state, now } = ctx;
265
255
  const change = await changeOn(ctx);
266
256
  const head = (await git.raw(["rev-parse", "HEAD"])).trim();
@@ -269,80 +259,74 @@ export const prepareLanding = async (ctx: LandContext, ownerApproved = false): P
269
259
  writeFileSync(file, markDone(readFileSync(file, "utf8")));
270
260
  await git.raw(["add", `${dir}/${id}.md`]);
271
261
  await git.raw(["commit", "-q", "-m", `hum: finish ${id}`]);
272
- await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
273
- state.landings.put(id, { item: id, branch, since: now(), change: { ...change, paths: [...change.paths] }, head, ownerApproved });
262
+ const pushed = await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
263
+
264
+ if (pushed.kind === "pushed") state.landings.put(id, { item: id, branch, since: now(), change, head, ownerApproved });
265
+
266
+ return pushed;
274
267
  };
275
268
 
276
- /** A merge is rechecked on the newest base: when the base moved, the change is rebased and the checks run again. */
277
- const pushOntoNewestBase = async ({
278
- git,
279
- base,
280
- branch,
281
- clone,
282
- env,
283
- checks,
284
- config,
285
- }: LandContext): Promise<void> => {
269
+ /** Whether the base already holds the change, as after a push whose op was not marked done. */
270
+ const isOnBase = async ({ git, base }: LandContext): Promise<boolean> => {
286
271
  await git.raw(["fetch", "-q", "origin", base]);
287
272
 
288
- if (!(await isAncestor(git, `origin/${base}`, "HEAD"))) {
289
- const rebased = await git.run(["rebase", "-q", `origin/${base}`]);
273
+ return isAncestor(git, { ancestor: "HEAD", descendant: `origin/${base}` });
274
+ };
275
+
276
+ /** The change on the newest base: when the base moved it is rebased and the checks run again; else why it cannot merge there. */
277
+ const ontoNewestBase = async ({ git, base, clone, env, checks, config }: LandContext): Promise<Stale | undefined> => {
278
+ await git.raw(["fetch", "-q", "origin", base]);
290
279
 
291
- if (rebased.code !== 0) {
292
- await git.run(["rebase", "--abort"]);
280
+ if (await isAncestor(git, { ancestor: `origin/${base}`, descendant: "HEAD" })) return undefined;
293
281
 
294
- throw new StaleMerge(
295
- `the change conflicts with the newest ${base}: ${rebased.stderr.trim().slice(0, SHORT_EXCERPT)}`,
296
- );
297
- }
282
+ const rebased = await git.run(["rebase", "-q", `origin/${base}`]);
298
283
 
299
- const failure = await runChecks(checks, clone, { env, timeoutMs: checksTimeoutMs(config.hum) });
284
+ if (rebased.code !== 0) {
285
+ await git.run(["rebase", "--abort"]);
300
286
 
301
- if (failure)
302
- throw new StaleMerge(
303
- `the checks fail on the newest ${base}: ${failure.slice(0, SHORT_EXCERPT)}`,
304
- );
287
+ return { kind: "stale", why: `the change conflicts with the newest ${base}: ${rebased.stderr.trim().slice(0, SHORT_EXCERPT)}` };
305
288
  }
306
289
 
307
- await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
290
+ const failure = await runChecks(checks, clone, { env, timeoutMs: checksTimeoutMs(config.hum) });
308
291
 
309
- if ((await push(git, ["origin", `HEAD:refs/heads/${base}`])) === "conflict")
310
- throw new BaseMoved(`another push moved ${base} first`);
292
+ return failure ? { kind: "stale", why: `the checks fail on the newest ${base}: ${failure.slice(0, SHORT_EXCERPT)}` } : undefined;
293
+ };
294
+
295
+ const pushBranchAndBase = async ({ git, base, branch }: LandContext): Promise<PushOutcome> => {
296
+ const toBranch = await push(git, ["--force", "origin", `HEAD:refs/heads/${branch}`]);
297
+
298
+ return toBranch.kind === "pushed" ? push(git, ["origin", `HEAD:refs/heads/${base}`]) : toBranch;
311
299
  };
312
300
 
313
301
  const finish = async ({ state, git, id, now }: LandContext): Promise<ThinResult> => {
314
- recordMerged(state, id, (await git.raw(["rev-parse", "HEAD"])).trim(), now());
302
+ recordMerged(state, { item: id, sha: (await git.raw(["rev-parse", "HEAD"])).trim(), at: now() });
315
303
 
316
304
  return { outcome: "merged", item: id };
317
305
  };
318
306
 
319
- const pushToBase = async (ctx: LandContext): Promise<void> => {
320
- await ctx.state.ops.once(
321
- { itemId: ctx.id, run: "merge", attempt: 0, op: "push-base" },
322
- {
323
- holds: async () => {
324
- await ctx.git.raw(["fetch", "-q", "origin", ctx.base]);
325
-
326
- return isAncestor(ctx.git, "HEAD", `origin/${ctx.base}`);
327
- },
328
- run: () =>
329
- pRetry(() => pushOntoNewestBase(ctx), {
330
- retries: ctx.config.hum.mergeTries - 1,
331
- minTimeout: 0,
332
- shouldRetry: ({ error }) => error instanceof BaseMoved,
333
- }),
334
- },
335
- );
307
+ /** Pushes the change to the base once, rechecked on the newest base before each try; a base another push moved first is tried again, up to `mergeTries` pushes. */
308
+ const pushToBase = async (ctx: LandContext): Promise<BaseLanding> => {
309
+ if (await isOnBase(ctx)) return LANDED;
310
+
311
+ for (let tries = 0; tries < ctx.config.hum.mergeTries; tries++) {
312
+ const stale = await ontoNewestBase(ctx);
313
+
314
+ if (stale) return stale;
315
+
316
+ const pushed = await ctx.state.ops.once({ itemId: ctx.id, run: "merge", attempt: 0, op: "push-base" }, { holds: () => isOnBase(ctx), run: () => pushBranchAndBase(ctx), isDone: ({ kind }) => kind === "pushed" });
317
+
318
+ if (pushed.kind === "skipped" || pushed.value.kind === "pushed") return LANDED;
319
+
320
+ if (pushed.value.kind === "refused") return pushed.value;
321
+ }
322
+
323
+ return { kind: "conflict" };
336
324
  };
337
325
 
338
326
  /** One pull request from the run branch: it merges itself once GitHub's required checks pass when the change is cleared, and waits for the owner otherwise. */
339
327
  const throughPullRequest = async (
340
328
  ctx: LandContext,
341
- pulls: PullRequests,
342
- autoMerge: boolean,
343
- route: Route,
344
- rules: BranchRules,
345
- why: string,
329
+ { pulls, autoMerge, route, rules, why }: { readonly pulls: PullRequests; readonly autoMerge: boolean; readonly route: Route; readonly rules: BranchRules; readonly why: string },
346
330
  ): Promise<ThinResult> => {
347
331
  const { id, branch, base, item, config } = ctx;
348
332
  const body = `${autoMerge ? `Level ${route.level.name}: it merges once the required checks pass.` : `Not merged by hum: ${why}.`}\n\nItem ${id}.`;
@@ -365,10 +349,10 @@ const throughPullRequest = async (
365
349
  detail: `its pull request was closed unmerged: ${pull.url}`,
366
350
  };
367
351
 
368
- const head = ctx.state.landings.get(id)?.head ?? branch;
352
+ const atHead: PullAtHead = { pulls, pull, head: ctx.state.landings.get(id)?.head ?? branch };
369
353
 
370
- await reportTaste(ctx, pulls, pull, head);
371
- await reportAlignment(ctx, pulls, pull, head);
354
+ await reportTaste(ctx, atHead);
355
+ await reportAlignment(ctx, atHead);
372
356
 
373
357
  const armed = await pulls.autoMerge(
374
358
  pull,
@@ -383,28 +367,31 @@ const throughPullRequest = async (
383
367
  return { outcome: "landing", item: id, detail: pull.url };
384
368
  };
385
369
 
386
- /** A push the remote refused, on GitHub: the rules are read again and the change goes through a pull request. */
370
+ /** A push the remote refused: on GitHub the rules are read again and the change goes through a pull request; elsewhere the item ends stuck in the remote's words. */
387
371
  const afterRefusal = async (
388
372
  ctx: LandContext,
389
- cleared: boolean,
390
- route: Route,
391
- why: string,
373
+ { cleared, route, why, said }: { readonly cleared: boolean; readonly route: Route; readonly why: string; readonly said: string },
392
374
  ): Promise<ThinResult> => {
393
- if (!ctx.pulls)
394
- throw new PushRefused(
395
- `the remote refused the push of ${ctx.id} to ${ctx.base}, and it is not on GitHub`,
396
- );
375
+ if (!ctx.pulls) return unpushed(ctx.id, ctx.base, { kind: "refused", said: `${said}; ${ctx.base} is not on GitHub, so no pull request can land it` });
397
376
 
398
377
  return throughPullRequest(
399
378
  ctx,
400
- ctx.pulls,
401
- cleared,
402
- route,
403
- await ctx.pulls.rules(ctx.base, true),
404
- why,
379
+ { pulls: ctx.pulls, autoMerge: cleared, route, rules: await ctx.pulls.rules(ctx.base, true), why },
405
380
  );
406
381
  };
407
382
 
383
+ /** The card of a base that other pushes kept moving through every one of `mergeTries` pushes. It stands while the item stays held; the pass that decides the item another way clears it. */
384
+ export const BASE_CONTENDED = "base-contended";
385
+
386
+ /** One card while the item's pushes to the base keep losing the race, however many passes that lasts. */
387
+ const raiseContention = ({ state, id, base, config }: LandContext): void =>
388
+ void state.faults.raise({
389
+ code: BASE_CONTENDED,
390
+ item: id,
391
+ cause: `${id} lost the race to ${base} on all ${config.hum.mergeTries} pushes of a pass: another push moved ${base} first each time`,
392
+ fix: `hum tries again each pass. If this card stays, find what keeps pushing to ${base}, or raise mergeTries in .hum/hum.json.`,
393
+ });
394
+
408
395
  const landBy = async (
409
396
  ctx: LandContext,
410
397
  landing: Landing,
@@ -416,20 +403,19 @@ const landBy = async (
416
403
  return { outcome: "review", item: ctx.id, detail: why };
417
404
 
418
405
  if (landing.via === "pull-request" && ctx.pulls)
419
- return throughPullRequest(ctx, ctx.pulls, landing.autoMerge, route, rules, why);
406
+ return throughPullRequest(ctx, { pulls: ctx.pulls, autoMerge: landing.autoMerge, route, rules, why });
420
407
 
421
- try {
422
- await pushToBase(ctx);
408
+ const landed = await pushToBase(ctx);
423
409
 
424
- return await finish(ctx);
425
- } catch (error) {
426
- if (error instanceof StaleMerge)
427
- return { outcome: "review", item: ctx.id, detail: error.message };
410
+ if (landed.kind === "refused") return afterRefusal(ctx, { cleared: true, route, why, said: landed.said });
428
411
 
429
- if (error instanceof PushRefused) return afterRefusal(ctx, true, route, why);
412
+ if (landed.kind === "conflict") {
413
+ raiseContention(ctx);
430
414
 
431
- throw error;
415
+ return unpushed(ctx.id, ctx.base, landed);
432
416
  }
417
+
418
+ return landed.kind === "stale" ? { outcome: "review", item: ctx.id, detail: landed.why } : finish(ctx);
433
419
  };
434
420
 
435
421
  /**
@@ -445,7 +431,9 @@ export const land = async (ctx: LandContext): Promise<ThinResult> => {
445
431
  const answered = answeredLevel(ctx.item, saved.since, levelNames(ctx.config));
446
432
  const learns = first.placement.unclear.length > 0 && answered !== undefined;
447
433
 
448
- if (learns) await learnRules(ctx, first.placement.unclear, answered);
434
+ const unlearned = learns ? await learnRules(ctx, first.placement.unclear, answered) : undefined;
435
+
436
+ if (unlearned) return unpushed(ctx.id, ctx.base, unlearned);
449
437
 
450
438
  const { placement, policy } = learns
451
439
  ? await placementOf(ctx, saved.change)
@@ -455,20 +443,20 @@ export const land = async (ctx: LandContext): Promise<ThinResult> => {
455
443
 
456
444
  const diff = await ctx.git.raw(["diff", ...PATCH, `origin/${ctx.base}...${saved.head}`]);
457
445
  const alignment = saved.change.paths.length > 0 ? await alignmentOf(ctx, saved, diff) : undefined;
458
- const aligned = gatesAlignment(ctx.config.hum) && alignment && "graded" in alignment ? alignedPlacement(placement, alignment.graded, ctx.config.hum) : placement;
446
+ const aligned = doesGateAlignment(ctx.config.hum) && alignment && "graded" in alignment ? alignedPlacement(placement, alignment.graded, ctx.config.hum) : placement;
459
447
  const routeWith = (verdict?: Verdict): Route => routeOf(aligned, policy.paths, ctx.kind, saved.change.paths, abstentionsOf(ctx, alignment, verdict));
460
448
  const placed = routeWith();
461
- const reviewed = needsReviewRun(placed) ? await verdictOn(ctx, { head: saved.head, diff, level: placed.level.name }) : undefined;
449
+ const reviewed = doesNeedReviewRun(placed) ? await verdictOn(ctx, { head: saved.head, diff, level: placed.level.name }) : undefined;
462
450
 
463
451
  if (reviewed && "halted" in reviewed) return reviewed.halted;
464
452
 
465
453
  const verdict = reviewed?.verdict;
466
454
  const route = routeWith(verdict);
467
- const approvals = { review: verdict?.event === REVIEW_APPROVAL, owner: saved.ownerApproved || ctx.item.thread.some(isOwnerApproval(saved.since)) };
455
+ const approvals = { review: verdict?.event === REVIEW_APPROVAL, owner: saved.ownerApproved || pickedAnswer(ctx.item.thread, [OWNER_APPROVAL], saved.since) !== undefined };
468
456
  const why = verdict && verdict.event !== REVIEW_APPROVAL ? `the review run answered ${verdict.event}: ${verdict.reason}` : waitReason(route);
469
457
  const rules = ctx.pulls ? await ctx.pulls.rules(ctx.base) : NO_RULES;
470
458
 
471
- return landBy(ctx, landingOf(rules.requiresPullRequest, isCleared(route, approvals)), route, rules, why);
459
+ return landBy(ctx, landingOf({ requiresPullRequest: rules.requiresPullRequest, cleared: isCleared(route, approvals) }), route, rules, why);
472
460
  };
473
461
 
474
462
  /** The alignment call's grades for a saved change, made once and kept with the landing. */
@@ -496,14 +484,14 @@ const unmeasured = (models: readonly string[]): string => `${models.join(", ") |
496
484
 
497
485
  /** Every model judgment behind the change that abstained, or came from a model id its boundary was not measured on. */
498
486
  const abstentionsOf = (ctx: LandContext, alignment: SavedLanding["alignment"], verdict: Verdict | undefined): Unclear[] => {
499
- const measured = (boundary: Boundary, models: readonly string[]): boolean => isTrusted(models, boundary, ctx.config.hum);
487
+ const isMeasured = (boundary: Boundary, models: readonly string[]): boolean => isTrusted(models, boundary, ctx.config.hum);
500
488
  const kind = ctx.state.itemKinds.get(ctx.id);
501
489
  const plan = ctx.state.plans.get(ctx.id);
502
490
 
503
491
  return [
504
492
  ...(kind?.from === "fallback" ? [abstained("kind", kind.why)] : []),
505
- ...(gatesAlignment(ctx.config.hum) && alignment && "abstained" in alignment ? [abstained("alignment", alignment.abstained)] : []),
506
- ...(plan && !measured("plan-outcome", plan.models) ? [abstained("plan-outcome", unmeasured(plan.models))] : []),
507
- ...(verdict && !measured("review-verdict", verdict.models) ? [abstained("review-verdict", unmeasured(verdict.models))] : []),
493
+ ...(doesGateAlignment(ctx.config.hum) && alignment && "abstained" in alignment ? [abstained("alignment", alignment.abstained)] : []),
494
+ ...(plan && !isMeasured("plan-outcome", plan.models) ? [abstained("plan-outcome", unmeasured(plan.models))] : []),
495
+ ...(verdict && !isMeasured("review-verdict", verdict.models) ? [abstained("review-verdict", unmeasured(verdict.models))] : []),
508
496
  ];
509
497
  };
@@ -5,10 +5,10 @@ import type { State } from "../state/open.ts";
5
5
  * An item's change reached the base: the merge is kept for the measure, the saved landing, plan and verdict go,
6
6
  * and the merge is logged once per commit.
7
7
  */
8
- export const recordMerged = (state: State, item: string, sha: string, at: number): void => {
8
+ export const recordMerged = (state: State, { item, sha, at }: { readonly item: string; readonly sha: string; readonly at: number }): void => {
9
9
  const landing = state.landings.get(item);
10
10
 
11
- state.merges.put(item, { item, sha, at, paths: landing?.change.paths ?? [] });
11
+ state.merges.put(item, { item, sha, at, paths: [...(landing?.change.paths ?? [])] });
12
12
  state.landings.remove(item);
13
13
  state.plans.remove(item);
14
14
  state.verdicts.remove(item);
@@ -20,10 +20,12 @@ export const recordMerged = (state: State, item: string, sha: string, at: number
20
20
  * listed again. Each saved landing whose pull request has merged is recorded as merged, so the measure counts it.
21
21
  */
22
22
  export const settleMergedPulls = async (state: State, pulls: Pick<PullRequests, "find">, at: number): Promise<void> => {
23
- for (const { item, branch, head } of state.landings.list()) {
24
- if ((await pulls.find(branch))?.state !== "MERGED") continue;
23
+ await Promise.all(
24
+ state.landings.list().map(async ({ item, branch, head }) => {
25
+ if ((await pulls.find(branch))?.state !== "MERGED") return;
25
26
 
26
- recordMerged(state, item, head, at);
27
- state.items.remove(item);
28
- }
27
+ recordMerged(state, { item, sha: head, at });
28
+ state.items.remove(item);
29
+ }),
30
+ );
29
31
  };
@@ -1,30 +1,32 @@
1
1
  import { join } from "node:path";
2
2
  import { z } from "zod";
3
- import type { Adapter } from "../adapter-api.ts";
3
+ import type { Integrations } from "../adapter-api.ts";
4
4
  import { resolveAdapters } from "../adapters/registry.ts";
5
5
  import { startBackgroundRunner } from "../adapters/claude-bg.ts";
6
6
  import { startRunner } from "../adapters/claude-p.ts";
7
7
  import { gitIn } from "../adapters/git.ts";
8
- import { gitHubClient, ownerToken, repoFromRemote } from "../adapters/github.ts";
8
+ import { repoFromRemote } from "../adapters/github.ts";
9
+ import { ownerGitHub } from "../adapters/github-client.ts";
9
10
  import { githubLoopReads } from "../loop/github.ts";
10
11
  import { gitHubPullRequests } from "../adapters/pull-requests.ts";
11
12
  import { serialized } from "../adapters/serial.ts";
12
13
  import { SlotPool } from "../slots/pool.ts";
13
14
  import { loadConfig, readConfigDir } from "../config/load.ts";
14
15
  import type { HumConfig } from "../config/schema.ts";
15
- import { commandTimeoutMs } from "../exec.ts";
16
+ import { commandTimeoutMs, type Env } from "../exec.ts";
16
17
  import { defaultStateDir, openState } from "../state/open.ts";
17
18
  import { DEFAULT_BASE } from "./thin-path.ts";
18
19
  import { Worker, type WorkerOptions } from "./worker.ts";
19
20
 
20
- export type OpenWorkerOptions = Omit<WorkerOptions, "repo" | "state" | "config" | "adapters" | "runner" | "remote" | "pulls" | "loop" | "checks"> & {
21
+ export type OpenWorkerOptions = Omit<WorkerOptions, "repo" | "state" | "config" | "adapters" | "runner" | "remote" | "pulls" | "loop" | "checks" | "runnerVariables"> & {
21
22
  /** Where saved state lives; default `<git common dir>/hum`. */
22
23
  readonly stateDir?: string;
23
24
  /** The skill names of hope's installed copy; a role that names another is refused. */
24
25
  readonly hopeSkills: ReadonlySet<string>;
25
26
  readonly remote?: string;
26
27
  readonly binary?: string;
27
- readonly env?: Readonly<Record<string, string>>;
28
+ /** The process environment: runs start with it, and the GitHub login and adapters read it. */
29
+ readonly env: Env;
28
30
  };
29
31
 
30
32
  const Latest = z.looseObject({ version: z.string().min(1) });
@@ -51,7 +53,7 @@ const isInBackground = ({ backgroundRuns }: Pick<HumConfig, "backgroundRuns">, w
51
53
  */
52
54
  export const openWorker = async (repo: string, options: OpenWorkerOptions): Promise<Worker> => {
53
55
  const { stateDir, hopeSkills, binary, env, ...rest } = options;
54
- const now = rest.now ?? Date.now;
56
+ const { now } = rest;
55
57
  const state = openState(stateDir ?? (await defaultStateDir(repo)), { now });
56
58
  const loaded = loadConfig(readConfigDir(join(repo, ".hum")), { env: { hopeSkills } });
57
59
 
@@ -69,13 +71,13 @@ export const openWorker = async (repo: string, options: OpenWorkerOptions): Prom
69
71
  const adapters = await resolveAdapters(repo, {
70
72
  faults: state.faults,
71
73
  guard: { lastReady: { load: () => state.ready.get("work-source")?.ids ?? [], save: (ids) => state.ready.put("work-source", { ids }) } },
72
- context: { report: (fault) => void state.faults.raise(fault), now },
74
+ context: { report: (fault) => void state.faults.raise(fault), now, env },
73
75
  });
74
76
 
75
77
  // One adapter serves several slots; its calls go one at a time whichever slot they come through.
76
- const ordered = new Map<Adapter, Adapter>();
78
+ const ordered = new Map<Integrations, Integrations>();
77
79
 
78
- const inOrder = (adapter: Adapter | undefined): Adapter | undefined => {
80
+ const inOrder = (adapter: Integrations | undefined): Integrations | undefined => {
79
81
  if (adapter && !ordered.has(adapter)) ordered.set(adapter, serialized(adapter));
80
82
 
81
83
  return adapter && ordered.get(adapter);
@@ -93,8 +95,8 @@ export const openWorker = async (repo: string, options: OpenWorkerOptions): Prom
93
95
  // A slot is a worktree a background run starts in, so the pool stands only where runs are background agents.
94
96
  const slots = config.hum.runSlots.enabled && isInBackground(config.hum, rest.where) ? new SlotPool({ repo, state, config: config.hum, base: rest.base ?? DEFAULT_BASE, liveRuns: runner.liveRuns, now }) : undefined;
95
97
  const github = repoFromRemote(remote);
96
- const pulls = github === undefined ? undefined : gitHubPullRequests(github, { timeoutMs });
97
- const loop = github === undefined ? undefined : githubLoopReads(github, rest.base ?? DEFAULT_BASE, config.hum.measureWindow, async () => gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs }));
98
+ const pulls = github === undefined ? undefined : gitHubPullRequests(github, { timeoutMs, env });
99
+ const loop = github === undefined ? undefined : githubLoopReads(github, rest.base ?? DEFAULT_BASE, config.hum.measureWindow, () => ownerGitHub(timeoutMs, env));
98
100
 
99
- return new Worker({ ...rest, checks: config.hum.checks, checkout: rest.checkout ?? slots?.checkout, slots, repo, state, config, adapters: { workSource, questions, answers }, runner, remote, pulls, loop });
101
+ return new Worker({ ...rest, checks: config.hum.checks, checkout: rest.checkout ?? slots?.checkout, slots, repo, state, config, adapters: { workSource, questions, answers }, runner, remote, pulls, loop, runnerVariables: new Set(Object.keys(env)) });
100
102
  };
@@ -1,11 +1,11 @@
1
1
  import { type AgentDecisionExecutor, createDecisionRequest, getMessageText, renderDecisionAttempts, resolveDecision } from "@statelyai/agent";
2
- import { type Finished, succeeded } from "../adapters/claude-p.ts";
2
+ import { type Finished, hasSucceeded } from "../adapters/claude-p.ts";
3
3
  import { type EventPick, type JsonSchema, PROSE_STATES, type ProsePurpose, pickSchema, readPick } from "../decide/prose.ts";
4
4
 
5
5
  const RESULT_EXCERPT = 300;
6
6
 
7
7
  /** One agent run answering in `schema`. It settles only with a finished run; a limit, a hold or a stop never settles it. */
8
- export type AnswerRun = (prompt: string, schema: JsonSchema) => Promise<Finished>;
8
+ type AnswerRun = (prompt: string, schema: JsonSchema) => Promise<Finished>;
9
9
 
10
10
  export type ProseDecision = { readonly pick: EventPick; readonly models: readonly string[] };
11
11
 
@@ -36,7 +36,7 @@ export const decideProse = async ({ purpose, prompt, diff, model, run, canTake =
36
36
  const feedback = renderDecisionAttempts(request).map(getMessageText);
37
37
  const outcome = await run([prompt, offer(offered), ...feedback].join("\n\n"), pickSchema(offered));
38
38
 
39
- if (!succeeded(outcome)) return { rejected: { failure: "invalid-payload", reason: `the run ended as ${outcome.subtype}: ${outcome.text.slice(0, RESULT_EXCERPT)}` } };
39
+ if (!hasSucceeded(outcome)) return { rejected: { failure: "invalid-payload", reason: `the run ended as ${outcome.subtype}: ${outcome.text.slice(0, RESULT_EXCERPT)}` } };
40
40
 
41
41
  const read = readPick(purpose, outcome, diff);
42
42