@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
@@ -5,38 +5,90 @@
5
5
  //
6
6
  // The Deep scan enters through `agent-kit deep-scan` itself, with the model
7
7
  // API pointed at the stub; the read-only Stage through stage.mjs.
8
+ // The audit Stage enters through `agent-kit stage audit` itself, likewise, and
9
+ // the review, plan and implement Stages through `agent-kit stage review`,
10
+ // `agent-kit stage plan` and `agent-kit stage implement`. The setup scenario
11
+ // is the implement Stage on a Consumer's image, with setup commands (setup.mjs).
8
12
 
9
13
  import { EventEmitter } from "node:events";
10
- import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
14
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
15
  import { tmpdir } from "node:os";
12
16
  import { join } from "node:path";
13
17
  import { main } from "../cli.mjs";
14
- import { claudeCode, TOOLS } from "../harness/claude-code.mjs";
18
+ import * as implement from "../stage/implement.mjs";
19
+ import * as plan from "../stage/plan.mjs";
20
+ import * as review from "../stage/review.mjs";
21
+ import * as reviewResponse from "../stage/review-response.mjs";
22
+ import { SUPPORT_TABLE } from "../harness/support-levels.mjs";
15
23
  import { startStubModel } from "../model-proxy/stub.mjs";
16
24
  import { assess, verdictOf } from "./assess.mjs";
17
- import {
18
- FAKE_CREDENTIAL,
19
- hostReachesOutside,
20
- inspectSandbox,
21
- listen,
22
- markersIn,
23
- plant,
24
- } from "./host.mjs";
25
+ import { LIVE_HARNESSES, liveFor } from "./harnesses.mjs";
26
+ import { hostReachesOutside, inspectSandbox, listen, markersIn, plant } from "./host.mjs";
25
27
  import { MARKER_DIR, probeScripts } from "./probes.mjs";
28
+ import {
29
+ SETUP_HARNESS,
30
+ SETUP_IMAGE,
31
+ SETUP_LEAVES_THE_AGENT_ALONE,
32
+ SETUP_PATH,
33
+ SETUP_PROBE,
34
+ SETUP_REACHES_ITS_REGISTRY_ALONE,
35
+ SETUP_REGISTRY,
36
+ SETUP_SCRIPT,
37
+ } from "./setup.mjs";
26
38
  import { runReadOnlyStage, STAGE_RESULT_PATH } from "./stage.mjs";
27
39
 
28
- /** Every run the suite makes: each way Claude Code is launched, on each credential kind. */
40
+ /**
41
+ /**
42
+ * Every run the suite makes: each harness as a read-only Stage, as a Deep scan
43
+ * and as each CI Stage the kit runs on it, on each credential kind it takes,
44
+ * and through each provider it is proven on; and one run of the setup inside
45
+ * the sandbox.
46
+ */
29
47
  export const SCENARIOS = Object.freeze(
30
- ["read-only-stage", "deep-scan"].flatMap((run) =>
31
- ["api-key", "subscription"].map((credentialKind) =>
32
- Object.freeze({ name: `claude-code ${run} (${credentialKind})`, run, credentialKind }),
33
- ),
48
+ Object.entries(LIVE_HARNESSES).flatMap(([harness, { profiles }]) =>
49
+ (profiles === undefined ? [undefined] : Object.keys(profiles)).flatMap((profile) => {
50
+ const { adapter, model } = liveFor({ harness, profile });
51
+ return [
52
+ "read-only-stage",
53
+ "deep-scan",
54
+ // Only where this kit runs the Stage on the harness.
55
+ ...(SUPPORT_TABLE[harness]["security-audit"].wired ? ["audit-stage"] : []),
56
+ ...(SUPPORT_TABLE[harness].review.wired ? ["review-stage"] : []),
57
+ ...(SUPPORT_TABLE[harness].plan.wired ? ["plan-stage"] : []),
58
+ ...(SUPPORT_TABLE[harness].implement.wired ? ["implement-stage"] : []),
59
+ ...(SUPPORT_TABLE[harness]["review-response"].wired ? ["review-response-stage"] : []),
60
+ ...(harness === SETUP_HARNESS ? ["setup-stage"] : []),
61
+ ].flatMap((run) =>
62
+ // The setup is the Launcher's own, so one credential kind shows it.
63
+ Object.keys(adapter({ model }).credentials.accepted)
64
+ .slice(0, run === "setup-stage" ? 1 : undefined)
65
+ .map((credentialKind) =>
66
+ Object.freeze({
67
+ name: `${harness}${profile === undefined ? "" : `/${profile}`} ${run} (${credentialKind})`,
68
+ harness,
69
+ ...(profile === undefined ? {} : { profile }),
70
+ run,
71
+ credentialKind,
72
+ }),
73
+ ),
74
+ );
75
+ }),
34
76
  ),
35
77
  );
36
78
 
37
79
  /** The report's path in a Deep scan's sandbox, which its lifecycle names. */
38
80
  const DEEP_SCAN_RESULT_PATH = "/agent-kit/out/report.md";
39
81
 
82
+ /** The CI Stage each scenario of `agent-kit stage` runs. */
83
+ const CI_STAGES = Object.freeze({
84
+ "audit-stage": "audit",
85
+ "review-stage": "review",
86
+ "plan-stage": "plan",
87
+ "implement-stage": "implement",
88
+ "review-response-stage": "review-response",
89
+ "setup-stage": "implement",
90
+ });
91
+
40
92
  /** The targets of the network probe beside the host's own listener. */
41
93
  const TARGETS = Object.freeze([
42
94
  "outside-host",
@@ -46,9 +98,6 @@ const TARGETS = Object.freeze([
46
98
  "docker-socket-run",
47
99
  ]);
48
100
 
49
- /** The markers the control run must leave, by the start of their names. */
50
- const CONTROL_MARKERS = Object.freeze(["settings-", "local-", "mcp-server"]);
51
-
52
101
  /** The sandbox's own container name, as the driver gives it. */
53
102
  const SANDBOX = /^agent-kit-deep-[0-9a-f]{12}$/;
54
103
 
@@ -60,33 +109,11 @@ const SANDBOX = /^agent-kit-deep-[0-9a-f]{12}$/;
60
109
  const NOT_ISOLATED =
61
110
  /^FAILED {2}(.* is not isolated|the sandbox is not on .* alone|the network is not cut|more than the model route is open)\b/m;
62
111
 
63
- /**
64
- * The control for the checkout-config probe: the harness started again in the
65
- * same sandbox with the checkout's config loaded on purpose, so a run in which
66
- * none of it left a marker is known to have been able to.
67
- * @param {{ url: string }} launch
68
- */
69
- function loadingConfig({ url }) {
70
- return [
71
- "claude",
72
- "--print",
73
- "--setting-sources",
74
- "user,project,local",
75
- "--settings",
76
- JSON.stringify({ env: { ANTHROPIC_BASE_URL: url } }),
77
- "--tools",
78
- TOOLS.join(","),
79
- "--permission-mode",
80
- "dontAsk",
81
- "--no-session-persistence",
82
- "--max-turns",
83
- "2",
84
- ];
85
- }
86
-
87
112
  /**
88
113
  * Run one scenario and judge it.
89
- * @param {typeof SCENARIOS[number]} scenario
114
+ * @param {typeof SCENARIOS[number] & {
115
+ * live?: import("./harnesses.mjs").LiveHarness }} scenario `live` is the
116
+ * entry of a harness the suite has none for: a Custom harness's.
90
117
  * @param {{
91
118
  * runner: import("../exec.mjs").Runner,
92
119
  * launcherCanary: string,
@@ -103,6 +130,7 @@ function loadingConfig({ url }) {
103
130
  * exit: number,
104
131
  * log: string,
105
132
  * outputs: Record<string, string>,
133
+ * failedAssertions?: Array<{ name: string, why: string }>,
106
134
  * }>} `guard-failed`: a Guard was breached or not shown held; `error`: the
107
135
  * run failed for another reason, such as before the harness started.
108
136
  */
@@ -119,24 +147,61 @@ export async function runScenario(
119
147
  }
120
148
 
121
149
  async function run() {
122
- const planted = plant({ runner, launcherCanary });
150
+ const stageRun = scenario.run === "read-only-stage";
151
+ const live = scenario.live ?? liveFor(scenario);
152
+ const planted = plant({
153
+ runner,
154
+ launcherCanary,
155
+ envFiles: stageRun,
156
+ committed: live.committed,
157
+ configPaths: live.committed === undefined ? [] : live.removed,
158
+ });
123
159
  undo.push(() => planted.remove());
124
160
  const listener = await listen();
125
161
  undo.push(() => listener.close());
126
162
  const hostControls = { listener: await listener.check(), outside: await hostReachesOutside() };
127
- const stageRun = scenario.run === "read-only-stage";
128
- const resultPath = stageRun ? STAGE_RESULT_PATH : DEEP_SCAN_RESULT_PATH;
163
+ const { model } = live;
164
+ /** The CI Stage a scenario runs through `agent-kit stage`, if it is one. */
165
+ const ciStage = CI_STAGES[scenario.run];
166
+ /** A writing Stage's second output, its git bundle. */
167
+ const bundleName =
168
+ ciStage === "implement" || ciStage === "review-response" ? "branch.bundle" : null;
169
+ const resultPath = stageRun
170
+ ? STAGE_RESULT_PATH
171
+ : ({
172
+ review: review.RESULT_PATH,
173
+ plan: plan.RESULT_PATH,
174
+ implement: implement.RESULT_PATH,
175
+ "review-response": reviewResponse.RESULT_PATH,
176
+ }[ciStage] ?? DEEP_SCAN_RESULT_PATH);
177
+ // `agent-kit stage` removes every path the adapter lists from its copy.
178
+ const removed = ciStage ? live.adapter({ model }).checkoutConfig : live.removed;
129
179
  const scripts = probeScripts({
130
180
  hostFiles: planted.hostFiles,
131
181
  hostTargets: listener.targets,
132
182
  resultPath,
183
+ baseUrlVariable: live.baseUrlVariable,
184
+ removed,
185
+ // A valid audit result opens with the report's heading, a review's is
186
+ // the schema's JSON, and a plan's is Markdown under its own heading.
187
+ ...(ciStage === "audit" ? { resultHeading: "## Security audit report" } : {}),
188
+ ...(ciStage === "review" ? { resultAsReview: true } : {}),
189
+ ...(ciStage === "plan" ? { resultAsPlan: true } : {}),
190
+ ...(ciStage === "implement" ? { resultAsImplement: true } : {}),
191
+ ...(ciStage === "review-response" ? { resultAsReviewResponse: true } : {}),
192
+ ...(scenario.run === "setup-stage" ? { extra: { setup: SETUP_PROBE } } : {}),
193
+ });
194
+ const stub = await startStubModel({
195
+ commands: scripts.map((s) => s.script),
196
+ dialect: live.dialect,
197
+ shellTool: live.shellTool,
133
198
  });
134
- const stub = await startStubModel({ commands: scripts.map((s) => s.script) });
135
199
  undo.push(() => stub.close());
136
200
  const outDir = mkdtempSync(join(tmpdir(), "agent-kit-live-out-"));
137
201
  undo.push(() => rmSync(outDir, { recursive: true, force: true }));
138
- const credential = FAKE_CREDENTIAL[scenario.credentialKind]();
139
- const { env: variable } = claudeCode().credentials.accepted[scenario.credentialKind];
202
+ const credential = live.credential(scenario.credentialKind);
203
+ const { accepted } = live.adapter({ model }).credentials;
204
+ const { env: variable } = accepted[scenario.credentialKind];
140
205
  const savedCredential = process.env[variable];
141
206
  process.env[variable] = credential;
142
207
  undo.push(() => {
@@ -152,6 +217,27 @@ export async function runScenario(
152
217
  let seen = { sandbox: null, markers: null, transcript: null };
153
218
  let outputs = null;
154
219
  let controlMarkers = null;
220
+ /** What the harness's own runs in the sandbox showed. */
221
+ let shown = {};
222
+ let state;
223
+ const sandboxExec =
224
+ (container, launch) =>
225
+ async (argv, { env = [], stdin, detach = false } = {}) => {
226
+ const r = await runner.start(
227
+ "docker",
228
+ [
229
+ "exec",
230
+ detach ? "--detach" : "-i",
231
+ ...[...launch.env, ...env].flatMap((v) => ["--env", v]),
232
+ "--workdir",
233
+ "/workspace",
234
+ container,
235
+ ...argv,
236
+ ],
237
+ { stdin: stdin ?? "", signal: AbortSignal.timeout(120_000) },
238
+ );
239
+ return { status: r.status, stdout: String(r.stdout ?? "") };
240
+ };
155
241
  const readSandbox = (container) => {
156
242
  seen = inspectSandbox(runner, container);
157
243
  outputs = Object.fromEntries(stub.results().map((r) => [scripts[r.index].guard, r.text]));
@@ -164,31 +250,46 @@ export async function runScenario(
164
250
  runtime,
165
251
  root: planted.root,
166
252
  commit: planted.commit,
253
+ harness: scenario.harness,
167
254
  credential,
168
255
  credentialKind: scenario.credentialKind,
256
+ model,
169
257
  modelApi: stub.url,
170
258
  outDir,
171
259
  out: say,
172
260
  err: say,
261
+ async beforeAgent(container, launch) {
262
+ state = await live.before?.({ exec: sandboxExec(container, launch), ...launch });
263
+ },
173
264
  async beforeTeardown(container, launch) {
174
265
  readSandbox(container);
175
266
  stub.script([]);
176
- runner("docker", ["exec", container, "rm", "-rf", MARKER_DIR]);
177
- const control = loadingConfig(launch);
178
- await runner.start(
179
- "docker",
180
- [
181
- "exec",
182
- "-i",
183
- ...launch.env.flatMap((v) => ["--env", v]),
184
- "--workdir",
185
- "/workspace",
186
- container,
187
- ...control,
188
- ],
189
- { stdin: "Say that you are done.", signal: AbortSignal.timeout(120_000) },
190
- );
191
- controlMarkers = markersIn(runner, container);
267
+ // A harness with no control proves nothing of its config loading.
268
+ if (live.control !== undefined) {
269
+ runner("docker", ["exec", container, "rm", "-rf", MARKER_DIR]);
270
+ const control = live.control(launch);
271
+ await runner.start(
272
+ "docker",
273
+ [
274
+ "exec",
275
+ "-i",
276
+ ...launch.env.flatMap((v) => ["--env", v]),
277
+ "--workdir",
278
+ "/workspace",
279
+ container,
280
+ ...control.argv,
281
+ ],
282
+ { stdin: control.stdin, signal: AbortSignal.timeout(120_000) },
283
+ );
284
+ controlMarkers = markersIn(runner, container);
285
+ }
286
+ shown =
287
+ (await live.after?.({
288
+ exec: sandboxExec(container, launch),
289
+ ...launch,
290
+ requests: () => stub.requests,
291
+ state,
292
+ })) ?? {};
192
293
  },
193
294
  });
194
295
  } else {
@@ -200,23 +301,72 @@ export async function runScenario(
200
301
  return runner(cmd, args, opts);
201
302
  };
202
303
  watching.start = runner.start;
304
+ // A CI Stage's brief and private streams stay out of `outDir`, which
305
+ // holds the one result.
306
+ const sink = mkdtempSync(join(tmpdir(), "agent-kit-live-stage-"));
307
+ undo.push(() => rmSync(sink, { recursive: true, force: true }));
308
+ if (ciStage) writeFileSync(join(sink, "brief.md"), `# Stage brief\n\nRun the ${ciStage}.\n`);
309
+ // The review's own file, copied in beside the brief.
310
+ if (ciStage === "review") writeFileSync(join(sink, "review-diff.patch"), "");
311
+ const setup = scenario.run === "setup-stage";
312
+ if (setup) writeFileSync(join(sink, "setup.sh"), SETUP_SCRIPT);
313
+ const stageArgs = [
314
+ "stage",
315
+ ciStage,
316
+ "--harness",
317
+ scenario.harness,
318
+ "--proving-run",
319
+ "--credential",
320
+ scenario.credentialKind,
321
+ "--max-turns",
322
+ "40",
323
+ "--scan-minutes",
324
+ "10",
325
+ "--brief",
326
+ join(sink, "brief.md"),
327
+ "--result",
328
+ join(outDir, resultPath.slice(resultPath.lastIndexOf("/") + 1)),
329
+ ...(ciStage === "review" ? ["--input", join(sink, "review-diff.patch")] : []),
330
+ ...(bundleName ? ["--bundle", join(outDir, bundleName)] : []),
331
+ ...(setup
332
+ ? [
333
+ "--sandbox-image",
334
+ SETUP_IMAGE,
335
+ "--setup-commands",
336
+ join(sink, "setup.sh"),
337
+ "--setup-registries",
338
+ SETUP_REGISTRY,
339
+ "--setup-paths",
340
+ SETUP_PATH,
341
+ ]
342
+ : []),
343
+ "--transcript",
344
+ join(sink, "transcript.log"),
345
+ "--error-log",
346
+ join(sink, "errors.log"),
347
+ ];
203
348
  exit = await main(
204
- [
205
- "deep-scan",
206
- // A Proving run (ADR 0028): the kit's own repository running the
207
- // Launcher, on a pair that may be below `tried`.
208
- "--proving-run",
209
- "--default-branch",
210
- "main",
211
- "--credential",
212
- scenario.credentialKind,
213
- "--max-turns",
214
- "40",
215
- "--scan-minutes",
216
- "10",
217
- "--report",
218
- join(outDir, "report.md"),
219
- ],
349
+ ciStage
350
+ ? stageArgs
351
+ : [
352
+ "deep-scan",
353
+ "--harness",
354
+ scenario.harness,
355
+ // A Proving run (ADR 0028): the kit's own repository running the
356
+ // Launcher, on a pair that may be below `tried`.
357
+ "--proving-run",
358
+ "--default-branch",
359
+ "main",
360
+ "--credential",
361
+ scenario.credentialKind,
362
+ ...(model === undefined ? [] : ["--model", model]),
363
+ "--max-turns",
364
+ "40",
365
+ "--scan-minutes",
366
+ "10",
367
+ "--report",
368
+ join(outDir, "report.md"),
369
+ ],
220
370
  {
221
371
  cwd: planted.root,
222
372
  stdout: say,
@@ -244,6 +394,8 @@ export async function runScenario(
244
394
  outputs: outputs ?? {},
245
395
  requests: stub.requests,
246
396
  launcherOutput: log,
397
+ stage: stageRun,
398
+ ...shown,
247
399
  result: existsSync(resultFile) ? readFileSync(resultFile, "utf8") : null,
248
400
  ...seen,
249
401
  controlMarkers,
@@ -253,33 +405,62 @@ export async function runScenario(
253
405
  listenerHits: listener.hits(),
254
406
  hostControls,
255
407
  };
256
- const { accepted } = claudeCode().credentials;
257
408
  const findings = assess(evidence, {
258
409
  canaries: { ...planted.canaries, key: [credential] },
259
410
  control: planted.control,
260
411
  placeholderEnv: `${variable}=${accepted[scenario.credentialKind].placeholder}`,
261
- upstreamAuth:
262
- scenario.credentialKind === "api-key"
263
- ? ["x-api-key", credential]
264
- : ["authorization", `Bearer ${credential}`],
412
+ upstreamAuth: live.upstreamAuth(scenario.credentialKind, credential),
265
413
  runtime: expectedRuntime,
266
414
  resultName,
415
+ ...(bundleName ? { bundleName } : {}),
267
416
  sweepControl: planted.sweepControl,
268
- configControl: stageRun ? [...CONTROL_MARKERS] : [],
417
+ configControl: stageRun ? [...live.configControl] : [],
418
+ removed,
419
+ harmlessVariables: live.harmlessVariables,
269
420
  hostFiles: planted.hostFiles,
270
421
  targets: [...TARGETS, ...listener.targets.map((_, i) => `host-${i}`)],
271
422
  });
272
- return {
273
- name: scenario.name,
274
- verdict: scenarioVerdict({ findings, started: stub.requests.length > 0, exit, log }),
275
- findings,
276
- exit,
277
- log,
278
- outputs: evidence.outputs,
279
- };
423
+ return withAssertions(
424
+ {
425
+ name: scenario.name,
426
+ verdict: scenarioVerdict({ findings, started: stub.requests.length > 0, exit, log }),
427
+ findings,
428
+ exit,
429
+ log,
430
+ outputs: evidence.outputs,
431
+ },
432
+ [
433
+ ...(live.assertions ?? []),
434
+ ...(scenario.run === "setup-stage"
435
+ ? [SETUP_REACHES_ITS_REGISTRY_ALONE, SETUP_LEAVES_THE_AGENT_ALONE]
436
+ : []),
437
+ ],
438
+ evidence,
439
+ );
280
440
  }
281
441
  }
282
442
 
443
+ /**
444
+ * A scenario's result with the harness's own named assertions judged: one that
445
+ * fails is listed by name with why, and makes a scenario that otherwise passed
446
+ * `error`, so the run and the `Harness live` check fail. It is not a Guard
447
+ * failure: it labels no issue `guard-failure` and so blocks no release, and a
448
+ * verdict already worse stays.
449
+ * @template {{ verdict: string }} R
450
+ * @param {R} result
451
+ * @param {ReadonlyArray<import("./harnesses.mjs").NamedAssertion>} assertions
452
+ * @param {Parameters<import("./harnesses.mjs").NamedAssertion["check"]>[0]} evidence
453
+ * @returns {R & { failedAssertions: Array<{ name: string, why: string }> }}
454
+ */
455
+ export function withAssertions(result, assertions, evidence) {
456
+ const failedAssertions = assertions.flatMap(({ name, check }) => {
457
+ const why = check(evidence);
458
+ return why === null ? [] : [{ name, why }];
459
+ });
460
+ const failed = result.verdict === "pass" && failedAssertions.length > 0;
461
+ return { ...result, verdict: failed ? "error" : result.verdict, failedAssertions };
462
+ }
463
+
283
464
  /**
284
465
  * A scenario's verdict from its findings. A breach counts however the run went.
285
466
  * A Guard not shown counts once the harness started, or when the sandbox failed
@@ -0,0 +1,116 @@
1
+ // `agent-kit harness test custom:<name>`: the live probe suite (ADR 0031) on a
2
+ // Consumer's own Custom harness file, as the trusted commit holds it. The
3
+ // harness is installed from npm, runs in the real sandbox under gVisor behind
4
+ // the real model proxy, whose upstream is the stub model, and attempts a breach
5
+ // of each of the six Guards, which the host judges. No model credential is read
6
+ // or needed. It is the first half of a Proving run (ADR 0028): the second is
7
+ // the real Stage on a real model.
8
+
9
+ import { createHash, randomBytes } from "node:crypto";
10
+ import { appendFileSync } from "node:fs";
11
+ import { writeRunSummary } from "./deep-scan/preflight.mjs";
12
+ import { selectRuntime } from "./deep-scan/runtime.mjs";
13
+ import { isCustom } from "./harness/custom/registry.mjs";
14
+ import { loadHarness } from "./harness/resolve.mjs";
15
+ import { CLI_VERSION } from "./tags.mjs";
16
+
17
+ const DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/harnesses.md#custom-harness`;
18
+ const NAME = /^custom:[A-Za-z0-9][A-Za-z0-9._-]*$/;
19
+
20
+ /**
21
+ * @param {{
22
+ * cwd: string,
23
+ * runner: import("./exec.mjs").Runner,
24
+ * harness: string,
25
+ * trustedRef?: string,
26
+ * defaultBranch?: string,
27
+ * platform?: string,
28
+ * env?: Record<string, string | undefined>,
29
+ * scenarioRunner?: Function,
30
+ * out: (s: string) => void,
31
+ * err: (s: string) => void,
32
+ * }} opts `scenarioRunner` runs one scenario; only tests pass another.
33
+ * @returns {Promise<number>} 0 when every Guard held in every scenario, 1 when
34
+ * one did not, a run failed or the test was refused, 2 on a usage error
35
+ */
36
+ export async function runHarnessTest({
37
+ cwd,
38
+ runner,
39
+ harness,
40
+ trustedRef,
41
+ defaultBranch,
42
+ platform = process.platform,
43
+ env = process.env,
44
+ scenarioRunner,
45
+ out,
46
+ err,
47
+ }) {
48
+ const refuse = (lines) => {
49
+ for (const [i, line] of lines.entries()) err(i === 0 ? `REFUSED ${line}` : line);
50
+ err(`See ${DOCS_URL}`);
51
+ return 1;
52
+ };
53
+ if (!isCustom(harness) || !NAME.test(harness)) {
54
+ err("harness test runs a Custom harness: name it custom:<name>.");
55
+ return 2;
56
+ }
57
+ const loaded = loadHarness({
58
+ harness,
59
+ runner,
60
+ cwd,
61
+ trustedRef,
62
+ defaultBranch,
63
+ flags: ["--default-branch", "--trusted-ref"],
64
+ });
65
+ if (loaded.refused !== undefined) return refuse(loaded.refused);
66
+
67
+ const choice = selectRuntime({ runner, platform });
68
+ if ("refused" in choice || choice.runtime.id !== "gvisor") {
69
+ return refuse([
70
+ "harness test proves the Guards under gVisor: run it on Linux with runsc registered as a Docker runtime.",
71
+ ...("refused" in choice ? choice.refused : [`This host offers ${choice.runtime.name}.`]),
72
+ ]);
73
+ }
74
+
75
+ const digest = createHash("sha256").update(loaded.text).digest("hex");
76
+ const tested = `${harness} (custom), its file at ${loaded.at}, sha256 ${digest}`;
77
+ out(`Testing ${tested}.`);
78
+ // Imported here: the suite enters through the CLI, which imports this module.
79
+ const { customScenarios } = await import("./harness-live/custom.mjs");
80
+ const { report, runScenarios } = await import("./harness-live/run.mjs");
81
+
82
+ // A made-up secret of this process's own command line, which no sandbox may
83
+ // see: on Linux the process title is what `/proc/<pid>/cmdline` holds.
84
+ const launcherCanary = `AKCANARY-${randomBytes(16).toString("hex")}`;
85
+ const title = process.title;
86
+ process.title = `agent-kit harness test ${launcherCanary}`;
87
+ let results;
88
+ try {
89
+ results = await runScenarios(customScenarios({ harness, text: loaded.text }), {
90
+ runner,
91
+ runtime: choice.runtime,
92
+ launcherCanary,
93
+ platform,
94
+ out,
95
+ ...(scenarioRunner === undefined ? {} : { scenarioRunner }),
96
+ });
97
+ } finally {
98
+ process.title = title;
99
+ }
100
+ const { exit, summary } = report(results);
101
+ out(summary);
102
+ const unwritten = writeRunSummary(env, `${summary}\n\nTested: ${tested}.`);
103
+ if (unwritten !== null) err(`Could not write the run summary: ${unwritten}`);
104
+ if (exit !== 0) {
105
+ err(`FAILED ${harness} did not pass the probe suite, so it earns no attestation.`);
106
+ return exit;
107
+ }
108
+ out(
109
+ [
110
+ `Passed: every Guard held in every scenario. This is the first half of a Proving run.`,
111
+ `For the second, run the Stage itself on a real model with --proving-run (agent-kit deep-scan or agent-kit stage audit, --harness ${harness}), under the same run URL.`,
112
+ `Then record that URL in the file under support_levels, with the level it earned: ${DOCS_URL}`,
113
+ ].join("\n"),
114
+ );
115
+ return 0;
116
+ }