@moo.md/hum 0.3.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 (67) hide show
  1. package/defaults/hum.json +5 -0
  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 +47 -7
  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 +9 -0
  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 +3 -6
  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 +4 -5
  27. package/src/config/checks.ts +21 -50
  28. package/src/config/load.ts +2 -3
  29. package/src/config/machine.ts +29 -0
  30. package/src/config/refusal.ts +5 -6
  31. package/src/config/schema.ts +23 -7
  32. package/src/config/wake-job.ts +6 -2
  33. package/src/decide/risk.ts +2 -2
  34. package/src/exec.ts +10 -0
  35. package/src/index.ts +1 -1
  36. package/src/loop/records.ts +8 -1
  37. package/src/measure/rate.ts +14 -0
  38. package/src/publish/bundle.ts +128 -0
  39. package/src/publish/handoff.ts +107 -0
  40. package/src/publish/handover.ts +182 -0
  41. package/src/publish/intents.ts +61 -0
  42. package/src/publish/publisher.ts +259 -0
  43. package/src/publish/wake.ts +78 -0
  44. package/src/service/ci-state.ts +99 -0
  45. package/src/service/plugins.ts +137 -0
  46. package/src/service/wake.ts +3 -1
  47. package/src/service/workflows.ts +122 -28
  48. package/src/setup/propose.ts +17 -4
  49. package/src/setup/prove.ts +3 -3
  50. package/src/setup/write.ts +2 -2
  51. package/src/state/items.ts +17 -8
  52. package/src/state/open.ts +20 -6
  53. package/src/state/records.ts +7 -0
  54. package/src/state/runs.ts +5 -0
  55. package/src/state/saved.ts +17 -2
  56. package/src/worker/base-check.ts +41 -13
  57. package/src/worker/checks.ts +3 -2
  58. package/src/worker/evidence.ts +72 -0
  59. package/src/worker/kind.ts +4 -7
  60. package/src/worker/land.ts +173 -81
  61. package/src/worker/merged.ts +20 -8
  62. package/src/worker/open.ts +33 -17
  63. package/src/worker/questions.ts +16 -8
  64. package/src/worker/signed-push.ts +167 -0
  65. package/src/worker/thin-path.ts +245 -133
  66. package/src/worker/worker.ts +50 -9
  67. package/surface.json +185 -56
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moo.md/hum",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "The hum engine: work items become Claude Code agent runs, the repo's checks decide what they can, and only what nothing settles becomes a question to the owner.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -29,7 +29,9 @@
29
29
  "defaults",
30
30
  "evals",
31
31
  "scripts/eval.ts",
32
- "surface.json"
32
+ "surface.json",
33
+ "release.json",
34
+ "npm-shrinkwrap.json"
33
35
  ],
34
36
  "scripts": {
35
37
  "typecheck": "test -d ../hum/node_modules || { echo \"hum-engine: the view tests import hum/mod, whose types come from hum's packages; run bun install in hum first\" >&2; exit 1; }; tsc --noEmit",
@@ -37,7 +39,9 @@
37
39
  "eval": "bun scripts/eval.ts",
38
40
  "release:check": "bun tools/release/main.ts check",
39
41
  "release:surface": "bun tools/release/main.ts surface",
42
+ "release:commit": "bun tools/release/main.ts commit",
40
43
  "lint": "oxlint src test tools/release",
44
+ "shrinkwrap": "d=$(mktemp -d) && cp package.json \"$d\" && (cd \"$d\" && npm install --package-lock-only --ignore-scripts --silent && npm shrinkwrap --silent) && cp \"$d/npm-shrinkwrap.json\" . && rm -rf \"$d\"",
41
45
  "test": "n=$(getconf _NPROCESSORS_ONLN); seq 1 $n | xargs -P $n -I{} bun test --shard={}/$n --timeout 30000 test"
42
46
  },
43
47
  "dependencies": {
package/release.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "commit": "f1231b15a3713a1eb20decc6ef455dea74cd7dae"
3
+ }
@@ -182,7 +182,12 @@
182
182
  "type": "object",
183
183
  "propertyNames": {
184
184
  "type": "string",
185
- "minLength": 1
185
+ "enum": [
186
+ "work-source",
187
+ "questions",
188
+ "answers",
189
+ "release"
190
+ ]
186
191
  },
187
192
  "additionalProperties": {
188
193
  "type": "string",
@@ -220,7 +225,7 @@
220
225
  "email"
221
226
  ],
222
227
  "additionalProperties": false,
223
- "description": "The owner's own name and email: the author and committer of every commit hum makes. Setup writes them from git config; hum ships none."
228
+ "description": "The owner's own name and email: the author and committer of every commit hum makes with git. Where the base requires signed commits, GitHub makes the commits and credits them to the account of the token hum writes with: the owner's own on a Mac; in CI, the GitHub App's bot or the account whose token pullRequestToken names. Setup writes them from git config; hum ships none."
224
229
  },
225
230
  "checks": {
226
231
  "default": [],
@@ -581,14 +586,49 @@
581
586
  "additionalProperties": false
582
587
  }
583
588
  ],
584
- "description": "Where a CI run's GitHub token comes from: { from: 'secret', secret } names a repository secret that holds a fine-grained token; { from: 'app', clientIdSecret, privateKeySecret } names the two secrets a GitHub App mints a token from each run, with the workflow's own permissions. clientIdSecret holds the App's client ID or its older App ID: the action that mints the token reads either as the same input. A pull request opened with the workflow token starts no workflows, so its required checks never run; one opened with this token does. A CI run falls back to the workflow token while the secret, or the client ID secret, is unset."
589
+ "description": "Where a CI run's GitHub token comes from: { from: 'secret', secret } names a repository secret that holds a fine-grained token; { from: 'app', clientIdSecret, privateKeySecret } names the two secrets a GitHub App mints a token from each run, with the workflow's own permissions. clientIdSecret holds the App's client ID or its older App ID: the action that mints the token reads either as the same input. A pull request opened with the workflow token starts no workflows, so its required checks never run; one opened with this token does. A CI run falls back to the workflow token while the secret is unset; a wake whose App secrets are unset stops with an error."
585
590
  },
586
591
  "ciWakeTimeoutMinutes": {
587
592
  "default": 60,
588
593
  "type": "integer",
589
594
  "exclusiveMinimum": 0,
590
595
  "maximum": 9007199254740991,
591
- "description": "Minutes a CI wake may run before GitHub stops it."
596
+ "description": "Minutes the CI wake's work job, which runs the runs, may run before GitHub stops it; the two jobs that hold GitHub's token stop within its hour."
597
+ },
598
+ "ciOutboxMaxMegabytes": {
599
+ "default": 200,
600
+ "type": "integer",
601
+ "exclusiveMinimum": 0,
602
+ "maximum": 9007199254740991,
603
+ "description": "Megabytes of a CI work job's outbox, its bundles and its state, past which publish refuses the whole wake before any write."
604
+ },
605
+ "ciUsageLimitMaxHours": {
606
+ "default": 168,
607
+ "type": "integer",
608
+ "exclusiveMinimum": 0,
609
+ "maximum": 9007199254740991,
610
+ "description": "Hours from now past which publish cuts the reset time of a usage limit a CI work job reports, so no work job can hold hum's runs longer than Claude's own limit window."
611
+ },
612
+ "followUpsPerPass": {
613
+ "default": 10,
614
+ "type": "integer",
615
+ "exclusiveMinimum": 0,
616
+ "maximum": 9007199254740991,
617
+ "description": "Follow-up items one pass may file; publish refuses a pass that files more, and each one it files counts against the daily question cap."
618
+ },
619
+ "publishTreeMaxMegabytes": {
620
+ "default": 1024,
621
+ "type": "integer",
622
+ "exclusiveMinimum": 0,
623
+ "maximum": 9007199254740991,
624
+ "description": "Megabytes of the tree a pass's branch holds, past which publish refuses the pass before it checks the branch out."
625
+ },
626
+ "ciMergeMarginMinutes": {
627
+ "default": 10,
628
+ "type": "integer",
629
+ "exclusiveMinimum": 0,
630
+ "maximum": 9007199254740991,
631
+ "description": "Minutes of the GitHub App token's hour publish keeps in hand: past the rest, it saves a landing and leaves its merge to the next wake."
592
632
  },
593
633
  "ciRunner": {
594
634
  "default": "ubuntu-latest",
@@ -639,7 +679,7 @@
639
679
  "additionalProperties": false
640
680
  }
641
681
  ],
642
- "description": "What the CI wake job runs on, as a workflow's runs-on holds it: one runner label, a list of labels the runner must carry all of, or { group, labels } for a runner group. On a public repo, a runner GitHub does not host keeps what a wake leaves on it, and setup asks before it writes one."
682
+ "description": "What each job of the CI wake runs on, as a workflow's runs-on holds it: one runner label, a list of labels the runner must carry all of, or { group, labels } for a runner group. On a public repo, a runner GitHub does not host keeps what a job leaves on it, and setup asks before it writes one."
643
683
  },
644
684
  "ciContainer": {
645
685
  "default": null,
@@ -724,7 +764,7 @@
724
764
  "type": "null"
725
765
  }
726
766
  ],
727
- "description": "The container the CI wake job runs in: its image, or { image, credentials: { username, password }, env, ports, volumes, options } as a workflow's container holds them, or null to run on the runner itself. The image needs git, node and npm; a container that runs as root needs IS_SANDBOX=1 in ciEnv, or Claude Code refuses to skip its permission prompts."
767
+ "description": "The container each job of the CI wake runs in: its image, or { image, credentials: { username, password }, env, ports, volumes, options } as a workflow's container holds them, or null to run on the runner itself. The image needs git, node and npm; a container that runs as root needs IS_SANDBOX=1 in ciEnv, or Claude Code refuses to skip its permission prompts."
728
768
  },
729
769
  "ciEnv": {
730
770
  "default": {},
@@ -736,7 +776,7 @@
736
776
  "additionalProperties": {
737
777
  "type": "string"
738
778
  },
739
- "description": "Env the CI wake job sets, such as a gateway's settings; a value may be a workflow expression. A value that reads a secret reaches only the step that runs hum; every other value reaches every step, the installs too. A name the job sets itself, such as GH_TOKEN, is refused."
779
+ "description": "Env the CI wake's jobs set, such as a gateway's settings; a value may be a workflow expression. A value that reads a secret reaches only the steps that run hum; every other value reaches every step, the installs too. A name the jobs set themselves, such as GH_TOKEN, is refused."
740
780
  },
741
781
  "ciClaudeAuth": {
742
782
  "default": "oauth-token",
package/scripts/eval.ts CHANGED
@@ -23,7 +23,7 @@ import { openState } from "../src/state/open.ts";
23
23
  import { decideProse } from "../src/worker/prose-run.ts";
24
24
  import { PROSE_PROMPTS } from "../src/worker/thin-path.ts";
25
25
  import { SECOND_MS } from "../src/time.ts";
26
- import { rateOf } from "../src/measure/rate.ts";
26
+ import { rateOf, withRate } from "../src/measure/rate.ts";
27
27
 
28
28
  /**
29
29
  * Measures one model-judgment boundary on its labelled cases, through the same prompts and fences the engine runs,
@@ -61,7 +61,21 @@ const started = await startRunner({ state, model, now: Date.now, env: process.en
61
61
  if (started.check.kind !== "finished") throw new Error(`the start check ended as ${started.check.kind}`);
62
62
 
63
63
  let calls = 1;
64
- const runner: Runner = { ...started.runner, run: (request) => (calls++, started.runner.run(request)) };
64
+ /** The model ids that answered since the boundary in hand started. */
65
+ const answered = new Set<string>();
66
+
67
+ const runner: Runner = {
68
+ ...started.runner,
69
+ run: async (request) => {
70
+ calls++;
71
+
72
+ const outcome = await started.runner.run(request);
73
+
74
+ if (outcome.kind === "finished") for (const id of outcome.models) answered.add(id);
75
+
76
+ return outcome;
77
+ },
78
+ };
65
79
  const judge = modelCallOver(runner, { model, timeoutMs: config.hum.modelCallTimeoutSeconds * SECOND_MS, trusts: () => true });
66
80
 
67
81
  /** A run that ended without an answer: a limit or a hold. It says nothing about the boundary. */
@@ -236,12 +250,12 @@ const precisionOf = ({ tp, fp }: PairCounts): number | undefined => rateOf(tp, t
236
250
  const pairRow = (day: string, pairs: PairCounts, abstained: number, used: number): string =>
237
251
  `| ${day} | ${model} | ${pairs.tp + pairs.fp + pairs.fn + pairs.tn} | ${pairs.tp} | ${pairs.fp} | ${pairs.fn} | ${pairs.tn} | ${abstained} | ${pairs.pairedBySignals} | ${rateCell(precisionOf(pairs))} | ${rateCell(rateOf(pairs.tp, pairs.tp + pairs.fn))} | ${used} |`;
238
252
 
239
- /** Sets one pooled rate in the owner's `hum.json`, where trust reads it. */
253
+ /** Sets one pooled rate in the owner's `hum.json`, where trust reads it, under the model as named and each id that answered for it. */
240
254
  const recordRate = async (folder: string, boundary: Boundary, rate: number): Promise<void> => {
241
255
  const file = join(folder, "hum.json");
242
- const written = z.looseObject({ measuredModels: z.record(z.string(), z.record(z.string(), z.number())).default({}) }).parse(JSON.parse(await Bun.file(file).text()));
256
+ const written = z.looseObject({ measuredModels: z.partialRecord(z.enum(BOUNDARIES), z.record(z.string(), z.number())).default({}) }).parse(JSON.parse(await Bun.file(file).text()));
243
257
 
244
- await Bun.write(file, `${JSON.stringify({ ...written, measuredModels: { ...written.measuredModels, [boundary]: { ...written.measuredModels[boundary], [model]: Number(rate.toFixed(2)) } } }, null, "\t")}\n`);
258
+ await Bun.write(file, `${JSON.stringify({ ...written, measuredModels: withRate(written.measuredModels, { boundary, model, answered: [...answered], rate }) }, null, "\t")}\n`);
245
259
  };
246
260
 
247
261
  const unmeasured: Boundary[] = [];
@@ -249,6 +263,8 @@ const unmeasured: Boundary[] = [];
249
263
  for (const boundary of boundaries) {
250
264
  const pool = { right: 0, measured: 0, pairs: NO_PAIRS };
251
265
 
266
+ answered.clear();
267
+
252
268
  for (let run = 1; run <= runs; run++) {
253
269
  const before = calls;
254
270
  const { verdicts, pairs = NO_PAIRS } = await BOUNDARY_RUNS[boundary]();
@@ -5,7 +5,7 @@ import type { FaultInput } from "./state/faults.ts";
5
5
  export type { FaultInput };
6
6
 
7
7
  /** Bumped on every change to the API an adapter implements; a breaking change bumps the engine's major version. */
8
- export const ADAPTER_API_VERSION = 2;
8
+ export const ADAPTER_API_VERSION = 3;
9
9
 
10
10
  /** Failure that retrying cannot fix: a reply of the wrong shape, a refused push. The engine surfaces it at once, as it does a `failed: "now"` answer. */
11
11
  export class PermanentError extends Error {
@@ -102,6 +102,8 @@ export interface WorkSource {
102
102
  comment(id: ItemId, text: string): Promise<void>;
103
103
  /** Files a ready item. Filing the same `title` from the same `from` twice returns the first item. */
104
104
  fileFollowUp(from: ItemId, followUp: FollowUp): Promise<ItemRef>;
105
+ /** Ends an item whose change merged, so `listReady` never lists it again. Ending an ended item changes nothing. */
106
+ finish(id: ItemId): Promise<void>;
105
107
  }
106
108
 
107
109
  /** Where a run's questions and the choices made without the owner land. */
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { stripVTControlCharacters } from "node:util";
5
5
  import { z } from "zod";
6
6
  import type { HumConfig } from "../config/schema.ts";
7
- import { commandTimeoutMs, exec } from "../exec.ts";
7
+ import { commandTimeoutMs, exec, withoutGitHubTokens } from "../exec.ts";
8
8
  import { listRecords, orMissing } from "../state/fs.ts";
9
9
  import type { State } from "../state/open.ts";
10
10
  import { CARD_EXCERPT, type Card } from "../status/format.ts";
@@ -184,7 +184,7 @@ export const backgroundRunner = ({ binary = "claude", env, state, config, fallba
184
184
  const jobsFolder = join(env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), JOBS_FOLDER);
185
185
 
186
186
  const claude = (args: readonly string[], options: { stdin?: string; cwd?: string } = {}) =>
187
- exec(binary, args, { stdin: options.stdin, nodePath: false, timeoutMs: commandTimeoutMs(config), nodeOptions: { cwd: options.cwd, env } });
187
+ exec(binary, args, { stdin: options.stdin, nodePath: false, timeoutMs: commandTimeoutMs(config), nodeOptions: { cwd: options.cwd, env: withoutGitHubTokens(env) } });
188
188
 
189
189
  /** The background runs Claude Code lists. A list hum cannot read throws, with one card: read as empty, it would start a run that is already going. */
190
190
  const agents = async (): Promise<Agent[]> => {
@@ -8,7 +8,7 @@ import semver from "semver";
8
8
  import { x } from "tinyexec";
9
9
  import { z } from "zod";
10
10
  import type { EFFORTS } from "../config/schema.ts";
11
- import { CommandTimedOut, type Env, exec, SHIPPED_COMMAND_TIMEOUT_MS } from "../exec.ts";
11
+ import { CommandTimedOut, type Env, exec, SHIPPED_COMMAND_TIMEOUT_MS, withoutGitHubTokens } from "../exec.ts";
12
12
  import { raiseRejectedToken, UNAUTHORIZED } from "../service/token.ts";
13
13
  import { atomicWrite, isMissing } from "../state/fs.ts";
14
14
  import type { State } from "../state/open.ts";
@@ -29,15 +29,16 @@ export const RUN_SETTINGS = JSON.stringify({
29
29
 
30
30
  /**
31
31
  * The two kinds of `claude -p` call. An agent run keeps its session. A model call runs as hope's judge does: no
32
- * session kept, no hooks, and the default output style, so the owner's style cannot reshape its answer. It also loads
33
- * no settings source (plugins, MCP servers, memory files) and no built-in tool: a question needs neither, and each
34
- * one bills on every call.
32
+ * session kept, no hooks, and the default output style, so the owner's style cannot reshape its answer. It loads the
33
+ * user's settings alone, which hold their sign-in (`apiKeyHelper`, a gateway's `env`); it runs in a temp folder, which
34
+ * holds no project settings. It loads no skill or command, no MCP server and no built-in tool: a question needs
35
+ * none, and each bills on every call. The user's CLAUDE.md does load with their settings, so a measured rate counts it.
35
36
  */
36
37
  const CALLS = {
37
38
  run: { settings: RUN_SETTINGS, flags: [] },
38
39
  judgment: {
39
40
  settings: JSON.stringify({ permissions: { defaultMode: "bypassPermissions" }, disableAllHooks: true, outputStyle: "default" }),
40
- flags: ["--no-session-persistence", "--setting-sources", "", "--tools", ""],
41
+ flags: ["--no-session-persistence", "--setting-sources", "user", "--disable-slash-commands", "--strict-mcp-config", "--tools", ""],
41
42
  },
42
43
  } as const satisfies Record<string, { settings: string; flags: readonly string[] }>;
43
44
 
@@ -318,7 +319,7 @@ export type RunnerOptions = {
318
319
  readonly binary?: string;
319
320
  /** The limit of `claude --version`, which the version floor reads, and of the start check; the owner's `commandTimeoutSeconds` in milliseconds. */
320
321
  readonly timeoutMs?: number;
321
- /** The environment `claude` runs with, the process's own from the root. An API key in it is passed on untouched. */
322
+ /** The environment `claude` runs with, the process's own from the root, without its GitHub tokens. An API key in it is passed on untouched. */
322
323
  readonly env: Env;
323
324
  readonly now: () => number;
324
325
  /** The first wait before a run that hit the refresh-lock error runs again; later waits grow from it. */
@@ -393,12 +394,9 @@ const isBelowFloor = (version: string | undefined): boolean => version === undef
393
394
 
394
395
  type Started = { readonly check: RunOutcome; readonly runner: Runner };
395
396
 
396
- /**
397
- * Runs `claude -p` as the owner's own unmodified `claude` binary, on their login, their plan token or an API key.
398
- * No run starts until the version floor and the start check pass; until then every run is held with one card.
399
- */
400
- const startChecked = async (options: RunnerOptions): Promise<Started> => {
401
- const { state, binary = "claude", env, now, lockBackoffMs = LOCK_BACKOFF_MS, timeoutMs = SHIPPED_COMMAND_TIMEOUT_MS } = options;
397
+ /** The calls of `claude -p` as the owner's own unmodified `claude` binary, on their login, their plan token or an API key, with no check made first. */
398
+ const callsOf = (options: RunnerOptions) => {
399
+ const { state, binary = "claude", env, now, lockBackoffMs = LOCK_BACKOFF_MS } = options;
402
400
  const limitedUntil = () => savedLimitUntil(state);
403
401
 
404
402
  const hold = (code: string, cause: string, fix: string): Extract<RunOutcome, { kind: "held" }> => ({
@@ -406,11 +404,6 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
406
404
  card: state.faults.raise({ code, cause, fix }),
407
405
  });
408
406
 
409
- const held = (outcome: Extract<RunOutcome, { kind: "held" }>) => ({
410
- check: outcome,
411
- runner: { run: async () => outcome, limitedUntil },
412
- });
413
-
414
407
  /** One process, read line by line. The cap is checked on every streamed message, and the process is killed the moment it is passed. */
415
408
  const spawnRun = async ({ prompt, cwd, model, effort, schema, call, name, tokenCap, signal, onFirstToken, env: runEnv }: RunRequest, sessionId: string): Promise<Ended> => {
416
409
  const stop = new AbortController();
@@ -426,7 +419,7 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
426
419
  // stderr goes to a file, so the line reader sees stdout alone: one stream cannot split another's line.
427
420
  nodeOptions: {
428
421
  cwd,
429
- env: { ...env, ...runEnv },
422
+ env: withoutGitHubTokens({ ...env, ...runEnv }),
430
423
  killSignal: "SIGKILL",
431
424
  stdio: ["pipe", "pipe", stderrFd],
432
425
  },
@@ -509,6 +502,22 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
509
502
  return outcome;
510
503
  };
511
504
 
505
+ return { hold, attempt, run, limitedUntil };
506
+ };
507
+
508
+ /**
509
+ * Runs `claude -p` as the owner's own unmodified `claude` binary. No run starts until the version floor and the start
510
+ * check pass; until then every run is held with one card.
511
+ */
512
+ const startChecked = async (options: RunnerOptions): Promise<Started> => {
513
+ const { state, binary = "claude", env, timeoutMs = SHIPPED_COMMAND_TIMEOUT_MS } = options;
514
+ const { hold, attempt, run, limitedUntil } = callsOf(options);
515
+
516
+ const held = (outcome: Extract<RunOutcome, { kind: "held" }>) => ({
517
+ check: outcome,
518
+ runner: { run: async () => outcome, limitedUntil },
519
+ });
520
+
512
521
  const version = await exec(binary, ["--version"], {
513
522
  nodePath: false,
514
523
  timeoutMs,
@@ -566,6 +575,23 @@ const startChecked = async (options: RunnerOptions): Promise<Started> => {
566
575
  /** A start check that a usage limit refused or that got no answer says nothing about the install: it is made again on the next run. */
567
576
  const isUnsettled = ({ check }: Started): boolean => check.kind === "limited" || (check.kind === "held" && (check.card.code === LIMIT_UNPARSED || check.card.code === START_TIMED_OUT));
568
577
 
578
+ /**
579
+ * A runner for judgment calls alone, as a job that holds GitHub's token needs: it makes no start check, which runs a
580
+ * full session with the repo's plugins and hooks, and it refuses any other run.
581
+ */
582
+ export const judgmentRunner = (options: RunnerOptions): Runner => {
583
+ const { run, limitedUntil } = callsOf(options);
584
+
585
+ return {
586
+ run: async (request) => {
587
+ if (request.call !== "judgment") throw new Error("this runner makes judgment calls alone: a job that holds GitHub's token starts no run");
588
+
589
+ return run(request);
590
+ },
591
+ limitedUntil,
592
+ };
593
+ };
594
+
569
595
  /**
570
596
  * A runner. Its start check is made again on the next run for as long as a usage limit refuses it, and a saved
571
597
  * limit that still stands defers the check, so no call is made before the limit ends and no restart is needed.
@@ -81,6 +81,18 @@ const workSourceChecks = (target: ContractTarget, source: WorkSource): Check[] =
81
81
  assert.equal(thread[0]?.text, "first words");
82
82
  },
83
83
  },
84
+ {
85
+ name: "work source: a finished item is never listed again, and finishing it twice changes nothing",
86
+ run: async () => {
87
+ const id = await target.seed("finished");
88
+
89
+ await source.finish(id);
90
+ await source.finish(id);
91
+
92
+ assert.ok(!(await isListed(id)), "a finished item is no longer listed");
93
+ assert.equal((await readItem(id)).ready, false);
94
+ },
95
+ },
84
96
  {
85
97
  name: "work source: two claims race and one wins",
86
98
  run: async () => {
@@ -139,6 +139,11 @@ export class FakeProvider {
139
139
 
140
140
  return { id, title };
141
141
  }),
142
+ finish: async (id) =>
143
+ spend(() => {
144
+ this.#get(id).ready = false;
145
+ this.#version++;
146
+ }),
142
147
  },
143
148
  questions: {
144
149
  ask: async (id, question) => spend(() => this.#push(id, { kind: "question", text: questionText(question) })),
@@ -1,3 +1,6 @@
1
+ import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
1
4
  import { exec } from "../exec.ts";
2
5
 
3
6
  /** No hook runs: the hooks path points nowhere, whatever the clone's own config says. */
@@ -21,6 +24,8 @@ export type Git = {
21
24
  readonly run: (args: readonly string[], input?: string) => Promise<GitResult>;
22
25
  /** Runs git and returns what it printed; a non-zero exit throws `GitFailed` with git's own words. */
23
26
  readonly raw: (args: readonly string[], input?: string) => Promise<string>;
27
+ /** As `raw`, with what git printed as bytes, which reading it as text would change. */
28
+ readonly bytes: (args: readonly string[], input?: string) => Promise<Buffer>;
24
29
  };
25
30
 
26
31
  class GitFailed extends Error {
@@ -87,25 +92,72 @@ export const readGitIdentity = async (git: Git): Promise<GitIdentityRead> => {
87
92
 
88
93
  /** git in `cwd` with hooks off. */
89
94
  export const gitIn = (cwd: string, { identity, env = {}, timeoutMs }: GitOptions): Git => {
90
- const run = async (args: readonly string[], input = ""): Promise<GitResult> => {
91
- const { exitCode, stdout, stderr } = await exec("git", ["-c", HOOKS_OFF, ...args], {
95
+ /** Runs git, its stdout piped back as text, or written to `stdout` where that names an open file. */
96
+ const spawn = async (args: readonly string[], input: string, stdout: "pipe" | number = "pipe"): Promise<GitResult> => {
97
+ const result = await exec("git", ["-c", HOOKS_OFF, ...args], {
92
98
  timeoutMs,
93
- nodeOptions: { cwd, env: { ...(identity && identityEnv(identity)), ...env } },
99
+ nodeOptions: { cwd, env: { ...(identity && identityEnv(identity)), ...env }, stdio: ["pipe", stdout, "pipe"] },
94
100
  stdin: input,
95
101
  });
96
102
 
97
- return { code: exitCode ?? -1, stdout, stderr };
103
+ return { code: result.exitCode ?? -1, stdout: result.stdout, stderr: result.stderr };
98
104
  };
99
105
 
100
- const raw = async (args: readonly string[], input?: string): Promise<string> => {
101
- const result = await run(args, input);
102
-
106
+ const succeeded = (args: readonly string[], result: GitResult): GitResult => {
103
107
  if (result.code !== 0) throw new GitFailed(args, result);
104
108
 
105
- return result.stdout;
109
+ return result;
110
+ };
111
+
112
+ const run = (args: readonly string[], input = ""): Promise<GitResult> => spawn(args, input);
113
+
114
+ const raw = async (args: readonly string[], input = ""): Promise<string> => succeeded(args, await spawn(args, input)).stdout;
115
+
116
+ const bytes = async (args: readonly string[], input = ""): Promise<Buffer> => {
117
+ const folder = mkdtempSync(join(tmpdir(), "hum-git-"));
118
+ const file = join(folder, "stdout");
119
+ const fd = openSync(file, "w");
120
+
121
+ try {
122
+ succeeded(args, await spawn(args, input, fd));
123
+
124
+ return readFileSync(file);
125
+ } finally {
126
+ closeSync(fd);
127
+ rmSync(folder, { recursive: true, force: true });
128
+ }
129
+ };
130
+
131
+ return { run, raw, bytes };
132
+ };
133
+
134
+ /** Every config entry git reads in the folder, with the file each came from: reading config runs nothing. */
135
+ const CONFIG_READ = ["config", "--list", "--show-origin"] as const;
136
+
137
+ /** The key of one `--show-origin` line, `<origin>\t<key>=<value>`, without its value. */
138
+ const keyOf = (line: string): string => line.slice(line.indexOf("\t") + 1).split("=")[0] ?? line;
139
+
140
+ /**
141
+ * `git` that runs nothing once the config git reads has changed since this was made. A run in the same folder can
142
+ * write config that git runs as code, such as core.fsmonitor, a filter or a credential helper, and hum's git would
143
+ * run it with hum's environment. A change throws, naming each key; no value is shown, as one may hold a secret.
144
+ */
145
+ export const withConfigPinned = async (git: Git): Promise<Git> => {
146
+ const read = async (): Promise<ReadonlySet<string>> => new Set((await git.raw(CONFIG_READ)).split("\n").filter(Boolean));
147
+ const pinned = await read();
148
+
149
+ const unchanged = async (): Promise<void> => {
150
+ const now = await read();
151
+ const changed = [...new Set([...now].filter((line) => !pinned.has(line)).concat([...pinned].filter((line) => !now.has(line))).map(keyOf))];
152
+
153
+ if (changed.length > 0) throw new Error(`the git config hum reads changed since hum checked the folder out: ${changed.join(", ")}. A run may have written config that git runs as code, so hum runs no more git in this folder.`);
106
154
  };
107
155
 
108
- return { run, raw };
156
+ return {
157
+ run: async (args, input) => (await unchanged(), git.run(args, input)),
158
+ raw: async (args, input) => (await unchanged(), git.raw(args, input)),
159
+ bytes: async (args, input) => (await unchanged(), git.bytes(args, input)),
160
+ };
109
161
  };
110
162
 
111
163
  /** The arguments for `git push` with hooks off, for a command line handed straight to git. */
@@ -31,12 +31,17 @@ type Failure =
31
31
  /** GraphQL errors about the request itself; any other, such as a timeout GitHub reports, may pass on a retry. */
32
32
  const PERMANENT_GRAPHQL_ERRORS: ReadonlySet<string> = new Set(["NOT_FOUND", "FORBIDDEN", "UNPROCESSABLE"]);
33
33
 
34
+ /** REST's words when another writer moved or made the ref first. */
35
+ const RACED = /not a fast.forward|already exists/i;
36
+
34
37
  const isRateLimited = (error: RequestError): boolean => error.status === 429 || (error.status === 403 && error.response?.headers["x-ratelimit-remaining"] === "0");
35
38
 
36
39
  export const failureOf = (cause: unknown): Failure => {
37
40
  if (cause instanceof RequestError) {
38
41
  if (cause.status === NOT_MODIFIED) return { kind: "not-modified" };
39
42
 
43
+ if (RACED.test(cause.message)) return { kind: "lost-race" };
44
+
40
45
  return cause.status >= 400 && cause.status < 500 && !isRateLimited(cause) ? { kind: "permanent", message: cause.message } : { kind: "transient" };
41
46
  }
42
47
 
@@ -99,4 +104,14 @@ export const gitHubClient = ({ token, baseUrl, fetch = globalThis.fetch, spaced
99
104
  });
100
105
 
101
106
  /** The client on the owner's own login, made once per process and `timeoutMs`, so every reader and writer shares its rate-limit spacing. */
107
+ /** How a repo's client is reached: one given, or the owner's own login, read within `timeoutMs`. */
108
+ export type RepoClientOptions = { readonly timeoutMs: number } & ({ readonly client: () => Promise<GitHubClient> } | { readonly env: Env });
109
+
110
+ /** The owner and name of `repo` (`owner/name`), and how to reach its client. */
111
+ export const repoClient = (repo: string, options: RepoClientOptions) => {
112
+ const [owner = "", name = ""] = repo.split("/");
113
+
114
+ return { owner, name, connect: "client" in options ? options.client : () => ownerGitHub(options.timeoutMs, options.env) };
115
+ };
116
+
102
117
  export const ownerGitHub = pMemoize(async (timeoutMs: number, env: Env): Promise<GitHubClient> => gitHubClient({ token: await ownerToken(timeoutMs, env), timeoutMs }), { cacheKey: ([timeoutMs]) => timeoutMs });
@@ -0,0 +1,84 @@
1
+ import { RequestError } from "@octokit/request-error";
2
+ import { z } from "zod";
3
+ import type { PushOutcome } from "./git.ts";
4
+ import { failureOf, type RepoClientOptions, repoClient } from "./github-client.ts";
5
+
6
+ /** A file a commit adds or changes, its bytes in base64, as `createCommitOnBranch` takes it. */
7
+ export type FileAddition = { readonly path: string; readonly contents: string };
8
+
9
+ export type FileChanges = { readonly additions: readonly FileAddition[]; readonly deletions: readonly { readonly path: string }[] };
10
+
11
+ /** A commit GitHub made: its sha and its tree's. */
12
+ export type MadeCommit = { readonly oid: string; readonly tree: string };
13
+
14
+ /** What a write to a branch came to: done, beaten by another writer, or refused by the repo's rules in GitHub's words. */
15
+ export type BranchWrite<T> = { readonly kind: "done"; readonly value: T } | Exclude<PushOutcome, { kind: "pushed" }>;
16
+
17
+ /** Branches of a GitHub repo, written through GitHub's API. GitHub signs each commit it makes for the caller. */
18
+ export type GitHubCommits = {
19
+ /** The branch's tip, or undefined when it does not exist. */
20
+ readonly head: (branch: string) => Promise<string | undefined>;
21
+ readonly createBranch: (branch: string, sha: string) => Promise<BranchWrite<void>>;
22
+ /** One commit on the branch's tip, which must still be `expected`. */
23
+ readonly commitOnBranch: (change: { readonly branch: string; readonly expected: string; readonly headline: string; readonly body: string; readonly files: FileChanges }) => Promise<BranchWrite<MadeCommit>>;
24
+ /** Points the branch at `sha`; without `force`, only as a fast-forward. */
25
+ readonly moveBranch: (branch: string, sha: string, force: boolean) => Promise<BranchWrite<void>>;
26
+ readonly deleteBranch: (branch: string) => Promise<void>;
27
+ };
28
+
29
+ const COMMIT_ON_BRANCH = `mutation CommitSigned($branch: CommittableBranch!, $expected: GitObjectID!, $message: CommitMessage!, $files: FileChanges!) {
30
+ createCommitOnBranch(input: { branch: $branch, expectedHeadOid: $expected, message: $message, fileChanges: $files }) { commit { oid tree { oid } } }
31
+ }`;
32
+
33
+ const Made = z.object({ createCommitOnBranch: z.object({ commit: z.object({ oid: z.string(), tree: z.object({ oid: z.string() }) }) }) });
34
+
35
+ const Ref = z.object({ object: z.object({ sha: z.string() }) });
36
+
37
+ const NOT_FOUND = 404;
38
+
39
+ /** A write's failure as an outcome: another writer first, or the repo's refusal; anything a retry may fix is thrown. */
40
+ const writeFailure = (cause: unknown): Exclude<PushOutcome, { kind: "pushed" }> => {
41
+
42
+ const failure = failureOf(cause);
43
+
44
+ if (failure.kind === "lost-race") return { kind: "conflict" };
45
+
46
+ if (failure.kind === "permanent") return { kind: "refused", said: `GitHub refused: ${failure.message}` };
47
+
48
+ throw cause;
49
+ };
50
+
51
+ const written = <T>(write: Promise<T>): Promise<BranchWrite<T>> => write.then((value) => ({ kind: "done" as const, value }), writeFailure);
52
+
53
+ /** The branches of `repo` (`owner/name`), on the owner's own login unless a client is given. */
54
+ export const gitHubCommits = (repo: string, options: RepoClientOptions): GitHubCommits => {
55
+ const { owner, name, connect } = repoClient(repo, options);
56
+ const where = { owner, repo: name };
57
+
58
+ return {
59
+ head: async (branch) =>
60
+ (await connect())
61
+ .request("GET /repos/{owner}/{repo}/git/ref/{ref}", { ...where, ref: `heads/${branch}` })
62
+ .then(
63
+ (reply) => Ref.parse(reply.data).object.sha,
64
+ (cause: unknown) => {
65
+ if (cause instanceof RequestError && cause.status === NOT_FOUND) return undefined;
66
+
67
+ throw cause;
68
+ },
69
+ ),
70
+ createBranch: async (branch, sha) => written((await connect()).request("POST /repos/{owner}/{repo}/git/refs", { ...where, ref: `refs/heads/${branch}`, sha }).then(() => undefined)),
71
+ commitOnBranch: async ({ branch, expected, headline, body, files }) =>
72
+ written(
73
+ (await connect())
74
+ .graphql(COMMIT_ON_BRANCH, { branch: { repositoryNameWithOwner: repo, branchName: branch }, expected, message: { headline, body }, files })
75
+ .then((reply) => {
76
+ const { commit } = Made.parse(reply).createCommitOnBranch;
77
+
78
+ return { oid: commit.oid, tree: commit.tree.oid };
79
+ }),
80
+ ),
81
+ moveBranch: async (branch, sha, force) => written((await connect()).request("PATCH /repos/{owner}/{repo}/git/refs/{ref}", { ...where, ref: `heads/${branch}`, sha, force }).then(() => undefined)),
82
+ deleteBranch: async (branch) => void (await (await connect()).request("DELETE /repos/{owner}/{repo}/git/refs/{ref}", { ...where, ref: `heads/${branch}` })),
83
+ };
84
+ };
@@ -125,6 +125,10 @@ const COMMIT_ON_BRANCH = `mutation CommitOnBranch($branch: CommittableBranch!, $
125
125
  createCommitOnBranch(input: { branch: $branch, expectedHeadOid: $expected, message: $message, fileChanges: {} }) { clientMutationId }
126
126
  }`;
127
127
 
128
+ const CLOSE_ISSUE = `mutation CloseIssue($issue: ID!) {
129
+ closeIssue(input: { issueId: $issue, stateReason: COMPLETED }) { clientMutationId }
130
+ }`;
131
+
128
132
  const CREATE_LABEL = `mutation CreateLabel($repository: ID!, $name: String!, $color: String!, $description: String!) {
129
133
  createLabel(input: { repositoryId: $repository, name: $name, color: $color, description: $description }) { label { id } }
130
134
  }`;
@@ -351,6 +355,11 @@ export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterConte
351
355
 
352
356
  return { id, title };
353
357
  },
358
+ finish: async (id) => {
359
+ const issue = await issueState(parseArgument(IssueNumber, id));
360
+
361
+ if (issue.state === "OPEN") await mutate(Acknowledged, CLOSE_ISSUE, { issue: issue.id });
362
+ },
354
363
  },
355
364
  questions: {
356
365
  ask: (id, question) => commentMarked(id, questionMarker(question.options), questionText(question)),
@@ -146,6 +146,7 @@ export const guarded = (adapter: Adapter, { provider, faults, timeoutMs, backoff
146
146
  renew: (id, holder, ttlMs) => retried(() => workSource.renew(id, holder, ttlMs), ClaimResult),
147
147
  comment: (id, text) => once(() => workSource.comment(id, text), none),
148
148
  fileFollowUp: (from, followUp) => retried(() => workSource.fileFollowUp(from, followUp), ItemRef),
149
+ finish: (id) => retried(() => workSource.finish(id), none),
149
150
  },
150
151
  questions: questions && {
151
152
  ask: (id, question) => once(() => questions.ask(id, question), none),
@@ -11,7 +11,7 @@ import { isMarkerLine, markerLine, splitMarker } from "./marked.ts";
11
11
  export const READY_STATE = "ready";
12
12
 
13
13
  /** The front matter `state` of a merged item. */
14
- const DONE_STATE = "done";
14
+ export const DONE_STATE = "done";
15
15
 
16
16
  /** Titles are never folded over several lines, so the owner reads the line they wrote. */
17
17
  const YAML_OPTIONS = { lineWidth: 0 };