@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.17

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 (120) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +332 -5
  4. package/src/deep-scan/docker-driver.mjs +70 -3
  5. package/src/deep-scan/lifecycle.mjs +2 -2
  6. package/src/deep-scan/sbx-driver.mjs +34 -47
  7. package/src/doctor.mjs +53 -1
  8. package/src/exec.mjs +18 -5
  9. package/src/factory/budget/budget.mjs +260 -0
  10. package/src/factory/build/command.mjs +321 -0
  11. package/src/factory/build/factory.mjs +473 -0
  12. package/src/factory/build/findings.mjs +55 -0
  13. package/src/factory/build/host.mjs +230 -0
  14. package/src/factory/build/notes.mjs +191 -0
  15. package/src/factory/build/pull-request.mjs +74 -0
  16. package/src/factory/bundle.mjs +146 -0
  17. package/src/factory/checks/allowed-paths.mjs +50 -0
  18. package/src/factory/checks/plan-header.mjs +296 -0
  19. package/src/factory/checks/qa.mjs +85 -0
  20. package/src/factory/checks/review.mjs +73 -0
  21. package/src/factory/checks/security.mjs +50 -0
  22. package/src/factory/checks/stage-check.mjs +89 -0
  23. package/src/factory/claims/command.mjs +187 -0
  24. package/src/factory/claims/release.mjs +111 -0
  25. package/src/factory/decision/answers.mjs +103 -0
  26. package/src/factory/decision/command.mjs +64 -0
  27. package/src/factory/decision/plan.mjs +99 -0
  28. package/src/factory/decision/request.mjs +116 -0
  29. package/src/factory/doctor/files.mjs +349 -0
  30. package/src/factory/doctor/index.mjs +56 -0
  31. package/src/factory/doctor/local.mjs +513 -0
  32. package/src/factory/doctor/orchestrate.mjs +146 -0
  33. package/src/factory/engine/lease.mjs +146 -0
  34. package/src/factory/engine/local-engine.mjs +177 -0
  35. package/src/factory/engine/lockfile.mjs +64 -0
  36. package/src/factory/engine/workflow-engine.mjs +124 -0
  37. package/src/factory/gate/comment.mjs +88 -0
  38. package/src/factory/gate/config.mjs +57 -0
  39. package/src/factory/gate/gate-core.mjs +250 -0
  40. package/src/factory/gate/guarded.mjs +17 -0
  41. package/src/factory/gate/reads.mjs +105 -0
  42. package/src/factory/gate/task.mjs +193 -0
  43. package/src/factory/gate/trip-reads.mjs +82 -0
  44. package/src/factory/gate/trip.mjs +87 -0
  45. package/src/factory/init/blueprint.mjs +181 -0
  46. package/src/factory/init/index.mjs +338 -0
  47. package/src/factory/labels/evidence.mjs +162 -0
  48. package/src/factory/labels/moves.mjs +32 -0
  49. package/src/factory/labels/reconcile.mjs +267 -0
  50. package/src/factory/labels/revert.mjs +87 -0
  51. package/src/factory/labels/timeline.mjs +72 -0
  52. package/src/factory/labels/voided.mjs +59 -0
  53. package/src/factory/limits/harness.mjs +39 -0
  54. package/src/factory/limits/limits.mjs +131 -0
  55. package/src/factory/merge/command.mjs +172 -0
  56. package/src/factory/outbox/check.mjs +240 -0
  57. package/src/factory/outbox/rulings.mjs +195 -0
  58. package/src/factory/plan/command.mjs +66 -0
  59. package/src/factory/plan/comment.mjs +156 -0
  60. package/src/factory/plan/publish.mjs +149 -0
  61. package/src/factory/plan/risk.mjs +153 -0
  62. package/src/factory/qa/command.mjs +301 -0
  63. package/src/factory/qa/decide.mjs +86 -0
  64. package/src/factory/qa/report.mjs +50 -0
  65. package/src/factory/records/engine-record.mjs +133 -0
  66. package/src/factory/records/main.mjs +96 -0
  67. package/src/factory/records/record.mjs +226 -0
  68. package/src/factory/records/sink.mjs +57 -0
  69. package/src/factory/report/build.mjs +92 -0
  70. package/src/factory/report/command.mjs +80 -0
  71. package/src/factory/report/facts.mjs +226 -0
  72. package/src/factory/report/gate-section.mjs +122 -0
  73. package/src/factory/report/metrics.mjs +111 -0
  74. package/src/factory/report/reads.mjs +246 -0
  75. package/src/factory/report/render.mjs +121 -0
  76. package/src/factory/report/rollout.mjs +154 -0
  77. package/src/factory/review/brief.mjs +195 -0
  78. package/src/factory/review/command.mjs +182 -0
  79. package/src/factory/run/awake.mjs +70 -0
  80. package/src/factory/run/collect.mjs +77 -0
  81. package/src/factory/run/command.mjs +556 -0
  82. package/src/factory/run/gh.mjs +46 -0
  83. package/src/factory/run/launch.mjs +66 -0
  84. package/src/factory/run/pipelines.mjs +694 -0
  85. package/src/factory/run/raw.mjs +96 -0
  86. package/src/factory/run/restart.mjs +83 -0
  87. package/src/factory/run/s3.mjs +193 -0
  88. package/src/factory/run/secrets.mjs +142 -0
  89. package/src/factory/run/teardown.mjs +242 -0
  90. package/src/factory/run/token.mjs +70 -0
  91. package/src/factory/run/worktree.mjs +160 -0
  92. package/src/factory/security/audit.mjs +353 -0
  93. package/src/factory/security/command.mjs +157 -0
  94. package/src/factory/setup/app.mjs +122 -0
  95. package/src/factory/setup/command.mjs +472 -0
  96. package/src/factory/setup/labels.mjs +25 -0
  97. package/src/factory/setup/reads.mjs +159 -0
  98. package/src/factory/setup/writes.mjs +138 -0
  99. package/src/factory/snapshot/write.mjs +176 -0
  100. package/src/factory/stop/command.mjs +136 -0
  101. package/src/factory/sweep/actions-main.mjs +119 -0
  102. package/src/factory/sweep/command.mjs +65 -0
  103. package/src/factory/sweep/knobs.mjs +78 -0
  104. package/src/factory/sweep/marker-version.mjs +15 -0
  105. package/src/factory/sweep/markers.mjs +112 -0
  106. package/src/factory/sweep/overlap.mjs +24 -0
  107. package/src/factory/sweep/run.mjs +198 -0
  108. package/src/factory/sweep/shell.mjs +398 -0
  109. package/src/factory/sweep/split.mjs +104 -0
  110. package/src/factory/sweep/states.mjs +87 -0
  111. package/src/factory/sweep/sweep-core.mjs +2009 -0
  112. package/src/factory/tracker/github.mjs +713 -0
  113. package/src/factory/tracker/operations.mjs +153 -0
  114. package/src/factory/upgrade/index.mjs +83 -0
  115. package/src/init.mjs +62 -24
  116. package/src/kit-owned-paths.mjs +1 -1
  117. package/src/stage/build.mjs +100 -0
  118. package/src/stage/factory-live.mjs +288 -0
  119. package/src/stage.mjs +100 -4
  120. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,87 @@
1
+ // The merge gate's trip (spec #500, Merge gate specifics; ADR 0041). A revert of a
2
+ // pull request the gate merged, or a `regression` issue that links one, within 7
3
+ // days of the merge, makes the gate act as `shadow`. The trip is remembered as an
4
+ // engine comment on the Factory control issue, its marker:
5
+ //
6
+ // <!-- factory:trip v=1 at=<ISO time of the revert or regression> state=tripped -->
7
+ //
8
+ // A person clears it by editing `state=tripped` to `state=cleared` in that comment.
9
+ // The gate leaves the trip only when the marker is cleared by someone with write
10
+ // access AND the shadow bar is met again, counted from the trip (`at`). Pure: the
11
+ // shell reads the control issue's comments and the evidence, this decides.
12
+ //
13
+ // no evidence, no marker -> none
14
+ // evidence newer than any marker -> tripped, and a new marker is written
15
+ // the newest marker says tripped -> tripped
16
+ // the newest marker says cleared -> cleared, with `barMet`; a clearing by
17
+ // the engine or by someone without write
18
+ // access does not count: tripped
19
+
20
+ export const TRIP_PREFIX = "<!-- factory:trip ";
21
+ const TRIP_MARKER =
22
+ /^<!-- factory:trip v=1 at=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z) state=(tripped|cleared) -->$/m;
23
+
24
+ /** The marker's fields, or null when the text holds no readable one. */
25
+ export function parseTripComment(body) {
26
+ const m = TRIP_MARKER.exec(String(body ?? ""));
27
+ return m ? { at: Date.parse(m[1]), atIso: m[1], state: m[2] } : null;
28
+ }
29
+
30
+ const tripCode = (iso) => `\`${iso}\``;
31
+
32
+ /** The comment the gate writes on the control issue for a new trip. */
33
+ export function renderTripComment({ atIso, pull = null }) {
34
+ const named = pull ? `pull request #${pull}` : "a pull request";
35
+ return `<!-- factory:trip v=1 at=${atIso} state=tripped -->
36
+ **Merge gate tripped** at ${tripCode(atIso)}: a revert or a regression names ${named}, which the gate merged, within 7 days of its merge. The gate acts as \`shadow\` and merges nothing.
37
+
38
+ To leave the trip, edit this comment and change \`state=tripped\` to \`state=cleared\` in the marker line (a person with write access). The gate then returns to \`on\` only once the shadow bar is met again, counted from the trip. \`agent-kit factory report --gate\` shows the bar.
39
+ `;
40
+ }
41
+
42
+ const tripLower = (login) =>
43
+ String(login ?? "")
44
+ .toLowerCase()
45
+ .replace(/\[bot\]$/, "");
46
+
47
+ /**
48
+ * @param {{
49
+ * evidenceAt: number | null | undefined,
50
+ * comments: Array<{ id: number, author: string, editor?: string | null, body: string }> | null | undefined,
51
+ * writers: string[] | null | undefined,
52
+ * isEngine: (login: string) => boolean,
53
+ * barMet: boolean | null | undefined,
54
+ * }} facts
55
+ * `evidenceAt` is the latest revert or regression time (ms), null for none, undefined when unread.
56
+ * `comments` are the control issue's comments, null when unread. `writers` are the logins with write
57
+ * access among the editors of those comments. `barMet` is the shadow bar on every auto tier since `at`.
58
+ * @returns {{ state: "none" | "tripped" | "cleared" | "unreadable", at: number | null, barMet?: boolean | null, write?: boolean, why?: string }}
59
+ */
60
+ export function tripState({ evidenceAt, comments, writers, isEngine, barMet }) {
61
+ if (evidenceAt === undefined || comments === null || comments === undefined) {
62
+ return { state: "unreadable", at: null, why: "the trip could not be read" };
63
+ }
64
+ const markers = comments
65
+ .filter((c) => isEngine(c.author))
66
+ .map((c) => ({ comment: c, marker: parseTripComment(c.body) }))
67
+ .filter((x) => x.marker)
68
+ .sort((a, b) => a.marker.at - b.marker.at || a.comment.id - b.comment.id);
69
+ const newest = markers.at(-1) ?? null;
70
+ if (evidenceAt !== null && (!newest || newest.marker.at < evidenceAt)) {
71
+ return { state: "tripped", at: evidenceAt, write: true };
72
+ }
73
+ if (!newest) return { state: "none", at: null };
74
+ const at = newest.marker.at;
75
+ if (newest.marker.state === "tripped") return { state: "tripped", at };
76
+ // Cleared: by a person with write access, never by the engine's own edit.
77
+ const editor = newest.comment.editor;
78
+ if (
79
+ !editor ||
80
+ isEngine(editor) ||
81
+ !Array.isArray(writers) ||
82
+ !writers.map(tripLower).includes(tripLower(editor))
83
+ ) {
84
+ return { state: "tripped", at, why: "cleared by someone without write access" };
85
+ }
86
+ return { state: "cleared", at, barMet: barMet ?? null };
87
+ }
@@ -0,0 +1,181 @@
1
+ // The Factory blueprint `init --factory` writes (ADR 0043): pure functions from
2
+ // the tag's `examples/factory/` and the Consumer's answers to file contents.
3
+ // Nothing here touches the disk or GitHub. The files are the Consumer's after
4
+ // the first copy; the Kit-owned bundle is copied by init's own Kit-owned step.
5
+
6
+ import { qaAppPathsFromConfig } from "../qa/decide.mjs";
7
+
8
+ export const FACTORY_DIR = ".github/factory";
9
+ export const CONFIG_PATH = `${FACTORY_DIR}/config.json`;
10
+ export const RISK_RULES_PATH = `${FACTORY_DIR}/risk-rules.json`;
11
+ export const RULESET_PATH = `${FACTORY_DIR}/ruleset.json`;
12
+ export const BUNDLE_PATH = ".github/agent-factory/";
13
+ export const CONFIG_EXAMPLE = "examples/factory/factory-config.json";
14
+ export const RISK_RULES_EXAMPLE = "examples/factory/risk-rules.json";
15
+ export const CALLERS_DIR = "examples/factory/";
16
+ export const RULESET_NAME = "Agent-kit Factory: default branch";
17
+ export const CONTROL_MARKER = "<!-- factory:control v=1 -->";
18
+ /** The control issue's body marker, of this version or the previous one (no `v`). */
19
+ export const CONTROL_MARKER_PATTERN = /<!-- factory:control(?: v=1)? -->/;
20
+ export const isControlBody = (body) => CONTROL_MARKER_PATTERN.test(String(body ?? ""));
21
+
22
+ const CALLER_NAME = /^factory-[a-z][a-z0-9-]*\.yml$/;
23
+ const KIT_PIN =
24
+ /(\/agent-kit\/\.github\/workflows\/[A-Za-z0-9._-]+\.ya?ml)@v\d+\.\d+\.\d+(?:-(?:alpha|beta|rc)\.\d+)?(?=$|[\s"'#])/gm;
25
+
26
+ export class BlueprintError extends Error {}
27
+
28
+ /**
29
+ * A Caller's text with every `uses:` pin of the kit's reusable workflows moved
30
+ * to `tag`. A Caller that calls none has nothing to pin and is copied as it is.
31
+ */
32
+ export function pinCaller(text, tag) {
33
+ return text.replace(KIT_PIN, (_, path) => `${path}@${tag}`);
34
+ }
35
+
36
+ /** The blueprint Callers the tag ships: `factory-*.yml` in `examples/factory/`. */
37
+ export function callerNames(files) {
38
+ return files.map((f) => f.replace(/^.*\//, "")).filter((n) => CALLER_NAME.test(n));
39
+ }
40
+
41
+ /** The factory config: the tag's blueprint (Phase 1 values), `budget.notify` set to the owners to mention. */
42
+ export function renderConfig(text, { notify }) {
43
+ let config;
44
+ try {
45
+ config = JSON.parse(text);
46
+ } catch {
47
+ throw new BlueprintError(`${CONFIG_EXAMPLE} is not JSON.`);
48
+ }
49
+ if (config === null || typeof config !== "object" || Array.isArray(config) || !config.budget) {
50
+ throw new BlueprintError(`${CONFIG_EXAMPLE} is not a factory config.`);
51
+ }
52
+ // The QA path rule (`qa.app_paths`, ADR 0048): without it every QA Report is held for a
53
+ // person, so the blueprint always carries one. `["**"]` makes every path an app path;
54
+ // the maintainers narrow it to say which paths a person must review.
55
+ if (qaAppPathsFromConfig(text).value === null) {
56
+ throw new BlueprintError(`${CONFIG_EXAMPLE} has no \`qa.app_paths\` list of path globs.`);
57
+ }
58
+ config.budget.notify = notify;
59
+ return `${JSON.stringify(config, null, 2)}\n`;
60
+ }
61
+
62
+ /** Whether `text` is JSON that is an object (the risk rules are copied as they are). */
63
+ export function checkRiskRules(text) {
64
+ try {
65
+ const rules = JSON.parse(text);
66
+ if (!Array.isArray(rules?.rules)) throw new Error("no rules");
67
+ } catch {
68
+ throw new BlueprintError(`${RISK_RULES_EXAMPLE} is not a risk-rules file.`);
69
+ }
70
+ return text;
71
+ }
72
+
73
+ /**
74
+ * The default-branch ruleset: pull requests and the Consumer's CI required,
75
+ * force-push and deletion blocked, no bypass actors. It never requires a
76
+ * `factory/*` context: the merge gate checks the Stage checks itself, by
77
+ * creator, and a ruleset would block every pull request that is not a
78
+ * factory one (ADR 0041).
79
+ */
80
+ export function buildRuleset({ ciChecks }) {
81
+ if (!ciChecks.length) throw new BlueprintError("the ruleset needs at least one CI check.");
82
+ return {
83
+ name: RULESET_NAME,
84
+ target: "branch",
85
+ enforcement: "active",
86
+ conditions: { ref_name: { include: ["~DEFAULT_BRANCH"], exclude: [] } },
87
+ bypass_actors: [],
88
+ rules: [
89
+ { type: "deletion" },
90
+ { type: "non_fast_forward" },
91
+ {
92
+ type: "pull_request",
93
+ parameters: {
94
+ required_approving_review_count: 0,
95
+ dismiss_stale_reviews_on_push: false,
96
+ require_code_owner_review: false,
97
+ require_last_push_approval: false,
98
+ required_review_thread_resolution: false,
99
+ },
100
+ },
101
+ {
102
+ type: "required_status_checks",
103
+ parameters: {
104
+ strict_required_status_checks_policy: false,
105
+ required_status_checks: ciChecks.map((context) => ({ context })),
106
+ },
107
+ },
108
+ ],
109
+ };
110
+ }
111
+
112
+ export const renderRuleset = (answers) => `${JSON.stringify(buildRuleset(answers), null, 2)}\n`;
113
+
114
+ /** The Guarded paths a person must approve (the gate never auto-merges a change to them). */
115
+ export const GUARDED_PATTERNS = [
116
+ "/.github/workflows/",
117
+ "/.github/factory/",
118
+ "/.github/agent-factory/",
119
+ ];
120
+
121
+ /**
122
+ * `CODEOWNERS` with a line for each Guarded path that has none. Existing
123
+ * lines are never changed. Returns the new text, or null when nothing is added.
124
+ */
125
+ export function addCodeowners(existing, owners) {
126
+ const have = new Set(
127
+ String(existing ?? "")
128
+ .split("\n")
129
+ .filter((l) => l.trim() && !l.trim().startsWith("#"))
130
+ .map((l) => l.trim().split(/\s+/)[0]),
131
+ );
132
+ const missing = GUARDED_PATTERNS.filter((p) => !have.has(p));
133
+ if (!missing.length) return null;
134
+ const base = String(existing ?? "");
135
+ const lead = base === "" ? "" : base.endsWith("\n") ? "\n" : "\n\n";
136
+ return (
137
+ `${base}${lead}# Agent-kit Factory: Guarded paths. The merge gate never auto-merges a change here.\n` +
138
+ `${missing.map((p) => `${p} ${owners.join(" ")}`).join("\n")}\n`
139
+ );
140
+ }
141
+
142
+ const OWNER = /^@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\/[A-Za-z0-9_.-]+)?$/;
143
+
144
+ /** Owners as `--codeowners` takes them: `@login` or `@org/team`, separated by commas or spaces. */
145
+ export function parseOwners(raw) {
146
+ const owners = [
147
+ ...new Set(
148
+ String(raw)
149
+ .split(/[\s,]+/)
150
+ .filter(Boolean),
151
+ ),
152
+ ];
153
+ const bad = owners.find((o) => !OWNER.test(o));
154
+ if (!owners.length || bad !== undefined) {
155
+ return { error: `--codeowners takes @login or @org/team, got ${JSON.stringify(bad ?? raw)}` };
156
+ }
157
+ return { value: owners };
158
+ }
159
+
160
+ const CONTROL = /[\p{Cc}\p{Zl}\p{Zp}]/u;
161
+
162
+ /** CI check names as `--ci-checks` takes them: comma-separated, none of them a `factory/*` context. */
163
+ export function parseCiChecks(raw) {
164
+ const names = [
165
+ ...new Set(
166
+ String(raw)
167
+ .split(",")
168
+ .map((s) => s.trim())
169
+ .filter(Boolean),
170
+ ),
171
+ ];
172
+ const bad = names.find((n) => CONTROL.test(n) || n.length > 200 || /^factory\//i.test(n));
173
+ if (!names.length || bad !== undefined) {
174
+ return {
175
+ error:
176
+ `--ci-checks takes your CI's check names, comma-separated, never a factory/* context ` +
177
+ `(the merge gate checks those itself), got ${JSON.stringify(bad ?? raw)}`,
178
+ };
179
+ }
180
+ return { value: names };
181
+ }
@@ -0,0 +1,338 @@
1
+ // `agent-kit init --factory [--engine workflow|orchestrate]` (ADR 0043): the
2
+ // Factory blueprint as a reviewable diff. It writes only local files: the
3
+ // blueprint Callers (Workflow engine), the factory config with Phase 1's
4
+ // values, the risk rules, `CODEOWNERS` lines for the Guarded paths, a ruleset
5
+ // JSON, and the Kit-owned paths (the bundle `.github/agent-factory/` among
6
+ // them, on both engines: the Orchestrate engine reads its prompt files). The GitHub side is `factory setup`; no
7
+ // command sets the Kill switch, which is the last step printed.
8
+ //
9
+ // Plan first, then write, as `init` does: every file is read and every
10
+ // refusal checked before anything on disk changes.
11
+
12
+ import { readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { command } from "../../checks/result.mjs";
15
+ import { DEFAULT_KIT_REPO } from "../../callers.mjs";
16
+ import { fileAndPinChecks, printFileAndPinChecks } from "../../doctor.mjs";
17
+ import { firstLine } from "../../exec.mjs";
18
+ import { PreManifestTagError, serverFromEnv } from "../../kit-tag.mjs";
19
+ import {
20
+ applyPlan,
21
+ checkLocalPath,
22
+ listed,
23
+ lstatOrNull,
24
+ Refusal,
25
+ reportRefusal,
26
+ stageFileModes,
27
+ } from "../../local-writes.mjs";
28
+ import { patPermissionsSummary } from "../setup/command.mjs";
29
+ import { caseCollisions } from "../../safe-paths.mjs";
30
+ import { isReleaseTag } from "../../tags.mjs";
31
+ import {
32
+ addCodeowners,
33
+ BlueprintError,
34
+ CALLERS_DIR,
35
+ callerNames,
36
+ checkRiskRules,
37
+ CONFIG_EXAMPLE,
38
+ CONFIG_PATH,
39
+ parseCiChecks,
40
+ parseOwners,
41
+ pinCaller,
42
+ renderConfig,
43
+ renderRuleset,
44
+ RISK_RULES_EXAMPLE,
45
+ RISK_RULES_PATH,
46
+ RULESET_PATH,
47
+ } from "./blueprint.mjs";
48
+
49
+ export const ENGINES = ["workflow", "orchestrate"];
50
+ const CODEOWNERS_FILES = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"];
51
+
52
+ /** The answers `init --factory` asks for, as flags name them. */
53
+ export const FACTORY_QUESTIONS = [
54
+ { key: "tag", flag: "--tag <vX>", ask: "Agent-kit tag to adopt (for example v1.0.0)" },
55
+ {
56
+ key: "codeowners",
57
+ flag: "--codeowners <@login,...>",
58
+ ask: "CODEOWNERS: who approves changes to the Guarded paths (@login or @org/team)",
59
+ },
60
+ {
61
+ key: "ciChecks",
62
+ flag: "--ci-checks <name,...>",
63
+ ask: "Your CI's check names, which the ruleset requires (comma-separated)",
64
+ },
65
+ ];
66
+
67
+ /** Check and normalise one answer. Returns { value } or { error }. */
68
+ export function parseFactoryAnswer(key, raw) {
69
+ const s = String(raw ?? "");
70
+ if (key === "tag") {
71
+ return isReleaseTag(s)
72
+ ? { value: s }
73
+ : {
74
+ error: `--tag must be a Release-line tag (vX.Y.Z or vX.Y.Z-stage.N), got ${JSON.stringify(s)}`,
75
+ };
76
+ }
77
+ if (key === "codeowners") return parseOwners(s);
78
+ if (key === "ciChecks") return parseCiChecks(s);
79
+ throw new Error(`unknown answer ${key}`);
80
+ }
81
+
82
+ async function collect({ flags, prompt, yes }) {
83
+ const interactive = Boolean(prompt) && !yes;
84
+ const answers = {};
85
+ const missing = [];
86
+ for (const q of FACTORY_QUESTIONS) {
87
+ let raw = flags[q.key];
88
+ if (raw === undefined && interactive) {
89
+ raw = await prompt(`${q.ask}: `);
90
+ if (raw === "") return { error: `${q.ask} is required (${q.flag}).` };
91
+ }
92
+ if (raw === undefined || raw === "") {
93
+ missing.push(q.flag);
94
+ continue;
95
+ }
96
+ const parsed = parseFactoryAnswer(q.key, raw);
97
+ if (parsed.error) return { error: parsed.error };
98
+ answers[q.key] = parsed.value;
99
+ }
100
+ return missing.length ? { missing } : { answers };
101
+ }
102
+
103
+ /**
104
+ * Everything `init --factory` would write, or a Refusal. Touches nothing on disk.
105
+ * @param {{ runner: any, root: string, snap: any, answers: any, engine: string, force: boolean, planKitOwned: Function }} opts
106
+ */
107
+ export function planFactoryInit({ runner, root, snap, answers, engine, force, planKitOwned }) {
108
+ const { tag } = snap;
109
+ const text = (path) => {
110
+ const t = snap.readFile(path);
111
+ if (t === null) throw new Refusal(`${tag} has no ${path}.`);
112
+ if (/[\r\ufffd\u0085]|[\p{Cc}\p{Zl}\p{Zp}]/u.test(t.replace(/[\n\t]/g, ""))) {
113
+ throw new Refusal(`${path} at ${tag} is not plain UTF-8 text with LF line endings.`);
114
+ }
115
+ return t;
116
+ };
117
+ const writes = [];
118
+ const conflicts = [];
119
+ const overwrites = [];
120
+ const fileTarget = (rel, what) => {
121
+ checkLocalPath(root, rel);
122
+ const st = lstatOrNull(join(root, rel));
123
+ if (st && !st.isFile()) {
124
+ throw new Refusal(`${rel} exists and is not a file, so init cannot write the ${what} there.`);
125
+ }
126
+ if (st) {
127
+ conflicts.push(`${rel} (${what})`);
128
+ overwrites.push(rel);
129
+ }
130
+ };
131
+ const add = (path, what, content) => {
132
+ fileTarget(path, what);
133
+ writes.push({ path, bytes: Buffer.from(content, "utf8") });
134
+ };
135
+
136
+ try {
137
+ // Both engines get every Kit-owned path, the bundle folder included: the Orchestrate engine
138
+ // runs the sweep from the CLI, but it reads `planner-header-prompt.md` (and the other files
139
+ // of `.github/agent-factory/`) from the default branch's remote head, so a Consumer cannot plan
140
+ // without them once they are merged. `upgrade` replaces the same folder whole.
141
+ const kit = planKitOwned({ runner, root, snap, force });
142
+ conflicts.push(...kit.conflicts);
143
+ writes.push(...kit.writes);
144
+
145
+ if (engine === "workflow") {
146
+ const names = callerNames(snap.listFiles(CALLERS_DIR).map((f) => f.path));
147
+ if (!names.length) throw new Refusal(`${tag} ships no Factory Callers in ${CALLERS_DIR}.`);
148
+ for (const name of names) {
149
+ add(`.github/workflows/${name}`, "Caller", pinCaller(text(`${CALLERS_DIR}${name}`), tag));
150
+ }
151
+ }
152
+ const mention = answers.codeowners.filter((o) => !o.includes("/"));
153
+ add(CONFIG_PATH, "factory config", renderConfig(text(CONFIG_EXAMPLE), { notify: mention }));
154
+ add(RISK_RULES_PATH, "risk rules", checkRiskRules(text(RISK_RULES_EXAMPLE)));
155
+ add(RULESET_PATH, "ruleset", renderRuleset(answers));
156
+
157
+ const codeowners = CODEOWNERS_FILES.find((p) => lstatOrNull(join(root, p)) !== null);
158
+ const target = codeowners ?? CODEOWNERS_FILES[0];
159
+ checkLocalPath(root, target);
160
+ const st = lstatOrNull(join(root, target));
161
+ if (st && !st.isFile()) throw new Refusal(`${target} exists and is not a file.`);
162
+ const current = st ? readFileSync(join(root, target), "utf8") : "";
163
+ const next = addCodeowners(current, answers.codeowners);
164
+ const rewrites = next === null ? [] : [{ path: target, bytes: Buffer.from(next, "utf8") }];
165
+
166
+ if (conflicts.length && !force) {
167
+ throw new Refusal(
168
+ `${conflicts.length} path(s) init --factory would write already exist, and init does not overwrite them ` +
169
+ "(they are yours after the first copy). Move to another tag with " +
170
+ `\`npx @mnaimfaizy/agent-kit upgrade --tag ${tag}\`, or run init --factory again with --force.`,
171
+ listed(conflicts),
172
+ );
173
+ }
174
+ const clash = caseCollisions(writes.map((w) => w.path));
175
+ if (clash.length)
176
+ throw new Refusal(`Two files differ only in case: ${clash[0].join(" and ")}.`);
177
+ return { deletes: kit.deletes, writes, rewrites, conflicts, unchanged: kit.unchanged };
178
+ } catch (e) {
179
+ if (e instanceof BlueprintError) throw new Refusal(e.message);
180
+ throw e;
181
+ }
182
+ }
183
+
184
+ /** The steps init leaves, as POSIX-shell commands built with `command()`. */
185
+ export function factorySteps({ engine, tag, kitRepo, serverUrl }) {
186
+ const docs = `${serverUrl}/${kitRepo}/blob/${tag}/docs/factory`;
187
+ const orchestrate = engine === "orchestrate";
188
+ const steps = [
189
+ `1. Review \`git status\` and \`git diff\`, then commit and push these files to the default branch (through a pull request if it is protected).`,
190
+ `2. The GitHub side (${orchestrate ? "labels, the control issue, the ruleset" : "labels, the control issue, the App, the ruleset"}), with an admin \`gh\` login, in a terminal:`,
191
+ ` $ ${command("npx", "@mnaimfaizy/agent-kit", "factory", "setup", "--engine", engine)}`,
192
+ `3. Read ${docs}/setup.md, then the Rollout phases.`,
193
+ ];
194
+ if (orchestrate) {
195
+ steps.push(
196
+ `4. The Orchestrate engine runs from your machine with a fine-grained PAT for this one repository: ${patPermissionsSummary()} (the security audit files its draft advisory with the advisories permission). \`factory setup\` prints the steps. Give it to the engine as AGENT_KIT_GITHUB_TOKEN (a value or an op:// reference), never \`gh auth token\`.`,
197
+ `5. Run it unattended from the host recipe (Linux, systemd, the proven one; Windows and macOS are unproven): ${docs}/host.md`,
198
+ );
199
+ }
200
+ steps.push(
201
+ `Last, only when you have reviewed and pushed ${orchestrate ? "these files" : "the Callers"}, turn the Factory on (the Kill switch; no agent-kit command ever sets it):`,
202
+ ` $ ${command("gh", "variable", "set", "AGENT_KIT_FACTORY_ENABLED", "--body", "true")}`,
203
+ );
204
+ return steps;
205
+ }
206
+
207
+ /**
208
+ * @param {{
209
+ * cwd: string, runner: any, flags: Record<string, string | undefined>, engine?: string,
210
+ * force?: boolean, yes?: boolean, prompt?: Function | null, confirm?: Function | null,
211
+ * out: Function, err: Function, openTag: Function, env?: NodeJS.ProcessEnv, planKitOwned: Function,
212
+ * }} opts
213
+ * @returns {Promise<number>} exit code
214
+ */
215
+ export async function runFactoryInit({
216
+ cwd,
217
+ runner,
218
+ flags,
219
+ engine = "workflow",
220
+ force = false,
221
+ yes = false,
222
+ prompt = null,
223
+ confirm = null,
224
+ out,
225
+ err,
226
+ openTag,
227
+ env = process.env,
228
+ planKitOwned,
229
+ }) {
230
+ const refuse = (e) => reportRefusal(out, e);
231
+ if (!ENGINES.includes(engine)) {
232
+ err(`--engine takes workflow or orchestrate, got ${JSON.stringify(engine)}`);
233
+ return 2;
234
+ }
235
+ const collected = await collect({ flags, prompt, yes });
236
+ if (collected.error) {
237
+ err(collected.error);
238
+ return 2;
239
+ }
240
+ if (collected.missing) {
241
+ const why = prompt && yes ? "--yes asks nothing" : "there is no terminal to ask on";
242
+ const needed = [...collected.missing, ...(prompt || yes ? [] : ["--yes"])];
243
+ err(`agent-kit init --factory: ${why}, so pass ${needed.join(" and ")}.`);
244
+ return 2;
245
+ }
246
+ if (!prompt && !yes) {
247
+ err("agent-kit init --factory: there is no terminal to confirm on, so pass --yes.");
248
+ return 2;
249
+ }
250
+ const { answers } = collected;
251
+ const top = runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
252
+ if (top.status !== 0) return refuse(new Refusal(`${cwd} is not a git repository.`));
253
+ const root = top.stdout.trim();
254
+ const serverUrl = serverFromEnv(env);
255
+ out(
256
+ `Adopting the Factory (${engine} engine) from ${DEFAULT_KIT_REPO}@${answers.tag} in ${root}.`,
257
+ );
258
+
259
+ let snap;
260
+ try {
261
+ snap = openTag({
262
+ runner,
263
+ repo: DEFAULT_KIT_REPO,
264
+ tag: answers.tag,
265
+ serverUrl,
266
+ forDeletion: true,
267
+ });
268
+ } catch (e) {
269
+ if (e instanceof PreManifestTagError) return refuse(e);
270
+ return refuse(new Refusal(firstLine(e?.message ?? e)));
271
+ }
272
+ try {
273
+ let plan;
274
+ try {
275
+ plan = planFactoryInit({ runner, root, snap, answers, engine, force, planKitOwned });
276
+ } catch (e) {
277
+ if (e instanceof Refusal) return refuse(e);
278
+ return refuse(new Refusal(firstLine(e?.message ?? e)));
279
+ }
280
+ out("");
281
+ out(`Write (from ${answers.tag}):`);
282
+ const kitPaths = snap.kitOwnedPaths.filter(
283
+ (p) => !plan.unchanged.includes(p) && plan.writes.some((w) => w.path.startsWith(p)),
284
+ );
285
+ for (const p of kitPaths) {
286
+ const n = plan.writes.filter((w) => w.path.startsWith(p)).length;
287
+ out(` ${p} (${n} file${n === 1 ? "" : "s"})`);
288
+ }
289
+ for (const w of plan.writes.filter(
290
+ (x) => !snap.kitOwnedPaths.some((p) => x.path.startsWith(p)),
291
+ )) {
292
+ out(` ${w.path}`);
293
+ }
294
+ for (const w of plan.rewrites) out(` ${w.path} (Guarded-path lines added)`);
295
+ if (plan.conflicts.length) {
296
+ out(`--force: overwriting ${plan.conflicts.length} existing path(s):`);
297
+ for (const c of listed(plan.conflicts)) out(` ${c}`);
298
+ }
299
+ out("");
300
+ if (!yes && !(confirm && (await confirm("Go ahead? [y/N] ")))) {
301
+ out("Stopped. Nothing was changed.");
302
+ return 1;
303
+ }
304
+ try {
305
+ applyPlan(root, plan);
306
+ } catch (e) {
307
+ if (e instanceof Refusal) return refuse(e);
308
+ out(`FAILED init stopped part-way: ${firstLine(e?.message ?? e)}`);
309
+ out(" See `git status`; remove what was written and run init --factory again.");
310
+ return 1;
311
+ }
312
+ out(`Wrote ${plan.writes.length + plan.rewrites.length} file(s).`);
313
+ const note = stageFileModes({ runner, root, writes: plan.writes });
314
+ if (note) out(note);
315
+ out("");
316
+ const failed =
317
+ engine === "workflow"
318
+ ? printFileAndPinChecks(out, fileAndPinChecks({ runner, root, snap }))
319
+ : false;
320
+ out("");
321
+ out(
322
+ "Still to do (init changed nothing on GitHub). Lines starting with $ are POSIX shell commands for you to run:",
323
+ );
324
+ for (const line of factorySteps({
325
+ engine,
326
+ tag: answers.tag,
327
+ kitRepo: DEFAULT_KIT_REPO,
328
+ serverUrl,
329
+ })) {
330
+ out(line);
331
+ }
332
+ out("");
333
+ out(failed ? "Result: a check failed (exit 1)." : "Result: done.");
334
+ return failed ? 1 : 0;
335
+ } finally {
336
+ snap.cleanup();
337
+ }
338
+ }