@ouro.bot/cli 0.1.0-alpha.1441 → 0.1.0-alpha.1443

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.
package/changelog.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1443",
6
+ "changes": [
7
+ "The blind interviews have a runner and a grader. The runner reads the pre-registered allocation, runs each session's three jobs with their debriefs, then asks which interface the model would choose and which product it thinks each one is, and writes a private report and a counts-only summary. The grader checks the request logs for leaked brand words and the guesses for broken blinding, and reports ouro's first-choice count against the pre-registered bars."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1442",
12
+ "changes": [
13
+ "An eval run's sandbox no longer shares names with the Butler's tooling, and it stays off the Butler's host.",
14
+ "Its containers, network and folder are named `eval-sandbox-<run>`, no longer `ouro-eval-<run>`.",
15
+ "Every container it starts carries the labels `ouro.eval=1` and `ouro.eval.run=<run>`, and so does its network. That includes the fixture, TLS and hand-back helpers. The books oracle's container carries `ouro.eval=1`. CI's clean-up step now removes containers and networks by that label.",
16
+ "A host that has any of the live Butler's containers (`ouro-butler`, `ouro-butler-staging` or `ouro-butler-rollback`) is refused before anything is created, unless the caller holds a host lock that the Butler's upgrade and rollback honour. Nothing provides that lock yet, so for now eval runs stay off the Butler's host.",
17
+ "Background: on 2026-11-23 a vanishing eval container broke the Butler's upgrade and its rollback (#1760).",
18
+ "butler:ship's check for running eval containers (#1764) now finds them by the `ouro.eval=1` label as well as by the old `ouro-eval-` names, so the rename does not hide them from it."
19
+ ]
20
+ },
4
21
  {
5
22
  "version": "0.1.0-alpha.1441",
6
23
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1441",
2
+ "runtimeVersion": "0.1.0-alpha.1443",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1441</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1443</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * `npm run interviews -- <flags>` (see `interviews/runner.ts` for the flags and refusals): runs blind-interview sessions
8
+ * from the pre-registration's Appendix B on one model target, writes the private report and the private request log
9
+ * (both opened `wx`, mode 0600, under a 0700 folder) and prints a counts-only summary. With `--sandbox-ssh
10
+ * <host>:<folder>` the sandbox runs on that Docker host, whose harness checkout is synced to `<folder>/harness`;
11
+ * `--bundle` and `--seed-bundle` are then paths on that host. Model calls and credentials stay on this machine.
12
+ */
13
+ const node_fs_1 = __importDefault(require("node:fs"));
14
+ const node_os_1 = __importDefault(require("node:os"));
15
+ const node_path_1 = __importDefault(require("node:path"));
16
+ const runtime_1 = require("../nerves/runtime");
17
+ const self_test_1 = require("./self-test");
18
+ const report_1 = require("./report");
19
+ const docker_1 = require("./sandbox/docker");
20
+ const remote_1 = require("./sandbox/remote");
21
+ const targets_1 = require("./targets");
22
+ const runner_1 = require("./interviews/runner");
23
+ const REPO = node_path_1.default.resolve(__dirname, "../..");
24
+ function take(argv, flag) {
25
+ const at = argv.indexOf(flag);
26
+ if (at < 0)
27
+ return { value: undefined, rest: argv };
28
+ return { value: argv[at + 1], rest: [...argv.slice(0, at), ...argv.slice(at + 2)] };
29
+ }
30
+ function runCaseFor(sandboxSsh, bundle, seedBundle, images) {
31
+ if (sandboxSsh) {
32
+ const split = sandboxSsh.indexOf(":");
33
+ if (split < 1)
34
+ throw new Error("--sandbox-ssh must be <host>:<folder>");
35
+ const host = sandboxSsh.slice(0, split);
36
+ const root = sandboxSsh.slice(split + 1);
37
+ return (0, remote_1.remoteRunCase)({
38
+ start: (0, remote_1.sshStart)(host, `${root}/harness/dist/eval/remote-entry.js`),
39
+ paths: { bundleDir: bundle, seedBundleDir: seedBundle ?? `${root}/harness/deploy/unraid/sanctuary.ouro`, workRoot: `${root}/work`, ...(images ? { images } : {}) },
40
+ });
41
+ }
42
+ const docker = (0, docker_1.dockerCli)();
43
+ return ({ case: c, host, budget, guest }) => (0, docker_1.runSandboxed)({
44
+ case: c, bundleDir: bundle, seedBundleDir: seedBundle ?? node_path_1.default.join(REPO, "deploy/unraid/sanctuary.ouro"), host, budget, docker, ...(guest ? { guest } : {}), ...(images ? { images } : {}),
45
+ });
46
+ }
47
+ function openPrivateLog(file) {
48
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(file), { recursive: true, mode: 0o700 });
49
+ node_fs_1.default.chmodSync(node_path_1.default.dirname(file), 0o700);
50
+ const fd = node_fs_1.default.openSync(file, "wx", 0o600);
51
+ return (line) => { node_fs_1.default.writeSync(fd, `${line}\n`); };
52
+ }
53
+ /** Every session ever started on this machine, one id per line, appended before the session reserves its budget. */
54
+ const STARTED = node_path_1.default.join(node_os_1.default.homedir(), ".ouro-eval", "reports", "interview-sessions-started.txt");
55
+ function startedSessions() {
56
+ const ids = () => node_fs_1.default.existsSync(STARTED) ? node_fs_1.default.readFileSync(STARTED, "utf8").split("\n") : [];
57
+ return {
58
+ has: (id) => ids().includes(id),
59
+ add: (id) => {
60
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(STARTED), { recursive: true, mode: 0o700 });
61
+ const fd = node_fs_1.default.openSync(STARTED, "a", 0o600);
62
+ node_fs_1.default.writeSync(fd, `${id}\n`);
63
+ node_fs_1.default.fsyncSync(fd);
64
+ node_fs_1.default.closeSync(fd);
65
+ },
66
+ };
67
+ }
68
+ async function main() {
69
+ const ssh = take(process.argv.slice(2), "--sandbox-ssh");
70
+ const bundle = take(ssh.rest, "--bundle");
71
+ const seed = take(bundle.rest, "--seed-bundle");
72
+ // `--images <agent>,<household>`: image tags of this run's own, so a run never uses images another checkout built.
73
+ const tags = take(seed.rest, "--images");
74
+ if (!bundle.value)
75
+ throw new Error("--bundle is required");
76
+ const [agent, household] = tags.value?.split(",") ?? [];
77
+ if (tags.value && !(agent && household))
78
+ throw new Error("--images must be <agent image>,<household image>");
79
+ const images = agent && household ? { agent, household } : undefined;
80
+ const args = (0, runner_1.parseInterviewArgs)(tags.rest);
81
+ const { exitCode } = await (0, runner_1.runInterviews)(args, {
82
+ readText: (file) => node_fs_1.default.readFileSync(file, "utf8"),
83
+ loadCases: self_test_1.loadCases,
84
+ resolveTarget: (spec, creds) => (0, targets_1.resolveTarget)(spec, creds),
85
+ runCase: runCaseFor(ssh.value, bundle.value, seed.value, images),
86
+ kits: { X: runner_1.X_KIT },
87
+ outputExists: (file) => node_fs_1.default.existsSync(file),
88
+ writeReport: report_1.writePrivateReport,
89
+ openLog: openPrivateLog,
90
+ started: startedSessions(),
91
+ print: (text) => { process.stdout.write(`${text}\n`); },
92
+ });
93
+ return exitCode;
94
+ }
95
+ const STOPPED = "budget-stopped";
96
+ const FAILED = "eval-error";
97
+ main().then((code) => {
98
+ if (code === 2)
99
+ process.stderr.write(`code: ${STOPPED}\n`);
100
+ process.exitCode = code;
101
+ }).catch((error) => {
102
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "error", event: "eval.interview_entry_error", message: "the interviews command failed", meta: { error: error instanceof Error ? error.message : String(error) } });
103
+ process.stderr.write(`interviews: ${error instanceof Error ? error.message : String(error)}\n`);
104
+ process.stderr.write(`code: ${FAILED}\n`);
105
+ process.exitCode = 1;
106
+ });
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /**
7
+ * `node dist/eval/interview-grade-entry.js --preregistration <file> --report <file> --request-log <file> [--reduced]`
8
+ * (`--report` and `--request-log` repeat, one pair per run): grades the blind interviews from the runner's private
9
+ * reports and request logs (see `interviews/grader.ts`) and prints the counts-only result. It calls no model.
10
+ */
11
+ const node_fs_1 = __importDefault(require("node:fs"));
12
+ const runtime_1 = require("../nerves/runtime");
13
+ const allocation_1 = require("./interviews/allocation");
14
+ const grader_1 = require("./interviews/grader");
15
+ function main() {
16
+ const argv = process.argv.slice(2);
17
+ const values = (flag) => argv.flatMap((word, i) => (word === flag && argv[i + 1] ? [argv[i + 1]] : []));
18
+ const [preregistration] = values("--preregistration");
19
+ if (!preregistration)
20
+ throw new Error("--preregistration is required");
21
+ const reduced = argv.includes("--reduced");
22
+ const all = (0, allocation_1.readAllocation)(node_fs_1.default.readFileSync(preregistration, "utf8"));
23
+ const records = values("--report").flatMap((file) => JSON.parse(node_fs_1.default.readFileSync(file, "utf8")).sessions);
24
+ const requests = values("--request-log").flatMap((file) => (0, grader_1.readRequestLog)(node_fs_1.default.readFileSync(file, "utf8")));
25
+ const grade = (0, grader_1.gradeStudy)({ design: reduced ? (0, allocation_1.reducedDesign)(all) : all, records, requests, reduced });
26
+ process.stdout.write(`${(0, grader_1.formatGrade)(grade, reduced)}\n`);
27
+ }
28
+ try {
29
+ main();
30
+ }
31
+ catch (error) {
32
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "error", event: "eval.interview_grade_error", message: "the interview grader failed", meta: { error: String(error) } });
33
+ process.stderr.write(`grade: ${error instanceof Error ? error.message : String(error)}\n`);
34
+ process.exitCode = 1;
35
+ }
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.closingTools = closingTools;
4
+ exports.finalTools = finalTools;
5
+ exports.readChoice = readChoice;
6
+ exports.readGuesses = readGuesses;
7
+ exports.runFinalConversation = runFinalConversation;
8
+ const runtime_1 = require("../../nerves/runtime");
9
+ const mcp_tools_1 = require("../../repertoire/mcp-tools");
10
+ const loop_1 = require("./guest/loop");
11
+ const protocol_1 = require("./protocol");
12
+ /** The code of a choose or identify call that recorded nothing. The model's answer is "Not recorded." only, as the
13
+ * pre-registration's closing step has it; the code goes to the nerves event. */
14
+ const NOT_RECORDED = "not-recorded";
15
+ /**
16
+ * The two closing tools as the pre-registration words them, `first` and `second` taking only the session's labels.
17
+ * Like the arms' tools they are the study's own, offered only to the study's model and never registered as the
18
+ * harness's tools, so they go out the way a connected server's tools do: through `mcpToolSchema`, the census's
19
+ * passthrough (ax/census.config.json). Each keeps its name and description.
20
+ */
21
+ function closingTools(labels) {
22
+ return [
23
+ {
24
+ name: "choose",
25
+ description: "Your first and second choice of the three, and one sentence on what decided it.",
26
+ inputSchema: {
27
+ type: "object",
28
+ properties: { first: { type: "string", enum: [...labels] }, second: { type: "string", enum: [...labels] }, reason: { type: "string" } },
29
+ required: ["first", "second", "reason"],
30
+ },
31
+ },
32
+ {
33
+ name: "identify",
34
+ description: "For each label, the product you think it is, or \"no idea\".",
35
+ inputSchema: {
36
+ type: "object",
37
+ properties: { guesses: { type: "object", properties: Object.fromEntries(labels.map((label) => [label, { type: "string" }])), additionalProperties: { type: "string" } } },
38
+ required: ["guesses"],
39
+ },
40
+ },
41
+ ];
42
+ }
43
+ function finalTools(labels) {
44
+ return closingTools(labels).map((tool) => (0, mcp_tools_1.mcpToolSchema)({ server: tool.name }, tool));
45
+ }
46
+ const parse = (text) => {
47
+ try {
48
+ const value = JSON.parse(text || "{}");
49
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ };
55
+ function readChoice(args, labels) {
56
+ const value = parse(args);
57
+ if (!value || typeof value.first !== "string" || !labels.includes(value.first))
58
+ return null;
59
+ const second = typeof value.second === "string" && labels.includes(value.second) ? value.second : null;
60
+ return { first: value.first, second, reason: typeof value.reason === "string" ? value.reason : "" };
61
+ }
62
+ function readGuesses(args) {
63
+ const guesses = parse(args)?.guesses;
64
+ if (!guesses || typeof guesses !== "object" || Array.isArray(guesses))
65
+ return null;
66
+ return Object.fromEntries(Object.entries(guesses).map(([label, guess]) => [label, typeof guess === "string" ? guess : JSON.stringify(guess)]));
67
+ }
68
+ /** Runs Q3 (with its one nudge) then Q4. `allowNudge` lets the choice's gate take the nudge's call. */
69
+ async function runFinalConversation(input) {
70
+ const labels = input.notes.map((note) => note.label);
71
+ const tools = finalTools(labels);
72
+ const messages = [{ role: "system", content: protocol_1.FINAL_SYSTEM_PROMPT }, { role: "user", content: (0, protocol_1.choiceQuestion)(input.product, input.notes) }];
73
+ const result = { choice: null, nudged: false, guesses: null, ended: null, replies: [] };
74
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_final_start", message: "asking an interview session's choice", meta: { labels: labels.join("") } });
75
+ const call = async () => {
76
+ input.runtime.resetTurnState(messages);
77
+ try {
78
+ const turn = await input.runtime.streamTurn({ messages, activeTools: tools, callbacks: loop_1.NO_CALLBACKS });
79
+ const content = (0, loop_1.withoutThinking)(turn.content);
80
+ result.replies.push(content);
81
+ messages.push({ role: "assistant", ...(content ? { content } : {}), ...(turn.toolCalls.length ? { tool_calls: turn.toolCalls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) } : {}) });
82
+ return turn;
83
+ }
84
+ catch (error) {
85
+ result.ended = (0, loop_1.messageOf)(error);
86
+ return null;
87
+ }
88
+ };
89
+ const answerCalls = (turn, accepted) => {
90
+ for (const toolCall of turn.toolCalls) {
91
+ const ok = accepted(toolCall.name, toolCall.arguments);
92
+ const content = ok ? "Recorded." : "Not recorded.";
93
+ if (!ok)
94
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.interview_final_not_recorded", message: "a closing tool call recorded nothing", meta: { code: NOT_RECORDED, tool: toolCall.name } });
95
+ messages.push({ role: "tool", tool_call_id: toolCall.id, content });
96
+ input.runtime.appendToolOutput(toolCall.id, content);
97
+ }
98
+ };
99
+ const takeChoice = (name, args) => {
100
+ if (name !== "choose" || result.choice)
101
+ return false;
102
+ result.choice = readChoice(args, labels);
103
+ return result.choice !== null;
104
+ };
105
+ let turn = await call();
106
+ if (!turn)
107
+ return result;
108
+ answerCalls(turn, takeChoice);
109
+ if (!result.choice) {
110
+ result.nudged = true;
111
+ input.allowNudge();
112
+ messages.push({ role: "user", content: protocol_1.CHOOSE_NUDGE });
113
+ turn = await call();
114
+ if (!turn)
115
+ return result;
116
+ answerCalls(turn, takeChoice);
117
+ }
118
+ if (!result.choice) {
119
+ (0, runtime_1.emitNervesEvent)({ component: "eval", level: "warn", event: "eval.interview_no_choice", message: "the session's model never called choose", meta: {} });
120
+ }
121
+ messages.push({ role: "user", content: protocol_1.IDENTIFY_QUESTION });
122
+ turn = await call();
123
+ if (!turn)
124
+ return result;
125
+ answerCalls(turn, (name, args) => {
126
+ if (name !== "identify" || result.guesses)
127
+ return false;
128
+ result.guesses = readGuesses(args);
129
+ return result.guesses !== null;
130
+ });
131
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_final_end", message: "finished an interview session's choice", meta: { chosen: result.choice !== null, nudged: result.nudged } });
132
+ return result;
133
+ }
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ALTERNATIVE_NAMES = void 0;
4
+ exports.bars = bars;
5
+ exports.guessFor = guessFor;
6
+ exports.isBroken = isBroken;
7
+ exports.gradeStudy = gradeStudy;
8
+ exports.formatGrade = formatGrade;
9
+ exports.readRequestLog = readRequestLog;
10
+ /**
11
+ * The grader (pre-registration section 7, item 9): section 3's blinding checks and section 6's analysis, from the
12
+ * runner's private reports and request logs and Appendix B. It runs no model and sends nothing. Its result is counts
13
+ * and labels only (no trace text, notes or reasons), so it can be committed as the study's result.
14
+ *
15
+ * Section 3: no leak (the brand pattern over every logged request body, zero matches outside void sessions); no
16
+ * identification (a session is broken when Q4 names the `ouro` label with a product matching /ouro/i); a valid count
17
+ * (at most 3 of 18 broken, or 1 of 9 in the reduced design). Section 6: k of n sessions with `ouro` first, where every
18
+ * session of the design counts and one that is void, crashed, missing or not run counts as `ouro` not first; the three
19
+ * pass conditions; and the figures reported beside them, never used to pass or fail.
20
+ */
21
+ const runtime_1 = require("../../nerves/runtime");
22
+ const stats_1 = require("../domain/stats");
23
+ const protocol_1 = require("./protocol");
24
+ /** What a correct guess for each alternative looks like (counted and reported; it never breaks a session). */
25
+ exports.ALTERNATIVE_NAMES = {
26
+ "codex": /codex/i,
27
+ "openhands": /open ?hands|all-hands/i,
28
+ "shadcn": /shadcn|radix/i,
29
+ "mui": /\bmui\b|material[ -]?ui/i,
30
+ "mcp-plain": /\bmcp\b|model context protocol/i,
31
+ "cli-shell": /\bcli\b|shell|command[- ]line|bash|terminal/i,
32
+ };
33
+ /** Section 6's bars: k of n for "more often than chance", and the most broken sessions a valid count allows. */
34
+ function bars(reduced) {
35
+ return reduced ? { n: 9, k: 7, broken: 1 } : { n: 18, k: 11, broken: 3 };
36
+ }
37
+ const brand = () => new RegExp(protocol_1.BRAND_PATTERN, "gi");
38
+ /** Q4's guess for `label`, whether the model keyed it `K`, ` k ` or `tool interface K`. */
39
+ function guessFor(guesses, label) {
40
+ const want = label.toLowerCase();
41
+ const key = Object.keys(guesses ?? {}).find((k) => {
42
+ const words = k.trim().toLowerCase().split(/\s+/);
43
+ return words[words.length - 1] === want;
44
+ });
45
+ return key === undefined ? undefined : guesses[key];
46
+ }
47
+ /** A session's blinding is broken when Q4 names the `ouro` arm's label with a product matching /ouro/i. */
48
+ function isBroken(record) {
49
+ const ouroLabel = Object.entries(record.labels).find(([, arm]) => arm === "ouro")?.[0];
50
+ const guess = ouroLabel ? guessFor(record.final?.guesses, ouroLabel) : undefined;
51
+ return typeof guess === "string" && /ouro/i.test(guess);
52
+ }
53
+ function gradeStudy(input) {
54
+ const byId = new Map();
55
+ for (const record of input.records) {
56
+ if (byId.has(record.id))
57
+ throw new Error(`session ${record.id} is in the reports twice; every session runs once`);
58
+ byId.set(record.id, record);
59
+ }
60
+ for (const session of input.design) {
61
+ const record = byId.get(session.id);
62
+ const labels = JSON.stringify(Object.fromEntries(session.arms.map((arm) => [arm.label, arm.arm])));
63
+ if (record && JSON.stringify(record.labels) !== labels)
64
+ throw new Error(`session ${session.id}'s report gives labels other than Appendix B's`);
65
+ }
66
+ const voids = new Set(input.records.filter((record) => record.status === "void").map((record) => record.id));
67
+ const leaking = input.requests.filter((request) => request.sent && (request.body.match(brand()) ?? []).length > 0);
68
+ const leak = {
69
+ requests: input.requests.length,
70
+ matches: input.requests.reduce((sum, request) => sum + (request.body.match(brand()) ?? []).length, 0),
71
+ outsideVoid: leaking.filter((request) => !voids.has(request.session)).length,
72
+ sessions: [...new Set(leaking.map((request) => request.session))],
73
+ };
74
+ const bar = bars(input.reduced);
75
+ const products = ["H", "U", "X"].flatMap((product) => {
76
+ const sessions = input.design.filter((session) => session.product === product && !session.pilot);
77
+ if (sessions.length === 0)
78
+ return [];
79
+ const ran = sessions.map((session) => ({ session, record: byId.get(session.id) }));
80
+ const first = (record) => record?.status === "complete" ? record.final?.choice?.first ?? null : null;
81
+ const armOf = (session, label) => session.arms.find((arm) => arm.label === label)?.arm ?? null;
82
+ // Recomputed from the choice and Appendix B's labels, not taken from the runner's own flag.
83
+ const firstIsOuro = ({ session, record }) => armOf(session, first(record)) === "ouro";
84
+ const leaked = sessions.some((session) => leaking.some((request) => request.session === session.id && !voids.has(session.id)));
85
+ const k = ran.filter(firstIsOuro).length;
86
+ const broken = ran.filter(({ record }) => record !== undefined && isBroken(record)).map(({ session }) => session.id);
87
+ const byModel = {};
88
+ for (const { session, record } of ran) {
89
+ const entry = byModel[session.model] ??= { sessions: 0, firsts: Object.fromEntries(protocol_1.ARMS[product].map((arm) => [arm, 0])), ouroAhead: false };
90
+ entry.sessions += 1;
91
+ const arm = armOf(session, first(record));
92
+ if (arm)
93
+ entry.firsts[arm] += 1;
94
+ }
95
+ for (const entry of Object.values(byModel))
96
+ entry.ouroAhead = protocol_1.ARMS[product].slice(1).every((alt) => entry.firsts.ouro > entry.firsts[alt]);
97
+ const arms = Object.fromEntries(protocol_1.ARMS[product].map((arm) => [arm, { firsts: 0, seconds: 0, meanRating: null, ratings: 0, missingRatings: 0, jobsRun: 0, jobsPassed: 0, identified: 0 }]));
98
+ const ratingSums = {};
99
+ let firstPassed = 0;
100
+ let firstOf = 0;
101
+ for (const { session, record } of ran) {
102
+ if (!record)
103
+ continue;
104
+ const firstArm = armOf(session, first(record));
105
+ const secondArm = armOf(session, record.status === "complete" ? record.final?.choice?.second ?? null : null);
106
+ if (firstArm)
107
+ arms[firstArm].firsts += 1;
108
+ if (secondArm)
109
+ arms[secondArm].seconds += 1;
110
+ for (const run of record.arms) {
111
+ const figures = arms[run.arm];
112
+ figures.jobsRun += 1;
113
+ if (run.passed)
114
+ figures.jobsPassed += 1;
115
+ if (run.rating === null)
116
+ figures.missingRatings += 1;
117
+ else {
118
+ figures.ratings += 1;
119
+ ratingSums[run.arm] = (ratingSums[run.arm] ?? 0) + run.rating;
120
+ }
121
+ }
122
+ for (const { label, arm } of session.arms) {
123
+ const guess = guessFor(record.final?.guesses, label);
124
+ if (arm !== "ouro" && typeof guess === "string" && exports.ALTERNATIVE_NAMES[arm].test(guess))
125
+ arms[arm].identified += 1;
126
+ }
127
+ if (firstArm) {
128
+ firstOf += 1;
129
+ if (record.arms.find((run) => run.arm === firstArm)?.passed)
130
+ firstPassed += 1;
131
+ }
132
+ }
133
+ for (const [arm, figures] of Object.entries(arms))
134
+ figures.meanRating = figures.ratings > 0 ? ratingSums[arm] / figures.ratings : null;
135
+ const n = sessions.length;
136
+ const interval = (0, stats_1.wilsonInterval)(k, n);
137
+ const conditions = {
138
+ moreThanChance: k >= bar.k,
139
+ everyModelAgrees: Object.values(byModel).every((entry) => entry.ouroAhead),
140
+ // A brand word sent outside a void session fails the blinding outright (section 3, no leak).
141
+ blindingHeld: broken.length <= bar.broken && !leaked,
142
+ };
143
+ const passed = conditions.moreThanChance && conditions.everyModelAgrees && conditions.blindingHeld;
144
+ const kept = ran.filter(({ session }) => !broken.includes(session.id));
145
+ const statuses = {};
146
+ for (const { record } of ran)
147
+ statuses[record?.status ?? "missing"] = (statuses[record?.status ?? "missing"] ?? 0) + 1;
148
+ return [{
149
+ // n is at least 1 here, so the interval has both bounds.
150
+ product, n, k, share: { value: k / n, low: interval.low, high: interval.high }, byModel, broken, conditions, passed,
151
+ verdict: !conditions.blindingHeld ? "blinding failed" : passed ? "passed" : "failed",
152
+ withoutBroken: { n: kept.length, k: kept.filter(firstIsOuro).length },
153
+ arms, firstChoiceJobPassed: { sessions: firstPassed, of: firstOf }, statuses,
154
+ }];
155
+ });
156
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_graded", message: "graded the blind interviews", meta: { products: products.length, leaks: leak.outsideVoid } });
157
+ return { leak, products };
158
+ }
159
+ const percent = (value) => `${(value * 100).toFixed(1)}%`;
160
+ /** The grade as text: counts, labels and arm names only. */
161
+ function formatGrade(grade, reduced) {
162
+ const bar = bars(reduced);
163
+ const lines = [
164
+ `Leak check: ${grade.leak.requests} logged requests, ${grade.leak.outsideVoid} sent with brand words outside void sessions (${grade.leak.matches} matches in all, sent or not).`,
165
+ ];
166
+ for (const p of grade.products) {
167
+ lines.push("", `${p.product}: ${p.verdict}. ouro first in ${p.k} of ${p.n} (bar ${bar.k} of ${bar.n}); share ${percent(p.share.value)}, Wilson 95% ${percent(p.share.low)} to ${percent(p.share.high)}.`, ` more often than chance: ${p.conditions.moreThanChance ? "yes" : "no"}; every model agrees: ${p.conditions.everyModelAgrees ? "yes" : "no"}; blinding held: ${p.conditions.blindingHeld ? "yes" : "no"} (${p.broken.length} broken, at most ${bar.broken}${p.broken.length ? `: ${p.broken.join(", ")}` : ""}).`, ` without broken sessions: ouro first in ${p.withoutBroken.k} of ${p.withoutBroken.n}.`, ` sessions: ${Object.entries(p.statuses).map(([status, count]) => `${count} ${status}`).join(", ")}.`, ...Object.entries(p.byModel).map(([model, entry]) => ` ${model}: ${entry.sessions} sessions; first choices ${Object.entries(entry.firsts).map(([arm, count]) => `${arm} ${count}`).join(", ")}.`), ...Object.entries(p.arms).map(([arm, f]) => ` ${arm}: first ${f.firsts}, second ${f.seconds}; mean rating ${f.meanRating === null ? "n/a" : f.meanRating.toFixed(2)} (${f.missingRatings} missing); jobs passed ${f.jobsPassed} of ${f.jobsRun}${arm === "ouro" ? "" : `; identified ${f.identified}`}.`), ` first choice was an arm whose job passed: ${p.firstChoiceJobPassed.sessions} of ${p.firstChoiceJobPassed.of}.`);
168
+ }
169
+ return lines.join("\n");
170
+ }
171
+ /** The request log's lines, refusing a line that is not one logged request. */
172
+ function readRequestLog(text) {
173
+ return text.split("\n").filter((line) => line.trim()).map((line, i) => {
174
+ const value = JSON.parse(line);
175
+ if (typeof value.session !== "string" || typeof value.kind !== "string" || typeof value.sent !== "boolean" || typeof value.body !== "string")
176
+ throw new Error(`request log line ${i + 1} is not a logged request`);
177
+ return value;
178
+ });
179
+ }
@@ -0,0 +1,292 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KNOWN_ARMS = exports.X_KIT = exports.NO_BOOKS = exports.NO_OPERATION = exports.FIDELITY = void 0;
4
+ exports.canonicalX = canonicalX;
5
+ exports.summarizeSessions = summarizeSessions;
6
+ exports.runInterviews = runInterviews;
7
+ exports.parseInterviewArgs = parseInterviewArgs;
8
+ const runtime_1 = require("../../nerves/runtime");
9
+ const assertions_1 = require("../assertions");
10
+ const budget_1 = require("../budget");
11
+ const report_1 = require("../report");
12
+ const allocation_1 = require("./allocation");
13
+ const final_1 = require("./final");
14
+ const arms_1 = require("./guest/arms");
15
+ const loop_1 = require("./guest/loop");
16
+ const operations_1 = require("./guest/operations");
17
+ const latch_1 = require("./latch");
18
+ const protocol_1 = require("./protocol");
19
+ /** What is recorded about each arm before any session: where it differs from the product it stands for. */
20
+ exports.FIDELITY = {
21
+ "X:ouro": [
22
+ "ax-command and its MCP handler are Ouro AX v1.3.445's files unchanged; only their `.ts` import suffixes are dropped so the harness compiles them",
23
+ "the tools are called in-process through the handler's tools/call, not over an MCP transport",
24
+ "ax-command types positional arguments as strings, so this arm asks for a book's id as a string (\"187\") where mcp-plain asks for an integer; its tool descriptions carry the kit's own effect sentence",
25
+ "only the kit's MCP-tool side reaches the model: its parser, `help --json`, `--json` output and exit codes are the same code behind each tool, but the model never sees the command line itself",
26
+ "the kit cuts a tool answer at its own 20,000-character limit; no answer in the books cases comes near it",
27
+ ],
28
+ "X:mcp-plain": ["hand-written for this study: the same operations, inputs and JSON results as the other arms, no kit"],
29
+ "X:cli-shell": [
30
+ "the shell runs one `books` command per call, with quoting but no other programs, pipes, redirection or chaining",
31
+ "its human-readable output is generated from the same JSON answer the other arms return",
32
+ ],
33
+ "X:all": [
34
+ "every arm runs the eval's books stub in the bundle, against the fake household; paths in answers are shown relative to the books folder",
35
+ "the persona is the Butler's psyche files from the seed bundle with the household's names filled in; the bundle's skills are left out, since they describe the shell command line",
36
+ "the debrief keeps the arm's tools; the job is scored on the household after the debrief, and debrief tool calls are counted",
37
+ "for scoring, each arm's calls are written as the books command line they ran, so the case's trace assertions read every arm the same way; a call the interface refused before any books operation ran (a bad argument, an unknown tool, a help request) is written as `no-operation` in every arm",
38
+ "the loop starts a failed call's answer with `Error: ` in every arm, in place of MCP's isError flag",
39
+ "on the Copilot Responses path the provider's body is rebuilt from the scanned messages before every call, so reasoning items from an earlier call are not sent back",
40
+ ],
41
+ };
42
+ /** What a call the interface refused, before any books operation ran, is written as for scoring, in every arm. */
43
+ exports.NO_OPERATION = "no-operation";
44
+ /** The books core for reading calls back on the host, where no operation ever runs. */
45
+ const NO_BOOKS = async () => { throw new Error("the host only reads calls back; it runs no books operation"); };
46
+ exports.NO_BOOKS = NO_BOOKS;
47
+ /** X's calls as the books command lines they ran, so `trace.*` assertions read every arm the same way. */
48
+ function canonicalX(arm, obs) {
49
+ const tools = (0, arms_1.buildArm)(arm, exports.NO_BOOKS);
50
+ return {
51
+ ...obs,
52
+ timeline: obs.timeline.map((entry) => {
53
+ if (entry.kind !== "call")
54
+ return entry;
55
+ const ran = tools.operationOf(entry.name, entry.args);
56
+ return ran ? { ...entry, name: "shell", args: JSON.stringify({ command: (0, operations_1.commandLine)((0, operations_1.argvOf)(ran.op, ran.input)) }) } : { ...entry, name: exports.NO_OPERATION };
57
+ }),
58
+ };
59
+ }
60
+ exports.X_KIT = {
61
+ guest: ({ session, arm, case: c, debrief }) => {
62
+ const last = c.prefix[c.prefix.length - 1];
63
+ return {
64
+ entry: "interview-guest-entry.js",
65
+ turn: { product: session.product, arm: arm.arm, labelLine: (0, protocol_1.labelLine)(session.product, arm.label), prefix: c.prefix.slice(0, -1), userText: last.content, followUps: [debrief] },
66
+ };
67
+ },
68
+ canonical: canonicalX,
69
+ };
70
+ const ZERO = { premium: 0, credits: 0 };
71
+ /** The brand words found, each once, in lower case. */
72
+ const named = (hits) => [...new Set(hits.map((hit) => hit.toLowerCase()))].join(", ");
73
+ const providerFailure = (outcome) => /^(provider-error|sandbox-error|trace-mismatch)/.test(outcome);
74
+ function armRecord(input) {
75
+ const { gaps: _gaps, followUps, ...raw } = input.obs;
76
+ const observation = input.kit.canonical(input.arm.arm, raw);
77
+ const graded = (0, assertions_1.evaluate)(input.c, observation);
78
+ const refused = input.job.refused();
79
+ const verdict = refused ? { passed: false, reason: `refused: ${refused}` } : (0, report_1.gradeRun)(observation, graded);
80
+ const debrief = followUps?.[0];
81
+ const note = debrief && debrief.outcome === "settled" ? debrief.finalReply : "";
82
+ return {
83
+ label: input.arm.label, arm: input.arm.arm, ...verdict, outcome: raw.outcome, checks: graded.checks, note, rating: (0, protocol_1.ratingOf)(note),
84
+ debriefOutcome: debrief?.outcome ?? null, debriefToolCalls: debrief?.toolCalls ?? 0,
85
+ jobCalls: input.job.calls(), debriefCalls: input.debrief.calls(), observation,
86
+ };
87
+ }
88
+ /** Runs one session. Returns its record; `stop` when the study must stop (402, 429 or a cap). */
89
+ async function runSession(input) {
90
+ const { session, latch } = input;
91
+ const record = {
92
+ id: session.id, product: session.product, model: session.model, job: session.job, pilot: session.pilot,
93
+ labels: Object.fromEntries(session.arms.map((arm) => [arm.label, arm.arm])), status: "complete", ended: null, arms: [], final: null,
94
+ ouroFirst: false, voidedBy: null, calls: [], spent: ZERO,
95
+ };
96
+ const c = input.cases.get(session.job);
97
+ const guard = (gateFor) => (0, latch_1.guardedRuntime)({
98
+ inner: input.target.runtime, latch, ledger: input.ledger, pricing: input.pricing, gateFor,
99
+ log: (entry) => input.log(JSON.stringify({ session: session.id, ...entry })),
100
+ });
101
+ const end = (status, why) => {
102
+ record.status = status;
103
+ record.ended = why;
104
+ };
105
+ for (const arm of session.arms) {
106
+ const debrief = (0, protocol_1.debriefQuestion)(session.product, arm.label);
107
+ const job = latch.gate("job");
108
+ const debriefGate = latch.gate("debrief");
109
+ const host = guard((request) => request.messages.some((m) => m.role === "user" && m.content === debrief) ? debriefGate : job);
110
+ let obs;
111
+ try {
112
+ obs = await input.runCase({ case: c, host, budget: { take: () => true }, guest: input.kit.guest({ session, arm, case: c, debrief }) });
113
+ }
114
+ catch (error) {
115
+ end("crashed", `${arm.label}: ${(0, loop_1.messageOf)(error)}`);
116
+ break;
117
+ }
118
+ const armResult = armRecord({ arm, c, obs, kit: input.kit, job, debrief: debriefGate });
119
+ record.arms.push(armResult);
120
+ if (latch.voided()) {
121
+ end("void", `${arm.label}: a request named ${named(latch.voided())}`);
122
+ break;
123
+ }
124
+ if (input.ledger.stopped()) {
125
+ end("crashed", `${arm.label}: ${input.ledger.stopped()}`);
126
+ break;
127
+ }
128
+ const refusedOnly = job.refused() !== null || debriefGate.refused() !== null;
129
+ const failed = [obs.outcome, armResult.debriefOutcome ?? ""].find((outcome) => providerFailure(outcome));
130
+ if (failed && !refusedOnly) {
131
+ end("crashed", `${arm.label}: ${failed}`);
132
+ break;
133
+ }
134
+ }
135
+ if (record.status === "complete") {
136
+ const notes = record.arms.map((arm) => ({ label: arm.label, answer: arm.note }));
137
+ const choose = latch.gate("choose");
138
+ const identify = latch.gate("identify");
139
+ const host = guard((request) => request.messages.some((m) => m.role === "user" && m.content === protocol_1.IDENTIFY_QUESTION) ? identify : choose);
140
+ record.final = await (0, final_1.runFinalConversation)({ runtime: host, product: session.product, notes, allowNudge: () => choose.allowOneMore() });
141
+ if (latch.voided())
142
+ end("void", `final: a request named ${named(latch.voided())}`);
143
+ else if (input.ledger.stopped())
144
+ end("crashed", `final: ${input.ledger.stopped()}`);
145
+ else if (record.final.ended && choose.refused() === null && identify.refused() === null && !record.final.choice)
146
+ end("crashed", `final: ${record.final.ended}`);
147
+ }
148
+ const ouroLabel = session.arms.find((arm) => arm.arm === "ouro").label;
149
+ record.ouroFirst = record.status === "complete" && record.final?.choice?.first === ouroLabel;
150
+ record.voidedBy = latch.voided();
151
+ record.calls = latch.calls();
152
+ record.spent = latch.release();
153
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_session_end", message: "finished an interview session", meta: { session: session.id, status: record.status, calls: record.calls.length } });
154
+ return record;
155
+ }
156
+ /** The counts-only summary: no trace text, no notes, no reasons. */
157
+ function summarizeSessions(records, spent, stopped) {
158
+ const lines = records.map((r) => {
159
+ const passed = r.arms.filter((arm) => arm.passed).length;
160
+ const usage = r.calls.reduce((sum, call) => ({ input: sum.input + (call.usage?.input_tokens ?? 0), output: sum.output + (call.usage?.output_tokens ?? 0) }), { input: 0, output: 0 });
161
+ return `${r.id} ${r.status} ouro-first=${r.ouroFirst ? "yes" : "no"} jobs-passed=${passed}/${r.arms.length} calls=${r.calls.length} tokens-in=${usage.input} tokens-out=${usage.output} credits=${r.spent.credits.toFixed(3)} premium=${r.spent.premium}`;
162
+ });
163
+ return [...lines, `spent: ${spent.credits.toFixed(3)} credits, ${spent.premium} premium requests${stopped ? `; stopped: ${stopped}` : ""}`].join("\n");
164
+ }
165
+ async function runInterviews(args, deps) {
166
+ const all = (0, allocation_1.readAllocation)(deps.readText(args.preregistration), deps.allocationSha256);
167
+ const design = args.reduced ? (0, allocation_1.reducedDesign)(all) : all;
168
+ const unknown = args.sessions.find((id) => !all.some((session) => session.id === id));
169
+ if (unknown)
170
+ throw new Error(`no session ${unknown} in Appendix B`);
171
+ const outside = args.sessions.find((id) => !design.some((session) => session.id === id));
172
+ if (outside)
173
+ throw new Error(`session ${outside} is not in the reduced design`);
174
+ const chosen = args.sessions.length > 0 ? design.filter((session) => args.sessions.includes(session.id)) : design;
175
+ const rerun = chosen.find((session) => deps.started.has(session.id));
176
+ if (rerun)
177
+ throw new Error(`session ${rerun.id} has already started once; a session is never rerun`);
178
+ const missingKit = chosen.find((session) => !deps.kits[session.product]);
179
+ if (missingKit)
180
+ throw new Error(`session ${missingKit.id} is product ${missingKit.product}, which has no runner kit yet`);
181
+ const cases = new Map(deps.loadCases(args.cases).map((c) => [c.id, c]));
182
+ const missingCase = chosen.find((session) => !cases.has(session.job));
183
+ if (missingCase)
184
+ throw new Error(`session ${missingCase.id} needs case ${missingCase.job}, which is not in ${args.cases}`);
185
+ for (const file of [args.output, args.requestLog])
186
+ if (deps.outputExists(file))
187
+ throw new Error(`${file} already exists; name a new file`);
188
+ if (args.budgetCredits !== undefined && (args.priceIn === undefined || args.priceOut === undefined || args.reserveCreditsPerCall === undefined)) {
189
+ throw new Error("a credits cap needs --price-in, --price-out and --reserve-credits-per-call (credits per million tokens, and per call)");
190
+ }
191
+ if (args.budgetCredits !== undefined && !(args.reserveCreditsPerCall > 0))
192
+ throw new Error("--reserve-credits-per-call must be more than 0 with a credits cap, or the cap reserves nothing");
193
+ const target = await deps.resolveTarget(args.target, { agent: args.credentialsAgent });
194
+ const before = await target.quota();
195
+ if (args.budgetCredits === undefined && (target.account === null || before.tokenBased !== false)) {
196
+ throw new Error(`${args.target} is billed by the token (or not known not to be); pass --budget-credits with --price-in, --price-out and --reserve-credits-per-call`);
197
+ }
198
+ const ledger = (0, budget_1.createBudgetLedger)({ premium: args.budgetPremium, ...(args.budgetCredits !== undefined ? { credits: args.budgetCredits } : {}) });
199
+ const pricing = { premiumPerCall: target.unitCost, creditsPerMillionInput: args.priceIn ?? 0, creditsPerMillionOutput: args.priceOut ?? 0 };
200
+ let perCallCredits = args.reserveCreditsPerCall ?? 0;
201
+ const interviewLatch = (0, latch_1.createInterviewLatch)({ ledger, pricing, perCall: () => ({ premium: target.unitCost, credits: perCallCredits }) });
202
+ const log = deps.openLog(args.requestLog);
203
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_run_start", message: "starting blind-interview sessions", meta: { sessions: chosen.length, target: args.target } });
204
+ const records = [];
205
+ let stopped = null;
206
+ const writeReport = () => {
207
+ const totals = ledger.totals();
208
+ deps.writeReport(args.output, {
209
+ schemaVersion: 1, kind: "blind-interviews", target: args.target, harnessRef: args.harnessRef, reduced: args.reduced, account: target.account,
210
+ premiumMultiplier: target.unitCost, caps: totals.caps, spent: totals.spent, calls: totals.calls, stopped, quota: { before, after: after ?? before },
211
+ fidelity: exports.FIDELITY, pricing, sessions: records,
212
+ });
213
+ };
214
+ let after = null;
215
+ try {
216
+ for (const session of chosen) {
217
+ const notRun = (why) => ({
218
+ id: session.id, product: session.product, model: session.model, job: session.job, pilot: session.pilot,
219
+ labels: Object.fromEntries(session.arms.map((arm) => [arm.label, arm.arm])), status: "not-run", ended: why, arms: [], final: null,
220
+ ouroFirst: false, voidedBy: null, calls: [], spent: ZERO,
221
+ });
222
+ if (stopped) {
223
+ records.push(notRun(`the study stopped: ${stopped}`));
224
+ continue;
225
+ }
226
+ const latch = interviewLatch.reserve(session.id, latch_1.SESSION_CALLS);
227
+ if ("refused" in latch) {
228
+ stopped = latch.refused;
229
+ records.push(notRun(latch.refused));
230
+ continue;
231
+ }
232
+ deps.started.add(session.id);
233
+ let record;
234
+ try {
235
+ record = await runSession({ session, kit: deps.kits[session.product], cases, latch, target, ledger, pricing, runCase: deps.runCase, log });
236
+ }
237
+ catch (error) {
238
+ // Nothing that goes wrong in one session loses the sessions already run, or holds its reservation.
239
+ record = { ...notRun((0, loop_1.messageOf)(error)), status: "crashed", voidedBy: latch.voided(), calls: latch.calls(), spent: latch.release() };
240
+ }
241
+ records.push(record);
242
+ perCallCredits = Math.max(perCallCredits, latch.hold.maxCall());
243
+ if (ledger.stopped())
244
+ stopped = ledger.stopped();
245
+ }
246
+ after = await target.quota();
247
+ }
248
+ finally {
249
+ writeReport();
250
+ }
251
+ deps.print(summarizeSessions(records, ledger.totals().spent, stopped));
252
+ (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.interview_run_end", message: "finished blind-interview sessions", meta: { sessions: records.length, stopped } });
253
+ return { exitCode: stopped ? 2 : 0, records };
254
+ }
255
+ /** Every X arm, for the parser's check. */
256
+ exports.KNOWN_ARMS = { H: [], U: [], X: arms_1.X_ARMS };
257
+ const STRING_FLAGS = { "--preregistration": "preregistration", "--cases": "cases", "--target": "target", "--credentials-agent": "credentialsAgent", "--output": "output", "--request-log": "requestLog", "--harness-ref": "harnessRef" };
258
+ const NUMBER_FLAGS = { "--budget-premium": "budgetPremium", "--budget-credits": "budgetCredits", "--price-in": "priceIn", "--price-out": "priceOut", "--reserve-credits-per-call": "reserveCreditsPerCall" };
259
+ const REQUIRED = ["--preregistration", "--cases", "--target", "--credentials-agent", "--budget-premium", "--output"];
260
+ function parseInterviewArgs(argv) {
261
+ const out = { sessions: [], reduced: false, harnessRef: "unknown" };
262
+ const seen = new Set();
263
+ for (let i = 0; i < argv.length; i += 1) {
264
+ const flag = argv[i];
265
+ if (flag === "--reduced") {
266
+ out.reduced = true;
267
+ continue;
268
+ }
269
+ const value = argv[i + 1];
270
+ if (flag !== "--session" && !Object.hasOwn(STRING_FLAGS, flag) && !Object.hasOwn(NUMBER_FLAGS, flag))
271
+ throw new Error(`unknown flag ${flag}`);
272
+ if (value === undefined)
273
+ throw new Error(`${flag} needs a value`);
274
+ i += 1;
275
+ seen.add(flag);
276
+ if (flag === "--session")
277
+ out.sessions.push(value);
278
+ else if (Object.hasOwn(STRING_FLAGS, flag))
279
+ out[STRING_FLAGS[flag]] = value;
280
+ else {
281
+ const number = Number(value);
282
+ if (!(Number.isFinite(number) && number >= 0))
283
+ throw new Error(`${flag} must be a number of at least 0`);
284
+ out[NUMBER_FLAGS[flag]] = number;
285
+ }
286
+ }
287
+ const missing = REQUIRED.find((flag) => !seen.has(flag));
288
+ if (missing)
289
+ throw new Error(`${missing} is required`);
290
+ out.requestLog ??= String(out.output).replace(/(\.json)?$/, ".requests.ndjson");
291
+ return out;
292
+ }
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.WRITABLE = exports.POCKETBOOK_ADDRESS = exports.LIBGEN_MIRRORS = exports.HOUSEHOLD_IMAGE = exports.SANDBOX_IMAGE = void 0;
6
+ exports.WRITABLE = exports.POCKETBOOK_ADDRESS = exports.LIBGEN_MIRRORS = exports.BUTLER_CONTAINERS = exports.EVAL_LABEL = exports.EVAL_RUN_PREFIX = exports.HOUSEHOLD_IMAGE = exports.SANDBOX_IMAGE = void 0;
7
7
  exports.dockerCli = dockerCli;
8
8
  exports.buildSandboxImage = buildSandboxImage;
9
9
  exports.splitTurns = splitTurns;
@@ -29,7 +29,12 @@ exports.runSandboxed = runSandboxed;
29
29
  * which ends every process the turn started, then the household, and only then reads the household's state file and
30
30
  * hashes the files that appeared in the writable mounts. A run whose files cannot be read back within the limits ends
31
31
  * as a sandbox error, which fails it. The containers, the network and the run's folder are removed afterwards,
32
- * whatever happened. Every name the run creates starts with `ouro-eval-`.
32
+ * whatever happened. Every name the run creates starts with `eval-sandbox-`, outside the `ouro-` names the Butler's
33
+ * tooling owns, and every container and network it creates carries the labels `ouro.eval=1` and `ouro.eval.run=<run>`.
34
+ *
35
+ * It refuses to run on a host that has any of the live Butler's containers unless the caller holds a host lock
36
+ * that the Butler's lifecycle honours: on 2026-11-23 an eval container vanishing mid-upgrade broke the Butler's
37
+ * upgrade and its rollback on the host they shared (#1760).
33
38
  */
34
39
  const node_child_process_1 = require("node:child_process");
35
40
  const node_crypto_1 = __importDefault(require("node:crypto"));
@@ -44,6 +49,12 @@ const projection_1 = require("./projection");
44
49
  const readback_1 = require("./readback");
45
50
  exports.SANDBOX_IMAGE = "ouro-eval-sandbox:local";
46
51
  exports.HOUSEHOLD_IMAGE = "ouro-eval-household:local";
52
+ /** What every container, network and folder a sandboxed run creates is named after. */
53
+ exports.EVAL_RUN_PREFIX = "eval-sandbox-";
54
+ /** The label on everything an eval run creates, so other tooling on the host can tell it is not its own. */
55
+ exports.EVAL_LABEL = "ouro.eval=1";
56
+ /** The live Butler's containers (sanctuary-deployment-target.mjs CANONICAL_NAMES); a host that has any of them is the Butler's. */
57
+ exports.BUTLER_CONTAINERS = "^/?ouro-butler(-staging|-rollback)?$";
47
58
  exports.LIBGEN_MIRRORS = ["libgen.li", "libgen.bz", "libgen.gl", "libgen.la", "libgen.vg"];
48
59
  exports.POCKETBOOK_ADDRESS = "pocketbook@example.invalid";
49
60
  const ALIASES = ["calibre-web", "smtp", ...exports.LIBGEN_MIRRORS];
@@ -182,12 +193,18 @@ function splitTurns(observation, turns) {
182
193
  async function runSandboxed(input) {
183
194
  const docker = input.docker ?? dockerCli();
184
195
  const images = input.images ?? { agent: exports.SANDBOX_IMAGE, household: exports.HOUSEHOLD_IMAGE };
185
- const runId = `ouro-eval-${node_crypto_1.default.randomBytes(4).toString("hex")}`;
196
+ const runId = `${exports.EVAL_RUN_PREFIX}${node_crypto_1.default.randomBytes(4).toString("hex")}`;
197
+ const runLabels = ["--label", exports.EVAL_LABEL, "--label", `ouro.eval.run=${runId}`];
186
198
  const last = input.case.prefix.at(-1);
187
199
  if (last?.role !== "user")
188
200
  throw new Error(`case ${input.case.id}: the prefix must end with the owner's message`);
201
+ // Docker matches the filter against the name with its leading slash; any container it lists makes this the Butler's host.
202
+ const butler = (await docker.run(["ps", "--all", "--filter", `name=${exports.BUTLER_CONTAINERS}`, "--format", "{{.Names}}"])).trim();
203
+ if (butler !== "" && !(await input.hostLock?.held())) {
204
+ throw new Error(`refusing to run the eval sandbox on this host: it runs the live Butler (${butler.split("\n").join(", ")}), and no host lock that the Butler's upgrade and rollback honour is held`);
205
+ }
189
206
  (0, runtime_1.emitNervesEvent)({ component: "eval", event: "eval.sandbox_run_start", message: "starting a sandboxed eval run", meta: { caseId: input.case.id, runId } });
190
- const work = node_fs_1.default.mkdtempSync(node_path_1.default.join(input.workRoot ?? node_os_1.default.tmpdir(), "ouro-eval-"));
207
+ const work = node_fs_1.default.mkdtempSync(node_path_1.default.join(input.workRoot ?? node_os_1.default.tmpdir(), exports.EVAL_RUN_PREFIX));
191
208
  node_fs_1.default.chmodSync(work, 0o700);
192
209
  const bundle = node_path_1.default.join(work, "bundle");
193
210
  const fixtures = node_path_1.default.join(work, "fixtures");
@@ -203,7 +220,7 @@ async function runSandboxed(input) {
203
220
  const reclaim = async () => {
204
221
  reclaimed = true;
205
222
  await docker.run([
206
- "run", "--rm", "--network", "none", "--log-driver", "none", "--cap-drop", "ALL", "--cap-add", "CHOWN", "--cap-add", "FOWNER", "--cap-add", "DAC_OVERRIDE",
223
+ "run", "--rm", ...runLabels, "--network", "none", "--log-driver", "none", "--cap-drop", "ALL", "--cap-add", "CHOWN", "--cap-add", "FOWNER", "--cap-add", "DAC_OVERRIDE",
207
224
  "--user", "0:0", "-v", `${work}:/work`, images.household, "sh", "-c", `chown -R ${self} /work && chmod -R u+rwX /work`,
208
225
  ]);
209
226
  };
@@ -212,7 +229,7 @@ async function runSandboxed(input) {
212
229
  node_fs_1.default.writeFileSync(node_path_1.default.join(bundle, "books/credentials.json"), `${JSON.stringify(booksSettings(), null, 1)}\n`);
213
230
  for (const dir of [fixtures, tls, household])
214
231
  node_fs_1.default.mkdirSync(dir);
215
- const helper = ["run", "--rm", "--network", "none", "--user", self, ...HARDENING];
232
+ const helper = ["run", "--rm", ...runLabels, "--network", "none", "--user", self, ...HARDENING];
216
233
  const labels = JSON.parse(await docker.run([...helper, "-v", `${fixtures}:/out`, images.household, "python3", "/opt/eval/fakes/fixtures.py", "build", "/out"]));
217
234
  // A seeded file sits where an earlier `books get` would have left it, so its place does not mark it as seeded.
218
235
  const earlier = Math.floor(Date.now() / 1000) - 86_400;
@@ -234,13 +251,13 @@ async function runSandboxed(input) {
234
251
  node_fs_1.default.chmodSync(household, 0o777);
235
252
  for (const entry of exports.WRITABLE)
236
253
  openUp(node_path_1.default.join(bundle, entry));
237
- await docker.run(["network", "create", "--internal", "--label", "ouro-eval", runId]);
254
+ await docker.run(["network", "create", "--internal", ...runLabels, runId]);
238
255
  networkMade = true;
239
256
  started.push(sidecarName);
240
257
  // From here a container's user may own files in the run's folder.
241
258
  reclaimed = false;
242
259
  const sidecar = docker.start([
243
- "run", "--rm", "--name", sidecarName, "--network", runId, ...ALIASES.flatMap((alias) => ["--network-alias", alias]),
260
+ "run", "--rm", "--name", sidecarName, ...runLabels, "--network", runId, ...ALIASES.flatMap((alias) => ["--network-alias", alias]),
244
261
  "--user", "10002:10002", ...HARDENING, "--tmpfs", "/tmp:rw,size=64m",
245
262
  "-v", `${fixtures}:/eval/fixtures:ro`, "-v", `${seedFile}:/eval/seed.json:ro`,
246
263
  "-v", `${tls}/server.pem:/eval/tls/server.pem:ro`, "-v", `${tls}/server.key:/eval/tls/server.key:ro`, "-v", `${household}:/eval/state`,
@@ -251,7 +268,7 @@ async function runSandboxed(input) {
251
268
  const before = (0, readback_1.snapshotFiles)(bundle, exports.WRITABLE);
252
269
  started.push(agentName);
253
270
  const agent = docker.start([
254
- "run", "-i", "--rm", "--name", agentName, "--network", runId, "--user", "10001:10001", ...HARDENING,
271
+ "run", "-i", "--rm", "--name", agentName, ...runLabels, "--network", runId, "--user", "10001:10001", ...HARDENING,
255
272
  "--tmpfs", "/tmp:rw,mode=1777,size=256m", "--tmpfs", "/home/ouro:rw,uid=10001,gid=10001,mode=0700,size=256m", "--env", "HOME=/home/ouro",
256
273
  "-v", `${bundle}:${BUNDLE}:ro`, ...exports.WRITABLE.flatMap((entry) => ["-v", `${node_path_1.default.join(bundle, entry)}:${BUNDLE}/${entry}`]),
257
274
  "-v", `${tls}/ca.pem:/etc/ssl/certs/ca-certificates.crt:ro`, "-v", `${turnFile}:/eval/turn.json:ro`,
@@ -8,12 +8,13 @@ exports.dockerOracle = dockerOracle;
8
8
  * checker that cannot run, or answers anything but true or false, grades the file as not readable.
9
9
  */
10
10
  const runtime_1 = require("../../nerves/runtime");
11
+ const docker_1 = require("./docker");
11
12
  const CHECK = "import json, sys; sys.path.insert(0, '/oracle'); from booklib import quality; print(json.dumps(bool(quality.check('/book.epub')['ok'])))";
12
13
  function dockerOracle(input) {
13
14
  return async (file) => {
14
15
  try {
15
16
  const out = await input.docker.run([
16
- "run", "--rm", "--network", "none", "--log-driver", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
17
+ "run", "--rm", "--label", docker_1.EVAL_LABEL, "--network", "none", "--log-driver", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
17
18
  "--tmpfs", "/tmp:rw,size=64m", "-v", `${input.booksLib}:/oracle:ro`, "-v", `${file}:/book.epub:ro`, input.image, "python3", "-I", "-c", CHECK,
18
19
  ]);
19
20
  const verdict = out.trim();
@@ -151,6 +151,10 @@ exports.ENTRY_POINT_COMMANDS = [
151
151
  { code: "budget-stopped", means: "The eval stopped early: a run's reservation would pass a cap, or the provider answered 402 or 429. The report holds the runs that finished.", fix: "Read the summary on stdout. Raise the cap only if that spend is approved; the report keeps every finished run as measured, so a rerun adds runs rather than replacing them." },
152
152
  { code: "eval-error", means: "The eval refused to start or failed: a bad or missing flag, a case that fails its self-test, a report file that exists already, a target without its prices or caps, or a run that threw.", fix: "Read the `eval:` line above it on stderr, fix that, and run again with a new --output path." },
153
153
  ] } },
154
+ { name: "node dist/eval/interview-entry.js", effect: "private", summary: "Run blind-interview sessions on a model.", ax: { id: "cli:node dist/eval/interview-entry.js", group: "diagnostics", effect: "consequential", confirm: "It spends model credits or premium requests on the account the flags name, up to the caps you pass, and a session it starts can never run again.", when: "Run the pre-registered blind-interview sessions on one model, writing a private report and request log; each session reserves its worst case first.", errors: [
155
+ { code: "budget-stopped", means: "The study stopped: a session's reservation would pass a cap, or the provider answered 402 or 429. Later sessions are recorded as not run.", fix: "Read the counts on stdout; the study stays stopped, since a session that didn't run counts as ouro not chosen first." },
156
+ { code: "eval-error", means: "The interviews refused to start (a bad flag, sandbox or target, or a session not allowed or already started) or failed after starting.", fix: "Read the `interviews:` line on stderr; the started file keeps every session it began, so a new run takes only sessions not yet in it." },
157
+ ] } },
154
158
  { name: "node dist/senses/shepherd/judge-evaluation-entry.js", effect: "private", summary: "Evaluate Shepherd's judge on its cases.", ax: { id: "cli:node dist/senses/shepherd/judge-evaluation-entry.js", group: "diagnostics", effect: "write", when: "Measure how Shepherd's judge classifies its evaluation cases, writing a report; it never qualifies v1 on its own.", errors: [
155
159
  { code: "not-passed", means: "The Shepherd judge evaluation finished, but its classification didn't pass or closing its report threw.", fix: "Read the JSON summary on stdout and the report for the failing cases." },
156
160
  { code: "evaluation-error", means: "The Shepherd judge evaluation stopped before running a case (bad arguments, an output that exists already, no judge for the agent, or a bad case corpus), or writing its report threw.", fix: "Read the error in the JSON on stdout, fix it, and run again with a new --output path." },
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1441",
3
+ "version": "0.1.0-alpha.1443",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1441",
9
+ "version": "0.1.0-alpha.1443",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1441",
3
+ "version": "0.1.0-alpha.1443",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {
@@ -39,6 +39,7 @@
39
39
  "test": "vitest run",
40
40
  "test:integration": "npm run build && vitest run --config vitest.integration.config.ts",
41
41
  "eval": "npm run build && node dist/eval/run-entry.js",
42
+ "interviews": "npm run build && node dist/eval/interview-entry.js",
42
43
  "test:eval-sandbox": "npm run build && vitest run --config vitest.eval.config.ts",
43
44
  "test:e2e:package": "npm run build && node scripts/package-e2e.cjs",
44
45
  "test:e2e:self-update": "node scripts/self-update-package-e2e.cjs",