@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,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,144 @@
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
+ sandbox,
18
+ setUpSandbox,
19
+ startServices,
20
+ stopServices,
21
+ } from "./environment.mts"
22
+ import {
23
+ ENV_DUMP_COMMAND,
24
+ type EnvContext,
25
+ classifyEnv,
26
+ parseEnvDump,
27
+ parseEnvFile,
28
+ secretsIn,
29
+ } from "./shared/env-leaks.mts"
30
+ import { type ResolvedFactory, checkPlan } from "./shared/factory.mts"
31
+
32
+ const envFile = (path: string) =>
33
+ existsSync(path) ? parseEnvFile(readFileSync(path, "utf8")) : []
34
+
35
+ const CANARY_NAME = "FACTORY_CHECK_CANARY"
36
+
37
+ /**
38
+ * Fail for every variable in the sandbox that shouldn't be there. It prints
39
+ * names and reasons only: the values are the secrets.
40
+ */
41
+ const checkEnvLeaks = async (
42
+ box: Pick<sandcastle.Sandbox, "exec">,
43
+ name: string,
44
+ envContext: EnvContext
45
+ ) => {
46
+ const result = await box.exec(ENV_DUMP_COMMAND)
47
+ const env = result.exitCode === 0 ? parseEnvDump(result.stdout) : undefined
48
+ if (!env) {
49
+ console.log(
50
+ `FAIL ${name} (couldn't read the sandbox's environment, exit ${result.exitCode})`
51
+ )
52
+ return false
53
+ }
54
+ const leaks = classifyEnv(env, envContext)
55
+ if (leaks.length === 0) {
56
+ console.log(`ok ${name}`)
57
+ return true
58
+ }
59
+ console.log(`FAIL ${name}`)
60
+ for (const leak of leaks) console.log(` ${leak.name}: ${leak.reason}`)
61
+ return false
62
+ }
63
+
64
+ /**
65
+ * Check the sandbox of the project at `repoRoot`, whose working directory
66
+ * this must run in: Sandcastle reads `.sandcastle/.env` from it, and without
67
+ * it the sandbox here wouldn't get the variables an agent's does. It returns
68
+ * 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
+
78
+ // Set on the host before the sandbox exists and declared nowhere, so it can
79
+ // only reach the sandbox if Sandcastle passes the host's environment through.
80
+ const canary = `canary-${randomBytes(12).toString("hex")}`
81
+ process.env[CANARY_NAME] = canary
82
+
83
+ // What the sandbox may get (`.sandcastle/.env`'s keys) and what it must
84
+ // not: the host's secret-looking variables and those in the repo's `.env`,
85
+ // which is read here on the host and never copied in.
86
+ const envContext: EnvContext = {
87
+ declared: new Set(
88
+ envFile(join(repoRoot, ".sandcastle/.env")).map(([k]) => k)
89
+ ),
90
+ hostSecrets: new Map([
91
+ ...secretsIn(process.env),
92
+ ...secretsIn(Object.fromEntries(envFile(join(repoRoot, ".env")))),
93
+ ]),
94
+ canary,
95
+ }
96
+
97
+ let failed = 0
98
+
99
+ try {
100
+ startServices(factory)
101
+
102
+ {
103
+ await using box = await sandcastle.createSandbox({
104
+ branch,
105
+ sandbox: sandbox(factory, 1),
106
+ })
107
+ await setUpSandbox(factory, box)
108
+ console.log(`\nSandbox ready at ${box.worktreePath}\n`)
109
+
110
+ for (const check of plan) {
111
+ if (check.kind === "env-leaks") {
112
+ if (!(await checkEnvLeaks(box, check.name, envContext))) failed++
113
+ continue
114
+ }
115
+ const started = Date.now()
116
+ const result = await box.exec(check.command)
117
+ const seconds = ((Date.now() - started) / 1000).toFixed(1)
118
+ if (result.exitCode === 0) {
119
+ console.log(`ok ${check.name} (${seconds}s)`)
120
+ } else {
121
+ failed++
122
+ console.log(
123
+ `FAIL ${check.name} (${seconds}s, exit ${result.exitCode})`
124
+ )
125
+ const output = `${result.stdout}\n${result.stderr}`.trim()
126
+ console.log(output.split("\n").slice(-40).join("\n"))
127
+ }
128
+ }
129
+ }
130
+ } finally {
131
+ // The branch only ever holds the commit it was created from.
132
+ try {
133
+ execFileSync("git", ["branch", "-D", branch], { stdio: "ignore" })
134
+ } catch {
135
+ // It was never created.
136
+ }
137
+ stopServices(factory)
138
+ }
139
+
140
+ console.log(
141
+ failed === 0 ? "\nThe environment works." : `\n${failed} check(s) failed.`
142
+ )
143
+ return failed
144
+ }
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 and `.sandcastle/.env` to the working
57
+ // directory, and the host's 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,63 @@
1
+ // The sandbox environment: what an agent's bwrap sandbox can see and reach.
2
+ //
3
+ // bwrap gives each sandbox a private, empty home directory. That hides the
4
+ // package caches, so the project's toolchains mount them back in, and it means
5
+ // nothing from the repo's `.env` is ever there: the sandbox gets only the
6
+ // variables the project declares and the tokens in `.sandcastle/.env`. Never
7
+ // copy `.env` into a worktree.
8
+ //
9
+ // What a sandbox gets comes from `.factory/factory.config.mts`, resolved in
10
+ // shared/factory.mts. Check it without spending tokens:
11
+ // factory check
12
+
13
+ import { execFileSync } from "node:child_process"
14
+ import type { Sandbox } from "@ai-hero/sandcastle"
15
+ import { bwrap } from "@ai-hero/sandcastle/sandboxes/bwrap"
16
+ import type { ResolvedFactory } from "./shared/factory.mts"
17
+ import { runSetupSteps } from "./shared/setup.mts"
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Services
21
+ // ---------------------------------------------------------------------------
22
+
23
+ const compose = (factory: ResolvedFactory, ...args: string[]) => {
24
+ if (factory.services === undefined) return
25
+ execFileSync(
26
+ "docker",
27
+ ["compose", "-f", factory.services.composeFile, ...args],
28
+ { stdio: ["ignore", "inherit", "inherit"] }
29
+ )
30
+ }
31
+
32
+ /** Start the project's services, if it has any, and wait until they're
33
+ * ready. */
34
+ export const startServices = (factory: ResolvedFactory) =>
35
+ compose(factory, "up", "--detach", "--wait")
36
+
37
+ /** Remove them, with their data. */
38
+ export const stopServices = (factory: ResolvedFactory) =>
39
+ compose(factory, "down", "--volumes")
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // The sandbox
43
+ // ---------------------------------------------------------------------------
44
+
45
+ /**
46
+ * A bwrap sandbox with the project's mounts and its variables for `slot`.
47
+ *
48
+ * `slot` separates sandboxes that run at the same time: 0 for a run with no
49
+ * parallel peer (the planner, preflight), 1 up for the parallel ones. The
50
+ * project's `env(slot)` decides what a slot changes, such as a Redis database.
51
+ */
52
+ export const sandbox = (factory: ResolvedFactory, slot = 0) =>
53
+ bwrap({
54
+ mounts: factory.sandbox.mounts,
55
+ env: factory.sandbox.env(slot),
56
+ })
57
+
58
+ /** Make a fresh sandbox fit for an agent: the toolchains' installs, the
59
+ * skill links and the project's setup steps (see shared/setup.mts). */
60
+ export const setUpSandbox = (
61
+ factory: ResolvedFactory,
62
+ box: Pick<Sandbox, "exec">
63
+ ) => 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"