@moo.md/hum 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/defaults/hum.json +321 -0
  2. package/defaults/kinds/check.json +183 -0
  3. package/defaults/kinds/docs.json +151 -0
  4. package/defaults/kinds/feature.json +202 -0
  5. package/defaults/kinds/fix.json +183 -0
  6. package/defaults/kinds/hotfix.json +164 -0
  7. package/defaults/roles/build.md +3 -0
  8. package/defaults/roles/fix.md +1 -0
  9. package/defaults/roles/plan.md +3 -0
  10. package/defaults/roles/review.md +3 -0
  11. package/evals/alignment/RESULTS.md +8 -0
  12. package/evals/alignment/cases.jsonl +128 -0
  13. package/evals/alignment/sample.jsonl +20 -0
  14. package/evals/kind/RESULTS.md +5 -0
  15. package/evals/kind/cases.jsonl +24 -0
  16. package/evals/plan-outcome/RESULTS.md +4 -0
  17. package/evals/plan-outcome/cases.jsonl +12 -0
  18. package/evals/repeat-pair/RESULTS.md +4 -0
  19. package/evals/repeat-pair/cases.jsonl +51 -0
  20. package/evals/reply-option/RESULTS.md +3 -0
  21. package/evals/reply-option/cases.jsonl +45 -0
  22. package/evals/review-verdict/RESULTS.md +4 -0
  23. package/evals/review-verdict/cases.jsonl +12 -0
  24. package/package.json +88 -4
  25. package/schema/hum.schema.json +1355 -0
  26. package/scripts/eval.ts +244 -0
  27. package/src/adapter-api.ts +134 -0
  28. package/src/adapters/admit.ts +111 -0
  29. package/src/adapters/argument.ts +11 -0
  30. package/src/adapters/claim.ts +93 -0
  31. package/src/adapters/claude-bg.ts +392 -0
  32. package/src/adapters/claude-p.ts +599 -0
  33. package/src/adapters/contract.ts +231 -0
  34. package/src/adapters/fake.ts +157 -0
  35. package/src/adapters/git.ts +156 -0
  36. package/src/adapters/github.ts +479 -0
  37. package/src/adapters/guard.ts +152 -0
  38. package/src/adapters/history.ts +215 -0
  39. package/src/adapters/item-file.ts +102 -0
  40. package/src/adapters/limit.ts +67 -0
  41. package/src/adapters/markdown.ts +365 -0
  42. package/src/adapters/marked.ts +127 -0
  43. package/src/adapters/model-call.ts +75 -0
  44. package/src/adapters/once.ts +45 -0
  45. package/src/adapters/owner-commit.ts +60 -0
  46. package/src/adapters/pull-requests.ts +253 -0
  47. package/src/adapters/registry.ts +156 -0
  48. package/src/adapters/roundup.ts +293 -0
  49. package/src/adapters/serial.ts +22 -0
  50. package/src/adapters/transcript.ts +99 -0
  51. package/src/cli/commands.ts +46 -0
  52. package/src/cli/main.ts +8 -0
  53. package/src/cli/ops.ts +224 -0
  54. package/src/cli/service.ts +156 -0
  55. package/src/cli/setup.ts +141 -0
  56. package/src/cli/shared-watch.ts +127 -0
  57. package/src/config/change.ts +54 -0
  58. package/src/config/checks.ts +217 -0
  59. package/src/config/git-ref-name.d.ts +3 -0
  60. package/src/config/hash.ts +6 -0
  61. package/src/config/json.ts +6 -0
  62. package/src/config/load.ts +88 -0
  63. package/src/config/machine.ts +20 -0
  64. package/src/config/migrate.ts +61 -0
  65. package/src/config/refusal.ts +58 -0
  66. package/src/config/schema.ts +465 -0
  67. package/src/config/settings.ts +6 -0
  68. package/src/config/state-map.ts +76 -0
  69. package/src/decide/alignment.ts +79 -0
  70. package/src/decide/answer.ts +131 -0
  71. package/src/decide/kind.ts +39 -0
  72. package/src/decide/labels.ts +137 -0
  73. package/src/decide/merge.ts +102 -0
  74. package/src/decide/prose.ts +109 -0
  75. package/src/decide/question.ts +159 -0
  76. package/src/decide/review.ts +10 -0
  77. package/src/decide/risk.ts +216 -0
  78. package/src/decide/taste.ts +37 -0
  79. package/src/exec.ts +85 -0
  80. package/src/index.ts +200 -0
  81. package/src/loop/breaks.ts +8 -0
  82. package/src/loop/check-item.ts +76 -0
  83. package/src/loop/ci.ts +8 -0
  84. package/src/loop/github.ts +81 -0
  85. package/src/loop/groups.ts +108 -0
  86. package/src/loop/memory.ts +70 -0
  87. package/src/loop/notes.ts +76 -0
  88. package/src/loop/pair.ts +39 -0
  89. package/src/loop/pass.ts +99 -0
  90. package/src/loop/proof.ts +85 -0
  91. package/src/loop/prove-item.ts +33 -0
  92. package/src/loop/records.ts +75 -0
  93. package/src/loop/signals.ts +130 -0
  94. package/src/measure/inputs.ts +28 -0
  95. package/src/measure/measure.ts +68 -0
  96. package/src/service/cards.ts +24 -0
  97. package/src/service/ci-tick.ts +28 -0
  98. package/src/service/launchd.ts +16 -0
  99. package/src/service/supervise.ts +145 -0
  100. package/src/service/systemd.ts +44 -0
  101. package/src/service/token.ts +21 -0
  102. package/src/service/unit.ts +29 -0
  103. package/src/service/wake.ts +30 -0
  104. package/src/service/workflows.ts +97 -0
  105. package/src/setup/propose.ts +120 -0
  106. package/src/setup/prove.ts +216 -0
  107. package/src/setup/scan.ts +186 -0
  108. package/src/setup/scratch.ts +81 -0
  109. package/src/setup/shipped.ts +15 -0
  110. package/src/setup/tables.ts +101 -0
  111. package/src/setup/waits.ts +58 -0
  112. package/src/setup/write.ts +161 -0
  113. package/src/slots/env.ts +42 -0
  114. package/src/slots/pool.ts +329 -0
  115. package/src/slots/scan.ts +26 -0
  116. package/src/slots/worktree.ts +17 -0
  117. package/src/state/events.ts +52 -0
  118. package/src/state/faults.ts +73 -0
  119. package/src/state/format.ts +50 -0
  120. package/src/state/fs.ts +100 -0
  121. package/src/state/items.ts +195 -0
  122. package/src/state/open.ts +80 -0
  123. package/src/state/ops.ts +76 -0
  124. package/src/state/records.ts +35 -0
  125. package/src/state/runs.ts +99 -0
  126. package/src/state/saved.ts +119 -0
  127. package/src/status/file.ts +49 -0
  128. package/src/status/format.ts +132 -0
  129. package/src/status/sections.ts +14 -0
  130. package/src/status/version.ts +2 -0
  131. package/src/time.ts +7 -0
  132. package/src/worker/alignment-report.ts +18 -0
  133. package/src/worker/answers.ts +153 -0
  134. package/src/worker/base-check.ts +45 -0
  135. package/src/worker/checks.ts +40 -0
  136. package/src/worker/kind.ts +68 -0
  137. package/src/worker/land.ts +509 -0
  138. package/src/worker/lifecycle.ts +97 -0
  139. package/src/worker/merged.ts +29 -0
  140. package/src/worker/open.ts +100 -0
  141. package/src/worker/prose-run.ts +56 -0
  142. package/src/worker/questions.ts +89 -0
  143. package/src/worker/scheduler.ts +135 -0
  144. package/src/worker/signature.ts +41 -0
  145. package/src/worker/tally.ts +25 -0
  146. package/src/worker/taste.ts +38 -0
  147. package/src/worker/thin-path.ts +886 -0
  148. package/src/worker/worker.ts +750 -0
  149. package/surface.json +8787 -0
  150. package/README.md +0 -3
package/src/cli/ops.ts ADDED
@@ -0,0 +1,224 @@
1
+ import { Command, CommanderError, Option } from "commander";
2
+ import { x } from "tinyexec";
3
+ import { z } from "zod";
4
+ import { type ClaimResult, type Item, type ItemRef, PermanentError, Watch } from "../adapter-api.ts";
5
+ import { pushArgs } from "../adapters/git.ts";
6
+ import { resolveAdapters, type Slot } from "../adapters/registry.ts";
7
+ import { readSettings } from "../config/settings.ts";
8
+ import { HumConfig } from "../config/schema.ts";
9
+ import { dropInto } from "../state/fs.ts";
10
+ import { defaultStateDir, openState } from "../state/open.ts";
11
+ import pkg from "../../package.json" with { type: "json" };
12
+ import { type OpName, commands, type Flag, opSpecs } from "./commands.ts";
13
+ import { addServiceCommands } from "./service.ts";
14
+ import { addSetupCommands } from "./setup.ts";
15
+ import { sharedWatch } from "./shared-watch.ts";
16
+ import { SECOND_MS } from "../time.ts";
17
+
18
+ type Printable = ItemRef[] | ItemRef | Item | ClaimResult | Watch | { readonly ok: true };
19
+
20
+ export type Io = {
21
+ readonly cwd: string;
22
+ readonly stdout: (text: string) => void;
23
+ readonly stderr: (text: string) => void;
24
+ };
25
+
26
+ const EXIT_FAILED = 1;
27
+ const EXIT_MISUSED = 2;
28
+
29
+ const OK = { ok: true } as const;
30
+
31
+ const CliSettings = z.looseObject({
32
+ claimExpirySeconds: HumConfig.shape.claimExpirySeconds,
33
+ watchCacheSeconds: HumConfig.shape.watchCacheSeconds,
34
+ watchLockSeconds: HumConfig.shape.watchLockSeconds,
35
+ runPlaces: HumConfig.shape.runPlaces,
36
+ });
37
+
38
+ type CliSettings = z.infer<typeof CliSettings>;
39
+
40
+ type Flags = { ttl?: number; renew?: boolean; option?: string | string[]; since?: string; body?: string };
41
+
42
+ type Adapters = Awaited<ReturnType<typeof resolveAdapters>>;
43
+
44
+ /** What every op reads: its positional arguments, flags and the integrations `hum.json` names. */
45
+ type Call = {
46
+ /** The first positional argument. */
47
+ readonly item: string;
48
+ /** The second positional argument. */
49
+ readonly second: string;
50
+ /** Every positional argument after the first, as one text. */
51
+ readonly text: string;
52
+ readonly flags: Flags;
53
+ readonly options: readonly string[];
54
+ readonly stateDir: string;
55
+ /** The folder the worker reads item ids from at once. */
56
+ readonly inbox: string;
57
+ readonly settings: CliSettings;
58
+ /** The integration role of a slot; throws when none is set up. */
59
+ readonly slot: <T>(name: Slot, role: (adapter: NonNullable<Adapters[Slot]>) => T | undefined) => T;
60
+ };
61
+
62
+ /** Leaves a wake file in the inbox for the worker on this machine. A repo that runs only in CI has no such worker to read it, so no file is left. */
63
+ const wakeWorker = ({ inbox, settings }: Pick<Call, "inbox" | "settings">, item: string): void => {
64
+ if (settings.runPlaces.includes("mac")) dropInto(inbox, item);
65
+ };
66
+
67
+ const performed = async (action: Promise<void>): Promise<Printable> => {
68
+ await action;
69
+
70
+ return OK;
71
+ };
72
+
73
+ type Handler = (call: Call) => Promise<Printable>;
74
+
75
+ const handlers = {
76
+ "list-ready": ({ slot }) => slot("work-source", (a) => a.workSource).listReady(),
77
+ claim: ({ slot, item, second: holder, flags, settings }) => {
78
+ const source = slot("work-source", (a) => a.workSource);
79
+ const ttlMs = (flags.ttl ?? settings.claimExpirySeconds) * SECOND_MS;
80
+
81
+ return (flags.renew ? source.renew : source.claim)(item, holder, ttlMs);
82
+ },
83
+ read: ({ slot, item }) => slot("work-source", (a) => a.workSource).read(item),
84
+ comment: ({ slot, item, text }) => performed(slot("work-source", (a) => a.workSource).comment(item, text)),
85
+ ask: ({ slot, item, text, options }) => performed(slot("questions", (a) => a.questions).ask(item, { text: text, options: options.length > 0 ? options : undefined })),
86
+ answer: async ({ slot, item, text, options, inbox, settings }) => {
87
+ await slot("answers", (a) => a.answers).answer(item, { text, option: options[0] });
88
+ wakeWorker({ inbox, settings }, item);
89
+
90
+ return OK;
91
+ },
92
+ watch: ({ slot, stateDir, inbox, flags, settings }) => {
93
+ const answers = slot("answers", (a) => a.answers);
94
+
95
+ if (flags.since !== undefined) return answers.watch(flags.since).then((found) => Watch.parse(found));
96
+
97
+ return sharedWatch({
98
+ stateDir,
99
+ now: Date.now,
100
+ cacheMs: settings.watchCacheSeconds * SECOND_MS,
101
+ lockMs: settings.watchLockSeconds * SECOND_MS,
102
+ read: async (since) => Watch.parse(await answers.watch(since)),
103
+ changed: () => wakeWorker({ inbox, settings }, ""),
104
+ });
105
+ },
106
+ "file-follow-up": ({ slot, item, second, flags }) => slot("work-source", (a) => a.workSource).fileFollowUp(item, { title: second, body: flags.body ?? "" }),
107
+ decide: ({ slot, item, text }) => performed(slot("questions", (a) => a.questions).decide(item, text)),
108
+ publish: ({ slot, item, second }) => performed(slot("release", (a) => a.release).publish(item, second)),
109
+ release: ({ slot, item, second }) => performed(slot("release", (a) => a.release).release(item, second)),
110
+ } as const satisfies Record<Exclude<OpName, "push">, Handler>;
111
+
112
+ const callOf = async (positionals: readonly string[], flags: Flags, io: Io): Promise<Call> => {
113
+ const stateDir = await defaultStateDir(io.cwd);
114
+ const state = openState(stateDir);
115
+ const settings = readSettings(io.cwd, CliSettings);
116
+
117
+ const adapters = await resolveAdapters(io.cwd, {
118
+ faults: state.faults,
119
+ guard: {},
120
+ context: { report: (fault) => void state.faults.raise(fault), now: Date.now },
121
+ });
122
+
123
+ const [item = "", ...rest] = positionals;
124
+
125
+ return {
126
+ item,
127
+ second: rest[0] ?? "",
128
+ text: rest.join(" "),
129
+ flags,
130
+ options: [flags.option ?? []].flat(),
131
+ stateDir,
132
+ inbox: state.inbox,
133
+ settings,
134
+ slot: (name, role) => {
135
+ const adapter = adapters[name];
136
+ const found = adapter && role(adapter);
137
+
138
+ if (!found) throw new PermanentError(`no ${name} integration is set up; name one under "integrations" in .hum/hum.json`);
139
+
140
+ return found;
141
+ },
142
+ };
143
+ };
144
+
145
+ /** Runs one parsed `hum <op>` and returns its exit code: 0 done, 1 failed, 2 misused. */
146
+ const perform = async (op: OpName, positionals: readonly string[], flags: Flags, io: Io): Promise<number> => {
147
+ if (op === "push") return (await x("git", pushArgs(positionals), { nodeOptions: { cwd: io.cwd, stdio: "inherit" } })).exitCode ?? EXIT_FAILED;
148
+
149
+ try {
150
+ const printed = await handlers[op](await callOf(positionals, flags, io));
151
+
152
+ io.stdout(`${JSON.stringify(printed)}\n`);
153
+
154
+ return 0;
155
+ } catch (error) {
156
+ io.stderr(`hum ${op}: ${error instanceof Error ? error.message : String(error)}\n`);
157
+
158
+ return EXIT_FAILED;
159
+ }
160
+ };
161
+
162
+ const optionOf = ({ flag, repeats, parse }: Flag): Option => {
163
+ const option = new Option(flag);
164
+
165
+ if (repeats) return option.default([]).argParser((word: string, seen: string[]) => [...seen, word]);
166
+
167
+ return parse ? option.argParser(parse) : option;
168
+ };
169
+
170
+ /** The `hum` command tree. Each command reports its exit code through `exitWith`. */
171
+ export const buildProgram = (io: Io, exitWith: (code: number) => void): Command => {
172
+ const root = new Command("hum")
173
+ .version(pkg.version)
174
+ .enablePositionalOptions()
175
+ .showHelpAfterError()
176
+ .exitOverride()
177
+ .configureOutput({ writeOut: io.stdout, writeErr: io.stderr });
178
+
179
+ // SAFETY: `opSpecs` is a record keyed by `OpName`, so its entries are `OpName` pairs.
180
+ for (const [name, spec] of Object.entries(opSpecs) as [OpName, (typeof opSpecs)[OpName]][]) {
181
+ const op = root.command(`${name} ${spec.args}`).description(spec.summary);
182
+
183
+ for (const flag of spec.flags ?? []) op.addOption(optionOf(flag));
184
+
185
+ if (name === "push") op.allowUnknownOption().allowExcessArguments().helpOption(false);
186
+
187
+ op.action(async () => {
188
+ exitWith(await perform(name, op.processedArgs.flat(), op.opts(), io));
189
+ });
190
+ }
191
+
192
+ root.command("help").description("Print every op's usage; --json prints the table roles read.").option("--json").action((flags: { json?: boolean }) => {
193
+ io.stdout(`${flags.json ? JSON.stringify(commands) : Object.values(commands).map((c) => c.usage).join("\n")}\n`);
194
+ });
195
+
196
+ addServiceCommands(root, io, exitWith);
197
+ addSetupCommands(root, io, exitWith);
198
+
199
+ return root;
200
+ };
201
+
202
+ /** Runs `hum <argv>` (an op and its arguments) and returns its exit code: 0 done, 1 failed, 2 misused. */
203
+ export const runCli = async (argv: readonly string[], io: Io): Promise<number> => {
204
+ let code = 0;
205
+
206
+ const root = buildProgram(io, (exit) => {
207
+ code = exit;
208
+ });
209
+
210
+ try {
211
+ await root.parseAsync([...argv], { from: "user" });
212
+ } catch (error) {
213
+ if (error instanceof CommanderError) return error.exitCode === 0 ? 0 : EXIT_MISUSED;
214
+
215
+ io.stderr(`hum ${argv[0] ?? ""}: ${error instanceof Error ? error.message : String(error)}\n`);
216
+
217
+ return EXIT_FAILED;
218
+ }
219
+
220
+ return code;
221
+ };
222
+
223
+ /** Runs one `hum <op>` and returns its exit code: 0 done, 1 failed, 2 misused. */
224
+ export const runOp = (op: OpName, argv: readonly string[], io: Io): Promise<number> => runCli([op, ...argv], io);
@@ -0,0 +1,156 @@
1
+ import { hostname } from "node:os";
2
+ import { join } from "node:path";
3
+ import type { Command } from "commander";
4
+ import { x } from "tinyexec";
5
+ import { z } from "zod";
6
+ import { listHopeSkills } from "../config/load.ts";
7
+ import { HumConfig } from "../config/schema.ts";
8
+ import { readSettings } from "../config/settings.ts";
9
+ import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
+ import { readCiTick, recordCiTick } from "../service/ci-tick.ts";
11
+ import { EXIT_UPDATED, supervise } from "../service/supervise.ts";
12
+ import { reportCards, wakeUntilQuiet } from "../service/wake.ts";
13
+ import { defaultStateDir, openState } from "../state/open.ts";
14
+ import { SECOND_MS } from "../time.ts";
15
+ import { readStatus } from "../status/file.ts";
16
+ import { npmLatest, openWorker } from "../worker/open.ts";
17
+ import type { Io } from "./ops.ts";
18
+
19
+ const EXIT_OK = 0;
20
+
21
+ /** The start script's exit code when it gave up or was stopped: the unit restarts a script only after a failure. */
22
+ const EXIT_STAY_DOWN = EXIT_OK;
23
+
24
+ const EXIT_CARDS_SHOWN = 1;
25
+
26
+ const SCHEDULE_EVENT = "schedule";
27
+
28
+ type WorkFlags = { holder?: string; base?: string };
29
+
30
+ /** What a worker needs to know that no file in the repo says: who it claims as, and where items merge. */
31
+ const withWorkOptions = (cmd: Command): Command =>
32
+ cmd
33
+ .option("--holder <name>", "the name this worker claims items by; default <where>@<host>")
34
+ .option("--base <branch>", "the branch items merge into; default main");
35
+
36
+ const PluginList = z.array(z.looseObject({ id: z.string(), installPath: z.string() }));
37
+
38
+ /** The folder of the installed hope plugin: `HUM_HOPE_ROOT`, else the path `claude plugin list` gives. */
39
+ export const hopeRoot = async (): Promise<string> => {
40
+ if (process.env.HUM_HOPE_ROOT) return process.env.HUM_HOPE_ROOT;
41
+
42
+ const listed = await exec("claude", ["plugin", "list", "--json"], { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
43
+ const hope = listed.exitCode === 0 ? PluginList.parse(JSON.parse(listed.stdout)).find((plugin) => plugin.id.startsWith("hope@")) : undefined;
44
+
45
+ if (!hope) throw new Error("the hope plugin is not installed: run `claude plugin install hope@moo.md`, or set HUM_HOPE_ROOT to its folder");
46
+
47
+ return hope.installPath;
48
+ };
49
+
50
+ const ServiceSettings = z.looseObject({
51
+ tickIntervalSeconds: HumConfig.shape.tickIntervalSeconds,
52
+ workerDownTicks: HumConfig.shape.workerDownTicks,
53
+ maxCrashes: HumConfig.shape.maxCrashes,
54
+ crashWindowSeconds: HumConfig.shape.crashWindowSeconds,
55
+ restartBackoff: HumConfig.shape.restartBackoff,
56
+ commandTimeoutSeconds: HumConfig.shape.commandTimeoutSeconds,
57
+ });
58
+
59
+ /**
60
+ * The settings the start script needs, with the shipped default for any it cannot read. A config the worker
61
+ * refuses is the worker's to report: it exits, and the script counts the crash and shows the card.
62
+ */
63
+ const serviceSettings = (repo: string): z.infer<typeof ServiceSettings> => {
64
+ try {
65
+ return readSettings(repo, ServiceSettings);
66
+ } catch {
67
+ return ServiceSettings.parse({});
68
+ }
69
+ };
70
+
71
+ /** The Mac reads the npm version and when the scheduled workflow last ran; a CI job is that workflow. */
72
+ const openFor = async (repo: string, flags: WorkFlags, where: "mac" | "ci") => {
73
+ const timeoutMs = commandTimeoutMs(serviceSettings(repo));
74
+
75
+ return openWorker(repo, {
76
+ hopeSkills: listHopeSkills(await hopeRoot()),
77
+ holder: flags.holder ?? `${where}@${hostname()}`,
78
+ base: flags.base,
79
+ where,
80
+ latestVersion: where === "mac" ? npmLatest : undefined,
81
+ ciTick: where === "mac" ? () => readCiTick(repo, "origin", timeoutMs) : undefined,
82
+ });
83
+ };
84
+
85
+ const onStop = (stop: () => void) => {
86
+ for (const signal of ["SIGTERM", "SIGINT"] as const) process.once(signal, stop);
87
+ };
88
+
89
+ /** `hum work` as a child process of this one, sharing its terminal. */
90
+ const spawnWorker = (cwd: string, workArgs: readonly string[]) => {
91
+ const child = x(process.execPath, [process.argv[1] ?? "", "work", ...workArgs], { nodeOptions: { cwd, stdio: "inherit" } });
92
+
93
+ return { exited: Promise.resolve(child).then(({ exitCode }) => exitCode ?? 1), kill: () => void child.kill("SIGTERM") };
94
+ };
95
+
96
+ /**
97
+ * `hum work`, `hum serve` and `hum wake`: the processes a service unit and a CI workflow start. They are not ops:
98
+ * roles and machines never name them, so they stay out of the table `hum help --json` prints.
99
+ */
100
+ export const addServiceCommands = (root: Command, io: Io, done: (code: number) => void): void => {
101
+ withWorkOptions(root.command("work").description("Run the worker on this machine until it is stopped or an update arrives; exits 75 for an update."))
102
+ .action(async (flags: WorkFlags) => {
103
+ const abort = new AbortController();
104
+
105
+ onStop(() => abort.abort());
106
+
107
+ const worker = await openFor(io.cwd, flags, "mac");
108
+ const ended = await worker.serve(abort.signal);
109
+
110
+ io.stderr(`hum work: stopped, ${ended.reason}\n`);
111
+ done(ended.reason === "stopped" ? EXIT_OK : EXIT_UPDATED);
112
+ });
113
+
114
+ root
115
+ .command("serve")
116
+ .description("The service unit's start script: run `hum work` with the arguments after `--`, start it again when it exits, and stop after too many crashes.")
117
+ .argument("[work-args...]", "options of `hum work`, after `--`")
118
+ .action(async (workArgs: string[]) => {
119
+ const abort = new AbortController();
120
+ const settings = serviceSettings(io.cwd);
121
+
122
+ onStop(() => abort.abort());
123
+
124
+ const ended = await supervise({
125
+ state: openState(await defaultStateDir(io.cwd)),
126
+ spawn: () => spawnWorker(io.cwd, workArgs),
127
+ now: Date.now,
128
+ intervalMs: settings.tickIntervalSeconds * SECOND_MS,
129
+ workerDownTicks: settings.workerDownTicks,
130
+ maxCrashes: settings.maxCrashes,
131
+ crashWindowMs: settings.crashWindowSeconds * SECOND_MS,
132
+ backoffMs: settings.restartBackoff.firstSeconds * SECOND_MS,
133
+ maxBackoffMs: settings.restartBackoff.maxSeconds * SECOND_MS,
134
+ stop: abort.signal,
135
+ });
136
+
137
+ io.stderr(`hum serve: ${ended}\n`);
138
+ done(EXIT_STAY_DOWN);
139
+ });
140
+
141
+ withWorkOptions(root.command("wake").description("One CI wake: tick until nothing more starts, record the tick when --event is schedule, and show the cards."))
142
+ .option("--event <name>", "the GitHub event that started this job")
143
+ .action(async (flags: WorkFlags & { event?: string }) => {
144
+ const worker = await openFor(io.cwd, flags, "ci");
145
+
146
+ await wakeUntilQuiet(worker);
147
+
148
+ if (flags.event === SCHEDULE_EVENT) await recordCiTick(io.cwd, "origin", Date.now(), worker.config.hum.commitIdentity, commandTimeoutMs(worker.config.hum));
149
+
150
+ const status = readStatus(join(await defaultStateDir(io.cwd), "status.json"));
151
+ const cards = status.ok ? status.status.cards : [];
152
+
153
+ await reportCards(cards);
154
+ done(cards.length > 0 ? EXIT_CARDS_SHOWN : EXIT_OK);
155
+ });
156
+ };
@@ -0,0 +1,141 @@
1
+ import { join } from "node:path";
2
+ import type { Command } from "commander";
3
+ import { x } from "tinyexec";
4
+ import { z } from "zod";
5
+ import type { Item } from "../adapter-api.ts";
6
+ import { gitIn, readGitIdentity } from "../adapters/git.ts";
7
+ import { listHopeSkills } from "../config/load.ts";
8
+ import { HumConfig } from "../config/schema.ts";
9
+ import { CommandTimedOut, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
+ import { readSettings } from "../config/settings.ts";
11
+ import { kindCoverage, proposeSetup } from "../setup/propose.ts";
12
+ import { proveSetup, type Step } from "../setup/prove.ts";
13
+ import { scanRepo } from "../setup/scan.ts";
14
+ import { shippedConfig } from "../setup/shipped.ts";
15
+ import { waitsOf } from "../setup/waits.ts";
16
+ import { readAnswers, writeSetup } from "../setup/write.ts";
17
+ import type { Io } from "./ops.ts";
18
+ import { hopeRoot } from "./service.ts";
19
+
20
+ const EXIT_OK = 0;
21
+ const EXIT_FAILED = 1;
22
+
23
+ const DEFAULT_BASE = "main";
24
+
25
+ const GH_LIST_LIMIT = "200";
26
+
27
+ const GhIssues = z.array(z.object({ body: z.string().default(""), labels: z.array(z.object({ name: z.string() })).default([]) }));
28
+
29
+ const GhLabels = z.array(z.object({ name: z.string() }));
30
+
31
+ const EVAL_SCRIPT = join(import.meta.dir, "..", "..", "scripts", "eval.ts");
32
+
33
+ type GithubFacts = {
34
+ readonly items: readonly Pick<Item, "body" | "labels">[];
35
+ readonly labels: readonly string[];
36
+ /** Whether the repo lets a workflow open pull requests; off, a CI run cannot open one at all. */
37
+ readonly workflowsMayOpenPullRequests: boolean;
38
+ };
39
+
40
+ const WorkflowPermissions = z.object({ can_approve_pull_request_reviews: z.boolean() });
41
+
42
+ /** Setup reads before any `hum.json` is written, so its commands run on the shipped time limit. */
43
+ const setupGit = (repo: string) => gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
44
+
45
+ /** `gh` in the repo, or nothing where `gh` is not installed; a `gh` that outruns its limit is an error. */
46
+ const gh = async (repo: string, args: readonly string[]) => {
47
+ try {
48
+ return await exec("gh", args, { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS, nodeOptions: { cwd: repo } });
49
+ } catch (error) {
50
+ if (error instanceof CommandTimedOut) throw error;
51
+
52
+ return undefined;
53
+ }
54
+ };
55
+
56
+ /** The repo's open issues and its label names, from `gh`. Without `gh` or a GitHub remote there are none, and the scan prints no coverage. */
57
+ const githubFacts = async (repo: string): Promise<GithubFacts | undefined> => {
58
+ const issues = await gh(repo, ["issue", "list", "--state", "open", "--limit", GH_LIST_LIMIT, "--json", "body,labels"]);
59
+ const labels = await gh(repo, ["label", "list", "--limit", GH_LIST_LIMIT, "--json", "name"]);
60
+
61
+ const permissions = await gh(repo, ["api", "repos/{owner}/{repo}/actions/permissions/workflow"]);
62
+
63
+ if (issues?.exitCode !== 0 || labels?.exitCode !== 0 || permissions?.exitCode !== 0) return undefined;
64
+
65
+ return {
66
+ items: GhIssues.parse(JSON.parse(issues.stdout)).map(({ body, labels: on }) => ({ body, labels: on.map(({ name }) => name) })),
67
+ labels: GhLabels.parse(JSON.parse(labels.stdout)).map(({ name }) => name),
68
+ workflowsMayOpenPullRequests: WorkflowPermissions.parse(JSON.parse(permissions.stdout)).can_approve_pull_request_reviews,
69
+ };
70
+ };
71
+
72
+ const printStep = ({ name, status, detail, ms }: Step): string => `${status.padEnd(7)} ${name} (${ms} ms): ${detail}`;
73
+
74
+ const ModelSettings = z.looseObject({ models: HumConfig.shape.models, decisionModel: HumConfig.shape.decisionModel });
75
+
76
+ /** The distinct model ids the owner's tiers and cheap call run on. */
77
+ const modelsOf = (repo: string): string[] => {
78
+ const { models, decisionModel } = readSettings(repo, ModelSettings);
79
+
80
+ return [...new Set([...Object.values(models), decisionModel])];
81
+ };
82
+
83
+ /** `hum setup scan | write | prove | measure`: the facts and writes behind the /hum skill. */
84
+ export const addSetupCommands = (root: Command, io: Io, done: (code: number) => void): void => {
85
+ const setup = root.command("setup").description("What the /hum skill calls: read the repo, write .hum/, prove it, measure the owner's models.");
86
+
87
+ setup
88
+ .command("scan")
89
+ .description("Read the repo and print what setup proposes: checks, paths, data and secrets globs, kind labels, the slot recipe, and a timeout question per wait.")
90
+ .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
91
+ .action(async ({ base }: { base: string }) => {
92
+ const shipped = shippedConfig();
93
+ const scan = await scanRepo(io.cwd, base);
94
+ const facts = await githubFacts(io.cwd);
95
+ const proposal = proposeSetup(scan, shipped.hum, facts?.labels);
96
+ const { tracked, folders, ...shown } = scan;
97
+ const coverage = facts && kindCoverage(facts.items, shipped.hum.kinds, proposal.kindLabels);
98
+ const gitIdentity = await readGitIdentity(setupGit(io.cwd));
99
+
100
+ io.stdout(`${JSON.stringify({ scan: { ...shown, trackedFiles: tracked.length, folders: folders.map(({ folder, changes }) => ({ folder, changes })) }, proposal, waits: waitsOf(shipped.kinds), coverage: coverage ?? null, workflowsMayOpenPullRequests: facts?.workflowsMayOpenPullRequests ?? null, gitIdentity }, null, "\t")}\n`);
101
+ });
102
+
103
+ setup
104
+ .command("write")
105
+ .description("Write .hum/ and the service files from the answers file, or write nothing and say why.")
106
+ .requiredOption("--answers <file>", 'JSON: { "hum": {settings}, "waitHours": { "kind/state": hours }, "schemaVersion": 1 }')
107
+ .option("--home <folder>", "where the service unit goes; default the user's home")
108
+ .action(async ({ answers, home }: { answers: string; home?: string }) => {
109
+ const result = writeSetup(io.cwd, readAnswers(answers), { hopeSkills: listHopeSkills(await hopeRoot()), home, gitIdentity: await readGitIdentity(setupGit(io.cwd)) });
110
+
111
+ io.stdout(`${JSON.stringify(result.ok ? { written: result.written } : { refused: result.refusal.message }, null, "\t")}\n`);
112
+ done(result.ok ? EXIT_OK : EXIT_FAILED);
113
+ });
114
+
115
+ setup
116
+ .command("prove")
117
+ .description("Prove the written setup: config checks, each check alone, the contract suite, the pinned engine, one slot, and with --item one item end to end.")
118
+ .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
119
+ .option("--item", "run one item through the real claude on a scratch copy; spends live calls")
120
+ .action(async ({ base, item }: { base: string; item?: true }) => {
121
+ const steps = await proveSetup(io.cwd, { hopeSkills: listHopeSkills(await hopeRoot()), base, item: item === true });
122
+
123
+ io.stdout(`${steps.map(printStep).join("\n")}\n`);
124
+ done(steps.some(({ status }) => status === "failed") ? EXIT_FAILED : EXIT_OK);
125
+ });
126
+
127
+ setup
128
+ .command("measure")
129
+ .description("Measure the owner's models on every labelled set and record the pooled rates in .hum/hum.json.")
130
+ .option("--runs <n>", "runs pooled per boundary", "3")
131
+ .option("--model <id...>", "model ids to measure; default every model the tiers and the cheap call use")
132
+ .action(async ({ runs, model }: { runs: string; model?: string[] }) => {
133
+ for (const id of model ?? modelsOf(io.cwd)) {
134
+ const ran = await x(process.execPath, [EVAL_SCRIPT, "--model", id, "--runs", runs, "--write", join(io.cwd, ".hum")], { throwOnError: false, nodeOptions: { stdio: "inherit" } });
135
+
136
+ if (ran.exitCode !== 0) return done(EXIT_FAILED);
137
+ }
138
+
139
+ done(EXIT_OK);
140
+ });
141
+ };
@@ -0,0 +1,127 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { lock } from "proper-lockfile";
4
+ import { z } from "zod";
5
+ import type { Watch } from "../adapter-api.ts";
6
+ import { atomicWrite, hasCode, orMissing, readJson } from "../state/fs.ts";
7
+
8
+ const Outcome = z.discriminatedUnion("kind", [
9
+ z.strictObject({ kind: z.literal("read"), changed: z.boolean() }),
10
+ z.strictObject({ kind: z.literal("failed"), cause: z.string().min(1) }),
11
+ ]);
12
+
13
+ /** The last read of what changed, kept for every `hum watch` in the repo. The token is the last one a read returned. */
14
+ export const SavedWatch = z.strictObject({
15
+ token: z.string().optional(),
16
+ checkedAt: z.number().int().nonnegative(),
17
+ outcome: Outcome,
18
+ });
19
+
20
+ export type SavedWatch = z.infer<typeof SavedWatch>;
21
+
22
+ export type SharedWatchOptions = {
23
+ readonly stateDir: string;
24
+ readonly now: () => number;
25
+ /** How long one read serves every caller. */
26
+ readonly cacheMs: number;
27
+ /** How long the reader's lock stands before another caller may take it over. */
28
+ readonly lockMs: number;
29
+ /** The one read of the work source, from the token the last read returned. */
30
+ readonly read: (since: string | undefined) => Promise<Watch>;
31
+ /** Called once per read that saw a change, so the worker reads now instead of on its next tick. */
32
+ readonly changed: () => void;
33
+ };
34
+
35
+ const cachePath = (stateDir: string): string => join(stateDir, "watch.json");
36
+
37
+ const lockPath = (stateDir: string): string => join(stateDir, "watch.lock");
38
+
39
+ export const loadSavedWatch = (stateDir: string): SavedWatch | undefined =>
40
+ orMissing(() => SavedWatch.parse(readJson(cachePath(stateDir))), undefined);
41
+
42
+ const save = (stateDir: string, saved: SavedWatch): void =>
43
+ atomicWrite(cachePath(stateDir), `${JSON.stringify(saved)}\n`);
44
+
45
+ /** The saved read while it still serves callers; none once it is older than `cacheMs`. */
46
+ const servable = (
47
+ saved: SavedWatch | undefined,
48
+ now: number,
49
+ cacheMs: number,
50
+ ): SavedWatch | undefined => saved !== undefined && now - saved.checkedAt < cacheMs ? saved : undefined;
51
+
52
+ /** What a saved read answers a caller: the same change, or the same failure. */
53
+ const replay = (saved: SavedWatch): Watch => {
54
+ if (saved.outcome.kind === "failed") throw new Error(saved.outcome.cause);
55
+
56
+ return { token: saved.token ?? "", changed: saved.outcome.changed };
57
+ };
58
+
59
+ /** proper-lockfile refuses a staleness under two seconds. */
60
+ const STALE_FLOOR_MS = 2000;
61
+
62
+ /**
63
+ * One read of what changed serves every caller in the repo for `cacheMs`. Only the caller holding the lock reads;
64
+ * the others answer from the saved read. A lock left by a reader that died stands for `lockMs`, then goes.
65
+ */
66
+ export async function sharedWatch(o: SharedWatchOptions): Promise<Watch> {
67
+ const before = loadSavedWatch(o.stateDir);
68
+
69
+ const served = servable(before, o.now(), o.cacheMs);
70
+
71
+ if (served !== undefined) return replay(served);
72
+
73
+ mkdirSync(o.stateDir, { recursive: true });
74
+
75
+ const release = await lock(o.stateDir, {
76
+ lockfilePath: lockPath(o.stateDir),
77
+ realpath: false,
78
+ retries: 0,
79
+ stale: Math.max(o.lockMs, STALE_FLOOR_MS),
80
+ }).catch((error: Error) => {
81
+ if (hasCode(error, "ELOCKED")) return undefined;
82
+
83
+ throw error;
84
+ });
85
+
86
+ if (release === undefined) {
87
+ if (before === undefined)
88
+ throw new Error(
89
+ "another hum watch is making the first read; ask again shortly",
90
+ );
91
+
92
+ return replay(before);
93
+ }
94
+
95
+ try {
96
+ const saved = loadSavedWatch(o.stateDir);
97
+
98
+ const servedMeanwhile = servable(saved, o.now(), o.cacheMs);
99
+
100
+ if (servedMeanwhile !== undefined) return replay(servedMeanwhile);
101
+
102
+ const read = await o.read(saved?.token).catch((error: Error) => {
103
+ save(o.stateDir, {
104
+ token: saved?.token,
105
+ checkedAt: o.now(),
106
+ outcome: {
107
+ kind: "failed",
108
+ cause: error.message,
109
+ },
110
+ });
111
+
112
+ throw error;
113
+ });
114
+
115
+ save(o.stateDir, {
116
+ token: read.token,
117
+ checkedAt: o.now(),
118
+ outcome: { kind: "read", changed: read.changed },
119
+ });
120
+
121
+ if (read.changed) o.changed();
122
+
123
+ return read;
124
+ } finally {
125
+ await release();
126
+ }
127
+ }