@moo.md/hum 0.1.0 → 0.3.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 (112) hide show
  1. package/defaults/hum.json +9 -2
  2. package/package.json +2 -2
  3. package/schema/hum.schema.json +208 -7
  4. package/scripts/eval.ts +88 -50
  5. package/src/adapter-api.ts +46 -14
  6. package/src/adapters/admit.ts +2 -2
  7. package/src/adapters/argument.ts +1 -1
  8. package/src/adapters/claim.ts +18 -15
  9. package/src/adapters/claude-bg.ts +50 -27
  10. package/src/adapters/claude-p.ts +18 -23
  11. package/src/adapters/contract.ts +22 -10
  12. package/src/adapters/each-call.ts +9 -0
  13. package/src/adapters/fake.ts +6 -6
  14. package/src/adapters/git.ts +10 -18
  15. package/src/adapters/github-client.ts +102 -0
  16. package/src/adapters/github.ts +61 -146
  17. package/src/adapters/guard.ts +20 -9
  18. package/src/adapters/history.ts +12 -15
  19. package/src/adapters/item-file.ts +1 -1
  20. package/src/adapters/markdown.ts +49 -42
  21. package/src/adapters/marked.ts +6 -12
  22. package/src/adapters/model-call.ts +4 -4
  23. package/src/adapters/once.ts +5 -5
  24. package/src/adapters/owner-commit.ts +13 -11
  25. package/src/adapters/pull-requests.ts +11 -13
  26. package/src/adapters/registry.ts +9 -8
  27. package/src/adapters/roundup.ts +27 -35
  28. package/src/adapters/serial.ts +4 -5
  29. package/src/adapters/transcript.ts +13 -8
  30. package/src/cli/main.ts +1 -0
  31. package/src/cli/ops.ts +32 -14
  32. package/src/cli/service.ts +14 -8
  33. package/src/cli/setup.ts +22 -7
  34. package/src/cli/shared-watch.ts +3 -3
  35. package/src/config/checks.ts +27 -18
  36. package/src/config/machine.ts +5 -7
  37. package/src/config/migrate.ts +5 -2
  38. package/src/config/refusal.ts +15 -2
  39. package/src/config/schema.ts +74 -12
  40. package/src/config/settings.ts +17 -2
  41. package/src/config/state-map.ts +5 -3
  42. package/src/config/wake-job.ts +74 -0
  43. package/src/decide/alignment.ts +4 -4
  44. package/src/decide/answer.ts +24 -22
  45. package/src/decide/kind.ts +1 -6
  46. package/src/decide/labels.ts +9 -9
  47. package/src/decide/merge.ts +6 -7
  48. package/src/decide/prose.ts +4 -4
  49. package/src/decide/question.ts +23 -20
  50. package/src/decide/review.ts +4 -2
  51. package/src/decide/risk.ts +25 -19
  52. package/src/decide/taste.ts +3 -3
  53. package/src/exec.ts +4 -3
  54. package/src/index.ts +14 -13
  55. package/src/loop/check-item.ts +3 -3
  56. package/src/loop/ci.ts +1 -1
  57. package/src/loop/github.ts +2 -2
  58. package/src/loop/groups.ts +13 -6
  59. package/src/loop/memory.ts +40 -28
  60. package/src/loop/notes.ts +5 -5
  61. package/src/loop/pair.ts +1 -1
  62. package/src/loop/pass.ts +18 -12
  63. package/src/loop/proof.ts +9 -7
  64. package/src/loop/prove-item.ts +1 -1
  65. package/src/loop/records.ts +12 -13
  66. package/src/loop/signals.ts +6 -6
  67. package/src/measure/inputs.ts +1 -1
  68. package/src/measure/measure.ts +4 -4
  69. package/src/measure/rate.ts +2 -0
  70. package/src/service/ci-tick.ts +2 -2
  71. package/src/service/supervise.ts +3 -2
  72. package/src/service/token.ts +3 -3
  73. package/src/service/wake.ts +2 -2
  74. package/src/service/workflows.ts +165 -48
  75. package/src/setup/propose.ts +78 -7
  76. package/src/setup/prove.ts +18 -12
  77. package/src/setup/scan.ts +91 -28
  78. package/src/setup/shipped.ts +8 -2
  79. package/src/setup/tables.ts +22 -3
  80. package/src/setup/waits.ts +9 -11
  81. package/src/setup/write.ts +67 -27
  82. package/src/slots/pool.ts +32 -24
  83. package/src/state/events.ts +1 -1
  84. package/src/state/faults.ts +13 -5
  85. package/src/state/format.ts +2 -2
  86. package/src/state/items.ts +9 -10
  87. package/src/state/open.ts +2 -2
  88. package/src/state/ops.ts +16 -10
  89. package/src/state/records.ts +5 -5
  90. package/src/state/runs.ts +33 -26
  91. package/src/state/saved.ts +44 -32
  92. package/src/status/file.ts +20 -1
  93. package/src/status/format.ts +47 -57
  94. package/src/status/sections.ts +2 -2
  95. package/src/worker/alignment-report.ts +4 -5
  96. package/src/worker/answers.ts +26 -24
  97. package/src/worker/base-check.ts +2 -2
  98. package/src/worker/kind.ts +23 -19
  99. package/src/worker/land.ts +114 -126
  100. package/src/worker/merged.ts +9 -7
  101. package/src/worker/open.ts +14 -12
  102. package/src/worker/prose-run.ts +3 -3
  103. package/src/worker/questions.ts +15 -12
  104. package/src/worker/scheduler.ts +4 -4
  105. package/src/worker/signature.ts +3 -3
  106. package/src/worker/tally.ts +0 -2
  107. package/src/worker/taste.ts +6 -15
  108. package/src/worker/thin-path.ts +148 -121
  109. package/src/worker/thread.ts +25 -0
  110. package/src/worker/worker.ts +77 -47
  111. package/surface.json +1091 -2251
  112. package/src/slots/scan.ts +0 -26
@@ -1,8 +1,8 @@
1
- import { type Adapter, type Claim, type ItemRef, PermanentError, type ThreadEntry, type Watch } from "../adapter-api.ts";
1
+ import { ADAPTER_API_VERSION, type Claim, type Integrations, ItemId, type ItemRef, PermanentError, type ThreadEntry, type Watch } from "../adapter-api.ts";
2
2
  import { claimer, isLive } from "./claim.ts";
3
3
  import { questionText } from "./marked.ts";
4
4
 
5
- type Stored = { id: string; title: string; body: string; ready: boolean; thread: ThreadEntry[]; claim?: Claim; from?: string };
5
+ type Stored = { id: ItemId; title: string; body: string; ready: boolean; thread: ThreadEntry[]; claim?: Claim; from?: string };
6
6
 
7
7
  /** A provider failure a retry can outlast, like a GitHub 502. */
8
8
  export class ProviderError extends Error {
@@ -48,8 +48,8 @@ export class FakeProvider {
48
48
  this.#emptyList = value;
49
49
  }
50
50
 
51
- seed(title: string, { ready = true }: { ready?: boolean } = {}): string {
52
- const id = `item-${this.#items.size + 1}`;
51
+ seed(title: string, { ready = true }: { ready?: boolean } = {}): ItemId {
52
+ const id = ItemId.parse(`item-${this.#items.size + 1}`);
53
53
 
54
54
  this.#items.set(id, { id, title, body: `${title} body`, ready, thread: [] });
55
55
  this.#version++;
@@ -107,12 +107,12 @@ export class FakeProvider {
107
107
  this.now,
108
108
  );
109
109
 
110
- adapter(): Adapter {
110
+ adapter(): Integrations {
111
111
  const asRef = ({ id, title }: Stored): ItemRef => ({ id, title });
112
112
  const spend = <T>(body: () => T) => this.#call(true, body);
113
113
 
114
114
  return {
115
- apiVersion: 1,
115
+ apiVersion: ADAPTER_API_VERSION,
116
116
  workSource: {
117
117
  listReady: async () =>
118
118
  spend(() => this.listReplacement?.() ?? (this.#emptyList ? [] : [...this.#items.values()].flatMap((item) => (this.#isReady(item) ? [asRef(item)] : [])))),
@@ -1,4 +1,3 @@
1
- import { PermanentError } from "../adapter-api.ts";
2
1
  import { exec } from "../exec.ts";
3
2
 
4
3
  /** No hook runs: the hooks path points nowhere, whatever the clone's own config says. */
@@ -15,7 +14,7 @@ export const PATCH = ["--no-ext-diff", "--no-color"] as const;
15
14
  const ANCESTOR = 0;
16
15
  const NOT_ANCESTOR = 1;
17
16
 
18
- export type GitResult = { readonly code: number; readonly stdout: string; readonly stderr: string };
17
+ type GitResult = { readonly code: number; readonly stdout: string; readonly stderr: string };
19
18
 
20
19
  export type Git = {
21
20
  /** Runs git; a non-zero exit is a result, not a throw, but a run past its time limit throws `CommandTimedOut`. `input` is its stdin, which is closed either way. */
@@ -24,7 +23,7 @@ export type Git = {
24
23
  readonly raw: (args: readonly string[], input?: string) => Promise<string>;
25
24
  };
26
25
 
27
- export class GitFailed extends Error {
26
+ class GitFailed extends Error {
28
27
  override name = "GitFailed";
29
28
 
30
29
  constructor(
@@ -44,12 +43,8 @@ export const whenGitFailed =
44
43
  throw error;
45
44
  };
46
45
 
47
- /** The remote refused the push: a protected branch, a hook, a permission. Retrying cannot help. */
48
- export class PushRefused extends PermanentError {
49
- override name = "PushRefused";
50
- }
51
-
52
- export type PushOutcome = "pushed" | "conflict";
46
+ /** `conflict`: another writer moved the ref first, and a retry can win. `refused`: the remote said no, in `said`, and no retry helps. */
47
+ export type PushOutcome = { readonly kind: "pushed" } | { readonly kind: "conflict" } | { readonly kind: "refused"; readonly said: string };
53
48
 
54
49
  /** The author and committer of the commits hum makes. */
55
50
  export type GitIdentity = { readonly name: string; readonly email: string };
@@ -95,7 +90,7 @@ export const gitIn = (cwd: string, { identity, env = {}, timeoutMs }: GitOptions
95
90
  const run = async (args: readonly string[], input = ""): Promise<GitResult> => {
96
91
  const { exitCode, stdout, stderr } = await exec("git", ["-c", HOOKS_OFF, ...args], {
97
92
  timeoutMs,
98
- nodeOptions: { cwd, env: { ...process.env, ...(identity && identityEnv(identity)), ...env } },
93
+ nodeOptions: { cwd, env: { ...(identity && identityEnv(identity)), ...env } },
99
94
  stdin: input,
100
95
  });
101
96
 
@@ -116,26 +111,23 @@ export const gitIn = (cwd: string, { identity, env = {}, timeoutMs }: GitOptions
116
111
  /** The arguments for `git push` with hooks off, for a command line handed straight to git. */
117
112
  export const pushArgs = (rest: readonly string[]): string[] => ["-c", HOOKS_OFF, "push", "--no-verify", ...rest];
118
113
 
119
- /**
120
- * Pushes. `conflict` means another writer moved the ref first and a retry can win.
121
- * A refusal throws `PushRefused` with the remote's own words; any other failure throws `GitFailed`.
122
- */
114
+ /** Pushes. A refusal is an outcome that carries the remote's own words; any other failure throws `GitFailed`. */
123
115
  export const push = async (git: Git, rest: readonly string[]): Promise<PushOutcome> => {
124
116
  const args = ["push", "--no-verify", ...rest];
125
117
  const result = await git.run(args);
126
118
  const said = `${result.stderr}${result.stdout}`.trim();
127
119
 
128
- if (result.code === 0) return "pushed";
120
+ if (result.code === 0) return { kind: "pushed" };
129
121
 
130
- if (CONFLICT.test(said)) return "conflict";
122
+ if (CONFLICT.test(said)) return { kind: "conflict" };
131
123
 
132
- if (REFUSED.test(said)) throw new PushRefused(`git push refused: ${said}`);
124
+ if (REFUSED.test(said)) return { kind: "refused", said: `git push refused: ${said}` };
133
125
 
134
126
  throw new GitFailed(args, result);
135
127
  };
136
128
 
137
129
  /** Whether `ancestor` is reachable from `descendant`. git answers by exit code alone. */
138
- export const isAncestor = async (git: Git, ancestor: string, descendant: string): Promise<boolean> => {
130
+ export const isAncestor = async (git: Git, { ancestor, descendant }: { readonly ancestor: string; readonly descendant: string }): Promise<boolean> => {
139
131
  const args = ["merge-base", "--is-ancestor", ancestor, descendant];
140
132
  const result = await git.run(args);
141
133
 
@@ -0,0 +1,102 @@
1
+ import { Octokit } from "@octokit/core";
2
+ import { GraphqlResponseError } from "@octokit/graphql";
3
+ import { paginateGraphQL } from "@octokit/plugin-paginate-graphql";
4
+ import { type ThrottlingOptions, throttling } from "@octokit/plugin-throttling";
5
+ import { RequestError } from "@octokit/request-error";
6
+ import pMemoize from "p-memoize";
7
+ import { PermanentError } from "../adapter-api.ts";
8
+ import type { MERGE_METHODS } from "../config/schema.ts";
9
+ import { type Env, exec } from "../exec.ts";
10
+
11
+ const RATE_LIMIT_RETRIES = 1;
12
+ const NOT_MODIFIED = 304;
13
+
14
+ const HumOctokit = Octokit.plugin(throttling, paginateGraphQL);
15
+
16
+ export type GitHubClient = InstanceType<typeof HumOctokit>;
17
+
18
+ /** The GraphQL name of each merge method. */
19
+ export const MERGE_METHOD = { merge: "MERGE", squash: "SQUASH", rebase: "REBASE" } as const satisfies Record<(typeof MERGE_METHODS)[number], string>;
20
+
21
+ /** What a failed request means to hum. */
22
+ type Failure =
23
+ /** GitHub answered 304 to a conditional request: nothing changed, and no rate limit was spent. */
24
+ | { readonly kind: "not-modified" }
25
+ /** Another writer took the ref first: it already exists, or it moved since it was read. */
26
+ | { readonly kind: "lost-race" }
27
+ /** No retry fixes it: a 4xx other than a rate limit, or a GraphQL error about the request itself. */
28
+ | { readonly kind: "permanent"; readonly message: string }
29
+ | { readonly kind: "transient" };
30
+
31
+ /** GraphQL errors about the request itself; any other, such as a timeout GitHub reports, may pass on a retry. */
32
+ const PERMANENT_GRAPHQL_ERRORS: ReadonlySet<string> = new Set(["NOT_FOUND", "FORBIDDEN", "UNPROCESSABLE"]);
33
+
34
+ const isRateLimited = (error: RequestError): boolean => error.status === 429 || (error.status === 403 && error.response?.headers["x-ratelimit-remaining"] === "0");
35
+
36
+ export const failureOf = (cause: unknown): Failure => {
37
+ if (cause instanceof RequestError) {
38
+ if (cause.status === NOT_MODIFIED) return { kind: "not-modified" };
39
+
40
+ return cause.status >= 400 && cause.status < 500 && !isRateLimited(cause) ? { kind: "permanent", message: cause.message } : { kind: "transient" };
41
+ }
42
+
43
+ const found = cause instanceof GraphqlResponseError ? cause.errors?.[0] : undefined;
44
+
45
+ if (found?.type === "STALE_DATA" || (found?.type === "UNPROCESSABLE" && /already exists/i.test(found.message))) return { kind: "lost-race" };
46
+
47
+ return found && PERMANENT_GRAPHQL_ERRORS.has(found.type ?? "") ? { kind: "permanent", message: found.message } : { kind: "transient" };
48
+ };
49
+
50
+ /** Throws `cause`, marked permanent when no retry can fix it. */
51
+ export const raise = (cause: unknown): never => {
52
+ const failure = failureOf(cause);
53
+
54
+ throw failure.kind === "permanent" ? new PermanentError(failure.message, { cause }) : cause;
55
+ };
56
+
57
+ /** The owner's own login: `GH_TOKEN` or `GITHUB_TOKEN`, else the token `gh` holds. */
58
+ const ownerToken = async (timeoutMs: number, env: Env): Promise<string> => {
59
+ const fromEnv = env.GH_TOKEN || env.GITHUB_TOKEN;
60
+
61
+ if (fromEnv) return fromEnv;
62
+
63
+ const gh = await exec("gh", ["auth", "token"], { stdin: "", timeoutMs });
64
+ const token = gh.stdout.trim();
65
+
66
+ if (gh.exitCode !== 0 || token === "") throw new PermanentError("no GitHub login: run `gh auth login`, or set GH_TOKEN");
67
+
68
+ return token;
69
+ };
70
+
71
+ const retryOnce: NonNullable<ThrottlingOptions["onRateLimit"]> = (_retryAfter, _options, _octokit, retryCount) => retryCount < RATE_LIMIT_RETRIES;
72
+
73
+ type Send = (url: string, init?: RequestInit) => Promise<Response>;
74
+
75
+ export type GitHubClientOptions = {
76
+ readonly token: string;
77
+ readonly baseUrl?: string;
78
+ /** Replaces `fetch`, for a GitHub that is not github.com. */
79
+ readonly fetch?: Send;
80
+ /** Whether writes are spaced as GitHub asks; only a GitHub with no secondary rate limit may go without. */
81
+ readonly spaced?: boolean;
82
+ /** The owner's `commandTimeoutSeconds` in milliseconds: how long one request may wait for GitHub's answer. */
83
+ readonly timeoutMs: number;
84
+ };
85
+
86
+ const bounded =
87
+ (send: Send, timeoutMs: number): Send =>
88
+ (url, init) =>
89
+ send(url, { ...init, signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(init?.signal ? [init.signal] : [])]) });
90
+
91
+ /** A GitHub client that waits out rate limits, spaces its writes as GitHub asks, and gives up on a request GitHub has not answered within `timeoutMs`. */
92
+ export const gitHubClient = ({ token, baseUrl, fetch = globalThis.fetch, spaced = true, timeoutMs }: GitHubClientOptions): GitHubClient =>
93
+ new HumOctokit({
94
+ auth: token,
95
+ userAgent: "hum",
96
+ baseUrl,
97
+ request: { fetch: bounded(fetch, timeoutMs) },
98
+ throttle: { enabled: spaced, onRateLimit: retryOnce, onSecondaryRateLimit: retryOnce },
99
+ });
100
+
101
+ /** The client on the owner's own login, made once per process and `timeoutMs`, so every reader and writer shares its rate-limit spacing. */
102
+ export const ownerGitHub = pMemoize(async (timeoutMs: number, env: Env): Promise<GitHubClient> => gitHubClient({ token: await ownerToken(timeoutMs, env), timeoutMs }), { cacheKey: ([timeoutMs]) => timeoutMs });
@@ -1,34 +1,29 @@
1
- import { Octokit } from "@octokit/core";
2
- import { GraphqlResponseError } from "@octokit/graphql";
3
- import { paginateGraphQL } from "@octokit/plugin-paginate-graphql";
4
- import { type ThrottlingOptions, throttling } from "@octokit/plugin-throttling";
5
- import { RequestError } from "@octokit/request-error";
1
+ import ExpiryMap from "expiry-map";
6
2
  import hostedGitInfo from "hosted-git-info";
7
3
  import pMemoize from "p-memoize";
8
4
  import { z } from "zod";
9
- import { type Adapter, type AdapterContext, type Answers, type Claim, type Item, ItemId, PermanentError, type Questions, type Release, type Watch, type WorkSource } from "../adapter-api.ts";
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";
10
6
  import type { Json } from "../config/json.ts";
11
7
  import type { MERGE_METHODS } from "../config/schema.ts";
12
- import { exec } from "../exec.ts";
8
+ import { TRUSTED_ASSOCIATIONS } from "../config/wake-job.ts";
9
+ import { HOUR_MS } from "../time.ts";
13
10
  import { parseArgument } from "./argument.ts";
14
11
  import { claimCommit, claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
12
+ import { failureOf, type GitHubClient, ownerGitHub, raise } from "./github-client.ts";
15
13
  import { answerMarker, commentText, filedFollowUp, followUpBody, followUpNote, isFollowUpOf, type Marker, marked, parseComment, questionMarker, questionText } from "./marked.ts";
14
+ import { gitHubPullRequests } from "./pull-requests.ts";
16
15
 
17
- const RATE_LIMIT_RETRIES = 1;
18
- const NOT_MODIFIED = 304;
19
16
  const READY_LABEL_COLOR = "0e8a16";
20
17
  const READY_LABEL_DESCRIPTION = "hum may take this item";
21
18
 
22
- const HumOctokit = Octokit.plugin(throttling, paginateGraphQL);
23
-
24
- export type GitHubClient = InstanceType<typeof HumOctokit>;
19
+ /** How long an issue's node id is kept after it was read. An id never changes; the limit only bounds what the worker holds. */
20
+ const ISSUE_ID_KEPT_MS = HOUR_MS;
25
21
 
26
22
  type Variables = Readonly<Record<string, Json>>;
27
23
 
28
- /** The GraphQL name of each merge method. */
29
- export const MERGE_METHOD = { merge: "MERGE", squash: "SQUASH", rebase: "REBASE" } as const satisfies Record<(typeof MERGE_METHODS)[number], string>;
24
+ const IssueId = ItemId.refine((id) => /^[1-9]\d*$/.test(id), "a GitHub issue number is a whole number above 0");
30
25
 
31
- const IssueNumber = ItemId.pipe(z.string().regex(/^[1-9]\d*$/, "a GitHub issue number is a whole number above 0")).transform(Number);
26
+ const IssueNumber = IssueId.transform(Number);
32
27
 
33
28
  const Repo = z.string().regex(/^[\w.-]+\/[\w.-]+$/, "a GitHub repo is owner/name");
34
29
 
@@ -36,6 +31,11 @@ const Commit = z.object({ oid: z.string(), message: z.string() });
36
31
 
37
32
  const Labels = z.object({ nodes: z.array(z.object({ name: z.string() })) });
38
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
+
39
39
  const ReadyItems = z.object({
40
40
  repository: z.object({
41
41
  issues: z.object({ nodes: z.array(z.object({ number: z.int().positive(), title: z.string() })) }),
@@ -51,7 +51,7 @@ const ItemReply = z.object({
51
51
  body: z.string(),
52
52
  state: z.enum(["OPEN", "CLOSED"]),
53
53
  labels: Labels,
54
- comments: z.object({ nodes: z.array(z.object({ body: z.string(), createdAt: z.string() })) }),
54
+ comments: z.object({ nodes: z.array(IssueComment) }),
55
55
  }),
56
56
  ref: z.object({ target: Commit.partial() }).nullable(),
57
57
  }),
@@ -71,14 +71,6 @@ const CreatedIssue = z.object({ createIssue: z.object({ issue: z.object({ number
71
71
 
72
72
  const RecentIssuesReply = z.object({ repository: z.object({ issues: z.object({ nodes: z.array(z.object({ number: z.int().positive(), title: z.string(), body: z.string() })) }) }) });
73
73
 
74
- const PullsReply = z.object({
75
- repository: z.object({
76
- id: z.string(),
77
- issue: z.object({ title: z.string() }),
78
- pullRequests: z.object({ nodes: z.array(z.object({ id: z.string(), state: z.enum(["OPEN", "MERGED", "CLOSED"]) })) }),
79
- }),
80
- });
81
-
82
74
  const CreatedCommit = z.object({ sha: z.string() });
83
75
 
84
76
  /** The reply of a write whose result hum does not read. */
@@ -99,7 +91,7 @@ const ITEM = `query Item($owner: String!, $name: String!, $number: Int!, $claimR
99
91
  issue(number: $number) {
100
92
  id title body state
101
93
  labels(first: 100) { nodes { name } }
102
- 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 } }
103
95
  }
104
96
  ref(qualifiedName: $claimRef) { target { ... on Commit { message } } }
105
97
  }
@@ -121,14 +113,6 @@ const LABEL = `query Label($owner: String!, $name: String!, $label: String!) {
121
113
  repository(owner: $owner, name: $name) { id label(name: $label) { id } }
122
114
  }`;
123
115
 
124
- const PULLS = `query Pulls($owner: String!, $name: String!, $number: Int!, $head: String!) {
125
- repository(owner: $owner, name: $name) {
126
- id
127
- issue(number: $number) { title }
128
- pullRequests(headRefName: $head, states: [OPEN, MERGED], first: 1) { nodes { id state } }
129
- }
130
- }`;
131
-
132
116
  const ADD_COMMENT = `mutation AddComment($subject: ID!, $body: String!) {
133
117
  addComment(input: { subjectId: $subject, body: $body }) { clientMutationId }
134
118
  }`;
@@ -154,50 +138,6 @@ const CREATE_ISSUE = `mutation CreateIssue($repository: ID!, $title: String!, $b
154
138
  createIssue(input: { repositoryId: $repository, title: $title, body: $body, labelIds: $labels }) { issue { number } }
155
139
  }`;
156
140
 
157
- const CREATE_PULL = `mutation CreatePull($repository: ID!, $base: String!, $head: String!, $title: String!, $body: String!) {
158
- createPullRequest(input: { repositoryId: $repository, baseRefName: $base, headRefName: $head, title: $title, body: $body }) { clientMutationId }
159
- }`;
160
-
161
- const MERGE_PULL = `mutation MergePull($pull: ID!, $mergeMethod: PullRequestMergeMethod!) {
162
- mergePullRequest(input: { pullRequestId: $pull, mergeMethod: $mergeMethod }) { clientMutationId }
163
- }`;
164
-
165
- /** What a failed request means to hum. */
166
- type Failure =
167
- /** GitHub answered 304 to a conditional request: nothing changed, and no rate limit was spent. */
168
- | { readonly kind: "not-modified" }
169
- /** Another writer took the ref first: it already exists, or it moved since it was read. */
170
- | { readonly kind: "lost-race" }
171
- /** No retry fixes it: a 4xx other than a rate limit, or a GraphQL error about the request itself. */
172
- | { readonly kind: "permanent"; readonly message: string }
173
- | { readonly kind: "transient" };
174
-
175
- /** GraphQL errors about the request itself; any other, such as a timeout GitHub reports, may pass on a retry. */
176
- const PERMANENT_GRAPHQL_ERRORS: ReadonlySet<string> = new Set(["NOT_FOUND", "FORBIDDEN", "UNPROCESSABLE"]);
177
-
178
- const isRateLimited = (error: RequestError): boolean => error.status === 429 || (error.status === 403 && error.response?.headers["x-ratelimit-remaining"] === "0");
179
-
180
- const failureOf = (cause: unknown): Failure => {
181
- if (cause instanceof RequestError) {
182
- if (cause.status === NOT_MODIFIED) return { kind: "not-modified" };
183
-
184
- return cause.status >= 400 && cause.status < 500 && !isRateLimited(cause) ? { kind: "permanent", message: cause.message } : { kind: "transient" };
185
- }
186
-
187
- const found = cause instanceof GraphqlResponseError ? cause.errors?.[0] : undefined;
188
-
189
- if (found?.type === "STALE_DATA" || (found?.type === "UNPROCESSABLE" && /already exists/i.test(found.message))) return { kind: "lost-race" };
190
-
191
- return found && PERMANENT_GRAPHQL_ERRORS.has(found.type ?? "") ? { kind: "permanent", message: found.message } : { kind: "transient" };
192
- };
193
-
194
- /** Throws `cause`, marked permanent when no retry can fix it. */
195
- export const raise = (cause: unknown): never => {
196
- const failure = failureOf(cause);
197
-
198
- throw failure.kind === "permanent" ? new PermanentError(failure.message, { cause }) : cause;
199
- };
200
-
201
141
  /** The `owner/name` of a GitHub remote URL, or undefined for any other host. */
202
142
  export const repoFromRemote = (url: string): string | undefined => {
203
143
  const remote = hostedGitInfo.fromUrl(url.trim());
@@ -205,50 +145,6 @@ export const repoFromRemote = (url: string): string | undefined => {
205
145
  return remote?.type === "github" ? `${remote.user}/${remote.project}` : undefined;
206
146
  };
207
147
 
208
- /** The owner's own login: `GH_TOKEN` or `GITHUB_TOKEN`, else the token `gh` holds. */
209
- export const ownerToken = async (timeoutMs: number): Promise<string> => {
210
- const fromEnv = process.env.GH_TOKEN || process.env.GITHUB_TOKEN;
211
-
212
- if (fromEnv) return fromEnv;
213
-
214
- const gh = await exec("gh", ["auth", "token"], { stdin: "", timeoutMs });
215
- const token = gh.stdout.trim();
216
-
217
- if (gh.exitCode !== 0 || token === "") throw new PermanentError("no GitHub login: run `gh auth login`, or set GH_TOKEN");
218
-
219
- return token;
220
- };
221
-
222
- const retryOnce: NonNullable<ThrottlingOptions["onRateLimit"]> = (_retryAfter, _options, _octokit, retryCount) => retryCount < RATE_LIMIT_RETRIES;
223
-
224
- type Send = (url: string, init?: RequestInit) => Promise<Response>;
225
-
226
- export type GitHubClientOptions = {
227
- readonly token: string;
228
- readonly baseUrl?: string;
229
- /** Replaces `fetch`, for a GitHub that is not github.com. */
230
- readonly fetch?: Send;
231
- /** Whether writes are spaced as GitHub asks; only a GitHub with no secondary rate limit may go without. */
232
- readonly spaced?: boolean;
233
- /** The owner's `commandTimeoutSeconds` in milliseconds: how long one request may wait for GitHub's answer. */
234
- readonly timeoutMs: number;
235
- };
236
-
237
- const bounded =
238
- (send: Send, timeoutMs: number): Send =>
239
- (url, init) =>
240
- send(url, { ...init, signal: AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(init?.signal ? [init.signal] : [])]) });
241
-
242
- /** A GitHub client that waits out rate limits, spaces its writes as GitHub asks, and gives up on a request GitHub has not answered within `timeoutMs`. */
243
- export const gitHubClient = ({ token, baseUrl, fetch = globalThis.fetch, spaced = true, timeoutMs }: GitHubClientOptions): GitHubClient =>
244
- new HumOctokit({
245
- auth: token,
246
- userAgent: "hum",
247
- baseUrl,
248
- request: { fetch: bounded(fetch, timeoutMs) },
249
- throttle: { enabled: spaced, onRateLimit: retryOnce, onSecondaryRateLimit: retryOnce },
250
- });
251
-
252
148
  export type GitHubOptions = {
253
149
  /** `owner/name`. */
254
150
  readonly repo: string;
@@ -259,40 +155,57 @@ export type GitHubOptions = {
259
155
  /** Open issues with this label are the ready items. */
260
156
  readonly readyLabel: string;
261
157
  readonly mergeMethod: (typeof MERGE_METHODS)[number];
158
+ /** Logins whose comments are read whatever GitHub says of them, beside the people the repo trusts. */
159
+ readonly ownerLogins: readonly string[];
262
160
  /** The client to use; by default one on the owner's own login. */
263
161
  readonly client?: GitHubClient;
264
162
  /** The owner's `commandTimeoutSeconds` in milliseconds: the limit of the `gh auth token` that reads the owner's login. */
265
163
  readonly timeoutMs: number;
266
164
  };
267
165
 
268
- type Whole = Adapter & {
166
+ type Whole = Integrations & {
269
167
  readonly workSource: WorkSource;
270
168
  readonly questions: Questions;
271
169
  readonly answers: Answers;
272
170
  readonly release: Release;
273
- /** Requests so far that spent rate limit; a 304 spends none. */
171
+ /** Requests so far on its client that spent rate limit; a 304 spends none. The owner's client is shared, so other readers count too. */
274
172
  readonly spent: () => number;
275
173
  };
276
174
 
277
175
  type StandingClaim = { readonly claim: Claim; readonly sha: string };
278
176
 
177
+ const TRUSTED: ReadonlySet<string> = new Set(TRUSTED_ASSOCIATIONS);
178
+
179
+ /**
180
+ * Whether hum reads a comment. Anyone may comment on a public repo, a reply after a question is an answer, and hum's
181
+ * marker is only text, so who wrote a comment decides, never what it says. A person's is read when the repo trusts
182
+ * 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
183
+ * bot or the owner's App, and only a workflow or an App the owner installed posts as a bot at all.
184
+ */
185
+ const isHeard = (owners: ReadonlySet<string>) => ({ body, author, authorAssociation }: IssueComment): boolean => {
186
+ if (author === null) return false;
187
+
188
+ return author.__typename === "Bot" ? parseComment(body, 0).author === "hum" : owners.has(author.login.toLowerCase()) || TRUSTED.has(authorAssociation);
189
+ };
190
+
279
191
  /**
280
- * GitHub on the owner's own login: issues are items, comments are the thread. Each read is one GraphQL query,
192
+ * GitHub on the owner's own login: issues are items, and the comments hum reads are the thread. Each read is one GraphQL query,
281
193
  * each write one mutation. A claim is a branch: its first commit is made through REST, since no mutation makes a
282
194
  * bare commit, and created with `createRef`; a renewal or an expired take is `createCommitOnBranch` on the head it
283
195
  * read. `watch` is one REST request with `If-None-Match`, because GitHub answers 304 free of rate limit.
284
196
  */
285
- export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext): Whole => {
197
+ export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterContext): Whole => {
286
198
  const { base, claimPrefix, readyLabel, mergeMethod, timeoutMs } = options;
199
+ const isHeardHere = isHeard(new Set(options.ownerLogins.map((login) => login.toLowerCase())));
287
200
  const repo = parseArgument(Repo, options.repo);
288
201
  const [owner = "", name = ""] = repo.split("/");
289
202
  const where = { owner, name };
290
203
  const claimRefs = `refs/heads/${claimPrefix}`;
291
- const issueIds = new Map<number, string>();
204
+ const issueIds = new ExpiryMap<number, string>(ISSUE_ID_KEPT_MS);
292
205
  let spent = 0;
293
206
 
294
207
  const client = pMemoize(async () => {
295
- const made = options.client ?? gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs });
208
+ const made = options.client ?? (await ownerGitHub(timeoutMs, env));
296
209
 
297
210
  made.hook.after("request", () => void spent++);
298
211
  made.hook.error("request", (error) => {
@@ -336,7 +249,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
336
249
 
337
250
  issueIds.set(number, repository.issue.id);
338
251
 
339
- return repository;
252
+ return { ...repository, issue: { ...repository.issue, comments: { nodes: repository.issue.comments.nodes.filter(isHeardHere) } } };
340
253
  };
341
254
 
342
255
  const comment = async (id: string, body: string): Promise<void> => {
@@ -354,7 +267,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
354
267
  return { repository: repository.id, label: repository.label?.id ?? (await made()) };
355
268
  });
356
269
 
357
- const claimFrom = (item: string, target: { oid?: string; message?: string } | undefined): Claim | undefined => claimOfCommit(item, target?.message ?? "");
270
+ const claimFrom = (item: ItemId, target: { oid?: string; message?: string } | undefined): Claim | undefined => claimOfCommit(item, target?.message ?? "");
358
271
 
359
272
  const firstClaim = async (claim: Claim): Promise<boolean> => {
360
273
  const { repository } = await query(BaseReply, BASE, { baseRef: `refs/heads/${base}` });
@@ -384,14 +297,10 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
384
297
  now,
385
298
  );
386
299
 
387
- const pullFor = async (id: string, head: string) => {
388
- const { repository } = await query(PullsReply, PULLS, { number: parseArgument(IssueNumber, id), head });
389
-
390
- return { ...repository, pull: repository.pullRequests.nodes[0] };
391
- };
300
+ const pulls = gitHubPullRequests(repo, { timeoutMs, client });
392
301
 
393
302
  return {
394
- apiVersion: 1,
303
+ apiVersion: ADAPTER_API_VERSION,
395
304
  spent: () => spent,
396
305
  workSource: {
397
306
  listReady: async () => {
@@ -399,9 +308,13 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
399
308
 
400
309
  if (refs.totalCount > refs.nodes.length) throw new PermanentError(`${repo} holds ${refs.totalCount} claim branches; hum reads ${refs.nodes.length}`);
401
310
 
402
- const claims = new Map(refs.nodes.map((ref) => [ref.name, claimFrom(ref.name, ref.target)]));
311
+ const claims = new Map(refs.nodes.flatMap((ref) => {
312
+ const item = ItemId.safeParse(ref.name);
313
+
314
+ return item.success ? [[ref.name, claimFrom(item.data, ref.target)] as const] : [];
315
+ }));
403
316
 
404
- return issues.nodes.flatMap(({ number, title }) => (isLive(claims.get(String(number)), now()) ? [] : [{ id: String(number), title }]));
317
+ return issues.nodes.flatMap(({ number, title }) => (isLive(claims.get(String(number)), now()) ? [] : [{ id: ItemId.parse(String(number)), title }]));
405
318
  },
406
319
  read: async (id): Promise<Item> => {
407
320
  const { issue, ref } = await fetchItem(parseArgument(IssueNumber, id));
@@ -415,8 +328,8 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
415
328
  labels: issue.labels.nodes.map((label) => label.name),
416
329
  };
417
330
  },
418
- claim: (id, holder, ttlMs) => take("claim", String(parseArgument(IssueNumber, id)), holder, ttlMs),
419
- renew: (id, holder, ttlMs) => take("renew", String(parseArgument(IssueNumber, id)), holder, ttlMs),
331
+ claim: (id, holder, ttlMs) => take("claim", parseArgument(IssueId, id), holder, ttlMs),
332
+ renew: (id, holder, ttlMs) => take("renew", parseArgument(IssueId, id), holder, ttlMs),
420
333
  comment: (id, text) => comment(id, commentText(text)),
421
334
  fileFollowUp: async (from, { title, body }) => {
422
335
  const { issue } = await fetchItem(parseArgument(IssueNumber, from));
@@ -431,7 +344,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
431
344
  };
432
345
 
433
346
  const recent = (await query(RecentIssuesReply, RECENT_ISSUES, {})).repository.issues.nodes;
434
- const id = String(recent.find(isFollowUpOf(`#${from}`, title))?.number ?? (await created()));
347
+ const id = ItemId.parse(String(recent.find(isFollowUpOf(`#${from}`, title))?.number ?? (await created())));
435
348
  const note = followUpNote(title, id);
436
349
 
437
350
  await commentMarked(from, note.marker, note.text);
@@ -461,18 +374,20 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
461
374
  },
462
375
  release: {
463
376
  publish: async (id, ref) => {
464
- const { pull, issue, id: repository } = await pullFor(id, ref);
377
+ const found = await pulls.find(ref);
378
+
379
+ if (found !== undefined && found.state !== "CLOSED") return;
465
380
 
466
- if (pull) return;
381
+ const { issue } = await fetchItem(parseArgument(IssueNumber, id));
467
382
 
468
- await mutate(Acknowledged, CREATE_PULL, { repository, base, head: ref, title: issue.title, body: `Closes #${id}` });
383
+ await pulls.open({ head: ref, base, title: issue.title, body: `Closes #${id}` });
469
384
  },
470
385
  release: async (id, ref) => {
471
- const { pull } = await pullFor(id, ref);
386
+ const pull = await pulls.find(ref);
472
387
 
473
- if (!pull) throw new PermanentError(`no pull request from ${ref} to release for item ${id}`);
388
+ if (!pull || pull.state === "CLOSED") throw new PermanentError(`no pull request from ${ref} to release for item ${id}`);
474
389
 
475
- if (pull.state === "OPEN") await mutate(Acknowledged, MERGE_PULL, { pull: pull.id, mergeMethod: MERGE_METHOD[mergeMethod] });
390
+ if (pull.state === "OPEN") await pulls.merge(pull, mergeMethod);
476
391
  },
477
392
  },
478
393
  };
@@ -1,6 +1,6 @@
1
1
  import pRetry, { AbortError, type RetryContext } from "p-retry";
2
2
  import { z } from "zod";
3
- import { type Adapter, ClaimResult, Item, ItemRef, PermanentError, Watch, type WorkSource } from "../adapter-api.ts";
3
+ import { type Adapter, ClaimResult, Failed, type Fallible, type Integrations, Item, ItemId, ItemRef, PermanentError, Watch, type WorkSource } from "../adapter-api.ts";
4
4
  import { type HumConfig, SHIPPED_DEFAULTS } from "../config/schema.ts";
5
5
  import type { Faults } from "../state/faults.ts";
6
6
  import { SECOND_MS } from "../time.ts";
@@ -42,10 +42,11 @@ const abortIfPermanent = (cause: unknown): never => {
42
42
  * - A transient failure is retried inside the timeout; one that outlasts it raises one card and throws.
43
43
  * - An empty ready list that contradicts the last read is a fault, not "no work".
44
44
  * - A call that would double on a retry (`comment`, `ask`, `decide`, `answer`) runs once; its caller retries it under an op key.
45
+ * - An answer of `failed: "now"` raises one card and throws at once; `failed: "retry"` is a transient failure like any other.
45
46
  */
46
- export const guarded = (adapter: Adapter, { provider, faults, timeoutMs, backoffMs = SHIPPED_BACKOFF_MS, lastReady: remembered }: GuardOptions): Adapter => {
47
- const unavailable = `provider-unavailable:${provider}`;
48
- const contradicted = `empty-list:${provider}`;
47
+ export const guarded = (adapter: Adapter, { provider, faults, timeoutMs, backoffMs = SHIPPED_BACKOFF_MS, lastReady: remembered }: GuardOptions): Integrations => {
48
+ const unavailable = { code: "provider-unavailable", item: provider };
49
+ const contradicted = { code: "empty-list", item: provider };
49
50
 
50
51
  const refuseChangedReply = (error: z.ZodError): never => {
51
52
  const [issue] = error.issues;
@@ -71,14 +72,24 @@ export const guarded = (adapter: Adapter, { provider, faults, timeoutMs, backoff
71
72
  });
72
73
  };
73
74
 
74
- const once = async <T>(call: () => Promise<T>, schema: z.ZodType<T>): Promise<T> => {
75
+ const failNow = ({ why }: Failed): never => {
76
+ faults.raise({ code: "provider-failed", item: provider, cause: `${provider} could not complete a call: ${why}`, fix: `Fix what ${provider} names, or update its adapter; hum calls it again on its next tick.` });
77
+
78
+ throw new PermanentError(`${provider}: ${why}`);
79
+ };
80
+
81
+ const once = async <T>(call: () => Promise<T | Failed>, schema: z.ZodType<T>): Promise<T> => {
75
82
  const reply = await call();
83
+ const failed = Failed.safeParse(reply);
84
+
85
+ if (failed.success) return failed.data.failed === "now" ? failNow(failed.data) : Promise.reject(new Error(`${provider}: ${failed.data.why}`));
86
+
76
87
  const parsed = schema.safeParse(reply);
77
88
 
78
89
  return parsed.success ? parsed.data : refuseChangedReply(parsed.error);
79
90
  };
80
91
 
81
- const retried = async <T>(call: () => Promise<T>, schema: z.ZodType<T>): Promise<T> => {
92
+ const retried = async <T>(call: () => Promise<T | Failed>, schema: z.ZodType<T>): Promise<T> => {
82
93
  const value = await pRetry(() => once(call, schema).catch(abortIfPermanent), {
83
94
  retries: Number.POSITIVE_INFINITY,
84
95
  maxRetryTime: timeoutMs,
@@ -93,15 +104,15 @@ export const guarded = (adapter: Adapter, { provider, faults, timeoutMs, backoff
93
104
  };
94
105
 
95
106
  const { workSource, questions, answers, release } = adapter;
96
- let lastReadyIds: string[] = remembered?.load() ?? [];
107
+ let lastReadyIds: ItemId[] = (remembered?.load() ?? []).flatMap((id) => ItemId.safeParse(id).data ?? []);
97
108
 
98
- const firstStillReady = async (source: WorkSource, ids: readonly string[]): Promise<string | undefined> => {
109
+ const firstStillReady = async (source: Fallible<WorkSource>, ids: readonly ItemId[]): Promise<ItemId | undefined> => {
99
110
  for (const id of ids) if ((await retried(() => source.read(id), Item)).ready) return id;
100
111
 
101
112
  return undefined;
102
113
  };
103
114
 
104
- const refuseContradictingEmptyList = async (source: WorkSource): Promise<void> => {
115
+ const refuseContradictingEmptyList = async (source: Fallible<WorkSource>): Promise<void> => {
105
116
  const stillReady = await firstStillReady(source, lastReadyIds);
106
117
 
107
118
  if (stillReady === undefined) return;