@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
@@ -0,0 +1,97 @@
1
+ import { stringify } from "yaml";
2
+ import { CLAUDE_FLOOR } from "../adapters/claude-p.ts";
3
+ import type { HumConfig } from "../config/schema.ts";
4
+
5
+ /** The settings the workflows are built from. */
6
+ export type WorkflowSettings = Pick<HumConfig, "runBranchPrefix" | "itemsDir" | "ciSchedule" | "commitIdentity" | "ciWakeTimeoutMinutes" | "pullRequestTokenSecret">;
7
+
8
+ export const WAKE_FILE = "hum-wake.yml";
9
+
10
+ /** The type of the `repository_dispatch` event a tracker's webhook sends. */
11
+ export const DISPATCH_EVENT = "hum-wake";
12
+
13
+ const WAKE_PATH = `./.github/workflows/${WAKE_FILE}`;
14
+
15
+ const TOKEN_SECRET = "CLAUDE_CODE_OAUTH_TOKEN";
16
+
17
+ const HOPE_MARKETPLACE = "saadshahd/moo.md";
18
+
19
+ /** The Bun that builds the workflows is the one the owner's repo runs, so CI installs with the same lockfile reader. */
20
+ const BUN_VERSION = Bun.version;
21
+
22
+ const ACTIONS = { checkout: "actions/checkout@v4", setupBun: "oven-sh/setup-bun@v2" } as const;
23
+
24
+ const PERMISSIONS = { contents: "write", issues: "write", "pull-requests": "write" } as const;
25
+
26
+ /** One wake at a time: a second event waits for the first run instead of racing it. */
27
+ const CONCURRENCY = { group: "hum-wake", "cancel-in-progress": false } as const;
28
+
29
+ /** The events a trigger workflow starts on. */
30
+ type TriggerEvents = {
31
+ readonly issue_comment?: { readonly types: readonly string[] };
32
+ readonly push?: { readonly branches: readonly string[]; readonly paths: readonly string[] };
33
+ readonly repository_dispatch?: { readonly types: readonly string[] };
34
+ readonly schedule?: readonly { readonly cron: string }[];
35
+ readonly workflow_dispatch?: null;
36
+ };
37
+
38
+ type TriggerJob = { readonly if?: string };
39
+
40
+ /** A workflow that only chooses what starts the shared wake job. */
41
+ const trigger = (name: string, on: TriggerEvents, job: TriggerJob = {}) => ({
42
+ name,
43
+ on,
44
+ permissions: PERMISSIONS,
45
+ concurrency: CONCURRENCY,
46
+ jobs: { wake: { ...job, uses: WAKE_PATH, secrets: "inherit" } },
47
+ });
48
+
49
+ /**
50
+ * The job every wake runs. A run clones the repo again into a temp folder, so the git credentials and identity are
51
+ * global: the checkout's own are local to its workspace. A run that needs the owner has pushed its run branch, asked
52
+ * on the item and ended; the owner's answer starts a fresh run on that branch, so no session, artifact or approval
53
+ * is kept between runs.
54
+ */
55
+ const wake = ({ commitIdentity, ciWakeTimeoutMinutes, pullRequestTokenSecret }: WorkflowSettings) => ({
56
+ name: "hum wake",
57
+ on: { workflow_call: { secrets: { [TOKEN_SECRET]: { required: true }, [pullRequestTokenSecret]: { required: false } } } },
58
+ permissions: PERMISSIONS,
59
+ jobs: {
60
+ wake: {
61
+ "runs-on": "ubuntu-latest",
62
+ "timeout-minutes": ciWakeTimeoutMinutes,
63
+ env: {
64
+ [TOKEN_SECRET]: `\${{ secrets.${TOKEN_SECRET} }}`,
65
+ GH_TOKEN: `\${{ secrets.${pullRequestTokenSecret} || github.token }}`,
66
+ HUM_EVENT: "${{ github.event_name }}",
67
+ },
68
+ steps: [
69
+ { uses: ACTIONS.checkout, with: { "fetch-depth": 0 } },
70
+ { uses: ACTIONS.setupBun, with: { "bun-version": BUN_VERSION } },
71
+ { run: "bun install --frozen-lockfile" },
72
+ { run: `npm install --global @anthropic-ai/claude-code@${CLAUDE_FLOOR}` },
73
+ { run: `claude plugin marketplace add ${HOPE_MARKETPLACE}\nclaude plugin install hope@moo.md\n` },
74
+ { run: "gh auth setup-git" },
75
+ {
76
+ run: 'git config --global user.name "$HUM_GIT_NAME"\ngit config --global user.email "$HUM_GIT_EMAIL"\n',
77
+ env: { HUM_GIT_NAME: commitIdentity.name, HUM_GIT_EMAIL: commitIdentity.email },
78
+ },
79
+ { run: './node_modules/.bin/hum wake --event "$HUM_EVENT"' },
80
+ ],
81
+ },
82
+ },
83
+ });
84
+
85
+ const WORKFLOWS = {
86
+ [WAKE_FILE]: wake,
87
+ "hum-comment.yml": () => trigger("hum on comment", { issue_comment: { types: ["created"] } }, { if: "github.event.comment.user.type != 'Bot'" }),
88
+ "hum-push.yml": ({ itemsDir, runBranchPrefix }) => trigger("hum on item push", { push: { branches: ["**", `!${runBranchPrefix}**`], paths: [`${itemsDir}/**`] } }),
89
+ "hum-dispatch.yml": () => trigger("hum on dispatch", { repository_dispatch: { types: [DISPATCH_EVENT] } }),
90
+ "hum-schedule.yml": ({ ciSchedule }) => trigger("hum on schedule", { schedule: [{ cron: ciSchedule }], workflow_dispatch: null }),
91
+ } as const satisfies Record<string, (settings: WorkflowSettings) => object>;
92
+
93
+ export type WorkflowFile = { readonly file: string; readonly text: string };
94
+
95
+ /** The workflow files for an owner's repo, each named for `.github/workflows/`. */
96
+ export const ciWorkflows = (settings: WorkflowSettings): WorkflowFile[] =>
97
+ Object.entries(WORKFLOWS).map(([file, build]) => ({ file, text: stringify(build(settings), { lineWidth: 0 }) }));
@@ -0,0 +1,120 @@
1
+ import type { Item } from "../adapter-api.ts";
2
+ import { declaredKind } from "../decide/kind.ts";
3
+ import { usualSize } from "../decide/risk.ts";
4
+ import type { DefaultsConfig, HumConfig, PathRule, RunPlace, SlotRecipe } from "../config/schema.ts";
5
+ import type { CiJob, RepoScan } from "./scan.ts";
6
+ import {
7
+ CHECK_COMMAND,
8
+ CHECK_SCRIPTS,
9
+ DATA_AND_SECRET_GLOBS,
10
+ DEFAULT_FOLDER_RANK,
11
+ FOLDER_RANKS,
12
+ INSTALL_COMMANDS,
13
+ KIND_LABEL_WORDS,
14
+ NOT_A_CHECK,
15
+ ROOT_MARKDOWN_RANK,
16
+ RUN_SCRIPT,
17
+ SECRET_TEMPLATE,
18
+ } from "./tables.ts";
19
+
20
+ /** The settings setup proposes from a scan; the owner changes any of them before they are written. */
21
+ export type Proposal = {
22
+ readonly checks: readonly string[];
23
+ readonly paths: readonly PathRule[];
24
+ readonly strictPaths: readonly string[];
25
+ /** The top of each folder's usual size; undefined while it has too few merged changes to have one. */
26
+ readonly usualSizes: readonly { readonly folder: string; readonly usual: number | undefined }[];
27
+ readonly windows: Pick<HumConfig["changeLabels"], "fixWindow"> & Pick<HumConfig, "measureWindow">;
28
+ readonly kindLabels: Readonly<Record<string, string>>;
29
+ readonly runSlots: Pick<HumConfig["runSlots"], "services" | "recipe">;
30
+ readonly runPlaces: readonly RunPlace[];
31
+ };
32
+
33
+ const isPullRequestJob = ({ triggers }: CiJob): boolean => triggers.includes("pull_request");
34
+
35
+ const isCheck = (command: string): boolean => CHECK_COMMAND.test(command) && !NOT_A_CHECK.test(command);
36
+
37
+ const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];
38
+
39
+ const scriptCommand = (scan: RepoScan, script: string): string | undefined => {
40
+ const run = scan.packageManager === undefined ? undefined : RUN_SCRIPT[scan.packageManager];
41
+
42
+ return run !== undefined && script in scan.scripts ? `${run} ${script}` : undefined;
43
+ };
44
+
45
+ /**
46
+ * The commands the repo's own CI runs on a pull request to check a change; else its package scripts that check.
47
+ * A run checks a fresh clone, which has no dependencies yet, so the lockfile install comes first.
48
+ */
49
+ export const checksOf = (scan: RepoScan): string[] => {
50
+ const fromCi = unique(scan.ci.filter(isPullRequestJob).flatMap(({ commands }) => commands.filter(isCheck)));
51
+ const checks = fromCi.length > 0 ? fromCi : CHECK_SCRIPTS.flatMap((script) => scriptCommand(scan, script) ?? []);
52
+
53
+ return scan.packageManager === undefined || checks.length === 0 ? checks : [INSTALL_COMMANDS[scan.packageManager], ...checks];
54
+ };
55
+
56
+ const levelAt = (levels: HumConfig["levels"], rank: number): string => levels[Math.min(rank, levels.length - 1)]?.name ?? "";
57
+
58
+ const rankOfFolder = (folder: string): number => FOLDER_RANKS.find((row) => row.folder.test(folder))?.rank ?? DEFAULT_FOLDER_RANK;
59
+
60
+ const topFolders = (tracked: readonly string[]): string[] => unique(tracked.flatMap((path) => (path.includes("/") ? [path.split("/")[0] ?? ""] : []))).sort();
61
+
62
+ /** A rule per top-level folder, one for markdown at the root and one for the other root files, so no path is left unplaced. */
63
+ export const pathRulesOf = (tracked: readonly string[], levels: HumConfig["levels"]): PathRule[] => [
64
+ ...topFolders(tracked).map((folder) => ({ glob: `${folder}/**`, level: levelAt(levels, rankOfFolder(folder)) })),
65
+ { glob: "*.md", level: levelAt(levels, ROOT_MARKDOWN_RANK) },
66
+ { glob: "*", level: levelAt(levels, DEFAULT_FOLDER_RANK) },
67
+ ];
68
+
69
+ /** The data and secrets globs that match a tracked file; a file that only shows the shape of a secret does not count. */
70
+ export const strictGlobsOf = (tracked: readonly string[]): string[] =>
71
+ DATA_AND_SECRET_GLOBS.filter((glob) => tracked.some((path) => new Bun.Glob(glob).match(path) && !SECRET_TEMPLATE.test(path)));
72
+
73
+ const mapLabels = (labels: readonly string[], kinds: readonly string[]): Record<string, string> =>
74
+ Object.fromEntries(
75
+ unique(labels.map((label) => label.toLowerCase())).flatMap((label) => {
76
+ const kind = Object.entries(KIND_LABEL_WORDS).find(([name, words]) => kinds.includes(name) && new Set<string>(words).has(label))?.[0];
77
+
78
+ return kind === undefined || kinds.includes(label) ? [] : [[label, kind]];
79
+ }),
80
+ );
81
+
82
+ /** Label → kind for the labels the repo uses: those on its issue templates and the ones it lists. A label the table does not know is left out. */
83
+ export const kindLabelsOf = (scan: RepoScan, repoLabels: readonly string[], kinds: readonly string[]): Record<string, string> =>
84
+ mapLabels([...scan.issueTemplates.flatMap(({ labels }) => labels), ...repoLabels], kinds);
85
+
86
+ /** How many of the open items name their kind through the map, a kind's own name or a template field. */
87
+ export const kindCoverage = (items: readonly Pick<Item, "body" | "labels">[], kinds: readonly string[], kindLabels: HumConfig["kindLabels"]) => ({
88
+ covered: items.filter((item) => declaredKind(item, kinds, kindLabels) !== undefined).length,
89
+ total: items.length,
90
+ });
91
+
92
+ const recipeOf = (scan: RepoScan, checks: readonly string[]): SlotRecipe => {
93
+ const install = scan.packageManager === undefined ? [] : [INSTALL_COMMANDS[scan.packageManager]];
94
+ const [script] = scan.envScripts;
95
+ const seed = scriptCommand(scan, "seed");
96
+ const services = scan.composeServices.length > 0 ? ['docker compose -p "$COMPOSE_PROJECT_NAME" up -d --wait'] : [];
97
+ const [fast] = checks.filter((command) => /\b(lint|typecheck|check)\b/.test(command));
98
+
99
+ return {
100
+ prepare: script === undefined ? [...install, ...services, ...(seed ? [seed] : [])] : [`./${script}`],
101
+ refresh: script === undefined ? install.map((run) => ({ run, when: "lockfile-changed" as const })) : [{ run: `./${script}`, when: "lockfile-changed" as const }],
102
+ ready: [fast ?? checks[0]].flatMap((command) => command ?? []),
103
+ };
104
+ };
105
+
106
+ /** Everything setup proposes from a scan, before it asks. */
107
+ export const proposeSetup = (scan: RepoScan, shipped: DefaultsConfig, repoLabels: readonly string[] = []): Proposal => {
108
+ const checks = checksOf(scan);
109
+
110
+ return {
111
+ checks,
112
+ paths: pathRulesOf(scan.tracked, shipped.levels),
113
+ strictPaths: strictGlobsOf(scan.tracked),
114
+ usualSizes: scan.folders.map(({ folder, sizes }) => ({ folder, usual: usualSize(sizes, shipped.sizeRange) })),
115
+ windows: { fixWindow: shipped.changeLabels.fixWindow, measureWindow: shipped.measureWindow },
116
+ kindLabels: kindLabelsOf(scan, repoLabels, shipped.kinds),
117
+ runSlots: { services: shipped.runSlots.services, recipe: recipeOf(scan, checks) },
118
+ runPlaces: shipped.runPlaces,
119
+ };
120
+ };
@@ -0,0 +1,216 @@
1
+ import { mkdtempSync, readFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { z } from "zod";
5
+ import type { AdapterContext } from "../adapter-api.ts";
6
+ import { runContract } from "../adapters/contract.ts";
7
+ import { markdownAdapter } from "../adapters/markdown.ts";
8
+ import { type Config, loadConfig, readConfigDir } from "../config/load.ts";
9
+ import { commandTimeoutMs, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
10
+ import { SlotPool } from "../slots/pool.ts";
11
+ import { orMissing } from "../state/fs.ts";
12
+ import { openState } from "../state/open.ts";
13
+ import { checksTimeoutMs, runChecks } from "../worker/checks.ts";
14
+ import { openWorker } from "../worker/open.ts";
15
+ import { Scratch } from "./scratch.ts";
16
+
17
+ export type StepStatus = "passed" | "failed" | "skipped";
18
+
19
+ /** One thing setup proved, with how long it took. A skip says why, so nothing passes silently. */
20
+ export type Step = { readonly name: string; readonly status: StepStatus; readonly detail: string; readonly ms: number };
21
+
22
+ type Outcome = { readonly status: StepStatus; readonly detail: string };
23
+
24
+ const passed = (detail: string): Outcome => ({ status: "passed", detail });
25
+
26
+ const failed = (detail: string): Outcome => ({ status: "failed", detail });
27
+
28
+ const skipped = (detail: string): Outcome => ({ status: "skipped", detail });
29
+
30
+ /** Runs one step; a throw is the step failing, in the error's own words. */
31
+ const stepOf = (name: string, outcome: Outcome, started: number): Step => ({ name, status: outcome.status, detail: outcome.detail, ms: Math.round(performance.now() - started) });
32
+
33
+ const timed = async (name: string, run: () => Promise<Outcome>): Promise<Step> => {
34
+ const started = performance.now();
35
+
36
+ return stepOf(name, await run().catch((error: Error) => failed(error.message)), started);
37
+ };
38
+
39
+ export type ProveEnv = {
40
+ readonly hopeSkills: ReadonlySet<string>;
41
+ readonly base: string;
42
+ /** Whether to run one item end to end through the real `claude`; each run spends live calls. */
43
+ readonly item: boolean;
44
+ /** Reads the registry for the pinned engine: the package's versions, or undefined while it is not published. */
45
+ readonly published?: (pin: string) => Promise<"found" | "missing-version" | "unpublished">;
46
+ };
47
+
48
+ const Manifest = z.looseObject({
49
+ dependencies: z.record(z.string(), z.string()).default({}),
50
+ devDependencies: z.record(z.string(), z.string()).default({}),
51
+ });
52
+
53
+ const ENGINE = "@moo.md/hum";
54
+
55
+ /** A pin that is a folder or tarball on disk rather than a registry version. */
56
+ const LOCAL_PIN = /^(file|link):/;
57
+
58
+ /** 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"> => {
60
+ const viewed = await exec("npm", ["view", `${ENGINE}@${pin}`, "version"], { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
61
+
62
+ if (viewed.exitCode === 0) return "found";
63
+
64
+ const package_ = await exec("npm", ["view", ENGINE, "name"], { throwOnError: false, timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
65
+
66
+ return package_.exitCode === 0 ? "missing-version" : "unpublished";
67
+ };
68
+
69
+ const pinOf = (repo: string): string | undefined => {
70
+ const manifest = Manifest.parse(orMissing(() => JSON.parse(readFileSync(join(repo, "package.json"), "utf8")), {}));
71
+
72
+ return { ...manifest.dependencies, ...manifest.devDependencies }[ENGINE];
73
+ };
74
+
75
+ const configStep = (repo: string, env: ProveEnv): Outcome & { readonly config?: Config } => {
76
+ const loaded = loadConfig(readConfigDir(join(repo, ".hum")), { env: { hopeSkills: env.hopeSkills } });
77
+
78
+ return loaded.ok ? { ...passed("every state is reachable, reaches done or stuck, and every wait has a timeout"), config: loaded.value } : failed(loaded.refusal.message);
79
+ };
80
+
81
+ const checksStep = async (repo: string, config: Config): Promise<Outcome> => {
82
+ if (config.hum.checks.length === 0) return failed('hum.json names no checks: set "checks"');
83
+
84
+ for (const check of config.hum.checks) {
85
+ const failure = await runChecks([check], repo, { timeoutMs: checksTimeoutMs(config.hum) });
86
+
87
+ if (failure) return failed(failure);
88
+ }
89
+
90
+ return passed(`${config.hum.checks.length} check(s), each run alone`);
91
+ };
92
+
93
+ const markdownOver = (repo: string, base: string, hum: Config["hum"], context: AdapterContext) =>
94
+ 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
+
96
+ const contractStep = async (config: Config, scratch: Scratch, base: string): Promise<Outcome> => {
97
+ const others = Object.entries(config.hum.integrations ?? {}).filter(([, adapter]) => adapter !== "markdown");
98
+
99
+ if (others.length > 0) return skipped(`${others.map(([slot, adapter]) => `${slot}: ${adapter}`).join(", ")} write to a live target; run its contract suite there`);
100
+
101
+ let skew = 0;
102
+ let count = 0;
103
+
104
+ const context: AdapterContext = { report: () => {}, now: () => Date.now() + skew };
105
+ const first = markdownOver(await scratch.worker(), base, config.hum, context);
106
+ const second = markdownOver(await scratch.worker(), base, config.hum, context);
107
+
108
+ const results = await runContract({
109
+ name: "markdown",
110
+ adapter: first,
111
+ other: async () => second,
112
+ seed: (title) => scratch.seed(`contract-${++count}`, title, "body"),
113
+ advance: async (ms) => void (skew += ms),
114
+ spent: () => first.spent(),
115
+ });
116
+
117
+ const broken = results.filter(({ failure }) => failure !== undefined);
118
+
119
+ return broken.length === 0 ? passed(`${results.length} contract checks on the markdown source`) : failed(broken.map(({ name, failure }) => `${name}: ${failure}`).join("\n"));
120
+ };
121
+
122
+ const pinStep = async (repo: string, env: ProveEnv): Promise<Outcome> => {
123
+ const pin = pinOf(repo);
124
+
125
+ if (pin === undefined) return failed(`package.json pins no ${ENGINE}: run bun add --exact ${ENGINE}@<version>`);
126
+
127
+ if (LOCAL_PIN.test(pin)) return passed(`${ENGINE} is pinned to ${pin}, a path on this machine`);
128
+
129
+ const found = await (env.published ?? npmPublished)(pin);
130
+
131
+ if (found === "found") return passed(`${ENGINE}@${pin} is on the registry, so each runner installs it`);
132
+
133
+ return found === "unpublished" ? skipped(`${ENGINE} is not published yet, so no runner can install it; run this step again after the first publish`) : failed(`${ENGINE}@${pin} is not on the registry`);
134
+ };
135
+
136
+ const slotStep = async (config: Config, scratch: Scratch, env: ProveEnv): Promise<Outcome> => {
137
+ if (!config.hum.runSlots.enabled) return skipped("run slots are off in hum.json");
138
+
139
+ 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 });
142
+ const started = performance.now();
143
+
144
+ await slots.maintain();
145
+
146
+ const [slot] = slots.list();
147
+ const cards = state.faults.list().map(({ cause }) => cause);
148
+
149
+ return slot?.status === "free" ? passed(`one slot prepared and ready in ${Math.round(performance.now() - started)} ms`) : failed(`the slot ended ${slot?.status ?? "missing"}: ${cards.join("; ")}`);
150
+ };
151
+
152
+ const SETUP_ITEM = { id: "hum-setup-proof", title: "Add a file named hum-setup-proof.md that says hello", body: "Kind: docs\n\nAdd a file named hum-setup-proof.md at the repo root with the single line: hello." } as const;
153
+
154
+ /** The item runs on a copy of its own, since the contract suite leaves ready items on the copy it used. */
155
+ const itemStep = async (repo: string, config: Config, env: ProveEnv): Promise<Outcome> => {
156
+ if (!env.item) return skipped("run without --item: no live run was made");
157
+
158
+ if (Bun.which("claude") === null) return skipped("claude is not installed on this machine");
159
+
160
+ const scratch = await Scratch.from(repo, env.base, config.hum);
161
+
162
+ try {
163
+ return await runItem(scratch, env);
164
+ } finally {
165
+ scratch.dispose();
166
+ }
167
+ };
168
+
169
+ const runItem = async (scratch: Scratch, env: ProveEnv): Promise<Outcome> => {
170
+ await scratch.seed(SETUP_ITEM.id, SETUP_ITEM.title, SETUP_ITEM.body);
171
+
172
+ const results: string[] = [];
173
+
174
+ const worker = await openWorker(scratch.owner, {
175
+ hopeSkills: env.hopeSkills,
176
+ holder: "setup-proof",
177
+ base: env.base,
178
+ where: "ci",
179
+ stateDir: mkdtempSync(join(tmpdir(), "hum-prove-state-")),
180
+ workDir: mkdtempSync(join(tmpdir(), "hum-prove-work-")),
181
+ onResult: (result) => results.push(result.outcome),
182
+ });
183
+
184
+ await worker.tick();
185
+ await worker.idle();
186
+
187
+ return results.includes("merged") ? passed("one item ran end to end and merged") : failed(`the item ended as ${results.join(", ") || "nothing"}`);
188
+ };
189
+
190
+ /**
191
+ * Proves a written setup: the config passes every check, each repo check passes alone, the markdown source passes its
192
+ * contract suite on a scratch copy, the pinned engine is installable, one slot is ready, and one item runs end to end
193
+ * on the scratch copy. Each part is its own step, so one failing hides no other.
194
+ */
195
+ export const proveSetup = async (repo: string, env: ProveEnv): Promise<Step[]> => {
196
+ const started = performance.now();
197
+ const { config, ...outcome } = configStep(repo, env);
198
+ const configured = stepOf("config", outcome, started);
199
+
200
+ if (!config) return [configured];
201
+
202
+ const scratch = await Scratch.from(repo, env.base, config.hum);
203
+
204
+ try {
205
+ return [
206
+ configured,
207
+ await timed("checks", () => checksStep(repo, config)),
208
+ await timed("contract", () => contractStep(config, scratch, env.base)),
209
+ await timed("engine pin", () => pinStep(repo, env)),
210
+ await timed("slot", () => slotStep(config, scratch, env)),
211
+ await timed("item", () => itemStep(repo, config, env)),
212
+ ];
213
+ } finally {
214
+ scratch.dispose();
215
+ }
216
+ };
@@ -0,0 +1,186 @@
1
+ import { accessSync, constants, readFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { z } from "zod";
5
+ import { gitIn } from "../adapters/git.ts";
6
+ import { readHistory } from "../adapters/history.ts";
7
+ import { SHIPPED_DEFAULTS } from "../config/schema.ts";
8
+ import { SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
9
+ import { orMissing } from "../state/fs.ts";
10
+ import { ENV_SCRIPTS } from "../slots/scan.ts";
11
+ import {
12
+ CODEOWNERS_FILES,
13
+ COMPOSE_FILES,
14
+ ENV_EXAMPLE_FILES,
15
+ ENV_TOOLING_FILES,
16
+ ISSUE_TEMPLATE_FOLDER,
17
+ LOCKFILES,
18
+ type PackageManager,
19
+ SETUP_TARGETS,
20
+ TOOL_VERSION_FILES,
21
+ TRACKED_FILE_LIMIT,
22
+ WORKFLOW_FOLDER,
23
+ } from "./tables.ts";
24
+
25
+ /** One job of a CI workflow: when it runs and the shell commands its steps run. */
26
+ export type CiJob = { readonly file: string; readonly job: string; readonly triggers: readonly string[]; readonly commands: readonly string[] };
27
+
28
+ export type FolderHistory = { readonly folder: string; readonly changes: number; readonly sizes: readonly number[] };
29
+
30
+ /** What a repo already holds that setup reads before it asks. */
31
+ export type RepoScan = {
32
+ readonly packageManager: PackageManager | undefined;
33
+ readonly scripts: Readonly<Record<string, string>>;
34
+ readonly ci: readonly CiJob[];
35
+ readonly codeowners: readonly { readonly glob: string; readonly owners: readonly string[] }[];
36
+ readonly composeServices: readonly { readonly name: string; readonly image: string | undefined }[];
37
+ readonly envScripts: readonly string[];
38
+ readonly setupTargets: readonly string[];
39
+ readonly toolVersions: readonly string[];
40
+ readonly envExamples: readonly string[];
41
+ readonly envTooling: readonly string[];
42
+ readonly issueTemplates: readonly { readonly file: string; readonly labels: readonly string[] }[];
43
+ readonly tracked: readonly string[];
44
+ readonly folders: readonly FolderHistory[];
45
+ /** The engine version `package.json` pins, and the schema version `.hum/hum.json` has. */
46
+ readonly engine: { readonly pinned: string | undefined };
47
+ readonly hum: { readonly schemaVersion: number | undefined };
48
+ };
49
+
50
+ const textOf = (repo: string, path: string): string => (path === "" ? "" : orMissing(() => readFileSync(join(repo, path), "utf8"), ""));
51
+
52
+ const exists = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path)), true), false);
53
+
54
+ const isRunnable = (repo: string, path: string): boolean => orMissing(() => (accessSync(join(repo, path), constants.X_OK), true), false);
55
+
56
+ const filesIn = (repo: string, pattern: string): string[] => [...new Bun.Glob(pattern).scanSync({ cwd: repo, onlyFiles: true, dot: true })].sort();
57
+
58
+ const PackageJson = z.looseObject({
59
+ scripts: z.record(z.string(), z.string()).default({}),
60
+ dependencies: z.record(z.string(), z.string()).default({}),
61
+ devDependencies: z.record(z.string(), z.string()).default({}),
62
+ });
63
+
64
+ const Workflow = z.looseObject({
65
+ on: z.union([z.string().transform((trigger) => [trigger]), z.array(z.string()), z.record(z.string(), z.unknown()).transform((triggers) => Object.keys(triggers))]).default([]),
66
+ jobs: z.record(z.string(), z.looseObject({ steps: z.array(z.looseObject({ run: z.string().optional() })).default([]) })).default({}),
67
+ });
68
+
69
+ const Compose = z.looseObject({ services: z.record(z.string(), z.looseObject({ image: z.string().optional() })).default({}) });
70
+
71
+ const Template = z.looseObject({ labels: z.union([z.string(), z.array(z.string())]).default([]) });
72
+
73
+ const TEMPLATE_FRONT_MATTER = /^---\n([\s\S]*?)\n---/;
74
+
75
+ const commandsOf = (run: string): string[] =>
76
+ run
77
+ .split("\n")
78
+ .map((line) => line.trim())
79
+ .filter((line) => line !== "" && !line.startsWith("#"));
80
+
81
+ /** The CI workflows' jobs. A workflow that does not parse is skipped, because the owner's CI is not setup's to judge. */
82
+ const ciJobsOf = (repo: string): CiJob[] =>
83
+ filesIn(repo, `${WORKFLOW_FOLDER}/*.{yml,yaml}`).flatMap((file) => {
84
+ const parsed = Workflow.safeParse(parseYaml(textOf(repo, file)));
85
+
86
+ if (!parsed.success) return [];
87
+
88
+ const triggers = parsed.data.on;
89
+
90
+ return Object.entries(parsed.data.jobs).map(([job, { steps }]) => ({
91
+ file: basename(file),
92
+ job,
93
+ triggers,
94
+ commands: steps.flatMap((step) => commandsOf(step.run ?? "")),
95
+ }));
96
+ });
97
+
98
+ const codeownersOf = (repo: string): RepoScan["codeowners"] => {
99
+ const file = CODEOWNERS_FILES.find((candidate) => exists(repo, candidate));
100
+
101
+ return textOf(repo, file ?? "")
102
+ .split("\n")
103
+ .map((line) => line.replace(/#.*/, "").trim().split(/\s+/))
104
+ .flatMap(([glob, ...owners]) => (glob === undefined || glob === "" || owners.length === 0 ? [] : [{ glob, owners }]));
105
+ };
106
+
107
+ 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 ?? "")));
110
+
111
+ return parsed.success ? Object.entries(parsed.data.services).map(([name, { image }]) => ({ name, image })) : [];
112
+ };
113
+
114
+ /** The environment scripts a repo is built to run: executable files in the usual places. */
115
+ const envScriptsOf = (repo: string): string[] => ENV_SCRIPTS.filter((script) => isRunnable(repo, script));
116
+
117
+ /** Makefile and justfile targets, and package scripts, that set up or seed an environment. */
118
+ const setupTargetsOf = (repo: string, scripts: Readonly<Record<string, string>>): string[] => {
119
+ const targets = ["Makefile", "justfile"].flatMap((file) => [...textOf(repo, file).matchAll(/^([\w:.-]+):/gm)].map(([, target]) => target ?? ""));
120
+
121
+ const wanted = new Set<string>(SETUP_TARGETS);
122
+
123
+ return [...new Set([...Object.keys(scripts), ...targets])].filter((target) => wanted.has(target));
124
+ };
125
+
126
+ const templatesOf = (repo: string): RepoScan["issueTemplates"] =>
127
+ filesIn(repo, `${ISSUE_TEMPLATE_FOLDER}/*`).flatMap((file) => {
128
+ const text = textOf(repo, file);
129
+ const front = file.endsWith(".md") ? TEMPLATE_FRONT_MATTER.exec(text)?.[1] ?? "" : text;
130
+ const parsed = Template.safeParse(parseYaml(front));
131
+
132
+ return parsed.success ? [{ file: basename(file), labels: [parsed.data.labels].flat().flatMap((label) => label.split(",").map((one) => one.trim()).filter(Boolean)) }] : [];
133
+ });
134
+
135
+ 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);
136
+
137
+ const topFolder = (path: string): string => (path.includes("/") ? (path.split("/")[0] ?? path) : "");
138
+
139
+ /** Each top-level folder's merged changes on the base, from the history setup reads. */
140
+ const foldersOf = async (repo: string, base: string): Promise<FolderHistory[]> => {
141
+ const git = gitIn(repo, { timeoutMs: SHIPPED_COMMAND_TIMEOUT_MS });
142
+ const log = await git.run(["rev-parse", "--verify", "-q", base]);
143
+
144
+ if (log.code !== 0) return [];
145
+
146
+ const changes = await readHistory(git, base, SHIPPED_DEFAULTS);
147
+ const folders = new Map<string, number[]>();
148
+
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
+ }
152
+
153
+ return [...folders].map(([folder, sizes]) => ({ folder, changes: sizes.length, sizes: sizes.toReversed() }));
154
+ };
155
+
156
+ const humSchemaOf = (repo: string): number | undefined => {
157
+ const parsed = z.looseObject({ schemaVersion: z.number().optional() }).safeParse(orMissing(() => JSON.parse(textOf(repo, ".hum/hum.json") || "null"), null));
158
+
159
+ return parsed.success ? parsed.data.schemaVersion : undefined;
160
+ };
161
+
162
+ /** Reads the repo's package manager, CI, scripts, owners, services, environment tooling, issue templates and per-folder history. */
163
+ export const scanRepo = async (repo: string, base: string): Promise<RepoScan> => {
164
+ const manifest = PackageJson.safeParse(orMissing(() => JSON.parse(textOf(repo, "package.json") || "null"), null));
165
+ const scripts = manifest.success ? manifest.data.scripts : {};
166
+ 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));
168
+
169
+ return {
170
+ packageManager: lockfile?.[1],
171
+ scripts,
172
+ ci: ciJobsOf(repo),
173
+ codeowners: codeownersOf(repo),
174
+ composeServices: composeOf(repo),
175
+ envScripts: envScriptsOf(repo),
176
+ 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)),
180
+ issueTemplates: templatesOf(repo),
181
+ tracked: await trackedOf(repo),
182
+ folders: await foldersOf(repo, base),
183
+ engine: { pinned },
184
+ hum: { schemaVersion: humSchemaOf(repo) },
185
+ };
186
+ };