@mnaimfaizy/agent-kit 1.0.0-beta.14 → 1.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +22 -4
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +244 -6
  4. package/package.json +3 -2
  5. package/src/checks/ci-workflow.mjs +105 -0
  6. package/src/checks/claude-app.mjs +11 -2
  7. package/src/checks/custom-harness.mjs +157 -0
  8. package/src/checks/github-app.mjs +214 -0
  9. package/src/checks/rulesets.mjs +9 -8
  10. package/src/checks/secrets-and-variables.mjs +27 -8
  11. package/src/checks/stages.mjs +705 -0
  12. package/src/cli.mjs +583 -36
  13. package/src/deep-scan/agent.mjs +88 -21
  14. package/src/deep-scan/credential.mjs +81 -32
  15. package/src/deep-scan/docker-driver.mjs +105 -42
  16. package/src/deep-scan/harness-text.mjs +99 -0
  17. package/src/deep-scan/lifecycle.mjs +68 -178
  18. package/src/deep-scan/limits.mjs +13 -7
  19. package/src/deep-scan/model-proxy.mjs +21 -10
  20. package/src/deep-scan/preflight.mjs +19 -6
  21. package/src/deep-scan/recipe.mjs +4 -0
  22. package/src/deep-scan/runtime.mjs +54 -6
  23. package/src/deep-scan/sandbox-run.mjs +232 -0
  24. package/src/deep-scan/sbx-driver.mjs +224 -39
  25. package/src/deep-scan/tar.mjs +69 -22
  26. package/src/deep-scan/verify.mjs +6 -1
  27. package/src/deep-scan.mjs +73 -13
  28. package/src/doctor.mjs +166 -5
  29. package/src/exec.mjs +14 -5
  30. package/src/factory/budget/budget.mjs +259 -0
  31. package/src/factory/build/command.mjs +321 -0
  32. package/src/factory/build/factory.mjs +473 -0
  33. package/src/factory/build/findings.mjs +55 -0
  34. package/src/factory/build/host.mjs +230 -0
  35. package/src/factory/build/notes.mjs +191 -0
  36. package/src/factory/build/pull-request.mjs +74 -0
  37. package/src/factory/bundle.mjs +146 -0
  38. package/src/factory/checks/allowed-paths.mjs +50 -0
  39. package/src/factory/checks/plan-header.mjs +296 -0
  40. package/src/factory/checks/qa.mjs +85 -0
  41. package/src/factory/checks/review.mjs +73 -0
  42. package/src/factory/checks/security.mjs +50 -0
  43. package/src/factory/checks/stage-check.mjs +89 -0
  44. package/src/factory/claims/command.mjs +187 -0
  45. package/src/factory/claims/release.mjs +111 -0
  46. package/src/factory/decision/answers.mjs +103 -0
  47. package/src/factory/decision/command.mjs +64 -0
  48. package/src/factory/decision/plan.mjs +99 -0
  49. package/src/factory/decision/request.mjs +116 -0
  50. package/src/factory/doctor/files.mjs +329 -0
  51. package/src/factory/doctor/index.mjs +56 -0
  52. package/src/factory/doctor/local.mjs +497 -0
  53. package/src/factory/doctor/orchestrate.mjs +146 -0
  54. package/src/factory/engine/lease.mjs +146 -0
  55. package/src/factory/engine/local-engine.mjs +177 -0
  56. package/src/factory/engine/lockfile.mjs +64 -0
  57. package/src/factory/engine/workflow-engine.mjs +124 -0
  58. package/src/factory/gate/comment.mjs +88 -0
  59. package/src/factory/gate/config.mjs +57 -0
  60. package/src/factory/gate/gate-core.mjs +250 -0
  61. package/src/factory/gate/guarded.mjs +17 -0
  62. package/src/factory/gate/reads.mjs +105 -0
  63. package/src/factory/gate/task.mjs +193 -0
  64. package/src/factory/gate/trip-reads.mjs +82 -0
  65. package/src/factory/gate/trip.mjs +87 -0
  66. package/src/factory/init/blueprint.mjs +174 -0
  67. package/src/factory/init/index.mjs +337 -0
  68. package/src/factory/labels/evidence.mjs +162 -0
  69. package/src/factory/labels/moves.mjs +32 -0
  70. package/src/factory/labels/reconcile.mjs +267 -0
  71. package/src/factory/labels/revert.mjs +87 -0
  72. package/src/factory/labels/timeline.mjs +72 -0
  73. package/src/factory/labels/voided.mjs +59 -0
  74. package/src/factory/limits/harness.mjs +39 -0
  75. package/src/factory/limits/limits.mjs +123 -0
  76. package/src/factory/merge/command.mjs +172 -0
  77. package/src/factory/outbox/check.mjs +240 -0
  78. package/src/factory/outbox/rulings.mjs +195 -0
  79. package/src/factory/plan/command.mjs +66 -0
  80. package/src/factory/plan/comment.mjs +156 -0
  81. package/src/factory/plan/publish.mjs +149 -0
  82. package/src/factory/plan/risk.mjs +153 -0
  83. package/src/factory/qa/command.mjs +163 -0
  84. package/src/factory/records/engine-record.mjs +133 -0
  85. package/src/factory/records/main.mjs +96 -0
  86. package/src/factory/records/record.mjs +226 -0
  87. package/src/factory/records/sink.mjs +57 -0
  88. package/src/factory/report/build.mjs +92 -0
  89. package/src/factory/report/command.mjs +80 -0
  90. package/src/factory/report/facts.mjs +226 -0
  91. package/src/factory/report/gate-section.mjs +122 -0
  92. package/src/factory/report/metrics.mjs +111 -0
  93. package/src/factory/report/reads.mjs +246 -0
  94. package/src/factory/report/render.mjs +121 -0
  95. package/src/factory/report/rollout.mjs +154 -0
  96. package/src/factory/review/command.mjs +182 -0
  97. package/src/factory/run/awake.mjs +70 -0
  98. package/src/factory/run/collect.mjs +77 -0
  99. package/src/factory/run/command.mjs +490 -0
  100. package/src/factory/run/gh.mjs +46 -0
  101. package/src/factory/run/launch.mjs +47 -0
  102. package/src/factory/run/pipelines.mjs +261 -0
  103. package/src/factory/run/raw.mjs +96 -0
  104. package/src/factory/run/restart.mjs +83 -0
  105. package/src/factory/run/s3.mjs +193 -0
  106. package/src/factory/run/secrets.mjs +142 -0
  107. package/src/factory/run/teardown.mjs +242 -0
  108. package/src/factory/run/token.mjs +68 -0
  109. package/src/factory/security/command.mjs +157 -0
  110. package/src/factory/setup/app.mjs +122 -0
  111. package/src/factory/setup/command.mjs +409 -0
  112. package/src/factory/setup/labels.mjs +25 -0
  113. package/src/factory/setup/reads.mjs +129 -0
  114. package/src/factory/setup/writes.mjs +126 -0
  115. package/src/factory/snapshot/write.mjs +176 -0
  116. package/src/factory/stop/command.mjs +136 -0
  117. package/src/factory/sweep/actions-main.mjs +117 -0
  118. package/src/factory/sweep/command.mjs +65 -0
  119. package/src/factory/sweep/knobs.mjs +78 -0
  120. package/src/factory/sweep/marker-version.mjs +15 -0
  121. package/src/factory/sweep/markers.mjs +112 -0
  122. package/src/factory/sweep/overlap.mjs +24 -0
  123. package/src/factory/sweep/run.mjs +198 -0
  124. package/src/factory/sweep/shell.mjs +394 -0
  125. package/src/factory/sweep/split.mjs +104 -0
  126. package/src/factory/sweep/states.mjs +87 -0
  127. package/src/factory/sweep/sweep-core.mjs +1781 -0
  128. package/src/factory/tracker/github.mjs +674 -0
  129. package/src/factory/tracker/operations.mjs +153 -0
  130. package/src/factory/upgrade/index.mjs +83 -0
  131. package/src/harness/adapters.mjs +30 -0
  132. package/src/harness/antigravity.mjs +187 -0
  133. package/src/harness/claude-code.mjs +8 -1
  134. package/src/harness/codex.mjs +219 -0
  135. package/src/harness/cursor.mjs +199 -0
  136. package/src/harness/custom/registry.mjs +21 -0
  137. package/src/harness/custom/schema.mjs +90 -0
  138. package/src/harness/custom.mjs +299 -0
  139. package/src/harness/facts.mjs +44 -7
  140. package/src/harness/gemini.mjs +164 -0
  141. package/src/harness/install-layer.mjs +86 -3
  142. package/src/harness/opencode.mjs +289 -0
  143. package/src/harness/resolve.mjs +156 -0
  144. package/src/harness/support-levels.mjs +151 -3
  145. package/src/harness-live/assess.mjs +29 -6
  146. package/src/harness-live/cursor-real.mjs +146 -0
  147. package/src/harness-live/cursor-version.mjs +70 -0
  148. package/src/harness-live/cursor.mjs +80 -0
  149. package/src/harness-live/custom.mjs +91 -0
  150. package/src/harness-live/fixture-harness.mjs +45 -0
  151. package/src/harness-live/harnesses.mjs +263 -0
  152. package/src/harness-live/host.mjs +113 -4
  153. package/src/harness-live/opencode.mjs +289 -0
  154. package/src/harness-live/probes.mjs +87 -7
  155. package/src/harness-live/run.mjs +101 -20
  156. package/src/harness-live/setup.mjs +126 -0
  157. package/src/harness-live/stage.mjs +25 -15
  158. package/src/harness-live/suite.mjs +276 -95
  159. package/src/harness-test.mjs +116 -0
  160. package/src/init.mjs +374 -36
  161. package/src/kit-owned-paths.mjs +1 -1
  162. package/src/model-proxy/core.mjs +128 -20
  163. package/src/model-proxy/profiles/anthropic.mjs +54 -10
  164. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  165. package/src/model-proxy/profiles/openai.mjs +327 -0
  166. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  167. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  168. package/src/model-proxy/stub.mjs +9 -1
  169. package/src/stage/audit.mjs +79 -0
  170. package/src/stage/egress-route.mjs +207 -0
  171. package/src/stage/implement/carry.mjs +308 -0
  172. package/src/stage/implement/sandbox.mjs +271 -0
  173. package/src/stage/implement/verify.mjs +70 -0
  174. package/src/stage/implement.mjs +218 -0
  175. package/src/stage/plan.mjs +115 -0
  176. package/src/stage/review-response.mjs +172 -0
  177. package/src/stage/review.mjs +185 -0
  178. package/src/stage/workspace.mjs +274 -0
  179. package/src/stage.mjs +1087 -0
  180. package/src/upgrade.mjs +39 -7
@@ -0,0 +1,116 @@
1
+ // The Factory's Decision Request (spec #500, Contracts): the one comment a task
2
+ // asks a person in, and its parser. The renderer is pure, so a fixture holds its
3
+ // exact text (scripts/factory-decision-request.test.mjs over
4
+ // scripts/fixtures/factory/decision/).
5
+ //
6
+ // <!-- factory:decision-request v=1 attempt=<n> -->
7
+ // <!-- factory:decision-context v=1 plan=<p> kinds=<questions|approval|criteria,...> -->
8
+ // ## Decision Request: <title>
9
+ // ### Q1: <question> options, evidence, recommendation
10
+ // ...
11
+ // ```text
12
+ // A1:
13
+ // ``` the block a person copies, fills in and posts as a reply
14
+ //
15
+ // The engine writes it as a new comment. A person never edits it: the answer is
16
+ // the person's own reply, and only a write user's reply counts (answers.mjs).
17
+
18
+ import { untrustedText } from "../checks/plan-header.mjs";
19
+ import { VERSION_PATTERN, VERSION_TOKEN } from "../sweep/marker-version.mjs";
20
+
21
+ /** What a request asks: the planner's own questions, plan approval, drafted acceptance criteria, or whether to go on after `max_attempts` failed Attempts. */
22
+ export const DECISION_KINDS = Object.freeze(["questions", "approval", "criteria", "attempts"]);
23
+
24
+ export const REQUEST_MARKER = new RegExp(
25
+ `^<!-- factory:decision-request${VERSION_PATTERN} attempt=([1-9][0-9]*) -->`,
26
+ );
27
+ const CONTEXT_MARKER =
28
+ /^<!-- factory:decision-context v=1 plan=([1-9][0-9]*) kinds=([a-z,]+) -->$/m;
29
+ const QUESTION_HEADING = /^### Q([1-9][0-9]*): (.*)$/gm;
30
+
31
+ /** The most questions one request holds. */
32
+ export const MAX_QUESTIONS = 12;
33
+
34
+ /** Free text on one line, defused: it cannot pose as a heading, a marker or an `A<n>:` line. */
35
+ const line = (text, cap) => untrustedText(text, cap).replace(/\s+/g, " ");
36
+
37
+ /**
38
+ * The comment a task asks a person in.
39
+ * @param {{
40
+ * attempt: number,
41
+ * plan: number,
42
+ * kinds: string[],
43
+ * title: string,
44
+ * intro: string,
45
+ * questions: Array<{ question: string, options: string[], recommendation: string, evidence: string }>,
46
+ * }} input
47
+ * @returns {string}
48
+ */
49
+ export function renderDecisionRequest({ attempt, plan, kinds, title, intro, questions }) {
50
+ if (!Number.isInteger(attempt) || attempt < 1)
51
+ throw new Error("attempt must be a positive integer");
52
+ if (!Number.isInteger(plan) || plan < 1) throw new Error("plan must be a positive integer");
53
+ if (!kinds?.length || !kinds.every((k) => DECISION_KINDS.includes(k))) {
54
+ throw new Error(`kinds must be among ${DECISION_KINDS.join(", ")}`);
55
+ }
56
+ if (!questions?.length || questions.length > MAX_QUESTIONS) {
57
+ throw new Error(`a request holds one to ${MAX_QUESTIONS} questions`);
58
+ }
59
+ const sections = questions.flatMap((q, i) => {
60
+ const evidence = (untrustedText(q.evidence ?? "", 1000) || "none given")
61
+ .split("\n")
62
+ .map((l) => `> ${l}`);
63
+ return [
64
+ `### Q${i + 1}: ${line(q.question, 500)}`,
65
+ "",
66
+ "**Options:**",
67
+ "",
68
+ ...q.options.map((o, j) => `${j + 1}. ${line(o, 200)}`),
69
+ "",
70
+ "**Evidence:**",
71
+ "",
72
+ ...evidence,
73
+ "",
74
+ `**Recommendation:** ${line(q.recommendation, 300)}`,
75
+ "",
76
+ ];
77
+ });
78
+ return [
79
+ `<!-- factory:decision-request${VERSION_TOKEN} attempt=${attempt} -->`,
80
+ `<!-- factory:decision-context v=1 plan=${plan} kinds=${kinds.join(",")} -->`,
81
+ `## Decision Request: ${line(title, 200)}`,
82
+ "",
83
+ line(intro, 600),
84
+ "",
85
+ ...sections,
86
+ "**How to answer.** Reply with a new comment: copy the block below and fill in every `A<n>:`. " +
87
+ "Only a reply from someone with write access counts, so do not edit this comment. " +
88
+ "Then swap `factory:needs-decision` for `factory:queued`: answering alone does not restart the task, and an empty answer sends it back here.",
89
+ "",
90
+ "```text",
91
+ ...questions.map((_, i) => `A${i + 1}:`),
92
+ "```",
93
+ ].join("\n");
94
+ }
95
+
96
+ /**
97
+ * What a request comment says, or null when the body is no request.
98
+ * @returns {{ attempt: number, plan: number | null, kinds: string[], questions: Array<{ n: number, question: string }> } | null}
99
+ */
100
+ export function parseDecisionRequest(body) {
101
+ const text = String(body ?? "");
102
+ const marker = REQUEST_MARKER.exec(text);
103
+ if (!marker) return null;
104
+ const context = CONTEXT_MARKER.exec(text);
105
+ const kinds = context ? context[2].split(",").filter((k) => DECISION_KINDS.includes(k)) : [];
106
+ const questions = [...text.matchAll(QUESTION_HEADING)].map((m) => ({
107
+ n: Number(m[1]),
108
+ question: m[2],
109
+ }));
110
+ return {
111
+ attempt: Number(marker[1]),
112
+ plan: context ? Number(context[1]) : null,
113
+ kinds,
114
+ questions,
115
+ };
116
+ }
@@ -0,0 +1,329 @@
1
+ // `doctor`'s Factory file checks (spec #500, #520): what the Consumer's checkout
2
+ // says about the Factory, read from files alone, so they run in CI mode too and
3
+ // `upgrade` runs them after it has written. Each is a function over injected
4
+ // reads (`read(path)` is a file's text or null; `list(dir)` its file names), never
5
+ // the disk or GitHub, so a contract case drives it with a fixture tree. The
6
+ // rules are the ones the sweep itself applies, read through the same modules.
7
+ //
8
+ // The checks and their ids:
9
+ // factory-config the factory config's schema: strict keys and values
10
+ // factory-caps every per-Stage token cap is at most the Daily cap
11
+ // factory-auto-tiers `high` is not in `merge.auto_tiers`
12
+ // factory-risk-rules the risk rules parse and make every Guarded path `high`
13
+ // factory-callers the blueprint Callers are present and pinned to the tag
14
+
15
+ import { result } from "../../checks/result.mjs";
16
+ import { versionForTag } from "../../tags.mjs";
17
+ import { budgetFromConfig, budgetStageCap } from "../budget/budget.mjs";
18
+ import { planApprovalFromConfig } from "../decision/plan.mjs";
19
+ import { GUARDED_PATHS } from "../gate/guarded.mjs";
20
+ import { mergeFromConfig } from "../gate/config.mjs";
21
+ import { CONFIG_PATH, RISK_RULES_PATH } from "../init/blueprint.mjs";
22
+ import { LIMIT_STAGES, stageLimits, TASK_SIZES } from "../limits/limits.mjs";
23
+ import { parseRiskRules, riskTier } from "../plan/risk.mjs";
24
+
25
+ export const FACTORY_FILE_CHECKS = Object.freeze([
26
+ ["factory-config", "Factory config is valid"],
27
+ ["factory-caps", "Per-Stage token caps fit the Daily cap"],
28
+ ["factory-auto-tiers", "Auto-merge tiers exclude high"],
29
+ ["factory-risk-rules", "Risk rules make every Guarded path high"],
30
+ ["factory-callers", "Factory Callers are present and pinned"],
31
+ ]);
32
+ const TITLE = Object.fromEntries(FACTORY_FILE_CHECKS);
33
+ const make = (id, status, summary, opts) => result(id, TITLE[id], status, summary, opts);
34
+
35
+ /** The Callers the Workflow engine's blueprint ships, one per Stage plus the Dispatcher and the merge job. */
36
+ export const FACTORY_CALLERS = Object.freeze([
37
+ "factory-dispatcher",
38
+ "factory-plan",
39
+ "factory-build",
40
+ "factory-review",
41
+ "factory-qa",
42
+ "factory-security",
43
+ "factory-merge",
44
+ ]);
45
+ const WORKFLOWS_DIR = ".github/workflows";
46
+ const FACTORY_DIR = ".github/factory";
47
+
48
+ const TOP_KEYS = ["max_running", "max_attempts", "plan_approval", "limits", "budget", "merge"];
49
+ const BUDGET_KEYS = ["daily_tokens", "notify"];
50
+ const MERGE_KEYS = ["mode", "auto_tiers", "method"];
51
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
52
+ const whole = (v) => Number.isSafeInteger(v) && v >= 1;
53
+
54
+ const CALLER_FILE = /^factory-[a-z][a-z0-9-]*\.ya?ml$/;
55
+
56
+ /**
57
+ * Whether the checkout has a Factory: the Consumer's own Factory files, which is its
58
+ * `.github/factory/` folder (config, risk rules, ruleset) or any `factory-*.yml` Caller.
59
+ * The bundle `.github/agent-factory/` does not count: it is a Kit-owned path that `init`
60
+ * and `upgrade` copy for every Consumer. A checkout with no Factory is not checked, so
61
+ * `doctor` and `upgrade` behave there exactly as they did before the Factory.
62
+ * @param {{ exists: (path: string) => boolean, list: (dir: string) => string[] }} reads
63
+ */
64
+ export function factoryPresent({ exists, list }) {
65
+ return exists(FACTORY_DIR) || list(WORKFLOWS_DIR).some((f) => CALLER_FILE.test(f));
66
+ }
67
+
68
+ /** The engine the checkout is set up for: the Workflow engine has Callers, the Orchestrate engine none. */
69
+ export function engineOf({ list }) {
70
+ return list(WORKFLOWS_DIR).some((f) => CALLER_FILE.test(f)) ? "workflow" : "orchestrate";
71
+ }
72
+
73
+ function parseJson(text) {
74
+ try {
75
+ return { data: JSON.parse(text) };
76
+ } catch {
77
+ return { error: "is not JSON" };
78
+ }
79
+ }
80
+
81
+ /** The config's problems, one sentence each; none when it is a valid factory config. */
82
+ export function configProblems(text) {
83
+ const parsed = parseJson(text);
84
+ if (parsed.error) return [`${CONFIG_PATH} ${parsed.error}.`];
85
+ const data = parsed.data;
86
+ if (!isObject(data)) return [`${CONFIG_PATH} is not an object.`];
87
+ const problems = [];
88
+ for (const key of Object.keys(data)) {
89
+ if (!TOP_KEYS.includes(key)) problems.push(`${key} is not a factory config key.`);
90
+ }
91
+ for (const key of ["max_running", "max_attempts"]) {
92
+ if (key in data && !whole(data[key]))
93
+ problems.push(`${key} must be a whole number of 1 or more.`);
94
+ }
95
+ const approval = planApprovalFromConfig(text);
96
+ if (approval.problem) problems.push(`${approval.problem}.`);
97
+ if ("limits" in data) {
98
+ if (!isObject(data.limits)) problems.push("limits is not an object.");
99
+ else {
100
+ for (const key of Object.keys(data.limits)) {
101
+ if (!LIMIT_STAGES.includes(key)) problems.push(`limits.${key} is not a Stage.`);
102
+ }
103
+ for (const stage of LIMIT_STAGES) {
104
+ const sizes = stage === "build" ? TASK_SIZES : [undefined];
105
+ for (const size of sizes) {
106
+ const read = stageLimits({ configText: text, stage, size });
107
+ if (read.error) problems.push(`${read.error}.`);
108
+ }
109
+ }
110
+ const build = data.limits.build;
111
+ if (isObject(build)) {
112
+ for (const key of Object.keys(build)) {
113
+ if (!TASK_SIZES.includes(key)) problems.push(`limits.build.${key} is not a Task size.`);
114
+ }
115
+ }
116
+ }
117
+ }
118
+ if ("budget" in data) {
119
+ if (!isObject(data.budget)) problems.push("budget is not an object.");
120
+ else {
121
+ for (const key of Object.keys(data.budget)) {
122
+ if (!BUDGET_KEYS.includes(key)) problems.push(`budget.${key} is not a budget key.`);
123
+ }
124
+ const budget = budgetFromConfig(text);
125
+ if (budget.problem) problems.push(`${budget.problem}.`);
126
+ }
127
+ }
128
+ if ("merge" in data) {
129
+ if (!isObject(data.merge)) problems.push("merge is not an object.");
130
+ else {
131
+ for (const key of Object.keys(data.merge)) {
132
+ if (!MERGE_KEYS.includes(key)) problems.push(`merge.${key} is not a merge key.`);
133
+ }
134
+ // `high` in auto_tiers is its own check: the gate drops it, doctor names it.
135
+ const merge = mergeFromConfig(text);
136
+ if (merge.problem) problems.push(`${merge.problem}.`);
137
+ }
138
+ }
139
+ return [...new Set(problems)];
140
+ }
141
+
142
+ function checkConfig(configText) {
143
+ if (configText === null) {
144
+ return make("factory-config", "fail", `${CONFIG_PATH} does not exist.`, {
145
+ details: [
146
+ "Write it with `agent-kit init --factory`, or copy examples/factory/factory-config.json.",
147
+ ],
148
+ });
149
+ }
150
+ const problems = configProblems(configText);
151
+ if (problems.length) {
152
+ return make("factory-config", "fail", `${CONFIG_PATH} is not a valid factory config.`, {
153
+ details: problems,
154
+ });
155
+ }
156
+ return make("factory-config", "pass", `${CONFIG_PATH} is a valid factory config.`);
157
+ }
158
+
159
+ function checkCaps(configText) {
160
+ if (configText === null || configProblems(configText).length) {
161
+ return make("factory-caps", "skip", "Needs a valid factory config: fix factory-config first.");
162
+ }
163
+ const data = JSON.parse(configText);
164
+ const cap = data.budget?.daily_tokens;
165
+ if (cap === undefined) {
166
+ return make(
167
+ "factory-caps",
168
+ "pass",
169
+ "budget.daily_tokens is not set: there is no Daily cap to exceed.",
170
+ );
171
+ }
172
+ const over = [];
173
+ for (const stage of LIMIT_STAGES) {
174
+ const sizes = stage === "build" ? TASK_SIZES : [undefined];
175
+ for (const size of sizes) {
176
+ const tokens = budgetStageCap({ limits: data.limits, stage, size });
177
+ if (tokens !== null && tokens > cap) {
178
+ const name = size ? `limits.build.${size}` : `limits.${stage}`;
179
+ over.push(`${name}.tokens is ${tokens}, over budget.daily_tokens ${cap}.`);
180
+ }
181
+ }
182
+ }
183
+ if (over.length) {
184
+ return make("factory-caps", "fail", "A per-Stage token cap is over the Daily cap.", {
185
+ details: [...over, "A Stage that could not fit under the Daily cap would never be claimed."],
186
+ });
187
+ }
188
+ return make(
189
+ "factory-caps",
190
+ "pass",
191
+ `Every per-Stage token cap is at most the Daily cap (${cap}).`,
192
+ );
193
+ }
194
+
195
+ function checkAutoTiers(configText) {
196
+ if (configText === null) return make("factory-auto-tiers", "skip", "Needs the factory config.");
197
+ const parsed = parseJson(configText);
198
+ const tiers = parsed.data?.merge?.auto_tiers;
199
+ if (parsed.error || !isObject(parsed.data)) {
200
+ return make("factory-auto-tiers", "skip", "Needs a factory config that is JSON.");
201
+ }
202
+ if (Array.isArray(tiers) && tiers.includes("high")) {
203
+ return make("factory-auto-tiers", "fail", "merge.auto_tiers lists `high`.", {
204
+ details: [
205
+ "The merge gate never auto-merges a `high` task (ADR 0041), so the entry does nothing but mislead.",
206
+ "Remove `high` from merge.auto_tiers.",
207
+ ],
208
+ });
209
+ }
210
+ return make("factory-auto-tiers", "pass", "merge.auto_tiers has no `high`.");
211
+ }
212
+
213
+ function checkRiskRules(rulesText) {
214
+ const parsed = parseRiskRules(rulesText);
215
+ if (parsed.status === "missing") {
216
+ return make("factory-risk-rules", "fail", `${RISK_RULES_PATH} does not exist.`, {
217
+ details: ["Without it every plan is `high`. Copy examples/factory/risk-rules.json."],
218
+ });
219
+ }
220
+ if (parsed.status === "unreadable") {
221
+ return make("factory-risk-rules", "fail", `${RISK_RULES_PATH} does not parse as risk rules.`, {
222
+ details: [
223
+ "Every plan is `high` until it does. Each rule is { id, tier, when: paths | size | label }.",
224
+ ],
225
+ });
226
+ }
227
+ const uncovered = GUARDED_PATHS.filter(
228
+ (glob) => riskTier({ planner: "low", parsed, allowedPaths: [glob], size: "s" }).risk !== "high",
229
+ );
230
+ if (uncovered.length) {
231
+ return make(
232
+ "factory-risk-rules",
233
+ "fail",
234
+ "A Guarded path is not made `high` by the risk rules.",
235
+ {
236
+ details: [
237
+ ...uncovered.map((g) => `${g} is judged below \`high\`.`),
238
+ "Add a `high` rule whose paths cover it, as the blueprint's `workflows` and `factory-config` rules do.",
239
+ ],
240
+ },
241
+ );
242
+ }
243
+ return make(
244
+ "factory-risk-rules",
245
+ "pass",
246
+ `${parsed.rules.length} risk rule${parsed.rules.length === 1 ? "" : "s"} parse and make every Guarded path high.`,
247
+ );
248
+ }
249
+
250
+ const CLI_PIN = /@mnaimfaizy\/agent-kit@([0-9][0-9A-Za-z.+-]*)/g;
251
+
252
+ /** The `@mnaimfaizy/agent-kit@<version>` pins of a Caller's text, with their version. */
253
+ export const cliPinsOf = (text) => [...String(text).matchAll(CLI_PIN)].map((m) => m[1]);
254
+
255
+ function checkCallers({ engine, list, read, tag }) {
256
+ if (engine === "orchestrate") {
257
+ return make(
258
+ "factory-callers",
259
+ "skip",
260
+ "The Orchestrate engine runs from the CLI: it has no Callers (its prompt files come with the Kit-owned bundle folder).",
261
+ );
262
+ }
263
+ const have = new Set(
264
+ list(WORKFLOWS_DIR)
265
+ .filter((f) => CALLER_FILE.test(f))
266
+ .map((f) => f.replace(/\.ya?ml$/, "")),
267
+ );
268
+ const missing = FACTORY_CALLERS.filter((n) => !have.has(n));
269
+ if (missing.length) {
270
+ return make("factory-callers", "fail", `${missing.length} Factory Caller(s) are missing.`, {
271
+ details: [
272
+ ...missing.map((n) => `${WORKFLOWS_DIR}/${n}.yml is not there.`),
273
+ "Copy it from the tag's examples/factory/ (`agent-kit init --factory` writes them all).",
274
+ ],
275
+ });
276
+ }
277
+ if (!tag) {
278
+ return make("factory-callers", "skip", "No single pinned tag to compare the Callers against.");
279
+ }
280
+ const version = versionForTag(tag);
281
+ const problems = [];
282
+ let pinned = 0;
283
+ for (const name of FACTORY_CALLERS) {
284
+ const path = `${WORKFLOWS_DIR}/${name}.yml`;
285
+ const text = read(path) ?? read(`${WORKFLOWS_DIR}/${name}.yaml`) ?? "";
286
+ for (const m of text.matchAll(
287
+ /\/agent-kit\/\.github\/workflows\/[A-Za-z0-9._-]+\.ya?ml@(\S+)/gi,
288
+ )) {
289
+ pinned++;
290
+ if (m[1] !== tag) problems.push(`${path} pins a reusable workflow at ${m[1]}, not ${tag}.`);
291
+ }
292
+ for (const v of cliPinsOf(text)) {
293
+ pinned++;
294
+ if (v !== version)
295
+ problems.push(`${path} installs the CLI at ${v}, not ${version} (${tag}).`);
296
+ }
297
+ }
298
+ if (problems.length) {
299
+ return make("factory-callers", "fail", "A Factory Caller is not pinned to the tag.", {
300
+ details: [...problems, "`agent-kit upgrade --tag <tag>` moves every pin."],
301
+ });
302
+ }
303
+ if (pinned === 0) {
304
+ return make("factory-callers", "fail", "No Factory Caller is pinned.", {
305
+ details: ["The Callers should call the Kit's reusable workflows at a Release-line tag."],
306
+ });
307
+ }
308
+ return make(
309
+ "factory-callers",
310
+ "pass",
311
+ `All ${FACTORY_CALLERS.length} Factory Callers are present, and their ${pinned} pins name ${tag}.`,
312
+ );
313
+ }
314
+
315
+ /**
316
+ * The Factory's file checks.
317
+ * @param {{ read: (path: string) => string | null, exists: (path: string) => boolean, list: (dir: string) => string[], tag?: string | null }} input
318
+ */
319
+ export function factoryFileChecks({ read, exists, list, tag = null }) {
320
+ const configText = read(CONFIG_PATH);
321
+ const engine = engineOf({ exists, list });
322
+ return [
323
+ checkConfig(configText),
324
+ checkCaps(configText),
325
+ checkAutoTiers(configText),
326
+ checkRiskRules(read(RISK_RULES_PATH)),
327
+ checkCallers({ engine, list, read, tag }),
328
+ ];
329
+ }
@@ -0,0 +1,56 @@
1
+ // The Factory's part of `doctor` and `upgrade` (spec #500, #520), wired in by
2
+ // cli/src/doctor.mjs and cli/src/upgrade.mjs. The checks themselves are
3
+ // functions over injected reads (files.mjs, local.mjs); this file holds the
4
+ // one disk reader, which only reads and never follows a symbolic link out of
5
+ // the checkout. Docs: docs/factory/doctor.md.
6
+
7
+ import { lstatSync, readdirSync, readFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { factoryFileChecks, factoryPresent } from "./files.mjs";
10
+
11
+ export { FACTORY_FILE_CHECKS, factoryFileChecks, engineOf, factoryPresent } from "./files.mjs";
12
+ export { FACTORY_LOCAL_CHECKS, factoryLocalChecks } from "./local.mjs";
13
+ export { ORCHESTRATE_LOCAL_CHECKS } from "./orchestrate.mjs";
14
+
15
+ /** Reads a checkout's files: a regular file's text or null, a folder's file names. */
16
+ export function diskReads(root) {
17
+ const kind = (path) => {
18
+ try {
19
+ const s = lstatSync(join(root, path));
20
+ return s.isSymbolicLink() ? "link" : s.isFile() ? "file" : s.isDirectory() ? "dir" : "other";
21
+ } catch {
22
+ return null;
23
+ }
24
+ };
25
+ return {
26
+ read: (path) => {
27
+ if (kind(path) !== "file") return null;
28
+ try {
29
+ return readFileSync(join(root, path), "utf8").replace(/^/, "");
30
+ } catch {
31
+ return null;
32
+ }
33
+ },
34
+ exists: (path) => kind(path) !== null,
35
+ list: (dir) => {
36
+ if (kind(dir) !== "dir") return [];
37
+ try {
38
+ return readdirSync(join(root, dir)).sort();
39
+ } catch {
40
+ return [];
41
+ }
42
+ },
43
+ };
44
+ }
45
+
46
+ /**
47
+ * The Factory's file checks for a checkout, or none when it has no Factory.
48
+ * @returns {object[]}
49
+ */
50
+ export function factoryFileResults({ root, tag = null }) {
51
+ const reads = diskReads(root);
52
+ return factoryPresent(reads) ? factoryFileChecks({ ...reads, tag }) : [];
53
+ }
54
+
55
+ /** Whether a checkout has a Factory (its files, its bundle or its Callers). */
56
+ export const hasFactory = (root) => factoryPresent(diskReads(root));