@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,195 @@
1
+ // The Chief of Staff's Rulings in factory mode (spec #500, ADR 0040): what counts as
2
+ // evidence, the trusted block the engine renders into the pull request body, and the
3
+ // reader the review Stage uses to hold each Ruling against its evidence. Pure: no IO.
4
+ // Contract suite: scripts/factory-outbox-rulings.test.mjs over
5
+ // scripts/fixtures/factory/outbox/rulings/.
6
+ //
7
+ // A factory Ruling cites only what GitHub still shows: `path:line@SHA`, a tracker
8
+ // permalink, a check or Actions run link, or an earlier Ruling's id. Local command
9
+ // output dies with the sandbox, so it is not evidence.
10
+
11
+ import { untrustedText } from "../checks/plan-header.mjs";
12
+
13
+ export const RULING_ID = /^R[1-9][0-9]{0,3}$/;
14
+ export const RULING_CAPS = Object.freeze({
15
+ question: 500,
16
+ option: 200,
17
+ choice: 200,
18
+ reason: 1500,
19
+ evidence: 300,
20
+ });
21
+ export const MAX_RULING_OPTIONS = 6;
22
+ export const MAX_RULING_EVIDENCE = 8;
23
+ export const MAX_RULINGS = 40;
24
+
25
+ const PATH_AT_SHA =
26
+ /^([A-Za-z0-9._@+-]+(?:\/[A-Za-z0-9._@+-]+)*):([1-9][0-9]{0,6})(?:-([1-9][0-9]{0,6}))?@([0-9a-f]{40})$/;
27
+ const RULING_REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
28
+
29
+ /**
30
+ * The form one piece of evidence takes, or null when it is no evidence GitHub still shows.
31
+ * @param {string} text
32
+ * @param {{ repo: string, earlier?: string[] }} where `earlier`: the ids of Rulings already made
33
+ * @returns {"path-line" | "tracker-permalink" | "run-link" | "ruling" | null}
34
+ */
35
+ export function evidenceForm(text, { repo, earlier = [] }) {
36
+ const value = String(text ?? "").trim();
37
+ if (value === "" || value !== String(text) || /[\s\u0000-\u001f\u007f`<>]/.test(value))
38
+ return null;
39
+ if (RULING_ID.test(value)) return earlier.includes(value) ? "ruling" : null;
40
+ const at = PATH_AT_SHA.exec(value);
41
+ if (at) {
42
+ if (at[1].split("/").some((s) => s === "." || s === "..")) return null;
43
+ if (at[3] !== undefined && Number(at[3]) < Number(at[2])) return null;
44
+ return "path-line";
45
+ }
46
+ if (!RULING_REPO.test(repo ?? "")) return null;
47
+ const slug = repo.replace(/[.]/g, "\\.");
48
+ const base = `https://github\\.com/${slug}`;
49
+ if (
50
+ new RegExp(
51
+ `^${base}/(?:issues|pull)/[1-9][0-9]*(?:#(?:issuecomment|discussion_r|pullrequestreview)-?[0-9]+)?$`,
52
+ ).test(value) ||
53
+ new RegExp(
54
+ `^${base}/pull/[1-9][0-9]*/(?:files|commits/[0-9a-f]{40})(?:#diff-[0-9a-f]+(?:R|L)[0-9]+)?$`,
55
+ ).test(value)
56
+ )
57
+ return "tracker-permalink";
58
+ if (
59
+ new RegExp(`^${base}/actions/runs/[1-9][0-9]*(?:/job/[1-9][0-9]*)?$`).test(value) ||
60
+ new RegExp(`^${base}/runs/[1-9][0-9]*$`).test(value)
61
+ )
62
+ return "run-link";
63
+ return null;
64
+ }
65
+
66
+ const rulingText = (value, cap) => (typeof value === "string" ? untrustedText(value, cap) : "");
67
+
68
+ /**
69
+ * Checks a Ruling entry's own fields. Returns the reasons it is refused (none when it holds).
70
+ * @param {object} ruling `{ id, question, options, choice, reason, evidence }`
71
+ * @param {{ repo: string, earlier?: string[] }} where
72
+ * @returns {string[]}
73
+ */
74
+ export function rulingProblems(ruling, where) {
75
+ const problems = [];
76
+ if (!ruling || typeof ruling !== "object" || Array.isArray(ruling))
77
+ return ["a ruling is an object"];
78
+ if (!RULING_ID.test(ruling.id ?? "")) problems.push("the ruling id is R<n>");
79
+ else if ((where.earlier ?? []).includes(ruling.id))
80
+ problems.push(`${ruling.id} was already made`);
81
+ for (const key of ["question", "choice", "reason"]) {
82
+ if (typeof ruling[key] !== "string" || ruling[key].trim() === "")
83
+ problems.push(`${key} is empty`);
84
+ else if (ruling[key].length > RULING_CAPS[key] * 4) problems.push(`${key} is too long`);
85
+ }
86
+ const options = ruling.options;
87
+ if (
88
+ !Array.isArray(options) ||
89
+ options.length < 2 ||
90
+ options.length > MAX_RULING_OPTIONS ||
91
+ !options.every((o) => typeof o === "string" && o.trim() !== "")
92
+ ) {
93
+ problems.push(`options are two to ${MAX_RULING_OPTIONS} non-empty strings`);
94
+ } else if (typeof ruling.choice === "string" && !options.includes(ruling.choice)) {
95
+ problems.push("the choice is not one of the options");
96
+ }
97
+ const evidence = ruling.evidence;
98
+ if (!Array.isArray(evidence) || evidence.length === 0 || evidence.length > MAX_RULING_EVIDENCE) {
99
+ problems.push(`a ruling cites one to ${MAX_RULING_EVIDENCE} pieces of evidence`);
100
+ } else {
101
+ for (const item of evidence) {
102
+ if (typeof item !== "string" || evidenceForm(item, where) === null) {
103
+ problems.push(
104
+ `evidence ${JSON.stringify(String(item).slice(0, 60))} is not path:line@SHA, a tracker permalink, a check or run link, or an earlier ruling`,
105
+ );
106
+ }
107
+ }
108
+ }
109
+ return problems;
110
+ }
111
+
112
+ /** Evidence was checked on its way in; a piece with a space or markup in it is dropped here, never passed through untrustedText (an `@` before a SHA would be broken). */
113
+ const plainEvidence = (e) => (/^[^\s<>`]{1,300}$/.test(String(e)) ? String(e) : "[not shown]");
114
+
115
+ const oneLine = (value, cap) => rulingText(value, cap).replace(/\s+/g, " ");
116
+
117
+ /**
118
+ * The trusted Rulings block for a pull request body. The engine alone writes it.
119
+ * @param {Array<{ id: string, question: string, options: string[], choice: string, reason: string, evidence: string[] }>} rulings
120
+ * @returns {string} empty when there are none
121
+ */
122
+ export function renderRulingsBlock(rulings) {
123
+ if (!rulings?.length) return "";
124
+ const items = rulings
125
+ .slice(0, MAX_RULINGS)
126
+ .flatMap((r) => [
127
+ `### ${r.id}: ${oneLine(r.question, RULING_CAPS.question)}`,
128
+ "",
129
+ `- **Options:** ${r.options.map((o) => oneLine(o, RULING_CAPS.option)).join(" | ")}`,
130
+ `- **Choice:** ${oneLine(r.choice, RULING_CAPS.choice)}`,
131
+ `- **Reason:** ${oneLine(r.reason, RULING_CAPS.reason)}`,
132
+ `- **Evidence:** ${r.evidence.map(plainEvidence).join(" ")}`,
133
+ "",
134
+ ]);
135
+ return [
136
+ `<!-- factory:rulings v=1 count=${Math.min(rulings.length, MAX_RULINGS)} -->`,
137
+ "## Rulings",
138
+ "",
139
+ "The Chief of Staff ruled on these without a person. The review Stage holds each one against the evidence it cites; a Ruling that does not hold is a Finding above nit.",
140
+ "",
141
+ ...items,
142
+ "<!-- /factory:rulings -->",
143
+ ].join("\n");
144
+ }
145
+
146
+ /**
147
+ * The Rulings a pull request body carries in its trusted block, or null when it has no block.
148
+ * @returns {null | Array<{ id: string, question: string, choice: string, reason: string, evidence: string[] }>}
149
+ */
150
+ export function parseRulingsBlock(body) {
151
+ const match =
152
+ /<!-- factory:rulings v=1 count=([0-9]+) -->\n([\s\S]*?)\n<!-- \/factory:rulings -->/.exec(
153
+ String(body ?? ""),
154
+ );
155
+ if (!match) return null;
156
+ const rulings = [];
157
+ for (const part of match[2].split(/^### /m).slice(1)) {
158
+ const head = /^(R[1-9][0-9]*): (.*)$/m.exec(part);
159
+ if (!head) continue;
160
+ const field = (name) => new RegExp(`^- \\*\\*${name}:\\*\\* (.*)$`, "m").exec(part)?.[1] ?? "";
161
+ rulings.push({
162
+ id: head[1],
163
+ question: head[2],
164
+ choice: field("Choice"),
165
+ reason: field("Reason"),
166
+ evidence: field("Evidence").split(" ").filter(Boolean),
167
+ });
168
+ }
169
+ return rulings;
170
+ }
171
+
172
+ /**
173
+ * What the review Stage holds each Ruling in a pull request's body to: the evidence forms.
174
+ * A Ruling with none, or with a piece GitHub no longer shows (local output, a bare claim), is a Finding.
175
+ * @returns {Array<{ id: string, problem: string }>}
176
+ */
177
+ export function rulingFindings(body, { repo }) {
178
+ const rulings = parseRulingsBlock(body);
179
+ if (rulings === null) return [];
180
+ const earlier = [];
181
+ const found = [];
182
+ for (const r of rulings) {
183
+ if (r.evidence.length === 0) found.push({ id: r.id, problem: "cites no evidence" });
184
+ for (const item of r.evidence) {
185
+ if (evidenceForm(item, { repo, earlier }) === null) {
186
+ found.push({
187
+ id: r.id,
188
+ problem: `cites ${item}, which is not evidence GitHub still shows`,
189
+ });
190
+ }
191
+ }
192
+ earlier.push(r.id);
193
+ }
194
+ return found;
195
+ }
@@ -0,0 +1,66 @@
1
+ // `plan-publish`, the plan Stage's trusted step, as a command of the Kit-owned
2
+ // bundle: the argument parsing and the tracker around `publishFactoryPlan`, with
3
+ // the process boundary (`gh`, the result file) handed in, so a test drives it
4
+ // over fakes.
5
+ //
6
+ // node .github/agent-factory/sweep.mjs plan-publish --issue <n> --claim <nonce> --attempt <n> [--result <file>]
7
+ //
8
+ // A missing or unreadable result file is a Stage that left no plan: one failed
9
+ // Attempt, recorded, and exit 1. Exit 2 is a usage error. Nothing the agent
10
+ // wrote reaches a log.
11
+
12
+ import { createGithubTracker } from "../tracker/github.mjs";
13
+ import { publishFactoryPlan } from "./publish.mjs";
14
+
15
+ const SLUG = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
16
+
17
+ /**
18
+ * @param {{
19
+ * gh: (args: string[], input?: string) => { status: number | null, stdout: string, stderr: string },
20
+ * env: Record<string, string | undefined>,
21
+ * args: string[],
22
+ * readResult: (path: string) => Uint8Array | null,
23
+ * out: (line: string) => void,
24
+ * err: (line: string) => void,
25
+ * }} io
26
+ * @returns {number} 0 published, 1 not published, 2 usage error
27
+ */
28
+ export function runPlanPublish({ gh, env, args, readResult, out, err }) {
29
+ const option = (name) => {
30
+ const at = args.indexOf(`--${name}`);
31
+ return at === -1 ? undefined : args[at + 1];
32
+ };
33
+ const repo = env.GITHUB_REPOSITORY ?? "";
34
+ if (!SLUG.test(repo)) {
35
+ err("plan-publish: GITHUB_REPOSITORY is not set");
36
+ return 2;
37
+ }
38
+ const issue = Number(option("issue"));
39
+ const attempt = Number(option("attempt"));
40
+ const claim = option("claim") ?? "";
41
+ if (
42
+ !Number.isInteger(issue) ||
43
+ issue < 1 ||
44
+ !Number.isInteger(attempt) ||
45
+ attempt < 1 ||
46
+ !claim
47
+ ) {
48
+ err("usage: plan-publish --issue <n> --claim <nonce> --attempt <n> [--result <file>]");
49
+ return 2;
50
+ }
51
+ try {
52
+ const file = option("result");
53
+ const outcome = publishFactoryPlan({
54
+ tracker: createGithubTracker({ gh, repo }),
55
+ issue,
56
+ claim,
57
+ attempt,
58
+ result: file ? readResult(file) : null,
59
+ log: out,
60
+ });
61
+ return outcome.outcome === "published" ? 0 : 1;
62
+ } catch (error) {
63
+ err(`::error title=Factory plan not published::${String(error.message).replace(/\s+/g, " ")}`);
64
+ return 1;
65
+ }
66
+ }
@@ -0,0 +1,156 @@
1
+ // The Verified plan comment (spec #500, Contracts): the existing planner marker
2
+ // plus `plan=<n>`, a fenced `agent-kit-plan` block holding the Plan header, then
3
+ // the planner's prose. The trusted step writes it; the sweep reads it. Each
4
+ // version of a plan is its own comment, numbered `plan=<n>`; a new plan marks
5
+ // the previous one "Superseded by plan n+1" in its first line, and only the
6
+ // highest `n` is read. Pure: no IO. Contract suite:
7
+ // scripts/factory-plan-comment.test.mjs.
8
+ //
9
+ // <!-- agent-kit-plan v=1 plan=2 claim=<nonce> -->**Plan 2**
10
+ // ```agent-kit-plan
11
+ // { ...the header, as JSON... }
12
+ // ```
13
+ // <the prose>
14
+ //
15
+ // A superseded comment's first line is
16
+ // `<!-- agent-kit-plan v=1 plan=1 claim=<nonce> superseded_by=2 -->[Superseded by plan 2](<url>)`,
17
+ // and its header gains `superseded_by`.
18
+
19
+ import { checkPlanHeader, parseHeaderBlock, untrustedText } from "../checks/plan-header.mjs";
20
+ import { VERSION_PATTERN, VERSION_TOKEN } from "../sweep/marker-version.mjs";
21
+
22
+ /** The plan comment's marker, the existing planner marker with the plan number and the Claim it answers. */
23
+ const PLAN_MARKER = new RegExp(
24
+ `^<!-- agent-kit-plan${VERSION_PATTERN} plan=([1-9][0-9]*) claim=([A-Za-z0-9._:+-]+)(?: superseded_by=([1-9][0-9]*))? -->`,
25
+ );
26
+
27
+ /** The note the trusted step leaves when a Stage ends with no usable plan: one failed Attempt. */
28
+ const FAILURE_MARKER = new RegExp(
29
+ `^<!-- factory:plan-failed${VERSION_PATTERN} claim=([A-Za-z0-9._:+-]+) -->`,
30
+ );
31
+
32
+ /** The most the plan comment holds, as GitHub caps a comment at 65536 characters. */
33
+ export const PLAN_COMMENT_CAP = 65_536;
34
+ export const PROSE_CAP = 55_000;
35
+
36
+ const planMarker = (n, claim, supersededBy) =>
37
+ `<!-- agent-kit-plan${VERSION_TOKEN} plan=${n} claim=${claim}${supersededBy ? ` superseded_by=${supersededBy}` : ""} -->`;
38
+
39
+ /** The header as JSON that cannot close its own fence or open markup. */
40
+ function headerJson(header) {
41
+ return JSON.stringify(header, null, 2).replace(/`/g, "\\u0060").replace(/</g, "\\u003c");
42
+ }
43
+
44
+ /** Prose that cannot ping, pose as a marker or open a second header block. */
45
+ export function neutralisedProse(prose) {
46
+ return untrustedText(prose, PROSE_CAP).replace(
47
+ /^([ \t]*)```agent-kit-plan/gm,
48
+ "$1``` agent-kit-plan",
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The whole plan comment.
54
+ * @param {{ n: number, claim: string, header: object, prose: string }} input a checked header
55
+ */
56
+ export function renderPlanComment({ n, claim, header, prose }) {
57
+ const body = [
58
+ `${planMarker(n, claim, header.superseded_by)}**Plan ${n}**`,
59
+ "```agent-kit-plan",
60
+ headerJson(header),
61
+ "```",
62
+ "",
63
+ neutralisedProse(prose),
64
+ ].join("\n");
65
+ if (body.length > PLAN_COMMENT_CAP) {
66
+ throw new Error(`the plan comment would be over ${PLAN_COMMENT_CAP} characters`);
67
+ }
68
+ return body;
69
+ }
70
+
71
+ /**
72
+ * A plan comment's marker and header, or null when the body is no plan comment.
73
+ * The header is the data in the block, not yet checked.
74
+ * @returns {{ n: number, claim: string, supersededBy: number | null, data: unknown } | null}
75
+ */
76
+ export function parsePlanComment(body) {
77
+ const text = String(body ?? "");
78
+ const match = PLAN_MARKER.exec(text);
79
+ if (!match) return null;
80
+ const block = parseHeaderBlock(text);
81
+ return {
82
+ n: Number(match[1]),
83
+ claim: match[2],
84
+ supersededBy: match[3] ? Number(match[3]) : null,
85
+ data: block.ok ? block.data : undefined,
86
+ blockError: block.ok ? undefined : block.error,
87
+ };
88
+ }
89
+
90
+ /**
91
+ * The plan the sweep reads: the highest `n` among the plan comments the engine
92
+ * wrote. Anyone else's comment, a forged marker included, is no plan.
93
+ * @param {Array<{ id: string|number, author: string, body: string }>} comments
94
+ * @param {(login: string) => boolean} isEngine
95
+ */
96
+ export function latestPlan(comments, isEngine) {
97
+ let best = null;
98
+ for (const comment of comments ?? []) {
99
+ if (!isEngine(comment.author)) continue;
100
+ const plan = parsePlanComment(comment.body);
101
+ if (plan && (best === null || plan.n > best.n)) best = { ...plan, commentId: comment.id };
102
+ }
103
+ return best;
104
+ }
105
+
106
+ /** The failed-plan note the engine wrote for `claim`, or null. */
107
+ export function planFailureFor(comments, isEngine, claim) {
108
+ for (const comment of comments ?? []) {
109
+ if (!isEngine(comment.author)) continue;
110
+ const match = FAILURE_MARKER.exec(String(comment.body ?? ""));
111
+ if (match && match[1] === claim) return { commentId: comment.id };
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /** The number the next plan takes: one above the highest the engine wrote. */
117
+ export function nextPlanNumber(comments, isEngine) {
118
+ return (latestPlan(comments, isEngine)?.n ?? 0) + 1;
119
+ }
120
+
121
+ /** The comment a failed Stage leaves: kit-written words, with the refusals cut and defused. */
122
+ export function renderPlanFailure({ claim, attempt, reasons }) {
123
+ const lines = reasons
124
+ .slice(0, 10)
125
+ .map((r) => `- ${untrustedText(String(r).replace(/`/g, "'"), 200)}`);
126
+ return [
127
+ `<!-- factory:plan-failed${VERSION_TOKEN} claim=${claim} -->`,
128
+ `The plan Stage's attempt ${attempt} left no usable plan, so nothing was published and planning runs again. It counts as one failed Attempt.`,
129
+ "",
130
+ ...lines,
131
+ ].join("\n");
132
+ }
133
+
134
+ /**
135
+ * The previous plan's comment, marked superseded: its first line becomes the
136
+ * link and its header gains `superseded_by`. Null when the body is no plan the
137
+ * trusted step wrote (a body that does not parse is left as it is).
138
+ * @returns {string | null}
139
+ */
140
+ export function supersededBody(body, newN, url) {
141
+ if (!/^https:\/\/[A-Za-z0-9.-]+\/[\w./#-]+$/.test(String(url))) {
142
+ throw new Error(`not a comment url: ${JSON.stringify(url)}`);
143
+ }
144
+ const text = String(body ?? "");
145
+ const plan = parsePlanComment(text);
146
+ if (!plan || plan.supersededBy !== null || plan.data === undefined) return null;
147
+ const checked = checkPlanHeader(plan.data, { trusted: true });
148
+ if (!checked.ok) return null;
149
+ const rest = text.slice(text.indexOf("\n") + 1);
150
+ const header = { ...checked.header, superseded_by: newN };
151
+ const lines = rest.split("\n");
152
+ const open = lines.findIndex((l) => l.startsWith("```agent-kit-plan"));
153
+ const close = lines.findIndex((l, i) => i > open && l.startsWith("```"));
154
+ const next = [...lines.slice(0, open + 1), headerJson(header), ...lines.slice(close)];
155
+ return `${planMarker(plan.n, plan.claim, newN)}[Superseded by plan ${newN}](${url})\n${next.join("\n")}`;
156
+ }
@@ -0,0 +1,149 @@
1
+ // The plan Stage's trusted step (ADR 0026, ADR 0034): it runs in a job where no
2
+ // agent ran, reads the Stage result as data, checks the Plan header, applies the
3
+ // risk rules from the base branch and posts the plan comment itself, as the job
4
+ // token's `github-actions[bot]`. The agent never writes to the tracker.
5
+ //
6
+ // a valid plan -> comment `plan=<n>` (the highest `n` plus one), the previous
7
+ // plan comment marked "Superseded by plan n"
8
+ // anything else -> a failure note for the Claim, which the Dispatcher counts as
9
+ // one failed Attempt, and the plan is run again
10
+ //
11
+ // IO is the `gh` function it is given, so scripts/factory-plan-publish.test.mjs
12
+ // runs it over a fake. Nothing the agent wrote reaches a log.
13
+
14
+ import { acceptanceCriteria, checkPlanHeader, parseHeaderBlock } from "../checks/plan-header.mjs";
15
+ import {
16
+ nextPlanNumber,
17
+ latestPlan,
18
+ renderPlanComment,
19
+ renderPlanFailure,
20
+ supersededBody,
21
+ } from "./comment.mjs";
22
+ import { parseRiskRules, riskTier } from "./risk.mjs";
23
+
24
+ /** Where the Consumer's risk rules live, read from the base branch. */
25
+ export const RISK_RULES_PATH = ".github/factory/risk-rules.json";
26
+
27
+ /** The most a Stage result holds. Past it, nothing is published. */
28
+ export const RESULT_BYTES_CAP = 256 * 1024;
29
+
30
+ const PLAIN = /^[A-Za-z0-9._:+-]+$/;
31
+ const ENGINE_LOGIN = "github-actions[bot]";
32
+
33
+ /**
34
+ * The refusals of a Stage result, in the kit's own words.
35
+ * @returns {{ ok: true, header: object, prose: string } | { ok: false, reasons: string[] }}
36
+ */
37
+ export function checkStageResult(result, { criteria }) {
38
+ if (result === null || result === undefined) {
39
+ return { ok: false, reasons: ["The Stage left no plan."] };
40
+ }
41
+ if (result.length > RESULT_BYTES_CAP) {
42
+ return {
43
+ ok: false,
44
+ reasons: [`The plan is over the size cap of ${RESULT_BYTES_CAP / 1024} KiB.`],
45
+ };
46
+ }
47
+ let text;
48
+ try {
49
+ text = new TextDecoder("utf-8", { fatal: true }).decode(result);
50
+ } catch {
51
+ return { ok: false, reasons: ["The plan is not UTF-8."] };
52
+ }
53
+ if (/[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(text)) {
54
+ return { ok: false, reasons: ["The plan holds a control character."] };
55
+ }
56
+ const block = parseHeaderBlock(text);
57
+ if (!block.ok) return { ok: false, reasons: [`The ${block.error.replace(/^the /, "")}.`] };
58
+ const checked = checkPlanHeader(block.data, { criteria });
59
+ if (!checked.ok) return { ok: false, reasons: checked.errors };
60
+ return { ok: true, header: checked.header, prose: block.prose };
61
+ }
62
+
63
+ /**
64
+ * @param {{
65
+ * tracker: { readIssue: Function, readComments: Function, postComment: Function, editComment: Function, readFile: Function, defaultBranch: Function },
66
+ * issue: number,
67
+ * claim: string,
68
+ * attempt: number,
69
+ * result: Uint8Array | null,
70
+ * log: (line: string) => void,
71
+ * }} deps `result` is the Stage result's bytes, or null when there is none
72
+ * @returns {{ outcome: "published", n: number } | { outcome: "failed", reasons: string[] }}
73
+ */
74
+ export function publishFactoryPlan({
75
+ tracker,
76
+ issue,
77
+ claim,
78
+ attempt,
79
+ result,
80
+ log,
81
+ engineLogin = ENGINE_LOGIN,
82
+ }) {
83
+ if (!PLAIN.test(claim)) throw new Error("the claim is not a plain value");
84
+ if (!Number.isInteger(issue) || issue < 1) throw new Error("the issue is not a number");
85
+ if (!Number.isInteger(attempt) || attempt < 1) throw new Error("the attempt is not a number");
86
+ const isEngine = (login) => login === engineLogin;
87
+
88
+ const failWith = (reasons) => {
89
+ tracker.postComment(issue, renderPlanFailure({ claim, attempt, reasons }));
90
+ log(`The plan could not be published: attempt ${attempt} is recorded as failed.`);
91
+ return { outcome: "failed", reasons };
92
+ };
93
+
94
+ const info = tracker.readIssue(issue);
95
+ const checked = checkStageResult(result, { criteria: acceptanceCriteria(info.body) });
96
+ if (!checked.ok) return failWith(checked.reasons);
97
+
98
+ // The risk rules, from the base branch alone: a person's pull request cannot lower its own risk.
99
+ let rulesText;
100
+ try {
101
+ rulesText = tracker.readFile(RISK_RULES_PATH, tracker.defaultBranch());
102
+ } catch {
103
+ rulesText = UNREADABLE_FILE;
104
+ }
105
+ const { risk, raisedBy } = riskTier({
106
+ planner: checked.header.risk,
107
+ parsed: parseRiskRules(rulesText),
108
+ allowedPaths: checked.header.allowed_paths,
109
+ size: checked.header.size,
110
+ labels: info.labels,
111
+ });
112
+ const header = {
113
+ ...checked.header,
114
+ risk,
115
+ ...(raisedBy.length ? { risk_raised_by: raisedBy } : {}),
116
+ };
117
+
118
+ const comments = tracker.readComments(issue);
119
+ const n = nextPlanNumber(comments, isEngine);
120
+ const previous = latestPlan(comments, isEngine);
121
+ let body;
122
+ try {
123
+ body = renderPlanComment({ n, claim, header, prose: checked.prose });
124
+ } catch {
125
+ // A plan too long for one comment is a plan that cannot be published: one failed Attempt.
126
+ return failWith(["The plan is too long to publish as one comment."]);
127
+ }
128
+ const posted = tracker.postComment(issue, body);
129
+ if (previous) {
130
+ // The new plan stands first; marking the old one is best-effort, and only the highest n is read.
131
+ const marked = supersededBody(
132
+ comments.find((c) => c.id === previous.commentId)?.body,
133
+ n,
134
+ posted.url,
135
+ );
136
+ if (marked !== null) {
137
+ try {
138
+ tracker.editComment(previous.commentId, marked);
139
+ } catch {
140
+ log(`Plan ${previous.n} could not be marked superseded; plan ${n} is still the one read.`);
141
+ }
142
+ }
143
+ }
144
+ log(`Plan ${n} published${raisedBy.length ? `, risk raised to ${risk}` : ""}.`);
145
+ return { outcome: "published", n };
146
+ }
147
+
148
+ /** Text no risk rules file can parse from: stands for a file that exists and could not be read. */
149
+ const UNREADABLE_FILE = "(the risk rules file could not be read)";