@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,145 @@
1
+ import { createActor, createAsyncLogic, setup, toPromise } from "xstate";
2
+ import { z } from "zod";
3
+ import { ENGINE_VERSION } from "../state/format.ts";
4
+ import type { State } from "../state/open.ts";
5
+ import { readHeartbeat, writeCards } from "../status/file.ts";
6
+ import { MINUTE_MS, SECOND_MS } from "../time.ts";
7
+ import { CARD_CODES, CARD_KINDS } from "./cards.ts";
8
+
9
+ /** The exit code of a worker that stopped because an update arrived. `EX_TEMPFAIL`: the supervisor starts it again without counting a crash. */
10
+ export const EXIT_UPDATED = 75;
11
+
12
+ /** A worker process, or a stand-in for one. */
13
+ export type Child = { readonly exited: Promise<number>; readonly kill: () => void };
14
+
15
+ export type Supervision = {
16
+ readonly state: Pick<State, "faults" | "heartbeatPath" | "statusPath">;
17
+ readonly spawn: () => Child;
18
+ readonly now: () => number;
19
+ /** The time between heartbeat looks, and the worker's tick interval until it writes a heartbeat. */
20
+ readonly intervalMs: number;
21
+ readonly workerDownTicks: number;
22
+ readonly maxCrashes: number;
23
+ readonly crashWindowMs: number;
24
+ /** The pause before the first restart, doubled for each crash still inside the window, up to `maxBackoffMs`. */
25
+ readonly backoffMs: number;
26
+ readonly maxBackoffMs: number;
27
+ readonly stop: AbortSignal;
28
+ };
29
+
30
+ export type Ended = "stopped" | "gave-up";
31
+
32
+ const Context = z.object({
33
+ crashes: z.array(z.number()),
34
+ /** The last time anything showed the worker alive, or the start. A restart does not move it, so a worker that exits at start still goes stale. */
35
+ quietSince: z.number(),
36
+ });
37
+
38
+ type Context = z.infer<typeof Context>;
39
+
40
+ type Card = ReturnType<(typeof CARD_KINDS)["workerSilent"]> | undefined;
41
+
42
+ /** Shows `card` as the only worker-down card, or none; the status file is written here because no worker is there to write it. */
43
+ const showWorkerDown = ({ faults, statusPath }: Supervision["state"], card: Card, now: number): void => {
44
+ faults.clear(CARD_CODES.workerDown);
45
+
46
+ if (card) faults.raise(card);
47
+
48
+ writeCards(statusPath, faults.list(), ENGINE_VERSION, now);
49
+ };
50
+
51
+ const isUpdateExit = (exitCode: number): boolean => exitCode === EXIT_UPDATED;
52
+
53
+ const crashesInWindow = (crashes: readonly number[], at: number, windowMs: number): number[] => [...crashes.filter((crashed) => at - crashed < windowMs), at];
54
+
55
+ type Silence = { readonly quietSince: number; readonly silentMs: number; readonly isSilent: boolean };
56
+
57
+ /** How long nothing has shown the worker alive, and whether that is `ticks` of the worker's own tick interval. */
58
+ const silenceOf = (quietSince: number, beat: { readonly time: number; readonly intervalMs: number } | undefined, now: number, o: Pick<Supervision, "intervalMs" | "workerDownTicks">): Silence => {
59
+ const lastSeen = Math.max(quietSince, beat?.time ?? 0);
60
+ const silentMs = now - lastSeen;
61
+
62
+ return { quietSince: lastSeen, silentMs, isSilent: silentMs >= o.workerDownTicks * (beat?.intervalMs ?? o.intervalMs) };
63
+ };
64
+
65
+ const backoffFor = (crashes: number, { backoffMs, maxBackoffMs }: Pick<Supervision, "backoffMs" | "maxBackoffMs">): number => Math.min(backoffMs * 2 ** (crashes - 1), maxBackoffMs);
66
+
67
+ /**
68
+ * The start script as a machine. It runs the worker and starts it again when it exits, looks at the heartbeat once
69
+ * a tick, and stops restarting after too many crashes in the window. Giving up ends it as `gave-up`, so the
70
+ * unit's exit code is 0 and the unit does not start the script again.
71
+ */
72
+ const supervisorMachine = (o: Supervision, current: { child?: Child }) => {
73
+ const supervisor = setup({
74
+ schemas: { context: Context, events: { stop: z.object({}) } },
75
+ delays: { tick: o.intervalMs, backoff: ({ context }) => backoffFor(context.crashes.length, o) },
76
+ actors: {
77
+ worker: createAsyncLogic({ run: () => (current.child = o.spawn()).exited }),
78
+ exit: createAsyncLogic({ run: () => current.child?.exited ?? Promise.resolve(0) }),
79
+ },
80
+ });
81
+
82
+ const hasReachedLimit = (crashes: readonly number[]): boolean => crashes.length >= o.maxCrashes;
83
+
84
+ const looking = {
85
+ after: {
86
+ tick: ({ context }: { context: Context }, enq: (effect: () => void) => void) => {
87
+ const now = o.now();
88
+ const { quietSince, silentMs, isSilent } = silenceOf(context.quietSince, readHeartbeat(o.state.heartbeatPath), now, o);
89
+ const isShown = o.state.faults.list().some((card) => card.key === CARD_CODES.workerDown);
90
+ const mustChangeCard = isSilent !== isShown;
91
+
92
+ if (mustChangeCard) enq(() => showWorkerDown(o.state, isSilent ? CARD_KINDS.workerSilent({ seconds: Math.round(silentMs / SECOND_MS), ticks: o.workerDownTicks }) : undefined, now));
93
+
94
+ return { target: "looking", reenter: true, context: { ...context, quietSince } };
95
+ },
96
+ },
97
+ };
98
+
99
+ return supervisor.createMachine({
100
+ id: "supervisor",
101
+ context: { crashes: [], quietSince: o.now() },
102
+ initial: "running",
103
+ on: { stop: { target: "#supervisor.stopping" } },
104
+ states: {
105
+ running: {
106
+ initial: "looking",
107
+ invoke: {
108
+ src: "worker",
109
+ onDone: ({ context, event }, enq) => {
110
+ const exitCode = event.output;
111
+
112
+ if (isUpdateExit(exitCode)) return { target: "running", reenter: true };
113
+
114
+ const now = o.now();
115
+ const crashes = crashesInWindow(context.crashes, now, o.crashWindowMs);
116
+
117
+ if (!hasReachedLimit(crashes)) return { target: "backingOff", context: { ...context, crashes } };
118
+
119
+ enq(() => showWorkerDown(o.state, CARD_KINDS.workerGaveUp({ crashes: crashes.length, windowMinutes: Math.round(o.crashWindowMs / MINUTE_MS), exitCode }), now));
120
+
121
+ return { target: "gaveUp", context: { ...context, crashes } };
122
+ },
123
+ },
124
+ states: { looking },
125
+ },
126
+ backingOff: { initial: "looking", after: { backoff: { target: "running" } }, states: { looking } },
127
+ stopping: { entry: (_, enq) => void enq(() => current.child?.kill()), invoke: { src: "exit", onDone: { target: "stopped" } }, on: { stop: undefined } },
128
+ gaveUp: { type: "final", output: "gave-up" as const },
129
+ stopped: { type: "final", output: "stopped" as const },
130
+ },
131
+ });
132
+ };
133
+
134
+ /** Runs the start script until `stop` or the crash limit. */
135
+ export const supervise = (o: Supervision): Promise<Ended> => {
136
+ const actor = createActor(supervisorMachine(o, {})).start();
137
+ const halt = () => actor.send({ type: "stop" });
138
+
139
+ showWorkerDown(o.state, undefined, o.now());
140
+
141
+ if (o.stop.aborted) halt();
142
+ else o.stop.addEventListener("abort", halt, { once: true });
143
+
144
+ return toPromise(actor).finally(() => o.stop.removeEventListener("abort", halt));
145
+ };
@@ -0,0 +1,44 @@
1
+ import type { UnitBuilder } from "./unit.ts";
2
+
3
+ type Sections = Readonly<Record<string, Readonly<Record<string, string>>>>;
4
+
5
+ /** systemd reads `%` as the start of a specifier. */
6
+ const literalPercent = (text: string): string => text.replace(/%/g, "%%");
7
+
8
+ /** A word in a systemd line: quoted, with `%` and `$` doubled so no specifier or variable expands. */
9
+ const word = (text: string): string => `"${literalPercent(text).replace(/[\\"]/g, "\\$&").replace(/\$/g, "$$$$")}"`;
10
+
11
+ const assertOneLine = (values: readonly string[]): void => {
12
+ for (const value of values) if (/[\n\r]/.test(value)) throw new Error(`a unit value holds a line break: ${JSON.stringify(value)}`);
13
+ };
14
+
15
+ /**
16
+ * systemd reads `Key=value` lines whose quotes are its own. An INI library quotes a value that holds a quote
17
+ * and so changes what systemd reads.
18
+ */
19
+ const serialize = (sections: Sections): string =>
20
+ `${Object.entries(sections)
21
+ .map(([section, keys]) => `[${section}]\n${Object.entries(keys).map(([key, value]) => `${key}=${value}`).join("\n")}`)
22
+ .join("\n\n")}\n`;
23
+
24
+ /** A user service that restarts after a failure only: the start script exits 0 when it gives up. */
25
+ export const systemdUnit: UnitBuilder = ({ repo, command, path, env, restartDelaySeconds }) => {
26
+ const environment = { PATH: path, ...env };
27
+
28
+ assertOneLine([repo, ...command, ...Object.values(environment)]);
29
+
30
+ return serialize({
31
+ Unit: { Description: `hum worker for ${literalPercent(repo)}`, After: "network-online.target", Wants: "network-online.target" },
32
+ Service: {
33
+ Type: "simple",
34
+ WorkingDirectory: literalPercent(repo),
35
+ Environment: Object.entries(environment)
36
+ .map(([key, value]) => word(`${key}=${value}`))
37
+ .join(" "),
38
+ ExecStart: command.map(word).join(" "),
39
+ Restart: "on-failure",
40
+ RestartSec: String(restartDelaySeconds),
41
+ },
42
+ Install: { WantedBy: "default.target" },
43
+ });
44
+ };
@@ -0,0 +1,21 @@
1
+ import type { Faults } from "../state/faults.ts";
2
+ import { DAY_MS } from "../time.ts";
3
+ import { CARD_CODES, CARD_KINDS } from "./cards.ts";
4
+
5
+ /** `claude setup-token` makes a one-year token. */
6
+ export const TOKEN_LIFE_DAYS = 365;
7
+
8
+ /** What `claude -p` prints for a rejected token: `Failed to authenticate. API Error: 401 Invalid bearer token`. */
9
+ export const UNAUTHORIZED = /API Error: 401|Failed to authenticate/i;
10
+
11
+ /** One card on the first 401. Items wait where they are until the token is renewed. */
12
+ export const rejectedToken = (faults: Faults, said: string) => faults.raise(CARD_KINDS.tokenRejected({ said }));
13
+
14
+ /** One card from `warnDays` before the token's year ends; it clears when `setUp` moves to a later day. */
15
+ export const checkTokenAge = (faults: Faults, setUp: string, now: number, warnDays: number): void => {
16
+ const expires = Date.parse(setUp) + TOKEN_LIFE_DAYS * DAY_MS;
17
+
18
+ if (now < expires - warnDays * DAY_MS) return faults.clear(CARD_CODES.tokenExpiring);
19
+
20
+ faults.raise(CARD_KINDS.tokenExpiring({ setUp, validUntil: new Date(expires).toISOString().slice(0, 10) }));
21
+ };
@@ -0,0 +1,29 @@
1
+ import { launchdUnit } from "./launchd.ts";
2
+ import { systemdUnit } from "./systemd.ts";
3
+
4
+ /** What a unit needs to run `hum serve` on its own: every path absolute, because a unit starts with a bare PATH. */
5
+ export type UnitVars = {
6
+ /** The launchd label, which also names the unit's file. */
7
+ readonly label: string;
8
+ /** The owner's checkout. */
9
+ readonly repo: string;
10
+ /** The program and its arguments: the runtime, the `hum` entry, `serve`, then the worker's options. */
11
+ readonly command: readonly string[];
12
+ /** The unit's PATH; it must reach `git`, `claude` and the runtime. */
13
+ readonly path: string;
14
+ /** More environment, such as `HOME`. */
15
+ readonly env?: Readonly<Record<string, string>>;
16
+ /** Where launchd writes the output. */
17
+ readonly log: string;
18
+ /** The seconds a service manager waits before it starts a failed script again. */
19
+ readonly restartDelaySeconds: number;
20
+ };
21
+
22
+ export type UnitKind = "launchd" | "systemd";
23
+
24
+ export type UnitBuilder = (vars: UnitVars) => string;
25
+
26
+ const UNITS = { launchd: launchdUnit, systemd: systemdUnit } as const satisfies Record<UnitKind, UnitBuilder>;
27
+
28
+ /** The unit file of one service manager. Throws when a value would break the file. */
29
+ export const renderUnit = (kind: UnitKind, vars: UnitVars): string => UNITS[kind](vars);
@@ -0,0 +1,30 @@
1
+ import * as core from "@actions/core";
2
+ import type { Card } from "../status/format.ts";
3
+ import type { Worker } from "../worker/worker.ts";
4
+
5
+ /**
6
+ * CI wake: ticks, lets the runs it started end, and ticks again until a tick starts nothing. A CI job holds no
7
+ * session across a wait for the owner: a run that needs them has pushed its branch, asked on the item and ended.
8
+ */
9
+ export const wakeUntilQuiet = async (worker: Worker): Promise<void> => {
10
+ for (;;) {
11
+ const result = await worker.tick();
12
+
13
+ await worker.idle();
14
+
15
+ if (result.kind !== "ran" || result.started.length === 0) return;
16
+ }
17
+ };
18
+
19
+ /** The card as one line of text. */
20
+ const line = (card: Card): string => `${card.cause} ${card.fix}`;
21
+
22
+ /**
23
+ * Shows the cards where a CI job's reader looks: one error annotation each, and the job's step summary when the
24
+ * runner gives one. The job's status file dies with the job, so this is the only place CI shows a card.
25
+ */
26
+ export const reportCards = async (cards: readonly Card[]): Promise<void> => {
27
+ for (const card of cards) core.error(line(card), { title: `hum ${card.code}` });
28
+
29
+ if (process.env.GITHUB_STEP_SUMMARY && cards.length > 0) await core.summary.addHeading("hum", 2).addList(cards.map((card) => `${card.code}: ${line(card)}`)).write();
30
+ };
@@ -0,0 +1,97 @@
1
+ import { stringify } from "yaml";
2
+ import { CLAUDE_FLOOR } from "../adapters/claude-p.ts";
3
+ import type { HumConfig } from "../config/schema.ts";
4
+
5
+ /** The settings the workflows are built from. */
6
+ export type WorkflowSettings = Pick<HumConfig, "runBranchPrefix" | "itemsDir" | "ciSchedule" | "commitIdentity" | "ciWakeTimeoutMinutes" | "pullRequestTokenSecret">;
7
+
8
+ export const WAKE_FILE = "hum-wake.yml";
9
+
10
+ /** The type of the `repository_dispatch` event a tracker's webhook sends. */
11
+ export const DISPATCH_EVENT = "hum-wake";
12
+
13
+ const WAKE_PATH = `./.github/workflows/${WAKE_FILE}`;
14
+
15
+ const TOKEN_SECRET = "CLAUDE_CODE_OAUTH_TOKEN";
16
+
17
+ const HOPE_MARKETPLACE = "saadshahd/moo.md";
18
+
19
+ /** The Bun that builds the workflows is the one the owner's repo runs, so CI installs with the same lockfile reader. */
20
+ const BUN_VERSION = Bun.version;
21
+
22
+ const ACTIONS = { checkout: "actions/checkout@v4", setupBun: "oven-sh/setup-bun@v2" } as const;
23
+
24
+ const PERMISSIONS = { contents: "write", issues: "write", "pull-requests": "write" } as const;
25
+
26
+ /** One wake at a time: a second event waits for the first run instead of racing it. */
27
+ const CONCURRENCY = { group: "hum-wake", "cancel-in-progress": false } as const;
28
+
29
+ /** The events a trigger workflow starts on. */
30
+ type TriggerEvents = {
31
+ readonly issue_comment?: { readonly types: readonly string[] };
32
+ readonly push?: { readonly branches: readonly string[]; readonly paths: readonly string[] };
33
+ readonly repository_dispatch?: { readonly types: readonly string[] };
34
+ readonly schedule?: readonly { readonly cron: string }[];
35
+ readonly workflow_dispatch?: null;
36
+ };
37
+
38
+ type TriggerJob = { readonly if?: string };
39
+
40
+ /** A workflow that only chooses what starts the shared wake job. */
41
+ const trigger = (name: string, on: TriggerEvents, job: TriggerJob = {}) => ({
42
+ name,
43
+ on,
44
+ permissions: PERMISSIONS,
45
+ concurrency: CONCURRENCY,
46
+ jobs: { wake: { ...job, uses: WAKE_PATH, secrets: "inherit" } },
47
+ });
48
+
49
+ /**
50
+ * The job every wake runs. A run clones the repo again into a temp folder, so the git credentials and identity are
51
+ * global: the checkout's own are local to its workspace. A run that needs the owner has pushed its run branch, asked
52
+ * on the item and ended; the owner's answer starts a fresh run on that branch, so no session, artifact or approval
53
+ * is kept between runs.
54
+ */
55
+ const wake = ({ commitIdentity, ciWakeTimeoutMinutes, pullRequestTokenSecret }: WorkflowSettings) => ({
56
+ name: "hum wake",
57
+ on: { workflow_call: { secrets: { [TOKEN_SECRET]: { required: true }, [pullRequestTokenSecret]: { required: false } } } },
58
+ permissions: PERMISSIONS,
59
+ jobs: {
60
+ wake: {
61
+ "runs-on": "ubuntu-latest",
62
+ "timeout-minutes": ciWakeTimeoutMinutes,
63
+ env: {
64
+ [TOKEN_SECRET]: `\${{ secrets.${TOKEN_SECRET} }}`,
65
+ GH_TOKEN: `\${{ secrets.${pullRequestTokenSecret} || github.token }}`,
66
+ HUM_EVENT: "${{ github.event_name }}",
67
+ },
68
+ steps: [
69
+ { uses: ACTIONS.checkout, with: { "fetch-depth": 0 } },
70
+ { uses: ACTIONS.setupBun, with: { "bun-version": BUN_VERSION } },
71
+ { run: "bun install --frozen-lockfile" },
72
+ { run: `npm install --global @anthropic-ai/claude-code@${CLAUDE_FLOOR}` },
73
+ { run: `claude plugin marketplace add ${HOPE_MARKETPLACE}\nclaude plugin install hope@moo.md\n` },
74
+ { run: "gh auth setup-git" },
75
+ {
76
+ run: 'git config --global user.name "$HUM_GIT_NAME"\ngit config --global user.email "$HUM_GIT_EMAIL"\n',
77
+ env: { HUM_GIT_NAME: commitIdentity.name, HUM_GIT_EMAIL: commitIdentity.email },
78
+ },
79
+ { run: './node_modules/.bin/hum wake --event "$HUM_EVENT"' },
80
+ ],
81
+ },
82
+ },
83
+ });
84
+
85
+ const WORKFLOWS = {
86
+ [WAKE_FILE]: wake,
87
+ "hum-comment.yml": () => trigger("hum on comment", { issue_comment: { types: ["created"] } }, { if: "github.event.comment.user.type != 'Bot'" }),
88
+ "hum-push.yml": ({ itemsDir, runBranchPrefix }) => trigger("hum on item push", { push: { branches: ["**", `!${runBranchPrefix}**`], paths: [`${itemsDir}/**`] } }),
89
+ "hum-dispatch.yml": () => trigger("hum on dispatch", { repository_dispatch: { types: [DISPATCH_EVENT] } }),
90
+ "hum-schedule.yml": ({ ciSchedule }) => trigger("hum on schedule", { schedule: [{ cron: ciSchedule }], workflow_dispatch: null }),
91
+ } as const satisfies Record<string, (settings: WorkflowSettings) => object>;
92
+
93
+ export type WorkflowFile = { readonly file: string; readonly text: string };
94
+
95
+ /** The workflow files for an owner's repo, each named for `.github/workflows/`. */
96
+ export const ciWorkflows = (settings: WorkflowSettings): WorkflowFile[] =>
97
+ Object.entries(WORKFLOWS).map(([file, build]) => ({ file, text: stringify(build(settings), { lineWidth: 0 }) }));
@@ -0,0 +1,120 @@
1
+ import type { Item } from "../adapter-api.ts";
2
+ import { declaredKind } from "../decide/kind.ts";
3
+ import { usualSize } from "../decide/risk.ts";
4
+ import type { DefaultsConfig, HumConfig, PathRule, RunPlace, SlotRecipe } from "../config/schema.ts";
5
+ import type { CiJob, RepoScan } from "./scan.ts";
6
+ import {
7
+ CHECK_COMMAND,
8
+ CHECK_SCRIPTS,
9
+ DATA_AND_SECRET_GLOBS,
10
+ DEFAULT_FOLDER_RANK,
11
+ FOLDER_RANKS,
12
+ INSTALL_COMMANDS,
13
+ KIND_LABEL_WORDS,
14
+ NOT_A_CHECK,
15
+ ROOT_MARKDOWN_RANK,
16
+ RUN_SCRIPT,
17
+ SECRET_TEMPLATE,
18
+ } from "./tables.ts";
19
+
20
+ /** The settings setup proposes from a scan; the owner changes any of them before they are written. */
21
+ export type Proposal = {
22
+ readonly checks: readonly string[];
23
+ readonly paths: readonly PathRule[];
24
+ readonly strictPaths: readonly string[];
25
+ /** The top of each folder's usual size; undefined while it has too few merged changes to have one. */
26
+ readonly usualSizes: readonly { readonly folder: string; readonly usual: number | undefined }[];
27
+ readonly windows: Pick<HumConfig["changeLabels"], "fixWindow"> & Pick<HumConfig, "measureWindow">;
28
+ readonly kindLabels: Readonly<Record<string, string>>;
29
+ readonly runSlots: Pick<HumConfig["runSlots"], "services" | "recipe">;
30
+ readonly runPlaces: readonly RunPlace[];
31
+ };
32
+
33
+ const isPullRequestJob = ({ triggers }: CiJob): boolean => triggers.includes("pull_request");
34
+
35
+ const isCheck = (command: string): boolean => CHECK_COMMAND.test(command) && !NOT_A_CHECK.test(command);
36
+
37
+ const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];
38
+
39
+ const scriptCommand = (scan: RepoScan, script: string): string | undefined => {
40
+ const run = scan.packageManager === undefined ? undefined : RUN_SCRIPT[scan.packageManager];
41
+
42
+ return run !== undefined && script in scan.scripts ? `${run} ${script}` : undefined;
43
+ };
44
+
45
+ /**
46
+ * The commands the repo's own CI runs on a pull request to check a change; else its package scripts that check.
47
+ * A run checks a fresh clone, which has no dependencies yet, so the lockfile install comes first.
48
+ */
49
+ export const checksOf = (scan: RepoScan): string[] => {
50
+ const fromCi = unique(scan.ci.filter(isPullRequestJob).flatMap(({ commands }) => commands.filter(isCheck)));
51
+ const checks = fromCi.length > 0 ? fromCi : CHECK_SCRIPTS.flatMap((script) => scriptCommand(scan, script) ?? []);
52
+
53
+ return scan.packageManager === undefined || checks.length === 0 ? checks : [INSTALL_COMMANDS[scan.packageManager], ...checks];
54
+ };
55
+
56
+ const levelAt = (levels: HumConfig["levels"], rank: number): string => levels[Math.min(rank, levels.length - 1)]?.name ?? "";
57
+
58
+ const rankOfFolder = (folder: string): number => FOLDER_RANKS.find((row) => row.folder.test(folder))?.rank ?? DEFAULT_FOLDER_RANK;
59
+
60
+ const topFolders = (tracked: readonly string[]): string[] => unique(tracked.flatMap((path) => (path.includes("/") ? [path.split("/")[0] ?? ""] : []))).sort();
61
+
62
+ /** A rule per top-level folder, one for markdown at the root and one for the other root files, so no path is left unplaced. */
63
+ export const pathRulesOf = (tracked: readonly string[], levels: HumConfig["levels"]): PathRule[] => [
64
+ ...topFolders(tracked).map((folder) => ({ glob: `${folder}/**`, level: levelAt(levels, rankOfFolder(folder)) })),
65
+ { glob: "*.md", level: levelAt(levels, ROOT_MARKDOWN_RANK) },
66
+ { glob: "*", level: levelAt(levels, DEFAULT_FOLDER_RANK) },
67
+ ];
68
+
69
+ /** The data and secrets globs that match a tracked file; a file that only shows the shape of a secret does not count. */
70
+ export const strictGlobsOf = (tracked: readonly string[]): string[] =>
71
+ DATA_AND_SECRET_GLOBS.filter((glob) => tracked.some((path) => new Bun.Glob(glob).match(path) && !SECRET_TEMPLATE.test(path)));
72
+
73
+ const mapLabels = (labels: readonly string[], kinds: readonly string[]): Record<string, string> =>
74
+ Object.fromEntries(
75
+ unique(labels.map((label) => label.toLowerCase())).flatMap((label) => {
76
+ const kind = Object.entries(KIND_LABEL_WORDS).find(([name, words]) => kinds.includes(name) && new Set<string>(words).has(label))?.[0];
77
+
78
+ return kind === undefined || kinds.includes(label) ? [] : [[label, kind]];
79
+ }),
80
+ );
81
+
82
+ /** Label → kind for the labels the repo uses: those on its issue templates and the ones it lists. A label the table does not know is left out. */
83
+ export const kindLabelsOf = (scan: RepoScan, repoLabels: readonly string[], kinds: readonly string[]): Record<string, string> =>
84
+ mapLabels([...scan.issueTemplates.flatMap(({ labels }) => labels), ...repoLabels], kinds);
85
+
86
+ /** How many of the open items name their kind through the map, a kind's own name or a template field. */
87
+ export const kindCoverage = (items: readonly Pick<Item, "body" | "labels">[], kinds: readonly string[], kindLabels: HumConfig["kindLabels"]) => ({
88
+ covered: items.filter((item) => declaredKind(item, kinds, kindLabels) !== undefined).length,
89
+ total: items.length,
90
+ });
91
+
92
+ const recipeOf = (scan: RepoScan, checks: readonly string[]): SlotRecipe => {
93
+ const install = scan.packageManager === undefined ? [] : [INSTALL_COMMANDS[scan.packageManager]];
94
+ const [script] = scan.envScripts;
95
+ const seed = scriptCommand(scan, "seed");
96
+ const services = scan.composeServices.length > 0 ? ['docker compose -p "$COMPOSE_PROJECT_NAME" up -d --wait'] : [];
97
+ const [fast] = checks.filter((command) => /\b(lint|typecheck|check)\b/.test(command));
98
+
99
+ return {
100
+ prepare: script === undefined ? [...install, ...services, ...(seed ? [seed] : [])] : [`./${script}`],
101
+ refresh: script === undefined ? install.map((run) => ({ run, when: "lockfile-changed" as const })) : [{ run: `./${script}`, when: "lockfile-changed" as const }],
102
+ ready: [fast ?? checks[0]].flatMap((command) => command ?? []),
103
+ };
104
+ };
105
+
106
+ /** Everything setup proposes from a scan, before it asks. */
107
+ export const proposeSetup = (scan: RepoScan, shipped: DefaultsConfig, repoLabels: readonly string[] = []): Proposal => {
108
+ const checks = checksOf(scan);
109
+
110
+ return {
111
+ checks,
112
+ paths: pathRulesOf(scan.tracked, shipped.levels),
113
+ strictPaths: strictGlobsOf(scan.tracked),
114
+ usualSizes: scan.folders.map(({ folder, sizes }) => ({ folder, usual: usualSize(sizes, shipped.sizeRange) })),
115
+ windows: { fixWindow: shipped.changeLabels.fixWindow, measureWindow: shipped.measureWindow },
116
+ kindLabels: kindLabelsOf(scan, repoLabels, shipped.kinds),
117
+ runSlots: { services: shipped.runSlots.services, recipe: recipeOf(scan, checks) },
118
+ runPlaces: shipped.runPlaces,
119
+ };
120
+ };