@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,39 @@
1
+ // Which harnesses a Factory Stage may run on (#515, spec #500 story 79): only
2
+ // one whose model traffic the Launcher's model proxy can front (ADR 0023), so
3
+ // every Stage's tokens are counted by the kit and its cap is enforced from
4
+ // outside the sandbox. A harness the proxy cannot front holds its own key in
5
+ // the sandbox and the proxy reads no usage, so it is refused here with a named
6
+ // reason, before the agent starts. Cursor CLI is the one built-in harness so
7
+ // refused (its requests all go through Cursor's own backend: cli/src/harness/cursor.mjs).
8
+ // A Custom harness names a provider profile, which the proxy fronts.
9
+
10
+ /** The built-in harnesses the model proxy fronts. */
11
+ export const PROXY_FRONTED = Object.freeze([
12
+ "claude-code",
13
+ "codex",
14
+ "gemini",
15
+ // Its Google sign-in cannot be fronted, so it takes the Gemini API key (ADR 0024).
16
+ "antigravity",
17
+ "opencode",
18
+ ]);
19
+
20
+ /** The built-in harnesses it cannot, and why. */
21
+ export const REFUSED = Object.freeze({
22
+ cursor:
23
+ "Cursor CLI cannot be fronted by the model proxy: its requests go through Cursor's own backend and its key would sit in the sandbox, so its tokens cannot be counted or capped from outside it.",
24
+ });
25
+
26
+ const CUSTOM = /^custom:[A-Za-z0-9][A-Za-z0-9._-]*$/;
27
+
28
+ /**
29
+ * @returns {{ ok: true } | { ok: false, reason: string }}
30
+ */
31
+ export function checkFactoryHarness(harness) {
32
+ const name = String(harness ?? "");
33
+ if (PROXY_FRONTED.includes(name) || CUSTOM.test(name)) return { ok: true };
34
+ if (Object.hasOwn(REFUSED, name)) return { ok: false, reason: REFUSED[name] };
35
+ return {
36
+ ok: false,
37
+ reason: `${JSON.stringify(name.slice(0, 40))} is not a harness the Factory knows, so the model proxy cannot be said to front it.`,
38
+ };
39
+ }
@@ -0,0 +1,123 @@
1
+ // `limits.<stage>` (turns, minutes, tokens) of the factory config, as the flags
2
+ // the Launcher enforces from outside the sandbox (#515), and the Task size that
3
+ // picks the build's row. Pure: the config's text and the plan's header come in,
4
+ // flags or a named refusal go out. A config that is not readable refuses the
5
+ // run rather than loosen a limit (a typo can only cost a Stage, never spend).
6
+ //
7
+ // The Launcher's own flags do the enforcing (cli/src/deep-scan/limits.mjs): the
8
+ // turn count by the harness's turn limit, the minutes by the Launcher's wall
9
+ // clock, the tokens by the model proxy's cap. A fired limit exits 3 and the
10
+ // usage file says which; the run counts as one Attempt.
11
+
12
+ export const LIMIT_STAGES = Object.freeze(["plan", "build", "review", "qa", "security"]);
13
+ export const TASK_SIZES = Object.freeze(["s", "m", "l"]);
14
+
15
+ const limitsRow = (turns, minutes, tokens) => Object.freeze({ turns, minutes, tokens });
16
+
17
+ /** The starting limits, the same as `examples/factory/factory-config.json`. */
18
+ export const DEFAULT_STAGE_LIMITS = Object.freeze({
19
+ plan: limitsRow(40, 30, 1_000_000),
20
+ build: Object.freeze({
21
+ s: limitsRow(80, 60, 2_000_000),
22
+ m: limitsRow(120, 90, 4_000_000),
23
+ l: limitsRow(160, 120, 8_000_000),
24
+ }),
25
+ review: limitsRow(40, 45, 1_000_000),
26
+ qa: limitsRow(60, 45, 2_000_000),
27
+ security: limitsRow(60, 45, 2_000_000),
28
+ });
29
+
30
+ const wholeNumber = (v) => Number.isSafeInteger(v) && v > 0;
31
+ export const LIMIT_MAX_MINUTES = Math.floor((2 ** 31 - 1) / 60_000);
32
+
33
+ function checkLimitsRow(value, where) {
34
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
35
+ return { error: `${where} is not an object of turns, minutes and tokens` };
36
+ }
37
+ const extra = Object.keys(value).filter((k) => !["turns", "minutes", "tokens"].includes(k));
38
+ if (extra.length) return { error: `${where} has a key that is not a limit: ${extra[0]}` };
39
+ for (const key of ["turns", "minutes", "tokens"]) {
40
+ const v = value[key];
41
+ if (!wholeNumber(v) || (key === "minutes" && v > LIMIT_MAX_MINUTES)) {
42
+ return { error: `${where}.${key} must be a wholeNumber number of 1 or more` };
43
+ }
44
+ }
45
+ return { limits: { turns: value.turns, minutes: value.minutes, tokens: value.tokens } };
46
+ }
47
+
48
+ /**
49
+ * The limits of `stage` from the config's text (null: the file is absent, so the
50
+ * defaults). `size` is the Task size and is needed for `build` alone.
51
+ * @returns {{ limits: { turns: number, minutes: number, tokens: number } } | { error: string }}
52
+ */
53
+ export function stageLimits({ configText, stage, size }) {
54
+ if (!LIMIT_STAGES.includes(stage)) return { error: `${JSON.stringify(stage)} is not a Stage` };
55
+ let configured;
56
+ if (configText === null || configText === undefined) {
57
+ configured = DEFAULT_STAGE_LIMITS;
58
+ } else {
59
+ let data;
60
+ try {
61
+ data = JSON.parse(String(configText));
62
+ } catch {
63
+ return { error: "the factory config is not JSON" };
64
+ }
65
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
66
+ return { error: "the factory config is not an object" };
67
+ }
68
+ const limits = data.limits;
69
+ if (limits !== undefined && (limits === null || typeof limits !== "object")) {
70
+ return { error: "limits is not an object" };
71
+ }
72
+ configured = { ...DEFAULT_STAGE_LIMITS, ...(limits ?? {}) };
73
+ }
74
+ const value = configured[stage];
75
+ if (stage !== "build") return checkLimitsRow(value, `limits.${stage}`);
76
+ if (!TASK_SIZES.includes(size))
77
+ return { error: `the Task size is ${JSON.stringify(size)}, not s, m or l` };
78
+ if (value === null || typeof value !== "object")
79
+ return { error: "limits.build is not an object" };
80
+ return checkLimitsRow(value[size], `limits.build.${size}`);
81
+ }
82
+
83
+ /** The Launcher's flags for a limits row, as separate arguments. */
84
+ export function limitFlags({ turns, minutes, tokens }) {
85
+ return [
86
+ "--max-turns",
87
+ String(turns),
88
+ "--max-tokens",
89
+ String(tokens),
90
+ "--scan-minutes",
91
+ String(minutes),
92
+ ];
93
+ }
94
+
95
+ const SIZE_ANSWER = /^size\s*[:=]?\s*([sml])\s*\.?$/i;
96
+
97
+ /**
98
+ * The Task size the build runs at: the size in the latest plan's header, raised
99
+ * only by a person's answer. `answers` are the `A<n>:` answers of the latest
100
+ * answered Decision Request that follows that plan (the caller reads them from
101
+ * writers alone); one reading `size: m` or `size: l` raises the size when it is
102
+ * larger. A lower answer, an answer of anyone's other, and text in the plan or
103
+ * the builder's own output never change it.
104
+ * @param {{ header: { size?: string } | null, answers?: Array<{ n: number, answer: string }> }} input
105
+ * @returns {{ size: string, raisedBy?: string } | { error: string }}
106
+ */
107
+ export function taskSizeOf({ header, answers = [] }) {
108
+ if (!header || !TASK_SIZES.includes(header.size)) {
109
+ return { error: "the latest plan has no valid Task size" };
110
+ }
111
+ let size = header.size;
112
+ let raisedBy;
113
+ for (const { n, answer } of answers) {
114
+ const match = SIZE_ANSWER.exec(String(answer ?? "").trim());
115
+ if (!match) continue;
116
+ const asked = match[1].toLowerCase();
117
+ if (TASK_SIZES.indexOf(asked) > TASK_SIZES.indexOf(size)) {
118
+ size = asked;
119
+ raisedBy = `A${n}`;
120
+ }
121
+ }
122
+ return raisedBy ? { size, raisedBy } : { size };
123
+ }
@@ -0,0 +1,172 @@
1
+ // The merge gate's two trusted steps, run by the `factory-merge` Caller (spec #500,
2
+ // ADR 0041), each in its own job step with its own token:
3
+ //
4
+ // merge-run holds the App token. Re-checks that the pull request is open at
5
+ // the exact head the gate judged, then runs
6
+ // `gh pr merge <n> --match-head-commit <sha> --<method>`: GitHub itself
7
+ // refuses the merge if the head moved. Never `--admin`, never `--auto`
8
+ // (GitHub's native auto-merge), never a merge queue.
9
+ // merge-record holds `GITHUB_TOKEN`. Once GitHub says the pull request merged at
10
+ // that head, it rewrites the engine's gate comment to "merged at
11
+ // `<sha>`", which is how `factory report` tells a gate merge from a
12
+ // person's. Statuses and comments stay on one identity, the engine's.
13
+ //
14
+ // A merge job that finds the pull request already merged at that head (a second
15
+ // dispatch for the same decision) records and exits 0. Any other state is an error.
16
+
17
+ import { MERGING_TEXT, parseGateComment, renderMergedComment } from "../gate/comment.mjs";
18
+ import { createGithubTracker } from "../tracker/github.mjs";
19
+
20
+ const MERGE_SHA = /^[0-9a-f]{40}$/;
21
+ const MERGE_METHODS = ["squash", "merge", "rebase"];
22
+ const MERGE_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
23
+
24
+ function parseMergeFlags(args) {
25
+ const out = {};
26
+ for (let i = 0; i < args.length; i += 2) {
27
+ if (!args[i].startsWith("--")) throw new Error(`unexpected ${JSON.stringify(args[i])}`);
28
+ out[args[i].slice(2)] = args[i + 1];
29
+ }
30
+ return out;
31
+ }
32
+
33
+ function mergeTarget({ args, env, err, name }) {
34
+ let flags;
35
+ try {
36
+ flags = parseMergeFlags(args);
37
+ } catch (error) {
38
+ err(`${name}: ${error.message}`);
39
+ return null;
40
+ }
41
+ const repo = flags.repo ?? env.GITHUB_REPOSITORY;
42
+ const pull = Number(flags.pull);
43
+ const issue = Number(flags.issue);
44
+ if (!repo || !MERGE_REPO.test(repo)) return (err(`${name}: no repository`), null);
45
+ if (!Number.isInteger(pull) || pull < 1) return (err(`${name}: --pull is a number`), null);
46
+ if (!MERGE_SHA.test(String(flags.head)))
47
+ return (err(`${name}: --head is a full commit sha`), null);
48
+ if (name === "merge-run" && !MERGE_METHODS.includes(flags.method)) {
49
+ return (err(`${name}: --method is one of ${MERGE_METHODS.join(", ")}`), null);
50
+ }
51
+ if (!Number.isInteger(issue) || issue < 1) return (err(`${name}: --issue is a number`), null);
52
+ return { repo, pull, issue, head: flags.head, method: flags.method };
53
+ }
54
+
55
+ const mergePullOf = (gh, repo, pull) => {
56
+ const r = gh(["api", `repos/${repo}/pulls/${pull}`]);
57
+ if (r.status !== 0)
58
+ throw new Error(`reading #${pull} failed: ${String(r.stderr).trim().slice(0, 300)}`);
59
+ const d = JSON.parse(r.stdout);
60
+ return {
61
+ state: d.merged ? "MERGED" : d.state === "open" ? "OPEN" : "CLOSED",
62
+ head: d.head?.sha,
63
+ branch: d.head?.ref ?? "",
64
+ // The gate merges with the App's token, so its merge is a bot's; a person's is not.
65
+ mergedByBot: d.merged_by?.type === "Bot",
66
+ };
67
+ };
68
+
69
+ const loginKey = (login) =>
70
+ String(login ?? "")
71
+ .toLowerCase()
72
+ .replace(/\[bot\]$/, "");
73
+
74
+ /** The engine's newest gate comment judging `head`, or null. */
75
+ function gateCommentFor({ gh, env, t }) {
76
+ const tracker = createGithubTracker({ gh, repo: t.repo });
77
+ const identity = loginKey(env.AGENT_KIT_FACTORY_IDENTITY || "github-actions[bot]");
78
+ return (
79
+ tracker
80
+ .readComments(t.pull)
81
+ .filter((c) => loginKey(c.author) === identity && parseGateComment(c.body)?.head === t.head)
82
+ .at(-1) ?? null
83
+ );
84
+ }
85
+
86
+ /** @returns {number} 0 merged (or already merged at that head), 1 refused or failed, 2 bad input */
87
+ export function runMergeRun({ gh, env, args, out, err }) {
88
+ const t = mergeTarget({ args, env, err, name: "merge-run" });
89
+ if (!t) return 2;
90
+ let pull;
91
+ try {
92
+ pull = mergePullOf(gh, t.repo, t.pull);
93
+ } catch (error) {
94
+ err(`merge-run: ${error.message}`);
95
+ return 1;
96
+ }
97
+ if (pull.state === "MERGED" && pull.head === t.head) {
98
+ out(`merge-run: #${t.pull} is already merged at ${t.head}`);
99
+ return 0;
100
+ }
101
+ // The job never trusts its inputs: the pull request must be this task's own build branch,
102
+ // and the engine's gate comment must say it decided to merge exactly this head.
103
+ if (!new RegExp(`^factory/${t.issue}/attempt-\\d+$`).test(pull.branch)) {
104
+ err(`merge-run: refused: #${t.pull} is on ${pull.branch}, not a build branch of #${t.issue}`);
105
+ return 1;
106
+ }
107
+ let decided;
108
+ try {
109
+ decided = gateCommentFor({ gh, env, t });
110
+ } catch (error) {
111
+ err(`merge-run: ${error.message}`);
112
+ return 1;
113
+ }
114
+ if (!decided || !decided.body.includes(MERGING_TEXT)) {
115
+ err(`merge-run: refused: the gate's comment on #${t.pull} does not say it merges ${t.head}`);
116
+ return 1;
117
+ }
118
+ if (pull.state !== "OPEN" || pull.head !== t.head) {
119
+ err(
120
+ `merge-run: refused: #${t.pull} is ${pull.state} at ${pull.head}, not open at ${t.head}; the gate judges the new head on its next sweep`,
121
+ );
122
+ return 1;
123
+ }
124
+ const merged = gh([
125
+ "pr",
126
+ "merge",
127
+ String(t.pull),
128
+ "--repo",
129
+ t.repo,
130
+ "--match-head-commit",
131
+ t.head,
132
+ `--${t.method}`,
133
+ ]);
134
+ if (merged.status !== 0) {
135
+ err(`merge-run: gh pr merge failed: ${String(merged.stderr).trim().slice(0, 300)}`);
136
+ return 1;
137
+ }
138
+ out(`merge-run: merged #${t.pull} at ${t.head} (${t.method})`);
139
+ return 0;
140
+ }
141
+
142
+ /** @returns {number} 0 recorded, 1 not merged at that head or the comment is not the gate's, 2 bad input */
143
+ export function runMergeRecord({ gh, env, args, out, err }) {
144
+ const t = mergeTarget({ args, env, err, name: "merge-record" });
145
+ if (!t) return 2;
146
+ try {
147
+ const pull = mergePullOf(gh, t.repo, t.pull);
148
+ if (pull.state !== "MERGED" || pull.head !== t.head) {
149
+ err(`merge-record: #${t.pull} is not merged at ${t.head}: nothing recorded`);
150
+ return 1;
151
+ }
152
+ // A person's merge stays a person's: only a merge made with the App's token is the gate's.
153
+ if (!pull.mergedByBot) {
154
+ err(`merge-record: #${t.pull} was not merged by the App: nothing recorded`);
155
+ return 1;
156
+ }
157
+ const tracker = createGithubTracker({ gh, repo: t.repo });
158
+ const mine = gateCommentFor({ gh, env, t });
159
+ const comment = mine && renderMergedComment(mine.body, t.head) ? mine : null;
160
+ if (!comment) {
161
+ err(`merge-record: no gate comment of the engine's judges ${t.head}: nothing recorded`);
162
+ return 1;
163
+ }
164
+ const body = renderMergedComment(comment.body, t.head);
165
+ if (body !== comment.body) tracker.editComment(comment.id, body);
166
+ out(`merge-record: the gate comment of #${t.pull} reads merged at ${t.head}`);
167
+ return 0;
168
+ } catch (error) {
169
+ err(`merge-record: ${error.message}`);
170
+ return 1;
171
+ }
172
+ }
@@ -0,0 +1,240 @@
1
+ // The Outbox entry checker (spec #500, ADR 0039, ADR 0026's trusted step made
2
+ // continuous): a pure function from the Chief of Staff's Outbox entries and what the
3
+ // engine knows to the entries it will act on and the ones it refuses, each with a
4
+ // reason. Nothing here reads a file, runs git or touches GitHub: the engine hands in
5
+ // the changed paths of each bundle it has already read as git objects.
6
+ //
7
+ // Eight kinds, and no other: delegate, message, cancel, push, pr, reply, ruling, result.
8
+ // There is no kind that writes a label, an issue comment, a status or a merge: those
9
+ // belong to the Dispatcher and the gate. A refusal comes back in the next Snapshot and
10
+ // is never an Attempt. Contract suite: scripts/factory-outbox-check.test.mjs over
11
+ // scripts/fixtures/factory/outbox/.
12
+
13
+ import { checkAllowedPaths } from "../checks/allowed-paths.mjs";
14
+ import { STAGE_SHA } from "../checks/stage-check.mjs";
15
+ import { rulingProblems } from "./rulings.mjs";
16
+
17
+ export const OUTBOX_KINDS = Object.freeze([
18
+ "delegate",
19
+ "message",
20
+ "cancel",
21
+ "push",
22
+ "pr",
23
+ "reply",
24
+ "ruling",
25
+ "result",
26
+ ]);
27
+ export const RESULTS = Object.freeze(["done", "questions", "failed"]);
28
+ export const OUTBOX_CAPS = Object.freeze({
29
+ brief: 40_000,
30
+ text: 8_000,
31
+ title: 200,
32
+ body: 20_000,
33
+ question: 500,
34
+ summary: 2_000,
35
+ });
36
+ export const MAX_DELEGATIONS = 8;
37
+ export const MAX_QUESTIONS = 12;
38
+
39
+ const DELEGATION_ID = /^d[1-9][0-9]{0,2}$/;
40
+ const FULL_SHA = STAGE_SHA;
41
+ const THREAD_ID = /^[A-Za-z0-9_=-]{1,128}$/;
42
+ const KEYS = {
43
+ delegate: ["kind", "id", "brief"],
44
+ message: ["kind", "to", "text"],
45
+ cancel: ["kind", "id"],
46
+ push: ["kind", "bundle", "base", "head", "branch"],
47
+ pr: ["kind", "title", "body", "number"],
48
+ reply: ["kind", "thread", "text"],
49
+ ruling: ["kind", "id", "question", "options", "choice", "reason", "evidence"],
50
+ result: ["kind", "result", "summary", "questions", "head", "regate"],
51
+ };
52
+
53
+ const nonEmpty = (v, cap) => typeof v === "string" && v.trim() !== "" && v.length <= cap;
54
+ const safeRelative = (p) =>
55
+ typeof p === "string" &&
56
+ p !== "" &&
57
+ p.length <= 300 &&
58
+ !p.startsWith("/") &&
59
+ !/[\\\u0000-\u001f\u007f]/.test(p) &&
60
+ p.split("/").every((s) => s !== "" && s !== "." && s !== "..");
61
+
62
+ /**
63
+ * @typedef {object} OutboxContext what the engine knows when it reads the Outbox
64
+ * @property {number} issue the task's issue
65
+ * @property {string} repo `owner/name`
66
+ * @property {string} branch the Attempt's branch, `factory/<issue>/attempt-<n>`: the only one a push may reach
67
+ * @property {string} baseSha the commit the branch starts from
68
+ * @property {string[]} allowedPaths the plan's Allowed paths
69
+ * @property {{ number: number, head: string, ci: string | null, closes: boolean } | null} pull the task's pull request, once open: its head, its checks' rollup, and whether its body closes the issue
70
+ * @property {string | null} [pushedHead] the tip the last accepted push left on the branch
71
+ * @property {Array<{ id: string, state: "running" | "done" | "failed" | "cancelled" }>} delegations
72
+ * @property {string[]} threads ids of the pull request's review threads
73
+ * @property {string[]} rulings ids of the Rulings already made
74
+ * @property {Record<string, string[] | null>} bundlePaths bundle path -> the paths its commits change (null: unreadable)
75
+ * @property {boolean} [resulted] a `result` entry was already accepted
76
+ */
77
+
78
+ /**
79
+ * @param {unknown[]} entries the Outbox entries, in order
80
+ * @param {OutboxContext} ctx
81
+ * @returns {{ accepted: Array<{ index: number, entry: object }>, refused: Array<{ index: number, kind: string, reason: string }> }}
82
+ */
83
+ export function checkOutbox(entries, ctx) {
84
+ const accepted = [];
85
+ const refused = [];
86
+ const delegations = new Map(ctx.delegations.map((d) => [d.id, d.state]));
87
+ const rulings = [...ctx.rulings];
88
+ let resulted = Boolean(ctx.resulted);
89
+ let pushedHead = ctx.pushedHead ?? null;
90
+ let live = [...delegations.values()].filter((s) => s === "running").length;
91
+
92
+ entries.forEach((raw, index) => {
93
+ const kind = typeof raw?.kind === "string" ? raw.kind : "";
94
+ const refuse = (reason) => refused.push({ index, kind: kind || "unknown", reason });
95
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
96
+ return refuse("an entry is an object");
97
+ if (!OUTBOX_KINDS.includes(kind)) {
98
+ return refuse(
99
+ `kind ${JSON.stringify(kind.slice(0, 40))} is not one of ${OUTBOX_KINDS.join(", ")}`,
100
+ );
101
+ }
102
+ const stray = Object.keys(raw).filter((k) => !KEYS[kind].includes(k));
103
+ if (stray.length) return refuse(`${kind} has no key ${JSON.stringify(stray[0].slice(0, 40))}`);
104
+ if (resulted) return refuse("an entry after the result: the Stage has ended");
105
+
106
+ switch (kind) {
107
+ case "delegate": {
108
+ if (!DELEGATION_ID.test(raw.id ?? "")) return refuse("a delegation id is d<n>");
109
+ if (delegations.has(raw.id)) return refuse(`${raw.id} already exists`);
110
+ if (!nonEmpty(raw.brief, OUTBOX_CAPS.brief))
111
+ return refuse("the brief is empty or too long");
112
+ if (live >= MAX_DELEGATIONS)
113
+ return refuse(`at most ${MAX_DELEGATIONS} delegations run at once`);
114
+ delegations.set(raw.id, "running");
115
+ live += 1;
116
+ break;
117
+ }
118
+ case "message": {
119
+ if (delegations.get(raw.to) !== "running")
120
+ return refuse(
121
+ `${JSON.stringify(String(raw.to).slice(0, 20))} is not a running delegation`,
122
+ );
123
+ if (!nonEmpty(raw.text, OUTBOX_CAPS.text))
124
+ return refuse("the message is empty or too long");
125
+ break;
126
+ }
127
+ case "cancel": {
128
+ if (delegations.get(raw.id) !== "running")
129
+ return refuse(
130
+ `${JSON.stringify(String(raw.id).slice(0, 20))} is not a running delegation`,
131
+ );
132
+ delegations.set(raw.id, "cancelled");
133
+ live -= 1;
134
+ break;
135
+ }
136
+ case "push": {
137
+ if (!safeRelative(raw.bundle))
138
+ return refuse("the bundle is a relative path inside the outbox");
139
+ if (!FULL_SHA.test(raw.base ?? "")) return refuse("base is a full commit sha");
140
+ if (raw.base !== ctx.baseSha)
141
+ return refuse("base is not the commit this Attempt starts from");
142
+ // The branch is the engine's: an entry may name it, never another.
143
+ if (raw.branch !== undefined && raw.branch !== ctx.branch) {
144
+ return refuse(`a push reaches ${ctx.branch} only`);
145
+ }
146
+ const paths = ctx.bundlePaths?.[raw.bundle];
147
+ if (!Array.isArray(paths)) return refuse("the bundle could not be read as git objects");
148
+ if (paths.length === 0) return refuse("the bundle changes no file");
149
+ const verdict = checkAllowedPaths({ allowedPaths: ctx.allowedPaths, changedPaths: paths });
150
+ if (!verdict.ok) {
151
+ const shown = verdict.outside.slice(0, 5).join(", ");
152
+ return refuse(
153
+ `the push changes ${verdict.outside.length} path(s) outside the plan's Allowed paths: ${shown}`,
154
+ );
155
+ }
156
+ pushedHead = raw.head;
157
+ break;
158
+ }
159
+ case "pr": {
160
+ if (pushedHead === null) return refuse("a pull request follows a push");
161
+ if (raw.number !== undefined && raw.number !== (ctx.pull?.number ?? null)) {
162
+ return refuse("a pull request entry reaches this task's own pull request only");
163
+ }
164
+ if (!nonEmpty(raw.title, OUTBOX_CAPS.title))
165
+ return refuse("the title is empty or too long");
166
+ if (typeof raw.body !== "string" || raw.body.length > OUTBOX_CAPS.body)
167
+ return refuse("the body is not text or is too long");
168
+ break;
169
+ }
170
+ case "reply": {
171
+ if (!THREAD_ID.test(raw.thread ?? "") || !ctx.threads.includes(raw.thread)) {
172
+ return refuse("a reply goes to a review thread of this pull request");
173
+ }
174
+ if (!nonEmpty(raw.text, OUTBOX_CAPS.text)) return refuse("the reply is empty or too long");
175
+ break;
176
+ }
177
+ case "ruling": {
178
+ const problems = rulingProblems(raw, { repo: ctx.repo, earlier: rulings });
179
+ if (problems.length) return refuse(problems[0]);
180
+ rulings.push(raw.id);
181
+ break;
182
+ }
183
+ case "result": {
184
+ if (!RESULTS.includes(raw.result)) return refuse(`result is one of ${RESULTS.join(", ")}`);
185
+ if (raw.summary !== undefined && !nonEmpty(raw.summary, OUTBOX_CAPS.summary))
186
+ return refuse("the summary is empty or too long");
187
+ if (raw.result === "questions") {
188
+ const q = raw.questions;
189
+ if (!Array.isArray(q) || q.length === 0 || q.length > MAX_QUESTIONS) {
190
+ return refuse(`a questions result holds one to ${MAX_QUESTIONS} questions`);
191
+ }
192
+ for (const item of q) {
193
+ const ok =
194
+ item &&
195
+ typeof item === "object" &&
196
+ nonEmpty(item.question, OUTBOX_CAPS.question) &&
197
+ Array.isArray(item.options) &&
198
+ item.options.length >= 2 &&
199
+ item.options.length <= 6 &&
200
+ item.options.every((o) => nonEmpty(o, 200)) &&
201
+ nonEmpty(item.recommendation, 300) &&
202
+ typeof item.evidence === "string" &&
203
+ item.evidence.length <= 1000;
204
+ if (!ok)
205
+ return refuse(
206
+ "each question has the question, two to six options, a recommendation and its evidence",
207
+ );
208
+ }
209
+ } else if (raw.questions !== undefined) {
210
+ return refuse("only a questions result carries questions");
211
+ }
212
+ if (raw.result === "done") {
213
+ // A build ends only on a verified head: pushed, a pull request that closes the
214
+ // issue, green CI on that head, and the re-gate passed. The engine reads the
215
+ // pull request itself; the Chief of Staff's word is only the re-gate and the head.
216
+ if (!FULL_SHA.test(raw.head ?? "")) return refuse("done names the head it verified");
217
+ if (raw.regate !== "passed") return refuse("done needs the re-gate passed on that head");
218
+ if (pushedHead === null) return refuse("done follows a push");
219
+ if (raw.head !== pushedHead)
220
+ return refuse("done names a head that is not the one pushed");
221
+ if (!ctx.pull) return refuse("done follows an open pull request");
222
+ if (ctx.pull.head !== raw.head)
223
+ return refuse("the pull request's head is not the head done names");
224
+ if (!ctx.pull.closes) return refuse(`the pull request does not close #${ctx.issue}`);
225
+ if (ctx.pull.ci !== "SUCCESS") {
226
+ return refuse(
227
+ `done needs green CI on the head, and it is ${ctx.pull.ci ?? "not reported yet"}`,
228
+ );
229
+ }
230
+ } else if (raw.head !== undefined || raw.regate !== undefined) {
231
+ return refuse("only a done result names a head and the re-gate");
232
+ }
233
+ resulted = true;
234
+ break;
235
+ }
236
+ }
237
+ accepted.push({ index, entry: raw });
238
+ });
239
+ return { accepted, refused };
240
+ }