@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,863 @@
1
+ // The factory's settings: a project's `.factory/factory.config.mts` declares
2
+ // what differs from the defaults, and `resolveFactory` turns that config plus
3
+ // facts about the host into what a run uses. Pure: no files, commands or
4
+ // environment here, so the tests fake the host as plain data
5
+ // (factory.test.mts).
6
+
7
+ import { dirname, join, relative, resolve } from "node:path"
8
+ import semver from "semver"
9
+ import { type SetupStep, shellQuote } from "./setup.mts"
10
+
11
+ export type Effort = "low" | "medium" | "high" | "xhigh" | "max"
12
+
13
+ export type ModelChoice = { model: string; effort: Effort }
14
+
15
+ const ROLES = [
16
+ "planner",
17
+ "implementer",
18
+ "reviewer",
19
+ "reviewAddresser",
20
+ "branchUpdater",
21
+ "prWriter",
22
+ "preflight",
23
+ ] as const
24
+
25
+ export const WORKFLOWS = [
26
+ "plan",
27
+ "implement",
28
+ "review",
29
+ "addressReview",
30
+ "updateBranch",
31
+ "publish",
32
+ ] as const
33
+
34
+ /** A step of the run with its own prompt. */
35
+ export type Workflow = (typeof WORKFLOWS)[number]
36
+
37
+ const isWorkflow = (name: string): name is Workflow =>
38
+ WORKFLOWS.some((workflow) => workflow === name)
39
+
40
+ /** An agent the factory runs, each with its own model and effort. */
41
+ export type Role = (typeof ROLES)[number]
42
+
43
+ export type Names = {
44
+ baseBranch: string
45
+ readyLabel: string
46
+ humanLabel: string
47
+ prLabel: string
48
+ /** A ticket's branch is this plus its issue number. */
49
+ branchPrefix: string
50
+ plannerBranch: string
51
+ preflightBranch: string
52
+ environmentCheckBranch: string
53
+ }
54
+
55
+ export type Limits = {
56
+ /** Parallel agents share one Claude subscription's rate limits. Each
57
+ * ticket holds a slot from its sandbox to its last CI result. */
58
+ parallel: number
59
+ /** Rounds of update, address, plan and build in one run. */
60
+ maxWaves: number
61
+ /** Each implementer iteration is a fresh session that picks up from the
62
+ * branch's commits. Ten is plenty for a ticket sized for one agent. */
63
+ implementIterations: number
64
+ /** Iterations the implementer gets for each CI fix. */
65
+ ciFixIterations: number
66
+ /** CI fixes a ticket gets before it goes to a person. */
67
+ maxCiFixes: number
68
+ /** Iterations the review addresser gets. */
69
+ addressIterations: number
70
+ }
71
+
72
+ export type Timeouts = {
73
+ /** Wall clock for one ticket, CI waits included. When it runs out, the
74
+ * agent in flight is killed and the ticket goes to a person. */
75
+ ticketMs: number
76
+ /** Bringing one conflicting pull request up to date, the agent included. */
77
+ updateMs: number
78
+ /** Addressing your review of one pull request, its CI fixes included. */
79
+ addressMs: number
80
+ /** Waiting for CI on one commit. */
81
+ ciMs: number
82
+ /** Between two reads of CI's checks. */
83
+ ciPollMs: number
84
+ /** GitHub works out whether a pull request merges after the first read
85
+ * asks. */
86
+ mergeabilityRecheckMs: number
87
+ }
88
+
89
+ export type Retries = { agentAttempts: number; delayMs: number }
90
+
91
+ /** A shell command that must exit 0 inside a sandbox. */
92
+ export type Check = {
93
+ name: string
94
+ command: string
95
+ /** `factory check --quick` skips it. */
96
+ slow?: boolean
97
+ }
98
+
99
+ /** A host path the sandbox can see. It appears at its own path unless
100
+ * `sandboxPath` says otherwise. */
101
+ export type Mount = {
102
+ hostPath: string
103
+ sandboxPath?: string
104
+ readonly?: boolean
105
+ }
106
+
107
+ /** A mount with both paths settled. */
108
+ export type ResolvedMount = {
109
+ hostPath: string
110
+ sandboxPath: string
111
+ readonly?: boolean
112
+ }
113
+
114
+ /** Variables a sandbox gets, by name. */
115
+ export type Env = Record<string, string>
116
+
117
+ /** What a toolchain or a listed skill adds to every sandbox. */
118
+ export type Contribution = {
119
+ mounts: readonly ResolvedMount[]
120
+ env: Env
121
+ setup: readonly SetupStep[]
122
+ probes: readonly Check[]
123
+ /** The lockfiles it installs from. */
124
+ lockfiles?: readonly Lockfile[]
125
+ }
126
+
127
+ /** A lockfile a toolchain installs from, and how to remake it. */
128
+ export type Lockfile = {
129
+ /** Its path from the repo's root. */
130
+ path: string
131
+ /** The file it locks, which a merge resolves first. */
132
+ manifest: string
133
+ /** Rewrites it from the manifest. */
134
+ regenerate: string
135
+ /** Installs from it, refusing to change it. */
136
+ install: string
137
+ }
138
+
139
+ /** A preset for one toolchain, such as `pnpm()` or `uv()`. */
140
+ export type Toolchain = {
141
+ name: string
142
+ contribute: (host: Host) => Contribution
143
+ }
144
+
145
+ /** What a project may set. Every field is optional. */
146
+ export type FactoryConfig = {
147
+ /** The versions of the factory CLI this config works with, as a semver
148
+ * range such as `^0.1.0`. A CLI outside it stops before it does anything. */
149
+ version?: string
150
+ names?: Partial<Names>
151
+ models?: Partial<Record<Role, Partial<ModelChoice>>>
152
+ limits?: Partial<Limits>
153
+ timeouts?: Partial<Timeouts>
154
+ retries?: Partial<Retries>
155
+ /** Quality gates: the agents run them before they commit, and so does
156
+ * `factory check`. */
157
+ checks?: readonly Check[]
158
+ /** Environment health, such as dependencies installed or services
159
+ * answering. Only `factory check` runs them. */
160
+ probes?: readonly Check[]
161
+ /** Toolchain presets. Each brings its cache mounts and variables, a
162
+ * locked install and probes. */
163
+ toolchains?: readonly Toolchain[]
164
+ /** Host paths to mount beyond what the toolchains mount. */
165
+ mounts?: readonly Mount[]
166
+ /** Variables for the sandbox in `slot`: 0 for a run with no parallel peer,
167
+ * 1 to the parallel limit for the others. */
168
+ env?: (slot: number) => Env
169
+ /** Setup steps beyond the toolchains' installs. They run after them. */
170
+ setup?: readonly SetupStep[]
171
+ /** A compose file in `.factory/` with the services the sandboxes use. The
172
+ * factory starts it before a run, waits until it's ready, and removes it
173
+ * with its data afterwards. */
174
+ services?: string
175
+ /** How many parallel slots the project can keep apart, such as one per
176
+ * Redis database. `limits.parallel` is capped at it. No cap when unset. */
177
+ maxSlots?: number
178
+ /** Skills from `~/.claude/skills`, by name, that the agents may use. Each
179
+ * is mounted read-only and linked into the sandbox's home. The PR writer
180
+ * uses `pr` when it's listed, and the factory's own template when not. */
181
+ skills?: readonly string[]
182
+ /** The project's coding standards, a file in `.factory/`. The reviewer
183
+ * holds each branch to it. */
184
+ standards?: string
185
+ /** Guidance appended to a workflow's prompt. The factory's prompt stays:
186
+ * no project can replace it. */
187
+ instructions?: Partial<Record<Workflow, string>>
188
+ }
189
+
190
+ /** Facts about the machine and checkout the factory runs on. */
191
+ export type Host = {
192
+ /** The repo's root directory on the host. */
193
+ repoRoot: string
194
+ /** The version of the factory CLI that runs. */
195
+ factoryVersion: string
196
+ /** The user's real home directory. */
197
+ home: string
198
+ /** The host's environment variables. */
199
+ env: Readonly<Record<string, string | undefined>>
200
+ /** Whether a path exists. */
201
+ exists: (path: string) => boolean
202
+ /** Where a path really is, symlinks followed. */
203
+ realPath: (path: string) => string
204
+ /** What a command prints, trimmed. It throws if the command fails. */
205
+ output: (command: readonly [string, ...string[]]) => string
206
+ /** A text file's contents. It throws if the file can't be read. */
207
+ read: (path: string) => string
208
+ }
209
+
210
+ /** What every sandbox gets. */
211
+ export type ResolvedSandbox = {
212
+ mounts: readonly ResolvedMount[]
213
+ /** The variables of the sandbox in `slot`. */
214
+ env: (slot: number) => Env
215
+ /** In order: the toolchains' steps, the skill links, then the project's. */
216
+ setup: readonly SetupStep[]
217
+ }
218
+
219
+ export type ResolvedNames = Names & { baseRef: string }
220
+
221
+ /** The project's text in each workflow's prompt, by placeholder. */
222
+ export type ResolvedPrompts = {
223
+ plan: { INSTRUCTIONS: string }
224
+ implement: { INSTRUCTIONS: string; CHECKS: string }
225
+ review: {
226
+ INSTRUCTIONS: string
227
+ CHECKS: string
228
+ CODING_STANDARDS: string
229
+ LOCKFILES: string
230
+ LOCKFILE_EXCLUDES: string
231
+ }
232
+ addressReview: { INSTRUCTIONS: string; CHECKS: string }
233
+ updateBranch: { INSTRUCTIONS: string; CHECKS: string; LOCKFILES: string }
234
+ publish: { INSTRUCTIONS: string; PULL_REQUEST_GUIDE: string }
235
+ }
236
+
237
+ /** Everything a run uses, defaults applied. */
238
+ export type ResolvedFactory = {
239
+ names: ResolvedNames
240
+ models: Record<Role, ModelChoice>
241
+ limits: Limits
242
+ timeouts: Timeouts
243
+ retries: Retries
244
+ checks: readonly Check[]
245
+ probes: readonly Check[]
246
+ sandbox: ResolvedSandbox
247
+ /** The compose file to start before a run, if the project has services. */
248
+ services?: { composeFile: string }
249
+ /** The highest slot a sandbox may take, if the project limits it. */
250
+ maxSlots?: number
251
+ /** The project's text for each workflow's prompt, as its prompt args. */
252
+ prompts: ResolvedPrompts
253
+ /** Where each agent's log goes. */
254
+ logDir: string
255
+ }
256
+
257
+ // ---------------------------------------------------------------------------
258
+ // Toolchain presets
259
+ // ---------------------------------------------------------------------------
260
+
261
+ const atOwnPath = (hostPath: string, readonly?: true): ResolvedMount =>
262
+ readonly
263
+ ? { hostPath, sandboxPath: hostPath, readonly }
264
+ : { hostPath, sandboxPath: hostPath }
265
+
266
+ // Both installs copy from the mounted caches (a hard link can't cross a
267
+ // mount), so nothing an agent edits in its worktree reaches them. The
268
+ // lockfiles are the contract: an install that would change one fails.
269
+ const INSTALL_TIMEOUT_SECONDS = 600
270
+
271
+ const PNPM_LOCKFILE: Lockfile = {
272
+ path: "pnpm-lock.yaml",
273
+ manifest: "package.json",
274
+ regenerate: "pnpm install --prefer-offline",
275
+ install: "pnpm install --frozen-lockfile --prefer-offline",
276
+ }
277
+
278
+ const UV_LOCKFILE: Lockfile = {
279
+ path: "uv.lock",
280
+ manifest: "pyproject.toml",
281
+ regenerate: "uv lock",
282
+ install: "uv sync --locked",
283
+ }
284
+
285
+ /**
286
+ * pnpm, run through corepack. The store is mounted writable, because an agent
287
+ * that adds a dependency has to fetch it, and pnpm locks it, so parallel
288
+ * sandboxes can share it. Corepack's cache is mounted read-only: without it,
289
+ * every sandbox would download pnpm again before it could install anything.
290
+ */
291
+ export const pnpm = (): Toolchain => ({
292
+ name: "pnpm",
293
+ contribute: (host) => {
294
+ // `pnpm store path` ends in the store's version (…/store/v10); pnpm
295
+ // wants the directory above it.
296
+ const store = dirname(host.output(["pnpm", "store", "path"]))
297
+ const corepack =
298
+ host.env["COREPACK_HOME"] ?? join(host.home, ".cache/node/corepack")
299
+ const hasCorepack = host.exists(corepack)
300
+ return {
301
+ mounts: [
302
+ atOwnPath(store),
303
+ ...(hasCorepack ? [atOwnPath(corepack, true)] : []),
304
+ ],
305
+ env: {
306
+ npm_config_store_dir: store,
307
+ ...(hasCorepack ? { COREPACK_HOME: corepack } : {}),
308
+ },
309
+ setup: [
310
+ {
311
+ command: PNPM_LOCKFILE.install,
312
+ timeoutSeconds: INSTALL_TIMEOUT_SECONDS,
313
+ },
314
+ ],
315
+ lockfiles: [PNPM_LOCKFILE],
316
+ probes: [
317
+ {
318
+ name: "pnpm runs from the mounted corepack cache",
319
+ command: "pnpm --version",
320
+ },
321
+ {
322
+ name: "pnpm uses the mounted store",
323
+ command:
324
+ 'test "$(dirname "$(pnpm store path)")" = "$npm_config_store_dir"',
325
+ },
326
+ ],
327
+ }
328
+ },
329
+ })
330
+
331
+ /**
332
+ * uv. Its cache and the Pythons it installs are mounted writable, for the
333
+ * same reason as pnpm's store; uv locks its cache too.
334
+ */
335
+ export const uv = (): Toolchain => ({
336
+ name: "uv",
337
+ contribute: (host) => {
338
+ const cache = host.output(["uv", "cache", "dir"])
339
+ const pythons = host.output(["uv", "python", "dir"])
340
+ return {
341
+ mounts: [atOwnPath(cache), atOwnPath(pythons)],
342
+ env: { UV_CACHE_DIR: cache, UV_PYTHON_INSTALL_DIR: pythons },
343
+ setup: [
344
+ {
345
+ command: UV_LOCKFILE.install,
346
+ timeoutSeconds: INSTALL_TIMEOUT_SECONDS,
347
+ },
348
+ ],
349
+ lockfiles: [UV_LOCKFILE],
350
+ probes: [
351
+ {
352
+ name: "uv uses the mounted cache",
353
+ command: 'test "$(uv cache dir)" = "$UV_CACHE_DIR"',
354
+ },
355
+ ],
356
+ }
357
+ },
358
+ })
359
+
360
+ /** Types a project's config. It returns the config unchanged. */
361
+ export const defineFactory = (config: FactoryConfig) => config
362
+
363
+ const DEFAULT_NAMES: Names = {
364
+ baseBranch: "main",
365
+ readyLabel: "ready-for-agent",
366
+ humanLabel: "ready-for-human",
367
+ prLabel: "factory",
368
+ branchPrefix: "factory/issue-",
369
+ plannerBranch: "factory/planner",
370
+ preflightBranch: "factory/preflight",
371
+ environmentCheckBranch: "factory/environment-check",
372
+ }
373
+
374
+ const opus = (effort: Effort): ModelChoice => ({
375
+ model: "claude-opus-5-5",
376
+ effort,
377
+ })
378
+
379
+ const DEFAULT_MODELS: Record<Role, ModelChoice> = {
380
+ planner: opus("high"),
381
+ implementer: opus("medium"),
382
+ reviewer: opus("high"),
383
+ reviewAddresser: opus("high"),
384
+ branchUpdater: opus("high"),
385
+ prWriter: { model: "claude-sonnet-5-5", effort: "medium" },
386
+ preflight: { model: "claude-haiku-5-5", effort: "low" },
387
+ }
388
+
389
+ const DEFAULT_LIMITS: Limits = {
390
+ parallel: 3,
391
+ maxWaves: 10,
392
+ implementIterations: 10,
393
+ ciFixIterations: 5,
394
+ maxCiFixes: 2,
395
+ addressIterations: 5,
396
+ }
397
+
398
+ const MINUTE = 60_000
399
+
400
+ const DEFAULT_TIMEOUTS: Timeouts = {
401
+ ticketMs: 180 * MINUTE,
402
+ updateMs: 60 * MINUTE,
403
+ addressMs: 120 * MINUTE,
404
+ ciMs: 45 * MINUTE,
405
+ ciPollMs: MINUTE,
406
+ mergeabilityRecheckMs: 15_000,
407
+ }
408
+
409
+ const DEFAULT_RETRIES: Retries = { agentAttempts: 3, delayMs: MINUTE }
410
+
411
+ const validateChecks = (section: string, list: readonly Check[]) => {
412
+ list.forEach((check, i) => {
413
+ if (!check.name?.trim() || !check.command?.trim()) {
414
+ throw new Error(`${section}[${i}] needs a name and a command.`)
415
+ }
416
+ })
417
+ return [...list]
418
+ }
419
+
420
+ const checkWhole = (section: string, values: Record<string, number>) => {
421
+ for (const [key, value] of Object.entries(values)) {
422
+ if (!Number.isInteger(value) || value < 1) {
423
+ throw new Error(
424
+ `${section}.${key} must be a positive whole number, got ${value}.`
425
+ )
426
+ }
427
+ }
428
+ }
429
+
430
+ const checkPositive = (section: string, values: Record<string, number>) => {
431
+ for (const [key, value] of Object.entries(values)) {
432
+ if (!Number.isFinite(value) || value <= 0) {
433
+ throw new Error(
434
+ `${section}.${key} must be a positive number, got ${value}.`
435
+ )
436
+ }
437
+ }
438
+ }
439
+
440
+ /** Whether `path` is `inner` or a directory above it. */
441
+ const contains = (path: string, inner: string) => {
442
+ const rel = relative(resolve(path), resolve(inner))
443
+ return rel === "" || !rel.startsWith("..")
444
+ }
445
+
446
+ // What `factory check` proves the sandbox can't see (see SECURITY_STEPS).
447
+ const CREDENTIALS = [".ssh", ".config/gh", ".claude"]
448
+
449
+ // The sandbox's private home is the factory's: a project's mounts can't
450
+ // show it the real home or the credentials in it.
451
+ const projectMount = (mount: Mount, home: string): ResolvedMount => {
452
+ if (contains(mount.hostPath, home)) {
453
+ throw new Error(
454
+ `mounts: ${mount.hostPath} would show the sandbox your home directory.`
455
+ )
456
+ }
457
+ for (const credential of CREDENTIALS.map((c) => join(home, c))) {
458
+ if (
459
+ contains(mount.hostPath, credential) ||
460
+ contains(credential, mount.hostPath)
461
+ ) {
462
+ throw new Error(
463
+ `mounts: ${mount.hostPath} would show the sandbox your credentials.`
464
+ )
465
+ }
466
+ }
467
+ return { ...mount, sandboxPath: mount.sandboxPath ?? mount.hostPath }
468
+ }
469
+
470
+ const checkSlot = (slot: number, maxSlots: number | undefined) => {
471
+ if (
472
+ Number.isInteger(slot) &&
473
+ slot >= 0 &&
474
+ (maxSlots === undefined || slot <= maxSlots)
475
+ ) {
476
+ return
477
+ }
478
+ throw new Error(
479
+ maxSlots === undefined
480
+ ? `Sandbox slot must be a whole number from 0, got ${slot}.`
481
+ : `Sandbox slot must be 0 to ${maxSlots}, got ${slot}.`
482
+ )
483
+ }
484
+
485
+ // ---------------------------------------------------------------------------
486
+ // Skills
487
+ // ---------------------------------------------------------------------------
488
+
489
+ /** What a listed skill adds to every sandbox. Skills live in the real home,
490
+ * which the sandbox can't see, so the skill's real directory is mounted
491
+ * read-only and a setup step links it into the sandbox's own
492
+ * `~/.claude/skills`, where Claude Code looks for skills. */
493
+ const skillContribution = (name: string, host: Host): Contribution => {
494
+ if (!/^[\w.-]+$/u.test(name) || name === "." || name === "..") {
495
+ throw new Error(`skills: "${name}" isn't a skill's directory name.`)
496
+ }
497
+ const link = join(host.home, ".claude/skills", name)
498
+ const file = join(link, "SKILL.md")
499
+ if (!host.exists(file)) {
500
+ throw new Error(`skills: the ${name} skill is missing: no ${file}.`)
501
+ }
502
+ const real = host.realPath(link)
503
+ // A skill may live in ~/.claude/skills, but its real directory can't show
504
+ // the sandbox the home or a credential, as a project's mount can't.
505
+ const skillsDir = join(host.home, ".claude/skills")
506
+ const inSkillsDir = contains(skillsDir, real) && resolve(real) !== skillsDir
507
+ const exposes =
508
+ contains(real, host.home) ||
509
+ CREDENTIALS.map((c) => join(host.home, c)).some(
510
+ (credential) => contains(real, credential) || contains(credential, real)
511
+ )
512
+ if (exposes && !inSkillsDir) {
513
+ throw new Error(
514
+ `skills: the ${name} skill is at ${real}, which would show the sandbox your home or credentials.`
515
+ )
516
+ }
517
+ const linked = `$HOME/.claude/skills/${name}`
518
+ return {
519
+ mounts: [atOwnPath(real, true)],
520
+ env: {},
521
+ setup: [
522
+ {
523
+ command: `mkdir -p "$HOME/.claude/skills" && ln -sfn ${shellQuote(real)} "${linked}"`,
524
+ },
525
+ ],
526
+ probes: [
527
+ {
528
+ name: `the ${name} skill is linked into the sandbox's home`,
529
+ command: `test -f "${linked}/SKILL.md"`,
530
+ },
531
+ ],
532
+ }
533
+ }
534
+
535
+ const PR_SKILL_GUIDE =
536
+ "Use the `pr` skill: invoke it, and write the body with its template and guidance: **Summary**, **Evidence**, **Merge Danger**."
537
+
538
+ // For a project that doesn't list the `pr` skill.
539
+ const BUILT_IN_PR_GUIDE = `Write the body with this template:
540
+
541
+ \`\`\`markdown
542
+ ## Summary
543
+
544
+ <the smallest view that makes the change clear: pseudocode, a call tree, a file tree, a diff sketch or a Mermaid diagram, next to a line or two of text>
545
+
546
+ ## Evidence
547
+
548
+ - **Before:** <the failing test run or output>
549
+ **After:** <the passing test run or output>
550
+
551
+ ## Merge Danger
552
+
553
+ **Door:** <one-way or two-way>
554
+
555
+ <optional: why>
556
+
557
+ **Blast Radius:** <one word>
558
+
559
+ <optional: what the merge could break>
560
+ \`\`\`
561
+
562
+ - **Summary**: skip preambles, keep prose brief, and show only the calls, files and states the reader needs.
563
+ - **Evidence**: a test that fails before the change and passes after it is the best evidence; show it as pseudocode if that's clearer.
564
+ - **Merge Danger**: a two-way door is cheap to roll back; destructive or hard-to-reverse changes are one-way doors. The blast radius is what the change could affect: consumers, data, layout, other apps.`
565
+
566
+ /** What a toolchain or a listed skill adds, and where it came from. */
567
+ type Source = { name: string; contribution: Contribution }
568
+
569
+ /** The sandbox: the toolchains' and skills' contributions, then the
570
+ * project's own. */
571
+ const resolveSandbox = (
572
+ config: FactoryConfig,
573
+ host: Host,
574
+ sources: readonly Source[]
575
+ ): ResolvedSandbox => {
576
+ // Which toolchain sets each variable. A project's `env` can't repoint
577
+ // them, nor move the sandbox's private home.
578
+ const owners = new Map([
579
+ ["HOME", "the factory"],
580
+ ...sources.flatMap(({ name, contribution }) =>
581
+ Object.keys(contribution.env).map((key): [string, string] => [key, name])
582
+ ),
583
+ ])
584
+ const toolchainEnv: Env = Object.assign(
585
+ {},
586
+ ...sources.map((t) => t.contribution.env)
587
+ )
588
+ return {
589
+ mounts: [
590
+ ...sources.flatMap((t) => t.contribution.mounts),
591
+ ...(config.mounts ?? []).map((m) => projectMount(m, host.home)),
592
+ ],
593
+ env: (slot) => {
594
+ checkSlot(slot, config.maxSlots)
595
+ const projectEnv = config.env?.(slot) ?? {}
596
+ for (const key of Object.keys(projectEnv)) {
597
+ const owner = owners.get(key)
598
+ if (owner) throw new Error(`env can't set ${key}: ${owner} sets it.`)
599
+ }
600
+ return { ...toolchainEnv, ...projectEnv }
601
+ },
602
+ setup: [
603
+ ...sources.flatMap((t) => t.contribution.setup),
604
+ ...(config.setup ?? []),
605
+ ],
606
+ }
607
+ }
608
+
609
+ const NO_STANDARDS =
610
+ "The project has no coding standards file. Hold the diff to the conventions of the code around it, and to what `AGENTS.md` or `CLAUDE.md` says."
611
+
612
+ /** The project's standards file in `.factory/`, for the reviewer. */
613
+ const readStandards = (file: string | undefined, host: Host) => {
614
+ if (file === undefined) return NO_STANDARDS
615
+ const path = join(host.repoRoot, ".factory", file)
616
+ try {
617
+ return host.read(path)
618
+ } catch (error) {
619
+ throw new Error(`standards: can't read ${path}.`, { cause: error })
620
+ }
621
+ }
622
+
623
+ /** A workflow's instructions as the end of its prompt, or nothing. */
624
+ const instructionsText = (text: string | undefined) =>
625
+ text?.trim()
626
+ ? [
627
+ "# THIS PROJECT",
628
+ "",
629
+ "The project adds this guidance for this step. Where it conflicts with the rules above, the rules above win.",
630
+ "",
631
+ text.trim(),
632
+ ].join("\n")
633
+ : ""
634
+
635
+ const inlineCode = (text: string) => `\`${text}\``
636
+
637
+ /** How the reviewer reads the lockfiles it leaves out of the diff. */
638
+ const reviewLockfiles = (lockfiles: readonly Lockfile[], baseRef: string) =>
639
+ lockfiles.length === 0
640
+ ? ""
641
+ : `The lockfiles are left out: check them with ${inlineCode(`git diff ${baseRef}...HEAD -- ${lockfiles.map((l) => l.path).join(" ")}`)} if a dependency changed.`
642
+
643
+ /** How the branch updater resolves a conflicting lockfile. */
644
+ const mergeLockfiles = (lockfiles: readonly Lockfile[], baseRef: string) =>
645
+ lockfiles.length === 0
646
+ ? ""
647
+ : [
648
+ `Don't merge a lockfile's hunks by hand. Resolve the file it locks first, take \`${baseRef}\`'s lockfile (\`git checkout --theirs <lockfile>\`), then regenerate it:`,
649
+ "",
650
+ ...lockfiles.map(
651
+ (l) =>
652
+ `- ${inlineCode(l.path)}: resolve ${inlineCode(l.manifest)}, then run ${inlineCode(l.regenerate)}`
653
+ ),
654
+ "",
655
+ "The sandbox was installed from the branch before the merge. If a lockfile changed, install from it again before the checks:",
656
+ "",
657
+ ...lockfiles.map(
658
+ (l) => `- ${inlineCode(l.path)}: ${inlineCode(l.install)}`
659
+ ),
660
+ ].join("\n")
661
+
662
+ const resolvePrompts = (
663
+ config: FactoryConfig,
664
+ host: Host,
665
+ baseRef: string,
666
+ lockfiles: readonly Lockfile[],
667
+ checks: readonly Check[],
668
+ pullRequestGuide: string
669
+ ): ResolvedPrompts => {
670
+ const instructions = config.instructions ?? {}
671
+ for (const key of Object.keys(instructions)) {
672
+ if (!isWorkflow(key)) {
673
+ throw new Error(`instructions: the factory has no "${key}" workflow.`)
674
+ }
675
+ }
676
+ const instructionsArg = (workflow: Workflow) => ({
677
+ INSTRUCTIONS: instructionsText(instructions[workflow]),
678
+ })
679
+ const CHECKS = checksPrompt({ checks })
680
+ return {
681
+ plan: instructionsArg("plan"),
682
+ implement: { ...instructionsArg("implement"), CHECKS },
683
+ review: {
684
+ ...instructionsArg("review"),
685
+ CHECKS,
686
+ CODING_STANDARDS: readStandards(config.standards, host),
687
+ LOCKFILES: reviewLockfiles(lockfiles, baseRef),
688
+ LOCKFILE_EXCLUDES: lockfiles.map((l) => `':!${l.path}'`).join(" "),
689
+ },
690
+ addressReview: { ...instructionsArg("addressReview"), CHECKS },
691
+ updateBranch: {
692
+ ...instructionsArg("updateBranch"),
693
+ CHECKS,
694
+ LOCKFILES: mergeLockfiles(lockfiles, baseRef),
695
+ },
696
+ publish: {
697
+ ...instructionsArg("publish"),
698
+ PULL_REQUEST_GUIDE: pullRequestGuide,
699
+ },
700
+ }
701
+ }
702
+
703
+ const PACKAGE_NAME = "@tirso0882/factory"
704
+
705
+ /** Stops a CLI the project's `version` range doesn't accept. */
706
+ export const checkVersion = (
707
+ range: string | undefined,
708
+ installed: string
709
+ ) => {
710
+ if (range === undefined) return
711
+ if (semver.validRange(range) === null) {
712
+ throw new Error(`version: "${range}" isn't a semver range.`)
713
+ }
714
+ if (!semver.satisfies(installed, range)) {
715
+ throw new Error(
716
+ [
717
+ `This project needs factory ${range}, but ${installed} is installed.`,
718
+ `Install a version it accepts: npm install -g "${PACKAGE_NAME}@${range}"`,
719
+ ].join("\n")
720
+ )
721
+ }
722
+ }
723
+
724
+ /** The settings a run uses: `config`, defaults filled in, for `host`. */
725
+ export const resolveFactory = (
726
+ config: FactoryConfig,
727
+ host: Host
728
+ ): ResolvedFactory => {
729
+ // First: a config for another version may not mean what this one reads.
730
+ checkVersion(config.version, host.factoryVersion)
731
+ const names = { ...DEFAULT_NAMES, ...config.names }
732
+ const models = { ...DEFAULT_MODELS }
733
+ for (const role of ROLES) {
734
+ models[role] = { ...DEFAULT_MODELS[role], ...config.models?.[role] }
735
+ }
736
+ const limits = { ...DEFAULT_LIMITS, ...config.limits }
737
+ const { maxSlots } = config
738
+ const timeouts = { ...DEFAULT_TIMEOUTS, ...config.timeouts }
739
+ const retries = { ...DEFAULT_RETRIES, ...config.retries }
740
+ checkWhole("limits", limits)
741
+ checkPositive("timeouts", timeouts)
742
+ checkWhole("retries", { agentAttempts: retries.agentAttempts })
743
+ checkPositive("retries", { delayMs: retries.delayMs })
744
+ if (maxSlots !== undefined && (!Number.isInteger(maxSlots) || maxSlots < 1)) {
745
+ throw new Error(
746
+ `maxSlots must be a positive whole number, got ${maxSlots}.`
747
+ )
748
+ }
749
+ // The toolchains, then the skills.
750
+ const sources: Source[] = [
751
+ ...(config.toolchains ?? []).map((t) => ({
752
+ name: `the ${t.name} toolchain`,
753
+ contribution: t.contribute(host),
754
+ })),
755
+ ...[...new Set(config.skills)].map((name) => ({
756
+ name: `the ${name} skill`,
757
+ contribution: skillContribution(name, host),
758
+ })),
759
+ ]
760
+ const baseRef = `origin/${names.baseBranch}`
761
+ const checks = validateChecks("checks", config.checks ?? [])
762
+ const pullRequestGuide = config.skills?.includes("pr")
763
+ ? PR_SKILL_GUIDE
764
+ : BUILT_IN_PR_GUIDE
765
+ return {
766
+ names: { ...names, baseRef },
767
+ models,
768
+ limits: { ...limits, parallel: capParallel({ maxSlots }, limits.parallel) },
769
+ timeouts,
770
+ retries,
771
+ checks,
772
+ probes: validateChecks("probes", [
773
+ ...sources.flatMap((t) => t.contribution.probes),
774
+ ...(config.probes ?? []),
775
+ ]),
776
+ sandbox: resolveSandbox(config, host, sources),
777
+ ...(config.services === undefined
778
+ ? {}
779
+ : {
780
+ services: {
781
+ composeFile: join(host.repoRoot, ".factory", config.services),
782
+ },
783
+ }),
784
+ ...(maxSlots === undefined ? {} : { maxSlots }),
785
+ prompts: resolvePrompts(
786
+ config,
787
+ host,
788
+ baseRef,
789
+ sources.flatMap((s) => s.contribution.lockfiles ?? []),
790
+ checks,
791
+ pullRequestGuide
792
+ ),
793
+ logDir: join(host.repoRoot, ".factory", "logs"),
794
+ }
795
+ }
796
+
797
+ /** `parallel` slots, capped at the project's `maxSlots` if it has one. */
798
+ export const capParallel = (
799
+ factory: Pick<ResolvedFactory, "maxSlots">,
800
+ parallel: number
801
+ ) =>
802
+ factory.maxSlots === undefined
803
+ ? parallel
804
+ : Math.min(parallel, factory.maxSlots)
805
+
806
+ /** The configured checks as the agents' prompts list them. */
807
+ export const checksPrompt = (factory: Pick<ResolvedFactory, "checks">) =>
808
+ [
809
+ "```bash",
810
+ ...factory.checks.map((c) => `${c.command} # ${c.name}`),
811
+ "```",
812
+ ].join("\n")
813
+
814
+ /** One step of `factory check`: a shell command, or the scan of the
815
+ * sandbox's environment for host secrets and the canary. */
816
+ export type CheckStep =
817
+ | { kind: "command"; name: string; command: string }
818
+ | { kind: "env-leaks"; name: string }
819
+
820
+ // The factory's own guarantees. They aren't config: a project can't drop them.
821
+ const SECURITY_STEPS: readonly CheckStep[] = [
822
+ {
823
+ kind: "command",
824
+ name: "the home directory is private",
825
+ // The sandbox has its own ~/.claude (the skill links), so look for a file
826
+ // only the host's has.
827
+ command:
828
+ 'test ! -e "$HOME/.ssh" && test ! -e "$HOME/.claude/CLAUDE.md" && test ! -e "$HOME/.config/gh"',
829
+ },
830
+ {
831
+ kind: "command",
832
+ name: "the repo's .env is not in the worktree",
833
+ command: "test ! -e .env",
834
+ },
835
+ { kind: "env-leaks", name: "no host secret or canary reaches the sandbox" },
836
+ ]
837
+
838
+ /** What `factory check` runs, in order: the probes, the checks, then the
839
+ * security checks. `quick` skips the probes and checks marked slow. */
840
+ export const checkPlan = (
841
+ factory: Pick<ResolvedFactory, "checks" | "probes">,
842
+ { quick }: { quick: boolean }
843
+ ): CheckStep[] => [
844
+ ...[...factory.probes, ...factory.checks]
845
+ .filter((check) => !(quick && check.slow))
846
+ .map(({ name, command }) => ({ kind: "command" as const, name, command })),
847
+ ...SECURITY_STEPS,
848
+ ]
849
+
850
+ /** A time limit for a public comment: "3-hour", or "90-minute". */
851
+ export const limitText = (ms: number) =>
852
+ ms % (60 * MINUTE) === 0
853
+ ? `${ms / (60 * MINUTE)}-hour`
854
+ : `${Math.round(ms / MINUTE)}-minute`
855
+
856
+ const forFilename = (text: string) =>
857
+ text.toLowerCase().replaceAll(/[^a-z0-9_.-]/gu, "-")
858
+
859
+ /** The log of agent `name` on `branch`, in `logDir`. */
860
+ export const logFile = (logDir: string, branch: string, name: string) => ({
861
+ type: "file" as const,
862
+ path: join(logDir, `${forFilename(branch)}-${forFilename(name)}.log`),
863
+ })