@moo.md/hum 0.2.0 → 0.4.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 (70) hide show
  1. package/defaults/hum.json +14 -2
  2. package/defaults/roles/build.md +1 -1
  3. package/defaults/roles/fix.md +1 -1
  4. package/npm-shrinkwrap.json +3297 -0
  5. package/package.json +6 -2
  6. package/release.json +3 -0
  7. package/schema/hum.schema.json +251 -10
  8. package/scripts/eval.ts +21 -5
  9. package/src/adapter-api.ts +3 -1
  10. package/src/adapters/claude-bg.ts +2 -2
  11. package/src/adapters/claude-p.ts +44 -18
  12. package/src/adapters/contract.ts +12 -0
  13. package/src/adapters/fake.ts +5 -0
  14. package/src/adapters/git.ts +61 -9
  15. package/src/adapters/github-client.ts +15 -0
  16. package/src/adapters/github-commits.ts +84 -0
  17. package/src/adapters/github.ts +36 -4
  18. package/src/adapters/guard.ts +1 -0
  19. package/src/adapters/item-file.ts +1 -1
  20. package/src/adapters/markdown.ts +10 -1
  21. package/src/adapters/pull-requests.ts +8 -8
  22. package/src/adapters/registry.ts +5 -7
  23. package/src/adapters/roundup.ts +3 -0
  24. package/src/bytes.ts +1 -0
  25. package/src/cli/service.ts +176 -29
  26. package/src/cli/setup.ts +16 -7
  27. package/src/config/checks.ts +27 -43
  28. package/src/config/load.ts +2 -3
  29. package/src/config/machine.ts +29 -0
  30. package/src/config/migrate.ts +5 -2
  31. package/src/config/refusal.ts +9 -4
  32. package/src/config/schema.ts +86 -8
  33. package/src/config/wake-job.ts +78 -0
  34. package/src/decide/risk.ts +2 -2
  35. package/src/exec.ts +10 -0
  36. package/src/index.ts +1 -1
  37. package/src/loop/records.ts +8 -1
  38. package/src/measure/rate.ts +14 -0
  39. package/src/publish/bundle.ts +128 -0
  40. package/src/publish/handoff.ts +107 -0
  41. package/src/publish/handover.ts +182 -0
  42. package/src/publish/intents.ts +61 -0
  43. package/src/publish/publisher.ts +259 -0
  44. package/src/publish/wake.ts +78 -0
  45. package/src/service/ci-state.ts +99 -0
  46. package/src/service/plugins.ts +137 -0
  47. package/src/service/wake.ts +3 -1
  48. package/src/service/workflows.ts +261 -50
  49. package/src/setup/propose.ts +87 -3
  50. package/src/setup/prove.ts +3 -3
  51. package/src/setup/scan.ts +61 -5
  52. package/src/setup/tables.ts +18 -0
  53. package/src/setup/write.ts +52 -19
  54. package/src/state/items.ts +17 -8
  55. package/src/state/open.ts +20 -6
  56. package/src/state/records.ts +7 -0
  57. package/src/state/runs.ts +5 -0
  58. package/src/state/saved.ts +17 -2
  59. package/src/worker/base-check.ts +41 -13
  60. package/src/worker/checks.ts +3 -2
  61. package/src/worker/evidence.ts +72 -0
  62. package/src/worker/kind.ts +4 -7
  63. package/src/worker/land.ts +173 -81
  64. package/src/worker/merged.ts +20 -8
  65. package/src/worker/open.ts +33 -17
  66. package/src/worker/questions.ts +16 -8
  67. package/src/worker/signed-push.ts +167 -0
  68. package/src/worker/thin-path.ts +245 -133
  69. package/src/worker/worker.ts +50 -9
  70. package/surface.json +610 -76
@@ -1,23 +1,38 @@
1
+ import * as core from "@actions/core";
1
2
  import { randomUUID } from "node:crypto";
2
- import { hostname } from "node:os";
3
+ import { mkdtempSync } from "node:fs";
4
+ import { hostname, tmpdir } from "node:os";
3
5
  import { join } from "node:path";
4
6
  import type { Command } from "commander";
5
7
  import { x } from "tinyexec";
6
8
  import { z } from "zod";
7
- import { listHopeSkills } from "../config/load.ts";
9
+ import { listPluginSkills } from "../config/load.ts";
8
10
  import { HumConfig } from "../config/schema.ts";
9
11
  import { readSettings } from "../config/settings.ts";
10
12
  import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
13
+ import { CI_STATE_REF, CiStateRaced, restoreCiState, saveCiState } from "../service/ci-state.ts";
11
14
  import { readCiTick, recordCiTick } from "../service/ci-tick.ts";
12
15
  import { EXIT_UPDATED, supervise } from "../service/supervise.ts";
16
+ import { installPlugins } from "../service/plugins.ts";
13
17
  import { reportCards, wakeUntilQuiet } from "../service/wake.ts";
14
- import { defaultStateDir, openState } from "../state/open.ts";
18
+ import { defaultStateDir, openState, STATUS_FILE } from "../state/open.ts";
15
19
  import { SECOND_MS } from "../time.ts";
16
20
  import { readStatus } from "../status/file.ts";
17
- import { npmLatest, openWorker } from "../worker/open.ts";
21
+ import { npmLatest, type OpenWorkerOptions, workerOptions } from "../worker/open.ts";
22
+ import { Worker, type WorkerOptions } from "../worker/worker.ts";
23
+ import { DEFAULT_BASE, publisherOf } from "../worker/thin-path.ts";
24
+ import { tallyOf } from "../worker/tally.ts";
25
+ import { Gathered, inboxIntegrations, readInbox, readOutbox, workRemote, writeBaseCheck, writeInbox, writeOutboxState, writePass } from "../publish/handover.ts";
26
+ import { checkMergesAt } from "../worker/base-check.ts";
27
+ import { publishWake } from "../publish/wake.ts";
28
+ import { configuredModelCall } from "../adapters/model-call.ts";
29
+ import { type Git, gitIn } from "../adapters/git.ts";
30
+ import { APP_TOKEN_MINUTES, WAKE_ENV } from "../config/wake-job.ts";
31
+ import { MINUTE_MS } from "../time.ts";
18
32
  import type { Io } from "./ops.ts";
19
- import { Holder } from "../adapter-api.ts";
33
+ import { Holder, type Item, ItemId } from "../adapter-api.ts";
20
34
  import { parseArgument } from "../adapters/argument.ts";
35
+ import { MEGABYTE } from "../bytes.ts";
21
36
 
22
37
  const EXIT_OK = 0;
23
38
 
@@ -26,6 +41,8 @@ const EXIT_STAY_DOWN = EXIT_OK;
26
41
 
27
42
  const EXIT_CARDS_SHOWN = 1;
28
43
 
44
+ const EXIT_FAILED = 1;
45
+
29
46
  const SCHEDULE_EVENT = "schedule";
30
47
 
31
48
  type WorkFlags = { holder?: string; base?: string };
@@ -36,18 +53,23 @@ const withWorkOptions = (cmd: Command): Command =>
36
53
  .option("--holder <name>", "the name this worker claims items by; default <where>@<host>")
37
54
  .option("--base <branch>", "the branch items merge into; default main");
38
55
 
39
- const PluginList = z.array(z.looseObject({ id: z.string(), installPath: z.string() }));
56
+ const PluginList = z.array(z.looseObject({ id: z.string(), installPath: z.string(), enabled: z.boolean().default(true) }));
40
57
 
41
- /** The folder of the installed hope plugin: `HUM_HOPE_ROOT`, else the path `claude plugin list` gives. */
42
- export const hopeRoot = async (): Promise<string> => {
43
- if (process.env.HUM_HOPE_ROOT) return process.env.HUM_HOPE_ROOT;
58
+ const HOPE = "hope";
59
+
60
+ /**
61
+ * The skills of every enabled plugin, as a role names them (`sound:prime`), read from the folders `claude plugin list`
62
+ * gives. `HUM_HOPE_ROOT` names hope's folder instead, and then hope's skills are all there is. hope must be there.
63
+ */
64
+ export const installedSkills = async (): Promise<ReadonlySet<string>> => {
65
+ if (process.env.HUM_HOPE_ROOT) return new Set(listPluginSkills(HOPE, process.env.HUM_HOPE_ROOT));
44
66
 
45
67
  const listed = await exec("claude", ["plugin", "list", "--json"], { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
46
- const hope = listed.exitCode === 0 ? PluginList.parse(JSON.parse(listed.stdout)).find((plugin) => plugin.id.startsWith("hope@")) : undefined;
68
+ const plugins = listed.exitCode === 0 ? PluginList.parse(JSON.parse(listed.stdout)).filter(({ enabled }) => enabled).map(({ id, installPath }) => ({ name: id.split("@")[0] ?? id, installPath })) : [];
47
69
 
48
- 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");
70
+ if (!plugins.some(({ name }) => name === 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");
49
71
 
50
- return hope.installPath;
72
+ return new Set(plugins.flatMap(({ name, installPath }) => listPluginSkills(name, installPath)));
51
73
  };
52
74
 
53
75
  const ServiceSettings = z.looseObject({
@@ -72,19 +94,20 @@ const serviceSettings = (repo: string): z.infer<typeof ServiceSettings> => {
72
94
  };
73
95
 
74
96
  /** The Mac reads the npm version and when the scheduled workflow last ran; a CI job is that workflow. */
75
- const openFor = async ({ cwd: repo, env }: Io, flags: WorkFlags, where: "mac" | "ci") => {
97
+ const optionsFor = async ({ cwd: repo, env }: Io, flags: WorkFlags, where: "mac" | "ci", extra: Partial<OpenWorkerOptions> = {}): Promise<WorkerOptions> => {
76
98
  const timeoutMs = commandTimeoutMs(serviceSettings(repo));
77
99
 
78
- return openWorker(repo, {
100
+ return workerOptions(repo, {
79
101
  now: Date.now,
80
102
  env,
81
103
  newSessionId: randomUUID,
82
- hopeSkills: listHopeSkills(await hopeRoot()),
104
+ installedSkills: extra.judgmentsOnly ? undefined : await installedSkills(),
83
105
  holder: parseArgument(Holder, flags.holder ?? `${where}@${hostname()}`),
84
106
  base: flags.base,
85
107
  where,
86
108
  latestVersion: where === "mac" ? npmLatest : undefined,
87
109
  ciTick: where === "mac" ? () => readCiTick({ repo, remote: "origin", timeoutMs }) : undefined,
110
+ ...extra,
88
111
  });
89
112
  };
90
113
 
@@ -100,8 +123,9 @@ const spawnWorker = (cwd: string, workArgs: readonly string[]) => {
100
123
  };
101
124
 
102
125
  /**
103
- * `hum work`, `hum serve` and `hum wake`: the processes a service unit and a CI workflow start. They are not ops:
104
- * roles and machines never name them, so they stay out of the table `hum help --json` prints.
126
+ * `hum work`, `hum serve` and `hum wake`'s jobs: the processes a service unit and a CI workflow start. They are not ops:
127
+ * roles and machines never name them, so they stay out of the table `hum help --json` prints. A CI job's git dir dies
128
+ * with it, so gather brings back the state the last wake saved first and saves it for publish, which saves it again.
105
129
  */
106
130
  export const addServiceCommands = (root: Command, io: Io, done: (code: number) => void): void => {
107
131
  withWorkOptions(root.command("work").description("Run the worker on this machine until it is stopped or an update arrives; exits 75 for an update."))
@@ -110,7 +134,7 @@ export const addServiceCommands = (root: Command, io: Io, done: (code: number) =
110
134
 
111
135
  onStop(() => abort.abort());
112
136
 
113
- const worker = await openFor(io, flags, "mac");
137
+ const worker = new Worker(await optionsFor(io, flags, "mac"));
114
138
  const ended = await worker.serve(abort.signal);
115
139
 
116
140
  io.stderr(`hum work: stopped, ${ended.reason}\n`);
@@ -144,19 +168,142 @@ export const addServiceCommands = (root: Command, io: Io, done: (code: number) =
144
168
  done(EXIT_STAY_DOWN);
145
169
  });
146
170
 
147
- withWorkOptions(root.command("wake").description("One CI wake: tick until nothing more starts, record the tick when --event is schedule, and show the cards."))
148
- .option("--event <name>", "the GitHub event that started this job")
149
- .action(async (flags: WorkFlags & { event?: string }) => {
150
- const worker = await openFor(io, flags, "ci");
171
+ root
172
+ .command("plugins")
173
+ .description("Install hope and the repo's own Claude Code plugins for a CI wake: moo.md at the commit this engine shipped with, then each marketplace and enabled plugin .claude/settings.json names.")
174
+ .action(async () => {
175
+ try {
176
+ for (const args of await installPlugins({ repo: io.cwd, env: io.env })) io.stdout(`claude ${args.join(" ")}\n`);
151
177
 
152
- await wakeUntilQuiet(worker);
178
+ done(EXIT_OK);
179
+ } catch (error) {
180
+ io.stderr(`hum plugins: ${error instanceof Error ? error.message : String(error)}\n`);
181
+ done(EXIT_FAILED);
182
+ }
183
+ });
153
184
 
154
- if (flags.event === SCHEDULE_EVENT) await recordCiTick({ repo: io.cwd, remote: "origin", at: Date.now(), identity: worker.config.hum.commitIdentity, timeoutMs: commandTimeoutMs(worker.config.hum) });
185
+ const wake = root.command("wake").description("One CI wake, as three jobs: gather claims and settles with GitHub's token, work runs with none, and publish checks and applies what work made.");
155
186
 
156
- const status = readStatus(join(await defaultStateDir(io.cwd), "status.json"));
157
- const cards = status.ok ? status.status.cards : [];
187
+ withWorkOptions(wake.command("gather").description("Bring back the state the last wake saved, claim each item and settle its answers and kind, save the state, and write the inbox the work job reads; sets the job output `gathered` for publish."))
188
+ .requiredOption("--inbox <folder>", "where to write the inbox")
189
+ .action((flags: WorkFlags & { inbox: string }) => wakeJob(io, done, async () => {
190
+ const dir = await defaultStateDir(io.cwd);
191
+ const timeoutMs = commandTimeoutMs(serviceSettings(io.cwd));
192
+ const where = { repo: io.cwd, remote: "origin", dir, timeoutMs };
193
+ const read = await restoreCiState(where);
194
+ const claimed = new Map<string, Item>();
195
+ const options = await optionsFor(io, flags, "ci", { ciJob: { kind: "gather", gathered: claimed }, judgmentsOnly: true });
196
+ const worker = new Worker(options);
158
197
 
159
- await reportCards(cards, { hasStepSummary: Boolean(process.env.GITHUB_STEP_SUMMARY) });
160
- done(cards.length > 0 ? EXIT_CARDS_SHOWN : EXIT_OK);
161
- });
198
+ for (let before = -1; claimed.size > before; ) {
199
+ before = claimed.size;
200
+ await worker.tick();
201
+ await worker.idle();
202
+ }
203
+
204
+ const base = options.base ?? DEFAULT_BASE;
205
+ const saved = await saveCiState({ ...where, ...read, identity: options.config.hum.commitIdentity, at: Date.now() });
206
+ const heads = await remoteHeads(gitIn(io.cwd, { timeoutMs }), options.config.hum.runBranchPrefix);
207
+ const baseSha = (await remoteHeads(gitIn(io.cwd, { timeoutMs }), base)).get(base);
208
+
209
+ if (baseSha === undefined) throw new Error(`origin has no branch ${base}`);
210
+
211
+ heads.delete(base);
212
+
213
+ const gathered: Gathered = { holder: options.holder, base, baseSha, heads: Object.fromEntries(heads), claimed: [...claimed.keys()].map((id) => ItemId.parse(id)), stateRead: saved.read };
214
+
215
+ writeInbox(flags.inbox, { gathered, items: [...claimed.values()] }, dir);
216
+ core.setOutput("gathered", JSON.stringify(gathered));
217
+
218
+ return dir;
219
+ }));
220
+
221
+ wake
222
+ .command("work")
223
+ .description("Run each item the inbox holds with no GitHub token: runs clone the base and hum branches gather saw, and each pass leaves what it asks publish to do in the outbox, with hum's state.")
224
+ .requiredOption("--inbox <folder>", "the inbox gather wrote")
225
+ .requiredOption("--outbox <folder>", "where to write the outbox")
226
+ .action((flags: { inbox: string; outbox: string }) => wakeJob(io, done, async () => {
227
+ const dir = await defaultStateDir(io.cwd);
228
+ const timeoutMs = commandTimeoutMs(serviceSettings(io.cwd));
229
+ const inbox = readInbox(flags.inbox, dir);
230
+ const { gathered } = inbox;
231
+ const remote = await workRemote({ checkout: io.cwd, gathered, folder: mkdtempSync(join(io.env.RUNNER_TEMP ?? tmpdir(), "hum-remote-")), timeoutMs });
232
+
233
+ const options = await optionsFor(io, { holder: gathered.holder, base: gathered.base }, "ci", {
234
+ remote,
235
+ integrations: inboxIntegrations(inbox, Date.now),
236
+ ciJob: { kind: "work", publish: async (pass, worked) => void writePass(flags.outbox, { ...pass, result: worked }) },
237
+ });
238
+
239
+ const baseCheck = await checkMergesAt({ ...options, git: gitIn(io.cwd, { timeoutMs }) }, gathered.baseSha);
240
+
241
+ if (baseCheck !== undefined) writeBaseCheck(flags.outbox, baseCheck);
242
+
243
+ await wakeUntilQuiet(new Worker(options));
244
+ writeOutboxState(flags.outbox, dir);
245
+
246
+ return dir;
247
+ }));
248
+
249
+ wake
250
+ .command("publish")
251
+ .description(`Check and apply the work job's outbox with GitHub's token, from what gather settled in ${WAKE_ENV.gathered}, save the state, and record the tick when --event is schedule.`)
252
+ .requiredOption("--outbox <folder>", "the outbox the work job wrote")
253
+ .option("--event <name>", "the GitHub event that started this wake")
254
+ .action((flags: { outbox: string; event?: string }) => wakeJob(io, done, async () => {
255
+ const started = Date.now();
256
+ const gathered = Gathered.parse(JSON.parse(io.env[WAKE_ENV.gathered] ?? "null"));
257
+ const dir = await defaultStateDir(io.cwd);
258
+ const timeoutMs = commandTimeoutMs(serviceSettings(io.cwd));
259
+ const where = { repo: io.cwd, remote: "origin", dir, timeoutMs };
260
+ const read = await restoreCiState(where);
261
+
262
+ if (read.read !== gathered.stateRead) throw new CiStateRaced(`hum's state at ${CI_STATE_REF} is not the one gather saved, so another wake ran since; this wake publishes nothing`);
263
+
264
+ const options = await optionsFor(io, { holder: gathered.holder, base: gathered.base }, "ci", { judgmentsOnly: true });
265
+ const { hum } = options.config;
266
+ const outbox = readOutbox(flags.outbox, { maxBytes: hum.ciOutboxMaxMegabytes * MEGABYTE, claimed: new Set(gathered.claimed) });
267
+ const judge = options.judge ?? configuredModelCall(options.runner, hum, (item, tokens) => tallyOf(options.state, item).spend(tokens));
268
+ const publisher = publisherOf({ ...options, workSource: options.adapters.workSource, questions: options.adapters.questions }, judge, started + (APP_TOKEN_MINUTES - hum.ciMergeMarginMinutes) * MINUTE_MS);
269
+
270
+ let saved = read;
271
+
272
+ const save = async () => {
273
+ saved = await saveCiState({ ...where, ...saved, identity: hum.commitIdentity, at: Date.now() });
274
+ };
275
+
276
+ await publishWake({ publisher, gathered, outbox, work: openState(outbox.stateDir, { now: Date.now }), save });
277
+
278
+ if (flags.event === SCHEDULE_EVENT) await recordCiTick({ repo: io.cwd, remote: "origin", at: Date.now(), identity: hum.commitIdentity, timeoutMs });
279
+
280
+ return dir;
281
+ }));
282
+ };
283
+
284
+ /** Runs one job of a wake, then shows the cards its state holds; the job exits 1 when it shows any or fails. */
285
+ const wakeJob = async (io: Io, done: (code: number) => void, job: () => Promise<string>): Promise<void> => {
286
+ try {
287
+ const status = readStatus(join(await job(), STATUS_FILE));
288
+ const cards = status.ok ? status.status.cards : [];
289
+
290
+ await reportCards(cards, { hasStepSummary: Boolean(process.env.GITHUB_STEP_SUMMARY) });
291
+ done(cards.length > 0 ? EXIT_CARDS_SHOWN : EXIT_OK);
292
+ } catch (error) {
293
+ io.stderr(`hum wake: ${error instanceof Error ? error.message : String(error)}\n`);
294
+ done(EXIT_FAILED);
295
+ }
162
296
  };
297
+
298
+ /** Each branch on origin under `prefix`, or named `prefix`, at its head. */
299
+ const remoteHeads = async (git: Git, prefix: string): Promise<Map<string, string>> =>
300
+ new Map(
301
+ (await git.raw(["ls-remote", "--heads", "origin", `refs/heads/${prefix}*`]))
302
+ .split("\n")
303
+ .filter(Boolean)
304
+ .map((line) => {
305
+ const [sha = "", ref = ""] = line.split("\t");
306
+
307
+ return [ref.slice("refs/heads/".length), sha] as const;
308
+ }),
309
+ );
package/src/cli/setup.ts CHANGED
@@ -5,7 +5,6 @@ import { x } from "tinyexec";
5
5
  import { z } from "zod";
6
6
  import type { Item } from "../adapter-api.ts";
7
7
  import { gitIn, readGitIdentity } from "../adapters/git.ts";
8
- import { listHopeSkills } from "../config/load.ts";
9
8
  import { HumConfig } from "../config/schema.ts";
10
9
  import { CommandTimedOut, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
11
10
  import { readSettings } from "../config/settings.ts";
@@ -16,7 +15,7 @@ import { shippedConfig } from "../setup/shipped.ts";
16
15
  import { waitsOf } from "../setup/waits.ts";
17
16
  import { readAnswers, writeSetup } from "../setup/write.ts";
18
17
  import type { Io } from "./ops.ts";
19
- import { hopeRoot } from "./service.ts";
18
+ import { installedSkills } from "./service.ts";
20
19
 
21
20
  const EXIT_OK = 0;
22
21
  const EXIT_FAILED = 1;
@@ -38,6 +37,15 @@ type GithubFacts = {
38
37
  readonly workflowsMayOpenPullRequests: boolean;
39
38
  };
40
39
 
40
+ const Visibility = z.object({ visibility: z.string() });
41
+
42
+ /** Whether anyone may read and comment on the repo; undefined without `gh` or a GitHub remote. */
43
+ const isPublicRepo = async (repo: string): Promise<boolean | undefined> => {
44
+ const viewed = await gh(repo, ["repo", "view", "--json", "visibility"]);
45
+
46
+ return isRead(viewed) ? Visibility.parse(JSON.parse(viewed.stdout)).visibility === "PUBLIC" : undefined;
47
+ };
48
+
41
49
  const WorkflowPermissions = z.object({ can_approve_pull_request_reviews: z.boolean() });
42
50
 
43
51
  /** Setup reads before any `hum.json` is written, so its commands run on the shipped time limit. */
@@ -97,21 +105,22 @@ export const addSetupCommands = (root: Command, io: Io, done: (code: number) =>
97
105
  const shipped = shippedConfig();
98
106
  const scan = await scanRepo(io.cwd, base);
99
107
  const facts = await githubFacts(io.cwd);
100
- const proposal = proposeSetup(scan, shipped.hum, facts?.labels);
108
+ const isPublic = await isPublicRepo(io.cwd);
109
+ const proposal = proposeSetup(scan, shipped.hum, { labels: facts?.labels, isPublic: isPublic ?? true, openIssues: facts?.items.length });
101
110
  const { tracked, folders, ...shown } = scan;
102
111
  const coverage = facts && kindCoverage(facts.items, shipped.hum.kinds, proposal.kindLabels);
103
112
  const gitIdentity = await readGitIdentity(setupGit(io.cwd));
104
113
 
105
- 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`);
114
+ 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, isPublicRepo: isPublic ?? null, gitIdentity }, null, "\t")}\n`);
106
115
  });
107
116
 
108
117
  setup
109
118
  .command("write")
110
119
  .description("Write .hum/ and the service files from the answers file, or write nothing and say why.")
111
- .requiredOption("--answers <file>", 'JSON: { "hum": {settings}, "waitHours": { "kind/state": hours }, "schemaVersion": 1 }')
120
+ .requiredOption("--answers <file>", 'JSON: { "hum": {settings}, "waitHours": { "kind/state": hours }, "schemaVersion": 2 }')
112
121
  .option("--home <folder>", "where the service unit goes; default the user's home")
113
122
  .action(async ({ answers, home }: { answers: string; home?: string }) => {
114
- const result = writeSetup(io.cwd, readAnswers(answers), { hopeSkills: listHopeSkills(await hopeRoot()), home, gitIdentity: await readGitIdentity(setupGit(io.cwd)) });
123
+ const result = writeSetup(io.cwd, readAnswers(answers), { installedSkills: await installedSkills(), home, gitIdentity: await readGitIdentity(setupGit(io.cwd)), isPublicRepo: await isPublicRepo(io.cwd) });
115
124
 
116
125
  io.stdout(`${JSON.stringify(result.ok ? { written: result.written } : { refused: result.refusal.message }, null, "\t")}\n`);
117
126
  done(result.ok ? EXIT_OK : EXIT_FAILED);
@@ -123,7 +132,7 @@ export const addSetupCommands = (root: Command, io: Io, done: (code: number) =>
123
132
  .option("--base <branch>", "the branch items merge into", DEFAULT_BASE)
124
133
  .option("--item", "run one item through the real claude on a scratch copy; spends live calls")
125
134
  .action(async ({ base, item }: { base: string; item?: true }) => {
126
- const steps = await proveSetup(io.cwd, { now: Date.now, processEnv: io.env, newSessionId: randomUUID, hopeSkills: listHopeSkills(await hopeRoot()), base, item: item === true });
135
+ const steps = await proveSetup(io.cwd, { now: Date.now, processEnv: io.env, newSessionId: randomUUID, installedSkills: await installedSkills(), base, item: item === true });
127
136
 
128
137
  io.stdout(`${steps.map(printStep).join("\n")}\n`);
129
138
  done(steps.some(({ status }) => status === "failed") ? EXIT_FAILED : EXIT_OK);
@@ -1,5 +1,5 @@
1
- import { toDirectedGraph } from "xstate/graph";
2
- import { kindMachine } from "./machine.ts";
1
+ import { APP_TOKEN_MINUTES, WAKE_OWN_ENV } from "./wake-job.ts";
2
+ import { kindMachine, nextStates, reachedFrom } from "./machine.ts";
3
3
  import type { Problem } from "./refusal.ts";
4
4
  import {
5
5
  FIXED_PARTS,
@@ -14,8 +14,8 @@ import {
14
14
  WAIT_TAG,
15
15
  } from "./schema.ts";
16
16
 
17
- /** What the checks read besides the config: hope's installed skills, by bare name (`intent`, not `hope:intent`). */
18
- export type CheckEnv = { readonly hopeSkills: ReadonlySet<string> };
17
+ /** What the checks read besides the config: the installed plugins' skills, as a role names them (`hope:intent`); absent where no role runs, so no role's skills are checked. */
18
+ export type CheckEnv = { readonly installedSkills?: ReadonlySet<string> };
19
19
 
20
20
  type Transitions = StateNodeJSON["onTimeout"];
21
21
 
@@ -36,39 +36,14 @@ const isXstateEvent = (event: string): boolean => event.startsWith("xstate.") ||
36
36
  /** Every state is reachable and reaches done or stuck; every wait has a timeout and an action. */
37
37
  const graphProblems = (kind: string, config: Kind): Problem[] => {
38
38
  const { states, initial } = config.machine;
39
- const graph = toDirectedGraph(kindMachine(config));
40
- const forward = new Map<string, string[]>();
39
+ const forward = nextStates(config);
41
40
  const backward = new Map<string, string[]>();
42
41
 
43
- for (const node of graph.children) {
44
- for (const edge of node.edges) {
45
- forward.set(edge.source.key, [...(forward.get(edge.source.key) ?? []), edge.target.key]);
46
- backward.set(edge.target.key, [...(backward.get(edge.target.key) ?? []), edge.source.key]);
47
- }
48
- }
49
-
50
- const walk = (from: Iterable<string>, edges: Map<string, string[]>) => {
51
- const seen = new Set<string>(from);
52
- const todo = [...seen];
53
-
54
- for (let key = todo.pop(); key !== undefined; key = todo.pop()) {
55
- for (const next of edges.get(key) ?? []) {
56
- if (seen.has(next)) continue;
57
-
58
- seen.add(next);
59
- todo.push(next);
60
- }
61
- }
42
+ for (const [source, targets] of forward) for (const target of targets) backward.set(target, [...(backward.get(target) ?? []), source]);
62
43
 
63
- return seen;
64
- };
65
-
66
- const reachable = walk([initial], forward);
67
-
68
- const finishing = walk(
69
- Object.entries(states).flatMap(([name, node]) => (isTerminal(node) ? [name] : [])),
70
- backward,
71
- );
44
+ const reachable = reachedFrom(initial, forward);
45
+ const terminal = Object.entries(states).flatMap(([name, node]) => (isTerminal(node) ? [name] : []));
46
+ const finishing = new Set(terminal.flatMap((state) => [...reachedFrom(state, backward)]));
72
47
 
73
48
  return Object.entries(states).flatMap(([state, node]): Problem[] => [
74
49
  ...(reachable.has(state) ? [] : [{ problem: "unreachable-state", kind, state } as const]),
@@ -156,15 +131,14 @@ const eventProblems = (hum: HumConfig, kinds: Readonly<Record<string, Kind>>): P
156
131
  ];
157
132
  };
158
133
 
159
- /** Each `hope:<skill>` a role names exists in hope's installed copy. */
160
- const skillProblems = (hum: HumConfig, env: CheckEnv): Problem[] =>
161
- Object.entries(hum.roles).flatMap(([role, { skills }]) =>
162
- skills.flatMap((skill): Problem[] =>
163
- skill.startsWith("hope:") && !env.hopeSkills.has(skill.slice("hope:".length))
164
- ? [{ problem: "missing-hope-skill", skill, role }]
165
- : [],
166
- ),
167
- );
134
+ /** A plugin's skill is named `<plugin>:<skill>`; a bare name is the repo's or the user's own, which no plugin list holds. */
135
+ const isPluginSkill = (skill: string): boolean => skill.includes(":");
136
+
137
+ /** Each plugin skill a role names is in an installed plugin, where roles run. */
138
+ const skillProblems = (hum: HumConfig, { installedSkills }: CheckEnv): Problem[] =>
139
+ installedSkills === undefined
140
+ ? []
141
+ : Object.entries(hum.roles).flatMap(([role, { skills }]) => skills.flatMap((skill): Problem[] => (isPluginSkill(skill) && !installedSkills.has(skill) ? [{ problem: "missing-skill", skill, role }] : [])));
168
142
 
169
143
  /** A run branch could then share a name, or a folder, with a claim branch. */
170
144
  const doPrefixesOverlap = ({ runBranchPrefix, claimPrefix }: Naming): boolean =>
@@ -193,6 +167,14 @@ const pathProblems = (hum: HumConfig): Problem[] => {
193
167
  ];
194
168
  };
195
169
 
170
+ /** `ciEnv` sets none of the env the wake's jobs set themselves. */
171
+ const wakeEnvProblems = ({ ciEnv }: HumConfig): Problem[] =>
172
+ Object.keys(ciEnv).flatMap((name): Problem[] => (WAKE_OWN_ENV.has(name) ? [{ problem: "wake-env-taken", name }] : []));
173
+
174
+ /** Publish keeps less than the App token's hour in hand, so it has time left to merge. */
175
+ const mergeMarginProblems = ({ ciMergeMarginMinutes }: HumConfig): Problem[] =>
176
+ ciMergeMarginMinutes < APP_TOKEN_MINUTES ? [] : [{ problem: "merge-margin-fills-token-hour", minutes: ciMergeMarginMinutes, tokenMinutes: APP_TOKEN_MINUTES }];
177
+
196
178
  /** The proof a path names for a kind: its own, else the one for every kind. */
197
179
  export const proofFor = (rule: PathRule, kind: string): string | undefined => rule.proofs?.[kind] ?? rule.proofs?.[ALL_KINDS];
198
180
 
@@ -210,4 +192,6 @@ export const checkConfig = (
210
192
  ...eventProblems(hum, kinds),
211
193
  ...skillProblems(hum, env),
212
194
  ...namingProblems(hum),
195
+ ...wakeEnvProblems(hum),
196
+ ...mergeMarginProblems(hum),
213
197
  ];
@@ -83,6 +83,5 @@ export const readConfigDir = (dir: string): RawConfig => ({
83
83
  roles: Object.fromEntries(filesIn(join(dir, "roles"), ".md").map((file) => [`roles/${file}`, readFileSync(join(dir, "roles", file), "utf8")])),
84
84
  });
85
85
 
86
- /** The skill names (`intent`, not `hope:intent`) in a hope plugin folder's `skills/*\/SKILL.md`. */
87
- export const listHopeSkills = (hopeRoot: string): ReadonlySet<string> =>
88
- new Set(scan("*/SKILL.md", join(hopeRoot, "skills")).map((file) => dirname(file)));
86
+ /** The skills in a plugin folder's `skills/*\/SKILL.md`, as a role names them: `hope:intent` for the plugin `hope`. */
87
+ export const listPluginSkills = (plugin: string, root: string): string[] => scan("*/SKILL.md", join(root, "skills")).map((file) => `${plugin}:${dirname(file)}`);
@@ -1,4 +1,5 @@
1
1
  import { type AnyActorLogic, type AnyStateMachine, createAsyncLogic, machineFromJSON } from "xstate";
2
+ import { toDirectedGraph } from "xstate/graph";
2
3
  import type { Kind } from "./schema.ts";
3
4
 
4
5
  const placeholder = createAsyncLogic({ run: async () => {} });
@@ -16,3 +17,31 @@ export const kindMachine = (kind: Kind, sources: Readonly<Record<string, AnyActo
16
17
  /** An actor for each source the kind's machine invokes: the one `sources` gives, else `fallback`. */
17
18
  export const invokedSources = (kind: Kind, fallback: AnyActorLogic, sources: Readonly<Record<string, AnyActorLogic>> = {}): Record<string, AnyActorLogic> =>
18
19
  Object.fromEntries(Object.values(kind.machine.states).flatMap(({ invoke }) => (invoke ? [[invoke.src, sources[invoke.src] ?? fallback]] : [])));
20
+
21
+ /** Each state's next states, by every transition of the kind's machine. */
22
+ export const nextStates = (kind: Kind): ReadonlyMap<string, readonly string[]> => {
23
+ const next = new Map<string, string[]>();
24
+
25
+ for (const node of toDirectedGraph(kindMachine(kind)).children) for (const edge of node.edges) next.set(edge.source.key, [...(next.get(edge.source.key) ?? []), edge.target.key]);
26
+
27
+ return next;
28
+ };
29
+
30
+ /** The states `from` reaches through `next`, `from` among them; `expands` says which reached states lead on. */
31
+ export const reachedFrom = (from: string, next: ReadonlyMap<string, readonly string[]>, expands: (state: string) => boolean = () => true): ReadonlySet<string> => {
32
+ const seen = new Set([from]);
33
+ const todo = [from];
34
+
35
+ for (let state = todo.pop(); state !== undefined; state = todo.pop()) {
36
+ if (!expands(state)) continue;
37
+
38
+ for (const target of next.get(state) ?? []) {
39
+ if (seen.has(target)) continue;
40
+
41
+ seen.add(target);
42
+ todo.push(target);
43
+ }
44
+ }
45
+
46
+ return seen;
47
+ };
@@ -21,8 +21,11 @@ export const climb = <T extends object>(value: T, from: number, to: number, step
21
21
  /** Per earlier schema version: rewrites a config at that version into the next version's shape. */
22
22
  export type Migrations = Steps<ConfigJson>;
23
23
 
24
- /** One entry per earlier schema version. Empty while version 1 is the first. */
25
- export const MIGRATIONS: Migrations = {};
24
+ /** One entry per earlier schema version. Setup climbs the owner's answers, a part of a config, through the same steps, so a step rewrites only the keys it finds. */
25
+ export const MIGRATIONS = {
26
+ /** 2 holds the pull request token as one of its sources: the secret 1 named becomes `{ from: "secret", secret }`. */
27
+ 1: ({ pullRequestTokenSecret, ...config }) => (pullRequestTokenSecret === undefined ? config : { ...config, pullRequestToken: { from: "secret", secret: pullRequestTokenSecret } }),
28
+ } satisfies Migrations;
26
29
 
27
30
  const Raw = z.record(z.string(), Json);
28
31
  const Version = z.int();
@@ -6,7 +6,7 @@ export type Problem =
6
6
  | { readonly problem: "event-without-source"; readonly event: string; readonly source: string | undefined }
7
7
  | { readonly problem: "event-without-handler"; readonly event: string }
8
8
  | { readonly problem: "run-and-owner-wait"; readonly kind: string; readonly state: string }
9
- | { readonly problem: "missing-hope-skill"; readonly skill: string; readonly role: string }
9
+ | { readonly problem: "missing-skill"; readonly skill: string; readonly role: string }
10
10
  | { readonly problem: "unknown-state"; readonly kind: string; readonly state: string; readonly why: string }
11
11
  | { readonly problem: "unknown-run-source"; readonly kind: string; readonly state: string; readonly src: string }
12
12
  | { readonly problem: "tier-table-gap"; readonly kind: string; readonly purpose: string; readonly level: string; readonly size: string }
@@ -14,7 +14,9 @@ export type Problem =
14
14
  | { readonly problem: "missing-file"; readonly file: string }
15
15
  | { readonly problem: "unknown-level"; readonly level: string }
16
16
  | { readonly problem: "path-without-proof"; readonly glob: string; readonly level: string }
17
- | { readonly problem: "overlapping-prefixes"; readonly run: string; readonly claim: string };
17
+ | { readonly problem: "overlapping-prefixes"; readonly run: string; readonly claim: string }
18
+ | { readonly problem: "wake-env-taken"; readonly name: string }
19
+ | { readonly problem: "merge-margin-fills-token-hour"; readonly minutes: number; readonly tokenMinutes: number };
18
20
 
19
21
  /** A config change the engine will not take. The caller keeps the last good config. */
20
22
  export type Refusal =
@@ -23,7 +25,8 @@ export type Refusal =
23
25
  | { readonly code: "invalid-config"; readonly problems: readonly Problem[]; readonly message: string }
24
26
  | { readonly code: "unmapped-state"; readonly items: readonly { readonly kind: string; readonly state: string }[]; readonly message: string }
25
27
  | { readonly code: "change-from-run"; readonly branch: string; readonly message: string }
26
- | { readonly code: "no-git-identity"; readonly missing: readonly string[]; readonly message: string };
28
+ | { readonly code: "no-git-identity"; readonly missing: readonly string[]; readonly message: string }
29
+ | { readonly code: "own-runner-on-public-repo"; readonly message: string };
27
30
 
28
31
  export type Result<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly refusal: Refusal };
29
32
 
@@ -37,7 +40,7 @@ const DESCRIPTIONS = {
37
40
  p.source === undefined ? `event "${p.event}" is waited on but declared nowhere` : `event "${p.event}" has no source: "${p.source}" is not a part or role`,
38
41
  "event-without-handler": (p) => `event "${p.event}" has no handler in any kind`,
39
42
  "run-and-owner-wait": (p) => `${p.kind}: state "${p.state}" starts a run and waits on the owner`,
40
- "missing-hope-skill": (p) => `role "${p.role}" names hope skill "${p.skill}", which hope's installed copy lacks`,
43
+ "missing-skill": (p) => `role "${p.role}" names skill "${p.skill}", which no installed plugin has`,
41
44
  "unknown-state": (p) => `${p.kind}: ${p.why} names state "${p.state}", which does not exist`,
42
45
  "unknown-run-source": (p) => `${p.kind}: state "${p.state}" invokes "${p.src}", which is neither a role nor a part`,
43
46
  "tier-table-gap": (p) => `${p.kind}: no tier for purpose "${p.purpose}", level "${p.level}", size "${p.size}"`,
@@ -46,6 +49,8 @@ const DESCRIPTIONS = {
46
49
  "unknown-level": (p) => `risk level "${p.level}" is not in levels`,
47
50
  "path-without-proof": (p) => `path "${p.glob}" is at level "${p.level}", whose release waits for proof, and names no proof for every kind`,
48
51
  "overlapping-prefixes": (p) => `the run branch prefix "${p.run}" and the claim prefix "${p.claim}" overlap: one starts with the other`,
52
+ "wake-env-taken": (p) => `ciEnv sets ${p.name}, which the CI wake's jobs set themselves`,
53
+ "merge-margin-fills-token-hour": (p) => `ciMergeMarginMinutes is ${p.minutes}, and the token a GitHub App mints lasts ${p.tokenMinutes} minutes: publish would never have time left to merge`,
49
54
  } as const satisfies Describe;
50
55
 
51
56
  // SAFETY: each description is keyed by the problem name it reads, so the lookup by `problem.problem` takes its own variant.