@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
@@ -1,9 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { stripVTControlCharacters } from "node:util";
3
3
  import parseDiff from "parse-diff";
4
- import stringify from "safe-stable-stringify";
5
4
  import { z } from "zod";
6
5
  import type { Finished } from "../adapters/claude-p.ts";
6
+ import { hashJson } from "../config/hash.ts";
7
7
  import type { Boundary, HumConfig } from "../config/schema.ts";
8
8
 
9
9
  const TAG_HASH = 12;
@@ -41,7 +41,7 @@ export const PlanFile = z.strictObject({
41
41
  export type PlanFile = z.infer<typeof PlanFile>;
42
42
 
43
43
  /** A plan's identity: a later run reads the plan with this hash, and any other text is not the approved plan. */
44
- export const planHash = (plan: PlanFile): string => createHash("sha256").update(stringify(plan)).digest("hex");
44
+ export const planHash = (plan: PlanFile): string => hashJson(plan);
45
45
 
46
46
  /** The two states whose outcome is prose: the events each may pick, and the safer pick an unsure run takes. */
47
47
  export const PROSE_STATES = {
@@ -75,7 +75,7 @@ export const pickSchema = (events: readonly string[]): JsonSchema => jsonSchemaO
75
75
  const isInHunk = (line: number, { newStart, newLines }: { newStart: number; newLines: number }): boolean => line >= newStart && line < newStart + Math.max(newLines, 1);
76
76
 
77
77
  /** At least one cite, and each names a file the diff changes and a line inside one of its hunks. */
78
- export const citesDiff = (cites: readonly Cite[], diff: string): boolean => {
78
+ export const doesCiteDiff = (cites: readonly Cite[], diff: string): boolean => {
79
79
  const files = parseDiff(diff);
80
80
  const isChanged = ({ file, line }: Cite): boolean => files.some((changed) => changed.to === file && changed.chunks.some((hunk) => isInHunk(line, hunk)));
81
81
 
@@ -84,7 +84,7 @@ export const citesDiff = (cites: readonly Cite[], diff: string): boolean => {
84
84
 
85
85
  /** Code's check on the artifact behind a pick: why it fails, or undefined when it holds. */
86
86
  const FENCES = new Map<string, (pick: EventPick, diff: string) => string | undefined>([
87
- ["request-changes", (pick, diff) => (citesDiff(pick.cites, diff) ? undefined : "request-changes must cite a file and a line the diff changes")],
87
+ ["request-changes", (pick, diff) => (doesCiteDiff(pick.cites, diff) ? undefined : "request-changes must cite a file and a line the diff changes")],
88
88
  ["plan-ready", (pick) => (pick.plan ? undefined : "plan-ready must hold a plan: a summary, at least one step and the paths it touches")],
89
89
  ]);
90
90
 
@@ -4,9 +4,9 @@ import type { HumConfig } from "../config/schema.ts";
4
4
  import { DAY_MS } from "../time.ts";
5
5
 
6
6
  /** The reasons a run gives for needing the owner, each with the facts code checks it against. */
7
- export const ASK_REASONS = ["missing-secret", "past-undoing", "spends-money", "publishes", "choice", "unsure"] as const;
7
+ const ASK_REASONS = ["missing-secret", "past-undoing", "spends-money", "publishes", "choice", "unsure"] as const;
8
8
 
9
- export type AskReason = (typeof ASK_REASONS)[number];
9
+ type AskReason = (typeof ASK_REASONS)[number];
10
10
 
11
11
  const ChoiceOption = z.strictObject({ word: z.string().min(1), paths: z.array(z.string().min(1)) });
12
12
 
@@ -33,29 +33,29 @@ export type AskFacts = {
33
33
  readonly undoableLevels: readonly string[];
34
34
  };
35
35
 
36
- export type AskDecision =
36
+ type AskDecision =
37
37
  /** `confirmed`: the facts bear the reason out, so its own question is asked; otherwise the owner gets the plain one. */
38
38
  | { readonly action: "ask"; readonly reason: AskReason; readonly confirmed: boolean }
39
39
  | { readonly action: "decide"; readonly choice: string; readonly over: readonly string[] };
40
40
 
41
- /** A choice is cheap to undo when every option touches only the change's own files, on a level where that is safe. */
42
- const isCheapChoice = ({ options = [], default: chosen }: RunReason, { changedPaths, level, undoableLevels }: AskFacts): boolean =>
43
- options.some(({ word }) => word === chosen) && undoableLevels.includes(level) && options.every(({ paths }) => paths.every((path) => changedPaths.includes(path)));
41
+ /** The run's own pick, when the choice is cheap to undo: every option touches only the change's own files, on a level where that is safe. */
42
+ const cheapPick = ({ options = [], default: chosen }: RunReason, { changedPaths, level, undoableLevels }: AskFacts): string | undefined =>
43
+ undoableLevels.includes(level) && options.every(({ paths }) => paths.every((path) => changedPaths.includes(path))) ? options.find(({ word }) => word === chosen)?.word : undefined;
44
44
 
45
- const CONFIRMS: Readonly<Record<AskReason, (reason: RunReason, facts: AskFacts) => boolean>> = {
45
+ const CONFIRMS = {
46
46
  "missing-secret": ({ variable }, { runnerVariables }) => variable !== undefined && !runnerVariables.has(variable),
47
47
  "past-undoing": ({ command }) => command !== undefined,
48
48
  "spends-money": () => true,
49
49
  publishes: () => true,
50
50
  choice: () => false,
51
51
  unsure: () => true,
52
- };
52
+ } as const satisfies Record<AskReason, (reason: RunReason, facts: AskFacts) => boolean>;
53
53
 
54
54
  /** Whether the owner is asked: a reason the facts cannot confirm still asks, and a cheap choice is made without them. */
55
55
  export const askDecision = (reason: RunReason, facts: AskFacts): AskDecision => {
56
- if (reason.kind === "choice" && isCheapChoice(reason, facts)) {
57
- return { action: "decide", choice: reason.default ?? "", over: (reason.options ?? []).map(({ word }) => word) };
58
- }
56
+ const choice = reason.kind === "choice" ? cheapPick(reason, facts) : undefined;
57
+
58
+ if (choice !== undefined) return { action: "decide", choice, over: (reason.options ?? []).map(({ word }) => word) };
59
59
 
60
60
  return { action: "ask", reason: reason.kind, confirmed: CONFIRMS[reason.kind](reason, facts) };
61
61
  };
@@ -86,10 +86,10 @@ const ASKED = {
86
86
  unsure: () => PLAIN_QUESTIONS.unsure,
87
87
  } as const satisfies Record<AskReason, (reason: RunReason) => string>;
88
88
 
89
- export type AskedQuestion = { readonly question: Question; readonly plain: PlainQuestion };
89
+ type AskedQuestion = { readonly question: Question; readonly plain: PlainQuestion };
90
90
 
91
91
  /** The question a run's need becomes. A reason the facts bear out asks its own question with the run's words folded; any other asks in the run's words. */
92
- export const askedQuestion = (reason: RunReason, confirmed: boolean, runsWords: string | undefined): AskedQuestion => {
92
+ export const askedQuestion = ({ reason, confirmed, runsWords }: { readonly reason: RunReason; readonly confirmed: boolean; readonly runsWords: string | undefined }): AskedQuestion => {
93
93
  const kind = confirmed ? reason.kind : "unsure";
94
94
  const options = reason.options?.map(({ word }) => word);
95
95
 
@@ -105,7 +105,7 @@ const SIDE_QUESTIONS: readonly string[] = [PLAIN_QUESTIONS.kind, PLAIN_QUESTIONS
105
105
  export const isWaitQuestion = (text: string): boolean => !SIDE_QUESTIONS.includes(text);
106
106
 
107
107
  /** Why a question text is refused. */
108
- export type QuestionIssue = "too-wide" | "no-question-mark" | "names-item" | "long-word";
108
+ type QuestionIssue = "too-wide" | "no-question-mark" | "names-item" | "long-word";
109
109
 
110
110
  const QUESTION_MARK = "?";
111
111
 
@@ -113,11 +113,14 @@ const words = (text: string): string[] => text.split(/\s+/).filter(Boolean);
113
113
 
114
114
  const cellsOf = (text: string): number => Bun.stringWidth(text);
115
115
 
116
- const WORD_EDGES = /^\W+|\W+$/g;
116
+ const WORD_EDGES = /^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu;
117
+
118
+ /** A word without the punctuation around it. */
119
+ export const bareWord = (word: string): string => word.replaceAll(WORD_EDGES, "");
117
120
 
118
121
  /** The question text rules: at most `cells` wide, ends in "?", names no item id, and no word over `wordCells`. */
119
- export const questionIssues = (text: string, item: string, { cells, wordCells }: HumConfig["questionLimits"]): QuestionIssue[] => {
120
- const mentionsItem = words(text).some((word) => word.replaceAll(WORD_EDGES, "") === item);
122
+ export const questionIssues = ({ text, item, limits: { cells, wordCells } }: { readonly text: string; readonly item: string; readonly limits: HumConfig["questionLimits"] }): QuestionIssue[] => {
123
+ const mentionsItem = words(text).some((word) => bareWord(word) === item);
121
124
 
122
125
  return [
123
126
  ...(cellsOf(text) > cells ? (["too-wide"] as const) : []),
@@ -129,7 +132,7 @@ export const questionIssues = (text: string, item: string, { cells, wordCells }:
129
132
 
130
133
  /** A question to put on the thread: the run's own text when it passes the rules, else the plain one with the run's text folded. */
131
134
  export const composeQuestion = (draft: Question, plain: PlainQuestion, item: string, limits: HumConfig["questionLimits"]): Question => {
132
- if (questionIssues(draft.text, item, limits).length === 0) return draft;
135
+ if (questionIssues({ text: draft.text, item, limits }).length === 0) return draft;
133
136
 
134
137
  return { ...draft, text: PLAIN_QUESTIONS[plain], detail: [draft.text, draft.detail].filter(Boolean).join("\n\n") };
135
138
  };
@@ -148,12 +151,12 @@ export type Waiting = {
148
151
  export const questionOrder = (a: Waiting, b: Waiting): number => a.priority - b.priority || b.behind - a.behind || a.since - b.since;
149
152
 
150
153
  /** The priority of an item: the index of its first label in the owner's list, or past the end when it has none. */
151
- export const priorityOf = (labels: readonly string[], priorityLabels: readonly string[]): number => {
154
+ export const priorityOf = ({ labels, priorityLabels }: { readonly labels: readonly string[]; readonly priorityLabels: readonly string[] }): number => {
152
155
  const found = priorityLabels.findIndex((label) => labels.includes(label));
153
156
 
154
157
  return found < 0 ? priorityLabels.length : found;
155
158
  };
156
159
 
157
160
  /** How many more questions the owner can be asked now: the cap less those asked within the last day. No cap leaves no limit. */
158
- export const roomToAsk = (askedAt: readonly number[], cap: number | undefined, now: number): number =>
161
+ export const roomToAsk = ({ askedAt, cap, now }: { readonly askedAt: readonly number[]; readonly cap: number | undefined; readonly now: number }): number =>
159
162
  cap === undefined ? Number.POSITIVE_INFINITY : Math.max(0, cap - askedAt.filter((at) => now - at < DAY_MS).length);
@@ -1,4 +1,3 @@
1
- import type { Item } from "../adapter-api.ts";
2
1
  import type { HumConfig } from "../config/schema.ts";
3
2
  import { DATA_RULE, fenced } from "./prose.ts";
4
3
 
@@ -6,5 +5,8 @@ import { DATA_RULE, fenced } from "./prose.ts";
6
5
  * What a fresh review run reads: the item as the owner asked it and the change's diff. It takes no thread, so the
7
6
  * author's plan, questions and answers never reach the reviewer.
8
7
  */
9
- export const reviewInput = (item: Pick<Item, "id" | "title" | "body">, diff: string, { diffLimit }: Pick<HumConfig, "diffLimit">): string =>
8
+ /** What a prompt quotes of an item: plain text, whatever its id's source. */
9
+ export type ItemText = { readonly id: string; readonly title: string; readonly body: string };
10
+
11
+ export const reviewInput = (item: ItemText, diff: string, { diffLimit }: Pick<HumConfig, "diffLimit">): string =>
10
12
  [`# Item ${item.id}: ${item.title}`, DATA_RULE, fenced("item", item.body.trim()), `## The change`, fenced("diff", diff.slice(0, diffLimit))].join("\n\n");
@@ -1,19 +1,24 @@
1
1
  import { quantile } from "simple-statistics";
2
+ import { z } from "zod";
2
3
  import type { HumConfig, Launch, Level, PathRule } from "../config/schema.ts";
3
4
 
4
5
  /** What only the owner changes: hum's own config, the owner's adapters and the CI workflows. */
5
6
  const OWN_PATHS = [".hum/**", "adapters/**", ".github/workflows/**"] as const;
6
7
 
7
8
  /** What hum reads from a change's diff. */
8
- export type Change = {
9
- readonly paths: readonly string[];
10
- /** Lines added plus lines deleted. */
11
- readonly size: number;
12
- /** An added or removed line matches the project's loosened-check rule. */
13
- readonly loosened: boolean;
14
- /** A changed line in `package.json` or a lockfile names the engine package. */
15
- readonly pinChanged: boolean;
16
- };
9
+ export const Change = z
10
+ .object({
11
+ paths: z.array(z.string().min(1)).readonly(),
12
+ /** Lines added plus lines deleted. */
13
+ size: z.int().nonnegative(),
14
+ /** An added or removed line matches the project's loosened-check rule. */
15
+ loosened: z.boolean(),
16
+ /** A changed line in `package.json` or a lockfile names the engine package. */
17
+ pinChanged: z.boolean(),
18
+ })
19
+ .readonly();
20
+
21
+ export type Change = z.infer<typeof Change>;
17
22
 
18
23
  export const LABELS = ["reverted", "fixed", "clean"] as const;
19
24
 
@@ -76,12 +81,12 @@ export type Placement = {
76
81
  readonly steps: readonly Step[];
77
82
  };
78
83
 
79
- const matches = (glob: string, path: string): boolean =>
84
+ const doesMatch = (glob: string, path: string): boolean =>
80
85
  new Bun.Glob(glob).match(path);
81
86
 
82
87
  const isLaunchOn = (launch: Launch, { now, base }: Moment): boolean =>
83
88
  "base" in launch
84
- ? matches(launch.base, base)
89
+ ? doesMatch(launch.base, base)
85
90
  : Date.parse(launch.from) <= now && now < Date.parse(launch.until);
86
91
 
87
92
  /** Fixed or reverted changes among a path's last `of` merged changes. */
@@ -119,13 +124,16 @@ export const placeChange = (
119
124
  names[Math.min(strictest, rank(name) + 1)] ?? name;
120
125
 
121
126
  const rulesOn = (path: string): readonly PathRule[] =>
122
- policy.paths.filter((rule) => matches(rule.glob, path));
127
+ policy.paths.filter((rule) => doesMatch(rule.glob, path));
123
128
 
124
129
  const isStrict = (path: string): boolean =>
125
- policy.strictPaths.some((glob) => matches(glob, path));
130
+ policy.strictPaths.some((glob) => doesMatch(glob, path));
126
131
 
127
132
  const isOwn = (path: string): boolean =>
128
- [...OWN_PATHS, ...policy.hookPaths].some((glob) => matches(glob, path));
133
+ [...OWN_PATHS, ...policy.hookPaths].some((glob) => doesMatch(glob, path));
134
+
135
+ /** A path no rule places, outside the strict paths and hum's own. */
136
+ const isUnclear = (path: string): boolean => rulesOn(path).length === 0 && !isStrict(path) && !isOwn(path);
129
137
 
130
138
  const touched = [
131
139
  ...new Map(
@@ -162,7 +170,7 @@ export const placeChange = (
162
170
 
163
171
  const launchSteps = policy.launches.flatMap((launch): SetsLevel[] =>
164
172
  isLaunchOn(launch, moment) &&
165
- change.paths.some((path) => matches(launch.glob, path))
173
+ change.paths.some((path) => doesMatch(launch.glob, path))
166
174
  ? [{ step: "launch", glob: launch.glob, level: launch.level }]
167
175
  : [],
168
176
  );
@@ -176,7 +184,7 @@ export const placeChange = (
176
184
  ),
177
185
  ...(change.pinChanged ? [{ step: "engine-pin" } as const] : []),
178
186
  ...change.paths.flatMap((path): Step[] =>
179
- (moment.blocked ?? []).some((glob) => matches(glob, path)) ? [{ step: "blocked-path", path }] : [],
187
+ (moment.blocked ?? []).some((glob) => doesMatch(glob, path)) ? [{ step: "blocked-path", path }] : [],
180
188
  ),
181
189
  ];
182
190
 
@@ -208,9 +216,7 @@ export const placeChange = (
208
216
 
209
217
  return {
210
218
  level,
211
- unclear: change.paths.filter(
212
- (path) => rulesOn(path).length === 0 && !isStrict(path) && !isOwn(path),
213
- ),
219
+ unclear: change.paths.filter(isUnclear),
214
220
  steps: [...ruleSteps, ...launchSteps, ...kindFloorSteps, ...floors, ...bumps],
215
221
  };
216
222
  };
@@ -3,9 +3,9 @@ import type { HumConfig } from "../config/schema.ts";
3
3
  import { DATA_RULE, fenced } from "./prose.ts";
4
4
 
5
5
  /** Whether the diff keeps one taste rule, and the line of the diff that shows it. */
6
- export const TasteAnswer = z.strictObject({ keeps: z.boolean(), evidence: z.string() });
6
+ const TasteAnswer = z.strictObject({ keeps: z.boolean(), evidence: z.string() });
7
7
 
8
- export type TasteAnswer = z.infer<typeof TasteAnswer>;
8
+ type TasteAnswer = z.infer<typeof TasteAnswer>;
9
9
 
10
10
  /** The cheap model call that checks a diff against one taste rule. Its pick is for a report and decides nothing. */
11
11
  export const tasteQuestion = (rule: string, diff: string, { diffLimit }: Pick<HumConfig, "diffLimit">) => ({
@@ -24,7 +24,7 @@ export const tasteQuestion = (rule: string, diff: string, { diffLimit }: Pick<Hu
24
24
  export type TasteResult = { readonly rule: string; readonly answer: TasteAnswer | { readonly abstained: string } };
25
25
 
26
26
  /** The pull request comment. It only reports; `measured` says whether the model's rate at this boundary meets the bar. */
27
- export const tasteComment = (results: readonly TasteResult[], measured: boolean): string => {
27
+ export const tasteComment = (results: readonly TasteResult[], { measured }: { readonly measured: boolean }): string => {
28
28
  const lines = results.map(({ rule, answer }) => {
29
29
  if ("abstained" in answer) return `- ? ${rule} (not checked: ${answer.abstained})`;
30
30
 
package/src/exec.ts CHANGED
@@ -3,6 +3,9 @@ import { type Options, type Output, x } from "tinyexec";
3
3
  import { type HumConfig, SHIPPED_DEFAULTS } from "./config/schema.ts";
4
4
  import { SECOND_MS } from "./time.ts";
5
5
 
6
+ /** A process environment: the root reads `process.env` once and hands it down. */
7
+ export type Env = Readonly<Record<string, string | undefined>>;
8
+
6
9
  /** A command ran past its limit and was told to stop. */
7
10
  export class CommandTimedOut extends Error {
8
11
  override name = "CommandTimedOut";
@@ -47,9 +50,7 @@ const signalGroup = (group: number, signal: "SIGTERM" | "SIGKILL" | 0): boolean
47
50
  };
48
51
 
49
52
  const isGone = async (group: number, graceMs: number): Promise<boolean> => {
50
- const deadline = Date.now() + graceMs;
51
-
52
- while (signalGroup(group, 0) && Date.now() < deadline) await Bun.sleep(POLL_MS);
53
+ for (let waited = 0; waited < graceMs && signalGroup(group, 0); waited += POLL_MS) await Bun.sleep(POLL_MS);
53
54
 
54
55
  return !signalGroup(group, 0);
55
56
  };
package/src/index.ts CHANGED
@@ -57,15 +57,15 @@ export {
57
57
  type EnvelopeMigrations,
58
58
  } from "./state/format.ts";
59
59
 
60
- export { OpKey, OpKeys, type OpProvider } from "./state/ops.ts";
60
+ export { OpKey, OpKeys, type OpProvider, type OpRun } from "./state/ops.ts";
61
61
 
62
62
  export { defaultStateDir, openState, type State, type StateOptions } from "./state/open.ts";
63
63
 
64
64
  export { type BegunRun, RunKey, RunRecord, RunRecords } from "./state/runs.ts";
65
65
 
66
- export { readStatus, type StatusRead, writeStatus } from "./status/file.ts";
66
+ export { emptyStatus, readStatus, type StatusRead, writeStatus } from "./status/file.ts";
67
67
 
68
- export { Action, Card, CardAction, Choice, emptyStatus, InFlight, Measure, Merged, Question, Status, STATUS_FORMAT } from "./status/format.ts";
68
+ export { Action, Card, CardAction, Choice, InFlight, Measure, Merged, Question, Status, STATUS_FORMAT } from "./status/format.ts";
69
69
 
70
70
  export * from "./adapter-api.ts";
71
71
 
@@ -75,11 +75,13 @@ export { type Check, contractChecks, type ContractResult, type ContractTarget, r
75
75
 
76
76
  export { FakeProvider, ProviderError } from "./adapters/fake.ts";
77
77
 
78
- export { pushArgs, PushRefused } from "./adapters/git.ts";
78
+ export { pushArgs } from "./adapters/git.ts";
79
79
 
80
80
  export { type GuardOptions, guarded } from "./adapters/guard.ts";
81
81
 
82
- export { type GitHubClient, gitHubClient, githubAdapter, type GitHubOptions, repoFromRemote } from "./adapters/github.ts";
82
+ export { githubAdapter, type GitHubOptions, repoFromRemote } from "./adapters/github.ts";
83
+
84
+ export { type GitHubClient, gitHubClient } from "./adapters/github-client.ts";
83
85
 
84
86
  export { Marker, marked, markerOf, parseComment } from "./adapters/marked.ts";
85
87
 
@@ -109,7 +111,7 @@ export {
109
111
  type RunnerOptions,
110
112
  runArgs,
111
113
  startRunner,
112
- succeeded,
114
+ hasSucceeded,
113
115
  } from "./adapters/claude-p.ts";
114
116
 
115
117
  export {
@@ -125,21 +127,21 @@ export {
125
127
 
126
128
  export { type Change, type Histories, LABELS, type Label, type Moment, type PathHistory, type Placement, type Policy, placeChange, type Step, usualSize } from "./decide/risk.ts";
127
129
 
128
- export { type Approvals, isCleared, type Landing, landingOf, needsReviewRun, OWNER_APPROVAL, type Route, routeOf, type Unclear, waitReason } from "./decide/merge.ts";
130
+ export { type Approvals, isCleared, type Landing, landingOf, doesNeedReviewRun, OWNER_APPROVAL, type Route, routeOf, type Unclear, waitReason } from "./decide/merge.ts";
129
131
 
130
132
  export { reviewInput } from "./decide/review.ts";
131
133
 
132
- export { citesDiff, DATA_RULE, fenced, EventPick, isTrusted, PlanFile, planHash, PROSE_STATES, type ProsePurpose, readPick } from "./decide/prose.ts";
134
+ export { doesCiteDiff, DATA_RULE, fenced, EventPick, isTrusted, PlanFile, planHash, PROSE_STATES, type ProsePurpose, readPick } from "./decide/prose.ts";
133
135
 
134
- export { declaredKind, kindQuestion, leavesDocs, UNSURE } from "./decide/kind.ts";
136
+ export { declaredKind, kindQuestion, doesLeaveDocs, UNSURE } from "./decide/kind.ts";
135
137
 
136
- export { AlignmentAnswer, alignedPlacement, alignmentQuestion, GRADES, raisesLevel } from "./decide/alignment.ts";
138
+ export { AlignmentAnswer, alignedPlacement, alignmentQuestion, GRADES, doesRaiseLevel } from "./decide/alignment.ts";
137
139
 
138
140
  export { configuredModelCall, type Judgment, type ModelCall, modelCallOver, type Question as ModelQuestion } from "./adapters/model-call.ts";
139
141
 
140
142
  export { decideProse, type ProseDecision } from "./worker/prose-run.ts";
141
143
 
142
- export { decideKind } from "./worker/kind.ts";
144
+ export { keepKind, pickKind } from "./worker/kind.ts";
143
145
 
144
146
  export { labelChanges, type LabelRules, matchedSample, type PastChange } from "./decide/labels.ts";
145
147
 
@@ -167,7 +169,7 @@ export { Heartbeat } from "./status/format.ts";
167
169
 
168
170
  export { readHeartbeat, writeHeartbeat } from "./status/file.ts";
169
171
 
170
- export { type Candidate, type Footprint, footprintOf, overlaps, pick, type Picked, PrefixGate } from "./worker/scheduler.ts";
172
+ export { type Candidate, type Footprint, footprintOf, doOverlap, pick, type Picked, PrefixGate } from "./worker/scheduler.ts";
171
173
 
172
174
  export { installedVersion, type Signature, signatureOf } from "./worker/signature.ts";
173
175
 
@@ -197,4 +199,3 @@ export { SLOT_ENV, slotEnv } from "./slots/env.ts";
197
199
 
198
200
  export { type PoolOptions, SLOT_KEPT_CODE, SLOT_MAINTENANCE_CODE, SLOT_OUT_CODE, SlotPool } from "./slots/pool.ts";
199
201
 
200
- export { proposeRecipe } from "./slots/scan.ts";
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import type { WorkSource } from "../adapter-api.ts";
2
+ import { ItemId, type WorkSource } from "../adapter-api.ts";
3
3
  import type { State } from "../state/open.ts";
4
4
  import { noteKey, type RepeatGroup, type ReviewNote } from "./records.ts";
5
5
 
@@ -12,7 +12,7 @@ const hashOf = (groupKey: string): string => createHash("sha1").update(groupKey)
12
12
  export const checkNameOf = (groupKey: string): string => `hum-check-${hashOf(groupKey)}`;
13
13
 
14
14
  /** The id a group files its items from; filing the same title from it twice returns the first item. */
15
- export const filedFrom = (groupKey: string): string => `rn-${hashOf(groupKey)}`;
15
+ export const filedFrom = (groupKey: string): ItemId => ItemId.parse(`rn-${hashOf(groupKey)}`);
16
16
 
17
17
  const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
18
18
 
@@ -69,7 +69,7 @@ export const fileChecks = async ({ state, workSource, repeatAt, checkKind }: Fil
69
69
 
70
70
  const unposted = notes.filter((found) => !group.commented.includes(noteKey(found)));
71
71
 
72
- for (const note of unposted) await workSource.comment(group.item, noteBlock(note));
72
+ for (const note of unposted) await workSource.comment(ItemId.parse(group.item), noteBlock(note));
73
73
 
74
74
  if (unposted.length > 0) state.repeats.put(group.key, { ...group, commented: group.notes });
75
75
  }
package/src/loop/ci.ts CHANGED
@@ -5,4 +5,4 @@ import { checkNameOf } from "./check-item.ts";
5
5
  export type CiLogs = (since: number) => Promise<readonly string[]>;
6
6
 
7
7
  /** Whether a CI log names the check: the next run after the check landed proves it ran. */
8
- export const logNames = (log: string, groupKey: RepeatGroup["key"]): boolean => log.includes(checkNameOf(groupKey));
8
+ export const doesLogName = (log: string, groupKey: RepeatGroup["key"]): boolean => log.includes(checkNameOf(groupKey));
@@ -35,7 +35,7 @@ const pagesOf = async <T>(read: (page: number) => Promise<T[]>): Promise<T[]> =>
35
35
  };
36
36
 
37
37
  /** Every pull request review comment on the repo since a time, as raw comments. */
38
- export const reviewComments = async (client: Requester, repo: string, since: number): Promise<RawComment[]> =>
38
+ const reviewComments = async (client: Requester, repo: string, since: number): Promise<RawComment[]> =>
39
39
  (
40
40
  await pagesOf(async (page) =>
41
41
  z.array(ReviewComment).parse((await client.request(`GET /repos/${repo}/pulls/comments`, { per_page: PAGE_SIZE, page, since: new Date(since).toISOString(), sort: "created", direction: "asc" })).data),
@@ -54,7 +54,7 @@ export const reviewComments = async (client: Requester, repo: string, since: num
54
54
  }));
55
55
 
56
56
  /** The logs of the newest runs on the base branch that started after a time, one text per job. */
57
- export const ciLogsOf =
57
+ const ciLogsOf =
58
58
  (client: Requester, repo: string, base: string, runsRead: number) =>
59
59
  async (since: number): Promise<string[]> => {
60
60
  const { workflow_runs: runs } = Runs.parse((await client.request(`GET /repos/${repo}/actions/runs`, { branch: base, per_page: runsRead, created: `>=${new Date(since).toISOString()}` })).data);
@@ -5,7 +5,7 @@ import { noteKey, type RepeatGroup, type ReviewNote } from "./records.ts";
5
5
  import { type Pairing, pairing, prepare } from "./signals.ts";
6
6
 
7
7
  /** A model's answer to whether two notes state one rule; `undefined` when it abstained. */
8
- export type Proposal = { readonly same: boolean; readonly models: readonly string[] } | undefined;
8
+ type Proposal = { readonly same: boolean; readonly models: readonly string[] } | undefined;
9
9
 
10
10
  export type Proposer = (a: ReviewNote, b: ReviewNote) => Promise<Proposal>;
11
11
 
@@ -56,15 +56,22 @@ const join = (state: State, group: RepeatGroup, key: string): RepeatGroup => {
56
56
  return joined;
57
57
  };
58
58
 
59
- /** Joins the groups the note pairs with into the oldest one. */
59
+ const isFiled = (group: RepeatGroup): boolean => group.item !== undefined;
60
+
61
+ /**
62
+ * Joins the groups the note pairs with into one: the oldest with a filed check item, else the oldest. Only groups
63
+ * with no item merge into it; a group whose item is filed stays whole, so no filed item loses the group it proves.
64
+ */
60
65
  const mergeInto = (state: State, groups: readonly RepeatGroup[], key: string): void => {
61
- const [oldest, ...rest] = groups.toSorted(byAge(state));
66
+ const oldestFirst = groups.toSorted(byAge(state));
67
+ const target = oldestFirst.find(isFiled) ?? oldestFirst[0];
62
68
 
63
- if (!oldest) return;
69
+ if (!target) return;
64
70
 
65
- const merged = { ...oldest, notes: [...new Set([oldest, ...rest].flatMap(({ notes }) => notes))], commented: [...new Set([oldest, ...rest].flatMap(({ commented }) => commented))] };
71
+ const absorbed = oldestFirst.filter((group) => group !== target && !isFiled(group));
72
+ const merged = { ...target, notes: [...new Set([target, ...absorbed].flatMap(({ notes }) => notes))] };
66
73
 
67
- for (const other of rest) state.repeats.remove(other.key);
74
+ for (const other of absorbed) state.repeats.remove(other.key);
68
75
 
69
76
  join(state, merged, key);
70
77
  };
@@ -1,54 +1,66 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
2
  import { z } from "zod";
3
3
  import type { Finished } from "../adapters/claude-p.ts";
4
+ import type { RunRecord } from "../state/runs.ts";
4
5
 
5
6
  export type MemoryEntry = { readonly rule: string; readonly source: string };
6
7
 
7
8
  /** One entry per line: `- <rule> (source: <where the owner said it>)`. */
8
9
  const ENTRY_LINE = /^- (.+) \(source: (.+)\)$/;
9
10
 
10
- export class MemoryFormatError extends Error {
11
- override name = "MemoryFormatError";
12
- }
11
+ /** A memory.md list line runs are not shown: it names no source, or it comes after the entries passed the byte cap. */
12
+ export type RefusedLine = { readonly line: number; readonly why: "no-source" | "past-cap" };
13
13
 
14
- export class MemoryFull extends Error {
15
- override name = "MemoryFull";
16
- }
14
+ /** What memory.md holds: the entries runs are shown, and the list lines refused. */
15
+ export type Memory = { readonly entries: readonly MemoryEntry[]; readonly refused: readonly RefusedLine[] };
17
16
 
18
- const squash = (rule: string): string => rule.toLowerCase().replace(/\s+/g, " ").trim();
17
+ const NO_MEMORY: Memory = { entries: [], refused: [] };
19
18
 
20
- /** The entries of a memory file. A list line with no source is refused: every entry names where it came from. */
21
- export const parseMemory = (text: string): MemoryEntry[] =>
22
- text.split("\n").flatMap((line, at): MemoryEntry[] => {
23
- if (!line.startsWith("- ")) return [];
19
+ const entryOf = (line: string): MemoryEntry | undefined => {
20
+ const [, rule, source] = ENTRY_LINE.exec(line) ?? [];
24
21
 
25
- const [, rule, source] = ENTRY_LINE.exec(line) ?? [];
22
+ return rule === undefined || source === undefined ? undefined : { rule, source };
23
+ };
26
24
 
27
- if (rule === undefined || source === undefined) throw new MemoryFormatError(`memory.md line ${at + 1} has no "(source: …)": ${line.slice(0, 80)}`);
25
+ const isListLine = (line: string): boolean => line.startsWith("- ");
28
26
 
29
- return [{ rule, source }];
30
- });
27
+ /** The entries of a memory file, in order, while their lines fit in `maxBytes`; every entry names where it came from. */
28
+ export const parseMemory = (text: string, maxBytes: number): Memory => {
29
+ const { entries, refused } = text.split("\n").reduce(
30
+ (memory, line, at) => {
31
+ if (!isListLine(line)) return memory;
31
32
 
32
- export const renderMemory = (entries: readonly MemoryEntry[]): string => entries.map(({ rule, source }) => `- ${rule} (source: ${source})\n`).join("");
33
+ const entry = entryOf(line);
34
+ const bytes = memory.bytes + Buffer.byteLength(`${line}\n`);
35
+ const refuse = (why: RefusedLine["why"]) => ({ ...memory, refused: [...memory.refused, { line: at + 1, why }] });
33
36
 
34
- /** A new entry on a rule already held replaces it, so one rule has one entry; past the byte cap the entry is refused. */
35
- export const addEntry = (entries: readonly MemoryEntry[], entry: MemoryEntry, maxBytes: number): MemoryEntry[] => {
36
- const next = [...entries.filter(({ rule }) => squash(rule) !== squash(entry.rule)), entry];
37
+ if (entry === undefined) return refuse("no-source");
37
38
 
38
- if (Buffer.byteLength(renderMemory(next)) > maxBytes) throw new MemoryFull(`memory.md would pass ${maxBytes} bytes; remove an entry first`);
39
+ return bytes > maxBytes ? { ...refuse("past-cap"), bytes } : { ...memory, bytes, entries: [...memory.entries, entry] };
40
+ },
41
+ { ...NO_MEMORY, bytes: 0 },
42
+ );
39
43
 
40
- return next;
44
+ return { entries, refused };
41
45
  };
42
46
 
43
- /** The entries left once a check covers the rules whose sources are `covered`. */
44
- export const withoutCovered = (entries: readonly MemoryEntry[], covered: ReadonlySet<string>): MemoryEntry[] => entries.filter(({ source }) => !covered.has(source));
47
+ /** memory.md's text without the entries whose sources a check now covers; every other line stays as the owner wrote it. */
48
+ export const withoutCovered = (text: string, covered: ReadonlySet<string>): string =>
49
+ text
50
+ .split("\n")
51
+ .filter((line) => {
52
+ const source = entryOf(line)?.source;
53
+
54
+ return source === undefined || !covered.has(source);
55
+ })
56
+ .join("\n");
45
57
 
46
58
  /** Entries no run used within the last `limit` runs: `lastUsed` is the run number of an entry's last use, absent when none used it. */
47
- export const unusedEntries = (entries: readonly MemoryEntry[], lastUsed: ReadonlyMap<string, number>, runsSoFar: number, limit: number): MemoryEntry[] =>
59
+ export const unusedEntries = ({ entries, lastUsed, runsSoFar, limit }: { readonly entries: readonly MemoryEntry[]; readonly lastUsed: ReadonlyMap<string, number>; readonly runsSoFar: number; readonly limit: number }): MemoryEntry[] =>
48
60
  entries.filter(({ rule }) => runsSoFar - (lastUsed.get(rule) ?? 0) >= limit);
49
61
 
50
- /** The entries of the file at `path`; none when it is absent. */
51
- export const readMemory = (path: string): MemoryEntry[] => (existsSync(path) ? parseMemory(readFileSync(path, "utf8")) : []);
62
+ /** The memory file at `path`; empty when it is absent. */
63
+ export const readMemory = (path: string, maxBytes: number): Memory => (existsSync(path) ? parseMemory(readFileSync(path, "utf8"), maxBytes) : NO_MEMORY);
52
64
 
53
65
  /** What a run reads of memory.md: its rules, numbered, and the ask to name the ones it applied. */
54
66
  export const memorySection = (entries: readonly MemoryEntry[]): string =>
@@ -63,8 +75,8 @@ export const rulesUsed = ({ structured }: Pick<Finished, "structured">, entries:
63
75
  export type MemoryUse = { readonly runsSoFar: number; readonly lastUsed: ReadonlyMap<string, number> };
64
76
 
65
77
  /** From the runs that were shown memory.md, oldest first: how many there were, and the run each rule was last used in. */
66
- export const useOf = (runs: readonly { readonly memoryUsed?: readonly string[] }[]): MemoryUse => {
67
- const shown = runs.flatMap(({ memoryUsed }) => (memoryUsed === undefined ? [] : [memoryUsed]));
78
+ export const useOf = (runs: readonly RunRecord[]): MemoryUse => {
79
+ const shown = runs.flatMap((run) => (run.endedAt === undefined || run.memoryUsed === undefined ? [] : [run.memoryUsed]));
68
80
 
69
81
  return { runsSoFar: shown.length, lastUsed: new Map(shown.flatMap((rules, at) => rules.map((rule): [string, number] => [rule, at + 1]))) };
70
82
  };
package/src/loop/notes.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { PastChange } from "../decide/labels.ts";
2
2
  import { breakOf, type LabelRules } from "../decide/labels.ts";
3
- import type { SettledAnswer } from "../state/saved.ts";
3
+ import { optionOf, type SettledAnswer } from "../state/saved.ts";
4
4
  import type { State } from "../state/open.ts";
5
5
  import { type NoteSource, noteKey, type ReviewNote } from "./records.ts";
6
6
 
@@ -19,7 +19,7 @@ export type RawComment = {
19
19
  readonly at: number;
20
20
  };
21
21
 
22
- const SOURCE_OF_KIND: Readonly<Record<RawComment["kind"], NoteSource>> = { comment: "review-comment", review: "review-body" };
22
+ const SOURCE_OF_KIND = { comment: "review-comment", review: "review-body" } as const satisfies Record<RawComment["kind"], NoteSource>;
23
23
 
24
24
  /** The owner's comments and review bodies; a bot's, another person's and an empty body are not review notes. */
25
25
  export const ownerNotes = (raw: readonly RawComment[], owners: readonly string[]): ReviewNote[] =>
@@ -30,13 +30,13 @@ export const ownerNotes = (raw: readonly RawComment[], owners: readonly string[]
30
30
  );
31
31
 
32
32
  /** The option that approves a plan; every other answer changed it. */
33
- export const APPROVAL_OPTION = "approve";
33
+ const APPROVAL_OPTION = "approve";
34
34
 
35
35
  /** An answer that changed the plan: one applied, and not an approval. */
36
36
  export const planChangingNotes = (answers: readonly SettledAnswer[]): ReviewNote[] =>
37
37
  answers
38
- .flatMap(({ item, ordinal, text, at, disposition, option }): ReviewNote[] =>
39
- disposition === "applied" && option !== APPROVAL_OPTION ? [{ source: "plan-answer", sourceId: `${item}:${ordinal}`, change: item, item, hunk: "", text, at }] : [],
38
+ .flatMap((answer): ReviewNote[] =>
39
+ answer.disposition === "applied" && optionOf(answer) !== APPROVAL_OPTION ? [{ source: "plan-answer", sourceId: `${answer.item}:${answer.ordinal}`, change: answer.item, item: answer.item, hunk: "", text: answer.text, at: answer.at }] : [],
40
40
  );
41
41
 
42
42
  /** The revert or fix commit behind each broken change, with the hunk it made. */
package/src/loop/pair.ts CHANGED
@@ -35,5 +35,5 @@ export const modelProposer =
35
35
  };
36
36
 
37
37
  /** Whether every model id behind a proposal reached the owner's precision bar on labelled pairs. */
38
- export const trustsRepeats = (models: readonly string[], { measuredModels, repeatPrecision }: Pick<HumConfig, "measuredModels" | "repeatPrecision">): boolean =>
38
+ export const doesTrustRepeats = (models: readonly string[], { measuredModels, repeatPrecision }: Pick<HumConfig, "measuredModels" | "repeatPrecision">): boolean =>
39
39
  models.length > 0 && models.every((model) => (measuredModels["repeat-pair"]?.[model] ?? 0) >= repeatPrecision);