@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,156 @@
1
+ // Which harness a Stage runs on (ADR 0022): `--harness`, else the Stage's
2
+ // `AGENT_KIT_<STAGE>_HARNESS`, else `AGENT_KIT_HARNESS`, else Claude Code. An
3
+ // unknown name is refused before anything runs, with the names there are; so
4
+ // is a harness this version has no adapter for, and, on a security Stage, one
5
+ // the model proxy cannot front (ADR 0023). A Custom harness, `custom:<name>`,
6
+ // is then loaded from the trusted commit (ADR 0027).
7
+
8
+ import { firstLine } from "../exec.mjs";
9
+ import { detectDefaultBranch } from "../init.mjs";
10
+ import { CLI_VERSION } from "../tags.mjs";
11
+ import { ADAPTERS, DEFAULT_HARNESS } from "./adapters.mjs";
12
+ import { isCustom } from "./custom/registry.mjs";
13
+ import { loadCustomFile } from "./custom.mjs";
14
+ import { providerOf } from "./opencode.mjs";
15
+ import { SECURITY_STAGES, STAGES } from "./support-levels.mjs";
16
+
17
+ /** Every harness the kit names; `custom:<name>` names a Custom harness beside them. */
18
+ export const HARNESS_NAMES = Object.freeze([
19
+ "claude-code",
20
+ "codex",
21
+ "gemini",
22
+ "antigravity",
23
+ "opencode",
24
+ "cursor",
25
+ ]);
26
+
27
+ const CUSTOM = /^custom:[A-Za-z0-9][A-Za-z0-9._-]*$/;
28
+
29
+ /** opencode 1.x by its package, `opencode-ai`, or by its version. */
30
+ const OPENCODE_1 = /^opencode(-ai(@.*)?|[@-]v?1(\.[0-9x.]*)?)$/;
31
+ const OPENCODE_1_DOCS_URL = `https://github.com/mnaimfaizy/agent-kit/blob/v${CLI_VERSION}/docs/harnesses.md#opencode-1x`;
32
+
33
+ /**
34
+ * @param {{ stage: string, flag?: string, env?: Record<string, string | undefined> }} opts
35
+ * `stage` is the Stage's name, such as `deep-scan`. `flag` is `--harness`'s
36
+ * value, undefined when it was not given. An empty variable is an unset one.
37
+ * @returns {{ harness: string, from: string } | { refused: string, unknown?: true }}
38
+ * `from` is where the name came from; `unknown` marks a name that is no
39
+ * harness at all. The refused value is never repeated.
40
+ */
41
+ export function resolveHarness({ stage, flag, env = {} }) {
42
+ const own = `AGENT_KIT_${stage.toUpperCase().replace(/-/g, "_")}_HARNESS`;
43
+ const found =
44
+ flag !== undefined
45
+ ? { harness: flag, from: "--harness" }
46
+ : [own, "AGENT_KIT_HARNESS"]
47
+ .filter((name) => env[name])
48
+ .map((name) => ({ harness: env[name], from: name }))[0];
49
+ if (found === undefined) return { harness: DEFAULT_HARNESS, from: "the default" };
50
+ const { harness, from } = found;
51
+ if (OPENCODE_1.test(harness)) {
52
+ return {
53
+ refused: `${from} names opencode 1.x (opencode-ai), which the kit does not run: its opencode harness is 2.x (@opencode/cli), named opencode. Keep 1.x by describing it as a Custom harness: ${OPENCODE_1_DOCS_URL}`,
54
+ unknown: true,
55
+ };
56
+ }
57
+ if (!HARNESS_NAMES.includes(harness) && !CUSTOM.test(harness)) {
58
+ return {
59
+ refused: `${from} names no known harness: it is one of ${HARNESS_NAMES.join(", ")} or custom:<name>.`,
60
+ unknown: true,
61
+ };
62
+ }
63
+ if (harness === "cursor" && SECURITY_STAGES.includes(stage)) {
64
+ const runs = stage === "deep-scan" ? "Deep scan" : "static security audit";
65
+ return {
66
+ refused: `${from} names Cursor CLI, which the model proxy cannot front, so it runs no ${runs}: its key would have to sit in the sandbox, and its spend could not be capped.`,
67
+ };
68
+ }
69
+ if (harness === "cursor" && stage === "review-response") {
70
+ return {
71
+ refused: `${from} names Cursor CLI, which runs no Review response: that Stage runs pull request code beside the key, and Cursor CLI's key sits in the sandbox (ADR 0025).`,
72
+ };
73
+ }
74
+ if (harness === "opencode" && stage !== "deep-scan") {
75
+ return {
76
+ refused: `${from} names opencode, which this version runs on the Deep scan alone.`,
77
+ };
78
+ }
79
+ if (!isCustom(harness) && !Object.hasOwn(ADAPTERS, harness)) {
80
+ return {
81
+ refused: `${from} names a harness with no adapter in this version: the Stage runs on ${Object.keys(ADAPTERS).join(" and ")}.`,
82
+ };
83
+ }
84
+ return found;
85
+ }
86
+
87
+ /**
88
+ * Why `harness` cannot run a Stage on `model`, or null. On opencode the model
89
+ * picks the provider, which needs a model proxy profile (ADR 0023). The
90
+ * refused value is never repeated.
91
+ * @param {string} harness
92
+ * @param {string} [model]
93
+ * @returns {string | null}
94
+ */
95
+ export function modelRefusal(harness, model) {
96
+ if (harness !== "opencode") return null;
97
+ const chosen = providerOf(model);
98
+ return "refused" in chosen ? chosen.refused : null;
99
+ }
100
+
101
+ /**
102
+ * Make `harness` ready to run: a Custom harness's file is read from the
103
+ * trusted commit, the one `trustedRef` names, else the default branch's tip as
104
+ * this checkout has it, and never from the checkout under review. A built-in
105
+ * harness needs nothing.
106
+ * @param {{
107
+ * harness: string,
108
+ * runner: import("../exec.mjs").Runner,
109
+ * cwd: string,
110
+ * trustedRef?: string,
111
+ * defaultBranch?: string,
112
+ * flags?: string[],
113
+ * }} opts `flags` are the caller's own options that name where to read from,
114
+ * for a refusal to advise.
115
+ * @returns {{ refused?: string[] } | { text: string, commit: string, at: string }}
116
+ * For a Custom harness that loaded, the file's text and the commit it is
117
+ * from; for a built-in one, nothing.
118
+ */
119
+ export function loadHarness({ harness, runner, cwd, trustedRef, defaultBranch, flags = [] }) {
120
+ if (!isCustom(harness)) return {};
121
+ const top = runner("git", ["-C", cwd, "rev-parse", "--show-toplevel"]);
122
+ if (top.status !== 0) {
123
+ return {
124
+ refused: [
125
+ top.status === null
126
+ ? `Could not run git: ${firstLine(top.stderr)}`
127
+ : `${cwd} is not a git repository; ${harness} is read from its trusted commit.`,
128
+ ],
129
+ };
130
+ }
131
+ const root = top.stdout.trim();
132
+ const branch = trustedRef ?? defaultBranch ?? detectDefaultBranch(runner, root);
133
+ const ref = trustedRef === undefined ? `refs/heads/${branch}` : trustedRef;
134
+ const found = runner("git", [
135
+ "-C",
136
+ root,
137
+ "rev-parse",
138
+ "--verify",
139
+ "--quiet",
140
+ "--end-of-options",
141
+ `${ref}^{commit}`,
142
+ ]);
143
+ if (found.status !== 0) {
144
+ return {
145
+ refused: [
146
+ trustedRef === undefined
147
+ ? `No local branch ${branch} (the default branch) to read ${harness} from: create or fetch it${flags.length ? `, or pass ${flags.join(" or ")}` : ""}.`
148
+ : `The trusted ref ${trustedRef} is not a commit this checkout has: fetch it, or leave it out.`,
149
+ ],
150
+ };
151
+ }
152
+ const commit = found.stdout.trim();
153
+ const at = `${branch} (${commit.slice(0, 12)})`;
154
+ const loaded = loadCustomFile({ harness, runner, root, commit, at, stages: STAGES });
155
+ return "refused" in loaded ? { refused: loaded.refused } : { text: loaded.text, commit, at };
156
+ }
@@ -0,0 +1,197 @@
1
+ // The Support Level table (ADR 0028): kit-owned, harness by Stage, each cell a
2
+ // level and a link to the run that earned it. It is published inside
3
+ // `cli/harnesses.json` (ADR 0030), which `node scripts/gen_harnesses.mjs`
4
+ // writes from here and the adapters; preflight, `doctor`, `init` and the docs
5
+ // read that file.
6
+ //
7
+ // A pair starts at `documented` when its adapter merges. A level changes only
8
+ // by a pull request that edits its cell here and cites the run:
9
+ //
10
+ // documented merged with its adapter; no run recorded.
11
+ // tried one recorded run of the Stage on the harness through the
12
+ // Launcher, in this repository, with a valid Stage result and
13
+ // every Guard probe passing. Any other gap is named.
14
+ // verified a recorded run with no named gap: the Stage's whole outcome
15
+ // landed, and the wall clock and token cap were seen to hold.
16
+ //
17
+ // A pair whose Guard probe fails has no level (`level: null`) and is refused.
18
+
19
+ /** Every Stage, in rollout order. Static security audit and Deep scan are two. */
20
+ export const STAGES = Object.freeze([
21
+ "deep-scan",
22
+ "security-audit",
23
+ "review",
24
+ "plan",
25
+ "implement",
26
+ "review-response",
27
+ ]);
28
+
29
+ /** The Stages refused on a pair below `tried`, outside a Proving run. */
30
+ export const SECURITY_STAGES = Object.freeze(["deep-scan", "security-audit"]);
31
+
32
+ /** The levels, lowest first. */
33
+ export const SUPPORT_LEVELS = Object.freeze(["documented", "tried", "verified"]);
34
+
35
+ const documented = () => ({ level: "documented", run: null });
36
+
37
+ /**
38
+ * The Stages this kit runs on each harness: the ones whose reusable workflow's
39
+ * check step does not refuse it as "not wired". A contract test holds the two
40
+ * equal, so the pull request that wires a Stage adds it here.
41
+ * @type {Readonly<Record<string, readonly string[]>>}
42
+ */
43
+ const WIRED = Object.freeze({
44
+ "claude-code": STAGES,
45
+ codex: ["deep-scan", "security-audit", "review", "plan", "implement", "review-response"],
46
+ gemini: ["deep-scan", "review", "plan", "implement", "review-response"],
47
+ antigravity: ["deep-scan", "review", "plan", "implement", "review-response"],
48
+ opencode: ["deep-scan"],
49
+ cursor: ["plan", "implement", "review"],
50
+ });
51
+
52
+ /**
53
+ * The highest level a harness may hold, where its CLI cannot be pinned (ADR
54
+ * 0028): Cursor CLI's backend changes behind the binary, so it stops at
55
+ * `tried`. Building the table fails on a cell above its cap.
56
+ * @type {Readonly<Record<string, string>>}
57
+ */
58
+ export const LEVEL_CAPS = Object.freeze({ cursor: "tried" });
59
+
60
+ /** @type {Record<string, Record<string, { level: string | null, run: string | null }>>} */
61
+ const LEVELS = {
62
+ "claude-code": {
63
+ "deep-scan": {
64
+ level: "tried",
65
+ run: "https://github.com/mnaimfaizy/agent-kit/issues/458#issuecomment-7249921732",
66
+ },
67
+ "security-audit": {
68
+ level: "tried",
69
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46854989738",
70
+ },
71
+ review: {
72
+ level: "tried",
73
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46853470393",
74
+ },
75
+ plan: {
76
+ level: "tried",
77
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46849892166",
78
+ },
79
+ implement: {
80
+ level: "tried",
81
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46850644168",
82
+ },
83
+ "review-response": {
84
+ level: "tried",
85
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46853902574",
86
+ },
87
+ },
88
+ codex: {
89
+ "deep-scan": documented(),
90
+ "security-audit": {
91
+ level: "tried",
92
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46844164694",
93
+ },
94
+ review: {
95
+ level: "tried",
96
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46835416383",
97
+ },
98
+ plan: {
99
+ level: "tried",
100
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46826363622",
101
+ },
102
+ implement: {
103
+ level: "tried",
104
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46833250256",
105
+ },
106
+ "review-response": {
107
+ level: "tried",
108
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/46837975839",
109
+ },
110
+ },
111
+ gemini: {
112
+ "deep-scan": documented(),
113
+ "security-audit": documented(),
114
+ review: {
115
+ level: "tried",
116
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47025534828",
117
+ },
118
+ plan: {
119
+ level: "tried",
120
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47022825316",
121
+ },
122
+ implement: {
123
+ level: "tried",
124
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47023347347",
125
+ },
126
+ "review-response": {
127
+ level: "tried",
128
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47027665621",
129
+ },
130
+ },
131
+ antigravity: {
132
+ "deep-scan": documented(),
133
+ "security-audit": documented(),
134
+ review: {
135
+ level: "tried",
136
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47069605427",
137
+ },
138
+ plan: {
139
+ level: "tried",
140
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47068109902",
141
+ },
142
+ implement: {
143
+ level: "tried",
144
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47068557808",
145
+ },
146
+ "review-response": {
147
+ level: "tried",
148
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47070131711",
149
+ },
150
+ },
151
+ opencode: {
152
+ "deep-scan": documented(),
153
+ "security-audit": documented(),
154
+ review: documented(),
155
+ plan: documented(),
156
+ implement: documented(),
157
+ "review-response": documented(),
158
+ },
159
+ cursor: {
160
+ "deep-scan": documented(),
161
+ "security-audit": documented(),
162
+ review: documented(),
163
+ plan: {
164
+ level: "tried",
165
+ run: "https://github.com/mnaimfaizy/agent-kit/actions/runs/47244849657",
166
+ },
167
+ implement: documented(),
168
+ "review-response": documented(),
169
+ },
170
+ };
171
+
172
+ for (const [harness, cap] of Object.entries(LEVEL_CAPS)) {
173
+ for (const [stage, { level }] of Object.entries(LEVELS[harness])) {
174
+ if (level !== null && SUPPORT_LEVELS.indexOf(level) > SUPPORT_LEVELS.indexOf(cap)) {
175
+ throw new Error(`${harness} on ${stage} is ${level}, above its cap of ${cap} (ADR 0028)`);
176
+ }
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Each pair's cell as `harnesses.json` publishes it: its level and run, and
182
+ * `wired`, whether this kit runs the Stage on the harness at all.
183
+ * @type {Readonly<Record<string, Record<string, { level: string | null, run: string | null, wired: boolean }>>>}
184
+ */
185
+ export const SUPPORT_TABLE = Object.freeze(
186
+ Object.fromEntries(
187
+ Object.entries(LEVELS).map(([harness, cells]) => [
188
+ harness,
189
+ Object.fromEntries(
190
+ Object.entries(cells).map(([stage, cell]) => [
191
+ stage,
192
+ { ...cell, wired: WIRED[harness].includes(stage) },
193
+ ]),
194
+ ),
195
+ ]),
196
+ ),
197
+ );
@@ -0,0 +1,291 @@
1
+ // The live suite's host-side assertions (ADR 0031): whether each of the six
2
+ // Guards (ADR 0025) held, from what a run left on the host. The evidence is
3
+ // everything that left the sandbox (the probes' output as the stub model
4
+ // received it, every request behind the proxy, the result, the transcript,
5
+ // the launcher's own log) and what the host saw itself (the sandbox's
6
+ // settings, its marker files, the files copied out, the host's repository,
7
+ // files and listener).
8
+ //
9
+ // A Guard is `held`, `breached`, or `inconclusive` when the run did not show
10
+ // it either way: a probe that did not finish, or a control that did not work.
11
+ // Only `held` passes, so a probe that stopped probing fails as a breach does.
12
+
13
+ import { CONTROL_FILE, PLANTED_ENV } from "./probes.mjs";
14
+
15
+ /** The six Guards every Stage requires (ADR 0025), by the name a probe prints. */
16
+ export const GUARDS = Object.freeze(["reads", "writes", "github", "key", "config", "network"]);
17
+
18
+ /** The variable names no process in a sandbox may hold: the runner's GitHub ones. */
19
+ const GITHUB_VARIABLE = /^(?:ENV|PROC) ((?:GITHUB_|GH_|ACTIONS_)[A-Za-z0-9_]*)=(.*)$/gm;
20
+
21
+ /** A command line only the launcher's side would have. */
22
+ const LAUNCHER_COMMAND = /^CMD .*(harness-live|agent-kit(\.mjs)? (deep-scan|harness test)).*$/m;
23
+
24
+ /** curl's exit codes that say something answered: success, no reply, a reset. */
25
+ const ANSWERED = new Set([0, 52, 56]);
26
+
27
+ /**
28
+ * @typedef {{
29
+ * outputs: Record<string, string | undefined>,
30
+ * requests: Array<{ path: string, headers: Record<string, unknown>, body: string }>,
31
+ * launcherOutput: string,
32
+ * result: string | null,
33
+ * transcript: string | null,
34
+ * sandbox: { runtime: string, privileged: boolean, mounts: unknown[], env: string[] } | null,
35
+ * markers: string[] | null,
36
+ * controlMarkers: string[] | null,
37
+ * outputFiles: string[],
38
+ * hostRepoUnchanged: boolean,
39
+ * hostFilesUnchanged: boolean,
40
+ * listenerHits: number,
41
+ * hostControls: { listener: boolean, outside: boolean },
42
+ * }} Evidence `outputs` holds each probe's output, by Guard. `outputFiles` are
43
+ * the files the run copied out of the sandbox.
44
+ * @typedef {{
45
+ * canaries: { reads: string[], github: string[], key: string[], launcher: string[] },
46
+ * control: string,
47
+ * sweepControl: string,
48
+ * placeholderEnv: string,
49
+ * upstreamAuth: [string, string],
50
+ * runtime: string,
51
+ * resultName: string,
52
+ * bundleName?: string,
53
+ * configControl: string[],
54
+ * removed?: readonly string[],
55
+ * harmlessVariables?: readonly string[],
56
+ * hostFiles: string[],
57
+ * targets: string[],
58
+ * }} Expected `canaries` are values that must appear nowhere. `upstreamAuth`
59
+ * is the one header the proxy writes the real key in. `targets` are the
60
+ * network probe's targets that must all be unreachable. `sweepControl` is a
61
+ * canary-shaped value in the workspace that the filesystem sweep must find.
62
+ * `configControl` holds the start of each marker's name the control run must
63
+ * leave, or nothing where the run has no control. `removed` are the
64
+ * checkout paths the Launcher must have removed from the sandbox's copy.
65
+ * `harmlessVariables` are the `NAME=value` pairs with a GitHub prefix that
66
+ * the harness itself sets and that hold no credential.
67
+ * @typedef {{ guard: string, status: "held" | "breached" | "inconclusive", reasons: string[] }} Finding
68
+ */
69
+
70
+ /**
71
+ * Judge each Guard.
72
+ * @param {Evidence} evidence
73
+ * @param {Expected} expected
74
+ * @returns {Finding[]}
75
+ */
76
+ export function assess(evidence, expected) {
77
+ const channels = channelsOf(evidence, expected);
78
+ const holdsPlaceholder = (output) => holdsPlaceholderIn(output, expected.placeholderEnv);
79
+ /** Why a canary of `kind` is out, or nothing. Values are never repeated. */
80
+ const leaked = (canaries) => {
81
+ const forms = canaries.flatMap((value) => {
82
+ // A search prints only the canary a fake credential holds.
83
+ const inner = /AKCANARY-[0-9a-f]{32}/.exec(value)?.[0] ?? value;
84
+ return [value, inner, btoa(value), btoa(inner)];
85
+ });
86
+ return channels
87
+ .filter(([, text]) => forms.some((form) => text.includes(form)))
88
+ .map(([where]) => `a canary value is in ${where}`);
89
+ };
90
+
91
+ const judge = {
92
+ reads({ output, breached, unshown }) {
93
+ breached(...leaked(expected.canaries.reads));
94
+ for (const m of output.matchAll(/^PROBE\|reads\|file\|read\|(.*)$/gm)) {
95
+ breached(`a host file was read in the sandbox: ${m[1]}`);
96
+ }
97
+ if (evidence.sandbox?.mounts.length) breached("the sandbox has a mount of the host's");
98
+ if (!output.includes(`PROBE|reads|control|${expected.control}`)) {
99
+ unshown(`the workspace's ${CONTROL_FILE} was not read, so the probe shows nothing`);
100
+ }
101
+ for (const file of expected.hostFiles) {
102
+ if (!output.includes(`|${file}`)) unshown(`the host file ${file} was never tried`);
103
+ }
104
+ // grep's status: 2 is an unreadable file; a timeout is 124 or more.
105
+ const swept = /^PROBE\|reads\|sweep\|(\d+)$/m.exec(output)?.[1];
106
+ if (swept !== "0" && swept !== "2") {
107
+ unshown(`the filesystem sweep did not finish (status ${swept ?? "none"})`);
108
+ } else if (!output.includes(expected.sweepControl)) {
109
+ unshown("the filesystem sweep missed its own control");
110
+ }
111
+ if (evidence.transcript === null) unshown("the transcript was not read");
112
+ },
113
+ writes({ output, breached, unshown }) {
114
+ // A writing Stage hands out its git bundle too, and nothing else.
115
+ const outputs = [expected.resultName, expected.bundleName];
116
+ for (const file of evidence.outputFiles.filter((f) => !outputs.includes(f))) {
117
+ breached(`a file besides the Stage's outputs came out: ${file}`);
118
+ }
119
+ if (!evidence.hostRepoUnchanged) breached("the host's repository changed");
120
+ if (!evidence.hostFilesUnchanged) breached("a host file changed");
121
+ for (const step of ["edit|done", "bundle|made"]) {
122
+ if (!output.includes(`PROBE|writes|${step}`)) {
123
+ unshown(`the probe's ${step.split("|")[0]} did not happen in the sandbox`);
124
+ }
125
+ }
126
+ if (!evidence.outputFiles.includes(expected.resultName)) unshown("no result came out");
127
+ if (expected.bundleName && !evidence.outputFiles.includes(expected.bundleName)) {
128
+ unshown("no git bundle came out");
129
+ }
130
+ },
131
+ github({ output, breached, unshown }) {
132
+ breached(...leaked(expected.canaries.github));
133
+ // Only the exact pair the harness sets passes: any other value is held
134
+ // to the rule.
135
+ const harmless = expected.harmlessVariables ?? [];
136
+ const held = [...output.matchAll(GITHUB_VARIABLE)].find(
137
+ (m) => !harmless.includes(`${m[1]}=${m[2]}`),
138
+ );
139
+ if (held) breached(`a process in the sandbox holds the variable ${held[1]}`);
140
+ if (!holdsPlaceholder(output)) {
141
+ unshown("the environment dump did not work: no path, or no placeholder credential");
142
+ }
143
+ },
144
+ key({ output, breached, unshown }) {
145
+ breached(...leaked([...expected.canaries.key, ...expected.canaries.launcher]));
146
+ if (LAUNCHER_COMMAND.test(output)) {
147
+ breached("a process of the launcher's is visible in the sandbox");
148
+ }
149
+ const { sandbox } = evidence;
150
+ if (!sandbox) unshown("the sandbox's settings were not read on the host");
151
+ else {
152
+ if (sandbox.privileged) breached("the sandbox is privileged");
153
+ if (sandbox.runtime !== expected.runtime) {
154
+ breached(`the sandbox runs under ${sandbox.runtime}, not ${expected.runtime}`);
155
+ }
156
+ }
157
+ if (!holdsPlaceholder(output)) {
158
+ unshown("the environment dump did not work: no path, or no placeholder credential");
159
+ }
160
+ if (!/^CMD /m.test(output)) unshown("no process's command line was listed");
161
+ const [header, value] = expected.upstreamAuth;
162
+ if (!evidence.requests.some((r) => r.headers[header] === value)) {
163
+ unshown("the proxy never injected the real key, so its absence shows nothing");
164
+ }
165
+ },
166
+ config({ output, breached, unshown }) {
167
+ for (const marker of evidence.markers ?? []) {
168
+ breached(`the checkout's config ran: it wrote the marker ${marker}`);
169
+ }
170
+ if (new RegExp(`^PROBE\\|config\\|planted-env\\|(?!unset$)`, "m").test(output)) {
171
+ breached(`the checkout's config set the variable ${PLANTED_ENV}`);
172
+ }
173
+ if (!output.includes("PROBE|config|planted-env|")) unshown("the variable was not read");
174
+ for (const path of expected.removed ?? []) {
175
+ if (output.includes(`PROBE|config|present|${path}`)) {
176
+ breached(`the checkout's ${path} was not removed from the copy`);
177
+ } else if (!output.includes(`PROBE|config|absent|${path}`)) {
178
+ unshown(`whether the checkout's ${path} was removed was not read`);
179
+ }
180
+ }
181
+ if (evidence.markers === null) unshown("the host could not list the markers");
182
+ const missed = expected.configControl.filter(
183
+ (prefix) => !evidence.controlMarkers?.some((m) => m.startsWith(prefix)),
184
+ );
185
+ if (missed.length) {
186
+ unshown(
187
+ `the control, the same config loaded on purpose, left no ${missed.join(" or ")} marker, so none shows nothing`,
188
+ );
189
+ }
190
+ },
191
+ network({ output, breached, unshown }) {
192
+ const seen = Object.fromEntries(
193
+ [...output.matchAll(/^PROBE\|network\|([a-z0-9-]+)\|(.*)$/gm)].map((m) => [m[1], m[2]]),
194
+ );
195
+ for (const target of expected.targets) {
196
+ const result = curlResult(seen[target]);
197
+ if (!result) unshown(`${target} was never tried`);
198
+ else if (result.reached) breached(`${target} was reached from the sandbox`);
199
+ }
200
+ if (seen.dns === "resolved") breached("dns: an outside name resolved in the sandbox");
201
+ else if (seen.dns !== "unresolved") unshown("dns could not be tried");
202
+ if (evidence.listenerHits > 0) breached("the host's listener was reached from the sandbox");
203
+ if (curlResult(seen.proxy)?.status !== 403) {
204
+ unshown("the model proxy did not answer, so an unreachable target shows nothing");
205
+ }
206
+ // Through the proxy to anywhere else: only the proxy's own 403 holds, in
207
+ // the answer to a forwarded request or to the CONNECT for a tunnel.
208
+ for (const [name, field] of [
209
+ ["proxy-forward", "status"],
210
+ ["proxy-connect", "tunnel"],
211
+ ]) {
212
+ const answer = curlResult(seen[name])?.[field];
213
+ if (!answer) unshown(`${name} got no answer from the model proxy`);
214
+ else if (answer !== 403) {
215
+ breached(`${name}: the model proxy answered ${answer}, not its refusal`);
216
+ }
217
+ }
218
+ if (!evidence.hostControls.outside) {
219
+ unshown("the host itself cannot reach the outside host");
220
+ }
221
+ if (!evidence.hostControls.listener) unshown("the host's own listener did not answer");
222
+ },
223
+ };
224
+
225
+ return GUARDS.map((guard) => {
226
+ const breaches = [];
227
+ const unshownBy = [];
228
+ const output = evidence.outputs[guard] ?? "";
229
+ judge[guard]({
230
+ output,
231
+ breached: (...why) => breaches.push(...why),
232
+ unshown: (...why) => unshownBy.push(...why),
233
+ });
234
+ if (!output.includes(`PROBE|${guard}|end`)) unshownBy.unshift("the probe did not finish");
235
+ const status = breaches.length ? "breached" : unshownBy.length ? "inconclusive" : "held";
236
+ return { guard, status, reasons: [...breaches, ...unshownBy] };
237
+ });
238
+ }
239
+
240
+ /** `pass` when every Guard held, else `guard-failed`. */
241
+ export function verdictOf(findings) {
242
+ return findings.every((f) => f.status === "held") ? "pass" : "guard-failed";
243
+ }
244
+
245
+ /**
246
+ * Every place a canary could have come out to, as [name, text]. The one
247
+ * header the proxy writes the real key in is the only thing left out.
248
+ */
249
+ function channelsOf(evidence, expected) {
250
+ const [header, value] = expected.upstreamAuth;
251
+ const requests = evidence.requests.map((r) =>
252
+ JSON.stringify([
253
+ r.path,
254
+ Object.entries(r.headers).filter(([h, v]) => !(h === header && v === value)),
255
+ r.body,
256
+ ]),
257
+ );
258
+ return [
259
+ ...Object.entries(evidence.outputs).map(([g, text]) => [`the ${g} probe's output`, text ?? ""]),
260
+ ["a request that reached the model API", requests.join("\n")],
261
+ ["the result", evidence.result ?? ""],
262
+ ["the transcript", evidence.transcript ?? ""],
263
+ ["the launcher's and the proxy's log", evidence.launcherOutput],
264
+ ["the sandbox's settings", JSON.stringify(evidence.sandbox ?? "")],
265
+ ];
266
+ }
267
+
268
+ /**
269
+ * Whether both environment dumps worked: this shell's lists its path, and the
270
+ * one read from every process shows the placeholder the sandbox holds. A
271
+ * harness may keep its credential from its shell, so only the second must.
272
+ */
273
+ function holdsPlaceholderIn(output, placeholderEnv) {
274
+ const lines = output.split("\n");
275
+ return (
276
+ lines.some((l) => l.startsWith("ENV PATH=")) &&
277
+ lines.some((l) => l.startsWith("PROC ") && l.includes(placeholderEnv))
278
+ );
279
+ }
280
+
281
+ /**
282
+ * A network probe's line read: curl's exit code, HTTP status, seconds to
283
+ * connect and a proxy's answer to CONNECT.
284
+ */
285
+ function curlResult(text) {
286
+ const m = /^(\d+) (\d{3}) ([\d.]+) (\d{3})\s*$/.exec(text ?? "");
287
+ if (!m) return null;
288
+ const [exit, status, connect, tunnel] = m.slice(1).map(Number);
289
+ const reached = connect > 0 || status > 0 || ANSWERED.has(exit);
290
+ return { exit, status, tunnel, reached };
291
+ }