@tirso0882/factory 0.1.0 → 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.
@@ -14,6 +14,7 @@ import { existsSync, readFileSync } from "node:fs"
14
14
  import { join } from "node:path"
15
15
  import * as sandcastle from "@ai-hero/sandcastle"
16
16
  import {
17
+ hostSandbox,
17
18
  sandbox,
18
19
  setUpSandbox,
19
20
  startServices,
@@ -63,9 +64,8 @@ const checkEnvLeaks = async (
63
64
 
64
65
  /**
65
66
  * 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.
67
+ * this must run in: Sandcastle anchors its worktrees there, as it does an
68
+ * agent's. It returns how many checks failed.
69
69
  */
70
70
  export const checkEnvironment = async (
71
71
  factory: ResolvedFactory,
@@ -74,19 +74,18 @@ export const checkEnvironment = async (
74
74
  ) => {
75
75
  const branch = factory.names.environmentCheckBranch
76
76
  const plan = checkPlan(factory, { quick })
77
+ console.log(`Sandbox: ${hostSandbox()}`)
77
78
 
78
79
  // Set on the host before the sandbox exists and declared nowhere, so it can
79
80
  // only reach the sandbox if Sandcastle passes the host's environment through.
80
81
  const canary = `canary-${randomBytes(12).toString("hex")}`
81
82
  process.env[CANARY_NAME] = canary
82
83
 
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.
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.
86
87
  const envContext: EnvContext = {
87
- declared: new Set(
88
- envFile(join(repoRoot, ".sandcastle/.env")).map(([k]) => k)
89
- ),
88
+ declared: new Set(factory.agentEnv.declared),
90
89
  hostSecrets: new Map([
91
90
  ...secretsIn(process.env),
92
91
  ...secretsIn(Object.fromEntries(envFile(join(repoRoot, ".env")))),
package/cli.mts CHANGED
@@ -53,8 +53,8 @@ const main = async (argv: readonly string[]) => {
53
53
  }
54
54
 
55
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).
56
+ // Sandcastle anchors worktrees to the working directory, and the host's
57
+ // git and gh run in it (shared/host.mts).
58
58
  process.chdir(root)
59
59
  const factory = await loadFactory(root)
60
60
 
package/environment.mts CHANGED
@@ -1,9 +1,12 @@
1
- // The sandbox environment: what an agent's bwrap sandbox can see and reach.
1
+ // The sandbox environment: what an agent's sandbox can see and reach.
2
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
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
7
10
  // copy `.env` into a worktree.
8
11
  //
9
12
  // What a sandbox gets comes from `.factory/factory.config.mts`, resolved in
@@ -11,9 +14,18 @@
11
14
  // factory check
12
15
 
13
16
  import { execFileSync } from "node:child_process"
14
- import type { Sandbox } from "@ai-hero/sandcastle"
15
- import { bwrap } from "@ai-hero/sandcastle/sandboxes/bwrap"
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"
16
24
  import type { ResolvedFactory } from "./shared/factory.mts"
25
+ import {
26
+ type NativeSandbox,
27
+ chooseNativeSandbox,
28
+ } from "./shared/native-sandbox.mts"
17
29
  import { runSetupSteps } from "./shared/setup.mts"
18
30
 
19
31
  // ---------------------------------------------------------------------------
@@ -42,18 +54,33 @@ export const stopServices = (factory: ResolvedFactory) =>
42
54
  // The sandbox
43
55
  // ---------------------------------------------------------------------------
44
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
+
45
70
  /**
46
- * A bwrap sandbox with the project's mounts and its variables for `slot`.
71
+ * The host's sandbox with the project's mounts and its variables for `slot`.
47
72
  *
48
73
  * `slot` separates sandboxes that run at the same time: 0 for a run with no
49
74
  * parallel peer (the planner, preflight), 1 up for the parallel ones. The
50
75
  * project's `env(slot)` decides what a slot changes, such as a Redis database.
51
76
  */
52
- export const sandbox = (factory: ResolvedFactory, slot = 0) =>
53
- bwrap({
77
+ export const sandbox = (factory: ResolvedFactory, slot = 0) => {
78
+ const options: SandboxOptions = {
54
79
  mounts: factory.sandbox.mounts,
55
- env: factory.sandbox.env(slot),
56
- })
80
+ env: { ...factory.sandbox.env(slot), ...factory.agentEnv.values },
81
+ }
82
+ return PROVIDERS[hostSandbox()](options)
83
+ }
57
84
 
58
85
  /** Make a fresh sandbox fit for an agent: the toolchains' installs, the
59
86
  * skill links and the project's setup steps (see shared/setup.mts). */
package/main.mts CHANGED
@@ -11,9 +11,10 @@
11
11
  // Plan The host lists the open `ready-for-agent` issues you wrote and
12
12
  // drops any with an open blocker or an open factory pull request.
13
13
  // A planner picks the ones that can be built side by side.
14
- // Implement Each issue gets a bwrap sandbox on `factory/issue-<n>`,
15
- // branched from origin/main. The implementer builds it and the
16
- // reviewer checks it against the coding standards and the issue.
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.
17
18
  // Publish A writer drafts the pull request body, with the `pr` skill if
18
19
  // the config lists it, and the host pushes the branch and opens
19
20
  // the pull request.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tirso0882/factory",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The agent factory: builds ready-for-agent issues into pull requests.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -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
+ }
@@ -5,7 +5,8 @@
5
5
  export type EnvLeak = { name: string; reason: string }
6
6
 
7
7
  export type EnvContext = {
8
- /** Keys `.sandcastle/.env` declares: Sandcastle passes these on purpose. */
8
+ /** Keys the agent's env files declare (agent-env.mts): the factory passes
9
+ * these on purpose. */
9
10
  declared: ReadonlySet<string>
10
11
  /** The host's secrets, name → value. */
11
12
  hostSecrets: ReadonlyMap<string, string>
@@ -26,8 +27,8 @@ export const secretsIn = (env: NodeJS.ProcessEnv) =>
26
27
  )
27
28
 
28
29
  /**
29
- * The name/value pairs of a `.env` file, read the way Sandcastle reads
30
- * `.sandcastle/.env`: blank lines and comments skipped, quotes stripped.
30
+ * The name/value pairs of a `.env` file: blank lines and comments skipped,
31
+ * quotes stripped.
31
32
  */
32
33
  export const parseEnvFile = (text: string): [string, string][] =>
33
34
  text.split("\n").flatMap((line) => {
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { dirname, join, relative, resolve } from "node:path"
8
8
  import semver from "semver"
9
+ import { type AgentEnv, resolveAgentEnv } from "./agent-env.mts"
9
10
  import { type SetupStep, shellQuote } from "./setup.mts"
10
11
 
11
12
  export type Effort = "low" | "medium" | "high" | "xhigh" | "max"
@@ -244,6 +245,9 @@ export type ResolvedFactory = {
244
245
  checks: readonly Check[]
245
246
  probes: readonly Check[]
246
247
  sandbox: ResolvedSandbox
248
+ /** The agent's tokens, from the per-user and project env files
249
+ * (agent-env.mts). Every sandbox gets them. */
250
+ agentEnv: AgentEnv
247
251
  /** The compose file to start before a run, if the project has services. */
248
252
  services?: { composeFile: string }
249
253
  /** The highest slot a sandbox may take, if the project limits it. */
@@ -774,6 +778,7 @@ export const resolveFactory = (
774
778
  ...(config.probes ?? []),
775
779
  ]),
776
780
  sandbox: resolveSandbox(config, host, sources),
781
+ agentEnv: resolveAgentEnv(host),
777
782
  ...(config.services === undefined
778
783
  ? {}
779
784
  : {
@@ -0,0 +1,42 @@
1
+ // Which native sandbox the host runs agents in. The factory picks it on every
2
+ // run, so one committed config works on every machine: the config has no OS
3
+ // setting.
4
+
5
+ /** What the choice reads from the host: `process.platform` and
6
+ * `os.release()` (the kernel's version: Darwin's, on macOS). */
7
+ export type Host = { platform: NodeJS.Platform; release: string }
8
+
9
+ export type NativeSandbox = "bwrap" | "seatbelt"
10
+
11
+ /** Darwin 23 is macOS 14, the first macOS seatbelt supports. */
12
+ const FIRST_SEATBELT_DARWIN = 23
13
+
14
+ /** From Darwin 20 (macOS 11) on, the macOS major is Darwin's less 9. */
15
+ const FIRST_NUMBERED_DARWIN = 20
16
+ const DARWIN_TO_MACOS = 9
17
+
18
+ /** The native sandbox for `host`: bwrap on Linux (WSL2 reports itself as
19
+ * Linux), seatbelt on macOS 14 and later. Anywhere else it throws: the
20
+ * factory never runs an agent unsandboxed. */
21
+ export const chooseNativeSandbox = (host: Host): NativeSandbox => {
22
+ if (host.platform === "linux") return "bwrap"
23
+ if (host.platform === "darwin") {
24
+ const darwin = Number.parseInt(host.release, 10)
25
+ if (darwin >= FIRST_SEATBELT_DARWIN) return "seatbelt"
26
+ throw unsupported(macOSName(darwin))
27
+ }
28
+ throw unsupported(host.platform === "win32" ? "native Windows" : host.platform)
29
+ }
30
+
31
+ const macOSName = (darwin: number) => {
32
+ if (Number.isNaN(darwin)) return "a macOS whose version can't be read"
33
+ return darwin >= FIRST_NUMBERED_DARWIN
34
+ ? `macOS ${darwin - DARWIN_TO_MACOS}`
35
+ : "a macOS older than 11"
36
+ }
37
+
38
+ const unsupported = (hostName: string) =>
39
+ new Error(
40
+ `This host is ${hostName}, which has no sandbox the factory supports. ` +
41
+ "Use Linux, WSL2 on Windows, or macOS 14 or later."
42
+ )
@@ -1,5 +1,5 @@
1
- // One tiny call through a sandbox proves the token in `.sandcastle/.env`
2
- // before any ticket depends on it.
1
+ // One tiny call through a sandbox proves the agent's token (from
2
+ // `~/.config/factory/.env` or `.factory/.env`) before any ticket depends on it.
3
3
 
4
4
  import * as sandcastle from "@ai-hero/sandcastle"
5
5
  import { sandbox } from "../../environment.mts"
@@ -31,9 +31,10 @@ export const preflight = async (
31
31
  signal,
32
32
  })
33
33
  } catch (error) {
34
+ const { user, project } = factory.agentEnv.files
34
35
  throw new Error(
35
36
  isAuthFailure(error)
36
- ? "The agent can't log in: renew CLAUDE_CODE_OAUTH_TOKEN in .sandcastle/.env with `claude setup-token`."
37
+ ? `The agent can't log in: renew CLAUDE_CODE_OAUTH_TOKEN with \`claude setup-token\`, in ${user} or in ${project}, which wins.`
37
38
  : "The preflight agent run failed.",
38
39
  { cause: error }
39
40
  )