@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,220 @@
1
+ // Your review of a factory pull request, as the agent that addresses it reads
2
+ // it. Pure: no git or gh here, so the tests can load it
3
+ // (review-feedback.test.mts).
4
+ //
5
+ // The repo is public: anyone can comment on a pull request. So the agent
6
+ // reads only what you wrote, the same rule as `ticketText` in tickets.mts.
7
+
8
+ import type { CiResult } from "./ci.mts"
9
+ import type { ResolvedNames } from "./factory.mts"
10
+
11
+ // The factory posts with your token, so GitHub says you wrote its comments
12
+ // too. This hidden mark tells them apart.
13
+ const FACTORY_MARK = "<!-- sandcastle-factory -->"
14
+
15
+ /** A comment or reply the factory posts, signed and marked as its own. */
16
+ export const fromFactory = (body: string) =>
17
+ `${body.trim()}\n\n<sub>Sent by the Sandcastle factory.</sub>\n${FACTORY_MARK}`
18
+
19
+ // Comments posted before the mark existed all start this way.
20
+ const isFromFactory = (body: string) =>
21
+ body.includes(FACTORY_MARK) || body.startsWith("The Sandcastle factory ")
22
+
23
+ type GhActor = { login: string } | null
24
+
25
+ /** A review thread, from the `reviewThreads` GraphQL query. */
26
+ export type GhReviewThread = {
27
+ id: string
28
+ isResolved: boolean
29
+ isOutdated: boolean
30
+ comments: {
31
+ nodes: {
32
+ /** The GraphQL node id. */
33
+ id: string
34
+ /** The REST id, which the replies endpoint takes. */
35
+ databaseId: number
36
+ path: string | null
37
+ line: number | null
38
+ originalLine: number | null
39
+ body: string
40
+ author: GhActor
41
+ }[]
42
+ }
43
+ }
44
+
45
+ /** A conversation comment, from `gh pr view --json comments`. */
46
+ export type GhPullRequestComment = {
47
+ author: GhActor
48
+ body: string
49
+ createdAt: string
50
+ }
51
+
52
+ /** A review, from `GET /repos/{repo}/pulls/{n}/reviews`. */
53
+ export type GhReview = {
54
+ user: GhActor
55
+ state: string
56
+ body: string
57
+ submitted_at: string | null
58
+ }
59
+
60
+ /** What the agent reads: your unresolved threads, comments and reviews. */
61
+ export type Feedback = {
62
+ threads: {
63
+ threadId: string
64
+ path: string | null
65
+ line: number | null
66
+ outdated: boolean
67
+ comments: { commentId: string; body: string }[]
68
+ }[]
69
+ comments: { body: string; createdAt: string }[]
70
+ reviews: { state: string; body: string; submittedAt: string | null }[]
71
+ }
72
+
73
+ /**
74
+ * Your feedback on a pull request, and the REST id of each thread comment the
75
+ * agent may reply to, by its node id.
76
+ */
77
+ export const ownerFeedback = (
78
+ owner: string,
79
+ gh: {
80
+ threads: readonly GhReviewThread[]
81
+ comments: readonly GhPullRequestComment[]
82
+ reviews: readonly GhReview[]
83
+ }
84
+ ) => {
85
+ const fromOwner = (actor: GhActor, body: string) =>
86
+ actor?.login === owner && !isFromFactory(body)
87
+ const replyTo = new Map<string, number>()
88
+ const threads: Feedback["threads"] = []
89
+ for (const thread of gh.threads) {
90
+ if (thread.isResolved) continue
91
+ const mine = thread.comments.nodes.filter((c) =>
92
+ fromOwner(c.author, c.body)
93
+ )
94
+ if (mine.length === 0) continue
95
+ for (const c of mine) replyTo.set(c.id, c.databaseId)
96
+ threads.push({
97
+ threadId: thread.id,
98
+ path: mine[0]?.path ?? null,
99
+ line: mine[0]?.line ?? mine[0]?.originalLine ?? null,
100
+ outdated: thread.isOutdated,
101
+ comments: mine.map((c) => ({ commentId: c.id, body: c.body })),
102
+ })
103
+ }
104
+ const feedback: Feedback = {
105
+ threads,
106
+ comments: gh.comments
107
+ .filter((c) => fromOwner(c.author, c.body))
108
+ .map(({ body, createdAt }) => ({ body, createdAt })),
109
+ reviews: gh.reviews
110
+ .filter((r) => r.body.trim() !== "" && fromOwner(r.user, r.body))
111
+ .map(({ state, body, submitted_at }) => ({
112
+ state,
113
+ body,
114
+ submittedAt: submitted_at,
115
+ })),
116
+ }
117
+ return { feedback, replyTo }
118
+ }
119
+
120
+ /** A reply the agent wrote to one of your thread comments, by its node id. */
121
+ export type ThreadReply = { commentId: string; body: string }
122
+
123
+ /**
124
+ * The agent's replies the host can post: only those to a comment it fetched,
125
+ * each with the REST id the replies endpoint takes.
126
+ */
127
+ export const filterReplies = (
128
+ replies: readonly ThreadReply[],
129
+ replyTo: ReadonlyMap<string, number>
130
+ ) =>
131
+ replies.flatMap(({ commentId, body }) => {
132
+ const databaseId = replyTo.get(commentId)
133
+ if (databaseId === undefined) {
134
+ console.warn(
135
+ ` Dropping a reply to ${commentId}: not one of the comments fetched.`
136
+ )
137
+ return []
138
+ }
139
+ return [{ databaseId, body }]
140
+ })
141
+
142
+ /** The comment when the agent changed nothing and had nothing to say. */
143
+ export const nothingActionableComment = (names: ResolvedNames) =>
144
+ [
145
+ "The Sandcastle factory read your unresolved review comments and found nothing to change or answer. The branch is unchanged.",
146
+ `To send it back, leave a review comment, then add \`${names.readyLabel}\` again.`,
147
+ ].join("\n\n")
148
+
149
+ /**
150
+ * The comment when the factory couldn't finish. It is public, so `reason` is
151
+ * one the host wrote or the agent's own explanation, never raw output.
152
+ */
153
+ export const addressFailedComment = (names: ResolvedNames, reason: string) =>
154
+ [
155
+ "The Sandcastle factory couldn't finish addressing your review on this pull request.",
156
+ `**Why:** ${reason}`,
157
+ `Commits and replies it already pushed stay. Look at the branch as it is, then add \`${names.readyLabel}\` again to send it back.`,
158
+ ].join("\n\n")
159
+
160
+ const NO_CI_FAILURE =
161
+ "None: CI passes on the branch's head, or it has no checks."
162
+
163
+ /**
164
+ * Whether the agent has anything to address: your feedback, or CI that fails
165
+ * on the head it starts from. `ciFailure` is what the prompt's CI FAILURE
166
+ * section says. It goes to the agent only, never into a comment.
167
+ */
168
+ export const whatToAddress = (
169
+ feedback: Feedback,
170
+ ci: CiResult
171
+ ): "nothing actionable" | { ciFailure: string } => {
172
+ if (!ci.passed) return { ciFailure: ci.log }
173
+ const empty =
174
+ feedback.threads.length === 0 &&
175
+ feedback.comments.length === 0 &&
176
+ feedback.reviews.length === 0
177
+ return empty ? "nothing actionable" : { ciFailure: NO_CI_FAILURE }
178
+ }
179
+
180
+ /**
181
+ * What the host does once the agent stops, from CI on the head it started
182
+ * from, its new commits and how many replies and comments it wrote. On red
183
+ * CI with no commit, what it said is still posted, then the run fails.
184
+ */
185
+ export const afterAddressing = (
186
+ ci: CiResult,
187
+ agent: { commits: number; said: number }
188
+ ): "nothing to do" | "publish" | "no fix for CI" => {
189
+ if (!ci.passed && agent.commits === 0) return "no fix for CI"
190
+ if (agent.commits === 0 && agent.said === 0) return "nothing to do"
191
+ return "publish"
192
+ }
193
+
194
+ // Shorter lines are words a reply may well share with the log.
195
+ const MIN_QUOTE_CHARS = 20
196
+
197
+ /**
198
+ * What the agent wrote, without anything that quotes a line of the CI `log`:
199
+ * it is posted publicly, and the log never is. The check names and job links
200
+ * the host put in the log may stay.
201
+ */
202
+ export const withoutLogQuotes = <T extends { body: string }>(
203
+ said: readonly T[],
204
+ log: string
205
+ ): T[] => {
206
+ const quotable = log
207
+ .split("\n")
208
+ .filter((line) => !line.startsWith("## ") && !line.startsWith("http"))
209
+ // "<step> | <line>": a quote would be of the line.
210
+ .map((line) => {
211
+ const step = line.indexOf(" | ")
212
+ return (step === -1 ? line : line.slice(step + 3)).trim()
213
+ })
214
+ .filter((line) => line.length >= MIN_QUOTE_CHARS)
215
+ return said.filter(({ body }) => {
216
+ const quotes = quotable.some((line) => body.includes(line))
217
+ if (quotes) console.warn(" Dropping a reply that quotes the CI log.")
218
+ return !quotes
219
+ })
220
+ }
@@ -0,0 +1,144 @@
1
+ // An agent's answer to the host, read as structured output: the work run,
2
+ // then a short run that resumes its session and asks for the answer as JSON in
3
+ // a tag. Ported from Sandcastle's own factory
4
+ // (`sandcastle/.sandcastle/agent-workflows/shared/run-with-extraction.ts`),
5
+ // which runs on top-level `run()`. Ours runs on a `Sandbox`, and 0.14's
6
+ // `box.run` takes `resumeSession` but not `output`, so the host reads the tag
7
+ // and validates it here, the way `run()` does.
8
+
9
+ import type {
10
+ OutputObjectDefinition,
11
+ Sandbox,
12
+ SandboxRunOptions,
13
+ SandboxRunResult,
14
+ } from "@ai-hero/sandcastle"
15
+ import type { Retries } from "./factory.mts"
16
+ import { TicketFailure, withRetry } from "./failures.mts"
17
+
18
+ export type Answer<T> =
19
+ | { ok: true; value: T }
20
+ | { ok: false; problem: string; raw: string | undefined }
21
+
22
+ const lastTagContent = (text: string, tag: string) => {
23
+ const open = `<${tag}>`
24
+ const close = `</${tag}>`
25
+ let content: string | undefined
26
+ for (let from = 0; ;) {
27
+ const start = text.indexOf(open, from)
28
+ if (start === -1) return content
29
+ const end = text.indexOf(close, start + open.length)
30
+ if (end === -1) return content
31
+ content = text.slice(start + open.length, end)
32
+ from = end + close.length
33
+ }
34
+ }
35
+
36
+ const unwrapFences = (text: string) =>
37
+ /^```(?:json)?\s*\n(?<body>[\s\S]*?)\n\s*```\s*$/u
38
+ .exec(text)
39
+ ?.groups?.body?.trim() ?? text
40
+
41
+ /**
42
+ * The answer in the last `<tag>` of `stdout`, checked against the schema. The
43
+ * agent may quote the prompt's example first, so the last tag counts.
44
+ */
45
+ export const readAnswer = async <T,>(
46
+ stdout: string,
47
+ output: OutputObjectDefinition<T>
48
+ ): Promise<Answer<T>> => {
49
+ const raw = lastTagContent(stdout, output.tag)
50
+ if (raw === undefined) {
51
+ return { ok: false, problem: `No <${output.tag}> tag.`, raw }
52
+ }
53
+ let parsed: unknown
54
+ try {
55
+ parsed = JSON.parse(unwrapFences(raw.trim()))
56
+ } catch (error) {
57
+ return { ok: false, problem: `Not JSON: ${String(error)}`, raw }
58
+ }
59
+ const result = await output.schema["~standard"].validate(parsed)
60
+ if (result.issues) {
61
+ const issues = result.issues.map((issue) => {
62
+ const path = issue.path
63
+ ?.map((key) => (typeof key === "object" ? key.key : key))
64
+ .join(".")
65
+ return `- ${path ? `${path}: ` : ""}${issue.message}`
66
+ })
67
+ return {
68
+ ok: false,
69
+ problem: `It doesn't match the schema:\n${issues.join("\n")}`,
70
+ raw,
71
+ }
72
+ }
73
+ return { ok: true, value: result.value }
74
+ }
75
+
76
+ const retryPrompt = (tag: string, problem: string, raw: string | undefined) =>
77
+ `Your answer couldn't be read.
78
+
79
+ ${problem}
80
+
81
+ ${raw === undefined ? "" : `What you sent:\n${raw}\n\n`}Send only a corrected <${tag}> block. Don't change files or run commands.`
82
+
83
+ export interface RunWithExtractionOptions<T> extends SandboxRunOptions {
84
+ /** Who answers, for the failure: "the reviewer". */
85
+ readonly role: string
86
+ readonly output: OutputObjectDefinition<T>
87
+ /** Asks for the answer. It must show the `<tag>` the output reads. */
88
+ readonly extractionPrompt: string
89
+ /** How often to try again when the model API has trouble. */
90
+ readonly retries: Retries
91
+ }
92
+
93
+ /** Extra tries at the answer after the first. */
94
+ const MAX_ANSWER_RETRIES = 2
95
+
96
+ /**
97
+ * Run the agent on `box`, then ask it for its answer in the same session. An
98
+ * answer that never validates is a `TicketFailure`: a person reads why.
99
+ */
100
+ export const runWithExtraction = async <T,>(
101
+ box: Pick<Sandbox, "run">,
102
+ options: RunWithExtractionOptions<T>
103
+ ): Promise<SandboxRunResult & { output: T }> => {
104
+ const { role, output, extractionPrompt, retries, ...workOptions } = options
105
+ const name = workOptions.name ?? role
106
+ const signal = workOptions.signal ?? new AbortController().signal
107
+ const work = await withRetry(name, retries, signal, () =>
108
+ box.run(workOptions)
109
+ )
110
+
111
+ let session = work.iterations.at(-1)?.sessionId
112
+ let prompt = extractionPrompt
113
+ for (let attempt = 0; ; attempt++) {
114
+ if (!session) {
115
+ throw new Error(`${name} left no session to read its answer from.`)
116
+ }
117
+ const resumeSession = session
118
+ const extraction = await withRetry(
119
+ `${name} (answer)`,
120
+ retries,
121
+ signal,
122
+ () =>
123
+ box.run({
124
+ agent: workOptions.agent,
125
+ name: `${name} (answer)`,
126
+ prompt,
127
+ // No completion signal: the resumed turn ends on its own, and a
128
+ // closing tag the agent quotes before its answer would cut it short.
129
+ resumeSession,
130
+ idleTimeoutSeconds: workOptions.idleTimeoutSeconds,
131
+ logging: workOptions.logging,
132
+ signal,
133
+ })
134
+ )
135
+ const answer = await readAnswer(extraction.stdout, output)
136
+ if (answer.ok) return { ...work, output: answer.value }
137
+ console.warn(` ${name}: couldn't read its answer. ${answer.problem}`)
138
+ if (attempt >= MAX_ANSWER_RETRIES) {
139
+ throw new TicketFailure(`The factory couldn't read ${role}'s answer.`)
140
+ }
141
+ session = extraction.iterations.at(-1)?.sessionId
142
+ prompt = retryPrompt(output.tag, answer.problem, answer.raw)
143
+ }
144
+ }
@@ -0,0 +1,60 @@
1
+ // Running setup steps in a fresh sandbox. Pure apart from the sandbox it's
2
+ // given, so the tests can hand it a fake one (setup.test.mts).
3
+
4
+ import type { Sandbox } from "@ai-hero/sandcastle"
5
+
6
+ export type SetupStep = { command: string; timeoutSeconds?: number }
7
+
8
+ const DEFAULT_SETUP_TIMEOUT_SECONDS = 120
9
+ const MAX_SETUP_OUTPUT_LINES = 30
10
+
11
+ /** A setup step failed: the sandbox isn't fit for an agent. */
12
+ export class SandboxSetupError extends Error {}
13
+
14
+ /** `text` as one word for `sh`. */
15
+ export const shellQuote = (text: string) => `'${text.replaceAll("'", `'\\''`)}'`
16
+
17
+ /**
18
+ * Run the setup steps in the sandbox, side by side, and throw if any fails.
19
+ *
20
+ * Sandcastle 0.14's `createSandbox()` ignores an `onSandboxReady` hook's exit
21
+ * code and its `timeoutMs`, so a failed install would hand the agent a broken
22
+ * worktree. The steps run here instead, each under coreutils' `timeout`
23
+ * because `exec()` takes no deadline. Once a release has the fix (its
24
+ * changeset is reject-failed-ready-hooks), they can go back to being hooks.
25
+ */
26
+ export const runSetupSteps = async (
27
+ box: Pick<Sandbox, "exec">,
28
+ steps: readonly SetupStep[]
29
+ ) => {
30
+ const results = await Promise.all(
31
+ steps.map(async (step) => {
32
+ const seconds = step.timeoutSeconds ?? DEFAULT_SETUP_TIMEOUT_SECONDS
33
+ const result = await box.exec(
34
+ `timeout --kill-after=30 ${seconds} sh -c ${shellQuote(step.command)}`
35
+ )
36
+ return { step, seconds, result }
37
+ })
38
+ )
39
+ const failed = results.filter((r) => r.result.exitCode !== 0)
40
+ if (failed.length === 0) return
41
+ const summary = failed
42
+ .map(({ step, seconds, result }) =>
43
+ // 124 is timeout's own exit code; 137 is its SIGKILL after the grace.
44
+ result.exitCode === 124 || result.exitCode === 137
45
+ ? `\`${step.command}\` timed out after ${seconds}s`
46
+ : `\`${step.command}\` exited ${result.exitCode}`
47
+ )
48
+ .join("; ")
49
+ const output = failed
50
+ .map(({ step, result }) => {
51
+ const tail = `${result.stdout}\n${result.stderr}`
52
+ .trim()
53
+ .split("\n")
54
+ .slice(-MAX_SETUP_OUTPUT_LINES)
55
+ .join("\n")
56
+ return `--- ${step.command}\n${tail}`
57
+ })
58
+ .join("\n")
59
+ throw new SandboxSetupError(`Sandbox setup failed: ${summary}.\n${output}`)
60
+ }
@@ -0,0 +1,73 @@
1
+ // A ticket and what the agents read of it. Pure: no git or gh here, so the
2
+ // tests can load it (tickets.test.mts).
3
+
4
+ import type { ResolvedNames } from "./factory.mts"
5
+
6
+ export type Ticket = {
7
+ number: number
8
+ title: string
9
+ branch: string
10
+ /** What the agents read: the body, your comments and the parent's body. */
11
+ text: string
12
+ }
13
+
14
+ export type GhIssue = {
15
+ number: number
16
+ title: string
17
+ body: string
18
+ author: { login: string }
19
+ comments: { author: { login: string }; body: string }[]
20
+ }
21
+
22
+ export type GhParentIssue = {
23
+ number: number
24
+ title: string
25
+ body: string | null
26
+ user: { login: string }
27
+ }
28
+
29
+ export const branchFor = (names: ResolvedNames, issue: number) =>
30
+ `${names.branchPrefix}${issue}`
31
+
32
+ /** The issue a factory branch builds, if its name has one. */
33
+ export const issueFor = (names: ResolvedNames, branch: string) => {
34
+ const digits = branch.startsWith(names.branchPrefix)
35
+ ? branch.slice(names.branchPrefix.length)
36
+ : ""
37
+ return /^[1-9]\d*$/.test(digits) ? Number(digits) : undefined
38
+ }
39
+
40
+ /** The prompt arguments every agent on a ticket gets. */
41
+ export const ticketArgs = (names: ResolvedNames, ticket: Ticket) => ({
42
+ ISSUE_NUMBER: String(ticket.number),
43
+ ISSUE_TITLE: ticket.title,
44
+ ISSUE: ticket.text,
45
+ BRANCH: ticket.branch,
46
+ BASE_REF: names.baseRef,
47
+ })
48
+
49
+ // The repo is public: anyone can comment on an issue, and anyone can open one.
50
+ // Only you can apply the label, but an author can edit the body after you do,
51
+ // so the agents see only issues you wrote, and only your comments. Nothing an
52
+ // agent reads from GitHub comes from anyone else.
53
+ export const ticketText = (
54
+ issue: GhIssue,
55
+ owner: string,
56
+ parent: GhParentIssue | undefined
57
+ ) => {
58
+ const parts = [`# #${issue.number}: ${issue.title}`, issue.body]
59
+ const comments = issue.comments.filter((c) => c.author.login === owner)
60
+ if (comments.length > 0) {
61
+ parts.push(
62
+ "## Comments from the maintainer",
63
+ ...comments.map((c) => c.body)
64
+ )
65
+ }
66
+ if (parent && parent.user.login === owner && parent.body) {
67
+ parts.push(
68
+ `## Parent issue #${parent.number}: ${parent.title}`,
69
+ parent.body
70
+ )
71
+ }
72
+ return parts.join("\n\n")
73
+ }
package/ticket.mts ADDED
@@ -0,0 +1,116 @@
1
+ // Phases 2 to 4 for one ticket: implement, review, publish, CI. It ends with a
2
+ // pull request whose CI passes, or with the ticket handed to a person.
3
+
4
+ import * as sandcastle from "@ai-hero/sandcastle"
5
+ import { sandbox, setUpSandbox } from "./environment.mts"
6
+ import { type ResolvedFactory, limitText } from "./shared/factory.mts"
7
+ import { SandboxSetupError } from "./shared/setup.mts"
8
+ import {
9
+ TicketFailure,
10
+ isApiTrouble,
11
+ isAuthFailure,
12
+ } from "./shared/failures.mts"
13
+ import { handToHuman } from "./shared/github.mts"
14
+ import type { Ticket } from "./shared/tickets.mts"
15
+ import { HostError, discardWorktree, isAheadOfBase } from "./shared/host.mts"
16
+ import {
17
+ NO_CI_FAILURE,
18
+ implement,
19
+ untilCiPasses,
20
+ } from "./workflows/implement/implement.mts"
21
+ import { publish } from "./workflows/publish/publish.mts"
22
+ import { review } from "./workflows/review/review.mts"
23
+
24
+ const buildTicket = async (
25
+ factory: ResolvedFactory,
26
+ ticket: Ticket,
27
+ slot: number,
28
+ signal: AbortSignal,
29
+ progress: { pullRequest?: string }
30
+ ): Promise<string> => {
31
+ discardWorktree(ticket.branch)
32
+ await using box = await sandcastle.createSandbox({
33
+ branch: ticket.branch,
34
+ baseBranch: factory.names.baseRef,
35
+ sandbox: sandbox(factory, slot),
36
+ })
37
+ await setUpSandbox(factory, box)
38
+
39
+ await implement(
40
+ factory,
41
+ box,
42
+ ticket,
43
+ NO_CI_FAILURE,
44
+ factory.limits.implementIterations,
45
+ signal
46
+ )
47
+ if (!isAheadOfBase(factory.names.baseRef, ticket.branch)) {
48
+ throw new TicketFailure("The implementer finished without a commit.")
49
+ }
50
+
51
+ const report = await review(factory, box, ticket, signal)
52
+ const pullRequest = await publish(factory, box, ticket, report, signal)
53
+ progress.pullRequest = pullRequest
54
+
55
+ await untilCiPasses(factory, box, ticket, signal)
56
+ return pullRequest
57
+ }
58
+
59
+ export type Outcome =
60
+ | { status: "ready"; pullRequest: string }
61
+ | { status: "handed-off"; reason: string }
62
+ | { status: "interrupted"; reason: string }
63
+
64
+ /**
65
+ * Build one ticket in sandbox `slot`. `stop` is the whole run's: an agent that
66
+ * can't log in stops it.
67
+ */
68
+ export const runTicket = async (
69
+ factory: ResolvedFactory,
70
+ ticket: Ticket,
71
+ slot: number,
72
+ stop: AbortController
73
+ ): Promise<Outcome> => {
74
+ const deadline = AbortSignal.timeout(factory.timeouts.ticketMs)
75
+ const signal = AbortSignal.any([stop.signal, deadline])
76
+ const progress: { pullRequest?: string } = {}
77
+ try {
78
+ const pullRequest = await buildTicket(
79
+ factory,
80
+ ticket,
81
+ slot,
82
+ signal,
83
+ progress
84
+ )
85
+ return { status: "ready", pullRequest }
86
+ } catch (error) {
87
+ console.error(` ✗ #${ticket.number} (${ticket.branch}):`, error)
88
+ if (isAuthFailure(error)) {
89
+ stop.abort(new Error("The agent can't authenticate."))
90
+ }
91
+ // Not the ticket's fault: leave it labelled for the next run. A failed
92
+ // setup counts too: its output stays in this log, never on the issue.
93
+ if (
94
+ stop.signal.aborted ||
95
+ error instanceof HostError ||
96
+ error instanceof SandboxSetupError ||
97
+ isApiTrouble(error)
98
+ ) {
99
+ return { status: "interrupted", reason: String(error).split("\n")[0]! }
100
+ }
101
+ // The comment is public, so it carries only the reasons written here and
102
+ // the implementer's own blocked reason, never raw error output.
103
+ const reason =
104
+ error instanceof TicketFailure
105
+ ? error.message
106
+ : deadline.aborted
107
+ ? `It ran past its ${limitText(factory.timeouts.ticketMs)} limit.`
108
+ : "The factory hit an unexpected error. Its log on the factory host has the details."
109
+ try {
110
+ handToHuman(factory.names, ticket, reason, progress.pullRequest)
111
+ } catch (labelError) {
112
+ console.error(` Couldn't relabel #${ticket.number}:`, labelError)
113
+ }
114
+ return { status: "handed-off", reason }
115
+ }
116
+ }