@moo.md/hum 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/package.json +2 -2
  2. package/scripts/eval.ts +88 -50
  3. package/src/adapter-api.ts +46 -14
  4. package/src/adapters/admit.ts +2 -2
  5. package/src/adapters/argument.ts +1 -1
  6. package/src/adapters/claim.ts +18 -15
  7. package/src/adapters/claude-bg.ts +50 -27
  8. package/src/adapters/claude-p.ts +18 -23
  9. package/src/adapters/contract.ts +22 -10
  10. package/src/adapters/each-call.ts +9 -0
  11. package/src/adapters/fake.ts +6 -6
  12. package/src/adapters/git.ts +10 -18
  13. package/src/adapters/github-client.ts +102 -0
  14. package/src/adapters/github.ts +34 -142
  15. package/src/adapters/guard.ts +20 -9
  16. package/src/adapters/history.ts +12 -15
  17. package/src/adapters/item-file.ts +1 -1
  18. package/src/adapters/markdown.ts +49 -42
  19. package/src/adapters/marked.ts +6 -12
  20. package/src/adapters/model-call.ts +4 -4
  21. package/src/adapters/once.ts +5 -5
  22. package/src/adapters/owner-commit.ts +13 -11
  23. package/src/adapters/pull-requests.ts +11 -13
  24. package/src/adapters/registry.ts +7 -7
  25. package/src/adapters/roundup.ts +27 -35
  26. package/src/adapters/serial.ts +4 -5
  27. package/src/adapters/transcript.ts +13 -8
  28. package/src/cli/main.ts +1 -0
  29. package/src/cli/ops.ts +32 -14
  30. package/src/cli/service.ts +14 -8
  31. package/src/cli/setup.ts +8 -3
  32. package/src/cli/shared-watch.ts +3 -3
  33. package/src/config/checks.ts +14 -18
  34. package/src/config/machine.ts +5 -7
  35. package/src/config/refusal.ts +7 -0
  36. package/src/config/schema.ts +7 -7
  37. package/src/config/settings.ts +17 -2
  38. package/src/config/state-map.ts +5 -3
  39. package/src/decide/alignment.ts +4 -4
  40. package/src/decide/answer.ts +24 -22
  41. package/src/decide/kind.ts +1 -6
  42. package/src/decide/labels.ts +9 -9
  43. package/src/decide/merge.ts +6 -7
  44. package/src/decide/prose.ts +4 -4
  45. package/src/decide/question.ts +23 -20
  46. package/src/decide/review.ts +4 -2
  47. package/src/decide/risk.ts +25 -19
  48. package/src/decide/taste.ts +3 -3
  49. package/src/exec.ts +4 -3
  50. package/src/index.ts +14 -13
  51. package/src/loop/check-item.ts +3 -3
  52. package/src/loop/ci.ts +1 -1
  53. package/src/loop/github.ts +2 -2
  54. package/src/loop/groups.ts +13 -6
  55. package/src/loop/memory.ts +40 -28
  56. package/src/loop/notes.ts +5 -5
  57. package/src/loop/pair.ts +1 -1
  58. package/src/loop/pass.ts +18 -12
  59. package/src/loop/proof.ts +9 -7
  60. package/src/loop/prove-item.ts +1 -1
  61. package/src/loop/records.ts +12 -13
  62. package/src/loop/signals.ts +6 -6
  63. package/src/measure/inputs.ts +1 -1
  64. package/src/measure/measure.ts +4 -4
  65. package/src/measure/rate.ts +2 -0
  66. package/src/service/ci-tick.ts +2 -2
  67. package/src/service/supervise.ts +3 -2
  68. package/src/service/token.ts +3 -3
  69. package/src/service/wake.ts +2 -2
  70. package/src/service/workflows.ts +2 -2
  71. package/src/setup/propose.ts +4 -4
  72. package/src/setup/prove.ts +18 -12
  73. package/src/setup/scan.ts +31 -24
  74. package/src/setup/shipped.ts +8 -2
  75. package/src/setup/tables.ts +4 -3
  76. package/src/setup/waits.ts +9 -11
  77. package/src/setup/write.ts +17 -10
  78. package/src/slots/pool.ts +32 -24
  79. package/src/state/events.ts +1 -1
  80. package/src/state/faults.ts +13 -5
  81. package/src/state/format.ts +2 -2
  82. package/src/state/items.ts +9 -10
  83. package/src/state/open.ts +2 -2
  84. package/src/state/ops.ts +16 -10
  85. package/src/state/records.ts +5 -5
  86. package/src/state/runs.ts +33 -26
  87. package/src/state/saved.ts +44 -32
  88. package/src/status/file.ts +20 -1
  89. package/src/status/format.ts +47 -57
  90. package/src/status/sections.ts +2 -2
  91. package/src/worker/alignment-report.ts +4 -5
  92. package/src/worker/answers.ts +26 -24
  93. package/src/worker/base-check.ts +2 -2
  94. package/src/worker/kind.ts +23 -19
  95. package/src/worker/land.ts +114 -126
  96. package/src/worker/merged.ts +9 -7
  97. package/src/worker/open.ts +14 -12
  98. package/src/worker/prose-run.ts +3 -3
  99. package/src/worker/questions.ts +15 -12
  100. package/src/worker/scheduler.ts +4 -4
  101. package/src/worker/signature.ts +3 -3
  102. package/src/worker/tally.ts +0 -2
  103. package/src/worker/taste.ts +6 -15
  104. package/src/worker/thin-path.ts +148 -121
  105. package/src/worker/thread.ts +25 -0
  106. package/src/worker/worker.ts +77 -47
  107. package/surface.json +632 -2197
  108. package/src/slots/scan.ts +0 -26
@@ -5,7 +5,7 @@ import { SECOND_MS } from "../time.ts";
5
5
  export const CI_TICK_REF = "refs/hum/ticks/ci";
6
6
 
7
7
  /** The scheduled workflow records its tick as an empty commit dated now, force-pushed to `CI_TICK_REF`. */
8
- export const recordCiTick = async (repo: string, remote: string, at: number, identity: GitIdentity, timeoutMs: number): Promise<void> => {
8
+ export const recordCiTick = async ({ repo, remote, at, identity, timeoutMs }: { readonly repo: string; readonly remote: string; readonly at: number; readonly identity: GitIdentity; readonly timeoutMs: number }): Promise<void> => {
9
9
  const when = `${Math.floor(at / SECOND_MS)} +0000`;
10
10
  const git = gitIn(repo, { identity, timeoutMs, env: { GIT_AUTHOR_DATE: when, GIT_COMMITTER_DATE: when } });
11
11
  const tree = (await git.raw(["hash-object", "-w", "-t", "tree", "/dev/null"])).trim();
@@ -15,7 +15,7 @@ export const recordCiTick = async (repo: string, remote: string, at: number, ide
15
15
  };
16
16
 
17
17
  /** The time of the last recorded tick, or undefined when the scheduled workflow has never run or the remote cannot be read. */
18
- export const readCiTick = async (repo: string, remote: string, timeoutMs: number): Promise<number | undefined> => {
18
+ export const readCiTick = async ({ repo, remote, timeoutMs }: { readonly repo: string; readonly remote: string; readonly timeoutMs: number }): Promise<number | undefined> => {
19
19
  const git = gitIn(repo, { timeoutMs });
20
20
 
21
21
  const fetched = await git.raw(["fetch", "--quiet", "--no-tags", remote, `+${CI_TICK_REF}:${CI_TICK_REF}`]).then(() => true, whenGitFailed(false));
@@ -41,7 +41,7 @@ type Card = ReturnType<(typeof CARD_KINDS)["workerSilent"]> | undefined;
41
41
 
42
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
43
  const showWorkerDown = ({ faults, statusPath }: Supervision["state"], card: Card, now: number): void => {
44
- faults.clear(CARD_CODES.workerDown);
44
+ faults.clear({ code: CARD_CODES.workerDown });
45
45
 
46
46
  if (card) faults.raise(card);
47
47
 
@@ -62,7 +62,8 @@ const silenceOf = (quietSince: number, beat: { readonly time: number; readonly i
62
62
  return { quietSince: lastSeen, silentMs, isSilent: silentMs >= o.workerDownTicks * (beat?.intervalMs ?? o.intervalMs) };
63
63
  };
64
64
 
65
- const backoffFor = (crashes: number, { backoffMs, maxBackoffMs }: Pick<Supervision, "backoffMs" | "maxBackoffMs">): number => Math.min(backoffMs * 2 ** (crashes - 1), maxBackoffMs);
65
+ /** The pause before a restart once `crashes` crashes sit inside the window. */
66
+ export const backoffFor = (crashes: number, { backoffMs, maxBackoffMs }: Pick<Supervision, "backoffMs" | "maxBackoffMs">): number => Math.min(backoffMs * 2 ** (crashes - 1), maxBackoffMs);
66
67
 
67
68
  /**
68
69
  * The start script as a machine. It runs the worker and starts it again when it exits, looks at the heartbeat once
@@ -9,13 +9,13 @@ export const TOKEN_LIFE_DAYS = 365;
9
9
  export const UNAUTHORIZED = /API Error: 401|Failed to authenticate/i;
10
10
 
11
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 }));
12
+ export const raiseRejectedToken = (faults: Faults, said: string) => faults.raise(CARD_KINDS.tokenRejected({ said }));
13
13
 
14
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 => {
15
+ export const checkTokenAge = (faults: Faults, { setUp, now, warnDays }: { readonly setUp: string; readonly now: number; readonly warnDays: number }): void => {
16
16
  const expires = Date.parse(setUp) + TOKEN_LIFE_DAYS * DAY_MS;
17
17
 
18
- if (now < expires - warnDays * DAY_MS) return faults.clear(CARD_CODES.tokenExpiring);
18
+ if (now < expires - warnDays * DAY_MS) return faults.clear({ code: CARD_CODES.tokenExpiring });
19
19
 
20
20
  faults.raise(CARD_KINDS.tokenExpiring({ setUp, validUntil: new Date(expires).toISOString().slice(0, 10) }));
21
21
  };
@@ -23,8 +23,8 @@ const line = (card: Card): string => `${card.cause} ${card.fix}`;
23
23
  * Shows the cards where a CI job's reader looks: one error annotation each, and the job's step summary when the
24
24
  * runner gives one. The job's status file dies with the job, so this is the only place CI shows a card.
25
25
  */
26
- export const reportCards = async (cards: readonly Card[]): Promise<void> => {
26
+ export const reportCards = async (cards: readonly Card[], { hasStepSummary }: { readonly hasStepSummary: boolean }): Promise<void> => {
27
27
  for (const card of cards) core.error(line(card), { title: `hum ${card.code}` });
28
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();
29
+ if (hasStepSummary && cards.length > 0) await core.summary.addHeading("hum", 2).addList(cards.map((card) => `${card.code}: ${line(card)}`)).write();
30
30
  };
@@ -5,10 +5,10 @@ import type { HumConfig } from "../config/schema.ts";
5
5
  /** The settings the workflows are built from. */
6
6
  export type WorkflowSettings = Pick<HumConfig, "runBranchPrefix" | "itemsDir" | "ciSchedule" | "commitIdentity" | "ciWakeTimeoutMinutes" | "pullRequestTokenSecret">;
7
7
 
8
- export const WAKE_FILE = "hum-wake.yml";
8
+ const WAKE_FILE = "hum-wake.yml";
9
9
 
10
10
  /** The type of the `repository_dispatch` event a tracker's webhook sends. */
11
- export const DISPATCH_EVENT = "hum-wake";
11
+ const DISPATCH_EVENT = "hum-wake";
12
12
 
13
13
  const WAKE_PATH = `./.github/workflows/${WAKE_FILE}`;
14
14
 
@@ -46,7 +46,7 @@ const scriptCommand = (scan: RepoScan, script: string): string | undefined => {
46
46
  * The commands the repo's own CI runs on a pull request to check a change; else its package scripts that check.
47
47
  * A run checks a fresh clone, which has no dependencies yet, so the lockfile install comes first.
48
48
  */
49
- export const checksOf = (scan: RepoScan): string[] => {
49
+ const checksOf = (scan: RepoScan): string[] => {
50
50
  const fromCi = unique(scan.ci.filter(isPullRequestJob).flatMap(({ commands }) => commands.filter(isCheck)));
51
51
  const checks = fromCi.length > 0 ? fromCi : CHECK_SCRIPTS.flatMap((script) => scriptCommand(scan, script) ?? []);
52
52
 
@@ -60,14 +60,14 @@ const rankOfFolder = (folder: string): number => FOLDER_RANKS.find((row) => row.
60
60
  const topFolders = (tracked: readonly string[]): string[] => unique(tracked.flatMap((path) => (path.includes("/") ? [path.split("/")[0] ?? ""] : []))).sort();
61
61
 
62
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[] => [
63
+ const pathRulesOf = (tracked: readonly string[], levels: HumConfig["levels"]): PathRule[] => [
64
64
  ...topFolders(tracked).map((folder) => ({ glob: `${folder}/**`, level: levelAt(levels, rankOfFolder(folder)) })),
65
65
  { glob: "*.md", level: levelAt(levels, ROOT_MARKDOWN_RANK) },
66
66
  { glob: "*", level: levelAt(levels, DEFAULT_FOLDER_RANK) },
67
67
  ];
68
68
 
69
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[] =>
70
+ const strictGlobsOf = (tracked: readonly string[]): string[] =>
71
71
  DATA_AND_SECRET_GLOBS.filter((glob) => tracked.some((path) => new Bun.Glob(glob).match(path) && !SECRET_TEMPLATE.test(path)));
72
72
 
73
73
  const mapLabels = (labels: readonly string[], kinds: readonly string[]): Record<string, string> =>
@@ -80,7 +80,7 @@ const mapLabels = (labels: readonly string[], kinds: readonly string[]): Record<
80
80
  );
81
81
 
82
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> =>
83
+ const kindLabelsOf = (scan: RepoScan, repoLabels: readonly string[], kinds: readonly string[]): Record<string, string> =>
84
84
  mapLabels([...scan.issueTemplates.flatMap(({ labels }) => labels), ...repoLabels], kinds);
85
85
 
86
86
  /** How many of the open items name their kind through the map, a kind's own name or a template field. */
@@ -2,11 +2,11 @@ import { mkdtempSync, readFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { z } from "zod";
5
- import type { AdapterContext } from "../adapter-api.ts";
5
+ import { type AdapterContext, Holder, ItemId } from "../adapter-api.ts";
6
6
  import { runContract } from "../adapters/contract.ts";
7
7
  import { markdownAdapter } from "../adapters/markdown.ts";
8
8
  import { type Config, loadConfig, readConfigDir } from "../config/load.ts";
9
- import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
9
+ import { commandTimeoutMs, type Env, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
10
  import { SlotPool } from "../slots/pool.ts";
11
11
  import { orMissing } from "../state/fs.ts";
12
12
  import { openState } from "../state/open.ts";
@@ -14,7 +14,7 @@ import { checksTimeoutMs, runChecks } from "../worker/checks.ts";
14
14
  import { openWorker } from "../worker/open.ts";
15
15
  import { Scratch } from "./scratch.ts";
16
16
 
17
- export type StepStatus = "passed" | "failed" | "skipped";
17
+ type StepStatus = "passed" | "failed" | "skipped";
18
18
 
19
19
  /** One thing setup proved, with how long it took. A skip says why, so nothing passes silently. */
20
20
  export type Step = { readonly name: string; readonly status: StepStatus; readonly detail: string; readonly ms: number };
@@ -27,9 +27,9 @@ const failed = (detail: string): Outcome => ({ status: "failed", detail });
27
27
 
28
28
  const skipped = (detail: string): Outcome => ({ status: "skipped", detail });
29
29
 
30
- /** Runs one step; a throw is the step failing, in the error's own words. */
31
30
  const stepOf = (name: string, outcome: Outcome, started: number): Step => ({ name, status: outcome.status, detail: outcome.detail, ms: Math.round(performance.now() - started) });
32
31
 
32
+ /** Runs one step; a throw is the step failing, in the error's own words. */
33
33
  const timed = async (name: string, run: () => Promise<Outcome>): Promise<Step> => {
34
34
  const started = performance.now();
35
35
 
@@ -37,6 +37,9 @@ const timed = async (name: string, run: () => Promise<Outcome>): Promise<Step> =
37
37
  };
38
38
 
39
39
  export type ProveEnv = {
40
+ readonly now: () => number;
41
+ readonly processEnv: Env;
42
+ readonly newSessionId: () => string;
40
43
  readonly hopeSkills: ReadonlySet<string>;
41
44
  readonly base: string;
42
45
  /** Whether to run one item end to end through the real `claude`; each run spends live calls. */
@@ -56,7 +59,7 @@ const ENGINE = "@moo.md/hum";
56
59
  const LOCAL_PIN = /^(file|link):/;
57
60
 
58
61
  /** What the registry says about the pinned version: found, or the package exists without it, or the package is not published. */
59
- export const npmPublished = async (pin: string): Promise<"found" | "missing-version" | "unpublished"> => {
62
+ const npmPublished = async (pin: string): Promise<"found" | "missing-version" | "unpublished"> => {
60
63
  const viewed = await exec("npm", ["view", `${ENGINE}@${pin}`, "version"], { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
61
64
 
62
65
  if (viewed.exitCode === 0) return "found";
@@ -93,7 +96,7 @@ const checksStep = async (repo: string, config: Config): Promise<Outcome> => {
93
96
  const markdownOver = (repo: string, base: string, hum: Config["hum"], context: AdapterContext) =>
94
97
  markdownAdapter({ repo, base, claimPrefix: hum.claimPrefix, itemsDir: hum.itemsDir, identity: hum.commitIdentity, writeRaceRetries: hum.writeRaceRetries, itemReadsAtOnce: hum.itemReadsAtOnce, mergeMethod: hum.mergeMethod, ownerBranchPrefix: hum.ownerBranchPrefix, timeoutMs: commandTimeoutMs(hum) }, context);
95
98
 
96
- const contractStep = async (config: Config, scratch: Scratch, base: string): Promise<Outcome> => {
99
+ const contractStep = async (config: Config, scratch: Scratch, { base, now, processEnv }: Pick<ProveEnv, "base" | "now" | "processEnv">): Promise<Outcome> => {
97
100
  const others = Object.entries(config.hum.integrations ?? {}).filter(([, adapter]) => adapter !== "markdown");
98
101
 
99
102
  if (others.length > 0) return skipped(`${others.map(([slot, adapter]) => `${slot}: ${adapter}`).join(", ")} write to a live target; run its contract suite there`);
@@ -101,7 +104,7 @@ const contractStep = async (config: Config, scratch: Scratch, base: string): Pro
101
104
  let skew = 0;
102
105
  let count = 0;
103
106
 
104
- const context: AdapterContext = { report: () => {}, now: () => Date.now() + skew };
107
+ const context: AdapterContext = { report: () => {}, now: () => now() + skew, env: processEnv };
105
108
  const first = markdownOver(await scratch.worker(), base, config.hum, context);
106
109
  const second = markdownOver(await scratch.worker(), base, config.hum, context);
107
110
 
@@ -109,7 +112,7 @@ const contractStep = async (config: Config, scratch: Scratch, base: string): Pro
109
112
  name: "markdown",
110
113
  adapter: first,
111
114
  other: async () => second,
112
- seed: (title) => scratch.seed(`contract-${++count}`, title, "body"),
115
+ seed: async (title) => ItemId.parse(await scratch.seed(`contract-${++count}`, title, "body")),
113
116
  advance: async (ms) => void (skew += ms),
114
117
  spent: () => first.spent(),
115
118
  });
@@ -137,8 +140,8 @@ const slotStep = async (config: Config, scratch: Scratch, env: ProveEnv): Promis
137
140
  if (!config.hum.runSlots.enabled) return skipped("run slots are off in hum.json");
138
141
 
139
142
  const pool = mkdtempSync(join(tmpdir(), "hum-prove-slots-"));
140
- const state = openState(mkdtempSync(join(tmpdir(), "hum-prove-state-")));
141
- const slots = new SlotPool({ repo: scratch.owner, state, config: { ...config.hum, runners: 1, runSlots: { ...config.hum.runSlots, pool } }, base: env.base });
143
+ const state = openState(mkdtempSync(join(tmpdir(), "hum-prove-state-")), { now: env.now });
144
+ const slots = new SlotPool({ repo: scratch.owner, state, config: { ...config.hum, runners: 1, runSlots: { ...config.hum.runSlots, pool } }, base: env.base, now: env.now });
142
145
  const started = performance.now();
143
146
 
144
147
  await slots.maintain();
@@ -172,8 +175,11 @@ const runItem = async (scratch: Scratch, env: ProveEnv): Promise<Outcome> => {
172
175
  const results: string[] = [];
173
176
 
174
177
  const worker = await openWorker(scratch.owner, {
178
+ now: env.now,
179
+ env: env.processEnv,
180
+ newSessionId: env.newSessionId,
175
181
  hopeSkills: env.hopeSkills,
176
- holder: "setup-proof",
182
+ holder: Holder.parse("setup-proof"),
177
183
  base: env.base,
178
184
  where: "ci",
179
185
  stateDir: mkdtempSync(join(tmpdir(), "hum-prove-state-")),
@@ -205,7 +211,7 @@ export const proveSetup = async (repo: string, env: ProveEnv): Promise<Step[]> =
205
211
  return [
206
212
  configured,
207
213
  await timed("checks", () => checksStep(repo, config)),
208
- await timed("contract", () => contractStep(config, scratch, env.base)),
214
+ await timed("contract", () => contractStep(config, scratch, env)),
209
215
  await timed("engine pin", () => pinStep(repo, env)),
210
216
  await timed("slot", () => slotStep(config, scratch, env)),
211
217
  await timed("item", () => itemStep(repo, config, env)),
package/src/setup/scan.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  import { accessSync, constants, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
- import { parse as parseYaml } from "yaml";
3
+ import { parseDocument } from "yaml";
4
4
  import { z } from "zod";
5
5
  import { gitIn } from "../adapters/git.ts";
6
6
  import { readHistory } from "../adapters/history.ts";
7
7
  import { SHIPPED_DEFAULTS } from "../config/schema.ts";
8
8
  import { SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
9
9
  import { orMissing } from "../state/fs.ts";
10
- import { ENV_SCRIPTS } from "../slots/scan.ts";
11
10
  import {
12
11
  CODEOWNERS_FILES,
13
12
  COMPOSE_FILES,
14
13
  ENV_EXAMPLE_FILES,
14
+ ENV_SCRIPTS,
15
15
  ENV_TOOLING_FILES,
16
16
  ISSUE_TEMPLATE_FOLDER,
17
17
  LOCKFILES,
@@ -25,7 +25,7 @@ import {
25
25
  /** One job of a CI workflow: when it runs and the shell commands its steps run. */
26
26
  export type CiJob = { readonly file: string; readonly job: string; readonly triggers: readonly string[]; readonly commands: readonly string[] };
27
27
 
28
- export type FolderHistory = { readonly folder: string; readonly changes: number; readonly sizes: readonly number[] };
28
+ type FolderHistory = { readonly folder: string; readonly changes: number; readonly sizes: readonly number[] };
29
29
 
30
30
  /** What a repo already holds that setup reads before it asks. */
31
31
  export type RepoScan = {
@@ -49,7 +49,7 @@ export type RepoScan = {
49
49
 
50
50
  const textOf = (repo: string, path: string): string => (path === "" ? "" : orMissing(() => readFileSync(join(repo, path), "utf8"), ""));
51
51
 
52
- const exists = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path)), true), false);
52
+ const doesExist = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path)), true), false);
53
53
 
54
54
  const isRunnable = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path), constants.X_OK), true), false);
55
55
 
@@ -72,6 +72,14 @@ const Template = z.looseObject({ labels: z.union([z.string(), z.array(z.string()
72
72
 
73
73
  const TEMPLATE_FRONT_MATTER = /^---\n([\s\S]*?)\n---/;
74
74
 
75
+ /** A YAML file read through `schema`, or undefined when the file does not parse or does not fit it. */
76
+ const yamlOf = <Schema extends z.ZodType>(schema: Schema, text: string): z.output<Schema> | undefined => {
77
+ const document = parseDocument(text);
78
+ const parsed = document.errors.length === 0 ? schema.safeParse(document.toJS()) : undefined;
79
+
80
+ return parsed?.success ? parsed.data : undefined;
81
+ };
82
+
75
83
  const commandsOf = (run: string): string[] =>
76
84
  run
77
85
  .split("\n")
@@ -81,13 +89,13 @@ const commandsOf = (run: string): string[] =>
81
89
  /** The CI workflows' jobs. A workflow that does not parse is skipped, because the owner's CI is not setup's to judge. */
82
90
  const ciJobsOf = (repo: string): CiJob[] =>
83
91
  filesIn(repo, `${WORKFLOW_FOLDER}/*.{yml,yaml}`).flatMap((file) => {
84
- const parsed = Workflow.safeParse(parseYaml(textOf(repo, file)));
92
+ const workflow = yamlOf(Workflow, textOf(repo, file));
85
93
 
86
- if (!parsed.success) return [];
94
+ if (workflow === undefined) return [];
87
95
 
88
- const triggers = parsed.data.on;
96
+ const triggers = workflow.on;
89
97
 
90
- return Object.entries(parsed.data.jobs).map(([job, { steps }]) => ({
98
+ return Object.entries(workflow.jobs).map(([job, { steps }]) => ({
91
99
  file: basename(file),
92
100
  job,
93
101
  triggers,
@@ -96,7 +104,7 @@ const ciJobsOf = (repo: string): CiJob[] =>
96
104
  });
97
105
 
98
106
  const codeownersOf = (repo: string): RepoScan["codeowners"] => {
99
- const file = CODEOWNERS_FILES.find((candidate) => exists(repo, candidate));
107
+ const file = CODEOWNERS_FILES.find((candidate) => doesExist(repo, candidate));
100
108
 
101
109
  return textOf(repo, file ?? "")
102
110
  .split("\n")
@@ -105,10 +113,10 @@ const codeownersOf = (repo: string): RepoScan["codeowners"] => {
105
113
  };
106
114
 
107
115
  const composeOf = (repo: string): RepoScan["composeServices"] => {
108
- const file = COMPOSE_FILES.find((candidate) => exists(repo, candidate));
109
- const parsed = Compose.safeParse(parseYaml(textOf(repo, file ?? "")));
116
+ const file = COMPOSE_FILES.find((candidate) => doesExist(repo, candidate));
117
+ const compose = yamlOf(Compose, textOf(repo, file ?? ""));
110
118
 
111
- return parsed.success ? Object.entries(parsed.data.services).map(([name, { image }]) => ({ name, image })) : [];
119
+ return compose ? Object.entries(compose.services).map(([name, { image }]) => ({ name, image })) : [];
112
120
  };
113
121
 
114
122
  /** The environment scripts a repo is built to run: executable files in the usual places. */
@@ -127,9 +135,9 @@ const templatesOf = (repo: string): RepoScan["issueTemplates"] =>
127
135
  filesIn(repo, `${ISSUE_TEMPLATE_FOLDER}/*`).flatMap((file) => {
128
136
  const text = textOf(repo, file);
129
137
  const front = file.endsWith(".md") ? TEMPLATE_FRONT_MATTER.exec(text)?.[1] ?? "" : text;
130
- const parsed = Template.safeParse(parseYaml(front));
138
+ const template = yamlOf(Template, front);
131
139
 
132
- return parsed.success ? [{ file: basename(file), labels: [parsed.data.labels].flat().flatMap((label) => label.split(",").map((one) => one.trim()).filter(Boolean)) }] : [];
140
+ return template ? [{ file: basename(file), labels: [template.labels].flat().flatMap((label) => label.split(",").map((one) => one.trim()).filter(Boolean)) }] : [];
133
141
  });
134
142
 
135
143
  const trackedOf = async (repo: string): Promise<string[]> => (await gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS }).raw(["ls-files"])).split("\n").filter(Boolean).slice(0, TRACKED_FILE_LIMIT);
@@ -143,14 +151,13 @@ const foldersOf = async (repo: string, base: string): Promise<FolderHistory[]> =
143
151
 
144
152
  if (log.code !== 0) return [];
145
153
 
146
- const changes = await readHistory(git, base, SHIPPED_DEFAULTS);
147
- const folders = new Map<string, number[]>();
154
+ const touches = (await readHistory(git, base, SHIPPED_DEFAULTS)).flatMap(({ files, size }) => [...new Set(files.map(topFolder).filter(Boolean))].map((folder) => ({ folder, size })));
148
155
 
149
- for (const change of changes) {
150
- for (const folder of new Set(change.files.map(topFolder).filter(Boolean))) folders.set(folder, [...(folders.get(folder) ?? []), change.size]);
151
- }
156
+ return [...new Set(touches.map(({ folder }) => folder))].map((folder) => {
157
+ const sizes = touches.flatMap((touch) => (touch.folder === folder ? [touch.size] : []));
152
158
 
153
- return [...folders].map(([folder, sizes]) => ({ folder, changes: sizes.length, sizes: sizes.toReversed() }));
159
+ return { folder, changes: sizes.length, sizes: sizes.toReversed() };
160
+ });
154
161
  };
155
162
 
156
163
  const humSchemaOf = (repo: string): number | undefined => {
@@ -164,7 +171,7 @@ export const scanRepo = async (repo: string, base: string): Promise<RepoScan> =>
164
171
  const manifest = PackageJson.safeParse(orMissing(() => JSON.parse(textOf(repo, "package.json") || "null"), null));
165
172
  const scripts = manifest.success ? manifest.data.scripts : {};
166
173
  const pinned = manifest.success ? { ...manifest.data.dependencies, ...manifest.data.devDependencies }["@moo.md/hum"] : undefined;
167
- const lockfile = Object.entries(LOCKFILES).find(([file]) => exists(repo, file));
174
+ const lockfile = Object.entries(LOCKFILES).find(([file]) => doesExist(repo, file));
168
175
 
169
176
  return {
170
177
  packageManager: lockfile?.[1],
@@ -174,9 +181,9 @@ export const scanRepo = async (repo: string, base: string): Promise<RepoScan> =>
174
181
  composeServices: composeOf(repo),
175
182
  envScripts: envScriptsOf(repo),
176
183
  setupTargets: setupTargetsOf(repo, scripts),
177
- toolVersions: TOOL_VERSION_FILES.filter((file) => exists(repo, file)),
178
- envExamples: ENV_EXAMPLE_FILES.filter((file) => exists(repo, file)),
179
- envTooling: ENV_TOOLING_FILES.filter((file) => exists(repo, file)),
184
+ toolVersions: TOOL_VERSION_FILES.filter((file) => doesExist(repo, file)),
185
+ envExamples: ENV_EXAMPLE_FILES.filter((file) => doesExist(repo, file)),
186
+ envTooling: ENV_TOOLING_FILES.filter((file) => doesExist(repo, file)),
180
187
  issueTemplates: templatesOf(repo),
181
188
  tracked: await trackedOf(repo),
182
189
  folders: await foldersOf(repo, base),
@@ -1,9 +1,11 @@
1
1
  import { join } from "node:path";
2
+ import type { GitIdentityRead } from "../adapters/git.ts";
2
3
  import { type RawConfig, readConfigDir } from "../config/load.ts";
3
- import { DefaultsConfig, Kind } from "../config/schema.ts";
4
+ import { noGitIdentity, type Result } from "../config/refusal.ts";
5
+ import { DefaultsConfig, type HumConfig, Kind } from "../config/schema.ts";
4
6
 
5
7
  /** Where the shipped defaults sit, in the package or in the owner's `node_modules`. */
6
- export const DEFAULTS_DIR = join(import.meta.dir, "..", "..", "defaults");
8
+ const DEFAULTS_DIR = join(import.meta.dir, "..", "..", "defaults");
7
9
 
8
10
  export const shippedRaw = (): RawConfig => readConfigDir(DEFAULTS_DIR);
9
11
 
@@ -13,3 +15,7 @@ export const shippedConfig = () => {
13
15
 
14
16
  return { hum: DefaultsConfig.parse(raw.hum), kinds: Object.fromEntries(Object.entries(raw.kinds).map(([name, file]) => [name, Kind.parse(file)])) };
15
17
  };
18
+
19
+ /** The shipped settings as an owner's own: they commit as the identity git config holds, and refuse without one. */
20
+ export const shippedSettingsAs = (git: GitIdentityRead): Result<HumConfig> =>
21
+ git.found ? { ok: true, value: { ...DefaultsConfig.parse(shippedRaw().hum), commitIdentity: git.identity } } : { ok: false, refusal: noGitIdentity(git.missing) };
@@ -26,7 +26,7 @@ export const INSTALL_COMMANDS = {
26
26
  } as const satisfies Record<PackageManager, string>;
27
27
 
28
28
  /** The command that runs a package script, per package manager that has scripts. */
29
- export const RUN_SCRIPT: Readonly<Record<PackageManager, string | undefined>> = { bun: "bun run", pnpm: "pnpm run", yarn: "yarn", npm: "npm run", uv: undefined, poetry: undefined, cargo: undefined, go: undefined };
29
+ export const RUN_SCRIPT = { bun: "bun run", pnpm: "pnpm run", yarn: "yarn", npm: "npm run", uv: undefined, poetry: undefined, cargo: undefined, go: undefined } as const satisfies Record<PackageManager, string | undefined>;
30
30
 
31
31
  /** Package scripts that check a change, in the order a repo's own run gives them. */
32
32
  export const CHECK_SCRIPTS = ["check", "typecheck", "lint", "test"] as const;
@@ -43,6 +43,9 @@ export const NOT_A_CHECK = /^(echo|export|cd|mkdir|cp|mv|rm|curl|wget|sudo|gh|gi
43
43
  /** The files that hold a repo's tool versions. */
44
44
  export const TOOL_VERSION_FILES = [".tool-versions", ".nvmrc", ".node-version", ".bun-version", ".python-version", "mise.toml", ".mise.toml", "rust-toolchain.toml", ".go-version"] as const;
45
45
 
46
+ /** Where owners keep a script that sets up a working environment, in the order a repo's own convention is preferred. */
47
+ export const ENV_SCRIPTS = ["bin/setup", "script/setup", "scripts/setup", "scripts/setup.sh", "bin/env", "scripts/env", "scripts/env.sh"] as const;
48
+
46
49
  export const ENV_EXAMPLE_FILES = [".env.example", ".env.sample", ".env.template"] as const;
47
50
 
48
51
  /** The owner's own environment tooling: a recipe calls it and rebuilds nothing. */
@@ -95,7 +98,5 @@ export const KIND_LABEL_WORDS = {
95
98
  /** Hours a wait gets before it ends stuck, by who it waits on. */
96
99
  export const WAIT_HOURS = { owner: 72, other: 24 } as const;
97
100
 
98
- export const HOUR_MS = 3_600_000;
99
-
100
101
  /** Tracked files setup reads the repo's shape from, at most. */
101
102
  export const TRACKED_FILE_LIMIT = 50_000;
@@ -1,5 +1,6 @@
1
1
  import { OWNER_WAIT_TAG, STUCK_TAG, WAIT_TAG, type Kind, type StateNodeJSON } from "../config/schema.ts";
2
- import { HOUR_MS, WAIT_HOURS } from "./tables.ts";
2
+ import { HOUR_MS } from "../time.ts";
3
+ import { WAIT_HOURS } from "./tables.ts";
3
4
 
4
5
  /** A state a kind's machine waits in, with the hours its timeout proposes. */
5
6
  export type Wait = { readonly kind: string; readonly state: string; readonly waitsOn: "owner" | "other"; readonly hours: number };
@@ -8,7 +9,7 @@ export type Wait = { readonly kind: string; readonly state: string; readonly wai
8
9
  export type WaitAnswers = Readonly<Record<string, number>>;
9
10
 
10
11
  /** The key a wait's answer sits under. */
11
- export const waitKey = ({ kind, state }: Pick<Wait, "kind" | "state">): string => `${kind}/${state}`;
12
+ const waitKey = ({ kind, state }: Pick<Wait, "kind" | "state">): string => `${kind}/${state}`;
12
13
 
13
14
  const isOwnerWait = (tags: readonly string[] | undefined): boolean => tags?.includes(OWNER_WAIT_TAG) ?? false;
14
15
 
@@ -27,24 +28,21 @@ export const waitsOf = (kinds: Readonly<Record<string, Kind>>): Wait[] =>
27
28
  );
28
29
 
29
30
  /** The state a timed-out wait goes to: the kind's first stuck state. */
30
- const stuckStateOf = (kind: string, config: Kind): string => {
31
- const stuck = Object.entries(config.machine.states).find(([, node]) => node.tags?.includes(STUCK_TAG));
32
-
33
- if (!stuck) throw new Error(`kind "${kind}" has no state tagged "${STUCK_TAG}" for a timed-out wait to go to`);
34
-
35
- return stuck[0];
36
- };
31
+ const stuckStateOf = (config: Kind): string | undefined => Object.entries(config.machine.states).find(([, node]) => node.tags?.includes(STUCK_TAG))?.[0];
37
32
 
38
33
  const hasTimeout = (node: StateNodeJSON): boolean => node.timeout !== undefined || Object.keys(node.after ?? {}).length > 0;
39
34
 
40
35
  /**
41
36
  * The kinds with a timeout on every wait: the hours answered, else the proposed hours. A timed-out wait ends stuck.
42
- * A wait that already has a timeout keeps it.
37
+ * A wait that already has a timeout keeps it. A kind with no stuck state stays as it is, so the config check refuses its waits.
43
38
  */
44
39
  export const withTimeouts = (kinds: Readonly<Record<string, Kind>>, answers: WaitAnswers): Record<string, Kind> =>
45
40
  Object.fromEntries(
46
41
  Object.entries(kinds).map(([kind, config]) => {
47
- const stuck = stuckStateOf(kind, config);
42
+ const stuck = stuckStateOf(config);
43
+
44
+ if (stuck === undefined) return [kind, config];
45
+
48
46
  const hoursOf = new Map(waitsOf({ [kind]: config }).map((wait) => [wait.state, answers[waitKey(wait)] ?? wait.hours]));
49
47
 
50
48
  const states = Object.entries(config.machine.states).map(([state, node]): [string, StateNodeJSON] => {
@@ -7,7 +7,7 @@ import { type Config, loadConfig, type RawConfig, readConfigDir } from "../confi
7
7
  import { hashJson } from "../config/hash.ts";
8
8
  import { Json } from "../config/json.ts";
9
9
  import { migrateConfig } from "../config/migrate.ts";
10
- import type { Refusal, Result } from "../config/refusal.ts";
10
+ import { noGitIdentity, type Refusal, type Result } from "../config/refusal.ts";
11
11
  import { Kind, READABLE_SCHEMA_VERSIONS, SCHEMA_VERSION } from "../config/schema.ts";
12
12
  import { ciWorkflows } from "../service/workflows.ts";
13
13
  import { renderUnit, type UnitKind } from "../service/unit.ts";
@@ -63,17 +63,15 @@ const schemaRefusal = (existing: Json | undefined, target: number): Refusal | un
63
63
  return migrated && !migrated.ok ? { ...migrated.refusal, message: `${migrated.refusal.message} Nothing was written.` } : undefined;
64
64
  };
65
65
 
66
- const noGitIdentity = (missing: readonly string[]): Refusal => ({
67
- code: "no-git-identity",
68
- missing,
69
- message: `hum commits as you, and git config holds no ${missing.join(" or ")}. Set ${missing.length === 1 ? "it" : "each"}, then run setup again: ${missing.map((key) => `git config --global ${key} "<yours>"`).join("; ")}. Nothing was written.`,
70
- });
71
-
72
66
  /** The identity hum.json already holds, else the one git config holds, else the refusal that says what to set. */
73
67
  const identityOf = (hum: Readonly<Record<string, Json>>, git: GitIdentityRead): Result<Json> => {
74
68
  if (hum.commitIdentity !== undefined) return { ok: true, value: hum.commitIdentity };
75
69
 
76
- return git.found ? { ok: true, value: asJson(git.identity) } : { ok: false, refusal: noGitIdentity(git.missing) };
70
+ if (git.found) return { ok: true, value: asJson(git.identity) };
71
+
72
+ const refusal = noGitIdentity(git.missing);
73
+
74
+ return { ok: false, refusal: { ...refusal, message: `${refusal.message} Nothing was written.` } };
77
75
  };
78
76
 
79
77
  const readExisting = (repo: string): RawConfig | undefined => (existsSync(join(repo, ".hum", "hum.json")) ? readConfigDir(join(repo, ".hum")) : undefined);
@@ -114,7 +112,8 @@ export const writeSetup = (repo: string, answers: SetupAnswers, env: SetupEnv):
114
112
  if (!identity.ok) return identity;
115
113
 
116
114
  const hum = { ...given, commitIdentity: identity.value };
117
- const kinds = Object.fromEntries(Object.entries(withTimeouts(parseKinds(base), answers.waitHours)).map(([name, kind]) => [name, asJson(kind)]));
115
+ const timed = withTimeouts(parsedKinds(base), answers.waitHours);
116
+ const kinds = Object.fromEntries(Object.entries(base.kinds).map(([name, file]) => [name, timed[name] ? asJson(timed[name]) : file]));
118
117
  const roles = { ...shipped.roles, ...existing?.roles };
119
118
  const loaded = loadConfig({ hum: asJson(hum), kinds, roles }, { env: { hopeSkills: env.hopeSkills } });
120
119
 
@@ -135,7 +134,15 @@ export const writeSetup = (repo: string, answers: SetupAnswers, env: SetupEnv):
135
134
  return { ok: true, written: files.map(({ path }) => path), config: loaded.value };
136
135
  };
137
136
 
138
- const parseKinds = (raw: RawConfig): Record<string, Kind> => Object.fromEntries(Object.entries(raw.kinds).map(([name, file]) => [name, Kind.parse(file)]));
137
+ /** The kind files that parse. One that does not stays as it is, so the config check refuses it by name. */
138
+ const parsedKinds = (raw: RawConfig): Record<string, Kind> =>
139
+ Object.fromEntries(
140
+ Object.entries(raw.kinds).flatMap(([name, file]) => {
141
+ const kind = Kind.safeParse(file);
142
+
143
+ return kind.success ? [[name, kind.data]] : [];
144
+ }),
145
+ );
139
146
 
140
147
  const serviceFile = (repo: string, config: Config, env: SetupEnv): FileToWrite => {
141
148
  const kind: UnitKind = (env.platform ?? process.platform) === "darwin" ? "launchd" : "systemd";