@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.
Files changed (39) hide show
  1. package/bin/factory.mjs +19 -0
  2. package/check-environment.mts +143 -0
  3. package/cli.mts +109 -0
  4. package/environment.mts +90 -0
  5. package/index.mts +19 -0
  6. package/main.mts +376 -0
  7. package/package.json +49 -4
  8. package/shared/agent-env.mts +76 -0
  9. package/shared/agents.mts +10 -0
  10. package/shared/answers.mts +163 -0
  11. package/shared/ci.mts +128 -0
  12. package/shared/env-leaks.mts +93 -0
  13. package/shared/factory.mts +868 -0
  14. package/shared/failures.mts +45 -0
  15. package/shared/github.mts +341 -0
  16. package/shared/host.mts +106 -0
  17. package/shared/load-factory.mts +74 -0
  18. package/shared/native-sandbox.mts +42 -0
  19. package/shared/pull-requests.mts +56 -0
  20. package/shared/remote.mts +18 -0
  21. package/shared/review-feedback.mts +220 -0
  22. package/shared/run-with-extraction.mts +144 -0
  23. package/shared/setup.mts +60 -0
  24. package/shared/tickets.mts +73 -0
  25. package/ticket.mts +116 -0
  26. package/workflows/address-review/address-review.mts +254 -0
  27. package/workflows/address-review/prompt.md +88 -0
  28. package/workflows/implement/implement.mts +84 -0
  29. package/workflows/implement/prompt.md +93 -0
  30. package/workflows/plan/plan.mts +68 -0
  31. package/workflows/plan/prompt.md +45 -0
  32. package/workflows/preflight/preflight.mts +44 -0
  33. package/workflows/publish/prompt.md +67 -0
  34. package/workflows/publish/publish.mts +80 -0
  35. package/workflows/review/prompt.md +69 -0
  36. package/workflows/review/review.mts +43 -0
  37. package/workflows/update-branch/prompt.md +75 -0
  38. package/workflows/update-branch/update-branch.mts +286 -0
  39. package/README.md +0 -3
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ // The `factory` command. The factory is TypeScript, and so is a project's
3
+ // `.factory/factory.config.mts`: tsx loads both. The config's `factory` import
4
+ // resolves to this package, so the project needs no node_modules of its own.
5
+
6
+ import { registerHooks } from "node:module"
7
+ import { register } from "tsx/esm/api"
8
+
9
+ const API = new URL("../index.mts", import.meta.url).href
10
+
11
+ registerHooks({
12
+ resolve: (specifier, context, nextResolve) =>
13
+ specifier === "factory"
14
+ ? { url: API, format: "module", shortCircuit: true }
15
+ : nextResolve(specifier, context),
16
+ })
17
+ register()
18
+
19
+ await import("../cli.mts")
@@ -0,0 +1,143 @@
1
+ // Proves the sandbox environment works, without running an agent: it opens
2
+ // one sandbox on a throwaway branch, installs it the way an implementer's is,
3
+ // then runs the config's probes and checks (.factory/factory.config.mts) and
4
+ // the factory's security checks, which always run (shared/factory.mts).
5
+ //
6
+ // Run it after changing `.factory/factory.config.mts`, the lockfiles or the
7
+ // toolchain, and before leaving the factory alone:
8
+ // factory check # everything
9
+ // factory check --quick # skip what's marked slow
10
+
11
+ import { execFileSync } from "node:child_process"
12
+ import { randomBytes } from "node:crypto"
13
+ import { existsSync, readFileSync } from "node:fs"
14
+ import { join } from "node:path"
15
+ import * as sandcastle from "@ai-hero/sandcastle"
16
+ import {
17
+ hostSandbox,
18
+ sandbox,
19
+ setUpSandbox,
20
+ startServices,
21
+ stopServices,
22
+ } from "./environment.mts"
23
+ import {
24
+ ENV_DUMP_COMMAND,
25
+ type EnvContext,
26
+ classifyEnv,
27
+ parseEnvDump,
28
+ parseEnvFile,
29
+ secretsIn,
30
+ } from "./shared/env-leaks.mts"
31
+ import { type ResolvedFactory, checkPlan } from "./shared/factory.mts"
32
+
33
+ const envFile = (path: string) =>
34
+ existsSync(path) ? parseEnvFile(readFileSync(path, "utf8")) : []
35
+
36
+ const CANARY_NAME = "FACTORY_CHECK_CANARY"
37
+
38
+ /**
39
+ * Fail for every variable in the sandbox that shouldn't be there. It prints
40
+ * names and reasons only: the values are the secrets.
41
+ */
42
+ const checkEnvLeaks = async (
43
+ box: Pick<sandcastle.Sandbox, "exec">,
44
+ name: string,
45
+ envContext: EnvContext
46
+ ) => {
47
+ const result = await box.exec(ENV_DUMP_COMMAND)
48
+ const env = result.exitCode === 0 ? parseEnvDump(result.stdout) : undefined
49
+ if (!env) {
50
+ console.log(
51
+ `FAIL ${name} (couldn't read the sandbox's environment, exit ${result.exitCode})`
52
+ )
53
+ return false
54
+ }
55
+ const leaks = classifyEnv(env, envContext)
56
+ if (leaks.length === 0) {
57
+ console.log(`ok ${name}`)
58
+ return true
59
+ }
60
+ console.log(`FAIL ${name}`)
61
+ for (const leak of leaks) console.log(` ${leak.name}: ${leak.reason}`)
62
+ return false
63
+ }
64
+
65
+ /**
66
+ * Check the sandbox of the project at `repoRoot`, whose working directory
67
+ * this must run in: Sandcastle anchors its worktrees there, as it does an
68
+ * agent's. It returns how many checks failed.
69
+ */
70
+ export const checkEnvironment = async (
71
+ factory: ResolvedFactory,
72
+ repoRoot: string,
73
+ { quick }: { quick: boolean }
74
+ ) => {
75
+ const branch = factory.names.environmentCheckBranch
76
+ const plan = checkPlan(factory, { quick })
77
+ console.log(`Sandbox: ${hostSandbox()}`)
78
+
79
+ // Set on the host before the sandbox exists and declared nowhere, so it can
80
+ // only reach the sandbox if Sandcastle passes the host's environment through.
81
+ const canary = `canary-${randomBytes(12).toString("hex")}`
82
+ process.env[CANARY_NAME] = canary
83
+
84
+ // What the sandbox may get (the keys of the agent's env files) and what
85
+ // it must not: the host's secret-looking variables and those in the repo's
86
+ // `.env`, which is read here on the host and never copied in.
87
+ const envContext: EnvContext = {
88
+ declared: new Set(factory.agentEnv.declared),
89
+ hostSecrets: new Map([
90
+ ...secretsIn(process.env),
91
+ ...secretsIn(Object.fromEntries(envFile(join(repoRoot, ".env")))),
92
+ ]),
93
+ canary,
94
+ }
95
+
96
+ let failed = 0
97
+
98
+ try {
99
+ startServices(factory)
100
+
101
+ {
102
+ await using box = await sandcastle.createSandbox({
103
+ branch,
104
+ sandbox: sandbox(factory, 1),
105
+ })
106
+ await setUpSandbox(factory, box)
107
+ console.log(`\nSandbox ready at ${box.worktreePath}\n`)
108
+
109
+ for (const check of plan) {
110
+ if (check.kind === "env-leaks") {
111
+ if (!(await checkEnvLeaks(box, check.name, envContext))) failed++
112
+ continue
113
+ }
114
+ const started = Date.now()
115
+ const result = await box.exec(check.command)
116
+ const seconds = ((Date.now() - started) / 1000).toFixed(1)
117
+ if (result.exitCode === 0) {
118
+ console.log(`ok ${check.name} (${seconds}s)`)
119
+ } else {
120
+ failed++
121
+ console.log(
122
+ `FAIL ${check.name} (${seconds}s, exit ${result.exitCode})`
123
+ )
124
+ const output = `${result.stdout}\n${result.stderr}`.trim()
125
+ console.log(output.split("\n").slice(-40).join("\n"))
126
+ }
127
+ }
128
+ }
129
+ } finally {
130
+ // The branch only ever holds the commit it was created from.
131
+ try {
132
+ execFileSync("git", ["branch", "-D", branch], { stdio: "ignore" })
133
+ } catch {
134
+ // It was never created.
135
+ }
136
+ stopServices(factory)
137
+ }
138
+
139
+ console.log(
140
+ failed === 0 ? "\nThe environment works." : `\n${failed} check(s) failed.`
141
+ )
142
+ return failed
143
+ }
package/cli.mts ADDED
@@ -0,0 +1,109 @@
1
+ // The `factory` command (bin/factory.mjs loads it). It runs in the git repo
2
+ // it's started from, with that repo's `.factory/factory.config.mts`:
3
+ //
4
+ // factory [--issue <n>]... [--parallel <n>] build the backlog (main.mts)
5
+ // [--update-pr <n> | --address-pr <n>]
6
+ // factory check [--quick] check the sandbox without an agent
7
+ // factory preflight one tiny agent call: does the token work?
8
+ // factory --version
9
+
10
+ import { execFileSync } from "node:child_process"
11
+ import { factoryVersion, loadFactory } from "./shared/load-factory.mts"
12
+
13
+ const USAGE = `Usage, in a repo with .factory/factory.config.mts:
14
+ factory [--issue <n>]... [--parallel <n>] build the ready-for-agent backlog
15
+ factory --update-pr <n> only merge the base branch into it
16
+ factory --address-pr <n> only address your review of it
17
+ factory check [--quick] check the sandbox, no tokens spent
18
+ factory preflight check the Claude token
19
+ factory --version`
20
+
21
+ /** The root of the git repo the command was started in. */
22
+ const repoRoot = () => {
23
+ try {
24
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
25
+ encoding: "utf8",
26
+ stdio: ["ignore", "pipe", "ignore"],
27
+ }).trim()
28
+ } catch {
29
+ throw new Error("Run factory inside a git repo.")
30
+ }
31
+ }
32
+
33
+ /** An abort signal that Ctrl-C trips; a second Ctrl-C exits at once. */
34
+ const ctrlC = () => {
35
+ const stop = new AbortController()
36
+ process.on("SIGINT", () => {
37
+ if (stop.signal.aborted) process.exit(130)
38
+ console.warn("\nStopping. Ctrl-C again to quit.")
39
+ stop.abort(new Error("Stopped by Ctrl-C."))
40
+ })
41
+ return stop.signal
42
+ }
43
+
44
+ const main = async (argv: readonly string[]) => {
45
+ const [command, ...rest] = argv
46
+ if (command === "--version" || command === "-v") {
47
+ console.log(factoryVersion())
48
+ return
49
+ }
50
+ if (command === "--help" || command === "-h" || command === "help") {
51
+ console.log(USAGE)
52
+ return
53
+ }
54
+
55
+ const root = repoRoot()
56
+ // Sandcastle anchors worktrees to the working directory, and the host's
57
+ // git and gh run in it (shared/host.mts).
58
+ process.chdir(root)
59
+ const factory = await loadFactory(root)
60
+
61
+ // Each command's modules load only now: the host's look up the repo when
62
+ // they load, which needs the working directory set.
63
+ switch (command) {
64
+ case "check": {
65
+ const unknown = rest.filter((arg) => arg !== "--quick")
66
+ if (unknown.length > 0) {
67
+ throw new Error(`factory check takes only --quick, got ${unknown.join(" ")}.`)
68
+ }
69
+ const { checkEnvironment } = await import("./check-environment.mts")
70
+ const failed = await checkEnvironment(factory, root, {
71
+ quick: rest.includes("--quick"),
72
+ })
73
+ process.exitCode = failed === 0 ? 0 : 1
74
+ return
75
+ }
76
+ case "preflight": {
77
+ if (rest.length > 0) {
78
+ throw new Error(`factory preflight takes no options, got ${rest.join(" ")}.`)
79
+ }
80
+ const { preflight } = await import("./workflows/preflight/preflight.mts")
81
+ await preflight(factory, ctrlC())
82
+ console.log("The agent logged in and answered.")
83
+ return
84
+ }
85
+ default: {
86
+ if (command !== undefined && !command.startsWith("-")) {
87
+ throw new Error(`factory has no "${command}" command.\n\n${USAGE}`)
88
+ }
89
+ const { runFactory } = await import("./main.mts")
90
+ await runFactory(factory, argv)
91
+ }
92
+ }
93
+ }
94
+
95
+ try {
96
+ await main(process.argv.slice(2))
97
+ } catch (error) {
98
+ // The message, and what caused it: a stack trace is noise for a config
99
+ // mistake, and FACTORY_DEBUG=1 shows it.
100
+ if (process.env["FACTORY_DEBUG"]) console.error(error)
101
+ else {
102
+ for (let e: unknown = error; e !== undefined; ) {
103
+ const text = e instanceof Error ? e.message : String(e)
104
+ console.error(e === error ? text : ` Caused by: ${text}`)
105
+ e = e instanceof Error ? e.cause : undefined
106
+ }
107
+ }
108
+ process.exitCode = 1
109
+ }
@@ -0,0 +1,90 @@
1
+ // The sandbox environment: what an agent's sandbox can see and reach.
2
+ //
3
+ // The sandbox is the host's native one, picked on every run (see
4
+ // shared/native-sandbox.mts): bwrap on Linux and WSL2, seatbelt on macOS 14
5
+ // and later. Either gives each sandbox a private, empty home directory. That
6
+ // hides the package caches, so the project's toolchains mount them back in,
7
+ // and it means nothing from the repo's `.env` is ever there: the sandbox gets
8
+ // only the variables the project declares and the tokens in
9
+ // `~/.config/factory/.env` and `.factory/.env` (shared/agent-env.mts). Never
10
+ // copy `.env` into a worktree.
11
+ //
12
+ // What a sandbox gets comes from `.factory/factory.config.mts`, resolved in
13
+ // shared/factory.mts. Check it without spending tokens:
14
+ // factory check
15
+
16
+ import { execFileSync } from "node:child_process"
17
+ import { release } from "node:os"
18
+ import type { Sandbox, SandboxProvider } from "@ai-hero/sandcastle"
19
+ import { type BwrapOptions, bwrap } from "@ai-hero/sandcastle/sandboxes/bwrap"
20
+ import {
21
+ type SeatbeltOptions,
22
+ seatbelt,
23
+ } from "@ai-hero/sandcastle/sandboxes/seatbelt"
24
+ import type { ResolvedFactory } from "./shared/factory.mts"
25
+ import {
26
+ type NativeSandbox,
27
+ chooseNativeSandbox,
28
+ } from "./shared/native-sandbox.mts"
29
+ import { runSetupSteps } from "./shared/setup.mts"
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Services
33
+ // ---------------------------------------------------------------------------
34
+
35
+ const compose = (factory: ResolvedFactory, ...args: string[]) => {
36
+ if (factory.services === undefined) return
37
+ execFileSync(
38
+ "docker",
39
+ ["compose", "-f", factory.services.composeFile, ...args],
40
+ { stdio: ["ignore", "inherit", "inherit"] }
41
+ )
42
+ }
43
+
44
+ /** Start the project's services, if it has any, and wait until they're
45
+ * ready. */
46
+ export const startServices = (factory: ResolvedFactory) =>
47
+ compose(factory, "up", "--detach", "--wait")
48
+
49
+ /** Remove them, with their data. */
50
+ export const stopServices = (factory: ResolvedFactory) =>
51
+ compose(factory, "down", "--volumes")
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // The sandbox
55
+ // ---------------------------------------------------------------------------
56
+
57
+ /** This host's native sandbox. It throws, naming the supported hosts, on one
58
+ * that has none: the factory never runs an agent unsandboxed. */
59
+ export const hostSandbox = () =>
60
+ chooseNativeSandbox({ platform: process.platform, release: release() })
61
+
62
+ /** What both native sandboxes take. */
63
+ type SandboxOptions = BwrapOptions & SeatbeltOptions
64
+
65
+ const PROVIDERS = { bwrap, seatbelt } satisfies Record<
66
+ NativeSandbox,
67
+ (options: SandboxOptions) => SandboxProvider
68
+ >
69
+
70
+ /**
71
+ * The host's sandbox with the project's mounts and its variables for `slot`.
72
+ *
73
+ * `slot` separates sandboxes that run at the same time: 0 for a run with no
74
+ * parallel peer (the planner, preflight), 1 up for the parallel ones. The
75
+ * project's `env(slot)` decides what a slot changes, such as a Redis database.
76
+ */
77
+ export const sandbox = (factory: ResolvedFactory, slot = 0) => {
78
+ const options: SandboxOptions = {
79
+ mounts: factory.sandbox.mounts,
80
+ env: { ...factory.sandbox.env(slot), ...factory.agentEnv.values },
81
+ }
82
+ return PROVIDERS[hostSandbox()](options)
83
+ }
84
+
85
+ /** Make a fresh sandbox fit for an agent: the toolchains' installs, the
86
+ * skill links and the project's setup steps (see shared/setup.mts). */
87
+ export const setUpSandbox = (
88
+ factory: ResolvedFactory,
89
+ box: Pick<Sandbox, "exec">
90
+ ) => runSetupSteps(box, factory.sandbox.setup)
package/index.mts ADDED
@@ -0,0 +1,19 @@
1
+ // What a project's `.factory/factory.config.mts` imports from `factory`.
2
+
3
+ export { defineFactory, pnpm, uv } from "./shared/factory.mts"
4
+ export type {
5
+ Check,
6
+ Effort,
7
+ Env,
8
+ FactoryConfig,
9
+ Limits,
10
+ ModelChoice,
11
+ Mount,
12
+ Names,
13
+ Retries,
14
+ Role,
15
+ Timeouts,
16
+ Toolchain,
17
+ Workflow,
18
+ } from "./shared/factory.mts"
19
+ export type { SetupStep } from "./shared/setup.mts"