@unson/brainbase-mcp 0.50.28 → 0.50.30

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 (39) 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/mcp-tool-schema-portability.d.ts +54 -0
  35. package/dist/mcp-tool-schema-portability.js +1013 -0
  36. package/dist/organization-graph.js +9 -1
  37. package/dist/remote-judgment-hook-http.d.ts +36 -3
  38. package/dist/remote-judgment-hook-http.js +94 -15
  39. package/package.json +14 -2
@@ -0,0 +1,623 @@
1
+ import { JUDGMENT_FRAME_ROLE_BY_KIND, validateJudgmentFrameRecord, } from './judgment-frame.js';
2
+ import { isAnecdotalRefutation, summarizeJudgmentModelOutcomes, } from './judgment-model-outcome.js';
3
+ import { buildOfflineGradedDistortionJudgePrompt, toJudgmentDAGBinaryAuditObservations, } from './judgment-offline-binary-audit.js';
4
+ /**
5
+ * Deterministic structural audit and shared rubric for the five canonical
6
+ * reasoning-distortion patterns.
7
+ *
8
+ * Design boundary:
9
+ * - This module evaluates ONLY structural fields (escalations, claim scopes,
10
+ * representativeness, population/support/counter balance fields, retrieval
11
+ * counts/coverage, option/catalog structure, verify node evidence IDs, and
12
+ * world-model refutation/learning-candidate links).
13
+ * - It deliberately avoids free-text regex heuristics. Semantic assessment of
14
+ * free-text reasoning belongs to offline LLM-as-a-Judge evaluation using the
15
+ * co-exported `JUDGMENT_REASONING_DISTORTION_RUBRIC_V1` vocabulary.
16
+ * - Side-effect free: never mutates inputs or performs I/O.
17
+ */
18
+ export const JUDGMENT_REASONING_AUDIT_SCHEMA_VERSION = 'judgment-reasoning-audit.v1';
19
+ export const JUDGMENT_REASONING_DISTORTION_RUBRIC_VERSION = 'judgment-reasoning-distortion-rubric.v1';
20
+ export const JUDGMENT_REASONING_DISTORTION_PATTERNS = [
21
+ 'counterexample_scope_mismatch',
22
+ 'base_rate_neglect',
23
+ 'layer_conflation',
24
+ 'conclusion_lock_cherry_picking',
25
+ 'local_patch_without_model_update',
26
+ ];
27
+ function deepFreeze(value) {
28
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
29
+ Object.freeze(value);
30
+ for (const child of Object.values(value)) {
31
+ deepFreeze(child);
32
+ }
33
+ }
34
+ return value;
35
+ }
36
+ export const JUDGMENT_REASONING_DISTORTION_RUBRIC_V1 = deepFreeze({
37
+ counterexample_scope_mismatch: {
38
+ pattern: 'counterexample_scope_mismatch',
39
+ title: '反証の射程ミス(Counterexample Scope Mismatch)',
40
+ definition: '傾向・確率的な主張(claim_scope: probabilistic)を単発・逸話的な反例(counter_representativeness: anecdotal)だけで全面否定したり、逆に全称主張(universal)の反証範囲を取り違える推論歪み。',
41
+ pass_criteria: '主張の射程(universal / probabilistic / bounded_case)と反証証拠の代表性(census / representative / anecdotal)が整合している。傾向主張を failed とする場合は census または representative な反証に基づく。',
42
+ warn_criteria: '傾向主張を failed と判定しているが、反証の代表性が unknown または未指定(かつ履歴上は逸話反証のみ)で射程の妥当性を構造的に確定できない。',
43
+ fail_criteria: 'prediction_scope_mismatch エスカレーションが発火している、または claim_scope === "probabilistic" の予測チェックを counter_representativeness === "anecdotal" のまま status === "failed" と判定している。',
44
+ positive_anchor: '全12施設×30日の集計(representative)で傾向が逆転したことを確認して probabilistic 予測を failed とする、または universal 予測を単発の確証反例(anecdotal)で棄却する。',
45
+ negative_anchor: '全体では改善傾向にある probabilistic 予測を、1施設の特例日(counter_representativeness: anecdotal)だけを根拠に status: failed として棄却する。',
46
+ },
47
+ base_rate_neglect: {
48
+ pattern: 'base_rate_neglect',
49
+ title: '全体傾向・母集団の無視(Base Rate Neglect)',
50
+ definition: '母集団(population)や支持・反証の双方の要約(supporting_summary / counter_summary)を確認せず、局所的・部分的な検索結果や偏った事例だけで結論を下す推論歪み。',
51
+ pass_criteria: '予測チェックに balance(population / supporting_summary / counter_summary)が欠落なく記載されており、部分検索(coverage: partial や returnedCount < totalScopedCount)がある場合でも母集団の分母が明示されている。',
52
+ warn_criteria: '部分検索の兆候はないが、採用案の検証済み予測チェック(held / failed)に balance 自体が省略されており、母集団と支持・反証の対比が明示されていない。',
53
+ fail_criteria: 'prediction_unbalanced_evidence が発火している、balance 付き予測で population / supporting_summary / counter_summary が欠落・空白である、または retrieval が部分取得(coverage: partial または returnedCount < totalScopedCount)であるのに balance.population が未記載である。',
54
+ positive_anchor: 'retrieval が 5/50 件の partial 取得であることを踏まえ、balance.population に全50件の母集団と抽出範囲を明記し、支持例と反例を両方要約したうえで判断する。',
55
+ negative_anchor: '上位5件しか返らない部分検索結果のみを根拠に balance.population を記載せず判断する、あるいは counter_summary を空のまま予測成立(held)とする。',
56
+ },
57
+ layer_conflation: {
58
+ pattern: 'layer_conflation',
59
+ title: '事実・因果・価値(制約)の混同(Layer Conflation)',
60
+ definition: '哲学(constraint)・目的(criterion)・世界モデル(prediction)の役割境界を混同したり、未検証の因果仮説(draft / adopted_unverified)を反証条件の検証なしに既定の事実として扱う推論歪み。',
61
+ pass_criteria: 'philosophy は constraint(verdict 必須・check なし)、objective は criterion(check/verdict なし)、model は prediction(falsified_if を持つ check で検証)として層が分離され、採用案が依存する未検証モデルはすべて検証済み(held)である。',
62
+ warn_criteria: '層・ロールの混同はないが、採用案が依存する verified モデルについて当ケースでの予測チェックが unchecked(または未記載)のまま残っている。',
63
+ fail_criteria: '採用案が draft / adopted_unverified の未検証モデルを unchecked(または check なし)のまま依存している、予測チェックの falsified_if が欠落している、またはカタログ種別とロール・verdict・check の対応が構造的に混同されている。',
64
+ positive_anchor: 'adopted_unverified のモデルを prediction として明示的に falsified_if と実測データで検証(status: held)したうえで採用し、philosophy は constraint + verdict として独立に評価する。',
65
+ negative_anchor: 'adopted_unverified の因果モデルを check.status: unchecked のまま採用案の根拠にする、またはモデルを constraint として扱ったり falsified_if を空にする。',
66
+ },
67
+ conclusion_lock_cherry_picking: {
68
+ pattern: 'conclusion_lock_cherry_picking',
69
+ title: '結論先固定・チェリーピッキング(Conclusion Lock & Cherry-Picking)',
70
+ definition: '単一案のみを並べて代替案比較を行わない、同スコープの競合モデルや現行版で構造的反証済みのモデルを無視して都合のよい根拠だけを集める、あるいは検証ノード(node_id を区切り文字で分割したトークンに verify を含むノード)に実行証跡を伴わせない推論歪み。',
71
+ pass_criteria: '2案以上の選択肢(options.length >= 2)を比較し、モデル使用時に同スコープの他モデルまたは現行版の構造的反証済みモデルが存在する場合は competing_hypotheses または counter_summary で明示的に対比し、verify ノード(例: verify, judgment.verify)には業務ツールの証跡(evidence_tool_use_ids)が紐づいている。',
72
+ warn_criteria: '結論先固定の直接違反はないが、verify ノード(node_id の区切りトークンに verify を含むノード)が insufficient かつ evidence_tool_use_ids が空のまま残っている。',
73
+ fail_criteria: 'options.length <= 1(代替案比較なし)、モデル使用時にカタログ内に同スコープの他モデルまたは現行版の構造的反証済みモデルがあるのに competing_hypotheses が空かつ counter_summary も空・未記載、または nodeResults の verify ノード(区切り文字で分割したトークンに verify を含む node_id)が証跡(evidence_tool_use_ids)なしで supported となっている。',
74
+ positive_anchor: '2案以上を同一基準で比較し、同スコープの競合モデルを competing_hypotheses で比較したうえで、verify ノードに実測クエリの tool_use_id を紐づける。',
75
+ negative_anchor: '採用したい1案だけを options に並べる、カタログ内の競合モデルを無視して counter_summary も空にする、または verify ノードを evidence_tool_use_ids: [] のまま supported と記録する。',
76
+ },
77
+ local_patch_without_model_update: {
78
+ pattern: 'local_patch_without_model_update',
79
+ title: '局所訂正のみで世界モデル未更新(Local Patch Without Model Update)',
80
+ definition: '反証済みモデルや失敗した予測に依存したまま結論を通す、あるいは構造的反証が蓄積しているのに世界モデルの改訂候補(LearningCandidate)や反証IDの紐づけ(addressedRefutationIds)を行わず場当たり的に済ませる推論歪み。',
81
+ pass_criteria: '採用案が反証済みモデルや failed 予測に依存しておらず、使用モデルに構造的反証が2件以上蓄積している場合は該当モデルに対する LearningCandidate が存在し、記録済み構造的反証IDを addressedRefutationIds で漏れなく参照している。',
82
+ warn_criteria: '反証蓄積モデルに対して LearningCandidate と非空の addressedRefutationIds が提示されているが、現行版の構造的反証IDの一部が addressedRefutationIds に含まれていない。',
83
+ fail_criteria: 'chosen_uses_refuted_model または chosen_relies_on_failed_prediction が発火している、使用モデルに構造的反証が2件以上蓄積しているのに該当モデルへの LearningCandidate が0件である、または世界モデルの LearningCandidate で addressedRefutationIds が空のまま改訂提案している。',
84
+ positive_anchor: '構造的反証が2件蓄積したモデルAへの依存を避けてモデルBの案を採用しつつ、モデルAに対する LearningCandidate を addressedRefutationIds に両反証IDを紐づけて起票する。',
85
+ negative_anchor: '構造的反証が2件以上あるモデルを使い続ける、あるいは別案へ切り替えてもモデル改訂候補を0件のまま放置する、または addressedRefutationIds を空配列で提出する。',
86
+ },
87
+ });
88
+ const VALID_CONSTRAINT_VERDICTS = new Set(['satisfied', 'violated', 'tension']);
89
+ function hasText(value) {
90
+ return typeof value === 'string' && value.trim().length > 0;
91
+ }
92
+ function normalizedScopeKey(appliesWhen) {
93
+ return typeof appliesWhen === 'string' ? appliesWhen.trim() : '';
94
+ }
95
+ /**
96
+ * Structural verify-node matcher: splits `node_id` on delimiter characters
97
+ * (`-`, `.`, `_`, `/`, `:`, whitespace) and returns true when one of the
98
+ * lowercase tokens is `"verify"` (e.g., `"verify"`, `"judgment.verify"`,
99
+ * `"hypothesis-verify"`).
100
+ */
101
+ function isVerifyNodeId(nodeId) {
102
+ const normalized = nodeId.trim().toLowerCase();
103
+ if (!normalized)
104
+ return false;
105
+ return normalized.split(/[-._/:\s]+/u).includes('verify');
106
+ }
107
+ function isPartialRetrievalSample(sample) {
108
+ if (sample.coverage === 'partial')
109
+ return true;
110
+ if (typeof sample.returnedCount === 'number' && typeof sample.totalScopedCount === 'number') {
111
+ return sample.returnedCount < sample.totalScopedCount;
112
+ }
113
+ return false;
114
+ }
115
+ function structuralRefutationCount(summary) {
116
+ if (!summary)
117
+ return 0;
118
+ return summary.structural_refutes ?? summary.refutes;
119
+ }
120
+ function uniqueStrings(values) {
121
+ const seen = new Set();
122
+ const result = [];
123
+ for (const value of values) {
124
+ if (!seen.has(value)) {
125
+ seen.add(value);
126
+ result.push(value);
127
+ }
128
+ }
129
+ return result;
130
+ }
131
+ function createAccumulator() {
132
+ return { failSignals: [], warnSignals: [], evidencePaths: [] };
133
+ }
134
+ function addFail(acc, signal, paths = []) {
135
+ acc.failSignals.push(signal);
136
+ acc.evidencePaths.push(...paths);
137
+ }
138
+ function addWarn(acc, signal, paths = []) {
139
+ acc.warnSignals.push(signal);
140
+ acc.evidencePaths.push(...paths);
141
+ }
142
+ function finalizePattern(pattern, applicable, acc) {
143
+ const hasFail = acc.failSignals.length > 0;
144
+ const hasWarn = acc.warnSignals.length > 0;
145
+ if (!applicable && !hasFail && !hasWarn) {
146
+ return {
147
+ pattern,
148
+ status: 'not_applicable',
149
+ score: 1,
150
+ signals: [],
151
+ evidence_paths: [],
152
+ };
153
+ }
154
+ if (hasFail) {
155
+ return {
156
+ pattern,
157
+ status: 'fail',
158
+ score: 0,
159
+ signals: uniqueStrings([...acc.failSignals, ...acc.warnSignals]),
160
+ evidence_paths: uniqueStrings(acc.evidencePaths),
161
+ };
162
+ }
163
+ if (hasWarn) {
164
+ return {
165
+ pattern,
166
+ status: 'warn',
167
+ score: 0.5,
168
+ signals: uniqueStrings(acc.warnSignals),
169
+ evidence_paths: uniqueStrings(acc.evidencePaths),
170
+ };
171
+ }
172
+ return {
173
+ pattern,
174
+ status: 'pass',
175
+ score: 1,
176
+ signals: [],
177
+ evidence_paths: [],
178
+ };
179
+ }
180
+ function hasBalancePopulated(balance) {
181
+ return Boolean(balance && hasText(balance.population));
182
+ }
183
+ function hasCompetingHypotheses(balance) {
184
+ return Array.isArray(balance?.competing_hypotheses) && balance.competing_hypotheses.length > 0;
185
+ }
186
+ function hasCounterSummary(balance) {
187
+ return Boolean(balance && hasText(balance.counter_summary));
188
+ }
189
+ /**
190
+ * Audit a judgment frame and its optional surrounding evidence (model outcomes,
191
+ * node results, retrieval samples, and learning candidates) against the five
192
+ * canonical reasoning-distortion patterns using purely structural checks.
193
+ */
194
+ export function auditJudgmentReasoning(input) {
195
+ const frame = input.frame;
196
+ const catalog = input.catalog;
197
+ const outcomes = input.outcomes ?? [];
198
+ const nodeResults = input.nodeResults ?? [];
199
+ const retrieval = input.retrieval ?? [];
200
+ const learningCandidates = input.learningCandidates ?? [];
201
+ const outcomeSummaries = summarizeJudgmentModelOutcomes(outcomes, catalog);
202
+ const validation = validateJudgmentFrameRecord(frame, catalog, outcomeSummaries);
203
+ const escalationRefsByCode = new Map();
204
+ for (const escalation of validation.escalations) {
205
+ escalationRefsByCode.set(escalation.code, escalation.refs);
206
+ }
207
+ const hasEscalation = (code) => escalationRefsByCode.has(code);
208
+ const catalogItems = Array.isArray(catalog.items) ? catalog.items : [];
209
+ const catalogById = new Map();
210
+ const catalogIndexById = new Map();
211
+ catalogItems.forEach((item, index) => {
212
+ catalogById.set(item.id, item);
213
+ catalogIndexById.set(item.id, index);
214
+ });
215
+ const options = Array.isArray(frame.options) ? frame.options : [];
216
+ const chosenOptionIndex = options.findIndex((option) => option.label === frame.chosen_option);
217
+ const allUses = [];
218
+ options.forEach((option, optionIndex) => {
219
+ const uses = Array.isArray(option.uses) ? option.uses : [];
220
+ const isChosen = optionIndex === chosenOptionIndex;
221
+ uses.forEach((use, useIndex) => {
222
+ allUses.push({
223
+ optionIndex,
224
+ useIndex,
225
+ option,
226
+ use,
227
+ path: `options[${optionIndex}].uses[${useIndex}]`,
228
+ isChosen,
229
+ });
230
+ });
231
+ });
232
+ const predictionUses = allUses.filter((entry) => entry.use.role === 'prediction');
233
+ const chosenPredictionUses = predictionUses.filter((entry) => entry.isChosen);
234
+ const modelCatalogItems = catalogItems.filter((item) => item.kind === 'model');
235
+ const currentModelRevisionById = new Map(modelCatalogItems.map((item) => [item.id, item.revision]));
236
+ // Map model id -> current-revision structural refutation outcomes with original index
237
+ const structuralRefutationOutcomesByModel = new Map();
238
+ outcomes.forEach((record, index) => {
239
+ if (record.verdict !== 'refutes')
240
+ return;
241
+ if (currentModelRevisionById.get(record.model.id) !== record.model.revision)
242
+ return;
243
+ if (isAnecdotalRefutation(record))
244
+ return;
245
+ const list = structuralRefutationOutcomesByModel.get(record.model.id) ?? [];
246
+ list.push({ index, record });
247
+ structuralRefutationOutcomesByModel.set(record.model.id, list);
248
+ });
249
+ // -------------------------------------------------------------------------
250
+ // 1. counterexample_scope_mismatch
251
+ // -------------------------------------------------------------------------
252
+ const scopeAcc = createAccumulator();
253
+ if (hasEscalation('prediction_scope_mismatch')) {
254
+ const refs = new Set(escalationRefsByCode.get('prediction_scope_mismatch') ?? []);
255
+ const matchingPaths = predictionUses
256
+ .filter((entry) => refs.has(entry.use.ref) && entry.use.check?.balance)
257
+ .map((entry) => `${entry.path}.check.balance`);
258
+ addFail(scopeAcc, 'escalation:prediction_scope_mismatch', matchingPaths);
259
+ }
260
+ for (const entry of predictionUses) {
261
+ const check = entry.use.check;
262
+ const balance = check?.balance;
263
+ if (!check || check.status !== 'failed' || !balance)
264
+ continue;
265
+ if (balance.claim_scope === 'probabilistic') {
266
+ if (balance.counter_representativeness === 'anecdotal') {
267
+ addFail(scopeAcc, 'probabilistic_failed_by_anecdotal', [`${entry.path}.check.balance`]);
268
+ }
269
+ else if (balance.counter_representativeness === 'unknown') {
270
+ addWarn(scopeAcc, 'probabilistic_failed_with_unknown_representativeness', [`${entry.path}.check.balance`]);
271
+ }
272
+ else if (balance.counter_representativeness === undefined) {
273
+ const summary = outcomeSummaries.get(entry.use.ref);
274
+ if (summary && (summary.anecdotal_refutes ?? 0) > 0 && structuralRefutationCount(summary) === 0) {
275
+ addWarn(scopeAcc, 'probabilistic_failed_on_anecdotal_only_outcomes', [`${entry.path}.check.balance`]);
276
+ }
277
+ }
278
+ }
279
+ }
280
+ const scopeApplicable = predictionUses.length > 0
281
+ || outcomes.some((record) => record.verdict === 'refutes')
282
+ || hasEscalation('prediction_scope_mismatch');
283
+ const scopeResult = finalizePattern('counterexample_scope_mismatch', scopeApplicable, scopeAcc);
284
+ // -------------------------------------------------------------------------
285
+ // 2. base_rate_neglect
286
+ // -------------------------------------------------------------------------
287
+ const baseRateAcc = createAccumulator();
288
+ if (hasEscalation('prediction_unbalanced_evidence')) {
289
+ const refs = new Set(escalationRefsByCode.get('prediction_unbalanced_evidence') ?? []);
290
+ const matchingPaths = predictionUses
291
+ .filter((entry) => refs.has(entry.use.ref) && entry.use.check?.balance)
292
+ .map((entry) => `${entry.path}.check.balance`);
293
+ addFail(baseRateAcc, 'escalation:prediction_unbalanced_evidence', matchingPaths);
294
+ }
295
+ for (const entry of predictionUses) {
296
+ const check = entry.use.check;
297
+ const balance = check?.balance;
298
+ if (!check || !balance)
299
+ continue;
300
+ if (!hasText(balance.population)) {
301
+ addFail(baseRateAcc, 'balance_missing_population', [`${entry.path}.check.balance.population`]);
302
+ }
303
+ if (!hasText(balance.counter_summary)) {
304
+ addFail(baseRateAcc, 'balance_missing_counter_summary', [`${entry.path}.check.balance.counter_summary`]);
305
+ }
306
+ if (!hasText(balance.supporting_summary)) {
307
+ if (check.status === 'failed' && balance.claim_scope === 'universal') {
308
+ addWarn(baseRateAcc, 'balance_missing_supporting_summary', [`${entry.path}.check.balance.supporting_summary`]);
309
+ }
310
+ else {
311
+ addFail(baseRateAcc, 'balance_missing_supporting_summary', [`${entry.path}.check.balance.supporting_summary`]);
312
+ }
313
+ }
314
+ }
315
+ const partialRetrievalPaths = [];
316
+ retrieval.forEach((sample, index) => {
317
+ if (isPartialRetrievalSample(sample)) {
318
+ partialRetrievalPaths.push(`retrieval[${index}]`);
319
+ }
320
+ });
321
+ if (partialRetrievalPaths.length > 0) {
322
+ const anyPredictionHasPopulation = predictionUses.some((entry) => hasBalancePopulated(entry.use.check?.balance));
323
+ const chosenMissingPopulation = chosenPredictionUses.filter((entry) => !hasBalancePopulated(entry.use.check?.balance));
324
+ if (!anyPredictionHasPopulation || chosenMissingPopulation.length > 0) {
325
+ addFail(baseRateAcc, 'partial_retrieval_missing_population', [
326
+ ...partialRetrievalPaths,
327
+ ...chosenMissingPopulation.map((entry) => entry.use.check ? `${entry.path}.check` : entry.path),
328
+ ]);
329
+ }
330
+ }
331
+ else {
332
+ // When retrieval is not partial (or omitted), warn if a checked prediction on the chosen option omits balance entirely.
333
+ for (const entry of chosenPredictionUses) {
334
+ const check = entry.use.check;
335
+ if (check && (check.status === 'held' || check.status === 'failed') && check.balance === undefined) {
336
+ addWarn(baseRateAcc, 'prediction_check_missing_balance', [`${entry.path}.check`]);
337
+ }
338
+ }
339
+ }
340
+ const baseRateApplicable = predictionUses.length > 0
341
+ || retrieval.length > 0
342
+ || hasEscalation('prediction_unbalanced_evidence');
343
+ const baseRateResult = finalizePattern('base_rate_neglect', baseRateApplicable, baseRateAcc);
344
+ // -------------------------------------------------------------------------
345
+ // 3. layer_conflation
346
+ // -------------------------------------------------------------------------
347
+ const layerAcc = createAccumulator();
348
+ for (const issue of validation.issues) {
349
+ if (issue.code === 'frame_role_mismatch') {
350
+ addFail(layerAcc, 'role_kind_conflation', [issue.path]);
351
+ }
352
+ else if (issue.code === 'frame_verdict_missing') {
353
+ addFail(layerAcc, 'constraint_verdict_conflation', [issue.path]);
354
+ }
355
+ }
356
+ for (const entry of allUses) {
357
+ const catalogItem = catalogById.get(entry.use.ref);
358
+ if (catalogItem && entry.use.role !== JUDGMENT_FRAME_ROLE_BY_KIND[catalogItem.kind]) {
359
+ addFail(layerAcc, 'role_kind_conflation', [`${entry.path}.role`]);
360
+ }
361
+ if (entry.use.role !== 'prediction' && entry.use.check !== undefined) {
362
+ addFail(layerAcc, 'check_on_non_prediction_role', [`${entry.path}.check`]);
363
+ }
364
+ if (entry.use.role === 'constraint') {
365
+ if (!VALID_CONSTRAINT_VERDICTS.has(String(entry.use.verdict ?? ''))) {
366
+ addFail(layerAcc, 'constraint_verdict_conflation', [`${entry.path}.verdict`]);
367
+ }
368
+ }
369
+ else if (entry.use.verdict !== undefined) {
370
+ addFail(layerAcc, 'constraint_verdict_conflation', [`${entry.path}.verdict`]);
371
+ }
372
+ if (entry.use.role === 'prediction' && entry.use.check !== undefined && !hasText(entry.use.check.falsified_if)) {
373
+ addFail(layerAcc, 'prediction_check_missing_falsified_if', [`${entry.path}.check.falsified_if`]);
374
+ }
375
+ if (entry.isChosen && entry.use.role === 'prediction' && catalogItem?.kind === 'model') {
376
+ const checkStatus = entry.use.check?.status ?? 'unchecked';
377
+ if (checkStatus === 'unchecked') {
378
+ const evidencePath = entry.use.check ? `${entry.path}.check` : entry.path;
379
+ if (catalogItem.status !== 'verified') {
380
+ addFail(layerAcc, 'chosen_unverified_model_unchecked', [evidencePath]);
381
+ }
382
+ else {
383
+ addWarn(layerAcc, 'chosen_verified_model_unchecked', [evidencePath]);
384
+ }
385
+ }
386
+ }
387
+ }
388
+ const layerApplicable = allUses.length > 0 || validation.issues.length > 0;
389
+ const layerResult = finalizePattern('layer_conflation', layerApplicable, layerAcc);
390
+ // -------------------------------------------------------------------------
391
+ // 4. conclusion_lock_cherry_picking
392
+ // -------------------------------------------------------------------------
393
+ const lockAcc = createAccumulator();
394
+ if (options.length <= 1) {
395
+ addFail(lockAcc, 'single_option_no_alternative', ['options']);
396
+ }
397
+ const usedModelIds = new Set(predictionUses
398
+ .map((entry) => entry.use.ref)
399
+ .filter((ref) => catalogById.get(ref)?.kind === 'model'));
400
+ // Only check competing / structurally-refuted catalog models when the frame
401
+ // actually uses at least one model; a philosophy/objective-only frame must
402
+ // not treat unrelated catalog models as unaddressed competitors.
403
+ const competingOrRefutedCatalogPaths = [];
404
+ if (usedModelIds.size > 0) {
405
+ const usedModelScopes = new Set([...usedModelIds].map((id) => normalizedScopeKey(catalogById.get(id)?.applies_when)));
406
+ for (const modelItem of modelCatalogItems) {
407
+ const idx = catalogIndexById.get(modelItem.id);
408
+ const itemPath = idx === undefined ? `catalog.items` : `catalog.items[${idx}]`;
409
+ const isOtherSameScope = !usedModelIds.has(modelItem.id)
410
+ && usedModelScopes.has(normalizedScopeKey(modelItem.applies_when));
411
+ const summary = outcomeSummaries.get(modelItem.id);
412
+ const isRefuted = structuralRefutationCount(summary) > 0;
413
+ if (isOtherSameScope || isRefuted) {
414
+ competingOrRefutedCatalogPaths.push(itemPath);
415
+ }
416
+ }
417
+ }
418
+ if (competingOrRefutedCatalogPaths.length > 0) {
419
+ const anyCompeting = predictionUses.some((entry) => hasCompetingHypotheses(entry.use.check?.balance));
420
+ const anyCounter = predictionUses.some((entry) => hasCounterSummary(entry.use.check?.balance));
421
+ if (!anyCompeting && !anyCounter) {
422
+ const targetUsePaths = chosenPredictionUses.length > 0
423
+ ? chosenPredictionUses.map((entry) => entry.use.check?.balance ? `${entry.path}.check.balance` : entry.path)
424
+ : predictionUses.map((entry) => entry.use.check?.balance ? `${entry.path}.check.balance` : entry.path);
425
+ addFail(lockAcc, 'unaddressed_competing_or_refuted_models', [
426
+ ...competingOrRefutedCatalogPaths,
427
+ ...targetUsePaths,
428
+ ]);
429
+ }
430
+ }
431
+ nodeResults.forEach((result, index) => {
432
+ if (!isVerifyNodeId(result.node_id))
433
+ return;
434
+ const evidenceIds = Array.isArray(result.evidence_tool_use_ids)
435
+ ? result.evidence_tool_use_ids.filter((id) => hasText(id))
436
+ : [];
437
+ if (evidenceIds.length === 0) {
438
+ const path = `nodeResults[${index}].evidence_tool_use_ids`;
439
+ if (result.status === 'supported') {
440
+ addFail(lockAcc, 'verify_node_without_evidence', [path]);
441
+ }
442
+ else {
443
+ addWarn(lockAcc, 'verify_node_insufficient_without_evidence', [path]);
444
+ }
445
+ }
446
+ });
447
+ const lockResult = finalizePattern('conclusion_lock_cherry_picking', true, lockAcc);
448
+ // -------------------------------------------------------------------------
449
+ // 5. local_patch_without_model_update
450
+ // -------------------------------------------------------------------------
451
+ const patchAcc = createAccumulator();
452
+ if (hasEscalation('chosen_uses_refuted_model')) {
453
+ const refs = new Set(escalationRefsByCode.get('chosen_uses_refuted_model') ?? []);
454
+ const paths = chosenPredictionUses
455
+ .filter((entry) => refs.has(entry.use.ref))
456
+ .map((entry) => entry.path);
457
+ addFail(patchAcc, 'escalation:chosen_uses_refuted_model', paths);
458
+ }
459
+ if (hasEscalation('chosen_relies_on_failed_prediction')) {
460
+ const refs = new Set(escalationRefsByCode.get('chosen_relies_on_failed_prediction') ?? []);
461
+ const paths = chosenPredictionUses
462
+ .filter((entry) => refs.has(entry.use.ref) && entry.use.check?.status === 'failed')
463
+ .map((entry) => `${entry.path}.check`);
464
+ addFail(patchAcc, 'escalation:chosen_relies_on_failed_prediction', paths);
465
+ }
466
+ const worldModelCandidatesByModelId = new Map();
467
+ learningCandidates.forEach((candidate, index) => {
468
+ if (candidate.target?.kind !== 'world_model')
469
+ return;
470
+ const list = worldModelCandidatesByModelId.get(candidate.target.id) ?? [];
471
+ list.push({ index, candidate });
472
+ worldModelCandidatesByModelId.set(candidate.target.id, list);
473
+ });
474
+ for (const modelId of usedModelIds) {
475
+ const structuralCount = structuralRefutationCount(outcomeSummaries.get(modelId));
476
+ if (structuralCount < 2)
477
+ continue;
478
+ const matchingCandidates = worldModelCandidatesByModelId.get(modelId) ?? [];
479
+ if (matchingCandidates.length === 0) {
480
+ const outcomePaths = (structuralRefutationOutcomesByModel.get(modelId) ?? [])
481
+ .map((entry) => `outcomes[${entry.index}]`);
482
+ const usePaths = predictionUses
483
+ .filter((entry) => entry.use.ref === modelId)
484
+ .map((entry) => entry.path);
485
+ addFail(patchAcc, 'accumulated_structural_refutations_without_learning_candidate', [
486
+ ...outcomePaths,
487
+ ...usePaths,
488
+ ]);
489
+ }
490
+ }
491
+ learningCandidates.forEach((candidate, index) => {
492
+ if (candidate.target?.kind !== 'world_model')
493
+ return;
494
+ const targetId = candidate.target.id;
495
+ const structuralOutcomes = structuralRefutationOutcomesByModel.get(targetId) ?? [];
496
+ const structuralCount = structuralRefutationCount(outcomeSummaries.get(targetId));
497
+ const hasExplicitField = candidate.addressedRefutationIds !== undefined;
498
+ const addressedIds = Array.isArray(candidate.addressedRefutationIds)
499
+ ? candidate.addressedRefutationIds.filter((id) => hasText(id))
500
+ : [];
501
+ if ((hasExplicitField && addressedIds.length === 0) || (structuralCount > 0 && addressedIds.length === 0)) {
502
+ const path = hasExplicitField
503
+ ? `learningCandidates[${index}].addressedRefutationIds`
504
+ : `learningCandidates[${index}]`;
505
+ addFail(patchAcc, 'learning_candidate_empty_addressed_refutation_ids', [path]);
506
+ return;
507
+ }
508
+ if (structuralOutcomes.length > 0 && addressedIds.length > 0) {
509
+ const addressedSet = new Set(addressedIds);
510
+ const missingOutcomePaths = structuralOutcomes
511
+ .filter((entry) => !addressedSet.has(entry.record.id))
512
+ .map((entry) => `outcomes[${entry.index}]`);
513
+ if (missingOutcomePaths.length > 0) {
514
+ addWarn(patchAcc, 'learning_candidate_partial_refutation_coverage', [
515
+ `learningCandidates[${index}].addressedRefutationIds`,
516
+ ...missingOutcomePaths,
517
+ ]);
518
+ }
519
+ }
520
+ });
521
+ const patchApplicable = usedModelIds.size > 0
522
+ || outcomes.length > 0
523
+ || learningCandidates.length > 0
524
+ || hasEscalation('chosen_uses_refuted_model')
525
+ || hasEscalation('chosen_relies_on_failed_prediction');
526
+ const patchResult = finalizePattern('local_patch_without_model_update', patchApplicable, patchAcc);
527
+ // -------------------------------------------------------------------------
528
+ // Aggregate overall status and score
529
+ // -------------------------------------------------------------------------
530
+ const patterns = {
531
+ counterexample_scope_mismatch: scopeResult,
532
+ base_rate_neglect: baseRateResult,
533
+ layer_conflation: layerResult,
534
+ conclusion_lock_cherry_picking: lockResult,
535
+ local_patch_without_model_update: patchResult,
536
+ };
537
+ const results = JUDGMENT_REASONING_DISTORTION_PATTERNS.map((pattern) => patterns[pattern]);
538
+ const overall_status = results.some((r) => r.status === 'fail')
539
+ ? 'fail'
540
+ : results.some((r) => r.status === 'warn')
541
+ ? 'warn'
542
+ : 'pass';
543
+ const applicableResults = results.filter((r) => r.status !== 'not_applicable');
544
+ const rawScore = applicableResults.length === 0
545
+ ? 1
546
+ : applicableResults.reduce((sum, r) => sum + r.score, 0) / applicableResults.length;
547
+ const overall_score = Math.round(rawScore * 10_000) / 10_000;
548
+ return deepFreeze({
549
+ schema_version: JUDGMENT_REASONING_AUDIT_SCHEMA_VERSION,
550
+ overall_status,
551
+ overall_score,
552
+ patterns,
553
+ });
554
+ }
555
+ /**
556
+ * Convert a `JudgmentReasoningAuditResult` into `JudgmentDAGOutcomeObservation[]`
557
+ * consumable directly by `createJudgmentDAGOutcomeAttachment` and
558
+ * `evaluateJudgmentDAGVersions` in `src/judgment-dag-replay-evaluation.ts`.
559
+ *
560
+ * Emits 5 per-pattern numeric scores (`distortion.<pattern>`, range 0..1) and
561
+ * 1 overall boolean pass indicator (`distortion.overall_pass`) at run scope.
562
+ * When `options.nodeId` or `options.patternNodeIds` is provided, matching
563
+ * node-scoped observations are appended to enable `node_calibration`.
564
+ */
565
+ export function toJudgmentDAGDistortionObservations(audit, options = {}) {
566
+ const observations = [];
567
+ for (const pattern of JUDGMENT_REASONING_DISTORTION_PATTERNS) {
568
+ const score = audit.patterns[pattern].score;
569
+ const metricId = `distortion.${pattern}`;
570
+ observations.push({
571
+ metric_id: metricId,
572
+ scope: 'run',
573
+ value: score,
574
+ });
575
+ const patternNodeId = options.patternNodeIds?.[pattern] ?? options.nodeId;
576
+ if (hasText(patternNodeId)) {
577
+ observations.push({
578
+ metric_id: metricId,
579
+ scope: 'node',
580
+ node_id: patternNodeId.trim(),
581
+ value: score,
582
+ });
583
+ }
584
+ }
585
+ const overallPass = audit.overall_status === 'pass';
586
+ observations.push({
587
+ metric_id: 'distortion.overall_pass',
588
+ scope: 'run',
589
+ value: overallPass,
590
+ });
591
+ if (hasText(options.nodeId)) {
592
+ observations.push({
593
+ metric_id: 'distortion.overall_pass',
594
+ scope: 'node',
595
+ node_id: options.nodeId.trim(),
596
+ value: overallPass,
597
+ });
598
+ }
599
+ return deepFreeze(observations);
600
+ }
601
+ /**
602
+ * Convenience wrapper building a graded LLM-as-a-Judge prompt using the canonical
603
+ * `JUDGMENT_REASONING_DISTORTION_RUBRIC_V1` with explicit higher-is-better score polarity
604
+ * (`1 = pass / 歪みなし, 0.5 = warn, 0 = fail / 歪みあり`).
605
+ */
606
+ export function buildJudgmentReasoningGradedJudgePrompt(input) {
607
+ return buildOfflineGradedDistortionJudgePrompt({
608
+ ...input,
609
+ rubricEntries: JUDGMENT_REASONING_DISTORTION_RUBRIC_V1,
610
+ });
611
+ }
612
+ /**
613
+ * Combine deterministic structural distortion observations and offline 7-item PoLL
614
+ * binary audit observations into a single immutable observation array for Replay Eval
615
+ * (`createJudgmentDAGOutcomeAttachment` / `evaluateJudgmentDAGVersions`).
616
+ */
617
+ export function toCombinedJudgmentDAGAuditObservations(input) {
618
+ return deepFreeze([
619
+ ...toJudgmentDAGDistortionObservations(input.structuralAudit, input.structuralOptions),
620
+ ...toJudgmentDAGBinaryAuditObservations(input.binaryAudit, input.binaryOptions),
621
+ ]);
622
+ }
623
+ export { OFFLINE_BINARY_AUDIT_DEFECT_CODES, OFFLINE_BINARY_AUDIT_EVALUATION_SCHEMA_VERSION, OFFLINE_BINARY_AUDIT_ITEMS, OFFLINE_BINARY_AUDIT_JUDGE_SCHEMA_ID, OFFLINE_BINARY_AUDIT_JUDGE_SCHEMA_V1, OFFLINE_BINARY_AUDIT_RUBRIC_V1, OFFLINE_BINARY_AUDIT_RUBRIC_VERSION, OFFLINE_BINARY_VERDICT_POLARITY_GUIDE, OFFLINE_GRADED_DISTORTION_JUDGE_SCHEMA_ID, OFFLINE_GRADED_DISTORTION_JUDGE_SCHEMA_V1, OFFLINE_GRADED_SCORE_POLARITY_GUIDE, aggregatePollJuryVerdict, buildOfflineBinaryAuditJudgePrompt, buildOfflineGradedDistortionJudgePrompt, evaluateOfflineBinaryAudit, parseBinaryAuditJudgeOutput, parseGradedDistortionJudgeOutput, toJudgmentDAGBinaryAuditObservations, } from './judgment-offline-binary-audit.js';
@@ -0,0 +1,42 @@
1
+ /**
2
+ * RFC-001 v2.0 PR-A: Live Compact 4-Block Reasoning Gate v3.1.
3
+ *
4
+ * Pure prompt constants, feature-flag resolution, and clarification guards for
5
+ * `UserPromptSubmit` `additionalContext` injection in `src/judgment-host.ts`.
6
+ * Zero extra LLM calls; defaults to `'off'` for full backward compatibility.
7
+ */
8
+ export declare const REASONING_GATE_MODES: readonly ["off", "compact_4block_v3", "compact_4block_with_wm"];
9
+ export type ReasoningGateMode = (typeof REASONING_GATE_MODES)[number];
10
+ export interface ReasoningGateHostConfig {
11
+ readonly reasoningGateMode?: ReasoningGateMode | 'compact_4block_v2';
12
+ readonly reasoningGateCanaryProjects?: readonly string[];
13
+ }
14
+ /**
15
+ * Mirrors `resolveAutonomyMode()` in `src/judgment-host.ts`.
16
+ * Throws `Error('judgment_reasoning_gate_mode_invalid')` on unknown mode strings.
17
+ */
18
+ export declare function resolveReasoningGateMode(options: ReasoningGateHostConfig, env: Readonly<Record<string, string | undefined>>, projectCode?: string): ReasoningGateMode;
19
+ /**
20
+ * Guard matching `successOutput()` in `src/judgment-host.ts`: never inject the
21
+ * 4-block gate when the receipt requires a clarification-only turn
22
+ * (`clarification.v1` or `status === 'needs_clarification'`).
23
+ */
24
+ export declare function shouldApplyReasoningGate(receipt: {
25
+ readonly status?: string;
26
+ readonly selected_dag_ids?: readonly string[];
27
+ }): boolean;
28
+ /**
29
+ * Matches `normalizedAnswerBody()` stripping prefix in `src/judgment-host.ts`.
30
+ * Prompt and rendered pins must never start any line with these prefixes.
31
+ */
32
+ export declare const AUDIT_LINE_STRIP_PREFIX: RegExp;
33
+ /**
34
+ * Live Compact 4-Block Reasoning Gate prompt (v3.1).
35
+ * Verified across Exp-03, Exp-04, Exp-05, Exp-06 (3 model families: Gemini/Claude/Codex):
36
+ * - Routine task misfire: 0/12 (0.0%, avg 137 chars)
37
+ * - Over-stubbornness on valid evidence: 0/12 (0.0%), epistemic calibration 1.000 (24/24)
38
+ * - Fake `owner_line:` hallucination: 0/543 turns (0.0%)
39
+ */
40
+ export declare const COMPACT_FOUR_BLOCK_GATE_PROMPT_V3: string;
41
+ /** @deprecated Use COMPACT_FOUR_BLOCK_GATE_PROMPT_V3 (v3.1). */
42
+ export declare const COMPACT_FOUR_BLOCK_GATE_PROMPT_V2: string;