@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,78 @@
1
+ // `max_running`, `max_attempts` and the Claim-expiry minutes of `limits` in the factory
2
+ // config (spec #500, Factory config), read from the default branch with the rest of the
3
+ // file (a Guarded path). Pure: the shell hands the text in. A key that is absent keeps the
4
+ // default. A key that is present but wrong keeps the default too, and says why in
5
+ // `problems` (the sweep logs each one as a notice): the defaults are the shipped values
6
+ // (3, 3, and the example's minutes), so a typo can never loosen a cap beyond them.
7
+ // A file that cannot be read, or is not a JSON object, keeps every default and says nothing
8
+ // here: the readers of `plan_approval`, `merge` and `budget` already say so.
9
+
10
+ import { LIMIT_MAX_MINUTES, LIMIT_STAGES, TASK_SIZES } from "../limits/limits.mjs";
11
+
12
+ const knobIsObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
13
+ const knobWhole = (v) => Number.isSafeInteger(v) && v >= 1;
14
+ // The same ceiling `stage-limits` holds a Stage's minutes to, so a Claim's expiry is a real date.
15
+ const knobMinutes = (v) => knobWhole(v) && v <= LIMIT_MAX_MINUTES;
16
+
17
+ /**
18
+ * @param {string | null | undefined | symbol} text the config file's text; null or undefined when it is missing
19
+ * @returns {{ value: { max_running?: number, max_attempts?: number, limits?: object }, problems: string[] }}
20
+ * `limits` holds only `{ minutes }` rows, by Stage (`build` by Task size `s|m|l`), and only
21
+ * those that are valid.
22
+ */
23
+ export function sweepKnobsFromConfig(text) {
24
+ const none = { value: {}, problems: [] };
25
+ if (text === null || text === undefined) return none;
26
+ if (typeof text !== "string") return none;
27
+ let data;
28
+ try {
29
+ data = JSON.parse(text);
30
+ } catch {
31
+ return none;
32
+ }
33
+ if (!knobIsObject(data)) return none;
34
+ const value = {};
35
+ const problems = [];
36
+ for (const key of ["max_running", "max_attempts"]) {
37
+ if (!(key in data)) continue;
38
+ if (knobWhole(data[key])) value[key] = data[key];
39
+ else problems.push(`${key} is ${JSON.stringify(data[key])}, not a whole number of 1 or more`);
40
+ }
41
+ if ("limits" in data) {
42
+ if (!knobIsObject(data.limits)) {
43
+ problems.push("limits is not an object");
44
+ } else {
45
+ const limits = {};
46
+ const minutesOf = (row, where) => {
47
+ if (!knobIsObject(row) || !("minutes" in row)) return undefined;
48
+ if (knobMinutes(row.minutes)) return { minutes: row.minutes };
49
+ problems.push(
50
+ `${where}.minutes is ${JSON.stringify(row.minutes)}, not a whole number of 1 to ${LIMIT_MAX_MINUTES}`,
51
+ );
52
+ return undefined;
53
+ };
54
+ for (const stage of LIMIT_STAGES) {
55
+ if (!(stage in data.limits)) continue;
56
+ if (stage !== "build") {
57
+ const row = minutesOf(data.limits[stage], `limits.${stage}`);
58
+ if (row) limits[stage] = row;
59
+ continue;
60
+ }
61
+ if (!knobIsObject(data.limits.build)) {
62
+ problems.push("limits.build is not an object");
63
+ continue;
64
+ }
65
+ const sizes = {};
66
+ for (const size of TASK_SIZES) {
67
+ const row = minutesOf(data.limits.build[size], `limits.build.${size}`);
68
+ if (row) sizes[size] = row;
69
+ }
70
+ if (Object.keys(sizes).length) limits.build = sizes;
71
+ else if (Object.keys(data.limits.build).length)
72
+ problems.push("limits.build has no row keyed s, m or l");
73
+ }
74
+ if (Object.keys(limits).length) value.limits = limits;
75
+ }
76
+ }
77
+ return { value, problems };
78
+ }
@@ -0,0 +1,15 @@
1
+ // The format version of every tracker marker the Factory writes (spec #500,
2
+ // Markers; docs/factory/markers.md). A marker names its version right after its
3
+ // own name, `<!-- factory:<name> v=1 ... -->`. The version this Kit writes is
4
+ // MARKER_VERSION. A marker with no `v` is the previous version, written before
5
+ // versions existed, and a reader reads it with the same fields, so an upgrade
6
+ // needs no drain: markers already on the tracker stay readable. A marker that
7
+ // names a version this reader does not know is not read at all, as no marker.
8
+
9
+ export const MARKER_VERSION = 1;
10
+
11
+ /** What a writer puts after the marker's name. */
12
+ export const VERSION_TOKEN = ` v=${MARKER_VERSION}`;
13
+
14
+ /** What a reader's pattern puts after the marker's name: this version or the previous one (none). */
15
+ export const VERSION_PATTERN = `(?: v=${MARKER_VERSION})?`;
@@ -0,0 +1,112 @@
1
+ // The Claim marker: one HTML comment in a comment body, written and read by the
2
+ // sweep alone. Versioned: `v=1` leads, and a marker without `v` is read as the
3
+ // previous (unversioned) form, which has the same fields. A reader that meets a
4
+ // version it does not know treats the comment as no Claim at all.
5
+ //
6
+ // <!-- factory:claim v=1 engine=<e> claim=<nonce> stage=<s> attempt=<n> run=<id> expires=<ISO> -->
7
+ //
8
+ // A release edits the marker in place, adding ` released=<reason>` before `-->`.
9
+
10
+ import { MARKER_VERSION, VERSION_TOKEN } from "./marker-version.mjs";
11
+
12
+ export const CLAIM_VERSION = MARKER_VERSION;
13
+
14
+ const VALUE = "[A-Za-z0-9._:+-]+";
15
+ const CLAIM = new RegExp(
16
+ `<!-- factory:claim(?: v=(${VALUE}))? engine=(${VALUE}) claim=(${VALUE}) stage=(${VALUE}) attempt=(${VALUE}) run=(${VALUE}) expires=(${VALUE})(?: released=(${VALUE}))? -->`,
17
+ );
18
+
19
+ /** Release reasons the sweep writes. Any other plain value is accepted when a release names it. */
20
+ export const RELEASE_REASONS = Object.freeze([
21
+ "done",
22
+ "expired",
23
+ "failed",
24
+ "error",
25
+ "lost-race",
26
+ "paused",
27
+ "stopped",
28
+ "engine-restart",
29
+ "question",
30
+ ]);
31
+
32
+ /**
33
+ * @typedef {{ engine: string, claim: string, stage: string, attempt: number, run: string, expires: string, released?: string }} Claim
34
+ */
35
+
36
+ function check(claim) {
37
+ for (const key of ["engine", "claim", "stage", "run", "expires"]) {
38
+ if (!new RegExp(`^${VALUE}$`).test(String(claim[key] ?? ""))) {
39
+ throw new Error(`claim ${key} is not a plain value: ${JSON.stringify(claim[key])}`);
40
+ }
41
+ }
42
+ if (!Number.isInteger(claim.attempt) || claim.attempt < 1) {
43
+ throw new Error(`claim attempt must be a positive integer, got ${claim.attempt}`);
44
+ }
45
+ }
46
+
47
+ /** The marker text for a Claim. */
48
+ export function renderClaimMarker(claim) {
49
+ check(claim);
50
+ const { engine, claim: nonce, stage, attempt, run, expires } = claim;
51
+ return `<!-- factory:claim v=${CLAIM_VERSION} engine=${engine} claim=${nonce} stage=${stage} attempt=${attempt} run=${run} expires=${expires} -->`;
52
+ }
53
+
54
+ /** The whole Claim comment: the marker, then one line for a person. */
55
+ export function renderClaimComment(claim) {
56
+ return `${renderClaimMarker(claim)}\nFactory claim: ${claim.stage} stage, attempt ${claim.attempt}, run ${claim.run}. Expires ${claim.expires}.`;
57
+ }
58
+
59
+ /**
60
+ * The Claim in a comment body, or null. Only the first marker counts, and only
61
+ * a version this reader knows.
62
+ * @returns {Claim | null}
63
+ */
64
+ export function parseClaim(body) {
65
+ const match = CLAIM.exec(String(body ?? ""));
66
+ if (!match) return null;
67
+ const [, version, engine, claim, stage, attempt, run, expires, released] = match;
68
+ if (version !== undefined && version !== String(CLAIM_VERSION)) return null;
69
+ if (!/^[1-9][0-9]*$/.test(attempt) || Number.isNaN(Date.parse(expires))) return null;
70
+ return {
71
+ engine,
72
+ claim,
73
+ stage,
74
+ attempt: Number(attempt),
75
+ run,
76
+ expires,
77
+ ...(released === undefined ? {} : { released }),
78
+ };
79
+ }
80
+
81
+ /** The comment body with its Claim released for `reason`; unchanged when it has none. */
82
+ export function releaseClaimBody(body, reason) {
83
+ if (!RELEASE_REASONS.includes(reason) && !new RegExp(`^${VALUE}$`).test(reason)) {
84
+ throw new Error(`release reason is not a plain value: ${JSON.stringify(reason)}`);
85
+ }
86
+ const claim = parseClaim(body);
87
+ if (!claim || claim.released !== undefined) return body;
88
+ // Edit the Claim marker itself, not the first ` -->` of the body.
89
+ return String(body).replace(CLAIM, (marker) =>
90
+ marker.replace(/ -->$/, ` released=${reason} -->`),
91
+ );
92
+ }
93
+
94
+ /** The marker of a plain note the sweep leaves, so it is not left twice. */
95
+ export const noteMarker = (reason) => `<!-- factory:note${VERSION_TOKEN} reason=${reason} -->`;
96
+
97
+ /** Whether a body holds the note for `reason`, of this version or the previous one (no `v`). */
98
+ export const hasNote = (body, reason) =>
99
+ [noteMarker(reason), noteMarker(reason).replace(VERSION_TOKEN, "")].some((m) =>
100
+ String(body ?? "").includes(m),
101
+ );
102
+
103
+ /**
104
+ * The body a voided Claim is rewritten to when the sweep releases it: the same
105
+ * marker, released, and a line saying why. Writing it makes the engine the
106
+ * comment's last editor again, so the void is not read twice.
107
+ */
108
+ export function renderVoidedClaim(claim, reason) {
109
+ check(claim);
110
+ const { engine, claim: nonce, stage, attempt, run, expires } = claim;
111
+ return `<!-- factory:claim v=${CLAIM_VERSION} engine=${engine} claim=${nonce} stage=${stage} attempt=${attempt} run=${run} expires=${expires} released=${reason} -->\nFactory claim voided: the comment was edited by someone other than its writer, so it counts as expired.`;
112
+ }
@@ -0,0 +1,24 @@
1
+ // Whether two tasks' Allowed paths can touch the same files (#507). The rule is
2
+ // conservative: it would rather make a task wait than let two builds collide, and
3
+ // the gate later measures the real diff. Two paths overlap when the literal part
4
+ // of one, the text before its first wildcard, is a prefix of the other's.
5
+
6
+ const PATH_WILDCARD = /[*?[\]{}]/;
7
+
8
+ /** The text of an Allowed path before its first wildcard character. */
9
+ export function literalPrefix(path) {
10
+ const at = String(path).search(PATH_WILDCARD);
11
+ return at === -1 ? String(path) : String(path).slice(0, at);
12
+ }
13
+
14
+ /** Whether two Allowed paths overlap. */
15
+ export function allowedPathsOverlap(a, b) {
16
+ const x = literalPrefix(a);
17
+ const y = literalPrefix(b);
18
+ return x.startsWith(y) || y.startsWith(x);
19
+ }
20
+
21
+ /** Whether any path of one task overlaps any path of the other. */
22
+ export function taskPathsOverlap(paths, others) {
23
+ return paths.some((p) => others.some((o) => allowedPathsOverlap(p, o)));
24
+ }
@@ -0,0 +1,198 @@
1
+ // One sweep from an environment: the module `agent-kit factory sweep` and the
2
+ // Workflow engine's bundle both call. It resolves the repository, the Kill
3
+ // switch and the clock, builds the GitHub tracker and the Workflow engine over
4
+ // the `gh` function it is given, and runs the shell once.
5
+
6
+ import { budgetFromConfig } from "../budget/budget.mjs";
7
+ import { planApprovalFromConfig, UNREADABLE } from "../decision/plan.mjs";
8
+ import { mergeFromConfig } from "../gate/config.mjs";
9
+ import { sweepKnobsFromConfig } from "./knobs.mjs";
10
+ import { TRIP_EVIDENCE_DAYS } from "../gate/trip-reads.mjs";
11
+ import { createWorkflowEngine, WORKFLOW_IDENTITY } from "../engine/workflow-engine.mjs";
12
+ import { readTracker } from "../report/reads.mjs";
13
+ import { DAY } from "../report/facts.mjs";
14
+ import { createGithubTracker } from "../tracker/github.mjs";
15
+ import { runSweep } from "./shell.mjs";
16
+
17
+ /** Where the factory config lives, read from the default branch. */
18
+ export const SWEEP_CONFIG_PATH = ".github/factory/config.json";
19
+
20
+ const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
21
+
22
+ /**
23
+ * @param {{
24
+ * gh: (args: string[]) => { status: number | null, stdout: string, stderr: string },
25
+ * env: Record<string, string | undefined>,
26
+ * repo?: string,
27
+ * identity?: string,
28
+ * dryRun?: boolean,
29
+ * clock?: () => number,
30
+ * nonce?: (issue: number, attempt: number) => string,
31
+ * tracker?: object,
32
+ * engine?: object,
33
+ * out: (line: string) => void,
34
+ * err: (line: string) => void,
35
+ * }} io
36
+ * @returns {number} exit code: 0 swept (or drained), 1 an action failed, 2 not runnable
37
+ */
38
+ export function runFromEnvironment({
39
+ gh,
40
+ env,
41
+ repo,
42
+ identity,
43
+ dryRun = false,
44
+ clock = Date.now,
45
+ nonce,
46
+ tracker: givenTracker,
47
+ engine: givenEngine,
48
+ out,
49
+ err,
50
+ }) {
51
+ const slug = repo ?? env.GITHUB_REPOSITORY;
52
+ if (!slug || !REPO.test(slug)) {
53
+ err(
54
+ `factory sweep: no repository (pass --repo owner/name or set GITHUB_REPOSITORY), got ${JSON.stringify(slug)}`,
55
+ );
56
+ return 2;
57
+ }
58
+ const tracker = givenTracker ?? createGithubTracker({ gh, repo: slug });
59
+ let ref;
60
+ // The Orchestrate engine host hands in its own engine (and its tracker over the PAT).
61
+ const engine =
62
+ givenEngine ??
63
+ createWorkflowEngine({
64
+ gh,
65
+ repo: slug,
66
+ ref: () => (ref ??= tracker.defaultBranch()),
67
+ identity: identity ?? env.AGENT_KIT_FACTORY_IDENTITY ?? WORKFLOW_IDENTITY,
68
+ });
69
+ // The factory config, from the default branch alone (a Guarded path). The sweep reads
70
+ // `plan_approval`, `merge`, `budget`, `max_running`, `max_attempts` and the `minutes` of
71
+ // `limits` from it. A file it cannot read holds every plan, and says so.
72
+ let configText = null;
73
+ const killOn = env.AGENT_KIT_FACTORY_ENABLED === "true";
74
+ if (killOn) {
75
+ try {
76
+ configText = tracker.readFile(SWEEP_CONFIG_PATH, tracker.defaultBranch());
77
+ } catch (error) {
78
+ out(`notice: ${SWEEP_CONFIG_PATH} could not be read (${error.message}): every plan is held`);
79
+ configText = UNREADABLE;
80
+ }
81
+ }
82
+ const approval = planApprovalFromConfig(configText);
83
+ if (approval.problem) out(`notice: ${approval.problem}: every plan is held for approval`);
84
+ // `merge` from the same file: `off` unless it says otherwise, and `off` when it cannot be read.
85
+ const merge = mergeFromConfig(configText);
86
+ if (merge.problem) out(`notice: ${merge.problem}: the merge gate stays off`);
87
+ // `budget` and `limits` from the same file, and the owner's override: the Daily cap.
88
+ const budget = budgetFromConfig(configText);
89
+ if (budget.problem)
90
+ out(`notice: ${budget.problem}: no new Claim until the Daily cap can be read`);
91
+ // `max_running`, `max_attempts` and the Claim-expiry minutes: a key that is wrong keeps its
92
+ // default, and says so.
93
+ const knobs = sweepKnobsFromConfig(configText);
94
+ for (const problem of knobs.problems) out(`notice: ${problem}: the default stands`);
95
+ const dailyOverride = killOn ? dailyOverrideOf({ gh, env, slug }) : undefined;
96
+ const run = env.GITHUB_RUN_ID ?? `local-${Math.floor(clock() / 1000)}`;
97
+ const { results } = runSweep({
98
+ tracker,
99
+ engine,
100
+ config: {
101
+ plan_approval: approval.value,
102
+ merge: merge.value,
103
+ budget: budget.value,
104
+ ...knobs.value,
105
+ daily_override: dailyOverride,
106
+ },
107
+ killSwitch: env.AGENT_KIT_FACTORY_ENABLED,
108
+ clock,
109
+ run,
110
+ nonce:
111
+ nonce ??
112
+ ((issue, attempt) => `${issue}-${attempt}-${globalThis.crypto.randomUUID().slice(0, 8)}`),
113
+ dryRun,
114
+ log: out,
115
+ // The evidence of a revert or a regression: the report's own read of the closed tasks.
116
+ readTripEvidence: () =>
117
+ readTracker({
118
+ gh,
119
+ repo: slug,
120
+ since: clock() - TRIP_EVIDENCE_DAYS * DAY,
121
+ env,
122
+ identity: engine.identity,
123
+ log: () => {},
124
+ }),
125
+ });
126
+ for (const { action, status, error } of results) {
127
+ if (action.type === "notice") continue;
128
+ out(
129
+ `${status}: ${action.type}${action.issue ? ` #${action.issue}` : ""}${describe(action)}${error ? ` (${error})` : ""}`,
130
+ );
131
+ }
132
+ const failed = results.filter((r) => r.status === "failed").length;
133
+ out(
134
+ `factory sweep: ${results.filter((r) => r.action.type !== "notice").length} actions, ${failed} failed`,
135
+ );
136
+ return failed ? 1 : 0;
137
+ }
138
+
139
+ function describe(action) {
140
+ switch (action.type) {
141
+ case "set-state":
142
+ return ` ${action.from} -> ${action.to}`;
143
+ case "start-stage":
144
+ return ` ${action.stage} attempt ${action.attempt}`;
145
+ case "cancel-stage":
146
+ return ` ${action.stage} claim ${action.claim}`;
147
+ case "post-decision-request":
148
+ return "";
149
+ case "gate-update":
150
+ case "gate-comment":
151
+ return ` pull #${action.pull}`;
152
+ case "merge":
153
+ return ` pull #${action.pull} at ${action.head.slice(0, 7)} (${action.method})`;
154
+ case "trip-marker":
155
+ return " (the merge gate tripped)";
156
+ case "budget-notice":
157
+ return ` (${action.threshold}% of the Daily cap)`;
158
+ case "copy-stage-checks":
159
+ return ` to ${action.head.slice(0, 7)} from ${action.from.slice(0, 7)}`;
160
+ case "claim":
161
+ return ` ${action.claim.stage} attempt ${action.claim.attempt}`;
162
+ case "revert-label":
163
+ return ` ${action.remove
164
+ .map((l) => `-${l}`)
165
+ .concat(action.add.map((l) => `+${l}`))
166
+ .join(" ")} (by ${action.actor})`;
167
+ case "remove-label":
168
+ return ` ${action.label}`;
169
+ case "split":
170
+ return ` into ${action.entries.length} sub-issues (plan ${action.plan})`;
171
+ case "close-parent":
172
+ return ` closes #${action.parent}`;
173
+ default:
174
+ return "";
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The owner's override of the Daily cap: `AGENT_KIT_FACTORY_DAILY_TOKENS` from the environment (the
180
+ * Workflow engine's dispatcher passes the repository variable in), else the repository variable
181
+ * itself (the Orchestrate engine and `factory sweep`, which have a token that may read it).
182
+ * A variable that is not there is no override; one that cannot be read is carried as text that is
183
+ * not a number, which stops new Claims rather than lets the config's larger cap stand.
184
+ */
185
+ function dailyOverrideOf({ gh, env, slug }) {
186
+ if (env.AGENT_KIT_FACTORY_DAILY_TOKENS !== undefined) return env.AGENT_KIT_FACTORY_DAILY_TOKENS;
187
+ const variable = gh(["api", `repos/${slug}/actions/variables/AGENT_KIT_FACTORY_DAILY_TOKENS`]);
188
+ if (variable.status === 0) {
189
+ try {
190
+ const value = JSON.parse(variable.stdout)?.value;
191
+ return typeof value === "string" ? value : undefined;
192
+ } catch {
193
+ return undefined;
194
+ }
195
+ }
196
+ if (/\b404\b|Not Found/i.test(String(variable.stderr))) return undefined;
197
+ return `unreadable: ${String(variable.stderr).trim().slice(0, 120)}`;
198
+ }