@moo.md/hum 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/defaults/hum.json +321 -0
  2. package/defaults/kinds/check.json +183 -0
  3. package/defaults/kinds/docs.json +151 -0
  4. package/defaults/kinds/feature.json +202 -0
  5. package/defaults/kinds/fix.json +183 -0
  6. package/defaults/kinds/hotfix.json +164 -0
  7. package/defaults/roles/build.md +3 -0
  8. package/defaults/roles/fix.md +1 -0
  9. package/defaults/roles/plan.md +3 -0
  10. package/defaults/roles/review.md +3 -0
  11. package/evals/alignment/RESULTS.md +8 -0
  12. package/evals/alignment/cases.jsonl +128 -0
  13. package/evals/alignment/sample.jsonl +20 -0
  14. package/evals/kind/RESULTS.md +5 -0
  15. package/evals/kind/cases.jsonl +24 -0
  16. package/evals/plan-outcome/RESULTS.md +4 -0
  17. package/evals/plan-outcome/cases.jsonl +12 -0
  18. package/evals/repeat-pair/RESULTS.md +4 -0
  19. package/evals/repeat-pair/cases.jsonl +51 -0
  20. package/evals/reply-option/RESULTS.md +3 -0
  21. package/evals/reply-option/cases.jsonl +45 -0
  22. package/evals/review-verdict/RESULTS.md +4 -0
  23. package/evals/review-verdict/cases.jsonl +12 -0
  24. package/package.json +88 -4
  25. package/schema/hum.schema.json +1355 -0
  26. package/scripts/eval.ts +244 -0
  27. package/src/adapter-api.ts +134 -0
  28. package/src/adapters/admit.ts +111 -0
  29. package/src/adapters/argument.ts +11 -0
  30. package/src/adapters/claim.ts +93 -0
  31. package/src/adapters/claude-bg.ts +392 -0
  32. package/src/adapters/claude-p.ts +599 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +156 -0
  36. package/src/adapters/github.ts +479 -0
  37. package/src/adapters/guard.ts +152 -0
  38. package/src/adapters/history.ts +215 -0
  39. package/src/adapters/item-file.ts +102 -0
  40. package/src/adapters/limit.ts +67 -0
  41. package/src/adapters/markdown.ts +365 -0
  42. package/src/adapters/marked.ts +127 -0
  43. package/src/adapters/model-call.ts +75 -0
  44. package/src/adapters/once.ts +45 -0
  45. package/src/adapters/owner-commit.ts +60 -0
  46. package/src/adapters/pull-requests.ts +253 -0
  47. package/src/adapters/registry.ts +156 -0
  48. package/src/adapters/roundup.ts +293 -0
  49. package/src/adapters/serial.ts +22 -0
  50. package/src/adapters/transcript.ts +99 -0
  51. package/src/cli/commands.ts +46 -0
  52. package/src/cli/main.ts +8 -0
  53. package/src/cli/ops.ts +224 -0
  54. package/src/cli/service.ts +156 -0
  55. package/src/cli/setup.ts +141 -0
  56. package/src/cli/shared-watch.ts +127 -0
  57. package/src/config/change.ts +54 -0
  58. package/src/config/checks.ts +217 -0
  59. package/src/config/git-ref-name.d.ts +3 -0
  60. package/src/config/hash.ts +6 -0
  61. package/src/config/json.ts +6 -0
  62. package/src/config/load.ts +88 -0
  63. package/src/config/machine.ts +20 -0
  64. package/src/config/migrate.ts +61 -0
  65. package/src/config/refusal.ts +58 -0
  66. package/src/config/schema.ts +465 -0
  67. package/src/config/settings.ts +6 -0
  68. package/src/config/state-map.ts +76 -0
  69. package/src/decide/alignment.ts +79 -0
  70. package/src/decide/answer.ts +131 -0
  71. package/src/decide/kind.ts +39 -0
  72. package/src/decide/labels.ts +137 -0
  73. package/src/decide/merge.ts +102 -0
  74. package/src/decide/prose.ts +109 -0
  75. package/src/decide/question.ts +159 -0
  76. package/src/decide/review.ts +10 -0
  77. package/src/decide/risk.ts +216 -0
  78. package/src/decide/taste.ts +37 -0
  79. package/src/exec.ts +85 -0
  80. package/src/index.ts +200 -0
  81. package/src/loop/breaks.ts +8 -0
  82. package/src/loop/check-item.ts +76 -0
  83. package/src/loop/ci.ts +8 -0
  84. package/src/loop/github.ts +81 -0
  85. package/src/loop/groups.ts +108 -0
  86. package/src/loop/memory.ts +70 -0
  87. package/src/loop/notes.ts +76 -0
  88. package/src/loop/pair.ts +39 -0
  89. package/src/loop/pass.ts +99 -0
  90. package/src/loop/proof.ts +85 -0
  91. package/src/loop/prove-item.ts +33 -0
  92. package/src/loop/records.ts +75 -0
  93. package/src/loop/signals.ts +130 -0
  94. package/src/measure/inputs.ts +28 -0
  95. package/src/measure/measure.ts +68 -0
  96. package/src/service/cards.ts +24 -0
  97. package/src/service/ci-tick.ts +28 -0
  98. package/src/service/launchd.ts +16 -0
  99. package/src/service/supervise.ts +145 -0
  100. package/src/service/systemd.ts +44 -0
  101. package/src/service/token.ts +21 -0
  102. package/src/service/unit.ts +29 -0
  103. package/src/service/wake.ts +30 -0
  104. package/src/service/workflows.ts +97 -0
  105. package/src/setup/propose.ts +120 -0
  106. package/src/setup/prove.ts +216 -0
  107. package/src/setup/scan.ts +186 -0
  108. package/src/setup/scratch.ts +81 -0
  109. package/src/setup/shipped.ts +15 -0
  110. package/src/setup/tables.ts +101 -0
  111. package/src/setup/waits.ts +58 -0
  112. package/src/setup/write.ts +161 -0
  113. package/src/slots/env.ts +42 -0
  114. package/src/slots/pool.ts +329 -0
  115. package/src/slots/scan.ts +26 -0
  116. package/src/slots/worktree.ts +17 -0
  117. package/src/state/events.ts +52 -0
  118. package/src/state/faults.ts +73 -0
  119. package/src/state/format.ts +50 -0
  120. package/src/state/fs.ts +100 -0
  121. package/src/state/items.ts +195 -0
  122. package/src/state/open.ts +80 -0
  123. package/src/state/ops.ts +76 -0
  124. package/src/state/records.ts +35 -0
  125. package/src/state/runs.ts +99 -0
  126. package/src/state/saved.ts +119 -0
  127. package/src/status/file.ts +49 -0
  128. package/src/status/format.ts +132 -0
  129. package/src/status/sections.ts +14 -0
  130. package/src/status/version.ts +2 -0
  131. package/src/time.ts +7 -0
  132. package/src/worker/alignment-report.ts +18 -0
  133. package/src/worker/answers.ts +153 -0
  134. package/src/worker/base-check.ts +45 -0
  135. package/src/worker/checks.ts +40 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +509 -0
  138. package/src/worker/lifecycle.ts +97 -0
  139. package/src/worker/merged.ts +29 -0
  140. package/src/worker/open.ts +100 -0
  141. package/src/worker/prose-run.ts +56 -0
  142. package/src/worker/questions.ts +89 -0
  143. package/src/worker/scheduler.ts +135 -0
  144. package/src/worker/signature.ts +41 -0
  145. package/src/worker/tally.ts +25 -0
  146. package/src/worker/taste.ts +38 -0
  147. package/src/worker/thin-path.ts +886 -0
  148. package/src/worker/worker.ts +750 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,10 @@
1
+ import type { Item } from "../adapter-api.ts";
2
+ import type { HumConfig } from "../config/schema.ts";
3
+ import { DATA_RULE, fenced } from "./prose.ts";
4
+
5
+ /**
6
+ * 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
+ * author's plan, questions and answers never reach the reviewer.
8
+ */
9
+ export const reviewInput = (item: Pick<Item, "id" | "title" | "body">, diff: string, { diffLimit }: Pick<HumConfig, "diffLimit">): string =>
10
+ [`# Item ${item.id}: ${item.title}`, DATA_RULE, fenced("item", item.body.trim()), `## The change`, fenced("diff", diff.slice(0, diffLimit))].join("\n\n");
@@ -0,0 +1,216 @@
1
+ import { quantile } from "simple-statistics";
2
+ import type { HumConfig, Launch, Level, PathRule } from "../config/schema.ts";
3
+
4
+ /** What only the owner changes: hum's own config, the owner's adapters and the CI workflows. */
5
+ const OWN_PATHS = [".hum/**", "adapters/**", ".github/workflows/**"] as const;
6
+
7
+ /** 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
+ };
17
+
18
+ export const LABELS = ["reverted", "fixed", "clean"] as const;
19
+
20
+ export type Label = (typeof LABELS)[number];
21
+
22
+ /** A path rule's merged changes on the base, newest first. */
23
+ export type PathHistory = {
24
+ readonly sizes: readonly number[];
25
+ readonly labels: readonly Label[];
26
+ };
27
+
28
+ export type Histories = ReadonlyMap<string, PathHistory>;
29
+
30
+ export type Policy = Pick<
31
+ HumConfig,
32
+ "levels" | "paths" | "strictPaths" | "launches" | "sizeRange" | "hookPaths"
33
+ >;
34
+
35
+ /** When the change is placed, and onto which base: launches depend on both. */
36
+ export type Moment = {
37
+ readonly now: number;
38
+ readonly base: string;
39
+ /** The lowest level the change's kind takes. */
40
+ readonly kindFloor?: string;
41
+ /** Globs of paths with a break the owner's level blocks until its follow-up merges. */
42
+ readonly blocked?: readonly string[];
43
+ };
44
+
45
+ /** One reason the level is what it is. */
46
+ export type Step =
47
+ | { readonly step: "path"; readonly glob: string; readonly level: string }
48
+ | { readonly step: "launch"; readonly glob: string; readonly level: string }
49
+ | {
50
+ readonly step: "fix-limit";
51
+ readonly glob: string;
52
+ readonly level: string;
53
+ readonly breaks: number;
54
+ readonly limit: number;
55
+ }
56
+ | { readonly step: "data-or-secret"; readonly path: string }
57
+ | { readonly step: "own-config"; readonly path: string }
58
+ | { readonly step: "kind-floor"; readonly level: string }
59
+ | { readonly step: "blocked-path"; readonly path: string }
60
+ | { readonly step: "engine-pin" }
61
+ | {
62
+ readonly step: "size";
63
+ readonly glob: string;
64
+ readonly size: number;
65
+ readonly usual: number;
66
+ }
67
+ | { readonly step: "loosened-check" }
68
+ | { readonly step: "alignment" };
69
+
70
+ type SetsLevel = Extract<Step, { level: string }>;
71
+
72
+ export type Placement = {
73
+ readonly level: Level;
74
+ /** Paths no rule places. The change runs at the level of the rest and never merges on its own. */
75
+ readonly unclear: readonly string[];
76
+ readonly steps: readonly Step[];
77
+ };
78
+
79
+ const matches = (glob: string, path: string): boolean =>
80
+ new Bun.Glob(glob).match(path);
81
+
82
+ const isLaunchOn = (launch: Launch, { now, base }: Moment): boolean =>
83
+ "base" in launch
84
+ ? matches(launch.base, base)
85
+ : Date.parse(launch.from) <= now && now < Date.parse(launch.until);
86
+
87
+ /** Fixed or reverted changes among a path's last `of` merged changes. */
88
+ const breaksIn = (labels: readonly Label[], of: number): number =>
89
+ labels.slice(0, of).filter((label) => label !== "clean").length;
90
+
91
+ /** The top of a path's usual size range, or undefined while it has too few merged changes to have one. */
92
+ export const usualSize = (
93
+ sizes: readonly number[],
94
+ { changes, fewest, middle }: Policy["sizeRange"],
95
+ ): number | undefined => {
96
+ const recent = sizes.slice(0, changes);
97
+ const upperShare = (1 + middle) / 2;
98
+
99
+ return recent.length < fewest ? undefined : quantile([...recent], upperShare);
100
+ };
101
+
102
+ /**
103
+ * A change's risk level: the highest level among the paths it touches, each raised by a launch or by its
104
+ * fix-and-revert limit; the strictest level for data, secrets and hum's own config; then one step up above a
105
+ * path's usual size range and one for a loosened check. A path no rule places marks the change unclear and
106
+ * never raises its level.
107
+ */
108
+ export const placeChange = (
109
+ change: Change,
110
+ policy: Policy,
111
+ histories: Histories,
112
+ moment: Moment,
113
+ ): Placement => {
114
+ const names = policy.levels.map(({ name }) => name);
115
+ const strictest = names.length - 1;
116
+ const rank = (name: string): number => names.indexOf(name);
117
+
118
+ const above = (name: string): string =>
119
+ names[Math.min(strictest, rank(name) + 1)] ?? name;
120
+
121
+ const rulesOn = (path: string): readonly PathRule[] =>
122
+ policy.paths.filter((rule) => matches(rule.glob, path));
123
+
124
+ const isStrict = (path: string): boolean =>
125
+ policy.strictPaths.some((glob) => matches(glob, path));
126
+
127
+ const isOwn = (path: string): boolean =>
128
+ [...OWN_PATHS, ...policy.hookPaths].some((glob) => matches(glob, path));
129
+
130
+ const touched = [
131
+ ...new Map(
132
+ change.paths.flatMap(rulesOn).map((rule) => [rule.glob, rule]),
133
+ ).values(),
134
+ ];
135
+
136
+ const ruleSteps = touched.flatMap((rule): SetsLevel[] => {
137
+ const limit = rule.limit;
138
+
139
+ const breaks = limit
140
+ ? breaksIn(histories.get(rule.glob)?.labels ?? [], limit.of)
141
+ : 0;
142
+
143
+ const isPastLimit = limit !== undefined && breaks > limit.fixes;
144
+
145
+ return [
146
+ { step: "path", glob: rule.glob, level: rule.level },
147
+ ...(isPastLimit
148
+ ? [
149
+ {
150
+ step: "fix-limit",
151
+ glob: rule.glob,
152
+ level: above(rule.level),
153
+ breaks,
154
+ limit: limit.fixes,
155
+ } as const,
156
+ ]
157
+ : []),
158
+ ];
159
+ });
160
+
161
+ const kindFloorSteps: SetsLevel[] = moment.kindFloor === undefined ? [] : [{ step: "kind-floor", level: moment.kindFloor }];
162
+
163
+ const launchSteps = policy.launches.flatMap((launch): SetsLevel[] =>
164
+ isLaunchOn(launch, moment) &&
165
+ change.paths.some((path) => matches(launch.glob, path))
166
+ ? [{ step: "launch", glob: launch.glob, level: launch.level }]
167
+ : [],
168
+ );
169
+
170
+ const floors: Step[] = [
171
+ ...change.paths.flatMap((path): Step[] =>
172
+ isStrict(path) ? [{ step: "data-or-secret", path }] : [],
173
+ ),
174
+ ...change.paths.flatMap((path): Step[] =>
175
+ isOwn(path) ? [{ step: "own-config", path }] : [],
176
+ ),
177
+ ...(change.pinChanged ? [{ step: "engine-pin" } as const] : []),
178
+ ...change.paths.flatMap((path): Step[] =>
179
+ (moment.blocked ?? []).some((glob) => matches(glob, path)) ? [{ step: "blocked-path", path }] : [],
180
+ ),
181
+ ];
182
+
183
+ const oversized = touched.flatMap((rule): Step[] => {
184
+ const usual = usualSize(
185
+ histories.get(rule.glob)?.sizes ?? [],
186
+ policy.sizeRange,
187
+ );
188
+
189
+ return usual !== undefined && change.size > usual
190
+ ? [{ step: "size", glob: rule.glob, size: change.size, usual }]
191
+ : [];
192
+ });
193
+
194
+ const bumps: Step[] = [
195
+ ...oversized.slice(0, 1),
196
+ ...(change.loosened ? [{ step: "loosened-check" } as const] : []),
197
+ ];
198
+
199
+ const highest = Math.max(
200
+ 0,
201
+ ...[...ruleSteps, ...launchSteps, ...kindFloorSteps].map(({ level }) => rank(level)),
202
+ );
203
+
204
+ const floored = floors.length > 0 ? strictest : highest;
205
+ const level = policy.levels[Math.min(strictest, floored + bumps.length)];
206
+
207
+ if (!level) throw new Error("a config has at least one level");
208
+
209
+ return {
210
+ level,
211
+ unclear: change.paths.filter(
212
+ (path) => rulesOn(path).length === 0 && !isStrict(path) && !isOwn(path),
213
+ ),
214
+ steps: [...ruleSteps, ...launchSteps, ...kindFloorSteps, ...floors, ...bumps],
215
+ };
216
+ };
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ import type { HumConfig } from "../config/schema.ts";
3
+ import { DATA_RULE, fenced } from "./prose.ts";
4
+
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() });
7
+
8
+ export type TasteAnswer = z.infer<typeof TasteAnswer>;
9
+
10
+ /** The cheap model call that checks a diff against one taste rule. Its pick is for a report and decides nothing. */
11
+ export const tasteQuestion = (rule: string, diff: string, { diffLimit }: Pick<HumConfig, "diffLimit">) => ({
12
+ boundary: "taste" as const,
13
+ reportOnly: true as const,
14
+ prompt: [
15
+ "Check this change against the owner's rule. keeps: true when the diff keeps the rule or does not touch it, false when it breaks it. evidence: the line of the diff that shows it, or an empty string.",
16
+ DATA_RULE,
17
+ fenced("rule", rule),
18
+ fenced("diff", diff.slice(0, diffLimit)),
19
+ ].join("\n\n"),
20
+ answer: TasteAnswer,
21
+ });
22
+
23
+ /** One rule's result: its answer, or why the call gave none. */
24
+ export type TasteResult = { readonly rule: string; readonly answer: TasteAnswer | { readonly abstained: string } };
25
+
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 => {
28
+ const lines = results.map(({ rule, answer }) => {
29
+ if ("abstained" in answer) return `- ? ${rule} (not checked: ${answer.abstained})`;
30
+
31
+ return answer.keeps ? `- kept: ${rule}` : `- broken: ${rule}${answer.evidence === "" ? "" : `\n > ${answer.evidence}`}`;
32
+ });
33
+
34
+ const status = measured ? "The model's rate on the owner's past violations meets the bar." : "The model's rate on the owner's past violations is not measured, so this is a report only.";
35
+
36
+ return ["hum checked this change against the owner's taste rules.", lines.join("\n"), `${status} It blocks nothing.`].join("\n\n");
37
+ };
package/src/exec.ts ADDED
@@ -0,0 +1,85 @@
1
+ import pTimeout from "p-timeout";
2
+ import { type Options, type Output, x } from "tinyexec";
3
+ import { type HumConfig, SHIPPED_DEFAULTS } from "./config/schema.ts";
4
+ import { SECOND_MS } from "./time.ts";
5
+
6
+ /** A command ran past its limit and was told to stop. */
7
+ export class CommandTimedOut extends Error {
8
+ override name = "CommandTimedOut";
9
+
10
+ constructor(
11
+ readonly command: string,
12
+ readonly args: readonly string[],
13
+ readonly timeoutMs: number,
14
+ ) {
15
+ super(`\`${[command, ...args].join(" ")}\` ran longer than ${timeoutMs / SECOND_MS} seconds and was stopped`);
16
+ }
17
+ }
18
+
19
+ /** The owner's `commandTimeoutSeconds` in milliseconds. */
20
+ export const commandTimeoutMs = ({ commandTimeoutSeconds }: Pick<HumConfig, "commandTimeoutSeconds">): number => commandTimeoutSeconds * SECOND_MS;
21
+
22
+ /** The limit where no `hum.json` is read yet. */
23
+ export const SHIPPED_COMMAND_TIMEOUT_MS = commandTimeoutMs(SHIPPED_DEFAULTS);
24
+
25
+ /** How long a command's processes get to end after the stop signal before they are killed. */
26
+ const STOP_GRACE_MS = 2000;
27
+ const POLL_MS = 50;
28
+
29
+ export type ExecOptions = Partial<Omit<Options, "timeout" | "signal" | "persist">> & {
30
+ readonly timeoutMs: number;
31
+ readonly graceMs?: number;
32
+ };
33
+
34
+ /**
35
+ * Signals every process in the group, and answers false once none is left to signal. macOS answers EPERM, not ESRCH,
36
+ * while the group holds only processes that have exited and wait to be reaped, as the command itself does until Bun
37
+ * reaps it.
38
+ */
39
+ const signalGroup = (group: number, signal: "SIGTERM" | "SIGKILL" | 0): boolean => {
40
+ try {
41
+ return process.kill(-group, signal);
42
+ } catch (error) {
43
+ if (error instanceof Error && "code" in error && (error.code === "ESRCH" || error.code === "EPERM")) return false;
44
+
45
+ throw error;
46
+ }
47
+ };
48
+
49
+ 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
+
54
+ return !signalGroup(group, 0);
55
+ };
56
+
57
+ /** Ends every process the command started: SIGTERM first, so git removes its lock files, then SIGKILL for what ignores it. */
58
+ const stopGroup = async (group: number, graceMs: number): Promise<void> => {
59
+ signalGroup(group, "SIGTERM");
60
+
61
+ if (await isGone(group, graceMs)) return;
62
+
63
+ signalGroup(group, "SIGKILL");
64
+ await isGone(group, graceMs);
65
+ };
66
+
67
+ /**
68
+ * Runs a command and returns what it printed. The call ends at `timeoutMs` whatever the child does: tinyexec's own
69
+ * `timeout` still waits for the child to exit and close its pipes, which a child that ignores the stop signal, a
70
+ * grandchild that holds a pipe, or an exit the runtime never reports does not allow. The command runs as its own
71
+ * process group, and a timeout ends the whole group, so the helpers git and ssh start do not outlive it. A timeout
72
+ * throws `CommandTimedOut`, never a result.
73
+ */
74
+ export const exec = (command: string, args: readonly string[], { timeoutMs, graceMs = STOP_GRACE_MS, ...options }: ExecOptions): Promise<Output> => {
75
+ const child = x(command, [...args], { ...options, persist: true });
76
+
77
+ return pTimeout(child, {
78
+ milliseconds: timeoutMs,
79
+ fallback: async () => {
80
+ if (child.pid !== undefined) await stopGroup(child.pid, graceMs);
81
+
82
+ throw new CommandTimedOut(command, args, timeoutMs);
83
+ },
84
+ });
85
+ };
package/src/index.ts ADDED
@@ -0,0 +1,200 @@
1
+ export { type Command, commands } from "./cli/commands.ts";
2
+
3
+ export { type CheckEnv, pickTier } from "./config/checks.ts";
4
+
5
+ export {
6
+ applyConfigChange,
7
+ type ConfigChange,
8
+ type ConfigResult,
9
+ isHumBranch,
10
+ } from "./config/change.ts";
11
+
12
+ export { hashJson } from "./config/hash.ts";
13
+
14
+ export { Json } from "./config/json.ts";
15
+
16
+ export {
17
+ type Config,
18
+ listHopeSkills,
19
+ loadConfig,
20
+ type LoadOptions,
21
+ type RawConfig,
22
+ readConfigDir,
23
+ } from "./config/load.ts";
24
+
25
+ export { kindMachine } from "./config/machine.ts";
26
+
27
+ export { MIGRATIONS, type Migrations, migrateConfig } from "./config/migrate.ts";
28
+
29
+ export { describeProblem, type Problem, type Refusal, type Result } from "./config/refusal.ts";
30
+
31
+ export {
32
+ FIXED_PARTS,
33
+ HumConfig,
34
+ Kind,
35
+ MachineJSON,
36
+ OWNER_CHANGEABLE,
37
+ OWNER_WAIT_TAG,
38
+ READABLE_SCHEMA_VERSIONS,
39
+ SCHEMA_VERSION,
40
+ STUCK_TAG,
41
+ WAIT_TAG,
42
+ } from "./config/schema.ts";
43
+
44
+ export { migrateSnapshot, type SavedItem, unmappedItems } from "./config/state-map.ts";
45
+
46
+ export { type Codec, Items, persistedSnapshot, type RestoreOptions } from "./state/items.ts";
47
+
48
+ export { EventLog, type NewEvent, SavedEvent } from "./state/events.ts";
49
+
50
+ export { Faults, type FaultInput, type Outcome } from "./state/faults.ts";
51
+
52
+ export {
53
+ ENGINE_VERSION,
54
+ ENVELOPE_FORMAT,
55
+ ENVELOPE_MIGRATIONS,
56
+ Envelope,
57
+ type EnvelopeMigrations,
58
+ } from "./state/format.ts";
59
+
60
+ export { OpKey, OpKeys, type OpProvider } from "./state/ops.ts";
61
+
62
+ export { defaultStateDir, openState, type State, type StateOptions } from "./state/open.ts";
63
+
64
+ export { type BegunRun, RunKey, RunRecord, RunRecords } from "./state/runs.ts";
65
+
66
+ export { readStatus, type StatusRead, writeStatus } from "./status/file.ts";
67
+
68
+ export { Action, Card, CardAction, Choice, emptyStatus, InFlight, Measure, Merged, Question, Status, STATUS_FORMAT } from "./status/format.ts";
69
+
70
+ export * from "./adapter-api.ts";
71
+
72
+ export { type Admission, admit, type AdmitInput, engineImporters, sourceFiles } from "./adapters/admit.ts";
73
+
74
+ export { type Check, contractChecks, type ContractResult, type ContractTarget, runContract } from "./adapters/contract.ts";
75
+
76
+ export { FakeProvider, ProviderError } from "./adapters/fake.ts";
77
+
78
+ export { pushArgs, PushRefused } from "./adapters/git.ts";
79
+
80
+ export { type GuardOptions, guarded } from "./adapters/guard.ts";
81
+
82
+ export { type GitHubClient, gitHubClient, githubAdapter, type GitHubOptions, repoFromRemote } from "./adapters/github.ts";
83
+
84
+ export { Marker, marked, markerOf, parseComment } from "./adapters/marked.ts";
85
+
86
+ export { markdownAdapter, type MarkdownOptions } from "./adapters/markdown.ts";
87
+
88
+ export { markDone, parseItemFile } from "./adapters/item-file.ts";
89
+
90
+ export { refuseOtherVersion, resolveAdapters, type Slot, SLOTS } from "./adapters/registry.ts";
91
+
92
+ export { type OpName } from "./cli/commands.ts";
93
+
94
+ export { type Io, runCli, runOp } from "./cli/ops.ts";
95
+
96
+ export { limitOf, type LimitEnded, parseLimit, settleLimit } from "./adapters/limit.ts";
97
+
98
+ export { BACKGROUND_CHECK_CODE, FALLBACK_CODE, type BackgroundOptions, type BackgroundStartOptions, backgroundRunner, backgroundSettings, type StartedBackground, startBackgroundRunner } from "./adapters/claude-bg.ts";
99
+
100
+ export {
101
+ CLAUDE_FLOOR,
102
+ type Effort,
103
+ type Finished,
104
+ RUN_SETTINGS,
105
+ type RunOutcome,
106
+ type RunRequest,
107
+ type RunSpec,
108
+ type Runner,
109
+ type RunnerOptions,
110
+ runArgs,
111
+ startRunner,
112
+ succeeded,
113
+ } from "./adapters/claude-p.ts";
114
+
115
+ export {
116
+ PLAN_MARK,
117
+ RUN_SCHEMA,
118
+ runBranch,
119
+ runThinPath,
120
+ type Checkout,
121
+ type Source,
122
+ type ThinPathOptions,
123
+ type ThinResult,
124
+ } from "./worker/thin-path.ts";
125
+
126
+ 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
+
128
+ export { type Approvals, isCleared, type Landing, landingOf, needsReviewRun, OWNER_APPROVAL, type Route, routeOf, type Unclear, waitReason } from "./decide/merge.ts";
129
+
130
+ export { reviewInput } from "./decide/review.ts";
131
+
132
+ export { citesDiff, DATA_RULE, fenced, EventPick, isTrusted, PlanFile, planHash, PROSE_STATES, type ProsePurpose, readPick } from "./decide/prose.ts";
133
+
134
+ export { declaredKind, kindQuestion, leavesDocs, UNSURE } from "./decide/kind.ts";
135
+
136
+ export { AlignmentAnswer, alignedPlacement, alignmentQuestion, GRADES, raisesLevel } from "./decide/alignment.ts";
137
+
138
+ export { configuredModelCall, type Judgment, type ModelCall, modelCallOver, type Question as ModelQuestion } from "./adapters/model-call.ts";
139
+
140
+ export { decideProse, type ProseDecision } from "./worker/prose-run.ts";
141
+
142
+ export { decideKind } from "./worker/kind.ts";
143
+
144
+ export { labelChanges, type LabelRules, matchedSample, type PastChange } from "./decide/labels.ts";
145
+
146
+ export { changeOf, historiesOf, readHistory } from "./adapters/history.ts";
147
+
148
+ export { type CommitLanded, landOwnerCommit, type OwnerCommit } from "./adapters/owner-commit.ts";
149
+
150
+ export { type BranchRules, gitHubPullRequests, methodFor, type Pull, type PullRequests } from "./adapters/pull-requests.ts";
151
+
152
+ export { land, type LandContext, prepareLanding, ruleGlobFor } from "./worker/land.ts";
153
+
154
+ export { roundupAdapter, type RoundupOptions, stdioCall, type ToolCall } from "./adapters/roundup.ts";
155
+
156
+ export { type CallScope, onceCalls } from "./adapters/once.ts";
157
+
158
+ export { serialized } from "./adapters/serial.ts";
159
+
160
+ export { Records } from "./state/records.ts";
161
+
162
+ export { Limit, Parked, ReadyList, Spent } from "./state/saved.ts";
163
+
164
+ export type { SavedSnapshot } from "./state/items.ts";
165
+
166
+ export { Heartbeat } from "./status/format.ts";
167
+
168
+ export { readHeartbeat, writeHeartbeat } from "./status/file.ts";
169
+
170
+ export { type Candidate, type Footprint, footprintOf, overlaps, pick, type Picked, PrefixGate } from "./worker/scheduler.ts";
171
+
172
+ export { installedVersion, type Signature, signatureOf } from "./worker/signature.ts";
173
+
174
+ export { openWorker, type OpenWorkerOptions, npmLatest } from "./worker/open.ts";
175
+
176
+ export { Worker, type WorkerOptions } from "./worker/worker.ts";
177
+
178
+ export type { Exit, TickResult } from "./worker/lifecycle.ts";
179
+
180
+ export { claimTtlMs, park, rememberKinds } from "./worker/thin-path.ts";
181
+
182
+ export { CI_TICK_REF, readCiTick, recordCiTick } from "./service/ci-tick.ts";
183
+
184
+ export { type Child, EXIT_UPDATED, supervise, type Supervision } from "./service/supervise.ts";
185
+
186
+ export { checkTokenAge, TOKEN_LIFE_DAYS } from "./service/token.ts";
187
+
188
+ export { renderUnit, type UnitKind, type UnitVars } from "./service/unit.ts";
189
+
190
+ export { reportCards, wakeUntilQuiet } from "./service/wake.ts";
191
+
192
+ export { ciWorkflows, type WorkflowFile, type WorkflowSettings } from "./service/workflows.ts";
193
+
194
+ export { writeCards } from "./status/file.ts";
195
+
196
+ export { SLOT_ENV, slotEnv } from "./slots/env.ts";
197
+
198
+ export { type PoolOptions, SLOT_KEPT_CODE, SLOT_MAINTENANCE_CODE, SLOT_OUT_CODE, SlotPool } from "./slots/pool.ts";
199
+
200
+ export { proposeRecipe } from "./slots/scan.ts";
@@ -0,0 +1,8 @@
1
+ import type { State } from "../state/open.ts";
2
+
3
+ /** Paths blocked by a break whose level blocks and whose follow-up has not merged. */
4
+ export const blockedPaths = (state: State): string[] =>
5
+ state.breaks.list().flatMap(({ onBreak, followUp, paths }) => (onBreak === "block" && !state.merges.get(followUp) ? paths : []));
6
+
7
+ /** The commits whose merge broke the base: the fix limit counts them beside the breaks git labels. */
8
+ export const brokenCommits = (state: State): ReadonlySet<string> => new Set(state.breaks.list().map(({ sha }) => sha));
@@ -0,0 +1,76 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { WorkSource } from "../adapter-api.ts";
3
+ import type { State } from "../state/open.ts";
4
+ import { noteKey, type RepeatGroup, type ReviewNote } from "./records.ts";
5
+
6
+ const SHORT_HASH = 10;
7
+ const TITLE_CELLS = 60;
8
+
9
+ const hashOf = (groupKey: string): string => createHash("sha1").update(groupKey).digest("hex").slice(0, SHORT_HASH);
10
+
11
+ /** The name the check item is told to give its check, so CI's log can name it. */
12
+ export const checkNameOf = (groupKey: string): string => `hum-check-${hashOf(groupKey)}`;
13
+
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)}`;
16
+
17
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim();
18
+
19
+ const where = ({ file, line }: ReviewNote): string => (file === undefined ? "" : ` on ${file}${line === undefined ? "" : `:${line}`}`);
20
+
21
+ const quoted = (text: string): string => text.split("\n").map((line) => `> ${line}`).join("\n");
22
+
23
+ const noteBlock = (note: ReviewNote): string =>
24
+ [`- ${note.source} ${note.sourceId}${where(note)}, change ${note.change}`, quoted(note.text), ...(note.hunk === "" ? [] : ["", "```diff", note.hunk.trimEnd(), "```"])].join("\n");
25
+
26
+ const titleOf = (note: ReviewNote): string => `Check: ${oneLine(note.text).slice(0, TITLE_CELLS)}`;
27
+
28
+ /** The check item for a group: the kind, the name its check takes, and every note with its link and hunk. */
29
+ const checkItemOf = (first: ReviewNote, notes: readonly ReviewNote[], checkKind: string, checkName: string) => ({
30
+ title: titleOf(first),
31
+ body: [
32
+ `Kind: ${checkKind}`,
33
+ "",
34
+ `The owner made these review notes about one rule. Turn them into one rule with hope:anchor, widen it where the notes show a wider class, and add the cheapest check that decides it: a type, then a rule the repo's linter has, then a custom lint rule, then a test. Name the check \`${checkName}\`. It must fail on each note's commit and pass on the base.`,
35
+ "",
36
+ notes.map(noteBlock).join("\n\n"),
37
+ ].join("\n"),
38
+ });
39
+
40
+ export type FilingOptions = {
41
+ readonly state: State;
42
+ readonly workSource: Pick<WorkSource, "fileFollowUp" | "comment">;
43
+ /** Notes stating one rule at which a check item is filed. */
44
+ readonly repeatAt: number;
45
+ readonly checkKind: string;
46
+ };
47
+
48
+ const notesOf = (state: State, group: RepeatGroup): ReviewNote[] =>
49
+ group.notes.flatMap((key) => state.notes.get(key) ?? []).toSorted((a, b) => a.at - b.at);
50
+
51
+ /**
52
+ * Files one check item for each group that reached `repeatAt` notes and has none, and adds every later note to its
53
+ * item's thread. The item's id comes from the group, so a rerun files nothing.
54
+ */
55
+ export const fileChecks = async ({ state, workSource, repeatAt, checkKind }: FilingOptions): Promise<void> => {
56
+ for (const group of state.repeats.list()) {
57
+ const notes = notesOf(state, group);
58
+
59
+ const [first] = notes;
60
+
61
+ if (first === undefined || notes.length < repeatAt) continue;
62
+
63
+ if (group.item === undefined) {
64
+ const filed = await workSource.fileFollowUp(filedFrom(group.key), checkItemOf(first, notes, checkKind, checkNameOf(group.key)));
65
+
66
+ state.repeats.put(group.key, { ...group, item: filed.id, commented: group.notes });
67
+ continue;
68
+ }
69
+
70
+ const unposted = notes.filter((found) => !group.commented.includes(noteKey(found)));
71
+
72
+ for (const note of unposted) await workSource.comment(group.item, noteBlock(note));
73
+
74
+ if (unposted.length > 0) state.repeats.put(group.key, { ...group, commented: group.notes });
75
+ }
76
+ };
package/src/loop/ci.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { RepeatGroup } from "./records.ts";
2
+ import { checkNameOf } from "./check-item.ts";
3
+
4
+ /** The text of CI runs that started after a time; the integration reads them from the CI provider. */
5
+ export type CiLogs = (since: number) => Promise<readonly string[]>;
6
+
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));