@moo.md/hum 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/package.json +2 -2
  2. package/scripts/eval.ts +88 -50
  3. package/src/adapter-api.ts +46 -14
  4. package/src/adapters/admit.ts +2 -2
  5. package/src/adapters/argument.ts +1 -1
  6. package/src/adapters/claim.ts +18 -15
  7. package/src/adapters/claude-bg.ts +50 -27
  8. package/src/adapters/claude-p.ts +18 -23
  9. package/src/adapters/contract.ts +22 -10
  10. package/src/adapters/each-call.ts +9 -0
  11. package/src/adapters/fake.ts +6 -6
  12. package/src/adapters/git.ts +10 -18
  13. package/src/adapters/github-client.ts +102 -0
  14. package/src/adapters/github.ts +34 -142
  15. package/src/adapters/guard.ts +20 -9
  16. package/src/adapters/history.ts +12 -15
  17. package/src/adapters/item-file.ts +1 -1
  18. package/src/adapters/markdown.ts +49 -42
  19. package/src/adapters/marked.ts +6 -12
  20. package/src/adapters/model-call.ts +4 -4
  21. package/src/adapters/once.ts +5 -5
  22. package/src/adapters/owner-commit.ts +13 -11
  23. package/src/adapters/pull-requests.ts +11 -13
  24. package/src/adapters/registry.ts +7 -7
  25. package/src/adapters/roundup.ts +27 -35
  26. package/src/adapters/serial.ts +4 -5
  27. package/src/adapters/transcript.ts +13 -8
  28. package/src/cli/main.ts +1 -0
  29. package/src/cli/ops.ts +32 -14
  30. package/src/cli/service.ts +14 -8
  31. package/src/cli/setup.ts +8 -3
  32. package/src/cli/shared-watch.ts +3 -3
  33. package/src/config/checks.ts +14 -18
  34. package/src/config/machine.ts +5 -7
  35. package/src/config/refusal.ts +7 -0
  36. package/src/config/schema.ts +7 -7
  37. package/src/config/settings.ts +17 -2
  38. package/src/config/state-map.ts +5 -3
  39. package/src/decide/alignment.ts +4 -4
  40. package/src/decide/answer.ts +24 -22
  41. package/src/decide/kind.ts +1 -6
  42. package/src/decide/labels.ts +9 -9
  43. package/src/decide/merge.ts +6 -7
  44. package/src/decide/prose.ts +4 -4
  45. package/src/decide/question.ts +23 -20
  46. package/src/decide/review.ts +4 -2
  47. package/src/decide/risk.ts +25 -19
  48. package/src/decide/taste.ts +3 -3
  49. package/src/exec.ts +4 -3
  50. package/src/index.ts +14 -13
  51. package/src/loop/check-item.ts +3 -3
  52. package/src/loop/ci.ts +1 -1
  53. package/src/loop/github.ts +2 -2
  54. package/src/loop/groups.ts +13 -6
  55. package/src/loop/memory.ts +40 -28
  56. package/src/loop/notes.ts +5 -5
  57. package/src/loop/pair.ts +1 -1
  58. package/src/loop/pass.ts +18 -12
  59. package/src/loop/proof.ts +9 -7
  60. package/src/loop/prove-item.ts +1 -1
  61. package/src/loop/records.ts +12 -13
  62. package/src/loop/signals.ts +6 -6
  63. package/src/measure/inputs.ts +1 -1
  64. package/src/measure/measure.ts +4 -4
  65. package/src/measure/rate.ts +2 -0
  66. package/src/service/ci-tick.ts +2 -2
  67. package/src/service/supervise.ts +3 -2
  68. package/src/service/token.ts +3 -3
  69. package/src/service/wake.ts +2 -2
  70. package/src/service/workflows.ts +2 -2
  71. package/src/setup/propose.ts +4 -4
  72. package/src/setup/prove.ts +18 -12
  73. package/src/setup/scan.ts +31 -24
  74. package/src/setup/shipped.ts +8 -2
  75. package/src/setup/tables.ts +4 -3
  76. package/src/setup/waits.ts +9 -11
  77. package/src/setup/write.ts +17 -10
  78. package/src/slots/pool.ts +32 -24
  79. package/src/state/events.ts +1 -1
  80. package/src/state/faults.ts +13 -5
  81. package/src/state/format.ts +2 -2
  82. package/src/state/items.ts +9 -10
  83. package/src/state/open.ts +2 -2
  84. package/src/state/ops.ts +16 -10
  85. package/src/state/records.ts +5 -5
  86. package/src/state/runs.ts +33 -26
  87. package/src/state/saved.ts +44 -32
  88. package/src/status/file.ts +20 -1
  89. package/src/status/format.ts +47 -57
  90. package/src/status/sections.ts +2 -2
  91. package/src/worker/alignment-report.ts +4 -5
  92. package/src/worker/answers.ts +26 -24
  93. package/src/worker/base-check.ts +2 -2
  94. package/src/worker/kind.ts +23 -19
  95. package/src/worker/land.ts +114 -126
  96. package/src/worker/merged.ts +9 -7
  97. package/src/worker/open.ts +14 -12
  98. package/src/worker/prose-run.ts +3 -3
  99. package/src/worker/questions.ts +15 -12
  100. package/src/worker/scheduler.ts +4 -4
  101. package/src/worker/signature.ts +3 -3
  102. package/src/worker/tally.ts +0 -2
  103. package/src/worker/taste.ts +6 -15
  104. package/src/worker/thin-path.ts +148 -121
  105. package/src/worker/thread.ts +25 -0
  106. package/src/worker/worker.ts +77 -47
  107. package/surface.json +632 -2197
  108. package/src/slots/scan.ts +0 -26
@@ -1,34 +1,28 @@
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 { HOUR_MS } from "../time.ts";
13
9
  import { parseArgument } from "./argument.ts";
14
10
  import { claimCommit, claimCommitMessage, claimer, claimOfCommit, isLive } from "./claim.ts";
11
+ import { failureOf, type GitHubClient, ownerGitHub, raise } from "./github-client.ts";
15
12
  import { answerMarker, commentText, filedFollowUp, followUpBody, followUpNote, isFollowUpOf, type Marker, marked, parseComment, questionMarker, questionText } from "./marked.ts";
13
+ import { gitHubPullRequests } from "./pull-requests.ts";
16
14
 
17
- const RATE_LIMIT_RETRIES = 1;
18
- const NOT_MODIFIED = 304;
19
15
  const READY_LABEL_COLOR = "0e8a16";
20
16
  const READY_LABEL_DESCRIPTION = "hum may take this item";
21
17
 
22
- const HumOctokit = Octokit.plugin(throttling, paginateGraphQL);
23
-
24
- export type GitHubClient = InstanceType<typeof HumOctokit>;
18
+ /** 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. */
19
+ const ISSUE_ID_KEPT_MS = HOUR_MS;
25
20
 
26
21
  type Variables = Readonly<Record<string, Json>>;
27
22
 
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>;
23
+ const IssueId = ItemId.refine((id) => /^[1-9]\d*$/.test(id), "a GitHub issue number is a whole number above 0");
30
24
 
31
- const IssueNumber = ItemId.pipe(z.string().regex(/^[1-9]\d*$/, "a GitHub issue number is a whole number above 0")).transform(Number);
25
+ const IssueNumber = IssueId.transform(Number);
32
26
 
33
27
  const Repo = z.string().regex(/^[\w.-]+\/[\w.-]+$/, "a GitHub repo is owner/name");
34
28
 
@@ -71,14 +65,6 @@ const CreatedIssue = z.object({ createIssue: z.object({ issue: z.object({ number
71
65
 
72
66
  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
67
 
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
68
  const CreatedCommit = z.object({ sha: z.string() });
83
69
 
84
70
  /** The reply of a write whose result hum does not read. */
@@ -121,14 +107,6 @@ const LABEL = `query Label($owner: String!, $name: String!, $label: String!) {
121
107
  repository(owner: $owner, name: $name) { id label(name: $label) { id } }
122
108
  }`;
123
109
 
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
110
  const ADD_COMMENT = `mutation AddComment($subject: ID!, $body: String!) {
133
111
  addComment(input: { subjectId: $subject, body: $body }) { clientMutationId }
134
112
  }`;
@@ -154,50 +132,6 @@ const CREATE_ISSUE = `mutation CreateIssue($repository: ID!, $title: String!, $b
154
132
  createIssue(input: { repositoryId: $repository, title: $title, body: $body, labelIds: $labels }) { issue { number } }
155
133
  }`;
156
134
 
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
135
  /** The `owner/name` of a GitHub remote URL, or undefined for any other host. */
202
136
  export const repoFromRemote = (url: string): string | undefined => {
203
137
  const remote = hostedGitInfo.fromUrl(url.trim());
@@ -205,50 +139,6 @@ export const repoFromRemote = (url: string): string | undefined => {
205
139
  return remote?.type === "github" ? `${remote.user}/${remote.project}` : undefined;
206
140
  };
207
141
 
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
142
  export type GitHubOptions = {
253
143
  /** `owner/name`. */
254
144
  readonly repo: string;
@@ -265,12 +155,12 @@ export type GitHubOptions = {
265
155
  readonly timeoutMs: number;
266
156
  };
267
157
 
268
- type Whole = Adapter & {
158
+ type Whole = Integrations & {
269
159
  readonly workSource: WorkSource;
270
160
  readonly questions: Questions;
271
161
  readonly answers: Answers;
272
162
  readonly release: Release;
273
- /** Requests so far that spent rate limit; a 304 spends none. */
163
+ /** 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
164
  readonly spent: () => number;
275
165
  };
276
166
 
@@ -282,17 +172,17 @@ type StandingClaim = { readonly claim: Claim; readonly sha: string };
282
172
  * bare commit, and created with `createRef`; a renewal or an expired take is `createCommitOnBranch` on the head it
283
173
  * read. `watch` is one REST request with `If-None-Match`, because GitHub answers 304 free of rate limit.
284
174
  */
285
- export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext): Whole => {
175
+ export const githubAdapter = (options: GitHubOptions, { now, env }: AdapterContext): Whole => {
286
176
  const { base, claimPrefix, readyLabel, mergeMethod, timeoutMs } = options;
287
177
  const repo = parseArgument(Repo, options.repo);
288
178
  const [owner = "", name = ""] = repo.split("/");
289
179
  const where = { owner, name };
290
180
  const claimRefs = `refs/heads/${claimPrefix}`;
291
- const issueIds = new Map<number, string>();
181
+ const issueIds = new ExpiryMap<number, string>(ISSUE_ID_KEPT_MS);
292
182
  let spent = 0;
293
183
 
294
184
  const client = pMemoize(async () => {
295
- const made = options.client ?? gitHubClient({ token: await ownerToken(timeoutMs), timeoutMs });
185
+ const made = options.client ?? (await ownerGitHub(timeoutMs, env));
296
186
 
297
187
  made.hook.after("request", () => void spent++);
298
188
  made.hook.error("request", (error) => {
@@ -354,7 +244,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
354
244
  return { repository: repository.id, label: repository.label?.id ?? (await made()) };
355
245
  });
356
246
 
357
- const claimFrom = (item: string, target: { oid?: string; message?: string } | undefined): Claim | undefined => claimOfCommit(item, target?.message ?? "");
247
+ const claimFrom = (item: ItemId, target: { oid?: string; message?: string } | undefined): Claim | undefined => claimOfCommit(item, target?.message ?? "");
358
248
 
359
249
  const firstClaim = async (claim: Claim): Promise<boolean> => {
360
250
  const { repository } = await query(BaseReply, BASE, { baseRef: `refs/heads/${base}` });
@@ -384,14 +274,10 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
384
274
  now,
385
275
  );
386
276
 
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
- };
277
+ const pulls = gitHubPullRequests(repo, { timeoutMs, client });
392
278
 
393
279
  return {
394
- apiVersion: 1,
280
+ apiVersion: ADAPTER_API_VERSION,
395
281
  spent: () => spent,
396
282
  workSource: {
397
283
  listReady: async () => {
@@ -399,9 +285,13 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
399
285
 
400
286
  if (refs.totalCount > refs.nodes.length) throw new PermanentError(`${repo} holds ${refs.totalCount} claim branches; hum reads ${refs.nodes.length}`);
401
287
 
402
- const claims = new Map(refs.nodes.map((ref) => [ref.name, claimFrom(ref.name, ref.target)]));
288
+ const claims = new Map(refs.nodes.flatMap((ref) => {
289
+ const item = ItemId.safeParse(ref.name);
403
290
 
404
- return issues.nodes.flatMap(({ number, title }) => (isLive(claims.get(String(number)), now()) ? [] : [{ id: String(number), title }]));
291
+ return item.success ? [[ref.name, claimFrom(item.data, ref.target)] as const] : [];
292
+ }));
293
+
294
+ return issues.nodes.flatMap(({ number, title }) => (isLive(claims.get(String(number)), now()) ? [] : [{ id: ItemId.parse(String(number)), title }]));
405
295
  },
406
296
  read: async (id): Promise<Item> => {
407
297
  const { issue, ref } = await fetchItem(parseArgument(IssueNumber, id));
@@ -415,8 +305,8 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
415
305
  labels: issue.labels.nodes.map((label) => label.name),
416
306
  };
417
307
  },
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),
308
+ claim: (id, holder, ttlMs) => take("claim", parseArgument(IssueId, id), holder, ttlMs),
309
+ renew: (id, holder, ttlMs) => take("renew", parseArgument(IssueId, id), holder, ttlMs),
420
310
  comment: (id, text) => comment(id, commentText(text)),
421
311
  fileFollowUp: async (from, { title, body }) => {
422
312
  const { issue } = await fetchItem(parseArgument(IssueNumber, from));
@@ -431,7 +321,7 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
431
321
  };
432
322
 
433
323
  const recent = (await query(RecentIssuesReply, RECENT_ISSUES, {})).repository.issues.nodes;
434
- const id = String(recent.find(isFollowUpOf(`#${from}`, title))?.number ?? (await created()));
324
+ const id = ItemId.parse(String(recent.find(isFollowUpOf(`#${from}`, title))?.number ?? (await created())));
435
325
  const note = followUpNote(title, id);
436
326
 
437
327
  await commentMarked(from, note.marker, note.text);
@@ -461,18 +351,20 @@ export const githubAdapter = (options: GitHubOptions, { now }: AdapterContext):
461
351
  },
462
352
  release: {
463
353
  publish: async (id, ref) => {
464
- const { pull, issue, id: repository } = await pullFor(id, ref);
354
+ const found = await pulls.find(ref);
355
+
356
+ if (found !== undefined && found.state !== "CLOSED") return;
465
357
 
466
- if (pull) return;
358
+ const { issue } = await fetchItem(parseArgument(IssueNumber, id));
467
359
 
468
- await mutate(Acknowledged, CREATE_PULL, { repository, base, head: ref, title: issue.title, body: `Closes #${id}` });
360
+ await pulls.open({ head: ref, base, title: issue.title, body: `Closes #${id}` });
469
361
  },
470
362
  release: async (id, ref) => {
471
- const { pull } = await pullFor(id, ref);
363
+ const pull = await pulls.find(ref);
472
364
 
473
- if (!pull) throw new PermanentError(`no pull request from ${ref} to release for item ${id}`);
365
+ if (!pull || pull.state === "CLOSED") throw new PermanentError(`no pull request from ${ref} to release for item ${id}`);
474
366
 
475
- if (pull.state === "OPEN") await mutate(Acknowledged, MERGE_PULL, { pull: pull.id, mergeMethod: MERGE_METHOD[mergeMethod] });
367
+ if (pull.state === "OPEN") await pulls.merge(pull, mergeMethod);
476
368
  },
477
369
  },
478
370
  };
@@ -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;
@@ -3,6 +3,7 @@ import parseDiff from "parse-diff";
3
3
  import PQueue from "p-queue";
4
4
  import pkg from "../../package.json" with { type: "json" };
5
5
  import type { HumConfig } from "../config/schema.ts";
6
+ import { SECOND_MS } from "../time.ts";
6
7
  import { labelChanges, type PastChange } from "../decide/labels.ts";
7
8
  import type { Change, Histories, Label } from "../decide/risk.ts";
8
9
  import { type Git, PATCH } from "./git.ts";
@@ -50,7 +51,7 @@ const readLog = async (
50
51
  return {
51
52
  sha,
52
53
  subject,
53
- committedAt: Number(committed) * 1000,
54
+ committedAt: Number(committed) * SECOND_MS,
54
55
  body: body.trim(),
55
56
  files: counted.map(({ file }) => file),
56
57
  size: counted.reduce((sum, { lines }) => sum + lines, 0),
@@ -79,7 +80,7 @@ const rewrittenRanges = (
79
80
  }),
80
81
  );
81
82
 
82
- /** The changes that wrote the lines `sha` deleted or rewrote: git blame at its parent. */
83
+ /** The changes that wrote the lines `sha` deleted or rewrote: git blame at its parent. A root commit deletes nothing, so it blames nothing; a blame git fails throws. */
83
84
  const blame = async (git: Git, sha: string): Promise<readonly string[]> => {
84
85
  const diff = await git.raw([
85
86
  "show",
@@ -92,7 +93,7 @@ const blame = async (git: Git, sha: string): Promise<readonly string[]> => {
92
93
 
93
94
  const found = await Promise.all(
94
95
  rewrittenRanges(diff).map(async ({ file, from, to }) => {
95
- const result = await git.run([
96
+ const blamed = await git.raw([
96
97
  "blame",
97
98
  "--porcelain",
98
99
  "-L",
@@ -102,11 +103,7 @@ const blame = async (git: Git, sha: string): Promise<readonly string[]> => {
102
103
  file,
103
104
  ]);
104
105
 
105
- return result.code === 0
106
- ? result.stdout
107
- .split("\n")
108
- .flatMap((line) => BLAME_HEADER.exec(line)?.[1] ?? [])
109
- : [];
106
+ return blamed.split("\n").flatMap((line) => BLAME_HEADER.exec(line)?.[1] ?? []);
110
107
  }),
111
108
  );
112
109
 
@@ -124,14 +121,14 @@ export const readHistory = async (
124
121
  ): Promise<PastChange[]> => {
125
122
  const changes = await readLog(git, base, historyDepth);
126
123
 
127
- const rewrites = (change: PastChange): boolean =>
124
+ const doesRewrite = (change: PastChange): boolean =>
128
125
  [changeLabels.fixSubject, changeLabels.revertSubject].some((subject) => new RegExp(subject).test(change.subject));
129
126
 
130
127
  const queue = new PQueue({ concurrency: BLAMES_AT_ONCE });
131
128
 
132
129
  return Promise.all(
133
130
  changes.map(async (change) =>
134
- rewrites(change)
131
+ doesRewrite(change)
135
132
  ? {
136
133
  ...change,
137
134
  blamed: (await queue.add(() => blame(git, change.sha))) ?? [],
@@ -167,7 +164,7 @@ export const historiesOf = (
167
164
  );
168
165
  };
169
166
 
170
- const matchesAny = (sources: readonly string[], line: string): boolean =>
167
+ const doesMatchAny = (sources: readonly string[], line: string): boolean =>
171
168
  sources.some((source) => new RegExp(source).test(line));
172
169
 
173
170
  /** What a diff tells the risk level: the paths, the size, a loosened check and a change to the engine's pin. */
@@ -187,7 +184,7 @@ export const changeOf = (
187
184
  ),
188
185
  );
189
186
 
190
- const holdsPin = (file: parseDiff.File): boolean =>
187
+ const doesHoldPin = (file: parseDiff.File): boolean =>
191
188
  [MANIFEST, ...lockfiles].includes(basename(file.to ?? file.from ?? ""));
192
189
 
193
190
  return {
@@ -204,12 +201,12 @@ export const changeOf = (
204
201
  size: files.reduce((sum, file) => sum + file.additions + file.deletions, 0),
205
202
  loosened: lines.some(
206
203
  ({ change, text }) =>
207
- (change.type === "add" && matchesAny(loosenedCheck.added, text)) ||
208
- (change.type === "del" && matchesAny(loosenedCheck.removed, text)),
204
+ (change.type === "add" && doesMatchAny(loosenedCheck.added, text)) ||
205
+ (change.type === "del" && doesMatchAny(loosenedCheck.removed, text)),
209
206
  ),
210
207
  pinChanged: lines.some(
211
208
  ({ file, change, text }) =>
212
- change.type !== "normal" && holdsPin(file) && text.includes(pkg.name),
209
+ change.type !== "normal" && doesHoldPin(file) && text.includes(pkg.name),
213
210
  ),
214
211
  };
215
212
  };
@@ -20,7 +20,7 @@ const FRONT_MATTER_FENCE = "---";
20
20
 
21
21
  const FrontMatter = z.looseObject({ title: z.string().min(1), state: z.string().min(1), kind: z.string().min(1).optional() });
22
22
 
23
- const EntryMarker = z.strictObject({ kind: z.enum(THREAD_KINDS), at: z.int().nonnegative(), option: z.string().min(1).optional() });
23
+ const EntryMarker = z.object({ kind: z.enum(THREAD_KINDS), at: z.int().nonnegative(), option: z.string().min(1).optional() });
24
24
 
25
25
  const Span = z.object({ start: z.object({ offset: z.int() }), end: z.object({ offset: z.int() }) });
26
26