@mnaimfaizy/agent-kit 1.0.0-beta.14 → 1.0.0-beta.16

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 (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,122 @@
1
+ // The GitHub App by the manifest flow (ADR 0043). The App holds Contents and
2
+ // Pull requests write and nothing else: Workflows is not in its manifest, so a
3
+ // factory branch cannot edit a workflow. The flow needs a person signed in to
4
+ // GitHub to click Create: this module serves one local page on 127.0.0.1 that
5
+ // posts the manifest to GitHub, and waits for GitHub's redirect back with the
6
+ // one-time code. `convertManifest` (writes.mjs) trades the code for the key.
7
+
8
+ import { randomBytes } from "node:crypto";
9
+ import { createServer } from "node:http";
10
+
11
+ export const APP_PERMISSIONS = Object.freeze({ contents: "write", pull_requests: "write" });
12
+ export const FLOW_TIMEOUT_MS = 10 * 60 * 1000;
13
+
14
+ /** The manifest GitHub is sent. No webhook, no events, no `workflows` permission. */
15
+ export function buildManifest({ repo, url, redirectUrl }) {
16
+ const name = `${repo.split("/")[1]}-factory`.slice(0, 34);
17
+ return {
18
+ name,
19
+ url,
20
+ redirect_url: redirectUrl,
21
+ public: false,
22
+ hook_attributes: { url, active: false },
23
+ default_events: [],
24
+ default_permissions: { ...APP_PERMISSIONS },
25
+ };
26
+ }
27
+
28
+ /** Where the form posts: the user's, or the organization's, App settings. */
29
+ export function createUrl({ host, owner, inOrganization, state }) {
30
+ const base = `https://${host}`;
31
+ return inOrganization
32
+ ? `${base}/organizations/${owner}/settings/apps/new?state=${state}`
33
+ : `${base}/settings/apps/new?state=${state}`;
34
+ }
35
+
36
+ const escapeHtml = (s) =>
37
+ String(s).replace(
38
+ /[&<>"']/g,
39
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c],
40
+ );
41
+
42
+ const page = (action, manifest) =>
43
+ `<!doctype html><meta charset="utf-8"><title>Create the Factory App</title>` +
44
+ `<p>Sending the App manifest to GitHub. If nothing happens, press the button.</p>` +
45
+ `<form id="f" method="post" action="${escapeHtml(action)}">` +
46
+ `<input type="hidden" name="manifest" value="${escapeHtml(JSON.stringify(manifest))}">` +
47
+ `<button>Continue to GitHub</button></form><script>document.getElementById("f").submit()</script>`;
48
+
49
+ /**
50
+ * Serve the form, wait for GitHub's redirect, and resolve `{ code }`. Rejects
51
+ * on a redirect with the wrong `state`, on a timeout, and on `signal`.
52
+ *
53
+ * @param {{
54
+ * repoInfo: { repo: string, url: string, host: string, owner: string, inOrganization: boolean },
55
+ * announce: (url: string) => void,
56
+ * signal?: AbortSignal,
57
+ * timeoutMs?: number,
58
+ * }} opts
59
+ */
60
+ export function runManifestFlow({ repoInfo, announce, signal, timeoutMs = FLOW_TIMEOUT_MS }) {
61
+ const state = randomBytes(16).toString("hex");
62
+ return new Promise((resolve, reject) => {
63
+ let finished = false;
64
+ let timer;
65
+ const server = createServer((req, res) => {
66
+ const url = new URL(req.url, "http://127.0.0.1");
67
+ if (url.pathname === "/callback") {
68
+ const ok =
69
+ url.searchParams.get("state") === state &&
70
+ /^[A-Za-z0-9]{10,}$/.test(url.searchParams.get("code") ?? "");
71
+ res.writeHead(ok ? 200 : 400, { "content-type": "text/plain; charset=utf-8" });
72
+ res.end(
73
+ ok
74
+ ? "The App was created. Return to the terminal."
75
+ : "Not the redirect this command waits for.",
76
+ );
77
+ if (ok) finish(null, { code: url.searchParams.get("code") });
78
+ return;
79
+ }
80
+ if (url.pathname === "/" && req.method === "GET") {
81
+ const { port } = server.address();
82
+ const manifest = buildManifest({
83
+ repo: repoInfo.repo,
84
+ url: repoInfo.url,
85
+ redirectUrl: `http://127.0.0.1:${port}/callback`,
86
+ });
87
+ res.writeHead(200, {
88
+ "content-type": "text/html; charset=utf-8",
89
+ "cache-control": "no-store",
90
+ });
91
+ res.end(page(createUrl({ ...repoInfo, state }), manifest));
92
+ return;
93
+ }
94
+ res.writeHead(404);
95
+ res.end();
96
+ });
97
+ function finish(err, value) {
98
+ if (finished) return;
99
+ finished = true;
100
+ clearTimeout(timer);
101
+ signal?.removeEventListener("abort", onAbort);
102
+ server.close();
103
+ server.closeAllConnections?.();
104
+ if (err) reject(err);
105
+ else resolve(value);
106
+ }
107
+ const onAbort = () => finish(new Error("the App flow was interrupted"));
108
+ server.on("error", (e) => finish(e));
109
+ server.listen(0, "127.0.0.1", () => {
110
+ timer = setTimeout(
111
+ () => finish(new Error("the App flow timed out: nobody clicked Create")),
112
+ timeoutMs,
113
+ );
114
+ if (signal?.aborted) return onAbort();
115
+ signal?.addEventListener("abort", onAbort, { once: true });
116
+ announce(`http://127.0.0.1:${server.address().port}/`);
117
+ });
118
+ });
119
+ }
120
+
121
+ /** The installation page for a new App, where the person picks this repository. */
122
+ export const installUrl = ({ host, slug }) => `https://${host}/apps/${slug}/installations/new`;
@@ -0,0 +1,409 @@
1
+ // `agent-kit factory setup [--engine workflow|orchestrate] [--repo o/r]`
2
+ // (ADR 0043): the GitHub side of adopting the Factory. It needs a terminal and
3
+ // an admin `gh` login, refuses in CI, shows and confirms each write before it
4
+ // makes it, and can be run again: whatever is already there is left as it is.
5
+ // It never sets the Kill switch AGENT_KIT_FACTORY_ENABLED; that is the last
6
+ // step it prints.
7
+ //
8
+ // What it writes, in order: the labels, the pinned Factory control issue, then
9
+ // (Workflow engine only) the GitHub App by the manifest flow with its key in
10
+ // the `factory-publish` environment secret (a repository secret on a private
11
+ // repository of a Free plan) and its client ID in a variable, then the
12
+ // default-branch ruleset from `.github/factory/ruleset.json`. On the
13
+ // Orchestrate engine it creates no App and no environment: it prints the PAT's
14
+ // permissions instead. Every write is in writes.mjs.
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { command, sanitizeLine } from "../../checks/result.mjs";
19
+ import { askYesNo } from "../../prompt.mjs";
20
+ import { CONTROL_MARKER, RULESET_PATH } from "../init/blueprint.mjs";
21
+ import { installUrl, runManifestFlow } from "./app.mjs";
22
+ import { SETUP_LABELS } from "./labels.mjs";
23
+ import * as read from "./reads.mjs";
24
+ import * as write from "./writes.mjs";
25
+
26
+ export const ENVIRONMENT = "factory-publish";
27
+ export const APP_VARIABLE = "AGENT_KIT_APP_ID";
28
+ export const APP_SECRET = "AGENT_KIT_APP_PRIVATE_KEY";
29
+ export const KILL_SWITCH = "AGENT_KIT_FACTORY_ENABLED";
30
+ export const CONTROL_TITLE = "Factory control";
31
+ const DOCS = "docs/factory/setup.md";
32
+ const HOST_DOCS = "docs/factory/host.md";
33
+ /** The PAT's repository permissions, as the token form labels them. */
34
+ export const PAT_PERMISSIONS = Object.freeze([
35
+ ["Contents", "Read and write"],
36
+ ["Issues", "Read and write"],
37
+ ["Pull requests", "Read and write"],
38
+ ["Commit statuses", "Read and write"],
39
+ ["Variables", "Read-only"],
40
+ ]);
41
+
42
+ const CONTROL_BODY = `${CONTROL_MARKER}
43
+ The Agent-kit Factory's control issue, pinned. It holds the Engine lease, the merge gate's trip marker and the daily-cap notices. Do not close it or edit this marker. See ${DOCS}.
44
+ `;
45
+
46
+ /** Whether the environment says this runs in CI. */
47
+ export const inCi = (env) =>
48
+ ["CI", "GITHUB_ACTIONS", "BUILDKITE", "GITLAB_CI", "TF_BUILD", "JENKINS_URL"].some((k) => {
49
+ const v = String(env[k] ?? "").toLowerCase();
50
+ return v !== "" && v !== "0" && v !== "false";
51
+ });
52
+
53
+ /** A ruleset file that setup may import, or why not. */
54
+ export function checkRulesetFile(text) {
55
+ let ruleset;
56
+ try {
57
+ ruleset = JSON.parse(text);
58
+ } catch {
59
+ return { error: `${RULESET_PATH} is not JSON` };
60
+ }
61
+ if (typeof ruleset?.name !== "string" || !ruleset.name)
62
+ return { error: `${RULESET_PATH} has no name` };
63
+ if (Array.isArray(ruleset.bypass_actors) ? ruleset.bypass_actors.length : true) {
64
+ return { error: `${RULESET_PATH} has bypass actors (a Factory ruleset has none)` };
65
+ }
66
+ const types = new Set((ruleset.rules ?? []).map((r) => r.type));
67
+ const lacking = ["pull_request", "required_status_checks", "non_fast_forward", "deletion"].filter(
68
+ (t) => !types.has(t),
69
+ );
70
+ if (lacking.length) return { error: `${RULESET_PATH} lacks the ${lacking.join(", ")} rule(s)` };
71
+ if (/"context"\s*:\s*"factory\//i.test(text)) {
72
+ return {
73
+ error: `${RULESET_PATH} requires a factory/* context (the merge gate checks those itself)`,
74
+ };
75
+ }
76
+ return { name: ruleset.name };
77
+ }
78
+
79
+ /**
80
+ * @param {{
81
+ * runner: any, env: NodeJS.ProcessEnv, repo?: string, engine?: string, cwd: string,
82
+ * prompt: ((q: string) => Promise<string>) | null,
83
+ * appFlow?: typeof runManifestFlow, signal?: AbortSignal,
84
+ * out: (s: string) => void, err: (s: string) => void,
85
+ * }} io
86
+ * @returns {Promise<number>} 0 done, 1 a step failed or this login is no admin, 2 refused to start
87
+ */
88
+ export async function runFactorySetup({
89
+ runner,
90
+ env,
91
+ repo,
92
+ engine = "workflow",
93
+ cwd,
94
+ prompt,
95
+ appFlow = runManifestFlow,
96
+ signal,
97
+ out,
98
+ err,
99
+ }) {
100
+ if (!["workflow", "orchestrate"].includes(engine)) {
101
+ err(`--engine takes workflow or orchestrate, got ${JSON.stringify(engine)}`);
102
+ return 2;
103
+ }
104
+ if (inCi(env)) {
105
+ err(
106
+ "agent-kit factory setup: refusing to run in CI. It writes repository settings and needs a person: run it in a terminal.",
107
+ );
108
+ return 2;
109
+ }
110
+ if (!prompt) {
111
+ err(
112
+ "agent-kit factory setup: there is no terminal to confirm on. Run it in a terminal; it asks before each write.",
113
+ );
114
+ return 2;
115
+ }
116
+ const ask = (q) => askYesNo(prompt, q);
117
+ const gh = async (args, stdin) => {
118
+ if (stdin !== undefined && !runner.start) {
119
+ // A value that must travel on stdin is never dropped or put in an argument.
120
+ return { status: 1, stdout: "", stderr: "this runner cannot pass a secret on stdin" };
121
+ }
122
+ if (stdin !== undefined) {
123
+ const r = await runner.start("gh", args, { cwd, stdin });
124
+ return { status: r.status, stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") };
125
+ }
126
+ const r = runner("gh", args, { cwd });
127
+ return { status: r.status, stdout: String(r.stdout ?? ""), stderr: String(r.stderr ?? "") };
128
+ };
129
+
130
+ let info;
131
+ try {
132
+ info = await read.readRepo(gh, repo);
133
+ } catch (e) {
134
+ err(`agent-kit factory setup: ${e.message}`);
135
+ return 1;
136
+ }
137
+ out(`Factory setup for ${info.repo} (${engine} engine).`);
138
+ if (!info.admin) {
139
+ err(
140
+ `agent-kit factory setup: this gh login is not an admin on ${info.repo}. Sign in as one (gh auth login) and run it again.`,
141
+ );
142
+ return 1;
143
+ }
144
+ const slug = info.repo;
145
+ let failed = 0;
146
+ const skipped = [];
147
+ const line = (s) => out(sanitizeLine(s));
148
+
149
+ /** Show what a write will do, ask, run it. Returns "done", "skipped" or "failed". */
150
+ async function step(title, lines, run) {
151
+ out("");
152
+ line(`${title}:`);
153
+ for (const l of lines) line(` ${l}`);
154
+ if (!(await ask("Go ahead? [y/N] "))) {
155
+ skipped.push(title);
156
+ out("Skipped.");
157
+ return "skipped";
158
+ }
159
+ const r = await run();
160
+ if (r.ok) {
161
+ out("Done.");
162
+ return "done";
163
+ }
164
+ failed += 1;
165
+ line(`FAILED ${r.reason}`);
166
+ return "failed";
167
+ }
168
+
169
+ try {
170
+ // Labels.
171
+ const have = await read.readLabels(gh, slug);
172
+ const missing = SETUP_LABELS.filter((l) => !have.has(l.name));
173
+ if (!missing.length) out("\nLabels: all present.");
174
+ else {
175
+ await step(
176
+ "Create labels",
177
+ missing.map((l) => l.name),
178
+ async () => {
179
+ for (const label of missing) {
180
+ const r = await write.createLabel(gh, slug, label);
181
+ if (!r.ok) return r;
182
+ }
183
+ return { ok: true };
184
+ },
185
+ );
186
+ }
187
+
188
+ // The pinned control issue.
189
+ let control = await read.readControlIssue(gh, slug);
190
+ if (control === null) {
191
+ const r = await step(
192
+ "Create the Factory control issue",
193
+ [`title ${CONTROL_TITLE}, with the marker ${CONTROL_MARKER}`],
194
+ async () => {
195
+ const made = await write.createControlIssue(gh, slug, {
196
+ title: CONTROL_TITLE,
197
+ body: CONTROL_BODY,
198
+ });
199
+ if (made.ok) control = made.number;
200
+ return made;
201
+ },
202
+ );
203
+ if (r === "done") out(`Control issue: #${control}.`);
204
+ } else out(`\nControl issue: #${control} exists.`);
205
+ if (control !== null) {
206
+ if ((await read.readPinned(gh, slug)).includes(control)) out("Control issue: pinned.");
207
+ else
208
+ await step(`Pin the control issue #${control}`, ["gh issue pin"], () =>
209
+ write.pinIssue(gh, slug, control),
210
+ );
211
+ }
212
+
213
+ if (engine === "workflow") await appStep();
214
+ else printPat();
215
+
216
+ // The ruleset.
217
+ await rulesetStep();
218
+ } catch (e) {
219
+ err(`agent-kit factory setup: ${e.message}`);
220
+ return 1;
221
+ }
222
+
223
+ async function appStep() {
224
+ const variables = await read.readVariableNames(gh, slug);
225
+ const envExists = await read.readEnvironmentExists(gh, slug, ENVIRONMENT);
226
+ const inEnv = envExists
227
+ ? (await read.readSecretNames(gh, slug, ENVIRONMENT)).has(APP_SECRET)
228
+ : false;
229
+ const inRepo = (await read.readSecretNames(gh, slug)).has(APP_SECRET);
230
+ if (variables.has(APP_VARIABLE) && (inEnv || inRepo)) {
231
+ out(
232
+ `\nApp: ${APP_VARIABLE} and ${APP_SECRET} (${inEnv ? `environment ${ENVIRONMENT}` : "repository secret"}) are set; left as they are.`,
233
+ );
234
+ return;
235
+ }
236
+ if (variables.has(APP_VARIABLE) || inEnv || inRepo) {
237
+ out(
238
+ `\nApp: only part of it is set (${[variables.has(APP_VARIABLE) && APP_VARIABLE, (inEnv || inRepo) && APP_SECRET].filter(Boolean).join(", ")}). Delete it, or set the rest by hand, then run this again. Left as it is.`,
239
+ );
240
+ return;
241
+ }
242
+ // One question per write, all before the App exists: its key is shown once
243
+ // and cannot be fetched again, so nothing may stay undecided afterwards.
244
+ out("");
245
+ line(
246
+ `The GitHub App: Contents and Pull requests write, Workflows off, installed on ${slug} only.`,
247
+ );
248
+ line(
249
+ `It opens one page on 127.0.0.1 that sends GitHub the App manifest; you click Create there, then install the App.`,
250
+ );
251
+ const useEnv = !envExists
252
+ ? await ask(
253
+ `Create the environment ${ENVIRONMENT}, limited to ${info.defaultBranch}, for the App's key? [y/N] `,
254
+ )
255
+ : true;
256
+ if (!useEnv) {
257
+ skipped.push("App");
258
+ return out("Skipped the App: it needs the key's home first.");
259
+ }
260
+ if (!(await ask(`Store the App's key as ${APP_SECRET} (never printed)? [y/N] `))) {
261
+ skipped.push("App key");
262
+ return out("Skipped the App: its key would have nowhere to go.");
263
+ }
264
+ if (
265
+ !(await ask(`Set the repository variable ${APP_VARIABLE} to the App's client ID? [y/N] `))
266
+ ) {
267
+ skipped.push("App client ID");
268
+ return out("Skipped the App: its client ID would have nowhere to go.");
269
+ }
270
+ if (!(await ask("Create the App now (you click Create on GitHub)? [y/N] "))) {
271
+ skipped.push("App");
272
+ return out("Skipped the App.");
273
+ }
274
+
275
+ let scope = envExists ? ENVIRONMENT : null;
276
+ if (!envExists) {
277
+ const made = await write.createEnvironment(gh, slug, {
278
+ name: ENVIRONMENT,
279
+ branch: info.defaultBranch,
280
+ });
281
+ if (made.ok) scope = ENVIRONMENT;
282
+ else if (info.private) {
283
+ line(`${made.reason}`);
284
+ out(
285
+ "An environment's secrets need a paid plan on a private repository. The key can go in a repository secret instead.",
286
+ );
287
+ if (!(await ask("Store the key as a repository secret instead? [y/N] "))) {
288
+ skipped.push("App");
289
+ return out("Skipped the App.");
290
+ }
291
+ } else {
292
+ failed += 1;
293
+ return line(`FAILED ${made.reason}`);
294
+ }
295
+ }
296
+ let created;
297
+ try {
298
+ created = await appFlow({
299
+ repoInfo: info,
300
+ announce: (url) => {
301
+ out("");
302
+ out(`Open this page in your browser and click Create: ${url}`);
303
+ out("Waiting for GitHub...");
304
+ },
305
+ signal,
306
+ });
307
+ } catch (e) {
308
+ failed += 1;
309
+ return line(`FAILED the App was not created: ${e.message}`);
310
+ }
311
+ const converted = await write.convertManifest(gh, created.code);
312
+ if (!converted.ok) {
313
+ failed += 1;
314
+ return line(`FAILED ${converted.reason}`);
315
+ }
316
+ const app = converted.app;
317
+ out(`Created the App ${app.slug}.`);
318
+ const key = await write.setSecret(gh, slug, { name: APP_SECRET, value: app.pem, env: scope });
319
+ if (!key.ok) {
320
+ failed += 1;
321
+ line(`FAILED ${key.reason}`);
322
+ out(
323
+ `The App ${app.slug} exists but its key was not stored. Delete it at https://${info.host}/settings/apps/${app.slug}/advanced and run this again.`,
324
+ );
325
+ return;
326
+ }
327
+ out(
328
+ `Stored ${APP_SECRET} in ${scope ? `the ${scope} environment` : "the repository's secrets"}.`,
329
+ );
330
+ if (scope) {
331
+ out(
332
+ `Note: the build's publish job still reads ${APP_SECRET} as a repository secret until it names the environment ${ENVIRONMENT}; until then it will not find this key.`,
333
+ );
334
+ }
335
+ const variable = await write.setVariable(gh, slug, { name: APP_VARIABLE, value: app.clientId });
336
+ if (!variable.ok) {
337
+ failed += 1;
338
+ return line(`FAILED ${variable.reason} (set it by hand to ${app.clientId})`);
339
+ }
340
+ out(`Set ${APP_VARIABLE}.`);
341
+ out("");
342
+ out(`Install the App on ${slug} only: ${installUrl({ host: info.host, slug: app.slug })}`);
343
+ if (!(await ask("Have you installed it? [y/N] "))) {
344
+ skipped.push("App installation");
345
+ out("Install it before turning the Factory on: the build cannot push without it.");
346
+ }
347
+ }
348
+
349
+ function printPat() {
350
+ out("");
351
+ out("Orchestrate engine: no App and no environment. Make the engine a fine-grained PAT:");
352
+ line(` 1. Create it at https://${info.host}/settings/personal-access-tokens/new`);
353
+ line(` 2. Repository access: Only select repositories, and select ${slug} alone.`);
354
+ out(
355
+ " 3. Repository permissions, and nothing else (Contents, Issues, Pull requests and Statuses write, Variables read):",
356
+ );
357
+ for (const [name, level] of PAT_PERMISSIONS) out(` ${name}: ${level}`);
358
+ out(" 4. Give it to `factory run` as AGENT_KIT_GITHUB_TOKEN: the token itself, or an");
359
+ out(" op:// reference read with `op read`. Never `gh auth token`.");
360
+ out(` 5. Run it unattended from the host recipe: ${HOST_DOCS}`);
361
+ }
362
+
363
+ async function rulesetStep() {
364
+ let root = cwd;
365
+ const top = runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
366
+ if (top.status === 0) root = String(top.stdout).trim();
367
+ const file = join(root, RULESET_PATH);
368
+ let text;
369
+ try {
370
+ text = readFileSync(file, "utf8");
371
+ } catch {
372
+ out(
373
+ `\nRuleset: no ${RULESET_PATH} here. Run \`agent-kit init --factory\` first, then this again.`,
374
+ );
375
+ return;
376
+ }
377
+ const checked = checkRulesetFile(text);
378
+ if (checked.error) {
379
+ failed += 1;
380
+ return line(`\nFAILED Ruleset: ${checked.error}`);
381
+ }
382
+ if ((await read.readRulesetNames(gh, slug)).has(checked.name)) {
383
+ return out(`\nRuleset: "${checked.name}" exists; left as it is.`);
384
+ }
385
+ await step(
386
+ "Import the default-branch ruleset",
387
+ [
388
+ `${RULESET_PATH} as "${checked.name}": pull requests and your CI required, no force-push, no deletion, no bypass`,
389
+ ],
390
+ () => write.createRuleset(gh, slug, { file }),
391
+ );
392
+ }
393
+
394
+ out("");
395
+ if (skipped.length) out(`Skipped: ${skipped.join(", ")}. Run this again to do them.`);
396
+ if (failed) {
397
+ out(
398
+ `Result: ${failed} step(s) failed (exit 1). Run this again after fixing them: it leaves what is done.`,
399
+ );
400
+ } else {
401
+ out("Result: done. Nothing here turned the Factory on.");
402
+ }
403
+ out("");
404
+ out(
405
+ `Last, only when you have reviewed and pushed ${engine === "workflow" ? "the Callers" : "the blueprint files"}, turn the Factory on (the Kill switch; no agent-kit command ever sets it):`,
406
+ );
407
+ out(` $ ${command("gh", "variable", "set", KILL_SWITCH, "--body", "true")}`);
408
+ return failed ? 1 : 0;
409
+ }
@@ -0,0 +1,25 @@
1
+ // The labels `factory setup` creates, each one only when it is missing: the
2
+ // nine Factory states and the modifier (ADR 0034), the three Risk tiers, and
3
+ // the two labels beside them the Dispatcher reads.
4
+
5
+ import { FACTORY_LABELS, PAUSED_LABEL, READY_LABEL } from "../sweep/states.mjs";
6
+
7
+ const STATE_COLOR = "0E8A16";
8
+
9
+ export const SETUP_LABELS = Object.freeze([
10
+ ...FACTORY_LABELS.filter((l) => l !== PAUSED_LABEL).map((name) => ({
11
+ name,
12
+ color: STATE_COLOR,
13
+ description: "Agent-kit Factory: the task's state (the Dispatcher moves it)",
14
+ })),
15
+ { name: PAUSED_LABEL, color: "FBCA04", description: "Agent-kit Factory: freeze this task" },
16
+ { name: "risk:low", color: "C2E0C6", description: "Agent-kit Factory: Risk tier low" },
17
+ { name: "risk:medium", color: "FEF2C0", description: "Agent-kit Factory: Risk tier medium" },
18
+ { name: "risk:high", color: "F9D0C4", description: "Agent-kit Factory: Risk tier high" },
19
+ {
20
+ name: "regression",
21
+ color: "D93F0B",
22
+ description: "Agent-kit Factory: a task that undoes a merge",
23
+ },
24
+ { name: READY_LABEL, color: "5319E7", description: "Ready for an agent to pick up" },
25
+ ]);
@@ -0,0 +1,129 @@
1
+ // What `factory setup` reads from GitHub before it writes: read-only `gh`
2
+ // calls through the same async `gh` as writes.mjs. A failed read throws, so
3
+ // setup never writes on a guess.
4
+
5
+ import { REPO_PATTERN } from "../../checks/result.mjs";
6
+ import { isControlBody } from "../init/blueprint.mjs";
7
+
8
+ export class ReadError extends Error {}
9
+
10
+ async function json(gh, args, what) {
11
+ const r = await gh(args);
12
+ if (r.status !== 0) {
13
+ throw new ReadError(
14
+ `${what}: ${
15
+ String(r.stderr || r.stdout)
16
+ .trim()
17
+ .split("\n")[0] || "gh failed"
18
+ }`,
19
+ );
20
+ }
21
+ try {
22
+ return JSON.parse(r.stdout || "null");
23
+ } catch {
24
+ throw new ReadError(`${what}: not JSON`);
25
+ }
26
+ }
27
+
28
+ /** The repository, and whether this login is an admin on it. */
29
+ export async function readRepo(gh, repo) {
30
+ const data = await json(
31
+ gh,
32
+ [
33
+ "repo",
34
+ "view",
35
+ ...(repo ? [repo] : []),
36
+ "--json",
37
+ "nameWithOwner,viewerPermission,isPrivate,isInOrganization,defaultBranchRef,url",
38
+ ],
39
+ "gh repo view",
40
+ );
41
+ if (!REPO_PATTERN.test(data?.nameWithOwner ?? ""))
42
+ throw new ReadError("gh repo view: no repository name");
43
+ let host = "github.com";
44
+ try {
45
+ host = new URL(data.url).host.toLowerCase();
46
+ } catch {
47
+ // github.com
48
+ }
49
+ return {
50
+ repo: data.nameWithOwner,
51
+ owner: data.nameWithOwner.split("/")[0],
52
+ host,
53
+ url: data.url,
54
+ admin: data.viewerPermission === "ADMIN",
55
+ private: Boolean(data.isPrivate),
56
+ inOrganization: Boolean(data.isInOrganization),
57
+ defaultBranch: data.defaultBranchRef?.name ?? "main",
58
+ };
59
+ }
60
+
61
+ export async function readLabels(gh, repo) {
62
+ const labels = await json(
63
+ gh,
64
+ ["label", "list", "--repo", repo, "--limit", "500", "--json", "name"],
65
+ "gh label list",
66
+ );
67
+ return new Set(labels.map((l) => l.name));
68
+ }
69
+
70
+ /** The open issue that carries the control marker, or null. */
71
+ export async function readControlIssue(gh, repo) {
72
+ const issues = await json(
73
+ gh,
74
+ ["issue", "list", "--repo", repo, "--state", "open", "--limit", "500", "--json", "number,body"],
75
+ "gh issue list",
76
+ );
77
+ return issues.find((i) => isControlBody(i.body))?.number ?? null;
78
+ }
79
+
80
+ export async function readPinned(gh, repo) {
81
+ const [owner, name] = repo.split("/");
82
+ const data = await json(
83
+ gh,
84
+ [
85
+ "api",
86
+ "graphql",
87
+ "-f",
88
+ "query=query($o:String!,$n:String!){repository(owner:$o,name:$n){pinnedIssues(first:3){nodes{issue{number}}}}}",
89
+ "-f",
90
+ `o=${owner}`,
91
+ "-f",
92
+ `n=${name}`,
93
+ ],
94
+ "read pinned issues",
95
+ );
96
+ return (data?.data?.repository?.pinnedIssues?.nodes ?? []).map((n) => n.issue.number);
97
+ }
98
+
99
+ export async function readVariableNames(gh, repo) {
100
+ const vars = await json(
101
+ gh,
102
+ ["variable", "list", "--repo", repo, "--json", "name"],
103
+ "gh variable list",
104
+ );
105
+ return new Set(vars.map((v) => v.name));
106
+ }
107
+
108
+ /** Secret names: the environment's, or (no `env`) the repository's. */
109
+ export async function readSecretNames(gh, repo, env = null) {
110
+ const secrets = await json(
111
+ gh,
112
+ ["secret", "list", "--repo", repo, ...(env ? ["--env", env] : []), "--json", "name"],
113
+ "gh secret list",
114
+ );
115
+ return new Set(secrets.map((s) => s.name));
116
+ }
117
+
118
+ /** Whether the environment exists (a 404 is "no"; any other failure throws). */
119
+ export async function readEnvironmentExists(gh, repo, name) {
120
+ const r = await gh(["api", `repos/${repo}/environments/${name}`, "--jq", ".name"]);
121
+ if (r.status === 0) return true;
122
+ if (/HTTP 404|Not Found/i.test(`${r.stderr}${r.stdout}`)) return false;
123
+ throw new ReadError(`read environment ${name}: ${String(r.stderr).trim().split("\n")[0]}`);
124
+ }
125
+
126
+ export async function readRulesetNames(gh, repo) {
127
+ const rulesets = await json(gh, ["api", `repos/${repo}/rulesets`], "read the rulesets");
128
+ return new Set(rulesets.map((r) => r.name));
129
+ }