@ouro.bot/cli 0.1.0-alpha.1442 → 0.1.0-alpha.1444

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,11 +1,24 @@
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.1444",
6
+ "changes": [
7
+ "Phone calls on the OpenAI Realtime and SIP engines now record an outcome for each thing the caller says, as cascade calls already did. The earlier note said these engines were \"not covered yet\". Local audio rooms, which also run on the Realtime engine, are still not recorded. Each utterance is recorded once its transcript arrives, before a reply is asked for. The next reply the caller asked for answers everything they said since the last one. A greeting or a holding phrase answers nobody, and a reply that only called a tool hands what it answers on to the next one.",
8
+ "On those engines a reply counts as answered only once some of its audio played. On a Media Stream that means Twilio reported it played. On SIP it means OpenAI reported it started streaming the reply's audio to the caller. A reply's speech is noted before its audio goes out. A tool that may message a person is noted once its own checks pass, just before it runs, so a tool they refuse is not noted.",
9
+ "A reply whose audio was cleared before any played is recorded as failed, with the reason: the call ended, the caller talked over it, or a tool's audio took its place. If OpenAI keeps sending that reply's audio and some of it plays, it counts as answered. The call's opening audio plays after whatever is already playing, so it no longer stops a reply from counting. When the call hangs up through `voice_end_call` without speaking to what the caller said, that is recorded as silent. So is a Realtime or SIP outbound call answered by a voicemail or fax machine. Live audio is never replayed.",
10
+ "Each utterance record now names the process and bridge that made it. Once a bridge is listening, it records as failed only leftovers from a bridge that closed, a process that stopped, or an older build. It does the same for its own calls if it shuts down. Records of a bridge still open, in this process or another running one, are left for a later check, so a second bridge on another port with the same folder no longer fails a running call. Nothing in the daemon closes a voice bridge today, so in practice what a stopped process left is recorded as failed when the voice sense next starts."
11
+ ]
12
+ },
13
+ {
14
+ "version": "0.1.0-alpha.1443",
15
+ "changes": [
16
+ "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."
17
+ ]
18
+ },
4
19
  {
5
20
  "version": "0.1.0-alpha.1442",
6
21
  "changes": [
7
- "A Butler upgrade or rollback no longer fails when a container on the host stops while the upgrade is checking for other programs reading the Butler's bundle. A container that has stopped can't be one of them, so it is skipped. One that is still running but can't be read still stops the upgrade.",
8
- "`npm run butler:ship` refuses to start the gate or the upgrade while eval containers (`ouro-eval-*`) are running on the host, and says which ones. Nothing on the host has changed when it refuses.",
9
22
  "An eval run's sandbox no longer shares names with the Butler's tooling, and it stays off the Butler's host.",
10
23
  "Its containers, network and folder are named `eval-sandbox-<run>`, no longer `ouro-eval-<run>`.",
11
24
  "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.",
@@ -14,6 +27,13 @@
14
27
  "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."
15
28
  ]
16
29
  },
30
+ {
31
+ "version": "0.1.0-alpha.1441",
32
+ "changes": [
33
+ "A Butler upgrade or rollback no longer fails when a container on the host stops while the upgrade is checking for other programs reading the Butler's bundle. A container that has stopped can't be one of them, so it is skipped. One that is still running but can't be read still stops the upgrade.",
34
+ "`npm run butler:ship` refuses to start the gate or the upgrade while eval containers (`ouro-eval-*`) are running on the host, and says which ones. Nothing on the host has changed when it refuses."
35
+ ]
36
+ },
17
37
  {
18
38
  "version": "0.1.0-alpha.1440",
19
39
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1442",
2
+ "runtimeVersion": "0.1.0-alpha.1444",
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.1442</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1444</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
+ }