@moo.md/hum 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/defaults/hum.json +14 -2
  2. package/defaults/roles/build.md +1 -1
  3. package/defaults/roles/fix.md +1 -1
  4. package/npm-shrinkwrap.json +3297 -0
  5. package/package.json +6 -2
  6. package/release.json +3 -0
  7. package/schema/hum.schema.json +251 -10
  8. package/scripts/eval.ts +21 -5
  9. package/src/adapter-api.ts +3 -1
  10. package/src/adapters/claude-bg.ts +2 -2
  11. package/src/adapters/claude-p.ts +44 -18
  12. package/src/adapters/contract.ts +12 -0
  13. package/src/adapters/fake.ts +5 -0
  14. package/src/adapters/git.ts +61 -9
  15. package/src/adapters/github-client.ts +15 -0
  16. package/src/adapters/github-commits.ts +84 -0
  17. package/src/adapters/github.ts +36 -4
  18. package/src/adapters/guard.ts +1 -0
  19. package/src/adapters/item-file.ts +1 -1
  20. package/src/adapters/markdown.ts +10 -1
  21. package/src/adapters/pull-requests.ts +8 -8
  22. package/src/adapters/registry.ts +5 -7
  23. package/src/adapters/roundup.ts +3 -0
  24. package/src/bytes.ts +1 -0
  25. package/src/cli/service.ts +176 -29
  26. package/src/cli/setup.ts +16 -7
  27. package/src/config/checks.ts +27 -43
  28. package/src/config/load.ts +2 -3
  29. package/src/config/machine.ts +29 -0
  30. package/src/config/migrate.ts +5 -2
  31. package/src/config/refusal.ts +9 -4
  32. package/src/config/schema.ts +86 -8
  33. package/src/config/wake-job.ts +78 -0
  34. package/src/decide/risk.ts +2 -2
  35. package/src/exec.ts +10 -0
  36. package/src/index.ts +1 -1
  37. package/src/loop/records.ts +8 -1
  38. package/src/measure/rate.ts +14 -0
  39. package/src/publish/bundle.ts +128 -0
  40. package/src/publish/handoff.ts +107 -0
  41. package/src/publish/handover.ts +182 -0
  42. package/src/publish/intents.ts +61 -0
  43. package/src/publish/publisher.ts +259 -0
  44. package/src/publish/wake.ts +78 -0
  45. package/src/service/ci-state.ts +99 -0
  46. package/src/service/plugins.ts +137 -0
  47. package/src/service/wake.ts +3 -1
  48. package/src/service/workflows.ts +261 -50
  49. package/src/setup/propose.ts +87 -3
  50. package/src/setup/prove.ts +3 -3
  51. package/src/setup/scan.ts +61 -5
  52. package/src/setup/tables.ts +18 -0
  53. package/src/setup/write.ts +52 -19
  54. package/src/state/items.ts +17 -8
  55. package/src/state/open.ts +20 -6
  56. package/src/state/records.ts +7 -0
  57. package/src/state/runs.ts +5 -0
  58. package/src/state/saved.ts +17 -2
  59. package/src/worker/base-check.ts +41 -13
  60. package/src/worker/checks.ts +3 -2
  61. package/src/worker/evidence.ts +72 -0
  62. package/src/worker/kind.ts +4 -7
  63. package/src/worker/land.ts +173 -81
  64. package/src/worker/merged.ts +20 -8
  65. package/src/worker/open.ts +33 -17
  66. package/src/worker/questions.ts +16 -8
  67. package/src/worker/signed-push.ts +167 -0
  68. package/src/worker/thin-path.ts +245 -133
  69. package/src/worker/worker.ts +50 -9
  70. package/surface.json +610 -76
@@ -1,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
+ };
@@ -5,6 +5,7 @@ import { z } from "zod";
5
5
  import { ADAPTER_API_VERSION, type AdapterContext, type Answers, type Claim, type Item, ItemId, PermanentError, type Integrations, type Questions, type Release, type Watch, type WorkSource } from "../adapter-api.ts";
6
6
  import type { Json } from "../config/json.ts";
7
7
  import type { MERGE_METHODS } from "../config/schema.ts";
8
+ import { TRUSTED_ASSOCIATIONS } from "../config/wake-job.ts";
8
9
  import { HOUR_MS } from "../time.ts";
9
10
  import { parseArgument } from "./argument.ts";
10
11
  import { claimCommit, claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
@@ -30,6 +31,11 @@ const Commit = z.object({ oid: z.string(), message: z.string() });
30
31
 
31
32
  const Labels = z.object({ nodes: z.array(z.object({ name: z.string() })) });
32
33
 
34
+ /** A comment with who wrote it; GitHub names no author once the account is deleted. */
35
+ const IssueComment = z.object({ body: z.string(), createdAt: z.string(), authorAssociation: z.string(), author: z.object({ __typename: z.string(), login: z.string() }).nullable() });
36
+
37
+ type IssueComment = z.infer<typeof IssueComment>;
38
+
33
39
  const ReadyItems = z.object({
34
40
  repository: z.object({
35
41
  issues: z.object({ nodes: z.array(z.object({ number: z.int().positive(), title: z.string() })) }),
@@ -45,7 +51,7 @@ const ItemReply = z.object({
45
51
  body: z.string(),
46
52
  state: z.enum(["OPEN", "CLOSED"]),
47
53
  labels: Labels,
48
- comments: z.object({ nodes: z.array(z.object({ body: z.string(), createdAt: z.string() })) }),
54
+ comments: z.object({ nodes: z.array(IssueComment) }),
49
55
  }),
50
56
  ref: z.object({ target: Commit.partial() }).nullable(),
51
57
  }),
@@ -85,7 +91,7 @@ const ITEM = `query Item($owner: String!, $name: String!, $number: Int!, $claimR
85
91
  issue(number: $number) {
86
92
  id title body state
87
93
  labels(first: 100) { nodes { name } }
88
- comments(first: 100, after: $cursor) { nodes { body createdAt } pageInfo { hasNextPage endCursor } }
94
+ comments(first: 100, after: $cursor) { nodes { body createdAt authorAssociation author { __typename login } } pageInfo { hasNextPage endCursor } }
89
95
  }
90
96
  ref(qualifiedName: $claimRef) { target { ... on Commit { message } } }
91
97
  }
@@ -119,6 +125,10 @@ const COMMIT_ON_BRANCH = `mutation CommitOnBranch($branch: CommittableBranch!, $
119
125
  createCommitOnBranch(input: { branch: $branch, expectedHeadOid: $expected, message: $message, fileChanges: {} }) { clientMutationId }
120
126
  }`;
121
127
 
128
+ const CLOSE_ISSUE = `mutation CloseIssue($issue: ID!) {
129
+ closeIssue(input: { issueId: $issue, stateReason: COMPLETED }) { clientMutationId }
130
+ }`;
131
+
122
132
  const CREATE_LABEL = `mutation CreateLabel($repository: ID!, $name: String!, $color: String!, $description: String!) {
123
133
  createLabel(input: { repositoryId: $repository, name: $name, color: $color, description: $description }) { label { id } }
124
134
  }`;
@@ -149,6 +159,8 @@ export type GitHubOptions = {
149
159
  /** Open issues with this label are the ready items. */
150
160
  readonly readyLabel: string;
151
161
  readonly mergeMethod: (typeof MERGE_METHODS)[number];
162
+ /** Logins whose comments are read whatever GitHub says of them, beside the people the repo trusts. */
163
+ readonly ownerLogins: readonly string[];
152
164
  /** The client to use; by default one on the owner's own login. */
153
165
  readonly client?: GitHubClient;
154
166
  /** The owner's `commandTimeoutSeconds` in milliseconds: the limit of the `gh auth token` that reads the owner's login. */
@@ -166,14 +178,29 @@ type Whole = Integrations & {
166
178
 
167
179
  type StandingClaim = { readonly claim: Claim; readonly sha: string };
168
180
 
181
+ const TRUSTED: ReadonlySet<string> = new Set(TRUSTED_ASSOCIATIONS);
182
+
183
+ /**
184
+ * Whether hum reads a comment. Anyone may comment on a public repo, a reply after a question is an answer, and hum's
185
+ * marker is only text, so who wrote a comment decides, never what it says. A person's is read when the repo trusts
186
+ * them or the owner names them. A bot's is read only when it is one of hum's own: in CI hum posts as the workflow's
187
+ * bot or the owner's App, and only a workflow or an App the owner installed posts as a bot at all.
188
+ */
189
+ const isHeard = (owners: ReadonlySet<string>) => ({ body, author, authorAssociation }: IssueComment): boolean => {
190
+ if (author === null) return false;
191
+
192
+ return author.__typename === "Bot" ? parseComment(body, 0).author === "hum" : owners.has(author.login.toLowerCase()) || TRUSTED.has(authorAssociation);
193
+ };
194
+
169
195
  /**
170
- * GitHub on the owner's own login: issues are items, comments are the thread. Each read is one GraphQL query,
196
+ * GitHub on the owner's own login: issues are items, and the comments hum reads are the thread. Each read is one GraphQL query,
171
197
  * each write one mutation. A claim is a branch: its first commit is made through REST, since no mutation makes a
172
198
  * bare commit, and created with `createRef`; a renewal or an expired take is `createCommitOnBranch` on the head it
173
199
  * read. `watch` is one REST request with `If-None-Match`, because GitHub answers 304 free of rate limit.
174
200
  */
175
201
  export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterContext): Whole => {
176
202
  const { base, claimPrefix, readyLabel, mergeMethod, timeoutMs } = options;
203
+ const isHeardHere = isHeard(new Set(options.ownerLogins.map((login) => login.toLowerCase())));
177
204
  const repo = parseArgument(Repo, options.repo);
178
205
  const [owner = "", name = ""] = repo.split("/");
179
206
  const where = { owner, name };
@@ -226,7 +253,7 @@ export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterConte
226
253
 
227
254
  issueIds.set(number, repository.issue.id);
228
255
 
229
- return repository;
256
+ return { ...repository, issue: { ...repository.issue, comments: { nodes: repository.issue.comments.nodes.filter(isHeardHere) } } };
230
257
  };
231
258
 
232
259
  const comment = async (id: string, body: string): Promise<void> => {
@@ -328,6 +355,11 @@ export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterConte
328
355
 
329
356
  return { id, title };
330
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
+ },
331
363
  },
332
364
  questions: {
333
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 };
@@ -9,7 +9,7 @@ import type { MergeMethod } from "../config/schema.ts";
9
9
  import { parseArgument } from "./argument.ts";
10
10
  import { claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
11
11
  import { type GitIdentity, gitIn, push, readOrAbsent } from "./git.ts";
12
- import { appendEntry, type ItemFile, newItemFile, parseItemFile, READY_STATE } from "./item-file.ts";
12
+ import { appendEntry, DONE_STATE, type ItemFile, markDone, newItemFile, parseItemFile, READY_STATE } from "./item-file.ts";
13
13
  import { answerMarker, followUpBody, followUpKey, questionText } from "./marked.ts";
14
14
  import { type CommitLanded, landOwnerCommit } from "./owner-commit.ts";
15
15
  import type { PullRequests } from "./pull-requests.ts";
@@ -352,6 +352,15 @@ export const markdownAdapter = ({ repo, claimPrefix, itemsDir, identity, writeRa
352
352
 
353
353
  return failed ?? { id, title };
354
354
  },
355
+ /** A landed change already carries the item file's done state, so this writes only where it does not. */
356
+ finish: async (id) =>
357
+ write(`hum: finish ${id}`, async () => {
358
+ const source = await itemSource(id);
359
+
360
+ if (source === undefined) throw new PermanentError(`no item "${id}" under ${itemsDir}/`);
361
+
362
+ return parseItemFile(source).state === DONE_STATE ? undefined : { path: pathOf(id), content: markDone(source) };
363
+ }),
355
364
  },
356
365
  questions: {
357
366
  ask: (id, question) => appendTo(id, { kind: "question" }, questionText(question)),
@@ -3,12 +3,13 @@ import pMemoize from "p-memoize";
3
3
  import { z } from "zod";
4
4
  import type { Json } from "../config/json.ts";
5
5
  import { MERGE_METHODS, type MergeMethod } from "../config/schema.ts";
6
- import type { Env } from "../exec.ts";
7
- import { type GitHubClient, MERGE_METHOD, ownerGitHub, raise } from "./github-client.ts";
6
+ import { MERGE_METHOD, raise, type RepoClientOptions, repoClient } from "./github-client.ts";
8
7
 
9
8
  /** What the target branch's rules ask of a change that lands on it. */
10
9
  export type BranchRules = {
11
10
  readonly requiresPullRequest: boolean;
11
+ /** Every commit that reaches the branch must carry a signature GitHub verifies. */
12
+ readonly requiresSignatures: boolean;
12
13
  /** The merge methods a pull request may use; undefined when no rule narrows them. */
13
14
  readonly mergeMethods: readonly MergeMethod[] | undefined;
14
15
  };
@@ -59,6 +60,8 @@ const Rule = z.looseObject({
59
60
 
60
61
  const PULL_REQUEST_RULE = "pull_request";
61
62
 
63
+ const SIGNATURES_RULE = "required_signatures";
64
+
62
65
  const PullNode = z.object({
63
66
  id: z.string(),
64
67
  number: z.int(),
@@ -137,12 +140,8 @@ export const methodFor = (
137
140
  : (allowed[0] ?? preferred);
138
141
 
139
142
  /** Pull requests and branch rules of a GitHub repo, on the owner's own login unless a client is given. `timeoutMs` bounds the `gh auth token` that reads that login. */
140
- export const gitHubPullRequests = (
141
- repo: string,
142
- options: { readonly timeoutMs: number } & ({ readonly client: () => Promise<GitHubClient> } | { readonly env: Env }),
143
- ): PullRequests => {
144
- const [owner = "", name = ""] = repo.split("/");
145
- const connect = "client" in options ? options.client : () => ownerGitHub(options.timeoutMs, options.env);
143
+ export const gitHubPullRequests = (repo: string, options: RepoClientOptions): PullRequests => {
144
+ const { owner, name, connect } = repoClient(repo, options);
146
145
 
147
146
  const rulesCache = new Map<string, BranchRules>();
148
147
 
@@ -176,6 +175,7 @@ export const gitHubPullRequests = (
176
175
 
177
176
  return {
178
177
  requiresPullRequest: pullRule !== undefined,
178
+ requiresSignatures: rules.some((rule) => rule.type === SIGNATURES_RULE),
179
179
  mergeMethods: pullRule?.parameters?.allowed_merge_methods,
180
180
  };
181
181
  },
@@ -4,7 +4,7 @@ import { pathToFileURL } from "node:url";
4
4
  import { z } from "zod";
5
5
  import { ADAPTER_API_VERSION, type Adapter, type AdapterContext, type AdapterFactory, type Integrations, PermanentError } from "../adapter-api.ts";
6
6
  import { readSettings } from "../config/settings.ts";
7
- import { HumConfig } from "../config/schema.ts";
7
+ import { HumConfig, SLOTS, type Slot } from "../config/schema.ts";
8
8
  import { commandTimeoutMs, type Env } from "../exec.ts";
9
9
  import type { Faults } from "../state/faults.ts";
10
10
  import type { Card } from "../status/format.ts";
@@ -15,10 +15,7 @@ import { markdownAdapter } from "./markdown.ts";
15
15
  import { gitHubPullRequests, type PullRequests } from "./pull-requests.ts";
16
16
  import { roundupAdapter } from "./roundup.ts";
17
17
 
18
- /** The integration slots `hum.json` `integrations` names, each to an adapter. */
19
- export const SLOTS = ["work-source", "questions", "answers", "release"] as const;
20
-
21
- export type Slot = (typeof SLOTS)[number];
18
+ export { SLOTS, type Slot } from "../config/schema.ts";
22
19
 
23
20
  const MARKDOWN = "markdown";
24
21
  const FALLBACK_BASE = "main";
@@ -28,11 +25,12 @@ const MARKDOWN_SLOTS: readonly Slot[] = ["work-source", "questions", "answers"];
28
25
 
29
26
  /** What the adapters read from `hum.json`; every other key belongs to the worker. */
30
27
  const AdapterSettings = z.looseObject({
31
- integrations: z.partialRecord(z.enum(SLOTS), z.string().min(1)).optional(),
28
+ integrations: HumConfig.shape.integrations,
32
29
  claimPrefix: HumConfig.shape.claimPrefix,
33
30
  itemsDir: HumConfig.shape.itemsDir,
34
31
  commitIdentity: HumConfig.shape.commitIdentity,
35
32
  readyLabel: HumConfig.shape.readyLabel,
33
+ ownerLogins: HumConfig.shape.ownerLogins,
36
34
  mergeMethod: HumConfig.shape.mergeMethod,
37
35
  ownerBranchPrefix: HumConfig.shape.ownerBranchPrefix,
38
36
  writeRaceRetries: HumConfig.shape.writeRaceRetries,
@@ -85,7 +83,7 @@ const BUILT_IN = {
85
83
  github: async ({ path, settings, context }) => {
86
84
  const timeoutMs = commandTimeoutMs(settings);
87
85
 
88
- return githubAdapter({ repo: await githubRepo(path, timeoutMs), base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, readyLabel: settings.readyLabel, mergeMethod: settings.mergeMethod, timeoutMs }, context);
86
+ return githubAdapter({ repo: await githubRepo(path, timeoutMs), base: await defaultBase(path, timeoutMs), claimPrefix: settings.claimPrefix, readyLabel: settings.readyLabel, mergeMethod: settings.mergeMethod, ownerLogins: settings.ownerLogins, timeoutMs }, context);
89
87
  },
90
88
  roundup: async ({ context }) => roundupAdapter({}, context),
91
89
  } satisfies Readonly<Record<string, (repo: Repo) => Promise<Adapter>>>;
@@ -267,6 +267,9 @@ export const roundupAdapter = (options: RoundupOptions, { now, env }: AdapterCon
267
267
 
268
268
  return { id, title };
269
269
  },
270
+ finish: async (id) => {
271
+ if (!(await todo(id)).done) await call("todo_complete", { id: parseArgument(TodoId, id) });
272
+ },
270
273
  },
271
274
  questions: {
272
275
  ask: (id, question) => postMarked(id, questionMarker(question.options), questionText(question)),
package/src/bytes.ts ADDED
@@ -0,0 +1 @@
1
+ export const MEGABYTE = 1024 * 1024;