@moo.md/hum 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/package.json +2 -2
  2. package/scripts/eval.ts +88 -50
  3. package/src/adapter-api.ts +46 -14
  4. package/src/adapters/admit.ts +2 -2
  5. package/src/adapters/argument.ts +1 -1
  6. package/src/adapters/claim.ts +18 -15
  7. package/src/adapters/claude-bg.ts +50 -27
  8. package/src/adapters/claude-p.ts +18 -23
  9. package/src/adapters/contract.ts +22 -10
  10. package/src/adapters/each-call.ts +9 -0
  11. package/src/adapters/fake.ts +6 -6
  12. package/src/adapters/git.ts +10 -18
  13. package/src/adapters/github-client.ts +102 -0
  14. package/src/adapters/github.ts +34 -142
  15. package/src/adapters/guard.ts +20 -9
  16. package/src/adapters/history.ts +12 -15
  17. package/src/adapters/item-file.ts +1 -1
  18. package/src/adapters/markdown.ts +49 -42
  19. package/src/adapters/marked.ts +6 -12
  20. package/src/adapters/model-call.ts +4 -4
  21. package/src/adapters/once.ts +5 -5
  22. package/src/adapters/owner-commit.ts +13 -11
  23. package/src/adapters/pull-requests.ts +11 -13
  24. package/src/adapters/registry.ts +7 -7
  25. package/src/adapters/roundup.ts +27 -35
  26. package/src/adapters/serial.ts +4 -5
  27. package/src/adapters/transcript.ts +13 -8
  28. package/src/cli/main.ts +1 -0
  29. package/src/cli/ops.ts +32 -14
  30. package/src/cli/service.ts +14 -8
  31. package/src/cli/setup.ts +8 -3
  32. package/src/cli/shared-watch.ts +3 -3
  33. package/src/config/checks.ts +14 -18
  34. package/src/config/machine.ts +5 -7
  35. package/src/config/refusal.ts +7 -0
  36. package/src/config/schema.ts +7 -7
  37. package/src/config/settings.ts +17 -2
  38. package/src/config/state-map.ts +5 -3
  39. package/src/decide/alignment.ts +4 -4
  40. package/src/decide/answer.ts +24 -22
  41. package/src/decide/kind.ts +1 -6
  42. package/src/decide/labels.ts +9 -9
  43. package/src/decide/merge.ts +6 -7
  44. package/src/decide/prose.ts +4 -4
  45. package/src/decide/question.ts +23 -20
  46. package/src/decide/review.ts +4 -2
  47. package/src/decide/risk.ts +25 -19
  48. package/src/decide/taste.ts +3 -3
  49. package/src/exec.ts +4 -3
  50. package/src/index.ts +14 -13
  51. package/src/loop/check-item.ts +3 -3
  52. package/src/loop/ci.ts +1 -1
  53. package/src/loop/github.ts +2 -2
  54. package/src/loop/groups.ts +13 -6
  55. package/src/loop/memory.ts +40 -28
  56. package/src/loop/notes.ts +5 -5
  57. package/src/loop/pair.ts +1 -1
  58. package/src/loop/pass.ts +18 -12
  59. package/src/loop/proof.ts +9 -7
  60. package/src/loop/prove-item.ts +1 -1
  61. package/src/loop/records.ts +12 -13
  62. package/src/loop/signals.ts +6 -6
  63. package/src/measure/inputs.ts +1 -1
  64. package/src/measure/measure.ts +4 -4
  65. package/src/measure/rate.ts +2 -0
  66. package/src/service/ci-tick.ts +2 -2
  67. package/src/service/supervise.ts +3 -2
  68. package/src/service/token.ts +3 -3
  69. package/src/service/wake.ts +2 -2
  70. package/src/service/workflows.ts +2 -2
  71. package/src/setup/propose.ts +4 -4
  72. package/src/setup/prove.ts +18 -12
  73. package/src/setup/scan.ts +31 -24
  74. package/src/setup/shipped.ts +8 -2
  75. package/src/setup/tables.ts +4 -3
  76. package/src/setup/waits.ts +9 -11
  77. package/src/setup/write.ts +17 -10
  78. package/src/slots/pool.ts +32 -24
  79. package/src/state/events.ts +1 -1
  80. package/src/state/faults.ts +13 -5
  81. package/src/state/format.ts +2 -2
  82. package/src/state/items.ts +9 -10
  83. package/src/state/open.ts +2 -2
  84. package/src/state/ops.ts +16 -10
  85. package/src/state/records.ts +5 -5
  86. package/src/state/runs.ts +33 -26
  87. package/src/state/saved.ts +44 -32
  88. package/src/status/file.ts +20 -1
  89. package/src/status/format.ts +47 -57
  90. package/src/status/sections.ts +2 -2
  91. package/src/worker/alignment-report.ts +4 -5
  92. package/src/worker/answers.ts +26 -24
  93. package/src/worker/base-check.ts +2 -2
  94. package/src/worker/kind.ts +23 -19
  95. package/src/worker/land.ts +114 -126
  96. package/src/worker/merged.ts +9 -7
  97. package/src/worker/open.ts +14 -12
  98. package/src/worker/prose-run.ts +3 -3
  99. package/src/worker/questions.ts +15 -12
  100. package/src/worker/scheduler.ts +4 -4
  101. package/src/worker/signature.ts +3 -3
  102. package/src/worker/tally.ts +0 -2
  103. package/src/worker/taste.ts +6 -15
  104. package/src/worker/thin-path.ts +148 -121
  105. package/src/worker/thread.ts +25 -0
  106. package/src/worker/worker.ts +77 -47
  107. package/surface.json +632 -2197
  108. package/src/slots/scan.ts +0 -26
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);
package/src/loop/pass.ts CHANGED
@@ -4,9 +4,9 @@ import type { Config } from "../config/load.ts";
4
4
  import type { PastChange } from "../decide/labels.ts";
5
5
  import type { State } from "../state/open.ts";
6
6
  import { checkNameOf, fileChecks, filedFrom } from "./check-item.ts";
7
- import { type CiLogs, logNames } from "./ci.ts";
7
+ import { type CiLogs, doesLogName } from "./ci.ts";
8
8
  import { type Proposer, groupNotes } from "./groups.ts";
9
- import { parseMemory, renderMemory, withoutCovered } from "./memory.ts";
9
+ import { withoutCovered } from "./memory.ts";
10
10
  import { breakNotes, ownerNotes, planChangingNotes, type RawComment, saveNotes } from "./notes.ts";
11
11
  import { type RepeatGroup, type ReviewNote, noteKey } from "./records.ts";
12
12
 
@@ -42,7 +42,7 @@ const unappliedCard = (state: State) => (extension: string, signals: readonly st
42
42
  };
43
43
 
44
44
  /** Step 1: the owner's notes from each source, saved once. Returns the ones this pass added. */
45
- export const collectNotes = async ({ state, config, comments, history, hunkOf }: LoopPass): Promise<ReviewNote[]> =>
45
+ const collectNotes = async ({ state, config, comments, history, hunkOf }: LoopPass): Promise<ReviewNote[]> =>
46
46
  saveNotes(state, [
47
47
  ...ownerNotes(await comments(sinceOfLastComment(state)), config.hum.ownerLogins),
48
48
  ...planChangingNotes(state.answers.list()),
@@ -51,15 +51,19 @@ export const collectNotes = async ({ state, config, comments, history, hunkOf }:
51
51
 
52
52
  /** Step 6: a landed check item whose name the next CI run's log shows. */
53
53
  export const confirmChecks = async ({ state, ciLogs, now }: Pick<LoopPass, "state" | "ciLogs" | "now">): Promise<void> => {
54
- for (const group of state.repeats.list()) {
54
+ const unconfirmed = state.repeats.list().flatMap((group) => {
55
55
  const merge = group.item === undefined ? undefined : state.merges.get(group.item);
56
56
 
57
- if (group.checked || !merge) continue;
57
+ return group.checked || !merge ? [] : [{ group, merge }];
58
+ });
58
59
 
59
- const logs = await ciLogs(merge.at);
60
+ await Promise.all(
61
+ unconfirmed.map(async ({ group, merge }) => {
62
+ const logs = await ciLogs(merge.at);
60
63
 
61
- if (logs.some((log) => logNames(log, group.key))) state.repeats.put(group.key, { ...group, checked: { at: now(), check: checkNameOf(group.key) } });
62
- }
64
+ if (logs.some((log) => doesLogName(log, group.key))) state.repeats.put(group.key, { ...group, checked: { at: now(), check: checkNameOf(group.key) } });
65
+ }),
66
+ );
63
67
  };
64
68
 
65
69
  const missesOf = (state: State, group: RepeatGroup): ReviewNote[] =>
@@ -69,11 +73,13 @@ const missesOf = (state: State, group: RepeatGroup): ReviewNote[] =>
69
73
  export const closeLoop = async ({ state, workSource, memoryPath }: Pick<LoopPass, "state" | "workSource" | "memoryPath">): Promise<void> => {
70
74
  const covered = new Set(state.repeats.list().flatMap((group) => (group.checked ? group.notes : [])));
71
75
 
72
- if (memoryPath !== undefined && covered.size > 0 && existsSync(memoryPath)) {
73
- const held = parseMemory(readFileSync(memoryPath, "utf8"));
74
- const kept = withoutCovered(held, covered);
76
+ const hasEntriesToDrop = memoryPath !== undefined && covered.size > 0 && existsSync(memoryPath);
77
+
78
+ if (hasEntriesToDrop) {
79
+ const text = readFileSync(memoryPath, "utf8");
80
+ const kept = withoutCovered(text, covered);
75
81
 
76
- if (kept.length < held.length) writeFileSync(memoryPath, renderMemory(kept));
82
+ if (kept !== text) writeFileSync(memoryPath, kept);
77
83
  }
78
84
 
79
85
  for (const group of state.repeats.list()) {
package/src/loop/proof.ts CHANGED
@@ -19,14 +19,15 @@ export type ProofOptions = {
19
19
  readonly now: () => number;
20
20
  };
21
21
 
22
- export type ProofResult = {
23
- readonly passed: boolean;
24
- readonly reason?: string;
22
+ /** What a proof cost. */
23
+ type ProofCost = {
25
24
  /** Worktrees made: one per note commit and one for the head. */
26
25
  readonly worktrees: number;
27
26
  readonly ms: number;
28
27
  };
29
28
 
29
+ export type ProofResult = ProofCost & ({ readonly passed: true } | { readonly passed: false; readonly reason: string });
30
+
30
31
  const isCommit = async (git: Git, sha: string): Promise<boolean> => (await git.run(["cat-file", "-e", `${sha}^{commit}`])).code === 0;
31
32
 
32
33
  /** The files the check item adds or changes against the base. */
@@ -56,13 +57,14 @@ export const proveCheck = async ({ git, head, base, notes, checks, timeoutMs, no
56
57
  const started = now();
57
58
  let worktrees = 0;
58
59
 
59
- const done = (reason?: string): ProofResult => ({ passed: reason === undefined, reason, worktrees, ms: now() - started });
60
+ const cost = (): ProofCost => ({ worktrees, ms: now() - started });
61
+ const failed = (reason: string): ProofResult => ({ passed: false, reason, ...cost() });
60
62
 
61
63
  const files = await checkFiles(git, base, head);
62
64
  const commits = [...new Set(notes.map(({ change }) => change))];
63
65
  const provable = (await Promise.all(commits.map(async (sha) => ((await isCommit(git, sha)) ? [sha] : [])))).flat();
64
66
 
65
- if (provable.length === 0) return done("no note points at a commit the check can run on");
67
+ if (provable.length === 0) return failed("no note points at a commit the check can run on");
66
68
 
67
69
  for (const sha of provable) {
68
70
  const failure = await inWorktreeAt(git, sha, async (folder) => {
@@ -72,7 +74,7 @@ export const proveCheck = async ({ git, head, base, notes, checks, timeoutMs, no
72
74
  return runChecks(checks, folder, { timeoutMs });
73
75
  });
74
76
 
75
- if (failure === undefined) return done(`the check passes on ${sha}, the commit a note points at`);
77
+ if (failure === undefined) return failed(`the check passes on ${sha}, the commit a note points at`);
76
78
  }
77
79
 
78
80
  const failure = await inWorktreeAt(git, head, async (folder) => {
@@ -81,5 +83,5 @@ export const proveCheck = async ({ git, head, base, notes, checks, timeoutMs, no
81
83
  return runChecks(checks, folder, { timeoutMs });
82
84
  });
83
85
 
84
- return failure === undefined ? done() : done(`the checks fail on the check item's own commit: ${failure.slice(0, 300)}`);
86
+ return failure === undefined ? { passed: true, ...cost() } : failed(`the checks fail on the check item's own commit: ${failure.slice(0, 300)}`);
85
87
  };
@@ -27,7 +27,7 @@ export const proveCheckItem = async ({ state, config, git, item, base, checks, n
27
27
  const head = (await git.raw(["rev-parse", "HEAD"])).trim();
28
28
  const proof = await proveCheck({ git, head, base: `origin/${base}`, notes, checks, timeoutMs: checksTimeoutMs(config.hum), now });
29
29
 
30
- state.proofs.put(item, { item, at: now(), passed: proof.passed, reason: proof.reason, worktrees: proof.worktrees, ms: proof.ms });
30
+ state.proofs.put(item, { item, at: now(), ...proof });
31
31
 
32
32
  return proof;
33
33
  };
@@ -4,12 +4,12 @@ const name = z.string().min(1);
4
4
  const time = z.int().nonnegative();
5
5
 
6
6
  /** Where a review note comes from. */
7
- export const NOTE_SOURCES = ["review-comment", "review-body", "plan-answer", "revert", "fix"] as const;
7
+ const NOTE_SOURCES = ["review-comment", "review-body", "plan-answer", "revert", "fix"] as const;
8
8
 
9
9
  export type NoteSource = (typeof NOTE_SOURCES)[number];
10
10
 
11
11
  /** One correction the owner made to hum's work, saved before anything acts on it and keyed by its source and source id. */
12
- export const ReviewNote = z.strictObject({
12
+ export const ReviewNote = z.object({
13
13
  source: z.enum(NOTE_SOURCES),
14
14
  sourceId: name,
15
15
  /** What the note is about: the commit a comment sits on, the change a revert or fix names, or the item a plan answer corrected. */
@@ -30,7 +30,7 @@ export type ReviewNote = z.infer<typeof ReviewNote>;
30
30
  export const noteKey = ({ source, sourceId }: Pick<ReviewNote, "source" | "sourceId">): string => `${source}:${sourceId}`;
31
31
 
32
32
  /** Notes that state one rule. The key is its first note's, so a later note joins instead of starting another group. */
33
- export const RepeatGroup = z.strictObject({
33
+ export const RepeatGroup = z.object({
34
34
  key: name,
35
35
  notes: z.array(name),
36
36
  /** The check item filed for the group. */
@@ -38,7 +38,7 @@ export const RepeatGroup = z.strictObject({
38
38
  /** Notes already added to the item's thread. */
39
39
  commented: z.array(name),
40
40
  /** The check landed and CI ran it. */
41
- checked: z.strictObject({ at: time, check: name }).optional(),
41
+ checked: z.object({ at: time, check: name }).optional(),
42
42
  /** Notes that came after the check ran in CI. */
43
43
  misses: z.array(name),
44
44
  });
@@ -46,30 +46,29 @@ export const RepeatGroup = z.strictObject({
46
46
  export type RepeatGroup = z.infer<typeof RepeatGroup>;
47
47
 
48
48
  /** Two notes only a model found alike, waiting for its precision to reach the owner's bar. */
49
- export const PossibleRepeat = z.strictObject({ a: name, b: name, models: z.array(name), at: time });
49
+ export const PossibleRepeat = z.object({ a: name, b: name, models: z.array(name), at: time });
50
50
 
51
51
  export type PossibleRepeat = z.infer<typeof PossibleRepeat>;
52
52
 
53
53
  /** A merged change: what the measure counts. */
54
- export const Merge = z.strictObject({ item: name, sha: name, at: time, paths: z.array(name) });
54
+ export const Merge = z.object({ item: name, sha: name, at: time, paths: z.array(name) });
55
55
 
56
56
  export type Merge = z.infer<typeof Merge>;
57
57
 
58
58
  /** A test of the base that failed after an item's change merged. */
59
- export const Break = z.strictObject({ item: name, sha: name, at: time, paths: z.array(name), level: name, failure: z.string(), onBreak: z.enum(["follow-up", "block"]), followUp: name });
59
+ export const Break = z.object({ item: name, sha: name, at: time, paths: z.array(name), level: name, failure: z.string(), onBreak: z.enum(["follow-up", "block"]), followUp: name });
60
60
 
61
61
  export type Break = z.infer<typeof Break>;
62
62
 
63
- /** What proving a check cost: the commits it ran on, and the time it took. */
64
- export const Proof = z.strictObject({
63
+ const proofFields = {
65
64
  item: name,
66
65
  at: time,
67
- passed: z.boolean(),
68
- /** Why it failed, when it did. */
69
- reason: z.string().optional(),
70
66
  /** Worktrees made: one per note commit and one for the check's own head. */
71
67
  worktrees: z.int().nonnegative(),
72
68
  ms: z.int().nonnegative(),
73
- });
69
+ };
70
+
71
+ /** What proving a check cost: the commits it ran on, and the time it took; a failed proof says why. */
72
+ export const Proof = z.discriminatedUnion("passed", [z.object({ ...proofFields, passed: z.literal(true) }), z.object({ ...proofFields, passed: z.literal(false), reason: z.string() })]);
74
73
 
75
74
  export type Proof = z.infer<typeof Proof>;
@@ -48,7 +48,7 @@ const codePatternOf = (hunk: string): string =>
48
48
  .replace(/\s+/g, "");
49
49
 
50
50
  /** The glob that holds a file's folder and kind: its siblings of the same extension. */
51
- export const globOf = (file: string): string => `${dirname(file)}/*${extname(file)}`;
51
+ const globOf = (file: string): string => `${dirname(file)}/*${extname(file)}`;
52
52
 
53
53
  const parsedOf = (note: ReviewNote): { identifiers: Set<string>; declared: Set<string> } | undefined => {
54
54
  if (note.hunk === "") return { identifiers: new Set(), declared: new Set() };
@@ -91,7 +91,7 @@ export const prepare = (note: ReviewNote): Prepared => {
91
91
  };
92
92
  };
93
93
 
94
- const shares = <T>(a: Set<T> | undefined, b: Set<T> | undefined): boolean => a !== undefined && b !== undefined && [...a].some((found) => b.has(found));
94
+ const doShare = <T>(a: Set<T> | undefined, b: Set<T> | undefined): boolean => a !== undefined && b !== undefined && [...a].some((found) => b.has(found));
95
95
 
96
96
  /** Two notes on one change are about one hunk; only notes across changes repeat. */
97
97
  const isAnotherChange = (a: Prepared, b: Prepared): boolean => a.note.change !== b.note.change;
@@ -106,11 +106,11 @@ type Signal = {
106
106
  };
107
107
 
108
108
  /** The deterministic signals, checked in order. */
109
- export const SIGNALS: readonly Signal[] = [
109
+ const SIGNALS: readonly Signal[] = [
110
110
  { name: "same-text", parsed: false, pairs: (a, b) => a.text === b.text },
111
- { name: "same-code", parsed: false, pairs: (a, b) => shares(a.suggestions, b.suggestions) || shares(a.spans, b.spans) },
112
- { name: "shared-identifier", parsed: true, pairs: (a, b) => isAnotherChange(a, b) && shares(a.named, b.named) },
113
- { name: "same-glob-symbol", parsed: true, pairs: (a, b) => isAnotherChange(a, b) && a.glob !== undefined && a.glob === b.glob && shares(a.declared, b.declared) },
111
+ { name: "same-code", parsed: false, pairs: (a, b) => doShare(a.suggestions, b.suggestions) || doShare(a.spans, b.spans) },
112
+ { name: "shared-identifier", parsed: true, pairs: (a, b) => isAnotherChange(a, b) && doShare(a.named, b.named) },
113
+ { name: "same-glob-symbol", parsed: true, pairs: (a, b) => isAnotherChange(a, b) && a.glob !== undefined && a.glob === b.glob && doShare(a.declared, b.declared) },
114
114
  {
115
115
  name: "same-code-pattern",
116
116
  parsed: false,
@@ -1,10 +1,10 @@
1
1
  import type { State } from "../state/open.ts";
2
2
  import type { Counted } from "./measure.ts";
3
3
 
4
- /** Spent records of work outside any item carry this prefix. */
5
4
  /** The prefix of the op key every question to the owner is written under. */
6
5
  const QUESTION_OP = "question:";
7
6
 
7
+ /** Spent records of work outside any item carry this prefix. */
8
8
  export const LOOP_SPEND_PREFIX = "loop:";
9
9
 
10
10
  /** Reads what each item cost from what the engine saved: notes, question events and the item's token total. */
@@ -6,7 +6,7 @@ export type MergedChange = Counted & { readonly item: string; readonly at: numbe
6
6
  /** An item that never merged. Its cost counts all the same, so dropping work never lowers a number. */
7
7
  export type AbandonedItem = Counted & { readonly item: string; readonly since: number; readonly paths: readonly string[] };
8
8
 
9
- export type PerMerge = { readonly merges: number; readonly abandoned: number; readonly notes: number; readonly questions: number; readonly tokens: number };
9
+ type PerMerge = { readonly merges: number; readonly abandoned: number; readonly notes: number; readonly questions: number; readonly tokens: number };
10
10
 
11
11
  export type MeasureInput = {
12
12
  readonly merged: readonly MergedChange[];
@@ -47,7 +47,7 @@ const abandonedSince = (abandoned: readonly AbandonedItem[], inWindow: readonly
47
47
  return abandoned.filter(({ since }) => since >= start);
48
48
  };
49
49
 
50
- const touches = (glob: string, paths: readonly string[]): boolean => paths.some((path) => new Bun.Glob(glob).match(path));
50
+ const doesTouch = (glob: string, paths: readonly string[]): boolean => paths.some((path) => new Bun.Glob(glob).match(path));
51
51
 
52
52
  /**
53
53
  * The three numbers per merged change over the last `window` merged changes, and over each path's own last
@@ -59,9 +59,9 @@ export const measureOf = ({ merged, abandoned, loopTokens, window, globs }: Meas
59
59
  if (recent.length === 0) return undefined;
60
60
 
61
61
  const byPath = globs.flatMap((glob) => {
62
- const onPath = newestFirst(merged.filter(({ paths }) => touches(glob, paths)), window);
62
+ const onPath = newestFirst(merged.filter(({ paths }) => doesTouch(glob, paths)), window);
63
63
 
64
- return onPath.length === 0 ? [] : [{ glob, ...perMerge(onPath, abandonedSince(abandoned, onPath).filter(({ paths }) => touches(glob, paths)), 0) }];
64
+ return onPath.length === 0 ? [] : [{ glob, ...perMerge(onPath, abandonedSince(abandoned, onPath).filter(({ paths }) => doesTouch(glob, paths)), 0) }];
65
65
  });
66
66
 
67
67
  return { window, ...perMerge(recent, abandonedSince(abandoned, recent), loopTokens), byPath };
@@ -0,0 +1,2 @@
1
+ /** The share of measured cases a model got right; none when nothing was measured, so no rate stands in for a measurement. */
2
+ export const rateOf = (right: number, measured: number): number | undefined => (measured === 0 ? undefined : right / measured);