@tirso0882/factory 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,45 @@
1
+ // Telling the ticket's failures from the model API's, and retrying the API's.
2
+
3
+ import { setTimeout as sleep } from "node:timers/promises"
4
+ import type { Retries } from "./factory.mts"
5
+
6
+ /** A ticket the factory can't finish, for a reason a person should read. */
7
+ export class TicketFailure extends Error {}
8
+
9
+ /**
10
+ * Trouble with the model API or the network, not with the ticket. Only the
11
+ * start of the error is read: further down is agent output, and a ticket about
12
+ * rate limits talks about 429s.
13
+ */
14
+ export const isApiTrouble = (error: unknown) =>
15
+ /overloaded|rate.?limit|usage limit|hit your limit|\b429\b|\b5(00|02|03|29)\b|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up/i.test(
16
+ String(error).slice(0, 500)
17
+ )
18
+
19
+ /**
20
+ * The agent can't log in. Every other ticket would fail the same way, so the
21
+ * run stops, and no ticket is handed off for it.
22
+ */
23
+ export const isAuthFailure = (error: unknown) =>
24
+ /Failed to authenticate|\b401\b|invalid x-api-key|OAuth (access )?token/i.test(
25
+ String(error).slice(0, 500)
26
+ )
27
+
28
+ export const withRetry = async <T,>(
29
+ label: string,
30
+ retries: Retries,
31
+ signal: AbortSignal,
32
+ run: () => Promise<T>
33
+ ) => {
34
+ for (let attempt = 1; ; attempt++) {
35
+ try {
36
+ return await run()
37
+ } catch (error) {
38
+ if (attempt >= retries.agentAttempts || !isApiTrouble(error)) throw error
39
+ console.warn(
40
+ ` ${label} hit API trouble. Retrying in ${retries.delayMs / 1000}s (${attempt}/${retries.agentAttempts}).`
41
+ )
42
+ await sleep(retries.delayMs, undefined, { signal })
43
+ }
44
+ }
45
+ }
@@ -0,0 +1,341 @@
1
+ // Talking to GitHub about tickets: which issues the factory builds, and
2
+ // handing one to a person.
3
+
4
+ import { setTimeout as sleep } from "node:timers/promises"
5
+ import type { ResolvedFactory, ResolvedNames } from "./factory.mts"
6
+ import { OWNER, REPO, gh, ghJson, host, onHost } from "./host.mts"
7
+ import {
8
+ type FactoryPullRequest,
9
+ type GhMergeability,
10
+ partitionByMergeability,
11
+ } from "./pull-requests.mts"
12
+ import {
13
+ type GhPullRequestComment,
14
+ type GhReview,
15
+ type GhReviewThread,
16
+ fromFactory,
17
+ ownerFeedback,
18
+ } from "./review-feedback.mts"
19
+ import {
20
+ type GhIssue,
21
+ type GhParentIssue,
22
+ type Ticket,
23
+ branchFor,
24
+ issueFor,
25
+ ticketText,
26
+ } from "./tickets.mts"
27
+
28
+ const parentOf = (issue: number) => {
29
+ try {
30
+ return ghJson<GhParentIssue>("api", `repos/${REPO}/issues/${issue}/parent`)
31
+ } catch {
32
+ return undefined // It has no parent.
33
+ }
34
+ }
35
+
36
+ /**
37
+ * The open pull requests the factory opened, only those with `label` if you
38
+ * name one. A fork can name its branch like the factory's, so only your own,
39
+ * from this repo, count.
40
+ */
41
+ export const openFactoryPullRequests = (
42
+ names: ResolvedNames,
43
+ label?: string
44
+ ): FactoryPullRequest[] =>
45
+ ghJson<
46
+ (FactoryPullRequest & {
47
+ author: { login: string }
48
+ isCrossRepository: boolean
49
+ })[]
50
+ >(
51
+ "pr",
52
+ "list",
53
+ "--repo",
54
+ REPO,
55
+ "--state",
56
+ "open",
57
+ "--limit",
58
+ "100",
59
+ ...(label === undefined ? [] : ["--label", label]),
60
+ "--json",
61
+ "number,title,body,headRefName,author,isCrossRepository"
62
+ )
63
+ .filter(
64
+ (pr) =>
65
+ pr.headRefName.startsWith(names.branchPrefix) &&
66
+ pr.author.login === OWNER &&
67
+ !pr.isCrossRepository
68
+ )
69
+ .map(({ number, title, body, headRefName }) => ({
70
+ number,
71
+ title,
72
+ body,
73
+ headRefName,
74
+ }))
75
+
76
+ const readMergeability = (numbers: readonly number[]) =>
77
+ numbers.map((n) => ghJson<GhMergeability>("api", `repos/${REPO}/pulls/${n}`))
78
+
79
+ /** The factory's open pull requests that conflict with the base. */
80
+ export const conflictingPullRequests = async (
81
+ factory: ResolvedFactory,
82
+ signal: AbortSignal
83
+ ) => {
84
+ const open = openFactoryPullRequests(factory.names)
85
+ let { conflicting, unknown } = partitionByMergeability(
86
+ readMergeability(open.map((pr) => pr.number))
87
+ )
88
+ if (unknown.length > 0) {
89
+ await sleep(factory.timeouts.mergeabilityRecheckMs, undefined, {
90
+ signal,
91
+ }).catch(() => undefined)
92
+ if (signal.aborted) return []
93
+ const second = partitionByMergeability(readMergeability(unknown))
94
+ conflicting = [...conflicting, ...second.conflicting]
95
+ for (const n of second.unknown) {
96
+ console.warn(
97
+ ` PR #${n} skipped: GitHub hasn't worked out whether it merges.`
98
+ )
99
+ }
100
+ }
101
+ return open.filter((pr) => conflicting.includes(pr.number))
102
+ }
103
+
104
+ /** Issue `number` as a ticket, or nothing if you didn't write it. */
105
+ export const readTicket = (
106
+ names: ResolvedNames,
107
+ number: number
108
+ ): Ticket | undefined => {
109
+ const issue = ghJson<GhIssue>(
110
+ "issue",
111
+ "view",
112
+ String(number),
113
+ "--repo",
114
+ REPO,
115
+ "--json",
116
+ "number,title,body,author,comments"
117
+ )
118
+ if (issue.author.login !== OWNER) return undefined
119
+ return {
120
+ number,
121
+ title: issue.title,
122
+ branch: branchFor(names, number),
123
+ text: ticketText(issue, OWNER, parentOf(number)),
124
+ }
125
+ }
126
+
127
+ /** The ticket a factory branch builds, if its name has one you wrote. */
128
+ export const ticketForBranch = (names: ResolvedNames, branch: string) => {
129
+ const number = issueFor(names, branch)
130
+ return number === undefined
131
+ ? undefined
132
+ : onHost(`Reading issue #${number}`, () => readTicket(names, number))
133
+ }
134
+
135
+ /** Comment on a pull request, signed as the factory's own. */
136
+ export const commentOnPullRequest = (number: number, body: string) =>
137
+ host(
138
+ "gh",
139
+ ["pr", "comment", String(number), "--repo", REPO, "--body-file", "-"],
140
+ fromFactory(body)
141
+ )
142
+
143
+ /** Reply in the thread of review comment `databaseId`, as the factory. */
144
+ export const replyToReviewComment = (
145
+ pullRequest: number,
146
+ databaseId: number,
147
+ body: string
148
+ ) =>
149
+ host(
150
+ "gh",
151
+ [
152
+ "api",
153
+ "--method",
154
+ "POST",
155
+ `repos/${REPO}/pulls/${pullRequest}/comments/${databaseId}/replies`,
156
+ "--input",
157
+ "-",
158
+ ],
159
+ JSON.stringify({ body: fromFactory(body) })
160
+ )
161
+
162
+ export const removeReadyLabel = (names: ResolvedNames, pullRequest: number) =>
163
+ gh(
164
+ "pr",
165
+ "edit",
166
+ String(pullRequest),
167
+ "--repo",
168
+ REPO,
169
+ "--remove-label",
170
+ names.readyLabel
171
+ )
172
+
173
+ const REVIEW_THREADS_QUERY = `
174
+ query($owner: String!, $repo: String!, $number: Int!) {
175
+ repository(owner: $owner, name: $repo) {
176
+ pullRequest(number: $number) {
177
+ reviewThreads(first: 100) {
178
+ nodes {
179
+ id
180
+ isResolved
181
+ isOutdated
182
+ comments(first: 50) {
183
+ nodes { id databaseId path line originalLine body author { login } }
184
+ }
185
+ }
186
+ }
187
+ }
188
+ }
189
+ }`
190
+
191
+ /**
192
+ * Your feedback on pull request `number` (see review-feedback.mts), and the
193
+ * REST id of each thread comment the agent may answer.
194
+ */
195
+ export const readFeedback = (number: number) => {
196
+ const [owner = "", repo = ""] = REPO.split("/")
197
+ const threads = ghJson<{
198
+ data: {
199
+ repository: {
200
+ pullRequest: { reviewThreads: { nodes: GhReviewThread[] } }
201
+ }
202
+ }
203
+ }>(
204
+ "api",
205
+ "graphql",
206
+ "-F",
207
+ `owner=${owner}`,
208
+ "-F",
209
+ `repo=${repo}`,
210
+ "-F",
211
+ `number=${number}`,
212
+ "-f",
213
+ `query=${REVIEW_THREADS_QUERY}`
214
+ ).data.repository.pullRequest.reviewThreads.nodes
215
+ const { comments } = ghJson<{ comments: GhPullRequestComment[] }>(
216
+ "pr",
217
+ "view",
218
+ String(number),
219
+ "--repo",
220
+ REPO,
221
+ "--json",
222
+ "comments"
223
+ )
224
+ const reviews = ghJson<GhReview[]>(
225
+ "api",
226
+ `repos/${REPO}/pulls/${number}/reviews?per_page=100`
227
+ )
228
+ return ownerFeedback(OWNER, { threads, comments, reviews })
229
+ }
230
+
231
+ /**
232
+ * The open, unblocked tickets you wrote that no pull request covers yet.
233
+ * `onlyIssues`, when not empty, limits them to the issues you named.
234
+ */
235
+ export const loadTickets = (
236
+ names: ResolvedNames,
237
+ done: ReadonlySet<number>,
238
+ onlyIssues: ReadonlySet<number>
239
+ ) => {
240
+ const inFlight = new Set(
241
+ openFactoryPullRequests(names).map((pr) => pr.headRefName)
242
+ )
243
+ const issues = ghJson<GhIssue[]>(
244
+ "issue",
245
+ "list",
246
+ "--repo",
247
+ REPO,
248
+ "--state",
249
+ "open",
250
+ "--label",
251
+ names.readyLabel,
252
+ "--limit",
253
+ "100",
254
+ "--json",
255
+ "number,title,body,author,comments"
256
+ )
257
+
258
+ const tickets: Ticket[] = []
259
+ for (const issue of issues) {
260
+ const skip = (reason: string) => {
261
+ if (onlyIssues.has(issue.number)) {
262
+ console.warn(` #${issue.number} skipped: ${reason}.`)
263
+ }
264
+ }
265
+ if (onlyIssues.size > 0 && !onlyIssues.has(issue.number)) continue
266
+ if (done.has(issue.number)) continue
267
+ if (issue.author.login !== OWNER) {
268
+ console.warn(` #${issue.number} skipped: written by someone else.`)
269
+ continue
270
+ }
271
+ if (inFlight.has(branchFor(names, issue.number))) {
272
+ skip("its pull request is open")
273
+ continue
274
+ }
275
+ const blockedBy = Number(
276
+ gh(
277
+ "api",
278
+ `repos/${REPO}/issues/${issue.number}`,
279
+ "--jq",
280
+ ".issue_dependencies_summary.blocked_by // 0"
281
+ )
282
+ )
283
+ if (blockedBy > 0) {
284
+ skip(`${blockedBy} open blocker(s)`)
285
+ continue
286
+ }
287
+ tickets.push({
288
+ number: issue.number,
289
+ title: issue.title,
290
+ branch: branchFor(names, issue.number),
291
+ text: ticketText(issue, OWNER, parentOf(issue.number)),
292
+ })
293
+ }
294
+ for (const n of onlyIssues) {
295
+ if (!issues.some((issue) => issue.number === n)) {
296
+ console.warn(` #${n} skipped: not an open ${names.readyLabel} issue.`)
297
+ }
298
+ }
299
+ return tickets
300
+ }
301
+
302
+ /** Take the ticket off the factory and say why on the issue. */
303
+ export const handToHuman = (
304
+ names: ResolvedNames,
305
+ ticket: Ticket,
306
+ reason: string,
307
+ pullRequest?: string
308
+ ) => {
309
+ const where = pullRequest
310
+ ? `**Pull request:** ${pullRequest}`
311
+ : `**Branch:** \`${ticket.branch}\`, on the factory host only (never pushed).`
312
+ gh(
313
+ "issue",
314
+ "edit",
315
+ String(ticket.number),
316
+ "--repo",
317
+ REPO,
318
+ "--remove-label",
319
+ names.readyLabel,
320
+ "--add-label",
321
+ names.humanLabel
322
+ )
323
+ host(
324
+ "gh",
325
+ [
326
+ "issue",
327
+ "comment",
328
+ String(ticket.number),
329
+ "--repo",
330
+ REPO,
331
+ "--body-file",
332
+ "-",
333
+ ],
334
+ [
335
+ "The Sandcastle factory stopped on this ticket and handed it to a person.",
336
+ `**Why:** ${reason}`,
337
+ where,
338
+ `To give it back, close any open factory pull request and swap \`${names.humanLabel}\` for \`${names.readyLabel}\`. The next run continues from the branch's commits.`,
339
+ ].join("\n\n")
340
+ )
341
+ }
@@ -0,0 +1,106 @@
1
+ // What the host runs itself: git and gh, outside any sandbox. They run in the
2
+ // working directory, which the CLI sets to the project's root before it loads
3
+ // this (cli.mts).
4
+
5
+ import { execFileSync } from "node:child_process"
6
+ import { githubRepo } from "./remote.mts"
7
+
8
+ export const host = (command: string, args: string[], input?: string) =>
9
+ execFileSync(command, args, {
10
+ encoding: "utf8",
11
+ input,
12
+ stdio: ["pipe", "pipe", "pipe"],
13
+ maxBuffer: 64 * 1024 * 1024,
14
+ }).trim()
15
+
16
+ export const git = (...args: string[]) => host("git", args)
17
+ export const gh = (...args: string[]) => host("gh", args)
18
+ export const ghJson = <T,>(...args: string[]) => JSON.parse(gh(...args)) as T
19
+
20
+ // The repo the host pushes to. Its owner is the one whose issues, reviews and
21
+ // comments the factory acts on.
22
+ const { nameWithOwner, owner } = githubRepo(git("remote", "get-url", "origin"))
23
+ export const REPO = nameWithOwner
24
+ export const OWNER = owner
25
+
26
+ export const isAheadOfBase = (baseRef: string, branch: string) => {
27
+ try {
28
+ return Number(git("rev-list", "--count", `${baseRef}..${branch}`)) > 0
29
+ } catch {
30
+ return false // the branch doesn't exist yet
31
+ }
32
+ }
33
+
34
+ /** Remove the worktree a crashed run left on `branch`. Its commits stay. */
35
+ export const discardWorktree = (branch: string) => {
36
+ const entries = git("worktree", "list", "--porcelain").split("\n\n")
37
+ for (const entry of entries) {
38
+ const path = /^worktree (.+)$/m.exec(entry)?.[1]
39
+ if (path && entry.includes(`branch refs/heads/${branch}\n`)) {
40
+ console.warn(` Removing a stale worktree for ${branch} at ${path}.`)
41
+ git("worktree", "remove", "--force", path)
42
+ }
43
+ }
44
+ git("worktree", "prune")
45
+ }
46
+
47
+ export const deleteBranch = (branch: string) => {
48
+ discardWorktree(branch)
49
+ try {
50
+ git("branch", "-D", branch)
51
+ } catch {
52
+ // It doesn't exist.
53
+ }
54
+ }
55
+
56
+ /** The host couldn't push or reach GitHub: not the ticket's fault either. */
57
+ export class HostError extends Error {}
58
+
59
+ export const onHost = <T,>(what: string, run: () => T) => {
60
+ try {
61
+ return run()
62
+ } catch (error) {
63
+ throw new HostError(`${what} failed: ${String(error).split("\n")[0]}`, {
64
+ cause: error,
65
+ })
66
+ }
67
+ }
68
+
69
+ // The branch belongs to the factory. The lease still refuses to overwrite a
70
+ // commit someone else pushed to it.
71
+ export const push = (branch: string) =>
72
+ onHost(`Pushing ${branch}`, () =>
73
+ git("push", "--force-with-lease", "origin", `${branch}:${branch}`)
74
+ )
75
+
76
+ /** Whether commit `ancestor` is in `descendant`'s history. */
77
+ export const isAncestor = (ancestor: string, descendant: string) => {
78
+ try {
79
+ git("merge-base", "--is-ancestor", ancestor, descendant)
80
+ return true
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Point the local `branch` at its head on GitHub, where a person may have
88
+ * pushed since. It refuses to drop local commits that never reached GitHub.
89
+ */
90
+ export const fetchBranch = (branch: string) =>
91
+ onHost(`Fetching ${branch}`, () => {
92
+ discardWorktree(branch)
93
+ const remote = `refs/remotes/origin/${branch}`
94
+ git("fetch", "--quiet", "origin", `+refs/heads/${branch}:${remote}`)
95
+ const local = `refs/heads/${branch}`
96
+ let exists = true
97
+ try {
98
+ git("rev-parse", "--verify", "--quiet", local)
99
+ } catch {
100
+ exists = false
101
+ }
102
+ if (exists && !isAncestor(local, remote)) {
103
+ throw new Error(`${branch} has local commits that aren't on GitHub.`)
104
+ }
105
+ git("branch", "--force", branch, remote)
106
+ })
@@ -0,0 +1,74 @@
1
+ // Reads a project's `.factory/factory.config.mts` and resolves it for this
2
+ // host (see factory.mts). The config's `factory` import is the CLI itself
3
+ // (bin/factory.mjs), so the project needs no Node tooling of its own.
4
+
5
+ import { execFileSync } from "node:child_process"
6
+ import { existsSync, readFileSync, realpathSync } from "node:fs"
7
+ import { homedir } from "node:os"
8
+ import { join } from "node:path"
9
+ import { pathToFileURL } from "node:url"
10
+ import {
11
+ type FactoryConfig,
12
+ type Host,
13
+ type ResolvedFactory,
14
+ checkVersion,
15
+ resolveFactory,
16
+ } from "./factory.mts"
17
+
18
+ const CONFIG_PATH = ".factory/factory.config.mts"
19
+
20
+ /** The version of the CLI that runs, from its package.json. */
21
+ export const factoryVersion = (): string =>
22
+ (
23
+ JSON.parse(
24
+ readFileSync(join(import.meta.dirname, "../package.json"), "utf8")
25
+ ) as { version: string }
26
+ ).version
27
+
28
+ /** The machine this runs on. Commands run only when a toolchain asks. */
29
+ const realHost = (repoRoot: string): Host => ({
30
+ repoRoot,
31
+ factoryVersion: factoryVersion(),
32
+ home: homedir(),
33
+ env: process.env,
34
+ exists: existsSync,
35
+ realPath: realpathSync,
36
+ read: (path) => readFileSync(path, "utf8"),
37
+ output: ([command, ...args]) =>
38
+ execFileSync(command, args, { encoding: "utf8" }).trim(),
39
+ })
40
+
41
+ /** The settings of the project at `repoRoot`, resolved for this host. */
42
+ export const loadFactory = async (
43
+ repoRoot: string
44
+ ): Promise<ResolvedFactory> => {
45
+ const path = join(repoRoot, CONFIG_PATH)
46
+ if (!existsSync(path)) {
47
+ throw new Error(`${repoRoot} has no ${CONFIG_PATH}.`)
48
+ }
49
+ let module: { default?: FactoryConfig }
50
+ try {
51
+ module = (await import(pathToFileURL(path).href)) as typeof module
52
+ } catch (error) {
53
+ // A config for a newer CLI may import what this one lacks, so it fails
54
+ // before resolveFactory can check its range: look for the range in its
55
+ // text, so the error says which version to install.
56
+ const range = /\bversion\s*:\s*["'`]([^"'`]+)["'`]/u.exec(
57
+ readFileSync(path, "utf8")
58
+ )?.[1]
59
+ try {
60
+ checkVersion(range, factoryVersion())
61
+ } catch (versionError) {
62
+ // The cause is the failed import, which the version error explains.
63
+ // eslint-disable-next-line preserve-caught-error
64
+ throw new Error((versionError as Error).message, { cause: error })
65
+ }
66
+ throw error
67
+ }
68
+ if (module.default === undefined) {
69
+ throw new Error(
70
+ `${CONFIG_PATH} must \`export default defineFactory({...})\`.`
71
+ )
72
+ }
73
+ return resolveFactory(module.default, realHost(repoRoot))
74
+ }
@@ -0,0 +1,56 @@
1
+ // Keeping the factory's pull requests mergeable. Pure: no git or gh here, so
2
+ // the tests can load it (pull-requests.test.mts).
3
+
4
+ import type { ResolvedNames } from "./factory.mts"
5
+
6
+ /** An open pull request the factory opened, on its own branch in this repo. */
7
+ export type FactoryPullRequest = {
8
+ number: number
9
+ title: string
10
+ body: string
11
+ headRefName: string
12
+ }
13
+
14
+ /** What `GET /repos/{repo}/pulls/{n}` says about merging pull request `n`. */
15
+ export type GhMergeability = {
16
+ number: number
17
+ mergeable: boolean | null
18
+ mergeable_state: string
19
+ }
20
+
21
+ /**
22
+ * Which pull requests conflict with the base, and which GitHub hasn't checked
23
+ * yet. It computes `mergeable` lazily: the first read after the base moves
24
+ * starts the check and answers `null`, so those need a second read. A pull
25
+ * request that is only behind merges cleanly and is in neither list.
26
+ */
27
+ export const partitionByMergeability = (answers: readonly GhMergeability[]) => {
28
+ const conflicting: number[] = []
29
+ const unknown: number[] = []
30
+ for (const a of answers) {
31
+ if (a.mergeable === null) unknown.push(a.number)
32
+ else if (a.mergeable_state === "dirty") conflicting.push(a.number)
33
+ }
34
+ return { conflicting, unknown }
35
+ }
36
+
37
+ /**
38
+ * The comment on a pull request the factory couldn't update. It is public, so
39
+ * `reason` is one the host wrote or the agent's own explanation, never raw
40
+ * output.
41
+ */
42
+ export const updateFailedComment = (
43
+ names: ResolvedNames,
44
+ reason: string,
45
+ conflicts: readonly string[]
46
+ ) =>
47
+ [
48
+ `The Sandcastle factory couldn't bring this pull request up to date with \`${names.baseBranch}\`. The branch is unchanged.`,
49
+ `**Why:** ${reason}`,
50
+ ...(conflicts.length > 0
51
+ ? [
52
+ `**Conflicted files:**\n\n${conflicts.map((f) => `- \`${f}\``).join("\n")}`,
53
+ ]
54
+ : []),
55
+ `Merge \`${names.baseBranch}\` into the branch by hand, or wait: the next factory run tries again.`,
56
+ ].join("\n\n")
@@ -0,0 +1,18 @@
1
+ // The GitHub repo a project's git remote points at, so the factory works on
2
+ // whichever repo it runs in.
3
+
4
+ export type GitHubRepo = { owner: string; name: string; nameWithOwner: string }
5
+
6
+ // https://github.com/o/r(.git), ssh://git@github.com/o/r(.git), git@github.com:o/r(.git)
7
+ const GITHUB_REMOTE =
8
+ /^(?:https:\/\/(?:[^@/]+@)?|ssh:\/\/git@|git@)github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/u
9
+
10
+ /** The GitHub repo of a remote's URL. */
11
+ export const githubRepo = (remoteUrl: string): GitHubRepo => {
12
+ const match = GITHUB_REMOTE.exec(remoteUrl.trim())
13
+ if (!match) {
14
+ throw new Error(`The git remote ${remoteUrl} isn't a GitHub repo.`)
15
+ }
16
+ const [, owner = "", name = ""] = match
17
+ return { owner, name, nameWithOwner: `${owner}/${name}` }
18
+ }