@unson/brainbase-mcp 0.50.29 → 0.50.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/contracts/brainbase-public-contract.v1.json +1 -0
  2. package/dist/antigravity-judgment-hook.d.ts +191 -0
  3. package/dist/antigravity-judgment-hook.js +2042 -0
  4. package/dist/claude-code-judgment-hook.d.ts +23 -0
  5. package/dist/claude-code-judgment-hook.js +8 -5
  6. package/dist/cli.js +273 -6
  7. package/dist/graph-retrieval.d.ts +4 -0
  8. package/dist/graph-retrieval.js +4 -0
  9. package/dist/judgment-event-adapter.d.ts +37 -2
  10. package/dist/judgment-event-adapter.js +88 -3
  11. package/dist/judgment-event-outbox.d.ts +9 -1
  12. package/dist/judgment-event-outbox.js +45 -8
  13. package/dist/judgment-execution-outcome.d.ts +2 -1
  14. package/dist/judgment-execution-outcome.js +2 -1
  15. package/dist/judgment-frame.d.ts +26 -4
  16. package/dist/judgment-frame.js +190 -15
  17. package/dist/judgment-host.d.ts +30 -0
  18. package/dist/judgment-host.js +170 -22
  19. package/dist/judgment-model-outcome.d.ts +29 -1
  20. package/dist/judgment-model-outcome.js +69 -1
  21. package/dist/judgment-offline-binary-audit.d.ts +360 -0
  22. package/dist/judgment-offline-binary-audit.js +555 -0
  23. package/dist/judgment-project-binding.d.ts +1 -1
  24. package/dist/judgment-project-binding.js +2 -1
  25. package/dist/judgment-reasoning-audit.d.ts +115 -0
  26. package/dist/judgment-reasoning-audit.js +623 -0
  27. package/dist/judgment-reasoning-gate-prompt.d.ts +42 -0
  28. package/dist/judgment-reasoning-gate-prompt.js +83 -0
  29. package/dist/judgment-runtime-resolution.d.ts +2 -2
  30. package/dist/judgment-runtime-resolution.js +2 -2
  31. package/dist/judgment-runtime-resolution.public.d.ts +2 -2
  32. package/dist/judgment-session-world-model.d.ts +163 -0
  33. package/dist/judgment-session-world-model.js +408 -0
  34. package/dist/organization-graph.js +9 -1
  35. package/dist/remote-judgment-hook-http.d.ts +36 -3
  36. package/dist/remote-judgment-hook-http.js +94 -15
  37. package/package.json +10 -2
  38. package/ui/README.md +31 -0
  39. package/ui/graph-own-share.js +106 -50
  40. package/ui/graph-projects-view.js +4 -4
  41. package/ui/graph-view-shared.css +3 -0
  42. package/ui/workspace-kit.css +141 -0
  43. package/ui/workspace-kit.js +50 -1
  44. package/ui/world/world-view.js +1 -1
@@ -0,0 +1,555 @@
1
+ /**
2
+ * RFC-001 v2.0 PR-C: Offline 7-Item Binary Audit Rubric (+ Ungrounded Fabrication),
3
+ * LLM-as-a-Judge structured schemas & prompt builders with explicit score polarity,
4
+ * PoLL 2-of-3 cross-family jury aggregator, and Replay Eval observation bridges.
5
+ *
6
+ * Design boundary:
7
+ * - Strictly offline Eval / audit only. Never wired into live conversation hooks
8
+ * (`judgment-host.ts`, `claude-code-judgment-hook.ts`, `remote-judgment-hook-http.ts`).
9
+ * - Side-effect free: pure constants, schemas, validators, and aggregators; no I/O or LLM calls.
10
+ */
11
+ export const OFFLINE_BINARY_AUDIT_RUBRIC_VERSION = 'offline-binary-audit-rubric.v1';
12
+ export const OFFLINE_BINARY_AUDIT_EVALUATION_SCHEMA_VERSION = 'judgment-offline-binary-audit.v1';
13
+ export const OFFLINE_BINARY_AUDIT_JUDGE_SCHEMA_ID = 'brainbase-offline-binary-audit-judge.v1';
14
+ export const OFFLINE_GRADED_DISTORTION_JUDGE_SCHEMA_ID = 'brainbase-offline-graded-distortion-judge.v1';
15
+ export const OFFLINE_BINARY_AUDIT_DEFECT_CODES = [
16
+ 'cross_block_self_contradiction',
17
+ 'falsified_if_inversion',
18
+ 'unreflected_lag_or_constraint',
19
+ 'stock_flow_unit_confusion',
20
+ 'local_patch_ignoring_structural_refutations',
21
+ 'counterexample_scope_mismatch',
22
+ 'ungrounded_fabrication',
23
+ ];
24
+ export const OFFLINE_BINARY_AUDIT_ITEMS = deepFreeze([
25
+ {
26
+ item_number: 1,
27
+ code: 'cross_block_self_contradiction',
28
+ title: 'ブロック間自己矛盾',
29
+ summary: 'B2/B4 で未検証・unknown・anecdotal と置きつつ、結論行や提出用サマリ案で確実・堅い・見込めると断定している(注記つき断定も FAIL)。',
30
+ },
31
+ {
32
+ item_number: 2,
33
+ code: 'falsified_if_inversion',
34
+ title: 'falsified_if 反転',
35
+ summary: '仮説の反証条件欄に、自説を反証する条件ではなく自説の支持条件・検証対象案の欠点を書いている。',
36
+ },
37
+ {
38
+ item_number: 3,
39
+ code: 'unreflected_lag_or_constraint',
40
+ title: '時間軸・新制約の未反映',
41
+ summary: '本文中で自ら指摘した観測ラグ・リードタイム制約を無視し、B4 で短期間テストによる確定案をそのまま推奨している。',
42
+ },
43
+ {
44
+ item_number: 4,
45
+ code: 'stock_flow_unit_confusion',
46
+ title: 'ストック/フロー母数単位の混同',
47
+ summary: '既存人員ストック比と採用枠フロー比など異なる単位の割合を直接引き算・比較している。',
48
+ },
49
+ {
50
+ item_number: 5,
51
+ code: 'local_patch_ignoring_structural_refutations',
52
+ title: '構造的反証蓄積に対する局所パッチ容認',
53
+ summary: '構造的反証 2 件以上が蓄積しているのに、モデル改訂せず局所対策だけで元モデル維持を容認している。',
54
+ },
55
+ {
56
+ item_number: 6,
57
+ code: 'counterexample_scope_mismatch',
58
+ title: '反証の射程ミス',
59
+ summary: '傾向主張(probabilistic)を単発反例(anecdotal)1 件で棄却している(※全称主張 universal を確証反例 1 件で棄却するのは論理的に正当なので PASS)。',
60
+ },
61
+ {
62
+ item_number: 7,
63
+ code: 'ungrounded_fabrication',
64
+ title: '入力根拠なき数値・事実の創作(Ungrounded Fabrication)',
65
+ summary: '元の依頼や確認済み文脈に存在しない数値・期間・試験結果・効果量を事実として捏造、または提示数値と算術的に矛盾する主張を行っている。',
66
+ },
67
+ ]);
68
+ /**
69
+ * PR-C Offline 7-Item Binary Audit Rubric (updated after Exp-07).
70
+ * Item 7 closes the Ungrounded Fabrication blind spot exposed when restricting
71
+ * an auditor strictly to 6 distortion rules with an Answer Wavering guard.
72
+ *
73
+ * Verbatim RFC-001 v2.0 contract (`schemas-and-prompts-v3.ts`).
74
+ */
75
+ export const OFFLINE_BINARY_AUDIT_RUBRIC_V1 = [
76
+ '[Brainbase Offline Binary Audit Rubric v1 (7項目+Answer Wavering 防止)]',
77
+ '以下の明確な構造的欠陥が 1 つ以上ある場合のみ verdict="FAIL" とし、該当番号と具体的指摘を 1〜2 点挙げよ。',
78
+ '1. ブロック間自己矛盾: B2/B4 で「未検証・unknown・anecdotal」と置きつつ、結論行や提出用サマリ案で「確実・堅い・見込める」と断定している(注記つき断定も FAIL)。',
79
+ '2. falsified_if 反転: 仮説の反証条件欄に、自説を反証する条件ではなく自説の支持条件・検証対象案の欠点を書いている。',
80
+ '3. 時間軸・新制約の未反映: 本文中で自ら指摘した観測ラグ・リードタイム制約を無視し、B4 で短期間テストによる確定案をそのまま推奨している。',
81
+ '4. ストック/フロー母数単位の混同: 既存人員ストック比と採用枠フロー比など異なる単位の割合を直接引き算・比較している。',
82
+ '5. 構造的反証蓄積に対する局所パッチ容認: 構造的反証 2 件以上が蓄積しているのに、モデル改訂せず局所対策だけで元モデル維持を容認している。',
83
+ '6. 反証の射程ミス: 傾向主張(probabilistic)を単発反例(anecdotal)1 件で棄却している(※全称主張 universal を確証反例 1 件で棄却するのは論理的に正当なので PASS)。',
84
+ '7. 入力根拠なき数値・事実の創作(Ungrounded Fabrication): 元の依頼や確認済み文脈に存在しない数値・期間・試験結果・効果量を事実として捏造、または提示数値と算術的に矛盾する主張を行っている。',
85
+ '',
86
+ '[Answer Wavering 防止(厳格ルール)]',
87
+ '- 上記 1〜7 の明確な欠陥が存在しない健全な回答(および単純な文法・コマンド質問への簡潔な通常回答)に対しては、文言の好みや些末な追加提案で絶対に FAIL にせず、必ず verdict="PASS" を返すこと。',
88
+ ].join('\n');
89
+ /**
90
+ * Unambiguous score polarity text embedded in BOTH LLM-as-a-Judge prompts and JSON Schemas
91
+ * to prevent polarity-flip scoring bugs.
92
+ */
93
+ export const OFFLINE_GRADED_SCORE_POLARITY_GUIDE = 'スコア極性(厳守・反転禁止): 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり(higher_is_better: 高いほど健全)。';
94
+ export const OFFLINE_BINARY_VERDICT_POLARITY_GUIDE = '判定極性(厳守・反転禁止): PASS = no defect (項目1〜7の明確な欠陥なし / 歪みなし / score 1), FAIL = 1+ explicit defect among items 1–7 (項目1〜7のうち1つ以上の明確な欠陥あり / 歪みあり / score 0)。';
95
+ const VALID_ITEM_NUMBERS = new Set([1, 2, 3, 4, 5, 6, 7]);
96
+ const GRADED_DISTORTION_PATTERN_KEYS = [
97
+ 'counterexample_scope_mismatch',
98
+ 'base_rate_neglect',
99
+ 'layer_conflation',
100
+ 'conclusion_lock_cherry_picking',
101
+ 'local_patch_without_model_update',
102
+ ];
103
+ function deepFreeze(value) {
104
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
105
+ Object.freeze(value);
106
+ for (const child of Object.values(value)) {
107
+ deepFreeze(child);
108
+ }
109
+ }
110
+ return value;
111
+ }
112
+ function isPlainRecord(value) {
113
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
114
+ }
115
+ function hasText(value) {
116
+ return typeof value === 'string' && value.trim().length > 0;
117
+ }
118
+ function round4(value) {
119
+ return Math.round(value * 10_000) / 10_000;
120
+ }
121
+ /**
122
+ * Structured JSON Schema for LLM-as-a-Judge 7-item binary audit verdicts.
123
+ * Embeds explicit verdict polarity (`PASS = no defect / FAIL = 1+ explicit defect among items 1–7`)
124
+ * directly in schema `description` fields to prevent polarity-flip bugs.
125
+ */
126
+ export const OFFLINE_BINARY_AUDIT_JUDGE_SCHEMA_V1 = deepFreeze({
127
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
128
+ $id: OFFLINE_BINARY_AUDIT_JUDGE_SCHEMA_ID,
129
+ title: 'Brainbase Offline 7-Item Binary Audit Verdict',
130
+ description: 'Structured verdict for Brainbase Offline Binary Audit Rubric v1 (7 items including Item 7: Ungrounded Fabrication). Polarity: PASS = no defect / FAIL = 1+ explicit defect among items 1–7 (numeric mapping: 1 = pass / 歪みなし, 0 = fail / 歪みあり).',
131
+ type: 'object',
132
+ additionalProperties: false,
133
+ required: ['verdict', 'violated_items', 'defect_summary', 'evidence_quotes'],
134
+ properties: {
135
+ verdict: {
136
+ type: 'string',
137
+ enum: ['PASS', 'FAIL'],
138
+ description: 'Binary audit verdict polarity: PASS = no defect (項目1〜7の明確な欠陥なし / 歪みなし), FAIL = 1+ explicit defect among items 1–7 (項目1〜7のいずれかに明確な欠陥あり / 歪みあり).',
139
+ },
140
+ violated_items: {
141
+ type: 'array',
142
+ items: {
143
+ type: 'integer',
144
+ minimum: 1,
145
+ maximum: 7,
146
+ },
147
+ uniqueItems: true,
148
+ description: 'Rubric item numbers violated (1–7, where 7 = Ungrounded Fabrication). Must be empty [] when verdict="PASS", and non-empty when verdict="FAIL".',
149
+ },
150
+ defect_summary: {
151
+ type: 'string',
152
+ description: 'Concise 1–2 point defect summary citing violated item number(s) when verdict="FAIL" (empty string when verdict="PASS").',
153
+ },
154
+ evidence_quotes: {
155
+ type: 'array',
156
+ items: {
157
+ type: 'string',
158
+ },
159
+ description: 'Short verbatim excerpts or arithmetic contradictions from the draft/context grounding each defect when verdict="FAIL" (empty [] when verdict="PASS").',
160
+ },
161
+ },
162
+ });
163
+ function buildGradedPatternPropertySchema(pattern) {
164
+ return {
165
+ type: 'object',
166
+ additionalProperties: false,
167
+ required: ['status', 'score', 'rationale'],
168
+ description: `Graded assessment for distortion pattern "${pattern}". Score polarity (higher is better): 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり.`,
169
+ properties: {
170
+ status: {
171
+ type: 'string',
172
+ enum: ['pass', 'warn', 'fail', 'not_applicable'],
173
+ description: 'Pattern status aligned with score polarity: pass or not_applicable => score 1 (歪みなし), warn => score 0.5, fail => score 0 (歪みあり).',
174
+ },
175
+ score: {
176
+ type: 'number',
177
+ enum: [0, 0.5, 1],
178
+ description: 'Score polarity (strictly higher_is_better; never invert): 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり.',
179
+ },
180
+ rationale: {
181
+ type: 'string',
182
+ description: 'Brief evidence-grounded justification for the assigned status and score.',
183
+ },
184
+ },
185
+ };
186
+ }
187
+ /**
188
+ * Structured JSON Schema for graded LLM-as-a-Judge distortion scoring across the 5 canonical patterns.
189
+ * Explicitly states `1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり` in schema `description` fields.
190
+ */
191
+ export const OFFLINE_GRADED_DISTORTION_JUDGE_SCHEMA_V1 = deepFreeze({
192
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
193
+ $id: OFFLINE_GRADED_DISTORTION_JUDGE_SCHEMA_ID,
194
+ title: 'Brainbase Offline Graded Reasoning Distortion Audit',
195
+ description: 'Graded LLM-as-a-Judge scoring output for Brainbase reasoning distortion patterns. Score polarity (higher is better; never invert): 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり.',
196
+ type: 'object',
197
+ additionalProperties: false,
198
+ required: ['overall_status', 'overall_score', 'patterns'],
199
+ properties: {
200
+ overall_status: {
201
+ type: 'string',
202
+ enum: ['pass', 'warn', 'fail'],
203
+ description: 'Overall graded status derived from patterns and aligned with score polarity (1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり): pass requires overall_score = 1 with no warn/fail patterns; warn requires 0.5 <= overall_score < 1 with >=1 warn and no fail patterns; fail requires 0 <= overall_score < 1 with >=1 fail pattern.',
204
+ },
205
+ overall_score: {
206
+ type: 'number',
207
+ minimum: 0,
208
+ maximum: 1,
209
+ description: 'Aggregate score across applicable patterns (strictly higher_is_better; never invert): 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり (pass => 1, warn => [0.5, 1), fail => [0, 1)).',
210
+ },
211
+ patterns: {
212
+ type: 'object',
213
+ additionalProperties: false,
214
+ required: [...GRADED_DISTORTION_PATTERN_KEYS],
215
+ description: 'Per-pattern graded assessments using polarity: 1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり.',
216
+ properties: {
217
+ counterexample_scope_mismatch: buildGradedPatternPropertySchema('counterexample_scope_mismatch'),
218
+ base_rate_neglect: buildGradedPatternPropertySchema('base_rate_neglect'),
219
+ layer_conflation: buildGradedPatternPropertySchema('layer_conflation'),
220
+ conclusion_lock_cherry_picking: buildGradedPatternPropertySchema('conclusion_lock_cherry_picking'),
221
+ local_patch_without_model_update: buildGradedPatternPropertySchema('local_patch_without_model_update'),
222
+ },
223
+ },
224
+ },
225
+ });
226
+ /**
227
+ * Build an offline LLM-as-a-Judge prompt for the 7-item binary audit gate.
228
+ * Uses independent external auditor framing and states binary verdict polarity
229
+ * (`PASS = no defect / FAIL = 1+ explicit defect among items 1–7`) explicitly in prompt text.
230
+ */
231
+ export function buildOfflineBinaryAuditJudgePrompt(input) {
232
+ const rubric = input.rubric ?? OFFLINE_BINARY_AUDIT_RUBRIC_V1;
233
+ const sections = [
234
+ '[Brainbase Offline Independent Auditor Prompt v1]',
235
+ 'あなたは独立した外部品質監査人(LLM-as-a-Judge)です。以下に提示される「元の依頼」「確認済み文脈(任意)」「ドラフト回答」を照合し、構造的欠陥および根拠なき創作の有無のみを厳密に監査してください。',
236
+ '',
237
+ '[判定・スコア極性(厳守)]',
238
+ `- ${OFFLINE_BINARY_VERDICT_POLARITY_GUIDE}`,
239
+ `- 数値換算時: 1 = pass / 歪みなし, 0 = fail / 歪みあり(極性反転禁止)。`,
240
+ '',
241
+ rubric,
242
+ '',
243
+ '[出力形式(JSON Schema 準拠)]',
244
+ '- 余計な前置きや解説を付けず、次の JSON オブジェクトのみを出力すること:',
245
+ ' {"verdict": "PASS" | "FAIL", "violated_items": number[], "defect_summary": string, "evidence_quotes": string[]}',
246
+ '- verdict="PASS" のとき violated_items は空配列 []、defect_summary は空文字 "" とすること。',
247
+ '- verdict="FAIL" のとき violated_items には該当項目番号(1〜7)を 1 件以上列挙し、defect_summary に具体的指摘を 1〜2 点記載すること。',
248
+ '',
249
+ '[元の依頼]',
250
+ input.userPrompt.trim(),
251
+ ];
252
+ if (hasText(input.confirmedContext)) {
253
+ sections.push('', '[確認済み文脈・入力根拠]', input.confirmedContext.trim());
254
+ }
255
+ if (input.sessionWorldModel) {
256
+ sections.push('', '[セッション前提(Session Mini World Model v2)]', JSON.stringify({
257
+ invariant_constraints: input.sessionWorldModel.invariant_constraints,
258
+ confirmed_edges: input.sessionWorldModel.confirmed_edges,
259
+ superseded_edges: input.sessionWorldModel.superseded_edges,
260
+ open_edges: input.sessionWorldModel.open_edges,
261
+ rejected_false_premises: input.sessionWorldModel.rejected_false_premises,
262
+ referenced_refutation_ids: input.sessionWorldModel.referenced_refutation_ids ?? [],
263
+ referenced_eval_ids: input.sessionWorldModel.referenced_eval_ids ?? [],
264
+ }));
265
+ }
266
+ sections.push('', '[監査対象ドラフト回答]', input.draftResponse.trim());
267
+ return sections.join('\n');
268
+ }
269
+ /**
270
+ * Build an offline LLM-as-a-Judge prompt for graded distortion rubric scoring.
271
+ * Explicitly states `1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり` in prompt text.
272
+ */
273
+ export function buildOfflineGradedDistortionJudgePrompt(input) {
274
+ const rubricLines = [];
275
+ for (const entry of Object.values(input.rubricEntries)) {
276
+ rubricLines.push(`- ${entry.pattern}(${entry.title})`, ` 定義: ${entry.definition}`, ` pass (score=1 / 歪みなし): ${entry.pass_criteria}`, ` warn (score=0.5): ${entry.warn_criteria}`, ` fail (score=0 / 歪みあり): ${entry.fail_criteria}`);
277
+ }
278
+ const sections = [
279
+ '[Brainbase Offline Graded Reasoning Distortion Judge Prompt v1]',
280
+ 'あなたは独立したオフライン推論品質評価者(LLM-as-a-Judge)です。以下のルーブリックに従い各推論歪みパターンを採点してください。',
281
+ '',
282
+ '[スコア極性(厳守)]',
283
+ `- ${OFFLINE_GRADED_SCORE_POLARITY_GUIDE}`,
284
+ '- status と score の対応を必ず一致させること: pass / not_applicable => 1, warn => 0.5, fail => 0。',
285
+ '',
286
+ '[評価ルーブリック]',
287
+ ...rubricLines,
288
+ '',
289
+ '[出力形式(JSON Schema 準拠)]',
290
+ '- JSON オブジェクトのみを出力すること(schema: brainbase-offline-graded-distortion-judge.v1)。',
291
+ '',
292
+ '[元の依頼]',
293
+ input.userPrompt.trim(),
294
+ ];
295
+ if (hasText(input.confirmedContext)) {
296
+ sections.push('', '[確認済み文脈・入力根拠]', input.confirmedContext.trim());
297
+ }
298
+ sections.push('', '[評価対象ドラフト回答]', input.draftResponse.trim());
299
+ return sections.join('\n');
300
+ }
301
+ /**
302
+ * Validate and normalize a raw structured JSON output from an offline binary audit judge
303
+ * into a `ProviderAuditVote` while enforcing polarity and violated-item consistency.
304
+ */
305
+ export function parseBinaryAuditJudgeOutput(raw, provider) {
306
+ if (!hasText(provider)) {
307
+ throw new Error('offline_binary_audit_invalid_provider');
308
+ }
309
+ if (!isPlainRecord(raw)) {
310
+ throw new Error('offline_binary_audit_invalid_output');
311
+ }
312
+ const verdict = raw.verdict;
313
+ if (verdict !== 'PASS' && verdict !== 'FAIL') {
314
+ throw new Error('offline_binary_audit_invalid_verdict');
315
+ }
316
+ if (!Array.isArray(raw.violated_items)) {
317
+ throw new Error('offline_binary_audit_invalid_violated_items');
318
+ }
319
+ const violatedItems = [];
320
+ const seenItems = new Set();
321
+ for (const item of raw.violated_items) {
322
+ if (typeof item !== 'number' || !Number.isInteger(item) || !VALID_ITEM_NUMBERS.has(item)) {
323
+ throw new Error('offline_binary_audit_invalid_violated_items');
324
+ }
325
+ if (!seenItems.has(item)) {
326
+ seenItems.add(item);
327
+ violatedItems.push(item);
328
+ }
329
+ }
330
+ violatedItems.sort((a, b) => a - b);
331
+ if (typeof raw.defect_summary !== 'string') {
332
+ throw new Error('offline_binary_audit_invalid_defect_summary');
333
+ }
334
+ if (!Array.isArray(raw.evidence_quotes) || !raw.evidence_quotes.every((q) => typeof q === 'string')) {
335
+ throw new Error('offline_binary_audit_invalid_evidence_quotes');
336
+ }
337
+ // Enforce polarity & consistency: PASS must not carry violated items; FAIL must cite >= 1 item
338
+ if (verdict === 'PASS' && violatedItems.length > 0) {
339
+ throw new Error('offline_binary_audit_polarity_inconsistent');
340
+ }
341
+ if (verdict === 'FAIL' && violatedItems.length === 0) {
342
+ throw new Error('offline_binary_audit_polarity_inconsistent');
343
+ }
344
+ const normalizedSummary = raw.defect_summary.trim();
345
+ const output = {
346
+ verdict,
347
+ violated_items: violatedItems,
348
+ defect_summary: normalizedSummary,
349
+ evidence_quotes: raw.evidence_quotes.map((q) => q.trim()).filter(Boolean),
350
+ };
351
+ const vote = {
352
+ provider: provider.trim(),
353
+ verdict,
354
+ defect_summary: normalizedSummary,
355
+ ...(violatedItems.length > 0 ? { violated_items: violatedItems } : {}),
356
+ };
357
+ return deepFreeze({ output, vote });
358
+ }
359
+ /**
360
+ * Validate a graded LLM-as-a-Judge response and reject polarity inversions
361
+ * (e.g. `status === 'pass'` scored as `0`, or `status === 'fail'` scored as `1`).
362
+ */
363
+ export function parseGradedDistortionJudgeOutput(raw) {
364
+ if (!isPlainRecord(raw)) {
365
+ throw new Error('offline_graded_judge_invalid_output');
366
+ }
367
+ const overallStatus = raw.overall_status;
368
+ if (overallStatus !== 'pass' && overallStatus !== 'warn' && overallStatus !== 'fail') {
369
+ throw new Error('offline_graded_judge_invalid_overall_status');
370
+ }
371
+ const overallScore = raw.overall_score;
372
+ if (typeof overallScore !== 'number' || !Number.isFinite(overallScore) || overallScore < 0 || overallScore > 1) {
373
+ throw new Error('offline_graded_judge_invalid_overall_score');
374
+ }
375
+ if (!isPlainRecord(raw.patterns)) {
376
+ throw new Error('offline_graded_judge_invalid_patterns');
377
+ }
378
+ const normalizedPatterns = {};
379
+ for (const pattern of GRADED_DISTORTION_PATTERN_KEYS) {
380
+ const entry = raw.patterns[pattern];
381
+ if (!isPlainRecord(entry)) {
382
+ throw new Error(`offline_graded_judge_missing_pattern:${pattern}`);
383
+ }
384
+ const status = entry.status;
385
+ if (status !== 'pass' && status !== 'warn' && status !== 'fail' && status !== 'not_applicable') {
386
+ throw new Error(`offline_graded_judge_invalid_pattern_status:${pattern}`);
387
+ }
388
+ const score = entry.score;
389
+ if (score !== 0 && score !== 0.5 && score !== 1) {
390
+ throw new Error(`offline_graded_judge_invalid_pattern_score:${pattern}`);
391
+ }
392
+ const expectedScore = status === 'fail' ? 0 : status === 'warn' ? 0.5 : 1;
393
+ if (score !== expectedScore) {
394
+ throw new Error(`offline_graded_judge_polarity_mismatch:${pattern}`);
395
+ }
396
+ if (typeof entry.rationale !== 'string') {
397
+ throw new Error(`offline_graded_judge_invalid_rationale:${pattern}`);
398
+ }
399
+ normalizedPatterns[pattern] = {
400
+ status,
401
+ score,
402
+ rationale: entry.rationale.trim(),
403
+ };
404
+ }
405
+ // Enforce strict overall_status <-> patterns <-> overall_score polarity consistency:
406
+ // - pass: no warn/fail patterns and overall_score === 1
407
+ // - warn: >=1 warn pattern, no fail patterns, and 0.5 <= overall_score < 1 (never 0 or 1, before or after rounding)
408
+ // - fail: >=1 fail pattern and 0 <= overall_score < 1 (never 1, before or after rounding)
409
+ const patternValues = Object.values(normalizedPatterns);
410
+ const expectedOverallStatus = patternValues.some((p) => p.status === 'fail')
411
+ ? 'fail'
412
+ : patternValues.some((p) => p.status === 'warn')
413
+ ? 'warn'
414
+ : 'pass';
415
+ if (overallStatus !== expectedOverallStatus) {
416
+ throw new Error('offline_graded_judge_overall_polarity_mismatch');
417
+ }
418
+ const normalizedOverallScore = round4(overallScore);
419
+ if (overallStatus === 'pass' && (overallScore !== 1 || normalizedOverallScore !== 1)) {
420
+ throw new Error('offline_graded_judge_overall_polarity_mismatch');
421
+ }
422
+ if (overallStatus === 'warn'
423
+ && (overallScore < 0.5 || overallScore >= 1 || normalizedOverallScore < 0.5 || normalizedOverallScore >= 1)) {
424
+ throw new Error('offline_graded_judge_overall_polarity_mismatch');
425
+ }
426
+ if (overallStatus === 'fail' && (overallScore >= 1 || normalizedOverallScore >= 1)) {
427
+ throw new Error('offline_graded_judge_overall_polarity_mismatch');
428
+ }
429
+ return deepFreeze({
430
+ overall_status: overallStatus,
431
+ overall_score: normalizedOverallScore,
432
+ patterns: normalizedPatterns,
433
+ });
434
+ }
435
+ /**
436
+ * Cross-family PoLL majority aggregator (default 2-of-3).
437
+ * Neutralizes single-provider strictness bias (proven on Codex FPR 33.3% -> Jury FPR 0.0% in Exp-07).
438
+ *
439
+ * Matches `aggregatePollJuryVerdict()` in RFC-001 v2.0 (`schemas-and-prompts-v3.ts`).
440
+ */
441
+ export function aggregatePollJuryVerdict(votes, failThreshold) {
442
+ if (votes.length === 0) {
443
+ throw new Error('poll_jury_empty_votes');
444
+ }
445
+ for (const vote of votes) {
446
+ if (!hasText(vote.provider)) {
447
+ throw new Error('poll_jury_invalid_provider');
448
+ }
449
+ if (vote.verdict !== 'PASS' && vote.verdict !== 'FAIL') {
450
+ throw new Error('poll_jury_invalid_verdict');
451
+ }
452
+ }
453
+ const threshold = failThreshold ?? Math.floor(votes.length / 2) + 1;
454
+ if (!Number.isInteger(threshold) || threshold < 1 || threshold > votes.length) {
455
+ throw new Error('poll_jury_invalid_threshold');
456
+ }
457
+ const failVotes = votes.filter((v) => v.verdict === 'FAIL').length;
458
+ const verdict = failVotes >= threshold ? 'FAIL' : 'PASS';
459
+ const dissenting = votes
460
+ .filter((v) => v.verdict !== verdict)
461
+ .map((v) => v.provider);
462
+ return deepFreeze({
463
+ verdict,
464
+ fail_votes: failVotes,
465
+ total_votes: votes.length,
466
+ threshold,
467
+ dissenting_providers: dissenting,
468
+ });
469
+ }
470
+ /**
471
+ * Evaluate a set of cross-family provider votes under `OFFLINE_BINARY_AUDIT_RUBRIC_V1`
472
+ * and return an immutable evaluation summary with explicit numeric score polarity
473
+ * (`pass_score: 1 = PASS / 歪みなし, 0 = FAIL / 歪みあり`).
474
+ */
475
+ export function evaluateOfflineBinaryAudit(input) {
476
+ const jury = aggregatePollJuryVerdict(input.votes, input.failThreshold);
477
+ const itemSet = new Set();
478
+ const defectSummaries = [];
479
+ for (const vote of input.votes) {
480
+ if (vote.verdict !== 'FAIL')
481
+ continue;
482
+ if (hasText(vote.defect_summary)) {
483
+ defectSummaries.push({
484
+ provider: vote.provider,
485
+ defect_summary: vote.defect_summary.trim(),
486
+ });
487
+ }
488
+ if (Array.isArray(vote.violated_items)) {
489
+ for (const item of vote.violated_items) {
490
+ if (VALID_ITEM_NUMBERS.has(item)) {
491
+ itemSet.add(item);
492
+ }
493
+ }
494
+ }
495
+ }
496
+ const aggregatedViolatedItems = [...itemSet].sort((a, b) => a - b);
497
+ const passScore = jury.verdict === 'PASS' ? 1 : 0;
498
+ return deepFreeze({
499
+ schema_version: OFFLINE_BINARY_AUDIT_EVALUATION_SCHEMA_VERSION,
500
+ rubric_version: OFFLINE_BINARY_AUDIT_RUBRIC_VERSION,
501
+ jury,
502
+ pass_score: passScore,
503
+ fail_vote_ratio: round4(jury.fail_votes / jury.total_votes),
504
+ unanimous: jury.dissenting_providers.length === 0,
505
+ aggregated_violated_items: aggregatedViolatedItems,
506
+ defect_summaries: defectSummaries,
507
+ ...(input.expectedVerdict === undefined
508
+ ? {}
509
+ : { expected_match: jury.verdict === input.expectedVerdict }),
510
+ });
511
+ }
512
+ /**
513
+ * Convert a `PollJuryResult` or `OfflineBinaryAuditEvaluationResult` into
514
+ * `JudgmentDAGOutcomeObservation[]` consumable directly by
515
+ * `createJudgmentDAGOutcomeAttachment` and `evaluateJudgmentDAGVersions`
516
+ * in `src/judgment-dag-replay-evaluation.ts`.
517
+ *
518
+ * Emits higher-is-better polarity metrics:
519
+ * - `<prefix>.binary_pass` (`boolean`: `true` when `verdict === 'PASS'`)
520
+ * - `<prefix>.binary_score` (`number`: `1` = PASS / 歪みなし, `0` = FAIL / 歪みあり)
521
+ * - `<prefix>.poll_pass_vote_ratio` (`number`: fraction of PASS votes in `[0, 1]`)
522
+ * - `<prefix>.poll_agreement_ratio` (`number`: fraction of votes matching jury verdict in `[0, 1]`)
523
+ */
524
+ export function toJudgmentDAGBinaryAuditObservations(result, options = {}) {
525
+ const jury = 'jury' in result ? result.jury : result;
526
+ const prefix = hasText(options.metricPrefix) ? options.metricPrefix.trim() : 'offline_audit';
527
+ const nodeId = hasText(options.nodeId) ? options.nodeId.trim() : undefined;
528
+ const binaryPass = jury.verdict === 'PASS';
529
+ const binaryScore = binaryPass ? 1 : 0;
530
+ const passVoteRatio = round4((jury.total_votes - jury.fail_votes) / jury.total_votes);
531
+ const agreementRatio = round4((jury.total_votes - jury.dissenting_providers.length) / jury.total_votes);
532
+ const metrics = [
533
+ [`${prefix}.binary_pass`, binaryPass],
534
+ [`${prefix}.binary_score`, binaryScore],
535
+ [`${prefix}.poll_pass_vote_ratio`, passVoteRatio],
536
+ [`${prefix}.poll_agreement_ratio`, agreementRatio],
537
+ ];
538
+ const observations = [];
539
+ for (const [metricId, value] of metrics) {
540
+ observations.push({
541
+ metric_id: metricId,
542
+ scope: 'run',
543
+ value,
544
+ });
545
+ if (nodeId) {
546
+ observations.push({
547
+ metric_id: metricId,
548
+ scope: 'node',
549
+ node_id: nodeId,
550
+ value,
551
+ });
552
+ }
553
+ }
554
+ return deepFreeze(observations);
555
+ }
@@ -1,5 +1,5 @@
1
1
  export interface JudgmentProjectBindingCandidates {
2
- /** The Host runtime of the turn (`codex` or `claude-code`). */
2
+ /** The Host runtime of the turn (`codex`, `claude-code`, or `antigravity`). */
3
3
  hostRuntime: string;
4
4
  /** BRAINBASE_JUDGMENT_PROJECT_CODE as the Host received it. */
5
5
  configuredProjectCode?: string | null;
@@ -21,8 +21,9 @@ function present(value) {
21
21
  */
22
22
  export function selectJudgmentProjectBinding(candidates) {
23
23
  const configured = present(candidates.configuredProjectCode);
24
- if (candidates.hostRuntime === 'claude-code' && configured)
24
+ if ((candidates.hostRuntime === 'claude-code' || candidates.hostRuntime === 'antigravity') && configured) {
25
25
  return configured;
26
+ }
26
27
  return present(candidates.relayProjectCode)
27
28
  ?? configured
28
29
  ?? present(candidates.ownerRepositoryProjectCode)