@moo.md/hum 0.0.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 (110) hide show
  1. package/package.json +2 -2
  2. package/schema/hum.schema.json +2 -2
  3. package/scripts/eval.ts +88 -50
  4. package/src/adapter-api.ts +46 -14
  5. package/src/adapters/admit.ts +2 -2
  6. package/src/adapters/argument.ts +1 -1
  7. package/src/adapters/claim.ts +18 -15
  8. package/src/adapters/claude-bg.ts +72 -32
  9. package/src/adapters/claude-p.ts +26 -25
  10. package/src/adapters/contract.ts +22 -10
  11. package/src/adapters/each-call.ts +9 -0
  12. package/src/adapters/fake.ts +6 -6
  13. package/src/adapters/git.ts +12 -19
  14. package/src/adapters/github-client.ts +102 -0
  15. package/src/adapters/github.ts +50 -136
  16. package/src/adapters/guard.ts +20 -9
  17. package/src/adapters/history.ts +12 -15
  18. package/src/adapters/item-file.ts +1 -1
  19. package/src/adapters/markdown.ts +49 -42
  20. package/src/adapters/marked.ts +15 -13
  21. package/src/adapters/model-call.ts +4 -4
  22. package/src/adapters/once.ts +5 -5
  23. package/src/adapters/owner-commit.ts +13 -11
  24. package/src/adapters/pull-requests.ts +11 -13
  25. package/src/adapters/registry.ts +7 -7
  26. package/src/adapters/roundup.ts +31 -37
  27. package/src/adapters/serial.ts +4 -5
  28. package/src/adapters/transcript.ts +13 -8
  29. package/src/cli/main.ts +1 -0
  30. package/src/cli/ops.ts +32 -14
  31. package/src/cli/service.ts +14 -8
  32. package/src/cli/setup.ts +8 -3
  33. package/src/cli/shared-watch.ts +3 -3
  34. package/src/config/checks.ts +14 -18
  35. package/src/config/machine.ts +5 -7
  36. package/src/config/refusal.ts +7 -0
  37. package/src/config/schema.ts +9 -9
  38. package/src/config/settings.ts +17 -2
  39. package/src/config/state-map.ts +5 -3
  40. package/src/decide/alignment.ts +4 -4
  41. package/src/decide/answer.ts +24 -22
  42. package/src/decide/kind.ts +1 -6
  43. package/src/decide/labels.ts +9 -9
  44. package/src/decide/merge.ts +6 -7
  45. package/src/decide/prose.ts +4 -4
  46. package/src/decide/question.ts +23 -20
  47. package/src/decide/review.ts +4 -2
  48. package/src/decide/risk.ts +25 -19
  49. package/src/decide/taste.ts +3 -3
  50. package/src/exec.ts +10 -4
  51. package/src/index.ts +14 -13
  52. package/src/loop/check-item.ts +3 -3
  53. package/src/loop/ci.ts +1 -1
  54. package/src/loop/github.ts +2 -2
  55. package/src/loop/groups.ts +13 -6
  56. package/src/loop/memory.ts +40 -28
  57. package/src/loop/notes.ts +5 -5
  58. package/src/loop/pair.ts +1 -1
  59. package/src/loop/pass.ts +18 -12
  60. package/src/loop/proof.ts +9 -7
  61. package/src/loop/prove-item.ts +3 -3
  62. package/src/loop/records.ts +12 -13
  63. package/src/loop/signals.ts +6 -6
  64. package/src/measure/inputs.ts +1 -1
  65. package/src/measure/measure.ts +4 -4
  66. package/src/measure/rate.ts +2 -0
  67. package/src/service/ci-tick.ts +2 -2
  68. package/src/service/supervise.ts +3 -2
  69. package/src/service/token.ts +3 -3
  70. package/src/service/wake.ts +2 -2
  71. package/src/service/workflows.ts +2 -2
  72. package/src/setup/propose.ts +4 -4
  73. package/src/setup/prove.ts +20 -14
  74. package/src/setup/scan.ts +31 -24
  75. package/src/setup/shipped.ts +8 -2
  76. package/src/setup/tables.ts +4 -3
  77. package/src/setup/waits.ts +9 -11
  78. package/src/setup/write.ts +17 -10
  79. package/src/slots/pool.ts +32 -24
  80. package/src/state/events.ts +1 -1
  81. package/src/state/faults.ts +13 -5
  82. package/src/state/format.ts +2 -2
  83. package/src/state/items.ts +20 -15
  84. package/src/state/open.ts +2 -2
  85. package/src/state/ops.ts +16 -10
  86. package/src/state/records.ts +5 -5
  87. package/src/state/runs.ts +33 -26
  88. package/src/state/saved.ts +44 -32
  89. package/src/status/file.ts +20 -1
  90. package/src/status/format.ts +47 -57
  91. package/src/status/sections.ts +2 -2
  92. package/src/worker/alignment-report.ts +4 -5
  93. package/src/worker/answers.ts +26 -24
  94. package/src/worker/base-check.ts +4 -5
  95. package/src/worker/checks.ts +25 -11
  96. package/src/worker/kind.ts +23 -19
  97. package/src/worker/land.ts +115 -126
  98. package/src/worker/merged.ts +9 -7
  99. package/src/worker/open.ts +15 -13
  100. package/src/worker/prose-run.ts +3 -3
  101. package/src/worker/questions.ts +15 -12
  102. package/src/worker/scheduler.ts +4 -4
  103. package/src/worker/signature.ts +3 -3
  104. package/src/worker/tally.ts +0 -2
  105. package/src/worker/taste.ts +6 -15
  106. package/src/worker/thin-path.ts +150 -123
  107. package/src/worker/thread.ts +25 -0
  108. package/src/worker/worker.ts +125 -73
  109. package/surface.json +633 -2198
  110. package/src/slots/scan.ts +0 -26
@@ -1,44 +1,46 @@
1
1
  import { z } from "zod";
2
2
  import { AlignmentAnswer } from "../decide/alignment.ts";
3
+ import { DISPOSITIONS, RESOLUTION_SOURCES } from "../decide/answer.ts";
3
4
  import { Cite, PlanFile } from "../decide/prose.ts";
5
+ import { Change } from "../decide/risk.ts";
4
6
 
5
7
  const name = z.string().min(1);
6
8
  const time = z.int().nonnegative();
7
9
 
8
10
  /** 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 });
11
+ export const Parked = z.object({ item: name, why: z.enum(["stuck", "review"]), cause: name, since: time });
10
12
 
11
13
  export type Parked = z.infer<typeof Parked>;
12
14
 
13
15
  /** 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 });
16
+ export const Spent = z.object({ item: name, total: time, base: time });
15
17
 
16
18
  export type Spent = z.infer<typeof Spent>;
17
19
 
18
20
  /** Until when every run is held. Saved so a restart makes no call before it. */
19
- export const Limit = z.strictObject({ until: time });
21
+ export const Limit = z.object({ until: time });
20
22
 
21
23
  /** 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) });
24
+ export const ReadyList = z.object({ ids: z.array(name) });
23
25
 
24
26
  /** 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({
27
+ export const Landing = z.object({
26
28
  item: name,
27
29
  branch: name,
28
30
  since: time,
29
- change: z.strictObject({ paths: z.array(name), size: z.int().nonnegative(), loosened: z.boolean(), pinChanged: z.boolean() }),
31
+ change: Change,
30
32
  /** The commit the change ends at, before hum marks the item done: what a review reads. */
31
33
  head: name,
32
34
  /** The owner approved this change in its review state, before it was saved. */
33
35
  ownerApproved: z.boolean(),
34
36
  /** 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(),
37
+ alignment: z.union([z.object({ graded: AlignmentAnswer }), z.object({ abstained: name })]).optional(),
36
38
  });
37
39
 
38
40
  export type Landing = z.infer<typeof Landing>;
39
41
 
40
42
  /** 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 });
43
+ export const Learned = z.object({ glob: name, level: name, item: name, commit: name, pull: name.optional(), at: time });
42
44
 
43
45
  export type Learned = z.infer<typeof Learned>;
44
46
 
@@ -47,25 +49,25 @@ const models = z.array(name);
47
49
 
48
50
  /** An item's kind, decided once: named by its source, picked by the model call, or the fallback when the call abstained. */
49
51
  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 }),
52
+ z.object({ item: name, kind: name, from: z.literal("source") }),
53
+ z.object({ item: name, kind: name, from: z.literal("model") }),
54
+ z.object({ item: name, kind: name, from: z.literal("fallback"), why: name }),
53
55
  ]);
54
56
 
55
57
  export type ItemKind = z.infer<typeof ItemKind>;
56
58
 
57
59
  /** 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 });
60
+ export const SavedPlan = z.object({ item: name, plan: PlanFile, hash: name, models });
59
61
 
60
62
  export type SavedPlan = z.infer<typeof SavedPlan>;
61
63
 
62
64
  /** 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 });
65
+ export const Verdict = z.object({ item: name, head: name, event: name, reason: z.string(), cites: z.array(Cite), models });
64
66
 
65
67
  export type Verdict = z.infer<typeof Verdict>;
66
68
 
67
69
  /** 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({
70
+ export const QueuedQuestion = z.object({
69
71
  item: name,
70
72
  text: name,
71
73
  options: z.array(name).optional(),
@@ -80,40 +82,50 @@ export const QueuedQuestion = z.strictObject({
80
82
 
81
83
  export type QueuedQuestion = z.infer<typeof QueuedQuestion>;
82
84
 
83
- /** What became of one answer on an item's thread, saved before its reply is posted. */
84
- export const SettledAnswer = z.strictObject({
85
+ const settledFields = {
85
86
  item: name,
86
87
  /** The answer's number among the thread's answers and replies from people. */
87
88
  ordinal: z.int().positive(),
88
89
  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"]),
90
+ disposition: z.enum(DISPOSITIONS),
93
91
  why: name,
94
92
  at: time,
95
- });
93
+ };
94
+
95
+ /** What became of one answer on an item's thread, saved before its reply is posted: a marker may name an option, a first word or a model call always does, and the rest name none. */
96
+ export const SettledAnswer = z.discriminatedUnion("source", [
97
+ z.object({ ...settledFields, source: z.literal(RESOLUTION_SOURCES.marker), option: name.optional() }),
98
+ z.object({ ...settledFields, source: z.enum([RESOLUTION_SOURCES["first-word"], RESOLUTION_SOURCES.model]), option: name }),
99
+ z.object({ ...settledFields, source: z.enum([RESOLUTION_SOURCES.free, RESOLUTION_SOURCES["none-of-these"], RESOLUTION_SOURCES.abstained]) }),
100
+ ]);
96
101
 
97
102
  export type SettledAnswer = z.infer<typeof SettledAnswer>;
98
103
 
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
+ /** The option a settled answer picked, when its source names one. */
105
+ export const optionOf = (answer: SettledAnswer): string | undefined => ("option" in answer ? answer.option : undefined);
104
106
 
105
- /** A prewarmed worktree of the owner's checkout that background runs work in. */
106
- export const Slot = z.strictObject({
107
+ const slotFields = {
107
108
  name,
108
109
  /** Which block of ports, among the slots, is this slot's. */
109
110
  index: z.int().nonnegative(),
110
111
  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
112
  /** The hash of the lockfiles the slot's dependencies were last installed from. */
115
113
  lockfiles: name.optional(),
116
114
  since: time,
117
- });
115
+ };
116
+
117
+ /**
118
+ * A prewarmed worktree of the owner's checkout that background runs work in. A free slot is made and not yet ready,
119
+ * ready, returned and waiting to be refreshed, or out of the pool. A held slot is taken by an item's pass, or kept
120
+ * because its branch holds a commit the remote lacks; it names the item.
121
+ */
122
+ export const Slot = z.discriminatedUnion("status", [
123
+ z.object({ ...slotFields, status: z.enum(["new", "free", "stale", "out"]) }),
124
+ z.object({ ...slotFields, status: z.enum(["taken", "kept"]), item: name }),
125
+ ]);
118
126
 
119
127
  export type Slot = z.infer<typeof Slot>;
128
+
129
+ export type HeldSlot = Extract<Slot, { readonly item: string }>;
130
+
131
+ export type FreeSlot = Exclude<Slot, HeldSlot>;
@@ -1,6 +1,25 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { ADAPTER_API_VERSION } from "../adapter-api.ts";
3
+ import { SCHEMA_VERSION } from "../config/schema.ts";
2
4
  import { atomicWrite, isMissing, orMissing } from "../state/fs.ts";
3
- import { emptyStatus, Heartbeat, Status } from "./format.ts";
5
+ import { Heartbeat, Status, STATUS_FORMAT } from "./format.ts";
6
+
7
+ /** A status with nothing in it, stamped with the engine that wrote it. */
8
+ export const emptyStatus = (engineVersion: string, writtenAt: number): Status => ({
9
+ format: STATUS_FORMAT,
10
+ writtenAt,
11
+ workers: {},
12
+ engine: { version: engineVersion, adapterApi: ADAPTER_API_VERSION, configSchema: SCHEMA_VERSION },
13
+ questions: [],
14
+ cards: [],
15
+ inFlight: [],
16
+ merged: [],
17
+ choices: [],
18
+ rules: [],
19
+ possibleRepeats: [],
20
+ unusedMemory: [],
21
+ measure: null,
22
+ });
4
23
 
5
24
  export type StatusRead =
6
25
  | { readonly ok: true; readonly status: Status }
@@ -1,88 +1,95 @@
1
- import { z } from "zod";
2
- import { SCHEMA_VERSION } from "../config/schema.ts";
3
- import { ADAPTER_API_VERSION } from "../adapter-api.ts";
1
+ /*
2
+ * The mod bundles this file for its reader: zod's mini build keeps that bundle small, where the full one brings
3
+ * every locale. Mini loads none, so the English messages are loaded here, for a reader that loads nothing else.
4
+ */
5
+ import * as z from "zod/mini";
6
+ import en from "zod/v4/locales/en.js";
4
7
  import { STATUS_FORMAT } from "./version.ts";
5
8
 
9
+ z.config(en());
10
+
6
11
  export { STATUS_FORMAT };
7
12
 
8
- const name = z.string().min(1);
13
+ const name = z.string().check(z.minLength(1));
9
14
 
10
15
  const ACTION_LABEL_CELLS = 14;
11
- const time = z.number().int().nonnegative();
16
+
17
+ const label = z.string().check(z.minLength(1), z.maxLength(ACTION_LABEL_CELLS));
18
+ const time = z.int().check(z.nonnegative());
12
19
 
13
20
  /** 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 });
21
+ export const Action = z.object({ label, command: name });
15
22
 
16
23
  /** 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 });
24
+ export const CardAction = z.object({ label, answer: name });
18
25
 
19
26
  /** The most characters of a tool's own words a card quotes. */
20
27
  export const CARD_EXCERPT = 200;
21
28
 
22
29
  /** The cause, the fix in one sentence, then at most one action. */
23
- export const Card = z.strictObject({
30
+ export const Card = z.object({
24
31
  kind: z.enum(["waiting", "limited", "fault"]),
25
32
  /** One card per key: a failure code plus the item it hit. */
26
33
  key: name,
27
- item: name.optional(),
34
+ item: z.optional(name),
28
35
  code: name,
29
36
  cause: name,
30
- fix: name.refine((fix) => !fix.includes("\n"), "the fix is one sentence on one line"),
31
- action: CardAction.optional(),
37
+ fix: name.check(z.refine((fix) => !fix.includes("\n"), "the fix is one sentence on one line")),
38
+ action: z.optional(CardAction),
32
39
  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");
40
+ }).check(z.refine(({ item, action }) => action === undefined || item !== undefined, "a card's action answers its item, so a card with an action names one"));
34
41
 
35
42
  export type Card = z.infer<typeof Card>;
36
43
 
37
- const Row = z.strictObject({ item: name, title: name, level: name.optional(), state: name, since: time });
44
+ const Row = z.object({ item: name, title: name, level: z.optional(name), state: name, since: time });
38
45
 
39
46
  /** An unclear item carries the mark apart from its risk level. */
40
- export const InFlight = Row.extend({ unclear: z.boolean() });
47
+ export const InFlight = z.extend(Row, { unclear: z.boolean() });
41
48
 
42
49
  /** 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 });
50
+ export const Question = z.object({ item: name, text: name, options: z.array(name), since: time });
44
51
 
45
52
  export type Question = z.infer<typeof Question>;
46
53
 
47
- export const Merged = z.strictObject({ item: name, title: name, level: name.optional(), mergedAt: time });
54
+ export const Merged = z.object({ item: name, title: name, level: z.optional(name), mergedAt: time });
48
55
 
49
- export const Choice = z.strictObject({ item: name, text: name, at: time });
56
+ export const Choice = z.object({ item: name, text: name, at: time });
50
57
 
51
- /** A path rule the owner's answer added, with the command that takes it back. */
52
58
  export type Choice = z.infer<typeof Choice>;
53
59
 
54
- export const LearnedRule = z.strictObject({ glob: name, level: name, item: name, at: time, undo: Action });
60
+ /** A path rule the owner's answer added, with the command that takes it back. */
61
+ const LearnedRule = z.object({ glob: name, level: name, item: name, at: time, undo: Action });
55
62
 
56
- const PerMerge = z.strictObject({
57
- merges: z.int().nonnegative(),
63
+ const PerMerge = z.object({
64
+ merges: z.int().check(z.nonnegative()),
58
65
  /** 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(),
66
+ abandoned: z.int().check(z.nonnegative()),
67
+ notes: z.number().check(z.nonnegative()),
68
+ questions: z.number().check(z.nonnegative()),
69
+ tokens: z.number().check(z.nonnegative()),
63
70
  });
64
71
 
65
72
  /** 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();
73
+ export const Measure = z.extend(PerMerge, {
74
+ window: z.int().check(z.positive()),
75
+ byPath: z.array(z.extend(PerMerge, { glob: name })),
76
+ });
70
77
 
71
78
  export type Measure = z.infer<typeof Measure>;
72
79
 
73
80
  /** One file per repo; the view shows the sections in this order. */
74
- export const Status = z.strictObject({
81
+ export const Status = z.object({
75
82
  format: z.literal(STATUS_FORMAT),
76
83
  /** Freshness is a pure function of these timestamps and the clock. */
77
84
  writtenAt: time,
78
85
  /** 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({
86
+ workers: z.object({ mac: z.optional(time), ci: z.optional(time) }),
87
+ engine: z.object({
81
88
  version: name,
82
- adapterApi: z.int().nonnegative(),
83
- configSchema: z.int().positive(),
89
+ adapterApi: z.int().check(z.nonnegative()),
90
+ configSchema: z.int().check(z.positive()),
84
91
  /** The newest published version, when the worker could read it. */
85
- latest: name.optional(),
92
+ latest: z.optional(name),
86
93
  }),
87
94
  questions: z.array(Question),
88
95
  cards: z.array(Card),
@@ -91,42 +98,25 @@ export const Status = z.strictObject({
91
98
  choices: z.array(Choice),
92
99
  rules: z.array(LearnedRule),
93
100
  /** 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 })),
101
+ possibleRepeats: z.array(z.object({ a: name, b: name })),
95
102
  /** memory.md rules no run applied in the last runs; the owner decides whether to keep them. */
96
103
  unusedMemory: z.array(z.string()),
97
- measure: Measure.nullable(),
104
+ measure: z.nullable(Measure),
98
105
  });
99
106
 
100
107
  export type Status = z.infer<typeof Status>;
101
108
 
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
109
  /** What the worker writes each tick. The service unit shows a card when it is three ticks old. */
120
- export const Heartbeat = z.strictObject({
110
+ export const Heartbeat = z.object({
121
111
  time,
122
112
  engineVersion: name,
123
113
  configHash: name,
124
114
  /** Items with a run going. */
125
115
  inFlight: z.array(name),
126
116
  /** The time between ticks, so a reader can tell three ticks old from fresh. */
127
- intervalMs: z.int().positive(),
117
+ intervalMs: z.int().check(z.positive()),
128
118
  /** Set once the worker has seen an update and will exit when its runs end. */
129
- restarting: name.optional(),
119
+ restarting: z.optional(name),
130
120
  });
131
121
 
132
122
  export type Heartbeat = z.infer<typeof Heartbeat>;
@@ -1,13 +1,13 @@
1
1
  import type { Choice, Question } from "./format.ts";
2
2
  import type { QueuedQuestion, SettledAnswer } from "../state/saved.ts";
3
3
 
4
- const answersAfter = (answers: readonly SettledAnswer[], item: string, asked: number): boolean =>
4
+ const hasAnswerAfter = (answers: readonly SettledAnswer[], item: string, asked: number): boolean =>
5
5
  answers.some((answer) => answer.item === item && answer.disposition === "applied" && answer.at >= asked);
6
6
 
7
7
  /** A question stays open from the moment it is asked until an answer to its item is applied. */
8
8
  export const openQuestions = (queued: readonly QueuedQuestion[], answers: readonly SettledAnswer[]): Question[] =>
9
9
  queued
10
- .flatMap(({ item, text, options = [], askedAt }) => (askedAt !== undefined && !answersAfter(answers, item, askedAt) ? [{ item, text, options, since: askedAt }] : []))
10
+ .flatMap(({ item, text, options = [], askedAt }) => (askedAt !== undefined && !hasAnswerAfter(answers, item, askedAt) ? [{ item, text, options, since: askedAt }] : []))
11
11
  .sort((a, b) => a.since - b.since);
12
12
 
13
13
  /** The newest `shown` choices, newest first. */
@@ -1,15 +1,14 @@
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";
1
+ import { alignmentComment, doesGateAlignment } from "../decide/alignment.ts";
2
+ import type { LandContext, PullAtHead } from "./land.ts";
4
3
 
5
4
  /**
6
5
  * Comments on the pull request what the alignment call made of the change, once per head, while the call's rate is
7
6
  * below the bar. Above the bar the call raises levels and needs no report.
8
7
  */
9
- export const reportAlignment = async (ctx: LandContext, pulls: PullRequests, pull: Pull, head: string): Promise<void> => {
8
+ export const reportAlignment = async (ctx: LandContext, { pulls, pull, head }: PullAtHead): Promise<void> => {
10
9
  const alignment = ctx.state.landings.get(ctx.id)?.alignment;
11
10
 
12
- if (!alignment || gatesAlignment(ctx.config.hum)) return;
11
+ if (!alignment || doesGateAlignment(ctx.config.hum)) return;
13
12
 
14
13
  await ctx.state.ops.once(
15
14
  { itemId: ctx.id, run: "merge", attempt: 0, op: `alignment:${head}` },
@@ -5,7 +5,8 @@ import { onceCalls } from "../adapters/once.ts";
5
5
  import { dispose, type Disposition, matchOption, NONE_OF_THESE, replyQuestion, replyStem, replyText, type Resolution, type Stage } from "../decide/answer.ts";
6
6
  import { visibleText } from "../adapters/marked.ts";
7
7
  import type { State } from "../state/open.ts";
8
- import type { SettledAnswer } from "../state/saved.ts";
8
+ import { optionOf, type SettledAnswer } from "../state/saved.ts";
9
+ import { isFromHum, latestQuestionAt } from "./thread.ts";
9
10
 
10
11
  export type AnswerContext = {
11
12
  readonly state: State;
@@ -21,10 +22,6 @@ export type AnswerScope = {
21
22
  readonly options?: readonly string[];
22
23
  };
23
24
 
24
- const isFromHum = (entry: ThreadEntry): boolean => entry.author !== "person";
25
-
26
- const isQuestion = (entry: ThreadEntry): boolean => entry.kind === "question" && isFromHum(entry);
27
-
28
25
  /** A marked answer, or a person's reply typed without a marker. */
29
26
  const isReply = (entry: ThreadEntry): boolean => entry.kind === "answer" || (entry.kind === "comment" && !isFromHum(entry));
30
27
 
@@ -43,12 +40,12 @@ const repliesOn = (thread: readonly ThreadEntry[], afterQuestion: number): Reply
43
40
  });
44
41
  };
45
42
 
46
- const resolveReply = async (ctx: AnswerContext, itemId: string, question: string, options: readonly string[], { entry }: Reply): Promise<Resolution> => {
43
+ const resolveReply = async (ctx: AnswerContext, { itemId, question, options, reply: { entry } }: { readonly itemId: string; readonly question: string; readonly options: readonly string[]; readonly reply: Reply }): Promise<Resolution> => {
47
44
  const matched = matchOption(entry, options);
48
45
 
49
46
  if (matched) return matched;
50
47
 
51
- const judged = await ctx.judge({ ...replyQuestion(question, options, entry.text), item: itemId });
48
+ const judged = await ctx.judge({ ...replyQuestion({ question, options, reply: entry.text }), item: itemId });
52
49
 
53
50
  if (judged.kind === "abstained") return { source: "abstained", why: judged.why };
54
51
 
@@ -57,27 +54,32 @@ const resolveReply = async (ctx: AnswerContext, itemId: string, question: string
57
54
 
58
55
  const keyOf = (item: string, ordinal: number): string => `${item}#${ordinal}`;
59
56
 
60
- const optionOf = (resolution: Resolution): { option?: string } => ("option" in resolution && resolution.option !== undefined ? { option: resolution.option } : {});
57
+ /** A resolution as its settled answer saves it; an abstention's own why gives way to the disposition's. */
58
+ const savedResolution = (resolution: Resolution) => (resolution.source === "abstained" ? { source: resolution.source } : resolution);
61
59
 
62
60
  const recordOf = (item: string, { entry, ordinal }: Reply, resolution: Resolution, outcome: Disposition, at: number): SettledAnswer => ({
63
61
  item,
64
62
  ordinal,
65
63
  text: entry.text,
66
- ...optionOf(resolution),
67
- source: resolution.source,
68
64
  disposition: outcome.disposition,
69
65
  why: outcome.why,
70
66
  at,
67
+ ...savedResolution(resolution),
71
68
  });
72
69
 
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 ?? "" };
70
+ const resolutionOf = (record: SettledAnswer): Resolution => {
71
+ switch (record.source) {
72
+ case "abstained":
73
+ return { source: record.source, why: record.why };
74
+ case "marker":
75
+ return { source: record.source, option: record.option };
76
+ case "first-word":
77
+ case "model":
78
+ return { source: record.source, option: record.option };
79
+ case "free":
80
+ case "none-of-these":
81
+ return { source: record.source };
82
+ }
81
83
  };
82
84
 
83
85
  const isFinal = ({ disposition }: SettledAnswer): boolean => disposition !== "held";
@@ -85,17 +87,17 @@ const isFinal = ({ disposition }: SettledAnswer): boolean => disposition !== "he
85
87
  const hasReplyOn = (thread: readonly ThreadEntry[], stem: string): boolean => thread.some((entry) => isFromHum(entry) && entry.kind === "comment" && entry.text.startsWith(stem));
86
88
 
87
89
  /** 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
+ const normalized = (entry: ThreadEntry, record: SettledAnswer): ThreadEntry =>
91
+ record.disposition === "applied" ? { ...entry, kind: "answer", option: optionOf(record) } : { ...entry, kind: "comment", option: undefined };
90
92
 
91
93
  const SUPERSEDED: Disposition = { disposition: "dropped", why: "A newer question replaced the one this answered." };
92
94
 
93
95
  type Settling = { readonly ctx: AnswerContext; readonly item: Item; readonly question: string; readonly options: readonly string[]; readonly stage: Stage };
94
96
 
95
97
  /** 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 }> => {
98
+ const settleOne = async ({ ctx, item, question, options, stage }: Settling, { reply, answeredBefore }: { readonly reply: Reply; readonly answeredBefore: boolean }): Promise<{ record: SettledAnswer; resolution: Resolution }> => {
97
99
  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);
100
+ const resolution = saved ? resolutionOf(saved) : await resolveReply(ctx, { itemId: item.id, question, options, reply });
99
101
 
100
102
  if (saved && isFinal(saved)) return { record: saved, resolution };
101
103
 
@@ -124,7 +126,7 @@ const dropSuperseded = async ({ ctx, item }: Settling, current: ReadonlySet<numb
124
126
  * other is a comment.
125
127
  */
126
128
  export const settleAnswers = async (ctx: AnswerContext, item: Item, { stage, options: cardOptions }: AnswerScope): Promise<Item> => {
127
- const asked = item.thread.findLastIndex(isQuestion);
129
+ const asked = latestQuestionAt(item.thread);
128
130
  const questionText = asked < 0 ? "" : (item.thread[asked]?.text ?? "");
129
131
  const settling: Settling = { ctx, item, question: visibleText(questionText), options: cardOptions ?? optionsIn(questionText), stage };
130
132
  const calls = onceCalls({ apiVersion: ADAPTER_API_VERSION, workSource: ctx.workSource }, ctx.state.ops, { run: "answer-reply", attempt: 0 });
@@ -133,7 +135,7 @@ export const settleAnswers = async (ctx: AnswerContext, item: Item, { stage, opt
133
135
 
134
136
  for (const reply of replies) {
135
137
  const answeredBefore = [...settled.values()].some(({ disposition }) => disposition === "applied");
136
- const { record, resolution } = await settleOne(settling, reply, answeredBefore);
138
+ const { record, resolution } = await settleOne(settling, { reply, answeredBefore });
137
139
  const outcome = { disposition: record.disposition, why: record.why };
138
140
 
139
141
  settled.set(reply.index, record);
@@ -1,10 +1,9 @@
1
- import type { WorkSource } from "../adapter-api.ts";
1
+ import { ItemId, type WorkSource } from "../adapter-api.ts";
2
2
  import { type Git } from "../adapters/git.ts";
3
3
  import type { Config } from "../config/load.ts";
4
4
  import { inWorktreeAt } from "../loop/proof.ts";
5
5
  import type { State } from "../state/open.ts";
6
- import { SECOND_MS } from "../time.ts";
7
- import { runChecks } from "./checks.ts";
6
+ import { checksTimeoutMs, runChecks } from "./checks.ts";
8
7
  import { placementOf } from "./land.ts";
9
8
 
10
9
  export type BaseCheckOptions = {
@@ -34,12 +33,12 @@ export const checkBaseAfterMerge = async ({ state, config, workSource, git, remo
34
33
 
35
34
  await git.raw(["fetch", "-q", remote, base]);
36
35
 
37
- const failure = await inWorktreeAt(git, merge.sha, (folder) => runChecks(checks, folder, { timeoutMs: config.hum.proofTimeoutSeconds * SECOND_MS }));
36
+ const failure = await inWorktreeAt(git, merge.sha, (folder) => runChecks(checks, folder, { timeoutMs: checksTimeoutMs(config.hum) }));
38
37
 
39
38
  if (failure === undefined) return;
40
39
 
41
40
  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\`\`\`` });
41
+ const followUp = await workSource.fileFollowUp(ItemId.parse(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
42
 
44
43
  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
44
  };
@@ -1,25 +1,39 @@
1
- import { x } from "tinyexec";
1
+ import type { HumConfig } from "../config/schema.ts";
2
+ import { CommandTimedOut, exec } from "../exec.ts";
3
+ import { SECOND_MS } from "../time.ts";
2
4
 
3
5
  export type ShellOptions = {
4
6
  /** Added to the worker's own environment. */
5
7
  readonly env?: Readonly<Record<string, string>>;
6
- /** A command still running after this many ms is killed and counts as failed. */
7
- readonly timeoutMs?: number;
8
+ /** A command still running after this many ms is stopped, with every process it started, and counts as failed. */
9
+ readonly timeoutMs: number;
8
10
  };
9
11
 
10
- /** A check runs with no stdin and the worker's own PATH, as in the owner's shell; the clone's `node_modules/.bin` is not added. */
11
- const shellOut = async (command: string, cwd: string, { env, timeoutMs }: ShellOptions): Promise<{ code: number | undefined; output: string }> => {
12
- const { exitCode, stdout, stderr } = await x("sh", ["-c", command], { nodePath: false, timeout: timeoutMs, nodeOptions: { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] } });
12
+ /**
13
+ * One check's failure as its command, exit code and output, or as the limit it ran past; undefined when it passes.
14
+ * It runs with no stdin and the worker's own PATH, as in the owner's shell; the clone's `node_modules/.bin` is not added.
15
+ */
16
+ const failureOf = async (command: string, cwd: string, { env, timeoutMs }: ShellOptions): Promise<string | undefined> => {
17
+ try {
18
+ const { exitCode, stdout, stderr } = await exec("sh", ["-c", command], { nodePath: false, timeoutMs, nodeOptions: { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"] } });
13
19
 
14
- return { code: exitCode, output: `${stdout}${stderr}` };
20
+ return exitCode === 0 ? undefined : `${command} exited ${exitCode}:\n${stdout}${stderr}`;
21
+ } catch (error) {
22
+ if (error instanceof CommandTimedOut) return error.message;
23
+
24
+ throw error;
25
+ }
15
26
  };
16
27
 
17
- /** The first failing check as its command, exit code and output; undefined when all pass. */
18
- export const runChecks = async (commands: readonly string[], cwd: string, options: ShellOptions = {}): Promise<string | undefined> => {
28
+ /** How long the repo's checks may run: the owner's `proofTimeoutSeconds` in milliseconds. */
29
+ export const checksTimeoutMs = ({ proofTimeoutSeconds }: Pick<HumConfig, "proofTimeoutSeconds">): number => proofTimeoutSeconds * SECOND_MS;
30
+
31
+ /** The first failing check; undefined when all pass. */
32
+ export const runChecks = async (commands: readonly string[], cwd: string, options: ShellOptions): Promise<string | undefined> => {
19
33
  for (const command of commands) {
20
- const ran = await shellOut(command, cwd, options);
34
+ const failure = await failureOf(command, cwd, options);
21
35
 
22
- if (ran.code !== 0) return `${command} exited ${ran.code}:\n${ran.output}`;
36
+ if (failure !== undefined) return failure;
23
37
  }
24
38
 
25
39
  return undefined;