@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,153 @@
1
+ // The risk rules (spec #500, Contracts): `{ id, tier, when: paths | size | label }`,
2
+ // read from the base branch alone. The Risk tier of a plan is the higher of the
3
+ // planner's proposal and what the rules give for its Allowed paths, size and the
4
+ // issue's labels, and the rules that raised it are named in `risk_raised_by`, so
5
+ // a planner cannot talk a risky change down. A missing or unreadable file makes
6
+ // every plan `high`. Pure: the trusted step reads the file and hands its text in.
7
+ // Contract suite: scripts/factory-risk-rules.test.mjs.
8
+
9
+ const TIER_ORDER = Object.freeze(["low", "medium", "high"]);
10
+ const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
11
+ const WHEN_KEYS = Object.freeze(["paths", "size", "label"]);
12
+ const SIZE_NAMES = Object.freeze(["s", "m", "l"]);
13
+
14
+ /** The ids the trusted step records when the file cannot give any rule. */
15
+ export const RULES_MISSING = "risk-rules-missing";
16
+ export const RULES_UNREADABLE = "risk-rules-unreadable";
17
+
18
+ const rankOf = (tier) => TIER_ORDER.indexOf(tier);
19
+ const isListOf = (v) =>
20
+ Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.trim() !== "");
21
+
22
+ /**
23
+ * The rules in a file's text.
24
+ * @param {string | null | undefined} text null or undefined when the file is missing
25
+ * @returns {{ status: "ok", rules: Array<{ id: string, tier: string, when: object }> } | { status: "missing" | "unreadable" }}
26
+ */
27
+ export function parseRiskRules(text) {
28
+ if (text === null || text === undefined) return { status: "missing" };
29
+ let data;
30
+ try {
31
+ data = JSON.parse(String(text));
32
+ } catch {
33
+ return { status: "unreadable" };
34
+ }
35
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
36
+ return { status: "unreadable" };
37
+ }
38
+ if (Object.keys(data).some((k) => k !== "rules") || !Array.isArray(data.rules)) {
39
+ return { status: "unreadable" };
40
+ }
41
+ const ids = new Set();
42
+ const rules = [];
43
+ for (const rule of data.rules) {
44
+ if (rule === null || typeof rule !== "object" || Array.isArray(rule)) {
45
+ return { status: "unreadable" };
46
+ }
47
+ if (Object.keys(rule).some((k) => !["id", "tier", "when"].includes(k))) {
48
+ return { status: "unreadable" };
49
+ }
50
+ const { id, tier, when } = rule;
51
+ if (typeof id !== "string" || !ID.test(id) || ids.has(id) || rankOf(tier) === -1) {
52
+ return { status: "unreadable" };
53
+ }
54
+ if (when === null || typeof when !== "object" || Array.isArray(when)) {
55
+ return { status: "unreadable" };
56
+ }
57
+ const keys = Object.keys(when);
58
+ if (keys.length !== 1 || !WHEN_KEYS.includes(keys[0]) || !isListOf(when[keys[0]])) {
59
+ return { status: "unreadable" };
60
+ }
61
+ if (keys[0] === "size" && !when.size.every((s) => SIZE_NAMES.includes(s))) {
62
+ return { status: "unreadable" };
63
+ }
64
+ ids.add(id);
65
+ rules.push({ id, tier, when });
66
+ }
67
+ return { status: "ok", rules };
68
+ }
69
+
70
+ const hasWildcard = (segment) => /[*?]/.test(segment);
71
+
72
+ /** One path segment's glob (`*` and `?` never cross a `/`). */
73
+ function segmentPattern(segment) {
74
+ const source = segment
75
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
76
+ .replace(/\*+/g, "[^/]*")
77
+ .replace(/\?/g, "[^/]");
78
+ return new RegExp(`^${source}$`);
79
+ }
80
+
81
+ /** Whether the glob segments `g` match the path segments `p`, `**` crossing folders. */
82
+ function matches(g, p) {
83
+ if (g.length === 0) return p.length === 0;
84
+ if (g[0] === "**") return matches(g.slice(1), p) || (p.length > 0 && matches(g, p.slice(1)));
85
+ return p.length > 0 && segmentPattern(g[0]).test(p[0]) && matches(g.slice(1), p.slice(1));
86
+ }
87
+
88
+ /** Whether the glob matches the whole path: `*` and `?` stay in one segment, `**` crosses folders. */
89
+ export const pathMatchesGlob = (glob, path) => matches(segments(glob), segments(path));
90
+
91
+ const segments = (glob) =>
92
+ String(glob)
93
+ .replace(/^\.\//, "")
94
+ .split("/")
95
+ .filter((s) => s !== "");
96
+
97
+ /** The leading segments of a glob that hold no wildcard. */
98
+ function staticPrefix(segs) {
99
+ const at = segs.findIndex(hasWildcard);
100
+ return at === -1 ? segs : segs.slice(0, at);
101
+ }
102
+
103
+ /**
104
+ * Whether an Allowed path and a rule's glob name the same files: the rule's
105
+ * glob matches the Allowed path as written, or the Allowed path ends in `**`
106
+ * and the rule's folder lies at or under it (`.github/**` covers
107
+ * `.github/agent-factory/**`). An Allowed path with no trailing `**` may be a
108
+ * folder, so it also counts as that folder's `**`. A rule reads the Allowed
109
+ * path as written: a broad `src/**` does not fire a rule for `**` + `/auth/`
110
+ * + `**`. The gate later measures the real diff.
111
+ */
112
+ export function pathsOverlap(allowed, ruleGlob) {
113
+ const a = segments(allowed);
114
+ const g = segments(ruleGlob);
115
+ const covers = (asked) => {
116
+ if (asked.at(-1) !== "**") return false;
117
+ const base = staticPrefix(asked);
118
+ const rule = staticPrefix(g);
119
+ return base.every((seg, i) => rule[i] === seg);
120
+ };
121
+ return matches(g, a) || covers(a) || (a.at(-1) !== "**" && covers([...a, "**"]));
122
+ }
123
+
124
+ /**
125
+ * The rules that fire for a plan.
126
+ * @returns {Array<{ id: string, tier: string }>}
127
+ */
128
+ export function firedRules(rules, { allowedPaths = [], size, labels = [] }) {
129
+ return rules.filter((rule) => {
130
+ const { paths, size: sizes, label } = rule.when;
131
+ if (paths) return allowedPaths.some((p) => paths.some((g) => pathsOverlap(p, g)));
132
+ if (sizes) return sizes.includes(size);
133
+ return labels.some((l) => label.includes(l));
134
+ });
135
+ }
136
+
137
+ /**
138
+ * The plan's Risk tier: the higher of the planner's and the rules'.
139
+ * `raisedBy` names the rules whose tier is above the planner's, or, when the
140
+ * file cannot give any rule, the one id that says so (and the tier is `high`).
141
+ * @param {{ planner: string, parsed: ReturnType<typeof parseRiskRules>, allowedPaths: string[], size: string, labels?: string[] }} input
142
+ * @returns {{ risk: string, raisedBy: string[] }}
143
+ */
144
+ export function riskTier({ planner, parsed, allowedPaths, size, labels = [] }) {
145
+ if (parsed.status !== "ok") {
146
+ const id = parsed.status === "missing" ? RULES_MISSING : RULES_UNREADABLE;
147
+ return planner === "high" ? { risk: "high", raisedBy: [] } : { risk: "high", raisedBy: [id] };
148
+ }
149
+ const fired = firedRules(parsed.rules, { allowedPaths, size, labels });
150
+ const raising = fired.filter((r) => rankOf(r.tier) > rankOf(planner));
151
+ const top = raising.reduce((best, r) => (rankOf(r.tier) > rankOf(best) ? r.tier : best), planner);
152
+ return { risk: top, raisedBy: raising.map((r) => r.id) };
153
+ }
@@ -0,0 +1,163 @@
1
+ // The QA Stage's trusted steps, as commands of the Kit-owned bundle
2
+ // (`node .github/agent-factory/sweep.mjs <command>`), run by the `factory-qa`
3
+ // Caller (examples/factory/factory-qa.yml). No agent runs in these jobs. The
4
+ // QA Report they read is a pull request comment the engine's identity wrote,
5
+ // and the status they write is the Stage check (ADR 0035).
6
+ //
7
+ // qa-target --issue <n>
8
+ // finds the open pull request of the task's newest build Attempt
9
+ // (branch factory/<issue>/attempt-<n>, from this repository) and
10
+ // prints `pr_number=` and `head_sha=` to GITHUB_OUTPUT. None: exit 1.
11
+ // qa-start --sha <head> [--run-url <url>]
12
+ // writes `factory/qa` as `pending` on the head.
13
+ // qa-check --pr <n> --sha <head> [--run-url <url>]
14
+ // reads the newest QA Report comment (first line `<!-- qa-report -->`)
15
+ // the engine's identity wrote, and writes `factory/qa` on the head
16
+ // from its strict header: `success` or `failure`, or `error` when
17
+ // there is no valid report for this head. Matches no run link.
18
+ // Prints `state=`. Exit 0 whatever the state (the status is the
19
+ // result); 1 when the status cannot be written.
20
+ // Exit 2 is a usage error. The write token is the job's GITHUB_TOKEN, with
21
+ // `statuses: write`, so the creator is the Workflow engine's identity.
22
+
23
+ import { qaStageCheck, QA_REPORT_MARKER } from "../checks/qa.mjs";
24
+ import { STAGE_REPO, STAGE_SHA, writeStageCheck } from "../checks/stage-check.mjs";
25
+ import { WORKFLOW_IDENTITY } from "../engine/workflow-engine.mjs";
26
+ import { newestBuildPull } from "../review/command.mjs";
27
+ import { createGithubTracker } from "../tracker/github.mjs";
28
+
29
+ const qaBare = (login) =>
30
+ String(login ?? "")
31
+ .replace(/\[bot\]$/, "")
32
+ .toLowerCase();
33
+
34
+ const qaOptionReader = (args) => (name) => {
35
+ const at = args.indexOf(`--${name}`);
36
+ return at === -1 ? undefined : args[at + 1];
37
+ };
38
+
39
+ function qaContext({ env, args, need }) {
40
+ const option = qaOptionReader(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 qaRunUrl = (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 qaFailure = (error, title = "Stage check not written") =>
58
+ `::error title=${title}::${String(error.message).replace(/\s+/g, " ")}`;
59
+
60
+ export function runQaTarget({ gh, env, args, out, err, appendOutput }) {
61
+ const c = qaContext({ env, args, need: ["issue"] });
62
+ if (c.usage) {
63
+ err(`qa-target: ${c.usage}`);
64
+ return 2;
65
+ }
66
+ const issue = Number(c.option("issue"));
67
+ if (!Number.isInteger(issue) || issue < 1) {
68
+ err("qa-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 ?? "")) {
81
+ err(
82
+ "::error title=No pull request::The task has no open pull request on a build Attempt's branch to check.",
83
+ );
84
+ return 1;
85
+ }
86
+ appendOutput(`pr_number=${Number(pull.number)}`);
87
+ appendOutput(`head_sha=${pull.head.sha}`);
88
+ out(`Checking QA of pull request #${pull.number} at ${pull.head.sha.slice(0, 7)}.`);
89
+ return 0;
90
+ } catch (error) {
91
+ err(qaFailure(error, "Pull request not found"));
92
+ return 1;
93
+ }
94
+ }
95
+
96
+ export function runQaStart({ gh, env, args, out, err }) {
97
+ const c = qaContext({ env, args, need: ["sha"] });
98
+ if (c.usage) {
99
+ err(`qa-start: ${c.usage}`);
100
+ return 2;
101
+ }
102
+ const sha = c.option("sha");
103
+ if (!STAGE_SHA.test(sha)) {
104
+ err("qa-start: --sha is not a commit sha");
105
+ return 2;
106
+ }
107
+ try {
108
+ writeStageCheck({
109
+ gh,
110
+ repo: c.repo,
111
+ sha,
112
+ check: qaStageCheck({ started: true }),
113
+ targetUrl: qaRunUrl(c.option, env, c.repo),
114
+ });
115
+ out("factory/qa: pending");
116
+ return 0;
117
+ } catch (error) {
118
+ err(qaFailure(error));
119
+ return 1;
120
+ }
121
+ }
122
+
123
+ export function runQaCheck({ gh, env, args, out, err, appendOutput, tracker }) {
124
+ const c = qaContext({ env, args, need: ["pr", "sha"] });
125
+ if (c.usage) {
126
+ err(`qa-check: ${c.usage}`);
127
+ return 2;
128
+ }
129
+ const pr = Number(c.option("pr"));
130
+ const sha = c.option("sha");
131
+ if (!Number.isInteger(pr) || pr < 1 || !STAGE_SHA.test(sha)) {
132
+ err("qa-check: --pr or --sha is malformed");
133
+ return 2;
134
+ }
135
+ const identity = env.AGENT_KIT_FACTORY_IDENTITY ?? WORKFLOW_IDENTITY;
136
+ try {
137
+ const comments = (tracker ?? createGithubTracker({ gh, repo: c.repo })).readComments(pr);
138
+ // The newest QA Report the engine's identity wrote: anyone can type a
139
+ // header, so a comment of anyone else's is never read. A report for an
140
+ // older head is the newest when nothing newer exists: it reads as another commit.
141
+ const report = comments
142
+ .filter(
143
+ (comment) =>
144
+ qaBare(comment.author) === qaBare(identity) &&
145
+ String(comment.body).split("\n", 1)[0].trim() === QA_REPORT_MARKER,
146
+ )
147
+ .at(-1);
148
+ const check = qaStageCheck({ report: report?.body ?? null, head: sha });
149
+ writeStageCheck({
150
+ gh,
151
+ repo: c.repo,
152
+ sha,
153
+ check,
154
+ targetUrl: qaRunUrl(c.option, env, c.repo),
155
+ });
156
+ appendOutput(`state=${check.state}`);
157
+ out(`factory/qa: ${check.state} (${check.description})`);
158
+ return 0;
159
+ } catch (error) {
160
+ err(qaFailure(error));
161
+ return 1;
162
+ }
163
+ }
@@ -0,0 +1,133 @@
1
+ // The Run Record of one Stage run on the Orchestrate engine (#523, ADR 0036): the
2
+ // same `run-record/2` the Workflow engine's record job writes, written by the engine
3
+ // itself at the run's teardown. Pure functions of what the kit ran (the Launcher's
4
+ // exit code and usage file, the Stage check, the pull request head), never of a
5
+ // transcript. It differs from the Workflow engine's record in these values only:
6
+ // `engine` is `orchestrate`, the id is `orc-<Claim nonce>`, the Sink path names the
7
+ // PAT's login, and `raw_upload` says whether `--upload-raw` was given.
8
+ //
9
+ // The build run is the parent of its Delegations: a Delegation's record is
10
+ // `kind: stage`, `stage: build`, with `parent_run_id` the build run's id.
11
+
12
+ import { parseUsage } from "../claims/release.mjs";
13
+ import { ORC_ID, STAGES, checkStageRecord, exitOf } from "./record.mjs";
14
+ import { writeRecord } from "./sink.mjs";
15
+
16
+ export const ORCHESTRATE_ENGINE = "orchestrate";
17
+
18
+ const REPO = /^github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
19
+ const LOGIN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,38}$/;
20
+ const NONCE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
21
+ const CHECKS = ["pending", "success", "failure", "error"];
22
+ const SHA = /^[0-9a-f]{40}$/;
23
+
24
+ /** The run id of a Stage run: `orc-<Claim nonce>`. */
25
+ export function runIdOf(claim) {
26
+ const id = `orc-${claim}`;
27
+ if (!NONCE.test(String(claim)) || !ORC_ID.test(id))
28
+ throw new Error("the Claim nonce is not a plain run id");
29
+ return id;
30
+ }
31
+
32
+ /** The run id of a Delegation: `orc-<nonce>-<delegation id>`. */
33
+ export function delegationRunIdOf(claim, delegation) {
34
+ // A name that is not a plain word could walk out of the run folder (`..`).
35
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,30}$/.test(String(delegation)))
36
+ throw new Error("the Delegation id is not a plain name");
37
+ const id = `${runIdOf(claim)}-${delegation}`;
38
+ if (!ORC_ID.test(id)) throw new Error("the Delegation id is not a plain run id");
39
+ return id;
40
+ }
41
+
42
+ /** `records/<host>/<owner>/<repo>/<login>/<run id>.json`, every segment lowercased (the skill's Sink path). */
43
+ export function engineRecordPath({ repo, login, runId }) {
44
+ if (!REPO.test(String(repo))) throw new Error(`not a github.com/<owner>/<repo> name: ${repo}`);
45
+ if (!LOGIN.test(String(login))) throw new Error("the engine's login is not a plain login");
46
+ if (!ORC_ID.test(String(runId))) throw new Error("not an Orchestrate run id");
47
+ return `records/${repo}/${login}/${runId}.json`.toLowerCase();
48
+ }
49
+
50
+ const whole = (value, what, min = 0) => {
51
+ if (!Number.isSafeInteger(Number(value)) || Number(value) < min || !/^\d+$/.test(String(value)))
52
+ throw new Error(`not a whole number${min ? ` of ${min} or more` : ""}: ${what}`);
53
+ return Number(value);
54
+ };
55
+
56
+ /**
57
+ * One Stage run's (or one Delegation's) record.
58
+ *
59
+ * @param {{
60
+ * repo: string, runId: string, parentRunId?: string | null, stage: string, task: number | string,
61
+ * attempt: number | string, headSha?: string | null, stageCheck?: string | null,
62
+ * code?: number | string | null, usageText?: string | null, rawUpload: boolean, now: Date | number
63
+ * }} input `code` is the Launcher's exit code; null when it never ran or never answered.
64
+ */
65
+ export function buildEngineRecord({
66
+ repo,
67
+ runId,
68
+ parentRunId = null,
69
+ stage,
70
+ task,
71
+ attempt,
72
+ headSha = null,
73
+ stageCheck = null,
74
+ code = null,
75
+ usageText = null,
76
+ rawUpload,
77
+ now,
78
+ }) {
79
+ if (!STAGES.includes(stage)) throw new Error(`not a Stage: ${stage}`);
80
+ if (!ORC_ID.test(String(runId))) throw new Error("not an Orchestrate run id");
81
+ if (parentRunId !== null && !ORC_ID.test(String(parentRunId)))
82
+ throw new Error("the parent run id is not an Orchestrate run id");
83
+ if (headSha !== null && !SHA.test(String(headSha))) throw new Error("head is not a commit sha");
84
+ if (stageCheck !== null && !CHECKS.includes(stageCheck))
85
+ throw new Error("Stage check is not a known state");
86
+ const usage = usageText ? parseUsage(usageText) : null;
87
+ const stageCode = code === null || code === undefined ? "" : String(code);
88
+ // QA has no agent yet: it ends as its check says, and carries no count.
89
+ const exit =
90
+ stage === "qa"
91
+ ? stageCheck === "success" || stageCheck === "failure"
92
+ ? "completed"
93
+ : "no-result"
94
+ : exitOf({ stageCode, usageText: usageText ?? "" });
95
+ const record = {
96
+ schema: "run-record/2",
97
+ run: {
98
+ id: runId,
99
+ repo: String(repo).toLowerCase(),
100
+ kind: "stage",
101
+ engine: ORCHESTRATE_ENGINE,
102
+ stage,
103
+ task: whole(task, "task", 1),
104
+ head_sha: headSha,
105
+ attempt: whole(attempt, "attempt", 1),
106
+ parent_run_id: parentRunId,
107
+ stage_check: stageCheck,
108
+ recorded_at: new Date(now).toISOString().replace(/\.\d+Z$/, "Z"),
109
+ exit,
110
+ ...(usage && stage !== "qa" ? { tokens: usage.tokens } : {}),
111
+ raw_upload: rawUpload === true,
112
+ },
113
+ };
114
+ const problems = checkStageRecord(record);
115
+ if (problems.length) throw new Error(`not a safe Run Record: ${problems.join("; ")}`);
116
+ return record;
117
+ }
118
+
119
+ /**
120
+ * Writes one record to the Sink, create-only. `sink` is `{ repo, token }` and the token
121
+ * goes only where `writeRecord` puts it, an Authorization header. Never throws; the
122
+ * result says what happened, in words that hold no token.
123
+ */
124
+ export async function writeEngineRecord({ sink, record, login, fetch }) {
125
+ const path = engineRecordPath({ repo: record.run.repo, login, runId: record.run.id });
126
+ const done = await writeRecord({
127
+ sink,
128
+ path,
129
+ text: `${JSON.stringify(record, null, 2)}\n`,
130
+ fetch,
131
+ });
132
+ return { ...done, path };
133
+ }
@@ -0,0 +1,96 @@
1
+ // The record job's one command (#517). Run by a Caller's `record` job, in a job
2
+ // that holds no agent and no pull request code: it reads the Caller's inputs
3
+ // from the environment, the head's Stage check from the tracker, and writes one
4
+ // Run Record to the Sink with the Caller's secret. It never fails the run: every
5
+ // outcome is one line of the job summary, and a missing secret says that no
6
+ // record was kept.
7
+ //
8
+ // node src/factory/records/main.mjs (inside the installed CLI)
9
+
10
+ import { appendFileSync } from "node:fs";
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ import { buildStageRecord, recordPath, stageCheckOf } from "./record.mjs";
14
+ import { writeRecord } from "./sink.mjs";
15
+
16
+ const NONE = "no Run Record was kept";
17
+
18
+ /**
19
+ * @param {{env: Record<string, string | undefined>, fetch?: Function, now?: Date, summary?: (line: string) => void}} io
20
+ * @returns {Promise<{status: "created" | "already" | "different" | "not-private" | "error" | "skipped" | "refused", detail?: string}>}
21
+ */
22
+ export async function runRecordJob({
23
+ env,
24
+ fetch = globalThis.fetch,
25
+ now = new Date(),
26
+ summary = () => {},
27
+ }) {
28
+ const say = (line) => summary(`Factory Run Record: ${line}`);
29
+ const token = env.AGENT_KIT_RECORDS_TOKEN ?? "";
30
+ const repo = env.AGENT_KIT_RECORDS_SINK ?? "";
31
+ if (token === "" || repo === "") {
32
+ say(
33
+ `${NONE}: ${token === "" ? "the AGENT_KIT_RECORDS_TOKEN secret is not set" : "the AGENT_KIT_RECORDS_SINK variable is not set"}.`,
34
+ );
35
+ return { status: "skipped" };
36
+ }
37
+ try {
38
+ const stage = env.STAGE ?? "";
39
+ const head = env.HEAD_SHA ?? "";
40
+ const where = env.GITHUB_REPOSITORY ?? "";
41
+ let statuses = null;
42
+ if (head !== "" && /^[0-9a-f]{40}$/.test(head) && /^[\w.-]+\/[\w.-]+$/.test(where)) {
43
+ const got = await fetch(`https://api.github.com/repos/${where}/commits/${head}/statuses`, {
44
+ headers: {
45
+ authorization: `Bearer ${env.GH_TOKEN ?? ""}`,
46
+ accept: "application/vnd.github+json",
47
+ "user-agent": "agent-kit-factory-record",
48
+ },
49
+ });
50
+ if (got.ok) statuses = await got.json();
51
+ }
52
+ const input = {
53
+ repo: `github.com/${where}`,
54
+ runId: env.GITHUB_RUN_ID ?? "",
55
+ runAttempt: env.GITHUB_RUN_ATTEMPT ?? "",
56
+ stage,
57
+ task: env.TASK ?? "",
58
+ attempt: env.ATTEMPT ?? "",
59
+ headSha: head,
60
+ parentRunId: env.PARENT_RUN_ID ?? "",
61
+ stageCheck: stageCheckOf({ statuses, stage }) ?? "",
62
+ stageCode: env.STAGE_CODE ?? "",
63
+ usageText: env.STAGE_USAGE ?? "",
64
+ now,
65
+ };
66
+ const record = buildStageRecord(input);
67
+ const path = recordPath(input);
68
+ const done = await writeRecord({
69
+ sink: { repo, token },
70
+ path,
71
+ text: `${JSON.stringify(record, null, 2)}\n`,
72
+ fetch,
73
+ });
74
+ if (done.status === "created") say(`Run Record kept at \`${path}\`.`);
75
+ else if (done.status === "already")
76
+ say(`Run Record kept: \`${path}\` already holds these bytes.`);
77
+ else if (done.status === "different")
78
+ say(`${NONE}: different bytes are already at \`${path}\`, and nothing was overwritten.`);
79
+ else if (done.status === "not-private") say(`${NONE}: the sink repository is not private.`);
80
+ else say(`${NONE}: ${done.detail}.`);
81
+ return done;
82
+ } catch (error) {
83
+ // The message comes from this module's own checks, which never echo a value or the token.
84
+ say(`${NONE}: ${error instanceof Error ? error.message : "the record could not be built"}.`);
85
+ return { status: "refused", detail: error instanceof Error ? error.message : undefined };
86
+ }
87
+ }
88
+
89
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
90
+ const file = process.env.GITHUB_STEP_SUMMARY;
91
+ const summary = (line) => {
92
+ console.log(line);
93
+ if (file) appendFileSync(file, `${line}\n`);
94
+ };
95
+ await runRecordJob({ env: process.env, summary });
96
+ }