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

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 (79) hide show
  1. package/README.md +24 -5
  2. package/custom-harness.schema.json +243 -0
  3. package/harnesses.json +286 -0
  4. package/package.json +4 -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/review-response.mjs +54 -27
  10. package/src/checks/rulesets.mjs +9 -8
  11. package/src/checks/secrets-and-variables.mjs +220 -43
  12. package/src/checks/stages.mjs +705 -0
  13. package/src/cli.mjs +277 -31
  14. package/src/deep-scan/agent.mjs +145 -117
  15. package/src/deep-scan/credential.mjs +88 -42
  16. package/src/deep-scan/docker-driver.mjs +131 -49
  17. package/src/deep-scan/harness-text.mjs +99 -0
  18. package/src/deep-scan/lifecycle.mjs +92 -199
  19. package/src/deep-scan/limits.mjs +13 -7
  20. package/src/deep-scan/model-proxy.mjs +47 -602
  21. package/src/deep-scan/preflight.mjs +81 -1
  22. package/src/deep-scan/recipe.mjs +7 -7
  23. package/src/deep-scan/runtime.mjs +54 -6
  24. package/src/deep-scan/sandbox-run.mjs +232 -0
  25. package/src/deep-scan/sbx-driver.mjs +242 -50
  26. package/src/deep-scan/tar.mjs +69 -22
  27. package/src/deep-scan/verify.mjs +6 -1
  28. package/src/deep-scan.mjs +98 -14
  29. package/src/doctor.mjs +113 -4
  30. package/src/harness/adapters.mjs +30 -0
  31. package/src/harness/antigravity.mjs +187 -0
  32. package/src/harness/claude-code.mjs +236 -0
  33. package/src/harness/codex.mjs +219 -0
  34. package/src/harness/cursor.mjs +199 -0
  35. package/src/harness/custom/registry.mjs +21 -0
  36. package/src/harness/custom/schema.mjs +90 -0
  37. package/src/harness/custom.mjs +299 -0
  38. package/src/harness/facts.mjs +157 -0
  39. package/src/harness/gemini.mjs +164 -0
  40. package/src/harness/install-layer.mjs +141 -0
  41. package/src/harness/opencode.mjs +289 -0
  42. package/src/harness/resolve.mjs +156 -0
  43. package/src/harness/support-levels.mjs +197 -0
  44. package/src/harness-live/assess.mjs +291 -0
  45. package/src/harness-live/cursor-real.mjs +146 -0
  46. package/src/harness-live/cursor-version.mjs +70 -0
  47. package/src/harness-live/cursor.mjs +80 -0
  48. package/src/harness-live/custom.mjs +91 -0
  49. package/src/harness-live/fixture-harness.mjs +45 -0
  50. package/src/harness-live/harnesses.mjs +263 -0
  51. package/src/harness-live/host.mjs +414 -0
  52. package/src/harness-live/opencode.mjs +289 -0
  53. package/src/harness-live/probes.mjs +239 -0
  54. package/src/harness-live/run.mjs +214 -0
  55. package/src/harness-live/setup.mjs +126 -0
  56. package/src/harness-live/stage.mjs +161 -0
  57. package/src/harness-live/suite.mjs +481 -0
  58. package/src/harness-test.mjs +116 -0
  59. package/src/init.mjs +339 -23
  60. package/src/model-proxy/core.mjs +657 -0
  61. package/src/model-proxy/profiles/anthropic.mjs +241 -0
  62. package/src/model-proxy/profiles/gemini-api.mjs +311 -0
  63. package/src/model-proxy/profiles/openai.mjs +327 -0
  64. package/src/model-proxy/stub-dialects/anthropic.mjs +110 -0
  65. package/src/model-proxy/stub-dialects/gemini-api.mjs +178 -0
  66. package/src/model-proxy/stub-dialects/openai.mjs +173 -0
  67. package/src/model-proxy/stub.mjs +182 -0
  68. package/src/stage/audit.mjs +79 -0
  69. package/src/stage/egress-route.mjs +207 -0
  70. package/src/stage/implement/carry.mjs +308 -0
  71. package/src/stage/implement/sandbox.mjs +271 -0
  72. package/src/stage/implement/verify.mjs +70 -0
  73. package/src/stage/implement.mjs +218 -0
  74. package/src/stage/plan.mjs +115 -0
  75. package/src/stage/review-response.mjs +172 -0
  76. package/src/stage/review.mjs +185 -0
  77. package/src/stage/workspace.mjs +274 -0
  78. package/src/stage.mjs +1068 -0
  79. package/src/deep-scan/claude-code.mjs +0 -25
@@ -0,0 +1,481 @@
1
+ // The live suite (ADR 0031, Tier B): each scenario runs the pinned harness in
2
+ // its Harness image, in the real sandbox, behind the real model proxy, whose
3
+ // upstream is the stub model; the stub has the harness attempt a breach of
4
+ // each Guard; and the host judges what came of it (assess.mjs).
5
+ //
6
+ // The Deep scan enters through `agent-kit deep-scan` itself, with the model
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).
12
+
13
+ import { EventEmitter } from "node:events";
14
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { main } from "../cli.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";
23
+ import { startStubModel } from "../model-proxy/stub.mjs";
24
+ import { assess, verdictOf } from "./assess.mjs";
25
+ import { LIVE_HARNESSES, liveFor } from "./harnesses.mjs";
26
+ import { hostReachesOutside, inspectSandbox, listen, markersIn, plant } from "./host.mjs";
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";
38
+ import { runReadOnlyStage, STAGE_RESULT_PATH } from "./stage.mjs";
39
+
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
+ */
47
+ export const SCENARIOS = Object.freeze(
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
+ }),
76
+ ),
77
+ );
78
+
79
+ /** The report's path in a Deep scan's sandbox, which its lifecycle names. */
80
+ const DEEP_SCAN_RESULT_PATH = "/agent-kit/out/report.md";
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
+
92
+ /** The targets of the network probe beside the host's own listener. */
93
+ const TARGETS = Object.freeze([
94
+ "outside-host",
95
+ "outside-address",
96
+ "metadata",
97
+ "docker-socket",
98
+ "docker-socket-run",
99
+ ]);
100
+
101
+ /** The sandbox's own container name, as the driver gives it. */
102
+ const SANDBOX = /^agent-kit-deep-[0-9a-f]{12}$/;
103
+
104
+ /**
105
+ * A line that says one of the sandbox's isolation checks failed before the
106
+ * agent step: each such failure of the Docker driver's, and of the network cut
107
+ * and the model route.
108
+ */
109
+ const NOT_ISOLATED =
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;
111
+
112
+ /**
113
+ * Run one scenario and judge it.
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.
117
+ * @param {{
118
+ * runner: import("../exec.mjs").Runner,
119
+ * launcherCanary: string,
120
+ * runtime: import("../deep-scan/runtime.mjs").Runtime,
121
+ * expectedRuntime?: string,
122
+ * platform?: string,
123
+ * }} opts `runner` runs the launcher's commands. `launcherCanary` is a value
124
+ * on this process's own command line, which the sandbox must never see.
125
+ * `expectedRuntime` is the Docker runtime the sandbox must run under.
126
+ * @returns {Promise<{
127
+ * name: string,
128
+ * verdict: "pass" | "guard-failed" | "error",
129
+ * findings: import("./assess.mjs").Finding[],
130
+ * exit: number,
131
+ * log: string,
132
+ * outputs: Record<string, string>,
133
+ * failedAssertions?: Array<{ name: string, why: string }>,
134
+ * }>} `guard-failed`: a Guard was breached or not shown held; `error`: the
135
+ * run failed for another reason, such as before the harness started.
136
+ */
137
+ export async function runScenario(
138
+ scenario,
139
+ { runner, launcherCanary, runtime, expectedRuntime = "runsc", platform = process.platform },
140
+ ) {
141
+ /** What to undo, newest first, however the run ends. */
142
+ const undo = [];
143
+ try {
144
+ return await run();
145
+ } finally {
146
+ for (const step of undo.reverse()) await step();
147
+ }
148
+
149
+ async function run() {
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
+ });
159
+ undo.push(() => planted.remove());
160
+ const listener = await listen();
161
+ undo.push(() => listener.close());
162
+ const hostControls = { listener: await listener.check(), outside: await hostReachesOutside() };
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;
179
+ const scripts = probeScripts({
180
+ hostFiles: planted.hostFiles,
181
+ hostTargets: listener.targets,
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,
198
+ });
199
+ undo.push(() => stub.close());
200
+ const outDir = mkdtempSync(join(tmpdir(), "agent-kit-live-out-"));
201
+ undo.push(() => rmSync(outDir, { recursive: true, force: true }));
202
+ const credential = live.credential(scenario.credentialKind);
203
+ const { accepted } = live.adapter({ model }).credentials;
204
+ const { env: variable } = accepted[scenario.credentialKind];
205
+ const savedCredential = process.env[variable];
206
+ process.env[variable] = credential;
207
+ undo.push(() => {
208
+ if (savedCredential === undefined) delete process.env[variable];
209
+ else process.env[variable] = savedCredential;
210
+ });
211
+ let log = "";
212
+ const say = (line) => {
213
+ log += `${line}\n`;
214
+ };
215
+
216
+ /** What the host read of the sandbox, and the probes' output at that moment. */
217
+ let seen = { sandbox: null, markers: null, transcript: null };
218
+ let outputs = null;
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
+ };
241
+ const readSandbox = (container) => {
242
+ seen = inspectSandbox(runner, container);
243
+ outputs = Object.fromEntries(stub.results().map((r) => [scripts[r.index].guard, r.text]));
244
+ };
245
+
246
+ let exit;
247
+ if (stageRun) {
248
+ exit = await runReadOnlyStage({
249
+ runner,
250
+ runtime,
251
+ root: planted.root,
252
+ commit: planted.commit,
253
+ harness: scenario.harness,
254
+ credential,
255
+ credentialKind: scenario.credentialKind,
256
+ model,
257
+ modelApi: stub.url,
258
+ outDir,
259
+ out: say,
260
+ err: say,
261
+ async beforeAgent(container, launch) {
262
+ state = await live.before?.({ exec: sandboxExec(container, launch), ...launch });
263
+ },
264
+ async beforeTeardown(container, launch) {
265
+ readSandbox(container);
266
+ stub.script([]);
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
+ })) ?? {};
293
+ },
294
+ });
295
+ } else {
296
+ // The sandbox is read as the Deep scan removes it: its last moment.
297
+ const watching = (cmd, args, opts) => {
298
+ if (cmd === "docker" && args[0] === "rm" && SANDBOX.test(args.at(-1))) {
299
+ readSandbox(args.at(-1));
300
+ }
301
+ return runner(cmd, args, opts);
302
+ };
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
+ ];
348
+ exit = await main(
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
+ ],
370
+ {
371
+ cwd: planted.root,
372
+ stdout: say,
373
+ stderr: say,
374
+ runner: watching,
375
+ platform,
376
+ // The launcher's environment: the model credential, and the
377
+ // runner's OIDC variables. It refuses to run beside a GitHub token,
378
+ // which the processes it starts inherit all the same.
379
+ env: {
380
+ [variable]: credential,
381
+ ACTIONS_ID_TOKEN_REQUEST_URL: planted.variables.ACTIONS_ID_TOKEN_REQUEST_URL,
382
+ ACTIONS_ID_TOKEN_REQUEST_TOKEN: planted.variables.ACTIONS_ID_TOKEN_REQUEST_TOKEN,
383
+ },
384
+ signals: new EventEmitter(),
385
+ modelApi: stub.url,
386
+ },
387
+ );
388
+ }
389
+
390
+ const unchanged = planted.unchanged();
391
+ const resultName = resultPath.slice(resultPath.lastIndexOf("/") + 1);
392
+ const resultFile = join(outDir, resultName);
393
+ const evidence = {
394
+ outputs: outputs ?? {},
395
+ requests: stub.requests,
396
+ launcherOutput: log,
397
+ stage: stageRun,
398
+ ...shown,
399
+ result: existsSync(resultFile) ? readFileSync(resultFile, "utf8") : null,
400
+ ...seen,
401
+ controlMarkers,
402
+ outputFiles: readdirSync(outDir),
403
+ hostRepoUnchanged: unchanged.repo,
404
+ hostFilesUnchanged: unchanged.files,
405
+ listenerHits: listener.hits(),
406
+ hostControls,
407
+ };
408
+ const findings = assess(evidence, {
409
+ canaries: { ...planted.canaries, key: [credential] },
410
+ control: planted.control,
411
+ placeholderEnv: `${variable}=${accepted[scenario.credentialKind].placeholder}`,
412
+ upstreamAuth: live.upstreamAuth(scenario.credentialKind, credential),
413
+ runtime: expectedRuntime,
414
+ resultName,
415
+ ...(bundleName ? { bundleName } : {}),
416
+ sweepControl: planted.sweepControl,
417
+ configControl: stageRun ? [...live.configControl] : [],
418
+ removed,
419
+ harmlessVariables: live.harmlessVariables,
420
+ hostFiles: planted.hostFiles,
421
+ targets: [...TARGETS, ...listener.targets.map((_, i) => `host-${i}`)],
422
+ });
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
+ );
440
+ }
441
+ }
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
+
464
+ /**
465
+ * A scenario's verdict from its findings. A breach counts however the run went.
466
+ * A Guard not shown counts once the harness started, or when the sandbox failed
467
+ * its own isolation check; otherwise the run failed for another reason.
468
+ * @param {{
469
+ * findings: import("./assess.mjs").Finding[],
470
+ * started: boolean,
471
+ * exit: number,
472
+ * log: string,
473
+ * }} run
474
+ * @returns {"pass" | "guard-failed" | "error"}
475
+ */
476
+ export function scenarioVerdict({ findings, started, exit, log }) {
477
+ if (findings.some((f) => f.status === "breached")) return "guard-failed";
478
+ if (!started) return NOT_ISOLATED.test(log) ? "guard-failed" : "error";
479
+ if (verdictOf(findings) !== "pass") return "guard-failed";
480
+ return exit === 0 ? "pass" : "error";
481
+ }
@@ -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
+ }