@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,230 @@
1
+ // The host side of the factory-mode build Stage (build/factory.mjs): every read and
2
+ // write it makes of GitHub, git and the disk, over what the Orchestrate engine holds
3
+ // (`ctx.gh`, `ctx.tracker`, `ctx.git`). The sandbox never sees any of it: it gets the
4
+ // Snapshot the pipeline writes from these reads, and its Outbox comes back through the
5
+ // checker before one of these writes runs. Contract suite:
6
+ // scripts/factory-build-host.test.mjs, over a fake `gh` and a fake `git`.
7
+
8
+ import {
9
+ copyFileSync,
10
+ mkdirSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ renameSync,
14
+ rmSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { dirname, join } from "node:path";
19
+
20
+ import { checkPlanHeader } from "../checks/plan-header.mjs";
21
+ import { latestPlan } from "../plan/comment.mjs";
22
+ import { bundleChangedPaths } from "./command.mjs";
23
+ import { bare } from "../report/facts.mjs";
24
+ import { earlierFindings } from "./findings.mjs";
25
+
26
+ /** The disk as the pipeline uses it: user-only files, written whole and renamed into place. */
27
+ export function createFsx() {
28
+ return {
29
+ mkdir: (dir) => mkdirSync(dir, { recursive: true, mode: 0o700 }),
30
+ writeFiles(dir, files) {
31
+ for (const [name, text] of Object.entries(files)) {
32
+ const path = join(dir, name);
33
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
34
+ const tmp = `${path}.tmp`;
35
+ writeFileSync(tmp, text, { mode: 0o600 });
36
+ renameSync(tmp, path);
37
+ }
38
+ },
39
+ list(dir) {
40
+ try {
41
+ return readdirSync(dir);
42
+ } catch {
43
+ return [];
44
+ }
45
+ },
46
+ read(path) {
47
+ try {
48
+ return readFileSync(path, "utf8");
49
+ } catch {
50
+ return null;
51
+ }
52
+ },
53
+ copy(from, to) {
54
+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 });
55
+ copyFileSync(from, to);
56
+ },
57
+ remove: (path) => rmSync(path, { recursive: true, force: true }),
58
+ };
59
+ }
60
+
61
+ /** The pull request's checks as the Snapshot and the checker say them. */
62
+ const CI = { success: "SUCCESS", failure: "FAILURE", pending: "PENDING" };
63
+
64
+ /**
65
+ * @param {object} ctx `{ repo, identity, issue, gh, tracker, git, fsx? }`; `git(args, { push })` runs
66
+ * git in the engine's clone, with the token in its environment only when `push` is set.
67
+ */
68
+ export function createBuildHost(ctx) {
69
+ const { repo, issue, tracker, gh } = ctx;
70
+ const isEngine = (login) => bare(login) === bare(ctx.identity);
71
+ const fs = ctx.fsx ?? createFsx();
72
+ const json = (args, input) => {
73
+ const result = gh(args, input);
74
+ if (result.status !== 0) throw new Error(`gh ${args.slice(0, 3).join(" ")} failed`);
75
+ return JSON.parse(result.stdout || "null");
76
+ };
77
+ const git = (args) => ctx.git(args);
78
+
79
+ return {
80
+ fs,
81
+
82
+ readPlan() {
83
+ const comments = tracker.readComments(issue);
84
+ const plan = latestPlan(comments, isEngine);
85
+ if (!plan) return null;
86
+ const checked = checkPlanHeader(plan.data, { trusted: true });
87
+ if (!checked.ok) return null;
88
+ const body = comments.find((c) => String(c.id) === String(plan.commentId))?.body ?? "";
89
+ return { n: plan.n, header: checked.header, prose: body };
90
+ },
91
+
92
+ readIssue() {
93
+ const data = json(["api", `repos/${repo}/issues/${issue}`]);
94
+ return { number: issue, title: data?.title ?? "", body: data?.body ?? "" };
95
+ },
96
+
97
+ findings: () => earlierFindings(tracker.readComments(issue), isEngine),
98
+
99
+ base() {
100
+ const branch = tracker.defaultBranch();
101
+ const ref = json([
102
+ "api",
103
+ `repos/${repo}/git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`,
104
+ ]);
105
+ return { branch, sha: ref?.object?.sha };
106
+ },
107
+
108
+ /** The open pull request on `branch`: its head, body and the rollup of its checks, or null. */
109
+ pull(branch) {
110
+ const owner = repo.split("/")[0];
111
+ const [found] =
112
+ json([
113
+ "api",
114
+ `repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branch}`)}`,
115
+ ]) ?? [];
116
+ if (!found) return null;
117
+ let ci = null;
118
+ let checks = [];
119
+ try {
120
+ const read = tracker.readChecks(found.head.sha);
121
+ ci = CI[read.state] ?? null;
122
+ checks = read.contexts.map((c) => ({ context: c.name, state: c.state }));
123
+ } catch {
124
+ // No checks recorded yet: CI has not started, which is not a pass.
125
+ }
126
+ return {
127
+ number: found.number,
128
+ url: found.html_url,
129
+ head: found.head.sha,
130
+ state: "OPEN",
131
+ body: found.body ?? "",
132
+ ci,
133
+ checks,
134
+ };
135
+ },
136
+
137
+ /** The pull request's review threads: `[{ id, path, line, author, resolved, body }]`. */
138
+ threads(number) {
139
+ const [owner, name] = repo.split("/");
140
+ const data = json([
141
+ "api",
142
+ "graphql",
143
+ "-f",
144
+ "query=query($owner: String!, $name: String!, $number: Int!) { repository(owner: $owner, name: $name) { pullRequest(number: $number) { reviewThreads(first: 50) { nodes { id path line isResolved comments(first: 1) { nodes { author { login } body } } } } } } }",
145
+ "-f",
146
+ `owner=${owner}`,
147
+ "-f",
148
+ `name=${name}`,
149
+ "-F",
150
+ `number=${Number(number)}`,
151
+ ]);
152
+ return (data?.data?.repository?.pullRequest?.reviewThreads?.nodes ?? []).map((t) => ({
153
+ id: t.id,
154
+ path: t.path ?? "",
155
+ line: t.line ?? null,
156
+ author: t.comments?.nodes?.[0]?.author?.login ?? "",
157
+ resolved: Boolean(t.isResolved),
158
+ body: t.comments?.nodes?.[0]?.body ?? "",
159
+ }));
160
+ },
161
+
162
+ /** The paths a bundle's commits change, read as git objects alone; null when git refuses it. */
163
+ bundlePaths(bundle, baseSha) {
164
+ try {
165
+ return bundleChangedPaths({ git, bundle, baseSha }).paths;
166
+ } catch {
167
+ return null;
168
+ }
169
+ },
170
+
171
+ /**
172
+ * Pushes a bundle to the Attempt's branch, if its tip is the head the entry names.
173
+ * The bundle is fetched again here as git objects, so a push never trusts an earlier read.
174
+ */
175
+ push({ bundle, base, head, branch }) {
176
+ try {
177
+ bundleChangedPaths({ git, bundle, baseSha: base });
178
+ const tip = git(["rev-parse", "--verify", "refs/agent-factory/build^{commit}"]);
179
+ if (tip.status !== 0 || tip.stdout.trim() !== head) return false;
180
+ const pushed = ctx.git(
181
+ ["push", `https://github.com/${repo}.git`, `${head}:refs/heads/${branch}`],
182
+ { push: true },
183
+ );
184
+ return pushed.status === 0;
185
+ } catch {
186
+ return false;
187
+ }
188
+ },
189
+
190
+ openPull({ branch, base, title, body }) {
191
+ return json(
192
+ ["api", `repos/${repo}/pulls`, "--input", "-"],
193
+ JSON.stringify({ title, body, head: branch, base, draft: false }),
194
+ );
195
+ },
196
+
197
+ editPullBody(number, body) {
198
+ const dir = ctx.tmpDir ?? tmpdir();
199
+ const name = `agent-kit-pull-body-${number}.md`;
200
+ fs.writeFiles(dir, { [name]: body });
201
+ const result = gh([
202
+ "pr",
203
+ "edit",
204
+ String(number),
205
+ "--repo",
206
+ repo,
207
+ "--body-file",
208
+ join(dir, name),
209
+ ]);
210
+ fs.remove(join(dir, name));
211
+ if (result.status !== 0) throw new Error("gh pr edit failed");
212
+ },
213
+
214
+ reply({ pull, thread, text }) {
215
+ json([
216
+ "api",
217
+ "graphql",
218
+ "-f",
219
+ "query=mutation($thread: ID!, $body: String!) { addPullRequestReviewThreadReply(input: { pullRequestReviewThreadId: $thread, body: $body }) { comment { id } } }",
220
+ "-f",
221
+ `thread=${thread}`,
222
+ "-f",
223
+ `body=${text}`,
224
+ ]);
225
+ return pull;
226
+ },
227
+
228
+ postComment: (body) => tracker.postComment(issue, body),
229
+ };
230
+ }
@@ -0,0 +1,191 @@
1
+ // What the build Stage's trusted steps write on the issue, and what the sweep
2
+ // reads back (spec #500, Building). Pure: no IO. Contract suite:
3
+ // scripts/factory-build-notes.test.mjs.
4
+ //
5
+ // Two comments, both written as the engine and both tied to the Claim they
6
+ // answer by its nonce:
7
+ //
8
+ // <!-- factory:build-failed v=1 claim=<nonce> --> one failed Attempt
9
+ // <!-- factory:decision-request v=1 kind=wider-paths claim=<nonce> -->
10
+ // the builder needs wider paths
11
+ //
12
+ // The wider-paths request itself comes from the builder as data: the Stage's
13
+ // result is `{ title, body }`, so a builder that cannot finish inside the
14
+ // plan's Allowed paths ends with a title that starts `wider-paths:` and one
15
+ // fenced `agent-kit-wider-paths` block of JSON in the body, and commits
16
+ // nothing it cannot keep (an empty commit does, since a Stage with no commit
17
+ // fails before it has a result).
18
+
19
+ import { untrustedText } from "../checks/plan-header.mjs";
20
+ import { renderDecisionRequest } from "../decision/request.mjs";
21
+ import { VERSION_PATTERN, VERSION_TOKEN } from "../sweep/marker-version.mjs";
22
+
23
+ const BUILD_FAILURE_MARKER = new RegExp(
24
+ `^<!-- factory:build-failed${VERSION_PATTERN} claim=([A-Za-z0-9._:+-]+) -->`,
25
+ );
26
+ const WIDER_PATHS_MARKER = new RegExp(
27
+ `^<!-- factory:decision-request${VERSION_PATTERN} kind=wider-paths claim=([A-Za-z0-9._:+-]+) -->`,
28
+ );
29
+ const BUILD_QUESTIONS_MARKER = new RegExp(
30
+ `^<!-- factory:build-questions${VERSION_PATTERN} claim=([A-Za-z0-9._:+-]+) -->$`,
31
+ "m",
32
+ );
33
+ const REQUEST_START = new RegExp(`^<!-- factory:decision-request${VERSION_PATTERN} attempt=`);
34
+ const WIDER_PATHS_BLOCK = /^```agent-kit-wider-paths[ \t]*\n([\s\S]*?)\n```[ \t]*$/gm;
35
+
36
+ export const WIDER_PATHS_TITLE = /^\s*wider-paths:/i;
37
+ export const MAX_REQUEST_PATHS = 20;
38
+ export const REQUEST_PATH_CAP = 200;
39
+ export const REQUEST_REASON_CAP = 1500;
40
+
41
+ /** The failure note's text. `reasons` are kit words or already-cut paths. */
42
+ export function renderBuildFailure({ claim, attempt, reasons }) {
43
+ const lines = reasons
44
+ .slice(0, 20)
45
+ .map((r) => `- ${untrustedText(String(r).replace(/`/g, "'"), 240)}`);
46
+ return [
47
+ `<!-- factory:build-failed${VERSION_TOKEN} claim=${claim} -->`,
48
+ `The build Stage's attempt ${attempt} ended without a verified head, so nothing was merged forward and the task is built again. It counts as one failed Attempt.`,
49
+ "",
50
+ ...lines,
51
+ ].join("\n");
52
+ }
53
+
54
+ /** The failed-build note the engine wrote for `claim`, or null. */
55
+ export function buildFailureFor(comments, isEngine, claim) {
56
+ for (const comment of comments ?? []) {
57
+ if (!isEngine(comment.author)) continue;
58
+ const match = BUILD_FAILURE_MARKER.exec(String(comment.body ?? ""));
59
+ if (match && match[1] === claim) return { commentId: comment.id };
60
+ }
61
+ return null;
62
+ }
63
+
64
+ /** The wider-paths Decision Request the engine wrote for `claim`, or null. */
65
+ export function widerPathsRequestFor(comments, isEngine, claim) {
66
+ for (const comment of comments ?? []) {
67
+ if (!isEngine(comment.author)) continue;
68
+ const match = WIDER_PATHS_MARKER.exec(String(comment.body ?? ""));
69
+ if (match && match[1] === claim) return { commentId: comment.id };
70
+ }
71
+ return null;
72
+ }
73
+
74
+ const safeGlob = (p) =>
75
+ typeof p === "string" &&
76
+ p.length > 0 &&
77
+ p.length <= REQUEST_PATH_CAP &&
78
+ !p.startsWith("/") &&
79
+ !/[\\`\0-\x1f\x7f]/.test(p) &&
80
+ p.split("/").every((s) => s !== ".." && s !== ".");
81
+
82
+ /**
83
+ * The builder's request in its Stage result, or null when the result is not one.
84
+ * A result that claims to be one but cannot be read is `{ error }`.
85
+ * @param {{ title: string, body: string }} result
86
+ * @returns {null | { error: string } | { paths: string[], reason: string }}
87
+ */
88
+ export function parseWiderPathsRequest(result) {
89
+ if (!WIDER_PATHS_TITLE.test(String(result?.title ?? ""))) return null;
90
+ const blocks = [...String(result.body ?? "").matchAll(WIDER_PATHS_BLOCK)];
91
+ if (blocks.length !== 1) {
92
+ return { error: "the wider-paths request needs exactly one agent-kit-wider-paths block" };
93
+ }
94
+ let data;
95
+ try {
96
+ data = JSON.parse(blocks[0][1]);
97
+ } catch {
98
+ return { error: "the wider-paths block is not JSON" };
99
+ }
100
+ const keys = data && typeof data === "object" && !Array.isArray(data) ? Object.keys(data) : [];
101
+ if (keys.sort().join(",") !== "paths,reason") {
102
+ return { error: "the wider-paths block is one object with exactly paths and reason" };
103
+ }
104
+ if (
105
+ !Array.isArray(data.paths) ||
106
+ data.paths.length === 0 ||
107
+ data.paths.length > MAX_REQUEST_PATHS ||
108
+ !data.paths.every(safeGlob)
109
+ ) {
110
+ return {
111
+ error: `the wider-paths paths are one to ${MAX_REQUEST_PATHS} relative paths, with no .., backslash or backtick`,
112
+ };
113
+ }
114
+ if (typeof data.reason !== "string" || data.reason.trim() === "") {
115
+ return { error: "the wider-paths reason is empty" };
116
+ }
117
+ return {
118
+ paths: [...new Set(data.paths)],
119
+ reason: untrustedText(data.reason, REQUEST_REASON_CAP),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * The Decision Request the trusted step posts for a wider-paths ending. The
125
+ * paths and the reason are the builder's own words, shown as untrusted text.
126
+ */
127
+ export function renderWiderPathsRequest({ claim, attempt, currentPaths, request }) {
128
+ const list = (paths) => paths.map((p) => ` - \`${p}\``);
129
+ return [
130
+ `<!-- factory:decision-request${VERSION_TOKEN} kind=wider-paths claim=${claim} -->`,
131
+ "### Decision Request: widen the Allowed paths of this build?",
132
+ "",
133
+ `**Task:** build Stage, attempt ${attempt}. The builder could not finish inside the plan's Allowed paths and stopped; nothing was pushed.`,
134
+ "",
135
+ "**Q1.** Should the plan also allow these paths?",
136
+ "",
137
+ ...list(request.paths),
138
+ "",
139
+ "The plan's Allowed paths now:",
140
+ "",
141
+ ...list(currentPaths),
142
+ "",
143
+ "**Options:**",
144
+ "",
145
+ "1. Widen: ask for a new plan that lists the paths, then set the task back to `factory:planned`.",
146
+ "2. Keep the paths: close this task, or narrow the issue so the builder can finish inside them.",
147
+ "",
148
+ "**Recommendation:** decide from the builder's reason below; the Factory does not judge it.",
149
+ "",
150
+ "_The builder's reason, as it wrote it (untrusted):_",
151
+ "",
152
+ request.reason
153
+ .split("\n")
154
+ .map((l) => `> ${l}`)
155
+ .join("\n"),
156
+ ].join("\n");
157
+ }
158
+
159
+ /** The build Stage's `questions` Decision Request, written for `claim`, or null. */
160
+ export function buildQuestionsFor(comments, isEngine, claim) {
161
+ for (const comment of comments ?? []) {
162
+ if (!isEngine(comment.author)) continue;
163
+ const body = String(comment.body ?? "");
164
+ if (!REQUEST_START.test(body)) continue;
165
+ const match = BUILD_QUESTIONS_MARKER.exec(body);
166
+ if (match && match[1] === claim) return { commentId: comment.id };
167
+ }
168
+ return null;
169
+ }
170
+
171
+ /**
172
+ * The Decision Request a factory-mode Chief of Staff's `result: questions` ends the
173
+ * Stage with (ADR 0040): the standard request (`A<n>:` answers, read back by the plan
174
+ * Stage), tied to the Claim it answers so the sweep can release it `question`.
175
+ * @param {{ claim: string, attempt: number, plan: number, questions: Array<{ question: string, options: string[], recommendation: string, evidence: string }> }} input
176
+ */
177
+ export function renderBuildQuestions({ claim, attempt, plan, questions }) {
178
+ const request = renderDecisionRequest({
179
+ attempt,
180
+ plan,
181
+ kinds: ["questions"],
182
+ title: "the builder has questions it cannot rule on",
183
+ intro:
184
+ "The Chief of Staff building this task ended its Stage on these questions: none could be settled from evidence GitHub still shows. Nothing was merged forward. The task is planned again with your answers.",
185
+ questions,
186
+ });
187
+ const [first, ...rest] = request.split("\n");
188
+ return [first, `<!-- factory:build-questions${VERSION_TOKEN} claim=${claim} -->`, ...rest].join(
189
+ "\n",
190
+ );
191
+ }
@@ -0,0 +1,74 @@
1
+ // The build Stage's pull request (spec #500, Building), opened by the publish
2
+ // job's trusted step with the Consumer's App token: that is what starts CI
3
+ // without approval. The text is the kit's: `Closes #<issue>` leads, so the
4
+ // merge closes the task's issue, and the builder's own title and body follow as
5
+ // untrusted text, capped, with mentions, references and closing keywords of
6
+ // the builder's made inert. Pure text here; the opener below is the one call
7
+ // with the token. Contract suite: scripts/factory-build-pull-request.test.mjs.
8
+
9
+ import { renderRulingsBlock } from "../outbox/rulings.mjs";
10
+
11
+ export const PR_TITLE_CAP = 200;
12
+ export const PR_BODY_CAP = 20_000;
13
+
14
+ /**
15
+ * The agent's text made inert on GitHub: no mention notifies, no issue
16
+ * reference or closing keyword links or closes anything, and no HTML comment
17
+ * can pass for one of the kit's markers.
18
+ */
19
+ export function neutralisePullRequestText(text) {
20
+ const gap = "​";
21
+ return (
22
+ String(text)
23
+ .replace(/\r\n?/g, "\n")
24
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
25
+ // An entity would spell any of the characters below.
26
+ .replace(/&(?=#|commat;|num;)/gi, "&amp;")
27
+ .replace(/@(?=[A-Za-z0-9])/g, `@${gap}`)
28
+ .replace(/#(?=[0-9])/g, `#${gap}`)
29
+ .replace(/\b(GH-)(?=[0-9])/gi, `$1${gap}`)
30
+ .replace(/\/(issues|pull|discussions)\/(?=[0-9])/gi, `/$1/${gap}`)
31
+ .replace(/<!--/g, "&lt;!--")
32
+ );
33
+ }
34
+
35
+ const cappedText = (text, max) =>
36
+ text.length > max ? `${text.slice(0, max)}\n\n_(truncated by agent-kit)_` : text;
37
+
38
+ /**
39
+ * With the Orchestrate engine's factory mode, `rulings` are the Chief of Staff's
40
+ * checked Rulings: the engine renders them into a trusted block right after
41
+ * `Closes #<issue>`, and the builder's own text can never carry one (a `<!--`
42
+ * of its own is defused). The review Stage holds each Ruling against its evidence.
43
+ * @param {{ issue: number, result: { title: string, body: string }, rulings?: Array<object> }} input
44
+ * @returns {{ title: string, body: string }}
45
+ */
46
+ export function factoryPullRequestText({ issue, result, rulings = [] }) {
47
+ const block = renderRulingsBlock(rulings);
48
+ const line = neutralisePullRequestText(result.title)
49
+ .replace(/\s+/g, " ")
50
+ .trim()
51
+ .slice(0, PR_TITLE_CAP);
52
+ return {
53
+ title: line || `Build the verified plan for #${issue}`,
54
+ body: [
55
+ `Closes #${issue}`,
56
+ "",
57
+ ...(block ? [block, ""] : []),
58
+ "## Contract notes",
59
+ "",
60
+ "Written by agent-kit:",
61
+ "",
62
+ "- Opened by the Factory's build Stage, in a trusted job. The builder held no GitHub credential and pushed nothing.",
63
+ "- Its commits were validated before the push: no workflow file, local action or protected path, no merge, symbolic link or submodule, and every path inside the plan's Allowed paths.",
64
+ "- This pull request's CI is the build Stage's check. Review, QA and security come next, each as its own Stage.",
65
+ "",
66
+ "## The builder's description",
67
+ "",
68
+ "_Everything below is the builder's own text, not checked by agent-kit._",
69
+ "",
70
+ cappedText(neutralisePullRequestText(result.body), PR_BODY_CAP),
71
+ "",
72
+ ].join("\n"),
73
+ };
74
+ }
@@ -0,0 +1,146 @@
1
+ // Builds the Kit-owned bundle, `.github/agent-factory/sweep.mjs` (ADR 0043): the
2
+ // sweep's modules joined into one file, so the Workflow engine's dispatcher runs
3
+ // it from the Consumer's checkout with `node` and nothing else. It is a plain
4
+ // concatenation, not a bundler: no dependency and no build tool. It follows
5
+ // each module's relative imports from the entry, orders the modules so each
6
+ // comes after what it imports, drops those imports and the `export` keywords,
7
+ // and hoists the `node:` imports. It refuses what it cannot join safely: an
8
+ // aliased or non-relative, non-`node:` import, `export {}` and `export default`,
9
+ // and two modules that declare the same top-level name.
10
+ //
11
+ // node cli/src/factory/bundle.mjs write the bundle
12
+ // node cli/src/factory/bundle.mjs --check exit 1 if the bundle is stale
13
+ //
14
+ // scripts/factory-bundle.test.mjs holds the committed bundle equal to this
15
+ // output.
16
+
17
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { dirname, join, relative, resolve } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url));
22
+ export const REPO_ROOT = resolve(HERE, "../../..");
23
+ export const ENTRY = "cli/src/factory/sweep/actions-main.mjs";
24
+ export const BUNDLE_PATH = ".github/agent-factory/sweep.mjs";
25
+
26
+ const IMPORT = /^import\s+(?:([\s\S]*?)\s+from\s+)?"([^"]+)";[ \t]*\n/gm;
27
+ const DECLARATION =
28
+ /^(?:export\s+)?(?:async\s+)?(?:function\*?|const|let|class)\s+([A-Za-z_$][\w$]*)/gm;
29
+
30
+ /** The modules to join, dependencies first. `read(path)` returns a repo-relative file's text. */
31
+ export function moduleOrder(entry, read) {
32
+ const order = [];
33
+ const seen = new Set();
34
+ const visit = (path, via) => {
35
+ if (seen.has(path)) return;
36
+ seen.add(path);
37
+ const text = read(path);
38
+ if (text === null) throw new Error(`bundle: ${path} (imported by ${via}) does not exist`);
39
+ for (const m of text.matchAll(IMPORT)) {
40
+ const spec = m[2];
41
+ if (spec.startsWith("."))
42
+ visit(
43
+ relative(".", join(dirname(path), spec))
44
+ .split("\\")
45
+ .join("/"),
46
+ path,
47
+ );
48
+ }
49
+ order.push(path);
50
+ };
51
+ visit(entry, "the entry");
52
+ return order;
53
+ }
54
+
55
+ /** The bundle text for `entry`. */
56
+ export function buildBundle({ entry = ENTRY, read }) {
57
+ const order = moduleOrder(entry, read);
58
+ const hoisted = new Map(); // node: module -> Set of named imports, or null for a side-effect import
59
+ const declared = new Map(); // top-level name -> module
60
+ const parts = [];
61
+ for (const path of order) {
62
+ let text = read(path);
63
+ for (const m of text.matchAll(IMPORT)) {
64
+ const [, clause, spec] = m;
65
+ if (spec.startsWith(".")) {
66
+ if (clause && /\bas\b|\*/.test(clause)) {
67
+ throw new Error(
68
+ `bundle: ${path} imports ${spec} with an alias or a namespace, which cannot be joined`,
69
+ );
70
+ }
71
+ } else if (spec.startsWith("node:")) {
72
+ const names = hoisted.get(spec) ?? new Set();
73
+ const named = /^\{([\s\S]*)\}$/.exec((clause ?? "").trim());
74
+ if (!named) throw new Error(`bundle: ${path} imports ${spec} other than by name`);
75
+ for (const n of named[1]
76
+ .split(",")
77
+ .map((s) => s.trim())
78
+ .filter(Boolean)) {
79
+ if (/\bas\b/.test(n)) throw new Error(`bundle: ${path} aliases an import from ${spec}`);
80
+ names.add(n);
81
+ }
82
+ hoisted.set(spec, names);
83
+ } else {
84
+ throw new Error(
85
+ `bundle: ${path} imports ${JSON.stringify(spec)}: only relative and node: imports are allowed`,
86
+ );
87
+ }
88
+ }
89
+ text = text.replace(IMPORT, "");
90
+ if (/^export\s+(?:default|\*|\{)/m.test(text)) {
91
+ throw new Error(
92
+ `bundle: ${path} uses export default, export * or export {}; name each export`,
93
+ );
94
+ }
95
+ for (const m of text.matchAll(DECLARATION)) {
96
+ if (declared.has(m[1])) {
97
+ throw new Error(`bundle: ${path} and ${declared.get(m[1])} both declare ${m[1]}`);
98
+ }
99
+ declared.set(m[1], path);
100
+ }
101
+ text = text
102
+ .replace(/^export\s+/gm, "")
103
+ .replace(/\n{3,}/g, "\n\n")
104
+ .replace(/^\n+/, "")
105
+ .trimEnd();
106
+ parts.push(`// ---- ${path}\n${text}\n`);
107
+ }
108
+ const imports = [...hoisted]
109
+ .sort(([a], [b]) => a.localeCompare(b))
110
+ .map(
111
+ ([spec, names]) => `import { ${[...names].sort().join(", ")} } from ${JSON.stringify(spec)};`,
112
+ )
113
+ .join("\n");
114
+ return [
115
+ "// Kit-owned: the Factory sweep, bundled. Generated by cli/src/factory/bundle.mjs from",
116
+ `// ${order.join(", ")}.`,
117
+ "// Never edit this file: `agent-kit upgrade` replaces .github/agent-factory/ whole.",
118
+ "// Run by the factory-dispatcher workflow: node .github/agent-factory/sweep.mjs",
119
+ "",
120
+ imports,
121
+ "",
122
+ parts.join("\n"),
123
+ ].join("\n");
124
+ }
125
+
126
+ /** The bundle built from this checkout's files. */
127
+ export function buildFromCheckout(root = REPO_ROOT) {
128
+ return buildBundle({
129
+ read: (path) => (existsSync(join(root, path)) ? readFileSync(join(root, path), "utf8") : null),
130
+ });
131
+ }
132
+
133
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
134
+ const text = buildFromCheckout();
135
+ const target = join(REPO_ROOT, BUNDLE_PATH);
136
+ if (process.argv.includes("--check")) {
137
+ const current = existsSync(target) ? readFileSync(target, "utf8") : "";
138
+ if (current !== text) {
139
+ process.stderr.write(`${BUNDLE_PATH} is stale: run node cli/src/factory/bundle.mjs\n`);
140
+ process.exitCode = 1;
141
+ }
142
+ } else {
143
+ writeFileSync(target, text);
144
+ process.stdout.write(`wrote ${BUNDLE_PATH}\n`);
145
+ }
146
+ }
@@ -0,0 +1,50 @@
1
+ // The Allowed paths check (spec #500, Building; ADR 0005): a pure function. The
2
+ // build Stage's trusted step hands it the latest plan's Allowed paths and every
3
+ // path the build changed, and it says which changed paths fall outside. One
4
+ // outside path is a failed Attempt. Contract suite:
5
+ // scripts/factory-check-allowed-paths.test.mjs over
6
+ // scripts/fixtures/factory/allowed-paths/.
7
+ //
8
+ // An Allowed path is a glob, as the Plan header check and the risk rules read
9
+ // it: `*` and `?` stay inside one path segment, `**` crosses folders, matching
10
+ // is case-sensitive and `*` matches a dotfile. One with no wildcard may be a
11
+ // folder, so it also covers everything under it. A changed path that is
12
+ // absolute, holds `..`, an empty segment, a backslash or a control character
13
+ // is outside whatever matches it: nothing unsafe to check out is ever allowed.
14
+
15
+ import { pathMatchesGlob } from "../plan/risk.mjs";
16
+
17
+ const WILDCARD = /[*?]/;
18
+
19
+ const isSafePath = (path) =>
20
+ path !== "" &&
21
+ !path.startsWith("/") &&
22
+ // eslint-disable-next-line no-control-regex
23
+ !/[\\\u0000-\u001f\u007f]/.test(path) &&
24
+ path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
25
+
26
+ function covers(allowed, path) {
27
+ const glob = String(allowed).replace(/^\.\//, "").replace(/\/+$/, "");
28
+ if (glob === "") return false;
29
+ if (pathMatchesGlob(glob, path)) return true;
30
+ // A folder: a path with no wildcard covers what lies under it.
31
+ return !WILDCARD.test(glob) && path.startsWith(`${glob}/`);
32
+ }
33
+
34
+ /**
35
+ * @param {{ allowedPaths: string[], changedPaths: string[] }} input
36
+ * @returns {{ ok: boolean, outside: string[] }} `outside` lists each changed path once, in order
37
+ */
38
+ export function checkAllowedPaths({ allowedPaths, changedPaths }) {
39
+ const strings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
40
+ if (!strings(allowedPaths)) throw new Error("allowedPaths must be a list of strings");
41
+ if (!strings(changedPaths)) throw new Error("changedPaths must be a list of strings");
42
+ const outside = [];
43
+ for (const path of changedPaths) {
44
+ if (outside.includes(path)) continue;
45
+ if (!isSafePath(path) || !allowedPaths.some((allowed) => covers(allowed, path))) {
46
+ outside.push(path);
47
+ }
48
+ }
49
+ return { ok: outside.length === 0, outside };
50
+ }