@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,142 @@
1
+ // The engine's secrets, read once into memory (ADR 0039): the GitHub PAT from
2
+ // `AGENT_KIT_GITHUB_TOKEN`, a literal or an `op://` reference read with `op read`
3
+ // (never `gh auth token`), and the model keys from the harnesses' own variables, each
4
+ // likewise. Nothing is written to a file or an argument. A missing secret is a refusal
5
+ // that names its cause.
6
+
7
+ import { CREDENTIAL_VARS } from "../../deep-scan/credential.mjs";
8
+ import { firstLine } from "../../exec.mjs";
9
+
10
+ export const TOKEN_VAR = "AGENT_KIT_GITHUB_TOKEN";
11
+
12
+ function resolve(name, value, runner) {
13
+ if (!String(value).startsWith("op://")) return { value };
14
+ const read = runner("op", ["read", "--no-newline", String(value)]);
15
+ if (read.status !== 0) {
16
+ return {
17
+ refused: `${name} is a 1Password reference that op read could not resolve: ${firstLine(read.stderr) || `exit ${read.status}`}`,
18
+ };
19
+ }
20
+ return { value: String(read.stdout).replace(/\r?\n$/, "") };
21
+ }
22
+
23
+ /**
24
+ * @param {{ env: Record<string, string | undefined>, runner: Function }} deps
25
+ * @returns {{ token: string, modelEnv: Record<string, string> } | { refused: string }}
26
+ */
27
+ export function readSecrets({ env, runner }) {
28
+ const raw = env[TOKEN_VAR];
29
+ if (raw === undefined || raw === "") {
30
+ return {
31
+ refused: `${TOKEN_VAR} is not set: the engine needs a fine-grained, one-repository GitHub token (a literal or an op:// reference). It never uses gh auth token.`,
32
+ };
33
+ }
34
+ const token = resolve(TOKEN_VAR, raw, runner);
35
+ if (token.refused) return { refused: token.refused };
36
+ if (!token.value || !/^[\x21-\x7e]+$/.test(token.value)) {
37
+ return { refused: `${TOKEN_VAR} is empty or not a token (its value is not shown).` };
38
+ }
39
+ const modelEnv = {};
40
+ for (const name of CREDENTIAL_VARS) {
41
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
42
+ if (key === undefined || env[key] === "") continue;
43
+ const got = resolve(name, env[key], runner);
44
+ if (got.refused) return { refused: got.refused };
45
+ modelEnv[name] = got.value;
46
+ }
47
+ if (Object.keys(modelEnv).length === 0) {
48
+ return {
49
+ refused: `no model credential: set one of ${CREDENTIAL_VARS.join(", ")} (a key or an op:// reference). It stays in the engine's memory and reaches only the model proxy.`,
50
+ };
51
+ }
52
+ return { token: token.value, modelEnv };
53
+ }
54
+
55
+ export const RECORDS_SINK_VAR = "AGENT_KIT_RECORDS_SINK";
56
+ export const RECORDS_TOKEN_VAR = "AGENT_KIT_RECORDS_TOKEN";
57
+ export const S3_KEY_ID_VAR = "ORCHESTRATE_S3_ACCESS_KEY_ID";
58
+ export const S3_SECRET_VAR = "ORCHESTRATE_S3_SECRET_ACCESS_KEY";
59
+ const RAW_VARS = Object.freeze({
60
+ endpoint: "AGENT_KIT_RAW_SINK_ENDPOINT",
61
+ bucket: "AGENT_KIT_RAW_SINK_BUCKET",
62
+ region: "AGENT_KIT_RAW_SINK_REGION",
63
+ });
64
+
65
+ /**
66
+ * The Sinks' settings and credentials (#523), read once into memory, from the environment
67
+ * only (a literal or an `op://` reference), and never written, logged or passed to a child.
68
+ *
69
+ * records `AGENT_KIT_RECORDS_SINK` (owner/name of a private repository) and
70
+ * `AGENT_KIT_RECORDS_TOKEN`: both, or the engine keeps no Run Record (`notice`).
71
+ * raw `AGENT_KIT_RAW_SINK_ENDPOINT`, `_BUCKET`, `_REGION` and the S3 key pair
72
+ * `ORCHESTRATE_S3_ACCESS_KEY_ID` / `ORCHESTRATE_S3_SECRET_ACCESS_KEY`: read only
73
+ * with `--upload-raw`, which needs all five (`refused` names what is missing).
74
+ *
75
+ * @returns {{ records: {repo: string, token: string} | null, raw: object | null, notice?: string, refused?: string }}
76
+ */
77
+ export function readSinks({ env, runner, uploadRaw }) {
78
+ const out = { records: null, raw: null };
79
+ const get = (name) => {
80
+ const value = env[name];
81
+ if (value === undefined || value === "") return { missing: true };
82
+ const got = resolve(name, value, runner);
83
+ return got.refused ? { refused: got.refused } : { value: got.value };
84
+ };
85
+ const repo = String(env[RECORDS_SINK_VAR] ?? "");
86
+ const token = get(RECORDS_TOKEN_VAR);
87
+ if (token.refused) return { ...out, refused: token.refused };
88
+ if (repo && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo) && !token.missing)
89
+ out.records = { repo, token: token.value };
90
+ else
91
+ out.notice = `no Run Record will be kept: ${
92
+ repo === ""
93
+ ? `${RECORDS_SINK_VAR} is not set`
94
+ : token.missing
95
+ ? `${RECORDS_TOKEN_VAR} is not set`
96
+ : `${RECORDS_SINK_VAR} is not owner/name`
97
+ }`;
98
+ if (!uploadRaw) return out;
99
+ const raw = {};
100
+ const missing = [];
101
+ for (const [key, name] of Object.entries(RAW_VARS)) {
102
+ if (env[name] === undefined || env[name] === "") missing.push(name);
103
+ else raw[key] = String(env[name]);
104
+ }
105
+ for (const [key, name] of [
106
+ ["accessKeyId", S3_KEY_ID_VAR],
107
+ ["secretAccessKey", S3_SECRET_VAR],
108
+ ]) {
109
+ const got = get(name);
110
+ if (got.refused) return { ...out, refused: got.refused };
111
+ if (got.missing) missing.push(name);
112
+ else raw[key] = got.value;
113
+ }
114
+ if (missing.length)
115
+ return {
116
+ ...out,
117
+ refused: `--upload-raw needs ${missing.join(", ")} (a value or an op:// reference)`,
118
+ };
119
+ let url;
120
+ try {
121
+ url = new URL(raw.endpoint);
122
+ } catch {
123
+ return { ...out, refused: `${RAW_VARS.endpoint} is not a URL` };
124
+ }
125
+ const plainHost = url.hostname === "localhost" || url.hostname === "127.0.0.1";
126
+ if (
127
+ !(url.protocol === "https:" || (url.protocol === "http:" && plainHost)) ||
128
+ url.username ||
129
+ url.password ||
130
+ (url.pathname !== "/" && url.pathname !== "") ||
131
+ url.search
132
+ )
133
+ return {
134
+ ...out,
135
+ refused: `${RAW_VARS.endpoint} is an https URL with no path, query or password`,
136
+ };
137
+ if (!/^[a-z0-9][a-z0-9.-]{1,62}$/.test(raw.bucket))
138
+ return { ...out, refused: `${RAW_VARS.bucket} is not a bucket name` };
139
+ if (!/^[a-z0-9-]+$/.test(raw.region))
140
+ return { ...out, refused: `${RAW_VARS.region} is not a region` };
141
+ return { ...out, raw };
142
+ }
@@ -0,0 +1,242 @@
1
+ // What the Orchestrate engine does when a Stage run ends, whatever ended it (#523):
2
+ //
3
+ // result the pipeline returned
4
+ // expiry the sweep cancelled it because its Claim expired
5
+ // cancel the sweep cancelled it for another reason (a pause, a withdrawal)
6
+ // drain the drain's time ran out, or the second Ctrl-C
7
+ // restart the next engine start found the run's folder and no process
8
+ //
9
+ // In that order of independence, each step catching its own failure so one cannot stop
10
+ // the next: (1) the run folder is collected under the home directory (collect.mjs),
11
+ // (2) it is uploaded raw, only with `--upload-raw` and never for the security Stage
12
+ // (raw.mjs), (3) the Stage's `run-record/2` is written to the Sink, and one
13
+ // per Delegation with the build run as their parent (records/engine-record.mjs).
14
+ // Every effect goes through injected `fs` and `fetch`. The Sink token lives in `sink`
15
+ // and the S3 keys in `s3`, closures this module never reads out.
16
+
17
+ import { join } from "node:path";
18
+
19
+ import {
20
+ delegationRunIdOf,
21
+ buildEngineRecord,
22
+ runIdOf,
23
+ writeEngineRecord,
24
+ } from "../records/engine-record.mjs";
25
+ import { uploadRawFolder } from "./raw.mjs";
26
+ import { collectRunFolder, leftoverFolders, pruneCollected } from "./collect.mjs";
27
+
28
+ export const TEARDOWN_KINDS = Object.freeze(["result", "expiry", "cancel", "drain", "restart"]);
29
+ const SHA = /^[0-9a-f]{40}$/;
30
+ const CHECK_STATES = ["pending", "success", "failure", "error"];
31
+ const CHECKED = ["review", "qa", "security"];
32
+
33
+ /** The working folder's name for a Claim nonce, as `runDir` makes it. */
34
+ const folderOf = (claim) => String(claim).replace(/[^A-Za-z0-9._-]/g, "_");
35
+ const message = (error) => (error instanceof Error ? error.message : "failed");
36
+
37
+ /**
38
+ * @param {{
39
+ * fs: object, runsDir: string, slug: string, identity: string,
40
+ * sink: { repo: string, token: string } | null,
41
+ * s3: object | null, uploadRaw: boolean,
42
+ * fetch: Function, now: () => number, log: (line: string) => void,
43
+ * }} deps
44
+ */
45
+ export function createTeardown({
46
+ fs,
47
+ runsDir,
48
+ slug,
49
+ identity,
50
+ sink,
51
+ s3,
52
+ uploadRaw,
53
+ fetch,
54
+ now,
55
+ log,
56
+ }) {
57
+ const repo = `github.com/${slug}`;
58
+ const read = (path) => {
59
+ try {
60
+ return fs.readFileSync(path, "utf8");
61
+ } catch {
62
+ return null;
63
+ }
64
+ };
65
+
66
+ async function raw({ stage, folders, tag }) {
67
+ if (!uploadRaw) return "raw upload off";
68
+ if (stage === "security") return "raw upload skipped (security)";
69
+ if (!s3) return "raw upload not set up";
70
+ const notes = [];
71
+ for (const { runId, dir } of folders) {
72
+ const done = await uploadRawFolder({ s3, fs, dir, repo, login: identity, runId, stage, log });
73
+ notes.push(
74
+ done.status === "uploaded" ? `${done.files} files` : `${done.status}: ${done.detail}`,
75
+ );
76
+ }
77
+ log(`${tag} raw upload: ${notes.join("; ")}`);
78
+ return "raw upload on";
79
+ }
80
+
81
+ async function keep(record, tag) {
82
+ if (!sink) return "no Run Record kept (no Sink)";
83
+ const done = await writeEngineRecord({ sink, record, login: identity, fetch });
84
+ log(
85
+ `${tag} Run Record ${record.run.id}: ${done.status}${done.detail ? ` (${done.detail})` : ""}`,
86
+ );
87
+ return done.status;
88
+ }
89
+
90
+ /**
91
+ * Ends one run. `end` is what the engine gives `onTeardown`; a restart gives one
92
+ * with the Claim's stage and no pipeline result.
93
+ */
94
+ async function teardown(end) {
95
+ const { issue, stage, attempt, claim, kind, result, trace = {} } = end;
96
+ const tag = `#${issue} ${stage} (${kind})`;
97
+ let runId;
98
+ try {
99
+ runId = runIdOf(claim);
100
+ } catch (error) {
101
+ log(`${tag}: no run id (${message(error)}): the folder stays where it is`);
102
+ return;
103
+ }
104
+ const working = join(runsDir, folderOf(claim));
105
+ const delegations = (trace.delegations ?? []).flatMap((d) => {
106
+ try {
107
+ return [
108
+ { ...d, runId: delegationRunIdOf(claim, d.id), dir: join(working, "delegations", d.id) },
109
+ ];
110
+ } catch {
111
+ return [];
112
+ }
113
+ });
114
+ const usage = read(join(working, "usage.json"));
115
+ const delegationUsage = new Map(
116
+ delegations.map((d) => [d.id, read(join(d.dir, "usage.json"))]),
117
+ );
118
+
119
+ let folders = [];
120
+ try {
121
+ const got = collectRunFolder({
122
+ fs,
123
+ root: runsDir,
124
+ source: working,
125
+ runId,
126
+ delegations: delegations.map((d) => ({ runId: d.runId, dir: d.dir })),
127
+ });
128
+ if (got.folder) {
129
+ folders = [
130
+ { runId, dir: got.folder },
131
+ ...delegations
132
+ .filter((d) => got.delegations.includes(join(runsDir, d.runId)))
133
+ .map((d) => ({ runId: d.runId, dir: join(runsDir, d.runId) })),
134
+ ];
135
+ log(`${tag}: run folder kept at ${got.folder}`);
136
+ }
137
+ } catch (error) {
138
+ log(`${tag}: the run folder could not be collected (${message(error)})`);
139
+ }
140
+
141
+ let rawState = uploadRaw ? "raw upload on" : "raw upload off";
142
+ try {
143
+ rawState = await raw({ stage, folders, tag });
144
+ } catch (error) {
145
+ log(`${tag}: raw upload failed (${message(error)})`);
146
+ }
147
+
148
+ try {
149
+ const head = trace.head ?? result?.head ?? null;
150
+ // A state the record does not know (a check can say anything) is no Stage check, not a lost record.
151
+ const stageCheck =
152
+ CHECKED.includes(stage) && CHECK_STATES.includes(result?.state) ? result.state : null;
153
+ const base = { repo, task: issue, attempt, rawUpload: uploadRaw, now: now() };
154
+ // Each record stands alone: one that cannot be built never costs the others.
155
+ const records = [
156
+ ...delegations.map((d) => ({
157
+ ...base,
158
+ runId: d.runId,
159
+ parentRunId: runId,
160
+ stage: "build",
161
+ code: d.code ?? null,
162
+ usageText: delegationUsage.get(d.id),
163
+ })),
164
+ {
165
+ ...base,
166
+ runId,
167
+ stage,
168
+ headSha: typeof head === "string" && SHA.test(head) ? head : null,
169
+ stageCheck,
170
+ code: trace.launcherCode ?? null,
171
+ usageText: usage,
172
+ },
173
+ ];
174
+ for (const input of records) {
175
+ try {
176
+ await keep(buildEngineRecord(input), tag);
177
+ } catch (error) {
178
+ log(`${tag}: no Run Record was kept for ${input.runId} (${message(error)})`);
179
+ }
180
+ }
181
+ } catch (error) {
182
+ log(`${tag}: no Run Record was kept (${message(error)})`);
183
+ }
184
+ try {
185
+ pruneCollected({ fs, root: runsDir, now: now() });
186
+ } catch {
187
+ // expiry is retried at the next teardown and the next start
188
+ }
189
+ log(`${tag}: ${rawState}`);
190
+ }
191
+
192
+ /**
193
+ * Start-up: collects every working folder a dead run left (the Claims `left` it released
194
+ * tell which Stage and Attempt each was), writes its record as `no-result`, then prunes
195
+ * the collected folders past their expiry.
196
+ */
197
+ async function restart({ left }) {
198
+ for (const name of leftoverFolders({ fs, root: runsDir })) {
199
+ const claim = left.find((c) => folderOf(c.claim) === name);
200
+ const delegations = [];
201
+ try {
202
+ const dir = join(runsDir, name, "delegations");
203
+ if (fs.existsSync(dir))
204
+ for (const e of fs.readdirSync(dir, { withFileTypes: true }))
205
+ if (e.isDirectory()) delegations.push({ id: e.name, code: null });
206
+ } catch {
207
+ // the folder is collected without its Delegations' records
208
+ }
209
+ if (claim) {
210
+ await teardown({
211
+ issue: claim.issue,
212
+ stage: claim.stage,
213
+ attempt: claim.attempt,
214
+ claim: name,
215
+ kind: "restart",
216
+ trace: { delegations },
217
+ });
218
+ } else {
219
+ // No open Claim names it: the folder is kept, with no record (its Stage is unknown).
220
+ try {
221
+ collectRunFolder({
222
+ fs,
223
+ root: runsDir,
224
+ source: join(runsDir, name),
225
+ runId: runIdOf(name),
226
+ });
227
+ log(`restart: run folder ${name} kept at ${join(runsDir, runIdOf(name))}`);
228
+ } catch (error) {
229
+ log(`restart: run folder ${name} could not be collected (${message(error)})`);
230
+ }
231
+ }
232
+ }
233
+ try {
234
+ const removed = pruneCollected({ fs, root: runsDir, now: now() });
235
+ if (removed.length) log(`restart: removed ${removed.length} expired run folder(s)`);
236
+ } catch (error) {
237
+ log(`restart: expired run folders could not be removed (${message(error)})`);
238
+ }
239
+ }
240
+
241
+ return { teardown, restart };
242
+ }
@@ -0,0 +1,68 @@
1
+ // The token's reach (ADR 0039): the engine refuses a token it can tell reaches more than
2
+ // this one repository. A classic token (`ghp_...`, or any answer carrying an
3
+ // `X-OAuth-Scopes` header) reaches every repository its owner can. A fine-grained token
4
+ // is asked which repositories it lists (`GET /user/repos`): more than the one named, or
5
+ // a different one, is refused. A token whose reach cannot be read is let through with a
6
+ // notice; a fine-grained token's own settings still bound it.
7
+
8
+ /**
9
+ * @param {{ gh: (args: string[]) => { status: number | null, stdout: string, stderr: string }, repo: string, token: string }} deps
10
+ * @returns {{ login: string, notice?: string } | { refused: string }}
11
+ */
12
+ export function checkToken({ gh, repo, token }) {
13
+ if (token.startsWith("ghp_")) {
14
+ return {
15
+ refused: `the token is a classic token, which reaches every repository its owner can, not only ${repo}: make a fine-grained token for this one repository`,
16
+ };
17
+ }
18
+ const who = gh(["api", "-i", "user"]);
19
+ if (who.status !== 0) {
20
+ return {
21
+ refused: `GitHub did not accept the token (gh api user): ${String(who.stderr).trim().slice(0, 200)}`,
22
+ };
23
+ }
24
+ const split = String(who.stdout).split(/\r?\n\r?\n/);
25
+ const headers = split[0] ?? "";
26
+ let login;
27
+ try {
28
+ login = JSON.parse(split.slice(1).join("\n\n")).login;
29
+ } catch {
30
+ login = undefined;
31
+ }
32
+ if (!login) return { refused: "GitHub did not say whose token this is (gh api user)" };
33
+ if (/^x-oauth-scopes:/im.test(headers)) {
34
+ return {
35
+ refused: `the token is a classic token (it carries OAuth scopes), which reaches every repository ${login} can, not only ${repo}: make a fine-grained token for this one repository`,
36
+ };
37
+ }
38
+ const listed = gh(["api", "user/repos?per_page=100", "--paginate", "--slurp"]);
39
+ if (listed.status !== 0) {
40
+ return {
41
+ login,
42
+ notice: `the token's reach could not be read (${String(listed.stderr).trim().slice(0, 120)}): make sure it names ${repo} alone`,
43
+ };
44
+ }
45
+ let names;
46
+ try {
47
+ names = JSON.parse(listed.stdout || "[]")
48
+ .flat()
49
+ .map((r) => String(r.full_name).toLowerCase());
50
+ } catch {
51
+ return {
52
+ login,
53
+ notice: "the token's reach could not be read: make sure it names this repository alone",
54
+ };
55
+ }
56
+ const here = names.includes(repo.toLowerCase());
57
+ const others = names.filter((n) => n !== repo.toLowerCase());
58
+ if (others.length > 0) {
59
+ return {
60
+ refused: `the token reaches ${names.length} repositories (also ${others.slice(0, 3).join(", ")}${others.length > 3 ? ", ..." : ""}), not only ${repo}: make a fine-grained token for this one repository`,
61
+ };
62
+ }
63
+ if (!here)
64
+ return {
65
+ refused: `the token does not reach ${repo}: it needs Contents, Issues, Pull requests and Statuses write there`,
66
+ };
67
+ return { login };
68
+ }
@@ -0,0 +1,157 @@
1
+ // The security Stage's trusted steps, as commands of the Kit-owned bundle
2
+ // (`node .github/agent-factory/sweep.mjs <command>`), run by the
3
+ // `factory-security` Caller (examples/factory/factory-security.yml). No agent
4
+ // runs in these jobs. The audit itself runs in the Caller's `security` job, the
5
+ // security-audit reusable with `factory: true`; its findings go to the private
6
+ // draft advisory only. All these steps ever learn of it is the job's result and
7
+ // one bare word, `clean` or `held`, and the status they write is the Stage
8
+ // check (ADR 0035), whose description is exactly `passed` or
9
+ // `held for a maintainer`.
10
+ //
11
+ // security-target --issue <n>
12
+ // finds the open pull request of the task's newest build
13
+ // Attempt (branch factory/<issue>/attempt-<n>, from this
14
+ // repository) and prints `pr_number=`, `head_sha=`,
15
+ // `base_sha=` and `base_ref=` to GITHUB_OUTPUT. None: exit 1.
16
+ // security-start --sha <head> [--run-url <url>]
17
+ // writes `factory/security` as `pending` on the head.
18
+ // security-check --sha <head> [--run-url <url>]
19
+ // with AUDIT_JOB_RESULT (the audit job's result) and
20
+ // AUDIT_RESULT (the reusable's verdict output) in the
21
+ // environment, writes `factory/security` on the head:
22
+ // `success` ("passed") only for a successful audit whose
23
+ // verdict is `clean`, otherwise `failure`
24
+ // ("held for a maintainer"). Prints `state=`. Exit 0
25
+ // whatever the state (the status is the result); 1 when the
26
+ // status cannot be written.
27
+ // Exit 2 is a usage error. The write token is the job's GITHUB_TOKEN, with
28
+ // `statuses: write`, so the creator is the Workflow engine's identity.
29
+
30
+ import { securityStageCheck } from "../checks/security.mjs";
31
+ import { STAGE_REPO, STAGE_SHA, writeStageCheck } from "../checks/stage-check.mjs";
32
+ import { newestBuildPull } from "../review/command.mjs";
33
+
34
+ const securityOptionReader = (args) => (name) => {
35
+ const at = args.indexOf(`--${name}`);
36
+ return at === -1 ? undefined : args[at + 1];
37
+ };
38
+
39
+ function securityContext({ env, args, need }) {
40
+ const option = securityOptionReader(args);
41
+ const repo = env.GITHUB_REPOSITORY ?? "";
42
+ if (!STAGE_REPO.test(repo)) return { usage: "GITHUB_REPOSITORY is not set" };
43
+ for (const name of need) {
44
+ if (!option(name)) return { usage: `--${name} is missing` };
45
+ }
46
+ return { option, repo };
47
+ }
48
+
49
+ const securityRunUrl = (option, env, repo) => {
50
+ const given = option("run-url");
51
+ if (given) return given;
52
+ return env.GITHUB_RUN_ID
53
+ ? `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${repo}/actions/runs/${env.GITHUB_RUN_ID}`
54
+ : undefined;
55
+ };
56
+
57
+ const securityFailure = (error, title = "Stage check not written") =>
58
+ `::error title=${title}::${String(error.message).replace(/\s+/g, " ")}`;
59
+
60
+ export function runSecurityTarget({ gh, env, args, out, err, appendOutput }) {
61
+ const c = securityContext({ env, args, need: ["issue"] });
62
+ if (c.usage) {
63
+ err(`security-target: ${c.usage}`);
64
+ return 2;
65
+ }
66
+ const issue = Number(c.option("issue"));
67
+ if (!Number.isInteger(issue) || issue < 1) {
68
+ err("security-target: --issue is not an issue number");
69
+ return 2;
70
+ }
71
+ try {
72
+ const result = gh([
73
+ "api",
74
+ "--paginate",
75
+ "--slurp",
76
+ `repos/${c.repo}/pulls?state=open&per_page=100`,
77
+ ]);
78
+ if (result.status !== 0) throw new Error(String(result.stderr).trim().slice(0, 300));
79
+ const pull = newestBuildPull(JSON.parse(result.stdout || "[]").flat(), { repo: c.repo, issue });
80
+ if (!pull || !STAGE_SHA.test(pull.head?.sha ?? "") || !STAGE_SHA.test(pull.base?.sha ?? "")) {
81
+ err(
82
+ "::error title=No pull request::The task has no open pull request on a build Attempt's branch to audit.",
83
+ );
84
+ return 1;
85
+ }
86
+ const baseRef = String(pull.base?.ref ?? "");
87
+ if (!/^[A-Za-z0-9._/-]+$/.test(baseRef)) throw new Error("the base branch name is not plain");
88
+ appendOutput(`pr_number=${Number(pull.number)}`);
89
+ appendOutput(`head_sha=${pull.head.sha}`);
90
+ appendOutput(`base_sha=${pull.base.sha}`);
91
+ appendOutput(`base_ref=${baseRef}`);
92
+ out(`Auditing pull request #${pull.number} at ${pull.head.sha.slice(0, 7)}.`);
93
+ return 0;
94
+ } catch (error) {
95
+ err(securityFailure(error, "Pull request not found"));
96
+ return 1;
97
+ }
98
+ }
99
+
100
+ export function runSecurityStart({ gh, env, args, out, err }) {
101
+ const c = securityContext({ env, args, need: ["sha"] });
102
+ if (c.usage) {
103
+ err(`security-start: ${c.usage}`);
104
+ return 2;
105
+ }
106
+ const sha = c.option("sha");
107
+ if (!STAGE_SHA.test(sha)) {
108
+ err("security-start: --sha is not a commit sha");
109
+ return 2;
110
+ }
111
+ try {
112
+ writeStageCheck({
113
+ gh,
114
+ repo: c.repo,
115
+ sha,
116
+ check: securityStageCheck({ started: true }),
117
+ targetUrl: securityRunUrl(c.option, env, c.repo),
118
+ });
119
+ out("factory/security: pending");
120
+ return 0;
121
+ } catch (error) {
122
+ err(securityFailure(error));
123
+ return 1;
124
+ }
125
+ }
126
+
127
+ export function runSecurityCheck({ gh, env, args, out, err, appendOutput }) {
128
+ const c = securityContext({ env, args, need: ["sha"] });
129
+ if (c.usage) {
130
+ err(`security-check: ${c.usage}`);
131
+ return 2;
132
+ }
133
+ const sha = c.option("sha");
134
+ if (!STAGE_SHA.test(sha)) {
135
+ err("security-check: --sha is not a commit sha");
136
+ return 2;
137
+ }
138
+ const check = securityStageCheck({
139
+ jobResult: env.AUDIT_JOB_RESULT,
140
+ auditResult: env.AUDIT_RESULT,
141
+ });
142
+ try {
143
+ writeStageCheck({
144
+ gh,
145
+ repo: c.repo,
146
+ sha,
147
+ check,
148
+ targetUrl: securityRunUrl(c.option, env, c.repo),
149
+ });
150
+ appendOutput(`state=${check.state}`);
151
+ out(`factory/security: ${check.state}`);
152
+ return 0;
153
+ } catch (error) {
154
+ err(securityFailure(error));
155
+ return 1;
156
+ }
157
+ }