@tirso0882/factory 0.0.0-stage → 0.1.1
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.
- package/bin/factory.mjs +19 -0
- package/check-environment.mts +143 -0
- package/cli.mts +109 -0
- package/environment.mts +90 -0
- package/index.mts +19 -0
- package/main.mts +376 -0
- package/package.json +49 -4
- package/shared/agent-env.mts +76 -0
- package/shared/agents.mts +10 -0
- package/shared/answers.mts +163 -0
- package/shared/ci.mts +128 -0
- package/shared/env-leaks.mts +93 -0
- package/shared/factory.mts +868 -0
- package/shared/failures.mts +45 -0
- package/shared/github.mts +341 -0
- package/shared/host.mts +106 -0
- package/shared/load-factory.mts +74 -0
- package/shared/native-sandbox.mts +42 -0
- package/shared/pull-requests.mts +56 -0
- package/shared/remote.mts +18 -0
- package/shared/review-feedback.mts +220 -0
- package/shared/run-with-extraction.mts +144 -0
- package/shared/setup.mts +60 -0
- package/shared/tickets.mts +73 -0
- package/ticket.mts +116 -0
- package/workflows/address-review/address-review.mts +254 -0
- package/workflows/address-review/prompt.md +88 -0
- package/workflows/implement/implement.mts +84 -0
- package/workflows/implement/prompt.md +93 -0
- package/workflows/plan/plan.mts +68 -0
- package/workflows/plan/prompt.md +45 -0
- package/workflows/preflight/preflight.mts +44 -0
- package/workflows/publish/prompt.md +67 -0
- package/workflows/publish/publish.mts +80 -0
- package/workflows/review/prompt.md +69 -0
- package/workflows/review/review.mts +43 -0
- package/workflows/update-branch/prompt.md +75 -0
- package/workflows/update-branch/update-branch.mts +286 -0
- package/README.md +0 -3
package/main.mts
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
// The factory: plan → implement → review → pull request → CI, in waves.
|
|
2
|
+
//
|
|
3
|
+
// Update Each wave starts by merging origin/main into every open factory
|
|
4
|
+
// pull request that conflicts with it. The host merges, and an
|
|
5
|
+
// agent resolves the conflicts if there are any. A pull request
|
|
6
|
+
// that is only behind merges cleanly and is left alone.
|
|
7
|
+
// Address Each factory pull request you labelled `ready-for-agent` goes
|
|
8
|
+
// back to an agent with your unresolved review comments. It fixes
|
|
9
|
+
// or answers them in the pull request's sandbox; the host pushes,
|
|
10
|
+
// posts its replies, removes the label and waits for CI.
|
|
11
|
+
// Plan The host lists the open `ready-for-agent` issues you wrote and
|
|
12
|
+
// drops any with an open blocker or an open factory pull request.
|
|
13
|
+
// A planner picks the ones that can be built side by side.
|
|
14
|
+
// Implement Each issue gets a sandbox (the host's own: bwrap or seatbelt)
|
|
15
|
+
// on `factory/issue-<n>`, branched from origin/main. The
|
|
16
|
+
// implementer builds it and the reviewer checks it against the
|
|
17
|
+
// coding standards and the issue.
|
|
18
|
+
// Publish A writer drafts the pull request body, with the `pr` skill if
|
|
19
|
+
// the config lists it, and the host pushes the branch and opens
|
|
20
|
+
// the pull request.
|
|
21
|
+
// CI The host waits for the checks on the pushed commit. On a failure
|
|
22
|
+
// the implementer gets the failing log, up to `limits.maxCiFixes`
|
|
23
|
+
// times.
|
|
24
|
+
//
|
|
25
|
+
// Nothing merges by itself: you merge the pull requests, and a later run picks
|
|
26
|
+
// up what they unblock. A ticket the factory can't finish is relabelled
|
|
27
|
+
// `ready-for-human` with a comment, so no run retries it.
|
|
28
|
+
//
|
|
29
|
+
// Worktrees branch from origin/main and the host pushes from refs, so the
|
|
30
|
+
// checkout you start it from can be on any branch, with uncommitted work.
|
|
31
|
+
//
|
|
32
|
+
// Where things are:
|
|
33
|
+
// .factory/factory.config.mts the project's settings: limits, labels,
|
|
34
|
+
// models, toolchains, services, its sandbox's variables
|
|
35
|
+
// cli.mts the `factory` command, which loads them
|
|
36
|
+
// shared/factory.mts the settings' defaults, resolved for a run
|
|
37
|
+
// shared/ host commands, tickets, CI, retries
|
|
38
|
+
// workflows/<name>/ one agent each, its code next to its prompt
|
|
39
|
+
// ticket.mts one ticket from sandbox to CI result
|
|
40
|
+
// environment.mts the sandbox built from the config's declarations
|
|
41
|
+
// **/*.test.mts `npm test`; `npm run typecheck` covers it all too
|
|
42
|
+
//
|
|
43
|
+
// Usage, in the project's repo:
|
|
44
|
+
// factory check --quick # first
|
|
45
|
+
// factory # the backlog
|
|
46
|
+
// factory --issue 160 --parallel 1
|
|
47
|
+
// factory --update-pr 187 # only merge main into it
|
|
48
|
+
// factory --address-pr 187 # only address your review of it
|
|
49
|
+
|
|
50
|
+
import { parseArgs } from "node:util"
|
|
51
|
+
import { startServices, stopServices } from "./environment.mts"
|
|
52
|
+
import { type ResolvedFactory, capParallel } from "./shared/factory.mts"
|
|
53
|
+
import {
|
|
54
|
+
conflictingPullRequests,
|
|
55
|
+
loadTickets,
|
|
56
|
+
openFactoryPullRequests,
|
|
57
|
+
} from "./shared/github.mts"
|
|
58
|
+
import { git } from "./shared/host.mts"
|
|
59
|
+
import type { FactoryPullRequest } from "./shared/pull-requests.mts"
|
|
60
|
+
import { type Outcome, runTicket } from "./ticket.mts"
|
|
61
|
+
import {
|
|
62
|
+
type AddressOutcome,
|
|
63
|
+
addressPullRequest,
|
|
64
|
+
} from "./workflows/address-review/address-review.mts"
|
|
65
|
+
import { plan } from "./workflows/plan/plan.mts"
|
|
66
|
+
import { preflight } from "./workflows/preflight/preflight.mts"
|
|
67
|
+
import {
|
|
68
|
+
type UpdateOutcome,
|
|
69
|
+
updatePullRequest,
|
|
70
|
+
} from "./workflows/update-branch/update-branch.mts"
|
|
71
|
+
|
|
72
|
+
/** A run of the factory on the project `factory` describes. `args` are the
|
|
73
|
+
* command line's options: `--issue`, `--parallel`, `--update-pr` and
|
|
74
|
+
* `--address-pr`. */
|
|
75
|
+
export const runFactory = async (
|
|
76
|
+
factory: ResolvedFactory,
|
|
77
|
+
args: readonly string[]
|
|
78
|
+
) => {
|
|
79
|
+
const { names, limits } = factory
|
|
80
|
+
const { baseBranch, baseRef, readyLabel, humanLabel } = names
|
|
81
|
+
|
|
82
|
+
// -------------------------------------------------------------------------
|
|
83
|
+
// Command line
|
|
84
|
+
// -------------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
const { values: cli } = parseArgs({
|
|
87
|
+
args: [...args],
|
|
88
|
+
options: {
|
|
89
|
+
issue: { type: "string", multiple: true },
|
|
90
|
+
parallel: { type: "string" },
|
|
91
|
+
"update-pr": { type: "string" },
|
|
92
|
+
"address-pr": { type: "string" },
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
const onlyIssues = new Set((cli.issue ?? []).map(Number))
|
|
97
|
+
// `limits.parallel` is already capped at the project's `maxSlots`.
|
|
98
|
+
const asked = Number(cli.parallel ?? limits.parallel)
|
|
99
|
+
if (cli.parallel !== undefined && (!Number.isInteger(asked) || asked < 1)) {
|
|
100
|
+
throw new Error(
|
|
101
|
+
`--parallel takes a positive whole number, got ${cli.parallel}.`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
const parallel = capParallel(factory, asked)
|
|
105
|
+
if (parallel < asked) {
|
|
106
|
+
console.warn(
|
|
107
|
+
`--parallel ${asked} is more than the project's maxSlots: running ${parallel} at once.`
|
|
108
|
+
)
|
|
109
|
+
}
|
|
110
|
+
if ([...onlyIssues].some((n) => !Number.isInteger(n) || n < 1)) {
|
|
111
|
+
throw new Error(`--issue takes issue numbers, got ${cli.issue?.join(", ")}.`)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const pullRequestOption = (name: "update-pr" | "address-pr") => {
|
|
115
|
+
const value = cli[name]
|
|
116
|
+
if (value === undefined) return undefined
|
|
117
|
+
const number = Number(value)
|
|
118
|
+
if (!Number.isInteger(number) || number < 1) {
|
|
119
|
+
throw new Error(`--${name} takes a pull request number, got ${value}.`)
|
|
120
|
+
}
|
|
121
|
+
return number
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const onlyUpdate = pullRequestOption("update-pr")
|
|
125
|
+
const onlyAddress = pullRequestOption("address-pr")
|
|
126
|
+
if (onlyUpdate !== undefined && onlyAddress !== undefined) {
|
|
127
|
+
throw new Error("--update-pr and --address-pr run on their own: pick one.")
|
|
128
|
+
}
|
|
129
|
+
if (
|
|
130
|
+
(onlyUpdate !== undefined || onlyAddress !== undefined) &&
|
|
131
|
+
onlyIssues.size > 0
|
|
132
|
+
) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
"--update-pr and --address-pr run on their own: drop --issue."
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// -------------------------------------------------------------------------
|
|
139
|
+
// Stopping and the concurrency cap
|
|
140
|
+
// -------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
// Ctrl-C stops the agents in flight and still tears everything down. A second
|
|
143
|
+
// Ctrl-C exits at once.
|
|
144
|
+
const stop = new AbortController()
|
|
145
|
+
process.on("SIGINT", () => {
|
|
146
|
+
if (stop.signal.aborted) process.exit(130)
|
|
147
|
+
console.warn(
|
|
148
|
+
"\nStopping: killing the agents in flight. Ctrl-C again to quit."
|
|
149
|
+
)
|
|
150
|
+
stop.abort(new Error("Stopped by Ctrl-C."))
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
// At most `size` tasks run at once, and each holds a numbered slot, 1 to
|
|
154
|
+
// `size`, while it runs. The project's `env(slot)` keeps parallel sandboxes
|
|
155
|
+
// apart, such as one Redis database each (.factory/factory.config.mts).
|
|
156
|
+
const createSlotPool = (size: number) => {
|
|
157
|
+
const free = Array.from({ length: size }, (_, i) => i + 1)
|
|
158
|
+
const waiting: ((slot: number) => void)[] = []
|
|
159
|
+
const acquire = () =>
|
|
160
|
+
free.length > 0
|
|
161
|
+
? Promise.resolve(free.shift()!)
|
|
162
|
+
: new Promise<number>((resolve) => waiting.push(resolve))
|
|
163
|
+
const release = (slot: number) => {
|
|
164
|
+
const next = waiting.shift()
|
|
165
|
+
if (next) next(slot)
|
|
166
|
+
else free.push(slot)
|
|
167
|
+
}
|
|
168
|
+
return async <T,>(task: (slot: number) => Promise<T>) => {
|
|
169
|
+
const slot = await acquire()
|
|
170
|
+
try {
|
|
171
|
+
return await task(slot)
|
|
172
|
+
} finally {
|
|
173
|
+
release(slot)
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// -------------------------------------------------------------------------
|
|
179
|
+
// Main loop
|
|
180
|
+
// -------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
const withSlot = createSlotPool(parallel)
|
|
183
|
+
const done = new Set<number>()
|
|
184
|
+
const outcomes = new Map<number, Outcome>()
|
|
185
|
+
const updates = new Map<number, UpdateOutcome>()
|
|
186
|
+
const reviewOutcomes = new Map<number, AddressOutcome>()
|
|
187
|
+
|
|
188
|
+
const updatePullRequests = (pullRequests: readonly FactoryPullRequest[]) =>
|
|
189
|
+
Promise.all(
|
|
190
|
+
pullRequests.map((pr) =>
|
|
191
|
+
withSlot(async (slot) => {
|
|
192
|
+
console.log(
|
|
193
|
+
` PR #${pr.number}: merging ${baseRef} into ${pr.headRefName}`
|
|
194
|
+
)
|
|
195
|
+
updates.set(
|
|
196
|
+
pr.number,
|
|
197
|
+
stop.signal.aborted
|
|
198
|
+
? { status: "interrupted", reason: "The run stopped first." }
|
|
199
|
+
: await updatePullRequest(factory, pr, slot, stop)
|
|
200
|
+
)
|
|
201
|
+
})
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
const addressPullRequests = (pullRequests: readonly FactoryPullRequest[]) =>
|
|
206
|
+
Promise.all(
|
|
207
|
+
pullRequests.map((pr) =>
|
|
208
|
+
withSlot(async (slot) => {
|
|
209
|
+
console.log(` PR #${pr.number}: addressing your review`)
|
|
210
|
+
reviewOutcomes.set(
|
|
211
|
+
pr.number,
|
|
212
|
+
stop.signal.aborted
|
|
213
|
+
? { status: "interrupted", reason: "The run stopped first." }
|
|
214
|
+
: await addressPullRequest(factory, pr, slot, stop)
|
|
215
|
+
)
|
|
216
|
+
})
|
|
217
|
+
)
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
// One pull request you named, whatever GitHub says of it or its labels.
|
|
221
|
+
const onePullRequest = (number: number) => {
|
|
222
|
+
git("fetch", "--quiet", "origin", baseBranch)
|
|
223
|
+
const pr = openFactoryPullRequests(names).find((p) => p.number === number)
|
|
224
|
+
if (pr === undefined) {
|
|
225
|
+
console.warn(`PR #${number} isn't an open factory pull request.`)
|
|
226
|
+
}
|
|
227
|
+
return pr
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
await preflight(factory, stop.signal)
|
|
231
|
+
|
|
232
|
+
const runWaves = async () => {
|
|
233
|
+
for (let wave = 1; wave <= limits.maxWaves && !stop.signal.aborted; wave++) {
|
|
234
|
+
console.log(`\n=== Wave ${wave}/${limits.maxWaves} ===\n`)
|
|
235
|
+
git("fetch", "--quiet", "origin", baseBranch)
|
|
236
|
+
|
|
237
|
+
// A pull request this run couldn't update waits for the next run: it
|
|
238
|
+
// has its comment, or the failure is in this log.
|
|
239
|
+
const conflicting = (
|
|
240
|
+
await conflictingPullRequests(factory, stop.signal)
|
|
241
|
+
).filter(
|
|
242
|
+
(pr) => (updates.get(pr.number)?.status ?? "updated") === "updated"
|
|
243
|
+
)
|
|
244
|
+
if (conflicting.length > 0) {
|
|
245
|
+
console.log(
|
|
246
|
+
`${conflicting.length} pull request(s) conflict with ${baseBranch}:`
|
|
247
|
+
)
|
|
248
|
+
await updatePullRequests(conflicting)
|
|
249
|
+
}
|
|
250
|
+
if (stop.signal.aborted) break
|
|
251
|
+
|
|
252
|
+
// A pull request is addressed once a run, and not while it conflicts.
|
|
253
|
+
const sentBack = openFactoryPullRequests(names, readyLabel).filter(
|
|
254
|
+
(pr) =>
|
|
255
|
+
!reviewOutcomes.has(pr.number) &&
|
|
256
|
+
(updates.get(pr.number)?.status ?? "updated") === "updated"
|
|
257
|
+
)
|
|
258
|
+
if (sentBack.length > 0) {
|
|
259
|
+
console.log(`${sentBack.length} pull request(s) sent back for review:`)
|
|
260
|
+
await addressPullRequests(sentBack)
|
|
261
|
+
}
|
|
262
|
+
if (stop.signal.aborted) break
|
|
263
|
+
|
|
264
|
+
const candidates = loadTickets(names, done, onlyIssues)
|
|
265
|
+
if (candidates.length === 0) {
|
|
266
|
+
console.log("No open, unblocked tickets. Exiting.")
|
|
267
|
+
break
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// One ticket, or tickets you named, need no planner.
|
|
271
|
+
const tickets =
|
|
272
|
+
candidates.length <= 1 || onlyIssues.size > 0
|
|
273
|
+
? candidates
|
|
274
|
+
: await plan(factory, candidates, stop.signal)
|
|
275
|
+
if (tickets.length === 0) {
|
|
276
|
+
console.log("The planner chose no tickets. Exiting.")
|
|
277
|
+
break
|
|
278
|
+
}
|
|
279
|
+
console.log(`${tickets.length} ticket(s), at most ${parallel} at once:`)
|
|
280
|
+
for (const t of tickets)
|
|
281
|
+
console.log(` #${t.number}: ${t.title} → ${t.branch}`)
|
|
282
|
+
|
|
283
|
+
await Promise.all(
|
|
284
|
+
tickets.map((ticket) =>
|
|
285
|
+
withSlot(async (slot) => {
|
|
286
|
+
done.add(ticket.number)
|
|
287
|
+
outcomes.set(
|
|
288
|
+
ticket.number,
|
|
289
|
+
stop.signal.aborted
|
|
290
|
+
? { status: "interrupted", reason: "The run stopped first." }
|
|
291
|
+
: await runTicket(factory, ticket, slot, stop)
|
|
292
|
+
)
|
|
293
|
+
})
|
|
294
|
+
)
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
// Tickets you named run once.
|
|
298
|
+
if (onlyIssues.size > 0) break
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const runOne = async () => {
|
|
303
|
+
if (onlyUpdate !== undefined) {
|
|
304
|
+
const pr = onePullRequest(onlyUpdate)
|
|
305
|
+
if (pr) await updatePullRequests([pr])
|
|
306
|
+
} else if (onlyAddress !== undefined) {
|
|
307
|
+
const pr = onePullRequest(onlyAddress)
|
|
308
|
+
if (pr) await addressPullRequests([pr])
|
|
309
|
+
} else {
|
|
310
|
+
await runWaves()
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
startServices(factory)
|
|
315
|
+
try {
|
|
316
|
+
await runOne()
|
|
317
|
+
} finally {
|
|
318
|
+
stopServices(factory)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
console.log("\n=== Summary ===\n")
|
|
322
|
+
for (const [number, update] of updates) {
|
|
323
|
+
switch (update.status) {
|
|
324
|
+
case "updated":
|
|
325
|
+
console.log(` ↻ PR #${number}: ${baseBranch} merged in, ${update.merge}`)
|
|
326
|
+
break
|
|
327
|
+
case "failed":
|
|
328
|
+
console.log(` ✗ PR #${number}: not updated, commented: ${update.reason}`)
|
|
329
|
+
break
|
|
330
|
+
case "interrupted":
|
|
331
|
+
console.log(` … PR #${number}: not updated: ${update.reason}`)
|
|
332
|
+
break
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
for (const [number, address] of reviewOutcomes) {
|
|
336
|
+
switch (address.status) {
|
|
337
|
+
case "addressed":
|
|
338
|
+
console.log(
|
|
339
|
+
` ✎ PR #${number}: review addressed: ${address.commits} commit(s), ${address.replies} reply(ies), ${address.comments} comment(s)`
|
|
340
|
+
)
|
|
341
|
+
break
|
|
342
|
+
case "nothing to do":
|
|
343
|
+
console.log(` ✎ PR #${number}: nothing actionable, commented`)
|
|
344
|
+
break
|
|
345
|
+
case "failed":
|
|
346
|
+
console.log(
|
|
347
|
+
` ✗ PR #${number}: review not addressed, commented: ${address.reason}`
|
|
348
|
+
)
|
|
349
|
+
break
|
|
350
|
+
case "interrupted":
|
|
351
|
+
console.log(
|
|
352
|
+
` … PR #${number}: interrupted, still ${readyLabel}: ${address.reason}`
|
|
353
|
+
)
|
|
354
|
+
break
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
for (const [number, outcome] of outcomes) {
|
|
358
|
+
switch (outcome.status) {
|
|
359
|
+
case "ready":
|
|
360
|
+
console.log(
|
|
361
|
+
` ✓ #${number}: CI passes, ready for review: ${outcome.pullRequest}`
|
|
362
|
+
)
|
|
363
|
+
break
|
|
364
|
+
case "handed-off":
|
|
365
|
+
console.log(` → #${number}: relabelled ${humanLabel}: ${outcome.reason}`)
|
|
366
|
+
break
|
|
367
|
+
case "interrupted":
|
|
368
|
+
console.log(
|
|
369
|
+
` … #${number}: interrupted, still ${readyLabel}: ${outcome.reason}`
|
|
370
|
+
)
|
|
371
|
+
break
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (outcomes.size === 0 && updates.size === 0 && reviewOutcomes.size === 0)
|
|
375
|
+
console.log(" Nothing ran.")
|
|
376
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tirso0882/factory",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The agent factory: builds ready-for-agent issues into pull requests.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Tirso0882/factory.git"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"factory": "bin/factory.mjs"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": "./index.mts"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"bin/",
|
|
18
|
+
"*.mts",
|
|
19
|
+
"shared/",
|
|
20
|
+
"workflows/",
|
|
21
|
+
"!**/*.test.mts",
|
|
22
|
+
"!shared/fake-host.mts"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=24"
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"typecheck": "tsc",
|
|
32
|
+
"test": "node --test 'shared/**/*.test.mts' 'workflows/**/*.test.mts' 'bin/**/*.test.mts'",
|
|
33
|
+
"lint": "eslint ."
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@ai-hero/sandcastle": "^0.14.0",
|
|
37
|
+
"semver": "^7.8.6",
|
|
38
|
+
"tsx": "^4.23.15",
|
|
39
|
+
"zod": "4.6.7"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@eslint/js": "^10.0.1",
|
|
43
|
+
"@standard-schema/spec": "^1.1.0",
|
|
44
|
+
"@types/node": "^24.0.0",
|
|
45
|
+
"@types/semver": "^7.8.0",
|
|
46
|
+
"eslint": "^10.15.0",
|
|
47
|
+
"globals": "^17.14.0",
|
|
48
|
+
"typescript": "^5.9.3",
|
|
49
|
+
"typescript-eslint": "^8.74.0"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// The variables every agent's sandbox gets on top of the project's: the
|
|
2
|
+
// Claude token and anything else a run needs that mustn't be committed. They
|
|
3
|
+
// live in two optional `.env` files, read in order:
|
|
4
|
+
//
|
|
5
|
+
// ~/.config/factory/.env once per user, for every project
|
|
6
|
+
// <repo>/.factory/.env this project's, over the user's
|
|
7
|
+
//
|
|
8
|
+
// A key with an empty value, in whichever file wins, takes the host's
|
|
9
|
+
// variable of that name. Only the keys these files declare reach the sandbox;
|
|
10
|
+
// the repo's own `.env` never does. Pure: the host is passed in (see
|
|
11
|
+
// factory.mts).
|
|
12
|
+
|
|
13
|
+
import { join } from "node:path"
|
|
14
|
+
import { parseEnvFile } from "./env-leaks.mts"
|
|
15
|
+
import type { Env, Host } from "./factory.mts"
|
|
16
|
+
|
|
17
|
+
export type AgentEnv = {
|
|
18
|
+
/** Where the two files are, whether or not they exist. */
|
|
19
|
+
files: { user: string; project: string }
|
|
20
|
+
/** Every key the two files name, in the order they first appear. */
|
|
21
|
+
declared: readonly string[]
|
|
22
|
+
/** The values the sandbox gets: keys with no value anywhere are left out. */
|
|
23
|
+
values: Env
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The two files, the per-user one first. */
|
|
27
|
+
const agentEnvFiles = (host: Pick<Host, "home" | "repoRoot">) => ({
|
|
28
|
+
user: join(host.home, ".config", "factory", ".env"),
|
|
29
|
+
project: join(host.repoRoot, ".factory", ".env"),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
/** The agent's variables for `host`. It throws, naming both files, if
|
|
33
|
+
* neither exists: without them no agent can log in. It throws too while the
|
|
34
|
+
* old `.sandcastle/.env` is left: Sandcastle reads it on its own and would
|
|
35
|
+
* pass its variables to every sandbox, declared here or not. */
|
|
36
|
+
export const resolveAgentEnv = (
|
|
37
|
+
host: Pick<Host, "home" | "repoRoot" | "env" | "exists" | "read">
|
|
38
|
+
): AgentEnv => {
|
|
39
|
+
const files = agentEnvFiles(host)
|
|
40
|
+
const { user, project } = files
|
|
41
|
+
const legacy = join(host.repoRoot, ".sandcastle", ".env")
|
|
42
|
+
const present = [user, project].filter((path) => host.exists(path))
|
|
43
|
+
const whereTokensGo = [
|
|
44
|
+
` ${user} for every project`,
|
|
45
|
+
` ${project} for this one`,
|
|
46
|
+
]
|
|
47
|
+
if (host.exists(legacy)) {
|
|
48
|
+
throw new Error(
|
|
49
|
+
[
|
|
50
|
+
`Move the tokens from ${legacy} to either file, then delete it: Sandcastle passes it to every sandbox.`,
|
|
51
|
+
...whereTokensGo,
|
|
52
|
+
].join("\n")
|
|
53
|
+
)
|
|
54
|
+
}
|
|
55
|
+
if (present.length === 0) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
[
|
|
58
|
+
"The agent has no token. Put CLAUDE_CODE_OAUTH_TOKEN (from `claude setup-token`) in either:",
|
|
59
|
+
...whereTokensGo,
|
|
60
|
+
].join("\n")
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
// The project's file is read last, so it wins.
|
|
64
|
+
const fromFiles = new Map<string, string>()
|
|
65
|
+
for (const path of present) {
|
|
66
|
+
for (const [key, value] of parseEnvFile(host.read(path))) {
|
|
67
|
+
fromFiles.set(key, value)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const values: Env = {}
|
|
71
|
+
for (const [key, value] of fromFiles) {
|
|
72
|
+
const resolved = value || host.env[key] || ""
|
|
73
|
+
if (resolved) values[key] = resolved
|
|
74
|
+
}
|
|
75
|
+
return { files, declared: [...fromFiles.keys()], values }
|
|
76
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The agent for each role, from the resolved settings.
|
|
2
|
+
|
|
3
|
+
import * as sandcastle from "@ai-hero/sandcastle"
|
|
4
|
+
import type { ResolvedFactory, Role } from "./factory.mts"
|
|
5
|
+
|
|
6
|
+
/** The agent that plays `role`, with the model and effort the settings give it. */
|
|
7
|
+
export const agentFor = (factory: ResolvedFactory, role: Role) => {
|
|
8
|
+
const { model, effort } = factory.models[role]
|
|
9
|
+
return sandcastle.claudeCode(model, { effort })
|
|
10
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// What each agent answers the host, as structured output (see
|
|
2
|
+
// `run-with-extraction.mts`), and what the host makes of it.
|
|
3
|
+
|
|
4
|
+
import * as sandcastle from "@ai-hero/sandcastle"
|
|
5
|
+
import { z } from "zod"
|
|
6
|
+
|
|
7
|
+
const MAX_REASON_CHARS = 1500
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Whether the implementer or the branch updater finished, or stopped. The
|
|
11
|
+
* reason is posted publicly, so it's cut to a comment's length.
|
|
12
|
+
*/
|
|
13
|
+
export const DONE_OR_BLOCKED = sandcastle.Output.object({
|
|
14
|
+
tag: "answer",
|
|
15
|
+
schema: z.discriminatedUnion("status", [
|
|
16
|
+
z.object({ status: z.literal("done") }),
|
|
17
|
+
z.object({
|
|
18
|
+
status: z.literal("blocked"),
|
|
19
|
+
reason: z
|
|
20
|
+
.string()
|
|
21
|
+
.trim()
|
|
22
|
+
.min(1)
|
|
23
|
+
.transform((reason) => reason.slice(0, MAX_REASON_CHARS)),
|
|
24
|
+
}),
|
|
25
|
+
]),
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
export const DONE_OR_BLOCKED_PROMPT = `Answer the host with JSON in an <answer> tag, and nothing else.
|
|
29
|
+
|
|
30
|
+
If you built everything the task asks and committed it:
|
|
31
|
+
|
|
32
|
+
<answer>{"status": "done"}</answer>
|
|
33
|
+
|
|
34
|
+
If you stopped as BLOCKED says, with your one-paragraph explanation for the maintainer:
|
|
35
|
+
|
|
36
|
+
<answer>{"status": "blocked", "reason": "The issue asks for X, but ADR 0010 says Y."}</answer>`
|
|
37
|
+
|
|
38
|
+
const reviewReport = z.object({
|
|
39
|
+
criteria: z.array(
|
|
40
|
+
z.object({
|
|
41
|
+
criterion: z.string().min(1),
|
|
42
|
+
status: z.enum(["met", "not-verifiable", "missing"]),
|
|
43
|
+
/** The test that proves a met criterion. */
|
|
44
|
+
// Models often send null for "no test".
|
|
45
|
+
test: z.string().min(1).nullish(),
|
|
46
|
+
})
|
|
47
|
+
),
|
|
48
|
+
/** What the reviewer changed, and why. */
|
|
49
|
+
changes: z.array(z.string()),
|
|
50
|
+
/** What a person should look at. */
|
|
51
|
+
notes: z.array(z.string()),
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
export type ReviewReport = z.infer<typeof reviewReport>
|
|
55
|
+
|
|
56
|
+
/** The reviewer's report: each acceptance criterion, its fixes, its notes. */
|
|
57
|
+
export const REVIEW_REPORT = sandcastle.Output.object({
|
|
58
|
+
tag: "review",
|
|
59
|
+
schema: reviewReport,
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
const CRITERION_STATUS: Record<
|
|
63
|
+
ReviewReport["criteria"][number]["status"],
|
|
64
|
+
string
|
|
65
|
+
> = {
|
|
66
|
+
met: "Met",
|
|
67
|
+
"not-verifiable": "Not verifiable in the sandbox",
|
|
68
|
+
missing: "Missing",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export const REVIEW_PROMPT = `Answer the host with your report as JSON in a <review> tag, and nothing else. The PR writer writes the pull request from it.
|
|
72
|
+
|
|
73
|
+
- \`criteria\`: every acceptance criterion of the issue, as the issue words it, with its \`status\`: "met", "not-verifiable" (it needs Docker, a browser, a model or a service the project doesn't start for the sandbox) or "missing". For a met criterion, \`test\` names the test that proves it.
|
|
74
|
+
- \`changes\`: what you changed on the branch, and why, one line each.
|
|
75
|
+
- \`notes\`: anything a person should look at, one line each.
|
|
76
|
+
|
|
77
|
+
<review>{"criteria": [{"criterion": "An order stores its total", "status": "met", "test": "test_an_order_stores_its_total"}, {"criterion": "Checked by hand in the running app", "status": "not-verifiable"}], "changes": ["Renamed data to invoice in the route, per the glossary."], "notes": []}</review>`
|
|
78
|
+
|
|
79
|
+
const bullets = (lines: readonly string[]) =>
|
|
80
|
+
lines.length === 0 ? "- None." : lines.map((line) => `- ${line}`).join("\n")
|
|
81
|
+
|
|
82
|
+
/** The reviewer's report as Markdown, for the PR writer. */
|
|
83
|
+
export const reviewMarkdown = (report: ReviewReport) =>
|
|
84
|
+
[
|
|
85
|
+
"### Acceptance criteria",
|
|
86
|
+
bullets(
|
|
87
|
+
report.criteria.map(
|
|
88
|
+
({ criterion, status, test }) =>
|
|
89
|
+
`**${CRITERION_STATUS[status]}:** ${criterion}${test ? ` (test: \`${test}\`)` : ""}`
|
|
90
|
+
)
|
|
91
|
+
),
|
|
92
|
+
"### What the reviewer changed",
|
|
93
|
+
bullets(report.changes),
|
|
94
|
+
"### For a person to look at",
|
|
95
|
+
bullets(report.notes),
|
|
96
|
+
].join("\n\n")
|
|
97
|
+
|
|
98
|
+
const pullRequestDraft = z.object({
|
|
99
|
+
title: z.string().trim().min(1),
|
|
100
|
+
body: z.string().trim().min(1),
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
export type PullRequestDraft = z.infer<typeof pullRequestDraft>
|
|
104
|
+
|
|
105
|
+
/** The PR writer's pull request. The host fixes it up before opening it. */
|
|
106
|
+
export const PULL_REQUEST_DRAFT = sandcastle.Output.object({
|
|
107
|
+
tag: "pull-request",
|
|
108
|
+
schema: pullRequestDraft,
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
export const PULL_REQUEST_PROMPT = `Answer the host with the pull request as JSON in a <pull-request> tag, and nothing else: its \`title\` and its Markdown \`body\`, as THE TITLE and THE BODY say.
|
|
112
|
+
|
|
113
|
+
<pull-request>{"title": "feat(agent): hand a support case to the operator", "body": "## Summary\\n\\n..."}</pull-request>`
|
|
114
|
+
|
|
115
|
+
const CONVENTIONAL_TITLE =
|
|
116
|
+
/^(feat|fix|docs|test|refactor|perf|build|ci|chore|style)(\([\w./-]+\))?!?: \S/
|
|
117
|
+
|
|
118
|
+
const FOOTER =
|
|
119
|
+
"---\n\nBuilt by the Sandcastle factory. It merges nothing: review it as you would any pull request."
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The pull request the host opens for issue `issue`: the writer's title on one
|
|
123
|
+
* line, and its body with a closing line for the issue and the factory's
|
|
124
|
+
* footer. A title that isn't a conventional commit is the host's to warn of:
|
|
125
|
+
* release tooling may read it.
|
|
126
|
+
*/
|
|
127
|
+
export const finishPullRequest = (issue: number, draft: PullRequestDraft) => {
|
|
128
|
+
const title = draft.title.trim().split("\n")[0] ?? ""
|
|
129
|
+
let body = draft.body.trim()
|
|
130
|
+
if (!new RegExp(`\\b(Closes|Fixes|Resolves) #${issue}\\b`, "i").test(body)) {
|
|
131
|
+
body += `\n\nCloses #${issue}`
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
title,
|
|
135
|
+
body: `${body}\n\n${FOOTER}`,
|
|
136
|
+
titleIsConventional: CONVENTIONAL_TITLE.test(title),
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const commentBody = z.string().trim().min(1)
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* What the review addresser posts: its replies to your thread comments, by
|
|
144
|
+
* their node ids, and comments on the pull request. The host posts them.
|
|
145
|
+
*/
|
|
146
|
+
export const FEEDBACK_ANSWER = sandcastle.Output.object({
|
|
147
|
+
tag: "answer",
|
|
148
|
+
schema: z.object({
|
|
149
|
+
threadReplies: z
|
|
150
|
+
.array(z.object({ commentId: z.string().min(1), body: commentBody }))
|
|
151
|
+
.default([]),
|
|
152
|
+
topLevelComments: z.array(z.object({ body: commentBody })).default([]),
|
|
153
|
+
}),
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
export const FEEDBACK_PROMPT = `Answer the host with JSON in an <answer> tag, and nothing else. The host posts it on the pull request, as the factory.
|
|
157
|
+
|
|
158
|
+
- \`threadReplies\`: your reply to a review comment, by the \`commentId\` it has in the feedback.
|
|
159
|
+
- \`topLevelComments\`: comments on the pull request itself, for feedback that isn't in a thread.
|
|
160
|
+
|
|
161
|
+
Use empty lists when you have nothing to say.
|
|
162
|
+
|
|
163
|
+
<answer>{"threadReplies": [{"commentId": "PRRC_kwDOexample", "body": "Renamed to \`invoice\` in 1a2b3c4."}], "topLevelComments": [{"body": "Kept the retry: ADR 0004 says every call to the payment service retries once."}]}</answer>`
|