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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,146 @@
1
+ // The Engine lease (spec #500, ADR 0039): one engine sweeps a repository. It is a
2
+ // comment on the Factory control issue,
3
+ //
4
+ // <!-- factory:engine v=1 id=<uuid> host=<name> expires=<ISO> [released=1] -->
5
+ //
6
+ // written when `factory run` starts, read back like a Claim (the oldest live lease
7
+ // wins), renewed every sweep and let go at teardown. A lease that is not renewed
8
+ // expires after LEASE_MISSED_SWEEPS sweeps, so a crashed engine does not hold the
9
+ // repository for ever. Labels have no compare-and-swap; this stands in for the
10
+ // Workflow engine's concurrency group. A pure reader plus three operations over a
11
+ // tracker (`readControl`, `postComment`, `editComment`).
12
+ //
13
+ // A lease counts only when its comment's author is the engine's own identity (the login
14
+ // the engine posts as), as a Claim does and as the gate's trip marker does: anyone who can
15
+ // comment on the control issue could otherwise plant a live lease and make every engine
16
+ // refuse. The operations take that `identity`.
17
+
18
+ import { VERSION_PATTERN, VERSION_TOKEN } from "../sweep/marker-version.mjs";
19
+
20
+ /** A lease expires after this many sweeps without a renewal. */
21
+ export const LEASE_MISSED_SWEEPS = 5;
22
+
23
+ const VALUE = "[A-Za-z0-9._:+-]+";
24
+ const LEASE = new RegExp(
25
+ `<!-- factory:engine${VERSION_PATTERN} id=(${VALUE}) host=(${VALUE}) expires=(${VALUE})( released=1)? -->`,
26
+ );
27
+
28
+ /** The host name as it can sit in the marker: anything else becomes `-`. */
29
+ export const plainHost = (host) =>
30
+ String(host ?? "").replace(/[^A-Za-z0-9._:+-]/g, "-") || "unknown";
31
+
32
+ /** The lease comment for an engine. */
33
+ export function renderLease({ id, host, expires, released = false }) {
34
+ const marker = `<!-- factory:engine${VERSION_TOKEN} id=${id} host=${plainHost(host)} expires=${expires}${released ? " released=1" : ""} -->`;
35
+ return `${marker}\nFactory engine lease: ${plainHost(host)}${released ? " let go." : `, until ${expires}.`}`;
36
+ }
37
+
38
+ /** The lease in a comment body, or null. */
39
+ export function parseLease(body) {
40
+ const match = LEASE.exec(String(body ?? ""));
41
+ if (!match || Number.isNaN(Date.parse(match[3]))) return null;
42
+ return { id: match[1], host: match[2], expires: match[3], released: match[4] !== undefined };
43
+ }
44
+
45
+ const bare = (login) =>
46
+ String(login ?? "")
47
+ .toLowerCase()
48
+ .replace(/\[bot\]$/, "");
49
+
50
+ /** Whether `login` is the engine's own identity (case and a `[bot]` suffix aside). */
51
+ export const isLeaseAuthor = (login, identity) =>
52
+ identity !== undefined && identity !== "" && bare(login) === bare(identity);
53
+
54
+ /**
55
+ * The leases on the control issue's comments, oldest first, with their comment ids. With an
56
+ * `identity`, only the comments that identity wrote; without one, every author's (a reader
57
+ * that cannot know the engine, such as `doctor`, which then shows who wrote it).
58
+ */
59
+ export function leasesOf(comments, identity) {
60
+ return (
61
+ (comments ?? [])
62
+ // The engine's own comment, and not one that someone else has edited since (as a Claim).
63
+ .filter(
64
+ (c) =>
65
+ identity === undefined ||
66
+ (isLeaseAuthor(c.author, identity) && (!c.editor || isLeaseAuthor(c.editor, identity))),
67
+ )
68
+ .map((c) => ({ ...parseLease(c.body), commentId: c.id, author: c.author }))
69
+ .filter((l) => l.id !== undefined)
70
+ .sort((a, b) => Number(a.commentId) - Number(b.commentId))
71
+ );
72
+ }
73
+
74
+ const live = (lease, nowMs) => !lease.released && Date.parse(lease.expires) > nowMs;
75
+
76
+ /** The lease that stands: the oldest one that is not let go and has not expired. */
77
+ export const standingLease = (comments, nowMs, identity) =>
78
+ leasesOf(comments, identity).find((l) => live(l, nowMs)) ?? null;
79
+
80
+ const needIdentity = (identity) => {
81
+ if (typeof identity !== "string" || identity === "")
82
+ throw new Error("an Engine lease needs the engine's identity");
83
+ };
84
+
85
+ const iso = (ms) => new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
86
+
87
+ /** How long a lease lasts from a renewal: five sweeps. */
88
+ export const leaseMs = (pollMs) => LEASE_MISSED_SWEEPS * pollMs;
89
+
90
+ /**
91
+ * Takes the lease. `{ held, commentId }` when this engine stands, else
92
+ * `{ refused: <lease> }` naming the host that holds it.
93
+ * @param {{ tracker: { readControl: Function, postComment: Function, editComment: Function }, identity: string, id: string, host: string, now: () => number, pollMs: number }} deps
94
+ */
95
+ export function acquireLease({ tracker, identity, id, host, now, pollMs }) {
96
+ needIdentity(identity);
97
+ const control = tracker.readControl();
98
+ if (!control) {
99
+ return { missing: true };
100
+ }
101
+ const standing = standingLease(control.comments, now(), identity);
102
+ if (standing && standing.id !== id) return { refused: standing };
103
+ const expires = iso(now() + leaseMs(pollMs));
104
+ const body = renderLease({ id, host, expires });
105
+ // Its own comment from this run, else one left by a run that has ended (let go or
106
+ // expired): reused, so the control issue does not collect a lease comment per start.
107
+ const own =
108
+ leasesOf(control.comments, identity).find((l) => l.id === id) ??
109
+ leasesOf(control.comments, identity).find((l) => !live(l, now()));
110
+ let commentId;
111
+ if (own) {
112
+ tracker.editComment(own.commentId, body);
113
+ commentId = own.commentId;
114
+ } else {
115
+ commentId = tracker.postComment(control.number, body).id;
116
+ }
117
+ // Read it back, fresh: the lease stands only if ours is the oldest live one.
118
+ const again = tracker.readControl();
119
+ const winner = standingLease(again?.comments ?? [], now(), identity);
120
+ if (!winner || winner.id !== id) {
121
+ tracker.editComment(commentId, renderLease({ id, host, expires, released: true }));
122
+ return { refused: winner ?? standing ?? { id: "?", host: "another engine", expires } };
123
+ }
124
+ return { held: true, commentId, control: control.number };
125
+ }
126
+
127
+ /**
128
+ * Renews the lease: false when it is no longer ours (another engine stands, or it
129
+ * was let go), in which case the engine must stop.
130
+ */
131
+ export function renewLease({ tracker, identity, id, host, commentId, now, pollMs }) {
132
+ needIdentity(identity);
133
+ const control = tracker.readControl();
134
+ const standing = standingLease(control?.comments ?? [], now(), identity);
135
+ if (standing && standing.id !== id) return { lost: standing };
136
+ tracker.editComment(commentId, renderLease({ id, host, expires: iso(now() + leaseMs(pollMs)) }));
137
+ return { renewed: true };
138
+ }
139
+
140
+ /** Lets the lease go, so the next engine starts at once. */
141
+ export function releaseLease({ tracker, id, host, commentId, now, pollMs }) {
142
+ tracker.editComment(
143
+ commentId,
144
+ renderLease({ id, host, expires: iso(now() + leaseMs(pollMs)), released: true }),
145
+ );
146
+ }
@@ -0,0 +1,177 @@
1
+ // The Orchestrate engine's side of the engine interface (spec #500, ADR 0039): what
2
+ // `agent-kit factory run` supplies to the sweep's shell. A Stage starts in the
3
+ // background (the sweep never waits on one), as a pipeline function run in a Launcher
4
+ // sandbox; it is cancelled by its Claim nonce, which aborts the pipeline's signal and
5
+ // so tears the sandbox down; its identity is the PAT's user, whose login also becomes
6
+ // the assignee of every task it claims (`assignee`). A merge, when the gate is `on`,
7
+ // runs the same two trusted steps as `factory-merge`, in this process with the PAT.
8
+ //
9
+ // `stages` lists the Stages it can run. The sweep never claims one it lacks (the build
10
+ // Stage waits for the Chief of Staff's factory mode, #522).
11
+
12
+ export const LOCAL_ENGINE_NAME = "orchestrate";
13
+
14
+ /**
15
+ * @param {{
16
+ * identity: string,
17
+ * pipelines: Record<string, (ctx: object) => Promise<unknown>>,
18
+ * context: () => object,
19
+ * merge?: (action: object) => void,
20
+ * onRunsChanged?: (running: number) => void,
21
+ * onTeardown?: (end: object) => Promise<void> | void,
22
+ * classifyCancel?: (run: { issue: number, stage: string, claim: string }) => "expiry" | "cancel",
23
+ * log?: (line: string) => void,
24
+ * }} deps `onTeardown({ issue, stage, attempt, claim, kind, result, trace })` runs once as each run
25
+ * ends, whatever ended it: `kind` is `result` (the pipeline returned), `expiry` or `cancel` (the sweep
26
+ * cancelled it; `classifyCancel` says which), or `drain` (the drain or the second signal). The run is
27
+ * still counted until it returns, so `idle()` waits for it. `trace` is an object the pipeline fills
28
+ * (`delegations`, `head`, `launcherCode`) for the Run Record.
29
+ * `pipelines[stage](ctx)` gets `{ issue, stage, attempt, claim, signal }` and
30
+ * what `context()` returns (the PAT's `gh`, the tracker, the Launcher, the paths).
31
+ */
32
+ export function createLocalEngine({
33
+ identity,
34
+ pipelines,
35
+ context,
36
+ merge,
37
+ onRunsChanged = () => {},
38
+ onTeardown = () => {},
39
+ classifyCancel = () => "cancel",
40
+ log = () => {},
41
+ }) {
42
+ /** @type {Map<string, { issue: number, stage: string, claim: string, controller: AbortController, done: Promise<void> }>} */
43
+ const runs = new Map();
44
+ /** Nonces of runs that ended on their own (their Claims are read by the next sweep). */
45
+ const finished = new Set();
46
+ /** Nonces of runs this engine cancelled. */
47
+ const cancelled = new Set();
48
+ /** Why each cancelled run was cancelled: the teardown kind. */
49
+ const why = new Map();
50
+
51
+ const engine = {
52
+ name: LOCAL_ENGINE_NAME,
53
+ identity,
54
+ assignee: identity,
55
+ stages: Object.keys(pipelines),
56
+ finished,
57
+ cancelled,
58
+
59
+ startStage({ issue, stage, attempt, claim }) {
60
+ const pipeline = pipelines[stage];
61
+ if (!pipeline) throw new Error(`this engine has no ${stage} pipeline`);
62
+ if (runs.has(claim)) return;
63
+ const controller = new AbortController();
64
+ const trace = {};
65
+ let result;
66
+ const done = Promise.resolve()
67
+ .then(() =>
68
+ // Cancelled before it began: nothing starts.
69
+ controller.signal.aborted
70
+ ? undefined
71
+ : pipeline({
72
+ ...context(),
73
+ issue: Number(issue),
74
+ stage,
75
+ attempt: Number(attempt),
76
+ claim,
77
+ signal: controller.signal,
78
+ trace,
79
+ }),
80
+ )
81
+ .then((value) => {
82
+ result = value;
83
+ })
84
+ .catch((error) => {
85
+ log(
86
+ `#${issue} ${stage} pipeline failed: ${error instanceof Error ? error.message : error}`,
87
+ );
88
+ })
89
+ .then(async () => {
90
+ const kind = controller.signal.aborted ? (why.get(claim) ?? "cancel") : "result";
91
+ try {
92
+ await onTeardown({
93
+ issue: Number(issue),
94
+ stage,
95
+ attempt: Number(attempt),
96
+ claim,
97
+ kind,
98
+ result,
99
+ trace,
100
+ });
101
+ } catch (error) {
102
+ log(
103
+ `#${issue} ${stage} teardown failed: ${error instanceof Error ? error.message : error}`,
104
+ );
105
+ }
106
+ })
107
+ .finally(() => {
108
+ runs.delete(claim);
109
+ why.delete(claim);
110
+ if (!controller.signal.aborted) finished.add(claim);
111
+ onRunsChanged(runs.size);
112
+ });
113
+ runs.set(claim, { issue: Number(issue), stage, claim, controller, done });
114
+ onRunsChanged(runs.size);
115
+ },
116
+
117
+ /** Aborts the run holding this nonce, if it is still going. Returns the nonces it stopped. */
118
+ cancelStage({ claim }, kind) {
119
+ const run = runs.get(claim);
120
+ if (!run) return [];
121
+ cancelled.add(claim);
122
+ if (!why.has(claim)) {
123
+ let named = kind;
124
+ if (!named) {
125
+ try {
126
+ named = classifyCancel({ issue: run.issue, stage: run.stage, claim });
127
+ } catch {
128
+ named = "cancel";
129
+ }
130
+ }
131
+ why.set(claim, named);
132
+ }
133
+ run.controller.abort();
134
+ return [claim];
135
+ },
136
+
137
+ startMerge(action) {
138
+ if (!merge) throw new Error("this engine cannot merge");
139
+ merge(action);
140
+ },
141
+
142
+ /** The runs still going: `[{ issue, stage, claim }]`. */
143
+ running: () => [...runs.values()].map(({ issue, stage, claim }) => ({ issue, stage, claim })),
144
+
145
+ /** Resolves when no run is going. */
146
+ async idle() {
147
+ while (runs.size) await Promise.allSettled([...runs.values()].map((r) => r.done));
148
+ },
149
+
150
+ /**
151
+ * The drain: running Stages finish for up to `timeoutMs` (as `wait` measures it),
152
+ * and the rest are cancelled and torn down. Returns the nonces it cancelled.
153
+ * @param {{ timeoutMs: number, wait: (ms: number, signal?: AbortSignal) => Promise<void> }} opts
154
+ */
155
+ async drain({ timeoutMs, wait }) {
156
+ let expired = false;
157
+ const stopTimer = new AbortController();
158
+ const timer = wait(timeoutMs, stopTimer.signal).then(() => {
159
+ expired = !stopTimer.signal.aborted;
160
+ });
161
+ await Promise.race([engine.idle(), timer]);
162
+ stopTimer.abort();
163
+ const stopped = [];
164
+ if (expired && runs.size) {
165
+ for (const run of [...runs.values()]) stopped.push(...engine.cancelStage(run, "drain"));
166
+ await engine.idle();
167
+ }
168
+ return stopped;
169
+ },
170
+
171
+ /** Stops every run at once (the second Ctrl-C). */
172
+ cancelAll() {
173
+ for (const run of [...runs.values()]) engine.cancelStage(run, "drain");
174
+ },
175
+ };
176
+ return engine;
177
+ }
@@ -0,0 +1,64 @@
1
+ // The local lockfile beside the Engine lease (ADR 0039): a second `factory run` on
2
+ // the same machine for the same repository refuses at once, without a tracker read.
3
+ // `<state dir>/engine.lock` holds `{ pid, host, startedAt }`, created with the
4
+ // exclusive flag. A lock whose process is gone on this host is stale and is taken over.
5
+
6
+ import { join } from "node:path";
7
+
8
+ /** Where an engine's state lives for one repository: `<home>/.agent-kit/factory/<owner>/<repo>`. */
9
+ export const stateDirOf = (home, slug) => join(home, ".agent-kit", "factory", ...slug.split("/"));
10
+
11
+ /**
12
+ * @param {{
13
+ * dir: string,
14
+ * fs: { mkdirSync: Function, writeFileSync: Function, readFileSync: Function, rmSync: Function },
15
+ * pid: number,
16
+ * host: string,
17
+ * alive: (pid: number) => boolean,
18
+ * now: () => number,
19
+ * }} deps
20
+ * @returns {{ held: true, release: () => void, path: string } | { refused: { pid: number, host: string } }}
21
+ */
22
+ export function acquireLock({ dir, fs, pid, host, alive, now }) {
23
+ const path = join(dir, "engine.lock");
24
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
25
+ const body = JSON.stringify({ pid, host, startedAt: new Date(now()).toISOString() });
26
+ for (let tries = 0; tries < 2; tries += 1) {
27
+ try {
28
+ fs.writeFileSync(path, body, { flag: "wx", mode: 0o600 });
29
+ return {
30
+ held: true,
31
+ path,
32
+ release() {
33
+ try {
34
+ fs.rmSync(path, { force: true });
35
+ } catch {
36
+ // Nothing to let go.
37
+ }
38
+ },
39
+ };
40
+ } catch (error) {
41
+ if (error?.code !== "EEXIST") throw error;
42
+ }
43
+ let other;
44
+ try {
45
+ other = JSON.parse(fs.readFileSync(path, "utf8"));
46
+ } catch {
47
+ other = null;
48
+ }
49
+ const stale = !other || (other.host === host && !alive(Number(other.pid)));
50
+ if (!stale) return { refused: { pid: Number(other.pid), host: String(other.host) } };
51
+ fs.rmSync(path, { force: true });
52
+ }
53
+ return { refused: { pid: 0, host: "another process" } };
54
+ }
55
+
56
+ /** The holder of a lockfile, for `factory stop`: `{ pid, host }` or null. */
57
+ export function readLock({ dir, fs }) {
58
+ try {
59
+ const other = JSON.parse(fs.readFileSync(join(dir, "engine.lock"), "utf8"));
60
+ return { pid: Number(other.pid), host: String(other.host) };
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
@@ -0,0 +1,124 @@
1
+ // The Workflow engine's side of the engine interface (spec #500, Engine
2
+ // interface): an engine supplies to the sweep's shell start-a-Stage,
3
+ // cancel-a-Stage, start-a-merge (the merge gate's `on`) and its identity. On the Workflow engine a
4
+ // Stage starts by `workflow_dispatch` of that Stage's Caller, with `issue`,
5
+ // `attempt` and `claim` inputs; the Caller puts the nonce in its `run-name`,
6
+ // which is how a later ticket finds the run to cancel. Its identity is
7
+ // `github-actions[bot]`.
8
+
9
+ export const WORKFLOW_ENGINE_NAME = "workflow";
10
+ export const WORKFLOW_IDENTITY = "github-actions[bot]";
11
+
12
+ /** The merge gate's Caller. */
13
+ export const MERGE_CALLER = "factory-merge.yml";
14
+
15
+ /** The Caller file of a Stage: `factory-plan.yml`, `factory-build.yml`, ... */
16
+ export const callerFile = (stage) => `factory-${stage}.yml`;
17
+
18
+ /**
19
+ * @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string, ref: () => string, identity?: string }} deps
20
+ */
21
+ export function createWorkflowEngine({ gh, repo, ref, identity = WORKFLOW_IDENTITY }) {
22
+ return {
23
+ name: WORKFLOW_ENGINE_NAME,
24
+ identity,
25
+ startStage({ issue, stage, attempt, claim }) {
26
+ if (!/^[a-z]+$/.test(stage)) throw new Error(`not a Stage name: ${JSON.stringify(stage)}`);
27
+ const result = gh([
28
+ "api",
29
+ "-X",
30
+ "POST",
31
+ `repos/${repo}/actions/workflows/${callerFile(stage)}/dispatches`,
32
+ "-f",
33
+ `ref=${ref()}`,
34
+ "-f",
35
+ `inputs[issue]=${Number(issue)}`,
36
+ "-f",
37
+ `inputs[attempt]=${Number(attempt)}`,
38
+ "-f",
39
+ `inputs[claim]=${claim}`,
40
+ ]);
41
+ if (result.status !== 0) {
42
+ throw new Error(
43
+ `dispatching ${callerFile(stage)} failed: ${String(result.stderr).trim().slice(0, 300)}`,
44
+ );
45
+ }
46
+ },
47
+ /**
48
+ * Starts the merge gate's `factory-merge` job for one pull request at one head: the
49
+ * Caller holds the App token, merges with `--match-head-commit <head>` and writes
50
+ * "merged at <head>" in the gate comment (docs/factory/merge-gate.md). A sweep
51
+ * dispatches at most one per run.
52
+ */
53
+ startMerge({ issue, pull, head, method }) {
54
+ if (!/^[0-9a-f]{40}$/.test(String(head))) throw new Error(`not a commit: ${head}`);
55
+ if (!["squash", "merge", "rebase"].includes(method)) {
56
+ throw new Error(`not a merge method: ${JSON.stringify(method)}`);
57
+ }
58
+ const result = gh([
59
+ "api",
60
+ "-X",
61
+ "POST",
62
+ `repos/${repo}/actions/workflows/${MERGE_CALLER}/dispatches`,
63
+ "-f",
64
+ `ref=${ref()}`,
65
+ "-f",
66
+ `inputs[issue]=${Number(issue)}`,
67
+ "-f",
68
+ `inputs[pull]=${Number(pull)}`,
69
+ "-f",
70
+ `inputs[head]=${head}`,
71
+ "-f",
72
+ `inputs[method]=${method}`,
73
+ ]);
74
+ if (result.status !== 0) {
75
+ throw new Error(
76
+ `dispatching ${MERGE_CALLER} failed: ${String(result.stderr).trim().slice(0, 300)}`,
77
+ );
78
+ }
79
+ },
80
+
81
+ /**
82
+ * Cancels the Stage run whose run-name ends `claim=<nonce>`: the Caller's
83
+ * runs that are queued or running are listed, and only an exact nonce
84
+ * matches (`claim=abc` is not `claim=abcd`). No such run, or one that
85
+ * ended meanwhile, is done. Returns the ids it cancelled.
86
+ */
87
+ cancelStage({ stage, claim }) {
88
+ if (!/^[a-z]+$/.test(stage)) throw new Error(`not a Stage name: ${JSON.stringify(stage)}`);
89
+ if (!/^[A-Za-z0-9._:+-]+$/.test(String(claim))) {
90
+ throw new Error(`not a plain nonce: ${JSON.stringify(claim)}`);
91
+ }
92
+ const suffix = ` claim=${claim}`;
93
+ const cancelled = [];
94
+ for (const status of ["queued", "in_progress"]) {
95
+ const listed = gh([
96
+ "api",
97
+ `repos/${repo}/actions/workflows/${callerFile(stage)}/runs?status=${status}&per_page=100`,
98
+ ]);
99
+ if (listed.status !== 0) {
100
+ throw new Error(
101
+ `listing ${callerFile(stage)} runs failed: ${String(listed.stderr).trim().slice(0, 300)}`,
102
+ );
103
+ }
104
+ for (const run of JSON.parse(listed.stdout || "{}").workflow_runs ?? []) {
105
+ if (!String(run.display_title ?? "").endsWith(suffix)) continue;
106
+ const result = gh([
107
+ "api",
108
+ `repos/${repo}/actions/runs/${Number(run.id)}/cancel`,
109
+ "-X",
110
+ "POST",
111
+ ]);
112
+ if (result.status === 0) {
113
+ cancelled.push(run.id);
114
+ } else if (!/\b409\b/.test(String(result.stderr))) {
115
+ throw new Error(
116
+ `cancelling run ${run.id} failed: ${String(result.stderr).trim().slice(0, 300)}`,
117
+ );
118
+ }
119
+ }
120
+ }
121
+ return cancelled;
122
+ },
123
+ };
124
+ }
@@ -0,0 +1,88 @@
1
+ // The gate comment (spec #500, Markers): one per pull request, edited in place,
2
+ // found by its marker among the engine's own comments. Pure: the sweep core
3
+ // renders the text, the shell posts or edits it.
4
+ //
5
+ // <!-- factory:gate v=1 head=<sha> [updating=1] [carried-from=<sha>] -->
6
+ //
7
+ // `head` is the head the comment judged. `updating=1` says the gate has just
8
+ // asked GitHub to update the branch from that head, so a different head next
9
+ // sweep is that update's result and its Stage checks may be carried over.
10
+ // `carried-from` says the Stage checks on `head` were copied from that earlier
11
+ // head, which the gate needs to read their ` (carried from <sha7>)` suffix.
12
+
13
+ export const GATE_MARKER_PREFIX = "<!-- factory:gate ";
14
+ const MARKER =
15
+ /^<!-- factory:gate v=1 head=([0-9a-f]{40})( updating=1)?( carried-from=([0-9a-f]{40}))? -->$/m;
16
+
17
+ /** The marker's fields, or null when the text holds no readable one. */
18
+ export function parseGateComment(body) {
19
+ const m = MARKER.exec(String(body ?? ""));
20
+ if (!m) return null;
21
+ return { head: m[1], updating: Boolean(m[2]), carriedFrom: m[4] ?? null };
22
+ }
23
+
24
+ export function renderGateMarker({ head, updating = false, carriedFrom = null }) {
25
+ return `<!-- factory:gate v=1 head=${head}${updating ? " updating=1" : ""}${carriedFrom ? ` carried-from=${carriedFrom}` : ""} -->`;
26
+ }
27
+
28
+ /** What the gate's comment says when it has decided to merge in `on`; the merge job checks for it. */
29
+ export const MERGING_TEXT = "the merge job merges that exact head";
30
+
31
+ const code = (sha) => `\`${sha}\``;
32
+
33
+ /**
34
+ * The comment's text for one decision.
35
+ * @param {{ mode: "off" | "shadow" | "on", decision: object, head: string, updating?: boolean, carriedFrom?: string | null }} input
36
+ */
37
+ export function renderGateComment({ mode, decision, head, updating = false, carriedFrom = null }) {
38
+ const marker = renderGateMarker({ head, updating, carriedFrom });
39
+ const tier = `Risk tier: ${decision.tier}${decision.tierReasons?.length ? ` (${decision.tierReasons.join("; ")})` : ""}.`;
40
+ const title = `**Merge gate** (${mode})`;
41
+ let line;
42
+ switch (decision.decision) {
43
+ case "back-to-checking":
44
+ line = `The head ${code(head)} has no passing QA and security checks, so the task goes back to \`factory:checking\`.`;
45
+ break;
46
+ case "update":
47
+ line = `Behind the base branch with nothing else in the way: updating the branch from ${code(head)}. Its Stage checks are carried over only if the base side changed none of this pull request's files.`;
48
+ break;
49
+ case "merge":
50
+ line =
51
+ mode === "shadow"
52
+ ? `Would merge at ${code(decision.head)}.`
53
+ : mode === "on"
54
+ ? `Every fact holds at ${code(decision.head)}: ${MERGING_TEXT}.`
55
+ : `Every fact holds at ${code(decision.head)}. A person merges.`;
56
+ break;
57
+ default: {
58
+ const reasons = decision.reasons ?? [];
59
+ if (mode === "off") {
60
+ const others = reasons.filter((r) => r !== "mode off");
61
+ line = `${others.length ? `Holds: ${others.join("; ")}.` : "No holds."} Mode is off: a person merges.`;
62
+ } else if (decision.tierOnly) {
63
+ line = `Held: tier ${decision.tier} only (would merge at ${code(head)}).`;
64
+ } else {
65
+ line = `Held: ${reasons.join("; ")}.`;
66
+ }
67
+ }
68
+ }
69
+ const tripped = decision.tripped
70
+ ? `The gate is tripped${decision.tripped === "tripped" ? "" : ` (${decision.tripped})`}: it acts as shadow and merges nothing.\n`
71
+ : "";
72
+ return `${marker}\n${title} for ${code(head)}\n${tier}\n${line}\n${tripped}`;
73
+ }
74
+
75
+ /**
76
+ * The gate comment once the merge job has merged the head: the marker, title and
77
+ * tier lines stay (the report reads the tier and the head from them), and the
78
+ * decision line becomes "merged at `<sha>`". Null when the comment is not the
79
+ * gate's own for that head.
80
+ */
81
+ export function renderMergedComment(oldBody, sha) {
82
+ const marker = parseGateComment(oldBody);
83
+ if (!marker || marker.head !== sha) return null;
84
+ const lines = String(oldBody).split("\n");
85
+ const keep = lines.slice(0, lines.findIndex((l) => /^Risk tier: /.test(l)) + 1);
86
+ if (keep.length < 3) return null;
87
+ return `${keep.join("\n")}\nAuto-merged: merged at ${code(sha)} by the merge gate.\n`;
88
+ }
@@ -0,0 +1,57 @@
1
+ // `merge` in the factory config (spec #500, Factory config): `mode` (`off`),
2
+ // `auto_tiers` (`[low]`) and `method` (`squash`). Read from the default branch
3
+ // with the rest of the config, a Guarded path. Pure: the shell hands the text in.
4
+ // A file or value the gate cannot read leaves the mode `off`, so a typo never
5
+ // turns the gate on, and says why in `problem`.
6
+
7
+ import { MERGE_MODES } from "./gate-core.mjs";
8
+
9
+ export const DEFAULT_MERGE = Object.freeze({ mode: "off", auto_tiers: ["low"], method: "squash" });
10
+ const METHODS = ["squash", "merge", "rebase"];
11
+
12
+ /**
13
+ * @param {string | null | undefined | symbol} text the config file's text; null or undefined when it is missing
14
+ * @returns {{ value: { mode: string, auto_tiers: string[], method: string }, problem?: string }}
15
+ */
16
+ export function mergeFromConfig(text) {
17
+ const off = (problem) => ({ value: { ...DEFAULT_MERGE, auto_tiers: ["low"] }, problem });
18
+ if (text === null || text === undefined)
19
+ return { value: { ...DEFAULT_MERGE, auto_tiers: ["low"] } };
20
+ if (typeof text !== "string") return off("the factory config could not be read");
21
+ let data;
22
+ try {
23
+ data = JSON.parse(text);
24
+ } catch {
25
+ return off("the factory config is not JSON");
26
+ }
27
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
28
+ return off("the factory config is not an object");
29
+ }
30
+ if (!("merge" in data)) return { value: { ...DEFAULT_MERGE, auto_tiers: ["low"] } };
31
+ const merge = data.merge;
32
+ if (merge === null || typeof merge !== "object" || Array.isArray(merge)) {
33
+ return off("merge is not an object");
34
+ }
35
+ const value = { ...DEFAULT_MERGE, auto_tiers: ["low"] };
36
+ if ("mode" in merge) {
37
+ if (!MERGE_MODES.includes(merge.mode)) {
38
+ return off(
39
+ `merge.mode is ${JSON.stringify(merge.mode)}, not one of ${MERGE_MODES.join(", ")}`,
40
+ );
41
+ }
42
+ value.mode = merge.mode;
43
+ }
44
+ if ("auto_tiers" in merge) {
45
+ const t = merge.auto_tiers;
46
+ if (!Array.isArray(t) || !t.every((x) => ["low", "medium", "high"].includes(x))) {
47
+ return off("merge.auto_tiers is not a list of tiers");
48
+ }
49
+ // `high` is refused: the riskiest work always has a person merge it.
50
+ value.auto_tiers = t.filter((x) => x !== "high");
51
+ }
52
+ if ("method" in merge) {
53
+ if (!METHODS.includes(merge.method)) return off("merge.method is not squash, merge or rebase");
54
+ value.method = merge.method;
55
+ }
56
+ return { value };
57
+ }