@mnaimfaizy/agent-kit 1.0.0-beta.15 → 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 (110) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +314 -4
  4. package/src/doctor.mjs +53 -1
  5. package/src/exec.mjs +14 -5
  6. package/src/factory/budget/budget.mjs +259 -0
  7. package/src/factory/build/command.mjs +321 -0
  8. package/src/factory/build/factory.mjs +473 -0
  9. package/src/factory/build/findings.mjs +55 -0
  10. package/src/factory/build/host.mjs +230 -0
  11. package/src/factory/build/notes.mjs +191 -0
  12. package/src/factory/build/pull-request.mjs +74 -0
  13. package/src/factory/bundle.mjs +146 -0
  14. package/src/factory/checks/allowed-paths.mjs +50 -0
  15. package/src/factory/checks/plan-header.mjs +296 -0
  16. package/src/factory/checks/qa.mjs +85 -0
  17. package/src/factory/checks/review.mjs +73 -0
  18. package/src/factory/checks/security.mjs +50 -0
  19. package/src/factory/checks/stage-check.mjs +89 -0
  20. package/src/factory/claims/command.mjs +187 -0
  21. package/src/factory/claims/release.mjs +111 -0
  22. package/src/factory/decision/answers.mjs +103 -0
  23. package/src/factory/decision/command.mjs +64 -0
  24. package/src/factory/decision/plan.mjs +99 -0
  25. package/src/factory/decision/request.mjs +116 -0
  26. package/src/factory/doctor/files.mjs +329 -0
  27. package/src/factory/doctor/index.mjs +56 -0
  28. package/src/factory/doctor/local.mjs +497 -0
  29. package/src/factory/doctor/orchestrate.mjs +146 -0
  30. package/src/factory/engine/lease.mjs +146 -0
  31. package/src/factory/engine/local-engine.mjs +177 -0
  32. package/src/factory/engine/lockfile.mjs +64 -0
  33. package/src/factory/engine/workflow-engine.mjs +124 -0
  34. package/src/factory/gate/comment.mjs +88 -0
  35. package/src/factory/gate/config.mjs +57 -0
  36. package/src/factory/gate/gate-core.mjs +250 -0
  37. package/src/factory/gate/guarded.mjs +17 -0
  38. package/src/factory/gate/reads.mjs +105 -0
  39. package/src/factory/gate/task.mjs +193 -0
  40. package/src/factory/gate/trip-reads.mjs +82 -0
  41. package/src/factory/gate/trip.mjs +87 -0
  42. package/src/factory/init/blueprint.mjs +174 -0
  43. package/src/factory/init/index.mjs +337 -0
  44. package/src/factory/labels/evidence.mjs +162 -0
  45. package/src/factory/labels/moves.mjs +32 -0
  46. package/src/factory/labels/reconcile.mjs +267 -0
  47. package/src/factory/labels/revert.mjs +87 -0
  48. package/src/factory/labels/timeline.mjs +72 -0
  49. package/src/factory/labels/voided.mjs +59 -0
  50. package/src/factory/limits/harness.mjs +39 -0
  51. package/src/factory/limits/limits.mjs +123 -0
  52. package/src/factory/merge/command.mjs +172 -0
  53. package/src/factory/outbox/check.mjs +240 -0
  54. package/src/factory/outbox/rulings.mjs +195 -0
  55. package/src/factory/plan/command.mjs +66 -0
  56. package/src/factory/plan/comment.mjs +156 -0
  57. package/src/factory/plan/publish.mjs +149 -0
  58. package/src/factory/plan/risk.mjs +153 -0
  59. package/src/factory/qa/command.mjs +163 -0
  60. package/src/factory/records/engine-record.mjs +133 -0
  61. package/src/factory/records/main.mjs +96 -0
  62. package/src/factory/records/record.mjs +226 -0
  63. package/src/factory/records/sink.mjs +57 -0
  64. package/src/factory/report/build.mjs +92 -0
  65. package/src/factory/report/command.mjs +80 -0
  66. package/src/factory/report/facts.mjs +226 -0
  67. package/src/factory/report/gate-section.mjs +122 -0
  68. package/src/factory/report/metrics.mjs +111 -0
  69. package/src/factory/report/reads.mjs +246 -0
  70. package/src/factory/report/render.mjs +121 -0
  71. package/src/factory/report/rollout.mjs +154 -0
  72. package/src/factory/review/command.mjs +182 -0
  73. package/src/factory/run/awake.mjs +70 -0
  74. package/src/factory/run/collect.mjs +77 -0
  75. package/src/factory/run/command.mjs +490 -0
  76. package/src/factory/run/gh.mjs +46 -0
  77. package/src/factory/run/launch.mjs +47 -0
  78. package/src/factory/run/pipelines.mjs +261 -0
  79. package/src/factory/run/raw.mjs +96 -0
  80. package/src/factory/run/restart.mjs +83 -0
  81. package/src/factory/run/s3.mjs +193 -0
  82. package/src/factory/run/secrets.mjs +142 -0
  83. package/src/factory/run/teardown.mjs +242 -0
  84. package/src/factory/run/token.mjs +68 -0
  85. package/src/factory/security/command.mjs +157 -0
  86. package/src/factory/setup/app.mjs +122 -0
  87. package/src/factory/setup/command.mjs +409 -0
  88. package/src/factory/setup/labels.mjs +25 -0
  89. package/src/factory/setup/reads.mjs +129 -0
  90. package/src/factory/setup/writes.mjs +126 -0
  91. package/src/factory/snapshot/write.mjs +176 -0
  92. package/src/factory/stop/command.mjs +136 -0
  93. package/src/factory/sweep/actions-main.mjs +117 -0
  94. package/src/factory/sweep/command.mjs +65 -0
  95. package/src/factory/sweep/knobs.mjs +78 -0
  96. package/src/factory/sweep/marker-version.mjs +15 -0
  97. package/src/factory/sweep/markers.mjs +112 -0
  98. package/src/factory/sweep/overlap.mjs +24 -0
  99. package/src/factory/sweep/run.mjs +198 -0
  100. package/src/factory/sweep/shell.mjs +394 -0
  101. package/src/factory/sweep/split.mjs +104 -0
  102. package/src/factory/sweep/states.mjs +87 -0
  103. package/src/factory/sweep/sweep-core.mjs +1781 -0
  104. package/src/factory/tracker/github.mjs +674 -0
  105. package/src/factory/tracker/operations.mjs +153 -0
  106. package/src/factory/upgrade/index.mjs +83 -0
  107. package/src/init.mjs +62 -24
  108. package/src/kit-owned-paths.mjs +1 -1
  109. package/src/stage.mjs +19 -0
  110. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,259 @@
1
+ // The Daily cap's arithmetic (#516, ADR 0042): pure functions, no IO, no clock.
2
+ // The sweep core (sweep/sweep-core.mjs) calls them; docs/factory/budget.md says
3
+ // the rules in prose. Tokens only, never money.
4
+ //
5
+ // effective cap = AGENT_KIT_FACTORY_DAILY_TOKENS (owner-only variable), else
6
+ // budget.daily_tokens of the factory config, else no cap
7
+ // spent today = tokens in the engine's release comments posted since 00:00
8
+ // UTC; a total that is missing, unknown or edited counts at
9
+ // the Stage's full cap, and so does a Claim written today that
10
+ // left no release comment
11
+ // reserved = the full cap of every Stage still running
12
+ // a Stage starts only if spent + reserved + its own cap <= the cap
13
+ //
14
+ // A value that cannot be read never loosens the cap: an invalid override, an
15
+ // invalid `budget` or `limits` value and an unreadable spend all stop new Claims.
16
+
17
+ import { DEFAULT_STAGE_LIMITS, TASK_SIZES } from "../limits/limits.mjs";
18
+ import { parseReleaseComment } from "../claims/release.mjs";
19
+
20
+ /** The two thresholds that post a notice on the Factory control issue, in percent. */
21
+ export const BUDGET_THRESHOLDS = Object.freeze([80, 100]);
22
+
23
+ /** The names a notice gives for where the effective cap came from. */
24
+ export const BUDGET_SOURCE_CONFIG = "budget.daily_tokens";
25
+ export const BUDGET_SOURCE_OVERRIDE = "AGENT_KIT_FACTORY_DAILY_TOKENS";
26
+
27
+ const BUDGET_DAY_MS = 86_400_000;
28
+ const BUDGET_WHOLE = /^[1-9][0-9]{0,14}$/;
29
+ const BUDGET_LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
30
+
31
+ const budgetIsObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
32
+
33
+ /** Midnight UTC that starts the day `ms` falls in. */
34
+ export const budgetDayStart = (ms) => Math.floor(ms / BUDGET_DAY_MS) * BUDGET_DAY_MS;
35
+
36
+ /** `YYYY-MM-DD`, the UTC day `ms` falls in. */
37
+ export const budgetDayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
38
+
39
+ /**
40
+ * `budget` and `limits` of the factory config's text, for the cap. `text` is
41
+ * null when the file is absent (no cap) and anything else that is not a string
42
+ * when the read failed (a `problem`, which stops new Claims).
43
+ * @returns {{ value: { daily_tokens?: number, notify: string[], limits?: object }, problem?: string }}
44
+ */
45
+ export function budgetFromConfig(text) {
46
+ const none = { value: { notify: [] } };
47
+ if (text === null || text === undefined) return none;
48
+ const stop = (problem) => ({ value: { notify: [], problem }, problem });
49
+ if (typeof text !== "string") return stop("the factory config could not be read");
50
+ // A file that is not a JSON object names no cap, and no Stage runs on it either:
51
+ // `stage-limits` refuses it (docs/factory/limits.md). Only a read that failed, and a
52
+ // `budget` or `limits` value that is wrong, stop new Claims.
53
+ let data;
54
+ try {
55
+ data = JSON.parse(text);
56
+ } catch {
57
+ return none;
58
+ }
59
+ if (!budgetIsObject(data)) return none;
60
+ const value = { notify: [] };
61
+ if ("limits" in data) {
62
+ if (!budgetIsObject(data.limits)) return stop("limits is not an object");
63
+ value.limits = data.limits;
64
+ }
65
+ if (!("budget" in data)) return { value };
66
+ const budget = data.budget;
67
+ if (!budgetIsObject(budget)) return stop("budget is not an object");
68
+ if ("daily_tokens" in budget) {
69
+ const n = budget.daily_tokens;
70
+ if (!Number.isSafeInteger(n) || n < 1) {
71
+ return stop("budget.daily_tokens must be a whole number of 1 or more");
72
+ }
73
+ value.daily_tokens = n;
74
+ }
75
+ if ("notify" in budget) {
76
+ const list = budget.notify;
77
+ const logins = Array.isArray(list) ? list.map((l) => String(l).replace(/^@/, "")) : [];
78
+ if (!Array.isArray(list) || !logins.every((l) => BUDGET_LOGIN.test(l))) {
79
+ return stop("budget.notify must be a list of GitHub logins");
80
+ }
81
+ value.notify = [...new Set(logins)];
82
+ }
83
+ return { value };
84
+ }
85
+
86
+ /**
87
+ * The effective Daily cap and where it came from. The override (the repository
88
+ * variable, set only by an owner or admin) wins over the config; an override
89
+ * that is not a whole number stops new Claims rather than fall back.
90
+ * @param {{ budget?: { daily_tokens?: number, notify?: string[], problem?: string }, override?: string }} input
91
+ * @returns {{ cap: number, source: string, notify: string[] } | { none: true } | { error: string }}
92
+ */
93
+ export function effectiveCap({ budget, override } = {}) {
94
+ const notify = budget?.notify ?? [];
95
+ // A config that cannot be read stops new Claims even under an override: its limits are
96
+ // what the reservation is made of.
97
+ if (budget?.problem) return { error: budget.problem };
98
+ if (override !== undefined && String(override).trim() !== "") {
99
+ const raw = String(override).trim();
100
+ if (!BUDGET_WHOLE.test(raw)) {
101
+ return {
102
+ error: `${BUDGET_SOURCE_OVERRIDE} is ${JSON.stringify(raw.slice(0, 40))}, not a whole number of tokens`,
103
+ };
104
+ }
105
+ return { cap: Number(raw), source: BUDGET_SOURCE_OVERRIDE, notify };
106
+ }
107
+ if (budget?.daily_tokens !== undefined) {
108
+ return { cap: budget.daily_tokens, source: BUDGET_SOURCE_CONFIG, notify };
109
+ }
110
+ return { none: true };
111
+ }
112
+
113
+ const wholeTokens = (v) => (Number.isSafeInteger(v) && v > 0 ? v : null);
114
+
115
+ /**
116
+ * A Stage's per-run token cap (`limits.<stage>.tokens`, the starting values
117
+ * where the config names none). For a build without a Task size, the largest
118
+ * size's cap. Null when the value cannot be read as a whole number.
119
+ */
120
+ export function budgetStageCap({ limits, stage, size }) {
121
+ const merged = { ...DEFAULT_STAGE_LIMITS, ...(budgetIsObject(limits) ? limits : {}) };
122
+ const row = merged[stage];
123
+ if (stage !== "build") return budgetIsObject(row) ? wholeTokens(row.tokens) : null;
124
+ if (!budgetIsObject(row)) return null;
125
+ if (TASK_SIZES.includes(size)) {
126
+ return budgetIsObject(row[size]) ? wholeTokens(row[size].tokens) : null;
127
+ }
128
+ const all = TASK_SIZES.map((s) => (budgetIsObject(row[s]) ? wholeTokens(row[s].tokens) : null));
129
+ return all.some((n) => n === null) ? null : Math.max(...all);
130
+ }
131
+
132
+ /**
133
+ * The release comments posted today by the engine, one per Stage run (its
134
+ * Claim nonce): `Map<"stage:claim", { stage, claim, issue, tokens, counted }>`.
135
+ * `tokens` is a whole number, or `"unknown"` when the total is missing, malformed
136
+ * or edited after it was written (an edit is anything that moved the comment's
137
+ * `updatedAt` past its `createdAt`, or names an `editor`). A second comment for
138
+ * the same run keeps the worse total.
139
+ * @param {{ comments: Array<{ issue?: number, author: string, body: string, createdAt: string, updatedAt?: string, editor?: string | null }>, isEngine: (login: string) => boolean, nowMs: number }} input
140
+ */
141
+ export function todaysReleases({ comments, isEngine, nowMs }) {
142
+ const start = budgetDayStart(nowMs);
143
+ const out = new Map();
144
+ for (const comment of comments ?? []) {
145
+ if (!isEngine(comment.author)) continue;
146
+ const release = parseReleaseComment(comment.body);
147
+ if (!release) continue;
148
+ const at = Date.parse(comment.createdAt);
149
+ if (!Number.isFinite(at) || at < start || at >= start + BUDGET_DAY_MS) continue;
150
+ const edited =
151
+ Boolean(comment.editor) ||
152
+ (comment.updatedAt !== undefined && Date.parse(comment.updatedAt) !== at);
153
+ const tokens = edited ? "unknown" : release.tokens;
154
+ const key = `${release.stage}:${release.claim}`;
155
+ const before = out.get(key);
156
+ const worse =
157
+ before === undefined
158
+ ? tokens
159
+ : before.tokens === "unknown" || tokens === "unknown"
160
+ ? "unknown"
161
+ : Math.max(before.tokens, tokens);
162
+ out.set(key, {
163
+ stage: release.stage,
164
+ claim: release.claim,
165
+ issue: comment.issue ?? before?.issue,
166
+ tokens: worse,
167
+ });
168
+ }
169
+ return out;
170
+ }
171
+
172
+ /**
173
+ * Tokens spent today: each release's total, or the Stage's full cap where the
174
+ * total is unknown, plus the full cap of each Stage run that left no release.
175
+ * @param {{ releases: Map<string, { stage: string, issue?: number, tokens: number | "unknown" }>, missing: Array<{ stage: string, issue?: number }>, capFor: (stage: string, issue?: number) => number | null }} input
176
+ * @returns {{ spent: number } | { error: string }}
177
+ */
178
+ export function tokensSpent({ releases, missing, capFor }) {
179
+ let spent = 0;
180
+ const full = capFor;
181
+ for (const release of releases.values()) {
182
+ if (release.tokens === "unknown") {
183
+ const cap = full(release.stage, release.issue);
184
+ if (cap === null) return { error: `the ${release.stage} Stage's token cap is not readable` };
185
+ spent += cap;
186
+ } else {
187
+ spent += release.tokens;
188
+ }
189
+ }
190
+ for (const run of missing) {
191
+ const cap = full(run.stage, run.issue);
192
+ if (cap === null) return { error: `the ${run.stage} Stage's token cap is not readable` };
193
+ spent += cap;
194
+ }
195
+ return { spent };
196
+ }
197
+
198
+ /** A Stage may start only if what is spent, what is reserved and its own cap fit the cap. */
199
+ export const budgetFits = ({ cap, spent, reserved, own }) => spent + reserved + own <= cap;
200
+
201
+ /** The whole percent of the cap that is spent (rounded down; the cap is never zero). */
202
+ export const budgetPercent = ({ cap, spent }) => Math.floor((spent * 100) / cap);
203
+
204
+ /** The notice marker, and its reader. One comment per threshold per UTC day. */
205
+ export const budgetNoticeMarker = ({ day, threshold }) =>
206
+ `<!-- factory:budget-notice v=1 day=${day} threshold=${threshold} -->`;
207
+
208
+ const NOTICE_MARKER =
209
+ /^<!-- factory:budget-notice v=1 day=(\d{4}-\d{2}-\d{2}) threshold=(80|100) -->/;
210
+
211
+ export function parseBudgetNotice(body) {
212
+ const match = NOTICE_MARKER.exec(String(body ?? ""));
213
+ return match ? { day: match[1], threshold: Number(match[2]) } : null;
214
+ }
215
+
216
+ /**
217
+ * The threshold to post a notice for now, or null. The highest one crossed that
218
+ * the control issue's engine comments do not already show for today; once the
219
+ * 100% notice stands, the 80% one is never posted late. A notice someone else
220
+ * edited does not count (it is evidence the engine did not write last).
221
+ * @param {{ cap: number, spent: number, nowMs: number, comments: Array<{ author: string, body: string, editor?: string | null }>, isEngine: (login: string) => boolean }} input
222
+ */
223
+ export function noticeDue({ cap, spent, nowMs, comments, isEngine }) {
224
+ const day = budgetDayOf(nowMs);
225
+ const percent = budgetPercent({ cap, spent });
226
+ const posted = new Set(
227
+ (comments ?? [])
228
+ .filter((c) => isEngine(c.author) && (!c.editor || isEngine(c.editor)))
229
+ .map((c) => parseBudgetNotice(c.body))
230
+ .filter((n) => n?.day === day)
231
+ .map((n) => n.threshold),
232
+ );
233
+ const crossed = BUDGET_THRESHOLDS.filter((t) => percent >= t);
234
+ const top = crossed.at(-1);
235
+ if (top === undefined) return null;
236
+ return BUDGET_THRESHOLDS.some((t) => t >= top && posted.has(t)) ? null : top;
237
+ }
238
+
239
+ /** The comment for one threshold: names the cap and its source, mentions `budget.notify`. */
240
+ export function renderBudgetNotice({ nowMs, threshold, cap, spent, source, notify }) {
241
+ const day = budgetDayOf(nowMs);
242
+ const who = notify.length
243
+ ? notify.map((l) => `@${l}`).join(" ")
244
+ : "(nobody is listed in `budget.notify`)";
245
+ const where =
246
+ source === BUDGET_SOURCE_OVERRIDE
247
+ ? "the repository variable `AGENT_KIT_FACTORY_DAILY_TOKENS`"
248
+ : "`budget.daily_tokens` in the factory config";
249
+ const what =
250
+ threshold >= 100
251
+ ? "The Daily cap is reached: the Factory takes no new Claims until 00:00 UTC. Running Stages finish and merges go on."
252
+ : "The Factory takes no new Claim once the cap is reached, and starts again at 00:00 UTC.";
253
+ return [
254
+ budgetNoticeMarker({ day, threshold }),
255
+ `Factory Daily cap: ${threshold}% reached on ${day} (UTC). ${spent} of ${cap} tokens are spent today. The cap is ${cap} tokens, set by ${where}.`,
256
+ what,
257
+ who,
258
+ ].join("\n");
259
+ }
@@ -0,0 +1,321 @@
1
+ // The build Stage's trusted steps, as commands of the Kit-owned bundle
2
+ // (`node .github/agent-factory/sweep.mjs <command>`), run by
3
+ // agent-implement-reusable.yml when its `factory` input is on. Each is the
4
+ // argument parsing and the tracker around pure code, with the process boundary
5
+ // (`gh`, `git`, files) handed in, so a test drives them over fakes
6
+ // (scripts/factory-build-command.test.mjs).
7
+ //
8
+ // build-plan --issue <n> --plan-out <file> --paths-out <file>
9
+ // writes the latest plan comment and its Allowed paths for the
10
+ // builder's brief. No valid plan: exit 1.
11
+ // build-check --issue <n> --claim <nonce> --attempt <n> --allowed-paths <file>
12
+ // --bundle <file> --result <file> --base-sha <sha>
13
+ // runs in the publish job after the builder, before any token
14
+ // exists or anything is pushed. It reads the bundle as git
15
+ // objects (never a checkout), refuses a diff outside the plan's
16
+ // Allowed paths as one failed Attempt, and turns a wider-paths
17
+ // result into a Decision Request. It reads and writes no GitHub
18
+ // state: it prints `ending=ok|wider-paths|failed` and `note=`
19
+ // (the comment for the report job to post, base64) to
20
+ // GITHUB_OUTPUT. Exit 0 for ok and wider-paths, 1 for failed.
21
+ // build-pr --issue <n> --base-branch <b> --branch <name> --sha <sha> --result <file>
22
+ // runs in the publish job, after the push, with the App's token as
23
+ // GH_TOKEN: opens the pull request that closes the issue (the one
24
+ // call whose token starts CI). Prints `number=` and `url=`.
25
+ // Exit 2 is a usage error. Nothing the agent wrote reaches a log. Only build-pr
26
+ // is run with the App's token, and it writes no comment: the notes are posted
27
+ // by the report job, with the job's `GITHUB_TOKEN`.
28
+
29
+ import { earlierFindings } from "./findings.mjs";
30
+ import { createHash } from "node:crypto";
31
+
32
+ import { checkAllowedPaths } from "../checks/allowed-paths.mjs";
33
+ import { checkPlanHeader } from "../checks/plan-header.mjs";
34
+ import { WORKFLOW_IDENTITY } from "../engine/workflow-engine.mjs";
35
+ import { latestPlan } from "../plan/comment.mjs";
36
+ import { createGithubTracker } from "../tracker/github.mjs";
37
+ import { factoryPullRequestText } from "./pull-request.mjs";
38
+ import { parseWiderPathsRequest, renderBuildFailure, renderWiderPathsRequest } from "./notes.mjs";
39
+
40
+ const BUILD_REPO_SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
41
+ const BUILD_FULL_SHA = /^[0-9a-f]{40}$/;
42
+ /** The most commits the check reads; the publish step holds the bundle to fewer. */
43
+ const MAX_COMMITS = 200;
44
+ const MAX_LISTED_PATHS = 15;
45
+
46
+ const bareLogin = (login) =>
47
+ String(login ?? "")
48
+ .replace(/\[bot\]$/, "")
49
+ .toLowerCase();
50
+
51
+ /** Reads one `--name value` option. */
52
+ const optionReader = (args) => (name) => {
53
+ const at = args.indexOf(`--${name}`);
54
+ return at === -1 ? undefined : args[at + 1];
55
+ };
56
+
57
+ function stepContext({ gh, env, args, tracker, err, need }) {
58
+ const option = optionReader(args);
59
+ const repo = env.GITHUB_REPOSITORY ?? "";
60
+ if (!BUILD_REPO_SLUG.test(repo)) return { usage: "GITHUB_REPOSITORY is not set" };
61
+ const issue = Number(option("issue"));
62
+ if (!Number.isInteger(issue) || issue < 1) return { usage: "--issue is not an issue number" };
63
+ for (const name of need) {
64
+ if (!option(name)) return { usage: `--${name} is missing` };
65
+ }
66
+ const identity = env.AGENT_KIT_FACTORY_IDENTITY ?? WORKFLOW_IDENTITY;
67
+ return {
68
+ option,
69
+ issue,
70
+ tracker: tracker ?? createGithubTracker({ gh, repo }),
71
+ isEngine: (login) => bareLogin(login) === bareLogin(identity),
72
+ err,
73
+ };
74
+ }
75
+
76
+ /** The latest valid plan on the issue: its comment body and its checked header, or null. */
77
+ function readPlan(tracker, issue, isEngine) {
78
+ const comments = tracker.readComments(issue);
79
+ const plan = latestPlan(comments, isEngine);
80
+ if (!plan) return { comments, plan: null };
81
+ const checked = checkPlanHeader(plan.data, { trusted: true });
82
+ if (!checked.ok) return { comments, plan: null };
83
+ const body = comments.find((c) => String(c.id) === String(plan.commentId))?.body ?? "";
84
+ return { comments, plan: { n: plan.n, body, header: checked.header } };
85
+ }
86
+
87
+ export function runBuildPlan({ gh, env, args, writeFile, out, err, tracker }) {
88
+ const c = stepContext({ gh, env, args, tracker, err, need: ["plan-out", "paths-out"] });
89
+ if (c.usage) {
90
+ err(`build-plan: ${c.usage}`);
91
+ return 2;
92
+ }
93
+ try {
94
+ const { plan, comments } = readPlan(c.tracker, c.issue, c.isEngine);
95
+ if (!plan) {
96
+ err("::error title=No verified plan::The issue has no valid plan comment of the engine's.");
97
+ return 1;
98
+ }
99
+ // The earlier Attempts' findings follow the plan, so the next builder reads them.
100
+ const findings = earlierFindings(comments, c.isEngine);
101
+ writeFile(c.option("plan-out"), `${plan.body}\n${findings ? `\n${findings}` : ""}`);
102
+ writeFile(c.option("paths-out"), `${plan.header.allowed_paths.join("\n")}\n`);
103
+ out(`Plan ${plan.n}: ${plan.header.allowed_paths.length} Allowed path(s).`);
104
+ return 0;
105
+ } catch (error) {
106
+ err(`::error title=Plan not read::${String(error.message).replace(/\s+/g, " ")}`);
107
+ return 1;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The paths a bundle changes on top of `baseSha`, read as git objects alone:
113
+ * every commit's paths, renames off, so a rename lists both ends.
114
+ * @returns {{ paths: string[], commits: number }}
115
+ */
116
+ export function bundleChangedPaths({ git, bundle, baseSha }) {
117
+ const run = (args) => {
118
+ const result = git(args);
119
+ if (result.status !== 0) throw new Error("git refused the bundle");
120
+ return result.stdout;
121
+ };
122
+ run(["cat-file", "-e", `${baseSha}^{commit}`]);
123
+ // fsck on the way in, with the tree-entry checks that default to warnings
124
+ // raised to errors, as the publish step's own fetch does.
125
+ run([
126
+ "-c",
127
+ "fetch.fsckObjects=true",
128
+ "-c",
129
+ "transfer.fsckObjects=true",
130
+ ...["hasDotgit", "hasDot", "hasDotdot", "zeroPaddedFilemode"].flatMap((id) => [
131
+ "-c",
132
+ `fetch.fsck.${id}=error`,
133
+ ]),
134
+ "fetch",
135
+ "--quiet",
136
+ "--no-tags",
137
+ "--no-recurse-submodules",
138
+ "--no-auto-maintenance",
139
+ "--no-write-fetch-head",
140
+ bundle,
141
+ "+HEAD:refs/agent-factory/build",
142
+ ]);
143
+ const tip = run(["rev-parse", "--verify", "refs/agent-factory/build^{commit}"]).trim();
144
+ if (tip === baseSha) throw new Error("the bundle holds no new commit");
145
+ const commits = run(["rev-list", "--reverse", `${baseSha}..${tip}`])
146
+ .split("\n")
147
+ .filter(Boolean);
148
+ if (commits.length === 0 || commits.length > MAX_COMMITS) {
149
+ throw new Error(`the bundle holds ${commits.length} commits`);
150
+ }
151
+ const seen = new Set();
152
+ for (const sha of commits) {
153
+ const names = run([
154
+ "diff-tree",
155
+ "-r",
156
+ "-z",
157
+ "--no-renames",
158
+ "--no-commit-id",
159
+ "--root",
160
+ "--name-only",
161
+ sha,
162
+ ]);
163
+ for (const path of names.split("\0")) if (path !== "") seen.add(path);
164
+ }
165
+ return { paths: [...seen], commits: commits.length };
166
+ }
167
+
168
+ export function runBuildCheck({ git, env, args, readFile, appendOutput, out, err }) {
169
+ const option = optionReader(args);
170
+ const issue = option("issue") ?? "";
171
+ const claim = option("claim") ?? "";
172
+ const attempt = Number(option("attempt"));
173
+ const baseSha = option("base-sha") ?? "";
174
+ for (const name of ["allowed-paths", "bundle", "result"]) {
175
+ if (!option(name)) {
176
+ err(`build-check: --${name} is missing`);
177
+ return 2;
178
+ }
179
+ }
180
+ if (!/^[1-9][0-9]*$/.test(issue) || !/^[A-Za-z0-9._:+-]+$/.test(claim)) {
181
+ err("build-check: --issue or --claim is not valid");
182
+ return 2;
183
+ }
184
+ if (!Number.isInteger(attempt) || attempt < 1 || !BUILD_FULL_SHA.test(baseSha)) {
185
+ err("build-check: --attempt or --base-sha is not valid");
186
+ return 2;
187
+ }
188
+ // The ending, and the comment the report job posts for it (base64, one line).
189
+ const end = (ending, note) => {
190
+ appendOutput(`ending=${ending}`);
191
+ if (note) appendOutput(`note=${Buffer.from(note, "utf8").toString("base64")}`);
192
+ };
193
+ const fail = (reasons) => {
194
+ err(`::error title=Build refused::${reasons[0]}`);
195
+ end("failed", renderBuildFailure({ claim, attempt, reasons }));
196
+ return 1;
197
+ };
198
+ try {
199
+ const rawPaths = readFile(option("allowed-paths"));
200
+ const allowed = rawPaths
201
+ ? Buffer.from(rawPaths)
202
+ .toString("utf8")
203
+ .split("\n")
204
+ .map((line) => line.trim())
205
+ .filter(Boolean)
206
+ : [];
207
+ if (allowed.length === 0) return fail(["the plan's Allowed paths are missing"]);
208
+
209
+ const rawResult = readFile(option("result"));
210
+ let result;
211
+ try {
212
+ result = rawResult ? JSON.parse(Buffer.from(rawResult).toString("utf8")) : null;
213
+ } catch {
214
+ result = null;
215
+ }
216
+ if (!result || typeof result.title !== "string" || typeof result.body !== "string") {
217
+ return fail(["the implementer's result is missing or not a title and a body"]);
218
+ }
219
+
220
+ const request = parseWiderPathsRequest(result);
221
+ if (request?.error) return fail([request.error]);
222
+ if (request) {
223
+ out(`The builder asked for ${request.paths.length} wider path(s): nothing is pushed.`);
224
+ end(
225
+ "wider-paths",
226
+ renderWiderPathsRequest({ claim, attempt, currentPaths: allowed, request }),
227
+ );
228
+ return 0;
229
+ }
230
+
231
+ if (!readFile(option("bundle"))) return fail(["the implementer left no bundle"]);
232
+ let changed;
233
+ try {
234
+ changed = bundleChangedPaths({ git, bundle: option("bundle"), baseSha });
235
+ } catch (error) {
236
+ // git's own errors can quote the bundle; the kit's reasons do not.
237
+ const own = /^the bundle holds|no new commit/.test(error.message);
238
+ return fail([own ? error.message : "the bundle could not be read as git objects"]);
239
+ }
240
+ if (changed.paths.length === 0) {
241
+ return fail(["the build changed no file, so there is nothing to open a pull request for"]);
242
+ }
243
+ const verdict = checkAllowedPaths({ allowedPaths: allowed, changedPaths: changed.paths });
244
+ if (!verdict.ok) {
245
+ const shown = verdict.outside.slice(0, MAX_LISTED_PATHS);
246
+ const more = verdict.outside.length - shown.length;
247
+ return fail([
248
+ `the diff changes ${verdict.outside.length} path(s) outside the plan's Allowed paths:`,
249
+ ...shown,
250
+ ...(more > 0 ? [`and ${more} more`] : []),
251
+ ]);
252
+ }
253
+ out(`The diff of ${changed.commits} commit(s) stays inside the plan's Allowed paths.`);
254
+ end("ok");
255
+ return 0;
256
+ } catch (error) {
257
+ err(`::error title=Build check failed::${String(error.message).replace(/\s+/g, " ")}`);
258
+ end(
259
+ "failed",
260
+ renderBuildFailure({ claim, attempt, reasons: ["the build could not be checked"] }),
261
+ );
262
+ return 1;
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Opens the build's pull request, or finds the one already open for the branch.
268
+ * `gh` carries the App's token in its environment (the step's GH_TOKEN).
269
+ */
270
+ export function runBuildPr({ gh, env, args, readFile, appendOutput, out, err }) {
271
+ const option = optionReader(args);
272
+ const repo = env.GITHUB_REPOSITORY ?? "";
273
+ const issue = option("issue") ?? "";
274
+ const branch = option("branch") ?? "";
275
+ const base = option("base-branch") ?? "";
276
+ const sha = option("sha") ?? "";
277
+ if (!BUILD_REPO_SLUG.test(repo) || !/^[1-9][0-9]*$/.test(issue) || !branch || !base) {
278
+ err("build-pr: needs GITHUB_REPOSITORY, --issue, --branch and --base-branch");
279
+ return 2;
280
+ }
281
+ if (!BUILD_FULL_SHA.test(sha)) {
282
+ err("build-pr: --sha is not a full sha");
283
+ return 2;
284
+ }
285
+ const json = (callArgs, input) => {
286
+ const result = gh(callArgs, input);
287
+ if (result.status !== 0) {
288
+ throw new Error(`gh ${callArgs.slice(0, 3).join(" ")} failed`);
289
+ }
290
+ return JSON.parse(result.stdout || "null");
291
+ };
292
+ try {
293
+ const raw = readFile(option("result") ?? "");
294
+ const result = raw ? JSON.parse(Buffer.from(raw).toString("utf8")) : null;
295
+ if (!result || typeof result.title !== "string" || typeof result.body !== "string") {
296
+ throw new Error("the implementer's result is not a title and a body");
297
+ }
298
+ const encoded = branch.split("/").map(encodeURIComponent).join("/");
299
+ const ref = json(["api", `repos/${repo}/git/ref/heads/${encoded}`]);
300
+ if (ref?.object?.sha !== sha) throw new Error("the branch moved after it was pushed");
301
+ const head = encodeURIComponent(`${repo.split("/")[0]}:${branch}`);
302
+ const [existing] = json(["api", `repos/${repo}/pulls?state=open&head=${head}`]) ?? [];
303
+ let pull = existing;
304
+ if (!pull) {
305
+ const text = factoryPullRequestText({ issue: Number(issue), result });
306
+ pull = json(
307
+ ["api", `repos/${repo}/pulls`, "--input", "-"],
308
+ JSON.stringify({ ...text, head: branch, base, draft: false }),
309
+ );
310
+ }
311
+ out(`The pull request: ${pull.html_url}`);
312
+ appendOutput(`number=${pull.number}`);
313
+ appendOutput(`url=${pull.html_url}`);
314
+ return 0;
315
+ } catch (error) {
316
+ err(
317
+ `::error title=Pull request not opened::${String(error.message).replace(/\s+/g, " ")}. The branch is pushed; the Dispatcher counts this Attempt.`,
318
+ );
319
+ return 1;
320
+ }
321
+ }