@mnaimfaizy/agent-kit 1.0.0-beta.15 → 1.0.0-beta.17

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 (120) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/src/cli.mjs +332 -5
  4. package/src/deep-scan/docker-driver.mjs +70 -3
  5. package/src/deep-scan/lifecycle.mjs +2 -2
  6. package/src/deep-scan/sbx-driver.mjs +34 -47
  7. package/src/doctor.mjs +53 -1
  8. package/src/exec.mjs +18 -5
  9. package/src/factory/budget/budget.mjs +260 -0
  10. package/src/factory/build/command.mjs +321 -0
  11. package/src/factory/build/factory.mjs +473 -0
  12. package/src/factory/build/findings.mjs +55 -0
  13. package/src/factory/build/host.mjs +230 -0
  14. package/src/factory/build/notes.mjs +191 -0
  15. package/src/factory/build/pull-request.mjs +74 -0
  16. package/src/factory/bundle.mjs +146 -0
  17. package/src/factory/checks/allowed-paths.mjs +50 -0
  18. package/src/factory/checks/plan-header.mjs +296 -0
  19. package/src/factory/checks/qa.mjs +85 -0
  20. package/src/factory/checks/review.mjs +73 -0
  21. package/src/factory/checks/security.mjs +50 -0
  22. package/src/factory/checks/stage-check.mjs +89 -0
  23. package/src/factory/claims/command.mjs +187 -0
  24. package/src/factory/claims/release.mjs +111 -0
  25. package/src/factory/decision/answers.mjs +103 -0
  26. package/src/factory/decision/command.mjs +64 -0
  27. package/src/factory/decision/plan.mjs +99 -0
  28. package/src/factory/decision/request.mjs +116 -0
  29. package/src/factory/doctor/files.mjs +349 -0
  30. package/src/factory/doctor/index.mjs +56 -0
  31. package/src/factory/doctor/local.mjs +513 -0
  32. package/src/factory/doctor/orchestrate.mjs +146 -0
  33. package/src/factory/engine/lease.mjs +146 -0
  34. package/src/factory/engine/local-engine.mjs +177 -0
  35. package/src/factory/engine/lockfile.mjs +64 -0
  36. package/src/factory/engine/workflow-engine.mjs +124 -0
  37. package/src/factory/gate/comment.mjs +88 -0
  38. package/src/factory/gate/config.mjs +57 -0
  39. package/src/factory/gate/gate-core.mjs +250 -0
  40. package/src/factory/gate/guarded.mjs +17 -0
  41. package/src/factory/gate/reads.mjs +105 -0
  42. package/src/factory/gate/task.mjs +193 -0
  43. package/src/factory/gate/trip-reads.mjs +82 -0
  44. package/src/factory/gate/trip.mjs +87 -0
  45. package/src/factory/init/blueprint.mjs +181 -0
  46. package/src/factory/init/index.mjs +338 -0
  47. package/src/factory/labels/evidence.mjs +162 -0
  48. package/src/factory/labels/moves.mjs +32 -0
  49. package/src/factory/labels/reconcile.mjs +267 -0
  50. package/src/factory/labels/revert.mjs +87 -0
  51. package/src/factory/labels/timeline.mjs +72 -0
  52. package/src/factory/labels/voided.mjs +59 -0
  53. package/src/factory/limits/harness.mjs +39 -0
  54. package/src/factory/limits/limits.mjs +131 -0
  55. package/src/factory/merge/command.mjs +172 -0
  56. package/src/factory/outbox/check.mjs +240 -0
  57. package/src/factory/outbox/rulings.mjs +195 -0
  58. package/src/factory/plan/command.mjs +66 -0
  59. package/src/factory/plan/comment.mjs +156 -0
  60. package/src/factory/plan/publish.mjs +149 -0
  61. package/src/factory/plan/risk.mjs +153 -0
  62. package/src/factory/qa/command.mjs +301 -0
  63. package/src/factory/qa/decide.mjs +86 -0
  64. package/src/factory/qa/report.mjs +50 -0
  65. package/src/factory/records/engine-record.mjs +133 -0
  66. package/src/factory/records/main.mjs +96 -0
  67. package/src/factory/records/record.mjs +226 -0
  68. package/src/factory/records/sink.mjs +57 -0
  69. package/src/factory/report/build.mjs +92 -0
  70. package/src/factory/report/command.mjs +80 -0
  71. package/src/factory/report/facts.mjs +226 -0
  72. package/src/factory/report/gate-section.mjs +122 -0
  73. package/src/factory/report/metrics.mjs +111 -0
  74. package/src/factory/report/reads.mjs +246 -0
  75. package/src/factory/report/render.mjs +121 -0
  76. package/src/factory/report/rollout.mjs +154 -0
  77. package/src/factory/review/brief.mjs +195 -0
  78. package/src/factory/review/command.mjs +182 -0
  79. package/src/factory/run/awake.mjs +70 -0
  80. package/src/factory/run/collect.mjs +77 -0
  81. package/src/factory/run/command.mjs +556 -0
  82. package/src/factory/run/gh.mjs +46 -0
  83. package/src/factory/run/launch.mjs +66 -0
  84. package/src/factory/run/pipelines.mjs +694 -0
  85. package/src/factory/run/raw.mjs +96 -0
  86. package/src/factory/run/restart.mjs +83 -0
  87. package/src/factory/run/s3.mjs +193 -0
  88. package/src/factory/run/secrets.mjs +142 -0
  89. package/src/factory/run/teardown.mjs +242 -0
  90. package/src/factory/run/token.mjs +70 -0
  91. package/src/factory/run/worktree.mjs +160 -0
  92. package/src/factory/security/audit.mjs +353 -0
  93. package/src/factory/security/command.mjs +157 -0
  94. package/src/factory/setup/app.mjs +122 -0
  95. package/src/factory/setup/command.mjs +472 -0
  96. package/src/factory/setup/labels.mjs +25 -0
  97. package/src/factory/setup/reads.mjs +159 -0
  98. package/src/factory/setup/writes.mjs +138 -0
  99. package/src/factory/snapshot/write.mjs +176 -0
  100. package/src/factory/stop/command.mjs +136 -0
  101. package/src/factory/sweep/actions-main.mjs +119 -0
  102. package/src/factory/sweep/command.mjs +65 -0
  103. package/src/factory/sweep/knobs.mjs +78 -0
  104. package/src/factory/sweep/marker-version.mjs +15 -0
  105. package/src/factory/sweep/markers.mjs +112 -0
  106. package/src/factory/sweep/overlap.mjs +24 -0
  107. package/src/factory/sweep/run.mjs +198 -0
  108. package/src/factory/sweep/shell.mjs +398 -0
  109. package/src/factory/sweep/split.mjs +104 -0
  110. package/src/factory/sweep/states.mjs +87 -0
  111. package/src/factory/sweep/sweep-core.mjs +2009 -0
  112. package/src/factory/tracker/github.mjs +713 -0
  113. package/src/factory/tracker/operations.mjs +153 -0
  114. package/src/factory/upgrade/index.mjs +83 -0
  115. package/src/init.mjs +62 -24
  116. package/src/kit-owned-paths.mjs +1 -1
  117. package/src/stage/build.mjs +100 -0
  118. package/src/stage/factory-live.mjs +288 -0
  119. package/src/stage.mjs +100 -4
  120. package/src/upgrade.mjs +39 -7
@@ -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
+ }
@@ -0,0 +1,226 @@
1
+ // The Run Record of one Workflow-engine Stage run (#517, ADR 0036): `run-record/2`,
2
+ // `run.kind: "stage"`. Pure functions of data the kit produced, never of the
3
+ // agent's transcript: the Caller's inputs, the Launcher's exit code and usage
4
+ // file, and the head's Stage check. The record has no cost field and no free text.
5
+ //
6
+ // The orchestrate skill's safe-field check (`checkRecord` in
7
+ // .claude/skills/orchestrate/records.mjs) is the authority on what may be kept;
8
+ // `checkStageRecord` below is this job's own copy, run before every write, and
9
+ // scripts/factory-record.test.mjs holds the two in step. The job installs the
10
+ // published CLI and cannot import the skill.
11
+
12
+ import { parseUsage } from "../claims/release.mjs";
13
+
14
+ export const RECORD_SCHEMA = "run-record/2";
15
+ /** The engine's identity in the Sink path: GITHUB_TOKEN's own login, the one that writes the Stage check. */
16
+ export const ENGINE_LOGIN = "github-actions";
17
+ const STATUS_CREATOR = "github-actions[bot]";
18
+
19
+ export const STAGES = Object.freeze(["plan", "build", "review", "qa", "security"]);
20
+ const CHECKS = Object.freeze(["pending", "success", "failure", "error"]);
21
+ const EXITS = Object.freeze([
22
+ "completed",
23
+ "turn-cap",
24
+ "wall-clock",
25
+ "token-cap",
26
+ "crashed",
27
+ "no-result",
28
+ ]);
29
+ /** The Stage checks that exist: plan and build have none. */
30
+ const CHECK_CONTEXT = Object.freeze({
31
+ review: "factory/review",
32
+ qa: "factory/qa",
33
+ security: "factory/security",
34
+ });
35
+
36
+ const REPO = /^github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
37
+ /** An Orchestrate-engine run id: the skill's id pattern, behind `orc-`. */
38
+ export const ORC_ID = /^orc-[A-Za-z0-9][A-Za-z0-9._:-]{0,58}$/;
39
+ const WHOLE = /^(?:0|[1-9][0-9]{0,15})$/;
40
+ const SHA = /^[0-9a-f]{40}$/;
41
+ const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/;
42
+
43
+ const whole = (value, what, min = 0) => {
44
+ if (!WHOLE.test(String(value)) || Number(value) < min)
45
+ throw new Error(`not a whole number${min ? ` of ${min} or more` : ""}: ${what}`);
46
+ return Number(value);
47
+ };
48
+
49
+ /** What a run ended as, from the Launcher's exit code (a string; empty when it never ran) and its usage file text. */
50
+ export function exitOf({ stageCode, usageText }) {
51
+ const code = String(stageCode ?? "").trim();
52
+ if (code === "") return "no-result";
53
+ if (code === "0") return "completed";
54
+ if (code === "3") {
55
+ const stopped = usageText ? parseUsage(usageText)?.stopped : null;
56
+ if (stopped === "turns") return "turn-cap";
57
+ if (stopped === "minutes") return "wall-clock";
58
+ if (stopped === "tokens") return "token-cap";
59
+ }
60
+ return "crashed";
61
+ }
62
+
63
+ /**
64
+ * The record's path in the Sink. Throws on a repository, run id or attempt that
65
+ * is not plain, so nothing outside `records/github.com/<owner>/<repo>/` is named.
66
+ */
67
+ export function recordPath({ repo, runId, runAttempt }) {
68
+ if (!REPO.test(String(repo))) throw new Error(`not a github.com/<owner>/<repo> name: ${repo}`);
69
+ whole(runId, "run id", 1);
70
+ whole(runAttempt, "run attempt", 1);
71
+ return `records/${repo.toLowerCase()}/${ENGINE_LOGIN}/gha-${runId}-${runAttempt}.json`;
72
+ }
73
+
74
+ /**
75
+ * The Stage check on a head: the newest status of the Stage's context that the
76
+ * engine's own identity wrote (ADR 0035). `statuses` is the commit's status list,
77
+ * newest first. Null for a Stage with no check, no such status, or data that is
78
+ * not a list.
79
+ */
80
+ export function stageCheckOf({ statuses, stage }) {
81
+ const context = CHECK_CONTEXT[stage];
82
+ if (!context || !Array.isArray(statuses)) return null;
83
+ const mine = statuses.find(
84
+ (s) =>
85
+ s?.context === context && s?.creator?.login === STATUS_CREATOR && CHECKS.includes(s?.state),
86
+ );
87
+ return mine ? mine.state : null;
88
+ }
89
+
90
+ /**
91
+ * One Stage run's record. Every input is a string from the workflow (or empty
92
+ * for none) and is checked as plain data; a value that is not throws, so
93
+ * nothing malformed is ever written.
94
+ */
95
+ export function buildStageRecord({
96
+ repo,
97
+ runId,
98
+ runAttempt,
99
+ stage,
100
+ task,
101
+ attempt,
102
+ headSha = "",
103
+ parentRunId = "",
104
+ stageCheck = "",
105
+ stageCode = "",
106
+ usageText = "",
107
+ now,
108
+ }) {
109
+ recordPath({ repo, runId, runAttempt });
110
+ if (!STAGES.includes(stage)) throw new Error(`not a Stage: ${stage}`);
111
+ if (headSha !== "" && !SHA.test(headSha)) throw new Error("head is not a commit sha");
112
+ if (stageCheck !== "" && !CHECKS.includes(stageCheck))
113
+ throw new Error("Stage check is not a known state");
114
+ if (parentRunId !== "") whole(parentRunId, "parent run id", 1);
115
+ const usage = usageText ? parseUsage(usageText) : null;
116
+ // QA has no agent yet: it ends as its check says, and carries no count.
117
+ const exit =
118
+ stage === "qa"
119
+ ? stageCheck === "success" || stageCheck === "failure"
120
+ ? "completed"
121
+ : "no-result"
122
+ : exitOf({ stageCode, usageText });
123
+ const record = {
124
+ schema: RECORD_SCHEMA,
125
+ run: {
126
+ id: `gha-${runId}-${runAttempt}`,
127
+ repo: repo.toLowerCase(),
128
+ kind: "stage",
129
+ engine: "workflow",
130
+ stage,
131
+ task: whole(task, "task", 1),
132
+ head_sha: headSha === "" ? null : headSha,
133
+ attempt: whole(attempt, "attempt", 1),
134
+ parent_run_id: parentRunId === "" ? null : `gha-${parentRunId}`,
135
+ stage_check: stageCheck === "" ? null : stageCheck,
136
+ recorded_at: (now instanceof Date ? now : new Date(now))
137
+ .toISOString()
138
+ .replace(/\.\d+Z$/, "Z"),
139
+ exit,
140
+ ...(usage && stage !== "qa" ? { tokens: usage.tokens } : {}),
141
+ },
142
+ };
143
+ const problems = checkStageRecord(record);
144
+ if (problems.length) throw new Error(`not a safe Run Record: ${problems.join("; ")}`);
145
+ return record;
146
+ }
147
+
148
+ const RUN_KEYS = Object.freeze([
149
+ "id",
150
+ "repo",
151
+ "kind",
152
+ "engine",
153
+ "stage",
154
+ "task",
155
+ "head_sha",
156
+ "attempt",
157
+ "parent_run_id",
158
+ "stage_check",
159
+ "recorded_at",
160
+ "exit",
161
+ "tokens",
162
+ "model_requests",
163
+ "denials",
164
+ "duration_seconds",
165
+ "raw_upload",
166
+ ]);
167
+ const OPTIONAL = Object.freeze([
168
+ "tokens",
169
+ "model_requests",
170
+ "denials",
171
+ "duration_seconds",
172
+ "raw_upload",
173
+ ]);
174
+ const REQUIRED = RUN_KEYS.filter((key) => !OPTIONAL.includes(key));
175
+
176
+ /** This job's copy of the safe-field check for a Stage record: a closed shape of ids, numbers and enums. */
177
+ export function checkStageRecord(record) {
178
+ const problems = [];
179
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
180
+ if (!isObject(record)) return ["record: must be an object"];
181
+ for (const key of Object.keys(record))
182
+ if (!["schema", "run"].includes(key)) problems.push(`${key}: is outside the schema`);
183
+ if (record.schema !== RECORD_SCHEMA) problems.push(`schema: must be ${RECORD_SCHEMA}`);
184
+ const run = record.run;
185
+ if (!isObject(run)) return [...problems, "run: must be an object"];
186
+ for (const key of Object.keys(run))
187
+ if (!RUN_KEYS.includes(key)) problems.push(`run.${key}: is outside the schema`);
188
+ for (const key of REQUIRED) if (!Object.hasOwn(run, key)) problems.push(`run.${key}: is missing`);
189
+ const bad = (key, ok) => {
190
+ if (Object.hasOwn(run, key) && !ok) problems.push(`run.${key}: is not valid`);
191
+ };
192
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
193
+ // A Workflow-engine id is `gha-<run>-<attempt>`; an Orchestrate-engine id is `orc-<Claim nonce>`
194
+ // (and `orc-<nonce>-<delegation>` for a Delegation's run). The id says which engine wrote it.
195
+ bad(
196
+ "id",
197
+ typeof run.id === "string" &&
198
+ (run.engine === "orchestrate" ? ORC_ID : /^gha-[1-9][0-9]*-[1-9][0-9]*$/).test(run.id),
199
+ );
200
+ bad(
201
+ "repo",
202
+ typeof run.repo === "string" && REPO.test(run.repo) && run.repo === run.repo.toLowerCase(),
203
+ );
204
+ bad("kind", run.kind === "stage");
205
+ bad("engine", run.engine === "workflow" || run.engine === "orchestrate");
206
+ bad("stage", STAGES.includes(run.stage));
207
+ bad("task", int(run.task) && run.task >= 1);
208
+ bad(
209
+ "head_sha",
210
+ run.head_sha === null || (typeof run.head_sha === "string" && SHA.test(run.head_sha)),
211
+ );
212
+ bad("attempt", int(run.attempt) && run.attempt >= 1);
213
+ bad(
214
+ "parent_run_id",
215
+ run.parent_run_id === null ||
216
+ (typeof run.parent_run_id === "string" &&
217
+ (run.engine === "orchestrate" ? ORC_ID : /^gha-[1-9][0-9]*$/).test(run.parent_run_id)),
218
+ );
219
+ bad("raw_upload", typeof run.raw_upload === "boolean");
220
+ bad("stage_check", run.stage_check === null || CHECKS.includes(run.stage_check));
221
+ bad("recorded_at", typeof run.recorded_at === "string" && ISO.test(run.recorded_at));
222
+ bad("exit", EXITS.includes(run.exit));
223
+ for (const key of ["tokens", "model_requests", "denials", "duration_seconds"])
224
+ bad(key, int(run[key]));
225
+ return problems;
226
+ }
@@ -0,0 +1,57 @@
1
+ // The Sink write of a Stage's Run Record (#517): one create-only file in a
2
+ // private GitHub repository, with the Caller's secret, over the contents API.
3
+ // `fetch` is injected, so the tests never reach a network. The token goes only
4
+ // in the Authorization header: no result, error or log line ever holds it.
5
+
6
+ const API = "https://api.github.com";
7
+ const SINK_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
8
+
9
+ const headers = (token) => ({
10
+ authorization: `Bearer ${token}`,
11
+ accept: "application/vnd.github+json",
12
+ "x-github-api-version": "2022-11-28",
13
+ "user-agent": "agent-kit-factory-record",
14
+ });
15
+
16
+ /**
17
+ * Write `text` at `path` in the sink repo, never over anything. A sink that is
18
+ * not private gets nothing (there is no override). Identical bytes already there
19
+ * count as written; different bytes stop the write.
20
+ *
21
+ * @returns {Promise<{status: "created" | "already" | "different" | "not-private" | "error", detail?: string}>}
22
+ */
23
+ export async function writeRecord({ sink, path, text, fetch = globalThis.fetch }) {
24
+ if (!SINK_REPO.test(String(sink?.repo ?? "")))
25
+ return { status: "error", detail: "the sink is not an owner/repo name" };
26
+ const base = `${API}/repos/${sink.repo}`;
27
+ const init = { headers: headers(sink.token) };
28
+ try {
29
+ const repo = await fetch(base, init);
30
+ if (!repo.ok) return { status: "error", detail: `the sink could not be read (${repo.status})` };
31
+ if ((await repo.json()).private !== true) return { status: "not-private" };
32
+
33
+ const url = `${base}/contents/${path.split("/").map(encodeURIComponent).join("/")}`;
34
+ const there = await fetch(url, init);
35
+ if (there.ok) {
36
+ const file = await there.json();
37
+ const old = Buffer.from(String(file.content ?? ""), "base64").toString("utf8");
38
+ return { status: old === text ? "already" : "different" };
39
+ }
40
+ if (there.status !== 404)
41
+ return { status: "error", detail: `the sink path could not be read (${there.status})` };
42
+
43
+ const made = await fetch(url, {
44
+ method: "PUT",
45
+ headers: { ...headers(sink.token), "content-type": "application/json" },
46
+ body: JSON.stringify({
47
+ message: `record: ${path.split("/").at(-1)}`,
48
+ content: Buffer.from(text, "utf8").toString("base64"),
49
+ }),
50
+ });
51
+ return made.ok
52
+ ? { status: "created" }
53
+ : { status: "error", detail: `the write was refused (${made.status})` };
54
+ } catch (error) {
55
+ return { status: "error", detail: `the sink was not reachable (${error?.name ?? "error"})` };
56
+ }
57
+ }
@@ -0,0 +1,92 @@
1
+ // The whole report as one plain object (`factory-report/1`), from what the reads
2
+ // found. Pure: the tracker's evidence, the identity of the engine and the clock
3
+ // in, the report out, so a suite drives it over fixtures and `--json` prints it.
4
+
5
+ import { planApprovalFromConfig, UNREADABLE } from "../decision/plan.mjs";
6
+ import { WORKFLOW_ENGINE_NAME } from "../engine/workflow-engine.mjs";
7
+ import { mergeFromConfig } from "../gate/config.mjs";
8
+ import { DEFAULT_STAGE_LIMITS, stageLimits } from "../limits/limits.mjs";
9
+ import { bare, DAY, gateDecisions, isoOf, taskFacts } from "./facts.mjs";
10
+ import { gateSection } from "./gate-section.mjs";
11
+ import { computeMetrics } from "./metrics.mjs";
12
+ import { rolloutOf } from "./rollout.mjs";
13
+
14
+ export const REPORT_SCHEMA = "factory-report/1";
15
+
16
+ /** The tokens of a Stage's cap: the configured limit, else the starting one. */
17
+ function capOf(configText) {
18
+ return (stage, size) => {
19
+ const read = stageLimits({ configText, stage, size });
20
+ if (read.limits) return read.limits.tokens;
21
+ const fallback = DEFAULT_STAGE_LIMITS[stage];
22
+ return (stage === "build" ? fallback[size] : fallback).tokens;
23
+ };
24
+ }
25
+
26
+ /**
27
+ * @param {{ issues: object[], writers?: string[], configText?: string | null, configProblem?: string | null, killSwitch?: "true" | "false" | null, warnings?: string[] }} read
28
+ * @param {{ repo: string, identity: string, now: number, days: number, gate?: boolean }} options
29
+ */
30
+ export function buildReport(read, { repo, identity, now, days, gate = false }) {
31
+ const since = now - days * DAY;
32
+ const ctx = {
33
+ isEngine: (login) => bare(login) === bare(identity),
34
+ writers: new Set((read.writers ?? []).map((w) => String(w).toLowerCase())),
35
+ engineName: WORKFLOW_ENGINE_NAME,
36
+ cap: capOf(read.configText ?? null),
37
+ };
38
+ const terminal = (read.issues ?? []).filter((i) => {
39
+ const closed = Date.parse(i.closedAt);
40
+ return i.state === "CLOSED" && closed >= since && closed <= now;
41
+ });
42
+ const tasks = terminal.map((i) => taskFacts(i, ctx));
43
+ const metrics = computeMetrics(tasks, now);
44
+ const gateRead = gateSection(
45
+ terminal.flatMap((i) => gateDecisions(i, ctx)),
46
+ { now },
47
+ );
48
+
49
+ const problems = [];
50
+ const text = read.configProblem ? UNREADABLE : (read.configText ?? null);
51
+ const approval = planApprovalFromConfig(text);
52
+ const merge = mergeFromConfig(text);
53
+ if (read.configProblem) problems.push("the factory config could not be read");
54
+ else {
55
+ if (approval.problem) problems.push(approval.problem);
56
+ if (merge.problem) problems.push(merge.problem);
57
+ }
58
+ const effective = {
59
+ kill_switch: read.killSwitch ?? null,
60
+ plan_approval: approval.value,
61
+ merge_mode: merge.value.mode,
62
+ auto_tiers: merge.value.auto_tiers,
63
+ };
64
+ const rollout = problems.length
65
+ ? { phase: null, name: null, candidates: [], effective, next: null, problems }
66
+ : {
67
+ ...rolloutOf({
68
+ effective: {
69
+ killSwitch: effective.kill_switch,
70
+ planApproval: effective.plan_approval,
71
+ mergeMode: effective.merge_mode,
72
+ autoTiers: effective.auto_tiers,
73
+ },
74
+ tasks,
75
+ gate: gateRead,
76
+ }),
77
+ problems,
78
+ };
79
+ // `effective` is spelled the same way in both branches.
80
+ rollout.effective = effective;
81
+
82
+ return {
83
+ schema: REPORT_SCHEMA,
84
+ repo,
85
+ generated_at: isoOf(now),
86
+ window: { since: isoOf(since), until: isoOf(now), days },
87
+ ...metrics,
88
+ rollout,
89
+ ...(gate ? { gate: gateRead } : {}),
90
+ warnings: read.warnings ?? [],
91
+ };
92
+ }
@@ -0,0 +1,80 @@
1
+ // `agent-kit factory report [--since 30d] [--json] [--gate]`: how the Factory is
2
+ // doing, from the tracker alone and the maintainer's own `gh` (ADR 0044). It
3
+ // reads and never posts: every `gh` call is a GET or a GraphQL query.
4
+ //
5
+ // Who the engine is: `github-actions[bot]` (the Workflow engine's identity), or
6
+ // AGENT_KIT_FACTORY_IDENTITY when the Factory runs as another login. This is not
7
+ // the maintainer's own login, which the report never needs.
8
+
9
+ import { WORKFLOW_IDENTITY } from "../engine/workflow-engine.mjs";
10
+ import { buildReport } from "./build.mjs";
11
+ import { DAY } from "./facts.mjs";
12
+ import { readTracker } from "./reads.mjs";
13
+ import { renderJson, renderText } from "./render.mjs";
14
+
15
+ const SINCE = /^([1-9][0-9]{0,3})d$/;
16
+ const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
17
+
18
+ /** `30d` is 30 days; anything else is not a window. */
19
+ export function parseSince(value) {
20
+ const m = SINCE.exec(String(value ?? "30d"));
21
+ return m ? Number(m[1]) : null;
22
+ }
23
+
24
+ /**
25
+ * @param {{
26
+ * runner: (cmd: string, args: string[]) => { status: number | null, stdout: string, stderr: string },
27
+ * env: Record<string, string | undefined>,
28
+ * repo?: string, since?: string, json?: boolean, gate?: boolean,
29
+ * clock?: () => number,
30
+ * out: (line: string) => void, err: (line: string) => void,
31
+ * }} io
32
+ * @returns {number} 0 reported, 1 a read failed, 2 not runnable
33
+ */
34
+ export function runFactoryReport({
35
+ runner,
36
+ env,
37
+ repo,
38
+ since,
39
+ json = false,
40
+ gate = false,
41
+ clock = Date.now,
42
+ out,
43
+ err,
44
+ }) {
45
+ const days = parseSince(since);
46
+ if (days === null) {
47
+ err(`factory report: --since is a number of days such as 30d, got ${JSON.stringify(since)}`);
48
+ return 2;
49
+ }
50
+ const gh = (args) => runner("gh", args);
51
+ let slug = repo ?? env.GITHUB_REPOSITORY;
52
+ if (!slug) {
53
+ const view = gh(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"]);
54
+ if (view.status === 0) slug = view.stdout.trim();
55
+ }
56
+ if (!slug || !REPO.test(slug)) {
57
+ err(`factory report: no repository (pass --repo owner/name), got ${JSON.stringify(slug)}`);
58
+ return 2;
59
+ }
60
+ const identity = env.AGENT_KIT_FACTORY_IDENTITY || WORKFLOW_IDENTITY;
61
+ const now = clock();
62
+ let read;
63
+ try {
64
+ // With --json the one thing on stdout is the report, so progress goes nowhere.
65
+ read = readTracker({
66
+ gh,
67
+ repo: slug,
68
+ since: now - days * DAY,
69
+ env,
70
+ identity,
71
+ log: json ? () => {} : out,
72
+ });
73
+ } catch (error) {
74
+ err(`factory report: ${error.message}`);
75
+ return 1;
76
+ }
77
+ const report = buildReport(read, { repo: slug, identity, now, days, gate });
78
+ out(json ? renderJson(report) : renderText(report));
79
+ return 0;
80
+ }