@moo.md/hum 0.0.0-stage → 0.0.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 +375 -0
  32. package/src/adapters/claude-p.ts +593 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +155 -0
  36. package/src/adapters/github.ts +457 -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 +119 -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 +291 -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 +80 -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 +189 -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 +46 -0
  135. package/src/worker/checks.ts +26 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +508 -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 +728 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
@@ -0,0 +1,99 @@
1
+ import { join } from "node:path";
2
+ import { z } from "zod";
3
+ import { atomicWrite, createOnce, listFiles, listRecords, orMissing, readJson, slug } from "./fs.ts";
4
+
5
+ export const RunKey = z.strictObject({ itemId: z.string().min(1), run: z.string().min(1), attempt: z.int().nonnegative() });
6
+
7
+ export type RunKey = z.infer<typeof RunKey>;
8
+
9
+ export const RunRecord = RunKey.extend({
10
+ /** On the Mac the run's name is saved before launch and found by it after a crash. */
11
+ name: z.string().min(1),
12
+ /** The Claude session id: set ahead in CI, learned after launch on the Mac. */
13
+ sessionId: z.string().min(1).optional(),
14
+ savedAt: z.int().nonnegative(),
15
+ /** Set when the run's outcome has been taken; a record without it is a run a restart adopts. */
16
+ endedAt: z.int().nonnegative().optional(),
17
+ /** The rules of memory.md the run says it applied; absent when the run was shown none. */
18
+ memoryUsed: z.array(z.string()).optional(),
19
+ });
20
+
21
+ export type RunRecord = z.infer<typeof RunRecord>;
22
+
23
+ export type BegunRun = { readonly record: RunRecord; readonly adopted: boolean };
24
+
25
+ /** The run's name, then its session id, saved so a restart adopts the run and never starts it twice. */
26
+ export class RunRecords {
27
+ readonly #folder: string;
28
+ readonly #now: () => number;
29
+
30
+ constructor(folder: string, now: () => number) {
31
+ this.#folder = folder;
32
+ this.#now = now;
33
+ }
34
+
35
+ #path(key: RunKey): string {
36
+ return join(this.#folder, slug(key.itemId), `${slug(`${key.run}\u0000${key.attempt}`)}.json`);
37
+ }
38
+
39
+ get(key: RunKey): RunRecord | undefined {
40
+ return orMissing(() => RunRecord.parse(readJson(this.#path(RunKey.parse(key)))), undefined);
41
+ }
42
+
43
+ /** Saves the run before it launches. When one is already saved for this key, returns it unchanged, so the caller adopts it. */
44
+ begin(key: RunKey, name: string, sessionId?: string): BegunRun {
45
+ const record = RunRecord.parse({ ...key, name, sessionId, savedAt: this.#now() });
46
+ const created = createOnce(this.#path(record), `${JSON.stringify(record)}\n`);
47
+ const saved = created ? record : this.get(key);
48
+
49
+ if (!saved) throw new Error(`run record for ${key.itemId} ${key.run} #${key.attempt} vanished after it was found`);
50
+
51
+ return { record: saved, adopted: !created };
52
+ }
53
+
54
+ /** Saves the session id once the launch has reported it. */
55
+ saveSession(key: RunKey, sessionId: string): RunRecord {
56
+ const record = this.get(key);
57
+
58
+ if (!record) throw new Error(`no saved run for ${key.itemId} ${key.run} #${key.attempt}; call begin before launch`);
59
+
60
+ const next = RunRecord.parse({ ...record, sessionId });
61
+
62
+ atomicWrite(this.#path(next), `${JSON.stringify(next)}\n`);
63
+
64
+ return next;
65
+ }
66
+
67
+ /** Marks the run's outcome as taken, so a restart starts a new attempt and adopts nothing. */
68
+ end(key: RunKey, memoryUsed?: readonly string[]): RunRecord {
69
+ const record = this.get(key);
70
+
71
+ if (!record) throw new Error(`no saved run for ${key.itemId} ${key.run} #${key.attempt}; call begin before launch`);
72
+
73
+ const next = RunRecord.parse({ ...record, endedAt: this.#now(), memoryUsed: memoryUsed && [...memoryUsed] });
74
+
75
+ atomicWrite(this.#path(next), `${JSON.stringify(next)}\n`);
76
+
77
+ return next;
78
+ }
79
+
80
+ /** The item's run of this purpose that was begun and never ended: the one a restart adopts. */
81
+ unended(itemId: string, run: string): RunRecord | undefined {
82
+ return this.list(itemId).find((record) => record.run === run && record.endedAt === undefined);
83
+ }
84
+
85
+ /** Every item's saved runs, oldest first. */
86
+ all(): RunRecord[] {
87
+ return listFiles(this.#folder)
88
+ .flatMap(listRecords)
89
+ .map((file) => RunRecord.parse(readJson(file)))
90
+ .sort((a, b) => a.savedAt - b.savedAt);
91
+ }
92
+
93
+ /** The item's saved runs, oldest first. */
94
+ list(itemId: string): RunRecord[] {
95
+ return listRecords(join(this.#folder, slug(itemId)))
96
+ .map((file) => RunRecord.parse(readJson(file)))
97
+ .sort((a, b) => a.savedAt - b.savedAt || a.attempt - b.attempt);
98
+ }
99
+ }
@@ -0,0 +1,119 @@
1
+ import { z } from "zod";
2
+ import { AlignmentAnswer } from "../decide/alignment.ts";
3
+ import { Cite, PlanFile } from "../decide/prose.ts";
4
+
5
+ const name = z.string().min(1);
6
+ const time = z.int().nonnegative();
7
+
8
+ /** Why an item sits out: it ended stuck, or its change waits for the owner's review. Until the owner acts, no run starts for it. */
9
+ export const Parked = z.strictObject({ item: name, why: z.enum(["stuck", "review"]), cause: name, since: time });
10
+
11
+ export type Parked = z.infer<typeof Parked>;
12
+
13
+ /** Tokens an item has spent over all its runs. The cap counts those after `base`, the total when the owner last answered. */
14
+ export const Spent = z.strictObject({ item: name, total: time, base: time });
15
+
16
+ export type Spent = z.infer<typeof Spent>;
17
+
18
+ /** Until when every run is held. Saved so a restart makes no call before it. */
19
+ export const Limit = z.strictObject({ until: time });
20
+
21
+ /** The ids a provider last listed as ready, so a restart still sees an empty list that contradicts them. */
22
+ export const ReadyList = z.strictObject({ ids: z.array(name) });
23
+
24
+ /** A finished change on its way to the base: what its diff showed, so a retry lands it again without a run. */
25
+ export const Landing = z.strictObject({
26
+ item: name,
27
+ branch: name,
28
+ since: time,
29
+ change: z.strictObject({ paths: z.array(name), size: z.int().nonnegative(), loosened: z.boolean(), pinChanged: z.boolean() }),
30
+ /** The commit the change ends at, before hum marks the item done: what a review reads. */
31
+ head: name,
32
+ /** The owner approved this change in its review state, before it was saved. */
33
+ ownerApproved: z.boolean(),
34
+ /** The alignment call's grades, or why it abstained; made once per change. */
35
+ alignment: z.union([z.strictObject({ graded: AlignmentAnswer }), z.strictObject({ abstained: name })]).optional(),
36
+ });
37
+
38
+ export type Landing = z.infer<typeof Landing>;
39
+
40
+ /** A path rule the owner's answer made, committed on the base; the view lists it with an undo. */
41
+ export const Learned = z.strictObject({ glob: name, level: name, item: name, commit: name, pull: name.optional(), at: time });
42
+
43
+ export type Learned = z.infer<typeof Learned>;
44
+
45
+ /** The model ids that answered a model-judgment call; the measured record decides later whether they count. */
46
+ const models = z.array(name);
47
+
48
+ /** An item's kind, decided once: named by its source, picked by the model call, or the fallback when the call abstained. */
49
+ export const ItemKind = z.discriminatedUnion("from", [
50
+ z.strictObject({ item: name, kind: name, from: z.literal("source") }),
51
+ z.strictObject({ item: name, kind: name, from: z.literal("model") }),
52
+ z.strictObject({ item: name, kind: name, from: z.literal("fallback"), why: name }),
53
+ ]);
54
+
55
+ export type ItemKind = z.infer<typeof ItemKind>;
56
+
57
+ /** The plan a plan run made ready, saved with its hash so later runs read it unchanged. */
58
+ export const SavedPlan = z.strictObject({ item: name, plan: PlanFile, hash: name, models });
59
+
60
+ export type SavedPlan = z.infer<typeof SavedPlan>;
61
+
62
+ /** A fresh review run's verdict on the change that ends at `head`. */
63
+ export const Verdict = z.strictObject({ item: name, head: name, event: name, reason: z.string(), cites: z.array(Cite), models });
64
+
65
+ export type Verdict = z.infer<typeof Verdict>;
66
+
67
+ /** A question the run asked, waiting for room under the daily cap until `askedAt` is set; `askedAt` stays to count the day. */
68
+ export const QueuedQuestion = z.strictObject({
69
+ item: name,
70
+ text: name,
71
+ options: z.array(name).optional(),
72
+ detail: z.string().optional(),
73
+ /** The index of the item's best priority label; no label is last. */
74
+ priority: z.int().nonnegative(),
75
+ /** The files the item declares it touches; none declared means it clashes with every item. */
76
+ footprint: z.array(name).optional(),
77
+ queuedAt: time,
78
+ askedAt: time.optional(),
79
+ });
80
+
81
+ export type QueuedQuestion = z.infer<typeof QueuedQuestion>;
82
+
83
+ /** What became of one answer on an item's thread, saved before its reply is posted. */
84
+ export const SettledAnswer = z.strictObject({
85
+ item: name,
86
+ /** The answer's number among the thread's answers and replies from people. */
87
+ ordinal: z.int().positive(),
88
+ text: name,
89
+ /** The option the answer picked, when it picked one. */
90
+ option: name.optional(),
91
+ source: z.enum(["marker", "free", "first-word", "model", "none-of-these", "abstained"]),
92
+ disposition: z.enum(["applied", "held", "dropped"]),
93
+ why: name,
94
+ at: time,
95
+ });
96
+
97
+ export type SettledAnswer = z.infer<typeof SettledAnswer>;
98
+
99
+ /**
100
+ * Where a run slot stands: made and not yet ready, ready, taken by an item's pass, returned and waiting to be
101
+ * refreshed, kept because its branch holds a commit the remote lacks, or out of the pool.
102
+ */
103
+ export const SLOT_STATUSES = ["new", "free", "stale", "taken", "kept", "out"] as const;
104
+
105
+ /** A prewarmed worktree of the owner's checkout that background runs work in. */
106
+ export const Slot = z.strictObject({
107
+ name,
108
+ /** Which block of ports, among the slots, is this slot's. */
109
+ index: z.int().nonnegative(),
110
+ folder: name,
111
+ status: z.enum(SLOT_STATUSES),
112
+ /** The item whose pass holds the slot; set while it is taken or kept. */
113
+ item: name.optional(),
114
+ /** The hash of the lockfiles the slot's dependencies were last installed from. */
115
+ lockfiles: name.optional(),
116
+ since: time,
117
+ });
118
+
119
+ export type Slot = z.infer<typeof Slot>;
@@ -0,0 +1,49 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { atomicWrite, isMissing, orMissing } from "../state/fs.ts";
3
+ import { emptyStatus, Heartbeat, Status } from "./format.ts";
4
+
5
+ export type StatusRead =
6
+ | { readonly ok: true; readonly status: Status }
7
+ | { readonly ok: false; readonly reason: "missing" | "unreadable"; readonly message: string };
8
+
9
+ /** The engine's one write of the status file. Validates first, then writes atomically, so no reader sees a part. */
10
+ export const writeStatus = (path: string, status: Status): void => {
11
+ atomicWrite(path, `${JSON.stringify(Status.parse(status))}\n`);
12
+ };
13
+
14
+ export const readStatus = (path: string): StatusRead => {
15
+ try {
16
+ const parsed = Status.safeParse(JSON.parse(readFileSync(path, "utf8")));
17
+
18
+ return parsed.success
19
+ ? { ok: true, status: parsed.data }
20
+ : { ok: false, reason: "unreadable", message: `${path} does not hold a status file this engine reads: ${parsed.error.message}` };
21
+ } catch (error) {
22
+ if (error instanceof Error && isMissing(error)) return { ok: false, reason: "missing", message: `${path} does not exist` };
23
+
24
+ return { ok: false, reason: "unreadable", message: `${path} cannot be read: ${error instanceof Error ? error.message : "unknown error"}` };
25
+ }
26
+ };
27
+
28
+ /** The worker's one write of its heartbeat each tick. */
29
+ export const writeHeartbeat = (path: string, heartbeat: Heartbeat): void => {
30
+ atomicWrite(path, `${JSON.stringify(Heartbeat.parse(heartbeat))}\n`);
31
+ };
32
+
33
+ export const readHeartbeat = (path: string): Heartbeat | undefined => {
34
+ return orMissing(() => {
35
+ const parsed = Heartbeat.safeParse(JSON.parse(readFileSync(path, "utf8")));
36
+
37
+ return parsed.success ? parsed.data : undefined;
38
+ }, undefined);
39
+ };
40
+
41
+ /**
42
+ * The service unit's write of the fault cards while no worker writes them. The status file's other fields
43
+ * stay as they were, `writtenAt` included, so a dead worker still reads as stale.
44
+ */
45
+ export const writeCards = (path: string, cards: Status["cards"], engineVersion: string, now: number): void => {
46
+ const read = readStatus(path);
47
+
48
+ writeStatus(path, { ...(read.ok ? read.status : emptyStatus(engineVersion, now)), cards });
49
+ };
@@ -0,0 +1,132 @@
1
+ import { z } from "zod";
2
+ import { SCHEMA_VERSION } from "../config/schema.ts";
3
+ import { ADAPTER_API_VERSION } from "../adapter-api.ts";
4
+ import { STATUS_FORMAT } from "./version.ts";
5
+
6
+ export { STATUS_FORMAT };
7
+
8
+ const name = z.string().min(1);
9
+
10
+ const ACTION_LABEL_CELLS = 14;
11
+ const time = z.number().int().nonnegative();
12
+
13
+ /** A command the owner may run. A label is at most 14 cells, the width the view gives it. */
14
+ export const Action = z.strictObject({ label: name.max(ACTION_LABEL_CELLS), command: name });
15
+
16
+ /** A card's action: it fills the prompt with this answer to the card's item, and only the owner's Enter posts it. */
17
+ export const CardAction = z.strictObject({ label: name.max(ACTION_LABEL_CELLS), answer: name });
18
+
19
+ /** The most characters of a tool's own words a card quotes. */
20
+ export const CARD_EXCERPT = 200;
21
+
22
+ /** The cause, the fix in one sentence, then at most one action. */
23
+ export const Card = z.strictObject({
24
+ kind: z.enum(["waiting", "limited", "fault"]),
25
+ /** One card per key: a failure code plus the item it hit. */
26
+ key: name,
27
+ item: name.optional(),
28
+ code: name,
29
+ cause: name,
30
+ fix: name.refine((fix) => !fix.includes("\n"), "the fix is one sentence on one line"),
31
+ action: CardAction.optional(),
32
+ since: time,
33
+ }).refine(({ item, action }) => action === undefined || item !== undefined, "a card's action answers its item, so a card with an action names one");
34
+
35
+ export type Card = z.infer<typeof Card>;
36
+
37
+ const Row = z.strictObject({ item: name, title: name, level: name.optional(), state: name, since: time });
38
+
39
+ /** An unclear item carries the mark apart from its risk level. */
40
+ export const InFlight = Row.extend({ unclear: z.boolean() });
41
+
42
+ /** A question to the owner: its text and the option words an answer may pick, none for a free answer. */
43
+ export const Question = z.strictObject({ item: name, text: name, options: z.array(name), since: time });
44
+
45
+ export type Question = z.infer<typeof Question>;
46
+
47
+ export const Merged = z.strictObject({ item: name, title: name, level: name.optional(), mergedAt: time });
48
+
49
+ export const Choice = z.strictObject({ item: name, text: name, at: time });
50
+
51
+ /** A path rule the owner's answer added, with the command that takes it back. */
52
+ export type Choice = z.infer<typeof Choice>;
53
+
54
+ export const LearnedRule = z.strictObject({ glob: name, level: name, item: name, at: time, undo: Action });
55
+
56
+ const PerMerge = z.strictObject({
57
+ merges: z.int().nonnegative(),
58
+ /** Items that never merged in the window; their costs are in the numbers. */
59
+ abandoned: z.int().nonnegative(),
60
+ notes: z.number().nonnegative(),
61
+ questions: z.number().nonnegative(),
62
+ tokens: z.number().nonnegative(),
63
+ });
64
+
65
+ /** Per merged change over the last `window` merged changes, and over each path's own last `window`. */
66
+ export const Measure = PerMerge.extend({
67
+ window: z.int().positive(),
68
+ byPath: z.array(PerMerge.extend({ glob: name })),
69
+ }).strict();
70
+
71
+ export type Measure = z.infer<typeof Measure>;
72
+
73
+ /** One file per repo; the view shows the sections in this order. */
74
+ export const Status = z.strictObject({
75
+ format: z.literal(STATUS_FORMAT),
76
+ /** Freshness is a pure function of these timestamps and the clock. */
77
+ writtenAt: time,
78
+ /** When each runner's worker last wrote; absent when it never has. */
79
+ workers: z.strictObject({ mac: time.optional(), ci: time.optional() }),
80
+ engine: z.strictObject({
81
+ version: name,
82
+ adapterApi: z.int().nonnegative(),
83
+ configSchema: z.int().positive(),
84
+ /** The newest published version, when the worker could read it. */
85
+ latest: name.optional(),
86
+ }),
87
+ questions: z.array(Question),
88
+ cards: z.array(Card),
89
+ inFlight: z.array(InFlight),
90
+ merged: z.array(Merged),
91
+ choices: z.array(Choice),
92
+ rules: z.array(LearnedRule),
93
+ /** Pairs of review notes only a model found alike, waiting for its precision to reach the owner's bar. */
94
+ possibleRepeats: z.array(z.strictObject({ a: name, b: name })),
95
+ /** memory.md rules no run applied in the last runs; the owner decides whether to keep them. */
96
+ unusedMemory: z.array(z.string()),
97
+ measure: Measure.nullable(),
98
+ });
99
+
100
+ export type Status = z.infer<typeof Status>;
101
+
102
+ /** A status with nothing in it, stamped with the engine that wrote it. */
103
+ export const emptyStatus = (engineVersion: string, writtenAt: number): Status => ({
104
+ format: STATUS_FORMAT,
105
+ writtenAt,
106
+ workers: {},
107
+ engine: { version: engineVersion, adapterApi: ADAPTER_API_VERSION, configSchema: SCHEMA_VERSION },
108
+ questions: [],
109
+ cards: [],
110
+ inFlight: [],
111
+ merged: [],
112
+ choices: [],
113
+ rules: [],
114
+ possibleRepeats: [],
115
+ unusedMemory: [],
116
+ measure: null,
117
+ });
118
+
119
+ /** What the worker writes each tick. The service unit shows a card when it is three ticks old. */
120
+ export const Heartbeat = z.strictObject({
121
+ time,
122
+ engineVersion: name,
123
+ configHash: name,
124
+ /** Items with a run going. */
125
+ inFlight: z.array(name),
126
+ /** The time between ticks, so a reader can tell three ticks old from fresh. */
127
+ intervalMs: z.int().positive(),
128
+ /** Set once the worker has seen an update and will exit when its runs end. */
129
+ restarting: name.optional(),
130
+ });
131
+
132
+ export type Heartbeat = z.infer<typeof Heartbeat>;
@@ -0,0 +1,14 @@
1
+ import type { Choice, Question } from "./format.ts";
2
+ import type { QueuedQuestion, SettledAnswer } from "../state/saved.ts";
3
+
4
+ const answersAfter = (answers: readonly SettledAnswer[], item: string, asked: number): boolean =>
5
+ answers.some((answer) => answer.item === item && answer.disposition === "applied" && answer.at >= asked);
6
+
7
+ /** A question stays open from the moment it is asked until an answer to its item is applied. */
8
+ export const openQuestions = (queued: readonly QueuedQuestion[], answers: readonly SettledAnswer[]): Question[] =>
9
+ queued
10
+ .flatMap(({ item, text, options = [], askedAt }) => (askedAt !== undefined && !answersAfter(answers, item, askedAt) ? [{ item, text, options, since: askedAt }] : []))
11
+ .sort((a, b) => a.since - b.since);
12
+
13
+ /** The newest `shown` choices, newest first. */
14
+ export const newestChoices = (choices: readonly Choice[], shown: number): Choice[] => [...choices].sort((a, b) => b.at - a.at).slice(0, shown);
@@ -0,0 +1,2 @@
1
+ /** The status file's shape version. The view reads exactly this; a change here is public surface. */
2
+ export const STATUS_FORMAT = 2;
package/src/time.ts ADDED
@@ -0,0 +1,7 @@
1
+ export const SECOND_MS = 1000;
2
+
3
+ export const MINUTE_MS = 60 * SECOND_MS;
4
+
5
+ export const HOUR_MS = 60 * MINUTE_MS;
6
+
7
+ export const DAY_MS = 24 * 60 * MINUTE_MS;
@@ -0,0 +1,18 @@
1
+ import type { Pull, PullRequests } from "../adapters/pull-requests.ts";
2
+ import { alignmentComment, gatesAlignment } from "../decide/alignment.ts";
3
+ import type { LandContext } from "./land.ts";
4
+
5
+ /**
6
+ * Comments on the pull request what the alignment call made of the change, once per head, while the call's rate is
7
+ * below the bar. Above the bar the call raises levels and needs no report.
8
+ */
9
+ export const reportAlignment = async (ctx: LandContext, pulls: PullRequests, pull: Pull, head: string): Promise<void> => {
10
+ const alignment = ctx.state.landings.get(ctx.id)?.alignment;
11
+
12
+ if (!alignment || gatesAlignment(ctx.config.hum)) return;
13
+
14
+ await ctx.state.ops.once(
15
+ { itemId: ctx.id, run: "merge", attempt: 0, op: `alignment:${head}` },
16
+ { holds: async () => false, run: () => pulls.comment(pull, alignmentComment(alignment, ctx.config.hum)) },
17
+ );
18
+ };
@@ -0,0 +1,153 @@
1
+ import { ADAPTER_API_VERSION, type Item, type ThreadEntry, type WorkSource } from "../adapter-api.ts";
2
+ import type { ModelCall } from "../adapters/model-call.ts";
3
+ import { optionsIn } from "../adapters/marked.ts";
4
+ import { onceCalls } from "../adapters/once.ts";
5
+ import { dispose, type Disposition, matchOption, NONE_OF_THESE, replyQuestion, replyStem, replyText, type Resolution, type Stage } from "../decide/answer.ts";
6
+ import { visibleText } from "../adapters/marked.ts";
7
+ import type { State } from "../state/open.ts";
8
+ import type { SettledAnswer } from "../state/saved.ts";
9
+
10
+ export type AnswerContext = {
11
+ readonly state: State;
12
+ readonly workSource: WorkSource;
13
+ readonly judge: ModelCall;
14
+ readonly now: () => number;
15
+ };
16
+
17
+ /** What the reader knows about the item that the thread does not say. */
18
+ export type AnswerScope = {
19
+ readonly stage: Stage;
20
+ /** The options a card offers when no question does, such as the parked item's actions. */
21
+ readonly options?: readonly string[];
22
+ };
23
+
24
+ const isFromHum = (entry: ThreadEntry): boolean => entry.author !== "person";
25
+
26
+ const isQuestion = (entry: ThreadEntry): boolean => entry.kind === "question" && isFromHum(entry);
27
+
28
+ /** A marked answer, or a person's reply typed without a marker. */
29
+ const isReply = (entry: ThreadEntry): boolean => entry.kind === "answer" || (entry.kind === "comment" && !isFromHum(entry));
30
+
31
+ type Reply = { readonly entry: ThreadEntry; readonly ordinal: number; readonly index: number };
32
+
33
+ /** Every reply on the thread, numbered. Replies from people count only after a question; before one they are remarks. */
34
+ const repliesOn = (thread: readonly ThreadEntry[], afterQuestion: number): Reply[] => {
35
+ let ordinal = 0;
36
+
37
+ return thread.flatMap((entry, index) => {
38
+ if (!isReply(entry)) return [];
39
+
40
+ ordinal++;
41
+
42
+ return index > afterQuestion && (afterQuestion >= 0 || entry.kind === "answer") ? [{ entry, ordinal, index }] : [];
43
+ });
44
+ };
45
+
46
+ const resolveReply = async (ctx: AnswerContext, itemId: string, question: string, options: readonly string[], { entry }: Reply): Promise<Resolution> => {
47
+ const matched = matchOption(entry, options);
48
+
49
+ if (matched) return matched;
50
+
51
+ const judged = await ctx.judge({ ...replyQuestion(question, options, entry.text), item: itemId });
52
+
53
+ if (judged.kind === "abstained") return { source: "abstained", why: judged.why };
54
+
55
+ return judged.value.option === NONE_OF_THESE ? { source: "none-of-these" } : { source: "model", option: judged.value.option };
56
+ };
57
+
58
+ const keyOf = (item: string, ordinal: number): string => `${item}#${ordinal}`;
59
+
60
+ const optionOf = (resolution: Resolution): { option?: string } => ("option" in resolution && resolution.option !== undefined ? { option: resolution.option } : {});
61
+
62
+ const recordOf = (item: string, { entry, ordinal }: Reply, resolution: Resolution, outcome: Disposition, at: number): SettledAnswer => ({
63
+ item,
64
+ ordinal,
65
+ text: entry.text,
66
+ ...optionOf(resolution),
67
+ source: resolution.source,
68
+ disposition: outcome.disposition,
69
+ why: outcome.why,
70
+ at,
71
+ });
72
+
73
+ const resolutionOf = ({ source, option, why }: SettledAnswer): Resolution => {
74
+ if (source === "abstained") return { source, why };
75
+
76
+ if (source === "marker") return { source, option };
77
+
78
+ if (source === "free" || source === "none-of-these") return { source };
79
+
80
+ return { source, option: option ?? "" };
81
+ };
82
+
83
+ const isFinal = ({ disposition }: SettledAnswer): boolean => disposition !== "held";
84
+
85
+ const hasReplyOn = (thread: readonly ThreadEntry[], stem: string): boolean => thread.some((entry) => isFromHum(entry) && entry.kind === "comment" && entry.text.startsWith(stem));
86
+
87
+ /** The answer as the engine reads it from here on: the option it picked, or no longer an answer at all. */
88
+ const normalized = (entry: ThreadEntry, { disposition, option }: SettledAnswer): ThreadEntry =>
89
+ disposition === "applied" ? { ...entry, kind: "answer", option } : { ...entry, kind: "comment", option: undefined };
90
+
91
+ const SUPERSEDED: Disposition = { disposition: "dropped", why: "A newer question replaced the one this answered." };
92
+
93
+ type Settling = { readonly ctx: AnswerContext; readonly item: Item; readonly question: string; readonly options: readonly string[]; readonly stage: Stage };
94
+
95
+ /** One reply's record: kept once final, else decided again from where the item stands now. */
96
+ const settleOne = async ({ ctx, item, question, options, stage }: Settling, reply: Reply, answeredBefore: boolean): Promise<{ record: SettledAnswer; resolution: Resolution }> => {
97
+ const saved = ctx.state.answers.get(keyOf(item.id, reply.ordinal));
98
+ const resolution = saved ? resolutionOf(saved) : await resolveReply(ctx, item.id, question, options, reply);
99
+
100
+ if (saved && isFinal(saved)) return { record: saved, resolution };
101
+
102
+ const outcome = dispose({ resolution, answeredBefore, stage });
103
+ const record = saved?.disposition === outcome.disposition ? saved : recordOf(item.id, reply, resolution, outcome, ctx.now());
104
+
105
+ if (record !== saved) ctx.state.answers.put(keyOf(item.id, reply.ordinal), record);
106
+
107
+ return { record, resolution };
108
+ };
109
+
110
+ /** Answers held for a question that a newer one replaced can no longer take effect. */
111
+ const dropSuperseded = async ({ ctx, item }: Settling, current: ReadonlySet<number>): Promise<void> => {
112
+ for (const held of ctx.state.answers.list()) {
113
+ if (held.item !== item.id || held.disposition !== "held" || current.has(held.ordinal)) continue;
114
+
115
+ ctx.state.answers.put(keyOf(item.id, held.ordinal), { ...held, disposition: SUPERSEDED.disposition, why: SUPERSEDED.why });
116
+ await onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource: ctx.workSource }, ctx.state.ops, { run: "answer-reply", attempt: 0 }).workSource?.comment(item.id, replyText(held.ordinal, SUPERSEDED, resolutionOf(held), [], held.text));
117
+ }
118
+ };
119
+
120
+ /**
121
+ * D4: every answer on the item's thread is saved with what became of it, and gets one reply: applied, held, or
122
+ * dropped and why. An answer's option comes from its marker, else its first word, else the cheap model call.
123
+ * Returns the item with its thread as the engine reads it: an applied reply is an answer carrying its option, any
124
+ * other is a comment.
125
+ */
126
+ export const settleAnswers = async (ctx: AnswerContext, item: Item, { stage, options: cardOptions }: AnswerScope): Promise<Item> => {
127
+ const asked = item.thread.findLastIndex(isQuestion);
128
+ const questionText = asked < 0 ? "" : (item.thread[asked]?.text ?? "");
129
+ const settling: Settling = { ctx, item, question: visibleText(questionText), options: cardOptions ?? optionsIn(questionText), stage };
130
+ const calls = onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource: ctx.workSource }, ctx.state.ops, { run: "answer-reply", attempt: 0 });
131
+ const settled = new Map<number, SettledAnswer>();
132
+ const replies = repliesOn(item.thread, asked);
133
+
134
+ for (const reply of replies) {
135
+ const answeredBefore = [...settled.values()].some(({ disposition }) => disposition === "applied");
136
+ const { record, resolution } = await settleOne(settling, reply, answeredBefore);
137
+ const outcome = { disposition: record.disposition, why: record.why };
138
+
139
+ settled.set(reply.index, record);
140
+
141
+ if (!hasReplyOn(item.thread, replyStem(reply.ordinal, outcome))) await calls.workSource?.comment(item.id, replyText(reply.ordinal, outcome, resolution, settling.options, reply.entry.text));
142
+ }
143
+
144
+ await dropSuperseded(settling, new Set(replies.map(({ ordinal }) => ordinal)));
145
+
146
+ const asEngineReads = (entry: ThreadEntry, index: number): ThreadEntry => {
147
+ const record = settled.get(index);
148
+
149
+ return record ? normalized(entry, record) : entry;
150
+ };
151
+
152
+ return { ...item, thread: item.thread.map(asEngineReads) };
153
+ };
@@ -0,0 +1,46 @@
1
+ import type { WorkSource } from "../adapter-api.ts";
2
+ import { type Git } from "../adapters/git.ts";
3
+ import type { Config } from "../config/load.ts";
4
+ import { inWorktreeAt } from "../loop/proof.ts";
5
+ import type { State } from "../state/open.ts";
6
+ import { SECOND_MS } from "../time.ts";
7
+ import { runChecks } from "./checks.ts";
8
+ import { placementOf } from "./land.ts";
9
+
10
+ export type BaseCheckOptions = {
11
+ readonly state: State;
12
+ readonly config: Config;
13
+ readonly workSource: Pick<WorkSource, "fileFollowUp">;
14
+ /** The owner's checkout; the merged commit is fetched into it. */
15
+ readonly git: Git;
16
+ readonly remote: string;
17
+ readonly base: string;
18
+ readonly checks: readonly string[];
19
+ readonly now: () => number;
20
+ readonly item: string;
21
+ };
22
+
23
+ const FAILURE_EXCERPT = 1500;
24
+
25
+ /**
26
+ * After an item merged, the repo's checks run on the base at the merged commit. A failure there is a break: it is
27
+ * saved, a follow-up fix item is filed, and the owner's level for the change says whether its paths are blocked until
28
+ * that item merges. The fix limit counts the break beside the breaks git shows.
29
+ */
30
+ export const checkBaseAfterMerge = async ({ state, config, workSource, git, remote, base, checks, now, item }: BaseCheckOptions): Promise<void> => {
31
+ const merge = state.merges.get(item);
32
+
33
+ if (!config.hum.breakCheck || checks.length === 0 || !merge) return;
34
+
35
+ await git.raw(["fetch", "-q", remote, base]);
36
+
37
+ const failure = await inWorktreeAt(git, merge.sha, (folder) => runChecks(checks, folder, { timeoutMs: config.hum.proofTimeoutSeconds * SECOND_MS }));
38
+
39
+ if (failure === undefined) return;
40
+
41
+ const { placement } = await placementOf({ config, state, git, base, now }, { paths: merge.paths, size: 0, loosened: false, pinChanged: false });
42
+ const followUp = await workSource.fileFollowUp(item, { title: `Fix the checks that fail on ${base} after ${item} merged`, body: `Kind: fix\n\nThe repo's checks fail on ${base} at ${merge.sha}, the commit that merged ${item}.\n\n\`\`\`\n${failure.slice(0, FAILURE_EXCERPT)}\n\`\`\`` });
43
+
44
+ state.breaks.put(item, { item, sha: merge.sha, at: now(), paths: merge.paths, level: placement.level.name, failure: failure.slice(0, FAILURE_EXCERPT), onBreak: placement.level.onBreak, followUp: followUp.id });
45
+ };
46
+